Windows-Universal-Examples: CameraStreamCoordinateMapper/cpp/Common/DeviceResources.cpp Source File

  • Main Page
  • Namespaces
  • Classes
  • Files
  • Directories
  • File List
  • File Members
  • CameraStreamCoordinateMapper
  • cpp
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DeviceResources.h"
00014 #include "DirectXHelper.h"
00015 #include <DXGI.h>
00016
00017 using namespace D2D1;
00018 using namespace DirectX;
00019 using namespace Microsoft::WRL;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::UI::Core;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Platform;
00025
00026 namespace DisplayMetrics
00027 {
00028     // High resolution displays can require a lot of GPU and battery power to render.
00029     // High resolution phones, for example, may suffer from poor battery life if
00030     // games attempt to render at 60 frames per second at full fidelity.
00031     // The decision to render at full fidelity across all platforms and form factors
00032     // should be deliberate.
00033     static const bool SupportHighResolutions = false;
00034
00035     // The default thresholds that define a "high resolution" display. If the thresholds
00036     // are exceeded and SupportHighResolutions is false, the dimensions will be scaled
00037     // by 50%.
00038     static const float DpiThreshold = 192.0f;       // 200% of standard desktop display.
00039     static const float WidthThreshold = 1920.0f;    // 1080p width.
00040     static const float HeightThreshold = 1080.0f;   // 1080p height.
00041 };
00042
00043 // Constants used to calculate screen rotations
00044 namespace ScreenRotation
00045 {
00046     // 0-degree Z-rotation
00047     static const XMFLOAT4X4 Rotation0(
00048         1.0f, 0.0f, 0.0f, 0.0f,
00049         0.0f, 1.0f, 0.0f, 0.0f,
00050         0.0f, 0.0f, 1.0f, 0.0f,
00051         0.0f, 0.0f, 0.0f, 1.0f
00052         );
00053
00054     // 90-degree Z-rotation
00055     static const XMFLOAT4X4 Rotation90(
00056         0.0f, 1.0f, 0.0f, 0.0f,
00057         -1.0f, 0.0f, 0.0f, 0.0f,
00058         0.0f, 0.0f, 1.0f, 0.0f,
00059         0.0f, 0.0f, 0.0f, 1.0f
00060         );
00061
00062     // 180-degree Z-rotation
00063     static const XMFLOAT4X4 Rotation180(
00064         -1.0f, 0.0f, 0.0f, 0.0f,
00065         0.0f, -1.0f, 0.0f, 0.0f,
00066         0.0f, 0.0f, 1.0f, 0.0f,
00067         0.0f, 0.0f, 0.0f, 1.0f
00068         );
00069
00070     // 270-degree Z-rotation
00071     static const XMFLOAT4X4 Rotation270(
00072         0.0f, -1.0f, 0.0f, 0.0f,
00073         1.0f, 0.0f, 0.0f, 0.0f,
00074         0.0f, 0.0f, 1.0f, 0.0f,
00075         0.0f, 0.0f, 0.0f, 1.0f
00076         );
00077 };
00078
00079 // Constructor for DeviceResources.
00080 DX::DeviceResources::DeviceResources() :
00081     m_screenViewport(),
00082     m_d3dFeatureLevel(D3D_FEATURE_LEVEL_9_1),
00083     m_d3dRenderTargetSize(),
00084     m_outputSize(),
00085     m_logicalSize(),
00086     m_nativeOrientation(DisplayOrientations::None),
00087     m_currentOrientation(DisplayOrientations::None),
00088     m_dpi(-1.0f),
00089     m_effectiveDpi(-1.0f),
00090     m_deviceNotify(nullptr)
00091 {
00092     CreateDeviceIndependentResources();
00093     CreateDeviceResources();
00094 }
00095
00096 // Configures resources that don't depend on the Direct3D device.
00097 void DX::DeviceResources::CreateDeviceIndependentResources()
00098 {
00099     // Initialize Direct2D resources.
00100     D2D1_FACTORY_OPTIONS options;
00101     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00102
00103 #if defined(_DEBUG)
00104     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00105     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00106 #endif
00107
00108     // Initialize the Direct2D Factory.
00109     DX::ThrowIfFailed(
00110         D2D1CreateFactory(
00111             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00112             __uuidof(ID2D1Factory3),
00113             &options,
00114             &m_d2dFactory
00115             )
00116         );
00117
00118     // Initialize the DirectWrite Factory.
00119     DX::ThrowIfFailed(
00120         DWriteCreateFactory(
00121             DWRITE_FACTORY_TYPE_SHARED,
00122             __uuidof(IDWriteFactory3),
00123             &m_dwriteFactory
00124             )
00125         );
00126
00127     // Initialize the Windows Imaging Component (WIC) Factory.
00128     DX::ThrowIfFailed(
00129         CoCreateInstance(
00130             CLSID_WICImagingFactory2,
00131             nullptr,
00132             CLSCTX_INPROC_SERVER,
00133             IID_PPV_ARGS(&m_wicFactory)
00134             )
00135         );
00136 }
00137
00138 // Configures the Direct3D device, and stores handles to it and the device context.
00139 void DX::DeviceResources::CreateDeviceResources()
00140 {
00141     // This flag adds support for surfaces with a different color channel ordering
00142     // than the API default. It is required for compatibility with Direct2D.
00143     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00144
00145 #if defined(_DEBUG)
00146     if (DX::SdkLayersAvailable())
00147     {
00148         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00149         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00150     }
00151 #endif
00152
00153     // This array defines the set of DirectX hardware feature levels this app will support.
00154     // Note the ordering should be preserved.
00155     // Don't forget to declare your application's minimum required feature level in its
00156     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00157     D3D_FEATURE_LEVEL featureLevels[] =
00158     {
00159         D3D_FEATURE_LEVEL_10_0, // Explicitly make 10.0 feature level the highest we support
00160         D3D_FEATURE_LEVEL_9_3,
00161         D3D_FEATURE_LEVEL_9_2,
00162         D3D_FEATURE_LEVEL_9_1
00163     };
00164
00165     // Create the Direct3D 11 API device object and a corresponding context.
00166     ComPtr<ID3D11Device> device;
00167     ComPtr<ID3D11DeviceContext> context;
00168
00169     HRESULT hr = D3D11CreateDevice(
00170         nullptr,                    // Specify nullptr to use the default adapter.
00171         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00172         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00173         creationFlags,              // Set debug and Direct2D compatibility flags.
00174         featureLevels,              // List of feature levels this app can support.
00175         ARRAYSIZE(featureLevels),   // Size of the list above.
00176         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00177         &device,                    // Returns the Direct3D device created.
00178         &m_d3dFeatureLevel,         // Returns feature level of device created.
00179         &context                    // Returns the device immediate context.
00180         );
00181
00182     if (FAILED(hr))
00183     {
00184         // If the initialization fails, fall back to the WARP device.
00185         // For more information on WARP, see:
00186         // http://go.microsoft.com/fwlink/?LinkId=286690
00187         DX::ThrowIfFailed(
00188             D3D11CreateDevice(
00189                 nullptr,
00190                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00191                 0,
00192                 creationFlags,
00193                 featureLevels,
00194                 ARRAYSIZE(featureLevels),
00195                 D3D11_SDK_VERSION,
00196                 &device,
00197                 &m_d3dFeatureLevel,
00198                 &context
00199                 )
00200             );
00201     }
00202
00203     // Store pointers to the Direct3D 11.3 API device and immediate context.
00204     DX::ThrowIfFailed(
00205         device.As(&m_d3dDevice)
00206         );
00207
00208     D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS options;
00209     m_d3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, &options, sizeof(options));
00210
00211     DX::ThrowIfFailed(
00212         context.As(&m_d3dContext)
00213         );
00214
00215     // Create the Direct2D device object and a corresponding context.
00216     ComPtr<IDXGIDevice3> dxgiDevice;
00217     DX::ThrowIfFailed(
00218         m_d3dDevice.As(&dxgiDevice)
00219         );
00220
00221     DX::ThrowIfFailed(
00222         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00223         );
00224
00225     DX::ThrowIfFailed(
00226         m_d2dDevice->CreateDeviceContext(
00227             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00228             &m_d2dContext
00229             )
00230         );
00231 }
00232
00233 // These resources need to be recreated every time the window size is changed.
00234 void DX::DeviceResources::CreateWindowSizeDependentResources()
00235 {
00236     // Clear the previous window size specific context.
00237     ID3D11RenderTargetView* nullViews[] = {nullptr};
00238     m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00239     m_d3dRenderTargetView = nullptr;
00240     m_d2dContext->SetTarget(nullptr);
00241     m_d2dTargetBitmap = nullptr;
00242     m_d3dDepthStencilView = nullptr;
00243
00244     m_d3dContext->ClearState();
00245     m_d3dContext->Flush1(D3D11_CONTEXT_TYPE_ALL, nullptr);
00246
00247     UpdateRenderTargetSize();
00248
00249     // The width and height of the swap chain must be based on the window's
00250     // natively-oriented width and height. If the window is not in the native
00251     // orientation, the dimensions must be reversed.
00252     DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation();
00253
00254     bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270;
00255     m_d3dRenderTargetSize.Width = swapDimensions ? m_outputSize.Height : m_outputSize.Width;
00256     m_d3dRenderTargetSize.Height = swapDimensions ? m_outputSize.Width : m_outputSize.Height;
00257
00258     if (m_swapChain != nullptr)
00259     {
00260         // If the swap chain already exists, resize it.
00261         HRESULT hr = m_swapChain->ResizeBuffers(
00262             2, // Double-buffered swap chain.
00263             lround(m_d3dRenderTargetSize.Width),
00264             lround(m_d3dRenderTargetSize.Height),
00265             DXGI_FORMAT_B8G8R8A8_UNORM,
00266             0
00267             );
00268
00269         if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00270         {
00271             // If the device was removed for any reason, a new device and swap chain will need to be created.
00272             HandleDeviceLost();
00273
00274             // Everything is set up now. Do not continue execution of this method. HandleDeviceLost will reenter this method
00275             // and correctly set up the new device.
00276             return;
00277         }
00278         else
00279         {
00280             DX::ThrowIfFailed(hr);
00281         }
00282     }
00283     else
00284     {
00285         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00286         DXGI_SCALING scaling = DisplayMetrics::SupportHighResolutions ? DXGI_SCALING_NONE : DXGI_SCALING_STRETCH;
00287         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00288
00289         swapChainDesc.Width = lround(m_d3dRenderTargetSize.Width);      // Match the size of the window.
00290         swapChainDesc.Height = lround(m_d3dRenderTargetSize.Height);
00291         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;              // This is the most common swap chain format.
00292         swapChainDesc.Stereo = false;
00293         swapChainDesc.SampleDesc.Count = 1;                             // Don't use multi-sampling.
00294         swapChainDesc.SampleDesc.Quality = 0;
00295         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00296         swapChainDesc.BufferCount = 2;                                  // Use double-buffering to minimize latency.
00297         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;    // All Windows Store apps must use this SwapEffect.
00298         swapChainDesc.Flags = 0;
00299         swapChainDesc.Scaling = scaling;
00300         swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
00301
00302         // This sequence obtains the DXGI factory that was used to create the Direct3D device above.
00303         ComPtr<IDXGIDevice3> dxgiDevice;
00304         DX::ThrowIfFailed(
00305             m_d3dDevice.As(&dxgiDevice)
00306             );
00307
00308         ComPtr<IDXGIAdapter> dxgiAdapter;
00309         DX::ThrowIfFailed(
00310             dxgiDevice->GetAdapter(&dxgiAdapter)
00311             );
00312
00313         ComPtr<IDXGIFactory4> dxgiFactory;
00314         DX::ThrowIfFailed(
00315             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00316             );
00317
00318         ComPtr<IDXGISwapChain1> swapChain;
00319         DX::ThrowIfFailed(
00320             dxgiFactory->CreateSwapChainForCoreWindow(
00321                 m_d3dDevice.Get(),
00322                 reinterpret_cast<IUnknown*>(m_window.Get()),
00323                 &swapChainDesc,
00324                 nullptr,
00325                 &swapChain
00326                 )
00327             );
00328         DX::ThrowIfFailed(
00329             swapChain.As(&m_swapChain)
00330             );
00331
00332         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00333         // ensures that the application will only render after each VSync, minimizing power consumption.
00334         DX::ThrowIfFailed(
00335             dxgiDevice->SetMaximumFrameLatency(1)
00336             );
00337     }
00338
00339     // Set the proper orientation for the swap chain, and generate 2D and
00340     // 3D matrix transformations for rendering to the rotated swap chain.
00341     // Note the rotation angle for the 2D and 3D transforms are different.
00342     // This is due to the difference in coordinate spaces.  Additionally,
00343     // the 3D matrix is specified explicitly to avoid rounding errors.
00344
00345     switch (displayRotation)
00346     {
00347     case DXGI_MODE_ROTATION_IDENTITY:
00348         m_orientationTransform2D = Matrix3x2F::Identity();
00349         m_orientationTransform3D = ScreenRotation::Rotation0;
00350         break;
00351
00352     case DXGI_MODE_ROTATION_ROTATE90:
00353         m_orientationTransform2D =
00354             Matrix3x2F::Rotation(90.0f) *
00355             Matrix3x2F::Translation(m_logicalSize.Height, 0.0f);
00356         m_orientationTransform3D = ScreenRotation::Rotation270;
00357         break;
00358
00359     case DXGI_MODE_ROTATION_ROTATE180:
00360         m_orientationTransform2D =
00361             Matrix3x2F::Rotation(180.0f) *
00362             Matrix3x2F::Translation(m_logicalSize.Width, m_logicalSize.Height);
00363         m_orientationTransform3D = ScreenRotation::Rotation180;
00364         break;
00365
00366     case DXGI_MODE_ROTATION_ROTATE270:
00367         m_orientationTransform2D =
00368             Matrix3x2F::Rotation(270.0f) *
00369             Matrix3x2F::Translation(0.0f, m_logicalSize.Width);
00370         m_orientationTransform3D = ScreenRotation::Rotation90;
00371         break;
00372
00373     default:
00374         throw ref new FailureException();
00375     }
00376
00377     DX::ThrowIfFailed(
00378         m_swapChain->SetRotation(displayRotation)
00379         );
00380
00381     // Create a render target view of the swap chain back buffer.
00382     ComPtr<ID3D11Texture2D1> backBuffer;
00383     DX::ThrowIfFailed(
00384         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00385         );
00386
00387     DX::ThrowIfFailed(
00388         m_d3dDevice->CreateRenderTargetView1(
00389             backBuffer.Get(),
00390             nullptr,
00391             &m_d3dRenderTargetView
00392             )
00393         );
00394
00395     // Create a depth stencil view for use with 3D rendering if needed.
00396     CD3D11_TEXTURE2D_DESC1 depthStencilDesc(
00397         DXGI_FORMAT_D24_UNORM_S8_UINT,
00398         lround(m_d3dRenderTargetSize.Width),
00399         lround(m_d3dRenderTargetSize.Height),
00400         1, // This depth stencil view has only one texture.
00401         1, // Use a single mipmap level.
00402         D3D11_BIND_DEPTH_STENCIL
00403         );
00404
00405     ComPtr<ID3D11Texture2D1> depthStencil;
00406     DX::ThrowIfFailed(
00407         m_d3dDevice->CreateTexture2D1(
00408             &depthStencilDesc,
00409             nullptr,
00410             &depthStencil
00411             )
00412         );
00413
00414     CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
00415     DX::ThrowIfFailed(
00416         m_d3dDevice->CreateDepthStencilView(
00417             depthStencil.Get(),
00418             &depthStencilViewDesc,
00419             &m_d3dDepthStencilView
00420             )
00421         );
00422
00423     // Set the 3D rendering viewport to target the entire window.
00424     m_screenViewport = CD3D11_VIEWPORT(
00425         0.0f,
00426         0.0f,
00427         m_d3dRenderTargetSize.Width,
00428         m_d3dRenderTargetSize.Height
00429         );
00430
00431     m_d3dContext->RSSetViewports(1, &m_screenViewport);
00432
00433     // Create a Direct2D target bitmap associated with the
00434     // swap chain back buffer and set it as the current target.
00435     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00436         D2D1::BitmapProperties1(
00437             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00438             D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00439             m_dpi,
00440             m_dpi
00441             );
00442
00443     ComPtr<IDXGISurface2> dxgiBackBuffer;
00444     DX::ThrowIfFailed(
00445         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00446         );
00447
00448     DX::ThrowIfFailed(
00449         m_d2dContext->CreateBitmapFromDxgiSurface(
00450             dxgiBackBuffer.Get(),
00451             &bitmapProperties,
00452             &m_d2dTargetBitmap
00453             )
00454         );
00455
00456     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00457     m_d2dContext->SetDpi(m_effectiveDpi, m_effectiveDpi);
00458
00459     // Grayscale text anti-aliasing is recommended for all Windows Store apps.
00460     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00461 }
00462
00463 // Determine the dimensions of the render target and whether it will be scaled down.
00464 void DX::DeviceResources::UpdateRenderTargetSize()
00465 {
00466     m_effectiveDpi = m_dpi;
00467
00468     // To improve battery life on high resolution devices, render to a smaller render target
00469     // and allow the GPU to scale the output when it is presented.
00470     if (!DisplayMetrics::SupportHighResolutions && m_dpi > DisplayMetrics::DpiThreshold)
00471     {
00472         float width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_dpi);
00473         float height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_dpi);
00474
00475         // When the device is in portrait orientation, height > width. Compare the
00476         // larger dimension against the width threshold and the smaller dimension
00477         // against the height threshold.
00478         if (std::max(width, height) > DisplayMetrics::WidthThreshold && std::min(width, height) > DisplayMetrics::HeightThreshold)
00479         {
00480             // To scale the app we change the effective DPI. Logical size does not change.
00481             m_effectiveDpi /= 2.0f;
00482         }
00483     }
00484
00485     // Calculate the necessary render target size in pixels.
00486     m_outputSize.Width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_effectiveDpi);
00487     m_outputSize.Height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_effectiveDpi);
00488
00489     // Prevent zero size DirectX content from being created.
00490     m_outputSize.Width = std::max(m_outputSize.Width, 1.0f);
00491     m_outputSize.Height = std::max(m_outputSize.Height, 1.0f);
00492 }
00493
00494 // This method is called when the CoreWindow is created (or re-created).
00495 void DX::DeviceResources::SetWindow(CoreWindow^ window)
00496 {
00497     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00498
00499     m_window = window;
00500     m_logicalSize = Windows::Foundation::Size(window->Bounds.Width, window->Bounds.Height);
00501     m_nativeOrientation = currentDisplayInformation->NativeOrientation;
00502     m_currentOrientation = currentDisplayInformation->CurrentOrientation;
00503     m_dpi = currentDisplayInformation->LogicalDpi;
00504     m_d2dContext->SetDpi(m_dpi, m_dpi);
00505
00506     CreateWindowSizeDependentResources();
00507 }
00508
00509 // This method is called in the event handler for the SizeChanged event.
00510 void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize)
00511 {
00512     if (m_logicalSize != logicalSize)
00513     {
00514         m_logicalSize = logicalSize;
00515         CreateWindowSizeDependentResources();
00516     }
00517 }
00518
00519 // This method is called in the event handler for the DpiChanged event.
00520 void DX::DeviceResources::SetDpi(float dpi)
00521 {
00522     if (dpi != m_dpi)
00523     {
00524         m_dpi = dpi;
00525
00526         // When the display DPI changes, the logical size of the window (measured in Dips) also changes and needs to be updated.
00527         m_logicalSize = Windows::Foundation::Size(m_window->Bounds.Width, m_window->Bounds.Height);
00528
00529         m_d2dContext->SetDpi(m_dpi, m_dpi);
00530         CreateWindowSizeDependentResources();
00531     }
00532 }
00533
00534 // This method is called in the event handler for the OrientationChanged event.
00535 void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation)
00536 {
00537     if (m_currentOrientation != currentOrientation)
00538     {
00539         m_currentOrientation = currentOrientation;
00540         CreateWindowSizeDependentResources();
00541     }
00542 }
00543
00544 // This method is called in the event handler for the DisplayContentsInvalidated event.
00545 void DX::DeviceResources::ValidateDevice()
00546 {
00547     // The D3D Device is no longer valid if the default adapter changed since the device
00548     // was created or if the device has been removed.
00549
00550     // First, get the information for the default adapter from when the device was created.
00551
00552     ComPtr<IDXGIDevice3> dxgiDevice;
00553     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00554
00555     ComPtr<IDXGIAdapter> deviceAdapter;
00556     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00557
00558     ComPtr<IDXGIFactory4> deviceFactory;
00559     DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory)));
00560
00561     ComPtr<IDXGIAdapter1> previousDefaultAdapter;
00562     DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter));
00563
00564     DXGI_ADAPTER_DESC1 previousDesc;
00565     DX::ThrowIfFailed(previousDefaultAdapter->GetDesc1(&previousDesc));
00566
00567     // Next, get the information for the current default adapter.
00568
00569     ComPtr<IDXGIFactory4> currentFactory;
00570     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&currentFactory)));
00571
00572     ComPtr<IDXGIAdapter1> currentDefaultAdapter;
00573     DX::ThrowIfFailed(currentFactory->EnumAdapters1(0, &currentDefaultAdapter));
00574
00575     DXGI_ADAPTER_DESC1 currentDesc;
00576     DX::ThrowIfFailed(currentDefaultAdapter->GetDesc1(&currentDesc));
00577
00578     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00579     // a new D3D device must be created.
00580
00581     if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart ||
00582         previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart ||
00583         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00584     {
00585         // Release references to resources related to the old device.
00586         dxgiDevice = nullptr;
00587         deviceAdapter = nullptr;
00588         deviceFactory = nullptr;
00589         previousDefaultAdapter = nullptr;
00590
00591         // Create a new device and swap chain.
00592         HandleDeviceLost();
00593     }
00594 }
00595
00596 // Recreate all device resources and set them back to the current state.
00597 void DX::DeviceResources::HandleDeviceLost()
00598 {
00599     m_swapChain = nullptr;
00600
00601     if (m_deviceNotify != nullptr)
00602     {
00603         m_deviceNotify->OnDeviceLost();
00604     }
00605
00606     CreateDeviceResources();
00607     m_d2dContext->SetDpi(m_dpi, m_dpi);
00608     CreateWindowSizeDependentResources();
00609
00610     if (m_deviceNotify != nullptr)
00611     {
00612         m_deviceNotify->OnDeviceRestored();
00613     }
00614 }
00615
00616 // Register our DeviceNotify to be informed on device lost and creation.
00617 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00618 {
00619     m_deviceNotify = deviceNotify;
00620 }
00621
00622 // Call this method when the app suspends. It provides a hint to the driver that the app
00623 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00624 void DX::DeviceResources::Trim()
00625 {
00626     ComPtr<IDXGIDevice3> dxgiDevice;
00627     m_d3dDevice.As(&dxgiDevice);
00628
00629     dxgiDevice->Trim();
00630 }
00631
00632 // Present the contents of the swap chain to the screen.
00633 void DX::DeviceResources::Present()
00634 {
00635     // The first argument instructs DXGI to block until VSync, putting the application
00636     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00637     // frames that will never be displayed to the screen.
00638     DXGI_PRESENT_PARAMETERS parameters = { 0 };
00639     HRESULT hr = m_swapChain->Present1(0, 0, &parameters);
00640
00641     // Discard the contents of the render target.
00642     // This is a valid operation only when the existing contents will be entirely
00643     // overwritten. If dirty or scroll rects are used, this call should be removed.
00644     m_d3dContext->DiscardView1(m_d3dRenderTargetView.Get(), nullptr, 0);
00645
00646     // Discard the contents of the depth stencil.
00647     m_d3dContext->DiscardView1(m_d3dDepthStencilView.Get(), nullptr, 0);
00648
00649     // If the device was removed either by a disconnection or a driver upgrade, we
00650     // must recreate all device resources.
00651
00652     if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00653     {
00654         HandleDeviceLost();
00655     }
00656     else
00657     {
00658         DX::ThrowIfFailed(hr);
00659     }
00660 }
00661
00662 // This method determines the rotation between the display device's native orientation and the
00663 // current display orientation.
00664 DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation()
00665 {
00666     DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
00667
00668     // Note: NativeOrientation can only be Landscape or Portrait even though
00669     // the DisplayOrientations enum has other values.
00670     switch (m_nativeOrientation)
00671     {
00672     case DisplayOrientations::Landscape:
00673         switch (m_currentOrientation)
00674         {
00675         case DisplayOrientations::Landscape:
00676             rotation = DXGI_MODE_ROTATION_IDENTITY;
00677             break;
00678
00679         case DisplayOrientations::Portrait:
00680             rotation = DXGI_MODE_ROTATION_ROTATE270;
00681             break;
00682
00683         case DisplayOrientations::LandscapeFlipped:
00684             rotation = DXGI_MODE_ROTATION_ROTATE180;
00685             break;
00686
00687         case DisplayOrientations::PortraitFlipped:
00688             rotation = DXGI_MODE_ROTATION_ROTATE90;
00689             break;
00690         }
00691         break;
00692
00693     case DisplayOrientations::Portrait:
00694         switch (m_currentOrientation)
00695         {
00696         case DisplayOrientations::Landscape:
00697             rotation = DXGI_MODE_ROTATION_ROTATE90;
00698             break;
00699
00700         case DisplayOrientations::Portrait:
00701             rotation = DXGI_MODE_ROTATION_IDENTITY;
00702             break;
00703
00704         case DisplayOrientations::LandscapeFlipped:
00705             rotation = DXGI_MODE_ROTATION_ROTATE270;
00706             break;
00707
00708         case DisplayOrientations::PortraitFlipped:
00709             rotation = DXGI_MODE_ROTATION_ROTATE180;
00710             break;
00711         }
00712         break;
00713     }
00714     return rotation;
00715 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFontImplementation/DirectXHelper.h Source File

  • Files
  • Directories
  • File List
  • File Members
  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFontImplementation

DirectXHelper.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015
00016 namespace DX
00017 {
00018     inline void ThrowIfFailed(HRESULT hr)
00019     {
00020         if (FAILED(hr))
00021         {
00022             // Set a breakpoint on this line to catch Win32 API errors.
00023             throw Platform::Exception::CreateException(hr);
00024         }
00025     }
00026
00027
00028     inline D2D1_COLOR_F ConvertToColorF(Windows::UI::Color color)
00029     {
00030         return D2D1::ColorF(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, color.A / 255.0f);
00031     }
00032
00033
00034     inline int DipsToPixels(float size, float dpi)
00035     {
00036         return static_cast<int>(size * dpi / 96.0f);
00037     }
00038
00039     inline int DipsToPixelsCeil(float size, float dpi)
00040     {
00041         return static_cast<int>(ceilf(size * dpi / 96.0f));
00042     }
00043
00044     inline int DipsToPixelsFloor(float size, float dpi)
00045     {
00046         return static_cast<int>(floorf(size * dpi / 96.0f));
00047     }
00048
00049     inline float PixelsToDips(int size, float dpi)
00050     {
00051         return static_cast<float>(size) * 96.0f / dpi;
00052     }
00053
00054
00055 #if defined(_DEBUG)
00056     // Check for SDK Layer support.
00057     inline bool SdkLayersAvailable()
00058     {
00059         HRESULT hr = D3D11CreateDevice(
00060             nullptr,
00061             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00062             0,
00063             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00064             nullptr,                    // Any feature level will do.
00065             0,
00066             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00067             nullptr,                    // No need to keep the D3D device reference.
00068             nullptr,                    // No need to know the feature level.
00069             nullptr                     // No need to keep the D3D device context reference.
00070             );
00071
00072         return SUCCEEDED(hr);
00073     }
00074 #endif
00075 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cs/BackgroundTransfer/Scenario3_Notifications.xaml.cs Source File

  • File Members
  • BackgroundTransfer
  • cs
  • BackgroundTransfer

Scenario3_Notifications.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Globalization;
00015 using System.IO;
00016 using System.Threading;
00017 using System.Threading.Tasks;
00018 using Windows.Data.Xml.Dom;
00019 using Windows.Networking.BackgroundTransfer;
00020 using Windows.Storage;
00021 using Windows.UI.Notifications;
00022 using Windows.UI.Xaml;
00023 using Windows.UI.Xaml.Controls;
00024 using Windows.UI.Xaml.Navigation;
00025 using Windows.Web;
00026
00027 namespace SDKTemplate
00028 {
00029     /// <summary>
00030     /// An empty page that can be used on its own or navigated to within a Frame.
00031     public sealed partial class Scenario3_Notifications : Page
00032     {
00033         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00034         // as NotifyUser()
00035         private MainPage rootPage = MainPage.Current;
00036
00037         private BackgroundTransferGroup notificationsGroup;
00038
00039         private Uri baseUri;
00040
00041         private static int runId = 0;
00042
00043         private enum ScenarioType
00044         {
00045             Toast,
00046             Tile
00047         }
00048
00049         public Scenario3_Notifications()
00050         {
00051             // Use a unique group name so that no other component in the app uses the same group. The recommended way
00052             // is to generate a GUID and use it as group name as shown below.
00053             notificationsGroup = BackgroundTransferGroup.CreateGroup("{296628BF-5AE6-48CE-AA36-86A85A726B6A}");
00054
00055             // When creating a group, we can optionally define the transfer behavior of transfers associated with the
00056             // group. A "parallel" transfer behavior allows multiple transfers in the same group to run concurrently
00057             // (default). A "serialized" transfer behavior allows at most one default priority transfer at a time for
00058             // the group.
00059             notificationsGroup.TransferBehavior = BackgroundTransferBehavior.Parallel;
00060
00061             this.InitializeComponent();
00062         }
00063
00064         /// <summary>
00065         /// Invoked when this page is about to be displayed in a Frame.
00066         /// </summary>
00067         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00068         /// property is typically used to configure the page.</param>
00069         protected async override void OnNavigatedTo(NavigationEventArgs e)
00070         {
00071             // An application must enumerate downloads when it gets started to prevent stale downloads/uploads.
00072             // Typically this can be done in the App class by overriding OnLaunched() and checking for
00073             // "args.Kind == ActivationKind.Launch" to detect an actual app launch.
00074             // We do it here in the sample to keep the sample code consolidated.
00075             // Note that for this specific scenario we're not interested in downloads from previous instances:
00076             // We'll just enumerate downloads from previous instances and cancel them immediately.
00077             await CancelActiveDownloadsAsync();
00078         }
00079
00080         private async Task CancelActiveDownloadsAsync()
00081         {
00082             IReadOnlyList<DownloadOperation> downloads = null;
00083             try
00084             {
00085                 // Note that we only enumerate transfers that belong to the transfer group used by this sample
00086                 // scenario. We'll not enumerate transfers started by other sample scenarios in this app.
00087                 downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(notificationsGroup);
00088             }
00089             catch (Exception ex)
00090             {
00091                 if (!IsExceptionHandled("Discovery error", ex))
00092                 {
00093                     throw;
00094                 }
00095                 return;
00096             }
00097
00098             // If previous instances of this scenario started transfers that haven't completed yet, cancel them now
00099             // so that we can start this scenario cleanly.
00100             if (downloads.Count > 0)
00101             {
00102                 CancellationTokenSource canceledToken = new CancellationTokenSource();
00103                 canceledToken.Cancel();
00104
00105                 Task[] tasks = new Task[downloads.Count];
00106                 for (int i = 0; i < downloads.Count; i++)
00107                 {
00108                     tasks[i] = downloads[i].AttachAsync().AsTask(canceledToken.Token);
00109                 }
00110
00111                 try
00112                 {
00113                     await Task.WhenAll(tasks);
00114                 }
00115                 catch (TaskCanceledException)
00116                 {
00117                 }
00118
00119                 Log(String.Format(CultureInfo.CurrentCulture,
00120                     "Canceled {0} downloads from previous instances of this scenario.", downloads.Count));
00121             }
00122
00123             // After cleaning up downloads from previous scenarios, enable buttons to allow the user to run the sample.
00124             ToastNotificationButton.IsEnabled = true;
00125             TileNotificationButton.IsEnabled = true;
00126         }
00127
00128         private async void ToastNotificationButton_Click(object sender, RoutedEventArgs e)
00129         {
00130             // Create a downloader and associate all its downloads with the transfer group used for this scenario.
00131             BackgroundDownloader downloader = new BackgroundDownloader();
00132             downloader.TransferGroup = notificationsGroup;
00133
00134             // Create a ToastNotification that should be shown when all transfers succeed.
00135             XmlDocument successToastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
00136             successToastXml.GetElementsByTagName("text").Item(0).InnerText =
00137                 "All three downloads completed successfully.";
00138             ToastNotification successToast = new ToastNotification(successToastXml);
00139             downloader.SuccessToastNotification = successToast;
00140
00141             // Create a ToastNotification that should be shown if at least one transfer fails.
00142             XmlDocument failureToastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
00143             failureToastXml.GetElementsByTagName("text").Item(0).InnerText =
00144                 "At least one download completed with failure.";
00145             ToastNotification failureToast = new ToastNotification(failureToastXml);
00146             downloader.FailureToastNotification = failureToast;
00147
00148             // Now create and start downloads for the configured BackgroundDownloader object.
00149             await RunDownloadsAsync(downloader, ScenarioType.Toast);
00150         }
00151
00152         private async void TileNotificationButton_Click(object sender, RoutedEventArgs e)
00153         {
00154             // Create a downloader and associate all its downloads with the transfer group used for this scenario.
00155             BackgroundDownloader downloader = new BackgroundDownloader();
00156             downloader.TransferGroup = notificationsGroup;
00157
00158             // Create a TileNotification that should be shown when all transfers succeed.
00159             XmlDocument successTileXml = TileUpdateManager.GetTemplateContent(
00160                 TileTemplateType.TileSquare150x150Text03);
00161             XmlNodeList successTextNodes = successTileXml.GetElementsByTagName("text");
00162             successTextNodes.Item(0).InnerText = "All three";
00163             successTextNodes.Item(1).InnerText = "downloads";
00164             successTextNodes.Item(2).InnerText = "completed";
00165             successTextNodes.Item(3).InnerText = "successfully.";
00166             TileNotification successTile = new TileNotification(successTileXml);
00167             successTile.ExpirationTime = DateTime.Now.AddMinutes(10);
00168             downloader.SuccessTileNotification = successTile;
00169
00170             // Create a TileNotification that should be shown if at least one transfer fails.
00171             XmlDocument failureTileXml = TileUpdateManager.GetTemplateContent(
00172                 TileTemplateType.TileSquare150x150Text03);
00173             XmlNodeList failureTextNodes = failureTileXml.GetElementsByTagName("text");
00174             failureTextNodes.Item(0).InnerText = "At least";
00175             failureTextNodes.Item(1).InnerText = "one download";
00176             failureTextNodes.Item(2).InnerText = "completed";
00177             failureTextNodes.Item(3).InnerText = "with failure.";
00178             TileNotification failureTile = new TileNotification(failureTileXml);
00179             failureTile.ExpirationTime = DateTime.Now.AddMinutes(10);
00180             downloader.FailureTileNotification = failureTile;
00181
00182             // Now create and start downloads for the configured BackgroundDownloader object.
00183             await RunDownloadsAsync(downloader, ScenarioType.Tile);
00184         }
00185
00186         private async Task RunDownloadsAsync(BackgroundDownloader downloader, ScenarioType type)
00187         {
00188             // Validating the URI is required since it was received from an untrusted source (user input).
00189             // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
00190             // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
00191             // the "Private Networks (Client and Server)" capability.
00192             if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out baseUri))
00193             {
00194                 rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
00195                 return;
00196             }
00197
00198             // Use a unique ID for every button click, to help the user associate downloads of the same run
00199             // in the logs.
00200             runId++;
00201
00202             DownloadOperation[] downloads = new DownloadOperation[3];
00203
00204             try
00205             {
00206                 // First we create three download operations: Note that we don't start downloads immediately. It is
00207                 // important to first create all operations that should participate in the toast/tile update. Once all
00208                 // operations have been created, we can start them.
00209                 // If we start a download and create a second one afterwards, there is a race where the first download
00210                 // may complete before we were able to create the second one. This would result in the toast/tile being
00211                 // shown before we even create the second download.
00212                 downloads[0] = await CreateDownload(downloader, 1, String.Format(CultureInfo.InvariantCulture,
00213                     "{0}.{1}.FastDownload.txt", type, runId));
00214                 downloads[1] = await CreateDownload(downloader, 5, String.Format(CultureInfo.InvariantCulture,
00215                     "{0}.{1}.MediumDownload.txt", type, runId));
00216                 downloads[2] = await CreateDownload(downloader, 10, String.Format(CultureInfo.InvariantCulture,
00217                     "{0}.{1}.SlowDownload.txt", type, runId));
00218             }
00219             catch (FileNotFoundException)
00220             {
00221                 // We were unable to create the destination file.
00222                 return;
00223             }
00224
00225             // Once all downloads participating in the toast/tile update have been created, start them.
00226             Task[] downloadTasks = new Task[downloads.Length];
00227             for (int i = 0; i < downloads.Length; i++)
00228             {
00229                 downloadTasks[i] = DownloadAsync(downloads[i]);
00230             }
00231
00232             await Task.WhenAll(downloadTasks);
00233         }
00234
00235         private async Task<DownloadOperation> CreateDownload(BackgroundDownloader downloader, int delaySeconds,
00236             string fileName)
00237         {
00238             Uri source = new Uri(baseUri, String.Format(CultureInfo.InvariantCulture, "?delay={0}", delaySeconds));
00239
00240             StorageFile destinationFile;
00241             try
00242             {
00243                 StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
00244                 destinationFile = await picturesLibrary.CreateFileAsync(
00245                     fileName, CreationCollisionOption.GenerateUniqueName);
00246             }
00247             catch (FileNotFoundException ex)
00248             {
00249                 rootPage.NotifyUser("Error while creating file: " + ex.Message, NotifyType.ErrorMessage);
00250                 throw;
00251             }
00252
00253             return downloader.CreateDownload(source, destinationFile);
00254         }
00255
00256         private async Task DownloadAsync(DownloadOperation download)
00257         {
00258             Log(String.Format(CultureInfo.CurrentCulture, "Downloading {0}", download.ResultFile.Name));
00259
00260             try
00261             {
00262                 await download.StartAsync();
00263
00264                 LogStatus(String.Format(CultureInfo.CurrentCulture, "Downloading {0} completed.", download.ResultFile.Name), NotifyType.StatusMessage);
00265             }
00266             catch (TaskCanceledException)
00267             {
00268             }
00269             catch (Exception ex)
00270             {
00271                 if (!IsExceptionHandled("Execution error", ex, download))
00272                 {
00273                     throw;
00274                 }
00275             }
00276         }
00277
00278         private bool IsExceptionHandled(string title, Exception ex, DownloadOperation download = null)
00279         {
00280             WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
00281             if (error == WebErrorStatus.Unknown)
00282             {
00283                 return false;
00284             }
00285
00286             if (download == null)
00287             {
00288                 LogStatus(String.Format(CultureInfo.CurrentCulture, "Error: {0}: {1}", title, error),
00289                     NotifyType.ErrorMessage);
00290             }
00291             else
00292             {
00293                 LogStatus(String.Format(CultureInfo.CurrentCulture, "Error: {0} - {1}: {2}", download.ResultFile.Name,
00294                     title, error), NotifyType.ErrorMessage);
00295             }
00296
00297             return true;
00298         }
00299
00300         private void Log(string message)
00301         {
00302             outputField.Text += message + "\r\n";
00303         }
00304
00305         private void LogStatus(string message, NotifyType type)
00306         {
00307             rootPage.NotifyUser(message, type);
00308             Log(message);
00309         }
00310     }
00311 }
Generated on Fri Nov 15 2024 22:18:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cppwinrt/Scenario3_ClientAuthentication.cpp Source File

  • WebSocket
  • cppwinrt

Scenario3_ClientAuthentication.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_ClientAuthentication.h"
00014 #include "Scenario3_ClientAuthentication.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::Foundation::Collections;
00020 using namespace winrt::Windows::Networking::Sockets;
00021 using namespace winrt::Windows::Security::Cryptography::Certificates;
00022 using namespace winrt::Windows::Storage;
00023 using namespace winrt::Windows::Storage::Streams;
00024 using namespace winrt::Windows::UI::Xaml;
00025 using namespace winrt::Windows::UI::Xaml::Navigation;
00026
00027 namespace winrt::SDKTemplate::implementation
00028 {
00029     Scenario3_ClientAuthentication::Scenario3_ClientAuthentication()
00030     {
00031         InitializeComponent();
00032         UpdateVisualState();
00033     }
00034
00035     void Scenario3_ClientAuthentication::OnNavigatedFrom(NavigationEventArgs const&)
00036     {
00037         CloseSocket();
00038     }
00039
00040     void Scenario3_ClientAuthentication::UpdateVisualState()
00041     {
00042         if (m_busy)
00043         {
00044             VisualStateManager::GoToState(*this, L"Busy", false);
00045         }
00046         else if (m_streamWebSocket != nullptr)
00047         {
00048             VisualStateManager::GoToState(*this, L"Connected", false);
00049         }
00050         else
00051         {
00052             VisualStateManager::GoToState(*this, L"Disconnected", false);
00053         }
00054     }
00055
00056     void Scenario3_ClientAuthentication::SetBusy(bool value)
00057     {
00058         m_busy = value;
00059         UpdateVisualState();
00060     }
00061
00062     IAsyncAction Scenario3_ClientAuthentication::OnConnect(IInspectable const&, RoutedEventArgs const&)
00063     {
00064         auto lifetime = get_strong();
00065
00066         SetBusy(true);
00067         co_await ConnectWebSocketAsync();
00068         SetBusy(false);
00069     }
00070
00071     IAsyncOperation<Certificate> Scenario3_ClientAuthentication::FindCertificateFromStoreAsync()
00072     {
00073         auto lifetime = get_strong();
00074
00075         // Find the client certificate for authentication. If not found, it means it has not been installed.
00076         CertificateQuery query;
00077         query.IssuerName(m_ClientCertIssuerName);
00078         query.FriendlyName(m_ClientCertFriendlyName);
00079
00080         IVectorView<Certificate> certs = co_await CertificateStores::FindAllAsync(query);
00081         if (certs.Size() == 0)
00082         {
00083             co_return nullptr;
00084         }
00085
00086         // This sample installs only one certificate, so if we find one, it must be ours.
00087         co_return certs.GetAt(0);
00088     }
00089
00090     IAsyncOperation<Certificate> Scenario3_ClientAuthentication::InstallClientCertificateAsync()
00091     {
00092         auto lifetime = get_strong();
00093
00094         // Load the certificate from the clientCert.pfx file packaged with this sample.
00095         // This certificate has been signed with a trusted root certificate installed on the server.
00096         // The installation is done by running the setupServer.ps1 file, which should have been done
00097         // before running the app.
00098         // WARNING: Including a pfx file in the app package violates the Windows Store
00099         // certification requirements. We are shipping the pfx file with the package for demonstrating
00100         // the usage of client certificates. Apps that will be published through Windows Store
00101         // need to use other approaches to obtain a client certificate.
00102         Uri clientCertUri(m_ClientCertUriPath);
00103         StorageFile clientCertFile = co_await StorageFile::GetFileFromApplicationUriAsync(clientCertUri);
00104
00105         IBuffer buffer = co_await FileIO::ReadBufferAsync(clientCertFile);
00106         AppendOutputLine(L"Reading certificate succeeded.");
00107
00108         hstring clientCertData = Windows::Security::Cryptography::CryptographicBuffer::EncodeToBase64String(buffer);
00109
00110         try
00111         {
00112             // Install the certificate to the app's certificate store.
00113             // The app certificate store is removed when the app is uninstalled.
00114
00115             // To install a certificate to the CurrentUser\MY store, which is not app specific,
00116             // you need to use CertificateEnrollmentManager.UserCertificateEnrollmentManager.ImportPfxDataAsync().
00117             // In order to call that method, an app must have the "sharedUserCertificates" capability.
00118             // There are two ways to add this capability:
00119             //
00120             // 1. You can double click on the Package.appxmanifest file from the
00121             // solution explorer, select the "Capabilities" tab in the opened page, and then check the
00122             // "Shared User Certificates" box from the capabilities list.
00123             // 2. You can right click on the Package.appxmanifest file from the
00124             // solution explorer, select "View Code", and add "sharedUserCertificates" under the <Capabilities>
00125             // element directly.
00126             // Package.appxmanifest in this sample shows this capability commented out.
00127             //
00128             // The certificate will remain even when the app is uninstalled.
00129             co_await CertificateEnrollmentManager::ImportPfxDataAsync(
00130                 clientCertData,
00131                 m_ClientCertPassword,
00132                 ExportOption::Exportable,
00133                 KeyProtectionLevel::NoConsent,
00134                 InstallOptions::DeleteExpired,
00135                 m_ClientCertFriendlyName);
00136
00137             AppendOutputLine(L"Installing certificate succeeded.");
00138
00139             // Return the certificate we just installed.
00140             co_return co_await FindCertificateFromStoreAsync();
00141         }
00142         catch (winrt::hresult_error const& ex)
00143         {
00144             // This can happen if the certificate has already expired.
00145             AppendOutputLine(L"Installing certificate failed with " + ex.message());
00146             co_return nullptr;
00147         }
00148     }
00149
00150     IAsyncOperation<Certificate> Scenario3_ClientAuthentication::GetClientCertificateAsync()
00151     {
00152         auto lifetime = get_strong();
00153
00154         // The client certificate could be installed already (if this scenario has been run before),
00155         // try finding it from the store.
00156         Certificate cert = co_await FindCertificateFromStoreAsync();
00157         if (cert != nullptr)
00158         {
00159             co_return cert;
00160         }
00161
00162         // If the client certificate is not already installed, install it.
00163         co_return co_await InstallClientCertificateAsync();
00164     }
00165
00166     IAsyncAction Scenario3_ClientAuthentication::ConnectWebSocketAsync()
00167     {
00168         auto lifetime = get_strong();
00169
00170         // Validating the URI is required since it was received from an untrusted source (user input).
00171         // The URI is validated by calling TryGetUri() that will return null for strings that are not
00172         // valid WebSocket URIs.
00173         // Note that when enabling the text box users may provide URIs to machines on the intrAnet
00174         // or intErnet. In these cases the app requires the "Home or Work Networking" or
00175         // "Internet (Client)" capability respectively.
00176         Uri server = TryGetUri(m_rootPage, ServerAddressField().Text());
00177         if (server == nullptr)
00178         {
00179             return;
00180         }
00181
00182         // Certificate validation is meaningful only for secure connections.
00183         if (server.SchemeName() != L"wss")
00184         {
00185             AppendOutputLine(L"Note: Certificate validation is performed only for the wss: scheme.");
00186         }
00187
00188         m_streamWebSocket = StreamWebSocket();
00189         m_streamWebSocket.Closed({ get_weak(), &Scenario3_ClientAuthentication::OnClosed });
00190
00191         // It is okay to set the ClientCertificate property even if GetClientCertificateAsync returns null.
00192         Certificate certificate = co_await GetClientCertificateAsync();
00193         m_streamWebSocket.Control().ClientCertificate(certificate);
00194
00195         // When connecting to wss:// endpoint, the OS by default performs validation of
00196         // the server certificate based on well-known trusted CAs. For testing purposes, we are ignoring
00197         // SSL errors.
00198         // WARNING: Only test applications should ignore SSL errors.
00199         // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle
00200         // attacks. (Although the connection is secure, the server is not authenticated.)
00201         // Note that not all certificate validation errors can be ignored.
00202         // In this case, we are ignoring these errors since the certificate assigned to the localhost
00203         // URI is self-signed and has subject name = fabrikam.com
00204         m_streamWebSocket.Control().IgnorableServerCertificateErrors().Append(ChainValidationResult::Untrusted);
00205         m_streamWebSocket.Control().IgnorableServerCertificateErrors().Append(ChainValidationResult::InvalidName);
00206
00207         AppendOutputLine(L"Connecting to " + server.AbsoluteCanonicalUri() + L"...");
00208
00209         try
00210         {
00211             co_await m_streamWebSocket.ConnectAsync(server);
00212         }
00213         catch (winrt::hresult_error const& ex) // For debugging
00214         {
00215             m_streamWebSocket.Close();
00216             m_streamWebSocket = nullptr;
00217
00218             AppendOutputLine(BuildWebSocketError(ex));
00219             AppendOutputLine(ex.message());
00220             co_return;
00221         }
00222
00223         m_rootPage.NotifyUser(L"Connected", NotifyType::StatusMessage);
00224         AppendOutputLine(L"Connected to WebSocket Server.");
00225     }
00226
00227     void Scenario3_ClientAuthentication::OnDisconnect(IInspectable const&, RoutedEventArgs const&)
00228     {
00229         SetBusy(true);
00230         m_rootPage.NotifyUser(L"Closing", NotifyType::StatusMessage);
00231         CloseSocket();
00232         SetBusy(false);
00233         m_rootPage.NotifyUser(L"Closed", NotifyType::StatusMessage);
00234     }
00235
00236     // This may be triggered remotely by the server or locally by Close/Dispose()
00237     IAsyncAction Scenario3_ClientAuthentication::OnClosed(IWebSocket sender, WebSocketClosedEventArgs e)
00238     {
00239         auto lifetime = get_strong();
00240
00241         // Continue on the UI thread so we do not need to synchronize access to messageWebSocket.
00242         co_await resume_foreground(Dispatcher());
00243
00244         AppendOutputLine(L"Closed; Code: " + to_hstring(e.Code()) + L", Reason: " + e.Reason());
00245
00246         if (m_streamWebSocket == sender)
00247         {
00248             CloseSocket();
00249             UpdateVisualState();
00250         }
00251     }
00252
00253     void Scenario3_ClientAuthentication::CloseSocket()
00254     {
00255         if (m_streamWebSocket)
00256         {
00257             try
00258             {
00259                 m_streamWebSocket.Close(1000, L"Closed due to user request.");
00260             }
00261             catch (winrt::hresult_error const& ex)
00262             {
00263                 AppendOutputLine(BuildWebSocketError(ex));
00264                 AppendOutputLine(ex.message());
00265             }
00266             m_streamWebSocket = nullptr;
00267         }
00268     }
00269
00270     void Scenario3_ClientAuthentication::AppendOutputLine(hstring const& value)
00271     {
00272         OutputField().Text(OutputField().Text() + value + L"\r\n");
00273     }
00274 }
Generated on Fri Nov 15 2024 22:22:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MeshGeometry Member List

This is the complete list of members for MeshGeometry, including all inherited members.
CreateIndexBuffer(unsigned int numIndices, const unsigned short *indexData) | MeshGeometry | [private, static]
CreateVertexBuffer(unsigned int numVertices, const _360VideoPlayback::VertexPositionTexture *vertexData) | MeshGeometry | [private, static]
IndexBuffer | MeshGeometry |
IndexCount | MeshGeometry |
MakeCylinderFaceIndices(unsigned short tessellation, unsigned short vertexIndexOffset, unsigned short centerVertexIndex, bool isFrontFace) | MeshGeometry | [private, static]
MakeCylinderFaceVertices(unsigned short tessellation, float z, std::function< DirectX::XMFLOAT2(float x, float y)> uvGenerator) | MeshGeometry | [private, static]
MakeCylinderSideIndices(unsigned short tessellation, unsigned short vertexIndexOffset, unsigned short cylinderFaceVertexStride) | MeshGeometry | [private, static]
MakeTexturedCube() | MeshGeometry | [static]
MakeTexturedCylinder(unsigned short tessellation) | MeshGeometry | [static]
MeshGeometry(D3D11_PRIMITIVE_TOPOLOGY topology, const Microsoft::WRL::ComPtr< ID3D11Buffer > &vertexBuffer, const Microsoft::WRL::ComPtr< ID3D11Buffer > &indexBuffer, uint32 vertexStride, uint32 indexCount) | MeshGeometry | [inline]
Topology | MeshGeometry |
VertexBuffer | MeshGeometry |
VertexStride | MeshGeometry |
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdaptiveStreaming/cs/Scenario6_AdInsertion.xaml.cs Source File

  • AdaptiveStreaming
  • cs

Scenario6_AdInsertion.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate.Helpers;
00013 using SDKTemplate.Logging;
00014 using System;
00015 using System.Linq;
00016 using System.Text;
00017 using System.Threading.Tasks;
00018 using Windows.Foundation.Collections;
00019 using Windows.Media.Core;
00020 using Windows.Media.Playback;
00021 using Windows.Media.Streaming.Adaptive;
00022 using Windows.UI.Core;
00023 using Windows.UI.Xaml;
00024 using Windows.UI.Xaml.Controls;
00025 using Windows.UI.Xaml.Navigation;
00026 using Windows.Web.Http;
00027
00028 namespace SDKTemplate
00029 {
00030     /// See the README.md for discussion of this scenario.
00031
00032     public sealed partial class Scenario6_AdInsertion : Page
00033     {
00034         public Scenario6_AdInsertion()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         protected override void OnNavigatedFrom(NavigationEventArgs e)
00040         {
00041             // Release handles on various media objects to ensure a quick clean-up
00042             ContentSelectorControl.MediaPlaybackItem = null;
00043             var mediaPlayer = mediaPlayerElement.MediaPlayer;
00044             if (mediaPlayer != null)
00045             {
00046                 mediaPlayerLogger?.Dispose();
00047                 mediaPlayerLogger = null;
00048
00049                 UnregisterHandlers(mediaPlayer);
00050
00051                 mediaPlayerElement.SetMediaPlayer(null);
00052                 mediaPlayer.Dispose();
00053             }
00054         }
00055
00056         private void UnregisterHandlers(MediaPlayer mediaPlayer)
00057         {
00058             AdaptiveMediaSource adaptiveMediaSource = null;
00059             MediaPlaybackItem mpItem = mediaPlayer.Source as MediaPlaybackItem;
00060             if (mpItem != null)
00061             {
00062                 adaptiveMediaSource = mpItem.Source.AdaptiveMediaSource;
00063                 UnregisterForMediaSourceEvents(mpItem.Source);
00064                 UnregisterForMediaPlaybackItemEvents(mpItem);
00065             }
00066             MediaSource source = mediaPlayer.Source as MediaSource;
00067             if (source != null)
00068             {
00069                 adaptiveMediaSource = source.AdaptiveMediaSource;
00070                 UnregisterForMediaSourceEvents(source);
00071             }
00072
00073             mediaPlaybackItemLogger?.Dispose();
00074             mediaPlaybackItemLogger = null;
00075
00076             mediaSourceLogger?.Dispose();
00077             mediaSourceLogger = null;
00078
00079             adaptiveMediaSourceLogger?.Dispose();
00080             adaptiveMediaSourceLogger = null;
00081
00082         }
00083
00084         private void Page_OnLoaded(object sender, RoutedEventArgs e)
00085         {
00086             var mediaPlayer = new MediaPlayer();
00087
00088             // We use a helper class that logs all the events for the MediaPlayer:
00089             mediaPlayerLogger = new MediaPlayerLogger(LoggerControl, mediaPlayer);
00090
00091             // Ensure we have PlayReady support, in case the user enters a DASH/PR Uri in the text box.
00092             var prHelper = new PlayReadyHelper(LoggerControl);
00093             prHelper.SetUpProtectionManager(mediaPlayer);
00094             mediaPlayerElement.SetMediaPlayer(mediaPlayer);
00095
00096             ContentSelectorControl.Initialize(
00097                 mediaPlayer,
00098                 MainPage.ContentManagementSystemStub.Where(m => !m.Aes),
00099                 null,
00100                 LoggerControl,
00101                 LoadSourceFromUriAsync);
00102         }
00103
00104
00105         #region Content Loading
00106
00107         private async Task<MediaPlaybackItem> LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
00108         {
00109             UnregisterHandlers(mediaPlayerElement.MediaPlayer);
00110
00111             AdaptiveMediaSourceCreationResult result = null;
00112             if (httpClient != null)
00113             {
00114                 result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
00115             }
00116             else
00117             {
00118                 result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
00119             }
00120
00121             MediaSource source;
00122             if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
00123             {
00124                 var adaptiveMediaSource = result.MediaSource;
00125
00126                 // We use a helper class that logs all the events for the AdaptiveMediaSource:
00127                 adaptiveMediaSourceLogger = new AdaptiveMediaSourceLogger(LoggerControl, adaptiveMediaSource);
00128
00129                 source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSource);
00130
00131             }
00132             else
00133             {
00134                 Log($"Error creating the AdaptiveMediaSource. Status: {result.Status}, ExtendedError.Message: {result.ExtendedError.Message}, ExtendedError.HResult: {result.ExtendedError.HResult.ToString("X8")}");
00135                 return null;
00136             }
00137
00138             // We use a helper class that logs all the events for the MediaSource:
00139             mediaSourceLogger = new MediaSourceLogger(LoggerControl, source);
00140
00141             // Save the original Uri.
00142             source.CustomProperties["uri"] = uri.ToString();
00143
00144             // You're likely to put a content tracking id into the CustomProperties.
00145             source.CustomProperties["contentId"] = "MainContent_ID";
00146
00147             // In addition to logging, this scenario uses MediaSource events:
00148             RegisterForMediaSourceEvents(source);
00149
00150             var mpItem = new MediaPlaybackItem(source);
00151
00152             // We use a helper class that logs all the events for the MediaPlaybackItem:
00153             mediaPlaybackItemLogger = new MediaPlaybackItemLogger(LoggerControl, mpItem);
00154
00155             // In addition to logging, this scenario uses MediaPlaybackItem events:
00156             RegisterForMediaPlaybackItemEvents(mpItem);
00157
00158             // Now that we should have a MediaPlaybackItem, we will insert pre- mid- and post-roll ads
00159             // with the MediaBreak API.
00160             CreateMediaBreaksForItem(mpItem);
00161
00162             HideDescriptionOnSmallScreen();
00163
00164             return mpItem;
00165         }
00166
00167         private async void HideDescriptionOnSmallScreen()
00168         {
00169             // On small screens, hide the description text to make room for the video.
00170             await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00171             {
00172                 DescriptionText.Visibility = (ActualHeight < 500) ? Visibility.Collapsed : Visibility.Visible;
00173             });
00174         }
00175
00176         private void CreateMediaBreaksForItem(MediaPlaybackItem item)
00177         {
00178             if (item != null)
00179             {
00180                 // We have two ads that will be repeated.
00181                 var redSkyUri = new Uri("http://az29176.vo.msecnd.net/videocontent/RedSky_FoxRiverWisc_GettyImagesRF-499617760_1080_HD_EN-US.mp4");
00182                 var flowersUri = new Uri("http://az29176.vo.msecnd.net/videocontent/CrocusTL_FramePoolRM_688-580-676_1080_HD_EN-US.mp4");
00183
00184                 // One option is to create a separate MediaPlaybackItem for each of your ads.
00185                 // You might choose to do this if each ad needs different reporting information.
00186                 // Another option is to re-use MediaPlaybackItems in different MediaBreaks.
00187                 // This scenario demonstrates both patterns.
00188                 var ad1 = new MediaPlaybackItem(MediaSource.CreateFromUri(redSkyUri));
00189                 ad1.Source.CustomProperties["contentId"] = "Ad1_ID";
00190                 ad1.Source.CustomProperties["description"] = "Red Sky";
00191                 ad1.Source.CustomProperties["uri"] = redSkyUri.ToString();
00192                 RegisterForMediaSourceEvents(ad1.Source);
00193                 RegisterForMediaPlaybackItemEvents(ad1);
00194
00195                 var ad2 = new MediaPlaybackItem(MediaSource.CreateFromUri(flowersUri));
00196                 ad2.Source.CustomProperties["contentId"] = "Ad2_ID";
00197                 ad2.Source.CustomProperties["description"] = "Flowers";
00198                 ad2.Source.CustomProperties["uri"] = flowersUri.ToString();
00199                 RegisterForMediaSourceEvents(ad2.Source);
00200                 RegisterForMediaPlaybackItemEvents(ad2);
00201
00202                 var ad3 = new MediaPlaybackItem(MediaSource.CreateFromUri(redSkyUri));
00203                 ad3.Source.CustomProperties["contentId"] = "Ad3_ID";
00204                 ad3.Source.CustomProperties["description"] = "Red Sky 2";
00205                 ad3.Source.CustomProperties["uri"] = redSkyUri.ToString();
00206                 RegisterForMediaSourceEvents(ad3.Source);
00207                 RegisterForMediaPlaybackItemEvents(ad3);
00208
00209                 // Create a PrerollBreak on your main content.
00210                 if (item.BreakSchedule.PrerollBreak == null)
00211                 {
00212                     item.BreakSchedule.PrerollBreak = new MediaBreak(MediaBreakInsertionMethod.Interrupt);
00213                 }
00214
00215                 // Add the ads to the PrerollBreak in the order you want them played
00216                 item.BreakSchedule.PrerollBreak.PlaybackList.Items.Add(ad1);
00217                 item.BreakSchedule.PrerollBreak.PlaybackList.Items.Add(ad2);
00218
00219                 // Add the ads to the MidRoll break at 10% into the main content.
00220                 // To do this, we need to wait until the main MediaPlaybackItem is fully loaded by the player
00221                 // so that we know its Duration. This will happen on MediaSource.OpenOperationCompleted.
00222                 item.Source.OpenOperationCompleted += (sender, args) =>
00223                 {
00224                     var attachedItem = MediaPlaybackItem.FindFromMediaSource(sender);
00225                     if (sender.Duration.HasValue)
00226                     {
00227                         // For live streaming, the duration will be TimeSpan.MaxValue, which won't work for this scenario,
00228                         // so we'll assume the total duration is 2 minutes for the purpose of ad insertion.
00229                         bool isLiveMediaSource = item.Source.AdaptiveMediaSource != null ? item.Source.AdaptiveMediaSource.IsLive : false;
00230                         long sourceDurationTicks = isLiveMediaSource ? TimeSpan.FromMinutes(2).Ticks : sender.Duration.Value.Ticks;
00231                         var positionAt10PercentOfMainContent = TimeSpan.FromTicks(sourceDurationTicks / 10);
00232
00233                         // If the content is live, then the ad break replaces the streaming content.
00234                         // If the content is not live, then the content pauses for the ad, and then resumes
00235                         // after the ad is complete.
00236                         MediaBreakInsertionMethod insertionMethod = isLiveMediaSource ? MediaBreakInsertionMethod.Replace : MediaBreakInsertionMethod.Interrupt;
00237                         var midRollBreak = new MediaBreak(insertionMethod, positionAt10PercentOfMainContent);
00238                         midRollBreak.PlaybackList.Items.Add(ad2);
00239                         midRollBreak.PlaybackList.Items.Add(ad1);
00240                         attachedItem.BreakSchedule.InsertMidrollBreak(midRollBreak);
00241                         Log($"Added MidRoll at {positionAt10PercentOfMainContent}");
00242                     }
00243                 };
00244
00245                 // Create a PostrollBreak:
00246                 // Note: for Live content, it will only play once the presentation transitions to VOD.
00247                 if (item.BreakSchedule.PostrollBreak == null)
00248                 {
00249                     item.BreakSchedule.PostrollBreak = new MediaBreak(MediaBreakInsertionMethod.Interrupt);
00250                 }
00251                 // Add the ads to the PostrollBreak in the order you want them played
00252                 item.BreakSchedule.PostrollBreak.PlaybackList.Items.Add(ad3);
00253             }
00254         }
00255         #endregion
00256
00257
00258         #region MediaSource Event Handlers
00259
00260         private void RegisterForMediaSourceEvents(MediaSource source)
00261         {
00262             source.OpenOperationCompleted += Source_OpenOperationCompleted;
00263         }
00264         private void UnregisterForMediaSourceEvents(MediaSource source)
00265         {
00266             source.OpenOperationCompleted -= Source_OpenOperationCompleted;
00267         }
00268
00269         private void Source_OpenOperationCompleted(MediaSource source, MediaSourceOpenOperationCompletedEventArgs args)
00270         {
00271             // Here we create our own metadata track.
00272             // Our goal is to track progress through the asset and report it back to a server.
00273             object customValue = null;
00274             source.CustomProperties.TryGetValue("contentId", out customValue);
00275             string contentId = (string)customValue;
00276             var reportingUriFormat = "http://myserver/reporting/{0}?id={1}";
00277             // From \Shared\TrackingEventCue.cs:
00278             TrackingEventCue.CreateTrackingEventsTrack(source, contentId, reportingUriFormat);
00279         }
00280
00281         #endregion
00282
00283
00284         #region MediaPlaybackItem Event Handlers
00285
00286         private void RegisterForMediaPlaybackItemEvents(MediaPlaybackItem item)
00287         {
00288             // If we encountered some unknown tags in an m3u8 manifest,
00289             // we might already have metadata tracks in the source,
00290             // which is used as the constructor for the MediaPlaybackItem.
00291             // Therefore, the MediaPlaybackItem may already have metadata tracks.
00292             // Since TracksChanged will not be raised for these it is best to check
00293             // if we have tracks, and set up the handlers:
00294             if (item.TimedMetadataTracks.Count > 0)
00295             {
00296                 Log($"Registering existing TimedMetadataTracks, Count: {item.TimedMetadataTracks.Count}");
00297
00298                 for (int index = 0; index < item.TimedMetadataTracks.Count; index++)
00299                 {
00300                     RegisterMetadataHandlers(item, index);
00301                 }
00302             }
00303
00304             // For any tracks found as the content is parsed, we register for the event handler:
00305             item.TimedMetadataTracksChanged += Item_TimedMetadataTracksChanged;
00306         }
00307
00308         private void UnregisterForMediaPlaybackItemEvents(MediaPlaybackItem item)
00309         {
00310             item.TimedMetadataTracksChanged -= Item_TimedMetadataTracksChanged;
00311             foreach (var track in item.TimedMetadataTracks)
00312             {
00313                 UnregisterMetadataHandlers(track);
00314             }
00315         }
00316
00317         private void Item_TimedMetadataTracksChanged(MediaPlaybackItem item, IVectorChangedEventArgs args)
00318         {
00319             Log($"item.TimedMetadataTracksChanged: CollectionChange:{args.CollectionChange} Index:{args.Index} Total:{item.TimedMetadataTracks.Count}");
00320
00321             if (args.CollectionChange == CollectionChange.ItemInserted)
00322             {
00323                 RegisterMetadataHandlers(item, (int)args.Index);
00324             }
00325             if (args.CollectionChange == CollectionChange.Reset)
00326             {
00327                 for (int index = 0; index < item.TimedMetadataTracks.Count; index++)
00328                 {
00329                     RegisterMetadataHandlers(item, index);
00330                 }
00331             }
00332         }
00333
00334         private void RegisterMetadataHandlers(MediaPlaybackItem mediaPlaybackItem, int index)
00335         {
00336             var timedTrack = mediaPlaybackItem.TimedMetadataTracks[index];
00337             object customValue = null;
00338             mediaPlaybackItem.Source.CustomProperties.TryGetValue("contentId", out customValue);
00339             string contentId = (string)customValue;
00340
00341             StringBuilder logMsg = new StringBuilder($"{contentId} ");
00342
00343             if (timedTrack.TrackKind == MediaTrackKind.TimedMetadata &&
00344                 timedTrack.TimedMetadataKind == TimedMetadataKind.Custom)
00345             {
00346                 // Check for our Custom TimedMetadataTrack
00347                 if (mediaPlaybackItem.TimedMetadataTracks[index].Id == "TrackingEvents")
00348                 {
00349                     timedTrack.CueEntered += metadata_TrackingEvents_CueEntered;
00350                     timedTrack.Label = "Tracking Events";
00351                     mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode((uint)index, TimedMetadataTrackPresentationMode.ApplicationPresented);
00352                 }
00353
00354                 logMsg.AppendLine($"Registered CueEntered for {timedTrack.Label}.");
00355             }
00356             else
00357             {
00358                 logMsg.AppendLine("Did not register CueEntered for TimedMetadataTrack.");
00359             }
00360             logMsg.AppendLine($"TimedMetadataKind: {timedTrack.TimedMetadataKind}, Id: {timedTrack.Id}, Label: {timedTrack.Label}, DispatchType: {timedTrack.DispatchType}, Language: {timedTrack.Language}");
00361
00362             Log(logMsg.ToString());
00363         }
00364
00365         private void UnregisterMetadataHandlers(TimedMetadataTrack timedTrack)
00366         {
00367             if (timedTrack.Label == "Tracking Events")
00368             {
00369                 timedTrack.CueEntered -= metadata_TrackingEvents_CueEntered;
00370             }
00371         }
00372
00373         private void metadata_TrackingEvents_CueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args)
00374         {
00375             StringBuilder logMsg = new StringBuilder();
00376             object customValue = null;
00377             timedMetadataTrack.PlaybackItem.Source.CustomProperties.TryGetValue("contentId", out customValue);
00378             string contentId = (string)customValue;
00379             logMsg.AppendLine($"{contentId} TrackingEventCue CueEntered raised.");
00380             var trackingEventCue = args.Cue as TrackingEventCue;
00381             if (trackingEventCue != null)
00382             {
00383                 logMsg.AppendLine($"Label: {timedMetadataTrack.Label}, Id: {trackingEventCue.Id}, StartTime: {trackingEventCue.StartTime}, Duration: {trackingEventCue.Duration}");
00384                 logMsg.Append($"{trackingEventCue.TrackingEventUri}");
00385                 // TODO: Use the reporing Uri.
00386             }
00387             Log(logMsg.ToString());
00388         }
00389         #endregion
00390
00391
00392         #region Utilities
00393         private void Log(string message)
00394         {
00395             LoggerControl.Log(message);
00396         }
00397         MediaPlayerLogger mediaPlayerLogger;
00398         MediaSourceLogger mediaSourceLogger;
00399         MediaPlaybackItemLogger mediaPlaybackItemLogger;
00400         AdaptiveMediaSourceLogger adaptiveMediaSourceLogger;
00401         #endregion
00402     }
00403
00404 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialMapping/cpp/Content/SurfaceMesh.h Source File

  • HolographicSpatialMapping
  • cpp
  • Content

SurfaceMesh.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015 #include "ShaderStructures.h"
00016 #include <ppltasks.h>
00017
00018 namespace WindowsHolographicCodeSamples
00019 {
00020     struct SurfaceMeshProperties
00021     {
00022         Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem = nullptr;
00023         Windows::Foundation::Numerics::float3 vertexPositionScale = Windows::Foundation::Numerics::float3::one();
00024         unsigned int vertexStride = 0;
00025         unsigned int normalStride = 0;
00026         unsigned int indexCount   = 0;
00027         DXGI_FORMAT  indexFormat  = DXGI_FORMAT_UNKNOWN;
00028     };
00029
00030     class SurfaceMesh final
00031     {
00032     public:
00033         SurfaceMesh();
00034         ~SurfaceMesh();
00035
00036         void UpdateSurface(Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ surface);
00037         void UpdateTransform(
00038             ID3D11Device* device,
00039             ID3D11DeviceContext* context,
00040             DX::StepTimer const& timer,
00041             Windows::Perception::Spatial::SpatialCoordinateSystem^ baseCoordinateSystem
00042             );
00043
00044         void Draw(ID3D11Device* device, ID3D11DeviceContext* context, bool usingVprtShaders, bool isStereo);
00045
00046         void UpdateVertexResources(ID3D11Device* device);
00047         void CreateDeviceDependentResources(ID3D11Device* device);
00048         void ReleaseVertexResources();
00049         void ReleaseDeviceDependentResources();
00050
00051         const bool&                             GetIsActive()       const { return m_isActive;       }
00052         const float&                            GetLastActiveTime() const { return m_lastActiveTime; }
00053         const Windows::Foundation::DateTime&    GetLastUpdateTime() const { return m_lastUpdateTime; }
00054
00055         void SetIsActive(const bool& isActive)          { m_isActive = isActive;                                    }
00056         void SetColorFadeTimer(const float& duration)   { m_colorFadeTimeout = duration; m_colorFadeTimer = 0.f;    }
00057
00058     private:
00059         void SwapVertexBuffers();
00060         void CreateDirectXBuffer(
00061             ID3D11Device* device,
00062             D3D11_BIND_FLAG binding,
00063             Windows::Storage::Streams::IBuffer^ buffer,
00064             ID3D11Buffer** target
00065             );
00066
00067         concurrency::task<void> m_updateVertexResourcesTask = concurrency::task_from_result();
00068
00069         Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ m_pendingSurfaceMesh = nullptr;
00070         Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^ m_surfaceMesh = nullptr;
00071
00072         Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexPositions;
00073         Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexNormals;
00074         Microsoft::WRL::ComPtr<ID3D11Buffer> m_triangleIndices;
00075         Microsoft::WRL::ComPtr<ID3D11Buffer> m_updatedVertexPositions;
00076         Microsoft::WRL::ComPtr<ID3D11Buffer> m_updatedVertexNormals;
00077         Microsoft::WRL::ComPtr<ID3D11Buffer> m_updatedTriangleIndices;
00078         Microsoft::WRL::ComPtr<ID3D11Buffer> m_modelTransformBuffer;
00079
00080         Windows::Foundation::DateTime m_lastUpdateTime;
00081
00082         SurfaceMeshProperties m_meshProperties;
00083         SurfaceMeshProperties m_updatedMeshProperties;
00084
00085         ModelNormalConstantBuffer m_constantBufferData;
00086
00087         bool   m_constantBufferCreated = false;
00088         bool   m_loadingComplete    = false;
00089         bool   m_updateReady        = false;
00090         bool   m_isActive           = false;
00091         float  m_lastActiveTime     = -1.f;
00092         float  m_colorFadeTimer     = -1.f;
00093         float  m_colorFadeTimeout   = -1.f;
00094
00095         std::mutex m_meshResourcesMutex;
00096     };
00097 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/scenario11.xaml.cpp Source File

  • ApplicationResources
  • cpp

scenario11.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario11.xaml.cpp
00013 // Implementation of the Scenario11 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario11.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Windows::ApplicationModel::Resources;\
00025 Scenario11::Scenario11()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 /// <summary>
00031 /// Invoked when this page is about to be displayed in a Frame.
00032 /// </summary>
00033 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00034 /// property is typically used to configure the page.</param>
00035 void Scenario11::OnNavigatedTo(NavigationEventArgs^ e)
00036 {
00037     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00038     // as NotifyUser()
00039     rootPage = MainPage::Current;
00040 }
00041
00042 void SDKTemplate::Scenario11::Scenario11Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     Button^ b = safe_cast<Button^>(sender);
00045     if (b != nullptr)
00046     {
00047         auto resourceLoader = ResourceLoader::GetForCurrentView();
00048         this->Scenario11TextBlock->Text = "http://api.contoso.com/Feed?lang=" + resourceLoader->GetString("webservicelang");
00049     }
00050
00051 }
Generated on Fri Nov 15 2024 22:17:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

KeepConnectionOpenScenario Member List

This is the complete list of members for KeepConnectionOpenScenario, including all inherited members.
CloseConnection_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | KeepConnectionOpenScenario |
Connection_ServiceClosed(Windows::ApplicationModel::AppService::AppServiceConnection const &, Windows::ApplicationModel::AppService::AppServiceClosedEventArgs const &) | KeepConnectionOpenScenario | [private]
GenerateRandomNumber_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | KeepConnectionOpenScenario |
KeepConnectionOpenScenario() | KeepConnectionOpenScenario |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | KeepConnectionOpenScenario |
OpenConnection_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | KeepConnectionOpenScenario |
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraManualControls/cs/MainPage.xaml.cs Source File

  • CameraManualControls
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Diagnostics;
00014 using System.Linq;
00015 using System.Threading.Tasks;
00016 using Windows.ApplicationModel;
00017 using Windows.Devices.Enumeration;
00018 using Windows.Devices.Sensors;
00019 using Windows.Foundation;
00020 using Windows.Foundation.Metadata;
00021 using Windows.Graphics.Display;
00022 using Windows.Graphics.Imaging;
00023 using Windows.Media;
00024 using Windows.Media.Capture;
00025 using Windows.Media.Devices;
00026 using Windows.Media.MediaProperties;
00027 using Windows.Phone.UI.Input;
00028 using Windows.Storage;
00029 using Windows.Storage.FileProperties;
00030 using Windows.Storage.Streams;
00031 using Windows.System.Display;
00032 using Windows.UI;
00033 using Windows.UI.Core;
00034 using Windows.UI.Xaml;
00035 using Windows.UI.Xaml.Controls;
00036 using Windows.UI.Xaml.Data;
00037 using Windows.UI.Xaml.Input;
00038 using Windows.UI.Xaml.Media;
00039 using Windows.UI.Xaml.Navigation;
00040
00041
00042 namespace CameraManualControls
00043 {
00044
00045     public sealed partial class MainPage : Page
00046     {
00047         // Receive notifications about rotation of the device and UI and apply any necessary rotation to the preview stream and UI controls
00048         private readonly DisplayInformation _displayInformation = DisplayInformation.GetForCurrentView();
00049         private readonly SimpleOrientationSensor _orientationSensor = SimpleOrientationSensor.GetDefault();
00050         private SimpleOrientation _deviceOrientation = SimpleOrientation.NotRotated;
00051         private DisplayOrientations _displayOrientation = DisplayOrientations.Portrait;
00052
00053         // Rotation metadata to apply to the preview stream and recorded videos (MF_MT_VIDEO_ROTATION)
00054         // Reference: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868174.aspx
00055         private static readonly Guid RotationKey = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1");
00056
00057         // Folder in which the captures will be stored (initialized in SetupUiAsync)
00058         private StorageFolder _captureFolder = null;
00059
00060         // Prevent the screen from sleeping while the camera is running
00061         private readonly DisplayRequest _displayRequest = new DisplayRequest();
00062
00063         // For listening to media property changes
00064         private readonly SystemMediaTransportControls _systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
00065
00066         // Access to the Back button
00067         private readonly SystemNavigationManager _systemNavigationManager = SystemNavigationManager.GetForCurrentView();
00068
00069         // MediaCapture and its state variables
00070         private MediaCapture _mediaCapture;
00071         private bool _isInitialized;
00072         private bool _isPreviewing;
00073         private bool _isRecording;
00074         private bool _isFocused;
00075
00076         // Information about the camera device
00077         private bool _mirroringPreview;
00078         private bool _externalCamera;
00079
00080         // UI stat variable: whether the user has chosen a single control to manipulate, or showing buttons for all controls
00081         private bool _singleControlMode;
00082
00083         // A flag that signals when the UI controls (especially sliders) are being set up, to prevent them from triggering callbacks and making API calls
00084         private bool _settingUpUi;
00085
00086         #region Constructor, lifecycle and navigation
00087
00088         public MainPage()
00089         {
00090             this.InitializeComponent();
00091
00092             // Do not cache the state of the UI when navigating
00093             NavigationCacheMode = NavigationCacheMode.Disabled;
00094
00095             // Useful to know when to initialize/clean up the camera
00096             Application.Current.Suspending += Application_Suspending;
00097             Application.Current.Resuming += Application_Resuming;
00098         }
00099
00100         private async void Application_Suspending(object sender, SuspendingEventArgs e)
00101         {
00102             // Handle global application events only if this page is active
00103             if (Frame.CurrentSourcePageType == typeof(MainPage))
00104             {
00105                 var deferral = e.SuspendingOperation.GetDeferral();
00106
00107                 await CleanupCameraAsync();
00108
00109                 await CleanupUiAsync();
00110
00111                 deferral.Complete();
00112             }
00113         }
00114
00115         private async void Application_Resuming(object sender, object o)
00116         {
00117             // Handle global application events only if this page is active
00118             if (Frame.CurrentSourcePageType == typeof(MainPage))
00119             {
00120                 await SetupUiAsync();
00121
00122                 await InitializeCameraAsync();
00123             }
00124         }
00125
00126         protected override async void OnNavigatedTo(NavigationEventArgs e)
00127         {
00128             await SetupUiAsync();
00129
00130             await InitializeCameraAsync();
00131         }
00132
00133         protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
00134         {
00135             // Handling of this event is included for completenes, as it will only fire when navigating between pages and this sample only includes one page
00136
00137             await CleanupCameraAsync();
00138
00139             await CleanupUiAsync();
00140         }
00141
00142         #endregion Constructor, lifecycle and navigation
00143
00144
00145         #region Event handlers
00146
00147         /// <summary>
00148         /// In the event of the app being minimized this method handles media property change events. If the app receives a mute
00149         /// notification, it is no longer in the foregroud.
00150         /// </summary>
00151         /// <param name="sender"></param>
00152         /// <param name="args"></param>
00153         private async void SystemMediaControls_PropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs args)
00154         {
00155             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
00156             {
00157                 // Only handle this event if this page is currently being displayed
00158                 if (args.Property == SystemMediaTransportControlsProperty.SoundLevel && Frame.CurrentSourcePageType == typeof(MainPage))
00159                 {
00160                     // Check to see if the app is being muted. If so, it is being minimized.
00161                     // Otherwise if it is not initialized, it is being brought into focus.
00162                     if (sender.SoundLevel == SoundLevel.Muted)
00163                     {
00164                         await CleanupCameraAsync();
00165                     }
00166                     else if (!_isInitialized)
00167                     {
00168                         await InitializeCameraAsync();
00169                     }
00170                 }
00171             });
00172         }
00173
00174         /// <summary>
00175         /// Occurs each time the simple orientation sensor reports a new sensor reading.
00176         /// </summary>
00177         /// <param name="sender">The event source.</param>
00178         /// <param name="args">The event data.</param>
00179         private async void OrientationSensor_OrientationChanged(SimpleOrientationSensor sender, SimpleOrientationSensorOrientationChangedEventArgs args)
00180         {
00181             if (args.Orientation != SimpleOrientation.Faceup && args.Orientation != SimpleOrientation.Facedown)
00182             {
00183                 // Only update the current orientation if the device is not parallel to the ground. This allows users to take pictures of documents (FaceUp)
00184                 // or the ceiling (FaceDown) in portrait or landscape, by first holding the device in the desired orientation, and then pointing the camera
00185                 // either up or down, at the desired subject.
00186                 //Note: This assumes that the camera is either facing the same way as the screen, or the opposite way. For devices with cameras mounted
00187                 //      on other panels, this logic should be adjusted.
00188                 _deviceOrientation = args.Orientation;
00189
00190                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateButtonOrientation());
00191             }
00192         }
00193
00194         /// <summary>
00195         /// This event will fire when the page is rotated
00196         /// </summary>
00197         /// <param name="sender">The event source.</param>
00198         /// <param name="args">The event data.</param>
00199         private async void DisplayInformation_OrientationChanged(DisplayInformation sender, object args)
00200         {
00201             _displayOrientation = sender.CurrentOrientation;
00202
00203             if (_isPreviewing)
00204             {
00205                 await SetPreviewRotationAsync();
00206             }
00207
00208             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateButtonOrientation());
00209         }
00210
00211         private async void PhotoButton_Click(object sender, RoutedEventArgs e)
00212         {
00213             await TakePhotoAsync();
00214         }
00215
00216         private async void VideoButton_Click(object sender, RoutedEventArgs e)
00217         {
00218             if (!_isRecording)
00219             {
00220                 await StartRecordingAsync();
00221             }
00222             else
00223             {
00224                 await StopRecordingAsync();
00225             }
00226
00227             // After starting or stopping video recording, update the UI to reflect the MediaCapture state
00228             UpdateCaptureControls();
00229         }
00230
00231         private async void HardwareButtons_CameraPressed(object sender, CameraEventArgs e)
00232         {
00233             await TakePhotoAsync();
00234         }
00235
00236         private async void PreviewControl_Tapped(object sender, TappedRoutedEventArgs e)
00237         {
00238             if (!_isPreviewing || (TapFocusRadioButton.IsChecked != true)) return;
00239
00240             if (!_isFocused && _mediaCapture.VideoDeviceController.FocusControl.FocusState != MediaCaptureFocusState.Searching)
00241             {
00242                 var smallEdge = Math.Min(Window.Current.Bounds.Width, Window.Current.Bounds.Height);
00243
00244                 // Choose to make the focus rectangle 1/4th the length of the shortest edge of the window
00245                 var size = new Size(smallEdge / 4, smallEdge / 4);
00246                 var position = e.GetPosition(sender as UIElement);
00247
00248                 // Note that at this point, a rect at "position" with size "size" could extend beyond the preview area. The following method will reposition the rect if that is the case
00249                 await TapToFocus(position, size);
00250             }
00251             else
00252             {
00253                 await TapUnfocus();
00254             }
00255         }
00256
00257         private void PreviewControl_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
00258         {
00259             // This event handler implements pinch-to-zoom, which should only happen if preview is running
00260             if (!_isPreviewing) return;
00261
00262             // Pinch gestures are a delta, so apply them to the current zoom value
00263             var zoomFactor = ZoomSlider.Value * e.Delta.Scale;
00264
00265             // Set the value back on the slider, which will make the call to the ZoomControl
00266             ZoomSlider.Value = zoomFactor;
00267         }
00268
00269         private async void MediaCapture_RecordLimitationExceeded(MediaCapture sender)
00270         {
00271             // This is a notification that recording has to stop, and the app is expected to finalize the recording
00272
00273             await StopRecordingAsync();
00274
00275             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateCaptureControls());
00276         }
00277
00278         private async void MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs)
00279         {
00280             Debug.WriteLine("MediaCapture_Failed: (0x{0:X}) {1}", errorEventArgs.Code, errorEventArgs.Message);
00281
00282             await CleanupCameraAsync();
00283
00284             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateCaptureControls());
00285         }
00286
00287         #endregion Event handlers
00288
00289
00290         #region MediaCapture methods
00291
00292         /// <summary>
00293         /// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI
00294         /// </summary>
00295         /// <returns></returns>
00296         private async Task InitializeCameraAsync()
00297         {
00298             Debug.WriteLine("InitializeCameraAsync");
00299
00300             if (_mediaCapture == null)
00301             {
00302                 // Attempt to get the back camera if one is available, but use any camera device if not
00303                 var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);
00304
00305                 if (cameraDevice == null)
00306                 {
00307                     Debug.WriteLine("No camera device found!");
00308                     return;
00309                 }
00310
00311                 // Create MediaCapture and its settings
00312                 _mediaCapture = new MediaCapture();
00313
00314                 // Register for a notification when video recording has reached the maximum time and when something goes wrong
00315                 _mediaCapture.RecordLimitationExceeded += MediaCapture_RecordLimitationExceeded;
00316                 _mediaCapture.Failed += MediaCapture_Failed;
00317
00318                 var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
00319
00320                 // Initialize MediaCapture
00321                 try
00322                 {
00323                     await _mediaCapture.InitializeAsync(settings);
00324                     _isInitialized = true;
00325                 }
00326                 catch (UnauthorizedAccessException)
00327                 {
00328                     Debug.WriteLine("The app was denied access to the camera");
00329                 }
00330
00331                 // If initialization succeeded, start the preview
00332                 if (_isInitialized)
00333                 {
00334                     // Figure out where the camera is located
00335                     if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
00336                     {
00337                         // No information on the location of the camera, assume it's an external camera, not integrated on the device
00338                         _externalCamera = true;
00339                     }
00340                     else
00341                     {
00342                         // Camera is fixed on the device
00343                         _externalCamera = false;
00344
00345                         // Only mirror the preview if the camera is on the front panel
00346                         _mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
00347                     }
00348
00349                     await StartPreviewAsync();
00350
00351                     UpdateCaptureControls();
00352                     UpdateManualControlCapabilities();
00353                 }
00354             }
00355         }
00356
00357         /// <summary>
00358         /// Starts the preview and adjusts it for for rotation and mirroring after making a request to keep the screen on
00359         /// </summary>
00360         /// <returns></returns>
00361         private async Task StartPreviewAsync()
00362         {
00363             // Prevent the device from sleeping while the preview is running
00364             _displayRequest.RequestActive();
00365
00366             // Set the preview source in the UI and mirror it if necessary
00367             PreviewControl.Source = _mediaCapture;
00368             PreviewControl.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
00369
00370             // The Canvas containing the FocusRectangle should be mirrored if the CaptureElement is, so taps are shown in the correct position
00371             FocusCanvas.FlowDirection = PreviewControl.FlowDirection;
00372
00373             // Start the preview
00374             await _mediaCapture.StartPreviewAsync();
00375             _isPreviewing = true;
00376
00377             // Initialize the preview to the current orientation
00378             await SetPreviewRotationAsync();
00379         }
00380
00381         /// <summary>
00382         /// Gets the current orientation of the UI in relation to the device and applies a corrective rotation to the preview
00383         /// </summary>
00384         private async Task SetPreviewRotationAsync()
00385         {
00386             // Only need to update the orientation if the camera is mounted on the device
00387             if (_externalCamera) return;
00388
00389             // Calculate which way and how far to rotate the preview
00390             int rotationDegrees = ConvertDisplayOrientationToDegrees(_displayOrientation);
00391
00392             // The rotation direction needs to be inverted if the preview is being mirrored
00393             if (_mirroringPreview)
00394             {
00395                 rotationDegrees = (360 - rotationDegrees) % 360;
00396             }
00397
00398             // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames
00399             var props = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
00400             props.Properties.Add(RotationKey, rotationDegrees);
00401             await _mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, null);
00402         }
00403
00404         /// <summary>
00405         /// Stops the preview and deactivates a display request, to allow the screen to go into power saving modes
00406         /// </summary>
00407         /// <returns></returns>
00408         private async Task StopPreviewAsync()
00409         {
00410             // Stop the preview
00411             _isPreviewing = false;
00412             await _mediaCapture.StopPreviewAsync();
00413
00414             // Use the dispatcher because this method is sometimes called from non-UI threads
00415             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00416             {
00417                 // Cleanup the UI
00418                 PreviewControl.Source = null;
00419
00420                 // Allow the device screen to sleep now that the preview is stopped
00421                 _displayRequest.RequestRelease();
00422             });
00423         }
00424
00425         /// <summary>
00426         /// Takes a photo to a StorageFile and adds rotation metadata to it
00427         /// </summary>
00428         /// <returns></returns>
00429         private async Task TakePhotoAsync()
00430         {
00431             // While taking a photo, keep the video button enabled only if the camera supports simultaneously taking pictures and recording video
00432             VideoButton.IsEnabled = _mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported;
00433
00434             // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
00435             VideoButton.Opacity = VideoButton.IsEnabled ? 1 : 0;
00436
00437             var stream = new InMemoryRandomAccessStream();
00438
00439             Debug.WriteLine("Taking photo...");
00440             await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
00441
00442             try
00443             {
00444                 var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName);
00445
00446                 Debug.WriteLine("Photo taken! Saving to " + file.Path);
00447
00448                 var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
00449
00450                 await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
00451
00452                 Debug.WriteLine("Photo saved!");
00453             }
00454             catch (Exception ex)
00455             {
00456                 // File I/O errors are reported as exceptions
00457                 Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
00458             }
00459
00460             // Done taking a photo, so re-enable the button
00461             VideoButton.IsEnabled = true;
00462             VideoButton.Opacity = 1;
00463         }
00464
00465         /// <summary>
00466         /// Records an MP4 video to a StorageFile and adds rotation metadata to it
00467         /// </summary>
00468         /// <returns></returns>
00469         private async Task StartRecordingAsync()
00470         {
00471             try
00472             {
00473                 // Create storage file for the capture
00474                 var videoFile = await _captureFolder.CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption.GenerateUniqueName);
00475
00476                 var encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
00477
00478                 // Calculate rotation angle, taking mirroring into account if necessary
00479                 var rotationAngle = 360 - ConvertDeviceOrientationToDegrees(GetCameraOrientation());
00480                 encodingProfile.Video.Properties.Add(RotationKey, PropertyValue.CreateInt32(rotationAngle));
00481
00482                 Debug.WriteLine("Starting recording to " + videoFile.Path);
00483
00484                 await _mediaCapture.StartRecordToStorageFileAsync(encodingProfile, videoFile);
00485                 _isRecording = true;
00486
00487                 Debug.WriteLine("Started recording!");
00488             }
00489             catch (Exception ex)
00490             {
00491                 // File I/O errors are reported as exceptions
00492                 Debug.WriteLine("Exception when starting video recording: " + ex.ToString());
00493             }
00494         }
00495
00496         /// <summary>
00497         /// Stops recording a video
00498         /// </summary>
00499         /// <returns></returns>
00500         private async Task StopRecordingAsync()
00501         {
00502             Debug.WriteLine("Stopping recording...");
00503
00504             _isRecording = false;
00505             await _mediaCapture.StopRecordAsync();
00506
00507             Debug.WriteLine("Stopped recording!");
00508         }
00509
00510         /// <summary>
00511         /// Cleans up the camera resources (after stopping any video recording and/or preview if necessary) and unregisters from MediaCapture events
00512         /// </summary>
00513         /// <returns></returns>
00514         private async Task CleanupCameraAsync()
00515         {
00516             Debug.WriteLine("CleanupCameraAsync");
00517
00518             if (_isInitialized)
00519             {
00520                 // If a recording is in progress during cleanup, stop it to save the recording
00521                 if (_isRecording)
00522                 {
00523                     await StopRecordingAsync();
00524                 }
00525
00526                 if (_isPreviewing)
00527                 {
00528                     // The call to stop the preview is included here for completeness, but can be
00529                     // safely removed if a call to MediaCapture.Dispose() is being made later,
00530                     // as the preview will be automatically stopped at that point
00531                     await StopPreviewAsync();
00532                 }
00533
00534                 _isInitialized = false;
00535             }
00536
00537             if (_mediaCapture != null)
00538             {
00539                 _mediaCapture.RecordLimitationExceeded -= MediaCapture_RecordLimitationExceeded;
00540                 _mediaCapture.Failed -= MediaCapture_Failed;
00541                 _mediaCapture.Dispose();
00542                 _mediaCapture = null;
00543             }
00544         }
00545
00546         #endregion MediaCapture methods
00547
00548
00549         #region Helper functions
00550
00551         /// <summary>
00552         /// Attempts to lock the page orientation, hide the StatusBar (on Phone) and registers event handlers for hardware buttons and orientation sensors
00553         /// </summary>
00554         /// <returns></returns>
00555         private async Task SetupUiAsync()
00556         {
00557             // Hide the status bar
00558             if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00559             {
00560                 await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();
00561             }
00562
00563             // Populate orientation variables with the current state
00564             _displayOrientation = _displayInformation.CurrentOrientation;
00565             if (_orientationSensor != null)
00566             {
00567                 _deviceOrientation = _orientationSensor.GetCurrentOrientation();
00568             }
00569
00570             RegisterEventHandlers();
00571
00572             var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
00573             // Fall back to the local app storage if the Pictures Library is not available
00574             _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
00575         }
00576
00577         /// <summary>
00578         /// Unregisters event handlers for hardware buttons and orientation sensors, allows the StatusBar (on Phone) to show, and removes the page orientation lock
00579         /// </summary>
00580         /// <returns></returns>
00581         private async Task CleanupUiAsync()
00582         {
00583             UnregisterEventHandlers();
00584
00585             // Show the status bar
00586             if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00587             {
00588                 await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync();
00589             }
00590         }
00591
00592         /// <summary>
00593         /// This method will update the icons, enable/disable and show/hide the photo/video buttons depending on the current state of the app and the capabilities of the device
00594         /// </summary>
00595         private void UpdateCaptureControls()
00596         {
00597             // The buttons should only be enabled if the preview started sucessfully
00598             PhotoButton.IsEnabled = _isPreviewing;
00599             VideoButton.IsEnabled = _isPreviewing;
00600
00601             // Depending on the preview, hide or show the controls grid which houses the individual control buttons and settings
00602             CameraControlsGrid.Visibility = _isPreviewing ? Visibility.Visible : Visibility.Collapsed;
00603
00604             // Update recording button to show "Stop" icon instead of red "Record" icon
00605             StartRecordingIcon.Visibility = _isRecording ? Visibility.Collapsed : Visibility.Visible;
00606             StopRecordingIcon.Visibility = _isRecording ? Visibility.Visible : Visibility.Collapsed;
00607
00608             // If the camera doesn't support simultaneosly taking pictures and recording video, disable the photo button on record
00609             if (_isInitialized && !_mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported)
00610             {
00611                 PhotoButton.IsEnabled = !_isRecording;
00612
00613                 // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
00614                 PhotoButton.Opacity = PhotoButton.IsEnabled ? 1 : 0;
00615             }
00616         }
00617
00618         /// <summary>
00619         /// Registers event handlers for hardware buttons and orientation sensors, and performs an initial update of the UI rotation
00620         /// </summary>
00621         private void RegisterEventHandlers()
00622         {
00623             if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00624             {
00625                 HardwareButtons.CameraPressed += HardwareButtons_CameraPressed;
00626             }
00627
00628             // If there is an orientation sensor present on the device, register for notifications
00629             if (_orientationSensor != null)
00630             {
00631                 _orientationSensor.OrientationChanged += OrientationSensor_OrientationChanged;
00632
00633                 // Update orientation of buttons with the current orientation
00634                 UpdateButtonOrientation();
00635             }
00636
00637             _displayInformation.OrientationChanged += DisplayInformation_OrientationChanged;
00638             _systemMediaControls.PropertyChanged += SystemMediaControls_PropertyChanged;
00639             _systemNavigationManager.BackRequested += SystemNavigationManager_BackRequested;
00640         }
00641
00642         private void SystemNavigationManager_BackRequested(object sender, BackRequestedEventArgs e)
00643         {
00644             if (_singleControlMode)
00645             {
00646                 // Exit single control mode
00647                 SetSingleControl(null);
00648
00649                 e.Handled = true;
00650             }
00651         }
00652
00653
00654         /// <summary>
00655         /// Unregisters event handlers for hardware buttons and orientation sensors
00656         /// </summary>
00657         private void UnregisterEventHandlers()
00658         {
00659             if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00660             {
00661                 HardwareButtons.CameraPressed -= HardwareButtons_CameraPressed;
00662             }
00663
00664             if (_orientationSensor != null)
00665             {
00666                 _orientationSensor.OrientationChanged -= OrientationSensor_OrientationChanged;
00667             }
00668
00669             _displayInformation.OrientationChanged -= DisplayInformation_OrientationChanged;
00670             _systemMediaControls.PropertyChanged -= SystemMediaControls_PropertyChanged;
00671             _systemNavigationManager.BackRequested -= SystemNavigationManager_BackRequested;
00672         }
00673
00674         /// <summary>
00675         /// Attempts to find and return a device mounted on the panel specified, and on failure to find one it will return the first device listed
00676         /// </summary>
00677         /// <param name="desiredPanel">The desired panel on which the returned device should be mounted, if available</param>
00678         /// <returns></returns>
00679         private static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel)
00680         {
00681             // Get available devices for capturing pictures
00682             var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
00683
00684             // Get the desired camera by panel
00685             DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);
00686
00687             // If there is no device mounted on the desired panel, return the first device found
00688             return desiredDevice ?? allVideoDevices.FirstOrDefault();
00689         }
00690
00691         /// <summary>
00692         /// Applies the given orientation to a photo stream and saves it as a StorageFile
00693         /// </summary>
00694         /// <param name="stream">The photo stream</param>
00695         /// <param name="file">The StorageFile in which the photo stream will be saved</param>
00696         /// <param name="photoOrientation">The orientation metadata to apply to the photo</param>
00697         /// <returns></returns>
00698         private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation)
00699         {
00700             using (var inputStream = stream)
00701             {
00702                 var decoder = await BitmapDecoder.CreateAsync(inputStream);
00703
00704                 using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
00705                 {
00706                     var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
00707
00708                     var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };
00709
00710                     await encoder.BitmapProperties.SetPropertiesAsync(properties);
00711                     await encoder.FlushAsync();
00712                 }
00713             }
00714         }
00715
00716         /// <summary>
00717         /// Calculates the size and location of the rectangle that contains the preview stream within the preview control, when the scaling mode is Uniform
00718         /// </summary>
00719         /// <param name="previewResolution">The resolution at which the preview is running</param>
00720         /// <param name="previewControl">The control that is displaying the preview using Uniform as the scaling mode</param>
00721         /// <param name="displayOrientation">The orientation of the display, to account for device rotation and changing of the CaptureElement display ratio compared to the camera stream</param>
00722         /// <returns></returns>
00723         public static Rect GetPreviewStreamRectInControl(VideoEncodingProperties previewResolution, CaptureElement previewControl, DisplayOrientations displayOrientation)
00724         {
00725             var result = new Rect();
00726
00727             // In case this function is called before everything is initialized correctly, return an empty result
00728             if (previewControl == null || previewControl.ActualHeight < 1 || previewControl.ActualWidth < 1 ||
00729                 previewResolution == null || previewResolution.Height == 0 || previewResolution.Width == 0)
00730             {
00731                 return result;
00732             }
00733
00734             var streamWidth = previewResolution.Width;
00735             var streamHeight = previewResolution.Height;
00736
00737             // For portrait orientations, the width and height need to be swapped
00738             if (displayOrientation == DisplayOrientations.Portrait || displayOrientation == DisplayOrientations.PortraitFlipped)
00739             {
00740                 streamWidth = previewResolution.Height;
00741                 streamHeight = previewResolution.Width;
00742             }
00743
00744             // Start by assuming the preview display area in the control spans the entire width and height both (this is corrected in the next if for the necessary dimension)
00745             result.Width = previewControl.ActualWidth;
00746             result.Height = previewControl.ActualHeight;
00747
00748             // If UI is "wider" than preview, letterboxing will be on the sides
00749             if ((previewControl.ActualWidth / previewControl.ActualHeight > streamWidth / (double)streamHeight))
00750             {
00751                 var scale = previewControl.ActualHeight / streamHeight;
00752                 var scaledWidth = streamWidth * scale;
00753
00754                 result.X = (previewControl.ActualWidth - scaledWidth) / 2.0;
00755                 result.Width = scaledWidth;
00756             }
00757             else // Preview stream is "wider" than UI, so letterboxing will be on the top+bottom
00758             {
00759                 var scale = previewControl.ActualWidth / streamWidth;
00760                 var scaledHeight = streamHeight * scale;
00761
00762                 result.Y = (previewControl.ActualHeight - scaledHeight) / 2.0;
00763                 result.Height = scaledHeight;
00764             }
00765
00766             return result;
00767         }
00768
00769         #endregion Helper functions
00770
00771
00772         #region Rotation helpers
00773
00774         /// <summary>
00775         /// Calculates the current camera orientation from the device orientation by taking into account whether the camera is external or facing the user
00776         /// </summary>
00777         /// <returns>The camera orientation in space, with an inverted rotation in the case the camera is mounted on the device and is facing the user</returns>
00778         private SimpleOrientation GetCameraOrientation()
00779         {
00780             if (_externalCamera)
00781             {
00782                 // Cameras that are not attached to the device do not rotate along with it, so apply no rotation
00783                 return SimpleOrientation.NotRotated;
00784             }
00785
00786             var result = _deviceOrientation;
00787
00788             // Account for the fact that, on portrait-first devices, the camera sensor is mounted at a 90 degree offset to the native orientation
00789             if (_displayInformation.NativeOrientation == DisplayOrientations.Portrait)
00790             {
00791                 switch (result)
00792                 {
00793                     case SimpleOrientation.Rotated90DegreesCounterclockwise:
00794                         result = SimpleOrientation.NotRotated;
00795                         break;
00796                     case SimpleOrientation.Rotated180DegreesCounterclockwise:
00797                         result = SimpleOrientation.Rotated90DegreesCounterclockwise;
00798                         break;
00799                     case SimpleOrientation.Rotated270DegreesCounterclockwise:
00800                         result = SimpleOrientation.Rotated180DegreesCounterclockwise;
00801                         break;
00802                     case SimpleOrientation.NotRotated:
00803                         result = SimpleOrientation.Rotated270DegreesCounterclockwise;
00804                         break;
00805                 }
00806             }
00807
00808             // If the preview is being mirrored for a front-facing camera, then the rotation should be inverted
00809             if (_mirroringPreview)
00810             {
00811                 // This only affects the 90 and 270 degree cases, because rotating 0 and 180 degrees is the same clockwise and counter-clockwise
00812                 switch (result)
00813                 {
00814                     case SimpleOrientation.Rotated90DegreesCounterclockwise:
00815                         return SimpleOrientation.Rotated270DegreesCounterclockwise;
00816                     case SimpleOrientation.Rotated270DegreesCounterclockwise:
00817                         return SimpleOrientation.Rotated90DegreesCounterclockwise;
00818                 }
00819             }
00820
00821             return result;
00822         }
00823
00824         /// <summary>
00825         /// Converts the given orientation of the device in space to the corresponding rotation in degrees
00826         /// </summary>
00827         /// <param name="orientation">The orientation of the device in space</param>
00828         /// <returns>An orientation in degrees</returns>
00829         private static int ConvertDeviceOrientationToDegrees(SimpleOrientation orientation)
00830         {
00831             switch (orientation)
00832             {
00833                 case SimpleOrientation.Rotated90DegreesCounterclockwise:
00834                     return 90;
00835                 case SimpleOrientation.Rotated180DegreesCounterclockwise:
00836                     return 180;
00837                 case SimpleOrientation.Rotated270DegreesCounterclockwise:
00838                     return 270;
00839                 case SimpleOrientation.NotRotated:
00840                 default:
00841                     return 0;
00842             }
00843         }
00844
00845         /// <summary>
00846         /// Converts the given orientation of the app on the screen to the corresponding rotation in degrees
00847         /// </summary>
00848         /// <param name="orientation">The orientation of the app on the screen</param>
00849         /// <returns>An orientation in degrees</returns>
00850         private static int ConvertDisplayOrientationToDegrees(DisplayOrientations orientation)
00851         {
00852             switch (orientation)
00853             {
00854                 case DisplayOrientations.Portrait:
00855                     return 90;
00856                 case DisplayOrientations.LandscapeFlipped:
00857                     return 180;
00858                 case DisplayOrientations.PortraitFlipped:
00859                     return 270;
00860                 case DisplayOrientations.Landscape:
00861                 default:
00862                     return 0;
00863             }
00864         }
00865
00866         /// <summary>
00867         /// Converts the given orientation of the device in space to the metadata that can be added to captured photos
00868         /// </summary>
00869         /// <param name="orientation">The orientation of the device in space</param>
00870         /// <returns></returns>
00871         private static PhotoOrientation ConvertOrientationToPhotoOrientation(SimpleOrientation orientation)
00872         {
00873             switch (orientation)
00874             {
00875                 case SimpleOrientation.Rotated90DegreesCounterclockwise:
00876                     return PhotoOrientation.Rotate90;
00877                 case SimpleOrientation.Rotated180DegreesCounterclockwise:
00878                     return PhotoOrientation.Rotate180;
00879                 case SimpleOrientation.Rotated270DegreesCounterclockwise:
00880                     return PhotoOrientation.Rotate270;
00881                 case SimpleOrientation.NotRotated:
00882                 default:
00883                     return PhotoOrientation.Normal;
00884             }
00885         }
00886
00887         /// <summary>
00888         /// Uses the current device orientation in space and page orientation on the screen to calculate the rotation
00889         /// transformation to apply to the controls
00890         /// </summary>
00891         private void UpdateButtonOrientation()
00892         {
00893             int device = ConvertDeviceOrientationToDegrees(_deviceOrientation);
00894             int display = ConvertDisplayOrientationToDegrees(_displayOrientation);
00895
00896             if (_displayInformation.NativeOrientation == DisplayOrientations.Portrait)
00897             {
00898                 device -= 90;
00899             }
00900
00901             // Combine both rotations and make sure that 0 <= result < 360
00902             var angle = (360 + display + device) % 360;
00903
00904             // Rotate the buttons in the UI to match the rotation of the device
00905             var transform = new RotateTransform { Angle = angle };
00906
00907             // The RenderTransform is safe to use (i.e. it won't cause layout issues) in this case, because these buttons have a 1:1 aspect ratio
00908             PhotoButton.RenderTransform = transform;
00909             VideoButton.RenderTransform = transform;
00910         }
00911
00912         #endregion Rotation helpers
00913
00914
00915         #region Manual controls setup
00916
00917         // If activeButton = null, then exit single control mode.
00918         private void SetSingleControl(object activeButton)
00919         {
00920             _singleControlMode = (activeButton != null);
00921
00922             // If in single control mode, hide all manual control buttons (except for the active button).
00923             // if not in single control mode, then show all the buttons which are supported.
00924             foreach (var button in ScenarioControlStackPanel.Children.OfType<Button>())
00925             {
00926                 if (button != activeButton)
00927                 {
00928                     // The Tag property of each button stores whether that button is supported.
00929                     // The value is set in the Update___ControlCapabilities method of each control.
00930                     button.Visibility = _singleControlMode ? Visibility.Collapsed : (Visibility)button.Tag;
00931                 }
00932             }
00933
00934             // Show the container control for manual configuration only when in single control mode
00935             ManualControlsGrid.Visibility = _singleControlMode ? Visibility.Visible : Visibility.Collapsed;
00936
00937             // Show the Back button only when in single control mode
00938             _systemNavigationManager.AppViewBackButtonVisibility = _singleControlMode ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
00939
00940         }
00941
00942         private void ManualControlButton_Click(object sender, RoutedEventArgs e)
00943         {
00944             // Toggle single control mode
00945             SetSingleControl(_singleControlMode ? null : sender);
00946         }
00947
00948         /// <summary>
00949         /// Reflect the capabilities of the device in the UI, and set the initial state for each control
00950         /// </summary>
00951         private void UpdateManualControlCapabilities()
00952         {
00953             // Prevent the setup from triggering API calls
00954             _settingUpUi = true;
00955
00956             // The implementation of these methods is in the partial classes named MainPage.Control.xaml.cs, where "Control" is the name of the control
00957             UpdateFlashControlCapabilities();
00958             UpdateZoomControlCapabilities();
00959             UpdateFocusControlCapabilities();
00960             UpdateWbControlCapabilities();
00961             UpdateIsoControlCapabilities();
00962             UpdateExposureControlCapabilities();
00963             UpdateEvControlCapabilities();
00964
00965             _settingUpUi = false;
00966         }
00967
00968         #endregion
00969
00970     }
00971
00972
00973     public class InvertBoolConverter : IValueConverter
00974     {
00975         public object Convert(object value, Type targetType, object parameter, string language)
00976         {
00977             return !(bool)value;
00978         }
00979
00980         public object ConvertBack(object value, Type targetType, object parameter, string language)
00981         {
00982             return !(bool)value;
00983         }
00984     }
00985
00986     public class RoundingConverter : IValueConverter
00987     {
00988         public object Convert(object value, Type targetType, object parameter, string language)
00989         {
00990             return Math.Round((double)value, 2);
00991         }
00992
00993         public object ConvertBack(object value, Type targetType, object parameter, string language)
00994         {
00995             return value;
00996         }
00997     }
00998 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/ProjectionViewPage.xaml.cs Source File

  • AdvancedCasting
  • cs

ProjectionViewPage.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using ScreenCasting.Controls;
00013 using System;
00014 using System.Threading.Tasks;
00015 using Windows.UI.Core;
00016 using Windows.UI.ViewManagement;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace ScreenCasting
00022 {
00023     public sealed partial class ProjectionViewPage : Page
00024     {
00025         public ProjectionViewPage()
00026         {
00027             this.InitializeComponent();
00028
00029             ProjectedMediaTransportControls pmtcs = this._player.TransportControls as ProjectedMediaTransportControls;
00030             if (pmtcs != null)
00031                 pmtcs.StopProjectingButtonClick += ProjectionViewPage_StopProjectingButtonClick;
00032
00033             this._player.MediaOpened += Player_MediaOpened;
00034         }
00035
00036         private void Player_MediaOpened(object sender, RoutedEventArgs e)
00037         {
00038             this._player.IsFullWindow = true;
00039             this._player.AreTransportControlsEnabled = true;
00040         }
00041
00042         private void ProjectionViewPage_StopProjectingButtonClick(object sender, EventArgs e)
00043         {
00044             this.StopProjecting();
00045         }
00046
00047
00048
00049         public async Task<bool> SetMediaSource (Uri source, TimeSpan position)
00050         {
00051             await this._player.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00052             {
00053                 this._player.Source = source;
00054                 this._player.Position = position;
00055                 this._player.Play();
00056             });
00057             return true;
00058         }
00059
00060         public MediaElement Player
00061         {
00062             get { return this._player; }
00063         }
00064
00065         ProjectionViewBroker broker = null;
00066         protected override void OnNavigatedTo(NavigationEventArgs e)
00067         {
00068             broker = (ProjectionViewBroker)e.Parameter;
00069             broker.ProjectedPage = this;
00070
00071             // Listen for when it's time to close this view
00072             broker.ProjectionViewPageControl.Released += thisViewControl_Released;
00073         }
00074
00075         private async void thisViewControl_Released(object sender, EventArgs e)
00076         {
00077             // There are two major cases where this event will get invoked:
00078             // 1. The view goes unused for some time, and the system cleans it up
00079             // 2. The app calls "StopProjectingAsync"
00080             broker.ProjectionViewPageControl.Released -= thisViewControl_Released;
00081             await broker.ProjectionViewPageControl.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00082                 {
00083                     this.broker.NotifyProjectionStopping();
00084                     MainPage.Current.ProjectionViewPageControl = null;
00085                 });
00086
00087             this._player.Stop();
00088             this._player.Source = null;
00089
00090             Window.Current.Close();
00091         }
00092
00093         public async void SwapViews()
00094         {
00095             // The view might arrive on the wrong display. The user can
00096             // easily swap the display on which the view appears
00097             broker.ProjectionViewPageControl.StartViewInUse();
00098             await ProjectionManager.SwapDisplaysForViewsAsync(
00099                 ApplicationView.GetForCurrentView().Id,
00100                 broker.MainViewId
00101             );
00102             broker.ProjectionViewPageControl.StopViewInUse();
00103         }
00104         private void SwapViews_Click(object sender, RoutedEventArgs e)
00105         {
00106             SwapViews();
00107         }
00108
00109         public async void StopProjecting()
00110         {
00111             broker.NotifyProjectionStopping();
00112
00113             // There may be cases to end the projection from the projected view
00114             // (e.g. the presentation hosted in that view concludes)
00115             // broker.ProjectionViewPageControl.StartViewInUse();
00116             await this._player.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
00117             {
00118                 this._player.Stop();
00119                 this._player.Source = null;
00120
00121                 broker.ProjectionViewPageControl.StartViewInUse();
00122
00123                 try
00124                 {
00125                     await ProjectionManager.StopProjectingAsync(
00126                         broker.ProjectionViewPageControl.Id,
00127                         broker.MainViewId
00128                         );
00129                 }
00130                 catch { }
00131                 Window.Current.Close();
00132
00133             });
00134
00135            broker.ProjectionViewPageControl.StopViewInUse();
00136         }
00137         private void StopProjecting_Click(object sender, RoutedEventArgs e)
00138         {
00139             StopProjecting();
00140         }
00141     }
00142 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OnDemandHotspot/cppwinrt/pch.cpp Source File

  • OnDemandHotspot
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/Renderers/ShapeRenderer.h Source File

  • ComplexInk
  • cpp
  • Renderers

ShapeRenderer.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Common/DirectXHelper.h"
00006 #include <random>
00007 #include <stdlib.h>
00008 #include <time.h>
00009
00010 #define MAX_SHAPE_SIZE_PERCENTAGE       0.20f
00011 #define MIN_SHAPE_SIZE_PERCENTAGE       0.08f
00012
00013 namespace SDKTemplate
00014 {
00015     // Struct to store the rectangle and the color for each object
00016     struct Shape
00017     {
00018         D2D1_RECT_F shape;
00019         Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> brush;
00020     };
00021
00022     class ShapeRenderer
00023     {
00024     public:
00025         ShapeRenderer();
00026         Shape Update(Microsoft::WRL::ComPtr<ID2D1DeviceContext> d2dContext);
00027         void Render(Shape shape, Microsoft::WRL::ComPtr<ID2D1DeviceContext> d2dContext);
00028         void RefreshSize(Windows::Foundation::Size newSize);
00029
00030     private:
00031         void CreateBrush(ID2D1SolidColorBrush** brush, Microsoft::WRL::ComPtr<ID2D1DeviceContext> d2dContext);
00032
00033         // Random engine generator to get the position of shapes on the canvas
00034         std::default_random_engine _generator;
00035
00036         // We create two normal distribution members so that shapes are mostly
00037         // placed in the middle of the canvas
00038         std::normal_distribution<float> _shapeDistributionX;
00039         std::normal_distribution<float> _shapeDistributionY;
00040     };
00041 }
Generated on Fri Nov 15 2024 22:18:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Nfc/NfcHceBackgroundTask/BgTask.h Source File

  • Nfc
  • NfcHceBackgroundTask

BgTask.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace NfcHceBackgroundTask
00015 {
00016     [Windows::Foundation::Metadata::WebHostHidden]
00017     public ref class BgTask sealed :
00018         public Windows::ApplicationModel::Background::IBackgroundTask
00019     {
00020     public:
00021         BgTask();
00022
00023         virtual void Run(
00024             Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance);
00025
00026     private:
00027         typedef enum _LaunchType
00028         {
00029             Complete,
00030             Failed,
00031             Denied
00032         } LaunchType;
00033
00034     private:
00035         void HandleHceActivation();
00036
00037         void LaunchForegroundApp(LaunchType type, LPWSTR wszMessage);
00038
00039         void EndTask();
00040
00041         void ApduReceived(
00042             Windows::Devices::SmartCards::SmartCardEmulator^ emulator,
00043             Windows::Devices::SmartCards::SmartCardEmulatorApduReceivedEventArgs^ eventArgs);
00044
00045         Windows::Storage::Streams::IBuffer^ ProcessCommandApdu(
00046             _In_ Windows::Storage::Streams::IBuffer^ commandApdu,
00047             _Out_ bool* pfComplete);
00048
00049         void DebugLogString(Platform::String^ message);
00050
00051         void DebugLog(const wchar_t* pwstrMessage);
00052
00053         void FlushDebugLog();
00054
00055     private:
00056         Microsoft::WRL::Wrappers::CriticalSection m_csLock;
00057         Windows::ApplicationModel::Background::IBackgroundTaskInstance^ m_taskInstance;
00058         Platform::Agile<Windows::ApplicationModel::Background::BackgroundTaskDeferral> m_deferral;
00059         Windows::Devices::SmartCards::SmartCardEmulator^ m_emulator;
00060         Windows::Devices::SmartCards::SmartCardTriggerDetails^ m_triggerDetails;
00061         Windows::Devices::SmartCards::SmartCardAppletIdGroupRegistration^ m_paymentAidRegistration;
00062
00063         Platform::Guid m_currentConnectionId;
00064         LPBYTE m_pbCurrentAppletId = nullptr;
00065         bool m_fTransactionCompleted = false;
00066         bool m_fDenyTransactions = false;
00067         bool m_fTaskEnded = false;
00068
00069         Microsoft::WRL::Wrappers::CriticalSection m_csDebugLog;
00070         std::wstring m_wsDebugLog;
00071     };
00072 }
Generated on Fri Nov 15 2024 22:20:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/xBindSampleModel/FileSystemDataSource.cs Source File

  • XamlBind
  • cs
  • xBindSampleModel

FileSystemDataSource.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections;
00003 using System.Collections.Generic;
00004 using System.Collections.Specialized;
00005 using System.ComponentModel;
00006 using System.Diagnostics;
00007 using System.Threading.Tasks;
00008 using Windows.Foundation;
00009 using Windows.Foundation.Collections;
00010 using Windows.Storage;
00011 using Windows.Storage.FileProperties;
00012 using Windows.Storage.Search;
00013 using Windows.UI.Core;
00014 using Windows.UI.Xaml.Interop;
00015 using Windows.UI.Xaml.Media.Imaging;
00016
00017 namespace xBindSampleModel
00018 {
00019
00020     public sealed class FileItem
00021     {
00022         public string DisplayName { get; set; }
00023         public string Path { get; set; }
00024         public int FileSize { get; set; }
00025         public DateTimeOffset Date { get; set; }
00026         public int ImageWidth { get; private set; }
00027         public int ImageHeight { get; private set; }
00028
00029         private BitmapImage _imageData;
00030         public BitmapImage ImageData { get { return _imageData; } }
00031
00032         private async Task FetchImageAsync()
00033         {
00034             _imageData = new BitmapImage();
00035             StorageFile f = await StorageFile.GetFileFromPathAsync(Path);
00036             await _imageData.SetSourceAsync(await f.GetThumbnailAsync(ThumbnailMode.SingleItem));
00037         }
00038         public string Key { get; private set; }
00039
00040         internal async static Task<FileItem> fromStorageFile(StorageFile f)
00041         {
00042             FileItem item = new FileItem();
00043             item.Path = f.Path;
00044             item.DisplayName = f.DisplayName;
00045             BasicProperties bp = await f.GetBasicPropertiesAsync();
00046             item.FileSize = (int)bp.Size;
00047             item.Date = bp.DateModified;
00048             item.Key = f.FolderRelativeId;
00049             ImageProperties ip = await f.Properties.GetImagePropertiesAsync();
00050             item.ImageWidth = (int)ip.Width;
00051             item.ImageHeight = (int)ip.Height;
00052             var t = item.FetchImageAsync();
00053             return item;
00054         }
00055
00056         public string prettyDate
00057         {
00058             get
00059             {
00060                 DateTime now = DateTime.Now;
00061                 if (Date.Date == now.Date)
00062                 {
00063                     return Date.ToLocalTime().ToString("T");
00064                 }
00065                 else if (Date.Date == now.Date.AddDays(-1))
00066                 {
00067                     return "Yesterday";
00068                 }
00069                 else return Date.ToLocalTime().ToString("d MMM yyyy");
00070             }
00071         }
00072
00073         public string prettyFileSize
00074         {
00075             get { return FileSize.ToString("N0") + " bytes"; }
00076         }
00077
00078         public string prettyImageSize
00079         {
00080             get { return ImageWidth + " x " + ImageHeight + " px"; }
00081         }
00082     }
00083
00084
00085     public sealed class FileDataSource : INotifyCollectionChanged, System.Collections.IList, IObservableVector<FileItem>
00086     {
00087         private StorageFileQueryResult _queryResult;
00088         private CoreDispatcher dispatcher;
00089         private int _count = 0;
00090         private List<FileItem> _cache;
00091
00092         public event NotifyCollectionChangedEventHandler CollectionChanged;
00093         public event VectorChangedEventHandler<FileItem> VectorChanged;
00094
00095         public FileDataSource()
00096         {
00097             dispatcher = Windows.UI.Xaml.Window.Current.Dispatcher;
00098             _cache = new List<FileItem>();
00099         }
00100
00101         //WinRT wrapper
00102         public IAsyncAction SetupDataSource(StorageFolder folder)
00103         {
00104             return this.SetupDataSourceImpl(folder).AsAsyncAction();
00105         }
00106
00107         private async Task SetupDataSourceImpl(StorageFolder folder)
00108         {
00109             this.Folder = folder;
00110             QueryOptions options = new QueryOptions();
00111             options.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
00112             _queryResult = this.Folder.CreateFileQueryWithOptions(options);
00113             _queryResult.ContentsChanged += QueryResult_ContentsChanged;
00114             await FetchData();
00115         }
00116
00117         public IAsyncAction SetupDataSourceUsingPicturesFolder()
00118         {
00119             return SetupDataSourceUsingPicturesFolderImpl().AsAsyncAction();
00120         }
00121         private async Task SetupDataSourceUsingPicturesFolderImpl()
00122         {
00123             StorageLibrary pictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
00124             await SetupDataSourceImpl(pictures.SaveFolder);
00125         }
00126         public StorageFolder Folder { get; set; }
00127
00128         private void QueryResult_ContentsChanged(IStorageQueryResultBase sender, object args)
00129         {
00130             if (!dispatcher.HasThreadAccess)
00131             {
00132                 var t = dispatcher.RunAsync(CoreDispatcherPriority.Normal, ResetCollection);
00133             }
00134         }
00135
00136         public void ResetCollection()
00137         {
00138             if (CollectionChanged != null)
00139             {
00140                 CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
00141             }
00142             if (VectorChanged != null)
00143             {
00144                 VectorChanged(this, new VectorChangedEventArgs() { CollectionChange = CollectionChange.Reset });
00145             }
00146         }
00147
00148         private const int BATCHSIZE = 50;
00149
00150         async Task FetchData()
00151         {
00152             _count = (int)await _queryResult.GetItemCountAsync();
00153             this._cache.Clear();
00154             this._cache.AddRange(new FileItem[_count]);
00155             for (int i = 0; i < _count; i += BATCHSIZE)
00156             {
00157                 await fetchBatch(i);
00158             }
00159
00160             if (VectorChanged != null)
00161             {
00162                 VectorChanged(this, new VectorChangedEventArgs() { CollectionChange = CollectionChange.Reset });
00163             }
00164             if (CollectionChanged != null)
00165             {
00166                 CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
00167             }
00168         }
00169
00170         async Task fetchBatch(int index)
00171         {
00172             IReadOnlyList<StorageFile> results = await _queryResult.GetFilesAsync((uint)index, (uint)BATCHSIZE);
00173             List<Task> tasks = new List<Task>(BATCHSIZE);
00174             for (int i = 0; i < results.Count; i++)
00175             {
00176                 tasks.Add(
00177                     FileItem.fromStorageFile(results[i]).ContinueWith((f, j) =>
00178                     {
00179                         int cacheIndex = index + (int)j;
00180                         _cache[cacheIndex] = f.Result;
00181                     }, i));
00182             }
00183             await Task.WhenAll(tasks.ToArray());
00184         }
00185
00186         bool IList.Contains(object item)
00187         {
00188             return ((IList)this).IndexOf(item) != -1;
00189         }
00190
00191         object this[int index]
00192         {
00193             get
00194             {
00195                 object result = null;
00196                 if (index < _cache.Count) result = _cache[index];
00197                 return result;
00198             }
00199             set
00200             {
00201                 FileItem f = value as FileItem;
00202                 if (f != null)
00203                     _cache[index] = f;
00204                 else
00205                     throw new ArgumentException("The value is expected to be a fileitem");
00206             }
00207         }
00208         public int Count
00209         {
00210             get { return _count; }
00211         }
00212
00213         bool IList.IsFixedSize { get { return false; } }
00214
00215         bool IList.IsReadOnly { get { return true; } }
00216
00217
00218         int ICollection.Count { get { return _count; } }
00219
00220         bool ICollection.IsSynchronized { get { throw new NotImplementedException(); } }
00221
00222         object ICollection.SyncRoot { get { throw new NotImplementedException(); } }
00223
00224         object IList.this[int index]
00225         {
00226             get
00227             {
00228                 return this[index];
00229             }
00230             set
00231             {
00232                 throw new NotImplementedException();
00233             }
00234         }
00235
00236         int IList.Add(object item)
00237         {
00238             throw new NotImplementedException();
00239         }
00240
00241         void IList.Clear()
00242         {
00243             throw new NotImplementedException();
00244         }
00245
00246         int IList.IndexOf(object item)
00247         {
00248             return _cache.IndexOf((FileItem)item);
00249         }
00250
00251         void IList.Insert(int index, object value)
00252         {
00253             throw new NotImplementedException();
00254         }
00255
00256         void IList.Remove(object value)
00257         {
00258             throw new NotImplementedException();
00259         }
00260
00261         void IList.RemoveAt(int index)
00262         {
00263             throw new NotImplementedException();
00264         }
00265
00266         void ICollection.CopyTo(Array array, int index)
00267         {
00268             throw new NotImplementedException();
00269         }
00270
00271         IEnumerator IEnumerable.GetEnumerator()
00272         {
00273             throw new NotImplementedException();
00274         }
00275
00276         #region IObservableVector Implementation
00277         FileItem IList<FileItem>.this[int index]
00278         {
00279             get
00280             {
00281                 FileItem result = null;
00282                 if (index < _cache.Count) result = _cache[index];
00283                 return result;
00284             }
00285
00286             set
00287             {
00288                 _cache[index] = value;
00289             }
00290         }
00291
00292         int ICollection<FileItem>.Count
00293         {
00294             get
00295             {
00296                 return _count;
00297             }
00298         }
00299
00300         bool ICollection<FileItem>.IsReadOnly
00301         {
00302             get
00303             {
00304                 return true;
00305             }
00306         }
00307
00308         void ICollection<FileItem>.Add(FileItem item)
00309         {
00310             throw new NotImplementedException();
00311         }
00312
00313         void ICollection<FileItem>.Clear()
00314         {
00315             throw new NotImplementedException();
00316         }
00317
00318         bool ICollection<FileItem>.Contains(FileItem item)
00319         {
00320             throw new NotImplementedException();
00321         }
00322
00323         void ICollection<FileItem>.CopyTo(FileItem[] array, int arrayIndex)
00324         {
00325             throw new NotImplementedException();
00326         }
00327
00328         IEnumerator<FileItem> IEnumerable<FileItem>.GetEnumerator()
00329         {
00330             throw new NotImplementedException();
00331         }
00332
00333         int IList<FileItem>.IndexOf(FileItem item)
00334         {
00335             throw new NotImplementedException();
00336         }
00337
00338         void IList<FileItem>.Insert(int index, FileItem item)
00339         {
00340             throw new NotImplementedException();
00341         }
00342
00343         bool ICollection<FileItem>.Remove(FileItem item)
00344         {
00345             throw new NotImplementedException();
00346         }
00347
00348         void IList<FileItem>.RemoveAt(int index)
00349         {
00350             throw new NotImplementedException();
00351         }
00352         #endregion
00353     }
00354
00355 }
00356
00357
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cppwinrt/Scenario3_Enum.h Source File

  • Calendar
  • cppwinrt

Scenario3_Enum.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_Enum.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario3_Enum : Scenario3_EnumT<Scenario3_Enum>
00019     {
00020         Scenario3_Enum();
00021
00022         void ShowResults_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario3_Enum : Scenario3_EnumT<Scenario3_Enum, implementation::Scenario3_Enum>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/ConsumerExperiences/cs/Scenario2ViewModel.cs Source File

  • AllJoyn
  • ConsumerExperiences
  • cs

Scenario2ViewModel.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using org.alljoyn.Onboarding;
00013 using SDKTemplate;
00014 using System;
00015 using System.Collections.Generic;
00016 using System.Collections.ObjectModel;
00017 using System.ComponentModel;
00018 using System.Runtime.CompilerServices;
00019 using System.Threading;
00020 using System.Threading.Tasks;
00021 using System.Windows.Input;
00022 using Windows.Devices.AllJoyn;
00023 using Windows.Devices.Enumeration;
00024 using Windows.Devices.WiFi;
00025 using Windows.Networking.Connectivity;
00026 using Windows.Security.Credentials;
00027 using Windows.Security.Cryptography;
00028 using Windows.UI.Core;
00029 using Windows.UI.Xaml;
00030
00031 namespace AllJoynConsumerExperiences
00032 {
00033     class Scenario2ViewModel : INotifyPropertyChanged
00034     {
00035         private MainPage m_rootPage;
00036         private CoreDispatcher m_dispatcher;
00037         private WiFiAdapter m_wiFiAdapter = null;
00038         private IReadOnlyList<WiFiAdapter> m_wiFiAdapterList;
00039         private ObservableCollection<string> m_wiFiAdapterDisplayNames;
00040         private ObservableCollection<WiFiAvailableNetwork> m_onboarderNetworkList;
00041         private ObservableCollection<OnboardingScanListItem> m_onboardeeNetworkList;
00042         private WiFiAvailableNetwork m_selectedSoftAPNetwork;
00043         private WiFiAvailableNetwork m_selectedOnboarderNetwork;
00044         private OnboardingScanListItem m_selectedOnboardeeNetwork;
00045         private Visibility m_passwordVisibility = Visibility.Collapsed;
00046         private Visibility m_onboardeeSsidListVisibility = Visibility.Visible;
00047         private Visibility m_onboarderSsidListVisibility = Visibility.Collapsed;
00048         private Visibility m_manualSsidTextBoxVisibility = Visibility.Collapsed;
00049         private Visibility m_connectPanelVisibility = Visibility.Collapsed;
00050         private Visibility m_onboardingConfigurationVisibility = Visibility.Collapsed;
00051         private Visibility m_scanPanelVisibility = Visibility.Collapsed;
00052         private Visibility m_wiFiAdapterListVisibility = Visibility.Collapsed;
00053         private Visibility m_authenticationVisibility = Visibility.Collapsed;
00054         private int m_selectedWiFiAdapterIndex = -1;
00055         private string m_savedProfileName;
00056         private string m_softAPPassword = "";
00057         private string m_onboardingPassword = "";
00058         private string m_manualSsid = "";
00059         private string m_key = "";
00060         private bool? m_manualSsidIsChecked = null;
00061         private bool? m_onboardingProducerIsChecked = null;
00062         private bool? m_physicalDeviceIsChecked = null;
00063         private bool m_showOnboardeeSsidList = true;
00064         private bool m_showOnboarderSsidList = false;
00065         private AllJoynBusAttachment m_busAttachment = null;
00066         private DeviceWatcher m_watcher = null;
00067         private OnboardingConsumer m_consumer = null;
00068         private OnboardingAuthenticationType m_selectedAuthType = OnboardingAuthenticationType.Any;
00069         private TaskCompletionSource<bool> m_authenticateClicked = null;
00070         private int m_onboardSessionAlreadyJoined;
00071
00072         public Scenario2ViewModel()
00073         {
00074             m_dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
00075             m_rootPage = MainPage.Current;
00076             m_wiFiAdapterDisplayNames = new ObservableCollection<string>();
00077             m_onboarderNetworkList = new ObservableCollection<WiFiAvailableNetwork>();
00078             m_onboardeeNetworkList = new ObservableCollection<OnboardingScanListItem>();
00079         }
00080
00081         public event PropertyChangedEventHandler PropertyChanged;
00082
00083         public ObservableCollection<string> WiFiAdapterDisplayNames
00084         {
00085             get
00086             {
00087                 return m_wiFiAdapterDisplayNames;
00088             }
00089         }
00090
00091         public ObservableCollection<WiFiAvailableNetwork> OnboarderNetworkList
00092         {
00093             get
00094             {
00095                 return m_onboarderNetworkList;
00096             }
00097         }
00098
00099         public ObservableCollection<OnboardingScanListItem> OnboardeeNetworkList
00100         {
00101             get
00102             {
00103                 return m_onboardeeNetworkList;
00104             }
00105         }
00106
00107         public int SelectedWiFiAdapterIndex
00108         {
00109             get
00110             {
00111                 return m_selectedWiFiAdapterIndex;
00112             }
00113             set
00114             {
00115                 m_selectedWiFiAdapterIndex = value;
00116                 ScanForWiFiNetworksAsync();
00117             }
00118         }
00119
00120         public WiFiAvailableNetwork SelectedSoftAPNetwork
00121         {
00122             get
00123             {
00124                 return m_selectedSoftAPNetwork;
00125             }
00126             set
00127             {
00128                 m_selectedSoftAPNetwork = value;
00129                 if (m_selectedSoftAPNetwork != null)
00130                 {
00131                     if (m_selectedSoftAPNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211)
00132                     {
00133                         PasswordVisibility = Visibility.Collapsed;
00134                     }
00135                     else
00136                     {
00137                         PasswordVisibility = Visibility.Visible;
00138                     }
00139                 }
00140                 else
00141                 {
00142                     PasswordVisibility = Visibility.Collapsed;
00143                 }
00144                 ClearPasswords();
00145             }
00146         }
00147
00148         public WiFiAvailableNetwork SelectedOnboarderNetwork
00149         {
00150             get
00151             {
00152                 return m_selectedOnboarderNetwork;
00153             }
00154             set
00155             {
00156                 m_selectedOnboarderNetwork = value;
00157             }
00158         }
00159
00160         public OnboardingScanListItem SelectedOnboardeeNetwork
00161         {
00162             get
00163             {
00164                 return m_selectedOnboardeeNetwork;
00165             }
00166             set
00167             {
00168                 m_selectedOnboardeeNetwork = value;
00169                 if (m_selectedOnboardeeNetwork != null)
00170                 {
00171                     SelectedAuthType = (OnboardingAuthenticationType)m_selectedOnboardeeNetwork.Value2;
00172                 }
00173             }
00174         }
00175
00176         public Visibility PasswordVisibility
00177         {
00178             get
00179             {
00180                 return m_passwordVisibility;
00181             }
00182             private set
00183             {
00184                 m_passwordVisibility = value;
00185                 RaisePropertyChangedEventAsync();
00186             }
00187         }
00188
00189         public Visibility OnboardeeSsidListVisibility
00190         {
00191             get
00192             {
00193                 return m_onboardeeSsidListVisibility;
00194             }
00195             private set
00196             {
00197                 m_onboardeeSsidListVisibility = value;
00198                 if (m_manualSsidIsChecked != true)
00199                 {
00200                     switch (m_onboardeeSsidListVisibility)
00201                     {
00202                         case Visibility.Visible:
00203                             m_showOnboardeeSsidList = true;
00204                             break;
00205                         case Visibility.Collapsed:
00206                             m_showOnboardeeSsidList = false;
00207                             break;
00208                         default:
00209                             break;
00210                     }
00211                 }
00212                 RaisePropertyChangedEventAsync();
00213             }
00214         }
00215
00216         public Visibility OnboarderSsidListVisibility
00217         {
00218             get
00219             {
00220                 return m_onboarderSsidListVisibility;
00221             }
00222             private set
00223             {
00224                 m_onboarderSsidListVisibility = value;
00225                 if (m_manualSsidIsChecked != true)
00226                 {
00227                     switch (m_onboarderSsidListVisibility)
00228                     {
00229                         case Visibility.Visible:
00230                             m_showOnboarderSsidList = true;
00231                             break;
00232                         case Visibility.Collapsed:
00233                             m_showOnboarderSsidList = false;
00234                             break;
00235                         default:
00236                             break;
00237                     }
00238                 }
00239                 RaisePropertyChangedEventAsync();
00240             }
00241         }
00242
00243         public Visibility ManualSsidTextBoxVisibility
00244         {
00245             get
00246             {
00247                 return m_manualSsidTextBoxVisibility;
00248             }
00249             private set
00250             {
00251                 m_manualSsidTextBoxVisibility = value;
00252                 RaisePropertyChangedEventAsync();
00253             }
00254         }
00255
00256         public Visibility ConnectPanelVisibility
00257         {
00258             get
00259             {
00260                 return m_connectPanelVisibility;
00261             }
00262             private set
00263             {
00264                 m_connectPanelVisibility = value;
00265                 RaisePropertyChangedEventAsync();
00266             }
00267         }
00268
00269         public Visibility OnboardingConfigurationVisibility
00270         {
00271             get
00272             {
00273                 return m_onboardingConfigurationVisibility;
00274             }
00275             private set
00276             {
00277                 m_onboardingConfigurationVisibility = value;
00278                 RaisePropertyChangedEventAsync();
00279             }
00280         }
00281
00282         public Visibility ScanPanelVisibility
00283         {
00284             get
00285             {
00286                 return m_scanPanelVisibility;
00287             }
00288             private set
00289             {
00290                 m_scanPanelVisibility = value;
00291                 RaisePropertyChangedEventAsync();
00292             }
00293         }
00294
00295         public Visibility WiFiAdapterListVisibility
00296         {
00297             get
00298             {
00299                 return m_wiFiAdapterListVisibility;
00300             }
00301             private set
00302             {
00303                 m_wiFiAdapterListVisibility = value;
00304                 RaisePropertyChangedEventAsync();
00305             }
00306         }
00307
00308         public Visibility AuthenticationVisibility
00309         {
00310             get
00311             {
00312                 return m_authenticationVisibility;
00313             }
00314             private set
00315             {
00316                 m_authenticationVisibility = value;
00317                 RaisePropertyChangedEventAsync();
00318             }
00319         }
00320
00321         public bool? ManualSsidIsChecked
00322         {
00323             get
00324             {
00325                 return m_manualSsidIsChecked;
00326             }
00327             set
00328             {
00329                 m_manualSsidIsChecked = value;
00330                 if (m_manualSsidIsChecked == true)
00331                 {
00332                     OnboardeeSsidListVisibility = Visibility.Collapsed;
00333                     OnboarderSsidListVisibility = Visibility.Collapsed;
00334                     ManualSsidTextBoxVisibility = Visibility.Visible;
00335                 }
00336                 else
00337                 {
00338                     if (m_showOnboardeeSsidList)
00339                     {
00340                         OnboardeeSsidListVisibility = Visibility.Visible;
00341                     }
00342                     else
00343                     {
00344                         OnboarderSsidListVisibility = Visibility.Visible;
00345                     }
00346                     ManualSsidTextBoxVisibility = Visibility.Collapsed;
00347                 }
00348             }
00349         }
00350
00351         public bool? OnboardingProducerIsChecked
00352         {
00353             get
00354             {
00355                 return m_onboardingProducerIsChecked;
00356             }
00357             set
00358             {
00359                 m_onboardingProducerIsChecked = value;
00360                 if (m_onboardingProducerIsChecked == true)
00361                 {
00362                     ResetControls();
00363                     ScenarioCleanup();
00364                 }
00365             }
00366         }
00367
00368         public bool? PhysicalDeviceIsChecked
00369         {
00370             get
00371             {
00372                 return m_physicalDeviceIsChecked;
00373             }
00374             set
00375             {
00376                 m_physicalDeviceIsChecked = value;
00377                 if (m_physicalDeviceIsChecked == true)
00378                 {
00379                     ResetControls();
00380                     ScenarioCleanup();
00381                 }
00382             }
00383         }
00384
00385         public string SoftAPPassword
00386         {
00387             get
00388             {
00389                 return m_softAPPassword;
00390             }
00391             set
00392             {
00393                 if (value != m_softAPPassword)
00394                 {
00395                     m_softAPPassword = value;
00396                     RaisePropertyChangedEventAsync();
00397                 }
00398             }
00399         }
00400
00401         public string OnboardingPassword
00402         {
00403             get
00404             {
00405                 return m_onboardingPassword;
00406             }
00407             set
00408             {
00409                 if (value != m_onboardingPassword)
00410                 {
00411                     m_onboardingPassword = value;
00412                     RaisePropertyChangedEventAsync();
00413                 }
00414             }
00415         }
00416
00417         public string ManualSsid
00418         {
00419             get
00420             {
00421                 return m_manualSsid;
00422             }
00423             set
00424             {
00425                 m_manualSsid = value;
00426             }
00427         }
00428
00429         public string EnteredKey
00430         {
00431             get
00432             {
00433                 return m_key;
00434             }
00435             set
00436             {
00437                 if (value != m_key)
00438                 {
00439                     m_key = value;
00440                     RaisePropertyChangedEventAsync();
00441                 }
00442             }
00443         }
00444
00445         public string[] AuthTypeArray
00446         {
00447             get
00448             {
00449                 return Enum.GetNames(typeof(OnboardingAuthenticationType));
00450             }
00451         }
00452
00453         public OnboardingAuthenticationType SelectedAuthType
00454         {
00455             get
00456             {
00457                 return m_selectedAuthType;
00458             }
00459             set
00460             {
00461                 if (value != m_selectedAuthType)
00462                 {
00463                     m_selectedAuthType = value;
00464                     RaisePropertyChangedEventAsync();
00465                 }
00466             }
00467         }
00468
00469         public ICommand StartScan
00470         {
00471             get
00472             {
00473                 return new RelayCommand((object args) =>
00474                 {
00475                     StartScanning();
00476                 });
00477             }
00478         }
00479
00480         public ICommand Connect
00481         {
00482             get
00483             {
00484                 return new RelayCommand((object args) =>
00485                 {
00486                     ConnectToSoftAPAsync();
00487                 });
00488             }
00489         }
00490
00491         public ICommand AttemptAuthentication
00492         {
00493             get
00494             {
00495                 return new RelayCommand((object args) =>
00496                 {
00497                     Authenticate();
00498                 });
00499             }
00500         }
00501
00502         public ICommand Onboard
00503         {
00504             get
00505             {
00506                 return new RelayCommand((object args) =>
00507                 {
00508                     GetOnboardingConfiguration();
00509                 });
00510             }
00511         }
00512
00513         public void ScenarioCleanup()
00514         {
00515             DisposeConsumer();
00516             DisposeWatcher();
00517
00518             if (m_busAttachment != null)
00519             {
00520                 m_busAttachment.CredentialsRequested -= BusAttachment_CredentialsRequested;
00521                 m_busAttachment.AuthenticationComplete -= BusAttachment_AuthenticationComplete;
00522                 m_busAttachment.StateChanged -= BusAttachment_StateChanged;
00523                 m_busAttachment.Disconnect();
00524                 m_busAttachment = null;
00525             }
00526         }
00527
00528         protected async void RaisePropertyChangedEventAsync([CallerMemberName] string name = "")
00529         {
00530             await m_dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00531             {
00532                 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
00533             });
00534         }
00535
00536         private void StartScanning()
00537         {
00538             if (m_onboardingProducerIsChecked == true)
00539             {
00540                 ScanForOnboardingInterfaces();
00541             }
00542             else if (m_physicalDeviceIsChecked == true)
00543             {
00544                 ScanForWiFiAdaptersAsync();
00545             }
00546         }
00547
00548         private async void ScanForWiFiAdaptersAsync()
00549         {
00550             if (m_wiFiAdapter == null)
00551             {
00552                 UpdateStatusAsync("Requesting WiFi access...", NotifyType.StatusMessage);
00553                 WiFiAccessStatus accessStatus = await WiFiAdapter.RequestAccessAsync();
00554                 if (accessStatus != WiFiAccessStatus.Allowed)
00555                 {
00556                     UpdateStatusAsync("WiFi access denied.", NotifyType.ErrorMessage);
00557                 }
00558                 else
00559                 {
00560                     m_wiFiAdapterList = await WiFiAdapter.FindAllAdaptersAsync();
00561                     if (m_wiFiAdapterList.Count > 0)
00562                     {
00563                         for (int i = 0; i < m_wiFiAdapterList.Count; i++)
00564                         {
00565                             m_wiFiAdapterDisplayNames.Add(string.Format("Adapter {0}", (i + 1)));
00566                         }
00567                         WiFiAdapterListVisibility = Visibility.Visible;
00568                         UpdateStatusAsync("Please select a WiFi adapter.", NotifyType.StatusMessage);
00569                     }
00570                     else
00571                     {
00572                         UpdateStatusAsync("No WiFi adapters detected on this machine.", NotifyType.ErrorMessage);
00573                     }
00574                 }
00575             }
00576         }
00577
00578         private async void ScanForWiFiNetworksAsync()
00579         {
00580             if (m_selectedWiFiAdapterIndex >= 0)
00581             {
00582                 m_wiFiAdapter = m_wiFiAdapterList[m_selectedWiFiAdapterIndex];
00583             }
00584
00585             if (m_wiFiAdapter != null)
00586             {
00587                 UpdateConnectivityStatusAsync();
00588                 NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;
00589                 UpdateStatusAsync("Scanning for available WiFi networks...", NotifyType.StatusMessage);
00590                 await m_wiFiAdapter.ScanAsync();
00591                 m_onboarderNetworkList.Clear();
00592                 if (m_wiFiAdapter.NetworkReport.AvailableNetworks.Count > 0)
00593                 {
00594                     foreach (WiFiAvailableNetwork network in m_wiFiAdapter.NetworkReport.AvailableNetworks)
00595                     {
00596                         m_onboarderNetworkList.Add(network);
00597                     }
00598                     ConnectPanelVisibility = Visibility.Visible;
00599                     UpdateStatusAsync("Scan complete. Please select a network to connect.", NotifyType.StatusMessage);
00600                 }
00601                 else
00602                 {
00603                     UpdateStatusAsync("Scan complete. No WiFi networks found.", NotifyType.ErrorMessage);
00604                 }
00605             }
00606         }
00607
00608         private async void UpdateConnectivityStatusAsync()
00609         {
00610             if (m_wiFiAdapter != null)
00611             {
00612                 ConnectionProfile connectedProfile = await m_wiFiAdapter.NetworkAdapter.GetConnectedProfileAsync();
00613                 if ((connectedProfile != null) && (!connectedProfile.ProfileName.Equals(m_savedProfileName)))
00614                 {
00615                     m_savedProfileName = connectedProfile.ProfileName;
00616                 }
00617                 else if ((connectedProfile == null) && (m_savedProfileName != null))
00618                 {
00619                     UpdateStatusAsync("WiFi adapter disconnected from: " + m_savedProfileName, NotifyType.StatusMessage);
00620                     m_savedProfileName = null;
00621                 }
00622             }
00623         }
00624
00625         private void NetworkInformation_NetworkStatusChanged(object sender)
00626         {
00627             UpdateConnectivityStatusAsync();
00628         }
00629
00630         private async void ConnectToSoftAPAsync()
00631         {
00632             if (m_wiFiAdapter != null)
00633             {
00634                 if (m_selectedSoftAPNetwork == null)
00635                 {
00636                     UpdateStatusAsync("Network not selected. Please select a network.", NotifyType.ErrorMessage);
00637                 }
00638                 else
00639                 {
00640                     UpdateStatusAsync(string.Format("Attempting to connect to {0}...", m_selectedSoftAPNetwork.Ssid), NotifyType.StatusMessage);
00641                     WiFiConnectionResult result = null;
00642                     if (m_selectedSoftAPNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211)
00643                     {
00644                         result = await m_wiFiAdapter.ConnectAsync(m_selectedSoftAPNetwork, WiFiReconnectionKind.Manual);
00645                     }
00646                     else
00647                     {
00648                         if (string.IsNullOrWhiteSpace(m_softAPPassword))
00649                         {
00650                             UpdateStatusAsync("No password entered.", NotifyType.ErrorMessage);
00651                         }
00652                         else
00653                         {
00654                             PasswordCredential credential = new PasswordCredential();
00655                             credential.Password = m_softAPPassword;
00656                             result = await m_wiFiAdapter.ConnectAsync(m_selectedSoftAPNetwork, WiFiReconnectionKind.Manual, credential);
00657                         }
00658                         ClearPasswords();
00659                     }
00660
00661                     if (result != null)
00662                     {
00663                         if (result.ConnectionStatus == WiFiConnectionStatus.Success)
00664                         {
00665                             UpdateStatusAsync(string.Format("Successfully connected to {0}.", m_selectedSoftAPNetwork.Ssid), NotifyType.StatusMessage);
00666                             ScanForOnboardingInterfaces();
00667                         }
00668                         else
00669                         {
00670                             UpdateStatusAsync(string.Format("Failed to connect to {0} with error: {1}.", m_selectedSoftAPNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage);
00671                         }
00672                     }
00673                 }
00674             }
00675         }
00676
00677         private void ScanForOnboardingInterfaces()
00678         {
00679             ScenarioCleanup();
00680
00681             // Allow re-joining of a new session
00682             Interlocked.Exchange(ref m_onboardSessionAlreadyJoined, 0);
00683
00684             m_busAttachment = new AllJoynBusAttachment();
00685             m_busAttachment.StateChanged += BusAttachment_StateChanged;
00686             m_busAttachment.AuthenticationMechanisms.Clear();
00687
00688             // EcdhePsk authentication is deprecated as of the AllJoyn 16.04 release.
00689             // Newly added EcdheSpeke should be used instead. EcdhePsk authentication is
00690             // added here to maintain compatibility with devices running older AllJoyn versions.
00691             m_busAttachment.AuthenticationMechanisms.Add(AllJoynAuthenticationMechanism.EcdheNull);
00692             m_busAttachment.AuthenticationMechanisms.Add(AllJoynAuthenticationMechanism.EcdhePsk);
00693             m_busAttachment.AuthenticationMechanisms.Add(AllJoynAuthenticationMechanism.EcdheSpeke);
00694             m_busAttachment.AuthenticationComplete += BusAttachment_AuthenticationComplete;
00695             m_busAttachment.CredentialsRequested += BusAttachment_CredentialsRequested;
00696             m_watcher = AllJoynBusAttachment.GetWatcher(new List<string> { "org.alljoyn.Onboarding" });
00697             m_watcher.Added += Watcher_Added;
00698             UpdateStatusAsync("Searching for onboarding interface...", NotifyType.StatusMessage);
00699             m_watcher.Start();
00700         }
00701
00702         private void BusAttachment_StateChanged(AllJoynBusAttachment sender, AllJoynBusAttachmentStateChangedEventArgs args)
00703         {
00704             if (args.State == AllJoynBusAttachmentState.Disconnected)
00705             {
00706                 UpdateStatusAsync(string.Format("AllJoyn bus attachment has disconnected with AllJoyn error: 0x{0:X}.", args.Status), NotifyType.StatusMessage);
00707                 ResetControls();
00708             }
00709         }
00710
00711         private void BusAttachment_AuthenticationComplete(AllJoynBusAttachment sender, AllJoynAuthenticationCompleteEventArgs args)
00712         {
00713             if (args.Succeeded)
00714             {
00715                 UpdateStatusAsync("Authentication was successful.", NotifyType.StatusMessage);
00716             }
00717             else
00718             {
00719                 UpdateStatusAsync("Authentication failed.", NotifyType.ErrorMessage);
00720             }
00721
00722             EnteredKey = "";
00723             AuthenticationVisibility = Visibility.Collapsed;
00724         }
00725
00726         private async void BusAttachment_CredentialsRequested(AllJoynBusAttachment sender, AllJoynCredentialsRequestedEventArgs args)
00727         {
00728             Windows.Foundation.Deferral credentialsDeferral = args.GetDeferral();
00729
00730             if ((args.Credentials.AuthenticationMechanism == AllJoynAuthenticationMechanism.EcdhePsk) ||
00731                 (args.Credentials.AuthenticationMechanism == AllJoynAuthenticationMechanism.EcdheSpeke))
00732             {
00733                 m_authenticateClicked = new TaskCompletionSource<bool>();
00734                 AuthenticationVisibility = Visibility.Visible;
00735
00736                 UpdateStatusAsync("Please enter the key.", NotifyType.StatusMessage);
00737                 await m_authenticateClicked.Task;
00738                 m_authenticateClicked = null;
00739
00740                 if (!string.IsNullOrEmpty(m_key))
00741                 {
00742                     args.Credentials.PasswordCredential.Password = m_key;
00743                 }
00744                 else
00745                 {
00746                     UpdateStatusAsync("Please enter a key.", NotifyType.ErrorMessage);
00747                 }
00748             }
00749             else if (args.Credentials.AuthenticationMechanism == AllJoynAuthenticationMechanism.EcdheNull)
00750             {
00751             }
00752             else
00753             {
00754                 UpdateStatusAsync("Unexpected authentication mechanism.", NotifyType.ErrorMessage);
00755             }
00756
00757             credentialsDeferral.Complete();
00758         }
00759
00760         private async void Watcher_Added(DeviceWatcher sender, DeviceInformation args)
00761         {
00762             // This demo supports a single onboarding producer, if there are multiple onboarding producers found, then they are ignored.
00763             // Another approach would be to create a list of all producers found and then allow the user to choose the one they want
00764             bool bAlreadyJoined = (Interlocked.CompareExchange(ref m_onboardSessionAlreadyJoined, 1, 0) == 1);
00765             if (bAlreadyJoined)
00766             {
00767                 return;
00768             }
00769
00770             DisposeConsumer();
00771             UpdateStatusAsync("Joining session...", NotifyType.StatusMessage);
00772             m_consumer = await OnboardingConsumer.FromIdAsync(args.Id, m_busAttachment);
00773
00774             if (m_consumer != null)
00775             {
00776                 m_consumer.Session.Lost += Consumer_SessionLost;
00777                 GetOnboardeeNetworkListAsync();
00778             }
00779             else
00780             {
00781                 UpdateStatusAsync("Attempt to join session failed.", NotifyType.ErrorMessage);
00782             }
00783         }
00784
00785         private void Consumer_SessionLost(AllJoynSession sender, AllJoynSessionLostEventArgs args)
00786         {
00787             UpdateStatusAsync(string.Format("AllJoyn session with the onboardee lost due to {0}.", args.Reason.ToString()), NotifyType.StatusMessage);
00788             DisposeConsumer();
00789             ResetControls();
00790         }
00791
00792         private void Authenticate()
00793         {
00794             if (string.IsNullOrWhiteSpace(m_key))
00795             {
00796                 UpdateStatusAsync("Please enter a key.", NotifyType.ErrorMessage);
00797             }
00798             else
00799             {
00800                 if (m_authenticateClicked != null)
00801                 {
00802                     UpdateStatusAsync("Authenticating...", NotifyType.StatusMessage);
00803                     m_authenticateClicked.SetResult(true);
00804                 }
00805             }
00806         }
00807
00808         private async void GetOnboardeeNetworkListAsync()
00809         {
00810             UpdateStatusAsync("Requesting network list from the onboardee...", NotifyType.StatusMessage);
00811             OnboardingGetScanInfoResult getScanResult = await m_consumer.GetScanInfoAsync();
00812             if (getScanResult.Status == AllJoynStatus.Ok)
00813             {
00814                 if (getScanResult.ScanList.Count > 0)
00815                 {
00816                     await m_dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00817                     {
00818                         foreach (OnboardingScanListItem item in getScanResult.ScanList)
00819                         {
00820                             m_onboardeeNetworkList.Add(item);
00821                         }
00822                     });
00823
00824                     ShowOnboardeeSsidList();
00825                     UpdateStatusAsync(string.Format("{0} network(s) returned. Scan age: {1} minutes.", getScanResult.ScanList.Count, getScanResult.Age), NotifyType.StatusMessage);
00826                 }
00827                 else
00828                 {
00829                     // No networks returned by the onboardee. Provide the user option to configure onboardee with networks visible from onboarder.
00830                     UpdateStatusAsync("Please select a network or enter one manually.", NotifyType.StatusMessage);
00831                     ShowOnboarderSsidList();
00832                 }
00833             }
00834             else
00835             {
00836                 // Unable to get scan information from the onboardee. Provide the user option to configure onboardee with networks visible from onboarder.
00837                 UpdateStatusAsync("Please select a network or enter one manually.", NotifyType.StatusMessage);
00838                 ShowOnboarderSsidList();
00839             }
00840             OnboardingConfigurationVisibility = Visibility.Visible;
00841         }
00842
00843         private void GetOnboardingConfiguration()
00844         {
00845             string configureSsid = null;
00846
00847             if (m_manualSsidIsChecked == true)
00848             {
00849                 if (!string.IsNullOrWhiteSpace(m_manualSsid))
00850                 {
00851                     configureSsid = m_manualSsid;
00852                 }
00853             }
00854             else
00855             {
00856                 if (m_showOnboardeeSsidList)
00857                 {
00858                     if (m_selectedOnboardeeNetwork != null)
00859                     {
00860                         configureSsid = m_selectedOnboardeeNetwork.Value1;
00861                     }
00862                 }
00863                 else
00864                 {
00865                     if (m_selectedOnboarderNetwork != null)
00866                     {
00867                         configureSsid = m_selectedOnboarderNetwork.Ssid;
00868                     }
00869                 }
00870             }
00871
00872             AttemptOnboardingAsync(configureSsid, m_onboardingPassword, (short)m_selectedAuthType);
00873         }
00874
00875         private async void AttemptOnboardingAsync(string ssid, string password, short authType)
00876         {
00877             if (string.IsNullOrWhiteSpace(ssid))
00878             {
00879                 UpdateStatusAsync("No SSID selected. Please select a network or manually enter SSID.", NotifyType.ErrorMessage);
00880             }
00881             else
00882             {
00883                 UpdateStatusAsync("Attempting to configure onboardee...", NotifyType.StatusMessage);
00884
00885                 OnboardingConfigureWiFiResult configureWifiResult = await m_consumer.ConfigureWiFiAsync(ssid, ConvertUtf8ToHex(password), authType);
00886                 if (configureWifiResult.Status == AllJoynStatus.Ok)
00887                 {
00888                     UpdateStatusAsync("Onboardee sucessfully configured.", NotifyType.StatusMessage);
00889                     if (configureWifiResult.Status2 == (short)ConfigureWiFiResultStatus.Concurrent)
00890                     {
00891                         // The Onboardee has indicated that it will attempt to connect to the desired AP concurrently, while the SoftAP is enabled. In this case,
00892                         // the Onboarder application must wait for the ConnectionResult signal to arrive over the AllJoyn session established over the SoftAP link.
00893                         // If the Onboardee does not connect to the desired AP concurrently, then there is no guaranteed way for the Onboarder application to find
00894                         // out if the connection attempt was successful or not. In the NotConcurrent connection attempt, if the Onboardee fails to connect to
00895                         // the desired AP, the Onboarder application will have to again start over with scanning and connecting to the Onboardee SoftAP.
00896                         // For more information please visit http://go.microsoft.com/fwlink/?LinkId=817239
00897                         m_consumer.Signals.ConnectionResultReceived += Signals_ConnectionResultReceived;
00898                     }
00899                     AttemptConnectionAsync();
00900                 }
00901                 else
00902                 {
00903                     UpdateStatusAsync(string.Format("Attempt to configure WiFi failed with AllJoyn error: 0x{0:X}.", configureWifiResult.Status), NotifyType.ErrorMessage);
00904                 }
00905             }
00906             ClearPasswords();
00907         }
00908
00909         private static string ConvertUtf8ToHex(string inputString)
00910         {
00911             if (string.IsNullOrEmpty(inputString))
00912             {
00913                 return string.Empty;
00914             }
00915             else
00916             {
00917                 var tempBuffer = CryptographicBuffer.ConvertStringToBinary(inputString, BinaryStringEncoding.Utf8);
00918                 var hexString = CryptographicBuffer.EncodeToHexString(tempBuffer);
00919                 return hexString;
00920             }
00921         }
00922
00923         private async void AttemptConnectionAsync()
00924         {
00925             OnboardingConnectResult connectResult = await m_consumer.ConnectAsync();
00926             UpdateStatusAsync("Connect request sent.", NotifyType.StatusMessage);
00927         }
00928
00929         private void Signals_ConnectionResultReceived(OnboardingSignals sender, OnboardingConnectionResultReceivedEventArgs args)
00930         {
00931             if (args.Arg.Value1 == (short)ConnectionResultCode.Validated)
00932             {
00933                 UpdateStatusAsync("Onboarding successful.", NotifyType.StatusMessage);
00934             }
00935             else
00936             {
00937                 UpdateStatusAsync(string.Format("Connection attempt failed with result code: {0} and message: {1}.", ((ConnectionResultCode)args.Arg.Value1).ToString(), args.Arg.Value2), NotifyType.ErrorMessage);
00938             }
00939         }
00940
00941         private void ClearPasswords()
00942         {
00943             SoftAPPassword = "";
00944             OnboardingPassword = "";
00945         }
00946
00947         private void ShowOnboardeeSsidList()
00948         {
00949             if (m_manualSsidIsChecked == true)
00950             {
00951                 m_showOnboardeeSsidList = true;
00952                 m_showOnboarderSsidList = false;
00953             }
00954             else
00955             {
00956                 OnboardeeSsidListVisibility = Visibility.Visible;
00957                 OnboarderSsidListVisibility = Visibility.Collapsed;
00958             }
00959         }
00960
00961         private void ShowOnboarderSsidList()
00962         {
00963             if (m_manualSsidIsChecked == true)
00964             {
00965                 m_showOnboardeeSsidList = false;
00966                 m_showOnboarderSsidList = true;
00967             }
00968             else
00969             {
00970                 OnboardeeSsidListVisibility = Visibility.Collapsed;
00971                 OnboarderSsidListVisibility = Visibility.Visible;
00972             }
00973         }
00974
00975         private void ResetControls()
00976         {
00977             ScanPanelVisibility = Visibility.Visible;
00978             WiFiAdapterListVisibility = Visibility.Collapsed;
00979             ConnectPanelVisibility = Visibility.Collapsed;
00980             AuthenticationVisibility = Visibility.Collapsed;
00981             OnboardingConfigurationVisibility = Visibility.Collapsed;
00982         }
00983
00984         private void DisposeConsumer()
00985         {
00986             if (m_consumer != null)
00987             {
00988                 m_consumer.Session.Lost -= Consumer_SessionLost;
00989                 m_consumer.Dispose();
00990                 m_consumer = null;
00991             }
00992         }
00993
00994         private void DisposeWatcher()
00995         {
00996             if (m_watcher != null)
00997             {
00998                 m_watcher.Added -= Watcher_Added;
00999                 m_watcher.Stop();
01000                 m_watcher = null;
01001             }
01002         }
01003
01004         private async void UpdateStatusAsync(string status, NotifyType statusType)
01005         {
01006             await m_dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
01007             {
01008                 m_rootPage.NotifyUser(status, statusType);
01009             });
01010         }
01011     }
01012 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_BankCards Member List

This is the complete list of members for Scenario1_BankCards, including all inherited members.
_claimedReader | Scenario1_BankCards | [private]
_reader | Scenario1_BankCards | [private]
ClaimReader() | Scenario1_BankCards | [inline, private]
CreateDefaultMagneticStripeReaderObject() | Scenario1_BankCards | [inline, private]
OnBankCardDataReceived(object sender, MagneticStripeReaderBankCardDataReceivedEventArgs args) | Scenario1_BankCards | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_BankCards | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_BankCards | [inline, protected]
OnReleaseDeviceRequested(object sender, ClaimedMagneticStripeReader args) | Scenario1_BankCards | [inline, private]
ResetTheScenarioState() | Scenario1_BankCards | [inline, private]
rootPage | Scenario1_BankCards | [private]
Scenario1_BankCards() | Scenario1_BankCards | [inline]
ScenarioEndReadButton_Click(object sender, RoutedEventArgs e) | Scenario1_BankCards | [inline, private]
ScenarioStartReadButton_Click(object sender, RoutedEventArgs e) | Scenario1_BankCards | [inline, private]
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DefaultCloseCommand Member List

This is the complete list of members for DefaultCloseCommand, including all inherited members.
DefaultCloseCommand() | DefaultCloseCommand | [inline]
DefaultCloseCommandButton_Click(object sender, RoutedEventArgs e) | DefaultCloseCommand | [inline, private]
rootPage | DefaultCloseCommand | [private]
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/App.h Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

App.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "DeviceResources.h"
00016 #include "CustomVertexShaderMain.h"
00017
00018 namespace CustomVertexShader
00019 {
00020     // Main entry point for our app. Connects the app with the Windows shell and handles application lifecycle events.
00021     ref class App sealed : public Windows::ApplicationModel::Core::IFrameworkView
00022     {
00023     public:
00024         App();
00025
00026         // IFrameworkView Methods.
00027         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00028         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00029         virtual void Load(Platform::String^ entryPoint);
00030         virtual void Run();
00031         virtual void Uninitialize();
00032
00033     protected:
00034         // Application lifecycle event handlers.
00035         void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00036         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00037         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00038
00039         // Window event handlers.
00040         void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args);
00041         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00042         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00043
00044         // DisplayInformation event handlers.
00045         void OnDpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00046         void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00047         void OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00048
00049         // Input and gesture event handlers.
00050         void OnPointerMoved(
00051             _In_ Windows::UI::Core::CoreWindow^ sender,
00052             _In_ Windows::UI::Core::PointerEventArgs^ args
00053             );
00054
00055         void OnPointerPressed(
00056             _In_ Windows::UI::Core::CoreWindow^ sender,
00057             _In_ Windows::UI::Core::PointerEventArgs^ args
00058             );
00059
00060         void OnPointerReleased(
00061             _In_ Windows::UI::Core::CoreWindow^ sender,
00062             _In_ Windows::UI::Core::PointerEventArgs^ args
00063             );
00064
00065         void OnPointerWheelChanged(
00066             _In_ Windows::UI::Core::CoreWindow^ sender,
00067             _In_ Windows::UI::Core::PointerEventArgs^ args
00068             );
00069
00070         void OnManipulationUpdated(
00071             _In_ Windows::UI::Input::GestureRecognizer^ sender,
00072             _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^ args
00073             );
00074
00075     private:
00076         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00077         std::unique_ptr<CustomVertexShaderMain> m_main;
00078         bool m_windowClosed;
00079         bool m_windowVisible;
00080         Windows::UI::Input::GestureRecognizer^ m_gestureRecognizer;
00081     };
00082 }
00083
00084 ref class Direct3DApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00085 {
00086 public:
00087     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00088 };
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomDevicePickerFilter Member List

This is the complete list of members for CustomDevicePickerFilter, including all inherited members.
supportedDeviceSelectors | CustomDevicePickerFilter | [private]
SupportedDeviceSelectors | CustomDevicePickerFilter |
ToString() | CustomDevicePickerFilter | [inline]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/App.xaml.cpp Source File

  • WindowsAudioSession
  • cpp

App.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014
00015 using namespace SDKSample;
00016
00017 using namespace Platform;
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::ApplicationModel::Activation;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Controls::Primitives;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::UI::Xaml::Input;
00027 using namespace Windows::UI::Xaml::Interop;
00028 using namespace Windows::UI::Xaml::Media;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
00032
00033 /// <summary>
00034 /// Initializes the singleton application object.  This is the first line of authored code
00035 /// executed, and as such is the logical equivalent of main() or WinMain().
00036 /// </summary>
00037 App::App()
00038 {
00039     InitializeComponent();
00040     Suspending += ref new Windows::UI::Xaml::SuspendingEventHandler(this, &SDKSample::App::OnSuspending);
00041 }
00042
00043 /// <summary>
00044 /// Invoked when the application is launched normally by the end user.  Other entry points
00045 /// will be used such as when the application is launched to open a specific file.
00046 /// </summary>
00047 /// <param name="e">Details about the launch request and process.</param>
00048 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
00049 {
00050 #if _DEBUG
00051     // Show graphics profiling information while debugging.
00052     if (IsDebuggerPresent())
00053     {
00054         // Display the current frame rate counters
00055         DebugSettings->EnableFrameRateCounter = false;
00056     }
00057 #endif
00058
00059     auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00060
00061     // Do not repeat app initialization when the Window already has content,
00062     // just ensure that the window is active
00063     if (rootFrame == nullptr)
00064     {
00065         // Create a Frame to act as the navigation context and associate it with
00066         // a SuspensionManager key
00067         rootFrame = ref new Frame();
00068
00069         // Set the default language
00070         rootFrame->Language = Windows::Globalization::ApplicationLanguages::Languages->GetAt(0);
00071
00072         rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed);
00073
00074         if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
00075         {
00076             // TODO: Restore the saved session state only when appropriate, scheduling the
00077             // final launch steps after the restore is complete
00078         }
00079
00080         if (rootFrame->Content == nullptr)
00081         {
00082             // When the navigation stack isn't restored navigate to the first page,
00083             // configuring the new page by passing required information as a navigation
00084             // parameter
00085             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00086         }
00087         // Place the frame in the current Window
00088         Window::Current->Content = rootFrame;
00089         // Ensure the current window is active
00090         Window::Current->Activate();
00091     }
00092     else
00093     {
00094         if (rootFrame->Content == nullptr)
00095         {
00096             // When the navigation stack isn't restored navigate to the first page,
00097             // configuring the new page by passing required information as a navigation
00098             // parameter
00099             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00100         }
00101         // Ensure the current window is active
00102         Window::Current->Activate();
00103     }
00104 }
00105
00106 /// <summary>
00107 /// Invoked when application execution is being suspended.  Application state is saved
00108 /// without knowing whether the application will be terminated or resumed with the contents
00109 /// of memory still intact.
00110 /// </summary>
00111 /// <param name="sender">The source of the suspend request.</param>
00112 /// <param name="e">Details about the suspend request.</param>
00113 void App::OnSuspending(Object^ /* sender */, SuspendingEventArgs^ /* e */)
00114 {
00115     //TODO: Save application state and stop any background activity
00116 }
00117
00118
00119 /// <summary>
00120 /// Invoked when Navigation to a certain page fails
00121 /// </summary>
00122 /// <param name="sender">The Frame which failed navigation</param>
00123 /// <param name="e">Details about the navigation failure</param>
00124 void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e)
00125 {
00126     throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name);
00127 }
Generated on Fri Nov 15 2024 22:16:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLOutOfProcessWinRTComponent/cpp/cpp/SampleConfiguration.cpp Source File

  • WRLOutOfProcessWinRTComponent
  • cpp
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     // The format here is the following:
00012     { "Using Custom Components",                                     "SDKTemplate.WRLOutOfProcessWinRTComponent.OvenClient" },
00013     { "Using Custom Components (Implemented using WRL)",             "SDKTemplate.WRLOutOfProcessWinRTComponent.OvenClientWRL" },
00014     { "Handling Windows Runtime Exceptions",                         "SDKTemplate.WRLOutOfProcessWinRTComponent.CustomException" },
00015     { "Handling Windows Runtime Exceptions (Implemented using WRL)", "SDKTemplate.WRLOutOfProcessWinRTComponent.CustomExceptionWRL" }
00016 };
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ExtendedExecution/cpp/Scenario1_UnspecifiedReason.xaml.cpp Source File

  • ExtendedExecution
  • cpp

Scenario1_UnspecifiedReason.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_UnspecifiedReason.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Concurrency;
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::ApplicationModel::Background;
00021 using namespace Windows::ApplicationModel::ExtendedExecution;
00022 using namespace Windows::System::Threading;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 UnspecifiedReason::UnspecifiedReason()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 void UnspecifiedReason::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00034 {
00035     ClearExtendedExecution();
00036 }
00037
00038 void UnspecifiedReason::ClearExtendedExecution()
00039 {
00040     if (session)
00041     {
00042         session->Revoked -= sessionRevokedToken;
00043         delete session;
00044         session = nullptr;
00045     }
00046
00047     if (periodicTimer)
00048     {
00049         periodicTimer->Cancel();
00050         periodicTimer = nullptr;
00051     }
00052 }
00053
00054 void UnspecifiedReason::UpdateUI()
00055 {
00056     if (session == nullptr)
00057     {
00058         Status->Text = "Not requested";
00059         RequestButton->IsEnabled = true;
00060         CloseButton->IsEnabled = false;
00061     }
00062     else
00063     {
00064         Status->Text = "Requested";
00065         RequestButton->IsEnabled = false;
00066         CloseButton->IsEnabled = true;
00067     }
00068 }
00069
00070 void UnspecifiedReason::BeginExtendedExecution()
00071 {
00072     // The previous Extended Execution must be closed before a new one can be requested.
00073     // This code is redundant here because the sample doesn't allow a new extended
00074     // execution to begin until the previous one ends, but we leave it here for illustration.
00075     ClearExtendedExecution();
00076
00077     auto newSession = ref new ExtendedExecutionSession();
00078     newSession->Reason = ExtendedExecutionReason::Unspecified;
00079     newSession->Description = "Raising periodic toasts";
00080     sessionRevokedToken = newSession->Revoked += ref new TypedEventHandler<Object^, ExtendedExecutionRevokedEventArgs^>(
00081         this, &UnspecifiedReason::SessionRevoked);
00082     create_task(newSession->RequestExtensionAsync()).then([this, newSession](ExtendedExecutionResult result)
00083     {
00084         switch (result)
00085         {
00086         case ExtendedExecutionResult::Allowed:
00087             rootPage->NotifyUser("Extended execution allowed.", NotifyType::StatusMessage);
00088             session = newSession;
00089             startTime = time(nullptr);
00090             periodicTimer = ThreadPoolTimer::CreatePeriodicTimer(ref new TimerElapsedHandler(this, &UnspecifiedReason::OnTimer), Helpers::TimeSpanFromSeconds(10));
00091             break;
00092
00093         default:
00094         case ExtendedExecutionResult::Denied:
00095             rootPage->NotifyUser("Extended execution denied.", NotifyType::ErrorMessage);
00096             delete newSession;
00097             break;
00098         }
00099         UpdateUI();
00100     }, task_continuation_context::get_current_winrt_context());
00101 }
00102
00103 void UnspecifiedReason::OnTimer(ThreadPoolTimer^ timer)
00104 {
00105     time_t now = time(nullptr);
00106     int runningTime = (int)(difftime(now, startTime) + 0.5);
00107     MainPage::DisplayToast("Extended execution has been active for " + runningTime.ToString() + " seconds");
00108 }
00109
00110 void UnspecifiedReason::EndExtendedExecution()
00111 {
00112     ClearExtendedExecution();
00113     UpdateUI();
00114 }
00115
00116 void UnspecifiedReason::SessionRevoked(Object^ sender, ExtendedExecutionRevokedEventArgs^ args)
00117 {
00118     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00119     {
00120         switch (args->Reason)
00121         {
00122         case ExtendedExecutionRevokedReason::Resumed:
00123             rootPage->NotifyUser("Extended execution revoked due to returning to foreground.", NotifyType::StatusMessage);
00124             break;
00125
00126         case ExtendedExecutionRevokedReason::SystemPolicy:
00127             rootPage->NotifyUser("Extended execution revoked due to system policy.", NotifyType::StatusMessage);
00128             break;
00129         }
00130
00131         EndExtendedExecution();
00132     }));
00133 }
Generated on Fri Nov 15 2024 22:19:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Inclinometer/cs/SampleConfiguration.cs Source File

  • Inclinometer
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using InclinometerCS;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Inclinometer";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title = "Data events", ClassType = typeof(InclinometerCS.Scenario1_DataEvents) },
00026             new Scenario() { Title = "Polling", ClassType = typeof(InclinometerCS.Scenario2_Polling) },
00027             new Scenario() { Title = "Calibration", ClassType = typeof(InclinometerCS.Scenario3_Calibration) }
00028         };
00029     }
00030
00031     public class Scenario
00032     {
00033         public string Title { get; set; }
00034         public Type ClassType { get; set; }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: InkAnalysis/cs/SampleConfiguration.cs Source File

  • InkAnalysis
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Ink Analysis C# Sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Scenario 1", ClassType=typeof(Scenario1)},
00025             new Scenario() { Title="Scenario 2", ClassType=typeof(Scenario2)},
00026         };
00027
00028         public void NavigateToScenario(Type type)
00029         {
00030             for (int index = 0; index < scenarios.Count; index++)
00031             {
00032                 if (scenarios[index].ClassType == type)
00033                 {
00034                     ScenarioControl.SelectedIndex = index;
00035                     break;
00036                 }
00037             }
00038         }
00039     }
00040
00041     public class Scenario
00042     {
00043         public string Title { get; set; }
00044         public Type ClassType { get; set; }
00045     }
00046 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Projection/cpp/Scenario2.xaml.h Source File

  • Projection
  • cpp

Scenario2.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKSample
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario2 sealed
00021     {
00022     public:
00023         Scenario2();
00024     protected:
00025         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00026         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00027     private:
00028         int thisViewId;
00029         void StartProjecting_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00030         void RequestAndStartProjecting_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00031         void OnProjectionDisplayAvailableChanged(Platform::Object^ sender, Platform::Object^ e);
00032         void UpdateTextBlock(bool screenAvailable);
00033         Windows::Foundation::EventRegistrationToken displayChangeToken;
00034         Windows::UI::Core::CoreDispatcher^ dispatcher;
00035     };
00036 }
Generated on Fri Nov 15 2024 22:18:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cs/Scenario6_SecondaryTileNotification.xaml.cs Source File

  • SecondaryTiles
  • cs

Scenario6_SecondaryTileNotification.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using NotificationsExtensions;
00012 using NotificationsExtensions.Badges;
00013 using NotificationsExtensions.Tiles;
00014 using System;
00015 using Windows.UI.Notifications;
00016 using Windows.UI.StartScreen;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario6_SecondaryTileNotification : Page
00023     {
00024         MainPage rootPage = MainPage.Current;
00025
00026         public Scenario6_SecondaryTileNotification()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         private bool VerifyTileIsPinned()
00032         {
00033             if (SecondaryTile.Exists(MainPage.dynamicTileId))
00034             {
00035                 return true;
00036             }
00037             rootPage.NotifyUser(MainPage.dynamicTileId + " is not pinned.", NotifyType.ErrorMessage);
00038             return false;
00039         }
00040
00041         private async void PinLiveTile_Click(object sender, RoutedEventArgs e)
00042         {
00043             // Prepare the images for our tile to be pinned.
00044             Uri square150x150Logo = new Uri("ms-appx:///Assets/square150x150Tile-sdk.png");
00045             Uri wide310x150Logo = new Uri("ms-appx:///Assets/wide310x150Tile-sdk.png");
00046
00047             // During creation of the secondary tile, an application may set additional arguments on the tile that will be passed in during activation.
00048             // These arguments should be meaningful to the application. In this sample, we'll pass in the date and time the secondary tile was pinned.
00049             string tileActivationArguments = MainPage.dynamicTileId + " WasPinnedAt=" + DateTime.Now.ToLocalTime().ToString();
00050
00051             // Create a Secondary tile with all the required properties and sets perfered size to Wide310x150.
00052             SecondaryTile secondaryTile = new SecondaryTile(MainPage.dynamicTileId,
00053                                                             "A Live Secondary Tile",
00054                                                             tileActivationArguments,
00055                                                             square150x150Logo,
00056                                                             TileSize.Wide310x150);
00057
00058             // Adding the wide tile logo.
00059             secondaryTile.VisualElements.Wide310x150Logo = wide310x150Logo;
00060
00061             // The display of the app name can be controlled for each tile size.
00062             secondaryTile.VisualElements.ShowNameOnSquare150x150Logo = true;
00063             secondaryTile.VisualElements.ShowNameOnWide310x150Logo = true;
00064
00065             // Specify a foreground text value.
00066             // The tile background color is inherited from the parent unless a separate value is specified.
00067             secondaryTile.VisualElements.ForegroundText = ForegroundText.Dark;
00068
00069             // OK, the tile is created and we can now attempt to pin the tile.
00070             // Note that the status message is updated when the async operation to pin the tile completes.
00071             bool isPinned = await secondaryTile.RequestCreateForSelectionAsync(MainPage.GetElementRect(sender), Windows.UI.Popups.Placement.Below);
00072             if (isPinned)
00073             {
00074                 rootPage.NotifyUser("Secondary tile successfully pinned.", NotifyType.StatusMessage);
00075             }
00076             else
00077             {
00078                 rootPage.NotifyUser("Secondary tile not pinned.", NotifyType.ErrorMessage);
00079             }
00080         }
00081
00082         private void SendTileNotification_Click(object sender, RoutedEventArgs e)
00083         {
00084             if (VerifyTileIsPinned())
00085             {
00086                 var tileContent = new TileContent
00087                 {
00088                     Visual = new TileVisual
00089                     {
00090                         TileWide = new TileBinding
00091                         {
00092                             Content = new TileBindingContentAdaptive
00093                             {
00094                                 Children =
00095                                     {
00096                                         new AdaptiveText{ Text = "Sent to a secondary tile from NotificationsExtensions!", HintWrap = true },
00097                                     }
00098                             }
00099                         }
00100                     }
00101                 };
00102                 // Send the notification to the secondary tile by creating a secondary tile updater
00103                 TileUpdateManager.CreateTileUpdaterForSecondaryTile(MainPage.dynamicTileId).Update(new TileNotification(tileContent.GetXml()));
00104
00105                 rootPage.NotifyUser("Tile notification sent to " + MainPage.dynamicTileId, NotifyType.StatusMessage);
00106             }
00107         }
00108
00109         private void SendBadgeNotification_Click(object sender, RoutedEventArgs e)
00110         {
00111             if (VerifyTileIsPinned())
00112             {
00113                 BadgeNumericNotificationContent badgeContent = new BadgeNumericNotificationContent(6);
00114
00115                 // Send the notification to the secondary tile
00116                 BadgeUpdateManager.CreateBadgeUpdaterForSecondaryTile(MainPage.dynamicTileId).Update(new BadgeNotification(badgeContent.GetXml()));
00117
00118                 rootPage.NotifyUser("Badge notification sent to " + MainPage.dynamicTileId, NotifyType.StatusMessage);
00119             }
00120         }
00121
00122         private void SendTileNotificationWithStringManipulation_Click(object sender, RoutedEventArgs e)
00123         {
00124             if (VerifyTileIsPinned())
00125             {
00126                 string tileXmlString = "<tile>"
00127                                  + "<visual version='2'>"
00128                                  + "<binding template='TileWide310x150Text04' fallback='TileWideText04'>"
00129                                  + "<text id='1'>Send to a secondary tile from strings</text>"
00130                                  + "</binding>"
00131                                  + "<binding template='TileSquare150x150Text04' fallback='TileSquareText04'>"
00132                                  + "<text id='1'>Send to a secondary tile from strings</text>"
00133                                  + "</binding>"
00134                                  + "</visual>"
00135                                  + "</tile>";
00136
00137                 var tileDOM = new Windows.Data.Xml.Dom.XmlDocument();
00138                 tileDOM.LoadXml(tileXmlString);
00139                 TileNotification tile = new TileNotification(tileDOM);
00140
00141                 // Send the notification to the secondary tile by creating a secondary tile updater
00142                 TileUpdateManager.CreateTileUpdaterForSecondaryTile(MainPage.dynamicTileId).Update(tile);
00143
00144                 rootPage.NotifyUser("Tile notification sent to " + MainPage.dynamicTileId, NotifyType.StatusMessage);
00145             }
00146         }
00147
00148         private void SendBadgeNotificationWithStringManipulation_Click(object sender, RoutedEventArgs e)
00149         {
00150             if (VerifyTileIsPinned())
00151             {
00152                 string badgeXmlString = "<badge value='9'/>";
00153                 var badgeDOM = new Windows.Data.Xml.Dom.XmlDocument();
00154                 badgeDOM.LoadXml(badgeXmlString);
00155                 BadgeNotification badge = new BadgeNotification(badgeDOM);
00156
00157                 // Send the notification to the secondary tile
00158                 BadgeUpdateManager.CreateBadgeUpdaterForSecondaryTile(MainPage.dynamicTileId).Update(badge);
00159
00160                 rootPage.NotifyUser("Badge notification sent to " + MainPage.dynamicTileId, NotifyType.StatusMessage);
00161             }
00162         }
00163     }
00164 }
Generated on Fri Nov 15 2024 22:21:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleOrientationSensor/cpp/Scenario2_Polling.xaml.h Source File

  • SimpleOrientationSensor
  • cpp

Scenario2_Polling.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_Polling.xaml.h
00014 // Declaration of the Scenario2_Polling class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario2_Polling.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario2_Polling sealed
00030     {
00031     public:
00032         Scenario2_Polling();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036
00037     private:
00038         SDKTemplate::MainPage^ rootPage;
00039         Windows::Devices::Sensors::SimpleOrientationSensor^ sensor;
00040
00041         void DisplayOrientation(Windows::Devices::Sensors::SimpleOrientation orientation);
00042         void ScenarioGet(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043     };
00044 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlLite/cpp/Scenario1_XmlReader.xaml.cpp Source File

  • XmlLite
  • cpp

Scenario1_XmlReader.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_XmlReader.xaml.h"
00014
00015 using namespace SDKTemplate::XmlLite;
00016
00017 using namespace concurrency;
00018 using namespace Microsoft::WRL;
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Storage;
00023 using namespace Windows::Storage::Streams;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Controls::Primitives;
00027 using namespace Windows::UI::Xaml::Data;
00028 using namespace Windows::UI::Xaml::Input;
00029 using namespace Windows::UI::Xaml::Media;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00033
00034 Scenario1::Scenario1() : rootPage(MainPage::Current)
00035 {
00036     InitializeComponent();
00037 }
00038
00039 void Scenario1::ReadXmlClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00040 {
00041     Button^ b = safe_cast<Button^>(sender);
00042     StorageFolder^ installFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;
00043
00044     create_task(installFolder->GetFileAsync("Stocks.xml")).then([](StorageFile^ file)
00045     {
00046         return file->OpenAsync(FileAccessMode::Read);
00047     }).then([this](IRandomAccessStream^ readStream)
00048     {
00049         HRESULT hr = ReadXml(readStream);
00050         if (FAILED(hr))
00051         {
00052             XmlTextbox->Text = "Exception occured while reading the xml file, and the error code is " + hr.ToString();
00053             rootPage->NotifyUser("Exception occured!", NotifyType::ErrorMessage);
00054         }
00055     });
00056 }
00057
00058 HRESULT Scenario1::ReadXml(IRandomAccessStream^ randomAccessReadStream)
00059 {
00060     HRESULT hr;
00061     ComPtr<IStream> readStream;
00062     ComPtr<IXmlReader> reader;
00063     XmlNodeType nodeType;
00064
00065     ChkHr(::CreateStreamOverRandomAccessStream(randomAccessReadStream, IID_PPV_ARGS(&readStream)));
00066     ChkHr(::CreateXmlReader(IID_PPV_ARGS(&reader), nullptr));
00067     ChkHr(reader->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit));
00068     ChkHr(reader->SetInput(readStream.Get()));
00069
00070     // Reads until there are no more nodes.
00071     while (S_OK == (hr = reader->Read(&nodeType)))
00072     {
00073         PCWSTR prefix = nullptr;
00074         PCWSTR localName = nullptr;
00075         PCWSTR value = nullptr;
00076
00077         UINT prefixSize = 0;
00078         UINT localNameSize = 0;
00079         UINT valueSize = 0;
00080
00081         switch (nodeType)
00082         {
00083         case XmlNodeType_XmlDeclaration:
00084             XmlTextbox->Text += L"XmlDeclaration\n";
00085             ChkHr(ReadAttributes(reader.Get()));
00086             break;
00087
00088         case XmlNodeType_Element:
00089             ChkHr(reader->GetPrefix(&prefix, &prefixSize));
00090             ChkHr(reader->GetLocalName(&localName, &localNameSize));
00091             if (prefixSize > 0)
00092             {
00093                 XmlTextbox->Text += L"Element: ";
00094                 ChkHr(ConcatToOutput(prefix, prefixSize));
00095                 XmlTextbox->Text += L":";
00096                 ChkHr(ConcatToOutput(localName, localNameSize));
00097                 XmlTextbox->Text += L"\n";
00098             }
00099             else
00100             {
00101                 XmlTextbox->Text += L"Element: ";
00102                 ChkHr(ConcatToOutput(localName, localNameSize));
00103                 XmlTextbox->Text += L"\n";
00104             }
00105             ChkHr(ReadAttributes(reader.Get()));
00106
00107             if (reader->IsEmptyElement())
00108             {
00109                 XmlTextbox->Text += L" (empty)";
00110             }
00111             break;
00112
00113         case XmlNodeType_EndElement:
00114             ChkHr(reader->GetPrefix(&prefix, &prefixSize));
00115             ChkHr(reader->GetLocalName(&localName, &localNameSize));
00116             if (prefixSize > 0)
00117             {
00118                 XmlTextbox->Text += L"End Element: ";
00119                 ChkHr(ConcatToOutput(prefix, prefixSize));
00120                 XmlTextbox->Text += L":";
00121                 ChkHr(ConcatToOutput(localName, localNameSize));
00122                 XmlTextbox->Text += L"\n";
00123             }
00124             else
00125             {
00126                 XmlTextbox->Text += L"End Element: ";
00127                 ChkHr(ConcatToOutput(localName, localNameSize));
00128                 XmlTextbox->Text += L"\n";
00129             }
00130             break;
00131
00132         case XmlNodeType_Text:
00133             ChkHr(reader->GetValue(&value, &valueSize));
00134             XmlTextbox->Text += L"Text: >";
00135             ChkHr(ConcatToOutput(value, valueSize));
00136             XmlTextbox->Text += L"<\n";
00137             break;
00138
00139         case XmlNodeType_CDATA:
00140             ChkHr(reader->GetValue(&value, &valueSize));
00141             XmlTextbox->Text += L"CDATA: ";
00142             XmlTextbox->Text += ref new String(value, valueSize);
00143             XmlTextbox->Text += L"\n";
00144             break;
00145
00146         case XmlNodeType_ProcessingInstruction:
00147             ChkHr(reader->GetLocalName(&localName, &localNameSize));
00148             ChkHr(reader->GetValue(&value, &valueSize));
00149             XmlTextbox->Text += L"Processing Instruction name:";
00150             ChkHr(ConcatToOutput(localName, localNameSize));
00151             XmlTextbox->Text += L"value:";
00152             ChkHr(ConcatToOutput(value, valueSize));
00153             XmlTextbox->Text += L"\n";
00154             break;
00155
00156         case XmlNodeType_Comment:
00157             ChkHr(reader->GetValue(&value, &valueSize));
00158             XmlTextbox->Text += L"Comment: ";
00159             ChkHr(ConcatToOutput(value, valueSize));
00160             XmlTextbox->Text += L"\n";
00161             break;
00162
00163         case XmlNodeType_DocumentType:
00164             XmlTextbox->Text += L"DOCTYPE is not printed\n";
00165             break;
00166
00167         case XmlNodeType_Whitespace:
00168             ChkHr(reader->GetValue(&value, &valueSize));
00169             XmlTextbox->Text += L"WhiteSpace: ";
00170             ChkHr(ConcatToOutput(value, valueSize));
00171             XmlTextbox->Text += L"\n";
00172             break;
00173
00174         default:
00175             break;
00176         }
00177     }
00178     return hr;
00179 }
00180
00181 HRESULT Scenario1::ReadAttributes(IXmlReader* reader)
00182 {
00183     HRESULT hr = S_OK;
00184
00185     ChkHr(reader->MoveToFirstAttribute());
00186
00187     for (;;)
00188     {
00189         if (!reader->IsDefault())
00190         {
00191             PCWSTR prefix = nullptr;
00192             PCWSTR localName = nullptr;
00193             PCWSTR value = nullptr;
00194
00195             UINT prefixSize = 0;
00196             UINT localNameSize = 0;
00197             UINT valueSize = 0;
00198
00199             ChkHr(reader->GetPrefix(&prefix, &prefixSize));
00200             ChkHr(reader->GetLocalName(&localName, &localNameSize));
00201             ChkHr(reader->GetValue(&value, &valueSize));
00202
00203             if (prefixSize > 0)
00204             {
00205                 XmlTextbox->Text += L"Attr: ";
00206                 ChkHr(ConcatToOutput(prefix, prefixSize));
00207                 XmlTextbox->Text += L":";
00208                 ChkHr(ConcatToOutput(localName, localNameSize));
00209                 XmlTextbox->Text += L"=\"";
00210                 ChkHr(ConcatToOutput(value, valueSize));
00211                 XmlTextbox->Text += L"\"\n";
00212             }
00213             else
00214             {
00215                 XmlTextbox->Text += L"Attr: ";
00216                 ChkHr(ConcatToOutput(localName, localNameSize));
00217                 XmlTextbox->Text += L"=\"";
00218                 ChkHr(ConcatToOutput(value, valueSize));
00219                 XmlTextbox->Text += L"\"\n";
00220             }
00221         }
00222
00223         if (S_OK != (hr = reader->MoveToNextAttribute()))
00224             break;
00225     }
00226
00227     return hr;
00228 }
00229
00230 HRESULT Scenario1::ConcatToOutput(PCWSTR str, UINT strLen)
00231 {
00232     HRESULT hr = S_OK;
00233
00234     try
00235     {
00236         XmlTextbox->Text += ref new String(str, strLen);
00237     }
00238     catch (Platform::Exception^ e)
00239     {
00240         hr = e->HResult;
00241     }
00242
00243     return hr;
00244 }
Generated on Fri Nov 15 2024 22:22:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario06_PostMultipart Member List

This is the complete list of members for Scenario06_PostMultipart, including all inherited members.
Cancel_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario06_PostMultipart |
CancelableRequestAsync(Windows::Foundation::Uri resourceUri, Windows::Web::Http::HttpMultipartFormDataContent form) | Scenario06_PostMultipart | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario06_PostMultipart |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario06_PostMultipart |
Scenario06_PostMultipart() | Scenario06_PostMultipart |
Start_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario06_PostMultipart |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialStage/cpp/AppView.h Source File

  • HolographicSpatialStage
  • cpp

AppView.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "Common\DeviceResources.h"
00004 #include "HolographicSpatialStageMain.h"
00005
00006 namespace HolographicSpatialStage
00007 {
00008     // IFrameworkView class. Connects the app with the Windows shell and handles application lifecycle events.
00009     ref class AppView sealed : public Windows::ApplicationModel::Core::IFrameworkView
00010     {
00011     public:
00012         AppView();
00013
00014         // IFrameworkView methods.
00015         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00016         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00017         virtual void Load(Platform::String^ entryPoint);
00018         virtual void Run();
00019         virtual void Uninitialize();
00020
00021     protected:
00022         // Application lifecycle event handlers.
00023         void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args);
00024         void OnViewActivated(Windows::ApplicationModel::Core::CoreApplicationView^ sender, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00025         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00026         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00027
00028         // Window event handlers.
00029         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00030         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00031
00032     private:
00033         std::unique_ptr<HolographicSpatialStageMain>  m_main;
00034
00035         std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00036         bool                                                m_windowClosed  = false;
00037         bool                                                m_windowVisible = true;
00038
00039         // The holographic space the app will use for rendering.
00040         Windows::Graphics::Holographic::HolographicSpace^   m_holographicSpace = nullptr;
00041     };
00042
00043     // The entry point for the app.
00044     ref class AppViewSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00045     {
00046     public:
00047         virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00048     };
00049 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/ActivationTypes/System/Dismiss/AutoContent/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • ActivationTypes
  • System
  • Dismiss
  • AutoContent

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Notifications;
00003 using Windows.UI.Popups;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00008
00009 namespace Notifications.ScenarioPages.Toasts.ActivationTypes.System.Dismiss.AutoContent
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     public sealed partial class ScenarioElement : UserControl
00015     {
00016         public ScenarioElement()
00017         {
00018             this.InitializeComponent();
00019         }
00020
00021         private void UserControl_Loaded(object sender, RoutedEventArgs e)
00022         {
00023             Initialize();
00024         }
00025
00026
00027         private void Initialize()
00028         {
00029             // Clear all existing notifications
00030             ToastNotificationManager.History.Clear();
00031
00032             // Pop reminder
00033             popToastControl.Payload =
00034                 $@"
00035                 <toast scenario='reminder' launch='args'>
00036                     <visual>
00037                         <binding template='ToastGeneric'>
00038                             <text>System Dismiss (Auto Content)</text>
00039                             <text>The button for dismissing should be localized in your language, generated by the system when displaying the toast.</text>
00040                         </binding>
00041                     </visual>
00042
00043                     <actions>
00044
00045                         <action activationType='system' arguments='dismiss' content='' />
00046
00047                     </actions>
00048                 </toast>";
00049         }
00050
00051         private async void Error(string message)
00052         {
00053             await new MessageDialog(message, "ERROR").ShowAsync();
00054         }
00055     }
00056 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/Common/BasicMath.h Source File

  • Simple3DGameXaml
  • cpp
  • Common

BasicMath.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #define _USE_MATH_DEFINES
00011 #include <math.h>
00012
00013 // This header defines math and matrix helper functions and structures used
00014 // by DirectX SDK samples.
00015
00016 // Common Constants
00017
00018 #define PI_F 3.1415927f
00019
00020 // Template Vector & Matrix Classes
00021
00022 template <class T> struct Vector2
00023 {
00024     union
00025     {
00026         struct
00027         {
00028             T x;
00029             T y;
00030         };
00031         struct
00032         {
00033             T r;
00034             T g;
00035         };
00036         struct
00037         {
00038             T u;
00039             T v;
00040         };
00041     };
00042
00043     T& operator[](unsigned int index)
00044     {
00045         return static_cast<T*>(this)[index];
00046     }
00047
00048     Vector2(T _x = 0, T _y = 0) : x(_x), y(_y) { }
00049 };
00050
00051 template <class T> struct Vector3
00052 {
00053     union
00054     {
00055         struct
00056         {
00057             T x;
00058             T y;
00059             T z;
00060         };
00061         struct
00062         {
00063             T r;
00064             T g;
00065             T b;
00066         };
00067         struct
00068         {
00069             T u;
00070             T v;
00071             T w;
00072         };
00073     };
00074
00075     T& operator[](unsigned int index)
00076     {
00077         return static_cast<T*>(this)[index];
00078     }
00079
00080     Vector3(T _x = 0, T _y = 0, T _z = 0) : x(_x), y(_y), z(_z) { }
00081 };
00082
00083 template <class T> struct Vector4
00084 {
00085     union
00086     {
00087         struct
00088         {
00089             T x;
00090             T y;
00091             T z;
00092             T w;
00093         };
00094         struct
00095         {
00096             T r;
00097             T g;
00098             T b;
00099             T a;
00100         };
00101     };
00102
00103     T& operator[](unsigned int index)
00104     {
00105         return static_cast<T*>(this)[index];
00106     }
00107
00108     Vector4(T _x = 0, T _y = 0, T _z = 0, T _w = 0) : x(_x), y(_y), z(_z), w(_w) { }
00109 };
00110
00111 template <class T> struct Matrix4x4
00112 {
00113     union
00114     {
00115         struct
00116         {
00117             T _11; T _12; T _13; T _14;
00118             T _21; T _22; T _23; T _24;
00119             T _31; T _32; T _33; T _34;
00120             T _41; T _42; T _43; T _44;
00121         };
00122         struct
00123         {
00124             T _m00; T _m01; T _m02; T _m03;
00125             T _m10; T _m11; T _m12; T _m13;
00126             T _m20; T _m21; T _m22; T _m23;
00127             T _m30; T _m31; T _m32; T _m33;
00128         };
00129     };
00130
00131     Matrix4x4(T value = 0)
00132     {
00133         _11 = _12 = _13 = _14 = value;
00134         _21 = _22 = _23 = _24 = value;
00135         _31 = _32 = _33 = _34 = value;
00136         _41 = _42 = _43 = _44 = value;
00137     }
00138
00139     Matrix4x4(
00140         T i11, T i12, T i13, T i14,
00141         T i21, T i22, T i23, T i24,
00142         T i31, T i32, T i33, T i34,
00143         T i41, T i42, T i43, T i44
00144         )
00145     {
00146         _11 = i11; _12 = i12; _13 = i13; _14 = i14;
00147         _21 = i21; _22 = i22; _23 = i23; _24 = i24;
00148         _31 = i31; _32 = i32; _33 = i33; _34 = i34;
00149         _41 = i41; _42 = i42; _43 = i43; _44 = i44;
00150     }
00151
00152     T* operator[](unsigned int index)
00153     {
00154         return &(reinterpret_cast<T*>(this)[index*4]);
00155     }
00156 };
00157
00158 // Template Vector Operations
00159
00160 template <class T>
00161 T dot(Vector2<T> a, Vector2<T> b)
00162 {
00163     return a.x * b.x + a.y * b.y;
00164 }
00165
00166 template <class T>
00167 T dot(Vector3<T> a, Vector3<T> b)
00168 {
00169     return a.x * b.x + a.y * b.y + a.z * b.z;
00170 }
00171
00172 template <class T>
00173 T dot(Vector4<T> a, Vector4<T> b)
00174 {
00175     return a.x * b.x + a.y * b.y + a.z * b.z + a.w + b.w;
00176 }
00177
00178 template <class T>
00179 T length(Vector2<T> a)
00180 {
00181     return sqrt(a.x * a.x + a.y * a.y);
00182 }
00183
00184 template <class T>
00185 T length(Vector3<T> a)
00186 {
00187     return sqrt(a.x * a.x + a.y * a.y + a.z * a.z);
00188 }
00189
00190 template <class T>
00191 T length(Vector4<T> a)
00192 {
00193     return sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w);
00194 }
00195
00196 template <class T>
00197 Vector3<T> cross(Vector3<T> a, Vector3<T> b)
00198 {
00199     return Vector3<T>((a.y*b.z)-(a.z*b.y), (a.z*b.x)-(a.x*b.z), (a.x*b.y)-(a.y*b.x));
00200 }
00201
00202 template <class T>
00203 Vector2<T> normalize(Vector2<T> a)
00204 {
00205     T len = length(a);
00206     return Vector2<T>(a.x / len, a.y / len);
00207 }
00208
00209 template <class T>
00210 Vector3<T> normalize(Vector3<T> a)
00211 {
00212     T len = length(a);
00213     return Vector3<T>(a.x / len, a.y / len, a.z / len);
00214 }
00215
00216 template <class T>
00217 Vector4<T> normalize(Vector4<T> a)
00218 {
00219     T len = length(a);
00220     return Vector4<T>(a.x / len, a.y / len, a.z / len, a.w / len);
00221 }
00222
00223 // Template Vector Operators
00224
00225 template <class T>
00226 Vector2<T> operator-(Vector2<T> a, Vector2<T> b)
00227 {
00228     return Vector2<T>(a.x - b.x, a.y - b.y);
00229 }
00230
00231 template <class T>
00232 Vector2<T> operator-(Vector2<T> a)
00233 {
00234     return Vector2<T>(-a.x, -a.y);
00235 }
00236
00237 template <class T>
00238 Vector3<T> operator-(Vector3<T> a, Vector3<T> b)
00239 {
00240     return Vector3<T>(a.x - b.x, a.y - b.y, a.z - b.z);
00241 }
00242
00243 template <class T>
00244 Vector3<T> operator-(Vector3<T> a)
00245 {
00246     return Vector3<T>(-a.x, -a.y, -a.z);
00247 }
00248
00249 template <class T>
00250 Vector4<T> operator-(Vector4<T> a, Vector4<T> b)
00251 {
00252     return Vector4<T>(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
00253 }
00254
00255 template <class T>
00256 Vector4<T> operator-(Vector4<T> a)
00257 {
00258     return Vector4<T>(-a.x, -a.y, -a.z, -a.w);
00259 }
00260
00261 template <class T>
00262 Vector2<T> operator+(Vector2<T> a, Vector2<T> b)
00263 {
00264     return Vector2<T>(a.x + b.x, a.y + b.y);
00265 }
00266
00267 template <class T>
00268 Vector3<T> operator+(Vector3<T> a, Vector3<T> b)
00269 {
00270     return Vector3<T>(a.x + b.x, a.y + b.y, a.z + b.z);
00271 }
00272
00273 template <class T>
00274 Vector4<T> operator+(Vector4<T> a, Vector4<T> b)
00275 {
00276     return Vector4<T>(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
00277 }
00278
00279 template <class T>
00280 Vector2<T> operator*(Vector2<T> a, T s)
00281 {
00282     return Vector2<T>(a.x * s, a.y * s);
00283 }
00284
00285 template <class T>
00286 Vector2<T> operator*(T s, Vector2<T> a)
00287 {
00288     return a * s;
00289 }
00290
00291 template <class T>
00292 Vector2<T> operator*(Vector2<T> a, Vector2<T> b)
00293 {
00294     return Vector2<T>(a.x * b.x, a.y * b.y);
00295 }
00296
00297 template <class T>
00298 Vector2<T> operator/(Vector2<T> a, T s)
00299 {
00300     return Vector2<T>(a.x / s, a.y / s);
00301 }
00302
00303 template <class T>
00304 Vector3<T> operator*(Vector3<T> a, T s)
00305 {
00306     return Vector3<T>(a.x * s, a.y * s, a.z * s);
00307 }
00308
00309 template <class T>
00310 Vector3<T> operator*(T s, Vector3<T> a)
00311 {
00312     return a * s;
00313 }
00314
00315 template <class T>
00316 Vector3<T> operator*(Vector3<T> a, Vector3<T> b)
00317 {
00318     return Vector3<T>(a.x * b.x, a.y * b.y, a.z * b.z);
00319 }
00320
00321 template <class T>
00322 Vector3<T> operator/(Vector3<T> a, T s)
00323 {
00324     return Vector3<T>(a.x / s, a.y / s, a.z / s);
00325 }
00326
00327 template <class T>
00328 Vector4<T> operator*(Vector4<T> a, T s)
00329 {
00330     return Vector4<T>(a.x * s, a.y * s, a.z * s, a.w * s);
00331 }
00332
00333 template <class T>
00334 Vector4<T> operator*(T s, Vector4<T> a)
00335 {
00336     return a * s;
00337 }
00338
00339 template <class T>
00340 Vector4<T> operator*(Vector4<T> a, Vector4<T> b)
00341 {
00342     return Vector4<T>(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w);
00343 }
00344
00345 template <class T>
00346 Vector4<T> operator/(Vector4<T> a, T s)
00347 {
00348     return Vector4<T>(a.x / s, a.y / s, a.z / s, a.w / s);
00349 }
00350
00351
00352
00353 // Template Matrix Operations
00354
00355 template <class T>
00356 Matrix4x4<T> transpose(Matrix4x4<T> m)
00357 {
00358     return Matrix4x4<T>(
00359         m._11, m._21, m._31, m._41,
00360         m_.12, m._22, m._32, m._42,
00361         m._13, m._23, m._33, m._43,
00362         m._14, m._24, m._34, m._44
00363         );
00364 }
00365
00366 template <class T>
00367 Matrix4x4<T> mul(Matrix4x4<T> m1, Matrix4x4<T> m2)
00368 {
00369     Matrix4x4<T> mOut;
00370
00371     for (int i = 0; i < 4; i++)
00372     {
00373         for (int j = 0; j < 4; j++)
00374         {
00375             for (int k = 0; k < 4; k++)
00376             {
00377                 mOut[i][j] += m1[i][k] * m2[k][j];
00378             }
00379         }
00380     }
00381
00382     return mOut;
00383 }
00384
00385 // Common HLSL-compatible vector typedefs
00386
00387 typedef unsigned int uint;
00388
00389 typedef Vector2<float> float2;
00390 typedef Vector3<float> float3;
00391 typedef Vector4<float> float4;
00392
00393 typedef Matrix4x4<float> float4x4;
00394
00395 // Standard Matrix Intializers
00396
00397 inline float4x4 identity()
00398 {
00399     float4x4 mOut;
00400
00401     mOut._11 = 1.0f; mOut._12 = 0.0f; mOut._13 = 0.0f; mOut._14 = 0.0f;
00402     mOut._21 = 0.0f; mOut._22 = 1.0f; mOut._23 = 0.0f; mOut._24 = 0.0f;
00403     mOut._31 = 0.0f; mOut._32 = 0.0f; mOut._33 = 1.0f; mOut._34 = 0.0f;
00404     mOut._41 = 0.0f; mOut._42 = 0.0f; mOut._43 = 0.0f; mOut._44 = 1.0f;
00405
00406     return mOut;
00407 }
00408
00409 inline float4x4 translation(float x, float y, float z)
00410 {
00411     float4x4 mOut;
00412
00413     mOut._11 = 1.0f; mOut._12 = 0.0f; mOut._13 = 0.0f; mOut._14 = x;
00414     mOut._21 = 0.0f; mOut._22 = 1.0f; mOut._23 = 0.0f; mOut._24 = y;
00415     mOut._31 = 0.0f; mOut._32 = 0.0f; mOut._33 = 1.0f; mOut._34 = z;
00416     mOut._41 = 0.0f; mOut._42 = 0.0f; mOut._43 = 0.0f; mOut._44 = 1.0f;
00417
00418     return mOut;
00419 }
00420
00421 inline float4x4 scale(float x, float y, float z)
00422 {
00423     float4x4 mOut;
00424
00425     mOut._11 = x;    mOut._12 = 0.0f; mOut._13 = 0.0f; mOut._14 = 0.0f;
00426     mOut._21 = 0.0f; mOut._22 = y;    mOut._23 = 0.0f; mOut._24 = 0.0f;
00427     mOut._31 = 0.0f; mOut._32 = 0.0f; mOut._33 = z;    mOut._34 = 0.0f;
00428     mOut._41 = 0.0f; mOut._42 = 0.0f; mOut._43 = 0.0f; mOut._44 = 1.0f;
00429
00430     return mOut;
00431 }
00432
00433 inline float4x4 rotationX(float degreeX)
00434 {
00435     float angleInRadians = degreeX * (PI_F / 180.0f);
00436
00437     float sinAngle = sinf(angleInRadians);
00438     float cosAngle = cosf(angleInRadians);
00439
00440     float4x4 mOut;
00441
00442     mOut._11 = 1.0f; mOut._12 = 0.0f;     mOut._13 = 0.0f;      mOut._14 = 0.0f;
00443     mOut._21 = 0.0f; mOut._22 = cosAngle; mOut._23 = -sinAngle; mOut._24 = 0.0f;
00444     mOut._31 = 0.0f; mOut._32 = sinAngle; mOut._33 = cosAngle;  mOut._34 = 0.0f;
00445     mOut._41 = 0.0f; mOut._42 = 0.0f;     mOut._43 = 0.0f;      mOut._44 = 1.0f;
00446
00447     return mOut;
00448 }
00449
00450 inline float4x4 rotationY(float degreeY)
00451 {
00452     float angleInRadians = degreeY * (PI_F / 180.0f);
00453
00454     float sinAngle = sinf(angleInRadians);
00455     float cosAngle = cosf(angleInRadians);
00456
00457     float4x4 mOut;
00458
00459     mOut._11 = cosAngle;  mOut._12 = 0.0f; mOut._13 = sinAngle; mOut._14 = 0.0f;
00460     mOut._21 = 0.0f;      mOut._22 = 1.0f; mOut._23 = 0.0f;     mOut._24 = 0.0f;
00461     mOut._31 = -sinAngle; mOut._32 = 0.0f; mOut._33 = cosAngle; mOut._34 = 0.0f;
00462     mOut._41 = 0.0f;      mOut._42 = 0.0f; mOut._43 = 0.0f;     mOut._44 = 1.0f;
00463
00464     return mOut;
00465 }
00466
00467 inline float4x4 rotationZ(float degreeZ)
00468 {
00469     float angleInRadians = degreeZ * (PI_F / 180.0f);
00470
00471     float sinAngle = sinf(angleInRadians);
00472     float cosAngle = cosf(angleInRadians);
00473
00474     float4x4 mOut;
00475
00476     mOut._11 = cosAngle; mOut._12 = -sinAngle; mOut._13 = 0.0f; mOut._14 = 0.0f;
00477     mOut._21 = sinAngle; mOut._22 = cosAngle;  mOut._23 = 0.0f; mOut._24 = 0.0f;
00478     mOut._31 = 0.0f;     mOut._32 = 0.0f;      mOut._33 = 1.0f; mOut._34 = 0.0f;
00479     mOut._41 = 0.0f;     mOut._42 = 0.0f;      mOut._43 = 0.0f; mOut._44 = 1.0f;
00480
00481     return mOut;
00482 }
00483
00484 // 3D Rotation matrix for an arbitrary axis specified by x, y and z
00485 inline float4x4 rotationArbitrary(float3 axis, float degree)
00486 {
00487     axis = normalize(axis);
00488
00489     float angleInRadians = degree * (PI_F / 180.0f);
00490
00491     float sinAngle = sinf(angleInRadians);
00492     float cosAngle = cosf(angleInRadians);
00493     float oneMinusCosAngle = 1 - cosAngle;
00494
00495     float4x4 mOut;
00496
00497     mOut._11 = 1.0f + oneMinusCosAngle * (axis.x * axis.x - 1.0f);
00498     mOut._12 = axis.z * sinAngle + oneMinusCosAngle * axis.x * axis.y;
00499     mOut._13 = -axis.y * sinAngle + oneMinusCosAngle * axis.x * axis.z;
00500     mOut._41 = 0.0f;
00501
00502     mOut._21 = -axis.z * sinAngle + oneMinusCosAngle * axis.y * axis.x;
00503     mOut._22 = 1.0f + oneMinusCosAngle * (axis.y * axis.y - 1.0f);
00504     mOut._23 = axis.x * sinAngle + oneMinusCosAngle * axis.y * axis.z;
00505     mOut._24 = 0.0f;
00506
00507     mOut._31 = axis.y * sinAngle + oneMinusCosAngle * axis.z * axis.x;
00508     mOut._32 = -axis.x * sinAngle + oneMinusCosAngle * axis.z * axis.y;
00509     mOut._33 = 1.0f + oneMinusCosAngle * (axis.z * axis.z - 1.0f);
00510     mOut._34 = 0.0f;
00511
00512     mOut._41 = 0.0f;
00513     mOut._42 = 0.0f;
00514     mOut._43 = 0.0f;
00515     mOut._44 = 1.0f;
00516
00517     return mOut;
00518 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DpiScaling/cpp/SampleConfiguration.cpp Source File

  • DpiScaling
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Load images for different scales",         "SDKTemplate.Scenario1" },
00012     { "Override default scaling of UI elements",  "SDKTemplate.Scenario2" },
00013 };
Generated on Fri Nov 15 2024 22:17:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cs/GroupInfoList.cs Source File

  • XamlListView
  • cs

GroupInfoList.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using System.Collections.Generic;
00012
00013 namespace SDKTemplate
00014 {
00015     public class GroupInfoList : List<object>
00016     {
00017         public string Key { get; set; }
00018     }
00019 }
Generated on Fri Nov 15 2024 22:22:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks/Common/BoolToVisibilityConverter.cpp Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks
  • Common

BoolToVisibilityConverter.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "BoolToVisibilityConverter.h"
00013
00014 using namespace AdventureWorks;
00015
00016 using namespace Platform;
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Interop;
00019
00020 BoolToVisibilityConverter::BoolToVisibilityConverter()
00021 {
00022 }
00023
00024 Object ^ BoolToVisibilityConverter::Convert(Object ^value, TypeName targetType, Object ^parameter, String ^language)
00025 {
00026     IBox<Boolean>^ b = dynamic_cast<IBox<Boolean>^>(value);
00027     if (b != nullptr)
00028     {
00029         if (b->Value)
00030         {
00031             return Visibility::Visible;
00032         }
00033         else
00034         {
00035             return Visibility::Collapsed;
00036         }
00037     }
00038
00039     return Visibility::Collapsed;
00040 }
00041
00042 Object ^ BoolToVisibilityConverter::ConvertBack(Object ^value, TypeName targetType, Object ^parameter, String ^language)
00043 {
00044     throw ref new NotImplementedException();
00045 }
Generated on Fri Nov 15 2024 22:18:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cppwinrt/OtherScenarios.h Source File

  • Clipboard
  • cppwinrt

OtherScenarios.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "OtherScenarios.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct OtherScenarios : OtherScenariosT<OtherScenarios>
00020     {
00021         OtherScenarios();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024
00025         void ShowFormatButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026         void EmptyClipboardButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         void RegisterClipboardContentChanged_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void ClearOutputButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029
00030     private:
00031         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00032         static bool registerContentChanged;
00033
00034         void ClearOutput();
00035         void DisplayFormats();
00036     };
00037 }
00038
00039 namespace winrt::SDKTemplate::factory_implementation
00040 {
00041     struct OtherScenarios : OtherScenariosT<OtherScenarios, implementation::OtherScenarios>
00042     {
00043     };
00044 }
Generated on Fri Nov 15 2024 22:18:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactPicker/cs/Scenario1_Single.xaml.cs Source File

  • ContactPicker
  • cs

Scenario1_Single.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using System.Text;
00015 using Windows.ApplicationModel.Contacts;
00016 using Windows.Foundation;
00017 using Windows.Storage.Streams;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Media.Imaging;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario1_Single : Page
00025     {
00026         private MainPage rootPage = MainPage.Current;
00027
00028         public Scenario1_Single()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         private void ClearOutputs()
00034         {
00035             // Reset the output fields.
00036             OutputText.Text = "";
00037             rootPage.NotifyUser("", NotifyType.StatusMessage);
00038         }
00039
00040         private void ReportContactResult(Contact contact)
00041         {
00042             if (contact != null)
00043             {
00044                 OutputText.Text = MainPage.GetContactResult(contact);
00045             }
00046             else
00047             {
00048                 rootPage.NotifyUser("No contact was selected.", NotifyType.ErrorMessage);
00049             }
00050         }
00051
00052         private async void PickContactEmail()
00053         {
00054             ClearOutputs();
00055
00056             // Ask the user to pick a contact email address.
00057             var contactPicker = new ContactPicker();
00058             contactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.Email);
00059
00060             Contact contact = await contactPicker.PickContactAsync();
00061
00062             ReportContactResult(contact);
00063         }
00064
00065         private async void PickContactPhone()
00066         {
00067             ClearOutputs();
00068
00069             // Ask the user to pick a contact phone number.
00070             var contactPicker = new ContactPicker();
00071             contactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber);
00072
00073             Contact contact = await contactPicker.PickContactAsync();
00074
00075             ReportContactResult(contact);
00076         }
00077     }
00078
00079 }
Generated on Fri Nov 15 2024 22:18:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LockScreenApps/cppwinrt/Scenario2_Notifications.cpp Source File

  • LockScreenApps
  • cppwinrt

Scenario2_Notifications.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Notifications.h"
00014 #include "Scenario2_Notifications.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace winrt::NotificationsExtensions::Badges;
00018 using namespace winrt::NotificationsExtensions::Tiles;
00019 using namespace winrt::Windows::Data::Xml::Dom;
00020 using namespace winrt::Windows::Foundation;
00021 using namespace winrt::Windows::UI::Notifications;
00022 using namespace winrt::Windows::UI::Xaml;
00023
00024 namespace winrt::SDKTemplate::implementation
00025 {
00026     Scenario2_Notifications::Scenario2_Notifications()
00027     {
00028         InitializeComponent();
00029     }
00030
00031     void Scenario2_Notifications::ClearBadge_Click(IInspectable const&, RoutedEventArgs const&)
00032     {
00033         BadgeUpdateManager::CreateBadgeUpdaterForApplication().Clear();
00034         rootPage.NotifyUser(L"Badge notification cleared", NotifyType::StatusMessage);
00035     }
00036
00037     void Scenario2_Notifications::SendBadge_Click(IInspectable const&, RoutedEventArgs const&)
00038     {
00039         BadgeNumericNotificationContent badgeContent(6);
00040         BadgeUpdateManager::CreateBadgeUpdaterForApplication().Update(BadgeNotification(badgeContent.GetXml()));
00041         rootPage.NotifyUser(L"Badge notification sent", NotifyType::StatusMessage);
00042     }
00043
00044     void Scenario2_Notifications::SendBadgeWithStringManipulation_Click(IInspectable const&, RoutedEventArgs const&)
00045     {
00046         hstring badgeXmlString{ L"<badge value='6'/>" };
00047         XmlDocument badgeDOM;
00048         badgeDOM.LoadXml(badgeXmlString);
00049         BadgeNotification badge(badgeDOM);
00050         BadgeUpdateManager::CreateBadgeUpdaterForApplication().Update(badge);
00051         rootPage.NotifyUser(L"Badge notification sent", NotifyType::StatusMessage);
00052     }
00053
00054     void Scenario2_Notifications::SendTile_Click(IInspectable const&, RoutedEventArgs const&)
00055     {
00056         auto tileDOM = TileUpdateManager::GetTemplateContent(TileTemplateType::TileWide310x150SmallImageAndText03);
00057         tileDOM.SelectSingleNode(L"//image[@id=1]/@src").NodeValue(box_value(L"'ms-appx:///Assets/tile-sdk.png"));
00058         tileDOM.SelectSingleNode(L"//text[@id=1]").InnerText(L"This tile notification has an image, but it won't be displayed on the lock screen");
00059         TileUpdateManager::CreateTileUpdaterForApplication().Update(TileNotification(tileDOM));
00060         rootPage.NotifyUser(L"Tile notification sent", NotifyType::StatusMessage);
00061     }
00062
00063     void Scenario2_Notifications::SendTileWithStringManipulation_Click(IInspectable const&, RoutedEventArgs const&)
00064     {
00065         hstring tileXmlString = L"<tile>"
00066             L"<visual version='2'>"
00067             L"<binding template='TileWide310x150SmallImageAndText03' fallback='TileWideSmallImageAndText03'>"
00068             L"<image id='1' src='ms-appx:///Assets/tile-sdk.png'/>"
00069             L"<text id='1'>This tile notification has an image, but it won't be displayed on the lock screen</text>"
00070             L"</binding>"
00071             L"</visual>"
00072             L"</tile>";
00073
00074         XmlDocument tileDOM;
00075         tileDOM.LoadXml(tileXmlString);
00076         TileNotification tile(tileDOM);
00077         TileUpdateManager::CreateTileUpdaterForApplication().Update(tile);
00078         rootPage.NotifyUser(L"Tile notification sent", NotifyType::StatusMessage);
00079     }
00080
00081     void Scenario2_Notifications::ClearTile_Click(IInspectable const&, RoutedEventArgs const&)
00082     {
00083         TileUpdateManager::CreateTileUpdaterForApplication().Clear();
00084         rootPage.NotifyUser(L"Tile notification cleared", NotifyType::StatusMessage);
00085     }
00086
00087 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboard/cs/Scenario1_Launch.xaml.cs Source File

  • TouchKeyboard
  • cs

Scenario1_Launch.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013
00014 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00015
00016 namespace SDKTemplate
00017 {
00018     /// <summary>
00019     /// An empty page that can be used on its own or navigated to within a Frame.
00020     /// </summary>
00021     public sealed partial class Scenario1_Launch : Page
00022     {
00023         public Scenario1_Launch()
00024         {
00025             this.InitializeComponent();
00026         }
00027     }
00028 }
Generated on Fri Nov 15 2024 22:21:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MainPage Member List

This is the complete list of members for MainPage, including all inherited members.
_captureFolder | MainPage | [private]
_displayRequest | MainPage | [private]
_externalCamera | MainPage | [private]
_isActivePage | MainPage | [private]
_isInitialized | MainPage | [private]
_isPreviewing | MainPage | [private]
_isRecording | MainPage | [private]
_isSuspending | MainPage | [private]
_isUIActive | MainPage | [private]
_mediaCapture | MainPage | [private]
_mirroringPreview | MainPage | [private]
_rotationHelper | MainPage | [private]
_setupTask | MainPage | [private]
_systemMediaControls | MainPage | [private]
Application_Resuming(object sender, object o) | MainPage | [inline, private]
Application_Suspending(object sender, SuspendingEventArgs e) | MainPage | [inline, private]
CleanupCameraAsync() | MainPage | [inline, private]
CleanupUiAsync() | MainPage | [inline, private]
FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel) | MainPage | [inline, private, static]
HardwareButtons_CameraPressed(object sender, CameraEventArgs e) | MainPage | [inline, private]
InitializeCameraAsync() | MainPage | [inline, private]
MainPage() | MainPage | [inline]
MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) | MainPage | [inline, private]
MediaCapture_RecordLimitationExceeded(MediaCapture sender) | MainPage | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | MainPage | [inline, protected]
PhotoButton_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation) | MainPage | [inline, private, static]
RegisterEventHandlers() | MainPage | [inline, private]
RotationHelper_OrientationChanged(object sender, bool updatePreview) | MainPage | [inline, private]
RotationKey | MainPage | [private, static]
SetPreviewRotationAsync() | MainPage | [inline, private]
SetUpBasedOnStateAsync() | MainPage | [inline, private]
SetupUiAsync() | MainPage | [inline, private]
StartPreviewAsync() | MainPage | [inline, private]
StartRecordingAsync() | MainPage | [inline, private]
StopPreviewAsync() | MainPage | [inline, private]
StopRecordingAsync() | MainPage | [inline, private]
SystemMediaControls_PropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs args) | MainPage | [inline, private]
TakePhotoAsync() | MainPage | [inline, private]
UnregisterEventHandlers() | MainPage | [inline, private]
UpdateButtonOrientation() | MainPage | [inline, private]
UpdateCaptureControls() | MainPage | [inline, private]
VideoButton_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Window_VisibilityChanged(object sender, VisibilityChangedEventArgs args) | MainPage | [inline, private]
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Content/SpatialInputHandler.cpp Source File

  • HolographicVoiceInput
  • cpp
  • Content

SpatialInputHandler.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
00012 #include "SpatialInputHandler.h"
00013 #include <functional>
00014
00015 using namespace HolographicVoiceInput;
00016
00017 using namespace Windows::Foundation;
00018 using namespace Windows::UI::Input::Spatial;
00019 using namespace std::placeholders;
00020
00021 // Creates and initializes a GestureRecognizer that listens to a Person.
00022 SpatialInputHandler::SpatialInputHandler()
00023 {
00024     // The interaction manager provides an event that informs the app when
00025     // spatial interactions are detected.
00026     m_interactionManager = SpatialInteractionManager::GetForCurrentView();
00027
00028     // Bind a handler to the SourcePressed event.
00029     m_sourcePressedEventToken =
00030         m_interactionManager->SourcePressed +=
00031             ref new TypedEventHandler<SpatialInteractionManager^, SpatialInteractionSourceEventArgs^>(
00032                 bind(&SpatialInputHandler::OnSourcePressed, this, _1, _2)
00033                 );
00034
00035     //
00036     // TODO: Expand this class to use other gesture-based input events as applicable to
00037     //       your app.
00038     //
00039 }
00040
00041 SpatialInputHandler::~SpatialInputHandler()
00042 {
00043     // Unregister our handler for the OnSourcePressed event.
00044     m_interactionManager->SourcePressed -= m_sourcePressedEventToken;
00045 }
00046
00047 // Checks if the user performed an input gesture since the last call to this method.
00048 // Allows the main update loop to check for asynchronous changes to the user
00049 // input state.
00050 SpatialInteractionSourceState^ SpatialInputHandler::CheckForInput()
00051 {
00052     SpatialInteractionSourceState^ sourceState = m_sourceState;
00053     m_sourceState = nullptr;
00054     return sourceState;
00055 }
00056
00057 void SpatialInputHandler::OnSourcePressed(SpatialInteractionManager^ sender, SpatialInteractionSourceEventArgs^ args)
00058 {
00059     m_sourceState = args->State;
00060
00061     //
00062     // TODO: In your app or game engine, rewrite this method to queue
00063     //       input events in your input class or event handler.
00064     //
00065 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Barometer/cpp/SampleConfiguration.h Source File

  • Barometer
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Barometer";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlTailoredMultipleViews/cs/TailoredMultipleViews/UserControls/Settings.xaml.cs Source File

  • XamlTailoredMultipleViews
  • cs
  • TailoredMultipleViews
  • UserControls

Settings.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.IO;
00004 using System.Linq;
00005 using System.Runtime.InteropServices.WindowsRuntime;
00006 using Windows.Foundation;
00007 using Windows.Foundation.Collections;
00008 using Windows.UI.Xaml;
00009 using Windows.UI.Xaml.Controls;
00010 using Windows.UI.Xaml.Controls.Primitives;
00011 using Windows.UI.Xaml.Data;
00012 using Windows.UI.Xaml.Input;
00013 using Windows.UI.Xaml.Media;
00014 using Windows.UI.Xaml.Navigation;
00015
00016 // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
00017
00018 namespace OneHandedUse_TailoredMultipleViews.UserControls
00019 {
00020     public sealed partial class Settings : UserControl
00021     {
00022         public Settings()
00023         {
00024             this.InitializeComponent();
00025         }
00026     }
00027 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

WASAPIRenderer Member List

This is the complete list of members for WASAPIRenderer, including all inherited members.
ActivateCompleted(IActivateAudioInterfaceAsyncOperation *operation) | WASAPIRenderer |
ConfigureDeviceInternal() | WASAPIRenderer | [private]
ConfigureSource() | WASAPIRenderer | [private]
GetBufferFramesPerPeriod() | WASAPIRenderer | [private]
GetDeviceStateEvent() | WASAPIRenderer | [inline]
GetMFSample(UINT32 FramesAvailable) | WASAPIRenderer | [private]
GetToneSample(UINT32 FramesAvailable) | WASAPIRenderer | [private]
InitializeAudioDeviceAsync() | WASAPIRenderer |
m_AudioClient | WASAPIRenderer | [private]
m_AudioRenderClient | WASAPIRenderer | [private]
m_BufferFrames | WASAPIRenderer | [private]
m_ChannelVolume | WASAPIRenderer | [private]
m_CritSec | WASAPIRenderer | [private]
m_DefaultPeriodInFrames | WASAPIRenderer | [private]
m_DeviceIdString | WASAPIRenderer | [private]
m_DeviceProps | WASAPIRenderer | [private]
m_DeviceStateChanged | WASAPIRenderer | [private]
m_FundamentalPeriodInFrames | WASAPIRenderer | [private]
m_MaxPeriodInFrames | WASAPIRenderer | [private]
m_MFSource | WASAPIRenderer | [private]
m_MinPeriodInFrames | WASAPIRenderer | [private]
m_MixFormat | WASAPIRenderer | [private]
m_SampleReadyAsyncResult | WASAPIRenderer | [private]
m_SampleReadyEvent | WASAPIRenderer | [private]
m_SampleReadyKey | WASAPIRenderer | [private]
m_ToneSource | WASAPIRenderer | [private]
METHODASYNCCALLBACK(WASAPIRenderer, StartPlayback, OnStartPlayback) | WASAPIRenderer |
METHODASYNCCALLBACK(WASAPIRenderer, StopPlayback, OnStopPlayback) | WASAPIRenderer |
METHODASYNCCALLBACK(WASAPIRenderer, PausePlayback, OnPausePlayback) | WASAPIRenderer |
METHODASYNCCALLBACK(WASAPIRenderer, SampleReady, OnSampleReady) | WASAPIRenderer |
OnAudioSampleRequested(Platform::Boolean IsSilence=false) | WASAPIRenderer | [private]
OnPausePlayback(IMFAsyncResult *pResult) | WASAPIRenderer | [private]
OnSampleReady(IMFAsyncResult *pResult) | WASAPIRenderer | [private]
OnStartPlayback(IMFAsyncResult *pResult) | WASAPIRenderer | [private]
OnStopPlayback(IMFAsyncResult *pResult) | WASAPIRenderer | [private]
PausePlaybackAsync() | WASAPIRenderer |
SetAudioClientChannelVolume() | WASAPIRenderer | [private]
SetProperties(DEVICEPROPS props) | WASAPIRenderer |
SetVolumeOnSession(UINT32 volume) | WASAPIRenderer |
StartPlaybackAsync() | WASAPIRenderer |
StopPlaybackAsync() | WASAPIRenderer |
ValidateBufferValue() | WASAPIRenderer | [private]
WASAPIRenderer() | WASAPIRenderer |
~WASAPIRenderer() | WASAPIRenderer | [private]
Generated on Fri Nov 15 2024 22:23:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MyUserControl1 Member List

This is the complete list of members for MyUserControl1, including all inherited members.
_nonDPProperty | MyUserControl1 | [private]
MyUserControl1() | MyUserControl1 | [inline]
NonDPProperty | MyUserControl1 |
PropertyChanged | MyUserControl1 |
Generated on Fri Nov 15 2024 22:24:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Project.idl Source File

  • Geolocation
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_TrackPosition : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_TrackPosition();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_GetPosition : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_GetPosition();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3_BackgroundTask : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3_BackgroundTask();
00030     }
00031
00032     [default_interface]
00033     runtimeclass Scenario4_ForegroundGeofence : Windows.UI.Xaml.Controls.Page
00034     {
00035         Scenario4_ForegroundGeofence();
00036         Windows.UI.Xaml.Controls.RadioButton StartAtSpecificTime{ get; };
00037     }
00038
00039     [default_interface]
00040     runtimeclass Scenario5_GeofenceBackgroundTask : Windows.UI.Xaml.Controls.Page
00041     {
00042         Scenario5_GeofenceBackgroundTask();
00043     }
00044
00045     [default_interface]
00046     runtimeclass Scenario6_GetLastVisit : Windows.UI.Xaml.Controls.Page
00047     {
00048         Scenario6_GetLastVisit();
00049     }
00050
00051     [default_interface]
00052     runtimeclass Scenario7_ForegroundVisits : Windows.UI.Xaml.Controls.Page
00053     {
00054         Scenario7_ForegroundVisits();
00055     }
00056
00057     [default_interface]
00058     runtimeclass Scenario8_VisitsBackgroundTask : Windows.UI.Xaml.Controls.Page
00059     {
00060         Scenario8_VisitsBackgroundTask();
00061     }
00062 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlContextMenu/cpp/Scenario3.xaml.cpp Source File

  • XamlContextMenu
  • cpp

Scenario3.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021 using namespace Windows::UI::Xaml::Input;
00022 using namespace Windows::UI::Xaml::Media;
00023
00024 Scenario3::Scenario3()
00025 {
00026     InitializeComponent();
00027     AllItems = SampleDataModel::GetSampleData();
00028     sharedFlyout = safe_cast<MenuFlyout^>(Resources->Lookup("SampleContextMenu"));
00029 }
00030
00031 void Scenario3::ListView_ContextRequested(UIElement^ sender, ContextRequestedEventArgs^ e)
00032 {
00033     // Walk up the tree to find the ListViewItem.
00034     // There may not be one if the click wasn't on an item.
00035     auto requestedElement = safe_cast<FrameworkElement^>(e->OriginalSource);
00036     while ((requestedElement != sender) && !dynamic_cast<ListViewItem^>(requestedElement))
00037     {
00038         requestedElement = safe_cast<FrameworkElement^>(VisualTreeHelper::GetParent(requestedElement));
00039     }
00040     if (requestedElement != sender)
00041     {
00042         // The context menu request was indeed for a ListViewItem.
00043         auto model = safe_cast<SampleDataModel^>(ItemListView->ItemFromContainer(requestedElement));
00044         Point point;
00045         if (e->TryGetPosition(requestedElement, &point))
00046         {
00047             rootPage->NotifyUser("Showing flyout for " + model->Title + " at " + point.X.ToString() + "," + point.Y.ToString(), NotifyType::StatusMessage);
00048             sharedFlyout->ShowAt(requestedElement, point);
00049         }
00050         else
00051         {
00052             // Not invoked via pointer, so let XAML choose a default location.
00053             rootPage->NotifyUser("Showing flyout for " + model->Title + " at default location", NotifyType::StatusMessage);
00054             sharedFlyout->ShowAt(requestedElement);
00055         }
00056
00057         e->Handled = true;
00058     }
00059 }
00060
00061 void Scenario3::ListView_ContextCanceled(UIElement^ sender, RoutedEventArgs^ e)
00062 {
00063     sharedFlyout->Hide();
00064 }
00065
00066 SampleDataModel^ Scenario3::GetDataModelForCurrentListViewFlyout()
00067 {
00068     // Obtain the ListViewItem for which the user requested a context menu.
00069     auto listViewItem = sharedFlyout->Target;
00070
00071     // Get the data model for the ListViewItem.
00072     return safe_cast<SampleDataModel^>(ItemListView->ItemFromContainer(listViewItem));
00073 }
00074
00075 void Scenario3::OpenMenuItem_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00076 {
00077     SampleDataModel^ model = GetDataModelForCurrentListViewFlyout();
00078     rootPage->NotifyUser("Item: " + model->Title + ", Action: Open", NotifyType::StatusMessage);
00079 }
00080
00081 void Scenario3::PrintMenuItem_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00082 {
00083     SampleDataModel^ model = GetDataModelForCurrentListViewFlyout();
00084     rootPage->NotifyUser("Item: " + model->Title + ", Action: Print", NotifyType::StatusMessage);
00085 }
00086
00087 void Scenario3::DeleteMenuItem_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00088 {
00089     SampleDataModel^ model = GetDataModelForCurrentListViewFlyout();
00090     rootPage->NotifyUser("Item: " + model->Title + ", Action: Delete", NotifyType::StatusMessage);
00091 }
00092
Generated on Fri Nov 15 2024 22:18:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: GlobalizationPreferences/cs/Scenario2_Lang.xaml.cs Source File

  • GlobalizationPreferences
  • cs

Scenario2_Lang.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.Foundation;
00013 using Windows.Globalization;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario2_Lang : Page
00020     {
00021         public Scenario2_Lang()
00022         {
00023             this.InitializeComponent();
00024         }
00025
00026         private string ReportLanguageData(Language lang)
00027         {
00028             return "Display Name: " + lang.DisplayName + "\n" +
00029                 "Language Tag: " + lang.LanguageTag + "\n" +
00030                 "Native Name: " + lang.NativeName + "\n" +
00031                 "Script Code: " + lang.Script + "\n\n";
00032         }
00033
00034         private void ShowResults_Click(object sender, RoutedEventArgs e)
00035         {
00036             // This scenario uses the Windows.System.UserProfile.GlobalizationPreferences class to
00037             // obtain the user's preferred language characteristics.
00038             var topUserLanguage = Windows.System.UserProfile.GlobalizationPreferences.Languages[0];
00039             var userLanguage = new Language(topUserLanguage);
00040
00041             // This obtains the language characteristics by providing a BCP47 tag.
00042             var exampleLanguage = new Language("ja");
00043
00044             // Display the results
00045             OutputTextBlock.Text = "User's Preferred Language\n" + ReportLanguageData(userLanguage) +
00046                 "Example Language by BCP47 tag (ja)\n" + ReportLanguageData(exampleLanguage);
00047         }
00048     }
00049 }
Generated on Fri Nov 15 2024 22:19:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ReceiptView Member List

This is the complete list of members for ReceiptView, including all inherited members.
btnDebugLog_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | ReceiptView | [inline, private]
btnMainMenu_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | ReceiptView | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | ReceiptView | [inline, protected]
ReceiptView() | ReceiptView | [inline]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_CloseDrawer Member List

This is the complete list of members for Scenario2_CloseDrawer, including all inherited members.
ClaimCashDrawer() | Scenario2_CloseDrawer | [inline, private]
claimedDrawer | Scenario2_CloseDrawer | [private]
CreateDefaultCashDrawerObject() | Scenario2_CloseDrawer | [inline, private]
drawer | Scenario2_CloseDrawer | [private]
drawer_AlarmExpired(CashDrawerCloseAlarm alarm, object sender) | Scenario2_CloseDrawer | [inline, private]
drawer_StatusUpdated(CashDrawer drawer, CashDrawerStatusUpdatedEventArgs e) | Scenario2_CloseDrawer | [inline, private]
EnableCashDrawer() | Scenario2_CloseDrawer | [inline, private]
InitDrawerButton_Click(object sender, RoutedEventArgs e) | Scenario2_CloseDrawer | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_CloseDrawer | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_CloseDrawer | [inline, protected]
ResetScenarioState() | Scenario2_CloseDrawer | [inline, private]
rootPage | Scenario2_CloseDrawer | [private]
Scenario2_CloseDrawer() | Scenario2_CloseDrawer | [inline]
UpdateStatusOutput(CashDrawerStatusKind status) | Scenario2_CloseDrawer | [inline, private]
WaitForDrawerCloseButton_Click(object sender, RoutedEventArgs e) | Scenario2_CloseDrawer | [inline, private]
Generated on Fri Nov 15 2024 22:23:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_MasterDetail Member List

This is the complete list of members for Scenario3_MasterDetail, including all inherited members.
AddItem(object sender, RoutedEventArgs e) | Scenario3_MasterDetail | [inline, private]
CancelSelection(object sender, RoutedEventArgs e) | Scenario3_MasterDetail | [inline, private]
Contacts | Scenario3_MasterDetail | [private]
DeleteItem(object sender, RoutedEventArgs e) | Scenario3_MasterDetail | [inline, private]
DeleteItems(object sender, RoutedEventArgs e) | Scenario3_MasterDetail | [inline, private]
EnableContentTransitions() | Scenario3_MasterDetail | [inline, private]
OnCurrentStateChanged(object sender, VisualStateChangedEventArgs e) | Scenario3_MasterDetail | [inline, private]
OnItemClick(object sender, ItemClickEventArgs e) | Scenario3_MasterDetail | [inline, private]
OnLoaded(object sender, RoutedEventArgs e) | Scenario3_MasterDetail | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_MasterDetail | [inline, protected]
OnSelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario3_MasterDetail | [inline, private]
Scenario3_MasterDetail() | Scenario3_MasterDetail | [inline]
SelectItems(object sender, RoutedEventArgs e) | Scenario3_MasterDetail | [inline, private]
SelectSomethingIfPossible() | Scenario3_MasterDetail | [inline, private]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/pch.cpp Source File

  • HolographicTagAlong
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // pch.cpp
00014 // Include the standard header and generate the precompiled header.
00015 //
00016
00017 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Appointments/cs/Scenario1_Define.xaml.cs Source File

  • Appointments
  • cs

Scenario1_Define.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario1_Define : Page
00020     {
00021         private MainPage rootPage = MainPage.Current;
00022
00023         public Scenario1_Define()
00024         {
00025             this.InitializeComponent();
00026         }
00027
00028         /// <summary>
00029         /// Creates an Appointment based on the input fields and validates it.
00030         /// </summary>
00031         /// <param name="sender"></param>
00032         /// <param name="e"></param>
00033         private void Create_Click(object sender, RoutedEventArgs e)
00034         {
00035             string errorMessage = null;
00036             var appointment = new Windows.ApplicationModel.Appointments.Appointment();
00037
00038             // StartTime
00039             var date = StartTimeDatePicker.Date;
00040             var time = StartTimeTimePicker.Time;
00041             var timeZoneOffset = TimeZoneInfo.Local.GetUtcOffset(DateTime.Now);
00042             var startTime = new DateTimeOffset(date.Year, date.Month, date.Day, time.Hours, time.Minutes, 0, timeZoneOffset);
00043             appointment.StartTime = startTime;
00044
00045             // Subject
00046             appointment.Subject = SubjectTextBox.Text;
00047
00048             if (appointment.Subject.Length > 255)
00049             {
00050                 errorMessage = "The subject cannot be greater than 255 characters.";
00051             }
00052
00053             // Location
00054             appointment.Location = LocationTextBox.Text;
00055
00056             if (appointment.Location.Length > 32768)
00057             {
00058                 errorMessage = "The location cannot be greater than 32,768 characters.";
00059             }
00060
00061             // Details
00062             appointment.Details = DetailsTextBox.Text;
00063
00064             if (appointment.Details.Length > 1073741823)
00065             {
00066                 errorMessage = "The details cannot be greater than 1,073,741,823 characters.";
00067             }
00068
00069             // Duration
00070             if (DurationComboBox.SelectedIndex == 0)
00071             {
00072                 // 30 minute duration is selected
00073                 appointment.Duration = TimeSpan.FromMinutes(30);
00074             }
00075             else
00076             {
00077                 // 1 hour duration is selected
00078                 appointment.Duration = TimeSpan.FromHours(1);
00079             }
00080
00081             // All Day
00082             appointment.AllDay = AllDayCheckBox.IsChecked.Value;
00083
00084             // Reminder
00085             if (ReminderCheckBox.IsChecked.Value)
00086             {
00087                 switch (ReminderComboBox.SelectedIndex)
00088                 {
00089                     case 0:
00090                         appointment.Reminder = TimeSpan.FromMinutes(15);
00091                         break;
00092                     case 1:
00093                         appointment.Reminder = TimeSpan.FromHours(1);
00094                         break;
00095                     case 2:
00096                         appointment.Reminder = TimeSpan.FromDays(1);
00097                         break;
00098                 }
00099             }
00100
00101             //Busy Status
00102             switch (BusyStatusComboBox.SelectedIndex)
00103             {
00104                 case 0:
00105                     appointment.BusyStatus = Windows.ApplicationModel.Appointments.AppointmentBusyStatus.Busy;
00106                     break;
00107                 case 1:
00108                     appointment.BusyStatus = Windows.ApplicationModel.Appointments.AppointmentBusyStatus.Tentative;
00109                     break;
00110                 case 2:
00111                     appointment.BusyStatus = Windows.ApplicationModel.Appointments.AppointmentBusyStatus.Free;
00112                     break;
00113                 case 3:
00114                     appointment.BusyStatus = Windows.ApplicationModel.Appointments.AppointmentBusyStatus.OutOfOffice;
00115                     break;
00116                 case 4:
00117                     appointment.BusyStatus = Windows.ApplicationModel.Appointments.AppointmentBusyStatus.WorkingElsewhere;
00118                     break;
00119             }
00120
00121             // Sensitivity
00122             switch (SensitivityComboBox.SelectedIndex)
00123             {
00124                 case 0:
00125                     appointment.Sensitivity = Windows.ApplicationModel.Appointments.AppointmentSensitivity.Public;
00126                     break;
00127                 case 1:
00128                     appointment.Sensitivity = Windows.ApplicationModel.Appointments.AppointmentSensitivity.Private;
00129                     break;
00130             }
00131
00132             // Uri
00133             if (UriTextBox.Text.Length > 0)
00134             {
00135                 try
00136                 {
00137                     appointment.Uri = new System.Uri(UriTextBox.Text);
00138                 }
00139                 catch (Exception)
00140                 {
00141                     errorMessage = "The Uri provided is invalid.";
00142                 }
00143             }
00144
00145             // Organizer
00146             // Note: Organizer can only be set if there are no invitees added to this appointment.
00147             if (OrganizerRadioButton.IsChecked.Value)
00148             {
00149                 var organizer = new Windows.ApplicationModel.Appointments.AppointmentOrganizer();
00150
00151                 // Organizer Display Name
00152                 organizer.DisplayName = OrganizerDisplayNameTextBox.Text;
00153
00154                 if (organizer.DisplayName.Length > 256)
00155                 {
00156                     errorMessage = "The organizer display name cannot be greater than 256 characters.";
00157                 }
00158                 else
00159                 {
00160                     // Organizer Address (e.g. Email Address)
00161                     organizer.Address = OrganizerAddressTextBox.Text;
00162
00163                     if (organizer.Address.Length > 321)
00164                     {
00165                         errorMessage = "The organizer address cannot be greater than 321 characters.";
00166                     }
00167                     else if (organizer.Address.Length == 0)
00168                     {
00169                         errorMessage = "The organizer address must be greater than 0 characters.";
00170                     }
00171                     else
00172                     {
00173                         appointment.Organizer = organizer;
00174                     }
00175                 }
00176             }
00177
00178             // Invitees
00179             // Note: If the size of the Invitees list is not zero, then an Organizer cannot be set.
00180             if (InviteeRadioButton.IsChecked.Value)
00181             {
00182                 var invitee = new Windows.ApplicationModel.Appointments.AppointmentInvitee();
00183
00184                 // Invitee Display Name
00185                 invitee.DisplayName = InviteeDisplayNameTextBox.Text;
00186
00187                 if (invitee.DisplayName.Length > 256)
00188                 {
00189                     errorMessage = "The invitee display name cannot be greater than 256 characters.";
00190                 }
00191                 else
00192                 {
00193                     // Invitee Address (e.g. Email Address)
00194                     invitee.Address = InviteeAddressTextBox.Text;
00195
00196                     if (invitee.Address.Length > 321)
00197                     {
00198                         errorMessage = "The invitee address cannot be greater than 321 characters.";
00199                     }
00200                     else if (invitee.Address.Length == 0)
00201                     {
00202                         errorMessage = "The invitee address must be greater than 0 characters.";
00203                     }
00204                     else
00205                     {
00206                         // Invitee Role
00207                         switch (RoleComboBox.SelectedIndex)
00208                         {
00209                             case 0:
00210                                 invitee.Role = Windows.ApplicationModel.Appointments.AppointmentParticipantRole.RequiredAttendee;
00211                                 break;
00212                             case 1:
00213                                 invitee.Role = Windows.ApplicationModel.Appointments.AppointmentParticipantRole.OptionalAttendee;
00214                                 break;
00215                             case 2:
00216                                 invitee.Role = Windows.ApplicationModel.Appointments.AppointmentParticipantRole.Resource;
00217                                 break;
00218                         }
00219
00220                         // Invitee Response
00221                         switch (ResponseComboBox.SelectedIndex)
00222                         {
00223                             case 0:
00224                                 invitee.Response = Windows.ApplicationModel.Appointments.AppointmentParticipantResponse.None;
00225                                 break;
00226                             case 1:
00227                                 invitee.Response = Windows.ApplicationModel.Appointments.AppointmentParticipantResponse.Tentative;
00228                                 break;
00229                             case 2:
00230                                 invitee.Response = Windows.ApplicationModel.Appointments.AppointmentParticipantResponse.Accepted;
00231                                 break;
00232                             case 3:
00233                                 invitee.Response = Windows.ApplicationModel.Appointments.AppointmentParticipantResponse.Declined;
00234                                 break;
00235                             case 4:
00236                                 invitee.Response = Windows.ApplicationModel.Appointments.AppointmentParticipantResponse.Unknown;
00237                                 break;
00238                         }
00239
00240                         appointment.Invitees.Add(invitee);
00241                     }
00242                 }
00243             }
00244
00245             if (errorMessage == null)
00246             {
00247                 rootPage.NotifyUser("The appointment was created successfully and is valid.", NotifyType.StatusMessage);
00248             }
00249             else
00250             {
00251                 rootPage.NotifyUser(errorMessage, NotifyType.ErrorMessage);
00252             }
00253         }
00254
00255         /// <summary>
00256         /// Organizer and Invitee properties are mutually exclusive.
00257         /// This radio button enables the organizer properties while disabling the invitees.
00258         /// </summary>
00259         /// <param name="sender"></param>
00260         /// <param name="e"></param>
00261         private void OrganizerRadioButton_Checked(object sender, RoutedEventArgs e)
00262         {
00263             OrganizerStackPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
00264             InviteeStackPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00265         }
00266
00267         /// <summary>
00268         /// Organizer and Invitee properties are mutually exclusive.
00269         /// This radio button enables the invitees properties while disabling the organizer.
00270         /// </summary>
00271         /// <param name="sender"></param>
00272         /// <param name="e"></param>
00273         private void InviteeRadioButton_Checked(object sender, RoutedEventArgs e)
00274         {
00275             InviteeStackPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
00276             OrganizerStackPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00277         }
00278
00279         /// <summary>
00280         /// Displays the combo box containing various reminder times.
00281         /// </summary>
00282         /// <param name="sender"></param>
00283         /// <param name="e"></param>
00284         private void ReminderCheckBox_Checked(object sender, RoutedEventArgs e)
00285         {
00286             ReminderComboBox.Visibility = Windows.UI.Xaml.Visibility.Visible;
00287         }
00288
00289         /// <summary>
00290         /// Hides the combo box containing various reminder times.
00291         /// </summary>
00292         /// <param name="sender"></param>
00293         /// <param name="e"></param>
00294         private void ReminderCheckBox_UnChecked(object sender, RoutedEventArgs e)
00295         {
00296             ReminderComboBox.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00297         }
00298     }
00299 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/VoiceCommandService/AdventureworksVoiceCommandService.h Source File

  • CortanaVoiceCommand
  • cpp
  • VoiceCommandService

AdventureworksVoiceCommandService.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012 namespace VoiceCommandService
00013 {
00014     [Windows::Foundation::Metadata::WebHostHidden]
00015     public ref class AdventureWorksVoiceCommandService sealed : public Windows::ApplicationModel::Background::IBackgroundTask
00016     {
00017     public:
00018         // Inherited via IBackgroundTask
00019         virtual void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance ^taskInstance);
00020
00021     private:
00022         Windows::ApplicationModel::Resources::Core::ResourceContext^ context;
00023         Windows::ApplicationModel::Resources::Core::ResourceMap^ resourceMap;
00024
00025         Windows::Foundation::EventRegistrationToken taskCancelledToken;
00026         Windows::ApplicationModel::VoiceCommands::VoiceCommandServiceConnection^ voiceServiceConnection;
00027         Platform::Agile<Windows::ApplicationModel::Background::BackgroundTaskDeferral^> serviceDeferral;
00028         void OnCanceled(
00029             Windows::ApplicationModel::Background::IBackgroundTaskInstance ^sender,
00030             Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason);
00031         void OnVoiceCommandCompleted(
00032             Windows::ApplicationModel::VoiceCommands::VoiceCommandServiceConnection ^sender,
00033             Windows::ApplicationModel::VoiceCommands::VoiceCommandCompletedEventArgs ^args);
00034
00035         void SendCompletionMessageForDestination(Platform::String^ destination);
00036         void SendCompletionMessageForCancellation(Platform::String^ destination);
00037         AdventureWorks_Shared::Trip^ DisambiguateTrips(std::vector<AdventureWorks_Shared::Trip^> trips, Platform::String^ disambiguationMessage, Platform::String^ secondDisambiguationMessage);
00038
00039         void LaunchAppInForeground();
00040
00041         void ShowProgressScreen(Platform::String^ progressMessage);
00042
00043         Platform::String^ GetResourceString(Platform::String^ resourceName);
00044         Platform::String^ GetResourceStringAndFormat(Platform::String^ resourceName, Platform::String^ param);
00045     };
00046 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisplayOrientation/cs/SampleConfiguration.cs Source File

  • DisplayOrientation
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Display orientation";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Show and lock orientation", ClassType=typeof(Scenario1_Orientation)},
00025         };
00026     }
00027
00028     public class Scenario
00029     {
00030         public string Title { get; set; }
00031         public Type ClassType { get; set; }
00032     }
00033 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/GameHud.h Source File

  • Simple3DGameXaml
  • cpp

GameHud.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // GameHud:
00015 // This class maintains the resources necessary to draw the Heads Up Display, which is a
00016 // 2D overlay on top of the main 3D graphics generated for the game.
00017 // The GameHud Render method expects to be called within the context of a D2D BeginDraw
00018 // and makes D2D drawing calls to draw the text elements on the window.
00019
00020 #include "Simple3DGame.h"
00021 #include "DirectXSample.h"
00022
00023 ref class Simple3DGame;
00024
00025 ref class GameHud
00026 {
00027 internal:
00028     GameHud(
00029         _In_ const std::shared_ptr<DX::DeviceResources>& deviceResources,
00030         _In_ Platform::String^ titleHeader,
00031         _In_ Platform::String^ titleBody,
00032         _In_ Platform::String^ titleLicenseInfo
00033         );
00034
00035     void CreateDeviceDependentResources();
00036     void CreateWindowSizeDependentResources();
00037     void ReleaseDeviceDependentResources();
00038     void Render(_In_ Simple3DGame^ game);
00039
00040     void SetLicenseInfo(_In_ Platform::String^ licenseInfo);
00041
00042 private:
00043     // Cached pointer to device resources.
00044     std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00045
00046     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>        m_textBrush;
00047     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>        m_textBrushGrey;
00048     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatBody;
00049     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatBodySymbol;
00050
00051     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatTitleHeader;
00052     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatTitleBody;
00053     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatTitleLicense;
00054     Microsoft::WRL::ComPtr<ID2D1Bitmap>                 m_logoBitmap;
00055     Microsoft::WRL::ComPtr<IDWriteTextLayout>           m_titleHeaderLayout;
00056     Microsoft::WRL::ComPtr<IDWriteTextLayout>           m_titleBodyLayout;
00057     Microsoft::WRL::ComPtr<IDWriteTextLayout>           m_titleLicenseInfoLayout;
00058
00059     bool                                                m_showTitle;
00060     Platform::String^                                   m_titleHeader;
00061     Platform::String^                                   m_titleBody;
00062     Platform::String^                                   m_titleLicenseInfo;
00063     bool                                                m_licenseInfoChanged;
00064
00065     float                                               m_titleBodyVerticalOffset;
00066     float                                               m_titleLicenseVerticalOffset;
00067     D2D1_SIZE_F                                         m_logoSize;
00068     D2D1_SIZE_F                                         m_maxTitleSize;
00069 };
Generated on Fri Nov 15 2024 22:21:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlLite/cpp/Scenario3_XmlWriterLite.xaml.h Source File

  • XmlLite
  • cpp

Scenario3_XmlWriterLite.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario3_XmlWriterLite.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     namespace XmlLite
00021     {
00022         /// <summary>
00023         /// An empty page that can be used on its own or navigated to within a Frame.
00024         /// </summary>
00025         [Windows::Foundation::Metadata::WebHostHidden]
00026         public ref class Scenario3 sealed
00027         {
00028         public:
00029             Scenario3();
00030
00031         private:
00032             MainPage^ rootPage;
00033             void DoSomething_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034
00035             HRESULT WriteXml(Windows::Storage::Streams::IRandomAccessStream^ writeStream);
00036             HRESULT ReadAndWrite(IXmlReader* reader, IXmlWriterLite* writer);
00037         };
00038     }
00039 }
Generated on Fri Nov 15 2024 22:22:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SocketReaderWriter Member List

This is the complete list of members for SocketReaderWriter, including all inherited members.
_dataReader | SocketReaderWriter | [private]
_dataWriter | SocketReaderWriter | [private]
_rootPage | SocketReaderWriter | [private]
_streamSocket | SocketReaderWriter | [private]
Dispose() | SocketReaderWriter | [inline]
ReadMessageAsync() | SocketReaderWriter | [inline]
SocketReaderWriter(StreamSocket socket, MainPage mainPage) | SocketReaderWriter | [inline]
WriteMessageAsync(string message) | SocketReaderWriter | [inline]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/Scenario3.cpp Source File

  • FileAccess
  • cppwinrt

Scenario3.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3.h"
00014 #include "Scenario3.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Storage;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Navigation;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario3::Scenario3()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     void Scenario3::OnNavigatedTo(NavigationEventArgs const&)
00031     {
00032         SampleState::ValidateFile();
00033     }
00034
00035     fire_and_forget Scenario3::WriteTextButton_Click(IInspectable const&, RoutedEventArgs const&)
00036     {
00037         auto lifetime = get_strong();
00038
00039         StorageFile file = SampleState::SampleFile();
00040         if (file != nullptr)
00041         {
00042             try
00043             {
00044                 hstring userContent = InputTextBox().Text();
00045                 co_await FileIO::WriteTextAsync(file, userContent);
00046                 rootPage.NotifyUser(L"The following text was written to '" + file.Name() + L"':\n" + userContent, NotifyType::StatusMessage);
00047             }
00048             catch (const hresult_error& ex)
00049             {
00050                 if (ex.code() == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
00051                 {
00052                     SampleState::NotifyUserFileNotExist();
00053                 }
00054                 else if (ex.code() == HRESULT_FROM_WIN32(ERROR_NO_UNICODE_TRANSLATION))
00055                 {
00056                     rootPage.NotifyUser(L"File cannot be decoded as Unicode.", NotifyType::ErrorMessage);
00057                 }
00058                 else
00059                 {
00060                     // I/O errors are reported as exceptions.
00061                     rootPage.NotifyUser(L"Error writing to '" + file.Name() + L"': " + ex.message(), NotifyType::ErrorMessage);
00062                 }
00063             }
00064         }
00065         else
00066         {
00067             SampleState::NotifyUserFileNotExist();
00068         }
00069     }
00070
00071     fire_and_forget Scenario3::ReadTextButton_Click(IInspectable const&, RoutedEventArgs const&)
00072     {
00073         auto lifetime = get_strong();
00074
00075         StorageFile file = SampleState::SampleFile();
00076         if (file != nullptr)
00077         {
00078             try
00079             {
00080                 hstring fileContent = co_await FileIO::ReadTextAsync(file);
00081                     rootPage.NotifyUser(L"The following text was read from '" + file.Name() + L"':\n" + fileContent, NotifyType::StatusMessage);
00082             }
00083             catch (const hresult_error& ex)
00084             {
00085                 if (ex.code() == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
00086                 {
00087                     SampleState::NotifyUserFileNotExist();
00088                 }
00089                 else
00090                 {
00091                     // I/O errors are reported as exceptions.
00092                     rootPage.NotifyUser(L"Error reading from '" + file.Name() + L"': " + ex.message(), NotifyType::ErrorMessage);
00093                 }
00094             }
00095         }
00096         else
00097         {
00098             SampleState::NotifyUserFileNotExist();
00099         }
00100     }
00101 }
Generated on Fri Nov 15 2024 22:19:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/MediaCaptureManager.cpp Source File

  • HolographicMixedRealityCapture
  • cpp

MediaCaptureManager.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "MediaCaptureManager.h"
00003 #include <windows.media.mediaproperties.h>
00004 #include <mfmediacapture.h>
00005 #include <collection.h>
00006
00007 using namespace HolographicMRCSample;
00008 using namespace Windows::Devices::Enumeration;
00009 using namespace Windows::Media;
00010 using namespace Windows::Media::Capture;
00011
00012 MediaCaptureManager::MediaCaptureManager() :
00013     m_currentState(Unknown),
00014     m_hologramEnabled(false),
00015     m_sysAudioEnabled(false),
00016     m_videoEffectAdded(false),
00017     m_photoEffectAdded(false),
00018     m_audioEffectAdded(false)
00019 {
00020 }
00021
00022 MediaCaptureManager::~MediaCaptureManager()
00023 {
00024 }
00025
00026 Concurrency::task<void> MediaCaptureManager::InitializeAsync(IMFDXGIDeviceManager *pDxgiDeviceManager)
00027 {
00028     m_mediaCapture = ref new Windows::Media::Capture::MediaCapture;
00029
00030     m_mediaCapture->Failed += ref new MediaCaptureFailedEventHandler([](MediaCapture^ sender, MediaCaptureFailedEventArgs ^args)
00031     {
00032         // Handle MediaCapture failure notification
00033         OutputDebugString(args->Message->Data());
00034     });
00035
00036     if (pDxgiDeviceManager)
00037     {
00038         m_spMFDXGIDeviceManager = pDxgiDeviceManager;
00039     }
00040
00041     return Concurrency::create_task(DeviceInformation::FindAllAsync(DeviceClass::VideoCapture)).then([this](DeviceInformationCollection^ devices)
00042     {
00043         auto initSetting = ref new Windows::Media::Capture::MediaCaptureInitializationSettings;
00044         initSetting->StreamingCaptureMode = Windows::Media::Capture::StreamingCaptureMode::AudioAndVideo;
00045         initSetting->MediaCategory = Windows::Media::Capture::MediaCategory::Media;
00046
00047         // Select video conferencing profile since it provides better performance on HoloLens 2
00048         for (auto cameraDeviceInfo : devices)
00049         {
00050             auto profiles = m_mediaCapture->FindKnownVideoProfiles(cameraDeviceInfo->Id, KnownVideoProfile::VideoConferencing);
00051             if (profiles->Size > 0)
00052             {
00053                 initSetting->VideoProfile = profiles->GetAt(0);
00054             }
00055         }
00056
00057         if (m_spMFDXGIDeviceManager)
00058         {
00059             // Optionally, you can put your D3D device into MediaCapture.
00060             // But, in most case, this is not mandatory.
00061             Microsoft::WRL::ComPtr<IAdvancedMediaCaptureInitializationSettings> spAdvancedSettings;
00062             ((IUnknown*)initSetting)->QueryInterface(IID_PPV_ARGS(&spAdvancedSettings));
00063             spAdvancedSettings->SetDirectxDeviceManager(m_spMFDXGIDeviceManager.Get());
00064         }
00065
00066         return Concurrency::create_task(m_mediaCapture->InitializeAsync(initSetting)).then([this]()
00067         {
00068             auto lock = m_lock.LockExclusive();
00069
00070             if (m_mediaCapture->MediaCaptureSettings->AudioDeviceId && m_mediaCapture->MediaCaptureSettings->VideoDeviceId)
00071             {
00072                 // MediaCapture is initialized with valid audio and video device.
00073                 m_currentState = Initialized;
00074             }
00075             else
00076             {
00077                 OutputDebugString(L"MediaCapture is initialized without valid sources.\n");
00078             }
00079         });
00080     });
00081 }
00082
00083 Concurrency::task<void> MediaCaptureManager::StartRecordingAsync()
00084 {
00085     // Lock to check current state
00086     auto lock = m_lock.LockExclusive();
00087
00088     if (m_currentState != Initialized)
00089     {
00090         OutputDebugString(L"Trying to start recording in invalid state.\n");
00091         throw ref new Platform::FailureException();
00092     }
00093
00094     m_currentState = StartingRecord;
00095
00096     return Concurrency::create_task(Windows::Storage::KnownFolders::GetFolderForUserAsync(nullptr, Windows::Storage::KnownFolderId::CameraRoll)).then([this](Windows::Storage::StorageFolder ^folder)
00097     {
00098         if (!folder)
00099         {
00100             OutputDebugString(L"Can't find camera roll folder for this user\n");
00101             throw ref new Platform::FailureException();
00102         }
00103
00104         // Create storage file for video capture
00105         return Concurrency::create_task(folder->CreateFileAsync(L"MrcVideo.mp4", Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this](Windows::Storage::StorageFile ^saveFile)
00106         {
00107             if (!saveFile)
00108             {
00109                 throw ref new Platform::FailureException();
00110             }
00111
00112             Concurrency::task<void> addEffectTask;
00113             auto lock = m_lock.LockShared();
00114
00115             if (m_hologramEnabled)
00116             {
00117                 // Add video effect on videoRecord stream
00118                 auto mrcVideoEffectDefinition = ref new MrcEffectDefinitions::MrcVideoEffectDefinition;
00119                 mrcVideoEffectDefinition->StreamType = MediaStreamType::VideoRecord;
00120
00121                 addEffectTask = Concurrency::create_task(m_mediaCapture->AddVideoEffectAsync(mrcVideoEffectDefinition, MediaStreamType::VideoRecord)).then([this](IMediaExtension ^videoExtension)
00122                 {
00123                     auto lock = m_lock.LockExclusive();
00124                     OutputDebugString(L"VideoEffect Added\n");
00125                     m_videoEffectAdded = true;
00126
00127                     if (m_sysAudioEnabled)
00128                     {
00129                         // Add audio effect on audio stream
00130                         auto mrcAudioEffectDefinition = ref new MrcEffectDefinitions::MrcAudioEffectDefinition;
00131                         mrcAudioEffectDefinition->MixerMode = MrcEffectDefinitions::AudioMixerMode::MicAndLoopback;
00132
00133                         auto addAudioEffectTask = Concurrency::create_task(m_mediaCapture->AddAudioEffectAsync(mrcAudioEffectDefinition)).then([this](IMediaExtension^ audioExtension)
00134                         {
00135                             auto lock = m_lock.LockExclusive();
00136                             OutputDebugString(L"AudioEffect Added\n");
00137                             m_audioEffectAdded = true;
00138                         });
00139                     }
00140                 });
00141             }
00142             else if (m_sysAudioEnabled)
00143             {
00144                 // Add audio effect on audio stream
00145                 auto mrcAudioEffectDefinition = ref new MrcEffectDefinitions::MrcAudioEffectDefinition;
00146                 mrcAudioEffectDefinition->MixerMode = MrcEffectDefinitions::AudioMixerMode::MicAndLoopback;
00147
00148                 addEffectTask = Concurrency::create_task(m_mediaCapture->AddAudioEffectAsync(mrcAudioEffectDefinition)).then([this](IMediaExtension^ audioExtension)
00149                 {
00150                     auto lock = m_lock.LockExclusive();
00151                     OutputDebugString(L"AudioEffect Added\n");
00152                     m_audioEffectAdded = true;
00153                 });
00154             }
00155
00156             if (m_hologramEnabled || m_sysAudioEnabled)
00157             {
00158                 return addEffectTask.then([this, saveFile]()
00159                 {
00160                     // When all effects are added, start video recording
00161                     auto encodingProperties = MediaProperties::MediaEncodingProfile::CreateMp4(MediaProperties::VideoEncodingQuality::Auto);
00162
00163                     return Concurrency::create_task(m_mediaCapture->StartRecordToStorageFileAsync(encodingProperties, saveFile)).then([this]()
00164                     {
00165                         auto lock = m_lock.LockExclusive();
00166                         OutputDebugString(L"Recording Started\n");
00167                         m_currentState = Recording;
00168                     });
00169                 });
00170             }
00171             else
00172             {
00173                 // Start video recording without any effects
00174                 auto encodingProperties = MediaProperties::MediaEncodingProfile::CreateMp4(MediaProperties::VideoEncodingQuality::Auto);
00175
00176                 return Concurrency::create_task(m_mediaCapture->StartRecordToStorageFileAsync(encodingProperties, saveFile)).then([this]()
00177                 {
00178                     auto lock = m_lock.LockExclusive();
00179                     OutputDebugString(L"Recording Started\n");
00180                     m_currentState = Recording;
00181                 });
00182             }
00183         });
00184     });
00185 }
00186
00187 Concurrency::task<void> MediaCaptureManager::StopRecordingAsync()
00188 {
00189     // Lock to check current state
00190     auto lock = m_lock.LockExclusive();
00191
00192     if (m_currentState != Recording)
00193     {
00194         OutputDebugString(L"Trying to stop recording in invalid state.\n");
00195         throw ref new Platform::FailureException();
00196     }
00197
00198     m_currentState = StoppingRecord;
00199
00200     // Stop video recording
00201     return Concurrency::create_task(m_mediaCapture->StopRecordAsync()).then([this]()
00202     {
00203         auto lock = m_lock.LockExclusive();
00204         OutputDebugString(L"Video Recording Stopped\n");
00205         m_currentState = Initialized;
00206
00207         if (m_videoEffectAdded)
00208         {
00209             // Clear effects in videoRecord stream
00210             Concurrency::create_task(m_mediaCapture->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::VideoRecord)).then([this]()
00211             {
00212                 auto lock = m_lock.LockExclusive();
00213                 OutputDebugString(L"VideoEffect removed\n");
00214                 m_videoEffectAdded = false;
00215
00216                 if (m_audioEffectAdded)
00217                 {
00218                     // Clear effects in audio stream
00219                     Concurrency::create_task(m_mediaCapture->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::Audio)).then([this]()
00220                     {
00221                         auto lock = m_lock.LockExclusive();
00222                         OutputDebugString(L"AudioEffect removed\n");
00223                         m_audioEffectAdded = false;
00224                     });
00225                 }
00226             });
00227         }
00228         else  if (m_audioEffectAdded)
00229         {
00230             // Clear effects in audio stream
00231             Concurrency::create_task(m_mediaCapture->ClearEffectsAsync(Windows::Media::Capture::MediaStreamType::Audio)).then([this]()
00232             {
00233                 auto lock = m_lock.LockExclusive();
00234                 OutputDebugString(L"AudioEffect removed\n");
00235                 m_audioEffectAdded = false;
00236             });
00237         }
00238     });
00239 }
00240
00241 Concurrency::task<void> MediaCaptureManager::TakePhotoAsync()
00242 {
00243     // Lock to check current state
00244     auto lock = m_lock.LockExclusive();
00245
00246     if (m_currentState != Initialized)
00247     {
00248         OutputDebugString(L"Trying to take photo in invalid state.\n");
00249         throw ref new Platform::FailureException();
00250     }
00251
00252     m_currentState = TakingPhoto;
00253
00254     return Concurrency::create_task(Windows::Storage::KnownFolders::GetFolderForUserAsync(nullptr, Windows::Storage::KnownFolderId::CameraRoll)).then([this](Windows::Storage::StorageFolder ^folder)
00255     {
00256         if (!folder)
00257         {
00258             OutputDebugString(L"Can't find camera roll folder for this user\n");
00259             throw ref new Platform::FailureException();
00260         }
00261
00262         // Create storage file for picture
00263         return Concurrency::create_task(folder->CreateFileAsync(L"MRCPhoto.jpg", Windows::Storage::CreationCollisionOption::GenerateUniqueName)).then([this](Windows::Storage::StorageFile ^saveFile)
00264         {
00265             if (!saveFile)
00266             {
00267                 OutputDebugString(L"Can't create MRC Photo file\n");
00268                 throw ref new Platform::FailureException();
00269             }
00270
00271             auto lock = m_lock.LockShared();
00272
00273             if (m_hologramEnabled)
00274             {
00275                 // Add video effect on photo stream
00276                 auto mrcVideoEffectDefinition = ref new MrcEffectDefinitions::MrcVideoEffectDefinition;
00277                 mrcVideoEffectDefinition->StreamType = MediaStreamType::Photo;
00278
00279                 return Concurrency::create_task(m_mediaCapture->AddVideoEffectAsync(mrcVideoEffectDefinition, MediaStreamType::Photo)).then([this, saveFile](IMediaExtension^ videoExtension)
00280                 {
00281                     OutputDebugString(L"VideoEffect Added\n");
00282                     m_photoEffectAdded = true;
00283
00284                     // Taking picture
00285                     auto encodingProperties = MediaProperties::ImageEncodingProperties::CreateJpeg();
00286
00287                     return Concurrency::create_task(m_mediaCapture->CapturePhotoToStorageFileAsync(encodingProperties, saveFile)).then([this]()
00288                     {
00289                         auto lock = m_lock.LockExclusive();
00290                         OutputDebugString(L"Photo taken\n");
00291                         m_currentState = Initialized;
00292
00293                         return Concurrency::create_task(m_mediaCapture->ClearEffectsAsync(MediaStreamType::Photo)).then([this]()
00294                         {
00295                             auto lock = m_lock.LockExclusive();
00296                             OutputDebugString(L"PhotoEffect removed\n");
00297                             m_photoEffectAdded = false;
00298                         });
00299                     });
00300                 });
00301             }
00302             else
00303             {
00304                 // Taking picture without any effect
00305                 auto encodingProperties = MediaProperties::ImageEncodingProperties::CreateJpeg();
00306
00307                 return Concurrency::create_task(m_mediaCapture->CapturePhotoToStorageFileAsync(encodingProperties, saveFile)).then([this]()
00308                 {
00309                     auto lock = m_lock.LockExclusive();
00310                     OutputDebugString(L"Photo taken\n");
00311                     m_currentState = Initialized;
00312                 });
00313             }
00314         });
00315     });
00316 }
00317
00318 bool MediaCaptureManager::CanTakePhoto()
00319 {
00320     auto lock = m_lock.LockShared();
00321     bool ret = false;
00322
00323     if (m_currentState == Initialized)
00324     {
00325         ret = true;
00326     }
00327
00328     return ret;
00329 }
00330
00331 bool MediaCaptureManager::CanToggleVideo()
00332 {
00333     auto lock = m_lock.LockShared();
00334     bool ret = false;
00335
00336     if (m_currentState == Initialized || m_currentState == Recording)
00337     {
00338         ret = true;
00339     }
00340
00341     return ret;
00342 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlLite/cpp/Scenario3_XmlWriterLite.xaml.cpp Source File

  • XmlLite
  • cpp

Scenario3_XmlWriterLite.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_XmlWriterLite.xaml.h"
00014
00015 using namespace SDKTemplate::XmlLite;
00016
00017 using namespace Concurrency;
00018 using namespace Microsoft::WRL;
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Storage;
00023 using namespace Windows::Storage::Streams;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Controls::Primitives;
00027 using namespace Windows::UI::Xaml::Data;
00028 using namespace Windows::UI::Xaml::Input;
00029 using namespace Windows::UI::Xaml::Media;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00033
00034 Scenario3::Scenario3() : rootPage(MainPage::Current)
00035 {
00036     InitializeComponent();
00037 }
00038
00039 void Scenario3::DoSomething_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00040 {
00041     Button^ b = safe_cast<Button^>(sender);
00042     StorageFolder^ folder = Windows::Storage::ApplicationData::Current->LocalFolder;
00043
00044     create_task(folder->CreateFileAsync(L"XmlWriterLiteOutput.xml", CreationCollisionOption::ReplaceExisting)).then([this](StorageFile^ file)
00045     {
00046         create_task(file->OpenAsync(FileAccessMode::ReadWrite)).then([file, this](IRandomAccessStream^ writeStream)
00047         {
00048             HRESULT hr = WriteXml(writeStream);
00049             if (FAILED(hr))
00050             {
00051                 OutputTextBlock1->Text = L"Exception occured while writing the xml file, and the error code is " + hr.ToString();
00052                 rootPage->NotifyUser("Exception occured!", NotifyType::ErrorMessage);
00053             }
00054             else
00055             {
00056                 OutputTextBlock1->Text = L"File is written to " + file->Path + L" successfully";
00057             }
00058         });
00059     });
00060 }
00061
00062 HRESULT Scenario3::WriteXml(IRandomAccessStream^ randomAccessWriteStream)
00063 {
00064     StorageFolder^ installFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;
00065
00066     create_task(installFolder->GetFileAsync("Stocks.xml")).then([](StorageFile^ file)
00067     {
00068         return file->OpenAsync(FileAccessMode::Read);
00069     }).then([=](IRandomAccessStream^ randomAccessReadStream)
00070     {
00071         HRESULT hr = S_OK;
00072         ComPtr<IStream> readStream;
00073         ComPtr<IStream> writeStream;
00074         ComPtr<IXmlReader> reader;
00075         ComPtr<IXmlWriterLite> writer;
00076
00077         ChkHr(::CreateStreamOverRandomAccessStream(randomAccessWriteStream, IID_PPV_ARGS(&writeStream)));
00078         ChkHr(::CreateXmlWriter(IID_PPV_ARGS(&writer), nullptr));
00079         ChkHr(writer->SetOutput(writeStream.Get()));
00080
00081         ChkHr(::CreateStreamOverRandomAccessStream(randomAccessReadStream, IID_PPV_ARGS(&readStream)));
00082         ChkHr(::CreateXmlReader(IID_PPV_ARGS(&reader), nullptr));
00083         ChkHr(reader->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit));
00084         ChkHr(reader->SetInput(readStream.Get()));
00085
00086         ChkHr(ReadAndWrite(reader.Get(), writer.Get()));
00087
00088         return hr;
00089     });
00090
00091     return S_FALSE;
00092 }
00093
00094 HRESULT Scenario3::ReadAndWrite(IXmlReader* reader, IXmlWriterLite* writer)
00095 {
00096     HRESULT     hr;
00097     XmlNodeType nodeType;
00098
00099     while ((hr = reader->Read(&nodeType)) == S_OK)
00100     {
00101         PCWSTR     qualifiedName = nullptr;
00102         PCWSTR     value = nullptr;
00103         UINT       qualifiedNameSize = 0;
00104         UINT       valueSize = 0;
00105
00106         switch (nodeType)
00107         {
00108         case XmlNodeType_Element:
00109         {
00110             ChkHr(reader->GetQualifiedName(&qualifiedName, &qualifiedNameSize));
00111             ChkHr(writer->WriteStartElement(qualifiedName, qualifiedNameSize));
00112             while ((hr = reader->MoveToNextAttribute()) == S_OK)
00113             {
00114                 ChkHr(reader->GetQualifiedName(&qualifiedName, &qualifiedNameSize));
00115                 ChkHr(reader->GetValue(&value, &valueSize));
00116                 ChkHr(writer->WriteAttributeString(qualifiedName, qualifiedNameSize, value, valueSize));
00117             }
00118             ChkHr(reader->MoveToElement());
00119             if (reader->IsEmptyElement())
00120             {
00121                 ChkHr(reader->GetQualifiedName(&qualifiedName, &qualifiedNameSize));
00122                 ChkHr(writer->WriteEndElement(qualifiedName, qualifiedNameSize));
00123             }
00124             break;
00125         }
00126         case XmlNodeType_Text:
00127             ChkHr(reader->GetValue(&value, nullptr));
00128             ChkHr(writer->WriteString(value));
00129             break;
00130
00131         case XmlNodeType_CDATA:
00132             ChkHr(reader->GetValue(&value, nullptr));
00133             ChkHr(writer->WriteCData(value));
00134             break;
00135
00136         case XmlNodeType_ProcessingInstruction:
00137             ChkHr(reader->GetQualifiedName(&qualifiedName, nullptr));
00138             ChkHr(reader->GetValue(&value, nullptr));
00139             ChkHr(writer->WriteProcessingInstruction(qualifiedName, value));
00140             break;
00141
00142         case XmlNodeType_Comment:
00143             ChkHr(reader->GetValue(&value, nullptr));
00144             ChkHr(writer->WriteComment(value));
00145             break;
00146
00147         case XmlNodeType_DocumentType:
00148         {
00149             PCWSTR publicId = nullptr;
00150             PCWSTR systemId = nullptr;
00151
00152             ChkHr(reader->GetQualifiedName(&qualifiedName, nullptr));
00153             ChkHr(reader->GetValue(&value, nullptr));
00154             if (reader->MoveToAttributeByName(L"PUBLIC", nullptr) == S_OK)
00155             {
00156                 reader->GetValue(&publicId, nullptr);
00157             }
00158             if (reader->MoveToAttributeByName(L"SYSTEM", nullptr) == S_OK)
00159             {
00160                 ChkHr(reader->GetValue(&systemId, nullptr));
00161             }
00162             ChkHr(writer->WriteDocType(
00163                 qualifiedName,
00164                 publicId,
00165                 systemId,
00166                 value));
00167             break;
00168         }
00169         case XmlNodeType_Whitespace:
00170             ChkHr(reader->GetValue(&value, nullptr));
00171             ChkHr(writer->WriteWhitespace(value));
00172             break;
00173
00174         case XmlNodeType_EndElement:
00175             ChkHr(reader->GetQualifiedName(&qualifiedName, &qualifiedNameSize));
00176             ChkHr(writer->WriteFullEndElement(qualifiedName, qualifiedNameSize));
00177             break;
00178
00179         default:
00180             break;
00181         }
00182     }
00183
00184     return hr;
00185 }
Generated on Fri Nov 15 2024 22:22:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteColorGlyph/cpp/DeviceResources.h Source File

  • DWriteColorGlyph
  • cpp

DeviceResources.h

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 namespace DX
00011 {
00012     // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created.
00013     interface IDeviceNotify
00014     {
00015         virtual void OnDeviceLost() = 0;
00016         virtual void OnDeviceRestored() = 0;
00017     };
00018
00019     // Controls all the DirectX device resources.
00020     class DeviceResources
00021     {
00022     public:
00023         DeviceResources();
00024         void SetWindow(Windows::UI::Core::CoreWindow^ window);
00025         void SetLogicalSize(Windows::Foundation::Size logicalSize);
00026         void SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation);
00027         void SetDpi(float dpi);
00028         void ValidateDevice();
00029         void HandleDeviceLost();
00030         void RegisterDeviceNotify(IDeviceNotify* deviceNotify);
00031         void Trim();
00032         void Present();
00033
00034         // Device Accessors.
00035         Windows::Foundation::Size GetOutputSize() const                 { return m_outputSize; }
00036         Windows::Foundation::Size GetLogicalSize() const                { return m_logicalSize; }
00037         Windows::UI::Core::CoreWindow^ GetWindow() const                { return m_window.Get(); }
00038
00039         // D3D Accessors.
00040         ID3D11Device2*          GetD3DDevice() const                    { return m_d3dDevice.Get(); }
00041         ID3D11DeviceContext2*   GetD3DDeviceContext() const             { return m_d3dContext.Get(); }
00042         IDXGISwapChain1*        GetSwapChain() const                    { return m_swapChain.Get(); }
00043         D3D_FEATURE_LEVEL       GetDeviceFeatureLevel() const           { return m_d3dFeatureLevel; }
00044         DirectX::XMFLOAT4X4     GetOrientationTransform3D() const       { return m_orientationTransform3D; }
00045
00046         // D2D Accessors.
00047         ID2D1Factory5*          GetD2DFactory() const                   { return m_d2dFactory.Get(); }
00048         ID2D1Device4*           GetD2DDevice() const                    { return m_d2dDevice.Get(); }
00049         ID2D1DeviceContext4*    GetD2DDeviceContext() const             { return m_d2dContext.Get(); }
00050         ID2D1Bitmap1*           GetD2DTargetBitmap() const              { return m_d2dTargetBitmap.Get(); }
00051         IDWriteFactory4*        GetDWriteFactory() const                { return m_dwriteFactory.Get(); }
00052         IWICImagingFactory2*    GetWicImagingFactory() const            { return m_wicFactory.Get(); }
00053         D2D1::Matrix3x2F        GetOrientationTransform2D() const       { return m_orientationTransform2D; }
00054
00055     private:
00056         void CreateDeviceIndependentResources();
00057         void CreateDeviceResources();
00058         void CreateWindowSizeDependentResources();
00059
00060         DXGI_MODE_ROTATION ComputeDisplayRotation();
00061
00062         // Direct3D objects.
00063         Microsoft::WRL::ComPtr<ID3D11Device2>           m_d3dDevice;
00064         Microsoft::WRL::ComPtr<ID3D11DeviceContext2>    m_d3dContext;
00065         Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00066
00067         // Direct2D drawing components.
00068         Microsoft::WRL::ComPtr<ID2D1Factory5>       m_d2dFactory;
00069         Microsoft::WRL::ComPtr<ID2D1Device4>        m_d2dDevice;
00070         Microsoft::WRL::ComPtr<ID2D1DeviceContext4> m_d2dContext;
00071         Microsoft::WRL::ComPtr<ID2D1Bitmap1>        m_d2dTargetBitmap;
00072
00073         // DirectWrite drawing components.
00074         Microsoft::WRL::ComPtr<IDWriteFactory4>     m_dwriteFactory;
00075         Microsoft::WRL::ComPtr<IWICImagingFactory2> m_wicFactory;
00076
00077         // Cached reference to the Window.
00078         Platform::Agile<Windows::UI::Core::CoreWindow>  m_window;
00079
00080         // Cached device properties.
00081         D3D_FEATURE_LEVEL                               m_d3dFeatureLevel;
00082         Windows::Foundation::Size                       m_d3dRenderTargetSize;
00083         Windows::Foundation::Size                       m_outputSize;
00084         Windows::Foundation::Size                       m_logicalSize;
00085         Windows::Graphics::Display::DisplayOrientations m_nativeOrientation;
00086         Windows::Graphics::Display::DisplayOrientations m_currentOrientation;
00087         float                                           m_dpi;
00088
00089         // Transforms used for display orientation.
00090         D2D1::Matrix3x2F    m_orientationTransform2D;
00091         DirectX::XMFLOAT4X4 m_orientationTransform3D;
00092
00093         // The IDeviceNotify can be held directly as it owns the DeviceResources.
00094         IDeviceNotify* m_deviceNotify;
00095     };
00096 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SimpleTaskCompletionSource< void > Member List

This is the complete list of members for SimpleTaskCompletionSource< void >, including all inherited members.
SetResult() | SimpleTaskCompletionSource< void > | [inline]
SimpleTaskCompletionSource() | SimpleTaskCompletionSource< void > | [inline]
Task() | SimpleTaskCompletionSource< void > | [inline]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cs/Scenario1_Data.xaml.cs Source File

  • Calendar
  • cs

Scenario1_Data.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.Foundation;
00013 using Windows.Globalization;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario1_Data : Page
00020     {
00021         public Scenario1_Data()
00022         {
00023             this.InitializeComponent();
00024         }
00025
00026         private string ReportCalendarData(Calendar calendar, string calendarLabel)
00027         {
00028             string results = calendarLabel + ": " + calendar.GetCalendarSystem() + "\n";
00029             results += "Name of Month: " + calendar.MonthAsSoloString() + "\n";
00030             results += "Day of Month: " + calendar.DayAsPaddedString(2) + "\n";
00031             results += "Day of Week: " + calendar.DayOfWeekAsSoloString() + "\n";
00032             results += "Year: " + calendar.YearAsString() + "\n";
00033             results += "\n";
00034             return results;
00035         }
00036
00037         private void ShowResults_Click(object sender, RoutedEventArgs e)
00038         {
00039             // This scenario uses the Windows.Globalization.Calendar class to display the parts of a date.
00040
00041             // Create Calendar objects using different constructors.
00042             Calendar calendar = new Calendar();
00043             Calendar japaneseCalendar = new Calendar(new[] { "ja-JP" }, CalendarIdentifiers.Japanese, ClockIdentifiers.TwelveHour);
00044             Calendar hebrewCalendar = new Calendar(new[] { "he-IL" }, CalendarIdentifiers.Hebrew, ClockIdentifiers.TwentyFourHour);
00045
00046             // Display the results
00047             OutputTextBlock.Text =
00048                 ReportCalendarData(calendar, "User's default calendar system") +
00049                 ReportCalendarData(japaneseCalendar, "Calendar system") +
00050                 ReportCalendarData(hebrewCalendar, "Calendar system");
00051         }
00052     }
00053 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SimpleTaskCompletionSource< T > Member List

This is the complete list of members for SimpleTaskCompletionSource< T >, including all inherited members.
SetResult(T value) | SimpleTaskCompletionSource< T > | [inline]
Task() | SimpleTaskCompletionSource< T > | [inline]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundSensors/cs/BackgroundTask/Scenario1_BackgroundTask.cs Source File

  • BackgroundSensors
  • cs
  • BackgroundTask

Scenario1_BackgroundTask.cs

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 using System;
00004 using System.Collections.Generic;
00005 using System.Linq;
00006 using System.Text;
00007 using System.Threading.Tasks;
00008
00009 using Windows.ApplicationModel.Background;
00010 using Windows.Devices.Background;
00011 using Windows.Devices.Sensors;
00012 using Windows.Foundation;
00013 using Windows.Storage;
00014
00015 namespace BackgroundTask
00016 {
00017     public sealed class Scenario1_BackgroundTask : IBackgroundTask, IDisposable
00018     {
00019         private Accelerometer Accelerometer;
00020         private BackgroundTaskDeferral Deferral;
00021         private ulong SampleCount;
00022
00023         /// <summary>
00024         /// Background task entry point.
00025         /// </summary>
00026         /// <param name="taskInstance"></param>
00027         public void Run(IBackgroundTaskInstance taskInstance)
00028         {
00029             Accelerometer = Accelerometer.GetDefault();
00030
00031             if (null != Accelerometer)
00032             {
00033                 SampleCount = 0;
00034
00035                 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00036                 uint minReportIntervalMsecs = Accelerometer.MinimumReportInterval;
00037                 Accelerometer.ReportInterval = minReportIntervalMsecs > 16 ? minReportIntervalMsecs : 16;
00038
00039                 // Subscribe to accelerometer ReadingChanged events.
00040                 Accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);
00041
00042                 // Take a deferral that is released when the task is completed.
00043                 Deferral = taskInstance.GetDeferral();
00044
00045                 // Get notified when the task is canceled.
00046                 taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
00047
00048                 // Store a setting so that the app knows that the task is running.
00049                 ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = true;
00050             }
00051         }
00052
00053         /// <summary>
00054         /// Called when the background task is canceled by the app or by the system.
00055         /// </summary>
00056         /// <param name="sender"></param>
00057         /// <param name="reason"></param>
00058         private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
00059         {
00060             ApplicationData.Current.LocalSettings.Values["TaskCancelationReason"] = reason.ToString();
00061             ApplicationData.Current.LocalSettings.Values["SampleCount"] = SampleCount;
00062             ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = false;
00063
00064             if (null != Accelerometer)
00065             {
00066                 Accelerometer.ReadingChanged -= new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);
00067                 Accelerometer.ReportInterval = 0;
00068             }
00069
00070             // Complete the background task (this raises the OnCompleted event on the corresponding BackgroundTaskRegistration).
00071             Deferral.Complete();
00072         }
00073
00074         /// <summary>
00075         /// Frees resources held by this background task.
00076         /// </summary>
00077         public void Dispose()
00078         {
00079         }
00080
00081         /// <summary>
00082         /// This is the event handler for acceleroemter ReadingChanged events.
00083         /// </summary>
00084         /// <param name="sender"></param>
00085         /// <param name="e"></param>
00086         private void ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e)
00087         {
00088             SampleCount++;
00089
00090             // Save the sample count if the foreground app is visible.
00091             bool appVisible = (bool)ApplicationData.Current.LocalSettings.Values["IsAppVisible"];
00092             if (appVisible)
00093             {
00094                 ApplicationData.Current.LocalSettings.Values["SampleCount"] = SampleCount;
00095             }
00096         }
00097     }
00098 }
Generated on Fri Nov 15 2024 22:18:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteLineSpacingModes/cpp/DWriteLineSpacingModes/Scenario3_ProportionalSpacing.xaml.cpp Source File

  • DWriteLineSpacingModes
  • cpp
  • DWriteLineSpacingModes

Scenario3_ProportionalSpacing.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_ProportionalSpacing.xaml.h"
00014
00015 using namespace SDKTemplate;
00016 using namespace DWriteTextLayoutImplementation;
00017
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Media;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029
00030 Scenario3_ProportionalSpacing::Scenario3_ProportionalSpacing()
00031 {
00032     InitializeComponent();
00033
00034     String^ text =
00035         L"Lorem ipsum dolor sit amet, consectetur 😐 adipiscing elit, sed do eiusmod tempor "
00036         L"incididunt ut labore et dolore magna aliqua.";
00037
00038     // Create the TextLayout for our text content.
00039     m_textLayout = ref new TextLayout(
00040         text,
00041         L"en-US",
00042         L"Cambria Math",
00043         24.0f, // text size (DIPs)
00044         static_cast<uint32>(floor(TextLayoutImage->Width)), // text layout width
00045         LineSpacingMethod::Proportional
00046         );
00047
00048     // Get the array of computed line metrics for the text layout -- we'll
00049     // report results for the first line.
00050     m_textLayoutLineMetrics = m_textLayout->GetTextLayoutLineMetrics();
00051
00052     // Create a new TextLayoutImageSource based on the text layout, have
00053     // it draw, and then use it as the source for the XAML image element.
00054     m_textLayoutImageSource = ref new TextLayoutImageSource(
00055         m_textLayout,
00056         static_cast<uint32>(floor(TextLayoutImage->Width)),
00057         static_cast<uint32>(floor(TextLayoutImage->Height))
00058         );
00059     m_textLayoutImageSource->Draw();
00060     TextLayoutImage->Source = m_textLayoutImageSource;
00061 }
00062
00063
00064 void Scenario3_ProportionalSpacing::IsFontLineGapUsageEnabled::set(bool value)
00065 {
00066     m_textLayout->FontLineGapUsage = (value) ? FontLineGapUsage::Enabled : FontLineGapUsage::Disabled;
00067     m_textLayoutLineMetrics = m_textLayout->GetTextLayoutLineMetrics();
00068     m_textLayoutImageSource->Draw();
00069     this->Bindings->Update();
00070 }
00071
00072
00073 void Scenario3_ProportionalSpacing::LineSpacingHeight::set(double value)
00074 {
00075     m_textLayout->LineSpacingHeight = static_cast<float>(value);
00076     m_textLayoutLineMetrics = m_textLayout->GetTextLayoutLineMetrics();
00077     m_textLayoutImageSource->Draw();
00078     this->Bindings->Update();
00079 }
00080
00081
00082 void Scenario3_ProportionalSpacing::LineSpacingBaseline::set(double value)
00083 {
00084     m_textLayout->LineSpacingBaseline = static_cast<float>(value);
00085     m_textLayoutLineMetrics = m_textLayout->GetTextLayoutLineMetrics();
00086     m_textLayoutImageSource->Draw();
00087     this->Bindings->Update();
00088 }
00089
00090
00091 void Scenario3_ProportionalSpacing::LineSpacingLeadingBefore::set(double value)
00092 {
00093     m_textLayout->LineSpacingLeadingBefore = static_cast<float>(value);
00094     m_textLayoutLineMetrics = m_textLayout->GetTextLayoutLineMetrics();
00095     m_textLayoutImageSource->Draw();
00096     this->Bindings->Update();
00097 }
00098
00099
00100
00101 void SDKTemplate::Scenario3_ProportionalSpacing::SingleSpace_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00102 {
00103     this->HeightSlider->Value = 1.0;
00104     this->BaselineSlider->Value = 1.0;
00105     this->LeadingBeforeSlider->Value = 0.0;
00106 }
00107
00108
00109 void SDKTemplate::Scenario3_ProportionalSpacing::OneAndHalfSpace_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00110 {
00111     this->HeightSlider->Value = 1.5;
00112     this->BaselineSlider->Value = 1.5;
00113     this->LeadingBeforeSlider->Value = 0.0;
00114 }
00115
00116
00117 void SDKTemplate::Scenario3_ProportionalSpacing::DoubleSpace_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00118 {
00119     this->HeightSlider->Value = 2.0;
00120     this->BaselineSlider->Value = 2.0;
00121     this->LeadingBeforeSlider->Value = 0.0;
00122 }
00123
00124
00125 void SDKTemplate::Scenario3_ProportionalSpacing::DoubleSpaceHalfLeading_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00126 {
00127     // For CSS "half-leading" guidance, see http://www.w3.org/TR/CSS21/visudet.html#leading.
00128     this->HeightSlider->Value = 2.0;
00129     this->BaselineSlider->Value = 1.0;
00130     this->LeadingBeforeSlider->Value = 0.5;
00131 }
Generated on Fri Nov 15 2024 22:19:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/scenario8.xaml.h Source File

  • ApplicationResources
  • cpp

scenario8.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario8.xaml.h
00013 // Declaration of the Scenario8 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario8.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024         [Windows::Foundation::Metadata::WebHostHidden]
00025         public ref class Scenario8 sealed
00026         {
00027         public:
00028             Scenario8();
00029             void ShowText();
00030
00031         private:
00032             void Scenario8::LanguageOverrideCombo_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00033             int lastSelectedIndex;
00034
00035             void AddItemForLanguageTag(Platform::String^ languageTag);
00036             void PopulateComboBox();
00037             void UpdateCurrentAppLanguageMessage();
00038             Platform::String^ GetAppLanguagesAsFormattedString();
00039         };
00040
00041
00042
00043 }
Generated on Fri Nov 15 2024 22:18:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1 Member List

This is the complete list of members for Scenario1, including all inherited members.
Apply_Click(object sender, RoutedEventArgs e) | Scenario1 | [inline, private]
Close_Click(object sender, RoutedEventArgs e) | Scenario1 | [inline, private]
DisplayImageUIAsync(StorageFile file, IDictionary< string, string > propertyText) | Scenario1 | [inline, private]
E_INVALIDARG | Scenario1 | [private]
GetImagePropertiesForDisplay(IDictionary< string, object > retrievedProps) | Scenario1 | [inline, private]
LoadFileAsync(StorageFile file) | Scenario1 | [inline, private]
m_fileToken | Scenario1 | [private]
m_futureAccess | Scenario1 | [private]
m_imageProperties | Scenario1 | [private]
m_localSettings | Scenario1 | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1 | [inline, protected]
Open_Click(object sender, RoutedEventArgs e) | Scenario1 | [inline, private]
ResetPersistedState() | Scenario1 | [inline, private]
ResetSessionState() | Scenario1 | [inline, private]
RestoreDataFromPersistedState() | Scenario1 | [inline, private]
rootPage | Scenario1 | [private]
SaveDataToPersistedState(object sender, SuspendingEventArgs args) | Scenario1 | [inline, private]
Scenario1() | Scenario1 | [inline]
Generated on Fri Nov 15 2024 22:24:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SourceHandler Member List

This is the complete list of members for SourceHandler, including all inherited members.
ComposeStroke() | SourceHandler | [protected, virtual]
GetCurrentTool() const | SourceHandler | [inline]
GetPosition() const | SourceHandler | [inline]
GetSourceKind() const | SourceHandler | [inline]
GetToolPosition() const | SourceHandler | [inline, virtual]
GetToolScale() const | SourceHandler | [inline, virtual]
IsPositionCurrent() const | SourceHandler | [inline]
m_currentMode | SourceHandler | [protected]
m_currentStroke | SourceHandler | [protected]
m_currentTool | SourceHandler | [protected]
m_eventsHandler | SourceHandler | [protected]
m_modelConstantBufferData | SourceHandler | [protected]
m_position | SourceHandler | [protected]
m_refreshModelConstantBufferData | SourceHandler | [protected]
m_sourceId | SourceHandler | [protected]
m_sourceKind | SourceHandler | [protected]
m_targetBoard | SourceHandler | [protected]
m_toolPosition | SourceHandler | [protected]
Make(std::shared_ptr< SourceHandler > *handler, Windows::UI::Input::Spatial::SpatialInteractionSource^source, ISourceCommandHandler *eventsHandler, std::shared_ptr< Whiteboard > &target) | SourceHandler | [static]
OnInteractionDetected(Windows::UI::Input::Spatial::SpatialInteraction^interaction, Windows::Perception::Spatial::SpatialCoordinateSystem^coordinateSystem) | SourceHandler | [inline, virtual]
OnSourcePressed(Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs^args) | SourceHandler | [inline, virtual]
OnSourceUpdated(Windows::UI::Input::Spatial::SpatialInteractionSourceState^state, Windows::Perception::Spatial::SpatialCoordinateSystem^coordinateSystem) | SourceHandler | [virtual]
Render(ID3D11DeviceContext *pDeviceContext, IRenderer *pRenderingHelper) override | SourceHandler | [virtual]
SetApplicationMode(ApplicationMode newMode) | SourceHandler | [inline]
SetCurrentTool(std::shared_ptr< Tool > tool) | SourceHandler |
SourceHandler(Windows::UI::Input::Spatial::SpatialInteractionSource^source, ISourceCommandHandler *eventsHandler, std::shared_ptr< Whiteboard > &target) | SourceHandler | [protected]
SourceId() const | SourceHandler | [inline]
TerminateStroke() | SourceHandler | [protected, virtual]
Update(ID3D11DeviceContext *pDeviceContext) override | SourceHandler | [virtual]
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/ActivationTypes/System/Snooze/CustomContent/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • ActivationTypes
  • System
  • Snooze
  • CustomContent

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Notifications;
00003 using Windows.UI.Popups;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00008
00009 namespace Notifications.ScenarioPages.Toasts.ActivationTypes.System.Snooze.CustomContent
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     public sealed partial class ScenarioElement : UserControl
00015     {
00016         public ScenarioElement()
00017         {
00018             this.InitializeComponent();
00019         }
00020
00021         private void UserControl_Loaded(object sender, RoutedEventArgs e)
00022         {
00023             Initialize();
00024         }
00025
00026
00027         private void Initialize()
00028         {
00029             // Clear all existing notifications
00030             ToastNotificationManager.History.Clear();
00031
00032             // Pop reminder
00033             popToastControl.Payload =
00034                 $@"
00035                 <toast scenario='reminder' launch='args'>
00036                     <visual>
00037                         <binding template='ToastGeneric'>
00038                             <text>System Snoozing (Custom Content)</text>
00039                             <text>The button for snoozing should have the content ""my snooze"" on it.</text>
00040                         </binding>
00041                     </visual>
00042
00043                     <actions>
00044
00045                         <input id='snoozeTime' type='selection' defaultInput='1'>
00046                             <selection id='1' content = '1 minute'/>
00047                             <selection id='2' content = '2 minutes'/>
00048                             <selection id='5' content = '5 minutes'/>
00049                         </input>
00050
00051                         <action activationType='system' arguments='snooze' hint-inputId='snoozeTime' content='my snooze'/>
00052
00053                         <action activationType='system' arguments='dismiss' content='dismiss (ignore my text)' />
00054
00055                     </actions>
00056                 </toast>";
00057         }
00058
00059         private async void Error(string message)
00060         {
00061             await new MessageDialog(message, "ERROR").ShowAsync();
00062         }
00063     }
00064 }
Generated on Fri Nov 15 2024 22:20:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/Scenario2_DeviceWatcher.xaml.cpp Source File

  • DeviceEnumerationAndPairing
  • cpp

Scenario2_DeviceWatcher.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario2_DeviceWatcher.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Platform::Collections;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::UI::Core;
00013 using namespace Windows::UI::Xaml;
00014 using namespace Windows::UI::Xaml::Controls;
00015 using namespace Windows::UI::Xaml::Controls::Primitives;
00016 using namespace Windows::UI::Xaml::Data;
00017 using namespace Windows::UI::Xaml::Input;
00018 using namespace Windows::UI::Xaml::Media;
00019 using namespace Windows::UI::Xaml::Navigation;
00020 using namespace Windows::Devices::Enumeration;
00021
00022 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00023
00024 Scenario2_DeviceWatcher::Scenario2_DeviceWatcher()
00025 {
00026     InitializeComponent();
00027     deviceWatcherHelper = ref new DeviceWatcherHelper(resultCollection, Dispatcher);
00028 }
00029
00030 void Scenario2_DeviceWatcher::OnNavigatedTo(NavigationEventArgs^ e)
00031 {
00032     resultsListView->ItemsSource = resultCollection;
00033
00034     selectorComboBox->ItemsSource = DeviceSelectorChoices::DeviceWatcherSelectors;
00035     selectorComboBox->SelectedIndex = 0;
00036 }
00037
00038 void Scenario2_DeviceWatcher::OnNavigatedFrom(NavigationEventArgs^ e)
00039 {
00040     deviceWatcherHelper->Reset();
00041 }
00042
00043 void Scenario2_DeviceWatcher::StartWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045     StartWatcher();
00046 }
00047
00048 void Scenario2_DeviceWatcher::StopWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00049 {
00050     StopWatcher();
00051 }
00052
00053 void Scenario2_DeviceWatcher::StartWatcher()
00054 {
00055     startWatcherButton->IsEnabled = false;
00056     resultCollection->Clear();
00057
00058     // First get the device selector chosen by the UI.
00059     DeviceSelectorInfo^ deviceSelectorInfo = safe_cast<DeviceSelectorInfo^>(selectorComboBox->SelectedItem);
00060
00061     DeviceWatcher^ deviceWatcher;
00062     if (nullptr == deviceSelectorInfo->Selector)
00063     {
00064         // If the a pre-canned device class selector was chosen, call the DeviceClass overload
00065         deviceWatcher = DeviceInformation::CreateWatcher(deviceSelectorInfo->DeviceClassSelector);
00066     }
00067     else if (deviceSelectorInfo->Kind == DeviceInformationKind::Unknown)
00068     {
00069         // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
00070         // Kind will be determined by the selector
00071         deviceWatcher = DeviceInformation::CreateWatcher(
00072             deviceSelectorInfo->Selector,
00073             nullptr // don't request additional properties for this sample
00074             );
00075     }
00076     else
00077     {
00078         // Kind is specified in the selector info
00079         deviceWatcher = DeviceInformation::CreateWatcher(
00080             deviceSelectorInfo->Selector,
00081             nullptr, // don't request additional properties for this sample
00082             deviceSelectorInfo->Kind);
00083     }
00084
00085     rootPage->NotifyUser("Starting Watcher...", NotifyType::StatusMessage);
00086     deviceWatcherHelper->StartWatcher(deviceWatcher);
00087     stopWatcherButton->IsEnabled = true;
00088 }
00089
00090 void Scenario2_DeviceWatcher::StopWatcher()
00091 {
00092     stopWatcherButton->IsEnabled = false;
00093     deviceWatcherHelper->StopWatcher();
00094     startWatcherButton->IsEnabled = true;
00095 }
00096
Generated on Fri Nov 15 2024 22:19:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-SPI/cppwinrt/Scenario1_ReadData.h Source File

  • IoT-SPI
  • cppwinrt

Scenario1_ReadData.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_ReadData.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_ReadData : Scenario1_ReadDataT<Scenario1_ReadData>
00019     {
00020         Scenario1_ReadData();
00021         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00022
00023         fire_and_forget StartStopScenario_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024
00025     private:
00026         Windows::Devices::Spi::SpiDevice adxl345Sensor{ nullptr };
00027         Windows::UI::Xaml::DispatcherTimer timer{ nullptr };
00028         event_token timerEventToken{};
00029
00030         Windows::Foundation::IAsyncAction StartScenarioAsync();
00031         void StopScenario();
00032         void Timer_Tick(Windows::Foundation::IInspectable const& sender, Windows::Foundation::IInspectable const& e);
00033     };
00034 }
00035
00036 namespace winrt::SDKTemplate::factory_implementation
00037 {
00038     struct Scenario1_ReadData : Scenario1_ReadDataT<Scenario1_ReadData, implementation::Scenario1_ReadData>
00039     {
00040     };
00041 }
Generated on Fri Nov 15 2024 22:20:03 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
BindToAny_Checked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
BindToAny_Unchecked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CloseListener_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CloseListenerSocket() | sealed | [private]
CloseSockets_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
connected | sealed | [private]
ConnectSocket_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
EchoMessage(Windows::Networking::Sockets::DatagramSocketMessageReceivedEventArgs^eventArguments) | sealed | [private]
GetWriter() | sealed |
hostName | sealed | [private]
IsConnected() | sealed |
IsMatching(Windows::Networking::HostName^hostName, Platform::String^port) | sealed |
listener | sealed | [private]
ListenerContext(MainPage^rootPage, Windows::Networking::Sockets::DatagramSocket^listener) | sealed |
listenerSocket | sealed | [private]
localHost | sealed |
LocalHostItem(Windows::Networking::HostName^localHostName) | sealed |
localHostItems | sealed | [private]
lock | sealed | [private]
MessageReceived(Windows::Networking::Sockets::DatagramSocket^socket, Windows::Networking::Sockets::DatagramSocketMessageReceivedEventArgs^eventArguments) | sealed | [private]
MulticastRadioButton_Checked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MulticastRadioButton_Unchecked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
NotifyUserFromAsyncThread(Platform::String^message, NotifyType type) | sealed | [private]
NotifyUserFromAsyncThread(Platform::String^message, NotifyType type) | sealed | [private]
NotifyUserFromAsyncThread(Platform::String^message, NotifyType type) | sealed | [private]
OnMessage(Windows::Networking::Sockets::DatagramSocket^socket, Windows::Networking::Sockets::DatagramSocketMessageReceivedEventArgs^eventArguments) | sealed |
OnMessage(Windows::Networking::Sockets::DatagramSocket^socket, Windows::Networking::Sockets::DatagramSocketMessageReceivedEventArgs^eventArguments) | sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | sealed | [protected, virtual]
outputStream | sealed | [private]
PopulateAdapterList() | sealed | [private]
port | sealed | [private]
rootPage | sealed | [private]
Scenario1() | sealed |
Scenario2() | sealed |
Scenario3() | sealed |
Scenario4() | sealed |
Scenario5() | sealed |
SendHello_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SendMessage_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SetConnected() | sealed |
SetupBroadcastScenarioUI() | sealed | [private]
SetupMulticastScenarioUI() | sealed | [private]
socket | sealed | [private]
SocketContext(MainPage^rootPage, Windows::Networking::Sockets::DatagramSocket^socket) | sealed |
StartListener_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartListener_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
writer | sealed | [private]
~ListenerContext() | sealed | [private]
~SocketContext() | sealed | [private]
Generated on Fri Nov 15 2024 22:24:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeferredControlTemplatePart Member List

This is the complete list of members for DeferredControlTemplatePart, including all inherited members.
DeferredControlTemplatePart() DeferredControlTemplatePart [inline]
Generated on Fri Nov 15 2024 22:24:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/StspMediaSink.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

StspMediaSink.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009 #include <CritSec.h>
00010 #include <linklist.h>
00011 #include <BaseAttributes.h>
00012 #include <StspDefs.h>
00013 #include <StspNetwork.h>
00014
00015 namespace Microsoft { namespace Samples { namespace SimpleCommunication {
00016 interface class ISinkCallback;
00017 class CStreamSink;
00018
00019 class CMediaSink
00020     : public Microsoft::WRL::RuntimeClass<
00021            Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >,
00022            ABI::Windows::Media::IMediaExtension,
00023            FtmBase,
00024            IMFMediaSink,
00025            IMFClockStateSink,
00026            IStspSinkInternal>
00027     , public Microsoft::Samples::Common::CBaseAttributes<>
00028 {
00029     InspectableClass(L"Microsoft::Samples::SimpleCommunication::StspMediaSink",BaseTrust)
00030
00031 public:
00032     CMediaSink();
00033     ~CMediaSink();
00034
00035     HRESULT RuntimeClassInitialize(
00036         ISinkCallback ^callback,
00037         Windows::Media::MediaProperties::IMediaEncodingProperties ^audioEncodingProperties,
00038         Windows::Media::MediaProperties::IMediaEncodingProperties ^videoEncodingProperties
00039         );
00040
00041     // IStspSinkInternal
00042     void TriggerAcceptConnection(DWORD connectionId);
00043     void TriggerRefuseConnection(DWORD connectionId);
00044
00045     // IMediaExtension
00046     IFACEMETHOD (SetProperties) (ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration) {return S_OK;}
00047
00048     // IMFMediaSink methods
00049     IFACEMETHOD (GetCharacteristics) (DWORD *pdwCharacteristics);
00050
00051     IFACEMETHOD (AddStreamSink)(
00052         /* [in] */ DWORD dwStreamSinkIdentifier,
00053         /* [in] */ IMFMediaType *pMediaType,
00054         /* [out] */ IMFStreamSink **ppStreamSink);
00055
00056     IFACEMETHOD (RemoveStreamSink) (DWORD dwStreamSinkIdentifier);
00057     IFACEMETHOD (GetStreamSinkCount) (_Out_ DWORD *pcStreamSinkCount);
00058     IFACEMETHOD (GetStreamSinkByIndex) (DWORD dwIndex, _Outptr_ IMFStreamSink **ppStreamSink);
00059     IFACEMETHOD (GetStreamSinkById) (DWORD dwIdentifier, IMFStreamSink **ppStreamSink);
00060     IFACEMETHOD (SetPresentationClock) (IMFPresentationClock *pPresentationClock);
00061     IFACEMETHOD (GetPresentationClock) (IMFPresentationClock **ppPresentationClock);
00062     IFACEMETHOD (Shutdown) ();
00063
00064     // IMFClockStateSink methods
00065     IFACEMETHOD (OnClockStart) (MFTIME hnsSystemTime, LONGLONG llClockStartOffset);
00066     IFACEMETHOD (OnClockStop) (MFTIME hnsSystemTime);
00067     IFACEMETHOD (OnClockPause) (MFTIME hnsSystemTime);
00068     IFACEMETHOD (OnClockRestart) (MFTIME hnsSystemTime);
00069     IFACEMETHOD (OnClockSetRate) (MFTIME hnsSystemTime, float flRate);
00070
00071     LONGLONG GetStartTime() const {return _llStartTime;}
00072
00073     void ReportEndOfStream();
00074     void ReportFormatChange(DWORD streamId);
00075
00076 private:
00077     typedef ComPtrList<IMFStreamSink> StreamContainer;
00078
00079 private:
00080     void StartListening();
00081     void StartReceiving(Network::IMediaBufferWrapper *pReceiveBuffer);
00082     concurrency::task<void> SendPacket(Network::IBufferPacket *pPacket);
00083     String ^PrepareRemoteUrl(StreamSocketInformation ^info);
00084     void SendDescription();
00085
00086     ComPtr<Network::IMediaBufferWrapper> FillStreamDescription(CStreamSink *pStream, StspStreamDescription *pStreamDescription);
00087
00088     void HandleError(HRESULT hr);
00089
00090     void SetMediaStreamProperties(
00091         Windows::Media::Capture::MediaStreamType MediaStreamType,
00092         _In_opt_ Windows::Media::MediaProperties::IMediaEncodingProperties ^mediaEncodingProperties);
00093
00094     HRESULT CheckShutdown() const
00095     {
00096         if (_IsShutdown)
00097         {
00098             return MF_E_SHUTDOWN;
00099         }
00100         else
00101         {
00102             return S_OK;
00103         }
00104     }
00105
00106 private:
00107     long                            _cRef;                      // reference count
00108     CritSec                         _critSec;                   // critical section for thread safety
00109
00110     bool                            _IsShutdown;                // Flag to indicate if Shutdown() method was called.
00111     bool                            _IsConnected;
00112     LONGLONG                        _llStartTime;
00113
00114     ComPtr<IMFPresentationClock>    _spClock;                   // Presentation clock.
00115     Network::INetworkChannel^       _networkSender;
00116     ISinkCallback^                  _callback;
00117     ComPtr<Network::IMediaBufferWrapper> _spReceiveBuffer;
00118     StreamContainer                 _streams;
00119     long                            _cStreamsEnded;
00120     String^                         _remoteUrl;
00121
00122     DWORD                           _waitingConnectionId;
00123 };
00124
00125 }}} // namespace Microsoft::Samples::SimpleCommunication
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Server/stdafx.cpp Source File

  • CustomCapability
  • Service
  • Server

stdafx.cpp

Go to the documentation of this file.
00001 // stdafx.cpp : source file that includes just the standard includes
00002 // RpcServer.pch will be the pre-compiled header
00003 // stdafx.obj will contain the pre-compiled type information
00004
00005 #include "stdafx.h"
00006
00007 // TODO: reference any additional headers you need in STDAFX.H
00008 // and not in this file
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/RecognizerHelper.h Source File

  • SimpleInk
  • cpp

RecognizerHelper.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <map>
00004
00005 namespace SDKTemplate
00006 {
00007     ref class RecognizerHelper sealed
00008     {
00009     public:
00010         static Platform::String^ LanguageTagToRecognizerName(Platform::String^ bcp47tag);
00011
00012     private:
00013         static std::map<Platform::String^, Platform::String^> Bcp47ToRecognizerNameDictionary;
00014     };
00015 }
00016
00017
Generated on Fri Nov 15 2024 22:21:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cppwinrt/Common/StepTimer.h Source File

  • BasicHologram
  • cppwinrt
  • Common

StepTimer.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 namespace DX
00004 {
00005     // Helper class for animation and simulation timing.
00006     class StepTimer
00007     {
00008     public:
00009         StepTimer() :
00010             m_elapsedTicks(0),
00011             m_totalTicks(0),
00012             m_leftOverTicks(0),
00013             m_frameCount(0),
00014             m_framesPerSecond(0),
00015             m_framesThisSecond(0),
00016             m_qpcSecondCounter(0),
00017             m_isFixedTimeStep(false),
00018             m_targetElapsedTicks(TicksPerSecond / 60)
00019         {
00020             m_qpcFrequency = GetPerformanceFrequency();
00021
00022             // Initialize max delta to 1/10 of a second.
00023             m_qpcMaxDelta = m_qpcFrequency / 10;
00024         }
00025
00026         // Get elapsed time since the previous Update call.
00027         uint64_t GetElapsedTicks() const                      { return m_elapsedTicks;                                  }
00028         double GetElapsedSeconds() const                      { return TicksToSeconds(m_elapsedTicks);                  }
00029
00030         // Get total time since the start of the program.
00031         uint64_t GetTotalTicks() const                        { return m_totalTicks;                                    }
00032         double GetTotalSeconds() const                        { return TicksToSeconds(m_totalTicks);                    }
00033
00034         // Get total number of updates since start of the program.
00035         uint32_t GetFrameCount() const                        { return m_frameCount;                                    }
00036
00037         // Get the current framerate.
00038         uint32_t GetFramesPerSecond() const                   { return m_framesPerSecond;                               }
00039
00040         // Set whether to use fixed or variable timestep mode.
00041         void SetFixedTimeStep(bool isFixedTimestep)           { m_isFixedTimeStep = isFixedTimestep;                    }
00042
00043         // Set how often to call Update when in fixed timestep mode.
00044         void SetTargetElapsedTicks(uint64_t targetElapsed)    { m_targetElapsedTicks = targetElapsed;                   }
00045         void SetTargetElapsedSeconds(double targetElapsed)    { m_targetElapsedTicks = SecondsToTicks(targetElapsed);   }
00046
00047         // Integer format represents time using 10,000,000 ticks per second.
00048         static const uint64_t TicksPerSecond = 10'000'000;
00049
00050         static double TicksToSeconds(uint64_t ticks)          { return static_cast<double>(ticks) / TicksPerSecond;     }
00051         static uint64_t SecondsToTicks(double seconds)        { return static_cast<uint64_t>(seconds * TicksPerSecond); }
00052
00053         // Convenient wrapper for QueryPerformanceFrequency. Throws an exception if
00054         // the call to QueryPerformanceFrequency fails.
00055         static inline uint64_t GetPerformanceFrequency()
00056         {
00057             LARGE_INTEGER freq;
00058             if (!QueryPerformanceFrequency(&freq))
00059             {
00060                 winrt::throw_last_error();
00061             }
00062             return freq.QuadPart;
00063         }
00064
00065         // Gets the current number of ticks from QueryPerformanceCounter. Throws an
00066         // exception if the call to QueryPerformanceCounter fails.
00067         static inline int64_t GetTicks()
00068         {
00069             LARGE_INTEGER ticks;
00070             if (!QueryPerformanceCounter(&ticks))
00071             {
00072                 winrt::throw_last_error();
00073             }
00074             return ticks.QuadPart;
00075         }
00076
00077         // After an intentional timing discontinuity (for instance a blocking IO operation)
00078         // call this to avoid having the fixed timestep logic attempt a set of catch-up
00079         // Update calls.
00080
00081         void ResetElapsedTime()
00082         {
00083             m_qpcLastTime = GetTicks();
00084
00085             m_leftOverTicks    = 0;
00086             m_framesPerSecond  = 0;
00087             m_framesThisSecond = 0;
00088             m_qpcSecondCounter = 0;
00089         }
00090
00091         // Update timer state, calling the specified Update function the appropriate number of times.
00092         template<typename TUpdate>
00093         void Tick(const TUpdate& update)
00094         {
00095             // Query the current time.
00096             uint64_t currentTime = GetTicks();
00097             uint64_t timeDelta   = currentTime - m_qpcLastTime;
00098
00099             m_qpcLastTime      = currentTime;
00100             m_qpcSecondCounter += timeDelta;
00101
00102             // Clamp excessively large time deltas (e.g. after paused in the debugger).
00103             if (timeDelta > m_qpcMaxDelta)
00104             {
00105                 timeDelta = m_qpcMaxDelta;
00106             }
00107
00108             // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp.
00109             timeDelta *= TicksPerSecond;
00110             timeDelta /= m_qpcFrequency;
00111
00112             uint32_t lastFrameCount = m_frameCount;
00113
00114             if (m_isFixedTimeStep)
00115             {
00116                 // Fixed timestep update logic
00117
00118                 // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp
00119                 // the clock to exactly match the target value. This prevents tiny and irrelevant errors
00120                 // from accumulating over time. Without this clamping, a game that requested a 60 fps
00121                 // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually
00122                 // accumulate enough tiny errors that it would drop a frame. It is better to just round
00123                 // small deviations down to zero to leave things running smoothly.
00124
00125                 if (abs(static_cast<int64_t>(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000)
00126                 {
00127                     timeDelta = m_targetElapsedTicks;
00128                 }
00129
00130                 m_leftOverTicks += timeDelta;
00131
00132                 while (m_leftOverTicks >= m_targetElapsedTicks)
00133                 {
00134                     m_elapsedTicks   = m_targetElapsedTicks;
00135                     m_totalTicks    += m_targetElapsedTicks;
00136                     m_leftOverTicks -= m_targetElapsedTicks;
00137                     m_frameCount++;
00138
00139                     update();
00140                 }
00141             }
00142             else
00143             {
00144                 // Variable timestep update logic.
00145                 m_elapsedTicks  = timeDelta;
00146                 m_totalTicks   += timeDelta;
00147                 m_leftOverTicks = 0;
00148                 m_frameCount++;
00149
00150                 update();
00151             }
00152
00153             // Track the current framerate.
00154             if (m_frameCount != lastFrameCount)
00155             {
00156                 m_framesThisSecond++;
00157             }
00158
00159             if (m_qpcSecondCounter >= static_cast<uint64_t>(m_qpcFrequency))
00160             {
00161                 m_framesPerSecond   = m_framesThisSecond;
00162                 m_framesThisSecond  = 0;
00163                 m_qpcSecondCounter %= m_qpcFrequency;
00164             }
00165         }
00166
00167     private:
00168
00169         // Source timing data uses QPC units.
00170         uint64_t m_qpcFrequency;
00171         uint64_t m_qpcLastTime;
00172         uint64_t m_qpcMaxDelta;
00173
00174         // Derived timing data uses a canonical tick format.
00175         uint64_t m_elapsedTicks;
00176         uint64_t m_totalTicks;
00177         uint64_t m_leftOverTicks;
00178
00179         // Members for tracking the framerate.
00180         uint32_t m_frameCount;
00181         uint32_t m_framesPerSecond;
00182         uint32_t m_framesThisSecond;
00183         uint64_t m_qpcSecondCounter;
00184
00185         // Members for configuring fixed timestep mode.
00186         bool     m_isFixedTimeStep;
00187         uint64_t m_targetElapsedTicks;
00188     };
00189 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Capabilities/cs/Scenario1_Check.xaml.cs Source File

  • Capabilities
  • cs

Scenario1_Check.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Devices.Geolocation;
00015 using Windows.Foundation;
00016 using Windows.Security.Authorization.AppCapabilityAccess;
00017 using Windows.System;
00018 using Windows.UI.Core;
00019 using Windows.UI.ViewManagement;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Input;
00023 using Windows.UI.Xaml.Navigation;
00024
00025 namespace SDKTemplate
00026 {
00027     public sealed partial class Scenario1_Check : Page
00028     {
00029         private MainPage rootPage = MainPage.Current;
00030         AppCapability locationCapability = null;
00031
00032         public Scenario1_Check()
00033         {
00034             this.InitializeComponent();
00035         }
00036
00037         protected override void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039             // Specify which capability we want to query/monitor.
00040             locationCapability = AppCapability.Create("location");
00041
00042             // Register a handler to be called when access changes.
00043             locationCapability.AccessChanged += OnCapabilityAccessChanged;
00044
00045             // Update UI to match current access.
00046             UpdateCapabilityStatus();
00047         }
00048
00049         protected override void OnNavigatedFrom(NavigationEventArgs e)
00050         {
00051             locationCapability.AccessChanged -= OnCapabilityAccessChanged;
00052         }
00053
00054         async void OnCapabilityAccessChanged(AppCapability sender, object e)
00055         {
00056             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateCapabilityStatus());
00057         }
00058
00059         async void StreamLocationButton_Click(object sender, RoutedEventArgs e)
00060         {
00061             switch (locationCapability.CheckAccess())
00062             {
00063                 case AppCapabilityAccessStatus.Allowed:
00064                     // Access was already granted.
00065                     // AccessChanged event will trigger a recalc.
00066                     await StreamLocationAsync();
00067                     break;
00068
00069                 case AppCapabilityAccessStatus.UserPromptRequired:
00070                     // Request access directly for a better experience than going to Settings.
00071                     // This is equivalent to calling Geolocator::RequestAccessAsync().
00072                     if (await locationCapability.RequestAccessAsync() == AppCapabilityAccessStatus.Allowed)
00073                     {
00074                         // The user granted access.
00075                         // AccessChanged event will trigger a recalc.
00076                         await StreamLocationAsync();
00077                     }
00078                     break;
00079
00080                 case AppCapabilityAccessStatus.DeniedByUser:
00081                 case AppCapabilityAccessStatus.DeniedBySystem:
00082                 default:
00083                     // Send user to Settings to obtain location permission
00084                     // or explain why access is denied.
00085                     await Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));
00086                     break;
00087             }
00088         }
00089
00090         async Task StreamLocationAsync()
00091         {
00092             if (await Geolocator.RequestAccessAsync() == GeolocationAccessStatus.Allowed)
00093             {
00094                 // Need try/catch because we can lose geolocator access at any time.
00095                 try
00096                 {
00097                     // Specify a message to explain to the user why we are tracking their location.
00098                     locationCapability.DisplayMessage = "Streaming location";
00099
00100                     LocationTextBlock.Text = "Finding your current location...";
00101                     Geolocator geolocator = new Geolocator();
00102
00103                     for (int i = 0; i < 4; i++)
00104                     {
00105                         Geoposition pos = await geolocator.GetGeopositionAsync();
00106
00107                         if (pos == null)
00108                         {
00109                             LocationTextBlock.Text = "Current location unknown.";
00110                         }
00111                         else
00112                         {
00113                             LocationTextBlock.Text = $"Your location is: Latitude {pos.Coordinate.Point.Position.Latitude:F}, Longitude {pos.Coordinate.Point.Position.Longitude:F}";
00114                         }
00115
00116                         await Task.Delay(500);
00117
00118                         // You can change the message as your app's usage changes.
00119                         locationCapability.DisplayMessage = "Tracking your current location...";
00120                     }
00121                 }
00122                 catch (Exception ex) when (ex.HResult == unchecked((int)0x80070005)) // E_ACCESSDENIED
00123                 {
00124                     // Lost access in the middle of the operation.
00125                     // AccessChanged event will trigger a recalc.
00126                 }
00127
00128                 LocationTextBlock.Text = "";
00129
00130                 // Even though we clear the message immediately, it will take time before the message
00131                 // disappear from the system. The system has a minimum display time for the message,
00132                 // so that users can observe brief usage.
00133                 locationCapability.DisplayMessage = "";
00134             }
00135             else
00136             {
00137                 // Lost access before operation started.
00138                 // AccessChanged event will trigger a recalc.
00139             }
00140         }
00141
00142         void UpdateCapabilityStatus()
00143         {
00144             AppCapabilityAccessStatus status = locationCapability.CheckAccess();
00145             if (status == AppCapabilityAccessStatus.Allowed)
00146             {
00147                 LocationAccessBlock.Visibility = Visibility.Collapsed;
00148                 LocationTextBlock.Visibility = Visibility.Visible;
00149             }
00150             else
00151             {
00152                 LocationTextBlock.Visibility = Visibility.Collapsed;
00153
00154                 switch (status)
00155                 {
00156                     case AppCapabilityAccessStatus.NotDeclaredByApp:
00157                         // The app neglected to declare the capability in its manifest.
00158                         // This is a developer error.
00159                         LocationAccessBlock.Text = "App misconfiguration error. Contact vendor for support.";
00160                         LocationAccessBlock.Visibility = Visibility.Visible;
00161                         break;
00162
00163                     default:
00164                     case AppCapabilityAccessStatus.DeniedBySystem:
00165                         // We can send the user to the Settings page to obtain access
00166                         // or at least explain why access is denied.
00167                         LocationAccessBlock.Text = "The system has blocked access to location.";
00168                         LocationAccessBlock.Visibility = Visibility.Visible;
00169                         break;
00170
00171                     case AppCapabilityAccessStatus.DeniedByUser:
00172                         // We can send the user to the Settings page to obtain access.
00173                         LocationAccessBlock.Text = "You must enable location access in Settings.";
00174                         LocationAccessBlock.Visibility = Visibility.Visible;
00175                         break;
00176
00177                     case AppCapabilityAccessStatus.UserPromptRequired:
00178                         // We can prompt the user to give us access.
00179                         LocationAccessBlock.Visibility = Visibility.Collapsed;
00180                         break;
00181                 }
00182             }
00183         }
00184     }
00185 }
Generated on Fri Nov 15 2024 22:18:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioGroup Member List

This is the complete list of members for ScenarioGroup, including all inherited members.
_name | ScenarioGroup | [private]
Children | ScenarioGroup |
Contains(Type scenarioType) | ScenarioGroup | [inline]
FindParent(IScenario ofScenario) | ScenarioGroup | [inline]
FindScenario(Type scenarioType) | ScenarioGroup | [inline]
GetPathToScenario(Scenario scenario) | ScenarioGroup | [inline]
GetPathToScenarioHelper(Scenario scenario, List< ScenarioGroup > listToAppendTo) | ScenarioGroup | [inline, private]
Name | ScenarioGroup |
OnPropertyChanged([CallerMemberName] string propertyName=null) | BindableBase | [inline, protected]
PropertyChanged | BindableBase |
ScenarioGroup(string name, IEnumerable< IScenario > children) | ScenarioGroup | [inline]
SetProperty< T >(ref T storage, T value,[CallerMemberName] String propertyName=null) | BindableBase | [inline, protected]
ToString() | ScenarioGroup | [inline]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Conversion Member List

This is the complete list of members for Scenario1_Conversion, including all inherited members.
CreateGeneratorButton_Click(object sender, RoutedEventArgs e) | Scenario1_Conversion | [inline, private]
Execute_Click(object sender, RoutedEventArgs e) | Scenario1_Conversion | [inline, private]
generator | Scenario1_Conversion | [private]
Methods_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario1_Conversion | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_Conversion | [inline, protected]
rootPage | Scenario1_Conversion | [private]
Scenario1_Conversion() | Scenario1_Conversion | [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Tasks/VisitBackgroundTask.h Source File

  • Geolocation
  • cppwinrt
  • Tasks

VisitBackgroundTask.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include "VisitBackgroundTask.g.h"
00004
00005 namespace winrt::BackgroundTask::implementation
00006 {
00007     struct VisitBackgroundTask : VisitBackgroundTaskT<VisitBackgroundTask>
00008     {
00009         VisitBackgroundTask() = default;
00010
00011         void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance const& taskInstance);
00012
00013     private:
00014         Windows::Foundation::Collections::IPropertySet m_values{ Windows::Storage::ApplicationData::Current().LocalSettings().Values() };
00015
00016         // Value determined by how many max length event descriptors (91 chars)
00017         // stored as a JSON string can fit in 8K (max allowed for local settings)
00018         static constexpr int maxEventDescriptors = 42;
00019
00020         void ProcessVisitReports(Windows::Devices::Geolocation::GeovisitTriggerDetails const& triggerDetails);
00021         hstring GenerateVisitDescription(Windows::Devices::Geolocation::Geovisit const& visit);
00022     };
00023 }
00024
00025 namespace winrt::BackgroundTask::factory_implementation
00026 {
00027     struct VisitBackgroundTask : VisitBackgroundTaskT<VisitBackgroundTask, implementation::VisitBackgroundTask>
00028     {
00029     };
00030 }
Generated on Fri Nov 15 2024 22:19:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cs/Scenario1_DevicePicker.xaml.cs Source File

  • DeviceEnumerationAndPairing
  • cs

Scenario1_DevicePicker.xaml.cs

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 using System;
00004 using System.Collections.ObjectModel;
00005 using Windows.Devices.Enumeration;
00006 using Windows.Foundation;
00007 using Windows.UI.Core;
00008 using Windows.UI.Xaml;
00009 using Windows.UI.Xaml.Controls;
00010 using Windows.UI.Xaml.Media;
00011 using Windows.UI.Xaml.Navigation;
00012
00013 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00014
00015 namespace SDKTemplate
00016 {
00017     /// <summary>
00018     /// An empty page that can be used on its own or navigated to within a Frame.
00019     /// </summary>
00020     public sealed partial class Scenario1_DevicePicker : Page
00021     {
00022         private MainPage rootPage = MainPage.Current;
00023
00024         private ObservableCollection<DeviceInformationDisplay> resultCollection = new ObservableCollection<DeviceInformationDisplay>();
00025
00026         public Scenario1_DevicePicker()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         protected override void OnNavigatedTo(NavigationEventArgs e)
00032         {
00033             resultsListView.ItemsSource = resultCollection;
00034             selectorComboBox.ItemsSource = DeviceSelectorChoices.DevicePickerSelectors;
00035             selectorComboBox.SelectedIndex = 0;
00036         }
00037
00038         private void PickSingleDeviceButton_Click(object sender, RoutedEventArgs e)
00039         {
00040             ShowDevicePicker(
00041                 true // pickSingle
00042                 );
00043         }
00044
00045         private void ShowDevicePickerButton_Click(object sender, RoutedEventArgs e)
00046         {
00047             ShowDevicePicker(
00048                 false // pickSingle
00049                 );
00050         }
00051
00052         private async void ShowDevicePicker(bool pickSingle)
00053         {
00054             showDevicePickerButton.IsEnabled = false;
00055             resultCollection.Clear();
00056
00057             var devicePicker = new DevicePicker();
00058
00059             // First get the device selector chosen by the UI.
00060             DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;
00061
00062             if (null == deviceSelectorInfo.Selector)
00063             {
00064                 // If the a pre-canned device class selector was chosen, call the DeviceClass overload
00065                 devicePicker.Filter.SupportedDeviceClasses.Add(deviceSelectorInfo.DeviceClassSelector);
00066             }
00067             else
00068             {
00069                 // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
00070                 devicePicker.Filter.SupportedDeviceSelectors.Add(deviceSelectorInfo.Selector);
00071             }
00072
00073             rootPage.NotifyUser("Showing Device Picker", NotifyType.StatusMessage);
00074
00075             // Calculate the position to show the picker (right below the buttons)
00076             GeneralTransform ge = pickSingleDeviceButton.TransformToVisual(null);
00077             Point point = ge.TransformPoint(new Point());
00078             Rect rect = new Rect(point, new Point(point.X + pickSingleDeviceButton.ActualWidth, point.Y + pickSingleDeviceButton.ActualHeight));
00079
00080             if (pickSingle)
00081             {
00082                 DeviceInformation di = await devicePicker.PickSingleDeviceAsync(rect);
00083                 if (null != di)
00084                 {
00085                     resultCollection.Add(new DeviceInformationDisplay(di));
00086                 }
00087                 showDevicePickerButton.IsEnabled = true;
00088             }
00089             else
00090             {
00091                 devicePicker.DevicePickerDismissed += new TypedEventHandler<DevicePicker, object>(
00092                 async (picker, obj) =>
00093                 {
00094                     // Must access UI elements from the UI thread.
00095                     await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
00096                     {
00097                         showDevicePickerButton.IsEnabled = true;
00098                         rootPage.NotifyUser("Hiding Device Picker", NotifyType.StatusMessage);
00099                     });
00100                 });
00101
00102                 devicePicker.DeviceSelected += new TypedEventHandler<DevicePicker, DeviceSelectedEventArgs>(
00103                 async (picker, args) =>
00104                 {
00105                     // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
00106                     await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
00107                     {
00108                         resultCollection.Clear();
00109                         resultCollection.Add(new DeviceInformationDisplay(args.SelectedDevice));
00110                     });
00111                 });
00112
00113                 // Show the picker
00114                 devicePicker.Show(rect);
00115             }
00116         }
00117     }
00118 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteLineSpacingModes/cpp/DWriteLineSpacingModes/Scenario2_UniformSpacing.xaml.cpp Source File

  • DWriteLineSpacingModes
  • cpp
  • DWriteLineSpacingModes

Scenario2_UniformSpacing.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_UniformSpacing.xaml.h"
00014
00015 using namespace SDKTemplate;
00016 using namespace DWriteTextLayoutImplementation;
00017
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Media;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029
00030 Scenario2_UniformSpacing::Scenario2_UniformSpacing()
00031 {
00032     InitializeComponent();
00033
00034     String^ text =
00035         L"Lorem ipsum dolor sit amet, consectetur 😐 adipiscing elit, sed do eiusmod tempor "
00036         L"incididunt ut labore et dolore magna aliqua.";
00037
00038     // Create the TextLayout for our text content.
00039     m_textLayout = ref new TextLayout(
00040         text,
00041         L"en-US",
00042         L"Cambria Math",
00043         24.0f, // text size (DIPs)
00044         static_cast<uint32>(floor(TextLayoutImage->Width)), // text layout width
00045         LineSpacingMethod::Uniform
00046         );
00047
00048     // Get the array of computed line metrics for the text layout -- we'll
00049     // report results for the first line.
00050     m_textLayoutLineMetrics = m_textLayout->GetTextLayoutLineMetrics();
00051
00052     // Create a new TextLayoutImageSource based on the text layout, have
00053     // it draw, and then use it as the source for the XAML image element.
00054     m_textLayoutImageSource = ref new TextLayoutImageSource(
00055         m_textLayout,
00056         static_cast<uint32>(floor(TextLayoutImage->Width)),
00057         static_cast<uint32>(floor(TextLayoutImage->Height))
00058         );
00059     m_textLayoutImageSource->Draw();
00060     TextLayoutImage->Source = m_textLayoutImageSource;
00061 }
00062
00063
00064 void Scenario2_UniformSpacing::LineSpacingHeight::set(double value)
00065 {
00066     m_textLayout->LineSpacingHeight = static_cast<float>(value);
00067     m_textLayoutLineMetrics = m_textLayout->GetTextLayoutLineMetrics();
00068     m_textLayoutImageSource->Draw();
00069     this->Bindings->Update();
00070 }
00071
00072
00073 void Scenario2_UniformSpacing::LineSpacingBaseline::set(double value)
00074 {
00075     m_textLayout->LineSpacingBaseline = static_cast<float>(value);
00076     m_textLayoutLineMetrics = m_textLayout->GetTextLayoutLineMetrics();
00077     m_textLayoutImageSource->Draw();
00078     this->Bindings->Update();
00079 }
00080
Generated on Fri Nov 15 2024 22:19:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Compass/cs/Scenario3_Calibration.xaml.cs Source File

  • Compass
  • cs

Scenario3_Calibration.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using System;
00012 using System.Threading.Tasks;
00013 using Windows.Devices.Sensors;
00014 using Windows.Foundation;
00015 using Windows.UI.Core;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario3_Calibration : Page
00023     {
00024         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00025         // as NotifyUser()
00026         MainPage rootPage = MainPage.Current;
00027         CalibrationBar calibrationBar = new CalibrationBar();
00028
00029         public Scenario3_Calibration()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         /// <summary>
00035         /// Invoked when this page is about to be displayed in a Frame.
00036         /// </summary>
00037         /// <param name="e">Event data that describes how this page was reached. The Parameter
00038         /// property is typically used to configure the page.</param>
00039         protected override void OnNavigatedTo(NavigationEventArgs e)
00040         {
00041         }
00042
00043         /// <summary>
00044         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00045         /// </summary>
00046         /// <param name="e">
00047         /// Event data that can be examined by overriding code. The event data is representative
00048         /// of the navigation that will unload the current Page unless canceled. The
00049         /// navigation can potentially be canceled by setting Cancel.
00050         /// </param>
00051         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00052         {
00053             calibrationBar.Hide();
00054             base.OnNavigatingFrom(e);
00055         }
00056
00057         /// <summary>
00058         /// This is the click handler for high accuracy. Acceptable accuracy met, so
00059         /// hide the calibration bar.
00060         /// </summary>
00061         /// <param name="sender"></param>
00062         /// <param name="e"></param>
00063         private void OnHighAccuracy(object sender, RoutedEventArgs e)
00064         {
00065             calibrationBar.Hide();
00066         }
00067
00068         /// <summary>
00069         /// This is the click handler for approximate accuracy. Acceptable accuracy met, so
00070         /// hide the calibration bar.
00071         /// </summary>
00072         /// <param name="sender"></param>
00073         /// <param name="e"></param>
00074         private void OnApproximateAccuracy(object sender, RoutedEventArgs e)
00075         {
00076             calibrationBar.Hide();
00077         }
00078
00079         /// <summary>
00080         /// This is the click handler for unreliable accuracy. Sensor does not meet accuracy
00081         /// requirements. Request to show the calibration bar per the calibration guidance.
00082         /// </summary>
00083         /// <param name="sender"></param>
00084         /// <param name="e"></param>
00085         private void OnUnreliableAccuracy(object sender, RoutedEventArgs e)
00086         {
00087             calibrationBar.RequestCalibration(MagnetometerAccuracy.Unreliable);
00088         }
00089     }
00090 }
Generated on Fri Nov 15 2024 22:18:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/xBindSampleModel/Converters.cs Source File

  • XamlBind
  • cs
  • xBindSampleModel

Converters.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI;
00003 using Windows.UI.Xaml;
00004 using Windows.UI.Xaml.Data;
00005
00006
00007 namespace BindTestbedModel
00008 {
00009     public sealed class ColorToStringConverter : IValueConverter
00010     {
00011         static string[] colorNames = { "AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenrod", "DarkGray", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "DarkOrange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DodgerBlue", "Firebrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "Goldenrod", "Gray", "Green", "GreenYellow", "Honeydew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenrodYellow", "LightGray", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquamarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenrod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Transparent", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen" };
00012         static Color[] colorValues = { Colors.AliceBlue, Colors.AntiqueWhite, Colors.Aqua, Colors.Aquamarine, Colors.Azure, Colors.Beige, Colors.Bisque, Colors.Black, Colors.BlanchedAlmond, Colors.Blue, Colors.BlueViolet, Colors.Brown, Colors.BurlyWood, Colors.CadetBlue, Colors.Chartreuse, Colors.Chocolate, Colors.Coral, Colors.CornflowerBlue, Colors.Cornsilk, Colors.Crimson, Colors.Cyan, Colors.DarkBlue, Colors.DarkCyan, Colors.DarkGoldenrod, Colors.DarkGray, Colors.DarkGreen, Colors.DarkKhaki, Colors.DarkMagenta, Colors.DarkOliveGreen, Colors.DarkOrange, Colors.DarkOrchid, Colors.DarkRed, Colors.DarkSalmon, Colors.DarkSeaGreen, Colors.DarkSlateBlue, Colors.DarkSlateGray, Colors.DarkTurquoise, Colors.DarkViolet, Colors.DeepPink, Colors.DeepSkyBlue, Colors.DimGray, Colors.DodgerBlue, Colors.Firebrick, Colors.FloralWhite, Colors.ForestGreen, Colors.Fuchsia, Colors.Gainsboro, Colors.GhostWhite, Colors.Gold, Colors.Goldenrod, Colors.Gray, Colors.Green, Colors.GreenYellow, Colors.Honeydew, Colors.HotPink, Colors.IndianRed, Colors.Indigo, Colors.Ivory, Colors.Khaki, Colors.Lavender, Colors.LavenderBlush, Colors.LawnGreen, Colors.LemonChiffon, Colors.LightBlue, Colors.LightCoral, Colors.LightCyan, Colors.LightGoldenrodYellow, Colors.LightGray, Colors.LightGreen, Colors.LightPink, Colors.LightSalmon, Colors.LightSeaGreen, Colors.LightSkyBlue, Colors.LightSlateGray, Colors.LightSteelBlue, Colors.LightYellow, Colors.Lime, Colors.LimeGreen, Colors.Linen, Colors.Magenta, Colors.Maroon, Colors.MediumAquamarine, Colors.MediumBlue, Colors.MediumOrchid, Colors.MediumPurple, Colors.MediumSeaGreen, Colors.MediumSlateBlue, Colors.MediumSpringGreen, Colors.MediumTurquoise, Colors.MediumVioletRed, Colors.MidnightBlue, Colors.MintCream, Colors.MistyRose, Colors.Moccasin, Colors.NavajoWhite, Colors.Navy, Colors.OldLace, Colors.Olive, Colors.OliveDrab, Colors.Orange, Colors.OrangeRed, Colors.Orchid, Colors.PaleGoldenrod, Colors.PaleGreen, Colors.PaleTurquoise, Colors.PaleVioletRed, Colors.PapayaWhip, Colors.PeachPuff, Colors.Peru, Colors.Pink, Colors.Plum, Colors.PowderBlue, Colors.Purple, Colors.Red, Colors.RosyBrown, Colors.RoyalBlue, Colors.SaddleBrown, Colors.Salmon, Colors.SandyBrown, Colors.SeaGreen, Colors.SeaShell, Colors.Sienna, Colors.Silver, Colors.SkyBlue, Colors.SlateBlue, Colors.SlateGray, Colors.Snow, Colors.SpringGreen, Colors.SteelBlue, Colors.Tan, Colors.Teal, Colors.Thistle, Colors.Tomato, Colors.Transparent, Colors.Turquoise, Colors.Violet, Colors.Wheat, Colors.White, Colors.WhiteSmoke, Colors.Yellow, Colors.YellowGreen };
00013
00014         public object Convert(object value, Type targetType, object parameter, string language)
00015         {
00016             Color src = (Color)value;
00017             for (int i = 0; i < colorValues.Length; i++)
00018             {
00019                 if (src == colorValues[i])
00020                 {
00021                     return colorNames[i];
00022                 }
00023             }
00024             return string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", src.A, src.R, src.G, src.B);
00025         }
00026
00027         public object ConvertBack(object value, Type targetType, object parameter, string language)
00028         {
00029             string src = (string)value;
00030             for (int i = 0; i < colorValues.Length; i++)
00031             {
00032                 if (src == colorNames[i])
00033                 {
00034                     return colorValues[i];
00035                 }
00036             }
00037             if (src.StartsWith("#"))
00038             {
00039                 return Color.FromArgb(Byte.Parse(src.Substring(1, 2), System.Globalization.NumberStyles.HexNumber),
00040                     Byte.Parse(src.Substring(3, 2), System.Globalization.NumberStyles.HexNumber),
00041                     Byte.Parse(src.Substring(5, 2), System.Globalization.NumberStyles.HexNumber),
00042                     Byte.Parse(src.Substring(7, 2), System.Globalization.NumberStyles.HexNumber));
00043             }
00044             throw new ArgumentException("Cannot parse the color");
00045         }
00046     }
00047 }
00048
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/Scenario2_SimpleGridView.cpp Source File

  • XamlListView
  • cppwinrt

Scenario2_SimpleGridView.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Contact.h"
00014 #include "Scenario2_SimpleGridView.h"
00015 #include "Scenario2_SimpleGridView.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::UI::Xaml;
00020
00021 namespace winrt::SDKTemplate::implementation
00022 {
00023     Scenario2_SimpleGridView::Scenario2_SimpleGridView()
00024     {
00025         InitializeComponent();
00026         ContactsCVS().Source(Contact::GetContactsGrouped(250));
00027     }
00028 }
Generated on Fri Nov 15 2024 22:22:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlTailoredMultipleViews/cs/TailoredMultipleViews/UserControls/Collections.xaml.cs Source File

  • XamlTailoredMultipleViews
  • cs
  • TailoredMultipleViews
  • UserControls

Collections.xaml.cs

Go to the documentation of this file.
00001 ﻿using OneHandedUse_TailoredMultipleViews.ViewModel;
00002 using System;
00003 using System.Collections.Generic;
00004 using System.IO;
00005 using System.Linq;
00006 using System.Runtime.InteropServices.WindowsRuntime;
00007 using Windows.Foundation;
00008 using Windows.Foundation.Collections;
00009 using Windows.UI.Xaml;
00010 using Windows.UI.Xaml.Controls;
00011 using Windows.UI.Xaml.Controls.Primitives;
00012 using Windows.UI.Xaml.Data;
00013 using Windows.UI.Xaml.Input;
00014 using Windows.UI.Xaml.Media;
00015 using Windows.UI.Xaml.Navigation;
00016
00017 // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
00018
00019 namespace OneHandedUse_TailoredMultipleViews.UserControls
00020 {
00021     public sealed partial class Collections : UserControl
00022     {
00023         private MainViewModel vm = new MainViewModel();
00024         public Collections()
00025         {
00026             this.InitializeComponent();
00027             this.DataContext = vm.GetCollections();
00028         }
00029     }
00030 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/scenario2.xaml.cpp Source File

  • ApplicationResources
  • cpp

scenario2.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario2.xaml.cpp
00013 // Implementation of the Scenario2 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario2.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario2::Scenario2()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 /// <summary>
00031 /// Invoked when this page is about to be displayed in a Frame.
00032 /// </summary>
00033 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00034 /// property is typically used to configure the page.</param>
00035 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00036 {
00037     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00038     // as NotifyUser()
00039     rootPage = MainPage::Current;
00040 }
00041
Generated on Fri Nov 15 2024 22:17:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteLineSpacingModes/cpp/DWriteLineSpacingModes/Scenario1_DefaultSpacing.xaml.cpp Source File

  • DWriteLineSpacingModes
  • cpp
  • DWriteLineSpacingModes

Scenario1_DefaultSpacing.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_DefaultSpacing.xaml.h"
00014
00015 using namespace SDKTemplate;
00016 using namespace DWriteTextLayoutImplementation;
00017
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Media;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029
00030 Scenario1_DefaultSpacing::Scenario1_DefaultSpacing()
00031 {
00032     InitializeComponent();
00033
00034     String^ text =
00035         L"Lorem ipsum dolor sit amet, consectetur 😐 adipiscing elit, sed do eiusmod tempor "
00036         L"incididunt ut labore et dolore magna aliqua.";
00037
00038     // Create the TextLayout for our text content.
00039     m_textLayout = ref new TextLayout(
00040         text,
00041         L"en-US",
00042         L"Cambria Math",
00043         24.0f, // text size (DIPs)
00044         static_cast<uint32>(floor(TextLayoutImage->Width)), // text layout width
00045         LineSpacingMethod::Default
00046         );
00047
00048     // Get the array of computed line metrics for the text layout -- we'll
00049     // report results for the first line.
00050     m_textLayoutLineMetrics = m_textLayout->GetTextLayoutLineMetrics();
00051
00052     // Create a new TextLayoutImageSource based on the text layout, have
00053     // it draw, and then use it as the source for the XAML image element.
00054     m_textLayoutImageSource = ref new TextLayoutImageSource(
00055         m_textLayout,
00056         static_cast<uint32>(floor(TextLayoutImage->Width)),
00057         static_cast<uint32>(floor(TextLayoutImage->Height))
00058         );
00059     m_textLayoutImageSource->Draw();
00060     TextLayoutImage->Source = m_textLayoutImageSource;
00061 }
00062
00063
00064 void Scenario1_DefaultSpacing::IsFontLineGapUsageEnabled::set(bool value)
00065 {
00066     m_textLayout->FontLineGapUsage = (value) ? FontLineGapUsage::Enabled : FontLineGapUsage::Disabled;
00067     m_textLayoutLineMetrics = m_textLayout->GetTextLayoutLineMetrics();
00068     m_textLayoutImageSource->Draw();
00069     this->Bindings->Update();
00070 }
Generated on Fri Nov 15 2024 22:19:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cppwinrt/Scenario2_Remove.h Source File

  • JumpList
  • cppwinrt

Scenario2_Remove.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Remove.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_Remove : Scenario2_RemoveT<Scenario2_Remove>
00019     {
00020         Scenario2_Remove();
00021
00022         // These methods are public so they can be called by binding.
00023         fire_and_forget RemoveJumpList_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024     };
00025 }
00026
00027 namespace winrt::SDKTemplate::factory_implementation
00028 {
00029     struct Scenario2_Remove : Scenario2_RemoveT<Scenario2_Remove, implementation::Scenario2_Remove>
00030     {
00031     };
00032 }
Generated on Fri Nov 15 2024 22:20:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NetworkConnectivity/cs/Scenario1_NetworkConnectivity.xaml.cs Source File

  • NetworkConnectivity
  • cs

Scenario1_NetworkConnectivity.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.Networking.Connectivity;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public sealed partial class Scenario1_NetworkConnectivity : Page
00019     {
00020         public Scenario1_NetworkConnectivity()
00021         {
00022             this.InitializeComponent();
00023         }
00024
00025         private async void QueryCurrentNetworkConnectivityButton_Click(object sender, RoutedEventArgs e)
00026         {
00027             ResultsText.Text = string.Empty;
00028
00029             ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile();
00030             NetworkConnectivityLevel connectivityLevel = NetworkConnectivityLevel.None;
00031             if (profile != null)
00032             {
00033                 // It can take the system a few moments to detect a change in network connectivity,
00034                 // so it's possible that the value returned is slightly out of date.
00035                 // Scenario3_NetworkConnectivityChanges shows how to be notified when the system
00036                 // detects connectivity changes.
00037                 connectivityLevel = profile.GetNetworkConnectivityLevel();
00038             }
00039
00040             Helpers.AppendLine(ResultsText, $"Current connectivity is {connectivityLevel}.");
00041
00042             if (Helpers.ShouldAttemptToConnectToInternet(connectivityLevel))
00043             {
00044                 await Helpers.EvaluateCostAndConnectAsync(profile.GetConnectionCost(), OptedInToNetworkUsageToggle.IsOn, ResultsText);
00045             }
00046             else
00047             {
00048                 Helpers.AppendLine(ResultsText, "Not attempting to connect to the Internet.");
00049             }
00050         }
00051     }
00052 }
00053
00054
Generated on Fri Nov 15 2024 22:20:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VertexPositionColor Member List

This is the complete list of members for VertexPositionColor, including all inherited members.
color | VertexPositionColor
pos | VertexPositionColor
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7_DeviceInformationKind Member List

This is the complete list of members for Scenario7_DeviceInformationKind, including all inherited members.
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario7_DeviceInformationKind |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario7_DeviceInformationKind |
resultCollection | Scenario7_DeviceInformationKind | [private]
Scenario7_DeviceInformationKind() | Scenario7_DeviceInformationKind |
StartWatcherButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario7_DeviceInformationKind |
StopWatcherButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario7_DeviceInformationKind |
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Projection/cpp/Scenario1.xaml.cpp Source File

  • Projection
  • cpp

Scenario1.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1.xaml.h"
00014 #include "MainPage.xaml.h"
00015 #include "ProjectionViewPage.xaml.h"
00016 #include "ViewLifetimeControl.h"
00017
00018 using namespace SDKSample;
00019
00020 using namespace Concurrency;
00021 using namespace Platform;
00022 using namespace SDKSample::SecondaryViewsHelpers;
00023 using namespace Windows::ApplicationModel::Core;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::UI::ViewManagement;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Interop;
00029
00030 Scenario1::Scenario1()
00031 {
00032     InitializeComponent();
00033     thisViewId = ApplicationView::GetForCurrentView()->Id;
00034 }
00035
00036 void Scenario1::StartProjecting_Click(Object^ sender, RoutedEventArgs^ e)
00037 {
00038     auto prerequisite = task<void>([]() {});
00039     // If projection is already in progress, then it could be shown on the monitor again
00040     // Otherwise, we need to create a new view to show the presentation
00041     if (MainPage::Current->ProjectionViewPageControl == nullptr)
00042     {
00043         // First, create a new, blank view
00044         auto mainDispatcher = Window::Current->Dispatcher;
00045         int mainViewId = thisViewId;
00046         prerequisite = create_task(CoreApplication::CreateNewView()->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([mainViewId, mainDispatcher]()
00047         {
00048             // ViewLifetimeControl is a wrapper to make sure the view is closed only
00049             // when the app is done with it
00050             MainPage::Current->ProjectionViewPageControl = ViewLifetimeControl::CreateForCurrentView();
00051
00052             // Assemble some data necessary for the new page
00053             auto initData = ref new ProjectionViewPageInitializationData();
00054             initData->MainDispatcher = mainDispatcher;
00055             initData->ProjectionViewPageControl = MainPage::Current->ProjectionViewPageControl;
00056             initData->MainViewId = mainViewId;
00057
00058             // Display the page in the view. Note that the view will not become visible
00059             // until "StartProjectingAsync" is called
00060             auto rootFrame = ref new Windows::UI::Xaml::Controls::Frame();
00061             rootFrame->Navigate(TypeName(ProjectionViewPage::typeid), initData);
00062             Window::Current->Content = rootFrame;
00063
00064             // The call to Window.Current.Activate is required starting in Windos 10.
00065             // Without it, the view will never appear.
00066             Window::Current->Activate();
00067         })));
00068     }
00069
00070     prerequisite.then([this]()
00071     {
00072         try
00073         {
00074             // Start/StopViewInUse are used to signal that the app is interacting with the
00075             // view, so it shouldn't be closed yet, even if the user loses access to it
00076             MainPage::Current->ProjectionViewPageControl->StartViewInUse();
00077
00078             // Show the view on a second display (if available) or on the primary display
00079             create_task(ProjectionManager::StartProjectingAsync(
00080                 MainPage::Current->ProjectionViewPageControl->Id,
00081                 thisViewId
00082                 )).then([]() {
00083                 MainPage::Current->ProjectionViewPageControl->StopViewInUse();
00084             });
00085         }
00086         catch (ObjectDisposedException^)
00087         {
00088             // The projection view is being disposed
00089             MainPage::Current->NotifyUser("The projection view is being disposed", NotifyType::ErrorMessage);
00090         }
00091     }, task_continuation_context::use_arbitrary());
00092 }
Generated on Fri Nov 15 2024 22:17:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

QuadRenderer Member List

This is the complete list of members for QuadRenderer, including all inherited members.
c_lerpRate | QuadRenderer | [private]
CreateDeviceDependentResourcesAsync() override | QuadRenderer | [virtual]
GetNormal() const | QuadRenderer | [inline]
GetPosition() const | QuadRenderer | [inline]
GetVelocity() const | QuadRenderer | [inline]
m_degreesPerSecond | QuadRenderer | [private]
m_deviceResources | Resource | [protected]
m_geometryShader | QuadRenderer | [private]
m_indexBuffer | QuadRenderer | [private]
m_indexCount | QuadRenderer | [private]
m_inputLayout | QuadRenderer | [private]
m_modelConstantBuffer | QuadRenderer | [private]
m_modelConstantBufferData | QuadRenderer | [private]
m_normal | QuadRenderer | [private]
m_pixelShaderNV12 | QuadRenderer | [private]
m_pixelShaderRGB | QuadRenderer | [private]
m_position | QuadRenderer | [private]
m_samplerState | QuadRenderer | [private]
m_targetForward | QuadRenderer | [private]
m_targetPosition | QuadRenderer | [private]
m_targetTexCoordOffset | QuadRenderer | [private]
m_targetTexCoordScale | QuadRenderer | [private]
m_targetUp | QuadRenderer | [private]
m_texCoordOffset | QuadRenderer | [private]
m_texCoordScale | QuadRenderer | [private]
m_usingVprtShaders | QuadRenderer | [private]
m_velocity | QuadRenderer | [private]
m_vertexBuffer | QuadRenderer | [private]
m_vertexShader | QuadRenderer | [private]
QuadRenderer(std::shared_ptr< DX::DeviceResources > deviceResources) | QuadRenderer |
ReleaseDeviceDependentResources() override | QuadRenderer | [virtual]
RenderInternal(void) | QuadRenderer | [protected]
RenderNV12(ID3D11ShaderResourceView *luminanceTexture, ID3D11ShaderResourceView *chrominanceTexture) | QuadRenderer |
RenderRGB(ID3D11ShaderResourceView *rgbTexture) | QuadRenderer |
ResetTexCoordScaleAndOffset(Windows::Foundation::Numerics::float2 const &texCoordScale={1.0f, 1.0f}, Windows::Foundation::Numerics::float2 const &texCoordOffset={0.0f, 0.0f}) | QuadRenderer |
Resource(std::shared_ptr< DeviceResources > deviceResources) | Resource | [inline]
SetTexCoordScaleAndOffset(Windows::Foundation::Numerics::float2 const &texCoordScale, Windows::Foundation::Numerics::float2 const &texCoordOffset) | QuadRenderer |
Update(Windows::UI::Input::Spatial::SpatialPointerPose^pointerPose, Windows::Foundation::Numerics::float3 const &offset, DX::StepTimer const &timer) | QuadRenderer |
~Resource() | Resource | [virtual]
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlLite/cppwinrt/Project.idl Source File

  • XmlLite
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_XmlReader : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_XmlReader();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_XmlWriter : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_XmlWriter();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3_XmlWriterLite : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3_XmlWriterLite();
00030     }
00031 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cppwinrt/SampleConfiguration.h Source File

  • Clipboard
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     struct SampleState
00018     {
00019         static Windows::UI::Notifications::ToastNotification DisplayToast(hstring const& message);
00020         static bool IsClipboardContentChangedEnabled();
00021         static bool EnableClipboardContentChangedNotifications(bool enable);
00022         static hstring BuildClipboardFormatsOutputString();
00023     private:
00024         static event_token clipboardContentChangedToken;
00025         static event_token activatedToken;
00026         static bool isClipboardContentChangedEnabled;
00027         static bool needToPrintClipboardFormat;
00028         static bool isApplicationWindowActive;
00029
00030         static void AddClipboardFormatsOutputString(std::wostringstream& output);
00031         static void DisplayChangedFormats();
00032         static void HandleClipboardChanged();
00033         static void OnWindowActivated(Windows::Foundation::IInspectable const& sender, Windows::UI::Core::WindowActivatedEventArgs const& e);
00034         static void OnClipboardChanged(Windows::Foundation::IInspectable const& sender, Windows::Foundation::IInspectable const& e);
00035     };
00036 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_UnpinTile Member List

This is the complete list of members for Scenario2_UnpinTile, including all inherited members.
rootPage | Scenario2_UnpinTile | [private]
Scenario2_UnpinTile() | Scenario2_UnpinTile | [inline]
UnpinSecondaryTile_Click(object sender, RoutedEventArgs e) | Scenario2_UnpinTile | [inline, private]
Generated on Fri Nov 15 2024 22:23:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/Scenario12.xaml.cpp Source File

  • SimpleInk
  • cpp

Scenario12.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario12.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Platform::Collections;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::UI::Core;
00020 using namespace Windows::UI::ViewManagement;
00021 using namespace Windows::UI::Input::Inking;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024
00025 Scenario12::Scenario12()
00026 {
00027     InitializeComponent();
00028
00029     inkCanvas->InkPresenter->InputDeviceTypes = CoreInputDeviceTypes::Mouse | CoreInputDeviceTypes::Pen | CoreInputDeviceTypes::Touch;
00030 }
00031
00032 void Scenario12::OnDrawingAttributesChanged(InkToolbar^ sender, Object^ args)
00033 {
00034     // Enable tilt support.
00035     sender->InkDrawingAttributes->IgnoreTilt = false;
00036     inkCanvas->InkPresenter->UpdateDefaultDrawingAttributes(sender->InkDrawingAttributes);
00037 }
00038
00039 void Scenario12::OnSizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00040 {
00041     HelperFunctions::UpdateCanvasSize(RootGrid, outputGrid, inkCanvas);
00042 }
00043
Generated on Fri Nov 15 2024 22:17:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario12_DisableCookies Member List

This is the complete list of members for Scenario12_DisableCookies, including all inherited members.
Cancel_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario12_DisableCookies |
CancelableInitialRequestAsync(Windows::Foundation::Uri resourceUri) | Scenario12_DisableCookies | [private]
CancelableNextRequestAsync(Windows::Foundation::Uri resourceUri) | Scenario12_DisableCookies | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario12_DisableCookies |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario12_DisableCookies |
Scenario12_DisableCookies() | Scenario12_DisableCookies |
SendInitialGetButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario12_DisableCookies |
SendNextRequestButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario12_DisableCookies |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cs/Content/SpinningCubeRenderer.cs Source File

  • BasicHologram
  • cs
  • Content

SpinningCubeRenderer.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Numerics;
00003 using BasicHologram.Common;
00004 using Windows.UI.Input.Spatial;
00005
00006 namespace BasicHologram.Content
00007 {
00008     /// <summary>
00009     /// This sample renderer instantiates a basic rendering pipeline.
00010     /// </summary>
00011     internal class SpinningCubeRenderer : Disposer
00012     {
00013         // Cached reference to device resources.
00014         private DeviceResources                     deviceResources;
00015
00016         // Direct3D resources for cube geometry.
00017         private SharpDX.Direct3D11.InputLayout      inputLayout;
00018         private SharpDX.Direct3D11.Buffer           vertexBuffer;
00019         private SharpDX.Direct3D11.Buffer           indexBuffer;
00020         private SharpDX.Direct3D11.VertexShader     vertexShader;
00021         private SharpDX.Direct3D11.GeometryShader   geometryShader;
00022         private SharpDX.Direct3D11.PixelShader      pixelShader;
00023         private SharpDX.Direct3D11.Buffer           modelConstantBuffer;
00024
00025         // System resources for cube geometry.
00026         private ModelConstantBuffer                 modelConstantBufferData;
00027         private int                                 indexCount = 0;
00028         private Vector3                             position = new Vector3(0.0f, 0.0f, -2.0f);
00029
00030         // Variables used with the rendering loop.
00031         private bool                                loadingComplete = false;
00032         private float                               degreesPerSecond = 45.0f;
00033
00034
00035         // If the current D3D Device supports VPRT, we can avoid using a geometry
00036         // shader just to set the render target array index.
00037         private bool                                usingVprtShaders = false;
00038
00039         /// <summary>
00040         /// Loads vertex and pixel shaders from files and instantiates the cube geometry.
00041         /// </summary>
00042         public SpinningCubeRenderer(DeviceResources deviceResources)
00043         {
00044             this.deviceResources  = deviceResources;
00045
00046             this.CreateDeviceDependentResourcesAsync();
00047         }
00048
00049         // This function uses a SpatialPointerPose to position the world-locked hologram
00050         // two meters in front of the user's heading.
00051         public void PositionHologram(SpatialPointerPose pointerPose)
00052         {
00053             if (null != pointerPose)
00054             {
00055                 // Get the gaze direction relative to the given coordinate system.
00056                 Vector3 headPosition        = pointerPose.Head.Position;
00057                 Vector3 headDirection       = pointerPose.Head.ForwardDirection;
00058
00059                 // The hologram is positioned two meters along the user's gaze direction.
00060                 float   distanceFromUser    = 2.0f; // meters
00061                 Vector3 gazeAtTwoMeters     = headPosition + (distanceFromUser * headDirection);
00062
00063                 // This will be used as the translation component of the hologram's
00064                 // model transform.
00065                 this.position = gazeAtTwoMeters;
00066             }
00067         }
00068
00069         /// <summary>
00070         /// Called once per frame, rotates the cube and calculates the model and view matrices.
00071         /// </summary>
00072         public void Update(StepTimer timer)
00073         {
00074             // Rotate the cube.
00075             // Convert degrees to radians, then convert seconds to rotation angle.
00076             float     radiansPerSecond  = this.degreesPerSecond * ((float)Math.PI / 180.0f);
00077             double    totalRotation     = timer.TotalSeconds * radiansPerSecond;
00078             float     radians           = (float)System.Math.IEEERemainder(totalRotation, 2 * Math.PI);
00079             Matrix4x4 modelRotation     = Matrix4x4.CreateFromAxisAngle(new Vector3(0, 1, 0), -radians);
00080
00081
00082             // Position the cube.
00083             Matrix4x4 modelTranslation  = Matrix4x4.CreateTranslation(position);
00084
00085
00086             // Multiply to get the transform matrix.
00087             // Note that this transform does not enforce a particular coordinate system. The calling
00088             // class is responsible for rendering this content in a consistent manner.
00089             Matrix4x4 modelTransform    = modelRotation * modelTranslation;
00090
00091             // The view and projection matrices are provided by the system; they are associated
00092             // with holographic cameras, and updated on a per-camera basis.
00093             // Here, we provide the model transform for the sample hologram. The model transform
00094             // matrix is transposed to prepare it for the shader.
00095             this.modelConstantBufferData.model = Matrix4x4.Transpose(modelTransform);
00096
00097             // Loading is asynchronous. Resources must be created before they can be updated.
00098             if (!loadingComplete)
00099             {
00100                 return;
00101             }
00102
00103             // Use the D3D device context to update Direct3D device-based resources.
00104             var context = this.deviceResources.D3DDeviceContext;
00105
00106             // Update the model transform buffer for the hologram.
00107             context.UpdateSubresource(ref this.modelConstantBufferData, this.modelConstantBuffer);
00108         }
00109
00110         /// <summary>
00111         /// Renders one frame using the vertex and pixel shaders.
00112         /// On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00113         /// VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00114         /// a pass-through geometry shader is also used to set the render
00115         /// target array index.
00116         /// </summary>
00117         public void Render()
00118         {
00119             // Loading is asynchronous. Resources must be created before drawing can occur.
00120             if (!this.loadingComplete)
00121             {
00122                 return;
00123             }
00124
00125             var context = this.deviceResources.D3DDeviceContext;
00126
00127             // Each vertex is one instance of the VertexPositionColor struct.
00128             int stride = SharpDX.Utilities.SizeOf<VertexPositionColor>();
00129             int offset = 0;
00130             var bufferBinding = new SharpDX.Direct3D11.VertexBufferBinding(this.vertexBuffer, stride, offset);
00131             context.InputAssembler.SetVertexBuffers(0, bufferBinding);
00132             context.InputAssembler.SetIndexBuffer(
00133                 this.indexBuffer,
00134                 SharpDX.DXGI.Format.R16_UInt, // Each index is one 16-bit unsigned integer (short).
00135                 0);
00136             context.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList;
00137             context.InputAssembler.InputLayout = this.inputLayout;
00138
00139             // Attach the vertex shader.
00140             context.VertexShader.SetShader(this.vertexShader, null, 0);
00141             // Apply the model constant buffer to the vertex shader.
00142             context.VertexShader.SetConstantBuffers(0, this.modelConstantBuffer);
00143
00144             if (!this.usingVprtShaders)
00145             {
00146                 // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00147                 // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00148                 // a pass-through geometry shader is used to set the render target
00149                 // array index.
00150                 context.GeometryShader.SetShader(this.geometryShader, null, 0);
00151             }
00152
00153             // Attach the pixel shader.
00154             context.PixelShader.SetShader(this.pixelShader, null, 0);
00155
00156             // Draw the objects.
00157             context.DrawIndexedInstanced(
00158                 indexCount,     // Index count per instance.
00159                 2,              // Instance count.
00160                 0,              // Start index location.
00161                 0,              // Base vertex location.
00162                 0               // Start instance location.
00163                 );
00164         }
00165
00166         /// <summary>
00167         /// Creates device-based resources to store a constant buffer, cube
00168         /// geometry, and vertex and pixel shaders. In some cases this will also
00169         /// store a geometry shader.
00170         /// </summary>
00171         public async void CreateDeviceDependentResourcesAsync()
00172         {
00173             ReleaseDeviceDependentResources();
00174
00175             usingVprtShaders = deviceResources.D3DDeviceSupportsVprt;
00176
00177             var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
00178
00179             // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3::
00180             // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature
00181             // we can avoid using a pass-through geometry shader to set the render
00182             // target array index, thus avoiding any overhead that would be
00183             // incurred by setting the geometry shader stage.
00184             var vertexShaderFileName = usingVprtShaders ? "Content\\Shaders\\VPRTVertexShader.cso" : "Content\\Shaders\\VertexShader.cso";
00185
00186             // Load the compiled vertex shader.
00187             var vertexShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync(vertexShaderFileName));
00188
00189             // After the vertex shader file is loaded, create the shader and input layout.
00190             vertexShader = this.ToDispose(new SharpDX.Direct3D11.VertexShader(
00191                 deviceResources.D3DDevice,
00192                 vertexShaderByteCode));
00193
00194             SharpDX.Direct3D11.InputElement[] vertexDesc =
00195             {
00196                 new SharpDX.Direct3D11.InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float,  0, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0),
00197                 new SharpDX.Direct3D11.InputElement("COLOR",    0, SharpDX.DXGI.Format.R32G32B32_Float, 12, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0),
00198             };
00199
00200             inputLayout = this.ToDispose(new SharpDX.Direct3D11.InputLayout(
00201                 deviceResources.D3DDevice,
00202                 vertexShaderByteCode,
00203                 vertexDesc));
00204
00205             if (!usingVprtShaders)
00206             {
00207                 // Load the compiled pass-through geometry shader.
00208                 var geometryShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync("Content\\Shaders\\GeometryShader.cso"));
00209
00210                 // After the pass-through geometry shader file is loaded, create the shader.
00211                 geometryShader = this.ToDispose(new SharpDX.Direct3D11.GeometryShader(
00212                     deviceResources.D3DDevice,
00213                     geometryShaderByteCode));
00214             }
00215
00216             // Load the compiled pixel shader.
00217             var pixelShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync("Content\\Shaders\\PixelShader.cso"));
00218
00219             // After the pixel shader file is loaded, create the shader.
00220             pixelShader = this.ToDispose(new SharpDX.Direct3D11.PixelShader(
00221                 deviceResources.D3DDevice,
00222                 pixelShaderByteCode));
00223
00224             // Load mesh vertices. Each vertex has a position and a color.
00225             // Note that the cube size has changed from the default DirectX app
00226             // template. Windows Holographic is scaled in meters, so to draw the
00227             // cube at a comfortable size we made the cube width 0.2 m (20 cm).
00228             VertexPositionColor[] cubeVertices =
00229             {
00230                 new VertexPositionColor(new Vector3(-0.1f, -0.1f, -0.1f), new Vector3(0.0f, 0.0f, 0.0f)),
00231                 new VertexPositionColor(new Vector3(-0.1f, -0.1f,  0.1f), new Vector3(0.0f, 0.0f, 1.0f)),
00232                 new VertexPositionColor(new Vector3(-0.1f,  0.1f, -0.1f), new Vector3(0.0f, 1.0f, 0.0f)),
00233                 new VertexPositionColor(new Vector3(-0.1f,  0.1f,  0.1f), new Vector3(0.0f, 1.0f, 1.0f)),
00234                 new VertexPositionColor(new Vector3( 0.1f, -0.1f, -0.1f), new Vector3(1.0f, 0.0f, 0.0f)),
00235                 new VertexPositionColor(new Vector3( 0.1f, -0.1f,  0.1f), new Vector3(1.0f, 0.0f, 1.0f)),
00236                 new VertexPositionColor(new Vector3( 0.1f,  0.1f, -0.1f), new Vector3(1.0f, 1.0f, 0.0f)),
00237                 new VertexPositionColor(new Vector3( 0.1f,  0.1f,  0.1f), new Vector3(1.0f, 1.0f, 1.0f)),
00238             };
00239
00240             vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
00241                 deviceResources.D3DDevice,
00242                 SharpDX.Direct3D11.BindFlags.VertexBuffer,
00243                 cubeVertices));
00244
00245             // Load mesh indices. Each trio of indices represents
00246             // a triangle to be rendered on the screen.
00247             // For example: 0,2,1 means that the vertices with indexes
00248             // 0, 2 and 1 from the vertex buffer compose the
00249             // first triangle of this mesh.
00250             ushort[] cubeIndices =
00251             {
00252                 2,1,0, // -x
00253                 2,3,1,
00254
00255                 6,4,5, // +x
00256                 6,5,7,
00257
00258                 0,1,5, // -y
00259                 0,5,4,
00260
00261                 2,6,7, // +y
00262                 2,7,3,
00263
00264                 0,4,6, // -z
00265                 0,6,2,
00266
00267                 1,3,7, // +z
00268                 1,7,5,
00269             };
00270
00271             indexCount = cubeIndices.Length;
00272
00273             indexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
00274                 deviceResources.D3DDevice,
00275                 SharpDX.Direct3D11.BindFlags.IndexBuffer,
00276                 cubeIndices));
00277
00278             // Create a constant buffer to store the model matrix.
00279             modelConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
00280                 deviceResources.D3DDevice,
00281                 SharpDX.Direct3D11.BindFlags.ConstantBuffer,
00282                 ref modelConstantBufferData));
00283
00284             // Once the cube is loaded, the object is ready to be rendered.
00285             loadingComplete = true;
00286         }
00287
00288         /// <summary>
00289         /// Releases device-based resources.
00290         /// </summary>
00291         public void ReleaseDeviceDependentResources()
00292         {
00293             loadingComplete = false;
00294             usingVprtShaders = false;
00295             this.RemoveAndDispose(ref vertexShader);
00296             this.RemoveAndDispose(ref inputLayout);
00297             this.RemoveAndDispose(ref pixelShader);
00298             this.RemoveAndDispose(ref geometryShader);
00299             this.RemoveAndDispose(ref modelConstantBuffer);
00300             this.RemoveAndDispose(ref vertexBuffer);
00301             this.RemoveAndDispose(ref indexBuffer);
00302         }
00303
00304         public Vector3 Position
00305         {
00306             get { return position;  }
00307             set { position = value; }
00308         }
00309     }
00310 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Server/targetver.h Source File

  • CustomCapability
  • Service
  • Server

targetver.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 // Including SDKDDKVer.h defines the highest available Windows platform.
00004
00005 // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
00006 // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
00007
00008 #include <SDKDDKVer.h>
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSuggestion/cs/Scenario1_Conversion.xaml.cs Source File

  • TextSuggestion
  • cs

Scenario1_Conversion.xaml.cs

Go to the documentation of this file.
00001 // Copyright (c) Microsoft Corporation. All rights reserved
00002
00003 using System;
00004 using Windows.Data.Text;
00005 using Windows.UI.Xaml;
00006 using Windows.UI.Xaml.Controls;
00007 using Windows.UI.Xaml.Navigation;
00008 using SDKTemplate;
00009
00010 namespace TextSuggestion
00011 {
00012     public sealed partial class Scenario1_Conversion : Page
00013     {
00014         private MainPage rootPage;
00015         private TextConversionGenerator generator;
00016
00017         /// <summary>
00018         /// Page initializer.
00019         /// </summary>
00020         public Scenario1_Conversion()
00021         {
00022             this.InitializeComponent();
00023         }
00024
00025         /// <summary>
00026         /// Clean up the notification area when user navigate to prediction page
00027         /// </summary>
00028         /// <param name="e">Event data that describes the click action on the button.</param>
00029         protected override void OnNavigatedTo(NavigationEventArgs e)
00030         {
00031             rootPage = MainPage.Current;
00032
00033             // Clean notification area.
00034             rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
00035         }
00036
00037         /// <summary>
00038         /// This is the click handler for the 'Execute' button.
00039         /// When this button is activated, the text suggestion generator will get
00040         /// the conversion result for given input string and language tag, then
00041         /// print them in result column.
00042         /// Using 'async' keyword to indicate that this method runs asynchronously
00043         /// and contains one 'await' expression.
00044         /// </summary>
00045         /// <param name="sender">The object that raised the event.</param>
00046         /// <param name="e">Event data that describes the click action on the button.</param>
00047         private async void Execute_Click(object sender, RoutedEventArgs e)
00048         {
00049             // Clean up result column.
00050             resultView.ItemsSource = null;
00051
00052             // Clean notification area.
00053             rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
00054
00055             var input = Input.Text;
00056
00057             ComboBoxItem selectedItem = methods.SelectedItem as ComboBoxItem;
00058
00059             if ((generator != null) && (selectedItem != null) && !String.IsNullOrEmpty(input))
00060             {
00061                 // Specify the candidate number to get.
00062                 if ((selectedItem.Tag != null) && selectedItem.Tag.ToString().Equals("needMaxCount"))
00063                 {
00064                     uint MaxCandidates = 0;
00065                     UInt32.TryParse(maxCandidates.Text, out MaxCandidates);
00066
00067                     if (MaxCandidates != 0)
00068                     {
00069                         // Call the API with max candidate number we expect, and list the result when there are any candidates.
00070                         // Using 'await' expression here to suspend the execution of this method until the awaited task completes.
00071                         resultView.ItemsSource = await generator.GetCandidatesAsync(input, MaxCandidates);
00072
00073                         if (resultView.Items.Count == 0)
00074                         {
00075                             rootPage.NotifyUser(string.Format("No candidates."), NotifyType.StatusMessage);
00076                         }
00077                     }
00078                     else
00079                     {
00080                         rootPage.NotifyUser(string.Format("Not a valid candidate number. Expecting positive integer."), NotifyType.ErrorMessage);
00081                     }
00082                 }
00083                 else
00084                 {
00085                     // Call the API with default candidate number, and list the result when there are any candidates.
00086                     resultView.ItemsSource = await generator.GetCandidatesAsync(input);
00087
00088                     if (resultView.Items.Count == 0)
00089                     {
00090                         rootPage.NotifyUser(string.Format("No candidates."), NotifyType.StatusMessage);
00091                     }
00092                 }
00093             }
00094         }
00095
00096         /// <summary>
00097         /// Selecting the API interface to use.
00098         /// User can either specify the max candidate number to get, or use the default value.
00099         /// </summary>
00100         /// <param name="sender">The object that raised the event.</param>
00101         /// <param name="e">Event data that describes the click action on the button.</param>
00102         private void Methods_SelectionChanged(object sender, SelectionChangedEventArgs e)
00103         {
00104             ComboBoxItem selectedItem = methods.SelectedItem as ComboBoxItem;
00105
00106             if (maxCandidatesArea != null)
00107             {
00108                 // Only show the candidate number input control when user chooses to specify the number.
00109                 if ((selectedItem.Tag != null) && selectedItem.Tag.ToString().Equals("needMaxCount"))
00110                 {
00111                     maxCandidatesArea.Visibility = Visibility.Visible;
00112                 }
00113                 else
00114                 {
00115                     maxCandidatesArea.Visibility = Visibility.Collapsed;
00116                 }
00117             }
00118         }
00119
00120         /// <summary>
00121         /// This is the click handler for the 'Create Generator' button.
00122         /// When this button is activated, the Text Suggestion API will try
00123         /// to resolve the language tag provided by the user, and create a
00124         /// Conversion Generator.
00125         /// </summary>
00126         /// <param name="sender">The object that raised the event.</param>
00127         /// <param name="e">Event data that describes the click action on the button.</param>
00128         private void CreateGeneratorButton_Click(object sender, RoutedEventArgs e)
00129         {
00130             // Try to parse the language and create generator accordingly.
00131             generator = new TextConversionGenerator(langTag.Text);
00132
00133             // Only allow generator operation when the language is available and installed.
00134             if (generator == null)
00135             {
00136                 if (GeneratorOperationArea != null)
00137                 {
00138                     GeneratorOperationArea.Visibility = Visibility.Collapsed;
00139                 }
00140
00141                 rootPage.NotifyUser(string.Format("Failed to instantiate a generator."), NotifyType.ErrorMessage);
00142             }
00143             else if (generator.ResolvedLanguage == "und")
00144             {
00145                 if (GeneratorOperationArea != null)
00146                 {
00147                     GeneratorOperationArea.Visibility = Visibility.Collapsed;
00148                 }
00149
00150                 rootPage.NotifyUser(string.Format("Unsupported language."), NotifyType.ErrorMessage);
00151             }
00152             else if (generator.LanguageAvailableButNotInstalled)
00153             {
00154                 if (GeneratorOperationArea != null)
00155                 {
00156                     GeneratorOperationArea.Visibility = Visibility.Collapsed;
00157                 }
00158
00159                 rootPage.NotifyUser(string.Format("Language available but not installed."), NotifyType.ErrorMessage);
00160             }
00161             else
00162             {
00163                 if (GeneratorOperationArea != null)
00164                 {
00165                     GeneratorOperationArea.Visibility = Visibility.Visible;
00166                 }
00167
00168                 rootPage.NotifyUser(string.Format("Successfully instantiated a generator."), NotifyType.StatusMessage);
00169             }
00170         }
00171     }
00172 }
Generated on Fri Nov 15 2024 22:21:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cs/Scenario3_CurrentStepCount.xaml.cs Source File

  • Pedometer
  • cs

Scenario3_CurrentStepCount.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013
00014 using System;
00015 using Windows.Devices.Enumeration;
00016 using Windows.Devices.Sensors;
00017 using Windows.Globalization.DateTimeFormatting;
00018 using Windows.UI.Xaml.Controls;
00019
00020 namespace PedometerCS
00021 {
00022     /// <summary>
00023     /// 'Current step count' illustration page
00024     /// </summary>
00025     public sealed partial class Scenario3_CurrentStepCount : Page
00026     {
00027         MainPage rootPage = MainPage.Current;
00028
00029         // Common class ID for pedometers
00030         Guid PedometerClassId = new Guid("B19F89AF-E3EB-444B-8DEA-202575A71599");
00031
00032         public Scenario3_CurrentStepCount()
00033         {
00034             this.InitializeComponent();
00035             rootPage.NotifyUser("Hit the 'Get steps count' Button", NotifyType.StatusMessage);
00036         }
00037
00038         /// <summary>
00039         /// Invoked when 'GetCurrentButton' is clicked.
00040         /// 'ReadingChanged' will not be fired when there is no activity on the pedometer
00041         /// and hence can't be reliably used to get the current step count. This handler makes
00042         /// use of 'GetCurrentReadings' API to determine the current step count
00043         /// </summary>
00044         async private void GetCurrentButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00045         {
00046             // Determine if we can access pedometers
00047             var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId);
00048             if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
00049             {
00050                 // Determine if a pedometer is present
00051                 // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
00052                 var sensor = await Pedometer.GetDefaultAsync();
00053                 if (sensor != null)
00054                 {
00055                     DateTime dt = DateTime.FromFileTimeUtc(0);
00056                     int totalStepCount = 0;
00057
00058                     // Get the current readings to find the current step counters
00059                     var currentReadings = sensor.GetCurrentReadings();
00060                     bool updateTimestamp = true;
00061                     foreach (PedometerStepKind kind in Enum.GetValues(typeof(PedometerStepKind)))
00062                     {
00063                         PedometerReading reading;
00064                         if (currentReadings.TryGetValue(kind, out reading))
00065                         {
00066                             totalStepCount += reading.CumulativeSteps;
00067                         }
00068                         if (updateTimestamp)
00069                         {
00070                             DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");
00071                             ScenarioOutput_Timestamp.Text = timestampFormatter.Format(reading.Timestamp);
00072                             updateTimestamp = false;
00073                         }
00074                     }
00075
00076                     ScenarioOutput_TotalStepCount.Text = totalStepCount.ToString();
00077                     rootPage.NotifyUser("Hit the 'Get steps count' Button", NotifyType.StatusMessage);
00078
00079                     // Re-enable button
00080                     GetCurrentButton.IsEnabled = true;
00081                 }
00082                 else
00083                 {
00084                     rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage);
00085                 }
00086             }
00087             else
00088             {
00089                 rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage);
00090             }
00091         }
00092     }
00093 }
Generated on Fri Nov 15 2024 22:20:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AdvertisementPublisherTask Member List

This is the complete list of members for AdvertisementPublisherTask, including all inherited members.
backgroundTaskInstance | AdvertisementPublisherTask | [private]
Run(IBackgroundTaskInstance taskInstance) | AdvertisementPublisherTask | [inline]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFontImplementation/TextLayoutImageSource.cpp Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFontImplementation

TextLayoutImageSource.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "TextLayoutImageSource.h"
00014 #include "DirectXHelper.h"
00015
00016 using namespace DWriteTextLayoutCloudFontImplementation;
00017 using namespace Platform;
00018 using namespace Microsoft::WRL;
00019 using namespace Windows::ApplicationModel;
00020 using namespace Windows::UI::Xaml;
00021
00022 using Windows::UI::Colors;
00023
00024
00025
00026 // Constructors:
00027
00028 // On older devices, the size of the canvas in which we can draw may be limited. For this sample,
00029 // the amount of text and the size of the frame containing the text have been limited to ensure that
00030 // the maximum dimension never exceeds 2048 pixels (the required minimum for DirectX feature level
00031 // 9_1) on a 200% scale display.
00032
00033 TextLayoutImageSource::TextLayoutImageSource(TextLayout^ textLayout, float dpi) :
00034     TextLayoutImageSource(textLayout, dpi, Colors::Black, Colors::White) {}
00035
00036
00037 TextLayoutImageSource::TextLayoutImageSource(TextLayout^ textLayout, float dpi, Windows::UI::Color textColor, Windows::UI::Color backgroundColor) :
00038     SurfaceImageSource(DX::DipsToPixelsCeil(textLayout->Width, dpi), DX::DipsToPixelsCeil(textLayout->Height, dpi)),
00039     m_textLayout(textLayout),
00040     m_dpi(dpi),
00041     m_width(textLayout->Width),
00042     m_height(textLayout->Height),
00043     m_pixelWidth(DX::DipsToPixelsCeil(m_width, dpi)),
00044     m_pixelHeight(DX::DipsToPixelsCeil(m_height, dpi))
00045 {
00046     CreateDeviceResources();
00047     m_suspendEventHandlerRegistrationToken = Application::Current->Suspending += ref new SuspendingEventHandler(this, &TextLayoutImageSource::OnSuspending);
00048
00049     SetTextColor(textColor);
00050     SetTextBackgroundColor(backgroundColor);
00051     Draw();
00052 }
00053
00054
00055 TextLayoutImageSource::~TextLayoutImageSource()
00056 {
00057     Application::Current->Suspending -= m_suspendEventHandlerRegistrationToken;
00058 }
00059
00060
00061 // Other Private methods:
00062
00063 void TextLayoutImageSource::CreateDeviceResources()
00064 {
00065     // This flag adds support for surfaces with a different color channel ordering
00066     // than the API default. It is required for compatibility with Direct2D.
00067     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00068
00069 #if defined(_DEBUG)
00070     if (DX::SdkLayersAvailable())
00071     {
00072         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00073         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00074     }
00075 #endif
00076
00077     // This array defines the set of DirectX hardware feature levels this app will support.
00078     // Note the ordering should be preserved.
00079     // Don't forget to declare your application's minimum required feature level in its
00080     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00081     D3D_FEATURE_LEVEL featureLevels[] =
00082     {
00083         D3D_FEATURE_LEVEL_11_1,
00084         D3D_FEATURE_LEVEL_11_0,
00085         D3D_FEATURE_LEVEL_10_1,
00086         D3D_FEATURE_LEVEL_10_0,
00087         D3D_FEATURE_LEVEL_9_3,
00088         D3D_FEATURE_LEVEL_9_2,
00089         D3D_FEATURE_LEVEL_9_1
00090     };
00091
00092     // Create the Direct3D 11 API device object.
00093     HRESULT hr = D3D11CreateDevice(
00094         nullptr,                    // Specify nullptr to use the default adapter.
00095         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00096         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00097         creationFlags,              // Set debug and Direct2D compatibility flags.
00098         featureLevels,              // List of feature levels this app can support.
00099         ARRAYSIZE(featureLevels),
00100         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00101         &m_d3dDevice,               // Returns the Direct3D device created.
00102         nullptr,
00103         nullptr
00104         );
00105
00106     if (FAILED(hr))
00107     {
00108         // If the initialization fails, fall back to the WARP device.
00109         // For more information on WARP, see:
00110         // http://go.microsoft.com/fwlink/?LinkId=286690
00111         DX::ThrowIfFailed(
00112             D3D11CreateDevice(
00113                 nullptr,
00114                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00115                 0,
00116                 creationFlags,
00117                 featureLevels,
00118                 ARRAYSIZE(featureLevels),
00119                 D3D11_SDK_VERSION,
00120                 &m_d3dDevice,
00121                 nullptr,
00122                 nullptr
00123                 )
00124             );
00125     }
00126
00127     // Get the Direct3D 11.1 API device.
00128     ComPtr<IDXGIDevice> dxgiDevice;
00129     DX::ThrowIfFailed(
00130         m_d3dDevice.As(&dxgiDevice)
00131         );
00132
00133     // Create the Direct2D device object and a corresponding context.
00134     DX::ThrowIfFailed(
00135         D2D1CreateDevice(
00136             dxgiDevice.Get(),
00137             nullptr,
00138             &m_d2dDevice
00139             )
00140         );
00141
00142     DX::ThrowIfFailed(
00143         m_d2dDevice->CreateDeviceContext(
00144             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00145             &m_d2dContext
00146             )
00147         );
00148
00149     // Set the DPI on the context -- it will operate in DIPs and handle scaling
00150     // to device pixels.
00151     m_d2dContext->SetDpi(m_dpi, m_dpi);
00152
00153     // Grayscale text anti-aliasing is recommended for all Windows Runtime apps.
00154     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00155
00156     // Query for ISurfaceImageSourceNative interface.
00157     ComPtr<ISurfaceImageSourceNative> sisNative;
00158     DX::ThrowIfFailed(
00159         reinterpret_cast<IUnknown*>(this)->QueryInterface(IID_PPV_ARGS(&sisNative))
00160         );
00161
00162     // Associate the DXGI device with the SurfaceImageSource.
00163     DX::ThrowIfFailed(
00164         sisNative->SetDevice(dxgiDevice.Get())
00165         );
00166 }
00167
00168
00169 void TextLayoutImageSource::SetTextColor(Windows::UI::Color color)
00170 {
00171     D2D1_COLOR_F d2dColor = DX::ConvertToColorF(color);
00172     m_d2dContext->CreateSolidColorBrush(d2dColor, &m_textBrush);
00173 }
00174
00175
00176 void TextLayoutImageSource::SetTextBackgroundColor(Windows::UI::Color color)
00177 {
00178     m_backgroundColor = DX::ConvertToColorF(color);
00179     m_d2dContext->CreateSolidColorBrush(m_backgroundColor, &m_textBackgroundBrush);
00180 }
00181
00182
00183 void TextLayoutImageSource::Draw()
00184 {
00185     // If the device was lost in one of the steps, an exception will bubble up.
00186     // We'll test for the relevant errors and attempt to recreate the device.
00187     try
00188     {
00189         BeginDraw();
00190         Clear();
00191         DrawText();
00192         EndDraw();
00193     }
00194     catch (Platform::Exception^ e)
00195     {
00196         HRESULT hr = e->HResult;
00197         if (hr == D2DERR_RECREATE_TARGET || hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00198         {
00199             // If the device has been removed or reset, attempt to recreate it and continue drawing.
00200             CreateDeviceResources();
00201             Draw();
00202         }
00203         else
00204         {
00205             // Notify the caller by throwing an exception if any other error was encountered.
00206             // If hit after a recursively re-entering, we won't be making another recursive
00207             // call -- this will bubble back up the call stack.
00208             DX::ThrowIfFailed(hr);
00209         }
00210     }
00211 }
00212
00213
00214 void TextLayoutImageSource::BeginDraw()
00215 {
00216     POINT offset = {}; // Returned from the SurfaceImageSource in device pixel units.
00217     ComPtr<IDXGISurface> surface;
00218
00219     // Express target area as a native RECT type.
00220     RECT updateRectNative;
00221     updateRectNative.left = 0;
00222     updateRectNative.top = 0;
00223     updateRectNative.right = static_cast<LONG>(m_pixelWidth);
00224     updateRectNative.bottom = static_cast<LONG>(m_pixelHeight);
00225
00226     // Query for ISurfaceImageSourceNative interface.
00227     ComPtr<ISurfaceImageSourceNative> sisNative;
00228     DX::ThrowIfFailed(
00229         reinterpret_cast<IUnknown*>(this)->QueryInterface(IID_PPV_ARGS(&sisNative))
00230         );
00231
00232     // Begin drawing - returns a target surface and an offset to use as the top left origin when drawing.
00233     DX::ThrowIfFailed(
00234         sisNative->BeginDraw(updateRectNative, &surface, &offset)
00235         );
00236
00237     // Create render target.
00238     ComPtr<ID2D1Bitmap1> bitmap;
00239     DX::ThrowIfFailed(
00240         m_d2dContext->CreateBitmapFromDxgiSurface(
00241             surface.Get(),
00242             nullptr,
00243             &bitmap
00244             )
00245         );
00246
00247     // Set context's render target.
00248     m_d2dContext->SetTarget(bitmap.Get());
00249
00250     // Begin drawing using D2D context.
00251     m_d2dContext->BeginDraw();
00252
00253     // Apply a clip and transform to constrain updates to the target update area.
00254     // This is required to ensure coordinates within the target surface remain
00255     // consistent by taking into account the offset returned by BeginDraw, and
00256     // can also improve performance by optimizing the area that is drawn by D2D.
00257     // Apps should always account for the offset output parameter returned by
00258     // BeginDraw, since it may not match the passed updateRect input parameter's location.
00259     m_d2dContext->PushAxisAlignedClip(
00260         D2D1::RectF(
00261             floorf(DX::PixelsToDips(offset.x, m_dpi)),
00262             floorf(DX::PixelsToDips(offset.y, m_dpi)),
00263             ceilf(DX::PixelsToDips(offset.x, m_dpi) + m_width),
00264             ceilf(DX::PixelsToDips(offset.y, m_dpi) + m_height)
00265             ),
00266         D2D1_ANTIALIAS_MODE_ALIASED
00267         );
00268
00269     m_d2dContext->SetTransform(
00270         D2D1::Matrix3x2F::Translation(
00271             DX::PixelsToDips(offset.x, m_dpi),
00272             DX::PixelsToDips(offset.y, m_dpi)
00273             )
00274         );
00275 }
00276
00277
00278 void TextLayoutImageSource::EndDraw()
00279 {
00280     // Remove the transform and clip applied in BeginDraw since
00281     // the target area can change on every update.
00282     m_d2dContext->SetTransform(D2D1::IdentityMatrix());
00283     m_d2dContext->PopAxisAlignedClip();
00284
00285     // Remove the render target and end drawing.
00286     m_d2dContext->SetTarget(nullptr);
00287     DX::ThrowIfFailed(
00288         m_d2dContext->EndDraw()
00289         );
00290
00291     // Query for ISurfaceImageSourceNative interface.
00292     Microsoft::WRL::ComPtr<ISurfaceImageSourceNative> sisNative;
00293     DX::ThrowIfFailed(
00294         reinterpret_cast<IUnknown*>(this)->QueryInterface(IID_PPV_ARGS(&sisNative))
00295         );
00296
00297     DX::ThrowIfFailed(
00298         sisNative->EndDraw()
00299         );
00300 }
00301
00302
00303 void TextLayoutImageSource::Clear()
00304 {
00305     m_d2dContext->Clear(m_backgroundColor);
00306 }
00307
00308
00309 void TextLayoutImageSource::DrawText()
00310 {
00311     // The underlying IDWriteTextLayout from the TextLayout object will be needed
00312     // to interact with D2D.
00313     Microsoft::WRL::ComPtr<IDWriteTextLayout> dwriteTextLayout = m_textLayout->GetDWriteTextLayout();
00314
00315     DWRITE_TEXT_METRICS textMetrics;
00316     DX::ThrowIfFailed(
00317         dwriteTextLayout->GetMetrics(&textMetrics)
00318         );
00319
00320     m_d2dContext->FillRectangle(
00321         D2D1::RectF(0.0f, 0.0f, textMetrics.widthIncludingTrailingWhitespace, textMetrics.height),
00322         m_textBackgroundBrush.Get()
00323         );
00324
00325     m_d2dContext->DrawTextLayout(D2D1::Point2F(), dwriteTextLayout.Get(), m_textBrush.Get());
00326 }
00327
00328
00329 // event handlers
00330
00331 void TextLayoutImageSource::OnSuspending(Object ^sender, SuspendingEventArgs ^e)
00332 {
00333     // Hint to the display driver that the app is entering an idle state and that its
00334     // memory can be used temporarily for other apps.
00335
00336     ComPtr<IDXGIDevice3> dxgiDevice;
00337     m_d3dDevice.As(&dxgiDevice);
00338     dxgiDevice->Trim();
00339 }
Generated on Fri Nov 15 2024 22:19:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Personalization/cpp/SetLockScreenImage.xaml.h Source File

  • Personalization
  • cpp

SetLockScreenImage.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1.xaml.h
00014 // Declaration of the Scenario1 class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "SetLockScreenImage.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     [Windows::Foundation::Metadata::WebHostHidden]
00026     public ref class SetLockScreenImage sealed
00027     {
00028     public:
00029         SetLockScreenImage();
00030
00031     protected:
00032         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00033
00034     private:
00035         MainPage^ rootPage;
00036         void PickAndSetButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037     };
00038 }
Generated on Fri Nov 15 2024 22:20:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProximitySensor/cpp/Tasks/ProximitySensorBackgroundTask.h Source File

  • ProximitySensor
  • cpp
  • Tasks

ProximitySensorBackgroundTask.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ProximitySensorBackgroundTask.h
00014 // Declaration of the ProximitySensorBackgroundTask class
00015 //
00016
00017 #pragma once
00018
00019 namespace Tasks
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ProximitySensorBackgroundTask sealed : public Windows::ApplicationModel::Background::IBackgroundTask
00023     {
00024     public:
00025         ProximitySensorBackgroundTask();
00026         virtual void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance);
00027         void OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason);
00028
00029     private:
00030         ~ProximitySensorBackgroundTask() {}
00031         Windows::ApplicationModel::Background::IBackgroundTaskInstance^ TaskInstance;
00032     };
00033 }
Generated on Fri Nov 15 2024 22:21:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/Templates.xaml.cs Source File

  • XamlBind
  • cs

Templates.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using Windows.UI.Xaml.Data;
00007
00008 namespace xBindSampleCS
00009 {
00010     public partial class Templates
00011     {
00012         public Templates()
00013         {
00014             InitializeComponent();
00015         }
00016     }
00017 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_ProvisionTPM Member List

This is the complete list of members for Scenario1_ProvisionTPM, including all inherited members.
Create_Click(object sender, RoutedEventArgs e) | Scenario1_ProvisionTPM | [inline, private]
HandleCardAdded(SmartCardReader sender, CardAddedEventArgs args) | Scenario1_ProvisionTPM | [inline, private]
NTE_DEVICE_NOT_FOUND | Scenario1_ProvisionTPM | [private]
NTE_DEVICE_NOT_READY | Scenario1_ProvisionTPM | [private]
ParsePinPolicy() | Scenario1_ProvisionTPM | [inline, private]
pinPolicyAllowed | Scenario1_ProvisionTPM | [private]
pinPolicyDisallowed | Scenario1_ProvisionTPM | [private]
pinPolicyRequireOne | Scenario1_ProvisionTPM | [private]
reader | Scenario1_ProvisionTPM | [private]
rootPage | Scenario1_ProvisionTPM | [private]
Scenario1_ProvisionTPM() | Scenario1_ProvisionTPM | [inline]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/pch.cpp Source File

  • ApplicationResources
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraAdvancedCapture/cs/App.xaml.cs Source File

  • CameraAdvancedCapture
  • cs

App.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.Activation;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 namespace CameraAdvancedCapture
00019 {
00020     /// <summary>
00021     /// Provides application-specific behavior to supplement the default Application class.
00022     /// </summary>
00023     sealed partial class App : Application
00024     {
00025         /// <summary>
00026         /// Initializes the singleton application object.  This is the first line of authored code
00027         /// executed, and as such is the logical equivalent of main() or WinMain().
00028         /// </summary>
00029         public App()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         /// <summary>
00035         /// Invoked when the application is launched normally by the end user.  Other entry points
00036         /// will be used such as when the application is launched to open a specific file.
00037         /// </summary>
00038         /// <param name="e">Details about the launch request and process.</param>
00039         protected override void OnLaunched(LaunchActivatedEventArgs e)
00040         {
00041
00042 #if DEBUG
00043             if (System.Diagnostics.Debugger.IsAttached)
00044             {
00045                 this.DebugSettings.EnableFrameRateCounter = true;
00046             }
00047 #endif
00048
00049             Frame rootFrame = Window.Current.Content as Frame;
00050
00051             // Do not repeat app initialization when the Window already has content,
00052             // just ensure that the window is active
00053             if (rootFrame == null)
00054             {
00055                 // Create a Frame to act as the navigation context and navigate to the first page
00056                 rootFrame = new Frame();
00057                 // Set the default language
00058                 rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
00059
00060                 rootFrame.NavigationFailed += OnNavigationFailed;
00061
00062                 // Place the frame in the current Window
00063                 Window.Current.Content = rootFrame;
00064             }
00065
00066             if (rootFrame.Content == null)
00067             {
00068                 // When the navigation stack isn't restored navigate to the first page,
00069                 // configuring the new page by passing required information as a navigation
00070                 // parameter
00071                 rootFrame.Navigate(typeof(MainPage), e.Arguments);
00072             }
00073             // Ensure the current window is active
00074             Window.Current.Activate();
00075         }
00076
00077         /// <summary>
00078         /// Invoked when Navigation to a certain page fails
00079         /// </summary>
00080         /// <param name="sender">The Frame which failed navigation</param>
00081         /// <param name="e">Details about the navigation failure</param>
00082         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00083         {
00084             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00085         }
00086     }
00087 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario9_Compare.xaml.h Source File

  • FileAccess
  • cpp

Scenario9_Compare.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario9_Compare.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Comparing two files to see if they are the same file.
00022     /// </summary>
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class Scenario9 sealed
00025     {
00026     public:
00027         Scenario9();
00028         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029
00030     private:
00031         MainPage^ rootPage = MainPage::Current;
00032
00033         void CompareFilesButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034     };
00035 }
Generated on Fri Nov 15 2024 22:19:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Constants Member List

This is the complete list of members for Constants, including all inherited members.
CalcServiceUuid | Constants | [static]
ConnectEntryPoint | Constants | [static]
ConnectTaskName | Constants | [static]
ContactEmail | Constants | [private]
ContactFirstName | Constants | [private]
ContactImageSource | Constants | [private, static]
ContactLastName | Constants | [private]
ContactListName | Constants | [private]
ContactPhone | Constants | [private]
ContactRemoteId | Constants | [private, static]
DeviceWatcherTaskName | Constants | [static]
gattOperandParameters | Constants | [static]
gattOperatorParameters | Constants | [static]
gattResultParameters | Constants | [static]
MetadataUpdateEntryPoint | Constants | [static]
MetadataUpdateTaskName | Constants | [static]
Op1CharacteristicUuid | Constants | [static]
Op2CharacteristicUuid | Constants | [static]
OperatorCharacteristicUuid | Constants | [static]
Protocol | Constants | [private]
ResultCharacteristicUuid | Constants | [static]
RfcommChatServiceUuid | Constants | [static]
SampleHotspotGuid | Constants | [static]
SdpServiceName | Constants |
SdpServiceNameAttributeId | Constants |
SdpServiceNameAttributeType | Constants |
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomUsbDeviceAccess/cs/EventHandlerForDevice.cs Source File

  • CustomUsbDeviceAccess
  • cs

EventHandlerForDevice.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017
00018 using Windows.Devices.Enumeration;
00019 using Windows.Devices.Usb;
00020
00021 using Windows.ApplicationModel;
00022 using Windows.Foundation;
00023
00024 using Windows.UI.Core;
00025 using Windows.UI.Xaml;
00026
00027 using SDKTemplate;
00028
00029 namespace CustomUsbDeviceAccess
00030 {
00031     /// <summary>
00032     /// The purpose of this class is to demonstrate the expected application behavior for app events
00033     /// such as suspension and resume or when the device is disconnected. In addition to handling
00034     /// the UsbDevice, the app's state should also be saved upon app suspension (will not be demonstrated here).
00035     ///
00036     /// This class will also demonstrate how to handle device watcher events.
00037     ///
00038     /// For simplicity, this class will only allow at most one device to be connected at any given time. In order
00039     /// to make this class support multiple devices, make this class a non-singleton and create multiple instances
00040     /// of this class; each instance should watch one connected device.
00041     /// </summary>
00042     public class EventHandlerForDevice
00043     {
00044         /// <summary>
00045         /// Allows for singleton EventHandlerForDevice
00046         /// </summary>
00047         private static EventHandlerForDevice eventHandlerForDevice;
00048
00049         /// <summary>
00050         /// Used to synchronize threads to avoid multiple instantiations of eventHandlerForDevice.
00051         /// </summary>
00052         private static Object singletonCreationLock = new Object();
00053
00054         private String deviceSelector;
00055         private DeviceWatcher deviceWatcher;
00056
00057         private DeviceInformation deviceInformation;
00058         private DeviceAccessInformation deviceAccessInformation;
00059         private UsbDevice device;
00060
00061         private SuspendingEventHandler appSuspendCallback;
00062
00063         private SuspendingEventHandler appSuspendEventHandler;
00064         private EventHandler<Object> appResumeEventHandler;
00065
00066         private TypedEventHandler<EventHandlerForDevice, DeviceInformation> deviceCloseCallback;
00067         private TypedEventHandler<EventHandlerForDevice, DeviceInformation> deviceConnectedCallback;
00068
00069         private TypedEventHandler<DeviceWatcher, DeviceInformation> deviceAddedEventHandler;
00070         private TypedEventHandler<DeviceWatcher, DeviceInformationUpdate> deviceRemovedEventHandler;
00071         private TypedEventHandler<DeviceAccessInformation, DeviceAccessChangedEventArgs> deviceAccessEventHandler;
00072
00073         private Boolean watcherSuspended;
00074         private Boolean watcherStarted;
00075         private Boolean isEnabledAutoReconnect;
00076
00077         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00078         // as NotifyUser()
00079         private MainPage rootPage = MainPage.Current;
00080
00081         /// <summary>
00082         /// Enforces the singleton pattern so that there is only one object handling app events
00083         /// as it relates to the UsbDevice because this sample app only supports communicating with one device at a time.
00084         ///
00085         /// An instance of EventHandlerForDevice is globally available because the device needs to persist across scenario pages.
00086         ///
00087         /// If there is no instance of EventHandlerForDevice created before this property is called,
00088         /// an EventHandlerForDevice will be created.
00089         /// </summary>
00090         public static EventHandlerForDevice Current
00091         {
00092             get
00093             {
00094                 if (eventHandlerForDevice == null)
00095                 {
00096                     lock (singletonCreationLock)
00097                     {
00098                         if (eventHandlerForDevice == null)
00099                         {
00100                             CreateNewEventHandlerForDevice();
00101                         }
00102                     }
00103                 }
00104
00105                 return eventHandlerForDevice;
00106             }
00107         }
00108
00109         /// <summary>
00110         /// Creates a new instance of EventHandlerForDevice, enables auto reconnect, and uses it as the Current instance.
00111         /// </summary>
00112         public static void CreateNewEventHandlerForDevice()
00113         {
00114             eventHandlerForDevice = new EventHandlerForDevice();
00115         }
00116
00117         public SuspendingEventHandler OnAppSuspendCallback
00118         {
00119             get
00120             {
00121                 return appSuspendCallback;
00122             }
00123
00124             set
00125             {
00126                 appSuspendCallback = value;
00127             }
00128         }
00129
00130         public TypedEventHandler<EventHandlerForDevice, DeviceInformation> OnDeviceClose
00131         {
00132             get
00133             {
00134                 return deviceCloseCallback;
00135             }
00136
00137             set
00138             {
00139                 deviceCloseCallback = value;
00140             }
00141         }
00142
00143         public TypedEventHandler<EventHandlerForDevice, DeviceInformation> OnDeviceConnected
00144         {
00145             get
00146             {
00147                 return deviceConnectedCallback;
00148             }
00149
00150             set
00151             {
00152                 deviceConnectedCallback = value;
00153             }
00154         }
00155
00156         public Boolean IsDeviceConnected
00157         {
00158             get
00159             {
00160                 return (device != null);
00161             }
00162         }
00163
00164         public UsbDevice Device
00165         {
00166             get
00167             {
00168                 return device;
00169             }
00170         }
00171
00172         /// <summary>
00173         /// This DeviceInformation represents which device is connected or which device will be reconnected when
00174         /// the device is plugged in again (if IsEnabledAutoReconnect is true);.
00175         /// </summary>
00176         public DeviceInformation DeviceInformation
00177         {
00178             get
00179             {
00180                 return deviceInformation;
00181             }
00182         }
00183
00184         /// <summary>
00185         /// Returns DeviceAccessInformation for the device that is currently connected using this EventHandlerForDevice
00186         /// object.
00187         /// </summary>
00188         public DeviceAccessInformation DeviceAccessInformation
00189         {
00190             get
00191             {
00192                 return deviceAccessInformation;
00193             }
00194         }
00195
00196         /// <summary>
00197         /// DeviceSelector AQS used to find this device
00198         /// </summary>
00199         public String DeviceSelector
00200         {
00201             get
00202             {
00203                 return deviceSelector;
00204             }
00205         }
00206
00207         /// <summary>
00208         /// True if EventHandlerForDevice will attempt to reconnect to the device once it is plugged into the computer again
00209         /// </summary>
00210         public Boolean IsEnabledAutoReconnect
00211         {
00212             get
00213             {
00214                 return isEnabledAutoReconnect;
00215             }
00216             set
00217             {
00218                 isEnabledAutoReconnect = value;
00219             }
00220         }
00221
00222         /// <summary>
00223         /// This method opens the device using the WinRT USB API. After the device is opened, save the device
00224         /// so that it can be used across scenarios.
00225         ///
00226         /// It is important that the FromIdAsync call is made on the UI thread because the consent prompt can only be displayed
00227         /// on the UI thread.
00228         ///
00229         /// This method is used to reopen the device after the device reconnects to the computer and when the app resumes.
00230         /// </summary>
00231         /// <param name="deviceInfo">Device information of the device to be opened</param>
00232         /// <param name="deviceSelector">The AQS used to find this device</param>
00233         /// <returns>True if the device was successfully opened, false if the device could not be opened for well known reasons.
00234         /// An exception may be thrown if the device could not be opened for extraordinary reasons.</returns>
00235         public async Task<Boolean> OpenDeviceAsync(DeviceInformation deviceInfo, String deviceSelector)
00236         {
00237             device = await UsbDevice.FromIdAsync(deviceInfo.Id);
00238
00239             Boolean successfullyOpenedDevice = false;
00240             NotifyType notificationStatus;
00241             String notificationMessage = null;
00242
00243             // Device could have been blocked by user or the device has already been opened by another app.
00244             if (device != null)
00245             {
00246                 successfullyOpenedDevice = true;
00247
00248                 deviceInformation = deviceInfo;
00249                 this.deviceSelector = deviceSelector;
00250
00251                 notificationStatus = NotifyType.StatusMessage;
00252                 notificationMessage = "Device " + deviceInformation.Id + " opened";
00253
00254                 // Notify registered callback handle that the device has been opened
00255                 if (deviceConnectedCallback != null)
00256                 {
00257                     deviceConnectedCallback(this, deviceInformation);
00258                 }
00259
00260                 if (appSuspendEventHandler == null || appResumeEventHandler == null)
00261                 {
00262                     RegisterForAppEvents();
00263                 }
00264
00265                 // Register for DeviceAccessInformation.AccessChanged event and react to any changes to the
00266                 // user access after the device handle was opened.
00267                 if (deviceAccessEventHandler == null)
00268                 {
00269                     RegisterForDeviceAccessStatusChange();
00270                 }
00271
00272                 // Create and register device watcher events for the device to be opened unless we're reopening the device
00273                 if (deviceWatcher == null)
00274                 {
00275                     deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector);
00276
00277                     RegisterForDeviceWatcherEvents();
00278                 }
00279
00280                 if (!watcherStarted)
00281                 {
00282                     // Start the device watcher after we made sure that the device is opened.
00283                     StartDeviceWatcher();
00284                 }
00285             }
00286             else
00287             {
00288                 successfullyOpenedDevice = false;
00289
00290                 notificationStatus = NotifyType.ErrorMessage;
00291
00292                 var deviceAccessStatus = DeviceAccessInformation.CreateFromId(deviceInfo.Id).CurrentStatus;
00293
00294                 if (deviceAccessStatus == DeviceAccessStatus.DeniedByUser)
00295                 {
00296                     notificationMessage = "Access to the device was blocked by the user : " + deviceInfo.Id;
00297                 }
00298                 else if (deviceAccessStatus == DeviceAccessStatus.DeniedBySystem)
00299                 {
00300                     // This status is most likely caused by app permissions (did not declare the device in the app's package.appxmanifest)
00301                     // This status does not cover the case where the device is already opened by another app.
00302                     notificationMessage = "Access to the device was blocked by the system : " + deviceInfo.Id;
00303                 }
00304                 else
00305                 {
00306                     // Most likely the device is opened by another app, but cannot be sure
00307                     notificationMessage = "Unknown error, possibly opened by another app : " + deviceInfo.Id;
00308                 }
00309             }
00310
00311             MainPage.Current.NotifyUser(notificationMessage, notificationStatus);
00312
00313             return successfullyOpenedDevice;
00314         }
00315
00316         /// <summary>
00317         /// Closes the device, stops the device watcher, stops listening for app events, and resets object state to before a device
00318         /// was ever connected.
00319         /// </summary>
00320         public void CloseDevice()
00321         {
00322             if (IsDeviceConnected)
00323             {
00324                 CloseCurrentlyConnectedDevice();
00325             }
00326
00327             if (deviceWatcher != null)
00328             {
00329                 if (watcherStarted)
00330                 {
00331                     StopDeviceWatcher();
00332
00333                     UnregisterFromDeviceWatcherEvents();
00334                 }
00335
00336                 deviceWatcher = null;
00337             }
00338
00339             if (deviceAccessInformation != null)
00340             {
00341                 UnregisterFromDeviceAccessStatusChange();
00342
00343                 deviceAccessInformation = null;
00344             }
00345
00346             if (appSuspendEventHandler != null || appResumeEventHandler != null)
00347             {
00348                 UnregisterFromAppEvents();
00349             }
00350
00351             deviceInformation = null;
00352             deviceSelector = null;
00353
00354             deviceConnectedCallback = null;
00355             deviceCloseCallback = null;
00356
00357             isEnabledAutoReconnect = true;
00358         }
00359
00360         private EventHandlerForDevice()
00361         {
00362             watcherStarted = false;
00363             watcherSuspended = false;
00364             isEnabledAutoReconnect = true;
00365         }
00366
00367         /// <summary>
00368         /// This method demonstrates how to close the device properly using the WinRT USB API.
00369         ///
00370         /// When the UsbDevice is closing, it will cancel all IO operations that are still pending (not complete).
00371         /// The close will not wait for any IO completion callbacks to be called, so the close call may complete before any of
00372         /// the IO completion callbacks are called.
00373         /// The pending IO operations will still call their respective completion callbacks with either a task
00374         /// cancelled error or the operation completed.
00375         /// </summary>
00376         private async void CloseCurrentlyConnectedDevice()
00377         {
00378             if (device != null)
00379             {
00380                 // Notify callback that we're about to close the device
00381                 if (deviceCloseCallback != null)
00382                 {
00383                     deviceCloseCallback(this, deviceInformation);
00384                 }
00385
00386                 // This closes the handle to the device
00387                 device.Dispose();
00388
00389                 device = null;
00390
00391                 // Save the deviceInformation.Id in case deviceInformation is set to null when closing the
00392                 // device
00393                 String deviceId = deviceInformation.Id;
00394
00395                 await rootPage.Dispatcher.RunAsync(
00396                     CoreDispatcherPriority.Normal,
00397                     new DispatchedHandler(() =>
00398                     {
00399                         MainPage.Current.NotifyUser(deviceId + " is closed", NotifyType.StatusMessage);
00400                     }));
00401             }
00402         }
00403
00404         /// <summary>
00405         /// Register for app suspension/resume events. See the comments
00406         /// for the event handlers for more information on the exact device operation performed.
00407         ///
00408         /// We will also register for when the app exists so that we may close the device handle.
00409         /// </summary>
00410         private void RegisterForAppEvents()
00411         {
00412             appSuspendEventHandler = new SuspendingEventHandler(EventHandlerForDevice.Current.OnAppSuspension);
00413             appResumeEventHandler = new EventHandler<Object>(EventHandlerForDevice.Current.OnAppResume);
00414
00415             // This event is raised when the app is exited and when the app is suspended
00416             App.Current.Suspending += appSuspendEventHandler;
00417
00418             App.Current.Resuming += appResumeEventHandler;
00419         }
00420
00421         private void UnregisterFromAppEvents()
00422         {
00423             // This event is raised when the app is exited and when the app is suspended
00424             App.Current.Suspending -= appSuspendEventHandler;
00425             appSuspendEventHandler = null;
00426
00427             App.Current.Resuming -= appResumeEventHandler;
00428             appResumeEventHandler = null;
00429         }
00430
00431         /// <summary>
00432         /// Register for Added and Removed events.
00433         /// Note that, when disconnecting the device, the device may be closed by the system before the OnDeviceRemoved callback is invoked.
00434         /// </summary>
00435         private void RegisterForDeviceWatcherEvents()
00436         {
00437             deviceAddedEventHandler = new TypedEventHandler<DeviceWatcher, DeviceInformation>(this.OnDeviceAdded);
00438
00439             deviceRemovedEventHandler = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(this.OnDeviceRemoved);
00440
00441             deviceWatcher.Added += deviceAddedEventHandler;
00442
00443             deviceWatcher.Removed += deviceRemovedEventHandler;
00444         }
00445
00446         private void UnregisterFromDeviceWatcherEvents()
00447         {
00448             deviceWatcher.Added -= deviceAddedEventHandler;
00449             deviceAddedEventHandler = null;
00450
00451             deviceWatcher.Removed -= deviceRemovedEventHandler;
00452             deviceRemovedEventHandler = null;
00453         }
00454
00455         /// <summary>
00456         /// Listen for any changed in device access permission. The user can block access to the device while the device is in use.
00457         /// If the user blocks access to the device while the device is opened, the device's handle will be closed automatically by
00458         /// the system; it is still a good idea to close the device explicitly so that resources are cleaned up.
00459         ///
00460         /// Note that by the time the AccessChanged event is raised, the device handle may already be closed by the system.
00461         /// </summary>
00462         private void RegisterForDeviceAccessStatusChange()
00463         {
00464             deviceAccessInformation = DeviceAccessInformation.CreateFromId(deviceInformation.Id);
00465
00466             deviceAccessEventHandler = new TypedEventHandler<DeviceAccessInformation, DeviceAccessChangedEventArgs>(this.OnDeviceAccessChanged);
00467             deviceAccessInformation.AccessChanged += deviceAccessEventHandler;
00468         }
00469
00470         private void UnregisterFromDeviceAccessStatusChange()
00471         {
00472             deviceAccessInformation.AccessChanged -= deviceAccessEventHandler;
00473
00474             deviceAccessEventHandler = null;
00475         }
00476
00477         private void StartDeviceWatcher()
00478         {
00479             watcherStarted = true;
00480
00481             if ((deviceWatcher.Status != DeviceWatcherStatus.Started)
00482                 && (deviceWatcher.Status != DeviceWatcherStatus.EnumerationCompleted))
00483             {
00484                 deviceWatcher.Start();
00485             }
00486         }
00487
00488         private void StopDeviceWatcher()
00489         {
00490             if ((deviceWatcher.Status == DeviceWatcherStatus.Started)
00491                 || (deviceWatcher.Status == DeviceWatcherStatus.EnumerationCompleted))
00492             {
00493                 deviceWatcher.Stop();
00494             }
00495
00496             watcherStarted = false;
00497         }
00498
00499         /// <summary>
00500         /// If a UsbDevice object has been instantiated (a handle to the device is opened), we must close it before the app
00501         /// goes into suspension because the API automatically closes it for us if we don't. When resuming, the API will
00502         /// not reopen the device automatically, so we need to explicitly open the device in the app (Scenario1_ConnectDisconnect_ConnectDisconnect).
00503         ///
00504         /// Since we have to reopen the device ourselves when the app resumes, it is good practice to explicitly call the close
00505         /// in the app as well (For every open there is a close).
00506         ///
00507         /// We must stop the DeviceWatcher because it will continue to raise events even if
00508         /// the app is in suspension, which is not desired (drains battery). We resume the device watcher once the app resumes again.
00509         /// </summary>
00510         /// <param name="sender"></param>
00511         /// <param name="eventArgs"></param>
00512         private void OnAppSuspension(Object sender, SuspendingEventArgs args)
00513         {
00514             if (watcherStarted)
00515             {
00516                 watcherSuspended = true;
00517                 StopDeviceWatcher();
00518             }
00519             else
00520             {
00521                 watcherSuspended = false;
00522             }
00523
00524             CloseCurrentlyConnectedDevice();
00525         }
00526
00527         /// <summary>
00528         /// When resume into the application, we should reopen a handle to the USB device again. This will automatically
00529         /// happen when we start the device watcher again; the device will be re-enumerated and we will attempt to reopen it
00530         /// if IsEnabledAutoReconnect property is enabled.
00531         ///
00532         /// See OnAppSuspension for why we are starting the device watcher again
00533         /// </summary>
00534         /// <param name="sender"></param>
00535         /// <param name="arg"></param>
00536         private void OnAppResume(Object sender, Object args)
00537         {
00538             if (watcherSuspended)
00539             {
00540                 watcherSuspended = false;
00541                 StartDeviceWatcher();
00542             }
00543         }
00544
00545         /// <summary>
00546         /// Close the device that is opened so that all pending operations are canceled properly.
00547         /// </summary>
00548         /// <param name="sender"></param>
00549         /// <param name="deviceInformationUpdate"></param>
00550         private void OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceInformationUpdate)
00551         {
00552             if (IsDeviceConnected && (deviceInformationUpdate.Id == deviceInformation.Id))
00553             {
00554                 // The main reasons to close the device explicitly is to clean up resources, to properly handle errors,
00555                 // and stop talking to the disconnected device.
00556                 CloseCurrentlyConnectedDevice();
00557             }
00558         }
00559
00560         /// <summary>
00561         /// Open the device that the user wanted to open if it hasn't been opened yet and auto reconnect is enabled.
00562         /// </summary>
00563         /// <param name="sender"></param>
00564         /// <param name="deviceInfo"></param>
00565         private async void OnDeviceAdded(DeviceWatcher sender, DeviceInformation deviceInfo)
00566         {
00567             if ((deviceInformation != null) && (deviceInfo.Id == deviceInformation.Id) && !IsDeviceConnected && isEnabledAutoReconnect)
00568             {
00569                 await rootPage.Dispatcher.RunAsync(
00570                     CoreDispatcherPriority.Normal,
00571                     new DispatchedHandler(async () =>
00572                     {
00573                         await OpenDeviceAsync(deviceInformation, deviceSelector);
00574
00575                         // Any app specific device intialization should be done here because we don't know the state of the device when it is re-enumerated.
00576                     }));
00577             }
00578         }
00579
00580         /// <summary>
00581         /// Close the device if the device access was denied by anyone (system or the user) and reopen it if permissions are allowed again
00582         /// </summary>
00583         /// <param name="sender"></param>
00584         /// <param name="eventArgs"></param>
00585         private async void OnDeviceAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs eventArgs)
00586         {
00587             if ((eventArgs.Status == DeviceAccessStatus.DeniedBySystem)
00588                 || (eventArgs.Status == DeviceAccessStatus.DeniedByUser))
00589             {
00590                 CloseCurrentlyConnectedDevice();
00591             }
00592             else if ((eventArgs.Status == DeviceAccessStatus.Allowed) && (deviceInformation != null) && isEnabledAutoReconnect)
00593             {
00594                 await rootPage.Dispatcher.RunAsync(
00595                     CoreDispatcherPriority.Normal,
00596                     new DispatchedHandler(async () =>
00597                     {
00598                         await OpenDeviceAsync(deviceInformation, deviceSelector);
00599
00600                         // Any app specific device intialization should be done here because we don't know the state of the device when it is re-enumerated.
00601                     }));
00602             }
00603         }
00604     }
00605 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/HttpFilters/pch.h Source File

  • HttpClient
  • HttpFilters

pch.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002 #include <unknwn.h>
00003 #include <winrt/Windows.Foundation.h>
00004 #include <winrt/Windows.Foundation.Collections.h>
00005 #include <winrt/Windows.Networking.Connectivity.h>
00006 #include <winrt/Windows.Web.Http.h>
00007 #include <winrt/Windows.Web.Http.Filters.h>
00008 #include <winrt/Windows.Web.Http.Headers.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geotag/cpp/SampleConfiguration.cpp Source File

  • Geotag
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Geotag a file", "SDKTemplate.Scenario1_Geotag" }
00012 };
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScannerProvider/cpp/BarcodeDecoder/Provider.cpp Source File

  • BarcodeScannerProvider
  • cpp
  • BarcodeDecoder

Provider.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Provider.h"
00013
00014 using namespace concurrency;
00015 using namespace Platform;
00016 using namespace Windows::ApplicationModel::Background;
00017 using namespace Windows::ApplicationModel::Resources;
00018 using namespace Windows::Devices::PointOfService;
00019 using namespace Windows::Devices::PointOfService::Provider;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Graphics::Imaging;
00022 using namespace Windows::Security::Cryptography;
00023 using namespace Windows::Storage::Streams;
00024 using namespace Windows::UI::Xaml;
00025
00026 namespace BarcodeDecoder
00027 {
00028     Provider::Provider(IBackgroundTaskInstance^ backgroundTask) :
00029         m_backgroundTask(backgroundTask)
00030     {
00031         auto triggerDetails = safe_cast<BarcodeScannerProviderTriggerDetails^>(backgroundTask->TriggerDetails);
00032         m_connection = triggerDetails->Connection;
00033
00034         Initialize();
00035     }
00036
00037     Provider::~Provider()
00038     {
00039         CleanUp();
00040     }
00041
00042     void Provider::CleanUp()
00043     {
00044         delete m_frameReader;
00045         m_frameReader = nullptr;
00046
00047         delete m_connection;
00048         m_connection = nullptr;
00049
00050         if (m_deferral != nullptr)
00051         {
00052             m_deferral->Complete();
00053             m_deferral = nullptr;
00054         }
00055     }
00056
00057     BarcodeScannerReport^ Provider::CreateBarcodeScannerReportFromString(String^ barcodeString, UINT barcodeSymbology)
00058     {
00059         IBuffer^ barcodeDataBuffer = CryptographicBuffer::ConvertStringToBinary(barcodeString, BinaryStringEncoding::Utf8);
00060         return ref new BarcodeScannerReport(barcodeSymbology, barcodeDataBuffer, barcodeDataBuffer);
00061     }
00062
00063     void Provider::Initialize()
00064     {
00065         m_deferral = m_backgroundTask->GetDeferral();
00066         RegisterEventHandlers();
00067
00068         // Set provider information. This information is localized, so read it from our resources.
00069         ResourceLoader^ resourceLoader = ResourceLoader::GetForViewIndependentUse();
00070         m_connection->CompanyName = resourceLoader->GetString("Company");
00071         m_connection->Name = resourceLoader->GetString("Product");
00072         m_connection->Version = resourceLoader->GetString("Version");
00073
00074         m_decodeEngine = ref new DecodeEngine();
00075
00076         BarcodeSymbologyAttributesBuilder^ attributesBuilder = ref new BarcodeSymbologyAttributesBuilder();
00077
00078         // Our decode engine does not support any of these features.
00079         attributesBuilder->IsCheckDigitTransmissionSupported = false;
00080         attributesBuilder->IsCheckDigitValidationSupported = false;
00081         attributesBuilder->IsDecodeLengthSupported = false;
00082
00083         // Tell the system which symbologies we support.
00084         for (UINT symbology : m_decodeEngine->SupportedSymbologies)
00085         {
00086             // Set symbologies supported by the provider
00087             m_connection->SupportedSymbologies->Append(symbology);
00088
00089             // Populate a std::map for tracking symbology attributes for each supported symbology.
00090             // (This step is unnecessary in the case of this sample because none of these properties
00091             // is marked as supported in our BarcodeSymbologyAttributesBuilder, but we track them
00092             // in this sample in order to show how it could be done.)
00093             BarcodeSymbologyAttributes^ defaultAttributes = attributesBuilder->CreateAttributes();
00094             if (attributesBuilder->IsDecodeLengthSupported)
00095             {
00096                 // These are the default values, but we set them explicitly for demonstration purposes.
00097                 defaultAttributes->DecodeLength1 = 0;
00098                 defaultAttributes->DecodeLength2 = 0;
00099                 defaultAttributes->DecodeLengthKind = BarcodeSymbologyDecodeLengthKind::AnyLength;
00100             }
00101             if (attributesBuilder->IsCheckDigitTransmissionSupported)
00102             {
00103                 // This is the default value, but we set it explicitly for demonstration purposes.
00104                 defaultAttributes->IsCheckDigitTransmissionEnabled = false;
00105             }
00106             if (attributesBuilder->IsCheckDigitValidationSupported)
00107             {
00108                 // This is the default value, but we set it explicitly for demonstration purposes.
00109                 defaultAttributes->IsCheckDigitValidationEnabled = false;
00110             }
00111
00112             m_symbologyAttributes[symbology] = defaultAttributes;
00113         }
00114
00115         // Start the connection after
00116         // 1. Provider information is set
00117         // 2. Supported symbologies are added
00118         // 3. All event handlers are registered
00119         m_connection->Start();
00120     }
00121
00122     void Provider::RegisterEventHandlers()
00123     {
00124         m_backgroundTask->Canceled += ref new BackgroundTaskCanceledEventHandler(this, &Provider::BackgroundTask_Canceled);
00125         m_backgroundTask->Task->Completed += ref new BackgroundTaskCompletedEventHandler(this, &Provider::Task_Completed);
00126
00127         m_connection->EnableScannerRequested += ref new TypedEventHandler<BarcodeScannerProviderConnection^, BarcodeScannerEnableScannerRequestEventArgs^>(this, &Provider::BarcodeScannerProviderConnection_EnableScannerRequested);
00128         m_connection->DisableScannerRequested += ref new TypedEventHandler<BarcodeScannerProviderConnection^, BarcodeScannerDisableScannerRequestEventArgs^>(this, &Provider::BarcodeScannerProviderConnection_DisableScannerRequested);
00129
00130         m_connection->GetBarcodeSymbologyAttributesRequested += ref new TypedEventHandler<BarcodeScannerProviderConnection^, BarcodeScannerGetSymbologyAttributesRequestEventArgs^>(this, &Provider::BarcodeScannerProviderConnection_GetBarcodeSymbologyAttributesRequested);
00131         m_connection->SetBarcodeSymbologyAttributesRequested += ref new TypedEventHandler<BarcodeScannerProviderConnection^, BarcodeScannerSetSymbologyAttributesRequestEventArgs^>(this, &Provider::BarcodeScannerProviderConnection_SetBarcodeSymbologyAttributesRequested);
00132
00133         m_connection->StartSoftwareTriggerRequested += ref new TypedEventHandler<BarcodeScannerProviderConnection^, BarcodeScannerStartSoftwareTriggerRequestEventArgs^>(this, &Provider::BarcodeScannerProviderConnection_StartSoftwareTriggerRequested);
00134         m_connection->StopSoftwareTriggerRequested += ref new TypedEventHandler<BarcodeScannerProviderConnection^, BarcodeScannerStopSoftwareTriggerRequestEventArgs^>(this, &Provider::BarcodeScannerProviderConnection_StopSoftwareTriggerRequested);
00135
00136         m_connection->HideVideoPreviewRequested += ref new TypedEventHandler<BarcodeScannerProviderConnection^, BarcodeScannerHideVideoPreviewRequestEventArgs^>(this, &Provider::BarcodeScannerProviderConnection_HideVideoPreviewRequested);
00137         m_connection->SetActiveSymbologiesRequested += ref new TypedEventHandler<BarcodeScannerProviderConnection^, BarcodeScannerSetActiveSymbologiesRequestEventArgs^>(this, &Provider::BarcodeScannerProviderConnection_SetActiveSymbologiesRequested);
00138     }
00139
00140     void Provider::Task_Completed(BackgroundTaskRegistration^ sender, BackgroundTaskCompletedEventArgs^ args)
00141     {
00142         CleanUp();
00143     }
00144
00145     void Provider::BackgroundTask_Canceled(IBackgroundTaskInstance^ sender, BackgroundTaskCancellationReason args)
00146     {
00147         CleanUp();
00148     }
00149
00150     void Provider::BarcodeScannerProviderConnection_EnableScannerRequested(BarcodeScannerProviderConnection^ sender, BarcodeScannerEnableScannerRequestEventArgs^ args)
00151     {
00152         // For BarcodeScannerProviderConnection events,
00153         // a deferral is not required if the only async operation
00154         // is ReportCompletedAsync or ReportFailedAsync.
00155         m_scannerEnabled = true;
00156         create_task(args->Request->ReportCompletedAsync());
00157     }
00158
00159     void Provider::BarcodeScannerProviderConnection_DisableScannerRequested(BarcodeScannerProviderConnection^ sender, BarcodeScannerDisableScannerRequestEventArgs^ args)
00160     {
00161         m_scannerEnabled = false;
00162
00163         // Stop the frame reader if we have one.
00164         task<void> stopFrameReaderTask = task_from_result();
00165         if (m_frameReader != nullptr)
00166         {
00167             stopFrameReaderTask = create_task(m_frameReader->StopAsync());
00168         }
00169
00170         stopFrameReaderTask.then([args]()
00171         {
00172             return args->Request->ReportCompletedAsync();
00173         }).then([deferral = args->GetDeferral()]()
00174         {
00175             deferral->Complete();
00176         });
00177     }
00178
00179     void Provider::BarcodeScannerProviderConnection_GetBarcodeSymbologyAttributesRequested(BarcodeScannerProviderConnection^ sender, BarcodeScannerGetSymbologyAttributesRequestEventArgs^ args)
00180     {
00181         UINT requestedSymbology = args->Request->Symbology;
00182         if (m_symbologyAttributes.find(requestedSymbology) != m_symbologyAttributes.end())
00183         {
00184             create_task(args->Request->ReportCompletedAsync(m_symbologyAttributes[requestedSymbology]));
00185         }
00186         else
00187         {
00188             create_task(args->Request->ReportFailedAsync(static_cast<int>(E_BOUNDS), L"The requested symbology is not supported."));
00189         }
00190     }
00191
00192     void Provider::BarcodeScannerProviderConnection_SetBarcodeSymbologyAttributesRequested(BarcodeScannerProviderConnection^ sender, BarcodeScannerSetSymbologyAttributesRequestEventArgs^ args)
00193     {
00194         UINT requestedSymbology = args->Request->Symbology;
00195         BarcodeSymbologyAttributes^ newAttributes = args->Request->Attributes;
00196
00197         if (m_symbologyAttributes.find(requestedSymbology) != m_symbologyAttributes.end())
00198         {
00199             BarcodeSymbologyAttributes^ existingAttributes = m_symbologyAttributes[requestedSymbology];
00200             if (existingAttributes->IsDecodeLengthSupported)
00201             {
00202                 existingAttributes->DecodeLength1 = newAttributes->DecodeLength1;
00203                 existingAttributes->DecodeLength2 = newAttributes->DecodeLength2;
00204                 existingAttributes->DecodeLengthKind = newAttributes->DecodeLengthKind;
00205             }
00206             if (existingAttributes->IsCheckDigitTransmissionSupported)
00207             {
00208                 existingAttributes->IsCheckDigitTransmissionEnabled = newAttributes->IsCheckDigitTransmissionEnabled;
00209             }
00210             if (existingAttributes->IsCheckDigitValidationSupported)
00211             {
00212                 existingAttributes->IsCheckDigitValidationEnabled = newAttributes->IsCheckDigitValidationEnabled;
00213             }
00214
00215             create_task(args->Request->ReportCompletedAsync());
00216         }
00217         else
00218         {
00219             create_task(args->Request->ReportFailedAsync(static_cast<int>(E_BOUNDS), L"The requested symbology is not supported."));
00220         }
00221     }
00222
00223     void Provider::FrameReader_FrameArrived(BarcodeScannerFrameReader^ sender, BarcodeScannerFrameReaderFrameArrivedEventArgs^ args)
00224     {
00225         if (!m_scannerEnabled)
00226         {
00227             // Return immediately if decoder is not enabled
00228             return;
00229         }
00230
00231         create_task(sender->TryAcquireLatestFrameAsync()).then([](BarcodeScannerVideoFrame^ frame)
00232         {
00233             // Build software bitmap from pixel data if we have any.
00234             return frame ? SoftwareBitmap::CreateCopyFromBuffer(frame->PixelData, frame->Format, static_cast<int>(frame->Width), static_cast<int>(frame->Height)) : nullptr;
00235         }).then([this](SoftwareBitmap^ frameBitmap)
00236         {
00237             return frameBitmap ? m_decodeEngine->DecodeAsync(frameBitmap) : task_from_result(static_cast<DecodeResult^>(nullptr));
00238         }).then([this](DecodeResult^ decodeResult)
00239         {
00240             // Report only if the result is different from previous one
00241             if (decodeResult && !DecodeResult::Equals(decodeResult, m_previousDecodeResult))
00242             {
00243                 m_previousDecodeResult = decodeResult;
00244
00245                 BarcodeScannerReport^ report = CreateBarcodeScannerReportFromString(decodeResult->Text, decodeResult->Symbology);
00246                 return create_task(m_connection->ReportScannedDataAsync(report));
00247             }
00248             else
00249             {
00250                 return task_from_result();
00251             }
00252         }).then([deferral = args->GetDeferral()]()
00253         {
00254             deferral->Complete();
00255         });
00256     }
00257
00258     void Provider::BarcodeScannerProviderConnection_StartSoftwareTriggerRequested(BarcodeScannerProviderConnection^ sender, BarcodeScannerStartSoftwareTriggerRequestEventArgs^ args)
00259     {
00260         task<bool> readerStartedTask = task_from_result(false);
00261
00262         if (m_scannerEnabled)
00263         {
00264             // Create a frame reader to read video frames if we don't have one already.
00265             task<void> readerCreatedTask = task_from_result();
00266             if (m_frameReader == nullptr)
00267             {
00268                 readerCreatedTask = create_task(m_connection->CreateFrameReaderAsync(BitmapPixelFormat::Nv12, BitmapSize{ 1280, 720 }))
00269                     .then([this](BarcodeScannerFrameReader^ newFrameReader)
00270                 {
00271                     m_frameReader = newFrameReader;
00272                     m_frameReader->FrameArrived += ref new TypedEventHandler<BarcodeScannerFrameReader^, BarcodeScannerFrameReaderFrameArrivedEventArgs^>(this, &Provider::FrameReader_FrameArrived);
00273                 });
00274             }
00275
00276             readerStartedTask = readerCreatedTask.then([this]()
00277             {
00278                 return m_frameReader->StartAsync();
00279             });
00280         }
00281
00282         readerStartedTask.then([args](bool success)
00283         {
00284             if (success)
00285             {
00286                 return args->Request->ReportCompletedAsync();
00287             }
00288             else
00289             {
00290                 return args->Request->ReportFailedAsync();
00291             }
00292         }).then([deferral = args->GetDeferral()]()
00293         {
00294             deferral->Complete();
00295         });
00296     }
00297
00298     void Provider::BarcodeScannerProviderConnection_StopSoftwareTriggerRequested(BarcodeScannerProviderConnection^ sender, BarcodeScannerStopSoftwareTriggerRequestEventArgs^ args)
00299     {
00300         // Stop the frame reader if we have one.
00301         task<void> stopTask = task_from_result();
00302         if (m_frameReader != nullptr)
00303         {
00304             stopTask = create_task(m_frameReader->StopAsync());
00305         }
00306
00307         stopTask.then([args]()
00308         {
00309             return args->Request->ReportCompletedAsync();
00310         }).then([deferral = args->GetDeferral()]()
00311         {
00312             deferral->Complete();
00313         });
00314     }
00315
00316     void Provider::BarcodeScannerProviderConnection_HideVideoPreviewRequested(BarcodeScannerProviderConnection^ sender, BarcodeScannerHideVideoPreviewRequestEventArgs^ args)
00317     {
00318         // There is no video preview running as background task. Simply report completed.
00319         create_task(args->Request->ReportCompletedAsync());
00320     }
00321
00322     void Provider::BarcodeScannerProviderConnection_SetActiveSymbologiesRequested(BarcodeScannerProviderConnection^ sender, BarcodeScannerSetActiveSymbologiesRequestEventArgs^ args)
00323     {
00324         auto newActiveSymbologies = ref new Platform::Collections::Vector<UINT>();
00325
00326         // Ensure symbologies being set to active are supported
00327         for (auto symbology : args->Request->Symbologies)
00328         {
00329             UINT index;
00330             if (!m_decodeEngine->SupportedSymbologies->IndexOf(symbology, &index))
00331             {
00332                 // Found invalid symbology
00333                 create_task(args->Request->ReportFailedAsync());
00334                 return;
00335             }
00336
00337             newActiveSymbologies->Append(symbology);
00338         }
00339
00340         m_decodeEngine->ActiveSymbologies = newActiveSymbologies;
00341
00342         create_task(args->Request->ReportCompletedAsync());
00343     }
00344 }
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomUsbDeviceAccess/cs/Scenario2_ControlTransfer.xaml.cs Source File

  • CustomUsbDeviceAccess
  • cs

Scenario2_ControlTransfer.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Devices.Usb;
00016 using Windows.Storage.Streams;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020 using SDKTemplate;
00021 using CustomUsbDeviceAccess;
00022
00023 namespace CustomUsbDeviceAccess
00024 {
00025     /// <summary>
00026     /// This page demonstrates how to use control transfers to communicate with the device.
00027     /// </summary>
00028     public sealed partial class Scenario2_ControlTransfer : Page
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         private MainPage rootPage = MainPage.Current;
00033
00034         public Scenario2_ControlTransfer()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         /// <summary>
00040         /// Invoked when this page is about to be displayed in a Frame.
00041         ///
00042         /// We will enable/disable parts of the UI if the device doesn't support it.
00043         /// </summary>
00044         /// <param name="eventArgs">Event data that describes how this page was reached.  The Parameter
00045         /// property is typically used to configure the page.</param>
00046         protected override void OnNavigatedTo(NavigationEventArgs eventArgs)
00047         {
00048             // We will disable the scenario that is not supported by the device.
00049             // If no devices are connected, none of the scenarios will be shown and an error will be displayed
00050             Dictionary<DeviceType, UIElement> deviceScenarios = new Dictionary<DeviceType, UIElement>();
00051             deviceScenarios.Add(DeviceType.OsrFx2, OsrFx2Scenario);
00052             deviceScenarios.Add(DeviceType.SuperMutt, SuperMuttScenario);
00053
00054             Utilities.SetUpDeviceScenarios(deviceScenarios, DeviceScenarioContainer);
00055         }
00056
00057         private async void GetOsrFx2SevenSegmentSetting_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00058         {
00059             if (EventHandlerForDevice.Current.IsDeviceConnected)
00060             {
00061                 ButtonGetOsrFx2SevenSegment.IsEnabled = false;
00062
00063                 await GetOsrFx2SevenSegmentAsync();
00064
00065                 ButtonGetOsrFx2SevenSegment.IsEnabled = true;
00066             }
00067             else
00068             {
00069                 Utilities.NotifyDeviceNotConnected();
00070             }
00071
00072         }
00073
00074         async void SetOsrFx2SevenSegmentSetting_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00075         {
00076             if (EventHandlerForDevice.Current.IsDeviceConnected)
00077             {
00078                 ButtonSetOsrFx2SevenSegment.IsEnabled = false;
00079
00080                 Byte numericValue = (Byte)OsrFx2SevenSegmentSettingInput.SelectedIndex;
00081
00082                 await SetOsrFx2SevenSegmentAsync(numericValue);
00083
00084                 ButtonSetOsrFx2SevenSegment.IsEnabled = true;
00085             }
00086             else
00087             {
00088                 Utilities.NotifyDeviceNotConnected();
00089             }
00090
00091         }
00092
00093         async void GetSuperMuttLedBlinkPattern_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00094         {
00095             if (EventHandlerForDevice.Current.IsDeviceConnected)
00096             {
00097                 ButtonGetSuperMuttLedBlinkPattern.IsEnabled = false;
00098
00099                 await GetSuperMuttLedBlinkPatternAsync();
00100
00101                 ButtonGetSuperMuttLedBlinkPattern.IsEnabled = true;
00102             }
00103             else
00104             {
00105                 Utilities.NotifyDeviceNotConnected();
00106             }
00107
00108         }
00109
00110         async void SetSuperMuttLedBlinkPattern_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00111         {
00112             if (EventHandlerForDevice.Current.IsDeviceConnected)
00113             {
00114                 ButtonSetSuperMuttLedBlinkPattern.IsEnabled = false;
00115
00116                 Byte pattern = (Byte)SuperMuttLedBlinkPatternInput.SelectedIndex;
00117
00118                 await SetSuperMuttLedBlinkPatternAsync(pattern);
00119
00120                 ButtonSetSuperMuttLedBlinkPattern.IsEnabled = true;
00121             }
00122             else
00123             {
00124                 Utilities.NotifyDeviceNotConnected();
00125             }
00126         }
00127
00128         /// <summary>
00129         /// Sets the seven segment display on the OSRFX2 device via control transfer
00130         ///
00131         /// Before sending the data through the control transfer, the numeric value is converted into a hex value that is
00132         /// bit masked. Different sections of the bit mask will turn on a different LEDs. Please refer to the OSRFX2 spec
00133         /// to see the hex values per LED.
00134         ///
00135         /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be
00136         /// handled at the end of the task chain.
00137         ///
00138         /// Setting Seven Segment LED require setup packet:
00139         /// bmRequestType:   type:       VENDOR
00140         ///                  recipient:  DEVICE
00141         /// bRequest:        0xDB
00142         /// wLength:         1
00143         ///
00144         /// The Buffer is used to hold data that is meant to be sent over during the data phase.
00145         /// The easiest way to write data to an IBuffer is to use a DataWriter. The DataWriter, when instantiated,
00146         /// creates a buffer internally. The buffer is of type IBuffer and can be detached from the writer, which gives us
00147         /// the internal IBuffer.
00148         /// </summary>
00149         /// <param name="numericValue"></param>
00150         /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
00151         async Task SetOsrFx2SevenSegmentAsync(Byte numericValue)
00152         {
00153             DataWriter writer = new DataWriter();
00154
00155             // Convert the numeric value into a 7 segment LED hex value and write it to a buffer.
00156             writer.WriteByte(OsrFx2.SevenLedSegmentMask[numericValue]);
00157
00158             // The buffer with the data
00159             var bufferToSend = writer.DetachBuffer();
00160
00161             UsbSetupPacket setupPacket = new UsbSetupPacket
00162             {
00163                 RequestType = new UsbControlRequestType
00164                 {
00165                     Direction = UsbTransferDirection.Out,
00166                     Recipient = UsbControlRecipient.Device,
00167                     ControlTransferType = UsbControlTransferType.Vendor
00168                 },
00169                 Request = OsrFx2.VendorCommand.SetSevenSegment,
00170                 Value = 0,
00171                 Length = bufferToSend.Length
00172             };
00173
00174             UInt32 bytesTransferred = await EventHandlerForDevice.Current.Device.SendControlOutTransferAsync(setupPacket, bufferToSend);
00175
00176             // Make sure we sent the correct number of bytes
00177             if (bytesTransferred == bufferToSend.Length)
00178             {
00179                 MainPage.Current.NotifyUser("The segment display value is set to " + numericValue.ToString(), NotifyType.StatusMessage);
00180             }
00181             else
00182             {
00183                 MainPage.Current.NotifyUser(
00184                     "Error sending data. Sent bytes: " + bytesTransferred.ToString() + "; Tried to send : " + bufferToSend.Length,
00185                     NotifyType.ErrorMessage);
00186             }
00187         }
00188
00189         /// <summary>
00190         /// Gets the current value of the seven segment display on the OSRFX2 device via control transfer.
00191         ///
00192         /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be handled at the
00193         /// end of the task chain.
00194         ///
00195         /// When the seven segment hex value is received, we attempt to match it with a known (has a numerical value 0-9) hex value.
00196         ///
00197         /// Getting Seven Segment LED require setup packet:
00198         /// bmRequestType:   type:       VENDOR
00199         ///                  recipient:  DEVICE
00200         /// bRequest:        0xD4
00201         /// wLength:         1
00202         /// </summary>
00203         /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
00204         async Task GetOsrFx2SevenSegmentAsync()
00205         {
00206             // We expect to receive 1 byte of data with our control transfer, which is the state of the seven segment
00207             uint receiveDataSize = 1;
00208
00209             // The Seven Segment display value is only 1 byte
00210             IBuffer dataBuffer = await SendVendorControlTransferInToDeviceRecipientAsync(OsrFx2.VendorCommand.GetSevenSegment, receiveDataSize);
00211
00212             if (dataBuffer.Length == receiveDataSize)
00213             {
00214                 DataReader reader = DataReader.FromBuffer(dataBuffer);
00215
00216                 // The raw hex value representing the seven segment display
00217                 Byte rawValue = reader.ReadByte();
00218
00219                 // The LED can't display the value of 255, so if the value
00220                 // we receive is not a number, we'll know by seeing if this value changed
00221                 Byte readableValue = 255;
00222
00223                 // Find which numeric value has the segment hex value
00224                 for (int i = 0; i < OsrFx2.SevenLedSegmentMask.Length; i += 1)
00225                 {
00226                     if (rawValue == OsrFx2.SevenLedSegmentMask[i])
00227                     {
00228                         readableValue = (Byte)i;
00229
00230                         break;
00231                     }
00232                 }
00233
00234                 // Seven Segment cannot display value 255, the value we received isn't a number
00235                 if (readableValue == 255)
00236                 {
00237                     MainPage.Current.NotifyUser("The segment display is not yet initialized", NotifyType.ErrorMessage);
00238                 }
00239                 else
00240                 {
00241                     MainPage.Current.NotifyUser("The segment display value is " + readableValue.ToString(), NotifyType.StatusMessage);
00242                 }
00243             }
00244             else
00245             {
00246                 MainPage.Current.NotifyUser(
00247                     "Expected to read " + receiveDataSize.ToString() + " bytes, but got " + dataBuffer.Length.ToString(),
00248                     NotifyType.ErrorMessage);
00249             }
00250         }
00251
00252         /// <summary>
00253         /// Initiates a control transfer to set the blink pattern on the SuperMutt's LED.
00254         ///
00255         /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be handled
00256         /// at the end of the task chain.
00257         ///
00258         /// Setting LED blink pattern require setup packet:
00259         /// bmRequestType:   type:       VENDOR
00260         ///                  recipient:  DEVICE
00261         /// bRequest:        0x03
00262         /// wValue:          0-7 (any number in that range, inclusive)
00263         /// wLength:         0
00264         ///
00265         /// The SuperMutt has the following patterns:
00266         /// 0 - LED always on
00267         /// 1 - LED flash 2 seconds on, 2 off, repeat
00268         /// 2 - LED flash 2 seconds on, 1 off, 2 on, 4 off, repeat
00269         /// ...
00270         /// 7 - 7 iterations of 2 on, 1 off, followed by 4 off, repeat
00271         /// </summary>
00272         /// <param name="pattern">A number from 0-7. Each number represents a different blinking pattern</param>
00273         /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
00274         async Task SetSuperMuttLedBlinkPatternAsync(Byte pattern)
00275         {
00276             UsbSetupPacket setupPacket = new UsbSetupPacket
00277             {
00278                 RequestType = new UsbControlRequestType
00279                 {
00280                     Direction = UsbTransferDirection.Out,
00281                     Recipient = UsbControlRecipient.Device,
00282                     ControlTransferType = UsbControlTransferType.Vendor
00283                 },
00284                 Request = SuperMutt.VendorCommand.SetLedBlinkPattern,
00285                 Value = pattern,
00286                 Length = 0
00287             };
00288
00289             UInt32 bytesTransferred = await EventHandlerForDevice.Current.Device.SendControlOutTransferAsync(setupPacket);
00290
00291             MainPage.Current.NotifyUser("The Led blink pattern is set to " + pattern.ToString(), NotifyType.StatusMessage);
00292         }
00293
00294         /// <summary>
00295         /// Sets up a UsbSetupPacket that will let the device know that we are trying to get the Led blink pattern on the SuperMutt via
00296         /// control transfer.
00297         ///
00298         /// Any errors in async function will be passed down the task chain and will not be caught here because errors should
00299         /// be handled at the end of the task chain.
00300         ///
00301         /// The simplest way to obtain a byte from the buffer is by using a DataReader. DataReader provides a simple way
00302         /// to read from buffers (e.g. can return bytes, strings, ints).
00303         ///
00304         /// Do note the method that is used to send a control transfer. There are two methods to send a control transfer.
00305         /// One is to send data and the other is to get data.
00306         /// </summary>
00307         /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
00308         async Task GetSuperMuttLedBlinkPatternAsync()
00309         {
00310             // The blink pattern is 1 byte long, so we only need to retrieve 1 byte of data
00311             IBuffer buffer = await SendVendorControlTransferInToDeviceRecipientAsync(SuperMutt.VendorCommand.GetLedBlinkPattern, 1);
00312
00313             if (buffer.Length > 0)
00314             {
00315                 // Easiest way to read from a buffer
00316                 DataReader dataReader = DataReader.FromBuffer(buffer);
00317
00318                 Byte pattern = dataReader.ReadByte();
00319
00320                 MainPage.Current.NotifyUser("The Led blink pattern is " + pattern.ToString(), NotifyType.StatusMessage);
00321             }
00322             else
00323             {
00324                 MainPage.Current.NotifyUser("ControlInTransfer returned 0 bytes", NotifyType.ErrorMessage);
00325             }
00326         }
00327
00328         /// <summary>
00329         /// Sets up a UsbSetupPacket and sends control transfer that will let the device know that we are trying to retrieve data from the device.
00330         /// This method only supports vendor commands because the scenario only uses vendor commands.
00331         ///
00332         /// Do note the method that is used to send a control transfer. There are two methods to send a control transfer.
00333         /// One involves receiving buffer data in the Data stage of the control transfer, and the other involves transmiting the buffer data.
00334         ///
00335         /// The simplest way to obtain a byte from the buffer is by using a DataReader. DataReader provides a simple way
00336         /// to read from buffers (e.g. can return bytes, strings, ints).
00337         /// </summary>
00338         /// <param name="vendorCommand">Command to put into SetupPacket's Request property</param>
00339         /// <param name="dataPacketLength">Number of bytes in the data packet that is sent in the Data Stage</param>
00340         /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
00341         async Task<IBuffer> SendVendorControlTransferInToDeviceRecipientAsync(Byte vendorCommand, UInt32 dataPacketLength)
00342         {
00343             // Data will be written to this buffer when we receive it
00344             var buffer = new Windows.Storage.Streams.Buffer(dataPacketLength);
00345
00346             UsbSetupPacket setupPacket = new UsbSetupPacket
00347             {
00348                 RequestType = new UsbControlRequestType
00349                 {
00350                     Direction = UsbTransferDirection.In,
00351                     Recipient = UsbControlRecipient.Device,
00352                     ControlTransferType = UsbControlTransferType.Vendor,
00353                 },
00354                 Request = vendorCommand,
00355                 Length = dataPacketLength
00356             };
00357             return await EventHandlerForDevice.Current.Device.SendControlInTransferAsync(setupPacket, buffer);
00358         }
00359     }
00360 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SectionView Member List

This is the complete list of members for SectionView, including all inherited members.
_uiSettings | SectionView | [private]
ArticleSelected | SectionView |
ArticleTapped(object sender, TappedRoutedEventArgs e) | SectionView | [inline, private]
ContentTransitionStoryboard_Completed(object sender, object e) | SectionView | [inline, private]
LayoutRoot_SizeChanged(object sender, SizeChangedEventArgs e) | SectionView | [inline, private]
OnViewModelChanged(HeroArticlesViewModel oldValue, HeroArticlesViewModel newValue) | SectionView | [inline, private]
OnViewModelPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) | SectionView | [inline, private, static]
s_viewModelProperty | SectionView | [private, static]
SectionView() | SectionView | [inline]
UpdateForSizeChanged(double newWidth, double newHeight) | SectionView | [inline, private]
ViewModel | SectionView |
ViewModelProperty | SectionView | [static]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario1WinRTComponent/SecureInterfaceSignals.h Source File

  • AllJoyn
  • Common
  • Scenario1WinRTComponent

SecureInterfaceSignals.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #pragma once
00022
00023 namespace com { namespace microsoft { namespace Samples { namespace SecureInterface {
00024
00025 ref class SecureInterfaceSignals;
00026
00027 public interface class ISecureInterfaceSignals
00028 {
00029     event Windows::Foundation::TypedEventHandler<SecureInterfaceSignals^, SecureInterfaceTextSentReceivedEventArgs^>^ TextSentReceived;
00030 };
00031
00032 public ref class SecureInterfaceSignals sealed : [Windows::Foundation::Metadata::Default] ISecureInterfaceSignals
00033 {
00034 public:
00035     // "This signal is emitted when producer sends a text message to consumer"
00036     // Calling this method will send the TextSent signal to every member of the session.
00037     void TextSent(_In_ Platform::String^ interfaceMemberMessage);
00038
00039     // This event fires whenever the TextSent signal is sent by another member of the session.
00040     virtual event Windows::Foundation::TypedEventHandler<SecureInterfaceSignals^, SecureInterfaceTextSentReceivedEventArgs^>^ TextSentReceived
00041     {
00042         Windows::Foundation::EventRegistrationToken add(Windows::Foundation::TypedEventHandler<SecureInterfaceSignals^, SecureInterfaceTextSentReceivedEventArgs^>^ handler)
00043         {
00044             return _TextSentReceived += ref new Windows::Foundation::EventHandler<Platform::Object^>
00045             ([handler](Platform::Object^ sender, Platform::Object^ args)
00046             {
00047                 handler->Invoke(safe_cast<SecureInterfaceSignals^>(sender), safe_cast<SecureInterfaceTextSentReceivedEventArgs^>(args));
00048             }, Platform::CallbackContext::Same);
00049         }
00050         void remove(Windows::Foundation::EventRegistrationToken token)
00051         {
00052             _TextSentReceived -= token;
00053         }
00054     internal:
00055         void raise(SecureInterfaceSignals^ sender, SecureInterfaceTextSentReceivedEventArgs^ args)
00056         {
00057             _TextSentReceived(sender, args);
00058         }
00059     }
00060
00061 internal:
00062     void Initialize(_In_ ISignalEmitter^ emitter);
00063     void CallTextSentReceived(_In_ SecureInterfaceSignals^ sender, _In_ SecureInterfaceTextSentReceivedEventArgs^ args);
00064
00065 private:
00066     ISignalEmitter^ m_emitter;
00067
00068     virtual event Windows::Foundation::EventHandler<Platform::Object^>^ _TextSentReceived;
00069
00070     alljoyn_interfacedescription_member m_memberTextSent;
00071 };
00072
00073 } } } }
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppWindow/cs/SecondaryAppWindowPage.xaml.cs Source File

  • AppWindow
  • cs

SecondaryAppWindowPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013
00014 namespace SDKTemplate
00015 {
00016     public sealed partial class SecondaryAppWindowPage : Page
00017     {
00018         public SecondaryAppWindowPage()
00019         {
00020             this.InitializeComponent();
00021         }
00022     }
00023 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cs/Scenario07_PostStreamWithProgress.xaml.cs Source File

  • HttpClient
  • cs

Scenario07_PostStreamWithProgress.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Globalization;
00014 using System.Threading;
00015 using System.Threading.Tasks;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019 using Windows.Web.Http;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario07_PostStreamWithProgress : Page
00024     {
00025         MainPage rootPage = MainPage.Current;
00026
00027         private HttpClient httpClient;
00028         private CancellationTokenSource cts;
00029
00030         public Scenario07_PostStreamWithProgress()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         protected override void OnNavigatedTo(NavigationEventArgs e)
00036         {
00037             httpClient = new HttpClient();
00038             cts = new CancellationTokenSource();
00039             UpdateAddressField();
00040         }
00041
00042         protected override void OnNavigatedFrom(NavigationEventArgs e)
00043         {
00044             cts.Cancel();
00045             cts.Dispose();
00046             httpClient.Dispose();
00047         }
00048
00049         private void UpdateAddressField()
00050         {
00051             // Tell the server we want a transfer-encoding chunked response.
00052             string queryString = "";
00053             if (ChunkedResponseToggle.IsOn)
00054             {
00055                 queryString = "?chunkedResponse=1";
00056             }
00057
00058             Helpers.ReplaceQueryString(AddressField, queryString);
00059         }
00060
00061         private void ChunkedResponseToggle_Toggled(object sender, RoutedEventArgs e)
00062         {
00063             UpdateAddressField();
00064         }
00065
00066         private async void Start_Click(object sender, RoutedEventArgs e)
00067         {
00068             // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00069             // valid, absolute URI, we'll notify the user about the incorrect input.
00070             Uri resourceUri = Helpers.TryParseHttpUri(AddressField.Text);
00071             if (resourceUri == null)
00072             {
00073                 rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
00074                 return;
00075             }
00076
00077             Helpers.ScenarioStarted(StartButton, CancelButton, null);
00078             ResetFields();
00079             rootPage.NotifyUser("In progress", NotifyType.StatusMessage);
00080
00081             const uint streamLength = 100000;
00082             HttpStreamContent streamContent = new HttpStreamContent(new SlowInputStream(streamLength));
00083
00084             // If stream length is unknown, the request is chunked transfer encoded.
00085             if (!ChunkedRequestToggle.IsOn)
00086             {
00087                 streamContent.Headers.ContentLength = streamLength;
00088             }
00089
00090             IProgress<HttpProgress> progress = new Progress<HttpProgress>(ProgressHandler);
00091
00092             // This sample uses a "try" in order to support TaskCanceledException.
00093             // If you don't need to support cancellation, then the "try" is not needed.
00094             try
00095             {
00096                 HttpRequestResult result = await httpClient.TryPostAsync(resourceUri, streamContent).AsTask(cts.Token, progress);
00097
00098                 if (result.Succeeded)
00099                 {
00100                     rootPage.NotifyUser("Completed", NotifyType.StatusMessage);
00101                 }
00102                 else
00103                 {
00104                     Helpers.DisplayWebError(rootPage, result.ExtendedError);
00105                 }
00106             }
00107             catch (TaskCanceledException)
00108             {
00109                 rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
00110             }
00111
00112             RequestProgressBar.Value = 100;
00113             Helpers.ScenarioCompleted(StartButton, CancelButton);
00114         }
00115
00116         private void ResetFields()
00117         {
00118             StageField.Text = "";
00119             RetriesField.Text = "0";
00120             BytesSentField.Text = "0";
00121             TotalBytesToSendField.Text = "0";
00122             BytesReceivedField.Text = "0";
00123             TotalBytesToReceiveField.Text = "0";
00124             RequestProgressBar.Value = 0;
00125         }
00126
00127         private void ProgressHandler(HttpProgress progress)
00128         {
00129             StageField.Text = progress.Stage.ToString();
00130             RetriesField.Text = progress.Retries.ToString(CultureInfo.InvariantCulture);
00131             BytesSentField.Text = progress.BytesSent.ToString(CultureInfo.InvariantCulture);
00132             BytesReceivedField.Text = progress.BytesReceived.ToString(CultureInfo.InvariantCulture);
00133
00134             ulong totalBytesToSend = 0;
00135             if (progress.TotalBytesToSend.HasValue)
00136             {
00137                 totalBytesToSend = progress.TotalBytesToSend.Value;
00138                 TotalBytesToSendField.Text = totalBytesToSend.ToString(CultureInfo.InvariantCulture);
00139             }
00140             else
00141             {
00142                 TotalBytesToSendField.Text = "unknown";
00143             }
00144
00145             ulong totalBytesToReceive = 0;
00146             if (progress.TotalBytesToReceive.HasValue)
00147             {
00148                 totalBytesToReceive = progress.TotalBytesToReceive.Value;
00149                 TotalBytesToReceiveField.Text = totalBytesToReceive.ToString(CultureInfo.InvariantCulture);
00150             }
00151             else
00152             {
00153                 TotalBytesToReceiveField.Text = "unknown";
00154             }
00155
00156             double requestProgress = 0;
00157             if (progress.Stage == HttpProgressStage.SendingContent && totalBytesToSend > 0)
00158             {
00159                     requestProgress = progress.BytesSent * 50 / totalBytesToSend;
00160             }
00161             else if (progress.Stage == HttpProgressStage.ReceivingContent)
00162             {
00163                 // Start with 50 percent, request content was already sent.
00164                 requestProgress += 50;
00165
00166                 if (totalBytesToReceive > 0)
00167                 {
00168                     requestProgress += progress.BytesReceived * 50 / totalBytesToReceive;
00169                 }
00170             }
00171             else
00172             {
00173                 return;
00174             }
00175
00176             RequestProgressBar.Value = requestProgress;
00177         }
00178
00179         private void Cancel_Click(object sender, RoutedEventArgs e)
00180         {
00181             cts.Cancel();
00182             cts.Dispose();
00183
00184             // Re-create the CancellationTokenSource.
00185             cts = new CancellationTokenSource();
00186         }
00187     }
00188 }
Generated on Fri Nov 15 2024 22:19:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

StringTrimmer Member List

This is the complete list of members for StringTrimmer, including all inherited members.
Trim(Platform::String^s) StringTrimmer [inline, static]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundSensors/cpp/SampleConfiguration.h Source File

  • BackgroundSensors
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Background sensors";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038
00039     namespace SampleConstants
00040     {
00041         static Platform::String^ Scenario1_TaskName = "Scenario1_BackgroundTask";
00042         static Platform::String^ Scenario1_TaskEntryPoint = "BackgroundTask.Scenario1_BackgroundTask";
00043     }
00044 }
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cpp/Scenario5_ApplicationTriggerTask.xaml.cpp Source File

  • BackgroundActivation
  • cpp

Scenario5_ApplicationTriggerTask.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario4_ApplicationTriggerTask.xaml.cpp
00013 // Implementation of the ApplicationTriggerTask class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario5_ApplicationTriggerTask.xaml.h"
00018 #include "SampleConfiguration.h"
00019
00020 using namespace SDKTemplate;
00021 using namespace concurrency;
00022 using namespace Windows::ApplicationModel::Background;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 ApplicationTriggerTask::ApplicationTriggerTask()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Invoked when this page is about to be displayed in a Frame.
00035 /// </summary>
00036 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037 /// property is typically used to configure the page.</param>
00038 void ApplicationTriggerTask::OnNavigatedTo(NavigationEventArgs^ e)
00039 {
00040     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00041     // as NotifyUser()
00042     rootPage = MainPage::Current;
00043
00044     //
00045     // Attach progress and completed handlers to any existing tasks.
00046     //
00047     for (auto pair : BackgroundTaskRegistration::AllTasks)
00048     {
00049         auto task = pair->Value;
00050         if (task->Name == ApplicationTriggerTaskName)
00051         {
00052             BackgroundTaskSample::UpdateBackgroundTaskRegistrationStatus(task->Name, true);
00053             AttachProgressAndCompletedHandlers(task);
00054             break;
00055         }
00056     }
00057
00058     trigger = ref new ApplicationTrigger();
00059     UpdateUI();
00060 }
00061
00062 /// <summary>
00063 /// Attach progress and completed handers to a background task.
00064 /// </summary>
00065 /// <param name="task">The task to attach progress and completed handlers to.</param>
00066 void ApplicationTriggerTask::AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration^ task)
00067 {
00068     task->Progress += ref new BackgroundTaskProgressEventHandler(this, &ApplicationTriggerTask::OnProgress);
00069     task->Completed += ref new BackgroundTaskCompletedEventHandler(this, &ApplicationTriggerTask::OnCompleted);
00070 }
00071
00072 /// <summary>
00073 /// Register a SampleBackgroundTask.
00074 /// </summary>
00075 /// <param name="sender"></param>
00076 /// <param name="e"></param>
00077 void ApplicationTriggerTask::RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00078 {
00079     auto task = BackgroundTaskSample::RegisterBackgroundTask(nullptr,
00080                                                              ApplicationTriggerTaskName,
00081                                                              trigger,
00082                                                              nullptr);
00083     AttachProgressAndCompletedHandlers(task);
00084     UpdateUI();
00085 }
00086
00087 /// <summary>
00088 /// Unregister a SampleBackgroundTask.
00089 /// </summary>
00090 /// <param name="sender"></param>
00091 /// <param name="e"></param>
00092 void ApplicationTriggerTask::UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00093 {
00094     BackgroundTaskSample::UnregisterBackgroundTasks(ApplicationTriggerTaskName);
00095     BackgroundTaskSample::ApplicationTriggerTaskResult = "";
00096     UpdateUI();
00097 }
00098
00099 /// <summary>
00100 /// Signal an ApplicationTrigger.
00101 /// </summary>
00102 /// <param name="sender"></param>
00103 /// <param name="e"></param>
00104 void ApplicationTriggerTask::SignalBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00105 {
00106     //
00107     // Reset the completion status
00108     //
00109     BackgroundTaskSample::RemoveBackgroundTaskStatus(ApplicationTriggerTaskName);
00110
00111     //
00112     // Signal the ApplicationTrigger
00113     //
00114     auto request = create_task(trigger->RequestAsync());
00115     request.then([this](ApplicationTriggerResult result) {
00116         BackgroundTaskSample::ApplicationTriggerTaskResult = "Signal Result: " + result.ToString();
00117     });
00118     UpdateUI();
00119 }
00120
00121 /// <summary>
00122 /// Handle background task progress.
00123 /// </summary>
00124 /// <param name="task">The task that is reporting progress.</param>
00125 /// <param name="args">Arguments of the progress report.</param>
00126 void ApplicationTriggerTask::OnProgress(BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
00127 {
00128     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00129     {
00130         auto progress = "Progress: " + args->Progress + "%";
00131         BackgroundTaskSample::ApplicationTriggerTaskProgress = progress;
00132         UpdateUI();
00133     }));
00134 }
00135
00136 /// <summary>
00137 /// Handle background task completion.
00138 /// </summary>
00139 /// <param name="task">The task that is reporting completion.</param>
00140 /// <param name="args">Arguments of the completion report.</param>
00141 void ApplicationTriggerTask::OnCompleted(BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
00142 {
00143     UpdateUI();
00144 }
00145
00146 /// <summary>
00147 /// Update the scenario UI.
00148 /// </summary>
00149 void ApplicationTriggerTask::UpdateUI()
00150 {
00151     auto uiDelegate = [this]()
00152     {
00153         RegisterButton->IsEnabled = !BackgroundTaskSample::ApplicationTriggerTaskRegistered;
00154         UnregisterButton->IsEnabled = BackgroundTaskSample::ApplicationTriggerTaskRegistered;
00155         SignalButton->IsEnabled = BackgroundTaskSample::ApplicationTriggerTaskRegistered & (trigger != nullptr);
00156         Progress->Text = BackgroundTaskSample::ApplicationTriggerTaskProgress;
00157         Result->Text = BackgroundTaskSample::ApplicationTriggerTaskResult;
00158         Status->Text = BackgroundTaskSample::GetBackgroundTaskStatus(ApplicationTriggerTaskName);
00159     };
00160     auto handler = ref new Windows::UI::Core::DispatchedHandler(uiDelegate, Platform::CallbackContext::Any);
00161
00162     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, handler);
00163 }
Generated on Fri Nov 15 2024 22:18:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppServices/cppwinrt/RandomNumberService/pch.h Source File

  • AppServices
  • cppwinrt
  • RandomNumberService

pch.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002 #include <unknwn.h>
00003 #include <winrt/Windows.ApplicationModel.AppService.h>
00004 #include <winrt/Windows.ApplicationModel.Background.h>
00005 #include <winrt/Windows.Foundation.h>
00006 #include <winrt/Windows.Foundation.Collections.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/xBindSampleModel/BoolToVisibilityConverter.cs Source File

  • XamlBind
  • cs
  • xBindSampleModel

BoolToVisibilityConverter.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using Windows.UI.Xaml.Data;
00007
00008 namespace xBindSampleModel
00009 {
00010     public sealed class BoolToVisibilityConverter : IValueConverter
00011     {
00012         object IValueConverter.Convert(object value, Type targetType, object parameter, string language)
00013         {
00014             if (!value.GetType().Equals(typeof(bool)))
00015             {
00016                 throw new ArgumentException("Only Boolean is supported");
00017             }
00018             if (targetType.Equals(typeof(Windows.UI.Xaml.Visibility)))
00019             {
00020                 return ((bool)value) ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed;
00021             }
00022             else
00023             {
00024                 throw new ArgumentException("Unsuported type {0}", targetType.FullName);
00025             }
00026         }
00027
00028         object IValueConverter.ConvertBack(object value, Type targetType, object parameter, string language)
00029         {
00030             throw new NotImplementedException();
00031         }
00032     }
00033 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_SimplestAdaptiveStreaming Member List

This is the complete list of members for Scenario1_SimplestAdaptiveStreaming, including all inherited members.
Load_Click(object sender, RoutedEventArgs e) | Scenario1_SimplestAdaptiveStreaming | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_SimplestAdaptiveStreaming | [inline, protected]
Scenario1_SimplestAdaptiveStreaming() | Scenario1_SimplestAdaptiveStreaming | [inline]
Generated on Fri Nov 15 2024 22:23:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AudioCreation/cs/CustomEffect/CustomEffect.cs Source File

  • AudioCreation
  • cs
  • CustomEffect

CustomEffect.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using Windows.Media.Effects;
00004 using Windows.Foundation;
00005 using Windows.Foundation.Collections;
00006 using Windows.Media;
00007 using Windows.Media.MediaProperties;
00008 using System.Runtime.InteropServices;
00009
00010 namespace CustomEffect
00011 {
00012     // Using the COM interface IMemoryBufferByteAccess allows us to access the underlying byte array in an AudioFrame
00013     [ComImport]
00014     [Guid("5B0D3235-4DBA-4D44-865E-8F1D0E4FD04D")]
00015     [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
00016     unsafe interface IMemoryBufferByteAccess
00017     {
00018         void GetBuffer(out byte* buffer, out uint capacity);
00019     }
00020
00021     public sealed class AudioEchoEffect : IBasicAudioEffect
00022     {
00023         private AudioEncodingProperties currentEncodingProperties;
00024         private List<AudioEncodingProperties> supportedEncodingProperties;
00025
00026         private float[] echoBuffer;
00027         private int currentActiveSampleIndex;
00028         private IPropertySet propertySet;
00029
00030         // Mix does not have a set - all updates should be done through the property set.
00031         private float Mix
00032         {
00033             get
00034             {
00035                 object val;
00036                 if (propertySet != null && propertySet.TryGetValue("Mix", out val))
00037                 {
00038                     return (float)val;
00039                 }
00040                 return .5f;
00041             }
00042         }
00043
00044         public bool UseInputFrameForOutput { get { return false; } }
00045
00046         // Set up constant members in the constructor
00047         public AudioEchoEffect()
00048         {
00049             // Support 44.1kHz and 48kHz mono float
00050             supportedEncodingProperties = new List<AudioEncodingProperties>();
00051             AudioEncodingProperties encodingProps1 = AudioEncodingProperties.CreatePcm(44100, 1, 32);
00052             encodingProps1.Subtype = MediaEncodingSubtypes.Float;
00053             AudioEncodingProperties encodingProps2 = AudioEncodingProperties.CreatePcm(48000, 1, 32);
00054             encodingProps2.Subtype = MediaEncodingSubtypes.Float;
00055
00056             supportedEncodingProperties.Add(encodingProps1);
00057             supportedEncodingProperties.Add(encodingProps2);
00058         }
00059
00060         public IReadOnlyList<AudioEncodingProperties> SupportedEncodingProperties
00061         {
00062             get
00063             {
00064                 return supportedEncodingProperties;
00065             }
00066         }
00067
00068         public void SetEncodingProperties(AudioEncodingProperties encodingProperties)
00069         {
00070             currentEncodingProperties = encodingProperties;
00071
00072             // Create and initialize the echo array
00073             echoBuffer = new float[encodingProperties.SampleRate]; // exactly one second delay
00074             currentActiveSampleIndex = 0;
00075         }
00076
00077         unsafe public void ProcessFrame(ProcessAudioFrameContext context)
00078         {
00079             AudioFrame inputFrame = context.InputFrame;
00080             AudioFrame outputFrame = context.OutputFrame;
00081
00082             using (AudioBuffer inputBuffer = inputFrame.LockBuffer(AudioBufferAccessMode.Read),
00083                                 outputBuffer = outputFrame.LockBuffer(AudioBufferAccessMode.Write))
00084             using (IMemoryBufferReference inputReference = inputBuffer.CreateReference(),
00085                                             outputReference = outputBuffer.CreateReference())
00086             {
00087                 byte* inputDataInBytes;
00088                 byte* outputDataInBytes;
00089                 uint inputCapacity;
00090                 uint outputCapacity;
00091
00092                 ((IMemoryBufferByteAccess)inputReference).GetBuffer(out inputDataInBytes, out inputCapacity);
00093                 ((IMemoryBufferByteAccess)outputReference).GetBuffer(out outputDataInBytes, out outputCapacity);
00094
00095                 float* inputDataInFloat = (float*)inputDataInBytes;
00096                 float* outputDataInFloat = (float*)outputDataInBytes;
00097
00098                 float inputData;
00099                 float echoData;
00100
00101                 // Process audio data
00102                 int dataInFloatLength = (int)inputBuffer.Length / sizeof(float);
00103
00104                 for (int i = 0; i < dataInFloatLength; i++)
00105                 {
00106                     inputData = inputDataInFloat[i] * (1.0f - this.Mix);
00107                     echoData = echoBuffer[currentActiveSampleIndex] * this.Mix;
00108                     outputDataInFloat[i] = inputData + echoData;
00109                     echoBuffer[currentActiveSampleIndex] = inputDataInFloat[i];
00110                     currentActiveSampleIndex++;
00111
00112                     if (currentActiveSampleIndex == echoBuffer.Length)
00113                     {
00114                         // Wrap around (after one second of samples)
00115                         currentActiveSampleIndex = 0;
00116                     }
00117                 }
00118             }
00119         }
00120
00121         public void Close(MediaEffectClosedReason reason)
00122         {
00123             // Clean-up any effect resources
00124             // This effect doesn't care about close, so there's nothing to do
00125         }
00126
00127         public void DiscardQueuedFrames()
00128         {
00129             // Reset contents of the samples buffer
00130             Array.Clear(echoBuffer, 0, echoBuffer.Length - 1);
00131             currentActiveSampleIndex = 0;
00132         }
00133
00134         public void SetProperties(IPropertySet configuration)
00135         {
00136             this.propertySet = configuration;
00137         }
00138     }
00139 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_DeviceCapture Member List

This is the complete list of members for Scenario2_DeviceCapture, including all inherited members.
CreateAudioGraph() | Scenario2_DeviceCapture | [inline, private]
CreateGraphButton_Click(object sender, RoutedEventArgs e) | Scenario2_DeviceCapture | [inline, private]
CreateMediaEncodingProfile(StorageFile file) | Scenario2_DeviceCapture | [inline, private]
deviceInputNode | Scenario2_DeviceCapture | [private]
deviceOutputNode | Scenario2_DeviceCapture | [private]
FileButton_Click(object sender, RoutedEventArgs e) | Scenario2_DeviceCapture | [inline, private]
fileOutputNode | Scenario2_DeviceCapture | [private]
graph | Scenario2_DeviceCapture | [private]
Graph_UnrecoverableErrorOccurred(AudioGraph sender, AudioGraphUnrecoverableErrorOccurredEventArgs args) | Scenario2_DeviceCapture | [inline, private]
inputDevices | Scenario2_DeviceCapture | [private]
inputDevicesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario2_DeviceCapture | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_DeviceCapture | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_DeviceCapture | [inline, protected]
outputDevices | Scenario2_DeviceCapture | [private]
outputDevicesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario2_DeviceCapture | [inline, private]
PopulateInputDeviceList() | Scenario2_DeviceCapture | [inline, private]
PopulateOutputDeviceList() | Scenario2_DeviceCapture | [inline, private]
RecordStopButton_Click(object sender, RoutedEventArgs e) | Scenario2_DeviceCapture | [inline, private]
rootPage | Scenario2_DeviceCapture | [private]
Scenario2_DeviceCapture() | Scenario2_DeviceCapture | [inline]
SelectOutputFile() | Scenario2_DeviceCapture | [inline, private]
ToggleRecordStop() | Scenario2_DeviceCapture | [inline, private]
Generated on Fri Nov 15 2024 22:23:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialMapping/cpp/Content/ShaderStructures.h Source File

  • HolographicSpatialMapping
  • cpp
  • Content

ShaderStructures.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace WindowsHolographicCodeSamples
00015 {
00016     // Constant buffer used to send hologram position transform to the shader pipeline.
00017     struct ModelConstantBuffer
00018     {
00019         DirectX::XMFLOAT4X4 modelToWorld;
00020     };
00021
00022     // Assert that the constant buffer remains 16-byte aligned (best practice).
00023     // If shader structure members are not aligned to a 4-float boundary, data may
00024     // not show up where it is expected by the time it is read by the shader.
00025     static_assert((sizeof(ModelConstantBuffer) % (sizeof(float) * 4)) == 0, "Model constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00026
00027     // Constant buffer used to send hologram position and normal transforms to the shader pipeline.
00028     struct ModelNormalConstantBuffer
00029     {
00030         DirectX::XMFLOAT4X4 modelToWorld;
00031         DirectX::XMFLOAT4X4 normalToWorld;
00032         DirectX::XMFLOAT4   colorFadeFactor;
00033     };
00034
00035     // Assert that the constant buffer remains 16-byte aligned (best practice).
00036     // If shader structure members are not aligned to a 4-float boundary, data may
00037     // not show up where it is expected by the time it is read by the shader.
00038     static_assert((sizeof(ModelNormalConstantBuffer) % (sizeof(float) * 4)) == 0, "Model/normal constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00039
00040     // Constant buffer used to send the view-projection matrices to the shader pipeline.
00041     struct ViewProjectionConstantBuffer
00042     {
00043         DirectX::XMFLOAT4   cameraPosition;
00044         DirectX::XMFLOAT4   lightPosition;
00045         DirectX::XMFLOAT4X4 viewProjection[2];
00046     };
00047
00048     // Assert that the constant buffer remains 16-byte aligned (best practice).
00049     static_assert((sizeof(ViewProjectionConstantBuffer) % (sizeof(float) * 4)) == 0, "View/projection constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00050
00051     // Used to send per-vertex data to the vertex shader.
00052     struct VertexPositionColor
00053     {
00054         DirectX::XMFLOAT3 pos;
00055         DirectX::XMFLOAT3 color;
00056     };
00057
00058     // Used to send per-vertex data to the vertex shader, including a normal.
00059     struct VertexPositionNormalColor
00060     {
00061         DirectX::XMFLOAT3 pos;
00062         DirectX::XMFLOAT3 normal;
00063         DirectX::XMFLOAT3 color;
00064     };
00065 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PosPrinter/cs/SampleConfiguration.cs Source File

  • PosPrinter
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Devices.PointOfService;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.Devices.Enumeration;
00019
00020 namespace SDKTemplate
00021 {
00022     public partial class MainPage : Page
00023     {
00024         public const string FEATURE_NAME = "POS Printer C# Sample";
00025
00026         List<Scenario> scenarios = new List<Scenario>
00027         {
00028             new Scenario() { Title="Find, claim, and enable printer", ClassType=typeof(Scenario1_FindClaimEnable)},
00029             new Scenario() { Title="Print receipt", ClassType=typeof(Scenario2_PrintReceipt)},
00030             new Scenario() { Title="Multiple claims", ClassType=typeof(Scenario3_MultipleClaims)},
00031         };
00032
00033         internal PosPrinter Printer = null;
00034         internal ClaimedPosPrinter ClaimedPrinter = null;
00035         internal DeviceInformation deviceInfo = null;
00036         internal bool IsAnImportantTransaction = true;
00037         internal event Action StateChanged;
00038
00039         public void SubscribeToReleaseDeviceRequested()
00040         {
00041             ClaimedPrinter.ReleaseDeviceRequested += ClaimedPrinter_ReleaseDeviceRequested;
00042         }
00043
00044         public void ReleaseClaimedPrinter()
00045         {
00046             if (ClaimedPrinter != null)
00047             {
00048                 ClaimedPrinter.ReleaseDeviceRequested -= ClaimedPrinter_ReleaseDeviceRequested;
00049                 ClaimedPrinter.Dispose();
00050                 ClaimedPrinter = null;
00051                 StateChanged?.Invoke();
00052             }
00053         }
00054
00055         public void ReleaseAllPrinters()
00056         {
00057             ReleaseClaimedPrinter();
00058
00059             if (Printer != null)
00060             {
00061                 Printer.Dispose();
00062                 Printer = null;
00063                 StateChanged?.Invoke();
00064             }
00065         }
00066
00067         /// <summary>
00068         /// If the "Retain device" checkbox is checked, we retain the device.
00069         /// Otherwise, we allow the other claimant to claim the device.
00070         /// </summary>
00071         private async void ClaimedPrinter_ReleaseDeviceRequested(ClaimedPosPrinter sender, PosPrinterReleaseDeviceRequestedEventArgs args)
00072         {
00073             if (IsAnImportantTransaction)
00074             {
00075                 await sender.RetainDeviceAsync();
00076             }
00077             else
00078             {
00079                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00080                 {
00081                     NotifyUser("Lost printer claim.", NotifyType.ErrorMessage);
00082                     ReleaseClaimedPrinter();
00083                 });
00084             }
00085         }
00086     }
00087
00088     public class Scenario
00089     {
00090         public string Title { get; set; }
00091         public Type ClassType { get; set; }
00092     }
00093 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cpp/Tasks/ActivitySensorBackgroundTask.h Source File

  • ActivitySensor
  • cpp
  • Tasks

ActivitySensorBackgroundTask.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ActivitySensorBackgroundTask.h
00014 // Declaration of the ActivitySensorBackgroundTask class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020
00021 using namespace Windows::ApplicationModel::Background;
00022
00023 namespace Tasks
00024 {
00025     [Windows::Foundation::Metadata::WebHostHidden]
00026     public ref class ActivitySensorBackgroundTask sealed : public IBackgroundTask
00027     {
00028
00029     public:
00030         ActivitySensorBackgroundTask() {}
00031
00032         virtual void Run(IBackgroundTaskInstance^ taskInstance);
00033         void OnCanceled(IBackgroundTaskInstance^ taskInstance, BackgroundTaskCancellationReason reason);
00034
00035     private:
00036         ~ActivitySensorBackgroundTask() {}
00037
00038         IBackgroundTaskInstance^ TaskInstance;
00039     };
00040 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Projection/cpp/Scenario3.xaml.h Source File

  • Projection
  • cpp

Scenario3.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKSample
00018 {
00019     [Windows::UI::Xaml::Data::Bindable]
00020     public ref class DeviceInformationViewTemplate sealed
00021     {
00022     public:
00023         property Platform::String^ Name;
00024         property Platform::String^ Id;
00025     };
00026
00027     [Windows::Foundation::Metadata::WebHostHidden]
00028     public ref class Scenario3 sealed
00029     {
00030     public:
00031         Scenario3();
00032     private:
00033         int thisViewId;
00034         void StartProjecting(Windows::Devices::Enumeration::DeviceInformation^ selectedDisplay);
00035         void LoadAndDisplayScreens_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         void displayList_listview_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00037     };
00038 }
Generated on Fri Nov 15 2024 22:18:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_GetLamp Member List

This is the complete list of members for Scenario1_GetLamp, including all inherited members.
GetDefaultAsyncBtn_Click(object sender, RoutedEventArgs e) | Scenario1_GetLamp | [inline, private]
InitLampBtn_Click(object sender, RoutedEventArgs e) | Scenario1_GetLamp | [inline, private]
LogStatusAsync(string message, NotifyType type) | Scenario1_GetLamp | [inline, private]
LogStatusToOutputBoxAsync(string message) | Scenario1_GetLamp | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_GetLamp | [inline, protected]
rootPage | Scenario1_GetLamp | [private]
Scenario1_GetLamp() | Scenario1_GetLamp | [inline]
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Tasks/Helpers.h Source File

  • Geolocation
  • cppwinrt
  • Tasks

Helpers.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002 namespace winrt::BackgroundTask
00003 {
00004     hstring FormatDateTime(Windows::Foundation::DateTime value, hstring const& format);
00005     hstring to_brief_hstring(double value);
00006     Windows::Data::Json::JsonArray LoadSavedJson(hstring const& key);
00007     void DisplayToast(hstring const& message);
00008 }
00009
00010 namespace winrt
00011 {
00012     hstring to_hstring(Windows::Devices::Geolocation::VisitStateChange value);
00013 }
Generated on Fri Nov 15 2024 22:18:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaEditing/cpp/Scenario2_AppendClips.xaml.cpp Source File

  • MediaEditing
  • cpp

Scenario2_AppendClips.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_AppendClips.xaml.h"
00014
00015 using namespace SDKTemplate;
00016 using namespace concurrency;
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Primitives;
00023 using namespace Windows::UI::Xaml::Data;
00024 using namespace Windows::UI::Xaml::Input;
00025 using namespace Windows::UI::Xaml::Media;
00026 using namespace Windows::UI::Xaml::Navigation;
00027 using namespace Windows::Media::Core;
00028 using namespace Windows::Media::Editing;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::Pickers;
00031 using namespace Windows::Storage::Streams;
00032
00033 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00034
00035 Scenario2_AppendClips::Scenario2_AppendClips() : rootPage(MainPage::Current)
00036 {
00037     InitializeComponent();
00038 }
00039
00040 void Scenario2_AppendClips::OnNavigatedFrom(NavigationEventArgs^ e)
00041 {
00042     mediaElement->Source = nullptr;
00043     mediaStreamSource = nullptr;
00044 }
00045
00046 void Scenario2_AppendClips::ChooseFirstVideo_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00047 {
00048     // Get first file
00049     auto picker = ref new FileOpenPicker();
00050     picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00051     picker->FileTypeFilter->Append(".mp4");
00052
00053     create_task(picker->PickSingleFileAsync()).then([this](StorageFile^ videoFile)
00054     {
00055         if (videoFile == nullptr)
00056         {
00057             rootPage->NotifyUser("File picking cancelled", NotifyType::ErrorMessage);
00058             return;
00059         }
00060
00061         this->firstVideoFile = videoFile;
00062         create_task(this->firstVideoFile->OpenReadAsync()).then([this](IRandomAccessStreamWithContentType^ videoSource)
00063         {
00064             mediaElement->SetSource(videoSource, this->firstVideoFile->ContentType);
00065             chooseSecondFile->IsEnabled = true;
00066         });
00067     });
00068 }
00069
00070 void Scenario2_AppendClips::ChooseSecondVideo_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00071 {
00072     // Get second file
00073     auto picker = ref new FileOpenPicker();
00074     picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00075     picker->FileTypeFilter->Append(".mp4");
00076
00077     create_task(picker->PickSingleFileAsync()).then([this](StorageFile^ videoFile)
00078     {
00079         if (videoFile == nullptr)
00080         {
00081             rootPage->NotifyUser("File picking cancelled", NotifyType::ErrorMessage);
00082             return;
00083         }
00084
00085         this->secondVideoFile = videoFile;
00086         create_task(this->secondVideoFile->OpenReadAsync()).then([this](IRandomAccessStreamWithContentType^ videoSource)
00087         {
00088             mediaElement->SetSource(videoSource, this->secondVideoFile->ContentType);
00089             appendFiles->IsEnabled = true;
00090         });
00091     });
00092 }
00093
00094 void Scenario2_AppendClips::AppendVideos_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00095 {
00096     // Combine two video files together into one
00097     create_task(MediaClip::CreateFromFileAsync(firstVideoFile)).then([this](MediaClip^ firstClip)
00098     {
00099         create_task(MediaClip::CreateFromFileAsync(secondVideoFile)).then([this, firstClip](MediaClip^ secondClip)
00100         {
00101             composition = ref new MediaComposition();
00102             composition->Clips->Append(firstClip);
00103             composition->Clips->Append(secondClip);
00104
00105             // Render to MediaElement
00106             mediaStreamSource = composition->GeneratePreviewMediaStreamSource((int)mediaElement->ActualWidth, (int)mediaElement->ActualHeight);
00107             mediaElement->SetMediaStreamSource(mediaStreamSource);
00108             rootPage->NotifyUser("Clips appended", NotifyType::StatusMessage);
00109         });
00110     });
00111 }
Generated on Fri Nov 15 2024 22:20:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CAsyncState Member List

This is the complete list of members for CAsyncState, including all inherited members.
CAsyncState(Platform::Array< int, 1 >^data, UINT32 size) | CAsyncState | [inline]
m_Data | CAsyncState |
m_Size | CAsyncState |
~CAsyncState() | CAsyncState | [inline, private, virtual]
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothRfcommChat/cs/Tasks/Properties/AssemblyInfo.cs Source File

  • BluetoothRfcommChat
  • cs
  • Tasks
  • Properties

AssemblyInfo.cs

Go to the documentation of this file.
00001 ﻿using System.Reflection;
00002 using System.Runtime.CompilerServices;
00003 using System.Runtime.InteropServices;
00004
00005 // General Information about an assembly is controlled through the following
00006 // set of attributes. Change these attribute values to modify the information
00007 // associated with an assembly.
00008 [assembly: AssemblyTitle("Tasks")]
00009 [assembly: AssemblyDescription("")]
00010 [assembly: AssemblyConfiguration("")]
00011 [assembly: AssemblyCompany("")]
00012 [assembly: AssemblyProduct("Tasks")]
00013 [assembly: AssemblyCopyright("Copyright ©  2015")]
00014 [assembly: AssemblyTrademark("")]
00015 [assembly: AssemblyCulture("")]
00016
00017 // Version information for an assembly consists of the following four values:
00018 //
00019 //      Major Version
00020 //      Minor Version
00021 //      Build Number
00022 //      Revision
00023 //
00024 // You can specify all the values or you can default the Build and Revision Numbers
00025 // by using the '*' as shown below:
00026 // [assembly: AssemblyVersion("1.0.*")]
00027 [assembly: AssemblyVersion("1.0.0.0")]
00028 [assembly: AssemblyFileVersion("1.0.0.0")]
00029 [assembly: ComVisible(false)]
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5 Member List

This is the complete list of members for Scenario5, including all inherited members.
CloseListener_Click(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
CloseListenerSocket() | Scenario5 | [inline, private]
listenerSocket | Scenario5 | [private]
MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments) | Scenario5 | [inline, private]
MulticastRadioButton_Checked(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
MulticastRadioButton_Unchecked(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
NotifyUserFromAsyncThread(string strMessage, NotifyType type) | Scenario5 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario5 | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario5 | [inline, protected]
rootPage | Scenario5 | [private]
Scenario5() | Scenario5 | [inline]
SendMessage_Click(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
SetupBroadcastScenarioUI() | Scenario5 | [inline, private]
SetupMulticastScenarioUI() | Scenario5 | [inline, private]
StartListener_Click(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
Generated on Fri Nov 15 2024 22:23:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VisitBackgroundTask Member List

This is the complete list of members for VisitBackgroundTask, including all inherited members.
GenerateVisitDescription(Windows::Devices::Geolocation::Geovisit const &visit) | VisitBackgroundTask | [private]
maxEventDescriptors | VisitBackgroundTask | [private, static]
ProcessVisitReports(Windows::Devices::Geolocation::GeovisitTriggerDetails const &triggerDetails) | VisitBackgroundTask | [private]
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance const &taskInstance) | VisitBackgroundTask |
VisitBackgroundTask() | VisitBackgroundTask |
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cppwinrt/CopyFiles.cpp Source File

  • Clipboard
  • cppwinrt

CopyFiles.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "CopyFiles.h"
00014 #include "CopyFiles.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::ApplicationModel::DataTransfer;
00020 using namespace Windows::Storage;
00021 using namespace Windows::Storage::Pickers;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     CopyFiles::CopyFiles()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     fire_and_forget CopyFiles::CopyButton_Click(IInspectable const&, RoutedEventArgs const&)
00033     {
00034         auto lifetime = get_strong();
00035
00036         rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00037
00038         FileOpenPicker filePicker;
00039         filePicker.ViewMode(PickerViewMode::List);
00040         filePicker.FileTypeFilter().ReplaceAll({ L"*" });
00041
00042         auto storageItems = co_await filePicker.PickMultipleFilesAsync();
00043         if (storageItems.Size() > 0)
00044         {
00045             DataPackage dataPackage;
00046             dataPackage.SetStorageItems(storageItems.as<IVectorView<IStorageItem>>());
00047
00048             // Request a copy operation from targets that support different file operations, like File Explorer
00049             dataPackage.RequestedOperation(DataPackageOperation::Copy);
00050             if (Clipboard::SetContentWithOptions(dataPackage, nullptr))
00051             {
00052                 rootPage.NotifyUser(L"Storage Items: " + to_hstring(storageItems.Size()) + L" file(s) are copied into clipboard", NotifyType::StatusMessage);
00053             }
00054             else
00055             {
00056                 // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
00057                 rootPage.NotifyUser(L"Error copying content to clipboard.", NotifyType::ErrorMessage);
00058             }
00059         }
00060     }
00061
00062     fire_and_forget CopyFiles::PasteButton_Click(IInspectable const&, RoutedEventArgs const&)
00063     {
00064         auto lifetime = get_strong();
00065
00066         rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00067
00068         // Get data package from clipboard
00069         auto dataPackageView = Clipboard::GetContent();
00070         if (dataPackageView.Contains(StandardDataFormats::StorageItems()))
00071         {
00072             IVectorView<IStorageItem> storageItems = nullptr;
00073             try
00074             {
00075                 storageItems = co_await dataPackageView.GetStorageItemsAsync();
00076             }
00077             catch (hresult_error const& ex)
00078             {
00079                 rootPage.NotifyUser(L"Error retrieving file(s) from Clipboard: " + ex.message(), NotifyType::ErrorMessage);
00080             }
00081
00082             if (storageItems)
00083             {
00084                 std::wostringstream output;
00085                 output << L"Pasting following " << storageItems.Size() <<
00086                     L" file(s) to the folder " <<
00087                     std::wstring_view(ApplicationData::Current().LocalFolder().Path()) << std::endl;
00088                 output << L"Requested Operation: ";
00089                 auto operation = dataPackageView.RequestedOperation();
00090                 switch (operation)
00091                 {
00092                 case DataPackageOperation::Copy:
00093                     output << L"Copy";
00094                     break;
00095                 case DataPackageOperation::Link:
00096                     output << L"Link";
00097                     break;
00098                 case DataPackageOperation::Move:
00099                     output << L"Move";
00100                     break;
00101                 case DataPackageOperation::None:
00102                     output << L"None";
00103                     break;
00104                 default:
00105                     output << L"Unknown";
00106                     break;
00107                 }
00108                 output << std::endl;
00109                 OutputText().Text(output.str());
00110
00111                 // Iterate through each item in the collection
00112                 for (auto&& storageItem : storageItems)
00113                 {
00114                     auto file = storageItem.try_as<StorageFile>();
00115                     if (file)
00116                     {
00117                         // Copy the file
00118                         auto newFile = co_await file.CopyAsync(ApplicationData::Current().LocalFolder(), file.Name(), NameCollisionOption::ReplaceExisting);
00119                         if (newFile)
00120                         {
00121                             output << std::wstring_view(file.Name()) << std::endl;
00122                         }
00123                     }
00124                     else
00125                     {
00126                         auto folder = storageItem.try_as<StorageFolder>();
00127                         if (folder)
00128                         {
00129                             // Skipping folders for brevity sake
00130                             output << std::wstring_view(folder.Path()) << L" is a folder, skipping" << std::endl;
00131                         }
00132                     }
00133                     ;
00134                     OutputText().Text(output.str());
00135                 }
00136             }
00137         }
00138         else
00139         {
00140             OutputText().Text(L"StorageItems format is not available in clipboard");
00141         }
00142     }
00143 }
00144
Generated on Fri Nov 15 2024 22:18:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Common/PrintWstringToDebugConsole.h Source File

  • HolographicVoiceInput
  • cpp
  • Common

PrintWstringToDebugConsole.h

Go to the documentation of this file.
00001 #pragma once
00002 //*********************************************************
00003 //
00004 // Copyright (c) Microsoft. All rights reserved.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012
00013 namespace HolographicVoiceInput {
00014
00015     static void PrintWstringToDebugConsole(std::wstring message)
00016     {
00017         OutputDebugString(message.c_str());
00018     }
00019 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/LiveTiles/BasicState/BackgroundColor/InheritFromPrimary/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • LiveTiles
  • BasicState
  • BackgroundColor
  • InheritFromPrimary

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.StartScreen;
00003 using Windows.UI.Xaml;
00004 using Windows.UI.Xaml.Controls;
00005
00006 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00007
00008 namespace Notifications.ScenarioPages.LiveTiles.BasicState.BackgroundColor.InheritFromPrimary
00009 {
00010     /// <summary>
00011     /// An empty page that can be used on its own or navigated to within a Frame.
00012     /// </summary>
00013     public sealed partial class ScenarioElement : UserControl
00014     {
00015         public ScenarioElement()
00016         {
00017             this.InitializeComponent();
00018         }
00019
00020         private string _tileId;
00021
00022         private async void ButtonPinSecondaryTile_Click(object sender, RoutedEventArgs e)
00023         {
00024             base.IsEnabled = false;
00025
00026             _tileId = DateTime.Now.Ticks.ToString();
00027
00028             SecondaryTile tile = new SecondaryTile(_tileId, "Inherit Primary Color", "args", new Uri("ms-appx:///Assets/DefaultSecondaryTileAssests/Medium.png"), TileSize.Default);
00029             tile.VisualElements.Square71x71Logo = new Uri("ms-appx:///Assets/DefaultSecondaryTileAssests/Small.png");
00030             tile.VisualElements.Wide310x150Logo = new Uri("ms-appx:///Assets/DefaultSecondaryTileAssests/Wide.png");
00031             tile.VisualElements.Square310x310Logo = new Uri("ms-appx:///Assets/DefaultSecondaryTileAssests/Large.png");
00032             tile.VisualElements.ShowNameOnSquare150x150Logo = true;
00033             tile.VisualElements.ShowNameOnSquare310x310Logo = true;
00034             tile.VisualElements.ShowNameOnWide310x150Logo = true;
00035             await tile.RequestCreateAsync();
00036
00037             base.IsEnabled = true;
00038         }
00039     }
00040 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FilmicEffect Member List

This is the complete list of members for FilmicEffect, including all inherited members.
Clamp(float v, float low, float high) | FilmicEffect | [inline, private, static]
CreateFilmicImpl(_Outptr_ IUnknown **ppEffectImpl) | FilmicEffect | [static]
dpi | FilmicEffect |
FilmicEffect() | FilmicEffect | [private]
IFACEMETHODIMP_(UINT32) GetInputCount() const | FilmicEffect |
IFACEMETHODIMP_(ULONG) AddRef() | FilmicEffect |
IFACEMETHODIMP_(ULONG) Release() | FilmicEffect |
Initialize(_In_ ID2D1EffectContext *pContextInternal, _In_ ID2D1TransformGraph *pTransformGraph) | FilmicEffect |
m_constants | FilmicEffect | [private]
m_dpi | FilmicEffect | [private]
m_drawInfo | FilmicEffect | [private]
m_effectContext | FilmicEffect | [private]
m_inputRect | FilmicEffect | [private]
m_refCount | FilmicEffect | [private]
MapInputRectsToOutputRect(_In_reads_(inputRectCount) CONST D2D1_RECT_L *pInputRects, _In_reads_(inputRectCount) CONST D2D1_RECT_L *pInputOpaqueSubRects, UINT32 inputRectCount, _Out_ D2D1_RECT_L *pOutputRect, _Out_ D2D1_RECT_L *pOutputOpaqueSubRect) | FilmicEffect |
MapInvalidRect(UINT32 inputIndex, D2D1_RECT_L invalidInputRect, _Out_ D2D1_RECT_L *pInvalidOutputRect) const | FilmicEffect |
MapOutputRectToInputRects(_In_ const D2D1_RECT_L *pOutputRect, _Out_writes_(inputRectCount) D2D1_RECT_L *pInputRects, UINT32 inputRectCount) const | FilmicEffect |
PrepareForRender(D2D1_CHANGE_TYPE changeType) | FilmicEffect |
QueryInterface(_In_ REFIID riid, _Outptr_ void **ppOutput) | FilmicEffect |
Register(_In_ ID2D1Factory1 *pFactory) | FilmicEffect | [static]
Round(float v) | FilmicEffect | [inline, private, static]
SafeAdd(long base, long valueToAdd) | FilmicEffect | [inline, private, static]
SetDrawInfo(_In_ ID2D1DrawInfo *pRenderInfo) | FilmicEffect |
SetGraph(_In_ ID2D1TransformGraph *pGraph) | FilmicEffect |
UpdateConstants() | FilmicEffect | [private]
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario2WinRTComponent/OnboardingLegacySignals.cpp Source File

  • AllJoyn
  • Common
  • Scenario2WinRTComponent

OnboardingLegacySignals.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #include "pch.h"
00022
00023 using namespace Microsoft::WRL;
00024 using namespace Platform;
00025 using namespace Windows::Devices::AllJoyn;
00026 using namespace Windows::Foundation;
00027 using namespace org::alljoyn::Onboarding;
00028
00029 void OnboardingLegacySignals::Initialize(_In_ alljoyn_busobject busObject, _In_ alljoyn_sessionid sessionId)
00030 {
00031     m_busObject = busObject;
00032     m_sessionId = sessionId;
00033
00034     auto interfaceDefinition = alljoyn_busattachment_getinterface(alljoyn_busobject_getbusattachment(busObject), "org.alljoyn.Onboarding");
00035     alljoyn_interfacedescription_getmember(interfaceDefinition, "ConnectionResult", &m_memberConnectionResult);
00036 }
00037
00038 void OnboardingLegacySignals::ConnectionResult(_In_ Onboarding^ interfaceMemberArg)
00039 {
00040     if (nullptr == m_busObject)
00041     {
00042         return;
00043     }
00044
00045     size_t argCount = 1;
00046     alljoyn_msgarg arguments = alljoyn_msgarg_array_create(argCount);
00047     (void)TypeConversionHelpers::SetAllJoynMessageArg(alljoyn_msgarg_array_element(arguments, 0), "(ns)", interfaceMemberArg);
00048
00049     alljoyn_busobject_signal(
00050         m_busObject,
00051         NULL,  // Generated code only supports broadcast signals.
00052         m_sessionId,
00053         m_memberConnectionResult,
00054         arguments,
00055         argCount,
00056         0, // A signal with a TTL of 0 will be sent to every member of the session, regardless of how long it takes to deliver the message
00057         ALLJOYN_MESSAGE_FLAG_GLOBAL_BROADCAST, // Broadcast to everyone in the session.
00058         NULL); // The generated code does not need the generated signal message
00059
00060     alljoyn_msgarg_destroy(arguments);
00061 }
00062
00063 void OnboardingLegacySignals::CallConnectionResultReceived(_In_ OnboardingLegacySignals^ sender, _In_ OnboardingConnectionResultReceivedEventArgs^ args)
00064 {
00065     ConnectionResultReceived(sender, args);
00066 }
00067
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Inclinometer/cpp/CalibrationBar.xaml.cpp Source File

  • Inclinometer
  • cpp

CalibrationBar.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // CalibrationBar.xaml.cpp
00014 // Implementation of the CalibrationBar class
00015 //
00016
00017 #include "pch.h"
00018 #include "CalibrationBar.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Media::Imaging;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::Devices::Sensors;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::UI::Core;
00029 using namespace Platform;
00030
00031 static const double LAYOUT_WIDTH_768 = 768.0;
00032
00033 CalibrationBar::CalibrationBar() : _barDismissed(false)
00034 {
00035     InitializeComponent();
00036
00037     _lastCalibrationTime.QuadPart = 0;
00038
00039     TimeSpan span;
00040     span.Duration = CALIBRATION_POPUP_AUTO_DISMISS_TIME_TICKS;
00041     _calibrationTimer = ref new DispatcherTimer();
00042     _calibrationTimer->Tick += ref new Windows::Foundation::EventHandler<Object^>(this, &CalibrationBar::OnAutoDismissTimerExpired);
00043     _calibrationTimer->Interval = span;
00044 }
00045
00046 /// <summary>
00047 /// Called when the application would like to show the calibration bar to the user
00048 /// to improve sensor accuracy.
00049 /// </summary>
00050 /// <param name="accuracy">Current accuracy of the sensor.</param>
00051 void CalibrationBar::RequestCalibration(MagnetometerAccuracy accuracy)
00052 {
00053     // Only show the calibration bar if it is hidden and sufficient
00054     // time has passed since it was last hidden.
00055     if (!CalibrationPopup->IsOpen && CanShowCalibrationBar(accuracy))
00056     {
00057         InvalidateLayout();
00058         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &CalibrationBar::OnWindowSizeChanged);
00059         HideGuidance(); // Calibration image hidden by default
00060         CalibrationPopup->IsOpen = true;
00061         _calibrationTimer->Start();
00062     }
00063 }
00064
00065 /// <summary>
00066 /// Called when sensor accuracy is sufficient and the application would like to
00067 /// hide the calibration bar.
00068 /// </summary>
00069 void CalibrationBar::Hide()
00070 {
00071     if (CalibrationPopup->IsOpen)
00072     {
00073         // Hide the calibration bar and save the current time.
00074         FILETIME filetime;
00075         GetSystemTimeAsFileTime(&filetime);
00076         _lastCalibrationTime.HighPart = filetime.dwHighDateTime;
00077         _lastCalibrationTime.LowPart = filetime.dwLowDateTime;
00078         HideGuidance();
00079         CalibrationPopup->IsOpen = false;
00080         Window::Current->SizeChanged -= _windowSizeEventToken;
00081         _calibrationTimer->Stop();
00082     }
00083 }
00084
00085 /// <summary>
00086 /// Invoked when the window size is updated.
00087 /// </summary>
00088 /// <param name="sender">Instance that triggered the event.</param>
00089 /// <param name="e">Event data describing the conditions that led to the event.</param>
00090 void CalibrationBar::OnWindowSizeChanged(Object^ sender, WindowSizeChangedEventArgs^ e)
00091 {
00092     InvalidateLayout();
00093 }
00094
00095 /// <summary>
00096 /// Updates the calibration bar layout based on the current window width.
00097 /// </summary>
00098 void CalibrationBar::InvalidateLayout()
00099 {
00100     CalibrationGrid->Width = Window::Current->Bounds.Width;
00101
00102     if (CalibrationGrid->Width < LAYOUT_WIDTH_768)
00103     {
00104         Grid::SetRow(DismissPopup, 1);
00105         Grid::SetColumn(DismissPopup, 1);
00106
00107         CalibrationGridTop->Margin = Thickness(0, 24, 20, 15);
00108         DismissPopup->Margin = Thickness(66, 15, 0, 0);
00109     }
00110     else
00111     {
00112         Grid::SetRow(DismissPopup, 0);
00113         Grid::SetColumn(DismissPopup, 2);
00114
00115         CalibrationGridTop->Margin = Thickness(0, 19, 66, 19);
00116         DismissPopup->Margin = Thickness(66, 0, 0, 0);
00117     }
00118 }
00119
00120 /// <summary>
00121 /// Called to determine if sufficient time has passed since the calibration bar
00122 /// was hidden to show the calibration bar again. This suppression time is
00123 /// dependent on the current sensor accuracy.
00124 /// </summary>
00125 /// <param name="accuracy">Current accuracy of the sensor.</param>
00126 bool CalibrationBar::CanShowCalibrationBar(MagnetometerAccuracy accuracy)
00127 {
00128     bool showBar = false;
00129     if (!_barDismissed)
00130     {
00131         FILETIME filetime;
00132         ULARGE_INTEGER now;
00133         GetSystemTimeAsFileTime(&filetime);
00134         now.HighPart = filetime.dwHighDateTime;
00135         now.LowPart = filetime.dwLowDateTime;
00136
00137         if ((accuracy == MagnetometerAccuracy::Approximate) &&
00138             (_lastCalibrationTime.QuadPart + SUPPRESS_DURATION_APPROXIMATE_TICKS <= now.QuadPart))
00139         {
00140             showBar = true;
00141         }
00142         else if ((accuracy == MagnetometerAccuracy::Unreliable) &&
00143             (_lastCalibrationTime.QuadPart + SUPPRESS_DURATION_UNRELIABLE_TICKS <= now.QuadPart))
00144         {
00145             showBar = true;
00146         }
00147     }
00148     return showBar;
00149 }
00150
00151 /// <summary>
00152 /// This is the click handler for the show guidance button.
00153 /// </summary>
00154 /// <param name="sender"></param>
00155 /// <param name="e"></param>
00156 void CalibrationBar::ShowGuidanceButton_Click(Object^ sender, RoutedEventArgs^ e)
00157 {
00158     if (Guidance->Visibility == Windows::UI::Xaml::Visibility::Collapsed)
00159     {
00160         ShowGuidance();
00161     }
00162 }
00163
00164 /// <summary>
00165 /// This is the click handler for the hide guidance button.
00166 /// </summary>
00167 /// <param name="sender"></param>
00168 /// <param name="e"></param>
00169 void CalibrationBar::HideGuidanceButton_Click(Object^ sender, RoutedEventArgs^ e)
00170 {
00171     if (Guidance->Visibility == Windows::UI::Xaml::Visibility::Visible)
00172     {
00173         HideGuidance();
00174     }
00175 }
00176
00177 /// <summary>
00178 /// This is the click handler for the dismiss popup button. It hides the
00179 /// calibration bar and prevents it from being shown again for the lifetime
00180 /// of the app.
00181 /// </summary>
00182 /// <param name="sender"></param>
00183 /// <param name="e"></param>
00184 void CalibrationBar::DismissPopup_Click(Object^ sender, RoutedEventArgs^ e)
00185 {
00186     // Don't show the calibration bar again.
00187     _barDismissed = true;
00188     Hide();
00189 }
00190
00191 /// <summary>
00192 /// Expands the calibration bar to show the calibration image to the user.
00193 /// </summary>
00194 /// <param name="sender"></param>
00195 /// <param name="e"></param>
00196 void CalibrationBar::ShowGuidance()
00197 {
00198     ShowGuidanceButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00199     HideGuidanceButton->Visibility = Windows::UI::Xaml::Visibility::Visible;
00200     Guidance->Visibility = Windows::UI::Xaml::Visibility::Visible;
00201 }
00202
00203 /// <summary>
00204 /// Collapses the calibration bar to hide the calibration image from the user.
00205 /// </summary>
00206 /// <param name="sender"></param>
00207 /// <param name="e"></param>
00208 void CalibrationBar::HideGuidance()
00209 {
00210     HideGuidanceButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00211     ShowGuidanceButton->Visibility = Windows::UI::Xaml::Visibility::Visible;
00212     Guidance->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00213 }
00214
00215 /// <summary>
00216 /// This is the handler for the auto dismiss timer. After the calibraiton bar
00217 /// has been shown for the maximum time, it is automatically hidden.
00218 /// </summary>
00219 /// <param name="sender"></param>
00220 /// <param name="e"></param>
00221 void CalibrationBar::OnAutoDismissTimerExpired(Object^ sender, Object^ e)
00222 {
00223     Hide();
00224 }
Generated on Fri Nov 15 2024 22:18:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/MainPage.xaml.cs Source File

  • Notifications
  • cs
  • Notifications

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿using Notifications.Helpers;
00002 using Notifications.Model;
00003 using System;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006 using Windows.UI.Xaml.Navigation;
00007
00008 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00009
00010 namespace Notifications
00011 {
00012     /// <summary>
00013     /// An empty page that can be used on its own or navigated to within a Frame.
00014     /// </summary>
00015     public sealed partial class MainPage : BackButtonPage
00016     {
00017         public MainPage()
00018         {
00019             this.InitializeComponent();
00020         }
00021
00022         protected override void OnNavigatedTo(NavigationEventArgs e)
00023         {
00024             if (e.Parameter is ScenarioGroup)
00025             {
00026                 ScenarioGroup = e.Parameter as ScenarioGroup;
00027
00028                 if (!base.Frame.CanGoBack && ScenarioGroup != Scenarios.MainGroup)
00029                     base.Frame.BackStack.Add(new PageStackEntry(typeof(MainPage), Scenarios.MainGroup.FindParent(ScenarioGroup), null));
00030             }
00031
00032             else
00033             {
00034                 ScenarioGroup = Scenarios.MainGroup;
00035                 base.Frame.BackStack.Clear(); //can't go back any further (in case they restored from tombstoning, we don't restore navigation history, so we start fresh)
00036             }
00037
00038             base.OnNavigatedTo(e);
00039         }
00040
00041         public static readonly DependencyProperty ScenarioGroupProperty = DependencyProperty.Register("ScenarioGroup", typeof(ScenarioGroup), typeof(MainPage), new PropertyMetadata(null));
00042
00043         public ScenarioGroup ScenarioGroup
00044         {
00045             get { return GetValue(ScenarioGroupProperty) as ScenarioGroup; }
00046             set { SetValue(ScenarioGroupProperty, value); }
00047         }
00048
00049         private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
00050         {
00051             ListView lv = sender as ListView;
00052
00053             // Get the selected scenario, if something's selected
00054             IScenario scenario = lv.SelectedItem as IScenario;
00055             if (scenario == null)
00056                 return;
00057
00058             // Unselect the item so it can be clicked again
00059             lv.SelectedItem = null;
00060
00061             OpenScenario(scenario);
00062         }
00063
00064         private void OpenScenario(IScenario scenario)
00065         {
00066             if (scenario == null)
00067                 return;
00068
00069             // If it's a scenario group, open that group
00070             if (scenario is ScenarioGroup)
00071                 base.Frame.Navigate(typeof(MainPage), scenario);
00072
00073             // Otherwise if it's a atomic scenario, open the page for that
00074             else if (scenario is Scenario)
00075                 base.Frame.Navigate(typeof(ScenarioPage), scenario);
00076
00077             else
00078                 throw new NotImplementedException("Unknown type of scenario");
00079         }
00080
00081         private async void Footer_Click(object sender, RoutedEventArgs e)
00082         {
00083             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00084         }
00085     }
00086 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AudioCategory/cs/AudioCategory/Scenario4.xaml.cs Source File

  • AudioCategory
  • cs
  • AudioCategory

Scenario4.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016 using Windows.UI.Xaml.Media;
00017
00018 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00019
00020 namespace PlaybackManager
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class Scenario4 : Page
00026     {
00027         public Scenario4()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         private void Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00033         {
00034             Playback.SetAudioCategory(AudioCategory.Speech);
00035             Playback.SelectFile();
00036         }
00037     }
00038 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Utils Member List

This is the complete list of members for Utils, including all inherited members.
CanSendMessage(hstring const &message, Windows::Foundation::IInspectable const &connectedDevice) | Utils | [inline, static]
IsNonEmptyString(hstring const &value) | Utils | [inline, static]
IsNonNull(Windows::Foundation::IInspectable const &value) | Utils | [inline, static]
Utils() | Utils |
Generated on Fri Nov 15 2024 22:24:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ColorToStringConverter Member List

This is the complete list of members for ColorToStringConverter, including all inherited members.
colorNames | ColorToStringConverter | [private, static]
colorValues | ColorToStringConverter | [private, static]
Convert(object value, Type targetType, object parameter, string language) | ColorToStringConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | ColorToStringConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ColorToStringConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ColorToStringConverter | [inline]
Generated on Fri Nov 15 2024 22:24:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ToastNotificationQuickReplyTask Member List

This is the complete list of members for ToastNotificationQuickReplyTask, including all inherited members.
Run(IBackgroundTaskInstance taskInstance) ToastNotificationQuickReplyTask [inline]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/ToastNotificationManagerHistory/Remove/ByTag/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • ToastNotificationManagerHistory
  • Remove
  • ByTag

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using BackgroundTasks.Helpers;
00002 using Windows.UI.Notifications;
00003 using Windows.UI.Xaml;
00004 using Windows.UI.Xaml.Controls;
00005
00006 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00007
00008 namespace Notifications.ScenarioPages.Toasts.ToastNotificationManagerHistory.Remove.ByTag
00009 {
00010     /// <summary>
00011     /// An empty page that can be used on its own or navigated to within a Frame.
00012     /// </summary>
00013     public sealed partial class ScenarioElement : UserControl
00014     {
00015         public ScenarioElement()
00016         {
00017             this.InitializeComponent();
00018         }
00019
00020         private void UserControl_Loaded(object sender, RoutedEventArgs e)
00021         {
00022             Initialize();
00023         }
00024
00025         private void Initialize()
00026         {
00027             // Clear all existing notifications
00028             ToastNotificationManager.History.Clear();
00029
00030             // Pop the toasts
00031             ToastHelper.PopToast("Toast 1", "This is the first toast", "toast1", null);
00032             ToastHelper.PopToast("Toast 2 - TO BE REMOVED", "This is the second toast, should be removed when you click the button", "toast2", null);
00033             ToastHelper.PopToast("Toast 3", "This is the third toast", "toast3", null);
00034         }
00035
00036         private void ButtonRemoveToast2_Click(object sender, RoutedEventArgs e)
00037         {
00038             ToastNotificationManager.History.Remove("toast2");
00039         }
00040     }
00041 }
Generated on Fri Nov 15 2024 22:20:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1 Member List

This is the complete list of members for Scenario1, including all inherited members.
loadButton_Click(object sender, RoutedEventArgs e) | Scenario1 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1 | [inline, protected]
rootPage | Scenario1 | [private]
Scenario1() | Scenario1 | [inline]
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/pch.h Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <wrl.h>
00015 #include <wrl/client.h>
00016 #include <memory>
00017 #include <agile.h>
00018 #include <concrt.h>
00019
00020 #include <d3d11_3.h>
00021 #include <d2d1_3.h>
00022 #include <d2d1effects_2.h>
00023 #include <dwrite_3.h>
00024 #include <wincodec.h>
00025 #include <DirectXMath.h>
00026
00027 #include <d2d1effectauthor_1.h>
00028 #include <d2d1effecthelpers.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FolderEnumeration/cs/SampleConfiguration.cs Source File

  • FolderEnumeration
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Folder enumeration C# sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title = "Enumerate files and folders in the Pictures library",        ClassType = typeof(Scenario1) },
00025             new Scenario() { Title = "Enumerate files in the Pictures library, by groups",         ClassType = typeof(Scenario2) },
00026             new Scenario() { Title = "Enumerate files in the Pictures library with prefetch APIs", ClassType = typeof(Scenario3) },
00027             new Scenario() { Title = "Enumerate files in a folder and display availability",       ClassType = typeof(Scenario4) },
00028         };
00029     }
00030
00031     public class Scenario
00032     {
00033         public string Title { get; set; }
00034         public Type ClassType { get; set; }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Scenario1_DevicePicker.cpp Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

Scenario1_DevicePicker.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_DevicePicker.h"
00014 #include "SampleConfiguration.h"
00015 #include "DeviceHelpers.h"
00016 #include "Scenario1_DevicePicker.g.cpp"
00017
00018 using namespace winrt;
00019 using namespace winrt::Windows::Devices::Enumeration;
00020 using namespace winrt::Windows::Foundation;
00021 using namespace winrt::Windows::UI::Xaml;
00022 using namespace winrt::Windows::UI::Xaml::Media;
00023 using namespace winrt::Windows::UI::Xaml::Navigation;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario1_DevicePicker::Scenario1_DevicePicker()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     void Scenario1_DevicePicker::OnNavigatedTo(NavigationEventArgs const&)
00033     {
00034         resultsListView().ItemsSource(resultCollection);
00035
00036         selectorComboBox().ItemsSource(DeviceSelectorChoices::DevicePickerSelectors());
00037         selectorComboBox().SelectedIndex(0);
00038     }
00039
00040     void Scenario1_DevicePicker::OnNavigatedFrom(NavigationEventArgs const&)
00041     {
00042         devicePicker = nullptr;
00043     }
00044
00045     void Scenario1_DevicePicker::PickSingleDeviceButton_Click(IInspectable const&, RoutedEventArgs const&)
00046     {
00047         ShowDevicePicker(
00048             true // pickSingle
00049         );
00050     }
00051
00052     void Scenario1_DevicePicker::ShowDevicePickerButton_Click(IInspectable const&, RoutedEventArgs const&)
00053     {
00054         ShowDevicePicker(
00055             false // pickSingle
00056         );
00057     }
00058
00059     fire_and_forget Scenario1_DevicePicker::ShowDevicePicker(bool pickSingle)
00060     {
00061         auto lifetime = get_strong();
00062
00063         showDevicePickerButton().IsEnabled(false);
00064         resultCollection.Clear();
00065
00066         devicePicker = DevicePicker();
00067
00068         // First get the device selector chosen by the UI.
00069         IInspectable item = selectorComboBox().SelectedItem();
00070         DeviceSelectorInfo* deviceSelectorInfo = FromInspectable<DeviceSelectorInfo>(item);
00071
00072         if (deviceSelectorInfo->Selector().empty())
00073         {
00074             // If the a pre-canned device class selector was chosen, call the DeviceClass overload
00075             devicePicker.Filter().SupportedDeviceClasses().Append(deviceSelectorInfo->DeviceClassSelector());
00076         }
00077         else
00078         {
00079             // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
00080             devicePicker.Filter().SupportedDeviceSelectors().Append(deviceSelectorInfo->Selector());
00081         }
00082
00083         rootPage.NotifyUser(L"Showing Device Picker", NotifyType::StatusMessage);
00084
00085         // Calculate the position to show the picker (right below the buttons)
00086         GeneralTransform ge = pickSingleDeviceButton().TransformToVisual(nullptr);
00087         Point point = ge.TransformPoint({ 0, 0 });
00088         Rect rect{ point,
00089                         { static_cast<float>(pickSingleDeviceButton().ActualWidth()),
00090                           static_cast<float>(pickSingleDeviceButton().ActualHeight()) }
00091         };
00092
00093         if (pickSingle)
00094         {
00095             DeviceInformation di = co_await devicePicker.PickSingleDeviceAsync(rect);
00096             if (nullptr != di)
00097             {
00098                 resultCollection.Append(make<DeviceInformationDisplay>(di));
00099             }
00100             showDevicePickerButton().IsEnabled(true);
00101         }
00102         else
00103         {
00104             devicePicker.DevicePickerDismissed({ get_weak(), &Scenario1_DevicePicker::OnDevicePickerDismissed });
00105             devicePicker.DeviceSelected({ get_weak(), &Scenario1_DevicePicker::OnDeviceSelected });
00106
00107             // Show the picker
00108             devicePicker.Show(rect);
00109         }
00110     }
00111
00112     fire_and_forget Scenario1_DevicePicker::OnDevicePickerDismissed(DevicePicker const&, IInspectable const&)
00113     {
00114         auto lifetime = get_strong();
00115
00116         // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
00117         co_await resume_foreground(Dispatcher());
00118
00119         showDevicePickerButton().IsEnabled(true);
00120         rootPage.NotifyUser(L"Hiding Device Picker", NotifyType::StatusMessage);
00121     }
00122
00123     fire_and_forget Scenario1_DevicePicker::OnDeviceSelected(DevicePicker const&, DeviceSelectedEventArgs args)
00124     {
00125         auto lifetime = get_strong();
00126
00127         // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
00128         co_await resume_foreground(Dispatcher());
00129
00130         resultCollection.Clear();
00131         resultCollection.Append(make<DeviceInformationDisplay>(args.SelectedDevice()));
00132     }
00133 }
Generated on Fri Nov 15 2024 22:19:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationData/cppwinrt/Scenario4_CompositeSettings.cpp Source File

  • ApplicationData
  • cppwinrt

Scenario4_CompositeSettings.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <sstream>
00014 #include "Scenario4_CompositeSettings.h"
00015 #include "Scenario4_CompositeSettings.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Storage;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Navigation;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario4_CompositeSettings::Scenario4_CompositeSettings()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     void Scenario4_CompositeSettings::WriteCompositeSetting_Click(IInspectable const&, RoutedEventArgs const&)
00031     {
00032         // Composite settings are used to group multiple settings.
00033         // Note that Composite settings may not be nested.
00034         ApplicationDataCompositeValue composite;
00035         composite.Insert(settingName1, box_value(1)); // example value
00036         composite.Insert(settingName2, box_value(L"world")); // example value
00037
00038         localSettings.Values().Insert(settingName, composite);
00039
00040         DisplayOutput();
00041     }
00042
00043     void Scenario4_CompositeSettings::DeleteCompositeSetting_Click(IInspectable const&, RoutedEventArgs const&)
00044     {
00045         localSettings.Values().Remove(settingName);
00046
00047         DisplayOutput();
00048     }
00049
00050     void Scenario4_CompositeSettings::DisplayOutput()
00051     {
00052         auto composite = localSettings.Values().Lookup(settingName).as<ApplicationDataCompositeValue>();
00053
00054         std::wstringstream output;
00055         if (!composite)
00056         {
00057             output << L"Composite Setting: <empty>";
00058         }
00059         else
00060         {
00061             output << L"Composite setting: {" << settingName1 << L" = " << composite.Lookup(settingName1).as<int>() << L", ";
00062             output << settingName2 << L" = \"" << composite.Lookup(settingName2).as<hstring>().c_str() << "\"}";
00063         }
00064
00065         OutputTextBlock().Text(output.str());
00066     }
00067
00068     void Scenario4_CompositeSettings::OnNavigatedTo(NavigationEventArgs const&)
00069     {
00070         DisplayOutput();
00071     }
00072 }
00073
Generated on Fri Nov 15 2024 22:17:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LanguageFont/cppwinrt/Scenario1_UIFonts.cpp Source File

  • LanguageFont
  • cppwinrt

Scenario1_UIFonts.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_UIFonts.h"
00014 #include "Scenario1_UIFonts.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Globalization::Fonts;
00020 using namespace Windows::UI::Xaml;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     Scenario1_UIFonts::Scenario1_UIFonts()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     void Scenario1_UIFonts::ApplyFonts_Click(IInspectable const&, RoutedEventArgs const&)
00030     {
00031         LanguageFontGroup languageFontGroup(L"ja-JP");
00032
00033         // Change the Font value with selected font from LanguageFontGroup API
00034         ApplyLanguageFont(HeadingTextBlock(), languageFontGroup.UIHeadingFont());
00035         ApplyLanguageFont(BodyTextBlock(), languageFontGroup.UITextFont());
00036
00037     }
00038 }
Generated on Fri Nov 15 2024 22:20:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_ShowHideMethods Member List

This is the complete list of members for Scenario3_ShowHideMethods, including all inherited members.
OnFadeOutCompleted(Windows::Foundation::IInspectable const &sender, Windows::Foundation::IInspectable const &e) | Scenario3_ShowHideMethods
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario3_ShowHideMethods
Scenario3_ShowHideMethods() | Scenario3_ShowHideMethods
WordListBox_OnKeyUp(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs const &e) | Scenario3_ShowHideMethods
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MicrosoftPassport/Server/Controllers/AuthenticationController.cs Source File

  • MicrosoftPassport
  • Server
  • Controllers

AuthenticationController.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 // Please refer to the Microsoft Passport and Windows Hello
00012 // whitepaper on the Windows Dev Center for a complete
00013 // explanation of Microsoft Passport and Windows Hello
00014 // implementation:
00015 // http://go.microsoft.com/fwlink/p/?LinkId=522066
00016 //*********************************************************
00017 using MicrosoftPassport.Models;
00018 using MicrosoftPassport.Server.Data;
00019 using System;
00020 using System.Net.Http;
00021 using System.Security.Cryptography;
00022 using System.Web.Http;
00023
00024 namespace MicrosoftPassport.Server.Controllers
00025 {
00026     public class AuthenticationController : ApiController
00027     {
00028         [HttpPost]
00029         public string RequestChallenge(UserAndKeyHintMessage message)
00030         {
00031             try
00032             {
00033                 byte[] challengeBuffer = new byte[16];
00034                 // Generate Random nonce
00035                 RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
00036                 rng.GetBytes(challengeBuffer);
00037
00038                 DAL.Instance.SetActiveChallenge(message.UserId, message.PublicKeyHint, challengeBuffer);
00039                 return Convert.ToBase64String(challengeBuffer);
00040             }
00041             catch (Exception)
00042             {
00043                 return string.Empty;
00044             }
00045         }
00046
00047         [HttpPost]
00048         public bool SubmitResponse(SignatureMessage message)
00049         {
00050             bool retval = false;
00051
00052             try
00053             {
00054                 // Use the public key hint to identify which public key to use.
00055                 byte[] challenge;
00056                 byte[] publicKey = DAL.Instance.GetPublicKeyForUser(message.UserId, message.PublicKeyHint, out challenge);
00057
00058                 CngKey pubCngKey = new SubjectPublicKeyInfo(publicKey).GetPublicKey();
00059
00060                 // Validate that the original challenge was signed using the corresponding private key.
00061                 using (RSACng pubKey = new RSACng(pubCngKey))
00062                 {
00063                     byte[] signature = Convert.FromBase64String(message.Signature);
00064                     retval = pubKey.VerifyData(challenge, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
00065                 }
00066             }
00067             catch (Exception)
00068             {
00069             }
00070
00071             // Return a boolean response to the client
00072             // TODO:  What should actually be returned is an authentication token (OAuth or equivalent)
00073             // that the client uses for subsequent authentication requests
00074             return retval;
00075         }
00076
00077         [HttpPost]
00078         public bool Register(RegisterMessage message)
00079         {
00080             bool retval = false;
00081
00082             if (string.IsNullOrEmpty(message.UserId) ||
00083                 string.IsNullOrEmpty(message.PublicKey))
00084             {
00085                 return false;
00086             }
00087
00088             try
00089             {
00090                 byte[] publicKeyBuffer = Convert.FromBase64String(message.PublicKey);
00091
00092                 // Hash the public key.
00093                 SHA256 hashalg = SHA256.Create();
00094                 byte[] publicKeyHashBuffer = hashalg.ComputeHash(publicKeyBuffer);
00095
00096                 string publicKeyHash = Convert.ToBase64String(publicKeyHashBuffer);
00097
00098                 retval = DAL.Instance.RegisterUser(message.UserId, publicKeyBuffer, publicKeyHash, message.DeviceName);
00099             }
00100             catch (Exception)
00101             {
00102             }
00103             return retval;
00104         }
00105
00106         [HttpPost]
00107         public bool RemoveRegisteredKey(UserAndKeyHintMessage message)
00108         {
00109             bool retval = false;
00110             try
00111             {
00112                 retval = DAL.Instance.RemoveRegisteredKey(message.UserId, message.PublicKeyHint);
00113             }
00114             catch (Exception)
00115             {
00116             }
00117             return retval;
00118         }
00119     }
00120 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Utilities Member List

This is the complete list of members for Utilities, including all inherited members.
NotifyDeviceNotConnected() Utilities [inline, static]
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NetworkConnectivity/cs/Helpers.cs Source File

  • NetworkConnectivity
  • cs

Helpers.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using System;
00012 using System.Threading.Tasks;
00013 using Windows.Networking.Connectivity;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.Web.Http;
00016
00017 namespace SDKTemplate
00018 {
00019     internal class Helpers
00020     {
00021         public static void AppendLine(TextBlock textBlock, string message)
00022         {
00023             textBlock.Text += message + "\n\n";
00024         }
00025
00026         enum CostGuidance
00027         {
00028             Normal,
00029             OptIn,
00030             Conservative
00031         }
00032
00033         public static bool ShouldAttemptToConnectToInternet(NetworkConnectivityLevel connectivityLevel)
00034         {
00035             bool shouldConnectToInternet = false;
00036             if (connectivityLevel == NetworkConnectivityLevel.LocalAccess || connectivityLevel == NetworkConnectivityLevel.InternetAccess)
00037             {
00038                 shouldConnectToInternet = true;
00039             }
00040
00041             return shouldConnectToInternet;
00042         }
00043
00044         private static async Task<string> SendHttpGetRequestAsync()
00045         {
00046             string message;
00047             HttpClient httpClient = new HttpClient();
00048             HttpGetStringResult result = await httpClient.TryGetStringAsync(new Uri("http://www.msftconnecttest.com/connecttest.txt"));
00049             if (result.Succeeded)
00050             {
00051                 message = $"Connection to server confirmed: \"{result.Value}\"";
00052             }
00053             else if (result.ResponseMessage != null)
00054             {
00055                 message = $"Cannot connect to server: {result.ResponseMessage.StatusCode}";
00056             }
00057             else
00058             {
00059                 message = $"Cannot connect to server: {result.ExtendedError.Message}";
00060             }
00061             return message;
00062         }
00063
00064         private static CostGuidance GetNetworkCostGuidance(ConnectionCost connectionCost)
00065         {
00066             CostGuidance costGuidance = CostGuidance.Normal;
00067             if (connectionCost.Roaming || connectionCost.OverDataLimit)
00068             {
00069                 costGuidance = CostGuidance.OptIn;
00070             }
00071             else if (connectionCost.NetworkCostType == NetworkCostType.Fixed || connectionCost.NetworkCostType == NetworkCostType.Variable)
00072             {
00073                 costGuidance = CostGuidance.Conservative;
00074             }
00075             else
00076             {
00077                 costGuidance = CostGuidance.Normal;
00078             }
00079             return costGuidance;
00080         }
00081
00082         public static void EvaluateAndReportConnectionCost(ConnectionCost connectionCost, TextBlock textBlock)
00083         {
00084             CostGuidance costGuidance = GetNetworkCostGuidance(connectionCost);
00085             switch (costGuidance)
00086             {
00087                 // In opt-in scenarios, apps handle cases where the network access cost is significantly higher than the plan cost.
00088                 // For example, when a user is roaming, a mobile carrier may charge a higher rate data usage.
00089                 case CostGuidance.OptIn:
00090                     AppendLine(textBlock, "Apps should implement opt-in behavior.");
00091                     break;
00092                 // In conservative scenarios, apps implement restrictions for optimizing network usage to handle transfers over metered networks.
00093                 case CostGuidance.Conservative:
00094                     AppendLine(textBlock, "Apps should implement conservative behavior.");
00095                     break;
00096                 // In normal scenarios, apps do not implement restrictions. Apps treat the connection as unlimited in cost.
00097                 case CostGuidance.Normal:
00098                 default:
00099                     AppendLine(textBlock, "Apps should implement normal behavior.");
00100                     break;
00101             }
00102         }
00103
00104         public static async Task EvaluateCostAndConnectAsync(ConnectionCost connectionCost, bool optedInToCharges, TextBlock textBlock)
00105         {
00106             CostGuidance costGuidance = GetNetworkCostGuidance(connectionCost);
00107             switch (costGuidance)
00108             {
00109                 case CostGuidance.OptIn:
00110                     {
00111                         AppendLine(textBlock, "Connecting to the Internet may incur charges.");
00112                         if (optedInToCharges)
00113                         {
00114                             AppendLine(textBlock, "User has opted in to additional network usage charges.");
00115                             AppendLine(textBlock, await SendHttpGetRequestAsync());
00116                         }
00117                         else
00118                         {
00119                             AppendLine(textBlock, "User has opted out of additional network usage charges. Not connecting to the Internet.");
00120                         }
00121                     }
00122                     break;
00123                 case CostGuidance.Conservative:
00124                     AppendLine(textBlock, "Attempting to connect to the Internet, optimizing traffic for conservative network usage.");
00125                     AppendLine(textBlock, await SendHttpGetRequestAsync());
00126                     break;
00127                 case CostGuidance.Normal:
00128                 default:
00129                     AppendLine(textBlock, "Attempting to connect to the Internet.");
00130                     AppendLine(textBlock, await SendHttpGetRequestAsync());
00131                     break;
00132             }
00133         }
00134     }
00135 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
ButtonRemoveToast2_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
GROUP_1 | ScenarioElement | [private, static]
GROUP_2 | ScenarioElement | [private, static]
Initialize() | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
TAG_1 | ScenarioElement | [private, static]
TAG_2 | ScenarioElement | [private, static]
TAG_3 | ScenarioElement | [private, static]
UserControl_Loaded(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
Generated on Fri Nov 15 2024 22:23:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_CustomItems Member List

This is the complete list of members for Scenario3_CustomItems, including all inherited members.
AddToJumpList_Click(object sender, RoutedEventArgs e) | Scenario3_CustomItems | [inline, private]
DescriptionLocalizedResource_Click(object sender, RoutedEventArgs e) | Scenario3_CustomItems | [inline, private]
DisplayNameLocalizedResource_Click(object sender, RoutedEventArgs e) | Scenario3_CustomItems | [inline, private]
GroupNameLocalizedResource_Click(object sender, RoutedEventArgs e) | Scenario3_CustomItems | [inline, private]
Scenario3_CustomItems() | Scenario3_CustomItems | [inline]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Size Member List

This is the complete list of members for Scenario3_Size, including all inherited members.
appWindow | Scenario3_Size | [private]
appWindowFrame | Scenario3_Size | [private]
MinWindowHeight | Scenario3_Size | [private]
MinWindowWidth | Scenario3_Size | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario3_Size | [inline, protected]
Scenario3_Size() | Scenario3_Size | [inline]
ShowWindowBtn_Click(object sender, RoutedEventArgs e) | Scenario3_Size | [inline, private]
Generated on Fri Nov 15 2024 22:23:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ShapeRenderer Member List

This is the complete list of members for ShapeRenderer, including all inherited members.
_generator | ShapeRenderer | [private]
_shapeDistributionX | ShapeRenderer | [private]
_shapeDistributionY | ShapeRenderer | [private]
CreateBrush(ID2D1SolidColorBrush **brush, Microsoft::WRL::ComPtr< ID2D1DeviceContext > d2dContext) | ShapeRenderer | [private]
RefreshSize(Windows::Foundation::Size newSize) | ShapeRenderer |
Render(Shape shape, Microsoft::WRL::ComPtr< ID2D1DeviceContext > d2dContext) | ShapeRenderer |
ShapeRenderer() | ShapeRenderer |
Update(Microsoft::WRL::ComPtr< ID2D1DeviceContext > d2dContext) | ShapeRenderer |
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cs/Scenario1_DataEvents.xaml.cs Source File

  • Accelerometer
  • cs

Scenario1_DataEvents.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Devices.Sensors;
00014 using Windows.UI.Core;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario1_DataEvents : Page
00022     {
00023         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00024         // as NotifyUser()
00025         MainPage rootPage = MainPage.Current;
00026
00027         private Accelerometer _accelerometer;
00028
00029         public Scenario1_DataEvents()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             _accelerometer = Accelerometer.GetDefault(rootPage.AccelerometerReadingType);
00037             if (_accelerometer != null)
00038             {
00039                 rootPage.NotifyUser(rootPage.AccelerometerReadingType + " accelerometer ready", NotifyType.StatusMessage);
00040                 ScenarioEnableButton.IsEnabled = true;
00041             }
00042             else
00043             {
00044                 rootPage.NotifyUser(rootPage.AccelerometerReadingType + " accelerometer not found", NotifyType.ErrorMessage);
00045             }
00046         }
00047
00048         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00049         {
00050             if (ScenarioDisableButton.IsEnabled)
00051             {
00052                 ScenarioDisable();
00053             }
00054         }
00055
00056         /// <summary>
00057         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00058         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00059         /// </summary>
00060         /// <param name="sender"></param>
00061         /// <param name="e">
00062         /// Event data that can be examined for the current visibility state.
00063         /// </param>
00064         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00065         {
00066             if (ScenarioDisableButton.IsEnabled)
00067             {
00068                 if (e.Visible)
00069                 {
00070                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00071                     _accelerometer.ReadingChanged += ReadingChanged;
00072                 }
00073                 else
00074                 {
00075                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00076                     _accelerometer.ReadingChanged -= ReadingChanged;
00077                 }
00078             }
00079         }
00080
00081         /// <summary>
00082         /// This is the event handler for ReadingChanged events.
00083         /// </summary>
00084         /// <param name="sender"></param>
00085         /// <param name="e"></param>
00086         async private void ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e)
00087         {
00088             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00089             {
00090                 MainPage.SetReadingText(ScenarioOutput, e.Reading);
00091             });
00092         }
00093
00094         /// <summary>
00095         /// This is the click handler for the 'Enable' button.
00096         /// </summary>
00097         private void ScenarioEnable()
00098         {
00099             // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00100             _accelerometer.ReportInterval = Math.Max(_accelerometer.MinimumReportInterval, 16);
00101
00102             Window.Current.VisibilityChanged += VisibilityChanged;
00103             _accelerometer.ReadingChanged += ReadingChanged;
00104
00105             ScenarioEnableButton.IsEnabled = false;
00106             ScenarioDisableButton.IsEnabled = true;
00107         }
00108
00109         /// <summary>
00110         /// This is the click handler for the 'Disable' button.
00111         /// </summary>
00112         private void ScenarioDisable()
00113         {
00114             Window.Current.VisibilityChanged -= VisibilityChanged;
00115             _accelerometer.ReadingChanged -= ReadingChanged;
00116
00117             // Restore the default report interval to release resources while the sensor is not in use
00118             _accelerometer.ReportInterval = 0;
00119
00120             ScenarioEnableButton.IsEnabled = true;
00121             ScenarioDisableButton.IsEnabled = false;
00122         }
00123     }
00124 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Package/cpp/scenario2_installedlocation.xaml.cpp Source File

  • Package
  • cpp

scenario2_installedlocation.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario2.xaml.cpp
00013 // Implementation of the Scenario2 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario2_InstalledLocation.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace Platform;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::ApplicationModel;
00027
00028 Scenario2::Scenario2()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Invoked when this page is about to be displayed in a Frame.
00035 /// </summary>
00036 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037 /// property is typically used to configure the page.</param>
00038 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00039 {
00040     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00041     // as NotifyUser()
00042     rootPage = MainPage::Current;
00043 }
00044
00045 void Scenario2::GetInstalledLocation_Click(Object^ sender, RoutedEventArgs^ e)
00046 {
00047     // This will give the Installed Location.  You can use this location to access files, if you need them.
00048     Package^ package = Package::Current;
00049     Windows::Storage::StorageFolder^ installedLocation = package->InstalledLocation;
00050
00051     OutputTextBlock->Text = "Installed Location: " + installedLocation->Path;
00052 }
Generated on Fri Nov 15 2024 22:20:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PlayReady/cs/ViewModels/HardwareDRMViewModel.cs Source File

  • PlayReady
  • cs
  • ViewModels

HardwareDRMViewModel.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate.Shared;
00013 using System;
00014 using Windows.Media.Protection;
00015 using Windows.Media.Protection.PlayReady;
00016 using Windows.UI.Xaml.Controls;
00017
00018 namespace SDKTemplate.ViewModels
00019 {
00020
00021     public class HardwareDRMViewModel : ViewModelBase
00022     {
00023         private string moviePath = MainPage.SampleMovieURL;
00024         private string licenseUrl = "http://playready.directtaps.net/pr/svc/rightsmanager.asmx?PlayRight=1&SecurityLevel=2000";
00025
00026         public RelayCommand CmdUseHardware { get; private set; }
00027         public RelayCommand CmdUseSoftware { get; private set; }
00028
00029         public RelayCommand CmdPlayMovie { get; private set; }
00030         public RelayCommand CmdStopMovie { get; private set; }
00031
00032         public PlayReadyInfoViewModel PlayReadyInfo { get; private set; }
00033
00034         // flag to determine if hardware or software have been selected.
00035         // The application should try to stay with one or the other mode
00036         // and not frequently jump between the two.
00037         private bool modeSelected = false;
00038         /// <summary>
00039         /// A view model class for the IndivReactive Scenario.
00040         /// </summary>
00041         public HardwareDRMViewModel(MediaElement mediaElement)
00042         {
00043             this.ProtectionManager = PlayReadyHelpers.InitializeProtectionManager(ServiceRequested);
00044             mediaElement.ProtectionManager = this.ProtectionManager;
00045             PlayReadyInfo = new PlayReadyInfoViewModel();
00046             PlayReadyInfo.RefreshStatics();
00047
00048             mediaElement.CurrentStateChanged += (s, a) => {
00049                 ViewModelBase.Log("Media State::" + mediaElement.CurrentState);
00050             };
00051
00052             mediaElement.MediaFailed += (s, a) => {
00053                 ViewModelBase.Log("Media Failed::" + a.ErrorMessage);
00054             };
00055
00056             CmdPlayMovie    = new RelayCommand(() => { mediaElement.Source = new Uri(moviePath); SetPlaybackEnabled(true); },
00057                                                () => { return modeSelected && PlayReadyHelpers.IsIndividualized; });
00058             CmdStopMovie    = new RelayCommand(() => { mediaElement.Stop(); SetPlaybackEnabled(false); });
00059             CmdUseHardware  = new RelayCommand(() => { ConfigureHardwareDRM(mediaElement); },
00060                                                () => { return !modeSelected;  });
00061             CmdUseSoftware  = new RelayCommand(() => { ConfigureSoftwareDRM(mediaElement); },
00062                                                () => { return !modeSelected; });
00063
00064         }
00065
00066         /// <summary>
00067         /// This method will configure the properties used by Media Foundation and PlayReady
00068         /// to specify Hardware DRM. The existing ProtectionManager assigned to the MediaElement
00069         /// is altered with updated/removed properties. Lastly, proactive individualiation is called.
00070         /// </summary>
00071         private void ConfigureHardwareDRM(MediaElement mediaElement)
00072         {
00073             var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
00074             localSettings.CreateContainer("PlayReady", Windows.Storage.ApplicationDataCreateDisposition.Always);
00075             localSettings.Containers["PlayReady"].Values["SoftwareOverride"] = 0;
00076             localSettings.Containers["PlayReady"].Values["HardwareOverride"] = 1;
00077             mediaElement.ProtectionManager.Properties.Remove("Windows.Media.Protection.UseSoftwareProtectionLayer");
00078             mediaElement.ProtectionManager.Properties["Windows.Media.Protection.UseHardwareProtectionLayer"] = true;
00079             Individualize();
00080         }
00081
00082         /// <summary>
00083         /// This method will configure the properties used by Media Foundation and PlayReady
00084         /// to specify Software DRM. The existing ProtectionManager assigned to the MediaElement
00085         /// is altered with updated/removed properties. Lastly, proactive individualiation is called.
00086         /// </summary>
00087         private void ConfigureSoftwareDRM(MediaElement mediaElement)
00088         {
00089             var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
00090             localSettings.CreateContainer("PlayReady", Windows.Storage.ApplicationDataCreateDisposition.Always);
00091             localSettings.Containers["PlayReady"].Values["SoftwareOverride"] = 1;
00092             localSettings.Containers["PlayReady"].Values["HardwareOverride"] = 0;
00093             mediaElement.ProtectionManager.Properties.Remove("Windows.Media.Protection.UseHardwareProtectionLayer");
00094             mediaElement.ProtectionManager.Properties["Windows.Media.Protection.UseSoftwareProtectionLayer"] = true;
00095             Individualize();
00096         }
00097
00098         // Proactive individualization is used to configure playready to the selected
00099         // hardware/software mode
00100         void Individualize()
00101         {
00102             PlayReadyHelpers.ProactiveIndividualization(() => {
00103                 modeSelected = true;
00104                 CmdPlayMovie.RaiseCanExecuteChanged();
00105                 CmdUseHardware.RaiseCanExecuteChanged();
00106                 CmdUseSoftware.RaiseCanExecuteChanged();
00107             });
00108         }
00109
00110
00111         /// <summary>
00112         /// The ProtectionManager defers the service call to the ServiceReqested handler.
00113         /// This handler will enable the application to customize the communication (custom data, http headers, manual request)
00114         /// The ServiceCompletion instance will notify the ProtectionManager in the case of queued requests.
00115         /// </summary>
00116         MediaProtectionServiceCompletion serviceCompletionNotifier = null;
00117         void ServiceRequested(MediaProtectionManager sender, ServiceRequestedEventArgs srEvent)
00118         {
00119             serviceCompletionNotifier = srEvent.Completion;
00120             IPlayReadyServiceRequest serviceRequest = (IPlayReadyServiceRequest)srEvent.Request;
00121             ViewModelBase.Log(serviceRequest.GetType().Name);
00122             ProcessServiceRequest(serviceRequest);
00123         }
00124
00125         /// <summary>
00126         /// The helper class will determine the exact type of ServiceRequest in order to customize and send
00127         /// the service request. ServiceRequests (except for Individualization and Revocation) also support the
00128         /// GenerateManualEnablingChallenge method. This can be used to read and customize the SOAP challenge
00129         /// and manually send the challenge.
00130         /// </summary>
00131         void ProcessServiceRequest(IMediaProtectionServiceRequest serviceRequest)
00132         {
00133             //Alternatively the serviceRequest can be determined by the Guid serviceRequest.Type
00134             if (serviceRequest is PlayReadyIndividualizationServiceRequest)
00135             {
00136                 PlayReadyHelpers.ReactiveIndividualization(serviceRequest as PlayReadyIndividualizationServiceRequest, serviceCompletionNotifier, () => PlayReadyInfo.RefreshStatics());
00137                 PlayReadyInfo.RefreshStatics();
00138             }
00139             else if (serviceRequest is PlayReadyLicenseAcquisitionServiceRequest)
00140             {
00141                 var licenseRequest = serviceRequest as PlayReadyLicenseAcquisitionServiceRequest;
00142                 // The initial service request url was taken from the playready header from the dash manifest.
00143                 // This can overridden to a different license service prior to sending the request (staging, production,...).
00144                 licenseRequest.Uri = new Uri(licenseUrl);
00145
00146                 PlayReadyHelpers.ReactiveLicenseAcquisition(licenseRequest, serviceCompletionNotifier);
00147             }
00148
00149         }
00150
00151         public string MoviePath
00152         {
00153             get
00154             {
00155                 return moviePath;
00156             }
00157             set
00158             {
00159                 if (moviePath != value)
00160                 {
00161                     moviePath = value;
00162                     RaisePropertyChanged();
00163                 }
00164             }
00165         }
00166     }
00167 }
Generated on Fri Nov 15 2024 22:20:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboard/cppwinrt/SampleConfiguration.cpp Source File

  • TouchKeyboard
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation::Collections;
00019 using namespace winrt::SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"Touch Keyboard C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Display touch keyboard automatically", xaml_typename<SDKTemplate::Scenario1_Launch>() },
00029     Scenario{ L"Listen for Show/Hide events", xaml_typename<SDKTemplate::Scenario2_ShowHideEvents>() },
00030     Scenario{ L"Programmatically Show/Hide\nthe touch keyboard", xaml_typename<SDKTemplate::Scenario3_ShowHideMethods>() },
00031     Scenario{ L"Showing the Emoji keyboard", xaml_typename<SDKTemplate::Scenario4_ShowView>() },
00032 });
Generated on Fri Nov 15 2024 22:17:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OCR/cppwinrt/WordOverlay.h Source File

  • OCR
  • cppwinrt

WordOverlay.h

Go to the documentation of this file.
00001 #pragma once
00002 #include "pch.h"
00003 #include "MainPage.h"
00004 #include "WordOverlay.g.h"
00005
00006 namespace winrt::SDKTemplate::implementation
00007 {
00008     struct WordOverlay : WordOverlayT<WordOverlay>
00009     {
00010         WordOverlay(Windows::Media::Ocr::OcrWord const& ocrWord);
00011         Windows::UI::Xaml::Thickness WordPosition() { return { m_wordBoundingBox.X, m_wordBoundingBox.Y, 0, 0 };  }
00012         double WordWidth() { return m_wordBoundingBox.Width; }
00013         double WordHeight() { return m_wordBoundingBox.Height; }
00014         event_token PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler);
00015         void PropertyChanged(event_token const& token) noexcept;
00016
00017         void Transform(Windows::UI::Xaml::Media::ScaleTransform const& scale);
00018         Windows::UI::Xaml::Controls::Border CreateBorder(Windows::UI::Xaml::Style const& style, Windows::UI::Xaml::UIElement const& child = nullptr);
00019
00020     private:
00021         Windows::UI::Xaml::Data::Binding CreateBinding(hstring const& propertyName);
00022         void UpdateProps(Windows::Foundation::Rect const& wordBoundingBox);
00023         void OnPropertyChanged(hstring const& PropertyName);
00024
00025     private:
00026         Windows::Media::Ocr::OcrWord word{ nullptr };
00027         Windows::Foundation::Rect m_wordBoundingBox;
00028         event<Windows::UI::Xaml::Data::PropertyChangedEventHandler> m_propertyChanged;
00029     };
00030 }
Generated on Fri Nov 15 2024 22:20:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OnDemandHotspot/cs/BackgroundTask/Tasks.cs Source File

  • OnDemandHotspot
  • cs
  • BackgroundTask

Tasks.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.Background;
00014 using Windows.Data.Xml.Dom;
00015 using Windows.Devices.WiFi;
00016 using Windows.Foundation.Collections;
00017 using Windows.Security.Credentials;
00018 using Windows.Storage;
00019 using Windows.UI.Notifications;
00020
00021 namespace BackgroundTask
00022 {
00023     // This task is triggered when the system wants us to refresh our hotspot metadata.
00024     // This typically happens when the system is about to show a list of available Wi-Fi networks.
00025     public sealed class UpdateMetadataTask : IBackgroundTask
00026     {
00027         public void Run(IBackgroundTaskInstance taskInstance)
00028         {
00029             // A real on-demand hotspot task would contact each hotspot device to
00030             // obtain this information. This sample doesn't have a real hotspot device,
00031             // so it just repeats the information set by the UI portion of the app.
00032             IPropertySet values = ApplicationData.Current.LocalSettings.Values;
00033             if (!values.TryGetValue("hotspotGuid", out object boxedHotspotGuid))
00034             {
00035                 // Nothing configured.
00036                 return;
00037             }
00038
00039             Guid hotspotGuid = (Guid)boxedHotspotGuid;
00040             WiFiOnDemandHotspotNetwork network = WiFiOnDemandHotspotNetwork.GetOrCreateById(hotspotGuid);
00041             WiFiOnDemandHotspotNetworkProperties properties = network.GetProperties();
00042             properties.Availability = (bool)values["availability"] ? WiFiOnDemandHotspotAvailability.Available : WiFiOnDemandHotspotAvailability.Unavailable;
00043             properties.DisplayName = (string)values["displayName"];
00044             properties.CellularBars = (WiFiOnDemandHotspotCellularBars?)(int?)values["bars"];
00045             properties.RemainingBatteryPercent = (uint?)values["battery"];
00046             properties.Ssid = (string)values["ssid"];
00047             properties.Password = new PasswordCredential { Password = (string)values["password"] };
00048             network.UpdateProperties(properties);
00049         }
00050     }
00051
00052     // This task is triggered when the user selects our hotspot in the list of available Wi-Fi networks.
00053     // The task should turn on the Wi-Fi hotspot so that the system can connect to it.
00054
00055     public sealed class ConnectTask : IBackgroundTask
00056     {
00057         public void Run(IBackgroundTaskInstance taskInstance)
00058         {
00059             var triggerDetails = (WiFiOnDemandHotspotConnectTriggerDetails)taskInstance.TriggerDetails;
00060
00061             // A real on-demand hotspot task would contact the hotspot device and tell it
00062             // to start advertising the SSID.
00063             //
00064             // This sample doesn't have a real hotspot device, so it will simulate the action
00065             // by displaying a toast to instruct the user to turn on the mobile hotspot manually.
00066             //
00067             // To demonstrate how to report errors turning on the hotspot, we will report an error
00068             // if the hotspot is configured without an SSID or without a password.
00069
00070             WiFiOnDemandHotspotNetwork network = triggerDetails.RequestedNetwork;
00071
00072             // Is this the network we know how to turn on?
00073             IPropertySet values = ApplicationData.Current.LocalSettings.Values;
00074             if (!values.TryGetValue("hotspotGuid", out object boxedHotspotGuid) || (Guid)boxedHotspotGuid != network.Id)
00075             {
00076                 triggerDetails.ReportError(WiFiOnDemandHotspotConnectStatus.UnspecifiedFailure);
00077                 return;
00078             }
00079
00080             // To demonstrate how to report errors turning on the hotspot, we will report an error
00081             // if the hotspot is configured with an SSID named "error".
00082             WiFiOnDemandHotspotNetworkProperties properties = network.GetProperties();
00083             if (properties.Ssid == "error")
00084             {
00085                 // Simulate an error turning on the hotspot. You can report any error code from the
00086                 // WiFiOnDemandHotspotConnectStatus enumeration.
00087                 triggerDetails.ReportError(WiFiOnDemandHotspotConnectStatus.NetworkNotAvailable);
00088             }
00089             else
00090             {
00091                 DisplayToast(properties.Ssid);
00092                 System.Threading.Thread.Sleep(5000);
00093
00094                 WiFiOnDemandHotspotConnectionResult result = triggerDetails.Connect();
00095                 values["connectResult"] = (int)result.Status;
00096             }
00097         }
00098
00099         private void DisplayToast(string ssid)
00100         {
00101             ToastNotifier ToastNotifier = ToastNotificationManager.CreateToastNotifier();
00102
00103             // Create a two line toast and add audio reminder
00104
00105             // Here the xml that will be passed to the
00106             // ToastNotification for the toast is retrieved
00107             XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
00108
00109             string message = $"SSID: '{ssid}'. Connecting in five seconds.";
00110
00111             // Set both lines of text
00112             XmlNodeList toastNodeList = toastXml.GetElementsByTagName("text");
00113             toastNodeList.Item(0).AppendChild(toastXml.CreateTextNode("Please turn on your hotspot now!"));
00114             toastNodeList.Item(1).AppendChild(toastXml.CreateTextNode(message));
00115
00116             // now create a xml node for the audio source
00117             IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
00118             XmlElement audio = toastXml.CreateElement("audio");
00119             audio.SetAttribute("src", "ms-winsoundevent:Notification.SMS");
00120
00121             ToastNotification toast = new ToastNotification(toastXml);
00122             ToastNotifier.Show(toast);
00123         }
00124     }
00125 }
Generated on Fri Nov 15 2024 22:20:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/BackgroundTask/pch.h Source File

  • BackgroundTask
  • cpp
  • BackgroundTask

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 #include <vccorlib.h>
00014 #include <collection.h>
00015 #include <ppltasks.h>
00016
00017 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario9_Compare.xaml.cpp Source File

  • FileAccess
  • cpp

Scenario9_Compare.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario9_Compare.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Storage;
00020 using namespace Windows::Storage::Pickers;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Navigation;
00023
00024 Scenario9::Scenario9()
00025 {
00026     InitializeComponent();
00027 }
00028
00029 void Scenario9::OnNavigatedTo(NavigationEventArgs^ e)
00030 {
00031     rootPage->ValidateFile();
00032 }
00033
00034 void Scenario9::CompareFilesButton_Click(Object^ sender, RoutedEventArgs^ e)
00035 {
00036     StorageFile^ file = rootPage->SampleFile;
00037     if (file != nullptr)
00038     {
00039         // Compares a picked file with sample.dat
00040         FileOpenPicker^ picker = ref new FileOpenPicker();
00041         picker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00042         picker->FileTypeFilter->Append("*");
00043         create_task(picker->PickSingleFileAsync()).then([this, file](StorageFile^ comparand)
00044         {
00045             if (comparand != nullptr)
00046             {
00047                 try
00048                 {
00049                     if (file->IsEqual(comparand))
00050                     {
00051                         rootPage->NotifyUser("Files are equal", NotifyType::StatusMessage);
00052                     }
00053                     else
00054                     {
00055                         rootPage->NotifyUser("Files are not equal", NotifyType::StatusMessage);
00056                     }
00057                 }
00058                 catch (COMException^ ex)
00059                 {
00060                     // I/O errors are reported as exceptions.
00061                     rootPage->HandleIoException(ex, "Error determining whether two files are the same");
00062                 }
00063             }
00064             else
00065             {
00066                 rootPage->NotifyUser("Operation cancelled", NotifyType::StatusMessage);
00067             }
00068         });
00069     }
00070     else
00071     {
00072         rootPage->NotifyUserFileNotExist();
00073     }
00074 }
Generated on Fri Nov 15 2024 22:19:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cpp/Scenario3_ResetPin.xaml.cpp Source File

  • SmartCard
  • cpp

Scenario3_ResetPin.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario3_ResetPin.xaml.h"
00005 #include "ChallengeResponseAlgorithm.h"
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace concurrency;
00010 using namespace Platform;
00011 using namespace Windows::Devices::SmartCards;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::Storage::Streams;
00015 using namespace Windows::Security::Cryptography;
00016 using namespace Windows::Security::Cryptography::Core;
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Controls::Primitives;
00020 using namespace Windows::UI::Xaml::Data;
00021 using namespace Windows::UI::Xaml::Input;
00022 using namespace Windows::UI::Xaml::Media;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario3_ResetPin::Scenario3_ResetPin()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 void Scenario3_ResetPin::ResetPin_Click(Platform::Object^ sender,
00031     Windows::UI::Xaml::RoutedEventArgs^ e)
00032 {
00033     if (MainPage::Current->SmartCardReaderDeviceId == nullptr)
00034     {
00035         MainPage::Current->NotifyUser("Use Scenario One to create a TPM virtual smart card.", NotifyType::ErrorMessage);
00036         return;
00037     }
00038
00039     Button^ b = dynamic_cast<Button^>(sender);
00040     b->IsEnabled = false;
00041     MainPage::Current->NotifyUser("Resetting smart card PIN...", NotifyType::StatusMessage);
00042
00043     create_task(MainPage::Current->GetSmartCard()).then(
00044         [=](task<Windows::Devices::SmartCards::SmartCard^> getSmartCardTask)
00045     {
00046         Windows::Devices::SmartCards::SmartCard^ card = getSmartCardTask.get();
00047         return SmartCardProvisioning::FromSmartCardAsync(card);
00048     }).then(
00049         [=](task<SmartCardProvisioning^> getProvisioningTask)
00050     {
00051         SmartCardProvisioning^ provisioning = getProvisioningTask.get();
00052
00053         // When requesting a PIN reset, a SmartCardPinResetHandler must be
00054         // provided as an argument.  This handler must use the challenge
00055         // it receives and the card's admin key to calculate and set the
00056         // response.
00057         return provisioning->RequestPinResetAsync(
00058             ref new SmartCardPinResetHandler(
00059             [=](SmartCardProvisioning^ sender,
00060             SmartCardPinResetRequest^ request)
00061         {
00062             IBuffer^ response = ChallengeResponseAlgorithm::CalculateResponse(request->Challenge, MainPage::Current->AdminKey);
00063             request->SetResponse(response);
00064
00065             SmartCardPinResetDeferral^ deferral = request->GetDeferral();
00066             deferral->Complete();
00067         }));
00068     }).then(
00069         [=](task<bool> pinResetTask)
00070     {
00071         try
00072         {
00073             bool result = pinResetTask.get();
00074             if (result)
00075             {
00076                 MainPage::Current->NotifyUser("Smart card PIN reset operation completed.", NotifyType::StatusMessage);
00077             }
00078             else
00079             {
00080                 MainPage::Current->NotifyUser("Smart card PIN reset operation was canceled by the user.", NotifyType::StatusMessage);
00081             }
00082         }
00083         catch (COMException ^ex)
00084         {
00085             MainPage::Current->NotifyUser("Resetting smart card PIN failed with exception: " + ex->ToString(), NotifyType::ErrorMessage);
00086         }
00087
00088         b->IsEnabled = true;
00089     });
00090 }
Generated on Fri Nov 15 2024 22:21:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSegmentation/cppwinrt/Scenario2_GetCurrentTextSegmentFromIndex.cpp Source File

  • TextSegmentation
  • cppwinrt

Scenario2_GetCurrentTextSegmentFromIndex.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_GetCurrentTextSegmentFromIndex.h"
00014 #include "Scenario2_GetCurrentTextSegmentFromIndex.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace winrt::Windows::Foundation;
00018 using namespace winrt::Windows::UI::Xaml;
00019
00020 namespace winrt::SDKTemplate::implementation
00021 {
00022     Scenario2_GetCurrentTextSegmentFromIndex::Scenario2_GetCurrentTextSegmentFromIndex()
00023     {
00024         InitializeComponent();
00025     }
00026
00027     // This is the click handler for the 'Word Segment' button.
00028     //
00029     // When this button is activated, the Text Segmentation API will calculate
00030     // the word segment from the given input string and character index for that string,
00031     // and return the WordSegment object that contains the index within its text bounds.
00032     // Segment breaking behavior is based off of the language-tag input, which defines
00033     // which language rules to use.
00034     void Scenario2_GetCurrentTextSegmentFromIndex::WordSegmentButton_Click(IInspectable const&, RoutedEventArgs const&)
00035     {
00036         std::wostringstream result;
00037
00038         // Obtain the input string value, check for non-emptiness
00039         hstring inputStringText = inputStringBox().Text();
00040         if (inputStringText.empty())
00041         {
00042             rootPage.NotifyUser(L"Cannot compute word segments: input string is empty.", NotifyType::ErrorMessage);
00043             return;
00044         }
00045
00046         // Obtain the language tag value, check for non-emptiness
00047         // Ex. Valid Values:
00048         //     "en-US" (English (United States))
00049         //     "fr-FR" (French (France))
00050         //     "de-DE" (German (Germany))
00051         //     "ja-JP" (Japanese (Japan))
00052         //     "ar-SA" (Arabic (Saudi Arabia))
00053         //     "zh-CN" (China (PRC))
00054         hstring languageTagText = languageTagBox().Text();
00055         if (languageTagText.empty())
00056         {
00057             result << L"Language tag input is empty ... using generic-language segmentation rules.\n";
00058             languageTagText = L"und";   // This is used for non language-specific locales. 'und' is short for 'undetermined'.
00059         }
00060         else
00061         {
00062             if (!Windows::Globalization::Language::IsWellFormed(languageTagText))
00063             {
00064                 rootPage.NotifyUser(L"Language tag is not well formed: \"" + languageTagText + L"\"", NotifyType::ErrorMessage);
00065                 return;
00066             }
00067         }
00068
00069         // Obtain the input Index
00070         hstring inputIndexString = indexBox().Text();
00071         uint32_t inputIndex = static_cast<uint32_t>(_wtoi(inputIndexString.c_str()));
00072         if (errno == EINVAL)
00073         {
00074             result << L"No input index provided ... using first segment reference (index = 0) as default.\n";
00075         }
00076         else if (inputIndex > inputStringText.size())
00077         {
00078             rootPage.NotifyUser(L"Invalid index supplied ... cannot use a negative index, or an index that is out of bounds of the input string.\n\nPlease re-check the index value, and try again.",
00079                 NotifyType::ErrorMessage);
00080             return;
00081         }
00082
00083         // Notify that we are going to calculate word segment
00084         result
00085             << L"\n\nFinding the word segment for the given index ...\n"
00086             << L"Input: \"" << std::wstring_view(inputStringText) << L"\"\n"
00087             << L"Language Tag: \"" << std::wstring_view(languageTagText) << L"\"\n"
00088             << L"Index: " << inputIndex << L"\n";
00089
00090         // Construct the WordsSegmenter instance
00091         Windows::Data::Text::WordsSegmenter segmenter(languageTagText);
00092
00093         // Obtain the token segment
00094         auto tokenSegment = segmenter.GetTokenAt(inputStringText, inputIndex);
00095         result << L"\nIndexed segment: \"" << std::wstring_view(tokenSegment.Text()) << L"\"";
00096
00097         // Set results to output box
00098         rootPage.NotifyUser(result.str(), NotifyType::StatusMessage);
00099     }
00100
00101     // This is the click handler for the 'Selection Segment' button.
00102     //
00103     // When this button is activated, the Text Segmentation API will calculate
00104     // the selection segment from the given input string and character index for that string,
00105     // and return the SelectableWordSegment object that contains the index within its text bounds.
00106     // Segment breaking behavior is based off of the language-tag input, which defines
00107     // which language rules to use.
00108     //
00109     // Selection segments differ from word segments in that they describe the bounds
00110     // between active-selection snapping behavior.
00111     void Scenario2_GetCurrentTextSegmentFromIndex::SelectionSegmentButton_Click(IInspectable const&, RoutedEventArgs const&)
00112     {
00113         std::wostringstream result;
00114
00115         // Obtain the input string value, check for non-emptiness
00116         hstring inputStringText = inputStringBox().Text();
00117         if (inputStringText.empty())
00118         {
00119             rootPage.NotifyUser(L"Cannot compute word segments: input string is empty.", NotifyType::ErrorMessage);
00120             return;
00121         }
00122
00123         // Obtain the language tag value, check for non-emptiness
00124         // Ex. Valid Values:
00125         //     "en-US" (English (United States))
00126         //     "fr-FR" (French (France))
00127         //     "de-DE" (German (Germany))
00128         //     "ja-JP" (Japanese (Japan))
00129         //     "ar-SA" (Arabic (Saudi Arabia))
00130         //     "zh-CN" (China (PRC))
00131         hstring languageTagText = languageTagBox().Text();
00132         if (languageTagText.empty())
00133         {
00134             result << L"Language tag input is empty ... using generic-language segmentation rules.\n";
00135             languageTagText = L"und";   // This is used for non language-specific locales. 'und' is short for 'undetermined'.
00136         }
00137         else
00138         {
00139             if (!Windows::Globalization::Language::IsWellFormed(languageTagText))
00140             {
00141                 rootPage.NotifyUser(L"Language tag is not well formed: \"" + languageTagText + L"\"", NotifyType::ErrorMessage);
00142                 return;
00143             }
00144         }
00145
00146         // Obtain the input Index
00147         hstring inputIndexString = indexBox().Text();
00148         uint32_t inputIndex = static_cast<uint32_t>(_wtoi(inputIndexString.c_str()));
00149         if (errno == EINVAL)
00150         {
00151             result << L"No input index provided ... using first segment reference (index = 0) as default.\n";
00152         }
00153         else if (inputIndex > inputStringText.size())
00154         {
00155             rootPage.NotifyUser(L"Invalid index supplied ... cannot use a negative index, or an index that is out of bounds of the input string.\n\nPlease re-check the index value, and try again.",
00156                 NotifyType::ErrorMessage);
00157             return;
00158         }
00159
00160         // Notify that we are going to calculate word segment
00161         result
00162             << L"\n\nFinding the selection segment for the given index ...\n"
00163             << L"Input: \"" << std::wstring_view(inputStringText) << L"\"\n"
00164             << L"Language Tag: \"" << std::wstring_view(languageTagText) << L"\"\n"
00165             << L"Index: " << inputIndex << L"\n";
00166
00167         // Construct the SelectableWordsSegmenter instance
00168         Windows::Data::Text::SelectableWordsSegmenter segmenter(languageTagText);
00169
00170         // Obtain the token segment
00171         auto tokenSegment = segmenter.GetTokenAt(inputStringText, inputIndex);
00172         result << L"\nIndexed segment: \"" << std::wstring_view(tokenSegment.Text()) << L"\"";
00173
00174         // Set results to output box
00175         rootPage.NotifyUser(result.str(), NotifyType::StatusMessage);
00176     }
00177 }
Generated on Fri Nov 15 2024 22:21:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MobileBroadband/cs/GetConnectionProfiles.xaml.cs Source File

  • MobileBroadband
  • cs

GetConnectionProfiles.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using SDKTemplate;
00017 using System;
00018 using Windows.Networking.NetworkOperators;
00019 using System.Collections.Generic;
00020 using Windows.Networking.Connectivity;
00021
00022 namespace MobileBroadband
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class GetConnectionProfiles : Page
00028     {
00029         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00030         // as NotifyUser()
00031         MainPage rootPage = MainPage.Current;
00032
00033         private IReadOnlyList<string> deviceAccountId = null;
00034
00035         public GetConnectionProfiles()
00036         {
00037             this.InitializeComponent();
00038         }
00039
00040         /// <summary>
00041         /// Invoked when this page is about to be displayed in a Frame.
00042         /// </summary>
00043         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00044         /// property is typically used to configure the page.</param>
00045         protected override void OnNavigatedTo(NavigationEventArgs e)
00046         {
00047             PrepareScenario();
00048         }
00049
00050         /// <summary>
00051         /// This is the click handler for the 'Default' button.  You would replace this with your own handler
00052         /// if you have a button or buttons on this page.
00053         /// </summary>
00054         /// <param name="sender"></param>
00055         /// <param name="e"></param>
00056         private void GetConnectionProfilesButton_Click(object sender, RoutedEventArgs e)
00057         {
00058             Button b = sender as Button;
00059             if (b != null)
00060             {
00061                 try
00062                 {
00063                     // For the sake of simplicity, we only get the ConnectionProfiles from the first NetworkAccountId
00064                     var mobileBroadbandAccount = MobileBroadbandAccount.CreateFromNetworkAccountId(deviceAccountId[0]);
00065                     PrintConnectionProfiles(mobileBroadbandAccount.GetConnectionProfiles());
00066                 }
00067                 catch (Exception ex)
00068                 {
00069                     rootPage.NotifyUser("Error:" + ex.Message, NotifyType.ErrorMessage);
00070                 }
00071             }
00072         }
00073
00074
00075         void PrepareScenario()
00076         {
00077             rootPage.NotifyUser("", NotifyType.StatusMessage);
00078
00079             try
00080             {
00081                 deviceAccountId = MobileBroadbandAccount.AvailableNetworkAccountIds;
00082
00083                 if (deviceAccountId.Count != 0)
00084                 {
00085                     GetConnectionProfilesButton.Content = "Get Connection Profiles";
00086                     GetConnectionProfilesButton.IsEnabled = true;
00087                 }
00088                 else
00089                 {
00090                     GetConnectionProfilesButton.Content = "No available accounts detected";
00091                     GetConnectionProfilesButton.IsEnabled = false;
00092                 }
00093             }
00094             catch (Exception ex)
00095             {
00096                 rootPage.NotifyUser("Error:" + ex.Message, NotifyType.ErrorMessage);
00097             }
00098         }
00099
00100         private void PrintConnectionProfiles(IReadOnlyList<ConnectionProfile> connectionProfiles)
00101         {
00102             string connectionProfileList = string.Empty;
00103             try
00104             {
00105                 foreach (var connectionProfile in connectionProfiles)
00106                 {
00107                     //Display Profile information for each of the connection profiles
00108                     connectionProfileList += GetConnectionProfile(connectionProfile);
00109                     connectionProfileList += "--------------------------------------------------------------------\n";
00110                 }
00111
00112                 if (connectionProfiles.Count == 0)
00113                 {
00114                     connectionProfileList += "No Connection Profiles found.\n";
00115                 }
00116
00117                 rootPage.NotifyUser(connectionProfileList, NotifyType.StatusMessage);
00118             }
00119
00120             catch (Exception ex)
00121             {
00122                 rootPage.NotifyUser("Unexpected exception occurred: " + ex.ToString(), NotifyType.ErrorMessage);
00123             }
00124         }
00125
00126         //
00127         //Get Connection Profile name and cost information
00128         //
00129         string GetConnectionProfile(ConnectionProfile connectionProfile)
00130         {
00131             string connectionProfileInfo = string.Empty;
00132             if (connectionProfile != null)
00133             {
00134                 connectionProfileInfo = "Profile Name : " + connectionProfile.ProfileName + "\n";
00135
00136                 switch (connectionProfile.GetNetworkConnectivityLevel())
00137                 {
00138                     case NetworkConnectivityLevel.None:
00139                         connectionProfileInfo += "Connectivity Level : None\n";
00140                         break;
00141                     case NetworkConnectivityLevel.LocalAccess:
00142                         connectionProfileInfo += "Connectivity Level : Local Access\n";
00143                         break;
00144                     case NetworkConnectivityLevel.ConstrainedInternetAccess:
00145                         connectionProfileInfo += "Connectivity Level : Constrained Internet Access\n";
00146                         break;
00147                     case NetworkConnectivityLevel.InternetAccess:
00148                         connectionProfileInfo += "Connectivity Level : Internet Access\n";
00149                         break;
00150                 }
00151
00152                 switch (connectionProfile.GetDomainConnectivityLevel())
00153                 {
00154                     case DomainConnectivityLevel.None:
00155                         connectionProfileInfo += "Domain Connectivity Level : None\n";
00156                         break;
00157                     case DomainConnectivityLevel.Unauthenticated:
00158                         connectionProfileInfo += "Domain Connectivity Level : Unauthenticated\n";
00159                         break;
00160                     case DomainConnectivityLevel.Authenticated:
00161                         connectionProfileInfo += "Domain Connectivity Level : Authenticated\n";
00162                         break;
00163                 }
00164
00165                 //Get Connection Cost information
00166                 ConnectionCost connectionCost = connectionProfile.GetConnectionCost();
00167                 connectionProfileInfo += GetConnectionCostInfo(connectionCost);
00168
00169                 //Get Dataplan Status information
00170                 DataPlanStatus dataPlanStatus = connectionProfile.GetDataPlanStatus();
00171                 connectionProfileInfo += GetDataPlanStatusInfo(dataPlanStatus);
00172
00173                 //Get Network Security Settings
00174                 NetworkSecuritySettings netSecuritySettings = connectionProfile.NetworkSecuritySettings;
00175                 connectionProfileInfo += GetNetworkSecuritySettingsInfo(netSecuritySettings);
00176
00177                 //Get Wlan Connection Profile Details if this is a Wlan ConnectionProfile
00178                 if (connectionProfile.IsWlanConnectionProfile)
00179                 {
00180                     WlanConnectionProfileDetails wlanConnectionProfileDetails = connectionProfile.WlanConnectionProfileDetails;
00181                     connectionProfileInfo += GetWlanConnectionProfileDetailsInfo(wlanConnectionProfileDetails);
00182                 }
00183
00184                 //Get Wwan Connection Profile Details if this is a Wwan ConnectionProfile
00185                 if (connectionProfile.IsWwanConnectionProfile)
00186                 {
00187                     WwanConnectionProfileDetails wwanConnectionProfileDetails = connectionProfile.WwanConnectionProfileDetails;
00188                     connectionProfileInfo += GetWwanConnectionProfileDetailsInfo(wwanConnectionProfileDetails);
00189                 }
00190
00191                 //Get the Service Provider GUID
00192                 if (connectionProfile.ServiceProviderGuid.HasValue)
00193                 {
00194                     connectionProfileInfo += "====================\n";
00195                     connectionProfileInfo += "Service Provider GUID: " + connectionProfile.ServiceProviderGuid + "\n";
00196                 }
00197
00198                 //Get the number of signal bars
00199                 if (connectionProfile.GetSignalBars().HasValue)
00200                 {
00201                     connectionProfileInfo += "====================\n";
00202                     connectionProfileInfo += "Signal Bars: " + connectionProfile.GetSignalBars() + "\n";
00203                 }
00204             }
00205             return connectionProfileInfo;
00206         }
00207
00208         //
00209         //Get Profile Connection cost
00210         //
00211         string GetConnectionCostInfo(ConnectionCost connectionCost)
00212         {
00213             string cost = string.Empty;
00214             cost += "Connection Cost Information: \n";
00215             cost += "====================\n";
00216
00217             if (connectionCost == null)
00218             {
00219                 cost += "Connection Cost not available\n";
00220                 return cost;
00221             }
00222
00223             switch (connectionCost.NetworkCostType)
00224             {
00225                 case NetworkCostType.Unrestricted:
00226                     cost += "Cost: Unrestricted";
00227                     break;
00228                 case NetworkCostType.Fixed:
00229                     cost += "Cost: Fixed";
00230                     break;
00231                 case NetworkCostType.Variable:
00232                     cost += "Cost: Variable";
00233                     break;
00234                 case NetworkCostType.Unknown:
00235                     cost += "Cost: Unknown";
00236                     break;
00237                 default:
00238                     cost += "Cost: Error";
00239                     break;
00240             }
00241             cost += "\n";
00242             cost += "Roaming: " + connectionCost.Roaming + "\n";
00243             cost += "Over Data Limit: " + connectionCost.OverDataLimit + "\n";
00244             cost += "Approaching Data Limit : " + connectionCost.ApproachingDataLimit + "\n";
00245
00246             //Display cost based suggestions to the user
00247             cost += CostBasedSuggestions(connectionCost);
00248             return cost;
00249         }
00250
00251         //
00252         //Display Cost based suggestions to the user
00253         //
00254         string CostBasedSuggestions(ConnectionCost connectionCost)
00255         {
00256             string costBasedSuggestions = string.Empty;
00257             costBasedSuggestions += "Cost Based Suggestions: \n";
00258             costBasedSuggestions += "====================\n";
00259
00260             if (connectionCost.Roaming)
00261             {
00262                 costBasedSuggestions += "Connection is out of MNO's network, using the connection may result in additional charge. Application can implement High Cost behavior in this scenario\n";
00263             }
00264             else if (connectionCost.NetworkCostType == NetworkCostType.Variable)
00265             {
00266                 costBasedSuggestions += "Connection cost is variable, and the connection is charged based on usage, so application can implement the Conservative behavior\n";
00267             }
00268             else if (connectionCost.NetworkCostType == NetworkCostType.Fixed)
00269             {
00270                 if (connectionCost.OverDataLimit || connectionCost.ApproachingDataLimit)
00271                 {
00272                     costBasedSuggestions += "Connection has exceeded the usage cap limit or is approaching the datalimit, and the application can implement High Cost behavior in this scenario\n";
00273                 }
00274                 else
00275                 {
00276                     costBasedSuggestions += "Application can implemement the Conservative behavior\n";
00277                 }
00278             }
00279             else
00280             {
00281                 costBasedSuggestions += "Application can implement the Standard behavior\n";
00282             }
00283             return costBasedSuggestions;
00284         }
00285
00286         //
00287         //Display Profile Dataplan Status information
00288         //
00289         string GetDataPlanStatusInfo(DataPlanStatus dataPlan)
00290         {
00291             string dataplanStatusInfo = string.Empty;
00292             dataplanStatusInfo = "Dataplan Status Information:\n";
00293             dataplanStatusInfo += "====================\n";
00294
00295             if (dataPlan == null)
00296             {
00297                 dataplanStatusInfo += "Dataplan Status not available\n";
00298                 return dataplanStatusInfo;
00299             }
00300
00301             if (dataPlan.DataPlanUsage != null)
00302             {
00303                 dataplanStatusInfo += "Usage In Megabytes : " + dataPlan.DataPlanUsage.MegabytesUsed + "\n";
00304                 dataplanStatusInfo += "Last Sync Time : " + dataPlan.DataPlanUsage.LastSyncTime + "\n";
00305             }
00306             else
00307             {
00308                 dataplanStatusInfo += "Usage In Megabytes : Not Defined\n";
00309             }
00310
00311             ulong? inboundBandwidth = dataPlan.InboundBitsPerSecond;
00312             if (inboundBandwidth.HasValue)
00313             {
00314                 dataplanStatusInfo += "InboundBitsPerSecond : " + inboundBandwidth + "\n";
00315             }
00316             else
00317             {
00318                 dataplanStatusInfo += "InboundBitsPerSecond : Not Defined\n";
00319             }
00320
00321             ulong? outboundBandwidth = dataPlan.OutboundBitsPerSecond;
00322             if (outboundBandwidth.HasValue)
00323             {
00324                 dataplanStatusInfo += "OutboundBitsPerSecond : " + outboundBandwidth + "\n";
00325             }
00326             else
00327             {
00328                 dataplanStatusInfo += "OutboundBitsPerSecond : Not Defined\n";
00329             }
00330
00331             uint? dataLimit = dataPlan.DataLimitInMegabytes;
00332             if (dataLimit.HasValue)
00333             {
00334                 dataplanStatusInfo += "DataLimitInMegabytes : " + dataLimit + "\n";
00335             }
00336             else
00337             {
00338                 dataplanStatusInfo += "DataLimitInMegabytes : Not Defined\n";
00339             }
00340
00341             System.DateTimeOffset? nextBillingCycle = dataPlan.NextBillingCycle;
00342             if (nextBillingCycle.HasValue)
00343             {
00344                 dataplanStatusInfo += "NextBillingCycle : " + nextBillingCycle + "\n";
00345             }
00346             else
00347             {
00348                 dataplanStatusInfo += "NextBillingCycle : Not Defined\n";
00349             }
00350
00351             uint? maxTransferSize = dataPlan.MaxTransferSizeInMegabytes;
00352             if (maxTransferSize.HasValue)
00353             {
00354                 dataplanStatusInfo += "MaxTransferSizeInMegabytes : " + maxTransferSize + "\n";
00355             }
00356             else
00357             {
00358                 dataplanStatusInfo += "MaxTransferSizeInMegabytes : Not Defined\n";
00359             }
00360             return dataplanStatusInfo;
00361         }
00362
00363         //
00364         //Get Network Security Settings information
00365         //
00366         string GetNetworkSecuritySettingsInfo(NetworkSecuritySettings netSecuritySettings)
00367         {
00368             string networkSecurity = string.Empty;
00369             networkSecurity += "Network Security Settings: \n";
00370             networkSecurity += "====================\n";
00371
00372             if (netSecuritySettings == null)
00373             {
00374                 networkSecurity += "Network Security Settings not available\n";
00375                 return networkSecurity;
00376             }
00377
00378             //NetworkAuthenticationType
00379             switch (netSecuritySettings.NetworkAuthenticationType)
00380             {
00381                 case NetworkAuthenticationType.None:
00382                     networkSecurity += "NetworkAuthenticationType: None";
00383                     break;
00384                 case NetworkAuthenticationType.Unknown:
00385                     networkSecurity += "NetworkAuthenticationType: Unknown";
00386                     break;
00387                 case NetworkAuthenticationType.Open80211:
00388                     networkSecurity += "NetworkAuthenticationType: Open80211";
00389                     break;
00390                 case NetworkAuthenticationType.SharedKey80211:
00391                     networkSecurity += "NetworkAuthenticationType: SharedKey80211";
00392                     break;
00393                 case NetworkAuthenticationType.Wpa:
00394                     networkSecurity += "NetworkAuthenticationType: Wpa";
00395                     break;
00396                 case NetworkAuthenticationType.WpaPsk:
00397                     networkSecurity += "NetworkAuthenticationType: WpaPsk";
00398                     break;
00399                 case NetworkAuthenticationType.WpaNone:
00400                     networkSecurity += "NetworkAuthenticationType: WpaNone";
00401                     break;
00402                 case NetworkAuthenticationType.Rsna:
00403                     networkSecurity += "NetworkAuthenticationType: Rsna";
00404                     break;
00405                 case NetworkAuthenticationType.RsnaPsk:
00406                     networkSecurity += "NetworkAuthenticationType: RsnaPsk";
00407                     break;
00408                 default:
00409                     networkSecurity += "NetworkAuthenticationType: Error";
00410                     break;
00411             }
00412             networkSecurity += "\n";
00413
00414             //NetworkEncryptionType
00415             switch (netSecuritySettings.NetworkEncryptionType)
00416             {
00417                 case NetworkEncryptionType.None:
00418                     networkSecurity += "NetworkEncryptionType: None";
00419                     break;
00420                 case NetworkEncryptionType.Unknown:
00421                     networkSecurity += "NetworkEncryptionType: Unknown";
00422                     break;
00423                 case NetworkEncryptionType.Wep:
00424                     networkSecurity += "NetworkEncryptionType: Wep";
00425                     break;
00426                 case NetworkEncryptionType.Wep40:
00427                     networkSecurity += "NetworkEncryptionType: Wep40";
00428                     break;
00429                 case NetworkEncryptionType.Wep104:
00430                     networkSecurity += "NetworkEncryptionType: Wep104";
00431                     break;
00432                 case NetworkEncryptionType.Tkip:
00433                     networkSecurity += "NetworkEncryptionType: Tkip";
00434                     break;
00435                 case NetworkEncryptionType.Ccmp:
00436                     networkSecurity += "NetworkEncryptionType: Ccmp";
00437                     break;
00438                 case NetworkEncryptionType.WpaUseGroup:
00439                     networkSecurity += "NetworkEncryptionType: WpaUseGroup";
00440                     break;
00441                 case NetworkEncryptionType.RsnUseGroup:
00442                     networkSecurity += "NetworkEncryptionType: RsnUseGroup";
00443                     break;
00444                 default:
00445                     networkSecurity += "NetworkEncryptionType: Error";
00446                     break;
00447             }
00448             networkSecurity += "\n";
00449             return networkSecurity;
00450         }
00451
00452         string GetWlanConnectionProfileDetailsInfo(WlanConnectionProfileDetails wlanConnectionProfileDetails)
00453         {
00454             string wlanDetails = string.Empty;
00455             wlanDetails += "Wireless LAN Connection Profile Details:\n";
00456             wlanDetails += "====================\n";
00457
00458             if (wlanConnectionProfileDetails == null)
00459             {
00460                 wlanDetails += "Wireless LAN connection profile details unavailable.\n";
00461                 return wlanDetails;
00462             }
00463
00464             wlanDetails += "Connected SSID: " + wlanConnectionProfileDetails.GetConnectedSsid() + "\n";
00465             return wlanDetails;
00466         }
00467
00468         string GetWwanConnectionProfileDetailsInfo(WwanConnectionProfileDetails wwanConnectionProfileDetails)
00469         {
00470             string wwanDetails = string.Empty;
00471             wwanDetails += "Wireless WAN Connection Profile Details:\n";
00472             wwanDetails += "====================\n";
00473
00474             if (wwanConnectionProfileDetails == null)
00475             {
00476                 wwanDetails += "Wireless WAN connection profile details unavailable.\n";
00477                 return wwanDetails;
00478             }
00479
00480             wwanDetails += "Home Provider ID: " + wwanConnectionProfileDetails.HomeProviderId + "\n";
00481             wwanDetails += "Access Point Name: " + wwanConnectionProfileDetails.AccessPointName + "\n";
00482             wwanDetails += "Network Registration State: " + wwanConnectionProfileDetails.GetNetworkRegistrationState() + "\n";
00483             wwanDetails += "Current Data Class: " + wwanConnectionProfileDetails.GetCurrentDataClass() + "\n";
00484
00485             return wwanDetails;
00486         }
00487     }
00488 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_StringTemplate Member List

This is the complete list of members for Scenario2_StringTemplate, including all inherited members.
Display() | Scenario2_StringTemplate | [inline, private]
Scenario2_StringTemplate() | Scenario2_StringTemplate | [inline]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
__pad0__ | sealed | [protected]
_applicationResumingEventToken | sealed | [private]
_applicationSuspendingEventToken | sealed | [private]
_captureFolder | sealed | [private]
_displayInformation | sealed | [private]
_displayInformationEventToken | sealed | [private]
_displayOrientation | sealed | [private]
_displayRequest | sealed | [private]
_externalCamera | sealed | [private]
_isInitialized | sealed | [private]
_isPreviewing | sealed | [private]
_mediaCapture | sealed | [private]
_mediaCaptureFailedEventToken | sealed | [private]
_mediaControlPropChangedEventToken | sealed | [private]
_mirroringPreview | sealed | [private]
_systemMediaControls | sealed | [private]
Application_Resuming(Object^sender, Object^args) | sealed | [private]
Application_Suspending(Object^sender, Windows::ApplicationModel::SuspendingEventArgs^e) | sealed | [private]
ApplyGreenFilter(Windows::Graphics::Imaging::SoftwareBitmap^bitmap) | sealed | [private]
CleanupCameraAsync() | sealed | [private]
ConvertDisplayOrientationToDegrees(Windows::Graphics::Display::DisplayOrientations orientation) | sealed | [private]
DisplayInformation_OrientationChanged(Windows::Graphics::Display::DisplayInformation^sender, Object^args) | sealed | [private]
FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel panel) | sealed | [private]
GetPreviewFrameAsD3DSurfaceAsync() | sealed | [private]
GetPreviewFrameAsSoftwareBitmapAsync() | sealed | [private]
GetPreviewFrameButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InitializeCameraAsync() | sealed | [private]
MainPage() | sealed |
MediaCapture_Failed(Windows::Media::Capture::MediaCapture^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^errorEventArgs) | sealed | [private]
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | sealed | [protected, virtual]
OnNavigationFailed(Platform::Object^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs^e) | sealed | [private]
RotationKey | sealed | [private]
SaveSoftwareBitmapAsync(Windows::Graphics::Imaging::SoftwareBitmap^bitmap) | sealed | [private]
SetPreviewRotationAsync() | sealed | [private]
StartPreviewAsync() | sealed | [private]
StopPreviewAsync() | sealed | [private]
SystemMediaControls_PropertyChanged(Windows::Media::SystemMediaTransportControls^sender, Windows::Media::SystemMediaTransportControlsPropertyChangedEventArgs^args) | sealed | [private]
WriteException(Platform::Exception^ex) | sealed | [private]
WriteLine(Platform::String^str) | sealed | [private]
~MainPage() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/Common/BasicReaderWriter.cpp Source File

  • Simple3DGameXaml
  • cpp
  • Common

BasicReaderWriter.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "BasicReaderWriter.h"
00010
00011 using namespace Microsoft::WRL;
00012 using namespace Windows::Storage;
00013 using namespace Windows::Storage::FileProperties;
00014 using namespace Windows::Storage::Streams;
00015 using namespace Windows::Foundation;
00016 using namespace Windows::ApplicationModel;
00017 using namespace concurrency;
00018
00019 BasicReaderWriter::BasicReaderWriter()
00020 {
00021     m_location = Package::Current->InstalledLocation;
00022 }
00023
00024 BasicReaderWriter::BasicReaderWriter(
00025     _In_ Windows::Storage::StorageFolder^ folder
00026     )
00027 {
00028     m_location = folder;
00029     Platform::String^ path = m_location->Path;
00030     if (path->Length() == 0)
00031     {
00032         // Applications are not permitted to access certain
00033         // folders, such as the Documents folder, using this
00034         // code path.  In such cases, the Path property for
00035         // the folder will be an empty string.
00036         throw ref new Platform::FailureException();
00037     }
00038 }
00039
00040 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00041     _In_ Platform::String^ filename
00042     )
00043 {
00044     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00045     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00046     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00047     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00048     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00049     extendedParams.lpSecurityAttributes = nullptr;
00050     extendedParams.hTemplateFile = nullptr;
00051
00052     Wrappers::FileHandle file(
00053         CreateFile2(
00054             filename->Data(),
00055             GENERIC_READ,
00056             FILE_SHARE_READ,
00057             OPEN_EXISTING,
00058             &extendedParams
00059             )
00060         );
00061     if (file.Get() == INVALID_HANDLE_VALUE)
00062     {
00063         throw ref new Platform::FailureException();
00064     }
00065
00066     FILE_STANDARD_INFO fileInfo = {0};
00067     if (!GetFileInformationByHandleEx(
00068         file.Get(),
00069         FileStandardInfo,
00070         &fileInfo,
00071         sizeof(fileInfo)
00072         ))
00073     {
00074         throw ref new Platform::FailureException();
00075     }
00076
00077     if (fileInfo.EndOfFile.HighPart != 0)
00078     {
00079         throw ref new Platform::OutOfMemoryException();
00080     }
00081
00082     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00083
00084     if (!ReadFile(
00085         file.Get(),
00086         fileData->Data,
00087         fileData->Length,
00088         nullptr,
00089         nullptr
00090         ))
00091     {
00092         throw ref new Platform::FailureException();
00093     }
00094
00095     return fileData;
00096 }
00097
00098 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00099     _In_ Platform::String^ filename
00100     )
00101 {
00102     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00103     {
00104         return FileIO::ReadBufferAsync(file);
00105     }).then([=](IBuffer^ buffer)
00106     {
00107         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00108         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00109         return fileData;
00110     });
00111 }
00112
00113 uint32 BasicReaderWriter::WriteData(
00114     _In_ Platform::String^ filename,
00115     _In_ const Platform::Array<byte>^ fileData
00116     )
00117 {
00118     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00119     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00120     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00121     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00122     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00123     extendedParams.lpSecurityAttributes = nullptr;
00124     extendedParams.hTemplateFile = nullptr;
00125
00126     Wrappers::FileHandle file(
00127         CreateFile2(
00128             filename->Data(),
00129             GENERIC_WRITE,
00130             0,
00131             CREATE_ALWAYS,
00132             &extendedParams
00133             )
00134         );
00135     if (file.Get() == INVALID_HANDLE_VALUE)
00136     {
00137         throw ref new Platform::FailureException();
00138     }
00139
00140     DWORD numBytesWritten;
00141     if (
00142         !WriteFile(
00143             file.Get(),
00144             fileData->Data,
00145             fileData->Length,
00146             &numBytesWritten,
00147             nullptr
00148             ) ||
00149         numBytesWritten != fileData->Length
00150         )
00151     {
00152         throw ref new Platform::FailureException();
00153     }
00154
00155     return numBytesWritten;
00156 }
00157
00158 task<void> BasicReaderWriter::WriteDataAsync(
00159     _In_ Platform::String^ filename,
00160     _In_ const Platform::Array<byte>^ fileData
00161     )
00162 {
00163     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00164     {
00165         FileIO::WriteBytesAsync(file, fileData);
00166     });
00167 }
Generated on Fri Nov 15 2024 22:19:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ApduResponse Member List

This is the complete list of members for ApduResponse, including all inherited members.
ApduResponse() | ApduResponse | [inline]
ExtractResponse(IBuffer response) | ApduResponse | [inline, virtual]
ExtractTlvDataObject(byte[] referenceTag) | ApduResponse | [inline]
ResponseData | ApduResponse |
Succeeded | ApduResponse |
SW | ApduResponse |
SW1 | ApduResponse |
SW2 | ApduResponse |
SWTranslation | ApduResponse |
TAG_COMPREHENSION_MASK | ApduResponse |
TAG_LENGTH_MULTI_BYTE_MASK | ApduResponse |
TAG_MULTI_BYTE_MASK | ApduResponse |
ToString() | ApduResponse | [inline]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FolderEnumeration/cppwinrt/pch.h Source File

  • FolderEnumeration
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Storage.h"
00008 #include "winrt/Windows.Storage.FileProperties.h"
00009 #include "winrt/Windows.Storage.Pickers.h"
00010 #include "winrt/Windows.Storage.Search.h"
00011 #include "winrt/Windows.System.h"
00012 #include "winrt/Windows.UI.Core.h"
00013 #include "winrt/Windows.UI.Xaml.h"
00014 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00015 #include "winrt/Windows.UI.Xaml.Controls.h"
00016 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00017 #include "winrt/Windows.UI.Xaml.Documents.h"
00018 #include "winrt/Windows.UI.Xaml.Interop.h"
00019 #include "winrt/Windows.UI.Xaml.Markup.h"
00020 #include "winrt/Windows.UI.Xaml.Media.h"
00021 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario1_Create.xaml.cpp Source File

  • FileAccess
  • cpp

Scenario1_Create.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_Create.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Storage;
00020 using namespace Windows::UI::Xaml;
00021
00022 Scenario1::Scenario1()
00023 {
00024     InitializeComponent();
00025 }
00026
00027 void Scenario1::CreateFileButton_Click(Object^ sender, RoutedEventArgs^ e)
00028 {
00029     create_task(KnownFolders::GetFolderForUserAsync(nullptr /* current user */, KnownFolderId::PicturesLibrary))
00030         .then([this](StorageFolder^ picturesFolder)
00031     {
00032         return picturesFolder->CreateFileAsync(rootPage->Filename, CreationCollisionOption::ReplaceExisting);
00033     }).then([this](task<StorageFile^> task)
00034     {
00035         try
00036         {
00037             StorageFile^ file = task.get();
00038             rootPage->SampleFile = file;
00039             rootPage->NotifyUser("The file '" + file->Name + "' was created.", NotifyType::StatusMessage);
00040         }
00041         catch (Exception^ e)
00042         {
00043             // I/O errors are reported as exceptions.
00044             rootPage->NotifyUser("Error creating file '" + MainPage::Filename + "': " + e->Message, NotifyType::ErrorMessage);
00045         }
00046     });
00047 }
Generated on Fri Nov 15 2024 22:19:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MessageDialog/cpp/CompletedCallback.xaml.cpp Source File

  • MessageDialog
  • cpp

CompletedCallback.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // CompletedCallback.xaml.cpp
00013 // Implementation of the CompletedCallback class
00014 //
00015
00016 #include "pch.h"
00017 #include "CompletedCallback.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::UI::Popups;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 CompletedCallback::CompletedCallback()
00030 {
00031     InitializeComponent();
00032 }
00033
00034 void CompletedCallback::OnNavigatedTo(NavigationEventArgs^ e)
00035 {
00036     rootPage = MainPage::Current;
00037 }
00038
00039 /// <summary>
00040 /// Click handler for the 'CompletedCallbackButton' button.
00041 /// Demonstrates the use of a message dialog with custom commands and using a completed callback instead of delegates.
00042 /// A message will be displayed indicating which command was invoked on the dialog.
00043 /// In this scenario, 'Install updates' is selected as the default choice.
00044 /// </summary>
00045 /// <param name="sender">The Object that caused this event to be fired.</param>
00046 /// <param name="e">State information and event data associated with the routed event.</param>
00047 void CompletedCallback::CompletedCallbackButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00048 {
00049     // Create the message dialog and set its content and title
00050     auto messageDialog = ref new MessageDialog("New updates have been found for this program. Would you like to install the new updates?", "Updates available");
00051
00052     // Add the commands to the dialog, use ids for the commands instead of delegates
00053     messageDialog->Commands->Append(ref new UICommand("Don't install", nullptr, PropertyValue::CreateInt32(0)));
00054     messageDialog->Commands->Append(ref new UICommand("Install updates", nullptr, PropertyValue::CreateInt32(1)));
00055
00056     // Set the command that will be invoked by default
00057     messageDialog->DefaultCommandIndex = 1;
00058
00059     // Show the message dialog and retrieve the id of the chosen command
00060     create_task(messageDialog->ShowAsync()).then([this](IUICommand^ command)
00061     {
00062         if (command->Id != nullptr)
00063         {
00064             rootPage->NotifyUser("The '" + command->Label + "' (" +  command->Id + ") command has been selected.", NotifyType::StatusMessage);
00065         }
00066         else
00067         {
00068             rootPage->NotifyUser("The dialog has now been closed", NotifyType::StatusMessage);
00069         }
00070     });
00071 }
Generated on Fri Nov 15 2024 22:20:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario_ContinuousRecognitionListGrammar Member List

This is the complete list of members for Scenario_ContinuousRecognitionListGrammar, including all inherited members.
cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario_ContinuousRecognitionListGrammar | [inline, private]
ContinuousRecognitionSession_Completed(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionCompletedEventArgs args) | Scenario_ContinuousRecognitionListGrammar | [inline, private]
ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionResultGeneratedEventArgs args) | Scenario_ContinuousRecognitionListGrammar | [inline, private]
ContinuousRecognize_Click(object sender, RoutedEventArgs e) | Scenario_ContinuousRecognitionListGrammar | [inline]
HResultRecognizerNotFound | Scenario_ContinuousRecognitionListGrammar | [private, static]
InitializeRecognizer(Language recognizerLanguage) | Scenario_ContinuousRecognitionListGrammar | [inline, private]
isListening | Scenario_ContinuousRecognitionListGrammar | [private]
isPopulatingLanguages | Scenario_ContinuousRecognitionListGrammar | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario_ContinuousRecognitionListGrammar | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario_ContinuousRecognitionListGrammar | [inline, protected]
PopulateLanguageDropdown() | Scenario_ContinuousRecognitionListGrammar | [inline, private]
rootPage | Scenario_ContinuousRecognitionListGrammar | [private]
Scenario_ContinuousRecognitionListGrammar() | Scenario_ContinuousRecognitionListGrammar | [inline]
speechContext | Scenario_ContinuousRecognitionListGrammar | [private]
speechRecognizer | Scenario_ContinuousRecognitionListGrammar | [private]
SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args) | Scenario_ContinuousRecognitionListGrammar | [inline, private]
speechResourceMap | Scenario_ContinuousRecognitionListGrammar | [private]
Generated on Fri Nov 15 2024 22:24:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_MultipleScanners Member List

This is the complete list of members for Scenario2_MultipleScanners, including all inherited members.
BarcodeScannerInstance enum name | Scenario2_MultipleScanners | [private]
ButtonEndScanningInstance1_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_MultipleScanners |
ButtonEndScanningInstance2_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_MultipleScanners |
ButtonStartScanningInstance1_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_MultipleScanners |
ButtonStartScanningInstance2_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_MultipleScanners |
ClaimBarcodeScannerAsync(BarcodeScannerInstance instance) | Scenario2_MultipleScanners | [private]
claimedBarcodeScannerInstance1_DataReceived(Windows::Devices::PointOfService::ClaimedBarcodeScanner const &, Windows::Devices::PointOfService::BarcodeScannerDataReceivedEventArgs args) | Scenario2_MultipleScanners | [private]
claimedBarcodeScannerInstance1_ReleaseDeviceRequested(Windows::Foundation::IInspectable const &sender, Windows::Devices::PointOfService::ClaimedBarcodeScanner const &) | Scenario2_MultipleScanners |
claimedBarcodeScannerInstance2_DataReceived(Windows::Devices::PointOfService::ClaimedBarcodeScanner const &, Windows::Devices::PointOfService::BarcodeScannerDataReceivedEventArgs args) | Scenario2_MultipleScanners | [private]
claimedBarcodeScannerInstance2_ReleaseDeviceRequested(Windows::Foundation::IInspectable const &sender, Windows::Devices::PointOfService::ClaimedBarcodeScanner const &) | Scenario2_MultipleScanners |
CreateDefaultScannerObjectAsync(BarcodeScannerInstance instance) | Scenario2_MultipleScanners | [private]
EnableBarcodeScannerAsync(BarcodeScannerInstance instance) | Scenario2_MultipleScanners | [private]
Instance1 enum value | Scenario2_MultipleScanners | [private]
Instance2 enum value | Scenario2_MultipleScanners | [private]
m_dev1DataReceivedToken | Scenario2_MultipleScanners | [private]
m_dev1ReleaseRequestedToken | Scenario2_MultipleScanners | [private]
m_dev2DataReceivedToken | Scenario2_MultipleScanners | [private]
m_dev2ReleaseRequestedToken | Scenario2_MultipleScanners | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario2_MultipleScanners |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario2_MultipleScanners |
ResetTheScenarioState() | Scenario2_MultipleScanners | [private]
ResetUI() | Scenario2_MultipleScanners | [private]
Scenario2_MultipleScanners() | Scenario2_MultipleScanners |
SetUI(BarcodeScannerInstance instance) | Scenario2_MultipleScanners | [private]
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cs/Scenario1.xaml.cs Source File

  • SimpleInk
  • cs

Scenario1.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using System.Linq;
00012 using Windows.Foundation;
00013 using Windows.UI.Input.Inking;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Media;
00017 using Windows.UI.Xaml.Navigation;
00018 using Windows.UI.Xaml.Shapes;
00019 using SDKTemplate;
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// This page shows the code to enabled the InkToolbar and InkCanvas.
00025     /// </summary>
00026     public sealed partial class Scenario1 : Page
00027     {
00028         public Scenario1()
00029         {
00030             this.InitializeComponent();
00031
00032             // Initialize the InkCanvas
00033             inkCanvas.InkPresenter.InputDeviceTypes =
00034                 Windows.UI.Core.CoreInputDeviceTypes.Mouse |
00035                 Windows.UI.Core.CoreInputDeviceTypes.Pen;
00036         }
00037
00038         private void OnSizeChanged(object sender, SizeChangedEventArgs e)
00039         {
00040             HelperFunctions.UpdateCanvasSize(RootGrid, outputGrid, inkCanvas);
00041         }
00042     }
00043 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RelativeInclinometer/cpp/SampleConfiguration.h Source File

  • RelativeInclinometer
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Relative inclinometer sensor";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cs/Tasks/CompletionGroupTask.cs Source File

  • BackgroundTransfer
  • cs
  • Tasks

CompletionGroupTask.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Globalization;
00015 using System.Linq;
00016 using System.Text;
00017 using System.Threading.Tasks;
00018 using Windows.ApplicationModel.Background;
00019 using Windows.Data.Xml.Dom;
00020 using Windows.Networking.BackgroundTransfer;
00021 using Windows.Storage;
00022 using Windows.UI.Notifications;
00023
00024 namespace Tasks
00025 {
00026     public sealed class CompletionGroupTask : IBackgroundTask
00027     {
00028         // Completion groups allow us to immediately take action after a set of downloads completes.
00029         // In this sample, the server intentionally replies with an error status for some of the downloads.
00030         // Based on the trigger details, we can determine which of the downloads have failed and try them again
00031         // using a new completion group.
00032         public async void Run(IBackgroundTaskInstance taskInstance)
00033         {
00034             // The background task awaits on an asynchronous task (RetryDownloadsAsync). Take a deferral
00035             // to delay the background task from closing prematurely while the asynchronous code is still running.
00036             BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
00037
00038             BackgroundTransferCompletionGroupTriggerDetails details = taskInstance.TriggerDetails
00039                 as BackgroundTransferCompletionGroupTriggerDetails;
00040
00041             if (details == null)
00042             {
00043                 // This task was not triggered by a completion group.
00044                 deferral.Complete();
00045                 return;
00046             }
00047
00048             List<DownloadOperation> failedDownloads = new List<DownloadOperation>();
00049             int succeeded = 0;
00050             foreach (DownloadOperation download in details.Downloads)
00051             {
00052                 if (IsFailed(download))
00053                 {
00054                     failedDownloads.Add(download);
00055                 }
00056                 else
00057                 {
00058                     succeeded++;
00059                 }
00060             }
00061
00062             InvokeSimpleToast(succeeded, failedDownloads.Count);
00063
00064             if (failedDownloads.Count > 0)
00065             {
00066                 await RetryDownloadsAsync(failedDownloads);
00067             }
00068
00069             deferral.Complete();
00070         }
00071
00072         private bool IsFailed(DownloadOperation download)
00073         {
00074             BackgroundTransferStatus status = download.Progress.Status;
00075             if (status == BackgroundTransferStatus.Error || status == BackgroundTransferStatus.Canceled)
00076             {
00077                 return true;
00078             }
00079
00080             ResponseInformation response = download.GetResponseInformation();
00081             if (response == null || response.StatusCode != 200)
00082             {
00083                 return true;
00084             }
00085
00086             return false;
00087         }
00088         private async Task RetryDownloadsAsync(IEnumerable<DownloadOperation> downloadsToRetry)
00089         {
00090             BackgroundDownloader downloader = CompletionGroupTask.CreateBackgroundDownloader();
00091
00092             foreach (DownloadOperation downloadToRetry in downloadsToRetry)
00093             {
00094                 // Retry with the same uri, but save to a different file name.
00095                 string originalName = downloadToRetry.ResultFile.Name;
00096                 string newName = originalName.Insert(originalName.LastIndexOf('.'), "_retried");
00097                 await downloadToRetry.ResultFile.RenameAsync(newName, NameCollisionOption.ReplaceExisting);
00098
00099                 DownloadOperation download = downloader.CreateDownload(downloadToRetry.RequestedUri, downloadToRetry.ResultFile);
00100
00101                 // We do not await on background transfer asynchronous tasks, since await will only
00102                 // finish after the entire transfer is complete, which may take a very long time.
00103                 // The completion of these downloads will be handled by a future CompletionGroupTask instance.
00104                 Task<DownloadOperation> startTask = download.StartAsync().AsTask();
00105             }
00106
00107             downloader.CompletionGroup.Enable();
00108         }
00109
00110         public void InvokeSimpleToast(int succeeded, int failed)
00111         {
00112             XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText02);
00113
00114             XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
00115             stringElements.Item(0).AppendChild(toastXml.CreateTextNode(String.Format(
00116                 CultureInfo.InvariantCulture,
00117                 "{0} downloads succeeded.",
00118                 succeeded)));
00119             stringElements.Item(1).AppendChild(toastXml.CreateTextNode(String.Format(
00120                 CultureInfo.InvariantCulture,
00121                 "{0} downloads failed.",
00122                 failed)));
00123
00124             ToastNotification toast = new ToastNotification(toastXml);
00125             ToastNotificationManager.CreateToastNotifier().Show(toast);
00126         }
00127
00128         public static BackgroundDownloader CreateBackgroundDownloader()
00129         {
00130             BackgroundTransferCompletionGroup completionGroup = new BackgroundTransferCompletionGroup();
00131
00132             BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
00133             builder.TaskEntryPoint = "Tasks.CompletionGroupTask";
00134             builder.SetTrigger(completionGroup.Trigger);
00135
00136             // The system automatically unregisters the BackgroundTransferCompletionGroup task when it triggers.
00137             // You do not need to unregister it explicitly.
00138             BackgroundTaskRegistration taskRegistration = builder.Register();
00139
00140             BackgroundDownloader downloader = new BackgroundDownloader(completionGroup);
00141
00142             return downloader;
00143         }
00144
00145     }
00146 }
Generated on Fri Nov 15 2024 22:18:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomHidDeviceAccess/cpp/DeviceListEntry.h Source File

  • CustomHidDeviceAccess
  • cpp

DeviceListEntry.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008
00009 #include "SampleConfiguration.h"
00010
00011 namespace SDKTemplate
00012 {
00013     /// <summary>
00014     /// The class will only expose properties from DeviceInformation that are going to be used
00015     /// in this sample. Each instance of this class provides information about a single device.
00016     ///
00017     /// This class is used by the UI to display device specific information so that
00018     /// the user can identify which device to use.
00019     /// </summary>
00020     [Windows::UI::Xaml::Data::Bindable]
00021     public ref class DeviceListEntry sealed
00022     {
00023     public:
00024         property Platform::String^ InstanceId
00025         {
00026             Platform::String^ get(void);
00027         }
00028
00029         property Windows::Devices::Enumeration::DeviceInformation^ DeviceInformation
00030         {
00031             Windows::Devices::Enumeration::DeviceInformation^ get(void)
00032             {
00033                 return device;
00034             }
00035         }
00036
00037         property Platform::String^ DeviceSelector
00038         {
00039             Platform::String^ get(void)
00040             {
00041                 return deviceSelector;
00042             }
00043         }
00044
00045         DeviceListEntry(Windows::Devices::Enumeration::DeviceInformation^ deviceInformation, Platform::String^ deviceSelector);
00046
00047     private:
00048         Windows::Devices::Enumeration::DeviceInformation^ device;
00049         Platform::String^ deviceSelector;
00050     };
00051 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlLite/cppwinrt/Scenario3_XmlWriterLite.cpp Source File

  • XmlLite
  • cppwinrt

Scenario3_XmlWriterLite.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_XmlWriterLite.h"
00014 #include "Scenario3_XmlWriterLite.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Storage;
00021 using namespace Windows::Storage::Streams;
00022 using namespace Windows::UI::Xaml;
00023
00024 namespace winrt::SDKTemplate::implementation
00025 {
00026     Scenario3_XmlWriterLite::Scenario3_XmlWriterLite()
00027     {
00028         InitializeComponent();
00029     }
00030
00031     fire_and_forget Scenario3_XmlWriterLite::DoSomething_Click(IInspectable const&, RoutedEventArgs const&)
00032     {
00033         auto lifetime = get_strong();
00034
00035         hstring result;
00036         try
00037         {
00038             StorageFolder installFolder = Package::Current().InstalledLocation();
00039             StorageFile inputFile = co_await installFolder.GetFileAsync(L"Stocks.xml");
00040             IRandomAccessStream randomAccessReadStream = co_await inputFile.OpenAsync(FileAccessMode::Read);
00041             com_ptr<IStream> readStream = capture<IStream>(::CreateStreamOverRandomAccessStream, winrt::get_unknown(randomAccessReadStream));
00042
00043             StorageFolder localFolder = ApplicationData::Current().LocalFolder();
00044             StorageFile outputFile = co_await localFolder.CreateFileAsync(L"XmlWriterLiteOutput.xml", CreationCollisionOption::ReplaceExisting);
00045             IRandomAccessStream randomAccessWriteStream = co_await outputFile.OpenAsync(FileAccessMode::ReadWrite);
00046             com_ptr<IStream> writeStream = capture<IStream>(::CreateStreamOverRandomAccessStream, winrt::get_unknown(randomAccessWriteStream));
00047
00048             ReadAndWrite(readStream, writeStream);
00049
00050             result = L"File is written to " + outputFile.Path() + L" successfully";
00051         }
00052         catch (hresult_error const& e)
00053         {
00054             result = L"Exception occured while writing the xml file: " + e.message() +
00055                 L"\nError code: " + to_hstring(e.code());
00056         }
00057         OutputTextBlock1().Text(result);
00058     }
00059
00060     void Scenario3_XmlWriterLite::ReadAndWrite(com_ptr<IStream> const& readStream, com_ptr<IStream> const& writeStream)
00061     {
00062         com_ptr<IXmlReader> reader;
00063         check_hresult(::CreateXmlReader(IID_PPV_ARGS(&reader), nullptr));
00064         check_hresult(reader->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit));
00065         check_hresult(reader->SetInput(readStream.get()));
00066
00067         com_ptr<IXmlWriterLite> writer;
00068         check_hresult(::CreateXmlWriter(IID_PPV_ARGS(&writer), nullptr));
00069         check_hresult(writer->SetOutput(writeStream.get()));
00070
00071         XmlNodeType nodeType;
00072
00073         while (check_enumerator(reader->Read(&nodeType)))
00074         {
00075             PCWSTR     qualifiedName = nullptr;
00076             PCWSTR     value = nullptr;
00077             UINT       qualifiedNameSize = 0;
00078             UINT       valueSize = 0;
00079
00080             switch (nodeType)
00081             {
00082             case XmlNodeType_Element:
00083             {
00084                 check_hresult(reader->GetQualifiedName(&qualifiedName, &qualifiedNameSize));
00085                 check_hresult(writer->WriteStartElement(qualifiedName, qualifiedNameSize));
00086                 while (check_enumerator(reader->MoveToNextAttribute()))
00087                 {
00088                     check_hresult(reader->GetQualifiedName(&qualifiedName, &qualifiedNameSize));
00089                     check_hresult(reader->GetValue(&value, &valueSize));
00090                     check_hresult(writer->WriteAttributeString(qualifiedName, qualifiedNameSize, value, valueSize));
00091                 }
00092                 check_hresult(reader->MoveToElement());
00093                 if (reader->IsEmptyElement())
00094                 {
00095                     check_hresult(reader->GetQualifiedName(&qualifiedName, &qualifiedNameSize));
00096                     check_hresult(writer->WriteEndElement(qualifiedName, qualifiedNameSize));
00097                 }
00098                 break;
00099             }
00100             case XmlNodeType_Text:
00101                 check_hresult(reader->GetValue(&value, nullptr));
00102                 check_hresult(writer->WriteString(value));
00103                 break;
00104
00105             case XmlNodeType_CDATA:
00106                 check_hresult(reader->GetValue(&value, nullptr));
00107                 check_hresult(writer->WriteCData(value));
00108                 break;
00109
00110             case XmlNodeType_ProcessingInstruction:
00111                 check_hresult(reader->GetQualifiedName(&qualifiedName, nullptr));
00112                 check_hresult(reader->GetValue(&value, nullptr));
00113                 check_hresult(writer->WriteProcessingInstruction(qualifiedName, value));
00114                 break;
00115
00116             case XmlNodeType_Comment:
00117                 check_hresult(reader->GetValue(&value, nullptr));
00118                 check_hresult(writer->WriteComment(value));
00119                 break;
00120
00121             case XmlNodeType_DocumentType:
00122             {
00123                 PCWSTR publicId = nullptr;
00124                 PCWSTR systemId = nullptr;
00125
00126                 check_hresult(reader->GetQualifiedName(&qualifiedName, nullptr));
00127                 check_hresult(reader->GetValue(&value, nullptr));
00128                 if (check_enumerator(reader->MoveToAttributeByName(L"PUBLIC", nullptr)))
00129                 {
00130                     reader->GetValue(&publicId, nullptr);
00131                 }
00132                 if (check_enumerator(reader->MoveToAttributeByName(L"SYSTEM", nullptr)))
00133                 {
00134                     check_hresult(reader->GetValue(&systemId, nullptr));
00135                 }
00136                 check_hresult(writer->WriteDocType(
00137                     qualifiedName,
00138                     publicId,
00139                     systemId,
00140                     value));
00141                 break;
00142             }
00143             case XmlNodeType_Whitespace:
00144                 check_hresult(reader->GetValue(&value, nullptr));
00145                 check_hresult(writer->WriteWhitespace(value));
00146                 break;
00147
00148             case XmlNodeType_EndElement:
00149                 check_hresult(reader->GetQualifiedName(&qualifiedName, &qualifiedNameSize));
00150                 check_hresult(writer->WriteFullEndElement(qualifiedName, qualifiedNameSize));
00151                 break;
00152
00153             default:
00154                 break;
00155             }
00156         }
00157     }
00158 }
Generated on Fri Nov 15 2024 22:22:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSensors/cpp/Scenario1_DataEvents.xaml.h Source File

  • CustomSensors
  • cpp

Scenario1_DataEvents.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario1_DataEvents.xaml.h
00013 // Declaration of the Scenario1_DataEvents class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario1_DataEvents.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     [Windows::Foundation::Metadata::WebHostHidden]
00028     public ref class Scenario1_DataEvents sealed
00029     {
00030     public:
00031         Scenario1_DataEvents();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036
00037     private:
00038         SDKTemplate::MainPage^ m_RootPage;
00039         Windows::Devices::Enumeration::DeviceWatcher^ m_Watcher;
00040         Windows::Devices::Sensors::Custom::CustomSensor^ m_CustomSensor;
00041         Windows::Foundation::EventRegistrationToken m_VisibilityToken;
00042         Windows::Foundation::EventRegistrationToken m_ReadingToken;
00043         uint32 m_DesiredReportInterval;
00044         Microsoft::WRL::Wrappers::CriticalSection m_CritsecCustomSensor;
00045         Windows::Devices::Enumeration::DeviceAccessInformation^ m_DeviceAccessInfo;
00046
00047         void OnVisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00048         void OnReadingChanged(Windows::Devices::Sensors::Custom::CustomSensor^ sender, Windows::Devices::Sensors::Custom::CustomSensorReadingChangedEventArgs^ e);
00049         void ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050         void ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00051         void OnCustomSensorAdded(Windows::Devices::Enumeration::DeviceWatcher^ watcher, Windows::Devices::Enumeration::DeviceInformation^ firstDevice);
00052         void OnAccessChanged(Windows::Devices::Enumeration::DeviceAccessInformation ^sender, Windows::Devices::Enumeration::DeviceAccessChangedEventArgs ^args);
00053         void StartWatcher();
00054     };
00055 }
Generated on Fri Nov 15 2024 22:17:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_GetCurrentTextSegmentFromIndex Member List

This is the complete list of members for Scenario2_GetCurrentTextSegmentFromIndex, including all inherited members.
Scenario2_GetCurrentTextSegmentFromIndex() | Scenario2_GetCurrentTextSegmentFromIndex
SelectionSegmentButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_GetCurrentTextSegmentFromIndex
WordSegmentButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_GetCurrentTextSegmentFromIndex
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LoggingSessionScenario::BusySetter Member List

This is the complete list of members for LoggingSessionScenario::BusySetter, including all inherited members.
_scenario | LoggingSessionScenario::BusySetter |
BusySetter(LoggingSessionScenario &scenario) | LoggingSessionScenario::BusySetter | [explicit]
~BusySetter() | LoggingSessionScenario::BusySetter |
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cpp/Scenario3_Polling.xaml.cpp Source File

  • Accelerometer
  • cpp

Scenario3_Polling.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario3_Polling.xaml.cpp
00014 // Implementation of the Scenario3_Polling class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario3_Polling.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Windows::Devices::Sensors;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::UI::Core;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 Scenario3_Polling::Scenario3_Polling()
00031 {
00032     InitializeComponent();
00033 }
00034 void Scenario3_Polling::OnNavigatedTo(NavigationEventArgs^ e)
00035 {
00036     accelerometer = Accelerometer::GetDefault(rootPage->AccelerometerReadingType);
00037     if (accelerometer != nullptr)
00038     {
00039         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00040         // This value will be used later to activate the sensor.
00041         desiredReportInterval = (std::max)(accelerometer->MinimumReportInterval, 16U);
00042
00043         // Set up a DispatchTimer
00044         TimeSpan span;
00045         span.Duration = static_cast<int32>(desiredReportInterval) * 10000;   // convert to 100ns ticks
00046         dispatcherTimer = ref new DispatcherTimer();
00047         dispatcherTimer->Interval = span;
00048         dispatcherTimer->Tick += ref new Windows::Foundation::EventHandler<Object^>(this, &Scenario3_Polling::DisplayCurrentReading);
00049
00050         rootPage->NotifyUser(rootPage->AccelerometerReadingType.ToString() + " accelerometer ready", NotifyType::StatusMessage);
00051         ScenarioEnableButton->IsEnabled = true;
00052     }
00053     else
00054     {
00055         rootPage->NotifyUser(rootPage->AccelerometerReadingType.ToString() + " accelerometer not found", NotifyType::ErrorMessage);
00056     }
00057 }
00058
00059 void Scenario3_Polling::OnNavigatedFrom(NavigationEventArgs^ e)
00060 {
00061     if (ScenarioDisableButton->IsEnabled)
00062     {
00063         ScenarioDisable();
00064     }
00065 }
00066
00067 /// <summary>
00068 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00069 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00070 /// </summary>
00071 /// <param name="sender"></param>
00072 /// <param name="e">
00073 /// Event data that can be examined for the current visibility state.
00074 /// </param>
00075 void Scenario3_Polling::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00076 {
00077     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00078     if (ScenarioDisableButton->IsEnabled)
00079     {
00080         if (e->Visible)
00081         {
00082             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00083             dispatcherTimer->Start();
00084         }
00085         else
00086         {
00087             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00088             dispatcherTimer->Stop();
00089         }
00090     }
00091 }
00092
00093 void Scenario3_Polling::DisplayCurrentReading(Object^ sender, Object^ e)
00094 {
00095     AccelerometerReading^ reading = accelerometer->GetCurrentReading();
00096     if (reading != nullptr)
00097     {
00098         MainPage::SetReadingText(ScenarioOutput, reading);
00099     }
00100 }
00101
00102 void Scenario3_Polling::ScenarioEnable()
00103 {
00104     visibilityToken = Window::Current->VisibilityChanged += ref new WindowVisibilityChangedEventHandler(this, &Scenario3_Polling::VisibilityChanged);
00105
00106     // Set the report interval to enable the sensor for polling
00107     accelerometer->ReportInterval = desiredReportInterval;
00108
00109     dispatcherTimer->Start();
00110
00111     ScenarioEnableButton->IsEnabled = false;
00112     ScenarioDisableButton->IsEnabled = true;
00113 }
00114
00115 void Scenario3_Polling::ScenarioDisable()
00116 {
00117     Window::Current->VisibilityChanged -= visibilityToken;
00118
00119     dispatcherTimer->Stop();
00120
00121     // Restore the default report interval to release resources while the sensor is not in use
00122     accelerometer->ReportInterval = 0;
00123
00124     ScenarioEnableButton->IsEnabled = true;
00125     ScenarioDisableButton->IsEnabled = false;
00126 }
Generated on Fri Nov 15 2024 22:17:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/HttpJsonContent.h Source File

  • HttpClient
  • cppwinrt

HttpJsonContent.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "HttpJsonContent.g.h"
00014
00015 namespace winrt::SDKTemplate::implementation
00016 {
00017     struct HttpJsonContent : HttpJsonContentT<HttpJsonContent>
00018     {
00019         HttpJsonContent(Windows::Data::Json::IJsonValue const& jsonValue);
00020         Windows::Web::Http::Headers::HttpContentHeaderCollection Headers() { return m_headers; }
00021         Windows::Foundation::IAsyncOperationWithProgress<uint64_t, uint64_t> BufferAllAsync();
00022         Windows::Foundation::IAsyncOperationWithProgress<Windows::Storage::Streams::IBuffer, uint64_t> ReadAsBufferAsync();
00023         Windows::Foundation::IAsyncOperationWithProgress<Windows::Storage::Streams::IInputStream, uint64_t> ReadAsInputStreamAsync();
00024         Windows::Foundation::IAsyncOperationWithProgress<hstring, uint64_t> ReadAsStringAsync();
00025         bool TryComputeLength(uint64_t& length);
00026         Windows::Foundation::IAsyncOperationWithProgress<uint64_t, uint64_t> WriteToStreamAsync(Windows::Storage::Streams::IOutputStream outputStream);
00027         void Close() {}
00028
00029     private:
00030         Windows::Data::Json::IJsonValue const m_jsonValue;
00031         Windows::Web::Http::Headers::HttpContentHeaderCollection const m_headers;
00032
00033         Windows::Storage::Streams::IBuffer ToBuffer();
00034         uint64_t GetLength();
00035     };
00036 }
00037 namespace winrt::SDKTemplate::factory_implementation
00038 {
00039     struct HttpJsonContent : HttpJsonContentT<HttpJsonContent, implementation::HttpJsonContent>
00040     {
00041     };
00042 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BindingHelpers Member List

This is the complete list of members for BindingHelpers, including all inherited members.
CollapsedIf(bool value) | BindingHelpers | [static]
Not(bool value) | BindingHelpers | [static]
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cs/Scenario5_LaunchedFromSecondaryTile.xaml.cs Source File

  • SecondaryTiles
  • cs

Scenario5_LaunchedFromSecondaryTile.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using Windows.UI.Xaml.Controls;
00013
00014 namespace SDKTemplate
00015 {
00016     public sealed partial class Scenario5_LaunchedFromSecondaryTile : Page
00017     {
00018         MainPage rootPage = MainPage.Current;
00019
00020         public Scenario5_LaunchedFromSecondaryTile()
00021         {
00022             this.InitializeComponent();
00023
00024             if (!String.IsNullOrEmpty(rootPage.LaunchParam))
00025             {
00026                 rootPage.NotifyUser("Application was activated from a Secondary Tile with the following Activation Arguments: " + MainPage.Current.LaunchParam, NotifyType.StatusMessage);
00027                 rootPage.LaunchParam = null;
00028             }
00029         }
00030     }
00031 }
00032
Generated on Fri Nov 15 2024 22:21:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/WASAPICapture.cpp Source File

  • WindowsAudioSession
  • cppwinrt

WASAPICapture.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
00012 #include "WASAPICapture.h"
00013
00014 using namespace winrt::Windows::Foundation;
00015 using namespace winrt::Windows::Media::Devices;
00016 using namespace winrt::Windows::Storage;
00017 using namespace winrt::Windows::Storage::Streams;
00018
00019 using namespace std::literals;
00020
00021 namespace winrt::SDKTemplate
00022 {
00023     static constexpr uint32_t BITS_PER_BYTE = 8;
00024     static constexpr TimeSpan FLUSH_INTERVAL = 3s;
00025     static constexpr TimeSpan DURATION_TO_VISUALIZE = 20ms;
00026     static constexpr wchar_t AUDIO_FILE_NAME[] = L"WASAPIAudioCapture.wav";
00027
00028     WASAPICapture::WASAPICapture()
00029     {
00030         // Set the capture event work queue to use the MMCSS queue
00031         m_SampleReadyCallback.SetQueueID(m_queueId.get());
00032     }
00033
00034     //
00035     //  InitializeAudioDeviceAsync()
00036     //
00037     //  Activates the default audio capture on a asynchronous callback thread.  This needs
00038     //  to be called from the main UI thread.
00039     //
00040     void WASAPICapture::AsyncInitializeAudioDevice() noexcept try
00041     {
00042         com_ptr<IActivateAudioInterfaceAsyncOperation> asyncOp;
00043
00044         // Get a string representing the Default Audio Capture Device
00045         hstring deviceIdString = MediaDevice::GetDefaultAudioCaptureId(AudioDeviceRole::Default);
00046
00047         // This call must be made on the main UI thread.  Async operation will call back to
00048         // IActivateAudioInterfaceCompletionHandler::ActivateCompleted, which must be an agile interface implementation
00049         check_hresult(ActivateAudioInterfaceAsync(deviceIdString.c_str(), __uuidof(IAudioClient3), nullptr, this, asyncOp.put()));
00050     }
00051     catch (...)
00052     {
00053         SetState(DeviceState::Error, to_hresult());
00054     }
00055
00056     //
00057     //  ActivateCompleted()
00058     //
00059     //  Callback implementation of ActivateAudioInterfaceAsync function.  This will be called on MTA thread
00060     //  when results of the activation are available.
00061     //
00062     HRESULT WASAPICapture::ActivateCompleted(IActivateAudioInterfaceAsyncOperation* operation) try
00063     {
00064         HRESULT status = S_OK;
00065         com_ptr<::IUnknown> punkAudioInterface;
00066
00067         // Check for a successful activation result
00068         check_hresult(operation->GetActivateResult(&status, punkAudioInterface.put()));
00069         check_hresult(status);
00070
00071         // Get the pointer for the Audio Client
00072         m_audioClient = punkAudioInterface.as<IAudioClient3>();
00073
00074         check_hresult(m_audioClient->GetMixFormat(m_mixFormat.put()));
00075
00076         // convert from Float to 16-bit PCM
00077         switch (m_mixFormat->wFormatTag)
00078         {
00079         case WAVE_FORMAT_PCM:
00080             // nothing to do
00081             break;
00082
00083         case WAVE_FORMAT_IEEE_FLOAT:
00084             m_mixFormat->wFormatTag = WAVE_FORMAT_PCM;
00085             m_mixFormat->wBitsPerSample = 16;
00086             m_mixFormat->nBlockAlign = m_mixFormat->nChannels * m_mixFormat->wBitsPerSample / BITS_PER_BYTE;
00087             m_mixFormat->nAvgBytesPerSec = m_mixFormat->nSamplesPerSec * m_mixFormat->nBlockAlign;
00088             break;
00089
00090         case WAVE_FORMAT_EXTENSIBLE:
00091         {
00092             WAVEFORMATEXTENSIBLE* pWaveFormatExtensible = reinterpret_cast<WAVEFORMATEXTENSIBLE*>(m_mixFormat.get());
00093             if (pWaveFormatExtensible->SubFormat == KSDATAFORMAT_SUBTYPE_PCM)
00094             {
00095                 // nothing to do
00096             }
00097             else if (pWaveFormatExtensible->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)
00098             {
00099                 pWaveFormatExtensible->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
00100                 pWaveFormatExtensible->Format.wBitsPerSample = 16;
00101                 pWaveFormatExtensible->Format.nBlockAlign =
00102                     pWaveFormatExtensible->Format.nChannels *
00103                     pWaveFormatExtensible->Format.wBitsPerSample /
00104                     BITS_PER_BYTE;
00105                 pWaveFormatExtensible->Format.nAvgBytesPerSec =
00106                     pWaveFormatExtensible->Format.nSamplesPerSec *
00107                     pWaveFormatExtensible->Format.nBlockAlign;
00108                 pWaveFormatExtensible->Samples.wValidBitsPerSample =
00109                     pWaveFormatExtensible->Format.wBitsPerSample;
00110
00111                 // leave the channel mask as-is
00112             }
00113             else
00114             {
00115                 // we can only handle float or PCM
00116                 throw hresult_error(HRESULT_FROM_WIN32(ERROR_NOT_FOUND));
00117             }
00118             break;
00119         }
00120
00121         default:
00122             // we can only handle float or PCM
00123             throw hresult_error(HRESULT_FROM_WIN32(ERROR_NOT_FOUND));
00124             break;
00125         }
00126
00127         // The wfx parameter below is optional (Its needed only for MATCH_FORMAT clients). Otherwise, wfx will be assumed
00128         // to be the current engine format based on the processing mode for this stream
00129         check_hresult(m_audioClient->GetSharedModeEnginePeriod(m_mixFormat.get(), &m_defaultPeriodInFrames, &m_fundamentalPeriodInFrames, &m_minPeriodInFrames, &m_maxPeriodInFrames));
00130
00131         // Initialize the AudioClient in Shared Mode with the user specified buffer
00132         if (!m_isLowLatency)
00133         {
00134             check_hresult(m_audioClient->Initialize(AUDCLNT_SHAREMODE_SHARED,
00135                 AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
00136                 TimeSpan{ 20ms }.count(), // hnsBufferDuration
00137                 0,
00138                 m_mixFormat.get(),
00139                 nullptr));
00140         }
00141         else
00142         {
00143             check_hresult(m_audioClient->InitializeSharedAudioStream(
00144                 AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
00145                 m_minPeriodInFrames,
00146                 m_mixFormat.get(),
00147                 nullptr));
00148         }
00149
00150         // Get the maximum size of the AudioClient Buffer
00151         check_hresult(m_audioClient->GetBufferSize(&m_bufferFrames));
00152
00153         // Get the capture client
00154         m_audioCaptureClient.capture(m_audioClient, &IAudioClient::GetService);
00155
00156         // Create Async callback for sample events
00157         check_hresult(MFCreateAsyncResult(nullptr, &m_SampleReadyCallback, nullptr, m_sampleReadyAsyncResult.put()));
00158
00159         // Provides the event handle for the system to signal when an audio buffer is ready to be processed by the client
00160         check_hresult(m_audioClient->SetEventHandle(m_SampleReadyEvent.get()));
00161
00162         // Create the visualization array
00163         InitializeScopeData();
00164
00165         // Creates the WAV file asynchronously.  If successful, will transition to DeviceState::Initialized
00166         CreateWAVFile();
00167
00168         // Need to return S_OK
00169         return S_OK;
00170     }
00171     catch (...)
00172     {
00173         SetState(DeviceState::Error, to_hresult());
00174         m_audioClient = nullptr;
00175         m_audioCaptureClient = nullptr;
00176         m_sampleReadyAsyncResult = nullptr;
00177
00178         // Must return S_OK even on failure.
00179         return S_OK;
00180     }
00181
00182     //
00183     //  CreateWAVFile()
00184     //
00185     //  Creates a WAV file in KnownFolders::MusicLibrary
00186     //
00187     fire_and_forget WASAPICapture::CreateWAVFile() try
00188     {
00189         auto lifetime = get_strong();
00190
00191         // Create the WAV file, appending a number if file already exists
00192         StorageFile file = co_await KnownFolders::MusicLibrary().CreateFileAsync(AUDIO_FILE_NAME, CreationCollisionOption::GenerateUniqueName);
00193
00194         // Then create a RandomAccessStream
00195         IRandomAccessStream stream = co_await file.OpenAsync(FileAccessMode::ReadWrite);
00196
00197         // Get the OutputStream for the file
00198         m_contentStream = stream;
00199         m_outputStream = stream.GetOutputStreamAt(0);
00200
00201         // Create the DataWriter
00202         m_dataWriter = DataWriter(m_outputStream);
00203
00204         // Create the WAV header
00205         DWORD formatSize = sizeof(WAVEFORMATEX) + m_mixFormat->cbSize; // Size of fmt chunk
00206         DWORD header[] = {
00207             FCC('RIFF'),        // RIFF header
00208             0,                  // Total size of WAV (will be filled in later)
00209             FCC('WAVE'),        // WAVE FourCC
00210             FCC('fmt '),        // Start of 'fmt ' chunk
00211             formatSize          // Size of fmt chunk
00212         };
00213
00214         DWORD data[] = { FCC('data'), 0 };  // Start of 'data' chunk (total size will be filled in later)
00215
00216         // Write the header
00217         m_dataWriter.WriteBytes({ reinterpret_cast<uint8_t*>(header), sizeof(header) });
00218         m_dataWriter.WriteBytes({ reinterpret_cast<uint8_t*>(m_mixFormat.get()), formatSize });
00219         m_dataWriter.WriteBytes({ reinterpret_cast<uint8_t*>(data), sizeof(data) });
00220
00221         m_headerSize = co_await m_dataWriter.StoreAsync();
00222         m_dataSize = 0;
00223         m_bytesSinceLastFlush = 0;
00224
00225         // Wait for file data to be written to file
00226         co_await m_dataWriter.FlushAsync();
00227
00228         SetState(DeviceState::Initialized);
00229     }
00230     catch (...)
00231     {
00232         SetState(DeviceState::Error, to_hresult());
00233     }
00234
00235     //
00236     //  FixWAVHeader()
00237     //
00238     //  The size values were not known when we originally wrote the header, so now go through and fix the values
00239     //
00240     fire_and_forget WASAPICapture::FixWAVHeader() try
00241     {
00242         auto lifetime = get_strong();
00243
00244         // Prepare a buffer to write DWORDs into the stream header.
00245         Buffer dwordBuffer(sizeof(DWORD));
00246         dwordBuffer.Length(sizeof(DWORD));
00247         auto dwordBufferPtr = reinterpret_cast<DWORD*>(dwordBuffer.data());
00248
00249         IRandomAccessStream stream = m_contentStream.CloneStream();
00250
00251         // Write the size of the 'data' chunk first
00252         stream.Seek(m_headerSize - sizeof(DWORD));
00253         *dwordBufferPtr = m_dataSize;
00254         co_await stream.WriteAsync(dwordBuffer);
00255
00256         // Write the total file size, minus RIFF chunk and size
00257         stream.Seek(sizeof(DWORD)); // sizeof(DWORD) == sizeof(FOURCC)
00258         *dwordBufferPtr = m_dataSize + m_headerSize - 8; // 8 = RIFF chunk and size
00259         co_await stream.WriteAsync(dwordBuffer);
00260
00261         co_await stream.FlushAsync();
00262         stream.Close();
00263
00264         SetState(DeviceState::Stopped);
00265     }
00266     catch (...)
00267     {
00268         SetState(DeviceState::Error, to_hresult());
00269     }
00270
00271     //
00272     //  InitializeScopeData()
00273     //
00274     //  Setup data structures for sample visualizations
00275     //
00276     void WASAPICapture::InitializeScopeData()
00277     {
00278         // Only Support 16 bit Audio for now
00279         if (m_mixFormat->wBitsPerSample != 16)
00280         {
00281             m_plotDataBuffer = nullptr;
00282             return;
00283         }
00284
00285         m_plotDataPointsFilled = 0;
00286         m_plotDataMaxPoints = static_cast<uint32_t>(DURATION_TO_VISUALIZE * m_mixFormat->nSamplesPerSec / 1s);
00287         m_plotDataBuffer = Buffer(m_plotDataMaxPoints * sizeof(int16_t));
00288     }
00289
00290     //
00291     //  AsyncStartCapture()
00292     //
00293     //  Starts asynchronous capture on a separate thread via MF Work Item
00294     //
00295     void WASAPICapture::AsyncStartCapture()
00296     {
00297         // We should be in the initialzied state if this is the first time through getting ready to capture.
00298         if (m_deviceState == DeviceState::Initialized)
00299         {
00300             SetState(DeviceState::Starting);
00301             MFPutWorkItem2(MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_StartCaptureCallback, nullptr);
00302         }
00303     }
00304
00305     //
00306     //  OnStartCapture()
00307     //
00308     //  Callback method to start capture
00309     //
00310     HRESULT WASAPICapture::OnStartCapture(IMFAsyncResult*) try
00311     {
00312         // Start the capture
00313         check_hresult(m_audioClient->Start());
00314         check_hresult(MFPutWaitingWorkItem(m_SampleReadyEvent.get(), 0, m_sampleReadyAsyncResult.get(), &m_sampleReadyKey));
00315         SetState(DeviceState::Capturing);
00316
00317         return S_OK;
00318     }
00319     catch (...)
00320     {
00321         SetState(DeviceState::Error, to_hresult());
00322         // Must return S_OK.
00323         return S_OK;
00324     }
00325
00326     //
00327     //  AsyncStopCapture()
00328     //
00329     //  Stop capture asynchronously via MF Work Item
00330     //
00331     void WASAPICapture::AsyncStopCapture()
00332     {
00333         if ((m_deviceState == DeviceState::Capturing) ||
00334             (m_deviceState == DeviceState::Error))
00335         {
00336             SetState(DeviceState::Stopping);
00337
00338             MFPutWorkItem2(MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_StopCaptureCallback, nullptr);
00339         }
00340     }
00341
00342     //
00343     //  OnStopCapture()
00344     //
00345     //  Callback method to stop capture
00346     //
00347     HRESULT WASAPICapture::OnStopCapture(IMFAsyncResult*) try
00348     {
00349         // Stop capture by cancelling Work Item
00350         // Cancel the queued work item (if any)
00351         if (0 != m_sampleReadyKey)
00352         {
00353             MFCancelWorkItem(std::exchange(m_sampleReadyKey, 0));
00354         }
00355
00356         m_sampleReadyAsyncResult = nullptr;
00357         if (m_audioClient)
00358         {
00359             m_audioClient->Stop();
00360
00361             if (m_writing)
00362             {
00363                 // A StoreAsync is already in progress. Let that one complete and finish the capture.
00364             }
00365             else
00366             {
00367                 SetState(DeviceState::Flushing);
00368                 AsyncStoreData();
00369             }
00370         }
00371         return S_OK;
00372     }
00373     catch (...) { return to_hresult(); }
00374
00375     //
00376     //  AsyncFinishCapture()
00377     //
00378     //  Finalizes WAV file on a separate thread via MF Work Item
00379     //
00380     fire_and_forget WASAPICapture::AsyncStoreData()
00381     {
00382         auto lifetime = get_strong();
00383
00384         co_await m_dataWriter.StoreAsync();
00385         m_writing = false;
00386
00387         if (m_deviceState == DeviceState::Stopping)
00388         {
00389             // A Stop request is pending. Transition to Flushing to write out the WAV header.
00390             SetState(DeviceState::Flushing);
00391         }
00392
00393         if (m_deviceState == DeviceState::Flushing)
00394         {
00395             check_hresult(MFPutWorkItem2(MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_FinishCaptureCallback, nullptr));
00396         }
00397     }
00398
00399     //
00400     //  OnFinishCapture()
00401     //
00402     //  Because of the asynchronous nature of the MF Work Queues and the DataWriter, there could still be
00403     //  a sample processing.  So this will get called to finalize the WAV header.
00404     //
00405     HRESULT WASAPICapture::OnFinishCapture(IMFAsyncResult*)
00406     {
00407         // FixWAVHeader will set the DeviceState::Stopped when all async tasks are complete
00408         FixWAVHeader();
00409         return S_OK;
00410     }
00411
00412     //
00413     //  OnSampleReady()
00414     //
00415     //  Callback method when ready to fill sample buffer
00416     //
00417     HRESULT WASAPICapture::OnSampleReady(IMFAsyncResult*) try
00418     {
00419         OnAudioSampleRequested();
00420
00421         // Re-queue work item for next sample
00422         if (m_deviceState == DeviceState::Capturing)
00423         {
00424             check_hresult(MFPutWaitingWorkItem(m_SampleReadyEvent.get(), 0, m_sampleReadyAsyncResult.get(), &m_sampleReadyKey));
00425         }
00426
00427         return S_OK;
00428     }
00429     catch (...)
00430     {
00431         hresult error = to_hresult();
00432         SetState(DeviceState::Error, error);
00433         return error;
00434     }
00435
00436     //
00437     //  OnAudioSampleRequested()
00438     //
00439     //  Called when audio device fires m_SampleReadyEvent
00440     //
00441     void WASAPICapture::OnAudioSampleRequested()
00442     {
00443         auto guard = slim_lock_guard(m_lock);
00444
00445         // If this flag is set, we have already queued up the async call to finialize the WAV header
00446         // So we don't want to grab or write any more data that would possibly give us an invalid size
00447         if ((m_deviceState == DeviceState::Stopping) ||
00448             (m_deviceState == DeviceState::Flushing))
00449         {
00450             return;
00451         }
00452
00453         // A word on why we have a loop here:
00454         // Suppose it has been 10 milliseconds or so since the last time
00455         // this routine was invoked, and that we're capturing 48000 samples per second.
00456         //
00457         // The audio engine can be reasonably expected to have accumulated about that much
00458         // audio data - that is, about 480 samples.
00459         //
00460         // However, the audio engine is free to accumulate this in various ways:
00461         // a. as a single packet of 480 samples, OR
00462         // b. as a packet of 80 samples plus a packet of 400 samples, OR
00463         // c. as 48 packets of 10 samples each.
00464         //
00465         // In particular, there is no guarantee that this routine will be
00466         // run once for each packet.
00467         //
00468         // So every time this routine runs, we need to read ALL the packets
00469         // that are now available;
00470         //
00471         // We do this by calling IAudioCaptureClient::GetNextPacketSize
00472         // over and over again until it indicates there are no more packets remaining.
00473         uint32_t framesAvailable = 0;
00474         while (SUCCEEDED(m_audioCaptureClient->GetNextPacketSize(&framesAvailable)) && framesAvailable > 0)
00475         {
00476             DWORD bytesToCapture = framesAvailable * m_mixFormat->nBlockAlign;
00477
00478             // WAV files have a 4GB (0xFFFFFFFF) size limit, so likely we have hit that limit when we
00479             // overflow here.  Time to stop the capture
00480             if ((m_dataSize + bytesToCapture) < m_dataSize)
00481             {
00482                 AsyncStopCapture();
00483                 return;
00484             }
00485
00486             { // Scope for GetBuffer / ReleaseBuffer variables.
00487                 uint8_t* data = nullptr;
00488                 DWORD dwCaptureFlags;
00489                 uint64_t devicePosition = 0;
00490                 uint64_t qpcPosition = 0;
00491
00492                 // Get sample buffer
00493                 check_hresult(m_audioCaptureClient->GetBuffer(&data, &framesAvailable, &dwCaptureFlags, &devicePosition, &qpcPosition));
00494
00495                 // Ensure that the buffer is released at scope exit, even if an exception occurs.
00496                 auto release = scope_exit([&] { m_audioCaptureClient->ReleaseBuffer(framesAvailable); });
00497
00498                 if (dwCaptureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY)
00499                 {
00500                     // Pass down a discontinuity flag in case the app is interested and reset back to capturing
00501                     SetState(DeviceState::Discontinuity);
00502                     SetStateNoNotify(DeviceState::Capturing);
00503                 }
00504
00505                 // Zero out sample if silence
00506                 if (dwCaptureFlags & AUDCLNT_BUFFERFLAGS_SILENT)
00507                 {
00508                     memset(data, 0, framesAvailable * m_mixFormat->nBlockAlign);
00509                 }
00510
00511                 // Update plotter data
00512                 array_view<uint8_t> dataBytes{ data, bytesToCapture };
00513                 ProcessScopeData(dataBytes);
00514
00515                 // Write File and async store
00516                 m_dataWriter.WriteBytes(dataBytes);
00517
00518                 // End of scope: Buffer is released back, and GetBuffer variables are no longer valid
00519             }
00520
00521             // Increase the size of our 'data' chunk and bytes since last flush.  m_dataSize needs to be accurate but
00522             // m_bytesSinceLastFlush need only be an approximation.
00523             m_dataSize += bytesToCapture;
00524             m_bytesSinceLastFlush += bytesToCapture;
00525
00526             if ((m_bytesSinceLastFlush > (m_mixFormat->nAvgBytesPerSec * FLUSH_INTERVAL / 1s)) && !m_writing)
00527             {
00528                 // Set this flag when about to commit the async storage operation.  We don't want to
00529                 // accidently call stop and finalize the WAV header or run into a scenario where the
00530                 // store operation takes longer than FLUSH_INTERVAL as multiple concurrent calls
00531                 // to StoreAsync() can cause an exception
00532                 m_writing = true;
00533
00534                 // Reset the counter now since we can process more samples during the async callback
00535                 m_bytesSinceLastFlush = 0;
00536
00537                 // Save the data we just wrote to the output file.
00538                 AsyncStoreData();
00539             }
00540         }
00541     }
00542
00543     //
00544     //  ProcessScopeData()
00545     //
00546     //  Copies sample data to the buffer array and fires the event
00547     //
00548     void WASAPICapture::ProcessScopeData(array_view<uint8_t> rawBytes)
00549     {
00550         // There is no buffer if the data format is not one we support.
00551         // (For now, the only format we support is 16-bit audio.)
00552         if (m_plotDataBuffer == nullptr)
00553         {
00554             return;
00555         }
00556
00557         uint32_t pointCount = rawBytes.size() / m_mixFormat->nChannels / (m_mixFormat->wBitsPerSample / BITS_PER_BYTE);
00558
00559         auto plotData = reinterpret_cast<int16_t*>(m_plotDataBuffer.data());
00560
00561         // Read the 16-bit samples from channel 0
00562         int16_t* pi16 = reinterpret_cast<int16_t*>(rawBytes.data());
00563
00564         for (DWORD i = 0; m_plotDataPointsFilled < m_plotDataMaxPoints && i < pointCount; i++)
00565         {
00566             plotData[m_plotDataPointsFilled] = *pi16;
00567             pi16 += m_mixFormat->nChannels;
00568
00569             m_plotDataPointsFilled++;
00570         }
00571
00572         // Send off the event and get ready for the next set of samples
00573         if (m_plotDataPointsFilled == m_plotDataMaxPoints)
00574         {
00575             auto plotDataBuffer = std::exchange(m_plotDataBuffer, nullptr);
00576             m_plotDataPointsFilled = 0;
00577
00578             plotDataBuffer.Length(m_plotDataMaxPoints * sizeof(int16_t));
00579             MFPutWorkItem2(MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_SendScopeDataCallback, winrt::get_unknown(plotDataBuffer));
00580
00581             // Create a new buffer to hold the next set of points.
00582             m_plotDataBuffer = Buffer(sizeof(int16_t) * m_plotDataMaxPoints);
00583         }
00584     }
00585
00586     //
00587     //  OnSendScopeData()
00588     //
00589     //  Callback method to delivery data for client visualizations
00590     //
00591     HRESULT WASAPICapture::OnSendScopeData(IMFAsyncResult* pResult) try
00592     {
00593         com_ptr<::IUnknown> points;
00594         check_hresult(pResult->GetState(points.put()));
00595         ReportPlotDataReady(points.as<IBuffer>());
00596         return S_OK;
00597     }
00598     catch (...)
00599     {
00600         return S_OK;
00601     }
00602 }
Generated on Fri Nov 15 2024 22:22:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Server/stdafx.h Source File

  • CustomCapability
  • Service
  • Server

stdafx.h

Go to the documentation of this file.
00001 // stdafx.h : include file for standard system include files,
00002 // or project specific include files that are used frequently, but
00003 // are changed infrequently
00004 //
00005
00006 #pragma once
00007
00008 #include "targetver.h"
00009
00010 #include <stdio.h>
00011 #include <tchar.h>
00012
00013 #define NOMINMAX    // disable min and max macros in windows.h
00014
00015 extern bool ShutdownRequested;
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cs/Scenario5_DisplayingBarcodePreview.xaml.cs Source File

  • BarcodeScanner
  • cs

Scenario5_DisplayingBarcodePreview.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.ObjectModel;
00014 using System.ComponentModel;
00015 using System.Threading;
00016 using System.Threading.Tasks;
00017 using Windows.Devices.Enumeration;
00018 using Windows.Devices.PointOfService;
00019 using Windows.Graphics.Display;
00020 using Windows.Media.Capture;
00021 using Windows.System.Display;
00022 using Windows.UI.Core;
00023 using Windows.UI.Xaml;
00024 using Windows.UI.Xaml.Controls;
00025 using Windows.UI.Xaml.Navigation;
00026
00027 namespace SDKTemplate
00028 {
00029     public sealed partial class Scenario5_DisplayingBarcodePreview : Page, INotifyPropertyChanged
00030     {
00031         public bool IsScannerClaimed { get; set; } = false;
00032         public bool IsPreviewing { get; set; } = false;
00033         public bool ScannerSupportsPreview { get; set; } = false;
00034         public bool SoftwareTriggerStarted { get; set; } = false;
00035
00036         MainPage rootPage = MainPage.Current;
00037         ObservableCollection<BarcodeScannerInfo> barcodeScanners = new ObservableCollection<BarcodeScannerInfo>();
00038         BarcodeScanner selectedScanner = null;
00039         ClaimedBarcodeScanner claimedScanner = null;
00040         DeviceWatcher watcher;
00041
00042         static readonly Guid rotationGuid = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1");
00043
00044         DisplayRequest displayRequest = new DisplayRequest();
00045         MediaCapture mediaCapture;
00046
00047         bool isSelectionChanging = false;
00048         string pendingSelectionDeviceId = null;
00049         bool isStopPending = false;
00050
00051         public event PropertyChangedEventHandler PropertyChanged;
00052
00053         public Scenario5_DisplayingBarcodePreview()
00054         {
00055             this.InitializeComponent();
00056
00057             ScannerListSource.Source = barcodeScanners;
00058
00059             watcher = DeviceInformation.CreateWatcher(BarcodeScanner.GetDeviceSelector());
00060             watcher.Added += Watcher_Added;
00061             watcher.Removed += Watcher_Removed;
00062             watcher.Updated += Watcher_Updated;
00063             watcher.Start();
00064
00065             DataContext = this;
00066         }
00067
00068         private async void Watcher_Added(DeviceWatcher sender, DeviceInformation args)
00069         {
00070             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00071             {
00072                 barcodeScanners.Add(new BarcodeScannerInfo(args.Name, args.Id));
00073
00074                 // Select the first scanner by default.
00075                 if (barcodeScanners.Count == 1)
00076                 {
00077                     ScannerListBox.SelectedIndex = 0;
00078                 }
00079             });
00080         }
00081
00082         private void Watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
00083         {
00084             // We don't do anything here, but this event needs to be handled to enable realtime updates.
00085             // See https://aka.ms/devicewatcher_added.
00086         }
00087
00088         private void Watcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
00089         {
00090             // We don't do anything here, but this event needs to be handled to enable realtime updates.
00091             //See https://aka.ms/devicewatcher_added.
00092         }
00093
00094         protected async override void OnNavigatedFrom(NavigationEventArgs e)
00095         {
00096             watcher.Stop();
00097
00098             if (isSelectionChanging)
00099             {
00100                 // If selection is changing, then let it know to stop media capture
00101                 // when it's done.
00102                 isStopPending = true;
00103             }
00104             else
00105             {
00106                 // If selection is not changing, then it's safe to stop immediately.
00107                 await CloseScannerResourcesAsync();
00108             }
00109         }
00110
00111         /// <summary>
00112         /// Starts previewing the selected scanner's video feed and prevents the display from going to sleep.
00113         /// </summary>
00114         private async Task StartMediaCaptureAsync(string videoDeviceId)
00115         {
00116             mediaCapture = new MediaCapture();
00117
00118             // Register for a notification when something goes wrong
00119             mediaCapture.Failed += MediaCapture_Failed;
00120
00121             var settings = new MediaCaptureInitializationSettings
00122             {
00123                 VideoDeviceId = videoDeviceId,
00124                 StreamingCaptureMode = StreamingCaptureMode.Video,
00125                 SharingMode = MediaCaptureSharingMode.SharedReadOnly,
00126             };
00127
00128             // Initialize MediaCapture
00129             bool captureInitialized = false;
00130             try
00131             {
00132                 await mediaCapture.InitializeAsync(settings);
00133                 captureInitialized = true;
00134             }
00135             catch (UnauthorizedAccessException)
00136             {
00137                 rootPage.NotifyUser("The app was denied access to the camera", NotifyType.ErrorMessage);
00138             }
00139             catch (Exception e)
00140             {
00141                 rootPage.NotifyUser("Failed to initialize the camera: " + e.Message, NotifyType.ErrorMessage);
00142             }
00143
00144             if (captureInitialized)
00145             {
00146                 // Prevent the device from sleeping while the preview is running.
00147                 displayRequest.RequestActive();
00148
00149                 PreviewControl.Source = mediaCapture;
00150                 await mediaCapture.StartPreviewAsync();
00151                 await SetPreviewRotationAsync(DisplayInformation.GetForCurrentView().CurrentOrientation);
00152                 IsPreviewing = true;
00153                 RaisePropertyChanged(nameof(IsPreviewing));
00154             }
00155             else
00156             {
00157                 mediaCapture.Dispose();
00158                 mediaCapture = null;
00159             }
00160         }
00161
00162         /// <summary>
00163         /// Close the scanners and stop the preview.
00164         /// </summary>
00165         private async Task CloseScannerResourcesAsync()
00166         {
00167             claimedScanner?.Dispose();
00168             claimedScanner = null;
00169
00170             selectedScanner?.Dispose();
00171             selectedScanner = null;
00172
00173             SoftwareTriggerStarted = false;
00174             RaisePropertyChanged(nameof(SoftwareTriggerStarted));
00175
00176             if (IsPreviewing)
00177             {
00178                 if (mediaCapture != null)
00179                 {
00180                     await mediaCapture.StopPreviewAsync();
00181                     mediaCapture.Dispose();
00182                     mediaCapture = null;
00183                 }
00184
00185                 // Allow the display to go to sleep.
00186                 displayRequest.RequestRelease();
00187
00188                 IsPreviewing = false;
00189                 RaisePropertyChanged(nameof(IsPreviewing));
00190             }
00191         }
00192
00193         /// <summary>
00194         /// Set preview rotation and mirroring state to adjust for the orientation of the camera, and for embedded cameras, the rotation of the device.
00195         /// </summary>
00196         /// <param name="message"></param>
00197         /// <param name="type"></param>
00198         private async Task SetPreviewRotationAsync(DisplayOrientations displayOrientation)
00199         {
00200             bool isExternalCamera;
00201             bool isPreviewMirrored;
00202
00203             // Figure out where the camera is located to account for mirroring and later adjust rotation accordingly.
00204             DeviceInformation cameraInformation = await DeviceInformation.CreateFromIdAsync(selectedScanner.VideoDeviceId);
00205
00206             if ((cameraInformation.EnclosureLocation == null) || (cameraInformation.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown))
00207             {
00208                 isExternalCamera = true;
00209                 isPreviewMirrored = false;
00210             }
00211             else
00212             {
00213                 isExternalCamera = false;
00214                 isPreviewMirrored = (cameraInformation.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
00215             }
00216
00217             PreviewControl.FlowDirection = isPreviewMirrored ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
00218
00219             if (!isExternalCamera)
00220             {
00221                 // Calculate which way and how far to rotate the preview.
00222                 int rotationDegrees = 0;
00223                 switch (displayOrientation)
00224                 {
00225                     case DisplayOrientations.Portrait:
00226                         rotationDegrees = 90;
00227                         break;
00228                     case DisplayOrientations.LandscapeFlipped:
00229                         rotationDegrees = 180;
00230                         break;
00231                     case DisplayOrientations.PortraitFlipped:
00232                         rotationDegrees = 270;
00233                         break;
00234                     case DisplayOrientations.Landscape:
00235                     default:
00236                         rotationDegrees = 0;
00237                         break;
00238                 }
00239
00240                 // The rotation direction needs to be inverted if the preview is being mirrored.
00241                 if (isPreviewMirrored)
00242                 {
00243                     rotationDegrees = (360 - rotationDegrees) % 360;
00244                 }
00245
00246                 // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames.
00247                 var streamProperties = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
00248                 streamProperties.Properties[rotationGuid] = rotationDegrees;
00249                 await mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, streamProperties, null);
00250             }
00251         }
00252
00253         /// <summary>
00254         /// Media capture failed, potentially due to the camera being unplugged.
00255         /// </summary>
00256         /// <param name="sender"></param>
00257         /// <param name="errorEventArgs"></param>
00258         private void MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs)
00259         {
00260             rootPage.NotifyUser("Media capture failed. Make sure the camera is still connected.", NotifyType.ErrorMessage);
00261         }
00262
00263         /// <summary>
00264         /// Event Handler for Show Preview Button Click.
00265         /// Displays the preview window for the selected barcode scanner.
00266         /// </summary>
00267         /// <param name="sender"></param>
00268         /// <param name="e"></param>
00269         private async void ShowPreviewButton_Click(object sender, RoutedEventArgs e)
00270         {
00271             await claimedScanner?.ShowVideoPreviewAsync();
00272         }
00273
00274         /// <summary>
00275         /// Event Handler for Hide Preview Button Click.
00276         /// Hides the preview window for the selected barcode scanner.
00277         /// </summary>
00278         /// <param name="sender"></param>
00279         /// <param name="e"></param>
00280         private void HidePreviewButton_Click(object sender, RoutedEventArgs e)
00281         {
00282             claimedScanner?.HideVideoPreview();
00283         }
00284
00285         /// <summary>
00286         /// Event Handler for Start Software Trigger Button Click.
00287         /// Starts scanning.
00288         /// </summary>
00289         /// <param name="sender"></param>
00290         /// <param name="e"></param>
00291         private async void StartSoftwareTriggerButton_Click(object sender, RoutedEventArgs e)
00292         {
00293             if (claimedScanner != null)
00294             {
00295                 await claimedScanner.StartSoftwareTriggerAsync();
00296
00297                 SoftwareTriggerStarted = true;
00298                 RaisePropertyChanged(nameof(SoftwareTriggerStarted));
00299             }
00300         }
00301
00302         /// <summary>
00303         /// Event Handler for Stop Software Trigger Button Click.
00304         /// Stops scanning.
00305         /// </summary>
00306         /// <param name="sender"></param>
00307         /// <param name="e"></param>
00308         private async void StopSoftwareTriggerButton_Click(object sender, RoutedEventArgs e)
00309         {
00310             if (claimedScanner != null)
00311             {
00312                 await claimedScanner.StopSoftwareTriggerAsync();
00313                 SoftwareTriggerStarted = false;
00314                 RaisePropertyChanged(nameof(SoftwareTriggerStarted));
00315             }
00316         }
00317
00318         /// <summary>
00319         /// Event Handler for Flip Preview Button Click.
00320         /// Stops scanning.
00321         /// </summary>
00322         /// <param name="sender"></param>
00323         /// <param name="e"></param>
00324         private void FlipPreview_Click(object sender, RoutedEventArgs e)
00325         {
00326             if (PreviewControl.FlowDirection == FlowDirection.LeftToRight)
00327             {
00328                 PreviewControl.FlowDirection = FlowDirection.RightToLeft;
00329             }
00330             else
00331             {
00332                 PreviewControl.FlowDirection = FlowDirection.LeftToRight;
00333             }
00334         }
00335
00336         /// <summary>
00337         /// Event handler for scanner listbox selection changed
00338         /// </summary>
00339         /// <param name="sender"></param>
00340         /// <param name="args"></param>
00341         private async void ScannerSelection_Changed(object sender, SelectionChangedEventArgs args)
00342         {
00343             var selectedScannerInfo = (BarcodeScannerInfo)args.AddedItems[0];
00344             var deviceId = selectedScannerInfo.DeviceId;
00345
00346             if (isSelectionChanging)
00347             {
00348                 pendingSelectionDeviceId = deviceId;
00349                 return;
00350             }
00351
00352             do
00353             {
00354                 await SelectScannerAsync(deviceId);
00355
00356                 // Stop takes precedence over updating the selection.
00357                 if (isStopPending)
00358                 {
00359                     await CloseScannerResourcesAsync();
00360                     break;
00361                 }
00362
00363                 deviceId = pendingSelectionDeviceId;
00364                 pendingSelectionDeviceId = null;
00365             } while (!String.IsNullOrEmpty(deviceId));
00366         }
00367
00368         /// <summary>
00369         /// Select the scanner specified by its device ID.
00370         /// </summary>
00371         /// <param name="scannerDeviceId"></param>
00372         private async Task SelectScannerAsync(string scannerDeviceId)
00373         {
00374             isSelectionChanging = true;
00375
00376             await CloseScannerResourcesAsync();
00377
00378             selectedScanner = await BarcodeScanner.FromIdAsync(scannerDeviceId);
00379
00380             if (selectedScanner != null)
00381             {
00382                 claimedScanner = await selectedScanner.ClaimScannerAsync();
00383                 if (claimedScanner != null)
00384                 {
00385                     await claimedScanner.EnableAsync();
00386                     claimedScanner.Closed += ClaimedScanner_Closed;
00387                     ScannerSupportsPreview = !String.IsNullOrEmpty(selectedScanner.VideoDeviceId);
00388                     RaisePropertyChanged(nameof(ScannerSupportsPreview));
00389
00390                     claimedScanner.DataReceived += ClaimedScanner_DataReceived;
00391
00392                     if (ScannerSupportsPreview)
00393                     {
00394                         await StartMediaCaptureAsync(selectedScanner.VideoDeviceId);
00395                     }
00396                 }
00397                 else
00398                 {
00399                     rootPage.NotifyUser("Failed to claim the selected barcode scanner", NotifyType.ErrorMessage);
00400                 }
00401
00402             }
00403             else
00404             {
00405                 rootPage.NotifyUser("Failed to create a barcode scanner object", NotifyType.ErrorMessage);
00406             }
00407
00408             IsScannerClaimed = claimedScanner != null;
00409             RaisePropertyChanged(nameof(IsScannerClaimed));
00410
00411             isSelectionChanging = false;
00412         }
00413
00414         /// <summary>
00415         /// Closed notification was received from the selected scanner.
00416         /// </summary>
00417         /// <param name="sender"></param>
00418         /// <param name="args"></param>
00419         private void ClaimedScanner_Closed(ClaimedBarcodeScanner sender, ClaimedBarcodeScannerClosedEventArgs args)
00420         {
00421             // Resources associated to the claimed barcode scanner can be cleaned up here
00422         }
00423
00424         /// <summary>
00425         /// Scan data was received from the selected scanner.
00426         /// </summary>
00427         /// <param name="sender"></param>
00428         /// <param name="args"></param>
00429         private async void ClaimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
00430         {
00431             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00432             {
00433                 ScenarioOutputScanDataLabel.Text = DataHelpers.GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType);
00434                 ScenarioOutputScanData.Text = DataHelpers.GetDataString(args.Report.ScanData);
00435                 ScenarioOutputScanDataType.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType);
00436             });
00437         }
00438
00439         /// <summary>
00440         /// Update listeners that a property was changed so that data bindings can be updated.
00441         /// </summary>
00442         /// <param name="propertyName"></param>
00443         public void RaisePropertyChanged(string propertyName = null)
00444         {
00445             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
00446         }
00447     }
00448 }
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/pch.cpp Source File

  • SimpleInk
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OrientationSensor/cpp/Scenario0_Choose.xaml.h Source File

  • OrientationSensor
  • cpp

Scenario0_Choose.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario0_Choose.xaml.h
00014 // Declaration of the Scenario0_Choose class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario0_Choose.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario0_Choose sealed
00030     {
00031     public:
00032         Scenario0_Choose();
00033
00034     protected:
00035         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036
00037     private:
00038         SDKTemplate::MainPage^ rootPage = MainPage::Current;
00039
00040         void AddReadingType(Windows::Devices::Sensors::SensorReadingType readingType);
00041         void AddOptimizationGoal(Windows::Devices::Sensors::SensorOptimizationGoal optimizationGoal);
00042     };
00043 }
Generated on Fri Nov 15 2024 22:17:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cpp/Scenario2_InAppPurchase.xaml.h Source File

  • Store
  • cpp

Scenario2_InAppPurchase.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario2_InAppPurchase.g.h"
00016 #include "MainPage.xaml.h"
00017 #include "ItemsListViewModel.h"
00018
00019 namespace SDKTemplate
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class Scenario2_InAppPurchase sealed
00023     {
00024     public:
00025         Scenario2_InAppPurchase();
00026
00027     private:
00028         MainPage^ rootPage = MainPage::Current;
00029         Windows::Services::Store::StoreContext^ storeContext;
00030
00031         void GetAssociatedProductsButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032         void PurchaseAddOnButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033     };
00034 }
Generated on Fri Nov 15 2024 22:21:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OrientationSensor/cs/CalibrationBar.xaml.cs Source File

  • OrientationSensor
  • cs

CalibrationBar.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Devices.Sensors;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class CalibrationBar : Page
00020     {
00021         // Constants specifying when the calibration bar is shown:
00022         //   * suppress duration determines how long (in minutes) to wait before
00023         //     showing the calibration bar again
00024         //   * auto dismiss time determines when to auto dismiss the bar
00025         //     if it's shown too long
00026         private const double SUPPRESS_DURATION_APPROXIMATE_MIN = 10.0;
00027         private const double SUPPRESS_DURATION_UNRELIABLE_MIN = 5.0;
00028         private TimeSpan CALIBRATION_POPUP_AUTO_DIMSMISS_TIME = new TimeSpan(0, 0, 30); // 30 seconds
00029
00030         private const double LAYOUT_WIDTH_768 = 768.0;
00031
00032         private DateTime _lastCalibrationTime = new DateTime(0);
00033         private bool _barDismissed = false;
00034         private DispatcherTimer _calibrationTimer;
00035
00036         public CalibrationBar()
00037         {
00038             this.InitializeComponent();
00039             _calibrationTimer = new DispatcherTimer();
00040             _calibrationTimer.Tick += OnAutoDismissTimerExpired;
00041             _calibrationTimer.Interval = CALIBRATION_POPUP_AUTO_DIMSMISS_TIME;
00042         }
00043
00044         /// <summary>
00045         /// Called when the application would like to show the calibration bar to the user
00046         /// to improve sensor accuracy.
00047         /// </summary>
00048         /// <param name="accuracy">Current accuracy of the sensor.</param>
00049         public void RequestCalibration(MagnetometerAccuracy accuracy)
00050         {
00051             // Only show the calibration bar if it is hidden and sufficient
00052             // time has passed since it was last hidden.
00053             if (!CalibrationPopup.IsOpen && CanShowCalibrationBar(accuracy))
00054             {
00055                 InvalidateLayout();
00056                 Window.Current.SizeChanged += OnWindowSizeChanged;
00057                 HideGuidance(); // Calibration image hidden by default
00058                 CalibrationPopup.IsOpen = true;
00059                 _calibrationTimer.Start();
00060             }
00061         }
00062
00063         /// <summary>
00064         /// Called when sensor accuracy is sufficient and the application would like to
00065         /// hide the calibration bar.
00066         /// </summary>
00067         public void Hide()
00068         {
00069             if (CalibrationPopup.IsOpen)
00070             {
00071                 // Hide the calibration bar and save the current time.
00072                 _lastCalibrationTime = DateTime.Now;
00073                 HideGuidance();
00074                 CalibrationPopup.IsOpen = false;
00075                 Window.Current.SizeChanged -= OnWindowSizeChanged;
00076                 _calibrationTimer.Stop();
00077             }
00078         }
00079
00080         /// <summary>
00081         /// Invoked when the window size is updated.
00082         /// </summary>
00083         /// <param name="sender">Instance that triggered the event.</param>
00084         /// <param name="e">Event data describing the conditions that led to the event.</param>
00085         void OnWindowSizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
00086         {
00087             InvalidateLayout();
00088         }
00089
00090         /// <summary>
00091         /// Updates the calibration bar layout based on the current window width.
00092         /// </summary>
00093         private void InvalidateLayout()
00094         {
00095             CalibrationGrid.Width = Window.Current.Bounds.Width;
00096
00097             if (CalibrationGrid.Width < LAYOUT_WIDTH_768)
00098             {
00099                 Grid.SetRow(DismissPopup, 1);
00100                 Grid.SetColumn(DismissPopup, 1);
00101
00102                 CalibrationGridTop.Margin = new Thickness(0, 24, 20, 15);
00103                 DismissPopup.Margin = new Thickness(66, 15, 0, 0);
00104             }
00105             else
00106             {
00107                 Grid.SetRow(DismissPopup, 0);
00108                 Grid.SetColumn(DismissPopup, 2);
00109
00110                 CalibrationGridTop.Margin = new Thickness(0, 19, 66, 19);
00111                 DismissPopup.Margin = new Thickness(66, 0, 0, 0);
00112             }
00113         }
00114
00115         /// <summary>
00116         /// Called to determine if sufficient time has passed since the calibration bar
00117         /// was hidden to show the calibration bar again. This suppression time is
00118         /// dependent on the current sensor accuracy.
00119         /// </summary>
00120         /// <param name="accuracy">Current accuracy of the sensor.</param>
00121         private bool CanShowCalibrationBar(MagnetometerAccuracy accuracy)
00122         {
00123             bool showBar = false;
00124             if (!_barDismissed)
00125             {
00126                 if ((accuracy == MagnetometerAccuracy.Approximate) &&
00127                     (DateTime.Now.CompareTo(_lastCalibrationTime.AddMinutes(SUPPRESS_DURATION_APPROXIMATE_MIN)) >= 0))
00128                 {
00129                     showBar = true;
00130                 }
00131                 else if ((accuracy == MagnetometerAccuracy.Unreliable) &&
00132                     (DateTime.Now.CompareTo(_lastCalibrationTime.AddMinutes(SUPPRESS_DURATION_UNRELIABLE_MIN)) >= 0))
00133                 {
00134                     showBar = true;
00135                 }
00136             }
00137             return showBar;
00138         }
00139
00140         /// <summary>
00141         /// This is the click handler for the show guidance button.
00142         /// </summary>
00143         /// <param name="sender"></param>
00144         /// <param name="e"></param>
00145         private void ShowGuidanceButton_Click(object sender, RoutedEventArgs e)
00146         {
00147             if (Guidance.Visibility == Windows.UI.Xaml.Visibility.Collapsed)
00148             {
00149                 ShowGuidance();
00150             }
00151         }
00152
00153         /// <summary>
00154         /// This is the click handler for the hide guidance button.
00155         /// </summary>
00156         /// <param name="sender"></param>
00157         /// <param name="e"></param>
00158         private void HideGuidanceButton_Click(object sender, RoutedEventArgs e)
00159         {
00160             if (Guidance.Visibility == Windows.UI.Xaml.Visibility.Visible)
00161             {
00162                 HideGuidance();
00163             }
00164         }
00165
00166         /// <summary>
00167         /// This is the click handler for the dismiss popup button. It hides the
00168         /// calibration bar and prevents it from being shown again for the lifetime
00169         /// of the app.
00170         /// </summary>
00171         /// <param name="sender"></param>
00172         /// <param name="e"></param>
00173         private void DismissPopup_Click(object sender, RoutedEventArgs e)
00174         {
00175             // Don't show the calibration bar again.
00176             _barDismissed = true;
00177             Hide();
00178         }
00179
00180         /// <summary>
00181         /// Expands the calibration bar to show the calibration image to the user.
00182         /// </summary>
00183         /// <param name="sender"></param>
00184         /// <param name="e"></param>
00185         private void ShowGuidance()
00186         {
00187             ShowGuidanceButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00188             HideGuidanceButton.Visibility = Windows.UI.Xaml.Visibility.Visible;
00189             Guidance.Visibility = Windows.UI.Xaml.Visibility.Visible;
00190         }
00191
00192         /// <summary>
00193         /// Collapses the calibration bar to hide the calibration image from the user.
00194         /// </summary>
00195         /// <param name="sender"></param>
00196         /// <param name="e"></param>
00197         private void HideGuidance()
00198         {
00199             HideGuidanceButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00200             ShowGuidanceButton.Visibility = Windows.UI.Xaml.Visibility.Visible;
00201             Guidance.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00202         }
00203
00204         /// <summary>
00205         /// This is the handler for the auto dismiss timer. After the calibraiton bar
00206         /// has been shown for the maximum time, it is automatically hidden.
00207         /// </summary>
00208         /// <param name="sender"></param>
00209         /// <param name="e"></param>
00210         private void OnAutoDismissTimerExpired(object sender, object e)
00211         {
00212             Hide();
00213         }
00214     }
00215 }
Generated on Fri Nov 15 2024 22:18:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cs/Scenario13_RetryFilter.xaml.cs Source File

  • HttpClient
  • cs

Scenario13_RetryFilter.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using HttpFilters;
00013 using System;
00014 using System.Threading;
00015 using System.Threading.Tasks;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019 using Windows.Web.Http;
00020 using Windows.Web.Http.Filters;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario13_RetryFilter : Page
00025     {
00026         MainPage rootPage = MainPage.Current;
00027
00028         private HttpClient httpClient;
00029         private CancellationTokenSource cts;
00030
00031         public Scenario13_RetryFilter()
00032         {
00033             this.InitializeComponent();
00034         }
00035
00036         protected override void OnNavigatedTo(NavigationEventArgs e)
00037         {
00038             HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter();
00039             HttpRetryFilter retryFilter = new HttpRetryFilter(baseProtocolFilter);
00040             httpClient = new HttpClient(retryFilter);
00041             cts = new CancellationTokenSource();
00042             UpdateAddressField();
00043         }
00044
00045         protected override void OnNavigatedFrom(NavigationEventArgs e)
00046         {
00047             cts.Cancel();
00048             cts.Dispose();
00049             httpClient.Dispose();
00050         }
00051
00052         private void UpdateAddressField()
00053         {
00054             // Tell the server which type of Retry-After header we would like to receive.
00055             string queryString = "";
00056             if (RetryAfterSwitch.IsOn)
00057             {
00058                 queryString += "?retryAfter=deltaSeconds";
00059             }
00060             else
00061             {
00062                 queryString += "?retryAfter=httpDate";
00063             }
00064
00065             Helpers.ReplaceQueryString(AddressField, queryString);
00066         }
00067
00068         private void RetryAfterSwitch_Toggled(object sender, RoutedEventArgs e)
00069         {
00070             UpdateAddressField();
00071         }
00072
00073         private async void Start_Click(object sender, RoutedEventArgs e)
00074         {
00075             Uri resourceUri = Helpers.TryParseHttpUri(AddressField.Text);
00076
00077             // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00078             // valid, absolute URI, we'll notify the user about the incorrect input.
00079             if (resourceUri == null)
00080             {
00081                 rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
00082                 return;
00083             }
00084
00085             Helpers.ScenarioStarted(StartButton, CancelButton, OutputField);
00086             rootPage.NotifyUser("In progress", NotifyType.StatusMessage);
00087
00088             // This sample uses a "try" in order to support TaskCanceledException.
00089             // If you don't need to support cancellation, then the "try" is not needed.
00090             try
00091             {
00092                 HttpRequestResult result = await httpClient.TryGetAsync(resourceUri).AsTask(cts.Token);
00093
00094                 if (result.Succeeded)
00095                 {
00096                     await Helpers.DisplayTextResultAsync(result.ResponseMessage, OutputField, cts.Token);
00097
00098                     rootPage.NotifyUser("Completed", NotifyType.StatusMessage);
00099                 }
00100                 else
00101                 {
00102                     Helpers.DisplayWebError(rootPage, result.ExtendedError);
00103                 }
00104             }
00105             catch (TaskCanceledException)
00106             {
00107                 rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
00108             }
00109
00110             Helpers.ScenarioCompleted(StartButton, CancelButton);
00111         }
00112
00113         private void Cancel_Click(object sender, RoutedEventArgs e)
00114         {
00115             cts.Cancel();
00116             cts.Dispose();
00117
00118             // Re-create the CancellationTokenSource.
00119             cts = new CancellationTokenSource();
00120         }
00121     }
00122 }
Generated on Fri Nov 15 2024 22:20:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cppwinrt/Scenario3_InkingFeedback.h Source File

  • PenHaptics
  • cppwinrt

Scenario3_InkingFeedback.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_InkingFeedback.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario3_InkingFeedback : Scenario3_InkingFeedbackT<Scenario3_InkingFeedback>
00020     {
00021         Scenario3_InkingFeedback();
00022
00023         void HapticCanvas_Entered(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::Input::PointerRoutedEventArgs const& e);
00024         void HapticCanvas_Exited(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::Input::PointerRoutedEventArgs const& e);
00025
00026     private:
00027         Windows::Devices::Haptics::SimpleHapticsController hapticsController{ nullptr };
00028         Windows::Devices::Input::PenDevice penDevice{ nullptr };
00029         Windows::Devices::Haptics::SimpleHapticsControllerFeedback currentFeedback{ nullptr };
00030
00031         Windows::Devices::Haptics::SimpleHapticsControllerFeedback GetSelectedFeedbackOrFallback(std::wstring& message);
00032
00033     };
00034 }
00035
00036 namespace winrt::SDKTemplate::factory_implementation
00037 {
00038     struct Scenario3_InkingFeedback : Scenario3_InkingFeedbackT<Scenario3_InkingFeedback, implementation::Scenario3_InkingFeedback>
00039     {
00040     };
00041 }
Generated on Fri Nov 15 2024 22:20:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cppwinrt/Common/CameraResources.cpp Source File

  • BasicHologram
  • cppwinrt
  • Common

CameraResources.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002
00003 #include "CameraResources.h"
00004 #include "Common\DirectXHelper.h"
00005 #include "DeviceResources.h"
00006
00007 using namespace DirectX;
00008 using namespace Microsoft::WRL;
00009 using namespace winrt::Windows::Foundation::Numerics;
00010 using namespace winrt::Windows::Graphics::DirectX::Direct3D11;
00011 using namespace winrt::Windows::Graphics::Holographic;
00012 using namespace winrt::Windows::Perception::Spatial;
00013
00014 DX::CameraResources::CameraResources(HolographicCamera const& camera) :
00015     m_holographicCamera(camera),
00016     m_isStereo(camera.IsStereo()),
00017     m_d3dRenderTargetSize(camera.RenderTargetSize())
00018 {
00019     m_d3dViewport = CD3D11_VIEWPORT(
00020         0.f, 0.f,
00021         m_d3dRenderTargetSize.Width,
00022         m_d3dRenderTargetSize.Height
00023     );
00024 };
00025
00026 // Updates resources associated with a holographic camera's swap chain.
00027 // The app does not access the swap chain directly, but it does create
00028 // resource views for the back buffer.
00029 void DX::CameraResources::CreateResourcesForBackBuffer(
00030     DX::DeviceResources* pDeviceResources,
00031     HolographicCameraRenderingParameters const& cameraParameters
00032 )
00033 {
00034     ID3D11Device* device = pDeviceResources->GetD3DDevice();
00035
00036     // Get the WinRT object representing the holographic camera's back buffer.
00037     IDirect3DSurface surface = cameraParameters.Direct3D11BackBuffer();
00038
00039     // Get the holographic camera's back buffer.
00040     // Holographic apps do not create a swap chain themselves; instead, buffers are
00041     // owned by the system. The Direct3D back buffer resources are provided to the
00042     // app using WinRT interop APIs.
00043     ComPtr<ID3D11Texture2D> cameraBackBuffer;
00044     winrt::check_hresult(surface.as<::Windows::Graphics::DirectX::Direct3D11::IDirect3DDxgiInterfaceAccess>()->GetInterface(IID_PPV_ARGS(&cameraBackBuffer)));
00045
00046     // Determine if the back buffer has changed. If so, ensure that the render target view
00047     // is for the current back buffer.
00048     if (m_d3dBackBuffer.Get() != cameraBackBuffer.Get())
00049     {
00050         // This can change every frame as the system moves to the next buffer in the
00051         // swap chain. This mode of operation will occur when certain rendering modes
00052         // are activated.
00053         m_d3dBackBuffer = cameraBackBuffer;
00054
00055         // Create a render target view of the back buffer.
00056         // Creating this resource is inexpensive, and is better than keeping track of
00057         // the back buffers in order to pre-allocate render target views for each one.
00058         winrt::check_hresult(
00059             device->CreateRenderTargetView(
00060                 m_d3dBackBuffer.Get(),
00061                 nullptr,
00062                 &m_d3dRenderTargetView
00063             ));
00064
00065         // Get the DXGI format for the back buffer.
00066         // This information can be accessed by the app using CameraResources::GetBackBufferDXGIFormat().
00067         D3D11_TEXTURE2D_DESC backBufferDesc;
00068         m_d3dBackBuffer->GetDesc(&backBufferDesc);
00069         m_dxgiFormat = backBufferDesc.Format;
00070
00071         // Check for render target size changes.
00072         winrt::Windows::Foundation::Size currentSize = m_holographicCamera.RenderTargetSize();
00073         if (m_d3dRenderTargetSize != currentSize)
00074         {
00075             // Set render target size.
00076             m_d3dRenderTargetSize = currentSize;
00077
00078             // A new depth stencil view is also needed.
00079             m_d3dDepthStencilView.Reset();
00080         }
00081     }
00082
00083     // Refresh depth stencil resources, if needed.
00084     if (m_d3dDepthStencilView == nullptr)
00085     {
00086         // Create a depth stencil view for use with 3D rendering if needed.
00087         CD3D11_TEXTURE2D_DESC depthStencilDesc(
00088             DXGI_FORMAT_R16_TYPELESS,
00089             static_cast<UINT>(m_d3dRenderTargetSize.Width),
00090             static_cast<UINT>(m_d3dRenderTargetSize.Height),
00091             m_isStereo ? 2 : 1, // Create two textures when rendering in stereo.
00092             1, // Use a single mipmap level.
00093             D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE
00094         );
00095
00096         winrt::check_hresult(
00097             device->CreateTexture2D(
00098                 &depthStencilDesc,
00099                 nullptr,
00100                 &m_d3dDepthStencil
00101             ));
00102
00103         CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(
00104             m_isStereo ? D3D11_DSV_DIMENSION_TEXTURE2DARRAY : D3D11_DSV_DIMENSION_TEXTURE2D,
00105             DXGI_FORMAT_D16_UNORM
00106         );
00107         winrt::check_hresult(
00108             device->CreateDepthStencilView(
00109                 m_d3dDepthStencil.Get(),
00110                 &depthStencilViewDesc,
00111                 &m_d3dDepthStencilView
00112             ));
00113     }
00114
00115     // Create the constant buffer, if needed.
00116     if (m_viewProjectionConstantBuffer == nullptr)
00117     {
00118         // Create a constant buffer to store view and projection matrices for the camera.
00119         CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00120         winrt::check_hresult(
00121             device->CreateBuffer(
00122                 &constantBufferDesc,
00123                 nullptr,
00124                 &m_viewProjectionConstantBuffer
00125             ));
00126     }
00127 }
00128
00129 // Releases resources associated with a back buffer.
00130 void DX::CameraResources::ReleaseResourcesForBackBuffer(DX::DeviceResources* pDeviceResources)
00131 {
00132     ID3D11DeviceContext* context = pDeviceResources->GetD3DDeviceContext();
00133
00134     // Release camera-specific resources.
00135     m_d3dBackBuffer.Reset();
00136     m_d3dDepthStencil.Reset();
00137     m_d3dRenderTargetView.Reset();
00138     m_d3dDepthStencilView.Reset();
00139     m_viewProjectionConstantBuffer.Reset();
00140
00141     // Ensure system references to the back buffer are released by clearing the render
00142     // target from the graphics pipeline state, and then flushing the Direct3D context.
00143     ID3D11RenderTargetView* nullViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { nullptr };
00144     context->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00145     context->Flush();
00146 }
00147
00148 // Updates the view/projection constant buffer for a holographic camera.
00149 void DX::CameraResources::UpdateViewProjectionBuffer(
00150     std::shared_ptr<DX::DeviceResources> deviceResources,
00151     HolographicCameraPose const& cameraPose,
00152     SpatialCoordinateSystem const& coordinateSystem
00153 )
00154 {
00155     // The system changes the viewport on a per-frame basis for system optimizations.
00156     auto viewport = cameraPose.Viewport();
00157     m_d3dViewport = CD3D11_VIEWPORT(
00158         viewport.X,
00159         viewport.Y,
00160         viewport.Width,
00161         viewport.Height
00162     );
00163
00164     // The projection transform for each frame is provided by the HolographicCameraPose.
00165     HolographicStereoTransform cameraProjectionTransform = cameraPose.ProjectionTransform();
00166
00167     // Get a container object with the view and projection matrices for the given
00168     // pose in the given coordinate system.
00169     auto viewTransformContainer = cameraPose.TryGetViewTransform(coordinateSystem);
00170
00171     // If TryGetViewTransform returns a null pointer, that means the pose and coordinate
00172     // system cannot be understood relative to one another; content cannot be rendered
00173     // in this coordinate system for the duration of the current frame.
00174     // This usually means that positional tracking is not active for the current frame, in
00175     // which case it is possible to use a SpatialLocatorAttachedFrameOfReference to render
00176     // content that is not world-locked instead.
00177     DX::ViewProjectionConstantBuffer viewProjectionConstantBufferData;
00178     bool viewTransformAcquired = viewTransformContainer != nullptr;
00179     if (viewTransformAcquired)
00180     {
00181         // Otherwise, the set of view transforms can be retrieved.
00182         HolographicStereoTransform viewCoordinateSystemTransform = viewTransformContainer.Value();
00183
00184         // Update the view matrices. Holographic cameras (such as Microsoft HoloLens) are
00185         // constantly moving relative to the world. The view matrices need to be updated
00186         // every frame.
00187         XMStoreFloat4x4(
00188             &viewProjectionConstantBufferData.viewProjection[0],
00189             XMMatrixTranspose(XMLoadFloat4x4(&viewCoordinateSystemTransform.Left) * XMLoadFloat4x4(&cameraProjectionTransform.Left))
00190         );
00191         XMStoreFloat4x4(
00192             &viewProjectionConstantBufferData.viewProjection[1],
00193             XMMatrixTranspose(XMLoadFloat4x4(&viewCoordinateSystemTransform.Right) * XMLoadFloat4x4(&cameraProjectionTransform.Right))
00194         );
00195     }
00196
00197     // Use the D3D device context to update Direct3D device-based resources.
00198     ID3D11DeviceContext* context = deviceResources->GetD3DDeviceContext();
00199
00200     // Loading is asynchronous. Resources must be created before they can be updated.
00201     if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || !viewTransformAcquired)
00202     {
00203         m_framePending = false;
00204     }
00205     else
00206     {
00207         // Update the view and projection matrices.
00208         context->UpdateSubresource(
00209             m_viewProjectionConstantBuffer.Get(),
00210             0,
00211             nullptr,
00212             &viewProjectionConstantBufferData,
00213             0,
00214             0
00215         );
00216
00217         m_framePending = true;
00218     }
00219 }
00220
00221 // Gets the view-projection constant buffer for the HolographicCamera and attaches it
00222 // to the shader pipeline.
00223 bool DX::CameraResources::AttachViewProjectionBuffer(
00224     std::shared_ptr<DX::DeviceResources>& deviceResources
00225 )
00226 {
00227     // This method uses Direct3D device-based resources.
00228     ID3D11DeviceContext* context = deviceResources->GetD3DDeviceContext();
00229
00230     // Loading is asynchronous. Resources must be created before they can be updated.
00231     // Cameras can also be added asynchronously, in which case they must be initialized
00232     // before they can be used.
00233     if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || m_framePending == false)
00234     {
00235         return false;
00236     }
00237
00238     // Set the viewport for this camera.
00239     context->RSSetViewports(1, &m_d3dViewport);
00240
00241     // Send the constant buffer to the vertex shader.
00242     context->VSSetConstantBuffers(
00243         1,
00244         1,
00245         m_viewProjectionConstantBuffer.GetAddressOf()
00246     );
00247
00248     // The template includes a pass-through geometry shader that is used by
00249     // default on systems that don't support the D3D11_FEATURE_D3D11_OPTIONS3::
00250     // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer extension. The shader
00251     // will be enabled at run-time on systems that require it.
00252     // If your app will also use the geometry shader for other tasks and those
00253     // tasks require the view/projection matrix, uncomment the following line
00254     // of code to send the constant buffer to the geometry shader as well.
00255     /*context->GSSetConstantBuffers(
00256     1,
00257     1,
00258     m_viewProjectionConstantBuffer.GetAddressOf()
00259     );*/
00260
00261     m_framePending = false;
00262
00263     return true;
00264 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/Common/CameraResources.cpp Source File

  • HolographicMixedRealityCapture
  • cpp
  • Common

CameraResources.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002
00003 #include "CameraResources.h"
00004 #include "Common\DirectXHelper.h"
00005 #include "DeviceResources.h"
00006 #include <windows.graphics.directx.direct3d11.interop.h>
00007
00008 using namespace DirectX;
00009 using namespace Microsoft::WRL;
00010 using namespace Windows::Graphics::DirectX::Direct3D11;
00011 using namespace Windows::Graphics::Holographic;
00012 using namespace Windows::Perception::Spatial;
00013
00014 DX::CameraResources::CameraResources(HolographicCamera^ camera) :
00015     m_holographicCamera(camera),
00016     m_isStereo(camera->IsStereo),
00017     m_d3dRenderTargetSize(camera->RenderTargetSize)
00018 {
00019     m_d3dViewport = CD3D11_VIEWPORT(
00020         0.f, 0.f,
00021         m_d3dRenderTargetSize.Width,
00022         m_d3dRenderTargetSize.Height
00023         );
00024 };
00025
00026 // Updates resources associated with a holographic camera's swap chain.
00027 // The app does not access the swap chain directly, but it does create
00028 // resource views for the back buffer.
00029 void DX::CameraResources::CreateResourcesForBackBuffer(
00030     DX::DeviceResources* pDeviceResources,
00031     HolographicCameraRenderingParameters^ cameraParameters
00032     )
00033 {
00034     const auto device = pDeviceResources->GetD3DDevice();
00035
00036     // Get the WinRT object representing the holographic camera's back buffer.
00037     IDirect3DSurface^ surface = cameraParameters->Direct3D11BackBuffer;
00038
00039     // Get a DXGI interface for the holographic camera's back buffer.
00040     // Holographic cameras do not provide the DXGI swap chain, which is owned
00041     // by the system. The Direct3D back buffer resource is provided using WinRT
00042     // interop APIs.
00043     ComPtr<ID3D11Resource> resource;
00044     ThrowIfFailed(
00045         GetDXGIInterfaceFromObject(surface, IID_PPV_ARGS(&resource))
00046         );
00047
00048     // Get a Direct3D interface for the holographic camera's back buffer.
00049     ComPtr<ID3D11Texture2D> cameraBackBuffer;
00050     ThrowIfFailed(
00051         resource.As(&cameraBackBuffer)
00052         );
00053
00054     // Determine if the back buffer has changed. If so, ensure that the render target view
00055     // is for the current back buffer.
00056     if (m_d3dBackBuffer.Get() != cameraBackBuffer.Get())
00057     {
00058         // This can change every frame as the system moves to the next buffer in the
00059         // swap chain. This mode of operation will occur when certain rendering modes
00060         // are activated.
00061         m_d3dBackBuffer = cameraBackBuffer;
00062
00063         // Create a render target view of the back buffer.
00064         // Creating this resource is inexpensive, and is better than keeping track of
00065         // the back buffers in order to pre-allocate render target views for each one.
00066         DX::ThrowIfFailed(
00067             device->CreateRenderTargetView(
00068                 m_d3dBackBuffer.Get(),
00069                 nullptr,
00070                 &m_d3dRenderTargetView
00071                 )
00072             );
00073
00074         // Get the DXGI format for the back buffer.
00075         // This information can be accessed by the app using CameraResources::GetBackBufferDXGIFormat().
00076         D3D11_TEXTURE2D_DESC backBufferDesc;
00077         m_d3dBackBuffer->GetDesc(&backBufferDesc);
00078         m_dxgiFormat = backBufferDesc.Format;
00079
00080         // Check for render target size changes.
00081         Windows::Foundation::Size currentSize = m_holographicCamera->RenderTargetSize;
00082         if (m_d3dRenderTargetSize != currentSize)
00083         {
00084             // Set render target size.
00085             m_d3dRenderTargetSize = currentSize;
00086
00087             // A new depth stencil view is also needed.
00088             m_d3dDepthStencilView.Reset();
00089         }
00090     }
00091
00092     // Refresh depth stencil resources, if needed.
00093     if (m_d3dDepthStencilView == nullptr)
00094     {
00095         // Create a depth stencil view for use with 3D rendering if needed.
00096         CD3D11_TEXTURE2D_DESC depthStencilDesc(
00097             DXGI_FORMAT_D16_UNORM,
00098             static_cast<UINT>(m_d3dRenderTargetSize.Width),
00099             static_cast<UINT>(m_d3dRenderTargetSize.Height),
00100             m_isStereo ? 2 : 1, // Create two textures when rendering in stereo.
00101             1, // Use a single mipmap level.
00102             D3D11_BIND_DEPTH_STENCIL
00103             );
00104
00105         ComPtr<ID3D11Texture2D> depthStencil;
00106         DX::ThrowIfFailed(
00107             device->CreateTexture2D(
00108                 &depthStencilDesc,
00109                 nullptr,
00110                 &depthStencil
00111                 )
00112             );
00113
00114         CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(
00115             m_isStereo ? D3D11_DSV_DIMENSION_TEXTURE2DARRAY : D3D11_DSV_DIMENSION_TEXTURE2D
00116             );
00117         DX::ThrowIfFailed(
00118             device->CreateDepthStencilView(
00119                 depthStencil.Get(),
00120                 &depthStencilViewDesc,
00121                 &m_d3dDepthStencilView
00122                 )
00123             );
00124     }
00125
00126     // Create the constant buffer, if needed.
00127     if (m_viewProjectionConstantBuffer == nullptr)
00128     {
00129         // Create a constant buffer to store view and projection matrices for the camera.
00130         CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00131         DX::ThrowIfFailed(
00132             device->CreateBuffer(
00133                 &constantBufferDesc,
00134                 nullptr,
00135                 &m_viewProjectionConstantBuffer
00136                 )
00137             );
00138     }
00139
00140     if (m_blendState == nullptr)
00141     {
00142         D3D11_BLEND_DESC blendStateDesc;
00143         ZeroMemory(&blendStateDesc, sizeof(D3D11_BLEND_DESC));
00144         blendStateDesc.AlphaToCoverageEnable = FALSE;
00145         blendStateDesc.IndependentBlendEnable = FALSE;
00146         blendStateDesc.RenderTarget[0].BlendEnable = TRUE;
00147         blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
00148         blendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
00149         blendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
00150         blendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
00151         blendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
00152         blendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
00153         blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
00154
00155         DX::ThrowIfFailed(
00156             device->CreateBlendState(&blendStateDesc, m_blendState.ReleaseAndGetAddressOf())
00157             );
00158
00159     }
00160 }
00161
00162 // Releases resources associated with a back buffer.
00163 void DX::CameraResources::ReleaseResourcesForBackBuffer(DX::DeviceResources* pDeviceResources)
00164 {
00165     const auto context = pDeviceResources->GetD3DDeviceContext();
00166
00167     // Release camera-specific resources.
00168     m_d3dBackBuffer.Reset();
00169     m_d3dRenderTargetView.Reset();
00170     m_d3dDepthStencilView.Reset();
00171     m_viewProjectionConstantBuffer.Reset();
00172
00173     // Ensure system references to the back buffer are released by clearing the render
00174     // target from the graphics pipeline state, and then flushing the Direct3D context.
00175     ID3D11RenderTargetView* nullViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { nullptr };
00176     context->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00177     context->Flush();
00178 }
00179
00180 // Updates the view/projection constant buffer for a holographic camera.
00181 void DX::CameraResources::UpdateViewProjectionBuffer(
00182     std::shared_ptr<DX::DeviceResources> deviceResources,
00183     HolographicCameraPose^ cameraPose,
00184     SpatialCoordinateSystem^ coordinateSystem
00185     )
00186 {
00187     // The system changes the viewport on a per-frame basis for system optimizations.
00188     m_d3dViewport = CD3D11_VIEWPORT(
00189         cameraPose->Viewport.Left,
00190         cameraPose->Viewport.Top,
00191         cameraPose->Viewport.Width,
00192         cameraPose->Viewport.Height
00193         );
00194
00195     // The projection transform for each frame is provided by the HolographicCameraPose.
00196     HolographicStereoTransform cameraProjectionTransform = cameraPose->ProjectionTransform;
00197
00198     // Get a container object with the view and projection matrices for the given
00199     // pose in the given coordinate system.
00200     Platform::IBox<HolographicStereoTransform>^ viewTransformContainer = cameraPose->TryGetViewTransform(coordinateSystem);
00201
00202     // If TryGetViewTransform returns a null pointer, that means the pose and coordinate
00203     // system cannot be understood relative to one another; content cannot be rendered
00204     // in this coordinate system for the duration of the current frame.
00205     // This usually means that positional tracking is not active for the current frame, in
00206     // which case it is possible to use a SpatialLocatorAttachedFrameOfReference to render
00207     // content that is not world-locked instead.
00208     DX::ViewProjectionConstantBuffer viewProjectionConstantBufferData;
00209     bool viewTransformAcquired = viewTransformContainer != nullptr;
00210     if (viewTransformAcquired)
00211     {
00212         // Otherwise, the set of view transforms can be retrieved.
00213         HolographicStereoTransform viewCoordinateSystemTransform = viewTransformContainer->Value;
00214
00215         // Update the view matrices. Holographic cameras (such as Microsoft HoloLens) are
00216         // constantly moving relative to the world. The view matrices need to be updated
00217         // every frame.
00218         XMStoreFloat4x4(
00219             &viewProjectionConstantBufferData.viewProjection[0],
00220             XMMatrixTranspose(XMLoadFloat4x4(&viewCoordinateSystemTransform.Left) * XMLoadFloat4x4(&cameraProjectionTransform.Left))
00221             );
00222         XMStoreFloat4x4(
00223             &viewProjectionConstantBufferData.viewProjection[1],
00224             XMMatrixTranspose(XMLoadFloat4x4(&viewCoordinateSystemTransform.Right) * XMLoadFloat4x4(&cameraProjectionTransform.Right))
00225             );
00226     }
00227
00228     // Use the D3D device context to update Direct3D device-based resources.
00229     const auto context = deviceResources->GetD3DDeviceContext();
00230
00231     // Loading is asynchronous. Resources must be created before they can be updated.
00232     if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || !viewTransformAcquired)
00233     {
00234         m_framePending = false;
00235     }
00236     else
00237     {
00238         // Update the view and projection matrices.
00239         context->UpdateSubresource(
00240             m_viewProjectionConstantBuffer.Get(),
00241             0,
00242             nullptr,
00243             &viewProjectionConstantBufferData,
00244             0,
00245             0
00246             );
00247
00248         m_framePending = true;
00249     }
00250 }
00251
00252 // Gets the view-projection constant buffer for the HolographicCamera and attaches it
00253 // to the shader pipeline.
00254 bool DX::CameraResources::AttachViewProjectionBuffer(
00255     std::shared_ptr<DX::DeviceResources> deviceResources
00256     )
00257 {
00258     // This method uses Direct3D device-based resources.
00259     const auto context = deviceResources->GetD3DDeviceContext();
00260
00261     // Loading is asynchronous. Resources must be created before they can be updated.
00262     // Cameras can also be added asynchronously, in which case they must be initialized
00263     // before they can be used.
00264     if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || m_framePending == false)
00265     {
00266         return false;
00267     }
00268
00269     // Set the viewport for this camera.
00270     context->RSSetViewports(1, &m_d3dViewport);
00271
00272     // Send the constant buffer to the vertex shader.
00273     context->VSSetConstantBuffers(
00274         1,
00275         1,
00276         m_viewProjectionConstantBuffer.GetAddressOf()
00277         );
00278
00279     // The template includes a pass-through geometry shader that is used by
00280     // default on systems that don't support the D3D11_FEATURE_D3D11_OPTIONS3::
00281     // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer extension. The shader
00282     // will be enabled at run-time on systems that require it.
00283     // If your app will also use the geometry shader for other tasks and those
00284     // tasks require the view/projection matrix, uncomment the following line
00285     // of code to send the constant buffer to the geometry shader as well.
00286     /*context->GSSetConstantBuffers(
00287         1,
00288         1,
00289         m_viewProjectionConstantBuffer.GetAddressOf()
00290         );*/
00291
00292     m_framePending = false;
00293
00294     return true;
00295 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/pch.h Source File

  • SpatialInteractionSource
  • cpp

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #define _USE_MATH_DEFINES
00004
00005 #include <agile.h>
00006 #include <array>
00007 #include <d2d1_2.h>
00008 #include <d3d11_4.h>
00009 #include <DirectXColors.h>
00010 #include <DirectXCollision.h>
00011
00012 #include <dwrite_2.h>
00013 #include <map>
00014 #include <mutex>
00015 #include <wincodec.h>
00016 #include <WindowsNumerics.h>
00017
00018 #include <vector>
00019 #include <memory>
00020 #include <wrl.h>
00021
00022 typedef unsigned int VertexIndex_t;
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PdfDocument/cpp/SampleConfiguration.h Source File

  • PdfDocument
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "PDF Document C++ Sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AudioCategory/cs/AudioCategory/Scenario7.xaml.cs Source File

  • AudioCategory
  • cs
  • AudioCategory

Scenario7.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016 using Windows.UI.Xaml.Media;
00017
00018 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00019
00020 namespace PlaybackManager
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class Scenario7 : Page
00026     {
00027         public Scenario7()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         private void Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00033         {
00034             Playback.SetAudioCategory(AudioCategory.SoundEffects);
00035             Playback.SelectFile();
00036         }
00037     }
00038 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCoordinateMapper/cpp/Content/CameraCoordinateMapper.h Source File

  • CameraStreamCoordinateMapper
  • cpp
  • Content

CameraCoordinateMapper.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015 #include "GpuCoordinateMapper.h"
00016
00017 namespace CameraStreamCoordinateMapper {
00018
00019     class CameraStreamProcessor;
00020
00021     ////////////////////////////////////////////////////////////////////////////////
00022     // CameraCoordinateMapper
00023     //
00024     // This gathers frames from the CameraStreamProcessor and feeds them into the GpuCoordinateMapper
00025     //
00026     // The core algorithm resides in GpuCoordinateMapper and its respective shaders, CameraCoordinateMapper
00027     // is meant to manage the resources and recreate them if the camera's intrinsics or other properties change
00028
00029     class CameraCoordinateMapper
00030     {
00031     public:
00032         static concurrency::task<std::shared_ptr<CameraCoordinateMapper>> CreateAndStartAsync(std::shared_ptr<DX::DeviceResources> deviceResources);
00033
00034         CameraCoordinateMapper(
00035             std::shared_ptr<DX::DeviceResources> deviceResources,
00036             std::shared_ptr<CameraStreamProcessor> colorStreamProcessor,
00037             std::shared_ptr<CameraStreamProcessor> depthStreamProcessor);
00038
00039         void CreateDeviceDependentResources();
00040         void ReleaseDeviceDependentResources();
00041
00042         concurrency::task<void> StartAsync();
00043         concurrency::task<void> StopAsync();
00044
00045         bool TryAcquireLatestFrameData();
00046
00047         void RunCoordinateMapping();
00048
00049         void VisualizeCoordinateMapping(
00050             ID3D11RenderTargetView* renderTarget,
00051             ID3D11DepthStencilView* depthBuffer,
00052             const D3D11_VIEWPORT& viewport,
00053             const Windows::Foundation::Numerics::float4x4& worldToView);
00054
00055         bool AreCamerasStreaming() const;
00056         ID3D11ShaderResourceView* GetTargetShaderResourceView() const;
00057         float GetTargetAspectRatio() const;
00058
00059     private:
00060         void UpdateDepthResources(Windows::Media::Capture::Frames::MediaFrameReference^ depthFrame);
00061         void UpdateColorResources(Windows::Media::Capture::Frames::MediaFrameReference^ colorFrame);
00062
00063         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00064
00065         std::shared_ptr<CameraStreamProcessor> m_colorCameraStreamProcessor;
00066         std::shared_ptr<CameraStreamProcessor> m_depthCameraStreamProcessor;
00067         std::unique_ptr<GpuCoordinateMapper> m_gpuCoordinateMapper;
00068
00069         Microsoft::WRL::ComPtr<ID3D11Texture2D> m_depthTexture;
00070         Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_depthTextureSRV;
00071
00072         Microsoft::WRL::ComPtr<ID3D11Texture2D> m_colorTexture;
00073         Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_colorTextureSRV;
00074
00075         Microsoft::WRL::ComPtr<ID3D11Texture2D> m_targetTexture;
00076         Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_targetTextureSRV;
00077         Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_targetTextureRTV;
00078
00079         Microsoft::WRL::ComPtr<ID3D11Texture2D> m_targetRasterizedDepthTexture;
00080         Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_targetRasterizedDepthTextureDSV;
00081         Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_targetRasterizedDepthTextureSRV;
00082
00083         Microsoft::WRL::ComPtr<ID3D11Texture2D> m_depthUnprojectionMapTexture;
00084         Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_depthUnprojectionMapTextureSRV;
00085
00086         Microsoft::WRL::ComPtr<ID3D11Texture2D> m_colorDistortionMapTexture;
00087         Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_colorDistortionMapTextureSRV;
00088
00089         GpuCoordinateMapper::RasterizedFrameBlob m_rasterizeFrameBlob = {};
00090         GpuCoordinateMapper::VisualizeFrameBlob m_visualizeFrameBlob = {};
00091
00092         GpuCoordinateMapper::CameraIntrinsics m_depthIntrinsics = {};
00093         GpuCoordinateMapper::CameraIntrinsics m_colorIntrinsics = {};
00094
00095         std::optional<uint32_t> m_depthFrameIndex = {};
00096         std::optional<uint32_t> m_colorFrameIndex = {};
00097     };
00098 }
00099
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Server/ServiceBase.h Source File

  • CustomCapability
  • Service
  • Server

ServiceBase.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 // Provides a base class for a service that will exist as part of a service
00013 // application. CServiceBase must be derived from when creating a new service
00014 // class.
00015
00016 #pragma once
00017
00018 #include <windows.h>
00019 #include <evntprov.h>
00020
00021 class CServiceBase
00022 {
00023 public:
00024
00025     // Register the executable for a service with the Service Control Manager
00026     // (SCM). After you call Run(ServiceBase), the SCM issues a Start command,
00027     // which results in a call to the OnStart method in the service. This
00028     // method blocks until the service has stopped.
00029     static BOOL Run(CServiceBase& service);
00030
00031     // Service object constructor. The optional parameters (fCanStop,
00032     // fCanShutdown and fCanPauseContinue) allow you to specify whether the
00033     // service can be stopped, paused and continued, or be notified when
00034     // system shutdown occurs.
00035     CServiceBase(PWSTR pszServiceName,
00036         BOOL fCanStop = TRUE,
00037         BOOL fCanShutdown = TRUE,
00038         BOOL fCanPauseContinue = FALSE);
00039
00040     // Service object destructor.
00041     virtual ~CServiceBase(void);
00042
00043     // Stop the service.
00044     void Stop();
00045
00046 protected:
00047
00048     // When implemented in a derived class, executes when a Start command is
00049     // sent to the service by the SCM or when the operating system starts
00050     // (for a service that starts automatically). Specifies actions to take
00051     // when the service starts.
00052     virtual void OnStart(DWORD dwArgc, PWSTR *pszArgv);
00053
00054     // When implemented in a derived class, executes when a Stop command is
00055     // sent to the service by the SCM. Specifies actions to take when a
00056     // service stops running.
00057     virtual void OnStop();
00058
00059     // When implemented in a derived class, executes when a Pause command is
00060     // sent to the service by the SCM. Specifies actions to take when a
00061     // service pauses.
00062     virtual void OnPause();
00063
00064     // When implemented in a derived class, OnContinue runs when a Continue
00065     // command is sent to the service by the SCM. Specifies actions to take
00066     // when a service resumes normal functioning after being paused.
00067     virtual void OnContinue();
00068
00069     // When implemented in a derived class, executes when the system is
00070     // shutting down. Specifies what should occur immediately prior to the
00071     // system shutting down.
00072     virtual void OnShutdown();
00073
00074     // Set the service status and report the status to the SCM.
00075     void SetServiceStatus(DWORD dwCurrentState,
00076         DWORD dwWin32ExitCode = NO_ERROR,
00077         DWORD dwWaitHint = 0);
00078
00079     // Log an event.
00080     virtual void WriteEventLogEntry(PWSTR pszMessage, BYTE bLevel);
00081
00082     // Log an event.
00083     void WriteErrorLogEntry(PWSTR pszFunction,
00084         DWORD dwError = GetLastError());
00085
00086 private:
00087
00088     // Entry point for the service. It registers the handler function for the
00089     // service and starts the service.
00090     static void WINAPI ServiceMain(DWORD dwArgc, LPWSTR *lpszArgv);
00091
00092     // The function is called by the SCM whenever a control code is sent to
00093     // the service.
00094     static void WINAPI ServiceCtrlHandler(DWORD dwCtrl);
00095
00096     // Start the service.
00097     void Start(DWORD dwArgc, PWSTR *pszArgv);
00098
00099     // Pause the service.
00100     void Pause();
00101
00102     // Resume the service after being paused.
00103     void Continue();
00104
00105     // Execute when the system is shutting down.
00106     void Shutdown();
00107
00108     // The singleton service instance.
00109     static CServiceBase *s_service;
00110
00111     // The name of the service
00112     PWSTR m_name;
00113
00114     // The status of the service
00115     SERVICE_STATUS m_status;
00116
00117     // The service status handle
00118     SERVICE_STATUS_HANDLE m_statusHandle;
00119
00120     REGHANDLE m_etwRegHandle;
00121 };
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Sphere Member List

This is the complete list of members for Sphere, including all inherited members.
Active(bool active) | GameObject |
Active() | GameObject |
AnimatePosition(_In_ std::shared_ptr< Animate > const &animate) | GameObject |
AnimatePosition() | GameObject |
GameObject() | GameObject |
Hit(bool hit) | GameObject |
Hit() | GameObject |
HitMaterial(_In_ std::shared_ptr< Material > const &material) | GameObject |
HitMaterial() | GameObject |
HitSound(_In_ std::shared_ptr< SoundEffect > const &hitSound) | GameObject |
HitSound() | GameObject |
HitTime(float t) | GameObject |
HitTime() | GameObject |
IsTouching(DirectX::XMFLOAT3 point, float radius, _Out_ DirectX::XMFLOAT3 *contact, _Out_ DirectX::XMFLOAT3 *normal) override | Sphere | [virtual]
m_modelMatrix | GameObject | [protected]
m_position | GameObject | [protected]
m_radius | Sphere | [private]
Mesh(_In_ std::shared_ptr< MeshObject > const &mesh) | GameObject |
ModelMatrix() | GameObject |
NormalMaterial(_In_ std::shared_ptr< Material > const &material) | GameObject |
NormalMaterial() | GameObject |
OnGround(bool ground) | GameObject |
OnGround() | GameObject |
PlaySound(float impactSpeed, DirectX::XMFLOAT3 eyePoint) | GameObject |
Position(DirectX::XMFLOAT3 position) | Sphere |
Position(DirectX::XMVECTOR position) | Sphere |
GameObject::Position() | GameObject |
Radius(float radius) | Sphere |
Radius() | Sphere |
Render(_In_ ID3D11DeviceContext *context, _In_ ID3D11Buffer *primitiveConstantBuffer) | GameObject |
Sphere() | Sphere |
Sphere(DirectX::XMFLOAT3 pos, float radius) | Sphere |
Target(bool target) | GameObject |
Target() | GameObject |
TargetId(int targetId) | GameObject |
TargetId() | GameObject |
Update() | Sphere | [private]
VectorPosition() | GameObject |
VectorVelocity() | GameObject |
Velocity(DirectX::XMFLOAT3 velocity) | GameObject |
Velocity(DirectX::XMVECTOR velocity) | GameObject |
Velocity() | GameObject |
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CBaseAttributes< TBase > Member List

This is the complete list of members for CBaseAttributes< TBase >, including all inherited members.
_spAttributes | CBaseAttributes< TBase > | [protected]
CBaseAttributes() | CBaseAttributes< TBase > | [inline, protected]
CBaseAttributes(HRESULT &hr, UINT32 cInitialSize=0) | CBaseAttributes< TBase > | [inline, protected]
CBaseAttributes(HRESULT &hr, IUnknown *pUnk) | CBaseAttributes< TBase > | [inline, protected]
Compare(IMFAttributes *pTheirs, MF_ATTRIBUTES_MATCH_TYPE MatchType, BOOL *pbResult) | CBaseAttributes< TBase > | [inline]
CompareItem(REFGUID guidKey, REFPROPVARIANT Value, BOOL *pbResult) | CBaseAttributes< TBase > | [inline]
CopyAllItems(IMFAttributes *pDest) | CBaseAttributes< TBase > | [inline]
DeleteAllItems() | CBaseAttributes< TBase > | [inline]
DeleteItem(REFGUID guidKey) | CBaseAttributes< TBase > | [inline]
DeserializeFromBlob(const UINT8 *pBuffer, UINT cbSize) | CBaseAttributes< TBase > | [inline]
DeserializeFromStream(DWORD dwOptions, IStream *pStm) | CBaseAttributes< TBase > | [inline]
GetAllocatedBlob(REFGUID guidKey, UINT8 **ppBuf, UINT32 *pcbSize) | CBaseAttributes< TBase > | [inline]
GetAllocatedString(REFGUID guidKey, LPWSTR *ppwszValue, UINT32 *pcchLength) | CBaseAttributes< TBase > | [inline]
GetBlob(REFGUID guidKey, UINT8 *pBuf, UINT32 cbBufSize, UINT32 *pcbBlobSize) | CBaseAttributes< TBase > | [inline]
GetBlobSize(REFGUID guidKey, UINT32 *pcbBlobSize) | CBaseAttributes< TBase > | [inline]
GetCount(UINT32 *pcItems) | CBaseAttributes< TBase > | [inline]
GetDouble(REFGUID guidKey, double *pfValue) | CBaseAttributes< TBase > | [inline]
GetGUID(REFGUID guidKey, GUID *pguidValue) | CBaseAttributes< TBase > | [inline]
GetItem(REFGUID guidKey, PROPVARIANT *pValue) | CBaseAttributes< TBase > | [inline]
GetItemByIndex(UINT32 unIndex, GUID *pguidKey, PROPVARIANT *pValue) | CBaseAttributes< TBase > | [inline]
GetItemType(REFGUID guidKey, MF_ATTRIBUTE_TYPE *pType) | CBaseAttributes< TBase > | [inline]
GetRatio(REFGUID guidKey, UINT32 *pnNumerator, UINT32 *punDenominator) | CBaseAttributes< TBase > | [inline]
GetSize(REFGUID guidKey, UINT32 *punWidth, UINT32 *punHeight) | CBaseAttributes< TBase > | [inline]
GetString(REFGUID guidKey, LPWSTR pwszValue, UINT32 cchBufSize, UINT32 *pcchLength) | CBaseAttributes< TBase > | [inline]
GetStringLength(REFGUID guidKey, UINT32 *pcchLength) | CBaseAttributes< TBase > | [inline]
GetUINT32(REFGUID guidKey, UINT32 *punValue) | CBaseAttributes< TBase > | [inline]
GetUINT64(REFGUID guidKey, UINT64 *punValue) | CBaseAttributes< TBase > | [inline]
GetUnknown(REFGUID guidKey, REFIID riid, LPVOID *ppv) | CBaseAttributes< TBase > | [inline]
Initialize(UINT32 cInitialSize=0) | CBaseAttributes< TBase > | [inline, protected]
Initialize(IUnknown *pUnk) | CBaseAttributes< TBase > | [inline, protected]
LockStore() | CBaseAttributes< TBase > | [inline]
SerializeToBlob(UINT8 **ppBuffer, UINT *pcbSize) | CBaseAttributes< TBase > | [inline]
SerializeToStream(DWORD dwOptions, IStream *pStm) | CBaseAttributes< TBase > | [inline]
SetBlob(REFGUID guidKey, const UINT8 *pBuf, UINT32 cbBufSize) | CBaseAttributes< TBase > | [inline]
SetDouble(REFGUID guidKey, double fValue) | CBaseAttributes< TBase > | [inline]
SetGUID(REFGUID guidKey, REFGUID guidValue) | CBaseAttributes< TBase > | [inline]
SetItem(REFGUID guidKey, REFPROPVARIANT Value) | CBaseAttributes< TBase > | [inline]
SetRatio(REFGUID guidKey, UINT32 unNumerator, UINT32 unDenominator) | CBaseAttributes< TBase > | [inline]
SetSize(REFGUID guidKey, UINT32 unWidth, UINT32 unHeight) | CBaseAttributes< TBase > | [inline]
SetString(REFGUID guidKey, LPCWSTR wszValue) | CBaseAttributes< TBase > | [inline]
SetUINT32(REFGUID guidKey, UINT32 unValue) | CBaseAttributes< TBase > | [inline]
SetUINT64(REFGUID guidKey, UINT64 unValue) | CBaseAttributes< TBase > | [inline]
SetUnknown(REFGUID guidKey, IUnknown *pUnknown) | CBaseAttributes< TBase > | [inline]
UnlockStore() | CBaseAttributes< TBase > | [inline]
~CBaseAttributes() | CBaseAttributes< TBase > | [inline, protected, virtual]
Generated on Fri Nov 15 2024 22:23:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_ShowView Member List

This is the complete list of members for Scenario4_ShowView, including all inherited members.
Scenario4_ShowView() | Scenario4_ShowView
TextBox_GotFocus(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario4_ShowView
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiScan/cs/Scenario1_CachedNetworks.xaml.cs Source File

  • WiFiScan
  • cs

Scenario1_CachedNetworks.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using System;
00017 using System.Collections.Generic;
00018 using Windows.Devices.WiFi;
00019 using System.Collections.ObjectModel;
00020
00021 namespace WiFiScan
00022 {
00023     public sealed partial class Scenario1_CachedNetworks : Page
00024     {
00025         private IReadOnlyList<WiFiAdapter> wiFiAdapters;
00026         MainPage rootPage;
00027         public ObservableCollection<WiFiNetworkDisplay> ResultCollection
00028         {
00029             get;
00030             private set;
00031         }
00032
00033         public Scenario1_CachedNetworks()
00034         {
00035             this.InitializeComponent();
00036         }
00037
00038         protected override async void OnNavigatedTo(NavigationEventArgs e)
00039         {
00040             ResultCollection = new ObservableCollection<WiFiNetworkDisplay>();
00041             rootPage = MainPage.Current;
00042
00043             // RequestAccessAsync must have been called at least once by the app before using the API
00044             // Calling it multiple times is fine but not necessary
00045             // RequestAccessAsync must be called from the UI thread
00046             var result = await WiFiAdapter.RequestAccessAsync();
00047             if (result != WiFiAccessStatus.Allowed)
00048             {
00049                 rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
00050             }
00051             else
00052             {
00053                 DataContext = this;
00054
00055                 wiFiAdapters = await WiFiAdapter.FindAllAdaptersAsync();
00056                 int index = 0;
00057                 foreach (var adapter in wiFiAdapters)
00058                 {
00059                     var button = new Button();
00060                     button.Tag = index;
00061                     button.Content = String.Format("WiFi Adapter {0}", ++index);
00062                     button.Click += Button_Click;
00063                     Buttons.Children.Add(button);
00064                 }
00065             }
00066         }
00067
00068         private void Button_Click(object sender, RoutedEventArgs e)
00069         {
00070             var button = (Button)sender;
00071             var index = (int)button.Tag;
00072
00073             // Accessing the NetworkReport property from the WiFiAdapter does not trigger any scans.
00074             // The NetworkReport will have the report generated by the last scan on the system; the
00075             // scan need not be generated by the app.
00076             DisplayNetworkReport(wiFiAdapters[index].NetworkReport, wiFiAdapters[index]);
00077         }
00078
00079         private async void DisplayNetworkReport(WiFiNetworkReport report, WiFiAdapter adapter)
00080         {
00081             rootPage.NotifyUser(string.Format("Network Report Timestamp: {0}", report.Timestamp), NotifyType.StatusMessage);
00082
00083             ResultCollection.Clear();
00084
00085             foreach (var network in report.AvailableNetworks)
00086             {
00087                 var networkDisplay = new WiFiNetworkDisplay(network, adapter);
00088                 await networkDisplay.UpdateConnectivityLevel();
00089                 ResultCollection.Add(networkDisplay);
00090             }
00091         }
00092     }
00093 }
Generated on Fri Nov 15 2024 22:22:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ShareWebLink Member List

This is the complete list of members for ShareWebLink, including all inherited members.
GetShareContent(DataRequest request) | ShareWebLink | [inline, protected]
ShareWebLink() | ShareWebLink | [inline]
ValidateAndGetUri(string uriString) | ShareWebLink | [inline, private]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cppwinrt/SampleConfiguration.cpp Source File

  • Clipboard
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::ApplicationModel::DataTransfer;
00021 using namespace Windows::Data::Xml::Dom;
00022 using namespace Windows::UI::Core;
00023 using namespace Windows::UI::Notifications;
00024 using namespace Windows::UI::Xaml;
00025 using namespace SDKTemplate;
00026
00027 hstring implementation::MainPage::FEATURE_NAME()
00028 {
00029     return L"Clipboard C++/WinRT Sample";
00030 }
00031
00032 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00033 {
00034     Scenario{ L"Copy and paste text", xaml_typename<SDKTemplate::CopyText>() },
00035     Scenario{ L"Copy and paste an image", xaml_typename<SDKTemplate::CopyImage>() },
00036     Scenario{ L"Copy and paste files", xaml_typename<SDKTemplate::CopyFiles>() },
00037     Scenario{ L"History and roaming", xaml_typename<SDKTemplate::HistoryAndRoaming>() },
00038     Scenario{ L"Other Clipboard operations", xaml_typename<SDKTemplate::OtherScenarios>() },
00039 });
00040
00041 event_token SampleState::clipboardContentChangedToken;
00042 event_token SampleState::activatedToken;
00043 bool SampleState::isClipboardContentChangedEnabled = false;
00044 bool SampleState::needToPrintClipboardFormat = false;
00045 bool SampleState::isApplicationWindowActive = true;
00046
00047 ToastNotification SampleState::DisplayToast(hstring const& message)
00048 {
00049     static constexpr wchar_t xml[] =
00050         LR"(<toast activationType='foreground'>
00051                <visual>
00052                    <binding template='ToastGeneric'/>
00053                </visual>
00054            </toast>)";
00055
00056     XmlDocument doc;
00057     doc.LoadXml(xml);
00058
00059     auto binding = doc.SelectSingleNode(L"//binding");
00060
00061     auto el = doc.CreateElement(L"text");
00062     el.InnerText(MainPage::FEATURE_NAME());
00063     binding.AppendChild(el);
00064
00065     el = doc.CreateElement(L"text");
00066     el.InnerText(message);
00067     binding.AppendChild(el);
00068
00069     ToastNotification toast(doc);
00070
00071     ToastNotificationManager::CreateToastNotifier().Show(toast);
00072     return toast;
00073 }
00074
00075 bool SampleState::IsClipboardContentChangedEnabled()
00076 {
00077     return isClipboardContentChangedEnabled;
00078 }
00079
00080 bool SampleState::EnableClipboardContentChangedNotifications(bool enable)
00081 {
00082     if (isClipboardContentChangedEnabled == enable)
00083     {
00084         return false;
00085     }
00086
00087     if (enable)
00088     {
00089         clipboardContentChangedToken = Clipboard::ContentChanged(OnClipboardChanged);
00090         activatedToken = Window::Current().Activated(OnWindowActivated);
00091     }
00092     else
00093     {
00094         Clipboard::ContentChanged(clipboardContentChangedToken);
00095         Window::Current().Activated(activatedToken);
00096     }
00097     return true;
00098 }
00099
00100 hstring SampleState::BuildClipboardFormatsOutputString()
00101 {
00102     std::wostringstream output;
00103     AddClipboardFormatsOutputString(output);
00104     return hstring{ output.str() };
00105 }
00106
00107 void SampleState::AddClipboardFormatsOutputString(std::wostringstream& output)
00108 {
00109     DataPackageView clipboardContent = Clipboard::GetContent();
00110
00111     if (clipboardContent && clipboardContent.AvailableFormats().Size() > 0)
00112     {
00113         output << L"Available formats in the clipboard:";
00114         for (auto&& format : clipboardContent.AvailableFormats())
00115         {
00116             output << std::endl << L" * " << std::wstring_view(format);
00117         }
00118     }
00119     else
00120     {
00121         output << L"The clipboard is empty";
00122     }
00123 }
00124
00125 void SampleState::DisplayChangedFormats()
00126 {
00127     std::wostringstream output;
00128     output << L"Clipboard content has changed!" << std::endl;
00129     AddClipboardFormatsOutputString(output);
00130     MainPage::Current().NotifyUser(output.str(), NotifyType::StatusMessage);
00131 }
00132
00133 void SampleState::HandleClipboardChanged()
00134 {
00135     if (isApplicationWindowActive)
00136     {
00137         DisplayChangedFormats();
00138     }
00139     else
00140     {
00141         // Background applications can't access clipboard
00142         // Deferring processing of update notification until the application returns to foreground
00143         needToPrintClipboardFormat = true;
00144     }
00145 }
00146 void SampleState::OnWindowActivated(IInspectable const&, WindowActivatedEventArgs const& e)
00147 {
00148     isApplicationWindowActive = (e.WindowActivationState() != CoreWindowActivationState::Deactivated);
00149     if (needToPrintClipboardFormat)
00150     {
00151         // The clipboard was updated while the sample was in the background. If the sample is now in the foreground,
00152         // display the new content.
00153         HandleClipboardChanged();
00154     }
00155 }
00156
00157 void SampleState::OnClipboardChanged(IInspectable const&, IInspectable const&)
00158 {
00159     DisplayToast(L"Clipboard changed.");
00160     HandleClipboardChanged();
00161 }
00162
Generated on Fri Nov 15 2024 22:17:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/06_Combine_Casting_Tech.xaml.cs Source File

  • AdvancedCasting
  • cs

06_Combine_Casting_Tech.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Foundation;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Navigation;
00017 using Windows.UI.Xaml.Media;
00018 using Windows.Media.DialProtocol;
00019 using ScreenCasting.Data.Azure;
00020 using ScreenCasting.Data.Common;
00021 using Windows.Devices.Enumeration;
00022 using System.Threading.Tasks;
00023 using Windows.Media.Casting;
00024 using ScreenCasting.Controls;
00025 using ScreenCasting.Util;
00026 using Windows.UI.ViewManagement;
00027 using Windows.ApplicationModel.Core;
00028 using Windows.UI.Core;
00029 using Windows.Storage;
00030
00031 namespace ScreenCasting
00032 {
00033     public sealed partial class Scenario06 : Page
00034     {
00035         private const int MAX_RESULTS = 10;
00036
00037         private MainPage rootPage;
00038         private DevicePicker picker = null;
00039         private DeviceInformation activeDevice = null;
00040         private object activeCastConnectionHandler = null;
00041         private VideoMetaData video = null;
00042         int thisViewId;
00043
00044         public Scenario06()
00045         {
00046             this.InitializeComponent();
00047
00048             rootPage = MainPage.Current;
00049
00050             //Subscribe to player events
00051             player.MediaOpened += Player_MediaOpened;
00052             player.MediaFailed += Player_MediaFailed;
00053             player.CurrentStateChanged += Player_CurrentStateChanged;
00054
00055             // Get an Azure hosted video
00056             AzureDataProvider dataProvider = new AzureDataProvider();
00057             video = dataProvider.GetRandomVideo();
00058
00059             //Set the source on the player
00060             rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage);
00061             this.player.Source = video.VideoLink;
00062             this.LicenseText.Text = "License: " + video.License;
00063
00064             //Configure the DIAL launch arguments for the current video
00065             this.dial_launch_args_textbox.Text = string.Format("v={0}&t=0&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id);
00066
00067             //Subscribe for the clicked event on the custom cast button
00068             ((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked;
00069
00070             // Instantiate the Device Picker
00071             picker = new DevicePicker();
00072
00073             //Hook up device selected event
00074             picker.DeviceSelected += Picker_DeviceSelected;
00075
00076             //Hook up device disconnected event
00077             picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked;
00078
00079             //Hook up device disconnected event
00080             picker.DevicePickerDismissed += Picker_DevicePickerDismissed;
00081
00082             //Add the DIAL Filter, so that the application only shows DIAL devices that have the application installed or advertise that they can install them.
00083             //BUG: picker.Filter.SupportedDeviceSelectors.Add(DialDevice.GetDeviceSelector(this.dial_appname_textbox.Text));
00084             picker.Filter.SupportedDeviceSelectors.Add("System.Devices.DevObjectType:=6 AND System.Devices.AepContainer.ProtocolIds:~~{0E261DE4-12F0-46E6-91BA-428607CCEF64} AND System.Devices.AepContainer.Categories:~~Multimedia.ApplicationLauncher.DIAL");
00085
00086             //Add the CAST API Filter, so that the application only shows Miracast, Bluetooth, DLNA devices that can render the video
00087             // BUG: picker.Filter.SupportedDeviceSelectors.Add(await CastingDevice.GetDeviceSelectorFromCastingSourceAsync(player.GetAsCastingSource()));
00088             // BUG: picker.Filter.SupportedDeviceSelectors.Add(CastingDevice.GetDeviceSelector(CastingPlaybackTypes.Video));
00089             picker.Filter.SupportedDeviceSelectors.Add("System.Devices.InterfaceClassGuid:=\"{D0875FB4-2196-4c7a-A63D-E416ADDD60A1}\"" + " AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True");
00090
00091             //Add projection manager filter
00092             picker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector());
00093
00094             pvb.ProjectionStopping += Pvb_ProjectionStopping;
00095         }
00096
00097         ProjectionViewBroker pvb = new ProjectionViewBroker();
00098
00099         private void TransportControls_CastButtonClicked(object sender, EventArgs e)
00100         {
00101             //Pause Current Playback
00102             player.Pause();
00103
00104             rootPage.NotifyUser("Show Device Picker Button Clicked", NotifyType.StatusMessage);
00105
00106             //Get the custom transport controls
00107             MediaTransportControlsWithCustomCastButton mtc = (MediaTransportControlsWithCustomCastButton)this.player.TransportControls;
00108             //Retrieve the location of the casting button
00109             GeneralTransform transform = mtc.CastButton.TransformToVisual(Window.Current.Content as UIElement);
00110             Point pt = transform.TransformPoint(new Point(0, 0));
00111
00112             //Show the picker above our Show Device Picker button
00113             picker.Show(new Rect(pt.X, pt.Y, mtc.CastButton.ActualWidth, mtc.CastButton.ActualHeight), Windows.UI.Popups.Placement.Above);
00114         }
00115
00116         #region Windows.Devices.Enumeration.DevicePicker Methods
00117         private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
00118         {
00119             string deviceId = args.SelectedDevice.Id;
00120
00121             //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
00122             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
00123             {
00124                 //Update the display status for the selected device to connecting.
00125                 try { picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress); } catch { }
00126
00127                 //The selectedDeviceInfo instance is needed to be able to update the picker.
00128                 DeviceInformation selectedDeviceInfo = args.SelectedDevice;
00129 #if DEBUG
00130                 // The args.SelectedCastingDevice is proxied from the picker process. The picker process is
00131                 // dismissmed as soon as you break into the debugger. Creating a non-proxied version
00132                 // allows debugging since the proxied version stops working once the picker is dismissed.
00133                 selectedDeviceInfo = await DeviceInformation.CreateFromIdAsync(args.SelectedDevice.Id);
00134 #endif
00135
00136                 bool castSucceeded = false;
00137
00138                 // If the ProjectionManager API did not work and the device id will have 'dial' in it.
00139                 castSucceeded = await TryLaunchDialAppAsync(selectedDeviceInfo);
00140
00141                 // If it doesn't try the ProjectionManager API.
00142                 if (!castSucceeded)
00143                     castSucceeded = await TryProjectionManagerCastAsync(selectedDeviceInfo);
00144
00145                 //If DIAL and ProjectionManager did not work for the selected device, try the CAST API
00146                 if (!castSucceeded)
00147                     castSucceeded = await TryCastMediaElementAsync(selectedDeviceInfo);
00148
00149                 if (castSucceeded)
00150                 {
00151                     //Update the display status for the selected device.  Try Catch in case the picker is not visible anymore.
00152                     try { picker.SetDisplayStatus(selectedDeviceInfo, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton); } catch { }
00153
00154                     // Hide the picker now that all the work is completed. Try Catch in case the picker is not visible anymore.
00155                     try { picker.Hide(); } catch { }
00156                 }
00157                 else
00158                 {
00159                     //Show a retry button when connecting to the selected device failed.
00160                     try { picker.SetDisplayStatus(selectedDeviceInfo, "Connecting failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { }
00161                 }
00162             });
00163         }
00164         private async void Picker_DevicePickerDismissed(DevicePicker sender, object args)
00165         {
00166             //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
00167             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00168             {
00169                 if (activeDevice == null)
00170                 {
00171                     player.Play();
00172                 }
00173             });
00174         }
00175         private async void Picker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args)
00176         {
00177             //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
00178             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
00179             {
00180                 rootPage.NotifyUser("Disconnect Button clicked", NotifyType.StatusMessage);
00181
00182                 //Update the display status for the selected device.
00183                 sender.SetDisplayStatus(args.Device, "Disconnecting", DevicePickerDisplayStatusOptions.ShowProgress);
00184
00185                 bool disconnected = false;
00186                 if (this.activeCastConnectionHandler is ProjectionViewBroker)
00187                     disconnected = TryStopProjectionManagerAsync((ProjectionViewBroker)activeCastConnectionHandler);
00188                 if (this.activeCastConnectionHandler is DialApp)
00189                     disconnected = await TryStopDialAppAsync((DialApp)activeCastConnectionHandler);
00190                 if (this.activeCastConnectionHandler is CastingConnection)
00191                     disconnected = await TryDisconnectCastingSessionAsync((CastingConnection)activeCastConnectionHandler);
00192
00193                 if (disconnected)
00194                 {
00195                     //Update the display status for the selected device.
00196                     try { sender.SetDisplayStatus(args.Device, "Disconnected", DevicePickerDisplayStatusOptions.None); } catch { }
00197                     // Set the active device variables to null
00198                     activeDevice = null;
00199                     activeCastConnectionHandler = null;
00200
00201                     //Hide the picker
00202                     sender.Hide();
00203                 }
00204                 else
00205                 {
00206                     //Update the display status for the selected device.
00207                     sender.SetDisplayStatus(args.Device, "Disconnect failed", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
00208                 }
00209             });
00210         }
00211
00212         #endregion
00213
00214         #region ProjectionManager APIs
00215         private async Task<bool> TryProjectionManagerCastAsync(DeviceInformation device)
00216         {
00217             bool projectionManagerCastAsyncSucceeded = false;
00218
00219             if ((activeDevice ==null && ProjectionManager.ProjectionDisplayAvailable && device == null) || device != null)
00220             {
00221                 thisViewId = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Id;
00222
00223                 // If projection is already in progress, then it could be shown on the monitor again
00224                 // Otherwise, we need to create a new view to show the presentation
00225                 if (rootPage.ProjectionViewPageControl == null)
00226                 {
00227                     // First, create a new, blank view
00228                     var thisDispatcher = Window.Current.Dispatcher;
00229                     await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00230                     {
00231                         // ViewLifetimeControl is a wrapper to make sure the view is closed only
00232                         // when the app is done with it
00233                         rootPage.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView();
00234
00235                         // Assemble some data necessary for the new page
00236                         pvb.MainPageDispatcher = thisDispatcher;
00237                         pvb.ProjectionViewPageControl = rootPage.ProjectionViewPageControl;
00238                         pvb.MainViewId = thisViewId;
00239
00240                         // Display the page in the view. Note that the view will not become visible
00241                         // until "StartProjectingAsync" is called
00242                         var rootFrame = new Frame();
00243                         rootFrame.Navigate(typeof(ProjectionViewPage), pvb);
00244                         Window.Current.Content = rootFrame;
00245                         Window.Current.Activate();
00246                     });
00247                 }
00248
00249                 try
00250                 {
00251                     // Start/StopViewInUse are used to signal that the app is interacting with the
00252                     // view, so it shouldn't be closed yet, even if the user loses access to it
00253                     rootPage.ProjectionViewPageControl.StartViewInUse();
00254
00255                     try
00256                     {
00257                         rootPage.NotifyUser(string.Format("Starting projection of '{0}' on a second view '{1}' using ProjectionManager", video.Title, device.Name), NotifyType.StatusMessage);
00258
00259                         await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId, device);
00260                     }
00261                     catch (Exception ex)
00262                     {
00263                         if (!ProjectionManager.ProjectionDisplayAvailable)
00264                             throw ex;
00265                     }
00266
00267                     if (pvb.ProjectedPage != null)
00268                     {
00269                         this.player.Pause();
00270                         await pvb.ProjectedPage.SetMediaSource(this.player.Source, this.player.Position);
00271                     }
00272                     if (device != null)
00273                     {
00274                         activeDevice = device;
00275                         activeCastConnectionHandler = pvb;
00276                     }
00277                     projectionManagerCastAsyncSucceeded = true;
00278
00279                     rootPage.NotifyUser(string.Format("Displaying '{0}' on a second view '{1}' using ProjectionManager", video.Title, device.Name), NotifyType.StatusMessage);
00280                 }
00281                 catch (Exception)
00282                 {
00283                     rootPage.NotifyUser("The projection view is being disposed", NotifyType.ErrorMessage);
00284                 }
00285                 ApplicationView.GetForCurrentView().ExitFullScreenMode();
00286             }
00287                 return projectionManagerCastAsyncSucceeded;
00288         }
00289         private bool TryStopProjectionManagerAsync(ProjectionViewBroker broker)
00290         {
00291             broker.ProjectedPage.StopProjecting();
00292             return true;
00293         }
00294
00295
00296         private async void Pvb_ProjectionStopping(object sender, EventArgs e)
00297         {
00298             ProjectionViewBroker broker = sender as ProjectionViewBroker;
00299
00300             TimeSpan position;
00301             Uri source = null;
00302
00303             await broker.ProjectedPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00304             {
00305                 position = broker.ProjectedPage.Player.Position;
00306                 source = broker.ProjectedPage.Player.Source;
00307             });
00308
00309             await rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00310             {
00311                 rootPage.NotifyUser("Resuming playback on the first screen", NotifyType.StatusMessage);
00312                 this.player.Source = source;
00313                 this.player.Position = position;
00314                 this.player.Play();
00315                 rootPage.ProjectionViewPageControl = null;
00316             });
00317         }
00318
00319         #endregion
00320
00321         #region Windows.Media.Casting APIs
00322
00323         private async Task<bool> TryCastMediaElementAsync(DeviceInformation device)
00324         {
00325             bool castMediaElementSucceeded = false;
00326
00327             //Verify whether the selected device supports DLNA, Bluetooth, or Miracast.
00328             rootPage.NotifyUser(string.Format("Checking to see if device {0} supports Miracast, Bluetooth, or DLNA", device.Name), NotifyType.StatusMessage);
00329
00330             CastingConnection connection = null;
00331
00332             //Check to see whether we are casting to the same device
00333             if (activeDevice != null && device.Id == activeDevice.Id)
00334                 connection = activeCastConnectionHandler as CastingConnection;
00335             else // if not casting to the same device reset the active device related variables.
00336             {
00337                 activeDevice = null;
00338                 activeCastConnectionHandler = null;
00339             }
00340
00341             // If we can re-use the existing connection
00342             if (connection == null || connection.State == CastingConnectionState.Disconnected || connection.State == CastingConnectionState.Disconnecting)
00343             {
00344                 CastingDevice castDevice = null;
00345                 activeDevice = null;
00346
00347                 //Try to create a CastingDevice instannce. If it doesn't succeed, the selected device does not support playback of the video source.
00348                 rootPage.NotifyUser(string.Format("Attempting to resolve casting device for '{0}'", device.Name), NotifyType.StatusMessage);
00349                 try { castDevice = await CastingDevice.FromIdAsync(device.Id); } catch { }
00350
00351                 if (castDevice == null)
00352                 {
00353                     //Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
00354                     rootPage.NotifyUser(string.Format("'{0}' does not support playback of this media", device.Name), NotifyType.StatusMessage);
00355                 }
00356                 else
00357                 {
00358                     //Create a casting conneciton from our selected casting device
00359                     rootPage.NotifyUser(string.Format("Creating connection for '{0}'", device.Name), NotifyType.StatusMessage);
00360                     connection = castDevice.CreateCastingConnection();
00361
00362                     //Hook up the casting events
00363                     connection.ErrorOccurred += Connection_ErrorOccurred;
00364                     connection.StateChanged += Connection_StateChanged;
00365                 }
00366
00367                 //Cast the content loaded in the media element to the selected casting device
00368                 rootPage.NotifyUser(string.Format("Casting to '{0}'", device.Name), NotifyType.StatusMessage);
00369
00370                 CastingSource source = null;
00371                 // Get the casting source
00372                 try { source = player.GetAsCastingSource(); } catch { }
00373
00374                 if (source == null)
00375                 {
00376                     rootPage.NotifyUser(string.Format("Failed to get casting source for video '{0}'", video.Title), NotifyType.ErrorMessage);
00377                 }
00378                 else
00379                 {
00380                     CastingConnectionErrorStatus status = await connection.RequestStartCastingAsync(source);
00381
00382                     if (status == CastingConnectionErrorStatus.Succeeded)
00383                     {
00384                         //Remember the device to which casting succeeded
00385                         activeDevice = device;
00386                         //Remember the current active connection.
00387                         activeCastConnectionHandler = connection;
00388                         castMediaElementSucceeded = true;
00389                         player.Play();
00390                     }
00391                     else
00392                     {
00393                         rootPage.NotifyUser(string.Format("Failed to cast to '{0}'", device.Name), NotifyType.ErrorMessage);
00394                     }
00395                 }
00396             }
00397             return castMediaElementSucceeded;
00398         }
00399         private async void Connection_StateChanged(CastingConnection sender, object args)
00400         {
00401             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00402             {
00403                 rootPage.NotifyUser("Casting Connection State Changed: " + sender.State, NotifyType.StatusMessage);
00404             });
00405         }
00406         private async void Connection_ErrorOccurred(CastingConnection sender, CastingConnectionErrorOccurredEventArgs args)
00407         {
00408             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00409             {
00410                 rootPage.NotifyUser("Casting Error Occured: " + args.Message, NotifyType.ErrorMessage);
00411                 activeDevice = null;
00412                 activeCastConnectionHandler = null;
00413             });
00414         }
00415         private async Task<bool> TryDisconnectCastingSessionAsync(CastingConnection connection)
00416         {
00417             bool disconnected = false;
00418
00419             //Disconnect the casting session
00420             CastingConnectionErrorStatus status = await connection.DisconnectAsync();
00421
00422             if (status == CastingConnectionErrorStatus.Succeeded)
00423             {
00424                 rootPage.NotifyUser("Connection disconnected successfully.", NotifyType.StatusMessage);
00425                 disconnected = true;
00426             }
00427             else
00428             {
00429                 rootPage.NotifyUser(string.Format("Failed to disconnect connection with reason {0}.", status.ToString()), NotifyType.ErrorMessage);
00430             }
00431
00432             return disconnected;
00433         }
00434
00435         #endregion
00436
00437         #region Windows.Media.DialProtocol APIs
00438         private async Task<bool> TryLaunchDialAppAsync(DeviceInformation device)
00439         {
00440             bool dialAppLaunchSucceeded = false;
00441
00442             //Update the launch arguments to include the Position
00443             this.dial_launch_args_textbox.Text = string.Format("v={0}&t={1}&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id, player.Position.Ticks);
00444
00445             //Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
00446             rootPage.NotifyUser(string.Format("Checking to see if device {0} supports DIAL", device.Name), NotifyType.StatusMessage);
00447
00448             DialDevice dialDevice = null;
00449
00450             //Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
00451             rootPage.NotifyUser(string.Format("Attempting to resolve DIAL device for '{0}'", device.Name), NotifyType.StatusMessage);
00452
00453             string[] newIds = (string[])device.Properties["{0BBA1EDE-7566-4F47-90EC-25FC567CED2A} 2"];
00454
00455             if (newIds.Length > 0)
00456             {
00457                 string deviceId = newIds[0];
00458                 try { dialDevice = await DialDevice.FromIdAsync(deviceId); } catch { }
00459             }
00460
00461             if (dialDevice == null)
00462             {
00463                 //Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
00464                 rootPage.NotifyUser(string.Format("'{0}' does not support DIAL", device.Name), NotifyType.StatusMessage);
00465             }
00466             else
00467             {
00468                 //Get the DialApp object for the specific application on the selected device
00469                 DialApp app = dialDevice.GetDialApp(this.dial_appname_textbox.Text);
00470
00471                 if (app == null)
00472                 {
00473                     //Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
00474                     rootPage.NotifyUser(string.Format("'{0}' cannot find app with ID '{1}'", device.Name, this.dial_appname_textbox.Text), NotifyType.StatusMessage);
00475                 }
00476                 else
00477                 {
00478                     rootPage.NotifyUser(string.Format("Attempting to launch '{0}'", app.AppName), NotifyType.StatusMessage);
00479                     //Launch the application on the 1st screen device
00480                     DialAppLaunchResult result = await app.RequestLaunchAsync(this.dial_launch_args_textbox.Text);
00481
00482                     //Verify to see whether the application was launched
00483                     if (result == DialAppLaunchResult.Launched)
00484                     {
00485                         //Remember the device to which casting succeeded
00486                         activeDevice = device;
00487                         //DIAL is sessionsless but the DIAL app allows us to get the state and "disconnect".
00488                         //Disconnect in the case of DIAL is equivalenet to stopping the app.
00489                         activeCastConnectionHandler = app;
00490                         rootPage.NotifyUser(string.Format("Launched '{0}'", app.AppName), NotifyType.StatusMessage);
00491                         //This is where you will need to add you application specific communication between your 1st and 2nd screen applications
00492                         //...
00493
00494
00495                         dialAppLaunchSucceeded = true;
00496                     }
00497                 }
00498             }
00499
00500             return dialAppLaunchSucceeded;
00501         }
00502         private async Task<bool> TryStopDialAppAsync(DialApp app)
00503         {
00504             bool stopped = false;
00505
00506             //Get the current application state
00507             DialAppStateDetails stateDetails = await app.GetAppStateAsync();
00508
00509             switch (stateDetails.State)
00510             {
00511                 case DialAppState.NetworkFailure:
00512                     {
00513                         // In case getting the application state failed because of a network failure, you could add retry logic
00514                         rootPage.NotifyUser("Network Failure while getting application state", NotifyType.ErrorMessage);
00515                         break;
00516                     }
00517                 case DialAppState.Stopped:
00518                     {
00519                         stopped = true;
00520                         // In case getting the application state failed because of a network failure, you could add retry logic
00521                         rootPage.NotifyUser("Application was already stopped.", NotifyType.StatusMessage);
00522                         break;
00523                     }
00524                 default:
00525                     {
00526                         DialAppStopResult result = await app.StopAsync();
00527
00528                         if (result == DialAppStopResult.Stopped)
00529                         {
00530                             stopped = true;
00531                             // In case getting the application state failed because of a network failure, you could add retry logic
00532                             rootPage.NotifyUser("Application stopped successfully.", NotifyType.StatusMessage);
00533                         }
00534                         else
00535                         {
00536                             if (result == DialAppStopResult.StopFailed || result == DialAppStopResult.NetworkFailure)
00537                             {
00538                                 // In case getting the application state failed because of a network failure, you could add retry logic
00539                                 rootPage.NotifyUser(string.Format("Error occured trying to stop application. Status: '{0}'", result.ToString()), NotifyType.StatusMessage);
00540                             }
00541                             else //in case of DialAppStopResult.OperationNotSupported, there is not much more you can do. You could implement your own
00542                             // mechanism to stop the application on that device.
00543                             {
00544                                 stopped = true;
00545                                 // In case getting the application state failed because of a network failure, you could add retry logic
00546                                 rootPage.NotifyUser(string.Format("Stop is not supported by device: '{0}'", activeDevice.Name), NotifyType.ErrorMessage);
00547                             }
00548                         }
00549                         break;
00550                     }
00551             }
00552             return stopped;
00553         }
00554
00555         #endregion
00556
00557         #region Media Element Status Methods
00558         private void Player_CurrentStateChanged(object sender, RoutedEventArgs e)
00559         {
00560             // Update status
00561             rootPage.NotifyUser(string.Format("{0} '{1}'", this.player.CurrentState, video.Title), NotifyType.StatusMessage);
00562         }
00563         private void Player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
00564         {
00565             rootPage.NotifyUser(string.Format("Failed to load '{0}'", video.Title), NotifyType.ErrorMessage);
00566         }
00567         private void Player_MediaOpened(object sender, RoutedEventArgs e)
00568         {
00569             rootPage.NotifyUser(string.Format("Openend '{0}'", video.Title), NotifyType.StatusMessage);
00570
00571             player.Play();
00572         }
00573
00574         #endregion
00575         protected override void OnNavigatedTo(NavigationEventArgs e)
00576         {
00577             rootPage = MainPage.Current;
00578         }
00579
00580     }
00581 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaTranscoding/cpp/Scenario1_Default.xaml.cpp Source File

  • MediaTranscoding
  • cpp

Scenario1_Default.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_Default.xaml.h"
00013
00014 using namespace SDKTemplate;
00015 using namespace Windows::UI::Xaml;
00016 using namespace Windows::UI::Xaml::Controls;
00017 using namespace Windows::UI::Xaml::Navigation;
00018 using namespace Windows::Storage::Streams;
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Media;
00022 using namespace Windows::Media::MediaProperties;
00023 using namespace Windows::Media::Transcoding;
00024 using namespace Windows::Storage;
00025 using namespace Windows::Storage::Pickers;
00026 using namespace Windows::Storage::Streams;
00027 using namespace concurrency;
00028
00029 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00030
00031 Scenario1_Default::Scenario1_Default()
00032 {
00033     InitializeComponent();
00034
00035     // Hook up UI
00036     PickFileButton->Click += ref new RoutedEventHandler(this, &Scenario1_Default::PickFile);
00037     SetOutputButton->Click += ref new RoutedEventHandler(this, &Scenario1_Default::PickOutput);
00038     TargetFormat->SelectionChanged += ref new SelectionChangedEventHandler(this, &Scenario1_Default::OnTargetFormatChanged);
00039     Transcode->Click += ref new RoutedEventHandler(this, &Scenario1_Default::TranscodePreset);
00040     Cancel->Click += ref new RoutedEventHandler(this, &Scenario1_Default::TranscodeCancel);
00041
00042     // Media Controls
00043     InputPlayButton->Click += ref new RoutedEventHandler(this, &Scenario1_Default::InputPlayButton_Click);
00044     InputPauseButton->Click += ref new RoutedEventHandler(this, &Scenario1_Default::InputPauseButton_Click);
00045     InputStopButton->Click += ref new RoutedEventHandler(this, &Scenario1_Default::InputStopButton_Click);
00046     OutputPlayButton->Click += ref new RoutedEventHandler(this, &Scenario1_Default::OutputPlayButton_Click);
00047     OutputPauseButton->Click += ref new RoutedEventHandler(this, &Scenario1_Default::OutputPauseButton_Click);
00048     OutputStopButton->Click += ref new RoutedEventHandler(this, &Scenario1_Default::OutputStopButton_Click);
00049
00050     // File is not selected, disable all buttons but PickFileButton
00051     DisableButtons();
00052     SetPickFileButton(true);
00053     SetCancelButton(false);
00054
00055     // Initialize Objects
00056     _Transcoder = ref new MediaTranscoder();
00057     _Profile = nullptr;
00058     _InputFile = nullptr;
00059     _OutputFile = nullptr;
00060     _OutputFileName = "TranscodeSampleOutput.mp4";
00061     _CTS = cancellation_token_source();
00062
00063     // Initial values
00064     _OutputType = "MP4";
00065     _OutputFileExtension = ".mp4";
00066 }
00067
00068 /// <summary>
00069 /// Invoked when this page is about to be displayed in a Frame.
00070 /// </summary>
00071 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00072 /// property is typically used to configure the page.</param>
00073 void Scenario1_Default::OnNavigatedTo(NavigationEventArgs^ e)
00074 {
00075     // A pointer back to the main page.  This is needed if you want to call methods in Presets such
00076     // as NotifyUser()
00077     rootPage = MainPage::Current;
00078 }
00079
00080 void Scenario1_Default::GetPresetProfile(ComboBox^ comboBox)
00081 {
00082     _Profile = nullptr;
00083     VideoEncodingQuality videoEncodingProfile = VideoEncodingQuality::Wvga;
00084     switch (comboBox->SelectedIndex)
00085     {
00086     case 0:
00087         videoEncodingProfile = VideoEncodingQuality::HD1080p;
00088         break;
00089     case 1:
00090         videoEncodingProfile = VideoEncodingQuality::HD720p;
00091         break;
00092     case 2:
00093         videoEncodingProfile = VideoEncodingQuality::Wvga;
00094         break;
00095     case 3:
00096         videoEncodingProfile = VideoEncodingQuality::Ntsc;
00097         break;
00098     case 4:
00099         videoEncodingProfile = VideoEncodingQuality::Pal;
00100         break;
00101     case 5:
00102         videoEncodingProfile = VideoEncodingQuality::Vga;
00103         break;
00104     case 6:
00105         videoEncodingProfile = VideoEncodingQuality::Qvga;
00106         break;
00107     }
00108
00109     if (_OutputType == "AVI")
00110     {
00111         _Profile = MediaEncodingProfile::CreateAvi(videoEncodingProfile);
00112     }
00113     else if (_OutputType == "WMV")
00114     {
00115         _Profile = MediaEncodingProfile::CreateWmv(videoEncodingProfile);
00116     }
00117     else
00118     {
00119         _Profile = MediaEncodingProfile::CreateMp4(videoEncodingProfile);
00120     }
00121
00122     /*
00123     For transcoding to audio profiles, create the encoding profile using one of these APIs:
00124     MediaEncodingProfile::CreateMp3(audioEncodingProfile)
00125     MediaEncodingProfile::CreateM4a(audioEncodingProfile)
00126     MediaEncodingProfile::CreateWma(audioEncodingProfile)
00127     MediaEncodingProfile::CreateWav(audioEncodingProfile)
00128
00129     where audioEncodingProfile is one of these presets:
00130     AudioEncodingQuality::High
00131     AudioEncodingQuality::Medium
00132     AudioEncodingQuality::Low
00133     */
00134 }
00135
00136 void Scenario1_Default::TranscodePreset(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00137 {
00138     StopPlayers();
00139     DisableButtons();
00140     GetPresetProfile(ProfileSelect);
00141
00142     if ((EnableMrfCrf444->IsChecked != nullptr) && (EnableMrfCrf444->IsChecked->Value))
00143     {
00144         _Transcoder->VideoProcessingAlgorithm = Windows::Media::Transcoding::MediaVideoProcessingAlgorithm::MrfCrf444;
00145     }
00146     else
00147     {
00148         _Transcoder->VideoProcessingAlgorithm = Windows::Media::Transcoding::MediaVideoProcessingAlgorithm::Default;
00149     }
00150
00151     // Clear messages
00152     StatusMessage->Text = "";
00153
00154     try
00155     {
00156         if ((_InputFile != nullptr) && (_OutputFile != nullptr))
00157         {
00158             create_task(_Transcoder->PrepareFileTranscodeAsync(_InputFile, _OutputFile, _Profile)).then(
00159                 [this](PrepareTranscodeResult^ transcode)
00160             {
00161                 try
00162                 {
00163                     if (transcode->CanTranscode)
00164                     {
00165                         OutputMsg->Text = "";
00166                         SetCancelButton(true);
00167                         Windows::Foundation::IAsyncActionWithProgress<double>^ transcodeOp = transcode->TranscodeAsync();
00168
00169                         // Set Progress Callback
00170                         transcodeOp->Progress = ref new AsyncActionProgressHandler<double>(
00171                             [this](IAsyncActionWithProgress<double>^ asyncInfo, double percent) {
00172                             TranscodeProgress(asyncInfo, percent);
00173                         }, Platform::CallbackContext::Same);
00174
00175                         return transcodeOp;
00176                     }
00177                     else
00178                     {
00179                         TranscodeFailure(transcode->FailureReason);
00180                     }
00181                 }
00182                 catch (Platform::Exception^ exception)
00183                 {
00184                     TranscodeError(exception->Message);
00185                 }
00186
00187                 cancel_current_task();
00188             }).then(
00189                 [this](task<void> transcodeTask)
00190             {
00191                 try
00192                 {
00193                     transcodeTask.get();
00194                     OutputMsg->Text = "Transcode Completed.";
00195                     OutputPath->Text = "Output (" + _OutputFile->Path + ")";
00196                     PlayFile(_OutputFile);
00197                 }
00198                 catch (task_canceled&)
00199                 {
00200                     OutputMsg->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red);
00201                     OutputMsg->Text = "Transcode Cancelled.";
00202                 }
00203                 catch (Exception^ exception)
00204                 {
00205                     TranscodeError(exception->Message);
00206                 }
00207
00208                 EnableButtons();
00209                 SetCancelButton(false);
00210             });
00211         }
00212     }
00213     catch (Platform::Exception^ exception)
00214     {
00215         TranscodeError(exception->Message);
00216     }
00217 }
00218
00219 void Scenario1_Default::TranscodeCancel(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00220 {
00221     try
00222     {
00223         _CTS.cancel();
00224         _CTS = cancellation_token_source();
00225
00226         if (_OutputFile != nullptr)
00227         {
00228             create_task(_OutputFile->DeleteAsync()).then(
00229                 [this](task<void> deleteTask)
00230             {
00231                 try
00232                 {
00233                     deleteTask.get();
00234                 }
00235                 catch (Platform::Exception^ exception)
00236                 {
00237                     TranscodeError(exception->Message);
00238                 }
00239             });
00240         }
00241     }
00242     catch (Platform::Exception^ exception)
00243     {
00244         TranscodeError(exception->Message);
00245     }
00246 }
00247
00248 void Scenario1_Default::TranscodeProgress(IAsyncActionWithProgress<double>^ asyncInfo, double percent)
00249 {
00250     OutputMsg->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Green);
00251     OutputMsg->Text = "Progress:  " + ((int)percent).ToString() + "%";
00252 }
00253
00254 void Scenario1_Default::TranscodeError(Platform::String^ error)
00255 {
00256     StatusMessage->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red);
00257     StatusMessage->Text = error;
00258     EnableButtons();
00259     SetCancelButton(false);
00260 }
00261
00262 void Scenario1_Default::TranscodeFailure(TranscodeFailureReason reason)
00263 {
00264     try
00265     {
00266         if (_OutputFile != nullptr)
00267         {
00268             create_task(_OutputFile->DeleteAsync()).then(
00269                 [this](task<void> deleteTask)
00270             {
00271                 try
00272                 {
00273                     deleteTask.get();
00274                 }
00275                 catch (Platform::Exception^ exception)
00276                 {
00277                     TranscodeError(exception->Message);
00278                 }
00279             });
00280         }
00281     }
00282     catch (Platform::Exception^ exception)
00283     {
00284         TranscodeError(exception->Message);
00285     }
00286
00287     switch (reason)
00288     {
00289     case TranscodeFailureReason::CodecNotFound:
00290         TranscodeError("Codec not found.");
00291         break;
00292     case TranscodeFailureReason::InvalidProfile:
00293         TranscodeError("Invalid profile.");
00294         break;
00295     default:
00296         TranscodeError("Unknown failure.");
00297     }
00298 }
00299
00300 void Scenario1_Default::SetCancelButton(bool isEnabled)
00301 {
00302     Cancel->IsEnabled = isEnabled;
00303 }
00304
00305 void Scenario1_Default::EnableButtons()
00306 {
00307     PickFileButton->IsEnabled = true;
00308     SetOutputButton->IsEnabled = true;
00309     TargetFormat->IsEnabled = true;
00310     ProfileSelect->IsEnabled = true;
00311     EnableMrfCrf444->IsEnabled = true;
00312
00313
00314 }
00315
00316 void Scenario1_Default::DisableButtons()
00317 {
00318     ProfileSelect->IsEnabled = false;
00319     Transcode->IsEnabled = false;
00320     PickFileButton->IsEnabled = false;
00321     SetOutputButton->IsEnabled = false;
00322     TargetFormat->IsEnabled = false;
00323     EnableMrfCrf444->IsEnabled = false;
00324 }
00325
00326 void Scenario1_Default::EnableNonSquarePARProfiles()
00327 {
00328     ComboBoxItem_NTSC->IsEnabled = true;
00329     ComboBoxItem_PAL->IsEnabled = true;
00330 }
00331
00332 void Scenario1_Default::DisableNonSquarePARProfiles()
00333 {
00334     ComboBoxItem_NTSC->IsEnabled = false;
00335     ComboBoxItem_PAL->IsEnabled = false;
00336
00337     // Ensure a valid profile is set
00338     if ((ProfileSelect->SelectedIndex == 3) || (ProfileSelect->SelectedIndex == 4))
00339     {
00340         ProfileSelect->SelectedIndex = 2;
00341     }
00342 }
00343
00344 void Scenario1_Default::PickFile(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00345 {
00346     try
00347     {
00348         FileOpenPicker^ picker = ref new FileOpenPicker();
00349         picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00350         picker->FileTypeFilter->Append(".wmv");
00351         picker->FileTypeFilter->Append(".mp4");
00352
00353         create_task(picker->PickSingleFileAsync()).then(
00354             [this](StorageFile^ inputFile)
00355         {
00356             try
00357             {
00358                 _InputFile = inputFile;
00359
00360                 if (_InputFile != nullptr)
00361                 {
00362                     return inputFile->OpenAsync(FileAccessMode::Read);
00363                 }
00364             }
00365             catch (Platform::Exception^ exception)
00366             {
00367                 TranscodeError(exception->Message);
00368             }
00369
00370             cancel_current_task();
00371         }).then(
00372             [this](IRandomAccessStream^ inputStream)
00373         {
00374             try
00375             {
00376                 InputVideo->SetSource(inputStream, _InputFile->ContentType);;
00377                 InputVideo->Play();
00378
00379                 //Enable buttons
00380                 EnableButtons();
00381             }
00382             catch (Platform::Exception^ exception)
00383             {
00384                 TranscodeError(exception->Message);
00385             }
00386         });
00387     }
00388     catch (Exception^ exception)
00389     {
00390         TranscodeError(exception->Message);
00391     }
00392 }
00393
00394 void Scenario1_Default::PickOutput(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00395 {
00396     try
00397     {
00398         FileSavePicker^ picker = ref new FileSavePicker();
00399         picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00400         picker->SuggestedFileName = _OutputFileName;
00401
00402         auto extensions = ref new Platform::Collections::Vector<String^>();
00403         extensions->Append(_OutputFileExtension);
00404         picker->FileTypeChoices->Insert(_OutputType, extensions);
00405
00406         create_task(picker->PickSaveFileAsync()).then([this](StorageFile^ file) {
00407             if (file != nullptr)
00408             {
00409                 _OutputFile = file;
00410                 SetTranscodeButton(true);
00411             }
00412         });
00413     }
00414     catch (Exception^ exception)
00415     {
00416         TranscodeError(exception->Message);
00417     }
00418 }
00419
00420 void Scenario1_Default::OnTargetFormatChanged(Object^ sender, SelectionChangedEventArgs^ e)
00421 {
00422     switch (TargetFormat->SelectedIndex)
00423     {
00424     case 1:
00425         _OutputFileExtension = ".wmv";
00426         _OutputType = "WMV";
00427         EnableNonSquarePARProfiles();
00428         break;
00429     case 2:
00430         _OutputFileExtension = ".avi";
00431         _OutputType = "AVI";
00432
00433         // Disable NTSC and PAL profiles as non-square pixel aspect ratios are not supported by AVI
00434         DisableNonSquarePARProfiles();
00435         break;
00436     default:
00437         _OutputFileExtension = ".mp4";
00438         _OutputType = "MP4";
00439         EnableNonSquarePARProfiles();
00440         break;
00441     }
00442 }
00443
00444 void Scenario1_Default::InputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00445 {
00446     if (InputVideo->DefaultPlaybackRate == 0)
00447     {
00448         InputVideo->DefaultPlaybackRate = 1.0;
00449         InputVideo->PlaybackRate = 1.0;
00450     }
00451
00452     InputVideo->Play();
00453 }
00454
00455 void Scenario1_Default::InputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00456 {
00457     InputVideo->Stop();
00458 }
00459
00460 void Scenario1_Default::InputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00461 {
00462     InputVideo->Pause();
00463 }
00464
00465 void Scenario1_Default::OutputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00466 {
00467     if (OutputVideo->DefaultPlaybackRate == 0)
00468     {
00469         OutputVideo->DefaultPlaybackRate = 1.0;
00470         OutputVideo->PlaybackRate = 1.0;
00471     }
00472
00473     OutputVideo->Play();
00474 }
00475
00476 void Scenario1_Default::OutputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00477 {
00478     OutputVideo->Stop();
00479 }
00480
00481 void Scenario1_Default::OutputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00482 {
00483     OutputVideo->Pause();
00484 }
00485
00486 void Scenario1_Default::SetPickFileButton(bool isEnabled)
00487 {
00488     PickFileButton->IsEnabled = isEnabled;
00489 }
00490
00491 void Scenario1_Default::SetTranscodeButton(bool isEnabled)
00492 {
00493     Transcode->IsEnabled = isEnabled;
00494 }
00495
00496 void Scenario1_Default::StopPlayers()
00497 {
00498     if (InputVideo->CurrentState != Media::MediaElementState::Paused)
00499     {
00500         InputVideo->Pause();
00501     }
00502     if (OutputVideo->CurrentState != Media::MediaElementState::Paused)
00503     {
00504         OutputVideo->Pause();
00505     }
00506 }
00507
00508 void Scenario1_Default::PlayFile(Windows::Storage::StorageFile^ MediaFile)
00509 {
00510     try
00511     {
00512         create_task(MediaFile->OpenAsync(FileAccessMode::Read)).then(
00513             [&, this, MediaFile](IRandomAccessStream^ outputStream)
00514         {
00515             try
00516             {
00517                 OutputVideo->SetSource(outputStream, MediaFile->ContentType);
00518                 OutputVideo->Play();
00519             }
00520             catch (Platform::Exception^ exception)
00521             {
00522                 TranscodeError(exception->Message);
00523             }
00524         });
00525     }
00526     catch (Exception^ exception)
00527     {
00528         TranscodeError(exception->Message);
00529     }
00530 }
Generated on Fri Nov 15 2024 22:20:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/NetworkServer.cpp Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

NetworkServer.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "NetworkServer.h"
00010 #include "StspDefs.h"
00011
00012 using namespace Microsoft::Samples::SimpleCommunication::Network;
00013
00014 INetworkServer ^Microsoft::Samples::SimpleCommunication::Network::CreateNetworkServer(unsigned short listeningPort)
00015 {
00016     return ref new CNetworkServer(listeningPort);
00017 }
00018
00019 CNetworkServer::CNetworkServer(unsigned short listeningPort)
00020     : _listeningPort(listeningPort)
00021 {
00022 }
00023
00024 CNetworkServer::~CNetworkServer()
00025 {
00026     OnClose();
00027 }
00028
00029 Windows::Foundation::IAsyncOperation<Windows::Networking::Sockets::StreamSocketInformation^>^ CNetworkServer::AcceptAsync()
00030 {
00031     return concurrency::create_async([this](){
00032         AutoLock lock(_critSec);
00033
00034         try
00035         {
00036             if (_acceptOperation != nullptr)
00037             {
00038                 // We only support accepting one connection.
00039                 Throw(MF_E_INVALIDREQUEST);
00040             }
00041
00042             _acceptOperation = ref new CAcceptOperation(this, _critSec);
00043             return concurrency::create_task(_acceptOperation->AcceptAsync(_listeningPort)).then([this](concurrency::task<IStreamSocket^>& acceptTask)
00044             {
00045                 try
00046                 {
00047                     auto clientSocket = acceptTask.get();
00048
00049                     SetSocket(clientSocket);
00050
00051                     return clientSocket->Information;
00052                 }
00053                 catch (Exception ^exc)
00054                 {
00055                     if (_acceptOperation != nullptr)
00056                     {
00057                         delete _acceptOperation;
00058                         _acceptOperation = nullptr;
00059                     }
00060                     throw;
00061                 }
00062             });
00063         }
00064         catch (Exception ^exc)
00065         {
00066             if (_acceptOperation != nullptr)
00067             {
00068                 delete _acceptOperation;
00069                 _acceptOperation = nullptr;
00070             }
00071             throw;
00072         }
00073     });
00074 }
00075
00076 void CNetworkServer::OnClose()
00077 {
00078     if (_acceptOperation != nullptr)
00079     {
00080         delete _acceptOperation;
00081         _acceptOperation = nullptr;
00082     }
00083 }
00084
00085 CAcceptOperation::CAcceptOperation(CNetworkServer ^parent, CritSec &critSec)
00086     : _parent(parent)
00087     , _critSec(critSec)
00088     , _fAsyncOperationInProgress(false)
00089 {
00090 }
00091
00092 CAcceptOperation::~CAcceptOperation()
00093 {
00094     AutoLock lock(_critSec);
00095     Detach();
00096     if (_fAsyncOperationInProgress && !_completionEvent._IsTriggered())
00097     {
00098         _completionEvent.set_exception(ref new DisconnectedException());
00099     }
00100 }
00101
00102 concurrency::task<IStreamSocket^> CAcceptOperation::AcceptAsync(unsigned short port)
00103 {
00104     AutoLock lock(_critSec);
00105     if (_listener != nullptr)
00106     {
00107         Throw(MF_E_INVALIDREQUEST);
00108     }
00109     WCHAR szPortNumber[6];
00110     if (port == 0)
00111     {
00112         port = c_wStspDefaultPort;
00113     }
00114
00115     ThrowIfError(StringCchPrintf(szPortNumber, _countof(szPortNumber), L"%hu", port));
00116     _listener = ref new StreamSocketListener();
00117     _connectionReceivedToken = _listener->ConnectionReceived += ref new Windows::Foundation::TypedEventHandler<Windows::Networking::Sockets::StreamSocketListener ^, Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs ^>(this, &Microsoft::Samples::SimpleCommunication::Network::CAcceptOperation::OnConnectionReceived);
00118     concurrency::create_task(_listener->BindServiceNameAsync(ref new String(szPortNumber)));
00119     auto &result = concurrency::create_task(_completionEvent);
00120     _fAsyncOperationInProgress = true;
00121     return result;
00122 }
00123
00124 void CAcceptOperation::OnConnectionReceived(Windows::Networking::Sockets::StreamSocketListener ^sender, Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs ^args)
00125 {
00126     AutoLock lock(_critSec);
00127     Detach();
00128     if (!_completionEvent.set(args->Socket))
00129     {
00130         delete args->Socket;
00131     }
00132 }
00133
00134 void CAcceptOperation::Detach()
00135 {
00136     _parent = nullptr;
00137     delete _listener;
00138     _listener = nullptr;
00139 }
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks/Common/RelayCommand.h Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks
  • Common

RelayCommand.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012 namespace AdventureWorks
00013 {
00014     [Windows::Foundation::Metadata::WebHostHidden]
00015     public ref class RelayCommand sealed : [Windows::Foundation::Metadata::Default] Windows::UI::Xaml::Input::ICommand
00016     {
00017     public:
00018         virtual event Windows::Foundation::EventHandler<Platform::Object^>^ CanExecuteChanged;
00019         virtual bool CanExecute(Platform::Object^ parameter);
00020         virtual void Execute(Platform::Object^ parameter);
00021         virtual ~RelayCommand();
00022
00023     internal:
00024         RelayCommand(std::function<bool(Platform::Object^)> canExecuteCallback,
00025             std::function<void(Platform::Object^)> executeCallback);
00026         void RaiseCanExecuteChanged();
00027
00028     private:
00029         std::function<bool(Platform::Object^)> _canExecuteCallback;
00030         std::function<void(Platform::Object^)> _executeCallback;
00031     };
00032 }
00033
Generated on Fri Nov 15 2024 22:18:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraGetPreviewFrame/cpp/MainPage.xaml.h Source File

  • CameraGetPreviewFrame
  • cpp

MainPage.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "MainPage.g.h"
00015
00016 namespace CameraGetPreviewFrame
00017 {
00018     public ref class MainPage sealed
00019     {
00020     private:
00021         // Receive notifications about rotation of the device and UI and apply any necessary rotation to the preview stream and UI controls
00022         Windows::Graphics::Display::DisplayInformation^ _displayInformation;
00023         Windows::Graphics::Display::DisplayOrientations _displayOrientation;
00024
00025         // Prevent the screen from sleeping while the camera is running
00026         Windows::System::Display::DisplayRequest^ _displayRequest;
00027
00028         // For listening to media property changes
00029         Windows::Media::SystemMediaTransportControls^ _systemMediaControls;
00030
00031         // MediaCapture and its state variables
00032         Platform::Agile<Windows::Media::Capture::MediaCapture^> _mediaCapture;
00033         bool _isInitialized;
00034         bool _isPreviewing;
00035
00036         // Information about the camera device
00037         bool _externalCamera;
00038         bool _mirroringPreview;
00039
00040         // Rotation metadata to apply to the preview stream and recorded videos(MF_MT_VIDEO_ROTATION)
00041         // Reference: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868174.aspx
00042         const GUID RotationKey;
00043
00044         // Folder in which the captures will be stored (availability check performed in InitializeCameraAsync)
00045         Windows::Storage::StorageFolder^ _captureFolder;
00046
00047         // Event tokens
00048         Windows::Foundation::EventRegistrationToken _applicationSuspendingEventToken;
00049         Windows::Foundation::EventRegistrationToken _applicationResumingEventToken;
00050         Windows::Foundation::EventRegistrationToken _mediaControlPropChangedEventToken;
00051         Windows::Foundation::EventRegistrationToken _mediaCaptureFailedEventToken;
00052         Windows::Foundation::EventRegistrationToken _displayInformationEventToken;
00053
00054         // MediaCapture methods
00055         Concurrency::task<void> InitializeCameraAsync();
00056         Concurrency::task<void> CleanupCameraAsync();
00057         Concurrency::task<void> StartPreviewAsync();
00058         Concurrency::task<void> SetPreviewRotationAsync();
00059         Concurrency::task<void> StopPreviewAsync();
00060         Concurrency::task<void> GetPreviewFrameAsSoftwareBitmapAsync();
00061         Concurrency::task<void> GetPreviewFrameAsD3DSurfaceAsync();
00062
00063         // Helpers
00064         Concurrency::task<void> SaveSoftwareBitmapAsync(Windows::Graphics::Imaging::SoftwareBitmap^ bitmap);
00065         Concurrency::task<Windows::Devices::Enumeration::DeviceInformation^> FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel panel);
00066         void WriteLine(Platform::String^ str);
00067         void WriteException(Platform::Exception^ ex);
00068         int ConvertDisplayOrientationToDegrees(Windows::Graphics::Display::DisplayOrientations orientation);
00069         void ApplyGreenFilter(Windows::Graphics::Imaging::SoftwareBitmap^ bitmap);
00070
00071         // Event handlers
00072         void Application_Suspending(Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
00073         void Application_Resuming(Object^ sender, Object^ args);
00074         void DisplayInformation_OrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Object^ args);
00075         void SystemMediaControls_PropertyChanged(Windows::Media::SystemMediaTransportControls^ sender, Windows::Media::SystemMediaTransportControlsPropertyChangedEventArgs^ args);
00076         void GetPreviewFrameButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00077         void MediaCapture_Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ errorEventArgs);
00078
00079     protected:
00080         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00081         virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00082
00083     public:
00084         MainPage();
00085         virtual ~MainPage();
00086     };
00087 }
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaTranscoding/cpp/Scenario2_Custom.xaml.h Source File

  • MediaTranscoding
  • cpp

Scenario2_Custom.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Custom.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario2_Custom sealed
00024     {
00025     public:
00026         Scenario2_Custom();
00027     protected:
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029
00030     private:
00031         void GetCustomProfile();
00032         void PickFile(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033         void PickOutput(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void OnTargetFormatChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00035         void SetPickFileButton(bool isEnabled);
00036         void StopPlayers();
00037         void PlayFile(Windows::Storage::StorageFile^ MediaFile);
00038
00039         void TranscodeCustom(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void TranscodeCancel(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void TranscodeProgress(Windows::Foundation::IAsyncActionWithProgress<double>^ asyncInfo, double percent);
00042         void TranscodeError(Platform::String^ error);
00043         void TranscodeFailure(Windows::Media::Transcoding::TranscodeFailureReason reason);
00044         void SetCancelButton(bool isEnabled);
00045         void SetOutputFileButton(bool isEnabled);
00046         void SetTranscodeButton(bool isEnabled);
00047         void EnableButtons();
00048         void DisableButtons();
00049
00050         // Media Controls
00051         void InputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00052         void InputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00053         void InputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00054         void OutputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00055         void OutputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00056         void OutputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00057
00058
00059         Platform::String^ _OutputFileName;
00060         Platform::String^ _OutputFileExtension = ".mp4";
00061         Platform::String^ _OutputType = "MP4";
00062         Windows::Media::MediaProperties::MediaEncodingProfile^ _Profile;
00063         Windows::Storage::StorageFile^ _InputFile;
00064         Windows::Storage::StorageFile^ _OutputFile;
00065         Windows::Media::Transcoding::MediaTranscoder^ _Transcoder;
00066         Concurrency::cancellation_token_source _CTS;
00067
00068         boolean _UseMp4;
00069
00070         SDKTemplate::MainPage^ rootPage;
00071     };
00072 }
Generated on Fri Nov 15 2024 22:20:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario05_PostStream.cpp Source File

  • HttpClient
  • cppwinrt

Scenario05_PostStream.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario05_PostStream.h"
00014 #include "Scenario05_PostStream.g.cpp"
00015 #include "Helpers.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::Storage::Streams;
00020 using namespace winrt::Windows::UI::Xaml;
00021 using namespace winrt::Windows::UI::Xaml::Navigation;
00022 using namespace winrt::Windows::Web::Http;
00023
00024 namespace
00025 {
00026     IAsyncOperation<IRandomAccessStream> GenerateSampleStreamAsync(int contentLength)
00027     {
00028         auto cancellation = co_await get_cancellation_token();
00029         cancellation.enable_propagation();
00030
00031         Buffer buffer(contentLength);
00032         memset(buffer.data(), '@', contentLength);
00033
00034         InMemoryRandomAccessStream stream;
00035         co_await stream.WriteAsync(buffer);
00036
00037         // Rewind the stream.
00038         stream.Seek(0);
00039
00040         co_return stream;
00041     }
00042 }
00043
00044 namespace winrt::SDKTemplate::implementation
00045 {
00046     Scenario05_PostStream::Scenario05_PostStream()
00047     {
00048         InitializeComponent();
00049     }
00050
00051     void Scenario05_PostStream::OnNavigatedTo(NavigationEventArgs const&)
00052     {
00053         httpClient = Helpers::CreateHttpClientWithCustomHeaders();
00054     }
00055
00056     void Scenario05_PostStream::OnNavigatedFrom(NavigationEventArgs const&)
00057     {
00058         httpClient.Close();
00059     }
00060
00061     fire_and_forget Scenario05_PostStream::Start_Click(IInspectable const&, RoutedEventArgs const&)
00062     {
00063         auto lifetime = get_strong();
00064
00065         // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00066         // valid, absolute URI, we'll notify the user about the incorrect input.
00067         Uri resourceUri = Helpers::TryParseHttpUri(AddressField().Text());
00068         if (!resourceUri)
00069         {
00070             rootPage.NotifyUser(L"Invalid URI.", NotifyType::ErrorMessage);
00071             return;
00072         }
00073
00074         Helpers::ScenarioStarted(StartButton(), CancelButton(), OutputField());
00075         rootPage.NotifyUser(L"In progress", NotifyType::StatusMessage);
00076
00077         static constexpr int contentLength = 1000;
00078         IRandomAccessStream stream = co_await GenerateSampleStreamAsync(contentLength);
00079
00080         // If the stream does not implement the IRandomAccessStream interface,
00081         // chunked transfer encoding is used during the request.
00082         HttpStreamContent streamContent(stream);
00083
00084         HttpRequestMessage request(HttpMethod::Post(), resourceUri);
00085         request.Content(streamContent);
00086
00087         // This sample uses a "try" in order to support cancellation.
00088         // If you don't need to support cancellation, then the "try" is not needed.
00089         try
00090         {
00091             pendingAction = CancelableRequestAsync(request);
00092             co_await pendingAction;
00093         }
00094         catch (hresult_canceled const&)
00095         {
00096             rootPage.NotifyUser(L"Request canceled.", NotifyType::ErrorMessage);
00097         }
00098
00099         Helpers::ScenarioCompleted(StartButton(), CancelButton());
00100     }
00101
00102     IAsyncAction Scenario05_PostStream::CancelableRequestAsync(HttpRequestMessage request)
00103     {
00104         auto lifetime = get_strong();
00105         auto cancellation = co_await get_cancellation_token();
00106         cancellation.enable_propagation();
00107
00108         // Do an asynchronous POST.
00109         HttpRequestResult result = co_await httpClient.TrySendRequestAsync(request);
00110
00111         if (result.Succeeded())
00112         {
00113             co_await Helpers::DisplayTextResultAsync(result.ResponseMessage(), OutputField());
00114
00115             rootPage.NotifyUser(L"Completed", NotifyType::StatusMessage);
00116         }
00117         else
00118         {
00119             Helpers::DisplayWebError(rootPage, result.ExtendedError());
00120         }
00121     }
00122
00123     void Scenario05_PostStream::Cancel_Click(IInspectable const&, RoutedEventArgs const&)
00124     {
00125         if (pendingAction)
00126         {
00127             pendingAction.Cancel();
00128         }
00129     }
00130 }
Generated on Fri Nov 15 2024 22:19:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/Scenario6_ScrollIntoView.h Source File

  • XamlListView
  • cppwinrt

Scenario6_ScrollIntoView.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "Item.h"
00014 #include "Scenario6_ScrollIntoView.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario6_ScrollIntoView : Scenario6_ScrollIntoViewT<Scenario6_ScrollIntoView>
00019     {
00020         Scenario6_ScrollIntoView();
00021
00022         auto _items() { return items; }
00023         void Scroll_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00024
00025     private:
00026         Windows::Foundation::Collections::IObservableVector<SDKTemplate::Item> items = Item::GetItems(300);
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario6_ScrollIntoView : Scenario6_ScrollIntoViewT<Scenario6_ScrollIntoView, implementation::Scenario6_ScrollIntoView>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:22:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Data Member List

This is the complete list of members for Scenario1_Data, including all inherited members.
Scenario1_Data() | Scenario1_Data
ShowResults_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1_Data
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Unicode/cppwinrt/SampleConfiguration.cpp Source File

  • Unicode
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"Unicode C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Tokenize lexical identifiers within a string", xaml_typename<SDKTemplate::Scenario1_FindId>() },
00029 });
Generated on Fri Nov 15 2024 22:17:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlLite/cppwinrt/SampleConfiguration.cpp Source File

  • XmlLite
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::Storage;
00021 using namespace Windows::Storage::Streams;
00022 using namespace SDKTemplate;
00023
00024 hstring implementation::MainPage::FEATURE_NAME()
00025 {
00026     return L"XmlLite C++/WinRT Sample";
00027 }
00028
00029 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00030 {
00031     Scenario{ L"XmlLite Reader", xaml_typename<SDKTemplate::Scenario1_XmlReader>() },
00032     Scenario{ L"Write XML with XmlWriter", xaml_typename<SDKTemplate::Scenario2_XmlWriter>() },
00033     Scenario{ L"Write XML with XmlWriterLite", xaml_typename<SDKTemplate::Scenario3_XmlWriterLite>() },
00034 });
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cppwinrt/Scenario4_SaveFile.cpp Source File

  • FilePicker
  • cppwinrt

Scenario4_SaveFile.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario4_SaveFile.h"
00014 #include "Scenario4_SaveFile.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Storage;
00019 using namespace Windows::Storage::Pickers;
00020 using namespace Windows::Storage::Provider;
00021 using namespace Windows::UI::Xaml;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario4_SaveFile::Scenario4_SaveFile()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     fire_and_forget Scenario4_SaveFile::SaveFileButton_Click(IInspectable const&, RoutedEventArgs const&)
00031     {
00032         auto lifetime = get_strong();
00033
00034         // Clear previous returned file name, if it exists, between iterations of this scenario
00035         OutputTextBlock().Text(L"");
00036
00037         FileSavePicker savePicker;
00038         savePicker.SuggestedStartLocation(PickerLocationId::DocumentsLibrary);
00039         // Dropdown of file types the user can save the file as
00040         savePicker.FileTypeChoices().Insert(L"Plain Text", single_threaded_vector<hstring>({ L".txt" }));
00041         // Default file name if the user does not type one in or select a file to replace
00042         savePicker.SuggestedFileName(L"New Document");
00043         StorageFile file = co_await savePicker.PickSaveFileAsync();
00044         if (file != nullptr)
00045         {
00046             // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
00047             CachedFileManager::DeferUpdates(file);
00048             // write to file
00049             await FileIO::WriteTextAsync(file, L"Example file contents.");
00050             // Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
00051             // Completing updates may require Windows to ask for user input.
00052             FileUpdateStatus status = co_await CachedFileManager::CompleteUpdatesAsync(file);
00053             if (status == FileUpdateStatus::Complete)
00054             {
00055                 OutputTextBlock().Text(L"File " + file.Name() + L" was saved.");
00056             }
00057             else if (status == FileUpdateStatus::CompleteAndRenamed)
00058             {
00059                 OutputTextBlock().Text(L"File " + file.Name() + L" was renamed and saved.");
00060             }
00061             else
00062             {
00063                 OutputTextBlock().Text(L"File " + file.Name() + L" couldn't be saved.");
00064             }
00065         }
00066         else
00067         {
00068             OutputTextBlock().Text(L"Operation cancelled.");
00069         }
00070     }
00071 }
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboardTextInput/cs/SampleConfiguration.cs Source File

  • TouchKeyboardTextInput
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "TouchKeyboardTextInput";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Spelling and Text Suggestions", ClassType=typeof(Scenario1_SpellingTextSuggestions)},
00025             new Scenario() { Title="Scoped Views", ClassType=typeof(Scenario2_ScopedViews)}
00026         };
00027     }
00028
00029     public class Scenario
00030     {
00031         public string Title { get; set; }
00032         public Type ClassType { get; set; }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContentIndexer/cpp/S6_DeleteWithAppContent.xaml.cpp Source File

  • ContentIndexer
  • cpp

S6_DeleteWithAppContent.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // S6_DeleteWithAppContent.xaml.cpp
00014 // Implementation of the S6_DeleteWithAppContent class
00015 //
00016
00017 #include "pch.h"
00018 #include "S6_DeleteWithAppContent.xaml.h"
00019 #include "MainPage.xaml.h"
00020 #include "Helpers.h"
00021
00022 using namespace SDKTemplate;
00023
00024 using namespace concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::Foundation;
00030 using namespace Windows::Foundation::Collections;
00031
00032 S6_DeleteWithAppContent::S6_DeleteWithAppContent()
00033 {
00034     InitializeComponent();
00035     InitializeRevisionNumber();
00036 }
00037
00038 void S6_DeleteWithAppContent::AddToIndex_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00039 {
00040     return AddAppContentFilesToIndexedFolder();
00041 }
00042
00043 // This function deletes a single appcontent-ms file, "sample1.appcontent-ms". Upon deletion, the indexer is notified
00044 // and the content indexed from this file is removed from the index.
00045 void S6_DeleteWithAppContent::DeleteSingleItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     auto localFolder = Windows::Storage::ApplicationData::Current->LocalFolder;
00048     auto outputStrings = ref new Vector<String^>();
00049     outputStrings->Append(L"Items deleted from the \"Indexed\" folder:");
00050     create_task(localFolder->CreateFolderAsync(L"Indexed", Windows::Storage::CreationCollisionOption::OpenIfExists)).then(
00051     [](Windows::Storage::StorageFolder^ indexedFolder)
00052     {
00053         return indexedFolder->GetFileAsync(L"sample1.appcontent-ms");
00054     }).then([outputStrings](Windows::Storage::StorageFile^ file)
00055     {
00056         outputStrings->Append(L"\n" + file->DisplayName);
00057         return file->DeleteAsync();
00058     }).then([outputStrings]()
00059     {
00060         auto outputString = ref new String(L"");
00061         for (const auto& str : outputStrings)
00062         {
00063             outputString += str;
00064         }
00065         return outputString;
00066     }).then([](task<String^> outputStringTask)
00067     {
00068         try
00069         {
00070             MainPage::Current->NotifyUser(outputStringTask.get(), NotifyType::StatusMessage);
00071         }
00072         catch (Platform::Exception^ e)
00073         {
00074             MainPage::Current->NotifyUser(L"Exception thrown! Did you already delete the \"sample1.appcontent-ms\" file?" +
00075                                           L"\nMessage: " + e->Message +
00076                                           L"\nHRESULT: " + HResultToString(e->HResult),
00077                                           NotifyType::ErrorMessage);
00078         }
00079     });
00080 }
00081
00082 // This function deletes all appcontent-ms files in the "LocalState\Indexed" folder. Upon deletion, the indexer is notified and
00083 // the content indexed from these files is removed from the index.
00084 void S6_DeleteWithAppContent::DeleteAllItems_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00085 {
00086     auto localFolder = Windows::Storage::ApplicationData::Current->LocalFolder;
00087     auto outputStrings = ref new Vector<String^>();
00088     outputStrings->Append(L"Items deleted from the \"Indexed\" folder:");
00089     create_task(localFolder->CreateFolderAsync(L"Indexed", Windows::Storage::CreationCollisionOption::OpenIfExists)).then(
00090     [](Windows::Storage::StorageFolder^ indexedFolder)
00091     {
00092         return indexedFolder->GetFilesAsync();
00093     }).then([outputStrings](IVectorView<Windows::Storage::StorageFile^>^ files)
00094     {
00095         std::vector<task<void>> deleteTasks;
00096         for (const auto& file : files)
00097         {
00098             deleteTasks.push_back(create_task(file->DeleteAsync()));
00099             outputStrings->Append(L"\n" + file->DisplayName);
00100         }
00101         return when_all(deleteTasks.begin(), deleteTasks.end());
00102     }).then([outputStrings]()
00103     {
00104         auto outputString = ref new String(L"");
00105         for (const auto& str : outputStrings)
00106         {
00107             outputString += str;
00108         }
00109         MainPage::Current->NotifyUser(outputString, NotifyType::StatusMessage);
00110     });
00111 }
Generated on Fri Nov 15 2024 22:18:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Badges/Local/PrimaryTile/SetBadgeNumber/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Badges
  • Local
  • PrimaryTile
  • SetBadgeNumber

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.Data.Xml.Dom;
00003 using Windows.UI.Notifications;
00004 using Windows.UI.Popups;
00005 using Windows.UI.Xaml;
00006 using Windows.UI.Xaml.Controls;
00007
00008 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00009
00010 namespace Notifications.ScenarioPages.Badges.Local.PrimaryTile.SetBadgeNumber
00011 {
00012     /// <summary>
00013     /// An empty page that can be used on its own or navigated to within a Frame.
00014     /// </summary>
00015     public sealed partial class ScenarioElement : UserControl
00016     {
00017         public ScenarioElement()
00018         {
00019             this.InitializeComponent();
00020         }
00021
00022         private async void ButtonUpdateBadgeNumber_Click(object sender, RoutedEventArgs e)
00023         {
00024             int num;
00025
00026             if (!int.TryParse(TextBoxNumber.Text, out num))
00027             {
00028                 await new MessageDialog("You must provide a valid integer.", "Error").ShowAsync();
00029                 return;
00030             }
00031
00032             // Get the blank badge XML payload for a badge number
00033             XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
00034
00035             // Set the value of the badge in the XML to our number
00036             XmlElement badgeElement = badgeXml.SelectSingleNode("/badge") as XmlElement;
00037             badgeElement.SetAttribute("value", num.ToString());
00038
00039             // Create the badge notification
00040             BadgeNotification badge = new BadgeNotification(badgeXml);
00041
00042             // Create the badge updater for the application
00043             BadgeUpdater badgeUpdater = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
00044
00045             // And update the badge
00046             badgeUpdater.Update(badge);
00047         }
00048     }
00049 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RecognizedTextRun Member List

This is the complete list of members for RecognizedTextRun, including all inherited members.
First | RecognizedTextRun
Last | RecognizedTextRun
Script | RecognizedTextRun
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/Common/BasicLoader.h Source File

  • Simple3DGameXaml
  • cpp
  • Common

BasicLoader.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include "BasicReaderWriter.h"
00011
00012 // A simple loader class that provides support for loading shaders, textures,
00013 // and meshes from files on disk. Provides synchronous and asynchronous methods.
00014 ref class BasicLoader
00015 {
00016 internal:
00017     BasicLoader(
00018         _In_ ID3D11Device* d3dDevice,
00019         _In_opt_ IWICImagingFactory2* wicFactory = nullptr
00020         );
00021
00022     void LoadTexture(
00023         _In_ Platform::String^ filename,
00024         _Out_opt_ ID3D11Texture2D** texture,
00025         _Out_opt_ ID3D11ShaderResourceView** textureView
00026         );
00027
00028     concurrency::task<void> LoadTextureAsync(
00029         _In_ Platform::String^ filename,
00030         _Out_opt_ ID3D11Texture2D** texture,
00031         _Out_opt_ ID3D11ShaderResourceView** textureView
00032         );
00033
00034     void LoadShader(
00035         _In_ Platform::String^ filename,
00036         _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[],
00037         _In_ uint32 layoutDescNumElements,
00038         _Out_ ID3D11VertexShader** shader,
00039         _Out_opt_ ID3D11InputLayout** layout
00040         );
00041
00042     concurrency::task<void> LoadShaderAsync(
00043         _In_ Platform::String^ filename,
00044         _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[],
00045         _In_ uint32 layoutDescNumElements,
00046         _Out_ ID3D11VertexShader** shader,
00047         _Out_opt_ ID3D11InputLayout** layout
00048         );
00049
00050     void LoadShader(
00051         _In_ Platform::String^ filename,
00052         _Out_ ID3D11PixelShader** shader
00053         );
00054
00055     concurrency::task<void> LoadShaderAsync(
00056         _In_ Platform::String^ filename,
00057         _Out_ ID3D11PixelShader** shader
00058         );
00059
00060     void LoadShader(
00061         _In_ Platform::String^ filename,
00062         _Out_ ID3D11ComputeShader** shader
00063         );
00064
00065     concurrency::task<void> LoadShaderAsync(
00066         _In_ Platform::String^ filename,
00067         _Out_ ID3D11ComputeShader** shader
00068         );
00069
00070     void LoadShader(
00071         _In_ Platform::String^ filename,
00072         _Out_ ID3D11GeometryShader** shader
00073         );
00074
00075     concurrency::task<void> LoadShaderAsync(
00076         _In_ Platform::String^ filename,
00077         _Out_ ID3D11GeometryShader** shader
00078         );
00079
00080     void LoadShader(
00081         _In_ Platform::String^ filename,
00082         _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration,
00083         _In_ uint32 numEntries,
00084         _In_reads_opt_(numStrides) const uint32* bufferStrides,
00085         _In_ uint32 numStrides,
00086         _In_ uint32 rasterizedStream,
00087         _Out_ ID3D11GeometryShader** shader
00088         );
00089
00090     concurrency::task<void> LoadShaderAsync(
00091         _In_ Platform::String^ filename,
00092         _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration,
00093         _In_ uint32 numEntries,
00094         _In_reads_opt_(numStrides) const uint32* bufferStrides,
00095         _In_ uint32 numStrides,
00096         _In_ uint32 rasterizedStream,
00097         _Out_ ID3D11GeometryShader** shader
00098         );
00099
00100     void LoadShader(
00101         _In_ Platform::String^ filename,
00102         _Out_ ID3D11HullShader** shader
00103         );
00104
00105     concurrency::task<void> LoadShaderAsync(
00106         _In_ Platform::String^ filename,
00107         _Out_ ID3D11HullShader** shader
00108         );
00109
00110     void LoadShader(
00111         _In_ Platform::String^ filename,
00112         _Out_ ID3D11DomainShader** shader
00113         );
00114
00115     concurrency::task<void> LoadShaderAsync(
00116         _In_ Platform::String^ filename,
00117         _Out_ ID3D11DomainShader** shader
00118         );
00119
00120     void LoadMesh(
00121         _In_ Platform::String^ filename,
00122         _Out_ ID3D11Buffer** vertexBuffer,
00123         _Out_ ID3D11Buffer** indexBuffer,
00124         _Out_opt_ uint32* vertexCount,
00125         _Out_opt_ uint32* indexCount
00126         );
00127
00128     concurrency::task<void> LoadMeshAsync(
00129         _In_ Platform::String^ filename,
00130         _Out_ ID3D11Buffer** vertexBuffer,
00131         _Out_ ID3D11Buffer** indexBuffer,
00132         _Out_opt_ uint32* vertexCount,
00133         _Out_opt_ uint32* indexCount
00134         );
00135
00136 private:
00137     Microsoft::WRL::ComPtr<ID3D11Device> m_d3dDevice;
00138     Microsoft::WRL::ComPtr<IWICImagingFactory2> m_wicFactory;
00139     BasicReaderWriter^ m_basicReaderWriter;
00140
00141     template <class DeviceChildType>
00142     inline void SetDebugName(
00143         _In_ DeviceChildType* object,
00144         _In_ Platform::String^ name
00145         );
00146
00147     Platform::String^ GetExtension(
00148         _In_ Platform::String^ filename
00149         );
00150
00151     void CreateTexture(
00152         _In_ bool decodeAsDDS,
00153         _In_reads_bytes_(dataSize) byte* data,
00154         _In_ uint32 dataSize,
00155         _Out_opt_ ID3D11Texture2D** texture,
00156         _Out_opt_ ID3D11ShaderResourceView** textureView,
00157         _In_opt_ Platform::String^ debugName
00158         );
00159
00160     void CreateInputLayout(
00161         _In_reads_bytes_(bytecodeSize) byte* bytecode,
00162         _In_ uint32 bytecodeSize,
00163         _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC* layoutDesc,
00164         _In_ uint32 layoutDescNumElements,
00165         _Out_ ID3D11InputLayout** layout
00166         );
00167
00168     void CreateMesh(
00169         _In_ byte* meshData,
00170         _Out_ ID3D11Buffer** vertexBuffer,
00171         _Out_ ID3D11Buffer** indexBuffer,
00172         _Out_opt_ uint32* vertexCount,
00173         _Out_opt_ uint32* indexCount,
00174         _In_opt_ Platform::String^ debugName
00175         );
00176 };
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundSensors/cpp/BackgroundTask/pch.cpp Source File

  • BackgroundSensors
  • cpp
  • BackgroundTask

pch.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cpp/Scenario1_PercentPermilleFormatting.xaml.cpp Source File

  • NumberFormatting
  • cpp

Scenario1_PercentPermilleFormatting.xaml.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario1_PercentPermilleFormatting.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Windows::UI::Xaml;
00010 using namespace Windows::UI::Xaml::Controls;
00011 using namespace Windows::UI::Xaml::Navigation;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::Globalization::NumberFormatting;
00015
00016 Scenario1_PercentPermilleFormatting::Scenario1_PercentPermilleFormatting()
00017 {
00018     InitializeComponent();
00019 }
00020
00021 void Scenario1_PercentPermilleFormatting::Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00022 {
00023     // This scenario uses the Windows.Globalization.NumberFormatting.PercentFormatter and
00024     // the Windows.Globalization.NumberFormatting.PermilleFormatter classes to format numbers
00025     // as a percent or a permille.
00026
00027     // Create formatters initialized using the current user's preference settings.
00028     PercentFormatter^ percentFormat = ref new PercentFormatter();
00029     PermilleFormatter^ permilleFormat = ref new PermilleFormatter();
00030
00031     // Make a random number.
00032     float randomNumber = (float)rand() / RAND_MAX;
00033
00034     // Format with current user preferences.
00035     String^ percent = percentFormat->Format(randomNumber);
00036     String^ permille = permilleFormat->Format(randomNumber);
00037
00038     // Get a fixed number.
00039     long long fixedNumber = 500;
00040
00041     // Format with grouping using default.
00042     PercentFormatter^ percentFormat1 = ref new PercentFormatter();
00043     percentFormat1->IsGrouped = true;
00044     String^ percent1 = percentFormat1->Format(fixedNumber);
00045
00046     // Format with grouping using French.
00047     auto fr = ref new Platform::Collections::Vector<String^>();
00048     fr->Append("fr-FR");
00049     PercentFormatter^ percentFormatFR = ref new PercentFormatter(fr, "ZZ");
00050     percentFormatFR->IsGrouped = true;
00051     String^ percentFR1 = percentFormatFR->Format(randomNumber);
00052     String^ percentFR2 = percentFormatFR->Format(fixedNumber);
00053
00054     // Format with grouping using Arabic.
00055     auto ar = ref new Platform::Collections::Vector<String^>();
00056     ar->Append("ar");
00057     PercentFormatter^ percentFormatAR = ref new PercentFormatter(ar, "ZZ");
00058     percentFormatAR->IsGrouped = true;
00059     percentFormatAR->FractionDigits = 2;
00060     String^ percentAR = percentFormatAR->Format(fixedNumber);
00061     PermilleFormatter^ permilleFormatAR = ref new PermilleFormatter(ar, "ZZ");
00062     String^ permilleAR = permilleFormatAR->Format(randomNumber);
00063
00064     // Format with no fractional digits using default.
00065     PercentFormatter^ percentFormat2 = ref new PercentFormatter();
00066     percentFormat2->FractionDigits = 0;
00067     String^ percent2 = percentFormat2->Format(fixedNumber);
00068
00069     // Format always with a decimal point.
00070     PercentFormatter^ percentFormat3 = ref new PercentFormatter();
00071     percentFormat3->IsDecimalPointAlwaysDisplayed = true;
00072     percentFormat3->FractionDigits = 0;
00073     String^ percent3 = percentFormat3->Format(fixedNumber);
00074
00075     // Display the results.
00076     String^ results =
00077         "Random number ("                                   + randomNumber + ")\n" +
00078         "Percent formatted: "                               + percent  + "\n" +
00079         "Permille formatted: "                              + permille + "\n\n" +
00080         "Language-specific percent formatted: "             + percentFR1 + "\n" +
00081         "Language-specific permille formatted: "            + permilleAR + "\n\n" +
00082         "Fixed number ("                                    + fixedNumber + ")\n" +
00083         "Percent formatted (grouped): "                     + percent1 + "\n" +
00084         "Percent formatted (grouped as fr-FR): "            + percentFR2 + "\n" +
00085         "Percent formatted (grouped w/digits as ar): "      + percentAR + "\n" +
00086         "Percent formatted (no fractional digits): "        + percent2  + "\n" +
00087         "Percent formatted (always with a decimal point): " + percent3;
00088
00089     OutputTextBlock->Text = results;
00090 }
Generated on Fri Nov 15 2024 22:20:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cpp/ItemsListViewModel.h Source File

  • Store
  • cpp

ItemsListViewModel.h

Go to the documentation of this file.
00001 #pragma once
00002 namespace SDKTemplate
00003 {
00004     [Windows::UI::Xaml::Data::Bindable]
00005     public ref class ItemDetails sealed
00006     {
00007     public:
00008         ItemDetails(Windows::Services::Store::StoreProduct^ product)
00009         {
00010             title = product->Title;
00011             price = product->Price->FormattedPrice;
00012             inCollection = product->IsInUserCollection;
00013             productKind = product->ProductKind;
00014             storeId = product->StoreId;
00015         }
00016
00017         property Platform::String^ Title { Platform::String^ get() { return title; }}
00018         property Platform::String^ Price { Platform::String^ get() { return price; }}
00019         property boolean InCollection { boolean get() { return inCollection; }}
00020         property Platform::String^ ProductKind { Platform::String^ get() { return productKind; }}
00021         property Platform::String^ StoreId { Platform::String^ get() { return storeId; }}
00022
00023         property Platform::String^ FormattedTitle
00024         {
00025             Platform::String^ get()
00026             {
00027                 return Title + " (" + ProductKind + ") " + Price + ", InUserCollection:" + (InCollection ? "True" : "False");
00028             }
00029         }
00030
00031     private:
00032         Platform::String^ title;
00033         Platform::String^ price;
00034         boolean inCollection;
00035         Platform::String^ productKind;
00036         Platform::String^ storeId;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Barometer/cs/Scenario1_DataEvents.xaml.cs Source File

  • Barometer
  • cs

Scenario1_DataEvents.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Devices.Sensors;
00015 using Windows.Foundation;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario1_DataEvents : Page
00024     {
00025         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00026         // as NotifyUser()
00027         MainPage rootPage = MainPage.Current;
00028
00029         private Barometer sensor;
00030         private uint desiredReportIntervalMs;
00031
00032         public Scenario1_DataEvents()
00033         {
00034             this.InitializeComponent();
00035
00036             sensor = Barometer.GetDefault();
00037             if (null != sensor)
00038             {
00039                 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00040                 // This value will be used later to activate the sensor.
00041                 uint minReportIntervalMs = sensor.MinimumReportInterval;
00042                 desiredReportIntervalMs = minReportIntervalMs > 1000 ? minReportIntervalMs : 1000;
00043             }
00044             else
00045             {
00046                 rootPage.NotifyUser("No barometer found", NotifyType.ErrorMessage);
00047             }
00048         }
00049
00050         /// <summary>
00051         /// Invoked when this page is about to be displayed in a Frame.
00052         /// </summary>
00053         /// <param name="e">Event data that describes how this page was reached. The Parameter
00054         /// property is typically used to configure the page.</param>
00055         protected override void OnNavigatedTo(NavigationEventArgs e)
00056         {
00057             ScenarioEnableButton.IsEnabled = true;
00058             ScenarioDisableButton.IsEnabled = false;
00059         }
00060
00061         /// <summary>
00062         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00063         /// </summary>
00064         /// <param name="e">
00065         /// Event data that can be examined by overriding code. The event data is representative
00066         /// of the navigation that will unload the current Page unless canceled. The
00067         /// navigation can potentially be canceled by setting Cancel.
00068         /// </param>
00069         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00070         {
00071             if (ScenarioDisableButton.IsEnabled)
00072             {
00073                 Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00074                 sensor.ReadingChanged -= new TypedEventHandler<Barometer, BarometerReadingChangedEventArgs>(ReadingChanged);
00075
00076                 // Restore the default report interval to release resources while the sensor is not in use
00077                 sensor.ReportInterval = 0;
00078             }
00079
00080             base.OnNavigatingFrom(e);
00081         }
00082
00083         /// <summary>
00084         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00085         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00086         /// </summary>
00087         /// <param name="sender"></param>
00088         /// <param name="e">
00089         /// Event data that can be examined for the current visibility state.
00090         /// </param>
00091         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00092         {
00093             if (ScenarioDisableButton.IsEnabled)
00094             {
00095                 if (e.Visible)
00096                 {
00097                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00098                     sensor.ReadingChanged += new TypedEventHandler<Barometer, BarometerReadingChangedEventArgs>(ReadingChanged);
00099                 }
00100                 else
00101                 {
00102                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00103                     sensor.ReadingChanged -= new TypedEventHandler<Barometer, BarometerReadingChangedEventArgs>(ReadingChanged);
00104                 }
00105             }
00106         }
00107
00108         /// <summary>
00109         /// This is the event handler for ReadingChanged events.
00110         /// </summary>
00111         /// <param name="sender"></param>
00112         /// <param name="e"></param>
00113         async private void ReadingChanged(object sender, BarometerReadingChangedEventArgs e)
00114         {
00115             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00116             {
00117                 BarometerReading reading = e.Reading;
00118                 ScenarioOutput_hPa.Text = String.Format("{0,5:0.00}", reading.StationPressureInHectopascals);
00119             });
00120         }
00121
00122         /// <summary>
00123         /// This is the click handler for the 'Enable' button.
00124         /// </summary>
00125         /// <param name="sender"></param>
00126         /// <param name="e"></param>
00127         private void ScenarioEnable(object sender, RoutedEventArgs e)
00128         {
00129             if (null != sensor)
00130             {
00131                 // Establish the report interval
00132                 sensor.ReportInterval = desiredReportIntervalMs;
00133
00134                 Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged);
00135                 sensor.ReadingChanged += new TypedEventHandler<Barometer, BarometerReadingChangedEventArgs>(ReadingChanged);
00136
00137                 ScenarioEnableButton.IsEnabled = false;
00138                 ScenarioDisableButton.IsEnabled = true;
00139             }
00140             else
00141             {
00142                 rootPage.NotifyUser("No barometer found", NotifyType.ErrorMessage);
00143             }
00144         }
00145
00146         /// <summary>
00147         /// This is the click handler for the 'Disable' button.
00148         /// </summary>
00149         /// <param name="sender"></param>
00150         /// <param name="e"></param>
00151         private void ScenarioDisable(object sender, RoutedEventArgs e)
00152         {
00153             Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00154             sensor.ReadingChanged -= new TypedEventHandler<Barometer, BarometerReadingChangedEventArgs>(ReadingChanged);
00155
00156             // Restore the default report interval to release resources while the sensor is not in use
00157             sensor.ReportInterval = 0;
00158
00159             ScenarioEnableButton.IsEnabled = true;
00160             ScenarioDisableButton.IsEnabled = false;
00161         }
00162     }
00163 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/Scenario4PageRange.xaml.h Source File

  • Printing
  • cpp

Scenario4PageRange.xaml.h

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario4PageRange.g.h"
00006 #include "PrintHelper.h"
00007
00008 namespace SDKTemplate
00009 {
00010     class InvalidPageException
00011     {
00012     public:
00013         InvalidPageException(const std::wstring &message)
00014         {
00015             m_displayMessage = message;
00016         }
00017
00018         std::wstring get_DisplayMessage()
00019         {
00020             return m_displayMessage;
00021         }
00022
00023     private:
00024         std::wstring m_displayMessage;
00025     };
00026
00027     ref class PageRangePrintHelper sealed : public PrintHelper
00028     {
00029     public:
00030         PageRangePrintHelper(Page^ scenarioPage);
00031
00032     protected:
00033         /// <summary>
00034         /// This is the event handler for PrintManager.PrintTaskRequested.
00035         /// In order to ensure a good user experience, the system requires that the app handle the PrintTaskRequested event within the time specified by PrintTaskRequestedEventArgs->Request->Deadline.
00036         /// Therefore, we use this handler to only create the print task.
00037         /// The print settings customization can be done when the print document source is requested.
00038         /// </summary>
00039         /// <param name="sender">PrintManager</param>
00040         /// <param name="e">PrintTaskRequestedEventArgs</param>
00041         virtual void PrintTaskRequested(Windows::Graphics::Printing::PrintManager^ sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^ e) override;
00042
00043         /// <summary>
00044         /// This is called when the preview pages have been recreated. We use it to call ValidatePageRangeOption to make
00045         /// sure that the Page Ranges are still valid
00046         /// </summary>
00047         /// <param name="printTaskOptions"></param>
00048         virtual void OnPreviewPagesCreated(Windows::Graphics::Printing::PrintTaskOptions^ printTaskOptions) override;
00049
00050         /// <summary>
00051         /// Deals with validating that the Page Ranges only contain pages that are present in the document.
00052         ///
00053         /// This is not necessary and some apps don't do this validation. Instead, they just ignore the pages
00054         /// that are not present in the document and simply don't print them.
00055         /// </summary>
00056         /// <param name="pageRangeOption">The PrintPageRangeOptionDetails option</param>
00057         void ValidatePageRangeOption(Windows::Graphics::Printing::OptionDetails::PrintPageRangeOptionDetails^ pageRangeOption);
00058
00059         /// <summary>
00060         /// This is the event handler for PrintDocument.AddPages. It provides all pages to be printed, in the form of
00061         /// UIElements, to an instance of PrintDocument. PrintDocument subsequently converts the UIElements
00062         /// into a pages that the Windows print system can deal with.
00063         /// </summary>
00064         /// <param name="sender"></param>
00065         /// <param name="e">Add page event arguments containing a print task options reference</param>
00066         virtual void AddPrintPages(Platform::Object^ sender, Windows::UI::Xaml::Printing::AddPagesEventArgs^ e) override;
00067
00068     private:
00069
00070         /// <summary>
00071         /// Option change event handler
00072         /// </summary>
00073         /// <param name="sender">PrintTaskOptionsDetails object</param>
00074         /// <param name="args">the event arguments containing the changed option id</param>
00075         void printDetailedOptions_OptionChanged(Windows::Graphics::Printing::OptionDetails::PrintTaskOptionDetails^ sender,
00076             Windows::Graphics::Printing::OptionDetails::PrintTaskOptionChangedEventArgs^ args);
00077
00078         /// <summary>
00079         /// Helper function used to triger a preview refresh
00080         /// </summary>
00081         void RefreshPreview();
00082     };
00083
00084     /// <summary>
00085     /// Scenario that demonstrates a page range implementation
00086     /// </summary>
00087     [Windows::Foundation::Metadata::WebHostHidden]
00088     public ref class Scenario4PageRange sealed
00089     {
00090     public:
00091         Scenario4PageRange();
00092         property Windows::UI::Xaml::Controls::Frame^ PrintFrame;
00093
00094     protected:
00095         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00096         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00097
00098     private:
00099         PrintHelper^ printHelper;
00100         void OnPrintButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00101     };
00102 }
Generated on Fri Nov 15 2024 22:21:03 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_Show Member List

This is the complete list of members for Scenario5_Show, including all inherited members.
rootPage | Scenario5_Show | [private]
Scenario5_Show() | Scenario5_Show | [inline]
Show_Click(object sender, RoutedEventArgs e) | Scenario5_Show | [inline, private]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInteractionMode/cppwinrt/Scenario1_Basic.h Source File

  • UserInteractionMode
  • cppwinrt

Scenario1_Basic.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Basic.g.h"
00015 #include "SampleConfiguration.h"
00016 #include "MainPage.h"
00017
00018 namespace winrt::SDKTemplate::implementation
00019 {
00020     struct Scenario1_Basic : Scenario1_BasicT<Scenario1_Basic>
00021     {
00022         Scenario1_Basic();
00023
00024         Windows::UI::Xaml::Style CheckBoxStyle()
00025         {
00026             return m_checkBoxStyle;
00027         }
00028
00029         Windows::UI::ViewManagement::UserInteractionMode InteractionMode()
00030         {
00031             return m_interactionMode;
00032         }
00033
00034         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00035         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00036
00037         event_token PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler);
00038         void PropertyChanged(event_token const& token) noexcept;
00039
00040     private:
00041         SDKTemplate::MainPage rootPage{ SDKTemplate::implementation::MainPage::Current() };
00042         event<Windows::UI::Xaml::Data::PropertyChangedEventHandler> m_propertyChanged;
00043         Windows::UI::Xaml::Style m_checkBoxStyle{ nullptr };
00044         Windows::UI::ViewManagement::UserInteractionMode m_interactionMode;
00045         event_token windowResizeToken;
00046
00047     private:
00048         void OnWindowResize(Windows::Foundation::IInspectable const&, Windows::UI::Core::WindowSizeChangedEventArgs const& e);
00049         void UpdateContent();
00050
00051     };
00052 }
00053
00054 namespace winrt::SDKTemplate::factory_implementation
00055 {
00056     struct Scenario1_Basic : Scenario1_BasicT<Scenario1_Basic, implementation::Scenario1_Basic>
00057     {
00058     };
00059 }
Generated on Fri Nov 15 2024 22:19:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFontImplementation/FontNameCollector.h Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFontImplementation

FontNameCollector.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014
00015 namespace DWriteTextLayoutCloudFontImplementation
00016 {
00017     // An implementation of IDWriteTextRender is included here solely to allow
00018     // us to get information back from the text layout about the fonts that
00019     // have been used. It is not required for using downloadable fonts, and
00020     // most of the methods have trivial implementations because they will
00021     // not be used.
00022     class FontNameCollector : public IDWriteTextRenderer
00023     {
00024     public:
00025         // Method to provide font names from a text layout
00026         std::wstring GetFontNames();
00027
00028         void ClearNames();
00029
00030         // IDWriteTextRenderer implementation
00031         HRESULT STDMETHODCALLTYPE DrawGlyphRun(
00032             _In_opt_ void* clientDrawingContext,
00033             FLOAT baselineOriginX,
00034             FLOAT baselineOriginY,
00035             DWRITE_MEASURING_MODE measuringMode,
00036             _In_ DWRITE_GLYPH_RUN const* glyphRun,
00037             _In_ DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
00038             _In_opt_ IUnknown* clientDrawingEffect
00039             ) override;
00040
00041         HRESULT STDMETHODCALLTYPE DrawInlineObject(
00042             _In_opt_ void* clientDrawingContext,
00043             FLOAT originX,
00044             FLOAT originY,
00045             _In_ IDWriteInlineObject* inlineObject,
00046             BOOL isSideways,
00047             BOOL isRightToLeft,
00048             _In_opt_ IUnknown* clientDrawingEffect
00049             ) override
00050         {
00051             return S_OK;
00052         }
00053
00054         HRESULT STDMETHODCALLTYPE DrawStrikethrough(
00055             _In_opt_ void* clientDrawingContext,
00056             FLOAT baselineOriginX,
00057             FLOAT baselineOriginY,
00058             _In_ DWRITE_STRIKETHROUGH const* strikethrough,
00059             _In_opt_ IUnknown* clientDrawingEffect
00060             ) override
00061         {
00062             return S_OK;
00063         }
00064
00065         HRESULT STDMETHODCALLTYPE DrawUnderline(
00066             _In_opt_ void* clientDrawingContext,
00067             FLOAT baselineOriginX,
00068             FLOAT baselineOriginY,
00069             _In_ DWRITE_UNDERLINE const* underline,
00070             _In_opt_ IUnknown* clientDrawingEffect
00071             ) override
00072         {
00073             return S_OK;
00074         }
00075
00076         // IDWriteTextRenderer inherits from IDWritePixelSnapping:
00077
00078         HRESULT STDMETHODCALLTYPE GetCurrentTransform(
00079             _In_opt_ void* clientDrawingContext,
00080             _Out_ DWRITE_MATRIX* transform
00081             ) override;
00082
00083         HRESULT STDMETHODCALLTYPE GetPixelsPerDip(
00084             _In_opt_ void* clientDrawingContext,
00085             _Out_ FLOAT* pixelsPerDip
00086             ) override;
00087
00088         HRESULT STDMETHODCALLTYPE IsPixelSnappingDisabled(
00089             _In_opt_ void* clientDrawingContext,
00090             _Out_ BOOL* isDisabled
00091             ) override;
00092
00093         // IDWritePixelSnapping inherits from IUnknown:
00094
00095         HRESULT STDMETHODCALLTYPE QueryInterface(
00096             REFIID riid,
00097             _COM_Outptr_ void **obj
00098             ) override;
00099
00100         ULONG STDMETHODCALLTYPE AddRef(void) override;
00101
00102         ULONG STDMETHODCALLTYPE Release(void) override;
00103
00104     private:
00105         uint32                  m_refCount = 0;
00106         std::set<std::wstring>  m_uniqueFontNames;
00107     };
00108 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/ActivationTypes/System/Dismiss/CustomContent/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • ActivationTypes
  • System
  • Dismiss
  • CustomContent

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Notifications;
00003 using Windows.UI.Popups;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00008
00009 namespace Notifications.ScenarioPages.Toasts.ActivationTypes.System.Dismiss.CustomContent
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     public sealed partial class ScenarioElement : UserControl
00015     {
00016         public ScenarioElement()
00017         {
00018             this.InitializeComponent();
00019         }
00020
00021         private void UserControl_Loaded(object sender, RoutedEventArgs e)
00022         {
00023             Initialize();
00024         }
00025
00026
00027         private void Initialize()
00028         {
00029             // Clear all existing notifications
00030             ToastNotificationManager.History.Clear();
00031
00032             // Pop reminder
00033             popToastControl.Payload =
00034                 $@"
00035                 <toast scenario='reminder' launch='args'>
00036                     <visual>
00037                         <binding template='ToastGeneric'>
00038                             <text>System Dismiss (Custom Content)</text>
00039                             <text>The button for dismissing should be localized in your language, generated by the system when displaying the toast.</text>
00040                         </binding>
00041                     </visual>
00042
00043                     <actions>
00044
00045                         <action activationType='system' arguments='dismiss' content='my dismiss' />
00046
00047                     </actions>
00048                 </toast>";
00049         }
00050
00051         private async void Error(string message)
00052         {
00053             await new MessageDialog(message, "ERROR").ShowAsync();
00054         }
00055     }
00056 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraResolution/cs/Scenario1_PreviewSettings.xaml.cs Source File

  • CameraResolution
  • cs

Scenario1_PreviewSettings.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using System;
00012 using System.Collections.Generic;
00013 using System.Linq;
00014 using System.Threading.Tasks;
00015 using Windows.Media.Capture;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// Scenario 1 Change camera preview settings
00024     /// </summary>
00025     public sealed partial class Scenario1_PreviewSettings : Page
00026     {
00027         // Private MainPage object for status updates
00028         private MainPage rootPage = MainPage.Current;
00029
00030         // Object to manage access to camera devices
00031         private MediaCapturePreviewer _previewer = null;
00032
00033         /// <summary>
00034         /// Initializes a new instance of the <see cref="Scenario1_PreviewSettings"/> class.
00035         /// </summary>
00036         public Scenario1_PreviewSettings()
00037         {
00038             this.InitializeComponent();
00039             _previewer = new MediaCapturePreviewer(PreviewControl, Dispatcher);
00040         }
00041
00042         protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
00043         {
00044             await _previewer.CleanupCameraAsync();
00045         }
00046
00047         /// <summary>
00048         /// Initializes the camera and populates the UI
00049         /// </summary>
00050         /// <param name="sender"></param>
00051         /// <param name="e"></param>
00052         private async void InitializeCameraButton_Click(object sender, RoutedEventArgs e)
00053         {
00054             var button = sender as Button;
00055
00056             // Clear any previous message.
00057             rootPage.NotifyUser("", NotifyType.StatusMessage);
00058
00059             button.IsEnabled = false;
00060             await _previewer.InitializeCameraAsync();
00061             button.IsEnabled = true;
00062
00063             if (_previewer.IsPreviewing)
00064             {
00065                 button.Visibility = Visibility.Collapsed;
00066                 PreviewControl.Visibility = Visibility.Visible;
00067                 PopulateSettingsComboBox();
00068             }
00069         }
00070
00071         /// <summary>
00072         ///  Event handler for Preview settings combo box. Updates stream resolution based on the selection.
00073         /// </summary>
00074         /// <param name="sender"></param>
00075         /// <param name="e"></param>
00076         private async void ComboBoxSettings_Changed(object sender, RoutedEventArgs e)
00077         {
00078             if (_previewer.IsPreviewing)
00079             {
00080                 var selectedItem = (sender as ComboBox).SelectedItem as ComboBoxItem;
00081                 var encodingProperties = (selectedItem.Tag as StreamResolution).EncodingProperties;
00082                 await _previewer.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, encodingProperties);
00083             }
00084         }
00085
00086         /// <summary>
00087         /// Populates the combo box with all possible combinations of settings returned by the camera driver
00088         /// </summary>
00089         private void PopulateSettingsComboBox()
00090         {
00091             // Query all properties of the device
00092             IEnumerable<StreamResolution> allProperties = _previewer.MediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoPreview).Select(x => new StreamResolution(x));
00093
00094             // Order them by resolution then frame rate
00095             allProperties = allProperties.OrderByDescending(x => x.Height * x.Width).ThenByDescending(x => x.FrameRate);
00096
00097             // Populate the combo box with the entries
00098             foreach (var property in allProperties)
00099             {
00100                 ComboBoxItem comboBoxItem = new ComboBoxItem();
00101                 comboBoxItem.Content = property.GetFriendlyName();
00102                 comboBoxItem.Tag = property;
00103                 CameraSettings.Items.Add(comboBoxItem);
00104             }
00105         }
00106     }
00107 }
Generated on Fri Nov 15 2024 22:18:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCoordinateMapper/cpp/Content/CameraCoordinateMapper.cpp Source File

  • CameraStreamCoordinateMapper
  • cpp
  • Content

CameraCoordinateMapper.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013
00014 #include "Common\DirectXHelper.h"
00015
00016 #include "CameraCoordinateMapper.h"
00017 #include "CameraStreamProcessor.h"
00018 #include "GpuCoordinateMapper.h"
00019
00020 #include <MemoryBuffer.h>
00021
00022 using namespace CameraStreamCoordinateMapper;
00023 using namespace concurrency;
00024
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Foundation::Numerics;
00027 using namespace Windows::Graphics::Imaging;
00028 using namespace Windows::Media::Capture;
00029 using namespace Windows::Media::Capture::Frames;
00030 using namespace Windows::Media::Devices::Core;
00031 using namespace Windows::Media::MediaProperties;
00032
00033 using namespace Microsoft::WRL;
00034
00035 namespace
00036 {
00037     template<typename Func>
00038     void AccessSoftwareBitmap(SoftwareBitmap^ bitmap, Func&& func)
00039     {
00040         if (BitmapBuffer^ bitmapBuffer = bitmap->LockBuffer(BitmapBufferAccessMode::Read))
00041         {
00042             if (IMemoryBufferReference^ bitmapRef = bitmapBuffer->CreateReference())
00043             {
00044                 ComPtr<IMemoryBufferByteAccess> memoryBufferByteAccess;
00045                 const HRESULT hr = reinterpret_cast<IInspectable*>(bitmapRef)->QueryInterface(IID_PPV_ARGS(&memoryBufferByteAccess));
00046
00047                 if (SUCCEEDED(hr) && memoryBufferByteAccess)
00048                 {
00049                     byte* pSourceBuffer;
00050                     UINT32 capacity;
00051                     if (SUCCEEDED(memoryBufferByteAccess->GetBuffer(&pSourceBuffer, &capacity)) && pSourceBuffer)
00052                     {
00053                         func(pSourceBuffer, capacity);
00054                     }
00055                 }
00056             }
00057         }
00058     }
00059
00060     void CopySoftwareBitmapToDirect3DTexture(SoftwareBitmap^ softwareBitmap, ID3D11DeviceContext* context, ID3D11Texture2D* texture)
00061     {
00062         AccessSoftwareBitmap(softwareBitmap, [&](byte* buffer, UINT32 capacity)
00063         {
00064             D3D11_MAPPED_SUBRESOURCE subresource;
00065             if (SUCCEEDED(context->Map(texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &subresource)))
00066             {
00067                 std::memcpy(subresource.pData, buffer, capacity);
00068                 context->Unmap(texture, 0);
00069             }
00070         });
00071     };
00072
00073     ////////////////////////////////////////////////////////////////////////////////
00074     // This is used to generate look-up tables based on the camera intrinsics
00075     //
00076     // For every point on the CameraIntrinsics from [0, imageWidth] and [0, imageHeight]
00077     // "func" will be called, and the result stored in the corresponding location in the
00078     // gpu texture. This allows us to utilize the camera intrinsics in shaders.
00079     template<typename Func>
00080     ComPtr<ID3D11Texture2D> GenerateIntrinsicsMapping(ID3D11Device* device, CameraIntrinsics^ cameraIntrinsics, Func&& func)
00081     {
00082         using OutputType = decltype(func(cameraIntrinsics, Point{}));
00083         static_assert(sizeof(OutputType) == sizeof(float2), "Func should return the equivalent of 2 floats");
00084
00085         const uint32_t imageWidth = cameraIntrinsics->ImageWidth;
00086         const uint32_t imageHeight = cameraIntrinsics->ImageHeight;
00087
00088         const size_t numElements = imageWidth * imageHeight;
00089
00090         auto spMap = std::make_unique<OutputType[]>(numElements);
00091
00092         for (uint32_t y = 0; y < imageHeight; ++y)
00093         {
00094             for (uint32_t x = 0; x < imageWidth; ++x)
00095             {
00096                 spMap[y * imageWidth + x] = func(cameraIntrinsics, Point(float(x), float(y)));
00097             }
00098         }
00099
00100         DX::TextureData data{ spMap.get(), sizeof(OutputType) };
00101         return DX::CreateTexture(
00102             device,
00103             imageWidth,
00104             imageHeight,
00105             DXGI_FORMAT_R32G32_FLOAT,
00106             data,
00107             D3D11_BIND_SHADER_RESOURCE,
00108             D3D11_USAGE_IMMUTABLE);
00109     }
00110
00111     bool IsValidColorFrame(MediaFrameReference^ frame)
00112     {
00113         // These properties are required for our coordinate mapping algorithm
00114         return frame &&
00115                frame->CoordinateSystem &&
00116                frame->VideoMediaFrame &&
00117                frame->VideoMediaFrame->CameraIntrinsics &&
00118                frame->VideoMediaFrame->SoftwareBitmap;
00119     }
00120
00121     bool IsValidDepthFrame(MediaFrameReference^ frame)
00122     {
00123         // A valid depth frame has the same properties of a color frame, as well as a valid DepthMediaFrame property
00124         return IsValidColorFrame(frame) && frame->VideoMediaFrame->DepthMediaFrame;
00125     }
00126 }
00127
00128 task<std::shared_ptr<CameraCoordinateMapper>> CameraCoordinateMapper::CreateAndStartAsync(std::shared_ptr<DX::DeviceResources> deviceResources)
00129 {
00130     // Future work: Support more color formats
00131     std::shared_ptr<CameraStreamProcessor> colorStreamProcessor;
00132     std::shared_ptr<CameraStreamProcessor> depthStreamProcessor;
00133
00134     // Creating the camera streams is not required to succeed, if there are failures we display an error message to the user
00135     try
00136     {
00137         colorStreamProcessor = co_await CameraStreamProcessor::CreateAndStartAsync(MediaFrameSourceKind::Color, MediaEncodingSubtypes::Bgra8);
00138         depthStreamProcessor = co_await CameraStreamProcessor::CreateAndStartAsync(MediaFrameSourceKind::Depth, MediaEncodingSubtypes::D16);
00139     }
00140     catch (Platform::Exception^ exception)
00141     {
00142         OutputDebugString(exception->Message->Data());
00143     }
00144
00145     return std::make_shared<CameraCoordinateMapper>(
00146         std::move(deviceResources),
00147         std::move(colorStreamProcessor),
00148         std::move(depthStreamProcessor));
00149 }
00150
00151 CameraCoordinateMapper::CameraCoordinateMapper(std::shared_ptr<DX::DeviceResources> deviceResources, std::shared_ptr<CameraStreamProcessor> colorStreamProcessor, std::shared_ptr<CameraStreamProcessor> depthStreamProcessor) :
00152     m_deviceResources(std::move(deviceResources)),
00153     m_colorCameraStreamProcessor(std::move(colorStreamProcessor)),
00154     m_depthCameraStreamProcessor(std::move(depthStreamProcessor))
00155 {
00156     m_gpuCoordinateMapper = std::make_unique<GpuCoordinateMapper>(m_deviceResources);
00157 }
00158
00159 void CameraCoordinateMapper::CreateDeviceDependentResources()
00160 {
00161     m_gpuCoordinateMapper->CreateDeviceDependentResources();
00162 }
00163
00164 void CameraCoordinateMapper::ReleaseDeviceDependentResources()
00165 {
00166     m_depthTexture = nullptr;
00167     m_depthTextureSRV = nullptr;
00168
00169     m_colorTexture = nullptr;
00170     m_colorTextureSRV = nullptr;
00171
00172     m_targetTexture = nullptr;
00173     m_targetTextureSRV = nullptr;
00174     m_targetTextureRTV = nullptr;
00175
00176     m_targetRasterizedDepthTexture = nullptr;
00177     m_targetRasterizedDepthTextureDSV = nullptr;
00178     m_targetRasterizedDepthTextureSRV = nullptr;
00179
00180     m_depthUnprojectionMapTexture = nullptr;
00181     m_depthUnprojectionMapTextureSRV = nullptr;
00182
00183     m_colorDistortionMapTexture = nullptr;
00184     m_colorDistortionMapTextureSRV = nullptr;
00185
00186     m_rasterizeFrameBlob = {};
00187     m_visualizeFrameBlob = {};
00188
00189     m_depthIntrinsics = {};
00190     m_colorIntrinsics = {};
00191
00192     m_depthFrameIndex = {};
00193     m_colorFrameIndex = {};
00194
00195     m_gpuCoordinateMapper->ReleaseDeviceDependentResources();
00196 }
00197
00198 task<void> CameraCoordinateMapper::StartAsync()
00199 {
00200     if (m_colorCameraStreamProcessor)
00201     {
00202         co_await m_colorCameraStreamProcessor->StartAsync();
00203     }
00204
00205     if (m_depthCameraStreamProcessor)
00206     {
00207         co_await m_depthCameraStreamProcessor->StartAsync();
00208     }
00209 }
00210
00211 task<void> CameraCoordinateMapper::StopAsync()
00212 {
00213     if (m_colorCameraStreamProcessor)
00214     {
00215         co_await m_colorCameraStreamProcessor->StopAsync();
00216     }
00217
00218     if (m_depthCameraStreamProcessor)
00219     {
00220         co_await m_depthCameraStreamProcessor->StopAsync();
00221     }
00222 }
00223
00224 bool CameraCoordinateMapper::TryAcquireLatestFrameData() try {
00225
00226     if (!m_colorCameraStreamProcessor || !m_depthCameraStreamProcessor)
00227     {
00228         return false;
00229     }
00230
00231     CameraStreamProcessor::FrameData colorFrameBlob = m_colorCameraStreamProcessor->GetLatestFrame();
00232     CameraStreamProcessor::FrameData depthFrameBlob = m_depthCameraStreamProcessor->GetLatestFrame();
00233
00234     MediaFrameReference^ colorFrame = colorFrameBlob.frame;
00235     MediaFrameReference^ depthFrame = depthFrameBlob.frame;
00236
00237     // Invalid color or depth frame
00238     if (!IsValidColorFrame(colorFrame) || !IsValidDepthFrame(depthFrame))
00239     {
00240         return false;
00241     }
00242
00243     const bool sameColorFrame = m_colorFrameIndex.has_value() && colorFrameBlob.index == m_colorFrameIndex.value();
00244     const bool sameDepthFrame = m_depthFrameIndex.has_value() && depthFrameBlob.index == m_depthFrameIndex.value();
00245
00246     // Already processed this frame
00247     if (sameColorFrame && sameDepthFrame)
00248     {
00249         return false;
00250     }
00251
00252     ID3D11DeviceContext* context = m_deviceResources->GetD3DDeviceContext();
00253
00254     if (!sameColorFrame)
00255     {
00256         UpdateColorResources(colorFrame);
00257         CopySoftwareBitmapToDirect3DTexture(colorFrame->VideoMediaFrame->SoftwareBitmap, context, m_colorTexture.Get());
00258
00259         m_rasterizeFrameBlob.sourceIntrinsics = m_colorIntrinsics;
00260         m_rasterizeFrameBlob.targetIntrinsics = m_colorIntrinsics;
00261
00262         const float4x4 colorProjectionMatrix = colorFrame->VideoMediaFrame->CameraIntrinsics->UndistortedProjectionTransform;
00263
00264         m_rasterizeFrameBlob.sourceProjectionMatrix = colorProjectionMatrix;
00265         m_rasterizeFrameBlob.targetProjectionMatrix = colorProjectionMatrix;
00266         m_rasterizeFrameBlob.sourceImage = m_colorTextureSRV;
00267         m_rasterizeFrameBlob.sourceDistortionMap = m_colorDistortionMapTextureSRV;
00268         m_rasterizeFrameBlob.targetImage = m_targetTextureRTV;
00269         m_rasterizeFrameBlob.targetRasterizedDepth = m_targetRasterizedDepthTextureDSV;
00270         m_rasterizeFrameBlob.targetDistortionMap = m_colorDistortionMapTextureSRV;
00271
00272         m_colorFrameIndex = colorFrameBlob.index;
00273     }
00274
00275     if (!sameDepthFrame)
00276     {
00277         UpdateDepthResources(depthFrame);
00278         CopySoftwareBitmapToDirect3DTexture(depthFrame->VideoMediaFrame->SoftwareBitmap, context, m_depthTexture.Get());
00279
00280         const float depthScaleInMeters = static_cast<float>(depthFrame->VideoMediaFrame->DepthMediaFrame->DepthFormat->DepthScaleInMeters);
00281
00282         m_rasterizeFrameBlob.depthIntrinsics = m_depthIntrinsics;
00283         m_rasterizeFrameBlob.depthScaleInMeters = depthScaleInMeters;
00284         m_rasterizeFrameBlob.depthRangeMinimumInMeters = static_cast<float>(depthFrame->VideoMediaFrame->DepthMediaFrame->MinReliableDepth) * depthScaleInMeters;
00285         m_rasterizeFrameBlob.depthRangeMaximumInMeters = static_cast<float>(depthFrame->VideoMediaFrame->DepthMediaFrame->MaxReliableDepth) * depthScaleInMeters;
00286         m_rasterizeFrameBlob.depthImage = m_depthTextureSRV;
00287         m_rasterizeFrameBlob.depthUnprojectionMap = m_depthUnprojectionMapTextureSRV;
00288
00289         m_depthFrameIndex = depthFrameBlob.index;
00290     }
00291
00292     Platform::IBox<float4x4>^ depthToColorRef = depthFrame->CoordinateSystem->TryGetTransformTo(colorFrame->CoordinateSystem);
00293
00294     if (depthToColorRef)
00295     {
00296         static const float4x4 leftToRight = make_float4x4_scale(1, 1, -1);
00297         static const float4x4 rightToLeft = leftToRight; // inverse is the same
00298
00299         // Camera coordinate systems are right-handed with -Z pointing forward out from the camera,
00300         // but camera intrinsics are left-handed with +Z pointing forward out from the camera.
00301         // Therefore we need to transform left-handed 3D coordinates from the intrinsics to right-handed
00302         // and back again when applying the coordinate system transforms which expect right-handed coordinates.
00303         m_rasterizeFrameBlob.depthToSource = leftToRight * depthToColorRef->Value * rightToLeft;
00304         m_rasterizeFrameBlob.depthToTarget = leftToRight * depthToColorRef->Value * rightToLeft;
00305     }
00306     else
00307     {
00308         throw std::exception("These camera frames can't be correlated");
00309     }
00310
00311     return true;
00312 }
00313 // If we're too slow while processing frames (i.e. running under a debugger), then we may access a VideoMediaFrame that was already closed.
00314 catch (Platform::ObjectDisposedException^)
00315 {
00316     return false;
00317 }
00318
00319 void CameraCoordinateMapper::RunCoordinateMapping()
00320 {
00321     m_gpuCoordinateMapper->RunCoordinateMapping(m_rasterizeFrameBlob);
00322 }
00323
00324 void CameraCoordinateMapper::VisualizeCoordinateMapping(ID3D11RenderTargetView * renderTarget, ID3D11DepthStencilView * depthBuffer, const D3D11_VIEWPORT & viewport, const Windows::Foundation::Numerics::float4x4 & worldToView)
00325 {
00326     const float aspectRatio = float(viewport.Width) / float(viewport.Height);
00327
00328     const float4x4 viewToProj = make_float4x4_perspective_field_of_view(DirectX::XMConvertToRadians(90.0f), aspectRatio, 0.001f, 100.0f);
00329
00330     m_visualizeFrameBlob.renderTarget = renderTarget;
00331     m_visualizeFrameBlob.renderTargetDepthBuffer = depthBuffer;
00332     m_visualizeFrameBlob.worldToView = worldToView;
00333     m_visualizeFrameBlob.viewToProj = viewToProj;
00334     m_visualizeFrameBlob.viewport = viewport;
00335
00336     m_gpuCoordinateMapper->VisualizeCoordinateMapping(m_rasterizeFrameBlob, m_visualizeFrameBlob);
00337
00338     m_visualizeFrameBlob.renderTargetDepthBuffer = nullptr;
00339     m_visualizeFrameBlob.renderTarget = nullptr;
00340 }
00341
00342 bool CameraCoordinateMapper::AreCamerasStreaming() const
00343 {
00344     const bool colorIsStreaming = m_colorCameraStreamProcessor && m_colorCameraStreamProcessor->IsStreaming();
00345     const bool depthIsStreaming = m_depthCameraStreamProcessor && m_depthCameraStreamProcessor->IsStreaming();
00346
00347     return colorIsStreaming && depthIsStreaming;
00348 }
00349
00350 ID3D11ShaderResourceView* CameraCoordinateMapper::GetTargetShaderResourceView() const
00351 {
00352     return m_targetTextureSRV.Get();
00353 }
00354
00355 float CameraCoordinateMapper::GetTargetAspectRatio() const
00356 {
00357     return static_cast<float>(m_colorIntrinsics.imageWidth) / static_cast<float>(m_colorIntrinsics.imageHeight);
00358 }
00359
00360 void CameraCoordinateMapper::UpdateDepthResources(Windows::Media::Capture::Frames::MediaFrameReference ^ depthFrame)
00361 {
00362     ID3D11Device* device = m_deviceResources->GetD3DDevice();
00363     ID3D11DeviceContext* context = m_deviceResources->GetD3DDeviceContext();
00364
00365     CameraIntrinsics^ depthIntrinsicsRt = depthFrame->VideoMediaFrame->CameraIntrinsics;
00366     const GpuCoordinateMapper::CameraIntrinsics depthIntrinsics(depthIntrinsicsRt);
00367
00368     // Only need to update the internal data if the intrinsics have changed
00369     if (depthIntrinsics != m_depthIntrinsics)
00370     {
00371         if (depthFrame->VideoMediaFrame->VideoFormat->MediaFrameFormat->Subtype != Windows::Media::MediaProperties::MediaEncodingSubtypes::D16)
00372         {
00373             throw std::invalid_argument("This depth format is not yet supported");
00374         }
00375
00376         m_depthTexture = DX::CreateTexture(
00377             device,
00378             depthIntrinsics.imageWidth,
00379             depthIntrinsics.imageHeight,
00380             DXGI_FORMAT_R16_UNORM,
00381             std::nullopt,
00382             D3D11_BIND_SHADER_RESOURCE,
00383             D3D11_USAGE_DYNAMIC,
00384             D3D11_CPU_ACCESS_WRITE);
00385
00386         m_depthTextureSRV = DX::CreateShaderResourceView(m_depthTexture.Get());
00387
00388         m_depthUnprojectionMapTexture = GenerateIntrinsicsMapping(device, depthIntrinsicsRt,
00389             [](CameraIntrinsics^ intrinsics, Point point)
00390         {
00391             return intrinsics->UnprojectAtUnitDepth(point);
00392         });
00393
00394         m_depthUnprojectionMapTextureSRV = DX::CreateShaderResourceView(m_depthUnprojectionMapTexture.Get());
00395
00396         m_depthIntrinsics = depthIntrinsics;
00397     }
00398 }
00399
00400 void CameraCoordinateMapper::UpdateColorResources(Windows::Media::Capture::Frames::MediaFrameReference ^ colorFrame)
00401 {
00402     ID3D11Device* device = m_deviceResources->GetD3DDevice();
00403     ID3D11DeviceContext* context = m_deviceResources->GetD3DDeviceContext();
00404
00405     CameraIntrinsics^ colorIntrinsicsRt = colorFrame->VideoMediaFrame->CameraIntrinsics;
00406     const GpuCoordinateMapper::CameraIntrinsics colorIntrinsics(colorIntrinsicsRt);
00407
00408     // Only need to update the internal data if the intrinsics have changed
00409     if (colorIntrinsics != m_colorIntrinsics)
00410     {
00411         // Future work: Support more color formats
00412         if (colorFrame->VideoMediaFrame->VideoFormat->MediaFrameFormat->Subtype != L"ARGB32")
00413         {
00414             throw std::invalid_argument("This video format is not yet supported");
00415         }
00416
00417         m_colorTexture = DX::CreateTexture(
00418             device,
00419             colorIntrinsics.imageWidth,
00420             colorIntrinsics.imageHeight,
00421             DXGI_FORMAT_B8G8R8A8_UNORM,
00422             std::nullopt,
00423             D3D11_BIND_SHADER_RESOURCE,
00424             D3D11_USAGE_DYNAMIC,
00425             D3D11_CPU_ACCESS_WRITE);
00426
00427         m_colorTextureSRV = DX::CreateShaderResourceView(m_colorTexture.Get());
00428
00429         m_colorDistortionMapTexture = GenerateIntrinsicsMapping(device, colorIntrinsicsRt,
00430             [](CameraIntrinsics^ intrinsics, Point point)
00431         {
00432             return intrinsics->DistortPoint(point);
00433         });
00434
00435         m_colorDistortionMapTextureSRV = DX::CreateShaderResourceView(m_colorDistortionMapTexture.Get());
00436
00437         m_targetTexture = DX::CreateTexture(
00438             device,
00439             colorIntrinsics.imageWidth,
00440             colorIntrinsics.imageHeight,
00441             DXGI_FORMAT_B8G8R8A8_UNORM,
00442             std::nullopt,
00443             D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET);
00444
00445         m_targetTextureSRV = DX::CreateShaderResourceView(m_targetTexture.Get());
00446         m_targetTextureRTV = DX::CreateRenderTargetView(m_targetTexture.Get());
00447
00448         m_targetRasterizedDepthTexture = DX::CreateTexture(
00449             device,
00450             colorIntrinsics.imageWidth,
00451             colorIntrinsics.imageHeight,
00452             DXGI_FORMAT_R24G8_TYPELESS,
00453             std::nullopt,
00454             D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_DEPTH_STENCIL);
00455
00456         m_targetRasterizedDepthTextureDSV = DX::CreateDepthStencilView(
00457             m_targetRasterizedDepthTexture.Get(),
00458             DXGI_FORMAT_D24_UNORM_S8_UINT);
00459
00460         m_targetRasterizedDepthTextureSRV = DX::CreateShaderResourceView(
00461             m_targetRasterizedDepthTexture.Get(),
00462             DXGI_FORMAT_R24_UNORM_X8_TYPELESS);
00463
00464         m_visualizeFrameBlob.targetImage = m_targetTextureSRV;
00465         m_visualizeFrameBlob.targetImageDepthBuffer = m_targetRasterizedDepthTextureSRV;
00466
00467         m_colorIntrinsics = colorIntrinsics;
00468     }
00469 }
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AdventureWorksVoiceCommandService Member List

This is the complete list of members for AdventureWorksVoiceCommandService, including all inherited members.
cortanaContext | AdventureWorksVoiceCommandService | [private]
cortanaResourceMap | AdventureWorksVoiceCommandService | [private]
dateFormatInfo | AdventureWorksVoiceCommandService | [private]
DisambiguateTrips(IEnumerable< Model.Trip > trips, string disambiguationMessage, string secondDisambiguationMessage) | AdventureWorksVoiceCommandService | [inline, private]
LaunchAppInForeground() | AdventureWorksVoiceCommandService | [inline, private]
OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) | AdventureWorksVoiceCommandService | [inline, private]
OnVoiceCommandCompleted(VoiceCommandServiceConnection sender, VoiceCommandCompletedEventArgs args) | AdventureWorksVoiceCommandService | [inline, private]
Run(IBackgroundTaskInstance taskInstance) | AdventureWorksVoiceCommandService | [inline]
SendCompletionMessageForCancellation(string destination) | AdventureWorksVoiceCommandService | [inline, private]
SendCompletionMessageForDestination(string destination) | AdventureWorksVoiceCommandService | [inline, private]
serviceDeferral | AdventureWorksVoiceCommandService | [private]
ShowProgressScreen(string message) | AdventureWorksVoiceCommandService | [inline, private]
voiceServiceConnection | AdventureWorksVoiceCommandService | [private]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/Scenario11.xaml.h Source File

  • SimpleInk
  • cpp

Scenario11.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario11.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario11 sealed
00024     {
00025     public:
00026         Scenario11();
00027
00028     private:
00029         Windows::UI::ViewManagement::AccessibilitySettings^ accessibility;
00030
00031         void Accessibility_HighContrastChanged(Windows::UI::ViewManagement::AccessibilitySettings^ sender, Platform::Object^ args);
00032         void ContrastingColorButtonCheckedChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033         void OnSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00034     };
00035 }
Generated on Fri Nov 15 2024 22:17:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DGradientMesh/cpp/App.h Source File

  • D2DGradientMesh
  • cpp

App.h

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include "pch.h"
00011 #include "DeviceResources.h"
00012 #include "D2DGradientMeshMain.h"
00013
00014 namespace D2DGradientMesh
00015 {
00016     // Main entry point for our app. Connects the app with the Windows shell and handles application lifecycle events.
00017     ref class App sealed : public Windows::ApplicationModel::Core::IFrameworkView
00018     {
00019     public:
00020         App();
00021
00022         // IFrameworkView Methods.
00023         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00024         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00025         virtual void Load(Platform::String^ entryPoint);
00026         virtual void Run();
00027         virtual void Uninitialize();
00028
00029     protected:
00030         // Application lifecycle event handlers.
00031         void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00032         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00033         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00034
00035         // Window event handlers.
00036         void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args);
00037         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00038         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00039
00040         // DisplayInformation event handlers.
00041         void OnDpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00042         void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00043         void OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00044
00045     private:
00046         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00047         std::unique_ptr<D2DGradientMeshMain> m_main;
00048         bool m_windowClosed;
00049         bool m_windowVisible;
00050     };
00051 }
00052
00053 ref class DirectXApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00054 {
00055 public:
00056     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00057 };
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/Content/ToolCarousel.h Source File

  • SpatialInteractionSource
  • cpp
  • Content

ToolCarousel.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "Tool.h"
00004 #include "..\Common\StepTimer.h"
00005
00006 namespace HolographicPaint
00007 {
00008     enum class RotationDirection : int { RotateLeft = -1, RotateRight = 1 };
00009
00010     // Class responsible for arranging tools in 3D Space and animating them
00011     class ToolCarousel
00012     {
00013     public:
00014         void SetPosition(
00015             Windows::Foundation::Numerics::float3 center,
00016             Windows::Foundation::Numerics::float3 radius,
00017             Windows::Foundation::Numerics::float3 rotationAxis);
00018
00019         void ArrangeTools(std::vector<std::shared_ptr<Tool>>& tools, size_t selectedIndex, double baseAngle = 0.0);
00020
00021         void StartRotation(RotationDirection rotationDirection, const DX::StepTimer& timer);
00022
00023         void Update(std::vector<std::shared_ptr<Tool>>& tools, size_t& selectedIndex, const DX::StepTimer& timer);
00024
00025         bool IsRotating() const { return m_isRotating; }
00026
00027     private:
00028         Windows::Foundation::Numerics::float3 m_center;
00029         Windows::Foundation::Numerics::float3 m_radius;
00030         Windows::Foundation::Numerics::float3 m_rotationAxis;
00031
00032         bool m_isRotating = false;
00033         RotationDirection m_rotationDirection;
00034         double m_rotationStart = 0.0;
00035     };
00036
00037 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MIDI/cs/SampleConfiguration.cs Source File

  • MIDI
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using MIDI;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "MIDI";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="MIDI Device Enumeration", ClassType=typeof(Scenario1_MIDIDeviceEnumeration)},
00026             new Scenario() { Title="Receive MIDI Messages", ClassType=typeof(Scenario2_ReceiveMIDIMessages)},
00027             new Scenario() { Title="Send MIDI Messages", ClassType=typeof(Scenario3_SendMIDIMessages)}
00028         };
00029     }
00030
00031     public class Scenario
00032     {
00033         public string Title { get; set; }
00034         public Type ClassType { get; set; }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MultipleViews/cppwinrt/SecondaryViewPage.h Source File

  • MultipleViews
  • cppwinrt

SecondaryViewPage.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "SecondaryViewPage.g.h"
00015 #include "SampleConfiguration.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct SecondaryViewPage : SecondaryViewPageT<SecondaryViewPage>
00020     {
00021         SecondaryViewPage();
00022         fire_and_forget SwitchAndAnimate(int32_t fromViewId);
00023         void HandleProtocolLaunch(Windows::Foundation::Uri const& uri);
00024
00025         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00026
00027         fire_and_forget GoToMain_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00028         fire_and_forget HideView_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00029         void SetTitle_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00030         void ClearTitle_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00031         fire_and_forget ProtocolLaunch_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00032
00033     private:
00034         Windows::UI::Xaml::Media::Animation::Storyboard m_enterAnimation{ nullptr };
00035         ViewLifetimeControl m_thisViewControl{ nullptr };
00036         event_token m_releasedToken;
00037
00038         fire_and_forget View_Released(SDKTemplate::ViewLifetimeControl const& sender, Windows::Foundation::IInspectable const&);
00039         fire_and_forget SetTitle(hstring newTitle);
00040         Windows::UI::Xaml::Media::Animation::Storyboard CreateEnterAnimation();
00041
00042     };
00043 }
00044
00045 namespace winrt::SDKTemplate::factory_implementation
00046 {
00047     struct SecondaryViewPage : SecondaryViewPageT<SecondaryViewPage, implementation::SecondaryViewPage>
00048     {
00049     };
00050 }
Generated on Fri Nov 15 2024 22:20:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/Common/PersistentState.h Source File

  • Simple3DGameDX
  • cpp
  • Common

PersistentState.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 // A simple helper class that provides support for saving and loading various
00011 // data types to an IPropertySet. Used by DirectX SDK samples to implement
00012 // process lifetime management (PLM).
00013 ref class PersistentState
00014 {
00015 internal:
00016     void Initialize(
00017         _In_ Windows::Foundation::Collections::IPropertySet^ settingsValues,
00018         _In_ Platform::String^ key
00019         );
00020
00021     void SaveBool(Platform::String^ key, bool value);
00022     void SaveInt32(Platform::String^ key, int value);
00023     void SaveSingle(Platform::String^ key, float value);
00024     void SaveXMFLOAT3(Platform::String^ key, DirectX::XMFLOAT3 value);
00025     void SaveString(Platform::String^ key, Platform::String^ string);
00026
00027     bool LoadBool(Platform::String^ key, bool defaultValue);
00028     int  LoadInt32(Platform::String^ key, int defaultValue);
00029     float LoadSingle(Platform::String^ key, float defaultValue);
00030     DirectX::XMFLOAT3 LoadXMFLOAT3(Platform::String^ key, DirectX::XMFLOAT3 defaultValue);
00031     Platform::String^ LoadString(Platform::String^ key, Platform::String^ defaultValue);
00032
00033 private:
00034     Platform::String^ m_keyName;
00035     Windows::Foundation::Collections::IPropertySet^ m_settingsValues;
00036 };
Generated on Fri Nov 15 2024 22:21:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboardTextInput/cpp/Scenario1_SpellingTextSuggestions.xaml.h Source File

  • TouchKeyboardTextInput
  • cpp

Scenario1_SpellingTextSuggestions.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_SpellingTextSuggestions.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario1_SpellingTextSuggestions sealed
00024     {
00025     public:
00026         Scenario1_SpellingTextSuggestions();
00027     };
00028 }
Generated on Fri Nov 15 2024 22:21:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RequiredDeviceProperties Member List

This is the complete list of members for RequiredDeviceProperties, including all inherited members.
AddProps(IList< string > list) | RequiredDeviceProperties | [inline, static]
DEVPKEY_AepContainer_Categories | RequiredDeviceProperties | [static]
DEVPKEY_AepContainer_FriendlyName | RequiredDeviceProperties | [static]
DEVPKEY_AepContainer_SupportedUriSchemes | RequiredDeviceProperties | [static]
DEVPKEY_AepContainer_SupportsAudio | RequiredDeviceProperties | [static]
DEVPKEY_AepContainer_SupportsImages | RequiredDeviceProperties | [static]
DEVPKEY_AepContainer_SupportsVideo | RequiredDeviceProperties | [static]
DEVPKEY_Device_ContainerId | RequiredDeviceProperties | [static]
DEVPKEY_Device_InstanceId | RequiredDeviceProperties | [static]
DEVPKEY_DeviceContainer_Manufacturer | RequiredDeviceProperties | [static]
DEVPKEY_DeviceContainer_ModelName | RequiredDeviceProperties | [static]
Props | RequiredDeviceProperties | [static]
RequiredDeviceProperties() | RequiredDeviceProperties | [inline, private]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/Scenario5Photos.xaml.cpp Source File

  • Printing
  • cpp

Scenario5Photos.xaml.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario5Photos.xaml.h"
00005 #include "PageToPrint.xaml.h"
00006 #include "PreviewUnavailable.xaml.h"
00007 #include <robuffer.h>
00008 #include <wrl\client.h>
00009 #include <sstream>
00010
00011 using namespace SDKTemplate;
00012
00013 using namespace Platform;
00014 using namespace Windows::Foundation;
00015 using namespace Windows::Foundation::Collections;
00016 using namespace Windows::Graphics::Display;
00017 using namespace Windows::Graphics::Imaging;
00018 using namespace Windows::Graphics::Printing;
00019 using namespace Windows::Graphics::Printing::OptionDetails;
00020 using namespace Windows::UI;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Documents;
00024 using namespace Windows::UI::Xaml::Media;
00025 using namespace Windows::UI::Xaml::Media::Imaging;
00026 using namespace Windows::UI::Xaml::Navigation;
00027 using namespace Windows::Storage;
00028 using namespace Windows::Storage::Streams;
00029
00030 /// <summary>
00031 /// This is the event handler for PrintManager.PrintTaskRequested.
00032 /// In order to ensure a good user experience, the system requires that the app handle the PrintTaskRequested event within the time specified
00033 /// by PrintTaskRequestedEventArgs->Request->Deadline.
00034 /// Therefore, we use this handler to only create the print task.
00035 /// The print settings customization can be done when the print document source is requested.
00036 /// </summary>
00037 /// <param name="sender">The print manager for which a print task request was made.</param>
00038 /// <param name="e">The print taks request associated arguments.</param>
00039 void PhotosPrintHelper::PrintTaskRequested(PrintManager^ sender, PrintTaskRequestedEventArgs^ e)
00040 {
00041     PrintTask^ printTask = e->Request->CreatePrintTask("C++ Printing SDK Sample", ref new PrintTaskSourceRequestedHandler([=](PrintTaskSourceRequestedArgs^ args)
00042     {
00043         // Set the document source.
00044         args->SetSource(PrintDocumentSource);
00045     }));
00046
00047     // Choose the printer options to be shown.
00048     // The order in which the options are appended determines the order in which they appear in the UI
00049     PrintTaskOptionDetails^ printDetailedOptions = PrintTaskOptionDetails::GetFromPrintTaskOptions(printTask->Options);
00050     printDetailedOptions->DisplayedOptions->Clear();
00051     printDetailedOptions->DisplayedOptions->Append(Windows::Graphics::Printing::StandardPrintTaskOptions::MediaSize);
00052     printDetailedOptions->DisplayedOptions->Append(Windows::Graphics::Printing::StandardPrintTaskOptions::Copies);
00053
00054     // Create a new list option.
00055     PrintCustomItemListOptionDetails^ photoSize = printDetailedOptions->CreateItemListOption("photoSize", "Photo Size");
00056     photoSize->AddItem("SizeFullPage", "Full Page");
00057     photoSize->AddItem("Size4x6", "4 x 6 in");
00058     photoSize->AddItem("Size5x7", "5 x 7 in");
00059     photoSize->AddItem("Size8x10", "8 x 10 in");
00060
00061     // Add the custom option to the option list.
00062     printDetailedOptions->DisplayedOptions->Append("photoSize");
00063
00064     PrintCustomItemListOptionDetails^ scaling = printDetailedOptions->CreateItemListOption("scaling", "Scaling");
00065     scaling->AddItem("ShrinkToFit", "Shrink To Fit");
00066     scaling->AddItem("Crop", "Crop");
00067
00068     // Add the custom option to the option list.
00069     printDetailedOptions->DisplayedOptions->Append("scaling");
00070
00071     // Set default orientation to landscape.
00072     printTask->Options->Orientation = PrintOrientation::Landscape;
00073
00074     // Register for print task option changed notifications.
00075     printDetailedOptions->OptionChanged += ref new TypedEventHandler<PrintTaskOptionDetails^, PrintTaskOptionChangedEventArgs^>(this, &PhotosPrintHelper::PrintDetailedOptionsOptionChanged);
00076
00077     // Print Task event handler is invoked when the print job is completed.
00078     printTask->Completed += ref new TypedEventHandler<PrintTask^, PrintTaskCompletedEventArgs^>([=](PrintTask^ sender, PrintTaskCompletedEventArgs^ e)
00079     {
00080         auto callback = ref new Windows::UI::Core::DispatchedHandler([=]()
00081         {
00082             ClearPageCollection();
00083
00084             // Reset image options to default values.
00085             m_photoScale = Scaling::ShrinkToFit;
00086             m_photoSize = PhotoSize::SizeFullPage;
00087
00088             // Reset the current page description ( modify any size)
00089             m_currentPageDescription = PageDescription();
00090
00091             // Notify the user when the print operation fails.
00092             if (e->Completion == Windows::Graphics::Printing::PrintTaskCompletion::Failed)
00093             {
00094                 MainPage::Current->NotifyUser(ref new String(L"Failed to print."), NotifyType::ErrorMessage);
00095             }
00096         });
00097
00098         ScenarioPage->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00099     });
00100 }
00101
00102 /// <summary>
00103 /// Option change event handler
00104 /// </summary>
00105 /// <param name="sender">The print task option details for which an option changed.</param>
00106 /// <param name="args">The event arguments containing the id of the changed option.</param>
00107 void PhotosPrintHelper::PrintDetailedOptionsOptionChanged(PrintTaskOptionDetails^ sender, PrintTaskOptionChangedEventArgs^ args)
00108 {
00109     bool invalidatePreview = false;
00110
00111     // For this scenario we are interested only when the 2 custom options change (photoSize & scaling) in order to trigger a preview refresh.
00112     // Default options that change page aspect will trigger preview invalidation (refresh) automatically.
00113     // It is safe to ignore verifying other options and(or) combinations here because during Paginate event(CreatePrintPreviewPages) we check if the PageDescription changed.
00114     if (args->OptionId == nullptr)
00115     {
00116         return;
00117     }
00118
00119     String^ optionId = safe_cast<String^>(args->OptionId);
00120     if (optionId == "photoSize")
00121     {
00122         IPrintOptionDetails^ photoSizeOption = sender->Options->Lookup(optionId);
00123         String^ photoSizeValue = safe_cast<String^>(photoSizeOption->Value);
00124
00125         if (photoSizeValue == "SizeFullPage")
00126         {
00127             m_photoSize = PhotoSize::SizeFullPage;
00128         }
00129         else if (photoSizeValue == "Size4x6")
00130         {
00131             m_photoSize = PhotoSize::Size4x6;
00132         }
00133         else if (photoSizeValue == "Size5x7")
00134         {
00135             m_photoSize = PhotoSize::Size5x7;
00136         }
00137         else if (photoSizeValue == "Size8x10")
00138         {
00139             m_photoSize = PhotoSize::Size8x10;
00140         }
00141         invalidatePreview = true;
00142     }
00143
00144     if (optionId == "scaling")
00145     {
00146         IPrintOptionDetails^ scalingOption = sender->Options->Lookup(optionId);
00147         String^ scalingValue = safe_cast<String^>(scalingOption->Value);
00148
00149         if (scalingValue == "Crop")
00150         {
00151             m_photoScale = Scaling::Crop;
00152         }
00153         if (scalingValue == "ShrinkToFit")
00154         {
00155             m_photoScale = Scaling::ShrinkToFit;
00156         }
00157         invalidatePreview = true;
00158     }
00159
00160     // Invalidate the preview if one of the 2 options (photoSize, scaling) changed.
00161     if (invalidatePreview)
00162     {
00163         RefreshPreview();
00164     }
00165 }
00166
00167 /// <summary>
00168 /// This is the event handler for Pagination.
00169 /// </summary>
00170 /// <param name="sender">The document for which pagination occurs.</param>
00171 /// <param name="e">The pagination event arguments containing the print options.</param>
00172 void PhotosPrintHelper::CreatePrintPreviewPages(Object^ sender, PaginateEventArgs^ e)
00173 {
00174     // A new "session" starts with each paginate event.
00175     InterlockedIncrement64(&m_requestCount);
00176
00177     // Get printer's page description.
00178     PrintTaskOptionDetails^ printDetailedOptions = PrintTaskOptionDetails::GetFromPrintTaskOptions(e->PrintTaskOptions);
00179     PrintPageDescription printPageDescription = e->PrintTaskOptions->GetPageDescription(0);
00180
00181     // Reset the error state
00182     printDetailedOptions->Options->Lookup("photoSize")->ErrorText = "";
00183
00184     // Compute the printing page description (page size & center printable area)
00185     PageDescription pageDescription;
00186     pageDescription.PageSize = printPageDescription.PageSize;
00187
00188     pageDescription.Margin.Width = (std::max)(printPageDescription.ImageableRect.Left,
00189         printPageDescription.ImageableRect.Right - printPageDescription.PageSize.Width);
00190
00191     pageDescription.Margin.Height = (std::max)(printPageDescription.ImageableRect.Top,
00192         printPageDescription.ImageableRect.Bottom - printPageDescription.PageSize.Height);
00193
00194     pageDescription.ViewablePageSize.Width = printPageDescription.PageSize.Width - pageDescription.Margin.Width * 2;
00195     pageDescription.ViewablePageSize.Height = printPageDescription.PageSize.Height - pageDescription.Margin.Height * 2;
00196
00197     // Compute print photo area.
00198     switch (m_photoSize)
00199     {
00200     case PhotoSize::Size4x6:
00201         pageDescription.PictureViewSize.Width = 4.0f * DPI96;
00202         pageDescription.PictureViewSize.Height = 6.0f * DPI96;
00203         break;
00204     case PhotoSize::Size5x7:
00205         pageDescription.PictureViewSize.Width = 5.0f * DPI96;
00206         pageDescription.PictureViewSize.Height = 7.0f * DPI96;
00207         break;
00208     case PhotoSize::Size8x10:
00209         pageDescription.PictureViewSize.Width = 8.0f * DPI96;
00210         pageDescription.PictureViewSize.Height = 10.0f * DPI96;
00211         break;
00212     case PhotoSize::SizeFullPage:
00213         pageDescription.PictureViewSize.Width = pageDescription.ViewablePageSize.Width;
00214         pageDescription.PictureViewSize.Height = pageDescription.ViewablePageSize.Height;
00215         break;
00216     }
00217
00218     // Try to maximize the photo's size based on its aspect-ratio.
00219     if ((pageDescription.ViewablePageSize.Width > pageDescription.ViewablePageSize.Height) && (m_photoSize != PhotoSize::SizeFullPage))
00220     {
00221         auto swap = pageDescription.PictureViewSize.Width;
00222         pageDescription.PictureViewSize.Width = pageDescription.PictureViewSize.Height;
00223         pageDescription.PictureViewSize.Height = swap;
00224     }
00225
00226     pageDescription.IsContentCropped = m_photoScale == Scaling::Crop;
00227
00228     // Recreate content only when :
00229     // - there is no current page description
00230     // - the current page description doesn't match the new one
00231     if (m_currentPageDescription != pageDescription)
00232     {
00233         ClearPageCollection();
00234         PrintDocument^ printDocument = safe_cast<PrintDocument^>(sender);
00235
00236         if (pageDescription.PictureViewSize.Width > pageDescription.ViewablePageSize.Width ||
00237             pageDescription.PictureViewSize.Height > pageDescription.ViewablePageSize.Height)
00238         {
00239             printDetailedOptions->Options->Lookup("photoSize")->ErrorText = "Photo doesn’t fit on the selected paper";
00240
00241             // Inform preview that it has only 1 page to show.
00242             printDocument->SetPreviewPageCount(1, PreviewPageCountType::Intermediate);
00243
00244             // Add a custom "preview" unavailable page
00245             m_csPrintSync.lock();
00246             m_pageCollection[0] = ref new PreviewUnavailable(pageDescription.PageSize, pageDescription.ViewablePageSize);
00247             m_csPrintSync.unlock();
00248         }
00249         else
00250         {
00251             // Inform preview that is has #NumberOfPhotos pages to show.
00252             printDocument->SetPreviewPageCount(NumberOfPhotos, PreviewPageCountType::Intermediate);
00253         }
00254
00255         m_currentPageDescription = pageDescription;
00256     }
00257 }
00258
00259 /// <summary>
00260 /// This is the event handler for PrintDocument.GetPrintPreviewPage. It provides a specific print page preview,
00261 /// in the form of an UIElement, to an instance of PrintDocument.
00262 /// PrintDocument subsequently converts the UIElement into a page that the Windows print system can deal with.
00263 /// </summary>
00264 /// <param name="sender">The print documet.</param>
00265 /// <param name="e">Arguments containing the requested page preview.</param>
00266 void PhotosPrintHelper::GetPrintPreviewPage(Object^ sender, GetPreviewPageEventArgs^ e)
00267 {
00268     PrintDocument^ printDocument = safe_cast<PrintDocument^>(sender);
00269
00270     // Store a local copy of the request count to use later to determine if the computed page is out of date.
00271     // If the page preview is unavailable an async operation will generate the content.
00272     // When the operation completes there is a chance that a pagination request was already made therefore making this page outdated.
00273     // If the page is outdated throw away the result (don't call SetPreviewPage) since a new GetPrintPreviewPage will server that request.
00274     LONGLONG requestNumber = 0;
00275     InterlockedExchange64(&requestNumber, m_requestCount);
00276     int pageNumber = e->PageNumber;
00277
00278     UIElement^ page;
00279
00280     // Try to get the page if it was previously generated.
00281     m_csPrintSync.lock();
00282     auto result = m_pageCollection.find(pageNumber - 1);
00283     if (result != m_pageCollection.end())
00284     {
00285         page = result->second;
00286     }
00287     m_csPrintSync.unlock();
00288
00289
00290     // Detect if the page is available.
00291     if (page != nullptr)
00292     {
00293         // Send the page to preview.
00294         printDocument->SetPreviewPage(pageNumber, page);
00295     }
00296     else
00297     {
00298         // The page is not available yet.
00299         GeneratePageAsync(pageNumber, m_currentPageDescription).then([=](UIElement^ page)
00300         {
00301             // If the ticket changed discard the result since the content is outdated.
00302             LONGLONG localRequestNumber = requestNumber;
00303             if (InterlockedCompareExchange64(&localRequestNumber, requestNumber, m_requestCount) == m_requestCount)
00304             {
00305                 // Store the page in the collection in case a pagination request is made but the content doesn't need to be regenerated.
00306                 m_csPrintSync.lock();
00307                 m_pageCollection[pageNumber - 1] = page;
00308
00309                 // Add the newly created page to the printing root which is part of the visual tree and force it to go
00310                 // through layout so that the linked containers correctly distribute the content inside them.
00311                 PrintCanvas->Children->Append(page);
00312                 PrintCanvas->InvalidateMeasure();
00313                 PrintCanvas->UpdateLayout();
00314                 m_csPrintSync.unlock();
00315
00316                 // Send the page to preview.
00317                 printDocument->SetPreviewPage(pageNumber, page);
00318             }
00319         });
00320     }
00321 }
00322
00323 /// <summary>
00324 /// This is the event handler for PrintDocument.AddPages. It provides all pages to be printed, in the form of
00325 /// UIElements, to an instance of PrintDocument. PrintDocument subsequently converts the UIElements
00326 /// into a pages that the Windows print system can deal with.
00327 /// </summary>
00328 /// <param name="sender">The print document.</param>
00329 /// <param name="e">Arguments containing the print task options.</param>
00330 void PhotosPrintHelper::AddPrintPages(Object^ sender, AddPagesEventArgs^ e)
00331 {
00332     PrintDocument^ printDocument = safe_cast<PrintDocument^>(sender);
00333
00334     // A list of tasks that will generate content for pages that are not ready at this point.
00335     std::vector<concurrency::task<void>> createPageTasks;
00336
00337     for (int i = 0; i < NumberOfPhotos; ++i)
00338     {
00339         UIElement^ page = nullptr;
00340
00341         m_csPrintSync.lock();
00342         auto value = m_pageCollection.find(i);
00343         if (value != m_pageCollection.end())
00344         {
00345             page = value->second;
00346         }
00347         m_csPrintSync.unlock();
00348
00349         if (page != nullptr)
00350         {
00351             m_pageCollection[i] = page;
00352         }
00353
00354         // If the page is not ready create a task that will generate its content.
00355         createPageTasks.push_back(GeneratePageAsync(i + 1, m_currentPageDescription).then([=](UIElement^ generatedPage)
00356         {
00357             m_pageCollection[i] = generatedPage;
00358         }));
00359     }
00360
00361     // Add the pages to the print document when content has been generated for all of them.
00362     concurrency::when_all(createPageTasks.begin(), createPageTasks.end()).then([=]
00363     {
00364         std::for_each(m_pageCollection.begin(), m_pageCollection.end(), [=](std::pair<int, UIElement^> keyValue)
00365         {
00366             printDocument->AddPage(keyValue.second);
00367         });
00368
00369         // Indicate that all of the print pages have been provided.
00370         printDocument->AddPagesComplete();
00371     });
00372
00373     // Reset the current page description as soon as possible since the PrintTask.Completed event might fire later (long running job)
00374     m_currentPageDescription = PageDescription();
00375 }
00376
00377 /// <summary>
00378 /// Helper function used to triger a preview refresh
00379 /// </summary>
00380 void PhotosPrintHelper::RefreshPreview()
00381 {
00382     // Invalidate the preview in order to refresh cotent and trigger a pagination request.
00383     auto callback = ref new Windows::UI::Core::DispatchedHandler([this]()
00384     {
00385         CurrentPrintDocument->InvalidatePreview();
00386     });
00387
00388     ScenarioPage->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00389 }
00390
00391 /// <summary>
00392 /// Helper function that clears the page collection and also the pages attached to the "visual root".
00393 /// </summary>
00394 void PhotosPrintHelper::ClearPageCollection()
00395 {
00396     m_csPrintSync.lock();
00397
00398     m_pageCollection.clear();
00399     PrintCanvas->Children->Clear();
00400
00401     m_csPrintSync.unlock();
00402 }
00403
00404 /// <summary>
00405 /// Generic swap of 2 values
00406 /// </summary>
00407 /// <typeparam name="T">typename</typeparam>
00408 /// <param name="v1">Value 1</param>
00409 /// <param name="v2">Value 2</param>
00410 template<class T> static void PhotosPrintHelper::Swap(T& v1, T& v2)
00411 {
00412     T swap = v1;
00413     v1 = v2;
00414     v2 = swap;
00415 }
00416
00417 /// <summary>
00418 /// Generates a page containing a photo.
00419 /// The image will be rotated if detected that there is a gain from that regarding size (try to maximize photo size).
00420 /// </summary>
00421 /// <param name="photoNumber">The photo number.</param>
00422 /// <param name="pageDescription">The description of the printer page.</param>
00423 /// <returns>A task that will return the page.</returns>
00424 concurrency::task<UIElement^> PhotosPrintHelper::GeneratePageAsync(int photoNumber, PageDescription pageDescription)
00425 {
00426     Canvas^ page = ref new Canvas();
00427     page->Width = pageDescription.PageSize.Width;
00428     page->Height = pageDescription.PageSize.Height;
00429
00430     Canvas^ viewablePage = ref new Canvas();
00431     viewablePage->Width = pageDescription.ViewablePageSize.Width;
00432     viewablePage->Height = pageDescription.ViewablePageSize.Height;
00433
00434     viewablePage->SetValue(Canvas::LeftProperty, pageDescription.Margin.Width);
00435     viewablePage->SetValue(Canvas::TopProperty, pageDescription.Margin.Height);
00436
00437     // The image "frame" which also acts as a viewport
00438     Grid^ photoView = ref new Grid();
00439     photoView->Width = pageDescription.PictureViewSize.Width;
00440     photoView->Height = pageDescription.PictureViewSize.Height;
00441
00442     // Center the frame.
00443     photoView->SetValue(Canvas::LeftProperty, (viewablePage->Width - photoView->Width) / 2);
00444     photoView->SetValue(Canvas::TopProperty, (viewablePage->Height - photoView->Height) / 2);
00445
00446     std::wostringstream imageUriStream;
00447     imageUriStream << "ms-appx:///Assets/photo" << photoNumber << ".jpg";
00448
00449     String^ imageUri = ref new String(imageUriStream.str().data());
00450
00451     // Return an async task that will complete when the image is fully loaded.
00452     return LoadBitmapAsync(ref new Uri(imageUri), pageDescription.PageSize.Width > pageDescription.PageSize.Height).then([=](WriteableBitmap^ bitmap) -> UIElement^
00453     {
00454         if (bitmap != nullptr)
00455         {
00456             Image^ image = ref new Image();
00457             image->Source = bitmap;
00458             image->HorizontalAlignment = Windows::UI::Xaml::HorizontalAlignment::Center;
00459             image->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Center;
00460
00461             // Use the real image size when croping or if the image is smaller then the target area (prevent a scale-up).
00462             if (m_photoScale == Scaling::Crop || (bitmap->PixelWidth <= pageDescription.PictureViewSize.Width &&
00463                 bitmap->PixelHeight <= pageDescription.PictureViewSize.Height))
00464             {
00465                 image->Stretch = Stretch::None;
00466                 image->Width = bitmap->PixelWidth;
00467                 image->Height = bitmap->PixelHeight;
00468             }
00469
00470             // Add the newly created image to the visual root.
00471             photoView->Children->Append(image);
00472             viewablePage->Children->Append(photoView);
00473             page->Children->Append(viewablePage);
00474         }
00475
00476         // Return the page with the image centered.
00477         return page;
00478     });
00479 }
00480
00481 /// <summary>
00482 /// Loads an image from an uri source and performs a rotation based on the print target aspect.
00483 /// </summary>
00484 /// <param name="source">The location of the image.</param>
00485 /// <param name="landscape">A flag that indicates if the target (printer page) is in landscape mode.</param>
00486 /// <returns>A task that will return the loaded bitmap.</returns>
00487 concurrency::task<WriteableBitmap^> PhotosPrintHelper::LoadBitmapAsync(Uri^ source, bool landscape)
00488 {
00489     return concurrency::create_task(StorageFile::GetFileFromApplicationUriAsync(source)).then([](StorageFile^ file)
00490     {
00491         return file->OpenAsync(FileAccessMode::Read);
00492     }).then([](IRandomAccessStream^ stream)
00493     {
00494         return BitmapDecoder::CreateAsync(stream);
00495     }).then([landscape](BitmapDecoder^ bitmapDecoder)
00496     {
00497         BitmapTransform^ transform = ref new BitmapTransform();
00498         transform->Rotation = BitmapRotation::None;
00499
00500         unsigned int width = bitmapDecoder->PixelWidth;
00501         unsigned int height = bitmapDecoder->PixelHeight;
00502
00503         // Rotate the image to match the printing target orientation.
00504         if (landscape && width < height)
00505         {
00506             transform->Rotation = BitmapRotation::Clockwise270Degrees;
00507             Swap(width, height);
00508         }
00509         else if (!landscape && width > height)
00510         {
00511             transform->Rotation = BitmapRotation::Clockwise90Degrees;
00512             Swap(width, height);
00513         }
00514
00515         return concurrency::create_task(bitmapDecoder->GetPixelDataAsync(
00516             BitmapPixelFormat::Bgra8,    // WriteableBitmap uses BGRA format.
00517             BitmapAlphaMode::Straight,
00518             transform,
00519             ExifOrientationMode::IgnoreExifOrientation,    // This sample ignores Exif orientation.
00520             ColorManagementMode::DoNotColorManage)).then([width, height](PixelDataProvider^ pixelData) -> WriteableBitmap^
00521         {
00522             WriteableBitmap^ bitmap = ref new WriteableBitmap(static_cast<int>(width), static_cast<int>(height));
00523
00524             IBuffer^ bitmapBuffer = bitmap->PixelBuffer;
00525             Microsoft::WRL::ComPtr<IUnknown> spUnknown = reinterpret_cast<IUnknown*>(bitmapBuffer);
00526             Microsoft::WRL::ComPtr<IBufferByteAccess> spBufferAcces;
00527
00528             if (SUCCEEDED(spUnknown.As(&spBufferAcces)))
00529             {
00530                 byte *buffer;
00531                 if (SUCCEEDED(spBufferAcces->Buffer(&buffer)))
00532                 {
00533                     // Copy the pixels in the WriteableBitmap.
00534                     auto pixelDataBuffer = pixelData->DetachPixelData();
00535                     memcpy_s(buffer, bitmapBuffer->Length, pixelDataBuffer->begin(), pixelDataBuffer->Length);
00536                 }
00537             }
00538
00539             return bitmap;
00540         });
00541     });
00542 }
00543
00544 Scenario5Photos::Scenario5Photos()
00545 {
00546     InitializeComponent();
00547 }
00548
00549 void Scenario5Photos::OnPrintButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00550 {
00551     printHelper->ShowPrintUIAsync();
00552 }
00553
00554 void Scenario5Photos::OnNavigatedTo(NavigationEventArgs^ e)
00555 {
00556     if (PrintManager::IsSupported())
00557     {
00558         // Tell the user how to print
00559         MainPage::Current->NotifyUser("Print contract registered with customization, use the Print button to print.", NotifyType::StatusMessage);
00560     }
00561     else
00562     {
00563         // Remove the print button
00564         InvokePrintingButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00565
00566         // Inform user that Printing is not supported
00567         MainPage::Current->NotifyUser("Printing is not supported.", NotifyType::ErrorMessage);
00568
00569         // Printing-related event handlers will never be called if printing
00570         // is not supported, but it's okay to register for them anyway.
00571     }
00572
00573     // Initalize common helper class and register for printing
00574     printHelper = ref new PhotosPrintHelper(this);
00575     printHelper->RegisterForPrinting();
00576 }
00577
00578 void Scenario5Photos::OnNavigatedFrom(NavigationEventArgs^ e)
00579 {
00580     if (printHelper)
00581     {
00582         printHelper->UnregisterForPrinting();
00583     }
00584 }
Generated on Fri Nov 15 2024 22:21:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OnDemandHotspot/cppwinrt/BackgroundTask/Tasks.idl Source File

  • OnDemandHotspot
  • cppwinrt
  • BackgroundTask

Tasks.idl

Go to the documentation of this file.
00001 namespace BackgroundTask
00002 {
00003     [default_interface]
00004     runtimeclass UpdateMetadataTask : Windows.ApplicationModel.Background.IBackgroundTask
00005     {
00006         UpdateMetadataTask();
00007     }
00008
00009     [default_interface]
00010     runtimeclass ConnectTask : Windows.ApplicationModel.Background.IBackgroundTask
00011     {
00012         ConnectTask();
00013     }
00014 }
Generated on Fri Nov 15 2024 22:19:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampDevice/cs/Scenario3_AvailabilityChanged.xaml.cs Source File

  • LampDevice
  • cs

Scenario3_AvailabilityChanged.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace Lamp
00013 {
00014     using Windows.UI.Xaml;
00015     using Windows.UI.Xaml.Controls;
00016     using Windows.UI.Xaml.Navigation;
00017     using SDKTemplate;
00018     using System;
00019     using System.Globalization;
00020     using System.Threading.Tasks;
00021     using Windows.Devices.Lights;
00022
00023     /// <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026     public sealed partial class Scenario3_AvailabilityChanged : Page
00027     {
00028         /// <summary>
00029         /// Private MainPage object for status updates
00030         /// </summary>
00031         private MainPage rootPage;
00032
00033         /// <summary>
00034         /// Private lamp object for the page
00035         /// </summary>
00036         private Lamp lamp;
00037
00038         /// <summary>
00039         /// Initializes a new instance of the <see cref="Scenario3_AvailabilityChanged("/> class.
00040         /// </summary>
00041         public Scenario3_AvailabilityChanged()
00042         {
00043             this.InitializeComponent();
00044         }
00045
00046         /// <summary>
00047         /// Event handler for the OnNavigatedTo event. In this scenario, we want
00048         /// to get a lamp object for the lifetime of the page, so when we first
00049         /// navigate to the page, we Initialize a private lamp object
00050         /// </summary>
00051         /// <param name="e">Contains state information and event data associated with the event</param>
00052         protected async override void OnNavigatedTo(NavigationEventArgs e)
00053         {
00054             rootPage = MainPage.Current;
00055             await InitializeLampAsync();
00056             base.OnNavigatedTo(e);
00057         }
00058
00059         /// <summary>
00060         /// Initialize the lamp acquiring the default instance
00061         /// </summary>
00062         /// <returns>async Task</returns>
00063         private async Task InitializeLampAsync()
00064         {
00065             lamp = await Lamp.GetDefaultAsync();
00066
00067             if (lamp == null)
00068             {
00069                 await LogStatusAsync("Error: No lamp device was found", NotifyType.ErrorMessage);
00070                 lampToggle.IsEnabled = false;
00071                 return;
00072             }
00073
00074             await LogStatusAsync(string.Format(CultureInfo.InvariantCulture, "Default lamp instance acquired, Device Id: {0}", lamp.DeviceId), NotifyType.StatusMessage);
00075             lampToggle.IsEnabled = true;
00076         }
00077
00078         /// <summary>
00079         /// Event handler for the OnNavigatingFrom event. Here
00080         /// we want to make sure to release the lamp before exiting this scenario page.
00081         /// </summary>
00082         /// <param name="e">Contains state information and event data associated with the event</param>
00083         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00084         {
00085             DisposeLamp();
00086             base.OnNavigatingFrom(e);
00087         }
00088
00089         /// <summary>
00090         /// Method to dispose of current Lamp instance
00091         /// and release all resources
00092         /// </summary>
00093         private void DisposeLamp()
00094         {
00095             if (lamp == null)
00096             {
00097                 return;
00098             }
00099
00100             lampToggle.IsEnabled = false;
00101             lamp.AvailabilityChanged -= Lamp_AvailabilityChanged;
00102             lamp.IsEnabled = false;
00103             lamp.Dispose();
00104             lamp = null;
00105         }
00106
00107         /// <summary>
00108         /// Event Handler for the register button click event
00109         /// </summary>
00110         /// <param name="sender">Contains information regarding button that fired event</param>
00111         /// <param name="e">Contains state information and event data associated with the event</param>
00112         private async void RegisterBtn_Click(object sender, RoutedEventArgs e)
00113         {
00114             if (lamp == null)
00115             {
00116                 await LogStatusAsync("Error: No lamp device was found", NotifyType.ErrorMessage);
00117                 return;
00118             }
00119
00120             lamp.AvailabilityChanged += Lamp_AvailabilityChanged;
00121             await LogStatusAsync("Registered for Lamp Availability Changed Notification", NotifyType.StatusMessage);
00122         }
00123
00124         /// <summary>
00125         /// Event Handler for Lamp Availability Changed. When it fires, we want to update to
00126         /// Lamp toggle UI to show that lamp is available or not
00127         /// </summary>
00128         /// <param name="sender">Contains information regarding  Lamp object that fired event</param>
00129         /// <param name="e">Contains state information and event data associated with the event</param>
00130         private async void Lamp_AvailabilityChanged(Lamp sender, LampAvailabilityChangedEventArgs args)
00131         {
00132             // Update the Lamp Toggle UI to indicate lamp has been consumed by another application
00133             await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00134             {
00135                 if (lampToggle.IsOn)
00136                 {
00137                     lampToggle.IsOn = args.IsAvailable;
00138                 }
00139
00140                 lampToggle.IsEnabled = args.IsAvailable;
00141             });
00142
00143             await LogStatusAsync(string.Format(CultureInfo.InvariantCulture,"Lamp Availability Changed Notification has fired, IsAvailable= {0}", args.IsAvailable), NotifyType.StatusMessage);
00144         }
00145
00146         /// <summary>
00147         /// Event handler for the Unregister Availability Event
00148         /// </summary>
00149         /// <param name="sender">Contains information regarding button that fired event</param>
00150         /// <param name="e">Contains state information and event data associated with the event</param>
00151         private async void UnRegisterBtn_Click(object sender, RoutedEventArgs e)
00152         {
00153             if (lamp == null)
00154             {
00155                 await LogStatusAsync("Error: No lamp device was found", NotifyType.ErrorMessage);
00156                 return;
00157             }
00158
00159             lamp.AvailabilityChanged -= Lamp_AvailabilityChanged;
00160             await LogStatusAsync("Unregistered for Lamp Availability Changed Notification", NotifyType.StatusMessage);
00161         }
00162
00163         /// <summary>
00164         /// Event handler for Lamp Toggle Switch
00165         /// Toggling the switch will turn Lamp on or off
00166         /// </summary>
00167         /// <param name="sender">Contains information regarding toggle switch that fired event</param>
00168         /// <param name="e">Contains state information and event data associated with the event</param>
00169         private async void lampToggle_Toggled(object sender, RoutedEventArgs e)
00170         {
00171             if (lamp == null)
00172             {
00173                 await LogStatusAsync("Error: No lamp device was found", NotifyType.ErrorMessage);
00174                 return;
00175             }
00176
00177             ToggleSwitch toggleSwitch = sender as ToggleSwitch;
00178             if (toggleSwitch != null)
00179             {
00180                 if (toggleSwitch.IsOn)
00181                 {
00182                     lamp.IsEnabled = true;
00183                     await LogStatusAsync("Lamp is Enabled", NotifyType.StatusMessage);
00184                 }
00185                 else
00186                 {
00187                     lamp.IsEnabled = false;
00188                     await LogStatusAsync("Lamp is Disabled", NotifyType.StatusMessage);
00189                 }
00190             }
00191         }
00192
00193         /// <summary>
00194         /// Marshall log message to the UI thread
00195         /// and update outputBox, this method is for more general messages
00196         /// </summary>
00197         /// <param name="message">Message to log</param>
00198         private async Task LogStatusToOutputBoxAsync(string message)
00199         {
00200             await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00201             {
00202                 outputBox.Text += message + "\r\n";
00203                 outputScrollViewer.ChangeView(0, outputBox.ActualHeight, 1);
00204             });
00205         }
00206
00207         /// <summary>
00208         /// Method to log Status to Main Status block,
00209         /// this method is for important status messages
00210         /// </summary>
00211         /// <param name="message">Message to log</param>
00212         /// <param name="type">Status notification type</param>
00213         private async Task LogStatusAsync(string message, NotifyType type)
00214         {
00215             await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00216             {
00217                 rootPage.NotifyUser(message, type);
00218             });
00219             await LogStatusToOutputBoxAsync(message);
00220         }
00221     }
00222 }
Generated on Fri Nov 15 2024 22:20:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SuspensionManagerException Member List

This is the complete list of members for SuspensionManagerException, including all inherited members.
SuspensionManagerException() | SuspensionManagerException | [inline]
SuspensionManagerException(Exception e) | SuspensionManagerException | [inline]
SuspensionManagerException() | SuspensionManagerException | [inline]
SuspensionManagerException(Exception e) | SuspensionManagerException | [inline]
Generated on Fri Nov 15 2024 22:24:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DashManifestParser Member List

This is the complete list of members for DashManifestParser, including all inherited members.
CalculateNumberIdentifierForLive(ulong hnsFragmentDuration, ref ulong segmentNumber) | DashManifestParser | [inline, private]
DashManifestParser(Windows.Data.Xml.Dom.XmlDocument document, ref Manifest manifest) | DashManifestParser | [inline]
DeterminePeriodStart(ulong presentationTimeOffset, IXmlNode periodNode, ref Period period) | DashManifestParser | [inline, private]
document | DashManifestParser | [private]
ExpandDASHUrlSegmentTemplate(string format, string baseUrl, uint bitrate, string repID, ulong number, ulong time, out string result) | DashManifestParser | [inline, private, static]
GetLowestBitrateRepresentation(IEnumerable< IXmlNode > representations) | DashManifestParser | [inline, private]
GetWallClockTime() | DashManifestParser | [inline, private]
hasPeriodStartAttribute | DashManifestParser | [private]
HttpPrefix | DashManifestParser | [private]
HttpsPrefix | DashManifestParser | [private]
LiveProfile | DashManifestParser |
LiveSegmentCount | DashManifestParser |
MakeNumberBaseSegmentInfo(uint bitrate, UInt64 timescale, UInt64 segmentDuration, string repID, uint startNumber, string mediaFormat, ref MediaStream stream) | DashManifestParser | [inline, private]
MakeTimelineInfo(IXmlNode segmentTimeline, uint bitrate, ulong timescale, string repID, uint startNumber, ulong presentationTimeOffset, string mediaFormat, ref MediaStream stream) | DashManifestParser | [inline, private]
manifest | DashManifestParser | [private]
Parse() | DashManifestParser | [inline]
ParseMPDElement() | DashManifestParser | [inline, private]
ParsePeriodElement(IXmlNode periodElement, ref Period period) | DashManifestParser | [inline, private]
ParseRepresentationElement(IXmlNode representaion, out uint bitrate, out string repID) | DashManifestParser | [inline, private]
ParseSegmentTemplateElement(IXmlNode segmentTemplate, ref UInt64 timescale, ref string initializationFormat, ref string mediaFormat, ref UInt64 duration, ref uint startNumber, ref UInt64 presentationTimeOffset) | DashManifestParser | [inline, private]
periodStart | DashManifestParser | [private]
ResolvePadding(string template, string idMatch, ulong value) | DashManifestParser | [inline, private, static]
UpdateBaseUrl() | DashManifestParser | [inline, private]
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cppwinrt/pch.cpp Source File

  • IoT-GPIO
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/Content/ControlBase.h Source File

  • HolographicMixedRealityCapture
  • cpp
  • Content

ControlBase.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "IControl.h"
00004 #include "ShaderStructures.h"
00005 #include <vector>
00006 #include <ppltasks.h>
00007
00008 using namespace Windows::Graphics::Holographic;
00009 using namespace Windows::Perception::Spatial;
00010 using namespace Windows::UI::Input::Spatial;
00011
00012 namespace HolographicMRCSample
00013 {
00014     // This sample renderer instantiates a basic rendering pipeline.
00015     class ControlBase : public IControl
00016     {
00017     public:
00018         ControlBase();
00019         virtual ~ControlBase();
00020
00021         // IObject
00022         virtual void Initialize(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00023         virtual void CreateDeviceDependentResources();
00024         virtual void ReleaseDeviceDependentResources();
00025         virtual void Update(
00026             const DX::StepTimer& timer,
00027             HolographicFrame^ holographicFrame,
00028             SpatialCoordinateSystem^ currentCoordinateSystem,
00029             SpatialInteractionSourceState^ interactionSource);
00030         virtual void Update(
00031             const DX::StepTimer& timer,
00032             HolographicFrame^ holographicFrame,
00033             SpatialCoordinateSystem^ currentCoordinateSystem,
00034             SpatialInteractionSourceState^ interactionSource,
00035             const DirectX::XMMATRIX &parentTransform);
00036         virtual void Render();
00037
00038         virtual void AddChild(const std::shared_ptr<IControl>& object) { m_children.push_back(object); }
00039
00040         virtual void SetPosition(Windows::Foundation::Numerics::float3 pos) { m_position = pos; }
00041         virtual void SetRotation(Windows::Foundation::Numerics::float3 rot) { m_rotation = rot; }
00042         virtual void SetScale(Windows::Foundation::Numerics::float3 scale)  { m_scale = scale; }
00043
00044         virtual Windows::Foundation::Numerics::float3 GetPosition() { return m_position; }
00045         virtual Windows::Foundation::Numerics::float3 GetRotation() { return m_rotation; }
00046         virtual Windows::Foundation::Numerics::float3 GetScale()    { return m_scale; }
00047
00048         virtual ControlType Type() { return m_type; }
00049         virtual bool IsFocused()   { return m_focused; }
00050         virtual bool IsEnabled()   { return m_enabled; }
00051
00052         virtual void SetEnabled(const bool enabled) { m_enabled = enabled; }
00053
00054         virtual void GetBoundingBox(DirectX::BoundingOrientedBox &boundingBox)
00055         {
00056             m_boundingBox.Transform(boundingBox, DirectX::XMLoadFloat4x4(&m_transform));
00057         }
00058
00059         virtual void SetOnAirTapCallback(std::function<void()> callback)
00060         {
00061             m_onAirTapCallback = callback;
00062         }
00063
00064     protected:
00065         virtual void DoCreateDeviceDependentResources()  = 0;
00066         virtual void DoReleaseDeviceDependentResources() = 0;
00067
00068         virtual void DoUpdate(
00069             const DX::StepTimer& timer,
00070             HolographicFrame^ holographicFrame,
00071             SpatialCoordinateSystem^ currentCoordinateSystem,
00072             SpatialInteractionSourceState^ interactionSource,
00073             const DirectX::XMMATRIX &parentTransform) = 0;
00074         virtual void DoRender() = 0;
00075
00076     protected:
00077         // Cached pointer to device resources.
00078         std::shared_ptr<DX::DeviceResources>    m_deviceResources;
00079
00080         Windows::Foundation::Numerics::float3   m_position = { 0.0f, 0.0f, 0.0f };
00081         Windows::Foundation::Numerics::float3   m_rotation = { 0.0f, 0.0f, 0.0f };
00082         Windows::Foundation::Numerics::float3   m_scale    = { 1.0f, 1.0f, 1.0f };
00083
00084         ControlType                             m_type = Control_Unknown;
00085         bool                                    m_enabled = true;
00086         bool                                    m_focused = false;
00087
00088         std::function<void()>                   m_onAirTapCallback;
00089
00090         DirectX::XMFLOAT4X4                     m_transform;
00091
00092         std::vector<std::shared_ptr<IControl>>  m_children;
00093
00094         DirectX::BoundingOrientedBox            m_boundingBox;
00095     };
00096 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Sphere.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Sphere.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Sphere:
00015 // This class is a specialization of GameObject that represents a sphere primitive.
00016 // The sphere is defined by a 'position' and radius.
00017
00018 #include "GameObject.h"
00019
00020 class Sphere : public GameObject
00021 {
00022 public:
00023     Sphere();
00024     Sphere(DirectX::XMFLOAT3 pos, float radius);
00025
00026     using GameObject::Position;
00027     void Position(DirectX::XMFLOAT3 position);
00028     void Position(DirectX::XMVECTOR position);
00029     void Radius(float radius);
00030     float Radius();
00031
00032     virtual bool IsTouching(
00033         DirectX::XMFLOAT3 point,
00034         float radius,
00035         _Out_ DirectX::XMFLOAT3* contact,
00036         _Out_ DirectX::XMFLOAT3* normal
00037         ) override;
00038
00039 private:
00040     float m_radius;
00041     void Update();
00042 };
00043
00044 __forceinline void Sphere::Position(DirectX::XMFLOAT3 position)
00045 {
00046     m_position = position;
00047     Update();
00048 }
00049
00050 __forceinline void Sphere::Position(DirectX::XMVECTOR position)
00051 {
00052     DirectX::XMStoreFloat3(&m_position, position);
00053     Update();
00054 }
00055
00056 __forceinline void Sphere::Radius(float radius)
00057 {
00058     m_radius = radius;
00059     Update();
00060 }
00061
00062 __forceinline float Sphere::Radius()
00063 {
00064     return m_radius;
00065 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6 Member List

This is the complete list of members for Scenario6, including all inherited members.
Scenario6() Scenario6 [inline]
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaImport/cs/SampleConfiguration.cs Source File

  • MediaImport
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using ImportSample;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "ImportSample";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Scenario 1", ClassType=typeof(Scenario1)},
00026         };
00027     }
00028
00029     public class Scenario
00030     {
00031         public string Title { get; set; }
00032         public Type ClassType { get; set; }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/StspMediaSource.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

StspMediaSource.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009 #include <CritSec.h>
00010 #include <OpQueue.h>
00011 #include <linklist.h>
00012 #include <BaseAttributes.h>
00013 #include <StspNetwork.h>
00014 #include <StspDefs.h>
00015
00016 namespace Microsoft { namespace Samples { namespace SimpleCommunication {
00017
00018 class CMediaStream;
00019
00020 // Base class representing asyncronous source operation
00021 class CSourceOperation : public IUnknown
00022 {
00023 public:
00024     enum Type
00025     {
00026         // Start the source
00027         Operation_Start,
00028         // Stop the source
00029         Operation_Stop,
00030         // Set rate
00031         Operation_SetRate,
00032     };
00033
00034 public:
00035     CSourceOperation(Type opType);
00036     virtual ~CSourceOperation();
00037     // IUnknown
00038     IFACEMETHOD (QueryInterface) (REFIID riid, void **ppv);
00039     IFACEMETHOD_(ULONG, AddRef) ();
00040     IFACEMETHOD_(ULONG, Release) ();
00041
00042     Type GetOperationType() const {return _opType;}
00043     const PROPVARIANT &GetData() const { return _data;}
00044     HRESULT SetData(const PROPVARIANT &varData);
00045
00046 private:
00047     long                        _cRef;                      // reference count
00048     Type                        _opType;
00049     PROPVARIANT                 _data;
00050 };
00051
00052 // Start operation
00053 class CStartOperation : public CSourceOperation
00054 {
00055 public:
00056     CStartOperation(IMFPresentationDescriptor *pPD);
00057     ~CStartOperation();
00058
00059     IMFPresentationDescriptor *GetPresentationDescriptor() {return _spPD.Get();}
00060
00061 private:
00062     ComPtr<IMFPresentationDescriptor> _spPD;   // Presentation descriptor
00063 };
00064
00065 // SetRate operation
00066 class CSetRateOperation : public CSourceOperation
00067 {
00068 public:
00069     CSetRateOperation(BOOL fThin, float flRate);
00070     ~CSetRateOperation();
00071
00072     BOOL IsThin() const {return _fThin;}
00073     float GetRate() const {return _flRate;}
00074
00075 private:
00076     BOOL _fThin;
00077     float _flRate;
00078 };
00079
00080 class CMediaSource :
00081     public OpQueue<CMediaSource, CSourceOperation>,
00082     public IMFMediaSource,
00083     public IMFGetService,
00084     public IMFRateControl,
00085     public Microsoft::Samples::Common::CBaseAttributes<>
00086 {
00087 public:
00088     static HRESULT CreateInstance(CMediaSource **ppNetSource);
00089
00090     // IUnknown
00091     IFACEMETHOD (QueryInterface) (REFIID riid, void **ppv);
00092     IFACEMETHOD_(ULONG, AddRef) ();
00093     IFACEMETHOD_(ULONG, Release) ();
00094
00095     // IMFMediaEventGenerator
00096     IFACEMETHOD (BeginGetEvent) (IMFAsyncCallback *pCallback,IUnknown *punkState);
00097     IFACEMETHOD (EndGetEvent) (IMFAsyncResult *pResult, IMFMediaEvent **ppEvent);
00098     IFACEMETHOD (GetEvent) (DWORD dwFlags, IMFMediaEvent **ppEvent);
00099     IFACEMETHOD (QueueEvent) (MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT *pvValue);
00100
00101     // IMFMediaSource
00102     IFACEMETHOD (CreatePresentationDescriptor) (IMFPresentationDescriptor **ppPresentationDescriptor);
00103     IFACEMETHOD (GetCharacteristics) (DWORD *pdwCharacteristics);
00104     IFACEMETHOD (Pause) ();
00105     IFACEMETHOD (Shutdown) ();
00106     IFACEMETHOD (Start) (
00107         IMFPresentationDescriptor *pPresentationDescriptor,
00108         const GUID *pguidTimeFormat,
00109         const PROPVARIANT *pvarStartPosition
00110     );
00111     IFACEMETHOD (Stop)();
00112
00113     // IMFGetService
00114     IFACEMETHOD (GetService) ( _In_ REFGUID guidService, _In_ REFIID riid, _Out_opt_ LPVOID *ppvObject);
00115
00116     // IMFRateControl
00117     IFACEMETHOD (SetRate) (BOOL fThin, float flRate);
00118     IFACEMETHOD (GetRate) (_Inout_opt_ BOOL *pfThin, _Inout_opt_ float *pflRate);
00119
00120     // OpQueue
00121     __override HRESULT DispatchOperation(_In_ CSourceOperation *pOp);
00122     __override HRESULT ValidateOperation(_In_ CSourceOperation *pOp);
00123
00124     // Called by the byte stream handler.
00125     concurrency::task<void> OpenAsync(LPCWSTR pszUrl);
00126
00127     // Other public methods
00128     _Acquires_lock_(_critSec)
00129     HRESULT Lock();
00130     _Releases_lock_(_critSec)
00131     HRESULT Unlock();
00132
00133 protected:
00134     CMediaSource(void);
00135     ~CMediaSource(void);
00136
00137 private:
00138     typedef ComPtrList<IMFMediaStream> StreamContainer;
00139
00140 private:
00141     void Initialize();
00142
00143     void HandleError(HRESULT hResult);
00144     HRESULT GetStreamById(DWORD dwId, CMediaStream **ppStream);
00145     void ParseServerUrl(LPCWSTR pszUrl);
00146     void CompleteOpen(HRESULT hResult);
00147     concurrency::task<void> SendRequestAsync(StspOperation eOperation);
00148     void SendDescribeRequest();
00149     void SendStartRequest();
00150     void Receive();
00151     void ParseCurrentBuffer();
00152     void ProcessPacket(StspOperationHeader *pOpHeader, Network::IBufferPacket *pPacket);
00153     void ProcessServerDescription(Network::IBufferPacket *pPacket);
00154     void ProcessServerSample(Network::IBufferPacket *pPacket);
00155     void ProcessServerFormatChange(Network::IBufferPacket *pPacket);
00156     HRESULT AddStream(StspStreamDescription *pStreamDesc);
00157     void InitPresentationDescription();
00158     HRESULT ValidatePresentationDescriptor(IMFPresentationDescriptor *pPD);
00159     void SelectStreams(IMFPresentationDescriptor *pPD);
00160
00161     void DoStart(CStartOperation *pOp);
00162     void DoStop(CSourceOperation *pOp);
00163     void DoSetRate(CSetRateOperation *pOp);
00164
00165     bool IsRateSupported(float flRate, float *pflAdjustedRate);
00166
00167     HRESULT CheckShutdown() const
00168     {
00169         if (_eSourceState == SourceState_Shutdown)
00170         {
00171             return MF_E_SHUTDOWN;
00172         }
00173         else
00174         {
00175             return S_OK;
00176         }
00177     }
00178
00179 private:
00180     long                        _cRef;                      // reference count
00181     CritSec                     _critSec;                   // critical section for thread safety
00182     SourceState                 _eSourceState;              // Flag to indicate if Shutdown() method was called.
00183     ComPtr<IMFMediaEventQueue>  _spEventQueue;              // Event queue
00184     Network::INetworkChannel^   _networkSender;             // Network sender
00185     String^                     _serverAddress;             // Address of a server
00186     WORD                        _serverPort;                // Port of a server
00187
00188     ComPtr<Network::IBufferPacket> _spCurrentReceivePacket;    // Receive packet
00189     ComPtr<Network::IMediaBufferWrapper> _spCurrentReceiveBuffer;    // Current buffer
00190     StspOperationHeader         _CurrentReceivedOperationHeader; // Header of the operation currently being received from the server.
00191
00192     ComPtr<IMFPresentationDescriptor> _spPresentationDescriptor;
00193
00194     StreamContainer             _streams;                   // Collection of streams associated with the source
00195
00196     concurrency::task_completion_event<void> _openedEvent;
00197
00198     float                       _flRate;
00199 };
00200
00201 }}} // namespace Microsoft::Samples::SimpleCommunication
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationData/cs/Scenario2_Settings.xaml.cs Source File

  • ApplicationData
  • cs

Scenario2_Settings.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using System;
00015 using Windows.Storage;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario2_Settings : Page
00020     {
00021         ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
00022
00023         const string SettingName = "exampleSetting";
00024
00025         public Scenario2_Settings()
00026         {
00027             InitializeComponent();
00028         }
00029
00030         // Guidance for Settings.
00031         //
00032         // Settings are a convenient way of storing small pieces of configuration data
00033         // for your application.
00034         //
00035         // There are two storage containers for settings: Local and Roaming. However,
00036         // Roaming settings no longer roam, so they are functionally equivalent to Local.
00037         //
00038         // Care should be taken to guard against an excessive volume of data being
00039         // stored in settings.  Settings are not intended to be used as a database.
00040         // Large data sets will take longer to load from disk during your application's
00041         // launch.
00042
00043         // This sample illustrates reading and writing from a local setting.
00044
00045         void WriteSetting_Click(Object sender, RoutedEventArgs e)
00046         {
00047             localSettings.Values[SettingName] = "Hello World"; // example value
00048
00049             DisplayOutput();
00050         }
00051
00052         void DeleteSetting_Click(Object sender, RoutedEventArgs e)
00053         {
00054             localSettings.Values.Remove(SettingName);
00055
00056             DisplayOutput();
00057         }
00058
00059         void DisplayOutput()
00060         {
00061             Object value = localSettings.Values[SettingName];
00062
00063             OutputTextBlock.Text = String.Format("Setting: {0}", (value == null ? "<empty>" : ("\"" + value + "\"")));
00064         }
00065
00066         protected override void OnNavigatedTo(NavigationEventArgs e)
00067         {
00068             DisplayOutput();
00069         }
00070     }
00071 }
Generated on Fri Nov 15 2024 22:17:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FocusableElement Member List

This is the complete list of members for FocusableElement, including all inherited members.
AddChildElement(const std::shared_ptr< BaseElement > &childElement) | BaseElement |
ArrangeElements() | BaseElement | [virtual]
BaseElement() | BaseElement |
FocusableElement() | FocusableElement |
FocusUpdate() | FocusableElement | [inline, virtual]
GetElementMargin() | BaseElement | [inline]
GetElementSize() | BaseElement | [inline]
GetIgnoreLayout() | BaseElement | [inline]
GetIsRenderPassNeeded() | BaseElement | [inline]
GetIsVisible() | BaseElement | [inline]
Initialize() | BaseElement | [virtual]
IsFocused() | FocusableElement | [inline, virtual]
m_deviceResources | BaseElement | [protected]
m_elementCoordIntersectionPoint | FocusableElement | [protected]
m_elementMargin | BaseElement | [protected]
m_elementSize | BaseElement | [protected]
m_ignoreLayout | BaseElement | [protected]
m_isFocused | FocusableElement | [protected]
m_isFocusIntersectionCalculated | FocusableElement | [protected]
m_isInitialized | BaseElement | [protected]
m_isLayoutHorizontal | BaseElement | [protected]
m_isParentFocused | FocusableElement | [protected]
m_isRenderPassNeeded | BaseElement | [protected]
m_isVisible | BaseElement | [protected]
m_parentFocusedPosition | FocusableElement | [protected]
m_parentTextureHeight | FocusableElement | [protected]
m_parentTextureWidth | FocusableElement | [protected]
m_parentTranslation | BaseElement | [protected]
m_transformedTranslation | BaseElement | [protected]
m_transformMatrix | BaseElement | [protected]
m_transformRecalculationNeeded | BaseElement | [protected]
m_translation | BaseElement | [protected]
PerformAction() | FocusableElement | [inline, virtual]
Render() | BaseElement | [protected, virtual]
SetBrush(ID2D1SolidColorBrush *brush) | BaseElement |
SetElementMargin(ElementMargin margin) | BaseElement | [inline]
SetElementSize(Windows::Foundation::Numerics::float2 size) | BaseElement | [inline]
SetIgnoreLayout(bool ignoreLayout) | BaseElement | [inline]
SetIsVisible(bool visible) | BaseElement |
SetLayoutHorizontal(bool isLayoutHorizontal) | BaseElement | [inline]
SetParentControlInformation(bool focused, Windows::Foundation::Numerics::float2 focusedPosition, UINT parentTextureWidth, UINT parentTextureHeight) | FocusableElement | [virtual]
SetParentTransform(Windows::Foundation::Numerics::float2 translation) | BaseElement |
SetTranslation(Windows::Foundation::Numerics::float2 translation) | BaseElement | [virtual]
TryRender() | BaseElement |
Update(const DX::StepTimer &timer, Windows::UI::Input::Spatial::SpatialPointerPose^cameraPose) override | FocusableElement | [virtual]
~BaseElement() | BaseElement | [virtual]
~FocusableElement() | FocusableElement | [virtual]
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactPicker/cpp/pch.cpp Source File

  • ContactPicker
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

INavigationService Member List

This is the complete list of members for INavigationService, including all inherited members.
GoBack() | INavigationService
Navigate(Type source, object parameter=null) | INavigationService
Navigate< T >(object parameter=null) | INavigationService
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SemanticTextQuery/cpp/pch.cpp Source File

  • SemanticTextQuery
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileSearch/cppwinrt/pch.h Source File

  • FileSearch
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Storage.h"
00008 #include "winrt/Windows.Storage.Search.h"
00009 #include "winrt/Windows.System.h"
00010 #include "winrt/Windows.UI.Core.h"
00011 #include "winrt/Windows.UI.Xaml.h"
00012 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.h"
00014 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00015 #include "winrt/Windows.UI.Xaml.Documents.h"
00016 #include "winrt/Windows.UI.Xaml.Interop.h"
00017 #include "winrt/Windows.UI.Xaml.Markup.h"
00018 #include "winrt/Windows.UI.Xaml.Media.h"
00019 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cppwinrt/SampleConfiguration.cpp Source File

  • JumpList
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::ApplicationModel::Activation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace SDKTemplate;
00021
00022 hstring implementation::MainPage::FEATURE_NAME()
00023 {
00024     return L"Jump List C++/WinRT Sample";
00025 }
00026
00027 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00028     {
00029         Scenario{ L"Respond to being launched", xaml_typename<SDKTemplate::Scenario1_Launched>() },
00030         Scenario{ L"Remove the jump list", xaml_typename<SDKTemplate::Scenario2_Remove>() },
00031         Scenario{ L"Creating custom items", xaml_typename<SDKTemplate::Scenario3_CustomItems>() },
00032         Scenario{ L"Change the system group", xaml_typename<SDKTemplate::Scenario4_ChangeSystemGroup>() },
00033         Scenario{ L"Check if the platform is supported", xaml_typename<SDKTemplate::Scenario5_IsSupported>() },
00034     });
00035
00036 void winrt::SDKTemplate::App_LaunchCompleted(LaunchActivatedEventArgs const& e)
00037 {
00038     hstring arguments = e.Arguments();
00039     if (!arguments.empty())
00040     {
00041         implementation::MainPage::Current().Navigate(xaml_typename<Scenario1_Launched>(), box_value(L"arguments: " + arguments));
00042     }
00043 }
00044
00045 void winrt::SDKTemplate::App_OnFileActivated(FileActivatedEventArgs const& e)
00046 {
00047     if (e.Files().Size() == 1)
00048     {
00049         implementation::MainPage::Current().Navigate(xaml_typename<Scenario1_Launched>(), box_value(L"file: " + e.Files().GetAt(0).Name()));
00050     }
00051 }
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomHidDeviceAccess/cpp/Scenario2_FeatureReports.xaml.h Source File

  • CustomHidDeviceAccess
  • cpp

Scenario2_FeatureReports.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 //
00008 // Scenario2.xaml.h
00009 // Declaration of the Scenario2 class
00010 //
00011
00012 #pragma once
00013 #include "Scenario2_FeatureReports.g.h"
00014
00015 namespace SDKTemplate
00016 {
00017     /// <summary>
00018     /// This page demonstrates how to use FeatureReports to communicate with the device
00019     /// </summary>
00020     [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class FeatureReports sealed
00022     {
00023     public:
00024         FeatureReports();
00025     protected:
00026         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00027     private:
00028         void GetLedBlinkPattern_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029         void SetLedBlinkPattern_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00030
00031         Concurrency::task<void> SetLedBlinkPatternAsync(uint8 pattern);
00032         Concurrency::task<void> GetLedBlinkPatternAsync(void);
00033     };
00034 }
Generated on Fri Nov 15 2024 22:19:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_DisplayRegion Member List

This is the complete list of members for Scenario2_DisplayRegion, including all inherited members.
Button_Click(IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_DisplayRegion |
GetOtherDisplayRegion(Windows::UI::WindowManagement::DisplayRegion currentAppDisplayRegion) | Scenario2_DisplayRegion | [private]
NumberOfAvailableDisplayRegions() | Scenario2_DisplayRegion | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario2_DisplayRegion |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario2_DisplayRegion |
OnWindowClosed(Windows::UI::WindowManagement::AppWindow const &sender, IInspectable const &) | Scenario2_DisplayRegion | [private]
Scenario2_DisplayRegion() | Scenario2_DisplayRegion |
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cs/HistoryAndRoaming.xaml.cs Source File

  • Clipboard
  • cs

HistoryAndRoaming.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.DataTransfer;
00014 using Windows.Graphics.Imaging;
00015 using Windows.Storage.Streams;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Media.Imaging;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class HistoryAndRoaming : Page
00024     {
00025         MainPage rootPage = MainPage.Current;
00026
00027         public HistoryAndRoaming()
00028         {
00029             InitializeComponent();
00030         }
00031
00032         protected override void OnNavigatedTo(NavigationEventArgs e)
00033         {
00034             Clipboard.HistoryEnabledChanged += OnHistoryEnabledChanged;
00035             Clipboard.RoamingEnabledChanged += OnRoamingEnabledChanged;
00036             CheckHistoryAndRoaming();
00037         }
00038
00039         protected override void OnNavigatedFrom(NavigationEventArgs e)
00040         {
00041             Clipboard.HistoryEnabledChanged -= OnHistoryEnabledChanged;
00042             Clipboard.RoamingEnabledChanged -= OnRoamingEnabledChanged;
00043         }
00044
00045         async void CopyButton_Click(object sender, RoutedEventArgs e)
00046         {
00047             // Generate a bitmap for our clipboard content.
00048             RenderTargetBitmap target = new RenderTargetBitmap();
00049             await target.RenderAsync(ClipboardContent);
00050             IBuffer buffer = await target.GetPixelsAsync();
00051             SoftwareBitmap bitmap = SoftwareBitmap.CreateCopyFromBuffer(buffer, BitmapPixelFormat.Bgra8, target.PixelWidth, target.PixelHeight, BitmapAlphaMode.Premultiplied);
00052
00053             // Save the bitmap to a stream.
00054             InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
00055             BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
00056             encoder.SetSoftwareBitmap(bitmap);
00057             await encoder.FlushAsync();
00058             stream.Seek(0);
00059
00060             // Create a DataPackage to hold the bitmap and text.
00061             var dataPackage = new DataPackage();
00062             dataPackage.SetBitmap(RandomAccessStreamReference.CreateFromStream(stream));
00063             dataPackage.SetText(ClipboardContent.Text);
00064
00065             ClipboardContentOptions options = new ClipboardContentOptions();
00066
00067             // Customize clipboard history.
00068             if (IncludeAllInHistory.IsChecked.Value)
00069             {
00070                 // This is the default, but set it explicitly for expository purposes.
00071                 options.IsAllowedInHistory = true;
00072             }
00073             else if (IncludeTextInHistory.IsChecked.Value)
00074             {
00075                 // This is the default, but set it explicitly for expository purposes.
00076                 options.IsAllowedInHistory = true;
00077                 // Allow only text to go into the history.
00078                 options.HistoryFormats.Add(StandardDataFormats.Text);
00079             }
00080             else
00081             {
00082                 // Exclude from history.
00083                 options.IsAllowedInHistory = false;
00084             }
00085
00086             // Customize clipboard roaming.
00087             if (AllowAllToRoam.IsChecked.Value)
00088             {
00089                 // This is the default, but set it explicitly for expository purposes.
00090                 options.IsRoamable = true;
00091             }
00092             else if (AllowTextToRoam.IsChecked.Value)
00093             {
00094                 // This is the default, but set it explicitly for expository purposes.
00095                 options.IsRoamable = true;
00096                 // Allow only text to roam.
00097                 options.RoamingFormats.Add(StandardDataFormats.Text);
00098             }
00099             else
00100             {
00101                 // Exclude from roaming.
00102                 options.IsRoamable = false;
00103             }
00104
00105             // Set the data package to the clipboard with our custom options.
00106             if (Clipboard.SetContentWithOptions(dataPackage, options))
00107             {
00108                 rootPage.NotifyUser("Text and bitmap have been copied to clipboard.", NotifyType.StatusMessage);
00109             }
00110             else
00111             {
00112                 // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
00113                 rootPage.NotifyUser("Error copying content to clipboard.", NotifyType.ErrorMessage);
00114             }
00115         }
00116
00117         void OnHistoryEnabledChanged(object sender, object e)
00118         {
00119             CheckHistoryAndRoaming();
00120         }
00121
00122         void OnRoamingEnabledChanged(object sender, object e)
00123         {
00124             CheckHistoryAndRoaming();
00125         }
00126
00127         static void SelectVisibleElement(UIElement ifTrue, UIElement ifFalse, bool value)
00128         {
00129             ifTrue.Visibility = value ? Visibility.Visible : Visibility.Collapsed;
00130             ifFalse.Visibility = !value ? Visibility.Visible : Visibility.Collapsed;
00131         }
00132
00133         async void CheckHistoryAndRoaming()
00134         {
00135             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00136             {
00137                 SelectVisibleElement(ClipboardHistoryBlock, ClipboardHistoryUnavailableBlock, Clipboard.IsHistoryEnabled());
00138                 SelectVisibleElement(ClipboardRoamingBlock, ClipboardRoamingUnavailableBlock, Clipboard.IsRoamingEnabled());
00139             });
00140         }
00141     }
00142 }
Generated on Fri Nov 15 2024 22:18:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisablingScreenCapture/cs/Scenario1_Enable.xaml.cs Source File

  • DisablingScreenCapture
  • cs

Scenario1_Enable.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013
00014 namespace SDKTemplate
00015 {
00016     public sealed partial class Scenario1_Enable : Page
00017     {
00018         public Scenario1_Enable()
00019         {
00020             this.InitializeComponent();
00021         }
00022     }
00023 }
Generated on Fri Nov 15 2024 22:19:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiScan/cpp/Scenario2_Scan.xaml.h Source File

  • WiFiScan
  • cpp

Scenario2_Scan.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Scan.g.h"
00015 #include "MainPage.xaml.h"
00016 #include "DisplayHelpers.h"
00017
00018 namespace SDKTemplate
00019 {
00020     namespace WiFiScan
00021     {
00022         /// <summary>
00023         /// An empty page that can be used on its own or navigated to within a Frame.
00024         /// </summary>
00025         [Windows::Foundation::Metadata::WebHostHidden]
00026         [Windows::UI::Xaml::Data::Bindable]
00027         public ref class Scenario2_Scan sealed
00028         {
00029         public:
00030             Scenario2_Scan();
00031             property Windows::Foundation::Collections::IObservableVector<WiFiNetworkDisplay^>^ ResultCollection;
00032
00033         protected:
00034             void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035
00036         private:
00037             void Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038             void DisplayNetworkReport(Windows::Devices::WiFi::WiFiNetworkReport^ report);
00039
00040             MainPage^ _rootPage;
00041             Windows::Devices::WiFi::WiFiAdapter^ _firstAdapter;
00042         };
00043     }
00044 }
Generated on Fri Nov 15 2024 22:22:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_SaveFile Member List

This is the complete list of members for Scenario4_SaveFile, including all inherited members.
SaveFileButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario4_SaveFile
Scenario4_SaveFile() | Scenario4_SaveFile
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBottomUpList/cpp/pch.cpp Source File

  • XamlBottomUpList
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLInProcessWinRTComponent/cpp/cpp/Scenario4_CustomExceptionWRL.xaml.cpp Source File

  • WRLInProcessWinRTComponent
  • cpp
  • cpp

Scenario4_CustomExceptionWRL.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include "pch.h"
00008 #include "Scenario4_CustomExceptionWRL.xaml.h"
00009 #include "MainPage.xaml.h"
00010 #include "..\Server\Microsoft.SDKSamples.Kitchen.h"
00011
00012 using namespace Microsoft::WRL;
00013 using namespace Microsoft::WRL::Wrappers;
00014 using namespace Microsoft::SDKSamples::Kitchen;
00015 using namespace Windows::Foundation;
00016 using namespace Windows::UI::Xaml;
00017 using namespace Windows::UI::Xaml::Controls;
00018 using namespace SDKTemplate::WRLInProcessWinRTComponent;
00019
00020 CustomExceptionWRL::CustomExceptionWRL()
00021 {
00022     InitializeComponent();
00023 }
00024
00025 void CustomExceptionWRL::Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00026 {
00027     ComPtr<ABI::Microsoft::SDKSamples::Kitchen::IOven> myOven;
00028     HRESULT hr = Windows::Foundation::ActivateInstance(HStringReference(
00029         RuntimeClass_Microsoft_SDKSamples_Kitchen_Oven).Get(), &myOven);
00030     if (SUCCEEDED(hr))
00031     {
00032         // Intentionally pass an invalid value
00033         hr = myOven->ConfigurePreheatTemperature((ABI::Microsoft::SDKSamples::Kitchen::OvenTemperature)5);
00034         if (hr == E_INVALIDARG)
00035         {
00036             CustomExceptionWRLOutput->Text += L"Error handled. Please attach a debugger and enable first chance native exceptions to view exception details.\n";
00037         }
00038     }
00039 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BasicHologramMain::GamepadWithButtonState Member List

This is the complete list of members for BasicHologramMain::GamepadWithButtonState, including all inherited members.
buttonAWasPressedLastFrame | BasicHologramMain::GamepadWithButtonState |
gamepad | BasicHologramMain::GamepadWithButtonState |
gamepad | BasicHologramMain::GamepadWithButtonState |
GamepadWithButtonState(Windows::Gaming::Input::Gamepad^gamepad, bool buttonAWasPressedLastFrame) | BasicHologramMain::GamepadWithButtonState | [inline]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LockScreenApps/cppwinrt/SampleConfiguration.cpp Source File

  • LockScreenApps
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"LockScreenApps C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Add app to lock screen", xaml_typename<SDKTemplate::Scenario1_Configure>() },
00029     Scenario{ L"Badge and tile notifications", xaml_typename<SDKTemplate::Scenario2_Notifications>() },
00030     Scenario{ L"Secondary tiles", xaml_typename<SDKTemplate::Scenario3_SecondaryTiles>() },
00031 });
Generated on Fri Nov 15 2024 22:17:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdaptiveStreaming/cs/Scenario5_Metadata.xaml.cs Source File

  • AdaptiveStreaming
  • cs

Scenario5_Metadata.xaml.cs

Go to the documentation of this file.
00001 // *********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 // *********************************************************
00011
00012 using SDKTemplate.Helpers;
00013 using SDKTemplate.Logging;
00014 using System;
00015 using System.Linq;
00016 using System.Text;
00017 using System.Threading.Tasks;
00018 using Windows.Foundation.Collections;
00019 using Windows.Media.Core;
00020 using Windows.Media.Playback;
00021 using Windows.Media.Streaming.Adaptive;
00022 using Windows.Storage.Streams;
00023 using Windows.UI.Core;
00024 using Windows.UI.Xaml;
00025 using Windows.UI.Xaml.Controls;
00026 using Windows.UI.Xaml.Navigation;
00027 using Windows.Web.Http;
00028
00029 namespace SDKTemplate
00030 {
00031     // See the README.md for discussion of this scenario.
00032
00033     public sealed partial class Scenario5_Metadata : Page
00034     {
00035         public Scenario5_Metadata()
00036         {
00037             this.InitializeComponent();
00038         }
00039
00040         protected override void OnNavigatedFrom(NavigationEventArgs e)
00041         {
00042
00043             // Release handles on various media objects to ensure a quick clean-up
00044             ContentSelectorControl.MediaPlaybackItem = null;
00045             var mediaPlayer = mediaPlayerElement.MediaPlayer;
00046             if (mediaPlayer != null)
00047             {
00048                 mediaPlayerLogger?.Dispose();
00049                 mediaPlayerLogger = null;
00050
00051                 UnregisterHandlers(mediaPlayer);
00052
00053                 mediaPlayerElement.SetMediaPlayer(null);
00054                 mediaPlayer.Dispose();
00055             }
00056         }
00057
00058         private void UnregisterHandlers(MediaPlayer mediaPlayer)
00059         {
00060             AdaptiveMediaSource adaptiveMediaSource = null;
00061             MediaPlaybackItem mpItem = mediaPlayer.Source as MediaPlaybackItem;
00062             if (mpItem != null)
00063             {
00064                 adaptiveMediaSource = mpItem.Source.AdaptiveMediaSource;
00065                 UnregisterForMediaSourceEvents(mpItem.Source);
00066                 UnregisterForMediaPlaybackItemEvents(mpItem);
00067             }
00068             MediaSource source = mediaPlayer.Source as MediaSource;
00069             if (source != null)
00070             {
00071                 adaptiveMediaSource = source.AdaptiveMediaSource;
00072                 UnregisterForMediaSourceEvents(source);
00073             }
00074
00075             mediaPlaybackItemLogger?.Dispose();
00076             mediaPlaybackItemLogger = null;
00077
00078             mediaSourceLogger?.Dispose();
00079             mediaSourceLogger = null;
00080
00081             adaptiveMediaSourceLogger?.Dispose();
00082             adaptiveMediaSourceLogger = null;
00083
00084         }
00085
00086         private void Page_OnLoaded(object sender, RoutedEventArgs e)
00087         {
00088             var mediaPlayer = new MediaPlayer();
00089
00090             // We use a helper class that logs all the events for the MediaPlayer:
00091             mediaPlayerLogger = new MediaPlayerLogger(LoggerControl, mediaPlayer);
00092
00093             // Ensure we have PlayReady support, in case the user enters a DASH/PR Uri in the text box.
00094             var prHelper = new PlayReadyHelper(LoggerControl);
00095             prHelper.SetUpProtectionManager(mediaPlayer);
00096             mediaPlayerElement.SetMediaPlayer(mediaPlayer);
00097
00098             ContentSelectorControl.Initialize(
00099                 mediaPlayer,
00100                 MainPage.ContentManagementSystemStub.Where(m => !m.Aes),
00101                 null,
00102                 LoggerControl,
00103                 LoadSourceFromUriAsync);
00104
00105             ContentSelectorControl.SetAutoPlay(true);  // Force AutoPlay in this scenario.
00106         }
00107
00108
00109         #region Content Loading
00110
00111         private async Task<MediaPlaybackItem> LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
00112         {
00113             UnregisterHandlers(mediaPlayerElement.MediaPlayer);
00114
00115             AdaptiveMediaSourceCreationResult result = null;
00116             if (httpClient != null)
00117             {
00118                 result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
00119             }
00120             else
00121             {
00122                 result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
00123             }
00124
00125             MediaSource source;
00126             if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
00127             {
00128                 var adaptiveMediaSource = result.MediaSource;
00129
00130                 // We use a helper class that logs all the events for the AdaptiveMediaSource:
00131                 adaptiveMediaSourceLogger = new AdaptiveMediaSourceLogger(LoggerControl, adaptiveMediaSource);
00132
00133                 source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSource);
00134
00135             }
00136             else
00137             {
00138                 Log($"Error creating the AdaptiveMediaSource. Status: {result.Status}, ExtendedError.Message: {result.ExtendedError.Message}, ExtendedError.HResult: {result.ExtendedError.HResult.ToString("X8")}");
00139                 return null;
00140             }
00141
00142             // We use a helper class that logs all the events for the MediaSource:
00143             mediaSourceLogger = new MediaSourceLogger(LoggerControl, source);
00144
00145             // Save the original Uri.
00146             source.CustomProperties["uri"] = uri.ToString();
00147
00148             // You're likely to put a content tracking id into the CustomProperties.
00149             source.CustomProperties["contentId"] = Guid.NewGuid().ToString();
00150
00151             // In addition to logging, this scenario uses MediaSource events:
00152             RegisterForMediaSourceEvents(source);
00153
00154             var mpItem = new MediaPlaybackItem(source);
00155
00156             // We use a helper class that logs all the events for the MediaPlaybackItem:
00157             mediaPlaybackItemLogger = new MediaPlaybackItemLogger(LoggerControl, mpItem);
00158
00159             // In addition to logging, this scenario uses MediaPlaybackItem events:
00160             RegisterForMediaPlaybackItemEvents(mpItem);
00161
00162             HideDescriptionOnSmallScreen();
00163
00164             return mpItem;
00165         }
00166
00167         private async void HideDescriptionOnSmallScreen()
00168         {
00169             // On small screens, hide the description text to make room for the video.
00170             await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00171             {
00172                 DescriptionText.Visibility = (ActualHeight < 500) ? Visibility.Collapsed : Visibility.Visible;
00173             });
00174         }
00175         #endregion
00176
00177
00178         #region MediaSource Event Handlers
00179
00180         private void RegisterForMediaSourceEvents(MediaSource source)
00181         {
00182             source.OpenOperationCompleted += Source_OpenOperationCompleted;
00183         }
00184         private void UnregisterForMediaSourceEvents(MediaSource source)
00185         {
00186             source.OpenOperationCompleted -= Source_OpenOperationCompleted;
00187         }
00188
00189         private void Source_OpenOperationCompleted(MediaSource source, MediaSourceOpenOperationCompletedEventArgs args)
00190         {
00191             // Here we create our own metadata track.
00192             // Our goal is to track progress through the asset and report it back to a server.
00193             object customValue = null;
00194             source.CustomProperties.TryGetValue("contentId", out customValue);
00195             string contentId = (string)customValue;
00196             var reportingUriFormat = "http://myserver/reporting/{0}?id={1}";
00197             // From \Shared\TrackingEventCue.cs :
00198             TrackingEventCue.CreateTrackingEventsTrack(source, contentId, reportingUriFormat);
00199         }
00200
00201         #endregion
00202
00203
00204         #region MediaPlaybackItem Event Handlers
00205
00206         private void RegisterForMediaPlaybackItemEvents(MediaPlaybackItem item)
00207         {
00208             // If we encountered some unknown tags in an m3u8 manifest,
00209             // we might already have metadata tracks in the source,
00210             // which is used as the constructor for the MediaPlaybackItem.
00211             // Therefore, the MediaPlaybackItem may already have metadata tracks.
00212             // Since TracksChanged will not be raised for these it is best to check
00213             // if we have tracks, and set up the handlers:
00214             if (item.TimedMetadataTracks.Count > 0)
00215             {
00216                 Log($"Registering existing TimedMetadataTracks, Count: {item.TimedMetadataTracks.Count}");
00217
00218                 for (int index = 0; index < item.TimedMetadataTracks.Count; index++)
00219                 {
00220                     RegisterMetadataHandlers(item, index);
00221                 }
00222             }
00223
00224             // For any tracks found as the content is parsed, we register for the event handler:
00225             item.TimedMetadataTracksChanged += Item_TimedMetadataTracksChanged;
00226         }
00227
00228         private void UnregisterForMediaPlaybackItemEvents(MediaPlaybackItem item)
00229         {
00230             item.TimedMetadataTracksChanged -= Item_TimedMetadataTracksChanged;
00231             foreach (var track in item.TimedMetadataTracks)
00232             {
00233                 UnregisterMetadataHandlers(track);
00234             }
00235         }
00236
00237         private void Item_TimedMetadataTracksChanged(MediaPlaybackItem item, IVectorChangedEventArgs args)
00238         {
00239             Log($"item.TimedMetadataTracksChanged: CollectionChange:{args.CollectionChange} Index:{args.Index} Total:{item.TimedMetadataTracks.Count}");
00240
00241             if (args.CollectionChange == CollectionChange.ItemInserted)
00242             {
00243                 RegisterMetadataHandlers(item, (int)args.Index);
00244             }
00245             if (args.CollectionChange == CollectionChange.Reset)
00246             {
00247                 for (int index = 0; index < item.TimedMetadataTracks.Count; index++)
00248                 {
00249                     RegisterMetadataHandlers(item, index);
00250                 }
00251             }
00252         }
00253
00254         private void RegisterMetadataHandlers(MediaPlaybackItem mediaPlaybackItem, int index)
00255         {
00256             var timedTrack = mediaPlaybackItem.TimedMetadataTracks[index];
00257             object customValue = null;
00258             mediaPlaybackItem.Source.CustomProperties.TryGetValue("contentId", out customValue);
00259             string contentId = (string)customValue;
00260
00261             StringBuilder logMsg = new StringBuilder($"{contentId} ");
00262
00263             if (timedTrack.TrackKind == MediaTrackKind.TimedMetadata &&
00264                 (timedTrack.TimedMetadataKind == TimedMetadataKind.Data ||
00265                 timedTrack.TimedMetadataKind == TimedMetadataKind.Custom))
00266             {
00267                 // Check for known dispatchTypes:
00268                 var dispatchType = mediaPlaybackItem.TimedMetadataTracks[index].DispatchType;
00269                 if (String.Equals(dispatchType, "EXTM3U", StringComparison.OrdinalIgnoreCase))
00270                 {
00271                     timedTrack.CueEntered += metadata_extm3u_CueEntered;
00272                     timedTrack.Label = "HLS Manifest comments";
00273                     // Tell the platform that the app will render these.
00274                     // Without this, the CueEntered event will not be raised by the platform.
00275                     mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode((uint)index, TimedMetadataTrackPresentationMode.ApplicationPresented);
00276                 }
00277                 else if (string.Equals(dispatchType, "15260DFFFF49443320FF49443320000F", StringComparison.OrdinalIgnoreCase)) // per Apple TS spec for ID3 meta
00278                 {
00279                     timedTrack.CueEntered += metadata_id3_CueEntered;
00280                     timedTrack.Label = "ID3 Tags";
00281                     mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode((uint)index, TimedMetadataTrackPresentationMode.ApplicationPresented);
00282                 }
00283                 else if (string.Equals(dispatchType, "emsg:mp4", StringComparison.OrdinalIgnoreCase)) // For 'emsg' box embedded in mp4 container
00284                 {
00285                     timedTrack.CueEntered += metadata_emsg_mp4_CueEntered;
00286                     timedTrack.Label = "emsg payload";
00287                     mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode((uint)index, TimedMetadataTrackPresentationMode.ApplicationPresented);
00288                 }
00289
00290                 // Check for our Custom TimedMetadataTrack
00291                 if (mediaPlaybackItem.TimedMetadataTracks[index].Id == "TrackingEvents")
00292                 {
00293                     timedTrack.CueEntered += metadata_TrackingEvents_CueEntered;
00294                     timedTrack.CueExited += metadata_TrackingEvents_CueExited;
00295                     timedTrack.Label = "Tracking Events";
00296                     mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode((uint)index, TimedMetadataTrackPresentationMode.ApplicationPresented);
00297                 }
00298
00299                 logMsg.AppendLine($"Registered CueEntered for {timedTrack.Label}.");
00300             }
00301             else
00302             {
00303                 logMsg.AppendLine("Did not register CueEntered for TimedMetadataTrack.");
00304             }
00305             logMsg.AppendLine($"TimedMetadataKind: {timedTrack.TimedMetadataKind}, Id: {timedTrack.Id}, Label: {timedTrack.Label}, DispatchType: {timedTrack.DispatchType}, Language: {timedTrack.Language}");
00306
00307             Log(logMsg.ToString());
00308         }
00309
00310         private void UnregisterMetadataHandlers(TimedMetadataTrack timedTrack)
00311         {
00312             if (timedTrack.Label == "HLS Manifest comments")
00313             {
00314                 timedTrack.CueEntered -= metadata_extm3u_CueEntered;
00315             }
00316             if(timedTrack.Label == "ID3 Tags")
00317             {
00318                 timedTrack.CueEntered -= metadata_id3_CueEntered;
00319             }
00320             if(timedTrack.Label == "emsg payload")
00321             {
00322                 timedTrack.CueEntered -= metadata_emsg_mp4_CueEntered;
00323             }
00324             if (timedTrack.Label == "Tracking Events")
00325             {
00326                 timedTrack.CueEntered -= metadata_TrackingEvents_CueEntered;
00327                 timedTrack.CueExited -= metadata_TrackingEvents_CueExited;
00328             }
00329         }
00330
00331
00332         private void metadata_extm3u_CueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args)
00333         {
00334             StringBuilder logMsg = new StringBuilder();
00335
00336             object customValue = null;
00337             timedMetadataTrack.PlaybackItem.Source.CustomProperties.TryGetValue("contentId", out customValue);
00338             string contentId = (string)customValue;
00339             logMsg.AppendLine($"{contentId} M3U8 DataCue CueEntered raised.");
00340             var dataCue = args.Cue as DataCue;
00341             if (dataCue != null && dataCue.Data != null)
00342             {
00343                 // The payload is a UTF-16 Little Endian null-terminated string.
00344                 // It is any comment line in a manifest that is not part of the HLS spec.
00345                 var dr = DataReader.FromBuffer(dataCue.Data);
00346                 dr.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
00347                 var m3u8Comment = dr.ReadString(dataCue.Data.Length / 2 - 1);
00348                 logMsg.AppendLine($"Label: {timedMetadataTrack.Label}, Id: {dataCue.Id}, StartTime: {dataCue.StartTime}, Duration: {dataCue.Duration}");
00349                 logMsg.Append(m3u8Comment);
00350                 // TODO: Use the m3u8Comment string for something useful.
00351             }
00352             Log(logMsg.ToString());
00353         }
00354
00355         private void metadata_id3_CueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args)
00356         {
00357             StringBuilder logMsg = new StringBuilder();
00358             object customValue = null;
00359             timedMetadataTrack.PlaybackItem.Source.CustomProperties.TryGetValue("contentId", out customValue);
00360             string contentId = (string)customValue;
00361             logMsg.AppendLine($"{contentId} ID3 DataCue CueEntered raised.");
00362             var dataCue = args.Cue as DataCue;
00363             if (dataCue != null && dataCue.Data != null && dataCue.Data.Length >= 10)
00364             {
00365                 // The payload is the raw ID3 bytes found in a TS stream
00366                 // Ref: http://id3.org/id3v2.4.0-structure
00367                 var dr = DataReader.FromBuffer(dataCue.Data);
00368                 var header_ID3 = dr.ReadString(3);
00369                 var header_version_major = dr.ReadByte();
00370                 var header_version_minor = dr.ReadByte();
00371                 var header_flags = dr.ReadByte();
00372                 var header_tagSize = dr.ReadUInt32();
00373                 // TODO: Use the ID3 bytes for something useful.
00374
00375                 logMsg.AppendLine($"Label: {timedMetadataTrack.Label}, Id: {dataCue.Id}, StartTime: {dataCue.StartTime}, Duration: {dataCue.Duration}");
00376                 logMsg.Append($"{header_ID3}, {header_version_major}.{header_version_minor}, {header_flags}, {header_tagSize}");
00377             }
00378             Log(logMsg.ToString());
00379         }
00380
00381         private UInt32 lastProcessedAdId = 0;
00382         private void metadata_emsg_mp4_CueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args)
00383         {
00384             StringBuilder logMsg = new StringBuilder();
00385             object customValue = null;
00386             timedMetadataTrack.PlaybackItem.Source.CustomProperties.TryGetValue("contentId", out customValue);
00387             string contentId = (string)customValue;
00388             logMsg.AppendLine($"{contentId} mp4 emsg DataCue CueEntered raised.");
00389             var dataCue = args.Cue as DataCue;
00390             if (dataCue != null)
00391             {
00392                 // Ref: ISO/IEC 20009-1, Section 5.10.3.3.2 Definition of Box Type: 'emsg'
00393                 string scheme_id_uri = string.Empty;
00394                 string value = string.Empty;
00395                 UInt32 timescale = (UInt32) TimeSpan.TicksPerSecond;
00396                 UInt32 presentation_time_delta = (UInt32)dataCue.StartTime.Ticks;
00397                 UInt32 event_duration = (UInt32)dataCue.Duration.Ticks;
00398                 UInt32 id = 0;
00399                 Byte[] message_data = null;
00400
00401                 const string scheme_id_uri_key = "emsg:scheme_id_uri";
00402                 object propValue = null;
00403                 dataCue.Properties.TryGetValue(scheme_id_uri_key, out propValue);
00404                 scheme_id_uri = propValue!=null ? (string)propValue : "";
00405
00406                 const string value_key = "emsg:value";
00407                 propValue = null;
00408                 dataCue.Properties.TryGetValue(value_key, out propValue);
00409                 value = propValue != null ? (string)propValue : "";
00410
00411                 const string timescale_key = "emsg:timescale";
00412                 propValue = null;
00413                 dataCue.Properties.TryGetValue(timescale_key, out propValue);
00414                 timescale = propValue != null ? (UInt32)propValue : timescale;
00415
00416                 const string presentation_time_delta_key = "emsg:presentation_time_delta";
00417                 propValue = null;
00418                 dataCue.Properties.TryGetValue(presentation_time_delta_key, out propValue);
00419                 presentation_time_delta = propValue != null ? (UInt32)propValue : presentation_time_delta;
00420
00421                 const string event_duration_key = "emsg:event_duration";
00422                 propValue = null;
00423                 dataCue.Properties.TryGetValue(event_duration_key, out propValue);
00424                 event_duration = propValue != null ? (UInt32)propValue : event_duration;
00425
00426                 const string id_key = "emsg:id";
00427                 propValue = null;
00428                 dataCue.Properties.TryGetValue(id_key, out propValue);
00429                 id = propValue != null ? (UInt32)propValue : 0;
00430
00431                 logMsg.AppendLine($"Label: {timedMetadataTrack.Label}, Id: {dataCue.Id}, StartTime: {dataCue.StartTime}, Duration: {dataCue.Duration}");
00432                 logMsg.Append($"scheme_id_uri: {scheme_id_uri}, value: {value}, timescale: {timescale}, presentation_time_delta: {presentation_time_delta}, event_duration: {event_duration}, id: {id}");
00433
00434                 if (dataCue.Data != null)
00435                 {
00436                     var dr = DataReader.FromBuffer(dataCue.Data);
00437
00438                     // Check if this is a SCTE ad message:
00439                     // Ref:  http://dashif.org/identifiers/event-schemes/
00440                     if (scheme_id_uri.ToLower() == "urn:scte:scte35:2013:xml")
00441                     {
00442                         // SCTE recommends publishing emsg more than once, so we avoid reprocessing the same message id:
00443                         if (lastProcessedAdId != id)
00444                         {
00445                             lastProcessedAdId = id; // TODO: Requires robustness. Messages may be out of order, which would break this sample's logic.
00446
00447                             dr.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
00448                             var scte35payload = dr.ReadString(dataCue.Data.Length);
00449                             logMsg.Append($", message_data: {scte35payload}");
00450                             ScheduleAdFromScte35Payload(timedMetadataTrack, presentation_time_delta, timescale, event_duration, scte35payload);
00451                         }
00452                         else
00453                         {
00454                             logMsg.AppendLine($"This emsg.Id, {id}, has already been processed.");
00455                         }
00456                     }
00457                     else
00458                     {
00459                         message_data = new byte[dataCue.Data.Length];
00460                         dr.ReadBytes(message_data);
00461                         // TODO: Use the 'emsg' bytes for something useful.
00462                         logMsg.Append($", message_data.Length: {message_data.Length}");
00463                     }
00464                 }
00465             }
00466             Log(logMsg.ToString());
00467         }
00468
00469         /// <summary>
00470         /// This function attempts to parse the SCTE-35 payload, then schedule an appropriately offset Ad using the MediaBreak APIs
00471         /// </summary>
00472         /// <param name="timedMetadataTrack">Track which fired the cue</param>
00473         /// <param name="presentation_time_delta"></param>
00474         /// <param name="timescale"></param>
00475         /// <param name="event_duration"></param>
00476         /// <param name="scte35payload"></param>
00477         private async void ScheduleAdFromScte35Payload(TimedMetadataTrack timedMetadataTrack, uint presentation_time_delta, uint timescale, uint event_duration, string scte35payload)
00478         {
00479             // TODO: Parse SCTE-35
00480             //
00481             // Ref:
00482             // http://www.scte.org/SCTEDocs/Standards/ANSI_SCTE%20214-3%202015.pdf
00483             //
00484             // Eg:
00485             //
00486             // <SpliceInfoSection ptsAdjustment="0" scte35:tier="4095">
00487             //  <SpliceInsert spliceEventId="147467497"
00488             //                spliceEventCancelIndicator="false"
00489             //                outOfNetworkIndicator="false"
00490             //                uniqueProgramId="0"
00491             //                availNum="0"
00492             //                availsExpected="0"
00493             //                spliceImmediateFlag="false" >
00494             //    <Program>
00495             //      <SpliceTime ptsTime="6257853600"/>
00496             //    </Program>
00497             //    <BreakDuration autoReturn="true" duration="900000"/>
00498             //  </SpliceInsert>
00499             // </SpliceInfoSection>
00500             //
00501             //
00502
00503             // We use the metadata track object which fired the Cue to walk our way back up the
00504             // media object stack to find our original AdaptiveMediaSource.
00505             //
00506             // The AdaptiveMediaSource is required because the SCTE-35 payload includes
00507             // timing offsets which are relative to the original content PTS -- see below.
00508             var ams = timedMetadataTrack.PlaybackItem.Source.AdaptiveMediaSource;
00509
00510             if (ams != null && timescale != 0)
00511             {
00512                 // ++++
00513                 // NOTE: DO NOT PARSE SCTE35 LIKE THIS IN PRODUCTION CODE!
00514                 //
00515                 // Reminder:
00516                 //
00517                 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00518                 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00519                 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00520                 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00521                 //
00522                 // We will not demonstrate proper SCTE35 parsing in this sample,
00523                 // but instead we search through the xml find the ptsTime if present,
00524                 // and use it to schedule an ad; keeping in place the various time offsets.
00525                 //
00526                 // e.g.: var sampleScte35Payload = "<SpliceInfoSection ptsAdjustment=\"0\" scte35:tier=\"4095\">< SpliceInsert spliceEventId = \"147467497\" spliceEventCancelIndicator = \"false\" outOfNetworkIndicator = \"false\" uniqueProgramId = \"0\" availNum = \"0\" availsExpected = \"0\" spliceImmediateFlag = \"false\" > < Program >< SpliceTime ptsTime = \"6257853600\" /></ Program >  < BreakDuration autoReturn = \"true\" duration = \"900000\" />  </ SpliceInsert > </ SpliceInfoSection > ";
00527                 //
00528                 var xmlStrings = scte35payload.Split(new string[] { "<", "/", ">", " ", "=", "\"" }, StringSplitOptions.RemoveEmptyEntries);
00529                 string ptsTime = string.Empty;
00530                 for (int i = 0; i < xmlStrings.Length; i++)
00531                 {
00532                     if (xmlStrings[i] == "ptsTime")
00533                     {
00534                         if (i + 1 < xmlStrings.Length)
00535                         {
00536                             ptsTime = xmlStrings[i + 1];
00537                             break;
00538                         }
00539                     }
00540                 }
00541                 // ----
00542
00543                 // The AdaptiveMediaSource keeps track of the original PTS in an AdaptiveMediaSourceCorrelatedTimes
00544                 // object that can be retrieved via ams.GetCorrelatedTimes().  All the while, it provids the
00545                 // media pipeline with a consistent timeline that re-aligns zero at the begining  of the SeekableRange
00546                 // when first joining a Live stream.
00547                 long pts = 0;
00548                 long.TryParse(ptsTime, out pts);
00549                 var timeCorrelation = ams.GetCorrelatedTimes();
00550                 if (timeCorrelation.Position.HasValue && timeCorrelation.PresentationTimeStamp.HasValue)
00551                 {
00552                     TimeSpan currentPosition;
00553                     await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00554                     {
00555                         currentPosition = mediaPlayerElement.MediaPlayer.PlaybackSession.Position;
00556                     });
00557                     TimeSpan emsgPresentationTimeDelta = TimeSpan.FromSeconds(presentation_time_delta/timescale);
00558                     long delayInTicks = timeCorrelation.PresentationTimeStamp.Value.Ticks - pts;
00559                     TimeSpan correctionForAsyncCalls = currentPosition - timeCorrelation.Position.Value;
00560                     TimeSpan targetAdPosition = emsgPresentationTimeDelta + TimeSpan.FromTicks(delayInTicks) + correctionForAsyncCalls;
00561
00562                     Log($"Timing Info: PlaybackSession.Position:{currentPosition}  targetAdPosition:{targetAdPosition}  Delta:{targetAdPosition-currentPosition}  Ams.Position:{timeCorrelation.Position.GetValueOrDefault().Ticks}  SCTE ptsTime:{pts}  emsgPresentationTimeDelta:{emsgPresentationTimeDelta} Ams.PresentationTimeStamp:{timeCorrelation.PresentationTimeStamp.GetValueOrDefault().Ticks}  Ams.ProgramDateTime:{timeCorrelation.ProgramDateTime.GetValueOrDefault()}");
00563
00564                     MediaBreakInsertionMethod insertionMethod = ams.IsLive ? MediaBreakInsertionMethod.Replace : MediaBreakInsertionMethod.Interrupt;
00565                     var redSkyUri = new Uri("http://az29176.vo.msecnd.net/videocontent/RedSky_FoxRiverWisc_GettyImagesRF-499617760_1080_HD_EN-US.mp4");
00566                     if (targetAdPosition != TimeSpan.Zero && targetAdPosition >= currentPosition)
00567                     {
00568                         // Schedule ad in the future:
00569                         Log($"Ad insertion triggerd by 'emsg'.  Scheduled: {targetAdPosition.ToString()} Current:{currentPosition.ToString()}");
00570                         var midRollBreak = new MediaBreak(insertionMethod, targetAdPosition);
00571                         midRollBreak.PlaybackList.Items.Add(new MediaPlaybackItem(MediaSource.CreateFromUri(redSkyUri)));
00572                         timedMetadataTrack.PlaybackItem.BreakSchedule.InsertMidrollBreak(midRollBreak);
00573                     }
00574                     else
00575                     {
00576                         // Play now!
00577                         Log($"Ad inserted immediately.  Scheduled: {targetAdPosition.ToString()} Current:{currentPosition.ToString()}");
00578                         var midRollBreak = new MediaBreak(insertionMethod);
00579                         midRollBreak.PlaybackList.Items.Add(new MediaPlaybackItem(MediaSource.CreateFromUri(redSkyUri)));
00580                         await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00581                         {
00582                             mediaPlayerElement.MediaPlayer.BreakManager.PlayBreak(midRollBreak);
00583                         });
00584                     }
00585                 }
00586             }
00587         }
00588
00589         private void metadata_TrackingEvents_CueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args)
00590         {
00591             StringBuilder logMsg = new StringBuilder();
00592             object customValue = null;
00593             timedMetadataTrack.PlaybackItem.Source.CustomProperties.TryGetValue("contentId", out customValue);
00594             string contentId = (string)customValue;
00595             logMsg.AppendLine($"{contentId} TrackingEventCue CueEntered raised.");
00596             var trackingEventCue = args.Cue as TrackingEventCue;
00597             if (trackingEventCue != null)
00598             {
00599                 logMsg.AppendLine($"Label: {timedMetadataTrack.Label}, Id: {trackingEventCue.Id}, StartTime: {trackingEventCue.StartTime}, Duration: {trackingEventCue.Duration}");
00600                 logMsg.Append($"{trackingEventCue.TrackingEventUri}");
00601                 // TODO: Use the reporing Uri for something useful.
00602             }
00603             Log(logMsg.ToString());
00604         }
00605
00606         private void metadata_TrackingEvents_CueExited(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args)
00607         {
00608             StringBuilder logMsg = new StringBuilder();
00609             object customValue = null;
00610             timedMetadataTrack.PlaybackItem.Source.CustomProperties.TryGetValue("contentId", out customValue);
00611             string contentId = (string)customValue;
00612             logMsg.AppendLine($"{contentId} TrackingEventCue CueExited raised.");
00613             var trackingEventCue = args.Cue as TrackingEventCue;
00614             if (trackingEventCue != null)
00615             {
00616                 logMsg.AppendLine($"Label: {timedMetadataTrack.Label}, Id: {trackingEventCue.Id}, StartTime: {trackingEventCue.StartTime}, Duration: {trackingEventCue.Duration}");
00617                 logMsg.Append($"{trackingEventCue.TrackingEventUri}");
00618             }
00619             Log(logMsg.ToString());
00620         }
00621         #endregion
00622
00623
00624         #region Utilities
00625         private void Log(string message)
00626         {
00627             LoggerControl.Log(message);
00628         }
00629         MediaPlayerLogger mediaPlayerLogger;
00630         MediaSourceLogger mediaSourceLogger;
00631         MediaPlaybackItemLogger mediaPlaybackItemLogger;
00632         AdaptiveMediaSourceLogger adaptiveMediaSourceLogger;
00633         #endregion
00634     }
00635
00636 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Json/cs/User.cs Source File

  • Json
  • cs

User.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.ObjectModel;
00014 using Windows.Data.Json;
00015
00016 namespace SDKTemplate
00017 {
00018     class User
00019     {
00020         private const string idKey = "id";
00021         private const string phoneKey = "phone";
00022         private const string nameKey = "name";
00023         private const string educationKey = "education";
00024         private const string timezoneKey = "timezone";
00025         private const string verifiedKey = "verified";
00026
00027         public User()
00028         {
00029         }
00030
00031         public User(string jsonString) : this()
00032         {
00033             JsonObject jsonObject = JsonObject.Parse(jsonString);
00034             Id = jsonObject.GetNamedString(idKey, "");
00035
00036             IJsonValue phoneJsonValue = jsonObject.GetNamedValue(phoneKey);
00037             if (phoneJsonValue.ValueType == JsonValueType.Null)
00038             {
00039                 Phone = null;
00040             }
00041             else
00042             {
00043                 Phone = phoneJsonValue.GetString();
00044             }
00045
00046             Name = jsonObject.GetNamedString(nameKey, "");
00047             Timezone = jsonObject.GetNamedNumber(timezoneKey, 0);
00048             Verified = jsonObject.GetNamedBoolean(verifiedKey, false);
00049
00050             foreach (IJsonValue jsonValue in jsonObject.GetNamedArray(educationKey, new JsonArray()))
00051             {
00052                 Education.Add(new School(jsonValue.GetObject()));
00053             }
00054         }
00055
00056         public string Stringify()
00057         {
00058             JsonObject jsonObject = new JsonObject();
00059             jsonObject[idKey] = JsonValue.CreateStringValue(Id);
00060
00061             // Treating a blank string as null
00062             if (String.IsNullOrEmpty(Phone))
00063             {
00064                 jsonObject[phoneKey] = JsonValue.CreateNullValue();
00065             }
00066             else
00067             {
00068                 jsonObject[phoneKey] = JsonValue.CreateStringValue(Phone);
00069             }
00070
00071             jsonObject[nameKey] = JsonValue.CreateStringValue(Name);
00072
00073             jsonObject[timezoneKey] = JsonValue.CreateNumberValue(Timezone);
00074             jsonObject[verifiedKey] = JsonValue.CreateBooleanValue(Verified);
00075
00076             JsonArray jsonArray = new JsonArray();
00077             foreach (School school in Education)
00078             {
00079                 jsonArray.Add(school.ToJsonObject());
00080             }
00081             jsonObject[educationKey] = jsonArray;
00082
00083             return jsonObject.Stringify();
00084         }
00085
00086         public string Id { get; set; } = "";
00087
00088         public string Phone { get; set; } = null;
00089
00090         public string Name { get; set; } = "";
00091
00092         public ObservableCollection<School> Education { get; } = new ObservableCollection<School>();
00093
00094         public double Timezone { get; set; } = 0.0;
00095         public bool Verified { get; set; } = false;
00096     }
00097 }
Generated on Fri Nov 15 2024 22:20:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomPixelShaderRenderer Member List

This is the complete list of members for CustomPixelShaderRenderer, including all inherited members.
CreateDeviceDependentResources() | CustomPixelShaderRenderer |
CreateDeviceIndependentResources() | CustomPixelShaderRenderer |
CreateWindowSizeDependentResources() | CustomPixelShaderRenderer |
CustomPixelShaderRenderer(const std::shared_ptr< DX::DeviceResources > &deviceResources) | CustomPixelShaderRenderer |
LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | CustomPixelShaderRenderer | [inline]
m_deviceResources | CustomPixelShaderRenderer | [private]
m_formatConvert | CustomPixelShaderRenderer | [private]
m_imageSize | CustomPixelShaderRenderer | [private]
m_imageSource | CustomPixelShaderRenderer | [private]
m_isRippleAnimating | CustomPixelShaderRenderer | [private]
m_isWindowClosed | CustomPixelShaderRenderer | [private]
m_rippleEffect | CustomPixelShaderRenderer | [private]
m_scale | CustomPixelShaderRenderer | [private]
m_timer | CustomPixelShaderRenderer | [private]
m_transformedImage | CustomPixelShaderRenderer | [private]
ReleaseDeviceDependentResources() | CustomPixelShaderRenderer |
Render() | CustomPixelShaderRenderer |
SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | CustomPixelShaderRenderer | [inline]
Update() | CustomPixelShaderRenderer |
UpdateImageScale(float scale) | CustomPixelShaderRenderer | [private]
UpdatePointer(_In_ Windows::UI::Core::PointerEventArgs^args) | CustomPixelShaderRenderer |
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HolographicSpatialMappingMain Member List

This is the complete list of members for HolographicSpatialMappingMain, including all inherited members.
HolographicSpatialMappingMain(const std::shared_ptr< DX::DeviceResources > &deviceResources) | HolographicSpatialMappingMain |
LoadAppState() | HolographicSpatialMappingMain |
m_cameraAddedToken | HolographicSpatialMappingMain | [private]
m_cameraRemovedToken | HolographicSpatialMappingMain | [private]
m_deviceResources | HolographicSpatialMappingMain | [private]
m_drawWireframe | HolographicSpatialMappingMain | [private]
m_holographicSpace | HolographicSpatialMappingMain | [private]
m_locator | HolographicSpatialMappingMain | [private]
m_positionalTrackingDeactivatingToken | HolographicSpatialMappingMain | [private]
m_referenceFrame | HolographicSpatialMappingMain | [private]
m_spatialPerceptionAccessRequested | HolographicSpatialMappingMain | [private]
m_surfaceAccessAllowed | HolographicSpatialMappingMain | [private]
m_surfaceMeshOptions | HolographicSpatialMappingMain | [private]
m_surfaceObserver | HolographicSpatialMappingMain | [private]
m_surfacesChangedToken | HolographicSpatialMappingMain | [private]
m_timer | HolographicSpatialMappingMain | [private]
OnCameraAdded(Windows::Graphics::Holographic::HolographicSpace^sender, Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs^args) | HolographicSpatialMappingMain | [private]
OnCameraRemoved(Windows::Graphics::Holographic::HolographicSpace^sender, Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs^args) | HolographicSpatialMappingMain | [private]
OnDeviceLost() | HolographicSpatialMappingMain | [virtual]
OnDeviceRestored() | HolographicSpatialMappingMain | [virtual]
OnPositionalTrackingDeactivating(Windows::Perception::Spatial::SpatialLocator^sender, Windows::Perception::Spatial::SpatialLocatorPositionalTrackingDeactivatingEventArgs^args) | HolographicSpatialMappingMain | [private]
OnSurfacesChanged(Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver^sender, Platform::Object^args) | HolographicSpatialMappingMain |
Render(Windows::Graphics::Holographic::HolographicFrame^holographicFrame) | HolographicSpatialMappingMain |
SaveAppState() | HolographicSpatialMappingMain |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^holographicSpace) | HolographicSpatialMappingMain |
UnregisterHolographicEventHandlers() | HolographicSpatialMappingMain | [private]
Update() | HolographicSpatialMappingMain |
~HolographicSpatialMappingMain() | HolographicSpatialMappingMain |
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialStage/cpp/Common/DeviceResources.cpp Source File

  • HolographicSpatialStage
  • cpp
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿
00002 #include "pch.h"
00003 #include "DeviceResources.h"
00004 #include "DirectXHelper.h"
00005
00006 #include <Collection.h>
00007 #include <windows.graphics.directx.direct3d11.interop.h>
00008
00009 using namespace D2D1;
00010 using namespace Microsoft::WRL;
00011 using namespace Windows::Graphics::DirectX::Direct3D11;
00012 using namespace Windows::Graphics::Display;
00013 using namespace Windows::Graphics::Holographic;
00014
00015 // Constructor for DeviceResources.
00016 DX::DeviceResources::DeviceResources()
00017 {
00018     CreateDeviceIndependentResources();
00019 }
00020
00021 // Configures resources that don't depend on the Direct3D device.
00022 void DX::DeviceResources::CreateDeviceIndependentResources()
00023 {
00024     // Initialize Direct2D resources.
00025     D2D1_FACTORY_OPTIONS options {};
00026
00027 #if defined(_DEBUG)
00028     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00029     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00030 #endif
00031
00032     // Initialize the Direct2D Factory.
00033     DX::ThrowIfFailed(
00034         D2D1CreateFactory(
00035             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00036             __uuidof(ID2D1Factory2),
00037             &options,
00038             &m_d2dFactory
00039             )
00040         );
00041
00042     // Initialize the DirectWrite Factory.
00043     DX::ThrowIfFailed(
00044         DWriteCreateFactory(
00045             DWRITE_FACTORY_TYPE_SHARED,
00046             __uuidof(IDWriteFactory2),
00047             &m_dwriteFactory
00048             )
00049         );
00050
00051     // Initialize the Windows Imaging Component (WIC) Factory.
00052     DX::ThrowIfFailed(
00053         CoCreateInstance(
00054             CLSID_WICImagingFactory2,
00055             nullptr,
00056             CLSCTX_INPROC_SERVER,
00057             IID_PPV_ARGS(&m_wicFactory)
00058             )
00059         );
00060 }
00061
00062 void DX::DeviceResources::SetHolographicSpace(HolographicSpace^ holographicSpace)
00063 {
00064     // Cache the holographic space. Used to re-initalize during device-lost scenarios.
00065     m_holographicSpace = holographicSpace;
00066
00067     InitializeUsingHolographicSpace();
00068 }
00069
00070 void DX::DeviceResources::InitializeUsingHolographicSpace()
00071 {
00072     // The holographic space might need to determine which adapter supports
00073     // holograms, in which case it will specify a non-zero PrimaryAdapterId.
00074     LUID id =
00075     {
00076         m_holographicSpace->PrimaryAdapterId.LowPart,
00077         m_holographicSpace->PrimaryAdapterId.HighPart
00078     };
00079
00080     // When a primary adapter ID is given to the app, the app should find
00081     // the corresponding DXGI adapter and use it to create Direct3D devices
00082     // and device contexts. Otherwise, there is no restriction on the DXGI
00083     // adapter the app can use.
00084     if ((id.HighPart != 0) || (id.LowPart != 0))
00085     {
00086         UINT createFlags = 0;
00087 #ifdef DEBUG
00088         if (DX::SdkLayersAvailable())
00089         {
00090             createFlags |= DXGI_CREATE_FACTORY_DEBUG;
00091         }
00092 #endif
00093         // Create the DXGI factory.
00094         ComPtr<IDXGIFactory1> dxgiFactory;
00095         DX::ThrowIfFailed(
00096             CreateDXGIFactory2(
00097                 createFlags,
00098                 IID_PPV_ARGS(&dxgiFactory)
00099                 )
00100             );
00101         ComPtr<IDXGIFactory4> dxgiFactory4;
00102         DX::ThrowIfFailed(dxgiFactory.As(&dxgiFactory4));
00103
00104         // Retrieve the adapter specified by the holographic space.
00105         DX::ThrowIfFailed(
00106             dxgiFactory4->EnumAdapterByLuid(
00107                 id,
00108                 IID_PPV_ARGS(&m_dxgiAdapter)
00109                 )
00110             );
00111     }
00112     else
00113     {
00114         m_dxgiAdapter.Reset();
00115     }
00116
00117     CreateDeviceResources();
00118
00119     m_holographicSpace->SetDirect3D11Device(m_d3dInteropDevice);
00120 }
00121
00122 // Configures the Direct3D device, and stores handles to it and the device context.
00123 void DX::DeviceResources::CreateDeviceResources()
00124 {
00125     // This flag adds support for surfaces with a different color channel ordering
00126     // than the API default. It is required for compatibility with Direct2D.
00127     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00128
00129 #if defined(_DEBUG)
00130     if (DX::SdkLayersAvailable())
00131     {
00132         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00133         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00134     }
00135 #endif
00136
00137     // This array defines the set of DirectX hardware feature levels this app will support.
00138     // Note the ordering should be preserved.
00139     // Note that HoloLens supports feature level 11.1. The HoloLens emulator is also capable
00140     // of running on graphics cards starting with feature level 10.0.
00141     D3D_FEATURE_LEVEL featureLevels [] =
00142     {
00143         D3D_FEATURE_LEVEL_12_1,
00144         D3D_FEATURE_LEVEL_12_0,
00145         D3D_FEATURE_LEVEL_11_1,
00146         D3D_FEATURE_LEVEL_11_0,
00147         D3D_FEATURE_LEVEL_10_1,
00148         D3D_FEATURE_LEVEL_10_0
00149     };
00150
00151     // Create the Direct3D 11 API device object and a corresponding context.
00152     ComPtr<ID3D11Device> device;
00153     ComPtr<ID3D11DeviceContext> context;
00154
00155     const D3D_DRIVER_TYPE driverType = m_dxgiAdapter == nullptr ? D3D_DRIVER_TYPE_HARDWARE : D3D_DRIVER_TYPE_UNKNOWN;
00156     const HRESULT hr = D3D11CreateDevice(
00157         m_dxgiAdapter.Get(),        // Either nullptr, or the primary adapter determined by Windows Holographic.
00158         driverType,                 // Create a device using the hardware graphics driver.
00159         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00160         creationFlags,              // Set debug and Direct2D compatibility flags.
00161         featureLevels,              // List of feature levels this app can support.
00162         ARRAYSIZE(featureLevels),   // Size of the list above.
00163         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00164         &device,                    // Returns the Direct3D device created.
00165         &m_d3dFeatureLevel,         // Returns feature level of device created.
00166         &context                    // Returns the device immediate context.
00167         );
00168
00169     if (FAILED(hr))
00170     {
00171         // If the initialization fails, fall back to the WARP device.
00172         // For more information on WARP, see:
00173         // http://go.microsoft.com/fwlink/?LinkId=286690
00174         DX::ThrowIfFailed(
00175             D3D11CreateDevice(
00176                 nullptr,              // Use the default DXGI adapter for WARP.
00177                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00178                 0,
00179                 creationFlags,
00180                 featureLevels,
00181                 ARRAYSIZE(featureLevels),
00182                 D3D11_SDK_VERSION,
00183                 &device,
00184                 &m_d3dFeatureLevel,
00185                 &context
00186                 )
00187             );
00188     }
00189
00190     // Store pointers to the Direct3D device and immediate context.
00191     DX::ThrowIfFailed(
00192         device.As(&m_d3dDevice)
00193         );
00194
00195     DX::ThrowIfFailed(
00196         context.As(&m_d3dContext)
00197         );
00198
00199     // Acquire the DXGI interface for the Direct3D device.
00200     ComPtr<IDXGIDevice3> dxgiDevice;
00201     DX::ThrowIfFailed(
00202         m_d3dDevice.As(&dxgiDevice)
00203         );
00204
00205     // Wrap the native device using a WinRT interop object.
00206     m_d3dInteropDevice = CreateDirect3DDevice(dxgiDevice.Get());
00207
00208     // Cache the DXGI adapter.
00209     // This is for the case of no preferred DXGI adapter, or fallback to WARP.
00210     ComPtr<IDXGIAdapter> dxgiAdapter;
00211     DX::ThrowIfFailed(
00212         dxgiDevice->GetAdapter(&dxgiAdapter)
00213         );
00214     DX::ThrowIfFailed(
00215         dxgiAdapter.As(&m_dxgiAdapter)
00216         );
00217
00218     // Check for device support for the optional feature that allows setting the render target array index from the vertex shader stage.
00219     D3D11_FEATURE_DATA_D3D11_OPTIONS3 options;
00220     m_d3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS3, &options, sizeof(options));
00221     if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer)
00222     {
00223         m_supportsVprt = true;
00224     }
00225 }
00226
00227 // Validates the back buffer for each HolographicCamera and recreates
00228 // resources for back buffers that have changed.
00229 // Locks the set of holographic camera resources until the function exits.
00230 void DX::DeviceResources::EnsureCameraResources(
00231     HolographicFrame^ frame,
00232     HolographicFramePrediction^ prediction)
00233 {
00234     UseHolographicCameraResources<void>([this, frame, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00235     {
00236         for (HolographicCameraPose^ pose : prediction->CameraPoses)
00237         {
00238             HolographicCameraRenderingParameters^ renderingParameters = frame->GetRenderingParameters(pose);
00239             CameraResources* pCameraResources = cameraResourceMap[pose->HolographicCamera->Id].get();
00240
00241             pCameraResources->CreateResourcesForBackBuffer(this, renderingParameters);
00242         }
00243     });
00244 }
00245
00246 // Prepares to allocate resources and adds resource views for a camera.
00247 // Locks the set of holographic camera resources until the function exits.
00248 void DX::DeviceResources::AddHolographicCamera(HolographicCamera^ camera)
00249 {
00250     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00251     {
00252         cameraResourceMap[camera->Id] = std::make_unique<CameraResources>(camera);
00253     });
00254 }
00255
00256 // Deallocates resources for a camera and removes the camera from the set.
00257 // Locks the set of holographic camera resources until the function exits.
00258 void DX::DeviceResources::RemoveHolographicCamera(HolographicCamera^ camera)
00259 {
00260     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00261     {
00262         CameraResources* pCameraResources = cameraResourceMap[camera->Id].get();
00263
00264         if (pCameraResources != nullptr)
00265         {
00266             pCameraResources->ReleaseResourcesForBackBuffer(this);
00267             cameraResourceMap.erase(camera->Id);
00268         }
00269     });
00270 }
00271
00272 // Recreate all device resources and set them back to the current state.
00273 // Locks the set of holographic camera resources until the function exits.
00274 void DX::DeviceResources::HandleDeviceLost()
00275 {
00276     if (m_deviceNotify != nullptr)
00277     {
00278         m_deviceNotify->OnDeviceLost();
00279     }
00280
00281     UseHolographicCameraResources<void>([this](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00282     {
00283         for (auto& pair : cameraResourceMap)
00284         {
00285             CameraResources* pCameraResources = pair.second.get();
00286             pCameraResources->ReleaseResourcesForBackBuffer(this);
00287         }
00288     });
00289
00290     InitializeUsingHolographicSpace();
00291
00292     if (m_deviceNotify != nullptr)
00293     {
00294         m_deviceNotify->OnDeviceRestored();
00295     }
00296 }
00297
00298 // Register our DeviceNotify to be informed on device lost and creation.
00299 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00300 {
00301     m_deviceNotify = deviceNotify;
00302 }
00303
00304 // Call this method when the app suspends. It provides a hint to the driver that the app
00305 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00306 void DX::DeviceResources::Trim()
00307 {
00308     m_d3dContext->ClearState();
00309
00310     ComPtr<IDXGIDevice3> dxgiDevice;
00311     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00312     dxgiDevice->Trim();
00313 }
00314
00315 // Present the contents of the swap chain to the screen.
00316 // Locks the set of holographic camera resources until the function exits.
00317 void DX::DeviceResources::Present(HolographicFrame^ frame)
00318 {
00319     // By default, this API waits for the frame to finish before it returns.
00320     // Holographic apps should wait for the previous frame to finish before
00321     // starting work on a new frame. This allows for better results from
00322     // holographic frame predictions.
00323     HolographicFramePresentResult presentResult = frame->PresentUsingCurrentPrediction();
00324
00325     HolographicFramePrediction^ prediction = frame->CurrentPrediction;
00326     UseHolographicCameraResources<void>([this, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00327     {
00328         for (auto cameraPose : prediction->CameraPoses)
00329         {
00330             // This represents the device-based resources for a HolographicCamera.
00331             DX::CameraResources* pCameraResources = cameraResourceMap[cameraPose->HolographicCamera->Id].get();
00332
00333             // Discard the contents of the render target.
00334             // This is a valid operation only when the existing contents will be
00335             // entirely overwritten. If dirty or scroll rects are used, this call
00336             // should be removed.
00337             m_d3dContext->DiscardView(pCameraResources->GetBackBufferRenderTargetView());
00338
00339             // Discard the contents of the depth stencil.
00340             m_d3dContext->DiscardView(pCameraResources->GetDepthStencilView());
00341         }
00342     });
00343
00344     // The PresentUsingCurrentPrediction API will detect when the graphics device
00345     // changes or becomes invalid. When this happens, it is considered a Direct3D
00346     // device lost scenario.
00347     if (presentResult == HolographicFramePresentResult::DeviceRemoved)
00348     {
00349         // The Direct3D device, context, and resources should be recreated.
00350         HandleDeviceLost();
00351     }
00352 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ISecureInterfaceLegacySignals Member List

This is the complete list of members for ISecureInterfaceLegacySignals, including all inherited members.
TextSentReceived ISecureInterfaceLegacySignals
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CMediaBufferWrapper Member List

This is the complete list of members for CMediaBufferWrapper, including all inherited members.
_nOffset | CMediaBufferWrapper | [private]
_pBuffer | CMediaBufferWrapper | [private]
_sp2DBuffer | CMediaBufferWrapper | [private]
_spBufferMarshal | CMediaBufferWrapper | [private]
_spMediaBuffer | CMediaBufferWrapper | [private]
Buffer(_Out_ BYTE **ppBuffer) | CMediaBufferWrapper |
CheckMarshal() | CMediaBufferWrapper | [protected]
CMediaBufferWrapper(void) | CMediaBufferWrapper |
CreateInstance(DWORD dwMaxLength, _Outptr_ IMediaBufferWrapper **ppMediaBufferWrapper) | CMediaBufferWrapper | [static]
CreateInstance(_In_ IMFMediaBuffer *pMediaBuffer, _Outptr_ IMediaBufferWrapper **ppMediaBufferWrapper) | CMediaBufferWrapper | [static]
DisconnectObject(DWORD) | CMediaBufferWrapper |
get_Capacity(UINT *pcbCapacity) | CMediaBufferWrapper |
get_Length(UINT *pcbLength) | CMediaBufferWrapper |
GetCurrentLength(DWORD *pcbCurrentLength) | CMediaBufferWrapper |
GetMarshalSizeMax(REFIID riid, _In_opt_ void *pv, DWORD dwDestContext, _Reserved_ void *pvDestContext, DWORD mshlflags, _Out_ DWORD *pcbSize) | CMediaBufferWrapper |
GetUnmarshalClass(REFIID riid, _In_opt_ void *pv, DWORD dwDestContext, _Reserved_ void *pvDestContext, DWORD mshlflags, _Out_ CLSID *pclsid) | CMediaBufferWrapper |
IFACEMETHOD_(IMFMediaBuffer *, GetMediaBuffer)() const | CMediaBufferWrapper | [inline]
IFACEMETHOD_(BYTE *, GetBuffer)() const | CMediaBufferWrapper | [inline]
IFACEMETHOD_(DWORD, GetOffset)() const | CMediaBufferWrapper | [inline]
InspectableClass(L"Microsoft.Samples.SimpleCommunication.Buffer", BaseTrust) | CMediaBufferWrapper | [private]
MarshalInterface(_In_ IStream *pStm, REFIID riid, _In_opt_ void *pv, DWORD dwDestContext, _Reserved_ void *pvDestContext, DWORD mshlflags) | CMediaBufferWrapper |
put_Length(UINT cbLength) | CMediaBufferWrapper |
ReleaseMarshalData(_In_ IStream *) | CMediaBufferWrapper |
Reset() | CMediaBufferWrapper |
RuntimeClassInitialize(IMFMediaBuffer *pMediaBuffer) | CMediaBufferWrapper |
SetCurrentLength(DWORD cbCurrentLength) | CMediaBufferWrapper |
SetOffset(DWORD nOffset) | CMediaBufferWrapper |
TrimLeft(DWORD cbSize) | CMediaBufferWrapper |
TrimRight(DWORD cbSize, _Out_ IMediaBufferWrapper **pWrapper) | CMediaBufferWrapper |
UnmarshalInterface(_In_ IStream *, _In_ REFIID, _Outptr_ void **) | CMediaBufferWrapper |
~CMediaBufferWrapper(void) | CMediaBufferWrapper |
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
ButtonUpdateBadgeGlyph_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cpp/Scenario3.xaml.h Source File

  • FileThumbnails
  • cpp

Scenario3.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario3.xaml.h
00014 // Declaration of the Scenario3 class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario3.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     [Windows::Foundation::Metadata::WebHostHidden]
00026     public ref class Scenario3 sealed
00027     {
00028     public:
00029         Scenario3();
00030
00031     protected:
00032         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00033
00034     private:
00035         MainPage^ rootPage;
00036
00037         void GetThumbnailButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Fri Nov 15 2024 22:18:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1 Member List

This is the complete list of members for Scenario1, including all inherited members.
m_scenario1ViewModel | Scenario1 | [private]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario1 | [inline, protected]
Scenario1() | Scenario1 | [inline]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-SPI/cpp/Scenario1_ReadData.xaml.cpp Source File

  • IoT-SPI
  • cpp

Scenario1_ReadData.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_ReadData.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace SDKTemplate;
00018
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Core;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Controls::Primitives;
00026 using namespace Windows::UI::Xaml::Data;
00027 using namespace Windows::UI::Xaml::Input;
00028 using namespace Windows::UI::Xaml::Media;
00029 using namespace Windows::UI::Xaml::Navigation;
00030 using namespace Windows::Devices::Spi;
00031 using namespace Windows::Devices::Enumeration;
00032 using namespace Windows::System::Threading;
00033 using namespace concurrency;
00034
00035 Scenario1_ReadData::Scenario1_ReadData()
00036 {
00037     InitializeComponent();
00038 }
00039
00040 void Scenario1_ReadData::OnNavigatedFrom(NavigationEventArgs^ e)
00041 {
00042     StopScenario();
00043 }
00044
00045 task<void> Scenario1_ReadData::StartScenarioAsync()
00046 {
00047     String^ spiDeviceSelector = SpiDevice::GetDeviceSelector();
00048     return create_task(DeviceInformation::FindAllAsync(spiDeviceSelector))
00049         .then([this](DeviceInformationCollection^ devices)
00050     {
00051         // 0 = Chip select line to use.
00052         auto ADXL345_Settings = ref new SpiConnectionSettings(0);
00053
00054         // 5MHz is the rated speed of the ADXL345 accelerometer.
00055         ADXL345_Settings->ClockFrequency = 5000000;
00056
00057         // The accelerometer expects an idle-high clock polarity.
00058         // We use Mode3 to set the clock polarity and phase to: CPOL = 1, CPHA = 1.
00059         ADXL345_Settings->Mode = SpiMode::Mode3;
00060
00061         // If this next line crashes with an OutOfBoundsException,
00062         // then the problem is that no SPI devices were found.
00063         //
00064         // If the next line crashes with Access Denied, then the problem is
00065         // that access to the SPI device (ADXL345) is denied.
00066         //
00067         // The call to FromIdAsync will also crash if the settings are invalid.
00068         return create_task(SpiDevice::FromIdAsync(devices->GetAt(0)->Id, ADXL345_Settings));
00069     }).then([this](SpiDevice^ spiDevice)
00070     {
00071         // spiDevice will be null if there is a sharing violation on the device.
00072         // This will result in a null reference exception a few lines later.
00073         adxl345Sensor = spiDevice;
00074
00075         //
00076         // Initialize the accelerometer:
00077         //
00078         // For this device, we create 2-byte write buffers:
00079         // The first byte is the register address we want to write to.
00080         // The second byte is the contents that we want to write to the register.
00081         //
00082         auto WriteBuf_DataFormat = ref new Array<byte>(2);
00083         WriteBuf_DataFormat[0] = 0x31; // 0x31 is address of data format register, 0x01 sets range to +- 4Gs
00084         WriteBuf_DataFormat[1] = 0x01; // 0x31 is address of data format register, 0x01 sets range to +- 4Gs
00085
00086         auto WriteBuf_PowerControl = ref new Array<byte>(2);
00087         WriteBuf_PowerControl[0] = 0x2D;    // 0x2D is address of power control register, 0x08 puts the accelerometer into measurement mode
00088         WriteBuf_PowerControl[1] = 0x08;    // 0x2D is address of power control register, 0x08 puts the accelerometer into measurement mode
00089
00090         // Write the register settings
00091         //
00092         // If this next line crashes with an access violation reading location 0x00000000,
00093         // then there was a sharing violation on the device.
00094         // (See comment earlier in this function.)
00095         //
00096         // If this next line crashes for some other reason, then there was
00097         // an error communicating with the device.
00098         adxl345Sensor->Write(WriteBuf_DataFormat);
00099         adxl345Sensor->Write(WriteBuf_PowerControl);
00100
00101         // Start the polling timer.
00102         timer = ref new DispatcherTimer();
00103         timer->Interval = TimeSpan{ 100 * 1000 * 10 }; // 100ms
00104         timerToken = timer->Tick += ref new EventHandler<Object^>(this, &Scenario1_ReadData::Timer_Tick);
00105         timer->Start();
00106     });
00107 }
00108
00109 void Scenario1_ReadData::StopScenario()
00110 {
00111     if (timer != nullptr)
00112     {
00113         timer->Tick -= timerToken;
00114         timer->Stop();
00115         timer = nullptr;
00116     }
00117
00118     // Release the SPI device.
00119     delete adxl345Sensor;
00120     adxl345Sensor = nullptr;
00121 }
00122
00123 void Scenario1_ReadData::StartStopScenario_Click(Object^ sender, RoutedEventArgs^ e)
00124 {
00125     if (timer != nullptr)
00126     {
00127         StopScenario();
00128         StartStopButton->Content = "Start";
00129         ScenarioControls->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00130     }
00131     else
00132     {
00133         StartStopButton->IsEnabled = false;
00134         StartScenarioAsync().then([this]()
00135         {
00136             StartStopButton->IsEnabled = true;
00137             StartStopButton->Content = "Stop";
00138             ScenarioControls->Visibility = Windows::UI::Xaml::Visibility::Visible;
00139         });
00140     }
00141 }
00142
00143 void Scenario1_ReadData::Timer_Tick(Object^ sender, Object^ e)
00144 {
00145     const byte ACCEL_SPI_RW_BIT = 0x80; // Bit used in SPI transactions to indicate read/write
00146     const byte ACCEL_SPI_MB_BIT = 0x40; // Bit used to indicate multi-byte SPI transactions
00147     const byte ACCEL_REG_X = 0x32;      // Address of the X Axis data register
00148     const int ACCEL_RES = 1024;         // The ADXL345 has 10 bit resolution giving 1024 unique values
00149     const int ACCEL_DYN_RANGE_G = 8;    // The ADXL345 had a total dynamic range of 8G, since we're configuring it to +-4G
00150     const int UNITS_PER_G = ACCEL_RES / ACCEL_DYN_RANGE_G;  // Ratio of raw int values to G units
00151
00152     auto ReadBuf = ref new Array<byte>(6 + 1);      // Read buffer of size 6 bytes (2 bytes * 3 axes) + 1 byte padding
00153     auto RegAddrBuf = ref new Array<byte>(1 + 6);   // Register address buffer of size 1 byte + 6 bytes padding
00154
00155     // Register address we want to read from with read and multi-byte bit set.
00156     RegAddrBuf[0] = ACCEL_REG_X | ACCEL_SPI_RW_BIT | ACCEL_SPI_MB_BIT;
00157
00158     // If this next line crashes, then there was an error communicating with the device.
00159
00160     adxl345Sensor->TransferFullDuplex(RegAddrBuf, ReadBuf);
00161
00162     // In order to get the raw 16-bit data values, we need to concatenate two 8-bit bytes for each axis.
00163     short AccelerationRawX = (ReadBuf[2] << 8) | ReadBuf[1];
00164     short AccelerationRawY = (ReadBuf[4] << 8) | ReadBuf[3];
00165     short AccelerationRawZ = (ReadBuf[6] << 8) | ReadBuf[5];
00166
00167     // Convert raw values to G's and display them.
00168     X->Text = ((double)AccelerationRawX / UNITS_PER_G).ToString();
00169     Y->Text = ((double)AccelerationRawY / UNITS_PER_G).ToString();
00170     Z->Text = ((double)AccelerationRawZ / UNITS_PER_G).ToString();
00171 }
Generated on Fri Nov 15 2024 22:20:03 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LockScreenApps/cppwinrt/Scenario2_Notifications.h Source File

  • LockScreenApps
  • cppwinrt

Scenario2_Notifications.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "Scenario2_Notifications.g.h"
00014 #include "MainPage.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_Notifications : Scenario2_NotificationsT<Scenario2_Notifications>
00019     {
00020         Scenario2_Notifications();
00021
00022         void ClearBadge_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023         void SendBadge_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024         void SendBadgeWithStringManipulation_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00025         void SendTile_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026         void SendTileWithStringManipulation_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         void ClearTile_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028
00029     private:
00030         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00031     };
00032 }
00033
00034 namespace winrt::SDKTemplate::factory_implementation
00035 {
00036     struct Scenario2_Notifications : Scenario2_NotificationsT<Scenario2_Notifications, implementation::Scenario2_Notifications>
00037     {
00038     };
00039 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/BackgroundTasks/BadgeNotificationHistoryChangedTriggerTask.cs Source File

  • Notifications
  • cs
  • BackgroundTasks

BadgeNotificationHistoryChangedTriggerTask.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using Windows.ApplicationModel.Background;
00004 using Windows.Data.Xml.Dom;
00005 using Windows.UI.Notifications;
00006
00007 namespace BackgroundTasks
00008 {
00009     public sealed class BadgeNotificationHistoryChangedTriggerTask : IBackgroundTask
00010     {
00011         public void Run(IBackgroundTaskInstance taskInstance)
00012         {
00013             var details = taskInstance.TriggerDetails as ToastNotificationHistoryChangedTriggerDetail;
00014             if (details == null)
00015                 return;
00016
00017             //Update the badge by taking the counter and deleting one
00018             IReadOnlyList<ToastNotification> TNList = ToastNotificationManager.History.GetHistory();
00019
00020             BadgeNumericNotificationContent badgeContent = new BadgeNumericNotificationContent((uint)TNList.Count);
00021
00022             // Send the notification to the application’s tile. Name taken from ScenarioPages.Toasts.HistoryChangedTrigger.BadgeControl
00023             BadgeUpdateManager.CreateBadgeUpdaterForSecondaryTile("ScenarioBadgeControl").Update(badgeContent.CreateNotification());
00024
00025             // We send back the change type, the UI listens to the progress and parses the change type
00026             taskInstance.Progress = (uint)details.ChangeType;
00027         }
00028     }
00029     /// <summary>
00030     /// Notification content object to display a number on a tile's badge.
00031     /// </summary>
00032     public sealed class BadgeNumericNotificationContent
00033     {
00034
00035         private uint m_Number = 0;
00036         /// <summary>
00037         /// Constructor to create a numeric badge content object with a number.
00038         /// </summary>
00039         /// <param name="number">
00040         /// The number that will appear on the badge.  If the number is 0, the badge
00041         /// will be removed.  The largest value that will appear on the badge is 99.
00042         /// Numbers greater than 99 are allowed, but will be displayed as "99+".
00043         /// </param>
00044         public BadgeNumericNotificationContent(uint number)
00045         {
00046             m_Number = number;
00047         }
00048
00049         /// <summary>
00050         /// The number that will appear on the badge.  If the number is 0, the badge
00051         /// will be removed.  The largest value that will appear on the badge is 99.
00052         /// Numbers greater than 99 are allowed, but will be displayed as "99+".
00053         /// </summary>
00054         public uint Number
00055         {
00056             get { return m_Number; }
00057             set { m_Number = value; }
00058         }
00059
00060         /// <summary>
00061         /// Retrieves the notification Xml content as a string.
00062         /// </summary>
00063         /// <returns>The notification Xml content as a string.</returns>
00064         public string GetContent()
00065         {
00066             return String.Format("<badge version='{0}' value='{1}'/>", Util.NOTIFICATION_CONTENT_VERSION, m_Number);
00067         }
00068
00069         /// <summary>
00070         /// Retrieves the notification Xml content as a string.
00071         /// </summary>
00072         /// <returns>The notification Xml content as a string.</returns>
00073         public override string ToString()
00074         {
00075             return GetContent();
00076         }
00077         /// <summary>
00078         /// Creates a WinRT BadgeNotification object based on the content.
00079         /// </summary>
00080         /// <returns>A WinRT BadgeNotification object based on the content.</returns>
00081         public BadgeNotification CreateNotification()
00082         {
00083             XmlDocument xmlDoc = new XmlDocument();
00084             xmlDoc.LoadXml(GetContent());
00085             return new BadgeNotification(xmlDoc);
00086         }
00087     }
00088     internal static class Util
00089     {
00090         public const int NOTIFICATION_CONTENT_VERSION = 1;
00091
00092         public static string HttpEncode(string value)
00093         {
00094             return value.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");
00095         }
00096     }
00097 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SoundEffect Member List

This is the complete list of members for SoundEffect, including all inherited members.
Initialize(_In_ IXAudio2 *masteringEngine, _In_ WAVEFORMATEX *sourceFormat, _In_ std::vector< byte > const &soundData) | SoundEffect |
m_audioAvailable | SoundEffect | [private]
m_soundData | SoundEffect | [private]
m_sourceVoice | SoundEffect | [private]
PlaySound(_In_ float volume) | SoundEffect |
SoundEffect() | SoundEffect |
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Vector2< T > Member List

This is the complete list of members for Vector2< T >, including all inherited members.
color | Vector2< T > |
coord | Vector2< T > |
g | Vector2< T > |
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
operator[](unsigned int index) | Vector2< T > | [inline]
r | Vector2< T > |
textcoord | Vector2< T > |
u | Vector2< T > |
v | Vector2< T > |
Vector2(T _x=0, T _y=0) | Vector2< T > | [inline]
Vector2(T _x=0, T _y=0) | Vector2< T > | [inline]
Vector2(T _x=0, T _y=0) | Vector2< T > | [inline]
x | Vector2< T > |
y | Vector2< T > |
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SplashScreen/cs/SampleConfiguration.cs Source File

  • SplashScreen
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Foundation;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Splash screen C# sample";
00022         internal bool Dismissed;
00023         internal Rect SplashImageRect;
00024
00025         public List<Scenario> scenarios = new List<Scenario>
00026         {
00027             new Scenario() { Title = "Registering for dismissal notifications", ClassType = typeof(SplashScreenSample.Scenario1) },
00028             new Scenario() { Title = "Extending the splash screen",             ClassType = typeof(SplashScreenSample.Scenario2) },
00029         };
00030
00031         public void SetExtendedSplashInfo(Rect splashRect, bool dismissStat)
00032         {
00033             SplashImageRect = splashRect;
00034             Dismissed = dismissStat;
00035         }
00036     }
00037
00038     public class Scenario
00039     {
00040         public string Title { get; set; }
00041
00042         public Type ClassType { get; set; }
00043
00044         public override string ToString()
00045         {
00046             return Title;
00047         }
00048     }
00049
00050     public class MainPageSizeChangedEventArgs : EventArgs
00051     {
00052         private double width;
00053
00054         public double Width
00055         {
00056             get { return width; }
00057             set { width = value; }
00058         }
00059     }
00060
00061     public enum NotifyType
00062     {
00063         StatusMessage,
00064         ErrorMessage
00065     };
00066 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothLE/cs/DispatcherTaskExtensions.cs Source File

  • BluetoothLE
  • cs

DispatcherTaskExtensions.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using Windows.UI.Core;
00007
00008 namespace SDKTemplate
00009 {
00010     /// <summary>
00011     /// Helper class used to run functions on the UI thread
00012     /// </summary>
00013     public static class DispatcherService
00014     {
00015         /// <summary>
00016         /// Helper function to run task on UI thread
00017         /// </summary>
00018         /// <typeparam name="T">return value of task</typeparam>
00019         /// <param name="dispatcher"></param>
00020         /// <param name="func"></param>
00021         /// <param name="priority"></param>
00022         /// <returns>UI thread task</returns>
00023         public static async Task<T> RunTaskAsync<T>(
00024             this CoreDispatcher dispatcher,
00025             Func<Task<T>> func,
00026             CoreDispatcherPriority priority = CoreDispatcherPriority.Normal)
00027         {
00028             var taskCompletionSource = new TaskCompletionSource<T>();
00029
00030             await dispatcher.RunAsync(
00031                 priority,
00032                 async () =>
00033                 {
00034                     try
00035                     {
00036                         taskCompletionSource.SetResult(await func());
00037                     }
00038                     catch (Exception ex)
00039                     {
00040                         taskCompletionSource.SetException(ex);
00041                     }
00042                 });
00043             return await taskCompletionSource.Task;
00044         }
00045
00046         //// There is no TaskCompletionSource<void> so we use a bool that we throw away.
00047
00048         /// <summary>
00049         /// Helper function to run task on UI thread
00050         /// </summary>
00051         /// <param name="dispatcher"></param>
00052         /// <param name="func"></param>
00053         /// <param name="priority"></param>
00054         /// <returns>UI thread task</returns>
00055         public static async Task RunTaskAsync(
00056             this CoreDispatcher dispatcher,
00057             Func<Task> func,
00058             CoreDispatcherPriority priority = CoreDispatcherPriority.Normal) =>
00059             await RunTaskAsync(
00060                 dispatcher,
00061                 async () =>
00062                 {
00063                     await func();
00064                     return false;
00065                 },
00066                 priority);
00067     }
00068 }
Generated on Fri Nov 15 2024 22:18:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cppwinrt/Scenario2.h Source File

  • FileThumbnails
  • cppwinrt

Scenario2.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario2 : Scenario2T<Scenario2>
00020     {
00021         Scenario2();
00022         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00023         fire_and_forget GetThumbnailButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024
00025     private:
00026         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario2 : Scenario2T<Scenario2, implementation::Scenario2>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:19:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SplashScreen/cs/Scenario1_SplashScreenDismiss.xaml.cs Source File

  • SplashScreen
  • cs

Scenario1_SplashScreenDismiss.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using SDKTemplate;
00015 using System;
00016
00017 namespace SplashScreenSample
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     public sealed partial class Scenario1 : Page
00023     {
00024         public Scenario1()
00025         {
00026             this.InitializeComponent();
00027         }
00028
00029         protected override void OnNavigatedTo(NavigationEventArgs e)
00030         {
00031             if (MainPage.Current.Dismissed)
00032             {
00033                 OutputTextBlock.Text = "Received the splash screen dismissal event.";
00034             }
00035             else
00036             {
00037                 OutputTextBlock.Text = "The application didn't receive the splash screen dismissal event.";
00038             }
00039         }
00040     }
00041 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cppwinrt/Project.idl Source File

  • BarcodeScanner
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_BasicFunctionality : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_BasicFunctionality();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_MultipleScanners : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_MultipleScanners();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3_ActiveSymbologies : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3_ActiveSymbologies();
00030     }
00031
00032     [Windows.UI.Xaml.Data.Bindable]
00033     runtimeclass SymbologyListEntry
00034     {
00035         SymbologyListEntry(UInt32 symbologyId);
00036         SymbologyListEntry(UInt32 symbologyId, Boolean symbologyEnabled);
00037
00038         UInt32 Id{ get; };
00039         Boolean IsEnabled;
00040         String Name{ get; };
00041     }
00042
00043     [default_interface]
00044     runtimeclass Scenario4_SymbologyAttributes : Windows.UI.Xaml.Controls.Page
00045     {
00046         Scenario4_SymbologyAttributes();
00047     }
00048
00049     runtimeclass Scenario5_DisplayingBarcodePreview :
00050         Windows.UI.Xaml.Controls.Page, Windows.UI.Xaml.Data.INotifyPropertyChanged
00051     {
00052         Scenario5_DisplayingBarcodePreview();
00053
00054         Boolean IsScannerClaimed;
00055         Boolean ScannerSupportsPreview;
00056         Boolean IsPreviewing;
00057         Boolean SoftwareTriggerStarted;
00058     }
00059
00060     static runtimeclass BindingHelpers
00061     {
00062         static Windows.UI.Xaml.Visibility CollapsedIf(Boolean value);
00063         static Boolean Not(Boolean value);
00064     }
00065
00066     runtimeclass BarcodeScannerInfo
00067     {
00068         BarcodeScannerInfo(String name, String deviceId);
00069
00070         String Name{ get; };
00071         String DeviceId{ get; };
00072     }
00073 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationData/cppwinrt/Scenario2_Settings.cpp Source File

  • ApplicationData
  • cppwinrt

Scenario2_Settings.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Settings.h"
00014 #include "Scenario2_Settings.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Storage;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Navigation;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     Scenario2_Settings::Scenario2_Settings()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     // Guidance for Settings.
00030     //
00031     // Settings are a convenient way of storing small pieces of configuration data
00032     // for your application.
00033     //
00034     // There are two storage containers for settings: Local and Roaming. However,
00035     // Roaming settings no longer roam, so they are functionally equivalent to Local.
00036     //
00037     // Care should be taken to guard against an excessive volume of data being
00038     // stored in settings.  Settings are not intended to be used as a database.
00039     // Large data sets will take longer to load from disk during your application's
00040     // launch.
00041
00042     // This sample illustrates reading and writing from a local setting.
00043
00044     void Scenario2_Settings::WriteSetting_Click(IInspectable const&, RoutedEventArgs const&)
00045     {
00046         hstring toSet = L"Hello World";
00047         localSettings.Values().Insert(SettingName, box_value(toSet)); // example value
00048
00049         DisplayOutput();
00050     }
00051
00052     void Scenario2_Settings::DeleteSetting_Click(IInspectable const&, RoutedEventArgs const&)
00053     {
00054         localSettings.Values().Remove(SettingName);
00055
00056         DisplayOutput();
00057     }
00058
00059     void Scenario2_Settings::DisplayOutput()
00060     {
00061         auto stringValue = localSettings.Values().TryLookup(SettingName).try_as<hstring>();
00062
00063         OutputTextBlock().Text(L"Setting: " + (stringValue.has_value() ? L"\"" + stringValue.value() + L"\"" : L"<empty>"));
00064     }
00065
00066     void Scenario2_Settings::OnNavigatedTo(NavigationEventArgs const&)
00067     {
00068         DisplayOutput();
00069     }
00070 }
00071
Generated on Fri Nov 15 2024 22:17:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Projection/cpp/pch.cpp Source File

  • Projection
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SemanticTextQuery/cpp/SampleConfiguration.h Source File

  • SemanticTextQuery
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Semantic text query C++ sample";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
00039
00040 namespace SDKTemplate
00041 {
00042     void HighlightRanges(Windows::UI::Xaml::Controls::TextBlock^ tb,  Platform::String^ strText, Windows::Foundation::Collections::IVectorView<Windows::Data::Text::TextSegment>^ ranges);
00043 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cs/Scenario1_Create.xaml.cs Source File

  • Playlists
  • cs

Scenario1_Create.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Media.Playlists;
00015 using Windows.Storage;
00016 using Windows.Storage.Pickers;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario1_Create : Page
00024     {
00025         private MainPage rootPage = MainPage.Current;
00026
00027         public Scenario1_Create()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         /// <summary>
00033         /// Creates a playlist with the audio picked by the user in the FilePicker
00034         /// </summary>
00035         /// <param name="sender"></param>
00036         /// <param name="e"></param>
00037         async private void PickAudioButton_Click(object sender, RoutedEventArgs e)
00038         {
00039             FileOpenPicker picker = MainPage.CreateFilePicker(MainPage.audioExtensions);
00040             IReadOnlyList<StorageFile> files = await picker.PickMultipleFilesAsync();
00041
00042             if (files.Count > 0)
00043             {
00044                 Playlist playlist = new Playlist();
00045
00046                 foreach (StorageFile file in files)
00047                 {
00048                     playlist.Files.Add(file);
00049                 }
00050
00051                 StorageFolder folder = KnownFolders.MusicLibrary;
00052                 string name = "Sample";
00053                 NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting;
00054                 PlaylistFormat format = PlaylistFormat.WindowsMedia;
00055
00056                 try
00057                 {
00058                     StorageFile savedFile = await playlist.SaveAsAsync(folder, name, collisionOption, format);
00059                     this.rootPage.NotifyUser(savedFile.Name + " was created and saved with " + files.Count + " files.", NotifyType.StatusMessage);
00060                 }
00061                 catch (Exception error)
00062                 {
00063                     rootPage.NotifyUser(error.Message, NotifyType.ErrorMessage);
00064                 }
00065             }
00066             else
00067             {
00068                 rootPage.NotifyUser("No files picked.", NotifyType.ErrorMessage);
00069             }
00070         }
00071     }
00072 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cppwinrt/Scenario4_ChangeSystemGroup.h Source File

  • JumpList
  • cppwinrt

Scenario4_ChangeSystemGroup.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_ChangeSystemGroup.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario4_ChangeSystemGroup : Scenario4_ChangeSystemGroupT<Scenario4_ChangeSystemGroup>
00019     {
00020         Scenario4_ChangeSystemGroup();
00021
00022         fire_and_forget OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00023
00024         // These methods are public so they can be called by binding.
00025         fire_and_forget SystemGroup_Recent_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026         fire_and_forget SystemGroup_Frequent_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         fire_and_forget SystemGroup_None_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         fire_and_forget PrepareSampleFiles_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029     };
00030 }
00031
00032 namespace winrt::SDKTemplate::factory_implementation
00033 {
00034     struct Scenario4_ChangeSystemGroup : Scenario4_ChangeSystemGroupT<Scenario4_ChangeSystemGroup, implementation::Scenario4_ChangeSystemGroup>
00035     {
00036     };
00037 }
Generated on Fri Nov 15 2024 22:20:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PosPrinter/cpp/Scenario2_PrintReceipt.xaml.cpp Source File

  • PosPrinter
  • cpp

Scenario2_PrintReceipt.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_PrintReceipt.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Devices::PointOfService;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Graphics::Imaging;
00022 using namespace Windows::Storage;
00023 using namespace Windows::Storage::Streams;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026
00027 Scenario2_PrintReceipt::Scenario2_PrintReceipt()
00028 {
00029     InitializeComponent();
00030 }
00031
00032 bool Scenario2_PrintReceipt::IsPrinterClaimed()
00033 {
00034     if (rootPage->ClaimedPrinter != nullptr)
00035     {
00036         rootPage->NotifyUser("", NotifyType::StatusMessage);
00037         return true;
00038     }
00039     else
00040     {
00041         rootPage->NotifyUser("Use scenario 1 to find, claim, and enable a receipt printer.", NotifyType::ErrorMessage);
00042         return false;
00043     }
00044 }
00045
00046 task<bool> Scenario2_PrintReceipt::ExecuteJobAndReportResultAsync(ReceiptPrintJob^ job)
00047 {
00048     return create_task(job->ExecuteAsync()).then([this](bool success)
00049     {
00050         if (success)
00051         {
00052             rootPage->NotifyUser("Printing complete.", NotifyType::StatusMessage);
00053         }
00054         else
00055         {
00056             String^ reason;
00057             ClaimedReceiptPrinter^ receipt = rootPage->ClaimedPrinter->Receipt;
00058             if (receipt->IsCartridgeEmpty)
00059             {
00060                 reason = "Printer is out of ink. Please replace cartridge.";
00061             }
00062             else if (receipt->IsCartridgeRemoved)
00063             {
00064                 reason = "Printer cartridge is missing. Please replace cartridge.";
00065             }
00066             else if (receipt->IsCoverOpen)
00067             {
00068                 reason = "Printer cover is open. Please close it.";
00069             }
00070             else if (receipt->IsHeadCleaning)
00071             {
00072                 reason = "Printer is currently cleaning the cartridge. Please wait until cleaning has completed.";
00073             }
00074             else if (receipt->IsPaperEmpty)
00075             {
00076                 reason = "Printer is out of paper. Please insert a new roll.";
00077             }
00078             else
00079             {
00080                 reason = "Unable to print.";
00081             }
00082             rootPage->NotifyUser(reason, NotifyType::ErrorMessage);
00083         }
00084         return success;
00085     });
00086 }
00087
00088 #pragma region Print a single line of text
00089 void Scenario2_PrintReceipt::PrintLine_Click()
00090 {
00091     if (!IsPrinterClaimed())
00092     {
00093         return;
00094     }
00095
00096     ReceiptPrintJob^ job = rootPage->ClaimedPrinter->Receipt->CreateJob();
00097     job->PrintLine(PrintLineTextBox->Text);
00098
00099     ExecuteJobAndReportResultAsync(job);
00100 }
00101 #pragma endregion
00102
00103 #pragma region Print a sample receipt
00104 void Scenario2_PrintReceipt::PrintReceipt_Click()
00105 {
00106     if (!IsPrinterClaimed())
00107     {
00108         return;
00109     }
00110
00111     String^ receiptString =
00112         "======================\n" +
00113         "|   Sample Header    |\n" +
00114         "======================\n" +
00115         "Item             Price\n" +
00116         "----------------------\n" +
00117         "Books            10.40\n" +
00118         "Games             9.60\n" +
00119         "----------------------\n" +
00120         "Total            20.00\n";
00121
00122     rootPage->NotifyUser("Printing receipt...", NotifyType::StatusMessage);
00123
00124     // The job consists of two receipts, one for the merchant and one
00125     // for the customer.
00126     ReceiptPrintJob^ job = rootPage->ClaimedPrinter->Receipt->CreateJob();
00127     PrintLineFeedAndCutPaper(job, receiptString + GetMerchantFooter());
00128     PrintLineFeedAndCutPaper(job, receiptString + GetCustomerFooter());
00129
00130     ExecuteJobAndReportResultAsync(job);
00131 }
00132
00133 Platform::String^ Scenario2_PrintReceipt::GetMerchantFooter()
00134 {
00135     return
00136         "\n" +
00137         "______________________\n" +
00138         "Signature\n" +
00139         "\n" +
00140         "Merchant Copy\n";
00141 }
00142
00143 Platform::String^ Scenario2_PrintReceipt::GetCustomerFooter()
00144 {
00145     return
00146         "\n" +
00147         "Customer Copy\n";
00148 }
00149
00150 // Cut the paper after printing enough blank lines to clear the paper cutter.
00151 void Scenario2_PrintReceipt::PrintLineFeedAndCutPaper(ReceiptPrintJob^ job, String^ receipt)
00152 {
00153     // Passing a multi-line string to the Print method results in
00154     // smoother paper feeding than sending multiple single-line strings
00155     // to PrintLine.
00156     String^ feedString = "";
00157     for (unsigned int n = 0; n < rootPage->ClaimedPrinter->Receipt->LinesToPaperCut; n++)
00158     {
00159         feedString += "\n";
00160     }
00161     job->Print(receipt + feedString);
00162     if (rootPage->Printer->Capabilities->Receipt->CanCutPaper)
00163     {
00164         job->CutPaper();
00165     }
00166 }
00167 #pragma endregion
00168
00169 #pragma region Print a bitmap
00170 void Scenario2_PrintReceipt::PrintBitmap_Click()
00171 {
00172     if (!IsPrinterClaimed())
00173     {
00174         return;
00175     }
00176
00177     LoadLogoBitmapAsync().then([this](BitmapFrame^ logoFrame)
00178     {
00179         ReceiptPrintJob^ job = rootPage->ClaimedPrinter->Receipt->CreateJob();
00180         rootPage->ClaimedPrinter->Receipt->IsLetterQuality = true;
00181         job->PrintBitmap(logoFrame, PosPrinterAlignment::Center);
00182         return ExecuteJobAndReportResultAsync(job);
00183     });
00184 }
00185
00186 task<BitmapFrame^> Scenario2_PrintReceipt::LoadLogoBitmapAsync()
00187 {
00188     Uri^ uri = ref new Uri("ms-appx:///Assets/coffee-logo.png");
00189     return create_task(StorageFile::GetFileFromApplicationUriAsync(uri)).then([](StorageFile^ file)
00190     {
00191         return create_task(file->OpenReadAsync());
00192     }).then([](IRandomAccessStream^ readStream)
00193     {
00194         return create_task(BitmapDecoder::CreateAsync(readStream));
00195     }).then([](BitmapDecoder^ decoder)
00196     {
00197         return create_task(decoder->GetFrameAsync(0));
00198     });
00199 }
00200 #pragma endregion
00201
00202 #pragma region Print a barcode
00203 void Scenario2_PrintReceipt::PrintBarcode_Click()
00204 {
00205     if (!IsPrinterClaimed())
00206     {
00207         return;
00208     }
00209
00210     rootPage->ClaimedPrinter->Receipt->IsLetterQuality = true;
00211     ReceiptPrintJob^ job = rootPage->ClaimedPrinter->Receipt->CreateJob();
00212     job->PrintBarcode(BarcodeText->Text, BarcodeSymbologies::Upca, 60, 3, PosPrinterBarcodeTextPosition::Below, PosPrinterAlignment::Center);
00213     ExecuteJobAndReportResultAsync(job);
00214 }
00215 #pragma endregion
Generated on Fri Nov 15 2024 22:20:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cpp/Common/CameraResources.h Source File

  • 360VideoPlayback
  • cpp
  • Common

CameraResources.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 namespace DX
00004 {
00005     class DeviceResources;
00006
00007     // Constant buffer used to send the view-projection matrices to the shader pipeline.
00008     struct ViewProjectionConstantBuffer
00009     {
00010         DirectX::XMFLOAT4X4 viewProjection[2];
00011     };
00012
00013     // Assert that the constant buffer remains 16-byte aligned (best practice).
00014     static_assert((sizeof(ViewProjectionConstantBuffer) % (sizeof(float) * 4)) == 0, "ViewProjection constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00015
00016     // Manages DirectX device resources that are specific to a holographic camera, such as the
00017     // back buffer, ViewProjection constant buffer, and viewport.
00018     class CameraResources
00019     {
00020     public:
00021         CameraResources(Windows::Graphics::Holographic::HolographicCamera^ holographicCamera);
00022
00023         void CreateResourcesForBackBuffer(
00024             DX::DeviceResources* pDeviceResources,
00025             Windows::Graphics::Holographic::HolographicCameraRenderingParameters^ cameraParameters
00026             );
00027         void ReleaseResourcesForBackBuffer(
00028             DX::DeviceResources* pDeviceResources
00029             );
00030
00031         void UpdateViewProjectionBuffer(
00032             std::shared_ptr<DX::DeviceResources> deviceResources,
00033             Windows::Graphics::Holographic::HolographicCameraPose^ cameraPose,
00034             Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem);
00035
00036         bool AttachViewProjectionBuffer(
00037             std::shared_ptr<DX::DeviceResources> deviceResources);
00038
00039         // Direct3D device resources.
00040         ID3D11RenderTargetView* GetBackBufferRenderTargetView()     const { return m_d3dRenderTargetView.Get();     }
00041         ID3D11DepthStencilView* GetDepthStencilView()               const { return m_d3dDepthStencilView.Get();     }
00042         ID3D11Texture2D*        GetBackBufferTexture2D()            const { return m_d3dBackBuffer.Get();           }
00043         D3D11_VIEWPORT          GetViewport()                       const { return m_d3dViewport;                   }
00044         DXGI_FORMAT             GetBackBufferDXGIFormat()           const { return m_dxgiFormat;                    }
00045
00046         // Render target properties.
00047         Windows::Foundation::Size GetRenderTargetSize()             const { return m_d3dRenderTargetSize;           }
00048         bool                    IsRenderingStereoscopic()           const { return m_isStereo;                      }
00049
00050         // The holographic camera these resources are for.
00051         Windows::Graphics::Holographic::HolographicCamera^ GetHolographicCamera() const { return m_holographicCamera; }
00052
00053     private:
00054         // Direct3D rendering objects. Required for 3D.
00055         Microsoft::WRL::ComPtr<ID3D11RenderTargetView>      m_d3dRenderTargetView;
00056         Microsoft::WRL::ComPtr<ID3D11DepthStencilView>      m_d3dDepthStencilView;
00057         Microsoft::WRL::ComPtr<ID3D11Texture2D>             m_d3dBackBuffer;
00058
00059         // Device resource to store view and projection matrices.
00060         Microsoft::WRL::ComPtr<ID3D11Buffer>                m_viewProjectionConstantBuffer;
00061
00062         // Direct3D rendering properties.
00063         DXGI_FORMAT                                         m_dxgiFormat;
00064         Windows::Foundation::Size                           m_d3dRenderTargetSize;
00065         D3D11_VIEWPORT                                      m_d3dViewport;
00066
00067         // Indicates whether the camera supports stereoscopic rendering.
00068         bool                                                m_isStereo = false;
00069
00070         // Indicates whether this camera has a pending frame.
00071         bool                                                m_framePending = false;
00072
00073         // Pointer to the holographic camera these resources are for.
00074         Windows::Graphics::Holographic::HolographicCamera^  m_holographicCamera = nullptr;
00075     };
00076 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileSearch/cppwinrt/Scenario1.h Source File

  • FileSearch
  • cppwinrt

Scenario1.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1 : Scenario1T<Scenario1>
00020     {
00021         Scenario1();
00022         fire_and_forget SearchButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00023
00024     private:
00025         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00026     };
00027 }
00028
00029 namespace winrt::SDKTemplate::factory_implementation
00030 {
00031     struct Scenario1 : Scenario1T<Scenario1, implementation::Scenario1>
00032     {
00033     };
00034 }
Generated on Fri Nov 15 2024 22:19:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlContextMenu/cpp/SampleConfiguration.h Source File

  • XamlContextMenu
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Resize app view";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Program Member List

This is the complete list of members for Program, including all inherited members.
Main() Program [inline, private, static]
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_ChatServer Member List

This is the complete list of members for Scenario2_ChatServer, including all inherited members.
Disconnect() | Scenario2_ChatServer | [inline, private]
DisconnectButton_Click(object sender, RoutedEventArgs e) | Scenario2_ChatServer | [inline, private]
InitializeRfcommServer() | Scenario2_ChatServer | [inline, private]
InitializeServiceSdpAttributes(RfcommServiceProvider rfcommProvider) | Scenario2_ChatServer | [inline, private]
KeyboardKey_Pressed(object sender, KeyRoutedEventArgs e) | Scenario2_ChatServer | [inline]
ListenButton_Click(object sender, RoutedEventArgs e) | Scenario2_ChatServer | [inline, private]
OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) | Scenario2_ChatServer | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_ChatServer | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_ChatServer | [inline, protected]
rfcommProvider | Scenario2_ChatServer | [private]
rootPage | Scenario2_ChatServer | [private]
Scenario2_ChatServer() | Scenario2_ChatServer | [inline]
SendButton_Click(object sender, RoutedEventArgs e) | Scenario2_ChatServer | [inline, private]
SendMessage() | Scenario2_ChatServer | [inline, private]
socket | Scenario2_ChatServer | [private]
socketListener | Scenario2_ChatServer | [private]
writer | Scenario2_ChatServer | [private]
Generated on Fri Nov 15 2024 22:23:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HistoryAndRoaming Member List

This is the complete list of members for HistoryAndRoaming, including all inherited members.
CheckHistoryAndRoaming() | HistoryAndRoaming | [private]
CopyButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | HistoryAndRoaming |
HistoryAndRoaming() | HistoryAndRoaming |
historyEnabledToken | HistoryAndRoaming | [private]
OnHistoryEnabledChanged(Windows::Foundation::IInspectable const &sender, Windows::Foundation::IInspectable const &e) | HistoryAndRoaming | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | HistoryAndRoaming |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | HistoryAndRoaming |
OnRoamingEnabledChanged(Windows::Foundation::IInspectable const &sender, Windows::Foundation::IInspectable const &e) | HistoryAndRoaming | [private]
roamingEnabledToken | HistoryAndRoaming | [private]
SelectVisibleElement(Windows::UI::Xaml::UIElement const &ifTrue, Windows::UI::Xaml::UIElement const &ifFalse, bool value) | HistoryAndRoaming | [private, static]
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/ToneSampleGenerator.cpp Source File

  • WindowsAudioSession
  • cpp

ToneSampleGenerator.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // ToneSampleGenerator.h
00013 //
00014
00015 #include "pch.h"
00016 #include "ToneSampleGenerator.h"
00017
00018 using namespace SDKSample::WASAPIAudio;
00019
00020 const int TONE_DURATION_SEC = 30;
00021 const double TONE_AMPLITUDE = 0.5;     // Scalar value, should be between 0.0 - 1.0
00022
00023 //
00024 //  Convert from double to float, byte, short or int32.
00025 //
00026 template<>
00027 float Convert<float>(double Value)
00028 {
00029     return (float)(Value);
00030 };
00031
00032 template<>
00033 short Convert<short>(double Value)
00034 {
00035     return (short)(Value * _I16_MAX);
00036 };
00037
00038 // 24-bit value stored in the upper bits of a 32-bit integer.
00039 struct int24in32
00040 {
00041     int value;
00042 };
00043 template<>
00044 int24in32 Convert<int24in32>(double Value)
00045 {
00046     constexpr int _I24_MAX = (1 << 23) - 1;
00047     return { (int)(Value * _I24_MAX) << 8 };
00048 };
00049
00050 //
00051 //  ToneSampleGenerator()
00052 //
00053 ToneSampleGenerator::ToneSampleGenerator()
00054 {
00055     m_SampleQueue = nullptr;
00056     m_SampleQueueTail = &m_SampleQueue;
00057 }
00058
00059 //
00060 //  ~ToneSampleGenerator()
00061 //
00062 ToneSampleGenerator::~ToneSampleGenerator()
00063 {
00064     // Flush unused samples
00065     Flush();
00066 }
00067
00068 //
00069 //  GenerateSampleBuffer()
00070 //
00071 //  Create a linked list of sample buffers
00072 //
00073 HRESULT ToneSampleGenerator::GenerateSampleBuffer( DWORD Frequency, UINT32 FramesPerPeriod, WAVEFORMATEX *wfx )
00074 {
00075     HRESULT hr = S_OK;
00076
00077     UINT32 renderBufferSizeInBytes = FramesPerPeriod * wfx->nBlockAlign;
00078     UINT64 renderDataLength = ( wfx->nSamplesPerSec * TONE_DURATION_SEC * wfx->nBlockAlign ) + ( renderBufferSizeInBytes - 1 );
00079     UINT64 renderBufferCount = renderDataLength / renderBufferSizeInBytes;
00080
00081     double theta = 0;
00082
00083     for( UINT64 i = 0; i < renderBufferCount; i++ )
00084     {
00085         RenderBuffer *SampleBuffer = new (std::nothrow) RenderBuffer();
00086         if (nullptr == SampleBuffer)
00087         {
00088             return E_OUTOFMEMORY;
00089         }
00090
00091         SampleBuffer->BufferSize = renderBufferSizeInBytes;
00092         SampleBuffer->BytesFilled = renderBufferSizeInBytes;
00093         SampleBuffer->Buffer = new (std::nothrow) BYTE[ renderBufferSizeInBytes ];
00094         if (nullptr == SampleBuffer->Buffer)
00095         {
00096             return E_OUTOFMEMORY;
00097         }
00098
00099         switch(GetRenderSampleType( wfx ) )
00100         {
00101         case RenderSampleType::SampleType16BitPCM:
00102             GenerateSineSamples<short>( SampleBuffer->Buffer, SampleBuffer->BufferSize, Frequency, wfx->nChannels, wfx->nSamplesPerSec, TONE_AMPLITUDE, &theta);
00103             break;
00104
00105         case RenderSampleType::SampleType24in32BitPCM:
00106             GenerateSineSamples<int24in32>(SampleBuffer->Buffer, SampleBuffer->BufferSize, Frequency, wfx->nChannels, wfx->nSamplesPerSec, TONE_AMPLITUDE, &theta);
00107             break;
00108
00109         case RenderSampleType::SampleTypeFloat:
00110             GenerateSineSamples<float>( SampleBuffer->Buffer, SampleBuffer->BufferSize, Frequency, wfx->nChannels, wfx->nSamplesPerSec, TONE_AMPLITUDE, &theta);
00111             break;
00112
00113         default:
00114             return E_UNEXPECTED;
00115             break;
00116         }
00117
00118         *m_SampleQueueTail = SampleBuffer;
00119         m_SampleQueueTail = &SampleBuffer->Next;
00120     }
00121     return hr;
00122 }
00123
00124 //
00125 // GenerateSineSamples()
00126 //
00127 //  Generate samples which represent a sine wave that fits into the specified buffer.
00128 //
00129 //  T:  Type of data holding the sample (short, int, byte, float)
00130 //  Buffer - Buffer to hold the samples
00131 //  BufferLength - Length of the buffer.
00132 //  ChannelCount - Number of channels per audio frame.
00133 //  SamplesPerSecond - Samples/Second for the output data.
00134 //  InitialTheta - Initial theta value - start at 0, modified in this function.
00135 //
00136 template <typename T>
00137 void ToneSampleGenerator::GenerateSineSamples(BYTE *Buffer, size_t BufferLength, DWORD Frequency, WORD ChannelCount, DWORD SamplesPerSecond, double Amplitude, double *InitialTheta)
00138 {
00139     double sampleIncrement = (Frequency * (M_PI*2)) / (double)SamplesPerSecond;
00140     T *dataBuffer = reinterpret_cast<T *>(Buffer);
00141     double theta = (InitialTheta != NULL ? *InitialTheta : 0);
00142
00143     for (size_t i = 0 ; i < BufferLength / sizeof(T) ; i += ChannelCount)
00144     {
00145         double sinValue = Amplitude * sin( theta );
00146         for(size_t j = 0 ;j < ChannelCount; j++)
00147         {
00148             dataBuffer[i+j] = Convert<T>(sinValue);
00149         }
00150         theta += sampleIncrement;
00151     }
00152
00153     if (InitialTheta != NULL)
00154     {
00155         *InitialTheta = theta;
00156     }
00157 }
00158
00159 //
00160 //  FillSampleBuffer()
00161 //
00162 //  File the Data buffer of size BytesToRead with the first item in the queue.  Caller is responsible for allocating and freeing buffer
00163 //
00164 HRESULT ToneSampleGenerator::FillSampleBuffer( UINT32 BytesToRead, BYTE *Data )
00165 {
00166     if (nullptr == Data)
00167     {
00168         return E_POINTER;
00169     }
00170
00171     RenderBuffer *SampleBuffer = m_SampleQueue;
00172
00173     if (BytesToRead > SampleBuffer->BufferSize)
00174     {
00175         return E_INVALIDARG;
00176     }
00177
00178     CopyMemory( Data, SampleBuffer->Buffer, BytesToRead );
00179
00180     m_SampleQueue = m_SampleQueue->Next;
00181     SAFE_DELETE(SampleBuffer);
00182
00183     return S_OK;
00184 }
00185
00186 //
00187 //  Flush()
00188 //
00189 //  Remove and free unused samples from the queue
00190 //
00191 void ToneSampleGenerator::Flush()
00192 {
00193     while( m_SampleQueue != nullptr )
00194     {
00195         RenderBuffer *SampleBuffer = m_SampleQueue;
00196         m_SampleQueue = SampleBuffer->Next;
00197         SAFE_DELETE( SampleBuffer );
00198     }
00199 }
00200
Generated on Fri Nov 15 2024 22:22:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cs/SampleConfiguration.cs Source File

  • NumberFormatting
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Number formatting C# sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title = "Percent and Permille Formatting", ClassType = typeof(Scenario1_PercentPermilleFormatting) },
00025             new Scenario() { Title = "Decimal Formatting", ClassType = typeof(Scenario2_DecimalFormatting) },
00026             new Scenario() { Title = "Currency Formatting", ClassType = typeof(Scenario3_CurrencyFormatting) },
00027             new Scenario() { Title = "Number Parsing", ClassType = typeof(Scenario4_NumberParsing) },
00028             new Scenario() { Title = "Rounding and Padding", ClassType = typeof(Scenario5_RoundingAndPadding) },
00029             new Scenario() { Title = "Numeral System Translation", ClassType = typeof(Scenario6_NumeralSystemTranslation) },
00030             new Scenario() { Title = "Formatting/Translation using Unicode Extensions", ClassType = typeof(Scenario7_UsingUnicodeExtensions) }
00031         };
00032     }
00033
00034     public class Scenario
00035     {
00036         public string Title { get; set; }
00037         public Type ClassType { get; set; }
00038     }
00039 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInfo/cs/Scenario3_CheckUserConsentGroup.xaml.cs Source File

  • UserInfo
  • cs

Scenario3_CheckUserConsentGroup.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Collections.ObjectModel;
00015 using Windows.Foundation.Collections;
00016 using Windows.Storage.Streams;
00017 using Windows.System;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Media.Imaging;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace SDKTemplate
00024 {
00025     public sealed partial class Scenario3_CheckUserConsentGroup : Page
00026     {
00027         private MainPage rootPage = MainPage.Current;
00028
00029         public Scenario3_CheckUserConsentGroup()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override async void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             // Populate the list of users.
00037             var observableUsers = await MainPage.GetUserViewModelsAsync();
00038             UserList.DataContext = observableUsers;
00039             if (observableUsers.Count > 0)
00040             {
00041                 UserList.SelectedIndex = 0;
00042             }
00043         }
00044
00045         static string EvaluateConsentResult(UserAgeConsentResult consentResult)
00046         {
00047             switch (consentResult)
00048             {
00049                 case UserAgeConsentResult.Included:
00050                 case UserAgeConsentResult.NotEnforced:
00051                     return "Allowed.";
00052                 case UserAgeConsentResult.NotIncluded:
00053                     return "Not allowed.";
00054                 case UserAgeConsentResult.Unknown:
00055                     return "Cannot determine. Default to app specific age unknown behavior.";
00056                 default:
00057                 case UserAgeConsentResult.Ambiguous:
00058                     return "Age regulations have changed, the app needs to be updated to reflect new catagories.";
00059             }
00060         }
00061
00062         private async void ShowConsentGroups(object sender, RoutedEventArgs e)
00063         {
00064             var selectedUser = (UserViewModel)UserList.SelectedValue;
00065             if (selectedUser != null)
00066             {
00067                 ResultsText.Text = "";
00068
00069                 rootPage.NotifyUser("", NotifyType.StatusMessage);
00070                 try
00071                 {
00072                     User user = User.GetFromId(selectedUser.UserId);
00073
00074                     String result = "";
00075
00076                     UserAgeConsentResult canShowChildContent = await user.CheckUserAgeConsentGroupAsync(UserAgeConsentGroup.Child);
00077                     result += "Child content: " + EvaluateConsentResult(canShowChildContent) + "\n";
00078
00079                     UserAgeConsentResult canShowMinorContent = await user.CheckUserAgeConsentGroupAsync(UserAgeConsentGroup.Minor);
00080                     result += "Minor content: " + EvaluateConsentResult(canShowMinorContent) + "\n";
00081
00082                     UserAgeConsentResult canShowAdultContent = await user.CheckUserAgeConsentGroupAsync(UserAgeConsentGroup.Adult);
00083                     result += "Adult content: " + EvaluateConsentResult(canShowAdultContent) + "\n";
00084
00085                     ResultsText.Text = result;
00086                 }
00087                 catch (Exception ex)
00088                 {
00089                     // Operations on the "User" object fail if the user signs out.
00090                     rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
00091                 }
00092             }
00093         }
00094     }
00095 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario07_PostStreamWithProgress Member List

This is the complete list of members for Scenario07_PostStreamWithProgress, including all inherited members.
Cancel_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario07_PostStreamWithProgress |
CancelableRequestAsync(Windows::Foundation::Uri resourceUri, Windows::Web::Http::IHttpContent content) | Scenario07_PostStreamWithProgress | [private]
ChunkedResponseToggle_Toggled(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario07_PostStreamWithProgress |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario07_PostStreamWithProgress |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario07_PostStreamWithProgress |
ProgressHandler(Windows::Foundation::IAsyncOperationWithProgress< Windows::Web::Http::HttpRequestResult, Windows::Web::Http::HttpProgress > const &sender, Windows::Web::Http::HttpProgress progress) | Scenario07_PostStreamWithProgress | [private]
ResetFields() | Scenario07_PostStreamWithProgress | [private]
Scenario07_PostStreamWithProgress() | Scenario07_PostStreamWithProgress |
Start_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario07_PostStreamWithProgress |
UpdateAddressField() | Scenario07_PostStreamWithProgress | [private]
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PdfDocument/cppwinrt/pch.cpp Source File

  • PdfDocument
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/GameTimer.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

GameTimer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 class GameTimer
00015 {
00016 public:
00017     GameTimer();
00018
00019     float PlayingTime();            // Return the Elapsed time the Game has been active in seconds since Reset
00020     void PlayingTime(float time);   // Set the Elapsed playing time -- used for restarting in the middle of a game
00021     float DeltaTime();              // Return the Delta time between the last two updates
00022
00023     void Reset();
00024     void Start();
00025     void Stop();
00026     void Update();
00027     bool Active() { return m_active; };
00028
00029 private:
00030     float m_secondsPerCount;  // 1.0 / Frequency
00031     float m_deltaTime;
00032
00033     LARGE_INTEGER m_baseTime;
00034     LARGE_INTEGER m_pausedTime;
00035     LARGE_INTEGER m_stopTime;
00036     LARGE_INTEGER m_previousTime;
00037     LARGE_INTEGER m_currentTime;
00038
00039     bool m_active;
00040 };
00041
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7 Member List

This is the complete list of members for Scenario7, including all inherited members.
CommandBar_Closed(object sender, object e) | Scenario7 | [inline, private]
CommandBar_Opening(object sender, object e) | Scenario7 | [inline, private]
Scenario7() | Scenario7 | [inline]
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

App Member List

This is the complete list of members for App, including all inherited members.
App() | App | [inline]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnSuspending(object sender, SuspendingEventArgs e) | App | [inline, private]
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactPicker/cpp/pch.h Source File

  • ContactPicker
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario9 Member List

This is the complete list of members for Scenario9, including all inherited members.
CompareFilesButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario9
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario9
Scenario9() | Scenario9
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlContextMenu/cpp/Scenario1.xaml.h Source File

  • XamlContextMenu
  • cpp

Scenario1.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario1 sealed
00021     {
00022     public:
00023         Scenario1();
00024
00025     private:
00026         MainPage^ rootPage = MainPage::Current;
00027
00028         void OpenMenuItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029         void PrintMenuItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00030         void DeleteMenuItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00031     };
00032 }
Generated on Fri Nov 15 2024 22:17:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/ContinuationPage.xaml.h Source File

  • Printing
  • cpp

ContinuationPage.xaml.h

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "ContinuationPage.g.h"
00005
00006 namespace SDKTemplate
00007 {
00008     /// <summary>
00009     /// A paged used to flow text from a given text container
00010     /// Usage: Output scenarios 1-4 might not fit entirely on a given "printer page"
00011     /// In that case simply add new continuation pages of the given size until all the content can be displayed
00012     /// </summary>
00013     [Windows::Foundation::Metadata::WebHostHidden]
00014     public ref class ContinuationPage sealed
00015     {
00016     public:
00017         /// <summary>
00018         /// Creates a continuation page and links text-flow to a text flow container
00019         /// </summary>
00020         /// <param name="textLinkContainer">Text link container which will flow text into this page</param>
00021         ContinuationPage(Windows::UI::Xaml::Controls::RichTextBlockOverflow^ textLinkContainer);
00022     };
00023 }
Generated on Fri Nov 15 2024 22:20:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/Common/DirectXSample.h Source File

  • Simple3DGameDX
  • cpp
  • Common

DirectXSample.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009 #include <math.h>
00010
00011 namespace DX
00012 {
00013     // Convert DirectX error codes to exceptions.
00014     inline void ThrowIfFailed(HRESULT hr)
00015     {
00016         if (FAILED(hr))
00017         {
00018             // Set a breakpoint on this line to catch DX API errors.
00019             throw Platform::Exception::CreateException(hr);
00020         }
00021     }
00022
00023     // Converts a length in device-independent pixels (DIPs) to a length in physical pixels.
00024     inline float ConvertDipsToPixels(float dips, float dpi)
00025     {
00026         static const float dipsPerInch = 96.0f;
00027         return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00028     }
00029
00030     // Converts a length in physical pixels to a length in device-independent pixels (DIPs).
00031     inline float ConvertPixelsToDips(float pixels)
00032     {
00033         static const float dipsPerInch = 96.0f;
00034         return pixels * dipsPerInch / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->LogicalDpi; // Do not round.
00035     }
00036
00037     // Converts a length in physical pixels to a length in device-independent pixels (DIPs) using the provided DPI. This removes the need
00038     // to call this function from a thread associated with a CoreWindow, which is required by DisplayInformation::GetForCurrentView().
00039     inline float ConvertPixelsToDips(float pixels, float dpi)
00040     {
00041         static const float dipsPerInch = 96.0f;
00042         return pixels * dipsPerInch / dpi; // Do not round.
00043     }
00044
00045 #if defined(_DEBUG)
00046     // Check for SDK Layer support.
00047     inline bool SdkLayersAvailable()
00048     {
00049         HRESULT hr = D3D11CreateDevice(
00050             nullptr,
00051             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00052             0,
00053             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00054             nullptr,                    // Any feature level will do.
00055             0,
00056             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Store apps.
00057             nullptr,                    // No need to keep the D3D device reference.
00058             nullptr,                    // No need to know the feature level.
00059             nullptr                     // No need to keep the D3D device context reference.
00060             );
00061
00062         return SUCCEEDED(hr);
00063     }
00064 #endif
00065 }
Generated on Fri Nov 15 2024 22:21:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AppData Member List

This is the complete list of members for AppData, including all inherited members.
IsUpperCaseEnabled | AppData | [static]
IsUpperCaseEnabledPropertyDataChanged | AppData | [static]
isUpperCaseEnabledPropertyKey | AppData | [private]
LastErrorCode | AppData | [static]
LastErrorMessage | AppData | [static]
localSettings | AppData | [private, static]
OnboardingConfigurationState | AppData | [static]
onboardingConfigurationStateKey | AppData | [private]
onboardingConfigureAuthenticationTypeKey | AppData | [private]
OnboardingConfigureAuthType | AppData | [static]
OnboardingConfigurePassphrase | AppData | [static]
onboardingConfigurePassphraseKey | AppData | [private]
OnboardingConfigureSsid | AppData | [static]
onboardingConfigureSsidKey | AppData | [private]
onboardingLastErrorCodeKey | AppData | [private]
onboardingLastErrorMessageKey | AppData | [private]
SampleNetworkPassword | AppData |
SampleNetworkScanList | AppData | [static]
Generated on Fri Nov 15 2024 22:23:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

StandardOptionsPrintHelper Member List

This is the complete list of members for StandardOptionsPrintHelper, including all inherited members.
AddOnePrintPreviewPage(RichTextBlockOverflow lastRTBOAdded, PrintPageDescription printPageDescription) | PrintHelper | [inline, protected, virtual]
AddPrintPages(object sender, AddPagesEventArgs e) | PrintHelper | [inline, protected, virtual]
ApplicationContentMarginLeft | PrintHelper | [protected]
ApplicationContentMarginTop | PrintHelper | [protected]
CreatePrintPreviewPages(object sender, PaginateEventArgs e) | PrintHelper | [inline, protected, virtual]
firstPage | PrintHelper | [protected]
GetPrintPreviewPage(object sender, GetPreviewPageEventArgs e) | PrintHelper | [inline, protected, virtual]
PreparePrintContent(Page page) | PrintHelper | [inline, virtual]
PreviewPagesCreated | PrintHelper | [protected]
PrintCanvas | PrintHelper | [protected]
printDocument | PrintHelper | [protected]
printDocumentSource | PrintHelper | [protected]
PrintHelper(Page scenarioPage) | PrintHelper | [inline]
PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e) | StandardOptionsPrintHelper | [inline, protected, virtual]
RegisterForPrinting() | PrintHelper | [inline, virtual]
scenarioPage | PrintHelper | [protected]
ShowPrintUIAsync() | PrintHelper | [inline]
StandardOptionsPrintHelper(Page scenarioPage) | StandardOptionsPrintHelper | [inline]
UnregisterForPrinting() | PrintHelper | [inline, virtual]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario9_CustomPairDevice Member List

This is the complete list of members for Scenario9_CustomPairDevice, including all inherited members.
CompleteConfirmPinTask(bool accept) | Scenario9_CustomPairDevice | [private]
CompletePasswordCredential(hstring username={}, hstring password={}) | Scenario9_CustomPairDevice | [private]
CompleteProvidePinTask(hstring pin={}) | Scenario9_CustomPairDevice | [private]
confirmPinTaskSrc | Scenario9_CustomPairDevice | [private]
deviceWatcherHelper | Scenario9_CustomPairDevice | [private]
GetPasswordCredentialFromUserAsync() | Scenario9_CustomPairDevice | [private]
GetPinFromUserAsync() | Scenario9_CustomPairDevice | [private]
GetSelectedCeremonies() | Scenario9_CustomPairDevice | [private]
GetUserConfirmationAsync(hstring const &pin) | Scenario9_CustomPairDevice | [private]
HidePairingPanel() | Scenario9_CustomPairDevice | [private]
noButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario9_CustomPairDevice |
okButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario9_CustomPairDevice |
OnDeviceListChanged(Windows::Devices::Enumeration::DeviceWatcher const &sender, hstring const &id) | Scenario9_CustomPairDevice | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario9_CustomPairDevice |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario9_CustomPairDevice |
PairButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario9_CustomPairDevice |
PairingRequestedHandler(Windows::Devices::Enumeration::DeviceInformationCustomPairing const &sender, Windows::Devices::Enumeration::DevicePairingRequestedEventArgs e) | Scenario9_CustomPairDevice | [private]
providePasswordCredentialTaskSrc | Scenario9_CustomPairDevice | [private]
providePinTaskSrc | Scenario9_CustomPairDevice | [private]
resultCollection | Scenario9_CustomPairDevice | [private]
ResultsListView_SelectionChanged(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs const &e) | Scenario9_CustomPairDevice |
Scenario9_CustomPairDevice() | Scenario9_CustomPairDevice |
ShowPairingPanel(hstring const &text, Windows::Devices::Enumeration::DevicePairingKinds pairingKind) | Scenario9_CustomPairDevice | [private]
StartWatcher() | Scenario9_CustomPairDevice | [private]
StartWatcherButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario9_CustomPairDevice |
StopWatcher() | Scenario9_CustomPairDevice | [private]
StopWatcherButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario9_CustomPairDevice |
UnpairButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario9_CustomPairDevice |
UpdatePairingButtons() | Scenario9_CustomPairDevice | [private]
verifyButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario9_CustomPairDevice |
yesButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario9_CustomPairDevice |
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/ComputeShader/DeviceResources.cpp Source File

  • D2DCustomEffects
  • cpp
  • ComputeShader

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DeviceResources.h"
00014 #include "DirectXHelper.h"
00015
00016 using namespace D2D1;
00017 using namespace DirectX;
00018 using namespace Microsoft::WRL;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Graphics::Display;
00021 using namespace Windows::UI::Core;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Platform;
00024
00025 // Constants used to calculate screen rotations
00026 namespace ScreenRotation
00027 {
00028     // 0-degree Z-rotation
00029     static const XMFLOAT4X4 Rotation0(
00030         1.0f, 0.0f, 0.0f, 0.0f,
00031         0.0f, 1.0f, 0.0f, 0.0f,
00032         0.0f, 0.0f, 1.0f, 0.0f,
00033         0.0f, 0.0f, 0.0f, 1.0f
00034         );
00035
00036     // 90-degree Z-rotation
00037     static const XMFLOAT4X4 Rotation90(
00038         0.0f, 1.0f, 0.0f, 0.0f,
00039         -1.0f, 0.0f, 0.0f, 0.0f,
00040         0.0f, 0.0f, 1.0f, 0.0f,
00041         0.0f, 0.0f, 0.0f, 1.0f
00042         );
00043
00044     // 180-degree Z-rotation
00045     static const XMFLOAT4X4 Rotation180(
00046         -1.0f, 0.0f, 0.0f, 0.0f,
00047         0.0f, -1.0f, 0.0f, 0.0f,
00048         0.0f, 0.0f, 1.0f, 0.0f,
00049         0.0f, 0.0f, 0.0f, 1.0f
00050         );
00051
00052     // 270-degree Z-rotation
00053     static const XMFLOAT4X4 Rotation270(
00054         0.0f, -1.0f, 0.0f, 0.0f,
00055         1.0f, 0.0f, 0.0f, 0.0f,
00056         0.0f, 0.0f, 1.0f, 0.0f,
00057         0.0f, 0.0f, 0.0f, 1.0f
00058         );
00059 };
00060
00061 // Constructor for DeviceResources.
00062 DX::DeviceResources::DeviceResources() :
00063     DeviceResources(false /* _In_ bool forceWarpDevice */)
00064 {}
00065
00066 // Constructor for DeviceResources; allows the caller to force usage of the WARP software
00067 // device which is useful if we need to use D3D features that are unsupported by the hardware.
00068 DX::DeviceResources::DeviceResources(_In_ bool forceWarpDevice) :
00069     m_screenViewport(),
00070     m_d3dFeatureLevel(D3D_FEATURE_LEVEL_9_1),
00071     m_d3dRenderTargetSize(),
00072     m_outputSize(),
00073     m_logicalSize(),
00074     m_nativeOrientation(DisplayOrientations::None),
00075     m_currentOrientation(DisplayOrientations::None),
00076     m_dpi(-1.0f),
00077     m_deviceNotify(nullptr),
00078     m_forceWarpDevice(forceWarpDevice)
00079 {
00080     CreateDeviceIndependentResources();
00081     CreateDeviceResources();
00082 }
00083
00084 // Configures resources that don't depend on the Direct3D device.
00085 void DX::DeviceResources::CreateDeviceIndependentResources()
00086 {
00087     // Initialize Direct2D resources.
00088     D2D1_FACTORY_OPTIONS options;
00089     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00090
00091 #if defined(_DEBUG)
00092     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00093     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00094 #endif
00095
00096     // Initialize the Direct2D Factory.
00097     DX::ThrowIfFailed(
00098         D2D1CreateFactory(
00099             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00100             __uuidof(ID2D1Factory2),
00101             &options,
00102             &m_d2dFactory
00103             )
00104         );
00105
00106     // Initialize the DirectWrite Factory.
00107     DX::ThrowIfFailed(
00108         DWriteCreateFactory(
00109             DWRITE_FACTORY_TYPE_SHARED,
00110             __uuidof(IDWriteFactory2),
00111             &m_dwriteFactory
00112             )
00113         );
00114
00115     // Initialize the Windows Imaging Component (WIC) Factory.
00116     DX::ThrowIfFailed(
00117         CoCreateInstance(
00118             CLSID_WICImagingFactory2,
00119             nullptr,
00120             CLSCTX_INPROC_SERVER,
00121             IID_PPV_ARGS(&m_wicFactory)
00122             )
00123         );
00124 }
00125
00126 // Configures the Direct3D device, and stores handles to it and the device context.
00127 void DX::DeviceResources::CreateDeviceResources()
00128 {
00129     // This flag adds support for surfaces with a different color channel ordering
00130     // than the API default. It is required for compatibility with Direct2D.
00131     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00132
00133 #if defined(_DEBUG)
00134     if (DX::SdkLayersAvailable())
00135     {
00136         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00137         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00138     }
00139 #endif
00140
00141     // This array defines the set of DirectX hardware feature levels this app will support.
00142     // Note the ordering should be preserved.
00143     // Don't forget to declare your application's minimum required feature level in its
00144     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00145     D3D_FEATURE_LEVEL featureLevels[] =
00146     {
00147         D3D_FEATURE_LEVEL_11_1,
00148         D3D_FEATURE_LEVEL_11_0,
00149         D3D_FEATURE_LEVEL_10_1,
00150         D3D_FEATURE_LEVEL_10_0,
00151         D3D_FEATURE_LEVEL_9_3,
00152         D3D_FEATURE_LEVEL_9_2,
00153         D3D_FEATURE_LEVEL_9_1
00154     };
00155
00156     // Create the Direct3D 11 API device object and a corresponding context.
00157     ComPtr<ID3D11Device> device;
00158     ComPtr<ID3D11DeviceContext> context;
00159
00160     // Create a device using the hardware graphics driver, unless WARP override is set.
00161     D3D_DRIVER_TYPE driverType = m_forceWarpDevice ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE;
00162
00163     HRESULT hr = D3D11CreateDevice(
00164         nullptr,                    // Specify nullptr to use the default adapter.
00165         driverType,
00166         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00167         creationFlags,              // Set debug and Direct2D compatibility flags.
00168         featureLevels,              // List of feature levels this app can support.
00169         ARRAYSIZE(featureLevels),   // Size of the list above.
00170         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00171         &device,                    // Returns the Direct3D device created.
00172         &m_d3dFeatureLevel,         // Returns feature level of device created.
00173         &context                    // Returns the device immediate context.
00174         );
00175
00176     if (FAILED(hr))
00177     {
00178         // If the initialization fails, fall back to the WARP device.
00179         // For more information on WARP, see:
00180         // http://go.microsoft.com/fwlink/?LinkId=286690
00181         DX::ThrowIfFailed(
00182             D3D11CreateDevice(
00183                 nullptr,
00184                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00185                 0,
00186                 creationFlags,
00187                 featureLevels,
00188                 ARRAYSIZE(featureLevels),
00189                 D3D11_SDK_VERSION,
00190                 &device,
00191                 &m_d3dFeatureLevel,
00192                 &context
00193                 )
00194             );
00195     }
00196
00197     // Store pointers to the Direct3D 11.1 API device and immediate context.
00198     DX::ThrowIfFailed(
00199         device.As(&m_d3dDevice)
00200         );
00201
00202     DX::ThrowIfFailed(
00203         context.As(&m_d3dContext)
00204         );
00205
00206     // Create the Direct2D device object and a corresponding context.
00207     ComPtr<IDXGIDevice3> dxgiDevice;
00208     DX::ThrowIfFailed(
00209         m_d3dDevice.As(&dxgiDevice)
00210         );
00211
00212     DX::ThrowIfFailed(
00213         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00214         );
00215
00216     DX::ThrowIfFailed(
00217         m_d2dDevice->CreateDeviceContext(
00218             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00219             &m_d2dContext
00220             )
00221         );
00222 }
00223
00224 // These resources need to be recreated every time the window size is changed.
00225 void DX::DeviceResources::CreateWindowSizeDependentResources()
00226 {
00227     // Clear the previous window size specific context.
00228     ID3D11RenderTargetView* nullViews[] = {nullptr};
00229     m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00230     m_d3dRenderTargetView = nullptr;
00231     m_d2dContext->SetTarget(nullptr);
00232     m_d2dTargetBitmap = nullptr;
00233     m_d3dDepthStencilView = nullptr;
00234     m_d3dContext->Flush();
00235
00236     // Calculate the necessary render target size in pixels.
00237     m_outputSize.Width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_dpi);
00238     m_outputSize.Height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_dpi);
00239
00240     // Prevent zero size DirectX content from being created.
00241     m_outputSize.Width = max(m_outputSize.Width, 1);
00242     m_outputSize.Height = max(m_outputSize.Height, 1);
00243
00244     // The width and height of the swap chain must be based on the window's
00245     // natively-oriented width and height. If the window is not in the native
00246     // orientation, the dimensions must be reversed.
00247     DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation();
00248
00249     bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270;
00250     m_d3dRenderTargetSize.Width = swapDimensions ? m_outputSize.Height : m_outputSize.Width;
00251     m_d3dRenderTargetSize.Height = swapDimensions ? m_outputSize.Width : m_outputSize.Height;
00252
00253     if (m_swapChain != nullptr)
00254     {
00255         // If the swap chain already exists, resize it.
00256         HRESULT hr = m_swapChain->ResizeBuffers(
00257             2, // Double-buffered swap chain.
00258             lround(m_d3dRenderTargetSize.Width),
00259             lround(m_d3dRenderTargetSize.Height),
00260             DXGI_FORMAT_B8G8R8A8_UNORM,
00261             0
00262             );
00263
00264         if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00265         {
00266             // If the device was removed for any reason, a new device and swap chain will need to be created.
00267             HandleDeviceLost();
00268
00269             // Everything is set up now. Do not continue execution of this method. HandleDeviceLost will reenter this method
00270             // and correctly set up the new device.
00271             return;
00272         }
00273         else
00274         {
00275             DX::ThrowIfFailed(hr);
00276         }
00277     }
00278     else
00279     {
00280         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00281         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00282
00283         swapChainDesc.Width = lround(m_d3dRenderTargetSize.Width); // Match the size of the window.
00284         swapChainDesc.Height = lround(m_d3dRenderTargetSize.Height);
00285         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swap chain format.
00286         swapChainDesc.Stereo = false;
00287         swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling.
00288         swapChainDesc.SampleDesc.Quality = 0;
00289         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00290         swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency.
00291         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Runtime apps must use this SwapEffect.
00292         swapChainDesc.Flags = 0;
00293         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00294         swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
00295
00296         // This sequence obtains the DXGI factory that was used to create the Direct3D device above.
00297         ComPtr<IDXGIDevice3> dxgiDevice;
00298         DX::ThrowIfFailed(
00299             m_d3dDevice.As(&dxgiDevice)
00300             );
00301
00302         ComPtr<IDXGIAdapter> dxgiAdapter;
00303         DX::ThrowIfFailed(
00304             dxgiDevice->GetAdapter(&dxgiAdapter)
00305             );
00306
00307         ComPtr<IDXGIFactory2> dxgiFactory;
00308         DX::ThrowIfFailed(
00309             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00310             );
00311
00312         DX::ThrowIfFailed(
00313             dxgiFactory->CreateSwapChainForCoreWindow(
00314                 m_d3dDevice.Get(),
00315                 reinterpret_cast<IUnknown*>(m_window.Get()),
00316                 &swapChainDesc,
00317                 nullptr,
00318                 &m_swapChain
00319                 )
00320             );
00321
00322         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00323         // ensures that the application will only render after each VSync, minimizing power consumption.
00324         DX::ThrowIfFailed(
00325             dxgiDevice->SetMaximumFrameLatency(1)
00326             );
00327     }
00328
00329     // Set the proper orientation for the swap chain, and generate 2D and
00330     // 3D matrix transformations for rendering to the rotated swap chain.
00331     // Note the rotation angle for the 2D and 3D transforms are different.
00332     // This is due to the difference in coordinate spaces.  Additionally,
00333     // the 3D matrix is specified explicitly to avoid rounding errors.
00334
00335     switch (displayRotation)
00336     {
00337     case DXGI_MODE_ROTATION_IDENTITY:
00338         m_orientationTransform2D = Matrix3x2F::Identity();
00339         m_orientationTransform3D = ScreenRotation::Rotation0;
00340         break;
00341
00342     case DXGI_MODE_ROTATION_ROTATE90:
00343         m_orientationTransform2D =
00344             Matrix3x2F::Rotation(90.0f) *
00345             Matrix3x2F::Translation(m_logicalSize.Height, 0.0f);
00346         m_orientationTransform3D = ScreenRotation::Rotation270;
00347         break;
00348
00349     case DXGI_MODE_ROTATION_ROTATE180:
00350         m_orientationTransform2D =
00351             Matrix3x2F::Rotation(180.0f) *
00352             Matrix3x2F::Translation(m_logicalSize.Width, m_logicalSize.Height);
00353         m_orientationTransform3D = ScreenRotation::Rotation180;
00354         break;
00355
00356     case DXGI_MODE_ROTATION_ROTATE270:
00357         m_orientationTransform2D =
00358             Matrix3x2F::Rotation(270.0f) *
00359             Matrix3x2F::Translation(0.0f, m_logicalSize.Width);
00360         m_orientationTransform3D = ScreenRotation::Rotation90;
00361         break;
00362
00363     default:
00364         throw ref new FailureException();
00365     }
00366
00367     DX::ThrowIfFailed(
00368         m_swapChain->SetRotation(displayRotation)
00369         );
00370
00371     // Create a render target view of the swap chain back buffer.
00372     ComPtr<ID3D11Texture2D> backBuffer;
00373     DX::ThrowIfFailed(
00374         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00375         );
00376
00377     DX::ThrowIfFailed(
00378         m_d3dDevice->CreateRenderTargetView(
00379             backBuffer.Get(),
00380             nullptr,
00381             &m_d3dRenderTargetView
00382             )
00383         );
00384
00385     // Create a depth stencil view for use with 3D rendering if needed.
00386     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00387         DXGI_FORMAT_D24_UNORM_S8_UINT,
00388         lround(m_d3dRenderTargetSize.Width),
00389         lround(m_d3dRenderTargetSize.Height),
00390         1, // This depth stencil view has only one texture.
00391         1, // Use a single mipmap level.
00392         D3D11_BIND_DEPTH_STENCIL
00393         );
00394
00395     ComPtr<ID3D11Texture2D> depthStencil;
00396     DX::ThrowIfFailed(
00397         m_d3dDevice->CreateTexture2D(
00398             &depthStencilDesc,
00399             nullptr,
00400             &depthStencil
00401             )
00402         );
00403
00404     CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
00405     DX::ThrowIfFailed(
00406         m_d3dDevice->CreateDepthStencilView(
00407             depthStencil.Get(),
00408             &depthStencilViewDesc,
00409             &m_d3dDepthStencilView
00410             )
00411         );
00412
00413     // Set the 3D rendering viewport to target the entire window.
00414     m_screenViewport = CD3D11_VIEWPORT(
00415         0.0f,
00416         0.0f,
00417         m_d3dRenderTargetSize.Width,
00418         m_d3dRenderTargetSize.Height
00419         );
00420
00421     m_d3dContext->RSSetViewports(1, &m_screenViewport);
00422
00423     // Create a Direct2D target bitmap associated with the
00424     // swap chain back buffer and set it as the current target.
00425     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00426         D2D1::BitmapProperties1(
00427             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00428             D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00429             m_dpi,
00430             m_dpi
00431             );
00432
00433     ComPtr<IDXGISurface2> dxgiBackBuffer;
00434     DX::ThrowIfFailed(
00435         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00436         );
00437
00438     DX::ThrowIfFailed(
00439         m_d2dContext->CreateBitmapFromDxgiSurface(
00440             dxgiBackBuffer.Get(),
00441             &bitmapProperties,
00442             &m_d2dTargetBitmap
00443             )
00444         );
00445
00446     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00447
00448     // Grayscale text anti-aliasing is recommended for all Windows Runtime apps.
00449     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00450 }
00451
00452 // This method is called when the CoreWindow is created (or re-created).
00453 void DX::DeviceResources::SetWindow(CoreWindow^ window)
00454 {
00455     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00456
00457     m_window = window;
00458     m_logicalSize = Windows::Foundation::Size(window->Bounds.Width, window->Bounds.Height);
00459     m_nativeOrientation = currentDisplayInformation->NativeOrientation;
00460     m_currentOrientation = currentDisplayInformation->CurrentOrientation;
00461     m_dpi = currentDisplayInformation->LogicalDpi;
00462     m_d2dContext->SetDpi(m_dpi, m_dpi);
00463
00464     CreateWindowSizeDependentResources();
00465 }
00466
00467 // This method is called in the event handler for the SizeChanged event.
00468 void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize)
00469 {
00470     if (m_logicalSize != logicalSize)
00471     {
00472         m_logicalSize = logicalSize;
00473         CreateWindowSizeDependentResources();
00474     }
00475 }
00476
00477 // This method is called in the event handler for the DpiChanged event.
00478 void DX::DeviceResources::SetDpi(float dpi)
00479 {
00480     if (dpi != m_dpi)
00481     {
00482         m_dpi = dpi;
00483
00484         // When the display DPI changes, the logical size of the window (measured in Dips) also changes and needs to be updated.
00485         m_logicalSize = Windows::Foundation::Size(m_window->Bounds.Width, m_window->Bounds.Height);
00486
00487         m_d2dContext->SetDpi(m_dpi, m_dpi);
00488         CreateWindowSizeDependentResources();
00489     }
00490 }
00491
00492 // This method is called in the event handler for the OrientationChanged event.
00493 void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation)
00494 {
00495     if (m_currentOrientation != currentOrientation)
00496     {
00497         m_currentOrientation = currentOrientation;
00498         CreateWindowSizeDependentResources();
00499     }
00500 }
00501
00502 // This method is called in the event handler for the DisplayContentsInvalidated event.
00503 void DX::DeviceResources::ValidateDevice()
00504 {
00505     // The D3D Device is no longer valid if the default adapter changed since the device
00506     // was created or if the device has been removed.
00507
00508     // First, get the information for the default adapter from when the device was created.
00509
00510     ComPtr<IDXGIDevice3> dxgiDevice;
00511     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00512
00513     ComPtr<IDXGIAdapter> deviceAdapter;
00514     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00515
00516     ComPtr<IDXGIFactory2> deviceFactory;
00517     DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory)));
00518
00519     ComPtr<IDXGIAdapter1> previousDefaultAdapter;
00520     DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter));
00521
00522     DXGI_ADAPTER_DESC previousDesc;
00523     DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc));
00524
00525     // Next, get the information for the current default adapter.
00526
00527     ComPtr<IDXGIFactory2> currentFactory;
00528     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&currentFactory)));
00529
00530     ComPtr<IDXGIAdapter1> currentDefaultAdapter;
00531     DX::ThrowIfFailed(currentFactory->EnumAdapters1(0, &currentDefaultAdapter));
00532
00533     DXGI_ADAPTER_DESC currentDesc;
00534     DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(&currentDesc));
00535
00536     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00537     // a new D3D device must be created.
00538
00539     if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart ||
00540         previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart ||
00541         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00542     {
00543         // Release references to resources related to the old device.
00544         dxgiDevice = nullptr;
00545         deviceAdapter = nullptr;
00546         deviceFactory = nullptr;
00547         previousDefaultAdapter = nullptr;
00548
00549         // Create a new device and swap chain.
00550         HandleDeviceLost();
00551     }
00552 }
00553
00554 // Recreate all device resources and set them back to the current state.
00555 void DX::DeviceResources::HandleDeviceLost()
00556 {
00557     m_swapChain = nullptr;
00558
00559     if (m_deviceNotify != nullptr)
00560     {
00561         m_deviceNotify->OnDeviceLost();
00562     }
00563
00564     CreateDeviceResources();
00565     m_d2dContext->SetDpi(m_dpi, m_dpi);
00566     CreateWindowSizeDependentResources();
00567
00568     if (m_deviceNotify != nullptr)
00569     {
00570         m_deviceNotify->OnDeviceRestored();
00571     }
00572 }
00573
00574 // Register our DeviceNotify to be informed on device lost and creation.
00575 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00576 {
00577     m_deviceNotify = deviceNotify;
00578 }
00579
00580 // Call this method when the app suspends. It provides a hint to the driver that the app
00581 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00582 void DX::DeviceResources::Trim()
00583 {
00584     ComPtr<IDXGIDevice3> dxgiDevice;
00585     m_d3dDevice.As(&dxgiDevice);
00586
00587     dxgiDevice->Trim();
00588 }
00589
00590 // Present the contents of the swap chain to the screen.
00591 void DX::DeviceResources::Present()
00592 {
00593     // The first argument instructs DXGI to block until VSync, putting the application
00594     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00595     // frames that will never be displayed to the screen.
00596     HRESULT hr = m_swapChain->Present(1, 0);
00597
00598     // Discard the contents of the render target.
00599     // This is a valid operation only when the existing contents will be entirely
00600     // overwritten. If dirty or scroll rects are used, this call should be removed.
00601     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00602
00603     // Discard the contents of the depth stencil.
00604     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00605
00606     // If the device was removed either by a disconnection or a driver upgrade, we
00607     // must recreate all device resources.
00608     if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00609     {
00610         HandleDeviceLost();
00611     }
00612     else
00613     {
00614         DX::ThrowIfFailed(hr);
00615     }
00616 }
00617
00618 // This method determines the rotation between the display device's native Orientation and the
00619 // current display orientation.
00620 DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation()
00621 {
00622     DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
00623
00624     // Note: NativeOrientation can only be Landscape or Portrait even though
00625     // the DisplayOrientations enum has other values.
00626     switch (m_nativeOrientation)
00627     {
00628     case DisplayOrientations::Landscape:
00629         switch (m_currentOrientation)
00630         {
00631         case DisplayOrientations::Landscape:
00632             rotation = DXGI_MODE_ROTATION_IDENTITY;
00633             break;
00634
00635         case DisplayOrientations::Portrait:
00636             rotation = DXGI_MODE_ROTATION_ROTATE270;
00637             break;
00638
00639         case DisplayOrientations::LandscapeFlipped:
00640             rotation = DXGI_MODE_ROTATION_ROTATE180;
00641             break;
00642
00643         case DisplayOrientations::PortraitFlipped:
00644             rotation = DXGI_MODE_ROTATION_ROTATE90;
00645             break;
00646         }
00647         break;
00648
00649     case DisplayOrientations::Portrait:
00650         switch (m_currentOrientation)
00651         {
00652         case DisplayOrientations::Landscape:
00653             rotation = DXGI_MODE_ROTATION_ROTATE90;
00654             break;
00655
00656         case DisplayOrientations::Portrait:
00657             rotation = DXGI_MODE_ROTATION_IDENTITY;
00658             break;
00659
00660         case DisplayOrientations::LandscapeFlipped:
00661             rotation = DXGI_MODE_ROTATION_ROTATE270;
00662             break;
00663
00664         case DisplayOrientations::PortraitFlipped:
00665             rotation = DXGI_MODE_ROTATION_ROTATE180;
00666             break;
00667         }
00668         break;
00669     }
00670     return rotation;
00671 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboardTextInput/cs/Scenario2_ScopedViews.xaml.cs Source File

  • TouchKeyboardTextInput
  • cs

Scenario2_ScopedViews.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013
00014 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00015
00016 namespace SDKTemplate
00017 {
00018     /// <summary>
00019     /// An empty page that can be used on its own or navigated to within a Frame.
00020     /// </summary>
00021     public sealed partial class Scenario2_ScopedViews : Page
00022     {
00023         public Scenario2_ScopedViews()
00024         {
00025             this.InitializeComponent();
00026         }
00027     }
00028 }
Generated on Fri Nov 15 2024 22:21:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario10_CpToClipboard Member List

This is the complete list of members for Scenario10_CpToClipboard, including all inherited members.
CopyToClipboard_Click(object sender, RoutedEventArgs e) | Scenario10_CpToClipboard | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario10_CpToClipboard | [inline, protected]
rootPage | Scenario10_CpToClipboard | [private]
Scenario10_CpToClipboard() | Scenario10_CpToClipboard | [inline]
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScannerProvider/cpp/BarcodeDecoder/pch.h Source File

  • BarcodeScannerProvider
  • cpp
  • BarcodeDecoder

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012
00013 #include <collection.h>
00014 #include <ppltasks.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OrientationSensor/cs/Scenario0_Choose.xaml.cs Source File

  • OrientationSensor
  • cs

Scenario0_Choose.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Devices.Sensors;
00016 using Windows.Foundation;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario0_Choose : Page
00025     {
00026         MainPage rootPage = MainPage.Current;
00027
00028         public Scenario0_Choose()
00029         {
00030             this.InitializeComponent();
00031             var readingTypes = new List<SensorReadingType>()
00032             {
00033                 SensorReadingType.Absolute,
00034                 SensorReadingType.Relative,
00035             };
00036             ReadingTypeComboBox.ItemsSource = readingTypes;
00037             ReadingTypeComboBox.SelectedIndex = readingTypes.IndexOf(rootPage.SensorReadingType);
00038
00039             var optimizationGoals = new List<SensorOptimizationGoal>()
00040             {
00041                 SensorOptimizationGoal.Precision,
00042                 SensorOptimizationGoal.PowerEfficiency,
00043             };
00044             OptimizationGoalComboBox.ItemsSource = optimizationGoals;
00045             OptimizationGoalComboBox.SelectedIndex = optimizationGoals.IndexOf(rootPage.SensorOptimizationGoal);
00046         }
00047
00048         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00049         {
00050             rootPage.SensorReadingType = (SensorReadingType)ReadingTypeComboBox.SelectedValue;
00051             rootPage.SensorOptimizationGoal = (SensorOptimizationGoal)OptimizationGoalComboBox.SelectedValue;
00052         }
00053     }
00054 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SuspensionManager Member List

This is the complete list of members for SuspensionManager, including all inherited members.
_knownTypes | SuspensionManager | [private, static]
_registeredFrames | SuspensionManager | [private, static]
_sessionState | SuspensionManager | [private, static]
FrameSessionBaseKeyProperty | SuspensionManager | [private, static]
FrameSessionStateKeyProperty | SuspensionManager | [private, static]
FrameSessionStateProperty | SuspensionManager | [private, static]
KnownTypes | SuspensionManager | [static]
RegisterFrame(Frame frame, String sessionStateKey, String sessionBaseKey=null) | SuspensionManager | [inline, static]
RestoreAsync(String sessionBaseKey=null) | SuspensionManager | [inline, static]
RestoreFrameNavigationState(Frame frame) | SuspensionManager | [inline, private, static]
SaveAsync() | SuspensionManager | [inline, static]
SaveFrameNavigationState(Frame frame) | SuspensionManager | [inline, private, static]
SessionState | SuspensionManager | [static]
sessionStateFilename | SuspensionManager | [private]
SessionStateForFrame(Frame frame) | SuspensionManager | [inline, static]
UnregisterFrame(Frame frame) | SuspensionManager | [inline, static]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ProtectionLevelSelectorInfo Member List

This is the complete list of members for ProtectionLevelSelectorInfo, including all inherited members.
DisplayName | ProtectionLevelSelectorInfo
ProtectionLevel | ProtectionLevelSelectorInfo
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1 Member List

This is the complete list of members for Scenario1, including all inherited members.
AddPrefix_Click(object sender, RoutedEventArgs e) | Scenario1 | [inline, private]
CreateAdvertiser_Click(object sender, RoutedEventArgs e) | Scenario1 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1 | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario1 | [inline, protected]
RemovePrefix_Click(object sender, RoutedEventArgs e) | Scenario1 | [inline, private]
ResetFields() | Scenario1 | [inline, private]
rootPage | Scenario1 | [private]
Scenario1() | Scenario1 | [inline]
Generated on Fri Nov 15 2024 22:24:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cs/scenario2.xaml.cs Source File

  • ApplicationResources
  • cs

scenario2.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using SDKTemplate;
00015 using System;
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     public sealed partial class Scenario2 : Page
00023     {
00024         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00025         // as NotifyUser()
00026         MainPage rootPage = MainPage.Current;
00027
00028         public Scenario2()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         /// <summary>
00034         /// Invoked when this page is about to be displayed in a Frame.
00035         /// </summary>
00036         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037         /// property is typically used to configure the page.</param>
00038         protected override void OnNavigatedTo(NavigationEventArgs e)
00039         {
00040         }
00041     }
00042 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cpp/Scenario1_Launched.xaml.cpp Source File

  • JumpList
  • cpp

Scenario1_Launched.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_Launched.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Xaml::Controls;
00020 using namespace Windows::UI::Xaml::Navigation;
00021
00022 Scenario1_Launched::Scenario1_Launched()
00023 {
00024     InitializeComponent();
00025 }
00026
00027 void Scenario1_Launched::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00028 {
00029     if (MainPage::Current->LaunchParam != nullptr && !MainPage::Current->LaunchParam->IsEmpty())
00030     {
00031         ActivatedBy->Text = MainPage::Current->LaunchParam;
00032     }
00033     else
00034     {
00035         ActivatedBy->Text = "manual navigation.";
00036     }
00037   MainPage::Current->LaunchParam = nullptr;
00038 }
Generated on Fri Nov 15 2024 22:20:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cpp/Scenario3_CurrentStepCount.xaml.h Source File

  • Pedometer
  • cpp

Scenario3_CurrentStepCount.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_CurrentStepCount.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// 'Current step count' illustration page
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario3_CurrentStepCount sealed
00024     {
00025     public:
00026         Scenario3_CurrentStepCount();
00027     private:
00028         Windows::Devices::Sensors::Pedometer^ pedometer;
00029
00030         SDKTemplate::MainPage^ rootPage;
00031         void GetCurrentButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032     };
00033 }
Generated on Fri Nov 15 2024 22:20:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

TextRenderer Member List

This is the complete list of members for TextRenderer, including all inherited members.
CreateDeviceDependentResources() | TextRenderer |
GetSampler() const | TextRenderer | [inline]
GetTexture() const | TextRenderer | [inline]
m_d2dRenderTarget | TextRenderer | [private]
m_deviceResources | TextRenderer | [private]
m_pointSampler | TextRenderer | [private]
m_renderTargetView | TextRenderer | [private]
m_shaderResourceView | TextRenderer | [private]
m_textFormat | TextRenderer | [private]
m_texture | TextRenderer | [private]
m_textureHeight | TextRenderer | [private]
m_textureWidth | TextRenderer | [private]
m_whiteBrush | TextRenderer | [private]
ReleaseDeviceDependentResources() | TextRenderer |
RenderTextOffscreen(const std::wstring &str) | TextRenderer |
TextRenderer(const std::shared_ptr< DX::DeviceResources > &deviceResources, unsigned int const &textureWidth, unsigned int const &textureHeight) | TextRenderer |
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CaptureFailedEventArgs Member List

This is the complete list of members for CaptureFailedEventArgs, including all inherited members.
__pad0__ | CaptureFailedEventArgs |
_message | CaptureFailedEventArgs |
_message(message) | CaptureFailedEventArgs | [inline]
message | CaptureFailedEventArgs |
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/scenario12.xaml.cpp Source File

  • ApplicationResources
  • cpp

scenario12.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario12.xaml.cpp
00013 // Implementation of the Scenario12 class
00014 //
00015
00016 #include <ppltasks.h>
00017 #include "pch.h"
00018 #include "Scenario12.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::ApplicationModel::Resources::Core;
00026 using namespace concurrency;
00027
00028 Scenario12::Scenario12()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Invoked when this page is about to be displayed in a Frame.
00035 /// </summary>
00036 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037 /// property is typically used to configure the page.</param>
00038 void Scenario12::OnNavigatedTo(NavigationEventArgs^ e)
00039 {
00040     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00041     // as NotifyUser()
00042     rootPage = MainPage::Current;
00043 }
00044
00045
00046 void Scenario12::Scenario12Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00047 {
00048     // Two coding patterns will be used:
00049     //   1. Get a ResourceContext on the UI thread using GetForCurrentView and pass
00050     //      to the non-UI thread
00051     //   2. Get a ResourceContext on the non-UI thread using GetForViewIndependentUse
00052     //
00053     // Two analogous patterns could be used for ResourceLoader instead of ResourceContext.
00054
00055     // pattern 1: get a ResourceContext for the UI thread
00056     ResourceContext^ defaultContextForUiThread = ResourceContext::GetForCurrentView();
00057
00058     // pattern 2: we'll create a view-independent context in the non-UI worker thread
00059
00060
00061     // We need some things in order to display results in the UI (doing that
00062     // for purposes of this sample, to show that work was actually done in the
00063     // worker thread): a pair of vectors to capture data, and a pair of variable
00064     // references to the controls where the results will be displayed (needed to
00065     // pass to the .then lambda).
00066     Platform::Collections::Vector<Platform::String^>^ uiDependentResourceItems = ref new Platform::Collections::Vector<Platform::String^>();
00067     Platform::Collections::Vector<Platform::String^>^ uiIndependentResourceItems = ref new Platform::Collections::Vector<Platform::String^>();
00068     ItemsControl^ viewDependentListControl = ViewDependentResourcesList;
00069     ItemsControl^ viewIndependentListControl = ViewIndependentResourcesList;
00070
00071
00072     // use a worker thread for the heavy lifting so the UI isn't blocked
00073     concurrency::create_task(
00074         Windows::System::Threading::ThreadPool::RunAsync(
00075             ref new Windows::System::Threading::WorkItemHandler(
00076             [defaultContextForUiThread, uiDependentResourceItems, uiIndependentResourceItems](Windows::Foundation::IAsyncAction^ /*action*/)
00077         {
00078             // This is happening asynchronously on a background worker thread,
00079             // not on the UI thread.
00080
00081             ResourceMap^ stringResourceMap = ResourceManager::Current->MainResourceMap->GetSubtree("Resources");
00082
00083
00084             // coding pattern 1: the defaultContextForUiThread variable was created above and has been captured to use here
00085
00086             // coding pattern 2: get a view-independent ResourceContext
00087             ResourceContext^ defaultViewIndependentResourceContext = ResourceContext::GetForViewIndependentUse();
00088
00089             // NOTE: The ResourceContext obtained using GetForViewIndependentUse() has no scale qualifier
00090             // value set. If this ResourceContext is used in its default state to retrieve a resource, that
00091             // will work provided that the resource does not have any scale-qualified variants. But if the
00092             // resource has any scale-qualified variants, then that will fail at runtime.
00093             //
00094             // A scale qualifier value on this ResourceContext can be set programmatically. If that is done,
00095             // then the ResourceContext can be used to retrieve a resource that has scale-qualified variants.
00096             // But if the scale qualifier is reset (e.g., using the ResourceContext::Reset() method), then
00097             // it will return to the default state with no scale qualifier value set, and cannot be used
00098             // to retrieve any resource that has scale-qualified variants.
00099
00100
00101             // simulate processing a number of items
00102             // just using a single string resource: that's sufficient to demonstrate
00103             for (auto i = 0; i < 4; i++)
00104             {
00105                 // pattern 1: use the ResourceContext from the UI thread
00106                 Platform::String^ item1 = stringResourceMap->GetValue("string1", defaultContextForUiThread)->ValueAsString;
00107                 uiDependentResourceItems->Append(item1);
00108
00109                 // pattern 2: use the view-independent ResourceContext
00110                 Platform::String^ item2 = stringResourceMap->GetValue("string1", defaultViewIndependentResourceContext)->ValueAsString;
00111                 uiIndependentResourceItems->Append(item2);
00112             }
00113
00114         }))
00115
00116     ).then([uiDependentResourceItems, uiIndependentResourceItems, viewDependentListControl, viewIndependentListControl]
00117     {
00118         // After the async work is complete, this will happen on the UI thread.
00119
00120         // Display the results in one go. (A more finessed design might add results
00121         // in the UI asynchronously, but that goes beyond what this sample is
00122         // demonstrating.)
00123         viewDependentListControl->ItemsSource = uiDependentResourceItems;
00124         viewIndependentListControl->ItemsSource = uiIndependentResourceItems;
00125     });
00126
00127 }
Generated on Fri Nov 15 2024 22:17:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInfo/cppwinrt/Scenario3_CheckUserConsentGroup.h Source File

  • UserInfo
  • cppwinrt

Scenario3_CheckUserConsentGroup.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_CheckUserConsentGroup.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario3_CheckUserConsentGroup : Scenario3_CheckUserConsentGroupT<Scenario3_CheckUserConsentGroup>
00019     {
00020         Scenario3_CheckUserConsentGroup();
00021
00022         fire_and_forget OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00023         fire_and_forget ShowConsentGroups(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00024
00025     private:
00026         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00027
00028         static hstring EvaluateConsentResult(Windows::System::UserAgeConsentResult consentResult);
00029     };
00030 }
00031
00032 namespace winrt::SDKTemplate::factory_implementation
00033 {
00034     struct Scenario3_CheckUserConsentGroup : Scenario3_CheckUserConsentGroupT <Scenario3_CheckUserConsentGroup, implementation::Scenario3_CheckUserConsentGroup>
00035     {
00036     };
00037 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CashDrawer/cs/SampleConfiguration.cs Source File

  • CashDrawer
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Devices.PointOfService;
00016 using Windows.UI.Xaml.Controls;
00017
00018 namespace SDKTemplate
00019 {
00020     public partial class MainPage : Page
00021     {
00022         public const string FEATURE_NAME = "Cash Drawer";
00023
00024         List<Scenario> scenarios = new List<Scenario>
00025         {
00026             new Scenario() { Title="Drawer Claim and Open", ClassType=typeof(Scenario1_OpenDrawer)},
00027             new Scenario() { Title="Wait for Drawer Close", ClassType=typeof(Scenario2_CloseDrawer)},
00028             new Scenario() { Title="Drawer Retain", ClassType=typeof(Scenario3_MultipleDrawers)}
00029         };
00030     }
00031
00032     public class Scenario
00033     {
00034         public string Title { get; set; }
00035         public Type ClassType { get; set; }
00036     }
00037
00038     public partial class DeviceHelpers
00039     {
00040         // By default, use all connections types.
00041         public static async Task<CashDrawer> GetFirstCashDrawerAsync(PosConnectionTypes connectionTypes = PosConnectionTypes.All)
00042         {
00043             return await DeviceHelpers.GetFirstDeviceAsync(CashDrawer.GetDeviceSelector(connectionTypes), async (id) => await CashDrawer.FromIdAsync(id));
00044         }
00045     }
00046
00047 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserConsentVerifier/cpp/Scenario2_RequestConsent.xaml.h Source File

  • UserConsentVerifier
  • cpp

Scenario2_RequestConsent.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario2_RequestConsent.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario2_RequestConsent sealed
00012     {
00013     public:
00014         Scenario2_RequestConsent();
00015     private:
00016         void RequestConsent_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00017     };
00018 }
Generated on Fri Nov 15 2024 22:21:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DAL::RegisteredUser Member List

This is the complete list of members for DAL::RegisteredUser, including all inherited members.
ActiveChallenge | DAL::RegisteredUser
DeviceName | DAL::RegisteredUser
PublicKey | DAL::RegisteredUser
PublicKeyHash | DAL::RegisteredUser
UserId | DAL::RegisteredUser
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlTransform3DAnimations/cs/SectionView.xaml.cs Source File

  • XamlTransform3DAnimations
  • cs

SectionView.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.IO;
00004 using System.Linq;
00005 using System.Runtime.InteropServices.WindowsRuntime;
00006 using Transform3DAnimations.ViewModels;
00007 using Windows.Foundation;
00008 using Windows.Foundation.Collections;
00009 using Windows.UI.ViewManagement;
00010 using Windows.UI.Xaml;
00011 using Windows.UI.Xaml.Controls;
00012 using Windows.UI.Xaml.Controls.Primitives;
00013 using Windows.UI.Xaml.Data;
00014 using Windows.UI.Xaml.Input;
00015 using Windows.UI.Xaml.Media;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
00019
00020 namespace Transform3DAnimations
00021 {
00022     public sealed partial class SectionView : UserControl
00023     {
00024         private UISettings _uiSettings;
00025
00026         // We will use the property changed handler to create a custom transition.
00027         // See SectionView.xaml and SectionView.OnViewModelChanged.
00028         private static DependencyProperty s_viewModelProperty
00029             = DependencyProperty.Register(
00030                 "ViewModel",
00031                 typeof(HeroArticlesViewModel),
00032                 typeof(SectionView),
00033                 new PropertyMetadata(null, new PropertyChangedCallback(OnViewModelPropertyChanged))
00034                 );
00035
00036         public static DependencyProperty ViewModelProperty
00037         {
00038             get { return s_viewModelProperty; }
00039         }
00040
00041         public HeroArticlesViewModel ViewModel
00042         {
00043             get { return (HeroArticlesViewModel)GetValue(s_viewModelProperty); }
00044             set { SetValue(s_viewModelProperty, value); }
00045         }
00046
00047         public SectionView()
00048         {
00049             this.InitializeComponent();
00050
00051             VisualStateManager.GoToState(this, "ContentSteadyState", false);
00052             _uiSettings = new UISettings();
00053         }
00054
00055
00056         private void UpdateForSizeChanged(double newWidth, double newHeight)
00057         {
00058             // The rotation creates a rectangular prism effect.
00059             // The center of rotation should be at X = Width / 2 and Z = -Width / 2
00060             var centerX = newWidth / 2.0;
00061             RootTransform.CenterX = centerX;
00062             NextContentTransform.CenterX = centerX;
00063
00064             var centerZ = -newWidth / 2.0;
00065             RootTransform.CenterZ = centerZ;
00066             NextContentTransform.CenterZ = centerZ;
00067
00068             // Clip to our left and right bounds so the effect doesn't get too crazy.
00069             ClipGeometry.Rect = new Rect(0.0, -1024.0, newWidth, newHeight + 1024.0);
00070         }
00071
00072         private void LayoutRoot_SizeChanged(object sender, SizeChangedEventArgs e)
00073         {
00074             var newSize = e.NewSize;
00075             UpdateForSizeChanged(newSize.Width, newSize.Height);
00076         }
00077
00078         private void ContentTransitionStoryboard_Completed(object sender, object e)
00079         {
00080             CurrentContentPresenter.Content = NextContentPresenter.Content;
00081             VisualStateManager.GoToState(this, "ContentSteadyState", false);
00082         }
00083
00084         private void OnViewModelChanged(HeroArticlesViewModel oldValue, HeroArticlesViewModel newValue)
00085         {
00086             if (oldValue != null && _uiSettings.AnimationsEnabled)
00087             {
00088                 NextContentPresenter.Content = newValue;
00089                 CurrentContentPresenter.Content = oldValue;
00090
00091                 // Play content transition
00092                 VisualStateManager.GoToState(this, "ContentTransitionState", true);
00093             }
00094             else
00095             {
00096                 CurrentContentPresenter.Content = newValue;
00097             }
00098         }
00099
00100         private static void OnViewModelPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
00101         {
00102             ((SectionView)o).OnViewModelChanged((HeroArticlesViewModel)e.OldValue, (HeroArticlesViewModel)e.NewValue);
00103         }
00104
00105         private void ArticleTapped(object sender, TappedRoutedEventArgs e)
00106         {
00107             if (ArticleSelected != null)
00108             {
00109                 ArticleSelected(this, (ArticleViewModel)((FrameworkElement)e.OriginalSource).DataContext);
00110             }
00111         }
00112
00113         public event TypedEventHandler<object, ArticleViewModel> ArticleSelected;
00114     }
00115 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/LiveTiles/AdaptiveTemplates/Images/Source/FromInternet/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • LiveTiles
  • AdaptiveTemplates
  • Images
  • Source
  • FromInternet

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Notifications.Helpers;
00002 using System;
00003 using Windows.Data.Xml.Dom;
00004 using Windows.UI.Notifications;
00005 using Windows.UI.StartScreen;
00006 using Windows.UI.Xaml;
00007 using Windows.UI.Xaml.Controls;
00008
00009 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00010
00011 namespace Notifications.ScenarioPages.LiveTiles.AdaptiveTemplates.Images.Source.FromInternet
00012 {
00013     /// <summary>
00014     /// An empty page that can be used on its own or navigated to within a Frame.
00015     /// </summary>
00016     public sealed partial class ScenarioElement : UserControl
00017     {
00018         public ScenarioElement()
00019         {
00020             this.InitializeComponent();
00021         }
00022
00023         private string _tileId;
00024
00025         private async void ButtonPinSecondaryTile_Click(object sender, RoutedEventArgs e)
00026         {
00027             base.IsEnabled = false;
00028
00029             _tileId = DateTime.Now.Ticks.ToString();
00030
00031             string ImageUrl = "http://c.s-microsoft.com/en-us/CMSImages/windows_symbol.png?version=f1f9db81-67ef-8866-1be3-d5b1c1bb0b26";
00032
00033             SecondaryTile tile = TilesHelper.GenerateSecondaryTile("Web Image");
00034             await tile.RequestCreateAsync();
00035
00036             string tileXmlString =
00037                 "<tile>"
00038                 + "<visual>"
00039                 + "<binding template='TileSmall'>"
00040                 + "<image src='" + ImageUrl + "' alt='Web image'/>"
00041                 + "</binding>"
00042                 + "<binding template='TileMedium'>"
00043                 + "<image src='" + ImageUrl + "' alt='Web image'/>"
00044                 + "</binding>"
00045                 + "<binding template='TileWide'>"
00046                 + "<image src='" + ImageUrl + "' alt='Web image'/>"
00047                 + "</binding>"
00048                 + "<binding template='TileLarge'>"
00049                 + "<image src='" + ImageUrl + "' alt='Web image'/>"
00050                 + "</binding>"
00051                 + "</visual>"
00052                 + "</tile>";
00053
00054             XmlDocument xmlDoc = new XmlDocument();
00055             xmlDoc.LoadXml(tileXmlString);
00056             TileNotification notifyTile = new TileNotification(xmlDoc);
00057             TileUpdateManager.CreateTileUpdaterForSecondaryTile(tile.TileId).Update(notifyTile);
00058
00059             base.IsEnabled = true;
00060         }
00061     }
00062 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ExtendedExecution/cs/Scenario1_UnspecifiedReason.xaml.cs Source File

  • ExtendedExecution
  • cs

Scenario1_UnspecifiedReason.xaml.cs

Go to the documentation of this file.
00001 ﻿
00002 //*********************************************************
00003 //
00004 // Copyright (c) Microsoft. All rights reserved.
00005 // This code is licensed under the MIT License (MIT).
00006 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00007 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00008 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00009 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00010 //
00011 //*********************************************************
00012
00013 using System;
00014 using System.Threading;
00015 using System.Threading.Tasks;
00016 using Windows.ApplicationModel.Background;
00017 using Windows.ApplicationModel.ExtendedExecution;
00018 using Windows.UI.Core;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// Page containing the Extended Execution Unspecified Reason scenario functions.
00027     /// </summary>
00028     public sealed partial class UnspecifiedReason : Page
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         private MainPage rootPage = MainPage.Current;
00033
00034         private ExtendedExecutionSession session = null;
00035         private Timer periodicTimer = null;
00036
00037         public UnspecifiedReason()
00038         {
00039             this.InitializeComponent();
00040         }
00041
00042         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00043         {
00044             // End the Extended Execution Session.
00045             // Only one extended execution session can be held by an application at one time.
00046             ClearExtendedExecution();
00047         }
00048
00049         void ClearExtendedExecution()
00050         {
00051             if (session != null)
00052             {
00053                 session.Revoked -= SessionRevoked;
00054                 session.Dispose();
00055                 session = null;
00056             }
00057
00058             if (periodicTimer != null)
00059             {
00060                 periodicTimer.Dispose();
00061                 periodicTimer = null;
00062             }
00063         }
00064
00065         private void UpdateUI()
00066         {
00067             if (session == null)
00068             {
00069                 Status.Text = "Not requested";
00070                 RequestButton.IsEnabled = true;
00071                 CloseButton.IsEnabled = false;
00072             }
00073             else
00074             {
00075                 Status.Text = "Requested";
00076                 RequestButton.IsEnabled = false;
00077                 CloseButton.IsEnabled = true;
00078             }
00079         }
00080
00081         private async void BeginExtendedExecution()
00082         {
00083             // The previous Extended Execution must be closed before a new one can be requested.
00084             // This code is redundant here because the sample doesn't allow a new extended
00085             // execution to begin until the previous one ends, but we leave it here for illustration.
00086             ClearExtendedExecution();
00087
00088             var newSession = new ExtendedExecutionSession();
00089             newSession.Reason = ExtendedExecutionReason.Unspecified;
00090             newSession.Description = "Raising periodic toasts";
00091             newSession.Revoked += SessionRevoked;
00092             ExtendedExecutionResult result = await newSession.RequestExtensionAsync();
00093
00094             switch (result)
00095             {
00096                 case ExtendedExecutionResult.Allowed:
00097                     rootPage.NotifyUser("Extended execution allowed.", NotifyType.StatusMessage);
00098                     session = newSession;
00099                     periodicTimer = new Timer(OnTimer, DateTime.Now, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10));
00100                     break;
00101
00102                 default:
00103                 case ExtendedExecutionResult.Denied:
00104                     rootPage.NotifyUser("Extended execution denied.", NotifyType.ErrorMessage);
00105                     newSession.Dispose();
00106                     break;
00107             }
00108             UpdateUI();
00109         }
00110
00111         private void OnTimer(object state)
00112         {
00113             var startTime = (DateTime)state;
00114             var runningTime = Math.Round((DateTime.Now - startTime).TotalSeconds, 0);
00115             MainPage.DisplayToast($"Extended execution has been active for {runningTime} seconds");
00116         }
00117
00118         private void EndExtendedExecution()
00119         {
00120             ClearExtendedExecution();
00121             UpdateUI();
00122         }
00123
00124         private async void SessionRevoked(object sender, ExtendedExecutionRevokedEventArgs args)
00125         {
00126             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00127             {
00128                 switch (args.Reason)
00129                 {
00130                     case ExtendedExecutionRevokedReason.Resumed:
00131                         rootPage.NotifyUser("Extended execution revoked due to returning to foreground.", NotifyType.StatusMessage);
00132                         break;
00133
00134                     case ExtendedExecutionRevokedReason.SystemPolicy:
00135                         rootPage.NotifyUser("Extended execution revoked due to system policy.", NotifyType.StatusMessage);
00136                         break;
00137                 }
00138
00139                 EndExtendedExecution();
00140             });
00141         }
00142     }
00143 }
Generated on Fri Nov 15 2024 22:19:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Nfc/NfcHceBackgroundTask/Utilities.h Source File

  • Nfc
  • NfcHceBackgroundTask

Utilities.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 Platform::String^ GetCurrentTimeString();
00015
00016 LPBYTE PointerFromIBuffer(_In_ Windows::Storage::Streams::IBuffer^ buffer, _Out_opt_ DWORD* pcbLength);
00017 Windows::Storage::Streams::IBuffer^ IBufferFromPointer(_In_ LPBYTE pbData, _In_ DWORD cbData);
00018 Windows::Storage::Streams::IBuffer^ IBufferFromArray(_In_ Platform::Array<unsigned char>^ data);
00019 std::wstring ByteArrayToString(_In_ Platform::Array<byte>^ byteArray);
00020
00021 HRESULT ParseApdu(_In_ BYTE* pbCommandApdu, _In_ DWORD cbCommandApdu, _Out_ USHORT* pusClaIns, _Out_ BYTE* pbP1, _Out_ BYTE* pbP2, _Out_ BYTE** ppbPayload, _Out_ DWORD* pcbPayload, _Out_ DWORD* pcbLE);
00022
00023 Concurrency::task<Platform::Array<byte>^> ReadAndUnprotectFileAsync(Platform::String^ filename);
00024 Concurrency::task<Windows::Storage::Streams::IBuffer^> ReadFileToBufferAsync(Platform::String^ filename);
00025
00026 void AppendFile(Platform::String^ filename, Platform::String^ data);
00027
00028 void ChkHR(HRESULT hr);
00029
00030 #ifndef SAFE_DELETEARRAY
00031 #define SAFE_DELETEARRAY(x) if ((x) != nullptr) { delete [] (x); (x) = nullptr; }
00032 #endif
00033
00034 #ifndef SAFE_DELETE
00035 #define SAFE_DELETE(x) if ((x) != nullptr) { delete (x); (x) = nullptr; }
00036 #endif
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/SetErrorMessage.xaml.h Source File

  • ShareSource
  • cpp

SetErrorMessage.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // FailWithError.xaml.h
00014 // Declaration of the FailWithError class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "SharePage.h"
00021 #include "SetErrorMessage.g.h"
00022 #include "MainPage.xaml.h"
00023
00024 namespace SDKTemplate
00025 {
00026     [Windows::Foundation::Metadata::WebHostHidden]
00027     public ref class SetErrorMessage sealed
00028     {
00029     public:
00030         SetErrorMessage();
00031
00032     protected:
00033         virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request) override;
00034     };
00035 }
Generated on Fri Nov 15 2024 22:21:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RadioModel Member List

This is the complete list of members for RadioModel, including all inherited members.
dispatcher | RadioModel | [private]
isEnabled | RadioModel | [private]
IsEnabled | RadioModel |
IsRadioOn | RadioModel |
Name | RadioModel |
NotifyPropertyChanged([CallerMemberName] string propertyName="") | RadioModel | [inline, private]
PropertyChanged | RadioModel |
radio | RadioModel | [private]
Radio_StateChanged(Radio sender, object args) | RadioModel | [inline, private]
RadioModel(Radio radio, CoreDispatcher dispatcher) | RadioModel | [inline]
SetRadioState(bool isRadioOn) | RadioModel | [inline, private]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Magnetometer/cs/SampleConfiguration.cs Source File

  • Magnetometer
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Magnetometer";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title = "Data Events", ClassType = typeof(SDKTemplate.Scenario1_DataEvents) },
00025             new Scenario() { Title = "Polling", ClassType = typeof(SDKTemplate.Scenario2_Polling) },
00026         };
00027     }
00028
00029     public class Scenario
00030     {
00031         public string Title { get; set; }
00032         public Type ClassType { get; set; }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContextMenu/cpp/Scenario2.xaml.cpp Source File

  • ContextMenu
  • cpp

Scenario2.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario2.xaml.cpp
00013 // Implementation of the Scenario2 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario2.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::ApplicationModel::DataTransfer;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::UI::Popups;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Media;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 Scenario2::Scenario2()
00032 {
00033     InitializeComponent();
00034     rootPage = MainPage::Current;
00035 }
00036
00037 // returns a rect for selected text in a single line.
00038 // if no text is selected, returns caret location
00039 // textbox should not be empty
00040 Rect Scenario2::GetTextboxSelectionRect(TextBox^ textbox)
00041 {
00042     Rect rectFirst, rectLast;
00043     if (textbox->SelectionStart == textbox->Text->Length())
00044     {
00045         rectFirst = textbox->GetRectFromCharacterIndex(textbox->SelectionStart - 1, true);
00046     }
00047     else
00048     {
00049         rectFirst = textbox->GetRectFromCharacterIndex(textbox->SelectionStart, false);
00050     }
00051
00052     const int lastIndex = textbox->SelectionStart + textbox->SelectionLength;
00053     if (lastIndex == textbox->Text->Length())
00054     {
00055         rectLast = textbox->GetRectFromCharacterIndex(lastIndex - 1, true);
00056     }
00057     else
00058     {
00059         rectLast = textbox->GetRectFromCharacterIndex(lastIndex, false);
00060     }
00061
00062     Rect selectionRect = RectHelper::Union(rectFirst, rectLast);
00063
00064     GeneralTransform^ transform = textbox->TransformToVisual(nullptr);
00065     return transform->TransformBounds(selectionRect);
00066 }
00067
00068 void Scenario2::ReadOnlyTextBox_ContextMenuOpening(Object^ sender, ContextMenuEventArgs^ e)
00069 {
00070     e->Handled = true;
00071     TextBox^ textbox = safe_cast<TextBox^>(sender);
00072
00073     if (textbox->SelectionLength > 0)
00074     {
00075         // Create a menu and add commands specifying an id value for each instead of a delegate.
00076         auto menu = ref new PopupMenu();
00077
00078         menu->Commands->Append(ref new UICommand("Copy",      nullptr, PropertyValue::CreateInt32(1)));
00079         menu->Commands->Append(ref new UICommandSeparator());
00080         menu->Commands->Append(ref new UICommand("Highlight", nullptr, PropertyValue::CreateInt32(2)));
00081         menu->Commands->Append(ref new UICommand("Look up",   nullptr, PropertyValue::CreateInt32(3)));
00082
00083         // We don't want to obscure content, so pass in a rectangle representing the selection area.
00084         // NOTE: this code only handles textboxes with a single line. If a textbox has multiple lines,
00085         //       then the context menu should be placed at cursor/pointer location by convention.
00086         Rect rectContent = GetTextboxSelectionRect(textbox);
00087         String^ selectedText = textbox->SelectedText;
00088         create_task(menu->ShowForSelectionAsync(rectContent)).then([this, selectedText](IUICommand^ command)
00089         {
00090             if (command != nullptr)
00091             {
00092                 int const id = safe_cast<IBox<int>^>(command->Id)->Value;
00093                 switch (id)
00094                 {
00095                 case 1:
00096                     {
00097                         auto dataPackage = ref new DataPackage();
00098                         dataPackage->SetText(selectedText);
00099                         Clipboard::SetContent(dataPackage);
00100                         OutputTextBlock->Text = "'" + command->Label + "'(" + id.ToString() + ")" + " selected; '" + selectedText + "' copied to clipboard";
00101                     }
00102                     break;
00103
00104                 case 2:
00105                     OutputTextBlock->Text = "'" + command->Label + "'(" + id.ToString() + ")" + " selected";
00106                     break;
00107
00108                 case 3:
00109                     OutputTextBlock->Text = "'" + command->Label + "'(" + id.ToString() + ")" + " selected";
00110                     break;
00111                 }
00112             }
00113             else
00114             {
00115                 OutputTextBlock->Text = "Context menu dismissed";
00116             }
00117         });
00118         OutputTextBlock->Text = "Context menu shown";
00119     }
00120     else
00121     {
00122         OutputTextBlock->Text = "Context menu not shown because there is no text selected";
00123     }
00124 }
Generated on Fri Nov 15 2024 22:17:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cpp/BackgroundTransfer/Scenario5_RandomAccess.xaml.cpp Source File

  • BackgroundTransfer
  • cpp
  • BackgroundTransfer

Scenario5_RandomAccess.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario5_RandomAccess.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Networking::BackgroundTransfer;
00022 using namespace Windows::Storage;
00023 using namespace Windows::Storage::Streams;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Navigation;
00028 using namespace Windows::Web;
00029
00030 Scenario5_RandomAccess::Scenario5_RandomAccess()
00031 {
00032     InitializeComponent();
00033 }
00034
00035 void Scenario5_RandomAccess::OnNavigatedTo(NavigationEventArgs^ e)
00036 {
00037     // An application must enumerate downloads when it gets started to prevent stale downloads/uploads.
00038     // Typically this can be done in the App class by overriding OnLaunched() and checking for
00039     // "args.Kind == ActivationKind.Launch" to detect an actual app launch.
00040     // We do it here in the sample to keep the sample code consolidated.
00041     // Note that for this specific scenario we are not interested in downloads from previous instances, so
00042     // we just enumerate all downloads from previous instances and cancel them immediately.
00043     CancelActiveDownloadsAsync();
00044 }
00045
00046 void Scenario5_RandomAccess::OnNavigatedFrom(NavigationEventArgs^ e)
00047 {
00048     // Cancel any outstanding reads.
00049     readCancellationTokenSource.cancel();
00050
00051 }
00052
00053 task<void> Scenario5_RandomAccess::CancelActiveDownloadsAsync()
00054 {
00055     return create_task(BackgroundDownloader::GetCurrentDownloadsAsync()).then([this](task<IVectorView<DownloadOperation^>^> downloadTask)
00056     {
00057         IVectorView<DownloadOperation^>^ downloads;
00058         try
00059         {
00060             downloads = downloadTask.get();
00061         }
00062         catch (Exception^ ex)
00063         {
00064             if (IsWebException("Discovery error", ex))
00065             {
00066                 // Don't worry if the old downloads encountered web exceptions.
00067                 return task_from_result();
00068             }
00069             throw;
00070         }
00071
00072         // If previous sample instances/scenarios started transfers that haven't completed yet, cancel them now
00073         // so that we can start this scenario cleanly.
00074         if (downloads->Size > 0)
00075         {
00076             cancellation_token_source canceledToken;
00077             canceledToken.cancel();
00078
00079             std::vector<task<void>> taskList;
00080             for (DownloadOperation^ downloadOperation : downloads)
00081             {
00082                 taskList.push_back(create_task(downloadOperation->AttachAsync(), canceledToken.get_token()).then([](task<DownloadOperation^> previousTask)
00083                 {
00084                     try
00085                     {
00086                         previousTask.get();
00087                     }
00088                     catch (task_canceled&)
00089                     {
00090                     }
00091                 }));
00092             }
00093
00094             return when_all(taskList.begin(), taskList.end()).then([this, downloads]()
00095             {
00096                 rootPage->NotifyUser("Canceled " + downloads->Size.ToString() + " downloads.", NotifyType::StatusMessage);
00097             });
00098         }
00099         return task_from_result();
00100     });
00101 }
00102
00103 void Scenario5_RandomAccess::PauseDownload_Click(Object^ sender, RoutedEventArgs^ e)
00104 {
00105     if (download != nullptr)
00106     {
00107         download->Pause();
00108         pauseDownloadButton->IsEnabled = false;
00109         resumeDownloadButton->IsEnabled = true;
00110     }
00111 }
00112
00113 void Scenario5_RandomAccess::ResumeDownload_Click(Object^ sender, RoutedEventArgs^ e)
00114 {
00115     if (download != nullptr)
00116     {
00117         download->Resume();
00118         pauseDownloadButton->IsEnabled = true;
00119         resumeDownloadButton->IsEnabled = false;
00120     }
00121 }
00122
00123 void Scenario5_RandomAccess::SeekDownload_Click(Object^ sender, RoutedEventArgs^ e)
00124 {
00125     // Cancel the ongoing read operation (if any).
00126     if (readOperation != task<IBuffer^>())
00127     {
00128         readCancellationTokenSource.cancel();
00129
00130         // Re-create the cancellation_token_source for future reads.
00131         readCancellationTokenSource = cancellation_token_source();
00132     }
00133
00134     if (randomAccessStream != nullptr)
00135     {
00136         // Update the stream's seek position to the user-selected one.
00137         // The new seek position will take effect on the next ReadAsync operation.
00138         auto seekPositionInMegaBytes = static_cast<unsigned>(seekSlider->Value);
00139         unsigned seekPositionInBytes = seekPositionInMegaBytes * BytesPerMegaByte;
00140         randomAccessStream->Seek(seekPositionInBytes);
00141     }
00142 }
00143
00144 String^ Scenario5_RandomAccess::FormatDownloadedRanges(IIterable<BackgroundTransferFileRange>^ ranges)
00145 {
00146     String^ result = "";
00147     for (const BackgroundTransferFileRange& range : ranges)
00148     {
00149         if (result != "")
00150         {
00151             result += ", ";
00152         }
00153
00154         result += range.Offset.ToString() + "-" + (range.Offset + range.Length - 1).ToString();
00155     }
00156
00157     if (result == "")
00158     {
00159         result = "None";
00160     }
00161     return result;
00162 }
00163
00164 void Scenario5_RandomAccess::OnDownloadProgress(IAsyncOperationWithProgress<DownloadOperation^, DownloadOperation^>^ sender, DownloadOperation^ progress)
00165 {
00166     // We capture a snapshot of DownloadOperation.Progress because
00167     // it is is updated in real-time while the operation is ongoing.
00168     BackgroundDownloadProgress currentProgress = progress->Progress;
00169
00170     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, currentProgress]()
00171     {
00172         // Prepare the progress message to display in the UI.
00173         uint64_t percent = 100;
00174         if (currentProgress.TotalBytesToReceive > 0)
00175         {
00176             percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive;
00177         }
00178         DownloadedStatusText->Text = currentProgress.Status.ToString() + " - " + percent.ToString() + "% downloaded.";
00179     }));
00180 }
00181
00182 void Scenario5_RandomAccess::OnRangesDownloaded(DownloadOperation^ sender, BackgroundTransferRangesDownloadedEventArgs^ args)
00183 {
00184     // BackgroundTransfer will wait for the app's RangesDownloaded event handlers to finish executing before
00185     // triggering the next RangesDownloaded event. Any download progress made while the app's handlers are
00186     // executing get coalesced into a single RangesDownloaded event.
00187     //
00188     // When calling async APIs inside this handler, we must first take a deferral and then complete it once we
00189     // are done processing the event. Otherwise, BackgroundTransfer will assume that the handler is done executing
00190     // as soon as the synchronous portion of the handler returns, even if there are still tasks running.
00191     auto deferral = args->GetDeferral();
00192
00193     // AddedRanges tells you which ranges were downloaded since the last RangesDownloaded event.
00194     // To get the full list of downloaded ranges, use the GetDownloadedRanges method.
00195     String^ message = " Newly-downloaded ranges: " + FormatDownloadedRanges(args->AddedRanges);
00196
00197     // A download may restart if the server contents changed while the download is in progress.
00198     if (args->WasDownloadRestarted)
00199     {
00200         message += " (download was restarted)";
00201     }
00202
00203     // Wait for the UI update to happen before completing the deferral. That way, we can be certain that
00204     // the next RangesDownloaded event will not get triggered midway through the UI update.
00205     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, sender, message, deferral]()
00206     {
00207         DownloadedRangesText->Text = FormatDownloadedRanges(sender->GetDownloadedRanges());
00208         rootPage->NotifyUser(message, NotifyType::StatusMessage);
00209         deferral->Complete();
00210     }));
00211 }
00212
00213 void Scenario5_RandomAccess::StartDownload_Click(Object^ sender, RoutedEventArgs^ e)
00214 {
00215     // Reset the output whenever a new download attempt begins.
00216     DownloadedInfoText->Text = "";
00217     DownloadedStatusText->Text = "";
00218     DownloadedRangesText->Text = "None";
00219     PreviousReadText->Text = "";
00220     CurrentReadText->Text = "";
00221
00222     Uri^ source;
00223     if (!rootPage->TryGetUri(serverAddressField->Text, &source))
00224     {
00225         return;
00226     }
00227
00228     String^ destination = StringTrimmer::Trim(fileNameField->Text);
00229     if (destination == "")
00230     {
00231         rootPage->NotifyUser("A local file name is required.", NotifyType::ErrorMessage);
00232         return;
00233     }
00234
00235     create_task(KnownFolders::GetFolderForUserAsync(nullptr /* current user */, KnownFolderId::PicturesLibrary))
00236         .then([this, destination](StorageFolder^ picturesLibrary) {
00237         return picturesLibrary->CreateFileAsync(destination, CreationCollisionOption::GenerateUniqueName);
00238     }).then([this, source](task<StorageFile^> previousTask)
00239     {
00240         StorageFile^ destinationFile;
00241         try
00242         {
00243             destinationFile = previousTask.get();
00244         }
00245         catch (Exception^ ex)
00246         {
00247             rootPage->NotifyUser("Error while creating file: " + ex->Message, NotifyType::ErrorMessage);
00248             return task_from_result();
00249         }
00250
00251         BackgroundDownloader^ downloader = ref new BackgroundDownloader();
00252         download = downloader->CreateDownload(source, destinationFile);
00253
00254         // Apps need to set the IsRandomAccessRequired boolean property to TRUE (default is FALSE) before they
00255         // call StartAsync() on a DownloadOperation object if they want to use the random access feature. After
00256         // opting into "random access" mode, GetResultRandomAccessStreamReference() can be called.
00257         //
00258         // Setting IsRandomAccessRequired to TRUE before starting the download is necessary because the
00259         // server-side requirements for Random Access functionality are stricter than for regular (sequential)
00260         // downloads, so BackgroundTransfer needs to know the app's intentions in advance. That way, it can fail
00261         // the transfer up front if the server does not satisfy those additional requirements (e.g., HTTP range
00262         // header support).
00263         download->IsRandomAccessRequired = true;
00264
00265         // Subscribe to RangesDownloaded notifications.
00266         download->RangesDownloaded += ref new TypedEventHandler<DownloadOperation^, BackgroundTransferRangesDownloadedEventArgs^>(this, &Scenario5_RandomAccess::OnRangesDownloaded);
00267
00268         DownloadedInfoText->Text = "Downloading to " + destinationFile->Name + ", " + download->Guid.ToString();
00269
00270         // Start the download and read partially-downloaded content while the transfer is still ongoing.
00271         return StartDownloadAndReadContentsAsync();
00272     });
00273 }
00274
00275 task<void> Scenario5_RandomAccess::StartDownloadAndReadContentsAsync()
00276 {
00277     // Retrieve a random access stream from the download operation. Every OpenReadAsync() operation returns
00278     // a new stream instance that is independent of previous ones (i.e., the seek position of one stream
00279     // isn't affected by calls on another stream).
00280     //
00281     // This sample demonstrates the direct usage of a DownloadOperation's random access stream and its
00282     // effects on the ongoing transfer. However, bear in mind that there are a variety of operations
00283     // that can manage the stream on the app's behalf for specific scenarios. For instance, a
00284     // DownloadOperation pointing to a video URL can be consumed by the MediaPlayer class in four easy
00285     // steps:
00286     //
00287     // auto randomAccessStreamReference = download->GetResultRandomAccessStreamReference();
00288     // create_task(randomAccessStreamReference->OpenReadAsync()).then([](IRandomAccessStream^ stream)
00289     // {
00290     //     auto mediaPlayer = ref new Windows::Media::Playback::MediaPlayer();
00291     //     mediaPlayer->Source = Windows::Media::Core::MediaSource::CreateFromStream(stream, stream->ContentType);
00292     // }
00293
00294     auto randomAccessStreamReference = download->GetResultRandomAccessStreamReference();
00295     return create_task(randomAccessStreamReference->OpenReadAsync()).then([this](IRandomAccessStreamWithContentType^ stream)
00296     {
00297         randomAccessStream = stream;
00298
00299         // Start the download. If the server doesn't support random access, the download will fail
00300         // with WebErrorStatus.InsufficientRangeSupport or WebErrorStatus.MissingContentLengthSupport.
00301         IAsyncOperationWithProgress<DownloadOperation^, DownloadOperation^>^ downloadOperation = download->StartAsync();
00302         downloadOperation->Progress = ref new AsyncOperationProgressHandler<DownloadOperation^, DownloadOperation^>(this, &Scenario5_RandomAccess::OnDownloadProgress);
00303
00304         task<DownloadOperation^> downloadTask = create_task(downloadOperation);
00305
00306         startDownloadButton->IsEnabled = false;
00307         pauseDownloadButton->IsEnabled = true;
00308
00309         // Read data while the download is still ongoing. Use a 1 MB read buffer for that purpose.
00310         auto readBuffer = ref new Buffer(BytesPerMegaByte);
00311
00312         return ReadStreamAsync(downloadTask, readBuffer).then([this, downloadTask]()
00313         {
00314             // Wait for the download to complete.
00315             return downloadTask;
00316         });
00317     }).then([this](DownloadOperation^)
00318     {
00319         rootPage->NotifyUser("Download completed successfully", NotifyType::StatusMessage);
00320     }).then([this](task<void> precedingTask)
00321     {
00322         try
00323         {
00324             precedingTask.get();
00325         }
00326         catch (Exception^ ex)
00327         {
00328             // Abandon the operation if a web exception occurs.
00329             if (IsWebException("Execution error", ex))
00330             {
00331                 return;
00332             }
00333             throw;
00334         }
00335     }).then([this]()
00336     {
00337         download = nullptr;
00338         randomAccessStream = nullptr;
00339         readOperation = task<IBuffer^>();
00340
00341         startDownloadButton->IsEnabled = true;
00342         pauseDownloadButton->IsEnabled = false;
00343         resumeDownloadButton->IsEnabled = false;
00344     });
00345 }
00346
00347 task<void> Scenario5_RandomAccess::ReadStreamAsync(task<DownloadOperation^> downloadTask, Buffer^ readBuffer)
00348 {
00349     if (downloadTask.is_done())
00350     {
00351         return task_from_result();
00352     }
00353
00354     uint64_t readOffsetInBytes = randomAccessStream->Position;
00355
00356     PreviousReadText->Text = CurrentReadText->Text;
00357     CurrentReadText->Text = "Reading from offset " + readOffsetInBytes.ToString();
00358
00359     readOperation = create_task(randomAccessStream->ReadAsync(readBuffer, readBuffer->Capacity, InputStreamOptions::None),
00360         readCancellationTokenSource.get_token());
00361
00362     // Update the UI to show the current read's position.
00363     currentPositionSlider->Value = static_cast<double>(readOffsetInBytes / BytesPerMegaByte);
00364
00365     // Wait for the read to complete.
00366     return readOperation.then([this](IBuffer^ bytesRead)
00367     {
00368         CurrentReadText->Text += ", completed with " + bytesRead->Length.ToString() + " bytes";
00369
00370         // At this point, a real app would process the 'bytesRead' data to do something interesting
00371         // with it (e.g., display video and/or play audio).
00372
00373         if (randomAccessStream->Position >= randomAccessStream->Size)
00374         {
00375             // We have reached EOF. Wrap around to the beginning while we wait for the download to complete.
00376             randomAccessStream->Seek(0);
00377         }
00378     }).then([this, downloadTask, readBuffer](task<void> precedingTask)
00379     {
00380         try
00381         {
00382             precedingTask.get();
00383         }
00384         catch (task_canceled&)
00385         {
00386             // The ongoing read was canceled by SeekDownload_Click(...) in order for a new download
00387             // position to take effect immediately.
00388             CurrentReadText->Text += ", cancelled.";
00389         }
00390         return ReadStreamAsync(downloadTask, readBuffer);
00391     });
00392 }
00393
00394 bool Scenario5_RandomAccess::IsWebException(String^ title, Exception^ ex)
00395 {
00396     WebErrorStatus error = BackgroundTransferError::GetStatus(ex->HResult);
00397     bool result = (error != WebErrorStatus::Unknown);
00398     String^ message = result ? error.ToString() : ex->Message;
00399     if (download == nullptr)
00400     {
00401         rootPage->NotifyUser(title + ": " + message, NotifyType::ErrorMessage);
00402     }
00403     else
00404     {
00405         rootPage->NotifyUser(download->Guid.ToString() + " - " + title + ": " + message, NotifyType::ErrorMessage);
00406     }
00407
00408     return result;
00409 }
Generated on Fri Nov 15 2024 22:18:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cs/SharePage.cs Source File

  • ShareSource
  • cs

SharePage.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.DataTransfer;
00014 using Windows.Foundation;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     public abstract class SharePage : Page
00022     {
00023         protected MainPage rootPage = MainPage.Current;
00024         private DataTransferManager dataTransferManager;
00025
00026         protected override void OnNavigatedTo(NavigationEventArgs e)
00027         {
00028             // Register the current page as a share source.
00029             this.dataTransferManager = DataTransferManager.GetForCurrentView();
00030             this.dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.OnDataRequested);
00031
00032             // Request to be notified when the user chooses a share target app.
00033             this.dataTransferManager.TargetApplicationChosen += OnTargetApplicationChosen;
00034         }
00035
00036         protected override void OnNavigatedFrom(NavigationEventArgs e)
00037         {
00038             // Unregister our event handlers.
00039             this.dataTransferManager.DataRequested -= new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.OnDataRequested);
00040             this.dataTransferManager.TargetApplicationChosen -= OnTargetApplicationChosen;
00041         }
00042
00043         // When share is invoked (by the user or programatically) the event handler we registered will be called to populate the datapackage with the
00044         // data to be shared.
00045         private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
00046         {
00047             // Register to be notified if the share operation completes.
00048             e.Request.Data.ShareCompleted += OnShareCompleted;
00049
00050             // Call the scenario specific function to populate the datapackage with the data to be shared.
00051             if (GetShareContent(e.Request))
00052             {
00053                 // Out of the datapackage properties, the title is required. If the scenario completed successfully, we need
00054                 // to make sure the title is valid since the sample scenario gets the title from the user.
00055                 if (String.IsNullOrEmpty(e.Request.Data.Properties.Title))
00056                 {
00057                     e.Request.FailWithDisplayText(MainPage.MissingTitleError);
00058                 }
00059             }
00060         }
00061
00062         private void OnTargetApplicationChosen(DataTransferManager sender, TargetApplicationChosenEventArgs e)
00063         {
00064             this.rootPage.NotifyUser($"User chose {e.ApplicationName}", NotifyType.StatusMessage);
00065         }
00066
00067         private void OnShareCompleted(DataPackage sender, ShareCompletedEventArgs e)
00068         {
00069             string shareCompletedStatus = "Shared successfully. ";
00070
00071             // Typically, this information is not displayed to the user because the
00072             // user already knows which share target was selected.
00073             if (!String.IsNullOrEmpty(e.ShareTarget.AppUserModelId))
00074             {
00075                 // The user picked an app.
00076                 shareCompletedStatus += $"Target: App \"{e.ShareTarget.AppUserModelId}\"";
00077             }
00078             else if (e.ShareTarget.ShareProvider != null)
00079             {
00080                 // The user picked a ShareProvider.
00081                 shareCompletedStatus += $"Target: Share Provider \"{e.ShareTarget.ShareProvider.Title}\"";
00082             }
00083
00084             this.rootPage.NotifyUser(shareCompletedStatus, NotifyType.StatusMessage);
00085         }
00086
00087         protected void ShowUIButton_Click(object sender, RoutedEventArgs e)
00088         {
00089             // If the user clicks the share button, invoke the share flow programatically.
00090             DataTransferManager.ShowShareUI();
00091         }
00092
00093         // This function is implemented by each scenario to share the content specific to that scenario (text, link, image, etc.).
00094         protected abstract bool GetShareContent(DataRequest request);
00095
00096         protected Uri ApplicationLink
00097         {
00098             get
00099             {
00100                 return GetApplicationLink(GetType().Name);
00101             }
00102         }
00103
00104         public static Uri GetApplicationLink(string sharePageName)
00105         {
00106             return new Uri("ms-sdk-sharesourcecs:navigate?page=" + sharePageName);
00107         }
00108     }
00109 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks/ViewModel/TripListViewModel.cpp Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks
  • ViewModel

TripListViewModel.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "ViewModel\TripListViewModel.h"
00013
00014 #include "Common\RelayCommand.h"
00015 #include "View\TripDetails.xaml.h"
00016
00017 using namespace AdventureWorks;
00018
00019 using namespace AdventureWorks_Shared;
00020 using namespace Concurrency;
00021 using namespace Platform;
00022 using namespace Windows::ApplicationModel::Core;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Input;
00028
00029 /// <summary>
00030 /// Sets up list view and command binding references.
00031 /// </summary>
00032 /// <param name="store">Shared reference to trip store.</param>
00033 TripListViewModel::TripListViewModel(AdventureWorks_Shared::TripStore ^ store)
00034 {
00035     this->store = store;
00036     this->trips = store->Trips;
00037
00038     addTripCommand = ref new RelayCommand(
00039         [this](Object^ parameter) {return true; },
00040         [this](Object^ parameter) {this->AddTrip(); });
00041 }
00042
00043 /// <summary> Command executed when new trip button is clicked </summary>
00044 void TripListViewModel::AddTrip()
00045 {
00046     auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00047     rootFrame->Navigate(TripDetails::typeid);
00048 }
00049
00050 Trip^ TripListViewModel::SelectedTrip::get()
00051 {
00052     return this->selectedTrip;
00053 }
00054
00055 void TripListViewModel::SelectedTrip::set(Trip^ value)
00056 {
00057     this->selectedTrip = value;
00058     NotifyPropertyChanged("SelectedTrip");
00059 }
00060
00061 ICommand^ TripListViewModel::AddTripCommand::get()
00062 {
00063     return this->addTripCommand;
00064 }
00065
00066 /// <summary> Triggers asynchronous initialization of trip store assets </summary>
00067 void TripListViewModel::LoadTrips()
00068 {
00069     store->LoadTrips();
00070 }
00071
00072 /// <summary> Handle clicking on a different trip to navigate to that trip </summary>
00073 void TripListViewModel::SelectionChanged()
00074 {
00075     if (this->SelectedTrip != nullptr)
00076     {
00077         auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00078         rootFrame->Navigate(TripDetails::typeid, this->SelectedTrip);
00079     }
00080 }
00081
00082 IObservableVector<AdventureWorks_Shared::Trip^>^ TripListViewModel::Trips::get()
00083 {
00084     return this->trips;
00085 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PresenceSensor/cppwinrt/Project.idl Source File

  • PresenceSensor
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_DataEvents : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_DataEvents();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_Polling : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_Polling();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3_Choosing : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3_Choosing();
00030     }
00031 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PasswordVault/cppwinrt/Scenario2_Manage.cpp Source File

  • PasswordVault
  • cppwinrt

Scenario2_Manage.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Manage.h"
00014 #include "Scenario2_Manage.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021 using namespace Windows::Security::Credentials;
00022
00023 constexpr auto hresult_not_found = winrt::hresult{ static_cast<int32_t>(0x80070490) };
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario2_Manage::Scenario2_Manage()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     void Scenario2_Manage::RetrieveCredentials_Click(IInspectable const&, IInspectable const&)
00033     {
00034         auto resource = InputResourceValue().Text();
00035         auto userName = InputUserNameValue().Text();
00036
00037         // Clear previous output.
00038         RetrievedCredentials().Items().Clear();
00039         rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00040
00041         PasswordVault vault;
00042         IVectorView<PasswordCredential> creds{ nullptr };
00043
00044         // The credential retrieval functions raise an "Element not found"
00045         // exception if there were no matches.
00046         try
00047         {
00048             // Perform the desired queryuserName
00049             if (resource.empty() && userName.empty())
00050             {
00051                 // Both resource and user name are empty: Use retrieveAll().
00052                 creds = vault.RetrieveAll();
00053             }
00054             else if (userName.empty())
00055             {
00056                 // Resource is provided but no user name: Use findAllByResource().
00057                 creds = vault.FindAllByResource(resource);
00058             }
00059             else if (resource.empty())
00060             {
00061                 // User name is provided but no resource: Use findByUserName().
00062                 creds = vault.FindAllByUserName(userName);
00063             }
00064             else
00065             {
00066                 // Both resource and user name are provided: Use retrieve().
00067                 // Add it to our results if the retrieval was successful.
00068                 if (PasswordCredential cred = vault.Retrieve(resource, userName))
00069                 {
00070                     creds = winrt::single_threaded_vector<PasswordCredential>({ cred }).GetView();
00071                 }
00072             }
00073         }
00074         catch (winrt::hresult_error const& e)
00075         {
00076             if (e.code() != hresult_not_found)
00077             {
00078                 throw;
00079             }
00080         }
00081
00082         // Display the results. Note that the password field is initially blank.
00083         // You must call retrievePassword() to get the password.
00084
00085         if (!creds || creds.Size() == 0)
00086         {
00087             rootPage.NotifyUser(L"No matching credentials", NotifyType::ErrorMessage);
00088         }
00089         else
00090         {
00091             ItemCollection items = RetrievedCredentials().Items();
00092             for (PasswordCredential const& cred : creds)
00093             {
00094                 TextBlock item;
00095                 item.DataContext(cred);
00096                 item.Text(cred.Resource() + L": " + cred.UserName());
00097                 items.Append(item);
00098             }
00099             rootPage.NotifyUser(L"Credentials found: " + std::to_wstring(items.Size()), NotifyType::StatusMessage);
00100         }
00101     }
00102
00103     void Scenario2_Manage::RevealPasswords_Click(IInspectable const&, IInspectable const&)
00104     {
00105         auto selectedItems = RetrievedCredentials().SelectedItems();
00106         if (selectedItems.Size() > 0)
00107         {
00108             int retrievedCount = 0;
00109             for(IInspectable const& o : selectedItems)
00110             {
00111                 auto item = o.as<TextBlock>();
00112                 auto cred = item.DataContext().as<PasswordCredential>();
00113
00114                 // The credential retrieval functions raise an "Element not found"
00115                 // exception if the credential is no longer in the PasswordVault.
00116                 // (For example, if the user manually removed the credential via the
00117                 // Control Panel.)
00118                 try
00119                 {
00120                     cred.RetrievePassword();
00121                     item.Text(cred.Resource() + L": " + cred.UserName() + L" (" + cred.Password() + L")");
00122                     retrievedCount++;
00123                 }
00124                 catch (winrt::hresult_error const& e)
00125                 {
00126                     if (e.code() != hresult_not_found)
00127                     {
00128                         throw;
00129                     }
00130
00131                     item.Text(cred.Resource() + L": " + cred.UserName() + L" (password unavailable)");
00132                 }
00133
00134             }
00135
00136             rootPage.NotifyUser(L"Passwords retrieved: " + std::to_wstring(retrievedCount), NotifyType::StatusMessage);
00137         }
00138         else
00139         {
00140             rootPage.NotifyUser(L"No credentials selected", NotifyType::ErrorMessage);
00141         }
00142     }
00143
00144     void Scenario2_Manage::RemoveCredentials_Click(IInspectable const&, IInspectable const&)
00145     {
00146         auto selectedItems = RetrievedCredentials().SelectedItems();
00147         if (selectedItems.Size() > 0)
00148         {
00149             PasswordVault vault;
00150             int removedCount = 0;
00151
00152             // Take a snapshot of the selectedOptions collection because we will be
00153             // changing the collection during the loop.
00154             std::vector<IInspectable> snapshot{ selectedItems.begin(), selectedItems.end() };
00155
00156             for (auto &&o : snapshot)
00157             {
00158                 TextBlock item = o.as<TextBlock>();
00159                 PasswordCredential cred = item.DataContext().as<PasswordCredential>();
00160                 uint32_t index;
00161                 if (RetrievedCredentials().Items().IndexOf(o, index))
00162                 {
00163                     RetrievedCredentials().Items().RemoveAt(index);
00164                 }
00165
00166                 try
00167                 {
00168                     vault.Remove(cred);
00169                     removedCount++;
00170                 }
00171                 catch (hresult_error const& e)
00172                 {
00173                     // Ignore exception if the credential was already removed.
00174                     if (e.code() != hresult_not_found)
00175                     {
00176                         throw;
00177                     }
00178                 }
00179             }
00180
00181             rootPage.NotifyUser(L"Credentials removed: " + std::to_wstring(removedCount), NotifyType::StatusMessage);
00182         }
00183         else
00184         {
00185             rootPage.NotifyUser(L"No credentials selected", NotifyType::ErrorMessage);
00186         }
00187     }
00188
00189 }
00190
Generated on Fri Nov 15 2024 22:20:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cs/LoggingSessionScenario.cs Source File

  • Logging
  • cs

LoggingSessionScenario.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using System;
00008 using System.Threading.Tasks;
00009 using Windows.Foundation.Diagnostics;
00010 using Windows.Storage;
00011
00012 namespace SDKTemplate
00013 {
00014     /// <summary>
00015     /// LoggingSessionScenario is a central singleton class which contains the logging-specific
00016     /// sample code.
00017     /// </summary>
00018     internal class LoggingSessionScenario
00019         : IDisposable
00020     {
00021         #region Primary scenario code
00022
00023         private string GetTimeStamp()
00024         {
00025             DateTime now = DateTime.Now;
00026             return string.Format(System.Globalization.CultureInfo.InvariantCulture,
00027                                  "{0:D2}{1:D2}{2:D2}-{3:D2}{4:D2}{5:D2}{6:D3}",
00028                                  now.Year - 2000,
00029                                  now.Month,
00030                                  now.Day,
00031                                  now.Hour,
00032                                  now.Minute,
00033                                  now.Second,
00034                                  now.Millisecond);
00035         }
00036
00037         /// <summary>
00038         /// Toggle the enabled/disabled status of logging.
00039         /// </summary>
00040         /// <returns>True if the resulting new status is enabled, else false for disabled.</returns>
00041         public bool ToggleLoggingEnabledDisabled()
00042         {
00043             CheckDisposed();
00044
00045             IsBusy = true;
00046
00047             try
00048             {
00049                 bool enabled;
00050                 if (session != null)
00051                 {
00052                     session.Dispose();
00053                     session = null;
00054                     ApplicationData.Current.LocalSettings.Values["LoggingEnabled"] = false;
00055                     enabled = false;
00056                 }
00057                 else
00058                 {
00059                     StartLogging();
00060                     ApplicationData.Current.LocalSettings.Values["LoggingEnabled"] = true;
00061                     enabled = true;
00062                 }
00063
00064                 if (StatusChanged != null)
00065                 {
00066                     StatusChanged.Invoke(this, new LoggingScenarioEventArgs(enabled));
00067                 }
00068
00069                 return enabled;
00070             }
00071             finally
00072             {
00073                 IsBusy = false;
00074             }
00075         }
00076
00077         /// <summary>
00078         /// The logging scenario. Log messages in a loop until 3 log files are created.
00079         /// </summary>
00080         /// <returns>The task.</returns>
00081         public async Task DoScenarioAsync()
00082         {
00083             CheckDisposed();
00084
00085             IsBusy = true;
00086
00087             try
00088             {
00089                 await Task.Run(async () =>
00090                 {
00091                     const int NUMBER_OF_LOG_FILES_TO_GENERATE = 3;
00092                     int messageIndex = 0;
00093                     int lastDelay = 0;
00094                     int lastAppError = 0;
00095                     int startFileCount = LogFileGeneratedCount;
00096
00097                     //
00098                     // Log large messages until the current log file hits the maximum size.
00099                     // When the current log file reaches its maximum size, LogFileGeneratedHandler
00100                     // will be called.
00101                     //
00102
00103                     while (LogFileGeneratedCount - startFileCount < NUMBER_OF_LOG_FILES_TO_GENERATE)
00104                     {
00105                         try
00106                         {
00107                             // Since the channel is added to the session at level Warning,
00108                             // the following is logged because it is logged at level LoggingLevel.Critical.
00109                             channel.LogMessage(
00110                                 string.Format("Message={0}: Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ligula nisi, vehicula nec eleifend vel, rutrum non dolor. Vestibulum ante ipsum " +
00111                                               "primis in faucibus orci luctus et ultrices posuere cubilia Curae; Curabitur elementum scelerisque accumsan. In hac habitasse platea dictumst.",
00112                                               ++messageIndex),
00113                                 LoggingLevel.Critical);
00114
00115                             // Since the channel is added to the session at level Warning,
00116                             // the following is *not* logged because it is logged at LoggingLevel.Information.
00117                             channel.LogMessage(
00118                                 string.Format("Message={0}: Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ligula nisi, vehicula nec eleifend vel, rutrum non dolor. Vestibulum ante ipsum " +
00119                                               "primis in faucibus orci luctus et ultrices posuere cubilia Curae; Curabitur elementum scelerisque accumsan. In hac habitasse platea dictumst.",
00120                                               ++messageIndex),
00121                                 LoggingLevel.Information);
00122
00123                             int value = 1000000; // one million, 7 digits, 4-bytes as an int, 14 bytes as a wide character string.
00124                             channel.LogMessage("Value #" + (++messageIndex).ToString() + "  " + value.ToString(), LoggingLevel.Critical); // value is logged as 14 byte wide character string.
00125                             channel.LogValuePair("Value #" + (++messageIndex).ToString(), value, LoggingLevel.Critical); // value is logged as a 4-byte integer.
00126
00127                             //
00128                             // Pause every once in a while to simulate application
00129                             // activity outside of logging.
00130                             //
00131
00132                             if (messageIndex - lastDelay > 100)
00133                             {
00134                                 lastDelay = messageIndex;
00135                                 await Task.Delay(10);
00136                             }
00137
00138                             //
00139                             // Every once in a while, simulate an application error
00140                             // which causes the app to save the current snapshot
00141                             // of logging events in memory to a disk ETL file.
00142                             //
00143
00144                             if (messageIndex - lastAppError >= 25000)
00145                             {
00146                                 lastAppError = messageIndex;
00147
00148                                 // Before simulating an application error, demonstrate LoggingActivity.
00149                                 // A LoggingActivity outputs a pair of begin and end messages to the channel.
00150                                 using (new LoggingActivity("Add two numbers.", channel, LoggingLevel.Critical))
00151                                 {
00152                                     int oneNumber = 100;
00153                                     int anotherNumber = 200;
00154                                     int total = oneNumber + anotherNumber;
00155                                     channel.LogMessage(string.Format("Message={0}: The result of adding two numbers: {1}", ++messageIndex, total), LoggingLevel.Critical);
00156                                 } // The LoggingActivity instance will log the second message at this scope exit.
00157
00158                                 // Simulate an application error.
00159                                 throw new AppException("Some bad app error occurred.");
00160                             }
00161                         }
00162                         catch (AppException e)
00163                         {
00164                             // Log the exception string.
00165                             channel.LogMessage("Exception occurrred: " + e.ToString(), LoggingLevel.Error);
00166
00167                             // Save the memory log buffer to file.
00168                             Task<string> op = SaveLogInMemoryToFileAsync();
00169                             op.Wait();
00170                             if (op.IsFaulted)
00171                             {
00172                                 throw new Exception("After an app error occurred, there was a failure to save the log file.", op.Exception);
00173                             }
00174                             LogFileGeneratedCount++;
00175                             // For the sample, update the UI to show a log file has been generated.
00176                             if (StatusChanged != null)
00177                             {
00178                                 StatusChanged.Invoke(this, new LoggingScenarioEventArgs(LoggingScenarioEventType.LogFileGenerated, op.Result));
00179                             }
00180                         }
00181                     }
00182                 });
00183             }
00184             finally
00185             {
00186                 IsBusy = false;
00187             }
00188         }
00189
00190         public void StartLogging()
00191         {
00192             CheckDisposed();
00193
00194             // If no session exists, create one.
00195             // NOTE: There are use cases where an application
00196             // may want to create only a channel for sessions outside
00197             // of the application itself. See MSDN for details. This
00198             // sample is the common scenario of an app logging events
00199             // which it wants to place in its own log file, so it creates
00200             // a session and channel as a pair. The channel is created
00201             // during construction of this LoggingSessionScenario class so
00202             // it already exsits by the time this function is called.
00203             if (session == null)
00204             {
00205                 session = new LoggingSession(DEFAULT_SESSION_NAME);
00206             }
00207
00208             // This sample adds the channel at level "warning" to
00209             // demonstrated how messages logged at more verbose levels
00210             // are ignored by the session.
00211             session.AddLoggingChannel(channel, LoggingLevel.Warning);
00212         }
00213
00214         private async Task<string> SaveLogInMemoryToFileAsync()
00215         {
00216             StorageFolder sampleAppDefinedLogFolder =
00217                 await ApplicationData.Current.LocalFolder.CreateFolderAsync(OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME,
00218                                                                             CreationCollisionOption.OpenIfExists);
00219             string newLogFileName = "Log-" + GetTimeStamp() + ".etl";
00220             StorageFile newLogFile = await session.SaveToFileAsync(sampleAppDefinedLogFolder, newLogFileName);
00221             if (newLogFile != null)
00222             {
00223                 return newLogFile.Path;
00224             }
00225             else
00226             {
00227                 return null;
00228             }
00229         }
00230
00231         #endregion
00232
00233         #region Scenario code for tracking a LoggingChannel's enablement status and related logging level.
00234
00235         /// <summary>
00236         /// This boolean tracks whether or not there are any
00237         /// sessions listening to the app's channel. This is
00238         /// adjusted as the channel's LoggingEnabled event is
00239         /// raised. Search for OnChannelLoggingEnabled for
00240         /// more information.
00241         /// </summary>
00242         private bool isChannelEnabled = false;
00243
00244         /// <summary>
00245         /// This is the current maximum level of listeners of
00246         /// the application's channel. It is adjusted as the
00247         /// channel's LoggingEnabled event is raised. Search
00248         /// for OnChannelLoggingEnabled for more information.
00249         /// </summary>
00250         private LoggingLevel channelLoggingLevel = LoggingLevel.Verbose;
00251
00252         void OnChannelLoggingEnabled(ILoggingChannel sender, object args)
00253         {
00254             // This method is called when the channel is informing us of channel-related state changes.
00255             // Save new channel state. These values can be used for advanced logging scenarios where,
00256             // for example, it's desired to skip blocks of logging code if the channel is not being
00257             // consumed by any sessions.
00258             isChannelEnabled = sender.Enabled;
00259             channelLoggingLevel = sender.Level;
00260         }
00261
00262         #endregion
00263
00264         #region Scenario code for suspend/resume.
00265
00266         private const string LoggingEnabledKey = Prefix + "LoggingEnabled";
00267
00268         public bool IsLoggingEnabled
00269         {
00270             get
00271             {
00272                 return session != null;
00273             }
00274         }
00275
00276         public void PrepareToSuspend()
00277         {
00278             CheckDisposed();
00279
00280             ApplicationData.Current.LocalSettings.Values["LoggingEnabled"] = session != null;
00281         }
00282
00283         public void ResumeLoggingIfApplicable()
00284         {
00285             CheckDisposed();
00286
00287             object loggingEnabled;
00288             if (ApplicationData.Current.LocalSettings.Values.TryGetValue("LoggingEnabled", out loggingEnabled) == false)
00289             {
00290                 ApplicationData.Current.LocalSettings.Values["LoggingEnabled"] = true;
00291                 loggingEnabled = ApplicationData.Current.LocalSettings.Values["LoggingEnabled"];
00292             }
00293
00294             if (loggingEnabled is bool && (bool)loggingEnabled == true)
00295             {
00296                 StartLogging();
00297             }
00298         }
00299
00300         #endregion
00301
00302         #region Helper functions/properties/events to support sample UI feedback.
00303
00304         public event EventHandler<LoggingScenarioEventArgs> StatusChanged;
00305
00306         private bool isBusy;
00307         /// <summary>
00308         /// True if the scenario is busy, or false if not busy.
00309         /// The UI can use this to affect UI controls.
00310         /// </summary>
00311         public bool IsBusy
00312         {
00313             get
00314             {
00315                 return isBusy;
00316             }
00317
00318             private set
00319             {
00320                 isBusy = value;
00321                 if (StatusChanged != null)
00322                 {
00323                     StatusChanged.Invoke(this, new LoggingScenarioEventArgs(LoggingScenarioEventType.BusyStatusChanged));
00324                 }
00325             }
00326         }
00327
00328         /// <summary>
00329         /// The number of times LogFileGeneratedHandler has been called.
00330         /// </summary>
00331         public int LogFileGeneratedCount { get; private set; }
00332
00333         #endregion
00334
00335         #region LoggingSessionScenario constants and privates.
00336
00337         private const string Prefix = "LoggingSessionScenario_";
00338         public const string DEFAULT_SESSION_NAME = Prefix + "Session";
00339         public const string DEFAULT_CHANNEL_NAME = Prefix + "Channel";
00340
00341         /// <summary>
00342         /// LoggingSessionScenario moves generated logs files into the
00343         /// this folder under the LocalState folder.
00344         /// </summary>
00345         public const string OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME = Prefix + "LogFiles";
00346
00347         /// <summary>
00348         /// <summary>
00349         /// The sample's one session.
00350         /// </summary>
00351         private LoggingSession session;
00352
00353         /// <summary>
00354         /// The sample's one channel.
00355         /// </summary>
00356         private LoggingChannel channel;
00357
00358         #endregion
00359
00360         #region LoggingSessionScenario constructor and singleton accessor.
00361
00362         /// <summary>
00363         /// Disallow creation of instances beyond the one instance for the process.
00364         /// The one instance is accessible via the Instance property (see below).
00365         /// </summary>
00366         private LoggingSessionScenario()
00367         {
00368             LogFileGeneratedCount = 0;
00369
00370             // This sample demonstrates LoggingSession using the Windows 8.1 LoggingChannel APIs.
00371 #pragma warning disable 618 // LoggingChannel is obsolete
00372             channel = new LoggingChannel(DEFAULT_CHANNEL_NAME);
00373 #pragma warning restore
00374
00375             channel.LoggingEnabled += OnChannelLoggingEnabled;
00376
00377             App.Current.Suspending += OnAppSuspending;
00378             App.Current.Resuming += OnAppResuming;
00379
00380             // If the app is being launched (not resumed), the
00381             // following call will activate logging if it had been
00382             // activated during the last suspend.
00383             ResumeLoggingIfApplicable();
00384         }
00385
00386         ~LoggingSessionScenario()
00387         {
00388             Dispose(false);
00389         }
00390
00391         void OnAppSuspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
00392         {
00393             // Get a deferral before performing any async operations
00394             // to avoid suspension prior to LoggingSessionScenario completing
00395             // PrepareToSuspendAsync().
00396             var deferral = e.SuspendingOperation.GetDeferral();
00397             // Prepare logging for suspension.
00398             PrepareToSuspend();
00399             // From LoggingSessionScenario's perspective, it's now okay to
00400             // suspend, so release the deferral.
00401             deferral.Complete();
00402         }
00403
00404         void OnAppResuming(object sender, object e)
00405         {
00406             // If logging was active at the last suspend,
00407             // ResumeLoggingIfApplicable will re-activate
00408             // logging.
00409             ResumeLoggingIfApplicable();
00410         }
00411
00412         /// The app's one and only LoggingSessionScenario instance.
00413         /// </summary>
00414         static private LoggingSessionScenario loggingSessionScenario;
00415
00416         /// <summary>
00417         /// A method to allowing callers to access the app's one and only LoggingSessionScenario instance.
00418         /// </summary>
00419         /// <returns>The logging helper.</returns>
00420         static public LoggingSessionScenario Instance
00421         {
00422             get
00423             {
00424                 if (loggingSessionScenario == null)
00425                 {
00426                     loggingSessionScenario = new LoggingSessionScenario();
00427                 }
00428                 return loggingSessionScenario;
00429             }
00430         }
00431
00432         #endregion
00433
00434         #region IDisposable handling
00435
00436         public void Dispose()
00437         {
00438             Dispose(true);
00439             GC.SuppressFinalize(this);
00440         }
00441
00442         protected virtual void Dispose(bool disposing)
00443         {
00444             if (isDisposed == false)
00445             {
00446                 isDisposed = true;
00447
00448                 if (disposing)
00449                 {
00450                     if (channel != null)
00451                     {
00452                         channel.Dispose();
00453                         channel = null;
00454                     }
00455
00456                     if (session != null)
00457                     {
00458                         session.Dispose();
00459                         session = null;
00460                     }
00461                 }
00462             }
00463         }
00464
00465         /// <summary>
00466         /// Set to 'true' if Dispose() has been called.
00467         /// </summary>
00468         private bool isDisposed = false;
00469
00470         /// <summary>
00471         /// Helper function for other methods to call to check Dispose() state.
00472         /// </summary>
00473         private void CheckDisposed()
00474         {
00475             if (isDisposed)
00476             {
00477                 throw new ObjectDisposedException("LoggingSessionScenario");
00478             }
00479         }
00480
00481         #endregion
00482     }
00483
00484     #region Exception to simulate an app error.
00485
00486     class AppException : Exception
00487     {
00488         public AppException()
00489         {
00490         }
00491
00492         public AppException(string message)
00493             : base(message)
00494         {
00495         }
00496     }
00497
00498     #endregion
00499 }
Generated on Fri Nov 15 2024 22:20:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppServices/cppwinrt/AppServicesProvider/ShowPackageFamilyName.h Source File

  • AppServices
  • cppwinrt
  • AppServicesProvider

ShowPackageFamilyName.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "ShowPackageFamilyName.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct ShowPackageFamilyName : ShowPackageFamilyNameT<ShowPackageFamilyName>
00019     {
00020         ShowPackageFamilyName();
00021     };
00022 }
00023
00024 namespace winrt::SDKTemplate::factory_implementation
00025 {
00026     struct ShowPackageFamilyName : ShowPackageFamilyNameT<ShowPackageFamilyName, implementation::ShowPackageFamilyName>
00027     {
00028     };
00029 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/Tasks/ServicingComplete.cpp Source File

  • BackgroundTask
  • cpp
  • Tasks

ServicingComplete.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 // ServicingComplete.cpp
00012 #include "pch.h"
00013 #include "ServicingComplete.h"
00014
00015 using namespace Tasks;
00016 using namespace Windows::Storage;
00017
00018 ServicingComplete::ServicingComplete() :
00019     CancelRequested(false)
00020 {
00021 }
00022
00023 ServicingComplete::~ServicingComplete()
00024 {
00025 }
00026
00027 void ServicingComplete::Run(IBackgroundTaskInstance^ taskInstance)
00028 {
00029     //
00030     // Do the background task activity.
00031     //
00032     unsigned int progress;
00033     for (progress = 0; progress <= 100; progress += 10)
00034     {
00035         //
00036         // If the cancellation handler indicated that the task was canceled, stop doing the task.
00037         //
00038         if (CancelRequested)
00039         {
00040             break;
00041         }
00042
00043         //
00044         // Indicate progress to the foreground application.
00045         //
00046         taskInstance->Progress = progress;
00047     }
00048
00049     //
00050     // Write to LocalSettings to indicate that this background task ran.
00051     //
00052     auto settings = ApplicationData::Current->LocalSettings;
00053     auto key = taskInstance->Task->Name;
00054     settings->Values->Insert(key, (progress < 100) ? "Canceled" : "Completed");
00055 }
00056
00057 void ServicingComplete::OnCanceled(IBackgroundTaskInstance^ taskInstance, BackgroundTaskCancellationReason reason)
00058 {
00059     //
00060     // Indicate that the background task is canceled.
00061     //
00062     CancelRequested = true;
00063 }
Generated on Fri Nov 15 2024 22:18:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Inclinometer/cs/Scenario2_Polling.xaml.cs Source File

  • Inclinometer
  • cs

Scenario2_Polling.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using System;
00017 using Windows.Devices.Sensors;
00018 using Windows.Foundation;
00019 using System.Threading.Tasks;
00020 using Windows.UI.Core;
00021
00022 namespace InclinometerCS
00023 {
00024     public sealed partial class Scenario2_Polling : Page
00025     {
00026         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00027         // as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         private Inclinometer _inclinometer;
00031         private uint _desiredReportInterval;
00032         private DispatcherTimer _dispatcherTimer;
00033
00034         public Scenario2_Polling()
00035         {
00036             this.InitializeComponent();
00037
00038             _inclinometer = Inclinometer.GetDefault();
00039             if (_inclinometer != null)
00040             {
00041                 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00042                 // This value will be used later to activate the sensor.
00043                 uint minReportInterval = _inclinometer.MinimumReportInterval;
00044                 _desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00045
00046                 // Set up a DispatchTimer
00047                 _dispatcherTimer = new DispatcherTimer();
00048                 _dispatcherTimer.Tick += DisplayCurrentReading;
00049                 _dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, (int)_desiredReportInterval);
00050             }
00051             else
00052             {
00053                 rootPage.NotifyUser("No inclinometer found", NotifyType.ErrorMessage);
00054             }
00055         }
00056
00057         /// <summary>
00058         /// Invoked when this page is about to be displayed in a Frame.
00059         /// </summary>
00060         /// <param name="e">Event data that describes how this page was reached. The Parameter
00061         /// property is typically used to configure the page.</param>
00062         protected override void OnNavigatedTo(NavigationEventArgs e)
00063         {
00064             ScenarioEnableButton.IsEnabled = true;
00065             ScenarioDisableButton.IsEnabled = false;
00066         }
00067
00068         /// <summary>
00069         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00070         /// </summary>
00071         /// <param name="e">
00072         /// Event data that can be examined by overriding code. The event data is representative
00073         /// of the navigation that will unload the current Page unless canceled. The
00074         /// navigation can potentially be canceled by setting Cancel.
00075         /// </param>
00076         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00077         {
00078             if (ScenarioDisableButton.IsEnabled)
00079             {
00080                 Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00081
00082                 // Stop the dispatcher
00083                 _dispatcherTimer.Stop();
00084
00085                 // Restore the default report interval to release resources while the sensor is not in use
00086                 _inclinometer.ReportInterval = 0;
00087             }
00088
00089             base.OnNavigatingFrom(e);
00090         }
00091
00092         /// <summary>
00093         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00094         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00095         /// </summary>
00096         /// <param name="sender"></param>
00097         /// <param name="e">
00098         /// Event data that can be examined for the current visibility state.
00099         /// </param>
00100         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00101         {
00102             if (ScenarioDisableButton.IsEnabled)
00103             {
00104                 if (e.Visible)
00105                 {
00106                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00107                     _dispatcherTimer.Start();
00108                 }
00109                 else
00110                 {
00111                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00112                     _dispatcherTimer.Stop();
00113                 }
00114             }
00115         }
00116
00117         /// <summary>
00118         /// This is the dispatcher callback.
00119         /// </summary>
00120         /// <param name="sender"></param>
00121         /// <param name="args"></param>
00122         private void DisplayCurrentReading(object sender, object args)
00123         {
00124             InclinometerReading reading = _inclinometer.GetCurrentReading();
00125             if (reading != null)
00126             {
00127                 ScenarioOutput_X.Text = String.Format("{0,5:0.00}", reading.PitchDegrees);
00128                 ScenarioOutput_Y.Text = String.Format("{0,5:0.00}", reading.RollDegrees);
00129                 ScenarioOutput_Z.Text = String.Format("{0,5:0.00}", reading.YawDegrees);
00130                 switch (reading.YawAccuracy)
00131                 {
00132                     case MagnetometerAccuracy.Unknown:
00133                         ScenarioOutput_YawAccuracy.Text = "Unknown";
00134                         break;
00135                     case MagnetometerAccuracy.Unreliable:
00136                         ScenarioOutput_YawAccuracy.Text = "Unreliable";
00137                         break;
00138                     case MagnetometerAccuracy.Approximate:
00139                         ScenarioOutput_YawAccuracy.Text = "Approximate";
00140                         break;
00141                     case MagnetometerAccuracy.High:
00142                         ScenarioOutput_YawAccuracy.Text = "High";
00143                         break;
00144                     default:
00145                         ScenarioOutput_YawAccuracy.Text = "No data";
00146                         break;
00147                 }
00148             }
00149         }
00150
00151         /// <summary>
00152         /// This is the click handler for the 'Enable' button.
00153         /// </summary>
00154         /// <param name="sender"></param>
00155         /// <param name="e"></param>
00156         private void ScenarioEnable(object sender, RoutedEventArgs e)
00157         {
00158             if (_inclinometer != null)
00159             {
00160                 // Set the report interval to enable the sensor for polling
00161                 _inclinometer.ReportInterval = _desiredReportInterval;
00162
00163                 Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged);
00164                 _dispatcherTimer.Start();
00165
00166                 ScenarioEnableButton.IsEnabled = false;
00167                 ScenarioDisableButton.IsEnabled = true;
00168             }
00169             else
00170             {
00171                 rootPage.NotifyUser("No inclinometer found", NotifyType.ErrorMessage);
00172             }
00173         }
00174
00175         /// <summary>
00176         /// This is the click handler for the 'Disable' button.
00177         /// </summary>
00178         /// <param name="sender"></param>
00179         /// <param name="e"></param>
00180         private void ScenarioDisable(object sender, RoutedEventArgs e)
00181         {
00182             Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00183
00184             // Stop the dispatcher
00185             _dispatcherTimer.Stop();
00186
00187             // Restore the default report interval to release resources while the sensor is not in use
00188             _inclinometer.ReportInterval = 0;
00189
00190             ScenarioEnableButton.IsEnabled = true;
00191             ScenarioDisableButton.IsEnabled = false;
00192         }
00193     }
00194 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario02_GetStream Member List

This is the complete list of members for Scenario02_GetStream, including all inherited members.
Cancel_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario02_GetStream |
CancelableRequestAsync(Windows::Web::Http::HttpRequestMessage request) | Scenario02_GetStream | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario02_GetStream |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario02_GetStream |
Scenario02_GetStream() | Scenario02_GetStream |
Start_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario02_GetStream |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: GlobalizationPreferences/cppwinrt/SampleConfiguration.h Source File

  • GlobalizationPreferences
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     hstring StringJoin(hstring const& delimiter, Windows::Foundation::Collections::IVectorView<hstring> const& vector);
00018 }
00019
00020 namespace winrt
00021 {
00022     hstring to_hstring(Windows::Globalization::DayOfWeek value);
00023 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

OsrFx2::Pipe Member List

This is the complete list of members for OsrFx2::Pipe, including all inherited members.
BulkInPipeIndex | OsrFx2::Pipe
BulkOutPipeIndex | OsrFx2::Pipe
InterruptInPipeIndex | OsrFx2::Pipe
Generated on Fri Nov 15 2024 22:23:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_TrimAndSaveClip Member List

This is the complete list of members for Scenario1_TrimAndSaveClip, including all inherited members.
ChooseFile_Click(object sender, RoutedEventArgs e) | Scenario1_TrimAndSaveClip | [inline, private]
composition | Scenario1_TrimAndSaveClip | [private]
EnableButtons(bool isEnabled) | Scenario1_TrimAndSaveClip | [inline, private]
mediaStreamSource | Scenario1_TrimAndSaveClip | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_TrimAndSaveClip | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_TrimAndSaveClip | [inline, protected]
pickedFile | Scenario1_TrimAndSaveClip | [private]
rootPage | Scenario1_TrimAndSaveClip | [private]
Save_Click(object sender, RoutedEventArgs e) | Scenario1_TrimAndSaveClip | [inline, private]
Scenario1_TrimAndSaveClip() | Scenario1_TrimAndSaveClip | [inline]
storageItemAccessList | Scenario1_TrimAndSaveClip | [private]
TrimClip_Click(object sender, RoutedEventArgs e) | Scenario1_TrimAndSaveClip | [inline, private]
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/AppView.cpp Source File

  • HolographicTagAlong
  • cpp

AppView.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "AppView.h"
00014
00015 #include <ppltasks.h>
00016
00017 using namespace HolographicTagAlongSample;
00018
00019 using namespace concurrency;
00020 using namespace Windows::ApplicationModel;
00021 using namespace Windows::ApplicationModel::Activation;
00022 using namespace Windows::ApplicationModel::Core;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Graphics::Holographic;
00025 using namespace Windows::UI::Core;
00026
00027 // The main function is only used to initialize our IFrameworkView class.
00028 // Under most circumstances, you should not need to modify this function.
00029 [Platform::MTAThread]
00030 int main(Platform::Array<Platform::String^>^)
00031 {
00032     AppViewSource^ appViewSource = ref new ::AppViewSource();
00033     CoreApplication::Run(appViewSource);
00034     return 0;
00035 }
00036
00037 IFrameworkView^ AppViewSource::CreateView()
00038 {
00039     return ref new AppView();
00040 }
00041
00042 AppView::AppView()
00043 {
00044 }
00045
00046
00047 // IFrameworkView methods
00048
00049 // The first method called when the IFrameworkView is being created.
00050 // Use this method to subscribe for Windows shell events and to initialize your app.
00051 void AppView::Initialize(CoreApplicationView^ applicationView)
00052 {
00053     applicationView->Activated +=
00054         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &AppView::OnViewActivated);
00055
00056     // Register event handlers for app lifecycle.
00057     CoreApplication::Suspending +=
00058         ref new EventHandler<SuspendingEventArgs^>(this, &AppView::OnSuspending);
00059
00060     CoreApplication::Resuming +=
00061         ref new EventHandler<Platform::Object^>(this, &AppView::OnResuming);
00062
00063     // At this point we have access to the device and we can create device-dependent
00064     // resources.
00065     m_deviceResources = std::make_shared<DX::DeviceResources>();
00066
00067     m_main = std::make_unique<HolographicTagAlongSampleMain>(m_deviceResources);
00068 }
00069
00070 // Called when the CoreWindow object is created (or re-created).
00071 void AppView::SetWindow(CoreWindow^ window)
00072 {
00073     // Register for keypress notifications.
00074     window->KeyDown +=
00075         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &AppView::OnKeyPressed);
00076
00077     // Register for notification that the app window is being closed.
00078     window->Closed +=
00079         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &AppView::OnWindowClosed);
00080
00081     // Register for notifications that the app window is losing focus.
00082     window->VisibilityChanged +=
00083         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &AppView::OnVisibilityChanged);
00084
00085     // Create a holographic space for the core window for the current view.
00086     // Presenting holographic frames that are created by this holographic space will put
00087     // the app into exclusive mode.
00088     m_holographicSpace = HolographicSpace::CreateForCoreWindow(window);
00089
00090     // The DeviceResources class uses the preferred DXGI adapter ID from the holographic
00091     // space (when available) to create a Direct3D device. The HolographicSpace
00092     // uses this ID3D11Device to create and manage device-based resources such as
00093     // swap chains.
00094     m_deviceResources->SetHolographicSpace(m_holographicSpace);
00095
00096     // The main class uses the holographic space for updates and rendering.
00097     m_main->SetHolographicSpace(m_holographicSpace);
00098 }
00099
00100 // The Load method can be used to initialize scene resources or to load a
00101 // previously saved app state.
00102 void AppView::Load(Platform::String^ entryPoint)
00103 {
00104 }
00105
00106 // This method is called after the window becomes active. It oversees the
00107 // update, draw, and present loop, and it also oversees window message processing.
00108 void AppView::Run()
00109 {
00110     while (!m_windowClosed)
00111     {
00112         if (m_windowVisible && (m_holographicSpace != nullptr))
00113         {
00114             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00115
00116             HolographicFrame^ holographicFrame = m_main->Update();
00117
00118             if (m_main->Render(holographicFrame))
00119             {
00120                 // The holographic frame has an API that presents the swap chain for each
00121                 // holographic camera.
00122                 m_deviceResources->Present(holographicFrame);
00123             }
00124         }
00125         else
00126         {
00127             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00128         }
00129     }
00130 }
00131
00132 // Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
00133 // class is torn down while the app is in the foreground.
00134 // This method is not often used, but IFrameworkView requires it and it will be called for
00135 // holographic apps.
00136 void AppView::Uninitialize()
00137 {
00138
00139 }
00140
00141
00142 // Application lifecycle event handlers
00143
00144 // Called when the app view is activated. Activates the app's CoreWindow.
00145 void AppView::OnViewActivated(CoreApplicationView^ sender, IActivatedEventArgs^ args)
00146 {
00147     // Run() won't start until the CoreWindow is activated.
00148     sender->CoreWindow->Activate();
00149 }
00150
00151 void AppView::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
00152 {
00153     // Save app state asynchronously after requesting a deferral. Holding a deferral
00154     // indicates that the application is busy performing suspending operations. Be
00155     // aware that a deferral may not be held indefinitely; after about five seconds,
00156     // the app will be forced to exit.
00157     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
00158
00159     create_task([this, deferral] ()
00160     {
00161         m_deviceResources->Trim();
00162
00163         if (m_main != nullptr)
00164         {
00165             m_main->SaveAppState();
00166         }
00167
00168         deferral->Complete();
00169     });
00170 }
00171
00172 void AppView::OnResuming(Platform::Object^ sender, Platform::Object^ args)
00173 {
00174     // Restore any data or state that was unloaded on suspend. By default, data
00175     // and state are persisted when resuming from suspend. Note that this event
00176     // does not occur if the app was previously terminated.
00177
00178     if (m_main != nullptr)
00179     {
00180         m_main->LoadAppState();
00181     }
00182 }
00183
00184
00185 // Window event handlers
00186
00187 void AppView::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
00188 {
00189     m_windowVisible = args->Visible;
00190 }
00191
00192 void AppView::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
00193 {
00194     m_windowClosed = true;
00195 }
00196
00197
00198 // Input event handlers
00199
00200 void AppView::OnKeyPressed(CoreWindow^ sender, KeyEventArgs^ args)
00201 {
00202     // This code sample does not use keyboard input.
00203 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SpinningCubeRenderer Member List

This is the complete list of members for SpinningCubeRenderer, including all inherited members.
CreateDeviceDependentResources() | SpinningCubeRenderer |
CreateDeviceDependentResources() | SpinningCubeRenderer |
GetPosition() | SpinningCubeRenderer | [inline]
GetPosition() | SpinningCubeRenderer | [inline]
m_degreesPerSecond | SpinningCubeRenderer | [private]
m_deviceResources | SpinningCubeRenderer | [private]
m_geometryShader | SpinningCubeRenderer | [private]
m_indexBuffer | SpinningCubeRenderer | [private]
m_indexCount | SpinningCubeRenderer | [private]
m_indexCount | SpinningCubeRenderer | [private]
m_inputLayout | SpinningCubeRenderer | [private]
m_loadingComplete | SpinningCubeRenderer | [private]
m_modelConstantBuffer | SpinningCubeRenderer | [private]
m_modelConstantBufferData | SpinningCubeRenderer | [private]
m_pixelShader | SpinningCubeRenderer | [private]
m_position | SpinningCubeRenderer | [private]
m_position | SpinningCubeRenderer | [private]
m_usingVprtShaders | SpinningCubeRenderer | [private]
m_vertexBuffer | SpinningCubeRenderer | [private]
m_vertexShader | SpinningCubeRenderer | [private]
PositionHologram(Windows::UI::Input::Spatial::SpatialPointerPose^pointerPose) | SpinningCubeRenderer |
PositionHologram(winrt::Windows::UI::Input::Spatial::SpatialPointerPose const &pointerPose) | SpinningCubeRenderer |
ReleaseDeviceDependentResources() | SpinningCubeRenderer |
ReleaseDeviceDependentResources() | SpinningCubeRenderer |
Render() | SpinningCubeRenderer |
Render() | SpinningCubeRenderer |
SetPosition(Windows::Foundation::Numerics::float3 pos) | SpinningCubeRenderer | [inline]
SetPosition(winrt::Windows::Foundation::Numerics::float3 const &pos) | SpinningCubeRenderer | [inline]
SpinningCubeRenderer(const std::shared_ptr< DX::DeviceResources > &deviceResources) | SpinningCubeRenderer |
SpinningCubeRenderer(std::shared_ptr< DX::DeviceResources > const &deviceResources) | SpinningCubeRenderer |
Update(const DX::StepTimer &timer) | SpinningCubeRenderer |
Update(DX::StepTimer const &timer) | SpinningCubeRenderer |
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cpp/pch.h Source File

  • XamlCommanding
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInteractionMode/cpp/SampleConfiguration.cpp Source File

  • UserInteractionMode
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Responding to mode", "SDKTemplate.Scenario1_Basic" },
00021 };
Generated on Fri Nov 15 2024 22:17:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-SPI/cs/Scenario1_ReadData.xaml.cs Source File

  • IoT-SPI
  • cs

Scenario1_ReadData.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Devices.Spi;
00016 using Windows.Devices.Enumeration;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario1_ReadData : Page
00024     {
00025         private SpiDevice adxl345Sensor;
00026         private DispatcherTimer timer;
00027
00028         public Scenario1_ReadData()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         protected override void OnNavigatedFrom(NavigationEventArgs e)
00034         {
00035             StopScenario();
00036         }
00037
00038         private async Task StartScenarioAsync()
00039         {
00040             String spiDeviceSelector = SpiDevice.GetDeviceSelector();
00041             IReadOnlyList<DeviceInformation> devices = await DeviceInformation.FindAllAsync(spiDeviceSelector);
00042
00043             // 0 = Chip select line to use.
00044             var ADXL345_Settings = new SpiConnectionSettings(0);
00045
00046             // 5MHz is the rated speed of the ADXL345 accelerometer.
00047             ADXL345_Settings.ClockFrequency = 5000000;
00048
00049             // The accelerometer expects an idle-high clock polarity.
00050             // We use Mode3 to set the clock polarity and phase to: CPOL = 1, CPHA = 1.
00051             ADXL345_Settings.Mode = SpiMode.Mode3;
00052
00053             // If this next line crashes with an ArgumentOutOfRangeException,
00054             // then the problem is that no SPI devices were found.
00055             //
00056             // If the next line crashes with Access Denied, then the problem is
00057             // that access to the SPI device (ADXL345) is denied.
00058             //
00059             // The call to FromIdAsync will also crash if the settings are invalid.
00060             //
00061             // FromIdAsync produces null if there is a sharing violation on the device.
00062             // This will result in a NullReferenceException a few lines later.
00063             adxl345Sensor = await SpiDevice.FromIdAsync(devices[0].Id, ADXL345_Settings);
00064
00065             //
00066             // Initialize the accelerometer:
00067             //
00068             // For this device, we create 2-byte write buffers:
00069             // The first byte is the register address we want to write to.
00070             // The second byte is the contents that we want to write to the register.
00071             //
00072
00073             // 0x31 is address of data format register, 0x01 sets range to +- 4Gs.
00074             byte[] WriteBuf_DataFormat = new byte[] { 0x31, 0x01 };
00075
00076             // 0x2D is address of power control register, 0x08 puts the accelerometer into measurement mode.
00077             byte[] WriteBuf_PowerControl = new byte[] { 0x2D, 0x08 };
00078
00079             // Write the register settings.
00080             //
00081             // If this next line crashes with a NullReferenceException, then
00082             // there was a sharing violation on the device.
00083             // (See comment earlier in this function.)
00084             //
00085             // If this next line crashes for some other reason, then there was
00086             // an error communicating with the device.
00087
00088             adxl345Sensor.Write(WriteBuf_DataFormat);
00089             adxl345Sensor.Write(WriteBuf_PowerControl);
00090
00091             // Start the polling timer.
00092             timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(100) };
00093             timer.Tick += Timer_Tick;
00094             timer.Start();
00095         }
00096
00097         void StopScenario()
00098         {
00099             if (timer != null)
00100             {
00101                 timer.Tick -= Timer_Tick;
00102                 timer.Stop();
00103                 timer = null;
00104             }
00105
00106             // Release the SPI sensor.
00107             if (adxl345Sensor != null)
00108             {
00109                 adxl345Sensor.Dispose();
00110                 adxl345Sensor = null;
00111             }
00112         }
00113
00114         async void StartStopScenario_Click(object sender, RoutedEventArgs e)
00115         {
00116             if (timer != null)
00117             {
00118                 StopScenario();
00119                 StartStopButton.Content = "Start";
00120                 ScenarioControls.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00121             }
00122             else
00123             {
00124                 StartStopButton.IsEnabled = false;
00125                 await StartScenarioAsync();
00126                 StartStopButton.IsEnabled = true;
00127                 StartStopButton.Content = "Stop";
00128                 ScenarioControls.Visibility = Windows.UI.Xaml.Visibility.Visible;
00129             }
00130         }
00131
00132         void Timer_Tick(object sender, object e)
00133         {
00134             const byte ACCEL_SPI_RW_BIT = 0x80; // Bit used in SPI transactions to indicate read/write
00135             const byte ACCEL_SPI_MB_BIT = 0x40; // Bit used to indicate multi-byte SPI transactions
00136             const byte ACCEL_REG_X = 0x32;      // Address of the X Axis data register
00137             const int ACCEL_RES = 1024;         // The ADXL345 has 10 bit resolution giving 1024 unique values
00138             const int ACCEL_DYN_RANGE_G = 8;    // The ADXL345 had a total dynamic range of 8G, since we're configuring it to +-4G
00139             const int UNITS_PER_G = ACCEL_RES / ACCEL_DYN_RANGE_G;  // Ratio of raw int values to G units
00140
00141             byte[] ReadBuf = new byte[6 + 1];    // Read buffer of size 6 bytes (2 bytes * 3 axes) + 1 byte padding
00142             byte[] RegAddrBuf = new byte[1 + 6]; // Register address buffer of size 1 byte + 6 bytes padding
00143
00144             // Register address we want to read from with read and multi-byte bit set
00145             RegAddrBuf[0] = ACCEL_REG_X | ACCEL_SPI_RW_BIT | ACCEL_SPI_MB_BIT;
00146
00147             // If this next line crashes, then there was an error communicating with the device.
00148             adxl345Sensor.TransferFullDuplex(RegAddrBuf, ReadBuf);
00149
00150             // In order to get the raw 16-bit data values, we need to concatenate two 8-bit bytes for each axis
00151             short AccelerationRawX = BitConverter.ToInt16(ReadBuf, 1);
00152             short AccelerationRawY = BitConverter.ToInt16(ReadBuf, 3);
00153             short AccelerationRawZ = BitConverter.ToInt16(ReadBuf, 5);
00154
00155             // Convert raw values to G's and display them.
00156             X.Text = ((double)AccelerationRawX / UNITS_PER_G).ToString();
00157             Y.Text = ((double)AccelerationRawY / UNITS_PER_G).ToString();
00158             Z.Text = ((double)AccelerationRawZ / UNITS_PER_G).ToString();
00159         }
00160     }
00161 }
Generated on Fri Nov 15 2024 22:20:03 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Personalization/cpp/AddImageFeedScenario.xaml.cpp Source File

  • Personalization
  • cpp

AddImageFeedScenario.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // AddImageFeedScenario.xaml.cpp
00014 // Implementation of the AddImageFeedScenario class
00015 //
00016
00017 #include "pch.h"
00018 #include "AddImageFeedScenario.xaml.h"
00019 #include "MainPage.xaml.h"
00020
00021 using namespace SDKTemplate;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::System::UserProfile;
00029
00030 AddImageFeedScenario::AddImageFeedScenario()
00031 {
00032     InitializeComponent();
00033 }
00034
00035 void AddImageFeedScenario::SetDefaultButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00036 {
00037     // Pass a URI to your enclosure-based feed of lock screen images.  These must be JPG or PNG files.
00038     // Note that the sample URL given here is deliberately non-functional.
00039     create_task(LockScreen::RequestSetImageFeedAsync(ref new Uri("http://contoso.com/myimagerss.xml")))
00040     .then([this] (SetImageFeedResult result)
00041     {
00042         if (result == SetImageFeedResult::Success)
00043         {
00044             AddImageFeedScenarioOutputText->Text = "Called RequestSetImageFeedAsync: the specified URL was set as the default.";
00045         }
00046         else if (result == SetImageFeedResult::ChangeDisabled)
00047         {
00048             AddImageFeedScenarioOutputText->Text = "Called RequestSetImageFeedAsync: call succeeded but group policy has the lock screen image slide show turned off.";
00049         }
00050         else // (result == SetImageFeedResult.UserCanceled)
00051         {
00052             AddImageFeedScenarioOutputText->Text = "Called RequestSetImageFeedAsync: the specified URL was not set as the default.";
00053         }
00054     }, task_continuation_context::use_current());
00055 }
00056
00057 void AddImageFeedScenario::RemoveFeedButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00058 {
00059     bool fResult = LockScreen::TryRemoveImageFeed();
00060     if (fResult)
00061     {
00062         AddImageFeedScenarioOutputText->Text = "Called TryRemoveImageFeed: the associated URL registration was removed.";
00063     }
00064     else
00065     {
00066         AddImageFeedScenarioOutputText->Text = "Called TryRemoveImageFeed: the associated URL registration removal failed.";
00067     }
00068 }
Generated on Fri Nov 15 2024 22:20:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_FindClaimEnable Member List

This is the complete list of members for Scenario1_FindClaimEnable, including all inherited members.
ClaimAndEnable_Click() | Scenario1_FindClaimEnable | [inline, private]
FindPrinter_Click() | Scenario1_FindClaimEnable | [inline, private]
isBusy | Scenario1_FindClaimEnable | [private]
IsImportantTransaction_Click() | Scenario1_FindClaimEnable | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_FindClaimEnable | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_FindClaimEnable | [inline, protected]
ReleaseAll_Click() | Scenario1_FindClaimEnable | [inline, private]
ReleaseClaim_Click() | Scenario1_FindClaimEnable | [inline, private]
rootPage | Scenario1_FindClaimEnable | [private]
Scenario1_FindClaimEnable() | Scenario1_FindClaimEnable | [inline]
UpdateButtons() | Scenario1_FindClaimEnable | [inline, private]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Input Member List

This is the complete list of members for Scenario1_Input, including all inherited members.
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario1_Input | [inline, protected]
Scenario1_Input() | Scenario1_Input | [inline]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
__pad0__ | sealed | [protected]
_firstAdapter | sealed | [private]
_registrationToken | sealed | [private]
_rootPage | sealed | [private]
_savedProfileName | sealed | [private]
_wiFiAdapters | sealed | [private]
adapter | sealed | [private]
Button_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Click_Register(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Click_Unregister(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ConnectButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ConnectivityLevel | sealed |
DisconnectButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DisplayNetworkReport(Windows::Devices::WiFi::WiFiNetworkReport^report, Windows::Devices::WiFi::WiFiAdapter^adapter) | sealed | [private]
DisplayNetworkReport(Windows::Devices::WiFi::WiFiNetworkReport^report) | sealed | [private]
DisplayNetworkReport(Windows::Devices::WiFi::WiFiNetworkReport^report, Windows::Devices::WiFi::WiFiAdapter^adapter) | sealed | [private]
DisplayNetworkReport(Windows::Devices::WiFi::WiFiNetworkReport^report) | sealed | [private]
GetConnectivityLevelAsString(Windows::Networking::Connectivity::NetworkConnectivityLevel conectivityLevel) | sealed | [protected, static]
GetNetworkAuthenticationTypeAsString(Windows::Networking::Connectivity::NetworkAuthenticationType authenticationType) | sealed | [private]
GetNetworkEncryptionTypeAsString(Windows::Networking::Connectivity::NetworkEncryptionType encryptionType) | sealed | [private]
OnAvailableNetworksChanged(Windows::Devices::WiFi::WiFiAdapter^sender, Platform::Object^args) | sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNetworkStatusChanged(Platform::Object^sender) | sealed | [private]
OnPropertyChanged(Platform::String^name) | sealed | [protected]
PropertyChanged | sealed |
ResultCollection | sealed |
ResultsListView_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
ScanButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Scenario1_CachedNetworks() | sealed |
Scenario2_Scan() | sealed |
Scenario3_RegisterForUpdates() | sealed |
Scenario4_Connect() | sealed |
UpdateConnectivityLevel() | sealed | [private]
UpdateConnectivityLevels(Windows::Foundation::Collections::IObservableVector< WiFiNetworkDisplay^>^networkCollection, UINT current) | sealed | [protected, static]
UpdateConnectivityStatus() | sealed | [private]
UpdateWiFiImage() | sealed | [private]
WiFiImage | sealed |
WiFiNetworkDisplay(Windows::Devices::WiFi::WiFiAvailableNetwork^availableNetwork, Windows::Devices::WiFi::WiFiAdapter^adapter) | sealed |
Generated on Fri Nov 15 2024 22:24:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LowLatencyInput/cpp/LowLatencyInputMain.h Source File

  • LowLatencyInput
  • cpp

LowLatencyInputMain.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015 #include "Content\RectRenderer.h"
00016
00017 // Renders Direct2D and 3D content on the screen.
00018 namespace SDKTemplate
00019 {
00020     class LowLatencyInputMain : public DX::IDeviceNotify
00021     {
00022     public:
00023         LowLatencyInputMain(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00024         ~LowLatencyInputMain();
00025         void StartRenderLoop();
00026         void StopRenderLoop();
00027         Concurrency::critical_section& GetCriticalSection() { return criticalSection; }
00028
00029         // IDeviceNotify
00030         virtual void OnDeviceLost();
00031         virtual void OnDeviceRestored();
00032
00033         void UpdateRectTransform(Windows::Foundation::Point newPosition, Windows::UI::Input::ManipulationDelta newDelta);
00034         void SetRectSize(float newSize);
00035         void SetBrushColor(D2D1::ColorF color);
00036         void ResetRect();
00037         bool HitTest( Windows::Foundation::Point position);
00038
00039     private:
00040         void Render();
00041
00042         // Cached pointer to device resources.
00043         std::shared_ptr<DX::DeviceResources> deviceResources;
00044
00045         std::unique_ptr<RectRenderer> sceneRenderer;
00046
00047         Windows::Foundation::IAsyncAction^ renderLoopWorker;
00048         Concurrency::critical_section criticalSection;
00049
00050     };
00051 }
Generated on Fri Nov 15 2024 22:20:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cppwinrt/Scenario4_TilePinned.cpp Source File

  • SecondaryTiles
  • cppwinrt

Scenario4_TilePinned.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario4_TilePinned.h"
00014 #include "Scenario4_TilePinned.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::UI::StartScreen;
00020 using namespace Windows::UI::Xaml;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     Scenario4_TilePinned::Scenario4_TilePinned()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     void Scenario4_TilePinned::TileExists_Click(IInspectable const&, RoutedEventArgs const&)
00030     {
00031         if (SecondaryTile::Exists(SampleHelpers::LogoSecondaryTileId))
00032         {
00033             rootPage.NotifyUser(hstring(SampleHelpers::LogoSecondaryTileId) + L" is pinned.", NotifyType::StatusMessage);
00034         }
00035         else
00036         {
00037             rootPage.NotifyUser(hstring(SampleHelpers::LogoSecondaryTileId) + L" is not currently pinned.", NotifyType::ErrorMessage);
00038         }
00039     }
00040 }
Generated on Fri Nov 15 2024 22:21:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDragAndDrop/cpp/Scenario3_StartDragAsync.xaml.cpp Source File

  • XamlDragAndDrop
  • cpp

Scenario3_StartDragAsync.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_StartDragAsync.xaml.h"
00014
00015 using namespace SDKTemplate;
00016 using namespace concurrency;
00017 using namespace Platform;
00018 using namespace Platform::Collections;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Media;
00027 using namespace Windows::UI::Xaml::Media::Imaging;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::Graphics::Imaging;
00030 using namespace Windows::Storage;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::ApplicationModel::DataTransfer;
00033
00034
00035 Scenario3_StartDragAsync::Scenario3_StartDragAsync() : rootPage(MainPage::Current)
00036 {
00037     InitializeComponent();
00038
00039     // Initialize the symbols from the Text file
00040     auto uri = ref new Uri(L"ms-appx:///Assets/Symbols.txt");
00041     create_task(StorageFile::GetFileFromApplicationUriAsync(uri)).then([](StorageFile^ file)
00042     {
00043         return FileIO::ReadLinesAsync(file);
00044     }).then([this](IVector<String^>^ lines)
00045     {
00046         _symbols = ref new Vector<Platform::String^>();
00047         for (unsigned int i = 0; i < lines->Size;i++)
00048         {
00049             _symbols->Append(lines->GetAt(i));
00050         }
00051         DropGridView->ItemsSource = _symbols;
00052
00053     });
00054 }
00055
00056 /// <summary>
00057 /// Start button clicked: select a symbol, update the display
00058 /// and start the timer according to the difficulty level
00059 /// </summary>
00060 /// <param name="sender"></param>
00061 /// <param name="e"></param>
00062 void Scenario3_StartDragAsync::StartButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00063 {
00064     if (!_isActive)
00065     {
00066         int index = _rnd() % _symbols->Size;
00067         _symbol = _symbols->GetAt(index);
00068         SourceTextBlock->Text = _symbol;
00069         ResultTextBlock->Text = nullptr;
00070         _isActive = true;
00071
00072         if (_timer == nullptr)
00073         {
00074             _timer = ref new DispatcherTimer();
00075             _timer->Tick += ref new EventHandler<Platform::Object ^>(this, &Scenario3_StartDragAsync::OnTick);
00076         }
00077         bool easy = (EasyRB->IsChecked != nullptr) && EasyRB->IsChecked->Value;
00078         TimeSpan duration;
00079         duration.Duration = easy ? 50000000 : 15000000;
00080         _timer->Interval = duration;
00081         _timer->Start();
00082         StartButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00083         SourceTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00084     }
00085 }
00086
00087 /// <summary>
00088 ///  End of the timer: player lost and we might have to cancel the drag operation
00089 /// </summary>
00090 /// <param name="sender"></param>
00091 /// <param name="args"></param>
00092 void Scenario3_StartDragAsync::OnTick(Platform::Object ^sender, Platform::Object ^args)
00093 {
00094     _timer->Stop();
00095     if (_dragOperation != nullptr)
00096     {
00097         // Cancel the drag operation: this is equivalent of the user pressing Escape
00098         // or releasing the pointer on a non-target
00099         // DropCompleted event would return DataPackageOperation.None as the result
00100         _dragOperation->Cancel();
00101     }
00102     else
00103     {
00104         // We test _isActive just in case the timer expired when we were handling the drop
00105         if (_isActive)
00106         {
00107             EndRound(false);
00108         }
00109     }
00110 }
00111
00112 /// <summary>
00113 /// If the pointer is moved and we are not yet dragging, start a drag operation
00114 /// using StartDragAsync, which will allow a later cancellation
00115 /// </summary>
00116 /// <param name="sender"></param>
00117 /// <param name="e"></param>
00118 void Scenario3_StartDragAsync::SourceTextBlock_PointerMoved(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e)
00119 {
00120     if (_isActive
00121         && e->Pointer->IsInContact
00122         && (_dragOperation == nullptr))
00123     {
00124         _dragOperation = SourceTextBlock->StartDragAsync(e->GetCurrentPoint(SourceTextBlock));
00125         _dragOperation->Completed = ref new AsyncOperationCompletedHandler<DataPackageOperation>(this, &Scenario3_StartDragAsync::DragCompleted);
00126     }
00127 }
00128
00129 /// <summary>
00130 /// Update the user interface when the round is finished
00131 /// </summary>
00132 /// <param name="hasWon"></param>
00133 void Scenario3_StartDragAsync::EndRound(bool hasWon)
00134 {
00135     _isActive = false;
00136     ResultTextBlock->Text = ref new String(hasWon ? L"You win :-) !!" : L"You lose :-( !!");
00137     StartButton->Visibility = Windows::UI::Xaml::Visibility::Visible;
00138     SourceTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00139 }
00140
00141 /// <summary>
00142 /// Completion callback for the asynchronous call:
00143 /// it is called whether the drop succeeded, or the user released the pointer on a non-target
00144 /// or else we cancelled the operation from the timer's callback
00145 /// </summary>
00146 /// <param name="asyncInfo"></param>
00147 /// <param name="asyncStatus"></param>
00148 void Scenario3_StartDragAsync::DragCompleted(IAsyncOperation<DataPackageOperation>^ asyncInfo, AsyncStatus asyncStatus)
00149 {
00150     _dragOperation = nullptr;
00151     if (_timer != nullptr) _timer->Stop();
00152     EndRound((asyncStatus == AsyncStatus::Completed) && (asyncInfo->GetResults() == DataPackageOperation::Copy));
00153 }
00154
00155 /// <summary>
00156 /// DragStarting is called even if we are starting the Drag Operation ourselved with StartDragAsync
00157 /// In this sample, we don't really need to handle it
00158 /// </summary>
00159 /// <param name="sender"></param>
00160 /// <param name="e"></param>
00161 void Scenario3_StartDragAsync::SourceTextBlock_DragStarting(Windows::UI::Xaml::UIElement^ sender, Windows::UI::Xaml::DragStartingEventArgs^ e)
00162 {
00163     e->Data->RequestedOperation = DataPackageOperation::Copy;
00164     e->Data->SetText(_symbol);
00165 }
00166
00167 /// <summary>
00168 /// Check if the sender is a border AND has the dragged symbol
00169 /// </summary>
00170 /// <param name="sender"></param>
00171 /// <returns></returns>
00172 bool Scenario3_StartDragAsync::IsTargetBorder(Platform::Object^ sender)
00173 {
00174     auto border = dynamic_cast<Border^>(sender);
00175     return (border != nullptr) && (dynamic_cast<String^>(border->DataContext) == _symbol);
00176 }
00177
00178 /// <summary>
00179 /// Entering a target: check if this will result in a win
00180 /// </summary>
00181 /// <param name="sender"></param>
00182 /// <param name="e"></param>
00183 void Scenario3_StartDragAsync::DropBorder_DragEnter(Platform::Object^ sender, Windows::UI::Xaml::DragEventArgs^ e)
00184 {
00185     bool win = (_dragOperation != nullptr) && e->DataView->Contains(StandardDataFormats::Text) && IsTargetBorder(sender);
00186     e->DragUIOverride->IsCaptionVisible = false;
00187     e->AcceptedOperation = win ? DataPackageOperation::Copy : DataPackageOperation::None;
00188 }
00189
00190 /// <summary>
00191 /// Drop: check if this results in a win
00192 /// </summary>
00193 /// <param name="sender"></param>
00194 /// <param name="e"></param>
00195 void Scenario3_StartDragAsync::DropBorder_Drop(Platform::Object^ sender, Windows::UI::Xaml::DragEventArgs^ e)
00196 {
00197     bool win = (_dragOperation != nullptr) && e->DataView->Contains(StandardDataFormats::Text) && IsTargetBorder(sender);
00198     e->AcceptedOperation = win ? DataPackageOperation::Copy : DataPackageOperation::None;
00199 }
Generated on Fri Nov 15 2024 22:22:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
AppView() | sealed |
CreateView() | sealed | [virtual]
Initialize(Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
Intersects(const Windows::Foundation::Numerics::float3 &origin, const Windows::Foundation::Numerics::float3 &direction, float *distance) | sealed |
IsValidPosition(const Windows::Foundation::Numerics::float3 &position) | sealed |
Load(Platform::String^entryPoint) | sealed | [virtual]
m_boundingBox | sealed | [private]
m_deviceResources | sealed | [private]
m_height | sealed | [private]
m_holographicSpace | sealed | [private]
m_main | sealed | [private]
m_modelConstantBufferData | sealed | [private]
m_position | sealed | [private]
m_width | sealed | [private]
m_windowClosed | sealed | [private]
m_windowVisible | sealed | [private]
OnKeyPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::KeyEventArgs^args) | sealed | [protected]
OnResuming(Platform::Object^sender, Platform::Object^args) | sealed | [protected]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [protected]
OnViewActivated(Windows::ApplicationModel::Core::CoreApplicationView^sender, Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | sealed | [protected]
OnVisibilityChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::VisibilityChangedEventArgs^args) | sealed | [protected]
OnWindowClosed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::CoreWindowEventArgs^args) | sealed | [protected]
Render(ID3D11DeviceContext *pDeviceContext, IRenderer *pRenderingHelper) override | sealed | [virtual]
Run() | sealed | [virtual]
SetWindow(Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
Uninitialize() | sealed | [virtual]
Update(ID3D11DeviceContext *pDeviceContext) override | sealed | [virtual]
Whiteboard(float width, float height, Windows::Foundation::Numerics::float3 position) | sealed |
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Binary Member List

This is the complete list of members for Scenario2_Binary, including all inherited members.
AppendOutputLine(hstring const &value) | Scenario2_Binary | [private]
CloseSocket() | Scenario2_Binary | [private]
OnClosed(Windows::Networking::Sockets::IWebSocket sender, Windows::Networking::Sockets::WebSocketClosedEventArgs e) | Scenario2_Binary | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario2_Binary |
OnServerCustomValidationRequested(Windows::Networking::Sockets::StreamWebSocket const &, Windows::Networking::Sockets::WebSocketServerCustomValidationRequestedEventArgs e) | Scenario2_Binary | [private]
OnStart(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_Binary |
OnStop(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_Binary |
ReceiveDataAsync(Windows::Networking::Sockets::StreamWebSocket activeSocket) | Scenario2_Binary | [private]
Scenario2_Binary() | Scenario2_Binary |
SendDataAsync(Windows::Networking::Sockets::StreamWebSocket activeSocket) | Scenario2_Binary | [private]
SetBusy(bool value) | Scenario2_Binary | [private]
StartAsync() | Scenario2_Binary | [private]
UpdateVisualState() | Scenario2_Binary | [private]
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MediaFoundationInitializer Member List

This is the complete list of members for MediaFoundationInitializer, including all inherited members.
MediaFoundationInitializer() | MediaFoundationInitializer | [inline]
~MediaFoundationInitializer() | MediaFoundationInitializer | [inline]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/MFSampleGenerator.cpp Source File

  • WindowsAudioSession
  • cpp

MFSampleGenerator.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // MFSampleGenerator.cpp
00013 //
00014
00015 #include "pch.h"
00016 #include "MFSampleGenerator.h"
00017
00018 using namespace SDKSample::WASAPIAudio;
00019
00020 //
00021 //  MFSampleGenerator()
00022 //
00023 MFSampleGenerator::MFSampleGenerator() :
00024     m_Ref( 1 ),
00025     m_IsInitialized( false ),
00026     m_BytesPerPeriod( 0 ),
00027     m_ReaderState( ReaderStateStopped ),
00028     m_MFSourceReader( nullptr ),
00029     m_AudioMT( nullptr ),
00030     m_SampleQueue( nullptr ),
00031     m_SampleQueueTail( &m_SampleQueue )
00032 {
00033 }
00034
00035 //
00036 //  ~MFSampleGenerator()
00037 //
00038 MFSampleGenerator::~MFSampleGenerator()
00039 {
00040     Shutdown();
00041 }
00042
00043 //
00044 //  Flush()
00045 //
00046 void MFSampleGenerator::Flush()
00047 {
00048     while( m_SampleQueue != nullptr )
00049     {
00050         RenderBuffer *SampleBuffer = m_SampleQueue;
00051         m_SampleQueue = SampleBuffer->Next;
00052         SAFE_DELETE( SampleBuffer );
00053     }
00054 }
00055
00056 //
00057 //  Shutdown()
00058 //
00059 void MFSampleGenerator::Shutdown()
00060 {
00061     if (m_IsInitialized)
00062     {
00063         SAFE_RELEASE( m_AudioMT );
00064         SAFE_RELEASE( m_MFSourceReader );
00065
00066         Flush();
00067
00068         m_IsInitialized = false;
00069     }
00070 }
00071
00072 //
00073 //  StartSource()
00074 //
00075 //  Start the media source to read samples
00076 //
00077 HRESULT MFSampleGenerator::StartSource()
00078 {
00079     if (!m_IsInitialized)
00080         return E_UNEXPECTED;
00081
00082     // We can be in EOS if this is a resume from pause
00083     if ( (m_ReaderState == ReaderStatePreRoll) ||
00084          (m_ReaderState == ReaderStatePlaying) ||
00085          (m_ReaderState == ReaderStateEOS) )
00086         return S_FALSE;
00087
00088     HRESULT hr = S_OK;
00089
00090     // This will start the source reader and asynchronously call OnReadSample
00091     hr = m_MFSourceReader->ReadSample( MF_SOURCE_READER_FIRST_AUDIO_STREAM, 0, nullptr, nullptr, nullptr, nullptr );
00092     if (SUCCEEDED( hr ))
00093     {
00094         m_ReaderState = ReaderStatePreRoll;
00095     }
00096
00097     return hr;
00098 }
00099
00100 //
00101 //  StopSource()
00102 //
00103 //  Stops the media source from reading samples
00104 //
00105 void MFSampleGenerator::StopSource()
00106 {
00107     // We only really need this if Source is still reading samples, otherwise
00108     // we should be in an EOS state and parsing existing samples in the queue
00109     m_ReaderState = ReaderStateStopped;
00110 }
00111
00112 //
00113 //  Initialize()
00114 //
00115 //  Configure the Source Reader
00116 //
00117 HRESULT MFSampleGenerator::Initialize( IRandomAccessStream^ stream, UINT32 FramesPerPeriod, WAVEFORMATEX *wfx )
00118 {
00119     HRESULT hr = S_OK;
00120
00121     m_ContentStream = stream;
00122     m_MixFormat = wfx;
00123     IMFByteStream *ByteStream = nullptr;
00124     IMFAttributes *Attributes = nullptr;
00125
00126     SAFE_RELEASE( m_AudioMT );
00127     SAFE_RELEASE( m_MFSourceReader );
00128
00129     hr = MFCreateAttributes( &Attributes, 3 );
00130     if (FAILED( hr ))
00131     {
00132         goto exit;
00133     }
00134
00135     // Specify Source Reader Attributes
00136     hr = Attributes->SetUnknown( MF_SOURCE_READER_ASYNC_CALLBACK, static_cast<IMFSourceReaderCallback *>(this) );
00137     if (FAILED( hr ))
00138     {
00139         goto exit;
00140     }
00141
00142     hr = Attributes->SetString( MF_READWRITE_MMCSS_CLASS_AUDIO, L"Audio" );
00143     if (FAILED( hr ))
00144     {
00145         goto exit;
00146     }
00147
00148     hr = Attributes->SetUINT32( MF_READWRITE_MMCSS_PRIORITY_AUDIO, 0 );
00149     if (FAILED( hr ))
00150     {
00151         goto exit;
00152     }
00153
00154     // Create a stream from IRandomAccessStream
00155     hr = MFCreateMFByteStreamOnStreamEx( reinterpret_cast<IUnknown*>(m_ContentStream), &ByteStream );
00156     if ( FAILED( hr ) )
00157     {
00158         goto exit;
00159     }
00160
00161     // Create source reader
00162     hr = MFCreateSourceReaderFromByteStream( ByteStream, Attributes, &m_MFSourceReader );
00163     if ( FAILED( hr ) )
00164     {
00165         goto exit;
00166     }
00167
00168     // Configures media types
00169     hr = ConfigureStreams();
00170     if ( FAILED( hr ) )
00171     {
00172         goto exit;
00173     }
00174
00175     m_BytesPerPeriod = FramesPerPeriod * m_MixFormat->nBlockAlign;
00176     m_IsInitialized = true;
00177
00178 exit:
00179     if ( FAILED( hr ) )
00180     {
00181         SAFE_RELEASE( m_AudioMT );
00182         SAFE_RELEASE( m_MFSourceReader );
00183     }
00184
00185     SAFE_RELEASE( Attributes );
00186     SAFE_RELEASE( ByteStream );
00187
00188     return hr;
00189 }
00190
00191 //
00192 //  ConfigureStreams()
00193 //
00194 //  Enables the first audio stream and configures the media type
00195 //
00196 HRESULT MFSampleGenerator::ConfigureStreams()
00197 {
00198     HRESULT hr = S_OK;
00199     IMFMediaType *UncompressedMT = nullptr;
00200     IMFMediaType *PartialMT = nullptr;
00201
00202     // Disable all streams
00203     hr = m_MFSourceReader->SetStreamSelection( MF_SOURCE_READER_ALL_STREAMS, false );
00204     if ( FAILED( hr ) )
00205     {
00206         goto exit;
00207     }
00208
00209     // Enable first audio stream
00210     hr = m_MFSourceReader->SetStreamSelection( MF_SOURCE_READER_FIRST_AUDIO_STREAM, true );
00211     if ( FAILED( hr ) )
00212     {
00213         goto exit;
00214     }
00215
00216     hr = CreateAudioType( &PartialMT );
00217     if ( FAILED( hr ) )
00218     {
00219         goto exit;
00220     }
00221
00222     // Set type on source reader so necessary converters / decoders will be added
00223     hr = m_MFSourceReader->SetCurrentMediaType( MF_SOURCE_READER_FIRST_AUDIO_STREAM, nullptr, PartialMT );
00224     if ( FAILED( hr ) )
00225     {
00226         goto exit;
00227     }
00228
00229     // Verify the media type on stream
00230     hr = m_MFSourceReader->GetCurrentMediaType( MF_SOURCE_READER_FIRST_AUDIO_STREAM, &UncompressedMT );
00231     if ( FAILED( hr ) )
00232     {
00233         goto exit;
00234     }
00235
00236     WAVEFORMATEX *pwfx = NULL;
00237     UINT32 cbFormat = 0;
00238     hr = MFCreateWaveFormatExFromMFMediaType( UncompressedMT, &pwfx, &cbFormat );
00239     if ( FAILED( hr ) )
00240     {
00241         goto exit;
00242     }
00243
00244     CoTaskMemFree( pwfx );
00245
00246     m_AudioMT = UncompressedMT;
00247     m_AudioMT->AddRef();
00248
00249 exit:
00250     SAFE_RELEASE( UncompressedMT );
00251     SAFE_RELEASE( PartialMT );
00252
00253     return hr;
00254 }
00255
00256 //
00257 //  CreateAudioType()
00258 //
00259 //  Create an audio type based on the default mix format from the renderer
00260 //
00261 HRESULT MFSampleGenerator::CreateAudioType( IMFMediaType **MediaType )
00262 {
00263     HRESULT hr = S_OK;
00264     IMFMediaType *MT = nullptr;
00265
00266     // Create a partial media type for our mix format (PCM or IEEE Float)
00267     hr = MFCreateMediaType( &MT );
00268     if (FAILED( hr ))
00269     {
00270         goto exit;
00271     }
00272
00273     // Set media type attributes
00274     hr = MT->SetGUID( MF_MT_MAJOR_TYPE, MFMediaType_Audio );
00275     if ( FAILED( hr ) )
00276     {
00277         goto exit;
00278     }
00279
00280     switch (GetRenderSampleType(m_MixFormat))
00281     {
00282     case RenderSampleType::SampleType16BitPCM:
00283     case RenderSampleType::SampleType24in32BitPCM:
00284         hr = MT->SetGUID( MF_MT_SUBTYPE, MFAudioFormat_PCM );
00285         break;
00286     case RenderSampleType::SampleTypeFloat:
00287         hr = MT->SetGUID( MF_MT_SUBTYPE, MFAudioFormat_Float );
00288         break;
00289     default:
00290         hr = E_UNEXPECTED;
00291         break;
00292     }
00293
00294     if (FAILED( hr ))
00295     {
00296         goto exit;
00297     }
00298
00299     hr = MT->SetUINT32( MF_MT_AUDIO_NUM_CHANNELS, m_MixFormat->nChannels );
00300     if (FAILED( hr ))
00301     {
00302         goto exit;
00303     }
00304
00305     hr = MT->SetUINT32( MF_MT_AUDIO_SAMPLES_PER_SECOND, m_MixFormat->nSamplesPerSec );
00306     if (FAILED( hr ))
00307     {
00308         goto exit;
00309     }
00310
00311     hr = MT->SetUINT32( MF_MT_AUDIO_BLOCK_ALIGNMENT, m_MixFormat->nBlockAlign );
00312     if (FAILED( hr ))
00313     {
00314         goto exit;
00315     }
00316
00317     hr = MT->SetUINT32( MF_MT_AUDIO_AVG_BYTES_PER_SECOND, m_MixFormat->nAvgBytesPerSec );
00318     if (FAILED( hr ))
00319     {
00320         goto exit;
00321     }
00322
00323     hr = MT->SetUINT32( MF_MT_AUDIO_BITS_PER_SAMPLE, m_MixFormat->wBitsPerSample );
00324     if (FAILED( hr ))
00325     {
00326         goto exit;
00327     }
00328
00329     hr = MT->SetUINT32( MF_MT_ALL_SAMPLES_INDEPENDENT, true );
00330     if (FAILED( hr ))
00331     {
00332         goto exit;
00333     }
00334
00335     *MediaType = MT;
00336     (*MediaType)->AddRef();
00337
00338 exit:
00339     SAFE_RELEASE( MT );
00340     return hr;
00341 }
00342
00343 //
00344 //  OnEvent()
00345 //
00346 //  Implementation of IMFSourceReaderCallback::OnEvent()
00347 //
00348 HRESULT MFSampleGenerator::OnEvent(_In_ DWORD dwStreamIndex, _In_ IMFMediaEvent *pEvent)
00349 {
00350     return S_OK;
00351 }
00352
00353 //
00354 //  OnFlush()
00355 //
00356 //  Implementation of IMFSourceReaderCallback::OnFlush()
00357 //
00358 HRESULT MFSampleGenerator::OnFlush(_In_ DWORD dwStreamIndex)
00359 {
00360     return S_OK;
00361 }
00362
00363 //
00364 //  OnReadSample()
00365 //
00366 //  Implementation of IMFSourceReaderCallback::OnReadSample().  When a sample is ready, add it to the sample queue.
00367 //
00368 HRESULT MFSampleGenerator::OnReadSample(_In_ HRESULT hrStatus, _In_ DWORD dwStreamIndex, _In_ DWORD dwStreamFlags, _In_ LONGLONG llTimestamp, _In_opt_ IMFSample *pSample)
00369 {
00370     HRESULT hr = S_OK;
00371
00372     if ( (m_ReaderState != ReaderStatePlaying) &&
00373          (m_ReaderState != ReaderStatePreRoll) )
00374         return S_OK;
00375
00376     // If we have a failure, change in stream format, or hit EOF, then we stop reading samples
00377     if ( (FAILED( hrStatus )) ||
00378          (dwStreamFlags & MF_SOURCE_READERF_ENDOFSTREAM) ||
00379          (dwStreamFlags & MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED) )
00380     {
00381         m_ReaderState = ReaderStateEOS;
00382         return S_OK;
00383     }
00384
00385     // Add the data from the Media Sample to our buffer queue
00386     hr = AddSamplesToQueue( pSample );
00387     if (SUCCEEDED( hr ))
00388     {
00389         // Pre-roll PREROLL_DURATION seconds worth of data
00390         if (m_ReaderState == ReaderStatePreRoll)
00391         {
00392             if (IsPreRollFilled())
00393             {
00394                 // Once Pre-roll is filled, audio endpoint will stop rendering silence and start
00395                 // picking up data from the queue
00396                 m_ReaderState = ReaderStatePlaying;
00397             }
00398         }
00399
00400         // Call ReadSample for next asynchronous sample event
00401         hr = m_MFSourceReader->ReadSample( MF_SOURCE_READER_FIRST_AUDIO_STREAM, 0, nullptr, nullptr, nullptr, nullptr );
00402     }
00403
00404     return S_OK;
00405 }
00406
00407 //
00408 //  FillSampleBuffer()
00409 //
00410 //  Called by the audio endpoint to get data to render, and will set cbWritten to valid number of
00411 //  bytes in the buffer.  The buffers are zeroed out when initialized so the endpoint could feasibly
00412 //  treat the data as silence. If there are no more samples to render, will return S_FALSE.
00413 //
00414 HRESULT MFSampleGenerator::FillSampleBuffer( UINT32 BytesToRead, BYTE *Data, UINT32 *cbWritten )
00415 {
00416     HRESULT hr = S_OK;
00417     *cbWritten = 0;
00418
00419     if (nullptr == Data)
00420     {
00421         return E_POINTER;
00422     }
00423
00424     if (!m_IsInitialized)
00425     {
00426         return E_UNEXPECTED;
00427     }
00428
00429     // Not going to return any data here while in a pre-roll state.
00430     if (m_ReaderState == ReaderStatePreRoll)
00431         return S_OK;
00432
00433     RenderBuffer *SampleBuffer = m_SampleQueue;
00434     if (nullptr == SampleBuffer)
00435     {
00436         if (m_ReaderState == ReaderStateEOS)
00437         {
00438             // We are EOS, should be set from OnReadSample() and the client should check for EOS before
00439             // calling FillSampleBuffer()
00440             hr = S_FALSE;
00441         }
00442         else
00443         {
00444             // There shouldn't be a situation where we get here unless the reader has
00445             // somehow gotten into the wrong state
00446             hr = E_FAIL;
00447         }
00448     }
00449     else
00450     {
00451         if (SampleBuffer->BufferSize > BytesToRead)
00452         {
00453             // We don't have enough data in the client audio buffer this pass
00454             // Do nothing and wait for the next sample period
00455             hr = S_OK;
00456         }
00457         else
00458         {
00459             CopyMemory( Data, SampleBuffer->Buffer, SampleBuffer->BufferSize );
00460
00461             *cbWritten = SampleBuffer->BufferSize;
00462             m_SampleQueue = m_SampleQueue->Next;
00463             SAFE_DELETE( SampleBuffer );
00464             hr = S_OK;
00465         }
00466     }
00467
00468     return hr;
00469 }
00470
00471 //
00472 //  AddSamplesToBuffer()
00473 //
00474 //  Data is added to the end of the sample queue
00475 //
00476 HRESULT MFSampleGenerator::AddSamplesToQueue( IMFSample *MFSample )
00477 {
00478     if (nullptr == MFSample)
00479     {
00480         return E_INVALIDARG;
00481     }
00482
00483     HRESULT hr = S_OK;
00484     IMFMediaBuffer *MediaBuffer = nullptr;
00485     BYTE *AudioData = nullptr;
00486     DWORD cbAudioData = 0;
00487
00488     // Since we are storing the raw byte data, convert this to a single buffer
00489     hr = MFSample->ConvertToContiguousBuffer( &MediaBuffer );
00490     if (FAILED( hr ))
00491     {
00492         goto exit;
00493     }
00494
00495     // Lock the sample
00496     hr = MediaBuffer->Lock( &AudioData, NULL, &cbAudioData );
00497     if ( (FAILED( hr )) || (cbAudioData == 0) )
00498     {
00499         goto exit;
00500     }
00501
00502     DWORD cbBytesCopied = 0;
00503
00504     // First fill up any partial buffers from the previous sample
00505     if ( (*m_SampleQueueTail != nullptr) &&
00506          ((*m_SampleQueueTail)->BytesFilled < m_BytesPerPeriod) )
00507     {
00508         RenderBuffer *PartialBuffer = *m_SampleQueueTail;
00509
00510         DWORD cbBytesRemaining = m_BytesPerPeriod - PartialBuffer->BytesFilled;
00511         DWORD cbBytesToCopy = min( cbAudioData, cbBytesRemaining );
00512
00513         CopyMemory( PartialBuffer->Buffer + PartialBuffer->BytesFilled, AudioData, cbBytesToCopy );
00514
00515         PartialBuffer->BytesFilled += cbBytesToCopy;
00516         cbBytesCopied += cbBytesToCopy;
00517
00518         // Move the tail pointer only if we have filled the sample
00519         if (PartialBuffer->BytesFilled == m_BytesPerPeriod)
00520         {
00521             m_SampleQueueTail = &PartialBuffer->Next;
00522         }
00523     }
00524
00525     // Create buffers for the remainder of the samples
00526     while( cbBytesCopied < cbAudioData )
00527     {
00528         RenderBuffer *SampleBuffer = new (std::nothrow) RenderBuffer();
00529         if (nullptr == SampleBuffer)
00530         {
00531             hr = E_OUTOFMEMORY;
00532             goto exit;
00533         }
00534
00535         DWORD cbBytesRemaining = cbAudioData - cbBytesCopied;
00536         DWORD cbBufferLengthInBytes = min( m_BytesPerPeriod, cbBytesRemaining );
00537
00538         SampleBuffer->Buffer = new (std::nothrow) BYTE[ m_BytesPerPeriod ];
00539         if (nullptr == SampleBuffer->Buffer)
00540         {
00541             SAFE_DELETE( SampleBuffer );
00542             hr = E_OUTOFMEMORY;
00543             goto exit;
00544         }
00545
00546         SampleBuffer->BufferSize = m_BytesPerPeriod;
00547         SampleBuffer->BytesFilled = 0;
00548
00549         ZeroMemory( SampleBuffer->Buffer, m_BytesPerPeriod );
00550         CopyMemory( SampleBuffer->Buffer, AudioData + cbBytesCopied, cbBufferLengthInBytes );
00551
00552         SampleBuffer->BytesFilled += cbBufferLengthInBytes;
00553         cbBytesCopied += cbBufferLengthInBytes;
00554
00555         *m_SampleQueueTail = SampleBuffer;
00556
00557         // Move the tail pointer only if we have filled the sample otherwise will get filled the
00558         // next time we add sample data to the queue
00559         if (SampleBuffer->BytesFilled == m_BytesPerPeriod)
00560         {
00561             m_SampleQueueTail = &SampleBuffer->Next;
00562         }
00563     }
00564
00565 exit:
00566     // Unlock the buffer
00567     hr = MediaBuffer->Unlock();
00568     AudioData = nullptr;
00569
00570     SAFE_RELEASE( MediaBuffer );
00571     return hr;
00572 }
00573
00574 //
00575 //  IsPreRollFilled()
00576 //
00577 //  Loops through the queue quickly to see if our pre-roll buffer is filled
00578 //
00579 Platform::Boolean MFSampleGenerator::IsPreRollFilled()
00580 {
00581     DWORD TotalBytesFilled = 0;
00582
00583     RenderBuffer *SampleBuffer = m_SampleQueue;
00584     while( SampleBuffer != nullptr )
00585     {
00586         TotalBytesFilled += SampleBuffer->BytesFilled;
00587
00588         // For uncompressed formats, nAvgBytesPerSec should equal nSamplesPerSecond * nBlockAlign
00589         if (TotalBytesFilled >= (m_MixFormat->nAvgBytesPerSec * PREROLL_DURATION_SEC))
00590         {
00591             return true;
00592         }
00593
00594         SampleBuffer = SampleBuffer->Next;
00595     }
00596
00597     return false;
00598 }
Generated on Fri Nov 15 2024 22:22:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SuperMutt Member List

This is the complete list of members for SuperMutt, including all inherited members.
DeviceInterfaceClass | SuperMutt | [static]
DevicePid | SuperMutt |
DeviceVid | SuperMutt |
Generated on Fri Nov 15 2024 22:23:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cs/Common/DeviceResources.cs Source File

  • BasicHologram
  • cs
  • Common

DeviceResources.cs

Go to the documentation of this file.
00001 ﻿using SharpDX.Direct3D;
00002 using SharpDX.Direct3D11;
00003 using System;
00004 using System.Collections.Generic;
00005 using System.Runtime.InteropServices;
00006 using System.Threading;
00007 using Windows.Graphics.DirectX.Direct3D11;
00008 using Windows.Graphics.Holographic;
00009
00010 namespace BasicHologram.Common
00011 {
00012     /// <summary>
00013     /// Controls all the DirectX device resources.
00014     /// </summary>
00015     internal class DeviceResources : Disposer
00016     {
00017         // Notifies the application that owns DeviceResources when the Direct3D device is lost.
00018         public event EventHandler DeviceLost;
00019
00020         // Notifies the application that owns DeviceResources when the Direct3D device is restored.
00021         public event EventHandler DeviceRestored;
00022
00023         // Direct3D objects.
00024         private Device3                         d3dDevice;
00025         private DeviceContext3                  d3dContext;
00026         private SharpDX.DXGI.Adapter3           dxgiAdapter;
00027
00028         // Direct3D interop objects.
00029         private IDirect3DDevice                 d3dInteropDevice;
00030
00031         // Direct2D factories.
00032         private SharpDX.Direct2D1.Factory2      d2dFactory;
00033         private SharpDX.DirectWrite.Factory1    dwriteFactory;
00034         private SharpDX.WIC.ImagingFactory2     wicFactory;
00035
00036         // The holographic space provides a preferred DXGI adapter ID.
00037         private HolographicSpace                holographicSpace = null;
00038
00039         // Properties of the Direct3D device currently in use.
00040         private FeatureLevel                    d3dFeatureLevel = FeatureLevel.Level_10_0;
00041
00042         // Whether or not the current Direct3D device supports the optional feature
00043         // for setting the render target array index from the vertex shader stage.
00044         bool                                    d3dDeviceSupportsVprt = false;
00045
00046         // Back buffer resources, etc. for attached holographic cameras.
00047         private Dictionary<uint, CameraResources> cameraResourcesDictionary = new Dictionary<uint, CameraResources>();
00048         private Object                          cameraResourcesLock = new Object();
00049
00050         /// <summary>
00051         /// Constructor for DeviceResources.
00052         /// </summary>
00053         public DeviceResources()
00054         {
00055             CreateDeviceIndependentResources();
00056         }
00057
00058         /// <summary>
00059         /// Configures resources that don't depend on the Direct3D device.
00060         /// </summary>
00061         private void CreateDeviceIndependentResources()
00062         {
00063             // Dispose previous references and set to null
00064             this.RemoveAndDispose(ref d2dFactory);
00065             this.RemoveAndDispose(ref dwriteFactory);
00066             this.RemoveAndDispose(ref wicFactory);
00067
00068             // Initialize Direct2D resources.
00069             var debugLevel = SharpDX.Direct2D1.DebugLevel.None;
00070 #if DEBUG
00071             if (DirectXHelper.SdkLayersAvailable())
00072             {
00073                 debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
00074             }
00075 #endif
00076
00077             // Initialize the Direct2D Factory.
00078             d2dFactory = this.ToDispose(
00079                 new SharpDX.Direct2D1.Factory2(
00080                     SharpDX.Direct2D1.FactoryType.SingleThreaded,
00081                     debugLevel
00082                     )
00083                 );
00084
00085             // Initialize the DirectWrite Factory.
00086             dwriteFactory = this.ToDispose(
00087                 new SharpDX.DirectWrite.Factory1(SharpDX.DirectWrite.FactoryType.Shared)
00088                 );
00089
00090             // Initialize the Windows Imaging Component (WIC) Factory.
00091             wicFactory = this.ToDispose(
00092                 new SharpDX.WIC.ImagingFactory2()
00093                 );
00094         }
00095
00096         public void SetHolographicSpace(HolographicSpace holographicSpace)
00097         {
00098             // Cache the holographic space. Used to re-initalize during device-lost scenarios.
00099             this.holographicSpace = holographicSpace;
00100
00101             InitializeUsingHolographicSpace();
00102         }
00103
00104         public void InitializeUsingHolographicSpace()
00105         {
00106             // The holographic space might need to determine which adapter supports
00107             // holograms, in which case it will specify a non-zero PrimaryAdapterId.
00108             int shiftPos = sizeof(uint);
00109             ulong id = (ulong)holographicSpace.PrimaryAdapterId.LowPart | (((ulong)holographicSpace.PrimaryAdapterId.HighPart) << shiftPos);
00110
00111             // When a primary adapter ID is given to the app, the app should find
00112             // the corresponding DXGI adapter and use it to create Direct3D devices
00113             // and device contexts. Otherwise, there is no restriction on the DXGI
00114             // adapter the app can use.
00115             if (id != 0)
00116             {
00117                 // Create the DXGI factory.
00118                 using (var dxgiFactory4 = new SharpDX.DXGI.Factory4())
00119                 {
00120                     // Retrieve the adapter specified by the holographic space.
00121                     IntPtr adapterPtr;
00122                     dxgiFactory4.EnumAdapterByLuid((long)id, InteropStatics.IDXGIAdapter3, out adapterPtr);
00123
00124                     if (adapterPtr != IntPtr.Zero)
00125                     {
00126                         dxgiAdapter = new SharpDX.DXGI.Adapter3(adapterPtr);
00127                     }
00128                 }
00129             }
00130             else
00131             {
00132                 this.RemoveAndDispose(ref dxgiAdapter);
00133             }
00134
00135             CreateDeviceResources();
00136
00137             holographicSpace.SetDirect3D11Device(d3dInteropDevice);
00138         }
00139
00140
00141         /// <summary>
00142         /// Configures the Direct3D device, and stores handles to it and the device context.
00143         /// </summary>
00144         private void CreateDeviceResources()
00145         {
00146             DisposeDeviceAndContext();
00147
00148             // This flag adds support for surfaces with a different color channel ordering
00149             // than the API default. It is required for compatibility with Direct2D.
00150             DeviceCreationFlags creationFlags = DeviceCreationFlags.BgraSupport;
00151
00152 #if DEBUG
00153             if (DirectXHelper.SdkLayersAvailable())
00154             {
00155                 // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00156                 creationFlags |= DeviceCreationFlags.Debug;
00157             }
00158 #endif
00159
00160             // This array defines the set of DirectX hardware feature levels this app will support.
00161             // Note the ordering should be preserved.
00162             // Note that HoloLens supports feature level 11.1. The HoloLens emulator is also capable
00163             // of running on graphics cards starting with feature level 10.0.
00164             FeatureLevel[] featureLevels =
00165             {
00166                 FeatureLevel.Level_12_1,
00167                 FeatureLevel.Level_12_0,
00168                 FeatureLevel.Level_11_1,
00169                 FeatureLevel.Level_11_0,
00170                 FeatureLevel.Level_10_1,
00171                 FeatureLevel.Level_10_0
00172             };
00173
00174             // Create the Direct3D 11 API device object and a corresponding context.
00175             try
00176             {
00177                 if (null != dxgiAdapter)
00178                 {
00179                     using (var device = new Device(dxgiAdapter, creationFlags, featureLevels))
00180                     {
00181                         // Store pointers to the Direct3D 11.1 API device.
00182                         d3dDevice = this.ToDispose(device.QueryInterface<Device3>());
00183                     }
00184                 }
00185                 else
00186                 {
00187                     using (var device = new Device(DriverType.Hardware, creationFlags, featureLevels))
00188                     {
00189                         // Store a pointer to the Direct3D device.
00190                         d3dDevice = this.ToDispose(device.QueryInterface<Device3>());
00191                     }
00192                 }
00193             }
00194             catch
00195             {
00196                 // If the initialization fails, fall back to the WARP device.
00197                 // For more information on WARP, see:
00198                 // http://go.microsoft.com/fwlink/?LinkId=286690
00199                 using (var device = new Device(DriverType.Warp, creationFlags, featureLevels))
00200                 {
00201                     d3dDevice = this.ToDispose(device.QueryInterface<Device3>());
00202                 }
00203             }
00204
00205             // Cache the feature level of the device that was created.
00206             d3dFeatureLevel = d3dDevice.FeatureLevel;
00207
00208             // Store a pointer to the Direct3D immediate context.
00209             d3dContext = this.ToDispose(d3dDevice.ImmediateContext3);
00210
00211             // Acquire the DXGI interface for the Direct3D device.
00212             using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device3>())
00213             {
00214                 // Wrap the native device using a WinRT interop object.
00215                 IntPtr pUnknown;
00216                 UInt32 hr = InteropStatics.CreateDirect3D11DeviceFromDXGIDevice(dxgiDevice.NativePointer, out pUnknown);
00217                 if (hr == 0)
00218                 {
00219                     d3dInteropDevice = (IDirect3DDevice)Marshal.GetObjectForIUnknown(pUnknown);
00220                     Marshal.Release(pUnknown);
00221                 }
00222
00223                 // Store a pointer to the DXGI adapter.
00224                 // This is for the case of no preferred DXGI adapter, or fallback to WARP.
00225                 dxgiAdapter = this.ToDispose(dxgiDevice.Adapter.QueryInterface<SharpDX.DXGI.Adapter3>());
00226             }
00227
00228             // Check for device support for the optional feature that allows setting the render target array index from the vertex shader stage.
00229             var options = d3dDevice.CheckD3D113Features3();
00230             if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer)
00231             {
00232                 d3dDeviceSupportsVprt = true;
00233             }
00234         }
00235
00236         /// <summary>
00237         /// Disposes of a device-based resources.
00238         /// </summary>
00239         private void DisposeDeviceAndContext()
00240         {
00241             // Dispose existing references to Direct3D 11 device and context, and set to null.
00242             this.RemoveAndDispose(ref d3dDevice);
00243             this.RemoveAndDispose(ref d3dContext);
00244
00245             // Release the interop device.
00246             d3dInteropDevice = null;
00247         }
00248
00249         /// <summary>
00250         /// Validates the back buffer for each HolographicCamera and recreates
00251         /// resources for back buffers that have changed.
00252         /// Locks the set of holographic camera resources until the function exits.
00253         /// </summary>
00254         public void EnsureCameraResources(HolographicFrame frame, HolographicFramePrediction prediction)
00255         {
00256             UseHolographicCameraResources((Dictionary<uint, CameraResources> cameraResourcesDictionary) =>
00257             {
00258                 foreach (var pose in prediction.CameraPoses)
00259                 {
00260                     var renderingParameters = frame.GetRenderingParameters(pose);
00261                     var cameraResources = cameraResourcesDictionary[pose.HolographicCamera.Id];
00262
00263                     cameraResources.CreateResourcesForBackBuffer(this, ref renderingParameters);
00264                 }
00265             });
00266         }
00267
00268         /// <summary>
00269         /// Prepares to allocate resources and adds resource views for a camera.
00270         /// Locks the set of holographic camera resources until the function exits.
00271         /// </summary>
00272         public void AddHolographicCamera(HolographicCamera camera)
00273         {
00274             UseHolographicCameraResources((Dictionary<uint, CameraResources> cameraResourcesDictionary) =>
00275             {
00276                 cameraResourcesDictionary.Add(camera.Id, new CameraResources(camera));
00277             });
00278         }
00279
00280         // Deallocates resources for a camera and removes the camera from the set.
00281         // Locks the set of holographic camera resources until the function exits.
00282         public void RemoveHolographicCamera(HolographicCamera camera)
00283         {
00284             UseHolographicCameraResources((Dictionary<uint, CameraResources> cameraResourcesDictionary) =>
00285             {
00286                 CameraResources cameraResources = cameraResourcesDictionary[camera.Id];
00287
00288                 if (null != cameraResources)
00289                 {
00290                     cameraResources.ReleaseResourcesForBackBuffer(this);
00291                     cameraResourcesDictionary.Remove(camera.Id);
00292                 }
00293             });
00294         }
00295
00296         /// <summary>
00297         /// Recreate all device resources and set them back to the current state.
00298         /// Locks the set of holographic camera resources until the function exits.
00299         /// </summary>
00300         public void HandleDeviceLost()
00301         {
00302             DeviceLost.Invoke(this, null);
00303
00304             UseHolographicCameraResources((Dictionary<uint, CameraResources> cameraResourcesDictionary) =>
00305             {
00306                 foreach (var pair in cameraResourcesDictionary)
00307                 {
00308                     CameraResources cameraResources = pair.Value;
00309                     cameraResources.ReleaseAllDeviceResources(this);
00310                 }
00311             });
00312
00313             InitializeUsingHolographicSpace();
00314
00315             DeviceRestored.Invoke(this, null);
00316         }
00317
00318         /// <summary>
00319         /// Call this method when the app suspends. It provides a hint to the driver that the app
00320         /// is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00321         /// </summary>
00322         public void Trim()
00323         {
00324             d3dContext.ClearState();
00325
00326             using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device3>())
00327             {
00328                 dxgiDevice.Trim();
00329             }
00330         }
00331
00332         /// <summary>
00333         /// Present the contents of the swap chain to the screen.
00334         /// Locks the set of holographic camera resources until the function exits.
00335         /// </summary>
00336         public void Present(ref HolographicFrame frame)
00337         {
00338             // By default, this API waits for the frame to finish before it returns.
00339             // Holographic apps should wait for the previous frame to finish before
00340             // starting work on a new frame. This allows for better results from
00341             // holographic frame predictions.
00342             var presentResult = frame.PresentUsingCurrentPrediction(
00343                 HolographicFramePresentWaitBehavior.WaitForFrameToFinish
00344                 );
00345
00346             // The PresentUsingCurrentPrediction API will detect when the graphics device
00347             // changes or becomes invalid. When this happens, it is considered a Direct3D
00348             // device lost scenario.
00349             if (presentResult == HolographicFramePresentResult.DeviceRemoved)
00350             {
00351                 // The Direct3D device, context, and resources should be recreated.
00352                 HandleDeviceLost();
00353             }
00354         }
00355
00356         public delegate void SwapChainAction(Dictionary<uint, CameraResources> cameraResourcesDictionary);
00357         public delegate bool SwapChainActionWithResult(Dictionary<uint, CameraResources> cameraResourcesDictionary);
00358
00359         /// <summary>
00360         /// Device-based resources for holographic cameras are stored in a std::map. Access this list by providing a
00361         /// callback to this function, and the std::map will be guarded from add and remove
00362         /// events until the callback returns. The callback is processed immediately and must
00363         /// not contain any nested calls to UseHolographicCameraResources.
00364         /// The callback takes a parameter of type Dictionary<uint, CameraResources> cameraResourcesDictionary
00365         /// through which the list of cameras will be accessed.
00366         /// The callback also returns a boolean result.
00367         /// </summary>
00368         public bool UseHolographicCameraResources(SwapChainActionWithResult callback)
00369         {
00370             bool success = false;
00371             lock(cameraResourcesLock)
00372             {
00373                 success = callback(cameraResourcesDictionary);
00374             }
00375             return success;
00376         }
00377
00378         /// <summary>
00379         /// Device-based resources for holographic cameras are stored in a std::map. Access this list by providing a
00380         /// callback to this function, and the std::map will be guarded from add and remove
00381         /// events until the callback returns. The callback is processed immediately and must
00382         /// not contain any nested calls to UseHolographicCameraResources.
00383         /// The callback takes a parameter of type Dictionary<uint, CameraResources> cameraResourcesDictionary
00384         /// through which the list of cameras will be accessed.
00385         /// </summary>
00386         public void UseHolographicCameraResources(SwapChainAction callback)
00387         {
00388             lock(cameraResourcesLock)
00389             {
00390                 callback(cameraResourcesDictionary);
00391             }
00392         }
00393
00394 #region Property accessors
00395
00396         public Device3 D3DDevice
00397         {
00398             get { return d3dDevice; }
00399         }
00400
00401         public DeviceContext3 D3DDeviceContext
00402         {
00403             get { return d3dContext; }
00404         }
00405
00406         public SharpDX.DXGI.Adapter3 DxgiAdapter
00407         {
00408             get { return dxgiAdapter; }
00409         }
00410
00411         public IDirect3DDevice D3DInteropDevice
00412         {
00413             get { return d3dInteropDevice; }
00414         }
00415
00416         public SharpDX.Direct2D1.Factory2 D2DFactory
00417         {
00418             get { return d2dFactory; }
00419         }
00420
00421         public SharpDX.DirectWrite.Factory1 DWriteFactory
00422         {
00423             get { return dwriteFactory; }
00424         }
00425
00426         public SharpDX.WIC.ImagingFactory2 WicImagingFactory
00427         {
00428             get { return wicFactory; }
00429         }
00430
00431         public SharpDX.Direct3D.FeatureLevel D3DDeviceFeatureLevel
00432         {
00433             get { return d3dFeatureLevel; }
00434         }
00435
00436         public bool D3DDeviceSupportsVprt
00437         {
00438             get { return d3dDeviceSupportsVprt; }
00439         }
00440
00441         #endregion
00442     }
00443 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cs/Scenario1_SampleBackgroundTask.xaml.cs Source File

  • BackgroundActivation
  • cs

Scenario1_SampleBackgroundTask.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.Background;
00014 using Windows.Storage;
00015 using Windows.UI.Core;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019 using SDKTemplate;
00020
00021 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class SampleBackgroundTask : Page
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         private MainPage rootPage = MainPage.Current;
00033
00034         public SampleBackgroundTask()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         /// <summary>
00040         /// Invoked when this page is about to be displayed in a Frame.
00041         /// </summary>
00042         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00043         /// property is typically used to configure the page.</param>
00044         protected override void OnNavigatedTo(NavigationEventArgs e)
00045         {
00046             foreach (var task in BackgroundTaskRegistration.AllTasks)
00047             {
00048                 if (task.Value.Name == BackgroundTaskSample.SampleBackgroundTaskName)
00049                 {
00050                     AttachProgressAndCompletedHandlers(task.Value);
00051                     BackgroundTaskSample.UpdateBackgroundTaskRegistrationStatus(BackgroundTaskSample.SampleBackgroundTaskName, true);
00052                     break;
00053                 }
00054             }
00055
00056             UpdateUI();
00057         }
00058
00059         /// <summary>
00060         /// Register a SampleBackgroundTask.
00061         /// </summary>
00062         /// <param name="sender"></param>
00063         /// <param name="e"></param>
00064         private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
00065         {
00066             var task = BackgroundTaskSample.RegisterBackgroundTask(null,
00067                                                                    BackgroundTaskSample.SampleBackgroundTaskName,
00068                                                                    new SystemTrigger(SystemTriggerType.TimeZoneChange, false),
00069                                                                    null);
00070             AttachProgressAndCompletedHandlers(task);
00071             UpdateUI();
00072         }
00073
00074         /// <summary>
00075         /// Unregister a SampleBackgroundTask.
00076         /// </summary>
00077         /// <param name="sender"></param>
00078         /// <param name="e"></param>
00079         private void UnregisterBackgroundTask(object sender, RoutedEventArgs e)
00080         {
00081             BackgroundTaskSample.UnregisterBackgroundTasks(BackgroundTaskSample.SampleBackgroundTaskName);
00082             UpdateUI();
00083         }
00084
00085         /// <summary>
00086         /// Attach progress and completed handers to a background task.
00087         /// </summary>
00088         /// <param name="task">The task to attach progress and completed handlers to.</param>
00089         private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
00090         {
00091             task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
00092             task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
00093         }
00094
00095         /// <summary>
00096         /// Handle background task progress.
00097         /// </summary>
00098         /// <param name="task">The task that is reporting progress.</param>
00099         /// <param name="e">Arguments of the progress report.</param>
00100         private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
00101         {
00102             var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00103             {
00104                 var progress = "Progress: " + args.Progress + "%";
00105                 BackgroundTaskSample.SampleBackgroundTaskProgress = progress;
00106                 UpdateUI();
00107             });
00108         }
00109
00110         /// <summary>
00111         /// Handle background task completion.
00112         /// </summary>
00113         /// <param name="task">The task that is reporting completion.</param>
00114         /// <param name="e">Arguments of the completion report.</param>
00115         private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
00116         {
00117             UpdateUI();
00118         }
00119
00120         /// <summary>
00121         /// Update the scenario UI.
00122         /// </summary>
00123         private async void UpdateUI()
00124         {
00125             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00126             () =>
00127             {
00128                 RegisterButton.IsEnabled = !BackgroundTaskSample.SampleBackgroundTaskRegistered;
00129                 UnregisterButton.IsEnabled = BackgroundTaskSample.SampleBackgroundTaskRegistered;
00130                 Progress.Text = BackgroundTaskSample.SampleBackgroundTaskProgress;
00131                 Status.Text = BackgroundTaskSample.GetBackgroundTaskStatus(BackgroundTaskSample.SampleBackgroundTaskName);
00132             });
00133         }
00134     }
00135 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cpp/SocketReaderWriter.cpp Source File

  • WiFiDirect
  • cpp

SocketReaderWriter.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SocketReaderWriter.h"
00014
00015 using namespace Platform;
00016 using namespace Windows::Networking::Sockets;
00017 using namespace Windows::Storage::Streams;
00018 using namespace SDKTemplate;
00019 using namespace Windows::Devices::WiFiDirect;
00020 using namespace Windows::Devices::Enumeration;
00021
00022 Platform::Array<byte>^ SDKTemplate::CustomOui = ref new Platform::Array<byte>{ 0xAA, 0xBB, 0xCC };
00023 byte SDKTemplate::CustomOuiType = 0xDD;
00024 Platform::Array<byte>^ SDKTemplate::WfaOui = ref new Platform::Array<byte>{ 0x50, 0x6F, 0x9A };
00025 Platform::Array<byte>^ SDKTemplate::MsftOui = ref new Platform::Array<byte>{ 0x00, 0x50, 0xF2 };
00026 Platform::String^ SDKTemplate::strServerPort = "50001";
00027
00028 void SocketReaderWriter::Close()
00029 {
00030     delete _socketReader;
00031     delete _socketWriter;
00032     delete _streamSocket;
00033 }
00034
00035 void SocketReaderWriter::WriteMessage(String^ message)
00036 {
00037     _socketWriter->WriteUInt32(_socketWriter->MeasureString(message));
00038     _socketWriter->WriteString(message);
00039     concurrency::task<unsigned int> storeTask(_socketWriter->StoreAsync());
00040     storeTask.then([this, message](concurrency::task<unsigned int> resultTask)
00041     {
00042         try
00043         {
00044             unsigned int numBytesWritten = resultTask.get();
00045             if (numBytesWritten > 0)
00046             {
00047                 _rootPage->NotifyUserFromBackground("Sent message: " + message, NotifyType::StatusMessage);
00048             }
00049             else
00050             {
00051                 _rootPage->NotifyUserFromBackground("The remote side closed the socket", NotifyType::ErrorMessage);
00052             }
00053         }
00054         catch (Exception^ e)
00055         {
00056             _rootPage->NotifyUserFromBackground("Failed to send message with error: " + e->Message, NotifyType::ErrorMessage);
00057         }
00058     });
00059 }
00060
00061 void SocketReaderWriter::ReadMessage()
00062 {
00063     concurrency::task<unsigned int> loadTask(_socketReader->LoadAsync(sizeof(UINT32)));
00064     loadTask.then([this](concurrency::task<unsigned int> stringBytesTask)
00065     {
00066         try
00067         {
00068             unsigned int bytesRead = stringBytesTask.get();
00069             if (bytesRead > 0)
00070             {
00071                 unsigned int strLength = (unsigned int)_socketReader->ReadUInt32();
00072                 concurrency::task<unsigned int> loadStringTask(_socketReader->LoadAsync(strLength));
00073                 loadStringTask.then([this, strLength](concurrency::task<unsigned int> resultTask)
00074                 {
00075                     try
00076                     {
00077                         unsigned int bytesRead = resultTask.get();
00078                         if (bytesRead > 0)
00079                         {
00080                             _currentMessage = _socketReader->ReadString(strLength);
00081                             _rootPage->NotifyUserFromBackground("Got message: " + _currentMessage, NotifyType::StatusMessage);
00082                             ReadMessage();
00083                         }
00084                         else
00085                         {
00086                             _rootPage->NotifyUserFromBackground("The remote side closed the socket", NotifyType::ErrorMessage);
00087                         }
00088                     }
00089                     catch (Exception^ e)
00090                     {
00091                         _rootPage->NotifyUserFromBackground("Failed to read from socket: " + e->Message, NotifyType::ErrorMessage);
00092                     }
00093                 });
00094             }
00095             else
00096             {
00097                 _rootPage->NotifyUserFromBackground("The remote side closed the socket", NotifyType::ErrorMessage);
00098             }
00099         }
00100         catch (Exception^ e)
00101         {
00102             _rootPage->NotifyUserFromBackground("Failed to read from socket: " + e->Message, NotifyType::ErrorMessage);
00103         }
00104     });
00105 }
00106
00107 String^ SocketReaderWriter::GetCurrentMessage()
00108 {
00109     return _currentMessage;
00110 }
00111
00112 DiscoveredDevice::DiscoveredDevice(DeviceInformation^ deviceInfoIn)
00113 {
00114     deviceInfo = deviceInfoIn;
00115 }
00116
00117 ConnectedDevice::ConnectedDevice(String^ displayName, WiFiDirectDevice^ wfdDevice, SocketReaderWriter^ socketRW)
00118 {
00119     this->socketRW = socketRW;
00120     this->wfdDevice = wfdDevice;
00121     this->displayName = displayName;
00122 }
Generated on Fri Nov 15 2024 22:22:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ChatListView Member List

This is the complete list of members for ChatListView, including all inherited members.
ArrangeOverride(Size finalSize) | ChatListView | [inline, protected]
averageContainerHeight | ChatListView | [private]
ChatListView() | ChatListView | [inline]
itemsSeen | ChatListView | [private]
OnApplyTemplate() | ChatListView | [inline, protected]
ProcessDataVirtualizationScrollOffsetsAsync(double actualHeight) | ChatListView | [inline, private]
processingScrollOffsets | ChatListView | [private]
processingScrollOffsetsDeferred | ChatListView | [private]
StartProcessingDataVirtualizationScrollOffsets(double actualHeight) | ChatListView | [inline, private]
UpdateRunningAverageContainerHeight(ListViewBase sender, ContainerContentChangingEventArgs args) | ChatListView | [inline, private]
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DPhotoAdjustment/cpp/PhotoAdjustmentRenderer.h Source File

  • D2DPhotoAdjustment
  • cpp

PhotoAdjustmentRenderer.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015 #include "PhotoAdjustmentProperties.h"
00016
00017 namespace D2DPhotoAdjustment
00018 {
00019     class PhotoAdjustmentRenderer : public DX::IDeviceNotify
00020     {
00021     public:
00022         PhotoAdjustmentRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00023         ~PhotoAdjustmentRenderer();
00024
00025         void CreateDeviceIndependentResources();
00026         void CreateDeviceDependentResources();
00027         void CreateWindowSizeDependentResources();
00028         void ReleaseDeviceDependentResources();
00029         void OnColorProfileChanged(_In_ Windows::Graphics::Display::DisplayInformation^ sender);
00030         void UpdatePhotoAdjustmentValues(PhotoAdjustmentProperties properties);
00031         void Draw();
00032
00033         // IDeviceNotify methods handle device lost and restored.
00034         virtual void OnDeviceLost();
00035         virtual void OnDeviceRestored();
00036
00037     private:
00038         void UpdateZoomState();
00039         void UpdateDisplayColorContext(_In_ Windows::Storage::Streams::DataReader^ colorProfileDataReader);
00040         float ConvertDipProperty(float valueInDips);
00041
00042     private:
00043         // Cached pointer to device resources.
00044         std::shared_ptr<DX::DeviceResources>                    m_deviceResources;
00045         Platform::Agile<Windows::UI::Input::GestureRecognizer>  m_gestureRecognizer;
00046         Microsoft::WRL::ComPtr<IWICFormatConverter>             m_formatConvert;
00047
00048         // Device-independent resources.
00049         Microsoft::WRL::ComPtr<IWICColorContext>                m_wicColorContext;
00050
00051         // Device-dependent resources.
00052         Microsoft::WRL::ComPtr<ID2D1ImageSourceFromWic>         m_imageSource;
00053         Microsoft::WRL::ComPtr<ID2D1TransformedImageSource>     m_scaledImage;
00054         Microsoft::WRL::ComPtr<ID2D1Effect>                     m_colorManagement;
00055         Microsoft::WRL::ComPtr<ID2D1Effect>                     m_straighten;
00056         Microsoft::WRL::ComPtr<ID2D1Effect>                     m_temperatureTint;
00057         Microsoft::WRL::ComPtr<ID2D1Effect>                     m_saturation;
00058         Microsoft::WRL::ComPtr<ID2D1Effect>                     m_contrast;
00059         Microsoft::WRL::ComPtr<ID2D1Effect>                     m_highlightsShadows;
00060         Microsoft::WRL::ComPtr<ID2D1Effect>                     m_outputEffect;
00061
00062         // Image view state.
00063         Windows::Foundation::Size                               m_imageSize;
00064         Windows::Foundation::Size                               m_panelSize;
00065         float                                                   m_zoom;
00066         bool                                                    m_isWindowClosed;
00067
00068         // Effect properties measured in DIPs.
00069         float                                                   m_hsMaskRadiusDips;
00070
00071         // Adjustable parameters.
00072         float                                                   m_maxZoom;
00073     };
00074 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OCR/cpp/SampleConfiguration.cpp Source File

  • OCR
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "OCR image file", "SDKTemplate.OcrFileImage" },
00021     { "OCR captured image", "SDKTemplate.OcrCapturedImage" }
00022 };
Generated on Fri Nov 15 2024 22:17:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlDocument/cs/Scenario3_XmlLoading.xaml.cs Source File

  • XmlDocument
  • cs

Scenario3_XmlLoading.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00019
00020 namespace Xml
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class XmlLoading : Page
00026     {
00027         private MainPage rootPage;
00028
00029         public XmlLoading()
00030         {
00031             this.InitializeComponent();
00032
00033             Scenario3Init();
00034         }
00035
00036         /// <summary>
00037         /// Invoked when this page is about to be displayed in a Frame.
00038         /// </summary>
00039         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00040         /// property is typically used to configure the page.</param>
00041         protected override void OnNavigatedTo(NavigationEventArgs e)
00042         {
00043             rootPage = MainPage.Current;
00044         }
00045
00046         async void Scenario3Init()
00047         {
00048             try
00049             {
00050                 Windows.Data.Xml.Dom.XmlDocument doc = await Scenario.LoadXmlFile("loadExternaldtd", "xmlWithExternaldtd.xml");
00051                 Scenario.RichEditBoxSetMsg(scenario3OriginalData, doc.GetXml(), true);
00052             }
00053             catch (Exception exp)
00054             {
00055                 Scenario.RichEditBoxSetError(scenario3Result, exp.Message);
00056                 rootPage.NotifyUser("Exception occured while loading xml file!", NotifyType.ErrorMessage);
00057             }
00058         }
00059
00060         /// <summary>
00061         /// This is the click handler for the 'scenario3BtnBuffer' button.  You would replace this with your own handler
00062         /// if you have a button or buttons on this page.
00063         /// </summary>
00064         /// <param name="sender"></param>
00065         /// <param name="e"></param>
00066         private async void Scenario3BtnBuffer_Click(object sender, RoutedEventArgs e)
00067         {
00068             try
00069             {
00070                 // Get load settings
00071                 var loadSettings = new Windows.Data.Xml.Dom.XmlLoadSettings();
00072                 if (true == scenario3RB1.IsChecked)
00073                 {
00074                     loadSettings.ProhibitDtd = true;        // DTD is prohibited
00075                     loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
00076                 }
00077                 else if (true == scenario3RB2.IsChecked)
00078                 {
00079                     loadSettings.ProhibitDtd = false;       // DTD is not prohibited
00080                     loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
00081                 }
00082                 else if (true == scenario3RB3.IsChecked)
00083                 {
00084                     loadSettings.ProhibitDtd = false;       // DTD is not prohibited
00085                     loadSettings.ResolveExternals = true;   // Enable the resolve to external definitions such as external DTD
00086                 }
00087
00088                 String xml;
00089
00090                 scenario3OriginalData.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xml);
00091
00092                 // Set external dtd file path
00093                 if (loadSettings.ResolveExternals == true && loadSettings.ProhibitDtd == false)
00094                 {
00095                     Windows.Storage.StorageFolder storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("loadExternaldtd");
00096                     String dtdPath = storageFolder.Path + "\\dtd.txt";
00097                     xml = xml.Replace("dtd.txt", dtdPath);
00098                 }
00099
00100                 var dataWriter = new Windows.Storage.Streams.DataWriter();
00101
00102                 dataWriter.WriteString(xml);
00103
00104                 Windows.Storage.Streams.IBuffer ibuffer = dataWriter.DetachBuffer();
00105
00106                 var doc = new Windows.Data.Xml.Dom.XmlDocument();
00107
00108                 doc.LoadXmlFromBuffer(ibuffer, loadSettings);
00109
00110                 Scenario.RichEditBoxSetMsg(scenario3Result, doc.GetXml(), true);
00111             }
00112             catch (Exception)
00113             {
00114                 // After loadSettings.ProhibitDtd is set to true, the exception is expected as the sample XML contains DTD
00115                 Scenario.RichEditBoxSetError(scenario3Result, "Error: DTD is prohibited");
00116             }
00117         }
00118
00119         /// <summary>
00120         /// This is the click handler for the 'Scenario3BtnFile' button.  You would replace this with your own handler
00121         /// if you have a button or buttons on this page.
00122         /// </summary>
00123         /// <param name="sender"></param>
00124         /// <param name="e"></param>
00125         private async void Scenario3BtnFile_Click(object sender, RoutedEventArgs e)
00126         {
00127             try
00128             {
00129                 // get load settings
00130                 var loadSettings = new Windows.Data.Xml.Dom.XmlLoadSettings();
00131                 if (true == scenario3RB1.IsChecked)
00132                 {
00133                     loadSettings.ProhibitDtd = true;        // DTD is prohibited
00134                     loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
00135                 }
00136                 else if (true == scenario3RB2.IsChecked)
00137                 {
00138                     loadSettings.ProhibitDtd = false;       // DTD is not prohibited
00139                     loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
00140                 }
00141                 else if (true == scenario3RB3.IsChecked)
00142                 {
00143                     loadSettings.ProhibitDtd = false;       // DTD is not prohibited
00144                     loadSettings.ResolveExternals = true;   // Enable the resolve to external definitions such as external DTD
00145                 }
00146
00147                 var folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("loadExternaldtd");
00148                 var file = await folder.GetFileAsync("xmlWithExternaldtd.xml");
00149
00150                 var doc = await Windows.Data.Xml.Dom.XmlDocument.LoadFromFileAsync(file, loadSettings);
00151
00152                 Scenario.RichEditBoxSetMsg(scenario3Result, doc.GetXml(), true);
00153             }
00154             catch (Exception)
00155             {
00156                 // After loadSettings.ProhibitDtd is set to true, the exception is expected as the sample XML contains DTD
00157                 Scenario.RichEditBoxSetError(scenario3Result, "Error: DTD is prohibited");
00158             }
00159         }
00160         async void LaunchUri(object sender, RoutedEventArgs e)
00161         {
00162             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00163         }
00164     }
00165 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2 Member List

This is the complete list of members for Scenario2, including all inherited members.
AllItems | Scenario2 |
AutoSuggestBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) | Scenario2 | [inline, private]
AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) | Scenario2 | [inline, private]
BackButton_Click(object sender, RoutedEventArgs e) | Scenario2 | [inline, private]
FlaggedItems | Scenario2 |
ListView_ItemClicked(object sender, ItemClickEventArgs e) | Scenario2 | [inline, private]
NewItems | Scenario2 |
Scenario2() | Scenario2 | [inline]
ShowItem(SampleDataModel model) | Scenario2 | [inline, private]
Suggestions | Scenario2 |
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6_NavToStream::StreamUriWinRTResolver Member List

This is the complete list of members for Scenario6_NavToStream::StreamUriWinRTResolver, including all inherited members.
GetContentAsync(Uri uri) | Scenario6_NavToStream::StreamUriWinRTResolver | [inline, private]
UriToStreamAsync(Uri uri) | Scenario6_NavToStream::StreamUriWinRTResolver | [inline]
Generated on Fri Nov 15 2024 22:23:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Common/DirectXHelper.h Source File

  • HolographicVoiceInput
  • cpp
  • Common

DirectXHelper.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 #include <ppltasks.h>    // For create_task
00014
00015 namespace DX
00016 {
00017     inline void ThrowIfFailed(HRESULT hr)
00018     {
00019         if (FAILED(hr))
00020         {
00021             // Set a breakpoint on this line to catch Win32 API errors.
00022             throw Platform::Exception::CreateException(hr);
00023         }
00024     }
00025
00026     // Function that reads from a binary file asynchronously.
00027     inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename)
00028     {
00029         using namespace Windows::Storage;
00030         using namespace Concurrency;
00031
00032         return create_task(PathIO::ReadBufferAsync(Platform::StringReference(filename.c_str()))).then(
00033             [] (Streams::IBuffer^ fileBuffer) -> std::vector<byte>
00034             {
00035                 std::vector<byte> returnBuffer;
00036                 returnBuffer.resize(fileBuffer->Length);
00037                 Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), returnBuffer.size()));
00038                 return returnBuffer;
00039             });
00040     }
00041
00042     // Converts a length in device-independent pixels (DIPs) to a length in physical pixels.
00043     inline float ConvertDipsToPixels(float dips, float dpi)
00044     {
00045         constexpr float dipsPerInch = 96.0f;
00046         return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00047     }
00048
00049 #if defined(_DEBUG)
00050     // Check for SDK Layer support.
00051     inline bool SdkLayersAvailable()
00052     {
00053         HRESULT hr = D3D11CreateDevice(
00054             nullptr,
00055             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00056             0,
00057             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00058             nullptr,                    // Any feature level will do.
00059             0,
00060             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00061             nullptr,                    // No need to keep the D3D device reference.
00062             nullptr,                    // No need to know the feature level.
00063             nullptr                     // No need to keep the D3D device context reference.
00064             );
00065
00066         return SUCCEEDED(hr);
00067     }
00068 #endif
00069 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisplayOrientation/cpp/pch.cpp Source File

  • DisplayOrientation
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/Scenario10.xaml.h Source File

  • SimpleInk
  • cpp

Scenario10.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario10.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario10 sealed
00024     {
00025     public:
00026         Scenario10();
00027
00028     private:
00029         Concurrency::task<void> ColorizeCustomButtonAsync(Windows::UI::Color newColor);
00030         void inkToolbar_InkDrawingAttributesChanged(Windows::UI::Xaml::Controls::InkToolbar^ sender, Platform::Object^ args);
00031         void inkToolbar_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032         void OnSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00033     };
00034 }
Generated on Fri Nov 15 2024 22:17:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cs/scenario5.xaml.cs Source File

  • ApplicationResources
  • cs

scenario5.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using SDKTemplate;
00015 using System;
00016 using Windows.ApplicationModel.Resources;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     public sealed partial class Scenario5 : Page
00024     {
00025         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00026         // as NotifyUser()
00027         MainPage rootPage = MainPage.Current;
00028
00029         public Scenario5()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         /// <summary>
00035         /// Invoked when this page is about to be displayed in a Frame.
00036         /// </summary>
00037         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00038         /// property is typically used to configure the page.</param>
00039         protected override void OnNavigatedTo(NavigationEventArgs e)
00040         {
00041             this.Scenario5TextBlock.Text = "";
00042         }
00043
00044         /// <summary>
00045         /// This is the click handler for the 'Scenario5Button_Show' button.  You would replace this with your own handler
00046         /// if you have a button or buttons on this page.
00047         /// </summary>
00048         /// <param name="sender"></param>
00049         /// <param name="e"></param>
00050         private void Scenario5Button_Show_Click(object sender, RoutedEventArgs e)
00051         {
00052             Button b = sender as Button;
00053             if (b != null)
00054             {
00055                 var resourceLoader = ResourceLoader.GetForCurrentView("Errors");
00056                 this.Scenario5TextBlock.Text = resourceLoader.GetString("InvalidOperation");
00057             }
00058         }
00059
00060     }
00061 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cs/Tasks/LocationBackgroundTask.cs Source File

  • Geolocation
  • cs
  • Tasks

LocationBackgroundTask.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Collections.Generic;
00013 using System.Threading;
00014 using Windows.ApplicationModel.Background;
00015 using Windows.Storage;
00016 using Windows.Devices.Geolocation;
00017
00018 namespace BackgroundTask
00019 {
00020     public sealed class LocationBackgroundTask : IBackgroundTask
00021     {
00022         private CancellationTokenSource _cts = null;
00023
00024         // LocalSettings persistent data.
00025         IDictionary<string, object> _values = ApplicationData.Current.LocalSettings.Values;
00026
00027         async void IBackgroundTask.Run(IBackgroundTaskInstance taskInstance)
00028         {
00029             BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
00030
00031             try
00032             {
00033                 // Associate a cancellation handler with the background task.
00034                 taskInstance.Canceled += OnCanceled;
00035
00036                 // Get cancellation token
00037                 _cts = new CancellationTokenSource();
00038                 CancellationToken token = _cts.Token;
00039
00040                 // Create geolocator object
00041                 Geolocator geolocator = new Geolocator();
00042
00043                 // Make the request for the current position
00044                 Geoposition pos = await geolocator.GetGeopositionAsync().AsTask(token);
00045
00046                 WriteStatusToAppData($"Time: {DateTime.Now:G}");
00047                 WriteGeolocToAppData(pos);
00048             }
00049             catch (UnauthorizedAccessException)
00050             {
00051                 WriteStatusToAppData("Disabled");
00052                 WipeGeolocDataFromAppData();
00053             }
00054             catch (Exception ex)
00055             {
00056                 WriteStatusToAppData(ex.ToString());
00057                 WipeGeolocDataFromAppData();
00058             }
00059             finally
00060             {
00061                 _cts = null;
00062                 deferral.Complete();
00063             }
00064         }
00065
00066         private void WriteGeolocToAppData(Geoposition pos)
00067         {
00068             _values["Latitude"] = pos.Coordinate.Point.Position.Latitude.ToString();
00069             _values["Longitude"] = pos.Coordinate.Point.Position.Longitude.ToString();
00070             _values["Accuracy"] = pos.Coordinate.Accuracy.ToString();
00071         }
00072
00073         private void WipeGeolocDataFromAppData()
00074         {
00075             _values.Remove("Latitude");
00076             _values.Remove("Longitude");
00077             _values.Remove("Accuracy");
00078         }
00079
00080         private void WriteStatusToAppData(string status)
00081         {
00082             _values["Status"] = status;
00083         }
00084
00085         private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
00086         {
00087             if (_cts != null)
00088             {
00089                 _cts.Cancel();
00090                 _cts = null;
00091             }
00092         }
00093     }
00094 }
Generated on Fri Nov 15 2024 22:19:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_ChooseControl Member List

This is the complete list of members for Scenario3_ChooseControl, including all inherited members.
Scenario3_ChooseControl() Scenario3_ChooseControl [inline]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_RelativePositioning Member List

This is the complete list of members for Scenario5_RelativePositioning, including all inherited members.
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario5_RelativePositioning |
OnWindowClosed(Windows::UI::WindowManagement::AppWindow const &sender, IInspectable const &) | Scenario5_RelativePositioning | [private]
Scenario5_RelativePositioning() | Scenario5_RelativePositioning |
ShowWindowBtn_Click(IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario5_RelativePositioning |
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cs/VoiceCommandService/AdventureWorksVoiceCommandService.cs Source File

  • CortanaVoiceCommand
  • cs
  • VoiceCommandService

AdventureWorksVoiceCommandService.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Globalization;
00015 using System.Linq;
00016 using System.Text;
00017 using System.Threading.Tasks;
00018 using Windows.ApplicationModel;
00019 using Windows.ApplicationModel.AppService;
00020 using Windows.ApplicationModel.Background;
00021 using Windows.ApplicationModel.Resources.Core;
00022 using Windows.ApplicationModel.VoiceCommands;
00023 using Windows.Storage;
00024
00025 namespace AdventureWorks.VoiceCommands
00026 {
00027     /// <summary>
00028     /// The VoiceCommandService implements the entrypoint for all headless voice commands
00029     /// invoked via Cortana. The individual commands supported are described in the
00030     /// AdventureworksCommands.xml VCD file in the AdventureWorks project. The service
00031     /// entrypoint is defined in the Package Manifest (See section uap:Extension in
00032     /// AdventureWorks:Package.appxmanifest)
00033     /// </summary>
00034     public sealed class AdventureWorksVoiceCommandService : IBackgroundTask
00035     {
00036         /// <summary>
00037         /// the service connection is maintained for the lifetime of a cortana session, once a voice command
00038         /// has been triggered via Cortana.
00039         /// </summary>
00040         VoiceCommandServiceConnection voiceServiceConnection;
00041
00042         /// <summary>
00043         /// Lifetime of the background service is controlled via the BackgroundTaskDeferral object, including
00044         /// registering for cancellation events, signalling end of execution, etc. Cortana may terminate the
00045         /// background service task if it loses focus, or the background task takes too long to provide.
00046         ///
00047         /// Background tasks can run for a maximum of 30 seconds.
00048         /// </summary>
00049         BackgroundTaskDeferral serviceDeferral;
00050
00051         /// <summary>
00052         /// ResourceMap containing localized strings for display in Cortana.
00053         /// </summary>
00054         ResourceMap cortanaResourceMap;
00055
00056         /// <summary>
00057         /// The context for localized strings.
00058         /// </summary>
00059         ResourceContext cortanaContext;
00060
00061         /// <summary>
00062         /// Get globalization-aware date formats.
00063         /// </summary>
00064         DateTimeFormatInfo dateFormatInfo;
00065
00066         /// <summary>
00067         /// Background task entrypoint. Voice Commands using the <VoiceCommandService Target="...">
00068         /// tag will invoke this when they are recognized by Cortana, passing along details of the
00069         /// invocation.
00070         ///
00071         /// Background tasks must respond to activation by Cortana within 0.5 seconds, and must
00072         /// report progress to Cortana every 5 seconds (unless Cortana is waiting for user
00073         /// input). There is no execution time limit on the background task managed by Cortana,
00074         /// but developers should use plmdebug (https://msdn.microsoft.com/en-us/library/windows/hardware/jj680085%28v=vs.85%29.aspx)
00075         /// on the Cortana app package in order to prevent Cortana timing out the task during
00076         /// debugging.
00077         ///
00078         /// Cortana dismisses its UI if it loses focus. This will cause it to terminate the background
00079         /// task, even if the background task is being debugged. Use of Remote Debugging is recommended
00080         /// in order to debug background task behaviors. In order to debug background tasks, open the
00081         /// project properties for the app package (not the background task project), and enable
00082         /// Debug -> "Do not launch, but debug my code when it starts". Alternatively, add a long
00083         /// initial progress screen, and attach to the background task process while it executes.
00084         /// </summary>
00085         /// <param name="taskInstance">Connection to the hosting background service process.</param>
00086         public async void Run(IBackgroundTaskInstance taskInstance)
00087         {
00088             serviceDeferral = taskInstance.GetDeferral();
00089
00090             // Register to receive an event if Cortana dismisses the background task. This will
00091             // occur if the task takes too long to respond, or if Cortana's UI is dismissed.
00092             // Any pending operations should be cancelled or waited on to clean up where possible.
00093             taskInstance.Canceled += OnTaskCanceled;
00094
00095             var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
00096
00097             // Load localized resources for strings sent to Cortana to be displayed to the user.
00098             cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");
00099
00100             // Select the system language, which is what Cortana should be running as.
00101             cortanaContext = ResourceContext.GetForViewIndependentUse();
00102
00103             // Get the currently used system date format
00104             dateFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat;
00105
00106             // This should match the uap:AppService and VoiceCommandService references from the
00107             // package manifest and VCD files, respectively. Make sure we've been launched by
00108             // a Cortana Voice Command.
00109             if (triggerDetails != null && triggerDetails.Name == "AdventureWorksVoiceCommandService")
00110             {
00111                 try
00112                 {
00113                     voiceServiceConnection =
00114                         VoiceCommandServiceConnection.FromAppServiceTriggerDetails(
00115                             triggerDetails);
00116
00117                     voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;
00118
00119                     // GetVoiceCommandAsync establishes initial connection to Cortana, and must be called prior to any
00120                     // messages sent to Cortana. Attempting to use ReportSuccessAsync, ReportProgressAsync, etc
00121                     // prior to calling this will produce undefined behavior.
00122                     VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();
00123
00124                     // Depending on the operation (defined in AdventureWorks:AdventureWorksCommands.xml)
00125                     // perform the appropriate command.
00126                     switch (voiceCommand.CommandName)
00127                     {
00128                         case "whenIsTripToDestination":
00129                             var destination = voiceCommand.Properties["destination"][0];
00130                             await SendCompletionMessageForDestination(destination);
00131                             break;
00132                         case "cancelTripToDestination":
00133                             var cancelDestination = voiceCommand.Properties["destination"][0];
00134                             await SendCompletionMessageForCancellation(cancelDestination);
00135                             break;
00136                         default:
00137                             // As with app activation VCDs, we need to handle the possibility that
00138                             // an app update may remove a voice command that is still registered.
00139                             // This can happen if the user hasn't run an app since an update.
00140                             LaunchAppInForeground();
00141                             break;
00142                     }
00143                 }
00144                 catch (Exception ex)
00145                 {
00146                     System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
00147                 }
00148             }
00149         }
00150
00151         /// <summary>
00152         /// Handle the Trip Cancellation task. This task demonstrates how to prompt a user
00153         /// for confirmation of an operation, show users a progress screen while performing
00154         /// a long-running task, and showing a completion screen.
00155         /// </summary>
00156         /// <param name="destination">The name of a destination, expected to match the phrase list.</param>
00157         /// <returns></returns>
00158         private async Task SendCompletionMessageForCancellation(string destination)
00159         {
00160             // Begin loading data to search for the target store. If this operation is going to take a long time,
00161             // for instance, requiring a response from a remote web service, consider inserting a progress screen
00162             // here, in order to prevent Cortana from timing out.
00163             string progressScreenString = string.Format(
00164                 cortanaResourceMap.GetValue("ProgressLookingForTripToDest", cortanaContext).ValueAsString,
00165                 destination);
00166             await ShowProgressScreen(progressScreenString);
00167
00168             Model.TripStore store = new Model.TripStore();
00169             await store.LoadTrips();
00170
00171             // We might have multiple trips to the destination. For now, we just pick the first.
00172             IEnumerable<Model.Trip> trips = store.Trips.Where(p => p.Destination == destination);
00173             Model.Trip trip = null;
00174             if (trips.Count() > 1)
00175             {
00176                 // If there is more than one trip, provide a disambiguation screen rather than just picking one
00177                 // however, more advanced logic here might be ideal (ie, if there's a significant number of items,
00178                 // you may want to just fall back to a link to your app where you can provide a deeper search experience.
00179                 string disambiguationDestinationString = string.Format(
00180                     cortanaResourceMap.GetValue("DisambiguationWhichTripToDest", cortanaContext).ValueAsString,
00181                     destination);
00182                 string disambiguationRepeatString = cortanaResourceMap.GetValue("DisambiguationRepeat", cortanaContext).ValueAsString;
00183                 trip = await DisambiguateTrips(trips, disambiguationDestinationString, disambiguationRepeatString);
00184             }
00185             else
00186             {
00187                 // One or no trips exist with that destination, so retrieve it, or return null.
00188                 trip = trips.FirstOrDefault();
00189             }
00190
00191             var userPrompt = new VoiceCommandUserMessage();
00192
00193             VoiceCommandResponse response;
00194             if (trip == null)
00195             {
00196                 var userMessage = new VoiceCommandUserMessage();
00197                 // In this scenario, perhaps someone has modified data on your service outside of this
00198                 // apps control. If you're accessing a remote service, having a background task that
00199                 // periodically refreshes the phrase list so it's likely to be in sync is ideal.
00200                 // This is unlikely to occur for this sample app, however.
00201                 string noSuchTripToDestination = string.Format(
00202                     cortanaResourceMap.GetValue("NoSuchTripToDestination", cortanaContext).ValueAsString,
00203                     destination);
00204                 userMessage.DisplayMessage = userMessage.SpokenMessage = noSuchTripToDestination;
00205
00206                 response = VoiceCommandResponse.CreateResponse(userMessage);
00207                 await voiceServiceConnection.ReportSuccessAsync(response);
00208             }
00209             else
00210             {
00211                 // Prompt the user for confirmation that we've selected the correct trip to cancel.
00212                 string cancelTripToDestination = string.Format(
00213                     cortanaResourceMap.GetValue("CancelTripToDestination", cortanaContext).ValueAsString,
00214                     destination);
00215                 userPrompt.DisplayMessage = userPrompt.SpokenMessage = cancelTripToDestination;
00216                 var userReprompt = new VoiceCommandUserMessage();
00217                 string confirmCancelTripToDestination = string.Format(
00218                     cortanaResourceMap.GetValue("ConfirmCancelTripToDestination", cortanaContext).ValueAsString,
00219                     destination);
00220                 userReprompt.DisplayMessage = userReprompt.SpokenMessage = confirmCancelTripToDestination;
00221
00222                 response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, userReprompt);
00223
00224                 var voiceCommandConfirmation = await voiceServiceConnection.RequestConfirmationAsync(response);
00225
00226                 // If RequestConfirmationAsync returns null, Cortana's UI has likely been dismissed.
00227                 if (voiceCommandConfirmation != null)
00228                 {
00229                     if (voiceCommandConfirmation.Confirmed == true)
00230                     {
00231                         string cancellingTripToDestination = string.Format(
00232                        cortanaResourceMap.GetValue("CancellingTripToDestination", cortanaContext).ValueAsString,
00233                        destination);
00234                         await ShowProgressScreen(cancellingTripToDestination);
00235
00236                         // Perform the operation to remote the trip from the app's data.
00237                         // Since the background task runs within the app package of the installed app,
00238                         // we can access local files belonging to the app without issue.
00239                         await store.DeleteTrip(trip);
00240
00241                         // Provide a completion message to the user.
00242                         var userMessage = new VoiceCommandUserMessage();
00243                         string cancelledTripToDestination = string.Format(
00244                             cortanaResourceMap.GetValue("CancelledTripToDestination", cortanaContext).ValueAsString,
00245                             destination);
00246                         userMessage.DisplayMessage = userMessage.SpokenMessage = cancelledTripToDestination;
00247                         response = VoiceCommandResponse.CreateResponse(userMessage);
00248                         await voiceServiceConnection.ReportSuccessAsync(response);
00249                     }
00250                     else
00251                     {
00252                         // Confirm no action for the user.
00253                         var userMessage = new VoiceCommandUserMessage();
00254                         string keepingTripToDestination = string.Format(
00255                             cortanaResourceMap.GetValue("KeepingTripToDestination", cortanaContext).ValueAsString,
00256                             destination);
00257                         userMessage.DisplayMessage = userMessage.SpokenMessage = keepingTripToDestination;
00258
00259                         response = VoiceCommandResponse.CreateResponse(userMessage);
00260                         await voiceServiceConnection.ReportSuccessAsync(response);
00261                     }
00262                 }
00263             }
00264         }
00265
00266         /// <summary>
00267         /// Show a progress screen. These should be posted at least every 5 seconds for a
00268         /// long-running operation, such as accessing network resources over a mobile
00269         /// carrier network.
00270         /// </summary>
00271         /// <param name="message">The message to display, relating to the task being performed.</param>
00272         /// <returns></returns>
00273         private async Task ShowProgressScreen(string message)
00274         {
00275             var userProgressMessage = new VoiceCommandUserMessage();
00276             userProgressMessage.DisplayMessage = userProgressMessage.SpokenMessage = message;
00277
00278             VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userProgressMessage);
00279             await voiceServiceConnection.ReportProgressAsync(response);
00280         }
00281
00282         /// <summary>
00283         /// Demonstrates providing the user with a choice between multiple items. In this case, if a user
00284         /// has two trips to the same destination with different dates, this will provide a way to differentiate
00285         /// them. Provide a way to choose between the items.
00286         /// </summary>
00287         /// <param name="trips">The set of trips to choose between</param>
00288         /// <param name="disambiguationMessage">The initial disambiguation message</param>
00289         /// <param name="secondDisambiguationMessage">Repeat prompt retry message</param>
00290         /// <returns></returns>
00291         private async Task<Model.Trip> DisambiguateTrips(IEnumerable<Model.Trip> trips, string disambiguationMessage, string secondDisambiguationMessage)
00292         {
00293             // Create the first prompt message.
00294             var userPrompt = new VoiceCommandUserMessage();
00295             userPrompt.DisplayMessage =
00296                 userPrompt.SpokenMessage = disambiguationMessage;
00297
00298             // Create a re-prompt message if the user responds with an out-of-grammar response.
00299             var userReprompt = new VoiceCommandUserMessage();
00300             userReprompt.DisplayMessage =
00301                 userReprompt.SpokenMessage = secondDisambiguationMessage;
00302
00303             // Create items for each item. Ideally, should be limited to a small number of items.
00304             var destinationContentTiles = new List<VoiceCommandContentTile>();
00305             int i = 1;
00306             foreach (Model.Trip trip in trips)
00307             {
00308                 var destinationTile = new VoiceCommandContentTile();
00309
00310                 // To handle UI scaling, Cortana automatically looks up files with FileName.scale-<n>.ext formats based on the requested filename.
00311                 // See the VoiceCommandService\Images folder for an example.
00312                 destinationTile.ContentTileType = VoiceCommandContentTileType.TitleWith68x68IconAndText;
00313                 destinationTile.Image = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///AdventureWorks.VoiceCommands/Images/GreyTile.png"));
00314
00315                 // The AppContext can be any arbitrary object, and will be maintained for the
00316                 // response.
00317                 destinationTile.AppContext = trip;
00318                 string dateFormat = "";
00319                 if (trip.StartDate != null)
00320                 {
00321                     dateFormat = trip.StartDate.Value.ToString(dateFormatInfo.LongDatePattern);
00322                 }
00323                 else
00324                 {
00325                     // The app allows a trip to not have a date, but the choices must be unique
00326                     // so they can be spoken aloud and be distinct, so add a number to identify them.
00327                     dateFormat = string.Format("{0}", i);
00328                 }
00329
00330                 destinationTile.Title = trip.Destination + " " + dateFormat;
00331                 destinationTile.TextLine1 = trip.Description;
00332
00333                 destinationContentTiles.Add(destinationTile);
00334                 i++;
00335             }
00336
00337             // Cortana will handle re-prompting if the user does not provide a valid response.
00338             var response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, userReprompt, destinationContentTiles);
00339
00340             // If cortana is dismissed in this operation, null will be returned.
00341             var voiceCommandDisambiguationResult = await
00342                 voiceServiceConnection.RequestDisambiguationAsync(response);
00343             if (voiceCommandDisambiguationResult != null)
00344             {
00345                 return (Model.Trip)voiceCommandDisambiguationResult.SelectedItem.AppContext;
00346             }
00347
00348             return null;
00349         }
00350
00351         /// <summary>
00352         /// Search for, and show details related to a single trip, if the trip can be
00353         /// found. This demonstrates a simple response flow in Cortana.
00354         /// </summary>
00355         /// <param name="destination">The destination, expected to be in the phrase list.</param>
00356         /// <returns></returns>
00357         private async Task SendCompletionMessageForDestination(string destination)
00358         {
00359             // If this operation is expected to take longer than 0.5 seconds, the task must
00360             // provide a progress response to Cortana prior to starting the operation, and
00361             // provide updates at most every 5 seconds.
00362             string loadingTripToDestination = string.Format(
00363                        cortanaResourceMap.GetValue("LoadingTripToDestination", cortanaContext).ValueAsString,
00364                        destination);
00365             await ShowProgressScreen(loadingTripToDestination);
00366             Model.TripStore store = new Model.TripStore();
00367             await store.LoadTrips();
00368
00369             // Look for the specified trip. The destination *should* be pulled from the grammar we
00370             // provided, and the subsequently updated phrase list, so it should be a 1:1 match, including case.
00371             // However, we might have multiple trips to the destination. For now, we just pick the first.
00372             IEnumerable<Model.Trip> trips = store.Trips.Where(p => p.Destination == destination);
00373
00374             var userMessage = new VoiceCommandUserMessage();
00375             var destinationsContentTiles = new List<VoiceCommandContentTile>();
00376             if (trips.Count() == 0)
00377             {
00378                 // In this scenario, perhaps someone has modified data on your service outside of your
00379                 // control. If you're accessing a remote service, having a background task that
00380                 // periodically refreshes the phrase list so it's likely to be in sync is ideal.
00381                 // This is unlikely to occur for this sample app, however.
00382                 string foundNoTripToDestination = string.Format(
00383                        cortanaResourceMap.GetValue("FoundNoTripToDestination", cortanaContext).ValueAsString,
00384                        destination);
00385                 userMessage.DisplayMessage = foundNoTripToDestination;
00386                 userMessage.SpokenMessage = foundNoTripToDestination;
00387             }
00388             else
00389             {
00390                 // Set a title message for the page.
00391                 string message = "";
00392                 if (trips.Count() > 1)
00393                 {
00394                     message = cortanaResourceMap.GetValue("PluralUpcomingTrips", cortanaContext).ValueAsString;
00395                 }
00396                 else
00397                 {
00398                     message = cortanaResourceMap.GetValue("SingularUpcomingTrip", cortanaContext).ValueAsString;
00399                 }
00400                 userMessage.DisplayMessage = message;
00401                 userMessage.SpokenMessage = message;
00402
00403                 // file in tiles for each destination, to display information about the trips without
00404                 // launching the app.
00405                 foreach (Model.Trip trip in trips)
00406                 {
00407                     int i = 1;
00408
00409                     var destinationTile = new VoiceCommandContentTile();
00410
00411                     // To handle UI scaling, Cortana automatically looks up files with FileName.scale-<n>.ext formats based on the requested filename.
00412                     // See the VoiceCommandService\Images folder for an example.
00413                     destinationTile.ContentTileType = VoiceCommandContentTileType.TitleWith68x68IconAndText;
00414                     destinationTile.Image = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///AdventureWorks.VoiceCommands/Images/GreyTile.png"));
00415
00416                     destinationTile.AppLaunchArgument = trip.Destination;
00417                     destinationTile.Title = trip.Destination;
00418                     if (trip.StartDate != null)
00419                     {
00420                         destinationTile.TextLine1 = trip.StartDate.Value.ToString(dateFormatInfo.LongDatePattern);
00421                     }
00422                     else
00423                     {
00424                         destinationTile.TextLine1 = trip.Destination + " " + i;
00425                     }
00426
00427                     destinationsContentTiles.Add(destinationTile);
00428                     i++;
00429                 }
00430             }
00431
00432             var response = VoiceCommandResponse.CreateResponse(userMessage, destinationsContentTiles);
00433
00434             if (trips.Count() > 0)
00435             {
00436                 response.AppLaunchArgument = destination;
00437             }
00438
00439             await voiceServiceConnection.ReportSuccessAsync(response);
00440         }
00441
00442         /// <summary>
00443         /// Provide a simple response that launches the app. Expected to be used in the
00444         /// case where the voice command could not be recognized (eg, a VCD/code mismatch.)
00445         /// </summary>
00446         private async void LaunchAppInForeground()
00447         {
00448             var userMessage = new VoiceCommandUserMessage();
00449             userMessage.SpokenMessage = cortanaResourceMap.GetValue("LaunchingAdventureWorks", cortanaContext).ValueAsString;
00450
00451             var response = VoiceCommandResponse.CreateResponse(userMessage);
00452
00453             response.AppLaunchArgument = "";
00454
00455             await voiceServiceConnection.RequestAppLaunchAsync(response);
00456         }
00457
00458         /// <summary>
00459         /// Handle the completion of the voice command. Your app may be cancelled
00460         /// for a variety of reasons, such as user cancellation or not providing
00461         /// progress to Cortana in a timely fashion. Clean up any pending long-running
00462         /// operations (eg, network requests).
00463         /// </summary>
00464         /// <param name="sender">The voice connection associated with the command.</param>
00465         /// <param name="args">Contains an Enumeration indicating why the command was terminated.</param>
00466         private void OnVoiceCommandCompleted(VoiceCommandServiceConnection sender, VoiceCommandCompletedEventArgs args)
00467         {
00468             if (this.serviceDeferral != null)
00469             {
00470                 this.serviceDeferral.Complete();
00471             }
00472         }
00473
00474         /// <summary>
00475         /// When the background task is cancelled, clean up/cancel any ongoing long-running operations.
00476         /// This cancellation notice may not be due to Cortana directly. The voice command connection will
00477         /// typically already be destroyed by this point and should not be expected to be active.
00478         /// </summary>
00479         /// <param name="sender">This background task instance</param>
00480         /// <param name="reason">Contains an enumeration with the reason for task cancellation</param>
00481         private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
00482         {
00483             System.Diagnostics.Debug.WriteLine("Task cancelled, clean up");
00484             if (this.serviceDeferral != null)
00485             {
00486                 //Complete the service deferral
00487                 this.serviceDeferral.Complete();
00488             }
00489         }
00490     }
00491 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: StreamSocket/cpp/Scenario1.xaml.cpp Source File

  • StreamSocket
  • cpp

Scenario1.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1.xaml.cpp
00014 // Implementation of the Scenario1 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario1.xaml.h"
00019
00020 using namespace SDKTemplate;
00021 using namespace SDKTemplate::StreamSocketSample;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Platform::Collections;
00026 using namespace Windows::ApplicationModel::Core;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Networking;
00029 using namespace Windows::Networking::Connectivity;
00030 using namespace Windows::Networking::Sockets;
00031 using namespace Windows::Storage::Streams;
00032 using namespace Windows::UI::Core;
00033 using namespace Windows::UI::Xaml;
00034 using namespace Windows::UI::Xaml::Controls;
00035 using namespace Windows::UI::Xaml::Navigation;
00036
00037 Scenario1::Scenario1()
00038 {
00039     InitializeComponent();
00040     this->localHostItems = ref new Vector<LocalHostItem^>();
00041 }
00042
00043 /// <summary>
00044 /// Invoked when this page is about to be displayed in a Frame.
00045 /// </summary>
00046 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00047 /// property is typically used to configure the page.</param>
00048 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00049 {
00050     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00051     // as NotifyUser()
00052     rootPage = MainPage::Current;
00053     BindToAny->IsChecked = true;
00054     PopulateAdapterList();
00055 }
00056
00057 void Scenario1::BindToAny_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00058 {
00059     AdapterList->IsEnabled = false;
00060 }
00061
00062 void Scenario1::BindToAny_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00063 {
00064     AdapterList->IsEnabled = true;
00065 }
00066
00067 void Scenario1::StartListener_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00068 {
00069     // Overriding the listener here is safe as it will be deleted once all references to it are gone. However,
00070     // in many cases this is a dangerous pattern to override data semi-randomly (each time user clicked the button)
00071     // so we block it here.
00072     if (CoreApplication::Properties->HasKey("listener"))
00073     {
00074         rootPage->NotifyUser(
00075             "This step has already been executed. Please move to the next one.",
00076             NotifyType::ErrorMessage);
00077         return;
00078     }
00079
00080     if (ServiceNameForListener->Text == nullptr)
00081     {
00082         rootPage->NotifyUser("Please provide a service name.", NotifyType::ErrorMessage);
00083         return;
00084     }
00085
00086     LocalHostItem^ selectedLocalHost = nullptr;
00087     if (BindToAddress->IsChecked->Value || BindToAdapter->IsChecked->Value)
00088     {
00089         selectedLocalHost = static_cast<LocalHostItem^>(AdapterList->SelectedItem);
00090         if (selectedLocalHost == nullptr)
00091         {
00092             rootPage->NotifyUser("Please select an address / adapter.", NotifyType::ErrorMessage);
00093             return;
00094         }
00095
00096         // The user selected an address. For demo purposes, we ensure that connect will be using the same address.
00097         CoreApplication::Properties->Insert("serverAddress", selectedLocalHost->LocalHost->CanonicalName);
00098     }
00099     else
00100     {
00101         // Clear up any previous serverAddress or adapter used by the client part of the demo.
00102         CoreApplication::Properties->Insert("serverAddress", nullptr);
00103         CoreApplication::Properties->Insert("adapter", nullptr);
00104     }
00105
00106     StreamSocketListener^ listener = ref new StreamSocketListener();
00107     ListenerContext^ listenerContext = ref new ListenerContext(rootPage, listener);
00108     listener->ConnectionReceived +=
00109         ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>(
00110             listenerContext,
00111             &ListenerContext::OnConnection);
00112
00113     // If necessary, tweak the listener's control options before carrying out the bind operation.
00114     // These options will be automatically applied to the connected StreamSockets resulting from
00115     // incoming connections (i.e., those passed as arguments to the ConnectionReceived event handler).
00116     // Refer to the StreamSocketListenerControl class' MSDN documentation for the full list of control options.
00117     listener->Control->KeepAlive = false;
00118
00119     // Events cannot be hooked up directly to the ScenarioInput1 object, as the object can fall out-of-scope and be
00120     // deleted. This would render any event hooked up to the object ineffective. The ListenerContext guarantees that
00121     // both the listener and object that serves its events have the same lifetime.
00122     CoreApplication::Properties->Insert("listener", listenerContext);
00123
00124     if (BindToAny->IsChecked->Value)
00125     {
00126         // Don't limit traffic to an address or an adapter.
00127         create_task(listener->BindServiceNameAsync(ServiceNameForListener->Text)).then([this] (task<void> previousTask)
00128         {
00129             try
00130             {
00131                 // Try getting an exception.
00132                 previousTask.get();
00133                 rootPage->NotifyUser("Listening", NotifyType::StatusMessage);
00134             }
00135             catch (Exception^ exception)
00136             {
00137                 CoreApplication::Properties->Remove("listener");
00138                 rootPage->NotifyUser(
00139                     "Start listening failed with error: " + exception->Message,
00140                     NotifyType::ErrorMessage);
00141             }
00142         });
00143     }
00144     else if (BindToAddress->IsChecked->Value)
00145     {
00146         // Try to bind to a specific address.
00147         create_task(listener->BindEndpointAsync(selectedLocalHost->LocalHost, ServiceNameForListener->Text)).then(
00148             [this, selectedLocalHost] (task<void> previousTask)
00149         {
00150             try
00151             {
00152                 // Try getting an exception.
00153                 previousTask.get();
00154                 rootPage->NotifyUser(
00155                     "Listening on address " + selectedLocalHost->LocalHost->CanonicalName,
00156                     NotifyType::StatusMessage);
00157             }
00158             catch (Exception^ exception)
00159             {
00160                 CoreApplication::Properties->Remove("listener");
00161                 rootPage->NotifyUser(
00162                     "Start listening failed with error: " + exception->Message,
00163                     NotifyType::ErrorMessage);
00164             }
00165         });
00166     }
00167     else if (BindToAdapter->IsChecked->Value)
00168     {
00169         // Try to limit traffic to the selected adapter.
00170         // This option will be overridden by interfaces with weak-host or forwarding modes enabled.
00171         NetworkAdapter^ selectedAdapter = selectedLocalHost->LocalHost->IPInformation->NetworkAdapter;
00172
00173         // For demo purposes, ensure that we use the same adapter in the client connect scenario.
00174         CoreApplication::Properties->Insert("adapter", selectedAdapter);
00175
00176         create_task(listener->BindServiceNameAsync(
00177             ServiceNameForListener->Text,
00178             SocketProtectionLevel::PlainSocket,
00179             selectedAdapter)).then([this, selectedAdapter] (task<void> previousTask)
00180         {
00181             try
00182             {
00183                 // Try getting an exception.
00184                 previousTask.get();
00185                 rootPage->NotifyUser(
00186                     "Listening on adapter" + selectedAdapter->NetworkAdapterId,
00187                     NotifyType::StatusMessage);
00188             }
00189             catch (Exception^ exception)
00190             {
00191                 CoreApplication::Properties->Remove("listener");
00192                 rootPage->NotifyUser(
00193                     "Start listening failed with error: " + exception->Message,
00194                     NotifyType::ErrorMessage);
00195             }
00196         });
00197     }
00198 }
00199
00200 void Scenario1::PopulateAdapterList()
00201 {
00202     localHostItems->Clear();
00203     AdapterList->ItemsSource = localHostItems;
00204     AdapterList->DisplayMemberPath = "DisplayString";
00205
00206     for (HostName^ localHostInfo : NetworkInformation::GetHostNames())
00207     {
00208         if (localHostInfo->IPInformation != nullptr)
00209         {
00210             LocalHostItem^ adapterItem = ref new LocalHostItem(localHostInfo);
00211             localHostItems->Append(adapterItem);
00212         }
00213     }
00214 }
00215
00216 ListenerContext::ListenerContext(MainPage^ rootPage, StreamSocketListener^ listener)
00217 {
00218     this->rootPage = rootPage;
00219     this->listener = listener;
00220 }
00221
00222 ListenerContext::~ListenerContext()
00223 {
00224     // The listener can be closed in two ways:
00225     //  - explicit: by using delete operator (the listener is closed even if there are outstanding references to it).
00226     //  - implicit: by removing last reference to it (i.e. falling out-of-scope).
00227     // In this case this is the last reference to the listener so both will yield the same result.
00228     delete listener;
00229     listener = nullptr;
00230 }
00231
00232 void ListenerContext::OnConnection(
00233     StreamSocketListener^ listener,
00234     StreamSocketListenerConnectionReceivedEventArgs^ object)
00235 {
00236     DataReader^ reader = ref new DataReader(object->Socket->InputStream);
00237
00238     // Start a receive loop.
00239     ReceiveStringLoop(reader, object->Socket);
00240 }
00241
00242 void ListenerContext::ReceiveStringLoop(DataReader^ reader, StreamSocket^ socket)
00243 {
00244     // Read first 4 bytes (length of the subsequent string).
00245     create_task(reader->LoadAsync(sizeof(UINT32))).then([this, reader, socket] (unsigned int size)
00246     {
00247         if (size < sizeof(UINT32))
00248         {
00249             // The underlying socket was closed before we were able to read the whole data.
00250             cancel_current_task();
00251         }
00252
00253         unsigned int stringLength = reader->ReadUInt32();
00254         return create_task(reader->LoadAsync(stringLength)).then(
00255             [this, reader, stringLength] (unsigned int actualStringLength)
00256         {
00257             if (actualStringLength != stringLength)
00258             {
00259                 // The underlying socket was closed before we were able to read the whole data.
00260                 cancel_current_task();
00261             }
00262
00263             // Display the string on the screen. This thread is invoked on non-UI thread, so we need to marshal the
00264             // call back to the UI thread.
00265             NotifyUserFromAsyncThread(
00266                 "Received data: \"" + reader->ReadString(actualStringLength) + "\"",
00267                 NotifyType::StatusMessage);
00268         });
00269     }).then([this, reader, socket] (task<void> previousTask)
00270     {
00271         try
00272         {
00273             // Try getting all exceptions from the continuation chain above this point.
00274             previousTask.get();
00275
00276             // Everything went ok, so try to receive another string. The receive will continue until the stream is
00277             // broken (i.e. peer closed the socket).
00278             ReceiveStringLoop(reader, socket);
00279         }
00280         catch (Exception^ exception)
00281         {
00282             NotifyUserFromAsyncThread(
00283                 "Read stream failed with error: " + exception->Message,
00284                 NotifyType::ErrorMessage);
00285
00286             // Explicitly close the socket.
00287             delete socket;
00288         }
00289         catch (task_canceled&)
00290         {
00291             // Do not print anything here - this will usually happen because user closed the client socket.
00292
00293             // Explicitly close the socket.
00294             delete socket;
00295         }
00296     });
00297 }
00298
00299 void ListenerContext::NotifyUserFromAsyncThread(String^ message, NotifyType type)
00300 {
00301     rootPage->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, message, type] ()
00302     {
00303         rootPage->NotifyUser(message, type);
00304     }));
00305 }
00306
00307 LocalHostItem::LocalHostItem(HostName^ localHostName)
00308 {
00309     if (localHostName == nullptr)
00310     {
00311         throw ref new InvalidArgumentException("localHostName cannot be null");
00312     }
00313
00314     if (localHostName->IPInformation == nullptr)
00315     {
00316         throw ref new InvalidArgumentException("Adapter information not found");
00317     }
00318
00319     this->localHost = localHostName;
00320     this->displayString = "Address: " + localHostName->DisplayName +
00321         " Adapter: " + localHostName->IPInformation->NetworkAdapter->NetworkAdapterId;
00322 }
Generated on Fri Nov 15 2024 22:17:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cpp/Server/OvenServer.h Source File

  • ProxyStubsForWinRTComponents
  • cpp
  • Server

OvenServer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008
00009 namespace Microsoft { namespace SDKSamples { namespace Kitchen {
00010
00011     ref class Oven;
00012
00013     // Explicitly declare IIDs to make it easier to author the proxy stub interface registration
00014     [uuid(332FD2F1-1C69-4C91-949E-4BB67A85BDC5)]
00015     public interface class IAppliance
00016     {
00017         property double Volume
00018         {
00019             double get();
00020         }
00021     };
00022
00023     // Explicitly declare IIDs to make it easier to author the proxy stub interface registration
00024     [uuid(6A112353-4F87-4460-A908-2944E92686F3)]
00025     public interface class IOven : public IAppliance
00026     {
00027         void ConfigurePreheatTemperature(OvenTemperature temperature);
00028         void BakeBread(Platform::String^ flavor);
00029
00030         event Windows::Foundation::TypedEventHandler<Oven^, Bread^>^ BreadBaked;
00031     };
00032
00033     public ref class Oven sealed : public [Windows::Foundation::Metadata::Default] IOven
00034     {
00035     public:
00036         [Windows::Foundation::Metadata::Overload("CreateOven")]
00037         Oven(Dimensions dimensions)
00038         {
00039             _dims = dimensions;
00040         }
00041
00042         Oven()
00043         {
00044             _dims.Height = 1.0;
00045             _dims.Width = 1.0;
00046             _dims.Depth = 1.0;
00047         }
00048
00049     public:
00050
00051         virtual property double Volume
00052         {
00053             // IAppliance::get_Volume
00054             virtual double get();
00055         }
00056
00057         // IOven::ConfigurePreheatTemperature
00058         virtual void ConfigurePreheatTemperature(OvenTemperature temperature);
00059
00060         // IOven::BakeBread
00061         virtual void BakeBread(Platform::String^ flavor);
00062
00063         virtual event Windows::Foundation::TypedEventHandler<Oven^, Bread^>^ BreadBaked;
00064
00065     private:
00066         Dimensions _dims;
00067         OvenTemperature _temperature;
00068     };
00069
00070 } /* Kitchen */ } /* SDKSamples */ } /* Microsoft */
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Write Member List

This is the complete list of members for Write, including all inherited members.
Address | UpdateBinary |
ApduCommand(byte cla, byte ins, byte p1, byte p2, byte[] commandData, byte?le) | ApduCommand | [inline]
ApduResponseType | ApduCommand |
CLA | ApduCommand |
CommandData | ApduCommand |
GetBuffer() | ApduCommand | [inline]
INS | ApduCommand |
Le | ApduCommand |
P1 | ApduCommand |
P2 | ApduCommand |
ToString() | ApduCommand | [inline]
UpdateBinary(ushort address, byte[] dataToWrite) | UpdateBinary | [inline]
Write(ushort blockNumber, byte[] dataToWrite) | Write | [inline]
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Content/FaceTrackerProcessor.cpp Source File

  • HolographicFaceTracking
  • cpp
  • Content

FaceTrackerProcessor.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "FaceTrackerProcessor.h"
00014 #include "VideoFrameProcessor.h"
00015
00016 using namespace HolographicFaceTracker;
00017
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::Foundation::Numerics;
00020 using namespace Windows::Media;
00021 using namespace Windows::Media::Capture;
00022 using namespace Windows::Media::Capture::Frames;
00023 using namespace Windows::Media::FaceAnalysis;
00024
00025 using namespace Concurrency;
00026
00027 task<std::shared_ptr<FaceTrackerProcessor>> FaceTrackerProcessor::CreateAsync(std::shared_ptr<VideoFrameProcessor> processor)
00028 {
00029     return create_task(FaceTracker::CreateAsync())
00030         .then([=](FaceTracker^ tracker)
00031     {
00032         tracker->MinDetectableFaceSize = Windows::Graphics::Imaging::BitmapSize{ 64u, 64u };
00033         tracker->MaxDetectableFaceSize = Windows::Graphics::Imaging::BitmapSize{ 512u, 512u };
00034
00035         return std::make_shared<FaceTrackerProcessor>(std::move(tracker), std::move(processor));
00036     });
00037 }
00038
00039 FaceTrackerProcessor::FaceTrackerProcessor(Windows::Media::FaceAnalysis::FaceTracker^ tracker, std::shared_ptr<VideoFrameProcessor> processor)
00040     : m_faceTracker(std::move(tracker))
00041     , m_videoProcessor(std::move(processor))
00042 {
00043     if (m_videoProcessor)
00044     {
00045         // Create explicit background thread for FaceTrackingProcessing, as it is an expensive operation.
00046         m_workerThread = std::thread([this]
00047         {
00048             m_isRunning = true;
00049
00050             while (m_isRunning)
00051             {
00052                 ProcessFrame();
00053             }
00054         });
00055     }
00056 }
00057
00058 FaceTrackerProcessor::~FaceTrackerProcessor(void)
00059 {
00060     m_isRunning = false;
00061 }
00062
00063 bool HolographicFaceTracker::FaceTrackerProcessor::IsTrackingFaces(void) const
00064 {
00065     auto lock = std::shared_lock<std::shared_mutex>(m_propertiesLock);
00066     return !m_latestFaces.empty();
00067 }
00068
00069 std::vector<Windows::Graphics::Imaging::BitmapBounds> FaceTrackerProcessor::GetLatestFaces(void) const
00070 {
00071     auto lock = std::shared_lock<std::shared_mutex>(m_propertiesLock);
00072     return m_latestFaces;
00073 }
00074
00075 void FaceTrackerProcessor::ProcessFrame(void)
00076 {
00077     if (MediaFrameReference^ frame = m_videoProcessor->GetLatestFrame())
00078     {
00079         if (VideoMediaFrame^ videoMediaFrame = frame->VideoMediaFrame)
00080         {
00081             // Validate that the incoming frame format is compatible with the FaceTracker
00082             if (videoMediaFrame->SoftwareBitmap && FaceTracker::IsBitmapPixelFormatSupported(videoMediaFrame->SoftwareBitmap->BitmapPixelFormat))
00083             {
00084                 // Ask the FaceTracker to process this frame asynchronously
00085                 task<IVector<DetectedFace^>^> processFrameTask = create_task(m_faceTracker->ProcessNextFrameAsync(videoMediaFrame->GetVideoFrame()));
00086
00087                 try
00088                 {
00089                     IVector<DetectedFace^>^ faces = processFrameTask.get();
00090
00091                     std::lock_guard<std::shared_mutex> lock(m_propertiesLock);
00092
00093                     if (faces->Size == 0u)
00094                     {
00095                         ++m_numFramesWithoutFaces;
00096
00097                         // The FaceTracker might lose track of faces for a few frames, for example,
00098                         // if the person momentarily turns their head away from the camera. To smooth out
00099                         // the tracking, we allow 30 video frames (~1 second) without faces before
00100                         // we say that we're no longer tracking any faces.
00101                         if (m_numFramesWithoutFaces > 30u && !m_latestFaces.empty())
00102                         {
00103                             m_latestFaces.resize(0u);
00104                         }
00105                     }
00106                     else
00107                     {
00108                         m_numFramesWithoutFaces = 0u;
00109                         m_latestFaces.resize(faces->Size);
00110
00111                         for (uint32_t i = 0u; i < faces->Size; ++i)
00112                         {
00113                             m_latestFaces[i] = faces->GetAt(i)->FaceBox;
00114                         }
00115                     }
00116                 }
00117                 catch(task_canceled const&)
00118                 {
00119                     // The task might be cancelled if the FaceAnalysis failed.
00120                     return;
00121                 }
00122             }
00123         }
00124     }
00125 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Capabilities/cppwinrt/pch.cpp Source File

  • Capabilities
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFontImplementation/pch.h Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFontImplementation

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <collection.h>
00015 #include <ppltasks.h>
00016
00017 #include <d3d11_3.h>
00018 #include <d2d1_3.h>
00019 #include <dwrite_3.h>
00020 #include <math.h>
00021
00022 #include <windows.ui.xaml.media.dxinterop.h>
00023
00024 #include <string>
00025 #include <set>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CStreamSink Member List

This is the complete list of members for CStreamSink, including all inherited members.
_Connected | CStreamSink | [private]
_cRef | CStreamSink | [private]
_critSec | CStreamSink | [private]
_dwIdentifier | CStreamSink | [private]
_fFirstSampleAfterConnect | CStreamSink | [private]
_fGetStartTimeFromSample | CStreamSink | [private]
_fIsVideo | CStreamSink | [private]
_fWaitingForFirstSample | CStreamSink | [private]
_guiCurrentSubtype | CStreamSink | [private]
_IsShutdown | CStreamSink | [private]
_networkSender | CStreamSink | [private]
_pParent | CStreamSink | [private]
_SampleQueue | CStreamSink | [private]
_spByteStream | CStreamSink | [private]
_spCurrentType | CStreamSink | [private]
_spEventQueue | CStreamSink | [private]
_spFirstVideoSample | CStreamSink | [private]
_spFTM | CStreamSink | [private]
_spSink | CStreamSink | [private]
_StartTime | CStreamSink | [private]
_state | CStreamSink | [private]
_WorkQueueCB | CStreamSink | [private]
_WorkQueueId | CStreamSink | [private]
AppendParameterSets(IMFSample *pCopyFrom, Network::IBufferPacket *pPacket) | CStreamSink | [private]
BeginGetEvent(IMFAsyncCallback *pCallback, IUnknown *punkState) | CStreamSink |
CheckShutdown() const | CStreamSink | [inline]
CStreamSink(DWORD dwIdentifier) | CStreamSink |
DispatchProcessSample(CAsyncOperation *pOp) | CStreamSink | [private]
DropSamplesFromQueue() | CStreamSink | [private]
EndGetEvent(IMFAsyncResult *pResult, IMFMediaEvent **ppEvent) | CStreamSink |
FillStreamDescription(IMFMediaType *pMediaType, StspStreamDescription *pStreamDescription) | CStreamSink |
Flush() | CStreamSink |
GetCurrentMediaType(IMFMediaType **ppMediaType) | CStreamSink |
GetEvent(DWORD dwFlags, IMFMediaEvent **ppEvent) | CStreamSink |
GetIdentifier(DWORD *pdwIdentifier) | CStreamSink |
GetMajorType(GUID *pguidMajorType) | CStreamSink |
GetMediaSink(IMFMediaSink **ppMediaSink) | CStreamSink |
GetMediaTypeByIndex(DWORD dwIndex, IMFMediaType **ppType) | CStreamSink |
GetMediaTypeCount(DWORD *pdwTypeCount) | CStreamSink |
GetMediaTypeHandler(IMFMediaTypeHandler **ppHandler) | CStreamSink |
HandleError(HRESULT hr) | CStreamSink | [private]
IFACEMETHOD_(ULONG, AddRef)() | CStreamSink |
IFACEMETHOD_(ULONG, Release)() | CStreamSink |
Initialize(CMediaSink *pParent, Network::INetworkChannel^sender) | CStreamSink |
IsMediaTypeSupported(IMFMediaType *pMediaType, IMFMediaType **ppMediaType) | CStreamSink |
IsVideo() const | CStreamSink | [inline]
OnDispatchWorkItem(IMFAsyncResult *pAsyncResult) | CStreamSink | [private]
Op_Count enum value | CStreamSink |
OpPause enum value | CStreamSink |
OpPlaceMarker enum value | CStreamSink |
OpProcessSample enum value | CStreamSink |
OpRestart enum value | CStreamSink |
OpSetMediaType enum value | CStreamSink |
OpStart enum value | CStreamSink |
OpStop enum value | CStreamSink |
Pause() | CStreamSink |
PlaceMarker(MFSTREAMSINK_MARKER_TYPE eMarkerType, PROPVARIANT const *pvarMarkerValue, PROPVARIANT const *pvarContextValue) | CStreamSink |
PrepareFormatChange(IMFMediaType *pMediaType) | CStreamSink | [private]
PrepareSample(IMFSample *pSample, bool fForce) | CStreamSink | [private]
ProcessFormatChange(IMFMediaType *pMediaType) | CStreamSink | [private]
ProcessSample(IMFSample *pSample) | CStreamSink |
ProcessSamplesFromQueue(bool fFlush) | CStreamSink | [private]
QueryInterface(REFIID riid, void **ppv) | CStreamSink |
QueueAsyncOperation(StreamOperation op) | CStreamSink | [private]
QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, PROPVARIANT const *pvValue) | CStreamSink |
Restart() | CStreamSink |
SendSampleFromQueue() | CStreamSink | [private]
SetConnected(bool fConnected, LONGLONG llCurrentTime) | CStreamSink |
SetCurrentMediaType(IMFMediaType *pMediaType) | CStreamSink |
Shutdown() | CStreamSink |
Start(MFTIME start) | CStreamSink |
State enum name | CStreamSink |
State_Count enum value | CStreamSink |
State_Paused enum value | CStreamSink |
State_Ready enum value | CStreamSink |
State_Started enum value | CStreamSink |
State_Stopped enum value | CStreamSink |
State_TypeNotSet enum value | CStreamSink |
Stop() | CStreamSink |
StreamOperation enum name | CStreamSink |
ValidateOperation(StreamOperation op) | CStreamSink | [private]
ValidStateMatrix | CStreamSink | [static]
~CStreamSink() | CStreamSink | [virtual]
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Shape Member List

This is the complete list of members for Shape, including all inherited members.
brush | Shape
shape | Shape
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cpp/pch.h Source File

  • Calendar
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraProfile/cpp/Scenario2_ConcurrentProfile.xaml.cpp Source File

  • CameraProfile
  • cpp

Scenario2_ConcurrentProfile.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_ConcurrentProfile.xaml.h"
00014 #include <sstream>
00015
00016 using namespace Concurrency;
00017 using namespace Platform;
00018 using namespace SDKTemplate;
00019 using namespace Windows::Devices::Enumeration;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Media::Capture;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Controls::Primitives;
00026 using namespace Windows::UI::Core;
00027 using namespace Windows::UI::Xaml::Data;
00028 using namespace Windows::UI::Xaml::Input;
00029 using namespace Windows::UI::Xaml::Media;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 /// <summary>
00033 /// Initializes a new instance of the <see cref="Scenario2_ConcurrentProfile"/> class.
00034 /// </summary>
00035 Scenario2_ConcurrentProfile::Scenario2_ConcurrentProfile() : _rootPage(MainPage::Current)
00036 {
00037     InitializeComponent();
00038 }
00039
00040 /// <summary>
00041 /// Override default OnNavigateTo to initialize
00042 /// the rootPage object for Status message updates
00043 /// </summary>
00044 /// <param name="e">Contains state information and event data associated with the event</param>
00045 void Scenario2_ConcurrentProfile::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00046 {
00047     _rootPage = MainPage::Current;
00048 }
00049
00050 /// <summary>
00051 /// Finds the video profile for the front and back camera and queries if
00052 /// both cameras have a matching video recording profile that supports concurrency.
00053 /// If a matching concurrent profile is supported, then we configure media initialization
00054 /// settings for both cameras to the matching profile.
00055 /// </summary>
00056 /// <param name="sender">Contains information regarding button that fired event</param>
00057 /// <param name="e">Contains state information and event data associated with the event</param>
00058 void Scenario2_ConcurrentProfile::CheckConcurrentProfileBtn_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00059 {
00060     // Find front and back Device Id of capture device that supports Video Profile
00061     LogStatusToOutputBoxAsync("Looking for all video capture devices on front panel");
00062     GetVideoProfileSupportedDeviceIdAsync(Windows::Devices::Enumeration::Panel::Front)
00063         .then([this](String^ frontVideoDeviceId)
00064     {
00065         LogStatusToOutputBoxAsync("Looking for all video capture devices on back panel");
00066         return GetVideoProfileSupportedDeviceIdAsync(Windows::Devices::Enumeration::Panel::Back)
00067             .then([this, frontVideoDeviceId](String^ backVideoDeviceId)
00068         {
00069             // First check if the devices support video profiles, if not there's no reason to proceed
00070             if (frontVideoDeviceId == nullptr || backVideoDeviceId == nullptr)
00071             {
00072                 LogStatusAsync("ERROR: A capture device doesn't support Video Profile", NotifyType::ErrorMessage);
00073                 return;
00074             }
00075
00076             LogStatusToOutputBoxAsync("Video Profiles are supported on both cameras");
00077
00078             MediaCapture^ mediaCaptureFront = ref new MediaCapture();
00079             MediaCapture^ mediaCaptureBack = ref new MediaCapture();
00080
00081             // Create MediaCaptureInitilization settings for each video capture device
00082             MediaCaptureInitializationSettings^ mediaInitSettingsFront = ref new MediaCaptureInitializationSettings();
00083             MediaCaptureInitializationSettings^ mediaInitSettingsBack = ref new MediaCaptureInitializationSettings();
00084
00085             mediaInitSettingsFront->VideoDeviceId = frontVideoDeviceId;
00086             mediaInitSettingsBack->VideoDeviceId = backVideoDeviceId;
00087             std::wstringstream ss;
00088             ss << "Front Device Id located: " << frontVideoDeviceId->Data();
00089             LogStatusToOutputBoxAsync(ref new String(ss.str().c_str()));
00090             ss.str(std::wstring());
00091             ss << "Back Device Id located: " << backVideoDeviceId->Data();
00092             LogStatusToOutputBoxAsync(ref new String(ss.str().c_str()));
00093
00094             LogStatusToOutputBoxAsync("Querying for concurrent profile");
00095
00096             // Acquire concurrent profiles available to front and back capture devices, then locate a concurrent
00097             // profile Id that matches for both devices
00098             auto allFrontProfiles = MediaCapture::FindConcurrentProfiles(frontVideoDeviceId);
00099             auto allBackProfiles = MediaCapture::FindConcurrentProfiles(backVideoDeviceId);
00100             MediaCaptureVideoProfile^ frontProfile = nullptr;
00101             MediaCaptureVideoProfile^ backProfile = nullptr;
00102             for (auto fProfile : allFrontProfiles)
00103             {
00104                 for (auto bProfile : allBackProfiles)
00105                 {
00106                     if (fProfile->Id == bProfile->Id)
00107                     {
00108                         frontProfile = fProfile;
00109                         backProfile = bProfile;
00110                     }
00111                 }
00112             }
00113
00114             // Initialize our concurrency support flag.
00115             bool concurrencySupported = false;
00116             if (frontProfile != nullptr && backProfile != nullptr)
00117             {
00118                 mediaInitSettingsFront->VideoProfile = frontProfile;
00119                 mediaInitSettingsBack->VideoProfile = backProfile;
00120                 concurrencySupported = true;
00121
00122                 LogStatusAsync("Concurrent profile located, device supports concurrency", NotifyType::StatusMessage);
00123             }
00124             else
00125             {
00126                 // There are no concurrent profiles available on this device, thus
00127                 // there is not profile to select. With a lack of concurrent profile
00128                 // each camera will have to be managed manually and cannot support
00129                 // simultaneous streams. So we set the Video profile to null to
00130                 // indicate that camera must be managed individually.
00131                 mediaInitSettingsFront->VideoProfile = nullptr;
00132                 mediaInitSettingsBack->VideoProfile = nullptr;
00133
00134                 LogStatusAsync("No Concurrent profiles located, device does not support concurrency", NotifyType::ErrorMessage);
00135             }
00136
00137             LogStatusToOutputBoxAsync("Initializing Front camera settings");
00138
00139             std::vector<task<void>> initializeTasks;
00140             initializeTasks.push_back(create_task(mediaCaptureFront->InitializeAsync(mediaInitSettingsFront)));
00141
00142             if (concurrencySupported)
00143             {
00144                 LogStatusToOutputBoxAsync("Device supports concurrency, initializing Back camera settings");
00145
00146                 // Only initialize the back camera if concurrency is available.  Otherwise,
00147                 // we can only use one camera at a time (which in this case will be the front
00148                 // camera).
00149                 initializeTasks.push_back(create_task(mediaCaptureBack->InitializeAsync(mediaInitSettingsBack)));
00150             }
00151
00152             when_all(initializeTasks.begin(), initializeTasks.end())
00153                 .then([this]()
00154             {
00155                 LogStatusToOutputBoxAsync("Initialization complete");
00156             });
00157         });
00158     });
00159 }
00160
00161 /// <summary>
00162 /// Helper method to obtain a device Id that supports a Video Profile.
00163 /// If no Video Profile is found we return empty string indicating that there isn't a device on
00164 /// the desired panel with a supported Video Profile.
00165 /// </summary>
00166 /// <param name="panel">Contains Device Enumeration information regarding camera panel we are looking for</param>
00167 /// <returns>Device Information Id string</returns>
00168 task<String^> Scenario2_ConcurrentProfile::GetVideoProfileSupportedDeviceIdAsync(Windows::Devices::Enumeration::Panel panel)
00169 {
00170     // Find all video capture devices
00171     LogStatusToOutputBoxAsync("Looking for all video capture devices");
00172
00173     return create_task(DeviceInformation::FindAllAsync(DeviceClass::VideoCapture))
00174         .then([this, panel](DeviceInformationCollection^ devices)
00175     {
00176         String^ deviceId = nullptr;
00177         std::wstringstream ss;
00178         ss << "Number of video capture devices found: " << devices->Size;
00179         LogStatusToOutputBoxAsync(ref new String(ss.str().c_str()));
00180
00181         // Loop through devices looking for device that supports Video Profile
00182         for (auto cameraDeviceInfo : devices)
00183         {
00184             if (MediaCapture::IsVideoProfileSupported(cameraDeviceInfo->Id) && cameraDeviceInfo->EnclosureLocation->Panel == panel)
00185             {
00186                 deviceId = cameraDeviceInfo->Id;
00187                 break;
00188             }
00189         }
00190
00191         return deviceId;
00192     });
00193 }
00194
00195 /// <summary>
00196 /// Marshall log message to the UI thread and update outputBox, this method is for more general messages
00197 /// Note: This method is asynchronous and is not guaranteed to display messages in the order in
00198 /// which they were called without task chaining
00199 /// </summary>
00200 /// <param name="message">Message to log to the outputBox</param>
00201 /// <returns></returns>
00202 task<void> Scenario2_ConcurrentProfile::LogStatusToOutputBoxAsync(String^ message)
00203 {
00204     return create_task(Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, message]()
00205     {
00206         outputBox->Text += message + "\r\n";
00207         outputScrollViewer->ChangeView(0.0, outputBox->ActualHeight, 1.0f);
00208     })));
00209 }
00210
00211 /// <summary>
00212 /// Method to log Status to Main Status block, this method is for important status messages to be
00213 /// displayed at bottom of scenario page
00214 /// Note: This method is asynchronous and is not guaranteed to display messages in the order in
00215 /// which they were called without task chaining
00216 /// </summary>
00217 /// <param name="message">Message to log to the output box</param>
00218 /// <param name="type">Notification Type for status message</param>
00219 /// <returns></returns>
00220 task<void> Scenario2_ConcurrentProfile::LogStatusAsync(String^ message, NotifyType type)
00221 {
00222     return create_task(Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, message, type]()
00223     {
00224         _rootPage->NotifyUser(message, type);
00225     }))).then([this, message]()
00226     {
00227         return LogStatusToOutputBoxAsync(message);
00228     });
00229 }
Generated on Fri Nov 15 2024 22:18:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_ActiveSymbologies Member List

This is the complete list of members for Scenario3_ActiveSymbologies, including all inherited members.
claimedScanner_DataReceived(Windows::Devices::PointOfService::ClaimedBarcodeScanner const &, Windows::Devices::PointOfService::BarcodeScannerDataReceivedEventArgs args) | Scenario3_ActiveSymbologies | [private]
claimedScanner_ReleaseDeviceRequested(Windows::Foundation::IInspectable const &, Windows::Devices::PointOfService::ClaimedBarcodeScanner const &e) | Scenario3_ActiveSymbologies | [private]
m_scannerDataReceivedToken | Scenario3_ActiveSymbologies | [private]
m_scannerReleaseRequestedToken | Scenario3_ActiveSymbologies | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario3_ActiveSymbologies |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario3_ActiveSymbologies |
ResetTheScenarioState() | Scenario3_ActiveSymbologies | [private]
Scenario3_ActiveSymbologies() | Scenario3_ActiveSymbologies |
ScenarioEndScanButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_ActiveSymbologies |
ScenarioStartScanButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_ActiveSymbologies |
SetActiveSymbologies_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_ActiveSymbologies |
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PasswordVault/cpp/Scenario2_Manage.xaml.cpp Source File

  • PasswordVault
  • cpp

Scenario2_Manage.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Manage.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Platform::Collections;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Security::Credentials;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024
00025 Scenario2_Manage::Scenario2_Manage()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 void Scenario2_Manage::RetrieveCredentials_Click(Object^, Object^)
00031 {
00032     auto resource = InputResourceValue->Text;
00033     auto userName = InputUserNameValue->Text;
00034
00035     // Clear previous output.
00036     RetrievedCredentials->Items->Clear();
00037     rootPage->NotifyUser("", NotifyType::StatusMessage);
00038
00039     auto vault = ref new PasswordVault();
00040     IVectorView<PasswordCredential^>^ creds = nullptr;
00041
00042     // The credential retrieval functions raise an "Element not found"
00043     // exception if there were no matches.
00044     try
00045     {
00046         // Perform the desired queryInputUserNameValue.Text
00047         if (!resource && !userName)
00048         {
00049             // Both resource and user name are empty: Use retrieveAll().
00050             creds = vault->RetrieveAll();
00051         }
00052         else if (!userName)
00053         {
00054             // Resource is provided but no user name: Use findAllByResource().
00055             creds = vault->FindAllByResource(resource);
00056         }
00057         else if (!resource)
00058         {
00059             // User name is provided but no resource: Use findByUserName().
00060             creds = vault->FindAllByUserName(userName);
00061         }
00062         else
00063         {
00064             // Both resource and user name are provided: Use retrieve().
00065             PasswordCredential^ cred = vault->Retrieve(resource, userName);
00066             // Add it to our results if the retrieval was successful.
00067             if (cred != nullptr)
00068             {
00069                 auto vector = ref new Vector<PasswordCredential^>();
00070                 vector->Append(cred);
00071                 creds = vector->GetView();
00072             }
00073         }
00074     }
00075     catch (Exception^ e)
00076     {
00077         if (e->HResult != ElementNotFound)
00078         {
00079             throw;
00080         }
00081     }
00082
00083     // Display the results. Note that the password field is initially blank.
00084     // You must call retrievePassword() to get the password.
00085
00086     if (creds == nullptr || creds->Size == 0)
00087     {
00088         rootPage->NotifyUser("No matching credentials", NotifyType::ErrorMessage);
00089     }
00090     else
00091     {
00092         ItemCollection^ items = RetrievedCredentials->Items;
00093         for (PasswordCredential^ cred : creds)
00094         {
00095             auto item = ref new TextBlock();
00096             item->DataContext = cred;
00097             item->Text = cred->Resource + ": " + cred->UserName;
00098             items->Append(item);
00099         }
00100         rootPage->NotifyUser("Credentials found: " + items->Size.ToString(), NotifyType::StatusMessage);
00101     }
00102 }
00103
00104 void Scenario2_Manage::RevealPasswords_Click(Object^, Object^)
00105 {
00106     IVector<Object^>^ selectedItems = RetrievedCredentials->SelectedItems;
00107     if (selectedItems->Size > 0)
00108     {
00109         int retrievedCount = 0;
00110         for (Object^ o : selectedItems)
00111         {
00112             TextBlock^ item = safe_cast<TextBlock^>(o);
00113             PasswordCredential^ cred = safe_cast<PasswordCredential^>(item->DataContext);
00114             try
00115             {
00116                 cred->RetrievePassword();
00117                 item->Text = cred->Resource + ": " + cred->UserName + " (" + cred->Password + ")";
00118                 retrievedCount++;
00119             }
00120             catch (Exception^ e)
00121             {
00122                 if (e->HResult != ElementNotFound)
00123                 {
00124                     throw;
00125                 }
00126                 item->Text = cred->Resource + ": " + cred->UserName + " (password unavailable)";
00127             }
00128         }
00129         rootPage->NotifyUser("Passwords retrieved: " + retrievedCount.ToString(), NotifyType::StatusMessage);
00130     }
00131     else
00132     {
00133         rootPage->NotifyUser("No credentials selected", NotifyType::ErrorMessage);
00134     }
00135 }
00136
00137 void Scenario2_Manage::RemoveCredentials_Click(Object^, Object^)
00138 {
00139     IVector<Object^>^ selectedItems = RetrievedCredentials->SelectedItems;
00140     if (selectedItems->Size > 0)
00141     {
00142         auto vault = ref new PasswordVault();
00143         int removedCount = 0;
00144
00145         // Take a snapshot of the selectedOptions collection because we will be
00146         // changing the collection during the loop.
00147         auto snapshot = ref new Vector<Object^>(begin(selectedItems), end(selectedItems));
00148
00149         for (Object^ o : snapshot)
00150         {
00151             TextBlock^ item = safe_cast<TextBlock^>(o);
00152             PasswordCredential^ cred = safe_cast<PasswordCredential^>(item->DataContext);
00153             unsigned int index;
00154             if (RetrievedCredentials->Items->IndexOf(o, &index))
00155             {
00156                 RetrievedCredentials->Items->RemoveAt(index);
00157             }
00158
00159             try
00160             {
00161                 vault->Remove(cred);
00162                 removedCount++;
00163             }
00164             catch (Exception^ e)
00165             {
00166                 // Ignore exception if the credential was already removed.
00167                 if (e->HResult != ElementNotFound)
00168                 {
00169                     throw;
00170                 }
00171             }
00172         }
00173         rootPage->NotifyUser("Credentials removed: " + removedCount.ToString(), NotifyType::StatusMessage);
00174     }
00175     else
00176     {
00177         rootPage->NotifyUser("No credentials selected", NotifyType::ErrorMessage);
00178     }
00179 }
Generated on Fri Nov 15 2024 22:20:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceReadWrite Member List

This is the complete list of members for DeviceReadWrite, including all inherited members.
DeviceReadWrite() | DeviceReadWrite | [inline]
LogMessage(string message) | DeviceReadWrite | [inline, private]
ReadBlock_Click(object sender, RoutedEventArgs e) | DeviceReadWrite | [inline, private]
readCounter | DeviceReadWrite | [private]
rootPage | DeviceReadWrite | [private]
WriteBlock_Click(object sender, RoutedEventArgs e) | DeviceReadWrite | [inline, private]
writeCounter | DeviceReadWrite | [private]
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/MoveLookController.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

MoveLookController.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MoveLookController.h"
00014
00015 using namespace DirectX;
00016 using namespace winrt::Windows::UI::Core;
00017 using namespace winrt::Windows::UI::Input;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::Devices::Input;
00020 using namespace winrt::Windows::Gaming::Input;
00021 using namespace winrt::Windows::System;
00022
00023 // Analog control deadzone definitions. Tune these values to adjust the size of the deadzone.
00024 // Thumbstick range in each dimension is defined as [-1, 1].
00025 #define THUMBSTICK_DEADZONE 0.25f
00026
00027 // Trigger range is defined as [0, 1].
00028 #define TRIGGER_DEADZONE 0.1f
00029
00030 // If a CoreDispatcher is provided, this indicates the game is running on a separate thread
00031 // from the Xaml UI thread, and this separate thread does NOT have access to
00032 // the CoreWindow. The dispatcher can be used to marshal execution back to
00033 // the Xaml UI thread which does have a CoreWindow. The Dispatcher is cached
00034 // to enable execution of code on the UI thread to turn on and off the cursor glyph.
00035 MoveLookController::MoveLookController(_In_ CoreWindow const& window, _In_ CoreDispatcher const& dispatcher) :
00036     m_dispatcher(dispatcher),
00037     m_activeGamepad(nullptr),
00038     m_autoFire(true),
00039     m_pitch(0.0f),
00040     m_yaw(0.0f),
00041     m_state(MoveLookControllerState::None),
00042     m_gamepadStartButtonInUse(false),
00043     m_gamepadTriggerInUse(false),
00044     m_gamepadsChanged(true)
00045 {
00046     InitWindow(window);
00047 }
00048
00049 MoveLookController::MoveLookController(_In_ CoreWindow const& window) :
00050     m_dispatcher(nullptr),
00051     m_activeGamepad(nullptr),
00052     m_autoFire(true),
00053     m_pitch(0.0f),
00054     m_yaw(0.0f),
00055     m_state(MoveLookControllerState::None),
00056     m_gamepadStartButtonInUse(false),
00057     m_gamepadTriggerInUse(false),
00058     m_gamepadsChanged(true)
00059 {
00060     InitWindow(window);
00061 }
00062
00063 void MoveLookController::InitWindow(_In_ CoreWindow const& window)
00064 {
00065     ResetState();
00066
00067     window.PointerPressed({ this, &MoveLookController::OnPointerPressed });
00068
00069     window.PointerMoved({ this, &MoveLookController::OnPointerMoved });
00070
00071     window.PointerReleased({ this, &MoveLookController::OnPointerReleased });
00072
00073     window.PointerExited({ this, &MoveLookController::OnPointerExited });
00074
00075     window.KeyDown({ this, &MoveLookController::OnKeyDown });
00076
00077     window.KeyUp({ this, &MoveLookController::OnKeyUp });
00078
00079     // There is a separate handler for mouse-only relative mouse movement events.
00080     MouseDevice::GetForCurrentView().MouseMoved({ this, &MoveLookController::OnMouseMoved });
00081
00082     SystemNavigationManager::GetForCurrentView().BackRequested({ this, &MoveLookController::OnBackRequested });
00083
00084     // Detect gamepad connection and disconnection events.
00085     Gamepad::GamepadAdded({ this, &MoveLookController::OnGamepadAdded });
00086
00087     Gamepad::GamepadRemoved({ this, &MoveLookController::OnGamepadRemoved });
00088 }
00089
00090 bool MoveLookController::IsPauseRequested()
00091 {
00092     switch (m_state)
00093     {
00094     case MoveLookControllerState::Active:
00095         UpdatePollingDevices();
00096         if (m_pausePressed)
00097         {
00098 #ifdef MOVELOOKCONTROLLER_TRACE
00099             DebugTrace(L"IsPauseRequested == true\n");
00100 #endif
00101             m_pausePressed = false;
00102             return true;
00103         }
00104         else
00105         {
00106             return false;
00107         }
00108     }
00109     return false;
00110 }
00111
00112 bool MoveLookController::IsFiring()
00113 {
00114     if (m_state == MoveLookControllerState::Active)
00115     {
00116         if (m_autoFire)
00117         {
00118             return (m_fireInUse || (m_mouseInUse && m_mouseLeftInUse) || PollingFireInUse());
00119         }
00120         else
00121         {
00122             if (m_firePressed)
00123             {
00124                 m_firePressed = false;
00125                 return true;
00126             }
00127         }
00128     }
00129     return false;
00130 }
00131
00132 bool MoveLookController::IsPressComplete()
00133 {
00134     switch (m_state)
00135     {
00136     case MoveLookControllerState::WaitForInput:
00137         UpdatePollingDevices();
00138         if (m_buttonPressed)
00139         {
00140 #ifdef MOVELOOKCONTROLLER_TRACE
00141             DebugTrace(L"IsPressComplete == true\n");
00142 #endif
00143             m_buttonPressed = false;
00144             return true;
00145         }
00146         else
00147         {
00148             return false;
00149         }
00150         break;
00151     }
00152
00153     return false;
00154 }
00155
00156 void MoveLookController::OnPointerPressed(
00157     _In_ CoreWindow const& /* sender */,
00158     _In_ PointerEventArgs const& args
00159     )
00160 {
00161     PointerPoint point = args.CurrentPoint();
00162     uint32_t pointerID = point.PointerId();
00163     Point pointerPosition = point.Position();
00164     PointerPointProperties pointProperties = point.Properties();
00165     auto pointerDevice = point.PointerDevice();
00166     auto pointerDeviceType = pointerDevice.PointerDeviceType();
00167
00168     XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y);
00169
00170 #ifdef MOVELOOKCONTROLLER_TRACE
00171     DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)", L"Pressed", pointerID, position.x, position.y);
00172 #endif
00173
00174     switch (m_state)
00175     {
00176     case MoveLookControllerState::WaitForInput:
00177         if (position.x > m_buttonUpperLeft.x &&
00178             position.x < m_buttonLowerRight.x &&
00179             position.y > m_buttonUpperLeft.y &&
00180             position.y < m_buttonLowerRight.y)
00181         {
00182             // Wait until button released before setting variable.
00183             m_buttonPointerID = pointerID;
00184             m_buttonInUse = true;
00185 #ifdef MOVELOOKCONTROLLER_TRACE
00186             DebugTrace(L"\tWaitForInput(%d) - BUTTON in USE", pointerID);
00187 #endif
00188         }
00189         break;
00190
00191     case MoveLookControllerState::Active:
00192         switch (pointerDeviceType)
00193         {
00194         case winrt::Windows::Devices::Input::PointerDeviceType::Touch:
00195             if (position.x > m_moveUpperLeft.x &&
00196                 position.x < m_moveLowerRight.x &&
00197                 position.y > m_moveUpperLeft.y &&
00198                 position.y < m_moveLowerRight.y)
00199             {
00200                 // This pointer is in the move control.
00201                 if (!m_moveInUse)
00202                 {
00203                     // There is not an active pointer in this control yet.
00204                     // Process a DPad touch down event.
00205                     m_moveFirstDown = position;                 // Save location of initial contact.
00206                     m_movePointerID = pointerID;                // Store the pointer using this control.
00207                     m_moveInUse = true;
00208                 }
00209             }
00210             else if (position.x > m_fireUpperLeft.x &&
00211                 position.x < m_fireLowerRight.x &&
00212                 position.y > m_fireUpperLeft.y &&
00213                 position.y < m_fireLowerRight.y)
00214             {
00215                 // This pointer is in the fire control.
00216                 if (!m_fireInUse)
00217                 {
00218                     m_fireLastPoint = position;
00219                     m_firePointerID = pointerID;
00220                     m_fireInUse = true;
00221                     if (!m_autoFire)
00222                     {
00223                         m_firePressed = true;
00224                     }
00225                 }
00226             }
00227             else
00228             {
00229                 if (!m_lookInUse)
00230                 {
00231                     // There is not an active pointer in this control yet.
00232                     m_lookLastPoint = position;                   // Save point for later move.
00233                     m_lookPointerID = pointerID;                  // Store the pointer using this control.
00234                     m_lookLastDelta.x = m_lookLastDelta.y = 0;    // These are for smoothing.
00235                     m_lookInUse = true;
00236                 }
00237             }
00238             break;
00239
00240         default:
00241             bool rightButton = pointProperties.IsRightButtonPressed();
00242             bool leftButton = pointProperties.IsLeftButtonPressed();
00243
00244             if (!m_autoFire && (!m_mouseLeftInUse && leftButton))
00245             {
00246                 m_firePressed = true;
00247             }
00248
00249             if (!m_mouseInUse)
00250             {
00251                 m_mouseInUse = true;
00252                 m_mouseLastPoint = position;
00253                 m_mousePointerID = pointerID;
00254                 m_mouseLeftInUse = leftButton;
00255                 m_mouseRightInUse = rightButton;
00256                 m_lookLastDelta.x = m_lookLastDelta.y = 0;          // These are for smoothing.
00257             }
00258             else
00259             {
00260 #ifdef MOVELOOKCONTROLLER_TRACE
00261                 DebugTrace(L"\tWARNING: OnPointerPressed()  Mouse aleady in use (%d-%s%s) and new event id: %d %s%s",
00262                     m_mousePointerID,
00263                     m_mouseLeftInUse ? "L" : "",
00264                     m_mouseRightInUse ? "R" : "",
00265                     pointerID,
00266                     leftButton ? "L" : "",
00267                     rightButton ? "R" : ""
00268                     );
00269 #endif
00270             }
00271             break;
00272         }
00273 #ifdef MOVELOOKCONTROLLER_TRACE
00274         DebugTrace(
00275             L"\t%s%s%s %s%s%s",
00276             m_moveInUse ? L"Move " : L"",
00277             m_lookInUse ? L"Look " : L"",
00278             m_fireInUse ? L"Fire " : L"",
00279             m_mouseInUse ? L"Mouse:" : L"",
00280             m_mouseLeftInUse ? L"L" : L"-",
00281             m_mouseRightInUse ? L"R" : L"-"
00282             );
00283 #endif
00284         break;
00285     }
00286 #ifdef MOVELOOKCONTROLLER_TRACE
00287     DebugTrace(L"\n");
00288 #endif
00289     return;
00290 }
00291
00292 void MoveLookController::OnPointerMoved(
00293     _In_ CoreWindow const& /* sender */,
00294     _In_ PointerEventArgs const& args
00295     )
00296 {
00297     PointerPoint point = args.CurrentPoint();
00298     uint32_t pointerID = point.PointerId();
00299     Point pointerPosition = point.Position();
00300     PointerPointProperties pointProperties = point.Properties();
00301     auto pointerDevice = point.PointerDevice();
00302
00303     XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y);     // convert to allow math
00304
00305 #ifdef MOVELOOKCONTROLLER_TRACE
00306     DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)", L"Moved", pointerID, position.x, position.y);
00307 #endif
00308
00309     switch (m_state)
00310     {
00311     case MoveLookControllerState::Active:
00312         // Decide which control this pointer is operating.
00313         if (pointerID == m_movePointerID)
00314         {
00315             m_movePointerPosition = position;       // Save the current position.
00316         }
00317         else if (pointerID == m_lookPointerID)
00318         {
00319             // Look control.
00320             XMFLOAT2 pointerDelta;
00321             pointerDelta.x = position.x - m_lookLastPoint.x;        // How far did pointer move?
00322             pointerDelta.y = position.y - m_lookLastPoint.y;
00323
00324             XMFLOAT2 rotationDelta;
00325             rotationDelta.x = pointerDelta.x * MoveLookConstants::RotationGain;       // Scale for control sensitivity.
00326             rotationDelta.y = pointerDelta.y * MoveLookConstants::RotationGain;
00327             m_lookLastPoint = position;                             // Save for next time through.
00328
00329 #ifdef MOVELOOKCONTROLLER_TRACE
00330             DebugTrace(L"\tDelta (%4.0f, %4.0f)", pointerDelta.x, pointerDelta.y);
00331 #endif
00332
00333             // Update our orientation based on the command.
00334             m_pitch -= rotationDelta.y;
00335             m_yaw += rotationDelta.x;
00336
00337             // Limit pitch to straight up or straight down.
00338             float limit = XM_PI / 2.0f - 0.01f;
00339             m_pitch = __max(-limit, m_pitch);
00340             m_pitch = __min(+limit, m_pitch);
00341
00342             // Keep longitude in sane range by wrapping.
00343             if (m_yaw > XM_PI)
00344             {
00345                 m_yaw -= XM_PI * 2.0f;
00346             }
00347             else if (m_yaw < -XM_PI)
00348             {
00349                 m_yaw += XM_PI * 2.0f;
00350             }
00351         }
00352         else if (pointerID == m_firePointerID)
00353         {
00354             m_fireLastPoint = position;
00355         }
00356         else if (pointerID == m_mousePointerID)
00357         {
00358             m_mouseLeftInUse = pointProperties.IsLeftButtonPressed();
00359             m_mouseRightInUse = pointProperties.IsRightButtonPressed();
00360             m_mouseLastPoint = position;                            // Save for next time through.
00361         }
00362
00363         // Mouse movement is handled via a separate relative mouse movement handler (OnMouseMoved).
00364
00365         break;
00366     }
00367 #ifdef MOVELOOKCONTROLLER_TRACE
00368     DebugTrace(L"\n");
00369 #endif
00370 }
00371
00372 void MoveLookController::OnMouseMoved(
00373     _In_ MouseDevice const& /* mouseDevice */,
00374     _In_ MouseEventArgs const& args
00375     )
00376 {
00377     // Handle Mouse Input via dedicated relative movement handler.
00378
00379     switch (m_state)
00380     {
00381     case MoveLookControllerState::Active:
00382         XMFLOAT2 mouseDelta;
00383         mouseDelta.x = static_cast<float>(args.MouseDelta().X);
00384         mouseDelta.y = static_cast<float>(args.MouseDelta().Y);
00385
00386         XMFLOAT2 rotationDelta;
00387         rotationDelta.x = mouseDelta.x * MoveLookConstants::RotationGain;   // Scale for control sensitivity.
00388         rotationDelta.y = mouseDelta.y * MoveLookConstants::RotationGain;
00389
00390         // Update our orientation based on the command.
00391         m_pitch -= rotationDelta.y;
00392         m_yaw += rotationDelta.x;
00393
00394         // Limit pitch to straight up or straight down.
00395         float limit = XM_PI / 2.0f - 0.01f;
00396         m_pitch = __max(-limit, m_pitch);
00397         m_pitch = __min(+limit, m_pitch);
00398
00399         // Keep longitude in sane range by wrapping.
00400         if (m_yaw > XM_PI)
00401         {
00402             m_yaw -= XM_PI * 2.0f;
00403         }
00404         else if (m_yaw < -XM_PI)
00405         {
00406             m_yaw += XM_PI * 2.0f;
00407         }
00408         break;
00409     }
00410 }
00411
00412 void MoveLookController::OnPointerReleased(
00413     _In_ CoreWindow const& /* sender */,
00414     _In_ PointerEventArgs const& args
00415     )
00416 {
00417     PointerPoint point = args.CurrentPoint();
00418     uint32_t pointerID = point.PointerId();
00419     Point pointerPosition = point.Position();
00420     PointerPointProperties pointProperties = point.Properties();
00421
00422     XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y);
00423
00424 #ifdef MOVELOOKCONTROLLER_TRACE
00425     DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)\n", L"Release", pointerID, position.x, position.y);
00426 #endif
00427
00428     switch (m_state)
00429     {
00430     case MoveLookControllerState::WaitForInput:
00431         if (m_buttonInUse && (pointerID == m_buttonPointerID))
00432         {
00433             m_buttonInUse = false;
00434             m_buttonPressed = true;
00435 #ifdef MOVELOOKCONTROLLER_TRACE
00436             DebugTrace(L"\tWaitForInput: ButtonPressed = true\n");
00437 #endif
00438         }
00439         break;
00440
00441     case MoveLookControllerState::Active:
00442         if (pointerID == m_movePointerID)
00443         {
00444             m_velocity = XMFLOAT3(0, 0, 0);      // Stop on release.
00445             m_moveInUse = false;
00446             m_movePointerID = 0;
00447         }
00448         else if (pointerID == m_lookPointerID)
00449         {
00450             m_lookInUse = false;
00451             m_lookPointerID = 0;
00452         }
00453         else if (pointerID == m_firePointerID)
00454         {
00455             m_fireInUse = false;
00456             m_firePointerID = 0;
00457         }
00458         else if (pointerID == m_mousePointerID)
00459         {
00460             bool rightButton = pointProperties.IsRightButtonPressed();
00461             bool leftButton = pointProperties.IsLeftButtonPressed();
00462
00463             m_mouseInUse = false;
00464
00465             // Don't clear the mouse Pointer ID so that Move events still result in Look changes.
00466             m_mouseLeftInUse = leftButton;
00467             m_mouseRightInUse = rightButton;
00468         }
00469         break;
00470     }
00471 }
00472
00473 void MoveLookController::OnPointerExited(
00474     _In_ CoreWindow const& /* sender */,
00475     _In_ PointerEventArgs const& args
00476     )
00477 {
00478     PointerPoint point = args.CurrentPoint();
00479     uint32_t pointerID = point.PointerId();
00480     Point pointerPosition = point.Position();
00481     PointerPointProperties pointProperties = point.Properties();
00482
00483     XMFLOAT2 position = XMFLOAT2(pointerPosition.X, pointerPosition.Y);
00484
00485 #ifdef MOVELOOKCONTROLLER_TRACE
00486     DebugTrace(L"%-7s (%d) at (%4.0f, %4.0f)\n", L"Exit", pointerID, position.x, position.y);
00487 #endif
00488
00489     switch (m_state)
00490     {
00491     case MoveLookControllerState::WaitForInput:
00492         if (m_buttonInUse && (pointerID == m_buttonPointerID))
00493         {
00494             m_buttonInUse = false;
00495             m_buttonPressed = false;
00496 #ifdef MOVELOOKCONTROLLER_TRACE
00497             DebugTrace(L"\tWaitForPress: ButtonPressed = false -- Got Exit Event\n");
00498 #endif
00499         }
00500         break;
00501
00502     case MoveLookControllerState::Active:
00503         if (pointerID == m_movePointerID)
00504         {
00505             m_velocity = XMFLOAT3(0, 0, 0);      // Stop on release.
00506             m_moveInUse = false;
00507             m_movePointerID = 0;
00508         }
00509         else if (pointerID == m_lookPointerID)
00510         {
00511             m_lookInUse = false;
00512             m_lookPointerID = 0;
00513         }
00514         else if (pointerID == m_firePointerID)
00515         {
00516             m_fireInUse = false;
00517             m_firePointerID = 0;
00518         }
00519         else if (pointerID == m_mousePointerID)
00520         {
00521             m_mouseInUse = false;
00522             m_mousePointerID = 0;
00523             m_mouseLeftInUse = false;
00524             m_mouseRightInUse = false;
00525         }
00526         break;
00527     }
00528 }
00529
00530 void MoveLookController::OnKeyDown(
00531     _In_ CoreWindow const& /* sender */,
00532     _In_ KeyEventArgs const& args
00533     )
00534 {
00535     winrt::Windows::System::VirtualKey Key;
00536     Key = args.VirtualKey();
00537
00538     // Figure out the command from the keyboard.
00539     if (Key == VirtualKey::W)
00540         m_forward = true;
00541     if (Key == VirtualKey::S)
00542         m_back = true;
00543     if (Key == VirtualKey::A)
00544         m_left = true;
00545     if (Key == VirtualKey::D)
00546         m_right = true;
00547     if (Key == VirtualKey::Space)
00548         m_up = true;
00549     if (Key == VirtualKey::X)
00550         m_down = true;
00551     if (Key == VirtualKey::P)
00552         m_pause = true;
00553 }
00554
00555 void MoveLookController::OnKeyUp(
00556     _In_ CoreWindow const& /* sender */,
00557     _In_ KeyEventArgs const& args
00558     )
00559 {
00560     winrt::Windows::System::VirtualKey Key;
00561     Key = args.VirtualKey();
00562
00563     // Figure out the command from the keyboard.
00564     if (Key == VirtualKey::W)
00565         m_forward = false;
00566     if (Key == VirtualKey::S)
00567         m_back = false;
00568     if (Key == VirtualKey::A)
00569         m_left = false;
00570     if (Key == VirtualKey::D)
00571         m_right = false;
00572     if (Key == VirtualKey::Space)
00573         m_up = false;
00574     if (Key == VirtualKey::X)
00575         m_down = false;
00576     if (Key == VirtualKey::P)
00577     {
00578         if (m_pause)
00579         {
00580             // Trigger pause only once on button release.
00581             m_pausePressed = true;
00582             m_pause = false;
00583         }
00584     }
00585 }
00586
00587 void MoveLookController::ResetState()
00588 {
00589     // Reset the state of the MoveLookController.
00590     // Disable any active pointer IDs to stop all interaction.
00591     m_buttonPressed = false;
00592     m_pausePressed = false;
00593     m_buttonInUse = false;
00594     m_moveInUse = false;
00595     m_lookInUse = false;
00596     m_fireInUse = false;
00597     m_mouseInUse = false;
00598     m_mouseLeftInUse = false;
00599     m_mouseRightInUse = false;
00600     m_movePointerID = 0;
00601     m_lookPointerID = 0;
00602     m_firePointerID = 0;
00603     m_mousePointerID = 0;
00604     m_velocity = XMFLOAT3(0.0f, 0.0f, 0.0f);
00605     m_moveCommand = XMFLOAT3(0.0f, 0.0f, 0.0f);
00606     m_forward = false;
00607     m_back = false;
00608     m_left = false;
00609     m_right = false;
00610     m_up = false;
00611     m_down = false;
00612     m_pause = false;
00613 }
00614
00615 void MoveLookController::UpdatePollingDevices()
00616 {
00617     if (m_gamepadsChanged)
00618     {
00619         m_gamepadsChanged = false;
00620         uint32_t index = 0;
00621
00622         // Capture the list of gamepads so it won't change while we are studying it.
00623         auto gamepads = Gamepad::Gamepads();
00624
00625         if (gamepads.Size() == 0)
00626         {
00627             m_activeGamepad = nullptr;
00628         }
00629         // Check if the cached gamepad is still connected.
00630         else if (!gamepads.IndexOf(m_activeGamepad, index))
00631         {
00632             // MoveLookController is intended to handle input for a single player, so it
00633             // defaults to the first active gamepad.
00634             m_activeGamepad = gamepads.GetAt(0);
00635         }
00636     }
00637
00638     if (m_activeGamepad == nullptr)
00639     {
00640         return;
00641     }
00642
00643     GamepadReading reading = m_activeGamepad.GetCurrentReading();
00644
00645     switch (m_state)
00646     {
00647     case MoveLookControllerState::WaitForInput:
00648         if ((reading.Buttons & GamepadButtons::Menu) == GamepadButtons::Menu)
00649         {
00650             m_gamepadStartButtonInUse = true;
00651         }
00652         else if (m_gamepadStartButtonInUse)
00653         {
00654             // Trigger once only on button release.
00655             m_gamepadStartButtonInUse = false;
00656             m_buttonPressed = true;
00657         }
00658         break;
00659
00660     case MoveLookControllerState::Active:
00661         if ((reading.Buttons & GamepadButtons::Menu) == GamepadButtons::Menu)
00662         {
00663             m_gamepadStartButtonInUse = true;
00664         }
00665         else if (m_gamepadStartButtonInUse)
00666         {
00667             // Trigger once only on button release.
00668             m_gamepadStartButtonInUse = false;
00669             m_pausePressed = true;
00670         }
00671         // Use the left thumbstick on the game controller to control
00672         // the eye point position control. Thumbstick input is defined from [-1, 1].
00673         // We use a deadzone in the middle range to avoid drift.
00674         if (reading.LeftThumbstickX > THUMBSTICK_DEADZONE ||
00675             reading.LeftThumbstickX < -THUMBSTICK_DEADZONE)
00676         {
00677             float x = static_cast<float>(reading.LeftThumbstickX);
00678             m_moveCommand.x -= (x > 0) ? 1 : -1;
00679         }
00680
00681         if (reading.LeftThumbstickY > THUMBSTICK_DEADZONE ||
00682             reading.LeftThumbstickY < -THUMBSTICK_DEADZONE)
00683         {
00684             float y = static_cast<float>(reading.LeftThumbstickY);
00685             m_moveCommand.y += (y > 0) ? 1 : -1;
00686         }
00687
00688         // Use the right thumbstick on the game controller to control
00689         // the look at control. Thumbstick input is defined from [-1, 1].
00690         // We use a deadzone in the middle range to avoid drift.
00691         XMFLOAT2 pointerDelta;
00692         if (reading.RightThumbstickX > THUMBSTICK_DEADZONE ||
00693             reading.RightThumbstickX < -THUMBSTICK_DEADZONE)
00694         {
00695             float x = static_cast<float>(reading.RightThumbstickX);
00696             pointerDelta.x = x * x * x;
00697         }
00698         else
00699         {
00700             pointerDelta.x = 0.0f;
00701         }
00702
00703         if (reading.RightThumbstickY > THUMBSTICK_DEADZONE ||
00704             reading.RightThumbstickY < -THUMBSTICK_DEADZONE)
00705         {
00706             float y = static_cast<float>(reading.RightThumbstickY);
00707             pointerDelta.y = y * y * y;
00708         }
00709         else
00710         {
00711             pointerDelta.y = 0.0f;
00712         }
00713
00714         XMFLOAT2 rotationDelta;
00715         rotationDelta.x = pointerDelta.x * 0.08f;       // Scale for control sensitivity.
00716         rotationDelta.y = pointerDelta.y * 0.08f;
00717
00718         // Update our orientation based on the command.
00719         m_pitch += rotationDelta.y;
00720         m_yaw += rotationDelta.x;
00721
00722         // Limit pitch to straight up or straight down.
00723         m_pitch = __max(-XM_PI / 2.0f, m_pitch);
00724         m_pitch = __min(+XM_PI / 2.0f, m_pitch);
00725
00726         // Check the state of the Right Trigger button. This is used to indicate fire control.
00727
00728         if (reading.RightTrigger > TRIGGER_DEADZONE)
00729         {
00730             if (!m_autoFire && !m_gamepadTriggerInUse)
00731             {
00732                 m_firePressed = true;
00733             }
00734
00735             m_gamepadTriggerInUse = true;
00736         }
00737         else
00738         {
00739             m_gamepadTriggerInUse = false;
00740         }
00741         break;
00742     }
00743 }
00744
00745 // Turn on mouse cursor, which also disables relative mouse movement tracking.
00746 winrt::fire_and_forget MoveLookController::ShowCursor()
00747 {
00748     if (m_dispatcher != nullptr)
00749     {
00750         // Use the CoreDispatcher to ensure that the pointer is updated on the UI thread.
00751         // This is needed for XAML updates in a XAML app.
00752         co_await winrt::resume_foreground(m_dispatcher);
00753     }
00754
00755     auto window = CoreWindow::GetForCurrentThread();
00756     if (window)
00757     {
00758         // Protect case where there isn't a window associated with the current thread.
00759         // This happens on initialization or when being called from a background thread.
00760         window.PointerCursor(CoreCursor(CoreCursorType::Arrow, 0));
00761     }
00762 }
00763
00764 // Turn mouse cursor off (hidden), which also enables relative mouse movement tracking.
00765 winrt::fire_and_forget MoveLookController::HideCursor()
00766 {
00767     if (m_dispatcher != nullptr)
00768     {
00769         // Use the CoreDispatcher to ensure that the pointer is updated on the UI thread.
00770         // This is needed for XAML updates in a XAML app.
00771         co_await winrt::resume_foreground(m_dispatcher);
00772     }
00773
00774     auto window = CoreWindow::GetForCurrentThread();
00775     if (window)
00776     {
00777         // Protect case where there isn't a window associated with the current thread.
00778         // This happens on initialization or when being called from a background thread.
00779         window.PointerCursor(nullptr);
00780     }
00781 }
00782
00783 void MoveLookController::SetMoveRect(
00784     _In_ XMFLOAT2 upperLeft,
00785     _In_ XMFLOAT2 lowerRight
00786     )
00787 {
00788 #ifdef MOVELOOKCONTROLLER_TRACE
00789     DebugTrace(L"MoveRect (%d, %d) to (%d, %d)", upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
00790 #endif
00791     m_moveUpperLeft = upperLeft;
00792     m_moveLowerRight = lowerRight;
00793 }
00794
00795 void MoveLookController::SetFireRect(
00796     _In_ XMFLOAT2 upperLeft,
00797     _In_ XMFLOAT2 lowerRight
00798     )
00799 {
00800 #ifdef MOVELOOKCONTROLLER_TRACE
00801     DebugTrace(L"FireRect (%d, %d) to (%d, %d)", upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
00802 #endif
00803     m_fireUpperLeft = upperLeft;
00804     m_fireLowerRight = lowerRight;
00805 }
00806
00807 void MoveLookController::WaitForPress(
00808     _In_ XMFLOAT2 upperLeft,
00809     _In_ XMFLOAT2 lowerRight
00810     )
00811 {
00812 #ifdef MOVELOOKCONTROLLER_TRACE
00813     DebugTrace(L"WaitForPress (%.1f, %.1f) to (%.1f, %.1f)\n", upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
00814 #endif
00815
00816     ResetState();
00817     m_state = MoveLookControllerState::WaitForInput;
00818     m_buttonUpperLeft = upperLeft;
00819     m_buttonLowerRight = lowerRight;
00820     ShowCursor();
00821 }
00822
00823 void MoveLookController::WaitForPress()
00824 {
00825 #ifdef MOVELOOKCONTROLLER_TRACE
00826     DebugTrace(L"WaitForPress (null rect)\n");
00827 #endif
00828
00829     ResetState();
00830     m_state = MoveLookControllerState::WaitForInput;
00831     m_buttonUpperLeft.x = 0.0f;
00832     m_buttonUpperLeft.y = 0.0f;
00833     m_buttonLowerRight.x = 0.0f;
00834     m_buttonLowerRight.y = 0.0f;
00835     ShowCursor();
00836 }
00837
00838 XMFLOAT3 MoveLookController::Velocity()
00839 {
00840     return m_velocity;
00841 }
00842
00843 XMFLOAT3 MoveLookController::LookDirection()
00844 {
00845     XMFLOAT3 lookDirection;
00846
00847     float r = cosf(m_pitch);              // In the plane.
00848     lookDirection.y = sinf(m_pitch);      // Vertical.
00849     lookDirection.z = r * cosf(m_yaw);    // Fwd-back.
00850     lookDirection.x = r * sinf(m_yaw);    // Left-right.
00851
00852     return lookDirection;
00853 }
00854
00855 float MoveLookController::Pitch()
00856 {
00857     return m_pitch;
00858 }
00859
00860 void MoveLookController::Pitch(_In_ float pitch)
00861 {
00862     m_pitch = pitch;
00863 }
00864
00865 float MoveLookController::Yaw()
00866 {
00867     return m_yaw;
00868 }
00869
00870 void MoveLookController::Yaw(_In_ float yaw)
00871 {
00872     m_yaw = yaw;
00873 }
00874
00875 void MoveLookController::Active(_In_ bool active)
00876 {
00877     ResetState();
00878 #ifdef MOVELOOKCONTROLLER_TRACE
00879     DebugTrace(L"Active = %s\n", active ? L"true" : L"false");
00880 #endif
00881
00882     if (active)
00883     {
00884         m_state = MoveLookControllerState::Active;
00885         HideCursor();
00886
00887     }
00888     else
00889     {
00890         m_state = MoveLookControllerState::None;
00891         ShowCursor();
00892     }
00893 }
00894
00895 bool MoveLookController::Active()
00896 {
00897     if (m_state == MoveLookControllerState::Active)
00898     {
00899         return true;
00900     }
00901     else
00902     {
00903         return false;
00904     }
00905 }
00906
00907 void MoveLookController::AutoFire(_In_ bool autoFire)
00908 {
00909     m_autoFire = autoFire;
00910 }
00911
00912 bool MoveLookController::AutoFire()
00913 {
00914     return m_autoFire;
00915 }
00916
00917 void MoveLookController::Update()
00918 {
00919     UpdatePollingDevices();
00920
00921     if (m_moveInUse)
00922     {
00923         // Move control.
00924         XMFLOAT2 pointerDelta;
00925
00926         pointerDelta.x = m_movePointerPosition.x - m_moveFirstDown.x;
00927         pointerDelta.y = m_movePointerPosition.y - m_moveFirstDown.y;
00928
00929         // Figure out the command from the virtual joystick.
00930         XMFLOAT3 commandDirection = XMFLOAT3(0.0f, 0.0f, 0.0f);
00931         if (fabsf(pointerDelta.x) > 16.0f)         // Leave 32 pixel-wide dead spot for being still.
00932             m_moveCommand.x -= pointerDelta.x / fabsf(pointerDelta.x);
00933
00934         if (fabsf(pointerDelta.y) > 16.0f)
00935             m_moveCommand.y -= pointerDelta.y / fabsf(pointerDelta.y);
00936     }
00937
00938     // Poll our state bits set by the keyboard input events.
00939     if (m_forward)
00940     {
00941         m_moveCommand.y += 1.0f;
00942     }
00943     if (m_back)
00944     {
00945         m_moveCommand.y -= 1.0f;
00946     }
00947     if (m_left)
00948     {
00949         m_moveCommand.x += 1.0f;
00950     }
00951     if (m_right)
00952     {
00953         m_moveCommand.x -= 1.0f;
00954     }
00955     if (m_up)
00956     {
00957         m_moveCommand.z += 1.0f;
00958     }
00959     if (m_down)
00960     {
00961         m_moveCommand.z -= 1.0f;
00962     }
00963
00964     // Make sure that 45deg cases are not faster.
00965     if (fabsf(m_moveCommand.x) > 0.1f ||
00966         fabsf(m_moveCommand.y) > 0.1f ||
00967         fabsf(m_moveCommand.z) > 0.1f)
00968     {
00969         XMStoreFloat3(&m_moveCommand, XMVector3Normalize(XMLoadFloat3(&m_moveCommand)));
00970     }
00971
00972     // Rotate command to align with our direction (world coordinates).
00973     XMFLOAT3 wCommand;
00974     wCommand.x = m_moveCommand.x * cosf(m_yaw) - m_moveCommand.y * sinf(m_yaw);
00975     wCommand.y = m_moveCommand.x * sinf(m_yaw) + m_moveCommand.y * cosf(m_yaw);
00976     wCommand.z = m_moveCommand.z;
00977
00978     // Scale for sensitivity adjustment.
00979     // Our velocity is based on the command. Y is up.
00980     m_velocity.x = -wCommand.x * MoveLookConstants::MovementGain;
00981     m_velocity.z = wCommand.y * MoveLookConstants::MovementGain;
00982     m_velocity.y = wCommand.z * MoveLookConstants::MovementGain;
00983
00984     // Clear movement input accumulator for use during next frame.
00985     m_moveCommand = XMFLOAT3(0.0f, 0.0f, 0.0f);
00986 }
00987
00988 void MoveLookController::OnBackRequested(
00989     _In_ IInspectable const& /* sender */,
00990     _In_ BackRequestedEventArgs const& args
00991     )
00992 {
00993     if (m_state == MoveLookControllerState::Active)
00994     {
00995         // The game is currently in active play mode, so hitting the hardware back button
00996         // will cause the game to pause.
00997         m_pausePressed = true;
00998         args.Handled(true);
00999     }
01000     else
01001     {
01002         // The game is not currently in active play mode, so take the default behavior
01003         // for the hardware back button.
01004         args.Handled(false);
01005     }
01006 }
01007
01008 void MoveLookController::OnGamepadAdded(_In_ IInspectable const& /* sender */, _In_ Gamepad const& /* gamepad */)
01009 {
01010     // OnGamepadAdded and OnGamepadRemoved can be called from a worker thread. For simplicity,
01011     // defer updating the active gamepad until Update().
01012     m_gamepadsChanged = true;
01013 }
01014
01015 void MoveLookController::OnGamepadRemoved(_In_ IInspectable const& /* sender */, _In_ Gamepad const& /* gamepad */)
01016 {
01017     // OnGamepadAdded and OnGamepadRemoved can be called from a worker thread. For simplicity,
01018     // defer updating the active gamepad until Update().
01019     m_gamepadsChanged = true;
01020 }
01021
01022 #ifdef MOVELOOKCONTROLLER_TRACE
01023 void MoveLookController::DebugTrace(const wchar_t* format, ...)
01024 {
01025     // Generate the message string.
01026     va_list args;
01027     va_start(args, format);
01028     wchar_t message[1024];
01029     vswprintf_s(message, 1024, format, args);
01030     OutputDebugStringW(message);
01031 }
01032 #endif
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
ABSOLUTE_FILE_NAME | ScenarioElement | [private, static]
Error(string message) | ScenarioElement | [inline, private]
FILE_NAME | ScenarioElement | [private, static]
Initialize() | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
UserControl_Loaded(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
Generated on Fri Nov 15 2024 22:23:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3CustomOptions Member List

This is the complete list of members for Scenario3CustomOptions, including all inherited members.
OnNavigatedFrom(NavigationEventArgs e) | Scenario3CustomOptions | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario3CustomOptions | [inline, protected]
OnPrintButtonClick(object sender, RoutedEventArgs e) | Scenario3CustomOptions | [inline, private]
printHelper | Scenario3CustomOptions | [private]
Scenario3CustomOptions() | Scenario3CustomOptions | [inline]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ProjectionViewBroker Member List

This is the complete list of members for ProjectionViewBroker, including all inherited members.
MainPageDispatcher | ProjectionViewBroker |
MainViewId | ProjectionViewBroker |
NotifyProjectionStopping() | ProjectionViewBroker | [inline]
ProjectedPage | ProjectionViewBroker |
ProjectionStopping | ProjectionViewBroker |
ProjectionViewPageControl | ProjectionViewBroker |
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/AppView.h Source File

  • HolographicMixedRealityCapture
  • cpp

AppView.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "Common\DeviceResources.h"
00004 #include "HolographicMRCSampleMain.h"
00005
00006 namespace HolographicMRCSample
00007 {
00008     // IFrameworkView class. Connects the app with the Windows shell and handles application lifecycle events.
00009     ref class AppView sealed : public Windows::ApplicationModel::Core::IFrameworkView
00010     {
00011     public:
00012         AppView();
00013
00014         // IFrameworkView methods.
00015         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00016         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00017         virtual void Load(Platform::String^ entryPoint);
00018         virtual void Run();
00019         virtual void Uninitialize();
00020
00021     protected:
00022         // Application lifecycle event handlers.
00023         void OnViewActivated(Windows::ApplicationModel::Core::CoreApplicationView^ sender, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00024         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00025         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00026
00027         // Window event handlers.
00028         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00029         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00030
00031         // CoreWindow input event handlers.
00032         void OnKeyPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args);
00033
00034     private:
00035         std::unique_ptr<HolographicMRCSampleMain> m_main;
00036
00037         std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00038         bool                                                m_windowClosed  = false;
00039         bool                                                m_windowVisible = true;
00040
00041         // The holographic space the app will use for rendering.
00042         Windows::Graphics::Holographic::HolographicSpace^   m_holographicSpace = nullptr;
00043     };
00044
00045     // The entry point for the app.
00046     ref class AppViewSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00047     {
00048     public:
00049         virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00050     };
00051 }
00052
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cs/SampleConfiguration.cs Source File

  • XamlCommanding
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using Commanding;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Commanding";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="AppBarButtons", ClassType=typeof(Scenario1)},
00026             new Scenario() { Title="Icons", ClassType=typeof(Scenario2)},
00027             new Scenario() { Title="Opening/Closing Events", ClassType=typeof(Scenario3)},
00028             new Scenario() { Title="Control the CommandBar", ClassType=typeof(Scenario4)},
00029             new Scenario() { Title="Multiple CommandBars", ClassType=typeof(Scenario5)},
00030             new Scenario() { Title="Styling", ClassType=typeof(Scenario6)},
00031             new Scenario() { Title="Custom Content", ClassType=typeof(Scenario7)},
00032             new Scenario() { Title="Command Reflow", ClassType=typeof(Scenario8)},
00033         };
00034     }
00035
00036     public class Scenario
00037     {
00038         public string Title { get; set; }
00039         public Type ClassType { get; set; }
00040     }
00041 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cs/Scenario3_UnmanagedConsumable.xaml.cs Source File

  • Store
  • cs

Scenario3_UnmanagedConsumable.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Services.Store;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public sealed partial class Scenario3_UnmanagedConsumable : Page
00019     {
00020         MainPage rootPage = MainPage.Current;
00021         private StoreContext storeContext = StoreContext.GetDefault();
00022
00023         public Scenario3_UnmanagedConsumable()
00024         {
00025             this.InitializeComponent();
00026         }
00027
00028         private async void GetUnmanagedConsumablesButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00029         {
00030             string[] filterList = new string[] { "UnmanagedConsumable" };
00031
00032             // Get list of Add Ons this app can sell, filtering for the types we know about.
00033             StoreProductQueryResult addOns = await storeContext.GetAssociatedStoreProductsAsync(filterList);
00034
00035             ProductsListView.ItemsSource = Utils.CreateProductListFromQueryResult(addOns, "UnmanagedConsumable Add-Ons");
00036         }
00037
00038         private async void PurchaseAddOnButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00039         {
00040             var item = (ItemDetails)ProductsListView.SelectedItem;
00041
00042             var result = await storeContext.RequestPurchaseAsync(item.StoreId);
00043             if (result.ExtendedError != null)
00044             {
00045                 Utils.ReportExtendedError(result.ExtendedError);
00046                 return;
00047             }
00048
00049             switch (result.Status)
00050             {
00051                 case StorePurchaseStatus.AlreadyPurchased:
00052                     rootPage.NotifyUser($"You already bought this consumable and must fulfill it.", NotifyType.ErrorMessage);
00053                     break;
00054
00055                 case StorePurchaseStatus.Succeeded:
00056                     rootPage.NotifyUser($"You bought {item.Title}.", NotifyType.StatusMessage);
00057                     break;
00058
00059                 case StorePurchaseStatus.NotPurchased:
00060                     rootPage.NotifyUser("Product was not purchased, it may have been canceled.", NotifyType.ErrorMessage);
00061                     break;
00062
00063                 case StorePurchaseStatus.NetworkError:
00064                     rootPage.NotifyUser("Product was not purchased due to a network error.", NotifyType.ErrorMessage);
00065                     break;
00066
00067                 case StorePurchaseStatus.ServerError:
00068                     rootPage.NotifyUser("Product was not purchased due to a server error.", NotifyType.ErrorMessage);
00069                     break;
00070
00071                 default:
00072                     rootPage.NotifyUser("Product was not purchased due to an unknown error.", NotifyType.ErrorMessage);
00073                     break;
00074             }
00075         }
00076
00077         private async void GetConsumableBalanceButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00078         {
00079             var item = (ItemDetails)ProductsListView.SelectedItem;
00080
00081             StoreConsumableResult result = await storeContext.GetConsumableBalanceRemainingAsync(item.StoreId);
00082             if (result.ExtendedError != null)
00083             {
00084                 Utils.ReportExtendedError(result.ExtendedError);
00085                 return;
00086             }
00087
00088             switch (result.Status)
00089             {
00090                 case StoreConsumableStatus.InsufficentQuantity: // should never get this...
00091                     rootPage.NotifyUser($"Insufficient Quantity! Balance Remaining: {result.BalanceRemaining}", NotifyType.ErrorMessage);
00092                     break;
00093
00094                 case StoreConsumableStatus.Succeeded:
00095                     rootPage.NotifyUser($"Balance Remaining: {result.BalanceRemaining}", NotifyType.StatusMessage);
00096                     break;
00097
00098                 case StoreConsumableStatus.NetworkError:
00099                     rootPage.NotifyUser("Network error retrieving consumable balance.", NotifyType.ErrorMessage);
00100                     break;
00101
00102                 case StoreConsumableStatus.ServerError:
00103                     rootPage.NotifyUser("Server error retrieving consumable balance.", NotifyType.ErrorMessage);
00104                     break;
00105
00106                 default:
00107                     rootPage.NotifyUser("Unknown error retrieving consumable balance.", NotifyType.ErrorMessage);
00108                     break;
00109             }
00110         }
00111
00112         private async void FulfillConsumableButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00113         {
00114             var item = (ItemDetails)ProductsListView.SelectedItem;
00115
00116             // This can be used to ensure this request is never double fulfilled. The server will
00117             // accept only one report for this specific GUID.
00118             Guid trackingId = Guid.NewGuid();
00119
00120             // Always use quantity of "1" to fulfill an Unmanaged consumable
00121             StoreConsumableResult result = await storeContext.ReportConsumableFulfillmentAsync(item.StoreId, 1, trackingId);
00122             if (result.ExtendedError != null)
00123             {
00124                 Utils.ReportExtendedError(result.ExtendedError);
00125                 return;
00126             }
00127
00128             switch (result.Status)
00129             {
00130                 case StoreConsumableStatus.InsufficentQuantity:
00131                     rootPage.NotifyUser($"Insufficient Quantity! Balance Remaining: {result.BalanceRemaining}", NotifyType.ErrorMessage);
00132                     break;
00133
00134                 case StoreConsumableStatus.Succeeded:
00135                     rootPage.NotifyUser($"Successful fulfillment! Balance Remaining: {result.BalanceRemaining}", NotifyType.StatusMessage);
00136                     break;
00137
00138                 case StoreConsumableStatus.NetworkError:
00139                     rootPage.NotifyUser("Network error fulfilling consumable.", NotifyType.ErrorMessage);
00140                     break;
00141
00142                 case StoreConsumableStatus.ServerError:
00143                     rootPage.NotifyUser("Server error fulfilling consumable.", NotifyType.ErrorMessage);
00144                     break;
00145
00146                 default:
00147                     rootPage.NotifyUser("Unknown error fulfilling consumable.", NotifyType.ErrorMessage);
00148                     break;
00149             }
00150         }
00151     }
00152 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LibraryManagement/cpp/SampleConfiguration.cpp Source File

  • LibraryManagement
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Adding a folder to the Pictures library",     "SDKTemplate.Scenario1" },
00021     { "Listing folders in the Pictures library",     "SDKTemplate.Scenario2" },
00022     { "Removing a folder from the Pictures library", "SDKTemplate.Scenario3" }
00023 };
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SizePreferenceString Member List

This is the complete list of members for SizePreferenceString, including all inherited members.
Preference | SizePreferenceString
Title | SizePreferenceString
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cs/Scenario_SynthesizeText.xaml.cs Source File

  • SpeechRecognitionAndSynthesis
  • cs

Scenario_SynthesizeText.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Linq;
00014 using Windows.ApplicationModel.Resources.Core;
00015 using Windows.Globalization;
00016 using Windows.Media.SpeechSynthesis;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Media;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario_SynthesizeText : Page
00024     {
00025         private SpeechSynthesizer synthesizer;
00026         private ResourceContext speechContext;
00027         private ResourceMap speechResourceMap;
00028
00029         public Scenario_SynthesizeText()
00030         {
00031             InitializeComponent();
00032             synthesizer = new SpeechSynthesizer();
00033
00034             speechContext = ResourceContext.GetForCurrentView();
00035             speechContext.Languages = new string[] { SpeechSynthesizer.DefaultVoice.Language };
00036
00037             speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationTTSResources");
00038
00039             InitializeListboxVoiceChooser();
00040         }
00041
00042         /// <summary>
00043         /// This is invoked when the user clicks on the speak/stop button.
00044         /// </summary>
00045         /// <param name="sender">Button that triggered this event</param>
00046         /// <param name="e">State information about the routed event</param>
00047         private async void Speak_Click(object sender, RoutedEventArgs e)
00048         {
00049             // If the media is playing, the user has pressed the button to stop the playback.
00050             if (media.CurrentState == MediaElementState.Playing)
00051             {
00052                 media.Stop();
00053                 btnSpeak.Content = "Speak";
00054             }
00055             else
00056             {
00057                 string text = textToSynthesize.Text;
00058                 if (!String.IsNullOrEmpty(text))
00059                 {
00060                     // Change the button label. You could also just disable the button if you don't want any user control.
00061                     btnSpeak.Content = "Stop";
00062
00063                     try
00064                     {
00065                         // Create a stream from the text. This will be played using a media element.
00066                         SpeechSynthesisStream synthesisStream = await synthesizer.SynthesizeTextToStreamAsync(text);
00067
00068                         // Set the source and start playing the synthesized audio stream.
00069                         media.AutoPlay = true;
00070                         media.SetSource(synthesisStream, synthesisStream.ContentType);
00071                         media.Play();
00072                     }
00073                     catch (System.IO.FileNotFoundException)
00074                     {
00075                         // If media player components are unavailable, (eg, using a N SKU of windows), we won't
00076                         // be able to start media playback. Handle this gracefully
00077                         btnSpeak.Content = "Speak";
00078                         btnSpeak.IsEnabled = false;
00079                         textToSynthesize.IsEnabled = false;
00080                         listboxVoiceChooser.IsEnabled = false;
00081                         var messageDialog = new Windows.UI.Popups.MessageDialog("Media player components unavailable");
00082                         await messageDialog.ShowAsync();
00083                     }
00084                     catch (Exception)
00085                     {
00086                         // If the text is unable to be synthesized, throw an error message to the user.
00087                         btnSpeak.Content = "Speak";
00088                         media.AutoPlay = false;
00089                         var messageDialog = new Windows.UI.Popups.MessageDialog("Unable to synthesize text");
00090                         await messageDialog.ShowAsync();
00091                     }
00092                 }
00093             }
00094         }
00095
00096         /// <summary>
00097         /// This is invoked when the stream is finished playing.
00098         /// </summary>
00099         /// <remarks>
00100         /// In this case, we're changing the button label based on the state.
00101         /// </remarks>
00102         /// <param name="sender">unused object parameter</param>
00103         /// <param name="e">unused event parameter</param>
00104         void media_MediaEnded(object sender, RoutedEventArgs e)
00105         {
00106             btnSpeak.Content = "Speak";
00107         }
00108
00109         /// <summary>
00110         /// This creates items out of the system installed voices. The voices are then displayed in a listbox.
00111         /// This allows the user to change the voice of the synthesizer in your app based on their preference.
00112         /// </summary>
00113         private void InitializeListboxVoiceChooser()
00114         {
00115             // Get all of the installed voices.
00116             var voices = SpeechSynthesizer.AllVoices;
00117
00118             // Get the currently selected voice.
00119             VoiceInformation currentVoice = synthesizer.Voice;
00120
00121             foreach (VoiceInformation voice in voices.OrderBy(p=>p.Language))
00122             {
00123                 ComboBoxItem item = new ComboBoxItem();
00124                 item.Name = voice.DisplayName;
00125                 item.Tag = voice;
00126                 item.Content = voice.DisplayName + " (Language: " + voice.Language + ")";
00127                 listboxVoiceChooser.Items.Add(item);
00128
00129                 // Check to see if we're looking at the current voice and set it as selected in the listbox.
00130                 if (currentVoice.Id == voice.Id)
00131                 {
00132                     item.IsSelected = true;
00133                     listboxVoiceChooser.SelectedItem = item;
00134                 }
00135             }
00136         }
00137
00138         /// <summary>
00139         /// This is called when the user has selects a voice from the drop down.
00140         /// </summary>
00141         /// <param name="sender">unused object parameter</param>
00142         /// <param name="e">unused event parameter</param>
00143         private void ListboxVoiceChooser_SelectionChanged(object sender, SelectionChangedEventArgs e)
00144         {
00145             ComboBoxItem item = (ComboBoxItem)(listboxVoiceChooser.SelectedItem);
00146             VoiceInformation voice = (VoiceInformation)(item.Tag);
00147             synthesizer.Voice = voice;
00148
00149             // update UI text to be an appropriate default translation.
00150             speechContext.Languages = new string[] { voice.Language };
00151             textToSynthesize.Text = speechResourceMap.GetValue("SynthesizeTextDefaultText", speechContext).ValueAsString;
00152         }
00153     }
00154 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaEditing/cs/SampleConfiguration.cs Source File

  • MediaEditing
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using MediaEditingSample;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Media Editing";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Trimming and saving a clip", ClassType=typeof(Scenario1_TrimAndSaveClip)},
00026             new Scenario() { Title="Appending multiple clips", ClassType=typeof(Scenario2_AppendClips)},
00027             new Scenario() { Title="Adding background audio tracks", ClassType=typeof(Scenario3_AddAudioTracks)},
00028             new Scenario() { Title="Adding overlays to a clip", ClassType=typeof(Scenario4_AddOverlays)},
00029         };
00030     }
00031
00032     public class Scenario
00033     {
00034         public string Title { get; set; }
00035         public Type ClassType { get; set; }
00036     }
00037 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FileOpenPicker_PickURLFile Member List

This is the complete list of members for FileOpenPicker_PickURLFile, including all inherited members.
AddUriFileButton_Click(object sender, RoutedEventArgs e) | FileOpenPicker_PickURLFile | [inline, private]
dispatcher | FileOpenPicker_PickURLFile | [private]
FileOpenPicker_PickURLFile() | FileOpenPicker_PickURLFile | [inline]
fileOpenPickerUI | FileOpenPicker_PickURLFile | [private]
id | FileOpenPicker_PickURLFile | [private]
OnNavigatedTo(NavigationEventArgs e) | FileOpenPicker_PickURLFile | [inline, protected]
RemoveUriFileButton_Click(object sender, RoutedEventArgs e) | FileOpenPicker_PickURLFile | [inline, private]
UpdateButtonState(bool fileInBasket) | FileOpenPicker_PickURLFile | [inline, private]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DialLaunchArguments Member List

This is the complete list of members for DialLaunchArguments, including all inherited members.
DialLaunchArguments() | DialLaunchArguments | [inline, private]
PairingCode | DialLaunchArguments |
Parse(string arguments) | DialLaunchArguments | [inline, static]
Position | DialLaunchArguments |
VideoId | DialLaunchArguments |
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/App.cpp Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

App.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "App.h"
00014
00015 #include <ppltasks.h>
00016
00017 using namespace CustomVertexShader;
00018
00019 using namespace concurrency;
00020 using namespace Windows::ApplicationModel;
00021 using namespace Windows::ApplicationModel::Core;
00022 using namespace Windows::ApplicationModel::Activation;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Input;
00025 using namespace Windows::System;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Graphics::Display;
00028 using namespace Windows::Storage;
00029
00030 // The main function is only used to initialize our IFrameworkView class.
00031 [Platform::MTAThread]
00032 int main(Platform::Array<Platform::String^>^)
00033 {
00034     auto direct3DApplicationSource = ref new Direct3DApplicationSource();
00035     CoreApplication::Run(direct3DApplicationSource);
00036     return 0;
00037 }
00038
00039 IFrameworkView^ Direct3DApplicationSource::CreateView()
00040 {
00041     return ref new App();
00042 }
00043
00044 App::App() :
00045     m_windowClosed(false),
00046     m_windowVisible(true)
00047 {
00048 }
00049
00050 // The first method called when the IFrameworkView is being created.
00051 void App::Initialize(CoreApplicationView^ applicationView)
00052 {
00053     // Register event handlers for app lifecycle. This example includes Activated, so that we
00054     // can make the CoreWindow active and start rendering on the window.
00055     applicationView->Activated +=
00056         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated);
00057
00058     CoreApplication::Suspending +=
00059         ref new EventHandler<SuspendingEventArgs^>(this, &App::OnSuspending);
00060
00061     CoreApplication::Resuming +=
00062         ref new EventHandler<Platform::Object^>(this, &App::OnResuming);
00063
00064     // At this point we have access to the device.
00065     // We can create the device-dependent resources.
00066     m_deviceResources = std::make_shared<DX::DeviceResources>();
00067 }
00068
00069 // Called when the CoreWindow object is created (or re-created).
00070 void App::SetWindow(CoreWindow^ window)
00071 {
00072     window->SizeChanged +=
00073         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &App::OnWindowSizeChanged);
00074
00075     window->VisibilityChanged +=
00076         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &App::OnVisibilityChanged);
00077
00078     window->Closed +=
00079         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::OnWindowClosed);
00080
00081     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00082
00083     currentDisplayInformation->DpiChanged +=
00084         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDpiChanged);
00085
00086     currentDisplayInformation->OrientationChanged +=
00087         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnOrientationChanged);
00088
00089     DisplayInformation::DisplayContentsInvalidated +=
00090         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDisplayContentsInvalidated);
00091
00092     window->PointerPressed +=
00093         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerPressed);
00094
00095     window->PointerReleased +=
00096         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerReleased);
00097
00098     window->PointerMoved +=
00099         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerMoved);
00100
00101     window->PointerWheelChanged +=
00102         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerWheelChanged);
00103
00104     // The gesture recognizer automatically recognizes actions such as zooms
00105     // (whether by pinching or using the scroll wheel) and cursor movement.
00106     m_gestureRecognizer = ref new GestureRecognizer();
00107
00108     m_gestureRecognizer->GestureSettings =
00109         GestureSettings::ManipulationTranslateX |
00110         GestureSettings::ManipulationTranslateY |
00111         GestureSettings::ManipulationTranslateInertia;
00112
00113     m_gestureRecognizer->ManipulationUpdated +=
00114         ref new TypedEventHandler<GestureRecognizer^, ManipulationUpdatedEventArgs^>(this, &App::OnManipulationUpdated);
00115
00116     // Disable all pointer visual feedback for better performance when touching.
00117     auto pointerVisualizationSettings = PointerVisualizationSettings::GetForCurrentView();
00118     pointerVisualizationSettings->IsContactFeedbackEnabled = false;
00119     pointerVisualizationSettings->IsBarrelButtonFeedbackEnabled = false;
00120
00121     m_deviceResources->SetWindow(window);
00122 }
00123
00124 // Initializes scene resources, or loads a previously saved app state.
00125 void App::Load(Platform::String^ entryPoint)
00126 {
00127     if (m_main == nullptr)
00128     {
00129         m_main = std::unique_ptr<CustomVertexShaderMain>(new CustomVertexShaderMain(m_deviceResources));
00130     }
00131 }
00132
00133 // This method is called after the window becomes active.
00134 void App::Run()
00135 {
00136     while (!m_windowClosed)
00137     {
00138         if (m_windowVisible)
00139         {
00140             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00141
00142             m_main->Update();
00143
00144             if (m_main->Render())
00145             {
00146                 m_deviceResources->Present();
00147             }
00148         }
00149         else
00150         {
00151             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00152         }
00153     }
00154 }
00155
00156 // Required for IFrameworkView.
00157 // Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
00158 // class is torn down while the app is in the foreground.
00159 void App::Uninitialize()
00160 {
00161 }
00162
00163 // Application lifecycle event handlers.
00164
00165 void App::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
00166 {
00167     // Run() won't start until the CoreWindow is activated.
00168     CoreWindow::GetForCurrentThread()->Activate();
00169 }
00170
00171 void App::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
00172 {
00173     // Save app state asynchronously after requesting a deferral. Holding a deferral
00174     // indicates that the application is busy performing suspending operations. Be
00175     // aware that a deferral may not be held indefinitely. After about five seconds,
00176     // the app will be forced to exit.
00177     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
00178
00179     create_task([this, deferral]()
00180     {
00181         m_deviceResources->Trim();
00182
00183         m_main->SaveInternalState(ApplicationData::Current->LocalSettings->Values);
00184
00185         deferral->Complete();
00186     });
00187 }
00188
00189 void App::OnResuming(Platform::Object^ sender, Platform::Object^ args)
00190 {
00191     // Restore any data or state that was unloaded on suspend. By default, data
00192     // and state are persisted when resuming from suspend. Note that this event
00193     // does not occur if the app was previously terminated.
00194
00195     m_main->LoadInternalState(ApplicationData::Current->LocalSettings->Values);
00196 }
00197
00198 // Window event handlers.
00199
00200 void App::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
00201 {
00202     m_deviceResources->SetLogicalSize(Size(sender->Bounds.Width, sender->Bounds.Height));
00203     m_main->CreateWindowSizeDependentResources();
00204 }
00205
00206 void App::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
00207 {
00208     m_windowVisible = args->Visible;
00209 }
00210
00211 void App::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
00212 {
00213     m_windowClosed = true;
00214 }
00215
00216 // DisplayInformation event handlers.
00217
00218 void App::OnDpiChanged(DisplayInformation^ sender, Object^ args)
00219 {
00220     m_deviceResources->SetDpi(sender->LogicalDpi);
00221     m_main->CreateWindowSizeDependentResources();
00222 }
00223
00224 void App::OnOrientationChanged(DisplayInformation^ sender, Object^ args)
00225 {
00226     m_deviceResources->SetCurrentOrientation(sender->CurrentOrientation);
00227     m_main->CreateWindowSizeDependentResources();
00228 }
00229
00230 void App::OnDisplayContentsInvalidated(DisplayInformation^ sender, Object^ args)
00231 {
00232     m_deviceResources->ValidateDevice();
00233 }
00234
00235 void App::OnPointerMoved(CoreWindow ^ sender, PointerEventArgs ^ args)
00236 {
00237     m_gestureRecognizer->ProcessMoveEvents(args->GetIntermediatePoints());
00238 }
00239
00240 void App::OnPointerPressed(CoreWindow ^ sender, PointerEventArgs ^ args)
00241 {
00242     m_gestureRecognizer->ProcessDownEvent(args->CurrentPoint);
00243 }
00244
00245 void App::OnPointerReleased(CoreWindow ^ sender, PointerEventArgs ^ args)
00246 {
00247     m_gestureRecognizer->ProcessUpEvent(args->CurrentPoint);
00248 }
00249
00250 void App::OnPointerWheelChanged(CoreWindow ^ sender, PointerEventArgs ^ args)
00251 {
00252     m_gestureRecognizer->ProcessMouseWheelEvent(args->CurrentPoint, false, true);
00253 }
00254
00255 void App::OnManipulationUpdated(GestureRecognizer ^ sender, ManipulationUpdatedEventArgs ^ args)
00256 {
00257     m_main->UpdateManipulationState(args);
00258 }
Generated on Fri Nov 15 2024 22:18:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DetailsPage Member List

This is the complete list of members for DetailsPage, including all inherited members.
DeleteItem(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | DetailsPage |
DetailsPage() | DetailsPage |
NavigateBackForWideState(bool useTransition) | DetailsPage | [private]
OnBackRequested(Windows::Foundation::IInspectable const &, Windows::UI::Core::BackRequestedEventArgs const &e) | DetailsPage | [private]
OnLoaded(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | DetailsPage |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | DetailsPage |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | DetailsPage |
OnUnloaded(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | DetailsPage |
OnWindowSizeChanged(Windows::Foundation::IInspectable const &, Windows::UI::Core::WindowSizeChangedEventArgs const &) | DetailsPage | [private]
SelectedContact() | DetailsPage | [inline]
ShouldGoToWideState() | DetailsPage | [private]
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteColorGlyph/cpp/pch.cpp Source File

  • DWriteColorGlyph
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SpatialInputHandler Member List

This is the complete list of members for SpatialInputHandler, including all inherited members.
CheckForInput() | SpatialInputHandler | [inline]
interactionManager | SpatialInputHandler | [private]
OnSourcePressed(SpatialInteractionManager sender, SpatialInteractionSourceEventArgs args) | SpatialInputHandler | [inline]
sourceState | SpatialInputHandler | [private]
SpatialInputHandler() | SpatialInputHandler | [inline]
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ConfigStore Member List

This is the complete list of members for ConfigStore, including all inherited members.
AuthenticateThroughBackgroundTask | ConfigStore | [static]
AuthenticationHost | ConfigStore | [static]
AuthenticationToken | ConfigStore | [static]
ExtraParameters | ConfigStore | [static]
GetValueWithDefault< T >(string name, T defaultValue) | ConfigStore | [inline, private, static]
MarkAsManualConnect | ConfigStore | [static]
Password | ConfigStore | [static]
UseNativeWISPr | ConfigStore | [static]
UserName | ConfigStore | [static]
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cs/SampleConfiguration.cs Source File

  • LineDisplay
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Devices.PointOfService;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Controls.Primitives;
00019
00020 namespace SDKTemplate
00021 {
00022     public partial class MainPage : Page
00023     {
00024         public const string FEATURE_NAME = "Line Display C# Sample";
00025
00026         List<Scenario> scenarios = new List<Scenario>
00027         {
00028             new Scenario() { Title="Selecting a Line Display", ClassType=typeof(Scenario1_SelectDisplay)},
00029             new Scenario() { Title="Displaying text", ClassType=typeof(Scenario2_DisplayText)},
00030             new Scenario() { Title="Using windows to control layout", ClassType=typeof(Scenario3_UsingWindows)},
00031             new Scenario() { Title="Updating line display attributes", ClassType=typeof(Scenario4_UpdatingLineDisplayAttributes)},
00032             new Scenario() { Title="Defining custom glyphs", ClassType=typeof(Scenario5_DefiningCustomGlyphs)},
00033             new Scenario() { Title="Modifying the display cursor", ClassType=typeof(Scenario6_ManipulatingCursorAttributes)},
00034             new Scenario() { Title="Scrolling content using marquee", ClassType=typeof(Scenario7_ScrollingContentUsingMarquee)},
00035         };
00036
00037         // The device ID of the selected line display.
00038         public string LineDisplayId = null;
00039
00040         public async Task<ClaimedLineDisplay> ClaimScenarioLineDisplayAsync()
00041         {
00042             ClaimedLineDisplay lineDisplay = null;
00043             if (String.IsNullOrEmpty(LineDisplayId))
00044             {
00045                 NotifyUser("You must use scenario 1 to select a line display", NotifyType.ErrorMessage);
00046             }
00047             else
00048             {
00049                 lineDisplay = await ClaimedLineDisplay.FromIdAsync(LineDisplayId);
00050                 if (lineDisplay == null)
00051                 {
00052                     NotifyUser("Unable to claim selected LineDisplay from id.", NotifyType.ErrorMessage);
00053                 }
00054             }
00055             return lineDisplay;
00056         }
00057     }
00058
00059     public class Scenario
00060     {
00061         public string Title { get; set; }
00062         public Type ClassType { get; set; }
00063     }
00064
00065     static class Helpers
00066     {
00067         public static double ParseUIntWithFallback(TextBox textBox, double fallback)
00068         {
00069             uint value;
00070             if (uint.TryParse(textBox.Text, out value))
00071             {
00072                 return value;
00073             }
00074             return fallback;
00075         }
00076
00077         public static T GetSelectedItemTag<T>(Selector selector)
00078         {
00079             return (T)((FrameworkElement)selector.SelectedItem).Tag;
00080         }
00081     }
00082 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OCR/cs/SampleConfiguration.cs Source File

  • OCR
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using SDKTemplate;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "OCR C# sample";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="OCR image file", ClassType=typeof(OcrFileImage)},
00026             new Scenario() { Title="OCR captured image", ClassType=typeof(OcrCapturedImage)}
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/ActivationTypes/ForegroundWithAppClosed/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • ActivationTypes
  • ForegroundWithAppClosed

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using BackgroundTasks.Helpers;
00002 using System;
00003 using Windows.ApplicationModel.Activation;
00004 using Windows.ApplicationModel.Core;
00005 using Windows.Foundation.Collections;
00006 using Windows.UI.Notifications;
00007 using Windows.UI.Popups;
00008 using Windows.UI.Xaml;
00009 using Windows.UI.Xaml.Controls;
00010
00011 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00012
00013 namespace Notifications.ScenarioPages.Toasts.ActivationTypes.ForegroundWithAppClosed
00014 {
00015     /// <summary>
00016     /// An empty page that can be used on its own or navigated to within a Frame.
00017     /// </summary>
00018     public sealed partial class ScenarioElement : UserControl
00019     {
00020         public ScenarioElement()
00021         {
00022             this.InitializeComponent();
00023
00024             base.Loaded += ScenarioElement_Loaded;
00025         }
00026
00027         private void ScenarioElement_Loaded(object sender, RoutedEventArgs e)
00028         {
00029             Initialize();
00030         }
00031
00032         private void Initialize()
00033         {
00034             if (Settings.ScenarioToOpenWhenLaunchedOrActivated == this.GetType())
00035             {
00036                 Settings.ScenarioToOpenWhenLaunchedOrActivated = null;
00037
00038                 if (App.ActivatedEventArgs == null)
00039                 {
00040                     Error("OnActivated was not triggered.");
00041                     return;
00042                 }
00043
00044                 if (App.ActivatedEventArgs.Kind != ActivationKind.ToastNotification)
00045                 {
00046                     Error("Activated args kind was not ActivationKind.ToastNotification");
00047                     return;
00048                 }
00049
00050                 var toastArgs = App.ActivatedEventArgs as ToastNotificationActivatedEventArgs;
00051                 if (toastArgs == null)
00052                 {
00053                     Error("Activated args was not of type ToastNotificationActivatedEventArgs.");
00054                     return;
00055                 }
00056
00057                 string arguments = toastArgs.Argument;
00058
00059                 if (arguments == null || !arguments.Equals("quickReply"))
00060                 {
00061                     Error($"Expected arguments to be 'quickReply' but was '{arguments}'.");
00062                     return;
00063                 }
00064
00065                 validateStep1(toastArgs.UserInput);
00066                 return;
00067             }
00068
00069
00070             // Clear all existing notifications
00071             ToastNotificationManager.History.Clear();
00072
00073             // Pop notifications
00074             popToastControl.Payload =
00075                 $@"
00076                 <toast activationType='foreground' launch='args'>
00077                     <visual>
00078                         <binding template='ToastGeneric'>
00079                             <text>Foreground with App Closed</text>
00080                             <text>Close the app. Make sure ""Windows 10"" is in the first text box. Press ""submit"".</text>
00081                         </binding>
00082                     </visual>
00083                     <actions>
00084
00085                         <input
00086                             id = 'message'
00087                             type = 'text'
00088                             title = 'Message'
00089                             placeHolderContent = 'Enter ""Windows 10""'
00090                             defaultInput = 'Windows 10' />
00091
00092                         <action activationType = 'foreground'
00093                                 arguments = 'quickReply'
00094                                 content = 'submit' />
00095
00096                         <action activationType = 'foreground'
00097                                 arguments = 'cancel'
00098                                 content = 'cancel' />
00099
00100                     </actions>
00101                 </toast>";
00102
00103             // Have it open this scenario when the app is launched or activated
00104             Settings.ScenarioToOpenWhenLaunchedOrActivated = this.GetType();
00105         }
00106
00107         private async void App_Activated(object sender, IActivatedEventArgs e)
00108         {
00109             await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, delegate
00110             {
00111                 var toastArgs = e as ToastNotificationActivatedEventArgs;
00112                 if (toastArgs == null)
00113                     return;
00114
00115                 string arguments = toastArgs.Argument;
00116
00117                 if (arguments == null || !arguments.Equals("quickReply"))
00118                 {
00119                     Error($"Expected arguments to be 'quickReply' but was '{arguments}'.");
00120                     return;
00121                 }
00122
00123                 switch (stepsControl.Step)
00124                 {
00125                     case 1:
00126                         validateStep1(toastArgs.UserInput);
00127                         break;
00128                 }
00129             });
00130         }
00131
00132         private async void Error(string message)
00133         {
00134             await new MessageDialog(message, "ERROR").ShowAsync();
00135         }
00136
00137         private void validateStep1(ValueSet result)
00138         {
00139             if (result.Count != 1)
00140                 Error("Expected 1 user input value, but there were " + result.Count);
00141
00142             else if (!result.ContainsKey("message"))
00143                 Error("Expected a user input value for 'message', but there was none.");
00144
00145             else if (!(result["message"] as string).Equals("Windows 10"))
00146                 Error("User input value for 'message' was not 'Windows 10'");
00147
00148             else
00149             {
00150                 stepsControl.Step = int.MaxValue;
00151             }
00152         }
00153     }
00154 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/xBindSampleModel/Employee.cs Source File

  • XamlBind
  • cs
  • xBindSampleModel

Employee.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Popups;
00003 using Windows.UI.Xaml;
00004
00005 namespace xBindSampleModel
00006 {
00007     internal class Employee : IEmployee
00008     {
00009         private string _FirstName;
00010         private string _LastName;
00011         private Manager _Manager;
00012
00013         internal Employee()
00014         {
00015             Visibility = true;
00016         }
00017
00018         public void Poke(object sender, RoutedEventArgs e)
00019         {
00020             MessageDialog dlg = new MessageDialog(Name + " has been poked.");
00021             var t = dlg.ShowAsync();
00022         }
00023
00024         public bool Visibility { get; set; }
00025
00026         public string NullStringProperty
00027         {
00028             get { return null; }
00029             set { }
00030         }
00031         public Windows.UI.Xaml.Media.ImageSource NullImageSource
00032         {
00033             get { return null; }
00034             set { }
00035         }
00036
00037         public string FirstName
00038         {
00039             get { return _FirstName; }
00040             set
00041             {
00042                 if (value != _FirstName)
00043                 {
00044                     _FirstName = value;
00045                 }
00046             }
00047         }
00048
00049         public string LastName
00050         {
00051             get { return _LastName; }
00052             set
00053             {
00054                 if (value != _LastName)
00055                 {
00056                     _LastName = value;
00057                 }
00058             }
00059         }
00060
00061         public Manager DirectManager
00062         {
00063             get { return _Manager; }
00064             set
00065             {
00066                 if (value != _Manager)
00067                 {
00068                     _Manager = value;
00069                 }
00070             }
00071         }
00072
00073         public bool IsManager { get { return false; } }
00074
00075         public String Title { get { return "Developer"; } }
00076
00077         public string Name { get { return FirstName + " " + LastName; } }
00078
00079         public string FullName() { return FirstName + " " + LastName; }
00080     }
00081 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cpp/SampleConfiguration.cpp Source File

  • Accelerometer
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Choose accelerometer", "SDKTemplate.Scenario0_Choose" },
00021     { "Data Events", "SDKTemplate.Scenario1_DataEvents" },
00022     { "Shake Events", "SDKTemplate.Scenario2_ShakeEvents" },
00023     { "Polling", "SDKTemplate.Scenario3_Polling" },
00024     { "OrientationChanged", "SDKTemplate.Scenario4_OrientationChanged" },
00025     { "Data Events Batching", "SDKTemplate.Scenario5_DataEventsBatching" }
00026 };
00027
00028 void MainPage::SetReadingText(Windows::UI::Xaml::Controls::TextBlock^ textBlock, Windows::Devices::Sensors::AccelerometerReading^ reading)
00029 {
00030     textBlock->Text = "X: " + reading->AccelerationX.ToString() +
00031         ", Y: " + reading->AccelerationY.ToString() +
00032         ", Z: " + reading->AccelerationZ.ToString();
00033 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/Content/DDSTextureLoader.h Source File

  • HolographicTagAlong
  • cpp
  • Content

DDSTextureLoader.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.h
00003 //
00004 // Functions for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note these functions are useful as a light-weight runtime loader for DDS files. For
00007 // a full-featured DDS file reader, writer, and texture processing pipeline see
00008 // the 'Texconv' sample and the 'DirectXTex' library.
00009 //
00010 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00011 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00012 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00013 // PARTICULAR PURPOSE.
00014 //
00015 // Copyright (c) Microsoft Corporation. All rights reserved.
00016 //
00017 // http://go.microsoft.com/fwlink/?LinkId=248926
00018 // http://go.microsoft.com/fwlink/?LinkId=248929
00019 //--------------------------------------------------------------------------------------
00020
00021 #ifdef _MSC_VER
00022 #pragma once
00023 #endif
00024
00025 #if defined(_XBOX_ONE) && defined(_TITLE)
00026 #include <d3d11_x.h>
00027 #define DCOMMON_H_INCLUDED
00028 #define NO_D3D11_DEBUG_NAME
00029 #else
00030 #include <d3d11_1.h>
00031 #endif
00032
00033 #pragma warning(push)
00034 #pragma warning(disable : 4005)
00035 #include <stdint.h>
00036 #pragma warning(pop)
00037
00038 #if defined(_MSC_VER) && (_MSC_VER<1610) && !defined(_In_reads_)
00039 #define _In_reads_(exp)
00040 #define _Out_writes_(exp)
00041 #define _In_reads_bytes_(exp)
00042 #define _In_reads_opt_(exp)
00043 #define _Outptr_opt_
00044 #endif
00045
00046 #ifndef _Use_decl_annotations_
00047 #define _Use_decl_annotations_
00048 #endif
00049
00050 namespace DirectX
00051 {
00052     enum DDS_ALPHA_MODE
00053     {
00054         DDS_ALPHA_MODE_UNKNOWN       = 0,
00055         DDS_ALPHA_MODE_STRAIGHT      = 1,
00056         DDS_ALPHA_MODE_PREMULTIPLIED = 2,
00057         DDS_ALPHA_MODE_OPAQUE        = 3,
00058         DDS_ALPHA_MODE_CUSTOM        = 4,
00059     };
00060
00061     // Standard version
00062     HRESULT CreateDDSTextureFromMemory( _In_ ID3D11Device* d3dDevice,
00063                                         _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
00064                                         _In_ size_t ddsDataSize,
00065                                         _Outptr_opt_ ID3D11Resource** texture,
00066                                         _Outptr_opt_ ID3D11ShaderResourceView** textureView,
00067                                         _In_ size_t maxsize = 0,
00068                                         _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
00069                                       );
00070
00071     HRESULT CreateDDSTextureFromFile( _In_ ID3D11Device* d3dDevice,
00072                                       _In_z_ const wchar_t* szFileName,
00073                                       _Outptr_opt_ ID3D11Resource** texture,
00074                                       _Outptr_opt_ ID3D11ShaderResourceView** textureView,
00075                                       _In_ size_t maxsize = 0,
00076                                       _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
00077                                     );
00078
00079     // Standard version with optional auto-gen mipmap support
00080     HRESULT CreateDDSTextureFromMemory( _In_ ID3D11Device* d3dDevice,
00081                                         _In_opt_ ID3D11DeviceContext* d3dContext,
00082                                         _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
00083                                         _In_ size_t ddsDataSize,
00084                                         _Outptr_opt_ ID3D11Resource** texture,
00085                                         _Outptr_opt_ ID3D11ShaderResourceView** textureView,
00086                                         _In_ size_t maxsize = 0,
00087                                         _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
00088                                       );
00089
00090     HRESULT CreateDDSTextureFromFile( _In_ ID3D11Device* d3dDevice,
00091                                       _In_opt_ ID3D11DeviceContext* d3dContext,
00092                                       _In_z_ const wchar_t* szFileName,
00093                                       _Outptr_opt_ ID3D11Resource** texture,
00094                                       _Outptr_opt_ ID3D11ShaderResourceView** textureView,
00095                                       _In_ size_t maxsize = 0,
00096                                       _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
00097                                     );
00098
00099     // Extended version
00100     HRESULT CreateDDSTextureFromMemoryEx( _In_ ID3D11Device* d3dDevice,
00101                                           _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
00102                                           _In_ size_t ddsDataSize,
00103                                           _In_ size_t maxsize,
00104                                           _In_ D3D11_USAGE usage,
00105                                           _In_ unsigned int bindFlags,
00106                                           _In_ unsigned int cpuAccessFlags,
00107                                           _In_ unsigned int miscFlags,
00108                                           _In_ bool forceSRGB,
00109                                           _Outptr_opt_ ID3D11Resource** texture,
00110                                           _Outptr_opt_ ID3D11ShaderResourceView** textureView,
00111                                           _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
00112                                       );
00113
00114     HRESULT CreateDDSTextureFromFileEx( _In_ ID3D11Device* d3dDevice,
00115                                         _In_z_ const wchar_t* szFileName,
00116                                         _In_ size_t maxsize,
00117                                         _In_ D3D11_USAGE usage,
00118                                         _In_ unsigned int bindFlags,
00119                                         _In_ unsigned int cpuAccessFlags,
00120                                         _In_ unsigned int miscFlags,
00121                                         _In_ bool forceSRGB,
00122                                         _Outptr_opt_ ID3D11Resource** texture,
00123                                         _Outptr_opt_ ID3D11ShaderResourceView** textureView,
00124                                         _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
00125                                     );
00126
00127     // Extended version with optional auto-gen mipmap support
00128     HRESULT CreateDDSTextureFromMemoryEx( _In_ ID3D11Device* d3dDevice,
00129                                           _In_opt_ ID3D11DeviceContext* d3dContext,
00130                                           _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
00131                                           _In_ size_t ddsDataSize,
00132                                           _In_ size_t maxsize,
00133                                           _In_ D3D11_USAGE usage,
00134                                           _In_ unsigned int bindFlags,
00135                                           _In_ unsigned int cpuAccessFlags,
00136                                           _In_ unsigned int miscFlags,
00137                                           _In_ bool forceSRGB,
00138                                           _Outptr_opt_ ID3D11Resource** texture,
00139                                           _Outptr_opt_ ID3D11ShaderResourceView** textureView,
00140                                           _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
00141                                       );
00142
00143     HRESULT CreateDDSTextureFromFileEx( _In_ ID3D11Device* d3dDevice,
00144                                         _In_opt_ ID3D11DeviceContext* d3dContext,
00145                                         _In_z_ const wchar_t* szFileName,
00146                                         _In_ size_t maxsize,
00147                                         _In_ D3D11_USAGE usage,
00148                                         _In_ unsigned int bindFlags,
00149                                         _In_ unsigned int cpuAccessFlags,
00150                                         _In_ unsigned int miscFlags,
00151                                         _In_ bool forceSRGB,
00152                                         _Outptr_opt_ ID3D11Resource** texture,
00153                                         _Outptr_opt_ ID3D11ShaderResourceView** textureView,
00154                                         _Out_opt_ DDS_ALPHA_MODE* alphaMode = nullptr
00155                                     );
00156 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ConstantBufferChangesEveryFrame Member List

This is the complete list of members for ConstantBufferChangesEveryFrame, including all inherited members.
view ConstantBufferChangesEveryFrame
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RadioManager/cs/SampleConfiguration.cs Source File

  • RadioManager
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using SDKTemplate;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "RadioManager C# Sample";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Toggle Radios", ClassType=typeof(Scenario1_Toggle)}
00026         };
00027     }
00028
00029     public class Scenario
00030     {
00031         public string Title { get; set; }
00032         public Type ClassType { get; set; }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCloudFontIntegration/cpp/Scenario_Document3.xaml.h Source File

  • XamlCloudFontIntegration
  • cpp

Scenario_Document3.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario_Document3.g.h"
00015
00016 namespace SDKTemplate
00017 {
00018     [Windows::Foundation::Metadata::WebHostHidden]
00019     public ref class Scenario_Document3 sealed
00020     {
00021     public:
00022         Scenario_Document3();
00023     private:
00024         void Page_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00025     };
00026 }
Generated on Fri Nov 15 2024 22:19:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JapanesePhoneticAnalysis/cpp/SampleConfiguration.h Source File

  • JapanesePhoneticAnalysis
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Japanese phonetic analysis";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

OvenClient Member List

This is the complete list of members for OvenClient, including all inherited members.
BreadCompletedHandler1(Oven oven, Bread bread) | OvenClient | [inline, private]
BreadCompletedHandler1(Oven oven, Bread bread) | OvenClient | [inline, private]
BreadCompletedHandler2(Oven oven, Bread bread) | OvenClient | [inline, private]
BreadCompletedHandler2(Oven oven, Bread bread) | OvenClient | [inline, private]
BreadCompletedHandler3(Oven oven, Bread bread) | OvenClient | [inline, private]
BreadCompletedHandler3(Oven oven, Bread bread) | OvenClient | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | OvenClient | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | OvenClient | [inline, protected]
OvenClient() | OvenClient | [inline]
OvenClient() | OvenClient | [inline]
rootPage | OvenClient | [private]
Start_Click(object sender, RoutedEventArgs e) | OvenClient | [inline, private]
Start_Click(object sender, RoutedEventArgs e) | OvenClient | [inline, private]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RectRenderer Member List

This is the complete list of members for RectRenderer, including all inherited members.
brush | RectRenderer | [private]
CreateDeviceDependentResources() | RectRenderer |
deviceResources | RectRenderer | [private]
HitTest(Windows::Foundation::Point position) | RectRenderer |
rect | RectRenderer | [private]
RectRenderer(const std::shared_ptr< DX::DeviceResources > &deviceResources) | RectRenderer |
rectSize | RectRenderer | [private]
rectTransform | RectRenderer | [private]
ReleaseDeviceDependentResources() | RectRenderer |
Render() | RectRenderer |
ResetRect() | RectRenderer |
SetBrushColor(D2D1::ColorF newColor) | RectRenderer |
SetRectSize(float newSize) | RectRenderer |
UpdateRectTransform(Windows::Foundation::Point newPosition, Windows::UI::Input::ManipulationDelta newDelta) | RectRenderer |
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cpp/Scenario7_ListSmartCards.xaml.cpp Source File

  • SmartCard
  • cpp

Scenario7_ListSmartCards.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario7_ListSmartCards.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace concurrency;
00009 using namespace Platform;
00010 using namespace Platform::Collections;
00011 using namespace Windows::Devices;
00012 using namespace Windows::Devices::Enumeration;
00013 using namespace Windows::Devices::SmartCards;
00014 using namespace Windows::Foundation;
00015 using namespace Windows::Foundation::Collections;
00016 using namespace Windows::UI::Xaml;
00017 using namespace Windows::UI::Xaml::Controls;
00018
00019 Scenario7_ListSmartCards::Scenario7_ListSmartCards()
00020 {
00021     InitializeComponent();
00022 }
00023
00024 void Scenario7_ListSmartCards::ListSmartCards_Click(Object^ sender, RoutedEventArgs^ e)
00025 {
00026     Button^ b = safe_cast<Button^>(sender);
00027     b->IsEnabled = false;
00028
00029     // Create a Vector of managed pointers to SmartCardItems to display in our
00030     // list.  We can immediately assign ItemListView's source to be this new
00031     // Vector, as the ItemListView will subscribe to the Vector's VectorChanged
00032     // event and update itself when the vector changes.  This turns out to be
00033     // very convenient given the asynchronous operations we must use to list the
00034     // cards.
00035     smartCardItems = ref new Vector<SmartCardItem^>();
00036     ItemListView->ItemsSource = smartCardItems;
00037
00038     MainPage::Current->NotifyUser("Enumerating smart cards...", NotifyType::StatusMessage);
00039
00040     String^ selector = SmartCardReader::GetDeviceSelector();
00041     create_task(DeviceInformation::FindAllAsync(selector)).then(
00042         [this](DeviceInformationCollection^ devices)
00043     {
00044         std::vector<task<void>> deviceTasks;
00045
00046         // From DeviceInformationCollection::FindAllAsync, we start with a
00047         // DeviceInformationCollection which is essentially a vector of
00048         // DeviceInformation objects.  For each of these objects, we perform
00049         // the following steps.
00050         for (DeviceInformation^ info : devices)
00051         {
00052             // 1. Instantiate a SmartCardReader using
00053             //    SmartCardReader::FromIdAsync
00054             task<void> deviceTask = create_task(SmartCardReader::FromIdAsync(info->Id)).then(
00055                 [](SmartCardReader^ reader)
00056             {
00057                 // 2. Enumerate all the cards attached to that reader using
00058                 //    SmartCardReader::FindAllCardsAsync
00059                 return reader->FindAllCardsAsync();
00060             }).then(
00061                 [this](IVectorView<SmartCard^>^ cards)
00062             {
00063                 std::vector<task<void>> getNameTasks;
00064
00065                 for (SmartCard^ card : cards)
00066                 {
00067                     // 3. For each card, instantiate a SmartCardProvisioning
00068                     //    object using SmartCardProvisioning::FromSmartCardAsync
00069                     task<void> getNameTask = create_task(SmartCardProvisioning::FromSmartCardAsync(card)).then(
00070                         [this](SmartCardProvisioning^ provisioning)
00071                     {
00072                         // 4. Once we have a SmartCardProvisioningObject for
00073                         //    each card, we need to use it to get the name of
00074                         //    the card.  This is another asynchronous operation.
00075                         return create_task(provisioning->GetNameAsync()).then(
00076                             [=](task<String^> getNameTask)
00077                         {
00078                             String^ cardName = "";
00079                             try
00080                             {
00081                                 cardName = getNameTask.get();
00082                             }
00083                             catch (COMException^ ex)
00084                             {
00085                                 cardName = "Exception: " + ex->ToString();
00086                             }
00087
00088                             // 5. Finally, now that we have the card name and
00089                             //    a provisioning object which contains a chain
00090                             //    of references we can use to get the reader
00091                             //    name, we can create a new SmartCardItem and
00092                             //    add it to our list.  Recall that the list view
00093                             //    which is the graphical representation of this
00094                             //    list will be updated automatically.
00095                             SmartCardItem^ item = ref new SmartCardItem;
00096                             item->ReaderName = provisioning->SmartCard->Reader->Name;
00097                             item->CardName = cardName;
00098                             smartCardItems->InsertAt(0, item);
00099                         });
00100                     });
00101                     getNameTasks.push_back(getNameTask);
00102                 }
00103
00104                 return when_all(begin(getNameTasks), end(getNameTasks));
00105             });
00106             deviceTasks.push_back(deviceTask);
00107         }
00108         return when_all(begin(deviceTasks), end(deviceTasks));
00109     }).then(
00110         [b](task<void> checkExceptionTask)
00111     {
00112         try
00113         {
00114             checkExceptionTask.get();
00115             MainPage::Current->NotifyUser("Enumerating smart cards completed.", NotifyType::StatusMessage);
00116         }
00117         catch (COMException^ ex)
00118         {
00119             MainPage::Current->NotifyUser("Enumerating smart cards failed with exception: " + ex->ToString(), NotifyType::ErrorMessage);
00120         }
00121         b->IsEnabled = true;
00122     });
00123 }
Generated on Fri Nov 15 2024 22:21:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LightSensor/cs/Scenario2_Polling.xaml.cs Source File

  • LightSensor
  • cs

Scenario2_Polling.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using System;
00017 using Windows.Devices.Sensors;
00018 using Windows.Foundation;
00019 using System.Threading.Tasks;
00020 using Windows.UI.Core;
00021
00022 namespace LightSensorCS
00023 {
00024     public sealed partial class Scenario2_Polling : Page
00025     {
00026         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00027         // as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         private LightSensor _sensor;
00031         private uint _desiredReportInterval;
00032         private DispatcherTimer _dispatcherTimer;
00033
00034         public Scenario2_Polling()
00035         {
00036             this.InitializeComponent();
00037
00038             _sensor = LightSensor.GetDefault();
00039             if (_sensor != null)
00040             {
00041                 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00042                 // This value will be used later to activate the sensor.
00043                 uint minReportInterval = _sensor.MinimumReportInterval;
00044                 _desiredReportInterval = minReportInterval > 100 ? minReportInterval : 100;
00045
00046                 // Set up a DispatchTimer
00047                 _dispatcherTimer = new DispatcherTimer();
00048                 _dispatcherTimer.Tick += DisplayCurrentReading;
00049                 _dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, (int)_desiredReportInterval);
00050             }
00051             else
00052             {
00053                 rootPage.NotifyUser("No light sensor found", NotifyType.ErrorMessage);
00054             }
00055         }
00056
00057         /// <summary>
00058         /// Invoked when this page is about to be displayed in a Frame.
00059         /// </summary>
00060         /// <param name="e">Event data that describes how this page was reached. The Parameter
00061         /// property is typically used to configure the page.</param>
00062         protected override void OnNavigatedTo(NavigationEventArgs e)
00063         {
00064             ScenarioEnableButton.IsEnabled = true;
00065             ScenarioDisableButton.IsEnabled = false;
00066         }
00067
00068         /// <summary>
00069         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00070         /// </summary>
00071         /// <param name="e">
00072         /// Event data that can be examined by overriding code. The event data is representative
00073         /// of the navigation that will unload the current Page unless canceled. The
00074         /// navigation can potentially be canceled by setting Cancel.
00075         /// </param>
00076         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00077         {
00078             if (ScenarioDisableButton.IsEnabled)
00079             {
00080                 Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00081
00082                 // Stop the dispatcher
00083                 _dispatcherTimer.Stop();
00084
00085                 // Restore the default report interval to release resources while the sensor is not in use
00086                 _sensor.ReportInterval = 0;
00087             }
00088
00089             base.OnNavigatingFrom(e);
00090         }
00091
00092         /// <summary>
00093         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00094         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00095         /// </summary>
00096         /// <param name="sender"></param>
00097         /// <param name="e">
00098         /// Event data that can be examined for the current visibility state.
00099         /// </param>
00100         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00101         {
00102             if (ScenarioDisableButton.IsEnabled)
00103             {
00104                 if (e.Visible)
00105                 {
00106                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00107                     _dispatcherTimer.Start();
00108                 }
00109                 else
00110                 {
00111                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00112                     _dispatcherTimer.Stop();
00113                 }
00114             }
00115         }
00116
00117         /// <summary>
00118         /// This is the dispatcher callback.
00119         /// </summary>
00120         /// <param name="sender"></param>
00121         /// <param name="args"></param>
00122         private void DisplayCurrentReading(object sender, object args)
00123         {
00124             LightSensorReading reading = _sensor.GetCurrentReading();
00125             if (reading != null)
00126             {
00127                 ScenarioOutput_LUX.Text = String.Format("{0,5:0.00}", reading.IlluminanceInLux);
00128             }
00129         }
00130
00131         /// <summary>
00132         /// This is the click handler for the 'Enable' button.
00133         /// </summary>
00134         /// <param name="sender"></param>
00135         /// <param name="e"></param>
00136         private void ScenarioEnable(object sender, RoutedEventArgs e)
00137         {
00138             if (_sensor != null)
00139             {
00140                 // Set the report interval to enable the sensor for polling
00141                 _sensor.ReportInterval = _desiredReportInterval;
00142
00143                 Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged);
00144                 _dispatcherTimer.Start();
00145
00146                 ScenarioEnableButton.IsEnabled = false;
00147                 ScenarioDisableButton.IsEnabled = true;
00148             }
00149             else
00150             {
00151                 rootPage.NotifyUser("No light sensor found", NotifyType.ErrorMessage);
00152             }
00153         }
00154
00155         /// <summary>
00156         /// This is the click handler for the 'Disable' button.
00157         /// </summary>
00158         /// <param name="sender"></param>
00159         /// <param name="e"></param>
00160         private void ScenarioDisable(object sender, RoutedEventArgs e)
00161         {
00162             Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00163
00164             // Stop the dispatcher
00165             _dispatcherTimer.Stop();
00166
00167             // Restore the default report interval to release resources while the sensor is not in use
00168             _sensor.ReportInterval = 0;
00169
00170             ScenarioEnableButton.IsEnabled = true;
00171             ScenarioDisableButton.IsEnabled = false;
00172         }
00173     }
00174 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/Scenario9.cpp Source File

  • FileAccess
  • cppwinrt

Scenario9.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario9.h"
00014 #include "Scenario9.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Storage;
00020 using namespace Windows::Storage::Pickers;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Navigation;
00023
00024 namespace winrt::SDKTemplate::implementation
00025 {
00026     Scenario9::Scenario9()
00027     {
00028         InitializeComponent();
00029     }
00030
00031     void Scenario9::OnNavigatedTo(NavigationEventArgs const&)
00032     {
00033         SampleState::ValidateFile();
00034     }
00035
00036     fire_and_forget Scenario9::CompareFilesButton_Click(IInspectable const&, RoutedEventArgs const&)
00037     {
00038         auto lifetime = get_strong();
00039
00040         StorageFile file = SampleState::SampleFile();
00041         if (file != nullptr)
00042         {
00043             FileOpenPicker picker;
00044             picker.SuggestedStartLocation(PickerLocationId::PicturesLibrary);
00045             picker.FileTypeFilter().Append(L"*");
00046             StorageFile comparand = co_await picker.PickSingleFileAsync();
00047             if (comparand != nullptr)
00048             {
00049                 try
00050                 {
00051                     if (file.IsEqual(comparand))
00052                     {
00053                         rootPage.NotifyUser(L"Files are equal.", NotifyType::StatusMessage);
00054                     }
00055                     else
00056                     {
00057                         rootPage.NotifyUser(L"Files are not equal.", NotifyType::StatusMessage);
00058                     }
00059                 }
00060                 catch (const hresult_error& ex)
00061                 {
00062                     // I/O errors are reported as exceptions.
00063                     rootPage.NotifyUser(L"Error comparing files: " + ex.message(), NotifyType::ErrorMessage);
00064                 }
00065             }
00066             else
00067             {
00068                 rootPage.NotifyUser(L"Operation cancelled", NotifyType::StatusMessage);
00069             }
00070         }
00071         else
00072         {
00073             SampleState::NotifyUserFileNotExist();
00074         }
00075     }
00076 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AppException Member List

This is the complete list of members for AppException, including all inherited members.
AppException() | AppException | [inline]
AppException(string message) | AppException | [inline]
Generated on Fri Nov 15 2024 22:23:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PlayPauseButton Member List

This is the complete list of members for PlayPauseButton, including all inherited members.
AddChildElement(const std::shared_ptr< BaseElement > &childElement) | BaseElement |
ArrangeElements() override | Button | [virtual]
BaseElement() | BaseElement |
Button(UINT initialSize=BUTTON_SIZE, ButtonShape shape=ButtonShape::Rectangle) | Button |
FocusableElement() | FocusableElement |
FocusUpdate() override | Button | [virtual]
GetElementMargin() | BaseElement | [inline]
GetElementSize() | BaseElement | [inline]
GetIgnoreLayout() | BaseElement | [inline]
GetIsRenderPassNeeded() | BaseElement | [inline]
GetIsVisible() | BaseElement | [inline]
Initialize() override | PlayPauseButton | [virtual]
IsFocused() | FocusableElement | [inline, virtual]
m_brush | Button | [protected]
m_buttonState | Button | [protected]
m_deviceResources | BaseElement | [protected]
m_elementCoordIntersectionPoint | FocusableElement | [protected]
m_elementMargin | BaseElement | [protected]
m_elementSize | BaseElement | [protected]
m_forceIconCentered | Button | [protected]
m_ignoreLayout | BaseElement | [protected]
m_isFocused | FocusableElement | [protected]
m_isFocusIntersectionCalculated | FocusableElement | [protected]
m_isInitialized | BaseElement | [protected]
m_isLayoutHorizontal | BaseElement | [protected]
m_isParentFocused | FocusableElement | [protected]
m_isRenderPassNeeded | BaseElement | [protected]
m_isVisible | BaseElement | [protected]
m_maxSecondsInPressingState | Button | [protected]
m_parentControlTransform | Button | [protected]
m_parentFocusedPosition | FocusableElement | [protected]
m_parentTextureHeight | FocusableElement | [protected]
m_parentTextureWidth | FocusableElement | [protected]
m_parentTranslation | BaseElement | [protected]
m_pauseText | PlayPauseButton | [private]
m_playText | PlayPauseButton | [private]
m_pressingTimeOut | Button | [protected]
m_shape | Button | [protected]
m_transformedTranslation | BaseElement | [protected]
m_transformMatrix | BaseElement | [protected]
m_transformRecalculationNeeded | BaseElement | [protected]
m_translation | BaseElement | [protected]
PerformAction() override | PlayPauseButton | [virtual]
PlayPauseButton(UINT buttonSize, UINT iconSize) | PlayPauseButton |
Render() | BaseElement | [protected, virtual]
SetBrush(ID2D1SolidColorBrush *brush) | BaseElement |
SetElementMargin(ElementMargin margin) | BaseElement | [inline]
SetElementSize(Windows::Foundation::Numerics::float2 size) | BaseElement | [inline]
SetIgnoreLayout(bool ignoreLayout) | BaseElement | [inline]
SetIsVisible(bool visible) | BaseElement |
SetLayoutHorizontal(bool isLayoutHorizontal) | BaseElement | [inline]
SetParentControlInformation(bool focused, Windows::Foundation::Numerics::float2 focusedPosition, UINT parentTextureWidth, UINT parentTextureHeight) | FocusableElement | [virtual]
SetParentTransform(Windows::Foundation::Numerics::float2 translation) | BaseElement |
SetTranslation(Windows::Foundation::Numerics::float2 translation) | BaseElement | [virtual]
TryRender() | BaseElement |
Update(const DX::StepTimer &timer, Windows::UI::Input::Spatial::SpatialPointerPose^cameraPose) override | PlayPauseButton | [virtual]
~BaseElement() | BaseElement | [virtual]
~FocusableElement() | FocusableElement | [virtual]
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CashDrawer/cs/Scenario1_OpenDrawer.xaml.cs Source File

  • CashDrawer
  • cs

Scenario1_OpenDrawer.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Devices.PointOfService;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026     public sealed partial class Scenario1_OpenDrawer : Page
00027     {
00028         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00029         // as NotifyUser()
00030         MainPage rootPage = MainPage.Current;
00031
00032         CashDrawer drawer = null;
00033         ClaimedCashDrawer claimedDrawer = null;
00034
00035
00036         public Scenario1_OpenDrawer()
00037         {
00038             this.InitializeComponent();
00039         }
00040
00041         /// <summary>
00042         /// Invoked when this page is about to be displayed in a Frame.
00043         /// </summary>
00044         /// <param name="e">Event data that describes how this page was reached.</param>
00045         protected override void OnNavigatedTo(NavigationEventArgs e)
00046         {
00047             ResetScenarioState();
00048             base.OnNavigatedTo(e);
00049         }
00050
00051         /// <summary>
00052         /// Invoked before the page is unloaded and is no longer the current source of a Frame.
00053         /// </summary>
00054         /// <param name="e">Event data describing the navigation that was requested.</param>
00055         protected override void OnNavigatedFrom(NavigationEventArgs e)
00056         {
00057             ResetScenarioState();
00058             base.OnNavigatedFrom(e);
00059         }
00060
00061         /// <summary>
00062         /// Event handler for Initialize Drawer button.
00063         /// Claims and enables the default cash drawer.
00064         /// </summary>
00065         /// <param name="sender">Button that was clicked.</param>
00066         /// <param name="e">Event data associated with click event.</param>
00067         private async void InitDrawerButton_Click(object sender, RoutedEventArgs e)
00068         {
00069             if (await CreateDefaultCashDrawerObject())
00070             {
00071                 if (await ClaimCashDrawer())
00072                 {
00073                     if (await EnableCashDrawer())
00074                     {
00075                         InitDrawerButton.IsEnabled = false;
00076                         OpenDrawerButton.IsEnabled = true;
00077
00078                         rootPage.NotifyUser("Successfully enabled cash drawer. Device ID: " + claimedDrawer.DeviceId, NotifyType.StatusMessage);
00079                     }
00080                     else
00081                     {
00082                         rootPage.NotifyUser("Failed to enable cash drawer.", NotifyType.ErrorMessage);
00083                     }
00084                 }
00085                 else
00086                 {
00087                     rootPage.NotifyUser("Failed to claim cash drawer.", NotifyType.ErrorMessage);
00088                 }
00089             }
00090             else
00091             {
00092                 rootPage.NotifyUser("Cash drawer not found. Please connect a cash drawer.", NotifyType.ErrorMessage);
00093             }
00094         }
00095
00096         /// <summary>
00097         /// Open the cash drawer.
00098         /// </summary>
00099         /// <param name="sender">Button that was clicked.</param>
00100         /// <param name="e">Event data associated with click event.</param>
00101         private async void OpenDrawerButton_Click(object sender, RoutedEventArgs e)
00102         {
00103             if (await OpenCashDrawer())
00104                 rootPage.NotifyUser("Cash drawer open succeeded.", NotifyType.StatusMessage);
00105             else
00106                 rootPage.NotifyUser("Cash drawer open failed.", NotifyType.ErrorMessage);
00107         }
00108
00109         /// <summary>
00110         /// Creates the default cash drawer.
00111         /// </summary>
00112         /// <returns>True if the cash drawer was created, false otherwise.</returns>
00113         private async Task<bool> CreateDefaultCashDrawerObject()
00114         {
00115             rootPage.NotifyUser("Creating cash drawer object.", NotifyType.StatusMessage);
00116
00117             if (drawer == null)
00118             {
00119                 drawer = await DeviceHelpers.GetFirstCashDrawerAsync();
00120                 if (drawer == null)
00121                     return false;
00122             }
00123
00124             return true;
00125         }
00126
00127         /// <summary>
00128         /// Attempt to claim the connected cash drawer.
00129         /// </summary>
00130         /// <returns>True if the cash drawer was successfully claimed, false otherwise.</returns>
00131         private async Task<bool> ClaimCashDrawer()
00132         {
00133             if (drawer == null)
00134                 return false;
00135
00136             if (claimedDrawer == null)
00137             {
00138                 claimedDrawer = await drawer.ClaimDrawerAsync();
00139                 if (claimedDrawer == null)
00140                     return false;
00141             }
00142
00143             return true;
00144         }
00145
00146         /// <summary>
00147         /// Attempt to enabled the claimed cash drawer.
00148         /// </summary>
00149         /// <returns>True if the cash drawer was successfully enabled, false otherwise.</returns>
00150         private async Task<bool> EnableCashDrawer()
00151         {
00152             if (claimedDrawer == null)
00153                 return false;
00154
00155             if (claimedDrawer.IsEnabled)
00156                 return true;
00157
00158             return await claimedDrawer.EnableAsync();
00159         }
00160
00161         /// <summary>
00162         /// Attempt to open the claimed cash drawer.
00163         /// </summary>
00164         /// <returns>True if the cash drawer was successfully opened, false otherwise.</returns>
00165         private async Task<bool> OpenCashDrawer()
00166         {
00167             if (claimedDrawer == null || !claimedDrawer.IsEnabled)
00168                 return false;
00169
00170             return await claimedDrawer.OpenDrawerAsync();
00171         }
00172
00173         /// <summary>
00174         /// Reset the scenario to its initial state.
00175         /// </summary>
00176         private void ResetScenarioState()
00177         {
00178             if (claimedDrawer != null)
00179             {
00180                 claimedDrawer.Dispose();
00181                 claimedDrawer = null;
00182             }
00183
00184             if (drawer != null)
00185             {
00186                 drawer.Dispose();
00187                 drawer = null;
00188             }
00189
00190             InitDrawerButton.IsEnabled = true;
00191             OpenDrawerButton.IsEnabled = false;
00192
00193             rootPage.NotifyUser("Click the init drawer button to begin.", NotifyType.StatusMessage);
00194         }
00195     }
00196 }
Generated on Fri Nov 15 2024 22:18:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cpp/cpp/Scenario2_OvenClientWRL.xaml.h Source File

  • ProxyStubsForWinRTComponents
  • cpp
  • cpp

Scenario2_OvenClientWRL.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008 #include "Scenario2_OvenClientWRL.g.h"
00009
00010 namespace SDKSample
00011 {
00012     namespace ProxyStubsForWinRTComponents
00013     {
00014         public ref class OvenClientWRL sealed
00015         {
00016         public:
00017             OvenClientWRL();
00018
00019         private:
00020             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021         };
00022     }
00023 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ReadBinary Member List

This is the complete list of members for ReadBinary, including all inherited members.
Address | ReadBinary |
ApduCommand(byte cla, byte ins, byte p1, byte p2, byte[] commandData, byte?le) | ApduCommand | [inline]
ApduResponseType | ApduCommand |
CLA | ApduCommand |
CommandData | ApduCommand |
GetBuffer() | ApduCommand | [inline]
INS | ApduCommand |
Le | ApduCommand |
P1 | ApduCommand |
P2 | ApduCommand |
ReadBinary(ushort address, byte?expectedReturnBytes) | ReadBinary | [inline]
ToString() | ApduCommand | [inline]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cs/Scenario2_MultipleScanners.xaml.cs Source File

  • BarcodeScanner
  • cs

Scenario2_MultipleScanners.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Devices.PointOfService;
00015 using Windows.UI;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Media;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class Scenario2_MultipleScanners : Page
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         MainPage rootPage = MainPage.Current;
00033
00034         BarcodeScanner barcodeScannerInstance1 = null;
00035         BarcodeScanner barcodeScannerInstance2 = null;
00036         ClaimedBarcodeScanner claimedBarcodeScannerInstance1 = null;
00037         ClaimedBarcodeScanner claimedBarcodeScannerInstance2 = null;
00038
00039
00040         public Scenario2_MultipleScanners()
00041         {
00042             this.InitializeComponent();
00043         }
00044
00045         /// <summary>
00046         /// Enumerator for current active Instance.
00047         /// </summary>
00048         private enum BarcodeScannerInstance
00049         {
00050             Instance1,
00051             Instance2
00052         }
00053
00054         /// <summary>
00055         /// Invoked when this page is about to be displayed in a Frame.
00056         /// </summary>
00057         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00058         /// property is typically used to configure the page.</param>
00059         protected override void OnNavigatedTo(NavigationEventArgs e)
00060         {
00061             ResetTheScenarioState();
00062             base.OnNavigatedTo(e);
00063         }
00064
00065         /// <summary>
00066         /// Invoked when this page is no longer displayed.
00067         /// </summary>
00068         /// <param name="e">Event data that describes how this page was exited.  The Parameter
00069         /// property is typically used to configure the page.</param>
00070         protected override void OnNavigatedFrom(NavigationEventArgs e)
00071         {
00072             ResetTheScenarioState();
00073             base.OnNavigatedFrom(e);
00074         }
00075
00076         /// <summary>
00077         /// This is the click handler for the 'ScenarioStartScanningInstance1' button. It initiates creation of scanner instance 1.
00078         /// </summary>
00079         /// <param name="sender"></param>
00080         /// <param name="e"></param>
00081         private async void ButtonStartScanningInstance1_Click(object sender, RoutedEventArgs e)
00082         {
00083             //Get the handle to the default scanner
00084             if (await CreateDefaultScannerObjectAsync(BarcodeScannerInstance.Instance1))
00085             {
00086                 //Claim the scanner
00087                 if (await ClaimBarcodeScannerAsync(BarcodeScannerInstance.Instance1))
00088                 {
00089                     //add the event handlers
00090                     claimedBarcodeScannerInstance1.ReleaseDeviceRequested += claimedBarcodeScannerInstance1_ReleaseDeviceRequested;
00091                     claimedBarcodeScannerInstance1.DataReceived += claimedBarcodeScannerInstance1_DataReceived;
00092                     claimedBarcodeScannerInstance1.IsDecodeDataEnabled = true;
00093
00094                     //Enable the Scanner
00095                     if (await EnableBarcodeScannerAsync(BarcodeScannerInstance.Instance1))
00096                     {
00097                         //Set the UI state
00098                         ResetUI();
00099                         SetUI(BarcodeScannerInstance.Instance1);
00100                     }
00101                 }
00102                 else
00103                 {
00104                     if (barcodeScannerInstance1 != null)
00105                     {
00106                         barcodeScannerInstance1.Dispose();
00107                         barcodeScannerInstance1 = null;
00108                     }
00109                 }
00110             }
00111         }
00112
00113         /// <summary>
00114         /// This method is called upon when a claim request is made on instance 1. If a retain request was placed on the device it rejects the new claim.
00115         /// </summary>
00116         /// <param name="instance"></param>
00117         /// <returns></returns>
00118         async void claimedBarcodeScannerInstance1_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e)
00119         {
00120             await Dispatcher.RunAsync(
00121                 Windows.UI.Core.CoreDispatcherPriority.Normal,
00122                 () =>
00123                 {
00124                     //check if the instance wants to retain the device
00125                     if (Retain1.IsChecked == true)
00126                     {
00127                         try
00128                         {
00129                             //Retain the device
00130                             claimedBarcodeScannerInstance1.RetainDevice();
00131                         }
00132                         catch (Exception exception)
00133                         {
00134                             rootPage.NotifyUser("Retain instance 1 failed: " + exception.Message, NotifyType.ErrorMessage);
00135                         }
00136                     }
00137                     //Release the device
00138                     else
00139                     {
00140                         claimedBarcodeScannerInstance1.Dispose();
00141                         claimedBarcodeScannerInstance1 = null;
00142
00143                         if (barcodeScannerInstance1 != null)
00144                         {
00145                             barcodeScannerInstance1.Dispose();
00146                             barcodeScannerInstance1 = null;
00147                         }
00148                     }
00149                 }
00150             );
00151         }
00152
00153
00154         /// <summary>
00155         /// This is the click handler for the 'ScenarioStartScanningInstance2' button. Initiates creation of scanner instance 2
00156         /// </summary>
00157         /// <param name="sender"></param>
00158         /// <param name="e"></param>
00159         private async void ButtonStartScanningInstance2_Click(object sender, RoutedEventArgs e)
00160         {
00161             //Get the handle to the default scanner
00162             if (await CreateDefaultScannerObjectAsync(BarcodeScannerInstance.Instance2))
00163             {
00164                 //Claim the scanner
00165                 if (await ClaimBarcodeScannerAsync(BarcodeScannerInstance.Instance2))
00166                 {
00167                     //set the handlers
00168                     claimedBarcodeScannerInstance2.ReleaseDeviceRequested += claimedBarcodeScannerInstance2_ReleaseDeviceRequested;
00169                     claimedBarcodeScannerInstance2.DataReceived += claimedBarcodeScannerInstance2_DataReceived;
00170
00171                     //enable the scanner to decode the scanned data
00172                     claimedBarcodeScannerInstance2.IsDecodeDataEnabled = true;
00173
00174                     //Enable the Scanner
00175                     if (await EnableBarcodeScannerAsync(BarcodeScannerInstance.Instance2))
00176                     {
00177                         //Set the UI state
00178                         ResetUI();
00179                         SetUI(BarcodeScannerInstance.Instance2);
00180                     }
00181                 }
00182                 else
00183                 {
00184                     if (barcodeScannerInstance2 != null)
00185                     {
00186                         barcodeScannerInstance2.Dispose();
00187                         barcodeScannerInstance2 = null;
00188                     }
00189                 }
00190             }
00191         }
00192
00193         /// <summary>
00194         /// This method is called upon when a claim request is made on instance 2. If a retain request was placed on the device it rejects the new claim.
00195         /// </summary>
00196         /// <param name="instance"></param>
00197         /// <returns></returns>
00198         async void claimedBarcodeScannerInstance2_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e)
00199         {
00200             await Dispatcher.RunAsync(
00201                 Windows.UI.Core.CoreDispatcherPriority.Normal,
00202                 () =>
00203                 {
00204                     //check if the instance wants to retain the device
00205                     if (Retain2.IsChecked == true)
00206                     {
00207                         try
00208                         {
00209                             //Retain the device
00210                             claimedBarcodeScannerInstance2.RetainDevice();
00211                         }
00212                         catch (Exception exception)
00213                         {
00214                             rootPage.NotifyUser("Retain instance 2 failed: " + exception.Message, NotifyType.ErrorMessage);
00215                         }
00216                     }
00217                     //Release the device
00218                     else
00219                     {
00220                         claimedBarcodeScannerInstance2.Dispose();
00221                         claimedBarcodeScannerInstance2 = null;
00222
00223                         if (barcodeScannerInstance2 != null)
00224                         {
00225                             barcodeScannerInstance2.Dispose();
00226                             barcodeScannerInstance2 = null;
00227                         }
00228                     }
00229
00230                 }
00231             );
00232         }
00233
00234         /// <summary>
00235         /// This is the click handler for the 'ScenarioEndScanningInstance1' button.
00236         /// Initiates the disposal of scanner instance 1.
00237         /// </summary>
00238         /// <param name="sender"></param>
00239         /// <param name="e"></param>
00240         private void ButtonEndScanningInstance1_Click(object sender, RoutedEventArgs e)
00241         {
00242             if (claimedBarcodeScannerInstance1 != null)
00243             {
00244                 //remove the event handlers
00245                 claimedBarcodeScannerInstance1.DataReceived -= claimedBarcodeScannerInstance1_DataReceived;
00246                 claimedBarcodeScannerInstance1.ReleaseDeviceRequested -= claimedBarcodeScannerInstance1_ReleaseDeviceRequested;
00247
00248                 //dispose the instance
00249                 claimedBarcodeScannerInstance1.Dispose();
00250                 claimedBarcodeScannerInstance1 = null;
00251             }
00252
00253             if (barcodeScannerInstance1 != null)
00254             {
00255                 barcodeScannerInstance1.Dispose();
00256                 barcodeScannerInstance1 = null;
00257             }
00258
00259             //reset the UI
00260
00261             ResetUI();
00262
00263             rootPage.NotifyUser("Click a start scanning button to begin.", NotifyType.StatusMessage);
00264         }
00265
00266         /// <summary>
00267         /// This is the click handler for the 'ScenarioEndScanningInstance2' button.
00268         /// Initiates the disposal fo scanner instance 2.
00269         /// </summary>
00270         /// <param name="sender"></param>
00271         /// <param name="e"></param>
00272         private void ButtonEndScanningInstance2_Click(object sender, RoutedEventArgs e)
00273         {
00274             if (claimedBarcodeScannerInstance2 != null)
00275             {
00276                 //remove the event handlers
00277                 claimedBarcodeScannerInstance2.DataReceived -= claimedBarcodeScannerInstance2_DataReceived;
00278                 claimedBarcodeScannerInstance2.ReleaseDeviceRequested -= claimedBarcodeScannerInstance2_ReleaseDeviceRequested;
00279
00280                 //dispose the instance
00281                 claimedBarcodeScannerInstance2.Dispose();
00282                 claimedBarcodeScannerInstance2 = null;
00283             }
00284
00285             if (barcodeScannerInstance2 != null)
00286             {
00287                 barcodeScannerInstance2.Dispose();
00288                 barcodeScannerInstance2 = null;
00289             }
00290
00291             //reset the UI
00292             ResetUI();
00293
00294             rootPage.NotifyUser("Click a start scanning button to begin.", NotifyType.StatusMessage);
00295         }
00296
00297         /// <summary>
00298         /// This method returns the first available Barcode Scanner. To enumerate and find a particular device use the device enumeration code.
00299         /// </summary>
00300         /// <returns>a boolean value based on whether it found a compatible scanner connected</returns>
00301         private async Task<bool> CreateDefaultScannerObjectAsync(BarcodeScannerInstance instance)
00302         {
00303             BarcodeScanner scanner = null;
00304             scanner = await DeviceHelpers.GetFirstBarcodeScannerAsync();
00305
00306             if (scanner == null)
00307             {
00308                 rootPage.NotifyUser("Barcode scanner not found. Please connect a barcode scanner.", NotifyType.ErrorMessage);
00309                 return false;
00310             }
00311
00312             switch (instance)
00313             {
00314                 case BarcodeScannerInstance.Instance1:
00315                     barcodeScannerInstance1 = scanner;
00316                     break;
00317                 case BarcodeScannerInstance.Instance2:
00318                     barcodeScannerInstance2 = scanner;
00319                     break;
00320                 default:
00321                     return false;
00322             }
00323
00324             return true;
00325         }
00326
00327         /// <summary>
00328         /// This method claims the connected scanner.
00329         /// </summary>
00330         /// <returns>a boolean based on whether it was able to claim the scanner.</returns>
00331         private async Task<bool> ClaimBarcodeScannerAsync(BarcodeScannerInstance instance)
00332         {
00333             bool bClaimAsyncStatus = false;
00334             //select the instance to claim
00335             switch (instance)
00336             {
00337                 case BarcodeScannerInstance.Instance1:
00338
00339                     claimedBarcodeScannerInstance1 = await barcodeScannerInstance1.ClaimScannerAsync();
00340                     if (claimedBarcodeScannerInstance1 == null)
00341                         rootPage.NotifyUser("Instance 1 claim barcode scanner failed.", NotifyType.ErrorMessage);
00342                     else
00343                         bClaimAsyncStatus = true;
00344                     break;
00345
00346                 case BarcodeScannerInstance.Instance2:
00347
00348                     claimedBarcodeScannerInstance2 = await barcodeScannerInstance2.ClaimScannerAsync();
00349                     if (claimedBarcodeScannerInstance2 == null)
00350                         rootPage.NotifyUser("Instance 2 claim barcode scanner failed.", NotifyType.ErrorMessage);
00351                     else
00352                         bClaimAsyncStatus = true;
00353                     break;
00354
00355                 default:
00356                     return bClaimAsyncStatus;
00357             }
00358             return bClaimAsyncStatus;
00359         }
00360
00361         /// <summary>
00362         /// This method enables the connected scanner.
00363         /// </summary>
00364         /// <returns>a boolean based on whether it was able to enable the scanner.</returns>
00365         private async Task<bool> EnableBarcodeScannerAsync(BarcodeScannerInstance instance)
00366         {
00367             switch (instance)
00368             {
00369                 case BarcodeScannerInstance.Instance1:
00370                     await claimedBarcodeScannerInstance1.EnableAsync();
00371                     rootPage.NotifyUser("Instance 1 ready to scan. Device ID: " + claimedBarcodeScannerInstance1.DeviceId, NotifyType.StatusMessage);
00372                     break;
00373                 case BarcodeScannerInstance.Instance2:
00374                     await claimedBarcodeScannerInstance2.EnableAsync();
00375                     rootPage.NotifyUser("Instance 2 ready to scan. Device ID: " + claimedBarcodeScannerInstance2.DeviceId, NotifyType.StatusMessage);
00376                     break;
00377                 default:
00378                     return false;
00379             }
00380             return true;
00381         }
00382
00383         /// <summary>
00384         /// Reset the Scenario state
00385         /// </summary>
00386         private void ResetTheScenarioState()
00387         {
00388             if (claimedBarcodeScannerInstance1 != null)
00389             {
00390                 claimedBarcodeScannerInstance1.Dispose();
00391                 claimedBarcodeScannerInstance1 = null;
00392             }
00393
00394             if (barcodeScannerInstance1 != null)
00395             {
00396                 barcodeScannerInstance1.Dispose();
00397                 barcodeScannerInstance1 = null;
00398             }
00399
00400             if (claimedBarcodeScannerInstance2 != null)
00401             {
00402                 claimedBarcodeScannerInstance2.Dispose();
00403                 claimedBarcodeScannerInstance2 = null;
00404             }
00405
00406             if (barcodeScannerInstance2 != null)
00407             {
00408                 barcodeScannerInstance2.Dispose();
00409                 barcodeScannerInstance2 = null;
00410             }
00411
00412             ResetUI();
00413         }
00414
00415         /// <summary>
00416         /// Resets the display Elements to original state
00417         /// </summary>
00418         private void ResetUI()
00419         {
00420             Instance1Border.BorderBrush = new SolidColorBrush(Colors.Gray);
00421             Instance2Border.BorderBrush = new SolidColorBrush(Colors.Gray);
00422
00423             ScanDataType1.Text = String.Format("No data");
00424             ScanData1.Text = String.Format("No data");
00425             DataLabel1.Text = String.Format("No data");
00426             ScanDataType2.Text = String.Format("No data");
00427             ScanData2.Text = String.Format("No data");
00428             DataLabel2.Text = String.Format("No data");
00429
00430             ScenarioStartScanningInstance1.IsEnabled = true;
00431             ScenarioStartScanningInstance2.IsEnabled = true;
00432             ScenarioEndScanningInstance1.IsEnabled = false;
00433             ScenarioEndScanningInstance2.IsEnabled = false;
00434         }
00435
00436         /// <summary>
00437         /// Sets the UI elements to a state corresponding to the current active Instance.
00438         /// </summary>
00439         /// <param name="instance">Corresponds to the current active instance</param>
00440         private void SetUI(BarcodeScannerInstance instance)
00441         {
00442             Instance1Border.BorderBrush = new SolidColorBrush(Colors.Gray);
00443             Instance2Border.BorderBrush = new SolidColorBrush(Colors.Gray);
00444
00445             switch (instance)
00446             {
00447                 case BarcodeScannerInstance.Instance1:
00448                     ScenarioStartScanningInstance1.IsEnabled = false;
00449                     ScenarioStartScanningInstance2.IsEnabled = true;
00450                     ScenarioEndScanningInstance1.IsEnabled = true;
00451                     ScenarioEndScanningInstance2.IsEnabled = false;
00452                     Instance1Border.BorderBrush = new SolidColorBrush(Colors.DarkBlue);
00453                     break;
00454
00455                 case BarcodeScannerInstance.Instance2:
00456                     ScenarioStartScanningInstance1.IsEnabled = true;
00457                     ScenarioStartScanningInstance2.IsEnabled = false;
00458                     ScenarioEndScanningInstance1.IsEnabled = false;
00459                     ScenarioEndScanningInstance2.IsEnabled = true;
00460                     Instance2Border.BorderBrush = new SolidColorBrush(Colors.DarkBlue);
00461                     break;
00462             }
00463         }
00464
00465         /// <summary>
00466         /// This is an event handler for the claimed scanner Instance 1 when it scans and recieves data
00467         /// </summary>
00468         /// <param name="sender"></param>
00469         /// <param name="args"></param>
00470         private async void claimedBarcodeScannerInstance1_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
00471         {
00472             await MainPage.Current.Dispatcher.RunAsync(
00473                 Windows.UI.Core.CoreDispatcherPriority.Normal,
00474                 () =>
00475                 {
00476                     ScanDataType1.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType);
00477                     DataLabel1.Text = DataHelpers.GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType);
00478                     ScanData1.Text = DataHelpers.GetDataString(args.Report.ScanData);
00479
00480                     rootPage.NotifyUser("Instance 1 received data from the barcode scanner.", NotifyType.StatusMessage);
00481                 }
00482             );
00483         }
00484
00485         /// <summary>
00486         /// This is an event handler for the claimed scanner Instance 2 when it scans and recieves data
00487         /// </summary>
00488         /// <param name="sender"></param>
00489         /// <param name="args"></param>
00490         private async void claimedBarcodeScannerInstance2_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
00491         {
00492             await MainPage.Current.Dispatcher.RunAsync(
00493                 Windows.UI.Core.CoreDispatcherPriority.Normal,
00494                 () =>
00495                 {
00496                     ScanDataType2.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType);
00497                     DataLabel2.Text = DataHelpers.GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType);
00498                     ScanData2.Text = DataHelpers.GetDataString(args.Report.ScanData);
00499
00500                     rootPage.NotifyUser("Instance 2 received data from the barcode scanner.", NotifyType.StatusMessage);
00501                 }
00502             );
00503         }
00504     }
00505
00506 }
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/PixelShader/CustomPixelShaderRenderer.h Source File

  • D2DCustomEffects
  • cpp
  • PixelShader

CustomPixelShaderRenderer.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "DeviceResources.h"
00015 #include "BasicTimer.h"
00016 #include "RippleEffect.h"
00017
00018 namespace CustomPixelShader
00019 {
00020     // This sample renderer instantiates a basic rendering pipeline.
00021     class CustomPixelShaderRenderer
00022     {
00023     public:
00024         CustomPixelShaderRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00025         void CreateDeviceIndependentResources();
00026         void CreateDeviceDependentResources();
00027         void CreateWindowSizeDependentResources();
00028         void ReleaseDeviceDependentResources();
00029         void UpdatePointer(_In_ Windows::UI::Core::PointerEventArgs^ args);
00030         void Update();
00031         void Render();
00032
00033         // Process lifetime management handlers.
00034         void SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state) {};
00035         void LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state) {};
00036
00037     private:
00038         void UpdateImageScale(float scale);
00039
00040     private:
00041         // Cached pointer to device resources.
00042         std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00043         Microsoft::WRL::ComPtr<IWICFormatConverter>         m_formatConvert;
00044         Microsoft::WRL::ComPtr<ID2D1ImageSourceFromWic>     m_imageSource;
00045         Microsoft::WRL::ComPtr<ID2D1TransformedImageSource> m_transformedImage;
00046         Microsoft::WRL::ComPtr<ID2D1Effect>                 m_rippleEffect;
00047
00048         bool                                                m_isWindowClosed;
00049         bool                                                m_isRippleAnimating;
00050         D2D1_SIZE_U                                         m_imageSize;
00051         float                                               m_scale;
00052
00053         BasicTimer^                                         m_timer;
00054     };
00055 }
00056
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/xBindSampleModel/Manager.cs Source File

  • XamlBind
  • cs
  • xBindSampleModel

Manager.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using Windows.UI.Xaml.Data;
00005 using System.ComponentModel;
00006 using System.Runtime.CompilerServices;
00007 using System.Collections.ObjectModel;
00008
00009 using Windows.Foundation.Collections;
00010 using System.Collections;
00011 using System.Collections.Specialized;
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Popups;
00014
00015 namespace xBindSampleModel
00016 {
00017     public sealed class Manager : IEmployee, INotifyPropertyChanged
00018     {
00019         private Employee _employee;
00020         private EmployeeCollection _reports;
00021         private EmployeeDictionary _reportsDictionary;
00022
00023         public Manager()
00024         {
00025             _employee = new Employee();
00026             _reports = new EmployeeCollection();
00027             _reportsDictionary = new EmployeeDictionary();
00028         }
00029
00030         public IEnumerable<IEmployee> ReportsEnum { get { return _reports; } }
00031         public IList<IEmployee> ReportsList { get { return _reports; } }
00032         public EmployeeCollection ReportsOC { get { return _reports; } }
00033                 public EmployeeDictionary ReportsDict {  get { return _reportsDictionary; } }
00034
00035         public string NullStringProperty { get; set; }
00036         public Windows.UI.Xaml.Media.ImageSource NullImageSource
00037         {
00038             get { return null; }
00039             set { }
00040         }
00041
00042         public bool Visibility
00043         {
00044             get { return _employee.Visibility; }
00045             set
00046             {
00047                 if (_employee.Visibility != value)
00048                 {
00049                     _employee.Visibility = value;
00050                     NotifyPropertyChanged("Visibility");
00051                 }
00052             }
00053         }
00054         public string FirstName
00055         {
00056             get { return _employee.FirstName; }
00057             set
00058             {
00059                 if (value != _employee.FirstName)
00060                 {
00061                     _employee.FirstName = value;
00062                     NotifyPropertyChanged();
00063                     NotifyPropertyChanged("Name");
00064                 }
00065             }
00066         }
00067
00068         public string LastName
00069         {
00070             get { return _employee.LastName; }
00071             set
00072             {
00073                 if (value != _employee.LastName)
00074                 {
00075                     _employee.LastName = value;
00076                     NotifyPropertyChanged();
00077                     NotifyPropertyChanged("Name");
00078                 }
00079             }
00080         }
00081
00082         public Manager DirectManager
00083         {
00084             get { return _employee.DirectManager; }
00085             set
00086             {
00087                 if (value != _employee.DirectManager)
00088                 {
00089                     _employee.DirectManager = value;
00090                     NotifyPropertyChanged();
00091                 }
00092             }
00093         }
00094
00095         public void Poke(object sender, RoutedEventArgs e)
00096         {
00097             MessageDialog dlg = new MessageDialog("Employees of " + Name + " have been poked.");
00098             var t = dlg.ShowAsync();
00099         }
00100
00101         public bool IsManager { get { return true; } }
00102
00103         public String Title
00104         {
00105             get
00106             {
00107                 return "Manager";
00108             }
00109         }
00110
00111         public string Name { get { return FirstName + " " + LastName; } }
00112
00113         public string FullName() {  return FirstName + " " + LastName; }
00114
00115         #region INPC
00116
00117         public event PropertyChangedEventHandler PropertyChanged;
00118
00119         private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
00120         {
00121             if (PropertyChanged != null)
00122             {
00123                 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
00124             }
00125         }
00126         #endregion
00127     }
00128 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/Renderers/SceneComposer.cpp Source File

  • ComplexInk
  • cpp
  • Renderers

SceneComposer.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "SceneComposer.h"
00005
00006 using namespace SDKTemplate;
00007 using namespace Microsoft::WRL;
00008
00009 Windows::UI::Xaml::Media::Imaging::VirtualSurfaceImageSource^ SceneComposer::Initialize(
00010     Windows::Foundation::Size sizeContent, Windows::Foundation::Size sizeViewPort)
00011 {
00012     _deviceResources = std::make_unique<DX::DeviceResources>(sizeContent, sizeViewPort);
00013     _shapeRenderer = std::make_unique<ShapeRenderer>();
00014     _inkRenderer = std::make_unique<InkRenderer>();
00015
00016     assert(_deviceResources != nullptr);
00017     assert(_shapeRenderer != nullptr);
00018     assert(_inkRenderer != nullptr);
00019
00020     _shapeRenderer->RefreshSize(sizeViewPort);
00021
00022     // Register image source's update callback so update can be made to it.
00023     Microsoft::WRL::ComPtr<IVirtualSurfaceImageSourceNative> imageSourceNative = _deviceResources->GetImageSourceNative();
00024     DX::ThrowIfFailed(imageSourceNative->RegisterForUpdatesNeeded(this));
00025
00026     _refCount = 0;
00027     _EndDryPending = false;
00028     _inLassoSelection = false;
00029
00030     return _deviceResources->GetImageSource();
00031 }
00032
00033 SceneComposer::~SceneComposer()
00034 {
00035     // Unregister image source's update callback
00036     ComPtr<IVirtualSurfaceImageSourceNative> imageSourceNative = _deviceResources->GetImageSourceNative();
00037     DX::ThrowIfFailed(imageSourceNative->RegisterForUpdatesNeeded(nullptr));
00038
00039     DeleteSceneObjects();
00040 }
00041
00042 void SceneComposer::UpdateInk(Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ strokes)
00043 {
00044     Windows::Foundation::Rect strokesBoundingRect = Windows::Foundation::Rect::Empty;
00045
00046     assert(strokes != nullptr);
00047     assert(_inkRenderer != nullptr);
00048
00049     for (unsigned int i = 0; i < strokes->Size; i++)
00050     {
00051         Windows::UI::Input::Inking::InkStroke^ inkStroke = strokes->GetAt(i);
00052         if (strokesBoundingRect.IsEmpty)
00053         {
00054             strokesBoundingRect = inkStroke->BoundingRect;
00055         }
00056         else
00057         {
00058             strokesBoundingRect.Union(inkStroke->BoundingRect);
00059         }
00060         _inkRenderer->Update(inkStroke);
00061         InkObject* inkObject = new InkObject(inkStroke);
00062         _sceneObjects.push_back(inkObject);
00063     }
00064
00065     if (strokes->Size > 0)
00066     {
00067         assert(!strokesBoundingRect.IsEmpty);
00068         assert(_deviceResources != nullptr);
00069         RECT updateRect = _deviceResources->AdjustUpdateRect(ConvertUpdateRect(strokesBoundingRect));
00070         Invalidate(&updateRect);
00071     }
00072     else
00073     {
00074         // Need to call EndDry to complete the drying process even if there is zero stroke returned
00075         if (_EndDryPending)
00076         {
00077             assert(_inkSynchronizer != nullptr);
00078             _inkSynchronizer->EndDry();
00079             _EndDryPending = false;
00080         }
00081     }
00082 }
00083
00084 void SceneComposer::UpdateShape()
00085 {
00086     Windows::Foundation::Rect shapeRect = Windows::Foundation::Rect::Empty;
00087
00088     assert(_shapeRenderer != nullptr);
00089     assert(_deviceResources != nullptr);
00090     Shape shape = _shapeRenderer->Update(_deviceResources->GetD2DDeviceContext());
00091     shapeRect.X = shape.shape.left;
00092     shapeRect.Y = shape.shape.top;
00093     shapeRect.Width = shape.shape.right - shape.shape.left;
00094     shapeRect.Height = shape.shape.bottom - shape.shape.top;
00095
00096     SceneComposer::ShapeObject* shapeObject = new ShapeObject(shape);
00097     _sceneObjects.push_back(shapeObject);
00098
00099     assert(shapeRect.Width > 0 && shapeRect.Height > 0);
00100     assert(_deviceResources != nullptr);
00101     RECT updateRect = _deviceResources->AdjustUpdateRect(ConvertUpdateRect(shapeRect));
00102     Invalidate(&updateRect);
00103 }
00104
00105 void SceneComposer::Invalidate(_In_opt_ RECT* pInvalidateRect)
00106 {
00107     assert(_deviceResources != nullptr);
00108
00109     if (pInvalidateRect != nullptr)
00110     {
00111         // Invalidate VSIS to trigger rendering update
00112         _deviceResources->InvalidateRect(*pInvalidateRect);
00113     }
00114     else
00115     {
00116         _deviceResources->InvalidateContentRect();
00117     }
00118 }
00119
00120 void SceneComposer::ClearScene()
00121 {
00122     assert(_inkRenderer != nullptr);
00123     assert(_deviceResources != nullptr);
00124
00125     DeleteSceneObjects();
00126     _sceneObjects.clear();
00127     _inkRenderer->Clear();
00128     _deviceResources->InvalidateContentRect();
00129 }
00130
00131 void SceneComposer::DeleteSceneObjects()
00132 {
00133     for (unsigned int index = 0; index < _sceneObjects.size(); index++)
00134     {
00135         if (_sceneObjects[index] != nullptr)
00136         {
00137             delete _sceneObjects[index];
00138             _sceneObjects[index] = nullptr;
00139         }
00140     }
00141 }
00142
00143 void SceneComposer::SelectSceneObjects(Windows::Foundation::Collections::IVector<Windows::Foundation::Point>^ selectionPoints)
00144 {
00145     _inLassoSelection = false;    // End of lasso selection
00146
00147     assert(_inkRenderer != nullptr);
00148     // We call the inkRenderer to select the strokes in the strokecontainer. Then retrieve the stroke container
00149     // and update the vector of objects in the scene
00150     _inkRenderer->Select(selectionPoints);
00151     SelectInkSceneObject();
00152 }
00153
00154 void SceneComposer::OnViewSizeChanged(Windows::Foundation::Size newSize)
00155 {
00156     // This method can be called at program launch. By then device resources and
00157     // renderers are not initialized so we need to have null check.
00158     if (_shapeRenderer != nullptr)
00159     {
00160         // The size of shapes are proportional to the size of screen, so call
00161         // the shape renderer to recalculate max and min size for shapes.
00162         _shapeRenderer->RefreshSize(newSize);
00163     }
00164     if (_deviceResources != nullptr)
00165     {
00166         _deviceResources->SetViewSize(newSize);
00167         Invalidate();
00168     }
00169 }
00170
00171 void SDKTemplate::SceneComposer::UnselectSceneObjects()
00172 {
00173     assert(_inkRenderer != nullptr);
00174     assert(_deviceResources != nullptr);
00175
00176     Windows::Foundation::Rect selectRect = _inkRenderer->GetSelectionRectangle();
00177     if (!selectRect.IsEmpty)
00178     {
00179         _inkRenderer->UnselectAll();
00180         SelectInkSceneObject();
00181         // Since we have undone the selection, it is safe to clear all the
00182         // temporarily created strokes for selection hollow effect
00183         _inkRenderer->ClearStrokeContainerForTemp();
00184         RECT updateRect = _deviceResources->AdjustUpdateRect(ConvertUpdateRect(selectRect));
00185         _deviceResources->InvalidateRect(updateRect);
00186     }
00187 }
00188
00189 Windows::Foundation::Rect SceneComposer::GetSceneSelectionRect()
00190 {
00191     assert(_inkRenderer != nullptr);
00192     Windows::Foundation::Rect rect = _inkRenderer->GetSelectionRectangle();
00193     return rect;
00194 }
00195
00196 void SceneComposer::DoErase(Windows::Foundation::Point prevPt, Windows::Foundation::Point currPt)
00197 {
00198     assert(_inkRenderer != nullptr);
00199     if (_inkRenderer->HasStrokesToErase(prevPt, currPt))
00200     {
00201         DeleteSelectedAndUpdate();
00202     }
00203 }
00204
00205 void SceneComposer::DeleteSelectedAndUpdate()
00206 {
00207     RemoveSelectedStrokesFromSceneObjects();
00208     Windows::Foundation::Rect updateRect = _inkRenderer->DeleteSelectedStrokes();
00209
00210     if (!_inkRenderer->IsEmptyRect(updateRect))
00211     {
00212         assert(_deviceResources != nullptr);
00213         RECT vsisUpdateRect = _deviceResources->AdjustUpdateRect(ConvertUpdateRect(updateRect));
00214         _deviceResources->InvalidateRect(vsisUpdateRect);
00215     }
00216 }
00217
00218 void SceneComposer::RemoveSelectedStrokesFromSceneObjects()
00219 {
00220     for (std::vector<SceneObject*>::iterator pos = _sceneObjects.begin(); pos != _sceneObjects.end(); )
00221     {
00222         if ((*pos)->getType() == SOT_Ink)
00223         {
00224             InkObject* inkObject = dynamic_cast<InkObject*>(*pos);
00225
00226             if(inkObject->IsStrokeSelected())
00227             {
00228                 pos = _sceneObjects.erase(pos);
00229                 delete inkObject;
00230                 continue;
00231             }
00232         }
00233         pos++;
00234     }
00235 }
00236
00237 void SceneComposer::StartLassoSelection(Windows::Foundation::Point pt)
00238 {
00239     _ptInitial = pt;
00240     _inLassoSelection = true;    // Start of lasso selection
00241
00242     assert(_deviceResources != nullptr);
00243     DX::ThrowIfFailed(_deviceResources->GetD2DDeviceContext()->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &_selectionBrush));
00244
00245     DX::ThrowIfFailed(_deviceResources->GetD2DFactory()->CreateStrokeStyle(
00246         D2D1::StrokeStyleProperties(
00247         D2D1_CAP_STYLE_FLAT,
00248         D2D1_CAP_STYLE_FLAT,
00249         D2D1_CAP_STYLE_FLAT,
00250         D2D1_LINE_JOIN_ROUND,
00251         10.0F,
00252         D2D1_DASH_STYLE_DASH,
00253         0.0F),
00254         NULL,
00255         0,
00256         &_strokeStyle));
00257 }
00258
00259 void SceneComposer::DrawLasso(Windows::Foundation::Point pt)
00260 {
00261     assert(_deviceResources != nullptr);
00262
00263     // Lasso selection continues. Update the current end point of lasso rect
00264     _ptCurrent = pt;
00265     // Invalidate VSIS to trigger rendering update
00266     _deviceResources->InvalidateContentRect();
00267 }
00268
00269 void SceneComposer::Render()
00270 {
00271     auto strokes = ref new Platform::Collections::Vector<Windows::UI::Input::Inking::InkStroke^>;
00272     for (unsigned int index = 0; index < _sceneObjects.size(); index++)
00273     {
00274         if (_sceneObjects[index]->getType() == SOT_Ink)
00275         {
00276             InkObject* inkObject = dynamic_cast<InkObject*>(_sceneObjects[index]);
00277             if (inkObject != nullptr)
00278             {
00279                 auto currentInkStroke = inkObject->getStrokes();
00280                 // The max number of strokes in here is 2, one for the actual stroke and one for the highlighter
00281                 for (unsigned int strokeIndex = 0; strokeIndex < currentInkStroke->Size; strokeIndex++)
00282                 {
00283                     strokes->Append(currentInkStroke->GetAt(strokeIndex));
00284                 }
00285                 // Instead of passing one stroke at a time, we append all the strokes in the same z-order
00286                 // to optimize the rendering of ink. Once we find that the next object in the scene is different
00287                 // from ink or if we have reached the end of the vector, we pass the stroke collection to the
00288                 // ink renderer.
00289                 if ((index == (_sceneObjects.size() - 1)) ||
00290                     _sceneObjects[index + 1]->getType() == SOT_Shape)
00291                 {
00292                     _inkRenderer->Render(strokes, _deviceResources->GetD2DDeviceContext());
00293                     strokes->Clear();
00294                 }
00295             }
00296         }
00297         else if (_sceneObjects[index]->getType() == SOT_Shape)
00298         {
00299             ShapeObject* shape = dynamic_cast<ShapeObject*>(_sceneObjects[index]);
00300             if (shape != nullptr)
00301             {
00302                 _shapeRenderer->Render(shape->getShape(), _deviceResources->GetD2DDeviceContext());
00303             }
00304         }
00305     }
00306 }
00307
00308 // Restore the width of selected strokes to default in case that they are copied/cut for pasting
00309 void SceneComposer::RestoreDefaultStrokeSize()
00310 {
00311     assert(_inkRenderer != nullptr);
00312     Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ inkStrokes = _inkRenderer->GetStrokeContainer()->GetStrokes();
00313     for (unsigned int i = 0; i < inkStrokes->Size; i++)
00314     {
00315         Windows::UI::Input::Inking::InkStroke^ inkStroke = inkStrokes->GetAt(i);
00316         if (inkStroke->Selected)
00317         {
00318             auto strokeDrawingAttributes = inkStroke->DrawingAttributes;
00319             strokeDrawingAttributes->Size = InkObject::GetDefaultStrokeSize();
00320             inkStroke->DrawingAttributes = strokeDrawingAttributes;
00321         }
00322     }
00323 }
00324
00325 void SceneComposer::CopySelected()
00326 {
00327     assert(_inkRenderer != nullptr);
00328     RestoreDefaultStrokeSize();
00329     _inkRenderer->GetStrokeContainer()->CopySelectedToClipboard();
00330 }
00331
00332 void SceneComposer::CutSelected()
00333 {
00334     assert(_inkRenderer != nullptr);
00335     RestoreDefaultStrokeSize();
00336     _inkRenderer->GetStrokeContainer()->CopySelectedToClipboard();
00337
00338     // Delete the scene objects in the cache and clear the selection rect
00339     _inkRenderer->UpdateSelectionRectangle(Windows::Foundation::Rect::Empty);
00340     DeleteSelectedAndUpdate();
00341 }
00342
00343 void SceneComposer::PasteSelected(Windows::Foundation::Point pastePosition)
00344 {
00345     assert(_inkRenderer != nullptr);
00346
00347     if (_inkRenderer->GetStrokeContainer()->CanPasteFromClipboard())
00348     {
00349         Windows::Foundation::Rect pasteRect = _inkRenderer->GetStrokeContainer()->PasteFromClipboard(pastePosition);
00350         Windows::Foundation::Collections::IVector<Windows::Foundation::Point>^ pasteRectVector;
00351
00352         // Create a selection rectangle that will be used to select strokes in the strokecontainer and then
00353         // we will add them to the scene object collection
00354         pasteRectVector = ref new Platform::Collections::Vector<Windows::Foundation::Point>();
00355         pasteRectVector->Append(Windows::Foundation::Point(pasteRect.Left, pasteRect.Top));
00356         pasteRectVector->Append(Windows::Foundation::Point(pasteRect.Left, pasteRect.Bottom));
00357         pasteRectVector->Append(Windows::Foundation::Point(pasteRect.Right, pasteRect.Bottom));
00358         pasteRectVector->Append(Windows::Foundation::Point(pasteRect.Right, pasteRect.Top));
00359
00360         _inkRenderer->Select(pasteRectVector);
00361         Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ inkStrokes = _inkRenderer->GetStrokeContainer()->GetStrokes();
00362         for (unsigned int i = 0; i < inkStrokes->Size; i++)
00363         {
00364             if (inkStrokes->GetAt(i)->Selected)
00365             {
00366                 InkObject* inkObject = new InkObject(inkStrokes->GetAt(i));
00367                 _sceneObjects.push_back(inkObject);
00368             }
00369         }
00370         UnselectSceneObjects();
00371     }
00372 }
00373
00374 void SceneComposer::SelectInkSceneObject()
00375 {
00376     Windows::Foundation::Rect selectionBoundingRect = Windows::Foundation::Rect::Empty;
00377
00378     // Update the sceneInkObject to create or delete the highlighter stroke
00379     for (unsigned int index = 0; index < _sceneObjects.size(); index++)
00380     {
00381         if (_sceneObjects[index]->getType() == SOT_Ink)
00382         {
00383             InkObject* inkObject = dynamic_cast<InkObject*>(_sceneObjects[index]);
00384             if (inkObject != nullptr)
00385             {
00386                 assert(_inkRenderer != nullptr);
00387                 inkObject->SelectStroke(_inkRenderer->GetStrokeContainerForTemp());
00388
00389                 // Need to update selection bounding rect since we have changed the size
00390                 // of selected strokes in the last step.
00391                 if (inkObject->IsStrokeSelected())
00392                 {
00393                     if (selectionBoundingRect.IsEmpty)
00394                     {
00395                         selectionBoundingRect = inkObject->GetInkStroke()->BoundingRect;
00396                     }
00397                     else
00398                     {
00399                         selectionBoundingRect.Union(inkObject->GetInkStroke()->BoundingRect);
00400                     }
00401                 }
00402             }
00403         }
00404     }
00405
00406     assert(_inkRenderer != nullptr);
00407     if (!_inkRenderer->IsEmptyRect(selectionBoundingRect))
00408     {
00409         _inkRenderer->UpdateSelectionRectangle(selectionBoundingRect);
00410     }
00411 }
00412
00413 void SceneComposer::DoCustomDry()
00414 {
00415     assert(_inkSynchronizer != nullptr);
00416     Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ inkStrokes = _inkSynchronizer->BeginDry();
00417     assert(inkStrokes != nullptr);
00418     // Request VSIS update by invalidation and set the flag to call
00419     // InkSynchronizer's EndDry later. Note that before EndDry is
00420     // called, there will be no new StrokesCollected event fired
00421     // from InkPresenter, and we will not get any new stroke to dry.
00422     assert(!_EndDryPending);
00423     _EndDryPending = true;
00424     UpdateInk(inkStrokes);
00425 }
00426
00427 // This method is called when the framework needs to update region managed by
00428 // the virtual surface image source.
00429 HRESULT STDMETHODCALLTYPE SceneComposer::UpdatesNeeded()
00430 {
00431     HRESULT hr = S_OK;
00432     RECT* updateRects = nullptr;
00433     ULONG updateRectsCount = 0;
00434
00435     assert(_deviceResources != nullptr);
00436
00437     try
00438     {
00439         _deviceResources->GetUpdateRects(&updateRects, &updateRectsCount);
00440
00441         for (ULONG i = 0; i < updateRectsCount; ++i)
00442         {
00443             Draw(&updateRects[i]);
00444         }
00445
00446     }
00447     catch (Platform::Exception^ exception)
00448     {
00449         hr = exception->HResult;
00450
00451         if (hr == D2DERR_RECREATE_TARGET ||
00452             hr == DXGI_ERROR_DEVICE_REMOVED)
00453         {
00454             // HandleDeviceLost
00455             _deviceResources->CreateDeviceResources();
00456
00457             _deviceResources->InvalidateContentRect();
00458         }
00459     }
00460
00461     // Clear up buffer for updateRects
00462     if (updateRects != nullptr)
00463     {
00464         delete updateRects;
00465     }
00466
00467     // Complete any pending call for EndDry so we can continue to
00468     // receive new strokes to dry through StrokesCollected event.
00469     if (_EndDryPending)
00470     {
00471         assert(_inkSynchronizer != nullptr);
00472         _inkSynchronizer->EndDry();
00473         _EndDryPending = false;
00474     }
00475
00476     return hr;
00477 }
00478
00479 bool SceneComposer::Draw(_In_opt_ const RECT* pUpdateRect)
00480 {
00481     assert(_deviceResources != nullptr);
00482
00483     _deviceResources->BeginDraw(pUpdateRect);
00484
00485     _deviceResources->ClearTarget();
00486
00487     Render();
00488
00489     if (_inLassoSelection)
00490     {
00491         // Draw lasso
00492         assert(_selectionBrush != nullptr && _strokeStyle != nullptr);
00493         D2D_RECT_F selectionRect = D2D1::RectF(_ptInitial.X, _ptInitial.Y, _ptCurrent.X, _ptCurrent.Y);
00494         _deviceResources->GetD2DDeviceContext()->DrawRectangle(selectionRect, _selectionBrush.Get(), 1.0f, _strokeStyle.Get());
00495     }
00496     else
00497     {
00498         // Draw selection rectangle
00499         _inkRenderer->DrawSelectionRect(_deviceResources->GetD2DDeviceContext(),
00500             _deviceResources->GetD2DFactory());
00501     }
00502
00503     _deviceResources->EndDraw();
00504
00505     return false;
00506 }
00507
00508 HRESULT STDMETHODCALLTYPE SceneComposer::QueryInterface(
00509     REFIID uuid,
00510     _Outptr_ void** object
00511     )
00512 {
00513     if (uuid == IID_IUnknown
00514         || uuid == __uuidof(IVirtualSurfaceUpdatesCallbackNative)
00515         )
00516     {
00517         *object = this;
00518         AddRef();
00519         return S_OK;
00520     }
00521     else
00522     {
00523         *object = nullptr;
00524         return E_NOINTERFACE;
00525     }
00526 }
00527
00528 ULONG STDMETHODCALLTYPE SceneComposer::AddRef()
00529 {
00530     return static_cast<ULONG>(InterlockedIncrement(&_refCount));
00531 }
00532
00533 ULONG STDMETHODCALLTYPE SceneComposer::Release()
00534 {
00535     ULONG newCount = static_cast<ULONG>(InterlockedDecrement(&_refCount));
00536
00537     if (newCount == 0)
00538         delete this;
00539
00540     return newCount;
00541 }
00542
00543 RECT SceneComposer::ConvertUpdateRect(Windows::Foundation::Rect const& updateRect)
00544 {
00545     // Enlarge the update rect to accommodate precision loss when covert float to long
00546     RECT updateRECT;
00547     updateRECT.left = static_cast<LONG>(updateRect.X) - RECT_DELTA;
00548     updateRECT.top = static_cast<LONG>(updateRect.Y) - RECT_DELTA;
00549     updateRECT.right = static_cast<LONG>(updateRect.X + updateRect.Width) + RECT_DELTA;
00550     updateRECT.bottom = static_cast<LONG>(updateRect.Y + updateRect.Height) + RECT_DELTA;
00551
00552     return updateRECT;
00553 }
Generated on Fri Nov 15 2024 22:18:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/DirectXPage.xaml.cpp Source File

  • Simple3DGameXaml
  • cpp

DirectXPage.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012
00013 #include "pch.h"
00014 #include "App.xaml.h"
00015 #include "DirectXPage.xaml.h"
00016 #include "ProductItem.h"
00017
00018 using namespace Simple3DGameXaml;
00019
00020 using namespace Microsoft::WRL;
00021 using namespace Platform;
00022 using namespace Windows::ApplicationModel;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::Graphics::Display;
00026 using namespace Windows::Storage;
00027 using namespace Windows::UI::Core;
00028 using namespace Windows::UI::Input;
00029 using namespace Windows::UI::ViewManagement;
00030 using namespace Windows::UI::Xaml;
00031 using namespace Windows::UI::Xaml::Controls;
00032 using namespace Windows::UI::Xaml::Controls::Primitives;
00033 using namespace Windows::UI::Xaml::Data;
00034 using namespace Windows::UI::Xaml::Input;
00035 using namespace Windows::UI::Xaml::Media;
00036 using namespace Windows::UI::Xaml::Navigation;
00037 using namespace Windows::ApplicationModel::Store;
00038 using namespace Windows::UI::Popups;
00039 using namespace concurrency;
00040
00041 //----------------------------------------------------------------------
00042
00043 DirectXPage::DirectXPage() :
00044     m_playActive(false),
00045     m_possiblePurchaseUpgrade(false)
00046 {
00047     InitializeComponent();
00048
00049 #ifdef USE_STORE_SIMULATOR
00050     ResetLicense->Visibility = ::Visibility::Visible;
00051 #endif
00052
00053     // Register event handlers for page lifecycle.
00054     CoreWindow^ window = Window::Current->CoreWindow;
00055
00056     window->VisibilityChanged +=
00057         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXPage::OnVisibilityChanged);
00058     window->SizeChanged +=
00059         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DirectXPage::OnWindowSizeChanged);
00060
00061     Window::Current->Activated +=
00062         ref new WindowActivatedEventHandler(this, &DirectXPage::OnWindowActivationChanged);
00063
00064     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00065
00066     currentDisplayInformation->DpiChanged +=
00067         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnDpiChanged);
00068
00069     currentDisplayInformation->OrientationChanged +=
00070         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnOrientationChanged);
00071
00072     currentDisplayInformation->StereoEnabledChanged +=
00073         ref new TypedEventHandler<DisplayInformation^, Platform::Object^>(this, &DirectXPage::OnStereoEnabledChanged);
00074
00075     DisplayInformation::DisplayContentsInvalidated +=
00076         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnDisplayContentsInvalidated);
00077
00078     DXSwapChainPanel->CompositionScaleChanged +=
00079         ref new TypedEventHandler<SwapChainPanel^, Object^>(this, &DirectXPage::OnCompositionScaleChanged);
00080
00081     DXSwapChainPanel->SizeChanged +=
00082         ref new SizeChangedEventHandler(this, &DirectXPage::OnSwapChainPanelSizeChanged);
00083
00084     // Disable all pointer visual feedback for better performance when touching.
00085     auto pointerVisualizationSettings = PointerVisualizationSettings::GetForCurrentView();
00086     pointerVisualizationSettings->IsContactFeedbackEnabled = false;
00087     pointerVisualizationSettings->IsBarrelButtonFeedbackEnabled = false;
00088
00089     // At this point we have access to the device.
00090     // We can create the device-dependent resources.
00091     m_deviceResources = std::make_shared<DX::DeviceResources>();
00092     m_deviceResources->SetSwapChainPanel(DXSwapChainPanel);
00093
00094     m_main = std::unique_ptr<GameMain>(new GameMain(m_deviceResources, this));
00095
00096     InitializeLicense();
00097
00098     m_main->StartRenderLoop();
00099 }
00100
00101 //----------------------------------------------------------------------
00102
00103 void DirectXPage::HideGameInfoOverlay()
00104 {
00105     // This function may be called from a different thread.
00106     // All XAML updates need to occur on the UI thread so dispatch to ensure this is true.
00107     Dispatcher->RunAsync(
00108         CoreDispatcherPriority::Normal,
00109         ref new DispatchedHandler([this]()
00110         {
00111             VisualStateManager::GoToState(this, "NormalState", true);
00112
00113             StoreFlyout->IsOpen = false;
00114             StoreFlyout->Visibility = ::Visibility::Collapsed;
00115             GameAppBar->IsOpen = false;
00116             Play->Label = "Pause";
00117             Play->Icon = ref new SymbolIcon(Symbol::Pause);
00118             m_playActive = true;
00119         })
00120         );
00121 }
00122
00123 //----------------------------------------------------------------------
00124
00125 void DirectXPage::ShowGameInfoOverlay()
00126 {
00127     // This function may be called from a different thread.
00128     // All XAML updates need to occur on the UI thread so dispatch to ensure this is true.
00129     Dispatcher->RunAsync(
00130         CoreDispatcherPriority::Normal,
00131         ref new DispatchedHandler([this]()
00132         {
00133             VisualStateManager::GoToState(this, "GameInfoOverlayState", true);
00134             Play->Label = "Play";
00135             Play->Icon = ref new SymbolIcon(Symbol::Play);
00136             m_playActive = false;
00137         })
00138         );
00139 }
00140
00141 //----------------------------------------------------------------------
00142
00143 void DirectXPage::SetAction(GameInfoOverlayCommand action)
00144 {
00145     // This function may be called from a different thread.
00146     // All XAML updates need to occur on the UI thread so dispatch to ensure this is true.
00147     Dispatcher->RunAsync(
00148         CoreDispatcherPriority::Normal,
00149         ref new DispatchedHandler([this, action]()
00150         {
00151             // Enable only one of the four possible commands at the bottom of the
00152             // Game Info Overlay.
00153
00154             PlayAgain->Visibility = ::Visibility::Collapsed;
00155             PleaseWait->Visibility = ::Visibility::Collapsed;
00156             TapToContinue->Visibility = ::Visibility::Collapsed;
00157
00158             switch (action)
00159             {
00160             case GameInfoOverlayCommand::PlayAgain:
00161                 PlayAgain->Visibility = ::Visibility::Visible;
00162                 break;
00163             case GameInfoOverlayCommand::PleaseWait:
00164                 PleaseWait->Visibility = ::Visibility::Visible;
00165                 break;
00166             case GameInfoOverlayCommand::TapToContinue:
00167                 TapToContinue->Visibility = ::Visibility::Visible;
00168                 break;
00169             case GameInfoOverlayCommand::None:
00170                 break;
00171             }
00172         })
00173         );
00174 }
00175
00176 //----------------------------------------------------------------------
00177
00178 void DirectXPage::SetGameLoading()
00179 {
00180     // This function may be called from a different thread.
00181     // All XAML updates need to occur on the UI thread so dispatch to ensure this is true.
00182     Dispatcher->RunAsync(
00183         CoreDispatcherPriority::Normal,
00184         ref new DispatchedHandler([this]()
00185         {
00186             GameInfoOverlayTitle->Text = "Loading Resources";
00187
00188             Loading->Visibility = ::Visibility::Visible;
00189             Stats->Visibility = ::Visibility::Collapsed;
00190             LevelStart->Visibility = ::Visibility::Collapsed;
00191             PauseData->Visibility = ::Visibility::Collapsed;
00192             LoadingProgress->IsActive = true;
00193         })
00194         );
00195 }
00196
00197 //----------------------------------------------------------------------
00198
00199 void DirectXPage::SetGameStats(
00200     int maxLevel,
00201     int hitCount,
00202     int shotCount
00203     )
00204 {
00205     // This function may be called from a different thread.
00206     // All XAML updates need to occur on the UI thread so dispatch to ensure this is true.
00207     Dispatcher->RunAsync(
00208         CoreDispatcherPriority::Normal,
00209         ref new DispatchedHandler([this, maxLevel, hitCount, shotCount]()
00210         {
00211             GameInfoOverlayTitle->Text = "Game Statistics";
00212             m_possiblePurchaseUpgrade = true;
00213             OptionalTrialUpgrade();
00214
00215             Loading->Visibility = ::Visibility::Collapsed;
00216             Stats->Visibility = ::Visibility::Visible;
00217             LevelStart->Visibility = ::Visibility::Collapsed;
00218             PauseData->Visibility = ::Visibility::Collapsed;
00219
00220             static const int bufferLength = 20;
00221             static char16 wsbuffer[bufferLength];
00222
00223             int length = swprintf_s(wsbuffer, bufferLength, L"%d", maxLevel);
00224             LevelsCompleted->Text = ref new Platform::String(wsbuffer, length);
00225
00226             length = swprintf_s(wsbuffer, bufferLength, L"%d", hitCount);
00227             TotalPoints->Text = ref new Platform::String(wsbuffer, length);
00228
00229             length = swprintf_s(wsbuffer, bufferLength, L"%d", shotCount);
00230             TotalShots->Text = ref new Platform::String(wsbuffer, length);
00231
00232             // High Score is not used for showing Game Statistics
00233             HighScoreTitle->Visibility = ::Visibility::Collapsed;
00234             HighScoreData->Visibility = ::Visibility::Collapsed;
00235         })
00236         );
00237 }
00238
00239 //----------------------------------------------------------------------
00240
00241 void DirectXPage::SetGameOver(
00242     bool win,
00243     int maxLevel,
00244     int hitCount,
00245     int shotCount,
00246     int highScore
00247     )
00248 {
00249     // This function may be called from a different thread.
00250     // All XAML updates need to occur on the UI thread so dispatch to ensure this is true.
00251     Dispatcher->RunAsync(
00252         CoreDispatcherPriority::Normal,
00253         ref new DispatchedHandler([this, win, maxLevel, hitCount, shotCount, highScore]()
00254         {
00255             if (win)
00256             {
00257                 GameInfoOverlayTitle->Text = "You Won!";
00258                 m_possiblePurchaseUpgrade = true;
00259                 OptionalTrialUpgrade();
00260             }
00261             else
00262             {
00263                 GameInfoOverlayTitle->Text = "Game Over";
00264                 m_possiblePurchaseUpgrade = false;
00265                 PurchaseUpgrade->Visibility = ::Visibility::Collapsed;
00266             }
00267             Loading->Visibility = ::Visibility::Collapsed;
00268             Stats->Visibility = ::Visibility::Visible;
00269             LevelStart->Visibility = ::Visibility::Collapsed;
00270             PauseData->Visibility = ::Visibility::Collapsed;
00271
00272             static const int bufferLength = 20;
00273             static char16 wsbuffer[bufferLength];
00274
00275             int length = swprintf_s(wsbuffer, bufferLength, L"%d", maxLevel);
00276             LevelsCompleted->Text = ref new Platform::String(wsbuffer, length);
00277
00278             length = swprintf_s(wsbuffer, bufferLength, L"%d", hitCount);
00279             TotalPoints->Text = ref new Platform::String(wsbuffer, length);
00280
00281             length = swprintf_s(wsbuffer, bufferLength, L"%d", shotCount);
00282             TotalShots->Text = ref new Platform::String(wsbuffer, length);
00283
00284             // Show High Score
00285             HighScoreTitle->Visibility = ::Visibility::Visible;
00286             HighScoreData->Visibility = ::Visibility::Visible;
00287             length = swprintf_s(wsbuffer, bufferLength, L"%d", highScore);
00288             HighScore->Text = ref new Platform::String(wsbuffer, length);
00289         })
00290         );
00291 }
00292
00293 //----------------------------------------------------------------------
00294
00295 void DirectXPage::SetLevelStart(
00296     int level,
00297     Platform::String^ objective,
00298     float timeLimit,
00299     float bonusTime
00300     )
00301 {
00302     // This function may be called from a different thread.
00303     // All XAML updates need to occur on the UI thread so dispatch to ensure this is true.
00304     Dispatcher->RunAsync(
00305         CoreDispatcherPriority::Normal,
00306         ref new DispatchedHandler([this, level, objective, timeLimit, bonusTime]()
00307         {
00308             static const int bufferLength = 20;
00309             static char16 wsbuffer[bufferLength];
00310
00311             int length = swprintf_s(wsbuffer, bufferLength, L"Level %d", level);
00312             GameInfoOverlayTitle->Text = ref new Platform::String(wsbuffer, length);
00313
00314             Loading->Visibility = ::Visibility::Collapsed;
00315             Stats->Visibility = ::Visibility::Collapsed;
00316             LevelStart->Visibility = ::Visibility::Visible;
00317             PauseData->Visibility = ::Visibility::Collapsed;
00318
00319             Objective->Text = objective;
00320
00321             length = swprintf_s(wsbuffer, bufferLength, L"%6.1f sec", timeLimit);
00322             TimeLimit->Text = ref new Platform::String(wsbuffer, length);
00323
00324             if (bonusTime > 0.0)
00325             {
00326                 BonusTimeTitle->Visibility = ::Visibility::Visible;
00327                 BonusTimeData->Visibility = ::Visibility::Visible;
00328                 length = swprintf_s(wsbuffer, bufferLength, L"%6.1f sec", bonusTime);
00329                 BonusTime->Text = ref new Platform::String(wsbuffer, length);
00330             }
00331             else
00332             {
00333                 BonusTimeTitle->Visibility = ::Visibility::Collapsed;
00334                 BonusTimeData->Visibility = ::Visibility::Collapsed;
00335             }
00336         })
00337         );
00338 }
00339
00340 //----------------------------------------------------------------------
00341
00342 void DirectXPage::SetPause(int level, int hitCount, int shotCount, float timeRemaining)
00343 {
00344     // This function may be called from a different thread.
00345     // All XAML updates need to occur on the UI thread so dispatch to ensure this is true.
00346     Dispatcher->RunAsync(
00347         CoreDispatcherPriority::Normal,
00348         ref new DispatchedHandler([this, level, hitCount, shotCount, timeRemaining]()
00349         {
00350             GameInfoOverlayTitle->Text = "Paused";
00351             Loading->Visibility = ::Visibility::Collapsed;
00352             Stats->Visibility = ::Visibility::Collapsed;
00353             LevelStart->Visibility = ::Visibility::Collapsed;
00354             PauseData->Visibility = ::Visibility::Visible;
00355
00356             static const int bufferLength = 20;
00357             static char16 wsbuffer[bufferLength];
00358
00359             int length = swprintf_s(wsbuffer, bufferLength, L"%d", level);
00360             PauseLevel->Text = ref new Platform::String(wsbuffer, length);
00361
00362             length = swprintf_s(wsbuffer, bufferLength, L"%d", hitCount);
00363             PauseHits->Text = ref new Platform::String(wsbuffer, length);
00364
00365             length = swprintf_s(wsbuffer, bufferLength, L"%d", shotCount);
00366             PauseShots->Text = ref new Platform::String(wsbuffer, length);
00367
00368             length = swprintf_s(wsbuffer, bufferLength, L"%6.1f sec", timeRemaining);
00369             PauseTimeRemaining->Text = ref new Platform::String(wsbuffer, length);
00370         })
00371         );
00372 }
00373
00374 //----------------------------------------------------------------------
00375
00376 void DirectXPage::ShowTooSmall()
00377 {
00378     // This function may be called from a different thread.
00379     // All XAML updates need to occur on the UI thread so dispatch to ensure this is true.
00380     Dispatcher->RunAsync(
00381         CoreDispatcherPriority::Normal,
00382         ref new DispatchedHandler([this]()
00383         {
00384             VisualStateManager::GoToState(this, "TooSmallState", true);
00385         })
00386         );
00387 }
00388
00389 //----------------------------------------------------------------------
00390
00391 void DirectXPage::HideTooSmall()
00392 {
00393     // This function may be called from a different thread.
00394     // All XAML updates need to occur on the UI thread so dispatch to ensure this is true.
00395     Dispatcher->RunAsync(
00396         CoreDispatcherPriority::Normal,
00397         ref new DispatchedHandler([this]()
00398         {
00399             VisualStateManager::GoToState(this, "NotTooSmallState", true);
00400         })
00401         );
00402 }
00403
00404 // Window event handlers.
00405 //----------------------------------------------------------------------
00406
00407 void DirectXPage::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
00408 {
00409     m_windowVisible = args->Visible;
00410     if (m_windowVisible)
00411     {
00412         m_main->StartRenderLoop();
00413     }
00414     else
00415     {
00416         m_main->StopRenderLoop();
00417     }
00418 }
00419
00420 //----------------------------------------------------------------------
00421
00422 void DirectXPage::OnWindowActivationChanged(
00423     _In_ Platform::Object^ /* sender */,
00424     _In_ Windows::UI::Core::WindowActivatedEventArgs^ args
00425     )
00426 {
00427     critical_section::scoped_lock lock(m_main->GetCriticalSection());
00428     m_main->WindowActivationChanged(args->WindowActivationState);
00429 }
00430
00431 // DisplayInformation event handlers.
00432 //----------------------------------------------------------------------
00433
00434 void DirectXPage::OnDpiChanged(DisplayInformation^ sender, Object^ args)
00435 {
00436     critical_section::scoped_lock lock(m_main->GetCriticalSection());
00437     m_deviceResources->SetDpi(sender->LogicalDpi);
00438     m_main->CreateWindowSizeDependentResources();
00439 }
00440
00441 //----------------------------------------------------------------------
00442
00443 void DirectXPage::OnOrientationChanged(DisplayInformation^ sender, Object^ args)
00444 {
00445     critical_section::scoped_lock lock(m_main->GetCriticalSection());
00446     m_deviceResources->SetCurrentOrientation(sender->CurrentOrientation);
00447     m_main->CreateWindowSizeDependentResources();
00448 }
00449
00450 //----------------------------------------------------------------------
00451
00452 void DirectXPage::OnStereoEnabledChanged(DisplayInformation^ /* sender */, Object^ /* args */)
00453 {
00454     critical_section::scoped_lock lock(m_main->GetCriticalSection());
00455     m_deviceResources->UpdateStereoState();
00456     m_main->CreateWindowSizeDependentResources();
00457 }
00458
00459 //----------------------------------------------------------------------
00460
00461 void DirectXPage::OnDisplayContentsInvalidated(DisplayInformation^ sender, Object^ args)
00462 {
00463     critical_section::scoped_lock lock(m_main->GetCriticalSection());
00464     m_deviceResources->ValidateDevice();
00465 }
00466
00467 //----------------------------------------------------------------------
00468
00469 void DirectXPage::OnCompositionScaleChanged(SwapChainPanel^ sender, Object^ args)
00470 {
00471     critical_section::scoped_lock lock(m_main->GetCriticalSection());
00472     m_deviceResources->SetCompositionScale(sender->CompositionScaleX, sender->CompositionScaleY);
00473     m_main->CreateWindowSizeDependentResources();
00474 }
00475
00476 //----------------------------------------------------------------------
00477
00478 void DirectXPage::OnSwapChainPanelSizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00479 {
00480     critical_section::scoped_lock lock(m_main->GetCriticalSection());
00481     m_deviceResources->SetLogicalSize(e->NewSize);
00482     m_main->CreateWindowSizeDependentResources();
00483 }
00484
00485 //----------------------------------------------------------------------
00486
00487 void DirectXPage::OnSuspending()
00488 {
00489     critical_section::scoped_lock lock(m_main->GetCriticalSection());
00490     m_main->Suspend();
00491     // Stop rendering when the app is suspended.
00492     m_main->StopRenderLoop();
00493
00494     m_deviceResources->Trim();
00495
00496 }
00497
00498 //----------------------------------------------------------------------
00499
00500 void DirectXPage::OnResuming()
00501 {
00502     m_main->Resume();
00503     m_main->StartRenderLoop();
00504 }
00505
00506 //----------------------------------------------------------------------
00507
00508 void DirectXPage::OnGameInfoOverlayTapped(Object^ /* sender */, TappedRoutedEventArgs^ /* args */)
00509 {
00510     m_main->PressComplete();
00511 }
00512
00513 //----------------------------------------------------------------------
00514
00515 void DirectXPage::OnPlayButtonClicked(Object^ /* sender */, RoutedEventArgs^ /* args */)
00516 {
00517     if (m_playActive)
00518     {
00519         m_main->PauseRequested();
00520     }
00521     else
00522     {
00523         m_main->PressComplete();
00524     }
00525 }
00526
00527 //----------------------------------------------------------------------
00528
00529 void DirectXPage::OnResetButtonClicked(Object^ /* sender */, RoutedEventArgs^ /* args */)
00530 {
00531     m_main->ResetGame();
00532     GameAppBar->IsOpen = false;
00533 }
00534
00535 //----------------------------------------------------------------------
00536 void DirectXPage::InitializeLicense()
00537 {
00538 #ifdef USE_STORE_SIMULATOR
00539     m_licenseState = ref new PersistentState();
00540     m_licenseState->Initialize(ApplicationData::Current->LocalSettings->Values, "CurrentAppSimulator");
00541     m_isTrial = m_licenseState->LoadBool(":isTrial", true);
00542
00543     Platform::String^ license;
00544     if (this->m_isTrial)
00545     {
00546         license = "TrialLicense.xml";
00547     }
00548     else
00549     {
00550         license = "FullLicense.xml";
00551     }
00552     task<StorageFile^> fileTask(Package::Current->InstalledLocation->GetFileAsync(license));
00553     fileTask.then([=](StorageFile^ sourceFile)
00554     {
00555         return create_task(CurrentAppSimulator::ReloadSimulatorAsync(sourceFile));
00556     }).then([this]()
00557     {
00558         this->InitializeLicenseCore();
00559     });
00560 #else
00561     this->InitializeLicenseCore();
00562 #endif
00563 }
00564
00565 //--------------------------------------------------------------------------------------
00566
00567 void DirectXPage::InitializeLicenseCore()
00568 {
00569 #ifdef USE_STORE_SIMULATOR
00570     this->m_licenseInformation = CurrentAppSimulator::LicenseInformation;
00571     task<ListingInformation^> listingTask(CurrentAppSimulator::LoadListingInformationAsync());
00572 #else
00573     m_licenseInformation = CurrentApp::LicenseInformation;
00574     task<ListingInformation^> listingTask(CurrentApp::LoadListingInformationAsync());
00575 #endif
00576
00577     this->m_licenseInformation->LicenseChanged += ref new LicenseChangedEventHandler(this, &DirectXPage::OnLicenseChanged);
00578     this->SetProductItems(nullptr, m_licenseInformation);
00579     this->OnLicenseChanged();
00580
00581     listingTask.then([=](ListingInformation^ listing)
00582     {
00583         this->m_listingInformation = listing;
00584         this->OnLicenseChanged();
00585     });
00586 }
00587
00588 //--------------------------------------------------------------------------------------
00589
00590 #ifdef USE_STORE_SIMULATOR
00591 void DirectXPage::ResetLicenseFromFile()
00592 {
00593     task<StorageFile^> fileTask(Package::Current->InstalledLocation->GetFileAsync("TrialLicense.xml"));
00594     fileTask.then([=](StorageFile^ sourceFile)
00595     {
00596         CurrentAppSimulator::ReloadSimulatorAsync(sourceFile);
00597     });
00598 }
00599 #endif
00600
00601 //--------------------------------------------------------------------------------------
00602
00603 void DirectXPage::OnLicenseChanged()
00604 {
00605 #ifdef USE_STORE_SIMULATOR
00606     m_isTrial = (m_licenseInformation->IsActive && m_licenseInformation->IsTrial);
00607     m_licenseState->SaveBool(":isTrial", m_isTrial);
00608 #endif
00609
00610     m_main->LicenseChanged(m_listingInformation, m_licenseInformation);
00611
00612     // This function may be called from a different thread.
00613     // All XAML updates need to occur on the UI thread so dispatch to ensure this is true.
00614     Dispatcher->RunAsync(
00615         CoreDispatcherPriority::Normal,
00616         ref new DispatchedHandler([this]()
00617         {
00618             if (m_licenseInformation->IsActive)
00619             {
00620                 if (!m_licenseInformation->IsTrial)
00621                 {
00622                     PurchaseUpgrade->Visibility = ::Visibility::Collapsed;
00623                 }
00624             }
00625             else
00626             {
00627                 ChangeBackground->Visibility = ::Visibility::Collapsed;
00628             }
00629
00630             if (m_licenseInformation->IsActive && m_licenseInformation->IsTrial)
00631             {
00632                 if (m_listingInformation != nullptr)
00633                 {
00634                     PurchaseMessage->Text =
00635                         "You are running a trial version. Purchase the full version for: " + m_listingInformation->FormattedPrice;
00636                 }
00637                 else
00638                 {
00639                     PurchaseMessage->Text =
00640                         "You are running a trial version. Purchase the full version.";
00641                 }
00642                 if (m_possiblePurchaseUpgrade)
00643                 {
00644                     PurchaseUpgrade->Visibility = ::Visibility::Visible;
00645                 }
00646             }
00647
00648             if (m_licenseInformation != nullptr)
00649             {
00650                 auto items = dynamic_cast<Platform::Collections::Vector<Platform::Object^>^>(ProductListView->ItemsSource);
00651                 for (uint32 i = 0; i < items->Size; i++)
00652                 {
00653                     dynamic_cast<ProductItem^>(items->GetAt(i))->UpdateContent(m_licenseInformation);
00654                 }
00655             }
00656             if (m_listingInformation != nullptr)
00657             {
00658                 auto items = dynamic_cast<Platform::Collections::Vector<Platform::Object^>^>(ProductListView->ItemsSource);
00659                 for (uint32 i = 0; i < items->Size; i++)
00660                 {
00661                     dynamic_cast<ProductItem^>(items->GetAt(i))->UpdateContent(m_listingInformation);
00662                 }
00663             }
00664         })
00665         );
00666 }
00667
00668 //----------------------------------------------------------------------
00669
00670 void DirectXPage::OnBuyAppButtonTapped(Object^ sender, TappedRoutedEventArgs^ args)
00671 {
00672     args->Handled = true;
00673     OnBuySelectorClicked(sender, args);
00674 }
00675
00676 //----------------------------------------------------------------------
00677
00678 void DirectXPage::OnBuySelectorClicked(Object^ sender, RoutedEventArgs^ /* args */)
00679 {
00680     Platform::String^ tag = dynamic_cast<Platform::String^>(dynamic_cast<Button^>(sender)->CommandParameter);
00681     StoreUnavailable->Visibility = ::Visibility::Collapsed;
00682
00683     if (tag == "MainApp")
00684     {
00685         if ((m_licenseInformation != nullptr) && m_licenseInformation->IsActive)
00686         {
00687             if (m_licenseInformation->IsTrial)
00688             {
00689 #ifdef USE_STORE_SIMULATOR
00690                 task<Platform::String^> purchaseTask(CurrentAppSimulator::RequestAppPurchaseAsync(false));
00691 #else
00692                 task<Platform::String^> purchaseTask(CurrentApp::RequestAppPurchaseAsync(false));
00693 #endif
00694                 purchaseTask.then([this](task<Platform::String^> previousTask)
00695                 {
00696                     try
00697                     {
00698                         // Try getting all exceptions from the continuation chain above this point.
00699                         previousTask.get();
00700                         if (m_licenseInformation->IsActive && !m_licenseInformation->IsTrial)
00701                         {
00702                             auto msgDlg = ref new MessageDialog("You successfully upgraded your app to the fully-licensed version.", "Information");
00703                             msgDlg->ShowAsync();
00704                         }
00705                         else
00706                         {
00707                             auto msgDlg = ref new MessageDialog("You still have a trial license for this app.", "Information");
00708                             msgDlg->ShowAsync();
00709                         }
00710                     }
00711                     catch (Platform::Exception^ exception)
00712                     {
00713                         if (exception->HResult == E_FAIL)
00714                         {
00715                             StoreUnavailable->Visibility = ::Visibility::Visible;
00716                         }
00717                     }
00718                 });
00719             }
00720         }
00721     }
00722     else
00723     {
00724         if ((m_licenseInformation != nullptr) && m_licenseInformation->IsActive && !m_licenseInformation->IsTrial)
00725         {
00726             if (!m_licenseInformation->ProductLicenses->Lookup(tag)->IsActive)
00727             {
00728 #ifdef USE_STORE_SIMULATOR
00729                 task<PurchaseResults^> purchaseTask(CurrentAppSimulator::RequestProductPurchaseAsync(tag));
00730 #else
00731                 task<PurchaseResults^> purchaseTask(CurrentApp::RequestProductPurchaseAsync(tag));
00732 #endif
00733                 purchaseTask.then([=](task<PurchaseResults^> previousTask)
00734                 {
00735                     try
00736                     {
00737                         // Try getting all exceptions from the continuation chain above this point
00738                         previousTask.get();
00739
00740                         if (m_licenseInformation->IsActive && !m_licenseInformation->IsTrial && m_licenseInformation->ProductLicenses->Lookup(tag)->IsActive)
00741                         {
00742                             auto msgDlg = ref new MessageDialog(
00743                                 Platform::String::Concat("You successfully upgraded your app with ",
00744                                 m_licenseInformation->ProductLicenses->Lookup(tag)->ProductId),
00745                                 "Information");
00746                             msgDlg->ShowAsync();
00747                         }
00748                         else
00749                         {
00750                             auto msgDlg = ref new MessageDialog("You did not upgrade your app.", "Information");
00751                             msgDlg->ShowAsync();
00752                         }
00753                     }
00754                     catch (Platform::Exception^ exception)
00755                     {
00756                         if (exception->HResult == E_FAIL)
00757                         {
00758                             StoreUnavailable->Visibility = ::Visibility::Visible;
00759                         }
00760                     }
00761                 });
00762             }
00763         }
00764     }
00765 }
00766
00767 //----------------------------------------------------------------------
00768
00769 void DirectXPage::OnChangeBackgroundButtonClicked(Object^ /* sender */, RoutedEventArgs^ /* args */)
00770 {
00771
00772     if ((m_licenseInformation != nullptr) && m_licenseInformation->IsActive)
00773     {
00774         if (m_licenseInformation->IsTrial ||
00775             (!m_licenseInformation->ProductLicenses->Lookup("NightBackground")->IsActive  &&
00776             !m_licenseInformation->ProductLicenses->Lookup("DayBackground")->IsActive))
00777         {
00778             if (m_playActive)
00779             {
00780                 m_main->PauseRequested();
00781             }
00782             ShowStoreFlyout();
00783         }
00784         else
00785         {
00786             m_main->CycleBackground();
00787         }
00788     }
00789 }
00790
00791 //----------------------------------------------------------------------
00792
00793 void DirectXPage::OnResetLicenseButtonClicked(Object^ /* sender */, RoutedEventArgs^ /* args */)
00794 {
00795 #ifdef USE_STORE_SIMULATOR
00796     ResetLicenseFromFile();
00797 #endif
00798     m_main->SetBackground(0);
00799 }
00800
00801 //----------------------------------------------------------------------
00802
00803 void DirectXPage::OptionalTrialUpgrade()
00804 {
00805     PurchaseUpgrade->Visibility = ::Visibility::Collapsed;
00806
00807     if (m_licenseInformation != nullptr)
00808     {
00809         if (m_licenseInformation->IsActive && m_licenseInformation->IsTrial)
00810         {
00811             if (m_listingInformation != nullptr)
00812             {
00813                 PurchaseMessage->Text =
00814                     "You are running a trial version. Purchase the full version for: " + m_listingInformation->FormattedPrice;
00815             }
00816             else
00817             {
00818                 PurchaseMessage->Text =
00819                     "You are running a trial version. Purchase the full version.";
00820             }
00821             PurchaseUpgrade->Visibility = ::Visibility::Visible;
00822         }
00823     }
00824 }
00825
00826 //----------------------------------------------------------------------
00827
00828 void DirectXPage::OnStoreReturnClicked(Object^ /* sender */, RoutedEventArgs^ /* args */)
00829 {
00830     StoreFlyout->IsOpen = false;
00831     StoreFlyout->Visibility = ::Visibility::Collapsed;
00832 }
00833
00834 //----------------------------------------------------------------------
00835
00836 void DirectXPage::OnLoadStoreClicked(Object^ /* sender */, RoutedEventArgs^ /* args */)
00837 {
00838     m_main->PauseRequested();
00839     ShowStoreFlyout();
00840 }
00841
00842 //----------------------------------------------------------------------
00843
00844 void DirectXPage::SetProductItems(
00845     ListingInformation^ listing,
00846     LicenseInformation^ license
00847     )
00848 {
00849     auto items = ref new Platform::Collections::Vector<Platform::Object^>();
00850     items->Append(ref new ProductItem(listing, license, "MainApp", true));
00851     items->Append(ref new ProductItem(listing, license, "AutoFire", false));
00852     items->Append(ref new ProductItem(listing, license, "NightBackground", false));
00853     items->Append(ref new ProductItem(listing, license, "DayBackground", false));
00854     ProductListView->ItemsSource = items;
00855     StoreUnavailable->Visibility = ::Visibility::Collapsed;
00856 }
00857
00858 //----------------------------------------------------------------------
00859 void DirectXPage::OnWindowSizeChanged(
00860     _In_ CoreWindow^ /* window */,
00861     _In_ WindowSizeChangedEventArgs^ /* args */
00862     )
00863 {
00864     StoreGrid->Height = Window::Current->Bounds.Height;
00865     StoreFlyout->HorizontalOffset = Window::Current->Bounds.Width - StoreGrid->Width;
00866 }
00867
00868 //----------------------------------------------------------------------
00869
00870 void DirectXPage::OnAppBarOpened(Object^ /* sender */, Object^ /* args */)
00871 {
00872     m_main->PauseRequested();
00873 }
00874
00875 //----------------------------------------------------------------------
00876
00877 void DirectXPage::ShowStoreFlyout()
00878 {
00879     StoreGrid->Height = Window::Current->Bounds.Height;
00880     StoreUnavailable->Visibility = ::Visibility::Collapsed;
00881     StoreFlyout->HorizontalOffset = Window::Current->Bounds.Width - StoreGrid->Width;
00882     StoreFlyout->IsOpen = true;
00883     StoreFlyout->Visibility = ::Visibility::Visible;
00884     GameAppBar->IsOpen = false;
00885 }
00886
00887 //----------------------------------------------------------------------
00888
00889
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Rectangle Member List

This is the complete list of members for Rectangle, including all inherited members.
AddChildElement(const std::shared_ptr< BaseElement > &childElement) | BaseElement |
ArrangeElements() | BaseElement | [virtual]
BaseElement() | BaseElement |
GetElementMargin() | BaseElement | [inline]
GetElementSize() | BaseElement | [inline]
GetIgnoreLayout() | BaseElement | [inline]
GetIsRenderPassNeeded() | BaseElement | [inline]
GetIsVisible() | BaseElement | [inline]
GetStrokeThickness() | Rectangle | [inline]
Initialize() override | Rectangle | [virtual]
m_brushColor | Rectangle | [private]
m_deviceResources | BaseElement | [protected]
m_elementMargin | BaseElement | [protected]
m_elementSize | BaseElement | [protected]
m_ignoreLayout | BaseElement | [protected]
m_isInitialized | BaseElement | [protected]
m_isLayoutHorizontal | BaseElement | [protected]
m_isRenderPassNeeded | BaseElement | [protected]
m_isVisible | BaseElement | [protected]
m_parentTranslation | BaseElement | [protected]
m_rect | Rectangle | [private]
m_strokeThickness | Rectangle | [private]
m_transformedTranslation | BaseElement | [protected]
m_transformMatrix | BaseElement | [protected]
m_transformRecalculationNeeded | BaseElement | [protected]
m_translation | BaseElement | [protected]
Rectangle(FLOAT width, FLOAT height, FLOAT strokeThickness, D2D1::ColorF brushColor) | Rectangle |
Render() override | Rectangle | [protected, virtual]
SetBrush(ID2D1SolidColorBrush *brush) | BaseElement |
SetElementMargin(ElementMargin margin) | BaseElement | [inline]
SetElementSize(Windows::Foundation::Numerics::float2 size) | BaseElement | [inline]
SetIgnoreLayout(bool ignoreLayout) | BaseElement | [inline]
SetIsVisible(bool visible) | BaseElement |
SetLayoutHorizontal(bool isLayoutHorizontal) | BaseElement | [inline]
SetParentTransform(Windows::Foundation::Numerics::float2 translation) | BaseElement |
SetRect(const D2D1_RECT_F &rect) | Rectangle | [inline]
SetTranslation(Windows::Foundation::Numerics::float2 translation) | BaseElement | [virtual]
TryRender() | BaseElement |
Update(const DX::StepTimer &timer, Windows::UI::Input::Spatial::SpatialPointerPose^cameraPose) | BaseElement | [virtual]
~BaseElement() | BaseElement | [virtual]
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ShareTarget Member List

This is the complete list of members for ShareTarget, including all inherited members.
AddContentValue(string title, string description=null) | ShareTarget | [inline, private]
AddQuickLink_Checked(object sender, RoutedEventArgs e) | ShareTarget | [inline, private]
AddQuickLink_Unchecked(object sender, RoutedEventArgs e) | ShareTarget | [inline, private]
dataFormatName | ShareTarget | [private]
DismissUI_Click(object sender, RoutedEventArgs e) | ShareTarget | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | ShareTarget | [inline, private]
NotifyUser(string strMessage, NotifyType type) | ShareTarget | [inline, private]
NotifyUserBackgroundThread(string message, NotifyType type) | ShareTarget | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | ShareTarget | [inline, protected]
OtherShareOperationMethodsSection_Checked(object sender, RoutedEventArgs e) | ShareTarget | [inline, private]
OtherShareOperationMethodsSection_Unchecked(object sender, RoutedEventArgs e) | ShareTarget | [inline, private]
OtherShareOperations_Tapped(object sender, TappedRoutedEventArgs e) | ShareTarget | [inline, private]
QuickLinkSectionLabel_Tapped(object sender, TappedRoutedEventArgs e) | ShareTarget | [inline, private]
ReportCompleted_Click(object sender, RoutedEventArgs e) | ShareTarget | [inline, private]
ReportDataRetrieved_Click(object sender, RoutedEventArgs e) | ShareTarget | [inline, private]
ReportErrorButton_Click(object sender, RoutedEventArgs e) | ShareTarget | [inline, private]
sharedApplicationLink | ShareTarget | [private]
sharedBitmapStreamRef | ShareTarget | [private]
sharedCustomData | ShareTarget | [private]
sharedDataContentSourceApplicationLink | ShareTarget | [private]
sharedDataContentSourceWebLink | ShareTarget | [private]
sharedDataDescription | ShareTarget | [private]
sharedDataLogoBackgroundColor | ShareTarget | [private]
sharedDataPackageFamilyName | ShareTarget | [private]
sharedDataSquare30x30Logo | ShareTarget | [private]
sharedDataTitle | ShareTarget | [private]
sharedHtmlFormat | ShareTarget | [private]
sharedResourceMap | ShareTarget | [private]
sharedStorageItems | ShareTarget | [private]
sharedText | ShareTarget | [private]
sharedThumbnailStreamRef | ShareTarget | [private]
sharedWebLink | ShareTarget | [private]
shareOperation | ShareTarget | [private]
shareQuickLinkId | ShareTarget | [private]
ShareTarget() | ShareTarget | [inline]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSensors/cpp/pch.h Source File

  • CustomSensors
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include <wrl\wrappers\corewrappers.h>
00011 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LinguisticServices/cs/Scenario4_CharacterGrouping.xaml.cs Source File

  • LinguisticServices
  • cs

Scenario4_CharacterGrouping.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.IO;
00004 using System.Linq;
00005 using System.Runtime.InteropServices.WindowsRuntime;
00006 using System.Text;
00007 using Windows.Foundation;
00008 using Windows.Foundation.Collections;
00009 using Windows.Globalization;
00010 using Windows.Globalization.Collation;
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Controls.Primitives;
00014 using Windows.UI.Xaml.Data;
00015 using Windows.UI.Xaml.Input;
00016 using Windows.UI.Xaml.Media;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026     public sealed partial class Scenario4_CharacterGrouping : Page
00027     {
00028         MainPage rootPage = MainPage.Current;
00029         CharacterGroupings ActiveGroupings = null;
00030         Dictionary<string, UIElement> groups = new Dictionary<string, UIElement>();
00031         static readonly string GlobeString = "\U0001F310";
00032
00033         public Scenario4_CharacterGrouping()
00034         {
00035             this.InitializeComponent();
00036         }
00037
00038         void AddGroup(string label, UIElement element)
00039         {
00040             groups.Add(label, element);
00041             GroupingsGrid.Items.Add(element);
00042         }
00043
00044         public void GetGroups_Click(object sender, RoutedEventArgs e)
00045         {
00046             rootPage.NotifyUser("", NotifyType.StatusMessage);
00047             if (LanguageText.Text == "Default")
00048             {
00049                 ActiveGroupings = new CharacterGroupings();
00050             }
00051             else if (Windows.Globalization.Language.IsWellFormed(LanguageText.Text))
00052             {
00053                 ActiveGroupings = new CharacterGroupings(LanguageText.Text);
00054             }
00055             else
00056             {
00057                 rootPage.NotifyUser("Invalid language tag.", NotifyType.ErrorMessage);
00058                 return;
00059             }
00060
00061             GroupingsGrid.Items.Clear();
00062             groups.Clear();
00063             foreach (CharacterGrouping grouping in ActiveGroupings)
00064             {
00065                 // Save the "other" group for the end.
00066                 if (!string.IsNullOrEmpty(grouping.Label))
00067                 {
00068                     AddGroup(grouping.Label, new TextBlock { Text = grouping.Label });
00069                 }
00070             }
00071             AddGroup(GlobeString, new SymbolIcon { Symbol = Symbol.Globe });
00072         }
00073
00074         public void AssignGroup_Click(object sender, RoutedEventArgs e)
00075         {
00076             rootPage.NotifyUser("", NotifyType.StatusMessage);
00077             if (ActiveGroupings == null)
00078             {
00079                 rootPage.NotifyUser("Select a language first.", NotifyType.ErrorMessage);
00080                 return;
00081             }
00082             if (String.IsNullOrEmpty(CandidateText.Text))
00083             {
00084                 rootPage.NotifyUser("Enter text to assign to a group.", NotifyType.ErrorMessage);
00085                 return;
00086             }
00087             string label = ActiveGroupings.Lookup(CandidateText.Text);
00088             if (!groups.TryGetValue(label, out UIElement element))
00089             {
00090                 label = GlobeString;
00091                 element = groups[GlobeString];
00092             }
00093             GroupingsGrid.SelectedItem = element;
00094             GroupingResult.Text = $"Group \"{label}\"";
00095             element.StartBringIntoView();
00096         }
00097     }
00098 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackButton/cpp/SecondaryPage.xaml.h Source File

  • BackButton
  • cpp

SecondaryPage.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // SecondaryPage.xaml.h
00003 // Declaration of the SecondaryPage class
00004 //
00005
00006 #pragma once
00007
00008 #include "SecondaryPage.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     /// <summary>
00013     /// An empty page that can be used on its own or navigated to within a Frame.
00014     /// </summary>
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class SecondaryPage sealed
00017     {
00018     public:
00019         SecondaryPage();
00020
00021     protected:
00022         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00023
00024     };
00025 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Client/RpcClientApi.cpp Source File

  • CustomCapability
  • Service
  • Client

RpcClientApi.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012
00013 #pragma push_macro("WINAPI_FAMILY")
00014 #undef WINAPI_FAMILY
00015 #define WINAPI_FAMILY WINAPI_FAMILY_DESKTOP_APP
00016 #include "RpcClient.h"
00017 #pragma pop_macro("WINAPI_FAMILY")
00018
00019 #include "RpcClientApi.h"
00020
00021 extern "C" {
00022 typedef struct _RPC_CLIENT {
00023     RpcClient* RpcClient;
00024 } RPC_CLIENT, *PRPC_CLIENT;
00025 }
00026
00027 RpcClient* RetriveRpcClientFromHandle(RPC_CLIENT_HANDLE RpcClientHandle);
00028
00029 // Opens metering RPC endpoint
00030 __int64 RpcClientInitialize(RPC_CLIENT_HANDLE* RpcClientHandle) {
00031     __int64 ret;
00032     PRPC_CLIENT rpcClientStruct = NULL;
00033     if (RpcClientHandle == NULL) {
00034         ret = ERROR_INVALID_PARAMETER;
00035         goto error;
00036     }
00037
00038     rpcClientStruct = new RPC_CLIENT();
00039     if (rpcClientStruct == NULL) {
00040         ret = ERROR_NOT_ENOUGH_MEMORY;
00041         goto error;
00042     }
00043     rpcClientStruct->RpcClient = new RpcClient();
00044     if (rpcClientStruct->RpcClient == NULL) {
00045         ret = ERROR_NOT_ENOUGH_MEMORY;
00046         goto error;
00047     }
00048
00049     ret = rpcClientStruct->RpcClient->Initialize();
00050
00051 error:
00052     if (ret != 0) {
00053         if (rpcClientStruct != NULL) {
00054             if (rpcClientStruct->RpcClient != NULL) {
00055                 delete rpcClientStruct->RpcClient;
00056             }
00057             delete rpcClientStruct;
00058         }
00059     }
00060     else {
00061         *RpcClientHandle = rpcClientStruct;
00062     }
00063
00064     return ret;
00065 }
00066
00067 // Starts metering service and blocks till metering is stopped
00068 __int64 StartMeteringAndWaitForStop(RPC_CLIENT_HANDLE RpcClientHandle, __int64 samplePeriod) {
00069     RpcClient* client;
00070     if (RpcClientHandle == NULL) {
00071         return ERROR_INVALID_PARAMETER;
00072     }
00073
00074     client = RetriveRpcClientFromHandle(RpcClientHandle);
00075     if (client == NULL) {
00076         return ERROR_INVALID_HANDLE;
00077     }
00078
00079     return client->StartMeteringAndWaitForStop(samplePeriod);
00080 }
00081
00082 // Sends stop metering to RPC Service
00083 __int64 StopMeteringData(RPC_CLIENT_HANDLE RpcClientHandle) {
00084     RpcClient* client;
00085     if (RpcClientHandle == NULL) {
00086         return ERROR_INVALID_PARAMETER;
00087     }
00088
00089     client = RetriveRpcClientFromHandle(RpcClientHandle);
00090     if (client == NULL) {
00091         return ERROR_INVALID_HANDLE;
00092     }
00093
00094     return client->StopMetering();
00095 }
00096
00097 // Updates sample rate of metering RPC Service
00098 __int64 SetSampleRate(RPC_CLIENT_HANDLE RpcClientHandle, int rate) {
00099     RpcClient* client;
00100     if (RpcClientHandle == NULL) {
00101         return ERROR_INVALID_PARAMETER;
00102     }
00103
00104     client = RetriveRpcClientFromHandle(RpcClientHandle);
00105     if (client == NULL) {
00106         return ERROR_INVALID_HANDLE;
00107     }
00108
00109     return client->SetSampleRate(rate);
00110 }
00111
00112 // Get the most recent metering data received from the metering RPC service
00113 __int64 GetMeteringData(RPC_CLIENT_HANDLE RpcClientHandle, __int64* MeteringData) {
00114     RpcClient* client;
00115     if (RpcClientHandle == NULL || MeteringData == NULL) {
00116         return ERROR_INVALID_PARAMETER;
00117     }
00118
00119     client = RetriveRpcClientFromHandle(RpcClientHandle);
00120     if (client == NULL) {
00121         return ERROR_INVALID_HANDLE;
00122     }
00123     *MeteringData = client->MeteringData;
00124     return ERROR_SUCCESS;
00125 }
00126
00127 // Closes metering RPC endpoint
00128 __int64 RpcClientClose(RPC_CLIENT_HANDLE RpcClientHandle) {
00129     RpcClient* client;
00130     if (RpcClientHandle == NULL) {
00131         return ERROR_INVALID_PARAMETER;
00132     }
00133
00134     client = RetriveRpcClientFromHandle(RpcClientHandle);
00135     if (client == NULL) {
00136         return ERROR_INVALID_HANDLE;
00137     }
00138     delete client;
00139     delete RpcClientHandle;
00140
00141     return ERROR_SUCCESS;
00142 }
00143
00144 // Retrieve the metering callback count for the current metering session
00145 __int64 GetCallbackCount(RPC_CLIENT_HANDLE RpcClientHandle, __int64* MeteringData)
00146 {
00147     RpcClient* client;
00148     if (RpcClientHandle == NULL || MeteringData == NULL) {
00149         return ERROR_INVALID_PARAMETER;
00150     }
00151
00152     client = RetriveRpcClientFromHandle(RpcClientHandle);
00153     if (client == NULL) {
00154         return ERROR_INVALID_HANDLE;
00155     }
00156
00157     *MeteringData = client->CallbackCount;
00158     return ERROR_SUCCESS;
00159 }
00160
00161 RpcClient* RetriveRpcClientFromHandle(RPC_CLIENT_HANDLE RpcClientHandle) {
00162     return ((PRPC_CLIENT)RpcClientHandle)->RpcClient;
00163 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/Scenario_PauseAsync.xaml.cpp Source File

  • SpeechRecognitionAndSynthesis
  • cpp

Scenario_PauseAsync.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario_PauseAsync.xaml.h"
00014 #include "AudioCapturePermissions.h"
00015
00016 using namespace SDKTemplate;
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::ApplicationModel::Resources::Core;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Media::SpeechRecognition;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Controls::Primitives;
00028 using namespace Windows::UI::Xaml::Data;
00029 using namespace Windows::UI::Xaml::Input;
00030 using namespace Windows::UI::Xaml::Media;
00031 using namespace Windows::UI::Xaml::Navigation;
00032
00033 Scenario_PauseAsync::Scenario_PauseAsync() : rootPage(MainPage::Current)
00034 {
00035     InitializeComponent();
00036 }
00037
00038 /// <summary>
00039 /// Upon entering the scenario, ensure that we have permissions to use the Microphone. This may entail popping up
00040 /// a dialog to the user on Desktop systems. Only enable functionality once we've gained that permission in order to
00041 /// prevent errors from occurring when using the SpeechRecognizer. If speech is not a primary input mechanism, developers
00042 /// should consider disabling appropriate parts of the UI if the user does not have a recording device, or does not allow
00043 /// audio input.
00044 /// </summary>
00045 /// <param name="e">Unused navigation parameters</param>
00046 void Scenario_PauseAsync::OnNavigatedTo(NavigationEventArgs^ e)
00047 {
00048     Page::OnNavigatedTo(e);
00049
00050     // Keep track of the UI thread dispatcher, as speech events will come in on a separate thread.
00051     dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
00052
00053     // Prompt the user for permission to access the microphone. This request will only happen
00054     // once, it will not re-prompt if the user rejects the permission.
00055     create_task(AudioCapturePermissions::RequestMicrophonePermissionAsync(), task_continuation_context::use_current())
00056         .then([this](bool permissionGained)
00057     {
00058         if (permissionGained)
00059         {
00060             this->btnRecognize->IsEnabled = true;
00061
00062       InitializeRecognizer();
00063         }
00064         else
00065         {
00066             this->resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00067             this->resultTextBlock->Text = L"Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
00068         }
00069     });
00070 }
00071
00072 /// <summary>
00073 /// Creates a SpeechRecognizer instance and initializes the grammar.
00074 /// </summary>
00075 void Scenario_PauseAsync::InitializeRecognizer()
00076 {
00077     // If reinitializing the recognizer (ie, changing the speech language), clean up the old recognizer first.
00078     // Avoid doing this while the recognizer is active by disabling the ability to change languages while listening.
00079     if (this->speechRecognizer != nullptr)
00080     {
00081         speechRecognizer->StateChanged -= stateChangedToken;
00082         speechRecognizer->ContinuousRecognitionSession->Completed -= continuousRecognitionCompletedToken;
00083         speechRecognizer->ContinuousRecognitionSession->ResultGenerated -= continuousRecognitionResultGeneratedToken;
00084
00085         delete this->speechRecognizer;
00086         this->speechRecognizer = nullptr;
00087     }
00088
00089     try
00090     {
00091         this->speechRecognizer = ref new SpeechRecognizer();
00092
00093         // Provide feedback to the user about the state of the recognizer. This can be used to provide visual feedback in the form
00094         // of an audio indicator to help the user understand whether they're being heard.
00095         stateChangedToken = speechRecognizer->StateChanged +=
00096             ref new TypedEventHandler<
00097             SpeechRecognizer ^,
00098             SpeechRecognizerStateChangedEventArgs ^>(
00099                 this,
00100                 &Scenario_PauseAsync::SpeechRecognizer_StateChanged);
00101
00102     // It's not valid to pause a list grammar recognizer and recompile the constraints without at least one
00103     // constraint in place, so create a permanent constraint.
00104     auto goHomeConstraint = ref new SpeechRecognitionListConstraint(ref new Vector<String^>( { L"Go Home" }), L"gohome");
00105
00106         // These speech recognition constraints will be added and removed from the recognizer.
00107         emailConstraint = ref new SpeechRecognitionListConstraint(ref new Vector<String^>({ L"Send email" }), L"email");
00108         phoneConstraint = ref new SpeechRecognitionListConstraint(ref new Vector<String^>({ L"Call phone" }), L"phone");
00109
00110         // Build a command-list grammar. Commands should ideally be drawn from a resource file for localization, and
00111         // be grouped into tags for alternate forms of the same command.
00112     speechRecognizer->Constraints->Append(goHomeConstraint);
00113         speechRecognizer->Constraints->Append(emailConstraint);
00114
00115         create_task(speechRecognizer->CompileConstraintsAsync(), task_continuation_context::use_current())
00116             .then([this](task<SpeechRecognitionCompilationResult^> previousTask)
00117         {
00118             SpeechRecognitionCompilationResult^ compilationResult = previousTask.get();
00119
00120             if (compilationResult->Status != SpeechRecognitionResultStatus::Success)
00121             {
00122                 // Disable the recognition buttons.
00123                 btnRecognize->IsEnabled = false;
00124
00125                 // Let the user know that the grammar didn't compile properly.
00126                 rootPage->NotifyUser(L"Grammar Compilation Failed: " + compilationResult->Status.ToString(), NotifyType::ErrorMessage);
00127             }
00128             else
00129             {
00130                 // Handle continuous recognition events. Completed fires when various error states occur. ResultGenerated fires when
00131                 // some recognized phrases occur, or the garbage rule is hit.
00132                 continuousRecognitionCompletedToken = speechRecognizer->ContinuousRecognitionSession->Completed +=
00133                     ref new TypedEventHandler<
00134                     SpeechContinuousRecognitionSession ^,
00135                     SpeechContinuousRecognitionCompletedEventArgs ^>(
00136                         this,
00137                         &Scenario_PauseAsync::ContinuousRecognitionSession_Completed);
00138                 continuousRecognitionResultGeneratedToken = speechRecognizer->ContinuousRecognitionSession->ResultGenerated +=
00139                     ref new TypedEventHandler<
00140                     SpeechContinuousRecognitionSession ^,
00141                     SpeechContinuousRecognitionResultGeneratedEventArgs ^>(
00142                         this,
00143                         &Scenario_PauseAsync::ContinuousRecognitionSession_ResultGenerated);
00144
00145                 btnRecognize->IsEnabled = true;
00146
00147                 resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00148             }
00149         }, task_continuation_context::use_current());
00150
00151
00152     }
00153     catch (Exception^ ex)
00154     {
00155         auto messageDialog = ref new Windows::UI::Popups::MessageDialog(ex->Message, L"Exception");
00156         create_task(messageDialog->ShowAsync());
00157     }
00158 }
00159
00160 /// <summary>
00161 /// Upon leaving, clean up the speech recognizer. Ensure we aren't still listening, and disable the event
00162 /// handlers to prevent leaks.
00163 /// </summary>
00164 /// <param name="e">Unused navigation parameters.</param>
00165 void Scenario_PauseAsync::OnNavigatedFrom(NavigationEventArgs^ e)
00166 {
00167     Page::OnNavigatedFrom(e);
00168
00169     this->resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00170
00171     if (speechRecognizer != nullptr)
00172     {
00173         // If we're currently active, start a cancellation task, and wait for it to finish before shutting down
00174         // the recognizer.
00175         Concurrency::task<void> cleanupTask;
00176         if (speechRecognizer->State != SpeechRecognizerState::Idle)
00177         {
00178             cleanupTask = create_task(speechRecognizer->ContinuousRecognitionSession->CancelAsync(), task_continuation_context::use_current());
00179         }
00180         else
00181         {
00182             cleanupTask = create_task([]() {}, task_continuation_context::use_current());
00183         }
00184
00185         cleanupTask.then([this]()
00186         {
00187             recognizeButtonText->Text = L" Continuous Recognition";
00188
00189             speechRecognizer->StateChanged -= stateChangedToken;
00190             speechRecognizer->ContinuousRecognitionSession->Completed -= continuousRecognitionCompletedToken;
00191             speechRecognizer->ContinuousRecognitionSession->ResultGenerated -= continuousRecognitionResultGeneratedToken;
00192
00193             delete speechRecognizer;
00194             speechRecognizer = nullptr;
00195         }, task_continuation_context::use_current());
00196     }
00197 }
00198
00199 /// <summary>
00200 /// Begin recognition, or finish the recognition session.
00201 /// </summary>
00202 /// <param name="sender">The button that generated this event</param>
00203 /// <param name="e">Unused event details</param>
00204 void Scenario_PauseAsync::Recognize_Click(Object^ sender, RoutedEventArgs^ e)
00205 {
00206   EnableUI(false);
00207     // The recognizer can only start listening in a continuous fashion if the recognizer is currently idle.
00208     // This prevents an exception from occurring.
00209     if (speechRecognizer->State == SpeechRecognizerState::Idle)
00210     {
00211         create_task(speechRecognizer->ContinuousRecognitionSession->StartAsync(), task_continuation_context::use_current())
00212             .then([this](task<void> startAsyncTask)
00213         {
00214             try
00215             {
00216                 // Retreive any exceptions that may have been generated by StartAsync.
00217                 startAsyncTask.get();
00218
00219                 recognizeButtonText->Text = L" Stop Continuous Recognition";
00220                 infoBoxes->Visibility = Windows::UI::Xaml::Visibility::Visible;
00221             }
00222             catch (Exception^ exception)
00223             {
00224                 auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, L"Exception");
00225                 create_task(messageDialog->ShowAsync());
00226             }
00227     }).then([this]() {
00228       EnableUI(true);
00229     });
00230     }
00231     else
00232     {
00233         // Cancelling recognition prevents any currently recognized speech from
00234         // generating a ResultGenerated event. StopAsync() will allow the final session to
00235         // complete.
00236         recognizeButtonText->Text = L" Continuous Recognition";
00237         infoBoxes->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00238
00239     create_task(speechRecognizer->ContinuousRecognitionSession->CancelAsync()).then([this]() {
00240       btnRecognize->IsEnabled = true;
00241       btnEmailGrammar->IsEnabled = false;
00242       btnPhoneGrammar->IsEnabled = false;
00243     });
00244     }
00245
00246 }
00247
00248 /// <summary>
00249 /// Adds or removes the 'email' constraint from the recognizer.
00250 /// </summary>
00251 /// <param name="sender">The button that generated this event</param>
00252 /// <param name="e">Unused event details</param>
00253 void Scenario_PauseAsync::EmailButton_Click(Object^ sender, RoutedEventArgs^ e)
00254 {
00255     // Update UI, disabling buttons so the user can't interrupt.
00256     EnableUI(false);
00257     ULONGLONG start = GetTickCount64();
00258
00259     try
00260     {
00261         // Pause the session. This allows you to update the grammars without stopping the
00262         // session and potentially losing audio and a recognition.
00263         create_task(speechRecognizer->ContinuousRecognitionSession->PauseAsync(), task_continuation_context::use_current())
00264             .then([this](task<void> startAsyncTask)
00265         {
00266             // Update the grammar appropriately.
00267             if (emailButtonText->Text->Equals(L"Remove 'email' grammar"))
00268             {
00269                 emailButtonText->Text = L"Updating...";
00270                 unsigned int index;
00271                 if (speechRecognizer->Constraints->IndexOf(emailConstraint, &index))
00272                 {
00273                     speechRecognizer->Constraints->RemoveAt(index);
00274                 }
00275                 newButtonText = L"Add 'email' grammar";
00276                 emailInfoTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00277             }
00278             else
00279             {
00280                 emailButtonText->Text = L"Updating...";
00281                 speechRecognizer->Constraints->Append(emailConstraint);
00282                 newButtonText = L"Remove 'email' grammar";
00283                 emailInfoTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00284             }
00285
00286             // Recompile with the new constraints and resume the session again.
00287             return create_task(speechRecognizer->CompileConstraintsAsync());
00288         }).then([start, this](task<Windows::Media::SpeechRecognition::SpeechRecognitionCompilationResult^> result)
00289         {
00290             SpeechRecognitionCompilationResult^ compilationResult = result.get();
00291
00292             if (compilationResult->Status != SpeechRecognitionResultStatus::Success)
00293             {
00294                 // Disable the recognition buttons.
00295                 EnableUI(false);
00296
00297                 // Let the user know that the grammar didn't compile properly.
00298                 resultTextBlock->Text = L"Unable to compile grammar.";
00299
00300                 create_task(speechRecognizer->ContinuousRecognitionSession->CancelAsync());
00301             }
00302             else
00303             {
00304                 speechRecognizer->ContinuousRecognitionSession->Resume();
00305
00306                 // For diagnostic purposes, display the amount of time it took to update the grammar.
00307                 ULONGLONG end = GetTickCount64();
00308                 msTextBlock->Text = L"Grammar update took " + (end - start) + L" ms";
00309
00310                 // Restore the original UI state.
00311                 EnableUI(true);
00312                 emailButtonText->Text = newButtonText;
00313             }
00314         });
00315     }
00316     catch(Exception^ ex)
00317     {
00318         auto messageDialog = ref new Windows::UI::Popups::MessageDialog(ex->Message, L"Exception");
00319         create_task(messageDialog->ShowAsync());
00320     }
00321 }
00322
00323 /// <summary>
00324 /// Adds or removes the 'phone' constraint from the recognizer.
00325 /// </summary>
00326 /// <param name="sender">The button that generated this event</param>
00327 /// <param name="e">Unused event details</param>
00328 void Scenario_PauseAsync::PhoneButton_Click(Object^ sender, RoutedEventArgs^ e)
00329 {
00330     // Update UI, disabling buttons so the user can't interrupt.
00331     EnableUI(false);
00332     ULONGLONG start = GetTickCount64();
00333
00334     try
00335     {
00336         // Pause the session. This allows you to update the grammars without stopping the
00337         // session and potentially losing audio and a recognition.
00338         create_task(speechRecognizer->ContinuousRecognitionSession->PauseAsync(), task_continuation_context::use_current())
00339             .then([this](task<void> startAsyncTask)
00340         {
00341             // Update the grammar appropriately.
00342             if (phoneButtonText->Text->Equals(L"Remove 'phone' grammar"))
00343             {
00344                 phoneButtonText->Text = L"Updating...";
00345                 unsigned int index;
00346                 if (speechRecognizer->Constraints->IndexOf(phoneConstraint, &index))
00347                 {
00348                     speechRecognizer->Constraints->RemoveAt(index);
00349                 }
00350                 newButtonText = L"Add 'phone' grammar";
00351                 phoneInfoTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00352             }
00353             else
00354             {
00355                 phoneButtonText->Text = L"Updating...";
00356                 speechRecognizer->Constraints->Append(phoneConstraint);
00357                 newButtonText = L"Remove 'phone' grammar";
00358                 phoneInfoTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00359             }
00360
00361             // Recompile with the new constraints and resume the session again.
00362             return create_task(speechRecognizer->CompileConstraintsAsync());
00363         }).then([start, this](task<Windows::Media::SpeechRecognition::SpeechRecognitionCompilationResult^> result)
00364         {
00365             SpeechRecognitionCompilationResult^ compilationResult = result.get();
00366
00367             if (compilationResult->Status != SpeechRecognitionResultStatus::Success)
00368             {
00369                 // Disable the recognition buttons.
00370                 EnableUI(false);
00371
00372                 // Let the user know that the grammar didn't compile properly.
00373                 resultTextBlock->Text = L"Unable to compile grammar.";
00374
00375                 create_task(speechRecognizer->ContinuousRecognitionSession->CancelAsync());
00376             }
00377             else
00378             {
00379                 speechRecognizer->ContinuousRecognitionSession->Resume();
00380
00381                 // For diagnostic purposes, display the amount of time it took to update the grammar.
00382                 ULONGLONG end = GetTickCount64();
00383                 msTextBlock->Text = L"Grammar update took " + (end - start) + " ms";
00384
00385                 // Restore the original UI state.
00386                 EnableUI(true);
00387                 phoneButtonText->Text = newButtonText;
00388             }
00389         });
00390     }
00391     catch (Exception^ ex)
00392     {
00393         auto messageDialog = ref new Windows::UI::Popups::MessageDialog(ex->Message, L"Exception");
00394         create_task(messageDialog->ShowAsync());
00395     }
00396 }
00397
00398 /// <summary>
00399 /// Provide feedback to the user based on whether the recognizer is receiving their voice input.
00400 /// </summary>
00401 /// <param name="sender">The recognizer that is currently running.</param>
00402 /// <param name="args">The current state of the recognizer.</param>
00403 void Scenario_PauseAsync::SpeechRecognizer_StateChanged(SpeechRecognizer ^sender, SpeechRecognizerStateChangedEventArgs ^args)
00404 {
00405     dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00406     {
00407         rootPage->NotifyUser(L"Speech recognizer state: " + args->State.ToString(), NotifyType::StatusMessage);
00408     }));
00409 }
00410
00411 /// <summary>
00412 /// Handle events fired when error conditions occur, such as the microphone becoming unavailable, or if
00413 /// some transient issues occur.
00414 /// </summary>
00415 /// <param name="sender">The continuous recognition session</param>
00416 /// <param name="args">The state of the recognizer</param>
00417 void Scenario_PauseAsync::ContinuousRecognitionSession_Completed(SpeechContinuousRecognitionSession ^sender, SpeechContinuousRecognitionCompletedEventArgs ^args)
00418 {
00419     if (args->Status != SpeechRecognitionResultStatus::Success)
00420     {
00421         dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00422         {
00423             rootPage->NotifyUser(L"Continuous Recognition Completed: " + args->Status.ToString(), NotifyType::ErrorMessage);
00424             recognizeButtonText->Text = L" Continuous Recognition";
00425
00426             btnEmailGrammar->IsEnabled = false;
00427             btnPhoneGrammar->IsEnabled = false;
00428         }));
00429     }
00430 }
00431
00432 /// <summary>
00433 /// Handle events fired when a result is generated. This may include a garbage rule that fires when general room noise
00434 /// or side-talk is captured (this will have a confidence of Rejected typically, but may occasionally match a rule with
00435 /// low confidence).
00436 /// </summary>
00437 /// <param name="sender">The Recognition session that generated this result</param>
00438 /// <param name="args">Details about the recognized speech</param>
00439 void Scenario_PauseAsync::ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession ^sender, SpeechContinuousRecognitionResultGeneratedEventArgs ^args)
00440 {
00441     // The garbage rule will not have a tag associated with it, the other rules will return a string matching the tag provided
00442     // when generating the grammar.
00443     String^ tag = L"unknown";
00444     if (args->Result->Constraint != nullptr)
00445     {
00446         tag = args->Result->Constraint->Tag;
00447     }
00448
00449     // Developers may decide to use per-phrase confidence levels in order to tune the behavior of their
00450     // grammar based on testing.
00451     if (args->Result->Confidence == SpeechRecognitionConfidence::Medium ||
00452         args->Result->Confidence == SpeechRecognitionConfidence::High)
00453     {
00454         dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args, tag]()
00455         {
00456             resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00457             resultTextBlock->Text = L"Heard: '" + args->Result->Text + L"', Tag( '" + tag + L"', Confidence: " + args->Result->Confidence.ToString() + L")";
00458         }));
00459     }
00460     else
00461     {
00462         // In some scenarios, a developer may choose to ignore giving the user feedback in this case, if speech
00463         // is not the primary input mechanism for the application.
00464         dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args, tag]()
00465         {
00466             resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00467             resultTextBlock->Text = L"Sorry, I didn't catch that. (Heard: '" + args->Result->Text + L"', (Tag: '" + tag + L"', Confidence: " + args->Result->Confidence.ToString() + L")";
00468         }));
00469     }
00470 }
00471
00472 /// <summary>
00473 /// Handles enabling/disabling all buttons in the scenario.
00474 /// </summary>
00475 /// <param name="newState">The new setting for the buttons.</param>
00476 void Scenario_PauseAsync::EnableUI(bool newState)
00477 {
00478     btnRecognize->IsEnabled = newState;
00479     btnEmailGrammar->IsEnabled = newState;
00480     btnPhoneGrammar->IsEnabled = newState;
00481 }
00482
Generated on Fri Nov 15 2024 22:21:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LinguisticServices/cppwinrt/SampleConfiguration.h Source File

  • LinguisticServices
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Projection/cs/ProjectionViewPage.xaml.cs Source File

  • Projection
  • cs

ProjectionViewPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using SecondaryViewsHelpers;
00014 using System;
00015 using Windows.UI.Core;
00016 using Windows.UI.ViewManagement;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00022
00023 namespace SDKSample
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class ProjectionViewPage : Page
00029     {
00030         ViewLifetimeControl thisViewControl;
00031         CoreDispatcher mainDispatcher;
00032         int mainViewId;
00033
00034         public ProjectionViewPage()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         protected override void OnNavigatedTo(NavigationEventArgs e)
00040         {
00041             var initData = (ProjectionViewPageInitializationData)e.Parameter;
00042
00043             // The ViewLifetimeControl is a convenient wrapper that ensures the
00044             // view is closed only when the user is done with it
00045             thisViewControl = initData.ProjectionViewPageControl;
00046             mainDispatcher = initData.MainDispatcher;
00047             mainViewId = initData.MainViewId;
00048
00049             // Listen for when it's time to close this view
00050             thisViewControl.Released += thisViewControl_Released;
00051         }
00052
00053         private async void thisViewControl_Released(object sender, EventArgs e)
00054         {
00055             // There are two major cases where this event will get invoked:
00056             // 1. The view goes unused for some time, and the system cleans it up
00057             // 2. The app calls "StopProjectingAsync"
00058             thisViewControl.Released -= thisViewControl_Released;
00059             await mainDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00060             {
00061                 MainPage.Current.ProjectionViewPageControl = null;
00062             });
00063             Window.Current.Close();
00064         }
00065
00066         private async void SwapViews_Click(object sender, RoutedEventArgs e)
00067         {
00068             // The view might arrive on the wrong display. The user can
00069             // easily swap the display on which the view appears
00070             thisViewControl.StartViewInUse();
00071             await ProjectionManager.SwapDisplaysForViewsAsync(
00072                 ApplicationView.GetForCurrentView().Id,
00073                 mainViewId
00074             );
00075             thisViewControl.StopViewInUse();
00076         }
00077
00078         private async void StopProjecting_Click(object sender, RoutedEventArgs e)
00079         {
00080             // There may be cases to end the projection from the projected view
00081             // (e.g. the presentation hosted in that view concludes)
00082             thisViewControl.StartViewInUse();
00083             await ProjectionManager.StopProjectingAsync(
00084                 ApplicationView.GetForCurrentView().Id,
00085                 mainViewId);
00086             thisViewControl.StopViewInUse();
00087         }
00088     }
00089 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/LiveTiles/AdaptiveTemplates/HintPresentation/People/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • LiveTiles
  • AdaptiveTemplates
  • HintPresentation
  • People

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Xaml.Controls;
00002
00003 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00004
00005 namespace Notifications.ScenarioPages.LiveTiles.AdaptiveTemplates.HintPresentation.People
00006 {
00007     /// <summary>
00008     /// An empty page that can be used on its own or navigated to within a Frame.
00009     /// </summary>
00010     public sealed partial class ScenarioElement : UserControl
00011     {
00012         public ScenarioElement()
00013         {
00014             this.InitializeComponent();
00015
00016             // Because different densities might be able to display more, we just set tons of text wrapped to make sure it overflows at some point
00017             updateFourTilesControl.SetTilePayload($@"
00018                 <tile>
00019                     <visual>
00020
00021                         <binding template='TileMedium' hint-presentation='people'>
00022                             <image src='Assets/Photos/1.jpg'/>
00023                             <image src='Assets/Photos/2.jpg'/>
00024                             <image src='Assets/Photos/3.jpg'/>
00025                             <image src='Assets/Photos/4.jpg'/>
00026                             <image src='Assets/Photos/5.jpg'/>
00027                             <image src='Assets/Photos/6.jpg'/>
00028                             <image src='Assets/Photos/7.jpg'/>
00029                             <image src='Assets/Photos/8.jpg'/>
00030                             <image src='Assets/Photos/9.jpg'/>
00031                             <image src='Assets/Photos/10.jpg'/>
00032                         </binding>
00033
00034                         <binding template='TileWide' hint-presentation='people'>
00035                             <image src='Assets/Photos/1.jpg'/>
00036                             <image src='Assets/Photos/2.jpg'/>
00037                             <image src='Assets/Photos/3.jpg'/>
00038                             <image src='Assets/Photos/4.jpg'/>
00039                             <image src='Assets/Photos/5.jpg'/>
00040                             <image src='Assets/Photos/6.jpg'/>
00041                             <image src='Assets/Photos/7.jpg'/>
00042                             <image src='Assets/Photos/8.jpg'/>
00043                             <image src='Assets/Photos/9.jpg'/>
00044                             <image src='Assets/Photos/10.jpg'/>
00045                         </binding>
00046
00047                         <binding template='TileLarge' hint-presentation='people'>
00048                             <image src='Assets/Photos/1.jpg'/>
00049                             <image src='Assets/Photos/2.jpg'/>
00050                             <image src='Assets/Photos/3.jpg'/>
00051                             <image src='Assets/Photos/4.jpg'/>
00052                             <image src='Assets/Photos/5.jpg'/>
00053                             <image src='Assets/Photos/6.jpg'/>
00054                             <image src='Assets/Photos/7.jpg'/>
00055                             <image src='Assets/Photos/8.jpg'/>
00056                             <image src='Assets/Photos/9.jpg'/>
00057                             <image src='Assets/Photos/10.jpg'/>
00058                         </binding>
00059
00060                     </visual>
00061                 </tile>");
00062         }
00063     }
00064 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VertexPositionTexture Member List

This is the complete list of members for VertexPositionTexture, including all inherited members.
pos | VertexPositionTexture
uv | VertexPositionTexture
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Tasks/pch.h Source File

  • Geolocation
  • cppwinrt
  • Tasks

pch.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002 #include <unknwn.h>
00003 #include <winrt/Windows.ApplicationModel.Background.h>
00004 #include <winrt/Windows.Data.Json.h>
00005 #include <winrt/Windows.Data.Xml.Dom.h>
00006 #include <winrt/Windows.Devices.Geolocation.h>
00007 #include <winrt/Windows.Devices.Geolocation.Geofencing.h>
00008 #include <winrt/Windows.Foundation.h>
00009 #include <winrt/Windows.Foundation.Collections.h>
00010 #include <winrt/Windows.Globalization.DateTimeFormatting.h>
00011 #include <winrt/Windows.Storage.h>
00012 #include <winrt/Windows.UI.Notifications.h>
00013 #include <ctime>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: GlobalizationPreferences/cppwinrt/Scenario2_Lang.h Source File

  • GlobalizationPreferences
  • cppwinrt

Scenario2_Lang.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Lang.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_Lang : Scenario2_LangT<Scenario2_Lang>
00019     {
00020         Scenario2_Lang();
00021
00022         void ShowResults_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario2_Lang : Scenario2_LangT<Scenario2_Lang, implementation::Scenario2_Lang>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:19:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserConsentVerifier/cpp/Scenario1_CheckConsentAvailability.xaml.h Source File

  • UserConsentVerifier
  • cpp

Scenario1_CheckConsentAvailability.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario1_CheckConsentAvailability.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario1_CheckConsentAvailability sealed
00012     {
00013     public:
00014         Scenario1_CheckConsentAvailability();
00015     private:
00016         void CheckAvailability_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00017     };
00018 }
Generated on Fri Nov 15 2024 22:21:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Cluster Member List

This is the complete list of members for Cluster, including all inherited members.
Location | Cluster
Places | Cluster
Places | Cluster
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario3.xaml.cpp Source File

  • MapControl
  • cpp

Scenario3.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario3.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Platform::Collections;
00018 using namespace Windows::Devices::Geolocation;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Maps;
00023
00024 Scenario3::Scenario3()
00025 {
00026     InitializeComponent();
00027 }
00028
00029 void Scenario3::MyMap_Loaded(Object^ sender, RoutedEventArgs^ e)
00030 {
00031     myMap->Center = MainPage::SeattleGeopoint;
00032     myMap->ZoomLevel = 16;
00033 }
00034
00035 void Scenario3::addXamlChildrenButton_Click(Object^ sender, RoutedEventArgs^ e)
00036 {
00037     BasicGeoposition center = myMap->Center->Position;
00038     auto pinUri = ref new Uri("ms-appx:///Assets/MapPin.png");
00039     auto places = ref new Vector<PointOfInterest^>();
00040
00041     PointOfInterest^ place = ref new PointOfInterest();
00042     place->DisplayName = L"Place One";
00043     place->ImageSourceUri = pinUri;
00044     place->NormalizedAnchorPoint = Point{ 0.5, 1 };
00045     place->Location = ref new Geopoint({ center.Latitude + 0.001, center.Longitude - 0.001 });
00046     places->Append(place);
00047
00048     place = ref new PointOfInterest();
00049     place->DisplayName = L"Place Two";
00050     place->ImageSourceUri = pinUri;
00051     place->NormalizedAnchorPoint = Point{ 0.5, 1 };
00052     place->Location = ref new Geopoint({ center.Latitude + 0.001, center.Longitude + 0.001 });
00053     places->Append(place);
00054
00055     place = ref new PointOfInterest();
00056     place->DisplayName = L"Place Three";
00057     place->ImageSourceUri = pinUri;
00058     place->NormalizedAnchorPoint = Point{ 0.5, 1 };
00059     place->Location = ref new Geopoint({ center.Latitude - 0.001, center.Longitude - 0.001 });
00060     places->Append(place);
00061
00062     place = ref new PointOfInterest();
00063     place->DisplayName = L"Place Four";
00064     place->ImageSourceUri = pinUri;
00065     place->NormalizedAnchorPoint = Point{ 0.5, 1 };
00066     place->Location = ref new Geopoint({ center.Latitude - 0.001, center.Longitude + 0.001 });
00067     places->Append(place);
00068
00069     MapItems->ItemsSource = places;
00070 }
00071
00072 void Scenario3::mapItemButton_Click(Object^ sender, RoutedEventArgs^ e)
00073 {
00074     Button^ buttonSender = safe_cast<Button^>(sender);
00075     PointOfInterest^ poi = safe_cast<PointOfInterest^>(buttonSender->DataContext);
00076     rootPage->NotifyUser(L"PointOfInterest clicked = " + poi->DisplayName, NotifyType::StatusMessage);
00077 }
Generated on Fri Nov 15 2024 22:18:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

WaveEffect::Vertex Member List

This is the complete list of members for WaveEffect::Vertex, including all inherited members.
x | WaveEffect::Vertex
y | WaveEffect::Vertex
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1ViewModel Member List

This is the complete list of members for Scenario1ViewModel, including all inherited members.
AlljoynBusAttachment_AuthenticationComplete(AllJoynBusAttachment sender, AllJoynAuthenticationCompleteEventArgs args) | Scenario1ViewModel | [inline, private]
AlljoynBusAttachment_CredentialsRequested(AllJoynBusAttachment sender, AllJoynCredentialsRequestedEventArgs args) | Scenario1ViewModel | [inline, private]
AlljoynBusAttachment_StateChanged(AllJoynBusAttachment sender, AllJoynBusAttachmentStateChangedEventArgs args) | Scenario1ViewModel | [inline, private]
AppData_IsUpperCaseEnabledPropertyDataChanged(object sender, EventArgs e) | Scenario1ViewModel | [inline, private]
IsUpperCaseEnabled | Scenario1ViewModel |
Key | Scenario1ViewModel |
LaunchProducer | Scenario1ViewModel |
m_busAttachment | Scenario1ViewModel | [private]
m_dispatcher | Scenario1ViewModel | [private]
m_isBusAttachmentConnected | Scenario1ViewModel | [private]
m_key | Scenario1ViewModel | [private]
m_producer | Scenario1ViewModel | [private]
m_producerOptionsVisibility | Scenario1ViewModel | [private]
ProducerOptionsVisibility | Scenario1ViewModel |
PropertyChanged | Scenario1ViewModel |
RaisePropertyChangedEventAsync([CallerMemberName] string name="") | Scenario1ViewModel | [inline, protected]
rootPage | Scenario1ViewModel | [private]
Scenario1ViewModel() | Scenario1ViewModel | [inline]
ScenarioCleanup() | Scenario1ViewModel | [inline]
SendSignal | Scenario1ViewModel |
SendTextSignal() | Scenario1ViewModel | [inline, private]
SignalText | Scenario1ViewModel |
Start() | Scenario1ViewModel | [inline, private]
UpdateStatusAsync(string status, NotifyType statusType) | Scenario1ViewModel | [inline, private]
Generated on Fri Nov 15 2024 22:23:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cpp/SampleConfiguration.h Source File

  • ActivitySensor
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Activity sensor";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Scenario3_BackgroundDeviceWatcher.h Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

Scenario3_BackgroundDeviceWatcher.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_BackgroundDeviceWatcher.g.h"
00015 #include "MainPage.h"
00016 #include "DeviceWatcherHelper.h"
00017
00018 namespace winrt::SDKTemplate::implementation
00019 {
00020     struct Scenario3_BackgroundDeviceWatcher : Scenario3_BackgroundDeviceWatcherT<Scenario3_BackgroundDeviceWatcher>
00021     {
00022         Scenario3_BackgroundDeviceWatcher();
00023
00024         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00026
00027         void StartWatcherButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void StopWatcherButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029
00030     private:
00031         SDKTemplate::MainPage rootPage{ SDKTemplate::implementation::MainPage::Current() };
00032         Windows::ApplicationModel::Background::IBackgroundTaskRegistration backgroundTaskRegistration{ nullptr };
00033         event_token taskCompletedToken{};
00034
00035         void StartWatcher();
00036         void StopWatcher();
00037         void RegisterBackgroundTask(Windows::ApplicationModel::Background::DeviceWatcherTrigger const& deviceWatcherTrigger);
00038         void UnregisterBackgroundTask(Windows::ApplicationModel::Background::IBackgroundTaskRegistration const& taskReg);
00039         fire_and_forget OnTaskCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration const& task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs const& args);
00040     };
00041 }
00042
00043 namespace winrt::SDKTemplate::factory_implementation
00044 {
00045     struct Scenario3_BackgroundDeviceWatcher : Scenario3_BackgroundDeviceWatcherT<Scenario3_BackgroundDeviceWatcher, implementation::Scenario3_BackgroundDeviceWatcher>
00046     {
00047     };
00048 }
Generated on Fri Nov 15 2024 22:19:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraManualControls/cs/MainPage.Shutter.xaml.cs Source File

  • CameraManualControls
  • cs

MainPage.Shutter.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019
00020 namespace CameraManualControls
00021 {
00022     public sealed partial class MainPage : Page
00023     {
00024
00025         private void UpdateExposureControlCapabilities()
00026         {
00027             var exposureControl = _mediaCapture.VideoDeviceController.ExposureControl;
00028
00029             if (exposureControl.Supported)
00030             {
00031                 ShutterButton.Tag = Visibility.Visible;
00032
00033                 ShutterAutoCheckBox.IsChecked = exposureControl.Auto;
00034
00035                 // Unhook the event handler, so that changing properties on the slider won't trigger an API call
00036                 ShutterSlider.ValueChanged -= ShutterSlider_ValueChanged;
00037
00038                 ShutterSlider.Minimum = exposureControl.Min.Ticks;
00039                 ShutterSlider.Maximum = exposureControl.Max.Ticks;
00040                 ShutterSlider.StepFrequency = exposureControl.Step.Ticks;
00041
00042                 var value = exposureControl.Value;
00043                 ShutterTextBlock.Text = value.TotalMilliseconds + " ms";
00044                 ShutterSlider.Value = value.Ticks;
00045
00046                 ShutterSlider.ValueChanged += ShutterSlider_ValueChanged;
00047             }
00048             else
00049             {
00050                 ShutterButton.Visibility = Visibility.Collapsed;
00051                 ShutterButton.Tag = Visibility.Collapsed;
00052             }
00053         }
00054
00055         private async void ShutterSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e)
00056         {
00057             if (_settingUpUi) return;
00058
00059             var value = TimeSpan.FromTicks((long)(sender as Slider).Value);
00060
00061             ShutterTextBlock.Text = value.TotalMilliseconds + " ms";
00062
00063             await _mediaCapture.VideoDeviceController.ExposureControl.SetValueAsync(value);
00064         }
00065
00066         private async void ShutterCheckBox_CheckedChanged(object sender, RoutedEventArgs e)
00067         {
00068             var autoShutter = ((sender as CheckBox).IsChecked == true);
00069
00070             await _mediaCapture.VideoDeviceController.ExposureControl.SetAutoAsync(autoShutter);
00071         }
00072
00073     }
00074 }
Generated on Fri Nov 15 2024 22:18:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario13_RetryFilter.cpp Source File

  • HttpClient
  • cppwinrt

Scenario13_RetryFilter.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario13_RetryFilter.h"
00014 #include "Scenario13_RetryFilter.g.cpp"
00015 #include "Helpers.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::HttpFilters;
00019 using namespace winrt::Windows::Foundation;
00020 using namespace winrt::Windows::UI::Xaml;
00021 using namespace winrt::Windows::UI::Xaml::Navigation;
00022 using namespace winrt::Windows::Web::Http;
00023 using namespace winrt::Windows::Web::Http::Filters;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario13_RetryFilter::Scenario13_RetryFilter()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     void Scenario13_RetryFilter::OnNavigatedTo(NavigationEventArgs const&)
00033     {
00034         HttpBaseProtocolFilter baseProtocolFilter;
00035         HttpRetryFilter retryFilter(baseProtocolFilter);
00036         httpClient = HttpClient(retryFilter);
00037         UpdateAddressField();
00038     }
00039
00040     void Scenario13_RetryFilter::OnNavigatedFrom(NavigationEventArgs const&)
00041     {
00042         httpClient.Close();
00043     }
00044
00045     void Scenario13_RetryFilter::UpdateAddressField()
00046     {
00047         // Tell the server which type of Retry-After header we would like to receive.
00048         hstring queryString;
00049         if (RetryAfterSwitch().IsOn())
00050         {
00051             queryString = L"?retryAfter=deltaSeconds";
00052         }
00053         else
00054         {
00055             queryString = L"?retryAfter=httpDate";
00056         }
00057
00058         Helpers::ReplaceQueryString(AddressField(), queryString);
00059     }
00060
00061     void Scenario13_RetryFilter::RetryAfterSwitch_Toggled(IInspectable const&, RoutedEventArgs const&)
00062     {
00063         UpdateAddressField();
00064     }
00065
00066     fire_and_forget Scenario13_RetryFilter::Start_Click(IInspectable const&, RoutedEventArgs const&)
00067     {
00068         auto lifetime = get_strong();
00069
00070         // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00071         // valid, absolute URI, we'll notify the user about the incorrect input.
00072         Uri resourceUri = Helpers::TryParseHttpUri(AddressField().Text());
00073         if (!resourceUri)
00074         {
00075             rootPage.NotifyUser(L"Invalid URI.", NotifyType::ErrorMessage);
00076             return;
00077         }
00078
00079         Helpers::ScenarioStarted(StartButton(), CancelButton(), OutputField());
00080         rootPage.NotifyUser(L"In progress", NotifyType::StatusMessage);
00081
00082         // This sample uses a "try" in order to support cancellation.
00083         // If you don't need to support cancellation, then the "try" is not needed.
00084         try
00085         {
00086             pendingAction = CancelableRequestAsync(resourceUri);
00087             co_await pendingAction;
00088         }
00089         catch (hresult_canceled const&)
00090         {
00091             rootPage.NotifyUser(L"Request canceled.", NotifyType::ErrorMessage);
00092         }
00093
00094         Helpers::ScenarioCompleted(StartButton(), CancelButton());
00095     }
00096
00097     IAsyncAction Scenario13_RetryFilter::CancelableRequestAsync(Uri resourceUri)
00098     {
00099         auto lifetime = get_strong();
00100         auto cancellation = co_await get_cancellation_token();
00101         cancellation.enable_propagation();
00102
00103         HttpRequestResult result = co_await httpClient.TryGetAsync(resourceUri);
00104
00105         if (result.Succeeded())
00106         {
00107             co_await Helpers::DisplayTextResultAsync(result.ResponseMessage(), OutputField());
00108
00109             rootPage.NotifyUser(L"Completed", NotifyType::StatusMessage);
00110         }
00111         else
00112         {
00113             Helpers::DisplayWebError(rootPage, result.ExtendedError());
00114         }
00115     }
00116
00117     void Scenario13_RetryFilter::Cancel_Click(IInspectable const&, RoutedEventArgs const&)
00118     {
00119         if (pendingAction)
00120         {
00121             pendingAction.Cancel();
00122         }
00123     }
00124 }
Generated on Fri Nov 15 2024 22:19:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraGetPreviewFrame/cpp/pch.h Source File

  • CameraGetPreviewFrame
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <collection.h>
00015 #include <ppltasks.h>
00016
00017 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/pch.h Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.ApplicationModel.Background.h"
00008 #include "winrt/Windows.Devices.Enumeration.h"
00009 #include "winrt/Windows.Security.Credentials.h"
00010 #include "winrt/Windows.Storage.h"
00011 #include "winrt/Windows.System.h"
00012 #include "winrt/Windows.UI.Core.h"
00013 #include "winrt/Windows.UI.Xaml.h"
00014 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00015 #include "winrt/Windows.UI.Xaml.Controls.h"
00016 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00017 #include "winrt/Windows.UI.Xaml.Documents.h"
00018 #include "winrt/Windows.UI.Xaml.Interop.h"
00019 #include "winrt/Windows.UI.Xaml.Markup.h"
00020 #include "winrt/Windows.UI.Xaml.Media.h"
00021 #include "winrt/Windows.UI.Xaml.Media.Imaging.h"
00022 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cs/Scenario3_ClientAuthentication.xaml.cs Source File

  • WebSocket
  • cs

Scenario3_ClientAuthentication.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Networking.Sockets;
00016 using Windows.Security.Cryptography.Certificates;
00017 using Windows.Storage;
00018 using Windows.Storage.Streams;
00019 using Windows.UI.Core;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Navigation;
00023
00024 namespace SDKTemplate
00025 {
00026     public sealed partial class Scenario3_ClientAuthentication : Page
00027     {
00028         private static readonly string ClientCertUriPath = "ms-appx:///Assets/clientCert.pfx";
00029         private static readonly string ClientCertPassword = "1234";
00030         private static readonly string ClientCertFriendlyName = "WebSocketSampleClientCert";
00031         private static readonly string ClientCertIssuerName = "www.contoso.com";
00032
00033         public Scenario3_ClientAuthentication()
00034         {
00035             this.InitializeComponent();
00036             UpdateVisualState();
00037         }
00038
00039         MainPage rootPage = MainPage.Current;
00040
00041         private StreamWebSocket streamWebSocket;
00042         private bool busy;
00043
00044         protected override void OnNavigatedFrom(NavigationEventArgs e)
00045         {
00046             CloseSocket();
00047         }
00048
00049         private void UpdateVisualState()
00050         {
00051             if (busy)
00052             {
00053                 VisualStateManager.GoToState(this, "Busy", false);
00054             }
00055             else
00056             {
00057                 VisualStateManager.GoToState(this, streamWebSocket != null ? "Connected" : "Disconnected", false);
00058             }
00059         }
00060
00061         private void SetBusy(bool value)
00062         {
00063             busy = value;
00064             UpdateVisualState();
00065         }
00066
00067         private async void OnConnect(object sender, RoutedEventArgs e)
00068         {
00069             SetBusy(true);
00070             await ConnectWebSocketAsync();
00071             SetBusy(false);
00072         }
00073
00074         private async Task<Certificate> FindCertificateFromStoreAsync()
00075         {
00076             // Find the client certificate for authentication. If not found, it means it has not been installed.
00077             CertificateQuery query = new CertificateQuery();
00078             query.IssuerName = ClientCertIssuerName;
00079             query.FriendlyName = ClientCertFriendlyName;
00080
00081             IReadOnlyList<Certificate> certs = await CertificateStores.FindAllAsync(query);
00082             if (certs.Count == 0)
00083             {
00084                 return null;
00085             }
00086
00087             // This sample installs only one certificate, so if we find one, it must be ours.
00088             return certs[0];
00089         }
00090
00091         private async Task<Certificate> InstallClientCertificateAsync()
00092         {
00093             // Load the certificate from the clientCert.pfx file packaged with this sample.
00094             // This certificate has been signed with a trusted root certificate installed on the server.
00095             // The installation is done by running the setupServer.ps1 file, which should have been done
00096             // before running the app.
00097             // WARNING: Including a pfx file in the app package violates the Windows Store
00098             // certification requirements. We are shipping the pfx file with the package for demonstrating
00099             // the usage of client certificates. Apps that will be published through Windows Store
00100             // need to use other approaches to obtain a client certificate.
00101             StorageFile clientCertFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(ClientCertUriPath));
00102
00103             IBuffer buffer = await FileIO.ReadBufferAsync(clientCertFile);
00104             AppendOutputLine("Reading certificate succeeded.");
00105
00106             string clientCertData = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(buffer);
00107
00108             try
00109             {
00110                 // Install the certificate to the app's certificate store.
00111                 // The app certificate store is removed when the app is uninstalled.
00112
00113                 //To install a certificate to the CurrentUser\MY store, which is not app specific,
00114                 // you need to use CertificateEnrollmentManager.UserCertificateEnrollmentManager.ImportPfxDataAsync().
00115                 // In order to call that method, an app must have the "sharedUserCertificates" capability.
00116                 // There are two ways to add this capability:
00117                 //
00118                 // 1. You can double click on the Package.appxmanifest file from the
00119                 // solution explorer, select the "Capabilities" tab in the opened page, and then check the
00120                 // "Shared User Certificates" box from the capabilities list.
00121                 // 2. You can right click on the Package.appxmanifest file from the
00122                 // solution explorer, select "View Code", and add "sharedUserCertificates" under the <Capabilities>
00123                 // element directly.
00124                 // Package.appxmanifest in this sample shows this capability commented out.
00125                 //
00126                 // The certificate will remain even when the app is uninstalled.
00127                 await CertificateEnrollmentManager.ImportPfxDataAsync(
00128                     clientCertData,
00129                     ClientCertPassword,
00130                     ExportOption.Exportable,
00131                     KeyProtectionLevel.NoConsent,
00132                     InstallOptions.DeleteExpired,
00133                     ClientCertFriendlyName);
00134
00135                 AppendOutputLine("Installing certificate succeeded.");
00136
00137                 // Return the certificate we just installed.
00138                 return await FindCertificateFromStoreAsync();
00139             }
00140             catch (Exception ex)
00141             {
00142                 // This can happen if the certificate has already expired.
00143                 AppendOutputLine("Installing certificate failed with " + ex.Message);
00144                 return null;
00145             }
00146         }
00147
00148         private async Task<Certificate> GetClientCertificateAsync()
00149         {
00150             // The client certificate could be installed already (if this scenario has been run before),
00151             // try finding it from the store.
00152             Certificate cert = await FindCertificateFromStoreAsync();
00153             if (cert != null)
00154             {
00155                 return cert;
00156             }
00157
00158             // If the client certificate is not already installed, install it.
00159             return await InstallClientCertificateAsync();
00160         }
00161
00162         private async Task ConnectWebSocketAsync()
00163         {
00164             // Validating the URI is required since it was received from an untrusted source (user input).
00165             // The URI is validated by calling TryGetUri() that will return null for strings that are not
00166             // valid WebSocket URIs.
00167             // Note that when enabling the text box users may provide URIs to machines on the intrAnet
00168             // or intErnet. In these cases the app requires the "Home or Work Networking" or
00169             // "Internet (Client)" capability respectively.
00170             Uri server = rootPage.TryGetUri(ServerAddressField.Text);
00171             if (server == null)
00172             {
00173                 return;
00174             }
00175
00176             // Certificate validation is meaningful only for secure connections.
00177             if (server.Scheme != "wss")
00178             {
00179                 AppendOutputLine("Note: Certificate validation is performed only for the wss: scheme.");
00180             }
00181
00182             streamWebSocket = new StreamWebSocket();
00183             streamWebSocket.Closed += OnClosed;
00184
00185             // It is okay to set the ClientCertificate property even if GetClientCertificateAsync returns null.
00186             streamWebSocket.Control.ClientCertificate = await GetClientCertificateAsync();
00187
00188             // When connecting to wss:// endpoint, the OS by default performs validation of
00189             // the server certificate based on well-known trusted CAs. For testing purposes, we are ignoring
00190             // SSL errors.
00191             // WARNING: Only test applications should ignore SSL errors.
00192             // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle
00193             // attacks. (Although the connection is secure, the server is not authenticated.)
00194             // Note that not all certificate validation errors can be ignored.
00195             // In this case, we are ignoring these errors since the certificate assigned to the localhost
00196             // URI is self-signed and has subject name = fabrikam.com
00197             streamWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
00198             streamWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
00199
00200             AppendOutputLine($"Connecting to {server}...");
00201
00202             try
00203             {
00204                 await streamWebSocket.ConnectAsync(server);
00205             }
00206             catch (Exception ex) // For debugging
00207             {
00208                 streamWebSocket.Dispose();
00209                 streamWebSocket = null;
00210
00211                 AppendOutputLine(MainPage.BuildWebSocketError(ex));
00212                 AppendOutputLine(ex.Message);
00213                 return;
00214             }
00215
00216             rootPage.NotifyUser("Connected", NotifyType.StatusMessage);
00217             AppendOutputLine("Connected to WebSocket Server.");
00218         }
00219
00220         private void OnDisconnect(object sender, RoutedEventArgs e)
00221         {
00222             SetBusy(true);
00223             rootPage.NotifyUser("Closing", NotifyType.StatusMessage);
00224             CloseSocket();
00225             SetBusy(false);
00226             rootPage.NotifyUser("Closed", NotifyType.StatusMessage);
00227         }
00228
00229         // This may be triggered remotely by the server or locally by Close/Dispose()
00230         private async void OnClosed(IWebSocket sender, WebSocketClosedEventArgs args)
00231         {
00232             // Dispatch the event to the UI thread so we do not need to synchronize access to streamWebSocket.
00233             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00234             {
00235                 AppendOutputLine("Closed; Code: " + args.Code + ", Reason: " + args.Reason);
00236
00237                 if (streamWebSocket == sender)
00238                 {
00239                     CloseSocket();
00240                     UpdateVisualState();
00241                 }
00242             });
00243         }
00244
00245         private void CloseSocket()
00246         {
00247             if (streamWebSocket != null)
00248             {
00249                 try
00250                 {
00251                     streamWebSocket.Close(1000, "Closed due to user request.");
00252                 }
00253                 catch (Exception ex)
00254                 {
00255                     AppendOutputLine(MainPage.BuildWebSocketError(ex));
00256                     AppendOutputLine(ex.Message);
00257                 }
00258
00259                 streamWebSocket = null;
00260             }
00261         }
00262
00263         private void AppendOutputLine(string value)
00264         {
00265             OutputField.Text += value + "\r\n";
00266         }
00267
00268     }
00269 }
Generated on Fri Nov 15 2024 22:22:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SampleOverlay Member List

This is the complete list of members for SampleOverlay, including all inherited members.
CreateDeviceDependentResources() | SampleOverlay |
CreateWindowSizeDependentResources() | SampleOverlay |
GetTitleHeightInDips() | SampleOverlay |
m_caption | SampleOverlay | [private]
m_deviceResources | SampleOverlay | [private]
m_drawOverlay | SampleOverlay | [private]
m_idIncrement | SampleOverlay | [private]
m_logoBitmap | SampleOverlay | [private]
m_logoSize | SampleOverlay | [private]
m_overlayWidth | SampleOverlay | [private]
m_padding | SampleOverlay | [private]
m_stateBlock | SampleOverlay | [private]
m_textLayout | SampleOverlay | [private]
m_textVerticalOffset | SampleOverlay | [private]
m_whiteBrush | SampleOverlay | [private]
ReleaseDeviceDependentResources() | SampleOverlay |
Render() | SampleOverlay |
SampleOverlay(const std::shared_ptr< DX::DeviceResources > &deviceResources, const std::wstring &caption) | SampleOverlay |
Generated on Fri Nov 15 2024 22:23:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cpp/Scenario2_Remove.xaml.h Source File

  • JumpList
  • cpp

Scenario2_Remove.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Remove.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario2_Remove sealed
00021     {
00022     public:
00023         Scenario2_Remove();
00024
00025     private:
00026         void RemoveJumpList_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00027     };
00028 }
Generated on Fri Nov 15 2024 22:20:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ViewProjectionConstantBuffer Member List

This is the complete list of members for ViewProjectionConstantBuffer, including all inherited members.
viewProjectionLeft | ViewProjectionConstantBuffer
viewProjectionRight | ViewProjectionConstantBuffer
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/BackgroundTasks/ToastActivationTypeBackgroundClosedTask.cs Source File

  • Notifications
  • cs
  • BackgroundTasks

ToastActivationTypeBackgroundClosedTask.cs

Go to the documentation of this file.
00001 ﻿using BackgroundTasks.Helpers;
00002 using Windows.ApplicationModel.Background;
00003 using Windows.UI.Notifications;
00004
00005 namespace BackgroundTasks
00006 {
00007     public sealed class ToastActivationTypeBackgroundClosedTask : IBackgroundTask
00008     {
00009         public void Run(IBackgroundTaskInstance taskInstance)
00010         {
00011             var details = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;
00012             if (details == null)
00013             {
00014                 ToastHelper.PopToast("ERROR", "TriggerDetails was not ToastNotificationActionTriggerDetail.");
00015                 return;
00016             }
00017
00018             string arguments = details.Argument;
00019
00020             if (arguments == null || !arguments.Equals("quickReply"))
00021             {
00022                 ToastHelper.PopToast("ERROR", $"Expected arguments to be 'quickReply' but was '{arguments}'.");
00023                 return;
00024             }
00025
00026             var result = details.UserInput;
00027
00028             if (result.Count != 1)
00029                 ToastHelper.PopToast("ERROR", "ERROR: Expected 1 user input value, but there were " + result.Count);
00030
00031             else if (!result.ContainsKey("message"))
00032                 ToastHelper.PopToast("ERROR", "ERROR: Expected a user input value for 'message', but there was none.");
00033
00034             else if (!(result["message"] as string).Equals("Windows 10"))
00035                 ToastHelper.PopToast("ERROR", "ERROR: User input value for 'message' was not 'Windows 10'");
00036
00037             else
00038             {
00039                 ToastHelper.PopToast("SUCCESS", "This scenario successfully completed. Please mark it as passed.");
00040             }
00041         }
00042     }
00043 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PresenceSensor/cppwinrt/SampleConfiguration.h Source File

  • PresenceSensor
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt
00016 {
00017     hstring to_hstring(Windows::Devices::Sensors::HumanPresence value);
00018     hstring to_hstring(Windows::Devices::Sensors::HumanEngagement value);
00019 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/Templates.xaml.cpp Source File

  • XamlBind
  • cpp

Templates.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // Templates.xaml.cpp
00003 // Implementation of the Templates class
00004 //
00005
00006 #include "pch.h"
00007 #include "Templates.xaml.h"
00008
00009 using namespace SDKTemplate;
00010
00011 using namespace Platform;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::UI::Xaml;
00015 using namespace Windows::UI::Xaml::Controls;
00016 using namespace Windows::UI::Xaml::Controls::Primitives;
00017 using namespace Windows::UI::Xaml::Data;
00018 using namespace Windows::UI::Xaml::Input;
00019 using namespace Windows::UI::Xaml::Media;
00020 using namespace Windows::UI::Xaml::Navigation;
00021
00022 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00023
00024 Templates::Templates()
00025 {
00026     InitializeComponent();
00027 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/SampleConfiguration.cpp Source File

  • WindowsAudioSession
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKSample;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Device Enumeration", "SDKSample.WASAPIAudio.Scenario1" },
00021     { "Audio Rendering with Hardware Offload", "SDKSample.WASAPIAudio.Scenario2" },
00022     { "Audio Rendering with Low Latency", "SDKSample.WASAPIAudio.Scenario3" },
00023     { "PCM Audio Capture", "SDKSample.WASAPIAudio.Scenario4" }
00024 };
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PersonalDataEncryption/cppwinrt/SampleConfiguration.h Source File

  • PersonalDataEncryption
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cpp/Scenario2_DecimalFormatting.xaml.h Source File

  • NumberFormatting
  • cpp

Scenario2_DecimalFormatting.xaml.h

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "pch.h"
00006 #include "Scenario2_DecimalFormatting.g.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario2_DecimalFormatting sealed
00012     {
00013     public:
00014         Scenario2_DecimalFormatting();
00015
00016     private:
00017         void Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00018     };
00019 }
Generated on Fri Nov 15 2024 22:20:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/OtherBindings.xaml.h Source File

  • XamlBind
  • cpp

OtherBindings.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // OtherBindings.xaml.h
00003 // Declaration of the OtherBindings class
00004 //
00005
00006 #pragma once
00007
00008 #include "OtherBindings.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     /// <summary>
00013     /// An empty page that can be used on its own or navigated to within a Frame.
00014     /// </summary>
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class OtherBindings sealed
00017     {
00018     private:
00019         const Platform::String^ DPOnPageName = "DPOnPage";
00020         static Windows::UI::Xaml::DependencyProperty^ _DPOnPage;
00021
00022     public:
00023         OtherBindings();
00024         property int MyInt;
00025         property xBindSampleModel::DataModel^ Model;
00026
00027         property Platform::String^ DPOnPage
00028         {
00029             Platform::String^ get()
00030             {
00031                 return dynamic_cast<Platform::String^>(GetValue(DPOnPageProperty));
00032             }
00033             void set(Platform::String^ value)
00034             {
00035                 SetValue(DPOnPageProperty, value);
00036             }
00037         }
00038
00039         static property Windows::UI::Xaml::DependencyProperty^ DPOnPageProperty
00040         {
00041             Windows::UI::Xaml::DependencyProperty^ get() { return _DPOnPage; }
00042         }
00043
00044         property xBindSampleModel::IEmployee^ NullEmployee;
00045         property Platform::String^ NullStringProperty;
00046
00047     private:
00048         void InitializeValues();
00049         void UpdateValuesClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050         void ResetValuesClick(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^ e);
00051         void UndeferElementClick(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^ e);
00052     };
00053 }
Generated on Fri Nov 15 2024 22:22:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

List< T >::Node Member List

This is the complete list of members for List< T >::Node, including all inherited members.
item | List< T >::Node |
Item() const | List< T >::Node | [inline]
next | List< T >::Node |
Node() | List< T >::Node | [inline]
Node(T item) | List< T >::Node | [inline]
prev | List< T >::Node |
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

App Member List

This is the complete list of members for App, including all inherited members.
App() | App | [inline]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
Generated on Fri Nov 15 2024 22:23:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NetworkConnectivity/cppwinrt/SampleConfiguration.h Source File

  • NetworkConnectivity
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt
00016 {
00017     hstring to_hstring(Windows::Networking::Connectivity::NetworkConnectivityLevel value);
00018     hstring to_hstring(Windows::Networking::Connectivity::NetworkCostType type);
00019 }
00020
00021 namespace winrt::SDKTemplate
00022 {
00023     void AppendLine(Windows::UI::Xaml::Controls::TextBlock const& textBlock, hstring const& message);
00024
00025     enum class CostGuidance
00026     {
00027         Normal,
00028         OptIn,
00029         Conservative
00030     };
00031
00032     bool ShouldAttemptToConnectToInternet(Windows::Networking::Connectivity::NetworkConnectivityLevel level);
00033     CostGuidance GetNetworkCostGuidance(Windows::Networking::Connectivity::ConnectionCost cost);
00034     void EvaluateAndReportConnectionCost(Windows::Networking::Connectivity::ConnectionCost cost, Windows::UI::Xaml::Controls::TextBlock const& textBlock);
00035     winrt::Windows::Foundation::IAsyncAction EvaluateCostAndConnectAsync(Windows::Networking::Connectivity::ConnectionCost cost, bool optedInToCharges, Windows::UI::Xaml::Controls::TextBlock textBlock);
00036 }
00037
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/ProducerExperiences/cs/AppData.cs Source File

  • AllJoyn
  • ProducerExperiences
  • cs

AppData.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using org.alljoyn.Onboarding;
00013 using System;
00014 using System.Collections.Generic;
00015 using Windows.Storage;
00016
00017 namespace AllJoynProducerExperiences
00018 {
00019     class AppData
00020     {
00021         private const string isUpperCaseEnabledPropertyKey = "IsUpperCaseEnabled";
00022         private const string onboardingConfigureSsidKey = "OnboardingConfigureSsid";
00023         private const string onboardingConfigurePassphraseKey = "OnboardingConfigurePassphrase";
00024         private const string onboardingConfigureAuthenticationTypeKey = "OnboardingConfigureAuthenticationType";
00025         private const string onboardingConfigurationStateKey = "OnboardingConfigurationState";
00026         private const string onboardingLastErrorCodeKey = "OnboardingLastErrorCode";
00027         private const string onboardingLastErrorMessageKey = "OnboardingLastErrorMessage";
00028         private static ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
00029
00030         public static event EventHandler IsUpperCaseEnabledPropertyDataChanged;
00031
00032         public static bool IsUpperCaseEnabled
00033         {
00034             get
00035             {
00036                 if (!localSettings.Values.ContainsKey(isUpperCaseEnabledPropertyKey))
00037                 {
00038                     localSettings.Values[isUpperCaseEnabledPropertyKey] = false;
00039                 }
00040                 return (bool)localSettings.Values[isUpperCaseEnabledPropertyKey];
00041             }
00042             set
00043             {
00044                 if (IsUpperCaseEnabled != value)
00045                 {
00046                     localSettings.Values[isUpperCaseEnabledPropertyKey] = value;
00047                     EventHandler handler = IsUpperCaseEnabledPropertyDataChanged;
00048                     if (handler != null)
00049                     {
00050                         handler(new object(), new EventArgs());
00051                     }
00052                 }
00053             }
00054         }
00055
00056         public static string OnboardingConfigureSsid
00057         {
00058             get
00059             {
00060                 if (!localSettings.Values.ContainsKey(onboardingConfigureSsidKey))
00061                 {
00062                     return null;
00063                 }
00064                 else
00065                 {
00066                     return (string)localSettings.Values[onboardingConfigureSsidKey];
00067                 }
00068             }
00069             set
00070             {
00071                 localSettings.Values[onboardingConfigureSsidKey] = value;
00072             }
00073         }
00074
00075         public static string OnboardingConfigurePassphrase
00076         {
00077             get
00078             {
00079                 if (!localSettings.Values.ContainsKey(onboardingConfigurePassphraseKey))
00080                 {
00081                     return null;
00082                 }
00083                 else
00084                 {
00085                     return (string)localSettings.Values[onboardingConfigurePassphraseKey];
00086                 }
00087             }
00088             set
00089             {
00090                 localSettings.Values[onboardingConfigurePassphraseKey] = value;
00091             }
00092         }
00093
00094         public static short OnboardingConfigureAuthType
00095         {
00096             get
00097             {
00098                 if (!localSettings.Values.ContainsKey(onboardingConfigureAuthenticationTypeKey))
00099                 {
00100                     return (short)OnboardingAuthenticationType.Any;
00101                 }
00102                 else
00103                 {
00104                     return (short)localSettings.Values[onboardingConfigureAuthenticationTypeKey];
00105                 }
00106             }
00107             set
00108             {
00109                 localSettings.Values[onboardingConfigureAuthenticationTypeKey] = value;
00110             }
00111         }
00112
00113         public static short OnboardingConfigurationState
00114         {
00115             get
00116             {
00117                 if (!localSettings.Values.ContainsKey(onboardingConfigurationStateKey))
00118                 {
00119                     localSettings.Values[onboardingConfigurationStateKey] = (short)ConfigurationState.NotConfigured;
00120                 }
00121                 return (short)localSettings.Values[onboardingConfigurationStateKey];
00122             }
00123             set
00124             {
00125                 localSettings.Values[onboardingConfigurationStateKey] = value;
00126             }
00127         }
00128
00129         public static short LastErrorCode
00130         {
00131             get
00132             {
00133                 if (localSettings.Values.ContainsKey(onboardingLastErrorCodeKey))
00134                 {
00135                     return (short)localSettings.Values[onboardingLastErrorCodeKey];
00136                 }
00137                 else
00138                 {
00139                     return (short)ConnectionResultCode.ErrorMessage;
00140                 }
00141             }
00142             set
00143             {
00144                 localSettings.Values[onboardingLastErrorCodeKey] = value;
00145             }
00146         }
00147
00148         public static string LastErrorMessage
00149         {
00150             get
00151             {
00152                 if (localSettings.Values.ContainsKey(onboardingLastErrorMessageKey))
00153                 {
00154                     return (string)localSettings.Values[onboardingLastErrorMessageKey];
00155                 }
00156                 else
00157                 {
00158                     return "No Last Error available";
00159                 }
00160             }
00161             set
00162             {
00163                 localSettings.Values[onboardingLastErrorMessageKey] = value;
00164             }
00165         }
00166
00167         public static List<OnboardingScanListItem> SampleNetworkScanList
00168         {
00169             get
00170             {
00171                 // Simulated network scan data.
00172
00173                 OnboardingScanListItem network1 = new OnboardingScanListItem();
00174                 network1.Value1 = "SampleNetwork1";
00175                 network1.Value2 = (short)OnboardingAuthenticationType.Open;
00176
00177                 OnboardingScanListItem network2 = new OnboardingScanListItem();
00178                 network2.Value1 = "SampleNetwork2";
00179                 network2.Value2 = (short)OnboardingAuthenticationType.Wep;
00180
00181                 OnboardingScanListItem network3 = new OnboardingScanListItem();
00182                 network3.Value1 = "SampleNetwork3";
00183                 network3.Value2 = (short)OnboardingAuthenticationType.WpaTkip;
00184
00185                 OnboardingScanListItem network4 = new OnboardingScanListItem();
00186                 network4.Value1 = "SampleNetwork4";
00187                 network4.Value2 = (short)OnboardingAuthenticationType.WpaCcmp;
00188
00189                 OnboardingScanListItem network5 = new OnboardingScanListItem();
00190                 network5.Value1 = "SampleNetwork5";
00191                 network5.Value2 = (short)OnboardingAuthenticationType.Wpa2Tkip;
00192
00193                 OnboardingScanListItem network6 = new OnboardingScanListItem();
00194                 network6.Value1 = "SampleNetwork6";
00195                 network6.Value2 = (short)OnboardingAuthenticationType.Wpa2Ccmp;
00196
00197                 OnboardingScanListItem network7 = new OnboardingScanListItem();
00198                 network7.Value1 = "SampleNetwork7";
00199                 network7.Value2 = (short)OnboardingAuthenticationType.Wps;
00200
00201                 List<OnboardingScanListItem> networkScanList = new List<OnboardingScanListItem>();
00202                 networkScanList.Add(network1);
00203                 networkScanList.Add(network2);
00204                 networkScanList.Add(network3);
00205                 networkScanList.Add(network4);
00206                 networkScanList.Add(network5);
00207                 networkScanList.Add(network6);
00208                 networkScanList.Add(network7);
00209
00210                 return networkScanList;
00211             }
00212         }
00213
00214         public const string SampleNetworkPassword = "SamplePassword";
00215     }
00216 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppServices/cppwinrt/AppServicesClient/KeepConnectionOpenScenario.h Source File

  • AppServices
  • cppwinrt
  • AppServicesClient

KeepConnectionOpenScenario.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "KeepConnectionOpenScenario.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct KeepConnectionOpenScenario : KeepConnectionOpenScenarioT<KeepConnectionOpenScenario>
00019     {
00020         KeepConnectionOpenScenario();
00021
00022         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00023
00024         fire_and_forget OpenConnection_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00025         void CloseConnection_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026         fire_and_forget GenerateRandomNumber_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027
00028     private:
00029         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00030         Windows::ApplicationModel::AppService::AppServiceConnection connection{ nullptr };
00031
00032         fire_and_forget Connection_ServiceClosed(Windows::ApplicationModel::AppService::AppServiceConnection const&, Windows::ApplicationModel::AppService::AppServiceClosedEventArgs const&);
00033     };
00034 }
00035
00036 namespace winrt::SDKTemplate::factory_implementation
00037 {
00038     struct KeepConnectionOpenScenario : KeepConnectionOpenScenarioT<KeepConnectionOpenScenario, implementation::KeepConnectionOpenScenario>
00039     {
00040     };
00041 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario03_GetList Member List

This is the complete list of members for Scenario03_GetList, including all inherited members.
Cancel_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario03_GetList |
CancelableRequestAsync(Windows::Foundation::Uri resourceUri) | Scenario03_GetList | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario03_GetList |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario03_GetList |
Scenario03_GetList() | Scenario03_GetList |
Start_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario03_GetList |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cpp/Scenario2_Launch.xaml.h Source File

  • ResizeAppView
  • cpp

Scenario2_Launch.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Launch.g.h"
00015
00016 namespace SDKTemplate
00017 {
00018     [Windows::Foundation::Metadata::WebHostHidden]
00019     public ref class Scenario2_Launch sealed
00020     {
00021     public:
00022         Scenario2_Launch();
00023
00024     private:
00025         void LaunchAtSize_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00026     };
00027 }
Generated on Fri Nov 15 2024 22:19:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/Scenario1_DevicePicker.xaml.cpp Source File

  • DeviceEnumerationAndPairing
  • cpp

Scenario1_DevicePicker.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario1_DevicePicker.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Platform::Collections;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::UI::Core;
00013 using namespace Windows::UI::Xaml;
00014 using namespace Windows::UI::Xaml::Controls;
00015 using namespace Windows::UI::Xaml::Controls::Primitives;
00016 using namespace Windows::UI::Xaml::Data;
00017 using namespace Windows::UI::Xaml::Input;
00018 using namespace Windows::UI::Xaml::Media;
00019 using namespace Windows::UI::Xaml::Navigation;
00020 using namespace Windows::Devices::Enumeration;
00021
00022 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00023
00024 Scenario1_DevicePicker::Scenario1_DevicePicker()
00025 {
00026     InitializeComponent();
00027 }
00028
00029 void Scenario1_DevicePicker::OnNavigatedTo(NavigationEventArgs^ e)
00030 {
00031     resultsListView->ItemsSource = resultCollection;
00032
00033     selectorComboBox->ItemsSource = DeviceSelectorChoices::DevicePickerSelectors;
00034     selectorComboBox->SelectedIndex = 0;
00035 }
00036
00037 void Scenario1_DevicePicker::PickSingleDeviceButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00038 {
00039     ShowDevicePicker(
00040         true // pickSingle
00041         );
00042 }
00043
00044 void Scenario1_DevicePicker::ShowDevicePickerButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046     ShowDevicePicker(
00047         false // pickSingle
00048         );
00049 }
00050
00051 void Scenario1_DevicePicker::ShowDevicePicker(bool pickSingle)
00052 {
00053     showDevicePickerButton->IsEnabled = false;
00054     resultCollection->Clear();
00055
00056     DevicePicker^ devicePicker = ref new DevicePicker();
00057
00058     // First get the device selector chosen by the UI.
00059     DeviceSelectorInfo^ deviceSelectorInfo = safe_cast<DeviceSelectorInfo^>(selectorComboBox->SelectedItem);
00060
00061     if (nullptr == deviceSelectorInfo->Selector)
00062     {
00063         // If the a pre-canned device class selector was chosen, call the DeviceClass overload
00064         devicePicker->Filter->SupportedDeviceClasses->Append(deviceSelectorInfo->DeviceClassSelector);
00065     }
00066     else
00067     {
00068         // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
00069         devicePicker->Filter->SupportedDeviceSelectors->Append(deviceSelectorInfo->Selector);
00070     }
00071
00072     rootPage->NotifyUser("Showing Device Picker", NotifyType::StatusMessage);
00073
00074     // Calculate the position to show the picker (right below the buttons)
00075     GeneralTransform^ ge = pickSingleDeviceButton->TransformToVisual(nullptr);
00076     Point point = ge->TransformPoint(Point());
00077     Rect rect(point, Point(point.X + (float)pickSingleDeviceButton->ActualWidth, point.Y + (float)pickSingleDeviceButton->ActualHeight));
00078
00079     if (pickSingle)
00080     {
00081         concurrency::create_task(devicePicker->PickSingleDeviceAsync(rect)).then(
00082             [this](DeviceInformation^ deviceInfo)
00083         {
00084             if (nullptr != deviceInfo)
00085             {
00086                 resultCollection->Append(ref new DeviceInformationDisplay(deviceInfo));
00087             }
00088             showDevicePickerButton->IsEnabled = true;
00089         }, concurrency::task_continuation_context::use_current());
00090     }
00091     else
00092     {
00093         devicePicker->DevicePickerDismissed += ref new TypedEventHandler<DevicePicker^, Object^>(
00094             [this](DevicePicker^ sender, Object^ obj)
00095         {
00096             // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
00097             rootPage->Dispatcher->RunAsync(CoreDispatcherPriority::Low, ref new DispatchedHandler(
00098                 [this]()
00099             {
00100                 showDevicePickerButton->IsEnabled = true;
00101                 rootPage->NotifyUser("Hiding Device Picker...", NotifyType::StatusMessage);
00102             }));
00103         });
00104
00105         // Hook up handlers for the watcher events before starting the watcher
00106         devicePicker->DeviceSelected += ref new TypedEventHandler<DevicePicker^, DeviceSelectedEventArgs^>(
00107             [this](DevicePicker^ sender, DeviceSelectedEventArgs^ eventArgs)
00108         {
00109             // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
00110             rootPage->Dispatcher->RunAsync(CoreDispatcherPriority::Low, ref new DispatchedHandler(
00111                 [this, eventArgs]()
00112             {
00113                 resultCollection->Clear();
00114                 resultCollection->Append(ref new DeviceInformationDisplay(eventArgs->SelectedDevice));
00115             }));
00116         });
00117         devicePicker->Show(rect);
00118     }
00119 }
Generated on Fri Nov 15 2024 22:19:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Scenario7_DeviceInformationKind.h Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

Scenario7_DeviceInformationKind.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario7_DeviceInformationKind.g.h"
00015 #include "MainPage.h"
00016 #include "DeviceWatcherHelper.h"
00017
00018 namespace winrt::SDKTemplate::implementation
00019 {
00020     struct Scenario7_DeviceInformationKind : Scenario7_DeviceInformationKindT<Scenario7_DeviceInformationKind>
00021     {
00022         Scenario7_DeviceInformationKind();
00023
00024         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00026
00027         void StartWatcherButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void StopWatcherButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029
00030     private:
00031         SDKTemplate::MainPage rootPage{ SDKTemplate::implementation::MainPage::Current() };
00032         Windows::Foundation::Collections::IObservableVector<SDKTemplate::DeviceInformationDisplay> resultCollection = winrt::single_threaded_observable_vector<SDKTemplate::DeviceInformationDisplay>();
00033         std::vector<com_ptr<DeviceWatcherHelper>> deviceWatcherHelpers;
00034
00035         void StartWatchers();
00036         void StopWatchers(bool reset = false);
00037         void OnDeviceListChanged(Windows::Devices::Enumeration::DeviceWatcher const& sender, hstring const& id);
00038     };
00039 }
00040
00041 namespace winrt::SDKTemplate::factory_implementation
00042 {
00043     struct Scenario7_DeviceInformationKind : Scenario7_DeviceInformationKindT<Scenario7_DeviceInformationKind, implementation::Scenario7_DeviceInformationKind>
00044     {
00045     };
00046 }
Generated on Fri Nov 15 2024 22:19:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Discovery Member List

This is the complete list of members for Scenario1_Discovery, including all inherited members.
DeviceWatcher_Added(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Devices::Enumeration::DeviceInformation deviceInfo) | Scenario1_Discovery | [private]
DeviceWatcher_EnumerationCompleted(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Foundation::IInspectable const &) | Scenario1_Discovery | [private]
DeviceWatcher_Removed(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Devices::Enumeration::DeviceInformationUpdate deviceInfoUpdate) | Scenario1_Discovery | [private]
DeviceWatcher_Stopped(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Foundation::IInspectable const &) | Scenario1_Discovery | [private]
DeviceWatcher_Updated(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Devices::Enumeration::DeviceInformationUpdate deviceInfoUpdate) | Scenario1_Discovery | [private]
deviceWatcherAddedToken | Scenario1_Discovery | [private]
deviceWatcherEnumerationCompletedToken | Scenario1_Discovery | [private]
deviceWatcherRemovedToken | Scenario1_Discovery | [private]
deviceWatcherStoppedToken | Scenario1_Discovery | [private]
deviceWatcherUpdatedToken | Scenario1_Discovery | [private]
EnumerateButton_Click() | Scenario1_Discovery |
FindBluetoothLEDeviceDisplay(hstring const &id) | Scenario1_Discovery | [private]
FindUnknownDevices(hstring const &id) | Scenario1_Discovery | [private]
KnownDevices() | Scenario1_Discovery | [inline]
m_knownDevices | Scenario1_Discovery | [private]
Not(bool value) | Scenario1_Discovery | [inline]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_Discovery |
PairButton_Click() | Scenario1_Discovery |
Scenario1_Discovery() | Scenario1_Discovery |
StartBleDeviceWatcher() | Scenario1_Discovery | [private]
StopBleDeviceWatcher() | Scenario1_Discovery | [private]
UnknownDevices | Scenario1_Discovery | [private]
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cs/Scenario4_SymbologyAttributes.xaml.cs Source File

  • BarcodeScanner
  • cs

Scenario4_SymbologyAttributes.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Collections.ObjectModel;
00015 using System.Threading.Tasks;
00016 using Windows.Devices.PointOfService;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario4_SymbologyAttributes : Page
00025     {
00026         MainPage rootPage = MainPage.Current;
00027         BarcodeScanner scanner = null;
00028         ClaimedBarcodeScanner claimedScanner = null;
00029
00030         ObservableCollection<SymbologyListEntry> listOfSymbologies = null;
00031         BarcodeSymbologyAttributes symbologyAttributes = null;
00032
00033         public Scenario4_SymbologyAttributes()
00034         {
00035             this.InitializeComponent();
00036
00037             listOfSymbologies = new ObservableCollection<SymbologyListEntry>();
00038             SymbologyListSource.Source = listOfSymbologies;
00039         }
00040
00041         protected override void OnNavigatedTo(NavigationEventArgs e)
00042         {
00043             ResetTheScenarioState();
00044         }
00045
00046         protected override void OnNavigatedFrom(NavigationEventArgs e)
00047         {
00048             ResetTheScenarioState();
00049         }
00050
00051         /// <summary>
00052         /// Event Handler for Start Scan Button Click.
00053         /// Sets up the barcode scanner to be ready to receive the data events from the scan.
00054         /// </summary>
00055         /// <param name="sender"></param>
00056         /// <param name="e"></param>
00057         private async void ScenarioStartScanButton_Click(object sender, RoutedEventArgs e)
00058         {
00059             ScenarioStartScanButton.IsEnabled = false;
00060
00061             rootPage.NotifyUser("Acquiring barcode scanner object.", NotifyType.StatusMessage);
00062
00063             // create the barcode scanner.
00064             scanner = await DeviceHelpers.GetFirstBarcodeScannerAsync();
00065
00066             if (scanner != null)
00067             {
00068                 // claim the scanner for exclusive use and enable it so that data received events are received.
00069                 claimedScanner = await scanner.ClaimScannerAsync();
00070                 if (claimedScanner != null)
00071                 {
00072                     // It is always a good idea to have a release device requested event handler. If this event is not handled, there are chances of another app can
00073                     // claim ownership of the barcode scanner.
00074                     claimedScanner.ReleaseDeviceRequested += claimedScanner_ReleaseDeviceRequested;
00075
00076                     // after successfully claiming, attach the datareceived event handler.
00077                     claimedScanner.DataReceived += claimedScanner_DataReceived;
00078
00079                     // Ask the API to decode the data by default. By setting this, API will decode the raw data from the barcode scanner and
00080                     // send the ScanDataLabel and ScanDataType in the DataReceived event
00081                     claimedScanner.IsDecodeDataEnabled = true;
00082
00083                     // enable the scanner.
00084                     // Note: If the scanner is not enabled (i.e. EnableAsync not called), attaching the event handler will not be any useful because the API will not fire the event
00085                     // if the claimedScanner has not been Enabled
00086                     await claimedScanner.EnableAsync();
00087
00088                     // after successful claim, list supported symbologies
00089                     IReadOnlyList<uint> supportedSymbologies = await scanner.GetSupportedSymbologiesAsync();
00090                     foreach (uint symbology in supportedSymbologies)
00091                     {
00092                         listOfSymbologies.Add(new SymbologyListEntry(symbology));
00093                     }
00094
00095                     // reset the button state
00096                     ScenarioEndScanButton.IsEnabled = true;
00097
00098                     rootPage.NotifyUser("Ready to scan. Device ID: " + claimedScanner.DeviceId, NotifyType.StatusMessage);
00099                 }
00100                 else
00101                 {
00102                     scanner.Dispose();
00103                     scanner = null;
00104                     ScenarioStartScanButton.IsEnabled = true;
00105                     rootPage.NotifyUser("Claim barcode scanner failed.", NotifyType.ErrorMessage);
00106                 }
00107             }
00108             else
00109             {
00110                 ScenarioStartScanButton.IsEnabled = true;
00111                 rootPage.NotifyUser("Barcode scanner not found. Please connect a barcode scanner.", NotifyType.ErrorMessage);
00112             }
00113         }
00114
00115         /// <summary>
00116         /// Event handler for the Release Device Requested event fired when barcode scanner receives Claim request from another application
00117         /// </summary>
00118         /// <param name="sender"></param>
00119         /// <param name="args"> Contains the ClamiedBarcodeScanner that is sending this request</param>
00120         void claimedScanner_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e)
00121         {
00122             // always retain the device
00123             e.RetainDevice();
00124             rootPage.NotifyUser("Event ReleaseDeviceRequested received. Retaining the barcode scanner.", NotifyType.StatusMessage);
00125         }
00126
00127         /// <summary>
00128         /// Event handler for the DataReceived event fired when a barcode is scanned by the barcode scanner
00129         /// </summary>
00130         /// <param name="sender"></param>
00131         /// <param name="args"> Contains the BarcodeScannerReport which contains the data obtained in the scan</param>
00132         async void claimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
00133         {
00134             // need to update the UI data on the dispatcher thread.
00135             // update the UI with the data received from the scan.
00136             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00137             {
00138                 // read the data from the buffer and convert to string.
00139                 ScenarioOutputScanDataLabel.Text = DataHelpers.GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType);
00140                 ScenarioOutputScanData.Text = DataHelpers.GetDataString(args.Report.ScanData);
00141                 ScenarioOutputScanDataType.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType);
00142             });
00143         }
00144
00145         /// <summary>
00146         /// Reset the Scenario state
00147         /// </summary>
00148         private void ResetTheScenarioState()
00149         {
00150             if (claimedScanner != null)
00151             {
00152                 // Detach the event handlers
00153                 claimedScanner.DataReceived -= claimedScanner_DataReceived;
00154                 claimedScanner.ReleaseDeviceRequested -= claimedScanner_ReleaseDeviceRequested;
00155                 // Release the Barcode Scanner and set to null
00156                 claimedScanner.Dispose();
00157                 claimedScanner = null;
00158             }
00159
00160             if (scanner != null)
00161             {
00162                 scanner.Dispose();
00163                 scanner = null;
00164             }
00165
00166             symbologyAttributes = null;
00167
00168             // Reset the UI if we are still the current page.
00169             if (Frame.Content == this)
00170             {
00171                 rootPage.NotifyUser("Click the start scanning button to begin.", NotifyType.StatusMessage);
00172                 this.ScenarioOutputScanData.Text = "No data";
00173                 this.ScenarioOutputScanDataLabel.Text = "No data";
00174                 this.ScenarioOutputScanDataType.Text = "No data";
00175
00176                 // reset the button state
00177                 ScenarioEndScanButton.IsEnabled = false;
00178                 ScenarioStartScanButton.IsEnabled = true;
00179                 SetSymbologyAttributesButton.IsEnabled = false;
00180                 EnableCheckDigit.IsEnabled = false;
00181                 TransmitCheckDigit.IsEnabled = false;
00182                 SetDecodeRangeLimits.IsEnabled = false;
00183
00184                 // reset symbology list
00185                 listOfSymbologies.Clear();
00186             }
00187         }
00188
00189         /// <summary>
00190         /// Event handler for End Scan Button Click.
00191         /// Releases the Barcode Scanner and resets the text in the UI
00192         /// </summary>
00193         /// <param name="sender"></param>
00194         /// <param name="e"></param>
00195         private void ScenarioEndScanButton_Click(object sender, RoutedEventArgs e)
00196         {
00197             // reset the scenario state
00198             this.ResetTheScenarioState();
00199         }
00200
00201         /// <summary>
00202         /// Event handler for Symbology listbox selection changed.
00203         /// Get symbology attributes and populate attribute UI components
00204         /// </summary>
00205         /// <param name="sender"></param>
00206         /// <param name="args"></param>
00207         private async void SymbologySelection_Changed(object sender, SelectionChangedEventArgs args)
00208         {
00209             if (claimedScanner != null)
00210             {
00211                 SymbologyListEntry symbologyListEntry = (SymbologyListEntry)SymbologyListBox.SelectedItem;
00212                 if (symbologyListEntry != null)
00213                 {
00214                     SetSymbologyAttributesButton.IsEnabled = false;
00215                     try
00216                     {
00217                         symbologyAttributes = await claimedScanner.GetSymbologyAttributesAsync(symbologyListEntry.Id);
00218                     }
00219                     catch (Exception)
00220                     {
00221                         symbologyAttributes = null;
00222                     }
00223
00224                     if (symbologyAttributes != null)
00225                     {
00226                         SetSymbologyAttributesButton.IsEnabled = true;
00227
00228                         // initialize attributes UIs
00229                         EnableCheckDigit.IsEnabled = symbologyAttributes.IsCheckDigitValidationSupported;
00230                         EnableCheckDigit.IsChecked = symbologyAttributes.IsCheckDigitValidationEnabled;
00231                         TransmitCheckDigit.IsEnabled = symbologyAttributes.IsCheckDigitTransmissionSupported;
00232                         TransmitCheckDigit.IsChecked = symbologyAttributes.IsCheckDigitTransmissionEnabled;
00233                         SetDecodeRangeLimits.IsEnabled = symbologyAttributes.IsDecodeLengthSupported;
00234                         bool decodeLengthEnabled = (symbologyAttributes.DecodeLengthKind == BarcodeSymbologyDecodeLengthKind.Range);
00235                         SetDecodeRangeLimits.IsChecked = decodeLengthEnabled;
00236                         if (decodeLengthEnabled)
00237                         {
00238                             MinimumDecodeLength.Value = Math.Min(symbologyAttributes.DecodeLength1, symbologyAttributes.DecodeLength2);
00239                             MaximumDecodeLength.Value = Math.Max(symbologyAttributes.DecodeLength1, symbologyAttributes.DecodeLength2);
00240                         }
00241                     }
00242                     else
00243                     {
00244                         rootPage.NotifyUser("Symbology attributes are not available.", NotifyType.ErrorMessage);
00245                         EnableCheckDigit.IsEnabled = false;
00246                         TransmitCheckDigit.IsEnabled = false;
00247                         SetDecodeRangeLimits.IsEnabled = false;
00248                     }
00249                 }
00250             }
00251         }
00252
00253         private async void SetSymbologyAttributes_Click(object sender, RoutedEventArgs e)
00254         {
00255             if ((claimedScanner != null) && (symbologyAttributes != null))
00256             {
00257                 // populate attributes
00258                 if (symbologyAttributes.IsCheckDigitValidationSupported)
00259                 {
00260                     symbologyAttributes.IsCheckDigitValidationEnabled = EnableCheckDigit.IsChecked.Value;
00261                 }
00262                 if (symbologyAttributes.IsCheckDigitTransmissionSupported)
00263                 {
00264                     symbologyAttributes.IsCheckDigitTransmissionEnabled = TransmitCheckDigit.IsChecked.Value;
00265                 }
00266                 if (symbologyAttributes.IsDecodeLengthSupported)
00267                 {
00268                     if (SetDecodeRangeLimits.IsChecked.Value)
00269                     {
00270                         symbologyAttributes.DecodeLengthKind = BarcodeSymbologyDecodeLengthKind.Range;
00271                         symbologyAttributes.DecodeLength1 = (uint)MinimumDecodeLength.Value;
00272                         symbologyAttributes.DecodeLength2 = (uint)MaximumDecodeLength.Value;
00273                     }
00274                     else
00275                     {
00276                         symbologyAttributes.DecodeLengthKind = BarcodeSymbologyDecodeLengthKind.AnyLength;
00277                     }
00278                 }
00279
00280                 SymbologyListEntry symbologyListEntry = (SymbologyListEntry)SymbologyListBox.SelectedItem;
00281                 if (symbologyListEntry != null)
00282                 {
00283                     bool attributesSet = false;
00284
00285                     try
00286                     {
00287                         attributesSet = await claimedScanner.SetSymbologyAttributesAsync(symbologyListEntry.Id, symbologyAttributes);
00288                     }
00289                     catch (Exception)
00290                     {
00291                         // Scanner could not set the attributes.
00292                     }
00293
00294                     if (attributesSet)
00295                     {
00296                         rootPage.NotifyUser("Attributes set for symbology '" + symbologyListEntry.Name + "'", NotifyType.StatusMessage);
00297                     }
00298                     else
00299                     {
00300                         rootPage.NotifyUser("Attributes could not be set for symbology '" + symbologyListEntry.Name + "'.", NotifyType.ErrorMessage);
00301                     }
00302                 }
00303                 else
00304                 {
00305                     rootPage.NotifyUser("Select a symbology from the list.", NotifyType.ErrorMessage);
00306                 }
00307             }
00308         }
00309     }
00310 }
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Content/NV12VideoTexture.h Source File

  • HolographicFaceTracking
  • cpp
  • Content

NV12VideoTexture.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015
00016 namespace HolographicFaceTracker
00017 {
00018     // Simple class to manage a NV12 texture and use it in Direct3D 11
00019     class NV12VideoTexture : public DX::Resource
00020     {
00021     public:
00022         NV12VideoTexture(
00023             std::shared_ptr<DX::DeviceResources> deviceResources,
00024             uint32_t width,
00025             uint32_t height);
00026
00027         void CopyFromVideoMediaFrame(
00028             Windows::Media::Capture::Frames::VideoMediaFrame^ source);
00029
00030         // DX::Resource Interface
00031         concurrency::task<void> CreateDeviceDependentResourcesAsync() override;
00032         void ReleaseDeviceDependentResources() override;
00033
00034         ID3D11Texture2D* GetTexture(void) const { return m_texture.Get(); }
00035         ID3D11ShaderResourceView* GetLuminanceTexture(void) const { return m_luminanceView.Get(); }
00036         ID3D11ShaderResourceView* GetChrominanceTexture(void) const { return m_chrominanceView.Get(); }
00037
00038     protected:
00039         Microsoft::WRL::ComPtr<ID3D11Texture2D>          m_texture;
00040         Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_luminanceView;
00041         Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> m_chrominanceView;
00042
00043         uint32_t const m_width;
00044         uint32_t const m_height;
00045     };
00046 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/MainPage.xaml.cs Source File

  • XamlBind
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Data;
00017 using Windows.UI.Xaml.Media;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class MainPage : Page
00028     {
00029         public static MainPage Current;
00030
00031         public MainPage()
00032         {
00033             this.InitializeComponent();
00034
00035             // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00036             // in order to call methods that are in this class.
00037             Current = this;
00038         }
00039
00040         protected override void OnNavigatedTo(NavigationEventArgs e)
00041         {
00042             // Populate the scenario list from the SampleConfiguration.cs file
00043             ScenarioControl.ItemsSource = scenarios;
00044             if (Window.Current.Bounds.Width < 640)
00045             {
00046                 ScenarioControl.SelectedIndex = -1;
00047             }
00048             else
00049             {
00050                 ScenarioControl.SelectedIndex = 0;
00051             }
00052         }
00053
00054         /// <summary>
00055         /// Called whenever the user changes selection in the scenarios list.  This method will navigate to the respective
00056         /// sample scenario page.
00057         /// </summary>
00058         /// <param name="sender"></param>
00059         /// <param name="e"></param>
00060         private void ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
00061         {
00062             // Clear the status block when navigating scenarios.
00063             NotifyUser(String.Empty, NotifyType.StatusMessage);
00064
00065             ListBox scenarioListBox = sender as ListBox;
00066             Scenario s = scenarioListBox.SelectedItem as Scenario;
00067             if (s != null)
00068             {
00069                 ScenarioFrame.Navigate(s.ClassType);
00070                 if (Window.Current.Bounds.Width < 640)
00071                 {
00072                     Splitter.IsPaneOpen = false;
00073                     StatusBorder.Visibility = Visibility.Collapsed;
00074                 }
00075             }
00076         }
00077
00078         public List<Scenario> Scenarios
00079         {
00080             get { return this.scenarios; }
00081         }
00082
00083         /// <summary>
00084         /// Used to display messages to the user
00085         /// </summary>
00086         /// <param name="strMessage"></param>
00087         /// <param name="type"></param>
00088         public void NotifyUser(string strMessage, NotifyType type)
00089         {
00090             switch (type)
00091             {
00092                 case NotifyType.StatusMessage:
00093                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green);
00094                     break;
00095                 case NotifyType.ErrorMessage:
00096                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red);
00097                     break;
00098             }
00099             StatusBlock.Text = strMessage;
00100
00101             // Collapse the StatusBlock if it has no text to conserve real estate.
00102             StatusPanel.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed;
00103         }
00104
00105         public void HideStatus()
00106         {
00107             this.StatusPanel.Visibility = Visibility.Collapsed;
00108         }
00109
00110         async void Footer_Click(object sender, RoutedEventArgs e)
00111         {
00112             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00113         }
00114
00115         private void Button_Click(object sender, RoutedEventArgs e)
00116         {
00117             Splitter.IsPaneOpen = !Splitter.IsPaneOpen;
00118             StatusBorder.Visibility = Visibility.Collapsed;
00119         }
00120     }
00121     public enum NotifyType
00122     {
00123         StatusMessage,
00124         ErrorMessage
00125     };
00126
00127     //public class ScenarioBindingConverter : IValueConverter
00128     //{
00129     //    public object Convert(object value, Type targetType, object parameter, string language)
00130     //    {
00131     //        Scenario s = value as Scenario;
00132     //        return (MainPage.Current.Scenarios.IndexOf(s) + 1) + ") " + s.Title;
00133     //    }
00134
00135     //    public object ConvertBack(object value, Type targetType, object parameter, string language)
00136     //    {
00137     //        return true;
00138     //    }
00139     //}
00140
00141 }
00142
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cs/scenario11.xaml.cs Source File

  • ApplicationResources
  • cs

scenario11.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using SDKTemplate;
00015 using System;
00016 using Windows.ApplicationModel.Resources;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     public sealed partial class Scenario11 : Page
00024     {
00025         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00026         // as NotifyUser()
00027         MainPage rootPage = MainPage.Current;
00028
00029         public Scenario11()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         /// <summary>
00035         /// Invoked when this page is about to be displayed in a Frame.
00036         /// </summary>
00037         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00038         /// property is typically used to configure the page.</param>
00039         protected override void OnNavigatedTo(NavigationEventArgs e)
00040         {
00041         }
00042
00043         /// <summary>
00044         /// This is the click handler for the 'Scenario11Button_Show' button.  You would replace this with your own handler
00045         /// if you have a button or buttons on this page.
00046         /// </summary>
00047         /// <param name="sender"></param>
00048         /// <param name="e"></param>
00049         private void Scenario11Button_Show_Click(object sender, RoutedEventArgs e)
00050         {
00051             Button b = sender as Button;
00052             if (b != null)
00053             {
00054                 var resourceLoader = ResourceLoader.GetForCurrentView();
00055                 this.Scenario11TextBlock.Text = "http://api.contoso.com/Feed?lang=" + resourceLoader.GetString("webservicelang");
00056             }
00057         }
00058     }
00059 }
Generated on Fri Nov 15 2024 22:18:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/NetworkServer.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

NetworkServer.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007 #pragma once
00008 #include "NetworkChannel.h"
00009
00010 namespace Microsoft { namespace Samples { namespace SimpleCommunication { namespace Network {
00011
00012     ref class CAcceptOperation;
00013
00014     ref class CNetworkServer sealed:
00015         public CNetworkChannel,
00016         public INetworkServer
00017     {
00018     public:
00019         virtual ~CNetworkServer();
00020
00021         // INetworkServer
00022         virtual Windows::Foundation::IAsyncOperation<Windows::Networking::Sockets::StreamSocketInformation^>^ AcceptAsync();
00023
00024     internal:
00025         CNetworkServer(unsigned short listeningPort);
00026
00027     protected:
00028         virtual void OnClose() override;
00029
00030     private:
00031         unsigned short _listeningPort;
00032         CAcceptOperation ^_acceptOperation;
00033     };
00034
00035     ref class CAcceptOperation sealed
00036     {
00037     public:
00038         virtual ~CAcceptOperation();
00039
00040     internal:
00041         CAcceptOperation(CNetworkServer ^parent, CritSec &critSec);
00042
00043         concurrency::task<IStreamSocket^> AcceptAsync(unsigned short port);
00044
00045     private:
00046         void Detach();
00047         void OnConnectionReceived(Windows::Networking::Sockets::StreamSocketListener ^sender, Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs ^args);
00048
00049         CritSec &_critSec;
00050         IStreamSocketListener ^_listener;
00051         concurrency::task_completion_event<IStreamSocket^>  _completionEvent;
00052         Windows::Foundation::EventRegistrationToken _connectionReceivedToken;
00053         CNetworkServer ^_parent;
00054         bool _fAsyncOperationInProgress;
00055     };
00056 }}}}
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/Scenario5_RestoreScrollPosition.h Source File

  • XamlListView
  • cppwinrt

Scenario5_RestoreScrollPosition.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "Item.h"
00014 #include "Scenario5_RestoreScrollPosition.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario5_RestoreScrollPosition : Scenario5_RestoreScrollPositionT<Scenario5_RestoreScrollPosition>
00019     {
00020         Scenario5_RestoreScrollPosition();
00021
00022         auto _items() { return items; }
00023         fire_and_forget Page_Loaded(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00024         void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs const&);
00025         void ItemsListView_ContainerContentChanging(Windows::UI::Xaml::Controls::ListViewBase const&, Windows::UI::Xaml::Controls::ContainerContentChangingEventArgs const& args);
00026         void ItemsListView_ItemClick(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00027
00028     private:
00029         Windows::Foundation::Collections::IObservableVector<SDKTemplate::Item> items = Item::GetItems(300);
00030
00031         // Static persisted variables are used by ListViewPersistenceHelper
00032         // We need to save the item container height if the items have variable heights. If all items have a constant fixed height, you can manually
00033         // set the height to the fixed value in ItemsListView_ContainerContentChanging
00034         static double _persistedItemContainerHeight;
00035         static hstring _persistedItemKey;
00036         static hstring _persistedPosition;
00037
00038         Windows::Foundation::IAsyncOperation<Windows::Foundation::IInspectable> GetItem(hstring const& key);
00039         hstring GetKey(IInspectable const& object);
00040     };
00041 }
00042
00043 namespace winrt::SDKTemplate::factory_implementation
00044 {
00045     struct Scenario5_RestoreScrollPosition : Scenario5_RestoreScrollPositionT<Scenario5_RestoreScrollPosition, implementation::Scenario5_RestoreScrollPosition>
00046     {
00047     };
00048 }
Generated on Fri Nov 15 2024 22:22:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/Contact.h Source File

  • XamlListView
  • cppwinrt

Contact.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Contact.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Contact : ContactT<Contact>
00019     {
00020         hstring Id() { return id; }
00021         hstring Initials() { return InitialOf(firstName) + InitialOf(lastName); }
00022         hstring Name() { return firstName + L" " + lastName; }
00023         hstring LastName() { return lastName; }
00024         hstring FirstName() { return firstName; }
00025         hstring Position() { return position; }
00026         hstring PhoneNumber() { return phoneNumber; }
00027         hstring Biography() { return biography; }
00028
00029         static SDKTemplate::Contact GetNewContact() { return make<Contact>(); }
00030         static Windows::Foundation::Collections::IObservableVector<SDKTemplate::Contact> GetContacts(int count);
00031         static Windows::Foundation::Collections::IObservableVector<SDKTemplate::GroupInfoList> GetContactsGrouped(int count);
00032
00033     private:
00034         hstring id = to_hstring(Windows::Foundation::GuidHelper::CreateNewGuid());
00035         hstring lastName = GenerateLastName();
00036         hstring firstName = GenerateFirstName();
00037         hstring position = GeneratePosition();
00038         hstring phoneNumber = GeneratePhoneNumber();
00039         hstring biography = GenerateBiography();
00040
00041         static hstring InitialOf(hstring const& word)
00042         {
00043             return hstring(static_cast<std::wstring_view>(word).substr(0, 1));
00044         }
00045
00046         static hstring GenerateLastName();
00047         static hstring GenerateFirstName();
00048         static hstring GeneratePosition();
00049         static hstring GeneratePhoneNumber();
00050         static hstring GenerateBiography();
00051     };
00052 }
Generated on Fri Nov 15 2024 22:22:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Prediction Member List

This is the complete list of members for Scenario2_Prediction, including all inherited members.
CreateGeneratorButton_Click(object sender, RoutedEventArgs e) | Scenario2_Prediction | [inline, private]
Execute_Click(object sender, RoutedEventArgs e) | Scenario2_Prediction | [inline, private]
generator | Scenario2_Prediction | [private]
Methods_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario2_Prediction | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_Prediction | [inline, protected]
rootPage | Scenario2_Prediction | [private]
Scenario2_Prediction() | Scenario2_Prediction | [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraGetPreviewFrame/cs/MainPage.xaml.cs Source File

  • CameraGetPreviewFrame
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Diagnostics;
00014 using System.Linq;
00015 using System.Runtime.InteropServices;
00016 using System.Threading;
00017 using System.Threading.Tasks;
00018 using Windows.ApplicationModel;
00019 using Windows.Devices.Enumeration;
00020 using Windows.Graphics.Display;
00021 using Windows.Graphics.Imaging;
00022 using Windows.Media;
00023 using Windows.Media.Capture;
00024 using Windows.Media.MediaProperties;
00025 using Windows.Storage;
00026 using Windows.System.Display;
00027 using Windows.UI.Core;
00028 using Windows.UI.Xaml;
00029 using Windows.UI.Xaml.Controls;
00030 using Windows.UI.Xaml.Input;
00031 using Windows.UI.Xaml.Media.Imaging;
00032 using Windows.UI.Xaml.Navigation;
00033
00034 namespace CameraGetPreviewFrame
00035 {
00036     [ComImport]
00037     [Guid("5b0d3235-4dba-4d44-865e-8f1d0e4fd04d")]
00038     [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
00039     unsafe interface IMemoryBufferByteAccess
00040     {
00041         void GetBuffer(out byte* buffer, out uint capacity);
00042     }
00043
00044     public sealed partial class MainPage : Page
00045     {
00046         // Receive notifications about rotation of the UI and apply any necessary rotation to the preview stream
00047         private readonly DisplayInformation _displayInformation = DisplayInformation.GetForCurrentView();
00048         private DisplayOrientations _displayOrientation = DisplayOrientations.Portrait;
00049
00050         // Rotation metadata to apply to the preview stream (MF_MT_VIDEO_ROTATION)
00051         // Reference: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868174.aspx
00052         private static readonly Guid RotationKey = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1");
00053
00054         // Folder in which the captures will be stored (initialized in InitializeCameraAsync)
00055         private StorageFolder _captureFolder = null;
00056
00057         // Prevent the screen from sleeping while the camera is running
00058         private readonly DisplayRequest _displayRequest = new DisplayRequest();
00059
00060         // For listening to media property changes
00061         private readonly SystemMediaTransportControls _systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
00062
00063         // MediaCapture and its state variables
00064         private MediaCapture _mediaCapture;
00065         private bool _isInitialized = false;
00066         private bool _isPreviewing = false;
00067         private static readonly SemaphoreSlim _mediaCaptureLifeLock = new SemaphoreSlim(1);
00068
00069         // Information about the camera device
00070         private bool _mirroringPreview = false;
00071         private bool _externalCamera = false;
00072
00073         #region Constructor, lifecycle and navigation
00074
00075         public MainPage()
00076         {
00077             this.InitializeComponent();
00078
00079             // Cache the UI to have the checkboxes retain their state, as the enabled/disabled state of the
00080             // GetPreviewFrameButton is reset in code when suspending/navigating (see Start/StopPreviewAsync)
00081             NavigationCacheMode = NavigationCacheMode.Required;
00082
00083             // Useful to know when to initialize/clean up the camera
00084             Application.Current.Suspending += Application_Suspending;
00085             Application.Current.Resuming += Application_Resuming;
00086         }
00087
00088         private async void Application_Suspending(object sender, SuspendingEventArgs e)
00089         {
00090             // Handle global application events only if this page is active
00091             if (Frame.CurrentSourcePageType == typeof(MainPage))
00092             {
00093                 var deferral = e.SuspendingOperation.GetDeferral();
00094
00095                 await CleanupCameraAsync();
00096
00097                 _displayInformation.OrientationChanged -= DisplayInformation_OrientationChanged;
00098
00099                 deferral.Complete();
00100             }
00101         }
00102
00103         private async void Application_Resuming(object sender, object o)
00104         {
00105             // Handle global application events only if this page is active
00106             if (Frame.CurrentSourcePageType == typeof(MainPage))
00107             {
00108                 // Populate orientation variables with the current state and register for future changes
00109                 _displayOrientation = _displayInformation.CurrentOrientation;
00110                 _displayInformation.OrientationChanged += DisplayInformation_OrientationChanged;
00111
00112                 await InitializeCameraAsync();
00113             }
00114         }
00115
00116         protected override async void OnNavigatedTo(NavigationEventArgs e)
00117         {
00118             // Populate orientation variables with the current state and register for future changes
00119             _displayOrientation = _displayInformation.CurrentOrientation;
00120             _displayInformation.OrientationChanged += DisplayInformation_OrientationChanged;
00121
00122             await InitializeCameraAsync();
00123         }
00124
00125         protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
00126         {
00127             // Handling of this event is included for completenes, as it will only fire when navigating between pages and this sample only includes one page
00128
00129             await CleanupCameraAsync();
00130
00131             _displayInformation.OrientationChanged -= DisplayInformation_OrientationChanged;
00132         }
00133
00134         #endregion Constructor, lifecycle and navigation
00135
00136
00137         #region Event handlers
00138
00139         /// <summary>
00140         /// In the event of the app being minimized this method handles media property change events. If the app receives a mute
00141         /// notification, it is no longer in the foregroud.
00142         /// </summary>
00143         /// <param name="sender"></param>
00144         /// <param name="args"></param>
00145         private async void SystemMediaControls_PropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs args)
00146         {
00147             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
00148             {
00149                 // Only handle this event if this page is currently being displayed
00150                 if (args.Property == SystemMediaTransportControlsProperty.SoundLevel && Frame.CurrentSourcePageType == typeof(MainPage))
00151                 {
00152                     // Check to see if the app is being muted. If so, it is being minimized.
00153                     // Otherwise if it is not initialized, it is being brought into focus.
00154                     if (sender.SoundLevel == SoundLevel.Muted)
00155                     {
00156                         await CleanupCameraAsync();
00157                     }
00158                     else if (!_isInitialized)
00159                     {
00160                         await InitializeCameraAsync();
00161                     }
00162                 }
00163             });
00164         }
00165
00166         /// <summary>
00167         /// This event will fire when the page is rotated
00168         /// </summary>
00169         /// <param name="sender">The event source.</param>
00170         /// <param name="args">The event data.</param>
00171         private async void DisplayInformation_OrientationChanged(DisplayInformation sender, object args)
00172         {
00173             _displayOrientation = sender.CurrentOrientation;
00174
00175             if (_isPreviewing)
00176             {
00177                 await SetPreviewRotationAsync();
00178             }
00179         }
00180
00181         private async void GetPreviewFrameButton_Click(object sender, RoutedEventArgs e)
00182         {
00183             // If preview is not running, no preview frames can be acquired
00184             if (!_isPreviewing) return;
00185
00186             if ((ShowFrameCheckBox.IsChecked == true) || (SaveFrameCheckBox.IsChecked == true))
00187             {
00188                 await GetPreviewFrameAsSoftwareBitmapAsync();
00189             }
00190             else
00191             {
00192                 await GetPreviewFrameAsD3DSurfaceAsync();
00193             }
00194         }
00195
00196         private async void MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs)
00197         {
00198             Debug.WriteLine("MediaCapture_Failed: (0x{0:X}) {1}", errorEventArgs.Code, errorEventArgs.Message);
00199
00200             await CleanupCameraAsync();
00201
00202             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => GetPreviewFrameButton.IsEnabled = _isPreviewing);
00203         }
00204
00205         #endregion Event handlers
00206
00207
00208         #region MediaCapture methods
00209
00210         /// <summary>
00211         /// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, and starts preview
00212         /// </summary>
00213         /// <returns></returns>
00214         private async Task InitializeCameraAsync()
00215         {
00216             Debug.WriteLine("InitializeCameraAsync");
00217
00218             await _mediaCaptureLifeLock.WaitAsync();
00219
00220             if (_mediaCapture == null)
00221             {
00222                 // Attempt to get the back camera if one is available, but use any camera device if not
00223                 var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);
00224
00225                 if (cameraDevice == null)
00226                 {
00227                     Debug.WriteLine("No camera device found!");
00228                     _mediaCaptureLifeLock.Release();
00229                     return;
00230                 }
00231
00232                 // Create MediaCapture and its settings
00233                 _mediaCapture = new MediaCapture();
00234
00235                 // Register for a notification when something goes wrong
00236                 _mediaCapture.Failed += MediaCapture_Failed;
00237
00238                 var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
00239
00240                 // Initialize MediaCapture
00241                 try
00242                 {
00243                     await _mediaCapture.InitializeAsync(settings);
00244                     _isInitialized = true;
00245                 }
00246                 catch (UnauthorizedAccessException)
00247                 {
00248                     Debug.WriteLine("The app was denied access to the camera");
00249                 }
00250                 finally
00251                 {
00252                     _mediaCaptureLifeLock.Release();
00253                 }
00254
00255                 // If initialization succeeded, start the preview
00256                 if (_isInitialized)
00257                 {
00258                     // Figure out where the camera is located
00259                     if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
00260                     {
00261                         // No information on the location of the camera, assume it's an external camera, not integrated on the device
00262                         _externalCamera = true;
00263                     }
00264                     else
00265                     {
00266                         // Camera is fixed on the device
00267                         _externalCamera = false;
00268
00269                         // Only mirror the preview if the camera is on the front panel
00270                         _mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
00271                     }
00272
00273                     await StartPreviewAsync();
00274
00275                     var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
00276                     // Fall back to the local app storage if the Pictures Library is not available
00277                     _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
00278                 }
00279             }
00280             else
00281             {
00282                 _mediaCaptureLifeLock.Release();
00283             }
00284         }
00285
00286         /// <summary>
00287         /// Starts the preview and adjusts it for for rotation and mirroring after making a request to keep the screen on and unlocks the UI
00288         /// </summary>
00289         /// <returns></returns>
00290         private async Task StartPreviewAsync()
00291         {
00292             Debug.WriteLine("StartPreviewAsync");
00293
00294             // Prevent the device from sleeping while the preview is running
00295             _displayRequest.RequestActive();
00296
00297             // Register to listen for media property changes
00298             _systemMediaControls.PropertyChanged += SystemMediaControls_PropertyChanged;
00299
00300             // Set the preview source in the UI and mirror it if necessary
00301             PreviewControl.Source = _mediaCapture;
00302             PreviewControl.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
00303
00304             // Start the preview
00305             await _mediaCapture.StartPreviewAsync();
00306             _isPreviewing = true;
00307
00308             // Initialize the preview to the current orientation
00309             if (_isPreviewing)
00310             {
00311                 await SetPreviewRotationAsync();
00312             }
00313
00314             // Enable / disable the button depending on the preview state
00315             GetPreviewFrameButton.IsEnabled = _isPreviewing;
00316         }
00317
00318         /// <summary>
00319         /// Gets the current orientation of the UI in relation to the device and applies a corrective rotation to the preview
00320         /// </summary>
00321         private async Task SetPreviewRotationAsync()
00322         {
00323             // Only need to update the orientation if the camera is mounted on the device
00324             if (_externalCamera) return;
00325
00326             // Calculate which way and how far to rotate the preview
00327             int rotationDegrees = ConvertDisplayOrientationToDegrees(_displayOrientation);
00328
00329             // The rotation direction needs to be inverted if the preview is being mirrored
00330             if (_mirroringPreview)
00331             {
00332                 rotationDegrees = (360 - rotationDegrees) % 360;
00333             }
00334
00335             // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames
00336             var props = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
00337             props.Properties.Add(RotationKey, rotationDegrees);
00338             await _mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, null);
00339         }
00340
00341         /// <summary>
00342         /// Stops the preview and deactivates a display request, to allow the screen to go into power saving modes, and locks the UI
00343         /// </summary>
00344         /// <returns></returns>
00345         private async Task StopPreviewAsync()
00346         {
00347             _isPreviewing = false;
00348             await _mediaCapture.StopPreviewAsync();
00349
00350             // Use the dispatcher because this method is sometimes called from non-UI threads
00351             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00352             {
00353                 PreviewControl.Source = null;
00354
00355                 // Allow the device to sleep now that the preview is stopped
00356                 _displayRequest.RequestRelease();
00357
00358                 GetPreviewFrameButton.IsEnabled = _isPreviewing;
00359             });
00360         }
00361
00362         /// <summary>
00363         /// Gets the current preview frame as a SoftwareBitmap, displays its properties in a TextBlock, and can optionally display the image
00364         /// in the UI and/or save it to disk as a jpg
00365         /// </summary>
00366         /// <returns></returns>
00367         private async Task GetPreviewFrameAsSoftwareBitmapAsync()
00368         {
00369             // Get information about the preview
00370             var previewProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
00371
00372             // Create the video frame to request a SoftwareBitmap preview frame
00373             var videoFrame = new VideoFrame(BitmapPixelFormat.Bgra8, (int)previewProperties.Width, (int)previewProperties.Height);
00374
00375             // Capture the preview frame
00376             using (var currentFrame = await _mediaCapture.GetPreviewFrameAsync(videoFrame))
00377             {
00378                 // Collect the resulting frame
00379                 SoftwareBitmap previewFrame = currentFrame.SoftwareBitmap;
00380
00381                 // Show the frame information
00382                 FrameInfoTextBlock.Text = String.Format("{0}x{1} {2}", previewFrame.PixelWidth, previewFrame.PixelHeight, previewFrame.BitmapPixelFormat);
00383
00384                 // Add a simple green filter effect to the SoftwareBitmap
00385                 if (GreenEffectCheckBox.IsChecked == true)
00386                 {
00387                     ApplyGreenFilter(previewFrame);
00388                 }
00389
00390                 // Show the frame (as is, no rotation is being applied)
00391                 if (ShowFrameCheckBox.IsChecked == true)
00392                 {
00393                     // Create a SoftwareBitmapSource to display the SoftwareBitmap to the user
00394                     var sbSource = new SoftwareBitmapSource();
00395                     await sbSource.SetBitmapAsync(previewFrame);
00396
00397                     // Display it in the Image control
00398                     PreviewFrameImage.Source = sbSource;
00399                 }
00400
00401                 // Save the frame (as is, no rotation is being applied)
00402                 if (SaveFrameCheckBox.IsChecked == true)
00403                 {
00404                     var file = await _captureFolder.CreateFileAsync("PreviewFrame.jpg", CreationCollisionOption.GenerateUniqueName);
00405
00406                     Debug.WriteLine("Saving preview frame to " + file.Path);
00407
00408                     await SaveSoftwareBitmapAsync(previewFrame, file);
00409                 }
00410             }
00411         }
00412
00413         /// <summary>
00414         /// Gets the current preview frame as a Direct3DSurface and displays its properties in a TextBlock
00415         /// </summary>
00416         /// <returns></returns>
00417         private async Task GetPreviewFrameAsD3DSurfaceAsync()
00418         {
00419             // Capture the preview frame as a D3D surface
00420             using (var currentFrame = await _mediaCapture.GetPreviewFrameAsync())
00421             {
00422                 // Check that the Direct3DSurface isn't null. It's possible that the device does not support getting the frame
00423                 // as a D3D surface
00424                 if (currentFrame.Direct3DSurface != null)
00425                 {
00426                     // Collect the resulting frame
00427                     var surface = currentFrame.Direct3DSurface;
00428
00429                     // Show the frame information
00430                     FrameInfoTextBlock.Text = String.Format("{0}x{1} {2}", surface.Description.Width, surface.Description.Height, surface.Description.Format);
00431                 }
00432                 else // Fall back to software bitmap
00433                 {
00434                     // Collect the resulting frame
00435                     SoftwareBitmap previewFrame = currentFrame.SoftwareBitmap;
00436
00437                     // Show the frame information
00438                     FrameInfoTextBlock.Text = String.Format("{0}x{1} {2}", previewFrame.PixelWidth, previewFrame.PixelHeight, previewFrame.BitmapPixelFormat);
00439                 }
00440
00441                 // Clear the image
00442                 PreviewFrameImage.Source = null;
00443             }
00444         }
00445
00446         /// <summary>
00447         /// Cleans up the camera resources (after stopping the preview if necessary) and unregisters from MediaCapture events
00448         /// </summary>
00449         /// <returns></returns>
00450         private async Task CleanupCameraAsync()
00451         {
00452             await _mediaCaptureLifeLock.WaitAsync();
00453
00454             try
00455             {
00456                 if (_isInitialized)
00457                 {
00458                     if (_isPreviewing)
00459                     {
00460                         // The call to stop the preview is included here for completeness, but can be
00461                         // safely removed if a call to MediaCapture.Dispose() is being made later,
00462                         // as the preview will be automatically stopped at that point
00463                         await StopPreviewAsync();
00464                     }
00465
00466                     _isInitialized = false;
00467                 }
00468
00469                 if (_mediaCapture != null)
00470                 {
00471                     _mediaCapture.Failed -= MediaCapture_Failed;
00472                     _mediaCapture.Dispose();
00473                     _mediaCapture = null;
00474                 }
00475             }
00476             finally
00477             {
00478                 _mediaCaptureLifeLock.Release();
00479             }
00480         }
00481
00482         #endregion MediaCapture methods
00483
00484
00485         #region Helper functions
00486
00487         /// <summary>
00488         /// Queries the available video capture devices to try and find one mounted on the desired panel
00489         /// </summary>
00490         /// <param name="desiredPanel">The panel on the device that the desired camera is mounted on</param>
00491         /// <returns>A DeviceInformation instance with a reference to the camera mounted on the desired panel if available,
00492         ///          any other camera if not, or null if no camera is available.</returns>
00493         private static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel)
00494         {
00495             // Get available devices for capturing pictures
00496             var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
00497
00498             // Get the desired camera by panel
00499             DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);
00500
00501             // If there is no device mounted on the desired panel, return the first device found
00502             return desiredDevice ?? allVideoDevices.FirstOrDefault();
00503         }
00504
00505         /// <summary>
00506         /// Converts the given orientation of the app on the screen to the corresponding rotation in degrees
00507         /// </summary>
00508         /// <param name="orientation">The orientation of the app on the screen</param>
00509         /// <returns>An orientation in degrees</returns>
00510         private static int ConvertDisplayOrientationToDegrees(DisplayOrientations orientation)
00511         {
00512             switch (orientation)
00513             {
00514                 case DisplayOrientations.Portrait:
00515                     return 90;
00516                 case DisplayOrientations.LandscapeFlipped:
00517                     return 180;
00518                 case DisplayOrientations.PortraitFlipped:
00519                     return 270;
00520                 case DisplayOrientations.Landscape:
00521                 default:
00522                     return 0;
00523             }
00524         }
00525
00526         /// <summary>
00527         /// Saves a SoftwareBitmap to the specified StorageFile
00528         /// </summary>
00529         /// <param name="bitmap">SoftwareBitmap to save</param>
00530         /// <param name="file">Target StorageFile to save to</param>
00531         /// <returns></returns>
00532         private static async Task SaveSoftwareBitmapAsync(SoftwareBitmap bitmap, StorageFile file)
00533         {
00534             using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
00535             {
00536                 var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream);
00537
00538                 // Grab the data from the SoftwareBitmap
00539                 encoder.SetSoftwareBitmap(bitmap);
00540                 await encoder.FlushAsync();
00541             }
00542         }
00543
00544         /// <summary>
00545         /// Applies a basic effect to a Bgra8 SoftwareBitmap in-place
00546         /// </summary>
00547         /// <param name="bitmap">SoftwareBitmap that will receive the effect</param>
00548         private unsafe void ApplyGreenFilter(SoftwareBitmap bitmap)
00549         {
00550             // Effect is hard-coded to operate on BGRA8 format only
00551             if (bitmap.BitmapPixelFormat == BitmapPixelFormat.Bgra8)
00552             {
00553                 // In BGRA8 format, each pixel is defined by 4 bytes
00554                 const int BYTES_PER_PIXEL = 4;
00555
00556                 using (var buffer = bitmap.LockBuffer(BitmapBufferAccessMode.ReadWrite))
00557                 using (var reference = buffer.CreateReference())
00558                 {
00559                     if (reference is IMemoryBufferByteAccess)
00560                     {
00561                         // Get a pointer to the pixel buffer
00562                         byte* data;
00563                         uint capacity;
00564                         ((IMemoryBufferByteAccess)reference).GetBuffer(out data, out capacity);
00565
00566                         // Get information about the BitmapBuffer
00567                         var desc = buffer.GetPlaneDescription(0);
00568
00569                         // Iterate over all pixels
00570                         for (uint row = 0; row < desc.Height; row++)
00571                         {
00572                             for (uint col = 0; col < desc.Width; col++)
00573                             {
00574                                 // Index of the current pixel in the buffer (defined by the next 4 bytes, BGRA8)
00575                                 var currPixel = desc.StartIndex + desc.Stride * row + BYTES_PER_PIXEL * col;
00576
00577                                 // Read the current pixel information into b,g,r channels (leave out alpha channel)
00578                                 var b = data[currPixel + 0]; // Blue
00579                                 var g = data[currPixel + 1]; // Green
00580                                 var r = data[currPixel + 2]; // Red
00581
00582                                 // Boost the green channel, leave the other two untouched
00583                                 data[currPixel + 0] = b;
00584                                 data[currPixel + 1] = (byte)Math.Min(g + 80, 255);
00585                                 data[currPixel + 2] = r;
00586                             }
00587                         }
00588                     }
00589                 }
00590             }
00591         }
00592
00593         #endregion Helper functions
00594
00595     }
00596 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AssociationLaunching/cs/Scenario1_LaunchFile.xaml.cs Source File

  • AssociationLaunching
  • cs

Scenario1_LaunchFile.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Storage;
00015 using Windows.System;
00016 using Windows.UI.ViewManagement;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020 using Windows.Foundation;
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class Scenario1_LaunchFile : Page
00028     {
00029         // A pointer back to the main page. This is needed if you want to call methods in MainPage such as NotifyUser().
00030         MainPage rootPage = MainPage.Current;
00031
00032         string fileToLaunch = @"Assets\microsoft-sdk.png";
00033
00034         public Scenario1_LaunchFile()
00035         {
00036             this.InitializeComponent();
00037             ViewPreference.ItemsSource = MainPage.ViewSizePreferences;
00038             ViewPreference.SelectedIndex = 0;
00039         }
00040
00041         private async Task<StorageFile> GetFileToLaunch()
00042         {
00043             // First, get the image file from the package's image directory.
00044             var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(fileToLaunch);
00045
00046             //Can't launch files directly from install folder so copy it over
00047             //to temporary folder first
00048             file = await file.CopyAsync(ApplicationData.Current.TemporaryFolder, "filetolaunch.png", NameCollisionOption.ReplaceExisting);
00049
00050             return file;
00051         }
00052
00053         /// <summary>
00054         // Launch a .png file that came with the package.
00055         /// </summary>
00056         private async void LaunchFileDefault()
00057         {
00058             // First, get the image file from the package's image directory.
00059             var file = await GetFileToLaunch();
00060
00061             // Next, launch the file.
00062             bool success = await Launcher.LaunchFileAsync(file);
00063             if (success)
00064             {
00065                 rootPage.NotifyUser("File launched: " + file.Name, NotifyType.StatusMessage);
00066             }
00067             else
00068             {
00069                 rootPage.NotifyUser("File launch failed.", NotifyType.ErrorMessage);
00070             }
00071         }
00072
00073         /// <summary>
00074         // Launch a .png file that came with the package. Show a warning prompt.
00075         /// </summary>
00076         private async void LaunchFileWithWarning()
00077         {
00078             // First, get the image file from the package's image directory.
00079             var file = await GetFileToLaunch();
00080
00081             // Next, configure the warning prompt.
00082             var options = new LauncherOptions() { TreatAsUntrusted = true };
00083
00084             // Finally, launch the file.
00085             bool success = await Launcher.LaunchFileAsync(file, options);
00086             if (success)
00087             {
00088                 rootPage.NotifyUser("File launched: " + file.Name, NotifyType.StatusMessage);
00089             }
00090             else
00091             {
00092                 rootPage.NotifyUser("File launch failed.", NotifyType.ErrorMessage);
00093             }
00094         }
00095
00096         /// <summary>
00097         // Launch a .png file that came with the package. Show an Open With dialog that lets the user chose the handler to use.
00098         /// </summary>
00099         private async void LaunchFileOpenWith(object sender, RoutedEventArgs e)
00100         {
00101             // First, get the image file from the package's image directory.
00102             var file = await GetFileToLaunch();
00103
00104             // Calculate the position for the Open With dialog.
00105             // An alternative to using the point is to set the rect of the UI element that triggered the launch.
00106             Point openWithPosition = MainPage.GetElementLocation(sender);
00107
00108             // Next, configure the Open With dialog.
00109             var options = new LauncherOptions();
00110             options.DisplayApplicationPicker = true;
00111             options.UI.InvocationPoint = openWithPosition;
00112             options.UI.PreferredPlacement = Windows.UI.Popups.Placement.Below;
00113
00114             // Finally, launch the file.
00115             bool success = await Launcher.LaunchFileAsync(file, options);
00116             if (success)
00117             {
00118                 rootPage.NotifyUser("File launched: " + file.Name, NotifyType.StatusMessage);
00119             }
00120             else
00121             {
00122                 rootPage.NotifyUser("File launch failed.", NotifyType.ErrorMessage);
00123             }
00124         }
00125
00126         /// <summary>
00127         // Launch a .png file that came with the package. Request to share the screen with the launched app.
00128         /// </summary>
00129         private async void LaunchFileSplitScreen()
00130         {
00131             // First, get a file via the picker.
00132             var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
00133             openPicker.FileTypeFilter.Add("*");
00134
00135             Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();
00136             if (file != null)
00137             {
00138                 // Configure the request for split screen launch.
00139                 var options = new LauncherOptions() { DesiredRemainingView = (ViewSizePreference)ViewPreference.SelectedValue };
00140
00141                 // Next, launch the file.
00142                 bool success = await Launcher.LaunchFileAsync(file, options);
00143                 if (success)
00144                 {
00145                     rootPage.NotifyUser("File launched: " + file.Name, NotifyType.StatusMessage);
00146                 }
00147                 else
00148                 {
00149                     rootPage.NotifyUser("File launch failed.", NotifyType.ErrorMessage);
00150                 }
00151             }
00152             else
00153             {
00154                 rootPage.NotifyUser("No file was picked.", NotifyType.ErrorMessage);
00155             }
00156         }
00157
00158         /// <summary>
00159         // Have the user pick a file, then launch it.
00160         /// </summary>
00161         private async void PickAndLaunchFile()
00162         {
00163             // First, get a file via the picker.
00164             var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
00165             openPicker.FileTypeFilter.Add("*");
00166             Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();
00167             if (file != null)
00168             {
00169                 // Next, launch the file.
00170                 bool success = await Launcher.LaunchFileAsync(file);
00171                 if (success)
00172                 {
00173                     rootPage.NotifyUser("File launched: " + file.Name, NotifyType.StatusMessage);
00174                 }
00175                 else
00176                 {
00177                     rootPage.NotifyUser("File launch failed.", NotifyType.ErrorMessage);
00178                 }
00179             }
00180             else
00181             {
00182                 rootPage.NotifyUser("No file was picked.", NotifyType.ErrorMessage);
00183             }
00184         }
00185
00186         /// <summary>
00187         // The Open With dialog should be displayed just under the element that triggered it.
00188         /// </summary>
00189         private Windows.Foundation.Point GetOpenWithPosition(FrameworkElement element)
00190         {
00191             Windows.UI.Xaml.Media.GeneralTransform buttonTransform = element.TransformToVisual(null);
00192
00193             Point desiredLocation = buttonTransform.TransformPoint(new Point());
00194             desiredLocation.Y = desiredLocation.Y + element.ActualHeight;
00195
00196             return desiredLocation;
00197         }
00198     }
00199 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CameraResources Member List

This is the complete list of members for CameraResources, including all inherited members.
AttachViewProjectionBuffer(DeviceResources deviceResources) | CameraResources | [inline]
BackBufferDxgiFormat | CameraResources |
BackBufferRenderTargetView | CameraResources |
BackBufferTexture2D | CameraResources |
CameraResources(HolographicCamera holographicCamera) | CameraResources | [inline]
CreateResourcesForBackBuffer(DeviceResources deviceResources, HolographicCameraRenderingParameters cameraParameters) | CameraResources | [inline]
d3dBackBuffer | CameraResources | [private]
d3dDepthStencilView | CameraResources | [private]
d3dRenderTargetSize | CameraResources | [private]
d3dRenderTargetView | CameraResources | [private]
d3dViewport | CameraResources | [private]
DepthStencilView | CameraResources |
Dispose() | Disposer | [inline]
Dispose(bool disposeManagedResources) | Disposer | [inline, protected, virtual]
Disposer() | Disposer | [inline, protected]
dxgiFormat | CameraResources | [private]
framePending | CameraResources | [private]
HolographicCamera | CameraResources |
holographicCamera | CameraResources | [private]
IsDisposed | Disposer | [protected]
IsRenderingStereoscopic | CameraResources |
isStereo | CameraResources | [private]
ReleaseAllDeviceResources(DeviceResources deviceResources) | CameraResources | [inline]
ReleaseResourcesForBackBuffer(DeviceResources deviceResources) | CameraResources | [inline]
RemoveAndDispose< T >(ref T objectToDispose) | Disposer | [inline, protected]
RemoveToDispose< T >(T objectToRemove) | Disposer | [inline, protected]
RenderTargetSize | CameraResources |
ToDispose< T >(T objectToDispose) | Disposer | [inline, protected]
UpdateViewProjectionBuffer(DeviceResources deviceResources, HolographicCameraPose cameraPose, SpatialCoordinateSystem coordinateSystem) | CameraResources | [inline]
Viewport | CameraResources |
viewProjectionConstantBuffer | CameraResources | [private]
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
ButtonUpdate_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
Generated on Fri Nov 15 2024 22:23:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScannerProvider/cpp/BarcodeDecoder/pch.cpp Source File

  • BarcodeScannerProvider
  • cpp
  • BarcodeDecoder

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInteractionMode/cpp/pch.h Source File

  • UserInteractionMode
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DpiScaling/cpp/SampleConfiguration.h Source File

  • DpiScaling
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "DPI scaling";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cs/Scenario09_GetCookie.xaml.cs Source File

  • HttpClient
  • cs

Scenario09_GetCookie.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading;
00014 using System.Threading.Tasks;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018 using Windows.Web.Http;
00019 using Windows.Web.Http.Filters;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario09_GetCookie : Page
00024     {
00025         MainPage rootPage = MainPage.Current;
00026
00027         private HttpClient httpClient;
00028         private CancellationTokenSource cts;
00029
00030         public Scenario09_GetCookie()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         protected override void OnNavigatedTo(NavigationEventArgs e)
00036         {
00037             httpClient = Helpers.CreateHttpClientWithPlugIn();
00038             cts = new CancellationTokenSource();
00039         }
00040
00041         protected override void OnNavigatedFrom(NavigationEventArgs e)
00042         {
00043             cts.Cancel();
00044             cts.Dispose();
00045             httpClient.Dispose();
00046         }
00047
00048         private void GetCookies_Click(object sender, RoutedEventArgs e)
00049         {
00050             Uri resourceUri = Helpers.TryParseHttpUri(AddressField.Text);
00051             if (resourceUri == null)
00052             {
00053                 rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
00054                 return;
00055             }
00056
00057             try
00058             {
00059                 HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
00060                 HttpCookieCollection cookieCollection = filter.CookieManager.GetCookies(resourceUri);
00061
00062                 OutputField.Text = cookieCollection.Count + " cookies found.\r\n";
00063                 foreach (HttpCookie cookie in cookieCollection)
00064                 {
00065                     OutputField.Text += "--------------------\r\n";
00066                     OutputField.Text += "Name: " + cookie.Name + "\r\n";
00067                     OutputField.Text += "Domain: " + cookie.Domain + "\r\n";
00068                     OutputField.Text += "Path: " + cookie.Path + "\r\n";
00069                     OutputField.Text += "Value: " + cookie.Value + "\r\n";
00070                     OutputField.Text += "Expires: " + cookie.Expires + "\r\n";
00071                     OutputField.Text += "Secure: " + cookie.Secure + "\r\n";
00072                     OutputField.Text += "HttpOnly: " + cookie.HttpOnly + "\r\n";
00073                 }
00074             }
00075             catch (Exception ex)
00076             {
00077                 rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage);
00078             }
00079         }
00080
00081         private async void SendHttpGetButton_Click(object sender, RoutedEventArgs e)
00082         {
00083             // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00084             // valid, absolute URI, we'll notify the user about the incorrect input.
00085             Uri resourceUri = Helpers.TryParseHttpUri(AddressField.Text);
00086             if (resourceUri == null)
00087             {
00088                 rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
00089                 return;
00090             }
00091
00092             Helpers.ScenarioStarted(SendHttpGetButton, CancelButton, OutputField);
00093             rootPage.NotifyUser("In progress", NotifyType.StatusMessage);
00094
00095             // This sample uses a "try" in order to support TaskCanceledException.
00096             // If you don't need to support cancellation, then the "try" is not needed.
00097             try
00098             {
00099                 HttpRequestResult result = await httpClient.TryGetAsync(resourceUri).AsTask(cts.Token);
00100
00101                 if (result.Succeeded)
00102                 {
00103                     await Helpers.DisplayTextResultAsync(result.ResponseMessage, OutputField, cts.Token);
00104
00105                     rootPage.NotifyUser("Completed", NotifyType.StatusMessage);
00106                 }
00107                 else
00108                 {
00109                     Helpers.DisplayWebError(rootPage, result.ExtendedError);
00110                 }
00111             }
00112             catch (TaskCanceledException)
00113             {
00114                 rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
00115             }
00116
00117             Helpers.ScenarioCompleted(SendHttpGetButton, CancelButton);
00118         }
00119
00120         private void Cancel_Click(object sender, RoutedEventArgs e)
00121         {
00122             cts.Cancel();
00123             cts.Dispose();
00124
00125             // Re-create the CancellationTokenSource.
00126             cts = new CancellationTokenSource();
00127         }
00128     }
00129 }
Generated on Fri Nov 15 2024 22:19:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserConsentVerifier/cpp/SampleConfiguration.cpp Source File

  • UserConsentVerifier
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Check Consent Availability", "SDKTemplate.Scenario1_CheckConsentAvailability" },
00012     { "Request Consent", "SDKTemplate.Scenario2_RequestConsent" }
00013 };
Generated on Fri Nov 15 2024 22:17:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PosPrinter/cpp/Scenario1_ReceiptPrinter.xaml.cpp Source File

  • PosPrinter
  • cpp

Scenario1_ReceiptPrinter.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_ReceiptPrinter.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Primitives;
00023 using namespace Windows::UI::Xaml::Data;
00024 using namespace Windows::UI::Xaml::Input;
00025 using namespace Windows::UI::Xaml::Media;
00026 using namespace Windows::UI::Xaml::Navigation;
00027 using namespace Concurrency;
00028 using namespace Windows::Devices::PointOfService;
00029 using namespace Windows::UI::Core;
00030 using namespace Windows::Devices::Enumeration;
00031
00032 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00033
00034 Scenario1_ReceiptPrinter::Scenario1_ReceiptPrinter() : rootPage(MainPage::Current)
00035 {
00036     InitializeComponent();
00037     ResetTheScenarioState();
00038 }
00039
00040 //
00041 //Creates multiple tasks, first to find a receipt printer, then to claim the printer and then to enable and add releasedevicerequested event handler.
00042 //
00043 void Scenario1_ReceiptPrinter::FindClaimEnable_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00044 {
00045     create_task(FindReceiptPrinter()).then([this]()
00046     {
00047         if (printer != nullptr)
00048         {
00049             create_task(ClaimPrinter()).then([this](void)
00050             {
00051                 if (claimedPrinter)
00052                 {
00053                     create_task(EnableAsync()).then([this](void)
00054                     {
00055                         releaseDeviceRequestedToken = claimedPrinter->ReleaseDeviceRequested::add
00056                         (ref new TypedEventHandler<ClaimedPosPrinter^, PosPrinterReleaseDeviceRequestedEventArgs^ >(this, &Scenario1_ReceiptPrinter::ClaimedPrinter_ReleaseDeviceRequested));
00057                     });
00058                 }
00059             });
00060         }
00061     });
00062 }
00063
00064 //
00065 //Default checkbox selection makes it an important transaction, hence we do not release claim when we get a release devicerequested event.
00066 //
00067 void Scenario1_ReceiptPrinter::ClaimedPrinter_ReleaseDeviceRequested(ClaimedPosPrinter ^claimedInstance, PosPrinterReleaseDeviceRequestedEventArgs ^args)
00068 {
00069     if (IsAnImportantTransaction)
00070     {
00071         create_task(claimedInstance->RetainDeviceAsync());
00072     }
00073     else
00074     {
00075         ResetTheScenarioState();
00076     }
00077 }
00078
00079 //
00080 //Prints the line that is in the textbox.
00081 //
00082 void Scenario1_ReceiptPrinter::PrintLine_Click(Platform::Object ^sender, RoutedEventArgs e)
00083 {
00084     if (claimedPrinter != nullptr)
00085     {
00086         ReceiptPrintJob^ job = claimedPrinter->Receipt->CreateJob();
00087         job->PrintLine(txtPrintLine->Text);
00088
00089         create_task(job->ExecuteAsync()).then([this](bool status)
00090         {
00091             if (status)
00092             {
00093                 rootPage->NotifyUser("Printed line", NotifyType::StatusMessage);
00094             }
00095             else
00096             {
00097                 rootPage->NotifyUser("Could not Print line", NotifyType::ErrorMessage);
00098             }
00099         });
00100     }
00101     else
00102     {
00103         rootPage->NotifyUser("Could not Print line. No claimed printer found.", NotifyType::ErrorMessage);
00104     }
00105
00106 }
00107
00108 void Scenario1_ReceiptPrinter::PrintReceipt_Click(Platform::Object ^sender, RoutedEventArgs e)
00109 {
00110     rootPage->NotifyUser("Trying to Print Receipt", NotifyType::StatusMessage);
00111     PrintReceipt();
00112
00113 }
00114
00115 void Scenario1_ReceiptPrinter::EndScenario_Click(Platform::Object ^sender, RoutedEventArgs e)
00116 {
00117     ResetTheScenarioState();
00118     rootPage->NotifyUser("Disconnected Printer", NotifyType::StatusMessage);
00119 }
00120
00121 //
00122 //Actual claim method task that claims the printer asynchronously
00123 //
00124 task<void> Scenario1_ReceiptPrinter::ClaimPrinter()
00125 {
00126     if (claimedPrinter == nullptr)
00127     {
00128         return create_task(printer->ClaimPrinterAsync()).then([this](ClaimedPosPrinter^ _claimedPrinter)
00129         {
00130             this->claimedPrinter = _claimedPrinter;
00131             if (claimedPrinter != nullptr)
00132             {
00133                 rootPage->NotifyUser("Claimed Printer", NotifyType::StatusMessage);
00134             }
00135             else
00136             {
00137                 rootPage->NotifyUser("Claim Printer failed", NotifyType::ErrorMessage);
00138             }
00139         });
00140     }
00141
00142     return task_from_result();
00143 }
00144
00145 task<void> Scenario1_ReceiptPrinter::EnableAsync()
00146 {
00147     if (claimedPrinter)
00148     {
00149         return create_task(claimedPrinter->EnableAsync()).then([this](bool)
00150         {
00151             rootPage->NotifyUser("Enabled printer.", NotifyType::StatusMessage);
00152         });
00153     }
00154     else
00155     {
00156         rootPage->NotifyUser("Error: Printer not claimed anymore to enable.", NotifyType::ErrorMessage);
00157         return task_from_result();
00158     }
00159 }
00160
00161 //
00162 //Prints a sample receipt.
00163 //
00164 void Scenario1_ReceiptPrinter::PrintReceipt()
00165 {
00166     if (printer != nullptr && claimedPrinter != nullptr)
00167     {
00168         String^ receiptString =
00169             "======================\n" +
00170             "|   Sample Header    |\n" +
00171             "======================\n" +
00172             "Item             Price\n" +
00173             "----------------------\n" +
00174             "Books            10.40\n" +
00175             "Games             9.60\n" +
00176             "----------------------\n" +
00177             "Total----------- 20.00\n";
00178
00179         ReceiptPrintJob^ merchantJob = claimedPrinter->Receipt->CreateJob();
00180         String^ merchantFooter = GetMerchantFooter();
00181         PrintLineFeedAndCutPaper(merchantJob, receiptString + merchantFooter);
00182         ReceiptPrintJob^ customerJob = claimedPrinter->Receipt->CreateJob();
00183         String^ customerFooter = GetCustomerFooter();
00184         PrintLineFeedAndCutPaper(customerJob, receiptString + customerFooter);
00185
00186
00187
00188         create_task(merchantJob->ExecuteAsync()).then([this, customerJob](bool)
00189         {
00190             rootPage->NotifyUser("Printed merchant receipt.", NotifyType::StatusMessage);
00191             create_task(customerJob->ExecuteAsync()).then([this](bool)
00192             {
00193                 rootPage->NotifyUser("Printed customer receipt.", NotifyType::StatusMessage);
00194             });
00195         });
00196
00197
00198     }
00199     else
00200     {
00201         rootPage->NotifyUser("Must find and claim printer before printing.", NotifyType::ErrorMessage);
00202     }
00203 }
00204
00205 Platform::String^ Scenario1_ReceiptPrinter::GetMerchantFooter()
00206 {
00207     return
00208         "\n" +
00209         "______________________\n" +
00210         "Tip\n" +
00211         "\n" +
00212         "______________________\n" +
00213         "Signature\n" +
00214         "\n" +
00215         "Merchant Copy\n";
00216 }
00217
00218 Platform::String^ Scenario1_ReceiptPrinter::GetCustomerFooter()
00219 {
00220     return
00221         "\n" +
00222         "______________________\n" +
00223         "Tip\n" +
00224         "\n" +
00225         "Customer Copy\n";
00226 }
00227
00228 // Cut the paper after printing enough blank lines to clear the paper cutter.
00229 void Scenario1_ReceiptPrinter::PrintLineFeedAndCutPaper(ReceiptPrintJob^ job, Platform::String^ receipt)
00230 {
00231     if (printer != nullptr && claimedPrinter != nullptr)
00232     {
00233         // Passing a multi-line string to the Print method results in
00234         // smoother paper feeding than sending multiple single-line strings
00235         // to PrintLine.
00236
00237         Platform::String^ feedString = "";
00238         for (unsigned int n = 0; n < claimedPrinter->Receipt->LinesToPaperCut; n++)
00239         {
00240             feedString += "\n";
00241         }
00242         job->Print(receipt + feedString);
00243         if (printer->Capabilities->Receipt->CanCutPaper)
00244         {
00245             job->CutPaper();
00246         }
00247     }
00248 }
00249
00250 task<void> Scenario1_ReceiptPrinter::FindReceiptPrinter()
00251 {
00252     if (printer == nullptr)
00253     {
00254         rootPage->NotifyUser("Finding printer", NotifyType::StatusMessage);
00255         return DeviceHelpers::GetFirstReceiptPrinterAsync().then([this](PosPrinter^ _printer)
00256         {
00257             printer = _printer;
00258             if (printer != nullptr)
00259             {
00260                 rootPage->NotifyUser("Got Printer with Device Id : " + printer->DeviceId, NotifyType::StatusMessage);
00261             }
00262             else
00263             {
00264                 rootPage->NotifyUser("Could not get printer.", NotifyType::ErrorMessage);
00265             }
00266         });
00267     }
00268     return task_from_result();
00269 }
00270
00271 //
00272 //Remove event handler and delete claimed instance.
00273 //
00274 void Scenario1_ReceiptPrinter::ResetTheScenarioState()
00275 {
00276     if (claimedPrinter != nullptr)
00277     {
00278         claimedPrinter->ReleaseDeviceRequested::remove(releaseDeviceRequestedToken);
00279         delete claimedPrinter;
00280         claimedPrinter = nullptr;
00281     }
00282
00283     if (printer != nullptr)
00284     {
00285         delete printer;
00286         printer = nullptr;
00287     }
00288 }
00289
00290 /// <summary>
00291 /// Invoked when this page is about to be displayed in a Frame.
00292 /// </summary>
00293 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00294 /// property is typically used to configure the page.</param>
00295 void Scenario1_ReceiptPrinter::OnNavigatedTo(NavigationEventArgs^ e)
00296 {
00297     ResetTheScenarioState();
00298 }
00299
00300 /// <summary>
00301 /// Invoked when this page is no longer displayed.
00302 /// </summary>
00303 /// <param name="e"></param>
00304 void Scenario1_ReceiptPrinter::OnNavigatedFrom(NavigationEventArgs^ e)
00305 {
00306     ResetTheScenarioState();
00307 }
Generated on Fri Nov 15 2024 22:20:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDeferLoadStrategy/cs/TitledImage.cs Source File

  • XamlDeferLoadStrategy
  • cs

TitledImage.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Xaml;
00002 using Windows.UI.Xaml.Controls;
00003 using Windows.UI.Xaml.Media;
00004 using Windows.UI.Xaml.Media.Imaging;
00005
00006 namespace xDeferLoadStrategy
00007 {
00008     public class TitledImage : Control
00009     {
00010         public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register("Header", typeof(string), typeof(TitledImage), new PropertyMetadata(null));
00011         public string Header
00012         {
00013             get { return (string)GetValue(HeaderProperty); }
00014             set { SetValue(HeaderProperty, value); }
00015         }
00016
00017         void HeaderChanged(DependencyObject sender, DependencyProperty prop)
00018         {
00019             string header = (string)sender.GetValue(prop);
00020             //Double check to make sure that we don't needlessly realize the header presenter
00021             if (!string.IsNullOrEmpty(Header) && _header == null)
00022             {
00023                 _header = (ContentPresenter)GetTemplateChild("HeaderPresenter"); //This will realize the element
00024             }
00025         }
00026
00027         public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(ImageSource), typeof(TitledImage), new PropertyMetadata(null));
00028         public ImageSource Source
00029         {
00030             get { return (BitmapSource)GetValue(SourceProperty); }
00031             set { SetValue(SourceProperty, value); }
00032         }
00033
00034         private ContentPresenter _header;
00035
00036         public TitledImage()
00037         {
00038             this.DefaultStyleKey = typeof(TitledImage);
00039
00040             //We need to register the callback in case they change the header at runtime
00041             this.RegisterPropertyChangedCallback(HeaderProperty, HeaderChanged);
00042         }
00043
00044         protected override void OnApplyTemplate()
00045         {
00046             base.OnApplyTemplate();
00047
00048             //Check to see if there's a header, and realize the element if there is one
00049             if(!string.IsNullOrEmpty(Header))
00050             {
00051                 _header = (ContentPresenter)GetTemplateChild("HeaderPresenter"); //This will realize the element
00052             }
00053         }
00054     }
00055 }
Generated on Fri Nov 15 2024 22:22:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ContinuationPage Member List

This is the complete list of members for ContinuationPage, including all inherited members.
ContinuationPage(RichTextBlockOverflow textLinkContainer) ContinuationPage [inline]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/ComputeShader/CustomComputeShaderMain.cpp Source File

  • D2DCustomEffects
  • cpp
  • ComputeShader

CustomComputeShaderMain.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "CustomComputeShaderMain.h"
00014 #include "DirectXHelper.h"
00015
00016 using namespace CustomComputeShader;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::System::Threading;
00020 using namespace Windows::UI::Core;
00021 using namespace Concurrency;
00022
00023 // Loads and initializes application assets when the application is loaded.
00024 CustomComputeShaderMain::CustomComputeShaderMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00025     m_deviceResources(deviceResources)
00026 {
00027     // Register to be notified if the Device is lost or recreated.
00028     m_deviceResources->RegisterDeviceNotify(this);
00029
00030     m_sceneRenderer = std::unique_ptr<CustomComputeShaderRenderer>(new CustomComputeShaderRenderer(m_deviceResources));
00031     m_sampleOverlay = std::unique_ptr<SampleOverlay>(new SampleOverlay(m_deviceResources, L"Direct2D Custom Compute Shader Effect"));
00032 }
00033
00034 CustomComputeShaderMain::~CustomComputeShaderMain()
00035 {
00036     // Deregister device notification.
00037     m_deviceResources->RegisterDeviceNotify(nullptr);
00038 }
00039
00040 // Updates application state when the window size changes (e.g. device orientation change)
00041 void CustomComputeShaderMain::CreateWindowSizeDependentResources()
00042 {
00043     m_sceneRenderer->CreateWindowSizeDependentResources();
00044     m_sampleOverlay->CreateWindowSizeDependentResources();
00045 }
00046
00047 void CustomComputeShaderMain::Update()
00048 {
00049     // Unlike the pixel and vertex shader effects, the compute shader effect does not animate over time.
00050     // Therefore, render state is only updated on events such as CreateWindowSizeDependentResources().
00051 }
00052
00053 // Renders the current frame according to the current application state.
00054 // Returns true if the frame was rendered and is ready to be displayed.
00055 bool CustomComputeShaderMain::Render()
00056 {
00057     m_sceneRenderer->Render();
00058     m_sampleOverlay->Render();
00059
00060     return true;
00061 }
00062
00063 // Notifies renderers that device resources need to be released.
00064 void CustomComputeShaderMain::OnDeviceLost()
00065 {
00066     m_sceneRenderer->ReleaseDeviceDependentResources();
00067     m_sampleOverlay->ReleaseDeviceDependentResources();
00068 }
00069
00070 // Notifies renderers that device resources may now be recreated.
00071 void CustomComputeShaderMain::OnDeviceRestored()
00072 {
00073     m_sceneRenderer->CreateDeviceDependentResources();
00074     m_sampleOverlay->CreateDeviceDependentResources();
00075     CreateWindowSizeDependentResources();
00076 }
00077
00078 void CustomComputeShaderMain::SaveInternalState(_In_ IPropertySet ^ state)
00079 {
00080     m_sceneRenderer->SaveInternalState(state);
00081 }
00082
00083 void CustomComputeShaderMain::LoadInternalState(_In_ IPropertySet ^ state)
00084 {
00085     m_sceneRenderer->LoadInternalState(state);
00086 }
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BadgeNotificationHistoryChangedTriggerTask Member List

This is the complete list of members for BadgeNotificationHistoryChangedTriggerTask, including all inherited members.
Run(IBackgroundTaskInstance taskInstance) BadgeNotificationHistoryChangedTriggerTask [inline]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3 Member List

This is the complete list of members for Scenario3, including all inherited members.
OnNavigatedTo(NavigationEventArgs e) | Scenario3 | [inline, protected]
rootPage | Scenario3 | [private]
Scenario3() | Scenario3 | [inline]
SendHello_Click(object sender, RoutedEventArgs e) | Scenario3 | [inline, private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cpp/Scenario2_DecimalFormatting.xaml.cpp Source File

  • NumberFormatting
  • cpp

Scenario2_DecimalFormatting.xaml.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario2_DecimalFormatting.xaml.h"
00005
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace Platform;
00010 using namespace Windows::UI::Xaml;
00011 using namespace Windows::UI::Xaml::Controls;
00012 using namespace Windows::UI::Xaml::Navigation;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::Foundation::Collections;
00015 using namespace Windows::Globalization::NumberFormatting;
00016
00017 Scenario2_DecimalFormatting::Scenario2_DecimalFormatting()
00018 {
00019     InitializeComponent();
00020 }
00021
00022 void Scenario2_DecimalFormatting::Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00023 {
00024     // This scenario uses the Windows.Globalization.NumberFormatting.DecimalFormatter class
00025     // to format a number.
00026
00027     // Create formatter initialized using the current user's preference settings.
00028     DecimalFormatter^ decimalFormat = ref new DecimalFormatter();
00029
00030     // Make a random number.
00031     float randomNumber = (float)rand() / RAND_MAX * 100000.0f;
00032
00033     // Format with the user's default preferences.
00034     String^ decimal = decimalFormat->Format(randomNumber);
00035
00036     // Format with grouping.
00037     DecimalFormatter^ decimalFormat1 = ref new DecimalFormatter();
00038     decimalFormat1->IsGrouped = true;
00039     String^ decimal1 = decimalFormat1->Format(randomNumber);
00040
00041     // Format with grouping using French.
00042     auto fr = ref new Platform::Collections::Vector<String^>();
00043     fr->Append("fr-FR");
00044     DecimalFormatter^ decimalFormatFR = ref new DecimalFormatter(fr, "ZZ");
00045     decimalFormatFR->IsGrouped = true;
00046     String^ decimalFR = decimalFormatFR->Format(randomNumber);
00047
00048     // Illustrate how automatic digit substitution works
00049     auto ar = ref new Platform::Collections::Vector<String^>();
00050     ar->Append("ar");
00051     DecimalFormatter^ decimalFormatAR = ref new DecimalFormatter(ar, "ZZ");
00052     String^ decimalAR = decimalFormatAR->Format(randomNumber);
00053
00054     // Get a fixed number.
00055     long long fixedNumber = 500;
00056
00057     // Format with the user's default preferences.
00058     String^ decimal2 = decimalFormat->Format(fixedNumber);
00059
00060     // Format always with a decimal point.
00061     DecimalFormatter^ decimalFormat3 = ref new DecimalFormatter();
00062     decimalFormat3->IsDecimalPointAlwaysDisplayed = true;
00063     decimalFormat3->FractionDigits = 0;
00064     String^ decimal3 = decimalFormat3->Format(fixedNumber);
00065
00066     // Format with no fractional digits or decimal point.
00067     DecimalFormatter^ decimalFormat4 = ref new DecimalFormatter();
00068     decimalFormat4->FractionDigits = 0;
00069     String^ decimal4 = decimalFormat4->Format(fixedNumber);
00070
00071     // Display the results.
00072     String^ results =
00073         "Random number ("                             + randomNumber + ")\n" +
00074         "With current user preferences: "             + decimal   + "\n" +
00075         "With grouping separators: "                  + decimal1  + "\n" +
00076         "With grouping separators (fr-FR): "          + decimalFR + "\n" +
00077         "With digit substitution (ar): "              + decimalAR + "\n\n" +
00078         "Fixed number ("                              + fixedNumber + ")\n" +
00079         "With current user preferences: "             + decimal2 + "\n" +
00080         "Always with a decimal point: "               + decimal3 + "\n" +
00081         "With no fraction digits or decimal points: " + decimal4;
00082
00083     OutputTextBlock->Text = results;
00084 }
Generated on Fri Nov 15 2024 22:20:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/cpp/Scenario1_LowLatency.xaml.h Source File

  • SimpleCommunication
  • cpp

Scenario1_LowLatency.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_LowLatency.g.h"
00015 #include "Utils.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario1_LowLatency sealed
00024     {
00025     public:
00026         Scenario1_LowLatency();
00027
00028     protected:
00029         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030         virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00031         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00032
00033         void VisibilityChanged(Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00034
00035     private:
00036         task<void> Initialize();
00037         void InitializeUIControls();
00038         void Reset();
00039         void UpdateLocalClientWindow();
00040         task<void> Cleanup();
00041         task<void> StartRecordingToCustomSink();
00042
00043         VideoSettingsFilter^ _videoSettingsFilter;
00044
00045         Windows::Foundation::EventRegistrationToken _incomingConnectionEventRegistrationToken;
00046         Windows::Foundation::EventRegistrationToken _mediaCaptureFailedEventRegistrationToken;
00047         void OnMediaCaptureFailed(CaptureDevice^ sender, CaptureFailedEventArgs^ errorEventArgs);
00048         void OnIncomingConnection(Microsoft::Samples::SimpleCommunication::StspMediaSinkProxy^ sender, Microsoft::Samples::SimpleCommunication::IncomingConnectionEventArgs^ args);
00049         void HandleError(Platform::Exception^ error, Platform::String^ msg, Platform::String^ prefix);
00050
00051         enum class ScenarioOneStates
00052         {
00053             uninitialized,
00054             initializing,
00055             waiting,
00056             previewing,
00057             streaming,
00058             end,
00059         };
00060         ScenarioOneStates _currentState;
00061         ScenarioOneStates _previousState;
00062
00063         /// This is the FSM encapsulating the state table (states and actions) of the scenario.
00064         delegate IAsyncAction^ ActionTransition();
00065         std::map<ScenarioOneStates, std::array<ActionTransition^, 5>> actionTransitionFunctions;
00066         IAsyncAction^ initializing_previewSetupCompleted();
00067         IAsyncAction^ waiting_previewButtonClicked();
00068         IAsyncAction^ previewing_previewButtonClicked();
00069         IAsyncAction^ previewing_localClientButtonClicked();
00070         IAsyncAction^ previewing_recordingStarted();
00071         IAsyncAction^ streaming_previewButtonClicked();
00072         IAsyncAction^ streaming_latencyModeToggled();
00073         IAsyncAction^ streaming_recordingStarted();
00074
00075         enum class LatencyModes
00076         {
00077             uninitialized,
00078             highLatency,
00079             lowLatency,
00080         };
00081         LatencyModes _latencyMode;
00082         std::map<LatencyModes, Windows::UI::Xaml::Controls::MediaElement^> _localHostVideo;
00083
00084         value struct StreamFilteringCriteria
00085         {
00086             Platform::String^   aspectRatio;
00087             int                 horizontalResolution;
00088             Platform::String^   subType;
00089         };
00090         StreamFilteringCriteria _streamFilteringCriteria;
00091
00092         bool _initialized;
00093         CaptureDevice^ _device;
00094
00095         void PreviewButtonClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00096         void LocalClientButtonClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00097         void LatencyModeToggled(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00098
00099         SdkSample _sdkSample;
00100         Windows::UI::Core::CoreDispatcher^ _dispatcher;
00101         Windows::Foundation::EventRegistrationToken m_visibilityEventRegistrationToken;
00102
00103         void OnMediaFailed(Platform::Object^ sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^ e);
00104
00105         void LockScenarioChange();
00106         void UnlockScenarioChange();
00107
00108         long volatile _navigationDisabled;
00109     };
00110 }
Generated on Fri Nov 15 2024 22:21:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/BackgroundTask/Scenario4_TimeTriggeredTask.xaml.cpp Source File

  • BackgroundTask
  • cpp
  • BackgroundTask

Scenario4_TimeTriggeredTask.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario4_TimeTriggeredTask.xaml.cpp
00013 // Implementation of the TimeTriggeredTask class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario4_TimeTriggeredTask.xaml.h"
00018 #include "SampleConfiguration.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::ApplicationModel::Background;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 TimeTriggeredTask::TimeTriggeredTask()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Invoked when this page is about to be displayed in a Frame.
00035 /// </summary>
00036 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037 /// property is typically used to configure the page.</param>
00038 void TimeTriggeredTask::OnNavigatedTo(NavigationEventArgs^ e)
00039 {
00040     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00041     // as NotifyUser()
00042     rootPage = MainPage::Current;
00043
00044     //
00045     // Attach progress and completed handlers to any existing tasks.
00046     //
00047     for (auto pair : BackgroundTaskRegistration::AllTasks)
00048     {
00049         auto task = pair->Value;
00050         if (task->Name == TimeTriggeredTaskName)
00051         {
00052             BackgroundTaskSample::UpdateBackgroundTaskRegistrationStatus(task->Name, true);
00053             AttachProgressAndCompletedHandlers(task);
00054             break;
00055         }
00056     }
00057
00058     UpdateUI();
00059 }
00060
00061 /// <summary>
00062 /// Attach progress and completed handers to a background task.
00063 /// </summary>
00064 /// <param name="task">The task to attach progress and completed handlers to.</param>
00065 void TimeTriggeredTask::AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration^ task)
00066 {
00067     task->Progress += ref new BackgroundTaskProgressEventHandler(this, &TimeTriggeredTask::OnProgress);
00068     task->Completed += ref new BackgroundTaskCompletedEventHandler(this, &TimeTriggeredTask::OnCompleted);
00069 }
00070
00071 /// <summary>
00072 /// Register a TimeTriggeredTask.
00073 /// </summary>
00074 /// <param name="sender"></param>
00075 /// <param name="e"></param>
00076 void TimeTriggeredTask::RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00077 {
00078     auto task = BackgroundTaskSample::RegisterBackgroundTask(SampleBackgroundTaskEntryPoint,
00079                                                              TimeTriggeredTaskName,
00080                                                              ref new TimeTrigger(15, false),
00081                                                              nullptr);
00082     AttachProgressAndCompletedHandlers(task);
00083     UpdateUI();
00084 }
00085
00086 /// <summary>
00087 /// Unregister a TimeTriggeredTask.
00088 /// </summary>
00089 /// <param name="sender"></param>
00090 /// <param name="e"></param>
00091 void TimeTriggeredTask::UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00092 {
00093     BackgroundTaskSample::UnregisterBackgroundTasks(TimeTriggeredTaskName);
00094     UpdateUI();
00095 }
00096
00097 /// <summary>
00098 /// Handle background task progress.
00099 /// </summary>
00100 /// <param name="task">The task that is reporting progress.</param>
00101 /// <param name="args">Arguments of the progress report.</param>
00102 void TimeTriggeredTask::OnProgress(BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
00103 {
00104     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00105     {
00106         auto progress = "Progress: " + args->Progress + "%";
00107         BackgroundTaskSample::TimeTriggeredTaskProgress = progress;
00108         UpdateUI();
00109     }));
00110 }
00111
00112 /// <summary>
00113 /// Handle background task completion.
00114 /// </summary>
00115 /// <param name="task">The task that is reporting completion.</param>
00116 /// <param name="args">Arguments of the completion report.</param>
00117 void TimeTriggeredTask::OnCompleted(BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
00118 {
00119     UpdateUI();
00120 }
00121
00122 /// <summary>
00123 /// Update the scenario UI.
00124 /// </summary>
00125 void TimeTriggeredTask::UpdateUI()
00126 {
00127     auto uiDelegate = [this]()
00128     {
00129         RegisterButton->IsEnabled = !BackgroundTaskSample::TimeTriggeredTaskRegistered;
00130         UnregisterButton->IsEnabled = BackgroundTaskSample::TimeTriggeredTaskRegistered;
00131         Progress->Text = BackgroundTaskSample::TimeTriggeredTaskProgress;
00132         Status->Text = BackgroundTaskSample::GetBackgroundTaskStatus(TimeTriggeredTaskName);
00133     };
00134     auto handler = ref new Windows::UI::Core::DispatchedHandler(uiDelegate, Platform::CallbackContext::Any);
00135
00136     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, handler);
00137 }
Generated on Fri Nov 15 2024 22:18:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCoordinateMapper/cpp/Content/QuadRenderer.h Source File

  • CameraStreamCoordinateMapper
  • cpp
  • Content

QuadRenderer.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015 #include "Common\StepTimer.h"
00016 #include "ShaderStructures.h"
00017
00018 namespace CameraStreamCoordinateMapper
00019 {
00020     // This sample renderer instantiates a basic rendering pipeline.
00021     class QuadRenderer
00022     {
00023     public:
00024         QuadRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00025
00026         void CreateDeviceDependentResources();
00027         void CreateWindowSizeDependentResources();
00028         void ReleaseDeviceDependentResources();
00029
00030         void Render(ID3D11ShaderResourceView* texture, float aspectRatio);
00031
00032     private:
00033         // Cached pointer to device resources.
00034         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00035
00036         // Direct3D resources for the geometry.
00037         Microsoft::WRL::ComPtr<ID3D11InputLayout>  m_inputLayout;
00038         Microsoft::WRL::ComPtr<ID3D11Buffer>       m_vertexBuffer;
00039         Microsoft::WRL::ComPtr<ID3D11Buffer>       m_indexBuffer;
00040         Microsoft::WRL::ComPtr<ID3D11VertexShader> m_vertexShader;
00041         Microsoft::WRL::ComPtr<ID3D11PixelShader>  m_pixelShader;
00042         Microsoft::WRL::ComPtr<ID3D11Buffer>       m_constantBuffer;
00043         Microsoft::WRL::ComPtr<ID3D11SamplerState> m_samplerState;
00044
00045         // System resources for the geometry.
00046         ModelViewProjectionConstantBuffer m_constantBufferData;
00047         uint32 m_indexCount = 0u;
00048     };
00049 }
00050
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CashDrawer/cpp/pch.cpp Source File

  • CashDrawer
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HotspotAuthentication/cs/Scenario1_Initialization.xaml.cs Source File

  • HotspotAuthentication
  • cs

Scenario1_Initialization.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using HotspotAuthenticationTask;
00012 using System;
00013 using Windows.ApplicationModel.Background;
00014 using Windows.Data.Xml.Dom;
00015 using Windows.Networking.NetworkOperators;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class Scenario1_Initialization : Page
00026     {
00027         private MainPage rootPage = MainPage.Current;
00028
00029         public Scenario1_Initialization()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             ConfigStore.UseNativeWISPr = true;
00037
00038             // Configure background task handler to perform authentication as default
00039             ConfigStore.AuthenticateThroughBackgroundTask = true;
00040
00041             // Setup completion handler
00042             var isTaskRegistered = ScenarioCommon.Instance.RegisteredCompletionHandlerForBackgroundTask();
00043
00044             // Initialize button state
00045             UpdateButtonState(isTaskRegistered);
00046
00047         }
00048
00049         private async void ProvisionButton_Click(object sender, RoutedEventArgs e)
00050         {
00051             ProvisionButton.IsEnabled = false;
00052
00053             // Open the installation folder
00054             var installLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
00055
00056             // Access the provisioning file
00057             var provisioningFile = await installLocation.GetFileAsync("ProvisioningData.xml");
00058
00059             // Load with XML parser
00060             var xmlDocument = await XmlDocument.LoadFromFileAsync(provisioningFile);
00061
00062             // Get raw XML
00063             var provisioningXml = xmlDocument.GetXml();
00064
00065             // Create ProvisiongAgent Object
00066             var provisioningAgent = new ProvisioningAgent();
00067
00068             try
00069             {
00070                 // Create ProvisionFromXmlDocumentResults Object
00071                 var result = await provisioningAgent.ProvisionFromXmlDocumentAsync(provisioningXml);
00072
00073                 if (result.AllElementsProvisioned)
00074                 {
00075                     rootPage.NotifyUser("Provisioning was successful", NotifyType.StatusMessage);
00076                 }
00077                 else
00078                 {
00079                     rootPage.NotifyUser("Provisioning result: " + result.ProvisionResultsXml, NotifyType.ErrorMessage);
00080                 }
00081             }
00082             catch (System.Exception ex)
00083             {
00084                 // See https://docs.microsoft.com/en-us/uwp/api/windows.networking.networkoperators.provisioningagent.provisionfromxmldocumentasync
00085                 // for list of possible exceptions.
00086                 rootPage.NotifyUser($"Unable to provision: {ex}", NotifyType.ErrorMessage);
00087             }
00088
00089             ProvisionButton.IsEnabled = true;
00090         }
00091
00092         private void RegisterButton_Click(object sender, RoutedEventArgs e)
00093         {
00094             // Create a new background task builder.
00095             var taskBuilder = new BackgroundTaskBuilder();
00096
00097             // Create a new NetworkOperatorHotspotAuthentication trigger.
00098             var trigger = new NetworkOperatorHotspotAuthenticationTrigger();
00099
00100             // Associate the NetworkOperatorHotspotAuthentication trigger with the background task builder.
00101             taskBuilder.SetTrigger(trigger);
00102
00103             // Specify the background task to run when the trigger fires.
00104             taskBuilder.TaskEntryPoint = ScenarioCommon.BackgroundTaskEntryPoint;
00105
00106             // Name the background task.
00107             taskBuilder.Name = ScenarioCommon.BackgroundTaskName;
00108
00109             try
00110             {
00111                 // Register the background task.
00112                 var task = taskBuilder.Register();
00113
00114                 // Associate progress and completed event handlers with the new background task.
00115                 task.Completed += ScenarioCommon.Instance.OnBackgroundTaskCompleted;
00116
00117                 UpdateButtonState(true);
00118
00119                 rootPage.NotifyUser("Register was successful", NotifyType.StatusMessage);
00120             }
00121             catch (System.Exception ex)
00122             {
00123                 rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
00124             }
00125         }
00126
00127         private void UnregisterButton_Click(object sender, RoutedEventArgs e)
00128         {
00129             if (UnregisterBackgroundTask())
00130             {
00131                 UpdateButtonState(false);
00132                 rootPage.NotifyUser("Unregister was successful.", NotifyType.StatusMessage);
00133             }
00134             else
00135             {
00136                 rootPage.NotifyUser(String.Format("Background {0} task is not registered", ScenarioCommon.BackgroundTaskName), NotifyType.StatusMessage);
00137             }
00138
00139         }
00140
00141         private bool UnregisterBackgroundTask()
00142         {
00143             bool unregister = false;
00144             // Loop through all background tasks and unregister any.
00145             foreach (var cur in BackgroundTaskRegistration.AllTasks)
00146             {
00147                 if (cur.Value.Name == ScenarioCommon.BackgroundTaskName)
00148                 {
00149                     cur.Value.Unregister(true);
00150                     unregister = true;
00151                 }
00152             }
00153             return unregister;
00154
00155         }
00156
00157         /// <summary>
00158         /// Enables or disables register and unregister buttons
00159         /// </summary>
00160         /// <param name="registered">True if background task is registered, false otherwise</param>
00161         private void UpdateButtonState(bool registered)
00162         {
00163             if (registered)
00164             {
00165                 RegisterButton.IsEnabled = false;
00166                 UnregisterButton.IsEnabled = true;
00167             }
00168             else
00169             {
00170                 RegisterButton.IsEnabled = true;
00171                 UnregisterButton.IsEnabled = false;
00172             }
00173         }
00174     }
00175 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Level1.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Level1.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Level1.h"
00014 #include "Face.h"
00015
00016 using namespace DirectX;
00017
00018 Level1::Level1()
00019 {
00020     m_timeLimit = 20.0f;
00021     m_objective = L"Hit each of the targets before time runs out.\nTouch to aim. Tap in right box to fire. Drag in left box to move.";
00022 }
00023
00024 void Level1::Initialize(std::vector<std::shared_ptr<GameObject>> const& objects)
00025 {
00026     XMFLOAT3 position[] =
00027     {
00028         XMFLOAT3(-2.5f, -1.0f, -1.5f),
00029         XMFLOAT3(-1.0f,  1.0f, -3.0f),
00030         XMFLOAT3(1.5f,  0.0f, -3.0f),
00031         XMFLOAT3(-2.5f, -1.0f, -5.5f),
00032         XMFLOAT3(0.5f, -2.0f, -5.0f),
00033         XMFLOAT3(1.5f, -2.0f, -5.5f),
00034         XMFLOAT3(2.0f,  0.0f,  0.0f),
00035         XMFLOAT3(0.0f,  0.0f,  0.0f),
00036         XMFLOAT3(-2.0f,  0.0f,  0.0f)
00037     };
00038
00039     int targetCount = 0;
00040     for (auto&& object : objects)
00041     {
00042         if (auto target = dynamic_cast<Face*>(object.get()))
00043         {
00044             if (targetCount < 9)
00045             {
00046                 target->Active(true);
00047                 target->Target(true);
00048                 target->Hit(false);
00049                 target->AnimatePosition(nullptr);
00050                 target->Position(position[targetCount]);
00051                 targetCount++;
00052             }
00053             else
00054             {
00055                 object->Active(false);
00056             }
00057         }
00058         else
00059         {
00060             object->Active(false);
00061         }
00062     }
00063 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-I2C/cs/SampleConfiguration.cs Source File

  • IoT-I2C
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "I2C C# Sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Read data from I2C device", ClassType=typeof(Scenario1_ReadData)},
00025         };
00026
00027     }
00028
00029     public class Scenario
00030     {
00031         public string Title { get; set; }
00032         public Type ClassType { get; set; }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomUsbDeviceAccess/cs/SampleConfiguration.cs Source File

  • CustomUsbDeviceAccess
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using CustomUsbDeviceAccess;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         // Change the string below to reflect the name of your sample.
00022         // This is used on the main page as the title of the sample.
00023         public const string FEATURE_NAME = "Custom USB Device Access";
00024
00025         // Change the array below to reflect the name of your scenarios.
00026         // This will be used to populate the list of scenarios on the main page with
00027         // which the user will choose the specific scenario that they are interested in.
00028         // These should be in the form: "Navigating to a web page".
00029         // The code in MainPage will take care of turning this into: "1) Navigating to a web page"
00030         List<Scenario> scenarios = new List<Scenario>
00031         {
00032             new Scenario() { Title="Connect/Disconnect", ClassType=typeof(Scenario1_ConnectDisconnect)},
00033             new Scenario() { Title="Control Transfer", ClassType=typeof(Scenario2_ControlTransfer)},
00034             new Scenario() { Title="Interrupt Pipes", ClassType=typeof(Scenario3_InterruptPipes)},
00035             new Scenario() { Title="Bulk Pipes", ClassType=typeof(Scenario4_BulkPipes)},
00036             new Scenario() { Title="USB Descriptors", ClassType=typeof(Scenario5_UsbDescriptors)},
00037             new Scenario() { Title="Interface Settings", ClassType=typeof(Scenario6_InterfaceSettings)},
00038             new Scenario() { Title="Sync Device", ClassType=typeof(Scenario7_SyncDevice)}
00039         };
00040     }
00041
00042     public class Scenario
00043     {
00044         public string Title { get; set; }
00045
00046         public Type ClassType { get; set; }
00047
00048         public override string ToString()
00049         {
00050             return Title;
00051         }
00052     }
00053 }
00054
00055 namespace CustomUsbDeviceAccess
00056 {
00057     public enum DeviceType
00058     {
00059         OsrFx2,
00060         SuperMutt,
00061         All,    // Can be any device
00062         None
00063     };
00064
00065     public enum Descriptor
00066     {
00067         Device,
00068         Configuration,
00069         Interface,
00070         Endpoint,
00071         String,
00072         Custom
00073     };
00074
00075     public class OnDeviceConnectedEventArgs
00076     {
00077         private Boolean isDeviceSuccessfullyConnected;
00078         private Windows.Devices.Enumeration.DeviceInformation deviceInformation;
00079
00080         public OnDeviceConnectedEventArgs(Boolean isDeviceSuccessfullyConnected, Windows.Devices.Enumeration.DeviceInformation deviceInformation)
00081         {
00082             this.isDeviceSuccessfullyConnected = isDeviceSuccessfullyConnected;
00083             this.deviceInformation = deviceInformation;
00084         }
00085
00086         public Boolean IsDeviceSuccessfullyConnected
00087         {
00088             get
00089             {
00090                 return isDeviceSuccessfullyConnected;
00091             }
00092         }
00093
00094         public Windows.Devices.Enumeration.DeviceInformation DeviceInformation
00095         {
00096             get
00097             {
00098                 return deviceInformation;
00099             }
00100         }
00101     }
00102
00103     public class LocalSettingKeys
00104     {
00105         public const String SyncBackgroundTaskStatus = "SyncBackgroundTaskStatus";
00106         public const String SyncBackgroundTaskResult = "SyncBackgroundTaskResult";
00107     }
00108
00109     public class SyncBackgroundTaskInformation
00110     {
00111         public const String Name = "SyncBackgroundTask";
00112         public const String TaskEntryPoint = "BackgroundTask.IoSyncBackgroundTask";
00113         public const String TaskCanceled = "Canceled";
00114         public const String TaskCompleted = "Completed";
00115     }
00116
00117     public class DeviceProperties
00118     {
00119         public const String DeviceInstanceId = "System.Devices.DeviceInstanceId";
00120     }
00121
00122     public class OsrFx2
00123     {
00124         public static class VendorCommand
00125         {
00126             public const Byte GetSevenSegment = 0xD4;
00127             public const Byte GetSwitchState = 0xD6;
00128             public const Byte SetSevenSegment = 0xDB;
00129         }
00130
00131         public class Pipe
00132         {
00133             public const UInt32 InterruptInPipeIndex = 0;
00134             public const UInt32 BulkInPipeIndex = 0;
00135             public const UInt32 BulkOutPipeIndex = 0;
00136         }
00137
00138
00139         // Seven Segment Masks and their associated numeric values
00140         public static Byte[] SevenLedSegmentMask =
00141             {
00142                 0xD7, // 0
00143                 0x06, // 1
00144                 0xB3, // 2
00145                 0xA7, // 3
00146                 0x66, // 4
00147                 0xE5, // 5
00148                 0xF4, // 6
00149                 0x07, // 7
00150                 0xF7, // 8
00151                 0x67, // 9
00152             };
00153
00154         // TODO
00155         public const UInt16 DeviceVid = 0x0547;
00156         public const UInt16 DevicePid = 0x1002;
00157         //public const UInt16 DeviceVid = 0x045E;
00158         //public const UInt16 DevicePid = 0x078E;
00159     }
00160
00161     public class SuperMutt
00162     {
00163         public class VendorCommand
00164         {
00165             public const Byte GetLedBlinkPattern = 0x03;
00166             public const Byte SetLedBlinkPattern = 0x03;
00167         }
00168
00169         public class Pipe
00170         {
00171             public const UInt32 InterruptInPipeIndex = 0;
00172             public const UInt32 InterruptOutPipeIndex = 0;
00173             public const UInt32 BulkInPipeIndex = 0;
00174             public const UInt32 BulkOutPipeIndex = 0;
00175         }
00176
00177         public const UInt16 DeviceVid = 0x045E;
00178         public const UInt16 DevicePid = 0x0611;
00179         public static Guid DeviceInterfaceClass = new Guid("{875d47fc-d331-4663-b339-624001a2dc5e}");
00180     }
00181 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Compass/cpp/Scenario3_Calibration.xaml.h Source File

  • Compass
  • cpp

Scenario3_Calibration.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario3_Calibration.xaml.h
00014 // Declaration of the Scenario3_Calibration class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario3_Calibration.g.h"
00021 #include "MainPage.xaml.h"
00022 #include "CalibrationBar.xaml.h"
00023
00024 namespace SDKTemplate
00025 {
00026     /// <summary>
00027     /// An empty page that can be used on its own or navigated to within a Frame.
00028     /// </summary>
00029     [Windows::Foundation::Metadata::WebHostHidden]
00030     public ref class Scenario3_Calibration sealed
00031     {
00032     public:
00033         Scenario3_Calibration();
00034
00035     protected:
00036         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038
00039     private:
00040         SDKTemplate::MainPage^ rootPage;
00041         SDKTemplate::CalibrationBar^ calibrationBar;
00042
00043         void OnHighAccuracy(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         void OnApproximateAccuracy(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045         void OnUnreliableAccuracy(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046     };
00047 }
Generated on Fri Nov 15 2024 22:18:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_RandomAccess Member List

This is the complete list of members for Scenario5_RandomAccess, including all inherited members.
BytesPerMegaByte | Scenario5_RandomAccess | [private]
CancelActiveDownloadsAsync() | Scenario5_RandomAccess | [inline, private]
download | Scenario5_RandomAccess | [private]
FormatDownloadedRanges(IEnumerable< BackgroundTransferFileRange > ranges) | Scenario5_RandomAccess | [inline, private, static]
IsWebException(string title, Exception ex) | Scenario5_RandomAccess | [inline, private]
OnDownloadProgress(IAsyncOperationWithProgress< DownloadOperation, DownloadOperation > sender, DownloadOperation progress) | Scenario5_RandomAccess | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario5_RandomAccess | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario5_RandomAccess | [inline, protected]
OnRangesDownloaded(DownloadOperation sender, BackgroundTransferRangesDownloadedEventArgs args) | Scenario5_RandomAccess | [inline, private]
PauseDownload_Click(object sender, RoutedEventArgs e) | Scenario5_RandomAccess | [inline, private]
randomAccessStream | Scenario5_RandomAccess | [private]
readCancellationTokenSource | Scenario5_RandomAccess | [private]
readOperation | Scenario5_RandomAccess | [private]
ResumeDownload_Click(object sender, RoutedEventArgs e) | Scenario5_RandomAccess | [inline, private]
rootPage | Scenario5_RandomAccess | [private]
Scenario5_RandomAccess() | Scenario5_RandomAccess | [inline]
SeekDownload_Click(object sender, RoutedEventArgs e) | Scenario5_RandomAccess | [inline, private]
StartDownload_Click(object sender, RoutedEventArgs e) | Scenario5_RandomAccess | [inline, private]
StartDownloadAndReadContentsAsync() | Scenario5_RandomAccess | [inline, private]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DSvgImage/cpp/DirectXPage.xaml.cpp Source File

  • D2DSvgImage
  • cpp

DirectXPage.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DirectXPage.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::System::Threading;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Input;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Controls::Primitives;
00028 using namespace Windows::UI::Xaml::Data;
00029 using namespace Windows::UI::Xaml::Input;
00030 using namespace Windows::UI::Xaml::Media;
00031 using namespace Windows::UI::Xaml::Navigation;
00032
00033 DirectXPage::DirectXPage() :
00034     m_isWindowVisible(true)
00035 {
00036     InitializeComponent();
00037
00038     // Register event handlers for page lifecycle.
00039     CoreWindow^ window = Window::Current->CoreWindow;
00040
00041     window->VisibilityChanged +=
00042         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXPage::OnVisibilityChanged);
00043
00044     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00045
00046     currentDisplayInformation->DpiChanged +=
00047         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnDpiChanged);
00048
00049     currentDisplayInformation->OrientationChanged +=
00050         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnOrientationChanged);
00051
00052     DisplayInformation::DisplayContentsInvalidated +=
00053         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnDisplayContentsInvalidated);
00054
00055     swapChainPanel->CompositionScaleChanged +=
00056         ref new TypedEventHandler<SwapChainPanel^, Object^>(this, &DirectXPage::OnCompositionScaleChanged);
00057
00058     swapChainPanel->SizeChanged +=
00059         ref new SizeChangedEventHandler(this, &DirectXPage::OnSwapChainPanelSizeChanged);
00060
00061     // At this point we have access to the device and
00062     // can create the device-dependent resources.
00063     m_deviceResources = std::make_shared<DX::DeviceResources>();
00064     m_deviceResources->SetSwapChainPanel(swapChainPanel);
00065
00066     m_renderer = std::unique_ptr<D2DSvgImageRenderer>(new D2DSvgImageRenderer(m_deviceResources));
00067 }
00068
00069 DirectXPage::~DirectXPage()
00070 {
00071 }
00072
00073 // UI element event handlers.
00074
00075 void DirectXPage::YellowButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00076 {
00077     m_renderer->RecolorSvg(D2D1::ColorF(D2D1::ColorF::Yellow));
00078     m_renderer->Draw();
00079 }
00080
00081 void DirectXPage::GreenButton_Click(_In_ Object^ sender, _In_ RoutedEventArgs^ e)
00082 {
00083     m_renderer->RecolorSvg(D2D1::ColorF(D2D1::ColorF::Green));
00084     m_renderer->Draw();
00085 }
00086
00087 void DirectXPage::PurpleButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00088 {
00089     m_renderer->RecolorSvg(D2D1::ColorF(D2D1::ColorF::Purple));
00090     m_renderer->Draw();
00091 }
00092
00093 void DirectXPage::TongueButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00094 {
00095     m_renderer->ToggleTongue();
00096     m_renderer->Draw();
00097 }
00098
00099 void DirectXPage::Slider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00100 {
00101     if (m_renderer)
00102     {
00103         m_renderer->SetScaleValue((float)e->NewValue);
00104         m_renderer->Draw();
00105     }
00106 }
00107 // Saves the current state of the app for suspend and terminate events.
00108 void DirectXPage::SaveInternalState(_In_ IPropertySet^ state)
00109 {
00110     m_deviceResources->Trim();
00111 }
00112
00113 // Loads the current state of the app for resume events.
00114 void DirectXPage::LoadInternalState(_In_ IPropertySet^ state)
00115 {
00116 }
00117
00118 // Window event handlers.
00119
00120 void DirectXPage::OnVisibilityChanged(_In_ CoreWindow^ sender, _In_ VisibilityChangedEventArgs^ args)
00121 {
00122     m_isWindowVisible = args->Visible;
00123     if (m_isWindowVisible)
00124     {
00125         m_renderer->Draw();
00126     }
00127 }
00128
00129 // DisplayInformation event handlers.
00130
00131 void DirectXPage::OnDpiChanged(_In_ DisplayInformation^ sender, _In_ Object^ args)
00132 {
00133     m_deviceResources->SetDpi(sender->LogicalDpi);
00134     m_renderer->CreateWindowSizeDependentResources();
00135     m_renderer->Draw();
00136 }
00137
00138 void DirectXPage::OnOrientationChanged(_In_ DisplayInformation^ sender, _In_ Object^ args)
00139 {
00140     m_deviceResources->SetCurrentOrientation(sender->CurrentOrientation);
00141     m_renderer->CreateWindowSizeDependentResources();
00142     m_renderer->Draw();
00143 }
00144
00145 void DirectXPage::OnDisplayContentsInvalidated(_In_ DisplayInformation^ sender, _In_ Object^ args)
00146 {
00147     m_deviceResources->ValidateDevice();
00148     m_renderer->Draw();
00149 }
00150
00151 // Other event handlers.
00152
00153 void DirectXPage::OnCompositionScaleChanged(_In_ SwapChainPanel^ sender, _In_ Object^ args)
00154 {
00155     m_deviceResources->SetCompositionScale(sender->CompositionScaleX, sender->CompositionScaleY);
00156     m_renderer->CreateWindowSizeDependentResources();
00157     m_renderer->Draw();
00158 }
00159
00160 void DirectXPage::OnSwapChainPanelSizeChanged(_In_ Object^ sender, _In_ SizeChangedEventArgs^ e)
00161 {
00162     m_deviceResources->SetLogicalSize(e->NewSize);
00163     m_renderer->CreateWindowSizeDependentResources();
00164     m_renderer->Draw();
00165 }
00166
00167 // INotifyPropertyChanged.
00168 void DirectXPage::OnPropertyChanged(String^ propertyName)
00169 {
00170     PropertyChanged(this, ref new PropertyChangedEventArgs(propertyName));
00171 }
Generated on Fri Nov 15 2024 22:19:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PasswordVault/cppwinrt/SampleConfiguration.cpp Source File

  • PasswordVault
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"PasswordVault C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Save credentials", xaml_typename<SDKTemplate::Scenario1_Save>() },
00029     Scenario{ L"Manage credentials", xaml_typename<SDKTemplate::Scenario2_Manage>() },
00030 });
Generated on Fri Nov 15 2024 22:17:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/Content/SpinningCubeRenderer.h Source File

  • HolographicMixedRealityCapture
  • cpp
  • Content

SpinningCubeRenderer.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "..\Common\DeviceResources.h"
00004 #include "..\Common\StepTimer.h"
00005 #include "ShaderStructures.h"
00006
00007 namespace HolographicMRCSample
00008 {
00009     // This sample renderer instantiates a basic rendering pipeline.
00010     class SpinningCubeRenderer
00011     {
00012     public:
00013         SpinningCubeRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00014         void CreateDeviceDependentResources();
00015         void ReleaseDeviceDependentResources();
00016         void Update(const DX::StepTimer& timer);
00017         void Render();
00018
00019         // Repositions the sample hologram.
00020         void PositionHologram(Windows::UI::Input::Spatial::SpatialPointerPose^ pointerPose);
00021
00022         // Property accessors.
00023         void SetPosition(Windows::Foundation::Numerics::float3 pos) { m_position = pos;  }
00024         Windows::Foundation::Numerics::float3 GetPosition()         { return m_position; }
00025
00026     private:
00027         // Cached pointer to device resources.
00028         std::shared_ptr<DX::DeviceResources>            m_deviceResources;
00029
00030         // Direct3D resources for cube geometry.
00031         Microsoft::WRL::ComPtr<ID3D11InputLayout>       m_inputLayout;
00032         Microsoft::WRL::ComPtr<ID3D11Buffer>            m_vertexBuffer;
00033         Microsoft::WRL::ComPtr<ID3D11Buffer>            m_indexBuffer;
00034         Microsoft::WRL::ComPtr<ID3D11VertexShader>      m_vertexShader;
00035         Microsoft::WRL::ComPtr<ID3D11GeometryShader>    m_geometryShader;
00036         Microsoft::WRL::ComPtr<ID3D11PixelShader>       m_pixelShader;
00037         Microsoft::WRL::ComPtr<ID3D11Buffer>            m_modelConstantBuffer;
00038
00039         // System resources for cube geometry.
00040         ModelConstantBuffer                             m_modelConstantBufferData;
00041         uint32                                          m_indexCount = 0;
00042
00043         // Variables used with the rendering loop.
00044         bool                                            m_loadingComplete = false;
00045         float                                           m_degreesPerSecond = 45.f;
00046         Windows::Foundation::Numerics::float3           m_position = { 0.f, 0.f, -2.f };
00047
00048         // If the current D3D Device supports VPRT, we can avoid using a geometry
00049         // shader just to set the render target array index.
00050         bool                                            m_usingVprtShaders = false;
00051     };
00052 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialSound/cpp/XAudio2Helpers.h Source File

  • SpatialSound
  • cpp

XAudio2Helpers.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014
00015 // Sets up XAudio2 for HRTF processing
00016 static HRESULT SetupXAudio2(_In_ const WAVEFORMATEX* format, _In_ IXAPO* xApo, _Outptr_ IXAudio2** xAudio2, _Outptr_ IXAudio2SourceVoice** sourceVoice)
00017 {
00018     // Initialize XAudio2 for HRTF processing with "XAUDIO2_1024_QUANTUM" flag which specifies processing frame size of 1024 samples.
00019     ComPtr<IXAudio2> xAudio2Instance;
00020     auto hr = XAudio2Create(&xAudio2Instance, XAUDIO2_1024_QUANTUM);
00021
00022     // HRTF APO expects mono audio data at 48kHz and produces stereo output at 48kHz
00023     // so we create a stereo mastering voice with specific rendering sample rate of 48kHz.
00024     // Mastering voice will be automatically destroyed when XAudio2 instance is destroyed.
00025     IXAudio2MasteringVoice* masteringVoice = nullptr;
00026     if (SUCCEEDED(hr))
00027     {
00028         hr = xAudio2Instance->CreateMasteringVoice(&masteringVoice, 2, 48000);
00029     }
00030
00031     // Create a source voice to accept audio data in the specified format.
00032     IXAudio2SourceVoice* sourceVoiceInstance = nullptr;
00033     if (SUCCEEDED(hr))
00034     {
00035         hr = xAudio2Instance->CreateSourceVoice(&sourceVoiceInstance, format);
00036     }
00037
00038     // Create a submix voice that will host the xAPO.
00039     // This submix voice will be detroyed when XAudio2 instance is destroyed.
00040     IXAudio2SubmixVoice* submixVoice = nullptr;
00041
00042     if (SUCCEEDED(hr))
00043     {
00044         XAUDIO2_EFFECT_DESCRIPTOR fxDesc{};
00045         fxDesc.InitialState = TRUE;
00046         fxDesc.OutputChannels = 2;          // Stereo output
00047         fxDesc.pEffect = xApo;              // HRTF xAPO set as the effect.
00048
00049         XAUDIO2_EFFECT_CHAIN fxChain{};
00050         fxChain.EffectCount = 1;
00051         fxChain.pEffectDescriptors = &fxDesc;
00052
00053         XAUDIO2_VOICE_SENDS sends = {};
00054         XAUDIO2_SEND_DESCRIPTOR sendDesc = {};
00055         sendDesc.pOutputVoice = masteringVoice;
00056         sends.SendCount = 1;
00057         sends.pSends = &sendDesc;
00058
00059         // HRTF APO expects mono 48kHz input, so we configure the submix voice for that format.
00060         hr = xAudio2Instance->CreateSubmixVoice(&submixVoice, 1, 48000, 0, 0, &sends, &fxChain);
00061     }
00062
00063     // Route the source voice to the submix voice.
00064     // The complete graph pipeline looks like this -
00065     // Source Voice -> Submix Voice (HRTF xAPO) -> Mastering Voice
00066     if (SUCCEEDED(hr))
00067     {
00068         XAUDIO2_VOICE_SENDS sends = {};
00069         XAUDIO2_SEND_DESCRIPTOR sendDesc = {};
00070         sendDesc.pOutputVoice = submixVoice;
00071         sends.SendCount = 1;
00072         sends.pSends = &sendDesc;
00073         hr = sourceVoiceInstance->SetOutputVoices(&sends);
00074     }
00075
00076     // Return the XAudio2 instance and the source voice.
00077     if (SUCCEEDED(hr))
00078     {
00079         *sourceVoice = sourceVoiceInstance;
00080         *xAudio2 = xAudio2Instance.Detach();
00081     }
00082
00083     return hr;
00084 }
00085
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFont/SampleConfiguration.h Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFont

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "DirectWrite TextLayout Downloadable Fonts Integration";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RandomNumberGeneratorTask Member List

This is the complete list of members for RandomNumberGeneratorTask, including all inherited members.
connection | RandomNumberGeneratorTask | [private]
OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) | RandomNumberGeneratorTask | [inline, private]
OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) | RandomNumberGeneratorTask | [inline, private]
randomNumberGenerator | RandomNumberGeneratorTask | [private]
Run(IBackgroundTaskInstance taskInstance) | RandomNumberGeneratorTask | [inline]
serviceDeferral | RandomNumberGeneratorTask | [private]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStarterKit/cpp/App.xaml.h Source File

  • CameraStarterKit
  • cpp

App.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "App.g.h"
00015
00016 namespace CameraStarterKit
00017 {
00018     /// <summary>
00019     /// Provides application-specific behavior to supplement the default Application class.
00020     /// </summary>
00021     ref class App sealed
00022     {
00023     protected:
00024         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override;
00025
00026     internal:
00027         App();
00028
00029     private:
00030         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
00031         void OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e);
00032     };
00033 }
Generated on Fri Nov 15 2024 22:16:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Appointments/cs/Scenario3_Replace.xaml.cs Source File

  • Appointments
  • cs

Scenario3_Replace.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario3_Replace : Page
00020     {
00021         private MainPage rootPage = MainPage.Current;
00022
00023         public Scenario3_Replace()
00024         {
00025             this.InitializeComponent();
00026         }
00027
00028         /// <summary>
00029         /// Replace an appointment on the user's calendar using the default appointments provider app.
00030         /// </summary>
00031         /// <param name="sender"></param>
00032         /// <param name="e"></param>
00033         private async void Replace_Click(object sender, RoutedEventArgs e)
00034         {
00035             // The appointment id argument for ReplaceAppointmentAsync is typically retrieved from AddAppointmentAsync and stored in app data.
00036             String appointmentIdOfAppointmentToReplace = AppointmentIdTextBox.Text;
00037
00038             if (String.IsNullOrEmpty(appointmentIdOfAppointmentToReplace))
00039             {
00040                 rootPage.NotifyUser("The appointment id cannot be empty", NotifyType.ErrorMessage);
00041             }
00042             else
00043             {
00044                 // The Appointment argument for ReplaceAppointmentAsync should contain all of the Appointment's properties including those that may have changed.
00045                 var appointment = new Windows.ApplicationModel.Appointments.Appointment();
00046
00047                 // Get the selection rect of the button pressed to replace this appointment
00048                 var rect = MainPage.GetElementRect(sender as FrameworkElement);
00049
00050                 // ReplaceAppointmentAsync returns an updated appointment id when the appointment was successfully replaced.
00051                 // The updated id may or may not be the same as the original one retrieved from AddAppointmentAsync.
00052                 // An optional instance start time can be provided to indicate that a specific instance on that date should be replaced
00053                 // in the case of a recurring appointment.
00054                 // If the appointment id returned is an empty string, that indicates that the appointment was not replaced.
00055                 String updatedAppointmentId;
00056                 if (InstanceStartDateCheckBox.IsChecked.Value)
00057                 {
00058                     // Replace a specific instance starting on the date provided.
00059                     var instanceStartDate = InstanceStartDateDatePicker.Date;
00060                     updatedAppointmentId = await Windows.ApplicationModel.Appointments.AppointmentManager.ShowReplaceAppointmentAsync(appointmentIdOfAppointmentToReplace, appointment, rect, Windows.UI.Popups.Placement.Default, instanceStartDate);
00061                 }
00062                 else
00063                 {
00064                     // Replace an appointment that occurs only once or in the case of a recurring appointment, replace the entire series.
00065                     updatedAppointmentId = await Windows.ApplicationModel.Appointments.AppointmentManager.ShowReplaceAppointmentAsync(appointmentIdOfAppointmentToReplace, appointment, rect, Windows.UI.Popups.Placement.Default);
00066                 }
00067
00068                 if (updatedAppointmentId != String.Empty)
00069                 {
00070                     rootPage.NotifyUser("Updated Appointment Id: " + updatedAppointmentId, NotifyType.StatusMessage);
00071                 }
00072                 else
00073                 {
00074                     rootPage.NotifyUser("Appointment not replaced.", NotifyType.ErrorMessage);
00075                 }
00076             }
00077         }
00078     }
00079 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileSearch/cpp/pch.cpp Source File

  • FileSearch
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomUsbDeviceAccess/cs/Scenario5_UsbDescriptors.xaml.cs Source File

  • CustomUsbDeviceAccess
  • cs

Scenario5_UsbDescriptors.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Collections.ObjectModel;
00015 using System.Globalization;
00016 using Windows.Devices.Usb;
00017 using Windows.Storage.Streams;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021 using SDKTemplate;
00022
00023 namespace CustomUsbDeviceAccess
00024 {
00025     /// <summary>
00026     /// DescriptorTypeEntry is used so that the UI can bind to the list of these entries and display them.
00027     /// </summary>
00028     public sealed class DescriptorTypeEntry
00029     {
00030         private String entryName;
00031         private Descriptor descriptorType;
00032
00033         public String EntryName
00034         {
00035             get
00036             {
00037                 return entryName;
00038             }
00039         }
00040
00041         public Descriptor DescriptorType
00042         {
00043             get
00044             {
00045                 return descriptorType;
00046             }
00047         }
00048
00049         public DescriptorTypeEntry(String name, Descriptor type)
00050         {
00051             entryName = name;
00052             descriptorType = type;
00053         }
00054     };
00055
00056     /// <summary>
00057     /// This scenario demonstrates how get various descriptors from UsbDevice.
00058     ///
00059     /// This scenario can work for any device as long as it is "added" into the sample. For more information on how to add a
00060     /// device to make it compatible with this scenario, please see Scenario1_DeviceConnect.
00061     /// </summary>
00062     public sealed partial class Scenario5_UsbDescriptors : Page
00063     {
00064         private ObservableCollection<DescriptorTypeEntry> listOfDescriptorTypes;
00065
00066         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00067         // as NotifyUser()
00068         private MainPage rootPage = MainPage.Current;
00069
00070         /// <summary>
00071         /// Initializes the list of descriptors that can be displayed in the UI
00072         /// </summary>
00073         public Scenario5_UsbDescriptors()
00074         {
00075             this.InitializeComponent();
00076
00077             listOfDescriptorTypes = new ObservableCollection<DescriptorTypeEntry>();
00078             listOfDescriptorTypes.Add(new DescriptorTypeEntry("Device Descriptor", Descriptor.Device));
00079             listOfDescriptorTypes.Add(new DescriptorTypeEntry("Configuration Descriptor", Descriptor.Configuration));
00080             listOfDescriptorTypes.Add(new DescriptorTypeEntry("All Interface Descriptors", Descriptor.Interface));
00081             listOfDescriptorTypes.Add(new DescriptorTypeEntry("All Endpoint Descriptors", Descriptor.Endpoint));
00082             listOfDescriptorTypes.Add(new DescriptorTypeEntry("All Custom Descriptors", Descriptor.Custom));
00083
00084             // The Product string is not a string descriptors, they are just strings
00085             // It is marked as String Descriptor because string descriptors are not available in this API explicitly like descriptors are; however, you may use control
00086             // transfers to obtain them. The recommended approach, at least to get the Product string, is to use the Windows.Devices.Enumeration API.
00087             //
00088             // To get the Manufacturer, the Windows.Devices.Enumeration.Pnp API must be used. The usage of PnpObject is similar to that of the Enumeration API. When
00089             // creating the PnpObject with one of it's static methods, add "System.Devices.Manufacturer" to the list of properties to include. Note that the PnpObjectType
00090             // must be of type DeviceContainer, otherwise the manufacturer name cannot be obtained.
00091             // Once the PnpObject for the device has been obtained, use PnpObject.Properties dictionary where the key is "System.Devices.Manufacturer" and the value is
00092             // the manufacturer name.
00093             listOfDescriptorTypes.Add(new DescriptorTypeEntry("Product String", Descriptor.String));
00094         }
00095
00096         /// <summary>
00097         /// Invoked when this page is about to be displayed in a Frame.
00098         ///
00099         /// We will enable/disable parts of the UI if the device doesn't support it.
00100         /// </summary>
00101         /// <param name="eventArgs">Event data that describes how this page was reached.  The Parameter
00102         /// property is typically used to configure the page.</param>
00103         protected override void OnNavigatedTo(NavigationEventArgs eventArgs)
00104         {
00105             // We will disable the scenario that is not supported by the device.
00106             // If no devices are connected, none of the scenarios will be shown and an error will be displayed
00107             Dictionary<DeviceType, UIElement> deviceScenarios = new Dictionary<DeviceType, UIElement>();
00108             deviceScenarios.Add(DeviceType.All, GenericScenario);
00109
00110             Utilities.SetUpDeviceScenarios(deviceScenarios, DeviceScenarioContainer);
00111
00112             // Display list of descriptors that can be printed
00113             if ((EventHandlerForDevice.Current.IsDeviceConnected) &&
00114                (Utilities.GetDeviceType(EventHandlerForDevice.Current.Device) != DeviceType.None))
00115             {
00116                 ListOfDescriptorTypesSource.Source = listOfDescriptorTypes;
00117             }
00118         }
00119
00120         /// <summary>
00121         /// When an entry is selected from the list of available descriptors, we will print out the contents of the descriptor.
00122         /// </summary>
00123         /// <param name="sender"></param>
00124         /// <param name="eventArgs"></param>
00125         private void Descriptor_SelectChanged(Object sender, RoutedEventArgs eventArgs)
00126         {
00127             if (EventHandlerForDevice.Current.IsDeviceConnected)
00128             {
00129                 var listOfDescriptorTypes = (ListBox)sender;
00130                 var selection = (DescriptorTypeEntry)listOfDescriptorTypes.SelectedValue;
00131                 var descriptorType = selection.DescriptorType;
00132
00133                 PrintDescriptor(descriptorType);
00134             }
00135             else
00136             {
00137                 Utilities.NotifyDeviceNotConnected();
00138             }
00139         }
00140
00141         /// <summary>
00142         /// Obtains the stringified form of the chosen descriptor and prints it.
00143         /// </summary>
00144         /// <param name="descriptorType"></param>
00145         private void PrintDescriptor(Descriptor descriptorType)
00146         {
00147             if (EventHandlerForDevice.Current.IsDeviceConnected)
00148             {
00149                 String descriptor = null;
00150
00151                 switch (descriptorType)
00152                 {
00153                     case Descriptor.Device:
00154                         descriptor = GetDeviceDescriptorAsString();
00155                         break;
00156                     case Descriptor.Configuration:
00157                         descriptor = GetConfigurationDescriptorAsString();
00158                         break;
00159                     case Descriptor.Interface:
00160                         descriptor = GetInterfaceDescriptorsAsString();
00161                         break;
00162                     case Descriptor.Endpoint:
00163                         descriptor = GetEndpointDescriptorsAsString();
00164                         break;
00165                     case Descriptor.String:
00166                         descriptor = GetProductName();
00167                         break;
00168                     case Descriptor.Custom:
00169                         descriptor = GetCustomDescriptorsAsString();
00170                         break;
00171                 }
00172
00173                 if (descriptor != null)
00174                 {
00175                     DescriptorOutput.Text = descriptor;
00176                 }
00177             }
00178         }
00179
00180         private String GetDeviceDescriptorAsString()
00181         {
00182             String content = null;
00183
00184             if (EventHandlerForDevice.Current.IsDeviceConnected)
00185             {
00186                 var deviceDescriptor = EventHandlerForDevice.Current.Device.DeviceDescriptor;
00187
00188                 content = "Device Descriptor\n"
00189                     + "\nUsb Spec Number : 0x" + deviceDescriptor.BcdUsb.ToString("X4", NumberFormatInfo.InvariantInfo)
00190                     + "\nMax Packet Size (Endpoint 0) : " + deviceDescriptor.MaxPacketSize0.ToString("D", NumberFormatInfo.InvariantInfo)
00191                     + "\nVendor ID : 0x" + deviceDescriptor.VendorId.ToString("X4", NumberFormatInfo.InvariantInfo)
00192                     + "\nProduct ID : 0x" + deviceDescriptor.ProductId.ToString("X4", NumberFormatInfo.InvariantInfo)
00193                     + "\nDevice Revision : 0x" + deviceDescriptor.BcdDeviceRevision.ToString("X4", NumberFormatInfo.InvariantInfo)
00194                     + "\nNumber of Configurations : " + deviceDescriptor.NumberOfConfigurations.ToString("D", NumberFormatInfo.InvariantInfo);
00195             }
00196
00197             return content;
00198         }
00199
00200         private String GetConfigurationDescriptorAsString()
00201         {
00202             String content = null;
00203
00204             if (EventHandlerForDevice.Current.IsDeviceConnected)
00205             {
00206                 var usbConfiguration = EventHandlerForDevice.Current.Device.Configuration;
00207                 var configurationDescriptor = usbConfiguration.ConfigurationDescriptor;
00208
00209                 content = "Configuration Descriptor\n"
00210                     + "\nNumber of Interfaces : " + usbConfiguration.UsbInterfaces.Count.ToString("D", NumberFormatInfo.InvariantInfo)
00211                     + "\nConfiguration Value : 0x" + configurationDescriptor.ConfigurationValue.ToString("X2", NumberFormatInfo.InvariantInfo)
00212                     + "\nSelf Powered : " + configurationDescriptor.SelfPowered.ToString()
00213                     + "\nRemote Wakeup : " + configurationDescriptor.RemoteWakeup.ToString()
00214                     + "\nMax Power (milliAmps) : " + configurationDescriptor.MaxPowerMilliamps.ToString("D", NumberFormatInfo.InvariantInfo);
00215             }
00216
00217             return content;
00218         }
00219
00220         /// <summary>
00221         /// Will convert all the interfaces to a human readable format
00222         /// </summary>
00223         private String GetInterfaceDescriptorsAsString()
00224         {
00225             String content = null;
00226
00227             if (EventHandlerForDevice.Current.IsDeviceConnected)
00228             {
00229                 var interfaces = EventHandlerForDevice.Current.Device.Configuration.UsbInterfaces;
00230
00231                 content = "Interface Descriptors";
00232
00233                 foreach (UsbInterface usbInterface in interfaces)
00234                 {
00235                     // Will use class/subclass/protocol values from the first interface setting (usually the selected one)
00236                     UsbInterfaceDescriptor usbInterfaceDescriptor = usbInterface.InterfaceSettings[0].InterfaceDescriptor;
00237
00238                     content += "\n\nInterface Number : 0x" + usbInterface.InterfaceNumber.ToString("X2", NumberFormatInfo.InvariantInfo)
00239                         + "\nClass Code : 0x" + usbInterfaceDescriptor.ClassCode.ToString("X2", NumberFormatInfo.InvariantInfo)
00240                         + "\nSubclass Code : 0x" + usbInterfaceDescriptor.SubclassCode.ToString("X2", NumberFormatInfo.InvariantInfo)
00241                         + "\nProtocol Code: 0x" + usbInterfaceDescriptor.ProtocolCode.ToString("X2", NumberFormatInfo.InvariantInfo)
00242                         + "\nNumber of Interface Settings : " + usbInterface.InterfaceSettings.Count.ToString("D", NumberFormatInfo.InvariantInfo)
00243                         + "\nNumber of open Bulk In Endpoints : " + usbInterface.BulkInPipes.Count.ToString("D", NumberFormatInfo.InvariantInfo)
00244                         + "\nNumber of open Bulk Out Endpoints : " + usbInterface.BulkOutPipes.Count.ToString("D", NumberFormatInfo.InvariantInfo)
00245                         + "\nNumber of open Interrupt In Endpoints : " + usbInterface.InterruptInPipes.Count.ToString("D", NumberFormatInfo.InvariantInfo)
00246                         + "\nNumber of open Interrupt Out Endpoints : " + usbInterface.InterruptOutPipes.Count.ToString("D", NumberFormatInfo.InvariantInfo);
00247                 }
00248
00249             }
00250
00251             return content;
00252         }
00253
00254         /// <summary>
00255         /// We will print all the endpoint descriptors of the default interface
00256         /// </summary>
00257         private String GetEndpointDescriptorsAsString()
00258         {
00259             String content = null;
00260
00261             if (EventHandlerForDevice.Current.IsDeviceConnected)
00262             {
00263                 var usbInterface = EventHandlerForDevice.Current.Device.DefaultInterface;
00264                 var bulkInPipes = usbInterface.BulkInPipes;
00265                 var bulkOutPipes = usbInterface.BulkOutPipes;
00266                 var interruptInPipes = usbInterface.InterruptInPipes;
00267                 var interruptOutPipes = usbInterface.InterruptOutPipes;
00268
00269                 content = "Endpoint Descriptors for open pipes";
00270
00271                 // Print Bulk In Endpoint descriptors
00272                 foreach (UsbBulkInPipe bulkInPipe in bulkInPipes)
00273                 {
00274                     var endpointDescriptor = bulkInPipe.EndpointDescriptor;
00275
00276                     content += "\n\nBulk In Endpoint Descriptor"
00277                         + "\nEndpoint Number : 0x" + endpointDescriptor.EndpointNumber.ToString("X2", NumberFormatInfo.InvariantInfo)
00278                         + "\nMax Packet Size : " + endpointDescriptor.MaxPacketSize.ToString("D", NumberFormatInfo.InvariantInfo);
00279                 }
00280
00281                 // Print Bulk Out Endpoint descriptors
00282                 foreach (UsbBulkOutPipe bulkOutPipe in bulkOutPipes)
00283                 {
00284                     var endpointDescriptor = bulkOutPipe.EndpointDescriptor;
00285
00286                     content += "\n\nBulk Out Endpoint Descriptor"
00287                         + "\nEndpoint Number : 0x" + endpointDescriptor.EndpointNumber.ToString("X2", NumberFormatInfo.InvariantInfo)
00288                         + "\nMax Packet Size : " + endpointDescriptor.MaxPacketSize.ToString("D", NumberFormatInfo.InvariantInfo);
00289                 }
00290
00291                 // Print Interrupt In Endpoint descriptors
00292                 foreach (UsbInterruptInPipe interruptInPipe in interruptInPipes)
00293                 {
00294                     var endpointDescriptor = interruptInPipe.EndpointDescriptor;
00295
00296                     content += "\n\nInterrupt In Endpoint Descriptor"
00297                         + "\nEndpoint Number : 0x" + endpointDescriptor.EndpointNumber.ToString("X2", NumberFormatInfo.InvariantInfo)
00298                         + "\nMax Packet Size : " + endpointDescriptor.MaxPacketSize.ToString("D", NumberFormatInfo.InvariantInfo)
00299                         + "\nInterval(milliseconds) : " + endpointDescriptor.Interval.Milliseconds.ToString("D", NumberFormatInfo.InvariantInfo);
00300                 }
00301
00302                 // Print Interrupt Out Endpoint descriptors
00303                 foreach (UsbInterruptOutPipe interruptOutPipe in interruptOutPipes)
00304                 {
00305                     var endpointDescriptor = interruptOutPipe.EndpointDescriptor;
00306
00307                     content += "\n\nInterrupt Out Endpoint Descriptor"
00308                         + "\nEndpoint Number : 0x" + endpointDescriptor.EndpointNumber.ToString("X2", NumberFormatInfo.InvariantInfo)
00309                         + "\nMax Packet Size : " + endpointDescriptor.MaxPacketSize.ToString("D", NumberFormatInfo.InvariantInfo)
00310                         + "\nInterval(milliseconds) : " + endpointDescriptor.Interval.Milliseconds.ToString("D", NumberFormatInfo.InvariantInfo);
00311                 }
00312             }
00313
00314             return content;
00315         }
00316
00317         /// <summary>
00318         /// There are no custom descriptors for the SuperMutt and OSRFX2 devices, however, this method will show you how to
00319         /// navigate through raw descriptors. The raw descriptors can be found in UsbConfiguration and
00320         /// UsbInterface, and UsbInterfaceSetting. All possible descriptors that you would find in the full Configuration Descriptor
00321         /// are found under UsbConfiguration.
00322         /// All raw descriptors under UsbInterface are constrained only to those that are found under the InterfaceDescriptor
00323         /// that is defined in the Usb spec.
00324         ///
00325         /// Usb descriptor header (first 2 bytes):
00326         /// bLength             Size of descriptor in bytes
00327         /// bDescriptorType     The type of descriptor (configuration, interface, endpoint)
00328         /// </summary>
00329         private String GetCustomDescriptorsAsString()
00330         {
00331             String content = null;
00332
00333             if (EventHandlerForDevice.Current.IsDeviceConnected)
00334             {
00335                 // Descriptor information will be appended to this string and then printed to UI
00336                 content = "Raw Descriptors";
00337
00338                 var configuration = EventHandlerForDevice.Current.Device.Configuration;
00339                 var allRawDescriptors = configuration.Descriptors;
00340
00341                 // Print first 2 bytes of all descriptors within the configuration descriptor
00342                 // because the first 2 bytes are always length and descriptor type
00343                 // the UsbDescriptor's DescriptorType and Length properties, but we will not use these properties
00344                 // in order to demonstrate ReadDescriptorBuffer() and how to parse it.
00345                 foreach (UsbDescriptor descriptor in allRawDescriptors)
00346                 {
00347                     var descriptorBuffer = new Windows.Storage.Streams.Buffer(descriptor.Length);
00348                     descriptor.ReadDescriptorBuffer(descriptorBuffer);
00349
00350                     DataReader reader = DataReader.FromBuffer(descriptorBuffer);
00351
00352                     // USB data is Little Endian according to the USB spec.
00353                     reader.ByteOrder = ByteOrder.LittleEndian;
00354
00355                     // ReadByte has a side effect where it consumes the current byte, so the next ReadByte will read the next character.
00356                     // Putting multiple ReadByte() on the same line (same variable assignment) may cause the bytes to be read out of order.
00357                     var length = reader.ReadByte().ToString("D", NumberFormatInfo.InvariantInfo);
00358                     var type = "0x" + reader.ReadByte().ToString("X2", NumberFormatInfo.InvariantInfo);
00359
00360                     content += "\n\nDescriptor"
00361                         + "\nLength : " + length
00362                         + "\nDescriptorType : " + type;
00363                 }
00364             }
00365
00366             return content;
00367         }
00368
00369         /// <summary>
00370         /// It is recommended to obtain the product string by using DeviceInformation.Name.
00371         /// </summary>
00372         private String GetProductName()
00373         {
00374             String content = null;
00375
00376             if (EventHandlerForDevice.Current.IsDeviceConnected)
00377             {
00378                 content = "Product name: " + EventHandlerForDevice.Current.DeviceInformation.Name;
00379             }
00380
00381             return content;
00382         }
00383     }
00384 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cppwinrt/pch.h Source File

  • BasicHologram
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <array>
00004 #include <d2d1_2.h>
00005 #include <d3d11_4.h>
00006 #include <DirectXColors.h>
00007 #include <dwrite_2.h>
00008 #include <future>
00009 #include <map>
00010 #include <mutex>
00011 #include <vector>
00012 #include <wincodec.h>
00013 #include <WindowsNumerics.h>
00014
00015 #include <Windows.Graphics.Directx.Direct3D11.Interop.h>
00016 #include <wrl\client.h>
00017
00018 #include <winrt\base.h>
00019 #include <winrt\Windows.ApplicationModel.Activation.h>
00020 #include <winrt\Windows.ApplicationModel.Core.h>
00021 #include <winrt\Windows.Foundation.h>
00022 #include <winrt\Windows.Foundation.Collections.h>
00023 #include <winrt\Windows.Foundation.Metadata.h>
00024 #include <winrt\Windows.Gaming.Input.h>
00025 #include <winrt\Windows.Graphics.Display.h>
00026 #include <winrt\Windows.Graphics.Holographic.h>
00027 #include <winrt\Windows.Perception.People.h>
00028 #include <winrt\Windows.Perception.Spatial.h>
00029 #include <winrt\Windows.Storage.h>
00030 #include <winrt\Windows.Storage.Streams.h>
00031 #include <winrt\Windows.UI.Core.h>
00032 #include <winrt\Windows.UI.Input.Spatial.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Face.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Face.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Face:
00015 // This class is a specialization of GameObject that represents a parallelogram primitive.
00016 // The face is defined by three points. It is positioned at 'origin'. The four corners
00017 // of the face are defined at 'origin', 'p1', 'p2' and 'p1' + ('p2' - 'origin').
00018
00019 #include "GameObject.h"
00020
00021 class Face : public GameObject
00022 {
00023 public:
00024     Face();
00025     Face(
00026         DirectX::XMFLOAT3 origin,
00027         DirectX::XMFLOAT3 p1,
00028         DirectX::XMFLOAT3 p2
00029         );
00030
00031     void SetPlane(
00032         DirectX::XMFLOAT3 origin,
00033         DirectX::XMFLOAT3 p1,
00034         DirectX::XMFLOAT3 p2
00035         );
00036
00037     virtual bool IsTouching(
00038         DirectX::XMFLOAT3 point,
00039         float radius,
00040         _Out_ DirectX::XMFLOAT3* contact,
00041         _Out_ DirectX::XMFLOAT3* normal
00042         ) override;
00043
00044 protected:
00045     virtual void UpdatePosition() override;
00046
00047 private:
00048     void UpdateMatrix();
00049
00050     DirectX::XMFLOAT3   m_widthVector;
00051     DirectX::XMFLOAT3   m_heightVector;
00052     DirectX::XMFLOAT3   m_normal;
00053     DirectX::XMFLOAT3   m_point[4];
00054     float               m_width;
00055     float               m_height;
00056     DirectX::XMFLOAT4X4 m_rotationMatrix;
00057 };
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: VideoPlayback/cs/Scenario9_TransferMediaPlayer2.xaml.cs Source File

  • VideoPlayback
  • cs

Scenario9_TransferMediaPlayer2.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015
00016 namespace SDKTemplate
00017 {
00018     /// <summary>
00019     /// This scenario demonstrates how the lifetime of a MediaPlayer is independent of the MediaPlayerElement.
00020     ///
00021     /// The MediaPlayerElement on this page is bound to a MediaPlayer created elsewhere.
00022     ///
00023     /// </summary>
00024     public sealed partial class Scenario9_TransferMediaPlayer2 : Page
00025     {
00026         private MainPage rootPage = MainPage.Current;
00027
00028         public Scenario9_TransferMediaPlayer2()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         protected override void OnNavigatedTo(NavigationEventArgs e)
00034         {
00035             // Attach any existing MediaPlayer to the MediaPlayerElement on this page.
00036             mediaPlayerElement.SetMediaPlayer(rootPage.commonMediaPlayer);
00037         }
00038         protected override void OnNavigatedFrom(NavigationEventArgs e)
00039         {
00040             // Detach the MediaPlayer from the MediaPlayerElement, but do not dispose it.
00041             // The MediaPlayer will continue to run, and it can be attached to another MediaPlayerElement.
00042             mediaPlayerElement.SetMediaPlayer(null);
00043         }
00044
00045         private void DisposeMediaPlayer_Click(object sender, RoutedEventArgs e)
00046         {
00047             if(rootPage.commonMediaPlayer != null)
00048             {
00049                 mediaPlayerElement.SetMediaPlayer(null);
00050                 rootPage.commonMediaPlayer.Dispose();
00051                 rootPage.commonMediaPlayer = null;
00052                 rootPage.NotifyUser("Disposed of MediaPlayer.", NotifyType.StatusMessage);
00053             }
00054             else
00055             {
00056                 rootPage.NotifyUser("MediaPlayer was already null.", NotifyType.ErrorMessage);
00057             }
00058         }
00059     }
00060 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Legacy Member List

This is the complete list of members for Scenario3_Legacy, including all inherited members.
LegacyControl_KeyUp(object sender, KeyRoutedEventArgs e) | Scenario3_Legacy | [inline, private]
Scenario3_Legacy() | Scenario3_Legacy | [inline]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraAdvancedCapture/cs/MainPage.xaml.cs Source File

  • CameraAdvancedCapture
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Diagnostics;
00014 using System.Linq;
00015 using System.Threading.Tasks;
00016 using Windows.ApplicationModel;
00017 using Windows.Devices.Enumeration;
00018 using Windows.Devices.Sensors;
00019 using Windows.Foundation;
00020 using Windows.Foundation.Metadata;
00021 using Windows.Graphics.Display;
00022 using Windows.Graphics.Imaging;
00023 using Windows.Media;
00024 using Windows.Media.Capture;
00025 using Windows.Media.Core;
00026 using Windows.Media.Devices;
00027 using Windows.Media.MediaProperties;
00028 using Windows.Phone.UI.Input;
00029 using Windows.Storage;
00030 using Windows.Storage.FileProperties;
00031 using Windows.Storage.Streams;
00032 using Windows.System.Display;
00033 using Windows.UI.Core;
00034 using Windows.UI.Xaml;
00035 using Windows.UI.Xaml.Controls;
00036 using Windows.UI.Xaml.Media;
00037 using Windows.UI.Xaml.Navigation;
00038
00039 namespace CameraAdvancedCapture
00040 {
00041
00042     public sealed partial class MainPage : Page
00043     {
00044         // Receive notifications about rotation of the device and UI and apply any necessary rotation to the preview stream and UI controls
00045         private readonly DisplayInformation _displayInformation = DisplayInformation.GetForCurrentView();
00046         private readonly SimpleOrientationSensor _orientationSensor = SimpleOrientationSensor.GetDefault();
00047         private SimpleOrientation _deviceOrientation = SimpleOrientation.NotRotated;
00048         private DisplayOrientations _displayOrientation = DisplayOrientations.Portrait;
00049
00050         // Rotation metadata to apply to the preview stream and recorded videos (MF_MT_VIDEO_ROTATION)
00051         // Reference: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868174.aspx
00052         private static readonly Guid RotationKey = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1");
00053
00054         // Folder in which the captures will be stored (initialized in SetupUiAsync)
00055         private StorageFolder _captureFolder = null;
00056
00057         // Prevent the screen from sleeping while the camera is running
00058         private readonly DisplayRequest _displayRequest = new DisplayRequest();
00059
00060         // For listening to media property changes
00061         private readonly SystemMediaTransportControls _systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
00062
00063         // MediaCapture and its state variables
00064         private MediaCapture _mediaCapture;
00065         private bool _isInitialized;
00066         private bool _isPreviewing;
00067
00068         // Holds the index of the current Advanced Capture mode (-1 for no Advanced Capture active)
00069         private int _advancedCaptureMode = -1;
00070
00071         // Information about the camera device
00072         private bool _mirroringPreview;
00073         private bool _externalCamera;
00074
00075         // The value at which the certainty from the HDR analyzer maxes out in the graphical representation
00076         private const double CERTAINTY_CAP = 0.7;
00077
00078         // Advanced Capture and Scene Analysis instances
00079         private AdvancedPhotoCapture _advancedCapture;
00080         private SceneAnalysisEffect _sceneAnalysisEffect;
00081
00082
00083         /// <summary>
00084         /// Helper class to contain the information that describes an Advanced Capture
00085         /// </summary>
00086         public class AdvancedCaptureContext
00087         {
00088             public string CaptureFileName;
00089             public PhotoOrientation CaptureOrientation;
00090         }
00091
00092
00093         #region Constructor, lifecycle and navigation
00094
00095         public MainPage()
00096         {
00097             this.InitializeComponent();
00098
00099             // Do not cache the state of the UI when suspending/navigating
00100             NavigationCacheMode = NavigationCacheMode.Disabled;
00101
00102             // Useful to know when to initialize/clean up the camera
00103             Application.Current.Suspending += Application_Suspending;
00104             Application.Current.Resuming += Application_Resuming;
00105
00106             // Set the maximum on the progress bar
00107             HdrImpactBar.Maximum = CERTAINTY_CAP;
00108         }
00109
00110         private async void Application_Suspending(object sender, SuspendingEventArgs e)
00111         {
00112             // Handle global application events only if this page is active
00113             if (Frame.CurrentSourcePageType == typeof(MainPage))
00114             {
00115                 var deferral = e.SuspendingOperation.GetDeferral();
00116
00117                 await CleanupCameraAsync();
00118
00119                 await CleanupUiAsync();
00120
00121                 deferral.Complete();
00122             }
00123         }
00124
00125         private async void Application_Resuming(object sender, object o)
00126         {
00127             // Handle global application events only if this page is active
00128             if (Frame.CurrentSourcePageType == typeof(MainPage))
00129             {
00130                 await SetupUiAsync();
00131
00132                 await InitializeCameraAsync();
00133             }
00134         }
00135
00136         protected override async void OnNavigatedTo(NavigationEventArgs e)
00137         {
00138             await SetupUiAsync();
00139
00140             await InitializeCameraAsync();
00141         }
00142
00143         protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
00144         {
00145             // Handling of this event is included for completeness, as it will only trigger when navigating between pages and this sample only includes one page
00146
00147             await CleanupCameraAsync();
00148
00149             await CleanupUiAsync();
00150         }
00151
00152         #endregion Constructor, lifecycle and navigation
00153
00154
00155         #region Event handlers
00156
00157         /// <summary>
00158         /// In the event of the app being minimized this method handles media property change events. If the app receives a mute
00159         /// notification, it is no longer in the foregroud.
00160         /// </summary>
00161         /// <param name="sender"></param>
00162         /// <param name="args"></param>
00163         private async void SystemMediaControls_PropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs args)
00164         {
00165             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
00166             {
00167                 // Only handle this event if this page is currently being displayed
00168                 if (args.Property == SystemMediaTransportControlsProperty.SoundLevel && Frame.CurrentSourcePageType == typeof(MainPage))
00169                 {
00170                     // Check to see if the app is being muted. If so, it is being minimized.
00171                     // Otherwise if it is not initialized, it is being brought into focus.
00172                     if (sender.SoundLevel == SoundLevel.Muted)
00173                     {
00174                         await CleanupCameraAsync();
00175                     }
00176                     else if (!_isInitialized)
00177                     {
00178                         await InitializeCameraAsync();
00179                     }
00180                 }
00181             });
00182         }
00183
00184         /// <summary>
00185         /// Occurs each time the simple orientation sensor reports a new sensor reading.
00186         /// </summary>
00187         /// <param name="sender">The event source.</param>
00188         /// <param name="args">The event data.</param>
00189         private async void OrientationSensor_OrientationChanged(SimpleOrientationSensor sender, SimpleOrientationSensorOrientationChangedEventArgs args)
00190         {
00191             if (args.Orientation != SimpleOrientation.Faceup && args.Orientation != SimpleOrientation.Facedown)
00192             {
00193                 // Only update the current orientation if the device is not parallel to the ground. This allows users to take pictures of documents (FaceUp)
00194                 // or the ceiling (FaceDown) in portrait or landscape, by first holding the device in the desired orientation, and then pointing the camera
00195                 // either up or down, at the desired subject.
00196                 //Note: This assumes that the camera is either facing the same way as the screen, or the opposite way. For devices with cameras mounted
00197                 //      on other panels, this logic should be adjusted.
00198                 _deviceOrientation = args.Orientation;
00199
00200                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateControlOrientation());
00201             }
00202         }
00203
00204         /// <summary>
00205         /// This event will be raised when the page is rotated, when the DisplayInformation.AutoRotationPreferences value set in the SetupUiAsync() method
00206         /// cannot be not honored.
00207         /// </summary>
00208         /// <param name="sender">The event source.</param>
00209         /// <param name="args">The event data.</param>
00210         private async void DisplayInformation_OrientationChanged(DisplayInformation sender, object args)
00211         {
00212             _displayOrientation = sender.CurrentOrientation;
00213
00214             if (_isPreviewing)
00215             {
00216                 await SetPreviewRotationAsync();
00217             }
00218
00219             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateControlOrientation());
00220         }
00221
00222         /// <summary>
00223         /// This event will be raised every time the effect processes a preview frame, to deliver information about the current scene in the camera preview.
00224         /// </summary>
00225         /// <param name="sender">The effect raising the event.</param>
00226         /// <param name="args">The event data.</param>
00227         private async void SceneAnalysisEffect_SceneAnalyzed(SceneAnalysisEffect sender, SceneAnalyzedEventArgs args)
00228         {
00229             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00230             {
00231                 // Update the graphical representation of how much detail could be recovered through an HDR capture, ranging
00232                 // from 0 ("everything is within the dynamic range of the camera") to CERTAINTY_CAP ("at this point the app
00233                 // strongly recommends an HDR capture"), where CERTAINTY_CAP can be any number between 0 and 1 that the app chooses.
00234                 HdrImpactBar.Value = Math.Min(CERTAINTY_CAP, args.ResultFrame.HighDynamicRange.Certainty);
00235
00236                 SceneTypeTextBlock.Text = "Scene: " + args.ResultFrame.AnalysisRecommendation;
00237             });
00238         }
00239
00240         /// <summary>
00241         /// This event will be raised only on devices that support returning a reference photo, which is a normal exposure of the scene
00242         /// without processing, also referred to as "EV0".
00243         /// </summary>
00244         /// <param name="sender">The object raising this event.</param>
00245         /// <param name="args">The event data.</param>
00246         private async void AdvancedCapture_OptionalReferencePhotoCaptured(AdvancedPhotoCapture sender, OptionalReferencePhotoCapturedEventArgs args)
00247         {
00248             // Retrieve the context (i.e. the information about the capture this event belongs to)
00249             var context = args.Context as AdvancedCaptureContext;
00250
00251             // Add "_Reference" at the end of the filename to create when saving the reference photo
00252             var referenceName = context.CaptureFileName.Replace(".jpg", "_Reference.jpg");
00253
00254             // Hold a reference to the frame before the async file creation operation so it's not cleaned up before ReencodeAndSavePhotoAsync
00255             using (var frame = args.Frame)
00256             {
00257                 var file = await _captureFolder.CreateFileAsync(referenceName, CreationCollisionOption.GenerateUniqueName);
00258                 Debug.WriteLine("AdvancedCapture_OptionalReferencePhotoCaptured for " + context.CaptureFileName + ". Saving to " + file.Path);
00259
00260                 await ReencodeAndSavePhotoAsync(frame, file, context.CaptureOrientation);
00261             }
00262         }
00263
00264         /// <summary>
00265         /// This event will be raised when all the necessary captures are completed, and at this point the camera is technically ready
00266         /// to capture again while the processing takes place.
00267         /// </summary>
00268         /// <param name="sender">The object raising this event.</param>
00269         /// <param name="args">The event data.</param>
00270         private void AdvancedCapture_AllPhotosCaptured(AdvancedPhotoCapture sender, object args)
00271         {
00272             Debug.WriteLine("AdvancedCapture_AllPhotosCaptured");
00273         }
00274
00275         private async void PhotoButton_Click(object sender, RoutedEventArgs e)
00276         {
00277             await TakeAdvancedCapturePhotoAsync();
00278         }
00279
00280         private async void HardwareButtons_CameraPressed(object sender, CameraEventArgs e)
00281         {
00282             await TakeAdvancedCapturePhotoAsync();
00283         }
00284
00285         private async void MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs)
00286         {
00287             Debug.WriteLine("MediaCapture_Failed: (0x{0:X}) {1}", errorEventArgs.Code, errorEventArgs.Message);
00288
00289             await CleanupCameraAsync();
00290
00291             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateUi());
00292         }
00293
00294         #endregion Event handlers
00295
00296
00297         #region MediaCapture methods
00298
00299         /// <summary>
00300         /// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI
00301         /// </summary>
00302         /// <returns></returns>
00303         private async Task InitializeCameraAsync()
00304         {
00305             Debug.WriteLine("InitializeCameraAsync");
00306
00307             if (_mediaCapture == null)
00308             {
00309                 // Attempt to get the back camera if one is available, but use any camera device if not
00310                 var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);
00311
00312                 if (cameraDevice == null)
00313                 {
00314                     Debug.WriteLine("No camera device found!");
00315                     return;
00316                 }
00317
00318                 // Create MediaCapture and its settings
00319                 _mediaCapture = new MediaCapture();
00320
00321                 // Register for a notification when something goes wrong
00322                 _mediaCapture.Failed += MediaCapture_Failed;
00323
00324                 var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
00325
00326                 // Initialize MediaCapture
00327                 try
00328                 {
00329                     await _mediaCapture.InitializeAsync(settings);
00330                     _isInitialized = true;
00331                 }
00332                 catch (UnauthorizedAccessException)
00333                 {
00334                     Debug.WriteLine("The app was denied access to the camera");
00335                 }
00336
00337                 // If initialization succeeded, start the preview, kick off scene analysis, and enable Advanced Capture
00338                 if (_isInitialized)
00339                 {
00340                     // Figure out where the camera is located to account for mirroring and later adjust rotation accordingly
00341                     if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
00342                     {
00343                         // No information on the location of the camera, assume it's an external camera, not integrated on the device
00344                         _externalCamera = true;
00345                     }
00346                     else
00347                     {
00348                         // Camera is fixed on the device
00349                         _externalCamera = false;
00350
00351                         // Only mirror the preview if the camera is on the front panel
00352                         _mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
00353                     }
00354
00355                     await StartPreviewAsync();
00356
00357                     // On successful preview, add a Scene Analysis effect to the pipeline and enter Advanced Capture mode
00358                     if (_isPreviewing)
00359                     {
00360                         await CreateSceneAnalysisEffectAsync();
00361
00362                         await EnableAdvancedCaptureAsync();
00363                     }
00364
00365                 }
00366
00367                 // Update the controls to reflect the current state of the app
00368                 UpdateUi();
00369             }
00370         }
00371
00372         /// <summary>
00373         /// Starts the preview and adjusts it for for rotation and mirroring after making a request to keep the screen on
00374         /// </summary>
00375         /// <returns></returns>
00376         private async Task StartPreviewAsync()
00377         {
00378             // Prevent the device from sleeping while the preview is running
00379             _displayRequest.RequestActive();
00380
00381             // Set the preview source in the UI and mirror it if necessary
00382             PreviewControl.Source = _mediaCapture;
00383             PreviewControl.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
00384
00385             // Start the preview
00386             await _mediaCapture.StartPreviewAsync();
00387             _isPreviewing = true;
00388
00389             // Initialize the preview to the current orientation
00390             if (_isPreviewing)
00391             {
00392                 await SetPreviewRotationAsync();
00393             }
00394         }
00395
00396         /// <summary>
00397         /// Gets the current orientation of the UI in relation to the device (when AutoRotationPreferences cannot be honored) and applies a corrective rotation to the preview
00398         /// </summary>
00399         private async Task SetPreviewRotationAsync()
00400         {
00401             // Only need to update the orientation if the camera is mounted on the device
00402             if (_externalCamera) return;
00403
00404             // Calculate which way and how far to rotate the preview
00405             int rotationDegrees = ConvertDisplayOrientationToDegrees(_displayOrientation);
00406
00407             // The rotation direction needs to be inverted if the preview is being mirrored
00408             if (_mirroringPreview)
00409             {
00410                 rotationDegrees = (360 - rotationDegrees) % 360;
00411             }
00412
00413             // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames
00414             var props = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
00415             props.Properties[RotationKey] = rotationDegrees;
00416             await _mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, null);
00417         }
00418
00419         /// <summary>
00420         /// Stops the preview and deactivates a display request, to allow the screen to go into power saving modes
00421         /// </summary>
00422         /// <returns></returns>
00423         private async Task StopPreviewAsync()
00424         {
00425             // Stop the preview
00426             _isPreviewing = false;
00427             await _mediaCapture.StopPreviewAsync();
00428
00429             // Use the dispatcher because this method is sometimes called from non-UI threads
00430             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00431             {
00432                 // Cleanup the UI
00433                 PreviewControl.Source = null;
00434
00435                 // Allow the device screen to sleep now that the preview is stopped
00436                 _displayRequest.RequestRelease();
00437             });
00438         }
00439
00440         /// <summary>
00441         /// Adds scene analysis to the video preview stream, registers for its event, enables it, and gets the effect instance
00442         /// </summary>
00443         /// <returns></returns>
00444         private async Task CreateSceneAnalysisEffectAsync()
00445         {
00446             // Create the definition, which will contain some initialization settings
00447             var definition = new SceneAnalysisEffectDefinition();
00448
00449             // Add the effect to the video preview stream
00450             _sceneAnalysisEffect = (SceneAnalysisEffect)await _mediaCapture.AddVideoEffectAsync(definition, MediaStreamType.VideoPreview);
00451
00452             Debug.WriteLine("SA effect added to pipeline");
00453
00454             // Subscribe to notifications about scene information
00455             _sceneAnalysisEffect.SceneAnalyzed += SceneAnalysisEffect_SceneAnalyzed;
00456
00457             // Enable HDR analysis
00458             _sceneAnalysisEffect.HighDynamicRangeAnalyzer.Enabled = true;
00459         }
00460
00461         /// <summary>
00462         /// Disables and removes the scene analysis effect, and unregisters the event handler for the SceneAnalyzed event of the effect
00463         /// </summary>
00464         /// <returns></returns>
00465         private async Task CleanSceneAnalysisEffectAsync()
00466         {
00467             // Disable detection and unsubscribe from the events
00468             _sceneAnalysisEffect.HighDynamicRangeAnalyzer.Enabled = false;
00469             _sceneAnalysisEffect.SceneAnalyzed -= SceneAnalysisEffect_SceneAnalyzed;
00470
00471             // Remove the effect from the pipeline (see ClearEffectsAsync method to remove all effects from a given stream)
00472             await _mediaCapture.RemoveEffectAsync(_sceneAnalysisEffect);
00473
00474             Debug.WriteLine("SA effect removed from pipeline");
00475
00476             // Clear the member variable that held the effect instance
00477             _sceneAnalysisEffect = null;
00478         }
00479
00480         /// <summary>
00481         /// Creates an instance of the AdvancedPhotoCapture and registers for its events
00482         /// </summary>
00483         /// <returns></returns>
00484         private async Task EnableAdvancedCaptureAsync()
00485         {
00486             // No work to be done if there already is an AdvancedCapture instance
00487             if (_advancedCapture != null) return;
00488
00489             // Configure one of the modes in the control
00490             CycleAdvancedCaptureMode();
00491
00492             // Prepare for an Advanced Capture
00493             _advancedCapture = await _mediaCapture.PrepareAdvancedPhotoCaptureAsync(ImageEncodingProperties.CreateJpeg());
00494
00495             Debug.WriteLine("Enabled Advanced Capture");
00496
00497             // Register for events published by the AdvancedCapture
00498             _advancedCapture.AllPhotosCaptured += AdvancedCapture_AllPhotosCaptured;
00499             _advancedCapture.OptionalReferencePhotoCaptured += AdvancedCapture_OptionalReferencePhotoCaptured;
00500         }
00501
00502         /// <summary>
00503         /// Configures the AdvancedPhotoControl to the next supported mode
00504         /// </summary>
00505         /// <remarks>
00506         /// Note that this method can be safely called regardless of whether the AdvancedPhotoCapture is in the "prepared
00507         /// state" or not. Internal changes to the mode will be applied  when calling Prepare, or when calling Capture if
00508         /// the mode has been changed since the call to Prepare. This allows for fast changing of desired capture modes,
00509         /// that can more quickly adapt to rapidly changing shooting conditions.
00510         /// </remarks>
00511         private void CycleAdvancedCaptureMode()
00512         {
00513             // Calculate the index for the next supported mode
00514             _advancedCaptureMode = (_advancedCaptureMode + 1) % _mediaCapture.VideoDeviceController.AdvancedPhotoControl.SupportedModes.Count;
00515
00516             // Configure the settings object to the mode at the calculated index
00517             var settings = new AdvancedPhotoCaptureSettings
00518             {
00519                 Mode = _mediaCapture.VideoDeviceController.AdvancedPhotoControl.SupportedModes[_advancedCaptureMode]
00520             };
00521
00522             // Configure the mode on the control
00523             _mediaCapture.VideoDeviceController.AdvancedPhotoControl.Configure(settings);
00524
00525             // Update the button text to reflect the current mode
00526             ModeTextBlock.Text = _mediaCapture.VideoDeviceController.AdvancedPhotoControl.Mode.ToString();
00527         }
00528
00529         /// <summary>
00530         /// Cleans up the instance of the AdvancedCapture
00531         /// </summary>
00532         /// <returns></returns>
00533         private async Task DisableAdvancedCaptureAsync()
00534         {
00535             // No work to be done if there is no AdvancedCapture
00536             if (_advancedCapture == null) return;
00537
00538             await _advancedCapture.FinishAsync();
00539             _advancedCapture = null;
00540
00541             // Reset the Advanced Capture Mode index
00542             _advancedCaptureMode = -1;
00543
00544             Debug.WriteLine("Disabled Advanced Capture");
00545         }
00546
00547         /// <summary>
00548         /// Takes an Advanced Capture photo to a StorageFile and adds rotation metadata to it
00549         /// </summary>
00550         /// <returns></returns>
00551         private async Task TakeAdvancedCapturePhotoAsync()
00552         {
00553             // Lock the UI as a simple way to prevent reentrancy
00554             PhotoButton.IsEnabled = false;
00555             CycleModeButton.IsEnabled = false;
00556
00557             try
00558             {
00559                 Debug.WriteLine("Taking Advanced Capture photo...");
00560                 // Read the current orientation of the camera and the capture time
00561                 var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
00562                 var fileName = String.Format("AdvancedCapturePhoto_{0}.jpg", DateTime.Now.ToString("HHmmss"));
00563
00564                 // Create a context object, to identify the capture later on
00565                 var context = new AdvancedCaptureContext {CaptureFileName = fileName, CaptureOrientation = photoOrientation};
00566
00567                 // Start capture, and pass the context object to get it back in the OptionalReferencePhotoCaptured event
00568                 var capture = await _advancedCapture.CaptureAsync(context);
00569
00570                 using (var frame = capture.Frame)
00571                 {
00572                     var file = await _captureFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
00573                     Debug.WriteLine("Advanced Capture photo taken! Saving to " + file.Path);
00574
00575                     await ReencodeAndSavePhotoAsync(frame, file, photoOrientation);
00576                 }
00577             }
00578             catch (Exception ex)
00579             {
00580                 // File I/O errors are reported as exceptions
00581                 Debug.WriteLine("Exception when taking an Advanced Capture photo: " + ex.ToString());
00582             }
00583             finally
00584             {
00585                 // Re-enable the buttons to reflect the current state of the app
00586                 UpdateUi();
00587             }
00588         }
00589
00590         /// <summary>
00591         /// Cleans up the camera resources (after stopping any video recording and/or preview if necessary) and unregisters from MediaCapture events
00592         /// </summary>
00593         /// <returns></returns>
00594         private async Task CleanupCameraAsync()
00595         {
00596             Debug.WriteLine("CleanupCameraAsync");
00597
00598             if (_isInitialized)
00599             {
00600                 if (_isPreviewing)
00601                 {
00602                     // The call to stop the preview is included here for completeness, but can be
00603                     // safely removed if a call to MediaCapture.Dispose() is being made later,
00604                     // as the preview will be automatically stopped at that point
00605                     await StopPreviewAsync();
00606                 }
00607
00608                 if (_advancedCapture != null)
00609                 {
00610                     await DisableAdvancedCaptureAsync();
00611                 }
00612
00613                 if (_sceneAnalysisEffect != null)
00614                 {
00615                     await CleanSceneAnalysisEffectAsync();
00616                 }
00617
00618                 _isInitialized = false;
00619             }
00620
00621             if (_mediaCapture != null)
00622             {
00623                 _mediaCapture.Failed -= MediaCapture_Failed;
00624                 _mediaCapture.Dispose();
00625                 _mediaCapture = null;
00626             }
00627         }
00628
00629         #endregion MediaCapture methods
00630
00631
00632         #region Helper methods
00633
00634         /// <summary>
00635         /// Attempts to lock the page orientation, hide the StatusBar (on Phone) and registers event handlers for hardware buttons and orientation sensors
00636         /// </summary>
00637         /// <returns></returns>
00638         private async Task SetupUiAsync()
00639             {
00640                 // Attempt to lock page to landscape orientation to prevent the CaptureElement from rotating, as this gives a better experience
00641                 DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
00642
00643                 // Hide the status bar
00644                 if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00645                 {
00646                     await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();
00647                 }
00648
00649                 // Populate orientation variables with the current state
00650                 _displayOrientation = _displayInformation.CurrentOrientation;
00651                 if (_orientationSensor != null)
00652                 {
00653                     _deviceOrientation = _orientationSensor.GetCurrentOrientation();
00654                 }
00655
00656                 RegisterEventHandlers();
00657
00658                 var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
00659                 // Fall back to the local app storage if the Pictures Library is not available
00660                 _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
00661             }
00662
00663         /// <summary>
00664         /// Unregisters event handlers for hardware buttons and orientation sensors, allows the StatusBar (on Phone) to show, and removes the page orientation lock
00665         /// </summary>
00666         /// <returns></returns>
00667         private async Task CleanupUiAsync()
00668         {
00669             UnregisterEventHandlers();
00670
00671             // Show the status bar
00672             if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00673             {
00674                 await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync();
00675             }
00676
00677             // Revert orientation preferences
00678             DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;
00679         }
00680
00681         /// <summary>
00682         /// This method will enable/disable the buttons depending on the current state of the app
00683         /// </summary>
00684         private void UpdateUi()
00685         {
00686             // The buttons should only be enabled if the preview started sucessfully
00687             PhotoButton.IsEnabled = _isPreviewing;
00688             CycleModeButton.IsEnabled = _isPreviewing;
00689         }
00690
00691         /// <summary>
00692         /// Registers event handlers for hardware buttons and orientation sensors, and performs an initial update of the UI rotation
00693         /// </summary>
00694         private void RegisterEventHandlers()
00695         {
00696             if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00697             {
00698                 HardwareButtons.CameraPressed += HardwareButtons_CameraPressed;
00699             }
00700
00701             // If there is an orientation sensor present on the device, register for notifications
00702             if (_orientationSensor != null)
00703             {
00704                 _orientationSensor.OrientationChanged += OrientationSensor_OrientationChanged;
00705
00706                 // Update orientation of buttons with the current orientation
00707                 UpdateControlOrientation();
00708             }
00709
00710             // Have the Advanced Capture button call the method that cycles through the modes
00711             CycleModeButton.Click += (sender, args) => CycleAdvancedCaptureMode();
00712
00713             _displayInformation.OrientationChanged += DisplayInformation_OrientationChanged;
00714             _systemMediaControls.PropertyChanged += SystemMediaControls_PropertyChanged;
00715         }
00716
00717         /// <summary>
00718         /// Unregisters event handlers for hardware buttons and orientation sensors
00719         /// </summary>
00720         private void UnregisterEventHandlers()
00721         {
00722             if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00723             {
00724                 HardwareButtons.CameraPressed -= HardwareButtons_CameraPressed;
00725             }
00726
00727             if (_orientationSensor != null)
00728             {
00729                 _orientationSensor.OrientationChanged -= OrientationSensor_OrientationChanged;
00730             }
00731
00732             _displayInformation.OrientationChanged -= DisplayInformation_OrientationChanged;
00733             _systemMediaControls.PropertyChanged -= SystemMediaControls_PropertyChanged;
00734         }
00735
00736         /// <summary>
00737         /// Attempts to find and return a device mounted on the panel specified, and on failure to find one it will return the first device listed
00738         /// </summary>
00739         /// <param name="desiredPanel">The desired panel on which the returned device should be mounted, if available</param>
00740         /// <returns></returns>
00741         private static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel)
00742         {
00743             // Get available devices for capturing pictures
00744             var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
00745
00746             // Get the desired camera by panel
00747             DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);
00748
00749             // If there is no device mounted on the desired panel, return the first device found
00750             return desiredDevice ?? allVideoDevices.FirstOrDefault();
00751         }
00752
00753         /// <summary>
00754         /// Applies the given orientation to a photo stream and saves it as a StorageFile
00755         /// </summary>
00756         /// <param name="stream">The photo stream</param>
00757         /// <param name="file">The StorageFile in which the photo stream will be saved</param>
00758         /// <param name="photoOrientation">The orientation metadata to apply to the photo</param>
00759         /// <returns></returns>
00760         private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation)
00761         {
00762             using (var inputStream = stream)
00763             {
00764                 var decoder = await BitmapDecoder.CreateAsync(inputStream);
00765
00766                 using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
00767                 {
00768                     var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
00769
00770                     var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };
00771
00772                     await encoder.BitmapProperties.SetPropertiesAsync(properties);
00773                     await encoder.FlushAsync();
00774                 }
00775             }
00776         }
00777
00778         #endregion Helper functions
00779
00780
00781         #region Rotation helpers
00782
00783         /// <summary>
00784         /// Calculates the current camera orientation from the device orientation by taking into account whether the camera is external or facing the user
00785         /// </summary>
00786         /// <returns>The camera orientation in space, with an inverted rotation in the case the camera is mounted on the device and is facing the user</returns>
00787         private SimpleOrientation GetCameraOrientation()
00788         {
00789             if (_externalCamera)
00790             {
00791                 // Cameras that are not attached to the device do not rotate along with it, so apply no rotation
00792                 return SimpleOrientation.NotRotated;
00793             }
00794
00795             var result = _deviceOrientation;
00796
00797             // Account for the fact that, on portrait-first devices, the camera sensor is mounted at a 90 degree offset to the native orientation
00798             if (_displayInformation.NativeOrientation == DisplayOrientations.Portrait)
00799             {
00800                 switch (result)
00801                 {
00802                     case SimpleOrientation.Rotated90DegreesCounterclockwise:
00803                         result = SimpleOrientation.NotRotated;
00804                         break;
00805                     case SimpleOrientation.Rotated180DegreesCounterclockwise:
00806                         result = SimpleOrientation.Rotated90DegreesCounterclockwise;
00807                         break;
00808                     case SimpleOrientation.Rotated270DegreesCounterclockwise:
00809                         result = SimpleOrientation.Rotated180DegreesCounterclockwise;
00810                         break;
00811                     case SimpleOrientation.NotRotated:
00812                         result = SimpleOrientation.Rotated270DegreesCounterclockwise;
00813                         break;
00814                 }
00815             }
00816
00817             // If the preview is being mirrored for a front-facing camera, then the rotation should be inverted
00818             if (_mirroringPreview)
00819             {
00820                 // This only affects the 90 and 270 degree cases, because rotating 0 and 180 degrees is the same clockwise and counter-clockwise
00821                 switch (result)
00822                 {
00823                     case SimpleOrientation.Rotated90DegreesCounterclockwise:
00824                         return SimpleOrientation.Rotated270DegreesCounterclockwise;
00825                     case SimpleOrientation.Rotated270DegreesCounterclockwise:
00826                         return SimpleOrientation.Rotated90DegreesCounterclockwise;
00827                 }
00828             }
00829
00830             return result;
00831         }
00832
00833         /// <summary>
00834         /// Converts the given orientation of the device in space to the corresponding rotation in degrees
00835         /// </summary>
00836         /// <param name="orientation">The orientation of the device in space</param>
00837         /// <returns>An orientation in degrees</returns>
00838         private static int ConvertDeviceOrientationToDegrees(SimpleOrientation orientation)
00839         {
00840             switch (orientation)
00841             {
00842                 case SimpleOrientation.Rotated90DegreesCounterclockwise:
00843                     return 90;
00844                 case SimpleOrientation.Rotated180DegreesCounterclockwise:
00845                     return 180;
00846                 case SimpleOrientation.Rotated270DegreesCounterclockwise:
00847                     return 270;
00848                 case SimpleOrientation.NotRotated:
00849                 default:
00850                     return 0;
00851             }
00852         }
00853
00854         /// <summary>
00855         /// Converts the given orientation of the app on the screen to the corresponding rotation in degrees
00856         /// </summary>
00857         /// <param name="orientation">The orientation of the app on the screen</param>
00858         /// <returns>An orientation in degrees</returns>
00859         private static int ConvertDisplayOrientationToDegrees(DisplayOrientations orientation)
00860         {
00861             switch (orientation)
00862             {
00863                 case DisplayOrientations.Portrait:
00864                     return 90;
00865                 case DisplayOrientations.LandscapeFlipped:
00866                     return 180;
00867                 case DisplayOrientations.PortraitFlipped:
00868                     return 270;
00869                 case DisplayOrientations.Landscape:
00870                 default:
00871                     return 0;
00872             }
00873         }
00874
00875         /// <summary>
00876         /// Converts the given orientation of the device in space to the metadata that can be added to captured photos
00877         /// </summary>
00878         /// <param name="orientation">The orientation of the device in space</param>
00879         /// <returns></returns>
00880         private static PhotoOrientation ConvertOrientationToPhotoOrientation(SimpleOrientation orientation)
00881         {
00882             switch (orientation)
00883             {
00884                 case SimpleOrientation.Rotated90DegreesCounterclockwise:
00885                     return PhotoOrientation.Rotate90;
00886                 case SimpleOrientation.Rotated180DegreesCounterclockwise:
00887                     return PhotoOrientation.Rotate180;
00888                 case SimpleOrientation.Rotated270DegreesCounterclockwise:
00889                     return PhotoOrientation.Rotate270;
00890                 case SimpleOrientation.NotRotated:
00891                 default:
00892                     return PhotoOrientation.Normal;
00893             }
00894         }
00895
00896         /// <summary>
00897         /// Uses the current device orientation in space and page orientation on the screen to calculate the rotation
00898         /// transformation to apply to the controls
00899         /// </summary>
00900         private void UpdateControlOrientation()
00901         {
00902             int device = ConvertDeviceOrientationToDegrees(_deviceOrientation);
00903             int display = ConvertDisplayOrientationToDegrees(_displayOrientation);
00904
00905             if (_displayInformation.NativeOrientation == DisplayOrientations.Portrait)
00906             {
00907                 device -= 90;
00908             }
00909
00910             // Combine both rotations and make sure that 0 <= result < 360
00911             var angle = (360 + display + device) % 360;
00912
00913             // Rotate the buttons in the UI to match the rotation of the device
00914             var transform = new RotateTransform { Angle = angle };
00915
00916             // The RenderTransform is safe to use (i.e. it won't cause layout issues) in this case, because these buttons have a 1:1 aspect ratio
00917             PhotoButton.RenderTransform = transform;
00918             CycleModeButton.RenderTransform = transform;
00919
00920             // Adjust which way the progress bar fills so it's always from the user's left->right or bottom->top
00921             HdrImpactBar.FlowDirection = (angle == 180 || angle == 270) ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
00922         }
00923
00924         #endregion Rotation helpers
00925     }
00926 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DAdvancedColorImages/cpp/D2DAdvancedColorImages/FilmicEffect.cpp Source File

  • D2DAdvancedColorImages
  • cpp
  • D2DAdvancedColorImages

FilmicEffect.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <initguid.h>
00014 #include "FilmicEffect.h"
00015 #include "BasicReaderWriter.h"
00016
00017 #define XML(X) TEXT(#X)
00018
00019 FilmicEffect::FilmicEffect() :
00020     m_refCount(1)
00021 {
00022 }
00023
00024 HRESULT __stdcall FilmicEffect::CreateFilmicImpl(_Outptr_ IUnknown** ppEffectImpl)
00025 {
00026     // Since the object's refcount is initialized to 1, we don't need to AddRef here.
00027     *ppEffectImpl = static_cast<ID2D1EffectImpl*>(new (std::nothrow) FilmicEffect());
00028
00029     if (*ppEffectImpl == nullptr)
00030     {
00031         return E_OUTOFMEMORY;
00032     }
00033     else
00034     {
00035         return S_OK;
00036     }
00037 }
00038
00039 HRESULT FilmicEffect::Register(_In_ ID2D1Factory1* pFactory)
00040 {
00041     // The inspectable metadata of an effect is defined in XML. This can be passed in from an external source
00042     // as well, however for simplicity we just inline the XML.
00043     PCWSTR pszXml =
00044         XML(
00045             <?xml version='1.0'?>
00046             <Effect>
00047                 <!-- System Properties -->
00048                 <Property name='DisplayName' type='string' value='Filmic Tonemapper' />
00049                 <Property name='Author' type='string' value='Microsoft Corporation' />
00050                 <Property name='Category' type='string' value='Stylize' />
00051                 <Property name='Description' type='string' value='Simplified version of the ACES Filmic HDR tonemapper' />
00052                 <Inputs>
00053                     <Input name='Source' />
00054                 </Inputs>
00055                 <!-- Custom Properties go here -->
00056             </Effect>
00057             );
00058
00059     // This registers the effect with the factory, which will make the effect
00060     // instantiatable.
00061     return pFactory->RegisterEffectFromString(
00062         CLSID_CustomFilmicEffect,
00063         pszXml,
00064         nullptr,
00065         0,
00066         CreateFilmicImpl
00067         );
00068 }
00069
00070 IFACEMETHODIMP FilmicEffect::Initialize(
00071     _In_ ID2D1EffectContext* pEffectContext,
00072     _In_ ID2D1TransformGraph* pTransformGraph
00073 )
00074 {
00075     // To maintain consistency across different DPIs, this effect needs to cover more pixels at
00076     // higher than normal DPIs. The context is saved here so the effect can later retrieve the DPI.
00077     m_effectContext = pEffectContext;
00078
00079     BasicReaderWriter^ reader = ref new BasicReaderWriter();
00080     Platform::Array<unsigned char, 1U>^ data;
00081
00082     try
00083     {
00084         data = reader->ReadData("FilmicEffect.cso");
00085     }
00086     catch (Platform::Exception^ e)
00087     {
00088         // Return error if file can not be read.
00089         return e->HResult;
00090     }
00091
00092     HRESULT hr = pEffectContext->LoadPixelShader(GUID_FilmicEffectPixelShader, data->Data, data->Length);
00093
00094     // This loads the shader into the Direct2D image effects system and associates it with the GUID passed in.
00095     // If this method is called more than once (say by other instances of the effect) with the same GUID,
00096     // the system will simply do nothing, ensuring that only one instance of a shader is stored regardless of how
00097     // many time it is used.
00098     if (SUCCEEDED(hr))
00099     {
00100         // The graph consists of a single transform. In fact, this class is the transform,
00101         // reducing the complexity of implementing an effect when all we need to
00102         // do is use a single pixel shader.
00103         hr = pTransformGraph->SetSingleTransformNode(this);
00104     }
00105
00106     return hr;
00107 }
00108
00109 HRESULT FilmicEffect::UpdateConstants()
00110 {
00111     // Update the DPI if it has changed. This allows the effect to scale across different DPIs automatically.
00112     m_effectContext->GetDpi(&m_dpi, &m_dpi);
00113     m_constants.dpi = m_dpi;
00114
00115     return m_drawInfo->SetPixelShaderConstantBuffer(reinterpret_cast<BYTE*>(&m_constants), sizeof(m_constants));
00116 }
00117
00118 IFACEMETHODIMP FilmicEffect::PrepareForRender(D2D1_CHANGE_TYPE changeType)
00119 {
00120     return UpdateConstants();
00121 }
00122
00123 // SetGraph is only called when the number of inputs changes. This never happens as we publish this effect
00124 // as a single input effect.
00125 IFACEMETHODIMP FilmicEffect::SetGraph(_In_ ID2D1TransformGraph* pGraph)
00126 {
00127     return E_NOTIMPL;
00128 }
00129
00130 // Called to assign a new render info class, which is used to inform D2D on
00131 // how to set the state of the GPU.
00132 IFACEMETHODIMP FilmicEffect::SetDrawInfo(_In_ ID2D1DrawInfo* pDrawInfo)
00133 {
00134     m_drawInfo = pDrawInfo;
00135
00136     return m_drawInfo->SetPixelShader(GUID_FilmicEffectPixelShader);
00137 }
00138
00139 // Calculates the mapping between the output and input rects.
00140 IFACEMETHODIMP FilmicEffect::MapOutputRectToInputRects(
00141     _In_ const D2D1_RECT_L* pOutputRect,
00142     _Out_writes_(inputRectCount) D2D1_RECT_L* pInputRects,
00143     UINT32 inputRectCount
00144     ) const
00145 {
00146     // This effect has exactly one input, so if there is more than one input rect,
00147     // something is wrong.
00148     if (inputRectCount != 1)
00149     {
00150         return E_INVALIDARG;
00151     }
00152
00153     pInputRects[0].left    = pOutputRect->left;
00154     pInputRects[0].top     = pOutputRect->top;
00155     pInputRects[0].right   = pOutputRect->right;
00156     pInputRects[0].bottom  = pOutputRect->bottom;
00157
00158     return S_OK;
00159 }
00160
00161 IFACEMETHODIMP FilmicEffect::MapInputRectsToOutputRect(
00162     _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputRects,
00163     _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputOpaqueSubRects,
00164     UINT32 inputRectCount,
00165     _Out_ D2D1_RECT_L* pOutputRect,
00166     _Out_ D2D1_RECT_L* pOutputOpaqueSubRect
00167     )
00168 {
00169     // This effect has exactly one input, so if there is more than one input rect,
00170     // something is wrong.
00171     if (inputRectCount != 1)
00172     {
00173         return E_INVALIDARG;
00174     }
00175
00176     *pOutputRect = pInputRects[0];
00177     m_inputRect = pInputRects[0];
00178
00179     // Indicate that entire output might contain transparency.
00180     ZeroMemory(pOutputOpaqueSubRect, sizeof(*pOutputOpaqueSubRect));
00181
00182     return S_OK;
00183 }
00184
00185 IFACEMETHODIMP FilmicEffect::MapInvalidRect(
00186     UINT32 inputIndex,
00187     D2D1_RECT_L invalidInputRect,
00188     _Out_ D2D1_RECT_L* pInvalidOutputRect
00189     ) const
00190 {
00191     HRESULT hr = S_OK;
00192
00193     // Indicate that the entire output may be invalid.
00194     *pInvalidOutputRect = m_inputRect;
00195
00196     return hr;
00197 }
00198
00199 IFACEMETHODIMP_(UINT32) FilmicEffect::GetInputCount() const
00200 {
00201     return 1;
00202 }
00203
00204 // D2D ensures that that effects are only referenced from one thread at a time.
00205 // To improve performance, we simply increment/decrement our reference count
00206 // rather than use atomic InterlockedIncrement()/InterlockedDecrement() functions.
00207 IFACEMETHODIMP_(ULONG) FilmicEffect::AddRef()
00208 {
00209     m_refCount++;
00210     return m_refCount;
00211 }
00212
00213 IFACEMETHODIMP_(ULONG) FilmicEffect::Release()
00214 {
00215     m_refCount--;
00216
00217     if (m_refCount == 0)
00218     {
00219         delete this;
00220         return 0;
00221     }
00222     else
00223     {
00224         return m_refCount;
00225     }
00226 }
00227
00228 // This enables the stack of parent interfaces to be queried.
00229 IFACEMETHODIMP FilmicEffect::QueryInterface(
00230     _In_ REFIID riid,
00231     _Outptr_ void** ppOutput
00232     )
00233 {
00234     *ppOutput = nullptr;
00235     HRESULT hr = S_OK;
00236
00237     if (riid == __uuidof(ID2D1EffectImpl))
00238     {
00239         *ppOutput = reinterpret_cast<ID2D1EffectImpl*>(this);
00240     }
00241     else if (riid == __uuidof(ID2D1DrawTransform))
00242     {
00243         *ppOutput = static_cast<ID2D1DrawTransform*>(this);
00244     }
00245     else if (riid == __uuidof(ID2D1Transform))
00246     {
00247         *ppOutput = static_cast<ID2D1Transform*>(this);
00248     }
00249     else if (riid == __uuidof(ID2D1TransformNode))
00250     {
00251         *ppOutput = static_cast<ID2D1TransformNode*>(this);
00252     }
00253     else if (riid == __uuidof(IUnknown))
00254     {
00255         *ppOutput = this;
00256     }
00257     else
00258     {
00259         hr = E_NOINTERFACE;
00260     }
00261
00262     if (*ppOutput != nullptr)
00263     {
00264         AddRef();
00265     }
00266
00267     return hr;
00268 }
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SpinningCubeRenderer Member List

This is the complete list of members for SpinningCubeRenderer, including all inherited members.
CreateDeviceDependentResources() | SpinningCubeRenderer |
GetPosition() | SpinningCubeRenderer | [inline]
m_degreesPerSecond | SpinningCubeRenderer | [private]
m_deviceResources | SpinningCubeRenderer | [private]
m_geometryShader | SpinningCubeRenderer | [private]
m_indexBuffer | SpinningCubeRenderer | [private]
m_indexCount | SpinningCubeRenderer | [private]
m_inputLayout | SpinningCubeRenderer | [private]
m_loadingComplete | SpinningCubeRenderer | [private]
m_modelConstantBuffer | SpinningCubeRenderer | [private]
m_modelConstantBufferData | SpinningCubeRenderer | [private]
m_pixelShader | SpinningCubeRenderer | [private]
m_position | SpinningCubeRenderer | [private]
m_usingVprtShaders | SpinningCubeRenderer | [private]
m_vertexBuffer | SpinningCubeRenderer | [private]
m_vertexShader | SpinningCubeRenderer | [private]
PositionHologram(Windows::UI::Input::Spatial::SpatialPointerPose^pointerPose) | SpinningCubeRenderer |
ReleaseDeviceDependentResources() | SpinningCubeRenderer |
Render() | SpinningCubeRenderer |
SetPosition(Windows::Foundation::Numerics::float3 pos) | SpinningCubeRenderer | [inline]
SpinningCubeRenderer(const std::shared_ptr< DX::DeviceResources > &deviceResources) | SpinningCubeRenderer |
Update(const DX::StepTimer &timer) | SpinningCubeRenderer |
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MFSampleGenerator Member List

This is the complete list of members for MFSampleGenerator, including all inherited members.
AddSamplesToQueue(IMFSample *MFSample) | MFSampleGenerator | [private]
ConfigureStreams(com_ptr< IMFSourceReader > const &reader, WAVEFORMATEX *wfx) | MFSampleGenerator | [private, static]
CreateAudioType(WAVEFORMATEX *wfx) | MFSampleGenerator | [private, static]
EndOfStream enum value | MFSampleGenerator |
event | MFSampleGenerator |
FillSampleBuffer(array_view< uint8_t > buffer, uint32_t *cbWritten) | MFSampleGenerator |
Initialize(Windows::Storage::Streams::IRandomAccessStream const &stream, UINT32 FramesPerPeriod, WAVEFORMATEX *wfx) | MFSampleGenerator |
IsEOF() | MFSampleGenerator | [inline]
IsPreRollFilled() | MFSampleGenerator | [private]
m_audioMediaType | MFSampleGenerator | [private]
m_bytesPerPeriod | MFSampleGenerator | [private]
m_bytesPerSecond | MFSampleGenerator | [private]
m_isInitialized | MFSampleGenerator | [private]
m_readerState | MFSampleGenerator | [private]
m_sampleQueue | MFSampleGenerator | [private]
m_sampleQueueTail | MFSampleGenerator | [private]
m_sourceReader | MFSampleGenerator | [private]
MFSampleGenerator() | MFSampleGenerator |
Playing enum value | MFSampleGenerator |
PreRoll enum value | MFSampleGenerator |
ReaderState enum name | MFSampleGenerator |
sample | MFSampleGenerator |
Shutdown() | MFSampleGenerator |
StartSource() | MFSampleGenerator |
STDMETHODIMP_(HRESULT) OnEvent(_In_ DWORD streamIndex | MFSampleGenerator |
STDMETHODIMP_(HRESULT) OnFlush(_In_ DWORD streamIndex) | MFSampleGenerator |
STDMETHODIMP_(HRESULT) OnReadSample(HRESULT error | MFSampleGenerator |
Stopped enum value | MFSampleGenerator |
StopSource() | MFSampleGenerator |
streamFlags | MFSampleGenerator |
streamIndex | MFSampleGenerator |
timestamp | MFSampleGenerator |
~MFSampleGenerator() | MFSampleGenerator |
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSerialDeviceAccess/cs/Scenario3_ReadWrite.xaml.cs Source File

  • CustomSerialDeviceAccess
  • cs

Scenario3_ReadWrite.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Diagnostics;
00014 using System.Threading;
00015
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 using Windows.Devices.SerialCommunication;
00022
00023 using System.Threading.Tasks;
00024 using Windows.Storage.Streams;
00025
00026 using SDKTemplate;
00027 using CustomSerialDeviceAccess;
00028
00029 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00030
00031 namespace CustomSerialDeviceAccess
00032 {
00033     /// <summary>
00034     /// An empty page that can be used on its own or navigated to within a Frame.
00035     /// </summary>
00036
00037     public sealed partial class Scenario3_ReadWrite : Page, IDisposable
00038     {
00039         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00040         // as NotifyUser()
00041         private MainPage rootPage = MainPage.Current;
00042
00043         // Track Read Operation
00044         private CancellationTokenSource ReadCancellationTokenSource;
00045         private Object ReadCancelLock = new Object();
00046
00047         private Boolean IsReadTaskPending;
00048         private uint ReadBytesCounter = 0;
00049         DataReader DataReaderObject = null;
00050
00051         // Track Write Operation
00052         private CancellationTokenSource WriteCancellationTokenSource;
00053         private Object WriteCancelLock = new Object();
00054
00055         private Boolean IsWriteTaskPending;
00056         private uint WriteBytesCounter = 0;
00057         DataWriter DataWriteObject = null;
00058
00059         bool WriteBytesAvailable = false;
00060
00061         // Indicate if we navigate away from this page or not.
00062         private Boolean IsNavigatedAway;
00063
00064         public Scenario3_ReadWrite()
00065         {
00066             this.InitializeComponent();
00067         }
00068
00069         public void Dispose()
00070         {
00071             if (ReadCancellationTokenSource != null)
00072             {
00073                 ReadCancellationTokenSource.Dispose();
00074                 ReadCancellationTokenSource = null;
00075             }
00076
00077             if (WriteCancellationTokenSource != null)
00078             {
00079                 WriteCancellationTokenSource.Dispose();
00080                 WriteCancellationTokenSource = null;
00081             }
00082         }
00083
00084         /// <summary>
00085         /// Invoked when this page is about to be displayed in a Frame.
00086         ///
00087         /// We will enable/disable parts of the UI if the device doesn't support it.
00088         /// </summary>
00089         /// <param name="eventArgs">Event data that describes how this page was reached.  The Parameter
00090         /// property is typically used to configure the page.</param>
00091         protected override void OnNavigatedTo(NavigationEventArgs eventArgs)
00092         {
00093
00094             IsNavigatedAway = false;
00095             if (EventHandlerForDevice.Current.Device == null)
00096             {
00097                 ReadWriteScollViewer.Visibility = Visibility.Collapsed;
00098                 MainPage.Current.NotifyUser("Device is not connected", NotifyType.ErrorMessage);
00099             }
00100             else
00101             {
00102                 if (EventHandlerForDevice.Current.Device.PortName != "")
00103                 {
00104                     MainPage.Current.NotifyUser("Connected to " + EventHandlerForDevice.Current.Device.PortName,
00105                                                 NotifyType.StatusMessage);
00106                 }
00107
00108                 // So we can reset future tasks
00109
00110                 ResetReadCancellationTokenSource();
00111                 ResetWriteCancellationTokenSource();
00112
00113                 UpdateReadButtonStates();
00114                 UpdateWriteButtonStates();
00115
00116                 UpdateReadBytesCounterView();
00117                 UpdateReadTimeoutView();
00118
00119                 UpdateWriteBytesCounterView();
00120                 UpdateWriteTimeoutView();
00121
00122             }
00123         }
00124
00125         /// <summary>
00126         /// Cancel any on going tasks when navigating away from the page so the device is in a consistent state throughout
00127         /// all the scenarios
00128         /// </summary>
00129         /// <param name="eventArgs"></param>
00130         protected override void OnNavigatedFrom(NavigationEventArgs eventArgs)
00131         {
00132             IsNavigatedAway = true;
00133
00134             CancelAllIoTasks();
00135         }
00136
00137         private void UpdateWriteBytesCounterView()
00138         {
00139             WriteBytesCounterValue.Text = " " + WriteBytesCounter.ToString() + " bytes";
00140         }
00141
00142         private void UpdateWriteTimeoutView()
00143         {
00144             WriteTimeoutValue.Text = EventHandlerForDevice.Current.Device.WriteTimeout.TotalMilliseconds.ToString();
00145         }
00146
00147         private void UpdateReadBytesCounterView()
00148         {
00149             ReadBytesCounterValue.Text = " " + ReadBytesCounter.ToString() + " bytes";
00150         }
00151
00152         private void UpdateReadTimeoutView()
00153         {
00154             ReadTimeoutValue.Text = EventHandlerForDevice.Current.Device.ReadTimeout.TotalMilliseconds.ToString();
00155         }
00156
00157         private void ReadTimeoutButton_Click(object sender, RoutedEventArgs e)
00158         {
00159             int ReadTimeoutInput = int.Parse(ReadTimeoutInputValue.Text);
00160             EventHandlerForDevice.Current.Device.ReadTimeout = new System.TimeSpan(ReadTimeoutInput * 10000);
00161             UpdateReadTimeoutView();
00162         }
00163
00164         private void WriteTimeoutButton_Click(object sender, RoutedEventArgs e)
00165         {
00166             int WriteTimeoutInput = int.Parse(WriteTimeoutInputValue.Text);
00167             EventHandlerForDevice.Current.Device.WriteTimeout = new System.TimeSpan(WriteTimeoutInput * 10000);
00168             UpdateWriteTimeoutView();
00169         }
00170
00171         async private void ReadButton_Click(object sender, RoutedEventArgs e)
00172         {
00173             if (EventHandlerForDevice.Current.IsDeviceConnected)
00174             {
00175                 try
00176                 {
00177                     rootPage.NotifyUser("Reading...", NotifyType.StatusMessage);
00178
00179                     // We need to set this to true so that the buttons can be updated to disable the read button. We will not be able to
00180                     // update the button states until after the read completes.
00181                     IsReadTaskPending = true;
00182                     DataReaderObject = new DataReader(EventHandlerForDevice.Current.Device.InputStream);
00183                     UpdateReadButtonStates();
00184
00185                     await ReadAsync(ReadCancellationTokenSource.Token);
00186                 }
00187                 catch (OperationCanceledException /*exception*/)
00188                 {
00189                     NotifyReadTaskCanceled();
00190                 }
00191                 catch (Exception exception)
00192                 {
00193                     MainPage.Current.NotifyUser(exception.Message.ToString(), NotifyType.ErrorMessage);
00194                     Debug.WriteLine(exception.Message.ToString());
00195                 }
00196                 finally
00197                 {
00198                     IsReadTaskPending = false;
00199                     DataReaderObject.DetachStream();
00200                     DataReaderObject = null;
00201
00202                     UpdateReadButtonStates();
00203                 }
00204             }
00205             else
00206             {
00207                 Utilities.NotifyDeviceNotConnected();
00208             }
00209         }
00210
00211         private async void WriteButton_Click(object sender, RoutedEventArgs e)
00212         {
00213             if (EventHandlerForDevice.Current.IsDeviceConnected)
00214             {
00215                 try
00216                 {
00217                     rootPage.NotifyUser("Writing...", NotifyType.StatusMessage);
00218
00219                     // We need to set this to true so that the buttons can be updated to disable the write button. We will not be able to
00220                     // update the button states until after the write completes.
00221                     IsWriteTaskPending = true;
00222                     DataWriteObject = new DataWriter(EventHandlerForDevice.Current.Device.OutputStream);
00223                     UpdateWriteButtonStates();
00224
00225                     await WriteAsync(WriteCancellationTokenSource.Token);
00226                 }
00227                 catch (OperationCanceledException /*exception*/)
00228                 {
00229                     NotifyWriteTaskCanceled();
00230                 }
00231                 catch (Exception exception)
00232                 {
00233                     MainPage.Current.NotifyUser(exception.Message.ToString(), NotifyType.ErrorMessage);
00234                     Debug.WriteLine(exception.Message.ToString());
00235                 }
00236                 finally
00237                 {
00238                     IsWriteTaskPending = false;
00239                     DataWriteObject.DetachStream();
00240                     DataWriteObject = null;
00241
00242                     UpdateWriteButtonStates();
00243                 }
00244             }
00245             else
00246             {
00247                 Utilities.NotifyDeviceNotConnected();
00248             }
00249         }
00250
00251         /// <summary>
00252         /// Allow for one operation at a time
00253         /// </summary>
00254         private void UpdateReadButtonStates()
00255         {
00256             if (IsPerformingRead())
00257             {
00258                 ReadButton.IsEnabled = false;
00259                 ReadCancelButton.IsEnabled = true;
00260                 ReadTimeoutButton.IsEnabled = false;
00261                 ReadTimeoutInputValue.IsEnabled = false;
00262             }
00263             else
00264             {
00265                 ReadButton.IsEnabled = true;
00266                 ReadCancelButton.IsEnabled = false;
00267                 ReadTimeoutButton.IsEnabled = true;
00268                 ReadTimeoutInputValue.IsEnabled = true;
00269             }
00270         }
00271
00272         private void UpdateWriteButtonStates()
00273         {
00274             if (IsPerformingWrite())
00275             {
00276                 WriteButton.IsEnabled = false;
00277                 WriteCancelButton.IsEnabled = true;
00278                 WriteTimeoutButton.IsEnabled = false;
00279                 WriteTimeoutInputValue.IsEnabled = false;
00280                 WriteBytesInputValue.IsEnabled = false;
00281             }
00282             else
00283             {
00284                 WriteButton.IsEnabled = true;
00285                 WriteCancelButton.IsEnabled = false;
00286                 WriteTimeoutButton.IsEnabled = true;
00287                 WriteTimeoutInputValue.IsEnabled = true;
00288                 WriteBytesInputValue.IsEnabled = true;
00289             }
00290         }
00291
00292         private async Task ReadAsync(CancellationToken cancellationToken)
00293         {
00294
00295             Task<UInt32> loadAsyncTask;
00296
00297             uint ReadBufferLength = 1024;
00298
00299             // Don't start any IO if we canceled the task
00300             lock (ReadCancelLock)
00301             {
00302                 cancellationToken.ThrowIfCancellationRequested();
00303
00304                 // Cancellation Token will be used so we can stop the task operation explicitly
00305                 // The completion function should still be called so that we can properly handle a canceled task
00306                 DataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
00307                 loadAsyncTask = DataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken);
00308             }
00309
00310             UInt32 bytesRead = await loadAsyncTask;
00311             if (bytesRead > 0)
00312             {
00313                 ReadBytesTextBlock.Text += DataReaderObject.ReadString(bytesRead);
00314                 ReadBytesCounter += bytesRead;
00315                 UpdateReadBytesCounterView();
00316
00317             }
00318             rootPage.NotifyUser("Read completed - " + bytesRead.ToString() + " bytes were read", NotifyType.StatusMessage);
00319         }
00320
00321         private async Task WriteAsync(CancellationToken cancellationToken)
00322         {
00323
00324             Task<UInt32> storeAsyncTask;
00325
00326             if ((WriteBytesAvailable) && (WriteBytesInputValue.Text.Length != 0))
00327             {
00328                 char[] buffer = new char[WriteBytesInputValue.Text.Length];
00329                 WriteBytesInputValue.Text.CopyTo(0, buffer, 0, WriteBytesInputValue.Text.Length);
00330                 String InputString = new string(buffer);
00331                 DataWriteObject.WriteString(InputString);
00332                 WriteBytesInputValue.Text = "";
00333
00334                 // Don't start any IO if we canceled the task
00335                 lock (WriteCancelLock)
00336                 {
00337                     cancellationToken.ThrowIfCancellationRequested();
00338
00339                     // Cancellation Token will be used so we can stop the task operation explicitly
00340                     // The completion function should still be called so that we can properly handle a canceled task
00341                     storeAsyncTask = DataWriteObject.StoreAsync().AsTask(cancellationToken);
00342                 }
00343
00344                 UInt32 bytesWritten = await storeAsyncTask;
00345                 if (bytesWritten > 0)
00346                 {
00347                     WriteBytesTextBlock.Text += InputString.Substring(0, (int)bytesWritten) + '\n';
00348                     WriteBytesCounter += bytesWritten;
00349                     UpdateWriteBytesCounterView();
00350                 }
00351                 rootPage.NotifyUser("Write completed - " + bytesWritten.ToString() + " bytes written", NotifyType.StatusMessage);
00352             }
00353             else
00354             {
00355                 rootPage.NotifyUser("No input received to write", NotifyType.StatusMessage);
00356             }
00357
00358         }
00359
00360         /// <summary>
00361         /// It is important to be able to cancel tasks that may take a while to complete. Cancelling tasks is the only way to stop any pending IO
00362         /// operations asynchronously. If the Serial Device is closed/deleted while there are pending IOs, the destructor will cancel all pending IO
00363         /// operations.
00364         /// </summary>
00365         ///
00366
00367         private void CancelReadTask()
00368         {
00369             lock (ReadCancelLock)
00370             {
00371                 if (ReadCancellationTokenSource != null)
00372                 {
00373                     if (!ReadCancellationTokenSource.IsCancellationRequested)
00374                     {
00375                         ReadCancellationTokenSource.Cancel();
00376
00377                         // Existing IO already has a local copy of the old cancellation token so this reset won't affect it
00378                         ResetReadCancellationTokenSource();
00379                     }
00380                 }
00381             }
00382         }
00383
00384         private void CancelWriteTask()
00385         {
00386             lock (WriteCancelLock)
00387             {
00388                 if (WriteCancellationTokenSource != null)
00389                 {
00390                     if (!WriteCancellationTokenSource.IsCancellationRequested)
00391                     {
00392                         WriteCancellationTokenSource.Cancel();
00393
00394                         // Existing IO already has a local copy of the old cancellation token so this reset won't affect it
00395                         ResetWriteCancellationTokenSource();
00396                     }
00397                 }
00398             }
00399         }
00400         private void CancelAllIoTasks()
00401         {
00402             CancelReadTask();
00403             CancelWriteTask();
00404         }
00405
00406         /// <summary>
00407         /// Determines if we are reading, writing, or reading and writing.
00408         /// </summary>
00409         /// <returns>If we are doing any of the above operations, we return true; false otherwise</returns>
00410         private Boolean IsPerformingRead()
00411         {
00412             return (IsReadTaskPending);
00413         }
00414
00415         private Boolean IsPerformingWrite()
00416         {
00417             return (IsWriteTaskPending);
00418         }
00419
00420         private void ResetReadCancellationTokenSource()
00421         {
00422             // Create a new cancellation token source so that can cancel all the tokens again
00423             ReadCancellationTokenSource = new CancellationTokenSource();
00424
00425             // Hook the cancellation callback (called whenever Task.cancel is called)
00426             ReadCancellationTokenSource.Token.Register(() => NotifyReadCancelingTask());
00427         }
00428
00429         private void ResetWriteCancellationTokenSource()
00430         {
00431             // Create a new cancellation token source so that can cancel all the tokens again
00432             WriteCancellationTokenSource = new CancellationTokenSource();
00433
00434             // Hook the cancellation callback (called whenever Task.cancel is called)
00435             WriteCancellationTokenSource.Token.Register(() => NotifyWriteCancelingTask());
00436         }
00437
00438         /// <summary>
00439         /// Print a status message saying we are canceling a task and disable all buttons to prevent multiple cancel requests.
00440         /// <summary>
00441         private async void NotifyReadCancelingTask()
00442         {
00443             // Setting the dispatcher priority to high allows the UI to handle disabling of all the buttons
00444             // before any of the IO completion callbacks get a chance to modify the UI; that way this method
00445             // will never get the opportunity to overwrite UI changes made by IO callbacks
00446             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.High,
00447                 new DispatchedHandler(() =>
00448                 {
00449                     ReadButton.IsEnabled = false;
00450                     ReadCancelButton.IsEnabled = false;
00451
00452                     if (!IsNavigatedAway)
00453                     {
00454                         rootPage.NotifyUser("Canceling Read... Please wait...", NotifyType.StatusMessage);
00455                     }
00456                 }));
00457         }
00458
00459         private async void NotifyWriteCancelingTask()
00460         {
00461             // Setting the dispatcher priority to high allows the UI to handle disabling of all the buttons
00462             // before any of the IO completion callbacks get a chance to modify the UI; that way this method
00463             // will never get the opportunity to overwrite UI changes made by IO callbacks
00464             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.High,
00465                 new DispatchedHandler(() =>
00466                 {
00467                     WriteButton.IsEnabled = false;
00468                     WriteCancelButton.IsEnabled = false;
00469
00470                     if (!IsNavigatedAway)
00471                     {
00472                         rootPage.NotifyUser("Canceling Write... Please wait...", NotifyType.StatusMessage);
00473                     }
00474                 }));
00475         }
00476
00477         /// <summary>
00478         /// Notifies the UI that the operation has been cancelled
00479         /// </summary>
00480         private async void NotifyReadTaskCanceled()
00481         {
00482             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00483                 new DispatchedHandler(() =>
00484                 {
00485                     if (!IsNavigatedAway)
00486                     {
00487                         rootPage.NotifyUser("Read request has been cancelled", NotifyType.StatusMessage);
00488                     }
00489                 }));
00490         }
00491
00492         private async void NotifyWriteTaskCanceled()
00493         {
00494             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00495                 new DispatchedHandler(() =>
00496                 {
00497                     if (!IsNavigatedAway)
00498                     {
00499                         rootPage.NotifyUser("Write request has been cancelled", NotifyType.StatusMessage);
00500                     }
00501                 }));
00502         }
00503
00504         private void ReadCancelButton_Click(object sender, RoutedEventArgs e)
00505         {
00506             if (EventHandlerForDevice.Current.IsDeviceConnected)
00507             {
00508                 CancelReadTask();
00509             }
00510             else
00511             {
00512                 Utilities.NotifyDeviceNotConnected();
00513             }
00514         }
00515
00516
00517         private void WriteCancelButton_Click(object sender, RoutedEventArgs e)
00518         {
00519             if (EventHandlerForDevice.Current.IsDeviceConnected)
00520             {
00521                 CancelWriteTask();
00522             }
00523             else
00524             {
00525                 Utilities.NotifyDeviceNotConnected();
00526             }
00527         }
00528
00529         private void WriteBytesInputValue_TextChanged(object sender, TextChangedEventArgs e)
00530         {
00531             if (WriteBytesAvailable == false)
00532             {
00533                 WriteBytesInputValue.Text = "";
00534             }
00535             WriteBytesAvailable = true;
00536         }
00537
00538         private void WriteBytesInputValue_GotFocus(object sender, RoutedEventArgs e)
00539         {
00540             if (WriteBytesAvailable == false)
00541             {
00542                 WriteBytesInputValue.Text = "";
00543             }
00544         }
00545     }
00546 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cs/SlowInputStream.cs Source File

  • HttpClient
  • cs

SlowInputStream.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.IO;
00015 using System.Linq;
00016 using System.Runtime.InteropServices.WindowsRuntime;
00017 using System.Text;
00018 using System.Threading.Tasks;
00019 using Windows.Foundation;
00020 using Windows.Storage.Streams;
00021
00022 namespace SDKTemplate
00023 {
00024     class SlowInputStream : IInputStream
00025     {
00026         uint length;
00027         uint position;
00028
00029         public SlowInputStream(uint length)
00030         {
00031             this.length = length;
00032             position = 0;
00033         }
00034
00035         public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
00036         {
00037             return AsyncInfo.Run<IBuffer, uint>(async (cancellationToken, progress) =>
00038             {
00039                 if (length - position < count)
00040                 {
00041                     count = length - position;
00042                 }
00043
00044                 byte[] data = new byte[count];
00045                 for (uint i = 0; i < count; i++)
00046                 {
00047                     data[i] = 64;
00048                 }
00049
00050                 // Introduce a 1 second delay.
00051                 await Task.Delay(1000);
00052
00053                 position += count;
00054                 progress.Report(count);
00055
00056                 return data.AsBuffer();
00057             });
00058         }
00059
00060         public void Dispose()
00061         {
00062         }
00063     }
00064 }
Generated on Fri Nov 15 2024 22:20:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cppwinrt/Scenario2_MultiFile.h Source File

  • FilePicker
  • cppwinrt

Scenario2_MultiFile.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_MultiFile.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario2_MultiFile : Scenario2_MultiFileT<Scenario2_MultiFile>
00020     {
00021         Scenario2_MultiFile();
00022         fire_and_forget PickFilesButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00023
00024     private:
00025         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00026     };
00027 }
00028
00029 namespace winrt::SDKTemplate::factory_implementation
00030 {
00031     struct Scenario2_MultiFile : Scenario2_MultiFileT<Scenario2_MultiFile, implementation::Scenario2_MultiFile>
00032     {
00033     };
00034 }
Generated on Fri Nov 15 2024 22:19:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cs/Scenario4_NumberParsing.xaml.cs Source File

  • NumberFormatting
  • cs

Scenario4_NumberParsing.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Text;
00013 using Windows.Globalization.NumberFormatting;
00014 using Windows.System.UserProfile;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class Scenario4_NumberParsing : Page
00021     {
00022         public Scenario4_NumberParsing()
00023         {
00024             this.InitializeComponent();
00025         }
00026
00027         /// <summary>
00028         /// This is the click handler for the 'Display' button.
00029         /// </summary>
00030         /// <param name="sender"></param>
00031         /// <param name="e"></param>
00032         private void Display_Click(object sender, RoutedEventArgs e)
00033         {
00034             // This scenario uses the Windows.Globalization.NumberFormatting.DecimalFormatter,
00035             // Windows.Globalization.NumberFormatting.CurrencyFormatter and
00036             // Windows.Globalization.NumberFormatting.PercentFormatter classes to format and parse a number
00037             // percentage or currency.
00038
00039             // Keep results of the scenario in a StringBuilder
00040             StringBuilder results = new StringBuilder();
00041
00042             // Define percent formatters.
00043             PercentFormatter percentFormat = new PercentFormatter();
00044             PercentFormatter percentFormatJP = new PercentFormatter(new string[] { "ja" }, "ZZ");
00045             PercentFormatter percentFormatFR = new PercentFormatter(new string[] { "fr-FR" }, "ZZ");
00046
00047             // Define decimal formatters.
00048             DecimalFormatter decimalFormat = new DecimalFormatter();
00049             decimalFormat.IsGrouped = true;
00050             DecimalFormatter decimalFormatJP = new DecimalFormatter(new string[] { "ja" }, "ZZ");
00051             decimalFormatJP.IsGrouped = true;
00052             DecimalFormatter decimalFormatFR = new DecimalFormatter(new string[] { "fr-FR" }, "ZZ");
00053             decimalFormatFR.IsGrouped = true;
00054
00055             // Define currency formatters
00056             string userCurrency = GlobalizationPreferences.Currencies[0];
00057             CurrencyFormatter currencyFormat = new CurrencyFormatter(userCurrency);
00058             CurrencyFormatter currencyFormatJP = new CurrencyFormatter("JPY", new string[] { "ja" }, "ZZ");
00059             CurrencyFormatter currencyFormatFR = new CurrencyFormatter("EUR", new string[] { "fr-FR" }, "ZZ");
00060
00061             // Generate numbers for parsing.
00062             double percentNumber = 0.523;
00063             double decimalNumber = 12345.67;
00064             double currencyNumber = 1234.56;
00065
00066             // Roundtrip the percent numbers by formatting and parsing.
00067             String percent1 = percentFormat.Format(percentNumber);
00068             double percent1Parsed = percentFormat.ParseDouble(percent1).Value;
00069
00070             String percent1JP = percentFormatJP.Format(percentNumber);
00071             double percent1JPParsed = percentFormatJP.ParseDouble(percent1JP).Value;
00072
00073             String percent1FR = percentFormatFR.Format(percentNumber);
00074             double percent1FRParsed = percentFormatFR.ParseDouble(percent1FR).Value;
00075
00076             // Generate the results for percent parsing.
00077             results.AppendLine("Percent parsing of " + percentNumber);
00078             results.AppendLine("Formatted for current user: " + percent1   + " Parsed as current user: " + percent1Parsed);
00079             results.AppendLine("Formatted for ja-JP: "        + percent1JP + " Parsed for ja-JP: "       + percent1JPParsed);
00080             results.AppendLine("Formatted for fr-FR: "        + percent1FR + " Parsed for fr-FR: "       + percent1FRParsed);
00081             results.AppendLine();
00082
00083             // Roundtrip the decimal numbers for formatting and parsing.
00084             String decimal1 = decimalFormat.Format(decimalNumber);
00085             double decimal1Parsed = decimalFormat.ParseDouble(decimal1).Value;
00086
00087             String decimal1JP = decimalFormatJP.Format(decimalNumber);
00088             double decimal1JPParsed = decimalFormatJP.ParseDouble(decimal1JP).Value;
00089
00090             String decimal1FR = decimalFormatFR.Format(decimalNumber);
00091             double decimal1FRParsed = decimalFormatFR.ParseDouble(decimal1FR).Value;
00092
00093             // Generate the results for decimal parsing.
00094             results.AppendLine("Decimal parsing of " + decimalNumber);
00095             results.AppendLine("Formatted for current user: " + decimal1   + " Parsed as current user: " + decimal1Parsed);
00096             results.AppendLine("Formatted for ja-JP: "        + decimal1JP + " Parsed for ja-JP: "       + decimal1JPParsed);
00097             results.AppendLine("Formatted for fr-FR: "        + decimal1FR + " Parsed for fr-FR: "       + decimal1FRParsed);
00098             results.AppendLine();
00099
00100             // Roundtrip the currency numbers for formatting and parsing.
00101             String currency1 = currencyFormat.Format(currencyNumber);
00102             double currency1Parsed = currencyFormat.ParseDouble(currency1).Value;
00103
00104             String currency1JP = currencyFormatJP.Format(currencyNumber);
00105             double currency1JPParsed = currencyFormatJP.ParseDouble(currency1JP).Value;
00106
00107             String currency1FR = currencyFormatFR.Format(currencyNumber);
00108             double currency1FRParsed = currencyFormatFR.ParseDouble(currency1FR).Value;
00109
00110             // Generate the results for decimal parsing.
00111             results.AppendLine("Currency parsing of " + currencyNumber);
00112             results.AppendLine("Formatted for current user: " + currency1   + " Parsed as current user: " + currency1Parsed);
00113             results.AppendLine("Formatted for ja-JP: "        + currency1JP + " Parsed for ja-JP: "       + currency1JPParsed);
00114             results.AppendLine("Formatted for fr-FR: "        + currency1FR + " Parsed for fr-FR: "       + currency1FRParsed);
00115             results.AppendLine();
00116
00117             // Display the results.
00118             OutputTextBlock.Text = results.ToString();
00119         }
00120     }
00121 }
Generated on Fri Nov 15 2024 22:20:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DatagramSocket/cpp/Scenario4.xaml.cpp Source File

  • DatagramSocket
  • cpp

Scenario4.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario4.xaml.cpp
00014 // Implementation of the Scenario4 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario4.xaml.h"
00019
00020 using namespace SDKTemplate;
00021 using namespace SDKTemplate::DatagramSocketSample;
00022
00023 using namespace Windows::ApplicationModel::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 Scenario4::Scenario4()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Invoked when this page is about to be displayed in a Frame.
00035 /// </summary>
00036 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037 /// property is typically used to configure the page.</param>
00038 void Scenario4::OnNavigatedTo(NavigationEventArgs^ e)
00039 {
00040     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00041     // as NotifyUser()
00042     rootPage = MainPage::Current;
00043 }
00044
00045 void Scenario4::CloseSockets_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     if (CoreApplication::Properties->HasKey("clientSocket"))
00048     {
00049         // This is the last reference to the context, so once removed the object will be deleted.
00050         // The SocketContext destructor takes care of explicitly closing the DatagramSocket instance.
00051         // (Refer to Scenario2.xamp.cpp)
00052         CoreApplication::Properties->Remove("clientSocket");
00053     }
00054
00055     if (CoreApplication::Properties->HasKey("listener"))
00056     {
00057         // This is the last reference to the context, so once removed the object will be deleted.
00058         // The ListenerContext  destructor takes care of explicitly closing the DatagramSocket instance.
00059         // (Refer to Scenario1.xamp.cpp)
00060         CoreApplication::Properties->Remove("listener");
00061     }
00062
00063     if (CoreApplication::Properties->HasKey("serverAddress"))
00064     {
00065         CoreApplication::Properties->Remove("serverAddress");
00066     }
00067
00068     rootPage->NotifyUser("Socket and listener closed", NotifyType::StatusMessage);
00069 }
Generated on Fri Nov 15 2024 22:18:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContentIndexer/cpp/Helpers.h Source File

  • ContentIndexer
  • cpp

Helpers.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005
00006 namespace SDKTemplate
00007 {
00008     inline void InitializeRevisionNumber()
00009     {
00010         // This initializes the value used throughout the sample which tracks the expected index revision number. This
00011         // value is used to check if the app's expected revision number matches the actual index revision number and is
00012         // stored in the app's local settings to allow it to persist across termination.
00013         auto localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;
00014         if (!localSettings->Values->HasKey(L"expectedIndexRevision"))
00015         {
00016             localSettings->Values->Insert(L"expectedIndexRevision", ref new Platform::Box<unsigned long long>(0));
00017         }
00018     }
00019
00020     inline void OnIndexerOperationBegin()
00021     {
00022         // Update the expected index revision number in expectation of the call that's about to be made
00023         auto localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;
00024         Platform::IBox<unsigned long long>^ revisionNumber = dynamic_cast<Platform::IBox<unsigned long long>^>(localSettings->Values->Lookup(L"expectedIndexRevision"));
00025         localSettings->Values->Insert(L"expectedIndexRevision", revisionNumber->Value + 1);
00026     }
00027
00028     inline void OnIndexerOperationComplete(Windows::Storage::Search::ContentIndexer^ indexer)
00029     {
00030         // Set the expectedIndexRevision to be the reported index revision number because the operation
00031         // has succeeded
00032         auto localSettings = Windows::Storage::ApplicationData::Current->LocalSettings;
00033         localSettings->Values->Insert(L"expectedIndexRevision", indexer->Revision);
00034     }
00035
00036     // This function takes a string or vector string property value and returns a flattened string representation of it.
00037     inline Platform::String^ StringifyProperty(Platform::Object^ property)
00038     {
00039         Platform::String^ propertyString;
00040         // We need special handling to stringify vector properties such as the Keywords property.
00041         auto vectorProperty = dynamic_cast<Platform::IBoxArray<Platform::String^>^>(property);
00042         if (vectorProperty != nullptr)
00043         {
00044             for (const auto& str : vectorProperty->Value)
00045             {
00046                 propertyString += str + L"; ";
00047             }
00048         }
00049         else
00050         {
00051             propertyString = property->ToString();
00052         }
00053         return propertyString;
00054     }
00055
00056     // This function creates an instance of the ContentIndexer and inserts three items into the index with generic Key,
00057     // Name, Keywords, and Comment properties.
00058     inline void AddItemsToIndex(Windows::Storage::Search::ContentIndexer^ indexer)
00059     {
00060         const int numberOfItemsToIndex = 3;
00061         Concurrency::task<void> addItemTasks;
00062         for (int i = 0; i < numberOfItemsToIndex; i++)
00063         {
00064             auto content = ref new Windows::Storage::Search::IndexableContent();
00065             content->Id = L"SampleKey" + i;
00066             content->Properties->Insert(Windows::Storage::SystemProperties::ItemNameDisplay, L"Sample Item Name " + i);
00067             content->Properties->Insert(Windows::Storage::SystemProperties::Keywords, L"Sample keyword " + i);
00068             content->Properties->Insert(Windows::Storage::SystemProperties::Comment, L"Sample comment " + i);
00069             OnIndexerOperationBegin();
00070             auto nextTask = Concurrency::create_task(indexer->AddAsync(content));
00071             addItemTasks = (i == 0) ? nextTask : (addItemTasks && nextTask);
00072         }
00073
00074         addItemTasks.then([indexer]()
00075         {
00076             OnIndexerOperationComplete(indexer);
00077             auto propertyKeys = ref new Platform::Collections::Vector<Platform::String^>();
00078             propertyKeys->Append(Windows::Storage::SystemProperties::ItemNameDisplay);
00079             auto query = indexer->CreateQuery(L"*", propertyKeys);
00080             return query->GetCountAsync();
00081         }).then([](unsigned int count)
00082         {
00083             MainPage::Current->NotifyUser(L"Number of items currently in the index: " + count, NotifyType::StatusMessage);
00084         });
00085     }
00086
00087     inline Platform::String^ CreateItemString(Platform::String^ itemKey,
00088                                               Platform::Collections::Vector<Platform::String^>^ propertyKeys,
00089                                               Windows::Foundation::Collections::IMapView<Platform::String^, Platform::Object^>^ properties)
00090     {
00091         Platform::String^ itemString = L"Key: " + itemKey + L"\n";
00092         for (const auto& propkey : propertyKeys)
00093         {
00094             itemString += propkey + L": " + StringifyProperty(properties->Lookup(propkey)) + L"\n";
00095         }
00096         return itemString;
00097     }
00098
00099     inline Platform::String^ HResultToString(int hr)
00100     {
00101         wchar_t hresultBuffer[11];
00102         swprintf_s(hresultBuffer, ARRAYSIZE(hresultBuffer), L"%X", hr);
00103         return ref new Platform::String(hresultBuffer);
00104     }
00105
00106     // For the purposes of this sample, the appcontent-ms files are stored in an "appcontent-ms" folder in the
00107     // install directory. These are then copied into the app's "LocalState\Indexed" folder, which exposes them
00108     // to the indexer.
00109     inline void AddAppContentFilesToIndexedFolder()
00110     {
00111         auto localFolder = Windows::Storage::ApplicationData::Current->LocalFolder;
00112         auto installDirectory = Windows::ApplicationModel::Package::Current->InstalledLocation;
00113         auto outputStrings = ref new Platform::Collections::Vector<Platform::String^>();
00114         outputStrings->Append(L"Items added to the \"Indexed\" folder:");
00115         Concurrency::create_task(installDirectory->GetFolderAsync(L"appcontent-ms")).then(
00116         [outputStrings, localFolder](Windows::Storage::StorageFolder^ appContentFolder)
00117         {
00118             return Concurrency::create_task(appContentFolder->GetFilesAsync()).then(
00119             [outputStrings, localFolder] (Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile^>^ files)
00120             {
00121                 return Concurrency::create_task(localFolder->CreateFolderAsync(L"Indexed", Windows::Storage::CreationCollisionOption::OpenIfExists)).then(
00122                 [outputStrings, files](Windows::Storage::StorageFolder^ indexedFolder)
00123                 {
00124                     std::vector<Concurrency::task<Windows::Storage::StorageFile^>> copyTasks;
00125                     for (const auto& file : files)
00126                     {
00127                         copyTasks.push_back(Concurrency::create_task(file->CopyAsync(indexedFolder, file->Name, Windows::Storage::NameCollisionOption::ReplaceExisting)));
00128                         outputStrings->Append(L"\n" + file->DisplayName + file->FileType);
00129                     }
00130                     return Concurrency::when_all(copyTasks.begin(), copyTasks.end());
00131                 });
00132             });
00133         }).then([outputStrings](std::vector<Windows::Storage::StorageFile^> files)
00134         {
00135             auto outputString = ref new Platform::String(L"");
00136             for (const auto& str : outputStrings)
00137             {
00138                 outputString += str;
00139             }
00140             MainPage::Current->NotifyUser(outputString, NotifyType::StatusMessage);
00141         });
00142     }
00143 }
Generated on Fri Nov 15 2024 22:18:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario4.xaml.cpp Source File

  • MapControl
  • cpp

Scenario4.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario4.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Devices::Geolocation;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021 using namespace Windows::UI::Xaml::Controls::Maps;
00022
00023 Scenario4::Scenario4()
00024 {
00025     InitializeComponent();
00026 }
00027
00028 void Scenario4::showSpaceNeedleButton_Click(Object^ sender, RoutedEventArgs^ e)
00029 {
00030     if (myMap->Is3DSupported)
00031     {
00032         myMap->Style = MapStyle::Aerial3DWithRoads;
00033         Geopoint^ spaceNeedleGeopoint = ref new Geopoint({ 47.6204, -122.3491 });
00034         MapScene^ spaceNeedleScene = MapScene::CreateFromLocationAndRadius(spaceNeedleGeopoint,
00035             400, /* show this many meters around */
00036             135, /* looking at it to the south east*/
00037             60 /* degrees pitch */);
00038
00039         myMap->TrySetSceneAsync(spaceNeedleScene);
00040     }
00041     else
00042     {
00043         rootPage->NotifyUser(L"3D views are not supported on this device.", NotifyType::ErrorMessage);
00044     }
00045 }
00046
00047 void Scenario4::myMap_Loaded(Object^ sender, RoutedEventArgs^ e)
00048 {
00049     myMap->Center = MainPage::SeattleGeopoint;
00050     myMap->ZoomLevel = 12;
00051 }
Generated on Fri Nov 15 2024 22:18:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomVertexShaderRenderer Member List

This is the complete list of members for CustomVertexShaderRenderer, including all inherited members.
CreateDeviceDependentResources() | CustomVertexShaderRenderer |
CreateDeviceIndependentResources() | CustomVertexShaderRenderer |
CreateWindowSizeDependentResources() | CustomVertexShaderRenderer |
CustomVertexShaderRenderer(const std::shared_ptr< DX::DeviceResources > &deviceResources) | CustomVertexShaderRenderer |
LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | CustomVertexShaderRenderer |
m_deviceResources | CustomVertexShaderRenderer | [private]
m_formatConvert | CustomVertexShaderRenderer | [private]
m_gestureRecognizer | CustomVertexShaderRenderer | [private]
m_imageSize | CustomVertexShaderRenderer | [private]
m_imageSource | CustomVertexShaderRenderer | [private]
m_isWindowClosed | CustomVertexShaderRenderer | [private]
m_skewX | CustomVertexShaderRenderer | [private]
m_skewY | CustomVertexShaderRenderer | [private]
m_timer | CustomVertexShaderRenderer | [private]
m_transformedImage | CustomVertexShaderRenderer | [private]
m_waveEffect | CustomVertexShaderRenderer | [private]
ReleaseDeviceDependentResources() | CustomVertexShaderRenderer |
Render() | CustomVertexShaderRenderer |
SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | CustomVertexShaderRenderer |
Update() | CustomVertexShaderRenderer |
UpdateImageScale(float scale) | CustomVertexShaderRenderer | [private]
UpdateManipulationState(_In_ Windows::UI::Input::ManipulationUpdatedEventArgs^args) | CustomVertexShaderRenderer |
Generated on Fri Nov 15 2024 22:23:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_ReceiveContact Member List

This is the complete list of members for Scenario2_ReceiveContact, including all inherited members.
OnNavigatedTo(NavigationEventArgs e) | Scenario2_ReceiveContact | [inline, protected]
Scenario2_ReceiveContact() | Scenario2_ReceiveContact | [inline]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cpp/Scenario1_DataEvents.xaml.h Source File

  • Accelerometer
  • cpp

Scenario1_DataEvents.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_DataEvents.xaml.h
00014 // Declaration of the Scenario1_DataEvents class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario1_DataEvents.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario1_DataEvents sealed
00030     {
00031     public:
00032         Scenario1_DataEvents();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         void ScenarioEnable();
00039         void ScenarioDisable();
00040
00041     private:
00042         SDKTemplate::MainPage^ rootPage = MainPage::Current;
00043         Windows::Devices::Sensors::Accelerometer^ accelerometer;
00044         Windows::Foundation::EventRegistrationToken visibilityToken;
00045         Windows::Foundation::EventRegistrationToken readingToken;
00046
00047         void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00048         void ReadingChanged(Windows::Devices::Sensors::Accelerometer^ sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^ e);
00049     };
00050 }
Generated on Fri Nov 15 2024 22:17:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cs/BackgroundTransfer/Scenario6_RecoverableErrors.xaml.cs Source File

  • BackgroundTransfer
  • cs
  • BackgroundTransfer

Scenario6_RecoverableErrors.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading;
00015 using System.Threading.Tasks;
00016 using Windows.Foundation;
00017 using Windows.Networking.BackgroundTransfer;
00018 using Windows.Storage;
00019 using Windows.UI.Core;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Navigation;
00023 using Windows.Web;
00024
00025 namespace SDKTemplate
00026 {
00027     public sealed partial class Scenario6_RecoverableErrors : Page
00028     {
00029         private MainPage rootPage = MainPage.Current;
00030
00031         // Scenario instance state.
00032         private DownloadOperation download = null;
00033         private CancellationTokenSource downloadCancellationTokenSource = new CancellationTokenSource();
00034
00035         public Scenario6_RecoverableErrors()
00036         {
00037             InitializeComponent();
00038         }
00039
00040         /// <summary>
00041         /// Invoked when this page is about to be displayed in a Frame.
00042         /// </summary>
00043         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00044         /// property is typically used to configure the page.</param>
00045         protected async override void OnNavigatedTo(NavigationEventArgs e)
00046         {
00047             // An application must enumerate downloads when it gets started to prevent stale downloads/uploads.
00048             // Typically this can be done in the App class by overriding OnLaunched() and checking for
00049             // "args.Kind == ActivationKind.Launch" to detect an actual app launch.
00050             // We do it here in the sample to keep the sample code consolidated.
00051             // Note that for this specific scenario we are not interested in downloads from previous instances, so
00052             // we just enumerate all downloads from previous instances and cancel them immediately.
00053             await CancelActiveDownloadsAsync();
00054         }
00055
00056         protected override void OnNavigatedFrom(NavigationEventArgs e)
00057         {
00058             downloadCancellationTokenSource.Cancel();
00059         }
00060
00061         private async Task CancelActiveDownloadsAsync()
00062         {
00063             IReadOnlyList<DownloadOperation> downloads;
00064             try
00065             {
00066                 downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
00067             }
00068             catch (Exception ex) when (IsWebException("Discovery error", ex))
00069             {
00070                 // Don't worry if the old downloads encountered web exceptions.
00071                 return;
00072             }
00073
00074             // If previous sample instances/scenarios started transfers that haven't completed yet, cancel them now
00075             // so that we can start this scenario cleanly.
00076             if (downloads.Count > 0)
00077             {
00078                 using (CancellationTokenSource canceledToken = new CancellationTokenSource())
00079                 {
00080                     canceledToken.Cancel();
00081
00082                     Task[] tasks = new Task[downloads.Count];
00083                     for (int i = 0; i < downloads.Count; i++)
00084                     {
00085                         tasks[i] = downloads[i].AttachAsync().AsTask(canceledToken.Token);
00086                     }
00087
00088                     try
00089                     {
00090                         await Task.WhenAll(tasks);
00091                     }
00092                     catch (TaskCanceledException)
00093                     {
00094                     }
00095                 }
00096
00097                 rootPage.NotifyUser($"Canceled {downloads.Count} downloads.", NotifyType.StatusMessage);
00098             }
00099         }
00100
00101         private async void OnDownloadProgress(IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> sender, DownloadOperation progress)
00102         {
00103             // We capture a snapshot of DownloadOperation.Progress because
00104             // it is is updated in real-time while the operation is ongoing.
00105             BackgroundDownloadProgress currentProgress = progress.Progress;
00106
00107             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
00108             {
00109                 // Prepare the progress message to display in the UI.
00110                 ulong percent = 100;
00111                 if (currentProgress.TotalBytesToReceive > 0)
00112                 {
00113                     percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive;
00114                 }
00115
00116                 DownloadedStatusText.Text = $"{currentProgress.Status} - {percent}% downloaded.";
00117
00118                 if (currentProgress.HasRestarted)
00119                 {
00120                     rootPage.NotifyUser("Download has restarted.", NotifyType.StatusMessage);
00121                 }
00122
00123                 if (currentProgress.Status == BackgroundTransferStatus.PausedRecoverableWebErrorStatus)
00124                 {
00125                     // The only value we put in RecoverableWebErrorStatuses is WebErrorStatus.Forbidden,
00126                     // so that will be the only value observed here.
00127                     System.Diagnostics.Debug.Assert(download.CurrentWebErrorStatus == WebErrorStatus.Forbidden);
00128
00129                     rootPage.NotifyUser("URL has expired.", NotifyType.ErrorMessage);
00130
00131                     // The URL expired. Ask the user for information so we can get a new URL.
00132                     ContentDialogResult result = await ReauthorizeDialog.ShowAsync();
00133
00134                     if (result == ContentDialogResult.Primary)
00135                     {
00136                         // For the purpose of this sample, we simply remove "?shouldExpire=yes" from the URL
00137                         // to indicate that the sample server should treat it like a new, unexpired URL.
00138                         string originalUrlString = download.RequestedUri.OriginalString;
00139                         string newUrlString = originalUrlString.Replace("?shouldExpire=yes", "");
00140
00141                         rootPage.NotifyUser("Updating URL and resuming the download.", NotifyType.StatusMessage);
00142                         download.RequestedUri = new Uri(newUrlString);
00143                         download.Resume();
00144                     }
00145                     else
00146                     {
00147                         // Cancel the download.
00148                         downloadCancellationTokenSource.Cancel();
00149                         downloadCancellationTokenSource.Dispose();
00150
00151                         // Re-create the CancellationTokenSource for future downloads.
00152                         downloadCancellationTokenSource = new CancellationTokenSource();
00153                     }
00154                 }
00155             });
00156         }
00157
00158         private async void StartDownload_Click(object sender, RoutedEventArgs e)
00159         {
00160             // Reset the output whenever a new download attempt begins.
00161             DownloadedInfoText.Text = "";
00162             DownloadedStatusText.Text = "";
00163             rootPage.NotifyUser("", NotifyType.StatusMessage);
00164
00165             Uri source;
00166             if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out source))
00167             {
00168                 rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
00169                 return;
00170             }
00171
00172             string destination = fileNameField.Text.Trim();
00173             if (string.IsNullOrWhiteSpace(destination))
00174             {
00175                 rootPage.NotifyUser("A local file name is required.", NotifyType.ErrorMessage);
00176                 return;
00177             }
00178
00179             StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
00180             StorageFile destinationFile;
00181             try
00182             {
00183                 destinationFile = await picturesLibrary.CreateFileAsync(destination, CreationCollisionOption.GenerateUniqueName);
00184             }
00185             catch (Exception ex)
00186             {
00187                 rootPage.NotifyUser($"Error while creating file: {ex.Message}", NotifyType.ErrorMessage);
00188                 return;
00189             }
00190
00191             BackgroundDownloader downloader = new BackgroundDownloader();
00192             download = downloader.CreateDownload(source, destinationFile);
00193
00194             // Opt into "random access" mode. Transfers configured this way have full support for resumable URL updates.
00195             // If the timestamp or file size of the updated URL is different from that of the previous URL, the download
00196             // will restart from scratch. Otherwise, the transfer will resume from the same position using the new URL.
00197             //
00198             // Due to OS limitations, downloads that don't opt into "random access" mode will always restart from scratch
00199             // whenever their URL is updated.
00200             download.IsRandomAccessRequired = true;
00201
00202             if (configureRecoverableErrorsCheckBox.IsChecked.Value)
00203             {
00204                 // Declare HTTP 403 (WebErrorStatus.Forbidden) as a recoverable error.
00205                 download.RecoverableWebErrorStatuses.Add(WebErrorStatus.Forbidden);
00206             }
00207
00208             DownloadedInfoText.Text = $"Downloading to {destinationFile.Name}, {download.Guid}";
00209
00210             // Start the download and wait for it to complete.
00211             await HandleDownloadAsync();
00212         }
00213
00214         private async Task HandleDownloadAsync()
00215         {
00216             try
00217             {
00218                 startDownloadButton.IsEnabled = false;
00219                 IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> downloadOperation = download.StartAsync();
00220                 downloadOperation.Progress += OnDownloadProgress;
00221                 await downloadOperation.AsTask(downloadCancellationTokenSource.Token);
00222
00223                 rootPage.NotifyUser("Download completed successfully", NotifyType.StatusMessage);
00224             }
00225             catch (Exception ex) when (IsWebException("Execution error", ex))
00226             {
00227             }
00228             catch (TaskCanceledException)
00229             {
00230                 // Download was canceled.
00231             }
00232             finally
00233             {
00234                 download = null;
00235                 startDownloadButton.IsEnabled = true;
00236             }
00237         }
00238
00239         private bool IsWebException(string title, Exception ex)
00240         {
00241             WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
00242             bool result = (error != WebErrorStatus.Unknown);
00243             string message = result ? error.ToString() : ex.Message;
00244             if (download == null)
00245             {
00246                 rootPage.NotifyUser($"{title}: {message}", NotifyType.ErrorMessage);
00247             }
00248             else
00249             {
00250                 rootPage.NotifyUser($"{download.Guid} - {title}: {message}", NotifyType.ErrorMessage);
00251             }
00252
00253             return result;
00254         }
00255     }
00256 }
Generated on Fri Nov 15 2024 22:18:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DataReaderWriter/cs/SampleConfiguration.cs Source File

  • DataReaderWriter
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System.Collections.Generic;
00012 using Windows.UI.Xaml.Controls;
00013 using System;
00014
00015 namespace SDKTemplate
00016 {
00017     public partial class MainPage : Page
00018     {
00019         // Change the string below to reflect the name of your sample.
00020         // This is used on the main page as the title of the sample.
00021         public const string FEATURE_NAME = "DataReader/Writer Sample";
00022
00023         // Change the array below to reflect the name of your scenarios.
00024         // This will be used to populate the list of scenarios on the main page with
00025         // which the user will choose the specific scenario that they are interested in.
00026         // These should be in the form: "Navigating to a web page".
00027         // The code in MainPage will take care of turning this into: "1) Navigating to a web page"
00028         List<Scenario> scenarios = new List<Scenario>
00029         {
00030             new Scenario() { Title = "Read and write simple structured data.", ClassType = typeof(WriteReadStream) },
00031             new Scenario() { Title = "Dump file contents using ReadBytes().", ClassType = typeof(ReadBytes) }
00032         };
00033     }
00034
00035     public class Scenario
00036     {
00037         public string Title { get; set; }
00038
00039         public Type ClassType { get; set; }
00040
00041         public override string ToString()
00042         {
00043             return Title;
00044         }
00045     }
00046 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MidiDeviceWatcher Member List

This is the complete list of members for MidiDeviceWatcher, including all inherited members.
coreDispatcher | MidiDeviceWatcher | [private]
deviceInformationCollection | MidiDeviceWatcher | [private]
deviceWatcher | MidiDeviceWatcher | [private]
DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args) | MidiDeviceWatcher | [inline, private]
DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object args) | MidiDeviceWatcher | [inline, private]
DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args) | MidiDeviceWatcher | [inline, private]
DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args) | MidiDeviceWatcher | [inline, private]
enumerationCompleted | MidiDeviceWatcher | [private]
GetDeviceInformationCollection() | MidiDeviceWatcher | [inline, private]
MidiDeviceWatcher(string midiSelectorString, CoreDispatcher dispatcher, ListBox portListBox) | MidiDeviceWatcher | [inline, private]
midiSelector | MidiDeviceWatcher | [private]
portList | MidiDeviceWatcher | [private]
Start() | MidiDeviceWatcher | [inline, private]
Stop() | MidiDeviceWatcher | [inline, private]
UpdateDevices() | MidiDeviceWatcher | [inline, private]
~MidiDeviceWatcher() | MidiDeviceWatcher | [inline, private]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DGradientMesh/cpp/DeviceResources.cpp Source File

  • D2DGradientMesh
  • cpp

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "DeviceResources.h"
00010
00011 #include "DirectXHelper.h"
00012 #include <windows.ui.xaml.media.dxinterop.h>
00013
00014 using namespace D2D1;
00015 using namespace DirectX;
00016 using namespace Microsoft::WRL;
00017 using namespace Windows::Graphics::Display;
00018 using namespace Windows::UI::Core;
00019 using namespace Windows::UI::Xaml::Controls;
00020 using namespace Platform;
00021
00022 // Constants used to calculate screen rotations
00023 namespace ScreenRotation
00024 {
00025     // 0-degree Z-rotation
00026     static const XMFLOAT4X4 Rotation0(
00027         1.0f, 0.0f, 0.0f, 0.0f,
00028         0.0f, 1.0f, 0.0f, 0.0f,
00029         0.0f, 0.0f, 1.0f, 0.0f,
00030         0.0f, 0.0f, 0.0f, 1.0f
00031         );
00032
00033     // 90-degree Z-rotation
00034     static const XMFLOAT4X4 Rotation90(
00035         0.0f, 1.0f, 0.0f, 0.0f,
00036         -1.0f, 0.0f, 0.0f, 0.0f,
00037         0.0f, 0.0f, 1.0f, 0.0f,
00038         0.0f, 0.0f, 0.0f, 1.0f
00039         );
00040
00041     // 180-degree Z-rotation
00042     static const XMFLOAT4X4 Rotation180(
00043         -1.0f, 0.0f, 0.0f, 0.0f,
00044         0.0f, -1.0f, 0.0f, 0.0f,
00045         0.0f, 0.0f, 1.0f, 0.0f,
00046         0.0f, 0.0f, 0.0f, 1.0f
00047         );
00048
00049     // 270-degree Z-rotation
00050     static const XMFLOAT4X4 Rotation270(
00051         0.0f, -1.0f, 0.0f, 0.0f,
00052         1.0f, 0.0f, 0.0f, 0.0f,
00053         0.0f, 0.0f, 1.0f, 0.0f,
00054         0.0f, 0.0f, 0.0f, 1.0f
00055         );
00056 };
00057
00058 // Constructor for DeviceResources.
00059 DX::DeviceResources::DeviceResources() :
00060     m_d3dFeatureLevel(D3D_FEATURE_LEVEL_9_1),
00061     m_d3dRenderTargetSize(),
00062     m_outputSize(),
00063     m_logicalSize(),
00064     m_nativeOrientation(DisplayOrientations::None),
00065     m_currentOrientation(DisplayOrientations::None),
00066     m_dpi(-1.0f),
00067     m_deviceNotify(nullptr)
00068 {
00069     CreateDeviceIndependentResources();
00070     CreateDeviceResources();
00071 }
00072
00073 // Configures resources that don't depend on the Direct3D device.
00074 void DX::DeviceResources::CreateDeviceIndependentResources()
00075 {
00076     // Initialize Direct2D resources.
00077     D2D1_FACTORY_OPTIONS options;
00078     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00079
00080 #if defined(_DEBUG)
00081     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00082     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00083 #endif
00084
00085     // Initialize the Direct2D Factory.
00086     DX::ThrowIfFailed(
00087         D2D1CreateFactory(
00088             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00089             __uuidof(ID2D1Factory3),
00090             &options,
00091             &m_d2dFactory
00092             )
00093         );
00094
00095     // Initialize the DirectWrite Factory.
00096     DX::ThrowIfFailed(
00097         DWriteCreateFactory(
00098             DWRITE_FACTORY_TYPE_SHARED,
00099             __uuidof(IDWriteFactory2),
00100             &m_dwriteFactory
00101             )
00102         );
00103
00104     // Initialize the Windows Imaging Component (WIC) Factory.
00105     DX::ThrowIfFailed(
00106         CoCreateInstance(
00107             CLSID_WICImagingFactory2,
00108             nullptr,
00109             CLSCTX_INPROC_SERVER,
00110             IID_PPV_ARGS(&m_wicFactory)
00111             )
00112         );
00113 }
00114
00115 // Configures the Direct3D device, and stores handles to it and the device context.
00116 void DX::DeviceResources::CreateDeviceResources()
00117 {
00118     // This flag adds support for surfaces with a different color channel ordering
00119     // than the API default. It is required for compatibility with Direct2D.
00120     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00121
00122 #if defined(_DEBUG)
00123     if (DX::SdkLayersAvailable())
00124     {
00125         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00126         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00127     }
00128 #endif
00129
00130     // This array defines the set of DirectX hardware feature levels this app will support.
00131     // Note the ordering should be preserved.
00132     // Don't forget to declare your application's minimum required feature level in its
00133     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00134     D3D_FEATURE_LEVEL featureLevels[] =
00135     {
00136         D3D_FEATURE_LEVEL_11_1,
00137         D3D_FEATURE_LEVEL_11_0,
00138         D3D_FEATURE_LEVEL_10_1,
00139         D3D_FEATURE_LEVEL_10_0,
00140         D3D_FEATURE_LEVEL_9_3,
00141         D3D_FEATURE_LEVEL_9_2,
00142         D3D_FEATURE_LEVEL_9_1
00143     };
00144
00145     // Create the Direct3D 11 API device object and a corresponding context.
00146     ComPtr<ID3D11Device> device;
00147     ComPtr<ID3D11DeviceContext> context;
00148
00149     HRESULT hr = D3D11CreateDevice(
00150         nullptr,                    // Specify nullptr to use the default adapter.
00151         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00152         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00153         creationFlags,              // Set debug and Direct2D compatibility flags.
00154         featureLevels,              // List of feature levels this app can support.
00155         ARRAYSIZE(featureLevels),   // Size of the list above.
00156         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00157         &device,                    // Returns the Direct3D device created.
00158         &m_d3dFeatureLevel,         // Returns feature level of device created.
00159         &context                    // Returns the device immediate context.
00160         );
00161
00162     if (FAILED(hr))
00163     {
00164         // If the initialization fails, fall back to the WARP device.
00165         // For more information on WARP, see:
00166         // http://go.microsoft.com/fwlink/?LinkId=286690
00167         DX::ThrowIfFailed(
00168             D3D11CreateDevice(
00169                 nullptr,
00170                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00171                 0,
00172                 creationFlags,
00173                 featureLevels,
00174                 ARRAYSIZE(featureLevels),
00175                 D3D11_SDK_VERSION,
00176                 &device,
00177                 &m_d3dFeatureLevel,
00178                 &context
00179                 )
00180             );
00181     }
00182
00183     // Store pointers to the Direct3D 11.1 API device and immediate context.
00184     DX::ThrowIfFailed(
00185         device.As(&m_d3dDevice)
00186         );
00187
00188     DX::ThrowIfFailed(
00189         context.As(&m_d3dContext)
00190         );
00191
00192     // Create the Direct2D device object and a corresponding context.
00193     ComPtr<IDXGIDevice3> dxgiDevice;
00194     DX::ThrowIfFailed(
00195         m_d3dDevice.As(&dxgiDevice)
00196         );
00197
00198     DX::ThrowIfFailed(
00199         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00200         );
00201
00202     DX::ThrowIfFailed(
00203         m_d2dDevice->CreateDeviceContext(
00204             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00205             &m_d2dContext
00206             )
00207         );
00208 }
00209
00210 // These resources need to be recreated every time the window size is changed.
00211 void DX::DeviceResources::CreateWindowSizeDependentResources()
00212 {
00213     // Clear the previous window size specific context.
00214     ID3D11RenderTargetView* nullViews [] = { nullptr };
00215     m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00216     m_d2dContext->SetTarget(nullptr);
00217     m_d2dTargetBitmap = nullptr;
00218     m_d3dContext->Flush();
00219
00220     // Calculate the necessary render target size in pixels.
00221     m_outputSize.Width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_dpi);
00222     m_outputSize.Height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_dpi);
00223
00224     // Prevent zero size DirectX content from being created.
00225     m_outputSize.Width = max(m_outputSize.Width, 1);
00226     m_outputSize.Height = max(m_outputSize.Height, 1);
00227
00228     // The width and height of the swap chain must be based on the window's
00229     // natively-oriented width and height. If the window is not in the native
00230     // orientation, the dimensions must be reversed.
00231     DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation();
00232
00233     bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270;
00234     m_d3dRenderTargetSize.Width = swapDimensions ? m_outputSize.Height : m_outputSize.Width;
00235     m_d3dRenderTargetSize.Height = swapDimensions ? m_outputSize.Width : m_outputSize.Height;
00236
00237     if (m_swapChain != nullptr)
00238     {
00239         // If the swap chain already exists, resize it.
00240         HRESULT hr = m_swapChain->ResizeBuffers(
00241             2, // Double-buffered swap chain.
00242             static_cast<UINT>(m_d3dRenderTargetSize.Width),
00243             static_cast<UINT>(m_d3dRenderTargetSize.Height),
00244             DXGI_FORMAT_B8G8R8A8_UNORM,
00245             0
00246             );
00247
00248         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00249         {
00250             // If the device was removed for any reason, a new device and swap chain will need to be created.
00251             HandleDeviceLost();
00252
00253             // Everything is set up now. Do not continue execution of this method. HandleDeviceLost will reenter this method
00254             // and correctly set up the new device.
00255             return;
00256         }
00257         else
00258         {
00259             DX::ThrowIfFailed(hr);
00260         }
00261     }
00262     else
00263     {
00264         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00265         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00266
00267         swapChainDesc.Width = static_cast<UINT>(m_d3dRenderTargetSize.Width); // Match the size of the window.
00268         swapChainDesc.Height = static_cast<UINT>(m_d3dRenderTargetSize.Height);
00269         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swap chain format.
00270         swapChainDesc.Stereo = false;
00271         swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling.
00272         swapChainDesc.SampleDesc.Quality = 0;
00273         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00274         swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency.
00275         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Runtime apps must use this SwapEffect.
00276         swapChainDesc.Flags = 0;
00277         swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE; // When using XAML interop, this value cannot be DXGI_ALPHA_MODE_PREMULTIPLIED.
00278         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00279
00280         // This sequence obtains the DXGI factory that was used to create the Direct3D device above.
00281         ComPtr<IDXGIDevice3> dxgiDevice;
00282         DX::ThrowIfFailed(
00283             m_d3dDevice.As(&dxgiDevice)
00284             );
00285
00286         ComPtr<IDXGIAdapter> dxgiAdapter;
00287         DX::ThrowIfFailed(
00288             dxgiDevice->GetAdapter(&dxgiAdapter)
00289             );
00290
00291         ComPtr<IDXGIFactory2> dxgiFactory;
00292         DX::ThrowIfFailed(
00293             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00294             );
00295
00296         DX::ThrowIfFailed(
00297             dxgiFactory->CreateSwapChainForCoreWindow(
00298                 m_d3dDevice.Get(),
00299                 reinterpret_cast<IUnknown*>(m_window.Get()),
00300                 &swapChainDesc,
00301                 nullptr,
00302                 &m_swapChain
00303                 )
00304             );
00305
00306         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00307         // ensures that the application will only render after each VSync, minimizing power consumption.
00308         DX::ThrowIfFailed(
00309             dxgiDevice->SetMaximumFrameLatency(1)
00310             );
00311     }
00312
00313     // Set the proper orientation for the swap chain, and generate 2D and
00314     // 3D matrix transformations for rendering to the rotated swap chain.
00315     // Note the rotation angle for the 2D and 3D transforms are different.
00316     // This is due to the difference in coordinate spaces.  Additionally,
00317     // the 3D matrix is specified explicitly to avoid rounding errors.
00318
00319     switch (displayRotation)
00320     {
00321     case DXGI_MODE_ROTATION_IDENTITY:
00322         m_orientationTransform2D = Matrix3x2F::Identity();
00323         m_orientationTransform3D = ScreenRotation::Rotation0;
00324         break;
00325
00326     case DXGI_MODE_ROTATION_ROTATE90:
00327         m_orientationTransform2D =
00328             Matrix3x2F::Rotation(90.0f) *
00329             Matrix3x2F::Translation(m_logicalSize.Height, 0.0f);
00330         m_orientationTransform3D = ScreenRotation::Rotation270;
00331         break;
00332
00333     case DXGI_MODE_ROTATION_ROTATE180:
00334         m_orientationTransform2D =
00335             Matrix3x2F::Rotation(180.0f) *
00336             Matrix3x2F::Translation(m_logicalSize.Width, m_logicalSize.Height);
00337         m_orientationTransform3D = ScreenRotation::Rotation180;
00338         break;
00339
00340     case DXGI_MODE_ROTATION_ROTATE270:
00341         m_orientationTransform2D =
00342             Matrix3x2F::Rotation(270.0f) *
00343             Matrix3x2F::Translation(0.0f, m_logicalSize.Width);
00344         m_orientationTransform3D = ScreenRotation::Rotation90;
00345         break;
00346
00347     default:
00348         throw ref new FailureException();
00349     }
00350
00351     DX::ThrowIfFailed(
00352         m_swapChain->SetRotation(displayRotation)
00353         );
00354
00355     // Create a Direct2D target bitmap associated with the
00356     // swap chain back buffer and set it as the current target.
00357     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00358         D2D1::BitmapProperties1(
00359             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00360             D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00361             m_dpi,
00362             m_dpi
00363             );
00364
00365     ComPtr<IDXGISurface2> dxgiBackBuffer;
00366     DX::ThrowIfFailed(
00367         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00368         );
00369
00370     DX::ThrowIfFailed(
00371         m_d2dContext->CreateBitmapFromDxgiSurface(
00372             dxgiBackBuffer.Get(),
00373             &bitmapProperties,
00374             &m_d2dTargetBitmap
00375             )
00376         );
00377
00378     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00379
00380     // Grayscale text anti-aliasing is recommended for all Windows Runtime apps.
00381     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00382 }
00383
00384 // This method is called when the CoreWindow is created (or re-created).
00385 void DX::DeviceResources::SetWindow(CoreWindow^ window)
00386 {
00387     m_window = window;
00388
00389     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00390
00391     m_logicalSize = Windows::Foundation::Size(window->Bounds.Width, window->Bounds.Height);
00392     m_nativeOrientation = currentDisplayInformation->NativeOrientation;
00393     m_currentOrientation = currentDisplayInformation->CurrentOrientation;
00394     m_dpi = currentDisplayInformation->LogicalDpi;
00395
00396     m_d2dContext->SetDpi(m_dpi, m_dpi);
00397     CreateWindowSizeDependentResources();
00398 }
00399
00400 // This method is called in the event handler for the SizeChanged event.
00401 void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize)
00402 {
00403     if (m_logicalSize != logicalSize)
00404     {
00405         m_logicalSize = logicalSize;
00406         CreateWindowSizeDependentResources();
00407     }
00408 }
00409
00410 // This method is called in the event handler for the DpiChanged event.
00411 void DX::DeviceResources::SetDpi(float dpi)
00412 {
00413     if (dpi != m_dpi)
00414     {
00415         m_dpi = dpi;
00416
00417         // When the display DPI changes, the logical size of the window (measured in Dips) also changes and needs to be updated.
00418         m_logicalSize = Windows::Foundation::Size(m_window->Bounds.Width, m_window->Bounds.Height);
00419
00420         m_d2dContext->SetDpi(m_dpi, m_dpi);
00421         CreateWindowSizeDependentResources();
00422     }
00423 }
00424
00425 // This method is called in the event handler for the OrientationChanged event.
00426 void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation)
00427 {
00428     if (m_currentOrientation != currentOrientation)
00429     {
00430         m_currentOrientation = currentOrientation;
00431         CreateWindowSizeDependentResources();
00432     }
00433 }
00434
00435 // This method is called in the event handler for the DisplayContentsInvalidated event.
00436 void DX::DeviceResources::ValidateDevice()
00437 {
00438     // The D3D Device is no longer valid if the default adapter changed since the device
00439     // was created or if the device has been removed.
00440
00441     // First, get the information for the default adapter from when the device was created.
00442
00443     ComPtr<IDXGIDevice3> dxgiDevice;
00444     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00445
00446     ComPtr<IDXGIAdapter> deviceAdapter;
00447     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00448
00449     ComPtr<IDXGIFactory2> deviceFactory;
00450     DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory)));
00451
00452     ComPtr<IDXGIAdapter1> previousDefaultAdapter;
00453     DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter));
00454
00455     DXGI_ADAPTER_DESC previousDesc;
00456     DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc));
00457
00458     // Next, get the information for the current default adapter.
00459
00460     ComPtr<IDXGIFactory2> currentFactory;
00461     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&currentFactory)));
00462
00463     ComPtr<IDXGIAdapter1> currentDefaultAdapter;
00464     DX::ThrowIfFailed(currentFactory->EnumAdapters1(0, &currentDefaultAdapter));
00465
00466     DXGI_ADAPTER_DESC currentDesc;
00467     DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(&currentDesc));
00468
00469     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00470     // a new D3D device must be created.
00471
00472     if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart ||
00473         previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart ||
00474         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00475     {
00476         // Release references to resources related to the old device.
00477         dxgiDevice = nullptr;
00478         deviceAdapter = nullptr;
00479         deviceFactory = nullptr;
00480         previousDefaultAdapter = nullptr;
00481
00482         // Create a new device and swap chain.
00483         HandleDeviceLost();
00484     }
00485 }
00486
00487 // Recreate all device resources and set them back to the current state.
00488 void DX::DeviceResources::HandleDeviceLost()
00489 {
00490     m_swapChain = nullptr;
00491
00492     if (m_deviceNotify != nullptr)
00493     {
00494         // Notify the renderers that device resources need to be released.
00495         // This ensures all references to the existing swap chain are released so that a new one can be created.
00496         m_deviceNotify->OnDeviceLost();
00497     }
00498
00499     // Create the new device and swap chain.
00500     CreateDeviceResources();
00501     m_d2dContext->SetDpi(m_dpi, m_dpi);
00502     CreateWindowSizeDependentResources();
00503
00504     if (m_deviceNotify != nullptr)
00505     {
00506         // Notify the renderers that resources can now be created again.
00507         m_deviceNotify->OnDeviceRestored();
00508     }
00509 }
00510
00511 // Register our DeviceNotify to be informed on device lost and creation.
00512 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify *deviceNotify)
00513 {
00514     m_deviceNotify = deviceNotify;
00515 }
00516
00517 // Call this method when the app suspends. It provides a hint to the driver that the app
00518 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00519 void DX::DeviceResources::Trim()
00520 {
00521     ComPtr<IDXGIDevice3> dxgiDevice;
00522     m_d3dDevice.As(&dxgiDevice);
00523
00524     dxgiDevice->Trim();
00525 }
00526
00527 // Present the contents of the swap chain to the screen.
00528 void DX::DeviceResources::Present()
00529 {
00530     // The first argument instructs DXGI to block until VSync, putting the application
00531     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00532     // frames that will never be displayed to the screen.
00533     HRESULT hr = m_swapChain->Present(1, 0);
00534
00535     // If the device was removed either by a disconnection or a driver upgrade, we
00536     // must recreate all device resources.
00537     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00538     {
00539         HandleDeviceLost();
00540     }
00541     else
00542     {
00543         DX::ThrowIfFailed(hr);
00544     }
00545 }
00546
00547 // This method determines the rotation between the display device's native Orientation and the
00548 // current display orientation.
00549 DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation()
00550 {
00551     DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
00552
00553     // Note: NativeOrientation can only be Landscape or Portrait even though
00554     // the DisplayOrientations enum has other values.
00555     switch (m_nativeOrientation)
00556     {
00557     case DisplayOrientations::Landscape:
00558         switch (m_currentOrientation)
00559         {
00560         case DisplayOrientations::Landscape:
00561             rotation = DXGI_MODE_ROTATION_IDENTITY;
00562             break;
00563
00564         case DisplayOrientations::Portrait:
00565             rotation = DXGI_MODE_ROTATION_ROTATE270;
00566             break;
00567
00568         case DisplayOrientations::LandscapeFlipped:
00569             rotation = DXGI_MODE_ROTATION_ROTATE180;
00570             break;
00571
00572         case DisplayOrientations::PortraitFlipped:
00573             rotation = DXGI_MODE_ROTATION_ROTATE90;
00574             break;
00575         }
00576         break;
00577
00578     case DisplayOrientations::Portrait:
00579         switch (m_currentOrientation)
00580         {
00581         case DisplayOrientations::Landscape:
00582             rotation = DXGI_MODE_ROTATION_ROTATE90;
00583             break;
00584
00585         case DisplayOrientations::Portrait:
00586             rotation = DXGI_MODE_ROTATION_IDENTITY;
00587             break;
00588
00589         case DisplayOrientations::LandscapeFlipped:
00590             rotation = DXGI_MODE_ROTATION_ROTATE270;
00591             break;
00592
00593         case DisplayOrientations::PortraitFlipped:
00594             rotation = DXGI_MODE_ROTATION_ROTATE180;
00595             break;
00596         }
00597         break;
00598     }
00599     return rotation;
00600 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Level Member List

This is the complete list of members for Level, including all inherited members.
Initialize(std::vector< std::shared_ptr< GameObject >> const &objects)=0 | Level | [pure virtual]
LoadState(PersistentState &state) | Level | [virtual]
m_objective | Level | [protected]
m_timeLimit | Level | [protected]
Objective() | Level |
SaveState(PersistentState &state) | Level | [virtual]
TimeLimit() | Level |
Update(float time, float elapsedTime, float timeRemaining, std::vector< std::shared_ptr< GameObject >> const &objects) | Level | [virtual]
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_LaunchUri Member List

This is the complete list of members for Scenario2_LaunchUri, including all inherited members.
Launch_Clicked(object sender, RoutedEventArgs e) | Scenario2_LaunchUri | [inline, private]
LaunchUriDefault() | Scenario2_LaunchUri | [inline, private]
LaunchUriOpenWith(object sender, RoutedEventArgs e) | Scenario2_LaunchUri | [inline, private]
LaunchUriSplitScreen() | Scenario2_LaunchUri | [inline, private]
LaunchUriWithWarning() | Scenario2_LaunchUri | [inline, private]
m_rootPage | Scenario2_LaunchUri | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_LaunchUri | [inline, protected]
rootPage | Scenario2_LaunchUri | [private]
Scenario2_LaunchUri() | Scenario2_LaunchUri | [inline]
Scenario2_LaunchUri() | Scenario2_LaunchUri | [inline]
SystemList | Scenario2_LaunchUri |
UpdateStatus(string status, NotifyType statusType) | Scenario2_LaunchUri | [inline, private]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Basic Member List

This is the complete list of members for Scenario1_Basic, including all inherited members.
CheckBoxStyle() | Scenario1_Basic | [inline]
InteractionMode() | Scenario1_Basic | [inline]
isLastKnownFullScreen | Scenario1_Basic | [private]
keyDownToken | Scenario1_Basic | [private]
m_interactionMode | Scenario1_Basic | [private]
m_propertyChanged | Scenario1_Basic | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_Basic |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_Basic |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_Basic |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_Basic |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_Basic |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_Basic |
OnWindowResize(Windows::Foundation::IInspectable const &, Windows::UI::Core::WindowSizeChangedEventArgs const &e) | Scenario1_Basic | [private]
PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const &handler) | Scenario1_Basic |
PropertyChanged(event_token const &token) noexcept | Scenario1_Basic |
ResizeView_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Basic |
RootPage_OnKeyDown(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs const &e) | Scenario1_Basic | [private]
Scenario1_Basic() | Scenario1_Basic |
Scenario1_Basic() | Scenario1_Basic |
Scenario1_Basic() | Scenario1_Basic |
SetMinimumSize_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Basic |
ShowStandardSystemOverlaysButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Basic |
ToggleFullScreenModeButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Basic |
UpdateContent() | Scenario1_Basic | [private]
UpdateContent() | Scenario1_Basic | [private]
UpdateContent() | Scenario1_Basic | [private]
UseMinimalOverlaysCheckBox_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Basic |
windowResizeToken | Scenario1_Basic | [private]
windowSizeChangedToken | Scenario1_Basic | [private]
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cpp/Scenario8_Reflow.xaml.h Source File

  • XamlCommanding
  • cpp

Scenario8_Reflow.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // Scenario8_Reflow.xaml.h
00003 // Declaration of the Scenario8_Reflow class
00004 //
00005
00006 #pragma once
00007
00008 #include "DynamicCommandBar.h"
00009 #include "Scenario8_Reflow.g.h"
00010
00011 namespace SDKTemplate
00012 {
00013     /// <summary>
00014     /// An empty page that can be used on its own or navigated to within a Frame.
00015     /// </summary>
00016     [Windows::Foundation::Metadata::WebHostHidden]
00017     public ref class Scenario8_Reflow sealed
00018     {
00019     public:
00020         Scenario8_Reflow();
00021     };
00022 }
Generated on Fri Nov 15 2024 22:22:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ProjectionViewPageInitializationData Member List

This is the complete list of members for ProjectionViewPageInitializationData, including all inherited members.
MainDispatcher | ProjectionViewPageInitializationData
MainViewId | ProjectionViewPageInitializationData
ProjectionViewPageControl | ProjectionViewPageInitializationData
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cppwinrt/Scenario1_PercentPermilleFormatting.h Source File

  • NumberFormatting
  • cppwinrt

Scenario1_PercentPermilleFormatting.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_PercentPermilleFormatting.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_PercentPermilleFormatting : Scenario1_PercentPermilleFormattingT<Scenario1_PercentPermilleFormatting>
00019     {
00020         Scenario1_PercentPermilleFormatting();
00021
00022         void Display_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario1_PercentPermilleFormatting : Scenario1_PercentPermilleFormattingT<Scenario1_PercentPermilleFormatting, implementation::Scenario1_PercentPermilleFormatting>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:20:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
App() | sealed |
Initialize(Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
Load(Platform::String^entryPoint) | sealed | [virtual]
m_deviceResources | sealed | [private]
m_gestureRecognizer | sealed | [private]
m_main | sealed | [private]
m_windowClosed | sealed | [private]
m_windowVisible | sealed | [private]
OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | sealed | [protected]
OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnDpiChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnManipulationUpdated(_In_ Windows::UI::Input::GestureRecognizer^sender, _In_ Windows::UI::Input::ManipulationUpdatedEventArgs^args) | sealed | [protected]
OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnPointerMoved(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | sealed | [protected]
OnPointerPressed(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | sealed | [protected]
OnPointerReleased(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | sealed | [protected]
OnPointerWheelChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::PointerEventArgs^args) | sealed | [protected]
OnResuming(Platform::Object^sender, Platform::Object^args) | sealed | [protected]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [protected]
OnVisibilityChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::VisibilityChangedEventArgs^args) | sealed | [protected]
OnWindowClosed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::CoreWindowEventArgs^args) | sealed | [protected]
OnWindowSizeChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::WindowSizeChangedEventArgs^args) | sealed | [protected]
Run() | sealed | [virtual]
SetWindow(Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
Uninitialize() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_SupportedTactileFeedback Member List

This is the complete list of members for Scenario2_SupportedTactileFeedback, including all inherited members.
Pointer_Entered(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::Input::PointerRoutedEventArgs const &e) | Scenario2_SupportedTactileFeedback
Pointer_Exited(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::Input::PointerRoutedEventArgs const &e) | Scenario2_SupportedTactileFeedback
Scenario2_SupportedTactileFeedback() | Scenario2_SupportedTactileFeedback
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

StringTrimmer Member List

This is the complete list of members for StringTrimmer, including all inherited members.
Trim(Platform::String^s) StringTrimmer [inline, static]
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cs/Scenario04_PostText.xaml.cs Source File

  • HttpClient
  • cs

Scenario04_PostText.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading;
00014 using System.Threading.Tasks;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018 using Windows.Web.Http;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario04_PostText : Page
00023     {
00024         MainPage rootPage = MainPage.Current;
00025
00026         private HttpClient httpClient;
00027         private CancellationTokenSource cts;
00028
00029         public Scenario04_PostText()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             httpClient = Helpers.CreateHttpClientWithPlugIn();
00037             cts = new CancellationTokenSource();
00038         }
00039
00040         protected override void OnNavigatedFrom(NavigationEventArgs e)
00041         {
00042             cts.Cancel();
00043             cts.Dispose();
00044             httpClient.Dispose();
00045         }
00046
00047         private async void Start_Click(object sender, RoutedEventArgs e)
00048         {
00049             // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00050             // valid, absolute URI, we'll notify the user about the incorrect input.
00051             Uri resourceUri = Helpers.TryParseHttpUri(AddressField.Text);
00052             if (resourceUri == null)
00053             {
00054                 rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
00055                 return;
00056             }
00057
00058             Helpers.ScenarioStarted(StartButton, CancelButton, OutputField);
00059             rootPage.NotifyUser("In progress", NotifyType.StatusMessage);
00060
00061             // This sample uses a "try" in order to support TaskCanceledException.
00062             // If you don't need to support cancellation, then the "try" is not needed.
00063             try
00064             {
00065                 HttpRequestResult result = await httpClient.TryPostAsync(resourceUri,
00066                     new HttpStringContent(RequestBodyField.Text)).AsTask(cts.Token);
00067
00068                 if (result.Succeeded)
00069                 {
00070                     await Helpers.DisplayTextResultAsync(result.ResponseMessage, OutputField, cts.Token);
00071
00072                     rootPage.NotifyUser("Completed", NotifyType.StatusMessage);
00073                 }
00074                 else
00075                 {
00076                     Helpers.DisplayWebError(rootPage, result.ExtendedError);
00077                 }
00078             }
00079             catch (TaskCanceledException)
00080             {
00081                 rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
00082             }
00083
00084             Helpers.ScenarioCompleted(StartButton, CancelButton);
00085         }
00086
00087         private void Cancel_Click(object sender, RoutedEventArgs e)
00088         {
00089             cts.Cancel();
00090             cts.Dispose();
00091
00092             // Re-create the CancellationTokenSource.
00093             cts = new CancellationTokenSource();
00094         }
00095     }
00096 }
Generated on Fri Nov 15 2024 22:19:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IControl Member List

This is the complete list of members for IControl, including all inherited members.
AddChild(const std::shared_ptr< IControl > &object)=0 | IControl | [pure virtual]
CreateDeviceDependentResources()=0 | IControl | [pure virtual]
GetBoundingBox(DirectX::BoundingOrientedBox &boundingBox)=0 | IControl | [pure virtual]
GetPosition()=0 | IControl | [pure virtual]
GetRotation()=0 | IControl | [pure virtual]
GetScale()=0 | IControl | [pure virtual]
Initialize(const std::shared_ptr< DX::DeviceResources > &deviceResources)=0 | IControl | [pure virtual]
IsEnabled()=0 | IControl | [pure virtual]
IsFocused()=0 | IControl | [pure virtual]
ReleaseDeviceDependentResources()=0 | IControl | [pure virtual]
Render()=0 | IControl | [pure virtual]
SetEnabled(const bool enabled)=0 | IControl | [pure virtual]
SetOnAirTapCallback(std::function< void()> callback)=0 | IControl | [pure virtual]
SetPosition(Windows::Foundation::Numerics::float3 pos)=0 | IControl | [pure virtual]
SetRotation(Windows::Foundation::Numerics::float3 rot)=0 | IControl | [pure virtual]
SetScale(Windows::Foundation::Numerics::float3 scale)=0 | IControl | [pure virtual]
Type()=0 | IControl | [pure virtual]
Update(const DX::StepTimer &timer, Windows::Graphics::Holographic::HolographicFrame^holographicFrame, Windows::Perception::Spatial::SpatialCoordinateSystem^currentCoordinateSystem, Windows::UI::Input::Spatial::SpatialInteractionSourceState^interactionSource)=0 | IControl | [pure virtual]
Update(const DX::StepTimer &timer, Windows::Graphics::Holographic::HolographicFrame^holographicFrame, Windows::Perception::Spatial::SpatialCoordinateSystem^currentCoordinateSystem, Windows::UI::Input::Spatial::SpatialInteractionSourceState^interactionSource, const DirectX::XMMATRIX &parentTransform)=0 | IControl | [pure virtual]
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

INetworkServer Member List

This is the complete list of members for INetworkServer, including all inherited members.
AcceptAsync() INetworkServer
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleImaging/cs/SampleConfiguration.cs Source File

  • SimpleImaging
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using SimpleImaging;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Simple imaging C# sample";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Image properties (FileProperties)", ClassType=typeof(Scenario1)},
00026             new Scenario() { Title="Image transforms/encode (BitmapDecoder)", ClassType=typeof(Scenario2)},
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProximitySensor/cpp/Scenario3_DisplayOnOff.xaml.h Source File

  • ProximitySensor
  • cpp

Scenario3_DisplayOnOff.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario3_DisplayOnOff.xaml.h
00014 // Declaration of the Scenario3_DisplayOnOff class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario3_DisplayOnOff.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario3_DisplayOnOff sealed
00030     {
00031     public:
00032         Scenario3_DisplayOnOff();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038     private:
00039         SDKTemplate::MainPage^ rootPage;
00040         Windows::Devices::Enumeration::DeviceWatcher^ watcher;
00041         Windows::Devices::Sensors::ProximitySensor^ sensor;
00042         Windows::Devices::Sensors::ProximitySensorDisplayOnOffController^ displayController;
00043
00044         void OnProximitySensorAdded(Windows::Devices::Enumeration::DeviceWatcher^ sender, Windows::Devices::Enumeration::DeviceInformation^ device);
00045         void ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046         void ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047     };
00048 }
Generated on Fri Nov 15 2024 22:21:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/SphereMesh.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

SphereMesh.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // SphereMesh:
00015 // This class derives from MeshObject and creates a ID3D11Buffer of
00016 // vertices and indices to represent a canonical sphere that is
00017 // positioned at the origin with a radius of 1.0.
00018
00019 #include "MeshObject.h"
00020
00021 class SphereMesh : public MeshObject
00022 {
00023 public:
00024     SphereMesh(_In_ winrt::com_ptr<ID3D11Device3> const& device, uint16_t segments);
00025 };
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

TransparentExchange Member List

This is the complete list of members for TransparentExchange, including all inherited members.
ApduCommand(byte cla, byte ins, byte p1, byte p2, byte[] commandData, byte?le) | ApduCommand | [inline]
ApduResponseType | ApduCommand |
CLA | ApduCommand |
CommandData | ApduCommand |
DataObjectType enum name | TransparentExchange |
GetBuffer() | ApduCommand | [inline]
INS | ApduCommand |
Le | ApduCommand |
P1 | ApduCommand |
P2 | ApduCommand |
ToString() | ApduCommand | [inline]
TransparentExchange(byte[] dataObjects) | TransparentExchange | [inline]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: KeyCredentialManager/cs/SignIn.xaml.cs Source File

  • KeyCredentialManager
  • cs

SignIn.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Security.Credentials;
00015 using Windows.Security.Cryptography;
00016 using Windows.Storage.Streams;
00017 using Windows.UI;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Media;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// The sign in form that contains username and password fields and the option to sign in
00027     /// with either Microsoft Passport or traditional username/password authentication.
00028     ///
00029     /// Right now there is no authentication of username/password except for that they are not empty -
00030     /// so any username/password combo will be accepted. However if Passport is used, it will use the
00031     /// actual Passport PIN that is set up on the machine running the sample.
00032     ///
00033     /// If an account was passed from the user select we will do one of two things
00034     ///
00035     ///     1. If the selected account used Microsoft Passport as the last sign in method, it will attempt Microsoft Passport
00036     ///         sign in first. If that is cancelled or fails, it will fall back on username/password form for sign in.
00037     ///
00038     ///     2. Else - show the username/password sign in form with username filled in based on chosen account.
00039     /// </summary>
00040     public sealed partial class SignIn : Page
00041     {
00042         private MainPage rootPage;
00043         private bool m_addingAccount = true;
00044         private Account m_account;
00045         private bool m_passportAvailable = true;
00046
00047         public SignIn()
00048         {
00049             this.InitializeComponent();
00050         }
00051
00052         /// <summary>
00053         /// The function that will be called when this frame is navigated to.
00054         ///
00055         /// Checks to see if Microsoft Passport is available and checks to see if an
00056         /// account was passed in.
00057         ///
00058         /// If an account was passed, check if it uses Microsoft Passport.
00059         /// and set the "adding user" flag so we don't add a new account
00060         /// to the list of users.
00061         /// </summary>
00062         /// <param name="e"></param>
00063         protected override async void OnNavigatedTo(NavigationEventArgs e)
00064         {
00065             rootPage = MainPage.Current;
00066             await PassportAvailableCheckAsync();
00067
00068             if (e.Parameter != null)
00069             {
00070                 m_account = (Account)e.Parameter;
00071                 textbox_Username.Text = m_account.Email;
00072                 textbox_Username.IsEnabled = false;
00073                 m_addingAccount = false;
00074
00075                 if (m_account.UsesPassport)
00076                 {
00077                     await SignInPassportAsync(true);
00078                 }
00079             }
00080         }
00081
00082         /// <summary>
00083         /// Function called when regular username/password sign in button is clicked
00084         /// </summary>
00085         /// <param name="sender"></param>
00086         /// <param name="e"></param>
00087         private async void Button_SignIn_Click(object sender, RoutedEventArgs e)
00088         {
00089             await SignInPasswordAsync(false);
00090         }
00091
00092         /// <summary>
00093         /// Function called when the "Sign In with Microsoft Passport" button is clicked.
00094         ///
00095         /// Checks if we are using an existing account and passes their preference for passport
00096         /// otherwise if this is a new account then they don't have a preference yet.
00097         /// </summary>
00098         /// <param name="sender"></param>
00099         /// <param name="e"></param>
00100         private async void Button_Passport_Click(object sender, RoutedEventArgs e)
00101         {
00102             if (m_addingAccount == false)
00103             {
00104                 await SignInPassportAsync(m_account.UsesPassport);
00105             }
00106             else
00107             {
00108                 await SignInPassportAsync(false);
00109             }
00110         }
00111
00112         /// <summary>
00113         /// Checks to see if Passport is ready to be used.
00114         ///
00115         /// Passport has dependencies on:
00116         ///     1. Having a connected MSA Account
00117         ///     2. Having a Windows PIN set up for that account on the local machine
00118         ///
00119         /// If Passport is not ready, then display how to set it up to the user and
00120         /// disable the "Sign In with Passport" button.
00121         /// </summary>
00122         private async Task PassportAvailableCheckAsync()
00123         {
00124             if (await KeyCredentialManager.IsSupportedAsync())
00125             {
00126                 button_PassportSignIn.IsEnabled = true;
00127             }
00128             else
00129             {
00130                 //
00131                 // Key credential is not enabled yet as user
00132                 // needs to connect to a MSA account and select a pin in the connecting flow.
00133                 //
00134                 grid_PassportStatus.Background = new SolidColorBrush(Color.FromArgb(255, 50, 170, 207));
00135                 textblock_PassportStatusText.Text = "Microsoft Passport is not set up.\nPlease go to Windows Settings and connect an MSA account!";
00136                 m_passportAvailable = false;
00137             }
00138         }
00139
00140         /// <summary>
00141         /// The function called when the user wants to sign in with Passport but from
00142         /// the username/password dialog.
00143         ///
00144         /// First we check if they already use Passport as their primary login method
00145         ///
00146         /// Otherwise we authenticate their username/password and then begin the Passport
00147         /// enrollment process which consists of creating a Passport key and then sending that to
00148         /// the authentication server.
00149         /// </summary>
00150         /// <param name="passportIsPrimaryLogin">Boolean representing if primary login method is Passport</param>
00151         private async Task SignInPassportAsync(bool passportIsPrimaryLogin)
00152         {
00153             if (passportIsPrimaryLogin == true)
00154             {
00155                 if (await AuthenticatePassportAsync() == true)
00156                 {
00157                     SuccessfulSignIn(m_account);
00158                     return;
00159                 }
00160             }
00161             else if (await SignInPasswordAsync(true) == true)
00162             {
00163                 if (await CreatePassportKeyAsync(textbox_Username.Text) == true)
00164                 {
00165                     bool serverAddedPassportToAccount = await AddPassportToAccountOnServer();
00166
00167                     if (serverAddedPassportToAccount == true)
00168                     {
00169                         rootPage.NotifyUser("Successfully signed in with Microsoft Passport!", NotifyType.StatusMessage);
00170                         if (m_addingAccount == true)
00171                         {
00172                             Account goodAccount = new Account() { Name = textbox_Username.Text, Email = textbox_Username.Text, UsesPassport = true };
00173                             SuccessfulSignIn(goodAccount);
00174                         }
00175                         else
00176                         {
00177                             m_account.UsesPassport = true;
00178                             SuccessfulSignIn(m_account);
00179                         }
00180                         return;
00181                     }
00182                 }
00183                 textblock_ErrorField.Text = "Sign In with Passport failed. Try later.";
00184                 button_PassportSignIn.IsEnabled = false;
00185             }
00186             textblock_ErrorField.Text = "Invalid username or password.";
00187         }
00188
00189         /// <summary>
00190         /// Method called when a user clicks on the username/password Sign In button.
00191         ///
00192         /// Will attempt to authenticate the credentials with the server and then either sign in
00193         /// or display an error to the user if applicable.
00194         /// </summary>
00195         /// <param name="calledFromPassport">Boolean representing if this method was called from the user clicking "Sign In with Microsoft Passport"</param>
00196         /// <returns>Boolean representing if signing in with password succeeded</returns>
00197         private async Task<bool> SignInPasswordAsync(bool calledFromPassport)
00198         {
00199             textblock_ErrorField.Text = "";
00200
00201             if (textbox_Username.Text.Length == 0 || passwordbox_Password.Password.Length == 0)
00202             {
00203                 textblock_ErrorField.Text = "Username/Password cannot be blank.";
00204                 return false;
00205             }
00206
00207             try
00208             {
00209                 bool signedIn = await AuthenticatePasswordCredentialsAsync();
00210
00211                 if (!signedIn)
00212                 {
00213                     textblock_ErrorField.Text = "Unable to sign you in with those credentials.";
00214                 }
00215                 else
00216                 {
00217                     // TODO: Roaming Passport settings. Make it so the server can tell us if they prefer to use Passport and upsell immediately.
00218
00219                     Account goodAccount = new Account() { Name = textbox_Username.Text, Email = textbox_Username.Text, UsesPassport = false };
00220                     if (!calledFromPassport)
00221                     {
00222                         rootPage.NotifyUser("Successfully signed in with traditional username/password!", NotifyType.StatusMessage);
00223                         SuccessfulSignIn(goodAccount);
00224                     }
00225
00226                     return true;
00227                 }
00228
00229                 return false;
00230             }
00231             catch (Exception e)
00232             {
00233                 rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage);
00234                 return false;
00235             }
00236         }
00237
00238         /// <summary>
00239         /// Authenticate user credentials with server and return result.
00240         /// </summary>
00241         /// <returns>Boolean representing if authenticating the user credentials with the server succeeded</returns>
00242         private async Task<bool> AuthenticatePasswordCredentialsAsync()
00243         {
00244             // TODO: Authenticate with server once that part is done for the sample.
00245             await Task.Delay(100);
00246
00247             return true;
00248         }
00249
00250         /// <summary>
00251         /// Attempts to get the authentication message from the Passport key for this account.
00252         ///
00253         /// This will bring up the Passport PIN dialog and prompt the user for their PIN.
00254         ///
00255         /// The authentication message will be null if signing fails.
00256         /// </summary>
00257         /// <returns>Boolean representing if authenticating Passport succeeded</returns>
00258         private async Task<bool> AuthenticatePassportAsync()
00259         {
00260             IBuffer message = CryptographicBuffer.ConvertStringToBinary("LoginAuth", BinaryStringEncoding.Utf8);
00261             IBuffer authMessage = await GetPassportAuthenticationMessageAsync(message, m_account.Email);
00262
00263             if (authMessage != null)
00264             {
00265                 return true;
00266             }
00267
00268             return false;
00269         }
00270
00271         /// <summary>
00272         /// Handles user saving for our list of users if this is a new user
00273         /// and navigates to the main content.
00274         /// </summary>
00275         /// <param name="account">The account used to sign in</param>
00276         private void SuccessfulSignIn(Account account)
00277         {
00278             // If this is an already existing account, replace the old
00279             // version of this account in the account list.
00280             if (m_addingAccount == false)
00281             {
00282                 foreach (Account a in UserSelect.accountList)
00283                 {
00284                     if (a.Email == account.Email)
00285                     {
00286                         UserSelect.accountList.Remove(a);
00287                         break;
00288                     }
00289                 }
00290             }
00291
00292             UserSelect.accountList.Add(account);
00293
00294             CleanUpUserList();
00295             this.Frame.Navigate(typeof(Content), account);
00296         }
00297
00298         /// <summary>
00299         /// Function to be called when we need to register our public key with
00300         /// the server for Microsoft Passport
00301         /// </summary>
00302         /// <returns>Boolean representing if adding the Passport login method to this account on the server succeeded</returns>
00303         private async Task<bool> AddPassportToAccountOnServer()
00304         {
00305             // TODO: Add Passport signing info to server when that part is done for the sample
00306             await Task.Delay(100);
00307
00308             return true;
00309         }
00310
00311         /// <summary>
00312         /// Uses the AccountsHelper class to save the account list before we move on from
00313         /// the sign in process
00314         /// </summary>
00315         private void CleanUpUserList()
00316         {
00317             AccountsHelper.SaveAccountList(UserSelect.accountList);
00318         }
00319
00320         /// <summary>
00321         /// Creates a Passport key on the machine using the account id passed.
00322         /// Then returns a boolean based on whether we were able to create a Passport key or not.
00323         ///
00324         /// Will also attempt to create an attestation that this key is backed by hardware on the device, but is not a requirement
00325         /// for a working key in this scenario. It is possible to not accept a key that is software-based only.
00326         /// </summary>
00327         /// <param name="accountId">The account id associated with the account that we are enrolling into Passport</param>
00328         /// <returns>Boolean representing if creating the Passport key succeeded</returns>
00329         private async Task<bool> CreatePassportKeyAsync(string accountId)
00330         {
00331             KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(accountId, KeyCredentialCreationOption.ReplaceExisting);
00332
00333             if (keyCreationResult.Status == KeyCredentialStatus.Success)
00334             {
00335                 rootPage.NotifyUser("Successfully made key", NotifyType.StatusMessage);
00336
00337                 KeyCredential userKey = keyCreationResult.Credential;
00338                 IBuffer publicKey = userKey.RetrievePublicKey();
00339                 KeyCredentialAttestationResult keyAttestationResult = await userKey.GetAttestationAsync();
00340
00341                 IBuffer keyAttestation = null;
00342                 IBuffer certificateChain = null;
00343                 bool keyAttestationIncluded = false;
00344                 bool keyAttestationCanBeRetrievedLater = false;
00345                 KeyCredentialAttestationStatus keyAttestationRetryType = 0;
00346
00347                 if (keyAttestationResult.Status == KeyCredentialAttestationStatus.Success)
00348                 {
00349                     keyAttestationIncluded = true;
00350                     keyAttestation = keyAttestationResult.AttestationBuffer;
00351                     certificateChain = keyAttestationResult.CertificateChainBuffer;
00352                     rootPage.NotifyUser("Successfully made key and attestation", NotifyType.StatusMessage);
00353                 }
00354                 else if (keyAttestationResult.Status == KeyCredentialAttestationStatus.TemporaryFailure)
00355                 {
00356                     keyAttestationRetryType = KeyCredentialAttestationStatus.TemporaryFailure;
00357                     keyAttestationCanBeRetrievedLater = true;
00358                     rootPage.NotifyUser("Successfully made key but not attestation", NotifyType.StatusMessage);
00359                 }
00360                 else if (keyAttestationResult.Status == KeyCredentialAttestationStatus.NotSupported)
00361                 {
00362                     keyAttestationRetryType = KeyCredentialAttestationStatus.NotSupported;
00363                     keyAttestationCanBeRetrievedLater = false;
00364                     rootPage.NotifyUser("Key created, but key attestation not supported", NotifyType.StatusMessage);
00365                 }
00366
00367                 // Package public key, keyAttesation if available,
00368                 // certificate chain for attestation endorsement key if available,
00369                 // status code of key attestation result: keyAttestationIncluded or
00370                 // keyAttestationCanBeRetrievedLater and keyAttestationRetryType
00371                 // and send it to application server to register the user.
00372                 bool serverAddedPassportToAccount = await AddPassportToAccountOnServer();
00373
00374                 if (serverAddedPassportToAccount == true)
00375                 {
00376                     return true;
00377                 }
00378             }
00379             else if (keyCreationResult.Status == KeyCredentialStatus.UserCanceled)
00380             {
00381                 // User cancelled the Passport enrollment process
00382             }
00383             else if (keyCreationResult.Status == KeyCredentialStatus.NotFound)
00384             {
00385                 // User needs to create PIN
00386                 textblock_PassportStatusText.Text = "Microsoft Passport is almost ready!\nPlease go to Windows Settings and set up a PIN to use it.";
00387                 grid_PassportStatus.Background = new SolidColorBrush(Color.FromArgb(255, 50, 170, 207));
00388                 button_PassportSignIn.IsEnabled = false;
00389
00390                 m_passportAvailable = false;
00391             }
00392             else
00393             {
00394                 rootPage.NotifyUser(keyCreationResult.Status.ToString(), NotifyType.ErrorMessage);
00395             }
00396
00397             return false;
00398         }
00399
00400         /// <summary>
00401         /// Attempts to sign a message using the Passport key on the system for the accountId passed.
00402         /// </summary>
00403         /// <param name="message">The message to be signed</param>
00404         /// <param name="accountId">The account id for the Passport key we are using to sign</param>
00405         /// <returns>Boolean representing if creating the Passport authentication message succeeded</returns>
00406         private async Task<IBuffer> GetPassportAuthenticationMessageAsync(IBuffer message, string accountId)
00407         {
00408             KeyCredentialRetrievalResult openKeyResult = await KeyCredentialManager.OpenAsync(accountId);
00409
00410             if (openKeyResult.Status == KeyCredentialStatus.Success)
00411             {
00412                 KeyCredential userKey = openKeyResult.Credential;
00413                 IBuffer publicKey = userKey.RetrievePublicKey();
00414
00415                 KeyCredentialOperationResult signResult = await userKey.RequestSignAsync(message);
00416
00417                 if (signResult.Status == KeyCredentialStatus.Success)
00418                 {
00419                     return signResult.Result;
00420                 }
00421                 else if (signResult.Status == KeyCredentialStatus.UserCanceled)
00422                 {
00423                     // User cancelled the Passport PIN entry.
00424                     //
00425                     // We will return null below this and the username/password
00426                     // sign in form will show.
00427                 }
00428                 else if (signResult.Status == KeyCredentialStatus.NotFound)
00429                 {
00430                     // Must recreate Passport key
00431                 }
00432                 else if (signResult.Status == KeyCredentialStatus.SecurityDeviceLocked)
00433                 {
00434                     // Can't use Passport right now, remember that hardware failed and suggest restart
00435                 }
00436                 else if (signResult.Status == KeyCredentialStatus.UnknownError)
00437                 {
00438                     // Can't use Passport right now, try again later
00439                 }
00440
00441                 return null;
00442             }
00443             else if (openKeyResult.Status == KeyCredentialStatus.NotFound)
00444             {
00445                 // Passport key lost, need to recreate it
00446                 textblock_PassportStatusText.Text = "Microsoft Passport is almost ready!\nPlease go to Windows Settings and set up a PIN to use it.";
00447                 grid_PassportStatus.Background = new SolidColorBrush(Color.FromArgb(255, 50, 170, 207));
00448                 button_PassportSignIn.IsEnabled = false;
00449
00450                 m_passportAvailable = false;
00451             }
00452             else
00453             {
00454                 // Can't use Passport right now, try again later
00455             }
00456             return null;
00457         }
00458     }
00459 }
Generated on Fri Nov 15 2024 22:20:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario9_CustomPairDevice Member List

This is the complete list of members for Scenario9_CustomPairDevice, including all inherited members.
CompleteConfirmPinTask(bool accept) | Scenario9_CustomPairDevice | [inline, private]
CompletePasswordCredential(string username=null, string password=null) | Scenario9_CustomPairDevice | [inline, private]
CompleteProvidePinTask(string pin=null) | Scenario9_CustomPairDevice | [inline, private]
confirmPinTaskSrc | Scenario9_CustomPairDevice | [private]
deviceWatcherHelper | Scenario9_CustomPairDevice | [private]
GetPasswordCredentialFromUserAsync() | Scenario9_CustomPairDevice | [inline, private]
GetPinFromUserAsync() | Scenario9_CustomPairDevice | [inline, private]
GetSelectedCeremonies() | Scenario9_CustomPairDevice | [inline, private]
GetUserConfirmationAsync(string pin) | Scenario9_CustomPairDevice | [inline, private]
HidePairingPanel() | Scenario9_CustomPairDevice | [inline, private]
noButton_Click(object sender, RoutedEventArgs e) | Scenario9_CustomPairDevice | [inline, private]
okButton_Click(object sender, RoutedEventArgs e) | Scenario9_CustomPairDevice | [inline, private]
OnDeviceListChanged(DeviceWatcher sender, string id) | Scenario9_CustomPairDevice | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario9_CustomPairDevice | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario9_CustomPairDevice | [inline, protected]
PairButton_Click(object sender, RoutedEventArgs e) | Scenario9_CustomPairDevice | [inline, private]
PairingRequestedHandler(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args) | Scenario9_CustomPairDevice | [inline, private]
providePasswordCredential | Scenario9_CustomPairDevice | [private]
providePinTaskSrc | Scenario9_CustomPairDevice | [private]
resultCollection | Scenario9_CustomPairDevice | [private]
ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario9_CustomPairDevice | [inline, private]
rootPage | Scenario9_CustomPairDevice | [private]
Scenario9_CustomPairDevice() | Scenario9_CustomPairDevice | [inline]
ShowPairingPanel(string text, DevicePairingKinds pairingKind) | Scenario9_CustomPairDevice | [inline, private]
StartWatcher() | Scenario9_CustomPairDevice | [inline, private]
StartWatcherButton_Click(object sender, RoutedEventArgs e) | Scenario9_CustomPairDevice | [inline, private]
StopWatcher() | Scenario9_CustomPairDevice | [inline, private]
StopWatcherButton_Click(object sender, RoutedEventArgs e) | Scenario9_CustomPairDevice | [inline, private]
UnpairButton_Click(object sender, RoutedEventArgs e) | Scenario9_CustomPairDevice | [inline, private]
UpdatePairingButtons() | Scenario9_CustomPairDevice | [inline, private]
verifyButton_Click(object sender, RoutedEventArgs e) | Scenario9_CustomPairDevice | [inline, private]
yesButton_Click(object sender, RoutedEventArgs e) | Scenario9_CustomPairDevice | [inline, private]
Generated on Fri Nov 15 2024 22:24:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/Scenario2StandardOptions.xaml.cpp Source File

  • Printing
  • cpp

Scenario2StandardOptions.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario2StandardOptions.xaml.h"
00005 #include "PageToPrint.xaml.h"
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace Platform;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::Graphics::Display;
00013 using namespace Windows::Graphics::Printing;
00014 using namespace Windows::UI::Xaml;
00015 using namespace Windows::UI::Xaml::Controls;
00016 using namespace Windows::UI::Xaml::Controls::Primitives;
00017 using namespace Windows::UI::Xaml::Data;
00018 using namespace Windows::UI::Xaml::Input;
00019 using namespace Windows::UI::Xaml::Media;
00020 using namespace Windows::UI::Xaml::Navigation;
00021
00022 void StandardOptionsPrintHelper::PrintTaskRequested(PrintManager^ sender, PrintTaskRequestedEventArgs^ e)
00023 {
00024     PrintTask^ printTask = e->Request->CreatePrintTask("C++ Printing SDK Sample", ref new PrintTaskSourceRequestedHandler([=](PrintTaskSourceRequestedArgs^ args)
00025     {
00026         args->SetSource(PrintDocumentSource);
00027     }));
00028
00029     // Clear the print options that are displayed beacuse adding the same one multiple times will throw an exception
00030     IVector<String^>^ displayedOptions = printTask->Options->DisplayedOptions;
00031     displayedOptions->Clear();
00032
00033     // Choose the printer options to be shown.
00034     // The order in which the options are appended determines the order in which they appear in the UI
00035     displayedOptions->Append(StandardPrintTaskOptions::Copies);
00036     displayedOptions->Append(StandardPrintTaskOptions::Orientation);
00037     displayedOptions->Append(StandardPrintTaskOptions::MediaSize);
00038     displayedOptions->Append(StandardPrintTaskOptions::Collation);
00039     displayedOptions->Append(StandardPrintTaskOptions::Duplex);
00040
00041     // Preset the default value of the printer option
00042     printTask->Options->MediaSize = PrintMediaSize::NorthAmericaLegal;
00043
00044     // Print Task event handler is invoked when the print job is completed.
00045     printTask->Completed += ref new TypedEventHandler<PrintTask^, PrintTaskCompletedEventArgs^>([=](PrintTask^ sender, PrintTaskCompletedEventArgs^ e)
00046     {
00047         // Notify the user when the print operation fails.
00048         if (e->Completion == Windows::Graphics::Printing::PrintTaskCompletion::Failed)
00049         {
00050             auto callback = ref new Windows::UI::Core::DispatchedHandler([=]()
00051             {
00052                 MainPage::Current->NotifyUser(ref new String(L"Failed to print."), NotifyType::ErrorMessage);
00053             });
00054
00055             ScenarioPage->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00056         }
00057     });
00058 }
00059
00060
00061 Scenario2StandardOptions::Scenario2StandardOptions()
00062 {
00063     InitializeComponent();
00064 }
00065
00066 void Scenario2StandardOptions::OnPrintButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00067 {
00068     printHelper->ShowPrintUIAsync();
00069 }
00070
00071 void Scenario2StandardOptions::OnNavigatedTo(NavigationEventArgs^ e)
00072 {
00073     if (PrintManager::IsSupported())
00074     {
00075         // Tell the user how to print
00076         MainPage::Current->NotifyUser("Print contract registered with customization, use the Print button to print.", NotifyType::StatusMessage);
00077     }
00078     else
00079     {
00080         // Remove the print button
00081         InvokePrintingButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00082
00083         // Inform user that Printing is not supported
00084         MainPage::Current->NotifyUser("Printing is not supported.", NotifyType::ErrorMessage);
00085
00086         // Printing-related event handlers will never be called if printing
00087         // is not supported, but it's okay to register for them anyway.
00088     }
00089
00090     // Initalize common helper class and register for printing
00091     printHelper = ref new StandardOptionsPrintHelper(this);
00092     printHelper->RegisterForPrinting();
00093
00094     // Initialize print content for this scenario
00095     printHelper->PreparePrintContent(ref new PageToPrint());
00096 }
00097
00098 void Scenario2StandardOptions::OnNavigatedFrom(NavigationEventArgs^ e)
00099 {
00100     if (printHelper)
00101     {
00102         printHelper->UnregisterForPrinting();
00103     }
00104 }
Generated on Fri Nov 15 2024 22:21:01 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NetworkConnectivity/cppwinrt/Scenario3_NetworkConnectivityChanges.h Source File

  • NetworkConnectivity
  • cppwinrt

Scenario3_NetworkConnectivityChanges.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012 #include "Scenario3_NetworkConnectivityChanges.g.h"
00013
00014 namespace winrt::SDKTemplate::implementation
00015 {
00016     struct Scenario3_NetworkConnectivityChanges : Scenario3_NetworkConnectivityChangesT<Scenario3_NetworkConnectivityChanges>
00017     {
00018         Scenario3_NetworkConnectivityChanges();
00019
00020         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00021         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00022         void RegisterUnregisterButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00023         void OptInOutComboBox_SelectionChanged(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::Controls::SelectionChangedEventArgs const&);
00024
00025     private:
00026         void UpdateButtonStates();
00027         fire_and_forget UpdateNetworkStatus();
00028         fire_and_forget OnNetworkStatusChanged(Windows::Foundation::IInspectable const&);
00029         void RegisterNetworkStatusChanged();
00030         void UnregisterNetworkStatusChanged();
00031
00032         winrt::event_token m_networkStatusChangeEventToken{};
00033         bool m_isUpdatingNetworkStatus = false;
00034         bool m_isNetworkStatusUpdatePending = false;
00035     };
00036 }
00037
00038 namespace winrt::SDKTemplate::factory_implementation
00039 {
00040     struct Scenario3_NetworkConnectivityChanges : Scenario3_NetworkConnectivityChangesT<Scenario3_NetworkConnectivityChanges, implementation::Scenario3_NetworkConnectivityChanges>
00041     {
00042     };
00043 }
Generated on Fri Nov 15 2024 22:20:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cs/SampleConfiguration.cs Source File

  • Playlists
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Media.Playlists;
00016 using Windows.Storage;
00017 using Windows.Storage.Pickers;
00018 using Windows.UI.Xaml.Controls;
00019
00020 namespace SDKTemplate
00021 {
00022     public partial class MainPage : Page
00023     {
00024         public const string FEATURE_NAME = "Playlists";
00025
00026         List<Scenario> scenarios = new List<Scenario>
00027         {
00028             new Scenario() { Title = "Create a playlist", ClassType = typeof(Scenario1_Create) },
00029             new Scenario() { Title = "Display a playlist", ClassType = typeof(Scenario2_Display) },
00030             new Scenario() { Title = "Add items to a playlist", ClassType = typeof(Scenario3_Add) },
00031             new Scenario() { Title = "Remove an item from a playlist", ClassType = typeof(Scenario4_Remove) },
00032             new Scenario() { Title = "Clear a playlist", ClassType = typeof(Scenario5_Clear) }
00033         };
00034
00035         /// <summary>
00036         /// Audio file extensions.
00037         /// </summary>
00038         public static readonly string[] audioExtensions = new string[] { ".wma", ".mp3", ".mp2", ".aac", ".adt", ".adts", ".m4a" };
00039
00040         /// <summary>
00041         /// Playlist file extensions.
00042         /// </summary>
00043         public static readonly string[] playlistExtensions = new string[] { ".m3u", ".wpl", ".zpl" };
00044
00045         /// <summary>
00046         /// Creates a FileOpenPicker for the specified extensions.
00047         /// </summary>
00048         /// <param name="extensions">File extensions to pick.</param>
00049         /// <returns>FileOpenPicker instance.</returns>
00050         public static FileOpenPicker CreateFilePicker(string[] extensions)
00051         {
00052             FileOpenPicker picker = new FileOpenPicker();
00053             picker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
00054
00055             foreach (string extension in extensions)
00056             {
00057                 picker.FileTypeFilter.Add(extension);
00058             }
00059
00060             return picker;
00061         }
00062
00063         /// <summary>
00064         /// Picks and loads a playlist.
00065         /// </summary>
00066         async public Task<Playlist> PickPlaylistAsync()
00067         {
00068             FileOpenPicker picker = CreateFilePicker(MainPage.playlistExtensions);
00069             StorageFile file = await picker.PickSingleFileAsync();
00070
00071             if (file == null)
00072             {
00073                 NotifyUser("No playlist picked.", NotifyType.ErrorMessage);
00074                 return null;
00075             }
00076
00077             try
00078             {
00079                 return await Playlist.LoadAsync(file);
00080             }
00081             catch (Exception ex)
00082             {
00083                 NotifyUser(ex.Message, NotifyType.ErrorMessage);
00084                 return null;
00085             }
00086         }
00087
00088         async public Task<bool> TrySavePlaylistAsync(Playlist playlist)
00089         {
00090             try
00091             {
00092                 await playlist.SaveAsync();
00093                 return true;
00094             }
00095             catch (Exception ex)
00096             {
00097                 NotifyUser(ex.Message, NotifyType.ErrorMessage);
00098                 return false;
00099             }
00100         }
00101     }
00102
00103     public class Scenario
00104     {
00105         public string Title { get; set; }
00106         public Type ClassType { get; set; }
00107     }
00108 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_ClientAuthentication Member List

This is the complete list of members for Scenario3_ClientAuthentication, including all inherited members.
AppendOutputLine(hstring const &value) | Scenario3_ClientAuthentication | [private]
CloseSocket() | Scenario3_ClientAuthentication | [private]
ConnectWebSocketAsync() | Scenario3_ClientAuthentication | [private]
FindCertificateFromStoreAsync() | Scenario3_ClientAuthentication | [private]
GetClientCertificateAsync() | Scenario3_ClientAuthentication | [private]
InstallClientCertificateAsync() | Scenario3_ClientAuthentication | [private]
OnClosed(Windows::Networking::Sockets::IWebSocket sender, Windows::Networking::Sockets::WebSocketClosedEventArgs e) | Scenario3_ClientAuthentication | [private]
OnConnect(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_ClientAuthentication |
OnDisconnect(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_ClientAuthentication |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario3_ClientAuthentication |
Scenario3_ClientAuthentication() | Scenario3_ClientAuthentication |
SetBusy(bool value) | Scenario3_ClientAuthentication | [private]
UpdateVisualState() | Scenario3_ClientAuthentication | [private]
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cpp/pch.cpp Source File

  • 360VideoPlayback
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/Scenario5_GetSingleDevice.xaml.h Source File

  • DeviceEnumerationAndPairing
  • cpp

Scenario5_GetSingleDevice.xaml.h

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario5_GetSingleDevice.g.h"
00006 #include "MainPage.xaml.h"
00007 #include "DisplayHelpers.h"
00008
00009 namespace SDKTemplate
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     [Windows::Foundation::Metadata::WebHostHidden]
00015     [Windows::UI::Xaml::Data::Bindable]
00016     public ref class Scenario5_GetSingleDevice sealed
00017     {
00018     public:
00019         Scenario5_GetSingleDevice();
00020
00021     protected:
00022         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00023
00024     private:
00025         void GetButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00026         void Page_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00027
00028         MainPage^ rootPage = MainPage::Current;
00029         Windows::Foundation::Collections::IObservableVector<DeviceInformationDisplay^>^ resultCollection = ref new Platform::Collections::Vector<DeviceInformationDisplay^>();
00030         Windows::Devices::Enumeration::DeviceInformationKind deviceInformationKind = Windows::Devices::Enumeration::DeviceInformationKind::Unknown;
00031     };
00032 }
Generated on Fri Nov 15 2024 22:19:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cs/Scenario8_VisitsBackgroundTask.xaml.cs Source File

  • Geolocation
  • cs

Scenario8_VisitsBackgroundTask.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.Background;
00014 using Windows.Data.Json;
00015 using Windows.Devices.Geolocation;
00016 using Windows.Storage;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario8_VisitsBackgroundTask : Page
00025     {
00026         private const string BackgroundTaskName = "SampleVisitBackgroundTask";
00027         private const string BackgroundTaskEntryPoint = "BackgroundTask.VisitBackgroundTask";
00028
00029         private IBackgroundTaskRegistration _visitTask = null;
00030
00031         // A pointer to the main page.
00032         private MainPage _rootPage = MainPage.Current;
00033
00034         public Scenario8_VisitsBackgroundTask()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         protected override void OnNavigatedTo(NavigationEventArgs e)
00040         {
00041             // See if our background task is already registered.
00042             _visitTask = MainPage.LookupBackgroundTask(BackgroundTaskName);
00043
00044             if (_visitTask != null)
00045             {
00046                 // Associate an event handler with the existing background task
00047                 _visitTask.Completed += OnCompleted;
00048
00049                 FillEventListBoxWithExistingEvents();
00050             }
00051             UpdateButtonStates();
00052         }
00053
00054         /// <summary>
00055         /// This is the click handler for the 'Register' button.
00056         /// </summary>
00057         /// <param name="sender"></param>
00058         /// <param name="e"></param>
00059         async private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
00060         {
00061             // Get permission for a background task from the user. If the user has already answered once,
00062             // this does nothing and the user must manually update their preference via Settings.
00063             BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
00064
00065             // Regardless of the answer, register the background task. If the user later enables background
00066             // execution, the background task will be ready to run.
00067             // Create a new background task builder
00068             BackgroundTaskBuilder visitTaskBuilder = new BackgroundTaskBuilder();
00069
00070             visitTaskBuilder.Name = BackgroundTaskName;
00071             visitTaskBuilder.TaskEntryPoint = BackgroundTaskEntryPoint;
00072
00073             // Create a new visit trigger
00074             var trigger = new GeovisitTrigger();
00075
00076             // Set the desired monitoring scope.
00077             // For higher granularity such as venue/building level changes, choose venue.
00078             // For lower granularity more or less in the range of zipcode level changes, choose city.
00079             // Choosing Venue here as an example.
00080             trigger.MonitoringScope = VisitMonitoringScope.Venue;
00081
00082             // Associate the trigger with the background task builder
00083             visitTaskBuilder.SetTrigger(trigger);
00084
00085             // If it is important that there is user presence and/or
00086             // internet connection when OnCompleted is called
00087             // the following could be called before calling Register()
00088             // SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable);
00089             // visitTaskBuilder.AddCondition(condition);
00090
00091             // Register the background task
00092             _visitTask = visitTaskBuilder.Register();
00093
00094             // Associate an event handler with the new background task
00095             _visitTask.Completed += OnCompleted;
00096
00097             UpdateButtonStates();
00098             MainPage.CheckBackgroundAndRequestLocationAccess();
00099         }
00100
00101         /// <summary>
00102         /// This is the click handler for the 'Unregister' button.
00103         /// </summary>
00104         /// <param name="sender"></param>
00105         /// <param name="e"></param>
00106         private void UnregisterBackgroundTask(object sender, RoutedEventArgs e)
00107         {
00108             // Unregister the background task
00109             if (null != _visitTask)
00110             {
00111                 _visitTask.Unregister(true);
00112                 _visitTask.Completed -= OnCompleted;
00113                 _visitTask = null;
00114             }
00115
00116             _rootPage.NotifyUser("Visit background task unregistered", NotifyType.StatusMessage);
00117             UpdateButtonStates();
00118         }
00119
00120         /// <summary>
00121         /// This is the callback when background event has been handled
00122         /// </summary>
00123         /// <param name="sender"></param>
00124         /// <param name="e"></param>
00125         async private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
00126         {
00127             // Update the UI with progress reported by the background task
00128             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00129             {
00130                 try
00131                 {
00132                     // Rethrow any exception that occurred in the background task.
00133                     e.CheckResult();
00134
00135                     // Update the UI with the completion status of the background task
00136                     MainPage.ReportSavedStatus();
00137                     FillEventListBoxWithExistingEvents();
00138                 }
00139                 catch (Exception ex)
00140                 {
00141                     // The background task had an error
00142                     _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
00143                 }
00144             });
00145         }
00146
00147         /// <summary>
00148         /// Update the enable state of the register/unregister buttons.
00149         /// </summary>
00150         private void UpdateButtonStates()
00151         {
00152             bool registered = (_visitTask != null);
00153             RegisterBackgroundTaskButton.IsEnabled = !registered;
00154             UnregisterBackgroundTaskButton.IsEnabled = registered;
00155         }
00156
00157         /// <summary>
00158         /// Populate events list box with entries from BackgroundVisitEventCollection.
00159         /// </summary>
00160         private void FillEventListBoxWithExistingEvents()
00161         {
00162             MainPage.FillItemsFromSavedJson(VisitBackgroundEventsListBox, "BackgroundVisitEventCollection");
00163         }
00164     }
00165 }
00166
Generated on Fri Nov 15 2024 22:19:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cppwinrt/Scenario1_InkCanvasTactileFeedback.cpp Source File

  • PenHaptics
  • cppwinrt

Scenario1_InkCanvasTactileFeedback.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_InkCanvasTactileFeedback.h"
00014 #include "Scenario1_InkCanvasTactileFeedback.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::UI::Xaml;
00019
00020 namespace winrt::SDKTemplate::implementation
00021 {
00022     Scenario1_InkCanvasTactileFeedback::Scenario1_InkCanvasTactileFeedback()
00023     {
00024         InitializeComponent();
00025     }
00026
00027     void Scenario1_InkCanvasTactileFeedback::OnSizeChanged(IInspectable const&, SizeChangedEventArgs const&)
00028     {
00029         outputGrid().Width(RootGrid().ActualWidth());
00030         outputGrid().Height(RootGrid().ActualHeight() / 2);
00031     }
00032 }
Generated on Fri Nov 15 2024 22:20:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialSound/cpp/Scenario1_OmnidirectionalSound.xaml.cpp Source File

  • SpatialSound
  • cpp

Scenario1_OmnidirectionalSound.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012
00013 #include "pch.h"
00014 #include "Scenario1_OmnidirectionalSound.xaml.h"
00015
00016 using namespace SDKTemplate;
00017
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Media;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 Scenario1_OmnidirectionalSound::Scenario1_OmnidirectionalSound() : _rootPage(MainPage::Current)
00030 {
00031     InitializeComponent();
00032     auto hr = _omnidirectionalSound.Initialize(L"assets//MonoSound.wav");
00033     if (SUCCEEDED(hr))
00034     {
00035         _timer = ref new DispatcherTimer();
00036         _timerEventToken = _timer->Tick += ref new EventHandler<Platform::Object^>(this, &Scenario1_OmnidirectionalSound::OnTimerTick);
00037         TimeSpan timespan;
00038         timespan.Duration = 10000 / 30;
00039         _timer->Interval = timespan;
00040         EnvironmentComboBox->SelectedIndex = static_cast<int>(_omnidirectionalSound.GetEnvironment());
00041         _rootPage->NotifyUser("Stopped", NotifyType::StatusMessage);
00042     }
00043     else
00044     {
00045         if (hr == E_NOTIMPL)
00046         {
00047             _rootPage->NotifyUser("HRTF API is not supported on this platform. Use X3DAudio API instead - https://code.msdn.microsoft.com/XAudio2-Win32-Samples-024b3933", NotifyType::ErrorMessage);
00048         }
00049         else
00050         {
00051             throw ref new COMException(hr);
00052         }
00053     }
00054
00055     _initialized = SUCCEEDED(hr);
00056 }
00057
00058 Scenario1_OmnidirectionalSound::~Scenario1_OmnidirectionalSound()
00059 {
00060     if (_timerEventToken.Value != 0)
00061     {
00062         _timer->Tick -= _timerEventToken;
00063     }
00064 }
00065
00066 void SDKTemplate::Scenario1_OmnidirectionalSound::PlayButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00067 {
00068     if (_initialized)
00069     {
00070         _omnidirectionalSound.Start();
00071         _timer->Start();
00072         _rootPage->NotifyUser("Playing", NotifyType::StatusMessage);
00073     }
00074 }
00075
00076 void SDKTemplate::Scenario1_OmnidirectionalSound::StopButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00077 {
00078     if (_initialized)
00079     {
00080         _omnidirectionalSound.Stop();
00081         _timer->Stop();
00082         _rootPage->NotifyUser("Stopped", NotifyType::StatusMessage);
00083     }
00084 }
00085
00086 void SDKTemplate::Scenario1_OmnidirectionalSound::OnTimerTick(Object^ sender, Object^ e)
00087 {
00088     // Update the sound position on every dispatcher timer tick.
00089     _omnidirectionalSound.OnUpdate(_angularVelocity, _height, _radius);
00090 }
00091
00092 void SDKTemplate::Scenario1_OmnidirectionalSound::RadiusSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00093 {
00094     _radius = static_cast<float>(e->NewValue);
00095 }
00096
00097 void SDKTemplate::Scenario1_OmnidirectionalSound::EnvironmentComboBox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
00098 {
00099     if (_initialized)
00100     {
00101         _omnidirectionalSound.SetEnvironment(static_cast<HrtfEnvironment>(EnvironmentComboBox->SelectedIndex));
00102     }
00103 }
00104
00105 void SDKTemplate::Scenario1_OmnidirectionalSound::RotationSpeedSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00106 {
00107     // Update angular velocity based on specified orbit time in seconds.
00108     if (_initialized)
00109     {
00110         auto milliseconds = static_cast<float>(e->NewValue) * 1000;
00111         if (milliseconds > 0)
00112         {
00113             _angularVelocity = HRTF_2PI / milliseconds;
00114         }
00115         else
00116         {
00117             _angularVelocity = 0;
00118         }
00119     }
00120 }
00121
00122 void SDKTemplate::Scenario1_OmnidirectionalSound::HeightSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00123 {
00124     _height = static_cast<float>(e->NewValue);
00125 }
Generated on Fri Nov 15 2024 22:21:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6_ClearScenario Member List

This is the complete list of members for Scenario6_ClearScenario, including all inherited members.
Clear_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario6_ClearScenario
Scenario6_ClearScenario() | Scenario6_ClearScenario
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RelayCommand Member List

This is the complete list of members for RelayCommand, including all inherited members.
canExecute | RelayCommand | [private]
CanExecute(object parameter) | RelayCommand | [inline]
CanExecuteChanged | RelayCommand |
Execute(object parameter) | RelayCommand | [inline]
execute | RelayCommand | [private]
RelayCommand(Action< object > execute) | RelayCommand | [inline]
RelayCommand(Action< object > execute, Predicate< object > canExecute) | RelayCommand | [inline]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_EnumerateTiles Member List

This is the complete list of members for Scenario3_EnumerateTiles, including all inherited members.
EnumerateSecondaryTiles_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario3_EnumerateTiles
Scenario3_EnumerateTiles() | Scenario3_EnumerateTiles
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario10.xaml.h Source File

  • MapControl
  • cpp

Scenario10.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario10.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario10 sealed
00021     {
00022     public:
00023         Scenario10();
00024     private:
00025         MainPage^ rootPage = MainPage::Current;
00026
00027         Windows::UI::Xaml::Controls::Maps::MapElementsLayer^ myLayer1;
00028         Windows::UI::Xaml::Controls::Maps::MapElementsLayer^ myLayer2;
00029         Windows::UI::Xaml::Controls::Maps::MapElementsLayer^ selectedLayer;
00030         Platform::Collections::Vector<Windows::UI::Xaml::Controls::Maps::MapLayer^>^ MapLayers =
00031             ref new Platform::Collections::Vector<Windows::UI::Xaml::Controls::Maps::MapLayer^>();
00032
00033         void MyMap_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void mapElementsLayer1Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         void mapElementsLayer2Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         void OnLayerMapElementClicked(Windows::UI::Xaml::Controls::Maps::MapElementsLayer^ sender, Windows::UI::Xaml::Controls::Maps::MapElementsLayerClickEventArgs^ args);
00037
00038         void CreateLayers();
00039         void AddLayer1();
00040         void AddLayer2();
00041         void SelectLayer(Windows::UI::Xaml::Controls::Maps::MapElementsLayer^ layer);
00042     };
00043 }
Generated on Fri Nov 15 2024 22:17:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/Scenario3.xaml.cpp Source File

  • WindowsAudioSession
  • cpp

Scenario3.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario3.xaml.cpp
00013 // Implementation of the Scenario3 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario3.xaml.h"
00018 #include <ppl.h>
00019 using namespace concurrency;
00020
00021 using namespace SDKSample;
00022 using namespace SDKSample::WASAPIAudio;
00023
00024 using namespace Platform;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Media;
00027 using namespace Windows::Storage;
00028 using namespace Windows::UI::Core;
00029 using namespace Windows::UI::Xaml;
00030 using namespace Windows::UI::Xaml::Controls;
00031 using namespace Windows::UI::Xaml::Navigation;
00032
00033
00034 Scenario3::Scenario3() :
00035     m_IsMFLoaded(false),
00036     m_ContentStream(nullptr),
00037     m_StateChangedEvent(nullptr),
00038     m_spRenderer(nullptr),
00039     m_ContentType(ContentType::ContentTypeTone),
00040     m_IsMinimumLatency(false)
00041 {
00042     InitializeComponent();
00043
00044     // Initialize MF
00045     HRESULT hr = MFStartup(MF_VERSION, MFSTARTUP_LITE);
00046     if (SUCCEEDED(hr))
00047     {
00048         m_IsMFLoaded = true;
00049     }
00050     else
00051     {
00052         ThrowIfFailed(hr);
00053     }
00054
00055     m_CoreDispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
00056
00057     // Register for Media Transport controls.  This is required to support background
00058     // audio scenarios.
00059     m_SystemMediaControls = SystemMediaTransportControls::GetForCurrentView();
00060     m_SystemMediaControlsButtonToken = m_SystemMediaControls->ButtonPressed += ref new TypedEventHandler<SystemMediaTransportControls^, SystemMediaTransportControlsButtonPressedEventArgs^>(this, &Scenario3::MediaButtonPressed);
00061     m_SystemMediaControls->IsPlayEnabled = true;
00062     m_SystemMediaControls->IsPauseEnabled = true;
00063     m_SystemMediaControls->IsStopEnabled = true;
00064
00065     // Get a string representing the Default Audio Render Device
00066     String^ deviceId = Windows::Media::Devices::MediaDevice::GetDefaultAudioRenderId(Windows::Media::Devices::AudioDeviceRole::Default);
00067
00068     // The string is empty if there is no such device.
00069     if (deviceId->IsEmpty())
00070     {
00071         ShowStatusMessage(L"No audio devices available", NotifyType::StatusMessage);
00072         return;
00073     }
00074
00075     auto PropertiesToRetrieve = ref new Platform::Collections::Vector<String^>();
00076     PropertiesToRetrieve->Append("System.Devices.AudioDevice.RawProcessingSupported");
00077
00078     // read property store to see if the device supports a RAW processing mode
00079     create_task(Windows::Devices::Enumeration::DeviceInformation::CreateFromIdAsync(deviceId, PropertiesToRetrieve)).then([this] (Windows::Devices::Enumeration::DeviceInformation^ deviceInformation)
00080     {
00081         auto obj = deviceInformation->Properties->Lookup("System.Devices.AudioDevice.RawProcessingSupported");
00082         this->m_deviceSupportsRawMode = false;
00083         if (obj)
00084         {
00085             this->m_deviceSupportsRawMode = obj->Equals(true);
00086         }
00087
00088         if (this->m_deviceSupportsRawMode)
00089         {
00090             this->toggleRawAudio->IsEnabled = true;
00091             ShowStatusMessage("Raw Supported", NotifyType::StatusMessage);
00092         }
00093         else
00094         {
00095             this->toggleRawAudio->IsEnabled = false;
00096             ShowStatusMessage("Raw Not Supported", NotifyType::StatusMessage);
00097         }
00098     });
00099 }
00100
00101 Scenario3::~Scenario3()
00102 {
00103     if (m_deviceStateChangeToken.Value != 0)
00104     {
00105         m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00106         m_StateChangedEvent = nullptr;
00107         m_deviceStateChangeToken.Value = 0;
00108     }
00109
00110     if (m_SystemMediaControls)
00111     {
00112         m_SystemMediaControls->ButtonPressed -= m_SystemMediaControlsButtonToken;
00113         m_SystemMediaControls->IsPlayEnabled = false;
00114         m_SystemMediaControls->IsPauseEnabled = false;
00115         m_SystemMediaControls->IsStopEnabled = false;
00116         m_SystemMediaControls->PlaybackStatus = MediaPlaybackStatus::Closed;
00117     }
00118
00119     // Uninitialize MF
00120     if (m_IsMFLoaded)
00121     {
00122         MFShutdown();
00123         m_IsMFLoaded = false;
00124     }
00125 }
00126
00127 /// <summary>
00128 /// Invoked when this page is about to be displayed in a Frame.
00129 /// </summary>
00130 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00131 /// property is typically used to configure the page.</param>
00132 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00133 {
00134     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00135     // as NotifyUser()
00136     rootPage = MainPage::Current;
00137     UpdateContentUI(false);
00138 }
00139
00140 /// <summary>
00141 /// Invoked when about to leave this page.
00142 /// </summary>
00143 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00144 /// property is typically used to configure the page.</param>
00145 void Scenario3::OnNavigatedFrom(NavigationEventArgs^ e)
00146 {
00147     if (nullptr != m_StateChangedEvent)
00148     {
00149         DeviceState deviceState = m_StateChangedEvent->GetState();
00150
00151         if (deviceState == DeviceState::DeviceStatePlaying)
00152         {
00153             StopDevice();
00154         }
00155     }
00156 }
00157
00158 #pragma region UI Related Code
00159 void Scenario3::ShowStatusMessage(Platform::String^ str, NotifyType messageType)
00160 {
00161     m_CoreDispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00162         [this, str, messageType]()
00163     {
00164         rootPage->NotifyUser(str, messageType);
00165     }));
00166 }
00167
00168 // Updates content controls based on selected option
00169 void Scenario3::UpdateContentUI(Platform::Boolean disableAll)
00170 {
00171     if ((nullptr != btnFilePicker) &&
00172         (nullptr != sliderFrequency))
00173     {
00174         if (disableAll)
00175         {
00176             btnFilePicker->IsEnabled = false;
00177             sliderFrequency->IsEnabled = false;
00178             radioFile->IsEnabled = false;
00179             radioTone->IsEnabled = false;
00180         }
00181         else
00182         {
00183             radioFile->IsEnabled = true;
00184             radioTone->IsEnabled = true;
00185
00186             switch (m_ContentType)
00187             {
00188             case ContentType::ContentTypeTone:
00189                 btnFilePicker->IsEnabled = false;
00190                 sliderFrequency->IsEnabled = true;
00191                 UpdateContentProps(sliderFrequency->Value.ToString() + " Hz");
00192                 break;
00193
00194             case ContentType::ContentTypeFile:
00195                 btnFilePicker->IsEnabled = true;
00196                 sliderFrequency->IsEnabled = false;
00197                 break;
00198
00199             default:
00200                 break;
00201             }
00202         }
00203     }
00204 }
00205
00206 // Updates transport controls based on current playstate
00207 void Scenario3::UpdateMediaControlUI(DeviceState deviceState)
00208 {
00209     switch (deviceState)
00210     {
00211     case DeviceState::DeviceStatePlaying:
00212         btnPlay->IsEnabled = false;
00213         btnStop->IsEnabled = true;
00214         btnPlayPause->IsEnabled = true;
00215         btnPause->IsEnabled = true;
00216         toggleMinimumLatency->IsEnabled = false;
00217         break;
00218
00219     case DeviceState::DeviceStateStopped:
00220     case DeviceState::DeviceStateInError:
00221         btnPlay->IsEnabled = true;
00222         btnStop->IsEnabled = false;
00223         btnPlayPause->IsEnabled = true;
00224         btnPause->IsEnabled = false;
00225         toggleMinimumLatency->IsEnabled = true;
00226
00227         UpdateContentUI(false);
00228         break;
00229
00230     case DeviceState::DeviceStatePaused:
00231         btnPlay->IsEnabled = true;
00232         btnStop->IsEnabled = true;
00233         btnPlayPause->IsEnabled = true;
00234         btnPause->IsEnabled = false;
00235         break;
00236
00237     case DeviceState::DeviceStateStarting:
00238     case DeviceState::DeviceStateStopping:
00239         btnPlay->IsEnabled = false;
00240         btnStop->IsEnabled = false;
00241         btnPlayPause->IsEnabled = false;
00242         btnPause->IsEnabled = false;
00243
00244         UpdateContentUI(true);
00245         break;
00246     }
00247 }
00248
00249 // Updates textbox on UI thread
00250 void Scenario3::UpdateContentProps(String^ str)
00251 {
00252     String^ text = str;
00253
00254     if (nullptr != txtContentProps)
00255     {
00256         // The event handler may be invoked on a background thread, so use the Dispatcher to invoke the UI-related code on the UI thread.
00257         txtContentProps->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00258             [this, text]()
00259         {
00260             Windows::UI::Xaml::Media::SolidColorBrush ^brush;
00261             txtContentProps->Text = text;
00262
00263             if (("" == text) && (m_ContentType == ContentType::ContentTypeFile))
00264             {
00265                 brush = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::ColorHelper::FromArgb(0xCC, 0xFF, 0x00, 0x00));
00266             }
00267             else
00268             {
00269                 brush = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::ColorHelper::FromArgb(0xFF, 0xFF, 0xFF, 0xFF));
00270             }
00271
00272             txtContentProps->Background = brush;
00273         }));
00274     }
00275 }
00276
00277 #pragma endregion
00278
00279 #pragma region UI Event Handlers
00280 void Scenario3::sliderFrequency_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00281 {
00282     Slider^ s = safe_cast<Slider^>(sender) ;
00283     if (s != nullptr)
00284     {
00285         UpdateContentProps(s->Value.ToString() + " Hz");
00286     }
00287 }
00288
00289 void Scenario3::sliderVolume_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00290 {
00291     Slider^ s = safe_cast<Slider^>(sender) ;
00292     if (s != nullptr)
00293     {
00294         OnSetVolume(static_cast<UINT32>(s->Value));
00295     }
00296 }
00297
00298 void Scenario3::radioTone_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00299 {
00300     m_ContentType = ContentType::ContentTypeTone;
00301     UpdateContentProps("");
00302     m_ContentStream = nullptr;
00303     UpdateContentUI(false);
00304 }
00305
00306 void Scenario3::radioFile_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00307 {
00308     m_ContentType = ContentType::ContentTypeFile;
00309     UpdateContentProps("");
00310     m_ContentStream = nullptr;
00311     UpdateContentUI(false);
00312 }
00313
00314 void Scenario3::btnPlay_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00315 {
00316     StartDevice();
00317 }
00318
00319 void Scenario3::btnPause_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00320 {
00321     PauseDevice();
00322 }
00323
00324 void Scenario3::btnPlayPause_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00325 {
00326     PlayPauseToggleDevice();
00327 }
00328
00329 void Scenario3::btnStop_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00330 {
00331     StopDevice();
00332 }
00333
00334 void Scenario3::btnFilePicker_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00335 {
00336     OnPickFileAsync();
00337 }
00338
00339 #pragma endregion
00340
00341 // Event callback from WASAPI renderer for changes in device state
00342 void Scenario3::OnDeviceStateChange(Object^ sender, DeviceStateChangedEventArgs^ e)
00343 {
00344     // Update Control Buttons
00345     m_CoreDispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00346         [this, e]()
00347     {
00348         UpdateMediaControlUI(e->State);
00349     }));
00350
00351     // Handle state specific messages
00352     switch (e->State)
00353     {
00354     case DeviceState::DeviceStateInitialized:
00355         StartDevice();
00356         m_SystemMediaControls->PlaybackStatus = MediaPlaybackStatus::Closed;
00357         break;
00358
00359     case DeviceState::DeviceStatePlaying:
00360         if (m_IsMinimumLatency == true)
00361         {
00362             ShowStatusMessage("Playback Started (minimum latency)", NotifyType::StatusMessage);
00363         }
00364         else
00365         {
00366             ShowStatusMessage("Playback Started (normal latency)", NotifyType::StatusMessage);
00367         }
00368         m_SystemMediaControls->PlaybackStatus = MediaPlaybackStatus::Playing;
00369         break;
00370
00371     case DeviceState::DeviceStatePaused:
00372         ShowStatusMessage("Playback Paused", NotifyType::StatusMessage);
00373         m_SystemMediaControls->PlaybackStatus = MediaPlaybackStatus::Paused;
00374         break;
00375
00376     case DeviceState::DeviceStateStopped:
00377         m_spRenderer = nullptr;
00378
00379         if (m_deviceStateChangeToken.Value != 0)
00380         {
00381             m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00382             m_StateChangedEvent = nullptr;
00383             m_deviceStateChangeToken.Value = 0;
00384         }
00385
00386         ShowStatusMessage("Playback Stopped", NotifyType::StatusMessage);
00387         m_SystemMediaControls->PlaybackStatus = MediaPlaybackStatus::Stopped;
00388         break;
00389
00390     case DeviceState::DeviceStateInError:
00391         HRESULT hr = e->hr;
00392
00393         if (m_deviceStateChangeToken.Value != 0)
00394         {
00395             m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00396             m_StateChangedEvent = nullptr;
00397             m_deviceStateChangeToken.Value = 0;
00398         }
00399
00400         m_spRenderer = nullptr;
00401
00402         m_SystemMediaControls->PlaybackStatus = MediaPlaybackStatus::Closed;
00403
00404         wchar_t hrVal[11];
00405         swprintf_s(hrVal, 11, L"0x%08x\0", hr);
00406         String^ strHRVal = ref new String(hrVal);
00407
00408         String^ strMessage = "";
00409
00410         // Specifically handle a couple of known errors
00411         switch (hr)
00412         {
00413         case AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE:
00414             strMessage = "ERROR: Endpoint Does Not Support HW Offload (" + strHRVal + ")";
00415             ShowStatusMessage(strMessage, NotifyType::ErrorMessage);
00416             break;
00417
00418         case AUDCLNT_E_RESOURCES_INVALIDATED:
00419             strMessage = "ERROR: Endpoint Lost Access To Resources (" + strHRVal + ")";
00420             ShowStatusMessage(strMessage, NotifyType::ErrorMessage);
00421             break;
00422
00423         default:
00424             strMessage = "ERROR: " + strHRVal + " has occurred.";
00425             ShowStatusMessage(strMessage, NotifyType::ErrorMessage);
00426         }
00427     }
00428 }
00429
00430 //
00431 //  OnPickFileAsync()
00432 //
00433 //  File chooser for MF Source playback.  Retrieves a pointer to IRandomAccessStream
00434 //
00435 void Scenario3::OnPickFileAsync()
00436 {
00437     Pickers::FileOpenPicker^ filePicker = ref new Pickers::FileOpenPicker();
00438     filePicker->ViewMode = Pickers::PickerViewMode::List;
00439     filePicker->SuggestedStartLocation = Pickers::PickerLocationId::MusicLibrary;
00440     filePicker->FileTypeFilter->Append(".wav");
00441     filePicker->FileTypeFilter->Append(".mp3");
00442     filePicker->FileTypeFilter->Append(".wma");
00443
00444     concurrency::create_task(filePicker->PickSingleFileAsync()).then(
00445         [this](Windows::Storage::StorageFile^ file)
00446     {
00447         if (nullptr != file)
00448         {
00449             // Open the stream
00450             concurrency::create_task(file->OpenAsync(FileAccessMode::Read)).then(
00451                 [this, file](IRandomAccessStream^ stream)
00452             {
00453                 if (stream != nullptr)
00454                 {
00455                     m_ContentStream = stream;
00456                     UpdateContentProps(file->Path);
00457                 }
00458             });
00459         }
00460     });
00461 }
00462
00463 //
00464 //  OnSetVolume()
00465 //
00466 //  Updates the session volume
00467 //
00468 void Scenario3::OnSetVolume(UINT32 volume)
00469 {
00470     if (m_spRenderer)
00471     {
00472         // Updates the Session volume on the AudioClient
00473         m_spRenderer->SetVolumeOnSession(volume);
00474     }
00475 }
00476
00477 //
00478 //  InitializeDevice()
00479 //
00480 //  Sets up a new instance of the WASAPI renderer
00481 //
00482 void Scenario3::InitializeDevice()
00483 {
00484     HRESULT hr = S_OK;
00485
00486     if (!m_spRenderer)
00487     {
00488         // Create a new WASAPI instance
00489         m_spRenderer = Make<WASAPIRenderer>();
00490
00491         if (nullptr == m_spRenderer)
00492         {
00493             OnDeviceStateChange(this, ref new DeviceStateChangedEventArgs(DeviceState::DeviceStateInError, E_OUTOFMEMORY));
00494             return;
00495         }
00496
00497         // Get a pointer to the device event interface
00498         m_StateChangedEvent = m_spRenderer->GetDeviceStateEvent();
00499
00500         if (nullptr == m_StateChangedEvent)
00501         {
00502             OnDeviceStateChange(this, ref new DeviceStateChangedEventArgs(DeviceState::DeviceStateInError, E_FAIL));
00503             return;
00504         }
00505
00506         // Register for events
00507         m_deviceStateChangeToken = m_StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler(this, &Scenario3::OnDeviceStateChange);
00508
00509         // Configure user based properties
00510         DEVICEPROPS props;
00511
00512         switch (m_ContentType)
00513         {
00514         case ContentType::ContentTypeTone:
00515             props.IsTonePlayback = true;
00516             props.Frequency = static_cast<DWORD>(sliderFrequency->Value);
00517             break;
00518
00519         case ContentType::ContentTypeFile:
00520             props.IsTonePlayback = false;
00521             props.ContentStream = m_ContentStream;
00522             break;
00523         }
00524
00525         m_IsMinimumLatency = static_cast<Platform::Boolean>(toggleMinimumLatency->IsOn);
00526
00527         props.IsLowLatency = m_IsMinimumLatency;
00528         props.IsHWOffload = false;
00529         props.IsBackground = false;
00530         props.IsRawChosen = static_cast<Platform::Boolean>(toggleRawAudio->IsOn);
00531         props.IsRawSupported = m_deviceSupportsRawMode;
00532
00533         m_spRenderer->SetProperties(props);
00534
00535         // Selects the Default Audio Device
00536         m_spRenderer->InitializeAudioDeviceAsync();
00537
00538         // Set the initial volume
00539         OnSetVolume(static_cast<UINT32>(sliderVolume->Value));
00540     }
00541 }
00542
00543 //
00544 //  StartDevice()
00545 //
00546 void Scenario3::StartDevice()
00547 {
00548     if (nullptr == m_spRenderer)
00549     {
00550         // Call from main UI thread
00551         InitializeDevice();
00552     }
00553     else
00554     {
00555         // Starts a work item to begin playback, likely in the paused state
00556         m_spRenderer->StartPlaybackAsync();
00557     }
00558 }
00559
00560 //
00561 //  StopDevice()
00562 //
00563 void Scenario3::StopDevice()
00564 {
00565     if (m_spRenderer)
00566     {
00567         // Set the event to stop playback
00568         m_spRenderer->StopPlaybackAsync();
00569     }
00570 }
00571
00572 //
00573 //  PauseDevice()
00574 //
00575 void Scenario3::PauseDevice()
00576 {
00577     if (m_spRenderer)
00578     {
00579         DeviceState deviceState = m_StateChangedEvent->GetState();
00580
00581         if (deviceState == DeviceState::DeviceStatePlaying)
00582         {
00583             // Starts a work item to pause playback
00584             m_spRenderer->PausePlaybackAsync();
00585         }
00586     }
00587 }
00588
00589 //
00590 //  PlayPauseToggleDevice()
00591 //
00592 void Scenario3::PlayPauseToggleDevice()
00593 {
00594     if (m_spRenderer)
00595     {
00596         DeviceState deviceState = m_StateChangedEvent->GetState();
00597
00598         if (deviceState == DeviceState::DeviceStatePlaying)
00599         {
00600             // Starts a work item to pause playback
00601             m_spRenderer->PausePlaybackAsync();
00602         }
00603         else if (deviceState == DeviceState::DeviceStatePaused)
00604         {
00605             // Starts a work item to pause playback
00606             m_spRenderer->StartPlaybackAsync();
00607         }
00608     }
00609     else
00610     {
00611         StartDevice();
00612     }
00613 }
00614
00615 //
00616 //   MediaButtonPressed
00617 //
00618 void Scenario3::MediaButtonPressed(SystemMediaTransportControls^ sender, SystemMediaTransportControlsButtonPressedEventArgs^ e)
00619 {
00620     m_CoreDispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00621         [this, e]()
00622     {
00623         switch (e->Button)
00624         {
00625         case SystemMediaTransportControlsButton::Play:
00626             StartDevice();
00627             break;
00628
00629         case SystemMediaTransportControlsButton::Pause:
00630             PauseDevice();
00631             break;
00632
00633         case SystemMediaTransportControlsButton::Stop:
00634             StopDevice();
00635             break;
00636
00637         default:
00638             break;
00639         }
00640     }));
00641 }
Generated on Fri Nov 15 2024 22:18:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cpp/2-PointerPointProperties.xaml.h Source File

  • BasicInput
  • cpp

2-PointerPointProperties.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "2-PointerPointProperties.g.h"
00015 #include "MainPage.xaml.h"
00016 #include <map>
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class Scenario2 sealed
00025     {
00026     public:
00027         Scenario2();
00028     private:
00029         void Pointer_Entered(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e);
00030         void Pointer_Pressed(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e);
00031         void Pointer_Moved(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e);
00032         void Pointer_Released(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e);
00033         void Pointer_Wheel_Changed(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ e);
00034
00035         void CreateOrUpdatePropertyPopUp(Windows::UI::Input::PointerPoint^ currentPoint);
00036         Platform::String^ GetPointerProperties(Windows::UI::Input::PointerPoint^ currentPoint);
00037         Platform::String^ GetDeviceSpecificProperties(Windows::UI::Input::PointerPoint^ currentPoint);
00038         Platform::String^ GetMouseProperties(Windows::UI::Input::PointerPoint^ currentPoint);
00039         Platform::String^ GetTouchProperties(Windows::UI::Input::PointerPoint^ currentPoint);
00040         Platform::String^ GetPenProperties(Windows::UI::Input::PointerPoint^ currentPoint);
00041
00042         void RenderPropertyPopUp(Platform::String^ pointerProperties, Platform::String^ deviceSpecificProperties, Windows::UI::Input::PointerPoint^ currentPoint);
00043         void HidePropertyPopUp(Windows::UI::Input::PointerPoint^ currentPoint);
00044
00045         MainPage^ rootPage = MainPage::Current;
00046         std::map<unsigned int, Windows::UI::Xaml::Controls::StackPanel^> popups;
00047     };
00048 }
Generated on Fri Nov 15 2024 22:18:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraFrames/cs/SampleConfiguration.cs Source File

  • CameraFrames
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Camera Frames";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Shared mode access to color, depth and infrared frame sources", ClassType=typeof(Scenario1_DisplayDepthColorIR)},
00025             new Scenario() { Title="Find and display all media frame sources", ClassType=typeof(Scenario2_FindAvailableSourceGroups)},
00026         };
00027     }
00028
00029     public class Scenario
00030     {
00031         public string Title { get; set; }
00032         public Type ClassType { get; set; }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cs/Scenario11.xaml.cs Source File

  • MapControl
  • cs

Scenario11.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Collections.ObjectModel;
00015 using Windows.Storage;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Controls.Maps;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario11 : Page
00023     {
00024         MapElementsLayer myLayer1;
00025         MapElementsLayer myLayer2;
00026         IList<MapLayer> myLayers = new ObservableCollection<MapLayer>();
00027
00028         [Flags]
00029         enum MapIconState
00030         {
00031             None = 0,
00032             Disabled = 1,
00033             Hover = 2,
00034             Selected = 4,
00035         }
00036
00037         delegate string MapIconStateToStyleEntryState(MapIconState state);
00038
00039         static string ToDefaultStyleEntryState(MapIconState state)
00040         {
00041             if (state.HasFlag(MapIconState.Disabled))
00042             {
00043                 return MapStyleSheetEntryStates.Disabled;
00044             }
00045             else if (state.HasFlag(MapIconState.Selected))
00046             {
00047                 return MapStyleSheetEntryStates.Selected;
00048             }
00049             else if (state.HasFlag(MapIconState.Hover))
00050             {
00051                 return MapStyleSheetEntryStates.Hover;
00052             }
00053             else
00054             {
00055                 return string.Empty;
00056             }
00057         }
00058
00059         static string ToCustomStyleEntryState(MapIconState state)
00060         {
00061             if (state.HasFlag(MapIconState.Disabled))
00062             {
00063                 return "disabled";
00064             }
00065             else if (state.HasFlag(MapIconState.Selected))
00066             {
00067                 return "myNamespace.selected";
00068             }
00069             else if (state.HasFlag(MapIconState.Hover))
00070             {
00071                 return "myNamespace.hover";
00072             }
00073             else
00074             {
00075                 return string.Empty;
00076             }
00077         }
00078
00079         public Scenario11()
00080         {
00081             this.InitializeComponent();
00082         }
00083
00084         private async void MyMap_Loaded(object sender, RoutedEventArgs e)
00085         {
00086             myMap.Center = MainPage.SeattleGeopoint;
00087             myMap.ZoomLevel = 16;
00088
00089             // Specify a style sheet.  It is not strictly necessary to Combine since RoadLight is the default.
00090             var myStyleSheetFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///StyleSheets/MyCustomStates.json"));
00091             string myStyleSheetJson = await FileIO.ReadTextAsync(myStyleSheetFile);
00092
00093             myMap.StyleSheet = MapStyleSheet.Combine(new MapStyleSheet[]
00094             {
00095                 MapStyleSheet.RoadLight(),
00096                 MapStyleSheet.ParseFromJson(myStyleSheetJson)
00097             });
00098
00099             // Populate various layers containing points and connect up states to events.
00100             AddLayer1();
00101             AddLayer2();
00102
00103             // Connect the layers to the map.
00104             myMap.Layers = this.myLayers;
00105         }
00106
00107         // The elements in layer 1 receive a default style.
00108         private void AddLayer1()
00109         {
00110             this.myLayer1 = new MapElementsLayer();
00111             this.myLayer1.MapElements = MainPage.CreateCityBuildingsCollection();
00112             this.myLayer1.MapElementPointerEntered += (sender, args) => UpdateMapElementOnPointerEntered(args.MapElement, ToDefaultStyleEntryState);
00113             this.myLayer1.MapElementPointerExited += (sender, args) => UpdateMapElementOnPointerExited(args.MapElement, ToDefaultStyleEntryState);
00114             this.myLayer1.MapElementClick += (sender, args) => UpdateMapElementOnClick(args.MapElements[0], ToDefaultStyleEntryState);
00115
00116             this.myLayers.Add(this.myLayer1);
00117         }
00118
00119         // The elements in layer 2 receive a custom style.
00120         private void AddLayer2()
00121         {
00122             this.myLayer2 = new MapElementsLayer();
00123             this.myLayer2.MapElements = MainPage.CreateCityParksCollection();
00124
00125             foreach (MapElement element in myLayer2.MapElements)
00126             {
00127                 element.MapStyleSheetEntry = "myNamespace.myPoi";
00128             }
00129
00130             this.myLayer2.MapElementPointerEntered += (sender, args) => UpdateMapElementOnPointerEntered(args.MapElement, ToCustomStyleEntryState);
00131             this.myLayer2.MapElementPointerExited += (sender, args) => UpdateMapElementOnPointerExited(args.MapElement, ToCustomStyleEntryState);
00132             this.myLayer2.MapElementClick += (sender, args) => UpdateMapElementOnClick(args.MapElements[0], ToCustomStyleEntryState);
00133
00134             this.myLayers.Add(this.myLayer2);
00135         }
00136
00137         static void UpdateMapElementOnPointerEntered(MapElement mapElement, MapIconStateToStyleEntryState toStyleEntryState)
00138         {
00139             var state = (MapIconState)(mapElement.Tag ?? MapIconState.None);
00140             if (!state.HasFlag(MapIconState.Hover) && !state.HasFlag(MapIconState.Disabled))
00141             {
00142                 state |= MapIconState.Hover;
00143                 mapElement.Tag = state;
00144                 mapElement.MapStyleSheetEntryState = toStyleEntryState(state);
00145             }
00146         }
00147
00148         static void UpdateMapElementOnPointerExited(MapElement mapElement, MapIconStateToStyleEntryState toStyleEntryState)
00149         {
00150             var state = (MapIconState)(mapElement.Tag ?? MapIconState.None);
00151             if (state.HasFlag(MapIconState.Hover) && !state.HasFlag(MapIconState.Disabled))
00152             {
00153                 state &= ~MapIconState.Hover;
00154                 mapElement.Tag = state;
00155                 mapElement.MapStyleSheetEntryState = toStyleEntryState(state);
00156             }
00157         }
00158
00159         static void UpdateMapElementOnClick(MapElement mapElement, MapIconStateToStyleEntryState toStyleEntryState)
00160         {
00161             var state = (MapIconState)(mapElement.Tag ?? MapIconState.None);
00162             if (!state.HasFlag(MapIconState.Disabled))
00163             {
00164                 // Toggle Selected flag (clear bit then OR-in toggled value)
00165                 state = (state & ~MapIconState.Selected) | (state ^ MapIconState.Selected);
00166                 mapElement.Tag = state;
00167                 mapElement.MapStyleSheetEntryState = toStyleEntryState(state);
00168             }
00169         }
00170
00171         private void SetStyleSheetStateCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
00172         {
00173             // Protect against events that are raised before we are fully initialized.
00174             if (this.myLayer1 == null) return;
00175
00176             string selectedState = string.Empty;
00177             switch (setStyleSheetStateCombobox.SelectedIndex)
00178             {
00179                 case 1:
00180                     selectedState = MapStyleSheetEntryStates.Disabled;
00181                     break;
00182                 case 2:
00183                     selectedState = MapStyleSheetEntryStates.Hover;
00184                     break;
00185                 case 3:
00186                     selectedState = MapStyleSheetEntryStates.Selected;
00187                     break;
00188                 case 4:
00189                     selectedState = "myNamespace.focused";
00190                     break;
00191                 case 0:
00192                 default:
00193                     selectedState = "";
00194                     break;
00195             }
00196
00197             foreach (MapElement element in this.myLayer1.MapElements)
00198             {
00199                 element.MapStyleSheetEntry = selectedState;
00200             }
00201         }
00202     }
00203 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/Scenario6.h Source File

  • FileAccess
  • cppwinrt

Scenario6.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario6.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     /// <summary>
00020     /// Displaying file properties.
00021     /// </summary>
00022     struct Scenario6 : Scenario6T<Scenario6>
00023     {
00024         Scenario6();
00025
00026         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00027         fire_and_forget ShowPropertiesButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00028
00029     private:
00030         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00031     };
00032 }
00033
00034 namespace winrt::SDKTemplate::factory_implementation
00035 {
00036     struct Scenario6 : Scenario6T<Scenario6, implementation::Scenario6>
00037     {
00038     };
00039 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1 Member List

This is the complete list of members for Scenario1, including all inherited members.
BindToAny_Checked(object sender, RoutedEventArgs e) | Scenario1 | [inline, private]
BindToAny_Unchecked(object sender, RoutedEventArgs e) | Scenario1 | [inline, private]
localHostItems | Scenario1 | [private]
NotifyUserFromAsyncThread(string strMessage, NotifyType type) | Scenario1 | [inline, private]
OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) | Scenario1 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1 | [inline, protected]
PopulateAdapterList() | Scenario1 | [inline, private]
rootPage | Scenario1 | [private]
Scenario1() | Scenario1 | [inline]
StartListener_Click(object sender, RoutedEventArgs e) | Scenario1 | [inline, private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Scenario6_CustomFilterAddedProps.h Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

Scenario6_CustomFilterAddedProps.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario6_CustomFilterAddedProps.g.h"
00015 #include "MainPage.h"
00016 #include "DeviceWatcherHelper.h"
00017
00018 namespace winrt::SDKTemplate::implementation
00019 {
00020     struct Scenario6_CustomFilterAddedProps : Scenario6_CustomFilterAddedPropsT<Scenario6_CustomFilterAddedProps>
00021     {
00022         Scenario6_CustomFilterAddedProps();
00023
00024         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00026
00027         void StartWatcherButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void StopWatcherButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029
00030     private:
00031         SDKTemplate::MainPage rootPage{ SDKTemplate::implementation::MainPage::Current() };
00032         Windows::Foundation::Collections::IObservableVector<SDKTemplate::DeviceInformationDisplay> resultCollection = winrt::single_threaded_observable_vector<SDKTemplate::DeviceInformationDisplay>();
00033         com_ptr<DeviceWatcherHelper> deviceWatcherHelper = make_self<DeviceWatcherHelper>(resultCollection, Dispatcher());
00034
00035         void StartWatcher();
00036         void StopWatcher();
00037     };
00038 }
00039
00040 namespace winrt::SDKTemplate::factory_implementation
00041 {
00042     struct Scenario6_CustomFilterAddedProps : Scenario6_CustomFilterAddedPropsT<Scenario6_CustomFilterAddedProps, implementation::Scenario6_CustomFilterAddedProps>
00043     {
00044     };
00045 }
Generated on Fri Nov 15 2024 22:19:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
AppView() | sealed |
CreateView() | sealed | [virtual]
Initialize(Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
Load(Platform::String^entryPoint) | sealed | [virtual]
m_deviceResources | sealed | [private]
m_holographicSpace | sealed | [private]
m_main | sealed | [private]
m_windowClosed | sealed | [private]
m_windowVisible | sealed | [private]
OnKeyPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::KeyEventArgs^args) | sealed | [protected]
OnResuming(Platform::Object^sender, Platform::Object^args) | sealed | [protected]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [protected]
OnViewActivated(Windows::ApplicationModel::Core::CoreApplicationView^sender, Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | sealed | [protected]
OnVisibilityChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::VisibilityChangedEventArgs^args) | sealed | [protected]
OnWindowClosed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::CoreWindowEventArgs^args) | sealed | [protected]
Run() | sealed | [virtual]
SetWindow(Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
Uninitialize() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_FindUsers Member List

This is the complete list of members for Scenario1_FindUsers, including all inherited members.
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario1_FindUsers
Scenario1_FindUsers() | Scenario1_FindUsers
ShowProperties() | Scenario1_FindUsers
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6_ScrollIntoView Member List

This is the complete list of members for Scenario6_ScrollIntoView, including all inherited members.
_items() | Scenario6_ScrollIntoView | [inline]
items | Scenario6_ScrollIntoView | [private]
Scenario6_ScrollIntoView() | Scenario6_ScrollIntoView |
Scroll_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario6_ScrollIntoView |
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteLineSpacingModes/cpp/DWriteTextLayoutImplementation/TextLayout.cpp Source File

  • DWriteLineSpacingModes
  • cpp
  • DWriteTextLayoutImplementation

TextLayout.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "TextLayout.h"
00014 #include "DirectXHelper.h"
00015
00016 using namespace DWriteTextLayoutImplementation;
00017 using namespace Platform;
00018 using namespace Microsoft::WRL;
00019
00020 /// <summary>
00021 /// Constructor for the TextLayout class, which wraps the IDWriteTextLayout3 API
00022 /// to allow interop from XAML apps. A text layout will be created using the text,
00023 /// font and line-spacing method specified. Other methods allow the line-spacing
00024 /// parameters to be changed.
00025 /// </summary>
00026 /// <param name="text">The text to be laid out.</param>
00027 /// <param name="languageTag">The language of the text.</param>
00028 /// <param name="fontFamily">The font family to be used in the text layout. (Normal
00029 /// weight, width and style will be used.)</param>
00030 /// <param name="fontSize">The font size to be used, in DIPs.</param>
00031 /// <param name="pixelWidth">The width for the text layout. (Height will be derived.)</param>
00032 /// <param name="lineSpacingMethod">The line spacing method to be used for the layout.</param>
00033 TextLayout::TextLayout(
00034     Platform::String^ text,
00035     Platform::String^ languageTag,
00036     Platform::String^ fontFamily,
00037     float fontSize,
00038     uint32 pixelWidth,
00039     DWriteTextLayoutImplementation::LineSpacingMethod lineSpacingMethod
00040     ) :
00041     m_text(text->Data(), text->Length()),
00042     m_languageTag(languageTag->Data(), languageTag->Length()),
00043     m_fontFamily(fontFamily->Data(), fontFamily->Length()),
00044     m_fontSize(fontSize),
00045     m_pixelWidth(pixelWidth),
00046     m_pixelHeight(0)
00047 {
00048     m_lineSpacing.method = static_cast<DWRITE_LINE_SPACING_METHOD>(lineSpacingMethod);
00049
00050     DX::ThrowIfFailed(
00051         DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory3), &m_dwriteFactory)
00052         );
00053
00054     // Create the IDWriteTextLayout.
00055
00056     ComPtr<IDWriteTextFormat> textFormat;
00057     DX::ThrowIfFailed(
00058         m_dwriteFactory->CreateTextFormat(
00059             m_fontFamily.c_str(),
00060             nullptr,    // default font collection
00061             DWRITE_FONT_WEIGHT_NORMAL,
00062             DWRITE_FONT_STYLE_NORMAL,
00063             DWRITE_FONT_STRETCH_NORMAL,
00064             m_fontSize,
00065             m_languageTag.c_str(),
00066             &textFormat
00067             )
00068         );
00069
00070     ComPtr<IDWriteTextLayout> textLayout;
00071     DX::ThrowIfFailed(
00072         m_dwriteFactory->CreateTextLayout(
00073             m_text.c_str(),
00074             static_cast<UINT32>(m_text.length()),
00075             textFormat.Get(),
00076             static_cast<float>(m_pixelWidth), // format width
00077             0.0f, // max height
00078             &textLayout
00079             )
00080         );
00081
00082     DX::ThrowIfFailed(textLayout.As(&m_textLayout));
00083
00084     // Before setting the line spacing method, select some default
00085     // parameters according to the method being used.
00086     SetLineSpacingDefaults();
00087
00088     // Set the line spacing method.
00089     SetLineSpacing();
00090 }
00091
00092
00093 /// <summary>
00094 /// Returns the line metrics for the text layout. The native implementation within
00095 /// the TextLayout class obtains these as DWRITE_LINE_METRICS1 structures; these
00096 /// are returned wrapped in the LineMetrics class.
00097 /// </summary>
00098 Platform::Array<LineMetrics^>^ TextLayout::GetTextLayoutLineMetrics()
00099 {
00100     EnsureCachedLineMetrics();
00101
00102     Platform::Array<LineMetrics^>^ results = ref new Platform::Array<LineMetrics^>(static_cast<unsigned int>(m_lineMetrics.size()));
00103
00104     for (uint32 i = 0; i < m_lineMetrics.size(); i++)
00105     {
00106         LineMetrics^ line = ref new LineMetrics();
00107         line->SetLineMetrics(m_lineMetrics[i]);
00108         results[i] = line;
00109     }
00110
00111     return results;
00112 }
00113
00114
00115
00116 /// <summary>
00117 /// Native API to obtain the DWRITE_TEXT_METRICS of the underlying
00118 /// IDWriteTextLayout3 object. Provided for use in TextLayoutImageSource.
00119 /// </summary>
00120 DWRITE_TEXT_METRICS TextLayout::GetTextMetrics()
00121 {
00122     DWRITE_TEXT_METRICS textMetrics;
00123     DX::ThrowIfFailed(m_textLayout.Get()->GetMetrics(&textMetrics));
00124     return textMetrics;
00125 }
00126
00127
00128 /// <summary>
00129 /// Native API to obtain the DWRITE_LINE_METRICS1 structures from the
00130 /// underlying IDWriteTextLayout3 object. Provided for use in
00131 /// TextLayoutImageSource.
00132 /// </summary>
00133 std::vector<DWRITE_LINE_METRICS1> TextLayout::GetLineMetrics()
00134 {
00135     EnsureCachedLineMetrics();
00136     return m_lineMetrics;
00137 }
00138
00139
00140
00141 // property setters
00142
00143 /// <summary>
00144 /// Sets the line spacing method to be used. In the native implementation within
00145 /// TextLayout, this is setting DWRITE_LINE_SPACING.method.
00146 /// <summary>
00147 /// <remarks>
00148 /// The method selected will impact how other line-spacing parameters are interpreted.
00149 /// </remarks>
00150 void TextLayout::LineSpacingMethod::set(DWriteTextLayoutImplementation::LineSpacingMethod value)
00151 {
00152     m_lineSpacing.method = static_cast<DWRITE_LINE_SPACING_METHOD>(value);
00153     SetLineSpacing();
00154 }
00155
00156
00157 /// <summary>
00158 /// Sets the line spacing height. In the native implementation within TextLayout,
00159 /// this is setting DWRITE_LINE_SPACING.height.
00160 /// </summary>
00161 /// <param name="value">The line spacing height.</param>
00162 /// <remarks>
00163 /// Interpretation of DWRITE_LINE_SPACING.height depends on the line spacing method
00164 /// (DWRITE_LINE_SPACING.method), as follows:
00165 /// Default line spacing: ignored.
00166 /// Uniform line spacing: the explicit distance between lines, in DIPs.
00167 /// Proportional line spacing: a scaling factor applied to the default computed height of each line.
00168 /// </remarks>
00169 void TextLayout::LineSpacingHeight::set(float value)
00170 {
00171     m_lineSpacing.height = value;
00172     SetLineSpacing();
00173 }
00174
00175
00176 /// <summary>
00177 /// Sets the line spacing baseline distance. In the native implementation within
00178 /// TextLayout, this is setting DWRITE_LINE_SPACING.baseline.
00179 /// </summary>
00180 /// <param name="value">The line spacing baseline distance.</param>
00181 /// <remarks>
00182 /// Interpretation of DWRITE_LINE_SPACING.baseline depends on the line spacing
00183 /// method (DWRITE_LINE_SPACING.method), as follows:
00184 /// Default line spacing: ignored.
00185 /// Uniform line spacing: the explicit distance from the top of the line to the baseline, in DIPs.
00186 /// Proportional line spacing: a scaling factor applied to the default computed baseline of each line.
00187 /// </remarks>
00188 void TextLayout::LineSpacingBaseline::set(float value)
00189 {
00190     m_lineSpacing.baseline = value;
00191     SetLineSpacing();
00192 }
00193
00194
00195 /// <summary>
00196 /// Sets the proportion of extra leading distributed before the line, rather than
00197 /// after. In the native implementation within TextLayout, this is setting
00198 /// DWRITE_LINE_SPACING.leadingBefore.
00199 /// </summary>
00200 /// <param name="value">The proportion of extra leading applied before the line.</param>
00201 /// <remarks>
00202 /// Interpretation of DWRITE_LINE_SPACING.leadingBefore depends on the line spacing
00203 /// method (DWRITE_LINE_SPACING.method), as follows:
00204 /// Default line spacing: ignored.
00205 /// Uniform line spacing: ignored.
00206 /// Proportional line spacing: a value between 0.0 and 1.0 indicating the proportion of the total leading distributed before the line.
00207 /// </remarks>
00208 void TextLayout::LineSpacingLeadingBefore::set(float value)
00209 {
00210     m_lineSpacing.leadingBefore = value;
00211     SetLineSpacing();
00212 }
00213
00214
00215 /// <summary>
00216 /// Sets whether line gap data in the font (if present) is to be used in computing
00217 /// line spacing for each line. Ignored when the uniform line spacing method is used.
00218 /// </summary>
00219 void TextLayout::FontLineGapUsage::set(DWriteTextLayoutImplementation::FontLineGapUsage value)
00220 {
00221     m_lineSpacing.fontLineGapUsage = static_cast<DWRITE_FONT_LINE_GAP_USAGE>(value);
00222     SetLineSpacing();
00223 }
00224
00225
00226
00227 // private helper methods
00228
00229 void TextLayout::SetLineSpacingDefaults()
00230 {
00231     // Used when the text layout is first created to set default
00232     // line spacing parameters according to the line spacing
00233     // method being used.
00234     //
00235     // Assumed: the m_lineSpacing.method value has been set.
00236
00237     // Common to all cases:
00238     m_lineSpacing.fontLineGapUsage = DWRITE_FONT_LINE_GAP_USAGE_DISABLED;
00239
00240     // These variables are used for the uniform spacing case.
00241     std::vector<DWRITE_LINE_METRICS1> lineMetrics;
00242     DWRITE_LINE_METRICS1 line;
00243
00244     switch (m_lineSpacing.method)
00245     {
00246     case DWRITE_LINE_SPACING_METHOD_DEFAULT:
00247         // The height, baseline and leadingBefore members are ignored.
00248         return;
00249
00250     case DWRITE_LINE_SPACING_METHOD_UNIFORM:
00251         // A reasonable default will be to get height and baseline values
00252         // from the first line of the default layout.
00253         lineMetrics = this->GetLineMetrics();
00254         line = lineMetrics[0];
00255
00256         m_lineSpacing.height = line.height;
00257         m_lineSpacing.baseline = line.baseline;
00258         // The leadingBefore member is ignored.
00259         return;
00260
00261     case DWRITE_LINE_SPACING_METHOD_PROPORTIONAL:
00262         m_lineSpacing.height = 1.0f;
00263         m_lineSpacing.baseline = 1.0f;
00264         m_lineSpacing.leadingBefore = 0.0f;
00265         return;
00266     }
00267 }
00268
00269
00270 void TextLayout::SetLineSpacing()
00271 {
00272     DX::ThrowIfFailed(
00273         m_textLayout->SetLineSpacing(&m_lineSpacing)
00274         );
00275     InvalidateLayout();
00276 }
00277
00278
00279 void TextLayout::InvalidateLayout()
00280 {
00281     // Calling InvalidateLayout will cause the layout to be performed again the
00282     // next time it is used (draw, get metrics, etc.) using the line spacing
00283     // parameters that are currently set.
00284     m_textLayout->InvalidateLayout();
00285
00286     // Invalidate the cached line metrics.
00287     m_lineMetrics.clear();
00288
00289     // Get the updated height and line metrics of the text layout.
00290     UpdateCachedMetrics();
00291 }
00292
00293
00294 void TextLayout::UpdateCachedMetrics()
00295 {
00296     // Get the total height of the text layout.
00297     DWRITE_TEXT_METRICS textMetrics;
00298     DX::ThrowIfFailed(
00299         m_textLayout->GetMetrics(&textMetrics)
00300         );
00301
00302     m_pixelHeight = static_cast<uint32>(ceilf(textMetrics.height));
00303
00304     // Get the line metrics.
00305     EnsureCachedLineMetrics();
00306 }
00307
00308
00309 void TextLayout::EnsureCachedLineMetrics()
00310 {
00311     // Any time the line metrics need to be accessed, we need to make
00312     // sure we have collected them. But we don't need to re-do that
00313     // every time they might need to be accessed; we only need to do
00314     // that if they've never been collected or if they had been
00315     // collected but then became invalid (hence cleared) as a result
00316     // in a change to the layout (the line spacing parameters were
00317     // changed.
00318
00319     // If m_lineMetrics has entries, assume they're valid. Otherwise,
00320     // get the line metrics.
00321     if (!m_lineMetrics.empty()) return;
00322
00323     // We will need to determine how many lines there are to set the size
00324     // of the vector. If we had a reason to call IDWriteTextLayout::GetMetrics
00325     // and had cached the DWRITE_TEXT_METRICS structure, then we could get
00326     // the line count directly from DWRITE_TEXT_METRICS.lineCount. Since we
00327     // haven't cached the text metrics, we can call GetLineMetrics with a
00328     // tentative count and and vector size, and it will return the actual
00329     // line count. If our tentative count is too small, there isn't any
00330     // perf hit of copying values into the vector on both first and second
00331     // calls since the GetLineMetrics call will return on the first call
00332     // before it even initializes the output buffer.
00333
00334     // Initialize the line metrics array to an estimated size.
00335     uint32 lineCount = 8;
00336     m_lineMetrics.resize(lineCount);
00337
00338     // Get the line metrics, and then resize the array based on the actual line count.
00339     HRESULT hr = m_textLayout.Get()->GetLineMetrics(&m_lineMetrics[0], lineCount, &lineCount);
00340     m_lineMetrics.resize(lineCount);
00341
00342     // If the initial buffer size was too small, get the line metrics again.
00343     if (hr == E_NOT_SUFFICIENT_BUFFER)
00344     {
00345         hr = m_textLayout.Get()->GetLineMetrics(&m_lineMetrics[0], lineCount, &lineCount);
00346     }
00347
00348     DX::ThrowIfFailed(hr);
00349 }
00350
00351
Generated on Fri Nov 15 2024 22:19:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactPicker/cpp/Scenario1_Single.xaml.cpp Source File

  • ContactPicker
  • cpp

Scenario1_Single.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_Single.xaml.h"
00013
00014 using namespace Concurrency;
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::ApplicationModel::Contacts;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Core;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024
00025 Scenario1_Single::Scenario1_Single() : rootPage(MainPage::Current)
00026 {
00027     InitializeComponent();
00028 }
00029
00030 void Scenario1_Single::ClearOutputs()
00031 {
00032     // Reset the output fields.
00033     OutputText->Text = "";
00034     rootPage->NotifyUser("", NotifyType::StatusMessage);
00035 }
00036
00037 void Scenario1_Single::ReportContactResult(Contact^ contact)
00038 {
00039     if (contact != nullptr)
00040     {
00041         OutputText->Text = MainPage::GetContactResult(contact);
00042     }
00043     else
00044     {
00045         rootPage->NotifyUser("No contact was selected.", NotifyType::ErrorMessage);
00046     }
00047 }
00048
00049 void Scenario1_Single::PickContactEmail()
00050 {
00051     ClearOutputs();
00052
00053     // Ask the user to pick a contact email address.
00054     auto contactPicker = ref new ContactPicker();
00055     contactPicker->DesiredFieldsWithContactFieldType->Append(ContactFieldType::Email);
00056
00057     create_task(contactPicker->PickContactAsync()).then([this](Contact^ contact)
00058     {
00059         ReportContactResult(contact);
00060     });
00061 }
00062
00063 void Scenario1_Single::PickContactPhone()
00064 {
00065     ClearOutputs();
00066
00067     // Ask the user to pick a contact phone number.
00068     auto contactPicker = ref new ContactPicker();
00069     contactPicker->DesiredFieldsWithContactFieldType->Append(ContactFieldType::PhoneNumber);
00070
00071     create_task(contactPicker->PickContactAsync()).then([this](Contact^ contact)
00072     {
00073         ReportContactResult(contact);
00074     });
00075 }
Generated on Fri Nov 15 2024 22:18:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cpp/Fx2Driver.h Source File

  • CustomCapability
  • cpp

Fx2Driver.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 //
00008 // Scenario1.xaml.h
00009 // Declaration of the Scenario1 class
00010 //
00011
00012 #pragma once
00013
00014 namespace SDKTemplate
00015 {
00016         ref class Fx2Driver
00017         {
00018         internal:
00019             static const uint16 DeviceType = 65500U;
00020             static const uint16 FunctionBase = 0x800;
00021
00022             static Windows::Devices::Custom::IOControlCode^ GetSevenSegmentDisplay;
00023             static Windows::Devices::Custom::IOControlCode^ SetSevenSegmentDisplay;
00024             static Windows::Devices::Custom::IOControlCode^ ReadSwitches;
00025             static Windows::Devices::Custom::IOControlCode^ GetInterruptMessage;
00026
00027             static const Platform::Guid DeviceInterfaceGuid;
00028
00029             static byte DigitToSevenSegment(byte value);
00030             static byte SevenSegmentToDigit(byte value);
00031
00032         private:
00033             static const byte SevenSegmentValues[10];
00034         };
00035 }
Generated on Fri Nov 15 2024 22:19:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cpp/SampleConfiguration.h Source File

  • IoT-GPIO
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012
00013 namespace SDKTemplate
00014 {
00015     value struct Scenario;
00016
00017     partial ref class MainPage
00018     {
00019     internal:
00020         static property Platform::String^ FEATURE_NAME
00021         {
00022             Platform::String^ get()
00023             {
00024                 return "GPIO C++ Sample";
00025             }
00026         }
00027
00028         static property Platform::Array<Scenario>^ scenarios
00029         {
00030             Platform::Array<Scenario>^ get()
00031             {
00032                 return scenariosInner;
00033             }
00034         }
00035
00036     private:
00037         static Platform::Array<Scenario>^ scenariosInner;
00038     };
00039
00040     public value struct Scenario
00041     {
00042         Platform::String^ Title;
00043         Platform::String^ ClassName;
00044     };
00045 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/MrcEffectDefinitions/MrcAudioEffectDefinition.cpp Source File

  • HolographicMixedRealityCapture
  • cpp
  • MrcEffectDefinitions

MrcAudioEffectDefinition.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "MrcAudioEffectDefinition.h"
00003
00004 using namespace MrcEffectDefinitions;
00005 using namespace Platform;
00006
00007 MrcAudioEffectDefinition::MrcAudioEffectDefinition()
00008 {
00009     MixerMode = DefaultAudioMixerMode;
00010 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_Connect Member List

This is the complete list of members for Scenario4_Connect, including all inherited members.
ConnectButton_Click(object sender, RoutedEventArgs e) | Scenario4_Connect | [inline, private]
DisconnectButton_Click(object sender, RoutedEventArgs e) | Scenario4_Connect | [inline, private]
DisplayNetworkReport(WiFiNetworkReport report) | Scenario4_Connect | [inline, private]
firstAdapter | Scenario4_Connect | [private]
NetworkInformation_NetworkStatusChanged(object sender) | Scenario4_Connect | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario4_Connect | [inline, protected]
ResultCollection | Scenario4_Connect |
ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario4_Connect | [inline, private]
rootPage | Scenario4_Connect | [private]
savedProfileName | Scenario4_Connect | [private]
ScanButton_Click(object sender, RoutedEventArgs e) | Scenario4_Connect | [inline, private]
Scenario4_Connect() | Scenario4_Connect | [inline]
UpdateConnectivityStatusAsync() | Scenario4_Connect | [inline, private]
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FullScreenMode/cppwinrt/Scenario2_Launch.h Source File

  • FullScreenMode
  • cppwinrt

Scenario2_Launch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Launch.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_Launch : Scenario2_LaunchT<Scenario2_Launch>
00019     {
00020         Scenario2_Launch();
00021
00022         void LaunchInFullScreenModeCheckBox_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario2_Launch : Scenario2_LaunchT<Scenario2_Launch, implementation::Scenario2_Launch>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cs/Scenario3.xaml.cs Source File

  • MapControl
  • cs

Scenario3.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Devices.Geolocation;
00015 using Windows.Foundation;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018
00019 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00020
00021 namespace SDKTemplate
00022 {
00023     public class PointOfInterest
00024     {
00025         public string DisplayName { get; set; }
00026         public Geopoint Location { get; set; }
00027         public Uri ImageSourceUri { get; set; }
00028         public Point NormalizedAnchorPoint { get; set; }
00029     }
00030
00031     public sealed partial class Scenario3 : Page
00032     {
00033         private MainPage rootPage = MainPage.Current;
00034
00035         public Scenario3()
00036         {
00037             this.InitializeComponent();
00038         }
00039
00040         private void MyMap_Loaded(object sender, RoutedEventArgs e)
00041         {
00042             myMap.Center = MainPage.SeattleGeopoint;
00043             myMap.ZoomLevel = 16;
00044         }
00045
00046         private void addXamlChildrenButton_Click(object sender, RoutedEventArgs e)
00047         {
00048             BasicGeoposition center = myMap.Center.Position;
00049             var pinUri = new Uri("ms-appx:///Assets/MapPin.png");
00050             MapItems.ItemsSource = new List<PointOfInterest>()
00051             {
00052                 new PointOfInterest()
00053                 {
00054                     DisplayName = "Place One",
00055                     ImageSourceUri = pinUri,
00056                     NormalizedAnchorPoint = new Point(0.5, 1),
00057                     Location = new Geopoint(new BasicGeoposition()
00058                     {
00059                         Latitude = center.Latitude + 0.001,
00060                         Longitude = center.Longitude - 0.001
00061                     })
00062                 },
00063                 new PointOfInterest()
00064                 {
00065                     DisplayName = "Place Two",
00066                     ImageSourceUri = pinUri,
00067                     NormalizedAnchorPoint = new Point(0.5, 1),
00068                     Location = new Geopoint(new BasicGeoposition()
00069                     {
00070                         Latitude = center.Latitude + 0.001,
00071                         Longitude = center.Longitude + 0.001
00072                     })
00073                 },
00074                 new PointOfInterest()
00075                 {
00076                     DisplayName = "Place Three",
00077                     ImageSourceUri = pinUri,
00078                     NormalizedAnchorPoint = new Point(0.5, 1),
00079                     Location = new Geopoint(new BasicGeoposition()
00080                     {
00081                         Latitude = center.Latitude - 0.001,
00082                         Longitude = center.Longitude - 0.001
00083                     })
00084                 },
00085                 new PointOfInterest()
00086                 {
00087                     DisplayName = "Place Four",
00088                     ImageSourceUri = pinUri,
00089                     NormalizedAnchorPoint = new Point(0.5, 1),
00090                     Location = new Geopoint(new BasicGeoposition()
00091                     {
00092                         Latitude = center.Latitude - 0.001,
00093                         Longitude = center.Longitude + 0.001
00094                     })
00095                 }
00096             };
00097         }
00098
00099         private void mapItemButton_Click(object sender, RoutedEventArgs e)
00100         {
00101             var buttonSender = sender as Button;
00102             PointOfInterest poi = buttonSender.DataContext as PointOfInterest;
00103             rootPage.NotifyUser("PointOfInterest clicked = " + poi.DisplayName, NotifyType.StatusMessage);
00104         }
00105     }
00106 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DGradientMesh/cpp/App.cpp Source File

  • D2DGradientMesh
  • cpp

App.cpp

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "App.h"
00010
00011 using namespace D2DGradientMesh;
00012
00013 using namespace concurrency;
00014 using namespace Windows::ApplicationModel;
00015 using namespace Windows::ApplicationModel::Core;
00016 using namespace Windows::ApplicationModel::Activation;
00017 using namespace Windows::UI::Core;
00018 using namespace Windows::UI::Input;
00019 using namespace Windows::System;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Graphics::Display;
00022
00023 // The main function is only used to initialize our IFrameworkView class.
00024 [Platform::MTAThread]
00025 int main(Platform::Array<Platform::String^>^)
00026 {
00027     auto directXApplicationSource = ref new DirectXApplicationSource();
00028     CoreApplication::Run(directXApplicationSource);
00029     return 0;
00030 }
00031
00032 IFrameworkView^ DirectXApplicationSource::CreateView()
00033 {
00034     return ref new App();
00035 }
00036
00037 App::App() :
00038     m_windowClosed(false),
00039     m_windowVisible(true)
00040 {
00041 }
00042
00043 // The first method called when the IFrameworkView is being created.
00044 void App::Initialize(CoreApplicationView^ applicationView)
00045 {
00046     // Register event handlers for app lifecycle. This example includes Activated, so that we
00047     // can make the CoreWindow active and start rendering on the window.
00048     applicationView->Activated +=
00049         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated);
00050
00051     CoreApplication::Suspending +=
00052         ref new EventHandler<SuspendingEventArgs^>(this, &App::OnSuspending);
00053
00054     CoreApplication::Resuming +=
00055         ref new EventHandler<Platform::Object^>(this, &App::OnResuming);
00056
00057     // At this point we have access to the device.
00058     // We can create the device-dependent resources.
00059     m_deviceResources = std::make_shared<DX::DeviceResources>();
00060 }
00061
00062 // Called when the CoreWindow object is created (or re-created).
00063 void App::SetWindow(CoreWindow^ window)
00064 {
00065     window->SizeChanged +=
00066         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &App::OnWindowSizeChanged);
00067
00068     window->VisibilityChanged +=
00069         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &App::OnVisibilityChanged);
00070
00071     window->Closed +=
00072         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::OnWindowClosed);
00073
00074     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00075
00076     currentDisplayInformation->DpiChanged +=
00077         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDpiChanged);
00078
00079     currentDisplayInformation->OrientationChanged +=
00080         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnOrientationChanged);
00081
00082     DisplayInformation::DisplayContentsInvalidated +=
00083         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDisplayContentsInvalidated);
00084
00085     m_deviceResources->SetWindow(window);
00086 }
00087
00088 // Initializes scene resources, or loads a previously saved app state.
00089 void App::Load(Platform::String^ entryPoint)
00090 {
00091     m_main = std::unique_ptr<D2DGradientMeshMain>(new D2DGradientMeshMain(m_deviceResources));
00092 }
00093
00094 // This method is called after the window becomes active.
00095 void App::Run()
00096 {
00097     while (!m_windowClosed)
00098     {
00099         if (m_windowVisible)
00100         {
00101             // Block until a UI event occurs.
00102             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00103
00104             if (m_main->Render())
00105             {
00106                 m_deviceResources->Present();
00107             }
00108         }
00109         else
00110         {
00111             // The window is hidden. Block until a UI event occurs.
00112             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00113         }
00114     }
00115 }
00116
00117 // Required for IFrameworkView.
00118 // Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
00119 // class is torn down while the app is in the foreground.
00120 void App::Uninitialize()
00121 {
00122 }
00123
00124 // Application lifecycle event handlers.
00125
00126 void App::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
00127 {
00128     // Run() won't start until the CoreWindow is activated.
00129     CoreWindow::GetForCurrentThread()->Activate();
00130 }
00131
00132 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ args)
00133 {
00134     m_deviceResources->Trim();
00135 }
00136
00137 void App::OnResuming(Object^ sender, Object^ args)
00138 {
00139     // Restore any data or state that was unloaded on suspend. By default, data
00140     // and state are persisted when resuming from suspend. Note that this event
00141     // does not occur if the app was previously terminated.
00142 }
00143
00144 // Window event handlers.
00145
00146 void App::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
00147 {
00148     m_deviceResources->SetLogicalSize(Size(sender->Bounds.Width, sender->Bounds.Height));
00149     m_main->UpdateForWindowSizeChange();
00150 }
00151
00152 void App::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
00153 {
00154     m_windowVisible = args->Visible;
00155 }
00156
00157 void App::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
00158 {
00159     m_windowClosed = true;
00160 }
00161
00162 // DisplayInformation event handlers.
00163
00164 void App::OnDpiChanged(DisplayInformation^ sender, Object^ args)
00165 {
00166     m_deviceResources->SetDpi(sender->LogicalDpi);
00167     m_main->UpdateForWindowSizeChange();
00168 }
00169
00170 void App::OnOrientationChanged(DisplayInformation^ sender, Object^ args)
00171 {
00172     m_deviceResources->SetCurrentOrientation(sender->CurrentOrientation);
00173     m_main->UpdateForWindowSizeChange();
00174 }
00175
00176 void App::OnDisplayContentsInvalidated(DisplayInformation^ sender, Object^ args)
00177 {
00178     m_deviceResources->ValidateDevice();
00179 }
Generated on Fri Nov 15 2024 22:18:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CompositionVisual/cs/VisualProperties.cs Source File

  • CompositionVisual
  • cs

VisualProperties.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
00006 // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
00007 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
00008 // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
00009 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
00010 // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
00011 // THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
00012 //
00013 //*********************************************************
00014
00015
00016 using System;
00017 using System.Collections.Generic;
00018 using System.Linq;
00019 using System.Numerics;
00020 using System.Text;
00021 using System.Threading.Tasks;
00022 using Windows.ApplicationModel.Core;
00023 using Windows.Foundation;
00024 using Windows.UI;
00025 using Windows.UI.Composition;
00026 using Windows.UI.Core;
00027
00028 namespace CompositionVisual
00029 {
00030     class VisualProperties : IFrameworkView
00031     {
00032         //------------------------------------------------------------------------------
00033         //
00034         // VisualProperties.Initialize
00035         //
00036         // This method is called during startup to associate the IFrameworkView with the
00037         // CoreApplicationView.
00038         //
00039         //------------------------------------------------------------------------------
00040
00041         void IFrameworkView.Initialize(CoreApplicationView view)
00042         {
00043             _view = view;
00044             _random = new Random();
00045         }
00046
00047         //------------------------------------------------------------------------------
00048         //
00049         // VisualProperties.SetWindow
00050         //
00051         // This method is called when the CoreApplication has created a new CoreWindow,
00052         // allowing the application to configure the window and start producing content
00053         // to display.
00054         //
00055         //------------------------------------------------------------------------------
00056
00057         void IFrameworkView.SetWindow(CoreWindow window)
00058         {
00059             _window = window;
00060             InitNewComposition();
00061             _window.PointerPressed += OnPointerPressed;
00062             _window.PointerMoved += OnPointerMoved;
00063             _window.PointerReleased += OnPointerReleased;
00064         }
00065
00066         //------------------------------------------------------------------------------
00067         //
00068         // VisualProperties.OnPointerPressed
00069         //
00070         // This method is called when the user touches the screen, taps it with a stylus
00071         // or clicks the mouse.
00072         //
00073         //------------------------------------------------------------------------------
00074
00075         void OnPointerPressed(CoreWindow window, PointerEventArgs args)
00076         {
00077             Point position = args.CurrentPoint.Position;
00078
00079             //
00080             // Walk our list of visuals to determine who, if anybody, was selected
00081             //
00082             foreach (var child in _root.Children)
00083             {
00084                 //
00085                 // Did we hit this child?
00086                 //
00087                 Vector3 offset = child.Offset;
00088                 Vector2 size = child.Size;
00089
00090                 if ((position.X >= offset.X) &&
00091                     (position.X < offset.X + size.X) &&
00092                     (position.Y >= offset.Y) &&
00093                     (position.Y < offset.Y + size.Y))
00094                 {
00095                     //
00096                     // This child was hit. Since the children are stored back to front,
00097                     // the last one hit is the front-most one so it wins
00098                     //
00099                     _currentVisual = child as ContainerVisual;
00100                     _offsetBias = new Vector2((float)(offset.X - position.X),
00101                                               (float)(offset.Y - position.Y));
00102                 }
00103             }
00104
00105             //
00106             // If a visual was hit, bring it to the front of the Z order
00107             //
00108             if (_currentVisual != null)
00109             {
00110                 ContainerVisual parent = _currentVisual.Parent as ContainerVisual;
00111                 parent.Children.Remove(_currentVisual);
00112                 parent.Children.InsertAtTop(_currentVisual);
00113             }
00114         }
00115
00116         //------------------------------------------------------------------------------
00117         //
00118         // VisualProperties.OnPointerMoved
00119         //
00120         // This method is called when the user moves their finger, stylus or mouse with
00121         // a button pressed over the screen.
00122         //
00123         //------------------------------------------------------------------------------
00124
00125         void OnPointerMoved(CoreWindow window, PointerEventArgs args)
00126         {
00127             //
00128             // If a visual is selected, drag it with the pointer position and
00129             // make it opaque while we drag it
00130             //
00131             if (_currentVisual != null)
00132             {
00133                 //
00134                 // Set up the properties of the visual the first time it is
00135                 // dragged. This will last for the duration of the drag
00136                 //
00137                 if (!_dragging)
00138                 {
00139                     _currentVisual.Opacity = 1.0f;
00140
00141                     //
00142                     // Transform the first child of the current visual so that
00143                     // the image is rotated
00144                     //
00145                     foreach (var child in _currentVisual.Children)
00146                     {
00147                         child.RotationAngleInDegrees = 45.0f;
00148                         child.CenterPoint = new Vector3(_currentVisual.Size.X / 2, _currentVisual.Size.Y / 2, 0);
00149                         break;
00150                     }
00151
00152                     //
00153                     // Clip the visual to its original layout rect by using an inset
00154                     // clip with a one-pixel margin all around
00155                     //
00156                     var clip = _compositor.CreateInsetClip();
00157                     clip.LeftInset = 1.0f;
00158                     clip.RightInset = 1.0f;
00159                     clip.TopInset = 1.0f;
00160                     clip.BottomInset = 1.0f;
00161                     _currentVisual.Clip = clip;
00162
00163                     _dragging = true;
00164                 }
00165
00166                 Point position = args.CurrentPoint.Position;
00167                 _currentVisual.Offset = new Vector3((float)(position.X + _offsetBias.X),
00168                                                     (float)(position.Y + _offsetBias.Y),
00169                                                     0.0f);
00170             }
00171         }
00172
00173         //------------------------------------------------------------------------------
00174         //
00175         // VisualProperties.OnPointerReleased
00176         //
00177         // This method is called when the user lifts their finger or stylus from the
00178         // screen, or lifts the mouse button.
00179         //
00180         //------------------------------------------------------------------------------
00181
00182         void OnPointerReleased(CoreWindow window, PointerEventArgs args)
00183         {
00184             //
00185             // If a visual was selected, make it transparent again when it is
00186             // released and restore the transform and clip
00187             //
00188             if (_currentVisual != null)
00189             {
00190                 if (_dragging)
00191                 {
00192                     //
00193                     // Remove the transform from the first child
00194                     //
00195                     foreach (var child in _currentVisual.Children)
00196                     {
00197                         child.RotationAngle = 0.0f;
00198                         child.CenterPoint = new Vector3(0.0f, 0.0f, 0.0f);
00199                         break;
00200                     }
00201
00202                     _currentVisual.Opacity = 0.8f;
00203                     _currentVisual.Clip = null;
00204                     _dragging = false;
00205                 }
00206
00207                 _currentVisual = null;
00208             }
00209         }
00210
00211         //------------------------------------------------------------------------------
00212         //
00213         // VisualProperties.Load
00214         //
00215         // This method is called when a specific page is being loaded in the
00216         // application.  It is not used for this application.
00217         //
00218         //------------------------------------------------------------------------------
00219
00220         void IFrameworkView.Load(string unused)
00221         {
00222
00223         }
00224
00225         //------------------------------------------------------------------------------
00226         //
00227         // VisualProperties.Run
00228         //
00229         // This method is called by CoreApplication.Run() to actually run the
00230         // dispatcher's message pump.
00231         //
00232         //------------------------------------------------------------------------------
00233
00234         void IFrameworkView.Run()
00235         {
00236             _window.Activate();
00237             _window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessUntilQuit);
00238         }
00239
00240         //------------------------------------------------------------------------------
00241         //
00242         // VisualProperties.Uninitialize
00243         //
00244         // This method is called during shutdown to disconnect the CoreApplicationView,
00245         // and CoreWindow from the IFrameworkView.
00246         //
00247         //------------------------------------------------------------------------------
00248
00249         void IFrameworkView.Uninitialize()
00250         {
00251             _window = null;
00252             _view = null;
00253         }
00254
00255         //------------------------------------------------------------------------------
00256         //
00257         // VisualProperties.InitNewComposition
00258         //
00259         // This method is called by SetWindow(), where we initialize Composition after
00260         // the CoreWindow has been created.
00261         //
00262         //------------------------------------------------------------------------------
00263
00264         void InitNewComposition()
00265         {
00266             //
00267             // Set up Windows.UI.Composition Compositor, root ContainerVisual, and associate with
00268             // the CoreWindow.
00269             //
00270
00271             _compositor = new Compositor();
00272
00273             _root = _compositor.CreateContainerVisual();
00274
00275
00276
00277             _compositionTarget = _compositor.CreateTargetForCurrentView();
00278             _compositionTarget.Root = _root;
00279
00280             //
00281             // Create a few visuals for our window
00282             //
00283             for (int index = 0; index < 20; index++)
00284             {
00285                 _root.Children.InsertAtTop(CreateChildElement());
00286             }
00287         }
00288
00289         //------------------------------------------------------------------------------
00290         //
00291         // VisualProperties.CreateChildElement
00292         //
00293         // Creates a small sub-tree to represent a visible element in our application.
00294         //
00295         //------------------------------------------------------------------------------
00296
00297         Visual CreateChildElement()
00298         {
00299             //
00300             // Each element consists of three visuals, which produce the appearance
00301             // of a framed rectangle
00302             //
00303             var element = _compositor.CreateContainerVisual();
00304             element.Size = new Vector2(100.0f, 100.0f);
00305
00306             //
00307             // Position this visual randomly within our window
00308             //
00309             element.Offset = new Vector3((float)(_random.NextDouble() * 400), (float)(_random.NextDouble() * 400), 0.0f);
00310
00311             //
00312             // The outer rectangle is always white
00313             //
00314             var visual = _compositor.CreateSpriteVisual();
00315             element.Children.InsertAtTop(visual);
00316             visual.Brush = _compositor.CreateColorBrush(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF));
00317             visual.Size = new Vector2(100.0f, 100.0f);
00318
00319             //
00320             // The inner rectangle is inset from the outer by three pixels all around
00321             //
00322             var child = _compositor.CreateSpriteVisual();
00323             visual.Children.InsertAtTop(child);
00324             child.Offset = new Vector3(3.0f, 3.0f, 0.0f);
00325             child.Size = new Vector2(94.0f, 94.0f);
00326
00327             //
00328             // Pick a random color for every rectangle
00329             //
00330             byte red = (byte)(0xFF * (0.2f + (_random.NextDouble() / 0.8f)));
00331             byte green = (byte)(0xFF * (0.2f + (_random.NextDouble() / 0.8f)));
00332             byte blue = (byte)(0xFF * (0.2f + (_random.NextDouble() / 0.8f)));
00333             child.Brush = _compositor.CreateColorBrush(Color.FromArgb(0xFF, red, green, blue));
00334
00335             //
00336             // Make the subtree root visual partially transparent. This will cause each visual in the subtree
00337             // to render partially transparent, since a visual's opacity is multiplied with its parent's
00338             // opacity
00339             //
00340             element.Opacity = 0.8f;
00341
00342             return element;
00343         }
00344
00345         // CoreWindow / CoreApplicationView
00346         private CoreWindow _window;
00347         private CoreApplicationView _view;
00348
00349         // Windows.UI.Composition
00350         private Compositor _compositor;
00351         private CompositionTarget _compositionTarget;
00352         private ContainerVisual _root;
00353         private ContainerVisual _currentVisual;
00354         private Vector2 _offsetBias;
00355         private bool _dragging;
00356
00357         // Helpers
00358         private Random _random;
00359     }
00360
00361
00362     public sealed class VisualPropertiesFactory : IFrameworkViewSource
00363     {
00364         //------------------------------------------------------------------------------
00365         //
00366         // VisualPropertiesFactory.CreateView
00367         //
00368         // This method is called by CoreApplication to provide a new IFrameworkView for
00369         // a CoreWindow that is being created.
00370         //
00371         //------------------------------------------------------------------------------
00372
00373         IFrameworkView IFrameworkViewSource.CreateView()
00374         {
00375             return new VisualProperties();
00376         }
00377
00378
00379         //------------------------------------------------------------------------------
00380         //
00381         // main
00382         //
00383         //------------------------------------------------------------------------------
00384
00385         static int Main(string[] args)
00386         {
00387             CoreApplication.Run(new VisualPropertiesFactory());
00388
00389             return 0;
00390         }
00391     }
00392 }
Generated on Fri Nov 15 2024 22:18:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MicrosoftPassport/Server/Models/SubjectPublicKeyInfo.cs Source File

  • MicrosoftPassport
  • Server
  • Models

SubjectPublicKeyInfo.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 // Please refer to the Microsoft Passport and Windows Hello
00012 // whitepaper on the Windows Dev Center for a complete
00013 // explanation of Microsoft Passport and Windows Hello
00014 // implementation:
00015 // http://go.microsoft.com/fwlink/p/?LinkId=522066
00016 //*********************************************************
00017 using Microsoft.Win32.SafeHandles;
00018 using System;
00019 using System.Runtime.ConstrainedExecution;
00020 using System.Runtime.InteropServices;
00021 using System.Security.Cryptography;
00022
00023 namespace MicrosoftPassport.Models
00024 {
00025     public sealed class SubjectPublicKeyInfo
00026     {
00027         const uint STATUS_SUCCESS = 0;
00028
00029         private readonly byte[] _rawCngPublicKeyBlob;
00030
00031         public SubjectPublicKeyInfo(byte[] subjectPublicKeyInfo)
00032         {
00033             if (subjectPublicKeyInfo == null)
00034             {
00035                 throw new ArgumentNullException(nameof(subjectPublicKeyInfo));
00036             }
00037             if (subjectPublicKeyInfo.Length == 0)
00038             {
00039                 throw new ArgumentException("Array cannot be empty.", nameof(subjectPublicKeyInfo));
00040             }
00041
00042             // const definitions from wincrypt.h and bcrypt.h
00043             const uint X509_ASN_ENCODING = 0x00000001;
00044             const uint CRYPT_DECODE_ALLOC_FLAG = 0x8000;
00045             const int X509_PUBLIC_KEY_INFO = 8;
00046             const string BCRYPT_PUBLIC_KEY_BLOB = "PUBLICBLOB";
00047
00048             // The incoming raw public key is an ASN.1-encoded subject public key info
00049
00050             SafeLocalAllocHandle publicKeyInfoSafeHandle;
00051             uint cbPublicKeyInfo; // unused
00052             bool success = NativeMethods.CryptDecodeObjectEx(
00053                 dwCertEncodingType: X509_ASN_ENCODING,
00054                 lpszStructType: (IntPtr)X509_PUBLIC_KEY_INFO,
00055                 pbEncoded: subjectPublicKeyInfo,
00056                 cbEncoded: (uint)subjectPublicKeyInfo.Length,
00057                 dwFlags: CRYPT_DECODE_ALLOC_FLAG,
00058                 pDecodePara: IntPtr.Zero,
00059                 pvStructInfo: out publicKeyInfoSafeHandle,
00060                 pcbStructInfo: out cbPublicKeyInfo);
00061
00062             if (!success)
00063             {
00064                 throw new CryptographicException($"CryptDecodeObjectEx failed with error code 0x{Marshal.GetLastWin32Error():X8}.");
00065             }
00066
00067             // The CERT_PUBLIC_KEY_INFO struct can be converted to a BCRYPT key handle
00068
00069             SafeBCryptKeyHandle bcryptKeyHandle;
00070             success = NativeMethods.CryptImportPublicKeyInfoEx2(
00071                 dwCertEncodingType: X509_ASN_ENCODING,
00072                 pInfo: publicKeyInfoSafeHandle,
00073                 dwFlags: 0,
00074                 pvAuxInfo: IntPtr.Zero,
00075                 phKey: out bcryptKeyHandle);
00076
00077             if (!success)
00078             {
00079                 throw new CryptographicException($"CryptImportPublicKeyInfoEx2 failed with error code 0x{Marshal.GetLastWin32Error():X8}.");
00080             }
00081
00082             publicKeyInfoSafeHandle.Dispose(); // no longer need this
00083
00084             // Export the BCRYPT key handle as raw CNG key material
00085
00086             // first, get the required byte count
00087             uint numBytesRequired;
00088             int ntstatus = NativeMethods.BCryptExportKey(
00089                 hKey: bcryptKeyHandle,
00090                 hExportKey: IntPtr.Zero,
00091                 pszBlobType: BCRYPT_PUBLIC_KEY_BLOB,
00092                 pbOutput: null,
00093                 cbOutput: 0,
00094                 pcbResult: out numBytesRequired,
00095                 dwFlags: 0);
00096
00097             if (ntstatus != STATUS_SUCCESS)
00098             {
00099                 throw new CryptographicException($"BCryptExportKey failed with error code 0x{ntstatus:X8}.");
00100             }
00101
00102             // next, allocate the real buffer and populate it
00103             byte[] rawCngKey = new byte[checked((int)numBytesRequired)];
00104             ntstatus = NativeMethods.BCryptExportKey(
00105                 hKey: bcryptKeyHandle,
00106                 hExportKey: IntPtr.Zero,
00107                 pszBlobType: BCRYPT_PUBLIC_KEY_BLOB,
00108                 pbOutput: rawCngKey,
00109                 cbOutput: (uint)rawCngKey.Length,
00110                 pcbResult: out numBytesRequired,
00111                 dwFlags: 0);
00112
00113             if (ntstatus != STATUS_SUCCESS)
00114             {
00115                 throw new CryptographicException($"BCryptExportKey failed with error code 0x{ntstatus:X8}.");
00116             }
00117
00118             bcryptKeyHandle.Dispose(); // no longer need this
00119
00120             // resize the CNG key buffer if we overallocated
00121             if (numBytesRequired != rawCngKey.Length)
00122             {
00123                 byte[] tempBuffer = new byte[numBytesRequired];
00124                 Buffer.BlockCopy(rawCngKey, 0, tempBuffer, 0, tempBuffer.Length);
00125                 rawCngKey = tempBuffer;
00126             }
00127
00128             // finally, set properties
00129             _rawCngPublicKeyBlob = rawCngKey;
00130         }
00131
00132         public CngKey GetPublicKey()
00133         {
00134             return CngKey.Import(_rawCngPublicKeyBlob, CngKeyBlobFormat.GenericPublicBlob);
00135         }
00136
00137         private sealed class SafeBCryptKeyHandle : SafeHandleZeroOrMinusOneIsInvalid
00138         {
00139             private SafeBCryptKeyHandle() : base(ownsHandle: true) { }
00140
00141             protected override bool ReleaseHandle()
00142             {
00143                 return (NativeMethods.BCryptDestroyKey(handle) == STATUS_SUCCESS);
00144             }
00145         }
00146
00147         private sealed class SafeLocalAllocHandle : SafeHandleZeroOrMinusOneIsInvalid
00148         {
00149             private SafeLocalAllocHandle() : base(ownsHandle: true) { }
00150
00151             public static SafeLocalAllocHandle Alloc(int cb)
00152             {
00153                 SafeLocalAllocHandle handle = new SafeLocalAllocHandle();
00154                 handle.AllocCore(cb);
00155                 return handle;
00156             }
00157
00158             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
00159             private void AllocCore(int cb)
00160             {
00161                 SetHandle(Marshal.AllocHGlobal(cb));
00162             }
00163
00164             protected override bool ReleaseHandle()
00165             {
00166                 Marshal.FreeHGlobal(handle);
00167                 return true;
00168             }
00169         }
00170
00171         private static class NativeMethods
00172         {
00173             // https://msdn.microsoft.com/en-us/library/windows/desktop/aa379912(v=vs.85).aspx
00174             [DllImport("crypt32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
00175             internal static extern bool CryptDecodeObjectEx(
00176                 [In] uint dwCertEncodingType,
00177                 [In] IntPtr lpszStructType,
00178                 [In] byte[] pbEncoded,
00179                 [In] uint cbEncoded,
00180                 [In] uint dwFlags,
00181                 [In] IntPtr pDecodePara,
00182                 [Out] out SafeLocalAllocHandle pvStructInfo,
00183                 [Out] out uint pcbStructInfo);
00184
00185             // https://msdn.microsoft.com/en-us/library/windows/desktop/aa380211(v=vs.85).aspx
00186             [DllImport("crypt32.dll", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
00187             internal static extern bool CryptImportPublicKeyInfoEx2(
00188                 [In] uint dwCertEncodingType,
00189                 [In] SafeLocalAllocHandle pInfo,
00190                 [In] uint dwFlags,
00191                 [In] IntPtr pvAuxInfo,
00192                 [Out] out SafeBCryptKeyHandle phKey);
00193
00194             // https://msdn.microsoft.com/en-us/library/windows/desktop/aa375404(v=vs.85).aspx
00195             [DllImport("bcrypt.dll", CallingConvention = CallingConvention.Winapi)]
00196             [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
00197             internal static extern int BCryptDestroyKey(
00198                 [In] IntPtr hKey);
00199
00200             // https://msdn.microsoft.com/en-us/library/windows/desktop/aa375434(v=vs.85).aspx
00201             [DllImport("bcrypt.dll", CallingConvention = CallingConvention.Winapi)]
00202             internal static extern int BCryptExportKey(
00203                 [In] SafeBCryptKeyHandle hKey,
00204                 [In] IntPtr hExportKey,
00205                 [In, MarshalAs(UnmanagedType.LPWStr)] string pszBlobType,
00206                 [Out] byte[] pbOutput,
00207                 [In] uint cbOutput,
00208                 [Out] out uint pcbResult,
00209                 [In] uint dwFlags);
00210         }
00211     }
00212 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
BeginDraw() | sealed | [private]
BeginDraw(Windows::Foundation::Rect updateRect) | sealed | [private]
Clear() | sealed | [private]
CreateDeviceResources() | sealed | [private]
Draw() | sealed |
DrawLineMetricsDecorations() | sealed | [private]
DrawText() | sealed | [private]
EndDraw() | sealed | [private]
EnsureCachedLineMetrics() | sealed | [private]
GetLineMetrics() | sealed |
GetTextLayoutLineMetrics() | sealed |
InvalidateLayout() | sealed | [private]
m_boundsBrush | sealed | [private]
m_boundsStrokeStyle | sealed | [private]
m_d2dContext | sealed | [private]
m_d2dDevice | sealed | [private]
m_d3dDevice | sealed | [private]
m_dwriteFactory | sealed | [private]
m_fontFamily | sealed | [private]
m_fontSize | sealed | [private]
m_languageTag | sealed | [private]
m_lineMetrics | sealed | [private]
m_lineSpacing | sealed | [private]
m_pixelHeight | sealed | [private]
m_pixelWidth | sealed | [private]
m_suspendEventHandlerRegistrationToken | sealed | [private]
m_text | sealed | [private]
m_textAscentBrush | sealed | [private]
m_textBackgroundBrush | sealed | [private]
m_textBrush | sealed | [private]
m_textDescentBrush | sealed | [private]
m_textLayout | sealed | [private]
m_textLayout | sealed | [private]
m_textLineGapBrush | sealed | [private]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^e) | sealed | [private]
SetLineSpacing() | sealed | [private]
SetLineSpacingDefaults() | sealed | [private]
TextLayout(Platform::String^text, Platform::String^languageTag, Platform::String^fontFamily, float fontSize, uint32 pixelWidth, DWriteTextLayoutImplementation::LineSpacingMethod lineSpacingMethod) | sealed |
TextLayoutImageSource(TextLayout^textLayout) | sealed |
TextLayoutImageSource(TextLayout^textLayout, uint32 pixelWidth, uint32 pixelHeight) | sealed |
UpdateCachedMetrics() | sealed | [private]
~TextLayoutImageSource() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothLE/cppwinrt/Scenario3_ServerForeground.cpp Source File

  • BluetoothLE
  • cppwinrt

Scenario3_ServerForeground.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_ServerForeground.h"
00014 #include "Scenario3_ServerForeground.g.cpp"
00015 #include "SampleConfiguration.h"
00016 #include "PresentationFormats.h"
00017
00018 using namespace winrt;
00019 using namespace Windows::Devices::Bluetooth;
00020 using namespace Windows::Devices::Bluetooth::GenericAttributeProfile;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Storage::Streams;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 namespace winrt
00028 {
00029     hstring to_hstring(BluetoothError error)
00030     {
00031         switch (error)
00032         {
00033         case BluetoothError::Success: return L"Success";
00034         case BluetoothError::RadioNotAvailable: return L"RadioNotAvailable";
00035         case BluetoothError::ResourceInUse: return L"ResourceInUse";
00036         case BluetoothError::DeviceNotConnected: return L"DeviceNotConnected";
00037         case BluetoothError::OtherError: return L"OtherError";
00038         case BluetoothError::DisabledByPolicy: return L"DisabledByPolicy";
00039         case BluetoothError::NotSupported: return L"NotSupported";
00040         case BluetoothError::DisabledByUser: return L"DisabledByUser";
00041         case BluetoothError::ConsentRequired: return L"ConsentRequired";
00042         case BluetoothError::TransportNotSupported: return L"TransportNotSupported";
00043         }
00044         return L"Code " + to_hstring(static_cast<int>(error));
00045     }
00046
00047     hstring to_hstring(GattServiceProviderAdvertisementStatus status)
00048     {
00049         switch (status)
00050         {
00051         case GattServiceProviderAdvertisementStatus::Created: return L"Created";
00052         case GattServiceProviderAdvertisementStatus::Stopped: return L"Stopped";
00053         case GattServiceProviderAdvertisementStatus::Started: return L"Started";
00054         case GattServiceProviderAdvertisementStatus::Aborted: return L"Aborted";
00055         }
00056         return L"Code " + to_hstring(static_cast<int>(status));
00057     }
00058 }
00059
00060 namespace winrt::SDKTemplate::implementation
00061 {
00062     // This scenario declares support for a calculator service.
00063     // Remote clients (including this sample on another machine) can supply:
00064     // - Operands 1 and 2
00065     // - an operator (+,-,*,/)
00066     // and get a result
00067
00068 #pragma region UI Code
00069     Scenario3_ServerForeground::Scenario3_ServerForeground()
00070     {
00071         InitializeComponent();
00072     }
00073
00074     fire_and_forget Scenario3_ServerForeground::OnNavigatedTo(NavigationEventArgs const&)
00075     {
00076         auto lifetime = get_strong();
00077         peripheralSupported = co_await CheckPeripheralRoleSupportAsync();
00078         if (peripheralSupported)
00079         {
00080             ServerPanel().Visibility(Visibility::Visible);
00081         }
00082         else
00083         {
00084             PeripheralWarning().Visibility(Visibility::Visible);
00085         }
00086     }
00087
00088     void Scenario3_ServerForeground::OnNavigatedFrom(NavigationEventArgs const&)
00089     {
00090         if (op1CharacteristicWriteToken)
00091         {
00092             op1Characteristic.WriteRequested(std::exchange(op1CharacteristicWriteToken, {}));
00093         }
00094         if (op2CharacteristicWriteToken)
00095         {
00096             op2Characteristic.WriteRequested(std::exchange(op2CharacteristicWriteToken, {}));
00097         }
00098         if (operatorCharacteristicWriteToken)
00099         {
00100             operatorCharacteristic.WriteRequested(std::exchange(operatorCharacteristicWriteToken, {}));
00101         }
00102         if (resultCharacteristicReadToken)
00103         {
00104             resultCharacteristic.ReadRequested(std::exchange(resultCharacteristicReadToken, {}));
00105         }
00106         if (resultCharacteristicClientsChangedToken)
00107         {
00108             resultCharacteristic.SubscribedClientsChanged(std::exchange(resultCharacteristicClientsChangedToken, {}));
00109         }
00110         if (serviceProviderAdvertisementChangedToken)
00111         {
00112             serviceProvider.AdvertisementStatusChanged(std::exchange(serviceProviderAdvertisementChangedToken, {}));
00113         }
00114
00115         if (serviceProvider != nullptr)
00116         {
00117             if (serviceProvider.AdvertisementStatus() != GattServiceProviderAdvertisementStatus::Stopped)
00118             {
00119                 serviceProvider.StopAdvertising();
00120             }
00121             serviceProvider = nullptr;
00122         }
00123     }
00124
00125     fire_and_forget Scenario3_ServerForeground::PublishButton_ClickAsync()
00126     {
00127         auto lifetime = get_strong();
00128
00129         // Server not initialized yet - initialize it and start publishing
00130         if (serviceProvider == nullptr)
00131         {
00132             bool serviceStarted = co_await ServiceProviderInitAsync();
00133             if (serviceStarted)
00134             {
00135                 rootPage.NotifyUser(L"Service successfully started", NotifyType::StatusMessage);
00136                 PublishButton().Content(box_value(L"Stop Service"));
00137             }
00138             else
00139             {
00140                 rootPage.NotifyUser(L"Service not started", NotifyType::ErrorMessage);
00141             }
00142         }
00143         else
00144         {
00145             // BT_Code: Stops advertising support for custom GATT Service
00146             serviceProvider.StopAdvertising();
00147             serviceProvider = nullptr;
00148             PublishButton().Content(box_value(L"Start Service"));
00149         }
00150     }
00151
00152     fire_and_forget Scenario3_ServerForeground::UpdateUX()
00153     {
00154         auto lifetime = get_strong();
00155         co_await resume_foreground(Dispatcher());
00156
00157         switch (operatorReceived)
00158         {
00159         case CalculatorOperators::Add:
00160             OperationText().Text(L"+");
00161             break;
00162         case CalculatorOperators::Subtract:
00163             OperationText().Text(L"-");
00164             break;
00165         case CalculatorOperators::Multiply:
00166             OperationText().Text(L"*");
00167             break;
00168         case CalculatorOperators::Divide:
00169             OperationText().Text(L"/");
00170             break;
00171         default:
00172             OperationText().Text(L"INV");
00173             break;
00174         }
00175         Operand1Text().Text(to_hstring(operand1Received));
00176         Operand2Text().Text(to_hstring(operand2Received));
00177         resultVal = ComputeResult();
00178         ResultText().Text(to_hstring(resultVal));
00179     }
00180 #pragma endregion
00181
00182     IAsyncOperation<bool> Scenario3_ServerForeground::CheckPeripheralRoleSupportAsync()
00183     {
00184         // BT_Code: New for Creator's Update - Bluetooth adapter has properties of the local BT radio.
00185         auto localAdapter = co_await BluetoothAdapter::GetDefaultAsync();
00186
00187         if (localAdapter != nullptr)
00188         {
00189             co_return localAdapter.IsPeripheralRoleSupported();
00190         }
00191         else
00192         {
00193             // Bluetooth is not turned on
00194             co_return false;
00195         }
00196     }
00197
00198     /// <summary>
00199     /// Uses the relevant Service/Characteristic UUIDs to initialize, hook up event handlers and start a service on the local system.
00200     /// </summary>
00201     /// <returns></returns>
00202     IAsyncOperation<bool> Scenario3_ServerForeground::ServiceProviderInitAsync()
00203     {
00204         // BT_Code: Initialize and starting a custom GATT Service using GattServiceProvider.
00205         auto lifetime = get_strong();
00206
00207         GattServiceProviderResult serviceResult = co_await GattServiceProvider::CreateAsync(Constants::CalcServiceUuid);
00208         if (serviceResult.Error() == BluetoothError::Success)
00209         {
00210             serviceProvider = serviceResult.ServiceProvider();
00211         }
00212         else
00213         {
00214             rootPage.NotifyUser(L"Could not create service provider: " + to_hstring(serviceResult.Error()), NotifyType::ErrorMessage);
00215             co_return false;
00216         }
00217
00218         // BT_Code: Initializes custom local parameters w/ properties, protection levels as well as common descriptors like User Description.
00219         GattLocalCharacteristicParameters gattOperandParameters;
00220         gattOperandParameters.CharacteristicProperties(GattCharacteristicProperties::Write | GattCharacteristicProperties::WriteWithoutResponse);
00221         gattOperandParameters.WriteProtectionLevel(GattProtectionLevel::Plain);
00222         gattOperandParameters.UserDescription(L"Operand Characteristic");
00223
00224         GattLocalCharacteristicResult result = co_await serviceProvider.Service().CreateCharacteristicAsync(Constants::Op1CharacteristicUuid, gattOperandParameters);
00225         if (result.Error() == BluetoothError::Success)
00226         {
00227             op1Characteristic = result.Characteristic();
00228         }
00229         else
00230         {
00231             rootPage.NotifyUser(L"Could not create operand1 characteristic: " + to_hstring(result.Error()), NotifyType::ErrorMessage);
00232             co_return false;
00233         }
00234         op1CharacteristicWriteToken = op1Characteristic.WriteRequested({ get_weak(), &Scenario3_ServerForeground::Op1Characteristic_WriteRequestedAsync });
00235
00236         // Create the second operand characteristic.
00237         result = co_await serviceProvider.Service().CreateCharacteristicAsync(Constants::Op2CharacteristicUuid, gattOperandParameters);
00238         if (result.Error() == BluetoothError::Success)
00239         {
00240             op2Characteristic = result.Characteristic();
00241         }
00242         else
00243         {
00244             rootPage.NotifyUser(L"Could not create operand2 characteristic: " + to_hstring(result.Error()), NotifyType::ErrorMessage);
00245             co_return false;
00246         }
00247
00248         op2CharacteristicWriteToken = op2Characteristic.WriteRequested({ get_weak(), &Scenario3_ServerForeground::Op2Characteristic_WriteRequestedAsync });
00249
00250         // Create the operator characteristic.
00251         GattLocalCharacteristicParameters gattOperatorParameters;
00252         gattOperandParameters.CharacteristicProperties(GattCharacteristicProperties::Write | GattCharacteristicProperties::WriteWithoutResponse);
00253         gattOperandParameters.WriteProtectionLevel(GattProtectionLevel::Plain);
00254         gattOperandParameters.UserDescription(L"Operator Characteristic");
00255
00256         result = co_await serviceProvider.Service().CreateCharacteristicAsync(Constants::OperatorCharacteristicUuid, gattOperatorParameters);
00257         if (result.Error() == BluetoothError::Success)
00258         {
00259             operatorCharacteristic = result.Characteristic();
00260         }
00261         else
00262         {
00263             rootPage.NotifyUser(L"Could not create operator characteristic: " + to_hstring(result.Error()), NotifyType::ErrorMessage);
00264             co_return false;
00265         }
00266
00267         operatorCharacteristicWriteToken = operatorCharacteristic.WriteRequested({ get_weak(), &Scenario3_ServerForeground::OperatorCharacteristic_WriteRequestedAsync });
00268
00269         // Create the result characteristic.
00270         GattLocalCharacteristicParameters gattResultParameters;
00271         gattResultParameters.CharacteristicProperties(GattCharacteristicProperties::Read | GattCharacteristicProperties::Notify);
00272         gattResultParameters.WriteProtectionLevel(GattProtectionLevel::Plain);
00273         gattResultParameters.UserDescription(L"Result  Characteristic");
00274
00275         // Add presentation format - 32-bit unsigned integer, with exponent 0, the unit is unitless, with no company description
00276         GattPresentationFormat intFormat = GattPresentationFormat::FromParts(
00277             GattPresentationFormatTypes::UInt32(),
00278             PresentationFormats::Exponent,
00279             static_cast<uint16_t>(PresentationFormats::Units::Unitless),
00280             static_cast<uint8_t>(PresentationFormats::NamespaceId::BluetoothSigAssignedNumber),
00281             PresentationFormats::Description);
00282
00283         gattResultParameters.PresentationFormats().Append(intFormat);
00284
00285         result = co_await serviceProvider.Service().CreateCharacteristicAsync(Constants::ResultCharacteristicUuid, gattResultParameters);
00286         if (result.Error() == BluetoothError::Success)
00287         {
00288             resultCharacteristic = result.Characteristic();
00289         }
00290         else
00291         {
00292             rootPage.NotifyUser(L"Could not create result characteristic: " + to_hstring(result.Error()), NotifyType::ErrorMessage);
00293             co_return false;
00294         }
00295         resultCharacteristicReadToken = resultCharacteristic.ReadRequested({ get_weak(), &Scenario3_ServerForeground::ResultCharacteristic_ReadRequestedAsync });
00296         resultCharacteristicClientsChangedToken = resultCharacteristic.SubscribedClientsChanged({ get_weak(), &Scenario3_ServerForeground::ResultCharacteristic_SubscribedClientsChanged });
00297
00298         // BT_Code: Indicate if your sever advertises as connectable and discoverable.
00299         GattServiceProviderAdvertisingParameters advParameters;
00300
00301         // IsConnectable determines whether a call to publish will attempt to start advertising and
00302         // put the service UUID in the ADV packet (best effort)
00303         advParameters.IsConnectable(peripheralSupported);
00304
00305         // IsDiscoverable determines whether a remote device can query the local device for support
00306         // of this service
00307         advParameters.IsDiscoverable(true);
00308
00309         serviceProviderAdvertisementChangedToken = serviceProvider.AdvertisementStatusChanged({ get_weak(), &Scenario3_ServerForeground::ServiceProvider_AdvertisementStatusChanged });
00310         serviceProvider.StartAdvertising(advParameters);
00311         co_return true;
00312     }
00313
00314     void Scenario3_ServerForeground::ResultCharacteristic_SubscribedClientsChanged(GattLocalCharacteristic const& sender, IInspectable const&)
00315     {
00316         rootPage.NotifyUser(L"New device subscribed. New subscribed count: " + to_hstring(sender.SubscribedClients().Size()), NotifyType::StatusMessage);
00317     }
00318
00319     void Scenario3_ServerForeground::ServiceProvider_AdvertisementStatusChanged(GattServiceProvider const& sender, GattServiceProviderAdvertisementStatusChangedEventArgs const&)
00320     {
00321         // Created - The default state of the advertisement, before the service is published for the first time.
00322         // Stopped - Indicates that the application has canceled the service publication and its advertisement.
00323         // Started - Indicates that the system was successfully able to issue the advertisement request.
00324         // Aborted - Indicates that the system was unable to submit the advertisement request, or it was canceled due to resource contention.
00325
00326         rootPage.NotifyUser(L"New Advertisement Status: AdvertisementStatus = " + to_hstring(sender.AdvertisementStatus()), NotifyType::StatusMessage);
00327     }
00328
00329     fire_and_forget Scenario3_ServerForeground::ResultCharacteristic_ReadRequestedAsync(GattLocalCharacteristic const&, GattReadRequestedEventArgs args)
00330     {
00331         // BT_Code: Process a read request.
00332         auto lifetime = get_strong();
00333         auto deferral = args.GetDeferral();
00334
00335         // Get the request information.  This requires device access before an app can access the device's request.
00336         GattReadRequest request = co_await args.GetRequestAsync();
00337         if (request == nullptr)
00338         {
00339             // No access allowed to the device.  Application should indicate this to the user.
00340             rootPage.NotifyUser(L"Access to device not allowed", NotifyType::ErrorMessage);
00341         }
00342         else
00343         {
00344             DataWriter writer;
00345             writer.ByteOrder(ByteOrder::LittleEndian);
00346             writer.WriteInt32(resultVal);
00347
00348             // Can get details about the request such as the size and offset, as well as monitor the state to see if it has been completed/cancelled externally.
00349             // request.Offset
00350             // request.Length
00351             // request.State
00352             // request.StateChanged += <Handler>
00353
00354             // Gatt code to handle the response
00355             request.RespondWithValue(writer.DetachBuffer());
00356         }
00357
00358         deferral.Complete();
00359     }
00360
00361     int Scenario3_ServerForeground::ComputeResult()
00362     {
00363         int computedValue = 0;
00364         switch (operatorReceived)
00365         {
00366         case CalculatorOperators::Add:
00367             computedValue = operand1Received + operand2Received;
00368             break;
00369         case CalculatorOperators::Subtract:
00370             computedValue = operand1Received - operand2Received;
00371             break;
00372         case CalculatorOperators::Multiply:
00373             computedValue = operand1Received * operand2Received;
00374             break;
00375         case CalculatorOperators::Divide:
00376             if (operand2Received == 0 || (operand1Received == std::numeric_limits<int>::min() && operand2Received == -1))
00377             {
00378                 rootPage.NotifyUser(L"Division overflow", NotifyType::ErrorMessage);
00379             }
00380             else
00381             {
00382                 computedValue = operand1Received / operand2Received;
00383             }
00384             break;
00385         default:
00386             rootPage.NotifyUser(L"Invalid Operator", NotifyType::ErrorMessage);
00387             break;
00388         }
00389         NotifyClientDevices(computedValue);
00390         return computedValue;
00391     }
00392
00393     fire_and_forget Scenario3_ServerForeground::NotifyClientDevices(int computedValue)
00394     {
00395         auto lifetime = get_strong();
00396         DataWriter writer;
00397         writer.ByteOrder(ByteOrder::LittleEndian);
00398         writer.WriteInt32(computedValue);
00399
00400         // BT_Code: Returns a collection of all clients that the notification was attempted and the result.
00401         IVectorView<GattClientNotificationResult> results = co_await resultCharacteristic.NotifyValueAsync(writer.DetachBuffer());
00402
00403         rootPage.NotifyUser(L"Sent value " + to_hstring(computedValue) + L" to clients.", NotifyType::StatusMessage);
00404         for (GattClientNotificationResult&& result : results)
00405         {
00406             // An application can iterate through each registered client that was notified and retrieve the results:
00407             //
00408             // result.SubscribedClient(): The details on the remote client.
00409             // result.Status(): The GattCommunicationStatus
00410             // result.ProtocolError(): iff Status() == GattCommunicationStatus::ProtocolError
00411         }
00412     }
00413
00414     fire_and_forget Scenario3_ServerForeground::Op1Characteristic_WriteRequestedAsync(GattLocalCharacteristic const&, GattWriteRequestedEventArgs args)
00415     {
00416         // BT_Code: Processing a write request.
00417         auto lifetime = get_strong();
00418         auto deferral = args.GetDeferral();
00419
00420         // Get the request information.  This requires device access before an app can access the device's request.
00421         GattWriteRequest request = co_await args.GetRequestAsync();
00422         if (request == nullptr)
00423         {
00424             // No access allowed to the device.  Application should indicate this to the user.
00425         }
00426         else
00427         {
00428             ProcessWriteCharacteristic(request, CalculatorCharacteristics::Operand1);
00429         }
00430         deferral.Complete();
00431     }
00432
00433     fire_and_forget Scenario3_ServerForeground::Op2Characteristic_WriteRequestedAsync(GattLocalCharacteristic const&, GattWriteRequestedEventArgs args)
00434     {
00435         auto lifetime = get_strong();
00436         auto deferral = args.GetDeferral();
00437
00438         // Get the request information.  This requires device access before an app can access the device's request.
00439         GattWriteRequest request = co_await args.GetRequestAsync();
00440         if (request == nullptr)
00441         {
00442             // No access allowed to the device.  Application should indicate this to the user.
00443         }
00444         else
00445         {
00446             ProcessWriteCharacteristic(request, CalculatorCharacteristics::Operand2);
00447         }
00448         deferral.Complete();
00449     }
00450
00451     fire_and_forget Scenario3_ServerForeground::OperatorCharacteristic_WriteRequestedAsync(GattLocalCharacteristic const&, GattWriteRequestedEventArgs args)
00452     {
00453         auto lifetime = get_strong();
00454         auto deferral = args.GetDeferral();
00455
00456         // Get the request information.  This requires device access before an app can access the device's request.
00457         GattWriteRequest request = co_await args.GetRequestAsync();
00458         if (request == nullptr)
00459         {
00460             // No access allowed to the device.  Application should indicate this to the user.
00461         }
00462         else
00463         {
00464             ProcessWriteCharacteristic(request, CalculatorCharacteristics::Operator);
00465         }
00466         deferral.Complete();
00467     }
00468
00469     void Scenario3_ServerForeground::ProcessWriteCharacteristic(GattWriteRequest const& request, CalculatorCharacteristics opCode)
00470     {
00471         if (request.Value().Length() != 4)
00472         {
00473             // Input is the wrong length. Respond with a protocol error if requested.
00474             if (request.Option() == GattWriteOption::WriteWithResponse)
00475             {
00476                 request.RespondWithProtocolError(GattProtocolError::InvalidAttributeValueLength());
00477             }
00478             return;
00479         }
00480
00481         DataReader reader = DataReader::FromBuffer(request.Value());
00482         reader.ByteOrder(ByteOrder::LittleEndian);
00483         int val = reader.ReadInt32();
00484
00485         switch (opCode)
00486         {
00487         case CalculatorCharacteristics::Operand1:
00488             operand1Received = val;
00489             break;
00490         case CalculatorCharacteristics::Operand2:
00491             operand2Received = val;
00492             break;
00493         case CalculatorCharacteristics::Operator:
00494             if (!IsValidOperator(static_cast<CalculatorOperators>(val)))
00495             {
00496                 if (request.Option() == GattWriteOption::WriteWithResponse)
00497                 {
00498                     request.RespondWithProtocolError(GattProtocolError::InvalidPdu());
00499                 }
00500                 return;
00501             }
00502             operatorReceived = static_cast<CalculatorOperators>(val);
00503             break;
00504         }
00505         // Complete the request if needed
00506         if (request.Option() == GattWriteOption::WriteWithResponse)
00507         {
00508             request.Respond();
00509         }
00510
00511         UpdateUX();
00512     }
00513 }
Generated on Fri Nov 15 2024 22:18:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VeryObservableCollection-g< T > Member List

This is the complete list of members for VeryObservableCollection-g< T >, including all inherited members.
Add(T item) | VeryObservableCollection-g< T > | [inline]
Add(object item) | VeryObservableCollection-g< T > | [inline, private]
Add(T item) | VeryObservableCollection-g< T > | [inline]
Add(object item) | VeryObservableCollection-g< T > | [inline, private]
Clear() | VeryObservableCollection-g< T > | [inline]
Clear() | VeryObservableCollection-g< T > | [inline, private]
Clear() | VeryObservableCollection-g< T > | [inline]
Clear() | VeryObservableCollection-g< T > | [inline, private]
CollectionChanged | VeryObservableCollection-g< T > |
Contains(T item) | VeryObservableCollection-g< T > | [inline]
Contains(object item) | VeryObservableCollection-g< T > | [inline, private]
Contains(T item) | VeryObservableCollection-g< T > | [inline]
Contains(object item) | VeryObservableCollection-g< T > | [inline, private]
CopyTo(T[] array, int arrayIndex) | VeryObservableCollection-g< T > | [inline]
CopyTo(Array dest, int index) | VeryObservableCollection-g< T > | [inline, private]
CopyTo(T[] array, int arrayIndex) | VeryObservableCollection-g< T > | [inline]
CopyTo(Array dest, int index) | VeryObservableCollection-g< T > | [inline, private]
Count | VeryObservableCollection-g< T > |
Count | VeryObservableCollection-g< T > | [private]
data | VeryObservableCollection-g< T > | [private]
Data_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) | VeryObservableCollection-g< T > | [inline, private]
Data_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) | VeryObservableCollection-g< T > | [inline, private]
GetEnumerator() | VeryObservableCollection-g< T > | [inline]
GetEnumerator() | VeryObservableCollection-g< T > | [inline, private]
GetEnumerator() | VeryObservableCollection-g< T > | [inline]
GetEnumerator() | VeryObservableCollection-g< T > | [inline, private]
IndexOf(T item) | VeryObservableCollection-g< T > | [inline]
IndexOf(object item) | VeryObservableCollection-g< T > | [inline, private]
IndexOf(T item) | VeryObservableCollection-g< T > | [inline]
IndexOf(object item) | VeryObservableCollection-g< T > | [inline, private]
Insert(int index, T item) | VeryObservableCollection-g< T > | [inline]
Insert(int index, object item) | VeryObservableCollection-g< T > | [inline, private]
Insert(int index, T item) | VeryObservableCollection-g< T > | [inline]
Insert(int index, object item) | VeryObservableCollection-g< T > | [inline, private]
IsFixedSize | VeryObservableCollection-g< T > | [private]
IsReadOnly | VeryObservableCollection-g< T > |
IsReadOnly | VeryObservableCollection-g< T > | [private]
IsSynchronized | VeryObservableCollection-g< T > | [private]
Remove(T item) | VeryObservableCollection-g< T > | [inline]
Remove(object item) | VeryObservableCollection-g< T > | [inline, private]
Remove(T item) | VeryObservableCollection-g< T > | [inline]
Remove(object item) | VeryObservableCollection-g< T > | [inline, private]
RemoveAt(int index) | VeryObservableCollection-g< T > | [inline]
RemoveAt(int index) | VeryObservableCollection-g< T > | [inline, private]
RemoveAt(int index) | VeryObservableCollection-g< T > | [inline]
RemoveAt(int index) | VeryObservableCollection-g< T > | [inline, private]
SyncRoot | VeryObservableCollection-g< T > | [private]
this | VeryObservableCollection-g< T > |
this | VeryObservableCollection-g< T > | [private]
VectorChanged | VeryObservableCollection-g< T > |
VeryObservableCollection() | VeryObservableCollection-g< T > | [inline]
VeryObservableCollection() | VeryObservableCollection-g< T > | [inline]
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_NetworkCost Member List

This is the complete list of members for Scenario2_NetworkCost, including all inherited members.
GetNetworkCost_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_NetworkCost
Scenario2_NetworkCost() | Scenario2_NetworkCost
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cs/AdventureWorks/ViewModel/ViewModelBase.cs Source File

  • CortanaVoiceCommand
  • cs
  • AdventureWorks
  • ViewModel

ViewModelBase.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.ComponentModel;
00013
00014 namespace AdventureWorks.ViewModel
00015 {
00016     /// <summary>
00017     /// Base class for all view models. Contains the common implementation of
00018     /// INotifyPropertyChanged and the notification helper method.
00019     /// </summary>
00020     public class ViewModelBase : INotifyPropertyChanged
00021     {
00022         /// <summary>
00023         /// Views subscribe to this event to get notified of property updates.
00024         /// </summary>
00025         public event PropertyChangedEventHandler PropertyChanged;
00026
00027         /// <summary>
00028         /// Notify subscribers of updates to the named property
00029         /// </summary>
00030         /// <param name="propertyName">The full, case-sensitive, name of a property.</param>
00031         protected void NotifyPropertyChanged(string propertyName)
00032         {
00033             PropertyChangedEventHandler handler = this.PropertyChanged;
00034             if (handler != null)
00035             {
00036                 PropertyChangedEventArgs args = new PropertyChangedEventArgs(propertyName);
00037
00038                 handler(this, args);
00039             }
00040         }
00041     }
00042 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cs/ShareFiles.xaml.cs Source File

  • ShareSource
  • cs

ShareFiles.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.ApplicationModel.DataTransfer;
00015 using Windows.Storage;
00016 using Windows.Storage.Pickers;
00017 using Windows.UI.Xaml;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class ShareFiles
00022     {
00023         private IReadOnlyList<StorageFile> storageItems;
00024
00025         public ShareFiles()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         protected override bool GetShareContent(DataRequest request)
00031         {
00032             bool succeeded = false;
00033
00034             if (storageItems != null)
00035             {
00036                 DataPackage requestData = request.Data;
00037                 requestData.Properties.Title = TitleInputBox.Text;
00038                 requestData.Properties.Description = DescriptionInputBox.Text; // The description is optional.
00039                 requestData.Properties.ContentSourceApplicationLink = ApplicationLink;
00040                 requestData.SetStorageItems(this.storageItems);
00041                 succeeded = true;
00042             }
00043             else
00044             {
00045                 request.FailWithDisplayText("Select the files you would like to share and try again.");
00046             }
00047             return succeeded;
00048         }
00049
00050         private async void SelectFilesButton_Click(object sender, RoutedEventArgs e)
00051         {
00052             FileOpenPicker filePicker = new FileOpenPicker
00053             {
00054                 ViewMode = PickerViewMode.List,
00055                 SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
00056                 FileTypeFilter = { "*" }
00057             };
00058
00059             IReadOnlyList<StorageFile> pickedFiles = await filePicker.PickMultipleFilesAsync();
00060
00061             if (pickedFiles.Count > 0)
00062             {
00063                 this.storageItems = pickedFiles;
00064
00065                 // Display the file names in the UI.
00066                 string selectedFiles = String.Empty;
00067                 for (int index = 0; index < pickedFiles.Count; index++)
00068                 {
00069                     selectedFiles += pickedFiles[index].Name;
00070
00071                     if (index != (pickedFiles.Count - 1))
00072                     {
00073                         selectedFiles += ", ";
00074                     }
00075                 }
00076                 this.rootPage.NotifyUser("Picked files: " + selectedFiles + ".", NotifyType.StatusMessage);
00077
00078                 ShareStep.Visibility = Visibility.Visible;
00079             }
00080         }
00081     }
00082 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DSvgImage/cpp/D2DSvgImageRenderer.cpp Source File

  • D2DSvgImage
  • cpp

D2DSvgImageRenderer.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "D2DSvgImageRenderer.h"
00014 #include "DirectXPage.xaml.h"
00015 #include "Common\DirectXHelper.h"
00016
00017 using namespace SDKTemplate;
00018
00019 using namespace concurrency;
00020 using namespace DirectX;
00021 using namespace Microsoft::WRL;
00022 using namespace Platform;
00023 using namespace std;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Windows::Graphics::Display;
00027 using namespace Windows::Storage;
00028 using namespace Windows::Storage::Streams;
00029 using namespace Windows::UI::Input;
00030
00031 static const float sc_svgSize = 500.0f;
00032
00033 D2DSvgImageRenderer::D2DSvgImageRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00034     m_deviceResources(deviceResources),
00035     m_scaleValue(1.0f),
00036     m_isWindowClosed(false)
00037 {
00038     // Register to be notified if the GPU device is lost or recreated.
00039     m_deviceResources->RegisterDeviceNotify(this);
00040
00041     CreateDeviceIndependentResources();
00042     CreateDeviceDependentResources();
00043     CreateWindowSizeDependentResources();
00044 }
00045
00046 D2DSvgImageRenderer::~D2DSvgImageRenderer()
00047 {
00048     // Deregister device notification.
00049     m_deviceResources->RegisterDeviceNotify(nullptr);
00050 }
00051
00052 void D2DSvgImageRenderer::CreateDeviceIndependentResources()
00053 {
00054 }
00055
00056 void D2DSvgImageRenderer::CreateDeviceDependentResources()
00057 {
00058     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00059
00060     StorageFolder^ packageFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;
00061
00062     // Retrieve the SVG file from the app package.
00063     create_task(packageFolder->GetFileAsync("Assets\\drawing.svg")).then([=](StorageFile^ file)
00064     {
00065         // Open the SVG file for reading.
00066         return file->OpenAsync(FileAccessMode::Read);
00067
00068     }).then([=](IRandomAccessStream^ stream)
00069     {
00070         // Wrap the WinRT stream with a COM stream.
00071         ComPtr<IStream> iStream;
00072         DX::ThrowIfFailed(
00073             CreateStreamOverRandomAccessStream(
00074                 stream,
00075                 IID_PPV_ARGS(&iStream)
00076                 )
00077             );
00078
00079         // Parse the file stream into an SVG document.
00080         DX::ThrowIfFailed(
00081             d2dContext->CreateSvgDocument(
00082                 iStream.Get(),
00083                 D2D1::SizeF(sc_svgSize, sc_svgSize), // Create the document at a size of 500x500 DIPs.
00084                 &m_svgDocument
00085                 )
00086             );
00087     });
00088 }
00089
00090 void D2DSvgImageRenderer::ReleaseDeviceDependentResources()
00091 {
00092     m_svgDocument.Reset();
00093 }
00094
00095 void D2DSvgImageRenderer::CreateWindowSizeDependentResources()
00096 {
00097 }
00098
00099 void D2DSvgImageRenderer::Draw()
00100 {
00101     ID2D1DeviceContext5* d2dContext = m_deviceResources->GetD2DDeviceContext();
00102     Size logicalSize = m_deviceResources->GetLogicalSize();
00103
00104     d2dContext->BeginDraw();
00105
00106     d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
00107
00108     // DeviceResources explicitly handles screen rotation by setting the rotation on the swap chain.
00109     // In order for Direct2D content to appear correctly on this swap chain, the app is responsible for
00110     // explicitly "prerotating" by setting the appropriate transform before drawing.
00111     D2D1_MATRIX_3X2_F transform = m_deviceResources->GetOrientationTransform2D();
00112
00113     // Also perform a translation to center the SVG image in the window.
00114     transform = transform * D2D1::Matrix3x2F::Translation(
00115         (logicalSize.Width - sc_svgSize) / 2.0f,
00116         (logicalSize.Height - sc_svgSize) / 2.0f
00117         );
00118
00119     // Also perform a scale based on the current slider value.
00120     transform = transform * D2D1::Matrix3x2F::Scale(
00121         m_scaleValue,
00122         m_scaleValue,
00123         D2D1::Point2F(
00124             logicalSize.Width / 2.0f,
00125             logicalSize.Height / 2.0f
00126             )
00127         );
00128
00129     m_deviceResources->GetD2DDeviceContext()->SetTransform(transform);
00130
00131     if (m_svgDocument)
00132     {
00133         // Draw the SVG document.
00134         d2dContext->DrawSvgDocument(m_svgDocument.Get());
00135     }
00136
00137     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00138     // is lost. It will be handled during the next call to Present.
00139     HRESULT hr = d2dContext->EndDraw();
00140     if (hr != D2DERR_RECREATE_TARGET)
00141     {
00142         DX::ThrowIfFailed(hr);
00143     }
00144
00145     m_deviceResources->Present();
00146 }
00147
00148 // Performs a rudimentary recoloring of the renderer's SVG document using
00149 // Direct2D's SVG OM APIs. Recursively walks the SVG tree and changes the
00150 // "fill" property of any non-black nodes to the specified new color.
00151 void D2DSvgImageRenderer::RecolorSvg(D2D1_COLOR_F newColor)
00152 {
00153     if (m_svgDocument)
00154     {
00155         // Retrieve the root element of the SVG document.
00156         ComPtr<ID2D1SvgElement> root;
00157         m_svgDocument->GetRoot(&root);
00158
00159         // Recursively recolor the tree, beginning at the root.
00160         RecolorSubtree(root.Get(), newColor);
00161     }
00162 }
00163
00164 // Helper method for RecolorSvg which recursively recolors the given subtree of SVG document using
00165 // the given color.
00166 void D2DSvgImageRenderer::RecolorSubtree(ID2D1SvgElement* element, D2D1_COLOR_F newColor)
00167 {
00168     // Check if this SVG element has a "fill" element explicitly specified or inherited.
00169     if (element->IsAttributeSpecified(L"fill"))
00170     {
00171         // Retrieve the value of this element's "fill" attribute, as a paint object.
00172         ComPtr<ID2D1SvgPaint> paint;
00173         DX::ThrowIfFailed(element->GetAttributeValue(L"fill", &paint));
00174
00175         // Check the type of paint object that was set. There are different types of
00176         // paints, such as plain colors, URLs, or the 'none' type. For this app we
00177         // only want to modify fills that were set to a specific color.
00178         D2D1_SVG_PAINT_TYPE paintType = paint->GetPaintType();
00179         if (paintType == D2D1_SVG_PAINT_TYPE_COLOR)
00180         {
00181             // Retrieve the color of this paint.
00182             D2D1_COLOR_F oldColor;
00183             paint->GetColor(&oldColor);
00184
00185             // If the old color not black, change it to newColor.
00186             if (oldColor.r != 0.0f || oldColor.g != 0.0f || oldColor.b != 0.0f)
00187             {
00188                 // Attributes that are returned as an interface (such as ID2D1SvgPaint)
00189                 // are returned by reference, rather than by value. This means that
00190                 // modifying them (such as by calling SetColor, below) directly modifies
00191                 // the SVG document, without needing to call SetAttributeValue.
00192                 DX::ThrowIfFailed(paint->SetColor(newColor));
00193             }
00194         }
00195     }
00196
00197     // Now, iterate through any child nodes of this SVG element and recursively recolor them.
00198
00199     // Retrieve the first child of the current element, if it has any.
00200     ComPtr<ID2D1SvgElement> child;
00201     element->GetFirstChild(&child);
00202
00203     while (child != nullptr)
00204     {
00205         // Recursively recolor the subtree starting with this child node.
00206         RecolorSubtree(child.Get(), newColor);
00207
00208         // Retrieve the next child, if any.
00209         ComPtr<ID2D1SvgElement> nextChild;
00210         element->GetNextChild(child.Get(), &nextChild);
00211
00212         // Move to the next child.
00213         child = nextChild;
00214     }
00215 }
00216
00217 // Performs a rudimentary SVG OM operation on the renderer's SVG document
00218 // to toggle the visibility of the element in the SVG drawing with the
00219 // identifier "tongue".
00220 void D2DSvgImageRenderer::ToggleTongue()
00221 {
00222     if (m_svgDocument)
00223     {
00224         // Retrieve the SVG element with the identifier "tongue". (Open
00225         // drawing.svg to see where this is defined by the SVG author.)
00226         ComPtr<ID2D1SvgElement> tongueElement;
00227         DX::ThrowIfFailed(m_svgDocument->FindElementById(L"tongue", &tongueElement));
00228
00229         // Retrieve the value of the element's "display" attribute.
00230         D2D1_SVG_DISPLAY displayValue;
00231         DX::ThrowIfFailed(tongueElement->GetAttributeValue(L"display", &displayValue));
00232
00233         // Invert the value of the retrieved variable.
00234         if (displayValue == D2D1_SVG_DISPLAY::D2D1_SVG_DISPLAY_NONE)
00235         {
00236             displayValue = D2D1_SVG_DISPLAY::D2D1_SVG_DISPLAY_INLINE;
00237         }
00238         else
00239         {
00240             displayValue = D2D1_SVG_DISPLAY::D2D1_SVG_DISPLAY_NONE;
00241         }
00242
00243         // Attributes that are returned as an enum (such as D2D1_SVG_DISPLAY) are
00244         // returned by value, rather than by reference. This means that in order
00245         // to change the SVG document itself, we must store the modified variable
00246         // back into the SVG document using SetAttributeValue. The new value will
00247         // be used the next time the SVG document is drawn.
00248         DX::ThrowIfFailed(tongueElement->SetAttributeValue(L"display", displayValue));
00249     }
00250 }
00251
00252 void D2DSvgImageRenderer::SetScaleValue(float val)
00253 {
00254     m_scaleValue = val;
00255 }
00256
00257 // Notifies renderers that device resources need to be released.
00258 void D2DSvgImageRenderer::OnDeviceLost()
00259 {
00260     ReleaseDeviceDependentResources();
00261 }
00262
00263 // Notifies renderers that device resources may now be recreated.
00264 void D2DSvgImageRenderer::OnDeviceRestored()
00265 {
00266     CreateDeviceDependentResources();
00267 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cpp/Scenario2_History.xaml.h Source File

  • Pedometer
  • cpp

Scenario2_History.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_History.g.h"
00015 #include <collection.h>
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Represents a history record object that gets binded to the ListView
00022     /// controller in the XAML
00023     /// </summary>
00024     [Windows::UI::Xaml::Data::Bindable]
00025     public ref class HistoryRecord sealed
00026     {
00027     public:
00028         property Platform::String^ TimeStamp
00029         {
00030             Platform::String^ get()
00031             {
00032                 Windows::Globalization::DateTimeFormatting::DateTimeFormatter^ timestampFormatter = ref new Windows::Globalization::DateTimeFormatting::DateTimeFormatter("shortdate longtime");
00033                 return timestampFormatter->Format(recordTimestamp);
00034             }
00035         }
00036
00037         property Platform::String^ StepKind
00038         {
00039             Platform::String^ get()
00040             {
00041                 Platform::String^ stepString = nullptr;
00042                 switch (stepKind)
00043                 {
00044                 case Windows::Devices::Sensors::PedometerStepKind::Unknown:
00045                     stepString = ref new Platform::String(L"Unknown");
00046                     break;
00047                 case Windows::Devices::Sensors::PedometerStepKind::Walking:
00048                     stepString = ref new Platform::String(L"Walking");
00049                     break;
00050                 case Windows::Devices::Sensors::PedometerStepKind::Running:
00051                     stepString = ref new Platform::String(L"Running");
00052                     break;
00053                 default:
00054                     stepString = ref new Platform::String(L"Invalid Step Kind");
00055                     break;
00056                 }
00057                 return stepString;
00058             }
00059         }
00060
00061         property INT32 StepsCount
00062         {
00063             INT32 get()
00064             {
00065                 return stepsCount;
00066             }
00067         }
00068
00069         property long long StepsDuration
00070         {
00071             long long get()
00072             {
00073                 // return Duration in ms
00074                 return (stepsDuration.Duration / 10000);
00075             }
00076         }
00077
00078         HistoryRecord(Windows::Devices::Sensors::PedometerReading^ reading)
00079         {
00080             stepKind = reading->StepKind;
00081             stepsCount = reading->CumulativeSteps;
00082             recordTimestamp.UniversalTime = reading->Timestamp.UniversalTime;
00083         }
00084
00085     private:
00086         Windows::Foundation::DateTime recordTimestamp;
00087         Windows::Devices::Sensors::PedometerStepKind stepKind;
00088         INT32 stepsCount;
00089         Windows::Foundation::TimeSpan stepsDuration;
00090     };
00091
00092     /// <summary>
00093     /// History Page that gets loaded when 'History' scenario is selected.
00094     /// </summary>
00095     [Windows::Foundation::Metadata::WebHostHidden]
00096     public ref class Scenario2_History sealed
00097     {
00098     public:
00099         Scenario2_History();
00100     private:
00101         void AllHistory_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00102         void SpecificHistory_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00103         void GetHistory_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00104
00105         SDKTemplate::MainPage^ rootPage;
00106         Windows::Devices::Enumeration::DeviceAccessInformation^ deviceAccessInfo;
00107         bool getAllHistory;
00108         Platform::Collections::Vector<HistoryRecord>^ recordCollection;
00109         Platform::Collections::Vector<HistoryRecord^> ^historyRecords;
00110     };
00111 }
Generated on Fri Nov 15 2024 22:17:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_DevicePicker Member List

This is the complete list of members for Scenario1_DevicePicker, including all inherited members.
OnNavigatedTo(NavigationEventArgs e) | Scenario1_DevicePicker | [inline, protected]
PickSingleDeviceButton_Click(object sender, RoutedEventArgs e) | Scenario1_DevicePicker | [inline, private]
resultCollection | Scenario1_DevicePicker | [private]
rootPage | Scenario1_DevicePicker | [private]
Scenario1_DevicePicker() | Scenario1_DevicePicker | [inline]
ShowDevicePicker(bool pickSingle) | Scenario1_DevicePicker | [inline, private]
ShowDevicePickerButton_Click(object sender, RoutedEventArgs e) | Scenario1_DevicePicker | [inline, private]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cs/LoggingScenarioEventArgs.cs Source File

  • Logging
  • cs

LoggingScenarioEventArgs.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using System;
00008
00009 namespace SDKTemplate
00010 {
00011     /// <summary>
00012     /// LoggingScenario tells the UI what's happening by
00013     /// using the following enums.
00014     /// </summary>
00015     enum LoggingScenarioEventType
00016     {
00017         BusyStatusChanged,
00018         LogFileGenerated,
00019         LogFileGeneratedAtDisable,
00020         LogFileGeneratedAtSuspend,
00021         LoggingEnabledDisabled
00022     }
00023
00024     class LoggingScenarioEventArgs : EventArgs
00025     {
00026         public LoggingScenarioEventArgs(LoggingScenarioEventType type)
00027         {
00028             Type = type;
00029         }
00030
00031         public LoggingScenarioEventArgs(LoggingScenarioEventType type, string logFilePath)
00032         {
00033             Type = type;
00034             LogFilePath = logFilePath;
00035         }
00036
00037         public LoggingScenarioEventArgs(bool enabled)
00038         {
00039             Type = LoggingScenarioEventType.LoggingEnabledDisabled;
00040             Enabled = enabled;
00041         }
00042
00043         public LoggingScenarioEventType Type { get; private set; }
00044         public string LogFilePath { get; private set; }
00045         public bool Enabled { get; private set; }
00046     }
00047 }
Generated on Fri Nov 15 2024 22:20:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/GameRenderer.h Source File

  • Simple3DGameXaml
  • cpp

GameRenderer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // GameRenderer:
00015 // This is the renderer for the game.
00016 // It is responsble for creating and maintaining all the D3D11 and D2D objects
00017 // used to generate the game visuals.  It maintains a reference to the Simple3DGame
00018 // object to retrieve the list of objects to render as well as status of the
00019 // game for the Heads Up Display (HUD).
00020 //
00021 // The renderer is designed to use a standard vertex layout across all objects.  This
00022 // simplifies the shader design and allows for easy changes between shaders independent
00023 // of the objects' geometry.  Each vertex is defined by a position, a normal and one set of
00024 // 2D texture coordinates.  The shaders all expect one 2D texture and 4 constant buffers:
00025 //     m_constantBufferNeverChanges - general parameters that are set only once.  This includes
00026 //         all the lights used in scene generation.
00027 //     m_constantBufferChangeOnResize - the projection matrix.  It is typically only changed when
00028 //         the window is resized, however it will be changed 2x per frame when rendering
00029 //         in 3D stereo.
00030 //     m_constantBufferChangesEveryFrame - the view transformation matrix.  This is set once per frame.
00031 //     m_constantBufferChangesEveryPrim - the parameters for each object.  It includes the object to world
00032 //         transformation matrix as well as material properties like color and specular exponent for lighting
00033 //         calculations.
00034 //
00035 // The renderer also maintains a set of texture resources that will be associated with particular game objects.
00036 // It knows which textures are to be associated with which objects and will do that association once the
00037 // textures have been loaded.
00038 //
00039 // The renderer provides a set of methods to allow for a "standard" sequence to be executed for loading general
00040 // game resources and for level specific resources.  Because D3D11 allows free threaded creation of objects,
00041 // textures will be loaded asynchronously and in parallel, however D3D11 does not allow for multiple threads to
00042 // be using the DeviceContext at the same time.
00043 //
00044 // The pattern is:
00045 //     create_task([this]()
00046 //     {
00047 //         // create/load device resources
00048 //     }).then([this]()
00049 //     {
00050 //         // create/load device context resources
00051 //     }, task_continuation_context::use_current());
00052
00053 #include "DeviceResources.h"
00054 #include "GameHud.h"
00055 #include "Simple3DGame.h"
00056
00057 ref class Simple3DGame;
00058 ref class GameHud;
00059
00060 ref class GameRenderer
00061 {
00062 internal:
00063     GameRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00064
00065     void CreateDeviceDependentResources();
00066     void CreateWindowSizeDependentResources();
00067     void ReleaseDeviceDependentResources();
00068     void Render();
00069
00070     concurrency::task<void> CreateGameDeviceResourcesAsync(_In_ Simple3DGame^ game);
00071     void FinalizeCreateGameDeviceResources();
00072     concurrency::task<void> LoadLevelResourcesAsync();
00073     void FinalizeLoadLevelResources();
00074
00075     void SetBackground(uint32 background);
00076
00077     GameHud^ Hud() { return m_gameHud; }
00078
00079 #if defined(_DEBUG)
00080     void ReportLiveDeviceObjects();
00081 #endif
00082
00083 protected private:
00084     // Cached pointer to device resources.
00085     std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00086
00087     bool                                                m_initialized;
00088     bool                                                m_gameResourcesLoaded;
00089     bool                                                m_levelResourcesLoaded;
00090     GameHud^                                            m_gameHud;
00091     Simple3DGame^                                       m_game;
00092
00093     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_sphereTexture;
00094     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_cylinderTexture;
00095     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_ceilingTexture[GameConstants::MaxBackgroundTextures];
00096     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_floorTexture[GameConstants::MaxBackgroundTextures];
00097     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_wallsTexture[GameConstants::MaxBackgroundTextures];
00098
00099     // Constant Buffers
00100     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBufferNeverChanges;
00101     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBufferChangeOnResize;
00102     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBufferChangesEveryFrame;
00103     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBufferChangesEveryPrim;
00104     Microsoft::WRL::ComPtr<ID3D11SamplerState>          m_samplerLinear;
00105     Microsoft::WRL::ComPtr<ID3D11VertexShader>          m_vertexShader;
00106     Microsoft::WRL::ComPtr<ID3D11VertexShader>          m_vertexShaderFlat;
00107     Microsoft::WRL::ComPtr<ID3D11PixelShader>           m_pixelShader;
00108     Microsoft::WRL::ComPtr<ID3D11PixelShader>           m_pixelShaderFlat;
00109     Microsoft::WRL::ComPtr<ID3D11InputLayout>           m_vertexLayout;
00110 };
Generated on Fri Nov 15 2024 22:21:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cpp/BackgroundTransfer/Scenario3_Notifications.xaml.h Source File

  • BackgroundTransfer
  • cpp
  • BackgroundTransfer

Scenario3_Notifications.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario3_Notifications.xaml.h
00014 // Declaration of the Scenario3_Notifications class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario3_Notifications.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario3_Notifications sealed
00030     {
00031     public:
00032         Scenario3_Notifications();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036
00037     private:
00038         SDKTemplate::MainPage^ rootPage;
00039         Windows::Networking::BackgroundTransfer::BackgroundTransferGroup^ notificationsGroup;
00040
00041         static UINT32 runId;
00042
00043         static const UINT64 tenMinutesIn100NanoSecondUnits = 6000000000;
00044
00045         enum ScenarioType
00046         {
00047             Toast,
00048             Tile
00049         };
00050
00051         void ToastNotificationButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00052         void TileNotificationButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00053
00054         void RunDownloads(
00055             Windows::Networking::BackgroundTransfer::BackgroundDownloader^ downloader,
00056             ScenarioType type);
00057         bool TryCreateDownloadAsync(
00058             Windows::Networking::BackgroundTransfer::BackgroundDownloader^ downloader,
00059             UINT8 delaySeconds,
00060             Platform::String^ fileNameSuffix,
00061             ScenarioType type,
00062             Platform::Collections::Vector<Windows::Networking::BackgroundTransfer::DownloadOperation^>^ downloadOperations,
00063             Concurrency::task<void>& resultTask);
00064         void RunDownload(Windows::Networking::BackgroundTransfer::DownloadOperation^ download);
00065         void CancelActiveDownloads();
00066         void LogException(
00067             Platform::String^ title,
00068             Platform::Exception^ ex,
00069             Windows::Networking::BackgroundTransfer::DownloadOperation^ download = nullptr);
00070         void Log(Platform::String^ message);
00071         void LogStatus(Platform::String^ message, SDKTemplate::NotifyType type);
00072
00073         ~Scenario3_Notifications();
00074     };
00075 }
Generated on Fri Nov 15 2024 22:18:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInteractionMode/cpp/Scenario1_Basic.xaml.cpp Source File

  • UserInteractionMode
  • cpp

Scenario1_Basic.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_Basic.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Core;
00020 using namespace Windows::UI::ViewManagement;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Input;
00024
00025 Scenario1_Basic::Scenario1_Basic() : rootPage(MainPage::Current)
00026 {
00027     InitializeComponent();
00028 }
00029
00030 void Scenario1_Basic::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00031 {
00032     // The SizeChanged event is raised when the user interaction mode changes.
00033     windowResizeToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &Scenario1_Basic::OnWindowResize);
00034     UpdateContent();
00035 }
00036
00037 void Scenario1_Basic::OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00038 {
00039     Window::Current->SizeChanged -= windowResizeToken;
00040 }
00041
00042 void Scenario1_Basic::OnWindowResize(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00043 {
00044     UpdateContent();
00045 }
00046
00047 void Scenario1_Basic::UpdateContent()
00048 {
00049     InteractionMode = UIViewSettings::GetForCurrentView()->UserInteractionMode;
00050
00051     // Update styles
00052     CheckBoxStyle = InteractionMode == UserInteractionMode::Mouse ? MouseCheckBoxStyle : TouchCheckBoxStyle;
00053 }
Generated on Fri Nov 15 2024 22:19:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MobileHotspot/cppwinrt/Scenario1_ConfigureMobileHotspot.cpp Source File

  • MobileHotspot
  • cppwinrt

Scenario1_ConfigureMobileHotspot.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_ConfigureMobileHotspot.h"
00014 #include "Scenario1_ConfigureMobileHotspot.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::Networking::Connectivity;
00020 using namespace Windows::Networking::NetworkOperators;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario1_ConfigureMobileHotspot::Scenario1_ConfigureMobileHotspot()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     void Scenario1_ConfigureMobileHotspot::OnNavigatedTo(NavigationEventArgs const&)
00033     {
00034         m_tetheringManager = SDKTemplate::TryGetCurrentNetworkOperatorTetheringManager();
00035
00036         if (m_tetheringManager)
00037         {
00038             InitializeTetheringControls();
00039             HotspotPanel().Visibility(Visibility::Visible);
00040         }
00041     }
00042
00043     void Scenario1_ConfigureMobileHotspot::AddComboBoxItem(ComboBox const& comboBox, hstring name, IInspectable const& tag, bool selected)
00044     {
00045         ComboBoxItem item;
00046         item.Tag(tag);
00047         item.Content(box_value(name));
00048         comboBox.Items().Append(item);
00049         if (selected)
00050         {
00051             comboBox.SelectedItem(item);
00052         }
00053     }
00054
00055     void Scenario1_ConfigureMobileHotspot::InitializeTetheringControls()
00056     {
00057         NetworkOperatorTetheringAccessPointConfiguration configuration = m_tetheringManager.GetCurrentAccessPointConfiguration();
00058
00059         SsidTextBox().Text(configuration.Ssid());
00060         PassphraseTextBox().Text(configuration.Passphrase());
00061
00062         // Fill the Band combo box with supported bands, and select the current one.
00063         TetheringWiFiBand currentBand = configuration.Band();
00064         BandComboBox().Items().Clear();
00065         for (TetheringWiFiBand band = TetheringWiFiBand::Auto; band <= TetheringWiFiBand::FiveGigahertz; band = (TetheringWiFiBand)((int)band + 1))
00066         {
00067             if (SDKTemplate::IsBandSupported(configuration, band))
00068             {
00069                 AddComboBoxItem(BandComboBox(), band, band == currentBand);
00070             }
00071         }
00072         if (BandComboBox().SelectedIndex() == -1)
00073         {
00074             AddComboBoxItem(BandComboBox(), currentBand, true);
00075         }
00076     }
00077
00078     fire_and_forget Scenario1_ConfigureMobileHotspot::ApplyChanges_Click(IInspectable const&, RoutedEventArgs const& e)
00079     {
00080         if (m_applying)
00081         {
00082             co_return;
00083
00084         }
00085         m_applying = true;
00086
00087         NetworkOperatorTetheringAccessPointConfiguration configuration = m_tetheringManager.GetCurrentAccessPointConfiguration();
00088
00089         configuration.Ssid(SsidTextBox().Text());
00090         configuration.Passphrase(PassphraseTextBox().Text());
00091         configuration.Band(BandComboBox().SelectedItem().as<ComboBoxItem>().Tag().as<TetheringWiFiBand>());
00092
00093         co_await m_tetheringManager.ConfigureAccessPointAsync(configuration);
00094         m_applying = false;
00095
00096         InitializeTetheringControls();
00097     }
00098
00099     void Scenario1_ConfigureMobileHotspot::DiscardChanges_Click(IInspectable const&, RoutedEventArgs const&)
00100     {
00101         InitializeTetheringControls();
00102     }
00103 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cppwinrt/SampleConfiguration.cpp Source File

  • PenHaptics
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation::Collections;
00019 using namespace winrt::Windows::Devices::Haptics;
00020 using namespace winrt::SDKTemplate;
00021
00022 hstring implementation::MainPage::FEATURE_NAME()
00023 {
00024     return L"PenHaptics C++/WinRT Sample";
00025 }
00026
00027 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00028 {
00029     Scenario{ L"Ink Canvas Tactile Feedback", xaml_typename<SDKTemplate::Scenario1_InkCanvasTactileFeedback>() },
00030     Scenario{ L"Query Tactile Feedback Support", xaml_typename<SDKTemplate::Scenario2_SupportedTactileFeedback>() },
00031     Scenario{ L"Inking Feedback", xaml_typename<SDKTemplate::Scenario3_InkingFeedback>() },
00032     Scenario{ L"Interaction Feedback", xaml_typename<SDKTemplate::Scenario4_InteractionFeedback>() },
00033     Scenario{ L"Inking and Interaction Feedback", xaml_typename<SDKTemplate::Scenario5_InkingAndInteractionFeedback>() },
00034 });
00035
00036 std::map<hstring, uint16_t> const& SDKTemplate::WaveformNamesMap()
00037 {
00038     static const std::map<winrt::hstring, uint16_t> map
00039     {
00040         { L"BrushContinuous", KnownSimpleHapticsControllerWaveforms::BrushContinuous() },
00041         { L"BuzzContinuous", KnownSimpleHapticsControllerWaveforms::BuzzContinuous() },
00042         { L"ChiselMarkerContinuous", KnownSimpleHapticsControllerWaveforms::ChiselMarkerContinuous() },
00043         { L"Click", KnownSimpleHapticsControllerWaveforms::Click() },
00044         { L"EraserContinuous", KnownSimpleHapticsControllerWaveforms::EraserContinuous() },
00045         { L"Error", KnownSimpleHapticsControllerWaveforms::Error() },
00046         { L"GalaxyPenContinuous", KnownSimpleHapticsControllerWaveforms::GalaxyPenContinuous() },
00047         { L"Hover", KnownSimpleHapticsControllerWaveforms::Hover() },
00048         { L"InkContinuous", KnownSimpleHapticsControllerWaveforms::InkContinuous() },
00049         { L"MarkerContinuous", KnownSimpleHapticsControllerWaveforms::MarkerContinuous() },
00050         { L"PencilContinuous", KnownSimpleHapticsControllerWaveforms::PencilContinuous() },
00051         { L"Press", KnownSimpleHapticsControllerWaveforms::Press() },
00052         { L"Release", KnownSimpleHapticsControllerWaveforms::Release() },
00053         { L"RumbleContinuous", KnownSimpleHapticsControllerWaveforms::RumbleContinuous() },
00054         { L"Success", KnownSimpleHapticsControllerWaveforms::Success() },
00055     };
00056     return map;
00057 }
00058
00059 SimpleHapticsControllerFeedback SDKTemplate::FindSupportedFeedback(SimpleHapticsController const& hapticsController, uint16_t waveform)
00060 {
00061     for (auto&& feedback : hapticsController.SupportedFeedback())
00062     {
00063         if (feedback.Waveform() == waveform)
00064         {
00065             return feedback;
00066         }
00067     }
00068     return nullptr;
00069 }
Generated on Fri Nov 15 2024 22:17:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario04_PostText Member List

This is the complete list of members for Scenario04_PostText, including all inherited members.
Cancel_Click(object sender, RoutedEventArgs e) | Scenario04_PostText | [inline, private]
cts | Scenario04_PostText | [private]
httpClient | Scenario04_PostText | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario04_PostText | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario04_PostText | [inline, protected]
rootPage | Scenario04_PostText | [private]
Scenario04_PostText() | Scenario04_PostText | [inline]
Start_Click(object sender, RoutedEventArgs e) | Scenario04_PostText | [inline, private]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationData/cs/Scenario1_Files.xaml.cs Source File

  • ApplicationData
  • cs

Scenario1_Files.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using Windows.Storage;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario1_Files : Page
00020     {
00021         StorageFolder localFolder = ApplicationData.Current.LocalFolder;
00022         int localCounter = 0;
00023         StorageFolder localCacheFolder = ApplicationData.Current.LocalCacheFolder;
00024         int localCacheCounter = 0;
00025         StorageFolder temporaryFolder = ApplicationData.Current.TemporaryFolder;
00026         int temporaryCounter = 0;
00027
00028         const string filename = "sampleFile.txt";
00029
00030         public Scenario1_Files()
00031         {
00032             InitializeComponent();
00033         }
00034
00035         // Guidance for Local, LocalCache, and Temporary files.
00036         //
00037         // Files are ideal for storing large data-sets, databases, or data that is
00038         // in a common file-format.
00039         //
00040         // Files can exist in either the Local, LocalCache, or Temporary folders.
00041         // (They can also be put in Roaming folders, but the data no longer roams.)
00042         //
00043         // Local files are not synchronized, but they are backed up, and can then be restored to a
00044         // machine different than where they were originally written. These should be for
00045         // important files that allow the feel that the user did not lose anything
00046         // when they restored to a new device.
00047         //
00048         // Temporary files are subject to deletion when not in use.  The system
00049         // considers factors such as available disk capacity and the age of a file when
00050         // determining when or whether to delete a temporary file.
00051         //
00052         // LocalCache files are for larger files that can be recreated by the app, and for
00053         // machine specific or private files that should not be restored to a new device.
00054
00055         async void Increment_Local_Click(Object sender, RoutedEventArgs e)
00056         {
00057             localCounter++;
00058
00059             StorageFile file = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
00060             await FileIO.WriteTextAsync(file, localCounter.ToString());
00061
00062             Read_Local_Counter();
00063         }
00064
00065         async void Read_Local_Counter()
00066         {
00067             StorageFile file = (await localFolder.TryGetItemAsync(filename)) as StorageFile;
00068             if (file != null)
00069             {
00070                 string text = await FileIO.ReadTextAsync(file);
00071
00072                 LocalOutputTextBlock.Text = "Local Counter: " + text;
00073
00074                 localCounter = int.Parse(text);
00075             }
00076             else
00077             {
00078                 LocalOutputTextBlock.Text = "Local Counter: <not found>";
00079             }
00080         }
00081
00082         async void Increment_LocalCache_Click(Object sender, RoutedEventArgs e)
00083         {
00084             localCacheCounter++;
00085
00086             StorageFile file = await localCacheFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
00087             await FileIO.WriteTextAsync(file, localCacheCounter.ToString());
00088
00089             Read_LocalCache_Counter();
00090         }
00091
00092         async void Read_LocalCache_Counter()
00093         {
00094             StorageFile file = (await localCacheFolder.TryGetItemAsync(filename)) as StorageFile;
00095             if (file != null)
00096             {
00097                 string text = await FileIO.ReadTextAsync(file);
00098
00099                 LocalCacheOutputTextBlock.Text = "LocalCache Counter: " + text;
00100
00101                 localCacheCounter = int.Parse(text);
00102             }
00103             else
00104             {
00105                 LocalCacheOutputTextBlock.Text = "LocalCache Counter: <not found>";
00106             }
00107         }
00108
00109         async void Increment_Temporary_Click(Object sender, RoutedEventArgs e)
00110         {
00111             temporaryCounter++;
00112
00113             StorageFile file = await temporaryFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
00114             await FileIO.WriteTextAsync(file, temporaryCounter.ToString());
00115
00116             Read_Temporary_Counter();
00117         }
00118
00119         async void Read_Temporary_Counter()
00120         {
00121             StorageFile file = (await temporaryFolder.TryGetItemAsync(filename)) as StorageFile;
00122             if (file != null)
00123             {
00124                 string text = await FileIO.ReadTextAsync(file);
00125
00126                 TemporaryOutputTextBlock.Text = "Temporary Counter: " + text;
00127
00128                 temporaryCounter = int.Parse(text);
00129             }
00130             else
00131             {
00132                 TemporaryOutputTextBlock.Text = "Temporary Counter: <not found>";
00133             }
00134         }
00135
00136         void DisplayOutput()
00137         {
00138             Read_Local_Counter();
00139             Read_LocalCache_Counter();
00140             Read_Temporary_Counter();
00141         }
00142
00143         protected override void OnNavigatedTo(NavigationEventArgs e)
00144         {
00145             DisplayOutput();
00146         }
00147     }
00148 }
Generated on Fri Nov 15 2024 22:17:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomHidDeviceAccess/cpp/DeviceListEntry.cpp Source File

  • CustomHidDeviceAccess
  • cpp

DeviceListEntry.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include "pch.h"
00008 #include "DeviceListEntry.h"
00009
00010 using namespace SDKTemplate;
00011
00012 using namespace Platform;
00013
00014 namespace SDKTemplate
00015 {
00016     String^ DeviceListEntry::InstanceId::get(void)
00017     {
00018         return static_cast<String^>(device->Properties->Lookup(const_cast<String^>(DeviceProperties::DeviceInstanceId)));
00019     }
00020
00021     /// <summary>
00022     /// The class is mainly used as a DeviceInformation wrapper so that the UI can bind to a list of these.
00023     /// </summary>
00024     /// <param name="deviceInformation"></param>
00025     /// <param name="deviceSelector">The AQS used to find this device</param>
00026     DeviceListEntry::DeviceListEntry(Windows::Devices::Enumeration::DeviceInformation^ deviceInformation, String^ deviceSelector) :
00027         device(deviceInformation),
00028         deviceSelector(deviceSelector)
00029     {
00030     }
00031 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CSchemeHandler Member List

This is the complete list of members for CSchemeHandler, including all inherited members.
BeginCreateObject(_In_ LPCWSTR pwszURL, _In_ DWORD dwFlags, _In_ IPropertyStore *pProps, _COM_Outptr_opt_ IUnknown **ppIUnknownCancelCookie, _In_ IMFAsyncCallback *pCallback, _In_ IUnknown *punkState) | CSchemeHandler | [private]
CancelObjectCreation(_In_ IUnknown *pIUnknownCancelCookie) | CSchemeHandler | [private]
EndCreateObject(_In_ IMFAsyncResult *pResult, _Out_ MF_OBJECT_TYPE *pObjectType, _Out_ IUnknown **ppObject) | CSchemeHandler | [private]
SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration) | CSchemeHandler | [private]
~CSchemeHandler(void) | CSchemeHandler | [private]
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SocketWrapper Member List

This is the complete list of members for SocketWrapper, including all inherited members.
datagramSocket | SocketWrapper | [private]
Dispose() | SocketWrapper | [inline]
Dispose(bool disposing) | SocketWrapper | [inline, protected, virtual]
disposed | SocketWrapper | [private]
HandleReceivedMessage(DataReader datareader, bool load=true) | SocketWrapper | [inline, private]
manager | SocketWrapper | [private]
OnUDPMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) | SocketWrapper | [inline, private]
Port | SocketWrapper |
Protocol | SocketWrapper |
reader | SocketWrapper | [private]
ReceiveMessageAsync() | SocketWrapper | [inline]
SendMessageAsync(string message) | SocketWrapper | [inline]
SocketWrapper(WiFiDirectServiceManager manager, StreamSocket streamSocket=null, DatagramSocket datagramSocket=null, bool canSend=true) | SocketWrapper | [inline]
streamSocket | SocketWrapper | [private]
ThrowIfDisposed() | SocketWrapper | [inline, private]
writer | SocketWrapper | [private]
~SocketWrapper() | SocketWrapper | [inline, private]
Generated on Fri Nov 15 2024 22:24:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
ButtonPin_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
PinTile(string style) | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
Generated on Fri Nov 15 2024 22:23:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cs/ItemsListViewModel.cs Source File

  • Store
  • cs

ItemsListViewModel.cs

Go to the documentation of this file.
00001 ﻿namespace SDKTemplate
00002 {
00003     public class ItemDetails
00004     {
00005         public string Title { get; private set; }
00006         public string Price { get; private set; }
00007         public bool InCollection { get; private set; }
00008         public string ProductKind { get; private set; }
00009         public string StoreId { get; private set; }
00010         public string FormattedTitle => $"{Title} ({ProductKind}) {Price}, InUserCollection:{InCollection}";
00011
00012         public ItemDetails(Windows.Services.Store.StoreProduct product)
00013         {
00014             Title = product.Title;
00015             Price = product.Price.FormattedPrice;
00016             InCollection = product.IsInUserCollection;
00017             ProductKind = product.ProductKind;
00018             StoreId = product.StoreId;
00019         }
00020     }
00021 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cpp/Tasks/pch.h Source File

  • Pedometer
  • cpp
  • Tasks

pch.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include <collection.h>
00004 #include <ppltasks.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Scenario5_GeofenceBackgroundTask.cpp Source File

  • Geolocation
  • cppwinrt

Scenario5_GeofenceBackgroundTask.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario5_GeofenceBackgroundTask.h"
00014 #include "Scenario5_GeofenceBackgroundTask.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::ApplicationModel::Background;
00019 using namespace winrt::Windows::Devices::Geolocation;
00020 using namespace winrt::Windows::Devices::Geolocation::Geofencing;
00021 using namespace winrt::Windows::Foundation;
00022 using namespace winrt::Windows::UI::Xaml;
00023 using namespace winrt::Windows::UI::Xaml::Navigation;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario5_GeofenceBackgroundTask::Scenario5_GeofenceBackgroundTask()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     void Scenario5_GeofenceBackgroundTask::OnNavigatedTo(NavigationEventArgs const&)
00033     {
00034         // See if our background task is already registered.
00035         m_geofenceTask = LookupBackgroundTask(BackgroundTaskName);
00036
00037         if (m_geofenceTask != nullptr)
00038         {
00039             // Associate an event handler with the existing background task
00040             m_taskCompletedToken = m_geofenceTask.Completed({ get_weak(), &Scenario5_GeofenceBackgroundTask::OnCompleted });
00041         }
00042         FillEventListBoxWithExistingEvents();
00043         UpdateButtonStates();
00044     }
00045
00046     void Scenario5_GeofenceBackgroundTask::RegisterBackgroundTask(IInspectable const&, RoutedEventArgs const&)
00047     {
00048         // Register the background task without checking whether the user has enabled background execution.
00049         // If it's disabled, and then the user later enables background execution, the background task will be ready to run.
00050         // Create a new background task builder
00051         BackgroundTaskBuilder geofenceTaskBuilder;
00052
00053         geofenceTaskBuilder.Name(BackgroundTaskName);
00054         geofenceTaskBuilder.TaskEntryPoint(BackgroundTaskEntryPoint);
00055
00056         // Create a new location trigger
00057         LocationTrigger trigger(LocationTriggerType::Geofence);
00058
00059         // Associate the location trigger with the background task builder
00060         geofenceTaskBuilder.SetTrigger(trigger);
00061
00062         // Register the background task
00063         m_geofenceTask = geofenceTaskBuilder.Register();
00064
00065         // Associate an event handler with the new background task
00066         m_taskCompletedToken = m_geofenceTask.Completed({ get_weak(), &Scenario5_GeofenceBackgroundTask::OnCompleted });
00067
00068         UpdateButtonStates();
00069
00070         CheckBackgroundAndRequestLocationAccess();
00071     }
00072
00073     void Scenario5_GeofenceBackgroundTask::UnregisterBackgroundTask(IInspectable const&, RoutedEventArgs const&)
00074     {
00075         // Unregister the background task
00076         if (m_geofenceTask != nullptr)
00077         {
00078             m_geofenceTask.Unregister(true);
00079             m_geofenceTask.Completed(m_taskCompletedToken);
00080             m_geofenceTask = nullptr;
00081         }
00082
00083         UpdateButtonStates();
00084         m_rootPage.NotifyUser(L"Geofence background task unregistered", NotifyType::StatusMessage);
00085     }
00086
00087     // This event handler is called when the background task is completed.
00088     fire_and_forget Scenario5_GeofenceBackgroundTask::OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
00089     {
00090         auto lifetime = get_strong();
00091
00092         // Update the UI with progress reported by the background task
00093         co_await resume_foreground(Dispatcher());
00094
00095         try
00096         {
00097             // Rethrow any exception that occurred in the background task.
00098             e.CheckResult();
00099
00100             // Update the UI with the completion status of the background task
00101             FillEventListBoxWithExistingEvents();
00102         }
00103         catch (...)
00104         {
00105             // The background task had an error
00106             m_rootPage.NotifyUser(to_message(), NotifyType::ErrorMessage);
00107         }
00108     }
00109
00110     // Update the enable state of the register/unregister buttons
00111     // based on whether we have already registered a task.
00112     void Scenario5_GeofenceBackgroundTask::UpdateButtonStates()
00113     {
00114         bool registered = (m_geofenceTask != nullptr);
00115         RegisterBackgroundTaskButton().IsEnabled(!registered);
00116         UnregisterBackgroundTaskButton().IsEnabled(registered);
00117     }
00118
00119     void Scenario5_GeofenceBackgroundTask::FillEventListBoxWithExistingEvents()
00120     {
00121         FillItemsFromSavedJson(GeofenceBackgroundEventsListBox(), L"BackgroundGeofenceEventCollection");
00122     }
00123 }
Generated on Fri Nov 15 2024 22:19:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: VersionAdaptiveCode/cs/Scenario2_Conditional.xaml.cs Source File

  • VersionAdaptiveCode
  • cs

Scenario2_Conditional.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Microsoft.Graphics.Canvas.Effects;
00013 using System.Numerics;
00014 using Windows.Foundation.Metadata;
00015 using Windows.UI.Composition;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Hosting;
00019 using Windows.UI.Xaml.Navigation;
00020
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// This page shows how to use the ApiInformation class in app code to
00026     // use new blur effects only if supported by the OS.
00027     /// </summary>
00028     public sealed partial class Scenario2_Conditional : Page
00029     {
00030         private MainPage rootPage;
00031
00032         private SpriteVisual _destVisual;
00033         private Compositor _compositor;
00034         private bool _destinationEffectsPresent = false;
00035         private Visual _rootVisual;
00036
00037         public Scenario2_Conditional()
00038         {
00039             this.InitializeComponent();
00040
00041             SetupBlur();
00042         }
00043
00044         public void SetupBlur()
00045         {
00046             _rootVisual = ElementCompositionPreview.GetElementVisual(this as UIElement);
00047             _compositor = _rootVisual.Compositor;
00048
00049             // If the Compositor.CreateBackdropBrush method exists, then set up the blur.
00050             if (ApiInformation.IsMethodPresent(_compositor.GetType().ToString(), "CreateBackdropBrush"))
00051             {
00052                 _destinationEffectsPresent = true;
00053                 SetupDestinationEffect(_compositor);
00054             }
00055         }
00056
00057         public void SetupDestinationEffect(Compositor compositor)
00058         {
00059             // Create SpriteVisual for blur effect
00060             _destVisual = compositor.CreateSpriteVisual();
00061             _destVisual.Size = new Vector2(0, 0);
00062
00063             // Create graphics effect for blur
00064             var graphicsEffect = new GaussianBlurEffect
00065             {
00066                 Name = "GB",
00067                 Source = new CompositionEffectSourceParameter("destinationSource"),
00068                 BlurAmount = 10f,
00069                 BorderMode = EffectBorderMode.Hard,
00070                 Optimization = EffectOptimization.Balanced
00071
00072             };
00073
00074             var effectFactory = compositor.CreateEffectFactory(graphicsEffect);
00075
00076             var blurEffect = effectFactory.CreateBrush();
00077             var destinationBrush = compositor.CreateBackdropBrush();
00078
00079             blurEffect.SetSourceParameter("destinationSource", destinationBrush);
00080
00081             // Set the SpriteVisual's brush as blur effect
00082             _destVisual.Brush = blurEffect;
00083
00084             // Insert the destination visual as child of the BlurRect UIElement.
00085             // Since the BlurRect is between the text of the flyout and the content of the page,
00086             // the destination visual will blur the content of the page.
00087             ElementCompositionPreview.SetElementChildVisual(BlurRect, _destVisual);
00088         }
00089
00090         protected override void OnNavigatedTo(NavigationEventArgs e)
00091         {
00092             rootPage = MainPage.Current;
00093         }
00094
00095         private void Flyout_Opened(object sender, object e)
00096         {
00097             BlurRect.IsHitTestVisible = true;
00098             if (_destVisual != null)
00099             {
00100                 _destVisual.Size = new Vector2((float)BlurRect.ActualWidth, (float)BlurRect.ActualHeight);
00101             }
00102         }
00103
00104         private void Flyout_Closed(object sender, object e)
00105         {
00106             BlurRect.IsHitTestVisible = false;
00107             if (_destVisual != null)
00108             {
00109                 _destVisual.Size = new Vector2(0, 0);
00110             }
00111         }
00112     }
00113 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ViewProjectionConstantBuffer Member List

This is the complete list of members for ViewProjectionConstantBuffer, including all inherited members.
cameraPosition | ViewProjectionConstantBuffer
lightPosition | ViewProjectionConstantBuffer
viewProjection | ViewProjectionConstantBuffer
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cs/Scenario1_SingleFile.xaml.cs Source File

  • FilePicker
  • cs

Scenario1_SingleFile.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Storage;
00014 using Windows.Storage.Pickers;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class Scenario1_SingleFile : Page
00025     {
00026         MainPage rootPage = MainPage.Current;
00027
00028         public Scenario1_SingleFile()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         private async void PickAFileButton_Click(object sender, RoutedEventArgs e)
00034         {
00035             // Clear previous returned file name, if it exists, between iterations of this scenario
00036             OutputTextBlock.Text = "";
00037
00038             FileOpenPicker openPicker = new FileOpenPicker();
00039             openPicker.ViewMode = PickerViewMode.Thumbnail;
00040             openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
00041             openPicker.FileTypeFilter.Add(".jpg");
00042             openPicker.FileTypeFilter.Add(".jpeg");
00043             openPicker.FileTypeFilter.Add(".png");
00044             StorageFile file = await openPicker.PickSingleFileAsync();
00045             if (file != null)
00046             {
00047                 // The StorageFile has read/write access to the picked file.
00048                 // See the FileAccess sample for code that uses a StorageFile to read and write.
00049                 OutputTextBlock.Text = "Picked photo: " + file.Name;
00050             }
00051             else
00052             {
00053                 OutputTextBlock.Text = "Operation cancelled.";
00054             }
00055         }
00056     }
00057 }
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlStateTriggers/cs/CustomTriggers/InputTypeTrigger.cs Source File

  • XamlStateTriggers
  • cs
  • CustomTriggers

InputTypeTrigger.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using Windows.Devices.Input;
00007 using Windows.UI.Xaml;
00008 using Windows.UI.Xaml.Input;
00009
00010 namespace StateTriggersSample.CustomTriggers
00011 {
00012     public class InputTypeTrigger : StateTriggerBase
00013     {
00014         //private variables
00015         private FrameworkElement _targetElement;
00016         private PointerDeviceType _lastPointerType, _triggerPointerType;
00017         //public properties to set from XAML
00018         public FrameworkElement TargetElement
00019         {
00020             get
00021             {
00022                 return _targetElement;
00023             }
00024             set
00025             {
00026                 _targetElement = value;
00027                 _targetElement.AddHandler(FrameworkElement.PointerPressedEvent, new PointerEventHandler(_targetElement_PointerPressed), true);
00028             }
00029         }
00030         public PointerDeviceType PointerType
00031         {
00032             get
00033             {
00034                 return _triggerPointerType;
00035             }
00036             set
00037             {
00038                 _triggerPointerType = value;
00039             }
00040         }
00041         //Handle event to get current values
00042         private void _targetElement_PointerPressed(object sender, PointerRoutedEventArgs e)
00043         {
00044             _lastPointerType = e.Pointer.PointerDeviceType;
00045             UpdateTrigger();
00046         }
00047         //Logic to evaluate and apply trigger value
00048         public void UpdateTrigger()
00049         {
00050             SetActive(_triggerPointerType == _lastPointerType);
00051         }
00052     }
00053 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlContextMenu/cpp/pch.h Source File

  • XamlContextMenu
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/Scenario7.xaml.cpp Source File

  • SimpleInk
  • cpp

Scenario7.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario7.xaml.h"
00013
00014 #include <WindowsNumerics.h>
00015
00016 #define _USE_MATH_DEFINES
00017 #include <math.h>
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace Platform;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::Foundation::Numerics;
00025 using namespace Windows::UI;
00026 using namespace Windows::UI::Core;
00027 using namespace Windows::UI::Input::Inking;
00028 using namespace Windows::UI::Xaml;
00029 using namespace Windows::UI::Xaml::Controls;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 Scenario7::Scenario7()
00033 {
00034     InitializeComponent();
00035
00036     inkCanvas->InkPresenter->InputDeviceTypes = CoreInputDeviceTypes::Mouse | CoreInputDeviceTypes::Pen;
00037
00038     // Customize the ruler
00039     auto ruler = ref new InkPresenterRuler(inkCanvas->InkPresenter);
00040     ruler->BackgroundColor = Colors::PaleTurquoise;
00041     ruler->ForegroundColor = Colors::MidnightBlue;
00042     ruler->Length = 800;
00043     ruler->AreTickMarksVisible = false;
00044     ruler->IsCompassVisible = false;
00045
00046     // Customize the protractor
00047     auto protractor = ref new InkPresenterProtractor(inkCanvas->InkPresenter);
00048     protractor->BackgroundColor = Colors::Bisque;
00049     protractor->ForegroundColor = Colors::DarkGreen;
00050     protractor->AccentColor = Colors::Firebrick;
00051     protractor->AreRaysVisible = false;
00052     protractor->AreTickMarksVisible = false;
00053     protractor->IsAngleReadoutVisible = false;
00054     protractor->IsCenterMarkerVisible = false;
00055 }
00056
00057 void Scenario7::InkToolbar_IsStencilButtonCheckedChanged(InkToolbar^ sender, InkToolbarIsStencilButtonCheckedChangedEventArgs^ args)
00058 {
00059     auto stencilButton = safe_cast<InkToolbarStencilButton^>(inkToolbar->GetMenuButton(InkToolbarMenuKind::Stencil));
00060     BringIntoViewButton->IsEnabled = stencilButton->IsChecked->Value;
00061 }
00062
00063 void Scenario7::OnNavigatedTo(NavigationEventArgs^ e)
00064 {
00065     // Make the ink canvas larger than the window, so that we can demonstrate
00066     // scrolling and zooming.
00067     inkCanvas->Width = Window::Current->Bounds.Width * 2;
00068     inkCanvas->Height = Window::Current->Bounds.Height * 2;
00069 }
00070
00071 void Scenario7::OnBringIntoView(Object^ sender, RoutedEventArgs^ e)
00072 {
00073     // Set stencil Origin to Scrollviewer Viewport origin.
00074     // The purpose of this behavior is to allow the user to "grab" the
00075     // stencil and bring it into view no matter where the scrollviewer viewport
00076     // happens to be.  Note that this is accomplished by a simple translation
00077     // that adjusts to the zoom factor.  The additional ZoomFactor term is to
00078     // make ensure the scale of the InkPresenterStencil is invariant to Zoom.
00079
00080     float3x2 viewportTransform = make_float3x2_scale(ScrollViewer->ZoomFactor) *
00081         make_float3x2_translation((float)ScrollViewer->HorizontalOffset, (float)ScrollViewer->VerticalOffset) *
00082         make_float3x2_scale(1.0f / ScrollViewer->ZoomFactor);
00083
00084     auto stencilButton = safe_cast<InkToolbarStencilButton^>(inkToolbar->GetMenuButton(InkToolbarMenuKind::Stencil));
00085     switch (stencilButton->SelectedStencil)
00086     {
00087     case InkToolbarStencilKind::Protractor:
00088         stencilButton->Protractor->Transform = viewportTransform;
00089         break;
00090
00091     case InkToolbarStencilKind::Ruler:
00092         stencilButton->Ruler->Transform = viewportTransform;
00093         break;
00094     }
00095 }
Generated on Fri Nov 15 2024 22:18:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cppwinrt/Scenario2_UnpinTile.h Source File

  • SecondaryTiles
  • cppwinrt

Scenario2_UnpinTile.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_UnpinTile.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario2_UnpinTile : Scenario2_UnpinTileT<Scenario2_UnpinTile>
00020     {
00021         Scenario2_UnpinTile();
00022
00023         fire_and_forget UnpinSecondaryTile_Click(Windows::Foundation::IInspectable sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024
00025     private:
00026         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario2_UnpinTile : Scenario2_UnpinTileT<Scenario2_UnpinTile, implementation::Scenario2_UnpinTile>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:21:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cs/1-InputEvents.xaml.cs Source File

  • BasicInput
  • cs

1-InputEvents.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Input;
00014 using Windows.UI.Xaml.Media;
00015
00016 namespace SDKTemplate
00017 {
00018     public sealed partial class Scenario1 : Page
00019     {
00020         public Scenario1()
00021         {
00022             this.InitializeComponent();
00023
00024             // pointer press/release handlers
00025             pressedTarget.PointerPressed += new PointerEventHandler(target_PointerPressed);
00026             pressedTarget.PointerReleased += new PointerEventHandler(target_PointerReleased);
00027
00028             // pointer enter/exit handlers
00029             enterExitTarget.PointerEntered += new PointerEventHandler(target_PointerEntered);
00030             enterExitTarget.PointerExited += new PointerEventHandler(target_PointerExited);
00031
00032             // gesture handlers
00033             tapTarget.Tapped += new TappedEventHandler(target_Tapped);
00034             tapTarget.DoubleTapped += new DoubleTappedEventHandler(target_DoubleTapped);
00035
00036             holdTarget.Holding += new HoldingEventHandler(target_Holding);
00037             holdTarget.RightTapped += new RightTappedEventHandler(target_RightTapped);
00038         }
00039
00040         // A PointerPressed event is sent whenever a mouse button, finger, or pen is pressed to make
00041         // contact with an object
00042         void target_PointerPressed(object sender, PointerRoutedEventArgs e)
00043         {
00044             pressedTarget.Background = new SolidColorBrush(Windows.UI.Colors.RoyalBlue);
00045             pressedTargetText.Text = "Pointer Pressed";
00046         }
00047
00048         // A PointerReleased event is sent whenever a mouse button, finger, or pen is released to remove
00049         // contact from an object
00050         void target_PointerReleased(object sender, PointerRoutedEventArgs e)
00051         {
00052             pressedTarget.Background = new SolidColorBrush(Windows.UI.Colors.LightGray);
00053             pressedTargetText.Text = "Pointer Released";
00054         }
00055
00056         // A PointerEntered event is sent whenever a mouse cursor is moved on top of an object
00057         // or when a pen or finger is dragged on top of an object
00058         void target_PointerEntered(object sender, PointerRoutedEventArgs e)
00059         {
00060             enterExitTarget.Background = new SolidColorBrush(Windows.UI.Colors.RoyalBlue);
00061             enterExitTargetText.Text = "Pointer Entered";
00062         }
00063
00064         // A PointerExited event is sent whenever a mouse cursor is moved off of an object
00065         // or when a pen or finger is dragged off of an object
00066         void target_PointerExited(object sender, PointerRoutedEventArgs e)
00067         {
00068             enterExitTarget.Background = new SolidColorBrush(Windows.UI.Colors.LightGray);
00069             enterExitTargetText.Text = "Pointer Exited";
00070         }
00071
00072         // A Tapped event is sent whenever a mouse is clicked or a finger or pen taps
00073         // the object
00074         void target_Tapped(object sender, TappedRoutedEventArgs e)
00075         {
00076             tapTarget.Background = new SolidColorBrush(Windows.UI.Colors.DeepSkyBlue);
00077             tapTargetText.Text = "Tapped";
00078         }
00079
00080         // A DoubleTapped event is sent whenever a mouse is double-clicked or a finger or pen taps
00081         // the object twice in quick succession
00082         void target_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
00083         {
00084             tapTarget.Background = new SolidColorBrush(Windows.UI.Colors.RoyalBlue);
00085             tapTargetText.Text = "Double-Tapped";
00086         }
00087
00088         // A RightTapped event is sent whenever a mouse is right-clicked or a finger or pen
00089         // completes a Holding event.  This is intended to be used to handle secondary actions
00090         // on an object.
00091         void target_RightTapped(object sender, RightTappedRoutedEventArgs e)
00092         {
00093             holdTarget.Background = new SolidColorBrush(Windows.UI.Colors.RoyalBlue);
00094             holdTargetText.Text = "Right Tapped";
00095         }
00096
00097         // A Holding event is sent whenever a finger or pen is pressed and held on top of
00098         // an object.
00099         // Once a small amount of time has elapsed, the event is sent with a HoldingState
00100         // of the type HoldingState.Started, indicating that the held threshold has just
00101         // been passed.
00102         // When a finger has been lifted after a successful hold, a Holding event is sent
00103         // with a HoldingState of Completed.
00104         // If the user cancels the hold after it has been started, but before it completes,
00105         // a Holding event is sent with a HoldingState of Canceled.
00106         void target_Holding(object sender, HoldingRoutedEventArgs e)
00107         {
00108             if (e.HoldingState == Windows.UI.Input.HoldingState.Started)
00109             {
00110                 holdTarget.Background = new SolidColorBrush(Windows.UI.Colors.DeepSkyBlue);
00111                 holdTargetText.Text = "Holding";
00112             }
00113             else if (e.HoldingState == Windows.UI.Input.HoldingState.Completed)
00114             {
00115                 holdTarget.Background = new SolidColorBrush(Windows.UI.Colors.LightGray);
00116                 holdTargetText.Text = "Held";
00117             }
00118             else
00119             {
00120                 holdTarget.Background = new SolidColorBrush(Windows.UI.Colors.LightGray);
00121                 holdTargetText.Text = "Hold Canceled";
00122             }
00123         }
00124     }
00125 }
Generated on Fri Nov 15 2024 22:18:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraProfile/cpp/Scenario2_ConcurrentProfile.xaml.h Source File

  • CameraProfile
  • cpp

Scenario2_ConcurrentProfile.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_ConcurrentProfile.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario2_ConcurrentProfile sealed
00024     {
00025     public:
00026         Scenario2_ConcurrentProfile();
00027
00028         void CheckConcurrentProfileBtn_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029
00030     protected:
00031         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00032
00033     private:
00034         MainPage^ _rootPage;
00035         Concurrency::task<Platform::String^> GetVideoProfileSupportedDeviceIdAsync(Windows::Devices::Enumeration::Panel panel);
00036
00037         Concurrency::task<void> LogStatusToOutputBoxAsync(Platform::String^ message);
00038         Concurrency::task<void> LogStatusAsync(Platform::String^ message, NotifyType type);
00039     };
00040 }
Generated on Fri Nov 15 2024 22:18:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_ProvisionTPM Member List

This is the complete list of members for Scenario1_ProvisionTPM, including all inherited members.
Create_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1_ProvisionTPM |
HandleCardAdded(Windows::Devices::SmartCards::SmartCardReader const &, Windows::Devices::SmartCards::CardAddedEventArgs const &) | Scenario1_ProvisionTPM | [private]
m_cardAddedToken | Scenario1_ProvisionTPM | [private]
ParsePinPolicy() | Scenario1_ProvisionTPM | [private]
Scenario1_ProvisionTPM() | Scenario1_ProvisionTPM |
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cpp/pch.cpp Source File

  • ActivitySensor
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/BackgroundTask/SampleConfiguration.h Source File

  • BackgroundTask
  • cpp
  • BackgroundTask

SampleConfiguration.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 #include <collection.h>
00014
00015 using namespace Platform;
00016 using namespace Windows::ApplicationModel::Background;
00017 using namespace Windows::Storage;
00018
00019 #define SampleBackgroundTaskEntryPoint "Tasks.SampleBackgroundTask"
00020 #define SampleBackgroundTaskName "SampleBackgroundTask"
00021 #define SampleBackgroundTaskWithConditionName "SampleBackgroundTaskWithCondition"
00022 #define ServicingCompleteTaskEntryPoint "Tasks.ServicingComplete"
00023 #define ServicingCompleteTaskName "ServicingCompleteTask"
00024 #define TimeTriggeredTaskName "TimeTriggeredTask"
00025 #define ApplicationTriggerTaskName "ApplicationTriggerTask"
00026 #define GroupedBackgroundTaskName "GroupedBackgroundTask"
00027 #define BackgroundTaskGroupId "3F2504E0-5F89-41D3-9A0C-0405E82C3333"
00028 #define BackgroundTaskGroupFriendlyName "Background Task Group"
00029
00030 namespace SDKTemplate
00031 {
00032     public value struct Scenario
00033     {
00034         String^ Title;
00035         String^ ClassName;
00036     };
00037
00038     partial ref class MainPage
00039     {
00040     public:
00041         static property String^ FEATURE_NAME
00042         {
00043             String^ get()
00044             {
00045                 return L"Background tasks";
00046             }
00047         }
00048
00049         static property Array<Scenario>^ scenarios
00050         {
00051             Array<Scenario>^ get()
00052             {
00053                 return scenariosInner;
00054             }
00055         }
00056     private:
00057         static Array<Scenario>^ scenariosInner;
00058     };
00059
00060     class BackgroundTaskSample
00061     {
00062     public:
00063         static String^ GetBackgroundTaskStatus(String^ name);
00064         static BackgroundTaskRegistration^ RegisterBackgroundTask(String^ taskEntryPoint, String^ name, IBackgroundTrigger^ trigger, IBackgroundCondition^ condition, BackgroundTaskRegistrationGroup^ group = nullptr);
00065         static bool TaskRequiresBackgroundAccess(String^ name);
00066         static void UnregisterBackgroundTasks(String^ name, BackgroundTaskRegistrationGroup^ group = nullptr);
00067         static BackgroundTaskRegistrationGroup^ GetTaskGroup(String^ id, String^ groupName);
00068         static void UpdateBackgroundTaskRegistrationStatus(String^ name, bool registered);
00069
00070         static String^ SampleBackgroundTaskProgress;
00071         static bool SampleBackgroundTaskRegistered;
00072
00073         static String^ SampleBackgroundTaskWithConditionProgress;
00074         static bool SampleBackgroundTaskWithConditionRegistered;
00075
00076         static String^ ServicingCompleteTaskProgress;
00077         static bool ServicingCompleteTaskRegistered;
00078
00079         static String^ TimeTriggeredTaskProgress;
00080         static bool TimeTriggeredTaskRegistered;
00081
00082         static String^ ApplicationTriggerTaskProgress;
00083         static bool ApplicationTriggerTaskRegistered;
00084         static String^ ApplicationTriggerTaskResult;
00085
00086         static String^ GroupedBackgroundTaskProgress;
00087         static bool GroupedBackgroundTaskRegistered;
00088     };
00089
00090 }
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/MyUserControl1.xaml.cs Source File

  • XamlBind
  • cs

MyUserControl1.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.ComponentModel;
00004 using System.IO;
00005 using System.Linq;
00006 using System.Runtime.InteropServices.WindowsRuntime;
00007 using Windows.Foundation;
00008 using Windows.Foundation.Collections;
00009 using Windows.UI.Xaml;
00010 using Windows.UI.Xaml.Controls;
00011 using Windows.UI.Xaml.Controls.Primitives;
00012 using Windows.UI.Xaml.Data;
00013 using Windows.UI.Xaml.Input;
00014 using Windows.UI.Xaml.Media;
00015 using Windows.UI.Xaml.Navigation;
00016
00017 // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
00018
00019 namespace xBindSampleCS
00020 {
00021     public sealed partial class MyUserControl1 : UserControl, INotifyPropertyChanged
00022     {
00023         public MyUserControl1()
00024         {
00025             NonDPProperty = "Not Set";
00026             this.InitializeComponent();
00027         }
00028
00029         private string _nonDPProperty;
00030         public string NonDPProperty {
00031             get { return _nonDPProperty; }
00032             set
00033             {
00034                 if (value != _nonDPProperty)
00035                 {
00036                     _nonDPProperty = value;
00037                     if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("NonDPProperty"));
00038                 }
00039             }
00040         }
00041
00042         public event PropertyChangedEventHandler PropertyChanged;
00043     }
00044 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraResolution/cs/Scenario2_PhotoSettings.xaml.cs Source File

  • CameraResolution
  • cs

Scenario2_PhotoSettings.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using System;
00012 using System.Collections.Generic;
00013 using System.Linq;
00014 using System.Threading.Tasks;
00015 using Windows.Graphics.Imaging;
00016 using Windows.Media.Capture;
00017 using Windows.Media.MediaProperties;
00018 using Windows.Storage;
00019 using Windows.Storage.Streams;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Navigation;
00023
00024 namespace SDKTemplate
00025 {
00026
00027     /// <summary>
00028     /// Scenario 2 Change camera preview and photo settings
00029     /// </summary>
00030     public sealed partial class Scenario2_PhotoSettings : Page
00031     {
00032         // Private MainPage object for status updates
00033         private MainPage rootPage = MainPage.Current;
00034
00035         // Object to manage access to camera devices
00036         private MediaCapturePreviewer _previewer = null;
00037
00038         // Folder in which the captures will be stored (initialized in InitializeCameraButton_Click)
00039         private StorageFolder _captureFolder = null;
00040
00041         /// <summary>
00042         /// Initializes a new instance of the <see cref="Scenario2_PhotoSettings"/> class.
00043         /// </summary>
00044         public Scenario2_PhotoSettings()
00045         {
00046             this.InitializeComponent();
00047             _previewer = new MediaCapturePreviewer(PreviewControl, Dispatcher);
00048         }
00049
00050         protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
00051         {
00052             await _previewer.CleanupCameraAsync();
00053         }
00054
00055         /// <summary>
00056         /// On some devices there may not be seperate streams for preview/photo/video. In this case, changing any of them
00057         /// will change all of them since they are the same stream
00058         /// </summary>
00059         public void CheckIfStreamsAreIdentical()
00060         {
00061             if (_previewer.MediaCapture.MediaCaptureSettings.VideoDeviceCharacteristic == VideoDeviceCharacteristic.AllStreamsIdentical ||
00062                 _previewer.MediaCapture.MediaCaptureSettings.VideoDeviceCharacteristic == VideoDeviceCharacteristic.PreviewPhotoStreamsIdentical)
00063             {
00064                 rootPage.NotifyUser("Warning: Preview and photo streams for this device are identical, changing one will affect the other", NotifyType.ErrorMessage);
00065             }
00066         }
00067
00068         /// <summary>
00069         /// Initializes the camera and populates the UI
00070         /// </summary>
00071         /// <param name="sender"></param>
00072         /// <param name="e"></param>
00073         private async void InitializeCameraButton_Click(object sender, RoutedEventArgs e)
00074         {
00075             var button = sender as Button;
00076
00077             // Clear any previous message.
00078             rootPage.NotifyUser("", NotifyType.StatusMessage);
00079
00080             button.IsEnabled = false;
00081             await _previewer.InitializeCameraAsync();
00082             button.IsEnabled = true;
00083
00084             if (_previewer.IsPreviewing)
00085             {
00086                 button.Visibility = Visibility.Collapsed;
00087                 PreviewControl.Visibility = Visibility.Visible;
00088                 CheckIfStreamsAreIdentical();
00089                 PopulateComboBox(MediaStreamType.VideoPreview, PreviewSettings);
00090                 PopulateComboBox(MediaStreamType.Photo, PhotoSettings, false);
00091                 PhotoButton.IsEnabled = true;
00092             }
00093
00094             var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
00095             // Fall back to the local app storage if the Pictures Library is not available
00096             _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
00097         }
00098
00099         /// <summary>
00100         ///  Event handler for Preview settings combo box. Updates stream resolution based on the selection.
00101         /// </summary>
00102         /// <param name="sender"></param>
00103         /// <param name="e"></param>
00104         private async void PreviewSettings_Changed(object sender, RoutedEventArgs e)
00105         {
00106             if (_previewer.IsPreviewing)
00107             {
00108                 var selectedItem = (sender as ComboBox).SelectedItem as ComboBoxItem;
00109                 var encodingProperties = (selectedItem.Tag as StreamResolution).EncodingProperties;
00110                 await _previewer.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, encodingProperties);
00111             }
00112         }
00113
00114         /// <summary>
00115         /// Event handler for Photo settings combo box. Updates stream resolution based on the selection.
00116         /// </summary>
00117         /// <param name="sender"></param>
00118         /// <param name="e"></param>
00119         private async void PhotoSettings_Changed(object sender, RoutedEventArgs e)
00120         {
00121             if (_previewer.IsPreviewing)
00122             {
00123                 var selectedItem = (sender as ComboBox).SelectedItem as ComboBoxItem;
00124                 var encodingProperties = (selectedItem.Tag as StreamResolution).EncodingProperties;
00125                 await _previewer.MediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, encodingProperties);
00126             }
00127         }
00128
00129         /// <summary>
00130         /// Takes a photo to and saves to a StorageFile
00131         /// </summary>
00132         /// <param name="sender"></param>
00133         /// <param name="e"></param>
00134         private async void PhotoButton_Click(object sender, RoutedEventArgs e)
00135         {
00136             if (_previewer.IsPreviewing)
00137             {
00138                 // Disable the photo button while taking a photo
00139                 PhotoButton.IsEnabled = false;
00140
00141                 var stream = new InMemoryRandomAccessStream();
00142
00143                 try
00144                 {
00145                     // Take and save the photo
00146                     var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName);
00147                     await _previewer.MediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), file);
00148                     rootPage.NotifyUser("Photo taken, saved to: " + file.Path, NotifyType.StatusMessage);
00149                 }
00150                 catch (Exception ex)
00151                 {
00152                     // File I/O errors are reported as exceptions.
00153                     rootPage.NotifyUser("Exception when taking a photo: " + ex.Message, NotifyType.ErrorMessage);
00154                 }
00155
00156                 // Done taking a photo, so re-enable the button
00157                 PhotoButton.IsEnabled = true;
00158             }
00159         }
00160
00161         /// <summary>
00162         /// Populates the given combo box with all possible combinations of the given stream type settings returned by the camera driver
00163         /// </summary>
00164         /// <param name="streamType"></param>
00165         /// <param name="comboBox"></param>
00166         private void PopulateComboBox(MediaStreamType streamType, ComboBox comboBox, bool showFrameRate = true)
00167         {
00168             // Query all preview properties of the device
00169             IEnumerable<StreamResolution> allStreamProperties = _previewer.MediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(streamType).Select(x => new StreamResolution(x));
00170             // Order them by resolution then frame rate
00171             allStreamProperties = allStreamProperties.OrderByDescending(x => x.Height * x.Width).ThenByDescending(x => x.FrameRate);
00172
00173             // Populate the combo box with the entries
00174             foreach (var property in allStreamProperties)
00175             {
00176                 ComboBoxItem comboBoxItem = new ComboBoxItem();
00177                 comboBoxItem.Content = property.GetFriendlyName(showFrameRate);
00178                 comboBoxItem.Tag = property;
00179                 comboBox.Items.Add(comboBoxItem);
00180             }
00181         }
00182     }
00183 }
Generated on Fri Nov 15 2024 22:18:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisablingScreenCapture/cpp/Scenario2_Disable.xaml.cpp Source File

  • DisablingScreenCapture
  • cpp

Scenario2_Disable.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Disable.xaml.h"
00014
00015 using namespace SDKTemplate;
00016 using namespace Windows::UI::Xaml::Navigation;
00017 using namespace Windows::UI::ViewManagement;
00018
00019 Scenario2_Disable::Scenario2_Disable()
00020 {
00021     this->InitializeComponent();
00022 }
00023
00024 void Scenario2_Disable::OnNavigatedTo(NavigationEventArgs^ e)
00025 {
00026     // Disable screen capture when the user navigates to this page.
00027     ApplicationView::GetForCurrentView()->IsScreenCaptureEnabled = false;
00028 }
00029
00030 void Scenario2_Disable::OnNavigatedFrom(NavigationEventArgs^ e)
00031 {
00032     // Re-enable screen capture when the user navigates away from this page.
00033     ApplicationView::GetForCurrentView()->IsScreenCaptureEnabled = true;
00034 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/LiveTiles/AdaptiveTemplates/Images/Source/FromAppPackage/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • LiveTiles
  • AdaptiveTemplates
  • Images
  • Source
  • FromAppPackage

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Notifications.Helpers;
00002 using System;
00003 using Windows.Data.Xml.Dom;
00004 using Windows.UI.Notifications;
00005 using Windows.UI.StartScreen;
00006 using Windows.UI.Xaml;
00007 using Windows.UI.Xaml.Controls;
00008
00009 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00010
00011 namespace Notifications.ScenarioPages.LiveTiles.AdaptiveTemplates.Images.Source.FromAppPackage
00012 {
00013     /// <summary>
00014     /// An empty page that can be used on its own or navigated to within a Frame.
00015     /// </summary>
00016     public sealed partial class ScenarioElement : UserControl
00017     {
00018         public ScenarioElement()
00019         {
00020             this.InitializeComponent();
00021         }
00022
00023         private string _tileId;
00024
00025         private async void ButtonPinSecondaryTile_Click(object sender, RoutedEventArgs e)
00026         {
00027             base.IsEnabled = false;
00028
00029             _tileId = DateTime.Now.Ticks.ToString();
00030
00031             string ImageUrl = "ms-appx:///Assets/check.png";
00032
00033             SecondaryTile tile = TilesHelper.GenerateSecondaryTile("App Package Image");
00034             await tile.RequestCreateAsync();
00035
00036             string tileXmlString =
00037                 "<tile>"
00038                 + "<visual>"
00039                 + "<binding template='TileSmall'>"
00040                 + "<image src='" + ImageUrl + "' alt='image'/>"
00041                 + "</binding>"
00042                 + "<binding template='TileMedium'>"
00043                 + "<image src='" + ImageUrl + "' alt='image'/>"
00044                 + "</binding>"
00045                 + "<binding template='TileWide'>"
00046                 + "<image src='" + ImageUrl + "' alt='image'/>"
00047                 + "</binding>"
00048                 + "<binding template='TileLarge'>"
00049                 + "<image src='" + ImageUrl + "' alt='image'/>"
00050                 + "</binding>"
00051                 + "</visual>"
00052                 + "</tile>";
00053
00054             XmlDocument xmlDoc = new XmlDocument();
00055             xmlDoc.LoadXml(tileXmlString);
00056             TileNotification notifyTile = new TileNotification(xmlDoc);
00057             TileUpdateManager.CreateTileUpdaterForSecondaryTile(tile.TileId).Update(notifyTile);
00058
00059             base.IsEnabled = true;
00060         }
00061     }
00062 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/ProducerExperiences/cs/Scenario2ViewModel.cs Source File

  • AllJoyn
  • ProducerExperiences
  • cs

Scenario2ViewModel.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using org.alljoyn.Onboarding;
00013 using SDKTemplate;
00014 using System;
00015 using System.Collections.Generic;
00016 using System.ComponentModel;
00017 using System.Runtime.CompilerServices;
00018 using System.Threading.Tasks;
00019 using System.Windows.Input;
00020 using Windows.Devices.AllJoyn;
00021 using Windows.Security.Cryptography;
00022 using Windows.UI.Core;
00023 using Windows.UI.Xaml;
00024
00025 namespace AllJoynProducerExperiences
00026 {
00027     class Scenario2ViewModel : INotifyPropertyChanged
00028     {
00029         private MainPage m_rootPage;
00030         private CoreDispatcher m_dispatcher;
00031         private bool m_isBusAttachmentConnected = false;
00032         private AllJoynBusAttachment m_busAttachment = null;
00033         private OnboardingProducer m_producer = null;
00034         private OnboardingScanListItem m_selectedSampleNetwork;
00035         private Visibility m_sampleNetworkInfoVisibility = Visibility.Collapsed;
00036         private string m_key = "";
00037
00038         public Scenario2ViewModel()
00039         {
00040             m_dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
00041             m_rootPage = MainPage.Current;
00042         }
00043
00044         public event PropertyChangedEventHandler PropertyChanged;
00045
00046         public string Key
00047         {
00048             get
00049             {
00050                 return m_key;
00051             }
00052             private set
00053             {
00054                 m_key = value;
00055                 RaisePropertyChangedEventAsync();
00056             }
00057         }
00058
00059         public List<OnboardingScanListItem> SampleNetworkList
00060         {
00061             get
00062             {
00063                 return AppData.SampleNetworkScanList;
00064             }
00065         }
00066
00067         public OnboardingScanListItem SelectedSampleNetwork
00068         {
00069             get
00070             {
00071                 return m_selectedSampleNetwork;
00072             }
00073             set
00074             {
00075                 m_selectedSampleNetwork = value;
00076                 RaisePropertyChangedEventAsync("SelectedSampleNetworkPassword");
00077                 RaisePropertyChangedEventAsync("SelectedSampleNetworkAuthentication");
00078             }
00079         }
00080
00081         public string SelectedSampleNetworkPassword
00082         {
00083             get
00084             {
00085                 if (m_selectedSampleNetwork != null)
00086                 {
00087                     if (m_selectedSampleNetwork.Value2 == (short)OnboardingAuthenticationType.Open)
00088                     {
00089                         return "";
00090                     }
00091                     else
00092                     {
00093                         return AppData.SampleNetworkPassword;
00094                     }
00095                 }
00096                 else
00097                 {
00098                     return "";
00099                 }
00100             }
00101         }
00102
00103         public string SelectedSampleNetworkAuthentication
00104         {
00105             get
00106             {
00107                 if (m_selectedSampleNetwork != null)
00108                 {
00109                     return ((OnboardingAuthenticationType)m_selectedSampleNetwork.Value2).ToString();
00110                 }
00111                 else
00112                 {
00113                     return "";
00114                 }
00115             }
00116         }
00117
00118         public Visibility SampleNetworkInfoVisibility
00119         {
00120             get
00121             {
00122                 return m_sampleNetworkInfoVisibility;
00123             }
00124             private set
00125             {
00126                 m_sampleNetworkInfoVisibility = value;
00127                 RaisePropertyChangedEventAsync();
00128             }
00129         }
00130
00131         public ICommand LaunchProducer
00132         {
00133             get
00134             {
00135                 return new RelayCommand((object args) =>
00136                 {
00137                     Start();
00138                 });
00139             }
00140         }
00141
00142         public void ScenarioCleanup()
00143         {
00144             OnboardingService.ConnectRequestRecieved -= OnboardingService_ConnectRequestRecieved;
00145
00146             if (m_producer != null)
00147             {
00148                 m_producer.Stop();
00149                 m_producer.Dispose();
00150             }
00151
00152             if (m_busAttachment != null)
00153             {
00154                 m_busAttachment.CredentialsRequested -= AlljoynBusAttachment_CredentialsRequested;
00155                 m_busAttachment.AuthenticationComplete -= AlljoynBusAttachment_AuthenticationComplete;
00156                 m_busAttachment.StateChanged -= AlljoynBusAttachment_StateChanged;
00157                 m_busAttachment.Disconnect();
00158             }
00159         }
00160
00161         protected async void RaisePropertyChangedEventAsync([CallerMemberName]string name = "")
00162         {
00163             await m_dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00164             {
00165                 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
00166             });
00167         }
00168
00169         private void Start()
00170         {
00171             // Prevent launching the producer again if it is already launched.
00172             if (m_isBusAttachmentConnected)
00173             {
00174                 UpdateStatusAsync("Already launched.", NotifyType.StatusMessage);
00175             }
00176             else
00177             {
00178                 UpdateStatusAsync("Launching...", NotifyType.StatusMessage);
00179
00180                 m_busAttachment = new AllJoynBusAttachment();
00181                 m_busAttachment.StateChanged += AlljoynBusAttachment_StateChanged;
00182                 m_busAttachment.AuthenticationMechanisms.Clear();
00183                 m_busAttachment.AuthenticationMechanisms.Add(AllJoynAuthenticationMechanism.EcdheSpeke);
00184                 m_busAttachment.AuthenticationComplete += AlljoynBusAttachment_AuthenticationComplete;
00185                 m_busAttachment.CredentialsRequested += AlljoynBusAttachment_CredentialsRequested;
00186
00187                 // Generate the one-time 6-digit numeric pre-shared key.
00188                 Random rnd = new Random();
00189                 Key = rnd.Next(100000, 1000000).ToString();
00190
00191                 // Initialize the producer object generated by the AllJoynCodeGenerator tool.
00192                 m_producer = new OnboardingProducer(m_busAttachment);
00193
00194                 // Instantiate OnboardingService which will handle the onboarding method calls.
00195                 m_producer.Service = new OnboardingService();
00196                 OnboardingService.ConnectRequestRecieved += OnboardingService_ConnectRequestRecieved;
00197
00198                 // Start listening for consumers.
00199                 m_producer.Start();
00200             }
00201         }
00202
00203         private void AlljoynBusAttachment_StateChanged(AllJoynBusAttachment sender, AllJoynBusAttachmentStateChangedEventArgs args)
00204         {
00205             switch (args.State)
00206             {
00207                 case AllJoynBusAttachmentState.Disconnected:
00208                     UpdateStatusAsync(string.Format("Disconnected from the AllJoyn bus attachment with AllJoyn status: 0x{0:X}.", args.Status), NotifyType.StatusMessage);
00209                     m_isBusAttachmentConnected = false;
00210                     SampleNetworkInfoVisibility = Visibility.Collapsed;
00211                     break;
00212                 case AllJoynBusAttachmentState.Connected:
00213                     UpdateStatusAsync("Launched.", NotifyType.StatusMessage);
00214                     m_isBusAttachmentConnected = true;
00215                     SampleNetworkInfoVisibility = Visibility.Visible;
00216                     break;
00217                 default:
00218                     break;
00219             }
00220         }
00221
00222         private void AlljoynBusAttachment_AuthenticationComplete(AllJoynBusAttachment sender, AllJoynAuthenticationCompleteEventArgs args)
00223         {
00224             if (args.Succeeded)
00225             {
00226                 UpdateStatusAsync("Authentication was successful.", NotifyType.StatusMessage);
00227             }
00228             else
00229             {
00230                 UpdateStatusAsync("Authentication failed.", NotifyType.ErrorMessage);
00231             }
00232         }
00233
00234         private void AlljoynBusAttachment_CredentialsRequested(AllJoynBusAttachment sender, AllJoynCredentialsRequestedEventArgs args)
00235         {
00236             if (args.Credentials.AuthenticationMechanism == AllJoynAuthenticationMechanism.EcdheSpeke)
00237             {
00238                 args.Credentials.PasswordCredential.Password = m_key;
00239             }
00240             else
00241             {
00242                 UpdateStatusAsync("Unexpected authentication mechanism.", NotifyType.ErrorMessage);
00243             }
00244         }
00245
00246         private async void OnboardingService_ConnectRequestRecieved(object sender, EventArgs e)
00247         {
00248             UpdateStatusAsync("Connect Request received. Attempting to connect...", NotifyType.StatusMessage);
00249             AppData.OnboardingConfigurationState = (short)ConfigurationState.Validating;
00250
00251             // 5 second delay to simulate connection attempt time.
00252             await Task.Delay(TimeSpan.FromSeconds(5));
00253             Onboarding returnArg = new Onboarding();
00254
00255             if (string.IsNullOrWhiteSpace(AppData.OnboardingConfigureSsid))
00256             {
00257                 returnArg.Value1 = (short)ConnectionResultCode.ErrorMessage;
00258                 returnArg.Value2 = "Invalid SSID";
00259                 AppData.OnboardingConfigurationState = (short)ConfigurationState.Error;
00260             }
00261             else
00262             {
00263                 bool foundSsid = false;
00264                 bool supportedProtocol = false;
00265
00266                 foreach (OnboardingScanListItem item in AppData.SampleNetworkScanList)
00267                 {
00268                     if (item.Value1.Equals(AppData.OnboardingConfigureSsid))
00269                     {
00270                         foundSsid = true;
00271                         if (AppData.OnboardingConfigureAuthType == (short)OnboardingAuthenticationType.Any)
00272                         {
00273                             supportedProtocol = true;
00274                         }
00275                         else if (AppData.OnboardingConfigureAuthType == (short)OnboardingAuthenticationType.WpaAuto)
00276                         {
00277                             if ((item.Value2 == (short)OnboardingAuthenticationType.WpaTkip) || (item.Value2 == (short)OnboardingAuthenticationType.WpaCcmp))
00278                             {
00279                                 supportedProtocol = true;
00280                             }
00281                         }
00282                         else if (AppData.OnboardingConfigureAuthType == (short)OnboardingAuthenticationType.Wpa2Auto)
00283                         {
00284                             if ((item.Value2 == (short)OnboardingAuthenticationType.Wpa2Tkip) || (item.Value2 == (short)OnboardingAuthenticationType.Wpa2Ccmp))
00285                             {
00286                                 supportedProtocol = true;
00287                             }
00288                         }
00289                         else
00290                         {
00291                             if (item.Value2 == AppData.OnboardingConfigureAuthType)
00292                             {
00293                                 supportedProtocol = true;
00294                             }
00295                         }
00296                         break;
00297                     }
00298                 }
00299
00300                 if (foundSsid)
00301                 {
00302                     if (supportedProtocol)
00303                     {
00304                         if (AppData.OnboardingConfigureAuthType == (short)OnboardingAuthenticationType.Open)
00305                         {
00306                             returnArg.Value1 = (short)ConnectionResultCode.Validated;
00307                             returnArg.Value2 = "Connected successfully";
00308                             AppData.OnboardingConfigurationState = (short)ConfigurationState.Validated;
00309                         }
00310                         else
00311                         {
00312                             if (AppData.OnboardingConfigurePassphrase.Equals(ConvertUtf8ToHex(AppData.SampleNetworkPassword), StringComparison.OrdinalIgnoreCase))
00313                             {
00314                                 returnArg.Value1 = (short)ConnectionResultCode.Validated;
00315                                 returnArg.Value2 = "Connected successfully";
00316                                 AppData.OnboardingConfigurationState = (short)ConfigurationState.Validated;
00317                             }
00318                             else
00319                             {
00320                                 returnArg.Value1 = (short)ConnectionResultCode.Unauthorized;
00321                                 returnArg.Value2 = "Invalid password";
00322                                 AppData.OnboardingConfigurationState = (short)ConfigurationState.Error;
00323                             }
00324                         }
00325                     }
00326                     else
00327                     {
00328                         returnArg.Value1 = (short)ConnectionResultCode.UnsupportedProtocol;
00329                         returnArg.Value2 = "Unsupported authentication mechanism";
00330                         AppData.OnboardingConfigurationState = (short)ConfigurationState.Error;
00331                     }
00332                 }
00333                 else
00334                 {
00335                     returnArg.Value1 = (short)ConnectionResultCode.Unreachable;
00336                     returnArg.Value2 = "Configured SSID unreachable";
00337                     AppData.OnboardingConfigurationState = (short)ConfigurationState.Error;
00338                 }
00339             }
00340
00341             m_producer.Signals.ConnectionResult(returnArg);
00342             AppData.LastErrorCode = returnArg.Value1;
00343             AppData.LastErrorMessage = returnArg.Value2;
00344
00345             if (returnArg.Value1 == (short)ConnectionResultCode.Validated)
00346             {
00347                 UpdateStatusAsync("Onboarding successful. Connected to " + AppData.OnboardingConfigureSsid, NotifyType.StatusMessage);
00348             }
00349             else
00350             {
00351                 UpdateStatusAsync(string.Format("Onboarding Failed. Attempt to connect failed with result code: {0} and message: {1}.", ((ConnectionResultCode)returnArg.Value1).ToString(), returnArg.Value2), NotifyType.ErrorMessage);
00352             }
00353         }
00354
00355         static private string ConvertUtf8ToHex(string inputString)
00356         {
00357             if (string.IsNullOrEmpty(inputString))
00358             {
00359                 return string.Empty;
00360             }
00361             else
00362             {
00363                 var tempBuffer = CryptographicBuffer.ConvertStringToBinary(inputString, BinaryStringEncoding.Utf8);
00364                 var hexString = CryptographicBuffer.EncodeToHexString(tempBuffer);
00365                 return hexString;
00366             }
00367         }
00368
00369         private async void UpdateStatusAsync(string status, NotifyType statusType)
00370         {
00371             await m_dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00372             {
00373                 m_rootPage.NotifyUser(status, statusType);
00374             });
00375         }
00376     }
00377 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserActivity/cs/Scenario1_BasicUserActivity.xaml.cs Source File

  • UserActivity
  • cs

Scenario1_BasicUserActivity.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.ApplicationModel.UserActivities;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class Scenario1_BasicUserActivity : Page
00025     {
00026         private UserActivitySession _currentSession;
00027
00028         public Scenario1_BasicUserActivity()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         protected override async void OnNavigatedTo(NavigationEventArgs e)
00034         {
00035             // If we were activated from a URI, say so.
00036             // A real app would use the information in the URI to restore state.
00037             var message = e.Parameter as string;
00038             if (!String.IsNullOrEmpty(message))
00039             {
00040                 MainPage.Current.NotifyUser(message, NotifyType.StatusMessage);
00041             }
00042
00043             await CreateUserActivityAsync();
00044         }
00045
00046         async Task CreateUserActivityAsync()
00047         {
00048             // Get channel and create activity.
00049             UserActivityChannel channel = UserActivityChannel.GetDefault();
00050             UserActivity activity = await channel.GetOrCreateUserActivityAsync("Scenario1_BasicUserActivity");
00051
00052             // Set deep-link and properties.
00053             activity.ActivationUri = new Uri("useractivitysdkcs:page?Scenario1_BasicUserActivity");
00054             activity.VisualElements.DisplayText = "User Activity Sample Scenario 1";
00055
00056             // Save to activity feed.
00057             await activity.SaveAsync();
00058
00059             // Create a session, which indicates that the user is engaged
00060             // in the activity.
00061             _currentSession = activity.CreateSession();
00062         }
00063
00064         protected override void OnNavigatedFrom(NavigationEventArgs e)
00065         {
00066             // Dispose the session, which indicates that the user is no longer
00067             // engaged in the activity.
00068             _currentSession?.Dispose();
00069         }
00070     }
00071 }
Generated on Fri Nov 15 2024 22:21:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SocketActivityStreamSocket/cs/SocketActivityStreamSocket/SampleConfiguration.cs Source File

  • SocketActivityStreamSocket
  • cs
  • SocketActivityStreamSocket

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using SocketActivityStreamSocket;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "SocketActivityStreamSocket";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Connect to Listener", ClassType=typeof(Scenario1_Connect)},
00026         };
00027     }
00028
00029     public class Scenario
00030     {
00031         public string Title { get; set; }
00032         public Type ClassType { get; set; }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cpp/Scenario4_ChangeSystemGroup.xaml.cpp Source File

  • JumpList
  • cpp

Scenario4_ChangeSystemGroup.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario4_ChangeSystemGroup.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace concurrency;
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Navigation;
00023 using namespace Windows::UI::StartScreen;
00024 using namespace Windows::Storage;
00025 using namespace Windows::Storage::AccessCache;
00026
00027
00028
00029 Scenario4_ChangeSystemGroup::Scenario4_ChangeSystemGroup()
00030 {
00031     InitializeComponent();
00032 }
00033
00034 void Scenario4_ChangeSystemGroup::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00035 {
00036     create_task(JumpList::LoadCurrentAsync()).then([this](JumpList^ jumpList)
00037     {
00038         switch (jumpList->SystemGroupKind)
00039         {
00040         case JumpListSystemGroupKind::Recent:
00041             SystemGroup_Recent->IsChecked = true;
00042             break;
00043         case JumpListSystemGroupKind::Frequent:
00044             SystemGroup_Frequent->IsChecked = true;
00045             break;
00046         case JumpListSystemGroupKind::None:
00047             SystemGroup_None->IsChecked = true;
00048             break;
00049         }
00050     }, task_continuation_context::use_current());
00051 }
00052
00053 void Scenario4_ChangeSystemGroup::SystemGroup_Recent_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00054 {
00055     create_task(JumpList::LoadCurrentAsync()).then([this](JumpList^ jumpList) -> IAsyncAction^
00056     {
00057         jumpList->SystemGroupKind = JumpListSystemGroupKind::Recent;
00058         return jumpList->SaveAsync();
00059     }, task_continuation_context::use_arbitrary());
00060 }
00061
00062 void Scenario4_ChangeSystemGroup::SystemGroup_Frequent_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00063 {
00064     create_task(JumpList::LoadCurrentAsync()).then([this](JumpList^ jumpList) -> IAsyncAction^
00065     {
00066         jumpList->SystemGroupKind = JumpListSystemGroupKind::Frequent;
00067         return jumpList->SaveAsync();
00068     }, task_continuation_context::use_arbitrary());
00069 }
00070
00071 void Scenario4_ChangeSystemGroup::SystemGroup_None_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00072 {
00073     create_task(JumpList::LoadCurrentAsync()).then([this](JumpList^ jumpList) -> IAsyncAction^
00074     {
00075         jumpList->SystemGroupKind = JumpListSystemGroupKind::None;
00076         return jumpList->SaveAsync();
00077     }, task_continuation_context::use_arbitrary());
00078 }
00079
00080 void Scenario4_ChangeSystemGroup::PrepareSampleFiles_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00081 {
00082     // NOTE: This is for the sake of the sample only. Real apps should allow
00083     // the system list to be populated by user activity.
00084
00085     for (int i = 0; i < 5; ++i)
00086     {
00087         StorageFolder^ localFolder = ApplicationData::Current->LocalFolder;
00088         create_task(localFolder->CreateFileAsync("Temp" + i.ToString() + ".ms-jumplist-sample", CreationCollisionOption::OpenIfExists)).then(
00089             [](StorageFile^ file)
00090         {
00091             StorageApplicationPermissions::MostRecentlyUsedList->Add(file, "", RecentStorageItemVisibility::AppAndSystem);
00092         }, task_continuation_context::use_arbitrary());
00093     }
00094 }
Generated on Fri Nov 15 2024 22:20:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cs/Scenario5_IsSupported.xaml.cs Source File

  • JumpList
  • cs

Scenario5_IsSupported.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using Windows.UI.StartScreen;
00015
00016 namespace SDKTemplate
00017 {
00018     public sealed partial class Scenario5_IsSupported : Page
00019     {
00020         public Scenario5_IsSupported()
00021         {
00022             this.InitializeComponent();
00023         }
00024
00025         protected override void OnNavigatedTo(NavigationEventArgs e)
00026         {
00027             Supported.Text = JumpList.IsSupported() ? "supports" : "does not support";
00028         }
00029     }
00030 }
Generated on Fri Nov 15 2024 22:20:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Nfc/PcscSdk/MifareStandardAccessHandler.cs Source File

  • Nfc
  • PcscSdk

MifareStandardAccessHandler.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.Threading.Tasks;
00013 using Windows.Devices.SmartCards;
00014 using System.Runtime.InteropServices.WindowsRuntime;
00015 using Windows.Storage.Streams;
00016
00017 using Pcsc;
00018 using System;
00019
00020 namespace MifareStandard
00021 {
00022     public class DefaultKeys
00023     {
00024         public static readonly byte[] FactoryDefault = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
00025     }
00026     /// <summary>
00027     /// Access handler class for Mifare Standard/Classic based ICC
00028     /// commands
00029     /// </summary>
00030     public class AccessHandler
00031     {
00032         /// <summary>
00033         /// connection object to smart card
00034         /// </summary>
00035         private SmartCardConnection connectionObject { set; get; }
00036         /// <summary>
00037         /// Class constructor
00038         /// </summary>
00039         /// <param name="ScConnection">
00040         /// connection object to a Mifare Standard ICC
00041         /// </param>
00042         public AccessHandler(SmartCardConnection ScConnection)
00043         {
00044             connectionObject = ScConnection;
00045         }
00046         /// <summary>
00047         /// Wrapper method to read 16 bytes
00048         /// </summary>
00049         /// <param name="pageAddress">
00050         /// start page to read
00051         /// </param>
00052         /// <returns>
00053         /// byte array of 16 bytes
00054         /// </returns>
00055         public async Task LoadKeyAsync(byte[] mifareKey, byte keySlotNumber = 0)
00056         {
00057             var apduRes = await connectionObject.TransceiveAsync(new MifareStandard.LoadKey(mifareKey, keySlotNumber));
00058
00059             if (!apduRes.Succeeded)
00060             {
00061                 throw new Exception("Failure loading key for MIFARE Standard card, " + apduRes.ToString());
00062             }
00063
00064             return;
00065         }
00066         /// <summary>
00067         /// Reads 16 bytes
00068         /// </summary>
00069         /// <param name="blockNumber">
00070         /// Block number to read
00071         /// </param>
00072         /// <param name="keyType">
00073         /// Choose MIFARE key A or B
00074         /// </param>
00075         /// <param name="keySlotNumber">
00076         /// Slot where key has previously been stored with a previous call to Load Keys
00077         /// </param>
00078         /// <returns>
00079         /// byte array of 16 bytes
00080         /// </returns>
00081         public async Task<byte[]> ReadAsync(ushort blockNumber, GeneralAuthenticate.GeneralAuthenticateKeyType keyType, byte keySlotNumber = 0)
00082         {
00083             var genAuthRes = await connectionObject.TransceiveAsync(new MifareStandard.GeneralAuthenticate(blockNumber, keySlotNumber, keyType));
00084             if (!genAuthRes.Succeeded)
00085             {
00086                 throw new Exception("Failure authenticating to MIFARE Standard card, " + genAuthRes.ToString());
00087             }
00088
00089             var readRes = await connectionObject.TransceiveAsync(new MifareStandard.Read(blockNumber));
00090             if (!readRes.Succeeded)
00091             {
00092                 throw new Exception("Failure reading MIFARE Standard card, " + readRes.ToString());
00093             }
00094
00095             return readRes.ResponseData;
00096         }
00097         /// <summary>
00098         /// Wrapper method write 16 bytes at the pageAddress
00099         /// </param name="blockNumber">
00100         /// Block number
00101         /// </param>
00102         /// <param name="keyType">
00103         /// Choose MIFARE key A or B
00104         /// </param>
00105         /// <param name="keySlotNumber">
00106         /// Slot where key has previously been stored with a previous call to Load Keys
00107         /// </param>
00108         /// byte array of the data to write
00109         /// </returns>
00110         public async void WriteAsync(byte blockNumber, byte[] data, GeneralAuthenticate.GeneralAuthenticateKeyType keyType, byte keySlotNumber = 0)
00111         {
00112             if (data.Length != 16)
00113             {
00114                 throw new NotSupportedException();
00115             }
00116
00117             var genAuthRes = await connectionObject.TransceiveAsync(new MifareStandard.GeneralAuthenticate(blockNumber, keySlotNumber, keyType));
00118             if (!genAuthRes.Succeeded)
00119             {
00120                 throw new Exception("Failure authenticating to MIFARE Standard card, " + genAuthRes.ToString());
00121             }
00122
00123             var apduRes = await connectionObject.TransceiveAsync(new MifareStandard.Write(blockNumber, ref data));
00124             if (!apduRes.Succeeded)
00125             {
00126                 throw new Exception("Failure writing MIFARE Standard card, " + apduRes.ToString());
00127             }
00128         }
00129         /// <summary>
00130         /// Wrapper method to perform transparent transceive data to the Mifare Standard card
00131         /// </summary>
00132         /// <param name="commandData">
00133         /// The command to send to the Mifare Standard card
00134         /// </param>
00135         /// <returns>
00136         /// byte array of the read data
00137         /// </returns>
00138         public async Task<byte[]> TransparentExchangeAsync(byte[] commandData)
00139         {
00140             byte[] responseData = await connectionObject.TransparentExchangeAsync(commandData);
00141
00142             return responseData;
00143         }
00144         /// <summary>
00145         /// Wrapper method get the Mifare Standard ICC UID
00146         /// </summary>
00147         /// <returns>
00148         /// byte array UID
00149         /// </returns>
00150         public async Task<byte[]> GetUidAsync()
00151         {
00152             var apduRes = await connectionObject.TransceiveAsync(new MifareStandard.GetUid());
00153             if (!apduRes.Succeeded)
00154             {
00155                 throw new Exception("Failure getting UID of MIFARE Standard card, " + apduRes.ToString());
00156             }
00157
00158             return apduRes.ResponseData;
00159         }
00160     }
00161 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cppwinrt/SampleConfiguration.h Source File

  • FilePicker
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cs/BasicHologramMain.cs Source File

  • BasicHologram
  • cs

BasicHologramMain.cs

Go to the documentation of this file.
00001 ﻿//
00002 // Comment out this preprocessor definition to disable all of the
00003 // sample content.
00004 //
00005 // To remove the content after disabling it:
00006 //     * Remove the unused code from this file.
00007 //     * Delete the Content folder provided with this template.
00008 //
00009 #define DRAW_SAMPLE_CONTENT
00010
00011 using System;
00012 using System.Diagnostics;
00013 using Windows.Gaming.Input;
00014 using Windows.Graphics.DirectX.Direct3D11;
00015 using Windows.Graphics.Holographic;
00016 using Windows.Perception.Spatial;
00017 using Windows.UI.Input.Spatial;
00018
00019 using BasicHologram.Common;
00020 using System.Threading.Tasks;
00021 using Windows.Foundation;
00022 using System.Collections.Generic;
00023
00024 #if DRAW_SAMPLE_CONTENT
00025 using BasicHologram.Content;
00026 #endif
00027
00028 namespace BasicHologram
00029 {
00030     /// <summary>
00031     /// Updates, renders, and presents holographic content using Direct3D.
00032     /// </summary>
00033     internal class HolographicTemplateAppMain : IDisposable
00034     {
00035
00036 #if DRAW_SAMPLE_CONTENT
00037         // Renders a colorful holographic cube that's 20 centimeters wide. This sample content
00038         // is used to demonstrate world-locked rendering.
00039         private SpinningCubeRenderer        spinningCubeRenderer;
00040
00041         private SpatialInputHandler         spatialInputHandler;
00042 #endif
00043
00044         // Cached reference to device resources.
00045         private DeviceResources             deviceResources;
00046
00047         // Render loop timer.
00048         private StepTimer                   timer = new StepTimer();
00049
00050         // Represents the holographic space around the user.
00051         HolographicSpace                    holographicSpace;
00052
00053         // SpatialLocator that is attached to the default HolographicDisplay.
00054         SpatialLocator                      spatialLocator;
00055
00056         // A stationary reference frame based on spatialLocator.
00057         SpatialStationaryFrameOfReference   stationaryReferenceFrame;
00058
00059         // Keep track of gamepads.
00060         private class GamepadWithButtonState
00061         {
00062             public Windows.Gaming.Input.Gamepad gamepad;
00063             public bool buttonAWasPressedLastFrame;
00064             public GamepadWithButtonState(
00065                 Windows.Gaming.Input.Gamepad gamepad,
00066                 bool buttonAWasPressedLastFrame)
00067             {
00068                 this.gamepad = gamepad;
00069                 this.buttonAWasPressedLastFrame = buttonAWasPressedLastFrame;
00070             }
00071         };
00072         List<GamepadWithButtonState>        gamepads = new List<GamepadWithButtonState>();
00073
00074         // Keep track of mouse input.
00075         bool                                pointerPressed = false;
00076
00077         // Cache whether or not the HolographicCamera.Display property can be accessed.
00078         bool                                canGetHolographicDisplayForCamera = false;
00079
00080         // Cache whether or not the HolographicDisplay.GetDefault() method can be called.
00081         bool                                canGetDefaultHolographicDisplay = false;
00082
00083         // Cache whether or not the HolographicCameraRenderingParameters.CommitDirect3D11DepthBuffer() method can be called.
00084         bool                                canCommitDirect3D11DepthBuffer = false;
00085
00086         /// <summary>
00087         /// Loads and initializes application assets when the application is loaded.
00088         /// </summary>
00089         /// <param name="deviceResources"></param>
00090         public HolographicTemplateAppMain(DeviceResources deviceResources)
00091         {
00092             this.deviceResources = deviceResources;
00093
00094             // Register to be notified if the Direct3D device is lost.
00095             this.deviceResources.DeviceLost     += this.OnDeviceLost;
00096             this.deviceResources.DeviceRestored += this.OnDeviceRestored;
00097
00098             // If connected, a game controller can also be used for input.
00099             Gamepad.GamepadAdded += this.OnGamepadAdded;
00100             Gamepad.GamepadRemoved += this.OnGamepadRemoved;
00101
00102             foreach (var gamepad in Gamepad.Gamepads)
00103             {
00104                 OnGamepadAdded(null, gamepad);
00105             }
00106
00107             canGetHolographicDisplayForCamera = Windows.Foundation.Metadata.ApiInformation.IsPropertyPresent("Windows.Graphics.Holographic.HolographicCamera", "Display");
00108             canGetDefaultHolographicDisplay = Windows.Foundation.Metadata.ApiInformation.IsMethodPresent("Windows.Graphics.Holographic.HolographicDisplay", "GetDefault");
00109             canCommitDirect3D11DepthBuffer = Windows.Foundation.Metadata.ApiInformation.IsMethodPresent("Windows.Graphics.Holographic.HolographicCameraRenderingParameters", "CommitDirect3D11DepthBuffer");
00110         }
00111
00112         public void SetHolographicSpace(HolographicSpace holographicSpace)
00113         {
00114             this.holographicSpace = holographicSpace;
00115
00116             //
00117             // TODO: Add code here to initialize your content.
00118             //
00119
00120 #if DRAW_SAMPLE_CONTENT
00121             // Initialize the sample hologram.
00122             spinningCubeRenderer = new SpinningCubeRenderer(deviceResources);
00123
00124             spatialInputHandler = new SpatialInputHandler();
00125 #endif
00126
00127             if (canGetDefaultHolographicDisplay)
00128             {
00129                 // Subscribe for notifications about changes to the state of the default HolographicDisplay
00130                 // and its SpatialLocator.
00131                 HolographicSpace.IsAvailableChanged += this.OnHolographicDisplayIsAvailableChanged;
00132             }
00133
00134             // Acquire the current state of the default HolographicDisplay and its SpatialLocator.
00135             OnHolographicDisplayIsAvailableChanged(null, null);
00136
00137             // Respond to camera added events by creating any resources that are specific
00138             // to that camera, such as the back buffer render target view.
00139             // When we add an event handler for CameraAdded, the API layer will avoid putting
00140             // the new camera in new HolographicFrames until we complete the deferral we created
00141             // for that handler, or return from the handler without creating a deferral. This
00142             // allows the app to take more than one frame to finish creating resources and
00143             // loading assets for the new holographic camera.
00144             // This function should be registered before the app creates any HolographicFrames.
00145             holographicSpace.CameraAdded += this.OnCameraAdded;
00146
00147             // Respond to camera removed events by releasing resources that were created for that
00148             // camera.
00149             // When the app receives a CameraRemoved event, it releases all references to the back
00150             // buffer right away. This includes render target views, Direct2D target bitmaps, and so on.
00151             // The app must also ensure that the back buffer is not attached as a render target, as
00152             // shown in DeviceResources.ReleaseResourcesForBackBuffer.
00153             holographicSpace.CameraRemoved += this.OnCameraRemoved;
00154
00155             // Notes on spatial tracking APIs:
00156             // * Stationary reference frames are designed to provide a best-fit position relative to the
00157             //   overall space. Individual positions within that reference frame are allowed to drift slightly
00158             //   as the device learns more about the environment.
00159             // * When precise placement of individual holograms is required, a SpatialAnchor should be used to
00160             //   anchor the individual hologram to a position in the real world - for example, a point the user
00161             //   indicates to be of special interest. Anchor positions do not drift, but can be corrected; the
00162             //   anchor will use the corrected position starting in the next frame after the correction has
00163             //   occurred.
00164         }
00165
00166         public void Dispose()
00167         {
00168 #if DRAW_SAMPLE_CONTENT
00169             if (spinningCubeRenderer != null)
00170             {
00171                 spinningCubeRenderer.Dispose();
00172                 spinningCubeRenderer = null;
00173             }
00174 #endif
00175         }
00176
00177         /// <summary>
00178         /// Updates the application state once per frame.
00179         /// </summary>
00180         public HolographicFrame Update()
00181         {
00182             // Before doing the timer update, there is some work to do per-frame
00183             // to maintain holographic rendering. First, we will get information
00184             // about the current frame.
00185
00186             // The HolographicFrame has information that the app needs in order
00187             // to update and render the current frame. The app begins each new
00188             // frame by calling CreateNextFrame.
00189             HolographicFrame holographicFrame = holographicSpace.CreateNextFrame();
00190
00191             // Get a prediction of where holographic cameras will be when this frame
00192             // is presented.
00193             HolographicFramePrediction prediction = holographicFrame.CurrentPrediction;
00194
00195             // Back buffers can change from frame to frame. Validate each buffer, and recreate
00196             // resource views and depth buffers as needed.
00197             deviceResources.EnsureCameraResources(holographicFrame, prediction);
00198
00199 #if DRAW_SAMPLE_CONTENT
00200             if (stationaryReferenceFrame != null)
00201             {
00202                 // Check for new input state since the last frame.
00203                 for (int i = 0; i < gamepads.Count; ++i)
00204                 {
00205                     bool buttonDownThisUpdate = (gamepads[i].gamepad.GetCurrentReading().Buttons & GamepadButtons.A) == GamepadButtons.A;
00206                     if (buttonDownThisUpdate && !gamepads[i].buttonAWasPressedLastFrame)
00207                     {
00208                         pointerPressed = true;
00209                     }
00210                     gamepads[i].buttonAWasPressedLastFrame = buttonDownThisUpdate;
00211                 }
00212
00213                 SpatialInteractionSourceState pointerState = spatialInputHandler.CheckForInput();
00214                 SpatialPointerPose pose = null;
00215                 if (null != pointerState)
00216                 {
00217                     pose = pointerState.TryGetPointerPose(stationaryReferenceFrame.CoordinateSystem);
00218                 }
00219                 else if (pointerPressed)
00220                 {
00221                     pose = SpatialPointerPose.TryGetAtTimestamp(stationaryReferenceFrame.CoordinateSystem, prediction.Timestamp);
00222                 }
00223                 pointerPressed = false;
00224
00225                 // When a Pressed gesture is detected, the sample hologram will be repositioned
00226                 // two meters in front of the user.
00227                 spinningCubeRenderer.PositionHologram(pose);
00228             }
00229 #endif
00230
00231             timer.Tick(() =>
00232             {
00233                 //
00234                 // TODO: Update scene objects.
00235                 //
00236                 // Put time-based updates here. By default this code will run once per frame,
00237                 // but if you change the StepTimer to use a fixed time step this code will
00238                 // run as many times as needed to get to the current step.
00239                 //
00240
00241 #if DRAW_SAMPLE_CONTENT
00242                 spinningCubeRenderer.Update(timer);
00243 #endif
00244             });
00245
00246             if (!canCommitDirect3D11DepthBuffer)
00247             {
00248                 // On versions of the platform that do not support the CommitDirect3D11DepthBuffer API, we can control
00249                 // image stabilization by setting a focus point with optional plane normal and velocity.
00250                 foreach (var cameraPose in prediction.CameraPoses)
00251                 {
00252 #if DRAW_SAMPLE_CONTENT
00253                     // The HolographicCameraRenderingParameters class provides access to set
00254                     // the image stabilization parameters.
00255                     HolographicCameraRenderingParameters renderingParameters = holographicFrame.GetRenderingParameters(cameraPose);
00256
00257                     // SetFocusPoint informs the system about a specific point in your scene to
00258                     // prioritize for image stabilization. The focus point is set independently
00259                     // for each holographic camera. When setting the focus point, put it on or
00260                     // near content that the user is looking at.
00261                     // In this example, we put the focus point at the center of the sample hologram.
00262                     // You can also set the relative velocity and facing of the stabilization
00263                     // plane using overloads of this method.
00264                     if (stationaryReferenceFrame != null)
00265                     {
00266                         renderingParameters.SetFocusPoint(
00267                             stationaryReferenceFrame.CoordinateSystem,
00268                             spinningCubeRenderer.Position
00269                             );
00270                     }
00271 #endif
00272                 }
00273             }
00274
00275             // The holographic frame will be used to get up-to-date view and projection matrices and
00276             // to present the swap chain.
00277             return holographicFrame;
00278         }
00279
00280         /// <summary>
00281         /// Renders the current frame to each holographic display, according to the
00282         /// current application and spatial positioning state. Returns true if the
00283         /// frame was rendered to at least one display.
00284         /// </summary>
00285         public bool Render(HolographicFrame holographicFrame)
00286         {
00287             // Don't try to render anything before the first Update.
00288             if (timer.FrameCount == 0)
00289             {
00290                 return false;
00291             }
00292
00293             //
00294             // TODO: Add code for pre-pass rendering here.
00295             //
00296             // Take care of any tasks that are not specific to an individual holographic
00297             // camera. This includes anything that doesn't need the final view or projection
00298             // matrix, such as lighting maps.
00299             //
00300
00301             // Up-to-date frame predictions enhance the effectiveness of image stablization and
00302             // allow more accurate positioning of holograms.
00303             holographicFrame.UpdateCurrentPrediction();
00304             HolographicFramePrediction prediction = holographicFrame.CurrentPrediction;
00305
00306             // Lock the set of holographic camera resources, then draw to each camera
00307             // in this frame.
00308             return deviceResources.UseHolographicCameraResources(
00309                 (Dictionary<uint, CameraResources> cameraResourceDictionary) =>
00310             {
00311                 bool atLeastOneCameraRendered = false;
00312
00313                 foreach (var cameraPose in prediction.CameraPoses)
00314                 {
00315                     // This represents the device-based resources for a HolographicCamera.
00316                     CameraResources cameraResources = cameraResourceDictionary[cameraPose.HolographicCamera.Id];
00317
00318                     // Get the device context.
00319                     var context = deviceResources.D3DDeviceContext;
00320                     var renderTargetView = cameraResources.BackBufferRenderTargetView;
00321                     var depthStencilView = cameraResources.DepthStencilView;
00322
00323                     // Set render targets to the current holographic camera.
00324                     context.OutputMerger.SetRenderTargets(depthStencilView, renderTargetView);
00325
00326                     // Clear the back buffer and depth stencil view.
00327                     if (canGetHolographicDisplayForCamera &&
00328                         cameraPose.HolographicCamera.Display.IsOpaque)
00329                     {
00330                         SharpDX.Mathematics.Interop.RawColor4 cornflowerBlue = new SharpDX.Mathematics.Interop.RawColor4(0.392156899f, 0.58431375f, 0.929411829f, 1.0f);
00331                         context.ClearRenderTargetView(renderTargetView, cornflowerBlue);
00332                     }
00333                     else
00334                     {
00335                         SharpDX.Mathematics.Interop.RawColor4 transparent = new SharpDX.Mathematics.Interop.RawColor4(0.0f, 0.0f, 0.0f, 0.0f);
00336                         context.ClearRenderTargetView(renderTargetView, transparent);
00337                     }
00338                     context.ClearDepthStencilView(
00339                         depthStencilView,
00340                         SharpDX.Direct3D11.DepthStencilClearFlags.Depth | SharpDX.Direct3D11.DepthStencilClearFlags.Stencil,
00341                         1.0f,
00342                         0);
00343
00344                     //
00345                     // TODO: Replace the sample content with your own content.
00346                     //
00347                     // Notes regarding holographic content:
00348                     //    * For drawing, remember that you have the potential to fill twice as many pixels
00349                     //      in a stereoscopic render target as compared to a non-stereoscopic render target
00350                     //      of the same resolution. Avoid unnecessary or repeated writes to the same pixel,
00351                     //      and only draw holograms that the user can see.
00352                     //    * To help occlude hologram geometry, you can create a depth map using geometry
00353                     //      data obtained via the surface mapping APIs. You can use this depth map to avoid
00354                     //      rendering holograms that are intended to be hidden behind tables, walls,
00355                     //      monitors, and so on.
00356                     //    * On HolographicDisplays that are transparent, black pixels will appear transparent
00357                     //      to the user. On such devices, you should clear the screen to Transparent as shown
00358                     //      above. You should still use alpha blending to draw semitransparent holograms.
00359                     //
00360
00361
00362                     // The view and projection matrices for each holographic camera will change
00363                     // every frame. This function refreshes the data in the constant buffer for
00364                     // the holographic camera indicated by cameraPose.
00365                     if (stationaryReferenceFrame != null)
00366                     {
00367                         cameraResources.UpdateViewProjectionBuffer(deviceResources, cameraPose, stationaryReferenceFrame.CoordinateSystem);
00368                     }
00369
00370                     // Attach the view/projection constant buffer for this camera to the graphics pipeline.
00371                     bool cameraActive = cameraResources.AttachViewProjectionBuffer(deviceResources);
00372
00373 #if DRAW_SAMPLE_CONTENT
00374                     // Only render world-locked content when positional tracking is active.
00375                     if (cameraActive)
00376                     {
00377                         // Draw the sample hologram.
00378                         spinningCubeRenderer.Render();
00379
00380                         if (canCommitDirect3D11DepthBuffer)
00381                         {
00382                             // On versions of the platform that support the CommitDirect3D11DepthBuffer API, we can
00383                             // provide the depth buffer to the system, and it will use depth information to stabilize
00384                             // the image at a per-pixel level.
00385                             HolographicCameraRenderingParameters renderingParameters = holographicFrame.GetRenderingParameters(cameraPose);
00386                             SharpDX.Direct3D11.Texture2D depthBuffer = cameraResources.DepthBufferTexture2D;
00387
00388                             // Direct3D interop APIs are used to provide the buffer to the WinRT API.
00389                             SharpDX.DXGI.Resource1 depthStencilResource = depthBuffer.QueryInterface<SharpDX.DXGI.Resource1>();
00390                             SharpDX.DXGI.Surface2 depthDxgiSurface = new SharpDX.DXGI.Surface2(depthStencilResource, 0);
00391                             IDirect3DSurface depthD3DSurface = InteropStatics.CreateDirect3DSurface(depthDxgiSurface.NativePointer);
00392                             if (depthD3DSurface != null)
00393                             {
00394                                 // Calling CommitDirect3D11DepthBuffer causes the system to queue Direct3D commands to
00395                                 // read the depth buffer. It will then use that information to stabilize the image as
00396                                 // the HolographicFrame is presented.
00397                                 renderingParameters.CommitDirect3D11DepthBuffer(depthD3DSurface);
00398                             }
00399                         }
00400                     }
00401 #endif
00402                     atLeastOneCameraRendered = true;
00403                 }
00404
00405                 return atLeastOneCameraRendered;
00406             });
00407         }
00408
00409         public void SaveAppState()
00410         {
00411             //
00412             // TODO: Insert code here to save your app state.
00413             //       This method is called when the app is about to suspend.
00414             //
00415             //       For example, store information in the SpatialAnchorStore.
00416             //
00417         }
00418
00419         public void LoadAppState()
00420         {
00421             //
00422             // TODO: Insert code here to load your app state.
00423             //       This method is called when the app resumes.
00424             //
00425             //       For example, load information from the SpatialAnchorStore.
00426             //
00427         }
00428
00429         public void OnPointerPressed()
00430         {
00431             this.pointerPressed = true;
00432         }
00433
00434         /// <summary>
00435         /// Notifies renderers that device resources need to be released.
00436         /// </summary>
00437         public void OnDeviceLost(Object sender, EventArgs e)
00438         {
00439
00440 #if DRAW_SAMPLE_CONTENT
00441             spinningCubeRenderer.ReleaseDeviceDependentResources();
00442 #endif
00443
00444         }
00445
00446         /// <summary>
00447         /// Notifies renderers that device resources may now be recreated.
00448         /// </summary>
00449         public void OnDeviceRestored(Object sender, EventArgs e)
00450         {
00451 #if DRAW_SAMPLE_CONTENT
00452             spinningCubeRenderer.CreateDeviceDependentResourcesAsync();
00453 #endif
00454         }
00455
00456         void OnLocatabilityChanged(SpatialLocator sender, Object args)
00457         {
00458             switch (sender.Locatability)
00459             {
00460                 case SpatialLocatability.Unavailable:
00461                     // Holograms cannot be rendered.
00462                     {
00463                         String message = "Warning! Positional tracking is " + sender.Locatability + ".";
00464                         Debug.WriteLine(message);
00465                     }
00466                     break;
00467
00468                 // In the following three cases, it is still possible to place holograms using a
00469                 // SpatialLocatorAttachedFrameOfReference.
00470                 case SpatialLocatability.PositionalTrackingActivating:
00471                 // The system is preparing to use positional tracking.
00472
00473                 case SpatialLocatability.OrientationOnly:
00474                 // Positional tracking has not been activated.
00475
00476                 case SpatialLocatability.PositionalTrackingInhibited:
00477                     // Positional tracking is temporarily inhibited. User action may be required
00478                     // in order to restore positional tracking.
00479                     break;
00480
00481                 case SpatialLocatability.PositionalTrackingActive:
00482                     // Positional tracking is active. World-locked content can be rendered.
00483                     break;
00484             }
00485         }
00486
00487         public void OnCameraAdded(
00488             HolographicSpace sender,
00489             HolographicSpaceCameraAddedEventArgs args
00490             )
00491         {
00492             Deferral deferral = args.GetDeferral();
00493             HolographicCamera holographicCamera = args.Camera;
00494
00495             Task task1 = new Task(() =>
00496             {
00497                 //
00498                 // TODO: Allocate resources for the new camera and load any content specific to
00499                 //       that camera. Note that the render target size (in pixels) is a property
00500                 //       of the HolographicCamera object, and can be used to create off-screen
00501                 //       render targets that match the resolution of the HolographicCamera.
00502                 //
00503
00504                 // Create device-based resources for the holographic camera and add it to the list of
00505                 // cameras used for updates and rendering. Notes:
00506                 //   * Since this function may be called at any time, the AddHolographicCamera function
00507                 //     waits until it can get a lock on the set of holographic camera resources before
00508                 //     adding the new camera. At 60 frames per second this wait should not take long.
00509                 //   * A subsequent Update will take the back buffer from the RenderingParameters of this
00510                 //     camera's CameraPose and use it to create the ID3D11RenderTargetView for this camera.
00511                 //     Content can then be rendered for the HolographicCamera.
00512                 deviceResources.AddHolographicCamera(holographicCamera);
00513
00514                 // Holographic frame predictions will not include any information about this camera until
00515                 // the deferral is completed.
00516                 deferral.Complete();
00517             });
00518             task1.Start();
00519         }
00520
00521         public void OnCameraRemoved(
00522             HolographicSpace sender,
00523             HolographicSpaceCameraRemovedEventArgs args
00524             )
00525         {
00526             Task task2 = new Task(() =>
00527             {
00528                 //
00529                 // TODO: Asynchronously unload or deactivate content resources (not back buffer
00530                 //       resources) that are specific only to the camera that was removed.
00531                 //
00532             });
00533             task2.Start();
00534
00535             // Before letting this callback return, ensure that all references to the back buffer
00536             // are released.
00537             // Since this function may be called at any time, the RemoveHolographicCamera function
00538             // waits until it can get a lock on the set of holographic camera resources before
00539             // deallocating resources for this camera. At 60 frames per second this wait should
00540             // not take long.
00541             deviceResources.RemoveHolographicCamera(args.Camera);
00542         }
00543
00544         public void OnGamepadAdded(Object o, Gamepad args)
00545         {
00546             foreach (var gamepadWithButtonState in gamepads)
00547             {
00548                 if (args == gamepadWithButtonState.gamepad)
00549                 {
00550                     // This gamepad is already in the list.
00551                     return;
00552                 }
00553             }
00554
00555             gamepads.Add(new GamepadWithButtonState(args, false));
00556         }
00557
00558         public void OnGamepadRemoved(Object o, Gamepad args)
00559         {
00560             foreach (var gamepadWithButtonState in gamepads)
00561             {
00562                 if (args == gamepadWithButtonState.gamepad)
00563                 {
00564                     // This gamepad is in the list; remove it.
00565                     gamepads.Remove(gamepadWithButtonState);
00566                     return;
00567                 }
00568             }
00569         }
00570
00571         void OnHolographicDisplayIsAvailableChanged(Object o, Object args)
00572         {
00573             // Get the spatial locator for the default HolographicDisplay, if one is available.
00574             SpatialLocator spatialLocator = null;
00575             if (canGetDefaultHolographicDisplay)
00576             {
00577                 HolographicDisplay defaultHolographicDisplay = HolographicDisplay.GetDefault();
00578                 if (defaultHolographicDisplay != null)
00579                 {
00580                     spatialLocator = defaultHolographicDisplay.SpatialLocator;
00581                 }
00582             }
00583             else
00584             {
00585                 spatialLocator = SpatialLocator.GetDefault();
00586             }
00587
00588             if (this.spatialLocator != spatialLocator)
00589             {
00590                 // If the spatial locator is disconnected or replaced, we should discard any state that was
00591                 // based on it.
00592                 if (this.spatialLocator != null)
00593                 {
00594                     this.spatialLocator.LocatabilityChanged -= this.OnLocatabilityChanged;
00595                     this.spatialLocator = null;
00596                 }
00597
00598                 this.stationaryReferenceFrame = null;
00599
00600                 if (spatialLocator != null)
00601                 {
00602                     // Use the SpatialLocator from the default HolographicDisplay to track the motion of the device.
00603                     this.spatialLocator = spatialLocator;
00604
00605                     // Respond to changes in the positional tracking state.
00606                     this.spatialLocator.LocatabilityChanged += this.OnLocatabilityChanged;
00607
00608                     // The simplest way to render world-locked holograms is to create a stationary reference frame
00609                     // based on a SpatialLocator. This is roughly analogous to creating a "world" coordinate system
00610                     // with the origin placed at the device's position as the app is launched.
00611                     this.stationaryReferenceFrame = this.spatialLocator.CreateStationaryFrameOfReferenceAtCurrentLocation();
00612                 }
00613             }
00614         }
00615     }
00616 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Level3.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Level3.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Level3:
00015 // This class defines the third level of the game. In this level each of the
00016 // nine targets is moving along closed paths and can be hit
00017 // in any order.
00018
00019 #include "Level.h"
00020
00021 class Level3 : public Level
00022 {
00023 public:
00024     Level3();
00025     virtual void Initialize(std::vector<std::shared_ptr<GameObject>> const& objects) override;
00026 };
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ISecureInterfaceConsumer Member List

This is the complete list of members for ISecureInterfaceConsumer, including all inherited members.
IsUpperCaseEnabledChanged ISecureInterfaceConsumer
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCloudFontIntegration/cpp/SampleConfiguration.h Source File

  • XamlCloudFontIntegration
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "XAML Integration of DirectWrite Downloadable Fonts";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cppwinrt/Scenario5_LaunchedFromSecondaryTile.cpp Source File

  • SecondaryTiles
  • cppwinrt

Scenario5_LaunchedFromSecondaryTile.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario5_LaunchedFromSecondaryTile.h"
00014 #include "Scenario5_LaunchedFromSecondaryTile.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::UI::Xaml;
00019 using namespace Windows::UI::Xaml::Navigation;
00020
00021 namespace winrt::SDKTemplate::implementation
00022 {
00023     Scenario5_LaunchedFromSecondaryTile::Scenario5_LaunchedFromSecondaryTile()
00024     {
00025         InitializeComponent();
00026     }
00027
00028     void Scenario5_LaunchedFromSecondaryTile::OnNavigatedTo(NavigationEventArgs const& e)
00029     {
00030         auto launchParam = unbox_value_or<hstring>(e.Parameter(), {});
00031         if (!launchParam.empty())
00032             {
00033                 rootPage.NotifyUser(L"Application was activated from a Secondary Tile with the following Activation Arguments: " + launchParam, NotifyType::StatusMessage);
00034             }
00035
00036     }
00037 }
Generated on Fri Nov 15 2024 22:21:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSegmentation/cpp/Scenario1_ExtractTextSegments.xaml.h Source File

  • TextSegmentation
  • cpp

Scenario1_ExtractTextSegments.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "Scenario1_ExtractTextSegments.g.h"
00005
00006 namespace SDKTemplate
00007 {
00008     public ref class Scenario1_ExtractTextSegments sealed
00009     {
00010     public:
00011         Scenario1_ExtractTextSegments();
00012
00013     private:
00014         void WordSegmentsButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00015         void SelectionSegmentsButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00016     };
00017 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlMasterDetail/cs/Data/ItemsDataSource.cs Source File

  • XamlMasterDetail
  • cs
  • Data

ItemsDataSource.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006
00007 namespace MasterDetailApp.Data
00008 {
00009     public class ItemsDataSource
00010     {
00011         private static List<Item> _items = new List<Item>()
00012         {
00013             new Item()
00014             {
00015                 Id = 0,
00016                 DateCreated = DateTime.Now,
00017                 Title = "Item 1",
00018                 Text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer id facilisis lectus. Cras nec convallis ante, quis pulvinar tellus. Integer dictum accumsan pulvinar. Pellentesque eget enim sodales sapien vestibulum consequat.
00019
00020 Maecenas eu sapien ac urna aliquam dictum.
00021
00022 Nullam eget mattis metus. Donec pharetra, tellus in mattis tincidunt, magna ipsum gravida nibh, vitae lobortis ante odio vel quam."
00023             },
00024             new Item()
00025             {
00026                 Id = 1,
00027                 DateCreated = DateTime.Now,
00028                 Title = "Item 2",
00029                 Text = @"Quisque accumsan pretium ligula in faucibus. Mauris sollicitudin augue vitae lorem cursus condimentum quis ac mauris. Pellentesque quis turpis non nunc pretium sagittis. Nulla facilisi. Maecenas eu lectus ante. Proin eleifend vel lectus non tincidunt. Fusce condimentum luctus nisi, in elementum ante tincidunt nec.
00030
00031 Aenean in nisl at elit venenatis blandit ut vitae lectus. Praesent in sollicitudin nunc. Pellentesque justo augue, pretium at sem lacinia, scelerisque semper erat. Ut cursus tortor at metus lacinia dapibus."
00032             },
00033             new Item()
00034             {
00035                 Id = 2,
00036                 DateCreated = DateTime.Now,
00037                 Title = "Item 3",
00038                 Text = @"Ut consequat magna luctus justo egestas vehicula. Integer pharetra risus libero, et posuere justo mattis et.
00039
00040 Proin malesuada, libero vitae aliquam venenatis, diam est faucibus felis, vitae efficitur erat nunc non mauris. Suspendisse at sodales erat.
00041 Aenean vulputate, turpis non tincidunt ornare, metus est sagittis erat, id lobortis orci odio eget quam. Suspendisse ex purus, lobortis quis suscipit a, volutpat vitae turpis."
00042             },
00043             new Item()
00044             {
00045                 Id = 3,
00046                 DateCreated = DateTime.Now,
00047                 Title = "Item 4",
00048                 Text = @"Duis facilisis, quam ut laoreet commodo, elit ex aliquet massa, non varius tellus lectus et nunc. Donec vitae risus ut ante pretium semper. Phasellus consectetur volutpat orci, eu dapibus turpis. Fusce varius sapien eu mattis pharetra.
00049
00050 Nam vulputate eu erat ornare blandit. Proin eget lacinia erat. Praesent nisl lectus, pretium eget leo et, dapibus dapibus velit. Integer at bibendum mi, et fringilla sem."
00051             }
00052         };
00053
00054         public static IList<Item> GetAllItems()
00055         {
00056             return _items;
00057         }
00058
00059         public static Item GetItemById(int id)
00060         {
00061             return _items[id];
00062         }
00063     }
00064 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_ConfigureDevice Member List

This is the complete list of members for Scenario2_ConfigureDevice, including all inherited members.
BaudRateSetButton_Click(object sender, RoutedEventArgs e) | Scenario2_ConfigureDevice | [inline, private]
BreakStateSignalToggleSwitch_Toggled(object sender, RoutedEventArgs e) | Scenario2_ConfigureDevice | [inline, private]
DataBitsComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario2_ConfigureDevice | [inline, private]
DataTerminalReadyEnabledToggleSwitch_Toggled(object sender, RoutedEventArgs e) | Scenario2_ConfigureDevice | [inline, private]
HandShakeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario2_ConfigureDevice | [inline, private]
OnNavigatedTo(NavigationEventArgs eventArgs) | Scenario2_ConfigureDevice | [inline, protected]
ParityComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario2_ConfigureDevice | [inline, private]
RequestToSendEnabledToggleSwitch_Toggled(object sender, RoutedEventArgs e) | Scenario2_ConfigureDevice | [inline, private]
rootPage | Scenario2_ConfigureDevice | [private]
Scenario2_ConfigureDevice() | Scenario2_ConfigureDevice | [inline]
StopBitCountComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario2_ConfigureDevice | [inline, private]
UpdateBaudRateView() | Scenario2_ConfigureDevice | [inline, private]
UpdateBreakStateSignalView() | Scenario2_ConfigureDevice | [inline, private]
UpdateCarrierDetectStateView() | Scenario2_ConfigureDevice | [inline, private]
UpdateDataBitsView() | Scenario2_ConfigureDevice | [inline, private]
UpdateDataSetReadyStateView() | Scenario2_ConfigureDevice | [inline, private]
UpdateDataTerminalReadyEnabledView() | Scenario2_ConfigureDevice | [inline, private]
UpdateHandShakeView() | Scenario2_ConfigureDevice | [inline, private]
UpdateParityView() | Scenario2_ConfigureDevice | [inline, private]
UpdateRequestToSendEnabledView() | Scenario2_ConfigureDevice | [inline, private]
UpdateStopBitCountView() | Scenario2_ConfigureDevice | [inline, private]
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cpp/SampleConfiguration.h Source File

  • BasicInput
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "BasicInput C++ Sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cs/ShareHtml.xaml.cs Source File

  • ShareSource
  • cs

ShareHtml.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.DataTransfer;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public sealed partial class ShareHtml
00019     {
00020         public ShareHtml()
00021         {
00022             this.InitializeComponent();
00023             ShareWebView.Navigate(new Uri("http://msdn.microsoft.com"));
00024         }
00025
00026         private void ShareWebView_NavigationCompleted(object sender, WebViewNavigationCompletedEventArgs e)
00027         {
00028             ShareWebView.Visibility = Windows.UI.Xaml.Visibility.Visible;
00029             BlockingRect.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00030             LoadingProgressRing.IsActive = false;
00031         }
00032
00033         protected override bool GetShareContent(DataRequest request)
00034         {
00035             // Get the user's selection from the WebView. Since this is an asynchronous operation we need to acquire the deferral first.
00036             DataRequestDeferral deferral = request.GetDeferral();
00037
00038             // Make sure to always call Complete when done with the deferral.
00039             try
00040             {
00041                 var requestDataOperation = ShareWebView.CaptureSelectedContentToDataPackageAsync();
00042                 requestDataOperation.Completed += (asyncInfo, status) =>
00043                 {
00044                     DataPackage requestData = asyncInfo.GetResults();
00045                     if ((requestData != null) && (requestData.GetView().AvailableFormats.Count > 0))
00046                     {
00047                         requestData.Properties.Title = "A web snippet for you";
00048                         requestData.Properties.Description = "HTML selection from a WebView control"; // The description is optional.
00049                         requestData.Properties.ContentSourceApplicationLink = ApplicationLink;
00050                         requestData.Properties.ContentSourceWebLink = new Uri("http://msdn.microsoft.com");
00051                         request.Data = requestData;
00052                         deferral.Complete();
00053                     }
00054                     else
00055                     {
00056                         // FailWithDisplayText calls Complete on the deferral.
00057                         request.FailWithDisplayText("Make a selection in the WebView control and try again.");
00058                     }
00059                 };
00060             }
00061             catch (Exception)
00062             {
00063                 deferral.Complete();
00064             }
00065
00066             // At this point, we haven't populated the data package yet. It's done asynchronously above.
00067             return false;
00068         }
00069     }
00070 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Polling Member List

This is the complete list of members for Scenario2_Polling, including all inherited members.
Scenario2_Polling() | Scenario2_Polling
ScenarioGetData_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Polling
ScenarioGetSensor_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Polling
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cpp/pch.h Source File

  • CustomCapability
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // pch.h
00014 // Header for standard system include files.
00015 //
00016
00017 #pragma once
00018
00019 #include <collection.h>
00020 #include <ppltasks.h>
00021
00022 #include "App.xaml.h"
00023 #include "MainPage.xaml.h"
00024
00025 byte* GetArrayFromBuffer(Windows::Storage::Streams::IBuffer^ buffer);
00026
00027 void NotifyStatusMessage(Platform::String^ message, SDKTemplate::NotifyType messageType);
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCoordinateMapper/cpp/Content/TextRenderer.cpp Source File

  • CameraStreamCoordinateMapper
  • cpp
  • Content

TextRenderer.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "TextRenderer.h"
00014 #include "Common\DirectXHelper.h"
00015
00016 using namespace CameraStreamCoordinateMapper;
00017 using namespace Microsoft::WRL;
00018
00019 // Initializes D2D resources used for text rendering.
00020 TextRenderer::TextRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00021     m_deviceResources(deviceResources)
00022 {
00023     // Create device independent resources
00024     DX::ThrowIfFailed(m_deviceResources->GetDWriteFactory()->CreateTextFormat(
00025         L"Courier New",
00026         nullptr,
00027         DWRITE_FONT_WEIGHT_LIGHT,
00028         DWRITE_FONT_STYLE_NORMAL,
00029         DWRITE_FONT_STRETCH_NORMAL,
00030         24.0f,
00031         L"en-US",
00032         &m_textFormat));
00033
00034     DX::ThrowIfFailed(m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR));
00035
00036     DX::ThrowIfFailed(m_deviceResources->GetD2DFactory()->CreateDrawingStateBlock(&m_stateBlock));
00037
00038     CreateDeviceDependentResources();
00039 }
00040
00041 // Updates the text to be displayed.
00042 void TextRenderer::Update(std::wstring_view text)
00043 {
00044     DX::ThrowIfFailed(m_deviceResources->GetDWriteFactory()->CreateTextLayout(
00045         text.data(),
00046         static_cast<UINT32>(text.length()),
00047         m_textFormat.Get(),
00048         1024.0f, // Max width of the input text.
00049         256.0f, // Max height of the input text.
00050         &m_textLayout));
00051
00052     DX::ThrowIfFailed(m_textLayout->GetMetrics(&m_textMetrics));
00053 }
00054
00055 D2D1::Matrix3x2F GetScreenTranslation(const Windows::Foundation::Size& screenSize, const DWRITE_TEXT_METRICS& textMetrics, TextRenderer::TextAlignment alignment)
00056 {
00057     const float layoutOffsetX = screenSize.Width - textMetrics.layoutWidth;
00058     const float layoutOffsetY = screenSize.Height - textMetrics.height;
00059
00060     if (alignment == TextRenderer::TextAlignment::BottomRight)
00061     {
00062         return D2D1::Matrix3x2F::Translation(layoutOffsetX, layoutOffsetY);
00063     }
00064
00065     if (alignment == TextRenderer::TextAlignment::TopRight)
00066     {
00067         return D2D1::Matrix3x2F::Translation(layoutOffsetX, 0.0f);
00068     }
00069
00070     if (alignment == TextRenderer::TextAlignment::BottomLeft)
00071     {
00072         return D2D1::Matrix3x2F::Translation(0.0f, layoutOffsetY);
00073     }
00074
00075     return D2D1::Matrix3x2F::Translation(0.0f, 0.0f);
00076 }
00077
00078 DWRITE_TEXT_ALIGNMENT GetDwriteTextAlignment(TextRenderer::TextAlignment alignment)
00079 {
00080     if (alignment == TextRenderer::TextAlignment::TopLeft || alignment == TextRenderer::TextAlignment::BottomLeft)
00081     {
00082         return DWRITE_TEXT_ALIGNMENT_LEADING;
00083     }
00084     else
00085     {
00086         return DWRITE_TEXT_ALIGNMENT_TRAILING;
00087     }
00088 }
00089
00090 // Renders a frame to the screen.
00091 void TextRenderer::Render(TextAlignment alignment)
00092 {
00093     ID2D1DeviceContext* context = m_deviceResources->GetD2DDeviceContext();
00094     const Windows::Foundation::Size logicalSize = m_deviceResources->GetLogicalSize();
00095
00096     context->SaveDrawingState(m_stateBlock.Get());
00097     context->BeginDraw();
00098
00099     // Position on the bottom right corner
00100     const D2D1::Matrix3x2F screenTranslation = GetScreenTranslation(logicalSize, m_textMetrics, alignment);
00101
00102     context->SetTransform(screenTranslation * m_deviceResources->GetOrientationTransform2D());
00103
00104     DX::ThrowIfFailed(m_textFormat->SetTextAlignment(GetDwriteTextAlignment(alignment)));
00105
00106     context->DrawTextLayout(
00107         D2D1::Point2F(0.f, 0.f),
00108         m_textLayout.Get(),
00109         m_whiteBrush.Get());
00110
00111     // Ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00112     // is lost. It will be handled during the next call to Present.
00113     const HRESULT hr = context->EndDraw();
00114     if (hr != D2DERR_RECREATE_TARGET)
00115     {
00116         DX::ThrowIfFailed(hr);
00117     }
00118
00119     context->RestoreDrawingState(m_stateBlock.Get());
00120 }
00121
00122 void TextRenderer::CreateDeviceDependentResources()
00123 {
00124     DX::ThrowIfFailed(m_deviceResources->GetD2DDeviceContext()->CreateSolidColorBrush(
00125         D2D1::ColorF(D2D1::ColorF::White),
00126         &m_whiteBrush));
00127 }
00128 void TextRenderer::ReleaseDeviceDependentResources()
00129 {
00130     m_whiteBrush = nullptr;
00131 }
Generated on Fri Nov 15 2024 22:18:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraAdvancedCapture/cpp/MainPage.xaml.h Source File

  • CameraAdvancedCapture
  • cpp

MainPage.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "MainPage.g.h"
00015
00016 namespace CameraAdvancedCapture
00017 {
00018     ref class ReencodeState sealed
00019     {
00020     internal:
00021         Windows::Graphics::Imaging::BitmapDecoder^ Decoder;
00022         Windows::Graphics::Imaging::BitmapEncoder^ Encoder;
00023         Windows::Storage::StorageFile^ File;
00024         Windows::Storage::FileProperties::PhotoOrientation Orientation;
00025     };
00026
00027     /// <summary>
00028     /// Helper class to contain the information that describes an advanced capture
00029     /// </summary>
00030     ref class AdvancedCaptureContext
00031     {
00032     internal:
00033         Platform::String^ CaptureFileName;
00034         Windows::Storage::FileProperties::PhotoOrientation CaptureOrientation;
00035         Windows::Media::Capture::AdvancedCapturedPhoto^ Photo;
00036     };
00037
00038     public ref class MainPage sealed
00039     {
00040     private:
00041         // Receive notifications about rotation of the device and UI and apply any necessary rotation to the preview stream and UI controls
00042         Windows::Devices::Sensors::SimpleOrientationSensor^ _orientationSensor;
00043         Windows::Graphics::Display::DisplayInformation^ _displayInformation;
00044         Windows::Devices::Sensors::SimpleOrientation _deviceOrientation;
00045         Windows::Graphics::Display::DisplayOrientations _displayOrientation;
00046
00047         // Rotation metadata to apply to the preview stream and recorded videos (MF_MT_VIDEO_ROTATION)
00048         // Reference: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868174.aspx
00049         const GUID RotationKey;
00050
00051         // Folder in which the captures will be stored (availability check performed in SetupUiAsync)
00052         Windows::Storage::StorageFolder^ _captureFolder;
00053
00054         // Prevent the screen from sleeping while the camera is running
00055         Windows::System::Display::DisplayRequest^ _displayRequest;
00056
00057         // For listening to media property changes
00058         Windows::Media::SystemMediaTransportControls^ _systemMediaControls;
00059
00060         // MediaCapture and its state variables
00061         Platform::Agile<Windows::Media::Capture::MediaCapture^> _mediaCapture;
00062         bool _isInitialized;
00063         bool _isPreviewing;
00064
00065         // Holds the index of the current advanced capture mode (-1 for no advanced capture active)
00066         int _advancedCaptureMode = -1;
00067
00068         // Information about the camera device
00069         bool _externalCamera;
00070         bool _mirroringPreview;
00071
00072         // The value at which the certainty from the HDR analyzer maxes out in the graphical representation
00073         const double CERTAINTY_CAP = 0.7;
00074
00075         // Advanced Capture and Scene Analysis instances
00076         Windows::Media::Capture::AdvancedPhotoCapture^ _advancedCapture;
00077         Windows::Media::Core::SceneAnalysisEffect^ _sceneAnalysisEffect;
00078
00079         // Event tokens
00080         Windows::Foundation::EventRegistrationToken _applicationSuspendingEventToken;
00081         Windows::Foundation::EventRegistrationToken _applicationResumingEventToken;
00082         Windows::Foundation::EventRegistrationToken _mediaControlPropChangedEventToken;
00083         Windows::Foundation::EventRegistrationToken _displayInformationEventToken;
00084         Windows::Foundation::EventRegistrationToken _mediaCaptureFailedEventToken;
00085         Windows::Foundation::EventRegistrationToken _orientationChangedEventToken;
00086         Windows::Foundation::EventRegistrationToken _hardwareCameraButtonEventToken;
00087         Windows::Foundation::EventRegistrationToken _sceneAnalyzedEventToken;
00088         Windows::Foundation::EventRegistrationToken _allPhotosCapturedEventToken;
00089         Windows::Foundation::EventRegistrationToken _optionalRefPhotoCapturedEventToken;
00090
00091         // MediaCapture methods
00092         Concurrency::task<void> InitializeCameraAsync();
00093         Concurrency::task<void> CleanupCameraAsync();
00094         Concurrency::task<void> StartPreviewAsync();
00095         Concurrency::task<void> SetPreviewRotationAsync();
00096         Concurrency::task<void> StopPreviewAsync();
00097         Concurrency::task<void> CreateSceneAnalysisEffectAsync();
00098         Concurrency::task<void> CleanSceneAnalysisEffectAsync();
00099         Concurrency::task<void> EnableAdvancedCaptureAsync();
00100         void CycleAdvancedCaptureMode();
00101         Concurrency::task<void> DisableAdvancedCaptureAsync();
00102         Concurrency::task<void> TakeAdvancedCapturePhotoAsync();
00103
00104         // Helpers
00105         Concurrency::task<Windows::Devices::Enumeration::DeviceInformation^> FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel panel);
00106         Concurrency::task<void> ReencodeAndSavePhotoAsync(Windows::Storage::Streams::IRandomAccessStream^ stream, Windows::Storage::StorageFile^ file, Windows::Storage::FileProperties::PhotoOrientation photoOrientation);
00107         void UpdateUi();
00108         Concurrency::task<void> SetupUiAsync();
00109         Concurrency::task<void> CleanupUiAsync();
00110         void RegisterEventHandlers();
00111         void UnregisterEventHandlers();
00112         void WriteLine(Platform::String^ str);
00113         void WriteException(Platform::Exception^ ex);
00114         Concurrency::task<void> EmptyTask();
00115         static Platform::String^ GetTimeStr();
00116         static bool StringReplace(std::wstring& string, const std::wstring& removalStr, const std::wstring& replacementStr);
00117
00118         // Rotation helpers
00119         Windows::Devices::Sensors::SimpleOrientation GetCameraOrientation();
00120         Windows::Storage::FileProperties::PhotoOrientation ConvertOrientationToPhotoOrientation(Windows::Devices::Sensors::SimpleOrientation orientation);
00121         int ConvertDeviceOrientationToDegrees(Windows::Devices::Sensors::SimpleOrientation orientation);
00122         int ConvertDisplayOrientationToDegrees(Windows::Graphics::Display::DisplayOrientations orientation);
00123         void UpdateControlOrientation();
00124
00125         // UI event handlers
00126         void Application_Suspending(Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
00127         void Application_Resuming(Object^ sender, Object^ args);
00128         void DisplayInformation_OrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Object^ args);
00129         void SceneAnalysisEffect_SceneAnalyzed(Windows::Media::Core::SceneAnalysisEffect^ sender, Windows::Media::Core::SceneAnalyzedEventArgs^ args);
00130         void PhotoButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00131         void CycleModeButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00132         void SystemMediaControls_PropertyChanged(Windows::Media::SystemMediaTransportControls^ sender, Windows::Media::SystemMediaTransportControlsPropertyChangedEventArgs^ args);
00133         void OrientationSensor_OrientationChanged(Windows::Devices::Sensors::SimpleOrientationSensor^, Windows::Devices::Sensors::SimpleOrientationSensorOrientationChangedEventArgs^);
00134
00135         // Camera event handlers
00136         void AdvancedCapture_OptionalReferencePhotoCaptured(Windows::Media::Capture::AdvancedPhotoCapture^ sender, Windows::Media::Capture::OptionalReferencePhotoCapturedEventArgs^ args);
00137         void AdvancedCapture_AllPhotosCaptured(Windows::Media::Capture::AdvancedPhotoCapture^ sender, Object^ args);
00138         void HardwareButtons_CameraPress(Platform::Object^, Windows::Phone::UI::Input::CameraEventArgs^);
00139         void MediaCapture_Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ errorEventArgs);
00140
00141     protected:
00142         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00143         virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00144
00145     public:
00146         MainPage();
00147         virtual ~MainPage();
00148     };
00149 }
Generated on Fri Nov 15 2024 22:17:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-I2C/cppwinrt/SampleConfiguration.cpp Source File

  • IoT-I2C
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"I2C C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Read data from I2C device", xaml_typename<SDKTemplate::Scenario1_ReadData>() },
00029 });
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaTranscoding/cpp/SampleConfiguration.cpp Source File

  • MediaTranscoding
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Transcode using default presets", "SDKTemplate.Scenario1_Default" },
00021     { "Transcode with custom settings", "SDKTemplate.Scenario2_Custom" },
00022     { "Trim and transcode", "SDKTemplate.Scenario3_Trim" }
00023 };
Generated on Fri Nov 15 2024 22:17:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Audio/AudioFileReader.h Source File

  • HolographicVoiceInput
  • cpp
  • Audio

AudioFileReader.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012
00013 #include <vector>
00014
00015 //
00016 // Helper class uses MediaFoundation to read audio files
00017 //
00018 class AudioFileReader
00019 {
00020 public:
00021     virtual ~AudioFileReader() {}
00022     HRESULT Initialize(_In_ LPCWSTR filename);
00023
00024     const WAVEFORMATEX* GetFormat() const
00025     {
00026         return &_format;
00027     }
00028
00029     size_t GetSize() const
00030     {
00031         return _audioData.size();
00032     }
00033
00034     const BYTE* GetData() const
00035     {
00036         return _audioData.data();
00037     }
00038
00039 private:
00040     WAVEFORMATEX        _format;
00041     std::vector<BYTE>   _audioData;
00042 };
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cs/ShareDelayRenderedFiles.xaml.cs Source File

  • ShareSource
  • cs

ShareDelayRenderedFiles.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.DataTransfer;
00014 using Windows.Graphics.Imaging;
00015 using Windows.Storage;
00016 using Windows.Storage.Pickers;
00017 using Windows.Storage.Streams;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Media.Imaging;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class ShareDelayRenderedFiles
00024     {
00025         private StorageFile selectedImage;
00026
00027         public ShareDelayRenderedFiles()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         protected override bool GetShareContent(DataRequest request)
00033         {
00034             bool succeeded = false;
00035
00036             if (this.selectedImage != null)
00037             {
00038                 DataPackage requestData = request.Data;
00039                 requestData.Properties.Title = "Delay rendered image";
00040                 requestData.Properties.Description = "Resized image from the Share Source sample";
00041                 requestData.Properties.ContentSourceApplicationLink = ApplicationLink;
00042                 requestData.Properties.Thumbnail = RandomAccessStreamReference.CreateFromFile(this.selectedImage);
00043                 requestData.SetDataProvider(StandardDataFormats.Bitmap, providerRequest => this.OnDeferredImageRequestedHandler(providerRequest, this.selectedImage));
00044                 succeeded = true;
00045             }
00046             else
00047             {
00048                 request.FailWithDisplayText("Select an image you would like to share and try again.");
00049             }
00050             return succeeded;
00051         }
00052
00053         private async void OnDeferredImageRequestedHandler(DataProviderRequest providerRequest, StorageFile imageFile)
00054         {
00055             // In this delegate we provide updated Bitmap data using delayed rendering.
00056
00057             if (imageFile != null)
00058             {
00059                 // If the delegate is calling any asynchronous operations it needs to acquire the deferral first. This lets the
00060                 // system know that you are performing some operations that might take a little longer and that the call to
00061                 // SetData could happen after the delegate returns. Once you acquired the deferral object you must call Complete
00062                 // on it after your final call to SetData.
00063                 DataProviderDeferral deferral = providerRequest.GetDeferral();
00064                 InMemoryRandomAccessStream inMemoryStream = new InMemoryRandomAccessStream();
00065
00066                 // Make sure to always call Complete when done with the deferral.
00067                 try
00068                 {
00069                     // Decode the image and re-encode it at 50% width and height.
00070                     IRandomAccessStream imageStream = await imageFile.OpenAsync(FileAccessMode.Read);
00071                     BitmapDecoder imageDecoder = await BitmapDecoder.CreateAsync(imageStream);
00072                     BitmapEncoder imageEncoder = await BitmapEncoder.CreateForTranscodingAsync(inMemoryStream, imageDecoder);
00073                     imageEncoder.BitmapTransform.ScaledWidth = (uint)(imageDecoder.OrientedPixelWidth * 0.5);
00074                     imageEncoder.BitmapTransform.ScaledHeight = (uint)(imageDecoder.OrientedPixelHeight * 0.5);
00075                     await imageEncoder.FlushAsync();
00076
00077                     providerRequest.SetData(RandomAccessStreamReference.CreateFromStream(inMemoryStream));
00078                 }
00079                 finally
00080                 {
00081                     deferral.Complete();
00082                 }
00083             }
00084         }
00085
00086         private async void SelectImageButton_Click(object sender, RoutedEventArgs e)
00087         {
00088             FileOpenPicker imagePicker = new FileOpenPicker
00089             {
00090                 ViewMode = PickerViewMode.Thumbnail,
00091                 SuggestedStartLocation = PickerLocationId.PicturesLibrary,
00092                 FileTypeFilter = { ".jpg", ".png", ".bmp", ".gif", ".tif" }
00093             };
00094
00095             StorageFile pickedImage = await imagePicker.PickSingleFileAsync();
00096
00097             if (pickedImage != null)
00098             {
00099                 this.selectedImage = pickedImage;
00100
00101                 // Display the image in the UI.
00102                 IRandomAccessStream displayStream = await pickedImage.OpenAsync(FileAccessMode.Read);
00103                 BitmapImage bitmapImage = new BitmapImage();
00104                 bitmapImage.SetSource(displayStream);
00105                 ImageHolder.Source = bitmapImage;
00106                 this.rootPage.NotifyUser("Selected " + pickedImage.Name + ".", NotifyType.StatusMessage);
00107
00108                 ShareStep.Visibility = Visibility.Visible;
00109             }
00110         }
00111     }
00112 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Projection/cpp/MainPage.xaml.cpp Source File

  • Projection
  • cpp

MainPage.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "App.xaml.h"
00015
00016 #include <collection.h>
00017
00018 using namespace SDKSample;
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Controls::Primitives;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::UI::Xaml::Input;
00027 using namespace Windows::UI::Xaml::Media;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Xaml::Interop;
00030
00031 MainPage^ MainPage::Current;
00032
00033 MainPage::MainPage()
00034 {
00035     InitializeComponent();
00036     SampleTitle->Text = FEATURE_NAME;
00037
00038     // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00039     // in order to call methods that are in this class.
00040     MainPage::Current = this;
00041 }
00042
00043 void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
00044 {
00045     // Populate the ListBox with the scenarios as defined in SampleConfiguration.cpp.
00046     auto itemCollection = ref new Platform::Collections::Vector<Object^>();
00047     int i = 1;
00048     for (auto const& s : MainPage::Current->scenarios)
00049     {
00050         // Create a textBlock to hold the content and apply the ListItemTextStyle from Styles.xaml
00051         TextBlock^ textBlock = ref new TextBlock();
00052         ListBoxItem^ item = ref new ListBoxItem();
00053         auto style = App::Current->Resources->Lookup("ListItemTextStyle");
00054
00055         textBlock->Text = (i++).ToString() + ") " + s.Title;
00056         textBlock->Style = safe_cast<Windows::UI::Xaml::Style ^>(style);
00057
00058         item->Name = s.ClassName;
00059         item->Content = textBlock;
00060         itemCollection->Append(item);
00061     }
00062
00063     // Set the newly created itemCollection as the ListBox ItemSource.
00064     ScenarioControl->ItemsSource = itemCollection;
00065     int startingScenarioIndex;
00066
00067     if (Window::Current->Bounds.Width < 640)
00068     {
00069         startingScenarioIndex = -1;
00070     }
00071     else
00072     {
00073         startingScenarioIndex = 0;
00074     }
00075
00076     ScenarioControl->SelectedIndex = startingScenarioIndex;
00077     ScenarioControl->ScrollIntoView(ScenarioControl->SelectedItem);
00078 }
00079
00080
00081 void MainPage::ScenarioControl_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00082 {
00083     ListBox^ scenarioListBox = safe_cast<ListBox^>(sender); //as ListBox;
00084     ListBoxItem^ item = dynamic_cast<ListBoxItem^>(scenarioListBox->SelectedItem);
00085     if (item != nullptr)
00086     {
00087         // Clear the status block when changing scenarios
00088         NotifyUser("", NotifyType::StatusMessage);
00089
00090         // Navigate to the selected scenario.
00091         TypeName scenarioType = { item->Name, TypeKind::Custom };
00092         ScenarioFrame->Navigate(scenarioType, this);
00093
00094         if (Window::Current->Bounds.Width < 640)
00095         {
00096             Splitter->IsPaneOpen = false;
00097             StatusBorder->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00098         }
00099     }
00100 }
00101
00102 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00103 {
00104     switch (type)
00105     {
00106     case NotifyType::StatusMessage:
00107         StatusBorder->Background = ref new SolidColorBrush(Windows::UI::Colors::Green);
00108         break;
00109     case NotifyType::ErrorMessage:
00110         StatusBorder->Background = ref new SolidColorBrush(Windows::UI::Colors::Red);
00111         break;
00112     default:
00113         break;
00114     }
00115     StatusBlock->Text = strMessage;
00116
00117     // Collapse the StatusBlock if it has no text to conserve real estate.
00118     if (StatusBlock->Text != "")
00119     {
00120         StatusBorder->Visibility = Windows::UI::Xaml::Visibility::Visible;
00121         StatusPanel->Visibility = Windows::UI::Xaml::Visibility::Visible;
00122     }
00123     else
00124     {
00125         StatusBorder->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00126         StatusPanel->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00127     }
00128 }
00129
00130 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00131 {
00132     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00133     Windows::System::Launcher::LaunchUriAsync(uri);
00134 }
00135
00136 void MainPage::Button_Click(Object^ sender, RoutedEventArgs^ e)
00137 {
00138     Splitter->IsPaneOpen = !Splitter->IsPaneOpen;
00139     StatusBorder->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00140 }
Generated on Fri Nov 15 2024 22:17:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/ComputeShader/DftEffect.cpp Source File

  • D2DCustomEffects
  • cpp
  • ComputeShader

DftEffect.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <initguid.h>
00014 #include "DftEffect.h"
00015
00016 // Helper macro for defining XML strings.
00017 #define XML(X) TEXT(#X)
00018
00019 // This effect demonstrates how to implement a basic Discrete
00020 // Fourier Transform (DFT) custom Direct2D effect using DirectCompute.
00021 DftEffect::DftEffect() :
00022     m_cRef(0)
00023 {
00024 }
00025
00026 // Register the effect, its properties, and its creation method with D2D.
00027 HRESULT DftEffect::Register(_In_ ID2D1Factory1* pFactory)
00028 {
00029     PCWSTR pszXml =
00030         XML(
00031             <?xml version='1.0'?>
00032             <Effect>
00033                 <!-- System Properties -->
00034                 <Property name='DisplayName' type='string' value='Sample Discrete Fourier Transform (DFT) Compute Effect'/>
00035                 <Property name='Author' type='string' value='Microsoft Corporation'/>
00036                 <Property name='Category' type='string' value='Transform'/>
00037                 <Property name='Description' type='string'
00038                     value='A sample compute shader effect that computes the Discrete Fourier Transform of a given input.'/>
00039                 <Inputs>
00040                     <Input name='Source'/>
00041                 </Inputs>
00042             </Effect>
00043             );
00044
00045     return pFactory->RegisterEffectFromString(CLSID_CustomDftEffect, pszXml, nullptr, 0, Create);
00046 }
00047
00048 // A static method to create and return an instance of the effect.
00049 HRESULT __stdcall DftEffect::Create(_Outptr_ IUnknown** ppEffectImpl)
00050 {
00051     // Use the nothrow syntax so that we can return an HRESULT in the event of an allocation failure.
00052     // No try/catch is necessary here since there is no code / no possible exceptions in the constructor.
00053     *ppEffectImpl = static_cast<ID2D1EffectImpl *>(new (std::nothrow) DftEffect());
00054
00055     if (*ppEffectImpl == nullptr)
00056     {
00057         return E_OUTOFMEMORY;
00058     }
00059     else
00060     {
00061         (*ppEffectImpl)->AddRef();
00062         return S_OK;
00063     }
00064 }
00065
00066 // This effect method is called first, after the effect is instantiated with Create().
00067 IFACEMETHODIMP DftEffect::Initialize(
00068     _In_ ID2D1EffectContext* pEffectContext,
00069     _In_ ID2D1TransformGraph* pTransformGraph
00070     )
00071 {
00072     // Check for compute shader support - DX Feature Level 10_0 is not guaranteed to support compute shaders.
00073     // Immediately return if compute is not supported.
00074     D2D1_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS hardwareOptions;
00075     HRESULT hr = pEffectContext->CheckFeatureSupport(
00076         D2D1_FEATURE_D3D10_X_HARDWARE_OPTIONS,
00077         &hardwareOptions,
00078         sizeof(hardwareOptions)
00079         );
00080
00081     // As stated above, not all DX Feature Level 10_0 parts support compute shaders. In this sample's case,
00082     // it checks for compute shader support at device creation in DeviceResources. If support is missing,
00083     // it uses the WARP software fallback, which is guaranteed to support compute.
00084     // All effects that use compute shaders should perform this check at instantiation.
00085     if (SUCCEEDED(hr))
00086     {
00087         if (!hardwareOptions.computeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x)
00088         {
00089             return D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES;
00090         }
00091     }
00092     else
00093     {
00094         return hr;
00095     }
00096
00097     // Create new Transform nodes. The vertical transform must run after all of the horizontal code
00098     // has run, so it is performed in its own transform. Smart pointers are used here to avoid memory leaks
00099     // in the event of a failure.
00100     Microsoft::WRL::ComPtr<DftTransform> dftHorizontalTransform;
00101     Microsoft::WRL::ComPtr<DftTransform> dftVerticalTransform;
00102
00103     if (SUCCEEDED(hr))
00104     {
00105         try
00106         {
00107             dftHorizontalTransform = new (std::nothrow) DftTransform(pEffectContext, TransformType::Horizontal);
00108             dftVerticalTransform = new (std::nothrow) DftTransform(pEffectContext, TransformType::Vertical);
00109             if (dftHorizontalTransform == nullptr || dftVerticalTransform == nullptr)
00110             {
00111                 return E_OUTOFMEMORY;
00112             }
00113         }
00114         catch (Platform::Exception^ e)
00115         {
00116             // Return HRESULT if transform throws exception during creation.
00117             return e->HResult;
00118         }
00119     }
00120
00121     if (SUCCEEDED(hr))
00122     {
00123         // Add horizontal transform node to the graph. Still need to connect its inputs/outputs (done below).
00124         hr = pTransformGraph->AddNode(dftHorizontalTransform.Get());
00125     }
00126
00127     if (SUCCEEDED(hr))
00128     {
00129         // Connect the input of this transform node to the parent effect's input.
00130         hr = pTransformGraph->ConnectToEffectInput(0, dftHorizontalTransform.Get(), 0);
00131     }
00132
00133     if (SUCCEEDED(hr))
00134     {
00135         // Add vertical transform node to the graph. Still need to connect its inputs/outputs (done below).
00136         // Logically, this transform relies on the horizontal transform's output, and must be located
00137         // after it in the effect graph.
00138         hr = pTransformGraph->AddNode(dftVerticalTransform.Get());
00139     }
00140
00141     if (SUCCEEDED(hr))
00142     {
00143         // Connects the input of the DFTV transform node to the output of the DFTH transform node.
00144         hr = pTransformGraph->ConnectNode(dftHorizontalTransform.Get(), dftVerticalTransform.Get(), 0);
00145     }
00146
00147     if (SUCCEEDED(hr))
00148     {
00149         // Designates the output of the DFTV transform node as the output of the effect.
00150         hr = pTransformGraph->SetOutputNode(dftVerticalTransform.Get());
00151     }
00152
00153     return hr;
00154 }
00155
00156 // This method provides the effect implementation with an interface for
00157 // specifying its transform graph and transform graph changes. This will be
00158 // called when the effect is first initialized, and if the number of inputs
00159 // to the effect changes (variable-input effects).
00160 IFACEMETHODIMP DftEffect::SetGraph(_In_ ID2D1TransformGraph* pTransformGraph)
00161 {
00162     // Because this effect only has one input, it doesn't need to do anything here.
00163     return E_NOTIMPL;
00164 }
00165
00166 // During this method, the effect must finalize the topology of its internal
00167 // transform graph.  As in this example effect, the transform graph may already
00168 // have been configured by the effect's Initialize method.
00169 //
00170 // This effect method is called before rendering the effect but after
00171 // property changes occur.
00172 IFACEMETHODIMP DftEffect::PrepareForRender(D2D1_CHANGE_TYPE changeType)
00173 {
00174     return S_OK;
00175 }
00176
00177 IFACEMETHODIMP_(ULONG) DftEffect::AddRef()
00178 {
00179     // D2D ensures that that effects are only referenced from one thread at a time.
00180     // To improve performance, we simply increment/decrement our reference count
00181     // rather than use atomic InterlockedIncrement()/InterlockedDecrement() functions.
00182     m_cRef++;
00183
00184     return m_cRef;
00185 }
00186
00187 IFACEMETHODIMP_(ULONG) DftEffect::Release()
00188 {
00189     m_cRef--;
00190
00191     if (m_cRef == 0)
00192     {
00193         delete this;
00194         return 0;
00195     }
00196     else
00197     {
00198         return m_cRef;
00199     }
00200 }
00201
00202 IFACEMETHODIMP DftEffect::QueryInterface(
00203     REFIID riid,
00204     _Outptr_ void** ppOutput
00205     )
00206 {
00207     *ppOutput = nullptr;
00208     HRESULT hr = S_OK;
00209
00210     if (riid == __uuidof(ID2D1EffectImpl))
00211     {
00212         *ppOutput = static_cast<ID2D1EffectImpl*>(this);
00213     }
00214     else if (riid == __uuidof(IUnknown))
00215     {
00216         *ppOutput = this;
00217     }
00218     else
00219     {
00220         hr = E_NOINTERFACE;
00221     }
00222
00223     if (*ppOutput != nullptr)
00224     {
00225         AddRef();
00226     }
00227
00228     return hr;
00229 }
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JapanesePhoneticAnalysis/cs/Scenario1_Analyze.xaml.cs Source File

  • JapanesePhoneticAnalysis
  • cs

Scenario1_Analyze.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Text;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.Globalization;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario1_Analyze : Page
00022     {
00023         public Scenario1_Analyze()
00024         {
00025             this.InitializeComponent();
00026         }
00027
00028         private void AnalyzeButton_Click(object sender, RoutedEventArgs e)
00029         {
00030             string input = this.InputTextBox.Text;
00031             StringBuilder output = new StringBuilder();
00032
00033             // monoRuby = false means that each element in the result corresponds to a single Japanese word.
00034             // monoRuby = true means that each element in the result corresponds to one or more characters which are pronounced as a single unit.
00035             bool monoRuby = MonoRubyRadioButton.IsChecked == true;
00036
00037             // Analyze the Japanese text according to the specified algorithm.
00038             // The maximum length of the input string is 100 characters.
00039             IReadOnlyList<JapanesePhoneme> words = JapanesePhoneticAnalyzer.GetWords(input, monoRuby);
00040             foreach (JapanesePhoneme word in words)
00041             {
00042                 // Put each phrase on its own line.
00043                 if (output.Length != 0 && word.IsPhraseStart)
00044                 {
00045                     output.AppendLine();
00046                 }
00047                 // DisplayText is the display text of the word, which has same characters as the input of GetWords().
00048                 // YomiText is the reading text of the word, as known as Yomi, which typically consists of Hiragana characters.
00049                 // However, please note that the reading can contains some non-Hiragana characters for some display texts such as emoticons or symbols.
00050                 output.AppendFormat("{0}({1})", word.DisplayText, word.YomiText);
00051             }
00052
00053             // Display the result.
00054             string outputString = output.ToString();
00055             this.OutputTextBlock.Text = outputString;
00056             if (input != "" && words.Count == 0)
00057             {
00058                 // If the result from GetWords() is empty but the input is not empty,
00059                 // it means the given input is too long to analyze.
00060                 MainPage.Current.NotifyUser("Failed to get words from the input text.  The input text is too long to analyze.", NotifyType.ErrorMessage);
00061             }
00062             else
00063             {
00064                 // Otherwise, the analysis has been done successfully.
00065                 MainPage.Current.NotifyUser("Got words from the input text successfully.", NotifyType.StatusMessage);
00066             }
00067         }
00068     }
00069 }
Generated on Fri Nov 15 2024 22:20:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cpp/Scenario2_Display.xaml.h Source File

  • Playlists
  • cpp

Scenario2_Display.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario2_Display.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario2_Display sealed
00012     {
00013     public:
00014         Scenario2_Display();
00015     private:
00016         MainPage^ rootPage;
00017         void PickPlaylistButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00018     };
00019 }
Generated on Fri Nov 15 2024 22:20:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/WaveEffect.cpp Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

WaveEffect.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <initguid.h>
00014 #include "WaveEffect.h"
00015 #include "BasicReaderWriter.h"
00016
00017 #define XML(X) TEXT(#X)
00018
00019 static const float WaveMarginLeft = 0.25f;
00020 static const float WaveMarginTop = 0.20f;
00021 static const float WaveMarginRight = 0.25f;
00022 static const float WaveMarginBottom = 0.40f;
00023 static const float WaveHeight = 60;
00024 static const float SkewOffset = -0.4f;
00025 static const unsigned int TessellationAmount = 32;
00026
00027 HRESULT __stdcall WaveEffect::CreateWaveImpl(_Outptr_ IUnknown** ppEffectImpl)
00028 {
00029     *ppEffectImpl = static_cast<ID2D1EffectImpl*>(new (std::nothrow) WaveEffect());
00030
00031     if (*ppEffectImpl == nullptr)
00032     {
00033         return E_OUTOFMEMORY;
00034     }
00035     else
00036     {
00037         return S_OK;
00038     }
00039 }
00040
00041 HRESULT WaveEffect::Register(_In_ ID2D1Factory1* pFactory)
00042 {
00043     PCWSTR propertyXml =
00044         XML(
00045             <?xml version='1.0'?>
00046             <Effect>
00047                 <!-- System Properties -->
00048                 <Property name='DisplayName' type='string' value='Wave Effect'/>
00049                 <Property name='Author' type='string' value='Microsoft Corporation'/>
00050                 <Property name='Category' type='string' value='Sample'/>
00051                 <Property name='Description' type='string' value='Animation of a wave.'/>
00052                 <Inputs>
00053                     <Input name='Source'/>
00054                 </Inputs>
00055                 <!-- Effect-specific Properties -->
00056                 <Property name='WaveOffset' type='float' value='0'>
00057                     <Property name='DisplayName' type='string' value='Wave Offset'/>
00058                     <Property name='Default' type='float' value='0.0'/>
00059                 </Property>
00060                 <Property name='SkewX' type='float' value='0'>
00061                     <Property name='DisplayName' type='string' value='Skew (X-Axis)'/>
00062                     <Property name='Min' type='float' value='-5.0'/>
00063                     <Property name='Max' type='float' value='5.0'/>
00064                     <Property name='Default' type='float' value='0.0'/>
00065                 </Property>
00066                 <Property name='SkewY' type='float' value='0'>
00067                     <Property name='DisplayName' type='string' value='Skew (Y-Axis)'/>
00068                     <Property name='Min' type='float' value='-5.0'/>
00069                     <Property name='Max' type='float' value='5.0'/>
00070                     <Property name='Default' type='float' value='0.0'/>
00071                 </Property>
00072             </Effect>
00073             );
00074
00075     // Property bindings are performed automatically for the system properties.
00076     // For effect-specific properties (i.e. WaveOffset), you must direct
00077     // Direct2D to the specific method in your implementation for manipulating
00078     // the property. This is done by assigning each property a 'setter' and 'getter'
00079     // in this table. Direct2D provides a set of helpers for doing this in
00080     // D2D1EffectHelpers.h, such as D2D1_VALUE_TYPE_BINDING used here.
00081     D2D1_PROPERTY_BINDING bindings[] =
00082     {
00083         D2D1_VALUE_TYPE_BINDING(L"WaveOffset",  &SetWaveOffset,  &GetWaveOffset),
00084         D2D1_VALUE_TYPE_BINDING(L"SkewX",  &SetSkewX,  &GetSkewX),
00085         D2D1_VALUE_TYPE_BINDING(L"SkewY",  &SetSkewY,  &GetSkewY)
00086     };
00087
00088     // Register the effect using the data defined above.
00089     return pFactory->RegisterEffectFromString(
00090         CLSID_CustomWaveEffect,
00091         propertyXml,
00092         bindings,
00093         ARRAYSIZE(bindings),
00094         CreateWaveImpl
00095         );
00096 }
00097
00098 WaveEffect::WaveEffect() :
00099     m_refCount(1),
00100     m_waveOffset(0),
00101     m_skewX(0),
00102     m_skewY(0),
00103     m_sizeX(0),
00104     m_sizeY(0)
00105 {
00106 }
00107
00108 // This method is where as many resources should be initialized as possible.
00109 // While some resources may change over time and cannot be initialized until
00110 // the PrepareForRender() call, initializing resources in this method
00111 // reduces the amount of processing needed during rendering, improving the
00112 // performance of your effect.
00113 HRESULT WaveEffect::Initialize(
00114     _In_ ID2D1EffectContext* pEffectContext,
00115     _In_ ID2D1TransformGraph* pTransformGraph
00116     )
00117 {
00118     BasicReaderWriter^ reader = ref new BasicReaderWriter();
00119
00120     // Read compiled shader data instructions. Visual Studio automatically generates
00121     // the cso (Compiled Shader Object) file at compile time from the HLSL.
00122
00123     Platform::Array<unsigned char, 1U>^ data;
00124
00125     try
00126     {
00127         data = reader->ReadData("WaveEffect.cso");
00128     }
00129     catch (Platform::Exception^ e)
00130     {
00131         // Return error if file can not be read.
00132         return e->HResult;
00133     }
00134
00135     HRESULT hr = pEffectContext->LoadVertexShader(GUID_WaveTransformVertexShader, data->Data, data->Length);
00136
00137     if (SUCCEEDED(hr))
00138     {
00139         // Only generate the vertex buffer if it has not already been initialized.
00140         pEffectContext->FindVertexBuffer(&GUID_WaveTransformVertexBuffer, &m_vertexBuffer);
00141         if (m_vertexBuffer == nullptr)
00142         {
00143             Vertex* mesh = nullptr;
00144             hr = GenerateMesh(&mesh);
00145
00146             if (SUCCEEDED(hr))
00147             {
00148                 // Updating geometry every time the effect is rendered can be costly, so it is
00149                 // recommended that vertex buffer remain static if possible (which it is in this
00150                 // sample effect).
00151                 D2D1_VERTEX_BUFFER_PROPERTIES vbProp = {0};
00152                 vbProp.byteWidth = sizeof(Vertex) * m_numVertices;
00153                 vbProp.data = reinterpret_cast<BYTE*>(mesh);
00154                 vbProp.inputCount = 1;
00155                 vbProp.usage =  D2D1_VERTEX_USAGE_STATIC;
00156
00157                 static const D2D1_INPUT_ELEMENT_DESC vertexLayout[] =
00158                 {
00159                     {"MESH_POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0},
00160                 };
00161
00162                 D2D1_CUSTOM_VERTEX_BUFFER_PROPERTIES cvbProp = {0};
00163                 cvbProp.elementCount = ARRAYSIZE(vertexLayout);
00164                 cvbProp.inputElements = vertexLayout;
00165                 cvbProp.stride = sizeof(Vertex);
00166                 cvbProp.shaderBufferWithInputSignature = data->Data;
00167                 cvbProp.shaderBufferSize = data->Length;
00168
00169                 // The GUID is optional, and is provided here to register the geometry globally.
00170                 // As mentioned above, this avoids duplication if multiple versions of the effect
00171                 // are created.
00172                 hr = pEffectContext->CreateVertexBuffer(
00173                     &vbProp,
00174                     &GUID_WaveTransformVertexBuffer,
00175                     &cvbProp,
00176                     &m_vertexBuffer
00177                     );
00178             }
00179
00180             // Since mesh has already been transferred to GPU, it can be removed.
00181             delete[] mesh;
00182         }
00183     }
00184
00185     hr = pTransformGraph->SetSingleTransformNode(this);
00186
00187     return hr;
00188 }
00189
00190 HRESULT WaveEffect::GenerateMesh(_Outptr_ Vertex** ppMesh)
00191 {
00192     m_numVertices = 6 * TessellationAmount * TessellationAmount;
00193
00194     Vertex *mesh = new (std::nothrow) Vertex[m_numVertices];
00195
00196     if (mesh == nullptr)
00197     {
00198         return E_OUTOFMEMORY;
00199     }
00200
00201     float offset = 1.0f / TessellationAmount;
00202
00203     for (int i = 0; i < TessellationAmount; i++)
00204     {
00205         for (int j = TessellationAmount - 1; j >= 0; j--)
00206         {
00207             int index = (i * TessellationAmount + j) * 6;
00208
00209             // This mesh consists of pairs of triangles forming squares. Each square contains
00210             // six vertices, three for each triangle. 'offset' represents the distance between each vertice
00211             // in the triangles. In this mesh, we only set the x and y coordinates of the vertices, since
00212             // they are the only variable part of the geometry. In the vertex shader, z is generated
00213             // based on x, and w is defined to be '1'. The actual coordinates here range from 0 to 1,
00214             // these values are scaled up based on the size of the image in the vertex shader.
00215
00216             mesh[index].x     = i * offset;
00217             mesh[index].y     = j * offset;
00218             mesh[index + 1].x = i * offset;
00219             mesh[index + 1].y = j * offset + offset;
00220             mesh[index + 2].x = i * offset + offset;
00221             mesh[index + 2].y = j * offset;
00222             mesh[index + 3].x = i * offset + offset;
00223             mesh[index + 3].y = j * offset;
00224             mesh[index + 4].x = i * offset;
00225             mesh[index + 4].y = j * offset + offset;
00226             mesh[index + 5].x = i * offset + offset;
00227             mesh[index + 5].y = j * offset + offset;
00228         }
00229     }
00230
00231     *ppMesh = mesh;
00232
00233     return S_OK;
00234 }
00235
00236 // Called on first render and/or when the context changes.
00237 IFACEMETHODIMP WaveEffect::PrepareForRender(D2D1_CHANGE_TYPE changeType)
00238 {
00239     return UpdateConstants();
00240 }
00241
00242 // The effect properties are not automatically clamped based on the
00243 // registration XML. Effects should manually implement the min and
00244 // max specified at registration. These functions are called by Direct2D itself,
00245 // based on the property specified in the ID2D1Effect::SetValue call.
00246 HRESULT WaveEffect::SetSkewX(float skew)
00247 {
00248     m_skewX = Clamp(skew, -5.0f, 5.0f);
00249     return S_OK;
00250 }
00251
00252 HRESULT WaveEffect::SetSkewY(float skew)
00253 {
00254     m_skewY = Clamp(skew, -5.0f, 5.0f);
00255     return S_OK;
00256 }
00257
00258 // The wave offset is not clamped since no min or max is specified.
00259 HRESULT WaveEffect::SetWaveOffset(float waveOffset)
00260 {
00261     m_waveOffset = waveOffset;
00262     return S_OK;
00263 }
00264
00265 float WaveEffect::GetSkewX() const
00266 {
00267     return m_skewX;
00268 }
00269
00270 float WaveEffect::GetSkewY() const
00271 {
00272     return m_skewY;
00273 }
00274
00275 float WaveEffect::GetWaveOffset() const
00276 {
00277     return m_waveOffset;
00278 }
00279
00280 HRESULT WaveEffect::UpdateConstants()
00281 {
00282     // Update constant buffer 1 (the first constant buffer available to the effect)
00283     // with the progress, skew, and size values.
00284
00285     m_constants.matrix = D2D1::Matrix4x4F::RotationX(3);
00286     m_constants.sizeX = m_sizeX;
00287     m_constants.sizeY = m_sizeY;
00288     m_constants.waveOffset = m_waveOffset;
00289     m_constants.skewX = m_skewX;
00290     m_constants.skewY = m_skewY;
00291
00292     return m_drawInfo->SetVertexShaderConstantBuffer(reinterpret_cast<const BYTE*>(&m_constants), sizeof(m_constants));
00293
00294 }
00295
00296 IFACEMETHODIMP WaveEffect::MapOutputRectToInputRects(
00297     _In_ const D2D1_RECT_L* pOutputRect,
00298     _Out_writes_(inputRectCount) D2D1_RECT_L* pInputRects,
00299     UINT32 inputRectCount
00300     ) const
00301 {
00302     if (inputRectCount != 1)
00303     {
00304         return E_FAIL;
00305     }
00306
00307     pInputRects[0] = m_inputRect;
00308
00309     return S_OK;
00310 }
00311
00312 IFACEMETHODIMP WaveEffect::MapInputRectsToOutputRect(
00313     _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputRects,
00314     _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputOpaqueSubRects,
00315     UINT32 inputRectCount,
00316     _Out_ D2D1_RECT_L* pOutputRect,
00317     _Out_ D2D1_RECT_L* pOutputOpaqueSubRect
00318     )
00319 {
00320     HRESULT hr = S_OK;
00321
00322     if (inputRectCount != 1)
00323     {
00324         return E_FAIL;
00325     }
00326
00327     m_inputRect = pInputRects[0];
00328
00329     // Store the size of the rect so we can pass it into the vertex shader later.
00330     int newSizeX = pInputRects[0].right - pInputRects[0].left;
00331     int newSizeY = pInputRects[0].bottom - pInputRects[0].top;
00332
00333     if (m_sizeX != newSizeX || m_sizeY != newSizeY)
00334     {
00335         m_sizeX = static_cast<float>(newSizeX);
00336         m_sizeY = static_cast<float>(newSizeY);
00337         hr = UpdateConstants();
00338     }
00339
00340     if (SUCCEEDED(hr))
00341     {
00342         // Based on how the vertex shader is deforming the image, we can adjust the output rect to
00343         // avoid unnecessary rendering/blending. While simply setting the output rect to the input
00344         // rect is the simplest solution, there will be rendering errors if the custom effect is
00345         // subsequently transformed such that content that was previously outside screen bounds
00346         // should now be visible (i.e. a translation). If no geometric transformation is done to
00347         // an image, the outputRect can simply be assigned to the inputRect (*outputRect = m_inputRect)
00348
00349         long inputRectHeight = m_inputRect.bottom - m_inputRect.top;
00350         long inputRectWidth = m_inputRect.right - m_inputRect.left;
00351
00352         // These values are based on the transforms done in the vertex shader itself.
00353
00354         // SkewOffset is the point where the wave is perpendicular to the screen.
00355         if (m_skewY > SkewOffset)
00356         {
00357             pOutputRect->top    = static_cast<long>(m_inputRect.top +    (inputRectHeight * WaveMarginTop) - WaveHeight);
00358             pOutputRect->bottom = static_cast<long>(m_inputRect.bottom - (inputRectHeight * WaveMarginBottom) + WaveHeight + (inputRectHeight * m_skewY));
00359         }
00360         else
00361         {
00362             pOutputRect->top    = static_cast<long>(m_inputRect.top + (inputRectHeight * WaveMarginTop) - WaveHeight + (inputRectHeight * (m_skewY - SkewOffset)));
00363             pOutputRect->bottom = static_cast<long>(m_inputRect.top + (inputRectHeight * WaveMarginTop) + WaveHeight);
00364         }
00365
00366         if (m_skewX > 0)
00367         {
00368             pOutputRect->left  = static_cast<long>(m_inputRect.left   + (inputRectWidth * WaveMarginLeft));
00369             pOutputRect->right = static_cast<long>(m_inputRect.right  - (inputRectWidth * WaveMarginRight) + (inputRectWidth * m_skewX));
00370         }
00371         else
00372         {
00373             pOutputRect->left  = static_cast<long>(m_inputRect.left  + (inputRectWidth * WaveMarginLeft) + (inputRectWidth * m_skewX));
00374             pOutputRect->right = static_cast<long>(m_inputRect.right - (inputRectWidth * WaveMarginRight));
00375         }
00376
00377         // Indicate that entire output might contain transparency
00378         ZeroMemory(pOutputOpaqueSubRect, sizeof(*pOutputOpaqueSubRect));
00379     }
00380
00381     return hr;
00382 }
00383
00384 IFACEMETHODIMP WaveEffect::MapInvalidRect(
00385     UINT32 inputIndex,
00386     D2D1_RECT_L invalidInputRect,
00387     _Out_ D2D1_RECT_L* pInvalidOutputRect
00388     ) const
00389 {
00390     // Indicate that the entire output may be invalid.
00391     *pInvalidOutputRect = m_inputRect;
00392
00393     return S_OK;
00394 }
00395
00396 IFACEMETHODIMP WaveEffect::SetDrawInfo(
00397     _In_ ID2D1DrawInfo* pDrawInfo
00398     )
00399 {
00400     m_drawInfo = pDrawInfo;
00401
00402     D2D1_VERTEX_RANGE range;
00403     range.startVertex = 0;
00404     range.vertexCount = m_numVertices;
00405
00406     return m_drawInfo->SetVertexProcessing(
00407         m_vertexBuffer.Get(),
00408         D2D1_VERTEX_OPTIONS_USE_DEPTH_BUFFER,
00409         nullptr, // Setting the blend description to nullptr draws the geometry using a simple source-over blend.
00410         &range,
00411         &GUID_WaveTransformVertexShader
00412         );
00413 }
00414
00415 // D2D ensures that that effects are only referenced from one thread at a time.
00416 // To improve performance, we simply increment/decrement our reference count
00417 // rather than use atomic InterlockedIncrement()/InterlockedDecrement() functions.
00418 IFACEMETHODIMP_(ULONG) WaveEffect::AddRef()
00419 {
00420     m_refCount++;
00421     return m_refCount;
00422 }
00423
00424 IFACEMETHODIMP_(ULONG) WaveEffect::Release()
00425 {
00426     m_refCount--;
00427
00428     if (m_refCount == 0)
00429     {
00430         delete this;
00431         return 0;
00432     }
00433     else
00434     {
00435         return m_refCount;
00436     }
00437 }
00438
00439 // This enables the stack of parent interfaces to be queried. In the instance
00440 // of the Wave interface, this method simply enables casting a Wave
00441 // instance to an ID2D1EffectImpl or IUnknown instance.
00442 IFACEMETHODIMP WaveEffect::QueryInterface(
00443     _In_ REFIID riid,
00444     _Outptr_ void** ppOutput
00445     )
00446 {
00447     *ppOutput = nullptr;
00448     HRESULT hr = S_OK;
00449
00450     if (riid == __uuidof(ID2D1EffectImpl))
00451     {
00452         *ppOutput = reinterpret_cast<ID2D1EffectImpl*>(this);
00453     }
00454     else if (riid == __uuidof(ID2D1DrawTransform))
00455     {
00456         *ppOutput = static_cast<ID2D1DrawTransform*>(this);
00457     }
00458     else if (riid == __uuidof(ID2D1Transform))
00459     {
00460         *ppOutput = static_cast<ID2D1Transform*>(this);
00461     }
00462     else if (riid == __uuidof(ID2D1TransformNode))
00463     {
00464         *ppOutput = static_cast<ID2D1TransformNode*>(this);
00465     }
00466     else if (riid == __uuidof(IUnknown))
00467     {
00468         *ppOutput = this;
00469     }
00470     else
00471     {
00472         hr = E_NOINTERFACE;
00473     }
00474
00475     if (*ppOutput != nullptr)
00476     {
00477         AddRef();
00478     }
00479
00480     return hr;
00481 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Albums Member List

This is the complete list of members for Albums, including all inherited members.
Albums() | Albums | [inline]
vm | Albums | [private]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/HolographicTagAlongSampleMain.cpp Source File

  • HolographicTagAlong
  • cpp

HolographicTagAlongSampleMain.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "HolographicTagAlongSampleMain.h"
00014 #include "Common\DirectXHelper.h"
00015
00016 #include <windows.graphics.directx.direct3d11.interop.h>
00017 #include <Collection.h>
00018
00019 using namespace HolographicTagAlongSample;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Foundation::Numerics;
00025 using namespace Windows::Graphics::Holographic;
00026 using namespace Windows::Perception::Spatial;
00027 using namespace Windows::UI::Input::Spatial;
00028 using namespace std::placeholders;
00029
00030 // Loads and initializes application assets when the application is loaded.
00031 HolographicTagAlongSampleMain::HolographicTagAlongSampleMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00032     m_deviceResources(deviceResources)
00033 {
00034     // Register to be notified if the device is lost or recreated.
00035     m_deviceResources->RegisterDeviceNotify(this);
00036 }
00037
00038 void HolographicTagAlongSampleMain::SetHolographicSpace(HolographicSpace^ holographicSpace)
00039 {
00040     UnregisterHolographicEventHandlers();
00041
00042     m_holographicSpace = holographicSpace;
00043
00044 #ifdef DRAW_SAMPLE_CONTENT
00045     // Initialize the sample hologram.
00046     m_quadRenderer = std::make_unique<QuadRenderer>(m_deviceResources);
00047
00048     // Initialize the text renderer.
00049     constexpr unsigned int offscreenRenderTargetWidth = 2048;
00050     m_textRenderer = std::make_unique<TextRenderer>(m_deviceResources, offscreenRenderTargetWidth, offscreenRenderTargetWidth);
00051
00052     // Initialize the distance renderer.
00053     // The algorithm seems to break down if the target width is any smaller than 16 times the source width.
00054     // This is sufficient to reduce the memory requirement for the text message texture by a factor of 768, given the
00055     // reduction in channels:
00056     //   * Memory required to store the offscreen DirectWrite source texture: 2048 * 2048 * 3 = 12,582,912 bytes
00057     //   * Memory required to store the offscreen distance field texture:      128 *  128 * 1 =     16,384 bytes
00058     constexpr unsigned int blurTargetWidth = 256;
00059     m_distanceFieldRenderer = std::make_unique<DistanceFieldRenderer>(m_deviceResources, blurTargetWidth, blurTargetWidth);
00060
00061     // Use DirectWrite to create a high-resolution, antialiased image of vector-based text.
00062     RenderOffscreenTexture();
00063
00064     // Initialize the input handler.
00065     m_spatialInputHandler = std::make_unique<SpatialInputHandler>();
00066 #endif
00067
00068     // Use the default SpatialLocator to track the motion of the device.
00069     m_locator = SpatialLocator::GetDefault();
00070
00071     // Be able to respond to changes in the positional tracking state.
00072     m_locatabilityChangedToken =
00073         m_locator->LocatabilityChanged +=
00074             ref new Windows::Foundation::TypedEventHandler<SpatialLocator^, Object^>(
00075                 std::bind(&HolographicTagAlongSampleMain::OnLocatabilityChanged, this, _1, _2)
00076                 );
00077
00078     // Respond to camera added events by creating any resources that are specific
00079     // to that camera, such as the back buffer render target view.
00080     // When we add an event handler for CameraAdded, the API layer will avoid putting
00081     // the new camera in new HolographicFrames until we complete the deferral we created
00082     // for that handler, or return from the handler without creating a deferral. This
00083     // allows the app to take more than one frame to finish creating resources and
00084     // loading assets for the new holographic camera.
00085     // This function should be registered before the app creates any HolographicFrames.
00086     m_cameraAddedToken =
00087         m_holographicSpace->CameraAdded +=
00088             ref new Windows::Foundation::TypedEventHandler<HolographicSpace^, HolographicSpaceCameraAddedEventArgs^>(
00089                 std::bind(&HolographicTagAlongSampleMain::OnCameraAdded, this, _1, _2)
00090                 );
00091
00092     // Respond to camera removed events by releasing resources that were created for that
00093     // camera.
00094     // When the app receives a CameraRemoved event, it releases all references to the back
00095     // buffer right away. This includes render target views, Direct2D target bitmaps, and so on.
00096     // The app must also ensure that the back buffer is not attached as a render target, as
00097     // shown in DeviceResources::ReleaseResourcesForBackBuffer.
00098     m_cameraRemovedToken =
00099         m_holographicSpace->CameraRemoved +=
00100             ref new Windows::Foundation::TypedEventHandler<HolographicSpace^, HolographicSpaceCameraRemovedEventArgs^>(
00101                 std::bind(&HolographicTagAlongSampleMain::OnCameraRemoved, this, _1, _2)
00102                 );
00103
00104     // In this example, we create a reference frame attached to the device.
00105     m_attachedReferenceFrame = m_locator->CreateAttachedFrameOfReferenceAtCurrentHeading();
00106
00107     // For comparison, we can also render the hologram in a stationary location.
00108     m_stationaryReferenceFrame = m_locator->CreateStationaryFrameOfReferenceAtCurrentLocation();
00109
00110     // Notes on spatial tracking APIs:
00111     // * Stationary reference frames are designed to provide a best-fit position relative to the
00112     //   overall space. Individual positions within that reference frame are allowed to drift slightly
00113     //   as the device learns more about the environment.
00114     // * When precise placement of individual holograms is required, a SpatialAnchor should be used to
00115     //   anchor the individual hologram to a position in the real world - for example, a point the user
00116     //   indicates to be of special interest. Anchor positions do not drift, but can be corrected; the
00117     //   anchor will use the corrected position starting in the next frame after the correction has
00118     //   occurred.
00119 }
00120
00121 void HolographicTagAlongSampleMain::UnregisterHolographicEventHandlers()
00122 {
00123     if (m_holographicSpace != nullptr)
00124     {
00125         // Clear previous event registrations.
00126
00127         if (m_cameraAddedToken.Value != 0)
00128         {
00129             m_holographicSpace->CameraAdded -= m_cameraAddedToken;
00130             m_cameraAddedToken.Value = 0;
00131         }
00132
00133         if (m_cameraRemovedToken.Value != 0)
00134         {
00135             m_holographicSpace->CameraRemoved -= m_cameraRemovedToken;
00136             m_cameraRemovedToken.Value = 0;
00137         }
00138     }
00139
00140     if (m_locator != nullptr)
00141     {
00142         // Clear previous event registrations.
00143
00144         if (m_locatabilityChangedToken.Value != 0)
00145         {
00146             m_locator->LocatabilityChanged -= m_locatabilityChangedToken;
00147             m_locatabilityChangedToken.Value = 0;
00148         }
00149     }
00150 }
00151
00152 HolographicTagAlongSampleMain::~HolographicTagAlongSampleMain()
00153 {
00154     // Deregister device notification.
00155     m_deviceResources->RegisterDeviceNotify(nullptr);
00156
00157     UnregisterHolographicEventHandlers();
00158 }
00159
00160 // Updates the application state once per frame.
00161 HolographicFrame^ HolographicTagAlongSampleMain::Update()
00162 {
00163     // Before doing the timer update, there is some work to do per-frame
00164     // to maintain holographic rendering. First, we will get information
00165     // about the current frame.
00166
00167     // The HolographicFrame has information that the app needs in order
00168     // to update and render the current frame. The app begins each new
00169     // frame by calling CreateNextFrame.
00170     HolographicFrame^ holographicFrame = m_holographicSpace->CreateNextFrame();
00171
00172     // Get a prediction of where holographic cameras will be when this frame
00173     // is presented.
00174     HolographicFramePrediction^ prediction = holographicFrame->CurrentPrediction;
00175
00176     // Back buffers can change from frame to frame. Validate each buffer, and recreate
00177     // resource views and depth buffers as needed.
00178     m_deviceResources->EnsureCameraResources(holographicFrame, prediction);
00179
00180     // Next, we get a coordinate system from the attached frame of reference that is
00181     // associated with the current frame. Later, this coordinate system is used for
00182     // for creating the stereo view matrices when rendering the sample content.
00183     SpatialCoordinateSystem^ currentCoordinateSystem =
00184         m_attachedReferenceFrame->GetStationaryCoordinateSystemAtTimestamp(prediction->Timestamp);
00185
00186     m_timer.Tick([&] ()
00187     {
00188 #ifdef DRAW_SAMPLE_CONTENT
00189         // Check for new input state since the last frame.
00190         SpatialInteractionSourceState^ pointerState = m_spatialInputHandler->CheckForInput();
00191         if (pointerState != nullptr)
00192         {
00193             // When a Pressed gesture is detected, the hologram is placed or picked up.
00194             m_dropHologram = !m_dropHologram;
00195
00196             SpatialCoordinateSystem^ coordinateSystemFrom = nullptr;
00197             SpatialCoordinateSystem^ coordinateSystemTo = nullptr;
00198
00199             // Drop the hologram - or pick it up.
00200             if (m_dropHologram)
00201             {
00202                 // For comparison, we can also render the hologram in a stationary location.
00203                 m_stationaryReferenceFrame = m_locator->CreateStationaryFrameOfReferenceAtCurrentLocation();
00204
00205                 // Prepare to transform the hologram between coordinate systems.Z
00206                 coordinateSystemFrom = currentCoordinateSystem;
00207                 coordinateSystemTo = m_stationaryReferenceFrame->CoordinateSystem;
00208             }
00209             else
00210             {
00211                 // Prepare to transform the hologram between coordinate systems.Z
00212                 coordinateSystemFrom = m_stationaryReferenceFrame->CoordinateSystem;
00213                 coordinateSystemTo = currentCoordinateSystem;
00214
00215                 // We are done with the stationary reference frame.
00216                 m_stationaryReferenceFrame = nullptr;
00217             }
00218
00219             // The position is transformed between reference frames.
00220             Platform::IBox<float4x4>^ coordinateContainer = coordinateSystemFrom->TryGetTransformTo(coordinateSystemTo);
00221             if (coordinateContainer != nullptr)
00222             {
00223                 float4x4 const& coordinateSystemTransform = coordinateContainer->Value;
00224
00225                 float3 stationaryPosition = transform(m_quadRenderer->GetPosition(), coordinateSystemTransform);
00226                 m_quadRenderer->ResetPosition(stationaryPosition);
00227             }
00228         }
00229
00230         if (!m_dropHologram)
00231         {
00232             SpatialPointerPose^ pose = SpatialPointerPose::TryGetAtTimestamp(currentCoordinateSystem, prediction->Timestamp);
00233             m_quadRenderer->UpdateHologramPosition(pose, m_timer);
00234         }
00235
00236         m_quadRenderer->Update(m_timer);
00237 #endif
00238     });
00239
00240     // We complete the frame update by using information about our content positioning
00241     // to set the focus point.
00242
00243     for (auto cameraPose : prediction->CameraPoses)
00244     {
00245 #ifdef DRAW_SAMPLE_CONTENT
00246         // The HolographicCameraRenderingParameters class provides access to set
00247         // the image stabilization parameters.
00248         HolographicCameraRenderingParameters^ renderingParameters = holographicFrame->GetRenderingParameters(cameraPose);
00249
00250         // SetFocusPoint informs the system about a specific point in your scene to
00251         // prioritize for image stabilization. The focus point is set independently
00252         // for each holographic camera.
00253         // In this example, we set position, normal, and velocity for a tag-along quad.
00254         float3 const& focusPointPosition = m_quadRenderer->GetPosition();
00255         float3        focusPointNormal = focusPointPosition == float3(0.f) ? float3(0.f, 0.f, 1.f) : -normalize(focusPointPosition);
00256         float3 const& focusPointVelocity = m_quadRenderer->GetVelocity();
00257
00258         // Set the focus point.
00259         SpatialCoordinateSystem^ coordinateSystemToUse = m_dropHologram ? m_stationaryReferenceFrame->CoordinateSystem : currentCoordinateSystem;
00260         renderingParameters->SetFocusPoint(
00261             coordinateSystemToUse,
00262             focusPointPosition,
00263             focusPointNormal,
00264             focusPointVelocity
00265         );
00266 #endif
00267     }
00268
00269     // The holographic frame will be used to get up-to-date view and projection matrices and
00270     // to present the swap chain.
00271     return holographicFrame;
00272 }
00273
00274 // Renders the current frame to each holographic camera, according to the
00275 // current application and spatial positioning state. Returns true if the
00276 // frame was rendered to at least one camera.
00277 bool HolographicTagAlongSampleMain::Render(Windows::Graphics::Holographic::HolographicFrame^ holographicFrame)
00278 {
00279     // Don't try to render anything before the first Update.
00280     if (m_timer.GetFrameCount() == 0)
00281     {
00282         return false;
00283     }
00284
00285     // Lock the set of holographic camera resources, then draw to each camera
00286     // in this frame.
00287     return m_deviceResources->UseHolographicCameraResources<bool>(
00288         [this, holographicFrame](std::map<UINT32, std::unique_ptr<DX::CameraResources>>& cameraResourceMap)
00289     {
00290         // Up-to-date frame predictions enhance the effectiveness of image stablization and
00291         // allow more accurate positioning of holograms.
00292         holographicFrame->UpdateCurrentPrediction();
00293         HolographicFramePrediction^ prediction = holographicFrame->CurrentPrediction;
00294
00295         // Off-screen drawing used by all cameras.
00296         // The distance function texture only needs to be created once, for a given text string.
00297         if (m_distanceFieldRenderer->GetRenderCount() == 0)
00298         {
00299             m_distanceFieldRenderer->RenderDistanceField(m_textRenderer->GetTexture());
00300
00301             // The 2048x2048 texture will not be needed again, unless we get hit DeviceLost scenario.
00302             m_textRenderer->ReleaseDeviceDependentResources();
00303         }
00304
00305         bool atLeastOneCameraRendered = false;
00306         for (auto cameraPose : prediction->CameraPoses)
00307         {
00308             // This represents the device-based resources for a HolographicCamera.
00309             DX::CameraResources* pCameraResources = cameraResourceMap[cameraPose->HolographicCamera->Id].get();
00310
00311             // Get the device context.
00312             const auto context = m_deviceResources->GetD3DDeviceContext();
00313             const auto depthStencilView = pCameraResources->GetDepthStencilView();
00314
00315             // Set render targets to the current holographic camera.
00316             ID3D11RenderTargetView *const targets[1] = { pCameraResources->GetBackBufferRenderTargetView() };
00317             context->OMSetRenderTargets(1, targets, depthStencilView);
00318
00319             // Clear the back buffer and depth stencil view.
00320             context->ClearRenderTargetView(targets[0], DirectX::Colors::Transparent);
00321             context->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
00322
00323             // The view and projection matrices for each holographic camera will change
00324             // every frame. This function refreshes the data in the constant buffer for
00325             // the holographic camera indicated by cameraPose.
00326             pCameraResources->UpdateViewProjectionBuffer(
00327                 m_deviceResources,
00328                 cameraPose,
00329                 m_dropHologram ? m_stationaryReferenceFrame->CoordinateSystem :
00330                                  m_attachedReferenceFrame->GetStationaryCoordinateSystemAtTimestamp(prediction->Timestamp)
00331                 );
00332
00333             // Attach the view/projection constant buffer for this camera to the graphics pipeline.
00334             bool cameraActive = pCameraResources->AttachViewProjectionBuffer(m_deviceResources);
00335
00336 #ifdef DRAW_SAMPLE_CONTENT
00337             // This example content can always be rendered, as long as the content and Direct3D
00338             // device-based resources are done loading.
00339             if (cameraActive)
00340             {
00341                 // Draw the sample hologram.
00342                 m_quadRenderer->Render(m_distanceFieldRenderer->GetTexture());
00343             }
00344 #endif
00345             atLeastOneCameraRendered = true;
00346         }
00347
00348         return atLeastOneCameraRendered;
00349     });
00350 }
00351
00352 void HolographicTagAlongSampleMain::SaveAppState()
00353 {
00354     // This code sample does not persist any app state between sessions.
00355 }
00356
00357 void HolographicTagAlongSampleMain::LoadAppState()
00358 {
00359     // This code sample does not persist any app state between sessions.
00360 }
00361
00362 void HolographicTagAlongSampleMain::RenderOffscreenTexture()
00363 {
00364     m_textRenderer->RenderTextOffscreen(L"Hello, Hologram!\n");
00365 }
00366
00367 // Notifies classes that use Direct3D device resources that the device resources
00368 // need to be released before this method returns.
00369 void HolographicTagAlongSampleMain::OnDeviceLost()
00370 {
00371 #ifdef DRAW_SAMPLE_CONTENT
00372     m_quadRenderer->ReleaseDeviceDependentResources();
00373     m_distanceFieldRenderer->ReleaseDeviceDependentResources();
00374     m_textRenderer->ReleaseDeviceDependentResources();
00375 #endif
00376 }
00377
00378 // Notifies classes that use Direct3D device resources that the device resources
00379 // may now be recreated.
00380 void HolographicTagAlongSampleMain::OnDeviceRestored()
00381 {
00382 #ifdef DRAW_SAMPLE_CONTENT
00383     m_quadRenderer->CreateDeviceDependentResources();
00384     m_textRenderer->CreateDeviceDependentResources();
00385     m_distanceFieldRenderer->CreateDeviceDependentResources();
00386     RenderOffscreenTexture();
00387 #endif
00388 }
00389
00390 void HolographicTagAlongSampleMain::OnLocatabilityChanged(SpatialLocator^ sender, Object^ args)
00391 {
00392     switch (sender->Locatability)
00393     {
00394     case SpatialLocatability::Unavailable:
00395         // Holograms cannot be rendered.
00396         {
00397             String^ message = L"Warning! Positional tracking is " +
00398                               sender->Locatability.ToString() + L".\n";
00399             OutputDebugStringW(message->Data());
00400         }
00401         break;
00402
00403     // In the following three cases, it is still possible to place holograms using a
00404     // SpatialLocatorAttachedFrameOfReference.
00405     case SpatialLocatability::PositionalTrackingActivating:
00406         // The system is preparing to use positional tracking.
00407
00408     case SpatialLocatability::OrientationOnly:
00409         // Positional tracking has not been activated.
00410
00411     case SpatialLocatability::PositionalTrackingInhibited:
00412         // Positional tracking is temporarily inhibited. User action may be required
00413         // in order to restore positional tracking.
00414         break;
00415
00416     case SpatialLocatability::PositionalTrackingActive:
00417         // Positional tracking is active. World-locked content can be rendered.
00418         break;
00419     }
00420 }
00421
00422 void HolographicTagAlongSampleMain::OnCameraAdded(
00423     HolographicSpace^ sender,
00424     HolographicSpaceCameraAddedEventArgs^ args
00425     )
00426 {
00427     Deferral^ deferral = args->GetDeferral();
00428     HolographicCamera^ holographicCamera = args->Camera;
00429     create_task([this, deferral, holographicCamera] ()
00430     {
00431         // Create device-based resources for the holographic camera and add it to the list of
00432         // cameras used for updates and rendering. Notes:
00433         //   * Since this function may be called at any time, the AddHolographicCamera function
00434         //     waits until it can get a lock on the set of holographic camera resources before
00435         //     adding the new camera. At 60 frames per second this wait should not take long.
00436         //   * A subsequent Update will take the back buffer from the RenderingParameters of this
00437         //     camera's CameraPose and use it to create the ID3D11RenderTargetView for this camera.
00438         //     Content can then be rendered for the HolographicCamera.
00439         m_deviceResources->AddHolographicCamera(holographicCamera);
00440
00441         // Holographic frame predictions will not include any information about this camera until
00442         // the deferral is completed.
00443         deferral->Complete();
00444     });
00445 }
00446
00447 void HolographicTagAlongSampleMain::OnCameraRemoved(
00448     HolographicSpace^ sender,
00449     HolographicSpaceCameraRemovedEventArgs^ args
00450     )
00451 {
00452     // Before letting this callback return, ensure that all references to the back buffer
00453     // are released.
00454     // Since this function may be called at any time, the RemoveHolographicCamera function
00455     // waits until it can get a lock on the set of holographic camera resources before
00456     // deallocating resources for this camera. At 60 frames per second this wait should
00457     // not take long.
00458     m_deviceResources->RemoveHolographicCamera(args->Camera);
00459 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BackgroundDeviceWatcher Member List

This is the complete list of members for BackgroundDeviceWatcher, including all inherited members.
Run(IBackgroundTaskInstance taskInstance) BackgroundDeviceWatcher [inline]
Generated on Fri Nov 15 2024 22:23:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cppwinrt/Project.idl Source File

  • PenHaptics
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_InkCanvasTactileFeedback : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_InkCanvasTactileFeedback();
00018
00019         Windows.UI.Xaml.Controls.InkCanvas appInkCanvas{ get; };
00020     }
00021
00022     [default_interface]
00023     runtimeclass Scenario2_SupportedTactileFeedback : Windows.UI.Xaml.Controls.Page
00024     {
00025         Scenario2_SupportedTactileFeedback();
00026     }
00027
00028     [default_interface]
00029     runtimeclass Scenario3_InkingFeedback : Windows.UI.Xaml.Controls.Page
00030     {
00031         Scenario3_InkingFeedback();
00032     }
00033
00034     [default_interface]
00035     runtimeclass Scenario4_InteractionFeedback : Windows.UI.Xaml.Controls.Page
00036     {
00037         Scenario4_InteractionFeedback();
00038     }
00039
00040     [default_interface]
00041     runtimeclass Scenario5_InkingAndInteractionFeedback : Windows.UI.Xaml.Controls.Page
00042     {
00043         Scenario5_InkingAndInteractionFeedback();
00044     }
00045 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cpp/SampleConfiguration.h Source File

  • Calendar
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Calendar C++ sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlGamepadNavigation/cs/SampleConfiguration.cs Source File

  • XamlGamepadNavigation
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Resize app view";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Directional navigation", ClassType=typeof(Scenario1_Directions)},
00025             new Scenario() { Title="Engaging focus", ClassType=typeof(Scenario2_Engage)},
00026             new Scenario() { Title="Legacy controls", ClassType=typeof(Scenario3_Legacy)},
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035
00036     partial class App
00037     {
00038         partial void Construct()
00039         {
00040             // Setting RequiresPointerMode to WhenRequested sets the default behavior for
00041             // the entire app to enter mouse mode only when requested. This is typically
00042             // set in the App.xaml markup, but we do it here explicitly in code so that
00043             // the step is easier to see.
00044             this.RequiresPointerMode = Windows.UI.Xaml.ApplicationRequiresPointerMode.WhenRequested;
00045         }
00046     }
00047
00048 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FolderEnumeration/cppwinrt/Scenario3.h Source File

  • FolderEnumeration
  • cppwinrt

Scenario3.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario3 : Scenario3T<Scenario3>
00019     {
00020         Scenario3();
00021         fire_and_forget GetFilesButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00022
00023     private:
00024         static hstring GetPropertyDisplayValue(Windows::Foundation::IInspectable const& rawValue);
00025     };
00026 }
00027
00028 namespace winrt::SDKTemplate::factory_implementation
00029 {
00030     struct Scenario3 : Scenario3T<Scenario3, implementation::Scenario3>
00031     {
00032     };
00033 }
Generated on Fri Nov 15 2024 22:19:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBottomUpList/cs/Scenario2_Load.xaml.cs Source File

  • XamlBottomUpList
  • cs

Scenario2_Load.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.ObjectModel;
00014 using System.Threading.Tasks;
00015 using Windows.Foundation;
00016 using Windows.System;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Data;
00019 using Windows.UI.Xaml.Input;
00020
00021 namespace SDKTemplate
00022 {
00023     // Bindable class representing a single text message.
00024     public class TextMessage
00025     {
00026         public string Body { get; set; }
00027         public string DisplayTime { get; set; }
00028         public bool IsSent { get; set; }
00029         public bool IsReceived { get { return !IsSent; } }
00030     }
00031
00032     // Observable collection representing a text message conversation
00033     // that can load more items incrementally.
00034     public class Conversation : ObservableCollection<TextMessage>, ISupportIncrementalLoading
00035     {
00036         private uint messageCount = 0;
00037
00038         public Conversation()
00039         {
00040         }
00041
00042         public bool HasMoreItems { get; } = true;
00043
00044         public IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
00045         {
00046             this.CreateMessages(count);
00047
00048             return Task.FromResult<LoadMoreItemsResult>(
00049                 new LoadMoreItemsResult()
00050                 {
00051                     Count = count
00052                 }).AsAsyncOperation();
00053         }
00054
00055         private void CreateMessages(uint count)
00056         {
00057             for (uint i = 0; i < count; i++)
00058             {
00059                 this.Insert(0, new TextMessage()
00060                 {
00061                     Body = $"{messageCount}: {CreateRandomMessage()}",
00062                     IsSent = 0 == messageCount++ % 2,
00063                     DisplayTime = DateTime.Now.ToString()
00064                 });
00065             }
00066         }
00067
00068         private static Random rand = new Random();
00069         private static string fillerText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
00070
00071         public static string CreateRandomMessage()
00072         {
00073             return fillerText.Substring(0, rand.Next(5, fillerText.Length));
00074         }
00075     }
00076
00077     /// <summary>
00078     /// This ListView is tailored to a Chat experience where the focus is on the last item in the list
00079     /// and as the user scrolls up the older messages are incrementally loaded.  We're performing our
00080     /// own logic to trigger loading more data.
00081     /// //
00082     /// Note: This is just delay loading the data, but isn't true data virtualization.  A user that
00083     /// scrolls all the way to the beginning of the list will cause all the data to be loaded.
00084     /// </summary>
00085     public class ChatListView : ListView
00086     {
00087         private uint itemsSeen;
00088         private double averageContainerHeight;
00089         private bool processingScrollOffsets = false;
00090         private bool processingScrollOffsetsDeferred = false;
00091
00092         public ChatListView()
00093         {
00094             // We'll manually trigger the loading of data incrementally and buffer for 2 pages worth of data
00095             this.IncrementalLoadingTrigger = IncrementalLoadingTrigger.None;
00096
00097             // Since we'll have variable sized items we compute a running average of height to help estimate
00098             // how much data to request for incremental loading
00099             this.ContainerContentChanging += this.UpdateRunningAverageContainerHeight;
00100         }
00101
00102         protected override void OnApplyTemplate()
00103         {
00104             var scrollViewer = this.GetTemplateChild("ScrollViewer") as ScrollViewer;
00105
00106             if (scrollViewer != null)
00107             {
00108                 scrollViewer.ViewChanged += (s, a) =>
00109                 {
00110                     // Check if we should load more data when the scroll position changes.
00111                     // We only get this once the content/panel is large enough to be scrollable.
00112                     this.StartProcessingDataVirtualizationScrollOffsets(this.ActualHeight);
00113                 };
00114             }
00115
00116             base.OnApplyTemplate();
00117         }
00118
00119         // We use ArrangeOverride to trigger incrementally loading data (if needed) when the panel is too small to be scrollable.
00120         protected override Size ArrangeOverride(Size finalSize)
00121         {
00122             // Allow the panel to arrange first
00123             var result = base.ArrangeOverride(finalSize);
00124
00125             StartProcessingDataVirtualizationScrollOffsets(finalSize.Height);
00126
00127             return result;
00128         }
00129
00130         private async void StartProcessingDataVirtualizationScrollOffsets(double actualHeight)
00131         {
00132             // Avoid re-entrancy. If we are already processing, then defer this request.
00133             if (processingScrollOffsets)
00134             {
00135                 processingScrollOffsetsDeferred = true;
00136                 return;
00137             }
00138
00139             this.processingScrollOffsets = true;
00140
00141             do
00142             {
00143                 processingScrollOffsetsDeferred = false;
00144                 await ProcessDataVirtualizationScrollOffsetsAsync(actualHeight);
00145
00146                 // If a request to process scroll offsets occurred while we were processing
00147                 // the previous request, then process the deferred request now.
00148             }
00149             while (processingScrollOffsetsDeferred);
00150
00151             // We have finished. Allow new requests to be processed.
00152             this.processingScrollOffsets = false;
00153         }
00154
00155         private async Task ProcessDataVirtualizationScrollOffsetsAsync(double actualHeight)
00156         {
00157             var panel = this.ItemsPanelRoot as ItemsStackPanel;
00158             if (panel != null)
00159             {
00160                 if ((panel.FirstVisibleIndex != -1 && panel.FirstVisibleIndex * this.averageContainerHeight < actualHeight * this.IncrementalLoadingThreshold) ||
00161                     (Items.Count == 0))
00162                 {
00163                     var virtualizingDataSource = this.ItemsSource as ISupportIncrementalLoading;
00164                     if (virtualizingDataSource != null)
00165                     {
00166                         if (virtualizingDataSource.HasMoreItems)
00167                         {
00168                             uint itemsToLoad;
00169                             if (this.averageContainerHeight == 0.0)
00170                             {
00171                                 // We don't have any items yet. Load the first one so we can get an
00172                                 // estimate of the height of one item, and then we can load the rest.
00173                                 itemsToLoad = 1;
00174                             }
00175                             else
00176                             {
00177                                 double avgItemsPerPage = actualHeight / this.averageContainerHeight;
00178                                 // We know there's data to be loaded so load at least one item
00179                                 itemsToLoad = Math.Max((uint)(this.DataFetchSize * avgItemsPerPage), 1);
00180                             }
00181
00182                             await virtualizingDataSource.LoadMoreItemsAsync(itemsToLoad);
00183                         }
00184                     }
00185                 }
00186             }
00187         }
00188
00189         private void UpdateRunningAverageContainerHeight(ListViewBase sender, ContainerContentChangingEventArgs args)
00190         {
00191             if (args.ItemContainer != null && !args.InRecycleQueue)
00192             {
00193                 switch (args.Phase)
00194                 {
00195                     case 0:
00196                         // use the size of the very first placeholder as a starting point until
00197                         // we've seen the first item
00198                         if (this.averageContainerHeight == 0)
00199                         {
00200                             this.averageContainerHeight = args.ItemContainer.DesiredSize.Height;
00201                         }
00202
00203                         args.RegisterUpdateCallback(1, this.UpdateRunningAverageContainerHeight);
00204                         args.Handled = true;
00205                         break;
00206
00207                     case 1:
00208                         // set the content
00209                         args.ItemContainer.Content = args.Item;
00210                         args.RegisterUpdateCallback(2, this.UpdateRunningAverageContainerHeight);
00211                         args.Handled = true;
00212                         break;
00213
00214                     case 2:
00215                         // refine the estimate based on the item's DesiredSize
00216                         this.averageContainerHeight = (this.averageContainerHeight * itemsSeen + args.ItemContainer.DesiredSize.Height) / ++itemsSeen;
00217                         args.Handled = true;
00218                         break;
00219                 }
00220             }
00221         }
00222     }
00223
00224     public sealed partial class Scenario2_Load : Page
00225     {
00226         private readonly Conversation conversation = new Conversation();
00227
00228         public Scenario2_Load()
00229         {
00230             this.InitializeComponent();
00231
00232             chatView.ItemsSource = this.conversation;
00233
00234             chatView.ContainerContentChanging += OnChatViewContainerContentChanging;
00235         }
00236
00237         async void SendTextMessage()
00238         {
00239             if (MessageTextBox.Text.Length > 0)
00240             {
00241                 this.conversation.Add(new TextMessage
00242                 {
00243                     Body = MessageTextBox.Text,
00244                     DisplayTime = DateTime.Now.ToString(),
00245                     IsSent = true
00246                 });
00247                 MessageTextBox.Text = string.Empty;
00248
00249                 // Send a simulated reply after a brief delay.
00250                 await Task.Delay(TimeSpan.FromSeconds(2));
00251
00252                 this.conversation.Add(new TextMessage
00253                 {
00254                     Body = Conversation.CreateRandomMessage(),
00255                     DisplayTime = DateTime.Now.ToString(),
00256                     IsSent = false
00257                 });
00258             }
00259         }
00260
00261         private void OnChatViewContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
00262         {
00263             if (args.InRecycleQueue) return;
00264             TextMessage message = (TextMessage)args.Item;
00265             args.ItemContainer.HorizontalAlignment = message.IsSent ? Windows.UI.Xaml.HorizontalAlignment.Right : Windows.UI.Xaml.HorizontalAlignment.Left;
00266         }
00267
00268         private void MessageTextBox_KeyUp(object sender, KeyRoutedEventArgs e)
00269         {
00270             if (e.Key == VirtualKey.Enter)
00271             {
00272                 this.SendTextMessage();
00273             }
00274         }
00275     }
00276 }
Generated on Fri Nov 15 2024 22:22:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomTitleBar Member List

This is the complete list of members for CustomTitleBar, including all inherited members.
coreTitleBar | CustomTitleBar | [private]
CoreTitleBarHeight | CustomTitleBar |
CoreTitleBarPadding | CustomTitleBar |
CustomTitleBar() | CustomTitleBar | [inline]
CustomTitleBar_Loaded(object sender, RoutedEventArgs e) | CustomTitleBar | [inline, private]
CustomTitleBar_Unloaded(object sender, RoutedEventArgs e) | CustomTitleBar | [inline, private]
EnableControlsInTitleBar(bool enable) | CustomTitleBar | [inline]
OnIsVisibleChanged(CoreApplicationViewTitleBar sender, object e) | CustomTitleBar | [inline, private]
OnLayoutMetricsChanged(CoreApplicationViewTitleBar sender, object e) | CustomTitleBar | [inline, private]
OnWindowSizeChanged(object sender, WindowSizeChangedEventArgs e) | CustomTitleBar | [inline, private]
pageContent | CustomTitleBar | [private]
PropertyChanged | CustomTitleBar |
SetPageContent(UIElement newContent) | CustomTitleBar | [inline]
UpdateLayoutMetrics() | CustomTitleBar | [inline, private]
UpdatePositionAndVisibility() | CustomTitleBar | [inline, private]
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cpp/pch.cpp Source File

  • Store
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // pch.cpp
00014 // Include the standard header and generate the precompiled header.
00015 //
00016
00017 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlWebView/cs/Scenario3_InvokeScript.xaml.cs Source File

  • XamlWebView
  • cs

Scenario3_InvokeScript.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using System;
00015
00016 namespace SDKTemplate
00017 {
00018     public sealed partial class Scenario3_InvokeScript : Page
00019     {
00020         private MainPage rootPage = MainPage.Current;
00021
00022         public Scenario3_InvokeScript()
00023         {
00024             this.InitializeComponent();
00025         }
00026
00027         protected override async void OnNavigatedTo(NavigationEventArgs e)
00028         {
00029             HtmlBox.Text = await MainPage.LoadStringFromPackageFileAsync("script_example.html");
00030         }
00031
00032         private void LoadHtml()
00033         {
00034             // Grab the HTML from the text box and load it into the WebView.
00035             WebViewControl.NavigateToString(HtmlBox.Text);
00036         }
00037
00038         private async void InvokeScript()
00039         {
00040             // Invoke the javascript function called 'doSomething' that is loaded into the WebView.
00041             try
00042             {
00043                 string result = await WebViewControl.InvokeScriptAsync("doSomething", null);
00044                 rootPage.NotifyUser($"Script returned \"{result}\"", NotifyType.StatusMessage);
00045             }
00046             catch (Exception ex)
00047             {
00048                 string errorText = null;
00049                 switch (ex.HResult)
00050                 {
00051                     case unchecked((int)0x80020006):
00052                         errorText = "There is no function called doSomething";
00053                         break;
00054                     case unchecked((int)0x80020101):
00055                         errorText = "A JavaScript error or exception occured while executing the function doSomething";
00056                         break;
00057
00058                     case unchecked((int)0x800a138a):
00059                         errorText = "doSomething is not a function";
00060                         break;
00061                     default:
00062                         // Some other error occurred.
00063                         errorText = ex.Message;
00064                         break;
00065                 }
00066                 rootPage.NotifyUser(errorText, NotifyType.ErrorMessage);
00067             }
00068         }
00069     }
00070 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario13_RetryFilter.h Source File

  • HttpClient
  • cppwinrt

Scenario13_RetryFilter.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario13_RetryFilter.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario13_RetryFilter : Scenario13_RetryFilterT<Scenario13_RetryFilter>
00020     {
00021         Scenario13_RetryFilter();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025
00026         void RetryAfterSwitch_Toggled(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         fire_and_forget Start_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void Cancel_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029
00030     private:
00031         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00032         Windows::Web::Http::HttpClient httpClient{ nullptr };
00033         Windows::Foundation::IAsyncAction pendingAction{ nullptr };
00034
00035         void UpdateAddressField();
00036         Windows::Foundation::IAsyncAction CancelableRequestAsync(Windows::Foundation::Uri resourceUri);
00037     };
00038 }
00039
00040 namespace winrt::SDKTemplate::factory_implementation
00041 {
00042     struct Scenario13_RetryFilter : Scenario13_RetryFilterT<Scenario13_RetryFilter, implementation::Scenario13_RetryFilter>
00043     {
00044     };
00045 }
Generated on Fri Nov 15 2024 22:19:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PresenceSensor/cppwinrt/Scenario1_DataEvents.cpp Source File

  • PresenceSensor
  • cppwinrt

Scenario1_DataEvents.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SampleConfiguration.h"
00014 #include "Scenario1_DataEvents.h"
00015 #include "Scenario1_DataEvents.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace Windows::Devices::Enumeration;
00019 using namespace Windows::Devices::Sensors;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Globalization::DateTimeFormatting;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario1_DataEvents::Scenario1_DataEvents()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     void Scenario1_DataEvents::OnNavigatedFrom(NavigationEventArgs const&)
00033     {
00034         if (sensor != nullptr)
00035         {
00036             sensor.ReadingChanged(sensorReadingChangedToken);
00037             sensor = nullptr;
00038         }
00039     }
00040
00041     fire_and_forget Scenario1_DataEvents::ScenarioGetSensor_Click(IInspectable const&, RoutedEventArgs const&)
00042     {
00043         // Disable the button so the user can't click it again while we are already working.
00044         GetSensorButton().IsEnabled(false);
00045
00046         // Clear any previous message.
00047         rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00048
00049         // Try to get the default presence sensor.
00050         try
00051         {
00052             sensor = co_await HumanPresenceSensor::GetDefaultAsync();
00053         }
00054         catch (hresult_access_denied const&)
00055         {
00056             // The user denied this app presence sensor access.
00057             sensor = nullptr;
00058         }
00059         GetSensorButton().IsEnabled(true);
00060
00061         if (sensor != nullptr)
00062         {
00063             VisualStateManager::GoToState(*this, L"Ready", true);
00064
00065             // Begin listening for data reports.
00066             sensorReadingChangedToken = sensor.ReadingChanged({ get_weak(), &Scenario1_DataEvents::ReadingChanged });
00067         }
00068         else
00069         {
00070             rootPage.NotifyUser(L"No presence sensor found", NotifyType::ErrorMessage);
00071         }
00072
00073     }
00074
00075     fire_and_forget Scenario1_DataEvents::ReadingChanged(HumanPresenceSensor const&, HumanPresenceSensorReadingChangedEventArgs e)
00076     {
00077         auto lifetime = get_strong();
00078         co_await resume_foreground(Dispatcher());
00079
00080         HumanPresenceSensorReading reading = e.Reading();
00081         if (reading != nullptr)
00082         {
00083             if (sensor.IsEngagementSupported())
00084             {
00085                 EngagementStateTextBlock().Text(to_hstring(reading.Engagement()));
00086             }
00087             else
00088             {
00089                 EngagementStateTextBlock().Text(L"Not Supported");
00090             }
00091
00092             if (sensor.IsPresenceSupported())
00093             {
00094                 DetectionStateTextBlock().Text(to_hstring(reading.Presence()));
00095             }
00096             else
00097             {
00098                 DetectionStateTextBlock().Text(L"Not Supported");
00099
00100             }
00101
00102             // Show the detection distance, if available
00103             IReference<uint32_t> distance = reading.DistanceInMillimeters();
00104             DetectionDistanceTextBlock().Text(distance == nullptr ? L"Unavailable" : to_hstring(distance.Value()));
00105
00106             TimestampTextBlock().Text(DateTimeFormatter(L"shortdate longtime").Format(reading.Timestamp()));
00107
00108         }
00109     }
00110 }
Generated on Fri Nov 15 2024 22:20:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cs/Scenario2_History.xaml.cs Source File

  • ActivitySensor
  • cs

Scenario2_History.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Devices.Enumeration;
00014 using Windows.Devices.Sensors;
00015 using Windows.Globalization;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario2_History : Page
00022     {
00023         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00024         // as NotifyUser()
00025         MainPage rootPage = MainPage.Current;
00026
00027         // Common class ID for activity sensors
00028         Guid ActivitySensorClassId = new Guid("9D9E0118-1807-4F2E-96E4-2CE57142E196");
00029
00030         public Scenario2_History()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         /// <summary>
00036         /// This is the click handler for the 'Get Activity History' button.
00037         /// </summary>
00038         /// <param name="sender"></param>
00039         /// <param name="e"></param>
00040         async private void ScenarioGetActivityHistory(object sender, RoutedEventArgs e)
00041         {
00042             // Reset fields and status
00043             ScenarioOutput_Count.Text = "No data";
00044             ScenarioOutput_Activity1.Text = "No data";
00045             ScenarioOutput_Confidence1.Text = "No data";
00046             ScenarioOutput_Timestamp1.Text = "No data";
00047             ScenarioOutput_ActivityN.Text = "No data";
00048             ScenarioOutput_ConfidenceN.Text = "No data";
00049             ScenarioOutput_TimestampN.Text = "No data";
00050             rootPage.NotifyUser("", NotifyType.StatusMessage);
00051
00052             // Determine if we can access activity sensors
00053             var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(ActivitySensorClassId);
00054             if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
00055             {
00056                 // Determine if an activity sensor is present
00057                 // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
00058                 var activitySensor = await ActivitySensor.GetDefaultAsync();
00059                 if (activitySensor != null)
00060                 {
00061                     var calendar = new Calendar();
00062                     calendar.SetToNow();
00063                     calendar.AddDays(-1);
00064                     var yesterday = calendar.GetDateTime();
00065
00066                     // Get history from yesterday onwards
00067                     var history = await ActivitySensor.GetSystemHistoryAsync(yesterday);
00068
00069                     ScenarioOutput_Count.Text = history.Count.ToString();
00070                     if (history.Count > 0)
00071                     {
00072                         var reading1 = history[0];
00073                         ScenarioOutput_Activity1.Text = reading1.Activity.ToString();
00074                         ScenarioOutput_Confidence1.Text = reading1.Confidence.ToString();
00075                         ScenarioOutput_Timestamp1.Text = reading1.Timestamp.ToString("u");
00076
00077                         var readingN = history[history.Count - 1];
00078                         ScenarioOutput_ActivityN.Text = readingN.Activity.ToString();
00079                         ScenarioOutput_ConfidenceN.Text = readingN.Confidence.ToString();
00080                         ScenarioOutput_TimestampN.Text = readingN.Timestamp.ToString("u");
00081                     }
00082                 }
00083                 else
00084                 {
00085                     rootPage.NotifyUser("No activity sensors found", NotifyType.ErrorMessage);
00086                 }
00087             }
00088             else
00089             {
00090                 rootPage.NotifyUser("Access to activity sensors is denied", NotifyType.ErrorMessage);
00091             }
00092         }
00093     }
00094 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppServices/cppwinrt/RandomNumberService/RandomNumberGeneratorTask.cpp Source File

  • AppServices
  • cppwinrt
  • RandomNumberService

RandomNumberGeneratorTask.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
00002 #include "RandomNumberGeneratorTask.h"
00003 #include "RandomNumberGeneratorTask.g.cpp"
00004
00005 using namespace winrt;
00006 using namespace winrt::Windows::ApplicationModel::AppService;
00007 using namespace winrt::Windows::ApplicationModel::Background;
00008 using namespace winrt::Windows::Foundation::Collections;
00009
00010 namespace winrt::RandomNumberService::implementation
00011 {
00012     void RandomNumberGeneratorTask::Run(IBackgroundTaskInstance const& taskInstance)
00013     {
00014         //Take a service deferral so the service isn't terminated
00015         serviceDeferral = taskInstance.GetDeferral();
00016
00017         taskInstance.Canceled({ get_weak(), &RandomNumberGeneratorTask::OnTaskCanceled });
00018
00019         //Initialize the random number generator
00020         randomNumberGenerator.seed(std::random_device()());
00021
00022         auto details = taskInstance.TriggerDetails().as<AppServiceTriggerDetails>();
00023         connection = details.AppServiceConnection();
00024
00025         //Listen for incoming app service requests
00026         connection.RequestReceived({ get_weak(), &RandomNumberGeneratorTask::OnRequestReceived });
00027     }
00028
00029     void RandomNumberGeneratorTask::OnTaskCanceled(IBackgroundTaskInstance const&, BackgroundTaskCancellationReason const&)
00030     {
00031         if (connection != nullptr)
00032         {
00033             connection.Close();
00034             connection = nullptr;
00035         }
00036
00037         if (serviceDeferral != nullptr)
00038         {
00039             //Complete the service deferral
00040             serviceDeferral.Complete();
00041             serviceDeferral = nullptr;
00042         }
00043     }
00044
00045     fire_and_forget RandomNumberGeneratorTask::OnRequestReceived(AppServiceConnection const&, AppServiceRequestReceivedEventArgs const& args)
00046     {
00047         //Get a deferral so we can use an awaitable API to respond to the message
00048         auto messageDeferral = args.GetDeferral();
00049
00050         ValueSet input = args.Request().Message();
00051         int minValue = input.TryLookup(L"minvalue").try_as<int>().value_or(0);
00052         int maxValue = input.TryLookup(L"maxvalue").try_as<int>().value_or(0);
00053         if (maxValue < minValue)
00054         {
00055             maxValue = minValue;
00056         }
00057
00058         std::uniform_int_distribution<std::mt19937::result_type> distribution(minValue, maxValue); // distribution in range [minValue, maxValue]
00059         int randomValue = distribution(randomNumberGenerator);
00060
00061         //Create the response
00062         ValueSet result;
00063         result.Insert(L"result", box_value(randomValue));
00064
00065         //Send the response
00066         co_await args.Request().SendResponseAsync(result);
00067
00068         //Destruction of the message deferral lets the platform know we're done responding
00069     }
00070
00071 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/Scenario4PageRange.xaml.cpp Source File

  • Printing
  • cpp

Scenario4PageRange.xaml.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario4PageRange.xaml.h"
00005 #include "PageToPrint.xaml.h"
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace Platform;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::Graphics::Display;
00013 using namespace Windows::Graphics::Printing;
00014 using namespace Windows::Graphics::Printing::OptionDetails;
00015 using namespace Windows::UI::Xaml;
00016 using namespace Windows::UI::Xaml::Controls;
00017 using namespace Windows::UI::Xaml::Controls::Primitives;
00018 using namespace Windows::UI::Xaml::Data;
00019 using namespace Windows::UI::Xaml::Input;
00020 using namespace Windows::UI::Xaml::Interop;
00021 using namespace Windows::UI::Xaml::Media;
00022 using namespace Windows::UI::Xaml::Media::Imaging;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 PageRangePrintHelper::PageRangePrintHelper(Page^ scenarioPage)
00026     : PrintHelper(scenarioPage)
00027 {
00028     // Use moderate margins to allow the content to span multiple pages
00029     ApplicationContentMarginLeft = 0.1F;
00030     ApplicationContentMarginTop = 0.1F;
00031 }
00032
00033 /// <summary>
00034 /// This is the event handler for PrintManager.PrintTaskRequested.
00035 /// In order to ensure a good user experience, the system requires that the app handle the PrintTaskRequested event within the time specified by PrintTaskRequestedEventArgs->Request->Deadline.
00036 /// Therefore, we use this handler to only create the print task.
00037 /// The print settings customization can be done when the print document source is requested.
00038 /// </summary>
00039 /// <param name="sender">PrintManager</param>
00040 /// <param name="e">PrintTaskRequestedEventArgs</param>
00041 void PageRangePrintHelper::PrintTaskRequested(PrintManager^ sender, PrintTaskRequestedEventArgs^ e)
00042 {
00043     PrintTask^ printTask = e->Request->CreatePrintTask(L"C++ Printing SDK Sample", ref new PrintTaskSourceRequestedHandler([=](PrintTaskSourceRequestedArgs^ args)
00044     {
00045         args->SetSource(PrintDocumentSource);
00046     }));
00047
00048     // Choose the printer options to be shown.
00049     // The order in which the options are appended determines the order in which they appear in the UI
00050     PrintTaskOptionDetails^ printDetailedOptions = PrintTaskOptionDetails::GetFromPrintTaskOptions(printTask->Options);
00051     IVector<String^>^ displayedOptions = printDetailedOptions->DisplayedOptions;
00052     displayedOptions->Clear();
00053
00054     displayedOptions->Append(StandardPrintTaskOptions::Copies);
00055     displayedOptions->Append(StandardPrintTaskOptions::CustomPageRanges);
00056     displayedOptions->Append(StandardPrintTaskOptions::MediaSize);
00057     displayedOptions->Append(StandardPrintTaskOptions::ColorMode);
00058
00059     printTask->Options->PageRangeOptions->AllowAllPages = true;
00060     printTask->Options->PageRangeOptions->AllowCurrentPage = true;
00061     printTask->Options->PageRangeOptions->AllowCustomSetOfPages = true;
00062
00063     // Register the handler for the option change event
00064     printDetailedOptions->OptionChanged += ref new TypedEventHandler<PrintTaskOptionDetails^, PrintTaskOptionChangedEventArgs^>(this, &PageRangePrintHelper::printDetailedOptions_OptionChanged);
00065
00066     // Print Task event handler is invoked when the print job is completed.
00067     printTask->Completed += ref new TypedEventHandler<PrintTask^, PrintTaskCompletedEventArgs^>([=](PrintTask^ sender, PrintTaskCompletedEventArgs^ e)
00068     {
00069
00070         // Notify the user when the print operation fails.
00071         if (e->Completion == Windows::Graphics::Printing::PrintTaskCompletion::Failed)
00072         {
00073             auto callback = ref new Windows::UI::Core::DispatchedHandler([=]()
00074             {
00075                 MainPage::Current->NotifyUser(ref new String(L"Failed to print."), NotifyType::ErrorMessage);
00076             });
00077
00078             ScenarioPage->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00079         }
00080     });
00081 }
00082
00083 /// <summary>
00084 /// Option change event handler
00085 /// </summary>
00086 /// <param name="sender">PrintTaskOptionsDetails object</param>
00087 /// <param name="args">the event arguments containing the changed option id</param>
00088 void PageRangePrintHelper::printDetailedOptions_OptionChanged(PrintTaskOptionDetails^ sender, PrintTaskOptionChangedEventArgs^ args)
00089 {
00090     if (args->OptionId == nullptr)
00091     {
00092         return;
00093     }
00094
00095     String^ optionId = args->OptionId->ToString();
00096
00097     // Handle change in Page Range Option
00098     if (optionId == StandardPrintTaskOptions::CustomPageRanges)
00099     {
00100         PrintPageRangeOptionDetails^ pageRangeOption = (PrintPageRangeOptionDetails^)sender->Options->Lookup(optionId);
00101         ValidatePageRangeOption(pageRangeOption);
00102     }
00103 }
00104
00105 /// <summary>
00106 /// This is the event handler for PrintDocument.AddPages. It provides all pages to be printed, in the form of
00107 /// UIElements, to an instance of PrintDocument. PrintDocument subsequently converts the UIElements
00108 /// into a pages that the Windows print system can deal with.
00109 /// </summary>
00110 /// <param name="sender"></param>
00111 /// <param name="e">Add page event arguments containing a print task options reference</param>
00112 void PageRangePrintHelper::AddPrintPages(Object^ sender, AddPagesEventArgs^ e)
00113 {
00114     IVectorView<PrintPageRange^>^ customPageRanges = e->PrintTaskOptions->CustomPageRanges->GetView();
00115     PrintDocument^ printDocument = safe_cast<PrintDocument^>(sender);
00116
00117     // An empty CustomPageRanges means "All Pages"
00118     if (customPageRanges->Size == 0)
00119     {
00120         // Loop over all of the preview pages and add each one to be printed
00121         for (UIElement^ previewPage : PrintPreviewPages)
00122         {
00123             printDocument->AddPage(previewPage);
00124         }
00125     }
00126     else
00127     {
00128         // Print only the pages chosen by the user.
00129         //
00130         // The "Current page" option is a special case of "Custom set of pages".
00131         // In case the user selects the "Current page" option, the PrintDialog
00132         // will turn that into a CustomPageRanges containing the page that the user was looking at.
00133         // If the user typed in an indefinite range such as "6-", the LastPageNumber value
00134         // will be whatever this sample app last passed into the PrintDocument->SetPreviewPageCount API.
00135         for (PrintPageRange^ pageRange : customPageRanges)
00136         {
00137             // The user may type in a page number that is not present in the document.
00138             // In this case, we just ignore those pages, hence the checks
00139             // (pageRange.FirstPageNumber <= printPreviewPages.Count) and (i <= printPreviewPages.Count).
00140             //
00141             // If the user types the same page multiple times, it will be printed multiple times
00142             // (e.g 3-4;1;1 will print pages 3 and 4 followed by two copies of page 1)
00143             if (pageRange->FirstPageNumber <= PrintPreviewPageCount)
00144             {
00145                 for (int i = pageRange->FirstPageNumber; (i <= pageRange->LastPageNumber) && (i <= PrintPreviewPageCount); i++)
00146                 {
00147                     // Subtract 1 because page numbers are 1-based, but our list is 0-based.
00148                     printDocument->AddPage(PrintPreviewPages.at(i - 1));
00149                 }
00150             }
00151         }
00152     }
00153
00154     // Indicate that all of the print pages have been provided
00155     printDocument->AddPagesComplete();
00156 }
00157
00158 /// <summary>
00159 /// If the preview pages are regenerated, we need to make validate the Page Ranges again
00160 /// </summary>
00161 /// <param name="printTaskOptions"></param>
00162 void PageRangePrintHelper::OnPreviewPagesCreated(PrintTaskOptions^ printTaskOptions)
00163 {
00164     PrintTaskOptionDetails^ printDetailedOptions = PrintTaskOptionDetails::GetFromPrintTaskOptions(printTaskOptions);
00165     PrintPageRangeOptionDetails^ pageRangeOption = (PrintPageRangeOptionDetails^)printDetailedOptions->Options->Lookup(StandardPrintTaskOptions::CustomPageRanges);
00166     ValidatePageRangeOption(pageRangeOption);
00167 }
00168
00169 /// <summary>
00170 /// Deals with validating that the Page Ranges only contain pages that are present in the document.
00171 ///
00172 /// This is not necessary and some apps don't do this validation. Instead, they just ignore the pages
00173 /// that are not present in the document and simply don't print them.
00174 /// </summary>
00175 /// <param name="pageRangeOption">The PrintPageRangeOptionDetails option</param>
00176 void PageRangePrintHelper::ValidatePageRangeOption(PrintPageRangeOptionDetails^ pageRangeOption)
00177 {
00178     IVectorView<PrintPageRange^>^ pageRanges = ((IVector<PrintPageRange^>^)pageRangeOption->Value)->GetView();
00179
00180     pageRangeOption->WarningText = "";
00181     pageRangeOption->ErrorText = "";
00182
00183     int currentPreviewPageCount = PrintPreviewPageCount;
00184
00185     // An empty list means AllPages, in which case we don't need to check the ranges
00186     if (pageRanges->Size > 0)
00187     {
00188         // Verify that the page ranges contain at least one printable page
00189         bool containsAtLeastOnePrintablePage = false;
00190         for (PrintPageRange^ pageRange : pageRanges)
00191         {
00192             if ((pageRange->FirstPageNumber <= currentPreviewPageCount) || (pageRange->LastPageNumber <= currentPreviewPageCount))
00193             {
00194                 containsAtLeastOnePrintablePage = true;
00195                 break;
00196             }
00197         }
00198
00199         if (containsAtLeastOnePrintablePage)
00200         {
00201             // Warn the user in case one of the page ranges contains pages that will not printed. That way, s/he
00202             // can fix the page numbers in case they were mistyped.
00203             for (PrintPageRange^ pageRange : pageRanges)
00204             {
00205                 if ((pageRange->FirstPageNumber > currentPreviewPageCount) || (pageRange->LastPageNumber > currentPreviewPageCount))
00206                 {
00207                     pageRangeOption->WarningText = "One of the ranges contains pages that are not present in the document";
00208                     break;
00209                 }
00210             }
00211         }
00212         else
00213         {
00214             pageRangeOption->ErrorText = "Those pages are not present in the document";
00215         }
00216     }
00217 }
00218
00219 /// <summary>
00220 /// Helper function used to triger a preview refresh
00221 /// </summary>
00222 void PageRangePrintHelper::RefreshPreview()
00223 {
00224     auto callback = ref new Windows::UI::Core::DispatchedHandler([this]()
00225     {
00226         CurrentPrintDocument->InvalidatePreview();
00227     });
00228
00229     ScenarioPage->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00230 }
00231
00232 Scenario4PageRange::Scenario4PageRange()
00233 {
00234     InitializeComponent();
00235 }
00236
00237 void Scenario4PageRange::OnPrintButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00238 {
00239     printHelper->ShowPrintUIAsync();
00240 }
00241
00242 void Scenario4PageRange::OnNavigatedTo(NavigationEventArgs^ e)
00243 {
00244     if (PrintManager::IsSupported())
00245     {
00246         // Tell the user how to print
00247         MainPage::Current->NotifyUser("Print contract registered with customization, use the Print button to print.", NotifyType::StatusMessage);
00248     }
00249     else
00250     {
00251         // Remove the print button
00252         InvokePrintingButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00253
00254         // Inform user that Printing is not supported
00255         MainPage::Current->NotifyUser("Printing is not supported.", NotifyType::ErrorMessage);
00256
00257         // Printing-related event handlers will never be called if printing
00258         // is not supported, but it's okay to register for them anyway.
00259     }
00260
00261     // Initalize common helper class and register for printing
00262     printHelper = ref new PageRangePrintHelper(this);
00263     printHelper->RegisterForPrinting();
00264
00265     // Initialize print content for this scenario
00266     printHelper->PreparePrintContent(ref new PageToPrint());
00267 }
00268
00269 void Scenario4PageRange::OnNavigatedFrom(NavigationEventArgs^ e)
00270 {
00271     if (printHelper)
00272     {
00273         printHelper->UnregisterForPrinting();
00274     }
00275 }
Generated on Fri Nov 15 2024 22:21:03 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceResources Member List

This is the complete list of members for DeviceResources, including all inherited members.
_beginDrawStarted | DeviceResources | [private]
_contentSize | DeviceResources | [private]
_contentZoomFactor | DeviceResources | [private]
_d2dContext | DeviceResources | [private]
_d2dDevice | DeviceResources | [private]
_d2dFactory | DeviceResources | [private]
_d3dContext | DeviceResources | [private]
_d3dDevice | DeviceResources | [private]
_dpiAdjustmentRatio | DeviceResources | [private]
_logicalDPI | DeviceResources | [private]
_viewSize | DeviceResources | [private]
_vsis | DeviceResources | [private]
_vsisNative | DeviceResources | [private]
AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
AddHolographicCamera(winrt::Windows::Graphics::Holographic::HolographicCamera camera) | DeviceResources |
AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
AdjustUpdateRect(RECT const &updateRect) | DeviceResources |
BeginDraw(_In_opt_ const RECT *pUpdateRect=nullptr) | DeviceResources |
CheckStereoEnabledStatus() | DeviceResources | [private]
CheckStereoEnabledStatus() | DeviceResources | [private]
CheckStereoEnabledStatus() | DeviceResources | [private]
ClearTarget() | DeviceResources |
ComputeDisplayRotation() | DeviceResources | [private]
ComputeDisplayRotation() | DeviceResources | [private]
ComputeDisplayRotation() | DeviceResources | [private]
ComputeDisplayRotation() | DeviceResources | [private]
ComputeDisplayRotation() | DeviceResources | [private]
ComputeDisplayRotation() | DeviceResources | [private]
ComputeDisplayRotation() | DeviceResources | [private]
ComputeDisplayRotation() | DeviceResources | [private]
ComputeDisplayRotation() | DeviceResources | [private]
ComputeDisplayRotation() | DeviceResources | [private]
ComputeDisplayRotation() | DeviceResources | [private]
ComputeDisplayRotation() | DeviceResources | [private]
ComputeDisplayRotation() | DeviceResources | [private]
ConvertFromDIPToPixelUnit(float val, bool rounded=true) | DeviceResources | [inline, private]
ConvertFromPixelToDIPUnit(float val, bool rounded=true) | DeviceResources | [inline, private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceIndependentResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources |
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateDeviceResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
CreateWindowSizeDependentResources() | DeviceResources | [private]
DEFAULT_DPI | DeviceResources | [private]
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources(Windows::Foundation::Size sizeContent, Windows::Foundation::Size sizeViewport) | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources(_In_ bool forceWarpDevice) | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
DeviceResources() | DeviceResources |
EndDraw() | DeviceResources |
EnsureCameraResources(Windows::Graphics::Holographic::HolographicFrame^frame, Windows::Graphics::Holographic::HolographicFramePrediction^prediction) | DeviceResources |
EnsureCameraResources(Windows::Graphics::Holographic::HolographicFrame^frame, Windows::Graphics::Holographic::HolographicFramePrediction^prediction) | DeviceResources |
EnsureCameraResources(winrt::Windows::Graphics::Holographic::HolographicFrame frame, winrt::Windows::Graphics::Holographic::HolographicFramePrediction prediction) | DeviceResources |
EnsureCameraResources(Windows::Graphics::Holographic::HolographicFrame^frame, Windows::Graphics::Holographic::HolographicFramePrediction^prediction) | DeviceResources |
EnsureCameraResources(Windows::Graphics::Holographic::HolographicFrame^frame, Windows::Graphics::Holographic::HolographicFramePrediction^prediction) | DeviceResources |
EnsureCameraResources(Windows::Graphics::Holographic::HolographicFrame^frame, Windows::Graphics::Holographic::HolographicFramePrediction^prediction) | DeviceResources |
EnsureCameraResources(Windows::Graphics::Holographic::HolographicFrame^frame, Windows::Graphics::Holographic::HolographicFramePrediction^prediction) | DeviceResources |
EnsureCameraResources(Windows::Graphics::Holographic::HolographicFrame^frame, Windows::Graphics::Holographic::HolographicFramePrediction^prediction) | DeviceResources |
EnsureCameraResources(Windows::Graphics::Holographic::HolographicFrame^frame, Windows::Graphics::Holographic::HolographicFramePrediction^prediction) | DeviceResources |
EnsureCameraResources(Windows::Graphics::Holographic::HolographicFrame^frame, Windows::Graphics::Holographic::HolographicFramePrediction^prediction) | DeviceResources |
GetBackBufferRenderTargetView() const | DeviceResources | [inline]
GetBackBufferRenderTargetView() const | DeviceResources | [inline]
GetBackBufferRenderTargetView() const | DeviceResources | [inline]
GetBackBufferRenderTargetView() const | DeviceResources | [inline]
GetBackBufferRenderTargetView() const | DeviceResources | [inline]
GetBackBufferRenderTargetView() const | DeviceResources | [inline]
GetBackBufferRenderTargetView() const | DeviceResources | [inline]
GetBackBufferRenderTargetView() const | DeviceResources | [inline]
GetBackBufferRenderTargetView() const | DeviceResources | [inline]
GetBackBufferRenderTargetView() const | DeviceResources | [inline]
GetBackBufferRenderTargetView() const | DeviceResources | [inline]
GetBackBufferRenderTargetViewRight() const | DeviceResources | [inline]
GetBackBufferRenderTargetViewRight() const | DeviceResources | [inline]
GetBackBufferRenderTargetViewRight() const | DeviceResources | [inline]
GetContentSize() | DeviceResources | [inline]
GetContentZoomFactor() | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDevice() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DDeviceContext() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DFactory() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmap() const | DeviceResources | [inline]
GetD2DTargetBitmapRight() const | DeviceResources | [inline]
GetD2DTargetBitmapRight() const | DeviceResources | [inline]
GetD2DTargetBitmapRight() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDevice() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DDeviceContext() const | DeviceResources | [inline]
GetD3DInteropDevice() const | DeviceResources | [inline]
GetD3DInteropDevice() const | DeviceResources | [inline]
GetD3DInteropDevice() const | DeviceResources | [inline]
GetD3DInteropDevice() const | DeviceResources | [inline]
GetD3DInteropDevice() const | DeviceResources | [inline]
GetD3DInteropDevice() const | DeviceResources | [inline]
GetD3DInteropDevice() const | DeviceResources | [inline]
GetD3DInteropDevice() const | DeviceResources | [inline]
GetD3DInteropDevice() const | DeviceResources | [inline]
GetD3DInteropDevice() const | DeviceResources | [inline]
GetDepthStencilView() const | DeviceResources | [inline]
GetDepthStencilView() const | DeviceResources | [inline]
GetDepthStencilView() const | DeviceResources | [inline]
GetDepthStencilView() const | DeviceResources | [inline]
GetDepthStencilView() const | DeviceResources | [inline]
GetDepthStencilView() const | DeviceResources | [inline]
GetDepthStencilView() const | DeviceResources | [inline]
GetDepthStencilView() const | DeviceResources | [inline]
GetDepthStencilView() const | DeviceResources | [inline]
GetDepthStencilView() const | DeviceResources | [inline]
GetDepthStencilView() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceFeatureLevel() const | DeviceResources | [inline]
GetDeviceSupportsVprt() const | DeviceResources | [inline]
GetDeviceSupportsVprt() const | DeviceResources | [inline]
GetDeviceSupportsVprt() const | DeviceResources | [inline]
GetDeviceSupportsVprt() const | DeviceResources | [inline]
GetDeviceSupportsVprt() const | DeviceResources | [inline]
GetDeviceSupportsVprt() const | DeviceResources | [inline]
GetDeviceSupportsVprt() const | DeviceResources | [inline]
GetDeviceSupportsVprt() const | DeviceResources | [inline]
GetDeviceSupportsVprt() const | DeviceResources | [inline]
GetDeviceSupportsVprt() const | DeviceResources | [inline]
GetDpi() const | DeviceResources | [inline]
GetDpi() const | DeviceResources | [inline]
GetDpi() const | DeviceResources | [inline]
GetDpi() const | DeviceResources | [inline]
GetDPI() | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDWriteFactory() const | DeviceResources | [inline]
GetDXGIAdapter() const | DeviceResources | [inline]
GetDXGIAdapter() const | DeviceResources | [inline]
GetDXGIAdapter() const | DeviceResources | [inline]
GetDXGIAdapter() const | DeviceResources | [inline]
GetDXGIAdapter() const | DeviceResources | [inline]
GetDXGIAdapter() const | DeviceResources | [inline]
GetDXGIAdapter() const | DeviceResources | [inline]
GetDXGIAdapter() const | DeviceResources | [inline]
GetDXGIAdapter() const | DeviceResources | [inline]
GetDXGIAdapter() const | DeviceResources | [inline]
GetGeometryShader(const GeometryShaderIndex index) | DeviceResources | [inline]
GetImageSource() const | DeviceResources | [inline]
GetImageSourceNative() const | DeviceResources | [inline]
GetInputLayout(const VertexShaderIndex index) | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetLogicalSize() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform2D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOrientationTransform3D() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetOutputSize() const | DeviceResources | [inline]
GetPixelShader(const PixelShaderIndex index) | DeviceResources | [inline]
GetRenderTargetSize() const | DeviceResources | [inline]
GetRenderTargetSize() const | DeviceResources | [inline]
GetRenderTargetSize() const | DeviceResources | [inline]
GetScreenViewport() const | DeviceResources | [inline]
GetScreenViewport() const | DeviceResources | [inline]
GetScreenViewport() const | DeviceResources | [inline]
GetScreenViewport() const | DeviceResources | [inline]
GetScreenViewport() const | DeviceResources | [inline]
GetScreenViewport() const | DeviceResources | [inline]
GetScreenViewport() const | DeviceResources | [inline]
GetScreenViewport() const | DeviceResources | [inline]
GetScreenViewport() const | DeviceResources | [inline]
GetScreenViewport() const | DeviceResources | [inline]
GetScreenViewport() const | DeviceResources | [inline]
GetStereoState() const | DeviceResources | [inline]
GetStereoState() const | DeviceResources | [inline]
GetStereoState() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChain() const | DeviceResources | [inline]
GetSwapChainPanel() const | DeviceResources | [inline]
GetTexture(const TextureIndex index) | DeviceResources | [inline]
GetUpdateRects(_Outptr_ RECT **ppUpdateRects, _Out_ ULONG *pUpdateRectsCount) | DeviceResources |
GetVertexShader(const VertexShaderIndex index) | DeviceResources | [inline]
GetViewSize() | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWicImagingFactory() const | DeviceResources | [inline]
GetWindow() const | DeviceResources | [inline]
GetWindow() const | DeviceResources | [inline]
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
HandleDeviceLost() | DeviceResources |
InitializeUsingHolographicSpace() | DeviceResources | [private]
InitializeUsingHolographicSpace() | DeviceResources | [private]
InitializeUsingHolographicSpace() | DeviceResources | [private]
InitializeUsingHolographicSpace() | DeviceResources | [private]
InitializeUsingHolographicSpace() | DeviceResources | [private]
InitializeUsingHolographicSpace() | DeviceResources | [private]
InitializeUsingHolographicSpace() | DeviceResources | [private]
InitializeUsingHolographicSpace() | DeviceResources | [private]
InitializeUsingHolographicSpace() | DeviceResources | [private]
InitializeUsingHolographicSpace() | DeviceResources | [private]
InvalidateAndResizeVSIS() | DeviceResources | [private]
InvalidateContentRect() | DeviceResources |
InvalidateRect(RECT const &updateRect) | DeviceResources |
LoadShaders() | DeviceResources | [private]
m_cameraResources | DeviceResources | [private]
m_cameraResourcesLock | DeviceResources | [private]
m_compositionScaleX | DeviceResources | [private]
m_compositionScaleY | DeviceResources | [private]
m_currentOrientation | DeviceResources | [private]
m_currentOrientation | DeviceResources | [private]
m_d2dContext | DeviceResources | [private]
m_d2dContext | DeviceResources | [private]
m_d2dContext | DeviceResources | [private]
m_d2dContext | DeviceResources | [private]
m_d2dContext | DeviceResources | [private]
m_d2dDevice | DeviceResources | [private]
m_d2dDevice | DeviceResources | [private]
m_d2dDevice | DeviceResources | [private]
m_d2dDevice | DeviceResources | [private]
m_d2dDevice | DeviceResources | [private]
m_d2dFactory | DeviceResources | [private]
m_d2dFactory | DeviceResources | [private]
m_d2dFactory | DeviceResources | [private]
m_d2dFactory | DeviceResources | [private]
m_d2dFactory | DeviceResources | [private]
m_d2dTargetBitmap | DeviceResources | [private]
m_d2dTargetBitmap | DeviceResources | [private]
m_d2dTargetBitmapRight | DeviceResources | [private]
m_d2dTargetBitmapRight | DeviceResources | [private]
m_d3dContext | DeviceResources | [private]
m_d3dContext | DeviceResources | [private]
m_d3dContext | DeviceResources | [private]
m_d3dDepthStencilView | DeviceResources | [private]
m_d3dDepthStencilView | DeviceResources | [private]
m_d3dDevice | DeviceResources | [private]
m_d3dDevice | DeviceResources | [private]
m_d3dDevice | DeviceResources | [private]
m_d3dDevice | DeviceResources | [private]
m_d3dFeatureLevel | DeviceResources | [private]
m_d3dInteropDevice | DeviceResources | [private]
m_d3dInteropDevice | DeviceResources | [private]
m_d3dRenderTargetSize | DeviceResources | [private]
m_d3dRenderTargetSize | DeviceResources | [private]
m_d3dRenderTargetView | DeviceResources | [private]
m_d3dRenderTargetView | DeviceResources | [private]
m_d3dRenderTargetView | DeviceResources | [private]
m_d3dRenderTargetViewRight | DeviceResources | [private]
m_d3dRenderTargetViewRight | DeviceResources | [private]
m_deviceNotify | DeviceResources | [private]
m_dpi | DeviceResources | [private]
m_dwriteFactory | DeviceResources | [private]
m_dwriteFactory | DeviceResources | [private]
m_dwriteFactory | DeviceResources | [private]
m_dwriteFactory | DeviceResources | [private]
m_dxgiAdapter | DeviceResources | [private]
m_dxgiFactory | DeviceResources | [private]
m_effectiveDpi | DeviceResources | [private]
m_forceWarpDevice | DeviceResources | [private]
m_frameLatencyWaitableObject | DeviceResources | [private]
m_geometryShaders | DeviceResources | [private]
m_holographicSpace | DeviceResources | [private]
m_holographicSpace | DeviceResources | [private]
m_inputLayouts | DeviceResources | [private]
m_logicalSize | DeviceResources |
m_logicalSize | DeviceResources | [private]
m_nativeOrientation | DeviceResources | [private]
m_nativeOrientation | DeviceResources | [private]
m_orientationTransform2D | DeviceResources | [private]
m_orientationTransform3D | DeviceResources | [private]
m_outputSize | DeviceResources | [private]
m_outputSize | DeviceResources | [private]
m_pixelShaders | DeviceResources | [private]
m_screenViewport | DeviceResources | [private]
m_stereoEnabled | DeviceResources | [private]
m_supportsVprt | DeviceResources | [private]
m_swapChain | DeviceResources | [private]
m_swapChain | DeviceResources | [private]
m_swapChain | DeviceResources | [private]
m_swapChainPanel | DeviceResources | [private]
m_textures | DeviceResources | [private]
m_vertexShaders | DeviceResources | [private]
m_wicFactory | DeviceResources | [private]
m_wicFactory | DeviceResources | [private]
m_window | DeviceResources | [private]
Present(Windows::Graphics::Holographic::HolographicFrame^frame) | DeviceResources |
Present(Windows::Graphics::Holographic::HolographicFrame^frame) | DeviceResources |
Present(winrt::Windows::Graphics::Holographic::HolographicFrame frame) | DeviceResources |
Present() | DeviceResources |
Present() | DeviceResources |
Present() | DeviceResources |
Present() | DeviceResources |
Present() | DeviceResources |
Present() | DeviceResources |
Present() | DeviceResources |
Present() | DeviceResources |
Present() | DeviceResources |
Present(Windows::Graphics::Holographic::HolographicFrame^frame) | DeviceResources |
Present(Windows::Graphics::Holographic::HolographicFrame^frame) | DeviceResources |
Present(Windows::Graphics::Holographic::HolographicFrame^frame) | DeviceResources |
Present(Windows::Graphics::Holographic::HolographicFrame^frame) | DeviceResources |
Present(Windows::Graphics::Holographic::HolographicFrame^frame) | DeviceResources |
Present(Windows::Graphics::Holographic::HolographicFrame^frame) | DeviceResources |
Present() | DeviceResources |
Present() | DeviceResources |
Present() | DeviceResources |
Present() | DeviceResources |
Present(Windows::Graphics::Holographic::HolographicFrame^frame) | DeviceResources |
RefreshScaleFactor() | DeviceResources | [private]
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RegisterDeviceNotify(IDeviceNotify *deviceNotify) | DeviceResources |
RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
RemoveHolographicCamera(winrt::Windows::Graphics::Holographic::HolographicCamera camera) | DeviceResources |
RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^camera) | DeviceResources |
SetCompositionScale(float compositionScaleX, float compositionScaleY) | DeviceResources |
SetCompositionScale(float compositionScaleX, float compositionScaleY) | DeviceResources |
SetCompositionScale(float compositionScaleX, float compositionScaleY) | DeviceResources |
SetCompositionScale(float compositionScaleX, float compositionScaleY) | DeviceResources |
SetCompositionScale(float compositionScaleX, float compositionScaleY) | DeviceResources |
SetContentSize(Windows::Foundation::Size size) | DeviceResources |
SetContentZoomFactor(float contentZoomFactor) | DeviceResources |
SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetCurrentOrientation(winrt::Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDpi(float dpi) | DeviceResources |
SetDPI(float dpi) | DeviceResources |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^space) | DeviceResources |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^space) | DeviceResources |
SetHolographicSpace(winrt::Windows::Graphics::Holographic::HolographicSpace space) | DeviceResources |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^space) | DeviceResources |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^space) | DeviceResources |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^space) | DeviceResources |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^space) | DeviceResources |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^space) | DeviceResources |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^space) | DeviceResources |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^space) | DeviceResources |
SetLogicalSize(Windows::Foundation::Size logicalSize) | DeviceResources |
SetLogicalSize(Windows::Foundation::Size logicalSize) | DeviceResources |
SetLogicalSize(Windows::Foundation::Size logicalSize) | DeviceResources |
SetLogicalSize(Windows::Foundation::Size logicalSize) | DeviceResources |
SetLogicalSize(Windows::Foundation::Size logicalSize) | DeviceResources |
SetLogicalSize(Windows::Foundation::Size logicalSize) | DeviceResources |
SetLogicalSize(Windows::Foundation::Size logicalSize) | DeviceResources |
SetLogicalSize(Windows::Foundation::Size logicalSize) | DeviceResources |
SetLogicalSize(Windows::Foundation::Size logicalSize) | DeviceResources |
SetLogicalSize(Windows::Foundation::Size logicalSize) | DeviceResources |
SetLogicalSize(Windows::Foundation::Size logicalSize) | DeviceResources |
SetLogicalSize(winrt::Windows::Foundation::Size logicalSize) | DeviceResources |
SetLogicalSize(Windows::Foundation::Size logicalSize) | DeviceResources |
SetSwapChainPanel(Windows::UI::Xaml::Controls::SwapChainPanel^panel) | DeviceResources |
SetSwapChainPanel(Windows::UI::Xaml::Controls::SwapChainPanel^panel) | DeviceResources |
SetSwapChainPanel(Windows::UI::Xaml::Controls::SwapChainPanel^panel) | DeviceResources |
SetSwapChainPanel(Windows::UI::Xaml::Controls::SwapChainPanel^panel) | DeviceResources |
SetSwapChainPanel(Windows::UI::Xaml::Controls::SwapChainPanel^panel) | DeviceResources |
SetViewSize(Windows::Foundation::Size size) | DeviceResources |
SetWindow(Windows::UI::Core::CoreWindow^window) | DeviceResources |
SetWindow(Windows::UI::Core::CoreWindow^window) | DeviceResources |
SetWindow(Windows::UI::Core::CoreWindow^window) | DeviceResources |
SetWindow(Windows::UI::Core::CoreWindow^window) | DeviceResources |
SetWindow(Windows::UI::Core::CoreWindow^window) | DeviceResources |
SetWindow(Windows::UI::Core::CoreWindow^window) | DeviceResources |
SetWindow(Windows::UI::Core::CoreWindow^window) | DeviceResources |
SetWindow(winrt::Windows::UI::Core::CoreWindow const &window) | DeviceResources |
ShouldApplyContentZoomFactor(float contentZoomFactor) | DeviceResources | [inline, private]
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
Trim() | DeviceResources |
UpdateRenderTargetSize() | DeviceResources | [private]
UpdateStereoState() | DeviceResources |
UpdateStereoState() | DeviceResources |
UpdateStereoState() | DeviceResources |
UseHolographicCameraResources(const LCallback &callback) | DeviceResources |
UseHolographicCameraResources(const LCallback &callback) | DeviceResources |
UseHolographicCameraResources(LCallback const &callback) | DeviceResources |
UseHolographicCameraResources(const LCallback &callback) | DeviceResources |
UseHolographicCameraResources(const LCallback &callback) | DeviceResources |
UseHolographicCameraResources(const LCallback &callback) | DeviceResources |
UseHolographicCameraResources(const LCallback &callback) | DeviceResources |
UseHolographicCameraResources(const LCallback &callback) | DeviceResources |
UseHolographicCameraResources(const LCallback &callback) | DeviceResources |
UseHolographicCameraResources(const LCallback &callback) | DeviceResources |
ValidateDevice() | DeviceResources |
ValidateDevice() | DeviceResources |
ValidateDevice() | DeviceResources |
ValidateDevice() | DeviceResources |
ValidateDevice() | DeviceResources |
ValidateDevice() | DeviceResources |
ValidateDevice() | DeviceResources |
ValidateDevice() | DeviceResources |
ValidateDevice() | DeviceResources |
ValidateDevice() | DeviceResources |
ValidateDevice() | DeviceResources |
ValidateDevice() | DeviceResources |
ValidateDevice() | DeviceResources |
WaitOnSwapChain() | DeviceResources |
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/LiveTiles/FindAllAsync/Visualizer/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • LiveTiles
  • FindAllAsync
  • Visualizer

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI;
00003 using Windows.UI.StartScreen;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00008
00009 namespace Notifications.ScenarioPages.LiveTiles.FindAllAsync.Visualizer
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     public sealed partial class ScenarioElement : UserControl
00015     {
00016         public ScenarioElement()
00017         {
00018             this.InitializeComponent();
00019
00020             ButtonUpdate_Click(this, null);
00021         }
00022
00023         private async void ButtonUpdate_Click(object sender, RoutedEventArgs e)
00024         {
00025             ListViewTiles.ItemsSource = await SecondaryTile.FindAllAsync();
00026         }
00027
00028         private void blah()
00029         {
00030             SecondaryTile tile = new SecondaryTile();
00031             tile.DisplayName = "";
00032             tile.VisualElements.BackgroundColor = Colors.Red;
00033         }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/ActivationTypes/Protocol/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • ActivationTypes
  • Protocol

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Notifications;
00003 using Windows.UI.Popups;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00008
00009 namespace Notifications.ScenarioPages.Toasts.ActivationTypes.Protocol
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     public sealed partial class ScenarioElement : UserControl
00015     {
00016         public ScenarioElement()
00017         {
00018             this.InitializeComponent();
00019         }
00020
00021         private void UserControl_Loaded(object sender, RoutedEventArgs e)
00022         {
00023             Initialize();
00024         }
00025
00026
00027         private void Initialize()
00028         {
00029             // Clear all existing notifications
00030             ToastNotificationManager.History.Clear();
00031
00032             // Pop notifications
00033             popToastControl.Payload =
00034                 $@"
00035                 <toast activationType='protocol' launch='bingmaps:?q=1+Microsoft+Way,+98052'>
00036                     <visual>
00037                         <binding template='ToastGeneric'>
00038                             <text>Click to launch Bing Maps</text>
00039                             <text>Searches for ""1 Microsoft Way, 98052""</text>
00040                         </binding>
00041                     </visual>
00042                 </toast>";
00043         }
00044
00045         private async void Error(string message)
00046         {
00047             await new MessageDialog(message, "ERROR").ShowAsync();
00048         }
00049     }
00050 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

StreamResolution Member List

This is the complete list of members for StreamResolution, including all inherited members.
_properties | StreamResolution | [private]
AspectRatio | StreamResolution |
EncodingProperties | StreamResolution |
FrameRate | StreamResolution |
GetFriendlyName(bool showFrameRate=true) | StreamResolution | [inline]
Height | StreamResolution |
StreamResolution(IMediaEncodingProperties properties) | StreamResolution | [inline]
Width | StreamResolution |
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_CheckUserConsentGroup Member List

This is the complete list of members for Scenario3_CheckUserConsentGroup, including all inherited members.
EvaluateConsentResult(Windows::System::UserAgeConsentResult consentResult) | Scenario3_CheckUserConsentGroup | [private, static]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario3_CheckUserConsentGroup |
Scenario3_CheckUserConsentGroup() | Scenario3_CheckUserConsentGroup |
ShowConsentGroups(IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_CheckUserConsentGroup |
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/pch.h Source File

  • Geolocation
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include <winrt/BackgroundTask.h>
00005 #include <winrt/Windows.ApplicationModel.Activation.h>
00006 #include <winrt/Windows.ApplicationModel.Background.h>
00007 #include <winrt/Windows.Data.Json.h>
00008 #include <winrt/Windows.Devices.Geolocation.h>
00009 #include <winrt/Windows.Devices.Geolocation.Geofencing.h>
00010 #include <winrt/Windows.Foundation.h>
00011 #include <winrt/Windows.Foundation.Collections.h>
00012 #include <winrt/Windows.Globalization.DateTimeFormatting.h>
00013 #include <winrt/Windows.Storage.h>
00014 #include <winrt/Windows.System.h>
00015 #include <winrt/Windows.UI.Core.h>
00016 #include <winrt/Windows.UI.Xaml.h>
00017 #include <winrt/Windows.UI.Xaml.Automation.Peers.h>
00018 #include <winrt/Windows.UI.Xaml.Controls.h>
00019 #include <winrt/Windows.UI.Xaml.Controls.Primitives.h>
00020 #include <winrt/Windows.UI.Xaml.Documents.h>
00021 #include <winrt/Windows.UI.Xaml.Interop.h>
00022 #include <winrt/Windows.UI.Xaml.Markup.h>
00023 #include <winrt/Windows.UI.Xaml.Media.h>
00024 #include <winrt/Windows.UI.Xaml.Navigation.h>
00025 #include <sstream>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cs/Helpers.cs Source File

  • HttpClient
  • cs

Helpers.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Text;
00016 using System.Threading;
00017 using System.Threading.Tasks;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.Web;
00020 using Windows.Web.Http;
00021 using Windows.Web.Http.Filters;
00022 using Windows.Web.Http.Headers;
00023
00024 namespace SDKTemplate
00025 {
00026     internal static class Helpers
00027     {
00028         internal static async Task DisplayTextResultAsync(
00029             HttpResponseMessage response,
00030             TextBox output,
00031             CancellationToken token)
00032         {
00033             string responseBodyAsText;
00034             output.Text += SerializeHeaders(response);
00035             responseBodyAsText = await response.Content.ReadAsStringAsync().AsTask(token);
00036
00037             token.ThrowIfCancellationRequested();
00038
00039             // Insert new lines.
00040             responseBodyAsText = responseBodyAsText.Replace("<br>", Environment.NewLine);
00041
00042             output.Text += responseBodyAsText;
00043         }
00044
00045         internal static void DisplayWebError(MainPage rootPage, Exception exception)
00046         {
00047             WebErrorStatus webErrorStatus = WebError.GetStatus(exception.HResult);
00048             if (webErrorStatus == WebErrorStatus.Unknown)
00049             {
00050                 rootPage.NotifyUser("Unknown Error: " + exception.Message, NotifyType.ErrorMessage);
00051             }
00052             else
00053             {
00054                 rootPage.NotifyUser("Web Error: " + webErrorStatus, NotifyType.ErrorMessage);
00055             }
00056
00057         }
00058
00059         internal static string SerializeHeaders(HttpResponseMessage response)
00060         {
00061             StringBuilder output = new StringBuilder();
00062
00063             // We cast the StatusCode to an int so we display the numeric value (e.g., "200") rather than the
00064             // name of the enum (e.g., "OK") which would often be redundant with the ReasonPhrase.
00065             output.Append(((int)response.StatusCode) + " " + response.ReasonPhrase + "\r\n");
00066
00067             SerializeHeaderCollection(response.Headers, output);
00068             SerializeHeaderCollection(response.Content.Headers, output);
00069             output.Append("\r\n");
00070             return output.ToString();
00071         }
00072
00073         internal static void SerializeHeaderCollection(
00074             IEnumerable<KeyValuePair<string, string>> headers,
00075             StringBuilder output)
00076         {
00077             foreach (var header in headers)
00078             {
00079                 output.Append(header.Key + ": " + header.Value + "\r\n");
00080             }
00081         }
00082
00083         internal static HttpClient CreateHttpClientWithPlugIn()
00084         {
00085
00086             // HttpClient functionality can be extended by plugging multiple filters together and providing
00087             // HttpClient with the configured filter pipeline.
00088             IHttpFilter filter = new HttpBaseProtocolFilter();
00089             filter = new PlugInFilter(filter); // Adds a custom header to every request and response message.
00090             HttpClient httpClient = new HttpClient(filter);
00091
00092             // The following line sets a "User-Agent" request header as a default header on the HttpClient instance.
00093             // Default headers will be sent with every request sent from this HttpClient instance.
00094             httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue("Sample", "v8"));
00095
00096             return httpClient;
00097         }
00098
00099         internal static void ScenarioStarted(Button startButton, Button cancelButton, TextBox outputField)
00100         {
00101             startButton.IsEnabled = false;
00102             cancelButton.IsEnabled = true;
00103             if (outputField != null)
00104             {
00105                 outputField.Text = String.Empty;
00106             }
00107         }
00108
00109         internal static void ScenarioCompleted(Button startButton, Button cancelButton)
00110         {
00111             startButton.IsEnabled = true;
00112             cancelButton.IsEnabled = false;
00113         }
00114
00115         internal static void ReplaceQueryString(TextBox addressField, string newQueryString)
00116         {
00117             string resourceAddress = addressField.Text;
00118
00119             // Remove previous query string.
00120             int questionMarkIndex = resourceAddress.IndexOf("?", StringComparison.Ordinal);
00121             if (questionMarkIndex != -1)
00122             {
00123                 resourceAddress = resourceAddress.Substring(0, questionMarkIndex);
00124             }
00125
00126             addressField.Text = resourceAddress + newQueryString;
00127         }
00128
00129         internal static Uri TryParseHttpUri(string uriString)
00130         {
00131             // Note that this app has both "Internet (Client)" and "Home and Work Networking" capabilities set,
00132             // since the user may provide URIs for servers located on the internet or intranet. If apps only
00133             // communicate with servers on the internet, only the "Internet (Client)" capability should be set.
00134             // Similarly if an app is only intended to communicate on the intranet, only the "Home and Work
00135             // Networking" capability should be set.
00136             Uri uri;
00137             if (!Uri.TryCreate(uriString.Trim(), UriKind.Absolute, out uri))
00138             {
00139                 return null;
00140             }
00141
00142             if (uri.Scheme != "http" && uri.Scheme != "https")
00143             {
00144                 return null;
00145             }
00146
00147             return uri;
00148         }
00149     }
00150 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/BackgroundTasks/Helpers/BackgroundTaskStorage.cs Source File

  • Notifications
  • cs
  • BackgroundTasks
  • Helpers

BackgroundTaskStorage.cs

Go to the documentation of this file.
00001 ﻿using System.Collections.Generic;
00002 using Windows.Foundation.Collections;
00003 using Windows.Storage;
00004
00005 namespace BackgroundTasks.Helpers
00006 {
00007     public static class BackgroundTaskStorage
00008     {
00009         private static IPropertySet Values = ApplicationData.Current.LocalSettings.CreateContainer("BackgroundTaskStorage", ApplicationDataCreateDisposition.Always).Values;
00010
00011         public static IPropertySet GetValues()
00012         {
00013             return Values;
00014         }
00015
00016         public static void PutError(string message)
00017         {
00018             Values["error"] = message;
00019         }
00020
00021         public static string GetError()
00022         {
00023             if (Values.ContainsKey("error"))
00024                 return Values["error"] as string;
00025
00026             return null;
00027         }
00028
00029         public static void PutAnswer(object answer)
00030         {
00031             // Clear the message since it was successful
00032             PutError(null);
00033
00034             Values["answer"] = answer;
00035         }
00036
00037         public static object GetAnswer()
00038         {
00039             object obj;
00040
00041             Values.TryGetValue("answer", out obj);
00042
00043             return obj;
00044         }
00045
00046         public static IDictionary<string, object> ConvertValueSetToDictionary(ValueSet valueSet)
00047         {
00048             Dictionary<string, object> converted = new Dictionary<string, object>();
00049
00050             foreach (var value in valueSet)
00051             {
00052                 converted[value.Key] = value.Value;
00053             }
00054
00055             return converted;
00056         }
00057
00058         public static ApplicationDataCompositeValue ConvertValueSetToApplicationDataCompositeValue(ValueSet valueSet)
00059         {
00060             ApplicationDataCompositeValue converted = new ApplicationDataCompositeValue();
00061
00062             foreach (var value in valueSet)
00063             {
00064                 converted[value.Key] = value.Value;
00065             }
00066
00067             return converted;
00068         }
00069     }
00070 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactCards/cpp/Scenario1_Mini.xaml.cpp Source File

  • ContactCards
  • cpp

Scenario1_Mini.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_Mini.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::ApplicationModel::Contacts;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Popups;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Input;
00024
00025 Scenario1_Mini::Scenario1_Mini()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 void Scenario1_Mini::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00031 {
00032     if (!ContactManager::IsShowContactCardSupported())
00033     {
00034         NotSupportedWarning->Visibility = Windows::UI::Xaml::Visibility::Visible;
00035     }
00036 }
00037
00038 void Scenario1_Mini::ShowContactCard_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00039 {
00040     Contact^ contact = rootPage->CreateContactFromUserInput(EmailAddress, PhoneNumber);
00041     if (contact != nullptr)
00042     {
00043         // Show the contact card next to the button.
00044         Rect rect = MainPage::GetElementRect(safe_cast<FrameworkElement^>(sender));
00045
00046         // Show with default placement.
00047         ContactManager::ShowContactCard(contact, rect);
00048     }
00049 }
00050
00051 void Scenario1_Mini::ShowContactCardWithPlacement_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00052 {
00053     Contact^ contact = rootPage->CreateContactFromUserInput(EmailAddress, PhoneNumber);
00054     if (contact != nullptr)
00055     {
00056         // Show the contact card next to the button.
00057         Rect rect = MainPage::GetElementRect(safe_cast<FrameworkElement^>(sender));
00058
00059         // Show with preferred placement to the right.
00060         ContactManager::ShowContactCard(contact, rect, Placement::Right);
00061     }
00062 }
00063
00064 void Scenario1_Mini::ShowContactCardWithOptions_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00065 {
00066     Contact^ contact = rootPage->CreateContactFromUserInput(EmailAddress, PhoneNumber);
00067     if (contact != nullptr)
00068     {
00069         // Show the contact card next to the button.
00070         Rect rect = MainPage::GetElementRect(safe_cast<FrameworkElement^>(sender));
00071
00072         // Ask for the initial tab to be Phone.
00073         ContactCardOptions^ options = ref new ContactCardOptions();
00074         options->InitialTabKind = ContactCardTabKind::Phone;
00075
00076         // Show with default placement.
00077         ContactManager::ShowContactCard(contact, rect, Placement::Default);
00078     }
00079 }
Generated on Fri Nov 15 2024 22:18:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

InstructionControl Member List

This is the complete list of members for InstructionControl, including all inherited members.
Instruction | InstructionControl |
InstructionControl() | InstructionControl | [inline]
InstructionProperty | InstructionControl | [static]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_StringTemplate Member List

This is the complete list of members for Scenario2_StringTemplate, including all inherited members.
Display_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_StringTemplate
Scenario2_StringTemplate() | Scenario2_StringTemplate
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameMain.cpp Source File

  • Simple3DGameDX
  • cppwinrt

GameMain.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "GameMain.h"
00014
00015 using namespace GameControl;
00016 using namespace Simple3DGameDX;
00017 using namespace DirectX;
00018 using namespace winrt::Windows::UI::Core;
00019
00020 GameMain::GameMain(std::shared_ptr<DX::DeviceResources> const& deviceResources) :
00021     m_deviceResources(deviceResources),
00022     m_windowClosed(false),
00023     m_haveFocus(false),
00024     m_gameInfoOverlayCommand(GameInfoOverlayCommand::None),
00025     m_visible(true),
00026     m_loadingCount(0),
00027     m_updateState(UpdateEngineState::WaitingForResources)
00028 {
00029     m_deviceResources->RegisterDeviceNotify(this);
00030
00031     m_renderer = std::make_shared<GameRenderer>(m_deviceResources);
00032     m_game = std::make_shared<Simple3DGame>();
00033
00034     m_uiControl = m_renderer->GameUIControl();
00035
00036     m_controller = std::make_shared<MoveLookController>(CoreWindow::GetForCurrentThread());
00037
00038     auto bounds = m_deviceResources->GetLogicalSize();
00039
00040     m_controller->SetMoveRect(
00041         XMFLOAT2(0.0f, bounds.Height - GameUIConstants::TouchRectangleSize),
00042         XMFLOAT2(GameUIConstants::TouchRectangleSize, bounds.Height)
00043         );
00044     m_controller->SetFireRect(
00045         XMFLOAT2(bounds.Width - GameUIConstants::TouchRectangleSize, bounds.Height - GameUIConstants::TouchRectangleSize),
00046         XMFLOAT2(bounds.Width, bounds.Height)
00047         );
00048
00049     SetGameInfoOverlay(GameInfoOverlayState::Loading);
00050     m_uiControl->SetAction(GameInfoOverlayCommand::None);
00051     m_uiControl->ShowGameInfoOverlay();
00052
00053     // Asynchronously initialize the game class and load the renderer device resources.
00054     // By doing all this asynchronously, the game gets to its main loop more quickly
00055     // and in parallel all the necessary resources are loaded on other threads.
00056     ConstructInBackground();
00057 }
00058
00059 winrt::fire_and_forget GameMain::ConstructInBackground()
00060 {
00061     auto lifetime = get_strong();
00062
00063     m_game->Initialize(m_controller, m_renderer);
00064
00065     co_await m_renderer->CreateGameDeviceResourcesAsync(m_game);
00066
00067     // The finalize code needs to run in the same thread context
00068     // as the m_renderer object was created because the D3D device context
00069     // can ONLY be accessed on a single thread.
00070     // co_await of an IAsyncAction resumes in the same thread context.
00071     m_renderer->FinalizeCreateGameDeviceResources();
00072
00073     InitializeGameState();
00074
00075     if (m_updateState == UpdateEngineState::WaitingForResources)
00076     {
00077         // In the middle of a game so spin up the async task to load the level.
00078         co_await m_game->LoadLevelAsync();
00079
00080         // The m_game object may need to deal with D3D device context work so
00081         // again the finalize code needs to run in the same thread
00082         // context as the m_renderer object was created because the D3D
00083         // device context can ONLY be accessed on a single thread.
00084         m_game->FinalizeLoadLevel();
00085         m_game->SetCurrentLevelToSavedState();
00086         m_updateState = UpdateEngineState::ResourcesLoaded;
00087     }
00088     else
00089     {
00090         // The game is not in the middle of a level so there aren't any level
00091         // resources to load.
00092     }
00093
00094     // Since Game loading is an async task, the app visual state
00095     // may be too small or not have focus. Put the state machine
00096     // into the correct state to reflect these cases.
00097
00098     if (m_deviceResources->GetLogicalSize().Width < GameUIConstants::MinPlayableWidth)
00099     {
00100         m_updateStateNext = m_updateState;
00101         m_updateState = UpdateEngineState::TooSmall;
00102         m_controller->Active(false);
00103         m_uiControl->HideGameInfoOverlay();
00104         m_uiControl->ShowTooSmall();
00105         m_renderNeeded = true;
00106     }
00107     else if (!m_haveFocus)
00108     {
00109         m_updateStateNext = m_updateState;
00110         m_updateState = UpdateEngineState::Deactivated;
00111         m_controller->Active(false);
00112         m_uiControl->SetAction(GameInfoOverlayCommand::None);
00113         m_renderNeeded = true;
00114     }
00115 }
00116
00117 GameMain::~GameMain()
00118 {
00119     // Deregister device notification
00120     m_deviceResources->RegisterDeviceNotify(nullptr);
00121 }
00122
00123 void GameMain::Run()
00124 {
00125     while (!m_windowClosed)
00126     {
00127         if (m_visible)
00128         {
00129             switch (m_updateState)
00130             {
00131             case UpdateEngineState::Deactivated:
00132             case UpdateEngineState::TooSmall:
00133                 if (m_updateStateNext == UpdateEngineState::WaitingForResources)
00134                 {
00135                     WaitingForResourceLoading();
00136                     m_renderNeeded = true;
00137                 }
00138                 else if (m_updateStateNext == UpdateEngineState::ResourcesLoaded)
00139                 {
00140                     // In the device lost case, we transition to the final waiting state
00141                     // and make sure the display is updated.
00142                     switch (m_pressResult)
00143                     {
00144                     case PressResultState::LoadGame:
00145                         SetGameInfoOverlay(GameInfoOverlayState::GameStats);
00146                         break;
00147
00148                     case PressResultState::PlayLevel:
00149                         SetGameInfoOverlay(GameInfoOverlayState::LevelStart);
00150                         break;
00151
00152                     case PressResultState::ContinueLevel:
00153                         SetGameInfoOverlay(GameInfoOverlayState::Pause);
00154                         break;
00155                     }
00156                     m_updateStateNext = UpdateEngineState::WaitingForPress;
00157                     m_uiControl->ShowGameInfoOverlay();
00158                     m_renderNeeded = true;
00159                 }
00160
00161                 if (!m_renderNeeded)
00162                 {
00163                     // The App is not currently the active window and not in a transient state so just wait for events.
00164                     CoreWindow::GetForCurrentThread().Dispatcher().ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00165                     break;
00166                 }
00167                 // otherwise fall through and do normal processing to get the rendering handled.
00168             default:
00169                 CoreWindow::GetForCurrentThread().Dispatcher().ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00170                 Update();
00171                 m_renderer->Render();
00172                 m_deviceResources->Present();
00173                 m_renderNeeded = false;
00174             }
00175         }
00176         else
00177         {
00178             CoreWindow::GetForCurrentThread().Dispatcher().ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00179         }
00180     }
00181     m_game->OnSuspending();  // Exiting due to window close, so save state.
00182 }
00183
00184 void GameMain::InitializeGameState()
00185 {
00186     // Set up the initial state machine for handling Game playing state.
00187     if (m_game->GameActive() && m_game->LevelActive())
00188     {
00189         // The last time the game terminated it was in the middle
00190         // of a level.
00191         // We are waiting for the user to continue the game.
00192         m_updateState = UpdateEngineState::WaitingForResources;
00193         m_pressResult = PressResultState::ContinueLevel;
00194         SetGameInfoOverlay(GameInfoOverlayState::Pause);
00195         m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait);
00196     }
00197     else if (!m_game->GameActive() && (m_game->HighScore().totalHits > 0))
00198     {
00199         // The last time the game terminated the game had been completed.
00200         // Show the high score.
00201         // We are waiting for the user to acknowledge the high score and start a new game.
00202         // The level resources for the first level will be loaded later.
00203         m_updateState = UpdateEngineState::WaitingForPress;
00204         m_pressResult = PressResultState::LoadGame;
00205         SetGameInfoOverlay(GameInfoOverlayState::GameStats);
00206         m_controller->WaitForPress(m_renderer->GameInfoOverlayUpperLeft(), m_renderer->GameInfoOverlayLowerRight());
00207         m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue);
00208     }
00209     else
00210     {
00211         // This is either the first time the game has run or
00212         // the last time the game terminated the level was completed.
00213         // We are waiting for the user to begin the next level.
00214         m_updateState = UpdateEngineState::WaitingForResources;
00215         m_pressResult = PressResultState::PlayLevel;
00216         SetGameInfoOverlay(GameInfoOverlayState::LevelStart);
00217         m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait);
00218     }
00219     m_uiControl->ShowGameInfoOverlay();
00220 }
00221
00222 void GameMain::WaitingForResourceLoading()
00223 {
00224     static uint32_t loadCount = 0;
00225
00226     // Waiting for initial load. Display an update once per 60 updates.
00227     if (((loadCount++) % 60) == 0)
00228     {
00229         m_loadingCount++;
00230         SetGameInfoOverlay(m_gameInfoOverlayState);
00231         m_renderNeeded = true;
00232     }
00233 }
00234
00235 void GameMain::Update()
00236 {
00237     m_controller->Update();
00238
00239     switch (m_updateState)
00240     {
00241     case UpdateEngineState::WaitingForResources:
00242         WaitingForResourceLoading();
00243         break;
00244
00245     case UpdateEngineState::ResourcesLoaded:
00246         switch (m_pressResult)
00247         {
00248         case PressResultState::LoadGame:
00249             SetGameInfoOverlay(GameInfoOverlayState::GameStats);
00250             break;
00251
00252         case PressResultState::PlayLevel:
00253             SetGameInfoOverlay(GameInfoOverlayState::LevelStart);
00254             break;
00255
00256         case PressResultState::ContinueLevel:
00257             SetGameInfoOverlay(GameInfoOverlayState::Pause);
00258             break;
00259         }
00260         m_updateState = UpdateEngineState::WaitingForPress;
00261         m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue);
00262         m_controller->WaitForPress(m_renderer->GameInfoOverlayUpperLeft(), m_renderer->GameInfoOverlayLowerRight());
00263         m_uiControl->ShowGameInfoOverlay();
00264         m_renderNeeded = true;
00265         break;
00266
00267     case UpdateEngineState::WaitingForPress:
00268         if (m_controller->IsPressComplete())
00269         {
00270             switch (m_pressResult)
00271             {
00272             case PressResultState::LoadGame:
00273                 m_updateState = UpdateEngineState::WaitingForResources;
00274                 m_pressResult = PressResultState::PlayLevel;
00275                 m_controller->Active(false);
00276                 m_game->LoadGame();
00277                 m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait);
00278                 SetGameInfoOverlay(GameInfoOverlayState::LevelStart);
00279                 m_uiControl->ShowGameInfoOverlay();
00280
00281                 LoadAndFinalizeLevelInBackground();
00282                 break;
00283
00284             case PressResultState::PlayLevel:
00285                 m_updateState = UpdateEngineState::Dynamics;
00286                 m_uiControl->HideGameInfoOverlay();
00287                 m_controller->Active(true);
00288                 m_game->StartLevel();
00289                 break;
00290
00291             case PressResultState::ContinueLevel:
00292                 m_updateState = UpdateEngineState::Dynamics;
00293                 m_uiControl->HideGameInfoOverlay();
00294                 m_controller->Active(true);
00295                 m_game->ContinueGame();
00296                 break;
00297             }
00298         }
00299         break;
00300
00301     case UpdateEngineState::Dynamics:
00302         if (m_controller->IsPauseRequested())
00303         {
00304             m_game->PauseGame();
00305             SetGameInfoOverlay(GameInfoOverlayState::Pause);
00306             m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue);
00307             m_updateState = UpdateEngineState::WaitingForPress;
00308             m_pressResult = PressResultState::ContinueLevel;
00309             m_uiControl->ShowGameInfoOverlay();
00310         }
00311         else
00312         {
00313             GameState runState = m_game->RunGame();
00314             switch (runState)
00315             {
00316             case GameState::TimeExpired:
00317                 m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue);
00318                 SetGameInfoOverlay(GameInfoOverlayState::GameOverExpired);
00319                 m_uiControl->ShowGameInfoOverlay();
00320                 m_updateState = UpdateEngineState::WaitingForPress;
00321                 m_pressResult = PressResultState::LoadGame;
00322                 break;
00323
00324             case GameState::LevelComplete:
00325                 m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait);
00326                 SetGameInfoOverlay(GameInfoOverlayState::LevelStart);
00327                 m_uiControl->ShowGameInfoOverlay();
00328                 m_updateState = UpdateEngineState::WaitingForResources;
00329                 m_pressResult = PressResultState::PlayLevel;
00330
00331                 LoadAndFinalizeLevelInBackground();
00332                 break;
00333
00334             case GameState::GameComplete:
00335                 m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue);
00336                 SetGameInfoOverlay(GameInfoOverlayState::GameOverCompleted);
00337                 m_uiControl->ShowGameInfoOverlay();
00338                 m_updateState = UpdateEngineState::WaitingForPress;
00339                 m_pressResult = PressResultState::LoadGame;
00340                 break;
00341             }
00342         }
00343
00344         if (m_updateState == UpdateEngineState::WaitingForPress)
00345         {
00346             // Transitioning state, so enable waiting for the press event
00347             m_controller->WaitForPress(m_renderer->GameInfoOverlayUpperLeft(), m_renderer->GameInfoOverlayLowerRight());
00348         }
00349         if (m_updateState == UpdateEngineState::WaitingForResources)
00350         {
00351             // Transitioning state, so shut down the input controller until resources are loaded
00352             m_controller->Active(false);
00353         }
00354         break;
00355     }
00356 }
00357
00358 winrt::fire_and_forget GameMain::LoadAndFinalizeLevelInBackground(bool renderNeeded)
00359 {
00360     auto lifetime = get_strong();
00361
00362     co_await m_game->LoadLevelAsync();
00363     m_game->FinalizeLoadLevel();
00364     m_updateState = UpdateEngineState::ResourcesLoaded;
00365     if (renderNeeded)
00366     {
00367         m_renderNeeded = true;
00368     }
00369 }
00370
00371 void GameMain::CreateWindowSizeDependentResources()
00372 {
00373     UpdateLayoutState();
00374     m_renderer->CreateWindowSizeDependentResources();
00375
00376     // The location of the Control regions may have changed with the size change so update the controller.
00377     auto bounds = m_deviceResources->GetLogicalSize();
00378
00379     m_controller->SetMoveRect(
00380         XMFLOAT2(0.0f, bounds.Height - GameUIConstants::TouchRectangleSize),
00381         XMFLOAT2(GameUIConstants::TouchRectangleSize, bounds.Height)
00382         );
00383     m_controller->SetFireRect(
00384         XMFLOAT2(bounds.Width - GameUIConstants::TouchRectangleSize, bounds.Height - GameUIConstants::TouchRectangleSize),
00385         XMFLOAT2(bounds.Width, bounds.Height)
00386         );
00387
00388     if (m_updateState == UpdateEngineState::WaitingForPress)
00389     {
00390         // A side effect of m_renderer->UpdateForWindowSizeChange() is that the GameInfoOverlay rectangle may have
00391         // changed as a result of layout, so make sure the WaitForPress rectangle is set to the new size.
00392         m_controller->WaitForPress(m_renderer->GameInfoOverlayUpperLeft(), m_renderer->GameInfoOverlayLowerRight());
00393     }
00394
00395     m_renderNeeded = true;
00396 }
00397
00398 void GameMain::OnDeviceLost()
00399 {
00400     if (m_updateState == UpdateEngineState::Dynamics)
00401     {
00402         // Game is in the active game play state, Stop Game Timer and Pause play and save state
00403         m_game->PauseGame();
00404     }
00405     m_renderNeeded = false;
00406     m_renderer->ReleaseDeviceDependentResources();
00407 }
00408
00409 void GameMain::OnDeviceRestored()
00410 {
00411     HandleDeviceRestored();
00412 }
00413
00414 winrt::fire_and_forget GameMain::HandleDeviceRestored()
00415 {
00416     auto lifetime = get_strong();
00417
00418     m_renderer->CreateDeviceDependentResources();
00419     m_renderer->CreateWindowSizeDependentResources();
00420
00421     m_loadingCount = 0;
00422     m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait);
00423     SetGameInfoOverlay(GameInfoOverlayState::Loading);
00424     m_updateState = UpdateEngineState::WaitingForResources;
00425     m_renderNeeded = true;
00426
00427     co_await m_renderer->CreateGameDeviceResourcesAsync(m_game);
00428
00429     // The finalize code needs to run in the same thread context
00430     // as the m_renderer object was created because the D3D device context
00431     // can ONLY be accessed on a single thread.
00432     // co_await of an IAsyncAction resumes in the same thread context.
00433     m_renderer->FinalizeCreateGameDeviceResources();
00434
00435     // Reset the main state machine based on the current game state now
00436     // that the device resources have been restored.
00437     InitializeGameState();
00438
00439     if (m_updateState == UpdateEngineState::WaitingForResources)
00440     {
00441         // In the middle of a game so spin up the async task to load the level.
00442         co_await m_game->LoadLevelAsync();
00443         // The m_game object may need to deal with D3D device context work so
00444         // again the finalize code needs to run in the same thread
00445         // context as the m_renderer object was created because the D3D
00446         // device context can be accessed ONLY on a single thread.
00447     // co_await of an IAsyncAction resumes in the same thread context.
00448         m_game->FinalizeLoadLevel();
00449         m_game->SetCurrentLevelToSavedState();
00450         m_updateState = UpdateEngineState::ResourcesLoaded;
00451         m_renderNeeded = true;
00452
00453     }
00454     else
00455     {
00456         // The game is not in the middle of a level so there aren't any level
00457         // resources to load.
00458     }
00459
00460
00461     // Since Device lost is an unexpected event, the app visual state
00462     // may be TooSmall or not have focus. Put the state machine
00463     // into the correct state to reflect these cases.
00464     if (CoreWindow::GetForCurrentThread().Bounds().Width < GameUIConstants::MinPlayableWidth)
00465     {
00466         m_updateStateNext = m_updateState;
00467         m_updateState = UpdateEngineState::TooSmall;
00468         m_controller->Active(false);
00469         m_uiControl->HideGameInfoOverlay();
00470         m_uiControl->ShowTooSmall();
00471         m_renderNeeded = true;
00472     }
00473     else if (!m_haveFocus)
00474     {
00475         m_updateStateNext = m_updateState;
00476         m_updateState = UpdateEngineState::Deactivated;
00477         m_controller->Active(false);
00478         m_uiControl->SetAction(GameInfoOverlayCommand::None);
00479         m_renderNeeded = true;
00480     }
00481 }
00482
00483 void GameMain::UpdateLayoutState()
00484 {
00485     m_renderNeeded = true;
00486
00487     if (m_deviceResources->GetLogicalSize().Width < GameUIConstants::MinPlayableWidth)
00488     {
00489         switch (m_updateState)
00490         {
00491         case UpdateEngineState::Dynamics:
00492             // From Dynamic mode, when coming out of TooSmall layout rather than going directly back into game play
00493             // go to the paused state waiting for user input to continue
00494             m_updateStateNext = UpdateEngineState::WaitingForPress;
00495             m_pressResult = PressResultState::ContinueLevel;
00496             SetGameInfoOverlay(GameInfoOverlayState::Pause);
00497             m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue);
00498             m_game->PauseGame();
00499             break;
00500
00501         case UpdateEngineState::WaitingForResources:
00502             // There is outstanding async loading in progress. This state change will be picked up after the
00503             // async task is completed.
00504             return;
00505
00506         case UpdateEngineState::WaitingForPress:
00507             // Avoid corrupting the m_updateStateNext on a transition from TooSmall -> TooSmall.
00508             // Otherwise just cache the current state and return to it when leaving TooSmall layout
00509
00510             m_updateStateNext = m_updateState;
00511             break;
00512
00513         default:
00514             break;
00515         }
00516
00517         m_updateState = UpdateEngineState::TooSmall;
00518         m_controller->Active(false);
00519         m_uiControl->HideGameInfoOverlay();
00520         m_uiControl->ShowTooSmall();
00521     }
00522     else
00523     {
00524         if (m_updateState == UpdateEngineState::TooSmall)
00525         {
00526             m_uiControl->HideTooSmall();
00527             m_uiControl->ShowGameInfoOverlay();
00528             m_renderNeeded = true;
00529
00530             if (m_haveFocus)
00531             {
00532                 if (m_updateStateNext == UpdateEngineState::WaitingForPress)
00533                 {
00534                     m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue);
00535                 }
00536                 else if (m_updateStateNext == UpdateEngineState::WaitingForResources)
00537                 {
00538                     m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait);
00539                 }
00540
00541                 m_updateState = m_updateStateNext;
00542             }
00543             else
00544             {
00545                 m_updateState = UpdateEngineState::Deactivated;
00546                 m_uiControl->SetAction(GameInfoOverlayCommand::None);
00547             }
00548         }
00549         else if (m_updateState == UpdateEngineState::Dynamics)
00550         {
00551             // In Dynamic mode, when a resize event happens, go to the paused state waiting for user input to continue.
00552             m_pressResult = PressResultState::ContinueLevel;
00553             SetGameInfoOverlay(GameInfoOverlayState::Pause);
00554             m_game->PauseGame();
00555             if (m_haveFocus)
00556             {
00557                 m_updateState = UpdateEngineState::WaitingForPress;
00558                 m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue);
00559             }
00560             else
00561             {
00562                 m_updateState = UpdateEngineState::Deactivated;
00563                 m_uiControl->SetAction(GameInfoOverlayCommand::None);
00564             }
00565             m_uiControl->ShowGameInfoOverlay();
00566             m_renderNeeded = true;
00567         }
00568     }
00569 }
00570
00571 void GameMain::ResetGame()
00572 {
00573     m_updateState = UpdateEngineState::WaitingForResources;
00574     m_pressResult = PressResultState::PlayLevel;
00575     m_controller->Active(false);
00576     m_game->LoadGame();
00577     m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait);
00578     SetGameInfoOverlay(GameInfoOverlayState::LevelStart);
00579     m_uiControl->ShowGameInfoOverlay();
00580     m_renderNeeded = true;
00581
00582     LoadAndFinalizeLevelInBackground(/* renderNeeded */ true);
00583 }
00584
00585 void GameMain::SetGameInfoOverlay(GameInfoOverlayState state)
00586 {
00587     m_gameInfoOverlayState = state;
00588     switch (state)
00589     {
00590     case GameInfoOverlayState::Loading:
00591         m_uiControl->SetGameLoading(m_loadingCount);
00592         break;
00593
00594     case GameInfoOverlayState::GameStats:
00595         m_uiControl->SetGameStats(
00596             m_game->HighScore().levelCompleted + 1,
00597             m_game->HighScore().totalHits,
00598             m_game->HighScore().totalShots
00599             );
00600         break;
00601
00602     case GameInfoOverlayState::LevelStart:
00603         m_uiControl->SetLevelStart(
00604             m_game->LevelCompleted() + 1,
00605             m_game->CurrentLevel()->Objective(),
00606             m_game->CurrentLevel()->TimeLimit(),
00607             m_game->BonusTime()
00608             );
00609         break;
00610
00611     case GameInfoOverlayState::GameOverCompleted:
00612         m_uiControl->SetGameOver(
00613             true,
00614             m_game->LevelCompleted() + 1,
00615             m_game->TotalHits(),
00616             m_game->TotalShots(),
00617             m_game->HighScore().totalHits
00618             );
00619         break;
00620
00621     case GameInfoOverlayState::GameOverExpired:
00622         m_uiControl->SetGameOver(
00623             false,
00624             m_game->LevelCompleted(),
00625             m_game->TotalHits(),
00626             m_game->TotalShots(),
00627             m_game->HighScore().totalHits
00628             );
00629         break;
00630
00631     case GameInfoOverlayState::Pause:
00632         m_uiControl->SetPause(
00633             m_game->LevelCompleted() + 1,
00634             m_game->TotalHits(),
00635             m_game->TotalShots(),
00636             m_game->TimeRemaining()
00637             );
00638         break;
00639     }
00640 }
00641
00642 void GameMain::WindowActivationChanged(CoreWindowActivationState activationState)
00643 {
00644     if (activationState == CoreWindowActivationState::Deactivated)
00645     {
00646         m_haveFocus = false;
00647
00648         switch (m_updateState)
00649         {
00650         case UpdateEngineState::Dynamics:
00651             // From Dynamic mode, when coming out of Deactivated rather than going directly back into game play
00652             // go to the paused state waiting for user input to continue
00653             m_updateStateNext = UpdateEngineState::WaitingForPress;
00654             m_pressResult = PressResultState::ContinueLevel;
00655             SetGameInfoOverlay(GameInfoOverlayState::Pause);
00656             m_uiControl->ShowGameInfoOverlay();
00657             m_game->PauseGame();
00658             m_updateState = UpdateEngineState::Deactivated;
00659             m_uiControl->SetAction(GameInfoOverlayCommand::None);
00660             m_renderNeeded = true;
00661             break;
00662
00663         case UpdateEngineState::WaitingForResources:
00664         case UpdateEngineState::WaitingForPress:
00665             m_updateStateNext = m_updateState;
00666             m_updateState = UpdateEngineState::Deactivated;
00667             m_uiControl->SetAction(GameInfoOverlayCommand::None);
00668             m_uiControl->ShowGameInfoOverlay();
00669             m_renderNeeded = true;
00670             break;
00671         }
00672         // Don't have focus so shutdown input processing
00673         m_controller->Active(false);
00674     }
00675     else if (activationState == CoreWindowActivationState::CodeActivated
00676         || activationState == CoreWindowActivationState::PointerActivated)
00677     {
00678         m_haveFocus = true;
00679
00680         if (m_updateState == UpdateEngineState::Deactivated)
00681         {
00682             m_updateState = m_updateStateNext;
00683
00684             if (m_updateState == UpdateEngineState::WaitingForPress)
00685             {
00686                 m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue);
00687                 m_controller->WaitForPress(m_renderer->GameInfoOverlayUpperLeft(), m_renderer->GameInfoOverlayLowerRight());
00688             }
00689             else if (m_updateStateNext == UpdateEngineState::WaitingForResources)
00690             {
00691                 m_uiControl->SetAction(GameInfoOverlayCommand::PleaseWait);
00692             }
00693         }
00694     }
00695 }
00696
00697 void GameMain::Suspend()
00698 {
00699     // Save application state.
00700     switch (m_updateState)
00701     {
00702     case UpdateEngineState::Dynamics:
00703         // Game is in the active game play state, Stop Game Timer and Pause play and save state
00704         m_uiControl->SetAction(GameInfoOverlayCommand::None);
00705         SetGameInfoOverlay(GameInfoOverlayState::Pause);
00706         m_updateStateNext = UpdateEngineState::WaitingForPress;
00707         m_pressResult = PressResultState::ContinueLevel;
00708         m_game->PauseGame();
00709         break;
00710
00711     case UpdateEngineState::WaitingForResources:
00712     case UpdateEngineState::WaitingForPress:
00713         m_updateStateNext = m_updateState;
00714         break;
00715
00716     default:
00717         // any other state don't save as next state as they are trancient states and have already set m_updateStateNext
00718         break;
00719     }
00720     m_updateState = UpdateEngineState::Suspended;
00721
00722     m_controller->Active(false);
00723     m_game->OnSuspending();
00724 }
00725
00726 void GameMain::Resume()
00727 {
00728     if (m_haveFocus)
00729     {
00730         m_updateState = m_updateStateNext;
00731     }
00732     else
00733     {
00734         m_updateState = UpdateEngineState::Deactivated;
00735     }
00736
00737     if (m_updateState == UpdateEngineState::WaitingForPress)
00738     {
00739         m_uiControl->SetAction(GameInfoOverlayCommand::TapToContinue);
00740         m_controller->WaitForPress(m_renderer->GameInfoOverlayUpperLeft(), m_renderer->GameInfoOverlayLowerRight());
00741     }
00742     m_game->OnResuming();
00743     m_uiControl->ShowGameInfoOverlay();
00744     m_renderNeeded = true;
00745 }
00746
00747 void GameMain::Visibility(bool visible)
00748 {
00749     if (visible && !m_visible)
00750     {
00751         m_renderNeeded = true;
00752     }
00753     m_visible = visible;
00754 }
Generated on Fri Nov 15 2024 22:21:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Custom Member List

This is the complete list of members for Scenario2_Custom, including all inherited members.
_cts | Scenario2_Custom | [private]
_dispatcher | Scenario2_Custom | [private]
_InputFile | Scenario2_Custom | [private]
_OutputFile | Scenario2_Custom | [private]
_OutputFileExtension | Scenario2_Custom | [private]
_OutputFileName | Scenario2_Custom | [private]
_OutputType | Scenario2_Custom | [private]
_Profile | Scenario2_Custom | [private]
_Transcoder | Scenario2_Custom | [private]
_UseMp4 | Scenario2_Custom | [private]
DisableButtons() | Scenario2_Custom | [inline, private]
Dispose() | Scenario2_Custom | [inline]
EnableButtons() | Scenario2_Custom | [inline, private]
GetCustomProfile() | Scenario2_Custom | [inline, private]
InputPauseButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_Custom | [inline, private]
InputPlayButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_Custom | [inline, private]
InputStopButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_Custom | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_Custom | [inline, protected]
OnTargetFormatChanged(object sender, SelectionChangedEventArgs e) | Scenario2_Custom | [inline, private]
OutputPathText(string text) | Scenario2_Custom | [inline, private]
OutputPauseButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_Custom | [inline, private]
OutputPlayButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_Custom | [inline, private]
OutputStopButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_Custom | [inline, private]
OutputText(string text) | Scenario2_Custom | [inline, private]
PickFile(object sender, RoutedEventArgs e) | Scenario2_Custom | [inline, private]
PickOutput(object sender, RoutedEventArgs e) | Scenario2_Custom | [inline, private]
PlayFile(Windows.Storage.StorageFile MediaFile) | Scenario2_Custom | [inline, private]
rootPage | Scenario2_Custom | [private]
Scenario2_Custom() | Scenario2_Custom | [inline]
SetCancelButton(bool isEnabled) | Scenario2_Custom | [inline, private]
SetOutputFileButton(bool isEnabled) | Scenario2_Custom | [inline, private]
SetPickFileButton(bool isEnabled) | Scenario2_Custom | [inline, private]
SetTranscodeButton(bool isEnabled) | Scenario2_Custom | [inline, private]
StopPlayers() | Scenario2_Custom | [inline, private]
TranscodeCancel(object sender, RoutedEventArgs e) | Scenario2_Custom | [inline, private]
TranscodeComplete() | Scenario2_Custom | [inline, private]
TranscodeCustom(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_Custom | [inline, private]
TranscodeError(string error) | Scenario2_Custom | [inline, private]
TranscodeFailure(TranscodeFailureReason reason) | Scenario2_Custom | [inline, private]
TranscodeProgress(double percent) | Scenario2_Custom | [inline, private]
Generated on Fri Nov 15 2024 22:23:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/Common/BasicReaderWriter.h Source File

  • Simple3DGameDX
  • cpp
  • Common

BasicReaderWriter.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include <ppltasks.h>
00011
00012 // A simple reader/writer class that provides support for reading and writing
00013 // files on disk. Provides synchronous and asynchronous methods.
00014 ref class BasicReaderWriter
00015 {
00016 private:
00017     Windows::Storage::StorageFolder^ m_location;
00018
00019 internal:
00020     BasicReaderWriter();
00021     BasicReaderWriter(
00022         _In_ Windows::Storage::StorageFolder^ folder
00023         );
00024
00025     Platform::Array<byte>^ ReadData(
00026         _In_ Platform::String^ filename
00027         );
00028
00029     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00030         _In_ Platform::String^ filename
00031         );
00032
00033     uint32 WriteData(
00034         _In_ Platform::String^ filename,
00035         _In_ const Platform::Array<byte>^ fileData
00036         );
00037
00038     concurrency::task<void> WriteDataAsync(
00039         _In_ Platform::String^ filename,
00040         _In_ const Platform::Array<byte>^ fileData
00041         );
00042 };
Generated on Fri Nov 15 2024 22:19:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cs/Scenario_SynthesizeSSML.xaml.cs Source File

  • SpeechRecognitionAndSynthesis
  • cs

Scenario_SynthesizeSSML.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Linq;
00014 using Windows.ApplicationModel.Resources.Core;
00015 using Windows.Data.Xml.Dom;
00016 using Windows.Foundation.Collections;
00017 using Windows.Media.Core;
00018 using Windows.Media.Playback;
00019 using Windows.Media.SpeechSynthesis;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Media;
00023
00024 namespace SDKTemplate
00025 {
00026     public sealed partial class Scenario_SynthesizeSSML : Page
00027     {
00028         private SpeechSynthesizer synthesizer;
00029         private ResourceContext speechContext;
00030         private ResourceMap speechResourceMap;
00031
00032         public Scenario_SynthesizeSSML()
00033         {
00034             InitializeComponent();
00035             synthesizer = new SpeechSynthesizer();
00036
00037             speechContext = ResourceContext.GetForCurrentView();
00038             speechContext.Languages = new string[] { SpeechSynthesizer.DefaultVoice.Language };
00039
00040             speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationTTSResources");
00041
00042             MediaPlayer player = new MediaPlayer();
00043             player.AutoPlay = false;
00044             player.MediaEnded += media_MediaEnded;
00045
00046             media.SetMediaPlayer(player);
00047             media.MediaPlayer.AutoPlay = false;
00048
00049             InitializeListboxVoiceChooser();
00050             UpdateSSMLText();
00051         }
00052
00053         /// <summary>
00054         /// This is invoked when the user clicks on the speak/stop button.
00055         /// </summary>
00056         /// <param name="sender">Button that triggered this event</param>
00057         /// <param name="e">State information about the routed event</param>
00058         private async void Speak_Click(object sender, RoutedEventArgs e)
00059         {
00060             // If the media is playing, the user has pressed the button to stop the playback.
00061             if (media.MediaPlayer.PlaybackSession.PlaybackState == MediaPlaybackState.Playing)
00062             {
00063                 media.MediaPlayer.Pause();
00064                 btnSpeak.Content = "Speak";
00065             }
00066             else
00067             {
00068                 string text = textToSynthesize.Text;
00069                 if (!string.IsNullOrEmpty(text))
00070                 {
00071                     // Change the button label. You could also just disable the button if you don't want any user control.
00072                     btnSpeak.Content = "Stop";
00073
00074                     try
00075                     {
00076                         // Create a stream from the text. This will be played using a media element.
00077                         SpeechSynthesisStream synthesisStream = await synthesizer.SynthesizeSsmlToStreamAsync(text);
00078
00079                         // Create a media source from the stream:
00080                         var mediaSource = MediaSource.CreateFromStream(synthesisStream, synthesisStream.ContentType);
00081
00082                         //Create a Media Playback Item
00083                         var mediaPlaybackItem = new MediaPlaybackItem(mediaSource);
00084
00085                         // Ensure that the app is notified for marks.
00086                         RegisterForMarkEvents(mediaPlaybackItem);
00087
00088                         // Set the source of the MediaElement or MediaPlayerElement to the MediaPlaybackItem
00089                         // and start playing the synthesized audio stream.
00090                         media.Source = mediaPlaybackItem;
00091                         media.MediaPlayer.Play();
00092                     }
00093                     catch (System.IO.FileNotFoundException)
00094                     {
00095                         // If media player components are unavailable, (eg, using a N SKU of windows), we won't
00096                         // be able to start media playback. Handle this gracefully
00097                         btnSpeak.Content = "Speak";
00098                         btnSpeak.IsEnabled = false;
00099                         textToSynthesize.IsEnabled = false;
00100                         listboxVoiceChooser.IsEnabled = false;
00101                         var messageDialog = new Windows.UI.Popups.MessageDialog("Media player components unavailable");
00102                         await messageDialog.ShowAsync();
00103                     }
00104                     catch (Exception)
00105                     {
00106                         // If the SSML stream is not in the correct format, throw an error message to the user.
00107                         btnSpeak.Content = "Speak";
00108                         var messageDialog = new Windows.UI.Popups.MessageDialog("Unable to synthesize text");
00109                         await messageDialog.ShowAsync();
00110                     }
00111                 }
00112             }
00113         }
00114
00115         /// <summary>
00116         /// Register for all mark events
00117         /// </summary>
00118         /// <param name="mediaPlaybackItem">The Media PLayback Item add handlers to.</param>
00119         private void RegisterForMarkEvents(MediaPlaybackItem mediaPlaybackItem)
00120         {
00121             //tracks could all be generated at creation
00122             for (int index =0; index < mediaPlaybackItem.TimedMetadataTracks.Count; index++)
00123             {
00124                 RegisterMetadataHandlerForMarks(mediaPlaybackItem, index);
00125             }
00126
00127             // if the tracks are added later we will
00128             // monitor the tracks being added and subscribe to the ones of interest
00129             mediaPlaybackItem.TimedMetadataTracksChanged += (MediaPlaybackItem sender, IVectorChangedEventArgs args) =>
00130             {
00131                 if (args.CollectionChange == CollectionChange.ItemInserted)
00132                 {
00133                     RegisterMetadataHandlerForMarks(sender, (int)args.Index);
00134                 }
00135                 else if (args.CollectionChange == CollectionChange.Reset)
00136                 {
00137                     for (int index = 0; index < sender.TimedMetadataTracks.Count; index++)
00138                     {
00139                         RegisterMetadataHandlerForMarks(sender, index);
00140                     }
00141                 }
00142             };
00143         }
00144
00145         /// <summary>
00146         /// Register for just word bookmark events.
00147         /// </summary>
00148         /// <param name="mediaPlaybackItem">The Media Playback Item to register handlers for.</param>
00149         /// <param name="index">Index of the timedMetadataTrack within the mediaPlaybackItem.</param>
00150         private void RegisterMetadataHandlerForMarks(MediaPlaybackItem mediaPlaybackItem, int index)
00151         {
00152             //make sure we only register for bookmarks
00153             var timedTrack = mediaPlaybackItem.TimedMetadataTracks[index];
00154             if(timedTrack.Id == "SpeechBookmark")
00155             {
00156                 timedTrack.CueEntered += metadata_MarkCueEntered;
00157                 mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode((uint)index, TimedMetadataTrackPresentationMode.ApplicationPresented);
00158
00159             }
00160         }
00161
00162         /// <summary>
00163         /// This function executes when a SpeechCue is hit and calls the functions to update the UI
00164         /// </summary>
00165         /// <param name="timedMetadataTrack">The timedMetadataTrack associated with the event.</param>
00166         /// <param name="args">the arguments associated with the event.</param>
00167         private async void metadata_MarkCueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args)
00168         {
00169             // Check in case there are different tracks and the handler was used for more tracks
00170             if (timedMetadataTrack.TimedMetadataKind == TimedMetadataKind.Speech)
00171             {
00172                 var cue = args.Cue as SpeechCue;
00173                 if (cue != null)
00174                 {
00175                     System.Diagnostics.Debug.WriteLine("Cue text:[" + cue.Text + "]");
00176                     // Do something with the cue
00177                     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
00178                      () =>
00179                      {
00180                          // Your UI update code goes here!
00181                          FillTextBox(cue);
00182                      });
00183                 }
00184             }
00185         }
00186
00187         /// <summary>
00188         /// Update the UI with text from the mark
00189         /// </summary>
00190         /// <param name="cue">The cue containing the text</param>
00191         private void FillTextBox(SpeechCue cue)
00192         {
00193             textBoxLastMarkTriggered.Text = cue.Text;
00194         }
00195
00196         /// <summary>
00197         /// This is invoked when the stream is finished playing.
00198         /// </summary>
00199         /// <remarks>
00200         /// In this case, we're changing the button label based on the state.
00201         /// </remarks>
00202         /// <param name="sender">unused object parameter</param>
00203         /// <param name="e">unused event parameter</param>
00204         async void media_MediaEnded(MediaPlayer sender, object e)
00205         {
00206             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
00207              () =>
00208              {
00209                  // Your UI update code goes here!
00210                  btnSpeak.Content = "Speak";
00211              });
00212         }
00213
00214         /// <summary>
00215         /// This creates items out of the system installed voices. The voices are then displayed in a listbox.
00216         /// This allows the user to change the voice of the synthesizer in your app based on their preference.
00217         /// </summary>
00218         private void InitializeListboxVoiceChooser()
00219         {
00220             // Get all of the installed voices.
00221             var voices = SpeechSynthesizer.AllVoices;
00222
00223             // Get the currently selected voice.
00224             VoiceInformation currentVoice = synthesizer.Voice;
00225
00226             foreach (VoiceInformation voice in voices.OrderBy(p => p.Language))
00227             {
00228                 ComboBoxItem item = new ComboBoxItem();
00229                 item.Name = voice.DisplayName;
00230                 item.Tag = voice;
00231                 item.Content = voice.DisplayName + " (Language: " + voice.Language + ")";
00232                 listboxVoiceChooser.Items.Add(item);
00233
00234                 // Check to see if we're looking at the current voice and set it as selected in the listbox.
00235                 if (currentVoice.Id == voice.Id)
00236                 {
00237                     item.IsSelected = true;
00238                     listboxVoiceChooser.SelectedItem = item;
00239                 }
00240             }
00241         }
00242
00243         /// <summary>
00244         /// This is called when the user has selects a voice from the drop down.
00245         /// </summary>
00246         /// <param name="sender">unused object parameter</param>
00247         /// <param name="e">unused event parameter</param>
00248         private void ListboxVoiceChooser_SelectionChanged(object sender, SelectionChangedEventArgs e)
00249         {
00250             ComboBoxItem item = (ComboBoxItem)(listboxVoiceChooser.SelectedItem);
00251             VoiceInformation voice = (VoiceInformation)(item.Tag);
00252             synthesizer.Voice = voice;
00253
00254             // update UI text to be an appropriate default translation.
00255             speechContext.Languages = new string[] { voice.Language };
00256             textToSynthesize.Text = speechResourceMap.GetValue("SynthesizeSSMLDefaultText", speechContext).ValueAsString;
00257
00258             UpdateSSMLText();
00259         }
00260
00261         /// <summary>
00262         /// Update the text in the SSML field to match the language of the chosen synthesizer voice.
00263         /// </summary>
00264         /// <remarks>
00265         /// SSML language takes priority over the chosen synthesizer language.
00266         /// Thus, when changing voices, we need to update the SSML language to match.
00267         /// </remarks>
00268         private void UpdateSSMLText()
00269         {
00270             try
00271             {
00272                 string text = textToSynthesize.Text;
00273                 string language = synthesizer.Voice.Language;
00274
00275                 XmlDocument doc = new XmlDocument();
00276                 doc.LoadXml(text);
00277
00278                 var LangAttribute = doc.DocumentElement.GetAttributeNode("xml:lang");
00279                 LangAttribute.InnerText = language;
00280
00281                 textToSynthesize.Text = doc.GetXml();
00282             }
00283             catch
00284             {
00285                 // This can fail if the user is in the process of editing the XML.
00286                 // In this case, we don't update the SSML language but also don't throw a failure.
00287             }
00288         }
00289     }
00290 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GpuCoordinateMapper::CameraIntrinsics Member List

This is the complete list of members for GpuCoordinateMapper::CameraIntrinsics, including all inherited members.
CameraIntrinsics() | GpuCoordinateMapper::CameraIntrinsics |
CameraIntrinsics(Windows::Media::Devices::Core::CameraIntrinsics^intrinsics) | GpuCoordinateMapper::CameraIntrinsics | [inline, explicit]
focalLength | GpuCoordinateMapper::CameraIntrinsics |
imageHeight | GpuCoordinateMapper::CameraIntrinsics |
imageWidth | GpuCoordinateMapper::CameraIntrinsics |
operator!=(const CameraIntrinsics &rhs) const | GpuCoordinateMapper::CameraIntrinsics | [inline]
principalPoint | GpuCoordinateMapper::CameraIntrinsics |
radialDistortion | GpuCoordinateMapper::CameraIntrinsics |
tangentialDistortion | GpuCoordinateMapper::CameraIntrinsics |
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Compression/cpp/CompressionUtils.cpp Source File

  • Compression
  • cpp

CompressionUtils.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "MainPage.xaml.h"
00003 #include "SampleConfiguration.h"
00004 #include "CompressionUtils.h"
00005
00006 using namespace Windows::Storage;
00007 using namespace Windows::Storage::Pickers;
00008 using namespace Windows::Storage::Streams;
00009 using namespace Windows::Storage::Compression;
00010
00011 using namespace concurrency;
00012
00013 #pragma region ReadStreamTask implementation
00014 // We can't derive from task because we need to initialize task_completion_event before task itself.
00015 struct ReadStreamTask::ReadStreamTaskImpl {
00016     ReadStreamTaskImpl(IInputStream^ Stream, std::vector<byte> &Destination) :
00017         _Destination(Destination),
00018         _Reader(ref new DataReader(Stream)),
00019         _CompletionEvent()
00020     {
00021     }
00022
00023     task<size_t> RunTask()
00024     {
00025         ReadChunk();
00026         return create_task(_CompletionEvent).then([this]
00027         {
00028             // Schedule resource deallocation
00029             std::unique_ptr<ReadStreamTaskImpl> thisHolder(this);
00030
00031             // Prevent user provided stream from being closed
00032             _Reader->DetachStream();
00033
00034             // Move data out
00035             _Destination = std::move(_StreamData);
00036
00037             return _Destination.size();
00038         });
00039     }
00040
00041     void ReadChunk()
00042     {
00043         // LoadAsync itself could throw exception if IAsyncOperation couldn't be created with
00044         // given parameters in a current state
00045         try
00046         {
00047             // Read data into the data reader
00048             _StreamData.reserve(_StreamData.size() + MinReadChunkSize);
00049             create_task(_Reader->LoadAsync(static_cast<unsigned int>(_StreamData.capacity() - _StreamData.size())))
00050
00051             // Then store it to the result vector
00052             .then([this](task<unsigned int> BytesRead)
00053             {
00054                 try
00055                 {
00056                     // exception is thrown here if LoadAsync operation has been completed with an error
00057                     auto bytesRead = BytesRead.get();
00058                     if (bytesRead)
00059                     {
00060                         // Store chunk of data in the result vector.
00061                         auto newData = ref new Platform::Array<byte>(bytesRead);
00062                         _Reader->ReadBytes(newData);
00063
00064                         _StreamData.insert(_StreamData.end(), newData->begin(), newData->end());
00065
00066                         // Then recurse to read next chunk.
00067                         ReadChunk();
00068                     }
00069                     else
00070                     {
00071                         // End of stream is reached - complete top level task with the data we've read so far
00072
00073                         // make sure that _CompletionEvent outlives continuation which deletes this ReadStreamTaskImpl
00074                         auto completionEvent = _CompletionEvent;
00075                         completionEvent.set();
00076                     }
00077                 }
00078                 catch (...)
00079                 {
00080                     // Schedule resource deallocation
00081                     std::unique_ptr<ReadStreamTaskImpl> thisHolder(this);
00082
00083                     _CompletionEvent.set_exception(std::current_exception());
00084                 }
00085             });
00086         }
00087         catch (...)
00088         {
00089             // Schedule resource deallocation
00090             std::unique_ptr<ReadStreamTaskImpl> thisHolder(this);
00091
00092             _CompletionEvent.set_exception(std::current_exception());
00093         }
00094     }
00095
00096     // All data members are accessed serially - no synchronization is done
00097     std::vector<byte> &_Destination;
00098     DataReader^ _Reader;
00099     std::vector<byte> _StreamData;
00100
00101     task_completion_event<void> _CompletionEvent;
00102 };
00103
00104 ReadStreamTask::ReadStreamTask(IInputStream^ Stream, std::vector<byte> &Destination) :
00105     _Impl(new ReadStreamTaskImpl(Stream, Destination))
00106 {
00107 }
00108
00109 ReadStreamTask::ReadStreamTask(const ReadStreamTask& Task) :
00110     _Impl(Task._Impl)
00111 {
00112 }
00113
00114 ReadStreamTask &ReadStreamTask::operator=(const ReadStreamTask& Task)
00115 {
00116     _Impl = Task._Impl;
00117     return *this;
00118 }
00119
00120 task<size_t> ReadStreamTask::RunTask()
00121 {
00122     return _Impl->RunTask();
00123 }
00124 #pragma endregion
Generated on Fri Nov 15 2024 22:18:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCloudFontIntegration/cs/Scenario_Document1.xaml.cs Source File

  • XamlCloudFontIntegration
  • cs

Scenario_Document1.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013
00014
00015 namespace SDKTemplate
00016 {
00017     public sealed partial class Scenario_Document1 : Page
00018     {
00019         public Scenario_Document1()
00020         {
00021             this.InitializeComponent();
00022         }
00023
00024         private void Page_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00025         {
00026             // Font formatting is being applied on page load rather than in XAML markup
00027             // so that the on-demand cloud font behavior can be experienced when the
00028             // app runs rather than when the XAML file is viewed in Visual Studio.
00029
00030             // Formatting will be applied to all content elements in the page that don't
00031             // already have FontFamily set.
00032             this.FontFamily = new Windows.UI.Xaml.Media.FontFamily("Neue Haas Grotesk Text Pro");
00033         }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:22:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Inclinometer/cpp/SampleConfiguration.cpp Source File

  • Inclinometer
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Data Events", "SDKTemplate.Scenario1_DataEvents" },
00021     { "Polling", "SDKTemplate.Scenario2_Polling" },
00022     { "Calibration", "SDKTemplate.Scenario3_Calibration" }
00023 };
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LanguageFont/cs/SampleConfiguration.cs Source File

  • LanguageFont
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Globalization.Fonts;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Media;
00017
00018 namespace SDKTemplate
00019 {
00020     public partial class MainPage : Page
00021     {
00022         public const string FEATURE_NAME = "Language Font CS Sample";
00023
00024         List<Scenario> scenarios = new List<Scenario>
00025         {
00026             new Scenario() { Title = "Fonts for UI", ClassType = typeof(Scenario1_UIFonts) },
00027             new Scenario() { Title = "Fonts for Documents", ClassType = typeof(Scenario2_DocumentFonts) }
00028         };
00029
00030         public static void ApplyLanguageFont(TextBlock textBlock, LanguageFont languageFont)
00031         {
00032             FontFamily fontFamily = new FontFamily(languageFont.FontFamily);
00033             textBlock.FontFamily = fontFamily;
00034             textBlock.FontWeight = languageFont.FontWeight;
00035             textBlock.FontStyle = languageFont.FontStyle;
00036             textBlock.FontStretch = languageFont.FontStretch;
00037         }
00038     }
00039
00040     public class Scenario
00041     {
00042         public string Title { get; set; }
00043         public Type ClassType { get; set; }
00044     }
00045 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario15_ServerCertificateValidation.h Source File

  • HttpClient
  • cppwinrt

Scenario15_ServerCertificateValidation.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario15_ServerCertificateValidation.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario15_ServerCertificateValidation : Scenario15_ServerCertificateValidationT<Scenario15_ServerCertificateValidation>
00020     {
00021         Scenario15_ServerCertificateValidation();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025
00026         fire_and_forget Start_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         void Cancel_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void DefaultOSValidation_Checked(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029         void DefaultAndCustomValidation_Checked(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00030         void IgnoreErrorsAndCustomValidation_Checked(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00031
00032     private:
00033         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00034         Windows::Web::Http::Filters::HttpBaseProtocolFilter filter{ nullptr };
00035         Windows::Web::Http::HttpClient httpClient{ nullptr };
00036         Windows::Foundation::IAsyncAction pendingAction{ nullptr };
00037
00038         Windows::Foundation::IAsyncAction CancelableRequestAsync(Windows::Web::Http::HttpRequestMessage request);
00039         fire_and_forget MyCustomServerCertificateValidator(
00040             Windows::Web::Http::Filters::HttpBaseProtocolFilter const& sender,
00041             Windows::Web::Http::Filters::HttpServerCustomValidationRequestedEventArgs args);
00042         Windows::Foundation::IAsyncOperation<bool> IsCertificateValidAsync(Windows::Security::Cryptography::Certificates::Certificate serverCert);
00043     };
00044 }
00045
00046 namespace winrt::SDKTemplate::factory_implementation
00047 {
00048     struct Scenario15_ServerCertificateValidation : Scenario15_ServerCertificateValidationT<Scenario15_ServerCertificateValidation, implementation::Scenario15_ServerCertificateValidation>
00049     {
00050     };
00051 }
Generated on Fri Nov 15 2024 22:19:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cppwinrt/Scenario1_PinTile.h Source File

  • SecondaryTiles
  • cppwinrt

Scenario1_PinTile.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_PinTile.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1_PinTile : Scenario1_PinTileT<Scenario1_PinTile>
00020     {
00021         Scenario1_PinTile();
00022
00023         fire_and_forget PinButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024
00025     private:
00026         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario1_PinTile : Scenario1_PinTileT<Scenario1_PinTile, implementation::Scenario1_PinTile>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:21:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7 Member List

This is the complete list of members for Scenario7, including all inherited members.
AddToListButton_Click(object sender, RoutedEventArgs e) | Scenario7 | [inline, private]
ArePointsNear(Point point1, Point point2, double threshold) | Scenario7 | [inline, private]
BindMediaPlayerToUIElement(MediaPlayer mediaPlayer, UIElement uiElement) | Scenario7 | [inline, private]
BuildClustersForZoomLevel(int zoomLevel) | Scenario7 | [inline, private]
CalculateCenter(IList< PlaceInfo > places) | Scenario7 | [inline, private]
clustersForZoomLevel | Scenario7 | [private]
defaultContextForCurrentView | Scenario7 | [private]
FA_E_MAX_PERSISTED_ITEMS_REACHED | Scenario7 | [private]
GetClustersForZoomLevel(int zoomLevel) | Scenario7 | [inline, private]
InkToolbar_IsStencilButtonCheckedChanged(InkToolbar sender, InkToolbarIsStencilButtonCheckedChangedEventArgs args) | Scenario7 | [inline, private]
LoadPlaceInfoAsync() | Scenario7 | [inline, private]
mediaPlayer | Scenario7 | [private]
mediaPlayerButton_Click(object sender, RoutedEventArgs e) | Scenario7 | [inline, private]
myMap_Loaded(object sender, RoutedEventArgs e) | Scenario7 | [inline, private]
myMap_ZoomLevelChanged(MapControl sender, object args) | Scenario7 | [inline, private]
numberIconReferences | Scenario7 | [private]
OnBringIntoView(object sender, RoutedEventArgs e) | Scenario7 | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario7 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario7 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario7 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario7 | [inline, protected]
OpenFromListButton_Click(object sender, RoutedEventArgs e) | Scenario7 | [inline, private]
pickFileButton_Click(object sender, RoutedEventArgs e) | Scenario7 | [inline, private]
places | Scenario7 | [private]
previousZoomLevel | Scenario7 | [private]
refreshMapIcons() | Scenario7 | [inline, private]
rootPage | Scenario7 | [private]
Scenario7() | Scenario7 | [inline]
Scenario7() | Scenario7 | [inline]
Scenario7() | Scenario7 | [inline]
Scenario7() | Scenario7 | [inline]
Scenario7() | Scenario7 | [inline]
Scenario7Button_Show_Click(object sender, RoutedEventArgs e) | Scenario7 | [inline, private]
Scenario8_Loaded(object sender, RoutedEventArgs e) | Scenario7 | [inline, private]
ShowListButton_Click(object sender, RoutedEventArgs e) | Scenario7 | [inline, private]
Generated on Fri Nov 15 2024 22:23:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DGradientMesh/cpp/D2DGradientMeshMain.cpp Source File

  • D2DGradientMesh
  • cpp

D2DGradientMeshMain.cpp

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "D2DGradientMeshMain.h"
00010
00011 #include <DirectXColors.h>
00012 #include "DirectXHelper.h"
00013
00014 using namespace D2DGradientMesh;
00015
00016 // Loads and initializes application assets when the application is loaded.
00017 D2DGradientMeshMain::D2DGradientMeshMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00018     m_deviceResources(deviceResources)
00019 {
00020     // Register to be notified if the Device is lost or recreated.
00021     m_deviceResources->RegisterDeviceNotify(this);
00022
00023     m_sceneRenderer = std::unique_ptr<D2DGradientMeshRenderer>(new D2DGradientMeshRenderer(m_deviceResources));
00024     m_sampleOverlay = std::unique_ptr<SampleOverlay>(new SampleOverlay(m_deviceResources, L"Direct2D Gradient Mesh Sample"));
00025 }
00026
00027 D2DGradientMeshMain::~D2DGradientMeshMain()
00028 {
00029     // Deregister device notification.
00030     m_deviceResources->RegisterDeviceNotify(nullptr);
00031 }
00032
00033 // Updates application state when the window size changes (e.g. device orientation change)
00034 void D2DGradientMeshMain::UpdateForWindowSizeChange()
00035 {
00036     m_sceneRenderer->CreateWindowSizeDependentResources();
00037     m_sampleOverlay->CreateWindowSizeDependentResources();
00038 }
00039
00040 // Renders the current frame according to the current application state.
00041 // Returns true if the frame was rendered and is ready to be displayed.
00042 bool D2DGradientMeshMain::Render()
00043 {
00044     // Render the scene objects.
00045     m_sceneRenderer->Render();
00046     m_sampleOverlay->Render();
00047
00048     return true;
00049 }
00050
00051 // Notifies renderers that device resources need to be released.
00052 void D2DGradientMeshMain::OnDeviceLost()
00053 {
00054     m_sceneRenderer->ReleaseDeviceDependentResources();
00055     m_sampleOverlay->ReleaseDeviceDependentResources();
00056 }
00057
00058 // Notifies renderers that device resources may now be re-created.
00059 void D2DGradientMeshMain::OnDeviceRestored()
00060 {
00061     m_sceneRenderer->CreateDeviceDependentResources();
00062     m_sampleOverlay->CreateDeviceDependentResources();
00063     UpdateForWindowSizeChange();
00064 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisplayOrientation/cpp/Scenario1_Orientation.xaml.cpp Source File

  • DisplayOrientation
  • cpp

Scenario1_Orientation.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_Orientation.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::Graphics::Display;
00020 using namespace Windows::UI::Core;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Input;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 Scenario1_Orientation::Scenario1_Orientation()
00027 {
00028     InitializeComponent();
00029 }
00030
00031 void Scenario1_Orientation::OnNavigatedTo(NavigationEventArgs^ e)
00032 {
00033     displayInfo = DisplayInformation::GetForCurrentView();
00034     orientationChangedToken = displayInfo->OrientationChanged += ref new TypedEventHandler<DisplayInformation^, Object^>(this, &Scenario1_Orientation::OnOrientationChanged);
00035     UpdateContent();
00036 }
00037
00038 void Scenario1_Orientation::OnNavigatedFrom(NavigationEventArgs^ e)
00039 {
00040     displayInfo->OrientationChanged -= orientationChangedToken;
00041 }
00042
00043 void Scenario1_Orientation::OnOrientationChanged(DisplayInformation^ sender, Object^ e)
00044 {
00045     UpdateContent();
00046 }
00047
00048 String^ Scenario1_Orientation::OrientationsToString(DisplayOrientations orientations)
00049 {
00050     std::wstring result = L"None";
00051
00052     if ((orientations & DisplayOrientations::Landscape) == DisplayOrientations::Landscape)
00053     {
00054         result += L", Landscape";
00055     }
00056     if ((orientations & DisplayOrientations::Portrait) == DisplayOrientations::Portrait)
00057     {
00058         result += L", Portrait";
00059     }
00060     if ((orientations & DisplayOrientations::LandscapeFlipped) == DisplayOrientations::LandscapeFlipped)
00061     {
00062         result += L", LandscapeFlipped";
00063     }
00064     if ((orientations & DisplayOrientations::PortraitFlipped) == DisplayOrientations::PortraitFlipped)
00065     {
00066         result += L", PortraitFlipped";
00067     }
00068     if (result != L"None")
00069     {
00070         result = result.substr(6);
00071     }
00072     return ref new String(result.c_str());
00073 }
00074
00075 void Scenario1_Orientation::UpdateContent()
00076 {
00077     NativeOrientationTextBlock->Text = OrientationsToString(displayInfo->NativeOrientation);
00078     CurrentOrientationTextBlock->Text = OrientationsToString(displayInfo->CurrentOrientation);
00079     AutoRotationPreferencesTextBlock->Text = OrientationsToString(DisplayInformation::AutoRotationPreferences);
00080 }
00081
00082 void Scenario1_Orientation::ApplyRotationLock_Click(Object^ sender, RoutedEventArgs^ e)
00083 {
00084     DisplayOrientations orientations = DisplayOrientations::None;
00085
00086     if (PreferLandscape->IsChecked->Value)
00087     {
00088         orientations = orientations | DisplayOrientations::Landscape;
00089     }
00090     if (PreferPortrait->IsChecked->Value)
00091     {
00092         orientations = orientations | DisplayOrientations::Portrait;
00093     }
00094     if (PreferLandscapeFlipped->IsChecked->Value)
00095     {
00096         orientations = orientations | DisplayOrientations::LandscapeFlipped;
00097     }
00098     if (PreferPortraitFlipped->IsChecked->Value)
00099     {
00100         orientations = orientations | DisplayOrientations::PortraitFlipped;
00101     }
00102     DisplayInformation::AutoRotationPreferences = orientations;
00103     UpdateContent();
00104 }
Generated on Fri Nov 15 2024 22:19:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

TripDetails Member List

This is the complete list of members for TripDetails, including all inherited members.
defaultViewModel | TripDetails | [private]
DefaultViewModel | TripDetails |
Footer_Click(object sender, RoutedEventArgs e) | TripDetails | [inline, private]
NavigationHelper | TripDetails |
navigationHelper | TripDetails | [private]
navigationHelper_LoadState(object sender, LoadStateEventArgs e) | TripDetails | [inline, private]
navigationHelper_SaveState(object sender, SaveStateEventArgs e) | TripDetails | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | TripDetails | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | TripDetails | [inline, protected]
TripDetails() | TripDetails | [inline]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PasswordVault/cppwinrt/pch.cpp Source File

  • PasswordVault
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Osrusbfx2Task/ConnectedTask.cs Source File

  • CustomCapability
  • Service
  • Osrusbfx2Task

ConnectedTask.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.ApplicationModel.Background;
00013 using Windows.Data.Xml.Dom;
00014 using Windows.UI.Notifications;
00015
00016 namespace Osrusbfx2Task
00017 {
00018     public sealed class ConnectedTask : IBackgroundTask
00019     {
00020         public void Run(IBackgroundTaskInstance taskInstance)
00021         {
00022             string xml = $@"<toast activationType='foreground'>
00023                               <visual>
00024                                 <binding template='ToastGeneric'>
00025                                   <text>CustomCapability Sample</text>
00026                                   <text>Osrfx2usb device connected.</text>
00027                                 </binding>
00028                               </visual>
00029                             </toast>";
00030
00031             XmlDocument doc = new XmlDocument();
00032             doc.LoadXml(xml);
00033
00034             var toast = new ToastNotification(doc);
00035             ToastNotificationManager.CreateToastNotifier().Show(toast);
00036         }
00037     }
00038 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cs/SampleConfiguration.cs Source File

  • WiFiDirectServices
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using SDKTemplate.WiFiDirectServices;
00017
00018 namespace SDKTemplate
00019 {
00020     public partial class MainPage : Page
00021     {
00022         public const string FEATURE_NAME = "Wi-Fi Direct Services";
00023
00024         List<Scenario> scenarios = new List<Scenario>
00025         {
00026             new Scenario() { Title="Create Advertiser", ClassType=typeof(Scenario1)},
00027             new Scenario() { Title="Advertiser Accept", ClassType=typeof(Scenario2)},
00028             new Scenario() { Title="Discover/Connect Services", ClassType=typeof(Scenario3)},
00029             new Scenario() { Title="Select Session (Seeker)", ClassType=typeof(Scenario4)},
00030             new Scenario() { Title="Send Data", ClassType=typeof(Scenario5)}
00031         };
00032
00033         public void GoToScenario(int index)
00034         {
00035             if (index >= scenarios.Count)
00036             {
00037                 throw new IndexOutOfRangeException();
00038             }
00039
00040             ScenarioControl.SelectedIndex = index;
00041         }
00042     }
00043
00044     public class Scenario
00045     {
00046         public string Title { get; set; }
00047         public Type ClassType { get; set; }
00048     }
00049 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleImaging/cs/Scenario2.xaml.cs Source File

  • SimpleImaging
  • cs

Scenario2.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Threading.Tasks;
00015 using Windows.ApplicationModel;
00016 using Windows.Foundation.Collections;
00017 using Windows.Graphics.Imaging;
00018 using Windows.Storage;
00019 using Windows.Storage.AccessCache;
00020 using Windows.Storage.FileProperties;
00021 using Windows.Storage.Pickers;
00022 using Windows.Storage.Streams;
00023 using Windows.UI.Xaml;
00024 using Windows.UI.Xaml.Automation;
00025 using Windows.UI.Xaml.Controls;
00026 using Windows.UI.Xaml.Media;
00027 using Windows.UI.Xaml.Media.Imaging;
00028 using Windows.UI.Xaml.Navigation;
00029
00030 namespace SimpleImaging
00031 {
00032     /// <summary>
00033     /// Code-behind for Scenario 2, which demonstrates image editing using BitmapDecoder and BitmapEncoder.
00034     /// </summary>
00035     public sealed partial class Scenario2 : Page
00036     {
00037         // Exception HResult constants. These constants are defined using values from winerror.h.
00038         // This file format does not support the requested operation; for example, metadata or thumbnails.
00039         const int WINCODEC_ERR_UNSUPPORTEDOPERATION = unchecked((int)0x88982F81);
00040         // This file format does not support the requested property/metadata query.
00041         const int WINCODEC_ERR_PROPERTYNOTSUPPORTED = unchecked((int)0x88982F41);
00042         // There is no codec or component that can handle the requested operation; for example, encoding.
00043         const int WINCODEC_ERR_COMPONENTNOTFOUND = unchecked((int)0x88982F50);
00044
00045         StorageItemAccessList m_futureAccess = StorageApplicationPermissions.FutureAccessList;
00046         IPropertySet m_localSettings = Windows.Storage.ApplicationData.Current.LocalSettings.Values;
00047         RotateTransform m_transform = new RotateTransform();
00048         string m_fileToken;
00049         uint m_displayWidthNonScaled;
00050         uint m_displayHeightNonScaled;
00051         double m_scaleFactor;
00052         PhotoOrientation m_userRotation;
00053         PhotoOrientation m_exifOrientation;
00054         bool m_disableExifOrientation;
00055         private MainPage rootPage;
00056
00057         public Scenario2()
00058         {
00059             this.InitializeComponent();
00060         }
00061
00062         /// <summary>
00063         /// Invoked when this page is about to be displayed in a Frame.
00064         /// </summary>
00065         protected override void OnNavigatedTo(NavigationEventArgs e)
00066         {
00067             rootPage = MainPage.Current;
00068             App.Current.Suspending += new SuspendingEventHandler(SaveDataToPersistedState);
00069
00070             // Reset scenario state before starting.
00071             ResetSessionState();
00072
00073             // Attempt to load the previously saved scenario state.
00074             if (m_localSettings.ContainsKey("scenario2FileToken"))
00075             {
00076                 RestoreDataFromPersistedState();
00077             }
00078         }
00079
00080         /// <summary>
00081         /// When the application is about to enter a suspended state, save the user edited properties text.
00082         /// This method does not use the SuspensionManager helper class (defined in SuspensionManager.cs).
00083         /// </summary>
00084         private void SaveDataToPersistedState(object sender, SuspendingEventArgs args)
00085         {
00086             // Only save state if we have valid data.
00087             if (m_fileToken != null)
00088             {
00089                 // Requesting a deferral prevents the application from being immediately suspended.
00090                 SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();
00091
00092                 // LocalSettings does not support overwriting existing items, so first clear the collection.
00093                 ResetPersistedState();
00094
00095                 m_localSettings.Add("scenario2FileToken", m_fileToken);
00096                 m_localSettings.Add("scenario2Width", m_displayWidthNonScaled);
00097                 m_localSettings.Add("scenario2Height", m_displayHeightNonScaled);
00098                 m_localSettings.Add("scenario2Scale", m_scaleFactor);
00099                 m_localSettings.Add("scenario2UserRotation",
00100                     Helpers.ConvertToExifOrientationFlag(m_userRotation)
00101                     );
00102
00103                 m_localSettings.Add("scenario2ExifOrientation",
00104                     Helpers.ConvertToExifOrientationFlag(m_exifOrientation)
00105                     );
00106
00107                 m_localSettings.Add("scenario2DisableExif", m_disableExifOrientation);
00108
00109                 deferral.Complete();
00110             }
00111         }
00112
00113         /// <summary>
00114         /// Reads the file token and image transform variables from the persisted state and
00115         /// restores the UI.
00116         /// </summary>
00117         private async void RestoreDataFromPersistedState()
00118         {
00119             try
00120             {
00121                 rootPage.NotifyUser("Loading image file from persisted state...", NotifyType.StatusMessage);
00122
00123                 m_fileToken = (string)m_localSettings["scenario2FileToken"];
00124                 m_displayWidthNonScaled = (uint)m_localSettings["scenario2Width"];
00125                 m_displayHeightNonScaled = (uint)m_localSettings["scenario2Height"];
00126                 m_scaleFactor = (double)m_localSettings["scenario2Scale"];
00127
00128                 PhotoOrientation desiredOrientation =
00129                     Helpers.ConvertToPhotoOrientation((ushort)m_localSettings["scenario2UserRotation"]);
00130
00131                 m_exifOrientation =
00132                     Helpers.ConvertToPhotoOrientation((ushort)m_localSettings["scenario2ExifOrientation"]);
00133
00134                 m_disableExifOrientation = (bool)m_localSettings["scenario2DisableExif"];
00135
00136                 // Display the image in the UI.
00137                 StorageFile file = await m_futureAccess.GetFileAsync(m_fileToken);
00138                 BitmapImage src = new BitmapImage();
00139
00140                 using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
00141                 {
00142                     await src.SetSourceAsync(stream);
00143                 }
00144                 PreviewImage.Source = src;
00145                 AutomationProperties.SetName(PreviewImage, file.Name);
00146
00147                 // Display the image dimensions and transformation state in the UI.
00148                 ExifOrientationTextblock.Text = Helpers.GetOrientationString(m_exifOrientation);
00149                 ScaleSlider.Value = m_scaleFactor * 100;
00150                 UpdateImageDimensionsUI();
00151
00152                 // Restore the image tag's rotation transform.
00153                 while (desiredOrientation != m_userRotation)
00154                 {
00155                     RotateRight_Click(null, null);
00156                 }
00157
00158                 RotateRightButton.IsEnabled = true;
00159                 RotateLeftButton.IsEnabled = true;
00160                 SaveButton.IsEnabled = true;
00161                 CloseButton.IsEnabled = true;
00162                 SaveAsButton.IsEnabled = true;
00163                 ScaleSlider.IsEnabled = true;
00164                 rootPage.NotifyUser("Loaded image file from persisted state: " + file.Name, NotifyType.StatusMessage);
00165             }
00166             catch (Exception err)
00167             {
00168                 rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage);
00169                 ResetSessionState();
00170                 ResetPersistedState();
00171             }
00172         }
00173
00174         /// <summary>
00175         /// Load an image from disk and display properties.
00176         /// Invoked when the user clicks on the Open button.
00177         /// </summary>
00178         private async void Open_Click(object sender, RoutedEventArgs e)
00179         {
00180             ResetPersistedState();
00181             ResetSessionState();
00182
00183             FileOpenPicker picker = new FileOpenPicker();
00184             Helpers.FillDecoderExtensions(picker.FileTypeFilter);
00185             picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
00186
00187             var file = await picker.PickSingleFileAsync();
00188             if (file != null)
00189             {
00190                 await LoadFileAsync(file);
00191             }
00192         }
00193
00194         /// <summary>
00195         /// Load an image from a file and display some basic imaging properties.
00196         /// </summary>
00197         /// <param name="file">The image to load.</param>
00198         private async Task LoadFileAsync(StorageFile file)
00199         {
00200             try
00201             {
00202                 await DisplayImageFileAsync(file);
00203                 rootPage.NotifyUser("Loaded file from picker: " + file.Name, NotifyType.StatusMessage);
00204             }
00205             catch (Exception err)
00206             {
00207                 rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage);
00208                 ResetSessionState();
00209                 ResetPersistedState();
00210             }
00211         }
00212
00213         /// <summary>
00214         /// This function is called when the user clicks the Open button,
00215         /// and when they save (to refresh the image state).
00216         /// </summary>
00217         private async Task DisplayImageFileAsync(StorageFile file)
00218         {
00219             // Request persisted access permissions to the file the user selected.
00220             // This allows the app to directly load the file in the future without relying on a
00221             // broker such as the file picker.
00222             m_fileToken = m_futureAccess.Add(file);
00223
00224             // Display the image in the UI.
00225             BitmapImage src = new BitmapImage();
00226             using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
00227             {
00228                 await src.SetSourceAsync(stream);
00229             }
00230
00231             PreviewImage.Source = src;
00232             AutomationProperties.SetName(PreviewImage, file.Name);
00233
00234             // Use BitmapDecoder to attempt to read EXIF orientation and image dimensions.
00235             await GetImageInformationAsync(file);
00236
00237             ExifOrientationTextblock.Text = Helpers.GetOrientationString(m_exifOrientation);
00238             UpdateImageDimensionsUI();
00239
00240             ScaleSlider.IsEnabled = true;
00241             RotateLeftButton.IsEnabled = true;
00242             RotateRightButton.IsEnabled = true;
00243             SaveButton.IsEnabled = true;
00244             SaveAsButton.IsEnabled = true;
00245             CloseButton.IsEnabled = true;
00246         }
00247
00248         /// <summary>
00249         /// Asynchronously attempts to get the oriented dimensions and EXIF orientation from the image file.
00250         /// Sets member variables instead of returning a value with the Task.
00251         /// </summary>
00252         /// <param name="file"></param>
00253         /// <returns></returns>
00254         private async Task GetImageInformationAsync(StorageFile file)
00255         {
00256             using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
00257             {
00258                 BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
00259
00260                 // The orientedPixelWidth and Height members provide the image dimensions
00261                 // reflecting any EXIF orientation.
00262                 m_displayHeightNonScaled = decoder.OrientedPixelHeight;
00263                 m_displayWidthNonScaled = decoder.OrientedPixelWidth;
00264
00265                 try
00266                 {
00267                     // Property access using BitmapProperties is similar to using
00268                     // Windows.Storage.FileProperties (see Scenario 1); BitmapProperties accepts
00269                     // property keys such as "System.Photo.Orientation".
00270                     // The EXIF orientation flag can be also be read using native metadata queries
00271                     // such as "/app1/ifd/{ushort=274}" (JPEG) or "/ifd/{ushort=274}" (TIFF).
00272                     string[] requestedProperties = { "System.Photo.Orientation" };
00273                     BitmapPropertySet retrievedProperties =
00274                         await decoder.BitmapProperties.GetPropertiesAsync(requestedProperties);
00275
00276                     // Check to see if the property exists in the file.
00277                     if (retrievedProperties.ContainsKey("System.Photo.Orientation"))
00278                     {
00279                         // EXIF orientation ("System.Photo.Orientation") is stored as a 16-bit unsigned integer.
00280                         m_exifOrientation = Helpers.ConvertToPhotoOrientation(
00281                             (ushort)retrievedProperties["System.Photo.Orientation"].Value
00282                             );
00283                     }
00284                 }
00285                 catch (Exception err)
00286                 {
00287                     switch (err.HResult)
00288                     {
00289                         // If the file format does not support properties continue without applying EXIF orientation.
00290                         case WINCODEC_ERR_UNSUPPORTEDOPERATION:
00291                         case WINCODEC_ERR_PROPERTYNOTSUPPORTED:
00292                             m_disableExifOrientation = true;
00293                             break;
00294                         default:
00295                             throw;
00296                     }
00297                 }
00298             }
00299         }
00300
00301         /// <summary>
00302         /// When the user clicks Rotate Right, rotate the ImageViewbox by 90 degrees clockwise,
00303         /// and update the dimensions.
00304         /// </summary>
00305         private void RotateRight_Click(object sender, RoutedEventArgs e)
00306         {
00307             m_userRotation = Helpers.Add90DegreesCW(m_userRotation);
00308
00309             // Swap width and height.
00310             uint temp = m_displayHeightNonScaled;
00311             m_displayHeightNonScaled = m_displayWidthNonScaled;
00312             m_displayWidthNonScaled = temp;
00313
00314             UpdateImageDimensionsUI();
00315             UpdateImageRotation(m_userRotation);
00316         }
00317
00318         /// <summary>
00319         /// When the user clicks Rotate Left, rotate the ImageViewbox by 90 degrees counterclockwise,
00320         /// and update the dimensions.
00321         /// </summary>
00322         private void RotateLeft_Click(object sender, RoutedEventArgs e)
00323         {
00324             m_userRotation = Helpers.Add90DegreesCCW(m_userRotation);
00325
00326             // Swap width and height.
00327             uint temp = m_displayHeightNonScaled;
00328             m_displayHeightNonScaled = m_displayWidthNonScaled;
00329             m_displayWidthNonScaled = temp;
00330
00331             UpdateImageDimensionsUI();
00332             UpdateImageRotation(m_userRotation);
00333         }
00334
00335         /// <summary>
00336         /// Applies the user-provided scale and rotation operation to the original image file.
00337         /// The "Transcoding" mode is used which preserves image metadata and performs other
00338         /// optimizations when possible.
00339         ///
00340         /// This method attempts to perform "soft" rotation using the EXIF orientation flag when possible,
00341         /// but falls back to a hard rotation of the image pixels.
00342         /// </summary>
00343         private async void Save_Click(object sender, RoutedEventArgs e)
00344         {
00345             try
00346             {
00347                 rootPage.NotifyUser("Saving file...", NotifyType.StatusMessage);
00348
00349                 // Create a new encoder and initialize it with data from the original file.
00350                 // The encoder writes to an in-memory stream, we then copy the contents to the file.
00351                 // This allows the application to perform in-place editing of the file: any unedited data
00352                 // is copied to the destination, and the original file is overwritten
00353                 // with updated data.
00354                 StorageFile file = await m_futureAccess.GetFileAsync(m_fileToken);
00355                 using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite),
00356                                            memStream = new InMemoryRandomAccessStream())
00357                 {
00358                     BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
00359
00360                     // Use the native (no orientation applied) image dimensions because we want to handle
00361                     // orientation ourselves.
00362                     uint originalWidth = decoder.PixelWidth;
00363                     uint originalHeight = decoder.PixelHeight;
00364
00365                     // Set the encoder's destination to the temporary, in-memory stream.
00366                     BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memStream, decoder);
00367
00368                     // Scaling occurs before flip/rotation, therefore use the original dimensions
00369                     // (no orientation applied) as parameters for scaling.
00370                     // Dimensions are rounded down by BitmapEncoder to the nearest integer.
00371                     if (m_scaleFactor != 1.0)
00372                     {
00373                         encoder.BitmapTransform.ScaledWidth = (uint)(originalWidth * m_scaleFactor);
00374                         encoder.BitmapTransform.ScaledHeight = (uint)(originalHeight * m_scaleFactor);
00375
00376                         // Fant is a relatively high quality interpolation mode.
00377                         encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
00378                     }
00379
00380                     // If the file format supports EXIF orientation ("System.Photo.Orientation") then
00381                     // update the orientation flag to reflect any user-specified rotation.
00382                     // Otherwise, perform a hard rotate using BitmapTransform.
00383                     if (m_disableExifOrientation == false)
00384                     {
00385                         BitmapPropertySet properties = new BitmapPropertySet();
00386                         ushort netExifOrientation = Helpers.ConvertToExifOrientationFlag(
00387                             Helpers.AddPhotoOrientation(m_userRotation, m_exifOrientation)
00388                             );
00389
00390                         // BitmapProperties requires the application to explicitly declare the type
00391                         // of the property to be written - this is different from FileProperties which
00392                         // automatically coerces the value to the correct type. System.Photo.Orientation
00393                         // is defined as an unsigned 16 bit integer.
00394                         BitmapTypedValue orientationTypedValue = new BitmapTypedValue(
00395                             netExifOrientation,
00396                             Windows.Foundation.PropertyType.UInt16
00397                             );
00398
00399                         properties.Add("System.Photo.Orientation", orientationTypedValue);
00400                         await encoder.BitmapProperties.SetPropertiesAsync(properties);
00401                     }
00402                     else
00403                     {
00404                         encoder.BitmapTransform.Rotation = Helpers.ConvertToBitmapRotation(m_userRotation);
00405                     }
00406
00407                     // Attempt to generate a new thumbnail to reflect any rotation operation.
00408                     encoder.IsThumbnailGenerated = true;
00409
00410                     try
00411                     {
00412                         await encoder.FlushAsync();
00413                     }
00414                     catch (Exception err)
00415                     {
00416                         switch (err.HResult)
00417                         {
00418                             case WINCODEC_ERR_UNSUPPORTEDOPERATION:
00419                                 // If the encoder does not support writing a thumbnail, then try again
00420                                 // but disable thumbnail generation.
00421                                 encoder.IsThumbnailGenerated = false;
00422                                 break;
00423                             default:
00424                                 throw;
00425                         }
00426                     }
00427
00428                     if (encoder.IsThumbnailGenerated == false)
00429                     {
00430                         await encoder.FlushAsync();
00431                     }
00432
00433                     // Now that the file has been written to the temporary stream, copy the data to the file.
00434                     memStream.Seek(0);
00435                     fileStream.Seek(0);
00436                     fileStream.Size = 0;
00437                     await RandomAccessStream.CopyAsync(memStream, fileStream);
00438                 }
00439
00440                 // Because the original file has been overwritten, reload it in the UI.
00441                 ResetSessionState();
00442                 await DisplayImageFileAsync(file);
00443
00444                 rootPage.NotifyUser("Successfully saved file: " + file.Name, NotifyType.StatusMessage);
00445             }
00446             catch (Exception err)
00447             {
00448                 if (err.HResult == WINCODEC_ERR_COMPONENTNOTFOUND)
00449                 {
00450                     // Some image formats (e.g. ICO) do not have encoders.
00451                     rootPage.NotifyUser("Error: this file format may not support editing.", NotifyType.ErrorMessage);
00452                 }
00453                 else
00454                 {
00455                     rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage);
00456                 }
00457
00458                 ResetPersistedState();
00459                 ResetSessionState();
00460             }
00461         }
00462
00463         /// <summary>
00464         /// Applies the user-provided scale and rotation operation to a new image file picked by the user.
00465         /// This method writes the edited pixel data to the new file without
00466         /// any regard to existing metadata or other information in the original file.
00467         /// </summary>
00468         private async void SaveAs_Click(object sender, RoutedEventArgs e)
00469         {
00470             FileSavePicker picker = new FileSavePicker();
00471             picker.FileTypeChoices.Add("JPEG image", new string[] { ".jpg" });
00472             picker.FileTypeChoices.Add("PNG image", new string[] { ".png" });
00473             picker.FileTypeChoices.Add("BMP image", new string[] { ".bmp" });
00474             picker.DefaultFileExtension = ".png";
00475             picker.SuggestedFileName = "Output file";
00476             picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
00477
00478             var file = await picker.PickSaveFileAsync();
00479             if (file != null)
00480             {
00481                 await LoadSaveFileAsync(file);
00482             }
00483         }
00484
00485         private async Task LoadSaveFileAsync(StorageFile outputFile)
00486         {
00487             try
00488             {
00489                 StorageFile inputFile = await m_futureAccess.GetFileAsync(m_fileToken);
00490                 Guid encoderId;
00491
00492                 switch (outputFile.FileType)
00493                 {
00494                     case ".png":
00495                         encoderId = BitmapEncoder.PngEncoderId;
00496                         break;
00497                     case ".bmp":
00498                         encoderId = BitmapEncoder.BmpEncoderId;
00499                         break;
00500                     case ".jpg":
00501                     default:
00502                         encoderId = BitmapEncoder.JpegEncoderId;
00503                         break;
00504                 }
00505
00506                 using (IRandomAccessStream inputStream = await inputFile.OpenAsync(FileAccessMode.Read),
00507                            outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
00508                 {
00509                     // BitmapEncoder expects an empty output stream; the user may have selected a
00510                     // pre-existing file.
00511                     outputStream.Size = 0;
00512
00513                     // Get pixel data from the decoder. We apply the user-requested transforms on the
00514                     // decoded pixels to take advantage of potential optimizations in the decoder.
00515                     BitmapDecoder decoder = await BitmapDecoder.CreateAsync(inputStream);
00516                     BitmapTransform transform = new BitmapTransform();
00517
00518                     // Scaling occurs before flip/rotation, therefore use the original dimensions
00519                     // (no orientation applied) as parameters for scaling.
00520                     transform.ScaledHeight = (uint)(decoder.PixelHeight * m_scaleFactor);
00521                     transform.ScaledWidth = (uint)(decoder.PixelWidth * m_scaleFactor);
00522                     transform.Rotation = Helpers.ConvertToBitmapRotation(m_userRotation);
00523
00524                     // Fant is a relatively high quality interpolation mode.
00525                     transform.InterpolationMode = BitmapInterpolationMode.Fant;
00526
00527                     // The BitmapDecoder indicates what pixel format and alpha mode best match the
00528                     // natively stored image data. This can provide a performance and/or quality gain.
00529                     BitmapPixelFormat format = decoder.BitmapPixelFormat;
00530                     BitmapAlphaMode alpha = decoder.BitmapAlphaMode;
00531
00532                     PixelDataProvider pixelProvider = await decoder.GetPixelDataAsync(
00533                         format,
00534                         alpha,
00535                         transform,
00536                         ExifOrientationMode.RespectExifOrientation,
00537                         ColorManagementMode.ColorManageToSRgb
00538                         );
00539
00540                     byte[] pixels = pixelProvider.DetachPixelData();
00541
00542                     // Write the pixel data onto the encoder. Note that we can't simply use the
00543                     // BitmapTransform.ScaledWidth and ScaledHeight members as the user may have
00544                     // requested a rotation (which is applied after scaling).
00545                     BitmapEncoder encoder = await BitmapEncoder.CreateAsync(encoderId, outputStream);
00546                     encoder.SetPixelData(
00547                         format,
00548                         alpha,
00549                         (uint)((double)m_displayWidthNonScaled * m_scaleFactor),
00550                         (uint)((double)m_displayHeightNonScaled * m_scaleFactor),
00551                         decoder.DpiX,
00552                         decoder.DpiY,
00553                         pixels
00554                         );
00555
00556                     await encoder.FlushAsync();
00557
00558                     rootPage.NotifyUser("Successfully saved a copy: " + outputFile.Name, NotifyType.StatusMessage);
00559                 }
00560             }
00561             catch (Exception err)
00562             {
00563                 rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage);
00564                 ResetPersistedState();
00565                 ResetSessionState();
00566             }
00567         }
00568
00569         /// <summary>
00570         /// Handles when the slider controlling image scale is changed.
00571         /// </summary>
00572         private void ScaleSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e)
00573         {
00574             // Ignore any value changed events the control is set up and we are accepting user input.
00575             if ((ScaleSlider != null) && (ScaleSlider.IsEnabled == true))
00576             {
00577                 // The slider control uses percentages (0 to 100) while m_scaleFactor is a coefficient (0 to 1).
00578                 m_scaleFactor = e.NewValue / 100;
00579                 UpdateImageDimensionsUI();
00580             }
00581         }
00582
00583         /// <summary>
00584         /// Display the image dimensions and transformation state in the UI.
00585         /// </summary>
00586         private void UpdateImageDimensionsUI()
00587         {
00588             ScaleTextblock.Text = (m_scaleFactor * 100).ToString() + "%";
00589             WidthTextblock.Text = Math.Floor(((double)m_displayWidthNonScaled * m_scaleFactor)).ToString() + " pixels";
00590             HeightTextblock.Text = Math.Floor(((double)m_displayHeightNonScaled * m_scaleFactor)).ToString() + " pixels";
00591             UserRotationTextblock.Text = Helpers.GetOrientationString(m_userRotation);
00592         }
00593
00594         /// <summary>
00595         /// Sets the RotationTransform angle of the Image (technically, its parent Viewbox).
00596         /// </summary>
00597         private void UpdateImageRotation(PhotoOrientation rotation)
00598         {
00599             switch (rotation)
00600             {
00601                 case PhotoOrientation.Rotate270:
00602                     // Note that the PhotoOrientation enumeration uses a counterclockwise convention,
00603                     // while the RotationTransform uses a clockwise convention.
00604                     m_transform.Angle = 90;
00605                     break;
00606                 case PhotoOrientation.Rotate180:
00607                     m_transform.Angle = 180;
00608                     break;
00609                 case PhotoOrientation.Rotate90:
00610                     m_transform.Angle = 270;
00611                     break;
00612                 case PhotoOrientation.Normal:
00613                 default:
00614                     m_transform.Angle = 0;
00615                     break;
00616             }
00617         }
00618
00619         /// <summary>
00620         /// Closing the file brings the scenario back to the default initialized state.
00621         /// </summary>
00622         private void Close_Click(object sender, RoutedEventArgs e)
00623         {
00624             ResetSessionState();
00625             ResetPersistedState();
00626             rootPage.NotifyUser("Closed file", NotifyType.StatusMessage);
00627         }
00628
00629         /// <summary>
00630         /// Clears all of the state for this scenario that is stored in app data.
00631         /// </summary>
00632         private void ResetPersistedState()
00633         {
00634             m_localSettings.Remove("scenario2FileToken");
00635             m_localSettings.Remove("scenario2Scale");
00636             m_localSettings.Remove("scenario2Rotation");
00637             m_localSettings.Remove("scenario2Width");
00638             m_localSettings.Remove("scenario2Height");
00639             m_localSettings.Remove("scenario2UserRotation");
00640             m_localSettings.Remove("scenario2ExifOrientation");
00641             m_localSettings.Remove("scenario2DisableExif");
00642         }
00643
00644         /// <summary>
00645         /// Clears all of the state that is stored in memory and in the UI.
00646         /// </summary>
00647         private void ResetSessionState()
00648         {
00649             m_fileToken = null;
00650             m_displayHeightNonScaled = 0;
00651             m_displayWidthNonScaled = 0;
00652             m_scaleFactor = 1;
00653             m_userRotation = PhotoOrientation.Normal;
00654             m_exifOrientation = PhotoOrientation.Normal;
00655             m_disableExifOrientation = false;
00656
00657             RotateLeftButton.IsEnabled = false;
00658             RotateRightButton.IsEnabled = false;
00659             SaveButton.IsEnabled = false;
00660             SaveAsButton.IsEnabled = false;
00661             CloseButton.IsEnabled = false;
00662
00663             PreviewImage.Source = null;
00664             m_transform.CenterX = ImageViewbox.Width / 2;
00665             m_transform.CenterY = ImageViewbox.Height / 2;
00666             ImageViewbox.RenderTransform = m_transform;
00667             UpdateImageRotation(PhotoOrientation.Normal);
00668
00669             ScaleTextblock.Text = "";
00670             ScaleSlider.Value = 100;
00671             ScaleSlider.IsEnabled = false;
00672             HeightTextblock.Text = "";
00673             WidthTextblock.Text = "";
00674             UserRotationTextblock.Text = "";
00675             ExifOrientationTextblock.Text = "";
00676         }
00677     }
00678 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MemDelete Member List

This is the complete list of members for MemDelete, including all inherited members.
operator()(void *p) MemDelete [inline]
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlContextMenu/cpp/Scenario1.xaml.cpp Source File

  • XamlContextMenu
  • cpp

Scenario1.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Core;
00020 using namespace Windows::UI::ViewManagement;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Input;
00024
00025 Scenario1::Scenario1()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 void Scenario1::OpenMenuItem_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00031 {
00032     rootPage->NotifyUser("Action: Open", NotifyType::StatusMessage);
00033 }
00034
00035 void Scenario1::PrintMenuItem_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00036 {
00037     rootPage->NotifyUser("Action: Print", NotifyType::StatusMessage);
00038 }
00039
00040 void Scenario1::DeleteMenuItem_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00041 {
00042     rootPage->NotifyUser("Action: Delete", NotifyType::StatusMessage);
00043 }
Generated on Fri Nov 15 2024 22:17:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cs/cpp/Scenario1_OvenClient.xaml.h Source File

  • ProxyStubsForWinRTComponents
  • cs
  • cpp

Scenario1_OvenClient.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008 #include "Scenario1_OvenClient.g.h"
00009
00010 namespace SDKSample
00011 {
00012     namespace ProxyStubsForWinRTComponents
00013     {
00014         public ref class OvenClient sealed
00015         {
00016         public:
00017             OvenClient();
00018
00019         private:
00020             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021             void BreadCompletedHandler1(Microsoft::SDKSamples::Kitchen::Oven^ oven, Microsoft::SDKSamples::Kitchen::Bread^ bread);
00022             void BreadCompletedHandler2(Microsoft::SDKSamples::Kitchen::Oven^ oven, Microsoft::SDKSamples::Kitchen::Bread^ bread);
00023             void BreadCompletedHandler3(Microsoft::SDKSamples::Kitchen::Oven^ oven, Microsoft::SDKSamples::Kitchen::Bread^ bread);
00024         };
00025     }
00026 }
Generated on Fri Nov 15 2024 22:21:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

TextureData Member List

This is the complete list of members for TextureData, including all inherited members.
buffer | TextureData
bytesPerPixel | TextureData
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: EnterpriseDataProtection/cs/Scenario8_ClipboardSource.xaml.cs Source File

  • EnterpriseDataProtection
  • cs

Scenario8_ClipboardSource.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using SDKTemplate;
00017 using Windows.Security.EnterpriseData;
00018
00019 namespace EdpSample
00020 {
00021     public sealed partial class Scenario8_ClipboardSource : Page
00022     {
00023         private MainPage rootPage;
00024
00025         public Scenario8_ClipboardSource()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         protected override void OnNavigatedTo(NavigationEventArgs e)
00031         {
00032             rootPage = MainPage.Current;
00033             var protectionPolicyManager = ProtectionPolicyManager.GetForCurrentView();
00034             protectionPolicyManager.Identity = ""; // personal context
00035             InputTxtBox.Text = "Copy and paste this text to a non-enterprise app such as notepad";
00036         }
00037
00038         private void Set_ClipboardSource(object sender, RoutedEventArgs e)
00039         {
00040             var protectionPolicyManager = ProtectionPolicyManager.GetForCurrentView();
00041             protectionPolicyManager.Identity = Scenario1.m_enterpriseId;
00042             rootPage.NotifyUser("Set ProtectionPolicyManager.Identity to: " + Scenario1.m_enterpriseId, NotifyType.StatusMessage);
00043         }
00044     }
00045 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario02_GetStream.cpp Source File

  • HttpClient
  • cppwinrt

Scenario02_GetStream.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario02_GetStream.h"
00014 #include "Scenario02_GetStream.g.cpp"
00015 #include "Helpers.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::Security::Cryptography;
00020 using namespace winrt::Windows::Storage::Streams;
00021 using namespace winrt::Windows::UI::Xaml;
00022 using namespace winrt::Windows::UI::Xaml::Navigation;
00023 using namespace winrt::Windows::Web::Http;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario02_GetStream::Scenario02_GetStream()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     void Scenario02_GetStream::OnNavigatedTo(NavigationEventArgs const&)
00033     {
00034         httpClient = Helpers::CreateHttpClientWithCustomHeaders();
00035     }
00036
00037     void Scenario02_GetStream::OnNavigatedFrom(NavigationEventArgs const&)
00038     {
00039         httpClient.Close();
00040     }
00041
00042     fire_and_forget Scenario02_GetStream::Start_Click(IInspectable const&, RoutedEventArgs const&)
00043     {
00044         auto lifetime = get_strong();
00045
00046         // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00047         // valid, absolute URI, we'll notify the user about the incorrect input.
00048         Uri resourceUri = Helpers::TryParseHttpUri(AddressField().Text());
00049         if (!resourceUri)
00050         {
00051             rootPage.NotifyUser(L"Invalid URI.", NotifyType::ErrorMessage);
00052             return;
00053         }
00054
00055         Helpers::ScenarioStarted(StartButton(), CancelButton(), OutputField());
00056         rootPage.NotifyUser(L"In progress", NotifyType::StatusMessage);
00057
00058         HttpRequestMessage request(HttpMethod::Get(), resourceUri);
00059
00060         // This sample uses a "try" in order to support cancellation.
00061         // If you don't need to support cancellation, then the "try" is not needed.
00062         try
00063         {
00064             pendingAction = CancelableRequestAsync(request);
00065             co_await pendingAction;
00066         }
00067         catch (hresult_canceled const&)
00068         {
00069             rootPage.NotifyUser(L"Request canceled.", NotifyType::ErrorMessage);
00070         }
00071
00072         Helpers::ScenarioCompleted(StartButton(), CancelButton());
00073     }
00074
00075     IAsyncAction Scenario02_GetStream::CancelableRequestAsync(HttpRequestMessage request)
00076     {
00077         auto lifetime = get_strong();
00078         auto cancellation = co_await get_cancellation_token();
00079         cancellation.enable_propagation();
00080
00081         // Do not buffer the response.
00082         HttpRequestResult result = co_await httpClient.TrySendRequestAsync(request, HttpCompletionOption::ResponseHeadersRead);
00083
00084         if (result.Succeeded())
00085         {
00086             OutputField().Text(OutputField().Text() + Helpers::SerializeHeaders(result.ResponseMessage()));
00087
00088             std::wostringstream responseBody;
00089             IInputStream responseStream = co_await result.ResponseMessage().Content().ReadAsInputStreamAsync();
00090             Buffer readBuffer(1000);
00091             IBuffer resultBuffer;
00092             do
00093             {
00094                 resultBuffer = co_await responseStream.ReadAsync(readBuffer, readBuffer.Capacity(), InputStreamOptions::Partial);
00095
00096                 responseBody << L"Bytes read from stream: " << resultBuffer.Length() << L"\n";
00097
00098                 // Use the buffer contents for something. We can't safely display it as a string though, since encodings
00099                 // like UTF-8 and UTF-16 have a variable number of bytes per character and so the last bytes in the buffer
00100                 // may not contain a whole character. Instead, we'll convert the bytes to hex and display the result.
00101                 hstring resultText = CryptographicBuffer::EncodeToHexString(resultBuffer);
00102                 responseBody << std::wstring_view(resultText) << L"\n";
00103             } while (resultBuffer.Length() > 0);
00104             responseStream.Close();
00105
00106             OutputField().Text(OutputField().Text() + responseBody.str());
00107
00108             rootPage.NotifyUser(L"Completed", NotifyType::StatusMessage);
00109         }
00110         else
00111         {
00112             Helpers::DisplayWebError(rootPage, result.ExtendedError());
00113         }
00114     }
00115
00116     void Scenario02_GetStream::Cancel_Click(IInspectable const&, RoutedEventArgs const&)
00117     {
00118         if (pendingAction)
00119         {
00120             pendingAction.Cancel();
00121         }
00122     }
00123 }
Generated on Fri Nov 15 2024 22:19:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PNTVertex Member List

This is the complete list of members for PNTVertex, including all inherited members.
normal | PNTVertex
position | PNTVertex
textureCoordinate | PNTVertex
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GiftDispatch Member List

This is the complete list of members for GiftDispatch, including all inherited members.
GiftDispatch() | GiftDispatch | [inline]
OnNavigatedTo(NavigationEventArgs e) | GiftDispatch | [inline, protected]
rootPage | GiftDispatch | [private]
Scenario4BtnDefault_Click(object sender, RoutedEventArgs e) | GiftDispatch | [inline, private]
Scenario4Init() | GiftDispatch | [inline, private]
Generated on Fri Nov 15 2024 22:24:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MapChangedEventArgs< K > Member List

This is the complete list of members for MapChangedEventArgs< K >, including all inherited members.
CollectionChange | MapChangedEventArgs< K >
Key | MapChangedEventArgs< K >
Generated on Fri Nov 15 2024 22:24:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cpp/SampleConfiguration.h Source File

  • JumpList
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Resize app view";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038         property Platform::String^ LaunchParam
00039         {
00040             Platform::String^ get()
00041             {
00042                 return launchParam;
00043             }
00044
00045             void set(Platform::String^ value);
00046         }
00047
00048     private:
00049         static Platform::Array<Scenario>^ scenariosInner;
00050         Platform::String^ launchParam;
00051     };
00052
00053     public value struct Scenario
00054     {
00055         Platform::String^ Title;
00056         Platform::String^ ClassName;
00057     };
00058
00059     partial ref class App
00060     {
00061         void Partial_LaunchCompleted(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e);
00062     public:
00063         void OnFileActivated(Windows::ApplicationModel::Activation::FileActivatedEventArgs^ args) override;
00064     };
00065 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Connect Member List

This is the complete list of members for Scenario1_Connect, including all inherited members.
ConnectButton_Click(object sender, RoutedEventArgs e) | Scenario1_Connect | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_Connect | [inline, protected]
port | Scenario1_Connect | [private]
rootPage | Scenario1_Connect | [private]
Scenario1_Connect() | Scenario1_Connect | [inline]
socket | Scenario1_Connect | [private]
socketId | Scenario1_Connect | [private]
task | Scenario1_Connect | [private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MeteringData Member List

This is the complete list of members for MeteringData, including all inherited members.
button_Click_StartMetering(Object sender, RoutedEventArgs e) | MeteringData | [inline]
button_Click_StopMetering(Object sender, RoutedEventArgs e) | MeteringData | [inline]
MeteringData() | MeteringData | [inline]
slider_ValueChanged(Object sender, RangeBaseValueChangedEventArgs e) | MeteringData | [inline]
ViewModel | MeteringData |
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cpp/Scenario3_ServicingCompleteTask.xaml.cpp Source File

  • BackgroundActivation
  • cpp

Scenario3_ServicingCompleteTask.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario3_ServicingCompleteTask.xaml.cpp
00013 // Implementation of the ServicingCompleteTask class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario3_ServicingCompleteTask.xaml.h"
00018 #include "SampleConfiguration.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::ApplicationModel::Background;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 ServicingCompleteTask::ServicingCompleteTask()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Invoked when this page is about to be displayed in a Frame.
00035 /// </summary>
00036 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037 /// property is typically used to configure the page.</param>
00038 void ServicingCompleteTask::OnNavigatedTo(NavigationEventArgs^ e)
00039 {
00040     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00041     // as NotifyUser()
00042     rootPage = MainPage::Current;
00043
00044     //
00045     // Attach progress and completed handlers to any existing tasks.
00046     //
00047     for (auto pair : BackgroundTaskRegistration::AllTasks)
00048     {
00049         auto task = pair->Value;
00050         if (task->Name == ServicingCompleteTaskName)
00051         {
00052             BackgroundTaskSample::UpdateBackgroundTaskRegistrationStatus(task->Name, true);
00053             AttachProgressAndCompletedHandlers(task);
00054             break;
00055         }
00056     }
00057
00058     UpdateUI();
00059 }
00060
00061 /// <summary>
00062 /// Attach progress and completed handers to a background task.
00063 /// </summary>
00064 /// <param name="task">The task to attach progress and completed handlers to.</param>
00065 void ServicingCompleteTask::AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration^ task)
00066 {
00067     task->Progress += ref new BackgroundTaskProgressEventHandler(this, &ServicingCompleteTask::OnProgress);
00068     task->Completed += ref new BackgroundTaskCompletedEventHandler(this, &ServicingCompleteTask::OnCompleted);
00069 }
00070
00071 /// <summary>
00072 /// Register a ServicingCompleteTask.
00073 /// </summary>
00074 /// <param name="sender"></param>
00075 /// <param name="e"></param>
00076 void ServicingCompleteTask::RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00077 {
00078     auto task = BackgroundTaskSample::RegisterBackgroundTask(nullptr,
00079                                                              ServicingCompleteTaskName,
00080                                                              ref new SystemTrigger(SystemTriggerType::ServicingComplete, false),
00081                                                              nullptr);
00082
00083     AttachProgressAndCompletedHandlers(task);
00084     UpdateUI();
00085 }
00086
00087 /// <summary>
00088 /// Unregister a ServicingCompleteTask.
00089 /// </summary>
00090 /// <param name="sender"></param>
00091 /// <param name="e"></param>
00092 void ServicingCompleteTask::UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00093 {
00094     BackgroundTaskSample::UnregisterBackgroundTasks(ServicingCompleteTaskName);
00095     UpdateUI();
00096 }
00097
00098 /// <summary>
00099 /// Handle background task progress.
00100 /// </summary>
00101 /// <param name="task">The task that is reporting progress.</param>
00102 /// <param name="args">Arguments of the progress report.</param>
00103 void ServicingCompleteTask::OnProgress(BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
00104 {
00105     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00106     {
00107         auto progress = "Progress: " + args->Progress + "%";
00108         BackgroundTaskSample::ServicingCompleteTaskProgress = progress;
00109         UpdateUI();
00110     }));
00111 }
00112
00113 /// <summary>
00114 /// Handle background task completion.
00115 /// </summary>
00116 /// <param name="task">The task that is reporting completion.</param>
00117 /// <param name="args">Arguments of the completion report.</param>
00118 void ServicingCompleteTask::OnCompleted(BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
00119 {
00120     UpdateUI();
00121 }
00122
00123 /// <summary>
00124 /// Update the scenario UI.
00125 /// </summary>
00126 void ServicingCompleteTask::UpdateUI()
00127 {
00128     auto uiDelegate = [this]()
00129     {
00130         RegisterButton->IsEnabled = !BackgroundTaskSample::ServicingCompleteTaskRegistered;
00131         UnregisterButton->IsEnabled = BackgroundTaskSample::ServicingCompleteTaskRegistered;
00132         Progress->Text = BackgroundTaskSample::ServicingCompleteTaskProgress;
00133         Status->Text = BackgroundTaskSample::GetBackgroundTaskStatus(ServicingCompleteTaskName);
00134     };
00135     auto handler = ref new Windows::UI::Core::DispatchedHandler(uiDelegate, Platform::CallbackContext::Any);
00136
00137     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, handler);
00138 }
Generated on Fri Nov 15 2024 22:18:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cpp/Scenario5_DataEventsBatching.xaml.h Source File

  • Accelerometer
  • cpp

Scenario5_DataEventsBatching.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario5_DataEventsBatching.xaml.h
00014 // Declaration of the Scenario5_DataEventsBatching class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario5_DataEventsBatching.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario5_DataEventsBatching sealed
00030     {
00031     public:
00032         Scenario5_DataEventsBatching();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         void ScenarioEnable();
00039         void ScenarioDisable();
00040
00041     private:
00042         SDKTemplate::MainPage^ rootPage = MainPage::Current;
00043         Windows::Devices::Sensors::Accelerometer^ accelerometer;
00044         Windows::Foundation::EventRegistrationToken visibilityToken;
00045         Windows::Foundation::EventRegistrationToken readingToken;
00046         uint32 desiredReportInterval = 0;
00047         uint32 desiredReportLatency = 0;
00048
00049         void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00050         void ReadingChanged(Windows::Devices::Sensors::Accelerometer^ sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^ e);
00051     };
00052 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomHidDeviceAccess/cs/Scenario2_FeatureReports.xaml.cs Source File

  • CustomHidDeviceAccess
  • cs

Scenario2_FeatureReports.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using System;
00008 using System.Collections.Generic;
00009 using System.Threading.Tasks;
00010 using Windows.Devices.HumanInterfaceDevice;
00011 using Windows.Storage.Streams;
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016
00017 namespace CustomHidDeviceAccess
00018 {
00019     /// <summary>
00020     /// This page demonstrates how to use FeatureReports to communicate with the device
00021     /// </summary>
00022     public sealed partial class FeatureReports : Page
00023     {
00024         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00025         // as NotifyUser()
00026         private MainPage rootPage = MainPage.Current;
00027
00028         public FeatureReports()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         /// <summary>
00034         /// Invoked when this page is about to be displayed in a Frame.
00035         ///
00036         /// We will enable/disable parts of the UI if the device doesn't support it.
00037         /// </summary>
00038         /// <param name="eventArgs">Event data that describes how this page was reached.  The Parameter
00039         /// property is typically used to configure the page.</param>
00040         protected override void OnNavigatedTo(NavigationEventArgs eventArgs)
00041         {
00042             // We will disable the scenario that is not supported by the device.
00043             // If no devices are connected, none of the scenarios will be shown and an error will be displayed
00044             Dictionary<DeviceType, UIElement> deviceScenarios = new Dictionary<DeviceType, UIElement>();
00045             deviceScenarios.Add(DeviceType.SuperMutt, SuperMuttScenario);
00046
00047             Utilities.SetUpDeviceScenarios(deviceScenarios, DeviceScenarioContainer);
00048         }
00049
00050         async void GetLedBlinkPattern_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00051         {
00052             if (EventHandlerForDevice.Current.IsDeviceConnected)
00053             {
00054                 ButtonGetLedBlinkPattern.IsEnabled = false;
00055
00056                 await GetLedBlinkPatternAsync();
00057
00058                 ButtonGetLedBlinkPattern.IsEnabled = true;
00059             }
00060             else
00061             {
00062                 Utilities.NotifyDeviceNotConnected();
00063             }
00064
00065         }
00066
00067         async void SetLedBlinkPattern_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00068         {
00069             if (EventHandlerForDevice.Current.IsDeviceConnected)
00070             {
00071                 ButtonSetLedBlinkPattern.IsEnabled = false;
00072
00073                 Byte pattern = (Byte)LedBlinkPatternInput.SelectedIndex;
00074
00075                 await SetLedBlinkPatternAsync(pattern);
00076
00077                 ButtonSetLedBlinkPattern.IsEnabled = true;
00078             }
00079             else
00080             {
00081                 Utilities.NotifyDeviceNotConnected();
00082             }
00083         }
00084
00085         /// <summary>
00086         /// Uses a feature report to set the blink pattern on the SuperMutt's LED.
00087         ///
00088         /// Please note that when we create a FeatureReport, all data is nulled out in the report. Since we will only be modifying
00089         /// data we care about, the other bits that we don't care about, will be zeroed out. Controls will effectively do the same thing (
00090         /// all bits are zeroed out except for the bits we care about).
00091         ///
00092         /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be handled
00093         /// at the end of the task chain.
00094         ///
00095         /// The SuperMutt has the following patterns:
00096         /// 0 - LED always on
00097         /// 1 - LED flash 2 seconds on, 2 off, repeat
00098         /// 2 - LED flash 2 seconds on, 1 off, 2 on, 4 off, repeat
00099         /// ...
00100         /// 7 - 7 iterations of 2 on, 1 off, followed by 4 off, repeat
00101         /// </summary>
00102         /// <param name="pattern">A number from 0-7. Each number represents a different blinking pattern</param>
00103         /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
00104         async Task SetLedBlinkPatternAsync(Byte pattern)
00105         {
00106             var featureReport = EventHandlerForDevice.Current.Device.CreateFeatureReport(SuperMutt.LedPattern.ReportId);
00107
00108             var dataWriter = new DataWriter();
00109
00110             // First byte is always the report id
00111             dataWriter.WriteByte((Byte)featureReport.Id);
00112             dataWriter.WriteByte(pattern);
00113
00114             featureReport.Data = dataWriter.DetachBuffer();
00115
00116             await EventHandlerForDevice.Current.Device.SendFeatureReportAsync(featureReport);
00117
00118             rootPage.NotifyUser("The Led blink pattern is set to " + pattern.ToString(), NotifyType.StatusMessage);
00119         }
00120
00121         /// <summary>
00122         /// Uses feature report to get the LED blink pattern.
00123         ///
00124         /// Any errors in async function will be passed down the task chain and will not be caught here because errors should
00125         /// be handled at the end of the task chain.
00126         ///
00127         /// The simplest way to obtain a byte from the buffer is by using a DataReader. DataReader provides a simple way
00128         /// to read from buffers (e.g. can return bytes, strings, ints).
00129         /// </summary>
00130         /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
00131         async Task GetLedBlinkPatternAsync()
00132         {
00133             var featureReport = await EventHandlerForDevice.Current.Device.GetFeatureReportAsync(SuperMutt.LedPattern.ReportId);
00134
00135             if (featureReport.Data.Length == 2)
00136             {
00137                 var dataReader = DataReader.FromBuffer(featureReport.Data);
00138
00139                 var reportId = dataReader.ReadByte();
00140                 var pattern = dataReader.ReadByte();
00141
00142                 rootPage.NotifyUser("The Led blink pattern is " + pattern.ToString(), NotifyType.StatusMessage);
00143             }
00144             else
00145             {
00146                 rootPage.NotifyUser("Expecting 2 bytes, but received " + featureReport.Data.Length, NotifyType.ErrorMessage);
00147             }
00148         }
00149
00150     }
00151 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cpp/Scenario8_Reflow.xaml.cpp Source File

  • XamlCommanding
  • cpp

Scenario8_Reflow.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // Scenario8_Reflow.xaml.cpp
00003 // Implementation of the Scenario8_Reflow class
00004 //
00005
00006 #include "pch.h"
00007 #include "Scenario8_Reflow.xaml.h"
00008
00009 using namespace SDKTemplate;
00010
00011 using namespace Platform;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::UI::Xaml;
00015 using namespace Windows::UI::Xaml::Controls;
00016 using namespace Windows::UI::Xaml::Controls::Primitives;
00017 using namespace Windows::UI::Xaml::Data;
00018 using namespace Windows::UI::Xaml::Input;
00019 using namespace Windows::UI::Xaml::Media;
00020 using namespace Windows::UI::Xaml::Navigation;
00021
00022 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00023
00024 Scenario8_Reflow::Scenario8_Reflow()
00025 {
00026     InitializeComponent();
00027 }
Generated on Fri Nov 15 2024 22:22:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Enum Member List

This is the complete list of members for Scenario3_Enum, including all inherited members.
Scenario3_Enum() | Scenario3_Enum | [inline]
ShowResults_Click(object sender, RoutedEventArgs e) | Scenario3_Enum | [inline, private]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSensors/cpp/Scenario2_Polling.xaml.h Source File

  • CustomSensors
  • cpp

Scenario2_Polling.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario2_Polling.xaml.h
00013 // Declaration of the Scenario2 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario2_Polling.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     [Windows::Foundation::Metadata::WebHostHidden]
00028     public ref class Scenario2_Polling sealed
00029     {
00030     public:
00031         Scenario2_Polling();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036
00037     private:
00038         SDKTemplate::MainPage^ m_RootPage;
00039         Windows::UI::Core::CoreDispatcher^ m_Dispatcher;
00040         Windows::Devices::Enumeration::DeviceWatcher^ m_Watcher;
00041         Windows::Devices::Sensors::Custom::CustomSensor^ m_CustomSensor;
00042         Microsoft::WRL::Wrappers::CriticalSection m_CritsecCustomSensor;
00043         Windows::Devices::Enumeration::DeviceAccessInformation^ m_DeviceAccessInfo;
00044
00045         void GetCO2Level(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046         void OnCustomSensorAdded(Windows::Devices::Enumeration::DeviceWatcher^ watcher, Windows::Devices::Enumeration::DeviceInformation^ firstDevice);
00047         void OnAccessChanged(Windows::Devices::Enumeration::DeviceAccessInformation ^sender, Windows::Devices::Enumeration::DeviceAccessChangedEventArgs ^args);
00048         void StartWatcher();
00049     };
00050 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSerialDeviceAccess/cs/Constants.cs Source File

  • CustomSerialDeviceAccess
  • cs

Constants.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017
00018 using CustomSerialDeviceAccess;
00019 using Windows.UI.Xaml.Controls;
00020
00021 namespace CustomSerialDeviceAccess
00022 {
00023     public class DeviceProperties
00024     {
00025         public const String DeviceInstanceId = "System.Devices.DeviceInstanceId";
00026     }
00027
00028     public class DeviceConfiguration
00029     {
00030         public const UInt32 BaudRate = 115200;
00031
00032         public const Windows.Devices.SerialCommunication.SerialParity Parity = Windows.Devices.SerialCommunication.SerialParity.Even;
00033
00034         public const Windows.Devices.SerialCommunication.SerialStopBitCount StopBits = Windows.Devices.SerialCommunication.SerialStopBitCount.OnePointFive;
00035
00036         public const UInt16 DataBits = 8;
00037
00038         public const Windows.Devices.SerialCommunication.SerialHandshake Handshake = Windows.Devices.SerialCommunication.SerialHandshake.RequestToSend;
00039
00040         public const Boolean BreakSignalState_false = false;
00041         public const Boolean BreakSignalState_true = true;
00042
00043         public const Boolean IsDataTerminalReady_false = false;
00044         public const Boolean IsDataTerminalReady_true = true;
00045
00046         public const Boolean IsRequestToSendEnabled_false = false;
00047         public const Boolean IsRequestToSendEnabled_true = true;
00048
00049     }
00050
00051 }
Generated on Fri Nov 15 2024 22:18:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7_PinFromAppbar Member List

This is the complete list of members for Scenario7_PinFromAppbar, including all inherited members.
BottomAppBar_Opened(object sender, object e) | Scenario7_PinFromAppbar | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario7_PinFromAppbar | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario7_PinFromAppbar | [inline, protected]
PinToAppBar_Click(object sender, RoutedEventArgs e) | Scenario7_PinFromAppbar | [inline, private]
Scenario7_PinFromAppbar() | Scenario7_PinFromAppbar | [inline]
UpdateAppBarButton() | Scenario7_PinFromAppbar | [inline, private]
Window_Activated(object sender, WindowActivatedEventArgs e) | Scenario7_PinFromAppbar | [inline, private]
Generated on Fri Nov 15 2024 22:23:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraFaceDetection/cpp/App.xaml.h Source File

  • CameraFaceDetection
  • cpp

App.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "App.g.h"
00015
00016 namespace FaceDetection
00017 {
00018     /// <summary>
00019     /// Provides application-specific behavior to supplement the default Application class.
00020     /// </summary>
00021     ref class App sealed
00022     {
00023     protected:
00024         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override;
00025
00026     internal:
00027         App();
00028
00029     private:
00030         void OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e);
00031     };
00032 }
Generated on Fri Nov 15 2024 22:16:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
ButtonUpdateBadgeNumber_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cppwinrt/Scenario5_TimeZone.h Source File

  • Calendar
  • cppwinrt

Scenario5_TimeZone.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario5_TimeZone.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario5_TimeZone : Scenario5_TimeZoneT<Scenario5_TimeZone>
00019     {
00020         Scenario5_TimeZone();
00021
00022         void ShowResults_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario5_TimeZone : Scenario5_TimeZoneT<Scenario5_TimeZone, implementation::Scenario5_TimeZone>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cs/Scenario3_ParameterizedTemplate.xaml.cs Source File

  • DateTimeFormatting
  • cs

Scenario3_ParameterizedTemplate.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Text;
00014 using Windows.Foundation;
00015 using Windows.Foundation.Collections;
00016 using Windows.Globalization;
00017 using Windows.Globalization.DateTimeFormatting;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario3_ParameterizedTemplate : Page
00025     {
00026         public Scenario3_ParameterizedTemplate()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         /// <summary>
00032         /// This is the click handler for the 'Display' button.
00033         /// </summary>
00034         private void Display()
00035         {
00036             // This scenario uses the Windows.Globalization.DateTimeFormatting.DateTimeFormatter class
00037             // to format a date/time by specifying a template via parameters.  Note that the user's language
00038             // and region preferences will determine the pattern of the date returned based on the
00039             // specified parts.
00040
00041             // We keep results in this variable
00042             StringBuilder results = new StringBuilder();
00043             results.AppendLine("Current application context language: " + ApplicationLanguages.Languages[0]);
00044             results.AppendLine();
00045
00046             // Create formatters with individual format specifiers for date/time elements.
00047             DateTimeFormatter[] dateFormatters = new[]
00048             {
00049                 // Example formatters for dates.
00050                 new DateTimeFormatter(
00051                     YearFormat.Full,
00052                     MonthFormat.Abbreviated,
00053                     DayFormat.Default,
00054                     DayOfWeekFormat.Abbreviated),
00055                 new DateTimeFormatter(
00056                     YearFormat.Abbreviated,
00057                     MonthFormat.Abbreviated,
00058                     DayFormat.Default,
00059                     DayOfWeekFormat.None),
00060                 new DateTimeFormatter(
00061                     YearFormat.Full,
00062                     MonthFormat.Full,
00063                     DayFormat.None,
00064                     DayOfWeekFormat.None),
00065                 new DateTimeFormatter(
00066                     YearFormat.None,
00067                     MonthFormat.Full,
00068                     DayFormat.Default,
00069                     DayOfWeekFormat.None)
00070             };
00071
00072             // Create formatters with individual format specifiers for time elements.
00073             DateTimeFormatter[] timeFormatters = new[]
00074             {
00075                 // Example formatters for times.
00076                 new DateTimeFormatter(
00077                     HourFormat.Default,
00078                     MinuteFormat.Default,
00079                     SecondFormat.Default),
00080                 new DateTimeFormatter(
00081                     HourFormat.Default,
00082                     MinuteFormat.Default,
00083                     SecondFormat.None),
00084                 new DateTimeFormatter(
00085                     HourFormat.Default,
00086                     MinuteFormat.None,
00087                     SecondFormat.None),
00088              };
00089
00090             // Create date/time to format and display.
00091             DateTime dateTime = DateTime.Now;
00092
00093             results.AppendLine("Dates:");
00094
00095             // Format and display date/time. Calendar always supports Now. Otherwise you may need to verify dateTime is in supported range.
00096             foreach (DateTimeFormatter formatter in dateFormatters)
00097             {
00098                 // Format and display date/time.
00099                 results.AppendLine(formatter.Template + ": " + formatter.Format(dateTime));
00100             }
00101
00102             results.AppendLine();
00103             results.AppendLine("Times:");
00104
00105             // Format and display date/time. Calendar always supports Now. Otherwise you may need to verify dateTime is in supported range.
00106             foreach (DateTimeFormatter formatter in timeFormatters)
00107             {
00108                 // Format and display date/time.
00109                 results.AppendLine(formatter.Template + ": " + formatter.Format(dateTime));
00110             }
00111
00112             // Display the results
00113             OutputTextBlock.Text = results.ToString();
00114         }
00115     }
00116 }
Generated on Fri Nov 15 2024 22:19:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cs/BackgroundTask/Scenario1_SampleBackgroundTask.xaml.cs Source File

  • BackgroundTask
  • cs
  • BackgroundTask

Scenario1_SampleBackgroundTask.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.Background;
00014 using Windows.Storage;
00015 using Windows.UI.Core;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019 using SDKTemplate;
00020
00021 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class SampleBackgroundTask : Page
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         private MainPage rootPage = MainPage.Current;
00033
00034         public SampleBackgroundTask()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         /// <summary>
00040         /// Invoked when this page is about to be displayed in a Frame.
00041         /// </summary>
00042         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00043         /// property is typically used to configure the page.</param>
00044         protected override void OnNavigatedTo(NavigationEventArgs e)
00045         {
00046             foreach (var task in BackgroundTaskRegistration.AllTasks)
00047             {
00048                 if (task.Value.Name == BackgroundTaskSample.SampleBackgroundTaskName)
00049                 {
00050                     AttachProgressAndCompletedHandlers(task.Value);
00051                     BackgroundTaskSample.UpdateBackgroundTaskRegistrationStatus(BackgroundTaskSample.SampleBackgroundTaskName, true);
00052                     break;
00053                 }
00054             }
00055
00056             UpdateUI();
00057         }
00058
00059         /// <summary>
00060         /// Register a SampleBackgroundTask.
00061         /// </summary>
00062         /// <param name="sender"></param>
00063         /// <param name="e"></param>
00064         private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
00065         {
00066             var task = BackgroundTaskSample.RegisterBackgroundTask(BackgroundTaskSample.SampleBackgroundTaskEntryPoint,
00067                                                                    BackgroundTaskSample.SampleBackgroundTaskName,
00068                                                                    new SystemTrigger(SystemTriggerType.TimeZoneChange, false),
00069                                                                    null);
00070             AttachProgressAndCompletedHandlers(task);
00071             UpdateUI();
00072         }
00073
00074         /// <summary>
00075         /// Unregister a SampleBackgroundTask.
00076         /// </summary>
00077         /// <param name="sender"></param>
00078         /// <param name="e"></param>
00079         private void UnregisterBackgroundTask(object sender, RoutedEventArgs e)
00080         {
00081             BackgroundTaskSample.UnregisterBackgroundTasks(BackgroundTaskSample.SampleBackgroundTaskName);
00082             UpdateUI();
00083         }
00084
00085         /// <summary>
00086         /// Attach progress and completed handers to a background task.
00087         /// </summary>
00088         /// <param name="task">The task to attach progress and completed handlers to.</param>
00089         private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
00090         {
00091             task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
00092             task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
00093         }
00094
00095         /// <summary>
00096         /// Handle background task progress.
00097         /// </summary>
00098         /// <param name="task">The task that is reporting progress.</param>
00099         /// <param name="e">Arguments of the progress report.</param>
00100         private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
00101         {
00102             var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00103             {
00104                 var progress = "Progress: " + args.Progress + "%";
00105                 BackgroundTaskSample.SampleBackgroundTaskProgress = progress;
00106                 UpdateUI();
00107             });
00108         }
00109
00110         /// <summary>
00111         /// Handle background task completion.
00112         /// </summary>
00113         /// <param name="task">The task that is reporting completion.</param>
00114         /// <param name="e">Arguments of the completion report.</param>
00115         private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
00116         {
00117             UpdateUI();
00118         }
00119
00120         /// <summary>
00121         /// Update the scenario UI.
00122         /// </summary>
00123         private async void UpdateUI()
00124         {
00125             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00126             () =>
00127             {
00128                 RegisterButton.IsEnabled = !BackgroundTaskSample.SampleBackgroundTaskRegistered;
00129                 UnregisterButton.IsEnabled = BackgroundTaskSample.SampleBackgroundTaskRegistered;
00130                 Progress.Text = BackgroundTaskSample.SampleBackgroundTaskProgress;
00131                 Status.Text = BackgroundTaskSample.GetBackgroundTaskStatus(BackgroundTaskSample.SampleBackgroundTaskName);
00132             });
00133         }
00134     }
00135 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DDS_PIXELFORMAT Member List

This is the complete list of members for DDS_PIXELFORMAT, including all inherited members.
ABitMask | DDS_PIXELFORMAT
ABitMask | DDS_PIXELFORMAT
BBitMask | DDS_PIXELFORMAT
BBitMask | DDS_PIXELFORMAT
flags | DDS_PIXELFORMAT
flags | DDS_PIXELFORMAT
fourCC | DDS_PIXELFORMAT
fourCC | DDS_PIXELFORMAT
GBitMask | DDS_PIXELFORMAT
GBitMask | DDS_PIXELFORMAT
RBitMask | DDS_PIXELFORMAT
RBitMask | DDS_PIXELFORMAT
RGBBitCount | DDS_PIXELFORMAT
RGBBitCount | DDS_PIXELFORMAT
size | DDS_PIXELFORMAT
size | DDS_PIXELFORMAT
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_ScriptDetection Member List

This is the complete list of members for Scenario2_ScriptDetection, including all inherited members.
Go_Click(object sender, RoutedEventArgs e) | Scenario2_ScriptDetection | [inline]
rootPage | Scenario2_ScriptDetection | [private]
Scenario2_ScriptDetection() | Scenario2_ScriptDetection | [inline]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/GameRenderer.h Source File

  • Simple3DGameDX
  • cpp

GameRenderer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // GameRenderer:
00015 // This is the renderer for the game.
00016 // It is responsble for creating and maintaining all the D3D11 and D2D objects
00017 // used to generate the game visuals.  It maintains a reference to the Simple3DGame
00018 // object to retrieve the list of objects to render as well as status of the
00019 // game for the Heads Up Display (HUD).
00020 //
00021 // The renderer is designed to use a standard vertex layout across all objects.  This
00022 // simplifies the shader design and allows for easy changes between shaders independent
00023 // of the objects' geometry.  Each vertex is defined by a position, a normal and one set of
00024 // 2D texture coordinates.  The shaders all expect one 2D texture and 4 constant buffers:
00025 //     m_constantBufferNeverChanges - general parameters that are set only once.  This includes
00026 //         all the lights used in scene generation.
00027 //     m_constantBufferChangeOnResize - the projection matrix.  It is typically only changed when
00028 //         the window is resized, however it will be changed 2x per frame when rendering
00029 //         in 3D stereo.
00030 //     m_constantBufferChangesEveryFrame - the view transformation matrix.  This is set once per frame.
00031 //     m_constantBufferChangesEveryPrim - the parameters for each object.  It includes the object to world
00032 //         transformation matrix as well as material properties like color and specular exponent for lighting
00033 //         calculations.
00034 //
00035 // The renderer also maintains a set of texture resources that will be associated with particular game objects.
00036 // It knows which textures are to be associated with which objects and will do that association once the
00037 // textures have been loaded.
00038 //
00039 // The renderer provides a set of methods to allow for a "standard" sequence to be executed for loading general
00040 // game resources and for level specific resources.  Because D3D11 allows free threaded creation of objects,
00041 // textures will be loaded asynchronously and in parallel, however D3D11 does not allow for multiple threads to
00042 // be using the DeviceContext at the same time.
00043 //
00044 // The pattern is:
00045 //     create_task([this]()
00046 //     {
00047 //         // create/load device resources
00048 //     }).then([this]()
00049 //     {
00050 //         // create/load device context resources
00051 //     }, task_continuation_context::use_current());
00052
00053 #include "DeviceResources.h"
00054 #include "GameUIConstants.h"
00055 #include "GameInfoOverlay.h"
00056 #include "GameHud.h"
00057 #include "Simple3DGame.h"
00058
00059 ref class Simple3DGame;
00060 ref class GameHud;
00061
00062 ref class GameRenderer
00063 {
00064 internal:
00065     GameRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00066
00067     void CreateDeviceDependentResources();
00068     void CreateWindowSizeDependentResources();
00069     void ReleaseDeviceDependentResources();
00070     void Render();
00071
00072     concurrency::task<void> CreateGameDeviceResourcesAsync(_In_ Simple3DGame^ game);
00073     void FinalizeCreateGameDeviceResources();
00074     concurrency::task<void> LoadLevelResourcesAsync();
00075     void FinalizeLoadLevelResources();
00076
00077     Simple3DGameDX::IGameUIControl^ GameUIControl()  { return m_gameInfoOverlay; };
00078
00079     DirectX::XMFLOAT2 GameInfoOverlayUpperLeft()
00080     {
00081         return DirectX::XMFLOAT2(m_gameInfoOverlayRect.left, m_gameInfoOverlayRect.top);
00082     };
00083     DirectX::XMFLOAT2 GameInfoOverlayLowerRight()
00084     {
00085         return DirectX::XMFLOAT2(m_gameInfoOverlayRect.right, m_gameInfoOverlayRect.bottom);
00086     };
00087     bool GameInfoOverlayVisible() { return m_gameInfoOverlay->Visible(); }
00088
00089 #if defined(_DEBUG)
00090     void ReportLiveDeviceObjects();
00091 #endif
00092
00093 protected private:
00094     // Cached pointer to device resources.
00095     std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00096
00097     bool                                                m_initialized;
00098     bool                                                m_gameResourcesLoaded;
00099     bool                                                m_levelResourcesLoaded;
00100     GameInfoOverlay^                                    m_gameInfoOverlay;
00101     GameHud^                                            m_gameHud;
00102     Simple3DGame^                                       m_game;
00103     D2D_RECT_F                                          m_gameInfoOverlayRect;
00104     D2D_SIZE_F                                          m_gameInfoOverlaySize;
00105
00106     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_sphereTexture;
00107     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_cylinderTexture;
00108     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_ceilingTexture;
00109     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_floorTexture;
00110     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_wallsTexture;
00111
00112     // Constant Buffers
00113     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBufferNeverChanges;
00114     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBufferChangeOnResize;
00115     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBufferChangesEveryFrame;
00116     Microsoft::WRL::ComPtr<ID3D11Buffer>                m_constantBufferChangesEveryPrim;
00117     Microsoft::WRL::ComPtr<ID3D11SamplerState>          m_samplerLinear;
00118     Microsoft::WRL::ComPtr<ID3D11VertexShader>          m_vertexShader;
00119     Microsoft::WRL::ComPtr<ID3D11VertexShader>          m_vertexShaderFlat;
00120     Microsoft::WRL::ComPtr<ID3D11PixelShader>           m_pixelShader;
00121     Microsoft::WRL::ComPtr<ID3D11PixelShader>           m_pixelShaderFlat;
00122     Microsoft::WRL::ComPtr<ID3D11InputLayout>           m_vertexLayout;
00123 };
Generated on Fri Nov 15 2024 22:21:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_StateTrigger Member List

This is the complete list of members for Scenario4_StateTrigger, including all inherited members.
Scenario4_StateTrigger() Scenario4_StateTrigger [inline]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraVideoStabilization/cs/App.xaml.cs Source File

  • CameraVideoStabilization
  • cs

App.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.Activation;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 namespace CameraVideoStabilization
00019 {
00020     /// <summary>
00021     /// Provides application-specific behavior to supplement the default Application class.
00022     /// </summary>
00023     sealed partial class App : Application
00024     {
00025         /// <summary>
00026         /// Initializes the singleton application object.  This is the first line of authored code
00027         /// executed, and as such is the logical equivalent of main() or WinMain().
00028         /// </summary>
00029         public App()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         /// <summary>
00035         /// Invoked when the application is launched normally by the end user.  Other entry points
00036         /// will be used such as when the application is launched to open a specific file.
00037         /// </summary>
00038         /// <param name="e">Details about the launch request and process.</param>
00039         protected override void OnLaunched(LaunchActivatedEventArgs e)
00040         {
00041
00042 #if DEBUG
00043             if (System.Diagnostics.Debugger.IsAttached)
00044             {
00045                 this.DebugSettings.EnableFrameRateCounter = true;
00046             }
00047 #endif
00048
00049             Frame rootFrame = Window.Current.Content as Frame;
00050
00051             // Do not repeat app initialization when the Window already has content,
00052             // just ensure that the window is active
00053             if (rootFrame == null)
00054             {
00055                 // Create a Frame to act as the navigation context and navigate to the first page
00056                 rootFrame = new Frame();
00057                 // Set the default language
00058                 rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
00059
00060                 rootFrame.NavigationFailed += OnNavigationFailed;
00061
00062                 // Place the frame in the current Window
00063                 Window.Current.Content = rootFrame;
00064             }
00065
00066             if (rootFrame.Content == null)
00067             {
00068                 // When the navigation stack isn't restored navigate to the first page,
00069                 // configuring the new page by passing required information as a navigation
00070                 // parameter
00071                 rootFrame.Navigate(typeof(MainPage), e.Arguments);
00072             }
00073             // Ensure the current window is active
00074             Window.Current.Activate();
00075         }
00076
00077         /// <summary>
00078         /// Invoked when Navigation to a certain page fails
00079         /// </summary>
00080         /// <param name="sender">The Frame which failed navigation</param>
00081         /// <param name="e">Details about the navigation failure</param>
00082         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00083         {
00084             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00085         }
00086     }
00087 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/scenario10.xaml.h Source File

  • ApplicationResources
  • cpp

scenario10.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario10.xaml.h
00013 // Declaration of the Scenario10 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario10.g.h"
00020 #include "MainPage.xaml.h"
00021 namespace SDKTemplate
00022 {
00023 /// <summary>
00024         /// An empty page that can be used on its own or navigated to within a Frame.
00025         /// </summary>
00026         [Windows::Foundation::Metadata::WebHostHidden]
00027         public ref class Scenario10 sealed
00028         {
00029         public:
00030             Scenario10();
00031
00032         protected:
00033             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00034         private:
00035             MainPage^ rootPage;
00036             void Scenario10Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037
00038             void Scenario10_SearchMultipleResourceIds(Windows::ApplicationModel::Resources::Core::ResourceContext^ context, Platform::Collections::Vector<Platform::String^>^ resourceIds);
00039             void Scenario10_ShowCandidates(Platform::String^ resourceId, Windows::Foundation::Collections::IVectorView<Windows::ApplicationModel::Resources::Core::ResourceCandidate^>^ resourceCandidates);
00040         };
00041
00042 }
Generated on Fri Nov 15 2024 22:17:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cppwinrt/pch.cpp Source File

  • BarcodeScanner
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboardTextInput/cpp/Scenario2_ScopedViews.xaml.h Source File

  • TouchKeyboardTextInput
  • cpp

Scenario2_ScopedViews.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_ScopedViews.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario2_ScopedViews sealed
00024     {
00025     public:
00026         Scenario2_ScopedViews();
00027     };
00028 }
Generated on Fri Nov 15 2024 22:21:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStarterKit/cpp/App.xaml.cpp Source File

  • CameraStarterKit
  • cpp

App.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014
00015 using namespace CameraStarterKit;
00016
00017 using namespace Platform;
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::ApplicationModel::Activation;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Controls::Primitives;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::UI::Xaml::Input;
00027 using namespace Windows::UI::Xaml::Interop;
00028 using namespace Windows::UI::Xaml::Media;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 /// <summary>
00032 /// Initializes the singleton application object.  This is the first line of authored code
00033 /// executed, and as such is the logical equivalent of main() or WinMain().
00034 /// </summary>
00035 App::App()
00036 {
00037     InitializeComponent();
00038     Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
00039 }
00040
00041 /// <summary>
00042 /// Invoked when the application is launched normally by the end user.  Other entry points
00043 /// will be used such as when the application is launched to open a specific file.
00044 /// </summary>
00045 /// <param name="e">Details about the launch request and process.</param>
00046 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
00047 {
00048
00049 #if _DEBUG
00050         // Show graphics profiling information while debugging.
00051         if (IsDebuggerPresent())
00052         {
00053             // Display the current frame rate counters
00054              DebugSettings->EnableFrameRateCounter = true;
00055         }
00056 #endif
00057
00058     auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00059
00060     // Do not repeat app initialization when the Window already has content,
00061     // just ensure that the window is active
00062     if (rootFrame == nullptr)
00063     {
00064         // Create a Frame to act as the navigation context and associate it with
00065         // a SuspensionManager key
00066         rootFrame = ref new Frame();
00067
00068         // Set the default language
00069         rootFrame->Language = Windows::Globalization::ApplicationLanguages::Languages->GetAt(0);
00070
00071         rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed);
00072
00073         if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
00074         {
00075             // Restore the saved session state only when appropriate, scheduling the
00076             // final launch steps after the restore is complete
00077
00078         }
00079
00080         if (rootFrame->Content == nullptr)
00081         {
00082             // When the navigation stack isn't restored navigate to the first page,
00083             // configuring the new page by passing required information as a navigation
00084             // parameter
00085             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00086         }
00087         // Place the frame in the current Window
00088         Window::Current->Content = rootFrame;
00089         // Ensure the current window is active
00090         Window::Current->Activate();
00091     }
00092     else
00093     {
00094         if (rootFrame->Content == nullptr)
00095         {
00096             // When the navigation stack isn't restored navigate to the first page,
00097             // configuring the new page by passing required information as a navigation
00098             // parameter
00099             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00100         }
00101         // Ensure the current window is active
00102         Window::Current->Activate();
00103     }
00104 }
00105
00106 /// <summary>
00107 /// Invoked when application execution is being suspended.  Application state is saved
00108 /// without knowing whether the application will be terminated or resumed with the contents
00109 /// of memory still intact.
00110 /// </summary>
00111 /// <param name="sender">The source of the suspend request.</param>
00112 /// <param name="e">Details about the suspend request.</param>
00113 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00114 {
00115     (void) sender;  // Unused parameter
00116     (void) e;   // Unused parameter
00117
00118     // Save application state and stop any background activity
00119 }
00120
00121 /// <summary>
00122 /// Invoked when Navigation to a certain page fails
00123 /// </summary>
00124 /// <param name="sender">The Frame which failed navigation</param>
00125 /// <param name="e">Details about the navigation failure</param>
00126 void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e)
00127 {
00128     throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name);
00129 }
Generated on Fri Nov 15 2024 22:16:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlMasterDetail/cppwinrt/App.h Source File

  • XamlMasterDetail
  • cppwinrt

App.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "App.xaml.g.h"
00014
00015 namespace winrt::MasterDetailApp::implementation
00016 {
00017     struct App : AppT<App>
00018     {
00019         App();
00020         Windows::UI::Xaml::Controls::Frame CreateRootFrame();
00021
00022         void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs const&);
00023         void OnNavigationFailed(IInspectable const&, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs const&);
00024     };
00025 }
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MobileHotspot/cppwinrt/Scenario2_ToggleMobileHotspot.h Source File

  • MobileHotspot
  • cppwinrt

Scenario2_ToggleMobileHotspot.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_ToggleMobileHotspot.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_ToggleMobileHotspot : Scenario2_ToggleMobileHotspotT<Scenario2_ToggleMobileHotspot>
00019     {
00020         Scenario2_ToggleMobileHotspot();
00021
00022         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00023         fire_and_forget MobileHotspotToggle_Toggled(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00024
00025     private:
00026         Windows::Networking::NetworkOperators::NetworkOperatorTetheringManager m_tetheringManager{ nullptr };
00027         bool m_toggling{ false };
00028     };
00029 }
00030
00031 namespace winrt::SDKTemplate::factory_implementation
00032 {
00033     struct Scenario2_ToggleMobileHotspot : Scenario2_ToggleMobileHotspotT<Scenario2_ToggleMobileHotspot, implementation::Scenario2_ToggleMobileHotspot>
00034     {
00035     };
00036 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/Scenario_ContinuousRecognitionSRGSGrammar.xaml.h Source File

  • SpeechRecognitionAndSynthesis
  • cpp

Scenario_ContinuousRecognitionSRGSGrammar.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario_ContinuousRecognitionSRGSGrammar.g.h"
00015 #include "MainPage.xaml.h"
00016 #include <sstream>
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class Scenario_ContinuousRecognitionSRGSGrammar sealed
00025     {
00026     public:
00027         Scenario_ContinuousRecognitionSRGSGrammar();
00028
00029     protected:
00030         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00031         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00032
00033     private:
00034         /// <summary>
00035         /// This HResult represents the scenario where a user is prompted to allow in-app speech, but
00036         /// declines. This should only happen on a Phone device, where speech is enabled for the entire device,
00037         /// not per-app.
00038         /// </summary>
00039         static const unsigned int HResultPrivacyStatementDeclined = 0x80045509;
00040         static const unsigned int HResultRecognizerNotFound = 0x8004503a;
00041
00042         SDKTemplate::MainPage^ rootPage;
00043         Windows::UI::Core::CoreDispatcher^ dispatcher;
00044         Windows::Media::SpeechRecognition::SpeechRecognizer^ speechRecognizer;
00045         Windows::Foundation::Collections::IMap<Platform::String^, Windows::UI::Color>^ colorLookup;
00046         Windows::ApplicationModel::Resources::Core::ResourceContext^ speechContext;
00047         Windows::ApplicationModel::Resources::Core::ResourceMap^ speechResourceMap;
00048         bool isPopulatingLanguages = false;
00049
00050         void ContinuousRecognize_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00051
00052         void PopulateLanguageDropdown();
00053         void InitializeRecognizer(Windows::Globalization::Language^ recognizerLanguage);
00054
00055         Windows::Foundation::EventRegistrationToken stateChangedToken;
00056         Windows::Foundation::EventRegistrationToken continuousRecognitionCompletedToken;
00057         Windows::Foundation::EventRegistrationToken continuousRecognitionResultGeneratedToken;
00058
00059         void SpeechRecognizer_StateChanged(Windows::Media::SpeechRecognition::SpeechRecognizer ^sender, Windows::Media::SpeechRecognition::SpeechRecognizerStateChangedEventArgs ^args);
00060         void ContinuousRecognitionSession_Completed(Windows::Media::SpeechRecognition::SpeechContinuousRecognitionSession ^sender, Windows::Media::SpeechRecognition::SpeechContinuousRecognitionCompletedEventArgs ^args);
00061         void ContinuousRecognitionSession_ResultGenerated(Windows::Media::SpeechRecognition::SpeechContinuousRecognitionSession ^sender, Windows::Media::SpeechRecognition::SpeechContinuousRecognitionResultGeneratedEventArgs ^args);
00062         void cbLanguageSelection_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00063
00064         void HandleRecognitionResult(Windows::Media::SpeechRecognition::SpeechRecognitionResult^ recoResult);
00065         Windows::UI::Color getColor(Platform::String^ colorString);
00066     };
00067 }
Generated on Fri Nov 15 2024 22:21:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ModelColorConstantBuffer Member List

This is the complete list of members for ModelColorConstantBuffer, including all inherited members.
color | ModelColorConstantBuffer
model | ModelColorConstantBuffer
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SpatialInputHandler Member List

This is the complete list of members for SpatialInputHandler, including all inherited members.
CheckForInput() | SpatialInputHandler |
m_interactionManager | SpatialInputHandler | [private]
m_sourcePressedEventToken | SpatialInputHandler | [private]
m_sourceState | SpatialInputHandler | [private]
OnSourcePressed(Windows::UI::Input::Spatial::SpatialInteractionManager^sender, Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs^args) | SpatialInputHandler | [private]
SpatialInputHandler() | SpatialInputHandler |
~SpatialInputHandler() | SpatialInputHandler |
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CardReader Member List

This is the complete list of members for CardReader, including all inherited members.
CardReader() | CardReader | [inline]
cardReader_CardAdded(SmartCardReader sender, CardAddedEventArgs args) | CardReader | [inline, private]
cardReader_CardRemoved(SmartCardReader sender, CardRemovedEventArgs args) | CardReader | [inline, private]
HandleCard(SmartCard card) | CardReader | [inline, private]
m_cardReader | CardReader | [private]
OnNavigatedTo(NavigationEventArgs e) | CardReader | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | CardReader | [inline, protected]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario1.xaml.h Source File

  • MapControl
  • cpp

Scenario1.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario1 sealed
00021     {
00022     public:
00023         Scenario1();
00024     private:
00025         MainPage^ rootPage = MainPage::Current;
00026
00027         void SetMapStyle();
00028         void SetMapProjection();
00029
00030         void MyMap_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00031         void MyMap_MapTapped(Windows::UI::Xaml::Controls::Maps::MapControl^ sender, Windows::UI::Xaml::Controls::Maps::MapInputEventArgs^ args);
00032         void TrafficFlowVisible_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033         void trafficFlowVisibleCheckBox_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void styleCombobox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00035         void projectionCombobox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00036     };
00037 }
Generated on Fri Nov 15 2024 22:17:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSegmentation/cpp/Scenario2_GetCurrentTextSegmentFromIndex.xaml.cpp Source File

  • TextSegmentation
  • cpp

Scenario2_GetCurrentTextSegmentFromIndex.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario2_GetCurrentTextSegmentFromIndex.xaml.h"
00005 #include "MainPage.xaml.h"
00006
00007 using namespace Platform;
00008
00009 using namespace SDKTemplate;
00010
00011 using namespace Windows::UI::Xaml;
00012 using namespace Windows::UI::Xaml::Controls;
00013
00014 Scenario2_GetCurrentTextSegmentFromIndex::Scenario2_GetCurrentTextSegmentFromIndex()
00015 {
00016     InitializeComponent();
00017 }
00018
00019 /// <summary>
00020 /// This is the click handler for the 'Word Segments' button.
00021 ///
00022 /// When this button is activated, the Text Segmentation API will calculate
00023 /// the word segment from the given input string and character index for that string,
00024 /// and return the WordSegment object that contains the index within its text bounds.
00025 /// Segment breaking behavior is based off of the language-tag input, which defines
00026 /// which language rules to use.
00027 ///
00028 /// </summary>
00029 /// <param name="sender">The object that raised the event.</param>
00030 /// <param name="e">Event data that describes the click action on the button.</param>
00031 void Scenario2_GetCurrentTextSegmentFromIndex::WordSegmentButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00032 {
00033     // Initialize and obtain input values
00034     String^ notifyText = ref new String();
00035
00036     // Obtain the input string value, check for non-emptiness
00037     String^ inputStringText = inputStringBox->Text;
00038     if (inputStringText->IsEmpty())
00039     {
00040         notifyText = "\nCannot compute word segments: input string is empty.";
00041         MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00042         return;
00043     }
00044
00045     // Obtain the language tag value, check for non-emptiness and that it is valid
00046     // Ex. Valid Values:
00047     //     "en-US" (English (United States))
00048     //     "fr-FR" (French (France))
00049     //     "de-DE" (German (Germany))
00050     //     "ja-JP" (Japanese (Japan))
00051     //     "ar-SA" (Arabic (Saudi Arabia))
00052     //     "zh-CN" (China (PRC))
00053     String^ languageTagText = languageTagBox->Text;
00054     if (languageTagText->IsEmpty())
00055     {
00056         notifyText += "\nLanguage tag input is empty ... using generic-language segmentation rules.";
00057         languageTagText = "und";    // This is used for non language-specific locales. 'und' is short for 'undetermined'.
00058     }
00059     else
00060     {
00061         if (!Windows::Globalization::Language::IsWellFormed(languageTagText))
00062         {
00063             notifyText = "\nLanguage tag is not well formed: \"" + languageTagText + "\"";
00064             MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00065             return;
00066         }
00067     }
00068
00069     // Obtain the input Index
00070     String^ inputIndexString = indexBox->Text;
00071     unsigned int inputIndex = 0;
00072     if (inputIndexString->IsEmpty())
00073     {
00074         notifyText += "\nNo input index provided ... using first segment reference (index = 0) as default.";
00075     }
00076     else
00077     {
00078         try
00079         {
00080             inputIndex = _wtoi(indexBox->Text->Data());
00081         }
00082         catch (Exception^)
00083         {
00084             notifyText = "\nInvalid index supplied.\n\nPlease check that this value is valid, and non-negative.";
00085             MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00086             return;
00087         }
00088
00089         if ((inputIndex < 0) || (inputIndex >= inputStringText->Length()))
00090         {
00091             notifyText = "\nInvalid index supplied ... cannot use a negative index, or an index that is out of bounds of the input string.\n\nPlease re-check the index value, and try again.";
00092             MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00093             return;
00094         }
00095     }
00096
00097     // Notify that we are going to calculate word segment
00098     notifyText += "\n\nFinding the word segment for the given index ...\n";
00099     notifyText += "\nInput: \"" + inputStringText + "\"";
00100     notifyText += "\nLanguage Tag: \"" + languageTagText + "\"";
00101     notifyText += "\nIndex: " + inputIndex + "\n";
00102
00103     // Construct the WordsSegmenter instance
00104     auto segmenter = ref new Windows::Data::Text::WordsSegmenter(languageTagText);
00105
00106     // Obtain the token segment
00107     auto tokenSegment = segmenter->GetTokenAt(inputStringText, inputIndex);
00108     notifyText += "\nIndexed segment: \"" + tokenSegment->Text + "\"";
00109
00110     // Set output box text to the contents of the StringBuilder instance
00111     MainPage::Current->NotifyUser(notifyText, NotifyType::StatusMessage);
00112 }
00113
00114 /// <summary>
00115 /// This is the click handler for the 'Selection Segment' button.
00116 ///
00117 /// When this button is activated, the Text Segmentation API will calculate
00118 /// the selection segment from the given input string and character index for that string,
00119 /// and return the SelectableWordSegment object that contains the index within its text bounds.
00120 /// Segment breaking behavior is based off of the language-tag input, which defines
00121 /// which language rules to use.
00122 ///
00123 /// Selection segments differ from word segments in that they describe the bounds
00124 /// between active-selection snapping behavior.
00125 ///
00126 /// </summary>
00127 /// <param name="sender">The object that raised the event.</param>
00128 /// <param name="e">Event data that describes the click action on the button.</param>
00129 void Scenario2_GetCurrentTextSegmentFromIndex::SelectionSegmentButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00130 {
00131     // Initialize and obtain input values
00132     String^ notifyText = ref new String();
00133
00134     // Obtain the input string value, check for non-emptiness
00135     String^ inputStringText = inputStringBox->Text;
00136     if (inputStringText->IsEmpty())
00137     {
00138         notifyText = "\nCannot compute word segments: input string is empty.";
00139         MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00140         return;
00141     }
00142
00143     // Obtain the language tag value, check for non-emptiness and that it is valid
00144     // Ex. Valid Values:
00145     //     "en-US" (English (United States))
00146     //     "fr-FR" (French (France))
00147     //     "de-DE" (German (Germany))
00148     //     "ja-JP" (Japanese (Japan))
00149     //     "ar-SA" (Arabic (Saudi Arabia))
00150     //     "zh-CN" (China (PRC))
00151     String^ languageTagText = languageTagBox->Text;
00152     if (languageTagText->IsEmpty())
00153     {
00154         notifyText += "\nLanguage tag input is empty ... using generic-language segmentation rules.";
00155         languageTagText = "und";    // This is used for non language-specific locales. 'und' is short for 'undetermined'.
00156     }
00157     else
00158     {
00159         if (!Windows::Globalization::Language::IsWellFormed(languageTagText))
00160         {
00161             notifyText = "\nLanguage tag is not well formed: \"" + languageTagText + "\"";
00162             MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00163             return;
00164         }
00165     }
00166
00167     // Obtain the input Index
00168     String^ inputIndexString = indexBox->Text;
00169     unsigned int inputIndex = 0;
00170     if (inputIndexString->IsEmpty())
00171     {
00172         notifyText += "\nNo input index provided ... using first segment reference (index = 0) as default.";
00173     }
00174     else
00175     {
00176         try
00177         {
00178             inputIndex = _wtoi(indexBox->Text->Data());
00179         }
00180         catch (Exception^)
00181         {
00182             notifyText = "\nInvalid index supplied.\n\nPlease check that this value is valid, and non-negative.";
00183             MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00184             return;
00185         }
00186
00187         if ((inputIndex < 0) || (inputIndex >= inputStringText->Length()))
00188         {
00189             notifyText = "\nInvalid index supplied ... cannot use a negative index, or an index that is out of bounds of the input string.\n\nPlease re-check the index value, and try again.";
00190             MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00191             return;
00192         }
00193     }
00194
00195     // Notify that we are going to calculate selection segment
00196     notifyText += "\n\nFinding the selection segment for the given index ...\n";
00197     notifyText += "\nInput: \"" + inputStringText + "\"";
00198     notifyText += "\nLanguage Tag: \"" + languageTagText + "\"";
00199     notifyText += "\nIndex: " + inputIndex + "\n";
00200
00201     // Construct the SelectableWordsSegmenter instance
00202     auto segmenter = ref new Windows::Data::Text::SelectableWordsSegmenter(languageTagText);
00203
00204     // Obtain the token segment
00205     auto tokenSegment = segmenter->GetTokenAt(inputStringText, inputIndex);
00206     notifyText += "\nIndexed segment: \"" + tokenSegment->Text + "\"";
00207
00208     // Set output box text to the contents of the StringBuilder instance
00209     MainPage::Current->NotifyUser(notifyText, NotifyType::StatusMessage);
00210 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LiveDash/cs/LiveDash/Models/MediaSegmentInformation.cs Source File

  • LiveDash
  • cs
  • LiveDash
  • Models

MediaSegmentInformation.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006
00007 namespace LiveDash.Models
00008 {
00009     class MediaSegmentInformation
00010     {
00011         private UInt64 timescale;
00012         private UInt64 startNumber;
00013         private UInt64 startTimestamp;
00014         private UInt64 duration;
00015         private UInt32 bitrate;
00016         private string representationID;
00017
00018         private string mediaUrlTemplate;
00019
00020         #region properties
00021
00022         internal UInt64 Timescale
00023         {
00024             get { return timescale; }
00025
00026             set { timescale = value; }
00027         }
00028
00029         internal UInt64 StartNumber
00030         {
00031             get { return startNumber; }
00032
00033             set { startNumber = value; }
00034         }
00035
00036         internal UInt64 StartTimestamp
00037         {
00038             get { return startTimestamp; }
00039
00040             set { startTimestamp = value; }
00041         }
00042
00043         internal UInt64 Duration
00044         {
00045             get { return duration; }
00046
00047             set { duration = value; }
00048         }
00049
00050         internal UInt32 Bitrate
00051         {
00052             get { return bitrate; }
00053
00054             set { bitrate = value; }
00055         }
00056
00057         internal string UrlTemplate
00058         {
00059             get { return mediaUrlTemplate; }
00060
00061             set { mediaUrlTemplate = value; }
00062         }
00063
00064         internal string RepresentationID
00065         {
00066             get { return representationID; }
00067
00068             set { representationID = value; }
00069         }
00070
00071         #endregion
00072
00073     }
00074 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaTranscoding/cpp/pch.h Source File

  • MediaTranscoding
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OCR/cpp/OcrCapturedImage.xaml.h Source File

  • OCR
  • cpp

OcrCapturedImage.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "OcrCapturedImage.g.h"
00015 #include "MainPage.xaml.h"
00016 #include "WordOverlay.h"
00017
00018 #include <ppl.h>
00019
00020 using namespace Concurrency;
00021 using namespace Windows::Devices::Enumeration;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::Media::Capture;
00024 using namespace Windows::System::Display;
00025
00026 namespace SDKTemplate
00027 {
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class OcrCapturedImage sealed
00030     {
00031     public:
00032         OcrCapturedImage();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038     private:
00039         MainPage^ rootPage;
00040
00041         bool isAngleDetected;
00042
00043         // Language for OCR.
00044         Windows::Globalization::Language^ ocrLanguage;
00045
00046         // Recognized words ovelay boxes.
00047         std::vector<WordOverlay^> wordBoxes;
00048
00049         // Receive notifications about rotation of the UI and apply any necessary rotation to the preview stream.
00050         DisplayInformation^ displayInformation = DisplayInformation::GetForCurrentView();
00051
00052         // Prevent the screen from sleeping while the camera is running.
00053         DisplayRequest^ displayRequest = ref new DisplayRequest();
00054
00055         // MediaCapture and its state variables.
00056         Platform::Agile<MediaCapture> mediaCapture;
00057         bool isInitialized = false;
00058         bool isPreviewing = false;
00059
00060         // Information about the camera device.
00061         bool mirroringPreview = false;
00062         bool externalCamera = false;
00063
00064         int rotationDegrees;
00065         VideoRotation sourceRotation;
00066
00067         // Event handler tokens.
00068         Windows::Foundation::EventRegistrationToken orientationChangedEventToken;
00069         Windows::Foundation::EventRegistrationToken mediaCaptureFailedEventToken;
00070
00071         void UpdateWordBoxTransform();
00072         task<void> CalculatePreviewRotation();
00073
00074         task<void> StartCameraAsync();
00075         task<void> StartPreviewAsync();
00076         task<void> SetPreviewRotationAsync();
00077         task<void> InitializeCameraAsync();
00078         task<void> StopPreviewAsync();
00079         task<void> CleanupCameraAsync();
00080         task<DeviceInformation^> FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel desiredPanel);
00081
00082         void PreviewImage_SizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00083         void ExtractButton_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e);
00084         void CameraButton_Tapped(Platform::Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ e);
00085         void DisplayInformation_OrientationChanged(Windows::Graphics::Display::DisplayInformation ^sender, Platform::Object ^args);
00086         void MediaCapture_Failed(MediaCapture^ sender, MediaCaptureFailedEventArgs^ errorEventArgs);
00087         void Application_Suspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
00088         void Application_Resuming(Platform::Object^ sender, Platform::Object^ o);
00089     };
00090 }
Generated on Fri Nov 15 2024 22:20:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/StspMediaSink.cpp Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

StspMediaSink.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include <InitGuid.h>
00010 #include "StspMediaSink.h"
00011 #include "StspStreamSink.h"
00012 #include "StspMediaSinkProxy.h"
00013
00014 using namespace Microsoft::Samples::SimpleCommunication;
00015 using namespace Microsoft::Samples::SimpleCommunication::Network;
00016
00017 namespace
00018 {
00019     const DWORD c_cbReceiveBuffer = 8 * 1024;
00020
00021     class ShutdownFunc
00022     {
00023     public:
00024         HRESULT operator()(IMFStreamSink *pStream) const
00025         {
00026             static_cast<CStreamSink *>(pStream)->Shutdown();
00027             return S_OK;
00028         }
00029     };
00030
00031     class SetConnectedFunc
00032     {
00033     public:
00034         SetConnectedFunc(bool fConnected, LONGLONG llStartTime)
00035             : _fConnected(fConnected)
00036             , _llStartTime(llStartTime)
00037         {
00038         }
00039
00040         HRESULT operator()(IMFStreamSink *pStream) const
00041         {
00042             return static_cast<CStreamSink *>(pStream)->SetConnected(_fConnected, _llStartTime);
00043         }
00044
00045         bool _fConnected;
00046         LONGLONG _llStartTime;
00047     };
00048
00049     class StartFunc
00050     {
00051     public:
00052         StartFunc(LONGLONG llStartTime)
00053             : _llStartTime(llStartTime)
00054         {
00055         }
00056
00057         HRESULT operator()(IMFStreamSink *pStream) const
00058         {
00059             return static_cast<CStreamSink *>(pStream)->Start(_llStartTime);
00060         }
00061
00062         LONGLONG _llStartTime;
00063     };
00064
00065     class StopFunc
00066     {
00067     public:
00068         HRESULT operator()(IMFStreamSink *pStream) const
00069         {
00070             return static_cast<CStreamSink *>(pStream)->Stop();
00071         }
00072     };
00073
00074     template <class T, class TFunc>
00075     HRESULT ForEach(ComPtrList<T> &col, TFunc fn)
00076     {
00077         ComPtrList<T>::POSITION pos = col.FrontPosition();
00078         ComPtrList<T>::POSITION endPos = col.EndPosition();
00079         HRESULT hr = S_OK;
00080
00081         for (;pos != endPos; pos = col.Next(pos))
00082         {
00083             ComPtr<T> spStream;
00084
00085             hr = col.GetItemPos(pos, &spStream);
00086             if (FAILED(hr))
00087             {
00088                 break;
00089             }
00090
00091             hr = fn(spStream.Get());
00092         }
00093
00094         return hr;
00095     }
00096
00097     static void AddAttribute(_In_ GUID guidKey, _In_ IPropertyValue ^value, _In_ IMFAttributes *pAttr)
00098     {
00099         PropertyType type = value->Type;
00100         switch (type)
00101         {
00102             case PropertyType::UInt8Array:
00103             {
00104                 Array<BYTE>^ arr;
00105                 value->GetUInt8Array(&arr);
00106
00107                 ThrowIfError(pAttr->SetBlob(guidKey, arr->Data, arr->Length));
00108             }
00109             break;
00110
00111             case PropertyType::Double:
00112             {
00113                 ThrowIfError(pAttr->SetDouble(guidKey, value->GetDouble()));
00114             }
00115             break;
00116
00117             case PropertyType::Guid:
00118             {
00119                 ThrowIfError(pAttr->SetGUID(guidKey, value->GetGuid()));
00120             }
00121             break;
00122
00123             case PropertyType::String:
00124             {
00125                 ThrowIfError(pAttr->SetString(guidKey, value->GetString()->Data()));
00126             }
00127             break;
00128
00129             case PropertyType::UInt32:
00130             {
00131                 ThrowIfError(pAttr->SetUINT32(guidKey, value->GetUInt32()));
00132             }
00133             break;
00134
00135             case PropertyType::UInt64:
00136             {
00137                 ThrowIfError(pAttr->SetUINT64(guidKey, value->GetUInt64()));
00138             }
00139             break;
00140
00141             // ignore unknown values
00142         }
00143     }
00144
00145     void ConvertPropertiesToMediaType(_In_ IMediaEncodingProperties ^mep, _Outptr_ IMFMediaType **ppMT)
00146     {
00147         if (mep == nullptr || ppMT == nullptr)
00148         {
00149             throw ref new InvalidArgumentException();
00150         }
00151         ComPtr<IMFMediaType> spMT;
00152         *ppMT = nullptr;
00153         ThrowIfError(MFCreateMediaType(&spMT));
00154
00155         auto it = mep->Properties->First();
00156
00157         while (it->HasCurrent)
00158         {
00159             auto currentValue = it->Current;
00160             AddAttribute(currentValue->Key, safe_cast<IPropertyValue^>(currentValue->Value), spMT.Get());
00161             it->MoveNext();
00162         }
00163
00164         GUID guiMajorType = safe_cast<IPropertyValue^>(mep->Properties->Lookup(MF_MT_MAJOR_TYPE))->GetGuid();
00165
00166         if (guiMajorType != MFMediaType_Video && guiMajorType != MFMediaType_Audio)
00167         {
00168             Throw(E_UNEXPECTED);
00169         }
00170
00171         *ppMT = spMT.Detach();
00172     }
00173
00174     DWORD GetStreamId(Windows::Media::Capture::MediaStreamType mediaStreamType)
00175     {
00176         switch(mediaStreamType)
00177         {
00178         case Windows::Media::Capture::MediaStreamType::VideoRecord:
00179             return 0;
00180         case Windows::Media::Capture::MediaStreamType::Audio:
00181             return 1;
00182         }
00183
00184         throw ref new InvalidArgumentException();
00185     }
00186 }
00187
00188 CMediaSink::CMediaSink()
00189 : _cRef(1)
00190 , _IsShutdown(false)
00191 , _IsConnected(false)
00192 , _llStartTime(0)
00193 , _cStreamsEnded(0)
00194 , _waitingConnectionId(0)
00195 {
00196 }
00197
00198 CMediaSink::~CMediaSink()
00199 {
00200     assert(_IsShutdown);
00201 }
00202
00203 HRESULT CMediaSink::RuntimeClassInitialize(
00204     ISinkCallback ^callback,
00205     Windows::Media::MediaProperties::IMediaEncodingProperties ^audioEncodingProperties,
00206     Windows::Media::MediaProperties::IMediaEncodingProperties ^videoEncodingProperties
00207     )
00208 {
00209     try
00210     {
00211         _callback = callback;
00212         // Create network server
00213         INetworkServer ^server = CreateNetworkServer(c_wStspDefaultPort);
00214         _networkSender = safe_cast<INetworkChannel^>(server);
00215
00216         // Set up media streams
00217         SetMediaStreamProperties(MediaStreamType::Audio, audioEncodingProperties);
00218         SetMediaStreamProperties(MediaStreamType::VideoRecord, videoEncodingProperties);
00219
00220         // Start listening from the connection from the client.
00221         StartListening();
00222     }
00223     catch (Exception ^exc)
00224     {
00225         _callback = nullptr;
00226         if (_networkSender != nullptr)
00227         {
00228             _networkSender->Close();
00229         }
00230         _networkSender = nullptr;
00231         return exc->HResult;
00232     }
00233
00234     return S_OK;
00235 }
00236
00237 void CMediaSink::SetMediaStreamProperties(
00238     Windows::Media::Capture::MediaStreamType MediaStreamType,
00239     _In_opt_ Windows::Media::MediaProperties::IMediaEncodingProperties ^mediaEncodingProperties)
00240 {
00241     if (MediaStreamType != MediaStreamType::VideoRecord && MediaStreamType != MediaStreamType::Audio)
00242     {
00243         throw ref new InvalidArgumentException();
00244     }
00245
00246     RemoveStreamSink(GetStreamId(MediaStreamType));
00247     const unsigned int streamId = GetStreamId(MediaStreamType);
00248
00249     if (mediaEncodingProperties != nullptr)
00250     {
00251         ComPtr<IMFStreamSink> spStreamSink;
00252         ComPtr<IMFMediaType> spMediaType;
00253         ConvertPropertiesToMediaType(mediaEncodingProperties, &spMediaType);
00254         ThrowIfError(AddStreamSink(streamId, spMediaType.Get(), spStreamSink.GetAddressOf()));
00255     }
00256 }
00257
00258 //   IStspSinkInternal
00259 void CMediaSink::TriggerAcceptConnection(DWORD connectionId)
00260 {
00261     try
00262     {
00263         AutoLock lock(_critSec);
00264         ThrowIfError(CheckShutdown());
00265
00266         if (_waitingConnectionId != 0 && connectionId == _waitingConnectionId)
00267         {
00268             _waitingConnectionId = 0;
00269             ComPtr<CMediaSink> spThis = this;
00270             concurrency::create_task([this, spThis]
00271             {
00272                 AutoLock lock(_critSec);
00273                 try
00274                 {
00275                     ThrowIfError(CheckShutdown());
00276
00277                     // Create receive buffer
00278                     ThrowIfError(CreateMediaBufferWrapper(c_cbReceiveBuffer, &_spReceiveBuffer));
00279
00280                     // Start receiving
00281                     StartReceiving(_spReceiveBuffer.Get());
00282                 }
00283                 catch(Exception ^exc)
00284                 {
00285                     HandleError(exc->HResult);
00286                 }
00287             });
00288         }
00289     }
00290     catch(Exception^)
00291     {
00292     }
00293 }
00294
00295 void CMediaSink::TriggerRefuseConnection(DWORD connectionId)
00296 {
00297     try
00298     {
00299         AutoLock lock(_critSec);
00300         ThrowIfError(CheckShutdown());
00301
00302         if (_waitingConnectionId != 0 && connectionId == _waitingConnectionId)
00303         {
00304             _waitingConnectionId = 0;
00305             ComPtr<CMediaSink> spThis;
00306             concurrency::create_task([this, spThis]
00307             {
00308                 AutoLock lock(_critSec);
00309                 try
00310                 {
00311                     ThrowIfError(CheckShutdown());
00312
00313                     // Connection refused disconnect current client.
00314                     _networkSender->Disconnect();
00315
00316                     StartListening();
00317                 }
00318                 catch(Exception ^exc)
00319                 {
00320                     HandleError(exc->HResult);
00321                 }
00322             });
00323         }
00324     }
00325     catch(Exception^)
00326     {
00327     }
00328 }
00329
00330 ///  IMFMediaSink
00331 IFACEMETHODIMP CMediaSink::GetCharacteristics(DWORD *pdwCharacteristics)
00332 {
00333     if (pdwCharacteristics == NULL)
00334     {
00335         return E_INVALIDARG;
00336     }
00337     AutoLock lock(_critSec);
00338
00339     HRESULT hr = CheckShutdown();
00340
00341     if (SUCCEEDED(hr))
00342     {
00343         // Rateless sink.
00344         *pdwCharacteristics = MEDIASINK_RATELESS;
00345     }
00346
00347     TRACEHR_RET(hr);
00348 }
00349
00350 IFACEMETHODIMP CMediaSink::AddStreamSink(
00351     DWORD dwStreamSinkIdentifier,
00352     IMFMediaType *pMediaType,
00353     IMFStreamSink **ppStreamSink)
00354 {
00355     CStreamSink *pStream = nullptr;
00356     ComPtr<IMFStreamSink> spMFStream;
00357     AutoLock lock(_critSec);
00358     HRESULT hr = CheckShutdown();
00359
00360     if (SUCCEEDED(hr))
00361     {
00362         hr = GetStreamSinkById(dwStreamSinkIdentifier, &spMFStream);
00363     }
00364
00365     if (SUCCEEDED(hr))
00366     {
00367         hr = MF_E_STREAMSINK_EXISTS;
00368     }
00369     else
00370     {
00371         hr = S_OK;
00372     }
00373
00374     if (SUCCEEDED(hr))
00375     {
00376         pStream = new CStreamSink(dwStreamSinkIdentifier);
00377         if (pStream == nullptr)
00378         {
00379             hr = E_OUTOFMEMORY;
00380         }
00381         spMFStream.Attach(pStream);
00382     }
00383
00384     // Initialize the stream.
00385     if (SUCCEEDED(hr))
00386     {
00387         hr = pStream->Initialize(this, _networkSender);
00388     }
00389
00390     if (SUCCEEDED(hr) && pMediaType != nullptr)
00391     {
00392         hr = pStream->SetCurrentMediaType(pMediaType);
00393     }
00394
00395     if (SUCCEEDED(hr))
00396     {
00397         StreamContainer::POSITION pos = _streams.FrontPosition();
00398         StreamContainer::POSITION posEnd = _streams.EndPosition();
00399
00400         // Insert in proper position
00401         for (; pos != posEnd; pos = _streams.Next(pos))
00402         {
00403             DWORD dwCurrId;
00404             ComPtr<IMFStreamSink> spCurr;
00405             hr = _streams.GetItemPos(pos, &spCurr);
00406             if (FAILED(hr))
00407             {
00408                 break;
00409             }
00410             hr = spCurr->GetIdentifier(&dwCurrId);
00411             if (FAILED(hr))
00412             {
00413                 break;
00414             }
00415
00416             if (dwCurrId > dwStreamSinkIdentifier)
00417             {
00418                 break;
00419             }
00420         }
00421
00422         if (SUCCEEDED(hr))
00423         {
00424             hr = _streams.InsertPos(pos, pStream);
00425         }
00426     }
00427
00428     if (SUCCEEDED(hr))
00429     {
00430         *ppStreamSink = spMFStream.Detach();
00431     }
00432
00433     TRACEHR_RET(hr);
00434 }
00435
00436 IFACEMETHODIMP CMediaSink::RemoveStreamSink(DWORD dwStreamSinkIdentifier)
00437 {
00438     AutoLock lock(_critSec);
00439     HRESULT hr = CheckShutdown();
00440     StreamContainer::POSITION pos = _streams.FrontPosition();
00441     StreamContainer::POSITION endPos = _streams.EndPosition();
00442     ComPtr<IMFStreamSink> spStream;
00443
00444     if (SUCCEEDED(hr))
00445     {
00446         for (;pos != endPos; pos = _streams.Next(pos))
00447         {
00448             hr = _streams.GetItemPos(pos, &spStream);
00449             DWORD dwId;
00450
00451             if (FAILED(hr))
00452             {
00453                 break;
00454             }
00455
00456             hr = spStream->GetIdentifier(&dwId);
00457             if (FAILED(hr) || dwId == dwStreamSinkIdentifier)
00458             {
00459                 break;
00460             }
00461         }
00462
00463         if (pos == endPos)
00464         {
00465             hr = MF_E_INVALIDSTREAMNUMBER;
00466         }
00467     }
00468
00469     if (SUCCEEDED(hr))
00470     {
00471         hr = _streams.Remove(pos, nullptr);
00472         static_cast<CStreamSink *>(spStream.Get())->Shutdown();
00473     }
00474
00475     TRACEHR_RET(hr);
00476 }
00477
00478 IFACEMETHODIMP CMediaSink::GetStreamSinkCount(_Out_ DWORD *pcStreamSinkCount)
00479 {
00480     if (pcStreamSinkCount == NULL)
00481     {
00482         return E_INVALIDARG;
00483     }
00484
00485     AutoLock lock(_critSec);
00486
00487     HRESULT hr = CheckShutdown();
00488
00489     if (SUCCEEDED(hr))
00490     {
00491         *pcStreamSinkCount = _streams.GetCount();
00492     }
00493
00494     TRACEHR_RET(hr);
00495 }
00496
00497 IFACEMETHODIMP CMediaSink::GetStreamSinkByIndex(
00498 DWORD dwIndex,
00499 _Outptr_ IMFStreamSink **ppStreamSink)
00500 {
00501     if (ppStreamSink == NULL)
00502     {
00503         return E_INVALIDARG;
00504     }
00505
00506     ComPtr<IMFStreamSink> spStream;
00507     AutoLock lock(_critSec);
00508     DWORD cStreams = _streams.GetCount();
00509
00510     if (dwIndex >= cStreams)
00511     {
00512         return MF_E_INVALIDINDEX;
00513     }
00514
00515     HRESULT hr = CheckShutdown();
00516
00517     if (SUCCEEDED(hr))
00518     {
00519         StreamContainer::POSITION pos = _streams.FrontPosition();
00520         StreamContainer::POSITION endPos = _streams.EndPosition();
00521         DWORD dwCurrent = 0;
00522
00523         for (;pos != endPos && dwCurrent < dwIndex; pos = _streams.Next(pos), ++dwCurrent)
00524         {
00525             // Just move to proper position
00526         }
00527
00528         if (pos == endPos)
00529         {
00530             hr = MF_E_UNEXPECTED;
00531         }
00532         else
00533         {
00534             hr = _streams.GetItemPos(pos, &spStream);
00535         }
00536     }
00537
00538     if (SUCCEEDED(hr))
00539     {
00540         *ppStreamSink = spStream.Detach();
00541     }
00542
00543     TRACEHR_RET(hr);
00544 }
00545
00546 IFACEMETHODIMP CMediaSink::GetStreamSinkById(
00547 DWORD dwStreamSinkIdentifier,
00548 IMFStreamSink **ppStreamSink)
00549 {
00550     if (ppStreamSink == NULL)
00551     {
00552         return E_INVALIDARG;
00553     }
00554
00555     AutoLock lock(_critSec);
00556     HRESULT hr = CheckShutdown();
00557     ComPtr<IMFStreamSink> spResult;
00558
00559     if (SUCCEEDED(hr))
00560     {
00561         StreamContainer::POSITION pos = _streams.FrontPosition();
00562         StreamContainer::POSITION endPos = _streams.EndPosition();
00563
00564         for (;pos != endPos; pos = _streams.Next(pos))
00565         {
00566             ComPtr<IMFStreamSink> spStream;
00567             hr = _streams.GetItemPos(pos, &spStream);
00568             DWORD dwId;
00569
00570             if (FAILED(hr))
00571             {
00572                 break;
00573             }
00574
00575             hr = spStream->GetIdentifier(&dwId);
00576             if (FAILED(hr))
00577             {
00578                 break;
00579             }
00580             else if (dwId == dwStreamSinkIdentifier)
00581             {
00582                 spResult = spStream;
00583                 break;
00584             }
00585         }
00586
00587         if (pos == endPos)
00588         {
00589             hr = MF_E_INVALIDSTREAMNUMBER;
00590         }
00591     }
00592
00593     if (SUCCEEDED(hr))
00594     {
00595         assert(spResult);
00596         *ppStreamSink = spResult.Detach();
00597     }
00598
00599     TRACEHR_RET(hr);
00600 }
00601
00602 IFACEMETHODIMP CMediaSink::SetPresentationClock(IMFPresentationClock *pPresentationClock)
00603 {
00604     AutoLock lock(_critSec);
00605
00606     HRESULT hr = CheckShutdown();
00607
00608     // If we already have a clock, remove ourselves from that clock's
00609     // state notifications.
00610     if (SUCCEEDED(hr))
00611     {
00612         if (_spClock)
00613         {
00614             hr = _spClock->RemoveClockStateSink(this);
00615         }
00616     }
00617
00618     // Register ourselves to get state notifications from the new clock.
00619     if (SUCCEEDED(hr))
00620     {
00621         if (pPresentationClock)
00622         {
00623             hr = pPresentationClock->AddClockStateSink(this);
00624         }
00625     }
00626
00627     if (SUCCEEDED(hr))
00628     {
00629         // Release the pointer to the old clock.
00630         // Store the pointer to the new clock.
00631         _spClock = pPresentationClock;
00632     }
00633
00634     TRACEHR_RET(hr);
00635 }
00636
00637 IFACEMETHODIMP CMediaSink::GetPresentationClock(IMFPresentationClock **ppPresentationClock)
00638 {
00639     if (ppPresentationClock == NULL)
00640     {
00641         return E_INVALIDARG;
00642     }
00643
00644     AutoLock lock(_critSec);
00645
00646     HRESULT hr = CheckShutdown();
00647
00648     if (SUCCEEDED(hr))
00649     {
00650         if (_spClock == NULL)
00651         {
00652             hr = MF_E_NO_CLOCK; // There is no presentation clock.
00653         }
00654         else
00655         {
00656             // Return the pointer to the caller.
00657             *ppPresentationClock = _spClock.Get();
00658             (*ppPresentationClock)->AddRef();
00659         }
00660     }
00661
00662     TRACEHR_RET(hr);
00663 }
00664
00665 IFACEMETHODIMP CMediaSink::Shutdown()
00666 {
00667     ISinkCallback ^callback;
00668     {
00669         AutoLock lock(_critSec);
00670
00671         HRESULT hr = CheckShutdown();
00672
00673         if (SUCCEEDED(hr))
00674         {
00675             ForEach(_streams, ShutdownFunc());
00676             _streams.Clear();
00677
00678             if (_networkSender != nullptr)
00679             {
00680                 _networkSender->Close();
00681             }
00682
00683             _networkSender = nullptr;
00684             _spClock.Reset();
00685
00686             _IsShutdown = true;
00687             callback = _callback;
00688         }
00689     }
00690
00691     if (callback != nullptr)
00692     {
00693         callback->OnShutdown();
00694     }
00695
00696     return S_OK;
00697 }
00698
00699 // IMFClockStateSink
00700 IFACEMETHODIMP CMediaSink::OnClockStart(
00701                                         MFTIME hnsSystemTime,
00702                                         LONGLONG llClockStartOffset)
00703 {
00704     AutoLock lock(_critSec);
00705
00706     HRESULT hr = CheckShutdown();
00707
00708     if (SUCCEEDED(hr))
00709     {
00710         TRACE(TRACE_LEVEL_LOW, L"OnClockStart ts=%I64d\n", llClockStartOffset);
00711         // Start each stream.
00712         _llStartTime = llClockStartOffset;
00713         hr = ForEach(_streams, StartFunc(llClockStartOffset));
00714     }
00715
00716     TRACEHR_RET(hr);
00717 }
00718
00719 IFACEMETHODIMP CMediaSink::OnClockStop(
00720                                        MFTIME hnsSystemTime)
00721 {
00722     AutoLock lock(_critSec);
00723
00724     HRESULT hr = CheckShutdown();
00725
00726     if (SUCCEEDED(hr))
00727     {
00728         // Stop each stream
00729         hr = ForEach(_streams, StopFunc());
00730     }
00731
00732     TRACEHR_RET(hr);
00733 }
00734
00735
00736 IFACEMETHODIMP CMediaSink::OnClockPause(
00737                                         MFTIME hnsSystemTime)
00738 {
00739     return MF_E_INVALID_STATE_TRANSITION;
00740 }
00741
00742 IFACEMETHODIMP CMediaSink::OnClockRestart(
00743 MFTIME hnsSystemTime)
00744 {
00745     return MF_E_INVALID_STATE_TRANSITION;
00746 }
00747
00748 IFACEMETHODIMP CMediaSink::OnClockSetRate(
00749 /* [in] */ MFTIME hnsSystemTime,
00750 /* [in] */ float flRate)
00751 {
00752     return S_OK;
00753 }
00754
00755 void CMediaSink::ReportEndOfStream()
00756 {
00757     AutoLock lock(_critSec);
00758     ++_cStreamsEnded;
00759 }
00760
00761 /// Private methods
00762 // Start listening on the network server
00763 void CMediaSink::StartListening()
00764 {
00765     ComPtr<CMediaSink> spThis = this;
00766     concurrency::create_task(safe_cast<INetworkServer^>(_networkSender)->AcceptAsync()).then([spThis, this](concurrency::task<StreamSocketInformation^>& acceptTask)
00767     {
00768         IncomingConnectionEventArgs ^args;
00769         ISinkCallback ^callback;
00770         try
00771         {
00772             {
00773                 AutoLock lock(_critSec);
00774                 auto info = acceptTask.get();
00775                 ThrowIfError(CheckShutdown());
00776                 if (_callback == nullptr)
00777                 {
00778                     Throw(E_UNEXPECTED);
00779                 }
00780                 _remoteUrl = PrepareRemoteUrl(info);
00781
00782                 _waitingConnectionId = LODWORD(GetTickCount64());
00783                 if (_waitingConnectionId == 0)
00784                 {
00785                     ++_waitingConnectionId;
00786                 }
00787
00788                 args = ref new IncomingConnectionEventArgs(this, _waitingConnectionId, _remoteUrl);
00789                 callback = _callback;
00790             }
00791
00792             callback->FireIncomingConnection(args);
00793         }
00794         catch(Exception ^exc)
00795         {
00796             AutoLock lock(_critSec);
00797             HandleError(exc->HResult);
00798         }
00799     });
00800 }
00801
00802 void CMediaSink::StartReceiving(IMediaBufferWrapper *pReceiveBuffer)
00803 {
00804     ComPtr<CMediaSink> spThis = this;
00805     ComPtr<IMediaBufferWrapper> spReceiveBuffer = pReceiveBuffer;
00806
00807     concurrency::create_task(_networkSender->ReceiveAsync(pReceiveBuffer)).then([spThis, spReceiveBuffer, this](concurrency::task<void>& task)
00808     {
00809         AutoLock lock(_critSec);
00810         try
00811         {
00812             StspOperation eOp = StspOperation_Unknown;
00813             task.get();
00814             ThrowIfError(CheckShutdown());
00815
00816             BYTE *pBuf = spReceiveBuffer->GetBuffer();
00817             DWORD cbCurrentLen;
00818             spReceiveBuffer->GetMediaBuffer()->GetCurrentLength(&cbCurrentLen);
00819
00820             // Validate if the data received from the client is sufficient to fit operation header which is the smallest size of message that we can handle.
00821             if (cbCurrentLen != sizeof(StspOperationHeader))
00822             {
00823                 Throw(MF_E_INVALID_FORMAT);
00824             }
00825
00826             StspOperationHeader *pOpHeader = reinterpret_cast<StspOperationHeader *>(pBuf);
00827             // We only support client's request for media description
00828             if (pOpHeader->cbDataSize != 0 ||
00829                 ((pOpHeader->eOperation != StspOperation_ClientRequestDescription) &&
00830                 (pOpHeader->eOperation != StspOperation_ClientRequestStart) &&
00831                 (pOpHeader->eOperation != StspOperation_ClientRequestStop)))
00832             {
00833                 Throw(MF_E_INVALID_FORMAT);
00834             }
00835             else
00836             {
00837                 eOp = pOpHeader->eOperation;
00838             }
00839
00840             switch(eOp)
00841             {
00842             case StspOperation_ClientRequestDescription:
00843                 // Send description to the client
00844                 SendDescription();
00845                 break;
00846             case StspOperation_ClientRequestStart:
00847                 {
00848                     _IsConnected = true;
00849                     if (_spClock)
00850                     {
00851                         ThrowIfError(_spClock->GetTime(&_llStartTime));
00852                     }
00853
00854                     // We are now connected we can start streaming.
00855                     ForEach(_streams, SetConnectedFunc(true, _llStartTime));
00856                 }
00857                 break;
00858             default:
00859                 Throw(MF_E_INVALID_FORMAT);
00860                 break;
00861             }
00862         }
00863         catch(Exception ^exc)
00864         {
00865             HandleError(exc->HResult);
00866         }
00867     });
00868 }
00869
00870 // Send packet
00871 concurrency::task<void> CMediaSink::SendPacket(Network::IBufferPacket *pPacket)
00872 {
00873     return concurrency::create_task(_networkSender->SendAsync(pPacket));
00874 }
00875
00876 // Send media description to the client
00877 void CMediaSink::SendDescription()
00878 {
00879     // Size of the description buffer
00880     const DWORD c_cStreams = _streams.GetCount();
00881     const DWORD c_cbDescriptionSize = sizeof(StspDescription) + (c_cStreams-1) * sizeof(StspStreamDescription);
00882     const DWORD c_cbPacketSize = sizeof(StspOperationHeader) + c_cbDescriptionSize;
00883
00884     ComPtr<IMediaBufferWrapper> spBuffer;
00885     ComPtr<IMediaBufferWrapper> *arrspAttributes = new ComPtr<IMediaBufferWrapper>[c_cStreams];
00886     if (arrspAttributes == nullptr)
00887     {
00888         Throw(E_OUTOFMEMORY);
00889     }
00890
00891     try
00892     {
00893         // Create send buffer
00894         ThrowIfError(CreateMediaBufferWrapper(c_cbPacketSize, &spBuffer));
00895
00896         // Prepare operation header
00897         BYTE *pBuf = spBuffer->GetBuffer();
00898         StspOperationHeader *pOpHeader = reinterpret_cast<StspOperationHeader *>(pBuf);
00899         pOpHeader->cbDataSize = c_cbDescriptionSize;
00900         pOpHeader->eOperation = StspOperation_ServerDescription;
00901
00902         // Prepare description
00903         StspDescription *pDescription = reinterpret_cast<StspDescription *>(pBuf + sizeof(StspOperationHeader));
00904         pDescription->cNumStreams = c_cStreams;
00905
00906         StreamContainer::POSITION pos = _streams.FrontPosition();
00907         StreamContainer::POSITION endPos = _streams.EndPosition();
00908         DWORD nStream = 0;
00909         for (;pos != endPos; pos = _streams.Next(pos), ++nStream)
00910         {
00911             ComPtr<IMFStreamSink> spStream;
00912             ThrowIfError(_streams.GetItemPos(pos, &spStream));
00913
00914             // Fill out stream description
00915             arrspAttributes[nStream] = FillStreamDescription(static_cast<CStreamSink *>(spStream.Get()), &pDescription->aStreams[nStream]);
00916
00917             // Add size of variable size attribute blob to size of the package.
00918             pOpHeader->cbDataSize += pDescription->aStreams[nStream].cbAttributesSize;
00919         }
00920
00921         // Set length of the packet
00922         ThrowIfError(spBuffer->SetCurrentLength(c_cbPacketSize));
00923
00924         // Prepare packet to send
00925         ComPtr<IBufferPacket> spPacket;
00926
00927         ThrowIfError(CreateBufferPacket(&spPacket));
00928         // Add fixed size header and description to the packet
00929         ThrowIfError(spPacket->AddBuffer(spBuffer.Get()));
00930
00931         for (DWORD nStream = 0; nStream < c_cStreams; ++nStream)
00932         {
00933             // Add variable size attributes.
00934             ThrowIfError(spPacket->AddBuffer(arrspAttributes[nStream].Get()));
00935         }
00936
00937         ComPtr<CMediaSink> spThis = this;
00938         // Send the data.
00939         SendPacket(spPacket.Get()).then([this, spThis](concurrency::task<void>& task)
00940         {
00941             try
00942             {
00943                 task.get();
00944             }
00945             catch(Exception ^exc)
00946             {
00947                 AutoLock lock(_critSec);
00948                 HandleError(exc->HResult);
00949             }
00950         });
00951
00952         // Keep receiving
00953         StartReceiving(_spReceiveBuffer.Get());
00954
00955         delete[] arrspAttributes;
00956     }
00957     catch(Exception ^exc)
00958     {
00959         delete[] arrspAttributes;
00960         throw;
00961     }
00962 }
00963
00964 // Fill stream description and prepare attributes blob.
00965 ComPtr<Network::IMediaBufferWrapper> CMediaSink::FillStreamDescription(CStreamSink *pStream, StspStreamDescription *pStreamDescription)
00966 {
00967     assert(pStream != nullptr);
00968     assert(pStreamDescription != nullptr);
00969
00970     ComPtr<IMFMediaType> spMediaType;
00971
00972     // Get current media type
00973     ThrowIfError(pStream->GetCurrentMediaType(&spMediaType));
00974
00975     return pStream->FillStreamDescription(spMediaType.Get(), pStreamDescription);
00976 }
00977
00978 void CMediaSink::HandleError(HRESULT hr)
00979 {
00980     Shutdown();
00981 }
00982
00983 String ^CMediaSink::PrepareRemoteUrl(StreamSocketInformation ^info)
00984 {
00985     WCHAR szBuffer[MAX_PATH];
00986
00987     if ( info->RemoteHostName->Type == HostNameType::Ipv4 || info->RemoteHostName->Type == HostNameType::DomainName)
00988     {
00989         ThrowIfError(StringCchPrintf(szBuffer, _countof(szBuffer), L"%s://%s", c_szStspScheme, info->RemoteHostName->RawName->Data()));
00990     }
00991     else if (info->RemoteHostName->Type == HostNameType::Ipv6)
00992     {
00993         ThrowIfError(StringCchPrintf(szBuffer, _countof(szBuffer), L"%s://[%s]", c_szStspScheme, info->RemoteHostName->RawName->Data()));
00994     }
00995     else
00996     {
00997         throw ref new InvalidArgumentException();
00998     }
00999
01000     return ref new String(szBuffer);
01001 }
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FileItem Member List

This is the complete list of members for FileItem, including all inherited members.
Filename | FileItem |
fromStorageFile(StorageFile f, CancellationToken ct) | FileItem | [inline, static]
gettingFileProperties | FileItem | [private, static]
ImageData | FileItem |
Key | FileItem |
Size | FileItem |
Generated on Fri Nov 15 2024 22:23:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioBindingConverter Member List

This is the complete list of members for ScenarioBindingConverter, including all inherited members.
Convert(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | ScenarioBindingConverter | [inline]
Generated on Fri Nov 15 2024 22:24:01 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStarterKit/cpp/MainPage.xaml.h Source File

  • CameraStarterKit
  • cpp

MainPage.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "MainPage.g.h"
00015 #include "CameraRotationHelper.h"
00016
00017 namespace CameraStarterKit
00018 {
00019     ref class ReencodeState sealed
00020     {
00021     internal:
00022         Windows::Graphics::Imaging::BitmapDecoder^ Decoder;
00023         Windows::Graphics::Imaging::BitmapEncoder^ Encoder;
00024         Windows::Storage::StorageFile^ File;
00025         Windows::Storage::FileProperties::PhotoOrientation Orientation;
00026     };
00027
00028     public ref class MainPage sealed
00029     {
00030     private:
00031         // Rotation Helper to simplify handling rotation compensation for the camera streams
00032         CameraRotationHelper^ _rotationHelper;
00033
00034         // Prevent the screen from sleeping while the camera is running
00035         Windows::System::Display::DisplayRequest^ _displayRequest;
00036
00037         // For listening to media property changes
00038         Windows::Media::SystemMediaTransportControls^ _systemMediaControls;
00039
00040         // MediaCapture and its state variables
00041         Platform::Agile<Windows::Media::Capture::MediaCapture^> _mediaCapture;
00042         bool _isInitialized;
00043         bool _isPreviewing;
00044         bool _isRecording;
00045
00046         // UI state
00047         bool _isSuspending = false;
00048         bool _isActivePage = false;
00049         bool _isUIActive = false;
00050         concurrency::task<void> _setupTask = concurrency::task_from_result();
00051
00052         // Information about the camera device
00053         bool _externalCamera;
00054         bool _mirroringPreview;
00055
00056         // Rotation metadata to apply to the preview stream and recorded videos (MF_MT_VIDEO_ROTATION)
00057         // Reference: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868174.aspx
00058         const GUID RotationKey;
00059
00060         // Folder in which the captures will be stored (availability check performed in SetupUiAsync)
00061         Windows::Storage::StorageFolder^ _captureFolder;
00062
00063         // Event tokens
00064         Windows::Foundation::EventRegistrationToken _applicationSuspendingEventToken;
00065         Windows::Foundation::EventRegistrationToken _applicationResumingEventToken;
00066         Windows::Foundation::EventRegistrationToken _windowVisibilityChangedEventToken;
00067         Windows::Foundation::EventRegistrationToken _mediaControlPropChangedEventToken;
00068         Windows::Foundation::EventRegistrationToken _displayInformationEventToken;
00069         Windows::Foundation::EventRegistrationToken _recordLimitationExceededEventToken;
00070         Windows::Foundation::EventRegistrationToken _mediaCaptureFailedEventToken;
00071         Windows::Foundation::EventRegistrationToken _orientationChangedEventToken;
00072         Windows::Foundation::EventRegistrationToken _hardwareCameraButtonEventToken;
00073
00074         // MediaCapture methods
00075         Concurrency::task<void> InitializeCameraAsync();
00076         Concurrency::task<void> CleanupCameraAsync();
00077         Concurrency::task<void> StartPreviewAsync();
00078         Concurrency::task<void> SetPreviewRotationAsync();
00079         Concurrency::task<void> StopPreviewAsync();
00080         Concurrency::task<void> TakePhotoAsync();
00081         Concurrency::task<void> StartRecordingAsync();
00082         Concurrency::task<void> StopRecordingAsync();
00083
00084         // Helpers
00085         Concurrency::task<Windows::Devices::Enumeration::DeviceInformation^> FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel panel);
00086         Concurrency::task<void> ReencodeAndSavePhotoAsync(Windows::Storage::Streams::IRandomAccessStream^ stream, Windows::Storage::StorageFile^ file, Windows::Storage::FileProperties::PhotoOrientation photoOrientation);
00087         void UpdateCaptureControls();
00088         Concurrency::task<void> SetUpBasedOnStateAsync();
00089         Concurrency::task<void> SetupUiAsync();
00090         Concurrency::task<void> CleanupUiAsync();
00091         void RegisterEventHandlers();
00092         void UnregisterEventHandlers();
00093         void WriteLine(Platform::String^ str);
00094         void WriteException(Platform::Exception^ ex);
00095         void UpdateButtonOrientation();
00096
00097         // UI event handlers
00098         void Application_Suspending(Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
00099         void Application_Resuming(Object^ sender, Object^ args);
00100         void Window_VisibilityChanged(Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00101         void PhotoButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00102         void VideoButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00103         void SystemMediaControls_PropertyChanged(Windows::Media::SystemMediaTransportControls^ sender, Windows::Media::SystemMediaTransportControlsPropertyChangedEventArgs^ args);
00104         void RotationHelper_OrientationChanged(Object^, bool);
00105         void HardwareButtons_CameraPressed(Platform::Object^, Windows::Phone::UI::Input::CameraEventArgs^);
00106
00107         // Camera event handlers
00108         void HardwareButtons_CameraPress(Platform::Object^, Windows::Phone::UI::Input::CameraEventArgs^);
00109         void MediaCapture_RecordLimitationExceeded(Windows::Media::Capture::MediaCapture ^currentCaptureObject);
00110         void MediaCapture_Failed(Windows::Media::Capture::MediaCapture ^currentCaptureObject, Windows::Media::Capture::MediaCaptureFailedEventArgs^ errorEventArgs);
00111
00112     protected:
00113         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00114         virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00115
00116     public:
00117         MainPage();
00118         virtual ~MainPage();
00119     };
00120 }
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cs/Tasks/Properties/AssemblyInfo.cs Source File

  • DeviceEnumerationAndPairing
  • cs
  • Tasks
  • Properties

AssemblyInfo.cs

Go to the documentation of this file.
00001 ﻿using System.Reflection;
00002 using System.Runtime.CompilerServices;
00003 using System.Runtime.InteropServices;
00004
00005 // General Information about an assembly is controlled through the following
00006 // set of attributes. Change these attribute values to modify the information
00007 // associated with an assembly.
00008 [assembly: AssemblyTitle("BackgroundDeviceWatcherTaskCs")]
00009 [assembly: AssemblyDescription("")]
00010 [assembly: AssemblyConfiguration("")]
00011 [assembly: AssemblyCompany("Microsoft Corporation")]
00012 [assembly: AssemblyProduct("BackgroundDeviceWatcherTaskCs")]
00013 [assembly: AssemblyCopyright("Copyright © Microsoft Corporation 2015")]
00014 [assembly: AssemblyTrademark("")]
00015 [assembly: AssemblyCulture("")]
00016
00017 // Version information for an assembly consists of the following four values:
00018 //
00019 //      Major Version
00020 //      Minor Version
00021 //      Build Number
00022 //      Revision
00023 //
00024 // You can specify all the values or you can default the Build and Revision Numbers
00025 // by using the '*' as shown below:
00026 // [assembly: AssemblyVersion("1.0.*")]
00027 [assembly: AssemblyVersion("1.0.0.0")]
00028 [assembly: AssemblyFileVersion("1.0.0.0")]
00029 [assembly: ComVisible(false)]
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Barometer/cpp/Scenario2_Polling.xaml.h Source File

  • Barometer
  • cpp

Scenario2_Polling.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_Polling.xaml.h
00014 // Declaration of the Scenario2_Polling class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario2_Polling.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario2_Polling sealed
00030     {
00031     public:
00032         Scenario2_Polling();
00033
00034     private:
00035         SDKTemplate::MainPage^ rootPage;
00036         Windows::UI::Core::CoreDispatcher^ dispatcher;
00037         Windows::Devices::Sensors::Barometer^ sensor;
00038
00039         void ScenarioGetData(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040     };
00041 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/Scenario1_SimpleListView.h Source File

  • XamlListView
  • cppwinrt

Scenario1_SimpleListView.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "Scenario1_SimpleListView.g.h"
00014
00015 namespace winrt::SDKTemplate::implementation
00016 {
00017     struct Scenario1_SimpleListView : Scenario1_SimpleListViewT<Scenario1_SimpleListView>
00018     {
00019         Scenario1_SimpleListView();
00020     };
00021 }
00022
00023 namespace winrt::SDKTemplate::factory_implementation
00024 {
00025     struct Scenario1_SimpleListView : Scenario1_SimpleListViewT<Scenario1_SimpleListView, implementation::Scenario1_SimpleListView>
00026     {
00027     };
00028 }
Generated on Fri Nov 15 2024 22:22:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProximitySensor/cpp/pch.h Source File

  • ProximitySensor
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AutoLock Member List

This is the complete list of members for AutoLock, including all inherited members.
_Acquires_lock_(m_pCriticalSection) AutoLock(CritSec &crit) | AutoLock | [inline]
_Releases_lock_(m_pCriticalSection)~AutoLock() | AutoLock | [inline]
m_pCriticalSection | AutoLock | [private]
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FxCompile Member List

This is the complete list of members for FxCompile, including all inherited members.
AddCommandLineCommands(CommandLineBuilderExtension commandLine) | FxCompile | [inline, protected]
AddCommandLineCommands(CommandLineBuilderExtension commandLine) | FxCompile | [inline, protected]
AdditionalIncludeDirectories | FxCompile |
AddResponseFileCommands(CommandLineBuilderExtension commandLine) | FxCompile | [inline, protected, virtual]
AddResponseFileCommands(CommandLineBuilderExtension commandLine) | FxCompile | [inline, protected, virtual]
AssemblerOutput | FxCompile |
AssemblerOutputFile | FxCompile |
bag | FxCompile | [private]
Bag | FxCompile | [protected]
DisableOptimizations | FxCompile |
EnableDebuggingInformation | FxCompile |
EntryPointName | FxCompile |
FxCompile() | FxCompile | [inline]
FxCompile() | FxCompile | [inline]
GenerateCommandLineCommands() | FxCompile | [inline, protected]
GenerateCommandLineCommands() | FxCompile | [inline, protected]
GenerateFullPathToTool() | FxCompile | [inline, protected]
GenerateFullPathToTool() | FxCompile | [inline, protected]
GenerateResponseFileCommands() | FxCompile | [inline, protected]
GenerateResponseFileCommands() | FxCompile | [inline, protected]
GetBoolParameterWithDefault(string parameterName, bool defaultValue) | FxCompile | [inline, protected]
GetBoolParameterWithDefault(string parameterName, bool defaultValue) | FxCompile | [inline, protected]
HeaderFileOutput | FxCompile |
ObjectFileOutput | FxCompile |
PreprocessorDefinitions | FxCompile |
SdkToolsPath | FxCompile |
ShaderModel | FxCompile |
ShaderType | FxCompile |
Source | FxCompile |
SuppressStartupBanner | FxCompile |
ToolName | FxCompile | [protected]
TreatWarningAsError | FxCompile |
VariableName | FxCompile |
Generated on Fri Nov 15 2024 22:23:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cs/Scenario7_FirmwareAccess.xaml.cs Source File

  • CustomCapability
  • cs

Scenario7_FirmwareAccess.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Runtime.InteropServices;
00014 using System.Text;
00015 using Windows.UI.Xaml;
00016
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class FirmwareAccess
00021     {
00022         MainPage rootPage = MainPage.Current;
00023
00024         public FirmwareAccess()
00025         {
00026             this.InitializeComponent();
00027         }
00028
00029         [DllImport("Kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
00030         public static extern int GetFirmwareEnvironmentVariable(string name, string guid,
00031         [Out, MarshalAs(UnmanagedType.LPArray)] char[] lpszBuffer, int size);
00032
00033         [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
00034         public static extern uint GetLastError();
00035
00036         [DllImport("rpcclient.dll", CharSet = CharSet.Unicode)]
00037         extern static uint GetManufacturerNameFromSmbios(StringBuilder ManufacturerName, uint Size);
00038
00039         [DllImport("rpcclient.dll", CharSet = CharSet.Unicode)]
00040         extern static uint GetSecureBootEnabledFromUefi([MarshalAs(UnmanagedType.U1)] ref bool SecureBootEnabled);
00041
00042         const uint ERROR_SUCCESS = 0;
00043         const uint ERROR_INVALID_FUNCTION = 1;
00044
00045         void GetManufacturerName_Click(Object sender, RoutedEventArgs e)
00046         {
00047             const int maxNameLength = 255;
00048             StringBuilder name = new StringBuilder(maxNameLength);
00049
00050             uint error = GetManufacturerNameFromSmbios(name, (uint)name.Capacity);
00051             if (error == ERROR_SUCCESS)
00052             {
00053                 ManufacturerName.Text = name.ToString();
00054             }
00055             else
00056             {
00057                 rootPage.NotifyUser($"Failed to retrieve manufacturer name from SMBIOS, error {error}", NotifyType.ErrorMessage);
00058             }
00059         }
00060
00061         void SecureBootState_Click(Object sender, RoutedEventArgs e)
00062         {
00063             bool secureBootEnabled = false;
00064
00065             uint error = GetSecureBootEnabledFromUefi(ref secureBootEnabled);
00066             switch (error)
00067             {
00068                 case ERROR_SUCCESS:
00069                 SecureBootState.Text = secureBootEnabled.ToString();
00070                     break;
00071
00072                 case ERROR_INVALID_FUNCTION:
00073                     rootPage.NotifyUser("Windows was installed using legacy BIOS", NotifyType.ErrorMessage);
00074                     break;
00075
00076                 default:
00077                     rootPage.NotifyUser($"Failed to retrieve secure boot state from UEFI, error {error}", NotifyType.ErrorMessage);
00078                     break;
00079             }
00080         }
00081     }
00082 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HotspotAuthentication/cs/Scenario2_BackgroundTask.xaml.cs Source File

  • HotspotAuthentication
  • cs

Scenario2_BackgroundTask.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using HotspotAuthenticationTask;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015
00016 namespace SDKTemplate
00017 {
00018     /// <summary>
00019     /// This page is used to handle authentication by background task scenario
00020     /// </summary>
00021     public sealed partial class Scenario2_BackgroundTask : Page
00022     {
00023         // A pointer back to the main page.  This is needed if you call methods in MainPage such as NotifyUser()
00024         MainPage rootPage = MainPage.Current;
00025         public Scenario2_BackgroundTask()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         /// <summary>
00031         /// Invoked when this page is about to be displayed in a Frame.
00032         /// </summary>
00033         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00034         /// property is typically used to configure the page.</param>
00035         protected override void OnNavigatedTo(NavigationEventArgs e)
00036         {
00037             // Configure background task handler to perform authentication
00038             ConfigStore.AuthenticateThroughBackgroundTask = true;
00039
00040             // Setup completion handler
00041             ScenarioCommon.Instance.RegisteredCompletionHandlerForBackgroundTask();
00042         }
00043     }
00044 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_SettingContainer Member List

This is the complete list of members for Scenario3_SettingContainer, including all inherited members.
containerName | Scenario3_SettingContainer | [inline, private, static]
CreateContainer_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_SettingContainer |
DeleteContainer_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_SettingContainer |
DeleteSetting_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_SettingContainer |
DisplayOutput() | Scenario3_SettingContainer | [private]
localSettings | Scenario3_SettingContainer | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario3_SettingContainer |
Scenario3_SettingContainer() | Scenario3_SettingContainer |
settingName | Scenario3_SettingContainer | [inline, private, static]
WriteSetting_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_SettingContainer |
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario5.xaml.h Source File

  • MapControl
  • cpp

Scenario5.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario5.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario5 sealed
00024     {
00025     public:
00026         Scenario5();
00027     private:
00028         MainPage^ rootPage = MainPage::Current;
00029         concurrency::task<void> Scenario5::nearbyStreetside(Windows::Devices::Geolocation::Geopoint^ spaceNeedlePoint);
00030         void showStreetSideNearSpaceneedle_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00031         void myMap_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032     };
00033 }
Generated on Fri Nov 15 2024 22:18:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DDS_HEADER Member List

This is the complete list of members for DDS_HEADER, including all inherited members.
caps | DDS_HEADER
caps | DDS_HEADER
caps2 | DDS_HEADER
caps2 | DDS_HEADER
caps3 | DDS_HEADER
caps3 | DDS_HEADER
caps4 | DDS_HEADER
caps4 | DDS_HEADER
ddspf | DDS_HEADER
depth | DDS_HEADER
depth | DDS_HEADER
flags | DDS_HEADER
flags | DDS_HEADER
height | DDS_HEADER
height | DDS_HEADER
mipMapCount | DDS_HEADER
mipMapCount | DDS_HEADER
pitchOrLinearSize | DDS_HEADER
pitchOrLinearSize | DDS_HEADER
reserved1 | DDS_HEADER
reserved1 | DDS_HEADER
reserved2 | DDS_HEADER
reserved2 | DDS_HEADER
size | DDS_HEADER
size | DDS_HEADER
width | DDS_HEADER
width | DDS_HEADER
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks/ViewModel/ViewModelLocator.h Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks
  • ViewModel

ViewModelLocator.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012
00013 #include "App.g.h"
00014 #include "ViewModel\ViewModelBase.h"
00015 #include "ViewModel\TripListViewModel.h"
00016 #include "ViewModel\TripViewModel.h"
00017
00018 namespace AdventureWorks
00019 {
00020     [Windows::UI::Xaml::Data::Bindable]
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class ViewModelLocator sealed
00023     {
00024     public:
00025         ViewModelLocator();
00026
00027         property TripListViewModel^ TripListViewModel
00028         {
00029             AdventureWorks::TripListViewModel^ get();
00030         }
00031
00032         property TripViewModel^ TripViewModel
00033         {
00034             AdventureWorks::TripViewModel^ get();
00035         }
00036
00037     private:
00038         Windows::Foundation::Collections::IMap<Platform::String^, ViewModelBase^>^ modelSet;
00039         AdventureWorks_Shared::TripStore^ store;
00040
00041     };
00042 }
00043
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cppwinrt/Scenario4_InteractionFeedback.cpp Source File

  • PenHaptics
  • cppwinrt

Scenario4_InteractionFeedback.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SampleConfiguration.h"
00014 #include "Scenario4_InteractionFeedback.h"
00015 #include "Scenario4_InteractionFeedback.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Devices::Haptics;
00020 using namespace Windows::Devices::Input;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Input;
00024
00025
00026 // This sample shows how to play Interaction feedback tactile signals, how to
00027 // adjust the intensity of the tactile signal, and how to fall back to a default
00028 // waveform if the desired waveform is not supported by the current PenDevice
00029 namespace winrt::SDKTemplate::implementation
00030 {
00031     Scenario4_InteractionFeedback::Scenario4_InteractionFeedback()
00032     {
00033         InitializeComponent();
00034     }
00035
00036     // The PointerEnter event will get fired as soon as Pointer input is received.
00037     // This event handler implementation will query the device providing input to see if it's a pen and
00038     // then check to see the pen supports tactile feedback
00039     void Scenario4_InteractionFeedback::MainGrid_Entered(IInspectable const&, PointerRoutedEventArgs const& e)
00040     {
00041         // If the current Pointer device is not a pen, exit
00042         if (e.Pointer().PointerDeviceType() != PointerDeviceType::Pen)
00043         {
00044             return;
00045         }
00046
00047         // Attempt to retrieve the PenDevice from the current PointerId
00048         penDevice = PenDevice::GetFromPointerId(e.Pointer().PointerId());
00049
00050         // If a PenDevice cannot be retrieved based on the PointerId, it does not support
00051         // advanced pen features, such as tactile feedback
00052         if (penDevice == nullptr)
00053         {
00054             statusText().Text(L"Advanced pen features not supported");
00055             return;
00056         }
00057
00058         // Check to see if the current PenDevice supports tactile feedback by seeing if it
00059         // has a SimpleHapticsController
00060         hapticsController = penDevice.SimpleHapticsController();
00061         if (hapticsController == nullptr)
00062         {
00063             statusText().Text(L"This pen does not provide tactile feedback");
00064             return;
00065         }
00066     }
00067
00068     // Stop sending the tactile feedback and clear the current penDevice and hapticsController on PointerExit.
00069     // Stopping the feedback is important as it clears the tactile signal from the PenDevice's
00070     // SimpleHapticsController, ensuring that it has a clean state once it next enters range.
00071     void Scenario4_InteractionFeedback::MainGrid_Exited(IInspectable const&, PointerRoutedEventArgs const&)
00072     {
00073         penDevice = nullptr;
00074         statusText().Text(L"");
00075         if (hapticsController != nullptr)
00076         {
00077             hapticsController.StopFeedback();
00078             hapticsController = nullptr;
00079             currentFeedback = nullptr;
00080         }
00081     }
00082
00083     // Send the selected waveform upon the button being clicked
00084     void Scenario4_InteractionFeedback::SendFeedback_Clicked(IInspectable const&, RoutedEventArgs const&)
00085     {
00086         if (hapticsController == nullptr)
00087         {
00088             return;
00089         }
00090
00091         // Get the current feedback based on what is selected in the dropdown
00092         std::wstring message;
00093         currentFeedback = GetSelectedFeedbackOrFallback(message);
00094
00095         // Send the current feedback to the PenDevice's SimpleHapticsController.
00096         // Once sent, unlike inking feedback, the feedback will be played immediately.
00097         // Also, check to see if the current PenDevice's SimpleHapticsController supports
00098         // setting the intensity value of the tactile feedback.  If so, set it based
00099         // on the slider.  If not, send the waveform without custom intensity.
00100         if (hapticsController.IsIntensitySupported())
00101         {
00102             hapticsController.SendHapticFeedback(currentFeedback, intensitySlider().Value() / 100);
00103             message.append(L"\nIntensity set to " + to_hstring(intensitySlider().Value()) + L"%");
00104         }
00105         else
00106         {
00107             hapticsController.SendHapticFeedback(currentFeedback);
00108             message.append(L"\nSetting intensity is not supported by this pen");
00109         }
00110         statusText().Text(message);
00111     }
00112
00113     // Get the currently selected waveform in the dropdown.
00114     // To get the waveform, the SimpleHapticsController's SupportedFeedback list must be traversed
00115     // to see if the desired waveform is present.
00116     // This is important because Click is the only Interaction waveform required to be
00117     // supported by every pen with haptics.
00118     // If the desired waveform is not in the SupportedFeedback list, this method returns
00119     // Click as a guaranteed fallback.
00120     SimpleHapticsControllerFeedback Scenario4_InteractionFeedback::GetSelectedFeedbackOrFallback(std::wstring& message)
00121     {
00122         // Look up the waveform the user selected.
00123         hstring name = waveformComboBox().SelectionBoxItem().as<hstring>();
00124         uint16_t waveform = WaveformNamesMap().at(name);
00125
00126         // See if the haptics controller supports the selected waveform.
00127         SimpleHapticsControllerFeedback feedback = FindSupportedFeedback(hapticsController, waveform);
00128         if (feedback != nullptr)
00129         {
00130             message = L"Waveform set to " + name;
00131             return feedback;
00132         }
00133
00134         // It does not. Use Click as a fallback.
00135         message = name + L" is not supported by this pen, so falling back to Click";
00136         return FindSupportedFeedback(hapticsController, KnownSimpleHapticsControllerWaveforms::Click());
00137     }
00138 }
Generated on Fri Nov 15 2024 22:20:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/AppViewSource.cs Source File

  • 360VideoPlayback
  • cs

AppViewSource.cs

Go to the documentation of this file.
00001 ﻿using Windows.ApplicationModel.Core;
00002 using System;
00003
00004 namespace _360VideoPlayback
00005 {
00006     // The entry point for the app.
00007     internal class AppViewSource : IFrameworkViewSource
00008     {
00009         public AppViewSource(Uri sourceUri)
00010         {
00011             this.sourceUri = sourceUri;
00012         }
00013
00014         public IFrameworkView CreateView()
00015         {
00016             return new AppView(sourceUri);
00017         }
00018
00019         private Uri sourceUri;
00020     }
00021 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cs/Tasks/Properties/AssemblyInfo.cs Source File

  • BackgroundTask
  • cs
  • Tasks
  • Properties

AssemblyInfo.cs

Go to the documentation of this file.
00001 ﻿using System.Resources;
00002 using System.Reflection;
00003 using System.Runtime.CompilerServices;
00004 using System.Runtime.InteropServices;
00005
00006 // General Information about an assembly is controlled through the following
00007 // set of attributes. Change these attribute values to modify the information
00008 // associated with an assembly.
00009 [assembly: AssemblyTitle("Tasks")]
00010 [assembly: AssemblyDescription("")]
00011 [assembly: AssemblyConfiguration("")]
00012 [assembly: AssemblyCompany("Microsoft Corporation")]
00013 [assembly: AssemblyProduct("")]
00014 [assembly: AssemblyCopyright("")]
00015 [assembly: AssemblyTrademark("")]
00016 [assembly: AssemblyCulture("")]
00017
00018 // Version information for an assembly consists of the following four values:
00019 //
00020 //      Major Version
00021 //      Minor Version
00022 //      Build Number
00023 //      Revision
00024 //
00025 // You can specify all the values or you can default the Build and Revision Numbers
00026 // by using the '*' as shown below:
00027 // [assembly: AssemblyVersion("1.0.*")]
00028 [assembly: AssemblyVersion("1.0.0.0")]
00029 [assembly: AssemblyFileVersion("1.0.0.0")]
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialStage/cpp/Common/StepTimer.h Source File

  • HolographicSpatialStage
  • cpp
  • Common

StepTimer.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 namespace DX
00004 {
00005     // Helper class for animation and simulation timing.
00006     class StepTimer
00007     {
00008     public:
00009         StepTimer() :
00010             m_elapsedTicks(0),
00011             m_totalTicks(0),
00012             m_leftOverTicks(0),
00013             m_frameCount(0),
00014             m_framesPerSecond(0),
00015             m_framesThisSecond(0),
00016             m_qpcSecondCounter(0),
00017             m_isFixedTimeStep(false),
00018             m_targetElapsedTicks(TicksPerSecond / 60)
00019         {
00020             m_qpcFrequency = GetPerformanceFrequency();
00021
00022             // Initialize max delta to 1/10 of a second.
00023             m_qpcMaxDelta = m_qpcFrequency / 10;
00024         }
00025
00026         // Get elapsed time since the previous Update call.
00027         uint64 GetElapsedTicks() const                        { return m_elapsedTicks;                  }
00028         double GetElapsedSeconds() const                      { return TicksToSeconds(m_elapsedTicks);  }
00029
00030         // Get total time since the start of the program.
00031         uint64 GetTotalTicks() const                          { return m_totalTicks;                    }
00032         double GetTotalSeconds() const                        { return TicksToSeconds(m_totalTicks);    }
00033
00034         // Get total number of updates since start of the program.
00035         uint32 GetFrameCount() const                          { return m_frameCount;                    }
00036
00037         // Get the current framerate.
00038         uint32 GetFramesPerSecond() const                     { return m_framesPerSecond;               }
00039
00040         // Set whether to use fixed or variable timestep mode.
00041         void SetFixedTimeStep(bool isFixedTimestep)           { m_isFixedTimeStep = isFixedTimestep;    }
00042
00043         // Set how often to call Update when in fixed timestep mode.
00044         void SetTargetElapsedTicks(uint64 targetElapsed)      { m_targetElapsedTicks = targetElapsed;   }
00045         void SetTargetElapsedSeconds(double targetElapsed)    { m_targetElapsedTicks = SecondsToTicks(targetElapsed);   }
00046
00047         // Integer format represents time using 10,000,000 ticks per second.
00048         static const uint64 TicksPerSecond = 10'000'000;
00049
00050         static double TicksToSeconds(uint64 ticks)            { return static_cast<double>(ticks) / TicksPerSecond;     }
00051         static uint64 SecondsToTicks(double seconds)          { return static_cast<uint64>(seconds * TicksPerSecond);   }
00052
00053         // Convenient wrapper for QueryPerformanceFrequency. Throws an exception if
00054         // the call to QueryPerformanceFrequency fails.
00055         static inline uint64 GetPerformanceFrequency()
00056         {
00057             LARGE_INTEGER freq;
00058             if (!QueryPerformanceFrequency(&freq))
00059             {
00060                 throw ref new Platform::FailureException();
00061             }
00062             return freq.QuadPart;
00063         }
00064
00065         // Gets the current number of ticks from QueryPerformanceCounter. Throws an
00066         // exception if the call to QueryPerformanceCounter fails.
00067         static inline int64 GetTicks()
00068         {
00069             LARGE_INTEGER ticks;
00070             if (!QueryPerformanceCounter(&ticks))
00071             {
00072                 throw ref new Platform::FailureException();
00073             }
00074             return ticks.QuadPart;
00075         }
00076
00077         // After an intentional timing discontinuity (for instance a blocking IO operation)
00078         // call this to avoid having the fixed timestep logic attempt a set of catch-up
00079         // Update calls.
00080
00081         void ResetElapsedTime()
00082         {
00083             m_qpcLastTime = GetTicks();
00084
00085             m_leftOverTicks    = 0;
00086             m_framesPerSecond  = 0;
00087             m_framesThisSecond = 0;
00088             m_qpcSecondCounter = 0;
00089         }
00090
00091         // Update timer state, calling the specified Update function the appropriate number of times.
00092         template<typename TUpdate>
00093         void Tick(const TUpdate& update)
00094         {
00095             // Query the current time.
00096             uint64 currentTime = GetTicks();
00097             uint64 timeDelta   = currentTime - m_qpcLastTime;
00098
00099             m_qpcLastTime      = currentTime;
00100             m_qpcSecondCounter += timeDelta;
00101
00102             // Clamp excessively large time deltas (e.g. after paused in the debugger).
00103             if (timeDelta > m_qpcMaxDelta)
00104             {
00105                 timeDelta = m_qpcMaxDelta;
00106             }
00107
00108             // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp.
00109             timeDelta *= TicksPerSecond;
00110             timeDelta /= m_qpcFrequency;
00111
00112             uint32 lastFrameCount = m_frameCount;
00113
00114             if (m_isFixedTimeStep)
00115             {
00116                 // Fixed timestep update logic
00117
00118                 // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp
00119                 // the clock to exactly match the target value. This prevents tiny and irrelevant errors
00120                 // from accumulating over time. Without this clamping, a game that requested a 60 fps
00121                 // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually
00122                 // accumulate enough tiny errors that it would drop a frame. It is better to just round
00123                 // small deviations down to zero to leave things running smoothly.
00124
00125                 if (abs(static_cast<int64>(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000)
00126                 {
00127                     timeDelta = m_targetElapsedTicks;
00128                 }
00129
00130                 m_leftOverTicks += timeDelta;
00131
00132                 while (m_leftOverTicks >= m_targetElapsedTicks)
00133                 {
00134                     m_elapsedTicks   = m_targetElapsedTicks;
00135                     m_totalTicks    += m_targetElapsedTicks;
00136                     m_leftOverTicks -= m_targetElapsedTicks;
00137                     m_frameCount++;
00138
00139                     update();
00140                 }
00141             }
00142             else
00143             {
00144                 // Variable timestep update logic.
00145                 m_elapsedTicks  = timeDelta;
00146                 m_totalTicks   += timeDelta;
00147                 m_leftOverTicks = 0;
00148                 m_frameCount++;
00149
00150                 update();
00151             }
00152
00153             // Track the current framerate.
00154             if (m_frameCount != lastFrameCount)
00155             {
00156                 m_framesThisSecond++;
00157             }
00158
00159             if (m_qpcSecondCounter >= static_cast<uint64>(m_qpcFrequency))
00160             {
00161                 m_framesPerSecond   = m_framesThisSecond;
00162                 m_framesThisSecond  = 0;
00163                 m_qpcSecondCounter %= m_qpcFrequency;
00164             }
00165         }
00166
00167     private:
00168
00169         // Source timing data uses QPC units.
00170         uint64 m_qpcFrequency;
00171         uint64 m_qpcLastTime;
00172         uint64 m_qpcMaxDelta;
00173
00174         // Derived timing data uses a canonical tick format.
00175         uint64 m_elapsedTicks;
00176         uint64 m_totalTicks;
00177         uint64 m_leftOverTicks;
00178
00179         // Members for tracking the framerate.
00180         uint32 m_frameCount;
00181         uint32 m_framesPerSecond;
00182         uint32 m_framesThisSecond;
00183         uint64 m_qpcSecondCounter;
00184
00185         // Members for configuring fixed timestep mode.
00186         bool   m_isFixedTimeStep;
00187         uint64 m_targetElapsedTicks;
00188     };
00189 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/SourceHandler.cpp Source File

  • SpatialInteractionSource
  • cpp

SourceHandler.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "SourceHandler.h"
00003 #include "SpatialControllerHandler.h"
00004 #include "HandHandler.h"
00005 #include "..\Common\DirectXHelper.h"
00006
00007 using namespace HolographicPaint;
00008 using namespace DirectX;
00009 using namespace Platform;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Numerics;
00012 using namespace Windows::Devices::Haptics;
00013 using namespace Windows::Perception::Spatial;
00014 using namespace Windows::UI::Input::Spatial;
00015 using namespace std::placeholders;
00016
00017 // If we lose tracking of a controller for too long, we consider its position as definitely invalid
00018 // Note that TimeStamp's unit is 100 nanoseconds
00019 static const long long TrackingTimeout = 50000000; // 5 seconds
00020
00021 void SourceHandler::PositionInformation::CheckIfObsolete(long long now)
00022 {
00023     if (IsCurrent)
00024     {
00025         LastValueTime = now;
00026     }
00027     else if (HasValue && (now - LastValueTime > TrackingTimeout))
00028     {
00029         HasValue = false;
00030     }
00031 }
00032
00033 SourceHandler::SourceHandler(SpatialInteractionSource^ source, ISourceCommandHandler* eventsHandler, std::shared_ptr<Whiteboard>& target)
00034     : m_sourceId(source->Id), m_sourceKind(source->Kind), m_eventsHandler(eventsHandler), m_targetBoard(target)
00035 {
00036 }
00037
00038 void SourceHandler::OnSourceUpdated(SpatialInteractionSourceState^ state, SpatialCoordinateSystem^ coordinateSystem)
00039 {
00040     SpatialInteractionSourceProperties^ properties = state->Properties;
00041     SpatialInteractionSourceLocation^ location = properties->TryGetLocation(coordinateSystem);
00042     m_position.IsCurrent = false;
00043     if (location != nullptr)
00044     {
00045         IBox<float3>^ position = location->Position;
00046         if (position != nullptr)
00047         {
00048             m_position.HasValue = true;
00049             m_position.Position = position->Value;
00050             m_position.IsCurrent = true;
00051             IBox<quaternion>^ orientation = location->Orientation;
00052             if (orientation == nullptr)
00053             {
00054                 m_position.Orientation = quaternion::identity();
00055             }
00056             else
00057             {
00058                 m_position.Orientation = orientation->Value;
00059             }
00060         }
00061     }
00062     m_position.CheckIfObsolete(state->Timestamp->TargetTime.UniversalTime);
00063 }
00064
00065 void SourceHandler::Update(ID3D11DeviceContext*)
00066 {
00067     if (m_refreshModelConstantBufferData)
00068     {
00069         const XMMATRIX modelRotation = XMMatrixRotationQuaternion(XMLoadQuaternion(&m_toolPosition.Orientation));
00070
00071         const float3 toolScale = GetToolScale();
00072         const XMMATRIX modelScale = XMMatrixScaling(toolScale.x, toolScale.y, toolScale.z);
00073
00074         const XMMATRIX modelTranslation = XMMatrixTranslationFromVector(XMLoadFloat3(&m_toolPosition.Position));
00075
00076         // Multiply to get the transform matrix.
00077         // Note that this transform does not enforce a particular coordinate system. The calling
00078         // class is responsible for rendering this content in a consistent manner.
00079         const XMMATRIX modelTransform = modelScale * modelRotation * modelTranslation;
00080
00081         // The view and projection matrices are provided by the system; they are associated
00082         // with holographic cameras, and updated on a per-camera basis.
00083         // Here, we provide the model transform for the sample hologram. The model transform
00084         // matrix is transposed to prepare it for the shader.
00085         XMStoreFloat4x4(&m_modelConstantBufferData.model, XMMatrixTranspose(modelTransform));
00086
00087
00088         m_refreshModelConstantBufferData = false;
00089     }
00090
00091     if (m_toolPosition.IsCurrent)
00092     {
00093         m_modelConstantBufferData.color = DX::GetDXColor(m_currentTool->GetColor());
00094     }
00095     else
00096     {
00097         m_modelConstantBufferData.color = XMFLOAT4(1.0f, .3f, .3f, .3f);
00098     }
00099
00100 }
00101
00102 void SourceHandler::Render(ID3D11DeviceContext* pDeviceContext, IRenderer* pRenderingHelper)
00103 {
00104     // We do not render the controller until it has been displayed at least once
00105     if (m_toolPosition.HasValue)
00106     {
00107         pRenderingHelper->SetConstantBuffer(&m_modelConstantBufferData);
00108         pRenderingHelper->DrawCube();
00109     }
00110 }
00111
00112 void SourceHandler::SetCurrentTool(std::shared_ptr<Tool> tool)
00113 {
00114     m_currentTool = tool;
00115     m_refreshModelConstantBufferData = true;
00116 }
00117
00118 void SourceHandler::ComposeStroke()
00119 {
00120     if (m_currentTool)
00121     {
00122         if (!m_currentStroke)
00123         {
00124             m_currentStroke = std::make_shared<Stroke>(m_currentTool->GetColor());
00125             m_eventsHandler->OnStrokeAdded(this, m_currentStroke);
00126         }
00127     }
00128     m_currentStroke->AddPosition(m_toolPosition.Position, m_toolPosition.Orientation, m_currentTool->GetDiameter());
00129 }
00130
00131 void SourceHandler::TerminateStroke()
00132 {
00133     m_currentStroke.reset();
00134 }
00135
00136 bool SourceHandler::Make(std::shared_ptr<SourceHandler>* handler, SpatialInteractionSource^ source, ISourceCommandHandler* eventsHandler, std::shared_ptr<Whiteboard>& target)
00137 {
00138     switch (source->Kind)
00139     {
00140     case SpatialInteractionSourceKind::Hand:
00141         *handler = std::make_shared<HandHandler>(source, eventsHandler, target);
00142         return true;
00143     case SpatialInteractionSourceKind::Controller:
00144         if (source->IsPointingSupported)
00145         {
00146             *handler = std::make_shared<SpatialControllerHandler>(source, eventsHandler, target);
00147             return true;
00148         }
00149     }
00150     return false;
00151 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CredentialPicker/cpp/pch.cpp Source File

  • CredentialPicker
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothAdvertisement/cs/SampleConfiguration.cs Source File

  • BluetoothAdvertisement
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using BluetoothAdvertisement;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Bluetooth Low Energy Advertisement";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario()
00026             {
00027                 Title = "Foreground watcher",
00028                 ClassType = typeof(Scenario1_Watcher)
00029             },
00030             new Scenario()
00031             {
00032                 Title = "Foreground publisher",
00033                 ClassType = typeof(Scenario2_Publisher)
00034             },
00035             new Scenario()
00036             {
00037                 Title = "Background watcher",
00038                 ClassType = typeof(Scenario3_BackgroundWatcher)
00039             },
00040             new Scenario()
00041             {
00042                 Title = "Background publisher",
00043                 ClassType = typeof(Scenario4_BackgroundPublisher)
00044             },
00045         };
00046     }
00047
00048     public class Scenario
00049     {
00050         public string Title { get; set; }
00051         public Type ClassType { get; set; }
00052     }
00053 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomPixelShaderMain Member List

This is the complete list of members for CustomPixelShaderMain, including all inherited members.
CreateWindowSizeDependentResources() | CustomPixelShaderMain |
CustomPixelShaderMain(const std::shared_ptr< DX::DeviceResources > &deviceResources) | CustomPixelShaderMain |
LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | CustomPixelShaderMain |
m_deviceResources | CustomPixelShaderMain | [private]
m_sampleOverlay | CustomPixelShaderMain | [private]
m_sceneRenderer | CustomPixelShaderMain | [private]
OnDeviceLost() | CustomPixelShaderMain | [virtual]
OnDeviceRestored() | CustomPixelShaderMain | [virtual]
Render() | CustomPixelShaderMain |
SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | CustomPixelShaderMain |
Update() | CustomPixelShaderMain |
UpdatePointer(_In_ Windows::UI::Core::PointerEventArgs^args) | CustomPixelShaderMain |
~CustomPixelShaderMain() | CustomPixelShaderMain |
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/scenario5.xaml.h Source File

  • ApplicationResources
  • cpp

scenario5.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario5.xaml.h
00013 // Declaration of the Scenario5 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario5.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024
00025         /// <summary>
00026         /// An empty page that can be used on its own or navigated to within a Frame.
00027         /// </summary>
00028         [Windows::Foundation::Metadata::WebHostHidden]
00029         public ref class Scenario5 sealed
00030         {
00031         public:
00032             Scenario5();
00033
00034         protected:
00035             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         private:
00037             MainPage^ rootPage;
00038             void Scenario5Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         };
00040
00041 }
Generated on Fri Nov 15 2024 22:18:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/SmartCardHelpers.cpp Source File

  • SmartCard
  • cppwinrt

SmartCardHelpers.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "SmartCardHelpers.h"
00003
00004 using namespace winrt::Windows::Foundation;
00005 using namespace winrt::Windows::Devices::SmartCards;
00006 using namespace winrt::Windows::Storage::Streams;
00007 using namespace winrt::Windows::Security::Cryptography::Core;
00008
00009 namespace winrt::SDKTemplate
00010 {
00011     hstring g_smartCardReaderDeviceId;
00012     IBuffer g_adminKey;
00013
00014     bool ValidateTPMSmartCard()
00015     {
00016         return !g_smartCardReaderDeviceId.empty();
00017     }
00018
00019     hstring GetSmartCardReaderDeviceId()
00020     {
00021         return g_smartCardReaderDeviceId;
00022     }
00023
00024     void SetSmartCardReaderDeviceId(hstring const& id)
00025     {
00026         g_smartCardReaderDeviceId = id;
00027     }
00028
00029     IBuffer GetAdminKey()
00030     {
00031         return g_adminKey;
00032     }
00033
00034     void SetAdminKey(IBuffer const& buffer)
00035     {
00036         g_adminKey = buffer;
00037     }
00038
00039     IAsyncOperation<SmartCard> GetSmartCardAsync()
00040     {
00041         SmartCardReader reader = co_await SmartCardReader::FromIdAsync(g_smartCardReaderDeviceId);
00042         auto cards = co_await reader.FindAllCardsAsync();
00043
00044         if (cards.Size() != 1)
00045         {
00046             throw winrt::hresult_error(E_UNEXPECTED);
00047         }
00048         else
00049         {
00050             co_return cards.GetAt(0);
00051         }
00052     }
00053
00054     IBuffer CalculateChallengeResponse(IBuffer const& challenge, IBuffer const& adminKey)
00055     {
00056         SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider::OpenAlgorithm(SymmetricAlgorithmNames::TripleDesCbc());
00057         CryptographicKey key = provider.CreateSymmetricKey(adminKey);
00058         return CryptographicEngine::Encrypt(key, challenge, nullptr);
00059     }
00060 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/Scenario_ContinuousDictation.xaml.cpp Source File

  • SpeechRecognitionAndSynthesis
  • cpp

Scenario_ContinuousDictation.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario_ContinuousDictation.xaml.h"
00014 #include "AudioCapturePermissions.h"
00015
00016 using namespace SDKTemplate;
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Globalization;
00022 using namespace Windows::Media::SpeechRecognition;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Controls::Primitives;
00027 using namespace Windows::UI::Xaml::Data;
00028 using namespace Windows::UI::Xaml::Documents;
00029 using namespace Windows::UI::Xaml::Input;
00030 using namespace Windows::UI::Xaml::Media;
00031 using namespace Windows::UI::Xaml::Navigation;
00032
00033 Scenario_ContinuousDictation::Scenario_ContinuousDictation() : rootPage(MainPage::Current)
00034 {
00035     InitializeComponent();
00036 }
00037
00038 /// <summary>
00039 /// Upon entering the scenario, ensure that we have permissions to use the Microphone. This may entail popping up
00040 /// a dialog to the user on Desktop systems. Only enable functionality once we've gained that permission in order to
00041 /// prevent errors from occurring when using the SpeechRecognizer. If speech is not a primary input mechanism, developers
00042 /// should consider disabling appropriate parts of the UI if the user does not have a recording device, or does not allow
00043 /// audio input.
00044 /// </summary>
00045 /// <param name="e">Unused navigation parameters</param>
00046 void Scenario_ContinuousDictation::OnNavigatedTo(NavigationEventArgs^ e)
00047 {
00048     Page::OnNavigatedTo(e);
00049
00050     // Prompt the user for permission to access the microphone. This request will only happen
00051     // once, it will not re-prompt if the user rejects the permission.
00052     create_task(AudioCapturePermissions::RequestMicrophonePermissionAsync(), task_continuation_context::use_current())
00053         .then([this](bool permissionGained)
00054     {
00055         if (permissionGained)
00056         {
00057             this->btnContinuousRecognize->IsEnabled = true;
00058
00059             PopulateLanguageDropdown();
00060             InitializeRecognizer(SpeechRecognizer::SystemSpeechLanguage);
00061         }
00062         else
00063         {
00064             this->dictationTextBox->Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
00065             this->cbLanguageSelection->IsEnabled = false;
00066         }
00067     });
00068 }
00069
00070 /// <summary>
00071 /// Creates a SpeechRecognizer instance and initializes the grammar.
00072 /// </summary>
00073 void Scenario_ContinuousDictation::InitializeRecognizer(Windows::Globalization::Language^ recognizerLanguage)
00074 {
00075     // If reinitializing the recognizer (ie, changing the speech language), clean up the old recognizer first.
00076     // Avoid doing this while the recognizer is active by disabling the ability to change languages while listening.
00077     if (this->speechRecognizer != nullptr)
00078     {
00079         speechRecognizer->StateChanged -= stateChangedToken;
00080         speechRecognizer->ContinuousRecognitionSession->Completed -= continuousRecognitionCompletedToken;
00081         speechRecognizer->ContinuousRecognitionSession->ResultGenerated -= continuousRecognitionResultGeneratedToken;
00082         speechRecognizer->HypothesisGenerated -= hypothesisGeneratedToken;
00083
00084         delete this->speechRecognizer;
00085         this->speechRecognizer = nullptr;
00086     }
00087
00088     this->speechRecognizer = ref new SpeechRecognizer(recognizerLanguage);
00089
00090     // Provide feedback to the user about the state of the recognizer. This can be used to provide visual feedback in the form
00091     // of an audio indicator to help the user understand whether they're being heard.
00092     stateChangedToken = speechRecognizer->StateChanged +=
00093         ref new TypedEventHandler<
00094         SpeechRecognizer ^,
00095         SpeechRecognizerStateChangedEventArgs ^>(
00096             this,
00097             &Scenario_ContinuousDictation::SpeechRecognizer_StateChanged);
00098
00099     // Apply the dictation topic constraint to optimize for dictated freeform speech.
00100     auto dictationConstraint = ref new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario::Dictation, "dictation");
00101     speechRecognizer->Constraints->Append(dictationConstraint);
00102
00103     create_task(speechRecognizer->CompileConstraintsAsync(), task_continuation_context::use_current())
00104         .then([this](task<SpeechRecognitionCompilationResult^> previousTask)
00105     {
00106         SpeechRecognitionCompilationResult^ compilationResult = previousTask.get();
00107
00108         if (compilationResult->Status != SpeechRecognitionResultStatus::Success)
00109         {
00110             btnContinuousRecognize->IsEnabled = false;
00111
00112             // Let the user know that the grammar didn't compile properly.
00113             rootPage->NotifyUser("Grammar Compilation Failed: " + compilationResult->Status.ToString(), NotifyType::ErrorMessage);
00114         }
00115
00116         // Handle continuous recognition events. Completed fires when various error states occur. ResultGenerated fires when
00117         // some recognized phrases occur, or the garbage rule is hit. HypothesisGenerated fires during recognition, and
00118         // allows us to provide incremental feedback based on what the user's currently saying.
00119         continuousRecognitionCompletedToken = speechRecognizer->ContinuousRecognitionSession->Completed +=
00120             ref new TypedEventHandler<
00121             SpeechContinuousRecognitionSession ^,
00122             SpeechContinuousRecognitionCompletedEventArgs ^>(
00123                 this,
00124                 &Scenario_ContinuousDictation::ContinuousRecognitionSession_Completed);
00125         continuousRecognitionResultGeneratedToken = speechRecognizer->ContinuousRecognitionSession->ResultGenerated +=
00126             ref new TypedEventHandler<
00127             SpeechContinuousRecognitionSession ^,
00128             SpeechContinuousRecognitionResultGeneratedEventArgs ^>(
00129                 this,
00130                 &Scenario_ContinuousDictation::ContinuousRecognitionSession_ResultGenerated);
00131         hypothesisGeneratedToken = speechRecognizer->HypothesisGenerated +=
00132             ref new TypedEventHandler<
00133             SpeechRecognizer ^,
00134             SpeechRecognitionHypothesisGeneratedEventArgs ^>(
00135                 this,
00136                 &Scenario_ContinuousDictation::SpeechRecognizer_HypothesisGenerated);
00137
00138
00139     }, task_continuation_context::use_current());
00140 }
00141
00142 /// <summary>
00143 /// Upon leaving, clean up the speech recognizer. Ensure we aren't still listening, and disable the event
00144 /// handlers to prevent leaks.
00145 /// </summary>
00146 /// <param name="e">Unused navigation parameters.</param>
00147 void Scenario_ContinuousDictation::OnNavigatedFrom(NavigationEventArgs^ e)
00148 {
00149     Page::OnNavigatedFrom(e);
00150
00151     if (speechRecognizer != nullptr)
00152     {
00153         // If we're currently active, start a cancellation task, and wait for it to finish before shutting down
00154         // the recognizer.
00155         Concurrency::task<void> cleanupTask;
00156         if (speechRecognizer->State != SpeechRecognizerState::Idle)
00157         {
00158             cleanupTask = create_task(speechRecognizer->ContinuousRecognitionSession->CancelAsync(), task_continuation_context::use_current());
00159         }
00160         else
00161         {
00162             cleanupTask = create_task([]() {}, task_continuation_context::use_current());
00163         }
00164
00165         cleanupTask.then([this]() {
00166             DictationButtonText->Text = " Dictate";
00167             dictationTextBox->Text = "";
00168
00169             speechRecognizer->StateChanged -= stateChangedToken;
00170             speechRecognizer->ContinuousRecognitionSession->Completed -= continuousRecognitionCompletedToken;
00171             speechRecognizer->ContinuousRecognitionSession->ResultGenerated -= continuousRecognitionResultGeneratedToken;
00172             speechRecognizer->HypothesisGenerated -= hypothesisGeneratedToken;
00173
00174             delete speechRecognizer;
00175             speechRecognizer = nullptr;
00176         }, task_continuation_context::use_current());
00177     }
00178 }
00179
00180 /// <summary>
00181 /// Begin recognition, or finish the recognition session.
00182 /// </summary>
00183 /// <param name="sender">The button that generated this event</param>
00184 /// <param name="e">Unused event details</param>
00185 void Scenario_ContinuousDictation::ContinuousRecognize_Click(Object^ sender, RoutedEventArgs^ e)
00186 {
00187     btnContinuousRecognize->IsEnabled = false;
00188     // The recognizer can only start listening in a continuous fashion if the recognizer is currently idle.
00189     // This prevents an exception from occurring.
00190     if (speechRecognizer->State == SpeechRecognizerState::Idle)
00191     {
00192         DictationButtonText->Text = " Stop Dictation";
00193         cbLanguageSelection->IsEnabled = false;
00194         hlOpenPrivacySettings->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00195         discardedTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00196
00197         try
00198         {
00199             create_task(speechRecognizer->ContinuousRecognitionSession->StartAsync(), task_continuation_context::use_current())
00200                 .then([this](task<void> startAsyncTask)
00201             {
00202                 try
00203                 {
00204                     // Retreive any exceptions that may have been generated by StartAsync.
00205                     startAsyncTask.get();
00206                 }
00207                 catch (Exception^ exception)
00208                 {
00209                     DictationButtonText->Text = " Dictate";
00210                     cbLanguageSelection->IsEnabled = true;
00211
00212                     auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00213                     create_task(messageDialog->ShowAsync());
00214                 }
00215             }).then([this]() {
00216                 btnContinuousRecognize->IsEnabled = true;
00217             });
00218         }
00219         catch (COMException^ exception)
00220         {
00221             if ((unsigned int)exception->HResult == HResultPrivacyStatementDeclined)
00222             {
00223                 // If the privacy policy hasn't been accepted, attempting to create a task out of RecognizeAsync fails immediately with a
00224                 // COMException and this specific HResult.
00225                 hlOpenPrivacySettings->Visibility = Windows::UI::Xaml::Visibility::Visible;
00226             }
00227             else
00228             {
00229                 auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00230                 create_task(messageDialog->ShowAsync());
00231             }
00232         }
00233     }
00234     else
00235     {
00236         DictationButtonText->Text = " Dictate";
00237         cbLanguageSelection->IsEnabled = true;
00238
00239
00240         // Cancelling recognition prevents any currently recognized speech from
00241         // generating a ResultGenerated event. StopAsync() will allow the final session to
00242         // complete.
00243         create_task(speechRecognizer->ContinuousRecognitionSession->StopAsync(), task_continuation_context::use_current())
00244             .then([this]()
00245         {
00246
00247             // Ensure we don't leave any hypothesis text behind
00248             dictationTextBox->Text = ref new Platform::String(this->dictatedTextBuilder.str().c_str());
00249         }).then([this]() {
00250             btnContinuousRecognize->IsEnabled = true;
00251         });
00252     }
00253 }
00254
00255 /// <summary>
00256 /// Clear text in the text box on demand.
00257 /// </summary>
00258 void Scenario_ContinuousDictation::btnClearText_Click(Object^ sender, RoutedEventArgs^ e)
00259 {
00260     btnClearText->IsEnabled = false;
00261     this->dictatedTextBuilder.str(L"");
00262     this->dictatedTextBuilder.clear();
00263     dictationTextBox->Text = "";
00264     discardedTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00265
00266     btnContinuousRecognize->Focus(Windows::UI::Xaml::FocusState::Programmatic);
00267 }
00268
00269 /// <summary>
00270 /// Automatically scroll the textbox down to the bottom whenever new dictated text arrives
00271 /// </summary>
00272 /// <param name="sender">The dictation textbox</param>
00273 /// <param name="e">Unused text changed arguments</param>
00274 void Scenario_ContinuousDictation::dictationTextBox_TextChanged(Object^ sender, TextChangedEventArgs^ e)
00275 {
00276     auto grid = static_cast<Grid^>(VisualTreeHelper::GetChild(dictationTextBox, 0));
00277     for (int i = 0; i < VisualTreeHelper::GetChildrenCount(grid) - 1; i++)
00278     {
00279         ScrollViewer^ scroller = dynamic_cast<ScrollViewer^>(VisualTreeHelper::GetChild(grid, i));
00280         if (scroller != nullptr)
00281         {
00282             scroller->ChangeView(0.0, scroller->ExtentHeight, 1.0f);
00283             break;
00284         }
00285     }
00286 }
00287
00288
00289 /// <summary>
00290 /// Provide feedback to the user based on whether the recognizer is receiving their voice input.
00291 /// </summary>
00292 /// <param name="sender">The recognizer that is currently running.</param>
00293 /// <param name="args">The current state of the recognizer.</param>
00294 void Scenario_ContinuousDictation::SpeechRecognizer_StateChanged(SpeechRecognizer ^sender, SpeechRecognizerStateChangedEventArgs ^args)
00295 {
00296     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00297     {
00298         rootPage->NotifyUser("Speech recognizer state: " + args->State.ToString(), NotifyType::StatusMessage);
00299     }));
00300
00301 }
00302
00303 /// <summary>
00304 /// Handle events fired when error conditions occur, such as the microphone becoming unavailable, or if
00305 /// some transient issues occur.
00306 /// </summary>
00307 /// <param name="sender">The continuous recognition session</param>
00308 /// <param name="args">The state of the recognizer</param>
00309 void Scenario_ContinuousDictation::ContinuousRecognitionSession_Completed(SpeechContinuousRecognitionSession ^sender, SpeechContinuousRecognitionCompletedEventArgs ^args)
00310 {
00311     if (args->Status != SpeechRecognitionResultStatus::Success)
00312     {
00313         // If TimeoutExceeded occurs, the user has been silent for too long. We can use this to
00314         // cancel recognition if the user in dictation mode and walks away from their device, etc.
00315         // In a global-command type scenario, this timeout won't apply automatically.
00316         // With dictation (no grammar in place) modes, the default timeout is 20 seconds.
00317         if (args->Status == SpeechRecognitionResultStatus::TimeoutExceeded)
00318         {
00319             Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00320             {
00321                 rootPage->NotifyUser("Automatic Time Out of Dictation", NotifyType::StatusMessage);
00322                 DictationButtonText->Text = " Dictate";
00323                 cbLanguageSelection->IsEnabled = true;
00324                 dictationTextBox->Text = ref new Platform::String(this->dictatedTextBuilder.str().c_str());
00325             }));
00326         }
00327         else
00328         {
00329             Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00330             {
00331                 rootPage->NotifyUser("Continuous Recognition Completed: " + args->Status.ToString(), NotifyType::ErrorMessage);
00332                 DictationButtonText->Text = " Dictate";
00333                 cbLanguageSelection->IsEnabled = true;
00334             }));
00335         }
00336     }
00337 }
00338
00339 /// <summary>
00340 /// Handle events fired when a result is generated. Check for high to medium confidence, and then append the
00341 /// string to the end of the stringbuffer, and replace the content of the textbox with the string buffer, to
00342 /// remove any hypothesis text that may be present.
00343 /// </summary>
00344 /// <param name="sender">The Recognition session that generated this result</param>
00345 /// <param name="args">Details about the recognized speech</param>
00346 void Scenario_ContinuousDictation::ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession ^sender, SpeechContinuousRecognitionResultGeneratedEventArgs ^args)
00347 {
00348     // We may choose to discard content that has low confidence, as that could indicate that we're picking up
00349     // noise via the microphone, or someone could be talking out of earshot.
00350     if (args->Result->Confidence == SpeechRecognitionConfidence::Medium ||
00351         args->Result->Confidence == SpeechRecognitionConfidence::High)
00352     {
00353         this->dictatedTextBuilder << args->Result->Text->Data() << " ";
00354
00355         Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00356         {
00357             this->discardedTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00358
00359             this->dictationTextBox->Text = ref new String(this->dictatedTextBuilder.str().c_str());
00360             this->btnClearText->IsEnabled = true;
00361         }));
00362     }
00363     else
00364     {
00365         Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00366         {
00367             // In some scenarios, a developer may choose to ignore giving the user feedback in this case, if speech
00368             // is not the primary input mechanism for the application.
00369             // Here, just remove any hypothesis text by resetting it to the last known good.
00370             this->dictationTextBox->Text = ref new String(this->dictatedTextBuilder.str().c_str());
00371
00372             if (!args->Result->Text->IsEmpty())
00373             {
00374                 std::wstring discardedText = args->Result->Text->Data();
00375
00376                 discardedText = discardedText.size() <= 25 ? discardedText : (discardedText.substr(0, 25) + L"...");
00377
00378                 discardedTextBlock->Text = L"Discarded due to low/rejected Confidence: " + ref new String(discardedText.c_str());
00379                 discardedTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00380             }
00381
00382         }));
00383     }
00384 }
00385
00386 /// <summary>
00387 /// While the user is speaking, update the textbox with the partial sentence of what's being said for user feedback.
00388 /// </summary>
00389 /// <param name="sender">The recognizer that has generated the hypothesis</param>
00390 /// <param name="args">The hypothesis formed</param>
00391 void Scenario_ContinuousDictation::SpeechRecognizer_HypothesisGenerated(SpeechRecognizer ^sender, SpeechRecognitionHypothesisGeneratedEventArgs ^args)
00392 {
00393     String^ hypothesis = args->Hypothesis->Text;
00394
00395     std::wstring textBoxContent = dictatedTextBuilder.str() + L" " + hypothesis->Data() + L"...";
00396     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, textBoxContent]()
00397     {
00398         // Update the textbox with the currently confirmed text, and the hypothesis combined.
00399         this->dictationTextBox->Text = ref new Platform::String(textBoxContent.c_str());
00400         this->btnClearText->IsEnabled = true;
00401     }));
00402 }
00403
00404 /// <summary>
00405 /// Populate language dropdown with supported Dictation languages.
00406 /// </summary>
00407 void Scenario_ContinuousDictation::PopulateLanguageDropdown()
00408 {
00409     Windows::Globalization::Language^ defaultLanguage = SpeechRecognizer::SystemSpeechLanguage;
00410     auto supportedLanguages = SpeechRecognizer::SupportedTopicLanguages;
00411     for (Windows::Globalization::Language^ lang : supportedLanguages)
00412     {
00413         ComboBoxItem^ item = ref new ComboBoxItem();
00414         item->Tag = lang;
00415         item->Content = lang->DisplayName;
00416
00417         cbLanguageSelection->Items->Append(item);
00418         if (lang->LanguageTag == defaultLanguage->LanguageTag)
00419         {
00420             item->IsSelected = true;
00421             cbLanguageSelection->SelectedItem = item;
00422         }
00423     }
00424 }
00425
00426 /// <summary>
00427 /// Re-initialize the recognizer based on selections from the language combobox.
00428 /// </summary>
00429 void Scenario_ContinuousDictation::cbLanguageSelection_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00430 {
00431     if (this->speechRecognizer != nullptr)
00432     {
00433         ComboBoxItem^ item = (ComboBoxItem^)(cbLanguageSelection->SelectedItem);
00434         Windows::Globalization::Language^ newLanguage = (Windows::Globalization::Language^)item->Tag;
00435         if (speechRecognizer->CurrentLanguage != newLanguage)
00436         {
00437             try
00438             {
00439                 InitializeRecognizer(newLanguage);
00440             }
00441             catch (Exception^ exception)
00442             {
00443                 auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00444                 create_task(messageDialog->ShowAsync());
00445             }
00446         }
00447     }
00448 }
00449
00450 /// <summary>
00451 /// Open the Speech, Inking and Typing page under Settings -> Privacy, enabling a user to accept the
00452 /// Microsoft Privacy Policy, and enable personalization.
00453 /// </summary>
00454 /// <param name="sender">Ignored</param>
00455 /// <param name="args">Ignored</param>
00456 void Scenario_ContinuousDictation::openPrivacySettings_Click(Hyperlink^ sender, HyperlinkClickEventArgs^ args)
00457 {
00458     create_task(Windows::System::Launcher::LaunchUriAsync(ref new Uri(L"ms-settings:privacy-speech")));
00459 }
Generated on Fri Nov 15 2024 22:21:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
ButtonRemoveToast2_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
Initialize() | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
UserControl_Loaded(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
Generated on Fri Nov 15 2024 22:23:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/Functions.xaml.cpp Source File

  • XamlBind
  • cpp

Functions.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // EventTests.xaml.cpp
00003 // Implementation of the EventTests class
00004 //
00005
00006 #include "pch.h"
00007 #include "Functions.xaml.h"
00008 #include "Strsafe.h"
00009
00010 using namespace SDKTemplate;
00011
00012 using namespace Platform;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::Foundation::Collections;
00015 using namespace Windows::UI::Xaml;
00016 using namespace Windows::UI::Xaml::Controls;
00017 using namespace Windows::UI::Xaml::Controls::Primitives;
00018 using namespace Windows::UI::Xaml::Data;
00019 using namespace Windows::UI::Xaml::Input;
00020 using namespace Windows::UI::Xaml::Media;
00021 using namespace Windows::UI::Xaml::Navigation;
00022 using namespace Windows::UI::Popups;
00023
00024 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00025
00026 Functions::Functions()
00027 {
00028     InitializeComponent();
00029     this->ColorEntries = ref new Platform::Collections::Vector<ColorEntry^>();
00030     this->Model = ref new xBindSampleModel::DataModel();
00031 }
00032
00033 void Functions::InitializeValues()
00034 {
00035     this->Model->InitializeValues();
00036 }
00037
00038 void Functions::UpdateValuesClick(Object^ sender, ::Windows::UI::Xaml::RoutedEventArgs^ e)
00039 {
00040     this->Model->UpdateValues();
00041 }
00042
00043 void Functions::ResetValuesClick(Object^ sender, ::Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045     this->Model->InitializeValues();
00046     this->InitializeValues();
00047 }
00048
00049 Platform::String^ Functions::GetTime()
00050 {
00051     Calendar^ calendar = ref new Calendar();
00052     return _longTimeFormatter->Format(calendar->GetDateTime());
00053 }
00054
00055
00056 Platform::String^ Functions::Display(Platform::String^ stringArg, int intArg, double floatArg, bool boolArg)
00057 {
00058     WCHAR longString[1024];
00059     HRESULT hr = S_OK;
00060     hr = StringCchPrintf(longString, _countof(longString),
00061         L"String is: %s, Integer is: %d, Float is: %f, Boolean is %s",
00062         stringArg->Data(), intArg, floatArg, (boolArg ? L"true" : L"false"));
00063     if (FAILED(hr))
00064     {
00065         throw ref new COMException(hr);
00066     }
00067     return ref new String(longString);
00068 }
00069
00070 Platform::String^  Functions::countVowels(Platform::String^  words)
00071 {
00072     int count = 0;
00073     PCWSTR wordsData = words->Data();
00074     for (UINT i = 0; i < words->Length(); i++ )
00075     {
00076         WCHAR ch = wordsData[i];
00077         if (ch == 'a' || ch == 'A' ||
00078             ch == 'e' || ch == 'E' ||
00079             ch == 'i' || ch == 'I' ||
00080             ch == 'o' || ch == 'O' ||
00081             ch == 'u' || ch == 'U')
00082         {
00083             count++;
00084         }
00085     }
00086     return count.ToString();
00087 }
00088
00089 int CountEmployeesInternal(xBindSampleModel::IEmployee^ e)
00090 {
00091     int reports = 1;
00092     if (e->IsManager)
00093     {
00094         xBindSampleModel::Manager^ manager = safe_cast<xBindSampleModel::Manager^>(e);
00095         for (xBindSampleModel::IEmployee^ employee : manager->ReportsList)
00096         {
00097             reports += CountEmployeesInternal(employee);
00098         }
00099     }
00100     return reports;
00101 }
00102
00103 Platform::String^ Functions::CountEmployees(xBindSampleModel::IEmployee^ e)
00104 {
00105     return CountEmployeesInternal(e).ToString();
00106 }
00107
00108 Windows::UI::Xaml::Media::SolidColorBrush^ Functions::MakeColor(double red, double green, double blue)
00109 {
00110     return ref new SolidColorBrush(Windows::UI::ColorHelper::FromArgb(255, (byte)red, (byte)green, (byte)blue));
00111 }
00112
00113 Platform::String^ Functions::ColorValue(double red, double green, double blue)
00114 {
00115     WCHAR longString[1024];
00116     HRESULT hr = S_OK;
00117     hr = StringCchPrintf(longString, _countof(longString), L"#%02X%02X%02X",(int)red, (int)green, (int)blue);
00118     if (FAILED(hr))
00119     {
00120         throw ref new COMException(hr);
00121     }
00122     return ref new String(longString);
00123 }
00124
00125 int GetHexDigit(const WCHAR hexDigit)
00126 {
00127     int digit = 0;
00128
00129     if( hexDigit >= 'a' && hexDigit <= 'f')
00130     {
00131         return 10 + hexDigit - 'a';
00132     }
00133     if (hexDigit >= 'A' && hexDigit <= 'F')
00134     {
00135         return 10 + hexDigit - 'A';
00136     }
00137     if (isdigit(hexDigit))
00138     {
00139         return hexDigit - '0';
00140     }
00141     throw ref new InvalidArgumentException();
00142 }
00143
00144 int ParseColorDoubleByte(PCWSTR colorString, int start)
00145 {
00146     int firstDigit = GetHexDigit(colorString[start]);
00147     int secondDigit = GetHexDigit(colorString[start +1]);
00148
00149     return firstDigit * 16 + secondDigit;
00150 }
00151
00152 void Functions::ProcessColor(Platform::String^ value)
00153 {
00154     PCWSTR colorString = value->Data();
00155     if (value->Length() == 7 && colorString[0] == '#')
00156     {
00157         int red = ParseColorDoubleByte(colorString, 1);
00158         int green = ParseColorDoubleByte(colorString, 3);
00159         int blue = ParseColorDoubleByte(colorString, 5);
00160
00161         RedSlider->Value = red;
00162         GreenSlider->Value = green;
00163         BlueSlider->Value = blue;
00164     }
00165     else
00166     {
00167         throw ref new InvalidArgumentException();
00168     }
00169 }
00170
00171 Platform::String^ _colorNames[] =
00172 {
00173     "AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenrod",
00174     "DarkGray", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "DarkOrange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DodgerBlue", "Firebrick", "FloralWhite",
00175     "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "Goldenrod", "Gray", "Green", "GreenYellow", "Honeydew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenrodYellow",
00176     "LightGray", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquamarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue",
00177     "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenrod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff",
00178     "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Transparent",
00179     "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"
00180 };
00181
00182 Windows::UI::Color _colors[] =
00183 {
00184     Windows::UI::Colors::AliceBlue, Windows::UI::Colors::AntiqueWhite, Windows::UI::Colors::Aqua, Windows::UI::Colors::Aquamarine, Windows::UI::Colors::Azure, Windows::UI::Colors::Beige, Windows::UI::Colors::Bisque, Windows::UI::Colors::Black, Windows::UI::Colors::BlanchedAlmond,
00185     Windows::UI::Colors::Blue, Windows::UI::Colors::BlueViolet, Windows::UI::Colors::Brown, Windows::UI::Colors::BurlyWood, Windows::UI::Colors::CadetBlue, Windows::UI::Colors::Chartreuse, Windows::UI::Colors::Chocolate, Windows::UI::Colors::Coral, Windows::UI::Colors::CornflowerBlue,
00186     Windows::UI::Colors::Cornsilk, Windows::UI::Colors::Crimson, Windows::UI::Colors::Cyan, Windows::UI::Colors::DarkBlue, Windows::UI::Colors::DarkCyan, Windows::UI::Colors::DarkGoldenrod, Windows::UI::Colors::DarkGray, Windows::UI::Colors::DarkGreen, Windows::UI::Colors::DarkKhaki,
00187     Windows::UI::Colors::DarkMagenta, Windows::UI::Colors::DarkOliveGreen, Windows::UI::Colors::DarkOrange, Windows::UI::Colors::DarkOrchid, Windows::UI::Colors::DarkRed, Windows::UI::Colors::DarkSalmon, Windows::UI::Colors::DarkSeaGreen, Windows::UI::Colors::DarkSlateBlue,
00188     Windows::UI::Colors::DarkSlateGray, Windows::UI::Colors::DarkTurquoise, Windows::UI::Colors::DarkViolet, Windows::UI::Colors::DeepPink, Windows::UI::Colors::DeepSkyBlue, Windows::UI::Colors::DimGray, Windows::UI::Colors::DodgerBlue, Windows::UI::Colors::Firebrick,
00189     Windows::UI::Colors::FloralWhite, Windows::UI::Colors::ForestGreen, Windows::UI::Colors::Fuchsia, Windows::UI::Colors::Gainsboro, Windows::UI::Colors::GhostWhite, Windows::UI::Colors::Gold, Windows::UI::Colors::Goldenrod, Windows::UI::Colors::Gray, Windows::UI::Colors::Green,
00190     Windows::UI::Colors::GreenYellow, Windows::UI::Colors::Honeydew, Windows::UI::Colors::HotPink, Windows::UI::Colors::IndianRed, Windows::UI::Colors::Indigo, Windows::UI::Colors::Ivory, Windows::UI::Colors::Khaki, Windows::UI::Colors::Lavender, Windows::UI::Colors::LavenderBlush,
00191     Windows::UI::Colors::LawnGreen, Windows::UI::Colors::LemonChiffon, Windows::UI::Colors::LightBlue, Windows::UI::Colors::LightCoral, Windows::UI::Colors::LightCyan, Windows::UI::Colors::LightGoldenrodYellow, Windows::UI::Colors::LightGray, Windows::UI::Colors::LightGreen,
00192     Windows::UI::Colors::LightPink, Windows::UI::Colors::LightSalmon, Windows::UI::Colors::LightSeaGreen, Windows::UI::Colors::LightSkyBlue, Windows::UI::Colors::LightSlateGray, Windows::UI::Colors::LightSteelBlue, Windows::UI::Colors::LightYellow, Windows::UI::Colors::Lime,
00193     Windows::UI::Colors::LimeGreen, Windows::UI::Colors::Linen, Windows::UI::Colors::Magenta, Windows::UI::Colors::Maroon, Windows::UI::Colors::MediumAquamarine, Windows::UI::Colors::MediumBlue, Windows::UI::Colors::MediumOrchid, Windows::UI::Colors::MediumPurple,
00194     Windows::UI::Colors::MediumSeaGreen, Windows::UI::Colors::MediumSlateBlue, Windows::UI::Colors::MediumSpringGreen, Windows::UI::Colors::MediumTurquoise, Windows::UI::Colors::MediumVioletRed, Windows::UI::Colors::MidnightBlue, Windows::UI::Colors::MintCream, Windows::UI::Colors::MistyRose,
00195     Windows::UI::Colors::Moccasin, Windows::UI::Colors::NavajoWhite, Windows::UI::Colors::Navy, Windows::UI::Colors::OldLace, Windows::UI::Colors::Olive, Windows::UI::Colors::OliveDrab, Windows::UI::Colors::Orange, Windows::UI::Colors::OrangeRed, Windows::UI::Colors::Orchid,
00196     Windows::UI::Colors::PaleGoldenrod, Windows::UI::Colors::PaleGreen, Windows::UI::Colors::PaleTurquoise, Windows::UI::Colors::PaleVioletRed, Windows::UI::Colors::PapayaWhip, Windows::UI::Colors::PeachPuff, Windows::UI::Colors::Peru, Windows::UI::Colors::Pink, Windows::UI::Colors::Plum,
00197     Windows::UI::Colors::PowderBlue, Windows::UI::Colors::Purple, Windows::UI::Colors::Red, Windows::UI::Colors::RosyBrown, Windows::UI::Colors::RoyalBlue, Windows::UI::Colors::SaddleBrown, Windows::UI::Colors::Salmon, Windows::UI::Colors::SandyBrown, Windows::UI::Colors::SeaGreen,
00198     Windows::UI::Colors::SeaShell, Windows::UI::Colors::Sienna, Windows::UI::Colors::Silver, Windows::UI::Colors::SkyBlue, Windows::UI::Colors::SlateBlue, Windows::UI::Colors::SlateGray, Windows::UI::Colors::Snow, Windows::UI::Colors::SpringGreen, Windows::UI::Colors::SteelBlue,
00199     Windows::UI::Colors::Tan, Windows::UI::Colors::Teal, Windows::UI::Colors::Thistle, Windows::UI::Colors::Tomato, Windows::UI::Colors::Transparent, Windows::UI::Colors::Turquoise, Windows::UI::Colors::Violet, Windows::UI::Colors::Wheat, Windows::UI::Colors::White,
00200     Windows::UI::Colors::WhiteSmoke, Windows::UI::Colors::Yellow, Windows::UI::Colors::YellowGreen
00201 };
00202
00203 void Functions::PopulateColorsClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00204 {
00205     _ASSERT(_countof(_colors) == _countof(_colorNames));
00206     for (int i = 0; i < _countof(_colors); i++)
00207     {
00208         ColorEntry^ ce = ref new ColorEntry();
00209         ce->ColorName = _colorNames[i];
00210         ce->Color = _colors[i];
00211         ColorEntries->Append(ce);
00212     }
00213 }
00214
00215 void Functions::ClearColorsClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00216 {
00217     ColorEntries->Clear();
00218 }
00219
00220 Windows::UI::Xaml::Visibility Functions::ShowPlaceholder(unsigned int count)
00221 {
00222     return count > 0 ? Windows::UI::Xaml::Visibility::Collapsed : Windows::UI::Xaml::Visibility::Visible;
00223 }
00224
00225 SolidColorBrush^ Functions::TextColor(Windows::UI::Color c)
00226 {
00227     return ref new SolidColorBrush(((c.R * 0.299 + c.G * 0.587 + c.B * 0.114) > 150) ? Colors::Black : Colors::White);
00228 }
Generated on Fri Nov 15 2024 22:22:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cs/Scenario3_ResetPIN.xaml.cs Source File

  • SmartCard
  • cs

Scenario3_ResetPIN.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Devices.SmartCards;
00014 using Windows.Storage.Streams;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class Scenario3_ResetPIN : Page
00021     {
00022         private MainPage rootPage = MainPage.Current;
00023
00024         public Scenario3_ResetPIN()
00025         {
00026             this.InitializeComponent();
00027         }
00028
00029         /// <summary>
00030         /// Click handler for the 'ResetPin' button.
00031         /// </summary>
00032         /// <param name="sender"></param>
00033         /// <param name="e"></param>
00034         private async void ResetPin_Click(object sender, RoutedEventArgs e)
00035         {
00036             if (!rootPage.ValidateTPMSmartCard())
00037             {
00038                 rootPage.NotifyUser("Use Scenario One to create a TPM virtual smart card.", NotifyType.ErrorMessage);
00039                 return;
00040             }
00041
00042             Button b = sender as Button;
00043             b.IsEnabled = false;
00044
00045             try
00046             {
00047                 SmartCard card = await rootPage.GetSmartCard();
00048                 SmartCardProvisioning provisioning = await SmartCardProvisioning.FromSmartCardAsync(card);
00049
00050                 rootPage.NotifyUser("Resetting smart card PIN...", NotifyType.StatusMessage);
00051
00052                 // When requesting a PIN reset, a SmartCardPinResetHandler must be
00053                 // provided as an argument.  This handler must use the challenge
00054                 // it receives and the card's admin key to calculate and set the
00055                 // response.
00056                 bool result = await provisioning.RequestPinResetAsync(
00057                     (pinResetSender, request) =>
00058                     {
00059                         SmartCardPinResetDeferral deferral = request.GetDeferral();
00060
00061                         try
00062                         {
00063                             IBuffer response = ChallengeResponseAlgorithm.CalculateResponse(request.Challenge, rootPage.AdminKey);
00064                             request.SetResponse(response);
00065                         }
00066                         finally
00067                         {
00068                             deferral.Complete();
00069                         }
00070                     });
00071
00072                 if (result)
00073                 {
00074                     rootPage.NotifyUser("Smart card PIN reset operation completed.", NotifyType.StatusMessage);
00075                 }
00076                 else
00077                 {
00078                     rootPage.NotifyUser("Smart card PIN reset operation was canceled by the user.", NotifyType.StatusMessage);
00079                 }
00080
00081             }
00082             catch (Exception ex)
00083             {
00084                 rootPage.NotifyUser("Resetting smart card PIN failed with exception: " + ex.ToString(), NotifyType.ErrorMessage);
00085             }
00086             finally
00087             {
00088                 b.IsEnabled = true;
00089             }
00090         }
00091     }
00092 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1 Member List

This is the complete list of members for Scenario1, including all inherited members.
m_scenario1ViewModel | Scenario1 | [private]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario1 | [inline, protected]
Scenario1() | Scenario1 | [inline]
Generated on Fri Nov 15 2024 22:23:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ViewProjectionConstantBuffer Member List

This is the complete list of members for ViewProjectionConstantBuffer, including all inherited members.
viewProjection | ViewProjectionConstantBuffer
viewProjection | ViewProjectionConstantBuffer
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cs/AdventureWorks.shared/Properties/AssemblyInfo.cs Source File

  • CortanaVoiceCommand
  • cs
  • AdventureWorks.shared
  • Properties

AssemblyInfo.cs

Go to the documentation of this file.
00001 ﻿using System.Reflection;
00002 using System.Runtime.CompilerServices;
00003 using System.Runtime.InteropServices;
00004
00005 // General Information about an assembly is controlled through the following
00006 // set of attributes. Change these attribute values to modify the information
00007 // associated with an assembly.
00008 [assembly: AssemblyTitle("AdventureWorks.Shared")]
00009 [assembly: AssemblyDescription("")]
00010 [assembly: AssemblyConfiguration("")]
00011 [assembly: AssemblyCompany("")]
00012 [assembly: AssemblyProduct("AdventureWorks.Shared")]
00013 [assembly: AssemblyCopyright("Copyright ©  2015")]
00014 [assembly: AssemblyTrademark("")]
00015 [assembly: AssemblyCulture("")]
00016
00017 // Version information for an assembly consists of the following four values:
00018 //
00019 //      Major Version
00020 //      Minor Version
00021 //      Build Number
00022 //      Revision
00023 //
00024 // You can specify all the values or you can default the Build and Revision Numbers
00025 // by using the '*' as shown below:
00026 // [assembly: AssemblyVersion("1.0.*")]
00027 [assembly: AssemblyVersion("1.0.0.0")]
00028 [assembly: AssemblyFileVersion("1.0.0.0")]
00029 [assembly: ComVisible(false)]
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationData/cppwinrt/Scenario1_Files.h Source File

  • ApplicationData
  • cppwinrt

Scenario1_Files.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Files.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1_Files : Scenario1_FilesT<Scenario1_Files>
00020     {
00021         Scenario1_Files();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00024         fire_and_forget Increment_Local_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00025         fire_and_forget Increment_LocalCache_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00026         fire_and_forget Increment_Temporary_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00027
00028         void DisplayOutput();
00029
00030     private:
00031
00032         fire_and_forget Read_Local_Counter();
00033         fire_and_forget Read_LocalCache_Counter();
00034         fire_and_forget Read_Temporary_Counter();
00035
00036         Windows::Storage::StorageFolder localFolder = Windows::Storage::ApplicationData::Current().LocalFolder();
00037         int localCounter = 0;
00038         Windows::Storage::StorageFolder localCacheFolder = Windows::Storage::ApplicationData::Current().LocalCacheFolder();
00039         int localCacheCounter = 0;
00040         Windows::Storage::StorageFolder temporaryFolder = Windows::Storage::ApplicationData::Current().TemporaryFolder();
00041         int temporaryCounter = 0;
00042
00043         inline static const auto filename = L"sampleFile.txt";
00044     };
00045 }
00046
00047 namespace winrt::SDKTemplate::factory_implementation
00048 {
00049     struct Scenario1_Files : Scenario1_FilesT<Scenario1_Files, implementation::Scenario1_Files>
00050     {
00051     };
00052 }
00053
Generated on Fri Nov 15 2024 22:17:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cpp/Scenario3.xaml.h Source File

  • Logging
  • cpp

Scenario3.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3.g.h"
00015 #include "FileLoggingSessionScenario.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario3 sealed
00021     {
00022     public:
00023
00024         Scenario3();
00025
00026     protected:
00027
00028         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029
00030     private:
00031
00032         property FileLoggingSessionScenario^ LoggingScenario
00033         {
00034             FileLoggingSessionScenario^ get()
00035             {
00036                 return FileLoggingSessionScenario::Instance::get();
00037             }
00038         }
00039
00040         concurrency::task<void> UpdateLogMessageCountDispatchAsync();
00041         void AddMessage(Platform::String^ message);
00042         concurrency::task<void> AddMessageDispatch(Platform::String^ message);
00043         concurrency::task<void> AddLogFileMessageDispatch(Platform::String^ message, const std::wstring& logFileFullPath);
00044         void UpdateControls();
00045         void DoScenario(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046         void EnableDisableLogging(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047         void OnStatusChanged(Platform::Object^ sender, LoggingScenarioEventArgs^ args);
00048         Windows::UI::Xaml::Controls::ScrollViewer^ FindScrollViewer(DependencyObject^ depObject);
00049     };
00050 }
Generated on Fri Nov 15 2024 22:18:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/SlowInputStream.cpp Source File

  • HttpClient
  • cppwinrt

SlowInputStream.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SlowInputStream.h"
00014 #include "SlowInputStream.g.cpp"
00015
00016 using namespace std::literals::chrono_literals;
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::Storage::Streams;
00020
00021 namespace winrt::SDKTemplate::implementation
00022 {
00023     IAsyncOperationWithProgress<IBuffer, uint32_t> SlowInputStream::ReadAsync(IBuffer buffer, uint32_t count, InputStreamOptions options)
00024     {
00025         auto lifetime = get_strong();
00026
00027         // Introduce a 1 second delay.
00028         co_await resume_after(1s);
00029
00030         uint32_t capacity = buffer.Capacity();
00031         if (count > capacity)
00032         {
00033             count = capacity;
00034         }
00035
00036         uint32_t available = m_length - m_position;
00037         if (count > available)
00038         {
00039             count = available;
00040         }
00041
00042         m_position += count;
00043
00044         memset(buffer.data(), '@', count);
00045         buffer.Length(count);
00046
00047         (co_await get_progress_token())(count);
00048
00049         co_return buffer;
00050     }
00051 }
Generated on Fri Nov 15 2024 22:19:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleOrientationSensor/cpp/pch.h Source File

  • SimpleOrientationSensor
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/PixelShader/BasicTimer.cpp Source File

  • D2DCustomEffects
  • cpp
  • PixelShader

BasicTimer.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "BasicTimer.h"
00014
00015 BasicTimer::BasicTimer()
00016 {
00017     if (!QueryPerformanceFrequency(&m_frequency))
00018     {
00019         throw ref new Platform::FailureException();
00020     }
00021     Reset();
00022 }
00023
00024 void BasicTimer::Reset()
00025 {
00026     Update();
00027     m_startTime = m_currentTime;
00028     m_total = 0.0f;
00029     m_delta = 1.0f / 60.0f;
00030 }
00031
00032 void BasicTimer::Update()
00033 {
00034     if (!QueryPerformanceCounter(&m_currentTime))
00035     {
00036         throw ref new Platform::FailureException();
00037     }
00038
00039     m_total = static_cast<float>(
00040         static_cast<double>(m_currentTime.QuadPart-m_startTime.QuadPart) /
00041         static_cast<double>(m_frequency.QuadPart)
00042         );
00043
00044     if (m_lastTime.QuadPart == m_startTime.QuadPart)
00045     {
00046         // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
00047         m_delta = 1.0f / 60.0f;
00048     }
00049     else
00050     {
00051         m_delta = static_cast<float>(
00052             static_cast<double>(m_currentTime.QuadPart-m_lastTime.QuadPart) /
00053             static_cast<double>(m_frequency.QuadPart)
00054             );
00055     }
00056
00057     m_lastTime = m_currentTime;
00058 }
00059
00060 float BasicTimer::Total::get()
00061 {
00062     return m_total;
00063 }
00064
00065 float BasicTimer::Delta::get()
00066 {
00067     return m_delta;
00068 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomTextBox Member List

This is the complete list of members for CustomTextBox, including all inherited members.
CustomTextBox() CustomTextBox [inline]
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NetworkConnectivity/cppwinrt/pch.h Source File

  • NetworkConnectivity
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <hstring.h>
00015 #include <winrt/Windows.ApplicationModel.Activation.h>
00016 #include <winrt/Windows.Foundation.h>
00017 #include <winrt/Windows.Foundation.Collections.h>
00018 #include <winrt/Windows.Globalization.DateTimeFormatting.h>
00019 #include <winrt/Windows.Networking.Connectivity.h>
00020 #include <winrt/Windows.System.h>
00021 #include <winrt/Windows.UI.Core.h>
00022 #include <winrt/Windows.UI.Xaml.h>
00023 #include <winrt/Windows.UI.Xaml.Automation.Peers.h>
00024 #include <winrt/Windows.UI.Xaml.Controls.h>
00025 #include <winrt/Windows.UI.Xaml.Controls.Primitives.h>
00026 #include <winrt/Windows.UI.Xaml.Documents.h>
00027 #include <winrt/Windows.UI.Xaml.Interop.h>
00028 #include <winrt/Windows.UI.Xaml.Markup.h>
00029 #include <winrt/Windows.UI.Xaml.Media.h>
00030 #include <winrt/Windows.UI.Xaml.Navigation.h>
00031 #include <winrt/Windows.Web.Http.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/PlaybackPage.xaml.cs Source File

  • 360VideoPlayback
  • cs

PlaybackPage.xaml.cs

Go to the documentation of this file.
00001 ﻿using _360VideoPlayback.Common;
00002 using System;
00003 using Windows.Foundation;
00004 using Windows.Gaming.Input;
00005 using Windows.Media.Core;
00006 using Windows.Media.Playback;
00007 using Windows.System;
00008 using Windows.System.Threading;
00009 using Windows.UI.Core;
00010 using Windows.UI.Xaml;
00011 using Windows.UI.Xaml.Controls;
00012 using Windows.UI.Xaml.Input;
00013 using Windows.UI.Xaml.Media;
00014 using Windows.UI.Xaml.Navigation;
00015
00016 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00017
00018 namespace _360VideoPlayback
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     public sealed partial class PlaybackPage : Page
00024     {
00025         private MediaPlayer mediaPlayer;
00026         // positions hold the center of the window
00027         private double centerX = 0, centerY = 0;
00028         // MTC grid to ignore mouse event on the MTC Panel
00029         Grid mtcGrid = null;
00030         private double pitch = 0, heading = 0;
00031         private MediaPlaybackSphericalVideoProjection videoProjection;
00032         private bool isPointerPress = false;
00033         IAsyncAction m_inputLoopWorker = null;
00034         Gamepad activeGamePad = null;
00035         WorkItemHandler workItemHandler;
00036         const double THUMBSTICK_DEADZONE = 0.25f;
00037         //Frame Timer
00038         private StepTimer timer = new StepTimer();
00039         double rotationdelta = 1.8f;
00040         const int scrollStep = 2;
00041         const int mouseWheelData = 120;
00042
00043         public PlaybackPage()
00044         {
00045             this.InitializeComponent();
00046             this.LayoutUpdated += PlaybackPage_LayoutUpdated;
00047         }
00048
00049         private void PlaybackPage_LayoutUpdated(object sender, object e)
00050         {
00051             centerX = VideoElement.ActualWidth / 2;
00052             centerY = VideoElement.ActualHeight / 2;
00053             if (mtcGrid == null)
00054             {
00055                 FrameworkElement transportControlsTemplateRoot = (FrameworkElement)VisualTreeHelper.GetChild(VideoElement.TransportControls, 0);
00056                 if (transportControlsTemplateRoot != null)
00057                 {
00058                     mtcGrid = (Grid)transportControlsTemplateRoot.FindName("ControlPanelGrid");
00059                     mtcGrid.PointerPressed += OnPointerPressed;
00060                     mtcGrid.PointerReleased += OnPointerReleased;
00061                     mtcGrid.PointerWheelChanged += OnPointerWheelChanged;
00062                     VideoElement.PointerPressed += OnPointerPressed;
00063                     VideoElement.PointerReleased += OnPointerReleased;
00064                     VideoElement.PointerMoved += OnPointerMoved;
00065                     VideoElement.PointerWheelChanged += OnPointerWheelChanged;
00066                     Window.Current.CoreWindow.KeyDown += OnKeyDown;
00067                 }
00068             }
00069         }
00070
00071         private void OnPointerWheelChanged(object sender, PointerRoutedEventArgs e)
00072         {
00073             if (e.OriginalSource != mtcGrid)
00074             {
00075                 double value = videoProjection.HorizontalFieldOfViewInDegrees +
00076                     (scrollStep * e.GetCurrentPoint(VideoElement).Properties.MouseWheelDelta / mouseWheelData);
00077                 if (value > 0 && value <= 180)
00078                 {
00079                     videoProjection.HorizontalFieldOfViewInDegrees = value;
00080                 }
00081             }
00082             e.Handled = true;
00083         }
00084
00085         private void OnKeyDown(CoreWindow sender, KeyEventArgs args)
00086         {
00087             if (IsMediaAlreadyOpened())
00088             {
00089                 bool isMTCEnabled = VideoElement.AreTransportControlsEnabled;
00090
00091                 if (args.VirtualKey == VirtualKey.Up)
00092                 {
00093                     pitch = pitch + 0.5;
00094                     videoProjection.ViewOrientation = Helpers.CreateFromHeadingPitchRoll(heading, pitch, 0);
00095                 }
00096                 if (args.VirtualKey == VirtualKey.Down)
00097                 {
00098                     pitch = pitch - 0.5;
00099                     videoProjection.ViewOrientation = Helpers.CreateFromHeadingPitchRoll(heading, pitch, 0);
00100                 }
00101                 if (args.VirtualKey == VirtualKey.Right)
00102                 {
00103                     heading = heading + 0.5;
00104                     videoProjection.ViewOrientation = Helpers.CreateFromHeadingPitchRoll(heading, pitch, 0);
00105                 }
00106                 if (args.VirtualKey == VirtualKey.Left)
00107                 {
00108                     heading = heading - 0.5;
00109                     videoProjection.ViewOrientation = Helpers.CreateFromHeadingPitchRoll(heading, pitch, 0);
00110                 }
00111                 if (args.VirtualKey == VirtualKey.GamepadA)
00112                 {
00113                     if (!isMTCEnabled)
00114                     {
00115                         VideoElement.AreTransportControlsEnabled = true;
00116                         m_inputLoopWorker.Cancel();
00117                         args.Handled = true;
00118                     }
00119
00120                 }
00121                 if (args.VirtualKey == VirtualKey.GamepadB)
00122                 {
00123                     if (isMTCEnabled)
00124                     {
00125                         VideoElement.AreTransportControlsEnabled = false;
00126                         StartInputLoop();
00127                         args.Handled = true;
00128                     }
00129                 }
00130                 if (args.VirtualKey == VirtualKey.GamepadLeftTrigger)
00131                 {
00132                     double value = videoProjection.HorizontalFieldOfViewInDegrees + 2;
00133
00134                     if (value <= 180)
00135                     {
00136                         videoProjection.HorizontalFieldOfViewInDegrees = value;
00137                     }
00138                     args.Handled = true;
00139                 }
00140                 if (args.VirtualKey == VirtualKey.GamepadRightTrigger)
00141                 {
00142                     double value = videoProjection.HorizontalFieldOfViewInDegrees - 2;
00143
00144                     if (value > 0)
00145                     {
00146                         videoProjection.HorizontalFieldOfViewInDegrees = value;
00147                     }
00148                     args.Handled = true;
00149                 }
00150             }
00151         }
00152
00153         private void OnPointerMoved(object sender, PointerRoutedEventArgs e)
00154         {
00155             if (e.OriginalSource != mtcGrid && isPointerPress)
00156             {
00157                 double ChangeX = e.GetCurrentPoint(VideoElement).Position.X - centerX;
00158                 double ChangeY = centerY - e.GetCurrentPoint(VideoElement).Position.Y;
00159                 videoProjection.ViewOrientation = Helpers.CreateFromHeadingPitchRoll(ChangeX, ChangeY, 0);
00160             }
00161             e.Handled = true;
00162         }
00163
00164         private void OnPointerReleased(object sender, PointerRoutedEventArgs e)
00165         {
00166             ResetState();
00167             e.Handled = true;
00168         }
00169
00170         private void OnPointerPressed(object sender, PointerRoutedEventArgs e)
00171         {
00172             if (e.OriginalSource != mtcGrid && IsMediaAlreadyOpened())
00173             {
00174                 isPointerPress = true;
00175             }
00176             e.Handled = true;
00177         }
00178
00179         protected override void OnNavigatedTo(NavigationEventArgs e)
00180         {
00181             SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
00182
00183             Uri sourceUri = (Uri)e.Parameter;
00184             if (sourceUri != null)
00185             {
00186                 mediaPlayer = new MediaPlayer();
00187                 MediaSource source = MediaSource.CreateFromUri(sourceUri);
00188                 mediaPlayer.Source = source;
00189                 mediaPlayer.MediaOpened += MediaPlayer_MediaOpened;
00190                 VideoElement.SetMediaPlayer(mediaPlayer);
00191             }
00192         }
00193
00194         private void MediaPlayer_MediaOpened(MediaPlayer sender, object args)
00195         {
00196             videoProjection = mediaPlayer.PlaybackSession.SphericalVideoProjection;
00197             Windows.Media.MediaProperties.SphericalVideoFrameFormat videoFormat = videoProjection.FrameFormat;
00198             // Some times Content metadata doesn't provided correct format. Try to force the equirectangular format, if doesn't match
00199             if (videoFormat != Windows.Media.MediaProperties.SphericalVideoFrameFormat.Equirectangular)
00200             {
00201                 videoProjection.FrameFormat = Windows.Media.MediaProperties.SphericalVideoFrameFormat.Equirectangular;
00202             }
00203             videoProjection.IsEnabled = true;
00204             videoProjection.HorizontalFieldOfViewInDegrees = 120;
00205             mediaPlayer.PlaybackSession.PlaybackStateChanged += PlaybackSession_PlaybackStateChanged;
00206
00207             StartInputLoop();
00208         }
00209
00210         private void PlaybackSession_PlaybackStateChanged(MediaPlaybackSession sender, object args)
00211         {
00212             if (mediaPlayer.PlaybackSession.PlaybackState == MediaPlaybackState.Playing)
00213             {
00214                 rotationdelta = 1.8f;
00215             }
00216             else
00217             {
00218                 rotationdelta = 0.25f;
00219             }
00220         }
00221
00222         private bool IsMediaAlreadyOpened()
00223         {
00224             if (mediaPlayer != null && videoProjection != null &&
00225                 mediaPlayer.PlaybackSession.PlaybackState != MediaPlaybackState.Opening &&
00226                 mediaPlayer.PlaybackSession.PlaybackState != MediaPlaybackState.None)
00227             {
00228                 return true;
00229             }
00230             return false;
00231         }
00232
00233         private void ResetState()
00234         {
00235             isPointerPress = false;
00236             pitch = 0;
00237             heading = 0;
00238         }
00239
00240         protected override void OnNavigatedFrom(NavigationEventArgs e)
00241         {
00242             if (mediaPlayer != null)
00243             {
00244                 mediaPlayer.PlaybackSession.PlaybackStateChanged -= PlaybackSession_PlaybackStateChanged;
00245                 mediaPlayer.MediaOpened -= MediaPlayer_MediaOpened;
00246             }
00247             if (mtcGrid != null)
00248             {
00249                 mtcGrid.PointerPressed -= OnPointerPressed;
00250                 mtcGrid.PointerReleased -= OnPointerReleased;
00251                 mtcGrid.PointerWheelChanged -= OnPointerWheelChanged;
00252                 VideoElement.PointerPressed -= OnPointerPressed;
00253                 VideoElement.PointerReleased -= OnPointerReleased;
00254                 VideoElement.PointerMoved -= OnPointerMoved;
00255                 VideoElement.PointerWheelChanged -= OnPointerWheelChanged;
00256                 Window.Current.CoreWindow.KeyDown -= OnKeyDown;
00257             }
00258
00259             SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
00260             mediaPlayer.Source = null;
00261             VideoElement.SetMediaPlayer(null);
00262             mediaPlayer = null;
00263         }
00264
00265         void StartInputLoop()
00266         {
00267             // If the animation render loop is already running then do not start another thread.
00268             if (m_inputLoopWorker != null)
00269             {
00270                 if (m_inputLoopWorker.Status == AsyncStatus.Started)
00271                 {
00272                     return;
00273                 }
00274                 else
00275                 {
00276                     m_inputLoopWorker.Close();
00277                 }
00278             }
00279
00280             workItemHandler = new WorkItemHandler((IAsyncAction action) =>
00281             {
00282                 while (action.Status == AsyncStatus.Started)
00283                 {
00284                     var gamepads = Gamepad.Gamepads;
00285                     if (gamepads.Count > 0 && activeGamePad == null)
00286                     {
00287                         // Get the Zero based first Gamepad
00288                         activeGamePad = gamepads[0];
00289                     }
00290
00291                     if (activeGamePad != null)
00292                     {
00293                         timer.Tick(() =>
00294                         {
00295                             GamepadReading reading = activeGamePad.GetCurrentReading();
00296                             double deltax;
00297                             if (reading.LeftThumbstickX > THUMBSTICK_DEADZONE || reading.LeftThumbstickX < -THUMBSTICK_DEADZONE)
00298                             {
00299                                 deltax = reading.LeftThumbstickX * reading.LeftThumbstickX * reading.LeftThumbstickX;
00300                             }
00301                             else
00302                             {
00303                                 deltax = 0.0f;
00304                             }
00305                             double deltay;
00306                             if (reading.LeftThumbstickY > THUMBSTICK_DEADZONE || reading.LeftThumbstickY < -THUMBSTICK_DEADZONE)
00307                             {
00308                                 deltay = reading.LeftThumbstickY * reading.LeftThumbstickY * reading.LeftThumbstickY;
00309                             }
00310                             else
00311                             {
00312                                 deltay = 0.0f;
00313                             }
00314
00315                             double rotationX = deltax * rotationdelta;
00316                             double rotationY = deltay * rotationdelta;
00317
00318                             pitch += rotationY;
00319                             heading += rotationX;
00320
00321                             // Limit pitch to straight up or straight down.
00322                             videoProjection.ViewOrientation = Helpers.CreateFromHeadingPitchRoll(heading, pitch, 0);
00323                         });
00324                     }
00325                 }
00326             });
00327
00328             m_inputLoopWorker = ThreadPool.RunAsync(workItemHandler, WorkItemPriority.High, WorkItemOptions.None);
00329         }
00330     }
00331 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cs/Scenario3_CustomItems.xaml.cs Source File

  • JumpList
  • cs

Scenario3_CustomItems.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.StartScreen;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario3_CustomItems : Page
00020     {
00021         public Scenario3_CustomItems()
00022         {
00023             this.InitializeComponent();
00024         }
00025
00026         private void DisplayNameLocalizedResource_Click(object sender, RoutedEventArgs e)
00027         {
00028             DisplayName.IsEnabled = !(bool)DisplayNameLocalizedResource.IsChecked;
00029             DisplayName.Text = "ms-resource:///Resources/CustomJumpListItemDisplayName";
00030         }
00031
00032         private void DescriptionLocalizedResource_Click(object sender, RoutedEventArgs e)
00033         {
00034             Description.IsEnabled = !(bool)DescriptionLocalizedResource.IsChecked;
00035             Description.Text = "ms-resource:///Resources/CustomJumpListItemDescription";
00036         }
00037
00038         private void GroupNameLocalizedResource_Click(object sender, RoutedEventArgs e)
00039         {
00040             GroupName.IsEnabled = !(bool)GroupNameLocalizedResource.IsChecked;
00041             GroupName.Text = "ms-resource:///Resources/CustomJumpListGroupName";
00042         }
00043
00044         private async void AddToJumpList_Click(object sender, RoutedEventArgs e)
00045         {
00046             var jumpList = await JumpList.LoadCurrentAsync();
00047
00048             var item = JumpListItem.CreateWithArguments(Arguments.Text, DisplayName.Text);
00049             item.Description = Description.Text;
00050             item.GroupName = GroupName.Text;
00051             item.Logo = new Uri("ms-appx:///Assets/smalltile-sdk.png");
00052
00053             jumpList.Items.Add(item);
00054
00055             await jumpList.SaveAsync();
00056         }
00057     }
00058 }
Generated on Fri Nov 15 2024 22:20:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Animate.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Animate.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Animate.h"
00014
00015 using namespace DirectX;
00016
00017 Animate::Animate() :
00018     m_continuous(false),
00019     m_startTime(0.0f),
00020     m_duration(10.0f)
00021 {
00022 }
00023
00024 float Animate::Start()
00025 {
00026     return m_startTime;
00027 }
00028
00029 void Animate::Start(_In_ float start)
00030 {
00031     m_startTime = start;
00032 }
00033
00034 float Animate::Duration()
00035 {
00036     return m_duration;
00037 }
00038
00039 void Animate::Duration(_In_ float duration)
00040 {
00041     m_duration = duration;
00042 }
00043
00044 bool Animate::Continuous()
00045 {
00046     return m_continuous;
00047 }
00048
00049 void Animate::Continuous(_In_ bool continuous)
00050 {
00051     m_continuous = continuous;
00052 }
00053
00054 AnimateLinePosition::AnimateLinePosition(
00055     _In_ XMFLOAT3 startPosition,
00056     _In_ XMFLOAT3 endPosition,
00057     _In_ float duration,
00058     _In_ bool continuous)
00059 {
00060     m_startPosition = startPosition;
00061     m_endPosition = endPosition;
00062     m_duration = duration;
00063     m_continuous = continuous;
00064
00065     m_length = XMVectorGetX(
00066         XMVector3Length(XMLoadFloat3(&endPosition) - XMLoadFloat3(&startPosition))
00067         );
00068 }
00069
00070 XMFLOAT3 AnimateLinePosition::Evaluate(_In_ float t)
00071 {
00072     if (t <= m_startTime)
00073     {
00074         return m_startPosition;
00075     }
00076
00077     if ((t >= (m_startTime + m_duration)) && !m_continuous)
00078     {
00079         return m_endPosition;
00080     }
00081
00082     float startTime = m_startTime;
00083     if (m_continuous)
00084     {
00085         // For continuous operation move the start time forward to
00086         // eliminate previous iterations.
00087         startTime += ((int)((t - m_startTime) / m_duration)) * m_duration;
00088     }
00089
00090     float u = (t - startTime) / m_duration;
00091     XMFLOAT3 currentPosition;
00092     currentPosition.x = m_startPosition.x + (m_endPosition.x - m_startPosition.x) * u;
00093     currentPosition.y = m_startPosition.y + (m_endPosition.y - m_startPosition.y) * u;
00094     currentPosition.z = m_startPosition.z + (m_endPosition.z - m_startPosition.z) * u;
00095
00096     return currentPosition;
00097 }
00098
00099 AnimateLineListPosition::AnimateLineListPosition(
00100     _In_ unsigned int count,
00101     _In_reads_(count) XMFLOAT3 const position[],
00102     _In_ float duration,
00103     _In_ bool continuous)
00104 {
00105     m_duration = duration;
00106     m_continuous = continuous;
00107     m_count = count;
00108
00109     m_segment = std::vector<LineSegment>(m_count);
00110     m_totalLength = 0.0f;
00111
00112     m_segment[0].position = position[0];
00113     for (unsigned int i = 1; i < count; i++)
00114     {
00115         m_segment[i].position = position[i];
00116         m_segment[i - 1].length = XMVectorGetX(
00117             XMVector3Length(
00118                 XMLoadFloat3(&m_segment[i].position) -
00119                 XMLoadFloat3(&m_segment[i - 1].position)
00120                 )
00121             );
00122         m_totalLength += m_segment[i - 1].length;
00123     }
00124
00125     // Parameterize the segments to ensure uniform evaluation along the path.
00126     float u = 0.0f;
00127     for (unsigned int i = 0; i < (count - 1); i++)
00128     {
00129         m_segment[i].uStart = u;
00130         m_segment[i].uLength = (m_segment[i].length / m_totalLength);
00131         u += m_segment[i].uLength;
00132     }
00133     m_segment[count - 1].uStart = 1.0f;
00134 }
00135
00136 XMFLOAT3 AnimateLineListPosition::Evaluate(_In_ float t)
00137 {
00138     if (t <= m_startTime)
00139     {
00140         return m_segment[0].position;
00141     }
00142
00143     if ((t >= (m_startTime + m_duration)) && !m_continuous)
00144     {
00145         return m_segment[m_count - 1].position;
00146     }
00147
00148     float startTime = m_startTime;
00149     if (m_continuous)
00150     {
00151         // For continuous operation move the start time forward to
00152         // eliminate previous iterations.
00153         startTime += ((int)((t - m_startTime) / m_duration)) * m_duration;
00154     }
00155
00156     float u = (t - startTime) / m_duration;
00157     // Find the right segment.
00158     unsigned int i = 0;
00159     while (u > m_segment[i + 1].uStart)
00160     {
00161         i++;
00162     }
00163
00164     u -= m_segment[i].uStart;
00165     u /= m_segment[i].uLength;
00166
00167     XMFLOAT3 currentPosition;
00168     currentPosition.x = m_segment[i].position.x + (m_segment[i + 1].position.x - m_segment[i].position.x) * u;
00169     currentPosition.y = m_segment[i].position.y + (m_segment[i + 1].position.y - m_segment[i].position.y) * u;
00170     currentPosition.z = m_segment[i].position.z + (m_segment[i + 1].position.z - m_segment[i].position.z) * u;
00171
00172     return currentPosition;
00173 }
00174
00175 AnimateCirclePosition::AnimateCirclePosition(
00176     _In_ XMFLOAT3 center,
00177     _In_ XMFLOAT3 startPosition,
00178     _In_ XMFLOAT3 planeNormal,
00179     _In_ float duration,
00180     _In_ bool continuous,
00181     _In_ bool clockwise)
00182 {
00183     m_center = center;
00184     m_planeNormal = planeNormal;
00185     m_startPosition = startPosition;
00186     m_duration = duration;
00187     m_continuous = continuous;
00188     m_clockwise = clockwise;
00189
00190     XMVECTOR coordX = XMLoadFloat3(&m_startPosition) - XMLoadFloat3(&m_center);
00191     m_radius = XMVectorGetX(XMVector3Length(coordX));
00192
00193     XMVector3Normalize(coordX);
00194
00195     XMVECTOR coordZ = XMLoadFloat3(&m_planeNormal);
00196     XMVector3Normalize(coordZ);
00197
00198     XMVECTOR coordY;
00199     if (m_clockwise)
00200     {
00201         coordY = XMVector3Cross(coordZ, coordX);
00202     }
00203     else
00204     {
00205         coordY = XMVector3Cross(coordX, coordZ);
00206     }
00207
00208     XMVECTOR vectorX = XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f);
00209     XMVECTOR vectorY = XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f);
00210     XMMATRIX mat1 = XMMatrixIdentity();
00211     XMMATRIX mat2 = XMMatrixIdentity();
00212
00213     if (!XMVector3Equal(coordX, vectorX))
00214     {
00215         float angle;
00216         angle = XMVectorGetX(
00217             XMVector3AngleBetweenVectors(vectorX, coordX)
00218             );
00219         if ((angle * angle) > 0.025)
00220         {
00221             XMVECTOR axis1 = XMVector3Cross(vectorX, coordX);
00222
00223             mat1 = XMMatrixRotationAxis(axis1, angle);
00224             vectorY = XMVector3TransformCoord(vectorY, mat1);
00225         }
00226     }
00227     if (!XMVector3Equal(vectorY, coordY))
00228     {
00229         float angle;
00230         angle = XMVectorGetX(
00231             XMVector3AngleBetweenVectors(vectorY, coordY)
00232             );
00233         if ((angle * angle) > 0.025)
00234         {
00235             XMVECTOR axis2 = XMVector3Cross(vectorY, coordY);
00236             mat2 = XMMatrixRotationAxis(axis2, angle);
00237         }
00238     }
00239     XMStoreFloat4x4(
00240         &m_rotationMatrix,
00241         mat1 *
00242         mat2 *
00243         XMMatrixTranslation(m_center.x, m_center.y, m_center.z)
00244         );
00245 }
00246
00247 XMFLOAT3 AnimateCirclePosition::Evaluate(_In_ float t)
00248 {
00249     if (t <= m_startTime)
00250     {
00251         return m_startPosition;
00252     }
00253
00254     if ((t >= (m_startTime + m_duration)) && !m_continuous)
00255     {
00256         return m_startPosition;
00257     }
00258
00259     float startTime = m_startTime;
00260     if (m_continuous)
00261     {
00262         // For continuous operation move the start time forward to
00263         // eliminate previous iterations.
00264         startTime += ((int)((t - m_startTime) / m_duration)) * m_duration;
00265     }
00266
00267     float u = (t - startTime) / m_duration * XM_2PI;
00268
00269     XMFLOAT3 currentPosition;
00270     currentPosition.x = m_radius * cos(u);
00271     currentPosition.y = m_radius * sin(u);
00272     currentPosition.z = 0.0f;
00273
00274     XMStoreFloat3(
00275         &currentPosition,
00276         XMVector3TransformCoord(
00277             XMLoadFloat3(&currentPosition),
00278             XMLoadFloat4x4(&m_rotationMatrix)
00279             )
00280         );
00281
00282     return currentPosition;
00283 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3 Member List

This is the complete list of members for Scenario3, including all inherited members.
ClearProcessUIPolicy_Click(object sender, RoutedEventArgs e) | Scenario3 | [inline, private]
m_clearPolicyText | Scenario3 | [private]
m_copyPasteScenarioText | Scenario3 | [private]
m_testDataToCopy | Scenario3 | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3 | [inline, protected]
rootPage | Scenario3 | [private]
Scenario3() | Scenario3 | [inline]
TryApplyProcessUIPolicy_Click(object sender, RoutedEventArgs e) | Scenario3 | [inline, private]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SampleBackgroundTask Member List

This is the complete list of members for SampleBackgroundTask, including all inherited members.
_cancelReason | SampleBackgroundTask | [private]
_cancelRequested | SampleBackgroundTask | [private]
_deferral | SampleBackgroundTask | [private]
_periodicTimer | SampleBackgroundTask | [private]
_progress | SampleBackgroundTask | [private]
_taskInstance | SampleBackgroundTask | [private]
OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) | SampleBackgroundTask | [inline, private]
PeriodicTimerCallback(ThreadPoolTimer timer) | SampleBackgroundTask | [inline, private]
Run(IBackgroundTaskInstance taskInstance) | SampleBackgroundTask | [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FullScreenMode/cpp/Scenario1_Basic.xaml.h Source File

  • FullScreenMode
  • cpp

Scenario1_Basic.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Basic.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario1_Basic sealed
00021     {
00022     public:
00023         Scenario1_Basic();
00024
00025     protected:
00026         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00027         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00028
00029     private:
00030         MainPage^ rootPage;
00031
00032         // What is the program's last known full-screen state?
00033         // We use this to detect when the system forced us out of full-screen mode.
00034         bool isLastKnownFullScreen = Windows::UI::ViewManagement::ApplicationView::GetForCurrentView()->IsFullScreenMode;
00035
00036         void ToggleFullScreenModeButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         void ShowStandardSystemOverlaysButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         void UseMinimalOverlaysCheckBox_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         void OnWindowResize(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e);
00040         void UpdateContent();
00041         void OnKeyDown(Platform::Object^ sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs^ e);
00042
00043         Windows::Foundation::EventRegistrationToken windowResizeToken;
00044         Windows::Foundation::EventRegistrationToken keyDownToken;
00045     };
00046 }
Generated on Fri Nov 15 2024 22:19:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/GameTimer.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

GameTimer.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "GameTimer.h"
00014
00015 GameTimer::GameTimer() :
00016     m_active(false)
00017 {
00018     LARGE_INTEGER frequency;
00019     if (!QueryPerformanceFrequency(&frequency))
00020     {
00021         winrt::throw_hresult(E_FAIL);
00022     }
00023     m_secondsPerCount = 1.0f / static_cast<float>(frequency.QuadPart);
00024
00025     Reset();
00026 }
00027
00028 // Returns the total time elapsed since Reset() was called, NOT counting any
00029 // time when the clock is stopped.
00030 float GameTimer::PlayingTime()
00031 {
00032     if (m_active)
00033     {
00034         // The distance m_currentTime - m_baseTime includes paused time,
00035         // which we do not want to count. To correct this, we can subtract
00036         // the paused time from m_currentTime:
00037         return static_cast<float>(((m_currentTime.QuadPart - m_pausedTime.QuadPart) - m_baseTime.QuadPart) * m_secondsPerCount);
00038     }
00039     else
00040     {
00041         // The clock is currently not running so don't count the time since
00042         // the clock was stopped
00043         return static_cast<float>(((m_stopTime.QuadPart - m_pausedTime.QuadPart) - m_baseTime.QuadPart) * m_secondsPerCount);
00044     }
00045 }
00046
00047
00048 void GameTimer::PlayingTime(float time)
00049 {
00050     // Reset the internal state to reflect a PlayingTime of 'time'
00051     // Offset the baseTime by this 'time'.
00052     m_active = false;
00053     m_stopTime = m_currentTime;
00054     m_pausedTime.QuadPart = 0;
00055
00056     m_baseTime.QuadPart = m_stopTime.QuadPart - static_cast<__int64>(time / m_secondsPerCount);
00057 }
00058
00059
00060 float GameTimer::DeltaTime()
00061 {
00062     return m_deltaTime;
00063 }
00064
00065 void GameTimer::Reset()
00066 {
00067     LARGE_INTEGER currentTime;
00068     if (!QueryPerformanceCounter(&currentTime))
00069     {
00070         winrt::throw_hresult(E_FAIL);
00071     }
00072     m_baseTime = currentTime;
00073     m_previousTime = currentTime;
00074     m_stopTime = currentTime;
00075     m_currentTime = currentTime;
00076     m_pausedTime.QuadPart = 0;
00077     m_active = false;
00078 }
00079
00080 void GameTimer::Start()
00081 {
00082     LARGE_INTEGER startTime;
00083     if (!QueryPerformanceCounter(&startTime))
00084     {
00085         winrt::throw_hresult(E_FAIL);
00086     }
00087     if (!m_active)
00088     {
00089         // Accumulate the time elapsed between stop and start pairs.
00090         m_pausedTime.QuadPart += (startTime.QuadPart - m_stopTime.QuadPart);
00091
00092         m_previousTime = startTime;
00093         m_stopTime.QuadPart = 0;
00094         m_active = true;
00095     }
00096 }
00097
00098 void GameTimer::Stop()
00099 {
00100     if (m_active)
00101     {
00102         // Set the stop time to the time of the last update.
00103         m_stopTime = m_currentTime;
00104         m_active = false;
00105     }
00106 }
00107
00108 void GameTimer::Update()
00109 {
00110     if (!m_active)
00111     {
00112         m_deltaTime = 0.0;
00113         return;
00114     }
00115
00116     LARGE_INTEGER currentTime;
00117     if (!QueryPerformanceCounter(&currentTime))
00118     {
00119         winrt::throw_hresult(E_FAIL);
00120     }
00121     m_currentTime = currentTime;
00122
00123     m_deltaTime = (m_currentTime.QuadPart - m_previousTime.QuadPart) * m_secondsPerCount;
00124     m_previousTime = m_currentTime;
00125
00126     if (m_deltaTime < 0.0)
00127     {
00128         m_deltaTime = 0.0;
00129     }
00130 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicMediaCasting/cs/Scenario3_CustomPicker.xaml.cs Source File

  • BasicMediaCasting
  • cs

Scenario3_CustomPicker.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using SDKTemplate;
00017 using Windows.Storage;
00018 using Windows.Storage.Pickers;
00019 using Windows.Storage.Streams;
00020 using Windows.Media.Casting;
00021 using Windows.Devices.Enumeration;
00022
00023 namespace BasicMediaCasting
00024 {
00025     public sealed partial class Scenario3 : Page
00026     {
00027         private MainPage rootPage;
00028         private DeviceWatcher watcher;
00029         private CastingConnection connection;
00030
00031         public Scenario3()
00032         {
00033             this.InitializeComponent();
00034
00035             //Create our watcher and have it find casting devices capable of video casting
00036             watcher = DeviceInformation.CreateWatcher(CastingDevice.GetDeviceSelector(CastingPlaybackTypes.Video));
00037
00038             //Register for watcher events
00039             watcher.Added += Watcher_Added;
00040             watcher.Removed += Watcher_Removed;
00041             watcher.Stopped += Watcher_Stopped;
00042             watcher.EnumerationCompleted += Watcher_EnumerationCompleted;
00043         }
00044
00045         protected override void OnNavigatedTo(NavigationEventArgs e)
00046         {
00047             rootPage = MainPage.Current;
00048         }
00049
00050         private async void loadButton_Click(object sender, RoutedEventArgs e)
00051         {
00052             //Create a new picker
00053             FileOpenPicker filePicker = new FileOpenPicker();
00054
00055             //Add filetype filters.  In this case wmv and mp4.
00056             filePicker.FileTypeFilter.Add(".wmv");
00057             filePicker.FileTypeFilter.Add(".mp4");
00058
00059             //Set picker start location to the video library
00060             filePicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
00061
00062             //Retrieve file from picker
00063             StorageFile file = await filePicker.PickSingleFileAsync();
00064
00065             //If we got a file, load it into the media element
00066             if (file != null)
00067             {
00068                 IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
00069                 video.SetSource(stream, file.ContentType);
00070                 rootPage.NotifyUser("Content Selected", NotifyType.StatusMessage);
00071             }
00072         }
00073
00074         private void watcherControlButton_Click(object sender, RoutedEventArgs e)
00075         {
00076             //If the watcher isn't running, start it up
00077             if (watcher.Status != DeviceWatcherStatus.Started)
00078             {
00079                 //clear the list as we're starting the watcher over
00080                 castingDevicesList.Items.Clear();
00081
00082                 //start the watcher
00083                 watcher.Start();
00084
00085                 //update the UI to reflect the watcher's state
00086                 rootPage.NotifyUser("Watcher has been started", NotifyType.StatusMessage);
00087                 watcherControlButton.Content = "Stop Device Watcher";
00088                 progressText.Text = "Searching";
00089                 progressRing.IsActive = true;
00090             }
00091             else
00092             {
00093                 //if the watcher is running, stop the watcher and update UI
00094                 progressText.Text = "";
00095                 watcher.Stop();
00096             }
00097         }
00098
00099         private async void Watcher_Added(DeviceWatcher sender, DeviceInformation args)
00100         {
00101             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
00102             {
00103                 //Add each discovered device to our listbox
00104                 CastingDevice addedDevice = await CastingDevice.FromIdAsync(args.Id);
00105                 castingDevicesList.Items.Add(addedDevice);
00106             });
00107         }
00108
00109         private async void Watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
00110         {
00111             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00112             {
00113                 //Remove any removed devices from our listbox
00114                 foreach (CastingDevice currentDevice in castingDevicesList.Items)
00115                 {
00116                     if (currentDevice.Id == args.Id)
00117                     {
00118                         castingDevicesList.Items.Remove(currentDevice);
00119                         break;
00120                     }
00121                 }
00122             });
00123         }
00124
00125         private async void Watcher_EnumerationCompleted(DeviceWatcher sender, object args)
00126         {
00127             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00128             {
00129                 //If enumeration completes, update UI and transition watcher to the stopped state
00130                 rootPage.NotifyUser("Watcher completed enumeration of devices", NotifyType.StatusMessage);
00131                 progressText.Text = "Enumeration Completed";
00132                 watcher.Stop();
00133             });
00134         }
00135
00136         private async void Watcher_Stopped(DeviceWatcher sender, object args)
00137         {
00138             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00139             {
00140                 //Update UX when the watcher stops
00141                 rootPage.NotifyUser("Watcher has been stopped", NotifyType.StatusMessage);
00142                 watcherControlButton.Content = "Start Device Watcher";
00143                 progressRing.IsActive = false;
00144             });
00145         }
00146
00147         private async void castingDevicesList_SelectionChanged(object sender, SelectionChangedEventArgs e)
00148         {
00149             if (castingDevicesList.SelectedItem != null)
00150             {
00151                 //When a device is selected, first thing we do is stop the watcher so it's search doesn't conflict with streaming
00152                 if (watcher.Status != DeviceWatcherStatus.Stopped)
00153                 {
00154                     progressText.Text = "";
00155                     watcher.Stop();
00156                 }
00157
00158                 //Create a new casting connection to the device that's been selected
00159                 connection = ((CastingDevice)castingDevicesList.SelectedItem).CreateCastingConnection();
00160
00161                 //Register for events
00162                 connection.ErrorOccurred += Connection_ErrorOccurred;
00163                 connection.StateChanged += Connection_StateChanged;
00164
00165                 //Cast the loaded video to the selected casting device.
00166                 await connection.RequestStartCastingAsync(video.GetAsCastingSource());
00167             }
00168         }
00169
00170         private async void Connection_StateChanged(CastingConnection sender, object args)
00171         {
00172            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00173            {
00174                //Update the UX based on the casting state
00175                if (sender.State == CastingConnectionState.Connected || sender.State == CastingConnectionState.Rendering)
00176                {
00177                    disconnectButton.Visibility = Visibility.Visible;
00178                    progressText.Text = "Connected";
00179                    progressRing.IsActive = false;
00180                }
00181                else if (sender.State == CastingConnectionState.Disconnected)
00182                {
00183                    disconnectButton.Visibility = Visibility.Collapsed;
00184                    castingDevicesList.SelectedItem = null;
00185                    progressText.Text = "";
00186                    progressRing.IsActive = false;
00187                }
00188                else if (sender.State == CastingConnectionState.Connecting)
00189                {
00190                    disconnectButton.Visibility = Visibility.Collapsed;
00191                    progressText.Text = "Connecting";
00192                    progressRing.IsActive = true;
00193                }
00194                else
00195                {
00196                    //Disconnecting is the remaining state
00197                    disconnectButton.Visibility = Visibility.Collapsed;
00198                    progressText.Text = "Disconnecting";
00199                    progressRing.IsActive = true;
00200                }
00201            });
00202         }
00203
00204         private async void Connection_ErrorOccurred(CastingConnection sender, CastingConnectionErrorOccurredEventArgs args)
00205         {
00206             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00207             {
00208                 //Clear the selection in the listbox on an error
00209                 rootPage.NotifyUser("Casting Error: " + args.Message, NotifyType.ErrorMessage);
00210                 castingDevicesList.SelectedItem = null;
00211             });
00212         }
00213
00214         private async void disconnectButton_Click(object sender, RoutedEventArgs e)
00215         {
00216             if (connection != null)
00217             {
00218                 //When disconnect is clicked, the casting conneciton is disconnected.  The video should return locally to the media element.
00219                 await connection.DisconnectAsync();
00220             }
00221         }
00222     }
00223 }
Generated on Fri Nov 15 2024 22:18:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

OpenCloseConnectionScenario Member List

This is the complete list of members for OpenCloseConnectionScenario, including all inherited members.
GenerateRandomNumber_Click(object sender, RoutedEventArgs e) | OpenCloseConnectionScenario | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | OpenCloseConnectionScenario | [inline, protected]
OpenCloseConnectionScenario() | OpenCloseConnectionScenario | [inline]
rootPage | OpenCloseConnectionScenario | [private]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario2WinRTComponent/OnboardingProducer.cpp Source File

  • AllJoyn
  • Common
  • Scenario2WinRTComponent

OnboardingProducer.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #include "pch.h"
00022
00023 using namespace concurrency;
00024 using namespace Microsoft::WRL;
00025 using namespace Platform;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Devices::AllJoyn;
00028 using namespace org::alljoyn::Onboarding;
00029
00030 std::map<alljoyn_busobject, WeakReference*> OnboardingProducer::SourceObjects;
00031 std::map<alljoyn_interfacedescription, WeakReference*> OnboardingProducer::SourceInterfaces;
00032
00033 OnboardingProducer::OnboardingProducer(AllJoynBusAttachment^ busAttachment)
00034     : m_busAttachment(busAttachment),
00035     m_sessionListener(nullptr),
00036     m_busObject(nullptr),
00037     m_sessionPort(0),
00038     m_sessionId(0)
00039 {
00040     m_weak = new WeakReference(this);
00041     ServiceObjectPath = ref new String(L"/Service");
00042     m_signals = ref new OnboardingLegacySignals();
00043     m_busAttachmentStateChangedToken.Value = 0;
00044 }
00045
00046 OnboardingProducer::~OnboardingProducer()
00047 {
00048     UnregisterFromBus();
00049     delete m_weak;
00050 }
00051
00052 void OnboardingProducer::UnregisterFromBus()
00053 {
00054     if ((nullptr != m_busAttachment) && (0 != m_busAttachmentStateChangedToken.Value))
00055     {
00056         m_busAttachment->StateChanged -= m_busAttachmentStateChangedToken;
00057         m_busAttachmentStateChangedToken.Value = 0;
00058     }
00059     if ((nullptr != m_busAttachment) && (nullptr != SessionPortListener))
00060     {
00061         alljoyn_busattachment_unbindsessionport(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), m_sessionPort);
00062         alljoyn_sessionportlistener_destroy(SessionPortListener);
00063         SessionPortListener = nullptr;
00064     }
00065     if ((nullptr != m_busAttachment) && (nullptr != BusObject))
00066     {
00067         alljoyn_busattachment_unregisterbusobject(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject);
00068         alljoyn_busobject_destroy(BusObject);
00069         BusObject = nullptr;
00070     }
00071     if ((nullptr != m_busAttachment) && (nullptr != SessionListener))
00072     {
00073         alljoyn_busattachment_leavesession(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), m_sessionId);
00074         alljoyn_busattachment_setsessionlistener(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), m_sessionId, nullptr);
00075         alljoyn_sessionlistener_destroy(SessionListener);
00076         SessionListener = nullptr;
00077     }
00078 }
00079
00080 bool OnboardingProducer::OnAcceptSessionJoiner(_In_ alljoyn_sessionport sessionPort, _In_ PCSTR joiner, _In_ const alljoyn_sessionopts opts)
00081 {
00082     UNREFERENCED_PARAMETER(sessionPort); UNREFERENCED_PARAMETER(joiner); UNREFERENCED_PARAMETER(opts);
00083
00084     return true;
00085 }
00086
00087 void OnboardingProducer::OnSessionJoined(_In_ alljoyn_sessionport sessionPort, _In_ alljoyn_sessionid id, _In_ PCSTR joiner)
00088 {
00089     UNREFERENCED_PARAMETER(joiner);
00090
00091     // We initialize the Signals object after the session has been joined, because it needs
00092     // the session id.
00093     m_signals->Initialize(BusObject, id);
00094     m_sessionPort = sessionPort;
00095     m_sessionId = id;
00096
00097     alljoyn_sessionlistener_callbacks callbacks =
00098     {
00099         AllJoynHelpers::SessionLostHandler<OnboardingProducer>,
00100         AllJoynHelpers::SessionMemberAddedHandler<OnboardingProducer>,
00101         AllJoynHelpers::SessionMemberRemovedHandler<OnboardingProducer>
00102     };
00103
00104     SessionListener = alljoyn_sessionlistener_create(&callbacks, m_weak);
00105     alljoyn_busattachment_setsessionlistener(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), id, SessionListener);
00106 }
00107
00108 void OnboardingProducer::OnSessionLost(_In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason)
00109 {
00110     if (sessionId == m_sessionId)
00111     {
00112         AllJoynSessionLostEventArgs^ args = ref new AllJoynSessionLostEventArgs(static_cast<AllJoynSessionLostReason>(reason));
00113         SessionLost(this, args);
00114     }
00115 }
00116
00117 void OnboardingProducer::OnSessionMemberAdded(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
00118 {
00119     if (sessionId == m_sessionId)
00120     {
00121         auto args = ref new AllJoynSessionMemberAddedEventArgs(AllJoynHelpers::MultibyteToPlatformString(uniqueName));
00122         SessionMemberAdded(this, args);
00123     }
00124 }
00125
00126 void OnboardingProducer::OnSessionMemberRemoved(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
00127 {
00128     if (sessionId == m_sessionId)
00129     {
00130         auto args = ref new AllJoynSessionMemberRemovedEventArgs(AllJoynHelpers::MultibyteToPlatformString(uniqueName));
00131         SessionMemberRemoved(this, args);
00132     }
00133 }
00134
00135 void OnboardingProducer::BusAttachmentStateChanged(_In_ AllJoynBusAttachment^ sender, _In_ AllJoynBusAttachmentStateChangedEventArgs^ args)
00136 {
00137     if (args->State == AllJoynBusAttachmentState::Connected)
00138     {
00139         QStatus result = AllJoynHelpers::CreateProducerSession<OnboardingProducer>(m_busAttachment, m_weak);
00140         if (ER_OK != result)
00141         {
00142             StopInternal(result);
00143             return;
00144         }
00145     }
00146     else if (args->State == AllJoynBusAttachmentState::Disconnected)
00147     {
00148         StopInternal(ER_BUS_STOPPING);
00149     }
00150 }
00151
00152 void OnboardingProducer::CallConfigureWiFiHandler(_Inout_ alljoyn_busobject busObject, _In_ alljoyn_message message)
00153 {
00154     auto source = SourceObjects.find(busObject);
00155     if (source == SourceObjects.end())
00156     {
00157         return;
00158     }
00159
00160     OnboardingProducer^ producer = source->second->Resolve<OnboardingProducer>();
00161     if (producer->Service != nullptr)
00162     {
00163         AllJoynMessageInfo^ callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
00164
00165         Platform::String^ inputArg0;
00166         (void)TypeConversionHelpers::GetAllJoynMessageArg(alljoyn_message_getarg(message, 0), "s", &inputArg0);
00167         Platform::String^ inputArg1;
00168         (void)TypeConversionHelpers::GetAllJoynMessageArg(alljoyn_message_getarg(message, 1), "s", &inputArg1);
00169         int16 inputArg2;
00170         (void)TypeConversionHelpers::GetAllJoynMessageArg(alljoyn_message_getarg(message, 2), "n", &inputArg2);
00171
00172         OnboardingConfigureWiFiResult^ result = create_task(producer->Service->ConfigureWiFiAsync(callInfo, inputArg0, inputArg1, inputArg2)).get();
00173         create_task([](){}).then([=]
00174         {
00175             int32 status;
00176
00177             if (nullptr == result)
00178             {
00179                 alljoyn_busobject_methodreply_status(busObject, message, ER_BUS_NO_LISTENER);
00180                 return;
00181             }
00182
00183             status = result->Status;
00184             if (AllJoynStatus::Ok != status)
00185             {
00186                 alljoyn_busobject_methodreply_status(busObject, message, static_cast<QStatus>(status));
00187                 return;
00188             }
00189
00190             size_t argCount = 1;
00191             alljoyn_msgarg outputs = alljoyn_msgarg_array_create(argCount);
00192
00193             status = TypeConversionHelpers::SetAllJoynMessageArg(alljoyn_msgarg_array_element(outputs, 0), "n", result->Status2);
00194             if (AllJoynStatus::Ok != status)
00195             {
00196                 alljoyn_busobject_methodreply_status(busObject, message, static_cast<QStatus>(status));
00197                 alljoyn_msgarg_destroy(outputs);
00198                 return;
00199             }
00200
00201             alljoyn_busobject_methodreply_args(busObject, message, outputs, argCount);
00202             alljoyn_msgarg_destroy(outputs);
00203         }, result->m_creationContext).wait();
00204     }
00205 }
00206
00207 void OnboardingProducer::CallConnectHandler(_Inout_ alljoyn_busobject busObject, _In_ alljoyn_message message)
00208 {
00209     auto source = SourceObjects.find(busObject);
00210     if (source == SourceObjects.end())
00211     {
00212         return;
00213     }
00214
00215     OnboardingProducer^ producer = source->second->Resolve<OnboardingProducer>();
00216     if (producer->Service != nullptr)
00217     {
00218         AllJoynMessageInfo^ callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
00219
00220
00221         OnboardingConnectResult^ result = create_task(producer->Service->ConnectAsync(callInfo)).get();
00222         create_task([](){}).then([=]
00223         {
00224             int32 status;
00225
00226             if (nullptr == result)
00227             {
00228                 alljoyn_busobject_methodreply_status(busObject, message, ER_BUS_NO_LISTENER);
00229                 return;
00230             }
00231
00232             status = result->Status;
00233             if (AllJoynStatus::Ok != status)
00234             {
00235                 alljoyn_busobject_methodreply_status(busObject, message, static_cast<QStatus>(status));
00236                 return;
00237             }
00238
00239             size_t argCount = 0;
00240             alljoyn_msgarg outputs = alljoyn_msgarg_array_create(argCount);
00241
00242             alljoyn_busobject_methodreply_args(busObject, message, outputs, argCount);
00243             alljoyn_msgarg_destroy(outputs);
00244         }, result->m_creationContext).wait();
00245     }
00246 }
00247
00248 void OnboardingProducer::CallOffboardHandler(_Inout_ alljoyn_busobject busObject, _In_ alljoyn_message message)
00249 {
00250     auto source = SourceObjects.find(busObject);
00251     if (source == SourceObjects.end())
00252     {
00253         return;
00254     }
00255
00256     OnboardingProducer^ producer = source->second->Resolve<OnboardingProducer>();
00257     if (producer->Service != nullptr)
00258     {
00259         AllJoynMessageInfo^ callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
00260
00261
00262         OnboardingOffboardResult^ result = create_task(producer->Service->OffboardAsync(callInfo)).get();
00263         create_task([](){}).then([=]
00264         {
00265             int32 status;
00266
00267             if (nullptr == result)
00268             {
00269                 alljoyn_busobject_methodreply_status(busObject, message, ER_BUS_NO_LISTENER);
00270                 return;
00271             }
00272
00273             status = result->Status;
00274             if (AllJoynStatus::Ok != status)
00275             {
00276                 alljoyn_busobject_methodreply_status(busObject, message, static_cast<QStatus>(status));
00277                 return;
00278             }
00279
00280             size_t argCount = 0;
00281             alljoyn_msgarg outputs = alljoyn_msgarg_array_create(argCount);
00282
00283             alljoyn_busobject_methodreply_args(busObject, message, outputs, argCount);
00284             alljoyn_msgarg_destroy(outputs);
00285         }, result->m_creationContext).wait();
00286     }
00287 }
00288
00289 void OnboardingProducer::CallGetScanInfoHandler(_Inout_ alljoyn_busobject busObject, _In_ alljoyn_message message)
00290 {
00291     auto source = SourceObjects.find(busObject);
00292     if (source == SourceObjects.end())
00293     {
00294         return;
00295     }
00296
00297     OnboardingProducer^ producer = source->second->Resolve<OnboardingProducer>();
00298     if (producer->Service != nullptr)
00299     {
00300         AllJoynMessageInfo^ callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
00301
00302
00303         OnboardingGetScanInfoResult^ result = create_task(producer->Service->GetScanInfoAsync(callInfo)).get();
00304         create_task([](){}).then([=]
00305         {
00306             int32 status;
00307
00308             if (nullptr == result)
00309             {
00310                 alljoyn_busobject_methodreply_status(busObject, message, ER_BUS_NO_LISTENER);
00311                 return;
00312             }
00313
00314             status = result->Status;
00315             if (AllJoynStatus::Ok != status)
00316             {
00317                 alljoyn_busobject_methodreply_status(busObject, message, static_cast<QStatus>(status));
00318                 return;
00319             }
00320
00321             size_t argCount = 2;
00322             alljoyn_msgarg outputs = alljoyn_msgarg_array_create(argCount);
00323
00324             status = TypeConversionHelpers::SetAllJoynMessageArg(alljoyn_msgarg_array_element(outputs, 0), "q", result->Age);
00325             if (AllJoynStatus::Ok != status)
00326             {
00327                 alljoyn_busobject_methodreply_status(busObject, message, static_cast<QStatus>(status));
00328                 alljoyn_msgarg_destroy(outputs);
00329                 return;
00330             }
00331
00332             status = TypeConversionHelpers::SetAllJoynMessageArg(alljoyn_msgarg_array_element(outputs, 1), "a(sn)", result->ScanList);
00333             if (AllJoynStatus::Ok != status)
00334             {
00335                 alljoyn_busobject_methodreply_status(busObject, message, static_cast<QStatus>(status));
00336                 alljoyn_msgarg_destroy(outputs);
00337                 return;
00338             }
00339
00340             alljoyn_busobject_methodreply_args(busObject, message, outputs, argCount);
00341             alljoyn_msgarg_destroy(outputs);
00342         }, result->m_creationContext).wait();
00343     }
00344 }
00345
00346 void OnboardingProducer::CallConnectionResultSignalHandler(_In_ const alljoyn_interfacedescription_member* member, _In_ alljoyn_message message)
00347 {
00348     auto source = SourceInterfaces.find(member->iface);
00349     if (source == SourceInterfaces.end())
00350     {
00351         return;
00352     }
00353
00354     auto producer = source->second->Resolve<OnboardingProducer>();
00355     if (producer->Signals != nullptr)
00356     {
00357         auto callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
00358         auto eventArgs = ref new OnboardingConnectionResultReceivedEventArgs();
00359         eventArgs->MessageInfo = callInfo;
00360
00361         Onboarding^ argument0;
00362         (void)TypeConversionHelpers::GetAllJoynMessageArg(alljoyn_message_getarg(message, 0), "(ns)", &argument0);
00363         eventArgs->Arg = argument0;
00364
00365         producer->Signals->CallConnectionResultReceived(producer->Signals, eventArgs);
00366     }
00367 }
00368
00369 QStatus OnboardingProducer::AddMethodHandler(_In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_methodhandler_ptr handler)
00370 {
00371     alljoyn_interfacedescription_member member;
00372     if (!alljoyn_interfacedescription_getmember(interfaceDescription, methodName, &member))
00373     {
00374         return ER_BUS_INTERFACE_NO_SUCH_MEMBER;
00375     }
00376
00377     return alljoyn_busobject_addmethodhandler(
00378         m_busObject,
00379         member,
00380         handler,
00381         m_weak);
00382 }
00383
00384 QStatus OnboardingProducer::AddSignalHandler(_In_ alljoyn_busattachment busAttachment, _In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_signalhandler_ptr handler)
00385 {
00386     alljoyn_interfacedescription_member member;
00387     if (!alljoyn_interfacedescription_getmember(interfaceDescription, methodName, &member))
00388     {
00389         return ER_BUS_INTERFACE_NO_SUCH_MEMBER;
00390     }
00391
00392     return alljoyn_busattachment_registersignalhandler(busAttachment, handler, member, NULL);
00393 }
00394
00395 QStatus OnboardingProducer::OnPropertyGet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _Inout_ alljoyn_msgarg value)
00396 {
00397     UNREFERENCED_PARAMETER(interfaceName);
00398
00399     if (0 == strcmp(propertyName, "Version"))
00400     {
00401         auto task = create_task(Service->GetVersionAsync(nullptr));
00402         auto result = task.get();
00403
00404         return create_task([](){}).then([=]() -> QStatus
00405         {
00406             if (AllJoynStatus::Ok != result->Status)
00407             {
00408                 return static_cast<QStatus>(result->Status);
00409             }
00410             return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "q", result->Version));
00411         }, result->m_creationContext).get();
00412     }
00413     if (0 == strcmp(propertyName, "State"))
00414     {
00415         auto task = create_task(Service->GetStateAsync(nullptr));
00416         auto result = task.get();
00417
00418         return create_task([](){}).then([=]() -> QStatus
00419         {
00420             if (AllJoynStatus::Ok != result->Status)
00421             {
00422                 return static_cast<QStatus>(result->Status);
00423             }
00424             return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "n", result->State));
00425         }, result->m_creationContext).get();
00426     }
00427     if (0 == strcmp(propertyName, "LastError"))
00428     {
00429         auto task = create_task(Service->GetLastErrorAsync(nullptr));
00430         auto result = task.get();
00431
00432         return create_task([](){}).then([=]() -> QStatus
00433         {
00434             if (AllJoynStatus::Ok != result->Status)
00435             {
00436                 return static_cast<QStatus>(result->Status);
00437             }
00438             return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "(ns)", result->LastError));
00439         }, result->m_creationContext).get();
00440     }
00441
00442     return ER_BUS_NO_SUCH_PROPERTY;
00443 }
00444
00445 QStatus OnboardingProducer::OnPropertySet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg value)
00446 {
00447     UNREFERENCED_PARAMETER(interfaceName);
00448
00449     return ER_BUS_NO_SUCH_PROPERTY;
00450 }
00451
00452 void OnboardingProducer::Start()
00453 {
00454     if (nullptr == m_busAttachment)
00455     {
00456         StopInternal(ER_FAIL);
00457         return;
00458     }
00459
00460     QStatus result = AllJoynHelpers::CreateInterfaces(m_busAttachment, c_OnboardingIntrospectionXml);
00461     if (result != ER_OK)
00462     {
00463         StopInternal(result);
00464         return;
00465     }
00466
00467     result = AllJoynHelpers::CreateBusObject<OnboardingProducer>(m_weak);
00468     if (result != ER_OK)
00469     {
00470         StopInternal(result);
00471         return;
00472     }
00473
00474     alljoyn_interfacedescription interfaceDescription = alljoyn_busattachment_getinterface(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), "org.alljoyn.Onboarding");
00475     if (interfaceDescription == nullptr)
00476     {
00477         StopInternal(ER_FAIL);
00478         return;
00479     }
00480     alljoyn_busobject_addinterface_announced(BusObject, interfaceDescription);
00481
00482     result = AddMethodHandler(
00483         interfaceDescription,
00484         "ConfigureWiFi",
00485         [](alljoyn_busobject busObject, const alljoyn_interfacedescription_member* member, alljoyn_message message) { UNREFERENCED_PARAMETER(member); CallConfigureWiFiHandler(busObject, message); });
00486     if (result != ER_OK)
00487     {
00488         StopInternal(result);
00489         return;
00490     }
00491
00492     result = AddMethodHandler(
00493         interfaceDescription,
00494         "Connect",
00495         [](alljoyn_busobject busObject, const alljoyn_interfacedescription_member* member, alljoyn_message message) { UNREFERENCED_PARAMETER(member); CallConnectHandler(busObject, message); });
00496     if (result != ER_OK)
00497     {
00498         StopInternal(result);
00499         return;
00500     }
00501
00502     result = AddMethodHandler(
00503         interfaceDescription,
00504         "Offboard",
00505         [](alljoyn_busobject busObject, const alljoyn_interfacedescription_member* member, alljoyn_message message) { UNREFERENCED_PARAMETER(member); CallOffboardHandler(busObject, message); });
00506     if (result != ER_OK)
00507     {
00508         StopInternal(result);
00509         return;
00510     }
00511
00512     result = AddMethodHandler(
00513         interfaceDescription,
00514         "GetScanInfo",
00515         [](alljoyn_busobject busObject, const alljoyn_interfacedescription_member* member, alljoyn_message message) { UNREFERENCED_PARAMETER(member); CallGetScanInfoHandler(busObject, message); });
00516     if (result != ER_OK)
00517     {
00518         StopInternal(result);
00519         return;
00520     }
00521
00522     result = AddSignalHandler(
00523         AllJoynHelpers::GetInternalBusAttachment(m_busAttachment),
00524         interfaceDescription,
00525         "ConnectionResult",
00526         [](const alljoyn_interfacedescription_member* member, PCSTR srcPath, alljoyn_message message) { UNREFERENCED_PARAMETER(srcPath); CallConnectionResultSignalHandler(member, message); });
00527     if (result != ER_OK)
00528     {
00529         StopInternal(result);
00530         return;
00531     }
00532
00533     SourceObjects[m_busObject] = m_weak;
00534     SourceInterfaces[interfaceDescription] = m_weak;
00535
00536     unsigned int noneMechanismIndex = 0;
00537     bool authenticationMechanismsContainsNone = m_busAttachment->AuthenticationMechanisms->IndexOf(AllJoynAuthenticationMechanism::None, &noneMechanismIndex);
00538     QCC_BOOL interfaceIsSecure = alljoyn_interfacedescription_issecure(interfaceDescription);
00539
00540     // If the current set of AuthenticationMechanisms supports authentication,
00541     // determine whether a secure BusObject is required.
00542     if (AllJoynHelpers::CanSecure(m_busAttachment->AuthenticationMechanisms))
00543     {
00544         // Register the BusObject as "secure" if the org.alljoyn.Bus.Secure XML annotation
00545         // is specified, or if None is not present in AuthenticationMechanisms.
00546         if (!authenticationMechanismsContainsNone || interfaceIsSecure)
00547         {
00548             result = alljoyn_busattachment_registerbusobject_secure(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject);
00549         }
00550         else
00551         {
00552             result = alljoyn_busattachment_registerbusobject(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject);
00553         }
00554     }
00555     else
00556     {
00557         // If the current set of AuthenticationMechanisms does not support authentication
00558         // but the interface requires security, report an error.
00559         if (interfaceIsSecure)
00560         {
00561             result = ER_BUS_NO_AUTHENTICATION_MECHANISM;
00562         }
00563         else
00564         {
00565             result = alljoyn_busattachment_registerbusobject(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject);
00566         }
00567     }
00568
00569     if (result != ER_OK)
00570     {
00571         StopInternal(result);
00572         return;
00573     }
00574
00575     m_busAttachmentStateChangedToken = m_busAttachment->StateChanged += ref new TypedEventHandler<AllJoynBusAttachment^,AllJoynBusAttachmentStateChangedEventArgs^>(this, &OnboardingProducer::BusAttachmentStateChanged);
00576     m_busAttachment->Connect();
00577 }
00578
00579 void OnboardingProducer::Stop()
00580 {
00581     StopInternal(AllJoynStatus::Ok);
00582 }
00583
00584 void OnboardingProducer::StopInternal(int32 status)
00585 {
00586     UnregisterFromBus();
00587     Stopped(this, ref new AllJoynProducerStoppedEventArgs(status));
00588 }
00589
00590 int32 OnboardingProducer::RemoveMemberFromSession(_In_ String^ uniqueName)
00591 {
00592     return alljoyn_busattachment_removesessionmember(
00593         AllJoynHelpers::GetInternalBusAttachment(m_busAttachment),
00594         m_sessionId,
00595         AllJoynHelpers::PlatformToMultibyteString(uniqueName).data());
00596 }
00597
00598 PCSTR org::alljoyn::Onboarding::c_OnboardingIntrospectionXml = "<interface name=\"org.alljoyn.Onboarding\">"
00599 "  <description>A secure onboarding interface</description>"
00600 "  <annotation name=\"org.alljoyn.Bus.Secure\" value=\"true\" />"
00601 "  <property name=\"Version\" type=\"q\" access=\"read\">"
00602 "    <description>Interface version number</description>"
00603 "    <annotation name=\"org.freedesktop.DBus.Property.EmitsChangedSignal\" value=\"false\" />"
00604 "  </property>"
00605 "  <property name=\"State\" type=\"n\" access=\"read\">"
00606 "    <description>The configuration state</description>"
00607 "    <annotation name=\"org.freedesktop.DBus.Property.EmitsChangedSignal\" value=\"false\" />"
00608 "  </property>"
00609 "  <property name=\"LastError\" type=\"(ns)\" access=\"read\">"
00610 "    <description>The last error code and error message</description>"
00611 "    <annotation name=\"org.freedesktop.DBus.Property.EmitsChangedSignal\" value=\"false\" />"
00612 "  </property>"
00613 "  <method name=\"ConfigureWiFi\">"
00614 "    <description>Sends the personal AP information to the onboardee</description>"
00615 "    <arg name=\"SSID\" type=\"s\" direction=\"in\" />"
00616 "    <arg name=\"passphrase\" type=\"s\" direction=\"in\" />"
00617 "    <arg name=\"authType\" type=\"n\" direction=\"in\" />"
00618 "    <arg name=\"status\" type=\"n\" direction=\"out\" />"
00619 "  </method>"
00620 "  <method name=\"Connect\">"
00621 "    <description>Tells the onboardee to connect to the personal AP</description>"
00622 "    <annotation name=\"org.freedesktop.DBus.Method.NoReply\" value=\"true\" />"
00623 "  </method>"
00624 "  <method name=\"Offboard\">"
00625 "    <description>Tells the onboardee to disconnect from the personal AP</description>"
00626 "    <annotation name=\"org.freedesktop.DBus.Method.NoReply\" value=\"true\" />"
00627 "  </method>"
00628 "  <method name=\"GetScanInfo\">"
00629 "    <description>Scans all the Wi-Fi access points in the onboardee's proximity</description>"
00630 "    <arg name=\"age\" type=\"q\" direction=\"out\" />"
00631 "    <arg name=\"scanList\" type=\"a(sn)\" direction=\"out\" />"
00632 "  </method>"
00633 "  <signal name=\"ConnectionResult\">"
00634 "    <description>This signal is emitted when the connection attempt against the personal AP is completed</description>"
00635 "    <arg type=\"(ns)\" />"
00636 "  </signal>"
00637 "</interface>"
00638 ;
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LibraryManagement/cpp/S2_ListFolders.xaml.h Source File

  • LibraryManagement
  • cpp

S2_ListFolders.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2.xaml.h
00014 // Declaration of the Scenario2 class
00015 //
00016
00017 #pragma once
00018 #include "S2_ListFolders.g.h"
00019
00020 namespace SDKTemplate
00021 {
00022     public ref class Scenario2 sealed
00023     {
00024     public:
00025         Scenario2();
00026
00027     private:
00028         void ListFoldersButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029         void UpdateHeaderText();
00030
00031         Windows::Storage::StorageLibrary^ picturesLibrary;
00032     };
00033 }
Generated on Fri Nov 15 2024 22:20:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomControlUsage Member List

This is the complete list of members for CustomControlUsage, including all inherited members.
CustomControlUsage() CustomControlUsage [inline]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSegmentation/cpp/pch.h Source File

  • TextSegmentation
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/BasicTests.xaml.cs Source File

  • XamlBind
  • cs

BasicTests.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Xaml;
00003 using Windows.UI.Xaml.Controls;
00004 using xBindSampleModel;
00005
00006 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00007
00008 namespace xBindSampleCS
00009 {
00010     public sealed partial class BasicTests : Page
00011     {
00012         public int MyInt { get; set; }
00013         public DataModel Model { get; set; }
00014
00015         public CSharpModel CSharpModel { get; set; }
00016
00017         public String DPOnPage
00018         {
00019             get { return (String)GetValue(DPOnPageProperty); }
00020             set { SetValue(DPOnPageProperty, value); }
00021         }
00022         public static DependencyProperty DPOnPageProperty { get { return _DPOnPage; } }
00023         private const string DPOnPageName = "DPOnPage";
00024         private static readonly DependencyProperty _DPOnPage =
00025         DependencyProperty.Register(DPOnPageName, typeof(int), typeof(DataModel), new PropertyMetadata(0));
00026
00027         public xBindSampleModel.IEmployee NullEmployee;
00028         public String NullStringProperty;
00029
00030         public BasicTests()
00031         {
00032             this.Model = new DataModel();
00033             this.CSharpModel = new CSharpModel();
00034             this.InitializeComponent();
00035             InitializeValues();
00036         }
00037
00038         void InitializeValues()
00039         {
00040             this.DPOnPage = "DP on page";
00041         }
00042
00043         private void UpdateValuesClick(object sender, RoutedEventArgs e)
00044         {
00045             this.Model.UpdateValues();
00046             this.CSharpModel.UpdateValues();
00047             this.DPOnPage += "-";
00048         }
00049
00050         private void ResetValuesClick(object sender, RoutedEventArgs e)
00051         {
00052             this.Model.InitializeValues();
00053             this.CSharpModel.InitializeValues();
00054             this.InitializeValues();
00055         }
00056
00057     }
00058 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LightSensor/cpp/pch.h Source File

  • LightSensor
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_SecondaryWindow Member List

This is the complete list of members for Scenario1_SecondaryWindow, including all inherited members.
appWindow | Scenario1_SecondaryWindow | [private]
appWindowFrame | Scenario1_SecondaryWindow | [private]
Button_Click(object sender, RoutedEventArgs e) | Scenario1_SecondaryWindow | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_SecondaryWindow | [inline, protected]
Scenario1_SecondaryWindow() | Scenario1_SecondaryWindow | [inline]
Generated on Fri Nov 15 2024 22:23:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/pch.h Source File

  • HolographicMixedRealityCapture
  • cpp

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <agile.h>
00004 #include <concrt.h>
00005 #include <d2d1_2.h>
00006 #include <d2d1effects_1.h>
00007 #include <d3d11_4.h>
00008 #include <DirectXColors.h>
00009 #include <DirectXMath.h>
00010 #include <dwrite_2.h>
00011 #include <dxgi1_5.h>
00012 #include <wincodec.h>
00013 #include <WindowsNumerics.h>
00014 #include <wrl.h>
00015 #include <memory>
00016 #include <map>
00017 #include <mutex>
00018
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/SampleConfiguration.h Source File

  • SmartCard
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LocationBackgroundTask Member List

This is the complete list of members for LocationBackgroundTask, including all inherited members.
_cts | LocationBackgroundTask | [private]
_values | LocationBackgroundTask | [private]
OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) | LocationBackgroundTask | [inline, private]
Run(IBackgroundTaskInstance taskInstance) | LocationBackgroundTask | [inline, private]
WipeGeolocDataFromAppData() | LocationBackgroundTask | [inline, private]
WriteGeolocToAppData(Geoposition pos) | LocationBackgroundTask | [inline, private]
WriteStatusToAppData(string status) | LocationBackgroundTask | [inline, private]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_AddAccount Member List

This is the complete list of members for Scenario1_AddAccount, including all inherited members.
AddAccount_Click(object sender, RoutedEventArgs e) | Scenario1_AddAccount | [inline, private]
DisplayUserInformationAsync(String id) | Scenario1_AddAccount | [inline, private]
isLaunched | Scenario1_AddAccount | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_AddAccount | [inline, protected]
rootPage | Scenario1_AddAccount | [private]
Scenario1_AddAccount() | Scenario1_AddAccount | [inline]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cs/Scenario4_UnicodeExtensions.xaml.cs Source File

  • Calendar
  • cs

Scenario4_UnicodeExtensions.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.Text;
00013 using Windows.Foundation;
00014 using Windows.Globalization;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class Scenario4_UnicodeExtensions : Page
00021     {
00022         public Scenario4_UnicodeExtensions()
00023         {
00024             this.InitializeComponent();
00025         }
00026
00027         private string ReportCalendarData(Calendar calendar, string calendarLabel)
00028         {
00029             string results = calendarLabel + ": " + calendar.GetCalendarSystem() + "\n";
00030             results += "Calendar system: " + calendar.GetCalendarSystem() + "\n";
00031             results += "Numeral System: " + calendar.NumeralSystem + "\n";
00032             results += "Resolved Language " + calendar.ResolvedLanguage + "\n";
00033             results += "Name of Month: " + calendar.MonthAsSoloString() + "\n";
00034             results += "Day of Month: " + calendar.DayAsPaddedString(2) + "\n";
00035             results += "Day of Week: " + calendar.DayOfWeekAsSoloString() + "\n";
00036             results += "Year: " + calendar.YearAsString() + "\n";
00037             results += "\n";
00038             return results;
00039         }
00040
00041         private void ShowResults_Click(object sender, RoutedEventArgs e)
00042         {
00043             // This scenario uses the Windows.Globalization.Calendar class to display the parts of a date.
00044
00045             // Create Calendar objects using different Unicode extensions for different languages.
00046             // NOTE: Calendar (ca) and numeral system (nu) are the only supported extensions with any others being ignored.
00047             // Note that collation (co) extension is ignored in the last example.
00048             Calendar cal1 = new Calendar();
00049             Calendar cal2 = new Calendar(new[] { "ar-SA-u-ca-gregory-nu-Latn" });
00050             Calendar cal3 = new Calendar(new[] { "he-IL-u-nu-arab" });
00051             Calendar cal4 = new Calendar(new[] { "he-IL-u-ca-hebrew-co-phonebk" });
00052
00053             // Display individual date/time elements.
00054             OutputTextBlock.Text =
00055                 ReportCalendarData(cal1, "User's default Calendar object") +
00056                 ReportCalendarData(cal2, "Calendar object with Arabic language, Gregorian Calendar and Latin Numeral System (ar-SA-ca-gregory-nu-Latn)") +
00057                 ReportCalendarData(cal3, "Calendar object with Hebrew language, Default Calendar for that language and Arab Numeral System (he-IL-u-nu-arab)") +
00058                 ReportCalendarData(cal4, "Calendar object with Hebrew language, Hebrew Calendar, Default Numeral System for that language and Phonebook collation (he-IL-u-ca-hebrew-co-phonebk)");
00059         }
00060     }
00061 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Server/SampleService.cpp Source File

  • CustomCapability
  • Service
  • Server

SampleService.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "stdafx.h"
00013
00014 #pragma region Includes
00015 #include "SampleService.h"
00016 #include "RpcServer.h"
00017 #include <Evntrace.h>
00018 #pragma endregion
00019
00020 CSampleService::CSampleService(
00021     PWSTR pszServiceName,
00022     BOOL fCanStop,
00023     BOOL fCanShutdown,
00024     BOOL fCanPauseContinue)
00025     : CServiceBase(pszServiceName, fCanStop, fCanShutdown, fCanPauseContinue)
00026 {
00027 }
00028
00029 void CSampleService::WriteEventLogEntry(PWSTR pszMessage, BYTE bLevel)
00030 {
00031     if (IsConsoleRun())
00032     {
00033         wprintf(L"%d: %ls\n", bLevel, pszMessage);
00034     }
00035     __super::WriteEventLogEntry(pszMessage, bLevel);
00036 }
00037
00038 CSampleService::~CSampleService(void)
00039 {
00040 }
00041
00042 //
00043 // This is the thread pool work callback function.
00044 //
00045 VOID CALLBACK ServiceWorkerThread(
00046     _In_ PTP_CALLBACK_INSTANCE /*Instance*/,
00047     _In_ PVOID Parameter,
00048     _In_ PTP_WORK /*Work*/)
00049 {
00050     //
00051     // Do something when the work callback is invoked.
00052     //
00053     {
00054         _int64 status = RpcServerStart();
00055         if (status)
00056         {
00057             CSampleService* sampleService = static_cast<CSampleService *>(Parameter);
00058             sampleService->Stop();
00059         }
00060     }
00061
00062     return;
00063 }
00064
00065 //
00066 //   FUNCTION: CSampleService::OnStart(DWORD, LPWSTR *)
00067 //
00068 //   PURPOSE: The function is executed when a Start command is sent to the
00069 //   service by the SCM or when the operating system starts (for a service
00070 //   that starts automatically). It specifies actions to take when the
00071 //   service starts. In this code sample, OnStart logs a service-start
00072 //   message to the Application log, and queues the main service function for
00073 //   execution in a thread pool worker thread.
00074 //
00075 //   PARAMETERS:
00076 //   * dwArgc   - number of command line arguments
00077 //   * lpszArgv - array of command line arguments
00078 //
00079 //   NOTE: A service application is designed to be long running. Therefore,
00080 //   it usually polls or monitors something in the system. The monitoring is
00081 //   set up in the OnStart method. However, OnStart does not actually do the
00082 //   monitoring. The OnStart method must return to the operating system after
00083 //   the service's operation has begun. It must not loop forever or block. To
00084 //   set up a simple monitoring mechanism, one general solution is to create
00085 //   a timer in OnStart. The timer would then raise events in your code
00086 //   periodically, at which time your service could do its monitoring. The
00087 //   other solution is to spawn a new thread to perform the main service
00088 //   functions, which is demonstrated in this code sample.
00089 //
00090 void CSampleService::OnStart(
00091     _In_ DWORD dwArgc,
00092     _In_ LPWSTR *lpszArgv)
00093 {
00094     // Log a service start message to the Application log.
00095     WriteEventLogEntry(L"CppWindowsService in OnStart", TRACE_LEVEL_INFORMATION);
00096
00097     // Queue the main service function for execution in a worker thread.
00098     PTP_WORK_CALLBACK workcallback = ServiceWorkerThread;
00099     m_work = CreateThreadpoolWork(workcallback, this, nullptr);
00100
00101     if (NULL == m_work)
00102     {
00103         // TODO: Capture get last error
00104         WriteEventLogEntry(L"CreateThreadpoolWork failed", TRACE_LEVEL_ERROR);
00105     }
00106
00107     //
00108     // Submit the work to the pool. Because this was a pre-allocated
00109     // work item (using CreateThreadpoolWork), it is guaranteed to execute.
00110     //
00111     SubmitThreadpoolWork(m_work);
00112 }
00113
00114 //
00115 //   FUNCTION: CSampleService::ConsoleRun()
00116 //
00117 //   PURPOSE: The function is executed to simulate OnStart in
00118 //   console mode.
00119 //
00120 void CSampleService::ConsoleRun()
00121 {
00122     m_runningInConsole = true;
00123
00124     WriteEventLogEntry(L"Starting Rpc Server..", TRACE_LEVEL_INFORMATION);
00125     long status = RpcServerStart();
00126
00127     if (status)
00128     {
00129         printf_s("RpcServerConnect returned: 0x%x\n", status);
00130         WriteEventLogEntry(L"Starting Rpc Server..", TRACE_LEVEL_INFORMATION);
00131         exit(static_cast<int>(status));
00132     }
00133 }
00134
00135 //
00136 //   FUNCTION: CSampleService::OnStop()
00137 //
00138 //   PURPOSE: The function is executed when a Stop command is sent to the
00139 //   service by SCM. It specifies actions to take when a service stops
00140 //   running. In this code sample, OnStop logs a service-stop message to the
00141 //   Application log, and waits for the finish of the main service function.
00142 //
00143 //   COMMENTS:
00144 //   Be sure to periodically call ReportServiceStatus() with
00145 //   SERVICE_STOP_PENDING if the procedure is going to take long time.
00146 //
00147 void CSampleService::OnStop()
00148 {
00149     // Log a service stop message to the Application log.
00150     WriteEventLogEntry(L"CppWindowsService in OnStop", TRACE_LEVEL_INFORMATION);
00151
00152     // Instruct server to stop listening to remote procedure calls and
00153     // unregister rpc interface
00154     RpcServerDisconnect();
00155 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Define Member List

This is the complete list of members for Scenario1_Define, including all inherited members.
Create_Click(object sender, RoutedEventArgs e) | Scenario1_Define | [inline, private]
InviteeRadioButton_Checked(object sender, RoutedEventArgs e) | Scenario1_Define | [inline, private]
OrganizerRadioButton_Checked(object sender, RoutedEventArgs e) | Scenario1_Define | [inline, private]
ReminderCheckBox_Checked(object sender, RoutedEventArgs e) | Scenario1_Define | [inline, private]
ReminderCheckBox_UnChecked(object sender, RoutedEventArgs e) | Scenario1_Define | [inline, private]
rootPage | Scenario1_Define | [private]
Scenario1_Define() | Scenario1_Define | [inline]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SemanticTextQuery/cs/FindInProperty.xaml.cs Source File

  • SemanticTextQuery
  • cs

FindInProperty.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.Collections.Generic;
00013 using Windows.Foundation;
00014 using Windows.Storage.Search;
00015 using Windows.UI.Text;
00016 using Windows.UI.Xaml.Documents;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020 using System;
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class Scenario2
00028     {
00029         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00030         // as NotifyUser()
00031         MainPage rootPage = MainPage.Current;
00032
00033         public Scenario2()
00034         {
00035             this.InitializeComponent();
00036         }
00037
00038         /// <summary>
00039         /// Invoked when this page is about to be displayed in a Frame.
00040         /// </summary>
00041         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00042         /// property is typically used to configure the page.</param>
00043         protected override void OnNavigatedTo(NavigationEventArgs e)
00044         {
00045             FindQueryText.Text = "Title:Good OR Content:Tree";
00046             TitleText.Text = "These are Good Times";
00047             ContentText.Text = "There are many good times to be had. Go for a walk among the trees.";
00048         }
00049
00050         private void Find_Click(object sender, RoutedEventArgs e)
00051         {
00052             ContentTextOutput.Text = "";
00053             TitleTextOutput.Text = "";
00054             var mySemanticTextQuery = new Windows.Data.Text.SemanticTextQuery(FindQueryText.Text);
00055             IReadOnlyList<Windows.Data.Text.TextSegment> ranges = mySemanticTextQuery.FindInProperty(ContentText.Text, "System.Search.Contents");
00056             rootPage.HighlightRanges(ContentTextOutput, ContentText.Text, ranges);
00057             IReadOnlyList<Windows.Data.Text.TextSegment> rangesTitle = mySemanticTextQuery.FindInProperty(TitleText.Text, "System.Title");
00058             rootPage.HighlightRanges(TitleTextOutput, TitleText.Text, rangesTitle);
00059         }
00060     }
00061 }
Generated on Fri Nov 15 2024 22:21:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppWindow/cppwinrt/Scenario5_RelativePositioning.h Source File

  • AppWindow
  • cppwinrt

Scenario5_RelativePositioning.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario5_RelativePositioning.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario5_RelativePositioning : Scenario5_RelativePositioningT<Scenario5_RelativePositioning>
00019     {
00020         Scenario5_RelativePositioning();
00021
00022         fire_and_forget OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00023
00024         fire_and_forget ShowWindowBtn_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00025
00026     private:
00027         Windows::UI::WindowManagement::AppWindow appWindow{ nullptr };
00028         Windows::UI::Xaml::Controls::Frame appWindowFrame{};
00029
00030         void OnWindowClosed(Windows::UI::WindowManagement::AppWindow const& sender, IInspectable const&);
00031     };
00032 }
00033
00034 namespace winrt::SDKTemplate::factory_implementation
00035 {
00036     struct Scenario5_RelativePositioning : Scenario5_RelativePositioningT<Scenario5_RelativePositioning, implementation::Scenario5_RelativePositioning>
00037     {
00038     };
00039 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cppwinrt/Common/DirectXHelper.h Source File

  • BasicHologram
  • cppwinrt
  • Common

DirectXHelper.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 namespace DX
00004 {
00005     // Function that reads from a binary file asynchronously.
00006     inline std::future<std::vector<byte>> ReadDataAsync(const std::wstring_view& filename)
00007     {
00008         using namespace winrt::Windows::Storage;
00009         using namespace winrt::Windows::Storage::Streams;
00010
00011         IBuffer fileBuffer = co_await PathIO::ReadBufferAsync(filename);
00012
00013         std::vector<byte> returnBuffer;
00014         returnBuffer.resize(fileBuffer.Length());
00015         DataReader::FromBuffer(fileBuffer).ReadBytes(winrt::array_view<uint8_t>(returnBuffer));
00016         return returnBuffer;
00017     }
00018
00019     // Converts a length in device-independent pixels (DIPs) to a length in physical pixels.
00020     inline float ConvertDipsToPixels(float dips, float dpi)
00021     {
00022         constexpr float dipsPerInch = 96.0f;
00023         return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00024     }
00025
00026     inline winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface CreateDepthTextureInteropObject(
00027         const Microsoft::WRL::ComPtr<ID3D11Texture2D> spTexture2D)
00028     {
00029         // Direct3D interop APIs are used to provide the buffer to the WinRT API.
00030         Microsoft::WRL::ComPtr<IDXGIResource1> depthStencilResource;
00031         winrt::check_hresult(spTexture2D.As(&depthStencilResource));
00032         Microsoft::WRL::ComPtr<IDXGISurface2> depthDxgiSurface;
00033         winrt::check_hresult(depthStencilResource->CreateSubresourceSurface(0, &depthDxgiSurface));
00034         winrt::com_ptr<::IInspectable> inspectableSurface;
00035         winrt::check_hresult(
00036             CreateDirect3D11SurfaceFromDXGISurface(
00037                 depthDxgiSurface.Get(),
00038                 inspectableSurface.put()
00039             ));
00040
00041         return inspectableSurface.as<winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface>();
00042     }
00043
00044 #if defined(_DEBUG)
00045     // Check for SDK Layer support.
00046     inline bool SdkLayersAvailable()
00047     {
00048         HRESULT hr = D3D11CreateDevice(
00049             nullptr,
00050             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00051             0,
00052             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00053             nullptr,                    // Any feature level will do.
00054             0,
00055             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00056             nullptr,                    // No need to keep the D3D device reference.
00057             nullptr,                    // No need to know the feature level.
00058             nullptr                     // No need to keep the D3D device context reference.
00059         );
00060
00061         return SUCCEEDED(hr);
00062     }
00063 #endif
00064 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/Content/DDSTextureLoader.cpp Source File

  • HolographicTagAlong
  • cpp
  • Content

DDSTextureLoader.cpp

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.cpp
00003 //
00004 // Functions for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note these functions are useful as a light-weight runtime loader for DDS files. For
00007 // a full-featured DDS file reader, writer, and texture processing pipeline see
00008 // the 'Texconv' sample and the 'DirectXTex' library.
00009 //
00010 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00011 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00012 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00013 // PARTICULAR PURPOSE.
00014 //
00015 // Copyright (c) Microsoft Corporation. All rights reserved.
00016 //
00017 // http://go.microsoft.com/fwlink/?LinkId=248926
00018 // http://go.microsoft.com/fwlink/?LinkId=248929
00019 //--------------------------------------------------------------------------------------
00020
00021 #include "pch.h"
00022
00023 #include <assert.h>
00024 #include <algorithm>
00025 #include <memory>
00026
00027 #include "DDSTextureLoader.h"
00028
00029 #if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) )
00030 #pragma comment(lib,"dxguid.lib")
00031 #endif
00032
00033 using namespace DirectX;
00034
00035 //--------------------------------------------------------------------------------------
00036 // Macros
00037 //--------------------------------------------------------------------------------------
00038 #ifndef MAKEFOURCC
00039     #define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
00040                 ((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) |       \
00041                 ((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24 ))
00042 #endif /* defined(MAKEFOURCC) */
00043
00044 //--------------------------------------------------------------------------------------
00045 // DDS file structure definitions
00046 //
00047 // See DDS.h in the 'Texconv' sample and the 'DirectXTex' library
00048 //--------------------------------------------------------------------------------------
00049 #pragma pack(push,1)
00050
00051 const uint32_t DDS_MAGIC = 0x20534444; // "DDS "
00052
00053 struct DDS_PIXELFORMAT
00054 {
00055     uint32_t    size;
00056     uint32_t    flags;
00057     uint32_t    fourCC;
00058     uint32_t    RGBBitCount;
00059     uint32_t    RBitMask;
00060     uint32_t    GBitMask;
00061     uint32_t    BBitMask;
00062     uint32_t    ABitMask;
00063 };
00064
00065 #define DDS_FOURCC      0x00000004  // DDPF_FOURCC
00066 #define DDS_RGB         0x00000040  // DDPF_RGB
00067 #define DDS_LUMINANCE   0x00020000  // DDPF_LUMINANCE
00068 #define DDS_ALPHA       0x00000002  // DDPF_ALPHA
00069
00070 #define DDS_HEADER_FLAGS_VOLUME         0x00800000  // DDSD_DEPTH
00071
00072 #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT
00073 #define DDS_WIDTH  0x00000004 // DDSD_WIDTH
00074
00075 #define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
00076 #define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
00077 #define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
00078 #define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
00079 #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
00080 #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
00081
00082 #define DDS_CUBEMAP_ALLFACES ( DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\
00083                                DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\
00084                                DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ )
00085
00086 #define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP
00087
00088 enum DDS_MISC_FLAGS2
00089 {
00090     DDS_MISC_FLAGS2_ALPHA_MODE_MASK = 0x7L,
00091 };
00092
00093 struct DDS_HEADER
00094 {
00095     uint32_t        size;
00096     uint32_t        flags;
00097     uint32_t        height;
00098     uint32_t        width;
00099     uint32_t        pitchOrLinearSize;
00100     uint32_t        depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags
00101     uint32_t        mipMapCount;
00102     uint32_t        reserved1[11];
00103     DDS_PIXELFORMAT ddspf;
00104     uint32_t        caps;
00105     uint32_t        caps2;
00106     uint32_t        caps3;
00107     uint32_t        caps4;
00108     uint32_t        reserved2;
00109 };
00110
00111 struct DDS_HEADER_DXT10
00112 {
00113     DXGI_FORMAT     dxgiFormat;
00114     uint32_t        resourceDimension;
00115     uint32_t        miscFlag; // see D3D11_RESOURCE_MISC_FLAG
00116     uint32_t        arraySize;
00117     uint32_t        miscFlags2;
00118 };
00119
00120 #pragma pack(pop)
00121
00122 //--------------------------------------------------------------------------------------
00123 namespace
00124 {
00125
00126 struct handle_closer { void operator()(HANDLE h) { if (h) CloseHandle(h); } };
00127
00128 typedef public std::unique_ptr<void, handle_closer> ScopedHandle;
00129
00130 inline HANDLE safe_handle( HANDLE h ) { return (h == INVALID_HANDLE_VALUE) ? 0 : h; }
00131
00132 template<UINT TNameLength>
00133 inline void SetDebugObjectName(_In_ ID3D11DeviceChild* resource, _In_ const char (&name)[TNameLength])
00134 {
00135 #if defined(_DEBUG) || defined(PROFILE)
00136     resource->SetPrivateData(WKPDID_D3DDebugObjectName, TNameLength - 1, name);
00137 #else
00138     UNREFERENCED_PARAMETER(resource);
00139     UNREFERENCED_PARAMETER(name);
00140 #endif
00141 }
00142
00143 };
00144
00145 //--------------------------------------------------------------------------------------
00146 static HRESULT LoadTextureDataFromFile( _In_z_ const wchar_t* fileName,
00147                                         std::unique_ptr<uint8_t[]>& ddsData,
00148                                         DDS_HEADER** header,
00149                                         uint8_t** bitData,
00150                                         size_t* bitSize
00151                                       )
00152 {
00153     if (!header || !bitData || !bitSize)
00154     {
00155         return E_POINTER;
00156     }
00157
00158     // open the file
00159 #if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
00160     ScopedHandle hFile( safe_handle( CreateFile2( fileName,
00161                                                   GENERIC_READ,
00162                                                   FILE_SHARE_READ,
00163                                                   OPEN_EXISTING,
00164                                                   nullptr ) ) );
00165 #else
00166     ScopedHandle hFile( safe_handle( CreateFileW( fileName,
00167                                                   GENERIC_READ,
00168                                                   FILE_SHARE_READ,
00169                                                   nullptr,
00170                                                   OPEN_EXISTING,
00171                                                   FILE_ATTRIBUTE_NORMAL,
00172                                                   nullptr ) ) );
00173 #endif
00174
00175     if ( !hFile )
00176     {
00177         return HRESULT_FROM_WIN32( GetLastError() );
00178     }
00179
00180     // Get the file size
00181     LARGE_INTEGER FileSize = { 0 };
00182
00183 #if (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
00184     FILE_STANDARD_INFO fileInfo;
00185     if ( !GetFileInformationByHandleEx( hFile.get(), FileStandardInfo, &fileInfo, sizeof(fileInfo) ) )
00186     {
00187         return HRESULT_FROM_WIN32( GetLastError() );
00188     }
00189     FileSize = fileInfo.EndOfFile;
00190 #else
00191     GetFileSizeEx( hFile.get(), &FileSize );
00192 #endif
00193
00194     // File is too big for 32-bit allocation, so reject read
00195     if (FileSize.HighPart > 0)
00196     {
00197         return E_FAIL;
00198     }
00199
00200     // Need at least enough data to fill the header and magic number to be a valid DDS
00201     if (FileSize.LowPart < ( sizeof(DDS_HEADER) + sizeof(uint32_t) ) )
00202     {
00203         return E_FAIL;
00204     }
00205
00206     // create enough space for the file data
00207     ddsData.reset( new (std::nothrow) uint8_t[ FileSize.LowPart ] );
00208     if (!ddsData)
00209     {
00210         return E_OUTOFMEMORY;
00211     }
00212
00213     // read the data in
00214     DWORD BytesRead = 0;
00215     if (!ReadFile( hFile.get(),
00216                    ddsData.get(),
00217                    FileSize.LowPart,
00218                    &BytesRead,
00219                    nullptr
00220                  ))
00221     {
00222         return HRESULT_FROM_WIN32( GetLastError() );
00223     }
00224
00225     if (BytesRead < FileSize.LowPart)
00226     {
00227         return E_FAIL;
00228     }
00229
00230     // DDS files always start with the same magic number ("DDS ")
00231     uint32_t dwMagicNumber = *( const uint32_t* )( ddsData.get() );
00232     if (dwMagicNumber != DDS_MAGIC)
00233     {
00234         return E_FAIL;
00235     }
00236
00237     auto hdr = reinterpret_cast<DDS_HEADER*>( ddsData.get() + sizeof( uint32_t ) );
00238
00239     // Verify header to validate DDS file
00240     if (hdr->size != sizeof(DDS_HEADER) ||
00241         hdr->ddspf.size != sizeof(DDS_PIXELFORMAT))
00242     {
00243         return E_FAIL;
00244     }
00245
00246     // Check for DX10 extension
00247     bool bDXT10Header = false;
00248     if ((hdr->ddspf.flags & DDS_FOURCC) &&
00249         (MAKEFOURCC( 'D', 'X', '1', '0' ) == hdr->ddspf.fourCC))
00250     {
00251         // Must be long enough for both headers and magic value
00252         if (FileSize.LowPart < ( sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10) ) )
00253         {
00254             return E_FAIL;
00255         }
00256
00257         bDXT10Header = true;
00258     }
00259
00260     // setup the pointers in the process request
00261     *header = hdr;
00262     ptrdiff_t offset = sizeof( uint32_t ) + sizeof( DDS_HEADER )
00263                        + (bDXT10Header ? sizeof( DDS_HEADER_DXT10 ) : 0);
00264     *bitData = ddsData.get() + offset;
00265     *bitSize = FileSize.LowPart - offset;
00266
00267     return S_OK;
00268 }
00269
00270
00271 //--------------------------------------------------------------------------------------
00272 // Return the BPP for a particular format
00273 //--------------------------------------------------------------------------------------
00274 static size_t BitsPerPixel( _In_ DXGI_FORMAT fmt )
00275 {
00276     switch( fmt )
00277     {
00278     case DXGI_FORMAT_R32G32B32A32_TYPELESS:
00279     case DXGI_FORMAT_R32G32B32A32_FLOAT:
00280     case DXGI_FORMAT_R32G32B32A32_UINT:
00281     case DXGI_FORMAT_R32G32B32A32_SINT:
00282         return 128;
00283
00284     case DXGI_FORMAT_R32G32B32_TYPELESS:
00285     case DXGI_FORMAT_R32G32B32_FLOAT:
00286     case DXGI_FORMAT_R32G32B32_UINT:
00287     case DXGI_FORMAT_R32G32B32_SINT:
00288         return 96;
00289
00290     case DXGI_FORMAT_R16G16B16A16_TYPELESS:
00291     case DXGI_FORMAT_R16G16B16A16_FLOAT:
00292     case DXGI_FORMAT_R16G16B16A16_UNORM:
00293     case DXGI_FORMAT_R16G16B16A16_UINT:
00294     case DXGI_FORMAT_R16G16B16A16_SNORM:
00295     case DXGI_FORMAT_R16G16B16A16_SINT:
00296     case DXGI_FORMAT_R32G32_TYPELESS:
00297     case DXGI_FORMAT_R32G32_FLOAT:
00298     case DXGI_FORMAT_R32G32_UINT:
00299     case DXGI_FORMAT_R32G32_SINT:
00300     case DXGI_FORMAT_R32G8X24_TYPELESS:
00301     case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
00302     case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
00303     case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
00304     case DXGI_FORMAT_Y416:
00305     case DXGI_FORMAT_Y210:
00306     case DXGI_FORMAT_Y216:
00307         return 64;
00308
00309     case DXGI_FORMAT_R10G10B10A2_TYPELESS:
00310     case DXGI_FORMAT_R10G10B10A2_UNORM:
00311     case DXGI_FORMAT_R10G10B10A2_UINT:
00312     case DXGI_FORMAT_R11G11B10_FLOAT:
00313     case DXGI_FORMAT_R8G8B8A8_TYPELESS:
00314     case DXGI_FORMAT_R8G8B8A8_UNORM:
00315     case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
00316     case DXGI_FORMAT_R8G8B8A8_UINT:
00317     case DXGI_FORMAT_R8G8B8A8_SNORM:
00318     case DXGI_FORMAT_R8G8B8A8_SINT:
00319     case DXGI_FORMAT_R16G16_TYPELESS:
00320     case DXGI_FORMAT_R16G16_FLOAT:
00321     case DXGI_FORMAT_R16G16_UNORM:
00322     case DXGI_FORMAT_R16G16_UINT:
00323     case DXGI_FORMAT_R16G16_SNORM:
00324     case DXGI_FORMAT_R16G16_SINT:
00325     case DXGI_FORMAT_R32_TYPELESS:
00326     case DXGI_FORMAT_D32_FLOAT:
00327     case DXGI_FORMAT_R32_FLOAT:
00328     case DXGI_FORMAT_R32_UINT:
00329     case DXGI_FORMAT_R32_SINT:
00330     case DXGI_FORMAT_R24G8_TYPELESS:
00331     case DXGI_FORMAT_D24_UNORM_S8_UINT:
00332     case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
00333     case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
00334     case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
00335     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00336     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00337     case DXGI_FORMAT_B8G8R8A8_UNORM:
00338     case DXGI_FORMAT_B8G8R8X8_UNORM:
00339     case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
00340     case DXGI_FORMAT_B8G8R8A8_TYPELESS:
00341     case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
00342     case DXGI_FORMAT_B8G8R8X8_TYPELESS:
00343     case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
00344     case DXGI_FORMAT_AYUV:
00345     case DXGI_FORMAT_Y410:
00346     case DXGI_FORMAT_YUY2:
00347         return 32;
00348
00349     case DXGI_FORMAT_P010:
00350     case DXGI_FORMAT_P016:
00351         return 24;
00352
00353     case DXGI_FORMAT_R8G8_TYPELESS:
00354     case DXGI_FORMAT_R8G8_UNORM:
00355     case DXGI_FORMAT_R8G8_UINT:
00356     case DXGI_FORMAT_R8G8_SNORM:
00357     case DXGI_FORMAT_R8G8_SINT:
00358     case DXGI_FORMAT_R16_TYPELESS:
00359     case DXGI_FORMAT_R16_FLOAT:
00360     case DXGI_FORMAT_D16_UNORM:
00361     case DXGI_FORMAT_R16_UNORM:
00362     case DXGI_FORMAT_R16_UINT:
00363     case DXGI_FORMAT_R16_SNORM:
00364     case DXGI_FORMAT_R16_SINT:
00365     case DXGI_FORMAT_B5G6R5_UNORM:
00366     case DXGI_FORMAT_B5G5R5A1_UNORM:
00367     case DXGI_FORMAT_A8P8:
00368     case DXGI_FORMAT_B4G4R4A4_UNORM:
00369         return 16;
00370
00371     case DXGI_FORMAT_NV12:
00372     case DXGI_FORMAT_420_OPAQUE:
00373     case DXGI_FORMAT_NV11:
00374         return 12;
00375
00376     case DXGI_FORMAT_R8_TYPELESS:
00377     case DXGI_FORMAT_R8_UNORM:
00378     case DXGI_FORMAT_R8_UINT:
00379     case DXGI_FORMAT_R8_SNORM:
00380     case DXGI_FORMAT_R8_SINT:
00381     case DXGI_FORMAT_A8_UNORM:
00382     case DXGI_FORMAT_AI44:
00383     case DXGI_FORMAT_IA44:
00384     case DXGI_FORMAT_P8:
00385         return 8;
00386
00387     case DXGI_FORMAT_R1_UNORM:
00388         return 1;
00389
00390     case DXGI_FORMAT_BC1_TYPELESS:
00391     case DXGI_FORMAT_BC1_UNORM:
00392     case DXGI_FORMAT_BC1_UNORM_SRGB:
00393     case DXGI_FORMAT_BC4_TYPELESS:
00394     case DXGI_FORMAT_BC4_UNORM:
00395     case DXGI_FORMAT_BC4_SNORM:
00396         return 4;
00397
00398     case DXGI_FORMAT_BC2_TYPELESS:
00399     case DXGI_FORMAT_BC2_UNORM:
00400     case DXGI_FORMAT_BC2_UNORM_SRGB:
00401     case DXGI_FORMAT_BC3_TYPELESS:
00402     case DXGI_FORMAT_BC3_UNORM:
00403     case DXGI_FORMAT_BC3_UNORM_SRGB:
00404     case DXGI_FORMAT_BC5_TYPELESS:
00405     case DXGI_FORMAT_BC5_UNORM:
00406     case DXGI_FORMAT_BC5_SNORM:
00407     case DXGI_FORMAT_BC6H_TYPELESS:
00408     case DXGI_FORMAT_BC6H_UF16:
00409     case DXGI_FORMAT_BC6H_SF16:
00410     case DXGI_FORMAT_BC7_TYPELESS:
00411     case DXGI_FORMAT_BC7_UNORM:
00412     case DXGI_FORMAT_BC7_UNORM_SRGB:
00413         return 8;
00414
00415 #if defined(_XBOX_ONE) && defined(_TITLE)
00416
00417     case DXGI_FORMAT_R10G10B10_7E3_A2_FLOAT:
00418     case DXGI_FORMAT_R10G10B10_6E4_A2_FLOAT:
00419         return 32;
00420
00421     case DXGI_FORMAT_D16_UNORM_S8_UINT:
00422     case DXGI_FORMAT_R16_UNORM_X8_TYPELESS:
00423     case DXGI_FORMAT_X16_TYPELESS_G8_UINT:
00424         return 24;
00425
00426 #endif // _XBOX_ONE && _TITLE
00427
00428     default:
00429         return 0;
00430     }
00431 }
00432
00433
00434 //--------------------------------------------------------------------------------------
00435 // Get surface information for a particular format
00436 //--------------------------------------------------------------------------------------
00437 static void GetSurfaceInfo( _In_ size_t width,
00438                             _In_ size_t height,
00439                             _In_ DXGI_FORMAT fmt,
00440                             _Out_opt_ size_t* outNumBytes,
00441                             _Out_opt_ size_t* outRowBytes,
00442                             _Out_opt_ size_t* outNumRows )
00443 {
00444     size_t numBytes = 0;
00445     size_t rowBytes = 0;
00446     size_t numRows = 0;
00447
00448     bool bc = false;
00449     bool packed = false;
00450     bool planar = false;
00451     size_t bpe = 0;
00452     switch (fmt)
00453     {
00454     case DXGI_FORMAT_BC1_TYPELESS:
00455     case DXGI_FORMAT_BC1_UNORM:
00456     case DXGI_FORMAT_BC1_UNORM_SRGB:
00457     case DXGI_FORMAT_BC4_TYPELESS:
00458     case DXGI_FORMAT_BC4_UNORM:
00459     case DXGI_FORMAT_BC4_SNORM:
00460         bc=true;
00461         bpe = 8;
00462         break;
00463
00464     case DXGI_FORMAT_BC2_TYPELESS:
00465     case DXGI_FORMAT_BC2_UNORM:
00466     case DXGI_FORMAT_BC2_UNORM_SRGB:
00467     case DXGI_FORMAT_BC3_TYPELESS:
00468     case DXGI_FORMAT_BC3_UNORM:
00469     case DXGI_FORMAT_BC3_UNORM_SRGB:
00470     case DXGI_FORMAT_BC5_TYPELESS:
00471     case DXGI_FORMAT_BC5_UNORM:
00472     case DXGI_FORMAT_BC5_SNORM:
00473     case DXGI_FORMAT_BC6H_TYPELESS:
00474     case DXGI_FORMAT_BC6H_UF16:
00475     case DXGI_FORMAT_BC6H_SF16:
00476     case DXGI_FORMAT_BC7_TYPELESS:
00477     case DXGI_FORMAT_BC7_UNORM:
00478     case DXGI_FORMAT_BC7_UNORM_SRGB:
00479         bc = true;
00480         bpe = 16;
00481         break;
00482
00483     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00484     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00485     case DXGI_FORMAT_YUY2:
00486         packed = true;
00487         bpe = 4;
00488         break;
00489
00490     case DXGI_FORMAT_Y210:
00491     case DXGI_FORMAT_Y216:
00492         packed = true;
00493         bpe = 8;
00494         break;
00495
00496     case DXGI_FORMAT_NV12:
00497     case DXGI_FORMAT_420_OPAQUE:
00498         planar = true;
00499         bpe = 2;
00500         break;
00501
00502     case DXGI_FORMAT_P010:
00503     case DXGI_FORMAT_P016:
00504         planar = true;
00505         bpe = 4;
00506         break;
00507
00508 #if defined(_XBOX_ONE) && defined(_TITLE)
00509
00510     case DXGI_FORMAT_D16_UNORM_S8_UINT:
00511     case DXGI_FORMAT_R16_UNORM_X8_TYPELESS:
00512     case DXGI_FORMAT_X16_TYPELESS_G8_UINT:
00513         planar = true;
00514         bpe = 4;
00515         break;
00516
00517 #endif
00518     }
00519
00520     if (bc)
00521     {
00522         size_t numBlocksWide = 0;
00523         if (width > 0)
00524         {
00525             numBlocksWide = std::max<size_t>( 1, (width + 3) / 4 );
00526         }
00527         size_t numBlocksHigh = 0;
00528         if (height > 0)
00529         {
00530             numBlocksHigh = std::max<size_t>( 1, (height + 3) / 4 );
00531         }
00532         rowBytes = numBlocksWide * bpe;
00533         numRows = numBlocksHigh;
00534         numBytes = rowBytes * numBlocksHigh;
00535     }
00536     else if (packed)
00537     {
00538         rowBytes = ( ( width + 1 ) >> 1 ) * bpe;
00539         numRows = height;
00540         numBytes = rowBytes * height;
00541     }
00542     else if ( fmt == DXGI_FORMAT_NV11 )
00543     {
00544         rowBytes = ( ( width + 3 ) >> 2 ) * 4;
00545         numRows = height * 2; // Direct3D makes this simplifying assumption, although it is larger than the 4:1:1 data
00546         numBytes = rowBytes * numRows;
00547     }
00548     else if (planar)
00549     {
00550         rowBytes = ( ( width + 1 ) >> 1 ) * bpe;
00551         numBytes = ( rowBytes * height ) + ( ( rowBytes * height + 1 ) >> 1 );
00552         numRows = height + ( ( height + 1 ) >> 1 );
00553     }
00554     else
00555     {
00556         size_t bpp = BitsPerPixel( fmt );
00557         rowBytes = ( width * bpp + 7 ) / 8; // round up to nearest byte
00558         numRows = height;
00559         numBytes = rowBytes * height;
00560     }
00561
00562     if (outNumBytes)
00563     {
00564         *outNumBytes = numBytes;
00565     }
00566     if (outRowBytes)
00567     {
00568         *outRowBytes = rowBytes;
00569     }
00570     if (outNumRows)
00571     {
00572         *outNumRows = numRows;
00573     }
00574 }
00575
00576
00577 //--------------------------------------------------------------------------------------
00578 #define ISBITMASK( r,g,b,a ) ( ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a )
00579
00580 static DXGI_FORMAT GetDXGIFormat( const DDS_PIXELFORMAT& ddpf )
00581 {
00582     if (ddpf.flags & DDS_RGB)
00583     {
00584         // Note that sRGB formats are written using the "DX10" extended header
00585
00586         switch (ddpf.RGBBitCount)
00587         {
00588         case 32:
00589             if (ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0xff000000))
00590             {
00591                 return DXGI_FORMAT_R8G8B8A8_UNORM;
00592             }
00593
00594             if (ISBITMASK(0x00ff0000,0x0000ff00,0x000000ff,0xff000000))
00595             {
00596                 return DXGI_FORMAT_B8G8R8A8_UNORM;
00597             }
00598
00599             if (ISBITMASK(0x00ff0000,0x0000ff00,0x000000ff,0x00000000))
00600             {
00601                 return DXGI_FORMAT_B8G8R8X8_UNORM;
00602             }
00603
00604             // No DXGI format maps to ISBITMASK(0x000000ff,0x0000ff00,0x00ff0000,0x00000000) aka D3DFMT_X8B8G8R8
00605
00606             // Note that many common DDS reader/writers (including D3DX) swap the
00607             // the RED/BLUE masks for 10:10:10:2 formats. We assumme
00608             // below that the 'backwards' header mask is being used since it is most
00609             // likely written by D3DX. The more robust solution is to use the 'DX10'
00610             // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly
00611
00612             // For 'correct' writers, this should be 0x000003ff,0x000ffc00,0x3ff00000 for RGB data
00613             if (ISBITMASK(0x3ff00000,0x000ffc00,0x000003ff,0xc0000000))
00614             {
00615                 return DXGI_FORMAT_R10G10B10A2_UNORM;
00616             }
00617
00618             // No DXGI format maps to ISBITMASK(0x000003ff,0x000ffc00,0x3ff00000,0xc0000000) aka D3DFMT_A2R10G10B10
00619
00620             if (ISBITMASK(0x0000ffff,0xffff0000,0x00000000,0x00000000))
00621             {
00622                 return DXGI_FORMAT_R16G16_UNORM;
00623             }
00624
00625             if (ISBITMASK(0xffffffff,0x00000000,0x00000000,0x00000000))
00626             {
00627                 // Only 32-bit color channel format in D3D9 was R32F
00628                 return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114
00629             }
00630             break;
00631
00632         case 24:
00633             // No 24bpp DXGI formats aka D3DFMT_R8G8B8
00634             break;
00635
00636         case 16:
00637             if (ISBITMASK(0x7c00,0x03e0,0x001f,0x8000))
00638             {
00639                 return DXGI_FORMAT_B5G5R5A1_UNORM;
00640             }
00641             if (ISBITMASK(0xf800,0x07e0,0x001f,0x0000))
00642             {
00643                 return DXGI_FORMAT_B5G6R5_UNORM;
00644             }
00645
00646             // No DXGI format maps to ISBITMASK(0x7c00,0x03e0,0x001f,0x0000) aka D3DFMT_X1R5G5B5
00647
00648             if (ISBITMASK(0x0f00,0x00f0,0x000f,0xf000))
00649             {
00650                 return DXGI_FORMAT_B4G4R4A4_UNORM;
00651             }
00652
00653             // No DXGI format maps to ISBITMASK(0x0f00,0x00f0,0x000f,0x0000) aka D3DFMT_X4R4G4B4
00654
00655             // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc.
00656             break;
00657         }
00658     }
00659     else if (ddpf.flags & DDS_LUMINANCE)
00660     {
00661         if (8 == ddpf.RGBBitCount)
00662         {
00663             if (ISBITMASK(0x000000ff,0x00000000,0x00000000,0x00000000))
00664             {
00665                 return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension
00666             }
00667
00668             // No DXGI format maps to ISBITMASK(0x0f,0x00,0x00,0xf0) aka D3DFMT_A4L4
00669         }
00670
00671         if (16 == ddpf.RGBBitCount)
00672         {
00673             if (ISBITMASK(0x0000ffff,0x00000000,0x00000000,0x00000000))
00674             {
00675                 return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension
00676             }
00677             if (ISBITMASK(0x000000ff,0x00000000,0x00000000,0x0000ff00))
00678             {
00679                 return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension
00680             }
00681         }
00682     }
00683     else if (ddpf.flags & DDS_ALPHA)
00684     {
00685         if (8 == ddpf.RGBBitCount)
00686         {
00687             return DXGI_FORMAT_A8_UNORM;
00688         }
00689     }
00690     else if (ddpf.flags & DDS_FOURCC)
00691     {
00692         if (MAKEFOURCC( 'D', 'X', 'T', '1' ) == ddpf.fourCC)
00693         {
00694             return DXGI_FORMAT_BC1_UNORM;
00695         }
00696         if (MAKEFOURCC( 'D', 'X', 'T', '3' ) == ddpf.fourCC)
00697         {
00698             return DXGI_FORMAT_BC2_UNORM;
00699         }
00700         if (MAKEFOURCC( 'D', 'X', 'T', '5' ) == ddpf.fourCC)
00701         {
00702             return DXGI_FORMAT_BC3_UNORM;
00703         }
00704
00705         // While pre-mulitplied alpha isn't directly supported by the DXGI formats,
00706         // they are basically the same as these BC formats so they can be mapped
00707         if (MAKEFOURCC( 'D', 'X', 'T', '2' ) == ddpf.fourCC)
00708         {
00709             return DXGI_FORMAT_BC2_UNORM;
00710         }
00711         if (MAKEFOURCC( 'D', 'X', 'T', '4' ) == ddpf.fourCC)
00712         {
00713             return DXGI_FORMAT_BC3_UNORM;
00714         }
00715
00716         if (MAKEFOURCC( 'A', 'T', 'I', '1' ) == ddpf.fourCC)
00717         {
00718             return DXGI_FORMAT_BC4_UNORM;
00719         }
00720         if (MAKEFOURCC( 'B', 'C', '4', 'U' ) == ddpf.fourCC)
00721         {
00722             return DXGI_FORMAT_BC4_UNORM;
00723         }
00724         if (MAKEFOURCC( 'B', 'C', '4', 'S' ) == ddpf.fourCC)
00725         {
00726             return DXGI_FORMAT_BC4_SNORM;
00727         }
00728
00729         if (MAKEFOURCC( 'A', 'T', 'I', '2' ) == ddpf.fourCC)
00730         {
00731             return DXGI_FORMAT_BC5_UNORM;
00732         }
00733         if (MAKEFOURCC( 'B', 'C', '5', 'U' ) == ddpf.fourCC)
00734         {
00735             return DXGI_FORMAT_BC5_UNORM;
00736         }
00737         if (MAKEFOURCC( 'B', 'C', '5', 'S' ) == ddpf.fourCC)
00738         {
00739             return DXGI_FORMAT_BC5_SNORM;
00740         }
00741
00742         // BC6H and BC7 are written using the "DX10" extended header
00743
00744         if (MAKEFOURCC( 'R', 'G', 'B', 'G' ) == ddpf.fourCC)
00745         {
00746             return DXGI_FORMAT_R8G8_B8G8_UNORM;
00747         }
00748         if (MAKEFOURCC( 'G', 'R', 'G', 'B' ) == ddpf.fourCC)
00749         {
00750             return DXGI_FORMAT_G8R8_G8B8_UNORM;
00751         }
00752
00753         if (MAKEFOURCC('Y','U','Y','2') == ddpf.fourCC)
00754         {
00755             return DXGI_FORMAT_YUY2;
00756         }
00757
00758         // Check for D3DFORMAT enums being set here
00759         switch( ddpf.fourCC )
00760         {
00761         case 36: // D3DFMT_A16B16G16R16
00762             return DXGI_FORMAT_R16G16B16A16_UNORM;
00763
00764         case 110: // D3DFMT_Q16W16V16U16
00765             return DXGI_FORMAT_R16G16B16A16_SNORM;
00766
00767         case 111: // D3DFMT_R16F
00768             return DXGI_FORMAT_R16_FLOAT;
00769
00770         case 112: // D3DFMT_G16R16F
00771             return DXGI_FORMAT_R16G16_FLOAT;
00772
00773         case 113: // D3DFMT_A16B16G16R16F
00774             return DXGI_FORMAT_R16G16B16A16_FLOAT;
00775
00776         case 114: // D3DFMT_R32F
00777             return DXGI_FORMAT_R32_FLOAT;
00778
00779         case 115: // D3DFMT_G32R32F
00780             return DXGI_FORMAT_R32G32_FLOAT;
00781
00782         case 116: // D3DFMT_A32B32G32R32F
00783             return DXGI_FORMAT_R32G32B32A32_FLOAT;
00784         }
00785     }
00786
00787     return DXGI_FORMAT_UNKNOWN;
00788 }
00789
00790
00791 //--------------------------------------------------------------------------------------
00792 static DXGI_FORMAT MakeSRGB( _In_ DXGI_FORMAT format )
00793 {
00794     switch( format )
00795     {
00796     case DXGI_FORMAT_R8G8B8A8_UNORM:
00797         return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
00798
00799     case DXGI_FORMAT_BC1_UNORM:
00800         return DXGI_FORMAT_BC1_UNORM_SRGB;
00801
00802     case DXGI_FORMAT_BC2_UNORM:
00803         return DXGI_FORMAT_BC2_UNORM_SRGB;
00804
00805     case DXGI_FORMAT_BC3_UNORM:
00806         return DXGI_FORMAT_BC3_UNORM_SRGB;
00807
00808     case DXGI_FORMAT_B8G8R8A8_UNORM:
00809         return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
00810
00811     case DXGI_FORMAT_B8G8R8X8_UNORM:
00812         return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
00813
00814     case DXGI_FORMAT_BC7_UNORM:
00815         return DXGI_FORMAT_BC7_UNORM_SRGB;
00816
00817     default:
00818         return format;
00819     }
00820 }
00821
00822
00823 //--------------------------------------------------------------------------------------
00824 static HRESULT FillInitData( _In_ size_t width,
00825                              _In_ size_t height,
00826                              _In_ size_t depth,
00827                              _In_ size_t mipCount,
00828                              _In_ size_t arraySize,
00829                              _In_ DXGI_FORMAT format,
00830                              _In_ size_t maxsize,
00831                              _In_ size_t bitSize,
00832                              _In_reads_bytes_(bitSize) const uint8_t* bitData,
00833                              _Out_ size_t& twidth,
00834                              _Out_ size_t& theight,
00835                              _Out_ size_t& tdepth,
00836                              _Out_ size_t& skipMip,
00837                              _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData )
00838 {
00839     if ( !bitData || !initData )
00840     {
00841         return E_POINTER;
00842     }
00843
00844     skipMip = 0;
00845     twidth = 0;
00846     theight = 0;
00847     tdepth = 0;
00848
00849     size_t NumBytes = 0;
00850     size_t RowBytes = 0;
00851     const uint8_t* pSrcBits = bitData;
00852     const uint8_t* pEndBits = bitData + bitSize;
00853
00854     size_t index = 0;
00855     for( size_t j = 0; j < arraySize; j++ )
00856     {
00857         size_t w = width;
00858         size_t h = height;
00859         size_t d = depth;
00860         for( size_t i = 0; i < mipCount; i++ )
00861         {
00862             GetSurfaceInfo( w,
00863                             h,
00864                             format,
00865                             &NumBytes,
00866                             &RowBytes,
00867                             nullptr
00868                           );
00869
00870             if ( (mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize) )
00871             {
00872                 if ( !twidth )
00873                 {
00874                     twidth = w;
00875                     theight = h;
00876                     tdepth = d;
00877                 }
00878
00879                 assert(index < mipCount * arraySize);
00880                 _Analysis_assume_(index < mipCount * arraySize);
00881                 initData[index].pSysMem = ( const void* )pSrcBits;
00882                 initData[index].SysMemPitch = static_cast<UINT>( RowBytes );
00883                 initData[index].SysMemSlicePitch = static_cast<UINT>( NumBytes );
00884                 ++index;
00885             }
00886             else if ( !j )
00887             {
00888                 // Count number of skipped mipmaps (first item only)
00889                 ++skipMip;
00890             }
00891
00892             if (pSrcBits + (NumBytes*d) > pEndBits)
00893             {
00894                 return HRESULT_FROM_WIN32( ERROR_HANDLE_EOF );
00895             }
00896
00897             pSrcBits += NumBytes * d;
00898
00899             w = w >> 1;
00900             h = h >> 1;
00901             d = d >> 1;
00902             if (w == 0)
00903             {
00904                 w = 1;
00905             }
00906             if (h == 0)
00907             {
00908                 h = 1;
00909             }
00910             if (d == 0)
00911             {
00912                 d = 1;
00913             }
00914         }
00915     }
00916
00917     return (index > 0) ? S_OK : E_FAIL;
00918 }
00919
00920
00921 //--------------------------------------------------------------------------------------
00922 static HRESULT CreateD3DResources( _In_ ID3D11Device* d3dDevice,
00923                                    _In_ uint32_t resDim,
00924                                    _In_ size_t width,
00925                                    _In_ size_t height,
00926                                    _In_ size_t depth,
00927                                    _In_ size_t mipCount,
00928                                    _In_ size_t arraySize,
00929                                    _In_ DXGI_FORMAT format,
00930                                    _In_ D3D11_USAGE usage,
00931                                    _In_ unsigned int bindFlags,
00932                                    _In_ unsigned int cpuAccessFlags,
00933                                    _In_ unsigned int miscFlags,
00934                                    _In_ bool forceSRGB,
00935                                    _In_ bool isCubeMap,
00936                                    _In_reads_opt_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData,
00937                                    _Outptr_opt_ ID3D11Resource** texture,
00938                                    _Outptr_opt_ ID3D11ShaderResourceView** textureView )
00939 {
00940     if ( !d3dDevice )
00941         return E_POINTER;
00942
00943     HRESULT hr = E_FAIL;
00944
00945     if ( forceSRGB )
00946     {
00947         format = MakeSRGB( format );
00948     }
00949
00950     switch ( resDim )
00951     {
00952         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00953             {
00954                 D3D11_TEXTURE1D_DESC desc;
00955                 desc.Width = static_cast<UINT>( width );
00956                 desc.MipLevels = static_cast<UINT>( mipCount );
00957                 desc.ArraySize = static_cast<UINT>( arraySize );
00958                 desc.Format = format;
00959                 desc.Usage = usage;
00960                 desc.BindFlags = bindFlags;
00961                 desc.CPUAccessFlags = cpuAccessFlags;
00962                 desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE;
00963
00964                 ID3D11Texture1D* tex = nullptr;
00965                 hr = d3dDevice->CreateTexture1D( &desc,
00966                                                  initData,
00967                                                  &tex
00968                                                );
00969                 if (SUCCEEDED( hr ) && tex != 0)
00970                 {
00971                     if (textureView != 0)
00972                     {
00973                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00974                         memset( &SRVDesc, 0, sizeof( SRVDesc ) );
00975                         SRVDesc.Format = format;
00976
00977                         if (arraySize > 1)
00978                         {
00979                             SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1DARRAY;
00980                             SRVDesc.Texture1DArray.MipLevels = (!mipCount) ? -1 : desc.MipLevels;
00981                             SRVDesc.Texture1DArray.ArraySize = static_cast<UINT>( arraySize );
00982                         }
00983                         else
00984                         {
00985                             SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D;
00986                             SRVDesc.Texture1D.MipLevels = (!mipCount) ? -1 : desc.MipLevels;
00987                         }
00988
00989                         hr = d3dDevice->CreateShaderResourceView( tex,
00990                                                                   &SRVDesc,
00991                                                                   textureView
00992                                                                 );
00993                         if ( FAILED(hr) )
00994                         {
00995                             tex->Release();
00996                             return hr;
00997                         }
00998                     }
00999
01000                     if (texture != 0)
01001                     {
01002                         *texture = tex;
01003                     }
01004                     else
01005                     {
01006                         SetDebugObjectName(tex, "DDSTextureLoader");
01007                         tex->Release();
01008                     }
01009                 }
01010             }
01011            break;
01012
01013         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
01014             {
01015                 D3D11_TEXTURE2D_DESC desc;
01016                 desc.Width = static_cast<UINT>( width );
01017                 desc.Height = static_cast<UINT>( height );
01018                 desc.MipLevels = static_cast<UINT>( mipCount );
01019                 desc.ArraySize = static_cast<UINT>( arraySize );
01020                 desc.Format = format;
01021                 desc.SampleDesc.Count = 1;
01022                 desc.SampleDesc.Quality = 0;
01023                 desc.Usage = usage;
01024                 desc.BindFlags = bindFlags;
01025                 desc.CPUAccessFlags = cpuAccessFlags;
01026                 if ( isCubeMap )
01027                 {
01028                     desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_TEXTURECUBE;
01029                 }
01030                 else
01031                 {
01032                     desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE;
01033                 }
01034
01035                 ID3D11Texture2D* tex = nullptr;
01036                 hr = d3dDevice->CreateTexture2D( &desc,
01037                                                  initData,
01038                                                  &tex
01039                                                );
01040                 if (SUCCEEDED( hr ) && tex != 0)
01041                 {
01042                     if (textureView != 0)
01043                     {
01044                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
01045                         memset( &SRVDesc, 0, sizeof( SRVDesc ) );
01046                         SRVDesc.Format = format;
01047
01048                         if ( isCubeMap )
01049                         {
01050                             if (arraySize > 6)
01051                             {
01052                                 SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBEARRAY;
01053                                 SRVDesc.TextureCubeArray.MipLevels = (!mipCount) ? -1 : desc.MipLevels;
01054
01055                                 // Earlier we set arraySize to (NumCubes * 6)
01056                                 SRVDesc.TextureCubeArray.NumCubes = static_cast<UINT>( arraySize / 6 );
01057                             }
01058                             else
01059                             {
01060                                 SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE;
01061                                 SRVDesc.TextureCube.MipLevels = (!mipCount) ? -1 : desc.MipLevels;
01062                             }
01063                         }
01064                         else if (arraySize > 1)
01065                         {
01066                             SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
01067                             SRVDesc.Texture2DArray.MipLevels = (!mipCount) ? -1 : desc.MipLevels;
01068                             SRVDesc.Texture2DArray.ArraySize = static_cast<UINT>( arraySize );
01069                         }
01070                         else
01071                         {
01072                             SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
01073                             SRVDesc.Texture2D.MipLevels = (!mipCount) ? -1 : desc.MipLevels;
01074                         }
01075
01076                         hr = d3dDevice->CreateShaderResourceView( tex,
01077                                                                   &SRVDesc,
01078                                                                   textureView
01079                                                                 );
01080                         if ( FAILED(hr) )
01081                         {
01082                             tex->Release();
01083                             return hr;
01084                         }
01085                     }
01086
01087                     if (texture != 0)
01088                     {
01089                         *texture = tex;
01090                     }
01091                     else
01092                     {
01093                         SetDebugObjectName(tex, "DDSTextureLoader");
01094                         tex->Release();
01095                     }
01096                 }
01097             }
01098             break;
01099
01100         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
01101             {
01102                 D3D11_TEXTURE3D_DESC desc;
01103                 desc.Width = static_cast<UINT>( width );
01104                 desc.Height = static_cast<UINT>( height );
01105                 desc.Depth = static_cast<UINT>( depth );
01106                 desc.MipLevels = static_cast<UINT>( mipCount );
01107                 desc.Format = format;
01108                 desc.Usage = usage;
01109                 desc.BindFlags = bindFlags;
01110                 desc.CPUAccessFlags = cpuAccessFlags;
01111                 desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE;
01112
01113                 ID3D11Texture3D* tex = nullptr;
01114                 hr = d3dDevice->CreateTexture3D( &desc,
01115                                                  initData,
01116                                                  &tex
01117                                                );
01118                 if (SUCCEEDED( hr ) && tex != 0)
01119                 {
01120                     if (textureView != 0)
01121                     {
01122                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
01123                         memset( &SRVDesc, 0, sizeof( SRVDesc ) );
01124                         SRVDesc.Format = format;
01125
01126                         SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D;
01127                         SRVDesc.Texture3D.MipLevels = (!mipCount) ? -1 : desc.MipLevels;
01128
01129                         hr = d3dDevice->CreateShaderResourceView( tex,
01130                                                                   &SRVDesc,
01131                                                                   textureView
01132                                                                 );
01133                         if ( FAILED(hr) )
01134                         {
01135                             tex->Release();
01136                             return hr;
01137                         }
01138                     }
01139
01140                     if (texture != 0)
01141                     {
01142                         *texture = tex;
01143                     }
01144                     else
01145                     {
01146                         SetDebugObjectName(tex, "DDSTextureLoader");
01147                         tex->Release();
01148                     }
01149                 }
01150             }
01151             break;
01152     }
01153
01154     return hr;
01155 }
01156
01157
01158 //--------------------------------------------------------------------------------------
01159 static HRESULT CreateTextureFromDDS( _In_ ID3D11Device* d3dDevice,
01160                                      _In_opt_ ID3D11DeviceContext* d3dContext,
01161                                      _In_ const DDS_HEADER* header,
01162                                      _In_reads_bytes_(bitSize) const uint8_t* bitData,
01163                                      _In_ size_t bitSize,
01164                                      _In_ size_t maxsize,
01165                                      _In_ D3D11_USAGE usage,
01166                                      _In_ unsigned int bindFlags,
01167                                      _In_ unsigned int cpuAccessFlags,
01168                                      _In_ unsigned int miscFlags,
01169                                      _In_ bool forceSRGB,
01170                                      _Outptr_opt_ ID3D11Resource** texture,
01171                                      _Outptr_opt_ ID3D11ShaderResourceView** textureView )
01172 {
01173     HRESULT hr = S_OK;
01174
01175     size_t width = header->width;
01176     size_t height = header->height;
01177     size_t depth = header->depth;
01178
01179     uint32_t resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN;
01180     size_t arraySize = 1;
01181     DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
01182     bool isCubeMap = false;
01183
01184     size_t mipCount = header->mipMapCount;
01185     if (0 == mipCount)
01186     {
01187         mipCount = 1;
01188     }
01189
01190     if ((header->ddspf.flags & DDS_FOURCC) &&
01191         (MAKEFOURCC( 'D', 'X', '1', '0' ) == header->ddspf.fourCC ))
01192     {
01193         auto d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>( (const char*)header + sizeof(DDS_HEADER) );
01194
01195         arraySize = d3d10ext->arraySize;
01196         if (arraySize == 0)
01197         {
01198            return HRESULT_FROM_WIN32( ERROR_INVALID_DATA );
01199         }
01200
01201         switch( d3d10ext->dxgiFormat )
01202         {
01203         case DXGI_FORMAT_AI44:
01204         case DXGI_FORMAT_IA44:
01205         case DXGI_FORMAT_P8:
01206         case DXGI_FORMAT_A8P8:
01207             return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01208
01209         default:
01210             if ( BitsPerPixel( d3d10ext->dxgiFormat ) == 0 )
01211             {
01212                 return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01213             }
01214         }
01215
01216         format = d3d10ext->dxgiFormat;
01217
01218         switch ( d3d10ext->resourceDimension )
01219         {
01220         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
01221             // D3DX writes 1D textures with a fixed Height of 1
01222             if ((header->flags & DDS_HEIGHT) && height != 1)
01223             {
01224                 return HRESULT_FROM_WIN32( ERROR_INVALID_DATA );
01225             }
01226             height = depth = 1;
01227             break;
01228
01229         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
01230             if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE)
01231             {
01232                 arraySize *= 6;
01233                 isCubeMap = true;
01234             }
01235             depth = 1;
01236             break;
01237
01238         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
01239             if (!(header->flags & DDS_HEADER_FLAGS_VOLUME))
01240             {
01241                 return HRESULT_FROM_WIN32( ERROR_INVALID_DATA );
01242             }
01243
01244             if (arraySize > 1)
01245             {
01246                 return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01247             }
01248             break;
01249
01250         default:
01251             return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01252         }
01253
01254         resDim = d3d10ext->resourceDimension;
01255     }
01256     else
01257     {
01258         format = GetDXGIFormat( header->ddspf );
01259
01260         if (format == DXGI_FORMAT_UNKNOWN)
01261         {
01262            return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01263         }
01264
01265         if (header->flags & DDS_HEADER_FLAGS_VOLUME)
01266         {
01267             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D;
01268         }
01269         else
01270         {
01271             if (header->caps2 & DDS_CUBEMAP)
01272             {
01273                 // We require all six faces to be defined
01274                 if ((header->caps2 & DDS_CUBEMAP_ALLFACES ) != DDS_CUBEMAP_ALLFACES)
01275                 {
01276                     return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01277                 }
01278
01279                 arraySize = 6;
01280                 isCubeMap = true;
01281             }
01282
01283             depth = 1;
01284             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D;
01285
01286             // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture
01287         }
01288
01289         assert( BitsPerPixel( format ) != 0 );
01290     }
01291
01292     // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements)
01293     if (mipCount > D3D11_REQ_MIP_LEVELS)
01294     {
01295         return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01296     }
01297
01298     switch ( resDim )
01299     {
01300         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
01301             if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) ||
01302                 (width > D3D11_REQ_TEXTURE1D_U_DIMENSION) )
01303             {
01304                 return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01305             }
01306             break;
01307
01308         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
01309             if ( isCubeMap )
01310             {
01311                 // This is the right bound because we set arraySize to (NumCubes*6) above
01312                 if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01313                     (width > D3D11_REQ_TEXTURECUBE_DIMENSION) ||
01314                     (height > D3D11_REQ_TEXTURECUBE_DIMENSION))
01315                 {
01316                     return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01317                 }
01318             }
01319             else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01320                      (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) ||
01321                      (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION))
01322             {
01323                 return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01324             }
01325             break;
01326
01327         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
01328             if ((arraySize > 1) ||
01329                 (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01330                 (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01331                 (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) )
01332             {
01333                 return HRESULT_FROM_WIN32( ERROR_NOT_SUPPORTED );
01334             }
01335             break;
01336     }
01337
01338     bool autogen = false;
01339     if ( mipCount == 1 && d3dContext != 0 && textureView != 0 ) // Must have context and shader-view to auto generate mipmaps
01340     {
01341         // See if format is supported for auto-gen mipmaps (varies by feature level)
01342         UINT fmtSupport = 0;
01343         hr = d3dDevice->CheckFormatSupport( format, &fmtSupport );
01344         if ( SUCCEEDED(hr) && ( fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN ) )
01345         {
01346             // 10level9 feature levels do not support auto-gen mipgen for volume textures
01347             if ( ( resDim != D3D11_RESOURCE_DIMENSION_TEXTURE3D )
01348                  || ( d3dDevice->GetFeatureLevel() >= D3D_FEATURE_LEVEL_10_0 ) )
01349             {
01350                 autogen = true;
01351             }
01352         }
01353     }
01354
01355     if ( autogen )
01356     {
01357         // Create texture with auto-generated mipmaps
01358         ID3D11Resource* tex = nullptr;
01359         hr = CreateD3DResources( d3dDevice, resDim, width, height, depth, 0, arraySize,
01360                                  format, usage,
01361                                  bindFlags | D3D11_BIND_RENDER_TARGET,
01362                                  cpuAccessFlags,
01363                                  miscFlags | D3D11_RESOURCE_MISC_GENERATE_MIPS, forceSRGB,
01364                                  isCubeMap, nullptr, &tex, textureView );
01365         if ( SUCCEEDED(hr) )
01366         {
01367             size_t numBytes = 0;
01368             size_t rowBytes = 0;
01369             GetSurfaceInfo( width, height, format, &numBytes, &rowBytes, nullptr );
01370
01371             if ( numBytes > bitSize )
01372             {
01373                 (*textureView)->Release();
01374                 *textureView = nullptr;
01375                 tex->Release();
01376                 return HRESULT_FROM_WIN32( ERROR_HANDLE_EOF );
01377             }
01378
01379             if ( arraySize > 1 )
01380             {
01381                 D3D11_SHADER_RESOURCE_VIEW_DESC desc;
01382                 (*textureView)->GetDesc( &desc );
01383
01384                 UINT mipLevels = 1;
01385
01386                 switch( desc.ViewDimension )
01387                 {
01388                 case D3D_SRV_DIMENSION_TEXTURE1D:       mipLevels = desc.Texture1D.MipLevels; break;
01389                 case D3D_SRV_DIMENSION_TEXTURE1DARRAY:  mipLevels = desc.Texture1DArray.MipLevels; break;
01390                 case D3D_SRV_DIMENSION_TEXTURE2D:       mipLevels = desc.Texture2D.MipLevels; break;
01391                 case D3D_SRV_DIMENSION_TEXTURE2DARRAY:  mipLevels = desc.Texture2DArray.MipLevels; break;
01392                 case D3D_SRV_DIMENSION_TEXTURECUBE:     mipLevels = desc.TextureCube.MipLevels; break;
01393                 case D3D_SRV_DIMENSION_TEXTURECUBEARRAY:mipLevels = desc.TextureCubeArray.MipLevels; break;
01394                 default:
01395                     (*textureView)->Release();
01396                     *textureView = nullptr;
01397                     tex->Release();
01398                     return E_UNEXPECTED;
01399                 }
01400
01401                 const uint8_t* pSrcBits = bitData;
01402                 const uint8_t* pEndBits = bitData + bitSize;
01403                 for( UINT item = 0; item < arraySize; ++item )
01404                 {
01405                     if ( (pSrcBits + numBytes) > pEndBits )
01406                     {
01407                         (*textureView)->Release();
01408                         *textureView = nullptr;
01409                         tex->Release();
01410                         return HRESULT_FROM_WIN32( ERROR_HANDLE_EOF );
01411                     }
01412
01413                     UINT res = D3D11CalcSubresource( 0, item, mipLevels );
01414                     d3dContext->UpdateSubresource( tex, res, nullptr, pSrcBits, static_cast<UINT>(rowBytes), static_cast<UINT>(numBytes) );
01415                     pSrcBits += numBytes;
01416                 }
01417             }
01418             else
01419             {
01420                 d3dContext->UpdateSubresource( tex, 0, nullptr, bitData, static_cast<UINT>(rowBytes), static_cast<UINT>(numBytes) );
01421             }
01422
01423             d3dContext->GenerateMips( *textureView );
01424
01425             if ( texture )
01426             {
01427                 *texture = tex;
01428             }
01429             else
01430             {
01431                 tex->Release();
01432             }
01433         }
01434     }
01435     else
01436     {
01437         // Create the texture
01438         std::unique_ptr<D3D11_SUBRESOURCE_DATA[]> initData( new (std::nothrow) D3D11_SUBRESOURCE_DATA[ mipCount * arraySize ] );
01439         if ( !initData )
01440         {
01441             return E_OUTOFMEMORY;
01442         }
01443
01444         size_t skipMip = 0;
01445         size_t twidth = 0;
01446         size_t theight = 0;
01447         size_t tdepth = 0;
01448         hr = FillInitData( width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData,
01449                            twidth, theight, tdepth, skipMip, initData.get() );
01450
01451         if ( SUCCEEDED(hr) )
01452         {
01453             hr = CreateD3DResources( d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize,
01454                                      format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB,
01455                                      isCubeMap, initData.get(), texture, textureView );
01456
01457             if ( FAILED(hr) && !maxsize && (mipCount > 1) )
01458             {
01459                 // Retry with a maxsize determined by feature level
01460                 switch( d3dDevice->GetFeatureLevel() )
01461                 {
01462                 case D3D_FEATURE_LEVEL_9_1:
01463                 case D3D_FEATURE_LEVEL_9_2:
01464                     if ( isCubeMap )
01465                     {
01466                         maxsize = 512 /*D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION*/;
01467                     }
01468                     else
01469                     {
01470                         maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01471                                   ? 256 /*D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/
01472                                   : 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
01473                     }
01474                     break;
01475
01476                 case D3D_FEATURE_LEVEL_9_3:
01477                     maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01478                               ? 256 /*D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/
01479                               : 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
01480                     break;
01481
01482                 default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1
01483                     maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01484                               ? 2048 /*D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION*/
01485                               : 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
01486                     break;
01487                 }
01488
01489                 hr = FillInitData( width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData,
01490                                    twidth, theight, tdepth, skipMip, initData.get() );
01491                 if ( SUCCEEDED(hr) )
01492                 {
01493                     hr = CreateD3DResources( d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize,
01494                                              format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB,
01495                                              isCubeMap, initData.get(), texture, textureView );
01496                 }
01497             }
01498         }
01499     }
01500
01501     return hr;
01502 }
01503
01504
01505 //--------------------------------------------------------------------------------------
01506 static DDS_ALPHA_MODE GetAlphaMode( _In_ const DDS_HEADER* header )
01507 {
01508     if ( header->ddspf.flags & DDS_FOURCC )
01509     {
01510         if ( MAKEFOURCC( 'D', 'X', '1', '0' ) == header->ddspf.fourCC )
01511         {
01512             auto d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>( (const char*)header + sizeof(DDS_HEADER) );
01513             auto mode = static_cast<DDS_ALPHA_MODE>( d3d10ext->miscFlags2 & DDS_MISC_FLAGS2_ALPHA_MODE_MASK );
01514             switch( mode )
01515             {
01516             case DDS_ALPHA_MODE_STRAIGHT:
01517             case DDS_ALPHA_MODE_PREMULTIPLIED:
01518             case DDS_ALPHA_MODE_OPAQUE:
01519             case DDS_ALPHA_MODE_CUSTOM:
01520                 return mode;
01521             }
01522         }
01523         else if ( ( MAKEFOURCC( 'D', 'X', 'T', '2' ) == header->ddspf.fourCC )
01524                   || ( MAKEFOURCC( 'D', 'X', 'T', '4' ) == header->ddspf.fourCC ) )
01525         {
01526             return DDS_ALPHA_MODE_PREMULTIPLIED;
01527         }
01528     }
01529
01530     return DDS_ALPHA_MODE_UNKNOWN;
01531 }
01532
01533
01534 //--------------------------------------------------------------------------------------
01535 _Use_decl_annotations_
01536 HRESULT DirectX::CreateDDSTextureFromMemory( ID3D11Device* d3dDevice,
01537                                              const uint8_t* ddsData,
01538                                              size_t ddsDataSize,
01539                                              ID3D11Resource** texture,
01540                                              ID3D11ShaderResourceView** textureView,
01541                                              size_t maxsize,
01542                                              DDS_ALPHA_MODE* alphaMode )
01543 {
01544     return CreateDDSTextureFromMemoryEx( d3dDevice, nullptr, ddsData, ddsDataSize, maxsize,
01545                                          D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false,
01546                                          texture, textureView, alphaMode );
01547 }
01548
01549 _Use_decl_annotations_
01550 HRESULT DirectX::CreateDDSTextureFromMemory( ID3D11Device* d3dDevice,
01551                                              ID3D11DeviceContext* d3dContext,
01552                                              const uint8_t* ddsData,
01553                                              size_t ddsDataSize,
01554                                              ID3D11Resource** texture,
01555                                              ID3D11ShaderResourceView** textureView,
01556                                              size_t maxsize,
01557                                              DDS_ALPHA_MODE* alphaMode )
01558 {
01559     return CreateDDSTextureFromMemoryEx( d3dDevice, d3dContext, ddsData, ddsDataSize, maxsize,
01560                                          D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false,
01561                                          texture, textureView, alphaMode );
01562 }
01563
01564 _Use_decl_annotations_
01565 HRESULT DirectX::CreateDDSTextureFromMemoryEx( ID3D11Device* d3dDevice,
01566                                                const uint8_t* ddsData,
01567                                                size_t ddsDataSize,
01568                                                size_t maxsize,
01569                                                D3D11_USAGE usage,
01570                                                unsigned int bindFlags,
01571                                                unsigned int cpuAccessFlags,
01572                                                unsigned int miscFlags,
01573                                                bool forceSRGB,
01574                                                ID3D11Resource** texture,
01575                                                ID3D11ShaderResourceView** textureView,
01576                                                DDS_ALPHA_MODE* alphaMode )
01577 {
01578     return CreateDDSTextureFromMemoryEx( d3dDevice, nullptr, ddsData, ddsDataSize, maxsize,
01579                                          usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB,
01580                                          texture, textureView, alphaMode );
01581 }
01582
01583 _Use_decl_annotations_
01584 HRESULT DirectX::CreateDDSTextureFromMemoryEx( ID3D11Device* d3dDevice,
01585                                                ID3D11DeviceContext* d3dContext,
01586                                                const uint8_t* ddsData,
01587                                                size_t ddsDataSize,
01588                                                size_t maxsize,
01589                                                D3D11_USAGE usage,
01590                                                unsigned int bindFlags,
01591                                                unsigned int cpuAccessFlags,
01592                                                unsigned int miscFlags,
01593                                                bool forceSRGB,
01594                                                ID3D11Resource** texture,
01595                                                ID3D11ShaderResourceView** textureView,
01596                                                DDS_ALPHA_MODE* alphaMode )
01597 {
01598     if ( texture )
01599     {
01600         *texture = nullptr;
01601     }
01602     if ( textureView )
01603     {
01604         *textureView = nullptr;
01605     }
01606     if ( alphaMode )
01607     {
01608         *alphaMode = DDS_ALPHA_MODE_UNKNOWN;
01609     }
01610
01611     if (!d3dDevice || !ddsData || (!texture && !textureView))
01612     {
01613         return E_INVALIDARG;
01614     }
01615
01616     // Validate DDS file in memory
01617     if (ddsDataSize < (sizeof(uint32_t) + sizeof(DDS_HEADER)))
01618     {
01619         return E_FAIL;
01620     }
01621
01622     uint32_t dwMagicNumber = *( const uint32_t* )( ddsData );
01623     if (dwMagicNumber != DDS_MAGIC)
01624     {
01625         return E_FAIL;
01626     }
01627
01628     auto header = reinterpret_cast<const DDS_HEADER*>( ddsData + sizeof( uint32_t ) );
01629
01630     // Verify header to validate DDS file
01631     if (header->size != sizeof(DDS_HEADER) ||
01632         header->ddspf.size != sizeof(DDS_PIXELFORMAT))
01633     {
01634         return E_FAIL;
01635     }
01636
01637     // Check for DX10 extension
01638     bool bDXT10Header = false;
01639     if ((header->ddspf.flags & DDS_FOURCC) &&
01640         (MAKEFOURCC( 'D', 'X', '1', '0' ) == header->ddspf.fourCC) )
01641     {
01642         // Must be long enough for both headers and magic value
01643         if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10)))
01644         {
01645             return E_FAIL;
01646         }
01647
01648         bDXT10Header = true;
01649     }
01650
01651     ptrdiff_t offset = sizeof( uint32_t )
01652                        + sizeof( DDS_HEADER )
01653                        + (bDXT10Header ? sizeof( DDS_HEADER_DXT10 ) : 0);
01654
01655     HRESULT hr = CreateTextureFromDDS( d3dDevice, d3dContext, header,
01656                                        ddsData + offset, ddsDataSize - offset, maxsize,
01657                                        usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB,
01658                                        texture, textureView );
01659     if ( SUCCEEDED(hr) )
01660     {
01661         if (texture != 0 && *texture != 0)
01662         {
01663             SetDebugObjectName(*texture, "DDSTextureLoader");
01664         }
01665
01666         if (textureView != 0 && *textureView != 0)
01667         {
01668             SetDebugObjectName(*textureView, "DDSTextureLoader");
01669         }
01670
01671         if ( alphaMode )
01672             *alphaMode = GetAlphaMode( header );
01673     }
01674
01675     return hr;
01676 }
01677
01678 //--------------------------------------------------------------------------------------
01679 _Use_decl_annotations_
01680 HRESULT DirectX::CreateDDSTextureFromFile( ID3D11Device* d3dDevice,
01681                                            const wchar_t* fileName,
01682                                            ID3D11Resource** texture,
01683                                            ID3D11ShaderResourceView** textureView,
01684                                            size_t maxsize,
01685                                            DDS_ALPHA_MODE* alphaMode )
01686 {
01687     return CreateDDSTextureFromFileEx( d3dDevice, nullptr, fileName, maxsize,
01688                                        D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false,
01689                                        texture, textureView, alphaMode );
01690 }
01691
01692 _Use_decl_annotations_
01693 HRESULT DirectX::CreateDDSTextureFromFile( ID3D11Device* d3dDevice,
01694                                            ID3D11DeviceContext* d3dContext,
01695                                            const wchar_t* fileName,
01696                                            ID3D11Resource** texture,
01697                                            ID3D11ShaderResourceView** textureView,
01698                                            size_t maxsize,
01699                                            DDS_ALPHA_MODE* alphaMode )
01700 {
01701     return CreateDDSTextureFromFileEx( d3dDevice, d3dContext, fileName, maxsize,
01702                                        D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false,
01703                                        texture, textureView, alphaMode );
01704 }
01705
01706 _Use_decl_annotations_
01707 HRESULT DirectX::CreateDDSTextureFromFileEx( ID3D11Device* d3dDevice,
01708                                              const wchar_t* fileName,
01709                                              size_t maxsize,
01710                                              D3D11_USAGE usage,
01711                                              unsigned int bindFlags,
01712                                              unsigned int cpuAccessFlags,
01713                                              unsigned int miscFlags,
01714                                              bool forceSRGB,
01715                                              ID3D11Resource** texture,
01716                                              ID3D11ShaderResourceView** textureView,
01717                                              DDS_ALPHA_MODE* alphaMode )
01718 {
01719     return CreateDDSTextureFromFileEx( d3dDevice, nullptr, fileName, maxsize,
01720                                        usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB,
01721                                        texture, textureView, alphaMode );
01722 }
01723
01724 _Use_decl_annotations_
01725 HRESULT DirectX::CreateDDSTextureFromFileEx( ID3D11Device* d3dDevice,
01726                                              ID3D11DeviceContext* d3dContext,
01727                                              const wchar_t* fileName,
01728                                              size_t maxsize,
01729                                              D3D11_USAGE usage,
01730                                              unsigned int bindFlags,
01731                                              unsigned int cpuAccessFlags,
01732                                              unsigned int miscFlags,
01733                                              bool forceSRGB,
01734                                              ID3D11Resource** texture,
01735                                              ID3D11ShaderResourceView** textureView,
01736                                              DDS_ALPHA_MODE* alphaMode )
01737 {
01738     if ( texture )
01739     {
01740         *texture = nullptr;
01741     }
01742     if ( textureView )
01743     {
01744         *textureView = nullptr;
01745     }
01746     if ( alphaMode )
01747     {
01748         *alphaMode = DDS_ALPHA_MODE_UNKNOWN;
01749     }
01750
01751     if (!d3dDevice || !fileName || (!texture && !textureView))
01752     {
01753         return E_INVALIDARG;
01754     }
01755
01756     DDS_HEADER* header = nullptr;
01757     uint8_t* bitData = nullptr;
01758     size_t bitSize = 0;
01759
01760     std::unique_ptr<uint8_t[]> ddsData;
01761     HRESULT hr = LoadTextureDataFromFile( fileName,
01762                                           ddsData,
01763                                           &header,
01764                                           &bitData,
01765                                           &bitSize
01766                                         );
01767     if (FAILED(hr))
01768     {
01769         return hr;
01770     }
01771
01772     hr = CreateTextureFromDDS( d3dDevice, d3dContext, header,
01773                                bitData, bitSize, maxsize,
01774                                usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB,
01775                                texture, textureView );
01776
01777     if ( SUCCEEDED(hr) )
01778     {
01779 #if !defined(NO_D3D11_DEBUG_NAME) && ( defined(_DEBUG) || defined(PROFILE) )
01780         if (texture != 0 || textureView != 0)
01781         {
01782             CHAR strFileA[MAX_PATH];
01783             int result = WideCharToMultiByte( CP_ACP,
01784                                               WC_NO_BEST_FIT_CHARS,
01785                                               fileName,
01786                                               -1,
01787                                               strFileA,
01788                                               MAX_PATH,
01789                                               nullptr,
01790                                               FALSE
01791                                );
01792             if ( result > 0 )
01793             {
01794                 const CHAR* pstrName = strrchr( strFileA, '\\' );
01795                 if (!pstrName)
01796                 {
01797                     pstrName = strFileA;
01798                 }
01799                 else
01800                 {
01801                     pstrName++;
01802                 }
01803
01804                 if (texture != 0 && *texture != 0)
01805                 {
01806                     (*texture)->SetPrivateData( WKPDID_D3DDebugObjectName,
01807                                                 static_cast<UINT>( strnlen_s(pstrName, MAX_PATH) ),
01808                                                 pstrName
01809                                               );
01810                 }
01811
01812                 if (textureView != 0 && *textureView != 0 )
01813                 {
01814                     (*textureView)->SetPrivateData( WKPDID_D3DDebugObjectName,
01815                                                     static_cast<UINT>( strnlen_s(pstrName, MAX_PATH) ),
01816                                                     pstrName
01817                                                   );
01818                 }
01819             }
01820         }
01821 #endif
01822
01823         if ( alphaMode )
01824             *alphaMode = GetAlphaMode( header );
01825     }
01826
01827     return hr;
01828 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Inclinometer/cs/Scenario3_Calibration.xaml.cs Source File

  • Inclinometer
  • cs

Scenario3_Calibration.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using System;
00017 using Windows.Devices.Sensors;
00018 using Windows.Foundation;
00019 using System.Threading.Tasks;
00020 using Windows.UI.Core;
00021 using Microsoft.Samples.Devices.Sensors.Calibration;
00022
00023 namespace InclinometerCS
00024 {
00025     public sealed partial class Scenario3_Calibration : Page
00026     {
00027         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00028         // as NotifyUser()
00029         MainPage rootPage = MainPage.Current;
00030         CalibrationBar calibrationBar = new CalibrationBar();
00031
00032         public Scenario3_Calibration()
00033         {
00034             this.InitializeComponent();
00035         }
00036
00037         /// <summary>
00038         /// Invoked when this page is about to be displayed in a Frame.
00039         /// </summary>
00040         /// <param name="e">Event data that describes how this page was reached. The Parameter
00041         /// property is typically used to configure the page.</param>
00042         protected override void OnNavigatedTo(NavigationEventArgs e)
00043         {
00044         }
00045
00046         /// <summary>
00047         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00048         /// </summary>
00049         /// <param name="e">
00050         /// Event data that can be examined by overriding code. The event data is representative
00051         /// of the navigation that will unload the current Page unless canceled. The
00052         /// navigation can potentially be canceled by setting Cancel.
00053         /// </param>
00054         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00055         {
00056             calibrationBar.Hide();
00057             base.OnNavigatingFrom(e);
00058         }
00059
00060         /// <summary>
00061         /// This is the click handler for high accuracy. Acceptable accuracy met, so
00062         /// hide the calibration bar.
00063         /// </summary>
00064         /// <param name="sender"></param>
00065         /// <param name="e"></param>
00066         private void OnHighAccuracy(object sender, RoutedEventArgs e)
00067         {
00068             calibrationBar.Hide();
00069         }
00070
00071         /// <summary>
00072         /// This is the click handler for approximate accuracy. Acceptable accuracy met, so
00073         /// hide the calibration bar.
00074         /// </summary>
00075         /// <param name="sender"></param>
00076         /// <param name="e"></param>
00077         private void OnApproximateAccuracy(object sender, RoutedEventArgs e)
00078         {
00079             calibrationBar.Hide();
00080         }
00081
00082         /// <summary>
00083         /// This is the click handler for unreliable accuracy. Sensor does not meet accuracy
00084         /// requirements. Request to show the calibration bar per the calibration guidance.
00085         /// </summary>
00086         /// <param name="sender"></param>
00087         /// <param name="e"></param>
00088         private void OnUnreliableAccuracy(object sender, RoutedEventArgs e)
00089         {
00090             calibrationBar.RequestCalibration(MagnetometerAccuracy.Unreliable);
00091         }
00092     }
00093 }
Generated on Fri Nov 15 2024 22:18:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleOrientationSensor/cpp/Scenario1_DataEvents.xaml.cpp Source File

  • SimpleOrientationSensor
  • cpp

Scenario1_DataEvents.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_DataEvents.xaml.cpp
00014 // Implementation of the Scenario1_DataEvents class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario1_DataEvents.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::Devices::Sensors;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::UI::Core;
00028 using namespace Platform;
00029
00030 Scenario1_DataEvents::Scenario1_DataEvents() : rootPage(MainPage::Current)
00031 {
00032     InitializeComponent();
00033
00034     sensor = SimpleOrientationSensor::GetDefault();
00035     if (sensor == nullptr)
00036     {
00037         rootPage->NotifyUser("No simple orientation sensor found", NotifyType::ErrorMessage);
00038     }
00039 }
00040
00041 /// <summary>
00042 /// Invoked when this page is about to be displayed in a Frame.
00043 /// </summary>
00044 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00045 /// property is typically used to configure the page.</param>
00046 void Scenario1_DataEvents::OnNavigatedTo(NavigationEventArgs^ e)
00047 {
00048     ScenarioEnableButton->IsEnabled = true;
00049     ScenarioDisableButton->IsEnabled = false;
00050 }
00051
00052 /// <summary>
00053 /// Invoked when this page is no longer displayed.
00054 /// </summary>
00055 /// <param name="e"></param>
00056 void Scenario1_DataEvents::OnNavigatedFrom(NavigationEventArgs^ e)
00057 {
00058     // If the navigation is external to the app do not clean up.
00059     // This can occur on Phone when suspending the app.
00060     if (e->NavigationMode == NavigationMode::Forward && e->Uri == nullptr)
00061     {
00062         return;
00063     }
00064
00065     if (ScenarioDisableButton->IsEnabled)
00066     {
00067         Window::Current->VisibilityChanged::remove(visibilityToken);
00068         sensor->OrientationChanged::remove(orientationToken);
00069     }
00070 }
00071
00072 /// <summary>
00073 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00074 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00075 /// </summary>
00076 /// <param name="sender"></param>
00077 /// <param name="e">
00078 /// Event data that can be examined for the current visibility state.
00079 /// </param>
00080 void Scenario1_DataEvents::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00081 {
00082     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00083     if (ScenarioDisableButton->IsEnabled)
00084     {
00085         if (e->Visible)
00086         {
00087             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00088             orientationToken = sensor->OrientationChanged::add(ref new TypedEventHandler<SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^>(this, &Scenario1_DataEvents::OrientationChanged));
00089         }
00090         else
00091         {
00092             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00093             sensor->OrientationChanged::remove(orientationToken);
00094         }
00095     }
00096 }
00097
00098 void Scenario1_DataEvents::DisplayOrientation(SimpleOrientation orientation)
00099 {
00100     switch (orientation)
00101     {
00102         case SimpleOrientation::NotRotated:
00103             ScenarioOutput_Orientation->Text = "Not Rotated";
00104             break;
00105         case SimpleOrientation::Rotated90DegreesCounterclockwise:
00106             ScenarioOutput_Orientation->Text = "Rotated 90 Degrees Counterclockwise";
00107             break;
00108         case SimpleOrientation::Rotated180DegreesCounterclockwise:
00109             ScenarioOutput_Orientation->Text = "Rotated 180 Degrees Counterclockwise";
00110             break;
00111         case SimpleOrientation::Rotated270DegreesCounterclockwise:
00112             ScenarioOutput_Orientation->Text = "Rotated 270 Degrees Counterclockwise";
00113             break;
00114         case SimpleOrientation::Faceup:
00115             ScenarioOutput_Orientation->Text = "Faceup";
00116             break;
00117         case SimpleOrientation::Facedown:
00118             ScenarioOutput_Orientation->Text = "Facedown";
00119             break;
00120         default:
00121             ScenarioOutput_Orientation->Text = "Unknown orientation";
00122             break;
00123     }
00124 }
00125
00126 void Scenario1_DataEvents::OrientationChanged(SimpleOrientationSensor^ sender, SimpleOrientationSensorOrientationChangedEventArgs^ e)
00127 {
00128     // We need to dispatch to the UI thread to display the output
00129     Dispatcher->RunAsync(
00130         CoreDispatcherPriority::Normal,
00131         ref new DispatchedHandler(
00132             [this, e]()
00133             {
00134                 DisplayOrientation(e->Orientation);
00135             },
00136             CallbackContext::Any
00137             )
00138         );
00139 }
00140
00141 void Scenario1_DataEvents::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00142 {
00143     if (sensor != nullptr)
00144     {
00145         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario1_DataEvents::VisibilityChanged));
00146         orientationToken = sensor->OrientationChanged::add(ref new TypedEventHandler<SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^>(this, &Scenario1_DataEvents::OrientationChanged));
00147
00148         // Display the current orientation once while waiting for the next orientation change
00149         DisplayOrientation(sensor->GetCurrentOrientation());
00150
00151         ScenarioEnableButton->IsEnabled = false;
00152         ScenarioDisableButton->IsEnabled = true;
00153     }
00154     else
00155     {
00156         rootPage->NotifyUser("No simple orientation sensor found", NotifyType::ErrorMessage);
00157     }
00158 }
00159
00160 void Scenario1_DataEvents::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00161 {
00162     Window::Current->VisibilityChanged::remove(visibilityToken);
00163     sensor->OrientationChanged::remove(orientationToken);
00164
00165     ScenarioEnableButton->IsEnabled = true;
00166     ScenarioDisableButton->IsEnabled = false;
00167 }
Generated on Fri Nov 15 2024 22:17:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlFocusVisuals/cs/Scenarios/CustomControlUsage.xaml.cs Source File

  • XamlFocusVisuals
  • cs
  • Scenarios

CustomControlUsage.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013
00014 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00015
00016 namespace FocusVisualsSample
00017 {
00018     /// <summary>
00019     /// An empty page that can be used on its own or navigated to within a Frame.
00020     /// </summary>
00021     public sealed partial class CustomControlUsage : Page
00022     {
00023         public CustomControlUsage()
00024         {
00025             this.InitializeComponent();
00026         }
00027     }
00028 }
Generated on Fri Nov 15 2024 22:22:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Stats Member List

This is the complete list of members for Scenario2_Stats, including all inherited members.
ReportCalendarData(Calendar calendar, string calendarLabel) | Scenario2_Stats | [inline, private]
Scenario2_Stats() | Scenario2_Stats | [inline]
ShowResults_Click(object sender, RoutedEventArgs e) | Scenario2_Stats | [inline, private]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ShareCustomProvider Member List

This is the complete list of members for ShareCustomProvider, including all inherited members.
dataTransferManager | ShareCustomProvider | [private]
GetShareContent(DataRequest request) | ShareCustomProvider | [inline, protected]
OnNavigatedFrom(NavigationEventArgs e) | ShareCustomProvider | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | ShareCustomProvider | [inline, protected]
OnShareProvidersRequested(DataTransferManager s, ShareProvidersRequestedEventArgs e) | ShareCustomProvider | [inline, private]
OnShareToContosoChat(ShareProviderOperation operation) | ShareCustomProvider | [inline, private]
ShareCustomProvider() | ShareCustomProvider | [inline]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1 Member List

This is the complete list of members for Scenario1, including all inherited members.
CreateFileButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1 |
CreateView_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1 |
DoWin10Mode(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &args) | Scenario1 |
DoWin81Mode(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &args) | Scenario1 |
Enumerate_Click(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1 |
GenerateSizePreferenceBinding() | Scenario1 | [private, static]
GetFilesAndFoldersButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1 |
GetThumbnailButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1 |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1 |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario1 |
Scenario1() | Scenario1 |
Scenario1() | Scenario1 |
Scenario1() | Scenario1 |
Scenario1() | Scenario1 |
Scenario1() | Scenario1 |
Scenario1() | Scenario1 |
Scenario1() | Scenario1 |
SearchButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1 |
ShowAsStandalone_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1 |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactCards/cpp/SampleConfiguration.cpp Source File

  • ContactCards
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017 using namespace Windows::ApplicationModel::Contacts;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021
00022 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00023 {
00024     { "Show mini contact card", "SDKTemplate.Scenario1_Mini" },
00025     { "Show mini contact card with delayed information", "SDKTemplate.Scenario2_DelayMini" },
00026     { "Show full contact card", "SDKTemplate.Scenario3_Full" },
00027
00028 };
00029
00030 Contact^ MainPage::CreateContactFromUserInput(TextBox^ EmailAddress, TextBox^ PhoneNumber)
00031 {
00032     if (EmailAddress->Text->Length() == 0 && PhoneNumber->Text->Length() == 0)
00033     {
00034         NotifyUser("You must enter an email address and/or phone number.", NotifyType::ErrorMessage);
00035         return nullptr;
00036     }
00037
00038     Contact^ contact = ref new Contact();
00039
00040     // Maximum length for email address is 321, enforced by XAML markup.
00041     if (EmailAddress->Text->Length() > 0)
00042     {
00043         ContactEmail^ email = ref new ContactEmail();
00044         email->Address = EmailAddress->Text;
00045         contact->Emails->Append(email);
00046     }
00047
00048     // Maximum length for phone number is 50, enforced by XAML markup.
00049     if (PhoneNumber->Text->Length() > 0)
00050     {
00051         ContactPhone^ phone = ref new ContactPhone();
00052         phone->Number = PhoneNumber->Text;
00053         contact->Phones->Append(phone);
00054     }
00055
00056     return contact;
00057 }
00058
00059 Rect MainPage::GetElementRect(FrameworkElement^ element)
00060 {
00061     Windows::UI::Xaml::Media::GeneralTransform^ buttonTransform = element->TransformToVisual(nullptr);
00062     Point point = buttonTransform->TransformPoint(Point());
00063     return Rect(point, Size(static_cast<float>(element->ActualWidth), static_cast<float>(element->ActualHeight)));
00064 }
Generated on Fri Nov 15 2024 22:17:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ProtectionSelectorChoices Member List

This is the complete list of members for ProtectionSelectorChoices, including all inherited members.
Selectors() ProtectionSelectorChoices [static]
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MessageDialog/cpp/CancelCommand.xaml.cpp Source File

  • MessageDialog
  • cpp

CancelCommand.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // CancelCommand.xaml.cpp
00013 // Implementation of the CancelCommand class
00014 //
00015
00016 #include "pch.h"
00017 #include "CancelCommand.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace Windows::UI::Popups;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 CancelCommand::CancelCommand()
00027 {
00028     InitializeComponent();
00029 }
00030
00031 void CancelCommand::OnNavigatedTo(NavigationEventArgs^ e)
00032 {
00033     rootPage = MainPage::Current;
00034 }
00035
00036 /// <summary>
00037 /// Click handler for the 'CancelCommandButton' button.
00038 /// Demonstrates setting the command to be invoked when the 'escape' key is pressed.
00039 /// Also demonstrates retrieval of the label of the chosen command and setting a callback to a function.
00040 /// A message will be displayed indicating which command was invoked.
00041 /// In this scenario, 'Try again' is selected as the default choice, and the 'escape' key will invoke the command named 'Close'
00042 /// </summary>
00043 /// <param name="sender">The Object that caused this event to be fired.</param>
00044 /// <param name="e">State information and event data associated with the routed event.</param>
00045 void CancelCommand::CancelCommandButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     // Create the message dialog and set its content
00048     MessageDialog^ msg = ref new MessageDialog("No internet connection has been found.");
00049
00050     // Add commands and set their callbacks; both commands use the same callback function instead of inline event handlers
00051     UICommand^ continueCommand = ref new UICommand("Try again", ref new UICommandInvokedHandler(this, &CancelCommand::CommandInvokedHandler));
00052     UICommand^ upgradeCommand = ref new UICommand("Close", ref new UICommandInvokedHandler(this, &CancelCommand::CommandInvokedHandler));
00053
00054     // Add the commands to the dialog
00055     msg->Commands->Append(continueCommand);
00056     msg->Commands->Append(upgradeCommand);
00057
00058     // Set the command that will be invoked by default
00059     msg->DefaultCommandIndex = 0;
00060
00061     // Set the command to be invoked when escape is pressed
00062     msg->CancelCommandIndex = 1;
00063
00064     // Show the message dialog
00065     msg->ShowAsync();
00066 }
00067
00068 /// <summary>
00069 /// Callback function for the invocation of the dialog commands.
00070 /// </summary>
00071 /// <param name="command">The command that was invoked.</param>
00072 void CancelCommand::CommandInvokedHandler(Windows::UI::Popups::IUICommand^ command)
00073 {
00074     // Display message
00075     rootPage->NotifyUser("The '" + command->Label + "' command has been selected.", NotifyType::StatusMessage);
00076 }
Generated on Fri Nov 15 2024 22:20:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Gyrometer/cpp/pch.cpp Source File

  • Gyrometer
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cpp/SampleConfiguration.h Source File

  • Accelerometer
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Accelerometer C# Sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038         static void SetReadingText(Windows::UI::Xaml::Controls::TextBlock^ textBlock, Windows::Devices::Sensors::AccelerometerReading^ reading);
00039
00040         property Windows::Devices::Sensors::AccelerometerReadingType AccelerometerReadingType
00041         {
00042             Windows::Devices::Sensors::AccelerometerReadingType get()
00043             {
00044                 return accelerometerReadingType;
00045             }
00046             void set(Windows::Devices::Sensors::AccelerometerReadingType value)
00047             {
00048                 accelerometerReadingType = value;
00049             }
00050         }
00051
00052     private:
00053         static Platform::Array<Scenario>^ scenariosInner;
00054         Windows::Devices::Sensors::AccelerometerReadingType accelerometerReadingType = Windows::Devices::Sensors::AccelerometerReadingType::Standard;
00055     };
00056
00057     public value struct Scenario
00058     {
00059         Platform::String^ Title;
00060         Platform::String^ ClassName;
00061     };
00062 }
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdaptiveStreaming/cs/SampleConfiguration.cs Source File

  • AdaptiveStreaming
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate.Models;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Linq;
00016 using Windows.ApplicationModel.DataTransfer;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml.Controls;
00019
00020 namespace SDKTemplate
00021 {
00022     public partial class MainPage : Page
00023     {
00024         public const string FEATURE_NAME = "AdaptiveStreaming";
00025
00026         List<Scenario> scenarios = new List<Scenario>
00027         {
00028             new Scenario() { Title="Simplest Adaptive Streaming", ClassType=typeof(Scenario1_SimplestAdaptiveStreaming)},
00029             new Scenario() { Title="Event Handlers", ClassType=typeof(Scenario2_EventHandlers)},
00030             new Scenario() { Title="Network Request Modification", ClassType=typeof(Scenario3_RequestModification)},
00031             new Scenario() { Title="Adaptive Streaming Tuning", ClassType=typeof(Scenario4_Tuning)},
00032             new Scenario() { Title="Metadata", ClassType=typeof(Scenario5_Metadata)},
00033             new Scenario() { Title="Ad Insertion", ClassType=typeof(Scenario6_AdInsertion)},
00034             new Scenario() { Title="Live Seekable Range", ClassType=typeof(Scenario7_LiveSeekableRange)},
00035         };
00036
00037         public static IReadOnlyList<AdaptiveContentModel> ContentManagementSystemStub = AdaptiveContentModel.GetKnownAzureMediaServicesModels();
00038         public static AdaptiveContentModel FindContentById(int id)
00039         {
00040             return ContentManagementSystemStub.First(model => model.Id == id);
00041         }
00042     }
00043
00044     public class Scenario
00045     {
00046         public string Title { get; set; }
00047         public Type ClassType { get; set; }
00048     }
00049
00050     public class BitrateHelper
00051     {
00052         // Each bitrate is assigned a symbol as follows:
00053         // The bottom quartile gets 1 bar, the second quartile gets 2 bars,
00054         // the third quartile gets 3 bars, and the top quartile gets 4 bars.
00055         private Dictionary<uint, Symbol> symbolAssignment = new Dictionary<uint, Symbol>();
00056
00057         public BitrateHelper(IEnumerable<uint> availableBitRates)
00058         {
00059             uint[] sortedBitRates = availableBitRates.ToArray();
00060             Array.Sort(sortedBitRates);
00061             int i = 0;
00062             while (i < sortedBitRates.Length * 1 / 4)
00063             {
00064                 symbolAssignment.Add(sortedBitRates[i++], Symbol.OneBar);
00065             }
00066             while (i < sortedBitRates.Length * 2 / 4)
00067             {
00068                 symbolAssignment.Add(sortedBitRates[i++], Symbol.TwoBars);
00069             }
00070             while (i < sortedBitRates.Length * 3 / 4)
00071             {
00072                 symbolAssignment.Add(sortedBitRates[i++], Symbol.ThreeBars);
00073             }
00074             while (i < sortedBitRates.Length * 4 / 4)
00075             {
00076                 symbolAssignment.Add(sortedBitRates[i++], Symbol.FourBars);
00077             }
00078         }
00079
00080         public Symbol GetBitrateSymbol(uint currentBitrate)
00081         {
00082             Symbol symbol = Symbol.ZeroBars;
00083             if (symbolAssignment.TryGetValue(currentBitrate, out symbol))
00084             {
00085                 return symbol;
00086             }
00087             return Symbol.ZeroBars;
00088         }
00089     }
00090 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MagneticStripeReader/cpp/SampleConfiguration.cpp Source File

  • MagneticStripeReader
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015 #include "DeviceHelpers.h"
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace SDKTemplate;
00020 using namespace Windows::Devices::PointOfService;
00021 using namespace Windows::Foundation;
00022
00023 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00024 {
00025     { "BankCardDataReceived Event", "SDKTemplate.Scenario1_BankCards" },
00026     { "AamvaCardDataReceived Event", "SDKTemplate.Scenario2_AamvaCards" }
00027 };
00028
00029 task<MagneticStripeReader^> DeviceHelpers::GetFirstMagneticStripeReaderAsync(PosConnectionTypes connectionTypes)
00030 {
00031     return DeviceHelpers::GetFirstDeviceAsync(MagneticStripeReader::GetDeviceSelector(connectionTypes),
00032         [](String^ id) { return create_task(MagneticStripeReader::FromIdAsync(id)); });
00033 }
Generated on Fri Nov 15 2024 22:17:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SplashScreen/cs/MainPage.xaml.cs Source File

  • SplashScreen
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate.Common;
00013
00014 using System;
00015 using System.Collections.Generic;
00016 using System.IO;
00017 using System.Linq;
00018 using System.Runtime.InteropServices.WindowsRuntime;
00019 using Windows.Foundation;
00020 using Windows.Foundation.Collections;
00021 using Windows.UI.ApplicationSettings;
00022 using Windows.UI.Popups;
00023 using Windows.UI.Xaml;
00024 using Windows.UI.Xaml.Controls;
00025 using Windows.UI.Xaml.Controls.Primitives;
00026 using Windows.UI.Xaml.Data;
00027 using Windows.UI.Xaml.Input;
00028 using Windows.UI.Xaml.Media;
00029 using Windows.UI.Xaml.Navigation;
00030 using Windows.UI.Core;
00031
00032 namespace SDKTemplate
00033 {
00034     /// <summary>
00035     /// An empty page that can be used on its own or navigated to within a Frame.
00036     /// </summary>
00037     public sealed partial class MainPage : Page
00038     {
00039         public static MainPage Current;
00040         public string LaunchParam { get; set; }
00041         partial void GetScenarioIdForLaunch(string launchParam, ref int index);
00042
00043         public MainPage()
00044         {
00045             this.InitializeComponent();
00046             SampleTitle.Text = FEATURE_NAME;
00047
00048             // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00049             // in order to call methods that are in this class.
00050             Current = this;
00051         }
00052
00053         protected override void OnNavigatedTo(NavigationEventArgs e)
00054         {
00055             // Populate the scenario list from the SampleConfiguration.cs file
00056             ScenarioControl.ItemsSource = scenarios;
00057
00058             // If we have saved state return to the previously selected scenario
00059             if (SuspensionManager.SessionState.ContainsKey("SelectedScenarioIndex") && String.IsNullOrEmpty(e.Parameter.ToString()))
00060             {
00061                 ScenarioControl.SelectedIndex = Convert.ToInt32(SuspensionManager.SessionState["SelectedScenarioIndex"]);
00062                 ScenarioControl.ScrollIntoView(ScenarioControl.SelectedItem);
00063             }
00064             else if (e.Parameter != null && !String.IsNullOrEmpty(e.Parameter.ToString()))
00065             {
00066                 this.LaunchParam = e.Parameter.ToString();
00067                 int index = 0;
00068                 this.GetScenarioIdForLaunch(this.LaunchParam, ref index);
00069                 ScenarioControl.SelectedIndex = index;
00070             }
00071         }
00072
00073         /// <summary>
00074         /// Called whenever the user changes selection in the scenarios list. This method will navigate to the respective
00075         /// sample scenario page.
00076         /// </summary>
00077         /// <param name="sender"></param>
00078         /// <param name="e"></param>
00079         private void ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
00080         {
00081             // Clear the status block when navigating scenarios.
00082             NotifyUser(String.Empty, NotifyType.StatusMessage);
00083
00084             ListBox scenarioListBox = sender as ListBox;
00085             Scenario s = scenarioListBox.SelectedItem as Scenario;
00086             if (s != null)
00087             {
00088                 SuspensionManager.SessionState["SelectedScenarioIndex"] = scenarioListBox.SelectedIndex;
00089                 ScenarioFrame.Navigate(s.ClassType);
00090             }
00091         }
00092
00093         /// <summary>
00094         /// List of Scenarios will be included in this page.
00095         /// </summary>
00096         public List<Scenario> Scenarios
00097         {
00098             get { return this.scenarios; }
00099         }
00100
00101         /// <summary>
00102         /// Used to display messages to the user
00103         /// </summary>
00104         /// <param name="strMessage"></param>
00105         /// <param name="type"></param>
00106         public void NotifyUser(string strMessage, NotifyType type)
00107         {
00108             switch (type)
00109             {
00110                 case NotifyType.StatusMessage:
00111                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green);
00112                     break;
00113                 case NotifyType.ErrorMessage:
00114                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red);
00115                     break;
00116             }
00117             StatusBlock.Text = strMessage;
00118
00119             // Collapse the StatusBlock if it has no text to conserve real estate.
00120             if (StatusBlock.Text != String.Empty)
00121             {
00122                 StatusBorder.Visibility = Windows.UI.Xaml.Visibility.Visible;
00123             }
00124             else
00125             {
00126                 StatusBorder.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00127             }
00128         }
00129
00130         async void Footer_Click(object sender, RoutedEventArgs e)
00131         {
00132             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00133         }
00134
00135         private void Button_Click(object sender, RoutedEventArgs e)
00136         {
00137             Splitter.IsPaneOpen = (Splitter.IsPaneOpen == true) ? false : true;
00138             StatusBorder.Visibility = Visibility.Collapsed;
00139         }
00140
00141     }
00142
00143     public class ScenarioBindingConverter : IValueConverter
00144     {
00145         public object Convert(object value, Type targetType, object parameter, string language)
00146         {
00147             Scenario s = value as Scenario;
00148             return (MainPage.Current.Scenarios.IndexOf(s) + 1) + ") " + s.Title;
00149         }
00150
00151         public object ConvertBack(object value, Type targetType, object parameter, string language)
00152         {
00153             return true;
00154         }
00155     }
00156 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cpp/Scenario4_TimeTriggeredTask.xaml.cpp Source File

  • BackgroundActivation
  • cpp

Scenario4_TimeTriggeredTask.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario4_TimeTriggeredTask.xaml.cpp
00013 // Implementation of the TimeTriggeredTask class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario4_TimeTriggeredTask.xaml.h"
00018 #include "SampleConfiguration.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::ApplicationModel::Background;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 TimeTriggeredTask::TimeTriggeredTask()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Invoked when this page is about to be displayed in a Frame.
00035 /// </summary>
00036 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037 /// property is typically used to configure the page.</param>
00038 void TimeTriggeredTask::OnNavigatedTo(NavigationEventArgs^ e)
00039 {
00040     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00041     // as NotifyUser()
00042     rootPage = MainPage::Current;
00043
00044     //
00045     // Attach progress and completed handlers to any existing tasks.
00046     //
00047     for (auto pair : BackgroundTaskRegistration::AllTasks)
00048     {
00049         auto task = pair->Value;
00050         if (task->Name == TimeTriggeredTaskName)
00051         {
00052             BackgroundTaskSample::UpdateBackgroundTaskRegistrationStatus(task->Name, true);
00053             AttachProgressAndCompletedHandlers(task);
00054             break;
00055         }
00056     }
00057
00058     UpdateUI();
00059 }
00060
00061 /// <summary>
00062 /// Attach progress and completed handers to a background task.
00063 /// </summary>
00064 /// <param name="task">The task to attach progress and completed handlers to.</param>
00065 void TimeTriggeredTask::AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration^ task)
00066 {
00067     task->Progress += ref new BackgroundTaskProgressEventHandler(this, &TimeTriggeredTask::OnProgress);
00068     task->Completed += ref new BackgroundTaskCompletedEventHandler(this, &TimeTriggeredTask::OnCompleted);
00069 }
00070
00071 /// <summary>
00072 /// Register a TimeTriggeredTask.
00073 /// </summary>
00074 /// <param name="sender"></param>
00075 /// <param name="e"></param>
00076 void TimeTriggeredTask::RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00077 {
00078     auto task = BackgroundTaskSample::RegisterBackgroundTask(nullptr,
00079                                                              TimeTriggeredTaskName,
00080                                                              ref new TimeTrigger(15, false),
00081                                                              nullptr);
00082     AttachProgressAndCompletedHandlers(task);
00083     UpdateUI();
00084 }
00085
00086 /// <summary>
00087 /// Unregister a TimeTriggeredTask.
00088 /// </summary>
00089 /// <param name="sender"></param>
00090 /// <param name="e"></param>
00091 void TimeTriggeredTask::UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00092 {
00093     BackgroundTaskSample::UnregisterBackgroundTasks(TimeTriggeredTaskName);
00094     UpdateUI();
00095 }
00096
00097 /// <summary>
00098 /// Handle background task progress.
00099 /// </summary>
00100 /// <param name="task">The task that is reporting progress.</param>
00101 /// <param name="args">Arguments of the progress report.</param>
00102 void TimeTriggeredTask::OnProgress(BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
00103 {
00104     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00105     {
00106         auto progress = "Progress: " + args->Progress + "%";
00107         BackgroundTaskSample::TimeTriggeredTaskProgress = progress;
00108         UpdateUI();
00109     }));
00110 }
00111
00112 /// <summary>
00113 /// Handle background task completion.
00114 /// </summary>
00115 /// <param name="task">The task that is reporting completion.</param>
00116 /// <param name="args">Arguments of the completion report.</param>
00117 void TimeTriggeredTask::OnCompleted(BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
00118 {
00119     UpdateUI();
00120 }
00121
00122 /// <summary>
00123 /// Update the scenario UI.
00124 /// </summary>
00125 void TimeTriggeredTask::UpdateUI()
00126 {
00127     auto uiDelegate = [this]()
00128     {
00129         RegisterButton->IsEnabled = !BackgroundTaskSample::TimeTriggeredTaskRegistered;
00130         UnregisterButton->IsEnabled = BackgroundTaskSample::TimeTriggeredTaskRegistered;
00131         Progress->Text = BackgroundTaskSample::TimeTriggeredTaskProgress;
00132         Status->Text = BackgroundTaskSample::GetBackgroundTaskStatus(TimeTriggeredTaskName);
00133     };
00134     auto handler = ref new Windows::UI::Core::DispatchedHandler(uiDelegate, Platform::CallbackContext::Any);
00135
00136     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, handler);
00137 }
Generated on Fri Nov 15 2024 22:18:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cppwinrt/pch.cpp Source File

  • PenHaptics
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboardTextInput/cpp/SampleConfiguration.h Source File

  • TouchKeyboardTextInput
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Touch Keyboard text input";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/shared/TypeConversionHelpers.cpp Source File

  • AllJoyn
  • shared

TypeConversionHelpers.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #include "pch.h"
00022
00023 _Check_return_ int32 TypeConversionHelpers::AppendNextCompleteType(_In_ PCSTR signature, _Inout_ std::vector<char>* typeSignature)
00024 {
00025     if (signature[0] == '\0')
00026     {
00027         return ER_BUS_BAD_SIGNATURE;
00028     }
00029
00030     typeSignature->push_back(signature[0]);
00031     if ((signature[0] == '(') || (signature[0] == '{'))
00032     {
00033         char openingParenthesis = signature[0];
00034         char closingParenthesis = signature[0] == '(' ? ')' : '}';
00035         // Find the matching closing parenthesis.
00036         int openParenthesisCount = 1;
00037         int index = 1;
00038         while (openParenthesisCount > 0)
00039         {
00040             if ('\0' == signature[index])
00041             {
00042                 return ER_BUS_BAD_SIGNATURE;
00043             }
00044
00045             typeSignature->push_back(signature[index]);
00046             if (openingParenthesis == signature[index])
00047             {
00048                 openParenthesisCount++;
00049             }
00050             else if (closingParenthesis == signature[index])
00051             {
00052                 openParenthesisCount--;
00053             }
00054             index++;
00055         }
00056         return S_OK;
00057     }
00058     else if (signature[0] == 'a')
00059     {
00060         return AppendNextCompleteType(signature + 1, typeSignature);
00061     }
00062     else
00063     {
00064         return S_OK;
00065     }
00066 }
00067
00068 _Check_return_ int32 TypeConversionHelpers::GetDictionaryTypeSignatures(_In_ PCSTR signature, _Inout_ std::vector<char>* keySignature, _Inout_ std::vector<char>* valueSignature)
00069 {
00070     if ((strlen(signature) < 3) || (signature[0] != 'a') || (signature[1] != '{'))
00071     {
00072         return ER_BUS_BAD_SIGNATURE;
00073     }
00074
00075     // Skip past the opening "a{".
00076     signature += 2;
00077     RETURN_IF_QSTATUS_ERROR(AppendNextCompleteType(signature, keySignature));
00078     signature += keySignature->size();
00079     RETURN_IF_QSTATUS_ERROR(AppendNextCompleteType(signature, valueSignature));
00080     keySignature->push_back('\0');
00081     valueSignature->push_back('\0');
00082     return ER_OK;
00083 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/Audio/Silent/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • Audio
  • Silent

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Xaml.Controls;
00002
00003 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00004
00005 namespace Notifications.ScenarioPages.Toasts.Audio.Silent
00006 {
00007     /// <summary>
00008     /// An empty page that can be used on its own or navigated to within a Frame.
00009     /// </summary>
00010     public sealed partial class ScenarioElement : UserControl
00011     {
00012         public ScenarioElement()
00013         {
00014             this.InitializeComponent();
00015
00016             Initialize();
00017         }
00018
00019         private void Initialize()
00020         {
00021             // Specify the toast payload
00022             popToastControl.Payload =
00023 $@"<toast>
00024     <visual>
00025         <binding template='ToastGeneric'>
00026             <text>Silent Toast</text>
00027             <text>This toast's audio is set to silent.</text>
00028         </binding>
00029     </visual>
00030
00031     <audio silent='true'/>
00032
00033 </toast>";
00034         }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:20:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAuthenticationBroker/cpp/Scenario2_oAuthFacebook.xaml.cpp Source File

  • WebAuthenticationBroker
  • cpp

Scenario2_oAuthFacebook.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario2_oAuthFacebook.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Concurrency;
00009 using namespace Platform;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::Security::Authentication::Web;
00013 using namespace Windows::ApplicationModel::Activation;
00014 using namespace Windows::UI::Xaml;
00015 using namespace Windows::UI::Xaml::Controls;
00016 using namespace Windows::UI::Xaml::Controls::Primitives;
00017 using namespace Windows::UI::Xaml::Data;
00018 using namespace Windows::UI::Xaml::Input;
00019 using namespace Windows::UI::Xaml::Media;
00020 using namespace Windows::UI::Xaml::Navigation;
00021
00022 Scenario2_oAuthFacebook::Scenario2_oAuthFacebook()
00023 {
00024     InitializeComponent();
00025
00026     // Use these SIDs to register the app with Facebook.
00027     WindowsStoreSidTextBlock->Text = WebAuthenticationBroker::GetCurrentApplicationCallbackUri()->Host;
00028     WindowsPhoneStoreSidTextBlock->Text = "f48e0417-873f-476c-97a2-2d25c5fa2dc7"; // copied from Package.appxmanifest
00029 }
00030
00031 void Scenario2_oAuthFacebook::Launch_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00032 {
00033     FacebookReturnedToken->Text = "";
00034
00035     String^ facebookURL = "https://www.facebook.com/dialog/oauth?client_id=";
00036
00037     auto clientID = FacebookClientID->Text;
00038     if (clientID->IsEmpty())
00039     {
00040         MainPage::Current->NotifyUser("Enter a ClientID", NotifyType::ErrorMessage);
00041         return;
00042     }
00043     if(FacebookCallbackUrl->Text->IsEmpty())
00044     {
00045         MainPage::Current->NotifyUser("Enter a Callback URL", NotifyType::ErrorMessage);
00046         return;
00047     }
00048
00049     facebookURL += clientID + "&redirect_uri=" + Uri::EscapeComponent(FacebookCallbackUrl->Text) + "&scope=email&display=popup&response_type=token";
00050
00051     try
00052     {
00053         auto facebookToken = FacebookReturnedToken;
00054
00055         auto startURI = ref new Uri(facebookURL);
00056         auto endURI = ref new Uri(FacebookCallbackUrl->Text);
00057         MainPage::Current->NotifyUser("Navigating to: " + facebookURL + "\n", NotifyType::StatusMessage);
00058
00059         create_task(WebAuthenticationBroker::AuthenticateAsync(WebAuthenticationOptions::None, startURI, endURI)).then([this](WebAuthenticationResult^ result)
00060         {
00061             String^ statusString;
00062             switch (result->ResponseStatus)
00063             {
00064             case WebAuthenticationStatus::ErrorHttp:
00065                 statusString = "ErrorHttp: " + result->ResponseErrorDetail;
00066                 break;
00067             case WebAuthenticationStatus::Success:
00068                 statusString = "Success";
00069                 FacebookReturnedToken->Text += result->ResponseData;
00070                 break;
00071             case WebAuthenticationStatus::UserCancel:
00072                 statusString = "UserCancel";
00073                 break;
00074             }
00075
00076             MainPage::Current->NotifyUser("Status returned by WebAuth broker: " + statusString, NotifyType::StatusMessage);
00077
00078         });
00079     }
00080     catch (Exception^ ex)
00081     {
00082         MainPage::Current->NotifyUser("Error launching WebAuth " + ex->Message, NotifyType::ErrorMessage);
00083         return;
00084     }
00085 }
Generated on Fri Nov 15 2024 22:21:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario6.xaml.cpp Source File

  • MapControl
  • cpp

Scenario6.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario6.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::System;
00019 using namespace Windows::UI::Xaml;
00020
00021 Scenario6::Scenario6()
00022 {
00023     InitializeComponent();
00024 }
00025
00026 void Scenario6::pfnLink_Click(Object^ sender, RoutedEventArgs^ e)
00027 {
00028     Windows::Foundation::Uri^ uri = ref new Windows::Foundation::Uri("bingmaps:?rtp=adr.Mountain%20View,%20CA~adr.San%20Francisco,%20CA&amp;mode=d&amp;trfc=1");
00029     LauncherOptions^ launcherOptions = ref new LauncherOptions();
00030     launcherOptions->TargetApplicationPackageFamilyName = "Microsoft.WindowsMaps_8wekyb3d8bbwe";
00031     Launcher::LaunchUriAsync(uri, launcherOptions);
00032 }
00033
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCustomMediaTransportControls/cs/App.xaml.cs Source File

  • XamlCustomMediaTransportControls
  • cs

App.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.IO;
00004 using System.Linq;
00005 using System.Runtime.InteropServices.WindowsRuntime;
00006 using Windows.ApplicationModel;
00007 using Windows.ApplicationModel.Activation;
00008 using Windows.Foundation;
00009 using Windows.Foundation.Collections;
00010 using Windows.UI.Xaml;
00011 using Windows.UI.Xaml.Controls;
00012 using Windows.UI.Xaml.Controls.Primitives;
00013 using Windows.UI.Xaml.Data;
00014 using Windows.UI.Xaml.Input;
00015 using Windows.UI.Xaml.Media;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
00019
00020 namespace CustomMediaTransportControls
00021 {
00022     /// <summary>
00023     /// Provides application-specific behavior to supplement the default Application class.
00024     /// </summary>
00025     sealed partial class App : Application
00026     {
00027         /// <summary>
00028         /// Allows tracking page views, exceptions and other telemetry through the Microsoft Application Insights service.
00029         /// </summary>
00030
00031         /// <summary>
00032         /// Initializes the singleton application object.  This is the first line of authored code
00033         /// executed, and as such is the logical equivalent of main() or WinMain().
00034         /// </summary>
00035         public App()
00036         {
00037
00038             this.InitializeComponent();
00039             this.Suspending += OnSuspending;
00040         }
00041
00042         /// <summary>
00043         /// Invoked when the application is launched normally by the end user.  Other entry points
00044         /// will be used such as when the application is launched to open a specific file.
00045         /// </summary>
00046         /// <param name="e">Details about the launch request and process.</param>
00047         protected override void OnLaunched(LaunchActivatedEventArgs e)
00048         {
00049
00050 #if DEBUG
00051             if (System.Diagnostics.Debugger.IsAttached)
00052             {
00053                 this.DebugSettings.EnableFrameRateCounter = false;
00054             }
00055 #endif
00056
00057             Frame rootFrame = Window.Current.Content as Frame;
00058
00059             // Do not repeat app initialization when the Window already has content,
00060             // just ensure that the window is active
00061             if (rootFrame == null)
00062             {
00063                 // Create a Frame to act as the navigation context and navigate to the first page
00064                 rootFrame = new Frame();
00065
00066                 rootFrame.NavigationFailed += OnNavigationFailed;
00067
00068                 if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
00069                 {
00070                     //TODO: Load state from previously suspended application
00071                 }
00072
00073                 // Place the frame in the current Window
00074                 Window.Current.Content = rootFrame;
00075             }
00076
00077             if (rootFrame.Content == null)
00078             {
00079                 // When the navigation stack isn't restored navigate to the first page,
00080                 // configuring the new page by passing required information as a navigation
00081                 // parameter
00082                 rootFrame.Navigate(typeof(MainPage), e.Arguments);
00083             }
00084             // Ensure the current window is active
00085             Window.Current.Activate();
00086         }
00087
00088         /// <summary>
00089         /// Invoked when Navigation to a certain page fails
00090         /// </summary>
00091         /// <param name="sender">The Frame which failed navigation</param>
00092         /// <param name="e">Details about the navigation failure</param>
00093         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00094         {
00095             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00096         }
00097
00098         /// <summary>
00099         /// Invoked when application execution is being suspended.  Application state is saved
00100         /// without knowing whether the application will be terminated or resumed with the contents
00101         /// of memory still intact.
00102         /// </summary>
00103         /// <param name="sender">The source of the suspend request.</param>
00104         /// <param name="e">Details about the suspend request.</param>
00105         private void OnSuspending(object sender, SuspendingEventArgs e)
00106         {
00107             var deferral = e.SuspendingOperation.GetDeferral();
00108             //TODO: Save application state and stop any background activity
00109             deferral.Complete();
00110         }
00111     }
00112 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaTranscoding/cpp/Scenario3_Trim.xaml.cpp Source File

  • MediaTranscoding
  • cpp

Scenario3_Trim.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_Trim.xaml.h"
00014
00015 using namespace SDKTemplate;
00016 using namespace Windows::UI::Xaml;
00017 using namespace Windows::UI::Xaml::Controls;
00018 using namespace Windows::UI::Xaml::Navigation;
00019 using namespace Windows::Storage::Streams;
00020 using namespace Platform;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Media;
00023 using namespace Windows::Media::MediaProperties;
00024 using namespace Windows::Media::Transcoding;
00025 using namespace Windows::Storage;
00026 using namespace Windows::Storage::Pickers;
00027 using namespace Windows::Storage::Streams;
00028 using namespace concurrency;
00029
00030 static const long c_TickToSec = (1000 * 1000 * 10);
00031
00032 Scenario3_Trim::Scenario3_Trim()
00033 {
00034     InitializeComponent();
00035
00036     // Hook up UI
00037     PickFileButton->Click += ref new RoutedEventHandler(this, &Scenario3_Trim::PickFile);
00038     SetOutputButton->Click += ref new RoutedEventHandler(this, &Scenario3_Trim::PickOutput);
00039     TargetFormat->SelectionChanged += ref new SelectionChangedEventHandler(this, &Scenario3_Trim::OnTargetFormatChanged);
00040     Transcode->Click += ref new RoutedEventHandler(this, &Scenario3_Trim::TranscodeTrim);
00041     Cancel->Click += ref new RoutedEventHandler(this, &Scenario3_Trim::TranscodeCancel);
00042     MarkInButton->Click += ref new RoutedEventHandler(this, &Scenario3_Trim::MarkIn);
00043     MarkOutButton->Click += ref new RoutedEventHandler(this, &Scenario3_Trim::MarkOut);
00044
00045     // Disable manual manipulation of trim points
00046     StartTimeText->Text = ((float)(_start.Duration) / c_TickToSec).ToString();
00047     EndTimeText->Text = ((float)(_stop.Duration) / c_TickToSec).ToString();
00048     StartTimeText->IsEnabled = false;
00049     EndTimeText->IsEnabled = false;
00050
00051
00052     // Media Controls
00053     InputPlayButton->Click += ref new RoutedEventHandler(this, &Scenario3_Trim::InputPlayButton_Click);
00054     InputPauseButton->Click += ref new RoutedEventHandler(this, &Scenario3_Trim::InputPauseButton_Click);
00055     InputStopButton->Click += ref new RoutedEventHandler(this, &Scenario3_Trim::InputStopButton_Click);
00056     OutputPlayButton->Click += ref new RoutedEventHandler(this, &Scenario3_Trim::OutputPlayButton_Click);
00057     OutputPauseButton->Click += ref new RoutedEventHandler(this, &Scenario3_Trim::OutputPauseButton_Click);
00058     OutputStopButton->Click += ref new RoutedEventHandler(this, &Scenario3_Trim::OutputStopButton_Click);
00059
00060     // File is not selected, disable all buttons but PickFileButton
00061     DisableButtons();
00062     SetPickFileButton(true);
00063     SetOutputFileButton(true);
00064     SetCancelButton(false);
00065
00066     // Initialize Objects
00067     _Transcoder = ref new MediaTranscoder();
00068     _Profile = nullptr;
00069     _InputFile = nullptr;
00070     _OutputFile = nullptr;
00071     _OutputFileName = "TranscodeSampleOutput";
00072
00073     _OutputType = "MP4";
00074     _OutputFileExtension = ".mp4";
00075 }
00076
00077 /// <summary>
00078 /// Invoked when this page is about to be displayed in a Frame.
00079 /// </summary>
00080 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00081 /// property is typically used to configure the page.</param>
00082 void Scenario3_Trim::OnNavigatedTo(NavigationEventArgs^ e)
00083 {
00084     // A pointer back to the main page.  This is needed if you want to call methods in Presets such
00085     // as NotifyUser()
00086     rootPage = MainPage::Current;
00087 }
00088
00089 void Scenario3_Trim::GetPresetProfile(ComboBox^ comboBox)
00090 {
00091     _Profile = nullptr;
00092     VideoEncodingQuality videoEncodingProfile = VideoEncodingQuality::Wvga;
00093     switch (comboBox->SelectedIndex)
00094     {
00095     case 0:
00096         videoEncodingProfile = VideoEncodingQuality::HD1080p;
00097         break;
00098     case 1:
00099         videoEncodingProfile = VideoEncodingQuality::HD720p;
00100         break;
00101     case 2:
00102         videoEncodingProfile = VideoEncodingQuality::Wvga;
00103         break;
00104     case 3:
00105         videoEncodingProfile = VideoEncodingQuality::Ntsc;
00106         break;
00107     case 4:
00108         videoEncodingProfile = VideoEncodingQuality::Pal;
00109         break;
00110     case 5:
00111         videoEncodingProfile = VideoEncodingQuality::Vga;
00112         break;
00113     case 6:
00114         videoEncodingProfile = VideoEncodingQuality::Qvga;
00115         break;
00116     }
00117
00118     if (_OutputType == "AVI")
00119     {
00120         _Profile = MediaEncodingProfile::CreateAvi(videoEncodingProfile);
00121     }
00122     else if (_OutputType == "WMV")
00123     {
00124         _Profile = MediaEncodingProfile::CreateWmv(videoEncodingProfile);
00125     }
00126     else
00127     {
00128         _Profile = MediaEncodingProfile::CreateMp4(videoEncodingProfile);
00129     }
00130     /*
00131     For transcoding to audio profiles, create the encoding profile using one of these APIs:
00132     MediaEncodingProfile::CreateMp3(audioEncodingProfile)
00133     MediaEncodingProfile::CreateM4a(audioEncodingProfile)
00134     MediaEncodingProfile::CreateWma(audioEncodingProfile)
00135     MediaEncodingProfile::CreateWav(audioEncodingProfile)
00136
00137     where audioEncodingProfile is one of these presets:
00138     AudioEncodingQuality::High
00139     AudioEncodingQuality::Medium
00140     AudioEncodingQuality::Low
00141     */
00142 }
00143
00144 void Scenario3_Trim::MarkIn(Object^ sender, RoutedEventArgs^ e)
00145 {
00146     _start = InputVideo->Position;
00147     StartTimeText->Text = ((float)(_start.Duration) / c_TickToSec).ToString();
00148     // Make sure end time is after start time.
00149     if (_start.Duration > _stop.Duration || (_start.Duration == _stop.Duration && _start.Duration != 0))
00150     {
00151         _stop.Duration = _start.Duration + c_TickToSec;
00152         EndTimeText->Text = ((float)(_stop.Duration) / c_TickToSec).ToString();
00153     }
00154 }
00155
00156 void Scenario3_Trim::MarkOut(Object^ sender, RoutedEventArgs^ e)
00157 {
00158     _stop = InputVideo->Position;
00159     EndTimeText->Text = ((float)(_stop.Duration) / c_TickToSec).ToString();
00160     // Make sure end time is after start time.
00161     if ((_start.Duration > _stop.Duration) || (_start.Duration == _stop.Duration && _start.Duration != 0))
00162     {
00163         if (_stop.Duration > c_TickToSec)
00164         {
00165             _start.Duration = _stop.Duration - c_TickToSec;
00166         }
00167         else
00168         {
00169             _start.Duration = 0;
00170         }
00171         StartTimeText->Text = ((float)(_start.Duration) / c_TickToSec).ToString();
00172     }
00173 }
00174
00175 void Scenario3_Trim::TranscodeTrim(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00176 {
00177     StopPlayers();
00178     DisableButtons();
00179     GetPresetProfile(ProfileSelect);
00180     _Transcoder->TrimStartTime = _start;
00181     _Transcoder->TrimStopTime = _stop;
00182
00183     if ((EnableMrfCrf444->IsChecked != nullptr) && (EnableMrfCrf444->IsChecked->Value))
00184     {
00185         _Transcoder->VideoProcessingAlgorithm = Windows::Media::Transcoding::MediaVideoProcessingAlgorithm::MrfCrf444;
00186     }
00187     else
00188     {
00189         _Transcoder->VideoProcessingAlgorithm = Windows::Media::Transcoding::MediaVideoProcessingAlgorithm::Default;
00190     }
00191
00192     // Clear messages
00193     StatusMessage->Text = "";
00194
00195     try
00196     {
00197         if ((_InputFile != nullptr) && (_OutputFile != nullptr))
00198         {
00199             create_task(_Transcoder->PrepareFileTranscodeAsync(_InputFile, _OutputFile, _Profile)).then(
00200                 [this](PrepareTranscodeResult^ transcode)
00201             {
00202                 try
00203                 {
00204                     if (transcode->CanTranscode)
00205                     {
00206                         OutputMsg->Text = "";
00207                         SetCancelButton(true);
00208                         Windows::Foundation::IAsyncActionWithProgress<double>^ transcodeOp = transcode->TranscodeAsync();
00209
00210                         // Set Progress Callback
00211                         transcodeOp->Progress = ref new AsyncActionProgressHandler<double>(
00212                             [this](IAsyncActionWithProgress<double>^ asyncInfo, double percent) {
00213                             TranscodeProgress(asyncInfo, percent);
00214                         }, Platform::CallbackContext::Same);
00215
00216                         return transcodeOp;
00217                     }
00218                     else
00219                     {
00220                         TranscodeFailure(transcode->FailureReason);
00221                     }
00222                 }
00223                 catch (Platform::Exception^ exception)
00224                 {
00225                     TranscodeError(exception->Message);
00226                 }
00227
00228                 cancel_current_task();
00229             }).then(
00230                 [this](task<void> transcodeTask)
00231             {
00232                 try
00233                 {
00234                     transcodeTask.get();
00235                     OutputMsg->Text = "Transcode Completed.";
00236                     OutputPath->Text = "Output (" + _OutputFile->Path + ")";
00237                     PlayFile(_OutputFile);
00238                 }
00239                 catch (task_canceled&)
00240                 {
00241                     OutputMsg->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red);
00242                     OutputMsg->Text = "Transcode Cancelled.";
00243                 }
00244                 catch (Exception^ exception)
00245                 {
00246                     TranscodeError(exception->Message);
00247                 }
00248
00249                 EnableButtons();
00250                 SetCancelButton(false);
00251             });
00252         }
00253     }
00254     catch (Platform::Exception^ exception)
00255     {
00256         TranscodeError(exception->Message);
00257     }
00258 }
00259
00260 void Scenario3_Trim::TranscodeCancel(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00261 {
00262     try
00263     {
00264         _CTS.cancel();
00265         _CTS = cancellation_token_source();
00266
00267         if (_OutputFile != nullptr)
00268         {
00269             create_task(_OutputFile->DeleteAsync()).then(
00270                 [this](task<void> deleteTask)
00271             {
00272                 try
00273                 {
00274                     deleteTask.get();
00275                 }
00276                 catch (Platform::Exception^ exception)
00277                 {
00278                     TranscodeError(exception->Message);
00279                 }
00280             });
00281         }
00282     }
00283     catch (Platform::Exception^ exception)
00284     {
00285         TranscodeError(exception->Message);
00286     }
00287 }
00288
00289 void Scenario3_Trim::TranscodeProgress(IAsyncActionWithProgress<double>^ asyncInfo, double percent)
00290 {
00291     OutputMsg->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Green);
00292     OutputMsg->Text = "Progress:  " + ((int)percent).ToString() + "%";
00293 }
00294
00295 void Scenario3_Trim::TranscodeError(Platform::String^ error)
00296 {
00297     StatusMessage->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red);
00298     StatusMessage->Text = error;
00299     EnableButtons();
00300     SetCancelButton(false);
00301 }
00302
00303 void Scenario3_Trim::TranscodeFailure(TranscodeFailureReason reason)
00304 {
00305     try
00306     {
00307         if (_OutputFile != nullptr)
00308         {
00309             create_task(_OutputFile->DeleteAsync()).then(
00310                 [this](task<void> deleteTask)
00311             {
00312                 try
00313                 {
00314                     deleteTask.get();
00315                 }
00316                 catch (Platform::Exception^ exception)
00317                 {
00318                     TranscodeError(exception->Message);
00319                 }
00320             });
00321         }
00322     }
00323     catch (Platform::Exception^ exception)
00324     {
00325         TranscodeError(exception->Message);
00326     }
00327
00328     switch (reason)
00329     {
00330     case TranscodeFailureReason::CodecNotFound:
00331         TranscodeError("Codec not found.");
00332         break;
00333     case TranscodeFailureReason::InvalidProfile:
00334         TranscodeError("Invalid profile.");
00335         break;
00336     default:
00337         TranscodeError("Unknown failure.");
00338     }
00339 }
00340
00341 void Scenario3_Trim::SetCancelButton(bool isEnabled)
00342 {
00343     Cancel->IsEnabled = isEnabled;
00344 }
00345
00346 void Scenario3_Trim::EnableButtons()
00347 {
00348     PickFileButton->IsEnabled = true;
00349     SetOutputButton->IsEnabled = true;
00350     TargetFormat->IsEnabled = true;
00351     ProfileSelect->IsEnabled = true;
00352     EnableMrfCrf444->IsEnabled = true;
00353
00354     // The transcode button's initial state should be disabled until an output
00355     // file has been set.
00356     Transcode->IsEnabled = false;
00357 }
00358
00359 void Scenario3_Trim::DisableButtons()
00360 {
00361     ProfileSelect->IsEnabled = false;
00362     Transcode->IsEnabled = false;
00363     PickFileButton->IsEnabled = false;
00364     SetOutputButton->IsEnabled = false;
00365     TargetFormat->IsEnabled = false;
00366     EnableMrfCrf444->IsEnabled = false;
00367 }
00368
00369 void Scenario3_Trim::EnableNonSquarePARProfiles()
00370 {
00371     ComboBoxItem_NTSC->IsEnabled = true;
00372     ComboBoxItem_PAL->IsEnabled = true;
00373 }
00374
00375 void Scenario3_Trim::DisableNonSquarePARProfiles()
00376 {
00377     ComboBoxItem_NTSC->IsEnabled = false;
00378     ComboBoxItem_PAL->IsEnabled = false;
00379
00380     // Ensure a valid profile is set
00381     if ((ProfileSelect->SelectedIndex == 3) || (ProfileSelect->SelectedIndex == 4))
00382     {
00383         ProfileSelect->SelectedIndex = 2;
00384     }
00385 }
00386
00387 void Scenario3_Trim::PickFile(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00388 {
00389     try
00390     {
00391         FileOpenPicker^ picker = ref new FileOpenPicker();
00392         picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00393         picker->FileTypeFilter->Append(".wmv");
00394         picker->FileTypeFilter->Append(".mp4");
00395
00396         create_task(picker->PickSingleFileAsync()).then(
00397             [this](StorageFile^ inputFile)
00398         {
00399             try
00400             {
00401                 _InputFile = inputFile;
00402
00403                 if (_InputFile != nullptr)
00404                 {
00405                     return inputFile->OpenAsync(FileAccessMode::Read);
00406                 }
00407             }
00408             catch (Platform::Exception^ exception)
00409             {
00410                 TranscodeError(exception->Message);
00411             }
00412
00413             cancel_current_task();
00414         }).then(
00415             [this](IRandomAccessStream^ inputStream)
00416         {
00417             try
00418             {
00419                 InputVideo->SetSource(inputStream, _InputFile->ContentType);;
00420                 InputVideo->Play();
00421
00422                 //Enable buttons
00423                 EnableButtons();
00424             }
00425             catch (Platform::Exception^ exception)
00426             {
00427                 TranscodeError(exception->Message);
00428             }
00429         });
00430     }
00431     catch (Exception^ exception)
00432     {
00433         TranscodeError(exception->Message);
00434     }
00435 }
00436
00437 void Scenario3_Trim::PickOutput(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00438 {
00439     try
00440     {
00441         FileSavePicker^ picker = ref new FileSavePicker();
00442         picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00443         picker->SuggestedFileName = _OutputFileName;
00444
00445         auto extensions = ref new Platform::Collections::Vector<String^>();
00446         extensions->Append(_OutputFileExtension);
00447         picker->FileTypeChoices->Insert(_OutputType, extensions);
00448
00449         create_task(picker->PickSaveFileAsync()).then([this](StorageFile^ file) {
00450             if (file != nullptr)
00451             {
00452                 _OutputFile = file;
00453                 SetTranscodeButton(true);
00454             }
00455         });
00456     }
00457     catch (Exception^ exception)
00458     {
00459         TranscodeError(exception->Message);
00460     }
00461 }
00462
00463 void Scenario3_Trim::OnTargetFormatChanged(Object^ sender, SelectionChangedEventArgs^ e)
00464 {
00465     switch (TargetFormat->SelectedIndex)
00466     {
00467     case 1:
00468         _OutputFileExtension = ".wmv";
00469         _OutputType = "WMV";
00470         EnableNonSquarePARProfiles();
00471         break;
00472     case 2:
00473         _OutputFileExtension = ".avi";
00474         _OutputType = "AVI";
00475
00476         // Disable NTSC and PAL profiles as non-square pixel aspect ratios are not supported by AVI
00477         DisableNonSquarePARProfiles();
00478         break;
00479     default:
00480         _OutputFileExtension = ".mp4";
00481         _OutputType = "MP4";
00482         EnableNonSquarePARProfiles();
00483         break;
00484     }
00485 }
00486
00487 void Scenario3_Trim::InputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00488 {
00489     if (InputVideo->DefaultPlaybackRate == 0)
00490     {
00491         InputVideo->DefaultPlaybackRate = 1.0;
00492         InputVideo->PlaybackRate = 1.0;
00493     }
00494
00495     InputVideo->Play();
00496 }
00497
00498 void Scenario3_Trim::InputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00499 {
00500     InputVideo->Stop();
00501 }
00502
00503 void Scenario3_Trim::InputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00504 {
00505     InputVideo->Pause();
00506 }
00507
00508 void Scenario3_Trim::OutputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00509 {
00510     if (OutputVideo->DefaultPlaybackRate == 0)
00511     {
00512         OutputVideo->DefaultPlaybackRate = 1.0;
00513         OutputVideo->PlaybackRate = 1.0;
00514     }
00515
00516     OutputVideo->Play();
00517 }
00518
00519 void Scenario3_Trim::OutputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00520 {
00521     OutputVideo->Stop();
00522 }
00523
00524 void Scenario3_Trim::OutputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00525 {
00526     OutputVideo->Pause();
00527 }
00528
00529 void Scenario3_Trim::SetPickFileButton(bool isEnabled)
00530 {
00531     PickFileButton->IsEnabled = isEnabled;
00532 }
00533
00534 void Scenario3_Trim::SetOutputFileButton(bool isEnabled)
00535 {
00536     SetOutputButton->IsEnabled = isEnabled;
00537 }
00538
00539 void Scenario3_Trim::SetTranscodeButton(bool isEnabled)
00540 {
00541     Transcode->IsEnabled = isEnabled;
00542 }
00543
00544 void Scenario3_Trim::StopPlayers()
00545 {
00546     if (InputVideo->CurrentState != Media::MediaElementState::Paused)
00547     {
00548         InputVideo->Pause();
00549     }
00550     if (OutputVideo->CurrentState != Media::MediaElementState::Paused)
00551     {
00552         OutputVideo->Pause();
00553     }
00554 }
00555
00556 void Scenario3_Trim::PlayFile(Windows::Storage::StorageFile^ MediaFile)
00557 {
00558     try
00559     {
00560         create_task(MediaFile->OpenAsync(FileAccessMode::Read)).then(
00561             [&, this, MediaFile](IRandomAccessStream^ outputStream)
00562         {
00563             try
00564             {
00565                 OutputVideo->SetSource(outputStream, MediaFile->ContentType);
00566                 OutputVideo->Play();
00567             }
00568             catch (Platform::Exception^ exception)
00569             {
00570                 TranscodeError(exception->Message);
00571             }
00572         });
00573     }
00574     catch (Exception^ exception)
00575     {
00576         TranscodeError(exception->Message);
00577     }
00578 }
Generated on Fri Nov 15 2024 22:20:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FrameSourceState Member List

This is the complete list of members for FrameSourceState, including all inherited members.
enabled | FrameSourceState
frameArrivedEventToken | FrameSourceState
latestFrame | FrameSourceState
reader | FrameSourceState
sourceInfo | FrameSourceState
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OCR/cpp/pch.cpp Source File

  • OCR
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cs/Scenario4_BackgroundActivity.xaml.cs Source File

  • ActivitySensor
  • cs

Scenario4_BackgroundActivity.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.Background;
00014 using Windows.Devices.Enumeration;
00015 using Windows.Devices.Sensors;
00016 using Windows.Storage;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class Scenario4_BackgroundActivity : Page
00028     {
00029         public const string SampleBackgroundTaskName = "ActivitySensorBackgroundTask";
00030         public const string SampleBackgroundTaskEntryPoint = "Tasks.ActivitySensorBackgroundTask";
00031
00032         // Common class ID for activity sensors
00033         Guid ActivitySensorClassId = new Guid("9D9E0118-1807-4F2E-96E4-2CE57142E196");
00034
00035         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00036         // as NotifyUser()
00037         MainPage rootPage = MainPage.Current;
00038         bool registered = false;
00039
00040         public Scenario4_BackgroundActivity()
00041         {
00042             this.InitializeComponent();
00043         }
00044
00045         /// <summary>
00046         /// Invoked when this page is about to be displayed in a Frame.
00047         /// </summary>
00048         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00049         /// property is typically used to configure the page.</param>
00050         protected override void OnNavigatedTo(NavigationEventArgs e)
00051         {
00052             foreach (var task in BackgroundTaskRegistration.AllTasks)
00053             {
00054                 if (task.Value.Name == Scenario4_BackgroundActivity.SampleBackgroundTaskName)
00055                 {
00056                     registered = true;
00057                     break;
00058                 }
00059             }
00060
00061             UpdateUIAsync(registered ? "Registered" : "Unregistered");
00062         }
00063
00064         /// <summary>
00065         /// This is the click handler for the 'Register Task' button.
00066         /// </summary>
00067         /// <param name="sender"></param>
00068         /// <param name="e"></param>
00069         async private void ScenarioRegisterTask(object sender, RoutedEventArgs e)
00070         {
00071             // Determine if we can access activity sensors
00072             var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(ActivitySensorClassId);
00073             if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
00074             {
00075                 // Determine if an activity sensor is present
00076                 // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
00077                 var activitySensor = await ActivitySensor.GetDefaultAsync();
00078                 if (true||activitySensor != null)
00079                 {
00080                     var status = await BackgroundExecutionManager.RequestAccessAsync();
00081
00082                     if ((BackgroundAccessStatus.AlwaysAllowed == status) ||
00083                         (BackgroundAccessStatus.AllowedSubjectToSystemPolicy == status))
00084                     {
00085                         RegisterBackgroundTask();
00086                     }
00087                     else
00088                     {
00089                         rootPage.NotifyUser("Background tasks may be disabled for this app", NotifyType.ErrorMessage);
00090                     }
00091                 }
00092                 else
00093                 {
00094                     rootPage.NotifyUser("No activity sensors found", NotifyType.ErrorMessage);
00095                 }
00096             }
00097             else
00098             {
00099                 rootPage.NotifyUser("Access denied to activity sensors", NotifyType.ErrorMessage);
00100             }
00101         }
00102
00103         /// <summary>
00104         /// This is the click handler for the 'Unregister Task' button.
00105         /// </summary>
00106         /// <param name="sender"></param>
00107         /// <param name="e"></param>
00108         private void ScenarioUnregisterTask(object sender, RoutedEventArgs e)
00109         {
00110             // Loop through all background tasks and unregister any with SampleBackgroundTaskName
00111             foreach (var cur in BackgroundTaskRegistration.AllTasks)
00112             {
00113                 if (SampleBackgroundTaskName == cur.Value.Name)
00114                 {
00115                     cur.Value.Unregister(true /*cancelTask*/);
00116                     registered = false;
00117                 }
00118             }
00119
00120             if (!registered)
00121             {
00122                 UpdateUIAsync("Unregistered");
00123             }
00124         }
00125
00126         /// <summary>
00127         /// This is the event handler for background task completion.
00128         /// </summary>
00129         /// <param name="task">The task that is reporting completion.</param>
00130         /// <param name="args">The completion report arguments.</param>
00131         private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
00132         {
00133             string status = "Completed";
00134             try
00135             {
00136                 args.CheckResult();
00137             }
00138             catch (Exception e)
00139             {
00140                 status = e.Message;
00141             }
00142             UpdateUIAsync(status);
00143         }
00144
00145         /// <summary>
00146         /// Registers the background task.
00147         /// </summary>
00148         private void RegisterBackgroundTask()
00149         {
00150             var builder = new BackgroundTaskBuilder()
00151             {
00152                 Name = SampleBackgroundTaskName,
00153                 TaskEntryPoint = SampleBackgroundTaskEntryPoint
00154             };
00155
00156             const UInt32 reportIntervalMs = 3000; // 3 seconds
00157             var trigger = new ActivitySensorTrigger(reportIntervalMs);
00158
00159             trigger.SubscribedActivities.Add(ActivityType.Walking);
00160             trigger.SubscribedActivities.Add(ActivityType.Running);
00161             trigger.SubscribedActivities.Add(ActivityType.Biking);
00162
00163             builder.SetTrigger(trigger);
00164
00165             BackgroundTaskRegistration task = builder.Register();
00166             task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
00167
00168             registered = true;
00169             UpdateUIAsync("Registered");
00170         }
00171
00172         /// <summary>
00173         /// Updates the scenario UI.
00174         /// </summary>
00175         /// <param name="status">The status string to display.</param>
00176         async private void UpdateUIAsync(string status)
00177         {
00178             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00179             {
00180                 ScenarioRegisterTaskButton.IsEnabled = !registered;
00181                 ScenarioUnregisterTaskButton.IsEnabled = registered;
00182                 ScenarioOutput_TaskRegistration.Text = status;
00183
00184                 var settings = ApplicationData.Current.LocalSettings;
00185
00186                 if (settings.Values.ContainsKey("ReportCount"))
00187                 {
00188                     ScenarioOutput_ReportCount.Text = settings.Values["ReportCount"].ToString(); // stored as a string
00189                 }
00190                 if (settings.Values.ContainsKey("TaskStatus"))
00191                 {
00192                     ScenarioOutput_TaskStatus.Text = settings.Values["TaskStatus"].ToString(); // stored as a string
00193                 }
00194                 if (settings.Values.ContainsKey("LastActivity"))
00195                 {
00196                     ScenarioOutput_LastActivity.Text = (string)settings.Values["LastActivity"]; // stored as a string
00197                 }
00198                 if (settings.Values.ContainsKey("LastConfidence"))
00199                 {
00200                     ScenarioOutput_LastConfidence.Text = (string)settings.Values["LastConfidence"]; // stored as a string
00201                 }
00202                 if (settings.Values.ContainsKey("LastTimestamp"))
00203                 {
00204                     ScenarioOutput_LastTimestamp.Text = settings.Values["LastTimestamp"].ToString(); // stored as a string
00205                 }
00206             });
00207         }
00208     }
00209 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraFrames/cpp/SimpleLogger.h Source File

  • CameraFrames
  • cpp

SimpleLogger.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace SDKTemplate
00015 {
00016     private ref class SimpleLogger sealed
00017     {
00018     public:
00019         SimpleLogger(Windows::UI::Xaml::Controls::TextBlock^ textBlock)
00020         {
00021             m_textBlock = textBlock;
00022             m_dispatcher = textBlock->Dispatcher;
00023         }
00024
00025         void Log(Platform::String^ message)
00026         {
00027             auto calendar = ref new Windows::Globalization::Calendar();
00028             auto formatter = ref new Windows::Globalization::DateTimeFormatting::DateTimeFormatter("hour minute second");
00029
00030             LONG messageNumber = InterlockedIncrement(&m_messageCount);
00031             Platform::String^ newMessage = "[" + messageNumber.ToString() + "] " +
00032                 formatter->Format(calendar->GetDateTime()) + " : " + message;
00033
00034             m_dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Low,
00035                 ref new Windows::UI::Core::DispatchedHandler(
00036                     [this, newMessage]()
00037             {
00038                 m_textBlock->Text = newMessage + "\r\n" + m_textBlock->Text;
00039             }));
00040         }
00041
00042     private:
00043         LONG m_messageCount = 0;
00044         Windows::UI::Xaml::Controls::TextBlock^ m_textBlock;
00045         Windows::UI::Core::CoreDispatcher^ m_dispatcher;
00046     };
00047
00048 } // SDKTemplate
Generated on Fri Nov 15 2024 22:18:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomEditControl/cs/Scenario1_Input.xaml.cs Source File

  • CustomEditControl
  • cs

Scenario1_Input.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Diagnostics;
00014 using Windows.Foundation;
00015 using Windows.UI.Core;
00016 using Windows.UI.Text.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Media;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class Scenario1_Input : Page
00028     {
00029         public Scenario1_Input()
00030         {
00031             this.InitializeComponent();
00032 #if x
00033             // Handle touch event to manage focus.
00034             CoreWindow.GetForCurrentThread().PointerPressed += Page_PointerPressed;
00035 #endif
00036         }
00037
00038 #if x
00039         //Used to check if the pointer is within the bounds of the edit control.
00040         //If it is, focus should go to the edit control.  If it is outside the bounds
00041         //Focus should not be in the edit control.
00042         private void Page_PointerPressed(CoreWindow sender, PointerEventArgs args)
00043         {
00044             Rect _boundingbox = EditControl.GetLayout();
00045             if (_boundingbox.Contains(args.CurrentPoint.Position))
00046             {
00047                 _textEditContext.InternalSetFocus();
00048                 EditControl.Focus(FocusState.Programmatic);
00049             }
00050             else
00051             {
00052                 _textEditContext.InternalRemoveFocus();
00053             }
00054         }
00055 #endif
00056
00057         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00058         {
00059 #if x
00060             //Destroy the pointer pressed handlers when navigating to another page.
00061             CoreWindow.GetForCurrentThread().PointerPressed -= Page_PointerPressed;
00062             _textEditContext.ShutDown();
00063             base.OnNavigatingFrom(e);
00064 #endif
00065         }
00066
00067     }
00068 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/Scenario8_PairDevice.xaml.h Source File

  • DeviceEnumerationAndPairing
  • cpp

Scenario8_PairDevice.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario8_PairDevice.g.h"
00006 #include "MainPage.xaml.h"
00007 #include "DisplayHelpers.h"
00008 #include "DeviceWatcherHelper.h"
00009
00010 namespace SDKTemplate
00011 {
00012     /// <summary>
00013     /// An empty page that can be used on its own or navigated to within a Frame.
00014     /// </summary>
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     [Windows::UI::Xaml::Data::Bindable]
00017     public ref class Scenario8_PairDevice sealed
00018     {
00019     public:
00020         Scenario8_PairDevice();
00021
00022     protected:
00023         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00024         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00025
00026     private:
00027         void StartWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00028         void StopWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029         void PairButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00030         void UnpairButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00031
00032         void ResultsListView_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00033
00034         void StartWatcher();
00035         void StopWatcher();
00036
00037         void OnDeviceListChanged(Windows::Devices::Enumeration::DeviceWatcher^ sender, Platform::String^ id);
00038         void UpdatePairingButtons();
00039
00040         MainPage^ rootPage = MainPage::Current;
00041         Windows::Foundation::Collections::IObservableVector<DeviceInformationDisplay^>^ resultCollection = ref new Platform::Collections::Vector<DeviceInformationDisplay^>();
00042         DeviceWatcherHelper^ deviceWatcherHelper;
00043     };
00044 }
Generated on Fri Nov 15 2024 22:19:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/pch.h Source File

  • SmartCard
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.System.h"
00008 #include "winrt/Windows.UI.Core.h"
00009 #include "winrt/Windows.UI.Xaml.h"
00010 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00011 #include "winrt/Windows.UI.Xaml.Controls.h"
00012 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00013 #include "winrt/Windows.UI.Xaml.Documents.h"
00014 #include "winrt/Windows.UI.Xaml.Interop.h"
00015 #include "winrt/Windows.UI.Xaml.Markup.h"
00016 #include "winrt/Windows.UI.Xaml.Media.h"
00017 #include "winrt/Windows.UI.Xaml.Navigation.h"
00018 #include "winrt/Windows.Devices.Enumeration.h"
00019 #include "winrt/Windows.Devices.SmartCards.h"
00020 #include "winrt/Windows.Storage.Streams.h"
00021 #include "winrt/Windows.Security.Cryptography.h"
00022 #include "winrt/Windows.Security.Cryptography.Core.h"
00023 #include "SmartCardHelpers.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiScan/cs/DisplayHelpers.cs Source File

  • WiFiScan
  • cs

DisplayHelpers.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.ComponentModel;
00015 using System.Threading.Tasks;
00016 using Windows.Devices.WiFi;
00017 using Windows.Networking.Connectivity;
00018 using Windows.UI.Core;
00019 using Windows.UI.Xaml.Media.Imaging;
00020
00021 namespace WiFiScan
00022 {
00023     public class WiFiNetworkDisplay : INotifyPropertyChanged
00024     {
00025         private WiFiAdapter adapter;
00026         public WiFiNetworkDisplay(WiFiAvailableNetwork availableNetwork, WiFiAdapter adapter)
00027         {
00028             AvailableNetwork = availableNetwork;
00029             this.adapter = adapter;
00030             UpdateWiFiImage();
00031         }
00032
00033         private void UpdateWiFiImage()
00034         {
00035             string imageFileNamePrefix = "secure";
00036             if (AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211)
00037             {
00038                 imageFileNamePrefix = "open";
00039             }
00040
00041             string imageFileName = string.Format("ms-appx:/Assets/{0}_{1}bar.png", imageFileNamePrefix, AvailableNetwork.SignalBars);
00042
00043             WiFiImage = new BitmapImage(new Uri(imageFileName));
00044
00045             OnPropertyChanged("WiFiImage");
00046
00047         }
00048
00049         public async Task UpdateConnectivityLevel()
00050         {
00051             string connectivityLevel = "Not Connected";
00052             string connectedSsid = null;
00053
00054             var connectedProfile = await adapter.NetworkAdapter.GetConnectedProfileAsync();
00055             if (connectedProfile != null &&
00056                 connectedProfile.IsWlanConnectionProfile &&
00057                 connectedProfile.WlanConnectionProfileDetails != null)
00058             {
00059                 connectedSsid = connectedProfile.WlanConnectionProfileDetails.GetConnectedSsid();
00060             }
00061
00062             if (!string.IsNullOrEmpty(connectedSsid))
00063             {
00064                 if (connectedSsid.Equals(AvailableNetwork.Ssid))
00065                 {
00066                     connectivityLevel = connectedProfile.GetNetworkConnectivityLevel().ToString();
00067                 }
00068             }
00069
00070             ConnectivityLevel = connectivityLevel;
00071
00072             OnPropertyChanged("ConnectivityLevel");
00073         }
00074
00075         public String Ssid
00076         {
00077             get
00078             {
00079                 return availableNetwork.Ssid;
00080             }
00081         }
00082
00083         public String Bssid
00084         {
00085             get
00086             {
00087                 return availableNetwork.Bssid;
00088
00089             }
00090         }
00091
00092         public String ChannelCenterFrequency
00093         {
00094             get
00095             {
00096                 return string.Format("{0}kHz", availableNetwork.ChannelCenterFrequencyInKilohertz);
00097             }
00098         }
00099
00100         public String Rssi
00101         {
00102             get
00103             {
00104                 return string.Format("{0}dBm", availableNetwork.NetworkRssiInDecibelMilliwatts);
00105             }
00106         }
00107
00108         public String SecuritySettings
00109         {
00110             get
00111             {
00112                 return string.Format("Authentication: {0}; Encryption: {1}", availableNetwork.SecuritySettings.NetworkAuthenticationType, availableNetwork.SecuritySettings.NetworkEncryptionType);
00113             }
00114         }
00115         public String ConnectivityLevel
00116         {
00117             get;
00118             private set;
00119         }
00120
00121         public BitmapImage WiFiImage
00122         {
00123             get;
00124             private set;
00125         }
00126
00127
00128         private WiFiAvailableNetwork availableNetwork;
00129         public WiFiAvailableNetwork AvailableNetwork
00130         {
00131             get
00132             {
00133                 return availableNetwork;
00134             }
00135
00136             private set
00137             {
00138                 availableNetwork = value;
00139             }
00140         }
00141
00142         public event PropertyChangedEventHandler PropertyChanged;
00143         protected async void OnPropertyChanged(string name)
00144         {
00145             var rootPage = MainPage.Current;
00146             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00147             {
00148                 PropertyChangedEventHandler handler = PropertyChanged;
00149                 if (handler != null)
00150                 {
00151                     handler(this, new PropertyChangedEventArgs(name));
00152                 }
00153             });
00154         }
00155     }
00156 }
Generated on Fri Nov 15 2024 22:18:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed::sealed Member List

This is the complete list of members for sealed::sealed, including all inherited members.
__pad0__ | sealed::sealed |
FireIncomingConnection(IncomingConnectionEventArgs^args) | sealed::sealed | [inline, virtual]
OnShutdown() | sealed::sealed | [inline, virtual]
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicFaceTracking/cppwinrt/Scenario1_TrackInWebcam.h Source File

  • BasicFaceTracking
  • cppwinrt

Scenario1_TrackInWebcam.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_TrackInWebcam.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1_TrackInWebcam : Scenario1_TrackInWebcamT<Scenario1_TrackInWebcam>
00020     {
00021         Scenario1_TrackInWebcam();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025
00026         fire_and_forget CameraStreamingButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027
00028     private:
00029         // Values for identifying and controlling scenario states.
00030         enum class ScenarioState
00031         {
00032             /// Display is blank - default state.
00033             Idle,
00034
00035             /// Webcam is actively engaged and a live video stream is displayed.
00036             Streaming,
00037         };
00038
00039     private:
00040         /// Reference back to the "root" page of the app.
00041         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00042
00043         /// Holds the current scenario state value.
00044         ScenarioState currentState = ScenarioState::Idle;
00045
00046         // References a MediaCapture instance; is null when not in Streaming state.
00047         agile_ref<Windows::Media::Capture::MediaCapture> agileMediaCapture{ nullptr };
00048
00049         // Cache of properties from the current MediaCapture device which is used for capturing the preview frame.
00050         Windows::Media::MediaProperties::VideoEncodingProperties videoProperties{ nullptr };
00051
00052         // References a FaceTracker instance.
00053         Windows::Media::FaceAnalysis::FaceTracker faceTracker{ nullptr };
00054
00055         // A periodic timer to execute FaceTracker on preview frames
00056         Windows::System::Threading::ThreadPoolTimer frameProcessingTimer{ nullptr };
00057
00058         // Flag to ensure FaceTracking logic only executes one at a time
00059         std::atomic<bool> busy{ false };
00060
00061         // Event registration tokens.
00062         event_token suspendingEventToken;
00063
00064     private:
00065         fire_and_forget OnSuspending(Windows::Foundation::IInspectable const& sender, Windows::ApplicationModel::SuspendingEventArgs const& e);
00066         Windows::Foundation::IAsyncOperation<bool> StartWebcamStreamingAsync();
00067         Windows::Foundation::IAsyncAction ShutdownWebcamAsync();
00068         Windows::Foundation::IAsyncAction ProcessCurrentVideoFrameAsync();
00069         fire_and_forget ProcessCurrentVideoFrame(Windows::System::Threading::ThreadPoolTimer const& timer);
00070         void SetupVisualization(Windows::Foundation::Size framePixelSize, Windows::Foundation::Collections::IVector<Windows::Media::FaceAnalysis::DetectedFace> const& foundFaces);
00071         Windows::Foundation::IAsyncAction ChangeScenarioStateAsync(ScenarioState newState);
00072         fire_and_forget AbandonStreaming();
00073         void MediaCapture_CameraStreamFailed(Windows::Media::Capture::MediaCapture const& sender, Windows::Foundation::IInspectable const& args);
00074     };
00075 }
00076
00077 namespace winrt::SDKTemplate::factory_implementation
00078 {
00079     struct Scenario1_TrackInWebcam : Scenario1_TrackInWebcamT<Scenario1_TrackInWebcam, implementation::Scenario1_TrackInWebcam>
00080     {
00081     };
00082 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/Actions/InputText/Title/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • Actions
  • InputText
  • Title

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Notifications;
00003 using Windows.UI.Popups;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00008
00009 namespace Notifications.ScenarioPages.Toasts.Actions.InputText.Title
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     public sealed partial class ScenarioElement : UserControl
00015     {
00016         public ScenarioElement()
00017         {
00018             this.InitializeComponent();
00019         }
00020
00021         private void UserControl_Loaded(object sender, RoutedEventArgs e)
00022         {
00023             Initialize();
00024         }
00025
00026         private void Initialize()
00027         {
00028             // Clear all existing notifications
00029             ToastNotificationManager.History.Clear();
00030
00031             // Pop notifications
00032             popToastControl.Payload =
00033                 $@"
00034                 <toast activationType='foreground' launch='args'>
00035                     <visual>
00036                         <binding template='ToastGeneric'>
00037                             <text>Input Text - Title</text>
00038                             <text>Make sure ""My Title"" is displayed as the title of the text box in this toast.</text>
00039                         </binding>
00040                     </visual>
00041                     <actions>
00042
00043                         <input
00044                             id = 'message'
00045                             type = 'text'
00046                             title = 'My Title' />
00047
00048                     </actions>
00049                 </toast>";
00050         }
00051
00052         private async void Error(string message)
00053         {
00054             await new MessageDialog(message, "ERROR").ShowAsync();
00055         }
00056     }
00057 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/WASAPIRenderer.h Source File

  • WindowsAudioSession
  • cpp

WASAPIRenderer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // wasapirenderer.h
00013 //
00014
00015 #include <Windows.h>
00016 #include <wrl\implements.h>
00017 #include <mfapi.h>
00018 #include <AudioClient.h>
00019 #include <mmdeviceapi.h>
00020 #include "MainPage.xaml.h"
00021 #include "DeviceState.h"
00022 #include "ToneSampleGenerator.h"
00023 #include "MFSampleGenerator.h"
00024
00025 using namespace Microsoft::WRL;
00026 using namespace Windows::Media::Devices;
00027 using namespace Windows::Storage::Streams;
00028
00029
00030 #pragma once
00031
00032 namespace SDKSample
00033 {
00034     namespace WASAPIAudio
00035     {
00036       public enum class ContentType
00037       {
00038          ContentTypeTone,
00039          ContentTypeFile
00040       };
00041
00042
00043         // User Configurable Arguments for Scenario
00044         struct DEVICEPROPS
00045         {
00046             Platform::Boolean       IsHWOffload;
00047             Platform::Boolean       IsTonePlayback;
00048             Platform::Boolean       IsBackground;
00049             Platform::Boolean       IsRawSupported;
00050             Platform::Boolean       IsRawChosen;
00051             Platform::Boolean       IsLowLatency;
00052             REFERENCE_TIME          hnsBufferDuration;
00053             DWORD                   Frequency;
00054             IRandomAccessStream^    ContentStream;
00055         };
00056
00057         // Primary WASAPI Renderering Class
00058         class WASAPIRenderer :
00059             public RuntimeClass< RuntimeClassFlags< ClassicCom >, FtmBase, IActivateAudioInterfaceCompletionHandler >
00060         {
00061         public:
00062             WASAPIRenderer();
00063
00064             HRESULT SetProperties( DEVICEPROPS props );
00065             HRESULT InitializeAudioDeviceAsync();
00066             HRESULT StartPlaybackAsync();
00067             HRESULT StopPlaybackAsync();
00068             HRESULT PausePlaybackAsync();
00069
00070             HRESULT SetVolumeOnSession( UINT32 volume );
00071             DeviceStateChangedEvent^ GetDeviceStateEvent() { return m_DeviceStateChanged; };
00072
00073             METHODASYNCCALLBACK( WASAPIRenderer, StartPlayback, OnStartPlayback );
00074             METHODASYNCCALLBACK( WASAPIRenderer, StopPlayback, OnStopPlayback );
00075             METHODASYNCCALLBACK( WASAPIRenderer, PausePlayback, OnPausePlayback );
00076             METHODASYNCCALLBACK( WASAPIRenderer, SampleReady, OnSampleReady );
00077
00078             // IActivateAudioInterfaceCompletionHandler
00079             STDMETHOD(ActivateCompleted)( IActivateAudioInterfaceAsyncOperation *operation );
00080
00081         private:
00082             ~WASAPIRenderer();
00083
00084             HRESULT OnStartPlayback( IMFAsyncResult* pResult );
00085             HRESULT OnStopPlayback( IMFAsyncResult* pResult );
00086             HRESULT OnPausePlayback( IMFAsyncResult* pResult );
00087             HRESULT OnSampleReady( IMFAsyncResult* pResult );
00088
00089             HRESULT ConfigureDeviceInternal();
00090             HRESULT ValidateBufferValue();
00091             HRESULT OnAudioSampleRequested( Platform::Boolean IsSilence = false );
00092             HRESULT ConfigureSource();
00093             UINT32 GetBufferFramesPerPeriod();
00094             HRESULT SetAudioClientChannelVolume();
00095
00096             HRESULT GetToneSample( UINT32 FramesAvailable );
00097             HRESULT GetMFSample( UINT32 FramesAvailable );
00098
00099         private:
00100             Platform::String^   m_DeviceIdString;
00101             UINT32              m_BufferFrames;
00102             HANDLE              m_SampleReadyEvent;
00103             MFWORKITEM_KEY      m_SampleReadyKey;
00104             CRITICAL_SECTION    m_CritSec;
00105
00106             WAVEFORMATEX           *m_MixFormat;
00107             UINT32                  m_DefaultPeriodInFrames;
00108             UINT32                  m_FundamentalPeriodInFrames;
00109             UINT32                  m_MaxPeriodInFrames;
00110             UINT32                  m_MinPeriodInFrames;
00111             float                   m_ChannelVolume;
00112
00113             IAudioClient3          *m_AudioClient;
00114             IAudioRenderClient     *m_AudioRenderClient;
00115             IMFAsyncResult         *m_SampleReadyAsyncResult;
00116
00117             DeviceStateChangedEvent^       m_DeviceStateChanged;
00118             DEVICEPROPS                    m_DeviceProps;
00119
00120             ToneSampleGenerator    *m_ToneSource;
00121             MFSampleGenerator      *m_MFSource;
00122         };
00123     }
00124 }
00125
Generated on Fri Nov 15 2024 22:22:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/pch.cpp Source File

  • DeviceEnumerationAndPairing
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/Controls/InstructionsControl.cs Source File

  • Notifications
  • cs
  • Notifications
  • Controls

InstructionsControl.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Xaml.Controls;
00002
00003 namespace Notifications.Controls
00004 {
00005     public class InstructionsControl : ItemsControl
00006     {
00007         public InstructionsControl()
00008         {
00009             this.DefaultStyleKey = typeof(InstructionsControl);
00010         }
00011     }
00012 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/Scenario6DisablePreview.xaml.cpp Source File

  • Printing
  • cpp

Scenario6DisablePreview.xaml.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario6DisablePreview.xaml.h"
00005 #include "PageToPrint.xaml.h"
00006 #include "ContinuationPage.xaml.h"
00007
00008 using namespace SDKTemplate;
00009
00010 using namespace Platform;
00011 using namespace Windows::Foundation;
00012 using namespace Windows::Foundation::Collections;
00013 using namespace Windows::Foundation::Metadata;
00014 using namespace Windows::Graphics::Display;
00015 using namespace Windows::Graphics::Printing;
00016 using namespace Windows::UI::Core;
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Controls::Primitives;
00020 using namespace Windows::UI::Xaml::Data;
00021 using namespace Windows::UI::Xaml::Input;
00022 using namespace Windows::UI::Xaml::Media;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025
00026 void PreviewOptionsPrintHelper::PrintTaskRequested(PrintManager^ sender, PrintTaskRequestedEventArgs^ e)
00027 {
00028     PrintTask^ printTask = e->Request->CreatePrintTask("C++ Printing SDK Sample", ref new PrintTaskSourceRequestedHandler([=](PrintTaskSourceRequestedArgs^ args)
00029     {
00030         args->SetSource(PrintDocumentSource);
00031     }));
00032
00033     // Print Task event handler is invoked when the print job is completed.
00034     printTask->Completed += ref new TypedEventHandler<PrintTask^, PrintTaskCompletedEventArgs^>([=](PrintTask^ sender, PrintTaskCompletedEventArgs^ e)
00035     {
00036         // Notify the user when the print operation fails.
00037         if (e->Completion == PrintTaskCompletion::Failed)
00038         {
00039             auto callback = ref new DispatchedHandler([=]()
00040             {
00041                 MainPage::Current->NotifyUser(ref new String(L"Failed to print."), NotifyType::ErrorMessage);
00042             });
00043
00044             ScenarioPage->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, callback);
00045         }
00046     });
00047
00048     // Choose not to show the preview by setting the property on PrintTask
00049     printTask->IsPreviewEnabled = false;
00050 }
00051
00052 void PreviewOptionsPrintHelper::AddPrintPages(Object^ sender, AddPagesEventArgs^ e)
00053 {
00054     // Clear the cache of print pages
00055     m_printPages.clear();
00056
00057     // Clear the printing root of print pages
00058     PrintCanvas->Children->Clear();
00059
00060     // This variable keeps track of the last RichTextBlockOverflow element that was added to a page which will be printed
00061     RichTextBlockOverflow^ lastRTBOOnPage;
00062
00063     // Get the PrintTaskOptions
00064     PrintTaskOptions^ printingOptions = safe_cast<PrintTaskOptions^>(e->PrintTaskOptions);
00065
00066     // Get the page description to deterimine how big the page is
00067     PrintPageDescription pageDescription = printingOptions->GetPageDescription(0);
00068
00069     // We know there is at least one page to be printed. passing null as the first parameter to
00070     // AddOnePrintPage tells the function to add the first page.
00071     lastRTBOOnPage = AddOnePrintPage(nullptr, pageDescription);
00072
00073     // We know there are more pages to be added as long as the last RichTextBoxOverflow added to a print
00074     // page has extra content
00075     while (lastRTBOOnPage->HasOverflowContent && (lastRTBOOnPage->Visibility == Visibility::Visible))
00076     {
00077         lastRTBOOnPage = AddOnePrintPage(lastRTBOOnPage, pageDescription);
00078     }
00079
00080     PrintDocument^ printDocument = safe_cast<PrintDocument^>(sender);
00081
00082     // Loop over all of the print pages and add each one to be printed
00083
00084     for (UIElement^ page : m_printPages)
00085     {
00086         printDocument->AddPage(page);
00087     }
00088
00089     // Indicate that all of the print pages have been provided
00090     printDocument->AddPagesComplete();
00091 }
00092
00093 RichTextBlockOverflow^ PreviewOptionsPrintHelper::AddOnePrintPage(RichTextBlockOverflow^ lastRTBOAdded, PrintPageDescription printPageDescription)
00094 {
00095     // XAML element that is used to represent to "printing page"
00096     FrameworkElement^ page;
00097
00098     // The link container for text overflowing in this page
00099     RichTextBlockOverflow^ textLink;
00100
00101     // Check if this is the first page ( no previous RichTextBlockOverflow)
00102     if (lastRTBOAdded == nullptr)
00103     {
00104         // If this is the first page add the specific scenario content
00105         page = FirstPage;
00106
00107         // Hide footer since we don't know yet if it will be displayed (this might not be the last page) - wait for layout
00108         StackPanel^ footer = safe_cast<StackPanel^>(page->FindName("Footer"));
00109         footer->Visibility = Visibility::Collapsed;
00110     }
00111     else
00112     {
00113         // Flow content (text) from previous pages
00114         page = ref new ContinuationPage(lastRTBOAdded);
00115     }
00116
00117     // Set "paper" width
00118     page->Width = printPageDescription.PageSize.Width;
00119     page->Height = printPageDescription.PageSize.Height;
00120
00121     Grid^ printableArea = safe_cast<Grid^>(page->FindName("PrintableArea"));
00122
00123     // Get the margins size
00124     // If the ImageableRect is smaller than the app provided margins use the ImageableRect
00125     double marginWidth = (std::max)(printPageDescription.PageSize.Width - printPageDescription.ImageableRect.Width, printPageDescription.PageSize.Width * ApplicationContentMarginLeft * 2);
00126     double marginHeight = (std::max)(printPageDescription.PageSize.Height - printPageDescription.ImageableRect.Height, printPageDescription.PageSize.Height * ApplicationContentMarginTop * 2);
00127
00128     // Set-up "printable area" on the "paper"
00129     printableArea->Width = FirstPage->Width - marginWidth;
00130     printableArea->Height = FirstPage->Height - marginHeight;
00131
00132     // Add the (newly created) page to the printing root which is part of the visual tree and force it to go
00133     // through layout so that the linked containers correctly distribute the content inside them.
00134     PrintCanvas->Children->Append(page);
00135     PrintCanvas->InvalidateMeasure();
00136     PrintCanvas->UpdateLayout();
00137
00138     // Find the last text container and see if the content is overflowing
00139     textLink = safe_cast<RichTextBlockOverflow^>(page->FindName("ContinuationPageLinkedContainer"));
00140
00141     // Check if this is the last page
00142     if ((!textLink->HasOverflowContent) && (textLink->Visibility == Visibility::Visible))
00143     {
00144         StackPanel^ footer = safe_cast<StackPanel^>(page->FindName("Footer"));
00145         footer->Visibility = Visibility::Visible;
00146         PrintCanvas->UpdateLayout();
00147     }
00148
00149     // Add the page to the page print collection
00150     m_printPages.push_back(page);
00151
00152     return textLink;
00153 }
00154
00155 Scenario6DisablePreview::Scenario6DisablePreview()
00156 {
00157     InitializeComponent();
00158 }
00159
00160 void Scenario6DisablePreview::OnPrintButtonClick(Object^ sender, RoutedEventArgs^ e)
00161 {
00162     printHelper->ShowPrintUIAsync();
00163 }
00164
00165 void Scenario6DisablePreview::OnNavigatedTo(NavigationEventArgs^ e)
00166 {
00167     if (PrintManager::IsSupported())
00168     {
00169         // Tell the user how to print
00170         MainPage::Current->NotifyUser("Print contract registered with customization, use the Print button to print.", NotifyType::StatusMessage);
00171     }
00172     else
00173     {
00174         // Remove the print button
00175         InvokePrintingButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00176
00177         // Inform user that Printing is not supported
00178         MainPage::Current->NotifyUser("Printing is not supported.", NotifyType::ErrorMessage);
00179
00180         // Printing-related event handlers will never be called if printing
00181         // is not supported, but it's okay to register for them anyway.
00182     }
00183
00184     // Initalize common helper class and register for printing
00185     printHelper = ref new PreviewOptionsPrintHelper(this);
00186     printHelper->RegisterForPrinting();
00187
00188     // Initialize print content for this scenario
00189     printHelper->PreparePrintContent(ref new PageToPrint());
00190 }
00191
00192 void Scenario6DisablePreview::OnNavigatedFrom(NavigationEventArgs^ e)
00193 {
00194     if (printHelper != nullptr)
00195     {
00196         printHelper->UnregisterForPrinting();
00197     }
00198 }
Generated on Fri Nov 15 2024 22:21:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/pch.cpp Source File

  • HttpClient
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlTransform3DAnimations/cs/MainPage.xaml.cs Source File

  • XamlTransform3DAnimations
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.IO;
00004 using System.Linq;
00005 using System.Runtime.InteropServices.WindowsRuntime;
00006 using Transform3DAnimations.ViewModels;
00007 using Windows.Foundation;
00008 using Windows.Foundation.Collections;
00009 using Windows.UI.Xaml;
00010 using Windows.UI.Xaml.Controls;
00011 using Windows.UI.Xaml.Controls.Primitives;
00012 using Windows.UI.Xaml.Data;
00013 using Windows.UI.Xaml.Input;
00014 using Windows.UI.Xaml.Media;
00015 using Windows.UI.Xaml.Navigation;
00016
00017 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00018
00019 namespace Transform3DAnimations
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class MainPage : Page
00025     {
00026         private Random _random;
00027         private DispatcherTimer _updateTimer;
00028
00029
00030         public MainPage()
00031         {
00032             this.InitializeComponent();
00033
00034             _random = new Random();
00035
00036             _updateTimer = new DispatcherTimer();
00037             _updateTimer.Interval = TimeSpan.FromSeconds(3.0);
00038             _updateTimer.Tick += UpdateTimer_Tick;
00039         }
00040
00041         private void UpdateRandomSection()
00042         {
00043             // Updating the section triggers a cool animation!
00044             // See SectionView.xaml and SectionView.xaml.cs
00045
00046             var sectionsInView = HeadlinesHub.SectionsInView;
00047             var sectionsCount = sectionsInView.Count;
00048
00049             if (sectionsCount > 0)
00050             {
00051                 var sectionToUpdate = sectionsInView[_random.Next(sectionsCount)];
00052                 sectionToUpdate.DataContext = new HeroArticlesViewModel();
00053             }
00054         }
00055
00056         private void UpdateTimer_Tick(object sender, object e)
00057         {
00058             UpdateRandomSection();
00059         }
00060
00061         protected override void OnNavigatedTo(NavigationEventArgs e)
00062         {
00063             base.OnNavigatedTo(e);
00064
00065             _updateTimer.Start();
00066         }
00067
00068         private void SectionView_ArticleSelected(object sender, ArticleViewModel e)
00069         {
00070             // In a real app, you might pass a unique ID for the article as a navigation parameter.
00071             // Here we pass the title.
00072             Frame.Navigate(typeof(ArticlePage), e.Headline);
00073         }
00074     }
00075 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cppwinrt/SampleConfiguration.h Source File

  • WebSocket
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt
00016 {
00017     hstring to_hstring(Windows::Networking::Sockets::SocketMessageType value);
00018     hstring to_hstring(Windows::Web::WebErrorStatus value);
00019 }
00020
00021 namespace winrt::SDKTemplate
00022 {
00023     Windows::Foundation::Uri TryGetUri(MainPage const& rootPage, hstring const& uriString);
00024     hstring BuildWebSocketError(hresult_error const& ex);
00025     Windows::Foundation::IAsyncOperation<bool> AreCertificateAndCertChainValidAsync(Windows::Security::Cryptography::Certificates::Certificate serverCert, Windows::Foundation::Collections::IVectorView<Windows::Security::Cryptography::Certificates::Certificate> certChain);
00026 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cs/AdventureWorks/ViewModel/TripListViewModel.cs Source File

  • CortanaVoiceCommand
  • cs
  • AdventureWorks
  • ViewModel

TripListViewModel.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using AdventureWorks.Common;
00013 using AdventureWorks.Model;
00014 using AdventureWorks.View;
00015 using System;
00016 using System.Collections.Generic;
00017 using System.Collections.ObjectModel;
00018 using System.Linq;
00019 using System.Text;
00020 using System.Threading.Tasks;
00021 using System.Windows.Input;
00022
00023 namespace AdventureWorks.ViewModel
00024 {
00025     /// <summary>
00026     /// View Model controlling the behavior of a List view of trips
00027     /// </summary>
00028     public class TripListViewModel : ViewModelBase
00029     {
00030         private ICommand addTripCommand;
00031         private ObservableCollection<Trip> trips;
00032         private Trip selectedTrip;
00033         private TripStore store;
00034
00035         /// <summary>
00036         /// Construct the trip view, passing in the persistent trip store. Sets up
00037         /// a command to handle invoking the Add button.
00038         /// </summary>
00039         /// <param name="store"></param>
00040         public TripListViewModel(TripStore store)
00041         {
00042             this.store = store;
00043             Trips = store.Trips;
00044
00045             addTripCommand = new RelayCommand(new Action(AddTrip));
00046         }
00047
00048         /// <summary>
00049         /// The list of trips to display on the UI.
00050         /// </summary>
00051         public ObservableCollection<Trip> Trips
00052         {
00053             get
00054             {
00055                 return trips;
00056             }
00057             private set
00058             {
00059                 trips = value;
00060                 NotifyPropertyChanged("Trips");
00061             }
00062         }
00063
00064         /// <summary>
00065         /// A two-way binding that keeps reference to the currently selected trip on
00066         /// the UI.
00067         /// </summary>
00068         public Trip SelectedTrip
00069         {
00070             get
00071             {
00072                 return selectedTrip;
00073             }
00074             set
00075             {
00076                 selectedTrip = value;
00077                 NotifyPropertyChanged("SelectedTrip");
00078             }
00079         }
00080
00081         /// <summary>
00082         /// The command to invoke when the Add button is pressed.
00083         /// </summary>
00084         public ICommand AddTripCommand
00085         {
00086             get
00087             {
00088                 return addTripCommand;
00089             }
00090         }
00091
00092         /// <summary>
00093         /// Reload the trip store from data files.
00094         /// </summary>
00095         internal async Task LoadTrips()
00096         {
00097             await store.LoadTrips();
00098         }
00099
00100
00101         /// <summary>
00102         /// The implementation of the command to execute when the Add button is pressed.
00103         /// </summary>
00104         private void AddTrip()
00105         {
00106             App.NavigationService.Navigate<TripDetails>();
00107         }
00108
00109         /// <summary>
00110         /// Handles a user selecting a trip on the UI by navigating to the TripDetails view
00111         /// for that trip.
00112         /// </summary>
00113         internal void SelectionChanged()
00114         {
00115             if (SelectedTrip != null)
00116             {
00117                 App.NavigationService.Navigate<TripDetails>(SelectedTrip);
00118             }
00119         }
00120     }
00121 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/PixelShader/BasicReaderWriter.cpp Source File

  • D2DCustomEffects
  • cpp
  • PixelShader

BasicReaderWriter.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "BasicReaderWriter.h"
00014
00015 using namespace Microsoft::WRL;
00016 using namespace Windows::Storage;
00017 using namespace Windows::Storage::FileProperties;
00018 using namespace Windows::Storage::Streams;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::ApplicationModel;
00021 using namespace concurrency;
00022
00023 BasicReaderWriter::BasicReaderWriter()
00024 {
00025     m_location = Package::Current->InstalledLocation;
00026 }
00027
00028 BasicReaderWriter::BasicReaderWriter(
00029     _In_ Windows::Storage::StorageFolder^ folder
00030     )
00031 {
00032     m_location = folder;
00033     Platform::String^ path = m_location->Path;
00034     if (path->Length() == 0)
00035     {
00036         // Applications are not permitted to access certain
00037         // folders, such as the Documents folder, using this
00038         // code path.  In such cases, the Path property for
00039         // the folder will be an empty string.
00040         throw ref new Platform::FailureException();
00041     }
00042 }
00043
00044 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00045     _In_ Platform::String^ filename
00046     )
00047 {
00048     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00049     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00050     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00051     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00052     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00053     extendedParams.lpSecurityAttributes = nullptr;
00054     extendedParams.hTemplateFile = nullptr;
00055
00056     Wrappers::FileHandle file(
00057         CreateFile2(
00058             filename->Data(),
00059             GENERIC_READ,
00060             FILE_SHARE_READ,
00061             OPEN_EXISTING,
00062             &extendedParams
00063             )
00064         );
00065     if (file.Get() == INVALID_HANDLE_VALUE)
00066     {
00067         throw ref new Platform::FailureException();
00068     }
00069
00070     FILE_STANDARD_INFO fileInfo = {0};
00071     if (!GetFileInformationByHandleEx(
00072         file.Get(),
00073         FileStandardInfo,
00074         &fileInfo,
00075         sizeof(fileInfo)
00076         ))
00077     {
00078         throw ref new Platform::FailureException();
00079     }
00080
00081     if (fileInfo.EndOfFile.HighPart != 0)
00082     {
00083         throw ref new Platform::OutOfMemoryException();
00084     }
00085
00086     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00087
00088     if (!ReadFile(
00089         file.Get(),
00090         fileData->Data,
00091         fileData->Length,
00092         nullptr,
00093         nullptr
00094         ))
00095     {
00096         throw ref new Platform::FailureException();
00097     }
00098
00099     return fileData;
00100 }
00101
00102 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00103     _In_ Platform::String^ filename
00104     )
00105 {
00106     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00107     {
00108         return FileIO::ReadBufferAsync(file);
00109     }).then([=](IBuffer^ buffer)
00110     {
00111         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00112         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00113         return fileData;
00114     });
00115 }
00116
00117 uint32 BasicReaderWriter::WriteData(
00118     _In_ Platform::String^ filename,
00119     _In_ const Platform::Array<byte>^ fileData
00120     )
00121 {
00122     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00123     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00124     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00125     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00126     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00127     extendedParams.lpSecurityAttributes = nullptr;
00128     extendedParams.hTemplateFile = nullptr;
00129
00130     Wrappers::FileHandle file(
00131         CreateFile2(
00132             filename->Data(),
00133             GENERIC_WRITE,
00134             0,
00135             CREATE_ALWAYS,
00136             &extendedParams
00137             )
00138         );
00139     if (file.Get() == INVALID_HANDLE_VALUE)
00140     {
00141         throw ref new Platform::FailureException();
00142     }
00143
00144     DWORD numBytesWritten;
00145     if (
00146         !WriteFile(
00147             file.Get(),
00148             fileData->Data,
00149             fileData->Length,
00150             &numBytesWritten,
00151             nullptr
00152             ) ||
00153         numBytesWritten != fileData->Length
00154         )
00155     {
00156         throw ref new Platform::FailureException();
00157     }
00158
00159     return numBytesWritten;
00160 }
00161
00162 task<void> BasicReaderWriter::WriteDataAsync(
00163     _In_ Platform::String^ filename,
00164     _In_ const Platform::Array<byte>^ fileData
00165     )
00166 {
00167     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00168     {
00169         FileIO::WriteBytesAsync(file, fileData);
00170     });
00171 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_TilePinned Member List

This is the complete list of members for Scenario4_TilePinned, including all inherited members.
rootPage | Scenario4_TilePinned | [private]
Scenario4_TilePinned() | Scenario4_TilePinned | [inline]
TileExists_Click(object sender, RoutedEventArgs e) | Scenario4_TilePinned | [inline, private]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ShareText Member List

This is the complete list of members for ShareText, including all inherited members.
GetShareContent(DataRequest request) | ShareText | [inline, protected]
ShareText() | ShareText | [inline]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleOrientationSensor/cpp/Scenario1_DataEvents.xaml.h Source File

  • SimpleOrientationSensor
  • cpp

Scenario1_DataEvents.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_DataEvents.xaml.h
00014 // Declaration of the Scenario1_DataEvents class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario1_DataEvents.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario1_DataEvents sealed
00030     {
00031     public:
00032         Scenario1_DataEvents();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038     private:
00039         SDKTemplate::MainPage^ rootPage;
00040         Windows::Devices::Sensors::SimpleOrientationSensor^ sensor;
00041         Windows::Foundation::EventRegistrationToken visibilityToken;
00042         Windows::Foundation::EventRegistrationToken orientationToken;
00043
00044         void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00045         void DisplayOrientation(Windows::Devices::Sensors::SimpleOrientation orientation);
00046         void OrientationChanged(Windows::Devices::Sensors::SimpleOrientationSensor^ sender, Windows::Devices::Sensors::SimpleOrientationSensorOrientationChangedEventArgs^ e);
00047         void ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048         void ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049     };
00050 }
Generated on Fri Nov 15 2024 22:17:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LinguisticServices/cs/Scenario3_Transliteration.xaml.cs Source File

  • LinguisticServices
  • cs

Scenario3_Transliteration.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Sample;
00015
00016 namespace SDKTemplate
00017 {
00018     public sealed partial class Scenario3_Transliteration : Page
00019     {
00020         private MainPage rootPage = MainPage.Current;
00021
00022         public Scenario3_Transliteration()
00023         {
00024             InitializeComponent();
00025         }
00026
00027         public void Go_Click(object sender, RoutedEventArgs e)
00028         {
00029             TextOutput.Text = LinguisticServices.TransliterateFromCyrillicToLatin(TextInput.Text);
00030         }
00031     }
00032 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cppwinrt/LoggingSessionScenario.h Source File

  • Logging
  • cppwinrt

LoggingSessionScenario.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "LoggingScenarioEventArgs.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     class LoggingSessionScenario
00018     {
00019         // This is a singleton, only created/destroyed by the Instance() method.
00020         ~LoggingSessionScenario();
00021         LoggingSessionScenario();
00022
00023     public:
00024
00025         static LoggingSessionScenario&
00026         Instance();
00027
00028         winrt::event_token
00029         StatusChanged(StatusChangedHandler const& handler);
00030
00031         void
00032         StatusChanged(winrt::event_token const& token) noexcept;
00033
00034         bool
00035         IsBusy() const noexcept;
00036
00037         int
00038         LogFileGeneratedCount() const noexcept;
00039
00040         bool
00041         LoggingEnabled() const noexcept;
00042
00043         bool
00044         ToggleLoggingEnabledDisabled();
00045
00046         Windows::Foundation::IAsyncAction
00047         DoScenarioAsync();
00048
00049     private:
00050
00051         void
00052         StartLogging();
00053
00054         void
00055         PrepareToSuspend();
00056
00057         void
00058         ResumeLoggingIfApplicable();
00059
00060         void
00061         OnChannelLoggingEnabled(
00062             Windows::Foundation::Diagnostics::ILoggingChannel const& sender,
00063             Windows::Foundation::IInspectable const& args);
00064
00065         void
00066         OnAppSuspending(
00067             Windows::Foundation::IInspectable const& sender,
00068             Windows::ApplicationModel::SuspendingEventArgs const& e);
00069
00070         void
00071         OnAppResuming(
00072             Windows::Foundation::IInspectable const& sender,
00073             Windows::Foundation::IInspectable const& args);
00074
00075     private:
00076
00077         struct BusySetter
00078         {
00079             ~BusySetter();
00080             explicit BusySetter(LoggingSessionScenario& scenario);
00081             LoggingSessionScenario& _scenario;
00082         };
00083
00084         Windows::Foundation::Diagnostics::LoggingSession _session{ nullptr };
00085         Windows::Foundation::Diagnostics::LoggingChannel _channel{ nullptr };
00086
00087         std::atomic<int> _logFileGeneratedCount;
00088         std::atomic<int> _isBusy;
00089
00090         bool _isChannelEnabled = false;
00091         Windows::Foundation::Diagnostics::LoggingLevel _channelLoggingLevel{};
00092
00093         Windows::Foundation::Collections::IPropertySet _settings{ Windows::Storage::ApplicationData::Current().LocalSettings().Values() };
00094
00095         event<StatusChangedHandler> _statusChanged;
00096     };
00097 }
Generated on Fri Nov 15 2024 22:20:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GetConnectionProfiles Member List

This is the complete list of members for GetConnectionProfiles, including all inherited members.
CostBasedSuggestions(ConnectionCost connectionCost) | GetConnectionProfiles | [inline, private]
deviceAccountId | GetConnectionProfiles | [private]
GetConnectionCostInfo(ConnectionCost connectionCost) | GetConnectionProfiles | [inline, private]
GetConnectionProfile(ConnectionProfile connectionProfile) | GetConnectionProfiles | [inline, private]
GetConnectionProfiles() | GetConnectionProfiles | [inline]
GetConnectionProfilesButton_Click(object sender, RoutedEventArgs e) | GetConnectionProfiles | [inline, private]
GetDataPlanStatusInfo(DataPlanStatus dataPlan) | GetConnectionProfiles | [inline, private]
GetNetworkSecuritySettingsInfo(NetworkSecuritySettings netSecuritySettings) | GetConnectionProfiles | [inline, private]
GetWlanConnectionProfileDetailsInfo(WlanConnectionProfileDetails wlanConnectionProfileDetails) | GetConnectionProfiles | [inline, private]
GetWwanConnectionProfileDetailsInfo(WwanConnectionProfileDetails wwanConnectionProfileDetails) | GetConnectionProfiles | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | GetConnectionProfiles | [inline, protected]
PrepareScenario() | GetConnectionProfiles | [inline, private]
PrintConnectionProfiles(IReadOnlyList< ConnectionProfile > connectionProfiles) | GetConnectionProfiles | [inline, private]
rootPage | GetConnectionProfiles | [private]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cppwinrt/Scenario6.cpp Source File

  • FileThumbnails
  • cppwinrt

Scenario6.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario6.h"
00014 #include "Scenario6.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Storage;
00020 using namespace Windows::Storage::FileProperties;
00021 using namespace Windows::Storage::Pickers;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 namespace
00026 {
00027     // Utility function to convert a string to a uint32_t and detect bad input
00028     bool TryParseUInt(const wchar_t* str, uint32_t& result)
00029     {
00030         wchar_t* end;
00031         errno = 0;
00032         result = std::wcstoul(str, &end, 0);
00033
00034         if (str == end)
00035         {
00036             // Not parseable.
00037             return false;
00038         }
00039
00040         if (errno == ERANGE)
00041         {
00042             // Out of range.
00043             return false;
00044         }
00045
00046         if (*end != L'\0')
00047         {
00048             // Extra unparseable characters at the end.
00049             return false;
00050         }
00051
00052         return true;
00053     }
00054
00055 }
00056
00057 namespace winrt::SDKTemplate::implementation
00058 {
00059     Scenario6::Scenario6()
00060     {
00061         InitializeComponent();
00062     }
00063
00064     void Scenario6::OnNavigatedTo(NavigationEventArgs const&)
00065     {
00066         Helpers::ResetOutput(rootPage, ThumbnailImage(), OutputTextBlock());
00067     }
00068
00069     fire_and_forget Scenario6::SelectImageButton_Click(IInspectable const&, RoutedEventArgs const&)
00070     {
00071         auto lifetime = get_strong();
00072
00073         Helpers::ResetOutput(rootPage, ThumbnailImage(), OutputTextBlock());
00074
00075         uint32_t size;
00076         if (TryParseUInt(RequestSize().Text().c_str(), size))
00077         {
00078             // Pick a photo
00079             FileOpenPicker openPicker;
00080             openPicker.FileTypeFilter().ReplaceAll(FileExtensions::Image());
00081             StorageFile file = co_await openPicker.PickSingleFileAsync();
00082             if (file != nullptr)
00083             {
00084                 const ThumbnailMode thumbnailMode = ThumbnailMode::SingleItem;
00085
00086                 bool fastThumbnail = FastThumbnailCheckBox().IsChecked().Value();
00087                 ThumbnailOptions thumbnailOptions = ThumbnailOptions::UseCurrentScale;
00088                 if (fastThumbnail)
00089                 {
00090                     thumbnailOptions |= ThumbnailOptions::ReturnOnlyIfCached;
00091                 }
00092
00093                 StorageItemThumbnail thumbnail = co_await file.GetScaledImageAsThumbnailAsync(thumbnailMode, size, thumbnailOptions);
00094                     if (thumbnail != nullptr)
00095                     {
00096                         Helpers::DisplayResult(ThumbnailImage(), OutputTextBlock(), thumbnailMode, size, file, thumbnail, false);
00097                         thumbnail.Close();
00098                     }
00099                     else if (fastThumbnail)
00100                     {
00101                         rootPage.NotifyUser(Errors::NoExifThumbnail, NotifyType::StatusMessage);
00102                     }
00103                     else
00104                     {
00105                         rootPage.NotifyUser(Errors::NoThumbnail, NotifyType::StatusMessage);
00106                     }
00107             }
00108             else
00109             {
00110                 rootPage.NotifyUser(Errors::Cancel, NotifyType::StatusMessage);
00111             }
00112         }
00113         else
00114         {
00115             rootPage.NotifyUser(Errors::InvalidSize, NotifyType::ErrorMessage);
00116         }
00117     }
00118 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MagneticStripeReader/cpp/pch.cpp Source File

  • MagneticStripeReader
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cppwinrt/Scenario8_UpdateAsync.cpp Source File

  • SecondaryTiles
  • cppwinrt

Scenario8_UpdateAsync.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario8_UpdateAsync.h"
00014 #include "Scenario8_UpdateAsync.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::UI::StartScreen;
00020 using namespace Windows::UI::Xaml;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     Scenario8_UpdateAsync::Scenario8_UpdateAsync()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     fire_and_forget Scenario8_UpdateAsync::UpdateDefaultLogo_Click(IInspectable const&, RoutedEventArgs const&)
00030     {
00031         auto lifetime = get_strong();
00032
00033         if (SecondaryTile::Exists(SampleHelpers::LogoSecondaryTileId))
00034         {
00035             // Add the properties we want to update (logo in this example)
00036             SecondaryTile secondaryTile(SampleHelpers::LogoSecondaryTileId);
00037             secondaryTile.VisualElements().Square150x150Logo(Uri(L"ms-appx:///Assets/squareTileLogoUpdate-sdk.png"));
00038             bool isUpdated = co_await secondaryTile.UpdateAsync();
00039
00040             if (isUpdated)
00041             {
00042                 rootPage.NotifyUser(L"Secondary tile logo updated.", NotifyType::StatusMessage);
00043             }
00044             else
00045             {
00046                 rootPage.NotifyUser(L"Secondary tile logo not updated.", NotifyType::ErrorMessage);
00047             }
00048         }
00049         else
00050         {
00051             rootPage.NotifyUser(L"Please pin a secondary tile using scenario 1 before updating the logo.", NotifyType::ErrorMessage);
00052         }
00053     }
00054 }
Generated on Fri Nov 15 2024 22:21:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cpp/Scenario3_ClientAuthentication.xaml.cpp Source File

  • WebSocket
  • cpp

Scenario3_ClientAuthentication.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario3.xaml.cpp
00014 // Implementation of the Scenario3 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario3_ClientAuthentication.xaml.h"
00019
00020 using namespace concurrency;
00021 using namespace Platform;
00022 using namespace SDKTemplate;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::Networking::Sockets;
00026 using namespace Windows::Security::Cryptography;
00027 using namespace Windows::Security::Cryptography::Certificates;
00028 using namespace Windows::Storage;
00029 using namespace Windows::Storage::Streams;
00030 using namespace Windows::UI::Core;
00031 using namespace Windows::UI::Xaml;
00032 using namespace Windows::UI::Xaml::Controls;
00033 using namespace Windows::UI::Xaml::Navigation;
00034 using namespace Windows::Web;
00035
00036 static String^ const ClientCertUriPath = "ms-appx:///Assets/clientCert.pfx";
00037 static String^ const ClientCertPassword = "1234";
00038 static String^ const ClientCertFriendlyName = "WebSocketSampleClientCert";
00039 static String^ const ClientCertIssuerName = "www.contoso.com";
00040
00041 Scenario3::Scenario3()
00042 {
00043     InitializeComponent();
00044     UpdateVisualState();
00045 }
00046
00047 void Scenario3::OnNavigatedFrom(NavigationEventArgs^ e)
00048 {
00049     CloseSocket();
00050 }
00051
00052 void Scenario3::UpdateVisualState()
00053 {
00054     if (busy)
00055     {
00056         VisualStateManager::GoToState(this, "Busy", false);
00057     }
00058     else
00059     {
00060         bool connected = (streamWebSocket != nullptr);
00061         VisualStateManager::GoToState(this, connected ? "Connected" : "Disconnected", false);
00062     }
00063 }
00064
00065 void Scenario3::SetBusy(bool value)
00066 {
00067     busy = value;
00068     UpdateVisualState();
00069 }
00070
00071 void Scenario3::OnConnect()
00072 {
00073     SetBusy(true);
00074     ConnectWebSocketAsync().then([this]()
00075     {
00076         SetBusy(false);
00077     });
00078 }
00079
00080 task<Certificate^> Scenario3::FindCertificateFromStoreAsync()
00081 {
00082     // Find the client certificate for authentication. If not found, it means it has not been installed.
00083     CertificateQuery^ query = ref new CertificateQuery();
00084     query->IssuerName = ClientCertIssuerName;
00085     query->FriendlyName = ClientCertFriendlyName;
00086
00087     return create_task(CertificateStores::FindAllAsync(query))
00088         .then([](IVectorView<Certificate^>^ certs)
00089     {
00090         // This sample installs only one certificate, so if we find one, it must be ours.
00091         return (certs->Size > 0) ? certs->GetAt(0) : nullptr;
00092     });
00093 }
00094
00095 task<Certificate^> Scenario3::InstallClientCertificateAsync()
00096 {
00097     // Load the certificate from the clientCert.pfx file packaged with this sample.
00098     // This certificate has been signed with a trusted root certificate installed on the server.
00099     // The installation is done by running the setupServer.ps1 file, which should have been done
00100     // before running the app.
00101     // WARNING: Including a pfx file in the app package violates the Windows Store
00102     // certification requirements. We are shipping the pfx file with the package for demonstrating
00103     // the usage of client certificates. Apps that will be published through Windows Store
00104     // need to use other approaches to obtain a client certificate.
00105     return create_task(StorageFile::GetFileFromApplicationUriAsync(ref new Uri(ClientCertUriPath)))
00106         .then([](StorageFile^ clientCertFile)
00107     {
00108         return create_task(FileIO::ReadBufferAsync(clientCertFile));
00109     }).then([this](IBuffer^ buffer)
00110     {
00111         String^ clientCertData = CryptographicBuffer::EncodeToBase64String(buffer);
00112         AppendOutputLine("Reading certificate succeeded.");
00113
00114         // Install the certificate to the app's certificate store.
00115         // The app certificate store is removed when the app is uninstalled.
00116
00117         //To install a certificate to the CurrentUser\MY store, which is not app specific,
00118         // you need to use CertificateEnrollmentManager.UserCertificateEnrollmentManager.ImportPfxDataAsync().
00119         // In order to call that method, an app must have the "sharedUserCertificates" capability.
00120         // There are two ways to add this capability:
00121         //
00122         // 1. You can double click on the Package.appxmanifest file from the
00123         // solution explorer, select the "Capabilities" tab in the opened page, and then check the
00124         // "Shared User Certificates" box from the capabilities list.
00125         // 2. You can right click on the Package.appxmanifest file from the
00126         // solution explorer, select "View Code", and add "sharedUserCertificates" under the <Capabilities>
00127         // element directly.
00128         // Package.appxmanifest in this sample shows this capability commented out.
00129         //
00130         // The certificate will remain even when the app is uninstalled.
00131         return create_task(CertificateEnrollmentManager::ImportPfxDataAsync(
00132             clientCertData,
00133             ClientCertPassword,
00134             ExportOption::Exportable,
00135             KeyProtectionLevel::NoConsent,
00136             InstallOptions::DeleteExpired,
00137             ClientCertFriendlyName));
00138     }).then([this]()
00139     {
00140         AppendOutputLine("Installing certificate succeeded.");
00141
00142         // Return the certificate we just installed.
00143         return FindCertificateFromStoreAsync();
00144     }).then([this](task<Certificate^> previousTask)
00145     {
00146         try
00147         {
00148             return previousTask.get();
00149         }
00150         catch (Exception^ ex)
00151         {
00152             // This can happen if the certificate has already expired.
00153             AppendOutputLine("Installing certificate failed with" + ex->Message);
00154             return static_cast<Certificate^>(nullptr);
00155         }
00156     });
00157 }
00158
00159 task<Certificate^> Scenario3::GetClientCertificateAsync()
00160 {
00161     // The client certificate could be installed already (if this scenario has been run before),
00162     // try finding it from the store.
00163     return FindCertificateFromStoreAsync().then([this](Certificate^ cert)
00164     {
00165         if (cert)
00166         {
00167             return task_from_result(cert);
00168         }
00169
00170         // If the client certificate is not already installed, install and return it.
00171         return InstallClientCertificateAsync();
00172     });
00173 }
00174
00175 task<void> Scenario3::ConnectWebSocketAsync()
00176 {
00177     // Validating the URI is required since it was received from an untrusted source (user input).
00178     // The URI is validated by calling TryGetUri() that will return 'nullptr' for strings that are not
00179     // valid WebSocket URIs.
00180     // Note that when enabling the text box users may provide URIs to machines on the intrAnet or intErnet. In
00181     // these cases the app requires the "Home or Work Networking" or "Internet (Client)" capability respectively.
00182     Uri^ server = rootPage->TryGetUri(ServerAddressField->Text);
00183     if (!server)
00184     {
00185         return task_from_result();
00186     }
00187
00188     // Certificate validation is meaningful only for secure connections.
00189     if (server->SchemeName != "wss")
00190     {
00191         AppendOutputLine("Note: Certificate validation is performed only for the wss: scheme.");
00192     }
00193
00194     streamWebSocket = ref new StreamWebSocket();
00195     streamWebSocket->Closed += ref new TypedEventHandler<IWebSocket^, WebSocketClosedEventArgs^>(this, &Scenario3::OnClosed);
00196
00197     return GetClientCertificateAsync().then([this, server](Certificate^ cert)
00198     {
00199         // It is okay to set the ClientCertificate property even if GetClientCertificateAsync returns null.
00200         streamWebSocket->Control->ClientCertificate = cert;
00201
00202         // When connecting to wss:// endpoint, the OS by default performs validation of
00203         // the server certificate based on well-known trusted CAs. For testing purposes, we are ignoring
00204         // SSL errors.
00205         // WARNING: Only test applications should ignore SSL errors.
00206         // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle
00207         // attacks. (Although the connection is secure, the server is not authenticated.)
00208         // Note that not all certificate validation errors can be ignored.
00209         // In this case, we are ignoring these errors since the certificate assigned to the localhost
00210         // URI is self-signed and has subject name = fabrikam.com
00211         streamWebSocket->Control->IgnorableServerCertificateErrors->Append(ChainValidationResult::Untrusted);
00212         streamWebSocket->Control->IgnorableServerCertificateErrors->Append(ChainValidationResult::InvalidName);
00213
00214         AppendOutputLine("Connecting to " + server->DisplayUri + "...");
00215         return create_task(streamWebSocket->ConnectAsync(server));
00216     }).then([this](task<void> previousTask)
00217     {
00218         try
00219         {
00220             // Reraise any exception that occurred in the task.
00221             previousTask.get();
00222         }
00223         catch (Exception^ ex)
00224         {
00225             // Error happened during connect operation.
00226             delete streamWebSocket;
00227             streamWebSocket = nullptr;
00228
00229             AppendOutputLine(MainPage::BuildWebSocketError(ex));
00230             AppendOutputLine(ex->Message);
00231             return;
00232         }
00233
00234         rootPage->NotifyUser("Connected", NotifyType::StatusMessage);
00235         AppendOutputLine("Connected to WebSocket Server.");
00236     });
00237 }
00238
00239 void Scenario3::OnDisconnect()
00240 {
00241     SetBusy(true);
00242     rootPage->NotifyUser("Closing", NotifyType::StatusMessage);
00243     CloseSocket();
00244     SetBusy(false);
00245     rootPage->NotifyUser("Closed", NotifyType::StatusMessage);
00246 }
00247
00248 // The method may be triggered remotely by the server or locally by Close()/delete operator.
00249 void Scenario3::OnClosed(IWebSocket^ sender, WebSocketClosedEventArgs^ args)
00250 {
00251     // Dispatch the event to the UI thread so we do not need to synchronize access to streamWebSocket.
00252     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, sender, args] ()
00253     {
00254         AppendOutputLine("Closed; Code: " + args->Code.ToString() + ", Reason: " + args->Reason);
00255
00256         if (streamWebSocket == sender)
00257         {
00258             CloseSocket();
00259             UpdateVisualState();
00260         }
00261     }));
00262 }
00263
00264 void Scenario3::CloseSocket()
00265 {
00266     if (streamWebSocket != nullptr)
00267     {
00268         try
00269         {
00270             streamWebSocket->Close(1000, "Closed due to user request.");
00271         }
00272         catch (Exception^ ex)
00273         {
00274             AppendOutputLine(MainPage::BuildWebSocketError(ex));
00275             AppendOutputLine(ex->Message);
00276         }
00277         streamWebSocket = nullptr;
00278     }
00279 }
00280
00281 void Scenario3::AppendOutputLine(String^ value)
00282 {
00283     OutputField->Text += value + "\r\n";
00284 }
Generated on Fri Nov 15 2024 22:22:01 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: KeyCredentialManager/cs/UserSelect.xaml.cs Source File

  • KeyCredentialManager
  • cs

UserSelect.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.IO;
00016 using System.Threading.Tasks;
00017 using System.Xml;
00018 using System.Xml.Serialization;
00019 using Windows.Security.Credentials;
00020 using Windows.Storage;
00021 using Windows.UI.Xaml;
00022 using Windows.UI.Xaml.Controls;
00023 using Windows.UI.Xaml.Navigation;
00024
00025 namespace SDKTemplate
00026 {
00027     /// <summary>
00028     /// The user select page, if users successfully log into the app they will be added to a saved set of users.
00029     /// That set of users will populate a list of account tiles that can be chosen from for signing in on this page.
00030     ///
00031     /// If there are no accounts in the history, it will skip this and go directly to the traditional username/password sign in page.
00032     ///
00033     /// If there exists 1 or more accounts, users can select an account tile which will pass the account object to the sign in form.
00034     /// </summary>
00035     public partial class UserSelect : Page
00036     {
00037         private MainPage rootPage;
00038         private ListView accountListView;
00039         static public List<Account> accountList;
00040
00041         public UserSelect()
00042         {
00043             this.InitializeComponent();
00044             accountListView = listView_UserTileList;
00045             accountListView.SelectionChanged += Button_SelectUser_Click;
00046             this.Loaded += OnLoadedActions;
00047         }
00048
00049         protected override void OnNavigatedTo(NavigationEventArgs e)
00050         {
00051             rootPage = MainPage.Current;
00052         }
00053
00054         /// <summary>
00055         /// Function called when the current frame is loaded.
00056         ///
00057         /// Calls SetUpAccounts
00058         /// </summary>
00059         /// <param name="sender"></param>
00060         /// <param name="e"></param>
00061         private void OnLoadedActions(object sender, RoutedEventArgs e)
00062         {
00063             SetUpAccounts();
00064         }
00065
00066         /// <summary>
00067         ///
00068         /// Function called when an account is selected in the list of accounts
00069         ///
00070         /// Navigates to the sign in form and passes the chosen account
00071         /// The sign in form will check if Microsoft Passport should be used or not
00072         /// </summary>
00073         /// <param name="sender"></param>
00074         /// <param name="e"></param>
00075         private void Button_SelectUser_Click(object sender, RoutedEventArgs e)
00076         {
00077             if (((ListView)sender).SelectedValue != null)
00078             {
00079                 Account account = (Account)((ListView)sender).SelectedValue;
00080                 rootPage.NotifyUser("Account " + account.Name + " selected!", NotifyType.StatusMessage);
00081                 this.Frame.Navigate(typeof(SignIn), account);
00082             }
00083         }
00084
00085         /// <summary>
00086         /// Function called when the "+" button is clicked for adding a new account
00087         ///
00088         /// Just navigates to the default sign in form with nothing filled out
00089         /// </summary>
00090         /// <param name="sender"></param>
00091         /// <param name="e"></param>
00092         private void Button_AddUser_Click(object sender, RoutedEventArgs e)
00093         {
00094             this.Frame.Navigate(typeof(SignIn));
00095         }
00096
00097         /// <summary>
00098         /// Uses the AccountsHelper to load the list of accounts from a saved local app file,
00099         /// then checks to see if it was empty or not. If it is empty then just go to the sign in form.
00100         /// </summary>
00101         private async void SetUpAccounts()
00102         {
00103             accountList = await AccountsHelper.LoadAccountList();
00104             accountListView.ItemsSource = accountList;
00105
00106             if (accountList.Count == 0)
00107             {
00108                 this.Frame.Navigate(typeof(SignIn));
00109             }
00110         }
00111     }
00112 }
Generated on Fri Nov 15 2024 22:20:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_SystemDefaultMenu Member List

This is the complete list of members for Scenario2_SystemDefaultMenu, including all inherited members.
AddCustomItem(object sender, RoutedEventArgs e) | Scenario2_SystemDefaultMenu | [inline, private]
config | Scenario2_SystemDefaultMenu | [private]
controller | Scenario2_SystemDefaultMenu | [private]
Controller_RotationChanged(RadialController sender, RadialControllerRotationChangedEventArgs args) | Scenario2_SystemDefaultMenu | [inline, private]
customItem | Scenario2_SystemDefaultMenu | [private]
ModifySystemDefaults(object sender, RoutedEventArgs e) | Scenario2_SystemDefaultMenu | [inline, private]
OnLogSizeChanged(object sender, object e) | Scenario2_SystemDefaultMenu | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_SystemDefaultMenu | [inline, protected]
PrintSelectedItem() | Scenario2_SystemDefaultMenu | [inline, private]
Remove_Defaults(object sender, RoutedEventArgs e) | Scenario2_SystemDefaultMenu | [inline, private]
RemoveCustomItem(object sender, RoutedEventArgs e) | Scenario2_SystemDefaultMenu | [inline, private]
Reset_ToDefault(object sender, RoutedEventArgs e) | Scenario2_SystemDefaultMenu | [inline, private]
Scenario2_SystemDefaultMenu() | Scenario2_SystemDefaultMenu | [inline]
Select_Volume(object sender, RoutedEventArgs e) | Scenario2_SystemDefaultMenu | [inline, private]
SelectCustomItem(object sender, RoutedEventArgs e) | Scenario2_SystemDefaultMenu | [inline, private]
SelectPreviouslySelectedItem(object sender, RoutedEventArgs e) | Scenario2_SystemDefaultMenu | [inline, private]
Generated on Fri Nov 15 2024 22:23:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/SampleConfiguration.h Source File

  • DeviceEnumerationAndPairing
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Device Enumeration and Pairing C++ Sample";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

UserSelect Member List

This is the complete list of members for UserSelect, including all inherited members.
accountList | UserSelect | [static]
accountListView | UserSelect | [private]
Button_AddUser_Click(object sender, RoutedEventArgs e) | UserSelect | [inline, private]
Button_SelectUser_Click(object sender, RoutedEventArgs e) | UserSelect | [inline, private]
OnLoadedActions(object sender, RoutedEventArgs e) | UserSelect | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | UserSelect | [inline, protected]
rootPage | UserSelect | [private]
SetUpAccounts() | UserSelect | [inline, private]
UserSelect() | UserSelect | [inline]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Unicode/cppwinrt/pch.cpp Source File

  • Unicode
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/Scenario3_ResetPIN.h Source File

  • SmartCard
  • cppwinrt

Scenario3_ResetPIN.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once;
00013
00014 #include "Scenario3_ResetPIN.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario3_ResetPIN : Scenario3_ResetPINT<Scenario3_ResetPIN>
00019     {
00020         SDKTemplate::MainPage m_rootPage{ SDKTemplate::MainPage::Current() };
00021
00022         Scenario3_ResetPIN();
00023
00024         fire_and_forget ResetPin_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const&);
00025     };
00026 }
00027
00028 namespace winrt::SDKTemplate::factory_implementation
00029 {
00030     struct Scenario3_ResetPIN : Scenario3_ResetPINT<Scenario3_ResetPIN, implementation::Scenario3_ResetPIN>
00031     {
00032     };
00033 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HomeController Member List

This is the complete list of members for HomeController, including all inherited members.
Index() HomeController [inline]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Level1 Member List

This is the complete list of members for Level1, including all inherited members.
Initialize(std::vector< std::shared_ptr< GameObject >> const &objects) override | Level1 | [virtual]
Level1() | Level1 |
LoadState(PersistentState &state) | Level | [virtual]
m_objective | Level | [protected]
m_timeLimit | Level | [protected]
Objective() | Level |
SaveState(PersistentState &state) | Level | [virtual]
TimeLimit() | Level |
Update(float time, float elapsedTime, float timeRemaining, std::vector< std::shared_ptr< GameObject >> const &objects) | Level | [virtual]
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: GlobalizationPreferences/cppwinrt/pch.cpp Source File

  • GlobalizationPreferences
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Facebook Member List

This is the complete list of members for Scenario1_Facebook, including all inherited members.
authzInProgress | Scenario1_Facebook | [private]
GetFacebookUserNameAsync(string responseData) | Scenario1_Facebook | [inline, private]
Launch_Click(object sender, RoutedEventArgs e) | Scenario1_Facebook | [inline, private]
rootPage | Scenario1_Facebook | [private]
Scenario1_Facebook() | Scenario1_Facebook | [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/Scenario4.xaml.h Source File

  • SimpleInk
  • cpp

Scenario4.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario4 sealed
00024     {
00025     public:
00026         Scenario4();
00027         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00028
00029     private:
00030         void OnSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs e);
00031         void OnRecognizerChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032         void OnRecognizeAsync(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033
00034         void OnClear(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         bool SetRecognizerByName(Platform::String^ recognizerName);
00036         void TextServiceManager_InputLanguageChanged(Windows::UI::Text::Core::CoreTextServicesManager^ sender, Platform::Object^ args);
00037         void SetDefaultRecognizerByCurrentInputMethodLanguageTag();
00038         void Scenario4::RecoButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039
00040         MainPage^ rootPage = MainPage::Current;
00041
00042         Windows::UI::Input::Inking::InkRecognizerContainer^ inkRecognizerContainer;
00043         Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkRecognizer^>^ recoView;
00044         Windows::Globalization::Language^ previousInputLanguage;
00045         Windows::UI::Text::Core::CoreTextServicesManager^ textServiceManager;
00046         Windows::Foundation::EventRegistrationToken languageChangedToken{};
00047     };
00048 }
Generated on Fri Nov 15 2024 22:18:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Nfc/Nfc/App.xaml.cs Source File

  • Nfc
  • Nfc

App.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel;
00014 using Windows.ApplicationModel.Activation;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018 using NfcSample;
00019
00020 // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// Provides application-specific behavior to supplement the default Application class.
00026     /// </summary>
00027     sealed partial class App : Application
00028     {
00029         public LaunchActivatedEventArgs LaunchArgs;
00030         /// <summary>
00031         /// Initializes the singleton application object.  This is the first line of authored code
00032         /// executed, and as such is the logical equivalent of main() or WinMain().
00033         /// </summary>
00034         public App()
00035         {
00036             this.InitializeComponent();
00037             this.Suspending += OnSuspending;
00038             this.UnhandledException += App_UnhandledException;
00039         }
00040
00041         private async void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
00042         {
00043             var msgbox = new Windows.UI.Popups.MessageDialog("Unhandled exception: " + e.Exception.ToString());
00044             msgbox.Commands.Add(new Windows.UI.Popups.UICommand("close"));
00045             await msgbox.ShowAsync();
00046         }
00047
00048         /// <summary>
00049         /// Invoked when the application is launched normally by the end user.  Other entry points
00050         /// will be used such as when the application is launched to open a specific file.
00051         /// </summary>
00052         /// <param name="e">Details about the launch request and process.</param>
00053         protected override void OnLaunched(LaunchActivatedEventArgs e)
00054         {
00055             this.LaunchArgs = e;
00056             System.Diagnostics.Debug.WriteLine("OnLaunched Arguments: " + e.Arguments);
00057 #if DEBUG
00058             if (System.Diagnostics.Debugger.IsAttached)
00059             {
00060                 this.DebugSettings.EnableFrameRateCounter = false;
00061             }
00062 #endif
00063
00064             Frame rootFrame = Window.Current.Content as Frame;
00065
00066             // Do not repeat app initialization when the Window already has content,
00067             // just ensure that the window is active
00068             if (rootFrame == null)
00069             {
00070                 // Create a Frame to act as the navigation context and navigate to the first page
00071                 rootFrame = new Frame();
00072                 // Set the default language
00073                 rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
00074
00075                 rootFrame.NavigationFailed += OnNavigationFailed;
00076
00077                 if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
00078                 {
00079                     //TODO: Load state from previously suspended application
00080                 }
00081
00082                 // Place the frame in the current Window
00083                 Window.Current.Content = rootFrame;
00084             }
00085
00086             if (!string.IsNullOrWhiteSpace(e.Arguments)
00087                 && e.Arguments.StartsWith("Receipt^"))
00088             {
00089                 // We're being launched/navigated to as a result of a tap, so show the results
00090                 rootFrame.Navigate(typeof(ReceiptView), e.Arguments);
00091             }
00092             else if (rootFrame.Content == null
00093                 || rootFrame.Content.GetType() != typeof(MainPage))
00094             {
00095                 // When the navigation stack isn't restored navigate to the first page,
00096                 // configuring the new page by passing required information as a navigation
00097                 // parameter
00098                 rootFrame.Navigate(typeof(MainPage), e.Arguments);
00099             }
00100             // Ensure the current window is active
00101             Window.Current.Activate();
00102         }
00103
00104         /// <summary>
00105         /// Invoked when Navigation to a certain page fails
00106         /// </summary>
00107         /// <param name="sender">The Frame which failed navigation</param>
00108         /// <param name="e">Details about the navigation failure</param>
00109         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00110         {
00111             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00112         }
00113
00114         /// <summary>
00115         /// Invoked when application execution is being suspended.  Application state is saved
00116         /// without knowing whether the application will be terminated or resumed with the contents
00117         /// of memory still intact.
00118         /// </summary>
00119         /// <param name="sender">The source of the suspend request.</param>
00120         /// <param name="e">Details about the suspend request.</param>
00121         private void OnSuspending(object sender, SuspendingEventArgs e)
00122         {
00123             var deferral = e.SuspendingOperation.GetDeferral();
00124             //TODO: Save application state and stop any background activity
00125             deferral.Complete();
00126         }
00127     }
00128 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Gyrometer/cpp/Scenario1_DataEvents.xaml.cpp Source File

  • Gyrometer
  • cpp

Scenario1_DataEvents.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_DataEvents.xaml.cpp
00014 // Implementation of the Scenario1_DataEvents class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario1_DataEvents.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::Devices::Sensors;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::UI::Core;
00028 using namespace Platform;
00029
00030 Scenario1_DataEvents::Scenario1_DataEvents() : rootPage(MainPage::Current), desiredReportInterval(0)
00031 {
00032     InitializeComponent();
00033
00034     gyrometer = Gyrometer::GetDefault();
00035     if (gyrometer != nullptr)
00036     {
00037         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00038         // This value will be used later to activate the sensor.
00039         uint32 minReportInterval = gyrometer->MinimumReportInterval;
00040         desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00041     }
00042     else
00043     {
00044         rootPage->NotifyUser("No gyrometer found", NotifyType::ErrorMessage);
00045     }
00046 }
00047
00048 /// <summary>
00049 /// Invoked when this page is about to be displayed in a Frame.
00050 /// </summary>
00051 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00052 /// property is typically used to configure the page.</param>
00053 void Scenario1_DataEvents::OnNavigatedTo(NavigationEventArgs^ e)
00054 {
00055     ScenarioEnableButton->IsEnabled = true;
00056     ScenarioDisableButton->IsEnabled = false;
00057 }
00058
00059 /// <summary>
00060 /// Invoked when this page is no longer displayed.
00061 /// </summary>
00062 /// <param name="e"></param>
00063 void Scenario1_DataEvents::OnNavigatedFrom(NavigationEventArgs^ e)
00064 {
00065     // If the navigation is external to the app do not clean up.
00066     // This can occur on Phone when suspending the app.
00067     if (e->NavigationMode == NavigationMode::Forward && e->Uri == nullptr)
00068     {
00069         return;
00070     }
00071
00072     if (ScenarioDisableButton->IsEnabled)
00073     {
00074         Window::Current->VisibilityChanged::remove(visibilityToken);
00075         gyrometer->ReadingChanged::remove(readingToken);
00076
00077         // Restore the default report interval to release resources while the sensor is not in use
00078         gyrometer->ReportInterval = 0;
00079     }
00080 }
00081
00082 /// <summary>
00083 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00084 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00085 /// </summary>
00086 /// <param name="sender"></param>
00087 /// <param name="e">
00088 /// Event data that can be examined for the current visibility state.
00089 /// </param>
00090 void Scenario1_DataEvents::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00091 {
00092     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00093     if (ScenarioDisableButton->IsEnabled)
00094     {
00095         if (e->Visible)
00096         {
00097             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00098             readingToken = gyrometer->ReadingChanged::add(ref new TypedEventHandler<Gyrometer^, GyrometerReadingChangedEventArgs^>(this, &Scenario1_DataEvents::ReadingChanged));
00099         }
00100         else
00101         {
00102             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00103             gyrometer->ReadingChanged::remove(readingToken);
00104         }
00105     }
00106 }
00107
00108 void Scenario1_DataEvents::ReadingChanged(Gyrometer^ sender, GyrometerReadingChangedEventArgs^ e)
00109 {
00110     // We need to dispatch to the UI thread to display the output
00111     Dispatcher->RunAsync(
00112         CoreDispatcherPriority::Normal,
00113         ref new DispatchedHandler(
00114             [this, e]()
00115             {
00116                 GyrometerReading^ reading = e->Reading;
00117
00118                 ScenarioOutput_X->Text = reading->AngularVelocityX.ToString();
00119                 ScenarioOutput_Y->Text = reading->AngularVelocityY.ToString();
00120                 ScenarioOutput_Z->Text = reading->AngularVelocityZ.ToString();
00121             },
00122             CallbackContext::Any
00123             )
00124         );
00125 }
00126
00127 void Scenario1_DataEvents::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00128 {
00129     if (gyrometer != nullptr)
00130     {
00131         // Establish the report interval
00132         gyrometer->ReportInterval = desiredReportInterval;
00133
00134         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario1_DataEvents::VisibilityChanged));
00135         readingToken = gyrometer->ReadingChanged::add(ref new TypedEventHandler<Gyrometer^, GyrometerReadingChangedEventArgs^>(this, &Scenario1_DataEvents::ReadingChanged));
00136
00137         ScenarioEnableButton->IsEnabled = false;
00138         ScenarioDisableButton->IsEnabled = true;
00139     }
00140     else
00141     {
00142         rootPage->NotifyUser("No gyrometer found", NotifyType::ErrorMessage);
00143     }
00144 }
00145
00146 void Scenario1_DataEvents::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00147 {
00148     Window::Current->VisibilityChanged::remove(visibilityToken);
00149     gyrometer->ReadingChanged::remove(readingToken);
00150
00151     // Restore the default report interval to release resources while the sensor is not in use
00152     gyrometer->ReportInterval = 0;
00153
00154     ScenarioEnableButton->IsEnabled = true;
00155     ScenarioDisableButton->IsEnabled = false;
00156 }
Generated on Fri Nov 15 2024 22:17:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cs/Scenario1.xaml.cs Source File

  • Logging
  • cs

Scenario1.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015
00016 namespace SDKTemplate
00017 {
00018     public sealed partial class Scenario1 : Page
00019     {
00020         private MainPage rootPage;
00021
00022         public Scenario1()
00023         {
00024             this.InitializeComponent();
00025         }
00026
00027         protected override void OnNavigatedTo(NavigationEventArgs e)
00028         {
00029             rootPage = MainPage.Current;
00030         }
00031
00032         /// <summary>
00033         /// This method demonstrates logging with a LoggingChannel constructed
00034         /// in Windows 8.1 compatibility mode.
00035         /// </summary>
00036         private void DoWin81Mode(object sender, RoutedEventArgs e)
00037         {
00038             new LoggingChannelScenario().LogWithWin81Constructor();
00039             this.rootPage.NotifyUser("Complete: Windows 8.1 mode", NotifyType.StatusMessage);
00040         }
00041
00042         /// <summary>
00043         /// This method demonstrates logging with a LoggingChannel constructed
00044         /// in Windows 10 enhanced mode.
00045         /// </summary>
00046         private void DoWin10Mode(object sender, RoutedEventArgs e)
00047         {
00048             new LoggingChannelScenario().LogWithWin10Constructor();
00049             this.rootPage.NotifyUser("Complete: Windows 10 mode", NotifyType.StatusMessage);
00050         }
00051     }
00052 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Content/VideoFrameProcessor.h Source File

  • HolographicFaceTracking
  • cpp
  • Content

VideoFrameProcessor.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace HolographicFaceTracker
00015 {
00016     // Class to manage receiving video frames from Windows::Media::Capture
00017     class VideoFrameProcessor
00018     {
00019     public:
00020         static Concurrency::task<std::shared_ptr<VideoFrameProcessor>> CreateAsync(void);
00021
00022         VideoFrameProcessor(
00023             Platform::Agile<Windows::Media::Capture::MediaCapture> mediaCapture,
00024             Windows::Media::Capture::Frames::MediaFrameReader^ reader,
00025             Windows::Media::Capture::Frames::MediaFrameSource^ source);
00026
00027         Windows::Media::Capture::Frames::MediaFrameReference^ GetLatestFrame(void) const;
00028         Windows::Media::Capture::Frames::VideoMediaFrameFormat^ GetCurrentFormat(void) const;
00029
00030     protected:
00031         void OnFrameArrived(
00032             Windows::Media::Capture::Frames::MediaFrameReader^ sender,
00033             Windows::Media::Capture::Frames::MediaFrameArrivedEventArgs^ args);
00034
00035         Platform::Agile<Windows::Media::Capture::MediaCapture> m_mediaCapture;
00036         Windows::Media::Capture::Frames::MediaFrameReader^     m_mediaFrameReader;
00037
00038         mutable std::shared_mutex                              m_propertiesLock;
00039         Windows::Media::Capture::Frames::MediaFrameSource^     m_mediaFrameSource;
00040         Windows::Media::Capture::Frames::MediaFrameReference^  m_latestFrame;
00041     };
00042 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LockScreenApps/cs/Scenario2_Notifications.xaml.cs Source File

  • LockScreenApps
  • cs

Scenario2_Notifications.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using NotificationsExtensions;
00013 using NotificationsExtensions.Badges;
00014 using NotificationsExtensions.Tiles;
00015 using Windows.Data.Xml.Dom;
00016 using Windows.UI.Notifications;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario2_Notifications : Page
00023     {
00024         MainPage rootPage = MainPage.Current;
00025
00026         public Scenario2_Notifications()
00027         {
00028             InitializeComponent();
00029         }
00030
00031         private void ClearBadge_Click(object sender, RoutedEventArgs e)
00032         {
00033             BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear();
00034             rootPage.NotifyUser("Badge notification cleared", NotifyType.StatusMessage);
00035         }
00036
00037         private void SendBadge_Click(object sender, RoutedEventArgs e)
00038         {
00039             BadgeNumericNotificationContent badgeContent = new BadgeNumericNotificationContent(6);
00040             BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(new BadgeNotification(badgeContent.GetXml()));
00041             rootPage.NotifyUser("Badge notification sent", NotifyType.StatusMessage);
00042         }
00043
00044         private void SendBadgeWithStringManipulation_Click(object sender, RoutedEventArgs e)
00045         {
00046             string badgeXmlString = "<badge value='6'/>";
00047             XmlDocument badgeDOM = new XmlDocument();
00048             badgeDOM.LoadXml(badgeXmlString);
00049             BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(new BadgeNotification(badgeDOM));
00050             rootPage.NotifyUser("Badge notification sent", NotifyType.StatusMessage);
00051         }
00052
00053         private void SendTile_Click(object sender, RoutedEventArgs e)
00054         {
00055             var tileDOM = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150SmallImageAndText03);
00056             tileDOM.SelectSingleNode("//image[@id=1]/@src").NodeValue = "'ms-appx:///Assets/tile-sdk.png";
00057             tileDOM.SelectSingleNode("//text[@id=1]").InnerText = "This tile notification has an image, but it won't be displayed on the lock screen";
00058
00059             TileUpdateManager.CreateTileUpdaterForApplication().Update(new TileNotification(tileDOM));
00060
00061             rootPage.NotifyUser("Tile notification sent", NotifyType.StatusMessage);
00062         }
00063
00064         private void SendTileWithStringManipulation_Click(object sender, RoutedEventArgs e)
00065         {
00066             string tileXmlString = "<tile>"
00067                                  + "<visual version='2'>"
00068                                  + "<binding template='TileWide310x150SmallImageAndText03' fallback='TileWideSmallImageAndText03'>"
00069                                  + "<image id='1' src='ms-appx:///Assets/tile-sdk.png'/>"
00070                                  + "<text id='1'>This tile notification has an image, but it won't be displayed on the lock screen</text>"
00071                                  + "</binding>"
00072                                  + "</visual>"
00073                                  + "</tile>";
00074
00075             XmlDocument tileDOM = new XmlDocument();
00076             tileDOM.LoadXml(tileXmlString);
00077             TileUpdateManager.CreateTileUpdaterForApplication().Update(new TileNotification(tileDOM));
00078             rootPage.NotifyUser("Tile notification sent", NotifyType.StatusMessage);
00079         }
00080
00081         private void ClearTile_Click(object sender, RoutedEventArgs e)
00082         {
00083             TileUpdateManager.CreateTileUpdaterForApplication().Clear();
00084             rootPage.NotifyUser("Tile notification cleared", NotifyType.StatusMessage);
00085         }
00086     }
00087 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cs/BackgroundTask/Scenario3_ServicingCompleteTask.xaml.cs Source File

  • BackgroundTask
  • cs
  • BackgroundTask

Scenario3_ServicingCompleteTask.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using SDKTemplate;
00014 using Windows.ApplicationModel.Background;
00015 using Windows.Storage;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class ServicingCompleteTask : Page
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         MainPage rootPage = MainPage.Current;
00033
00034         public ServicingCompleteTask()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         /// <summary>
00040         /// Invoked when this page is about to be displayed in a Frame.
00041         /// </summary>
00042         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00043         /// property is typically used to configure the page.</param>
00044         protected override void OnNavigatedTo(NavigationEventArgs e)
00045         {
00046             foreach (var task in BackgroundTaskRegistration.AllTasks)
00047             {
00048                 if (task.Value.Name == BackgroundTaskSample.ServicingCompleteTaskName)
00049                 {
00050                     AttachProgressAndCompletedHandlers(task.Value);
00051                     BackgroundTaskSample.UpdateBackgroundTaskRegistrationStatus(BackgroundTaskSample.ServicingCompleteTaskName, true);
00052                     break;
00053                 }
00054             }
00055
00056             UpdateUI();
00057         }
00058
00059         /// <summary>
00060         /// Register a ServicingCompleteTask.
00061         /// </summary>
00062         /// <param name="sender"></param>
00063         /// <param name="e"></param>
00064         private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
00065         {
00066             var task = BackgroundTaskSample.RegisterBackgroundTask(BackgroundTaskSample.ServicingCompleteTaskEntryPoint,
00067                                                                    BackgroundTaskSample.ServicingCompleteTaskName,
00068                                                                    new SystemTrigger(SystemTriggerType.ServicingComplete, false),
00069                                                                    null);
00070             AttachProgressAndCompletedHandlers(task);
00071             UpdateUI();
00072         }
00073
00074         /// <summary>
00075         /// Unregister a ServicingCompleteTask.
00076         /// </summary>
00077         /// <param name="sender"></param>
00078         /// <param name="e"></param>
00079         private void UnregisterBackgroundTask(object sender, RoutedEventArgs e)
00080         {
00081             BackgroundTaskSample.UnregisterBackgroundTasks(BackgroundTaskSample.ServicingCompleteTaskName);
00082             UpdateUI();
00083         }
00084
00085         /// <summary>
00086         /// Attach progress and completed handers to a background task.
00087         /// </summary>
00088         /// <param name="task">The task to attach progress and completed handlers to.</param>
00089         private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
00090         {
00091             task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
00092             task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
00093         }
00094
00095         /// <summary>
00096         /// Handle background task progress.
00097         /// </summary>
00098         /// <param name="task">The task that is reporting progress.</param>
00099         /// <param name="e">Arguments of the progress report.</param>
00100         private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
00101         {
00102             var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00103             {
00104                 var progress = "Progress: " + args.Progress + "%";
00105                 BackgroundTaskSample.ServicingCompleteTaskProgress = progress;
00106                 UpdateUI();
00107             });
00108         }
00109
00110         /// <summary>
00111         /// Handle background task completion.
00112         /// </summary>
00113         /// <param name="task">The task that is reporting completion.</param>
00114         /// <param name="e">Arguments of the completion report.</param>
00115         private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
00116         {
00117             UpdateUI();
00118         }
00119
00120         /// <summary>
00121         /// Update the scenario UI.
00122         /// </summary>
00123         private async void UpdateUI()
00124         {
00125             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00126             () =>
00127             {
00128                 RegisterButton.IsEnabled = !BackgroundTaskSample.ServicingCompleteTaskRegistered;
00129                 UnregisterButton.IsEnabled = BackgroundTaskSample.ServicingCompleteTaskRegistered;
00130                 Progress.Text = BackgroundTaskSample.ServicingCompleteTaskProgress;
00131                 Status.Text = BackgroundTaskSample.GetBackgroundTaskStatus(BackgroundTaskSample.ServicingCompleteTaskName);
00132             });
00133         }
00134
00135     }
00136 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Check Member List

This is the complete list of members for Scenario1_Check, including all inherited members.
locationCapability | Scenario1_Check | [private]
OnCapabilityAccessChanged(AppCapability sender, object e) | Scenario1_Check | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_Check | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_Check | [inline, protected]
rootPage | Scenario1_Check | [private]
Scenario1_Check() | Scenario1_Check | [inline]
StreamLocationAsync() | Scenario1_Check | [inline, private]
StreamLocationButton_Click(object sender, RoutedEventArgs e) | Scenario1_Check | [inline, private]
UpdateCapabilityStatus() | Scenario1_Check | [inline, private]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cpp/SampleConfiguration.cpp Source File

  • FileThumbnails
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace Platform;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Storage;
00012 using namespace Windows::Storage::FileProperties;
00013 using namespace Windows::UI::ViewManagement;
00014 using namespace Windows::UI::Xaml::Controls;
00015 using namespace Windows::UI::Xaml::Media::Imaging;
00016
00017 Array<Scenario>^ MainPage::scenariosInner = ref new Array<Scenario>
00018 {
00019     { "Display a thumbnail for a picture",    "SDKTemplate.Scenario1" },
00020     { "Display album art for a song",         "SDKTemplate.Scenario2" },
00021     { "Display an icon for a document",       "SDKTemplate.Scenario3" },
00022     { "Display a thumbnail for a folder",     "SDKTemplate.Scenario4" },
00023     { "Display a thumbnail for a file group", "SDKTemplate.Scenario5" },
00024     { "Display a scaled image",               "SDKTemplate.Scenario6" },
00025 };
00026
00027 String^ Errors::NoExifThumbnail   = "No result (no EXIF thumbnail or cached thumbnail available for fast retrieval)";
00028 String^ Errors::NoThumbnail       = "No result (no thumbnail could be obtained from the selected file)";
00029 String^ Errors::NoAlbumArt        = "No result (no album art available for this song)";
00030 String^ Errors::NoIcon            = "No result (no icon available for this document type)";
00031 String^ Errors::NoImages          = "No result (no thumbnail could be obtained from the selected folder - make sure that the folder contains images)";
00032 String^ Errors::FileGroupEmpty    = "No result (unexpected error: retrieved file group was null)";
00033 String^ Errors::FileGroupLocation = "File groups are only available for library locations, please select a folder from one of your libraries";
00034 String^ Errors::Cancel            = "No result (operation cancelled, no item selected)";
00035 String^ Errors::InvalidSize       = "Invalid size (specified size must be numerical and greater than zero)";
00036
00037 Array<String^>^ FileExtensions::Document = ref new Array<String^>
00038 {
00039     ".doc",
00040     ".docx",
00041     ".xls",
00042     ".xlsx",
00043     ".ppt",
00044     ".pptx",
00045     ".pdf",
00046     ".txt",
00047     ".rtf",
00048 };
00049
00050 Array<String^>^ FileExtensions::Image = ref new Array<String^>
00051 {
00052     ".jpg",
00053     ".png",
00054     ".bmp",
00055     ".gif",
00056     ".tif",
00057 };
00058
00059 Array<String^>^ FileExtensions::Music = ref new Array<String^>
00060 {
00061     ".mp3",
00062     ".wma",
00063     ".m4a",
00064     ".aac",
00065 };
00066
00067 BitmapImage^ MainPage::GetPlaceHolderImage()
00068 {
00069     if (_placeholder == nullptr)
00070     {
00071         _placeholder = ref new BitmapImage(ref new Uri(BaseUri->AbsoluteUri, "Assets/placeholder-sdk.png"));
00072     }
00073
00074     return _placeholder;
00075 }
00076
00077
00078
00079 void MainPage::ResetOutput(Image^ image, TextBlock^ output, TextBlock^ outputDetails)
00080 {
00081     image->Source = GetPlaceHolderImage();
00082     NotifyUser("", NotifyType::ErrorMessage);
00083     NotifyUser("", NotifyType::StatusMessage);
00084     output->Text = "";
00085     if (outputDetails != nullptr)
00086     {
00087         outputDetails->Text = "";
00088     }
00089 }
00090
00091 void MainPage::DisplayResult(Image^ image, TextBlock^ textBlock, String^ thumbnailModeName, size_t size, IStorageItem^ item, StorageItemThumbnail^ thumbnail, bool isGroup)
00092 {
00093     BitmapImage^ bitmapImage = ref new BitmapImage();
00094
00095     bitmapImage->SetSource(thumbnail);
00096     image->Source = bitmapImage;
00097
00098     String^ itemType = isGroup ? "Group" : item->IsOfType(StorageItemTypes::File) ? "File" : "Folder";
00099     textBlock->Text = "ThumbnailMode." + thumbnailModeName + "\n"
00100         + itemType + " used: " + item->Name + "\n"
00101         + "Requested size: " + size.ToString() + "\n"
00102         + "Returned size: " + thumbnail->OriginalWidth.ToString() + "x" + thumbnail->OriginalHeight.ToString();
00103 }
Generated on Fri Nov 15 2024 22:17:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cppwinrt/Scenario2_MultipleScanners.cpp Source File

  • BarcodeScanner
  • cppwinrt

Scenario2_MultipleScanners.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013
00014 #include "Scenario2_MultipleScanners.h"
00015 #include "Scenario2_MultipleScanners.g.cpp"
00016
00017 namespace winrt
00018 {
00019     using namespace Windows::Devices;
00020     using namespace Windows::Devices::Enumeration;
00021     using namespace Windows::Devices::PointOfService;
00022     using namespace Windows::Foundation;
00023     using namespace Windows::UI;
00024     using namespace Windows::UI::Xaml;
00025     using namespace Windows::UI::Xaml::Controls;
00026     using namespace Windows::UI::Xaml::Media;
00027     using namespace Windows::UI::Xaml::Navigation;
00028 }
00029
00030 namespace winrt::SDKTemplate::implementation
00031 {
00032
00033     Scenario2_MultipleScanners::Scenario2_MultipleScanners()
00034     {
00035         InitializeComponent();
00036     }
00037
00038     /// <summary>
00039     /// Invoked when this page is no longer displayed.
00040     /// </summary>
00041     /// <param name="e">Event data that describes how this page was exited.  The Parameter
00042     /// property is typically used to configure the page.</param>
00043     void Scenario2_MultipleScanners::OnNavigatedFrom(NavigationEventArgs const&)
00044     {
00045         ResetTheScenarioState();
00046     }
00047
00048     /// <summary>
00049     /// Invoked when this page is about to be displayed in a Frame.
00050     /// </summary>
00051     /// <param name="e">Event data that describes how this page was reached.  The Parameter
00052     /// property is typically used to configure the page.</param>
00053     void Scenario2_MultipleScanners::OnNavigatedTo(NavigationEventArgs const&)
00054     {
00055         ResetTheScenarioState();
00056     }
00057
00058     /// <summary>
00059     /// This is the click handler for the 'ScenarioStartScanningInstance1' button. It initiates creation of scanner instance 1.
00060     /// </summary>
00061     fire_and_forget Scenario2_MultipleScanners::ButtonStartScanningInstance1_Click(IInspectable const&, RoutedEventArgs const&)
00062     {
00063         auto lifetime = get_strong();
00064
00065         //Get the handle to the default scanner
00066         if (co_await CreateDefaultScannerObjectAsync(BarcodeScannerInstance::Instance1))
00067         {
00068             //Claim the scanner
00069             if (co_await ClaimBarcodeScannerAsync(BarcodeScannerInstance::Instance1))
00070             {
00071                 //add the event handlers
00072                 m_dev1ReleaseRequestedToken = m_claimedBarcodeScannerInstance1.ReleaseDeviceRequested({ get_weak(), &Scenario2_MultipleScanners::claimedBarcodeScannerInstance1_ReleaseDeviceRequested });
00073                 m_dev1DataReceivedToken = m_claimedBarcodeScannerInstance1.DataReceived({ get_weak(), &Scenario2_MultipleScanners::claimedBarcodeScannerInstance1_DataReceived });
00074                 m_claimedBarcodeScannerInstance1.IsDecodeDataEnabled(true);
00075
00076                 //Enable the Scanner
00077                 if (co_await EnableBarcodeScannerAsync(BarcodeScannerInstance::Instance1))
00078                 {
00079                     //Set the UI state
00080                     ResetUI();
00081                     SetUI(BarcodeScannerInstance::Instance1);
00082                 }
00083             }
00084             else
00085             {
00086                 if (m_barcodeScannerInstance1)
00087                 {
00088                     m_barcodeScannerInstance1.Close();
00089                     m_barcodeScannerInstance1 = nullptr;
00090                 }
00091             }
00092         }
00093     }
00094
00095     /// <summary>
00096     /// This method is called upon when a claim request is made on instance 1. If a retain request was placed on the device it rejects the new claim.
00097     /// </summary>
00098     fire_and_forget Scenario2_MultipleScanners::claimedBarcodeScannerInstance1_ReleaseDeviceRequested(IInspectable const&, ClaimedBarcodeScanner const&)
00099     {
00100         auto lifetime = get_strong();
00101
00102         co_await resume_foreground(Dispatcher());
00103
00104         //check if the instance wants to retain the device
00105         if (Retain1().IsChecked().Value())
00106         {
00107             try
00108             {
00109                 //Retain the device
00110                 m_claimedBarcodeScannerInstance1.RetainDevice();
00111             }
00112             catch (hresult_error const& exception)
00113             {
00114                 m_rootPage.NotifyUser(L"Retain instance 1 failed: " + exception.message(), NotifyType::ErrorMessage);
00115             }
00116         }
00117         //Release the device
00118         else
00119         {
00120             m_claimedBarcodeScannerInstance1.Close();
00121             m_claimedBarcodeScannerInstance1 = nullptr;
00122
00123             if (m_barcodeScannerInstance1)
00124             {
00125                 m_barcodeScannerInstance1.Close();
00126                 m_barcodeScannerInstance1 = nullptr;
00127             }
00128         }
00129     }
00130
00131     /// <summary>
00132     /// This is the click handler for the 'ScenarioStartScanningInstance2' button. Initiates creation of scanner instance 2
00133     /// </summary>
00134     fire_and_forget Scenario2_MultipleScanners::ButtonStartScanningInstance2_Click(IInspectable const&, RoutedEventArgs const&)
00135     {
00136         auto lifetime = get_strong();
00137
00138         //Get the handle to the default scanner
00139         if (co_await CreateDefaultScannerObjectAsync(BarcodeScannerInstance::Instance2))
00140         {
00141             //Claim the scanner
00142             if (co_await ClaimBarcodeScannerAsync(BarcodeScannerInstance::Instance2))
00143             {
00144                 //set the handlers
00145                 m_dev2ReleaseRequestedToken = m_claimedBarcodeScannerInstance2.ReleaseDeviceRequested({ get_weak(), &Scenario2_MultipleScanners::claimedBarcodeScannerInstance2_ReleaseDeviceRequested });
00146                 m_dev2DataReceivedToken = m_claimedBarcodeScannerInstance2.DataReceived({ get_weak(), &Scenario2_MultipleScanners::claimedBarcodeScannerInstance2_DataReceived });
00147
00148                 //enable the scanner to decode the scanned data
00149                 m_claimedBarcodeScannerInstance2.IsDecodeDataEnabled(true);
00150
00151                 //Enable the Scanner
00152                 if (co_await EnableBarcodeScannerAsync(BarcodeScannerInstance::Instance2))
00153                 {
00154                     //Set the UI state
00155                     ResetUI();
00156                     SetUI(BarcodeScannerInstance::Instance2);
00157                 }
00158             }
00159             else
00160             {
00161                 if (m_barcodeScannerInstance2)
00162                 {
00163                     m_barcodeScannerInstance2.Close();
00164                     m_barcodeScannerInstance2 = nullptr;
00165                 }
00166             }
00167         }
00168     }
00169
00170     /// <summary>
00171     /// This method is called upon when a claim request is made on instance 2. If a retain request was placed on the device it rejects the new claim.
00172     /// </summary>
00173     fire_and_forget Scenario2_MultipleScanners::claimedBarcodeScannerInstance2_ReleaseDeviceRequested(IInspectable const&, ClaimedBarcodeScanner const&)
00174     {
00175         auto lifetime = get_strong();
00176
00177         co_await resume_foreground(Dispatcher());
00178
00179         //check if the instance wants to retain the device
00180         if (Retain2().IsChecked().Value())
00181         {
00182             try
00183             {
00184                 //Retain the device
00185                 m_claimedBarcodeScannerInstance2.RetainDevice();
00186             }
00187             catch (hresult_error const& exception)
00188             {
00189                 m_rootPage.NotifyUser(L"Retain instance 2 failed: " + exception.message(), NotifyType::ErrorMessage);
00190             }
00191         }
00192         //Release the device
00193         else
00194         {
00195             m_claimedBarcodeScannerInstance2.Close();
00196             m_claimedBarcodeScannerInstance2 = nullptr;
00197
00198             if (m_barcodeScannerInstance2)
00199             {
00200                 m_barcodeScannerInstance2.Close();
00201                 m_barcodeScannerInstance2 = nullptr;
00202             }
00203         }
00204     }
00205
00206     /// <summary>
00207     /// This is the click handler for the 'ScenarioEndScanningInstance1' button.
00208     /// Initiates the disposal of scanner instance 1.
00209     /// </summary>
00210     void Scenario2_MultipleScanners::ButtonEndScanningInstance1_Click(IInspectable const&, RoutedEventArgs const&)
00211     {
00212         if (m_claimedBarcodeScannerInstance1)
00213         {
00214             //remove the event handlers
00215             m_claimedBarcodeScannerInstance1.ReleaseDeviceRequested(m_dev1ReleaseRequestedToken);
00216             m_claimedBarcodeScannerInstance1.DataReceived(m_dev1DataReceivedToken);
00217
00218             //dispose the instance
00219             m_claimedBarcodeScannerInstance1.Close();
00220             m_claimedBarcodeScannerInstance1 = nullptr;
00221         }
00222
00223         if (m_barcodeScannerInstance1)
00224         {
00225             m_barcodeScannerInstance1.Close();
00226             m_barcodeScannerInstance1 = nullptr;
00227         }
00228
00229         //reset the UI
00230
00231         ResetUI();
00232
00233         m_rootPage.NotifyUser(L"Click a start scanning button to begin.", NotifyType::StatusMessage);
00234     }
00235
00236     /// <summary>
00237     /// This is the click handler for the 'ScenarioEndScanningInstance2' button.
00238     /// Initiates the disposal fo scanner instance 2.
00239     /// </summary>
00240     void Scenario2_MultipleScanners::ButtonEndScanningInstance2_Click(IInspectable const&, RoutedEventArgs const&)
00241     {
00242         if (m_claimedBarcodeScannerInstance2)
00243         {
00244             //remove the event handlers
00245             m_claimedBarcodeScannerInstance2.ReleaseDeviceRequested(m_dev2ReleaseRequestedToken);
00246             m_claimedBarcodeScannerInstance2.DataReceived(m_dev2DataReceivedToken);
00247
00248             //dispose the instance
00249             m_claimedBarcodeScannerInstance2.Close();
00250             m_claimedBarcodeScannerInstance2 = nullptr;
00251         }
00252
00253         if (m_barcodeScannerInstance2)
00254         {
00255             m_barcodeScannerInstance2.Close();
00256             m_barcodeScannerInstance2 = nullptr;
00257         }
00258
00259         //reset the UI
00260         ResetUI();
00261
00262         m_rootPage.NotifyUser(L"Click a start scanning button to begin.", NotifyType::StatusMessage);
00263     }
00264
00265     /// <summary>
00266     /// This method returns the first available Barcode Scanner. To enumerate and find a particular device use the device enumeration code.
00267     /// </summary>
00268     /// <returns>a boolean value based on whether it found a compatible scanner connected</returns>
00269
00270     IAsyncOperation<bool> Scenario2_MultipleScanners::CreateDefaultScannerObjectAsync(BarcodeScannerInstance instance)
00271     {
00272         auto lifetime = get_strong();
00273
00274         BarcodeScanner scanner = co_await BarcodeScanner::GetDefaultAsync();
00275
00276         if (!scanner)
00277         {
00278             m_rootPage.NotifyUser(L"Barcode scanner not found. Please connect a barcode scanner.", NotifyType::ErrorMessage);
00279             co_return false;
00280         }
00281
00282         switch (instance)
00283         {
00284         case BarcodeScannerInstance::Instance1:
00285             m_barcodeScannerInstance1 = scanner;
00286             break;
00287         case BarcodeScannerInstance::Instance2:
00288             m_barcodeScannerInstance2 = scanner;
00289             break;
00290         default:
00291             co_return false;
00292         }
00293
00294         co_return true;
00295     }
00296
00297     /// <summary>
00298     /// This method claims the connected scanner.
00299     /// </summary>
00300     /// <returns>a boolean based on whether it was able to claim the scanner.</returns>
00301
00302     IAsyncOperation<bool> Scenario2_MultipleScanners::ClaimBarcodeScannerAsync(BarcodeScannerInstance instance)
00303     {
00304         auto lifetime = get_strong();
00305         bool claimAsyncStatus = false;
00306         //select the instance to claim
00307         switch (instance)
00308         {
00309         case BarcodeScannerInstance::Instance1:
00310
00311             m_claimedBarcodeScannerInstance1 = co_await m_barcodeScannerInstance1.ClaimScannerAsync();
00312             if (!m_claimedBarcodeScannerInstance1)
00313                 m_rootPage.NotifyUser(L"Instance 1 claim barcode scanner failed.", NotifyType::ErrorMessage);
00314             else
00315                 claimAsyncStatus = true;
00316             break;
00317
00318         case BarcodeScannerInstance::Instance2:
00319
00320             m_claimedBarcodeScannerInstance2 = co_await m_barcodeScannerInstance2.ClaimScannerAsync();
00321             if (!m_claimedBarcodeScannerInstance2)
00322                 m_rootPage.NotifyUser(L"Instance 2 claim barcode scanner failed.", NotifyType::ErrorMessage);
00323             else
00324                 claimAsyncStatus = true;
00325             break;
00326
00327         default:
00328             co_return claimAsyncStatus;
00329         }
00330         co_return claimAsyncStatus;
00331     }
00332
00333     /// <summary>
00334     /// This method enables the connected scanner.
00335     /// </summary>
00336     /// <returns>a boolean based on whether it was able to enable the scanner.</returns>
00337
00338     IAsyncOperation<bool> Scenario2_MultipleScanners::EnableBarcodeScannerAsync(BarcodeScannerInstance instance)
00339     {
00340         auto lifetime = get_strong();
00341         switch (instance)
00342         {
00343         case BarcodeScannerInstance::Instance1:
00344             co_await m_claimedBarcodeScannerInstance1.EnableAsync();
00345             m_rootPage.NotifyUser(L"Instance 1 ready to scan. Device ID: " + m_claimedBarcodeScannerInstance1.DeviceId(), NotifyType::StatusMessage);
00346             break;
00347         case BarcodeScannerInstance::Instance2:
00348             co_await m_claimedBarcodeScannerInstance2.EnableAsync();
00349             m_rootPage.NotifyUser(L"Instance 2 ready to scan. Device ID: " + m_claimedBarcodeScannerInstance2.DeviceId(), NotifyType::StatusMessage);
00350             break;
00351         default:
00352             co_return false;
00353         }
00354         co_return true;
00355     }
00356
00357     /// <summary>
00358     /// Reset the Scenario state
00359     /// </summary>
00360
00361     void Scenario2_MultipleScanners::ResetTheScenarioState()
00362     {
00363         if (m_claimedBarcodeScannerInstance1)
00364         {
00365             m_claimedBarcodeScannerInstance1.Close();
00366             m_claimedBarcodeScannerInstance1 = nullptr;
00367         }
00368
00369         if (m_barcodeScannerInstance1)
00370         {
00371             m_barcodeScannerInstance1.Close();
00372             m_barcodeScannerInstance1 = nullptr;
00373         }
00374
00375         if (m_claimedBarcodeScannerInstance2)
00376         {
00377             m_claimedBarcodeScannerInstance2.Close();
00378             m_claimedBarcodeScannerInstance2 = nullptr;
00379         }
00380
00381         if (m_barcodeScannerInstance2)
00382         {
00383             m_barcodeScannerInstance2.Close();
00384             m_barcodeScannerInstance2 = nullptr;
00385         }
00386
00387         ResetUI();
00388     }
00389
00390     /// <summary>
00391     /// Resets the display Elements to original state
00392     /// </summary>
00393
00394     void Scenario2_MultipleScanners::ResetUI()
00395     {
00396         Instance1Border().BorderBrush(SolidColorBrush{ Colors::Gray() });
00397         Instance2Border().BorderBrush(SolidColorBrush{ Colors::Gray() });
00398
00399         ScanDataType1().Text(L"No data");
00400         ScanData1().Text(L"No data");
00401         DataLabel1().Text(L"No data");
00402         ScanDataType2().Text(L"No data");
00403         ScanData2().Text(L"No data");
00404         DataLabel2().Text(L"No data");
00405
00406         ScenarioStartScanningInstance1().IsEnabled(true);
00407         ScenarioStartScanningInstance2().IsEnabled(true);
00408         ScenarioEndScanningInstance1().IsEnabled(false);
00409         ScenarioEndScanningInstance2().IsEnabled(false);
00410     }
00411
00412     /// <summary>
00413     /// Sets the UI elements to a state corresponding to the current active Instance.
00414     /// </summary>
00415     /// <param name="instance">Corresponds to the current active instance</param>
00416
00417     void Scenario2_MultipleScanners::SetUI(BarcodeScannerInstance instance)
00418     {
00419         Instance1Border().BorderBrush(SolidColorBrush{ Colors::Gray() });
00420         Instance2Border().BorderBrush(SolidColorBrush{ Colors::Gray() });
00421
00422         switch (instance)
00423         {
00424         case BarcodeScannerInstance::Instance1:
00425             ScenarioStartScanningInstance1().IsEnabled(false);
00426             ScenarioStartScanningInstance2().IsEnabled(true);
00427             ScenarioEndScanningInstance1().IsEnabled(true);
00428             ScenarioEndScanningInstance2().IsEnabled(false);
00429             Instance1Border().BorderBrush(SolidColorBrush{ Colors::DarkBlue() });
00430             break;
00431
00432         case BarcodeScannerInstance::Instance2:
00433             ScenarioStartScanningInstance1().IsEnabled(true);
00434             ScenarioStartScanningInstance2().IsEnabled(false);
00435             ScenarioEndScanningInstance1().IsEnabled(false);
00436             ScenarioEndScanningInstance2().IsEnabled(true);
00437             Instance2Border().BorderBrush(SolidColorBrush{ Colors::DarkBlue() });
00438             break;
00439         }
00440     }
00441
00442     /// <summary>
00443     /// This is an event handler for the claimed scanner Instance 1 when it scans and recieves data
00444     /// </summary>
00445     /// <param name="sender"></param>
00446     /// <param name="args"></param>
00447
00448     fire_and_forget Scenario2_MultipleScanners::claimedBarcodeScannerInstance1_DataReceived(ClaimedBarcodeScanner const&, BarcodeScannerDataReceivedEventArgs args)
00449     {
00450         auto lifetime = get_strong();
00451         co_await resume_foreground(Dispatcher());
00452
00453         ScanDataType1().Text(BarcodeSymbologies::GetName(args.Report().ScanDataType()));
00454         DataLabel1().Text(GetDataLabelString(args.Report().ScanDataLabel(), args.Report().ScanDataType()));
00455         ScanData1().Text(GetDataString(args.Report().ScanData()));
00456
00457         m_rootPage.NotifyUser(L"Instance 1 received data from the barcode scanner.", NotifyType::StatusMessage);
00458     }
00459
00460     /// <summary>
00461     /// This is an event handler for the claimed scanner Instance 2 when it scans and recieves data
00462     /// </summary>
00463     /// <param name="sender"></param>
00464     /// <param name="args"></param>
00465
00466     fire_and_forget Scenario2_MultipleScanners::claimedBarcodeScannerInstance2_DataReceived(ClaimedBarcodeScanner const&, BarcodeScannerDataReceivedEventArgs args)
00467     {
00468         auto lifetime = get_strong();
00469         co_await resume_foreground(Dispatcher());
00470         ScanDataType2().Text(BarcodeSymbologies::GetName(args.Report().ScanDataType()));
00471         DataLabel2().Text(GetDataLabelString(args.Report().ScanDataLabel(), args.Report().ScanDataType()));
00472         ScanData2().Text(GetDataString(args.Report().ScanData()));
00473
00474         m_rootPage.NotifyUser(L"Instance 2 received data from the barcode scanner.", NotifyType::StatusMessage);
00475     }
00476
00477 }
Generated on Fri Nov 15 2024 22:18:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cs/BackgroundTask/Scenario6_GroupedTask.xaml.cs Source File

  • BackgroundTask
  • cs
  • BackgroundTask

Scenario6_GroupedTask.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using SDKTemplate;
00014 using Windows.ApplicationModel.Background;
00015 using Windows.Storage;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class GroupedBackgroundTask : Page
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         MainPage rootPage = MainPage.Current;
00033
00034         public GroupedBackgroundTask()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         BackgroundTaskRegistrationGroup group;
00040
00041         /// <summary>
00042         /// Invoked when this page is about to be displayed in a Frame.
00043         /// </summary>
00044         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00045         /// property is typically used to configure the page.</param>
00046         protected override void OnNavigatedTo(NavigationEventArgs e)
00047         {
00048             group = BackgroundTaskSample.GetTaskGroup(BackgroundTaskSample.BackgroundTaskGroupId, BackgroundTaskSample.BackgroundTaskGroupFriendlyName);
00049
00050             foreach (var task in group.AllTasks)
00051             {
00052                 if (task.Value.Name == BackgroundTaskSample.GroupedBackgroundTaskName)
00053                 {
00054                     AttachProgressAndCompletedHandlers(task.Value);
00055                     BackgroundTaskSample.UpdateBackgroundTaskRegistrationStatus(BackgroundTaskSample.GroupedBackgroundTaskName, true);
00056                     break;
00057                 }
00058             }
00059
00060             UpdateUI();
00061         }
00062
00063         /// <summary>
00064         /// Register a Grouped Background Task.
00065         /// </summary>
00066         /// <param name="sender"></param>
00067         /// <param name="e"></param>
00068         private void RegisterGroupedBackgroundTask(object sender, RoutedEventArgs e)
00069         {
00070             var task = BackgroundTaskSample.RegisterBackgroundTask(BackgroundTaskSample.SampleBackgroundTaskEntryPoint,
00071                                                                    BackgroundTaskSample.GroupedBackgroundTaskName,
00072                                                                    new SystemTrigger(SystemTriggerType.TimeZoneChange, false),
00073                                                                    null,
00074                                                                    group);
00075             AttachProgressAndCompletedHandlers(task);
00076             UpdateUI();
00077         }
00078
00079
00080         /// <summary>
00081         /// Unregister a Grouped Background Task.
00082         /// </summary>
00083         /// <param name="sender"></param>
00084         /// <param name="e"></param>
00085         private void UnregisterGroupedTask(object sender, RoutedEventArgs e)
00086         {
00087             BackgroundTaskSample.UnregisterBackgroundTasks(BackgroundTaskSample.GroupedBackgroundTaskName, group);
00088             UpdateUI();
00089         }
00090
00091         /// <summary>
00092         /// Unregisters all Background Tasks that are not in groups.
00093         /// This will not impact tasks registered with groups.
00094         /// </summary>
00095         /// <param name="sender"></param>
00096         /// <param name="e"></param>
00097         private void UnregisterUngroupedTasks(object sender, RoutedEventArgs e)
00098         {
00099             foreach(var cur in BackgroundTaskRegistration.AllTasks)
00100             {
00101                 cur.Value.Unregister(true);
00102                 BackgroundTaskSample.UpdateBackgroundTaskRegistrationStatus(cur.Value.Name, false);
00103             }
00104         }
00105
00106         /// <summary>
00107         /// Attach progress and completed handers to a background task.
00108         /// </summary>
00109         /// <param name="task">The task to attach progress and completed handlers to.</param>
00110         private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
00111         {
00112             task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
00113             task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
00114         }
00115
00116         /// <summary>
00117         /// Handle background task progress.
00118         /// </summary>
00119         /// <param name="task">The task that is reporting progress.</param>
00120         /// <param name="e">Arguments of the progress report.</param>
00121         private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
00122         {
00123             var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00124             {
00125                 var progress = "Progress: " + args.Progress + "%";
00126                 BackgroundTaskSample.GroupedBackgroundTaskProgress = progress;
00127                 UpdateUI();
00128             });
00129         }
00130
00131         /// <summary>
00132         /// Handle background task completion.
00133         /// </summary>
00134         /// <param name="task">The task that is reporting completion.</param>
00135         /// <param name="e">Arguments of the completion report.</param>
00136         private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
00137         {
00138             UpdateUI();
00139         }
00140
00141         /// <summary>
00142         /// Update the scenario UI.
00143         /// </summary>
00144         private async void UpdateUI()
00145         {
00146             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00147             () =>
00148             {
00149                 RegisterButton.IsEnabled = !BackgroundTaskSample.GroupedBackgroundTaskRegistered;
00150                 UnregisterGroupedButton.IsEnabled = BackgroundTaskSample.GroupedBackgroundTaskRegistered;
00151                 Progress.Text = BackgroundTaskSample.GroupedBackgroundTaskProgress;
00152                 Status.Text = BackgroundTaskSample.GetBackgroundTaskStatus(BackgroundTaskSample.GroupedBackgroundTaskName);
00153             });
00154         }
00155     }
00156 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserConsentVerifier/cs/Scenario1_CheckConsentAvailability.xaml.cs Source File

  • UserConsentVerifier
  • cs

Scenario1_CheckConsentAvailability.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using Windows.Security.Credentials.UI;
00016 using System;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class Scenario1_CheckConsentAvailability : Page
00021     {
00022         private MainPage rootPage = MainPage.Current;
00023
00024         public Scenario1_CheckConsentAvailability()
00025         {
00026             this.InitializeComponent();
00027         }
00028
00029         private async void CheckAvailability_Click(object sender, RoutedEventArgs e)
00030         {
00031             CheckAvailabilityButton.IsEnabled = false;
00032
00033             // Check the availability of Windows Hello authentication through User Consent Verifier.
00034             UserConsentVerifierAvailability consentAvailability = await UserConsentVerifier.CheckAvailabilityAsync();
00035             switch (consentAvailability)
00036             {
00037                 case UserConsentVerifierAvailability.Available:
00038                     rootPage.NotifyUser("User consent verification available!", NotifyType.StatusMessage);
00039                     break;
00040
00041                 case UserConsentVerifierAvailability.DeviceNotPresent:
00042                     rootPage.NotifyUser("No PIN or biometric found, please set one up.", NotifyType.ErrorMessage);
00043                     break;
00044
00045                 default:
00046                     rootPage.NotifyUser("User consent verification is currently unavailable.", NotifyType.ErrorMessage);
00047                     break;
00048             }
00049
00050             CheckAvailabilityButton.IsEnabled = true;
00051         }
00052     }
00053 }
00054
Generated on Fri Nov 15 2024 22:21:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScannerProvider/cpp/BarcodeScannerProvider/SampleConfiguration.cpp Source File

  • BarcodeScannerProvider
  • cpp
  • BarcodeScannerProvider

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015 #include "DeviceHelpers.h"
00016 #include "Scenario1_Configuration.xaml.h"
00017
00018 using namespace Concurrency;
00019 using namespace Platform;
00020 using namespace SDKTemplate;
00021 using namespace Windows::Devices::PointOfService;
00022 using namespace Windows::Foundation;
00023
00024 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00025 {
00026     { "Decoder Configuration", "SDKTemplate.Scenario1_Configuration" }
00027 };
00028
00029 task<BarcodeScanner^> DeviceHelpers::GetFirstBarcodeScannerAsync(PosConnectionTypes connectionTypes)
00030 {
00031     return DeviceHelpers::GetFirstDeviceAsync(BarcodeScanner::GetDeviceSelector(connectionTypes),
00032         [](String^ id) { return create_task(BarcodeScanner::FromIdAsync(id)); });
00033 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_History Member List

This is the complete list of members for Scenario2_History, including all inherited members.
ActivitySensorClassId | Scenario2_History | [private]
rootPage | Scenario2_History | [private]
Scenario2_History() | Scenario2_History | [inline]
ScenarioGetActivityHistory(object sender, RoutedEventArgs e) | Scenario2_History | [inline, private]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInteractionMode/cpp/pch.cpp Source File

  • UserInteractionMode
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/Content/ShaderStructures.h Source File

  • SpatialInteractionSource
  • cpp
  • Content

ShaderStructures.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 namespace HolographicPaint
00004 {
00005     // Constant buffer used to send hologram position transform to the shader pipeline.
00006     struct ModelConstantBuffer
00007     {
00008         DirectX::XMFLOAT4X4 model;
00009         DirectX::XMFLOAT4 color;
00010     };
00011
00012     // Assert that the constant buffer remains 16-byte aligned (best practice).
00013     static_assert((sizeof(ModelConstantBuffer) % (sizeof(float) * 4)) == 0, "Model constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00014
00015
00016     // Used to send per-vertex data to the vertex shader.
00017     struct VertexPosition
00018     {
00019         DirectX::XMFLOAT3 pos;
00020     };
00021 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

XSLTTransform Member List

This is the complete list of members for XSLTTransform, including all inherited members.
OnNavigatedTo(NavigationEventArgs e) | XSLTTransform | [inline, protected]
rootPage | XSLTTransform | [private]
Scenario5BtnTransformToDocument_Click(object sender, RoutedEventArgs e) | XSLTTransform | [inline, private]
Scenario5BtnTransformToString_Click(object sender, RoutedEventArgs e) | XSLTTransform | [inline, private]
Scenario5Init() | XSLTTransform | [inline, private]
XsltInit() | XSLTTransform | [inline, private]
XSLTTransform() | XSLTTransform | [inline]
Generated on Fri Nov 15 2024 22:24:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GuidComparer Member List

This is the complete list of members for GuidComparer, including all inherited members.
operator()(const Platform::Guid &, const Platform::Guid &) const GuidComparer [inline]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCorrelation/cpp/pch.h Source File

  • CameraStreamCorrelation
  • cpp

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include <shared_mutex>
00021 #include <initguid.h>
00022
00023 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/Scenario1_ProvisionTPM.cpp Source File

  • SmartCard
  • cppwinrt

Scenario1_ProvisionTPM.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SampleConfiguration.h"
00014 #include "Scenario1_ProvisionTPM.h"
00015 #include "Scenario1_ProvisionTPM.g.cpp"
00016
00017 namespace winrt
00018 {
00019     using namespace Windows::Devices::SmartCards;
00020     using namespace Windows::Foundation;
00021     using namespace Windows::Security::Cryptography;
00022     using namespace Windows::Security::Cryptography::Core;
00023     using namespace Windows::Storage::Streams;
00024     using namespace Windows::UI::Xaml;
00025     using namespace Windows::UI::Xaml::Controls;
00026 }
00027
00028 namespace winrt::SDKTemplate::implementation
00029 {
00030     Scenario1_ProvisionTPM::Scenario1_ProvisionTPM()
00031     {
00032         InitializeComponent();
00033     }
00034
00035
00036     /// <summary>
00037     /// Click handler for the 'create' button.
00038     /// </summary>
00039     /// <param name="sender">The 'Create' button</param>
00040     fire_and_forget Scenario1_ProvisionTPM::Create_Click(IInspectable const& sender, RoutedEventArgs const&)
00041     {
00042         auto lifetime = get_strong();
00043         auto b = sender.as<Button>();
00044         b.IsEnabled(false);
00045         m_rootPage.NotifyUser(L"Creating TPM virtual smart card...", NotifyType::StatusMessage);
00046
00047         try
00048         {
00049             SmartCardPinPolicy pinPolicy = ParsePinPolicy();
00050
00051             IBuffer adminkey = CryptographicBuffer::GenerateRandom(ADMIN_KEY_LENGTH_IN_BYTES);
00052
00053             SmartCardProvisioning provisioning = co_await SmartCardProvisioning::RequestVirtualSmartCardCreationAsync(FriendlyName().Text(), adminkey, pinPolicy);
00054
00055             // If card creation is cancelled by the user,
00056             // RequestVirtualSmartCard will return nullptr instead of a
00057             // SmartCardProvisioning object.
00058             if (!provisioning)
00059             {
00060                 m_rootPage.NotifyUser(L"TPM virtual smart card creation was canceled by the user.", NotifyType::StatusMessage);
00061                 b.IsEnabled(true);
00062                 co_return;
00063             }
00064
00065             // The following two lines are not directly related to TPM virtual
00066             // smart card creation, but are used to demonstrate how to handle
00067             // CardAdded events by registering an event handler with a
00068             // SmartCardReader object.  Since we are using a TPM virtual smart
00069             // card in this case, the card cannot actually be added to or
00070             // removed from the reader, but a CardAdded event will fire as
00071             // soon as the event handler is added, since the card is already
00072             // inserted.
00073             //
00074             // We must retain a reference to the SmartCardReader object to
00075             // which we are adding the event handler.  Hence we assign the
00076             // reader object associated with the SmartCardProvisioning we
00077             // received from RequestVirtualSmartCardCreationAsync to the
00078             // class's "reader" member. Then, we add the HandleCardAdded method
00079             // as an event handler. Adding the handler with auto_revoke
00080             // returns an object which unregisters the handler at destruction.
00081             // We store that object into a member variable so that the handler
00082             // is unregistered when the page is destructed.
00083             m_reader = provisioning.SmartCard().Reader();
00084             m_cardAddedToken = m_reader.CardAdded(winrt::auto_revoke, { get_weak(), &Scenario1_ProvisionTPM::HandleCardAdded });
00085
00086             // Store the reader's device ID and admin key to enable the
00087             // following scenarios in the sample.
00088             SetSmartCardReaderDeviceId(provisioning.SmartCard().Reader().DeviceId());
00089             SetAdminKey(adminkey);
00090
00091             // Once RequestVirtualSmartCardCreationAsync has returned, the card
00092             // is already provisioned and ready to use.  Therefore, the steps
00093             // in this block are not actually necessary at this point.
00094             // However, should you want to re-provision the card in the future,
00095             // you would follow this sequence: acquire a challenge context,
00096             // calculate a response, and then call ProvisionAsync on the
00097             // challenge context with the calculated response.
00098
00099             // We rely on this object's destructor to clean up the context.
00100             SmartCardChallengeContext context = co_await provisioning.GetChallengeContextAsync();
00101             IBuffer response = CalculateChallengeResponse(context.Challenge(), adminkey);
00102             co_await context.ProvisionAsync(response, true);
00103
00104             m_rootPage.NotifyUser(L"TPM virtual smart card is provisioned and ready for use.", NotifyType::StatusMessage);
00105             // context destructed here
00106         }
00107         catch (hresult_error const& ex)
00108         {
00109             // Two potentially common error scenarios when creating a TPM
00110             // virtual smart card are that the user's machine may not have
00111             // a TPM, or the TPM may not be ready for use.  It is important
00112             // to explicitly check for these scenarios by checking the
00113             // error code of any exceptions thrown by
00114             // RequestVirtualSmartCardCreationAsync and gracefully
00115             // providing a suitable message to the user.
00116             if (NTE_DEVICE_NOT_FOUND == ex.code())
00117             {
00118                 m_rootPage.NotifyUser(L"We were unable to find a Trusted Platform Module on your machine. A TPM is required to use a TPM Virtual Smart Card.", NotifyType::ErrorMessage);
00119             }
00120             else if (NTE_DEVICE_NOT_READY == ex.code())
00121             {
00122                 m_rootPage.NotifyUser(L"Your Trusted Platform Module is not ready for use. Please contact your administrator for assistance with initializing your TPM.", NotifyType::ErrorMessage);
00123             }
00124             else
00125             {
00126                 m_rootPage.NotifyUser(L"TPM virtual smart card creation failed with exception: " + ex.message(), NotifyType::ErrorMessage);
00127             }
00128         }
00129
00130         b.IsEnabled(true);
00131     }
00132
00133     void Scenario1_ProvisionTPM::HandleCardAdded(SmartCardReader const&, CardAddedEventArgs const&)
00134     {
00135         // Note that this event is raised from a background thread.
00136         // However, the NotifyUser method is safe to call from background threads.
00137         m_rootPage.NotifyUser(L"Card added to reader " + m_reader.Name() + L".", NotifyType::StatusMessage);
00138     }
00139
00140     SmartCardPinCharacterPolicyOption ParsePinPolicyOption(hstring const& value)
00141     {
00142         static constexpr wchar_t pinPolicyDisallowed[] = L"Disallowed";
00143         static constexpr wchar_t pinPolicyAllowed[] = L"Allowed";
00144         static constexpr wchar_t pinPolicyRequireOne[] = L"Require At Least One";
00145
00146         if (value == pinPolicyDisallowed)
00147         {
00148             return SmartCardPinCharacterPolicyOption::Disallow;
00149         }
00150         else if (value == pinPolicyAllowed)
00151         {
00152             return SmartCardPinCharacterPolicyOption::Allow;
00153         }
00154         else if (value == pinPolicyRequireOne)
00155         {
00156             return SmartCardPinCharacterPolicyOption::RequireAtLeastOne;
00157         }
00158         else
00159         {
00160             throw hresult_invalid_argument();
00161         }
00162     }
00163
00164     SmartCardPinPolicy Scenario1_ProvisionTPM::ParsePinPolicy()
00165     {
00166         SmartCardPinPolicy pinPolicy;
00167         pinPolicy.MinLength(std::stoul(PinMinLength().Text().c_str()));
00168         pinPolicy.MaxLength(std::stoul(PinMaxLength().Text().c_str()));
00169
00170         const auto upperCaseSelection = winrt::unbox_value<hstring>(PinUppercase().SelectedValue());
00171         pinPolicy.UppercaseLetters(ParsePinPolicyOption(upperCaseSelection));
00172
00173         const auto lowerCaseSelection = winrt::unbox_value<hstring>(PinLowercase().SelectedValue());
00174         pinPolicy.LowercaseLetters(ParsePinPolicyOption(lowerCaseSelection));
00175
00176         const auto digitsSelection = winrt::unbox_value<hstring>(PinDigits().SelectedValue());
00177         pinPolicy.Digits(ParsePinPolicyOption(digitsSelection));
00178
00179         const auto specialSelection = winrt::unbox_value<hstring>(PinSpecial().SelectedValue());
00180         pinPolicy.SpecialCharacters(ParsePinPolicyOption(specialSelection));
00181
00182         return pinPolicy;
00183     }
00184 }
Generated on Fri Nov 15 2024 22:21:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cpp/pch.h Source File

  • WiFiDirect
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Scenario7_ForegroundVisits.cpp Source File

  • Geolocation
  • cppwinrt

Scenario7_ForegroundVisits.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario7_ForegroundVisits.h"
00014 #include "Scenario7_ForegroundVisits.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Devices::Geolocation;
00019 using namespace winrt::Windows::Foundation;
00020 using namespace winrt::Windows::UI::Xaml;
00021 using namespace winrt::Windows::UI::Xaml::Navigation;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario7_ForegroundVisits::Scenario7_ForegroundVisits()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     void Scenario7_ForegroundVisits::OnNavigatedFrom(NavigationEventArgs const&)
00031     {
00032         if (m_visitMonitor != nullptr)
00033         {
00034             m_visitMonitor.Stop();
00035             m_visitMonitor.VisitStateChanged(m_visitStateChangedToken);
00036         }
00037     }
00038
00039     fire_and_forget Scenario7_ForegroundVisits::StartMonitoring(IInspectable const&, RoutedEventArgs const&)
00040     {
00041         auto lifetime = get_strong();
00042
00043         // Request permission to access location
00044         auto accessStatus = co_await Geolocator::RequestAccessAsync();
00045
00046         switch (accessStatus)
00047         {
00048         case GeolocationAccessStatus::Allowed:
00049
00050             m_visitMonitor = GeovisitMonitor();
00051
00052             // Add visit state changed event handler.
00053             m_visitStateChangedToken = m_visitMonitor.VisitStateChanged({ get_weak(), &Scenario7_ForegroundVisits::OnVisitStateChanged });
00054
00055             // Start monitoring with the desired scope.
00056             // For higher granularity such as building/venue level changes, choose venue.
00057             // For lower granularity more or less in the range of zipcode level changes, choose city.
00058             // Choosing Venue here as an example.
00059             m_visitMonitor.Start(VisitMonitoringScope::Venue);
00060
00061             LocationDisabledMessage().Visibility(Visibility::Collapsed);
00062             m_rootPage.NotifyUser(L"Waiting for update...", NotifyType::StatusMessage);
00063
00064             StartMonitoringButton().IsEnabled(false);
00065             StopMonitoringButton().IsEnabled(true);
00066             break;
00067
00068         case GeolocationAccessStatus::Denied:
00069             m_rootPage.NotifyUser(L"Access to location is denied.", NotifyType::ErrorMessage);
00070             LocationDisabledMessage().Visibility(Visibility::Visible);
00071             break;
00072
00073         default:
00074         case GeolocationAccessStatus::Unspecified:
00075             m_rootPage.NotifyUser(L"Unspecificed error!", NotifyType::ErrorMessage);
00076             LocationDisabledMessage().Visibility(Visibility::Collapsed);
00077             break;
00078         }
00079     }
00080
00081     void Scenario7_ForegroundVisits::StopMonitoring(IInspectable const&, RoutedEventArgs const&)
00082     {
00083         // Stop visit monitoring.
00084         m_visitMonitor.Stop();
00085         m_visitMonitor.VisitStateChanged(m_visitStateChangedToken);
00086         m_visitMonitor = nullptr;
00087
00088         StartMonitoringButton().IsEnabled(true);
00089         StopMonitoringButton().IsEnabled(false);
00090
00091         // Clear status
00092         m_rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00093     }
00094
00095     // Event handler for VisitStateChanged events. It is raised when
00096     // a new visit state change is available based on the monitoring scope specified.
00097     fire_and_forget Scenario7_ForegroundVisits::OnVisitStateChanged(GeovisitMonitor const&, GeovisitStateChangedEventArgs args)
00098     {
00099         auto lifetime = get_strong();
00100
00101         co_await resume_foreground(Dispatcher());
00102
00103         m_rootPage.NotifyUser(L"Visit state changed.", NotifyType::StatusMessage);
00104         UpdateVisitData(args.Visit());
00105     }
00106
00107     // Updates the user interface with the Geovisit data provided
00108     void Scenario7_ForegroundVisits::UpdateVisitData(Geovisit const& visit)
00109     {
00110         // A valid visit is available, extract the state change and Timestamp.
00111         ScenarioOutput_VisitStateChange().Text(to_hstring(visit.StateChange()));
00112         ScenarioOutput_Timestamp().Text(FormatDateTime(visit.Timestamp(), L"shortdate shorttime"));
00113
00114         // If a valid position is available, extract the position information that caused the state change to happen.
00115         if (visit.Position() == nullptr)
00116         {
00117             ScenarioOutput_Latitude().Text(L"No data");
00118             ScenarioOutput_Longitude().Text(L"No data");
00119             ScenarioOutput_Accuracy().Text(L"No data");
00120             ScenarioOutput_IsRemoteSource().Text(L"No data");
00121         }
00122         else
00123         {
00124             ScenarioOutput_Latitude().Text(to_hstring(visit.Position().Coordinate().Point().Position().Latitude));
00125             ScenarioOutput_Longitude().Text(to_hstring(visit.Position().Coordinate().Point().Position().Longitude));
00126             ScenarioOutput_Accuracy().Text(to_hstring(visit.Position().Coordinate().Accuracy()));
00127             ScenarioOutput_IsRemoteSource().Text(to_hstring(visit.Position().Coordinate().IsRemoteSource()));
00128         }
00129     }
00130
00131 }
Generated on Fri Nov 15 2024 22:19:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2 Member List

This is the complete list of members for Scenario2, including all inherited members.
Scenario2() Scenario2 [inline]
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundMediaPlayback/cs/ViewModels/MediaItemViewModel.cs Source File

  • BackgroundMediaPlayback
  • cs
  • ViewModels

MediaItemViewModel.cs

Go to the documentation of this file.
00001 ﻿using BackgroundMediaPlayback.DataModels;
00002 using System;
00003 using System.Collections.Generic;
00004 using System.ComponentModel;
00005 using System.Linq;
00006 using System.Text;
00007 using System.Threading.Tasks;
00008 using Windows.Media.Playback;
00009 using Windows.UI.Xaml.Media.Imaging;
00010
00011 namespace BackgroundMediaPlayback.ViewModels
00012 {
00013     /// <summary>
00014     /// View model for media items.
00015     /// </summary>
00016     /// <remarks>
00017     /// The view model is backed by a data model (MediaItem)
00018     /// and a playback model (MediaPlaybackItem).
00019     ///
00020     /// This class currently supports OneWay (read only) binding
00021     /// but could be extended to support TwoWay binding to
00022     /// persist changes back to the data and playback models.
00023     ///
00024     /// The projected view is the same regardless of the type
00025     /// of media. More sophisticated applications may want to
00026     /// create separate models and XAML data templates for
00027     /// unique content display.
00028     /// </remarks>
00029     public class MediaItemViewModel : INotifyPropertyChanged
00030     {
00031         MediaListViewModel listViewModel;
00032         MediaPlaybackItem playbackItem;
00033
00034         BitmapImage previewImage;
00035
00036         public event PropertyChangedEventHandler PropertyChanged;
00037
00038         public MediaItem MediaItem { get; private set; }
00039
00040         public string Title => MediaItem.Title;
00041
00042         public BitmapImage PreviewImage
00043         {
00044             get { return previewImage; }
00045
00046             private set
00047             {
00048                 if (previewImage != value)
00049                 {
00050                     previewImage = value;
00051                     RaisePropertyChanged("PreviewImage");
00052                 }
00053             }
00054         }
00055
00056         public MediaPlaybackItem PlaybackItem
00057         {
00058             get
00059             {
00060                 // Already have one then return it
00061                 if (playbackItem != null)
00062                     return playbackItem;
00063
00064                 // Don't have one, try to rebind to one in the list
00065                 playbackItem = listViewModel.PlaybackList.Items.SingleOrDefault(pi =>
00066                     (string)pi.Source.CustomProperties[MediaItem.MediaItemIdKey] == MediaItem.ItemId);
00067
00068                 if (playbackItem != null)
00069                     return playbackItem;
00070
00071                 // Not in the list, make a new one
00072                 playbackItem = MediaItem.ToPlaybackItem();
00073                 RaisePropertyChanged("PlaybackItem");
00074                 return playbackItem;
00075             }
00076         }
00077
00078         public MediaItemViewModel(MediaListViewModel listViewModel, MediaItem mediaItem)
00079         {
00080             this.listViewModel = listViewModel;
00081             MediaItem = mediaItem;
00082
00083             RaisePropertyChanged("Title");
00084
00085             // This app caches all images by loading the BitmapImage
00086             // when the item is created, but production apps would
00087             // use a more resource friendly paging mechanism or
00088             // just use PreviewImageUri directly.
00089             //
00090             // The reason we cache here is to avoid audio gaps
00091             // between tracks on transitions when changing artwork.
00092             PreviewImage = new BitmapImage();
00093             PreviewImage.UriSource = mediaItem.PreviewImageUri;
00094         }
00095
00096         private void RaisePropertyChanged(string propertyName)
00097         {
00098             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
00099         }
00100     }
00101 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/Scenario_SRGSConstraint.xaml.h Source File

  • SpeechRecognitionAndSynthesis
  • cpp

Scenario_SRGSConstraint.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario_SRGSConstraint.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario_SRGSConstraint sealed
00024     {
00025     public:
00026         Scenario_SRGSConstraint();
00027
00028     protected:
00029         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00031
00032     private:
00033         /// <summary>
00034         /// This HResult represents the scenario where a user is prompted to allow in-app speech, but
00035         /// declines. This should only happen on a Phone device, where speech is enabled for the entire device,
00036         /// not per-app.
00037         /// </summary>
00038         static const unsigned int HResultPrivacyStatementDeclined = 0x80045509;
00039         static const unsigned int HResultRecognizerNotFound = 0x8004503a;
00040
00041         SDKTemplate::MainPage^ rootPage;
00042         Windows::UI::Core::CoreDispatcher^ dispatcher;
00043         Windows::Media::SpeechRecognition::SpeechRecognizer^ speechRecognizer;
00044         Windows::Foundation::Collections::IMap<Platform::String^, Windows::UI::Color>^ colorLookup;
00045         Windows::ApplicationModel::Resources::Core::ResourceContext^ speechContext;
00046         Windows::ApplicationModel::Resources::Core::ResourceMap^ speechResourceMap;
00047         bool isPopulatingLanguages = false;
00048
00049         void RecognizeWithUI_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050         void RecognizeWithoutUI_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00051
00052         void PopulateLanguageDropdown();
00053         void InitializeRecognizer(Windows::Globalization::Language^ recognizerLanguage);
00054
00055         void HandleRecognitionResult(Windows::Media::SpeechRecognition::SpeechRecognitionResult^ recoResult);
00056         Windows::UI::Color getColor(Platform::String^ colorString);
00057
00058         Windows::Foundation::EventRegistrationToken stateChangedToken;
00059
00060         void SpeechRecognizer_StateChanged(Windows::Media::SpeechRecognition::SpeechRecognizer ^sender, Windows::Media::SpeechRecognition::SpeechRecognizerStateChangedEventArgs ^args);
00061         void cbLanguageSelection_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00062     };
00063 }
Generated on Fri Nov 15 2024 22:21:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInfo/cppwinrt/pch.cpp Source File

  • UserInfo
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6 Member List

This is the complete list of members for Scenario6, including all inherited members.
GetBuffersStatus_Click(object sender, RoutedEventArgs e) | Scenario6 | [inline, private]
m_protectBufferScenario | Scenario6 | [private]
m_protectedBuffer | Scenario6 | [private]
m_protectedMessage | Scenario6 | [private]
m_statusBufferScenario | Scenario6 | [private]
m_unprotectedBuffer | Scenario6 | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario6 | [inline, protected]
ProtectAsyncBuffer_Click(object sender, RoutedEventArgs e) | Scenario6 | [inline, private]
rootPage | Scenario6 | [private]
Scenario6() | Scenario6 | [inline]
UnprotectAsyncBuffer_Click(object sender, RoutedEventArgs e) | Scenario6 | [inline, private]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cs/Tasks/BackgroundDeviceWatcher.cs Source File

  • DeviceEnumerationAndPairing
  • cs
  • Tasks

BackgroundDeviceWatcher.cs

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft Corporation. All rights reserved.
00002
00003 using System;
00004 using System.Collections.Generic;
00005 using System.Linq;
00006 using System.Text;
00007 using System.Threading.Tasks;
00008 using Windows.Storage;
00009 using System.Diagnostics;
00010
00011 // Needed for the DeviceWatcherTrigger
00012 using Windows.ApplicationModel.Background;
00013 using Windows.Devices.Enumeration;
00014
00015 namespace BackgroundDeviceWatcherTaskCs
00016 {
00017     public sealed class BackgroundDeviceWatcher : IBackgroundTask
00018     {
00019         public void Run(IBackgroundTaskInstance taskInstance)
00020         {
00021             Debug.WriteLine("BackgroundDeviceWatcher.Run called");
00022
00023             uint eventCount = 0;
00024             ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
00025             DeviceWatcherTriggerDetails triggerDetails = (DeviceWatcherTriggerDetails)taskInstance.TriggerDetails;
00026
00027             Debug.WriteLine(String.Format("Trigger contains {0} events", triggerDetails.DeviceWatcherEvents.Count));
00028
00029             foreach (DeviceWatcherEvent e in triggerDetails.DeviceWatcherEvents)
00030             {
00031                 switch (e.Kind)
00032                 {
00033                 case DeviceWatcherEventKind.Add:
00034                     Debug.WriteLine("Add: " + e.DeviceInformation.Id);
00035                     break;
00036
00037                 case DeviceWatcherEventKind.Update:
00038                     Debug.WriteLine("Update: " + e.DeviceInformationUpdate.Id);
00039                     break;
00040
00041                 case DeviceWatcherEventKind.Remove:
00042                     Debug.WriteLine("Remove: " + e.DeviceInformationUpdate.Id);
00043                     break;
00044                 }
00045             };
00046
00047             if (null != settings.Values["eventCount"] &&
00048                 settings.Values["eventCount"].GetType() == typeof(uint))
00049             {
00050                 eventCount = (uint)settings.Values["eventCount"];
00051             }
00052
00053             // Add the number of events for this trigger to the number of events received in the past
00054             eventCount += (uint)triggerDetails.DeviceWatcherEvents.Count;
00055
00056             Debug.WriteLine(eventCount + " events processed for lifetime of trigger");
00057
00058             settings.Values["eventCount"] = eventCount;
00059         }
00060     }
00061 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cpp/Scenario5_Multiple.xaml.h Source File

  • XamlCommanding
  • cpp

Scenario5_Multiple.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // Scenario5_Multiple.xaml.h
00003 // Declaration of the Scenario5_Multiple class
00004 //
00005
00006 #pragma once
00007
00008 #include "Scenario5_Multiple.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     /// <summary>
00013     /// An empty page that can be used on its own or navigated to within a Frame.
00014     /// </summary>
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class Scenario5_Multiple sealed
00017     {
00018     public:
00019         Scenario5_Multiple();
00020     };
00021 }
Generated on Fri Nov 15 2024 22:22:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cpp/Scenario4_UnicodeExtensions.xaml.h Source File

  • Calendar
  • cpp

Scenario4_UnicodeExtensions.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_UnicodeExtensions.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario4_UnicodeExtensions sealed
00021     {
00022     public:
00023         Scenario4_UnicodeExtensions();
00024         void ShowResults_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00025
00026     private:
00027         Platform::String^ ReportCalendarData(Windows::Globalization::Calendar^ calendar, Platform::String^ calendarLabel);
00028     };
00029 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cpp/SocketReaderWriter.h Source File

  • WiFiDirect
  • cpp

SocketReaderWriter.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "MainPage.xaml.h"
00014
00015 namespace SDKTemplate
00016 {
00017     extern Platform::Array<byte>^ CustomOui;
00018     extern byte CustomOuiType;
00019     extern Platform::Array<byte>^ WfaOui;
00020     extern Platform::Array<byte>^ MsftOui;
00021     extern Platform::String^ strServerPort;
00022
00023     public ref class SocketReaderWriter sealed
00024     {
00025     public:
00026         SocketReaderWriter(Windows::Networking::Sockets::StreamSocket^ socket, SDKTemplate::MainPage^ mainPage) :
00027             _streamSocket(socket),
00028             _rootPage(mainPage)
00029         {
00030             _socketReader = ref new Windows::Storage::Streams::DataReader(socket->InputStream);
00031             _socketReader->UnicodeEncoding = Windows::Storage::Streams::UnicodeEncoding::Utf8;
00032             _socketReader->ByteOrder = Windows::Storage::Streams::ByteOrder::LittleEndian;
00033
00034             _socketWriter = ref new Windows::Storage::Streams::DataWriter(socket->OutputStream);
00035             _socketWriter->UnicodeEncoding = Windows::Storage::Streams::UnicodeEncoding::Utf8;
00036             _socketWriter->ByteOrder = Windows::Storage::Streams::ByteOrder::LittleEndian;
00037
00038             _currentMessage = nullptr;
00039         }
00040
00041         void WriteMessage(Platform::String^ message);
00042         void ReadMessage();
00043         void Close();
00044         Platform::String^ GetCurrentMessage();
00045
00046     private:
00047         Windows::Storage::Streams::DataReader^ _socketReader;
00048         Windows::Storage::Streams::DataWriter^ _socketWriter;
00049         Windows::Networking::Sockets::StreamSocket^ _streamSocket;
00050         SDKTemplate::MainPage^ _rootPage;
00051         Platform::String^ _currentMessage;
00052     };
00053
00054     [Windows::UI::Xaml::Data::Bindable]
00055     public ref class DiscoveredDevice sealed : Windows::UI::Xaml::Data::INotifyPropertyChanged
00056     {
00057     public:
00058         DiscoveredDevice(Windows::Devices::Enumeration::DeviceInformation^ deviceInfoIn);
00059
00060         property Windows::Devices::Enumeration::DeviceInformation^ DeviceInfo
00061         {
00062             Windows::Devices::Enumeration::DeviceInformation^ get() { return deviceInfo; }
00063         }
00064
00065         property Platform::String^ DisplayName
00066         {
00067             Platform::String^ get() { return deviceInfo->Name; }
00068         }
00069
00070         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
00071
00072     private:
00073         Windows::Devices::Enumeration::DeviceInformation^ deviceInfo;
00074     };
00075
00076     [Windows::UI::Xaml::Data::Bindable]
00077     public ref class ConnectedDevice sealed : Windows::UI::Xaml::Data::INotifyPropertyChanged
00078     {
00079     public:
00080         ConnectedDevice(Platform::String^ displayName, Windows::Devices::WiFiDirect::WiFiDirectDevice^ wfdDevice, SocketReaderWriter^ socketRW);
00081
00082         property Platform::String^ DisplayName
00083         {
00084             Platform::String^ get() { return displayName; }
00085         }
00086
00087         property SocketReaderWriter^ SocketRW
00088         {
00089             SocketReaderWriter^ get() { return socketRW; }
00090
00091             void set(SocketReaderWriter^ socketRW) { this->socketRW = socketRW; }
00092         }
00093
00094         property Windows::Devices::WiFiDirect::WiFiDirectDevice^ WfdDevice
00095         {
00096             Windows::Devices::WiFiDirect::WiFiDirectDevice^ get() { return wfdDevice; }
00097
00098             void set(Windows::Devices::WiFiDirect::WiFiDirectDevice^ wfdDevice) { this->wfdDevice = wfdDevice; }
00099         }
00100
00101         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
00102
00103     private:
00104         SocketReaderWriter^ socketRW;
00105         Windows::Devices::WiFiDirect::WiFiDirectDevice^ wfdDevice;
00106         Platform::String^ displayName;
00107     };
00108 }
Generated on Fri Nov 15 2024 22:22:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario2WinRTComponent/AllJoynHelpers.h Source File

  • AllJoyn
  • Common
  • Scenario2WinRTComponent

AllJoynHelpers.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #pragma once
00022
00023 // The amount of time to wait (ms) for a response after sending a message before timing out.
00024 const int c_MessageTimeoutInMilliseconds = 10000;
00025
00026 // The maximum length of an AllJoyn type signature allowed by the AllJoyn Core library.
00027 const int c_MaximumSignatureLength = 255;
00028
00029 #define RETURN_IF_QSTATUS_ERROR(status) \
00030 {   \
00031 int32 alljoynStatus = static_cast<int32>(status);    \
00032 if (Windows::Devices::AllJoyn::AllJoynStatus::Ok != alljoynStatus)  \
00033 {   \
00034     return status;   \
00035 }   \
00036 }
00037
00038 namespace org { namespace alljoyn { namespace Onboarding {
00039
00040 public interface class ISignalEmitter
00041 {
00042     property Windows::Devices::AllJoyn::AllJoynBusObject^ BusObject
00043     {
00044         Windows::Devices::AllJoyn::AllJoynBusObject^ get();
00045     }
00046
00047     property Windows::Devices::AllJoyn::AllJoynSession^ Session
00048     {
00049         Windows::Devices::AllJoyn::AllJoynSession^ get();
00050     }
00051 };
00052
00053 } } }
00054
00055 class AllJoynHelpers
00056 {
00057 public:
00058     // The Windows::Devices::AllJoyn::AllJoynBusAttachment class wraps the alljoyn_busattachment type.  This
00059     // function gets the underlying alljoyn_busattachment.
00060     static alljoyn_busattachment GetInternalBusAttachment(_In_ Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment);
00061
00062     // The Windows::Devices::AllJoyn::AllJoynBusObject class wraps the alljoyn_busobject type.  This
00063     // function gets the underlying alljoyn_busobject.
00064     static alljoyn_busobject AllJoynHelpers::GetInternalBusObject(_In_ Windows::Devices::AllJoyn::AllJoynBusObject^ busObject);
00065
00066     // Create the alljoyn_interfacedescriptions described in introspectionXml and add them to the busAttachment.
00067     static QStatus CreateInterfaces(_Inout_ Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment, _In_ PCSTR introspectionXml);
00068
00069     // Convert a UTF8 string to a wide character Platform::String.
00070     static Platform::String^ MultibyteToPlatformString(_In_ PCSTR);
00071
00072     // Convert a wide character Platform::String to a UTF8 string.
00073     static std::vector<char> PlatformToMultibyteString(_In_ Platform::String^ str);
00074
00075     // Get the service object path from an objectDescriptionArg.  The objectDescriptionArg should
00076     // come from an Announce signal.
00077     static Platform::String^ GetObjectPath(_In_ alljoyn_aboutobjectdescription objectDescription, _In_ PCSTR interfaceName);
00078
00079     // Determine whether the supplied set of AuthenticationMechanisms is sufficient for securing an AllJoyn connection.
00080     static bool CanSecure(_In_ Windows::Foundation::Collections::IVector<Windows::Devices::AllJoyn::AllJoynAuthenticationMechanism>^ authenticationMechanisms);
00081
00082     // Callback for alljoyn_proxybusobject_listener_propertieschanged_ptr.
00083     // This callback expects the context to be of type T, which must implement the OnPropertyChanged function.
00084     template<class T>
00085     static void AJ_CALL PropertyChangedHandler(_In_ alljoyn_proxybusobject obj, _In_ PCSTR interfaceName, _In_ const alljoyn_msgarg changed, _In_ const alljoyn_msgarg invalidated, _In_ void* context)
00086     {
00087         T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
00088         caller->OnPropertyChanged(obj, interfaceName, changed, invalidated);
00089     }
00090
00091     // Callback for alljoyn_busobject_prop_get_ptr.
00092     template<class T>
00093     static QStatus AJ_CALL PropertyGetHandler(_In_ const void* context, _In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg value)
00094     {
00095         T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
00096         return caller->OnPropertyGet(interfaceName, propertyName, value);
00097     }
00098
00099     // Callback for alljoyn_busobject_prop_set_ptr.
00100     template<class T>
00101     static QStatus AJ_CALL PropertySetHandler(_In_ const void* context, _In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg value)
00102     {
00103         T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
00104         return caller->OnPropertySet(interfaceName, propertyName, value);
00105     }
00106
00107     // Callback for alljoyn_sessionlistener_sessionlost_ptr.
00108     template<class T>
00109     static void AJ_CALL SessionLostHandler(_In_ const void* context, _In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason)
00110     {
00111         T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
00112         caller->OnSessionLost(sessionId, reason);
00113     }
00114
00115     // Callback for alljoyn_sessionlistener_sessionmemberadded_ptr.
00116     template<class T>
00117     static void AJ_CALL SessionMemberAddedHandler(_In_ const void* context, _In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
00118     {
00119         T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
00120         caller->OnSessionMemberAdded(sessionId, uniqueName);
00121     }
00122
00123     // Callback for alljoyn_sessionlistener_sessionmemberremoved_ptr.
00124     template<class T>
00125     static void AJ_CALL SessionMemberRemovedHandler(_In_ const void* context, _In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
00126     {
00127         T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
00128         caller->OnSessionMemberRemoved(sessionId, uniqueName);
00129     }
00130
00131     // Create an AllJoyn bus object.
00132     template<class T>
00133     static QStatus CreateBusObject(_Inout_ Platform::WeakReference* target)
00134     {
00135         alljoyn_busobject_callbacks callbacks =
00136         {
00137             PropertyGetHandler<T>,
00138             PropertySetHandler<T>,
00139             nullptr,
00140             nullptr,
00141         };
00142
00143         T^ caller = target->Resolve<T>();
00144
00145         auto serviceObjectPath = PlatformToMultibyteString(caller->ServiceObjectPath);
00146         alljoyn_busobject busObject = alljoyn_busobject_create(serviceObjectPath.data(), false, &callbacks, target);
00147         if (busObject == nullptr)
00148         {
00149             return ER_FAIL;
00150         }
00151
00152         caller->BusObject = busObject;
00153
00154         return ER_OK;
00155     }
00156
00157     // Callback for alljoyn_sessionportlistener_acceptsessionjoiner_ptr.
00158     // This callback expects the context to be of type T, which must implement the OnAcceptSessionJoiner function.
00159     template<class T>
00160     static QCC_BOOL AJ_CALL AcceptSessionJoinerHandler(
00161         _In_ const void* context,
00162         _In_ alljoyn_sessionport sessionPort,
00163         _In_ PCSTR joiner,
00164         _In_ const alljoyn_sessionopts opts)
00165     {
00166         T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
00167         return caller->OnAcceptSessionJoiner(sessionPort, joiner, opts);
00168     }
00169
00170     // Callback for alljoyn_sessionportlistener_sessionjoined_ptr.
00171     // This callback expects the context to be of type T, which must implement the OnSessionJoined function.
00172     template<class T>
00173     static void AJ_CALL SessionJoinedHandler(
00174         _In_ const void* context,
00175         _In_ alljoyn_sessionport sessionPort,
00176         _In_ alljoyn_sessionid id,
00177         _In_ PCSTR joiner)
00178     {
00179         T^ caller = static_cast<const Platform::WeakReference*>(context)->Resolve<T>();
00180         caller->OnSessionJoined(sessionPort, id, joiner);
00181     }
00182
00183     // Create the session for an AllJoyn producer.
00184     template<class T>
00185     static QStatus CreateProducerSession(_Inout_ Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment, _Inout_ Platform::WeakReference* target)
00186     {
00187         alljoyn_sessionopts opts = alljoyn_sessionopts_create(ALLJOYN_TRAFFIC_TYPE_MESSAGES, true, ALLJOYN_PROXIMITY_ANY, ALLJOYN_TRANSPORT_ANY);
00188
00189         alljoyn_sessionportlistener_callbacks callbacks =
00190         {
00191             AcceptSessionJoinerHandler<T>,
00192             SessionJoinedHandler<T>
00193         };
00194
00195         T^ producer = target->Resolve<T>();
00196         producer->SessionPortListener = alljoyn_sessionportlistener_create(&callbacks, target);
00197
00198         alljoyn_sessionport sessionPort = 42;
00199         alljoyn_busattachment_unbindsessionport(AllJoynHelpers::GetInternalBusAttachment(busAttachment), sessionPort);
00200         RETURN_IF_QSTATUS_ERROR(alljoyn_busattachment_bindsessionport(AllJoynHelpers::GetInternalBusAttachment(busAttachment), &sessionPort, opts, producer->SessionPortListener));
00201         producer->SessionPort = sessionPort;
00202
00203         alljoyn_sessionopts_destroy(opts);
00204
00205         return ER_OK;
00206     }
00207 };
00208
00209 // Passed to property get callbacks to allow them to report when the async operation is completed.
00210 template<class T>
00211 class PropertyGetContext
00212 {
00213 public:
00214     void SetEvent()
00215     {
00216         m_event.set();
00217     }
00218
00219     void Wait()
00220     {
00221         m_event.wait();
00222     }
00223
00224     QStatus GetStatus()
00225     {
00226         return m_status;
00227     }
00228
00229     void SetStatus(QStatus value)
00230     {
00231         m_status = value;
00232     }
00233
00234     T GetValue()
00235     {
00236         return m_value;
00237     }
00238
00239     void SetValue(T value)
00240     {
00241         m_value = value;
00242     }
00243
00244 private:
00245     Concurrency::event m_event;
00246     QStatus m_status;
00247     T m_value;
00248 };
00249
00250 // Passed to property set callbacks to allow them to report when the async operation is completed.
00251 class PropertySetContext
00252 {
00253 public:
00254     void SetEvent()
00255     {
00256         m_event.set();
00257     }
00258
00259     void Wait()
00260     {
00261         m_event.wait();
00262     }
00263
00264     QStatus GetStatus()
00265     {
00266         return m_status;
00267     }
00268
00269     void SetStatus(QStatus value)
00270     {
00271         m_status = value;
00272     }
00273
00274 private:
00275     Concurrency::event m_event;
00276     QStatus m_status;
00277 };
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TitleBar/cppwinrt/Scenario1_Colors.h Source File

  • TitleBar
  • cppwinrt

Scenario1_Colors.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Colors.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt
00018 {
00019     // Used by binding.
00020     hstring to_hstring(Windows::Foundation::IReference<Windows::UI::Color> const& value);
00021 }
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     struct Scenario1_Colors : Scenario1_ColorsT<Scenario1_Colors>
00026     {
00027         Scenario1_Colors();
00028
00029         Windows::UI::ViewManagement::ApplicationViewTitleBar TitleBar()
00030         {
00031             return titleBar;
00032         }
00033
00034         event_token PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler);
00035         void PropertyChanged(event_token const& token) noexcept;
00036
00037         void UseCustomColors_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00038
00039     private:
00040         Windows::UI::ViewManagement::ApplicationViewTitleBar titleBar{ nullptr };
00041         event<Windows::UI::Xaml::Data::PropertyChangedEventHandler> m_propertyChanged;
00042
00043         void UpdateColors();
00044     };
00045 }
00046
00047 namespace winrt::SDKTemplate::factory_implementation
00048 {
00049     struct Scenario1_Colors : Scenario1_ColorsT<Scenario1_Colors, implementation::Scenario1_Colors>
00050     {
00051     };
00052 }
Generated on Fri Nov 15 2024 22:21:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MobileHotspot/cppwinrt/SampleConfiguration.h Source File

  • MobileHotspot
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     Windows::Networking::NetworkOperators::NetworkOperatorTetheringManager TryGetCurrentNetworkOperatorTetheringManager();
00018     hstring GetFriendlyName(Windows::Networking::NetworkOperators::TetheringWiFiBand value);
00019     bool IsBandSupported(Windows::Networking::NetworkOperators::NetworkOperatorTetheringAccessPointConfiguration const& configuration, Windows::Networking::NetworkOperators::TetheringWiFiBand band);
00020 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Connector Member List

This is the complete list of members for Scenario2_Connector, including all inherited members.
_deviceWatcher | Scenario2_Connector | [private]
_fWatcherStarted | Scenario2_Connector | [private]
_publisher | Scenario2_Connector | [private]
btnClose_Click(object sender, RoutedEventArgs e) | Scenario2_Connector | [inline, private]
btnFromId_Click(object sender, RoutedEventArgs e) | Scenario2_Connector | [inline, private]
btnIe_Click(object sender, RoutedEventArgs e) | Scenario2_Connector | [inline, private]
btnSendMessage_Click(object sender, RoutedEventArgs e) | Scenario2_Connector | [inline, private]
btnUnpair_Click(object sender, RoutedEventArgs e) | Scenario2_Connector | [inline, private]
btnWatcher_Click(object sender, RoutedEventArgs e) | Scenario2_Connector | [inline, private]
ConnectedDevices | Scenario2_Connector |
DiscoveredDevices | Scenario2_Connector |
OnConnectionStatusChanged(WiFiDirectDevice sender, object arg) | Scenario2_Connector | [inline, private]
OnDeviceAdded(DeviceWatcher deviceWatcher, DeviceInformation deviceInfo) | Scenario2_Connector | [inline, private]
OnDeviceRemoved(DeviceWatcher deviceWatcher, DeviceInformationUpdate deviceInfoUpdate) | Scenario2_Connector | [inline, private]
OnDeviceUpdated(DeviceWatcher deviceWatcher, DeviceInformationUpdate deviceInfoUpdate) | Scenario2_Connector | [inline, private]
OnEnumerationCompleted(DeviceWatcher deviceWatcher, object o) | Scenario2_Connector | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_Connector | [inline, protected]
OnStopped(DeviceWatcher deviceWatcher, object o) | Scenario2_Connector | [inline, private]
rootPage | Scenario2_Connector | [private]
Scenario2_Connector() | Scenario2_Connector | [inline]
StopWatcher() | Scenario2_Connector | [inline, private]
Generated on Fri Nov 15 2024 22:23:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/Marker.cpp Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

Marker.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007 #include "pch.h"
00008
00009 #include "Marker.h"
00010
00011 using namespace Microsoft::Samples::SimpleCommunication;
00012
00013 HRESULT Microsoft::Samples::SimpleCommunication::CreateMarker(
00014     MFSTREAMSINK_MARKER_TYPE eMarkerType,
00015     const PROPVARIANT *pvarMarkerValue,     // Can be NULL.
00016     const PROPVARIANT *pvarContextValue,    // Can be NULL.
00017     IMarker **ppMarker
00018     )
00019 {
00020     return CMarker::Create(eMarkerType, pvarMarkerValue, pvarContextValue, ppMarker);
00021 }
00022
00023 CMarker::CMarker(MFSTREAMSINK_MARKER_TYPE eMarkerType) : _cRef(1), _eMarkerType(eMarkerType)
00024 {
00025     ZeroMemory(&_varMarkerValue, sizeof(_varMarkerValue));
00026     ZeroMemory(&_varContextValue, sizeof(_varContextValue));
00027 }
00028
00029 CMarker::~CMarker()
00030 {
00031     assert(_cRef == 0);
00032
00033     PropVariantClear(&_varMarkerValue);
00034     PropVariantClear(&_varContextValue);
00035 }
00036
00037 /* static */
00038 HRESULT CMarker::Create(
00039     MFSTREAMSINK_MARKER_TYPE eMarkerType,
00040     const PROPVARIANT *pvarMarkerValue,     // Can be NULL.
00041     const PROPVARIANT *pvarContextValue,    // Can be NULL.
00042     IMarker **ppMarker
00043     )
00044 {
00045     if (ppMarker == nullptr)
00046     {
00047         return E_POINTER;
00048     }
00049
00050     HRESULT hr = S_OK;
00051     ComPtr<CMarker> spMarker;
00052
00053     spMarker.Attach(new (std::nothrow) CMarker(eMarkerType));
00054
00055     if (spMarker == nullptr)
00056     {
00057         hr = E_OUTOFMEMORY;
00058     }
00059
00060     // Copy the marker data.
00061     if (SUCCEEDED(hr))
00062     {
00063         if (pvarMarkerValue)
00064         {
00065             hr = PropVariantCopy(&spMarker->_varMarkerValue, pvarMarkerValue);
00066         }
00067     }
00068
00069     if (SUCCEEDED(hr))
00070     {
00071         if (pvarContextValue)
00072         {
00073             hr = PropVariantCopy(&spMarker->_varContextValue, pvarContextValue);
00074         }
00075     }
00076
00077     if (SUCCEEDED(hr))
00078     {
00079         *ppMarker = spMarker.Detach();
00080     }
00081
00082     return hr;
00083 }
00084
00085 // IUnknown methods.
00086
00087 IFACEMETHODIMP_(ULONG) CMarker::AddRef()
00088 {
00089     return InterlockedIncrement(&_cRef);
00090 }
00091
00092 IFACEMETHODIMP_(ULONG) CMarker::Release()
00093 {
00094     ULONG cRef = InterlockedDecrement(&_cRef);
00095     if (cRef == 0)
00096     {
00097         delete this;
00098     }
00099
00100     return cRef;
00101 }
00102
00103 IFACEMETHODIMP CMarker::QueryInterface(REFIID riid, void **ppv)
00104 {
00105     if (ppv == nullptr)
00106     {
00107         return E_POINTER;
00108     }
00109     (*ppv) = nullptr;
00110
00111     HRESULT hr = S_OK;
00112     if (riid == IID_IUnknown || riid == __uuidof(IMarker))
00113     {
00114         (*ppv) = static_cast<IMarker*>(this);
00115         AddRef();
00116     }
00117     else
00118     {
00119         hr = E_NOINTERFACE;
00120     }
00121
00122     return hr;
00123 }
00124
00125 // IMarker methods
00126 IFACEMETHODIMP CMarker::GetMarkerType(MFSTREAMSINK_MARKER_TYPE *pType)
00127 {
00128     if (pType == NULL)
00129     {
00130         return E_POINTER;
00131     }
00132
00133     *pType = _eMarkerType;
00134     return S_OK;
00135 }
00136
00137 IFACEMETHODIMP CMarker::GetMarkerValue(PROPVARIANT *pvar)
00138 {
00139     if (pvar == NULL)
00140     {
00141         return E_POINTER;
00142     }
00143     return PropVariantCopy(pvar, &_varMarkerValue);
00144
00145 }
00146 IFACEMETHODIMP CMarker::GetContext(PROPVARIANT *pvar)
00147 {
00148     if (pvar == NULL)
00149     {
00150         return E_POINTER;
00151     }
00152     return PropVariantCopy(pvar, &_varContextValue);
00153 }
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cpp/Helpers/ServiceStatusConverter.h Source File

  • WiFiDirectServices
  • cpp
  • Helpers

ServiceStatusConverter.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace SDKTemplate
00015 {
00016     namespace Helpers
00017     {
00018
00019         public ref class ServiceStatusConverter sealed : Windows::UI::Xaml::Data::IValueConverter
00020         {
00021         public:
00022             ServiceStatusConverter() {}
00023             virtual ~ServiceStatusConverter() {}
00024
00025             virtual Platform::Object^ Convert(Platform::Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^ parameter, Platform::String^ language)
00026             {
00027                 return static_cast<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceStatus>(value).ToString();
00028             }
00029
00030             virtual Platform::Object^ ConvertBack(Platform::Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^ parameter, Platform::String^ language)
00031             {
00032                 Platform::String^ statusString = dynamic_cast<Platform::String^>(value);
00033                 if (statusString == Windows::Devices::WiFiDirect::Services::WiFiDirectServiceStatus::Available.ToString())
00034                 {
00035                     return Windows::Devices::WiFiDirect::Services::WiFiDirectServiceStatus::Available;
00036                 }
00037                 else if (statusString == Windows::Devices::WiFiDirect::Services::WiFiDirectServiceStatus::Busy.ToString())
00038                 {
00039                     return Windows::Devices::WiFiDirect::Services::WiFiDirectServiceStatus::Busy;
00040                 }
00041                 else if (statusString == Windows::Devices::WiFiDirect::Services::WiFiDirectServiceStatus::Custom.ToString())
00042                 {
00043                     return Windows::Devices::WiFiDirect::Services::WiFiDirectServiceStatus::Custom;
00044                 }
00045                 else
00046                 {
00047                     return Windows::Devices::WiFiDirect::Services::WiFiDirectServiceStatus::Custom;
00048                 }
00049             }
00050         };
00051     }
00052 }
Generated on Fri Nov 15 2024 22:22:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactPicker/cpp/SampleConfiguration.h Source File

  • ContactPicker
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Contact picker C++ sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038         static Platform::String^ GetContactResult(Windows::ApplicationModel::Contacts::Contact^ contact);
00039
00040     private:
00041         static Platform::Array<Scenario>^ scenariosInner;
00042     };
00043
00044     public value struct Scenario
00045     {
00046         Platform::String^ Title;
00047         Platform::String^ ClassName;
00048     };
00049 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cpp/Scenario2_Listen.xaml.h Source File

  • IoT-GPIO
  • cpp

Scenario2_Listen.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_Listen.xaml.h
00014 //
00015
00016 #pragma once
00017
00018 #include "Scenario2_Listen.g.h"
00019
00020 namespace SDKTemplate
00021 {
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario2_Listen sealed
00024     {
00025     public:
00026         Scenario2_Listen();
00027         void StartStopScenario_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00028
00029     protected:
00030         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs ^e) override;
00031
00032     private:
00033         void StartScenario();
00034         void StopScenario();
00035         void Pin_ValueChanged(Windows::Devices::Gpio::GpioPin ^sender, Windows::Devices::Gpio::GpioPinValueChangedEventArgs ^e);
00036         void Timer_Tick(Platform::Object ^sender, Platform::Object ^e);
00037
00038     private:
00039         const int SET_PIN = 5;
00040         const int LISTEN_PIN = 6;
00041         Windows::Devices::Gpio::GpioPin ^setPin;
00042         Windows::Devices::Gpio::GpioPin ^listenPin;
00043         Windows::Devices::Gpio::GpioPinValue currentValue;
00044         Windows::UI::Xaml::DispatcherTimer ^timer;
00045         Windows::Foundation::EventRegistrationToken valueChangedToken{};
00046         Windows::Foundation::EventRegistrationToken timerToken{};
00047     };
00048 }
Generated on Fri Nov 15 2024 22:20:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisablingScreenCapture/cppwinrt/Project.idl Source File

  • DisablingScreenCapture
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_Enable : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_Enable();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_Disable : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_Disable();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3_AppCapture : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3_AppCapture();
00030     }
00031 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_CreateContact Member List

This is the complete list of members for Scenario1_CreateContact, including all inherited members.
AnnotateContactAsync(Contact contact) | Scenario1_CreateContact | [inline, private]
Cleanup_Click(object sender, RoutedEventArgs e) | Scenario1_CreateContact | [inline, private]
CreateContactAsync() | Scenario1_CreateContact | [inline, private]
GetContactListAsync() | Scenario1_CreateContact | [inline, private]
Pin_Click(object sender, RoutedEventArgs e) | Scenario1_CreateContact | [inline, private]
PinContactAsync(Contact contact) | Scenario1_CreateContact | [inline, private]
rootPage | Scenario1_CreateContact | [private]
Scenario1_CreateContact() | Scenario1_CreateContact | [inline]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DAdvancedColorImages/cpp/D2DAdvancedColorImages/D2DAdvancedColorImagesRenderer.cpp Source File

  • D2DAdvancedColorImages
  • cpp
  • D2DAdvancedColorImages

D2DAdvancedColorImagesRenderer.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "D2DAdvancedColorImagesRenderer.h"
00014 #include "DirectXPage.xaml.h"
00015 #include "DirectXHelper.h"
00016
00017 using namespace D2DAdvancedColorImages;
00018
00019 using namespace concurrency;
00020 using namespace DirectX;
00021 using namespace Microsoft::WRL;
00022 using namespace Platform;
00023 using namespace std;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Windows::Graphics::Display;
00027 using namespace Windows::Storage;
00028 using namespace Windows::Storage::Streams;
00029 using namespace Windows::UI::Input;
00030 using namespace Windows::UI::Xaml;
00031
00032 static const float sc_MaxZoom = 1.0f; // Restrict max zoom to 1:1 scale.
00033 static const unsigned int sc_MaxBytesPerPixel = 16; // Covers all supported image formats.
00034 static const float sc_nominalRefWhite = 80.0f; // Nominal white nits for sRGB and scRGB.
00035
00036 // 400 bins with gamma of 10 lets us measure luminance to within 10% error for any
00037 // luminance above ~1.5 nits, up to 1 million nits.
00038 static const unsigned int sc_histNumBins = 400;
00039 static const float        sc_histGamma = 0.1f;
00040 static const unsigned int sc_histMaxNits = 1000000;
00041
00042 D2DAdvancedColorImagesRenderer::D2DAdvancedColorImagesRenderer(
00043     const std::shared_ptr<DX::DeviceResources>& deviceResources
00044     ) :
00045     m_deviceResources(deviceResources),
00046     m_renderEffectKind(RenderEffectKind::None),
00047     m_zoom(1.0f),
00048     m_minZoom(1.0f), // Dynamically calculated on window size.
00049     m_imageOffset(),
00050     m_pointerPos(),
00051     m_maxCLL(-1.0f),
00052     m_brightnessAdjust(1.0f),
00053     m_imageInfo{},
00054     m_isComputeSupported(false)
00055 {
00056     // Register to be notified if the GPU device is lost or recreated.
00057     m_deviceResources->RegisterDeviceNotify(this);
00058
00059     CreateDeviceIndependentResources();
00060     CreateDeviceDependentResources();
00061     CreateWindowSizeDependentResources();
00062 }
00063
00064 D2DAdvancedColorImagesRenderer::~D2DAdvancedColorImagesRenderer()
00065 {
00066     // Deregister device notification.
00067     m_deviceResources->RegisterDeviceNotify(nullptr);
00068 }
00069
00070 void D2DAdvancedColorImagesRenderer::CreateDeviceIndependentResources()
00071 {
00072     // Register the custom render effects.
00073     DX::ThrowIfFailed(
00074         ReinhardEffect::Register(m_deviceResources->GetD2DFactory())
00075         );
00076
00077     DX::ThrowIfFailed(
00078         FilmicEffect::Register(m_deviceResources->GetD2DFactory())
00079         );
00080
00081     DX::ThrowIfFailed(
00082         SdrOverlayEffect::Register(m_deviceResources->GetD2DFactory())
00083         );
00084
00085     DX::ThrowIfFailed(
00086         LuminanceHeatmapEffect::Register(m_deviceResources->GetD2DFactory())
00087         );
00088 }
00089
00090 void D2DAdvancedColorImagesRenderer::CreateDeviceDependentResources()
00091 {
00092     // All this app's device-dependent resources also depend on
00093     // the loaded image, so they are all created in
00094     // CreateImageDependentResources.
00095 }
00096
00097 void D2DAdvancedColorImagesRenderer::ReleaseDeviceDependentResources()
00098 {
00099 }
00100
00101 // Whenever the app window is resized or changes displays, this method is used
00102 // to update the app's sizing and advanced color state.
00103 void D2DAdvancedColorImagesRenderer::CreateWindowSizeDependentResources()
00104 {
00105     FitImageToWindow();
00106 }
00107
00108 // White level scale is used to multiply the color values in the image; allows the user to
00109 // adjust the brightness of the image on an HDR display.
00110 void D2DAdvancedColorImagesRenderer::SetRenderOptions(
00111     RenderEffectKind effect,
00112     float brightnessAdjustment,
00113     AdvancedColorInfo^ acInfo
00114     )
00115 {
00116     m_dispInfo = acInfo;
00117     m_renderEffectKind = effect;
00118     m_brightnessAdjust = brightnessAdjustment;
00119
00120     auto sdrWhite = m_dispInfo ? m_dispInfo->SdrWhiteLevelInNits : sc_nominalRefWhite;
00121
00122     UpdateWhiteLevelScale(m_brightnessAdjust, sdrWhite);
00123
00124     // Adjust the Direct2D effect graph based on RenderEffectKind.
00125     // Some RenderEffectKind values require us to apply brightness adjustment
00126     // after the effect as their numerical output is affected by any luminance boost.
00127     switch (m_renderEffectKind)
00128     {
00129     // Effect graph: ImageSource > ColorManagement > WhiteScale > Reinhard
00130     case RenderEffectKind::ReinhardTonemap:
00131         m_finalOutput = m_reinhardEffect.Get();
00132         m_whiteScaleEffect->SetInputEffect(0, m_colorManagementEffect.Get());
00133         break;
00134
00135     // Effect graph: ImageSource > ColorManagement > WhiteScale > FilmicTonemap
00136     case RenderEffectKind::FilmicTonemap:
00137         m_finalOutput = m_filmicEffect.Get();
00138         m_whiteScaleEffect->SetInputEffect(0, m_colorManagementEffect.Get());
00139         break;
00140
00141     // Effect graph: ImageSource > ColorManagement > WhiteScale
00142     case RenderEffectKind::None:
00143         m_finalOutput = m_whiteScaleEffect.Get();
00144         m_whiteScaleEffect->SetInputEffect(0, m_colorManagementEffect.Get());
00145         break;
00146
00147     // Effect graph: ImageSource > ColorManagement > Heatmap > WhiteScale
00148     case RenderEffectKind::LuminanceHeatmap:
00149         m_finalOutput = m_whiteScaleEffect.Get();
00150         m_whiteScaleEffect->SetInputEffect(0, m_heatmapEffect.Get());
00151         break;
00152
00153     // Effect graph: ImageSource > ColorManagement > SdrOverlay > WhiteScale
00154     case RenderEffectKind::SdrOverlay:
00155         m_finalOutput = m_whiteScaleEffect.Get();
00156         m_whiteScaleEffect->SetInputEffect(0, m_sdrOverlayEffect.Get());
00157         break;
00158
00159     default:
00160         throw ref new NotImplementedException();
00161         break;
00162     }
00163
00164     Draw();
00165 }
00166
00167 // Reads the provided data stream and decodes an image from it using WIC. These resources are device-
00168 // independent.
00169 ImageInfo D2DAdvancedColorImagesRenderer::LoadImageFromWic(_In_ IStream* imageStream)
00170 {
00171     auto wicFactory = m_deviceResources->GetWicImagingFactory();
00172
00173     // Decode the image using WIC.
00174     ComPtr<IWICBitmapDecoder> decoder;
00175     DX::ThrowIfFailed(
00176         wicFactory->CreateDecoderFromStream(
00177             imageStream,
00178             nullptr,
00179             WICDecodeMetadataCacheOnDemand,
00180             &decoder
00181             ));
00182
00183     ComPtr<IWICBitmapFrameDecode> frame;
00184     DX::ThrowIfFailed(
00185         decoder->GetFrame(0, &frame)
00186         );
00187
00188     return LoadImageCommon(frame.Get());
00189 }
00190
00191 // Simplified heuristic to determine what advanced color kind the image is.
00192 // Requires that all fields other than imageKind are populated.
00193 void D2DAdvancedColorImagesRenderer::PopulateImageInfoACKind(_Inout_ ImageInfo* info)
00194 {
00195     if (info->bitsPerPixel == 0 ||
00196         info->bitsPerChannel == 0 ||
00197         info->size.Width == 0 ||
00198         info->size.Height == 0)
00199     {
00200         DX::ThrowIfFailed(E_INVALIDARG);
00201     }
00202
00203     info->imageKind = AdvancedColorKind::StandardDynamicRange;
00204
00205     // Bit depth > 8bpc or color gamut > sRGB signifies a WCG image.
00206     // The presence of a color profile is used as an approximation for wide gamut.
00207     if (info->bitsPerChannel > 8 || info->numProfiles >= 1)
00208     {
00209         info->imageKind = AdvancedColorKind::WideColorGamut;
00210     }
00211
00212     // This application currently only natively supports HDR images with floating point.
00213     // An image encoded using the HDR10 colorspace is also HDR, but this
00214     // is not automatically detected by the application.
00215     if (info->isFloat == true)
00216     {
00217         info->imageKind = AdvancedColorKind::HighDynamicRange;
00218     }
00219 }
00220
00221 // Configures a Direct2D image pipeline, including source, color management,
00222 // tonemapping, and white level, based on the loaded image.
00223 void D2DAdvancedColorImagesRenderer::CreateImageDependentResources()
00224 {
00225     auto d2dFactory = m_deviceResources->GetD2DFactory();
00226     auto context = m_deviceResources->GetD2DDeviceContext();
00227
00228     // Load the image from WIC using ID2D1ImageSource.
00229     DX::ThrowIfFailed(
00230         m_deviceResources->GetD2DDeviceContext()->CreateImageSourceFromWic(
00231             m_formatConvert.Get(),
00232             &m_imageSource
00233             )
00234         );
00235
00236     // Next, configure the app's effect pipeline, consisting of a color management effect
00237     // followed by a tone mapping effect.
00238
00239     DX::ThrowIfFailed(
00240         context->CreateEffect(CLSID_D2D1ColorManagement, &m_colorManagementEffect)
00241         );
00242
00243     DX::ThrowIfFailed(
00244         m_colorManagementEffect->SetValue(
00245             D2D1_COLORMANAGEMENT_PROP_QUALITY,
00246             D2D1_COLORMANAGEMENT_QUALITY_BEST   // Required for floating point and DXGI color space support.
00247             )
00248         );
00249
00250     // The color management effect takes a source color space and a destination color space,
00251     // and performs the appropriate math to convert images between them.
00252     UpdateImageColorContext();
00253
00254     // The destination color space is the render target's (swap chain's) color space. This app uses an
00255     // FP16 swap chain, which requires the colorspace to be scRGB.
00256     ComPtr<ID2D1ColorContext1> destColorContext;
00257     DX::ThrowIfFailed(
00258         context->CreateColorContextFromDxgiColorSpace(
00259             DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709, // scRGB
00260             &destColorContext
00261             )
00262         );
00263
00264     DX::ThrowIfFailed(
00265         m_colorManagementEffect->SetValue(
00266             D2D1_COLORMANAGEMENT_PROP_DESTINATION_COLOR_CONTEXT,
00267             destColorContext.Get()
00268             )
00269         );
00270
00271     // White level scale is used to multiply the color values in the image; this allows the user
00272     // to adjust the brightness of the image on an HDR display.
00273     DX::ThrowIfFailed(context->CreateEffect(CLSID_D2D1ColorMatrix, &m_whiteScaleEffect));
00274
00275     // Input to white level scale may be modified in SetRenderOptions.
00276     m_whiteScaleEffect->SetInputEffect(0, m_colorManagementEffect.Get());
00277
00278     // Set the actual matrix in SetRenderOptions.
00279
00280     // Instantiate and cache all of the tonemapping/render effects.
00281     // Each effect is implemented as a Direct2D custom effect; see the RenderEffects filter in the
00282     // Solution Explorer.
00283     DX::ThrowIfFailed(
00284         context->CreateEffect(CLSID_CustomReinhardEffect, &m_reinhardEffect)
00285         );
00286
00287     DX::ThrowIfFailed(
00288         context->CreateEffect(CLSID_CustomFilmicEffect, &m_filmicEffect)
00289         );
00290
00291     DX::ThrowIfFailed(
00292         context->CreateEffect(CLSID_CustomSdrOverlayEffect, &m_sdrOverlayEffect)
00293         );
00294
00295     DX::ThrowIfFailed(
00296         context->CreateEffect(CLSID_CustomLuminanceHeatmapEffect, &m_heatmapEffect)
00297         );
00298
00299     m_reinhardEffect->SetInputEffect(0, m_whiteScaleEffect.Get());
00300     m_filmicEffect->SetInputEffect(0, m_whiteScaleEffect.Get());
00301
00302     // For the following effects, we want white level scale to be applied after
00303     // tonemapping (otherwise brightness adjustments will affect numerical values).
00304     m_heatmapEffect->SetInputEffect(0, m_colorManagementEffect.Get());
00305     m_sdrOverlayEffect->SetInputEffect(0, m_colorManagementEffect.Get());
00306
00307     // The remainder of the Direct2D effect graph is constructed in SetRenderOptions based on the
00308     // selected RenderEffectKind.
00309
00310     CreateHistogramResources();
00311 }
00312
00313 // Perform histogram pipeline setup; this should occur as part of image resource creation.
00314 // Histogram results in no visual output but is used to calculate HDR metadata for the image.
00315 void D2DAdvancedColorImagesRenderer::CreateHistogramResources()
00316 {
00317     auto context = m_deviceResources->GetD2DDeviceContext();
00318
00319     // We need to preprocess the image data before running the histogram.
00320     // 1. Spatial downscale to reduce the amount of processing needed.
00321     DX::ThrowIfFailed(
00322         context->CreateEffect(CLSID_D2D1Scale, &m_histogramPrescale)
00323         );
00324
00325     DX::ThrowIfFailed(
00326         m_histogramPrescale->SetValue(D2D1_SCALE_PROP_SCALE, D2D1::Vector2F(0.5f, 0.5f))
00327         );
00328
00329     // The right place to compute HDR metadata is after color management to the
00330     // image's native colorspace but before any tonemapping or adjustments for the display.
00331     m_histogramPrescale->SetInputEffect(0, m_colorManagementEffect.Get());
00332
00333     // 2. Convert scRGB data into luminance (nits).
00334     // 3. Normalize color values. Histogram operates on [0-1] numeric range,
00335     //    while FP16 can go up to 65504 (5+ million nits).
00336     // Both steps are performed in the same color matrix.
00337     ComPtr<ID2D1Effect> histogramMatrix;
00338     DX::ThrowIfFailed(
00339         context->CreateEffect(CLSID_D2D1ColorMatrix, &histogramMatrix)
00340         );
00341
00342     histogramMatrix->SetInputEffect(0, m_histogramPrescale.Get());
00343
00344     float scale = sc_histMaxNits / sc_nominalRefWhite;
00345
00346     D2D1_MATRIX_5X4_F rgbtoYnorm = D2D1::Matrix5x4F(
00347         0.2126f / scale, 0, 0, 0,
00348         0.7152f / scale, 0, 0, 0,
00349         0.0722f / scale, 0, 0, 0,
00350         0              , 0, 0, 1,
00351         0              , 0, 0, 0);
00352     // 1st column: [R] output, contains normalized Y (CIEXYZ).
00353     // 2nd column: [G] output, unused.
00354     // 3rd column: [B] output, unused.
00355     // 4th column: [A] output, alpha passthrough.
00356     // We explicitly calculate Y; this deviates from the CEA 861.3 definition of MaxCLL
00357     // which approximates luminance with max(R, G, B).
00358
00359     DX::ThrowIfFailed(histogramMatrix->SetValue(D2D1_COLORMATRIX_PROP_COLOR_MATRIX, rgbtoYnorm));
00360
00361     // 4. Apply a gamma to allocate more histogram bins to lower luminance levels.
00362     ComPtr<ID2D1Effect> histogramGamma;
00363     DX::ThrowIfFailed(
00364         context->CreateEffect(CLSID_D2D1GammaTransfer, &histogramGamma)
00365         );
00366
00367     histogramGamma->SetInputEffect(0, histogramMatrix.Get());
00368
00369     // Gamma function offers an acceptable tradeoff between simplicity and efficient bin allocation.
00370     // A more sophisticated pipeline would use a more perceptually linear function than gamma.
00371     DX::ThrowIfFailed(histogramGamma->SetValue(D2D1_GAMMATRANSFER_PROP_RED_EXPONENT, sc_histGamma));
00372     // All other channels are passthrough.
00373     DX::ThrowIfFailed(histogramGamma->SetValue(D2D1_GAMMATRANSFER_PROP_GREEN_DISABLE, TRUE));
00374     DX::ThrowIfFailed(histogramGamma->SetValue(D2D1_GAMMATRANSFER_PROP_BLUE_DISABLE, TRUE));
00375     DX::ThrowIfFailed(histogramGamma->SetValue(D2D1_GAMMATRANSFER_PROP_ALPHA_DISABLE, TRUE));
00376
00377     // 5. Finally, the histogram itself.
00378     HRESULT hr = context->CreateEffect(CLSID_D2D1Histogram, &m_histogramEffect);
00379
00380     if (hr == D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES)
00381     {
00382         // The GPU doesn't support compute shaders and we can't run histogram on it.
00383         m_isComputeSupported = false;
00384     }
00385     else
00386     {
00387         DX::ThrowIfFailed(hr);
00388         m_isComputeSupported = true;
00389
00390         DX::ThrowIfFailed(m_histogramEffect->SetValue(D2D1_HISTOGRAM_PROP_NUM_BINS, sc_histNumBins));
00391
00392         m_histogramEffect->SetInputEffect(0, histogramGamma.Get());
00393     }
00394 }
00395
00396 void D2DAdvancedColorImagesRenderer::ReleaseImageDependentResources()
00397 {
00398     m_imageSource.Reset();
00399     m_scaledImage.Reset();
00400     m_colorManagementEffect.Reset();
00401     m_whiteScaleEffect.Reset();
00402     m_reinhardEffect.Reset();
00403     m_filmicEffect.Reset();
00404     m_sdrOverlayEffect.Reset();
00405     m_heatmapEffect.Reset();
00406     m_histogramPrescale.Reset();
00407     m_histogramEffect.Reset();
00408     m_finalOutput.Reset();
00409 }
00410
00411 void D2DAdvancedColorImagesRenderer::UpdateManipulationState(_In_ ManipulationUpdatedEventArgs^ args)
00412 {
00413     Point position = args->Position;
00414     Point positionDelta = args->Delta.Translation;
00415     float zoomDelta = args->Delta.Scale;
00416
00417     m_imageOffset.x += positionDelta.X;
00418     m_imageOffset.y += positionDelta.Y;
00419
00420     // We want to have any zoom operation be "centered" around the pointer position, which
00421     // requires recalculating the view position based on the new zoom and pointer position.
00422     // Step 1: Calculate the absolute pointer position (image position).
00423     D2D1_POINT_2F pointerAbsolutePosition = D2D1::Point2F(
00424         (m_imageOffset.x - position.X) / m_zoom,
00425         (m_imageOffset.y - position.Y) / m_zoom
00426         );
00427
00428     // Step 2: Apply the zoom; do not allow user to go beyond max zoom level.
00429     m_zoom *= zoomDelta;
00430     m_zoom = min(m_zoom, sc_MaxZoom);
00431
00432     // Step 3: Adjust the view position based on the new m_zoom value.
00433     m_imageOffset.x = pointerAbsolutePosition.x * m_zoom + position.X;
00434     m_imageOffset.y = pointerAbsolutePosition.y * m_zoom + position.Y;
00435
00436     // Step 4: Clamp the translation to the window bounds.
00437     Size panelSize = m_deviceResources->GetLogicalSize();
00438     m_imageOffset.x = Clamp(m_imageOffset.x, panelSize.Width - m_imageInfo.size.Width * m_zoom, 0);
00439     m_imageOffset.y = Clamp(m_imageOffset.y, panelSize.Height - m_imageInfo.size.Height * m_zoom, 0);
00440
00441     UpdateImageTransformState();
00442     Draw();
00443 }
00444
00445 // Overrides any pan/zoom state set by the user to fit image to the window size.
00446 // Returns the computed MaxCLL of the image in nits.
00447 float D2DAdvancedColorImagesRenderer::FitImageToWindow()
00448 {
00449     if (m_imageSource)
00450     {
00451         Size panelSize = m_deviceResources->GetLogicalSize();
00452
00453         // Set image to be letterboxed in the window, up to the max allowed scale factor.
00454         float letterboxZoom = min(
00455             panelSize.Width / m_imageInfo.size.Width,
00456             panelSize.Height / m_imageInfo.size.Height);
00457
00458         m_zoom = min(sc_MaxZoom, letterboxZoom);
00459
00460         // Center the image.
00461         m_imageOffset = D2D1::Point2F(
00462             (panelSize.Width - (m_imageInfo.size.Width * m_zoom)) / 2.0f,
00463             (panelSize.Height - (m_imageInfo.size.Height * m_zoom)) / 2.0f
00464             );
00465
00466         UpdateImageTransformState();
00467
00468         // HDR metadata is supposed to be independent of any rendering options, but
00469         // we can't compute it until the full effect graph is hooked up, which is here.
00470         ComputeHdrMetadata();
00471     }
00472
00473     return m_maxCLL;
00474 }
00475
00476 // After initial decode, obtain image information and do common setup.
00477 // Populates all members of ImageInfo.
00478 ImageInfo D2DAdvancedColorImagesRenderer::LoadImageCommon(_In_ IWICBitmapSource* source)
00479 {
00480     auto wicFactory = m_deviceResources->GetWicImagingFactory();
00481     m_imageInfo = {};
00482
00483     // Attempt to read the embedded color profile from the image; only valid for WIC images.
00484     ComPtr<IWICBitmapFrameDecode> frame;
00485     if (SUCCEEDED(source->QueryInterface(IID_PPV_ARGS(&frame))))
00486     {
00487         DX::ThrowIfFailed(
00488             wicFactory->CreateColorContext(&m_wicColorContext)
00489             );
00490
00491         DX::ThrowIfFailed(
00492             frame->GetColorContexts(
00493                 1,
00494                 m_wicColorContext.GetAddressOf(),
00495                 &m_imageInfo.numProfiles
00496                 )
00497             );
00498     }
00499
00500     // Check whether the image data is natively stored in a floating-point format, and
00501     // decode to the appropriate WIC pixel format.
00502
00503     WICPixelFormatGUID pixelFormat;
00504     DX::ThrowIfFailed(
00505         source->GetPixelFormat(&pixelFormat)
00506         );
00507
00508     ComPtr<IWICComponentInfo> componentInfo;
00509     DX::ThrowIfFailed(
00510         wicFactory->CreateComponentInfo(
00511             pixelFormat,
00512             &componentInfo
00513             )
00514         );
00515
00516     ComPtr<IWICPixelFormatInfo2> pixelFormatInfo;
00517     DX::ThrowIfFailed(
00518         componentInfo.As(&pixelFormatInfo)
00519         );
00520
00521     WICPixelFormatNumericRepresentation formatNumber;
00522     DX::ThrowIfFailed(
00523         pixelFormatInfo->GetNumericRepresentation(&formatNumber)
00524         );
00525
00526     DX::ThrowIfFailed(pixelFormatInfo->GetBitsPerPixel(&m_imageInfo.bitsPerPixel));
00527
00528     // Calculate the bits per channel (bit depth) using GetChannelMask.
00529     // This accounts for nonstandard color channel packing and padding, e.g. 32bppRGB.
00530     unsigned char channelMaskBytes[sc_MaxBytesPerPixel];
00531     ZeroMemory(channelMaskBytes, ARRAYSIZE(channelMaskBytes));
00532     unsigned int maskSize;
00533
00534     DX::ThrowIfFailed(
00535         pixelFormatInfo->GetChannelMask(
00536             0,  // Read the first color channel.
00537             ARRAYSIZE(channelMaskBytes),
00538             channelMaskBytes,
00539             &maskSize)
00540         );
00541
00542     // Count up the number of bits set in the mask for the first color channel.
00543     for (unsigned int i = 0; i < maskSize * 8; i++)
00544     {
00545         unsigned int byte = i / 8;
00546         unsigned int bit = i % 8;
00547         if ((channelMaskBytes[byte] & (1 << bit)) != 0)
00548         {
00549             m_imageInfo.bitsPerChannel += 1;
00550         }
00551     }
00552
00553     m_imageInfo.isFloat = (WICPixelFormatNumericRepresentationFloat == formatNumber) ? true : false;
00554
00555     // When decoding, preserve the numeric representation (float vs. non-float)
00556     // of the native image data. This avoids WIC performing an implicit gamma conversion
00557     // which occurs when converting between a fixed-point/integer pixel format (sRGB gamma)
00558     // and a float-point pixel format (linear gamma). Gamma adjustment, if specified by
00559     // the ICC profile, will be performed by the Direct2D color management effect.
00560
00561     WICPixelFormatGUID fmt = {};
00562     if (m_imageInfo.isFloat)
00563     {
00564         fmt = GUID_WICPixelFormat64bppPRGBAHalf; // Equivalent to DXGI_FORMAT_R16G16B16A16_FLOAT.
00565     }
00566     else
00567     {
00568         fmt = GUID_WICPixelFormat64bppPRGBA; // Equivalent to DXGI_FORMAT_R16G16B16A16_UNORM.
00569                                              // Many SDR images (e.g. JPEG) use <=32bpp, so it
00570                                              // is possible to further optimize this for memory usage.
00571     }
00572
00573     DX::ThrowIfFailed(
00574         wicFactory->CreateFormatConverter(&m_formatConvert)
00575         );
00576
00577     DX::ThrowIfFailed(
00578         m_formatConvert->Initialize(
00579             source,
00580             fmt,
00581             WICBitmapDitherTypeNone,
00582             nullptr,
00583             0.0f,
00584             WICBitmapPaletteTypeCustom
00585             )
00586         );
00587
00588     UINT width;
00589     UINT height;
00590     DX::ThrowIfFailed(
00591         m_formatConvert->GetSize(&width, &height)
00592         );
00593
00594     m_imageInfo.size = Size(static_cast<float>(width), static_cast<float>(height));
00595
00596     PopulateImageInfoACKind(&m_imageInfo);
00597
00598     return m_imageInfo;
00599 }
00600
00601 // Derive the source color context from the image (embedded ICC profile or metadata).
00602 void D2DAdvancedColorImagesRenderer::UpdateImageColorContext()
00603 {
00604     auto context = m_deviceResources->GetD2DDeviceContext();
00605
00606     ComPtr<ID2D1ColorContext> sourceColorContext;
00607
00608     // For most image types, automatically derive the color context from the image.
00609     if (m_imageInfo.numProfiles >= 1)
00610     {
00611         DX::ThrowIfFailed(
00612             context->CreateColorContextFromWicColorContext(
00613                 m_wicColorContext.Get(),
00614                 &sourceColorContext
00615             )
00616         );
00617     }
00618     else
00619     {
00620         // Since no embedded color profile/metadata exists, select a default
00621         // based on the pixel format: floating point == scRGB, others == sRGB.
00622         DX::ThrowIfFailed(
00623             context->CreateColorContext(
00624                 m_imageInfo.isFloat ? D2D1_COLOR_SPACE_SCRGB : D2D1_COLOR_SPACE_SRGB,
00625                 nullptr,
00626                 0,
00627                 &sourceColorContext
00628             )
00629         );
00630     }
00631
00632     DX::ThrowIfFailed(
00633         m_colorManagementEffect->SetValue(
00634             D2D1_COLORMANAGEMENT_PROP_SOURCE_COLOR_CONTEXT,
00635             sourceColorContext.Get()
00636         )
00637     );
00638 }
00639
00640 // When connected to an HDR display, the OS renders SDR content (e.g. 8888 UNORM) at
00641 // a user configurable white level; this typically is around 200-300 nits. It is the responsibility
00642 // of an advanced color app (e.g. FP16 scRGB) to emulate the OS-implemented SDR white level adjustment,
00643 // BUT only for non-HDR content (SDR or WCG).
00644 void D2DAdvancedColorImagesRenderer::UpdateWhiteLevelScale(float brightnessAdjustment, float sdrWhiteLevel)
00645 {
00646     float scale = 1.0f;
00647
00648     switch (m_imageInfo.imageKind)
00649     {
00650     case AdvancedColorKind::HighDynamicRange:
00651         // HDR content should not be compensated by the SdrWhiteLevel parameter.
00652         scale = 1.0f;
00653         break;
00654
00655     case AdvancedColorKind::StandardDynamicRange:
00656     case AdvancedColorKind::WideColorGamut:
00657     default:
00658         scale = sdrWhiteLevel / sc_nominalRefWhite;
00659         break;
00660     }
00661
00662     // The user may want to manually adjust brightness specifically for this image, on top of any
00663     // white level adjustment for SDR/WCG content. Brightness adjustment using a linear gamma scale
00664     // is mainly useful for HDR displays, but can be useful for HDR content tonemapped to an SDR/WCG display.
00665     scale *= brightnessAdjustment;
00666
00667     // SDR white level scaling is performing by multiplying RGB color values in linear gamma.
00668     // We implement this with a Direct2D matrix effect.
00669     D2D1_MATRIX_5X4_F matrix = D2D1::Matrix5x4F(
00670         scale, 0, 0, 0,  // [R] Multiply each color channel
00671         0, scale, 0, 0,  // [G] by the scale factor in
00672         0, 0, scale, 0,  // [B] linear gamma space.
00673         0, 0, 0    , 1,  // [A] Preserve alpha values.
00674         0, 0, 0    , 0); //     No offset.
00675
00676     DX::ThrowIfFailed(m_whiteScaleEffect->SetValue(D2D1_COLORMATRIX_PROP_COLOR_MATRIX, matrix));
00677 }
00678
00679 // Call this after updating any spatial transform state to regenerate the effect graph.
00680 void D2DAdvancedColorImagesRenderer::UpdateImageTransformState()
00681 {
00682     if (m_imageSource)
00683     {
00684         // When using ID2D1ImageSource, the recommend method of scaling is to use
00685         // ID2D1TransformedImageSource. It is inexpensive to recreate this object.
00686         D2D1_TRANSFORMED_IMAGE_SOURCE_PROPERTIES props =
00687         {
00688             D2D1_ORIENTATION_DEFAULT,
00689             m_zoom,
00690             m_zoom,
00691             D2D1_INTERPOLATION_MODE_LINEAR, // This is ignored when using DrawImage.
00692             D2D1_TRANSFORMED_IMAGE_SOURCE_OPTIONS_NONE
00693         };
00694
00695         DX::ThrowIfFailed(
00696             m_deviceResources->GetD2DDeviceContext()->CreateTransformedImageSource(
00697                 m_imageSource.Get(),
00698                 &props,
00699                 &m_scaledImage
00700                 )
00701             );
00702
00703         // Set the new image as the new source to the effect pipeline.
00704         m_colorManagementEffect->SetInput(0, m_scaledImage.Get());
00705     }
00706 }
00707
00708 // Uses a histogram to compute a modified version of MaxCLL (ST.2086 max content light level).
00709 // Performs Begin/EndDraw on the D2D context.
00710 void D2DAdvancedColorImagesRenderer::ComputeHdrMetadata()
00711 {
00712     // Initialize with a sentinel value.
00713     m_maxCLL = -1.0f;
00714
00715     // MaxCLL is not meaningful for SDR or WCG images.
00716     if ((!m_isComputeSupported) ||
00717         (m_imageInfo.imageKind != AdvancedColorKind::HighDynamicRange))
00718     {
00719         return;
00720     }
00721
00722     // MaxCLL is nominally calculated for the single brightest pixel in a frame.
00723     // But we take a slightly more conservative definition that takes the 99.99th percentile
00724     // to account for extreme outliers in the image.
00725     float maxCLLPercent = 0.9999f;
00726
00727     auto ctx = m_deviceResources->GetD2DDeviceContext();
00728
00729     ctx->BeginDraw();
00730
00731     ctx->DrawImage(m_histogramEffect.Get());
00732
00733     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00734     // is lost. It will be handled during the next call to Present.
00735     HRESULT hr = ctx->EndDraw();
00736     if (hr != D2DERR_RECREATE_TARGET)
00737     {
00738         DX::ThrowIfFailed(hr);
00739     }
00740
00741     float *histogramData = new float[sc_histNumBins];
00742     DX::ThrowIfFailed(
00743         m_histogramEffect->GetValue(D2D1_HISTOGRAM_PROP_HISTOGRAM_OUTPUT,
00744             reinterpret_cast<BYTE*>(histogramData),
00745             sc_histNumBins * sizeof(float)
00746             )
00747         );
00748
00749     unsigned int maxCLLbin = 0;
00750     float runningSum = 0.0f; // Cumulative sum of values in histogram is 1.0.
00751     for (int i = sc_histNumBins - 1; i >= 0; i--)
00752     {
00753         runningSum += histogramData[i];
00754         maxCLLbin = i;
00755
00756         if (runningSum >= 1.0f - maxCLLPercent)
00757         {
00758             break;
00759         }
00760     }
00761
00762     float binNorm = static_cast<float>(maxCLLbin) / static_cast<float>(sc_histNumBins);
00763     m_maxCLL = powf(binNorm, 1 / sc_histGamma) * sc_histMaxNits;
00764
00765     // Some drivers have a bug where histogram will always return 0. Treat this as unknown.
00766     m_maxCLL = (m_maxCLL == 0.0f) ? -1.0f : m_maxCLL;
00767 }
00768
00769 // Set HDR10 metadata to allow HDR displays to optimize behavior based on our content.
00770 void D2DAdvancedColorImagesRenderer::EmitHdrMetadata()
00771 {
00772     auto acKind = m_dispInfo ? m_dispInfo->CurrentAdvancedColorKind : AdvancedColorKind::StandardDynamicRange;
00773
00774     if (acKind == AdvancedColorKind::HighDynamicRange)
00775     {
00776         DXGI_HDR_METADATA_HDR10 metadata = {};
00777
00778         // This sample doesn't do any chrominance (e.g. xy) gamut mapping, so just use default
00779         // color primaries values; a more sophisticated app will explicitly set these.
00780         // DXGI_HDR_METADATA_HDR10 defines primaries as 1/50000 of a unit in xy space.
00781         metadata.RedPrimary[0]   = static_cast<UINT16>(m_dispInfo->RedPrimary.X   * 50000.0f);
00782         metadata.RedPrimary[1]   = static_cast<UINT16>(m_dispInfo->RedPrimary.Y   * 50000.0f);
00783         metadata.GreenPrimary[0] = static_cast<UINT16>(m_dispInfo->GreenPrimary.X * 50000.0f);
00784         metadata.GreenPrimary[1] = static_cast<UINT16>(m_dispInfo->GreenPrimary.Y * 50000.0f);
00785         metadata.BluePrimary[0]  = static_cast<UINT16>(m_dispInfo->BluePrimary.X  * 50000.0f);
00786         metadata.BluePrimary[1]  = static_cast<UINT16>(m_dispInfo->BluePrimary.Y  * 50000.0f);
00787         metadata.WhitePoint[0]   = static_cast<UINT16>(m_dispInfo->WhitePoint.X   * 50000.0f);
00788         metadata.WhitePoint[1]   = static_cast<UINT16>(m_dispInfo->WhitePoint.Y   * 50000.0f);
00789
00790         float effectiveMaxCLL = 0;
00791
00792         switch (m_renderEffectKind)
00793         {
00794         // Currently only the "None" render effect results in pixel values that exceed
00795         // the OS-specified SDR white level, as it just passes through HDR color values.
00796         case RenderEffectKind::None:
00797             effectiveMaxCLL = max(m_maxCLL, 0.0f) * m_brightnessAdjust;
00798             break;
00799
00800         default:
00801             effectiveMaxCLL = m_dispInfo->SdrWhiteLevelInNits * m_brightnessAdjust;
00802             break;
00803         }
00804
00805         // DXGI_HDR_METADATA_HDR10 defines MaxCLL in integer nits.
00806         metadata.MaxContentLightLevel = static_cast<UINT16>(effectiveMaxCLL);
00807
00808         // The luminance analysis doesn't calculate MaxFrameAverageLightLevel. We also don't have mastering
00809         // information (i.e. reference display in a studio), so Min/MaxMasteringLuminance is not relevant.
00810         // Leave these values as 0.
00811
00812         auto sc = m_deviceResources->GetSwapChain();
00813
00814         ComPtr<IDXGISwapChain4> sc4;
00815         DX::ThrowIfFailed(sc->QueryInterface(IID_PPV_ARGS(&sc4)));
00816         DX::ThrowIfFailed(sc4->SetHDRMetaData(DXGI_HDR_METADATA_TYPE_HDR10, sizeof(metadata), &metadata));
00817     }
00818 }
00819
00820 // Renders the loaded image with user-specified options.
00821 void D2DAdvancedColorImagesRenderer::Draw()
00822 {
00823     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00824
00825     d2dContext->BeginDraw();
00826
00827     d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::Black));
00828
00829     d2dContext->SetTransform(m_deviceResources->GetOrientationTransform2D());
00830
00831     if (m_scaledImage)
00832     {
00833         d2dContext->DrawImage(m_finalOutput.Get(), m_imageOffset);
00834
00835         EmitHdrMetadata();
00836     }
00837
00838     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00839     // is lost. It will be handled during the next call to Present.
00840     HRESULT hr = d2dContext->EndDraw();
00841     if (hr != D2DERR_RECREATE_TARGET)
00842     {
00843         DX::ThrowIfFailed(hr);
00844     }
00845
00846     m_deviceResources->Present();
00847 }
00848
00849 // Notifies renderers that device resources need to be released.
00850 void D2DAdvancedColorImagesRenderer::OnDeviceLost()
00851 {
00852     ReleaseImageDependentResources();
00853     ReleaseDeviceDependentResources();
00854 }
00855
00856 // Notifies renderers that device resources may now be recreated.
00857 void D2DAdvancedColorImagesRenderer::OnDeviceRestored()
00858 {
00859     CreateDeviceDependentResources();
00860     CreateImageDependentResources();
00861     CreateWindowSizeDependentResources();
00862
00863     Draw();
00864 }
Generated on Fri Nov 15 2024 22:19:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Tasks/GeofenceBackgroundTask.h Source File

  • Geolocation
  • cppwinrt
  • Tasks

GeofenceBackgroundTask.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include "GeofenceBackgroundTask.g.h"
00004
00005 namespace winrt::BackgroundTask::implementation
00006 {
00007     struct GeofenceBackgroundTask : GeofenceBackgroundTaskT<GeofenceBackgroundTask>
00008     {
00009         GeofenceBackgroundTask() = default;
00010
00011         void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance const& taskInstance);
00012
00013     private:
00014         Windows::Foundation::Collections::IPropertySet m_values{ Windows::Storage::ApplicationData::Current().LocalSettings().Values() };
00015
00016         // Value determined by how many max length event descriptors (91 chars)
00017         // stored as a JSON string can fit in 8K (max allowed for local settings)
00018         static constexpr int maxEventDescriptors = 42;
00019
00020         void ProcessGeofenceStateChangedReports();
00021         hstring GenerateReportDescription(Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport const& report);
00022     };
00023 }
00024
00025 namespace winrt::BackgroundTask::factory_implementation
00026 {
00027     struct GeofenceBackgroundTask : GeofenceBackgroundTaskT<GeofenceBackgroundTask, implementation::GeofenceBackgroundTask>
00028     {
00029     };
00030 }
Generated on Fri Nov 15 2024 22:19:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Altimeter/cpp/Scenario1_DataEvents.xaml.cpp Source File

  • Altimeter
  • cpp

Scenario1_DataEvents.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_DataEvents.xaml.cpp
00014 // Implementation of the Scenario1_DataEvents class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario1_DataEvents.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Windows::Devices::Sensors;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::UI::Core;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 Scenario1_DataEvents::Scenario1_DataEvents() : rootPage(MainPage::Current), desiredReportIntervalMs(0)
00031 {
00032     InitializeComponent();
00033
00034     sensor = Altimeter::GetDefault();
00035     if (nullptr != sensor)
00036     {
00037         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00038         // This value will be used later to activate the sensor.
00039         uint32 minReportIntervalMs = sensor->MinimumReportInterval;
00040         desiredReportIntervalMs = minReportIntervalMs > 1000 ? minReportIntervalMs : 1000;
00041     }
00042     else
00043     {
00044         rootPage->NotifyUser("No altimeter found", NotifyType::ErrorMessage);
00045     }
00046 }
00047
00048 /// <summary>
00049 /// Invoked when this page is about to be displayed in a Frame.
00050 /// </summary>
00051 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00052 /// property is typically used to configure the page.</param>
00053 void Scenario1_DataEvents::OnNavigatedTo(NavigationEventArgs^ e)
00054 {
00055     ScenarioEnableButton->IsEnabled = true;
00056     ScenarioDisableButton->IsEnabled = false;
00057 }
00058
00059 /// <summary>
00060 /// Invoked when this page is no longer displayed.
00061 /// </summary>
00062 /// <param name="e"></param>
00063 void Scenario1_DataEvents::OnNavigatedFrom(NavigationEventArgs^ e)
00064 {
00065     // If the navigation is external to the app do not clean up.
00066     // This can occur on Phone when suspending the app.
00067     if (NavigationMode::Forward == e->NavigationMode && nullptr == e->Uri)
00068     {
00069         return;
00070     }
00071
00072     if (ScenarioDisableButton->IsEnabled)
00073     {
00074         Window::Current->VisibilityChanged::remove(visibilityToken);
00075         sensor->ReadingChanged::remove(readingToken);
00076
00077         // Restore the default report interval to release resources while the sensor is not in use
00078         sensor->ReportInterval = 0;
00079     }
00080 }
00081
00082 /// <summary>
00083 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00084 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00085 /// </summary>ScenarioOutput_M
00086 /// <param name="sender"></param>
00087 /// <param name="e">
00088 /// Event data that can be examined for the current visibility state.
00089 /// </param>
00090 void Scenario1_DataEvents::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00091 {
00092     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00093     if (ScenarioDisableButton->IsEnabled)
00094     {
00095         if (e->Visible)
00096         {
00097             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00098             readingToken = sensor->ReadingChanged::add(ref new TypedEventHandler<Altimeter^, AltimeterReadingChangedEventArgs^>(this, &Scenario1_DataEvents::ReadingChanged));
00099         }
00100         else
00101         {
00102             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00103             sensor->ReadingChanged::remove(readingToken);
00104         }
00105     }
00106 }
00107
00108 void Scenario1_DataEvents::ReadingChanged(Altimeter^ sender, AltimeterReadingChangedEventArgs^ e)
00109 {
00110     // We need to dispatch to the UI thread to display the output
00111     Dispatcher->RunAsync(
00112         CoreDispatcherPriority::Normal,
00113         ref new DispatchedHandler(
00114             [this, e]()
00115             {
00116                 AltimeterReading^ reading = e->Reading;
00117
00118                 ScenarioOutput_M->Text = reading->AltitudeChangeInMeters.ToString();
00119             },
00120             CallbackContext::Any
00121             )
00122         );
00123 }
00124
00125 void Scenario1_DataEvents::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00126 {
00127     if (nullptr != sensor)
00128     {
00129         // Establish the report interval
00130         sensor->ReportInterval = desiredReportIntervalMs;
00131
00132         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario1_DataEvents::VisibilityChanged));
00133         readingToken = sensor->ReadingChanged::add(ref new TypedEventHandler<Altimeter^, AltimeterReadingChangedEventArgs^>(this, &Scenario1_DataEvents::ReadingChanged));
00134
00135         ScenarioEnableButton->IsEnabled = false;
00136         ScenarioDisableButton->IsEnabled = true;
00137     }
00138     else
00139     {
00140         rootPage->NotifyUser("No Altimeter found", NotifyType::ErrorMessage);
00141     }
00142 }
00143
00144 void Scenario1_DataEvents::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00145 {
00146     Window::Current->VisibilityChanged::remove(visibilityToken);
00147     sensor->ReadingChanged::remove(readingToken);
00148
00149     // Restore the default report interval to release resources while the sensor is not in use
00150     sensor->ReportInterval = 0;
00151
00152     ScenarioEnableButton->IsEnabled = true;
00153     ScenarioDisableButton->IsEnabled = false;
00154 }
Generated on Fri Nov 15 2024 22:17:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FolderEnumeration/cppwinrt/Scenario2.h Source File

  • FolderEnumeration
  • cppwinrt

Scenario2.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2 : Scenario2T<Scenario2>
00019     {
00020         Scenario2();
00021         fire_and_forget GroupByMonthButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00022         fire_and_forget GroupByRatingButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00023         fire_and_forget GroupByTagButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00024
00025     private:
00026         Windows::Foundation::IAsyncAction GroupByHelperAsync(Windows::Storage::Search::QueryOptions queryOptions);
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario2 : Scenario2T<Scenario2, implementation::Scenario2>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:19:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SampleDataModel Member List

This is the complete list of members for SampleDataModel, including all inherited members.
GetSampleData() | SampleDataModel | [inline, static]
ImagePath | SampleDataModel |
IsFlagged | SampleDataModel |
IsNew | SampleDataModel |
SampleDataModel(string title, string imagePath, bool isNew=false, bool isFlagged=false) | SampleDataModel | [inline]
Title | SampleDataModel |
ToString() | SampleDataModel | [inline]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundMediaPlayback/cs/Services/SettingsService.cs Source File

  • BackgroundMediaPlayback
  • cs
  • Services

SettingsService.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using Windows.Foundation.Collections;
00007 using Windows.Storage;
00008
00009 namespace BackgroundMediaPlayback.Services
00010 {
00011     class SettingsService
00012     {
00013         static SettingsService instance;
00014
00015         public static SettingsService Instance
00016         {
00017             get
00018             {
00019                 if (instance == null)
00020                     instance = new SettingsService();
00021
00022                 return instance;
00023             }
00024         }
00025
00026         const string ToastOnAppEventsKey = "toast-on-app-events";
00027         const string UseCustomControlsKey = "use-custom-controls";
00028         IPropertySet settings = ApplicationData.Current.RoamingSettings.Values;
00029
00030         public event EventHandler UseCustomControlsChanged;
00031
00032         public bool ToastOnAppEvents
00033         {
00034             get
00035             {
00036                 object setting;
00037                 if (settings.TryGetValue(ToastOnAppEventsKey, out setting))
00038                     return (bool)setting;
00039
00040                 return true;
00041             }
00042             set
00043             {
00044                 settings[ToastOnAppEventsKey] = value;
00045             }
00046         }
00047
00048         public bool UseCustomControls
00049         {
00050             get
00051             {
00052                 object setting;
00053                 if (settings.TryGetValue(UseCustomControlsKey, out setting))
00054                     return (bool)setting;
00055
00056                 return false;
00057             }
00058             set
00059             {
00060                 if (UseCustomControls != value) {
00061                     settings[UseCustomControlsKey] = value;
00062                     UseCustomControlsChanged?.Invoke(this, EventArgs.Empty);
00063                 }
00064             }
00065         }
00066     }
00067 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LanguageFont/cs/Scenario1_UIFonts.xaml.cs Source File

  • LanguageFont
  • cs

Scenario1_UIFonts.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011
00012 using Windows.Globalization.Fonts;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario1_UIFonts : Page
00020     {
00021         public Scenario1_UIFonts()
00022         {
00023             this.InitializeComponent();
00024         }
00025
00026         private void ApplyFonts_Click(object sender, RoutedEventArgs e)
00027         {
00028             var languageFontGroup = new LanguageFontGroup("ja-JP");
00029
00030             // Change the Font value with selected font from LanguageFontGroup API
00031             MainPage.ApplyLanguageFont(HeadingTextBlock, languageFontGroup.UIHeadingFont);
00032             MainPage.ApplyLanguageFont(BodyTextBlock, languageFontGroup.UITextFont);
00033         }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:20:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

TabHeader Member List

This is the complete list of members for TabHeader, including all inherited members.
Glyph | TabHeader |
GlyphProperty | TabHeader | [static]
Label | TabHeader |
LabelProperty | TabHeader | [static]
TabHeader() | TabHeader | [inline]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraFaceDetection/cpp/pch.cpp Source File

  • CameraFaceDetection
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/BasicTimer.h Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

BasicTimer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // A simple timer class used to drive the render loop of the actively-animated
00015 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00016 // high-resolution timing information.
00017 ref class BasicTimer
00018 {
00019 private:
00020     LARGE_INTEGER m_frequency;
00021     LARGE_INTEGER m_currentTime;
00022     LARGE_INTEGER m_startTime;
00023     LARGE_INTEGER m_lastTime;
00024     float m_total;
00025     float m_delta;
00026
00027 internal:
00028     BasicTimer();
00029     void Reset();
00030     void Update();
00031     property float Total
00032     {
00033         float get();
00034     }
00035     property float Delta
00036     {
00037         float get();
00038     }
00039 };
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6_SecondaryTileNotification Member List

This is the complete list of members for Scenario6_SecondaryTileNotification, including all inherited members.
PinLiveTile_Click(object sender, RoutedEventArgs e) | Scenario6_SecondaryTileNotification | [inline, private]
rootPage | Scenario6_SecondaryTileNotification | [private]
Scenario6_SecondaryTileNotification() | Scenario6_SecondaryTileNotification | [inline]
SendBadgeNotification_Click(object sender, RoutedEventArgs e) | Scenario6_SecondaryTileNotification | [inline, private]
SendBadgeNotificationWithStringManipulation_Click(object sender, RoutedEventArgs e) | Scenario6_SecondaryTileNotification | [inline, private]
SendTileNotification_Click(object sender, RoutedEventArgs e) | Scenario6_SecondaryTileNotification | [inline, private]
SendTileNotificationWithStringManipulation_Click(object sender, RoutedEventArgs e) | Scenario6_SecondaryTileNotification | [inline, private]
VerifyTileIsPinned() | Scenario6_SecondaryTileNotification | [inline, private]
Generated on Fri Nov 15 2024 22:23:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cpp/pch.cpp Source File

  • DateTimeFormatting
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/Common/DeviceResources.cpp Source File

  • HolographicTagAlong
  • cpp
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DeviceResources.h"
00014 #include "DirectXHelper.h"
00015
00016 #include <Collection.h>
00017 #include <windows.graphics.directx.direct3d11.interop.h>
00018
00019 using namespace D2D1;
00020 using namespace Microsoft::WRL;
00021 using namespace Windows::Graphics::DirectX::Direct3D11;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::Graphics::Holographic;
00024
00025 // Constructor for DeviceResources.
00026 DX::DeviceResources::DeviceResources()
00027 {
00028     CreateDeviceIndependentResources();
00029 }
00030
00031 // Configures resources that don't depend on the Direct3D device.
00032 void DX::DeviceResources::CreateDeviceIndependentResources()
00033 {
00034     // Initialize Direct2D resources.
00035     D2D1_FACTORY_OPTIONS options {};
00036
00037 #if defined(_DEBUG)
00038     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00039     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00040 #endif
00041
00042     // Initialize the Direct2D Factory.
00043     DX::ThrowIfFailed(
00044         D2D1CreateFactory(
00045             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00046             __uuidof(ID2D1Factory2),
00047             &options,
00048             &m_d2dFactory
00049             )
00050         );
00051
00052     // Initialize the DirectWrite Factory.
00053     DX::ThrowIfFailed(
00054         DWriteCreateFactory(
00055             DWRITE_FACTORY_TYPE_SHARED,
00056             __uuidof(IDWriteFactory2),
00057             &m_dwriteFactory
00058             )
00059         );
00060
00061     // Initialize the Windows Imaging Component (WIC) Factory.
00062     DX::ThrowIfFailed(
00063         CoCreateInstance(
00064             CLSID_WICImagingFactory2,
00065             nullptr,
00066             CLSCTX_INPROC_SERVER,
00067             IID_PPV_ARGS(&m_wicFactory)
00068             )
00069         );
00070 }
00071
00072 void DX::DeviceResources::SetHolographicSpace(HolographicSpace^ holographicSpace)
00073 {
00074     // Cache the holographic space. Used to re-initalize during device-lost scenarios.
00075     m_holographicSpace = holographicSpace;
00076
00077     InitializeUsingHolographicSpace();
00078 }
00079
00080 void DX::DeviceResources::InitializeUsingHolographicSpace()
00081 {
00082     // The holographic space might need to determine which adapter supports
00083     // holograms, in which case it will specify a non-zero PrimaryAdapterId.
00084     LUID id =
00085     {
00086         m_holographicSpace->PrimaryAdapterId.LowPart,
00087         m_holographicSpace->PrimaryAdapterId.HighPart
00088     };
00089
00090     // When a primary adapter ID is given to the app, the app should find
00091     // the corresponding DXGI adapter and use it to create Direct3D devices
00092     // and device contexts. Otherwise, there is no restriction on the DXGI
00093     // adapter the app can use.
00094     if ((id.HighPart != 0) && (id.LowPart != 0))
00095     {
00096         UINT createFlags = 0;
00097 #ifdef DEBUG
00098         if (DX::SdkLayersAvailable())
00099         {
00100             createFlags |= DXGI_CREATE_FACTORY_DEBUG;
00101         }
00102 #endif
00103         // Create the DXGI factory.
00104         ComPtr<IDXGIFactory1> dxgiFactory;
00105         DX::ThrowIfFailed(
00106             CreateDXGIFactory2(
00107                 createFlags,
00108                 IID_PPV_ARGS(&dxgiFactory)
00109                 )
00110             );
00111         ComPtr<IDXGIFactory4> dxgiFactory4;
00112         DX::ThrowIfFailed(dxgiFactory.As(&dxgiFactory4));
00113
00114         // Retrieve the adapter specified by the holographic space.
00115         DX::ThrowIfFailed(
00116             dxgiFactory4->EnumAdapterByLuid(
00117                 id,
00118                 IID_PPV_ARGS(&m_dxgiAdapter)
00119                 )
00120             );
00121     }
00122     else
00123     {
00124         m_dxgiAdapter.Reset();
00125     }
00126
00127     CreateDeviceResources();
00128
00129     m_holographicSpace->SetDirect3D11Device(m_d3dInteropDevice);
00130 }
00131
00132 // Configures the Direct3D device, and stores handles to it and the device context.
00133 void DX::DeviceResources::CreateDeviceResources()
00134 {
00135     // This flag adds support for surfaces with a different color channel ordering
00136     // than the API default. It is required for compatibility with Direct2D.
00137     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00138
00139 #if defined(_DEBUG)
00140     if (DX::SdkLayersAvailable())
00141     {
00142         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00143         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00144     }
00145 #endif
00146
00147     // This array defines the set of DirectX hardware feature levels this app will support.
00148     // Note the ordering should be preserved.
00149     // Note that HoloLens supports feature level 11.1. The HoloLens emulator is also capable
00150     // of running on graphics cards starting with feature level 10.0.
00151     D3D_FEATURE_LEVEL featureLevels [] =
00152     {
00153         D3D_FEATURE_LEVEL_12_1,
00154         D3D_FEATURE_LEVEL_12_0,
00155         D3D_FEATURE_LEVEL_11_1,
00156         D3D_FEATURE_LEVEL_11_0,
00157         D3D_FEATURE_LEVEL_10_1,
00158         D3D_FEATURE_LEVEL_10_0
00159     };
00160
00161     // Create the Direct3D 11 API device object and a corresponding context.
00162     ComPtr<ID3D11Device> device;
00163     ComPtr<ID3D11DeviceContext> context;
00164
00165     const HRESULT hr = D3D11CreateDevice(
00166         m_dxgiAdapter.Get(),        // Either nullptr, or the primary adapter determined by Windows Holographic.
00167         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00168         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00169         creationFlags,              // Set debug and Direct2D compatibility flags.
00170         featureLevels,              // List of feature levels this app can support.
00171         ARRAYSIZE(featureLevels),   // Size of the list above.
00172         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00173         &device,                    // Returns the Direct3D device created.
00174         &m_d3dFeatureLevel,         // Returns feature level of device created.
00175         &context                    // Returns the device immediate context.
00176         );
00177
00178     if (FAILED(hr))
00179     {
00180         // If the initialization fails, fall back to the WARP device.
00181         // For more information on WARP, see:
00182         // http://go.microsoft.com/fwlink/?LinkId=286690
00183         DX::ThrowIfFailed(
00184             D3D11CreateDevice(
00185                 nullptr,              // Use the default DXGI adapter for WARP.
00186                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00187                 0,
00188                 creationFlags,
00189                 featureLevels,
00190                 ARRAYSIZE(featureLevels),
00191                 D3D11_SDK_VERSION,
00192                 &device,
00193                 &m_d3dFeatureLevel,
00194                 &context
00195                 )
00196             );
00197     }
00198
00199     // Store pointers to the Direct3D device and immediate context.
00200     DX::ThrowIfFailed(
00201         device.As(&m_d3dDevice)
00202         );
00203
00204     DX::ThrowIfFailed(
00205         context.As(&m_d3dContext)
00206         );
00207
00208     // Acquire the DXGI interface for the Direct3D device.
00209     ComPtr<IDXGIDevice3> dxgiDevice;
00210     DX::ThrowIfFailed(
00211         m_d3dDevice.As(&dxgiDevice)
00212         );
00213
00214     // Wrap the native device using a WinRT interop object.
00215     m_d3dInteropDevice = CreateDirect3DDevice(dxgiDevice.Get());
00216
00217     // Cache the DXGI adapter.
00218     // This is for the case of no preferred DXGI adapter, or fallback to WARP.
00219     ComPtr<IDXGIAdapter> dxgiAdapter;
00220     DX::ThrowIfFailed(
00221         dxgiDevice->GetAdapter(&dxgiAdapter)
00222         );
00223     DX::ThrowIfFailed(
00224         dxgiAdapter.As(&m_dxgiAdapter)
00225         );
00226
00227     // Check for device support for the optional feature that allows setting the render target array index from the vertex shader stage.
00228     D3D11_FEATURE_DATA_D3D11_OPTIONS3 options;
00229     m_d3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS3, &options, sizeof(options));
00230     if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer)
00231     {
00232         m_supportsVprt = true;
00233     }
00234 }
00235
00236 // Validates the back buffer for each HolographicCamera and recreates
00237 // resources for back buffers that have changed.
00238 // Locks the set of holographic camera resources until the function exits.
00239 void DX::DeviceResources::EnsureCameraResources(
00240     HolographicFrame^ frame,
00241     HolographicFramePrediction^ prediction)
00242 {
00243     UseHolographicCameraResources<void>([this, frame, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00244     {
00245         for (const auto& pose : prediction->CameraPoses)
00246         {
00247             HolographicCameraRenderingParameters^ renderingParameters = frame->GetRenderingParameters(pose);
00248             CameraResources* pCameraResources = cameraResourceMap[pose->HolographicCamera->Id].get();
00249
00250             pCameraResources->CreateResourcesForBackBuffer(this, renderingParameters);
00251         }
00252     });
00253 }
00254
00255 // Prepares to allocate resources and adds resource views for a camera.
00256 // Locks the set of holographic camera resources until the function exits.
00257 void DX::DeviceResources::AddHolographicCamera(HolographicCamera^ camera)
00258 {
00259     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00260     {
00261         cameraResourceMap[camera->Id] = std::make_unique<CameraResources>(camera);
00262     });
00263 }
00264
00265 // Deallocates resources for a camera and removes the camera from the set.
00266 // Locks the set of holographic camera resources until the function exits.
00267 void DX::DeviceResources::RemoveHolographicCamera(HolographicCamera^ camera)
00268 {
00269     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00270     {
00271         CameraResources* pCameraResources = cameraResourceMap[camera->Id].get();
00272
00273         if (pCameraResources != nullptr)
00274         {
00275             pCameraResources->ReleaseResourcesForBackBuffer(this);
00276             cameraResourceMap.erase(camera->Id);
00277         }
00278     });
00279 }
00280
00281 // Recreate all device resources and set them back to the current state.
00282 // Locks the set of holographic camera resources until the function exits.
00283 void DX::DeviceResources::HandleDeviceLost()
00284 {
00285     if (m_deviceNotify != nullptr)
00286     {
00287         m_deviceNotify->OnDeviceLost();
00288     }
00289
00290     UseHolographicCameraResources<void>([this](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00291     {
00292         for (auto& pair : cameraResourceMap)
00293         {
00294             CameraResources* pCameraResources = pair.second.get();
00295             pCameraResources->ReleaseResourcesForBackBuffer(this);
00296         }
00297     });
00298
00299     InitializeUsingHolographicSpace();
00300
00301     if (m_deviceNotify != nullptr)
00302     {
00303         m_deviceNotify->OnDeviceRestored();
00304     }
00305 }
00306
00307 // Register our DeviceNotify to be informed on device lost and creation.
00308 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00309 {
00310     m_deviceNotify = deviceNotify;
00311 }
00312
00313 // Call this method when the app suspends. It provides a hint to the driver that the app
00314 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00315 void DX::DeviceResources::Trim()
00316 {
00317     m_d3dContext->ClearState();
00318
00319     ComPtr<IDXGIDevice3> dxgiDevice;
00320     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00321     dxgiDevice->Trim();
00322 }
00323
00324 // Present the contents of the swap chain to the screen.
00325 // Locks the set of holographic camera resources until the function exits.
00326 void DX::DeviceResources::Present(HolographicFrame^ frame)
00327 {
00328     // By default, this API waits for the frame to finish before it returns.
00329     // Holographic apps should wait for the previous frame to finish before
00330     // starting work on a new frame. This allows for better results from
00331     // holographic frame predictions.
00332     HolographicFramePresentResult presentResult = frame->PresentUsingCurrentPrediction();
00333
00334     HolographicFramePrediction^ prediction = frame->CurrentPrediction;
00335     UseHolographicCameraResources<void>([this, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00336     {
00337         for (auto cameraPose : prediction->CameraPoses)
00338         {
00339             // This represents the device-based resources for a HolographicCamera.
00340             DX::CameraResources* pCameraResources = cameraResourceMap[cameraPose->HolographicCamera->Id].get();
00341
00342             // Discard the contents of the render target.
00343             // This is a valid operation only when the existing contents will be
00344             // entirely overwritten. If dirty or scroll rects are used, this call
00345             // should be removed.
00346             m_d3dContext->DiscardView(pCameraResources->GetBackBufferRenderTargetView());
00347
00348             // Discard the contents of the depth stencil.
00349             m_d3dContext->DiscardView(pCameraResources->GetDepthStencilView());
00350         }
00351     });
00352
00353     // The PresentUsingCurrentPrediction API will detect when the graphics device
00354     // changes or becomes invalid. When this happens, it is considered a Direct3D
00355     // device lost scenario.
00356     if (presentResult == HolographicFramePresentResult::DeviceRemoved)
00357     {
00358         // The Direct3D device, context, and resources should be recreated.
00359         HandleDeviceLost();
00360     }
00361 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/Scenario5.xaml.h Source File

  • SimpleInk
  • cpp

Scenario5.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario5.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario5 sealed
00024     {
00025     public:
00026         Scenario5();
00027     private:
00028         MainPage^ rootPage;
00029         void Scenario5::OnSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00030     };
00031 }
Generated on Fri Nov 15 2024 22:18:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
consolidated | sealed | [private]
CreateForCurrentView() | sealed | [static]
dispatcher | sealed | [private]
FinalizeRelease() | sealed | [private]
globalMutex | sealed | [private]
InternalReleased | sealed | [private]
madeVisible | sealed | [private]
refCount | sealed | [private]
RegisterForEvents() | sealed | [private]
released | sealed | [private]
StartViewInUse() | sealed |
StopViewInUse() | sealed |
title | sealed | [private]
UnregisterForEvents() | sealed | [private]
ViewConsolidated(Windows::UI::ViewManagement::ApplicationView^sender, Windows::UI::ViewManagement::ApplicationViewConsolidatedEventArgs^e) | sealed | [private]
viewId | sealed | [private]
ViewLifetimeControl(Windows::UI::Core::CoreWindow^newWindow) | sealed | [private]
VisibilityChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
visibilityToken | sealed | [private]
window | sealed | [private]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DEVICEPROPS Member List

This is the complete list of members for DEVICEPROPS, including all inherited members.
ContentStream | DEVICEPROPS
Frequency | DEVICEPROPS
hnsBufferDuration | DEVICEPROPS
IsBackground | DEVICEPROPS
IsHWOffload | DEVICEPROPS
IsLowLatency | DEVICEPROPS
IsRawChosen | DEVICEPROPS
IsRawSupported | DEVICEPROPS
IsTonePlayback | DEVICEPROPS
Generated on Fri Nov 15 2024 22:23:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Audio/XAudio2Helpers.h Source File

  • HolographicVoiceInput
  • cpp
  • Audio

XAudio2Helpers.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Sets up XAudio2 for HRTF processing
00015 static HRESULT SetupXAudio2(_In_ const WAVEFORMATEX* format, _In_ IXAPO* xApo, _Outptr_ IXAudio2** xAudio2, _Outptr_ IXAudio2SourceVoice** sourceVoice)
00016 {
00017     using namespace Microsoft::WRL;
00018
00019     // Initialize XAudio2 for HRTF processing with "XAUDIO2_1024_QUANTUM" flag which specifies processing frame size of 1024 samples.
00020     ComPtr<IXAudio2> xAudio2Instance;
00021     auto hr = XAudio2Create(&xAudio2Instance, XAUDIO2_1024_QUANTUM);
00022
00023     // HRTF APO expects mono audio data at 48kHz and produces stereo output at 48kHz
00024     // so we create a stereo mastering voice with specific rendering sample rate of 48kHz.
00025     // Mastering voice will be automatically destroyed when XAudio2 instance is destroyed.
00026     IXAudio2MasteringVoice* masteringVoice = nullptr;
00027     if (SUCCEEDED(hr))
00028     {
00029         hr = xAudio2Instance->CreateMasteringVoice(&masteringVoice, 2, 48000);
00030     }
00031
00032     // Create a source voice to accept audio data in the specified format.
00033     IXAudio2SourceVoice* sourceVoiceInstance = nullptr;
00034     if (SUCCEEDED(hr))
00035     {
00036         hr = xAudio2Instance->CreateSourceVoice(&sourceVoiceInstance, format);
00037     }
00038
00039     // Create a submix voice that will host the xAPO.
00040     // This submix voice will be detroyed when XAudio2 instance is destroyed.
00041     IXAudio2SubmixVoice* submixVoice = nullptr;
00042
00043     if (SUCCEEDED(hr))
00044     {
00045         XAUDIO2_EFFECT_DESCRIPTOR fxDesc{};
00046         fxDesc.InitialState = TRUE;
00047         fxDesc.OutputChannels = 2;          // Stereo output
00048         fxDesc.pEffect = xApo;              // HRTF xAPO set as the effect.
00049
00050         XAUDIO2_EFFECT_CHAIN fxChain{};
00051         fxChain.EffectCount = 1;
00052         fxChain.pEffectDescriptors = &fxDesc;
00053
00054         XAUDIO2_VOICE_SENDS sends = {};
00055         XAUDIO2_SEND_DESCRIPTOR sendDesc = {};
00056         sendDesc.pOutputVoice = masteringVoice;
00057         sends.SendCount = 1;
00058         sends.pSends = &sendDesc;
00059
00060         // HRTF APO expects mono 48kHz input, so we configure the submix voice for that format.
00061         hr = xAudio2Instance->CreateSubmixVoice(&submixVoice, 1, 48000, 0, 0, &sends, &fxChain);
00062     }
00063
00064     // Route the source voice to the submix voice.
00065     // The complete graph pipeline looks like this -
00066     // Source Voice -> Submix Voice (HRTF xAPO) -> Mastering Voice
00067     if (SUCCEEDED(hr))
00068     {
00069         XAUDIO2_VOICE_SENDS sends = {};
00070         XAUDIO2_SEND_DESCRIPTOR sendDesc = {};
00071         sendDesc.pOutputVoice = submixVoice;
00072         sends.SendCount = 1;
00073         sends.pSends = &sendDesc;
00074         hr = sourceVoiceInstance->SetOutputVoices(&sends);
00075     }
00076
00077     // Return the XAudio2 instance and the source voice.
00078     if (SUCCEEDED(hr))
00079     {
00080         *sourceVoice = sourceVoiceInstance;
00081         *xAudio2 = xAudio2Instance.Detach();
00082     }
00083
00084     return hr;
00085 }
00086
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6_ScrollIntoView Member List

This is the complete list of members for Scenario6_ScrollIntoView, including all inherited members.
_items | Scenario6_ScrollIntoView | [private]
Scenario6_ScrollIntoView() | Scenario6_ScrollIntoView | [inline]
Scroll_Click(object sender, RoutedEventArgs e) | Scenario6_ScrollIntoView | [inline, private]
Generated on Fri Nov 15 2024 22:23:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothLE/cppwinrt/Scenario3_ServerForeground.h Source File

  • BluetoothLE
  • cppwinrt

Scenario3_ServerForeground.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_ServerForeground.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario3_ServerForeground : Scenario3_ServerForegroundT<Scenario3_ServerForeground>
00020     {
00021         Scenario3_ServerForeground();
00022
00023         fire_and_forget OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025
00026         fire_and_forget PublishButton_ClickAsync();
00027     private:
00028         enum class CalculatorCharacteristics
00029         {
00030             Operand1 = 1,
00031             Operand2 = 2,
00032             Operator = 3,
00033         };
00034
00035         enum class CalculatorOperators
00036         {
00037             Add = 1,
00038             Subtract = 2,
00039             Multiply = 3,
00040             Divide = 4,
00041         };
00042
00043         bool IsValidOperator(CalculatorOperators op)
00044         {
00045             return op >= CalculatorOperators::Add && op < CalculatorOperators::Divide;
00046         }
00047
00048         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00049         Windows::Devices::Bluetooth::GenericAttributeProfile::GattServiceProvider serviceProvider{ nullptr };
00050         Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic op1Characteristic{ nullptr };
00051         Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic op2Characteristic{ nullptr };
00052         Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic operatorCharacteristic{ nullptr };
00053         Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic resultCharacteristic{ nullptr };
00054         int operand1Received = 0;
00055         int operand2Received = 0;
00056         CalculatorOperators operatorReceived;
00057         int resultVal = 0;
00058         bool peripheralSupported = false;
00059
00060         event_token op1CharacteristicWriteToken;
00061         event_token op2CharacteristicWriteToken;
00062         event_token operatorCharacteristicWriteToken;
00063         event_token resultCharacteristicReadToken;
00064         event_token resultCharacteristicClientsChangedToken;
00065         event_token serviceProviderAdvertisementChangedToken;
00066
00067         fire_and_forget UpdateUX();
00068         static Windows::Foundation::IAsyncOperation<bool> CheckPeripheralRoleSupportAsync();
00069         Windows::Foundation::IAsyncOperation<bool> ServiceProviderInitAsync();
00070         void ResultCharacteristic_SubscribedClientsChanged(Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic const& sender, IInspectable const& args);
00071         void ServiceProvider_AdvertisementStatusChanged(Windows::Devices::Bluetooth::GenericAttributeProfile::GattServiceProvider const& sender, Windows::Devices::Bluetooth::GenericAttributeProfile::GattServiceProviderAdvertisementStatusChangedEventArgs const& args);
00072         fire_and_forget ResultCharacteristic_ReadRequestedAsync(Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic const& sender, Windows::Devices::Bluetooth::GenericAttributeProfile::GattReadRequestedEventArgs args);
00073         int ComputeResult();
00074         fire_and_forget NotifyClientDevices(int computedValue);
00075         fire_and_forget Op1Characteristic_WriteRequestedAsync(Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic const& sender, Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequestedEventArgs args);
00076         fire_and_forget Op2Characteristic_WriteRequestedAsync(Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic const& sender, Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequestedEventArgs args);
00077         fire_and_forget OperatorCharacteristic_WriteRequestedAsync(Windows::Devices::Bluetooth::GenericAttributeProfile::GattLocalCharacteristic const& sender, Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequestedEventArgs args);
00078         void ProcessWriteCharacteristic(Windows::Devices::Bluetooth::GenericAttributeProfile::GattWriteRequest const& request, CalculatorCharacteristics opCode);
00079     };
00080 }
00081
00082 namespace winrt::SDKTemplate::factory_implementation
00083 {
00084     struct Scenario3_ServerForeground : Scenario3_ServerForegroundT<Scenario3_ServerForeground, implementation::Scenario3_ServerForeground>
00085     {
00086     };
00087 }
Generated on Fri Nov 15 2024 22:18:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContextMenu/cpp/pch.cpp Source File

  • ContextMenu
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: KeyCredentialManager/cpp/SampleConfiguration.cpp Source File

  • KeyCredentialManager
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Sign In Scenario", "SDKTemplate.UserSelect" }
00012 };
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Client/FirmwareAccess.h Source File

  • CustomCapability
  • Service
  • Client

FirmwareAccess.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 extern "C" {
00004
00005 #define MANUFACTURER_NAME_LENGTH_MAX 1024
00006
00007 __declspec(dllexport)
00008 DWORD
00009 GetManufacturerNameFromSmbios(
00010     _Out_ wchar_t* ManufacturerName,
00011     _In_  DWORD    Size
00012     );
00013
00014 __declspec(dllexport)
00015 DWORD
00016 GetSecureBootEnabledFromUefi(
00017     _Out_ bool* SecureBootEnabled
00018     );
00019 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cs/Scenario2.xaml.cs Source File

  • FileThumbnails
  • cs

Scenario2.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Storage;
00014 using Windows.Storage.FileProperties;
00015 using Windows.Storage.Pickers;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario2 : Page
00023     {
00024         MainPage rootPage = MainPage.Current;
00025
00026         public Scenario2()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         protected override void OnNavigatedTo(NavigationEventArgs e)
00032         {
00033             rootPage.ResetOutput(ThumbnailImage, OutputTextBlock);
00034         }
00035
00036         private async void GetThumbnailButton_Click(object sender, RoutedEventArgs e)
00037         {
00038             rootPage.ResetOutput(ThumbnailImage, OutputTextBlock);
00039
00040             // Pick a music file
00041             FileOpenPicker openPicker = new FileOpenPicker();
00042             foreach (string extension in FileExtensions.Music)
00043             {
00044                 openPicker.FileTypeFilter.Add(extension);
00045             }
00046
00047             StorageFile file = await openPicker.PickSingleFileAsync();
00048
00049             if (file != null)
00050             {
00051                 const ThumbnailMode thumbnailMode = ThumbnailMode.MusicView;
00052                 const uint size = 100;
00053                 using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(thumbnailMode, size))
00054                 {
00055                     // Also verify the type is ThumbnailType.Image (album art) instead of ThumbnailType.Icon
00056                     // (which may be returned as a fallback if the file does not provide album art)
00057                     if (thumbnail != null && thumbnail.Type == ThumbnailType.Image)
00058                     {
00059                         // Display the thumbnail
00060                         MainPage.DisplayResult(ThumbnailImage, OutputTextBlock, thumbnailMode.ToString(), size, file, thumbnail, false);
00061                     }
00062                     else
00063                     {
00064                         rootPage.NotifyUser(Errors.NoAlbumArt, NotifyType.StatusMessage);
00065                     }
00066                 }
00067             }
00068             else
00069             {
00070                 rootPage.NotifyUser(Errors.Cancel, NotifyType.StatusMessage);
00071             }
00072         }
00073     }
00074 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cpp/Scenario4_Control.xaml.h Source File

  • XamlCommanding
  • cpp

Scenario4_Control.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_Control.g.h"
00015
00016 namespace SDKTemplate
00017 {
00018     /// <summary>
00019     /// An empty page that can be used on its own or navigated to within a Frame.
00020     /// </summary>
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class Scenario4_Control sealed
00023     {
00024     public:
00025         Scenario4_Control();
00026     };
00027 }
Generated on Fri Nov 15 2024 22:22:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cpp/SampleConfiguration.h Source File

  • LineDisplay
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Line Display C++ Sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038         Platform::String^ LineDisplayId = nullptr;
00039
00040         Concurrency::task<Windows::Devices::PointOfService::ClaimedLineDisplay^> ClaimScenarioLineDisplayAsync();
00041
00042     private:
00043         static Platform::Array<Scenario>^ scenariosInner;
00044     };
00045
00046     public value struct Scenario
00047     {
00048         Platform::String^ Title;
00049         Platform::String^ ClassName;
00050     };
00051
00052     namespace Helpers
00053     {
00054         template<typename T>
00055         T ParseUIntWithFallback(Windows::UI::Xaml::Controls::TextBox^ textBox, T fallback)
00056         {
00057             wchar_t* end;
00058             errno = 0;
00059             unsigned long value = wcstoul(textBox->Text->Data(), &end, 10);
00060             if (errno == ERANGE || *end != L'\0')
00061             {
00062                 return fallback;
00063             }
00064
00065             return static_cast<T>(value);
00066         }
00067
00068         void AddItem(Windows::UI::Xaml::Controls::ComboBox^ comboBox, Platform::Object^ value, Platform::String^ name);
00069
00070         template<typename T>
00071         void AddItem(Windows::UI::Xaml::Controls::ComboBox^ comboBox, T value)
00072         {
00073             AddItem(comboBox, value, value.ToString());
00074         }
00075
00076         template<typename T>
00077         T GetSelectedItemTag(Windows::UI::Xaml::Controls::Primitives::Selector^ selector)
00078         {
00079             return safe_cast<T>(safe_cast<Windows::UI::Xaml::FrameworkElement^>(selector->SelectedItem)->Tag);
00080         }
00081
00082         inline Windows::Foundation::TimeSpan TimeSpanFromMilliseconds(double value)
00083         {
00084             return Windows::Foundation::TimeSpan{ static_cast<long long>(value * 10000) };
00085         }
00086
00087         inline double MillisecondsFromTimeSpan(Windows::Foundation::TimeSpan value)
00088         {
00089             return static_cast<double>(value.Duration) / 10000;
00090         }
00091     }
00092
00093     template<typename TLambda>
00094     Concurrency::task<void> invoke_async_lambda(TLambda lambda)
00095     {
00096         co_await lambda();
00097     }
00098 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlAnimatedGif/cs/Scenario1_Basic.xaml.cs Source File

  • XamlAnimatedGif
  • cs

Scenario1_Basic.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.IO;
00015 using System.Linq;
00016 using System.Runtime.InteropServices.WindowsRuntime;
00017 using Windows.Foundation;
00018 using Windows.Foundation.Collections;
00019 using Windows.Storage;
00020 using Windows.System;
00021 using Windows.UI.Xaml;
00022 using Windows.UI.Xaml.Controls;
00023 using Windows.UI.Xaml.Controls.Primitives;
00024 using Windows.UI.Xaml.Data;
00025 using Windows.UI.Xaml.Input;
00026 using Windows.UI.Xaml.Media;
00027 using Windows.UI.Xaml.Media.Imaging;
00028 using Windows.UI.Xaml.Navigation;
00029
00030 namespace SDKTemplate
00031 {
00032
00033     public sealed partial class Scenario1_Basic : Page
00034     {
00035
00036         public Scenario1_Basic()
00037         {
00038             InitializeComponent();
00039         }
00040
00041         private void ClickToPlaySource_ImageOpened(object sender, RoutedEventArgs e)
00042         {
00043             // Once ImageOpened is raised, we can query whether an image is animated.
00044             if (ClickToPlaySource.IsAnimatedBitmap)
00045             {
00046                 PlaybackButtons.Visibility = Visibility.Visible;
00047             }
00048         }
00049     }
00050 }
Generated on Fri Nov 15 2024 22:19:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FileDataSource2 Member List

This is the complete list of members for FileDataSource2, including all inherited members.
_count | FileDataSource2 | [private]
_dispatcher | FileDataSource2 | [private]
_folder | FileDataSource2 | [private]
_queryResult | FileDataSource2 | [private]
Add(object value) | FileDataSource2 | [inline]
Clear() | FileDataSource2 | [inline]
CollectionChanged | FileDataSource2 |
Contains(object value) | FileDataSource2 | [inline]
CopyTo(Array array, int index) | FileDataSource2 | [inline]
Count | FileDataSource2 |
DeselectRange(ItemIndexRange range) | FileDataSource2 | [inline]
Dispose() | FileDataSource2 | [inline]
fetchDataCallback(ItemIndexRange batch, CancellationToken ct) | FileDataSource2 | [inline, private]
fetchSelectionDataCallback(ItemIndexRange batch, CancellationToken ct) | FileDataSource2 | [inline, private]
FileDataSource2() | FileDataSource2 | [inline, private]
GetDataSoure(string path) | FileDataSource2 | [inline, static]
GetEnumerator() | FileDataSource2 | [inline]
GetSelectedRanges() | FileDataSource2 | [inline]
IndexOf(object value) | FileDataSource2 | [inline]
Insert(int index, object value) | FileDataSource2 | [inline]
IsFixedSize | FileDataSource2 |
IsReadOnly | FileDataSource2 |
IsSelected(int index) | FileDataSource2 | [inline]
IsSynchronized | FileDataSource2 |
itemCache | FileDataSource2 | [private]
ItemCache_CacheChanged(object sender, CacheChangedEventArgs< FileItem > args) | FileDataSource2 | [inline, private]
QueryResult_ContentsChanged(IStorageQueryResultBase sender, object args) | FileDataSource2 | [inline, private]
RangesChanged(ItemIndexRange visibleRange, IReadOnlyList< ItemIndexRange > trackedItems) | FileDataSource2 | [inline]
RemapSelection() | FileDataSource2 | [inline, private]
Remove(object value) | FileDataSource2 | [inline]
RemoveAt(int index) | FileDataSource2 | [inline]
ResetCollection() | FileDataSource2 | [inline]
selection | FileDataSource2 | [private]
selectionCache | FileDataSource2 | [private]
SelectRange(ItemIndexRange range) | FileDataSource2 | [inline]
SetFolder(StorageFolder folder) | FileDataSource2 | [inline]
SyncRoot | FileDataSource2 |
this | FileDataSource2 |
UpdateCount() | FileDataSource2 | [inline, private]
Generated on Fri Nov 15 2024 22:23:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IccDetection Member List

This is the complete list of members for IccDetection, including all inherited members.
Atr | IccDetection |
AtrInformation | IccDetection |
CategoryIndicator enum name | IccDetection | [private]
connectionObject | IccDetection | [private]
DetectCard() | IccDetection | [inline, private]
DetectCardTypeAync() | IccDetection | [inline]
IccDetection(SmartCard card, SmartCardConnection connection) | IccDetection | [inline]
PcscCardName | IccDetection |
PcscDeviceClass | IccDetection |
smartCard | IccDetection | [private]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3 Member List

This is the complete list of members for Scenario3, including all inherited members.
CommandBar_Closed(object sender, object e) | Scenario3 | [inline, private]
CommandBar_Closing(object sender, object e) | Scenario3 | [inline, private]
CommandBar_Opened(object sender, object e) | Scenario3 | [inline, private]
CommandBar_Opening(object sender, object e) | Scenario3 | [inline, private]
Scenario3() | Scenario3 | [inline]
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

UserAndKeyHintMessage Member List

This is the complete list of members for UserAndKeyHintMessage, including all inherited members.
PublicKeyHint | UserAndKeyHintMessage
UserId | UserAndKeyHintMessage
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AccessHandler Member List

This is the complete list of members for AccessHandler, including all inherited members.
AccessHandler(SmartCardConnection ScConnection) | AccessHandler | [inline]
connectionObject | AccessHandler | [private]
GetUidAsync() | AccessHandler | [inline]
LoadKeyAsync(byte[] mifareKey, byte keySlotNumber=0) | AccessHandler | [inline]
ReadAsync(ushort blockNumber, GeneralAuthenticate.GeneralAuthenticateKeyType keyType, byte keySlotNumber=0) | AccessHandler | [inline]
TransparentExchangeAsync(byte[] commandData) | AccessHandler | [inline]
WriteAsync(byte blockNumber, byte[] data, GeneralAuthenticate.GeneralAuthenticateKeyType keyType, byte keySlotNumber=0) | AccessHandler | [inline]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario2.xaml.cpp Source File

  • MapControl
  • cpp

Scenario2.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario2.xaml.h"
00013 #include "WindowsNumerics.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Platform::Collections;
00019 using namespace Windows::Foundation::Numerics;
00020 using namespace Windows::Devices::Geolocation;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Storage::Streams;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls::Maps;
00025
00026 Scenario2::Scenario2()
00027 {
00028     InitializeComponent();
00029
00030     mapIconStreamReference = RandomAccessStreamReference::CreateFromUri(ref new Uri("ms-appx:///Assets/MapPin.png"));
00031     mapBillboardStreamReference = RandomAccessStreamReference::CreateFromUri(ref new Uri("ms-appx:///Assets/billboard.jpg"));
00032     mapModelStreamReference = RandomAccessStreamReference::CreateFromUri(ref new Uri("ms-appx:///Assets/box.3mf"));
00033 }
00034
00035 void Scenario2::MyMap_Loaded(Object^ sender, RoutedEventArgs^ e)
00036 {
00037     myMap->Center = MainPage::SeattleGeopoint;
00038     myMap->ZoomLevel = 17;
00039     myMap->DesiredPitch = 45;
00040 }
00041
00042 void Scenario2::mapClearButton_Click(Object^ sender, RoutedEventArgs^ e)
00043 {
00044     myMap->MapElements->Clear();
00045 }
00046
00047 void Scenario2::mapIconAddButton_Click(Object^ sender, RoutedEventArgs^ e)
00048 {
00049     MapIcon^ mapIcon = ref new MapIcon();
00050     mapIcon->Location = myMap->Center;
00051     mapIcon->NormalizedAnchorPoint = Point(0.5, 1.0);
00052     mapIcon->Title = "My Friend";
00053     mapIcon->Image = mapIconStreamReference;
00054     mapIcon->ZIndex = 0;
00055     myMap->MapElements->Append(mapIcon);
00056 }
00057
00058 void Scenario2::mapBillboardAddButton_Click(Object^ sender, RoutedEventArgs^ e)
00059 {
00060     MapBillboard^ mapBillboard = ref new MapBillboard(myMap->ActualCamera);
00061     mapBillboard->Location = myMap->Center;
00062     mapBillboard->NormalizedAnchorPoint = Point(0.5, 1.0);
00063     mapBillboard->Image = mapBillboardStreamReference;
00064     myMap->MapElements->Append(mapBillboard);
00065 }
00066
00067 void Scenario2::mapElement3DAddButton_Click(Object^ sender, RoutedEventArgs^ e)
00068 {
00069     concurrency::create_task(MapModel3D::CreateFrom3MFAsync(mapModelStreamReference, MapModel3DShadingOption::Smooth)).then([this](MapModel3D^ model)
00070     {
00071         // Compensate for 3D Model's local coordinate system and scale
00072         const float AltitudeOffset = 45.0f;
00073         const float HeadingOffset = -90.0f;
00074         const float ScaleOffset = 0.1f;
00075
00076         if (model != nullptr)
00077         {
00078             // MapElement3D scales with respect to the perspective projection of the 3D camera
00079             MapElement3D^ mapElement3D = ref new MapElement3D();
00080             mapElement3D->Location = ref new Geopoint({
00081                 myMap->Center->Position.Latitude,
00082                 myMap->Center->Position.Longitude,
00083                 AltitudeOffset },
00084                 AltitudeReferenceSystem::Terrain);
00085             mapElement3D->Model = model;
00086             mapElement3D->Heading = HeadingOffset + 180;
00087             mapElement3D->Scale = float3(ScaleOffset, ScaleOffset, ScaleOffset);
00088             myMap->MapElements->Append(mapElement3D);
00089         }
00090     });
00091 }
00092
00093 void Scenario2::mapPolygonAddButton_Click(Object^ sender, RoutedEventArgs^ e)
00094 {
00095     double centerLatitude = myMap->Center->Position.Latitude;
00096     double centerLongitude = myMap->Center->Position.Longitude;
00097     MapPolygon^ mapPolygon = ref new MapPolygon();
00098
00099     auto list = ref new Vector<BasicGeoposition, GeoEquals>();
00100     list->Append({ centerLatitude + 0.0005, centerLongitude - 0.001 });
00101     list->Append({ centerLatitude - 0.0005, centerLongitude - 0.001 });
00102     list->Append({ centerLatitude - 0.0005, centerLongitude + 0.001 });
00103     list->Append({ centerLatitude + 0.0005, centerLongitude + 0.001 });
00104
00105     mapPolygon->Path = ref new Geopath(list);
00106     mapPolygon->ZIndex = 1;
00107     mapPolygon->FillColor = Windows::UI::Colors::Red;
00108     mapPolygon->StrokeColor = Windows::UI::Colors::Blue;
00109     mapPolygon->StrokeThickness = 3;
00110     mapPolygon->StrokeDashed = false;
00111     myMap->MapElements->Append(mapPolygon);
00112 }
00113
00114 void Scenario2::mapPolylineAddButton_Click(Object^ sender, RoutedEventArgs^ e)
00115 {
00116     double centerLatitude = myMap->Center->Position.Latitude;
00117     double centerLongitude = myMap->Center->Position.Longitude;
00118     MapPolyline^ mapPolyline = ref new MapPolyline();
00119
00120     auto list = ref new Vector<BasicGeoposition, GeoEquals>();
00121     list->Append({ centerLatitude - 0.0005, centerLongitude - 0.001 });
00122     list->Append({ centerLatitude + 0.0005, centerLongitude + 0.001 });
00123
00124     mapPolyline->Path = ref new Geopath(list);
00125
00126     mapPolyline->StrokeColor = Windows::UI::Colors::Black;
00127     mapPolyline->StrokeThickness = 3;
00128     mapPolyline->StrokeDashed = true;
00129     myMap->MapElements->Append(mapPolyline);
00130 }
00131
Generated on Fri Nov 15 2024 22:17:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cs/Scenario6_NumeralSystemTranslation.xaml.cs Source File

  • NumberFormatting
  • cs

Scenario6_NumeralSystemTranslation.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Text;
00013 using Windows.Globalization.NumberFormatting;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario6_NumeralSystemTranslation : Page
00020     {
00021         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00022         // as NotifyUser()
00023         MainPage rootPage = MainPage.Current;
00024
00025         public Scenario6_NumeralSystemTranslation()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         /// <summary>
00031         /// This is the click handler for the 'Display' button.
00032         /// </summary>
00033         /// <param name="sender"></param>
00034         /// <param name="e"></param>
00035         private void Display_Click(object sender, RoutedEventArgs e)
00036         {
00037             // Text for which translation of the numeral system will be performed.  Please note that translation only happens between
00038             // Latin and any other supported numeral system.  Translation between numeral systems is not a supported scenario.
00039             String stringToTranslate = "These are the 10 digits of a numeral system: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9";
00040
00041             // Variable where we keep the results of the scenario
00042             StringBuilder results = new StringBuilder();
00043             results.Append("Original string: " + stringToTranslate + "\n\n");
00044
00045             // The numeral system translator is initialized based on the current application language.
00046             NumeralSystemTranslator numeralTranslator = new Windows.Globalization.NumberFormatting.NumeralSystemTranslator();
00047
00048             // Do translation
00049             results.Append("Using application settings (" + numeralTranslator.NumeralSystem + "): ");
00050             results.Append(numeralTranslator.TranslateNumerals(stringToTranslate) + "\n");
00051
00052             // Switch to a different numeral system
00053             numeralTranslator.NumeralSystem = "hanidec";
00054
00055             // Do translation
00056             results.Append("Using numeral system via property (" + numeralTranslator.NumeralSystem + " ): ");
00057             results.Append(numeralTranslator.TranslateNumerals(stringToTranslate) + "\n");
00058
00059             // Create a converter using a language list to initialize the numeral system to an appropriate default
00060             numeralTranslator = new Windows.Globalization.NumberFormatting.NumeralSystemTranslator(new string[] {"ar-SA", "en-US"});
00061
00062             // Do translation
00063             results.Append("Using numeral system via language list (" + numeralTranslator.NumeralSystem + "): ");
00064             results.Append(numeralTranslator.TranslateNumerals(stringToTranslate) + "\n");
00065
00066             // Display the results
00067             OutputTextBlock.Text = results.ToString();
00068         }
00069     }
00070 }
Generated on Fri Nov 15 2024 22:20:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

App Member List

This is the complete list of members for App, including all inherited members.
App() | App | [inline]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnSuspending(object sender, SuspendingEventArgs e) | App | [inline, private]
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LanguageFont/cppwinrt/pch.h Source File

  • LanguageFont
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Globalization.Fonts.h"
00008 #include "winrt/Windows.System.h"
00009 #include "winrt/Windows.UI.Core.h"
00010 #include "winrt/Windows.UI.Xaml.h"
00011 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00012 #include "winrt/Windows.UI.Xaml.Controls.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00014 #include "winrt/Windows.UI.Xaml.Documents.h"
00015 #include "winrt/Windows.UI.Xaml.Interop.h"
00016 #include "winrt/Windows.UI.Xaml.Markup.h"
00017 #include "winrt/Windows.UI.Xaml.Media.h"
00018 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/pch.h Source File

  • FileAccess
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteLineSpacingModes/cpp/DWriteTextLayoutImplementation/pch.cpp Source File

  • DWriteLineSpacingModes
  • cpp
  • DWriteTextLayoutImplementation

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Listener Member List

This is the complete list of members for Listener, including all inherited members.
AddRef() override | Listener |
DownloadCompleted(_In_ IDWriteFontDownloadQueue *downloadQueue, _In_opt_ IUnknown *context, HRESULT downloadResult) | Listener |
m_refCount | Listener | [private]
QueryInterface(REFIID riid, _COM_Outptr_ void **obj) override | Listener |
Release() override | Listener |
Generated on Fri Nov 15 2024 22:23:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaTranscoding/cpp/Scenario1_Default.xaml.h Source File

  • MediaTranscoding
  • cpp

Scenario1_Default.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Default.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario1_Default sealed
00024     {
00025     public:
00026         Scenario1_Default();
00027
00028     protected:
00029         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         void GetPresetProfile(Windows::UI::Xaml::Controls::ComboBox^ comboBox);
00033         void PickFile(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void PickOutput(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         void OnTargetFormatChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00036         void SetPickFileButton(bool isEnabled);
00037         void StopPlayers();
00038         void PlayFile(Windows::Storage::StorageFile^ MediaFile);
00039
00040         void TranscodePreset(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void TranscodeCancel(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void TranscodeProgress(Windows::Foundation::IAsyncActionWithProgress<double>^ asyncInfo, double percent);
00043         void TranscodeError(Platform::String^ error);
00044         void TranscodeFailure(Windows::Media::Transcoding::TranscodeFailureReason reason);
00045         void SetCancelButton(bool isEnabled);
00046         void SetTranscodeButton(bool isEnabled);
00047         void EnableButtons();
00048         void DisableButtons();
00049         void EnableNonSquarePARProfiles();
00050         void DisableNonSquarePARProfiles();
00051
00052         // Media Controls
00053         void InputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00054         void InputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00055         void InputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00056         void OutputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00057         void OutputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00058         void OutputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00059
00060         Platform::String^ _OutputFileName;
00061         Platform::String^ _OutputFileExtension;
00062         Windows::Media::MediaProperties::MediaEncodingProfile^ _Profile;
00063         Windows::Storage::StorageFile^ _InputFile;
00064         Windows::Storage::StorageFile^ _OutputFile;
00065         Windows::Media::Transcoding::MediaTranscoder^ _Transcoder;
00066         Concurrency::cancellation_token_source _CTS;
00067
00068         Platform::String^ _OutputType;
00069
00070         SDKTemplate::MainPage^ rootPage;
00071     };
00072 }
Generated on Fri Nov 15 2024 22:20:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraOpenCV/shared/OpenCVBridge/pch.h Source File

  • CameraOpenCV
  • shared
  • OpenCVBridge

pch.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include <collection.h>
00004 #include <ppltasks.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cppwinrt/ConnectionSettingsPanel.h Source File

  • WiFiDirect
  • cppwinrt

ConnectionSettingsPanel.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "ConnectionSettingsPanel.g.h"
00014
00015 namespace winrt::SDKTemplate::implementation
00016 {
00017     struct ConnectionSettingsPanel : ConnectionSettingsPanelT<ConnectionSettingsPanel>
00018     {
00019         ConnectionSettingsPanel();
00020
00021         void Reset();
00022         Windows::Foundation::IAsyncOperation<bool> RequestPairDeviceAsync(Windows::Devices::Enumeration::DeviceInformationPairing pairing);
00023
00024         void btnAddConfigMethods_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00025
00026     private:
00027         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00028         std::vector<Windows::Devices::WiFiDirect::WiFiDirectConfigurationMethod> supportedConfigMethods;
00029
00030         void OnPairingRequested(Windows::Devices::Enumeration::DeviceInformationCustomPairing const&, Windows::Devices::Enumeration::DevicePairingRequestedEventArgs const& e);
00031     };
00032 }
00033 namespace winrt::SDKTemplate::factory_implementation
00034 {
00035     struct ConnectionSettingsPanel : ConnectionSettingsPanelT<ConnectionSettingsPanel, implementation::ConnectionSettingsPanel>
00036     {
00037     };
00038 }
Generated on Fri Nov 15 2024 22:22:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Tool Member List

This is the complete list of members for Tool, including all inherited members.
GetColor() const | Tool | [inline]
GetDiameter() const | Tool | [inline]
m_color | Tool | [protected]
m_diameter | Tool | [protected]
m_modelConstantBufferData | Tool | [protected]
m_orientation | Tool | [protected]
m_position | Tool | [protected]
m_refreshModelConstantBufferData | Tool | [protected]
Render(ID3D11DeviceContext *pDeviceContext, IRenderer *pRenderingHelper) override | Tool | [virtual]
SetOrientation(Windows::Foundation::Numerics::quaternion orientation) | Tool |
SetPosition(Windows::Foundation::Numerics::float3 position) | Tool |
Tool(Windows::UI::Color color, float diameter) | Tool |
Update(ID3D11DeviceContext *pDeviceContext) override | Tool | [virtual]
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Replace Member List

This is the complete list of members for Scenario3_Replace, including all inherited members.
Replace_Click(object sender, RoutedEventArgs e) | Scenario3_Replace | [inline, private]
rootPage | Scenario3_Replace | [private]
Scenario3_Replace() | Scenario3_Replace | [inline]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cppwinrt/Scenario1_Launched.cpp Source File

  • JumpList
  • cppwinrt

Scenario1_Launched.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_Launched.h"
00014 #include "Scenario1_Launched.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::UI::ViewManagement;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Navigation;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     Scenario1_Launched::Scenario1_Launched()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     void Scenario1_Launched::OnNavigatedTo(NavigationEventArgs const& e)
00030     {
00031         auto argument = unbox_value_or<hstring>(e.Parameter(), hstring());
00032         if (!argument.empty())
00033         {
00034             ActivatedBy().Text(argument);
00035         }
00036         else
00037         {
00038             ActivatedBy().Text(L"manual navigation");
00039         }
00040     }
00041 }
Generated on Fri Nov 15 2024 22:20:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HttpJsonContent Member List

This is the complete list of members for HttpJsonContent, including all inherited members.
BufferAllAsync() | HttpJsonContent | [inline]
Dispose() | HttpJsonContent | [inline]
GetLength() | HttpJsonContent | [inline, private]
headers | HttpJsonContent | [private]
Headers | HttpJsonContent |
HttpJsonContent(IJsonValue jsonValue) | HttpJsonContent | [inline]
jsonValue | HttpJsonContent | [private]
ReadAsBufferAsync() | HttpJsonContent | [inline]
ReadAsInputStreamAsync() | HttpJsonContent | [inline]
ReadAsStringAsync() | HttpJsonContent | [inline]
TryComputeLength(out ulong length) | HttpJsonContent | [inline]
WriteToStreamAsync(IOutputStream outputStream) | HttpJsonContent | [inline]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cppwinrt/pch.h Source File

  • FileThumbnails
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Storage.h"
00008 #include "winrt/Windows.Storage.FileProperties.h"
00009 #include "winrt/Windows.Storage.Pickers.h"
00010 #include "winrt/Windows.Storage.Search.h"
00011 #include "winrt/Windows.System.h"
00012 #include "winrt/Windows.UI.Core.h"
00013 #include "winrt/Windows.UI.Xaml.h"
00014 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00015 #include "winrt/Windows.UI.Xaml.Controls.h"
00016 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00017 #include "winrt/Windows.UI.Xaml.Documents.h"
00018 #include "winrt/Windows.UI.Xaml.Interop.h"
00019 #include "winrt/Windows.UI.Xaml.Markup.h"
00020 #include "winrt/Windows.UI.Xaml.Media.h"
00021 #include "winrt/Windows.UI.Xaml.Media.Imaging.h"
00022 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MobileHotspot/cppwinrt/Scenario2_ToggleMobileHotspot.cpp Source File

  • MobileHotspot
  • cppwinrt

Scenario2_ToggleMobileHotspot.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_ToggleMobileHotspot.h"
00014 #include "Scenario2_ToggleMobileHotspot.g.cpp"
00015 #include "MainPage.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::ApplicationModel::Background;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Networking::Connectivity;
00022 using namespace Windows::Networking::NetworkOperators;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 namespace winrt::SDKTemplate::implementation
00027 {
00028     Scenario2_ToggleMobileHotspot::Scenario2_ToggleMobileHotspot()
00029     {
00030         InitializeComponent();
00031     }
00032
00033     void Scenario2_ToggleMobileHotspot::OnNavigatedTo(NavigationEventArgs const&)
00034     {
00035         MainPage::Current().NotifyUser(L"", NotifyType::StatusMessage);
00036
00037         m_tetheringManager = SDKTemplate::TryGetCurrentNetworkOperatorTetheringManager();
00038
00039         if (m_tetheringManager)
00040         {
00041             NetworkOperatorTetheringAccessPointConfiguration configuration = m_tetheringManager.GetCurrentAccessPointConfiguration();
00042             SsidRun().Text(configuration.Ssid());
00043             PasswordRun().Text(configuration.Passphrase());
00044             BandRun().Text(SDKTemplate::GetFriendlyName(configuration.Band()));
00045
00046             m_toggling = true;
00047             bool isTethered = m_tetheringManager.TetheringOperationalState() == TetheringOperationalState::On;
00048             MobileHotspotToggle().IsOn(isTethered);
00049             m_toggling = false;
00050
00051             HotspotPanel().Visibility(Visibility::Visible);
00052         }
00053     }
00054
00055     fire_and_forget Scenario2_ToggleMobileHotspot::MobileHotspotToggle_Toggled(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00056     {
00057         if (m_toggling)
00058         {
00059             co_return;
00060         }
00061         MainPage::Current().NotifyUser(L"", NotifyType::StatusMessage);
00062
00063         bool isTethered = m_tetheringManager.TetheringOperationalState() == TetheringOperationalState::On;
00064         if (MobileHotspotToggle().IsOn() == isTethered)
00065         {
00066             // Already in desired state.
00067             co_return;
00068         }
00069
00070         // Switch to opposite state.
00071         m_toggling = true;
00072
00073         NetworkOperatorTetheringOperationResult result{ nullptr };
00074         if (isTethered)
00075         {
00076             result = co_await m_tetheringManager.StopTetheringAsync();
00077         }
00078         else
00079         {
00080             result = co_await m_tetheringManager.StartTetheringAsync();
00081         }
00082
00083         if (result.Status() == TetheringOperationStatus::Success)
00084         {
00085             // Change to new state.
00086             MobileHotspotToggle().IsOn(!isTethered);
00087         }
00088         else
00089         {
00090             // Return to old state.
00091             MobileHotspotToggle().IsOn(isTethered);
00092
00093             switch (result.Status())
00094             {
00095             case TetheringOperationStatus::WiFiDeviceOff:
00096                 MainPage::Current().NotifyUser(
00097                     L"Wi-Fi adapter is either turned off or missing.",
00098                     NotifyType::ErrorMessage);
00099                 break;
00100
00101             default:
00102                 MainPage::Current().NotifyUser(
00103                     L"Unhandled result while toggling Mobile Hotspot: " + to_hstring(static_cast<int>(result.Status())), // TODO: stringify
00104                     NotifyType::ErrorMessage);
00105                 break;
00106             }
00107         }
00108         m_toggling = false;
00109     }
00110 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/Common/BasicLoader.cpp Source File

  • Simple3DGameDX
  • cpp
  • Common

BasicLoader.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "BasicLoader.h"
00010 #include "BasicShapes.h"
00011 #include "DDSTextureLoader.h"
00012 #include "DirectXSample.h"
00013 #include <memory>
00014
00015 using namespace Microsoft::WRL;
00016 using namespace Windows::Storage;
00017 using namespace Windows::Storage::Streams;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::ApplicationModel;
00020 using namespace std;
00021 using namespace concurrency;
00022
00023 BasicLoader::BasicLoader(
00024     _In_ ID3D11Device* d3dDevice,
00025     _In_opt_ IWICImagingFactory2* wicFactory
00026     ) :
00027     m_d3dDevice(d3dDevice),
00028     m_wicFactory(wicFactory)
00029 {
00030     // Create a new BasicReaderWriter to do raw file I/O.
00031     m_basicReaderWriter = ref new BasicReaderWriter();
00032 }
00033
00034 template <class DeviceChildType>
00035 inline void BasicLoader::SetDebugName(
00036     _In_ DeviceChildType* object,
00037     _In_ Platform::String^ name
00038     )
00039 {
00040 #if defined(_DEBUG)
00041     // Only assign debug names in debug builds.
00042
00043     char nameString[1024];
00044     int nameStringLength = WideCharToMultiByte(
00045         CP_ACP,
00046         0,
00047         name->Data(),
00048         -1,
00049         nameString,
00050         1024,
00051         nullptr,
00052         nullptr
00053         );
00054
00055     if (nameStringLength == 0)
00056     {
00057         char defaultNameString[] = "BasicLoaderObject";
00058         DX::ThrowIfFailed(
00059             object->SetPrivateData(
00060                 WKPDID_D3DDebugObjectName,
00061                 sizeof(defaultNameString) - 1,
00062                 defaultNameString
00063                 )
00064             );
00065     }
00066     else
00067     {
00068         DX::ThrowIfFailed(
00069             object->SetPrivateData(
00070                 WKPDID_D3DDebugObjectName,
00071                 nameStringLength - 1,
00072                 nameString
00073                 )
00074             );
00075     }
00076 #endif
00077 }
00078
00079 Platform::String^ BasicLoader::GetExtension(
00080     _In_ Platform::String^ filename
00081     )
00082 {
00083     int lastDotIndex = -1;
00084     for (int i = filename->Length() - 1; i >= 0 && lastDotIndex == -1; i--)
00085     {
00086         if (*(filename->Data() + i) == '.')
00087         {
00088             lastDotIndex = i;
00089         }
00090     }
00091     if (lastDotIndex != -1)
00092     {
00093         std::unique_ptr<wchar_t[]> extension(new wchar_t[filename->Length() - lastDotIndex]);
00094         for (unsigned int i = 0; i < filename->Length() - lastDotIndex; i++)
00095         {
00096             extension[i] = tolower(*(filename->Data() + lastDotIndex + 1 + i));
00097         }
00098         return ref new Platform::String(extension.get());
00099     }
00100     return "";
00101 }
00102
00103 void BasicLoader::CreateTexture(
00104     _In_ bool decodeAsDDS,
00105     _In_reads_bytes_(dataSize) byte* data,
00106     _In_ uint32 dataSize,
00107     _Out_opt_ ID3D11Texture2D** texture,
00108     _Out_opt_ ID3D11ShaderResourceView** textureView,
00109     _In_opt_ Platform::String^ debugName
00110     )
00111 {
00112     ComPtr<ID3D11ShaderResourceView> shaderResourceView;
00113     ComPtr<ID3D11Texture2D> texture2D;
00114
00115     if (decodeAsDDS)
00116     {
00117         ComPtr<ID3D11Resource> resource;
00118
00119         if (textureView == nullptr)
00120         {
00121             CreateDDSTextureFromMemory(
00122                 m_d3dDevice.Get(),
00123                 data,
00124                 dataSize,
00125                 &resource,
00126                 nullptr
00127                 );
00128         }
00129         else
00130         {
00131             CreateDDSTextureFromMemory(
00132                 m_d3dDevice.Get(),
00133                 data,
00134                 dataSize,
00135                 &resource,
00136                 &shaderResourceView
00137                 );
00138         }
00139
00140         DX::ThrowIfFailed(
00141             resource.As(&texture2D)
00142             );
00143     }
00144     else
00145     {
00146         if (m_wicFactory.Get() == nullptr)
00147         {
00148             // A WIC factory object is required in order to load texture
00149             // assets stored in non-DDS formats.  If BasicLoader was not
00150             // initialized with one, create one as needed.
00151             DX::ThrowIfFailed(
00152                 CoCreateInstance(
00153                     CLSID_WICImagingFactory,
00154                     nullptr,
00155                     CLSCTX_INPROC_SERVER,
00156                     IID_PPV_ARGS(&m_wicFactory)
00157                     )
00158                 );
00159         }
00160
00161         ComPtr<IWICStream> stream;
00162         DX::ThrowIfFailed(
00163             m_wicFactory->CreateStream(&stream)
00164             );
00165
00166         DX::ThrowIfFailed(
00167             stream->InitializeFromMemory(
00168                 data,
00169                 dataSize
00170                 )
00171             );
00172
00173         ComPtr<IWICBitmapDecoder> bitmapDecoder;
00174         DX::ThrowIfFailed(
00175             m_wicFactory->CreateDecoderFromStream(
00176                 stream.Get(),
00177                 nullptr,
00178                 WICDecodeMetadataCacheOnDemand,
00179                 &bitmapDecoder
00180                 )
00181             );
00182
00183         ComPtr<IWICBitmapFrameDecode> bitmapFrame;
00184         DX::ThrowIfFailed(
00185             bitmapDecoder->GetFrame(0, &bitmapFrame)
00186             );
00187
00188         ComPtr<IWICFormatConverter> formatConverter;
00189         DX::ThrowIfFailed(
00190             m_wicFactory->CreateFormatConverter(&formatConverter)
00191             );
00192
00193         DX::ThrowIfFailed(
00194             formatConverter->Initialize(
00195                 bitmapFrame.Get(),
00196                 GUID_WICPixelFormat32bppPBGRA,
00197                 WICBitmapDitherTypeNone,
00198                 nullptr,
00199                 0.0,
00200                 WICBitmapPaletteTypeCustom
00201                 )
00202             );
00203
00204         uint32 width;
00205         uint32 height;
00206         DX::ThrowIfFailed(
00207             bitmapFrame->GetSize(&width, &height)
00208             );
00209
00210         std::unique_ptr<byte[]> bitmapPixels(new byte[width * height * 4]);
00211         DX::ThrowIfFailed(
00212             formatConverter->CopyPixels(
00213                 nullptr,
00214                 width * 4,
00215                 width * height * 4,
00216                 bitmapPixels.get()
00217                 )
00218             );
00219
00220         D3D11_SUBRESOURCE_DATA initialData;
00221         ZeroMemory(&initialData, sizeof(initialData));
00222         initialData.pSysMem = bitmapPixels.get();
00223         initialData.SysMemPitch = width * 4;
00224         initialData.SysMemSlicePitch = 0;
00225
00226         CD3D11_TEXTURE2D_DESC textureDesc(
00227             DXGI_FORMAT_B8G8R8A8_UNORM,
00228             width,
00229             height,
00230             1,
00231             1
00232             );
00233
00234         DX::ThrowIfFailed(
00235             m_d3dDevice->CreateTexture2D(
00236                 &textureDesc,
00237                 &initialData,
00238                 &texture2D
00239                 )
00240             );
00241
00242         if (textureView != nullptr)
00243         {
00244             CD3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc(
00245                 texture2D.Get(),
00246                 D3D11_SRV_DIMENSION_TEXTURE2D
00247                 );
00248
00249             DX::ThrowIfFailed(
00250                 m_d3dDevice->CreateShaderResourceView(
00251                     texture2D.Get(),
00252                     &shaderResourceViewDesc,
00253                     &shaderResourceView
00254                     )
00255                 );
00256         }
00257     }
00258
00259     SetDebugName(texture2D.Get(), debugName);
00260
00261     if (texture != nullptr)
00262     {
00263         *texture = texture2D.Detach();
00264     }
00265     if (textureView != nullptr)
00266     {
00267         *textureView = shaderResourceView.Detach();
00268     }
00269 }
00270
00271 void BasicLoader::CreateInputLayout(
00272     _In_reads_bytes_(bytecodeSize) byte* bytecode,
00273     _In_ uint32 bytecodeSize,
00274     _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC* layoutDesc,
00275     _In_ uint32 layoutDescNumElements,
00276     _Out_ ID3D11InputLayout** layout
00277     )
00278 {
00279     if (layoutDesc == nullptr)
00280     {
00281         // If no input layout is specified, use the BasicVertex layout.
00282         const D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] =
00283         {
00284             { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,  D3D11_INPUT_PER_VERTEX_DATA, 0 },
00285             { "NORMAL",   0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00286             { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,    0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00287         };
00288
00289         DX::ThrowIfFailed(
00290             m_d3dDevice->CreateInputLayout(
00291                 basicVertexLayoutDesc,
00292                 ARRAYSIZE(basicVertexLayoutDesc),
00293                 bytecode,
00294                 bytecodeSize,
00295                 layout
00296                 )
00297             );
00298     }
00299     else
00300     {
00301         DX::ThrowIfFailed(
00302             m_d3dDevice->CreateInputLayout(
00303                 layoutDesc,
00304                 layoutDescNumElements,
00305                 bytecode,
00306                 bytecodeSize,
00307                 layout
00308                 )
00309             );
00310     }
00311 }
00312
00313 void BasicLoader::CreateMesh(
00314     _In_ byte* meshData,
00315     _Out_ ID3D11Buffer** vertexBuffer,
00316     _Out_ ID3D11Buffer** indexBuffer,
00317     _Out_opt_ uint32* vertexCount,
00318     _Out_opt_ uint32* indexCount,
00319     _In_opt_ Platform::String^ debugName
00320     )
00321 {
00322     // The first 4 bytes of the BasicMesh format define the number of vertices in the mesh.
00323     uint32 numVertices = *reinterpret_cast<uint32*>(meshData);
00324
00325     // The following 4 bytes define the number of indices in the mesh.
00326     uint32 numIndices = *reinterpret_cast<uint32*>(meshData + sizeof(uint32));
00327
00328     // The next segment of the BasicMesh format contains the vertices of the mesh.
00329     BasicVertex* vertices = reinterpret_cast<BasicVertex*>(meshData + sizeof(uint32) * 2);
00330
00331     // The last segment of the BasicMesh format contains the indices of the mesh.
00332     uint16* indices = reinterpret_cast<uint16*>(meshData + sizeof(uint32) * 2 + sizeof(BasicVertex) * numVertices);
00333
00334     // Create the vertex and index buffers with the mesh data.
00335
00336     D3D11_SUBRESOURCE_DATA vertexBufferData = {0};
00337     vertexBufferData.pSysMem = vertices;
00338     vertexBufferData.SysMemPitch = 0;
00339     vertexBufferData.SysMemSlicePitch = 0;
00340     CD3D11_BUFFER_DESC vertexBufferDesc(numVertices * sizeof(BasicVertex), D3D11_BIND_VERTEX_BUFFER);
00341     DX::ThrowIfFailed(
00342         m_d3dDevice->CreateBuffer(
00343             &vertexBufferDesc,
00344             &vertexBufferData,
00345             vertexBuffer
00346             )
00347         );
00348
00349     D3D11_SUBRESOURCE_DATA indexBufferData = {0};
00350     indexBufferData.pSysMem = indices;
00351     indexBufferData.SysMemPitch = 0;
00352     indexBufferData.SysMemSlicePitch = 0;
00353     CD3D11_BUFFER_DESC indexBufferDesc(numIndices * sizeof(uint16), D3D11_BIND_INDEX_BUFFER);
00354     DX::ThrowIfFailed(
00355         m_d3dDevice->CreateBuffer(
00356             &indexBufferDesc,
00357             &indexBufferData,
00358             indexBuffer
00359             )
00360         );
00361
00362     SetDebugName(*vertexBuffer, Platform::String::Concat(debugName, "_VertexBuffer"));
00363     SetDebugName(*indexBuffer, Platform::String::Concat(debugName, "_IndexBuffer"));
00364
00365     if (vertexCount != nullptr)
00366     {
00367         *vertexCount = numVertices;
00368     }
00369     if (indexCount != nullptr)
00370     {
00371         *indexCount = numIndices;
00372     }
00373 }
00374
00375 void BasicLoader::LoadTexture(
00376     _In_ Platform::String^ filename,
00377     _Out_opt_ ID3D11Texture2D** texture,
00378     _Out_opt_ ID3D11ShaderResourceView** textureView
00379     )
00380 {
00381     Platform::Array<byte>^ textureData = m_basicReaderWriter->ReadData(filename);
00382
00383     CreateTexture(
00384         GetExtension(filename) == "dds",
00385         textureData->Data,
00386         textureData->Length,
00387         texture,
00388         textureView,
00389         filename
00390         );
00391 }
00392
00393 task<void> BasicLoader::LoadTextureAsync(
00394     _In_ Platform::String^ filename,
00395     _Out_opt_ ID3D11Texture2D** texture,
00396     _Out_opt_ ID3D11ShaderResourceView** textureView
00397     )
00398 {
00399     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ textureData)
00400     {
00401         CreateTexture(
00402             GetExtension(filename) == "dds",
00403             textureData->Data,
00404             textureData->Length,
00405             texture,
00406             textureView,
00407             filename
00408             );
00409     });
00410 }
00411
00412 void BasicLoader::LoadShader(
00413     _In_ Platform::String^ filename,
00414     _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[],
00415     _In_ uint32 layoutDescNumElements,
00416     _Out_ ID3D11VertexShader** shader,
00417     _Out_opt_ ID3D11InputLayout** layout
00418     )
00419 {
00420     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00421
00422     DX::ThrowIfFailed(
00423         m_d3dDevice->CreateVertexShader(
00424             bytecode->Data,
00425             bytecode->Length,
00426             nullptr,
00427             shader
00428             )
00429         );
00430
00431     SetDebugName(*shader, filename);
00432
00433     if (layout != nullptr)
00434     {
00435         CreateInputLayout(
00436             bytecode->Data,
00437             bytecode->Length,
00438             layoutDesc,
00439             layoutDescNumElements,
00440             layout
00441             );
00442
00443         SetDebugName(*layout, filename);
00444     }
00445 }
00446
00447 task<void> BasicLoader::LoadShaderAsync(
00448     _In_ Platform::String^ filename,
00449     _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[],
00450     _In_ uint32 layoutDescNumElements,
00451     _Out_ ID3D11VertexShader** shader,
00452     _Out_opt_ ID3D11InputLayout** layout
00453     )
00454 {
00455     // This method assumes that the lifetime of input arguments may be shorter
00456     // than the duration of this task.  In order to ensure accurate results, a
00457     // copy of all arguments passed by pointer must be made.  The method then
00458     // ensures that the lifetime of the copied data exceeds that of the task.
00459
00460     // Create copies of the layoutDesc array as well as the SemanticName strings,
00461     // both of which are pointers to data whose lifetimes may be shorter than that
00462     // of this method's task.
00463     shared_ptr<vector<D3D11_INPUT_ELEMENT_DESC>> layoutDescCopy;
00464     shared_ptr<vector<string>> layoutDescSemanticNamesCopy;
00465     if (layoutDesc != nullptr)
00466     {
00467         layoutDescCopy.reset(
00468             new vector<D3D11_INPUT_ELEMENT_DESC>(
00469                 layoutDesc,
00470                 layoutDesc + layoutDescNumElements
00471                 )
00472             );
00473
00474         layoutDescSemanticNamesCopy.reset(
00475             new vector<string>(layoutDescNumElements)
00476             );
00477
00478         for (uint32 i = 0; i < layoutDescNumElements; i++)
00479         {
00480             layoutDescSemanticNamesCopy->at(i).assign(layoutDesc[i].SemanticName);
00481         }
00482     }
00483
00484     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00485     {
00486         DX::ThrowIfFailed(
00487             m_d3dDevice->CreateVertexShader(
00488                 bytecode->Data,
00489                 bytecode->Length,
00490                 nullptr,
00491                 shader
00492                 )
00493             );
00494
00495         SetDebugName(*shader, filename);
00496
00497         if (layout != nullptr)
00498         {
00499             if (layoutDesc != nullptr)
00500             {
00501                 // Reassign the SemanticName elements of the layoutDesc array copy to point
00502                 // to the corresponding copied strings. Performing the assignment inside the
00503                 // lambda body ensures that the lambda will take a reference to the shared_ptr
00504                 // that holds the data.  This will guarantee that the data is still valid when
00505                 // CreateInputLayout is called.
00506                 for (uint32 i = 0; i < layoutDescNumElements; i++)
00507                 {
00508                     layoutDescCopy->at(i).SemanticName = layoutDescSemanticNamesCopy->at(i).c_str();
00509                 }
00510             }
00511
00512             CreateInputLayout(
00513                 bytecode->Data,
00514                 bytecode->Length,
00515                 layoutDesc == nullptr ? nullptr : layoutDescCopy->data(),
00516                 layoutDescNumElements,
00517                 layout
00518                 );
00519
00520             SetDebugName(*layout, filename);
00521         }
00522     });
00523 }
00524
00525 void BasicLoader::LoadShader(
00526     _In_ Platform::String^ filename,
00527     _Out_ ID3D11PixelShader** shader
00528     )
00529 {
00530     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00531
00532     DX::ThrowIfFailed(
00533         m_d3dDevice->CreatePixelShader(
00534             bytecode->Data,
00535             bytecode->Length,
00536             nullptr,
00537             shader
00538             )
00539         );
00540
00541     SetDebugName(*shader, filename);
00542 }
00543
00544 task<void> BasicLoader::LoadShaderAsync(
00545     _In_ Platform::String^ filename,
00546     _Out_ ID3D11PixelShader** shader
00547     )
00548 {
00549     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00550     {
00551         DX::ThrowIfFailed(
00552             m_d3dDevice->CreatePixelShader(
00553                 bytecode->Data,
00554                 bytecode->Length,
00555                 nullptr,
00556                 shader
00557                 )
00558             );
00559
00560         SetDebugName(*shader, filename);
00561     });
00562 }
00563
00564 void BasicLoader::LoadShader(
00565     _In_ Platform::String^ filename,
00566     _Out_ ID3D11ComputeShader** shader
00567     )
00568 {
00569     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00570
00571     DX::ThrowIfFailed(
00572         m_d3dDevice->CreateComputeShader(
00573             bytecode->Data,
00574             bytecode->Length,
00575             nullptr,
00576             shader
00577             )
00578         );
00579
00580     SetDebugName(*shader, filename);
00581 }
00582
00583 task<void> BasicLoader::LoadShaderAsync(
00584     _In_ Platform::String^ filename,
00585     _Out_ ID3D11ComputeShader** shader
00586     )
00587 {
00588     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00589     {
00590         DX::ThrowIfFailed(
00591             m_d3dDevice->CreateComputeShader(
00592                 bytecode->Data,
00593                 bytecode->Length,
00594                 nullptr,
00595                 shader
00596                 )
00597             );
00598
00599         SetDebugName(*shader, filename);
00600     });
00601 }
00602
00603 void BasicLoader::LoadShader(
00604     _In_ Platform::String^ filename,
00605     _Out_ ID3D11GeometryShader** shader
00606     )
00607 {
00608     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00609
00610     DX::ThrowIfFailed(
00611         m_d3dDevice->CreateGeometryShader(
00612             bytecode->Data,
00613             bytecode->Length,
00614             nullptr,
00615             shader
00616             )
00617         );
00618
00619     SetDebugName(*shader, filename);
00620 }
00621
00622 task<void> BasicLoader::LoadShaderAsync(
00623     _In_ Platform::String^ filename,
00624     _Out_ ID3D11GeometryShader** shader
00625     )
00626 {
00627     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00628     {
00629         DX::ThrowIfFailed(
00630             m_d3dDevice->CreateGeometryShader(
00631                 bytecode->Data,
00632                 bytecode->Length,
00633                 nullptr,
00634                 shader
00635                 )
00636             );
00637
00638         SetDebugName(*shader, filename);
00639     });
00640 }
00641
00642 void BasicLoader::LoadShader(
00643     _In_ Platform::String^ filename,
00644     _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration,
00645     _In_ uint32 numEntries,
00646     _In_reads_opt_(numStrides) const uint32* bufferStrides,
00647     _In_ uint32 numStrides,
00648     _In_ uint32 rasterizedStream,
00649     _Out_ ID3D11GeometryShader** shader
00650     )
00651 {
00652     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00653
00654     DX::ThrowIfFailed(
00655         m_d3dDevice->CreateGeometryShaderWithStreamOutput(
00656             bytecode->Data,
00657             bytecode->Length,
00658             streamOutDeclaration,
00659             numEntries,
00660             bufferStrides,
00661             numStrides,
00662             rasterizedStream,
00663             nullptr,
00664             shader
00665             )
00666         );
00667
00668     SetDebugName(*shader, filename);
00669 }
00670
00671 task<void> BasicLoader::LoadShaderAsync(
00672     _In_ Platform::String^ filename,
00673     _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration,
00674     _In_ uint32 numEntries,
00675     _In_reads_opt_(numStrides) const uint32* bufferStrides,
00676     _In_ uint32 numStrides,
00677     _In_ uint32 rasterizedStream,
00678     _Out_ ID3D11GeometryShader** shader
00679     )
00680 {
00681     // This method assumes that the lifetime of input arguments may be shorter
00682     // than the duration of this task.  In order to ensure accurate results, a
00683     // copy of all arguments passed by pointer must be made.  The method then
00684     // ensures that the lifetime of the copied data exceeds that of the task.
00685
00686     // Create copies of the streamOutDeclaration array as well as the SemanticName
00687     // strings, both of which are pointers to data whose lifetimes may be shorter
00688     // than that of this method's task.
00689     shared_ptr<vector<D3D11_SO_DECLARATION_ENTRY>> streamOutDeclarationCopy;
00690     shared_ptr<vector<string>> streamOutDeclarationSemanticNamesCopy;
00691     if (streamOutDeclaration != nullptr)
00692     {
00693         streamOutDeclarationCopy.reset(
00694             new vector<D3D11_SO_DECLARATION_ENTRY>(
00695                 streamOutDeclaration,
00696                 streamOutDeclaration + numEntries
00697                 )
00698             );
00699
00700         streamOutDeclarationSemanticNamesCopy.reset(
00701             new vector<string>(numEntries)
00702             );
00703
00704         for (uint32 i = 0; i < numEntries; i++)
00705         {
00706             streamOutDeclarationSemanticNamesCopy->at(i).assign(streamOutDeclaration[i].SemanticName);
00707         }
00708     }
00709
00710     // Create a copy of the bufferStrides array, which is a pointer to data
00711     // whose lifetime may be shorter than that of this method's task.
00712     shared_ptr<vector<uint32>> bufferStridesCopy;
00713     if (bufferStrides != nullptr)
00714     {
00715         bufferStridesCopy.reset(
00716             new vector<uint32>(
00717                 bufferStrides,
00718                 bufferStrides + numStrides
00719                 )
00720             );
00721     }
00722
00723     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00724     {
00725         if (streamOutDeclaration != nullptr)
00726         {
00727             // Reassign the SemanticName elements of the streamOutDeclaration array copy to
00728             // point to the corresponding copied strings. Performing the assignment inside the
00729             // lambda body ensures that the lambda will take a reference to the shared_ptr
00730             // that holds the data.  This will guarantee that the data is still valid when
00731             // CreateGeometryShaderWithStreamOutput is called.
00732             for (uint32 i = 0; i < numEntries; i++)
00733             {
00734                 streamOutDeclarationCopy->at(i).SemanticName = streamOutDeclarationSemanticNamesCopy->at(i).c_str();
00735             }
00736         }
00737
00738         DX::ThrowIfFailed(
00739             m_d3dDevice->CreateGeometryShaderWithStreamOutput(
00740                 bytecode->Data,
00741                 bytecode->Length,
00742                 streamOutDeclaration == nullptr ? nullptr : streamOutDeclarationCopy->data(),
00743                 numEntries,
00744                 bufferStrides == nullptr ? nullptr : bufferStridesCopy->data(),
00745                 numStrides,
00746                 rasterizedStream,
00747                 nullptr,
00748                 shader
00749                 )
00750             );
00751
00752         SetDebugName(*shader, filename);
00753     });
00754 }
00755
00756 void BasicLoader::LoadShader(
00757     _In_ Platform::String^ filename,
00758     _Out_ ID3D11HullShader** shader
00759     )
00760 {
00761     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00762
00763     DX::ThrowIfFailed(
00764         m_d3dDevice->CreateHullShader(
00765             bytecode->Data,
00766             bytecode->Length,
00767             nullptr,
00768             shader
00769             )
00770         );
00771
00772     SetDebugName(*shader, filename);
00773 }
00774
00775 task<void> BasicLoader::LoadShaderAsync(
00776     _In_ Platform::String^ filename,
00777     _Out_ ID3D11HullShader** shader
00778     )
00779 {
00780     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00781     {
00782         DX::ThrowIfFailed(
00783             m_d3dDevice->CreateHullShader(
00784                 bytecode->Data,
00785                 bytecode->Length,
00786                 nullptr,
00787                 shader
00788                 )
00789             );
00790
00791         SetDebugName(*shader, filename);
00792     });
00793 }
00794
00795 void BasicLoader::LoadShader(
00796     _In_ Platform::String^ filename,
00797     _Out_ ID3D11DomainShader** shader
00798     )
00799 {
00800     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00801
00802     DX::ThrowIfFailed(
00803         m_d3dDevice->CreateDomainShader(
00804             bytecode->Data,
00805             bytecode->Length,
00806             nullptr,
00807             shader
00808             )
00809         );
00810
00811     SetDebugName(*shader, filename);
00812 }
00813
00814 task<void> BasicLoader::LoadShaderAsync(
00815     _In_ Platform::String^ filename,
00816     _Out_ ID3D11DomainShader** shader
00817     )
00818 {
00819     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00820     {
00821         DX::ThrowIfFailed(
00822             m_d3dDevice->CreateDomainShader(
00823                 bytecode->Data,
00824                 bytecode->Length,
00825                 nullptr,
00826                 shader
00827                 )
00828             );
00829
00830         SetDebugName(*shader, filename);
00831     });
00832 }
00833
00834 void BasicLoader::LoadMesh(
00835     _In_ Platform::String^ filename,
00836     _Out_ ID3D11Buffer** vertexBuffer,
00837     _Out_ ID3D11Buffer** indexBuffer,
00838     _Out_opt_ uint32* vertexCount,
00839     _Out_opt_ uint32* indexCount
00840     )
00841 {
00842     Platform::Array<byte>^ meshData = m_basicReaderWriter->ReadData(filename);
00843
00844     CreateMesh(
00845         meshData->Data,
00846         vertexBuffer,
00847         indexBuffer,
00848         vertexCount,
00849         indexCount,
00850         filename
00851         );
00852 }
00853
00854 task<void> BasicLoader::LoadMeshAsync(
00855     _In_ Platform::String^ filename,
00856     _Out_ ID3D11Buffer** vertexBuffer,
00857     _Out_ ID3D11Buffer** indexBuffer,
00858     _Out_opt_ uint32* vertexCount,
00859     _Out_opt_ uint32* indexCount
00860     )
00861 {
00862     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ meshData)
00863     {
00864         CreateMesh(
00865             meshData->Data,
00866             vertexBuffer,
00867             indexBuffer,
00868             vertexCount,
00869             indexCount,
00870             filename
00871             );
00872     });
00873 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Util Member List

This is the complete list of members for Util, including all inherited members.
NTE_NO_KEY | Util | [private]
NTE_PERM | Util | [private]
TryDeleteCredentialAccountAsync(string userId) | Util | [inline, static]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_ConnectDisconnect Member List

This is the complete list of members for Scenario1_ConnectDisconnect, including all inherited members.
AddDeviceToList(DeviceInformation deviceInformation, String deviceSelector) | Scenario1_ConnectDisconnect | [inline, private]
AddDeviceWatcher(DeviceWatcher deviceWatcher, String deviceSelector) | Scenario1_ConnectDisconnect | [inline, private]
appResumeEventHandler | Scenario1_ConnectDisconnect | [private]
appSuspendEventHandler | Scenario1_ConnectDisconnect | [private]
ButtonNameDisableReconnectToDevice | Scenario1_ConnectDisconnect | [private]
ButtonNameDisconnectFromDevice | Scenario1_ConnectDisconnect | [private]
ClearDeviceEntries() | Scenario1_ConnectDisconnect | [inline, private]
ConnectToDevice_Click(Object sender, RoutedEventArgs eventArgs) | Scenario1_ConnectDisconnect | [inline, private]
DisconnectFromDevice_Click(Object sender, RoutedEventArgs eventArgs) | Scenario1_ConnectDisconnect | [inline, private]
FindDevice(String deviceId) | Scenario1_ConnectDisconnect | [inline, private]
InitializeDeviceWatchers() | Scenario1_ConnectDisconnect | [inline, private]
isAllDevicesEnumerated | Scenario1_ConnectDisconnect | [private]
listOfDevices | Scenario1_ConnectDisconnect | [private]
mapDeviceWatchersToDeviceSelector | Scenario1_ConnectDisconnect | [private]
OnAppResume(Object sender, Object args) | Scenario1_ConnectDisconnect | [inline, private]
OnAppSuspension(Object sender, SuspendingEventArgs args) | Scenario1_ConnectDisconnect | [inline, private]
OnDeviceAdded(DeviceWatcher sender, DeviceInformation deviceInformation) | Scenario1_ConnectDisconnect | [inline, private]
OnDeviceClosing(EventHandlerForDevice sender, DeviceInformation deviceInformation) | Scenario1_ConnectDisconnect | [inline, private]
OnDeviceConnected(EventHandlerForDevice sender, DeviceInformation deviceInformation) | Scenario1_ConnectDisconnect | [inline, private]
OnDeviceEnumerationComplete(DeviceWatcher sender, Object args) | Scenario1_ConnectDisconnect | [inline, private]
OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceInformationUpdate) | Scenario1_ConnectDisconnect | [inline, private]
OnNavigatedFrom(NavigationEventArgs eventArgs) | Scenario1_ConnectDisconnect | [inline, protected]
OnNavigatedTo(NavigationEventArgs eventArgs) | Scenario1_ConnectDisconnect | [inline, protected]
RemoveDeviceFromList(String deviceId) | Scenario1_ConnectDisconnect | [inline, private]
rootPage | Scenario1_ConnectDisconnect | [private]
Scenario1_ConnectDisconnect() | Scenario1_ConnectDisconnect | [inline]
SelectDeviceInList(String deviceIdToSelect) | Scenario1_ConnectDisconnect | [inline, private]
StartDeviceWatchers() | Scenario1_ConnectDisconnect | [inline, private]
StartHandlingAppEvents() | Scenario1_ConnectDisconnect | [inline, private]
StopDeviceWatchers() | Scenario1_ConnectDisconnect | [inline, private]
StopHandlingAppEvents() | Scenario1_ConnectDisconnect | [inline, private]
UpdateConnectDisconnectButtonsAndList(Boolean enableConnectButton) | Scenario1_ConnectDisconnect | [inline, private]
watchersStarted | Scenario1_ConnectDisconnect | [private]
watchersSuspended | Scenario1_ConnectDisconnect | [private]
Generated on Fri Nov 15 2024 22:24:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ColorBGRA Member List

This is the complete list of members for ColorBGRA, including all inherited members.
A | ColorBGRA
B | ColorBGRA
G | ColorBGRA
R | ColorBGRA
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialStage/cpp/HolographicSpatialStageMain.cpp Source File

  • HolographicSpatialStage
  • cpp

HolographicSpatialStageMain.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "HolographicSpatialStageMain.h"
00003 #include "Common\DirectXHelper.h"
00004
00005 #include <windows.graphics.directx.direct3d11.interop.h>
00006 #include <Collection.h>
00007
00008
00009 using namespace HolographicSpatialStage;
00010
00011 using namespace concurrency;
00012 using namespace Platform;
00013 using namespace Microsoft::WRL;
00014 using namespace Windows::Graphics::DirectX::Direct3D11;
00015 using namespace Windows::Foundation;
00016 using namespace Windows::Foundation::Numerics;
00017 using namespace Windows::Gaming::Input;
00018 using namespace Windows::Graphics::Holographic;
00019 using namespace Windows::Perception::Spatial;
00020 using namespace Windows::UI::Input::Spatial;
00021 using namespace std::placeholders;
00022
00023 // Loads and initializes application assets when the application is loaded.
00024 HolographicSpatialStageMain::HolographicSpatialStageMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00025     m_deviceResources(deviceResources)
00026 {
00027     // Register to be notified if the device is lost or recreated.
00028     m_deviceResources->RegisterDeviceNotify(this);
00029 }
00030
00031 void HolographicSpatialStageMain::SetHolographicSpace(HolographicSpace^ holographicSpace)
00032 {
00033     UnregisterHolographicEventHandlers();
00034
00035     m_holographicSpace = holographicSpace;
00036
00037     // Initialize the sample.
00038     m_sceneController = std::make_shared<SceneController>(m_deviceResources);
00039
00040     // Set up spatial stage.
00041     m_spatialStageManager = std::make_shared<SpatialStageManager>(m_deviceResources, m_sceneController);
00042
00043     // Use the default SpatialLocator to track the motion of the device.
00044     auto locator = SpatialLocator::GetDefault();
00045
00046     // Be able to respond to changes in the positional tracking state.
00047     if (locator != nullptr)
00048     {
00049         m_locatabilityChangedToken =
00050             locator->LocatabilityChanged +=
00051             ref new Windows::Foundation::TypedEventHandler<SpatialLocator^, Object^>(
00052                 std::bind(&HolographicSpatialStageMain::OnLocatabilityChanged, this, _1, _2)
00053                 );
00054     }
00055
00056     // Respond to camera added events by creating any resources that are specific
00057     // to that camera, such as the back buffer render target view.
00058     // When we add an event handler for CameraAdded, the API layer will avoid putting
00059     // the new camera in new HolographicFrames until we complete the deferral we created
00060     // for that handler, or return from the handler without creating a deferral. This
00061     // allows the app to take more than one frame to finish creating resources and
00062     // loading assets for the new holographic camera.
00063     // This function should be registered before the app creates any HolographicFrames.
00064     m_cameraAddedToken =
00065         m_holographicSpace->CameraAdded +=
00066             ref new Windows::Foundation::TypedEventHandler<HolographicSpace^, HolographicSpaceCameraAddedEventArgs^>(
00067                 std::bind(&HolographicSpatialStageMain::OnCameraAdded, this, _1, _2)
00068                 );
00069
00070     // Respond to camera removed events by releasing resources that were created for that
00071     // camera.
00072     // When the app receives a CameraRemoved event, it releases all references to the back
00073     // buffer right away. This includes render target views, Direct2D target bitmaps, and so on.
00074     // The app must also ensure that the back buffer is not attached as a render target, as
00075     // shown in DeviceResources::ReleaseResourcesForBackBuffer.
00076     m_cameraRemovedToken =
00077         m_holographicSpace->CameraRemoved +=
00078             ref new Windows::Foundation::TypedEventHandler<HolographicSpace^, HolographicSpaceCameraRemovedEventArgs^>(
00079                 std::bind(&HolographicSpatialStageMain::OnCameraRemoved, this, _1, _2)
00080                 );
00081 }
00082
00083 void HolographicSpatialStageMain::UnregisterHolographicEventHandlers()
00084 {
00085     if (m_holographicSpace != nullptr)
00086     {
00087         // Clear previous event registrations.
00088
00089         if (m_cameraAddedToken.Value != 0)
00090         {
00091             m_holographicSpace->CameraAdded -= m_cameraAddedToken;
00092             m_cameraAddedToken.Value = 0;
00093         }
00094
00095         if (m_cameraRemovedToken.Value != 0)
00096         {
00097             m_holographicSpace->CameraRemoved -= m_cameraRemovedToken;
00098             m_cameraRemovedToken.Value = 0;
00099         }
00100     }
00101
00102     auto locator = SpatialLocator::GetDefault();
00103     if (locator != nullptr)
00104     {
00105         locator->LocatabilityChanged -= m_locatabilityChangedToken;
00106     }
00107 }
00108
00109 HolographicSpatialStageMain::~HolographicSpatialStageMain()
00110 {
00111     // Deregister device notification.
00112     m_deviceResources->RegisterDeviceNotify(nullptr);
00113
00114     UnregisterHolographicEventHandlers();
00115 }
00116
00117 // Updates the application state once per frame.
00118 HolographicFrame^ HolographicSpatialStageMain::Update()
00119 {
00120     // Before doing the timer update, there is some work to do per-frame
00121     // to maintain holographic rendering. First, we will get information
00122     // about the current frame.
00123
00124     // The HolographicFrame has information that the app needs in order
00125     // to update and render the current frame. The app begins each new
00126     // frame by calling CreateNextFrame.
00127     HolographicFrame^ holographicFrame = m_holographicSpace->CreateNextFrame();
00128
00129     // Get a prediction of where holographic cameras will be when this frame
00130     // is presented.
00131     HolographicFramePrediction^ prediction = holographicFrame->CurrentPrediction;
00132
00133     // Back buffers can change from frame to frame. Validate each buffer, and recreate
00134     // resource views and depth buffers as needed.
00135     m_deviceResources->EnsureCameraResources(holographicFrame, prediction);
00136
00137     // Next, we get a coordinate system from the attached frame of reference that is
00138     // associated with the current frame. Later, this coordinate system is used for
00139     // for creating the stereo view matrices when rendering the sample content.
00140     SpatialCoordinateSystem^ currentCoordinateSystem = m_spatialStageManager->GetCoordinateSystemForCurrentStage();
00141
00142     m_timer.Tick([&]()
00143     {
00144         m_sceneController->Update(m_timer, currentCoordinateSystem);
00145     });
00146
00147     // The holographic frame will be used to get up-to-date view and projection matrices and
00148     // to present the swap chain.
00149     return holographicFrame;
00150 }
00151
00152 // Renders the current frame to each holographic camera, according to the
00153 // current application and spatial positioning state. Returns true if the
00154 // frame was rendered to at least one camera.
00155 bool HolographicSpatialStageMain::Render(Windows::Graphics::Holographic::HolographicFrame^ holographicFrame)
00156 {
00157     // Don't try to render anything before the first Update.
00158     if (m_timer.GetFrameCount() == 0)
00159     {
00160         return false;
00161     }
00162
00163     // Lock the set of holographic camera resources, then draw to each camera
00164     // in this frame.
00165     return m_deviceResources->UseHolographicCameraResources<bool>(
00166         [this, holographicFrame](std::map<UINT32, std::unique_ptr<DX::CameraResources>>& cameraResourceMap)
00167     {
00168         // Up-to-date frame predictions enhance the effectiveness of image stablization and
00169         // allow more accurate positioning of holograms.
00170         holographicFrame->UpdateCurrentPrediction();
00171         HolographicFramePrediction^ prediction = holographicFrame->CurrentPrediction;
00172
00173         bool atLeastOneCameraRendered = false;
00174         for (auto cameraPose : prediction->CameraPoses)
00175         {
00176             // This represents the device-based resources for a HolographicCamera.
00177             DX::CameraResources* pCameraResources = cameraResourceMap[cameraPose->HolographicCamera->Id].get();
00178
00179             // Get the device context.
00180             const auto context = m_deviceResources->GetD3DDeviceContext();
00181             const auto depthStencilView = pCameraResources->GetDepthStencilView();
00182
00183             // Set render targets to the current holographic camera.
00184             ID3D11RenderTargetView *const targets[1] = { pCameraResources->GetBackBufferRenderTargetView() };
00185             context->OMSetRenderTargets(1, targets, depthStencilView);
00186
00187             // Clear the back buffer and depth stencil view.
00188             context->ClearRenderTargetView(targets[0], DirectX::Colors::Transparent);
00189             context->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
00190
00191             // The view and projection matrices for each holographic camera will change
00192             // every frame. This function refreshes the data in the constant buffer for
00193             // the holographic camera indicated by cameraPose.
00194             SpatialCoordinateSystem^ currentCoordinateSystem = m_spatialStageManager->GetCoordinateSystemForCurrentStage();
00195             if (currentCoordinateSystem != nullptr)
00196             {
00197                 pCameraResources->UpdateViewProjectionBuffer(m_deviceResources, cameraPose, currentCoordinateSystem);
00198             }
00199
00200             // Attach the view/projection constant buffer for this camera to the graphics pipeline.
00201             bool cameraActive = pCameraResources->AttachViewProjectionBuffer(m_deviceResources);
00202
00203             // Only render world-locked content when positional tracking is active.
00204             if (cameraActive)
00205             {
00206                 // Draw the sample hologram.
00207                 m_sceneController->Render();
00208
00209                 // We complete the frame by using the depth buffer to optimize image stabilization.
00210                 ComPtr<ID3D11Texture2D> depthBuffer = cameraResourceMap.at(cameraPose->HolographicCamera->Id)->GetDepthBufferTexture2D();
00211
00212                 // The depth buffer might be stereo, so we take the first subresource.
00213                 // This should also work for mono cameras.
00214                 ComPtr<IDXGIResource1> depthStencilResource;
00215                 HRESULT hr = depthBuffer.As(&depthStencilResource);
00216                 ComPtr<IDXGISurface2> depthDxgiSurface;
00217                 if (SUCCEEDED(hr))
00218                 {
00219                     hr = depthStencilResource->CreateSubresourceSurface(0, &depthDxgiSurface);
00220                 }
00221
00222                 if (SUCCEEDED(hr))
00223                 {
00224                     IDirect3DSurface^ depthD3DSurface = CreateDirect3DSurface(depthDxgiSurface.Get());
00225                     auto renderingParameters = holographicFrame->GetRenderingParameters(cameraPose);
00226                     try
00227                     {
00228                         // Provide the depth buffer.
00229                         renderingParameters->CommitDirect3D11DepthBuffer(depthD3DSurface);
00230                     }
00231                     catch (Platform::InvalidArgumentException^ ex)
00232                     {
00233                         OutputDebugStringA("Unsupported depth buffer format, invalid properties, or incorrect D3D device.\n");
00234                     }
00235                 }
00236
00237                 atLeastOneCameraRendered = true;
00238             }
00239         }
00240
00241         return atLeastOneCameraRendered;
00242     });
00243 }
00244
00245 // Notifies classes that use Direct3D device resources that the device resources
00246 // need to be released before this method returns.
00247 void HolographicSpatialStageMain::OnDeviceLost()
00248 {
00249     m_sceneController->ReleaseDeviceDependentResources();
00250 }
00251
00252 // Notifies classes that use Direct3D device resources that the device resources
00253 // may now be recreated.
00254 void HolographicSpatialStageMain::OnDeviceRestored()
00255 {
00256     m_sceneController->CreateDeviceDependentResources();
00257 }
00258
00259 void HolographicSpatialStageMain::OnLocatabilityChanged(SpatialLocator^ sender, Object^ args)
00260 {
00261     switch (sender->Locatability)
00262     {
00263     case SpatialLocatability::Unavailable:
00264         // Holograms cannot be rendered.
00265         {
00266             String^ message = L"Warning! Positional tracking is " +
00267                                         sender->Locatability.ToString() + L".\n";
00268             OutputDebugStringW(message->Data());
00269         }
00270         break;
00271
00272     // In the following three cases, it is still possible to place holograms using a
00273     // SpatialLocatorAttachedFrameOfReference.
00274     case SpatialLocatability::PositionalTrackingActivating:
00275         // The system is preparing to use positional tracking.
00276
00277     case SpatialLocatability::OrientationOnly:
00278         // Positional tracking has not been activated.
00279
00280     case SpatialLocatability::PositionalTrackingInhibited:
00281         // Positional tracking is temporarily inhibited. User action may be required
00282         // in order to restore positional tracking.
00283         break;
00284
00285     case SpatialLocatability::PositionalTrackingActive:
00286         // Positional tracking is active. World-locked content can be rendered.
00287         break;
00288     }
00289 }
00290
00291 void HolographicSpatialStageMain::OnCameraAdded(
00292     HolographicSpace^ sender,
00293     HolographicSpaceCameraAddedEventArgs^ args
00294     )
00295 {
00296     Deferral^ deferral = args->GetDeferral();
00297     HolographicCamera^ holographicCamera = args->Camera;
00298     create_task([this, deferral, holographicCamera] ()
00299     {
00300         // Create device-based resources for the holographic camera and add it to the list of
00301         // cameras used for updates and rendering. Notes:
00302         //   * Since this function may be called at any time, the AddHolographicCamera function
00303         //     waits until it can get a lock on the set of holographic camera resources before
00304         //     adding the new camera. At 60 frames per second this wait should not take long.
00305         //   * A subsequent Update will take the back buffer from the RenderingParameters of this
00306         //     camera's CameraPose and use it to create the ID3D11RenderTargetView for this camera.
00307         //     Content can then be rendered for the HolographicCamera.
00308         m_deviceResources->AddHolographicCamera(holographicCamera);
00309
00310         // Holographic frame predictions will not include any information about this camera until
00311         // the deferral is completed.
00312         deferral->Complete();
00313     });
00314 }
00315
00316 void HolographicSpatialStageMain::OnCameraRemoved(
00317     HolographicSpace^ sender,
00318     HolographicSpaceCameraRemovedEventArgs^ args
00319     )
00320 {
00321     // Before letting this callback return, ensure that all references to the back buffer
00322     // are released.
00323     // Since this function may be called at any time, the RemoveHolographicCamera function
00324     // waits until it can get a lock on the set of holographic camera resources before
00325     // deallocating resources for this camera. At 60 frames per second this wait should
00326     // not take long.
00327     m_deviceResources->RemoveHolographicCamera(args->Camera);
00328 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

S1_AddWithAPI Member List

This is the complete list of members for S1_AddWithAPI, including all inherited members.
AddToIndex_Click(object sender, RoutedEventArgs e) | S1_AddWithAPI | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | S1_AddWithAPI | [inline, protected]
rootPage | S1_AddWithAPI | [private]
S1_AddWithAPI() | S1_AddWithAPI | [inline]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CSetRateOperation Member List

This is the complete list of members for CSetRateOperation, including all inherited members.
_flRate | CSetRateOperation | [private]
_fThin | CSetRateOperation | [private]
CSetRateOperation(BOOL fThin, float flRate) | CSetRateOperation |
CSourceOperation(Type opType) | CSourceOperation |
GetData() const | CSourceOperation | [inline]
GetOperationType() const | CSourceOperation | [inline]
GetRate() const | CSetRateOperation | [inline]
IFACEMETHOD_(ULONG, AddRef)() | CSourceOperation |
IFACEMETHOD_(ULONG, Release)() | CSourceOperation |
IsThin() const | CSetRateOperation | [inline]
Operation_SetRate enum value | CSourceOperation |
Operation_Start enum value | CSourceOperation |
Operation_Stop enum value | CSourceOperation |
QueryInterface(REFIID riid, void **ppv) | CSourceOperation |
SetData(const PROPVARIANT &varData) | CSourceOperation |
Type enum name | CSourceOperation |
~CSetRateOperation() | CSetRateOperation |
~CSourceOperation() | CSourceOperation | [virtual]
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cpp/Scenario3_Add.xaml.h Source File

  • Playlists
  • cpp

Scenario3_Add.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario3_Add.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario3_Add sealed
00012     {
00013     public:
00014         Scenario3_Add();
00015     private:
00016         MainPage^ rootPage;
00017         Windows::Media::Playlists::Playlist^ playlist;
00018         void PickPlaylistButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00019         void PickAudioButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00020     };
00021 }
Generated on Fri Nov 15 2024 22:20:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

EventHandlerForDevice Member List

This is the complete list of members for EventHandlerForDevice, including all inherited members.
appResumeEventHandler | EventHandlerForDevice | [private]
appSuspendEventHandler | EventHandlerForDevice | [private]
CloseCurrentlyConnectedDevice() | EventHandlerForDevice | [inline, private]
CloseDevice() | EventHandlerForDevice | [inline]
CreateNewEventHandlerForDevice() | EventHandlerForDevice | [inline, static]
Current | EventHandlerForDevice | [static]
device | EventHandlerForDevice | [private]
Device | EventHandlerForDevice |
deviceAccessEventHandler | EventHandlerForDevice | [private]
DeviceAccessInformation | EventHandlerForDevice |
deviceAccessInformation | EventHandlerForDevice | [private]
deviceAddedEventHandler | EventHandlerForDevice | [private]
deviceCloseCallback | EventHandlerForDevice | [private]
deviceConnectedCallback | EventHandlerForDevice | [private]
DeviceInformation | EventHandlerForDevice |
deviceInformation | EventHandlerForDevice | [private]
deviceRemovedEventHandler | EventHandlerForDevice | [private]
deviceSelector | EventHandlerForDevice | [private]
DeviceSelector | EventHandlerForDevice |
deviceWatcher | EventHandlerForDevice | [private]
eventHandlerForDevice | EventHandlerForDevice | [private, static]
EventHandlerForDevice() | EventHandlerForDevice | [inline, private]
IsDeviceConnected | EventHandlerForDevice |
isEnabledAutoReconnect | EventHandlerForDevice | [private]
IsEnabledAutoReconnect | EventHandlerForDevice |
OnAppResume(Object sender, Object args) | EventHandlerForDevice | [inline, private]
OnAppSuspension(Object sender, SuspendingEventArgs args) | EventHandlerForDevice | [inline, private]
OnDeviceAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs eventArgs) | EventHandlerForDevice | [inline, private]
OnDeviceAdded(DeviceWatcher sender, DeviceInformation deviceInfo) | EventHandlerForDevice | [inline, private]
OnDeviceClose | EventHandlerForDevice |
OnDeviceConnected | EventHandlerForDevice |
OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceInformationUpdate) | EventHandlerForDevice | [inline, private]
OpenDeviceAsync(DeviceInformation deviceInfo, String deviceSelector) | EventHandlerForDevice | [inline]
RegisterForAppEvents() | EventHandlerForDevice | [inline, private]
RegisterForDeviceAccessStatusChange() | EventHandlerForDevice | [inline, private]
RegisterForDeviceWatcherEvents() | EventHandlerForDevice | [inline, private]
rootPage | EventHandlerForDevice | [private]
singletonCreationLock | EventHandlerForDevice | [private, static]
StartDeviceWatcher() | EventHandlerForDevice | [inline, private]
StopDeviceWatcher() | EventHandlerForDevice | [inline, private]
UnregisterFromAppEvents() | EventHandlerForDevice | [inline, private]
UnregisterFromDeviceAccessStatusChange() | EventHandlerForDevice | [inline, private]
UnregisterFromDeviceWatcherEvents() | EventHandlerForDevice | [inline, private]
watcherStarted | EventHandlerForDevice | [private]
watcherSuspended | EventHandlerForDevice | [private]
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DGradientMesh/cpp/pch.cpp Source File

  • D2DGradientMesh
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cppwinrt/SampleConfiguration.cpp Source File

  • Calendar
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"Calendar C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027     {
00028         Scenario{ L"Display a calendar", xaml_typename<SDKTemplate::Scenario1_Data>() },
00029         Scenario{ L"Retrieve calendar statistics", xaml_typename<SDKTemplate::Scenario2_Stats>() },
00030         Scenario{ L"Calendar enumeration and math", xaml_typename<SDKTemplate::Scenario3_Enum>() },
00031         Scenario{ L"Calendar with Unicode extensions in languages", xaml_typename<SDKTemplate::Scenario4_UnicodeExtensions>() },
00032         Scenario{ L"Calendar time zone support", xaml_typename<SDKTemplate::Scenario5_TimeZone>() },
00033     });
Generated on Fri Nov 15 2024 22:17:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlMasterDetail/cppwinrt/MasterDetailPage.cpp Source File

  • XamlMasterDetail
  • cppwinrt

MasterDetailPage.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MasterDetailPage.h"
00014 #include "MasterDetailPage.g.cpp"
00015 #include "ItemsDataSource.h"
00016 #include <algorithm>
00017
00018 using namespace winrt;
00019 using namespace MasterDetailApp::Data;
00020 using namespace MasterDetailApp::ViewModels;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Media::Animation;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 namespace winrt::MasterDetailApp::implementation
00029 {
00030     MasterDetailPage::MasterDetailPage()
00031     {
00032         InitializeComponent();
00033         m_items = single_threaded_observable_vector<ItemViewModel>();
00034         for (auto&& item : ItemsDataSource::GetAllItems())
00035         {
00036             m_items.Append(ItemViewModel::FromItem(item));
00037         }
00038         MasterListView().ItemsSource(m_items);
00039     }
00040
00041     void MasterDetailPage::OnNavigatedTo(NavigationEventArgs const& e)
00042     {
00043         m_lastSelectedItem = nullptr;
00044         if (e.Parameter())
00045         {
00046             // Parameter is item ID
00047             auto id = unbox_value<int>(e.Parameter());
00048
00049             for (auto&& item : m_items)
00050             {
00051                 if (item.ItemId() == id)
00052                 {
00053                     m_lastSelectedItem = item;
00054                     break;
00055                 }
00056             }
00057         }
00058
00059         UpdateForVisualState(AdaptiveStates().CurrentState());
00060
00061         // Don't play a content transition for first item load.
00062         // Sometimes, this content will be animated as part of the page transition.
00063         DisableContentTransitions();
00064     }
00065
00066     void MasterDetailPage::AdaptiveStates_CurrentStateChanged(IInspectable const&, VisualStateChangedEventArgs const& e)
00067     {
00068         UpdateForVisualState(e.NewState(), e.OldState());
00069     }
00070
00071     void MasterDetailPage::UpdateForVisualState(VisualState const& newState, VisualState const& oldState)
00072     {
00073         auto isNarrow = newState == NarrowState();
00074
00075         if (isNarrow && oldState == DefaultState() && m_lastSelectedItem != nullptr)
00076         {
00077             // Resize down to the detail item. Don't play a transition.
00078             Frame().Navigate(xaml_typename<DetailPage>(), box_value(m_lastSelectedItem.ItemId()), SuppressNavigationTransitionInfo());
00079         }
00080
00081         EntranceNavigationTransitionInfo::SetIsTargetElement(MasterListView(), isNarrow);
00082         if (DetailContentPresenter() != nullptr)
00083         {
00084             EntranceNavigationTransitionInfo::SetIsTargetElement(DetailContentPresenter(), !isNarrow);
00085         }
00086     }
00087
00088     void MasterDetailPage::EnableContentTransitions()
00089     {
00090         DetailContentPresenter().ContentTransitions().ReplaceAll({ EntranceThemeTransition() });
00091     }
00092
00093     void MasterDetailPage::DisableContentTransitions()
00094     {
00095         if (DetailContentPresenter() != nullptr)
00096         {
00097             DetailContentPresenter().ContentTransitions().Clear();
00098         }
00099     }
00100
00101     void MasterDetailPage::LayoutRoot_Loaded(IInspectable const&, RoutedEventArgs const&)
00102     {
00103         // Assure we are displaying the correct item. This is necessary in certain adaptive cases.
00104         MasterListView().SelectedItem(m_lastSelectedItem);
00105     }
00106
00107     void MasterDetailPage::MasterListView_ItemClick(IInspectable const&, ItemClickEventArgs const& e)
00108     {
00109         auto clickedItem = e.ClickedItem().as<ItemViewModel>();
00110         m_lastSelectedItem = clickedItem;
00111
00112         if (AdaptiveStates().CurrentState() == NarrowState())
00113         {
00114             // Use "drill in" transition for navigating from master list to detail view
00115             Frame().Navigate(xaml_typename<DetailPage>(), box_value(clickedItem.ItemId()), DrillInNavigationTransitionInfo());
00116         }
00117         else
00118         {
00119             // Play a refresh animation when the user switches detail items.
00120             EnableContentTransitions();
00121         }
00122     }
00123 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_UIFonts Member List

This is the complete list of members for Scenario1_UIFonts, including all inherited members.
ApplyFonts_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_UIFonts
Scenario1_UIFonts() | Scenario1_UIFonts
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cppwinrt/Scenario5_RoundingAndPadding.cpp Source File

  • NumberFormatting
  • cppwinrt

Scenario5_RoundingAndPadding.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario5_RoundingAndPadding.h"
00014 #include "Scenario5_RoundingAndPadding.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Globalization::NumberFormatting;
00019 using namespace Windows::UI::Xaml;
00020
00021 namespace
00022 {
00023     // Used to display the rounding algorithm in a string format.  Used by the different scenarios when
00024     // displaying results for the scenario
00025     std::wstring DisplayRoundingAlgorithmAsString(RoundingAlgorithm roundingAlgorithm)
00026     {
00027         // Convert the enumeration value into a string representation
00028         switch (roundingAlgorithm) {
00029         case RoundingAlgorithm::None:
00030             return L"no";
00031             break;
00032         case RoundingAlgorithm::RoundAwayFromZero:
00033             return L"away from zero";
00034             break;
00035         case RoundingAlgorithm::RoundDown:
00036             return L"down";
00037             break;
00038         case RoundingAlgorithm::RoundHalfAwayFromZero:
00039             return L"half away from zero";
00040             break;
00041         case RoundingAlgorithm::RoundHalfDown:
00042             return L"half down";
00043             break;
00044         case RoundingAlgorithm::RoundHalfToEven:
00045             return L"half to even";
00046             break;
00047         case RoundingAlgorithm::RoundHalfToOdd:
00048             return L"half to odd";
00049             break;
00050         case RoundingAlgorithm::RoundHalfTowardsZero:
00051             return L"half towards zero";
00052             break;
00053         case RoundingAlgorithm::RoundHalfUp:
00054             return L"half up";
00055             break;
00056         case RoundingAlgorithm::RoundTowardsZero:
00057             return L"toward zero";
00058             break;
00059         case RoundingAlgorithm::RoundUp:
00060             return L"up";
00061             break;
00062         default:
00063             return L"unknown";
00064             break;
00065         }
00066     }
00067
00068     // Executes the padding scenarios.
00069     /// The formatter parameter can be either a DecimalFormatter, PercentFormatter
00070     /// PerMilleFormatter or CurrencyFormatter
00071     void DoPaddingScenarios(std::wostream& results, INumberFormatter const& formatter)
00072     {
00073         // Display the properties of the scenario
00074         results << L"Padding with ";
00075         results << formatter.as<ISignificantDigitsOption>().SignificantDigits() << L" significant digits, ";
00076         results << formatter.as<INumberFormatterOptions>().IntegerDigits() << L" integer digits, ";
00077         results << formatter.as<INumberFormatterOptions>().FractionDigits() << L" fractional digits";
00078         results << std::endl << std::endl;
00079
00080         // Iterate through the numbers to pad, format them and add them to the results
00081         static constexpr double numbersToPad[] = { 0.12, 1.2, 10.2, 102 };
00082         for (double numberToPad : numbersToPad)
00083         {
00084             hstring paddedNumber = formatter.Format(numberToPad);
00085             results << L"Value: " << numberToPad << L" Padded: " << std::wstring_view(paddedNumber) << std::endl;
00086         }
00087
00088         // Add a carriage return at the end of the scenario for readability
00089         results << std::endl;
00090     }
00091
00092     /// Demonstrates how to perform padding and rounding by using the DecimalFormatter class (can be any of the
00093     /// formatter classes in the Windows.Globalization.Numberformatting namespace) and the IncrementNumberRounder
00094     /// to do so.  The SignificantDigitsNumberRounder can also be used instead of the latter.
00095     void DoPaddingAndRoundingScenarios(std::wostream& results, RoundingAlgorithm roundingAlgorithm, unsigned int significantDigits, int integerDigits, int fractionalDigits)
00096     {
00097         // Create the rounder and set the rounding algorithm provided as a parameter
00098         IncrementNumberRounder rounder;
00099         rounder.RoundingAlgorithm(roundingAlgorithm);
00100
00101         // Create the formatter, set the padding properties provided as parameters and associate the rounder
00102         // we have just created
00103         DecimalFormatter formatter;
00104         formatter.SignificantDigits(significantDigits);
00105         formatter.IntegerDigits(integerDigits);
00106         formatter.FractionDigits(fractionalDigits);
00107         formatter.NumberRounder(rounder);
00108
00109         // Iterate through the increments we have defined in the scenario
00110         static constexpr double incrementsToRound[] = { 0.001, 0.01, 0.1, 1.0 };
00111         for (double incrementToRound : incrementsToRound)
00112         {
00113             // Set the increment to round to
00114             rounder.Increment(incrementToRound);
00115
00116             // Display the properties of the scenario
00117             results << L"Padding and rounding with ";
00118             results << formatter.SignificantDigits() << L" significant digits, ";
00119             results << formatter.IntegerDigits() << L" integer digits, ";
00120             results << formatter.FractionDigits() << L" fractional digits, ";
00121             results << rounder.Increment() << L" increment and ";
00122             results << DisplayRoundingAlgorithmAsString(rounder.RoundingAlgorithm()) << L" rounding algorithm";
00123             results << std::endl << std::endl;
00124
00125             // Iterate through the numbers to round and pad, format them and add them to the results
00126             static constexpr double numbersToFormat[] = { 0.1458, 1.458, 14.58, 145.8 };
00127             for (double numberToFormat : numbersToFormat)
00128             {
00129                 hstring formattedNumber = formatter.Format(numberToFormat);
00130                 results << L"Value: " << numberToFormat << L" Formatted: " << std::wstring_view(formattedNumber) << std::endl;
00131             }
00132
00133             // Add a carriage return at the end of the scenario for readability
00134             results << std::endl;
00135         }
00136     }
00137
00138     /// This scenario illustrates how to provide a rounding algorithm to a CurrencyFormatter class by means of the
00139     /// applyRoundingForCurrency method.  This will associate an IncrementNumberRounder using the same increment as the
00140     /// fractionDigits appropriate for the currency and language.  You can always choose to provide a different rounding
00141     /// algorithm by setting the numberRounder property, as depicted in the doPaddingAndRoundingScenarios function.
00142     /// The mechanism provided here is better suited for currencies.
00143     void DoCurrencyRoundingScenarios(std::wostream& results, hstring const& currencyCode, RoundingAlgorithm roundingAlgorithm)
00144     {
00145         // Create the currency formatter and set the rounding algorithm provided as a parameter
00146         CurrencyFormatter currencyFormatter(currencyCode);
00147         currencyFormatter.ApplyRoundingForCurrency(roundingAlgorithm);
00148
00149         // Display the properties of the scenario
00150         results << L"Currency formatting for ";
00151         results << std::wstring_view(currencyFormatter.Currency()) << L" currency and using the ";
00152         results << DisplayRoundingAlgorithmAsString(roundingAlgorithm) << L" rounding algorithm";
00153         results << std::endl << std::endl;
00154
00155         // Iterate through the numbers to round and add them to the results
00156         static constexpr double numbersToFormat[] = { 14.55, 3.345, 16.2, 175.8 };
00157         for (double numberToFormat : numbersToFormat)
00158         {
00159             hstring formattedNumber = currencyFormatter.Format(numberToFormat);
00160             results << L"Value: " << numberToFormat << L" Formatted: " << std::wstring_view(formattedNumber) << std::endl;
00161         }
00162
00163         // Add a carriage return at the end of the scenario for readability
00164         results << std::endl;
00165     }
00166
00167     /// Shows how to do number rounding using the IncrementNumberRounding class.
00168     void DoIncrementRoundingScenarios(std::wostream& results, RoundingAlgorithm roundingAlgorithm)
00169     {
00170         // Create the rounder and set the rounding algorithm provided as a parameter
00171         IncrementNumberRounder rounder;
00172         rounder.RoundingAlgorithm(roundingAlgorithm);
00173
00174         // Formatter to display the rounded value.  It is recommended to use the increment number
00175         // rounder within a formatter object to avoid precision issues when displaying.
00176         DecimalFormatter formatter;
00177         formatter.NumberRounder(rounder);
00178
00179         // Iterate through the increments we have defined in the scenario
00180         static constexpr double incrementsToRound[] = { 0.001, 0.01, 0.1, 1.0 };
00181         for (double incrementToRound : incrementsToRound)
00182         {
00183             // Set the significant digits to round to
00184             rounder.Increment(incrementToRound);
00185
00186             // Display the properties of the scenario
00187             results << L"Rounding with ";
00188             results << rounder.Increment() << L" increment and ";
00189             results << DisplayRoundingAlgorithmAsString(rounder.RoundingAlgorithm()) << L" rounding algorithm";
00190             results << std::endl << std::endl;
00191
00192             // Iterate through the numbers to round and add them to the results
00193             static constexpr double numbersToRound[] = { 0.1458, 1.458, 14.58, 145.8 };
00194             for (double numberToRound : numbersToRound)
00195             {
00196                 results << L"Value: " << numberToRound << L" Rounded: " << std::wstring_view(formatter.Format(numberToRound)) << std::endl;
00197             }
00198
00199             // Add a carriage return at the end of the scenario for readability
00200             results << std::endl;
00201         }
00202     }
00203
00204     /// Shows how to do number rounding using the SignificantDigitsNumberRounder class.
00205     void DoSignificantDigitRoundingScenarios(std::wostream& results, RoundingAlgorithm roundingAlgorithm)
00206     {
00207         // Create the rounder and set the rounding algorithm provided as a parameter.
00208         SignificantDigitsNumberRounder rounder;
00209         rounder.RoundingAlgorithm(roundingAlgorithm);
00210
00211         // Iterate through the significant digits we have defined in the scenario
00212         static constexpr unsigned int digitsToRound[] = { 3, 2, 1 };
00213         for (unsigned int digitToRound : digitsToRound)
00214         {
00215             // Set the significant digits to round to
00216             rounder.SignificantDigits(digitToRound);
00217
00218             // Display the properties of the scenario
00219             results << L"Rounding with ";
00220             results << rounder.SignificantDigits() << L" significant digits and ";
00221             results << DisplayRoundingAlgorithmAsString(rounder.RoundingAlgorithm()) << L" rounding algorithm";
00222             results << std::endl << std::endl;
00223
00224             // Iterate through the numbers to round and add them to the results
00225             static constexpr double numbersToRound[] = { 0.1458, 1.458, 14.58, 145.8 };
00226             for (double numberToRound : numbersToRound)
00227             {
00228                 double roundedValue = rounder.RoundDouble(numberToRound);
00229                 results << L"Value: " << numberToRound << L" Rounded: " << roundedValue << std::endl;
00230             }
00231
00232             // Add a carriage return at the end of the scenario for readability
00233             results << std::endl;
00234         }
00235     }
00236 }
00237
00238 namespace winrt::SDKTemplate::implementation
00239 {
00240     Scenario5_RoundingAndPadding::Scenario5_RoundingAndPadding()
00241     {
00242         InitializeComponent();
00243     }
00244
00245     void Scenario5_RoundingAndPadding::Display_Click(IInspectable const&, RoutedEventArgs const&)
00246     {
00247         // Variable where we keep results to display
00248         std::wostringstream results;
00249
00250         // Create a decimal formatter used to do padding with only 4 significant digits.  We zero the
00251         // integerDigits and fractionDigits to only show the behavior of the significantDigits property
00252         // when formatting.
00253         DecimalFormatter decimalFormatter;
00254         decimalFormatter.SignificantDigits(4);
00255         decimalFormatter.IntegerDigits(0);
00256         decimalFormatter.FractionDigits(0);
00257
00258         // Run through the scenarios with padding
00259         DoPaddingScenarios(results, decimalFormatter);
00260
00261         // Create a percent formatter used to do padding with 4 significant digits, 2 minimum integer
00262         // digits, 2 minimum factional digits.  This will show how the behavior of the significantDigits
00263         // property in conjunction with the integerDigits and fractionDigits properties.
00264         PercentFormatter percentFormatter;
00265         percentFormatter.SignificantDigits(4);
00266         percentFormatter.IntegerDigits(2);
00267         percentFormatter.FractionDigits(2);
00268
00269         // Run through the scenarios
00270         DoPaddingScenarios(results, percentFormatter);
00271
00272         // Do the significant rounding scenarios with round up algorithm
00273         DoSignificantDigitRoundingScenarios(results, RoundingAlgorithm::RoundUp);
00274
00275         // Do the significant rounding scenarios with round down algorithm
00276         DoSignificantDigitRoundingScenarios(results, RoundingAlgorithm::RoundDown);
00277
00278         // Do the increment rounding scenarios with round half up algorithm
00279         DoIncrementRoundingScenarios(results, RoundingAlgorithm::RoundHalfUp);
00280
00281         // Do the increment rounding scenarios with round half down algorithm
00282         DoIncrementRoundingScenarios(results, RoundingAlgorithm::RoundHalfDown);
00283
00284         // Do currency formatting with rounding for Japanese Yen with round half to odd algorithm
00285         DoCurrencyRoundingScenarios(results, L"JPY", RoundingAlgorithm::RoundHalfToOdd);
00286
00287         // Do currency formatting with rounding for Euro with round half to even algorithm
00288         DoCurrencyRoundingScenarios(results, L"EUR", RoundingAlgorithm::RoundHalfToEven);
00289
00290         // Do padding and rounding scenarios using round half up algorithm
00291         DoPaddingAndRoundingScenarios(results, RoundingAlgorithm::RoundHalfUp, 4, 3, 2);
00292
00293         // Do padding and rounding scenarios using round half down algorithm
00294         DoPaddingAndRoundingScenarios(results, RoundingAlgorithm::RoundHalfDown, 4, 3, 2);
00295
00296         OutputTextBlock().Text(results.str());
00297     }
00298 }
Generated on Fri Nov 15 2024 22:20:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_Metadata Member List

This is the complete list of members for Scenario5_Metadata, including all inherited members.
adaptiveMediaSourceLogger | Scenario5_Metadata | [private]
HideDescriptionOnSmallScreen() | Scenario5_Metadata | [inline, private]
Item_TimedMetadataTracksChanged(MediaPlaybackItem item, IVectorChangedEventArgs args) | Scenario5_Metadata | [inline, private]
lastProcessedAdId | Scenario5_Metadata | [private]
LoadSourceFromUriAsync(Uri uri, HttpClient httpClient=null) | Scenario5_Metadata | [inline, private]
Log(string message) | Scenario5_Metadata | [inline, private]
mediaPlaybackItemLogger | Scenario5_Metadata | [private]
mediaPlayerLogger | Scenario5_Metadata | [private]
mediaSourceLogger | Scenario5_Metadata | [private]
metadata_emsg_mp4_CueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args) | Scenario5_Metadata | [inline, private]
metadata_extm3u_CueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args) | Scenario5_Metadata | [inline, private]
metadata_id3_CueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args) | Scenario5_Metadata | [inline, private]
metadata_TrackingEvents_CueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args) | Scenario5_Metadata | [inline, private]
metadata_TrackingEvents_CueExited(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args) | Scenario5_Metadata | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario5_Metadata | [inline, protected]
Page_OnLoaded(object sender, RoutedEventArgs e) | Scenario5_Metadata | [inline, private]
RegisterForMediaPlaybackItemEvents(MediaPlaybackItem item) | Scenario5_Metadata | [inline, private]
RegisterForMediaSourceEvents(MediaSource source) | Scenario5_Metadata | [inline, private]
RegisterMetadataHandlers(MediaPlaybackItem mediaPlaybackItem, int index) | Scenario5_Metadata | [inline, private]
Scenario5_Metadata() | Scenario5_Metadata | [inline]
ScheduleAdFromScte35Payload(TimedMetadataTrack timedMetadataTrack, uint presentation_time_delta, uint timescale, uint event_duration, string scte35payload) | Scenario5_Metadata | [inline, private]
Source_OpenOperationCompleted(MediaSource source, MediaSourceOpenOperationCompletedEventArgs args) | Scenario5_Metadata | [inline, private]
UnregisterForMediaPlaybackItemEvents(MediaPlaybackItem item) | Scenario5_Metadata | [inline, private]
UnregisterForMediaSourceEvents(MediaSource source) | Scenario5_Metadata | [inline, private]
UnregisterHandlers(MediaPlayer mediaPlayer) | Scenario5_Metadata | [inline, private]
UnregisterMetadataHandlers(TimedMetadataTrack timedTrack) | Scenario5_Metadata | [inline, private]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FilterConfig Member List

This is the complete list of members for FilterConfig, including all inherited members.
RegisterGlobalFilters(GlobalFilterCollection filters) FilterConfig [inline, static]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cs/scenario7.xaml.cs Source File

  • ApplicationResources
  • cs

scenario7.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using SDKTemplate;
00015 using System;
00016 using Windows.ApplicationModel.Resources.Core;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     public sealed partial class Scenario7 : Page
00024     {
00025         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00026         // as NotifyUser()
00027         MainPage rootPage = MainPage.Current;
00028
00029         // pointer to default resource context for this view
00030         ResourceContext defaultContextForCurrentView;
00031
00032
00033         public Scenario7()
00034         {
00035             this.InitializeComponent();
00036             defaultContextForCurrentView = ResourceContext.GetForCurrentView();
00037         }
00038
00039         /// <summary>
00040         /// Invoked when this page is about to be displayed in a Frame.
00041         /// </summary>
00042         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00043         /// property is typically used to configure the page.</param>
00044         protected override void OnNavigatedTo(NavigationEventArgs e)
00045         {
00046             this.Scenario7TextBlock.Text = "";
00047         }
00048
00049         /// <summary>
00050         /// This is the click handler for the 'Scenario7Button_Show' button.  You would replace this with your own handler
00051         /// if you have a button or buttons on this page.
00052         /// </summary>
00053         /// <param name="sender"></param>
00054         /// <param name="e"></param>
00055         private void Scenario7Button_Show_Click(object sender, RoutedEventArgs e)
00056         {
00057             Button b = sender as Button;
00058             if (b != null)
00059             {
00060
00061                 this.Scenario7TextBlock.Text = ResourceManager.Current.MainResourceMap.GetValue("Resources/string1", defaultContextForCurrentView).ValueAsString;
00062
00063                 defaultContextForCurrentView.QualifierValues.MapChanged += async (s, m) =>
00064                 {
00065                     await this.Scenario7TextBlock.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00066                     {
00067                         this.Scenario7TextBlock.Text = ResourceManager.Current.MainResourceMap.GetValue("Resources/string1", defaultContextForCurrentView).ValueAsString;
00068                     });
00069                 };
00070             }
00071         }
00072
00073     }
00074 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DataReaderWriter/cpp/SampleConfiguration.h Source File

  • DataReaderWriter
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return L"DataReader/Writer Sample";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks/Common/BoolToVisibilityConverter.h Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks
  • Common

BoolToVisibilityConverter.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012 namespace AdventureWorks
00013 {
00014     [Windows::UI::Xaml::Data::Bindable]
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class BoolToVisibilityConverter sealed : Windows::UI::Xaml::Data::IValueConverter
00017     {
00018     public:
00019         BoolToVisibilityConverter();
00020
00021         // Inherited via IValueConverter
00022         virtual Platform::Object ^ Convert(Platform::Object ^value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object ^parameter, Platform::String ^language);
00023         virtual Platform::Object ^ ConvertBack(Platform::Object ^value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object ^parameter, Platform::String ^language);
00024     };
00025 }
00026
Generated on Fri Nov 15 2024 22:18:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/Scenario2.h Source File

  • FileAccess
  • cppwinrt

Scenario2.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     /// <summary>
00020     /// Getting a file's parent folder.
00021     /// </summary>
00022     struct Scenario2 : Scenario2T<Scenario2>
00023     {
00024         Scenario2();
00025
00026         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00027         fire_and_forget GetParent_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00028
00029     private:
00030         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00031     };
00032 }
00033
00034 namespace winrt::SDKTemplate::factory_implementation
00035 {
00036     struct Scenario2 : Scenario2T<Scenario2, implementation::Scenario2>
00037     {
00038     };
00039 }
Generated on Fri Nov 15 2024 22:19:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampDevice/cs/Scenario1_GetLamp.xaml.cs Source File

  • LampDevice
  • cs

Scenario1_GetLamp.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace Lamp
00013 {
00014     using SDKTemplate;
00015     using System;
00016     using System.Globalization;
00017     using System.Linq;
00018     using System.Threading.Tasks;
00019     using Windows.Devices.Lights;
00020     using Windows.Devices.Enumeration;
00021     using Windows.UI.Xaml;
00022     using Windows.UI.Xaml.Controls;
00023     using Windows.UI.Xaml.Navigation;
00024
00025     /// <summary>
00026     /// Scenario 1 Get Lamp Page
00027     /// </summary>
00028     public sealed partial class Scenario1_GetLamp : Page
00029     {
00030         /// <summary>
00031         /// Private MainPage object for status updates
00032         /// </summary>
00033         private MainPage rootPage;
00034
00035         /// <summary>
00036         /// Initializes a new instance of the <see cref="Scenario1_GetLamp"/> class.
00037         /// </summary>
00038         public Scenario1_GetLamp()
00039         {
00040             this.InitializeComponent();
00041         }
00042
00043         /// <summary>
00044         /// Override default OnNavigateTo to initialize
00045         /// the rootPage object for Status message updates
00046         /// </summary>
00047         /// <param name="e"></param>
00048         protected override void OnNavigatedTo(NavigationEventArgs e)
00049         {
00050             rootPage = MainPage.Current;
00051             base.OnNavigatedTo(e);
00052         }
00053
00054         /// <summary>
00055         /// acquires Lamp instance by getting class selection string
00056         /// for Lamp devices, then selecting the first lamp device on
00057         /// the back of the device
00058         /// </summary>
00059         /// <param name="sender">Contains information regarding button that fired event</param>
00060         /// <param name="e">Contains state information and event data associated with the event</param>
00061         private async void InitLampBtn_Click(object sender, RoutedEventArgs e)
00062         {
00063             try
00064             {
00065                 await LogStatusToOutputBoxAsync("Getting class selection string for lamp devices...");
00066
00067                 // Returns class selection string for Lamp devices
00068                 string selectorStr = Lamp.GetDeviceSelector();
00069                 await LogStatusToOutputBoxAsync(string.Format(CultureInfo.InvariantCulture, "Lamp class selection string:\n {0}", selectorStr));
00070
00071                 await LogStatusToOutputBoxAsync("Finding all lamp devices...");
00072
00073                 // Finds all devices based on lamp class selector string
00074                 DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selectorStr);
00075                 await LogStatusToOutputBoxAsync(string.Format(CultureInfo.InvariantCulture, "Number of lamp devices found: {0}", devices.Count.ToString()));
00076
00077                 // Select the first lamp device found on the back of the device
00078                 await LogStatusToOutputBoxAsync("Selecting first lamp device found on back of the device");
00079                 DeviceInformation deviceInfo = devices.FirstOrDefault(di => di.EnclosureLocation != null && di.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);
00080
00081                 if (deviceInfo == null)
00082                 {
00083                     throw new InvalidOperationException("Error: No lamp device was found");
00084                 }
00085
00086                 await LogStatusToOutputBoxAsync(string.Format(CultureInfo.InvariantCulture, "Acquiring Lamp instance from Id:\n {0}", deviceInfo.Id));
00087                 Lamp lamp = await Lamp.FromIdAsync(deviceInfo.Id);
00088                 await LogStatusAsync(string.Format(CultureInfo.InvariantCulture, "Lamp instance acquired, Device Id:\n {0}", lamp.DeviceId), NotifyType.StatusMessage);
00089
00090                 // Here we must Dispose of the lamp object once we are no longer
00091                 // using it to release any native resources
00092                 await LogStatusToOutputBoxAsync("Disposing of lamp instance");
00093                 lamp.Dispose();
00094                 lamp = null;
00095                 await LogStatusToOutputBoxAsync("Disposed");
00096             }
00097             catch(InvalidOperationException eX)
00098             {
00099                 await LogStatusAsync(eX.Message, NotifyType.ErrorMessage);
00100             }
00101         }
00102
00103         /// <summary>
00104         /// Gets the Default Lamp instance, if no instance is found it throws
00105         /// InvalidOperation Exception
00106         /// </summary>
00107         /// <param name="sender">Contains information regarding button that fired event</param>
00108         /// <param name="e">Contains state information and event data associated with the event</param>
00109         private async void GetDefaultAsyncBtn_Click(object sender, RoutedEventArgs e)
00110         {
00111             try
00112             {
00113                 await LogStatusToOutputBoxAsync("Initializing lamp");
00114
00115                 // acquiring lamp instance via using statement allows for the
00116                 // object to be automatically disposed once the lamp object
00117                 // goes out of scope releasing native resources
00118                 using (var lamp = await Lamp.GetDefaultAsync())
00119                 {
00120                     if (lamp == null)
00121                     {
00122                         await LogStatusAsync("Error: No Lamp device found", NotifyType.ErrorMessage);
00123                         return;
00124                     }
00125
00126                     await LogStatusAsync(string.Format(CultureInfo.InvariantCulture, "Default lamp instance acquired, Device Id: {0}", lamp.DeviceId), NotifyType.StatusMessage);
00127                 }
00128
00129                 // Lamp object is automatically Disposed now that it's out of scope
00130                 await LogStatusToOutputBoxAsync("Lamp Disposed");
00131             }
00132             catch (InvalidOperationException ex)
00133             {
00134                 await LogStatusAsync(ex.ToString(), NotifyType.ErrorMessage);
00135             }
00136         }
00137
00138         /// <summary>
00139         /// Marshall log message to the UI thread
00140         /// and update outputBox, this method is for more general messages
00141         /// </summary>
00142         /// <param name="message">Message to log to the outputBox</param>
00143         private async Task LogStatusToOutputBoxAsync(string message)
00144         {
00145             await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00146             {
00147                 outputBox.Text += message + "\r\n";
00148                 outputScrollViewer.ChangeView(0, outputBox.ActualHeight, 1);
00149             });
00150         }
00151
00152         /// <summary>
00153         /// Method to log Status to Main Status block,
00154         /// this method is for important status messages to be
00155         /// displayed at bottom of scenario page
00156         /// </summary>
00157         /// <param name="message">Message to log to the output box</param>
00158         /// <param name="type">Notification Type for status message</param>
00159         private async Task LogStatusAsync(string message, NotifyType type)
00160         {
00161             await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00162             {
00163                 rootPage.NotifyUser(message, type);
00164             });
00165             await LogStatusToOutputBoxAsync(message);
00166         }
00167     }
00168 }
Generated on Fri Nov 15 2024 22:20:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OnDemandHotspot/cs/BackgroundTask/Properties/AssemblyInfo.cs Source File

  • OnDemandHotspot
  • cs
  • BackgroundTask
  • Properties

AssemblyInfo.cs

Go to the documentation of this file.
00001 ﻿using System.Reflection;
00002 using System.Runtime.CompilerServices;
00003 using System.Runtime.InteropServices;
00004
00005 // General Information about an assembly is controlled through the following
00006 // set of attributes. Change these attribute values to modify the information
00007 // associated with an assembly.
00008 [assembly: AssemblyTitle("BackgroundTask")]
00009 [assembly: AssemblyDescription("")]
00010 [assembly: AssemblyConfiguration("")]
00011 [assembly: AssemblyCompany("")]
00012 [assembly: AssemblyProduct("BackgroundTask")]
00013 [assembly: AssemblyCopyright("Copyright ©  2021")]
00014 [assembly: AssemblyTrademark("")]
00015 [assembly: AssemblyCulture("")]
00016
00017 // Version information for an assembly consists of the following four values:
00018 //
00019 //      Major Version
00020 //      Minor Version
00021 //      Build Number
00022 //      Revision
00023 //
00024 // You can specify all the values or you can default the Build and Revision Numbers
00025 // by using the '*' as shown below:
00026 // [assembly: AssemblyVersion("1.0.*")]
00027 [assembly: AssemblyVersion("1.0.0.0")]
00028 [assembly: AssemblyFileVersion("1.0.0.0")]
00029 [assembly: ComVisible(false)]
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6_SecondaryTileNotification Member List

This is the complete list of members for Scenario6_SecondaryTileNotification, including all inherited members.
PinLiveTile_Click(Windows::Foundation::IInspectable sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario6_SecondaryTileNotification |
Scenario6_SecondaryTileNotification() | Scenario6_SecondaryTileNotification |
SendBadgeNotification_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario6_SecondaryTileNotification |
SendBadgeNotificationWithStringManipulation_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario6_SecondaryTileNotification |
SendTileNotification_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario6_SecondaryTileNotification |
SendTileNotificationWithStringManipulation_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario6_SecondaryTileNotification |
VerifyTileIsPinned() | Scenario6_SecondaryTileNotification | [private]
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/Marker.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

Marker.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009 #include "StspDefs.h"
00010
00011 namespace Microsoft { namespace Samples { namespace SimpleCommunication {
00012 class CMarker : public IMarker
00013 {
00014 public:
00015     static HRESULT Create(
00016         MFSTREAMSINK_MARKER_TYPE eMarkerType,
00017         const PROPVARIANT *pvarMarkerValue,
00018         const PROPVARIANT *pvarContextValue,
00019         IMarker **ppMarker
00020         );
00021
00022     // IUnknown methods.
00023     IFACEMETHOD (QueryInterface) (REFIID riid, void **ppv);
00024     IFACEMETHOD_(ULONG, AddRef) ();
00025     IFACEMETHOD_(ULONG, Release) ();
00026
00027     IFACEMETHOD (GetMarkerType) (MFSTREAMSINK_MARKER_TYPE *pType);
00028     IFACEMETHOD (GetMarkerValue) (PROPVARIANT *pvar);
00029     IFACEMETHOD (GetContext) (PROPVARIANT *pvar);
00030
00031 protected:
00032     MFSTREAMSINK_MARKER_TYPE _eMarkerType;
00033     PROPVARIANT _varMarkerValue;
00034     PROPVARIANT _varContextValue;
00035
00036 private:
00037     long    _cRef;
00038
00039     CMarker(MFSTREAMSINK_MARKER_TYPE eMarkerType);
00040     virtual ~CMarker();
00041 };
00042 }}}
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CBufferEnumerator Member List

This is the complete list of members for CBufferEnumerator, including all inherited members.
_buffers | CBufferEnumerator | [private]
_cRef | CBufferEnumerator | [private]
_currentIt | CBufferEnumerator | [private]
_spParent | CBufferEnumerator | [private]
CBufferEnumerator(CBufferPacket::Container &container, IUnknown *pParent) | CBufferEnumerator | [protected]
CreateInstance(CBufferPacket::Container &container, IUnknown *pParent, IBufferEnumerator **ppEnumerator) | CBufferEnumerator | [static]
GetCurrent(_Out_ IMediaBufferWrapper **ppBuffer) | CBufferEnumerator |
IFACEMETHOD_(ULONG, AddRef)() | CBufferEnumerator |
IFACEMETHOD_(ULONG, Release)() | CBufferEnumerator |
IFACEMETHOD_(bool, IsValid)() | CBufferEnumerator |
MoveNext() | CBufferEnumerator |
QueryInterface(REFIID riid, void **ppv) | CBufferEnumerator |
Reset() | CBufferEnumerator |
~CBufferEnumerator() | CBufferEnumerator | [protected]
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlContextMenu/cpp/pch.cpp Source File

  • XamlContextMenu
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RadioManager/cppwinrt/pch.h Source File

  • RadioManager
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Devices.Radios.h"
00008 #include "winrt/Windows.System.h"
00009 #include "winrt/Windows.UI.Core.h"
00010 #include "winrt/Windows.UI.Xaml.h"
00011 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00012 #include "winrt/Windows.UI.Xaml.Controls.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00014 #include "winrt/Windows.UI.Xaml.Documents.h"
00015 #include "winrt/Windows.UI.Xaml.Interop.h"
00016 #include "winrt/Windows.UI.Xaml.Markup.h"
00017 #include "winrt/Windows.UI.Xaml.Media.h"
00018 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NfcProvisioner/cs/Scenario1.xaml.cs Source File

  • NfcProvisioner
  • cs

Scenario1.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading;
00014 using System.Threading.Tasks;
00015 using System.Runtime.InteropServices;
00016 using Windows.Networking.Proximity;
00017 using Windows.Storage;
00018 using Windows.Storage.Pickers;
00019 using Windows.Storage.Streams;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Navigation;
00023 using SDKTemplate;
00024
00025 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00026
00027 namespace NfcProvisioner
00028 {
00029     /// <summary>
00030     /// The NfcProvHeader is a prefix to each NFC provisioning message which contains information about the protocol version, message index, total message count, and etc.
00031     /// </summary>
00032     [StructLayout(LayoutKind.Sequential, Pack = 1)]
00033     public struct NfcProvHeader
00034     {
00035         public byte version;
00036         public byte leading;
00037         public byte index;
00038         public byte total;
00039     }
00040
00041     /// <summary>
00042     /// An empty page that can be used on its own or navigated to within a Frame.
00043     /// </summary>
00044     public sealed partial class Scenario1 : Page
00045     {
00046         private MainPage rootPage;
00047         private IStorageFile provisioningPackageFile = null;
00048         private CancellationTokenSource currentTransferCancelToken = null;
00049
00050         const byte NFC_PROV_MESSAGE_CURRENT_VERSION = 0;
00051         const byte NFC_PROV_MESSAGE_LEADING_BYTE = 0xFF;
00052         const string NFC_PROV_MESSAGE_PROTOCOL_NAME = "Windows.ProvPlugins.Chunk";
00053         const long INVALID_PUBLISHED_MESSAGE_ID = -1;
00054
00055         public Scenario1()
00056         {
00057             this.InitializeComponent();
00058         }
00059
00060         protected override void OnNavigatedTo(NavigationEventArgs e)
00061         {
00062             rootPage = MainPage.Current;
00063         }
00064
00065         private async void Browse_Click(object sender, RoutedEventArgs e)
00066         {
00067             FileOpenPicker openPicker = new FileOpenPicker();
00068
00069             // Filter *.ppkg files and only show provisioning package files when opening file picker.
00070             openPicker.FileTypeFilter.Add(".ppkg");
00071             provisioningPackageFile = await openPicker.PickSingleFileAsync();
00072
00073             if (null == provisioningPackageFile)
00074             {
00075                 rootPage.NotifyUser("No package was selected.", NotifyType.StatusMessage);
00076                 ProvisioningPackagePathText.Text = "";
00077                 TransferButton.Visibility = Visibility.Collapsed;
00078                 CancelTransferButton.Visibility = Visibility.Collapsed;
00079             }
00080             else
00081             {
00082                 rootPage.NotifyUser("One package was selected.", NotifyType.StatusMessage);
00083                 ProvisioningPackagePathText.Text = provisioningPackageFile.Name;
00084                 TransferButton.Visibility = Visibility.Visible;
00085             }
00086         }
00087
00088         private async void Transfer_Click(object sender, RoutedEventArgs e)
00089         {
00090             TransferButton.IsEnabled = false;
00091             TransferButton.Visibility = Visibility.Collapsed;
00092             CancelTransferButton.Visibility = Visibility.Visible;
00093
00094             try
00095             {
00096                 currentTransferCancelToken = new CancellationTokenSource();
00097                 await InternalTransferHandlerAsync(currentTransferCancelToken.Token);
00098                 currentTransferCancelToken = null;
00099             }
00100             catch (System.OperationCanceledException /*exception*/)
00101             {
00102                 rootPage.NotifyUser("Transfer has been cancelled.", NotifyType.StatusMessage);
00103             }
00104             catch (System.ArgumentException /*exception*/)
00105             {
00106                 rootPage.NotifyUser("We couldn't finish the transfer. Tap the devices again and keep them close together.", NotifyType.ErrorMessage);
00107             }
00108
00109             CancelTransferButton.Visibility = Visibility.Collapsed;
00110             TransferButton.Visibility = Visibility.Visible;
00111             TransferButton.IsEnabled = true;
00112         }
00113
00114         private void CancelTransfer_Click(object sender, RoutedEventArgs e)
00115         {
00116             if (null != currentTransferCancelToken)
00117             {
00118                 currentTransferCancelToken.Cancel();
00119             }
00120         }
00121
00122         /// <summary>
00123         /// Function to convert the selected provisioning package into chunk and send it over NFC.
00124         /// </summary>
00125         /// <returns></returns>
00126         private async Task InternalTransferHandlerAsync(CancellationToken ct)
00127         {
00128             rootPage.NotifyUser("Tap device to transfer package.", NotifyType.StatusMessage);
00129
00130             if (null == provisioningPackageFile)
00131             {
00132                 rootPage.NotifyUser("Select a package before transferring.", NotifyType.ErrorMessage);
00133                 return;
00134             }
00135
00136             IBuffer buffer = await FileIO.ReadBufferAsync(provisioningPackageFile);
00137             if (null == buffer)
00138             {
00139                 rootPage.NotifyUser("Something was wrong. Choose another package and retry again.", NotifyType.ErrorMessage);
00140                 return;
00141             }
00142
00143             ProximityDevice proximityDevice = ProximityDevice.GetDefault();
00144             if (null == proximityDevice)
00145             {
00146                 rootPage.NotifyUser("You'll need to turn on NFC to transfer the package. Go to NFC settings.", NotifyType.ErrorMessage);
00147                 return;
00148             }
00149
00150             // Start to format the provisioning package into chunks, and transfer it to another device to be provisioned.
00151             await ConvertToNfcMessageAsync(buffer, proximityDevice, NfcMessageHandlerAsync, ct);
00152
00153             rootPage.NotifyUser("Success!", NotifyType.StatusMessage);
00154         }
00155
00156         /// <summary>
00157         /// Function to handle the chunk message and push the NFC message to proximity device.
00158         /// </summary>
00159         /// <param name="proximityDevice">ProximityDevice instance to be used.</param>
00160         /// <param name="chuckData">IBuffer to chunk message.</param>
00161         private static async Task NfcMessageHandlerAsync(ProximityDevice proximityDevice, IBuffer chuckData, CancellationToken ct)
00162         {
00163             using (var publishedEvent = new AutoResetEvent(false))
00164             {
00165                 long publishedMessageId = INVALID_PUBLISHED_MESSAGE_ID;
00166
00167                 publishedMessageId = proximityDevice.PublishBinaryMessage(
00168                     NFC_PROV_MESSAGE_PROTOCOL_NAME,
00169                     chuckData, (
00170                         Windows.Networking.Proximity.ProximityDevice device,
00171                         long messageId
00172                     ) =>
00173                     {
00174                         publishedEvent.Set();
00175                     });
00176
00177                 if (INVALID_PUBLISHED_MESSAGE_ID == publishedMessageId)
00178                 {
00179                     throw new System.ArgumentException("Published message ID returned was invalid.");
00180                 }
00181
00182                 // Wait for the event to be signaled on a threadpool thread so we don't block the UI thread.
00183                 await Task.Run(() =>
00184                 {
00185                     // Wait for the message transmitted handler to ensure the NFC message has been processed internally.
00186                     WaitHandle.WaitAny(new WaitHandle[] { publishedEvent, ct.WaitHandle });
00187                     ct.ThrowIfCancellationRequested();
00188                 });
00189             }
00190         }
00191
00192         /// <summary>
00193         /// Function to format provisioning package into chunk data with a NfcProvHeader prefix.
00194         /// </summary>
00195         /// <param name="content">IBuffer to the provisioning package content.</param>
00196         /// <param name="device">ProximityDevice instance passed in the messageHandler.</param>
00197         /// <param name="messageHandler">Delegate handler to consume the chunk data.</param>
00198         private static async Task ConvertToNfcMessageAsync(IBuffer content, ProximityDevice device, Func<ProximityDevice, IBuffer, CancellationToken, Task> messageHandlerAsync, CancellationToken ct)
00199         {
00200             var maxMessageSize = device.MaxMessageBytes;
00201             var headerSize = GetNfcProvHeaderSize();
00202             uint chunkSize = maxMessageSize - (uint)headerSize;
00203
00204             // Calculate the chunk count needed for this transfer.
00205             uint chunks = content.Length / chunkSize;
00206             if ((content.Length % chunkSize) > 0)
00207             {
00208                 ++chunks;
00209             }
00210
00211             // Loop and compose the payload per chunk data.
00212             for (uint posToRead = 0; posToRead < content.Length; posToRead += chunkSize)
00213             {
00214                 var dataWriter = new DataWriter();
00215                 var header = new NfcProvHeader();
00216
00217                 header.version = NFC_PROV_MESSAGE_CURRENT_VERSION;  // Currently the supported version is 0x00.
00218                 header.leading = NFC_PROV_MESSAGE_LEADING_BYTE;     // The leading byte should be always 0xFF.
00219                 header.index = (byte)(posToRead / chunkSize);       // To specify which chunk to this message.
00220                 header.total = (byte)chunks;                        // To specify the total message count for this transfer.
00221
00222                 int bufferSizeToAlloc = (int)maxMessageSize;
00223                 if (header.total == (header.index + 1))
00224                 {
00225                     bufferSizeToAlloc = headerSize + (int)(content.Length - posToRead);
00226                 }
00227
00228                 // Write the prefix first and the chunk data of the provisioning package.
00229                 dataWriter.WriteBytes(GetBytes(header));
00230                 dataWriter.WriteBuffer(content, posToRead, (uint)(bufferSizeToAlloc - headerSize));
00231
00232                 // Invoke the delegate handler to handle the NFC message.
00233                 await messageHandlerAsync(device, dataWriter.DetachBuffer(), ct);
00234             }
00235         }
00236
00237         private static byte[] GetBytes(NfcProvHeader header)
00238         {
00239             int size = Marshal.SizeOf(header);
00240             byte[] arr = new byte[size];
00241             IntPtr ptr = Marshal.AllocHGlobal(size);
00242
00243             Marshal.StructureToPtr(header, ptr, true);
00244             Marshal.Copy(ptr, arr, 0, size);
00245             Marshal.FreeHGlobal(ptr);
00246
00247             return arr;
00248         }
00249
00250         private static int GetNfcProvHeaderSize()
00251         {
00252             var header = new NfcProvHeader();
00253             return Marshal.SizeOf(header);
00254         }
00255     }
00256 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LinguisticServices/cppwinrt/Scenario4_CharacterGrouping.h Source File

  • LinguisticServices
  • cppwinrt

Scenario4_CharacterGrouping.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_CharacterGrouping.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario4_CharacterGrouping : Scenario4_CharacterGroupingT<Scenario4_CharacterGrouping>
00020     {
00021         Scenario4_CharacterGrouping();
00022
00023         void GetGroups_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024         void AssignGroup_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00025
00026     private:
00027         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00028         Windows::Globalization::Collation::CharacterGroupings ActiveGroupings{ nullptr };
00029         std::map<hstring, Windows::UI::Xaml::UIElement> Groups;
00030         static constexpr wchar_t GlobeString[] = L"\U0001F310";
00031
00032         void AddGroup(hstring const& label, Windows::UI::Xaml::UIElement const& element);
00033     };
00034 }
00035
00036 namespace winrt::SDKTemplate::factory_implementation
00037 {
00038     struct Scenario4_CharacterGrouping : Scenario4_CharacterGroupingT<Scenario4_CharacterGrouping, implementation::Scenario4_CharacterGrouping>
00039     {
00040     };
00041 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ColorEntry Member List

This is the complete list of members for ColorEntry, including all inherited members.
Brushify(Color c) | ColorEntry | [inline]
Color | ColorEntry |
ColorName | ColorEntry |
Generated on Fri Nov 15 2024 22:24:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario11_TryGet.xaml.h Source File

  • FileAccess
  • cpp

Scenario11_TryGet.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario11_TryGet.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Attempting to get a file with no error on failure.
00022     /// </summary>
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class Scenario11 sealed
00025     {
00026     public:
00027         Scenario11();
00028
00029     private:
00030         MainPage^ rootPage = MainPage::Current;
00031
00032         void GetFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033     };
00034 }
Generated on Fri Nov 15 2024 22:19:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/Common/DeviceResources.cpp Source File

  • BasicHologram
  • cpp
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿
00002 #include "pch.h"
00003 #include "DeviceResources.h"
00004 #include "DirectXHelper.h"
00005
00006 #include <Collection.h>
00007 #include <windows.graphics.directx.direct3d11.interop.h>
00008
00009 using namespace D2D1;
00010 using namespace Microsoft::WRL;
00011 using namespace Windows::Graphics::DirectX::Direct3D11;
00012 using namespace Windows::Graphics::Display;
00013 using namespace Windows::Graphics::Holographic;
00014
00015 // Constructor for DeviceResources.
00016 DX::DeviceResources::DeviceResources()
00017 {
00018     CreateDeviceIndependentResources();
00019 }
00020
00021 // Configures resources that don't depend on the Direct3D device.
00022 void DX::DeviceResources::CreateDeviceIndependentResources()
00023 {
00024     // Initialize Direct2D resources.
00025     D2D1_FACTORY_OPTIONS options {};
00026
00027 #if defined(_DEBUG)
00028     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00029     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00030 #endif
00031
00032     // Initialize the Direct2D Factory.
00033     DX::ThrowIfFailed(
00034         D2D1CreateFactory(
00035             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00036             __uuidof(ID2D1Factory2),
00037             &options,
00038             &m_d2dFactory
00039             )
00040         );
00041
00042     // Initialize the DirectWrite Factory.
00043     DX::ThrowIfFailed(
00044         DWriteCreateFactory(
00045             DWRITE_FACTORY_TYPE_SHARED,
00046             __uuidof(IDWriteFactory2),
00047             &m_dwriteFactory
00048             )
00049         );
00050
00051     // Initialize the Windows Imaging Component (WIC) Factory.
00052     DX::ThrowIfFailed(
00053         CoCreateInstance(
00054             CLSID_WICImagingFactory2,
00055             nullptr,
00056             CLSCTX_INPROC_SERVER,
00057             IID_PPV_ARGS(&m_wicFactory)
00058             )
00059         );
00060 }
00061
00062 void DX::DeviceResources::SetHolographicSpace(HolographicSpace^ holographicSpace)
00063 {
00064     // Cache the holographic space. Used to re-initalize during device-lost scenarios.
00065     m_holographicSpace = holographicSpace;
00066
00067     InitializeUsingHolographicSpace();
00068 }
00069
00070 void DX::DeviceResources::InitializeUsingHolographicSpace()
00071 {
00072     // The holographic space might need to determine which adapter supports
00073     // holograms, in which case it will specify a non-zero PrimaryAdapterId.
00074     LUID id =
00075     {
00076         m_holographicSpace->PrimaryAdapterId.LowPart,
00077         m_holographicSpace->PrimaryAdapterId.HighPart
00078     };
00079
00080     // When a primary adapter ID is given to the app, the app should find
00081     // the corresponding DXGI adapter and use it to create Direct3D devices
00082     // and device contexts. Otherwise, there is no restriction on the DXGI
00083     // adapter the app can use.
00084     if ((id.HighPart != 0) || (id.LowPart != 0))
00085     {
00086         UINT createFlags = 0;
00087 #ifdef DEBUG
00088         if (DX::SdkLayersAvailable())
00089         {
00090             createFlags |= DXGI_CREATE_FACTORY_DEBUG;
00091         }
00092 #endif
00093         // Create the DXGI factory.
00094         ComPtr<IDXGIFactory1> dxgiFactory;
00095         DX::ThrowIfFailed(
00096             CreateDXGIFactory2(
00097                 createFlags,
00098                 IID_PPV_ARGS(&dxgiFactory)
00099                 )
00100             );
00101         ComPtr<IDXGIFactory4> dxgiFactory4;
00102         DX::ThrowIfFailed(dxgiFactory.As(&dxgiFactory4));
00103
00104         // Retrieve the adapter specified by the holographic space.
00105         DX::ThrowIfFailed(
00106             dxgiFactory4->EnumAdapterByLuid(
00107                 id,
00108                 IID_PPV_ARGS(&m_dxgiAdapter)
00109                 )
00110             );
00111     }
00112     else
00113     {
00114         m_dxgiAdapter.Reset();
00115     }
00116
00117     CreateDeviceResources();
00118
00119     m_holographicSpace->SetDirect3D11Device(m_d3dInteropDevice);
00120 }
00121
00122 // Configures the Direct3D device, and stores handles to it and the device context.
00123 void DX::DeviceResources::CreateDeviceResources()
00124 {
00125     // This flag adds support for surfaces with a different color channel ordering
00126     // than the API default. It is required for compatibility with Direct2D.
00127     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00128
00129 #if defined(_DEBUG)
00130     if (DX::SdkLayersAvailable())
00131     {
00132         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00133         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00134     }
00135 #endif
00136
00137     // This array defines the set of DirectX hardware feature levels this app will support.
00138     // Note the ordering should be preserved.
00139     // Note that HoloLens supports feature level 11.1. The HoloLens emulator is also capable
00140     // of running on graphics cards starting with feature level 10.0.
00141     D3D_FEATURE_LEVEL featureLevels [] =
00142     {
00143         D3D_FEATURE_LEVEL_12_1,
00144         D3D_FEATURE_LEVEL_12_0,
00145         D3D_FEATURE_LEVEL_11_1,
00146         D3D_FEATURE_LEVEL_11_0,
00147         D3D_FEATURE_LEVEL_10_1,
00148         D3D_FEATURE_LEVEL_10_0
00149     };
00150
00151     // Create the Direct3D 11 API device object and a corresponding context.
00152     ComPtr<ID3D11Device> device;
00153     ComPtr<ID3D11DeviceContext> context;
00154
00155     const D3D_DRIVER_TYPE driverType = m_dxgiAdapter == nullptr ? D3D_DRIVER_TYPE_HARDWARE : D3D_DRIVER_TYPE_UNKNOWN;
00156     const HRESULT hr = D3D11CreateDevice(
00157         m_dxgiAdapter.Get(),        // Either nullptr, or the primary adapter determined by Windows Holographic.
00158         driverType,                 // Create a device using the hardware graphics driver.
00159         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00160         creationFlags,              // Set debug and Direct2D compatibility flags.
00161         featureLevels,              // List of feature levels this app can support.
00162         ARRAYSIZE(featureLevels),   // Size of the list above.
00163         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00164         &device,                    // Returns the Direct3D device created.
00165         &m_d3dFeatureLevel,         // Returns feature level of device created.
00166         &context                    // Returns the device immediate context.
00167         );
00168
00169     if (FAILED(hr))
00170     {
00171         // If the initialization fails, fall back to the WARP device.
00172         // For more information on WARP, see:
00173         // http://go.microsoft.com/fwlink/?LinkId=286690
00174         DX::ThrowIfFailed(
00175             D3D11CreateDevice(
00176                 nullptr,              // Use the default DXGI adapter for WARP.
00177                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00178                 0,
00179                 creationFlags,
00180                 featureLevels,
00181                 ARRAYSIZE(featureLevels),
00182                 D3D11_SDK_VERSION,
00183                 &device,
00184                 &m_d3dFeatureLevel,
00185                 &context
00186                 )
00187             );
00188     }
00189
00190     // Store pointers to the Direct3D device and immediate context.
00191     DX::ThrowIfFailed(
00192         device.As(&m_d3dDevice)
00193         );
00194
00195     DX::ThrowIfFailed(
00196         context.As(&m_d3dContext)
00197         );
00198
00199     // Acquire the DXGI interface for the Direct3D device.
00200     ComPtr<IDXGIDevice3> dxgiDevice;
00201     DX::ThrowIfFailed(
00202         m_d3dDevice.As(&dxgiDevice)
00203         );
00204
00205     // Wrap the native device using a WinRT interop object.
00206     m_d3dInteropDevice = CreateDirect3DDevice(dxgiDevice.Get());
00207
00208     // Cache the DXGI adapter.
00209     // This is for the case of no preferred DXGI adapter, or fallback to WARP.
00210     ComPtr<IDXGIAdapter> dxgiAdapter;
00211     DX::ThrowIfFailed(
00212         dxgiDevice->GetAdapter(&dxgiAdapter)
00213         );
00214     DX::ThrowIfFailed(
00215         dxgiAdapter.As(&m_dxgiAdapter)
00216         );
00217
00218     // Check for device support for the optional feature that allows setting the render target array index from the vertex shader stage.
00219     D3D11_FEATURE_DATA_D3D11_OPTIONS3 options;
00220     m_d3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS3, &options, sizeof(options));
00221     if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer)
00222     {
00223         m_supportsVprt = true;
00224     }
00225 }
00226
00227 // Validates the back buffer for each HolographicCamera and recreates
00228 // resources for back buffers that have changed.
00229 // Locks the set of holographic camera resources until the function exits.
00230 void DX::DeviceResources::EnsureCameraResources(
00231     HolographicFrame^ frame,
00232     HolographicFramePrediction^ prediction)
00233 {
00234     UseHolographicCameraResources<void>([this, frame, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00235     {
00236         for (HolographicCameraPose^ pose : prediction->CameraPoses)
00237         {
00238             HolographicCameraRenderingParameters^ renderingParameters = frame->GetRenderingParameters(pose);
00239             CameraResources* pCameraResources = cameraResourceMap[pose->HolographicCamera->Id].get();
00240
00241             pCameraResources->CreateResourcesForBackBuffer(this, renderingParameters);
00242         }
00243     });
00244 }
00245
00246 // Prepares to allocate resources and adds resource views for a camera.
00247 // Locks the set of holographic camera resources until the function exits.
00248 void DX::DeviceResources::AddHolographicCamera(HolographicCamera^ camera)
00249 {
00250     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00251     {
00252         cameraResourceMap[camera->Id] = std::make_unique<CameraResources>(camera);
00253     });
00254 }
00255
00256 // Deallocates resources for a camera and removes the camera from the set.
00257 // Locks the set of holographic camera resources until the function exits.
00258 void DX::DeviceResources::RemoveHolographicCamera(HolographicCamera^ camera)
00259 {
00260     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00261     {
00262         CameraResources* pCameraResources = cameraResourceMap[camera->Id].get();
00263
00264         if (pCameraResources != nullptr)
00265         {
00266             pCameraResources->ReleaseResourcesForBackBuffer(this);
00267             cameraResourceMap.erase(camera->Id);
00268         }
00269     });
00270 }
00271
00272 // Recreate all device resources and set them back to the current state.
00273 // Locks the set of holographic camera resources until the function exits.
00274 void DX::DeviceResources::HandleDeviceLost()
00275 {
00276     if (m_deviceNotify != nullptr)
00277     {
00278         m_deviceNotify->OnDeviceLost();
00279     }
00280
00281     UseHolographicCameraResources<void>([this](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00282     {
00283         for (auto& pair : cameraResourceMap)
00284         {
00285             CameraResources* pCameraResources = pair.second.get();
00286             pCameraResources->ReleaseResourcesForBackBuffer(this);
00287         }
00288     });
00289
00290     InitializeUsingHolographicSpace();
00291
00292     if (m_deviceNotify != nullptr)
00293     {
00294         m_deviceNotify->OnDeviceRestored();
00295     }
00296 }
00297
00298 // Register our DeviceNotify to be informed on device lost and creation.
00299 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00300 {
00301     m_deviceNotify = deviceNotify;
00302 }
00303
00304 // Call this method when the app suspends. It provides a hint to the driver that the app
00305 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00306 void DX::DeviceResources::Trim()
00307 {
00308     m_d3dContext->ClearState();
00309
00310     ComPtr<IDXGIDevice3> dxgiDevice;
00311     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00312     dxgiDevice->Trim();
00313 }
00314
00315 // Present the contents of the swap chain to the screen.
00316 // Locks the set of holographic camera resources until the function exits.
00317 void DX::DeviceResources::Present(HolographicFrame^ frame)
00318 {
00319     // By default, this API waits for the frame to finish before it returns.
00320     // Holographic apps should wait for the previous frame to finish before
00321     // starting work on a new frame. This allows for better results from
00322     // holographic frame predictions.
00323     HolographicFramePresentResult presentResult = frame->PresentUsingCurrentPrediction();
00324
00325     // The PresentUsingCurrentPrediction API will detect when the graphics device
00326     // changes or becomes invalid. When this happens, it is considered a Direct3D
00327     // device lost scenario.
00328     if (presentResult == HolographicFramePresentResult::DeviceRemoved)
00329     {
00330         // The Direct3D device, context, and resources should be recreated.
00331         HandleDeviceLost();
00332     }
00333 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cs/Scenario2_ShakeEvents.xaml.cs Source File

  • Accelerometer
  • cs

Scenario2_ShakeEvents.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Devices.Sensors;
00014 using Windows.UI.Core;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario2_ShakeEvents : Page
00022     {
00023         private Accelerometer _accelerometer;
00024         private ushort _shakeCount = 0;
00025
00026         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00027         // as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         public Scenario2_ShakeEvents()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         protected override void OnNavigatedTo(NavigationEventArgs e)
00036         {
00037             _accelerometer = Accelerometer.GetDefault(rootPage.AccelerometerReadingType);
00038             if (_accelerometer != null)
00039             {
00040                 rootPage.NotifyUser(rootPage.AccelerometerReadingType + " accelerometer ready", NotifyType.StatusMessage);
00041                 ScenarioEnableButton.IsEnabled = true;
00042             }
00043             else
00044             {
00045                 rootPage.NotifyUser(rootPage.AccelerometerReadingType + " accelerometer not found", NotifyType.ErrorMessage);
00046             }
00047         }
00048
00049         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00050         {
00051             if (ScenarioDisableButton.IsEnabled)
00052             {
00053                 ScenarioDisable();
00054             }
00055         }
00056
00057         /// <summary>
00058         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00059         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00060         /// </summary>
00061         /// <param name="sender"></param>
00062         /// <param name="e">
00063         /// Event data that can be examined for the current visibility state.
00064         /// </param>
00065         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00066         {
00067             if (ScenarioDisableButton.IsEnabled)
00068             {
00069                 if (e.Visible)
00070                 {
00071                     // Re-enable sensor input
00072                     _accelerometer.Shaken += Shaken;
00073                 }
00074                 else
00075                 {
00076                     // Disable sensor input
00077                     _accelerometer.Shaken -= Shaken;
00078                 }
00079             }
00080         }
00081
00082         /// <summary>
00083         /// This is the event handler for Shaken events.
00084         /// </summary>
00085         /// <param name="sender"></param>
00086         /// <param name="e"></param>
00087         async private void Shaken(object sender, AccelerometerShakenEventArgs e)
00088         {
00089             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00090             {
00091                 _shakeCount++;
00092                 ScenarioOutputText.Text = _shakeCount.ToString();
00093             });
00094         }
00095
00096         /// <summary>
00097         /// This is the click handler for the 'Enable' button.
00098         /// </summary>
00099         private void ScenarioEnable()
00100         {
00101             Window.Current.VisibilityChanged += VisibilityChanged;
00102             _accelerometer.Shaken += Shaken;
00103             ScenarioEnableButton.IsEnabled = false;
00104             ScenarioDisableButton.IsEnabled = true;
00105         }
00106
00107         /// <summary>
00108         /// This is the click handler for the 'Disable' button.
00109         /// </summary>
00110         private void ScenarioDisable()
00111         {
00112             Window.Current.VisibilityChanged -= VisibilityChanged;
00113             _accelerometer.Shaken -= Shaken;
00114             ScenarioEnableButton.IsEnabled = true;
00115             ScenarioDisableButton.IsEnabled = false;
00116         }
00117     }
00118 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GpuCoordinateMapper Member List

This is the complete list of members for GpuCoordinateMapper, including all inherited members.
CreateDeviceDependentResources() | GpuCoordinateMapper |
GpuCoordinateMapper(const std::shared_ptr< DX::DeviceResources > &deviceResources) | GpuCoordinateMapper |
m_deviceResources | GpuCoordinateMapper | [private]
m_rasterizeDepthMeshConstants | GpuCoordinateMapper | [private]
m_rasterizeDepthMeshInputLayout | GpuCoordinateMapper | [private]
m_rasterizeDepthMeshPixelShader | GpuCoordinateMapper | [private]
m_rasterizeDepthMeshVertexShader | GpuCoordinateMapper | [private]
m_samplerState | GpuCoordinateMapper | [private]
m_vertexBuffer | GpuCoordinateMapper | [private]
m_vertexCount | GpuCoordinateMapper | [private]
m_visualizeDepthMeshConstants | GpuCoordinateMapper | [private]
m_visualizeDepthMeshInputLayout | GpuCoordinateMapper | [private]
m_visualizeDepthMeshPixelShader | GpuCoordinateMapper | [private]
m_visualizeDepthMeshVertexShader | GpuCoordinateMapper | [private]
ReleaseDeviceDependentResources() | GpuCoordinateMapper |
RunCoordinateMapping(const RasterizedFrameBlob &frameBlob) | GpuCoordinateMapper |
VisualizeCoordinateMapping(const RasterizedFrameBlob &rasterizedFrameBlob, const VisualizeFrameBlob &visualizeFrameBlob) | GpuCoordinateMapper |
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/Common/CameraResources.cs Source File

  • 360VideoPlayback
  • cs
  • Common

CameraResources.cs

Go to the documentation of this file.
00001 ﻿using SharpDX.Direct3D11;
00002 using SharpDX.Mathematics.Interop;
00003 using System;
00004 using System.Numerics;
00005 using System.Runtime.InteropServices;
00006 using Windows.Foundation;
00007 using Windows.Graphics.DirectX.Direct3D11;
00008 using Windows.Graphics.Holographic;
00009 using Windows.Perception.Spatial;
00010
00011 namespace _360VideoPlayback.Common
00012 {
00013     /// <summary>
00014     /// Constant buffer used to send hologram position transform to the shader pipeline.
00015     /// </summary>
00016     internal struct ViewProjectionConstantBuffer
00017     {
00018         public Matrix4x4 viewProjectionLeft;
00019         public Matrix4x4 viewProjectionRight;
00020     }
00021
00022     // Manages DirectX device resources that are specific to a holographic camera, such as the
00023     // back buffer, ViewProjection constant buffer, and viewport.
00024     class CameraResources : Disposer
00025     {
00026         // Direct3D rendering objects. Required for 3D.
00027         RenderTargetView d3dRenderTargetView;
00028         DepthStencilView d3dDepthStencilView;
00029         Texture2D d3dBackBuffer;
00030
00031         // Device resource to store view and projection matrices.
00032         SharpDX.Direct3D11.Buffer viewProjectionConstantBuffer;
00033
00034         // Direct3D rendering properties.
00035         SharpDX.DXGI.Format dxgiFormat;
00036         RawViewportF d3dViewport;
00037         Size d3dRenderTargetSize;
00038
00039         // Indicates whether the camera supports stereoscopic rendering.
00040         bool isStereo = false;
00041
00042         // Indicates whether this camera has a pending frame.
00043         bool framePending = false;
00044
00045         // Pointer to the holographic camera these resources are for.
00046         HolographicCamera holographicCamera = null;
00047
00048         public CameraResources(HolographicCamera holographicCamera)
00049         {
00050             this.holographicCamera = holographicCamera;
00051             isStereo = holographicCamera.IsStereo;
00052             d3dRenderTargetSize = holographicCamera.RenderTargetSize;
00053
00054             d3dViewport.Height = (float)d3dRenderTargetSize.Height;
00055             d3dViewport.Width = (float)d3dRenderTargetSize.Width;
00056             d3dViewport.X = 0;
00057             d3dViewport.Y = 0;
00058             d3dViewport.MinDepth = 0;
00059             d3dViewport.MaxDepth = 1;
00060         }
00061
00062         /// <summary>
00063         /// Updates resources associated with a holographic camera's swap chain.
00064         /// The app does not access the swap chain directly, but it does create
00065         /// resource views for the back buffer.
00066         /// </summary>
00067         public void CreateResourcesForBackBuffer(
00068             DeviceResources deviceResources,
00069             HolographicCameraRenderingParameters cameraParameters
00070             )
00071         {
00072             var device = deviceResources.D3DDevice;
00073
00074             // Get the WinRT object representing the holographic camera's back buffer.
00075             IDirect3DSurface surface = cameraParameters.Direct3D11BackBuffer;
00076
00077             // Get a DXGI interface for the holographic camera's back buffer.
00078             // Holographic cameras do not provide the DXGI swap chain, which is owned
00079             // by the system. The Direct3D back buffer resource is provided using WinRT
00080             // interop APIs.
00081             InteropStatics.IDirect3DDxgiInterfaceAccess surfaceDxgiInterfaceAccess = surface as InteropStatics.IDirect3DDxgiInterfaceAccess;
00082             IntPtr pResource = surfaceDxgiInterfaceAccess.GetInterface(InteropStatics.ID3D11Resource);
00083             SharpDX.Direct3D11.Resource resource = SharpDX.Direct3D11.Resource.FromPointer<SharpDX.Direct3D11.Resource>(pResource);
00084             Marshal.Release(pResource);
00085
00086             // Get a Direct3D interface for the holographic camera's back buffer.
00087             Texture2D cameraBackBuffer = resource.QueryInterface<Texture2D>();
00088
00089             // Determine if the back buffer has changed. If so, ensure that the render target view
00090             // is for the current back buffer.
00091             if ((null == d3dBackBuffer) || (d3dBackBuffer.NativePointer != cameraBackBuffer.NativePointer))
00092             {
00093                 // This can change every frame as the system moves to the next buffer in the
00094                 // swap chain. This mode of operation will occur when certain rendering modes
00095                 // are activated.
00096                 d3dBackBuffer = cameraBackBuffer;
00097
00098                 // Create a render target view of the back buffer.
00099                 // Creating this resource is inexpensive, and is better than keeping track of
00100                 // the back buffers in order to pre-allocate render target views for each one.
00101                 d3dRenderTargetView = this.ToDispose(new RenderTargetView(device, BackBufferTexture2D));
00102
00103                 // Get the DXGI format for the back buffer.
00104                 // This information can be accessed by the app using CameraResources::GetBackBufferDXGIFormat().
00105                 Texture2DDescription backBufferDesc = BackBufferTexture2D.Description;
00106                 dxgiFormat = backBufferDesc.Format;
00107
00108                 // Check for render target size changes.
00109                 Size currentSize = holographicCamera.RenderTargetSize;
00110                 if (d3dRenderTargetSize != currentSize)
00111                 {
00112                     // Set render target size.
00113                     d3dRenderTargetSize = HolographicCamera.RenderTargetSize;
00114
00115                     // A new depth stencil view is also needed.
00116                     this.RemoveAndDispose(ref d3dDepthStencilView);
00117                 }
00118             }
00119
00120             // Refresh depth stencil resources, if needed.
00121             if (null == DepthStencilView)
00122             {
00123                 // Create a depth stencil view for use with 3D rendering if needed.
00124                 var depthStencilDesc = new Texture2DDescription
00125                 {
00126                     Format = SharpDX.DXGI.Format.D16_UNorm,
00127                     Width = (int)RenderTargetSize.Width,
00128                     Height = (int)RenderTargetSize.Height,
00129                     ArraySize = IsRenderingStereoscopic ? 2 : 1, // Create two textures when rendering in stereo.
00130                     MipLevels = 1, // Use a single mipmap level.
00131                     BindFlags = BindFlags.DepthStencil,
00132                     SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0)
00133                 };
00134
00135                 using (var depthStencil = new Texture2D(device, depthStencilDesc))
00136                 {
00137                     var depthStencilViewDesc = new DepthStencilViewDescription();
00138                     depthStencilViewDesc.Dimension = IsRenderingStereoscopic ? DepthStencilViewDimension.Texture2DArray : DepthStencilViewDimension.Texture2D;
00139                     depthStencilViewDesc.Texture2DArray.ArraySize = IsRenderingStereoscopic ? 2 : 0;
00140                     d3dDepthStencilView = this.ToDispose(new DepthStencilView(device, depthStencil, depthStencilViewDesc));
00141                 }
00142             }
00143
00144             // Create the constant buffer, if needed.
00145             if (null == viewProjectionConstantBuffer)
00146             {
00147                 // Create a constant buffer to store view and projection matrices for the camera.
00148                 ViewProjectionConstantBuffer viewProjectionConstantBufferData = new ViewProjectionConstantBuffer();
00149                 viewProjectionConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
00150                     device,
00151                     BindFlags.ConstantBuffer,
00152                     ref viewProjectionConstantBufferData));
00153             }
00154         }
00155
00156         /// <summary>
00157         /// Releases resources associated with a holographic display back buffer.
00158         /// </summary>
00159         public void ReleaseResourcesForBackBuffer(DeviceResources deviceResources)
00160         {
00161             var context = deviceResources.D3DDeviceContext;
00162
00163             this.RemoveAndDispose(ref d3dBackBuffer);
00164             this.RemoveAndDispose(ref d3dRenderTargetView);
00165             this.RemoveAndDispose(ref d3dDepthStencilView);
00166
00167             const int D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT = 8;
00168             RenderTargetView[] nullViews = new RenderTargetView[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT];
00169
00170             // Ensure system references to the back buffer are released by clearing the render
00171             // target from the graphics pipeline state, and then flushing the Direct3D context.
00172             context.OutputMerger.SetRenderTargets(null, nullViews);
00173             context.Flush();
00174         }
00175
00176         public void ReleaseAllDeviceResources(DeviceResources deviceResources)
00177         {
00178             ReleaseResourcesForBackBuffer(deviceResources);
00179             this.RemoveAndDispose(ref viewProjectionConstantBuffer);
00180         }
00181
00182         /// <summary>
00183         /// Updates the constant buffer for the display with view and projection
00184         /// matrices for the current frame.
00185         /// </summary>
00186         public void UpdateViewProjectionBuffer(
00187             DeviceResources deviceResources,
00188             HolographicCameraPose cameraPose,
00189             SpatialCoordinateSystem coordinateSystem
00190             )
00191         {
00192             // The system changes the viewport on a per-frame basis for system optimizations.
00193             d3dViewport.X = (float)cameraPose.Viewport.Left;
00194             d3dViewport.Y = (float)cameraPose.Viewport.Top;
00195             d3dViewport.Width = (float)cameraPose.Viewport.Width;
00196             d3dViewport.Height = (float)cameraPose.Viewport.Height;
00197             d3dViewport.MinDepth = 0;
00198             d3dViewport.MaxDepth = 1;
00199
00200             // The projection transform for each frame is provided by the HolographicCameraPose.
00201             HolographicStereoTransform cameraProjectionTransform = cameraPose.ProjectionTransform;
00202
00203             // Get a container object with the view and projection matrices for the given
00204             // pose in the given coordinate system.
00205             HolographicStereoTransform? viewTransformContainer = cameraPose.TryGetViewTransform(coordinateSystem);
00206
00207             // If TryGetViewTransform returns null, that means the pose and coordinate system
00208             // cannot be understood relative to one another; content cannot be rendered in this
00209             // coordinate system for the duration of the current frame.
00210             // This usually means that positional tracking is not active for the current frame, in
00211             // which case it is possible to use a SpatialLocatorAttachedFrameOfReference to render
00212             // content that is not world-locked instead.
00213             ViewProjectionConstantBuffer viewProjectionConstantBufferData = new ViewProjectionConstantBuffer();
00214             bool viewTransformAcquired = viewTransformContainer.HasValue;
00215             if (viewTransformAcquired)
00216             {
00217                 // Otherwise, the set of view transforms can be retrieved.
00218                 HolographicStereoTransform viewCoordinateSystemTransform = viewTransformContainer.Value;
00219
00220                 // Update the view matrices. Holographic cameras (such as Microsoft HoloLens) are
00221                 // constantly moving relative to the world. The view matrices need to be updated
00222                 // every frame.
00223                 viewProjectionConstantBufferData.viewProjectionLeft = Matrix4x4.Transpose(
00224                     viewCoordinateSystemTransform.Left * cameraProjectionTransform.Left
00225                     );
00226                 viewProjectionConstantBufferData.viewProjectionRight = Matrix4x4.Transpose(
00227                     viewCoordinateSystemTransform.Right * cameraProjectionTransform.Right
00228                     );
00229             }
00230
00231             // Use the D3D device context to update Direct3D device-based resources.
00232             var context = deviceResources.D3DDeviceContext;
00233
00234             // Loading is asynchronous. Resources must be created before they can be updated.
00235             if (context == null || viewProjectionConstantBuffer == null || !viewTransformAcquired)
00236             {
00237                 framePending = false;
00238             }
00239             else
00240             {
00241                 // Update the view and projection matrices.
00242                 context.UpdateSubresource(ref viewProjectionConstantBufferData, viewProjectionConstantBuffer);
00243
00244                 framePending = true;
00245             }
00246         }
00247
00248         /// <summary>
00249         /// Gets the view-projection constant buffer for the display, and attaches it
00250         /// to the shader pipeline.
00251         /// </summary>
00252         public bool AttachViewProjectionBuffer(DeviceResources deviceResources)
00253         {
00254             // This method uses Direct3D device-based resources.
00255             var context = deviceResources.D3DDeviceContext;
00256
00257             // Loading is asynchronous. Resources must be created before they can be updated.
00258             // Cameras can also be added asynchronously, in which case they must be initialized
00259             // before they can be used.
00260             if (context == null || viewProjectionConstantBuffer == null || !framePending)
00261             {
00262                 return false;
00263             }
00264
00265             // Set the viewport for this camera.
00266             context.Rasterizer.SetViewport(Viewport);
00267
00268             // Send the constant buffer to the vertex shader.
00269             context.VertexShader.SetConstantBuffers(1, viewProjectionConstantBuffer);
00270
00271             // The template includes a pass-through geometry shader that is used by
00272             // default on systems that don't support the D3D11_FEATURE_D3D11_OPTIONS3::
00273             // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer extension. The shader
00274             // will be enabled at run-time on systems that require it.
00275             // If your app will also use the geometry shader for other tasks and those
00276             // tasks require the view/projection matrix, uncomment the following line
00277             // of code to send the constant buffer to the geometry shader as well.
00278             //context.GeometryShader.SetConstantBuffers(1, viewProjectionConstantBuffer);
00279
00280             framePending = false;
00281
00282             return true;
00283         }
00284
00285         // Direct3D device resources.
00286         public RenderTargetView BackBufferRenderTargetView => d3dRenderTargetView;
00287         public DepthStencilView DepthStencilView => d3dDepthStencilView;
00288         public Texture2D BackBufferTexture2D => d3dBackBuffer;
00289
00290         // Render target properties.
00291         public RawViewportF Viewport => d3dViewport;
00292         public SharpDX.DXGI.Format BackBufferDxgiFormat => dxgiFormat;
00293         public Size RenderTargetSize => d3dRenderTargetSize;
00294         public bool IsRenderingStereoscopic => isStereo;
00295
00296         // Associated objects.
00297         public HolographicCamera HolographicCamera => holographicCamera;
00298     }
00299 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

final Member List

This is the complete list of members for final, including all inherited members.
CreateDeviceDependentResources(ID3D11Device *device) | final |
CreateDirectXBuffer(ID3D11Device *device, D3D11_BIND_FLAG binding, Windows::Storage::Streams::IBuffer^buffer, ID3D11Buffer **target) | final | [private]
Draw(ID3D11Device *device, ID3D11DeviceContext *context, bool usingVprtShaders, bool isStereo) | final |
GetIsActive() const | final | [inline]
GetLastActiveTime() const | final | [inline]
GetLastUpdateTime() const | final | [inline]
m_colorFadeTimeout | final | [private]
m_colorFadeTimer | final | [private]
m_constantBufferCreated | final | [private]
m_constantBufferData | final | [private]
m_isActive | final | [private]
m_lastActiveTime | final | [private]
m_lastUpdateTime | final | [private]
m_loadingComplete | final | [private]
m_meshProperties | final | [private]
m_meshResourcesMutex | final | [private]
m_modelTransformBuffer | final | [private]
m_pendingSurfaceMesh | final | [private]
m_surfaceMesh | final | [private]
m_triangleIndices | final | [private]
m_updatedMeshProperties | final | [private]
m_updatedTriangleIndices | final | [private]
m_updatedVertexNormals | final | [private]
m_updatedVertexPositions | final | [private]
m_updateReady | final | [private]
m_updateVertexResourcesTask | final | [private]
m_vertexNormals | final | [private]
m_vertexPositions | final | [private]
ReleaseDeviceDependentResources() | final |
ReleaseVertexResources() | final |
SetColorFadeTimer(const float &duration) | final | [inline]
SetIsActive(const bool &isActive) | final | [inline]
SurfaceMesh() | final |
SwapVertexBuffers() | final | [private]
UpdateSurface(Windows::Perception::Spatial::Surfaces::SpatialSurfaceMesh^surface) | final |
UpdateTransform(ID3D11Device *device, ID3D11DeviceContext *context, DX::StepTimer const &timer, Windows::Perception::Spatial::SpatialCoordinateSystem^baseCoordinateSystem) | final |
UpdateVertexResources(ID3D11Device *device) | final |
~SurfaceMesh() | final |
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VertexPositionTexture Member List

This is the complete list of members for VertexPositionTexture, including all inherited members.
pos | VertexPositionTexture |
texture | VertexPositionTexture |
VertexPositionTexture(Vector3 pos, Vector2 texture) | VertexPositionTexture | [inline]
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

App Member List

This is the complete list of members for App, including all inherited members.
App() | App | [inline]
App() | App | [inline]
App() | App | [inline]
App() | App | [inline]
App() | App | [inline]
App() | App | [inline]
App() | App | [inline]
App() | App | [inline]
App() | App | [inline]
App_BackRequested(object sender, BackRequestedEventArgs e) | App | [inline, private]
App_EnteredBackground(object sender, EnteredBackgroundEventArgs e) | App | [inline, private]
App_LeavingBackground(object sender, LeavingBackgroundEventArgs e) | App | [inline, private]
App_Resuming(object sender, object e) | App | [inline, private]
App_Suspending(object sender, SuspendingEventArgs e) | App | [inline, private]
App_UnhandledException(object sender, UnhandledExceptionEventArgs e) | App | [inline, private]
Construct() | App | [private]
Construct() | App | [inline, private]
Construct() | App | [private]
Construct() | App | [inline, private]
Construct() | App | [private]
Construct() | App | [inline, private]
CreateRootFrame(ApplicationExecutionState previousExecutionState, string arguments) | App | [inline, private]
CreateRootFrame() | App | [inline, private]
GetMemoryUsageText() | App | [inline, private]
InitializeMainPage(ApplicationExecutionState previousExecutionState, String arguments) | App | [inline, private]
InitializeRootFrame(Frame frame) | App | [private]
InitializeRootFrame(Frame frame) | App | [inline, private]
isInBackgroundMode | App | [private]
LaunchArgs | App |
LaunchCompleted(LaunchActivatedEventArgs e) | App | [inline, private]
LaunchCompleted(LaunchActivatedEventArgs e) | App | [inline, private]
mainDispatcher | App | [private]
MainDispatcher | App |
MainViewId | App |
mainViewId | App | [private]
MemoryManager_AppMemoryUsageIncreased(object sender, object e) | App | [inline, private]
MemoryManager_AppMemoryUsageLimitChanging(object sender, AppMemoryUsageLimitChangingEventArgs e) | App | [inline, private]
OnActivated(IActivatedEventArgs e) | App | [inline, protected]
OnActivated(IActivatedEventArgs e) | App | [inline, protected]
OnActivated(IActivatedEventArgs args) | App | [inline, protected]
OnActivated(IActivatedEventArgs args) | App | [inline, protected]
OnActivated(IActivatedEventArgs args) | App | [inline, protected]
OnActivated(Windows::ApplicationModel::Activation::IActivatedEventArgs^args) override | App | [protected]
OnActivated(IActivatedEventArgs args) | App | [inline, protected]
OnActivated(IActivatedEventArgs e) | App | [inline, protected]
OnBackgroundActivated(Windows::ApplicationModel::Activation::BackgroundActivatedEventArgs^args) override | App | [protected, virtual]
OnBackgroundActivated(BackgroundActivatedEventArgs args) | App | [inline, protected]
OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs args) | App | [inline, protected]
OnFileActivated(FileActivatedEventArgs e) | App | [inline, protected]
OnFileActivated(Windows::ApplicationModel::Activation::FileActivatedEventArgs^args) override | App |
OnFileActivated(FileActivatedEventArgs args) | App | [inline, protected]
OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs args) | App | [inline, protected]
OnFileSavePickerActivated(FileSavePickerActivatedEventArgs args) | App | [inline, protected]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnShareTargetActivated(ShareTargetActivatedEventArgs args) | App | [inline, protected]
OnSuspending(object sender, SuspendingEventArgs e) | App | [inline, private]
OnSuspending(object sender, SuspendingEventArgs e) | App | [inline, private]
OnSuspending(object sender, SuspendingEventArgs e) | App | [inline, private]
OnSuspending(object sender, SuspendingEventArgs e) | App | [inline, private]
OnSuspending(object sender, SuspendingEventArgs e) | App | [inline, private]
OnSuspending(object sender, SuspendingEventArgs e) | App | [inline, private]
OverrideOnLaunched(LaunchActivatedEventArgs args, ref bool handled) | App | [private]
OverrideOnLaunched(LaunchActivatedEventArgs args, ref bool handled) | App | [inline, private]
Partial_Construct() | App | [private]
Partial_LaunchCompleted(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^e) | App |
ReduceMemoryUsage(ulong limit) | App | [inline]
rootFrameNavigationHelper | App | [private]
SecondaryViews | App |
sessionStateFilename | App | [private]
ShowToast(string msg, string subMsg=null) | App | [inline]
TryFindViewLifetimeControlForViewId(int viewId, out ViewLifetimeControl foundData) | App | [inline, private]
UpdateTitle(String newTitle, int viewId) | App | [inline]
Generated on Fri Nov 15 2024 22:23:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HistoryAndRoaming Member List

This is the complete list of members for HistoryAndRoaming, including all inherited members.
CheckHistoryAndRoaming() | HistoryAndRoaming | [inline, private]
CopyButton_Click(object sender, RoutedEventArgs e) | HistoryAndRoaming | [inline, private]
HistoryAndRoaming() | HistoryAndRoaming | [inline]
OnHistoryEnabledChanged(object sender, object e) | HistoryAndRoaming | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | HistoryAndRoaming | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | HistoryAndRoaming | [inline, protected]
OnRoamingEnabledChanged(object sender, object e) | HistoryAndRoaming | [inline, private]
rootPage | HistoryAndRoaming | [private]
SelectVisibleElement(UIElement ifTrue, UIElement ifFalse, bool value) | HistoryAndRoaming | [inline, private, static]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlWebView/cs/SampleConfiguration.cs Source File

  • XamlWebView
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Storage;
00016 using Windows.UI.Xaml.Controls;
00017
00018 namespace SDKTemplate
00019 {
00020     public partial class MainPage : Page
00021     {
00022         public const string FEATURE_NAME = "XAML WebView Control";
00023
00024         List<Scenario> scenarios = new List<Scenario>
00025         {
00026             new Scenario() { Title="Navigate to URL", ClassType=typeof(Scenario1_NavToUrl)},
00027             new Scenario() { Title="Navigate to string", ClassType=typeof(Scenario2_NavToString)},
00028             new Scenario() { Title="Invoke script", ClassType=typeof(Scenario3_InvokeScript)},
00029             new Scenario() { Title="Script notify", ClassType=typeof(Scenario4_ScriptNotify)},
00030             new Scenario() { Title="Navigate to package and local state", ClassType=typeof(Scenario5_NavToFiles)},
00031             new Scenario() { Title="Navigate with custom resolver", ClassType=typeof(Scenario6_NavToStream)},
00032             new Scenario() { Title="Share content", ClassType=typeof(Scenario7_Share)},
00033             new Scenario() { Title="Capture bitmap", ClassType=typeof(Scenario8_CaptureBitmap)},
00034             new Scenario() { Title="Full-screen mode", ClassType=typeof(Scenario9_ContainsFullScreenElement)},
00035             new Scenario() { Title="Unviewable content", ClassType=typeof(Scenario10_UnviewableContent) },
00036         };
00037
00038         public static async Task<string> LoadStringFromPackageFileAsync(string name)
00039         {
00040             // Using the storage classes to read the content from a file as a string.
00041             StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///html/{name}"));
00042             return await FileIO.ReadTextAsync(f);
00043         }
00044 }
00045
00046     public class Scenario
00047     {
00048         public string Title { get; set; }
00049         public Type ClassType { get; set; }
00050     }
00051 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

NfcUtils Member List

This is the complete list of members for NfcUtils, including all inherited members.
BgTask_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args) | NfcUtils | [inline, private, static]
BgTask_Progress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args) | NfcUtils | [inline, private, static]
CheckHceSupport() | NfcUtils | [inline, static]
DoBackgroundRequestAccess() | NfcUtils | [inline, private, static]
GetAidGroupById(Guid id) | NfcUtils | [inline, static]
GetOrRegisterHceBackgroundTask(string bgTaskName, string taskEntryPoint, SmartCardTriggerType triggerType) | NfcUtils | [inline, static]
HexStringToBytes(string hexString) | NfcUtils | [inline, static]
LaunchNfcPaymentsSettingsPage() | NfcUtils | [inline, static]
LaunchNfcProximitySettingsPage() | NfcUtils | [inline, static]
LogMessage(string message, NotifyType type=NotifyType.StatusMessage) | NfcUtils | [inline, static]
RegisterAidGroup(string displayName, IList< IBuffer > appletIds, SmartCardEmulationCategory?emulationCategory, SmartCardEmulationType emulationType, bool automaticEnablement) | NfcUtils | [inline, static]
SetCardActivationPolicy(SmartCardAppletIdGroupRegistration reg, SmartCardAppletIdGroupActivationPolicy policy) | NfcUtils | [inline, static]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Syndication/cpp/pch.h Source File

  • Syndication
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020
00021 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AudioCategory/cs/AudioCategory/Scenario9.xaml.cs Source File

  • AudioCategory
  • cs
  • AudioCategory

Scenario9.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016 using Windows.UI.Xaml.Media;
00017
00018 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00019
00020 namespace PlaybackManager
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class Scenario9 : Page
00026     {
00027         public Scenario9()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         private void Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00033         {
00034             Playback.SetAudioCategory(AudioCategory.GameMedia);
00035             Playback.SelectFile();
00036         }
00037     }
00038 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AudioCreation/cs/AudioCreation/Scenario1_FilePlayback.xaml.cs Source File

  • AudioCreation
  • cs
  • AudioCreation

Scenario1_FilePlayback.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Threading.Tasks;
00015 using Windows.Media.Audio;
00016 using Windows.Media.Render;
00017 using Windows.Storage;
00018 using Windows.Storage.Pickers;
00019 using Windows.UI;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Controls.Primitives;
00023 using Windows.UI.Xaml.Media;
00024 using Windows.UI.Xaml.Navigation;
00025
00026 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00027
00028 namespace AudioCreation
00029 {
00030     /// <summary>
00031     /// Using the AudioGraph API to playback from a file input.
00032     /// </summary>
00033     public sealed partial class Scenario1_FilePlayback : Page
00034     {
00035         private MainPage rootPage;
00036
00037         private AudioGraph graph;
00038         private AudioFileInputNode fileInput;
00039         private AudioDeviceOutputNode deviceOutput;
00040
00041         public Scenario1_FilePlayback()
00042         {
00043             this.InitializeComponent();
00044         }
00045
00046         protected override async void OnNavigatedTo(NavigationEventArgs e)
00047         {
00048             rootPage = MainPage.Current;
00049             await CreateAudioGraph();
00050         }
00051
00052         protected override void OnNavigatedFrom(NavigationEventArgs e)
00053         {
00054             // Destroy the graph if the page is naviated away from
00055             if (graph != null)
00056             {
00057                 graph.Dispose();
00058             }
00059         }
00060
00061         private async void File_Click(object sender, RoutedEventArgs e)
00062         {
00063             // Clear any old messages.
00064             rootPage.NotifyUser("", NotifyType.StatusMessage);
00065
00066             // If another file is already loaded into the FileInput node
00067             if (fileInput != null)
00068             {
00069                 // Release the file and dispose the contents of the node
00070                 fileInput.Dispose();
00071                 // Stop playback since a new file is being loaded. Also reset the button UI
00072                 if (graphButton.Content.Equals("Stop Graph"))
00073                 {
00074                     TogglePlay();
00075                 }
00076             }
00077
00078             FileOpenPicker filePicker = new FileOpenPicker();
00079             filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
00080             filePicker.FileTypeFilter.Add(".mp3");
00081             filePicker.FileTypeFilter.Add(".wav");
00082             filePicker.FileTypeFilter.Add(".wma");
00083             filePicker.FileTypeFilter.Add(".m4a");
00084             filePicker.ViewMode = PickerViewMode.Thumbnail;
00085             StorageFile file = await filePicker.PickSingleFileAsync();
00086
00087             // File can be null if cancel is hit in the file picker
00088             if(file == null)
00089             {
00090                 return;
00091             }
00092
00093             CreateAudioFileInputNodeResult fileInputResult = await graph.CreateFileInputNodeAsync(file);
00094             if (AudioFileNodeCreationStatus.Success != fileInputResult.Status)
00095             {
00096                 // Cannot read input file
00097                 rootPage.NotifyUser(String.Format("Cannot read input file because {0}", fileInputResult.Status.ToString()), NotifyType.ErrorMessage);
00098                 return;
00099             }
00100
00101             fileInput = fileInputResult.FileInputNode;
00102
00103             if (fileInput.Duration <= TimeSpan.FromSeconds(3))
00104             {
00105                 // Imported file is too short
00106                 rootPage.NotifyUser("Please pick an audio file which is longer than 3 seconds", NotifyType.ErrorMessage);
00107                 fileInput.Dispose();
00108                 fileInput = null;
00109                 return;
00110             }
00111
00112             fileInput.AddOutgoingConnection(deviceOutput);
00113             fileButton.Background = new SolidColorBrush(Colors.Green);
00114
00115             // Trim the file: set the start time to 3 seconds from the beginning
00116             // fileInput.EndTime can be used to trim from the end of file
00117             fileInput.StartTime = TimeSpan.FromSeconds(3);
00118
00119             // Enable buttons in UI to start graph, loop and change playback speed factor
00120             graphButton.IsEnabled = true;
00121             loopToggle.IsEnabled = true;
00122             playSpeedSlider.IsEnabled = true;
00123         }
00124
00125         private void Graph_Click(object sender, RoutedEventArgs e)
00126         {
00127             TogglePlay();
00128         }
00129
00130         private void TogglePlay()
00131         {
00132             //Toggle playback
00133             if (graphButton.Content.Equals("Start Graph"))
00134             {
00135                 graph.Start();
00136                 graphButton.Content = "Stop Graph";
00137                 audioPipe.Fill = new SolidColorBrush(Colors.Blue);
00138             }
00139             else
00140             {
00141                 graph.Stop();
00142                 graphButton.Content = "Start Graph";
00143                 audioPipe.Fill = new SolidColorBrush(Color.FromArgb(255, 49, 49, 49));
00144             }
00145         }
00146
00147         private void PlaySpeedSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
00148         {
00149             if (fileInput != null)
00150             {
00151                 fileInput.PlaybackSpeedFactor = playSpeedSlider.Value;
00152             }
00153         }
00154
00155         private void LoopToggle_Toggled(object sender, RoutedEventArgs e)
00156         {
00157             // Set loop count to null for infinite looping
00158             // Set loop count to 0 to stop looping after current iteration
00159             // Set loop count to non-zero value for finite looping
00160             if (loopToggle.IsOn)
00161             {
00162                 // If turning on looping, make sure the file hasn't finished playback yet
00163                 if (fileInput.Position >= fileInput.Duration)
00164                 {
00165                     // If finished playback, seek back to the start time we set
00166                     fileInput.Seek(fileInput.StartTime.Value);
00167                 }
00168                 fileInput.LoopCount = null; // infinite looping
00169             }
00170             else
00171             {
00172                 fileInput.LoopCount = 0; // stop looping
00173             }
00174         }
00175
00176         private async Task CreateAudioGraph()
00177         {
00178             // Create an AudioGraph with default settings
00179             AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media);
00180             CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings);
00181
00182             if (result.Status != AudioGraphCreationStatus.Success)
00183             {
00184                 // Cannot create graph
00185                 rootPage.NotifyUser(String.Format("AudioGraph Creation Error because {0}", result.Status.ToString()), NotifyType.ErrorMessage);
00186                 return;
00187             }
00188
00189             graph = result.Graph;
00190
00191             // Create a device output node
00192             CreateAudioDeviceOutputNodeResult deviceOutputNodeResult = await graph.CreateDeviceOutputNodeAsync();
00193
00194             if (deviceOutputNodeResult.Status != AudioDeviceNodeCreationStatus.Success)
00195             {
00196                 // Cannot create device output node
00197                 rootPage.NotifyUser(String.Format("Device Output unavailable because {0}", deviceOutputNodeResult.Status.ToString()), NotifyType.ErrorMessage);
00198                 speakerContainer.Background = new SolidColorBrush(Colors.Red);
00199                 return;
00200             }
00201
00202             deviceOutput = deviceOutputNodeResult.DeviceOutputNode;
00203             rootPage.NotifyUser("Device Output Node successfully created", NotifyType.StatusMessage);
00204             speakerContainer.Background = new SolidColorBrush(Colors.Green);
00205         }
00206     }
00207 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cs/Scenario5_Stream.xaml.cs Source File

  • FileAccess
  • cs

Scenario5_Stream.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.IO;
00014 using Windows.Storage;
00015 using Windows.Storage.Streams;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// Writing and reading using a stream.
00024     /// </summary>
00025     public sealed partial class Scenario5 : Page
00026     {
00027         MainPage rootPage = MainPage.Current;
00028
00029         public Scenario5()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             rootPage.ValidateFile();
00037         }
00038
00039         private async void WriteToStreamButton_Click(object sender, RoutedEventArgs e)
00040         {
00041             StorageFile file = rootPage.sampleFile;
00042             if (file != null)
00043             {
00044                 try
00045                 {
00046                     string userContent = InputTextBox.Text;
00047                     using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
00048                     {
00049                         IBuffer buffer = MainPage.GetBufferFromString(userContent);
00050                         await transaction.Stream.WriteAsync(buffer);
00051                         transaction.Stream.Size = buffer.Length; // truncate file
00052                         await transaction.CommitAsync();
00053                         rootPage.NotifyUser($"The following text was written to '{file.Name}' using a stream:\n{userContent}", NotifyType.StatusMessage);
00054                     }
00055                 }
00056                 catch (FileNotFoundException)
00057                 {
00058                     rootPage.NotifyUserFileNotExist();
00059                 }
00060                 catch (Exception ex)
00061                 {
00062                     // I/O errors are reported as exceptions.
00063                     rootPage.NotifyUser(String.Format("Error writing to '{0}': {1}", file.Name, ex.Message), NotifyType.ErrorMessage);
00064                 }
00065             }
00066             else
00067             {
00068                 rootPage.NotifyUserFileNotExist();
00069             }
00070         }
00071
00072         private async void ReadFromStreamButton_Click(object sender, RoutedEventArgs e)
00073         {
00074             StorageFile file = rootPage.sampleFile;
00075             if (file != null)
00076             {
00077                 try
00078                 {
00079                     using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
00080                     {
00081                         UInt64 size64 = readStream.Size;
00082                         if (size64 <= UInt32.MaxValue)
00083                         {
00084                             UInt32 size32 = (UInt32)size64;
00085                             IBuffer buffer = new Windows.Storage.Streams.Buffer(size32);
00086                             buffer = await readStream.ReadAsync(buffer, size32, InputStreamOptions.None);
00087                             string fileContent = MainPage.GetStringFromBuffer(buffer);
00088                             rootPage.NotifyUser($"The following text was read from '{file.Name}' using a stream:\n{fileContent}", NotifyType.StatusMessage);
00089                         }
00090                         else
00091                         {
00092                             rootPage.NotifyUser($"File {file.Name} is too big for ReadAsync to read in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be read by ReadAsync.", NotifyType.ErrorMessage);
00093                         }
00094                     }
00095                 }
00096                 catch (FileNotFoundException)
00097                 {
00098                     rootPage.NotifyUserFileNotExist();
00099                 }
00100                 catch (Exception ex) when (ex.HResult == MainPage.E_NO_UNICODE_TRANSLATION)
00101                 {
00102                     rootPage.NotifyUser("File is not UTF-8 encoded.", NotifyType.ErrorMessage);
00103                 }
00104                 catch (Exception ex)
00105                 {
00106                     // I/O errors are reported as exceptions.
00107                     rootPage.NotifyUser($"Error reading from '{file.Name}': {ex.Message}", NotifyType.ErrorMessage);
00108                 }
00109             }
00110             else
00111             {
00112                 rootPage.NotifyUserFileNotExist();
00113             }
00114         }
00115     }
00116 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cpp/LoggingScenarioEventArgs.h Source File

  • Logging
  • cpp

LoggingScenarioEventArgs.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008 #include "pch.h"
00009 #include <string>
00010
00011 namespace SDKTemplate
00012 {
00013     // LoggingScenario tells the UI what's happening by
00014     // using the following enums.
00015     enum LoggingScenarioEventType
00016     {
00017         BusyStatusChanged,
00018         LogFileGenerated,
00019         LogFileGeneratedAtDisable,
00020         LogFileGeneratedAtSuspend,
00021         LoggingEnabledDisabled
00022     };
00023
00024     ref class LoggingScenarioEventArgs sealed
00025     {
00026     private:
00027
00028         LoggingScenarioEventType _type;
00029         std::wstring _logFileFullPath;
00030         bool _enabled;
00031
00032     internal:
00033
00034         LoggingScenarioEventArgs(LoggingScenarioEventType type)
00035         {
00036             _type = type;
00037         }
00038
00039         LoggingScenarioEventArgs(LoggingScenarioEventType type, const std::wstring& logFileFullPath)
00040         {
00041             _type = type;
00042             _logFileFullPath = logFileFullPath;
00043         }
00044
00045         LoggingScenarioEventArgs(bool enabled)
00046         {
00047             _type = LoggingEnabledDisabled;
00048             _enabled = enabled;
00049         }
00050
00051         property LoggingScenarioEventType Type
00052         {
00053             LoggingScenarioEventType get()
00054             {
00055                 return _type;
00056             }
00057         }
00058
00059         property std::wstring LogFileFullPath
00060         {
00061             std::wstring get()
00062             {
00063                 return _logFileFullPath;
00064             }
00065         }
00066
00067         property bool Enabled
00068         {
00069             bool get()
00070             {
00071                 return _enabled;
00072             }
00073         }
00074     };
00075
00076     delegate void StatusChangedHandler(Platform::Object^ sender, LoggingScenarioEventArgs^ args);
00077 }
Generated on Fri Nov 15 2024 22:20:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/Content/Button.h Source File

  • HolographicMixedRealityCapture
  • cpp
  • Content

Button.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "ControlBase.h"
00004
00005 namespace HolographicMRCSample
00006 {
00007     // This sample renderer instantiates a basic rendering pipeline.
00008     class Button : public ControlBase
00009     {
00010     public:
00011         Button(const Windows::Foundation::Numerics::float3 size,
00012                const Windows::Foundation::Numerics::float4 color,
00013                const Windows::Foundation::Numerics::float4 focusColor,
00014                const Windows::Foundation::Numerics::float4 turnedOnColor,
00015                const DX::TextureIndex textureId);
00016
00017         void SetSwitch(const bool isOn) { m_turnedOn = isOn; }
00018         bool GetSwitch()                { return m_turnedOn; }
00019
00020     protected:
00021         virtual void DoCreateDeviceDependentResources();
00022         virtual void DoReleaseDeviceDependentResources();
00023
00024         virtual void DoUpdate(
00025             const DX::StepTimer& timer,
00026             HolographicFrame^ holographicFrame,
00027             SpatialCoordinateSystem^ currentCoordinateSystem,
00028             SpatialInteractionSourceState^ interactionSource,
00029             const DirectX::XMMATRIX &parentTransform);
00030         virtual void DoRender();
00031
00032     private:
00033         // Direct3D resources for cube geometry.
00034         Microsoft::WRL::ComPtr<ID3D11InputLayout>           m_inputLayout;
00035         Microsoft::WRL::ComPtr<ID3D11Buffer>                m_vertexBuffer;
00036         Microsoft::WRL::ComPtr<ID3D11Buffer>                m_indexBuffer;
00037         Microsoft::WRL::ComPtr<ID3D11VertexShader>          m_vertexShader;
00038         Microsoft::WRL::ComPtr<ID3D11GeometryShader>        m_geometryShader;
00039         Microsoft::WRL::ComPtr<ID3D11PixelShader>           m_pixelShader;
00040         Microsoft::WRL::ComPtr<ID3D11Buffer>                m_modelConstantBuffer;
00041         Microsoft::WRL::ComPtr<ID3D11SamplerState>          m_samplerState;
00042         Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_textureView;
00043
00044         // System resources for cube geometry.
00045         ModelColorConstantBuffer                            m_modelConstantBufferData;
00046         uint32                                              m_indexCount = 0;
00047
00048         Windows::Foundation::Numerics::float3               m_size;
00049         Windows::Foundation::Numerics::float4               m_color;
00050         Windows::Foundation::Numerics::float4               m_colorFocus;
00051         Windows::Foundation::Numerics::float4               m_colorOn;
00052         DX::TextureIndex                                    m_textureIndex;
00053
00054         bool                                                m_turnedOn = false;
00055
00056         // Variables used with the rendering loop.
00057         bool                                                m_loadingComplete = false;
00058
00059         // If the current D3D Device supports VPRT, we can avoid using a geometry
00060         // shader just to set the render target array index.
00061         bool                                                m_usingVprtShaders = false;
00062     };
00063 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

WASAPIRenderer Member List

This is the complete list of members for WASAPIRenderer, including all inherited members.
ActivateCompleted(IActivateAudioInterfaceAsyncOperation *operation) noexcept | WASAPIRenderer |
AsyncInitializeAudioDevice() noexcept | WASAPIRenderer |
ConfigureDeviceInternal() noexcept | WASAPIRenderer | [private]
ConfigureSource() | WASAPIRenderer | [private]
DeviceState() | DeviceStateSourceT< WASAPIRenderer > | [inline, private]
DeviceStateChanged(Windows::Foundation::TypedEventHandler< IDeviceStateSource, SDKTemplate::DeviceStateChangedEventArgs > const &handler) | DeviceStateSourceT< WASAPIRenderer > | [inline, private]
DeviceStateChanged(event_token token) | DeviceStateSourceT< WASAPIRenderer > | [inline, private]
GetBufferFramesPerPeriod() noexcept | WASAPIRenderer | [private]
GetMFSample(uint32_t framesAvailable) | WASAPIRenderer | [private]
GetToneSample(uint32_t framesAvailable) | WASAPIRenderer | [private]
m_AudioClient | WASAPIRenderer | [private]
m_AudioRenderClient | WASAPIRenderer | [private]
m_BufferFrames | WASAPIRenderer | [private]
m_channelVolume | WASAPIRenderer | [private]
m_ContentStream | WASAPIRenderer | [private]
m_contentType | WASAPIRenderer | [private]
m_DefaultPeriodInFrames | WASAPIRenderer | [private]
m_DeviceIdString | WASAPIRenderer | [private]
m_deviceState | DeviceStateSourceT< WASAPIRenderer > | [private]
m_deviceStateChanged | DeviceStateSourceT< WASAPIRenderer > | [private]
m_Frequency | WASAPIRenderer | [private]
m_FundamentalPeriodInFrames | WASAPIRenderer | [private]
m_hnsBufferDuration | WASAPIRenderer | [private]
m_IsBackground | WASAPIRenderer | [private]
m_IsHWOffload | WASAPIRenderer | [private]
m_IsLowLatency | WASAPIRenderer | [private]
m_IsRawAudio | WASAPIRenderer | [private]
m_lock | WASAPIRenderer | [private]
m_MaxPeriodInFrames | WASAPIRenderer | [private]
m_MFSource | WASAPIRenderer | [private]
m_MinPeriodInFrames | WASAPIRenderer | [private]
m_MixFormat | WASAPIRenderer | [private]
m_SampleReadyAsyncResult | WASAPIRenderer | [private]
m_SampleReadyKey | WASAPIRenderer | [private]
m_ToneSource | WASAPIRenderer | [private]
OnAudioSampleRequested(bool IsSilence=false) | WASAPIRenderer | [private]
OnPausePlayback(IMFAsyncResult *pResult) | WASAPIRenderer | [private]
OnSampleReady(IMFAsyncResult *pResult) | WASAPIRenderer | [private]
OnStartPlayback(IMFAsyncResult *pResult) noexcept | WASAPIRenderer | [private]
OnStopPlayback(IMFAsyncResult *pResult) | WASAPIRenderer | [private]
PausePlaybackAsync() | WASAPIRenderer |
SetAudioClientChannelVolume() | WASAPIRenderer | [private]
SetBackgroundAudio(bool value) | WASAPIRenderer | [inline]
SetBufferDuration(REFERENCE_TIME value) | WASAPIRenderer | [inline]
SetContentStream(Windows::Storage::Streams::IRandomAccessStream const &value) | WASAPIRenderer | [inline]
SetContentType(ContentType value) | WASAPIRenderer | [inline]
SetFrequency(double value) | WASAPIRenderer | [inline]
SetHWOffload(bool value) | WASAPIRenderer | [inline]
SetLowLatency(bool value) | WASAPIRenderer | [inline]
SetRawAudio(bool value) | WASAPIRenderer | [inline]
SetState(enum DeviceState state, HRESULT error=S_OK) | DeviceStateSourceT< WASAPIRenderer > | [inline, private]
SetStateNoNotify(enum DeviceState state) | DeviceStateSourceT< WASAPIRenderer > | [inline, private]
SetVolumeOnSession(double volume) noexcept | WASAPIRenderer |
StartPlayback() noexcept | WASAPIRenderer |
StopPlaybackAsync() noexcept | WASAPIRenderer |
ValidateBufferValue() | WASAPIRenderer | [private]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cs/AdventureWorks/App.xaml.cs Source File

  • CortanaVoiceCommand
  • cs
  • AdventureWorks

App.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel;
00014 using Windows.ApplicationModel.Activation;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018 using AdventureWorks.Common;
00019 using Windows.Media.SpeechRecognition;
00020 using System.Linq;
00021 using Windows.Storage;
00022 using System.Collections.Generic;
00023
00024 namespace AdventureWorks
00025 {
00026     /// <summary>
00027     /// Provides application-specific behavior to supplement the default Application class. Contains initialization of the
00028     /// NavigationService, and handles Activation via methods other than normal user interaction (For example, voice commands/Cortana
00029     /// or URI invoking)
00030     /// </summary>
00031     sealed partial class App : Application
00032     {
00033         /// <summary>
00034         /// Initializes the singleton application object.  This is the first line of authored code
00035         /// executed, and as such is the logical equivalent of main() or WinMain().
00036         /// </summary>
00037         public App()
00038         {
00039             this.InitializeComponent();
00040             this.Suspending += OnSuspending;
00041         }
00042
00043         /// <summary>
00044         /// Navigation service, provides a decoupled way to trigger the UI Frame
00045         /// to transition between views.
00046         /// </summary>
00047         public static NavigationService NavigationService { get; private set; }
00048
00049         private RootFrameNavigationHelper rootFrameNavigationHelper;
00050
00051         /// <summary>
00052         /// Invoked when the application is launched normally by the end user.  Other entry points
00053         /// will be used such as when the application is launched to respond to voice commands, or
00054         /// URI invoked. This also installs the voice commands into cortana.
00055         /// </summary>
00056         /// <param name="e">Details about the launch request and process.</param>
00057         protected async override void OnLaunched(LaunchActivatedEventArgs e)
00058         {
00059             Frame rootFrame = Window.Current.Content as Frame;
00060
00061             // Do not repeat app initialization when the Window already has content,
00062             // just ensure that the window is active
00063             if (rootFrame == null)
00064             {
00065                 // Create a Frame to act as the navigation context and navigate to the first page
00066                 rootFrame = new Frame();
00067                 App.NavigationService = new NavigationService(rootFrame);
00068
00069                 // Use the RootFrameNavigationHelper to respond to keyboard and mouse shortcuts.
00070                 this.rootFrameNavigationHelper = new RootFrameNavigationHelper(rootFrame);
00071
00072                 rootFrame.NavigationFailed += OnNavigationFailed;
00073
00074                 // Place the frame in the current Window
00075                 Window.Current.Content = rootFrame;
00076             }
00077
00078             if (rootFrame.Content == null)
00079             {
00080                 // Determine if we're being activated normally, or with arguments from Cortana.
00081                 if (string.IsNullOrEmpty(e.Arguments))
00082                 {
00083                     // Launching normally.
00084                     rootFrame.Navigate(typeof(View.TripListView), "");
00085                 }
00086                 else
00087                 {
00088                     // Launching with arguments. We assume, for now, that this is likely
00089                     // to be in the form of "destination=<location>" from activation via Cortana.
00090                     rootFrame.Navigate(typeof(View.TripDetails), e.Arguments);
00091                 }
00092             }
00093             // Ensure the current window is active
00094             Window.Current.Activate();
00095
00096             try
00097             {
00098                 // Install the main VCD. Since there's no simple way to test that the VCD has been imported, or that it's your most recent
00099                 // version, it's not unreasonable to do this upon app load.
00100                 StorageFile vcdStorageFile = await Package.Current.InstalledLocation.GetFileAsync(@"AdventureWorksCommands.xml");
00101
00102                 await Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync(vcdStorageFile);
00103
00104                 // Update phrase list.
00105                 ViewModel.ViewModelLocator locator = App.Current.Resources["ViewModelLocator"] as ViewModel.ViewModelLocator;
00106                 if(locator != null)
00107                 {
00108                     await locator.TripViewModel.UpdateDestinationPhraseList();
00109                 }
00110             }
00111             catch (Exception ex)
00112             {
00113                 System.Diagnostics.Debug.WriteLine("Installing Voice Commands Failed: " + ex.ToString());
00114             }
00115         }
00116
00117         /// <summary>
00118         /// Invoked when Navigation to a certain page fails
00119         /// </summary>
00120         /// <param name="sender">The Frame which failed navigation</param>
00121         /// <param name="e">Details about the navigation failure</param>
00122         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00123         {
00124             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00125         }
00126
00127         /// <summary>
00128         /// Invoked when application execution is being suspended.  Application state is saved
00129         /// without knowing whether the application will be terminated or resumed with the contents
00130         /// of memory still intact.
00131         /// </summary>
00132         /// <param name="sender">The source of the suspend request.</param>
00133         /// <param name="e">Details about the suspend request.</param>
00134         private void OnSuspending(object sender, SuspendingEventArgs e)
00135         {
00136             var deferral = e.SuspendingOperation.GetDeferral();
00137             deferral.Complete();
00138         }
00139
00140
00141         /// <summary>
00142         /// OnActivated is the entry point for an application when it is launched via
00143         /// means other normal user interaction. This includes Voice Commands, URI activation,
00144         /// being used as a share target from another app, etc. Here, we're going to handle the
00145         /// Voice Command activation from Cortana.
00146         ///
00147         /// Note: Be aware that an older VCD could still be in place for your application if you
00148         /// modify it and update your app via the store. You should be aware that you could get
00149         /// activations that include commands in older versions of your VCD, and you should try
00150         /// to handle them gracefully.
00151         /// </summary>
00152         /// <param name="args">Details about the activation method, including the activation
00153         /// phrase (for voice commands) and the semantic interpretation, parameters, etc.</param>
00154         protected override void OnActivated(IActivatedEventArgs args)
00155         {
00156             base.OnActivated(args);
00157
00158             Type navigationToPageType;
00159             ViewModel.TripVoiceCommand? navigationCommand = null;
00160
00161             // If the app was launched via a Voice Command, this corresponds to the "show trip to <location>" command.
00162             // Protocol activation occurs when a tile is clicked within Cortana (via the background task)
00163             if (args.Kind == ActivationKind.VoiceCommand)
00164             {
00165                 // The arguments can represent many different activation types. Cast it so we can get the
00166                 // parameters we care about out.
00167                 var commandArgs = args as VoiceCommandActivatedEventArgs;
00168
00169                 Windows.Media.SpeechRecognition.SpeechRecognitionResult speechRecognitionResult = commandArgs.Result;
00170
00171                 // Get the name of the voice command and the text spoken. See AdventureWorksCommands.xml for
00172                 // the <Command> tags this can be filled with.
00173                 string voiceCommandName = speechRecognitionResult.RulePath[0];
00174                 string textSpoken = speechRecognitionResult.Text;
00175
00176                 // The commandMode is either "voice" or "text", and it indictes how the voice command
00177                 // was entered by the user.
00178                 // Apps should respect "text" mode by providing feedback in silent form.
00179                 string commandMode = this.SemanticInterpretation("commandMode", speechRecognitionResult);
00180
00181                 switch (voiceCommandName)
00182                 {
00183                     case "showTripToDestination":
00184                         // Access the value of the {destination} phrase in the voice command
00185                         string destination = this.SemanticInterpretation("destination", speechRecognitionResult);
00186
00187                         // Create a navigation command object to pass to the page. Any object can be passed in,
00188                         // here we're using a simple struct.
00189                         navigationCommand = new ViewModel.TripVoiceCommand(
00190                             voiceCommandName,
00191                             commandMode,
00192                             textSpoken,
00193                             destination);
00194
00195                         // Set the page to navigate to for this voice command.
00196                         navigationToPageType = typeof(View.TripDetails);
00197                         break;
00198                     default:
00199                         // If we can't determine what page to launch, go to the default entry point.
00200                         navigationToPageType = typeof(View.TripListView);
00201                         break;
00202                 }
00203             }
00204             else if (args.Kind == ActivationKind.Protocol)
00205             {
00206                 // Extract the launch context. In this case, we're just using the destination from the phrase set (passed
00207                 // along in the background task inside Cortana), which makes no attempt to be unique. A unique id or
00208                 // identifier is ideal for more complex scenarios. We let the destination page check if the
00209                 // destination trip still exists, and navigate back to the trip list if it doesn't.
00210                 var commandArgs = args as ProtocolActivatedEventArgs;
00211                 Windows.Foundation.WwwFormUrlDecoder decoder = new Windows.Foundation.WwwFormUrlDecoder(commandArgs.Uri.Query);
00212                 var destination = decoder.GetFirstValueByName("LaunchContext");
00213
00214                 navigationCommand = new ViewModel.TripVoiceCommand(
00215                                         "protocolLaunch",
00216                                         "text",
00217                                         "destination",
00218                                         destination);
00219
00220                 navigationToPageType = typeof(View.TripDetails);
00221             }
00222             else
00223             {
00224                 // If we were launched via any other mechanism, fall back to the main page view.
00225                 // Otherwise, we'll hang at a splash screen.
00226                 navigationToPageType = typeof(View.TripListView);
00227             }
00228
00229             // Re"peat the same basic initialization as OnLaunched() above, taking into account whether
00230             // or not the app is already active.
00231             Frame rootFrame = Window.Current.Content as Frame;
00232
00233             // Do not repeat app initialization when the Window already has content,
00234             // just ensure that the window is active
00235             if (rootFrame == null)
00236             {
00237                 // Create a Frame to act as the navigation context and navigate to the first page
00238                 rootFrame = new Frame();
00239                 App.NavigationService = new NavigationService(rootFrame);
00240
00241                 rootFrame.NavigationFailed += OnNavigationFailed;
00242
00243                 // Place the frame in the current Window
00244                 Window.Current.Content = rootFrame;
00245             }
00246
00247             // Since we're expecting to always show a details page, navigate even if
00248             // a content frame is in place (unlike OnLaunched).
00249             // Navigate to either the main trip list page, or if a valid voice command
00250             // was provided, to the details page for that trip.
00251             rootFrame.Navigate(navigationToPageType, navigationCommand);
00252
00253             // Ensure the current window is active
00254             Window.Current.Activate();
00255         }
00256
00257         /// <summary>
00258         /// Returns the semantic interpretation of a speech result. Returns null if there is no interpretation for
00259         /// that key.
00260         /// </summary>
00261         /// <param name="interpretationKey">The interpretation key.</param>
00262         /// <param name="speechRecognitionResult">The result to get an interpretation from.</param>
00263         /// <returns></returns>
00264         private string SemanticInterpretation(string interpretationKey, SpeechRecognitionResult speechRecognitionResult)
00265         {
00266             return speechRecognitionResult.SemanticInterpretation.Properties[interpretationKey].FirstOrDefault();
00267         }
00268     }
00269 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cpp/Scenario6_CustomTrigger.xaml.cpp Source File

  • CustomCapability
  • cpp

Scenario6_CustomTrigger.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario6_CustomTrigger.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::ApplicationModel::Background;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Navigation;
00023
00024 // {C7BDD245-5CDA-4BBD-B68D-B5E36F7911A3}
00025 #define GUID_CUSTOMSYSTEMEVENTTRIGGERID_OSRUSBFX2 L"{C7BDD245-5CDA-4BBD-B68D-B5E36F7911A3}"
00026
00027 static String^ customTriggerTaskName = L"Osrusbfx2Task.ConnectedTask";
00028
00029 CustomTrigger::CustomTrigger()
00030 {
00031     InitializeComponent();
00032     UpdateUI();
00033 }
00034
00035 void CustomTrigger::OnNavigatedFrom(NavigationEventArgs^ e)
00036 {
00037     UnregisterTask();
00038 }
00039
00040 void CustomTrigger::UpdateUI()
00041 {
00042     RegisterCustomTrigger->IsEnabled = (taskRegistration == nullptr);
00043     UnregisterCustomTrigger->IsEnabled = (taskRegistration != nullptr);
00044 }
00045
00046 void CustomTrigger::UnregisterTask()
00047 {
00048     if (taskRegistration != nullptr)
00049     {
00050         taskRegistration->Unregister(true);
00051         taskRegistration = nullptr;
00052     }
00053 }
00054
00055
00056 void CustomTrigger::RegisterCustomTrigger_Click(Object^ sender, RoutedEventArgs^ e)
00057 {
00058     if (IsFx2CustomTriggerTaskRegistered())
00059     {
00060         rootPage->NotifyUser("Osrusbfx2.ConnectedTask background task has already been registered", NotifyType::ErrorMessage);
00061         return;
00062     }
00063
00064     // Create a new background task builder.
00065     BackgroundTaskBuilder^ taskBuilder = ref new BackgroundTaskBuilder();
00066
00067     // Create a new OEM trigger.
00068     CustomSystemEventTrigger^ fx2Trigger = ref new CustomSystemEventTrigger(
00069         GUID_CUSTOMSYSTEMEVENTTRIGGERID_OSRUSBFX2, // Trigger Qualifier
00070         CustomSystemEventTriggerRecurrence::Once); // One-shot trigger
00071
00072     // Associate the fx2Trigger trigger with the background task builder.
00073     taskBuilder->SetTrigger(fx2Trigger);
00074
00075     // Specify the background task to run when the trigger fires.
00076     taskBuilder->TaskEntryPoint = customTriggerTaskName;
00077
00078     // Name the background task.
00079     taskBuilder->Name = customTriggerTaskName;
00080
00081     try
00082     {
00083         // Register the background task.
00084         taskRegistration = taskBuilder->Register();
00085     }
00086     catch (Exception^ ex)
00087     {
00088         rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
00089         return;
00090     }
00091
00092     UpdateUI();
00093 }
00094
00095 bool CustomTrigger::IsFx2CustomTriggerTaskRegistered()
00096 {
00097     for (auto task : BackgroundTaskRegistration::AllTasks)
00098     {
00099         String^ taskName = task->Value->Name;
00100         if (taskName == customTriggerTaskName)
00101         {
00102             return true;
00103         }
00104     }
00105
00106     return false;
00107 }
00108
00109 void CustomTrigger::UnregisterCustomTrigger_Click(Object^ sender, RoutedEventArgs^ e)
00110 {
00111     UnregisterTask();
00112     UpdateUI();
00113 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DataReaderWriter/cpp/Scenario1_WriteReadStream.xaml.h Source File

  • DataReaderWriter
  • cpp

Scenario1_WriteReadStream.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // WriteReadStream.xaml.h
00014 // Declaration of the WriteReadStream class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario1_WriteReadStream.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class WriteReadStream sealed
00030     {
00031     public:
00032         WriteReadStream();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036     private:
00037         MainPage^ rootPage;
00038         void TransferData(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039     };
00040 }
Generated on Fri Nov 15 2024 22:19:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraResolution/cpp/Scenario2_PhotoSettings.xaml.h Source File

  • CameraResolution
  • cpp

Scenario2_PhotoSettings.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_PhotoSettings.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario2_PhotoSettings sealed
00021     {
00022     public:
00023         Scenario2_PhotoSettings();
00024         virtual ~Scenario2_PhotoSettings();
00025
00026     protected:
00027         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00028
00029     private:
00030         MainPage^ _rootPage;
00031         Platform::Agile<Windows::Media::Capture::MediaCapture^> _mediaCapture;
00032         Windows::Foundation::EventRegistrationToken _mediaCaptureFailedEventToken;
00033
00034         bool _isPreviewing;
00035
00036         // Folder in which the captures will be stored
00037         Windows::Storage::StorageFolder^ _captureFolder;
00038
00039         Concurrency::task<void> InitializeCameraAsync();
00040         Concurrency::task<void> CleanupCameraAsync();
00041
00042         void InitializeCameraButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         void PhotoButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044
00045         void PreviewSettings_Changed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046         void PhotoSettings_Changed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047
00048         void CheckIfStreamsAreIdentical();
00049         void PopulateComboBox(Windows::Media::Capture::MediaStreamType streamType, Windows::UI::Xaml::Controls::ComboBox^ comboBox, bool showFrameRate = true);
00050
00051         void MediaCapture_Failed(Windows::Media::Capture::MediaCapture^ sender, Windows::Media::Capture::MediaCaptureFailedEventArgs^ e);
00052     };
00053 }
Generated on Fri Nov 15 2024 22:18:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_NetworkCost Member List

This is the complete list of members for Scenario2_NetworkCost, including all inherited members.
GetNetworkCost_Click(object sender, RoutedEventArgs e) | Scenario2_NetworkCost | [inline, private]
Scenario2_NetworkCost() | Scenario2_NetworkCost | [inline]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Memory Member List

This is the complete list of members for Scenario2_Memory, including all inherited members.
OnNavigatedTo(NavigationEventArgs e) | Scenario2_Memory | [inline, protected]
protectedBuffer | Scenario2_Memory | [private]
ProtectL1_Click(object sender, RoutedEventArgs e) | Scenario2_Memory | [inline, private]
ProtectL2_Click(object sender, RoutedEventArgs e) | Scenario2_Memory | [inline, private]
ReportProtectedBuffer(IBuffer buffer) | Scenario2_Memory | [inline, private]
rootPage | Scenario2_Memory | [private]
Scenario2_Memory() | Scenario2_Memory | [inline]
Unprotect_Click(object sender, RoutedEventArgs e) | Scenario2_Memory | [inline, private]
userDataProtectionManager | Scenario2_Memory | [private]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RequestResponse Member List

This is the complete list of members for RequestResponse, including all inherited members.
OnNavigatedTo(NavigationEventArgs e) | RequestResponse | [inline, protected]
RequestResponse() | RequestResponse | [inline]
rootPage | RequestResponse | [private]
SendButton_Click(object sender, RoutedEventArgs e) | RequestResponse | [inline, private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/SampleConfiguration.cpp Source File

  • MapControl
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace Platform::Collections;
00017 using namespace SDKTemplate;
00018 using namespace Windows::Devices::Geolocation;
00019 using namespace Windows::UI::Xaml::Controls::Maps;
00020
00021 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00022 {
00023     { "MapControl configuration", "SDKTemplate.Scenario1" },
00024     { "Adding MapElements", "SDKTemplate.Scenario2" },
00025     { "Adding MapLayers", "SDKTemplate.Scenario10" },
00026     { "Adding XAML children", "SDKTemplate.Scenario3" },
00027     { "Showing 3D locations", "SDKTemplate.Scenario4" },
00028     { "Showing Streetside experience", "SDKTemplate.Scenario5" },
00029     { "Launching Maps using URI Schemes", "SDKTemplate.Scenario6" },
00030     { "Displaying points with clustering", "SDKTemplate.Scenario7" },
00031     { "Find and download Offline Maps", "SDKTemplate.Scenario8" },
00032     { "Custom map appearance", "SDKTemplate.Scenario9" },
00033     { "Custom map elements appearance", "SDKTemplate.Scenario11" },
00034     { "Animated MapTileSource", "SDKTemplate.Scenario12" },
00035 };
00036
00037 Geopoint^ MainPage::SeattleGeopoint = ref new Geopoint({ 47.604, -122.329 });
00038
00039 Vector<MapElement^>^ MainPage::CreateCityBuildingsCollection()
00040 {
00041     auto icon1 = ref new MapIcon();
00042     icon1->Location = ref new Geopoint({ 47.603830, -122.329900 });
00043     icon1->Title = "Seattle City Hall";
00044
00045     auto icon2 = ref new MapIcon();
00046     icon2->Location = ref new Geopoint({ 47.606709, -122.332672 });
00047     icon2->Title = "Seattle Public Library";
00048
00049     auto icon3 = ref new MapIcon();
00050     icon3->Location = ref new Geopoint({ 47.604100, -122.329204 });
00051     icon3->Title = "Municipal Court of Seattle";
00052
00053     return ref new Vector<MapElement^>({ icon1, icon2, icon3 });
00054 }
00055
00056 Vector<MapElement^>^ MainPage::CreateCityParksCollection()
00057 {
00058     auto icon1 = ref new MapIcon();
00059     icon1->Location = ref new Geopoint({ 47.608313, -122.331218 });
00060     icon1->Title = "Freeway Park";
00061
00062     auto icon2 = ref new MapIcon();
00063     icon2->Location = ref new Geopoint({ 47.602029, -122.333971 });
00064     icon2->Title = "Pioneer Square";
00065
00066     auto icon3 = ref new MapIcon();
00067     icon3->Location = ref new Geopoint({ 47.601990, -122.330681 });
00068     icon3->Title = "City Hall Park";
00069
00070     auto icon4 = ref new MapIcon();
00071     icon4->Location = ref new Geopoint({ 47.600619, -122.324957 });
00072     icon4->Title = "Kobe Terrace Park";
00073
00074     return ref new Vector<MapElement^>({ icon1, icon2, icon3, icon4 });
00075 }
Generated on Fri Nov 15 2024 22:17:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlWebView/cs/Scenario2_NavToString.xaml.cs Source File

  • XamlWebView
  • cs

Scenario2_NavToString.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.Storage;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using System;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     public sealed partial class Scenario2_NavToString : Page
00024     {
00025         public Scenario2_NavToString()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         protected override async void OnNavigatedTo(NavigationEventArgs e)
00031         {
00032             HtmlBox.Text = await MainPage.LoadStringFromPackageFileAsync("html_example.html");
00033         }
00034
00035         private void LoadAsHtml()
00036         {
00037             // Grab the HTML from the text box and load it into the WebView
00038             WebViewControl.NavigateToString(HtmlBox.Text);
00039         }
00040     }
00041 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
Blur(Windows::Graphics::Imaging::SoftwareBitmap^input, Windows::Graphics::Imaging::SoftwareBitmap^output) | sealed |
Contours(Windows::Graphics::Imaging::SoftwareBitmap^input, Windows::Graphics::Imaging::SoftwareBitmap^output) | sealed |
fgMaskMOG2 | sealed | [private]
GetPointerToPixelData(Windows::Graphics::Imaging::SoftwareBitmap^bitmap, unsigned char **pPixelData, unsigned int *capacity) | sealed | [private]
Histogram(Windows::Graphics::Imaging::SoftwareBitmap^input, Windows::Graphics::Imaging::SoftwareBitmap^output) | sealed |
HoughLines(Windows::Graphics::Imaging::SoftwareBitmap^input, Windows::Graphics::Imaging::SoftwareBitmap^output) | sealed |
MotionDetector(Windows::Graphics::Imaging::SoftwareBitmap^input, Windows::Graphics::Imaging::SoftwareBitmap^output) | sealed |
OpenCVHelper() | sealed |
pMOG2 | sealed | [private]
TryConvert(Windows::Graphics::Imaging::SoftwareBitmap^from, cv::Mat &convertedMat) | sealed | [private]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCloudFontIntegration/cpp/Scenario_SampleOverview.xaml.h Source File

  • XamlCloudFontIntegration
  • cpp

Scenario_SampleOverview.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario_SampleOverview.g.h"
00015
00016 namespace SDKTemplate
00017 {
00018     [Windows::Foundation::Metadata::WebHostHidden]
00019     public ref class Scenario_SampleOverview sealed
00020     {
00021     public:
00022         Scenario_SampleOverview();
00023     };
00024 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/Common/DDSTextureLoader.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • Common

DDSTextureLoader.cpp

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.cpp
00003 //
00004 // Functions for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note these functions are useful as a light-weight runtime loader for DDS files. For
00007 // a full-featured DDS file reader, writer, and texture processing pipeline see
00008 // the 'Texconv' sample and the 'DirectXTex' library.
00009 //
00010 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00011 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00012 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00013 // PARTICULAR PURPOSE.
00014 //
00015 // Copyright (c) Microsoft Corporation. All rights reserved.
00016 //
00017 // http://go.microsoft.com/fwlink/?LinkId=248926
00018 // http://go.microsoft.com/fwlink/?LinkId=248929
00019 //--------------------------------------------------------------------------------------
00020
00021 #include "pch.h"
00022 #include <dxgiformat.h>
00023 #include <assert.h>
00024 #include <memory>
00025 #include <algorithm>
00026 #include "DDSTextureLoader.h"
00027 #include "DirectXSample.h"
00028
00029 //--------------------------------------------------------------------------------------
00030 // Macros
00031 //--------------------------------------------------------------------------------------
00032 #ifndef MAKEFOURCC
00033 #define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
00034                 ((uint32_t)(byte)(ch0) | ((uint32_t)(byte)(ch1) << 8) |       \
00035                 ((uint32_t)(byte)(ch2) << 16) | ((uint32_t)(byte)(ch3) << 24))
00036 #endif /* defined(MAKEFOURCC) */
00037
00038 //--------------------------------------------------------------------------------------
00039 // DDS file structure definitions
00040 //
00041 // See DDS.h in the 'Texconv' sample and the 'DirectXTex' library
00042 //--------------------------------------------------------------------------------------
00043 #pragma pack(push, 1)
00044
00045 #define DDS_MAGIC 0x20534444 // "DDS "
00046
00047 struct DDS_PIXELFORMAT
00048 {
00049     uint32_t  size;
00050     uint32_t  flags;
00051     uint32_t  fourCC;
00052     uint32_t  RGBBitCount;
00053     uint32_t  RBitMask;
00054     uint32_t  GBitMask;
00055     uint32_t  BBitMask;
00056     uint32_t  ABitMask;
00057 };
00058
00059 #define DDS_FOURCC      0x00000004  // DDPF_FOURCC
00060 #define DDS_RGB         0x00000040  // DDPF_RGB
00061 #define DDS_RGBA        0x00000041  // DDPF_RGB | DDPF_ALPHAPIXELS
00062 #define DDS_LUMINANCE   0x00020000  // DDPF_LUMINANCE
00063 #define DDS_LUMINANCEA  0x00020001  // DDPF_LUMINANCE | DDPF_ALPHAPIXELS
00064 #define DDS_ALPHA       0x00000002  // DDPF_ALPHA
00065 #define DDS_PAL8        0x00000020  // DDPF_PALETTEINDEXED8
00066
00067 #define DDS_HEADER_FLAGS_TEXTURE        0x00001007  // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
00068 #define DDS_HEADER_FLAGS_MIPMAP         0x00020000  // DDSD_MIPMAPCOUNT
00069 #define DDS_HEADER_FLAGS_VOLUME         0x00800000  // DDSD_DEPTH
00070 #define DDS_HEADER_FLAGS_PITCH          0x00000008  // DDSD_PITCH
00071 #define DDS_HEADER_FLAGS_LINEARSIZE     0x00080000  // DDSD_LINEARSIZE
00072
00073 #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT
00074 #define DDS_WIDTH  0x00000004 // DDSD_WIDTH
00075
00076 #define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE
00077 #define DDS_SURFACE_FLAGS_MIPMAP  0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
00078 #define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX
00079
00080 #define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
00081 #define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
00082 #define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
00083 #define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
00084 #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
00085 #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
00086
00087 #define DDS_CUBEMAP_ALLFACES (DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\
00088                               DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\
00089                               DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ)
00090
00091 #define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP
00092
00093 #define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME
00094
00095 enum DDS_MISC_FLAGS2
00096 {
00097     DDS_MISC_FLAGS2_ALPHA_MODE_MASK = 0x7L,
00098 };
00099
00100 enum DDS_ALPHA_MODE
00101 {
00102     DDS_ALPHA_MODE_UNKNOWN = 0,
00103     DDS_ALPHA_MODE_STRAIGHT = 1,
00104     DDS_ALPHA_MODE_PREMULTIPLIED = 2,
00105     DDS_ALPHA_MODE_OPAQUE = 3,
00106     DDS_ALPHA_MODE_CUSTOM = 4,
00107 };
00108
00109 typedef struct
00110 {
00111     uint32_t          size;
00112     uint32_t          flags;
00113     uint32_t          height;
00114     uint32_t          width;
00115     uint32_t          pitchOrLinearSize;
00116     uint32_t          depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags
00117     uint32_t          mipMapCount;
00118     uint32_t          reserved1[11];
00119     DDS_PIXELFORMAT ddspf;
00120     uint32_t          caps;
00121     uint32_t          caps2;
00122     uint32_t          caps3;
00123     uint32_t          caps4;
00124     uint32_t          reserved2;
00125 } DDS_HEADER;
00126
00127 typedef struct
00128 {
00129     DXGI_FORMAT dxgiFormat;
00130     uint32_t      resourceDimension;
00131     uint32_t      miscFlag; // see D3D11_RESOURCE_MISC_FLAG
00132     uint32_t      arraySize;
00133     uint32_t      miscFlags2;
00134 } DDS_HEADER_DXT10;
00135
00136 #pragma pack(pop)
00137
00138 //--------------------------------------------------------------------------------------
00139 // Return the BPP for a particular format
00140 //--------------------------------------------------------------------------------------
00141 static size_t BitsPerPixel(_In_ DXGI_FORMAT fmt)
00142 {
00143     switch (fmt)
00144     {
00145     case DXGI_FORMAT_R32G32B32A32_TYPELESS:
00146     case DXGI_FORMAT_R32G32B32A32_FLOAT:
00147     case DXGI_FORMAT_R32G32B32A32_UINT:
00148     case DXGI_FORMAT_R32G32B32A32_SINT:
00149         return 128;
00150
00151     case DXGI_FORMAT_R32G32B32_TYPELESS:
00152     case DXGI_FORMAT_R32G32B32_FLOAT:
00153     case DXGI_FORMAT_R32G32B32_UINT:
00154     case DXGI_FORMAT_R32G32B32_SINT:
00155         return 96;
00156
00157     case DXGI_FORMAT_R16G16B16A16_TYPELESS:
00158     case DXGI_FORMAT_R16G16B16A16_FLOAT:
00159     case DXGI_FORMAT_R16G16B16A16_UNORM:
00160     case DXGI_FORMAT_R16G16B16A16_UINT:
00161     case DXGI_FORMAT_R16G16B16A16_SNORM:
00162     case DXGI_FORMAT_R16G16B16A16_SINT:
00163     case DXGI_FORMAT_R32G32_TYPELESS:
00164     case DXGI_FORMAT_R32G32_FLOAT:
00165     case DXGI_FORMAT_R32G32_UINT:
00166     case DXGI_FORMAT_R32G32_SINT:
00167     case DXGI_FORMAT_R32G8X24_TYPELESS:
00168     case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
00169     case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
00170     case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
00171         return 64;
00172
00173     case DXGI_FORMAT_R10G10B10A2_TYPELESS:
00174     case DXGI_FORMAT_R10G10B10A2_UNORM:
00175     case DXGI_FORMAT_R10G10B10A2_UINT:
00176     case DXGI_FORMAT_R11G11B10_FLOAT:
00177     case DXGI_FORMAT_R8G8B8A8_TYPELESS:
00178     case DXGI_FORMAT_R8G8B8A8_UNORM:
00179     case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
00180     case DXGI_FORMAT_R8G8B8A8_UINT:
00181     case DXGI_FORMAT_R8G8B8A8_SNORM:
00182     case DXGI_FORMAT_R8G8B8A8_SINT:
00183     case DXGI_FORMAT_R16G16_TYPELESS:
00184     case DXGI_FORMAT_R16G16_FLOAT:
00185     case DXGI_FORMAT_R16G16_UNORM:
00186     case DXGI_FORMAT_R16G16_UINT:
00187     case DXGI_FORMAT_R16G16_SNORM:
00188     case DXGI_FORMAT_R16G16_SINT:
00189     case DXGI_FORMAT_R32_TYPELESS:
00190     case DXGI_FORMAT_D32_FLOAT:
00191     case DXGI_FORMAT_R32_FLOAT:
00192     case DXGI_FORMAT_R32_UINT:
00193     case DXGI_FORMAT_R32_SINT:
00194     case DXGI_FORMAT_R24G8_TYPELESS:
00195     case DXGI_FORMAT_D24_UNORM_S8_UINT:
00196     case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
00197     case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
00198     case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
00199     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00200     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00201     case DXGI_FORMAT_B8G8R8A8_UNORM:
00202     case DXGI_FORMAT_B8G8R8X8_UNORM:
00203     case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
00204     case DXGI_FORMAT_B8G8R8A8_TYPELESS:
00205     case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
00206     case DXGI_FORMAT_B8G8R8X8_TYPELESS:
00207     case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
00208         return 32;
00209
00210     case DXGI_FORMAT_R8G8_TYPELESS:
00211     case DXGI_FORMAT_R8G8_UNORM:
00212     case DXGI_FORMAT_R8G8_UINT:
00213     case DXGI_FORMAT_R8G8_SNORM:
00214     case DXGI_FORMAT_R8G8_SINT:
00215     case DXGI_FORMAT_R16_TYPELESS:
00216     case DXGI_FORMAT_R16_FLOAT:
00217     case DXGI_FORMAT_D16_UNORM:
00218     case DXGI_FORMAT_R16_UNORM:
00219     case DXGI_FORMAT_R16_UINT:
00220     case DXGI_FORMAT_R16_SNORM:
00221     case DXGI_FORMAT_R16_SINT:
00222     case DXGI_FORMAT_B5G6R5_UNORM:
00223     case DXGI_FORMAT_B5G5R5A1_UNORM:
00224     case DXGI_FORMAT_B4G4R4A4_UNORM:
00225         return 16;
00226
00227     case DXGI_FORMAT_R8_TYPELESS:
00228     case DXGI_FORMAT_R8_UNORM:
00229     case DXGI_FORMAT_R8_UINT:
00230     case DXGI_FORMAT_R8_SNORM:
00231     case DXGI_FORMAT_R8_SINT:
00232     case DXGI_FORMAT_A8_UNORM:
00233         return 8;
00234
00235     case DXGI_FORMAT_R1_UNORM:
00236         return 1;
00237
00238     case DXGI_FORMAT_BC1_TYPELESS:
00239     case DXGI_FORMAT_BC1_UNORM:
00240     case DXGI_FORMAT_BC1_UNORM_SRGB:
00241     case DXGI_FORMAT_BC4_TYPELESS:
00242     case DXGI_FORMAT_BC4_UNORM:
00243     case DXGI_FORMAT_BC4_SNORM:
00244         return 4;
00245
00246     case DXGI_FORMAT_BC2_TYPELESS:
00247     case DXGI_FORMAT_BC2_UNORM:
00248     case DXGI_FORMAT_BC2_UNORM_SRGB:
00249     case DXGI_FORMAT_BC3_TYPELESS:
00250     case DXGI_FORMAT_BC3_UNORM:
00251     case DXGI_FORMAT_BC3_UNORM_SRGB:
00252     case DXGI_FORMAT_BC5_TYPELESS:
00253     case DXGI_FORMAT_BC5_UNORM:
00254     case DXGI_FORMAT_BC5_SNORM:
00255     case DXGI_FORMAT_BC6H_TYPELESS:
00256     case DXGI_FORMAT_BC6H_UF16:
00257     case DXGI_FORMAT_BC6H_SF16:
00258     case DXGI_FORMAT_BC7_TYPELESS:
00259     case DXGI_FORMAT_BC7_UNORM:
00260     case DXGI_FORMAT_BC7_UNORM_SRGB:
00261         return 8;
00262
00263     default:
00264         return 0;
00265     }
00266 }
00267
00268
00269 //--------------------------------------------------------------------------------------
00270 // Get surface information for a particular format
00271 //--------------------------------------------------------------------------------------
00272 static void GetSurfaceInfo(
00273     _In_ size_t width,
00274     _In_ size_t height,
00275     _In_ DXGI_FORMAT fmt,
00276     _Out_opt_ size_t* outNumBytes,
00277     _Out_opt_ size_t* outRowBytes,
00278     _Out_opt_ size_t* outNumRows
00279     )
00280 {
00281     size_t numBytes = 0;
00282     size_t rowBytes = 0;
00283     size_t numRows = 0;
00284
00285     bool bc = false;
00286     bool packed = false;
00287     size_t bcnumBytesPerBlock = 0;
00288     switch (fmt)
00289     {
00290     case DXGI_FORMAT_BC1_TYPELESS:
00291     case DXGI_FORMAT_BC1_UNORM:
00292     case DXGI_FORMAT_BC1_UNORM_SRGB:
00293     case DXGI_FORMAT_BC4_TYPELESS:
00294     case DXGI_FORMAT_BC4_UNORM:
00295     case DXGI_FORMAT_BC4_SNORM:
00296         bc = true;
00297         bcnumBytesPerBlock = 8;
00298         break;
00299
00300     case DXGI_FORMAT_BC2_TYPELESS:
00301     case DXGI_FORMAT_BC2_UNORM:
00302     case DXGI_FORMAT_BC2_UNORM_SRGB:
00303     case DXGI_FORMAT_BC3_TYPELESS:
00304     case DXGI_FORMAT_BC3_UNORM:
00305     case DXGI_FORMAT_BC3_UNORM_SRGB:
00306     case DXGI_FORMAT_BC5_TYPELESS:
00307     case DXGI_FORMAT_BC5_UNORM:
00308     case DXGI_FORMAT_BC5_SNORM:
00309     case DXGI_FORMAT_BC6H_TYPELESS:
00310     case DXGI_FORMAT_BC6H_UF16:
00311     case DXGI_FORMAT_BC6H_SF16:
00312     case DXGI_FORMAT_BC7_TYPELESS:
00313     case DXGI_FORMAT_BC7_UNORM:
00314     case DXGI_FORMAT_BC7_UNORM_SRGB:
00315         bc = true;
00316         bcnumBytesPerBlock = 16;
00317         break;
00318
00319     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00320     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00321         packed = true;
00322         break;
00323     }
00324
00325     if (bc)
00326     {
00327         size_t numBlocksWide = 0;
00328         if (width > 0)
00329         {
00330             numBlocksWide = std::max<size_t>(1, (width + 3) / 4);
00331         }
00332         size_t numBlocksHigh = 0;
00333         if (height > 0)
00334         {
00335             numBlocksHigh = std::max<size_t>(1, (height + 3) / 4);
00336         }
00337         rowBytes = numBlocksWide * bcnumBytesPerBlock;
00338         numRows = numBlocksHigh;
00339     }
00340     else if (packed)
00341     {
00342         rowBytes = ((width + 1) >> 1) * 4;
00343         numRows = height;
00344     }
00345     else
00346     {
00347         size_t bpp = BitsPerPixel(fmt);
00348         rowBytes = (width * bpp + 7) / 8; // round up to nearest byte
00349         numRows = height;
00350     }
00351
00352     numBytes = rowBytes * numRows;
00353     if (outNumBytes)
00354     {
00355         *outNumBytes = numBytes;
00356     }
00357     if (outRowBytes)
00358     {
00359         *outRowBytes = rowBytes;
00360     }
00361     if (outNumRows)
00362     {
00363         *outNumRows = numRows;
00364     }
00365 }
00366
00367 #define ISBITMASK(r, g, b, a) (ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a)
00368
00369 static DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf)
00370 {
00371     if (ddpf.flags & DDS_RGB)
00372     {
00373         // Note that sRGB formats are written using the "DX10" extended header
00374
00375         switch (ddpf.RGBBitCount)
00376         {
00377         case 32:
00378             if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000))
00379             {
00380                 return DXGI_FORMAT_R8G8B8A8_UNORM;
00381             }
00382
00383             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000))
00384             {
00385                 return DXGI_FORMAT_B8G8R8A8_UNORM;
00386             }
00387
00388             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000))
00389             {
00390                 return DXGI_FORMAT_B8G8R8X8_UNORM;
00391             }
00392
00393             // No DXGI format maps to ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000) aka D3DFMT_X8B8G8R8
00394
00395             // Note that many common DDS reader/writers (including D3DX) swap the
00396             // the RED/BLUE masks for 10:10:10:2 formats. We assumme
00397             // below that the 'backwards' header mask is being used since it is most
00398             // likely written by D3DX. The more robust solution is to use the 'DX10'
00399             // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly
00400
00401             // For 'correct' writers, this should be 0x000003ff, 0x000ffc00, 0x3ff00000 for RGB data
00402             if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000))
00403             {
00404                 return DXGI_FORMAT_R10G10B10A2_UNORM;
00405             }
00406
00407             // No DXGI format maps to ISBITMASK(0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000) aka D3DFMT_A2R10G10B10
00408
00409             if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000))
00410             {
00411                 return DXGI_FORMAT_R16G16_UNORM;
00412             }
00413
00414             if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000))
00415             {
00416                 // Only 32-bit color channel format in D3D9 was R32F
00417                 return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114
00418             }
00419             break;
00420
00421         case 24:
00422             // No 24bpp DXGI formats aka D3DFMT_R8G8B8
00423             break;
00424
00425         case 16:
00426             if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000))
00427             {
00428                 return DXGI_FORMAT_B5G5R5A1_UNORM;
00429             }
00430             if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000))
00431             {
00432                 return DXGI_FORMAT_B5G6R5_UNORM;
00433             }
00434
00435             // No DXGI format maps to ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x0000) aka D3DFMT_X1R5G5B5
00436             if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000))
00437             {
00438                 return DXGI_FORMAT_B4G4R4A4_UNORM;
00439             }
00440
00441             // No DXGI format maps to ISBITMASK(0x0f00, 0x00f0, 0x000f, 0x0000) aka D3DFMT_X4R4G4B4
00442
00443             // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc.
00444             break;
00445         }
00446     }
00447     else if (ddpf.flags & DDS_LUMINANCE)
00448     {
00449         if (8 == ddpf.RGBBitCount)
00450         {
00451             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000))
00452             {
00453                 return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension
00454             }
00455
00456             // No DXGI format maps to ISBITMASK(0x0f, 0x00, 0x00, 0xf0) aka D3DFMT_A4L4
00457         }
00458
00459         if (16 == ddpf.RGBBitCount)
00460         {
00461             if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000))
00462             {
00463                 return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension
00464             }
00465             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00))
00466             {
00467                 return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension
00468             }
00469         }
00470     }
00471     else if (ddpf.flags & DDS_ALPHA)
00472     {
00473         if (8 == ddpf.RGBBitCount)
00474         {
00475             return DXGI_FORMAT_A8_UNORM;
00476         }
00477     }
00478     else if (ddpf.flags & DDS_FOURCC)
00479     {
00480         if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC)
00481         {
00482             return DXGI_FORMAT_BC1_UNORM;
00483         }
00484         if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC)
00485         {
00486             return DXGI_FORMAT_BC2_UNORM;
00487         }
00488         if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC)
00489         {
00490             return DXGI_FORMAT_BC3_UNORM;
00491         }
00492
00493         // While pre-mulitplied alpha isn't directly supported by the DXGI formats,
00494         // they are basically the same as these BC formats so they can be mapped
00495         if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC)
00496         {
00497             return DXGI_FORMAT_BC2_UNORM;
00498         }
00499         if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC)
00500         {
00501             return DXGI_FORMAT_BC3_UNORM;
00502         }
00503
00504         if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC)
00505         {
00506             return DXGI_FORMAT_BC4_UNORM;
00507         }
00508         if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC)
00509         {
00510             return DXGI_FORMAT_BC4_UNORM;
00511         }
00512         if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC)
00513         {
00514             return DXGI_FORMAT_BC4_SNORM;
00515         }
00516
00517         if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC)
00518         {
00519             return DXGI_FORMAT_BC5_UNORM;
00520         }
00521         if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC)
00522         {
00523             return DXGI_FORMAT_BC5_UNORM;
00524         }
00525         if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC)
00526         {
00527             return DXGI_FORMAT_BC5_SNORM;
00528         }
00529
00530         // BC6H and BC7 are written using the "DX10" extended header
00531
00532         if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC)
00533         {
00534             return DXGI_FORMAT_R8G8_B8G8_UNORM;
00535         }
00536         if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC)
00537         {
00538             return DXGI_FORMAT_G8R8_G8B8_UNORM;
00539         }
00540
00541         // Check for D3DFORMAT enums being set here
00542         switch (ddpf.fourCC)
00543         {
00544         case 36: // D3DFMT_A16B16G16R16
00545             return DXGI_FORMAT_R16G16B16A16_UNORM;
00546
00547         case 110: // D3DFMT_Q16W16V16U16
00548             return DXGI_FORMAT_R16G16B16A16_SNORM;
00549
00550         case 111: // D3DFMT_R16F
00551             return DXGI_FORMAT_R16_FLOAT;
00552
00553         case 112: // D3DFMT_G16R16F
00554             return DXGI_FORMAT_R16G16_FLOAT;
00555
00556         case 113: // D3DFMT_A16B16G16R16F
00557             return DXGI_FORMAT_R16G16B16A16_FLOAT;
00558
00559         case 114: // D3DFMT_R32F
00560             return DXGI_FORMAT_R32_FLOAT;
00561
00562         case 115: // D3DFMT_G32R32F
00563             return DXGI_FORMAT_R32G32_FLOAT;
00564
00565         case 116: // D3DFMT_A32B32G32R32F
00566             return DXGI_FORMAT_R32G32B32A32_FLOAT;
00567         }
00568     }
00569
00570     return DXGI_FORMAT_UNKNOWN;
00571 }
00572
00573 static DXGI_FORMAT MakeSRGB(_In_ DXGI_FORMAT format)
00574 {
00575     switch (format)
00576     {
00577     case DXGI_FORMAT_R8G8B8A8_UNORM:
00578         return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
00579
00580     case DXGI_FORMAT_BC1_UNORM:
00581         return DXGI_FORMAT_BC1_UNORM_SRGB;
00582
00583     case DXGI_FORMAT_BC2_UNORM:
00584         return DXGI_FORMAT_BC2_UNORM_SRGB;
00585
00586     case DXGI_FORMAT_BC3_UNORM:
00587         return DXGI_FORMAT_BC3_UNORM_SRGB;
00588
00589     case DXGI_FORMAT_B8G8R8A8_UNORM:
00590         return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
00591
00592     case DXGI_FORMAT_B8G8R8X8_UNORM:
00593         return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
00594
00595     case DXGI_FORMAT_BC7_UNORM:
00596         return DXGI_FORMAT_BC7_UNORM_SRGB;
00597
00598     default:
00599         return format;
00600     }
00601 }
00602
00603 static void FillInitData(
00604     _In_ size_t width,
00605     _In_ size_t height,
00606     _In_ size_t depth,
00607     _In_ size_t mipCount,
00608     _In_ size_t arraySize,
00609     _In_ DXGI_FORMAT format,
00610     _In_ size_t maxsize,
00611     _In_ size_t bitSize,
00612     _In_reads_bytes_(bitSize) const byte* bitData,
00613     _Out_ size_t& twidth,
00614     _Out_ size_t& theight,
00615     _Out_ size_t& tdepth,
00616     _Out_ size_t& skipMip,
00617     _Out_writes_(mipCount* arraySize) D3D11_SUBRESOURCE_DATA* initData
00618     )
00619 {
00620     if (!bitData || !initData)
00621     {
00622         winrt::throw_hresult(E_INVALIDARG);
00623     }
00624
00625     skipMip = 0;
00626     twidth = 0;
00627     theight = 0;
00628     tdepth = 0;
00629
00630     size_t NumBytes = 0;
00631     size_t RowBytes = 0;
00632     size_t NumRows = 0;
00633     const byte* pSrcBits = bitData;
00634     const byte* pEndBits = bitData + bitSize;
00635
00636     size_t index = 0;
00637     for (size_t j = 0; j < arraySize; j++)
00638     {
00639         size_t w = width;
00640         size_t h = height;
00641         size_t d = depth;
00642         for (size_t i = 0; i < mipCount; i++)
00643         {
00644             GetSurfaceInfo(w, h, format, &NumBytes, &RowBytes, &NumRows);
00645
00646             if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize))
00647             {
00648                 if (!twidth)
00649                 {
00650                     twidth = w;
00651                     theight = h;
00652                     tdepth = d;
00653                 }
00654
00655                 assert(index < mipCount* arraySize);
00656                 _Analysis_assume_(index < mipCount* arraySize);
00657                 initData[index].pSysMem = (const void*)pSrcBits;
00658                 initData[index].SysMemPitch = static_cast<UINT>(RowBytes);
00659                 initData[index].SysMemSlicePitch = static_cast<UINT>(NumBytes);
00660                 ++index;
00661             }
00662             else if (!j)
00663             {
00664                 // Count number of skipped mipmaps (first item only)
00665                 ++skipMip;
00666             }
00667
00668             if (pSrcBits + (NumBytes * d) > pEndBits)
00669             {
00670                 winrt::throw_hresult(E_BOUNDS);
00671             }
00672
00673             pSrcBits += NumBytes * d;
00674
00675             w = w >> 1;
00676             h = h >> 1;
00677             d = d >> 1;
00678             if (w == 0)
00679             {
00680                 w = 1;
00681             }
00682             if (h == 0)
00683             {
00684                 h = 1;
00685             }
00686             if (d == 0)
00687             {
00688                 d = 1;
00689             }
00690         }
00691     }
00692
00693     if (!index)
00694     {
00695         winrt::throw_hresult(E_FAIL);
00696     }
00697 }
00698
00699 static HRESULT CreateD3DResources(
00700     _In_ ID3D11Device* d3dDevice,
00701     _In_ uint32_t resDim,
00702     _In_ size_t width,
00703     _In_ size_t height,
00704     _In_ size_t depth,
00705     _In_ size_t mipCount,
00706     _In_ size_t arraySize,
00707     _In_ DXGI_FORMAT format,
00708     _In_ D3D11_USAGE usage,
00709     _In_ unsigned int bindFlags,
00710     _In_ unsigned int cpuAccessFlags,
00711     _In_ unsigned int miscFlags,
00712     _In_ bool forceSRGB,
00713     _In_ bool isCubeMap,
00714     _In_reads_(mipCount* arraySize) D3D11_SUBRESOURCE_DATA* initData,
00715     _Outptr_opt_ ID3D11Resource** texture,
00716     _Outptr_opt_ ID3D11ShaderResourceView** textureView
00717     )
00718 {
00719     if (!d3dDevice || !initData)
00720     {
00721         return E_INVALIDARG;
00722     }
00723
00724     HRESULT hr = E_FAIL;
00725
00726     if (forceSRGB)
00727     {
00728         format = MakeSRGB(format);
00729     }
00730
00731     switch (resDim)
00732     {
00733     case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00734     {
00735         D3D11_TEXTURE1D_DESC desc;
00736         desc.Width = static_cast<UINT>(width);
00737         desc.MipLevels = static_cast<UINT>(mipCount);
00738         desc.ArraySize = static_cast<UINT>(arraySize);
00739         desc.Format = format;
00740         desc.Usage = usage;
00741         desc.BindFlags = bindFlags;
00742         desc.CPUAccessFlags = cpuAccessFlags;
00743         desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE;
00744
00745         ID3D11Texture1D* tex = nullptr;
00746         hr = d3dDevice->CreateTexture1D(&desc, initData, &tex);
00747
00748         if (SUCCEEDED(hr) && tex != 0)
00749         {
00750             if (textureView != 0)
00751             {
00752                 D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00753                 memset(&SRVDesc, 0, sizeof(SRVDesc));
00754                 SRVDesc.Format = format;
00755
00756                 if (arraySize > 1)
00757                 {
00758                     SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1DARRAY;
00759                     SRVDesc.Texture1DArray.MipLevels = desc.MipLevels;
00760                     SRVDesc.Texture1DArray.ArraySize = static_cast<UINT>(arraySize);
00761                 }
00762                 else
00763                 {
00764                     SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1D;
00765                     SRVDesc.Texture1D.MipLevels = desc.MipLevels;
00766                 }
00767
00768                 hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00769
00770                 if (FAILED(hr))
00771                 {
00772                     tex->Release();
00773                     return hr;
00774                 }
00775             }
00776
00777             if (texture != 0)
00778             {
00779                 *texture = tex;
00780             }
00781             else
00782             {
00783                 tex->Release();
00784             }
00785         }
00786     }
00787     break;
00788
00789     case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00790     {
00791         D3D11_TEXTURE2D_DESC desc;
00792         desc.Width = static_cast<UINT>(width);
00793         desc.Height = static_cast<UINT>(height);
00794         desc.MipLevels = static_cast<UINT>(mipCount);
00795         desc.ArraySize = static_cast<UINT>(arraySize);
00796         desc.Format = format;
00797         desc.SampleDesc.Count = 1;
00798         desc.SampleDesc.Quality = 0;
00799         desc.Usage = usage;
00800         desc.BindFlags = bindFlags;
00801         desc.CPUAccessFlags = cpuAccessFlags;
00802         if (isCubeMap)
00803         {
00804             desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_TEXTURECUBE;
00805         }
00806         else
00807         {
00808             desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE;
00809         }
00810
00811         ID3D11Texture2D* tex = nullptr;
00812         hr = d3dDevice->CreateTexture2D(&desc, initData, &tex);
00813
00814         if (SUCCEEDED(hr) && tex != 0)
00815         {
00816             if (textureView != 0)
00817             {
00818                 D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00819                 memset(&SRVDesc, 0, sizeof(SRVDesc));
00820                 SRVDesc.Format = format;
00821
00822                 if (isCubeMap)
00823                 {
00824                     if (arraySize > 6)
00825                     {
00826                         SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBEARRAY;
00827                         SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels;
00828
00829                         // Earlier we set arraySize to (NumCubes * 6)
00830                         SRVDesc.TextureCubeArray.NumCubes = static_cast<UINT>(arraySize / 6);
00831                     }
00832                     else
00833                     {
00834                         SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBE;
00835                         SRVDesc.TextureCube.MipLevels = desc.MipLevels;
00836                     }
00837                 }
00838                 else if (arraySize > 1)
00839                 {
00840                     SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY;
00841                     SRVDesc.Texture2DArray.MipLevels = desc.MipLevels;
00842                     SRVDesc.Texture2DArray.ArraySize = static_cast<UINT>(arraySize);
00843                 }
00844                 else
00845                 {
00846                     SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2D;
00847                     SRVDesc.Texture2D.MipLevels = desc.MipLevels;
00848                 }
00849
00850                 hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00851
00852                 if (FAILED(hr))
00853                 {
00854                     tex->Release();
00855                     return hr;
00856                 }
00857             }
00858
00859             if (texture != 0)
00860             {
00861                 *texture = tex;
00862             }
00863             else
00864             {
00865                 tex->Release();
00866             }
00867         }
00868     }
00869     break;
00870
00871     case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00872     {
00873         D3D11_TEXTURE3D_DESC desc;
00874         desc.Width = static_cast<UINT>(width);
00875         desc.Height = static_cast<UINT>(height);
00876         desc.Depth = static_cast<UINT>(depth);
00877         desc.MipLevels = static_cast<UINT>(mipCount);
00878         desc.Format = format;
00879         desc.Usage = usage;
00880         desc.BindFlags = bindFlags;
00881         desc.CPUAccessFlags = cpuAccessFlags;
00882         desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE;
00883
00884         ID3D11Texture3D* tex = nullptr;
00885         hr = d3dDevice->CreateTexture3D(&desc, initData, &tex);
00886
00887         if (SUCCEEDED(hr) && tex != 0)
00888         {
00889             if (textureView != 0)
00890             {
00891                 D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00892                 memset(&SRVDesc, 0, sizeof(SRVDesc));
00893                 SRVDesc.Format = format;
00894                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE3D;
00895                 SRVDesc.Texture3D.MipLevels = desc.MipLevels;
00896
00897                 hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00898
00899                 if (FAILED(hr))
00900                 {
00901                     tex->Release();
00902                     return hr;
00903                 }
00904             }
00905
00906             if (texture != 0)
00907             {
00908                 *texture = tex;
00909             }
00910             else
00911             {
00912                 tex->Release();
00913             }
00914         }
00915     }
00916     break;
00917     }
00918
00919     return hr;
00920 }
00921
00922 static void CreateTextureFromDDS(
00923     _In_ ID3D11Device* d3dDevice,
00924     _In_ const DDS_HEADER* header,
00925     _In_reads_bytes_(bitSize) const byte* bitData,
00926     _In_ size_t bitSize,
00927     _In_ size_t maxsize,
00928     _In_ D3D11_USAGE usage,
00929     _In_ unsigned int bindFlags,
00930     _In_ unsigned int cpuAccessFlags,
00931     _In_ unsigned int miscFlags,
00932     _In_ bool forceSRGB,
00933     _Outptr_opt_ ID3D11Resource** texture,
00934     _Outptr_opt_ ID3D11ShaderResourceView** textureView
00935     )
00936 {
00937     HRESULT hr = S_OK;
00938
00939     size_t width = header->width;
00940     size_t height = header->height;
00941     size_t depth = header->depth;
00942
00943     uint32_t resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN;
00944     size_t arraySize = 1;
00945     DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
00946     bool isCubeMap = false;
00947
00948     size_t mipCount = header->mipMapCount;
00949     if (0 == mipCount)
00950     {
00951         mipCount = 1;
00952     }
00953
00954     if ((header->ddspf.flags & DDS_FOURCC) &&
00955         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
00956     {
00957         auto d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER));
00958
00959         arraySize = d3d10ext->arraySize;
00960         if (arraySize == 0)
00961         {
00962             winrt::throw_hresult(E_FAIL);
00963         }
00964
00965         if (BitsPerPixel(d3d10ext->dxgiFormat) == 0)
00966         {
00967             winrt::throw_hresult(E_FAIL);
00968         }
00969
00970         format = d3d10ext->dxgiFormat;
00971
00972         switch (d3d10ext->resourceDimension)
00973         {
00974         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00975             // D3DX writes 1D textures with a fixed Height of 1
00976             if ((header->flags & DDS_HEIGHT) && height != 1)
00977             {
00978                 winrt::throw_hresult(E_FAIL);
00979             }
00980             height = depth = 1;
00981             break;
00982
00983         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00984             if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE)
00985             {
00986                 arraySize *= 6;
00987                 isCubeMap = true;
00988             }
00989             depth = 1;
00990             break;
00991
00992         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00993             if (!(header->flags & DDS_HEADER_FLAGS_VOLUME))
00994             {
00995                 winrt::throw_hresult(E_FAIL);
00996             }
00997
00998             if (arraySize > 1)
00999             {
01000                 winrt::throw_hresult(E_FAIL);
01001             }
01002             break;
01003
01004         default:
01005             winrt::throw_hresult(E_FAIL);
01006         }
01007
01008         resDim = d3d10ext->resourceDimension;
01009     }
01010     else
01011     {
01012         format = GetDXGIFormat(header->ddspf);
01013
01014         if (format == DXGI_FORMAT_UNKNOWN)
01015         {
01016             winrt::throw_hresult(E_FAIL);
01017         }
01018
01019         if (header->flags & DDS_HEADER_FLAGS_VOLUME)
01020         {
01021             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D;
01022         }
01023         else
01024         {
01025             if (header->caps2 & DDS_CUBEMAP)
01026             {
01027                 // We require all six faces to be defined
01028                 if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES)
01029                 {
01030                     winrt::throw_hresult(E_FAIL);
01031                 }
01032
01033                 arraySize = 6;
01034                 isCubeMap = true;
01035             }
01036
01037             depth = 1;
01038             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D;
01039
01040             // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture
01041         }
01042
01043         assert(BitsPerPixel(format) != 0);
01044     }
01045
01046     // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements)
01047     if (mipCount > D3D11_REQ_MIP_LEVELS)
01048     {
01049         winrt::throw_hresult(E_FAIL);
01050     }
01051
01052     switch (resDim)
01053     {
01054     case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
01055         if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) ||
01056             (width > D3D11_REQ_TEXTURE1D_U_DIMENSION))
01057         {
01058             winrt::throw_hresult(E_FAIL);
01059         }
01060         break;
01061
01062     case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
01063         if (isCubeMap)
01064         {
01065             // This is the right bound because we set arraySize to (NumCubes*6) above
01066             if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01067                 (width > D3D11_REQ_TEXTURECUBE_DIMENSION) ||
01068                 (height > D3D11_REQ_TEXTURECUBE_DIMENSION))
01069             {
01070                 winrt::throw_hresult(E_FAIL);
01071             }
01072         }
01073         else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01074             (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) ||
01075             (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION))
01076         {
01077             winrt::throw_hresult(E_FAIL);
01078         }
01079         break;
01080
01081     case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
01082         if ((arraySize > 1) ||
01083             (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01084             (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01085             (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION))
01086         {
01087             winrt::throw_hresult(E_FAIL);
01088         }
01089         break;
01090     }
01091
01092     // Create the texture
01093     std::unique_ptr<D3D11_SUBRESOURCE_DATA[]> initData(new D3D11_SUBRESOURCE_DATA[mipCount * arraySize]);
01094
01095     size_t skipMip = 0;
01096     size_t twidth = 0;
01097     size_t theight = 0;
01098     size_t tdepth = 0;
01099     FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01100
01101     hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, isCubeMap, initData.get(), texture, textureView);
01102
01103     if (FAILED(hr) && !maxsize && (mipCount > 1))
01104     {
01105         // Retry with a maxsize determined by feature level
01106         switch (d3dDevice->GetFeatureLevel())
01107         {
01108         case D3D_FEATURE_LEVEL_9_1:
01109         case D3D_FEATURE_LEVEL_9_2:
01110             if (isCubeMap)
01111             {
01112                 maxsize = D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION;
01113             }
01114             else
01115             {
01116                 maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01117                     ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01118                     : D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01119             }
01120             break;
01121
01122         case D3D_FEATURE_LEVEL_9_3:
01123             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01124                 ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01125                 : D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01126             break;
01127
01128         default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1
01129             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01130                 ? D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01131                 : D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01132             break;
01133         }
01134
01135         FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01136
01137         hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, isCubeMap, initData.get(), texture, textureView);
01138     }
01139
01140     winrt::check_hresult(hr);
01141 }
01142
01143 static D2D1_ALPHA_MODE GetAlphaMode(_In_ const DDS_HEADER* header)
01144 {
01145     if (header->ddspf.flags & DDS_FOURCC)
01146     {
01147         if (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)
01148         {
01149             auto d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER));
01150             switch (d3d10ext->miscFlags2 & DDS_MISC_FLAGS2_ALPHA_MODE_MASK)
01151             {
01152             case DDS_ALPHA_MODE_STRAIGHT:
01153                 return D2D1_ALPHA_MODE_STRAIGHT;
01154
01155             case DDS_ALPHA_MODE_PREMULTIPLIED:
01156                 return D2D1_ALPHA_MODE_PREMULTIPLIED;
01157
01158             case DDS_ALPHA_MODE_OPAQUE:
01159             case DDS_ALPHA_MODE_CUSTOM:
01160                 // No D2D1_ALPHA_MODE equivalent, so return "Ignore" for now
01161                 return D2D1_ALPHA_MODE_IGNORE;
01162             }
01163         }
01164         else if ((MAKEFOURCC('D', 'X', 'T', '2') == header->ddspf.fourCC)
01165             || (MAKEFOURCC('D', 'X', 'T', '4') == header->ddspf.fourCC))
01166         {
01167             return D2D1_ALPHA_MODE_PREMULTIPLIED;
01168         }
01169         // DXT1, DXT3, and DXT5 legacy files could be straight alpha or something else, so return "Unknown" to leave it up to the app
01170     }
01171
01172     return D2D1_ALPHA_MODE_UNKNOWN;
01173 }
01174
01175
01176 _Use_decl_annotations_
01177 void CreateDDSTextureFromMemory(
01178     ID3D11Device* d3dDevice,
01179     const uint8_t* ddsData,
01180     size_t ddsDataSize,
01181     ID3D11Resource** texture,
01182     ID3D11ShaderResourceView** textureView,
01183     size_t maxsize,
01184     D2D1_ALPHA_MODE* alphaMode
01185     )
01186 {
01187     return CreateDDSTextureFromMemoryEx(d3dDevice, ddsData, ddsDataSize, maxsize, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, texture, textureView, alphaMode);
01188 }
01189
01190 _Use_decl_annotations_
01191 void CreateDDSTextureFromMemoryEx(
01192     ID3D11Device* d3dDevice,
01193     const uint8_t* ddsData,
01194     size_t ddsDataSize,
01195     size_t maxsize,
01196     D3D11_USAGE usage,
01197     unsigned int bindFlags,
01198     unsigned int cpuAccessFlags,
01199     unsigned int miscFlags,
01200     bool forceSRGB,
01201     ID3D11Resource** texture,
01202     ID3D11ShaderResourceView** textureView,
01203     D2D1_ALPHA_MODE* alphaMode
01204     )
01205 {
01206     if (texture)
01207     {
01208         *texture = nullptr;
01209     }
01210     if (textureView)
01211     {
01212         *textureView = nullptr;
01213     }
01214     if (alphaMode)
01215     {
01216         *alphaMode = D2D1_ALPHA_MODE_UNKNOWN;
01217     }
01218
01219     if (!d3dDevice || !ddsData || (!texture && !textureView))
01220     {
01221         winrt::throw_hresult(E_INVALIDARG);
01222     }
01223
01224     // Validate DDS file in memory
01225     if (ddsDataSize < (sizeof(uint32_t) + sizeof(DDS_HEADER)))
01226     {
01227         winrt::throw_hresult(E_FAIL);
01228     }
01229
01230     uint32_t dwMagicNumber = *(const uint32_t*)(ddsData);
01231     if (dwMagicNumber != DDS_MAGIC)
01232     {
01233         winrt::throw_hresult(E_FAIL);
01234     }
01235
01236     auto header = reinterpret_cast<const DDS_HEADER*>(ddsData + sizeof(uint32_t));
01237
01238     // Verify header to validate DDS file
01239     if (header->size != sizeof(DDS_HEADER) ||
01240         header->ddspf.size != sizeof(DDS_PIXELFORMAT))
01241     {
01242         winrt::throw_hresult(E_FAIL);
01243     }
01244
01245     // Check for DX10 extension
01246     bool bDXT10Header = false;
01247     if ((header->ddspf.flags & DDS_FOURCC) &&
01248         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
01249     {
01250         // Must be long enough for both headers and magic value
01251         if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32_t) + sizeof(DDS_HEADER_DXT10)))
01252         {
01253             winrt::throw_hresult(E_FAIL);
01254         }
01255
01256         bDXT10Header = true;
01257     }
01258
01259     ptrdiff_t offset = sizeof(uint32_t) + sizeof(DDS_HEADER) + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0);
01260
01261     CreateTextureFromDDS(d3dDevice, header, ddsData + offset, ddsDataSize - offset, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, texture, textureView);
01262
01263     if (alphaMode)
01264         *alphaMode = GetAlphaMode(header);
01265 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/PlugInFilter.cpp Source File

  • HttpClient
  • cppwinrt

PlugInFilter.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "PlugInFilter.h"
00014 #include "PlugInFilter.g.cpp"
00015 #include "Helpers.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::Web::Http;
00020 using namespace winrt::Windows::Web::Http::Filters;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     PlugInFilter::PlugInFilter(IHttpFilter const& innerFilter) : m_innerFilter(innerFilter)
00025     {
00026         if (innerFilter == nullptr)
00027         {
00028             throw hresult_invalid_argument(L"innerFilter cannot be null.");
00029         }
00030     }
00031
00032     IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> PlugInFilter::SendRequestAsync(HttpRequestMessage request)
00033     {
00034         auto lifetime = get_strong();
00035         auto cancellation = co_await get_cancellation_token();
00036         cancellation.enable_propagation();
00037         auto progress = co_await get_progress_token();
00038
00039         request.Headers().Append(L"Custom-Header", L"CustomRequestValue");
00040
00041         IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> operation = m_innerFilter.SendRequestAsync(request);
00042         operation.Progress([progress](auto&&, auto&& data) mutable
00043             {
00044                 progress(data);
00045             });
00046         HttpResponseMessage response = co_await operation;
00047
00048         response.Headers().Append(L"Custom-Header", L"CustomResponseValue");
00049         co_return response;
00050     }
00051
00052     void PlugInFilter::Close()
00053     {
00054         m_innerFilter.Close();
00055     }
00056 }
00057
00058
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CameraStreamProcessor Member List

This is the complete list of members for CameraStreamProcessor, including all inherited members.
CameraStreamProcessor(Windows::Media::Capture::Frames::MediaFrameSourceKind sourceKind, Platform::String^format, Windows::Media::Capture::MediaCaptureMemoryPreference memoryPreference) | CameraStreamProcessor |
CreateAndStartAsync(Windows::Media::Capture::Frames::MediaFrameSourceKind sourceKind, Platform::String^format, Windows::Media::Capture::MediaCaptureMemoryPreference memoryPreference=Windows::Media::Capture::MediaCaptureMemoryPreference::Cpu) | CameraStreamProcessor | [static]
GetLatestFrame() const | CameraStreamProcessor |
IsStreaming() const | CameraStreamProcessor |
m_frameArrivedToken | CameraStreamProcessor | [private]
m_frameCount | CameraStreamProcessor | [private]
m_isStreaming | CameraStreamProcessor | [private]
m_latestFrameData | CameraStreamProcessor | [private]
m_lock | CameraStreamProcessor | [mutable, private]
m_mediaCapture | CameraStreamProcessor | [private]
m_mediaFrameReader | CameraStreamProcessor | [private]
m_memoryPreference | CameraStreamProcessor | [private]
m_sourceFormat | CameraStreamProcessor | [private]
m_sourceKind | CameraStreamProcessor | [private]
OnFrameArrived(Windows::Media::Capture::Frames::MediaFrameReader^sender, Windows::Media::Capture::Frames::MediaFrameArrivedEventArgs^args) | CameraStreamProcessor |
StartAsync() | CameraStreamProcessor |
StopAsync() | CameraStreamProcessor |
~CameraStreamProcessor() | CameraStreamProcessor |
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

UpdateFileTask Member List

This is the complete list of members for UpdateFileTask, including all inherited members.
Run(IBackgroundTaskInstance taskInstance) | UpdateFileTask | [inline]
ShowToast(string message) | UpdateFileTask | [inline, private]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInfo/cs/Scenario1_FindUsers.xaml.cs Source File

  • UserInfo
  • cs

Scenario1_FindUsers.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Collections.ObjectModel;
00015 using Windows.Foundation.Collections;
00016 using Windows.Storage.Streams;
00017 using Windows.System;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Media.Imaging;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace SDKTemplate
00024 {
00025     public sealed partial class Scenario1_FindUsers : Page
00026     {
00027         private MainPage rootPage;
00028
00029         public Scenario1_FindUsers()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override async void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             rootPage = MainPage.Current;
00037
00038             // Populate the list of users.
00039             var observableUsers = await MainPage.GetUserViewModelsAsync();
00040             UserList.DataContext = observableUsers;
00041             if (observableUsers.Count > 0)
00042             {
00043                 UserList.SelectedIndex = 0;
00044             }
00045         }
00046
00047         private async void ShowProperties()
00048         {
00049             var selectedUser = (UserViewModel)UserList.SelectedValue;
00050             if (selectedUser != null)
00051             {
00052                 ResultsText.Text = "";
00053                 ProfileImage.Source = null;
00054                 rootPage.NotifyUser("", NotifyType.StatusMessage);
00055                 try
00056                 {
00057                     User user = User.GetFromId(selectedUser.UserId);
00058
00059                     // Start with some fixed properties.
00060                     String result = "NonRoamableId: " + user.NonRoamableId + "\n";
00061                     result += "Type: " + user.Type.ToString() + "\n";
00062                     result += "AuthenticationStatus: " + user.AuthenticationStatus.ToString() + "\n";
00063
00064                     // Build a list of all the properties we want.
00065                     String[] desiredProperties = new String[]
00066                     {
00067                         KnownUserProperties.FirstName,
00068                         KnownUserProperties.LastName,
00069                         KnownUserProperties.ProviderName,
00070                         KnownUserProperties.AccountName,
00071                         KnownUserProperties.GuestHost,
00072                         KnownUserProperties.PrincipalName,
00073                         KnownUserProperties.DomainName,
00074                         KnownUserProperties.SessionInitiationProtocolUri,
00075                     };
00076                     // Issue a bulk query for all of the properties.
00077                     IPropertySet values = await user.GetPropertiesAsync(desiredProperties);
00078
00079                     // Add those properties to our results.
00080                     foreach (String property in desiredProperties)
00081                     {
00082                         result += property + ": " + values[property] + "\n";
00083                     }
00084                     ResultsText.Text = result;
00085
00086                     // Get the user's picture.
00087                     IRandomAccessStreamReference streamReference = await user.GetPictureAsync(UserPictureSize.Size64x64);
00088                     if (streamReference != null)
00089                     {
00090                         IRandomAccessStream stream = await streamReference.OpenReadAsync();
00091                         BitmapImage bitmapImage = new BitmapImage();
00092                         bitmapImage.SetSource(stream);
00093                         ProfileImage.Source = bitmapImage;
00094                     }
00095                 }
00096                 catch (Exception ex)
00097                 {
00098                     rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
00099                 }
00100             }
00101         }
00102     }
00103 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppServices/cs/AppServicesProvider/ShowPackageFamilyName.xaml.cs Source File

  • AppServices
  • cs
  • AppServicesProvider

ShowPackageFamilyName.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.ApplicationModel;
00013 using Windows.UI.Xaml.Controls;
00014
00015 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     public sealed partial class ShowPackageFamilyName : Page
00023     {
00024         public ShowPackageFamilyName()
00025         {
00026             this.InitializeComponent();
00027             PackageFamilyName.Text = Package.Current.Id.FamilyName;
00028         }
00029     }
00030 }
Generated on Fri Nov 15 2024 22:18:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Client/targetver.h Source File

  • CustomCapability
  • Service
  • Client

targetver.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 // Including SDKDDKVer.h defines the highest available Windows platform.
00004
00005 // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
00006 // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
00007
00008 #include <SDKDDKVer.h>
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/CustomVertexShaderRenderer.cpp Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

CustomVertexShaderRenderer.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "CustomVertexShaderRenderer.h"
00014 #include "DirectXHelper.h"
00015
00016 using namespace CustomVertexShader;
00017 using namespace DirectX;
00018 using namespace Microsoft::WRL;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021
00022 CustomVertexShaderRenderer::CustomVertexShaderRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00023     m_deviceResources(deviceResources)
00024 {
00025     m_timer = ref new BasicTimer();
00026
00027     CreateDeviceIndependentResources();
00028     CreateDeviceDependentResources();
00029     CreateWindowSizeDependentResources();
00030 }
00031
00032 void CustomVertexShaderRenderer::CreateDeviceIndependentResources()
00033 {
00034     auto wicFactory = m_deviceResources->GetWicImagingFactory();
00035     auto d2dFactory = m_deviceResources->GetD2DFactory();
00036
00037     // Create WIC Decoder to read JPG file.
00038     ComPtr<IWICBitmapDecoder> decoder;
00039     DX::ThrowIfFailed(
00040         wicFactory->CreateDecoderFromFilename(
00041         L"Assets\\rainier.jpg",
00042         nullptr,
00043         GENERIC_READ,
00044         WICDecodeMetadataCacheOnDemand,
00045         &decoder
00046         ));
00047
00048     ComPtr<IWICBitmapFrameDecode> frame;
00049     DX::ThrowIfFailed(decoder->GetFrame(0, &frame));
00050
00051     DX::ThrowIfFailed(wicFactory->CreateFormatConverter(&m_formatConvert));
00052     DX::ThrowIfFailed(m_formatConvert->Initialize(
00053         frame.Get(),
00054         GUID_WICPixelFormat32bppPBGRA, // 32bppPBGRA is used by Direct2D.
00055         WICBitmapDitherTypeNone,
00056         nullptr,
00057         0.0f,
00058         WICBitmapPaletteTypeCustom
00059         ));
00060
00061     UINT width;
00062     UINT height;
00063     DX::ThrowIfFailed(m_formatConvert->GetSize(&width, &height));
00064     m_imageSize = D2D1::SizeU(width, height);
00065
00066     // Register the custom wave effect.
00067     DX::ThrowIfFailed(WaveEffect::Register(d2dFactory));
00068 }
00069
00070 void CustomVertexShaderRenderer::CreateDeviceDependentResources()
00071 {
00072     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00073
00074     // Load the image from WIC using ImageSource. The image is scaled using
00075     // ID2D1TransformedImageSource which is dependent on the scale factor.
00076     DX::ThrowIfFailed(d2dContext->CreateImageSourceFromWic(m_formatConvert.Get(), &m_imageSource));
00077
00078     DX::ThrowIfFailed(d2dContext->CreateEffect(CLSID_CustomWaveEffect, &m_waveEffect));
00079 }
00080
00081 void CustomVertexShaderRenderer::ReleaseDeviceDependentResources()
00082 {
00083     m_imageSource.Reset();
00084     m_waveEffect.Reset();
00085     m_transformedImage.Reset();
00086 }
00087
00088 void CustomVertexShaderRenderer::CreateWindowSizeDependentResources()
00089 {
00090     auto size = m_deviceResources->GetLogicalSize();
00091     float scale = size.Width / m_imageSize.width;
00092
00093     UpdateImageScale(scale);
00094 }
00095
00096 // Sets up the image effect pipeline to reflect the new scale factor.
00097 void CustomVertexShaderRenderer::UpdateImageScale(float scale)
00098 {
00099     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00100
00101     // When using ID2D1ImageSource, the recommend method of applying a transform
00102     // is to use ID2D1TransformedImageSource. It is inexpensive to recreate this object.
00103     D2D1_TRANSFORMED_IMAGE_SOURCE_PROPERTIES props =
00104     {
00105         D2D1_ORIENTATION_DEFAULT,
00106         scale,
00107         scale,
00108         D2D1_INTERPOLATION_MODE_LINEAR, // This is ignored when using DrawImage.
00109         D2D1_TRANSFORMED_IMAGE_SOURCE_OPTIONS_NONE
00110     };
00111
00112     DX::ThrowIfFailed(d2dContext->CreateTransformedImageSource(
00113         m_imageSource.Get(),
00114         &props,
00115         &m_transformedImage));
00116
00117     m_waveEffect->SetInput(0, m_transformedImage.Get());
00118 }
00119
00120 void CustomVertexShader::CustomVertexShaderRenderer::UpdateManipulationState(Windows::UI::Input::ManipulationUpdatedEventArgs ^ args)
00121 {
00122     m_skewX += args->Delta.Translation.X * 0.01f;
00123     m_skewY += args->Delta.Translation.Y * 0.01f;
00124
00125     DX::ThrowIfFailed(m_waveEffect->SetValue(WAVE_PROP_SKEW_X, m_skewX));
00126     DX::ThrowIfFailed(m_waveEffect->SetValue(WAVE_PROP_SKEW_Y, m_skewY));
00127 }
00128
00129 void CustomVertexShaderRenderer::Update()
00130 {
00131     m_timer->Update();
00132
00133     // The wave ripples over time.
00134     DX::ThrowIfFailed(
00135         m_waveEffect->SetValue(WAVE_PROP_OFFSET, m_timer->Total)
00136         );
00137 }
00138
00139 void CustomVertexShaderRenderer::Render()
00140 {
00141     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00142
00143     d2dContext->BeginDraw();
00144     m_deviceResources->GetD2DDeviceContext()->SetTransform(m_deviceResources->GetOrientationTransform2D());
00145     d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
00146
00147     d2dContext->DrawImage(m_waveEffect.Get());
00148
00149     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00150     // is lost. It will be handled during the next call to Present.
00151     HRESULT hr = d2dContext->EndDraw();
00152     if (hr != D2DERR_RECREATE_TARGET)
00153     {
00154         DX::ThrowIfFailed(hr);
00155     }
00156 }
00157
00158 // Saves the current state of the app for suspend and terminate events.
00159 void _In_ CustomVertexShaderRenderer::SaveInternalState(_In_ IPropertySet ^ state)
00160 {
00161     // Check to ensure each key is not already in the collection. If it is present, remove
00162     // it, before storing in the new value.
00163
00164     if (state->HasKey("SkewX"))
00165     {
00166         state->Remove("SkewX");
00167     }
00168     state->Insert("SkewX", PropertyValue::CreateSingle(m_skewX));
00169
00170     if (state->HasKey("SkewY"))
00171     {
00172         state->Remove("SkewY");
00173     }
00174     state->Insert("SkewY", PropertyValue::CreateSingle(m_skewY));
00175 }
00176
00177 // Loads the current state of the app for resume events.
00178 void CustomVertexShaderRenderer::LoadInternalState(_In_ IPropertySet ^ state)
00179 {
00180     if (state->HasKey("skewX"))
00181     {
00182         m_skewX = safe_cast<IPropertyValue^>(state->Lookup("skewX"))->GetSingle();
00183     }
00184
00185     if (state->HasKey("skewY"))
00186     {
00187         m_skewY = safe_cast<IPropertyValue^>(state->Lookup("skewY"))->GetSingle();
00188     }
00189 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SeekBarElement Member List

This is the complete list of members for SeekBarElement, including all inherited members.
AddChildElement(const std::shared_ptr< BaseElement > &childElement) | BaseElement |
ArrangeElements() | BaseElement | [virtual]
BaseElement() | BaseElement |
FocusableElement() | FocusableElement |
FocusUpdate() | FocusableElement | [inline, virtual]
FormatTimeString(int64 intervalValue) | SeekBarElement | [private]
GetElementMargin() | BaseElement | [inline]
GetElementSize() | BaseElement | [inline]
GetIgnoreLayout() | BaseElement | [inline]
GetIsRenderPassNeeded() | BaseElement | [inline]
GetIsVisible() | BaseElement | [inline]
Initialize() override | SeekBarElement | [virtual]
IsFocused() | FocusableElement | [inline, virtual]
m_brush | SeekBarElement | [private]
m_currentPlayPosition | SeekBarElement | [private]
m_currentVideoDuration | SeekBarElement | [private]
m_deviceResources | BaseElement | [protected]
m_elapsedTimeString | SeekBarElement | [private]
m_elapsedTimeText | SeekBarElement | [private]
m_elementCoordIntersectionPoint | FocusableElement | [protected]
m_elementMargin | BaseElement | [protected]
m_elementSize | BaseElement | [protected]
m_endSegmentBrush | SeekBarElement | [private]
m_frontSegmentBrush | SeekBarElement | [private]
m_ignoreLayout | BaseElement | [protected]
m_isFocused | FocusableElement | [protected]
m_isFocusIntersectionCalculated | FocusableElement | [protected]
m_isInitialized | BaseElement | [protected]
m_isLayoutHorizontal | BaseElement | [protected]
m_isParentFocused | FocusableElement | [protected]
m_isRenderPassNeeded | BaseElement | [protected]
m_isVisible | BaseElement | [protected]
m_leftRightPadding | SeekBarElement | [private]
m_parentFocusedPosition | FocusableElement | [protected]
m_parentTextureHeight | FocusableElement | [protected]
m_parentTextureWidth | FocusableElement | [protected]
m_parentTranslation | BaseElement | [protected]
m_remainingTimeString | SeekBarElement | [private]
m_remainingTimeText | SeekBarElement | [private]
m_secondsElapsedSinceTimeUpdate | SeekBarElement | [private]
m_sliderFrontSegment | SeekBarElement | [private]
m_sliderFrontSegmentEnd | SeekBarElement | [private]
m_sliderFrontSegmentStart | SeekBarElement | [private]
m_sliderHeight | SeekBarElement | [private]
m_sliderPosition | SeekBarElement | [private]
m_sliderRemainingSegment | SeekBarElement | [private]
m_sliderRemainingSegmentEnd | SeekBarElement | [private]
m_sliderRemainingSegmentStart | SeekBarElement | [private]
m_sliderWidth | SeekBarElement | [private]
m_textSize | SeekBarElement | [private]
m_topBottomPadding | SeekBarElement | [private]
m_transformedTranslation | BaseElement | [protected]
m_transformMatrix | BaseElement | [protected]
m_transformRecalculationNeeded | BaseElement | [protected]
m_translation | BaseElement | [protected]
PerformAction() override | SeekBarElement | [virtual]
Render() | BaseElement | [protected, virtual]
SeekBarElement(float elementWidth, float elementHeight=FONT_SIZE *5.0f, float leftRightPadding=FONT_SIZE *2.0f, float topBottomPadding=FONT_SIZE *2.0f) | SeekBarElement |
SetBrush(ID2D1SolidColorBrush *brush) | BaseElement |
SetElementMargin(ElementMargin margin) | BaseElement | [inline]
SetElementSize(Windows::Foundation::Numerics::float2 size) | BaseElement | [inline]
SetIgnoreLayout(bool ignoreLayout) | BaseElement | [inline]
SetIsVisible(bool visible) | BaseElement |
SetLayoutHorizontal(bool isLayoutHorizontal) | BaseElement | [inline]
SetParentControlInformation(bool focused, Windows::Foundation::Numerics::float2 focusedPosition, UINT parentTextureWidth, UINT parentTextureHeight) | FocusableElement | [virtual]
SetParentTransform(Windows::Foundation::Numerics::float2 translation) | BaseElement |
SetTranslation(Windows::Foundation::Numerics::float2 translation) | BaseElement | [virtual]
TryRender() | BaseElement |
Update(const DX::StepTimer &timer, Windows::UI::Input::Spatial::SpatialPointerPose^cameraPose) override | SeekBarElement | [virtual]
UpdateLayoutFromCurrentTime() | SeekBarElement | [private]
UpdateSliderPosition(float position) | SeekBarElement | [private]
~BaseElement() | BaseElement | [virtual]
~FocusableElement() | FocusableElement | [virtual]
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2 Member List

This is the complete list of members for Scenario2, including all inherited members.
IsIdentityManaged_Click(object sender, RoutedEventArgs e) | Scenario2 | [inline, private]
m_scenarioText | Scenario2 | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2 | [inline, protected]
rootPage | Scenario2 | [private]
Scenario2() | Scenario2 | [inline]
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Stroke Member List

This is the complete list of members for Stroke, including all inherited members.
AddPosition(Windows::Foundation::Numerics::float3 position, Windows::Foundation::Numerics::quaternion orientation, float diameter) | Stroke |
m_indexBuffer | Stroke | [private]
m_indexCount | Stroke | [private]
m_modelConstantBufferData | Stroke | [private]
m_resetBuffers | Stroke | [private]
m_squares | Stroke | [private]
m_vertexBuffer | Stroke | [private]
Render(ID3D11DeviceContext *pDeviceContext, IRenderer *pRenderingHelper) override | Stroke | [virtual]
Stroke(Windows::UI::Color color) | Stroke |
Update(ID3D11DeviceContext *pDeviceContext) override | Stroke | [virtual]
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cpp/Scenario1_AdvertiserCreate.xaml.h Source File

  • WiFiDirectServices
  • cpp

Scenario1_AdvertiserCreate.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Helpers\ServiceStatusConverter.h"
00015 #include "Scenario1_AdvertiserCreate.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     namespace WiFiDirectServices
00021     {
00022         /// <summary>
00023         /// UI that exposes properties to begin advertising a Wi-Fi Direct Service.
00024         /// A normal application would hide this implementation and just provide a way to begin advertising a service
00025         ///
00026         /// Most of the actual logic for Wi-Fi Direct Services is in WiFiDirectServicesManager.h/cpp and WiFiDirectServicesWrappers.h/cpp
00027         /// </summary>
00028         [Windows::Foundation::Metadata::WebHostHidden]
00029         public ref class Scenario1 sealed
00030         {
00031         public:
00032             Scenario1();
00033         protected:
00034             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035
00036             virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00037
00038         private:
00039             SDKTemplate::MainPage^ _rootPage;
00040
00041             void ResetFields();
00042
00043             void CreateAdvertiser_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044
00045             void RemovePrefix_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046
00047             void AddPrefix_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048         };
00049     }
00050 }
Generated on Fri Nov 15 2024 22:22:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario15_DPLCreateFileEvents Member List

This is the complete list of members for Scenario15_DPLCreateFileEvents, including all inherited members.
AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task) | Scenario15_DPLCreateFileEvents | [inline, private]
OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) | Scenario15_DPLCreateFileEvents | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario15_DPLCreateFileEvents | [inline, protected]
OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args) | Scenario15_DPLCreateFileEvents | [inline, private]
OutputToTextBox(String text) | Scenario15_DPLCreateFileEvents | [inline, private]
Register_Click(object sender, RoutedEventArgs e) | Scenario15_DPLCreateFileEvents | [inline, private]
RegisterBackgroundTask() | Scenario15_DPLCreateFileEvents | [inline, private]
RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition) | Scenario15_DPLCreateFileEvents | [inline, static]
rootPage | Scenario15_DPLCreateFileEvents | [private]
SAMPLE_TASK_ENTRY_POINT | Scenario15_DPLCreateFileEvents | [private]
SAMPLE_TASK_NAME | Scenario15_DPLCreateFileEvents | [private]
Scenario15_DPLCreateFileEvents() | Scenario15_DPLCreateFileEvents | [inline]
UnRegister_Click(object sender, RoutedEventArgs e) | Scenario15_DPLCreateFileEvents | [inline, private]
UnregisterBackgroundTask() | Scenario15_DPLCreateFileEvents | [inline, private]
UpdateStatus() | Scenario15_DPLCreateFileEvents | [inline, private]
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: VideoPlayback/cs/Scenario3_DisplayingOutOfBandClosedCaptions.xaml.cs Source File

  • VideoPlayback
  • cs

Scenario3_DisplayingOutOfBandClosedCaptions.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate.Logging;
00013 using System;
00014 using System.Collections.Generic;
00015 using Windows.Media.Core;
00016 using Windows.Media.Playback;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// Demonstrates playing media with closed captions delivered out-of-band, specifically an MP4 video supplemented by external SRT files.
00025     /// </summary>
00026     public sealed partial class Scenario3 : Page
00027     {
00028         private MainPage rootPage = MainPage.Current;
00029         private MediaPlaybackItemLogger mpiLogger;
00030         private MediaSourceLogger msLogger;
00031
00032         // Keep a map to correlate sources with their URIs for error handling
00033         private Dictionary<TimedTextSource, Uri> ttsMap = new Dictionary<TimedTextSource, Uri>();
00034
00035         public Scenario3()
00036         {
00037             this.InitializeComponent();
00038         }
00039
00040         protected override void OnNavigatedTo(NavigationEventArgs e)
00041         {
00042             // Create the media source and supplement with external timed text sources.
00043             var source = MediaSource.CreateFromUri(rootPage.UncaptionedMediaUri);
00044             msLogger = new MediaSourceLogger(LoggerControl, source);
00045
00046             var ttsEnUri = new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-SRT_en.srt");
00047             var ttsEn = TimedTextSource.CreateFromUri(ttsEnUri);
00048             ttsMap[ttsEn] = ttsEnUri;
00049
00050             var ttsPtUri = new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-SRT_pt.srt");
00051             var ttsPt = TimedTextSource.CreateFromUri(ttsPtUri);
00052             ttsMap[ttsPt] = ttsPtUri;
00053
00054             var ttsSvUri = new Uri("ms-appx:///Assets/Media/ElephantsDream-Clip-SRT_sv.srt");
00055             var ttsSv = TimedTextSource.CreateFromUri(ttsSvUri);
00056             ttsMap[ttsSv] = ttsSvUri;
00057
00058             ttsEn.Resolved += Tts_Resolved;
00059             ttsPt.Resolved += Tts_Resolved;
00060             ttsSv.Resolved += Tts_Resolved;
00061
00062             source.ExternalTimedTextSources.Add(ttsEn);
00063             source.ExternalTimedTextSources.Add(ttsPt);
00064             source.ExternalTimedTextSources.Add(ttsSv);
00065
00066             // Create the playback item from the source
00067             var playbackItem = new MediaPlaybackItem(source);
00068             mpiLogger = new MediaPlaybackItemLogger(LoggerControl, playbackItem);
00069
00070             // Present the first track
00071             playbackItem.TimedMetadataTracksChanged += (item, args) =>
00072             {
00073                 LoggerControl.Log($"TimedMetadataTracksChanged, Number of tracks: {item.TimedMetadataTracks.Count}");
00074                 playbackItem.TimedMetadataTracks.SetPresentationMode(0, TimedMetadataTrackPresentationMode.PlatformPresented);
00075             };
00076
00077             // Set the source to start playback of the item
00078             this.mediaPlayerElement.Source = playbackItem;
00079             LoggerControl.Log($"Loaded: {rootPage.UncaptionedMediaUri}");
00080         }
00081
00082         protected override void OnNavigatedFrom(NavigationEventArgs e)
00083         {
00084             msLogger?.Dispose();
00085             msLogger = null;
00086             mpiLogger?.Dispose();
00087             mpiLogger = null;
00088             MediaPlayerHelper.CleanUpMediaPlayerSource(mediaPlayerElement.MediaPlayer);
00089         }
00090
00091         private void Tts_Resolved(TimedTextSource sender, TimedTextSourceResolveResultEventArgs args)
00092         {
00093             var ttsUri = ttsMap[sender];
00094
00095             // Handle errors
00096             if(args.Error != null)
00097             {
00098                 var ignoreAwaitWarning = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00099                 {
00100                     LoggerControl.Log("Error resolving track " + ttsUri + " due to error " + args.Error.ErrorCode, LogViewLoggingLevel.Error);
00101                 });
00102                 return;
00103             }
00104             LoggerControl.Log($"Resolved: {ttsUri}");
00105
00106             // Update label manually since the external SRT does not contain it
00107             var ttsUriString = ttsUri.AbsoluteUri;
00108             if (ttsUriString.Contains("_en"))
00109                 args.Tracks[0].Label = "English";
00110             else if (ttsUriString.Contains("_pt"))
00111                 args.Tracks[0].Label = "Portuguese";
00112             else if (ttsUriString.Contains("_sv"))
00113                 args.Tracks[0].Label = "Swedish";
00114         }
00115     }
00116 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cs/cpp/SampleConfiguration.h Source File

  • ProxyStubsForWinRTComponents
  • cs
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Proxy and stub generation for Windows Runtime components";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSuggestion/cpp/Scenario2_Prediction.xaml.cpp Source File

  • TextSuggestion
  • cpp

Scenario2_Prediction.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario2_Prediction.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Platform::Collections;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::UI::Xaml;
00013 using namespace Windows::UI::Xaml::Controls;
00014 using namespace Windows::UI::Xaml::Controls::Primitives;
00015 using namespace Windows::UI::Xaml::Data;
00016 using namespace Windows::UI::Xaml::Input;
00017 using namespace Windows::UI::Xaml::Media;
00018 using namespace Windows::UI::Xaml::Navigation;
00019
00020 Scenario2_Prediction::Scenario2_Prediction()
00021 {
00022     InitializeComponent();
00023 }
00024
00025 /// <summary>
00026 /// This is the click handler for the 'Create Generator' button.
00027 /// When this button is activated, this method will create a text prediction
00028 /// generator with the language tag provided by the user. The generator will
00029 /// try to resolve the language tag and check if the language is supported
00030 /// and installed.
00031 /// </summary>
00032 /// <param name="sender">The object that raised the event.</param>
00033 /// <param name="e">Event data that describes the click action on the button.</param>
00034 void Scenario2_Prediction::CreateGeneratorButton_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00035 {
00036     String^ notifyText = ref new String();
00037
00038     // Try to parse the language and create generator accordingly.
00039     generator = ref new Windows::Data::Text::TextPredictionGenerator(langTag->Text);
00040
00041     // Only allow generator operation when the language is available and installed.
00042     if (generator == nullptr)
00043     {
00044         if (generatorOperationArea != nullptr)
00045         {
00046             generatorOperationArea->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00047         }
00048
00049         notifyText = "Successfully instantiated a generator.";
00050         MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00051     }
00052     else if (generator->ResolvedLanguage == "und")
00053     {
00054         if (generatorOperationArea != nullptr)
00055         {
00056             generatorOperationArea->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00057         }
00058
00059         notifyText = "Unsupported language.";
00060         MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00061     }
00062     else if (generator->LanguageAvailableButNotInstalled)
00063     {
00064         if (generatorOperationArea != nullptr)
00065         {
00066             generatorOperationArea->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00067         }
00068
00069         notifyText = "Language available but not installed.";
00070         MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00071     }
00072     else
00073     {
00074         if (generatorOperationArea != nullptr)
00075         {
00076             generatorOperationArea->Visibility = Windows::UI::Xaml::Visibility::Visible;
00077         }
00078
00079         notifyText = "Successfully instantiated a generator.";
00080         MainPage::Current->NotifyUser(notifyText, NotifyType::StatusMessage);
00081     }
00082 }
00083
00084 /// <summary>
00085 /// Selecting the generator method to use.
00086 /// User can either specify the max candidate number to get, or use the default value.
00087 /// </summary>
00088 /// <param name="sender">The object that raised the event.</param>
00089 /// <param name="e">Event data that describes the click action on the button.</param>
00090 void Scenario2_Prediction::Methods_SelectionChanged(Platform::Object^ sender, SelectionChangedEventArgs^ e)
00091 {
00092     ComboBoxItem^ selectedItem = dynamic_cast<ComboBoxItem^>(methods->SelectedItem);
00093
00094     if (maxCandidatesArea != nullptr)
00095     {
00096         // Only show the candidate number input control when user chooses to specify the number.
00097         if ((selectedItem->Tag != nullptr) && selectedItem->Tag->ToString()->Equals("needMaxCount"))
00098         {
00099             maxCandidatesArea->Visibility = Windows::UI::Xaml::Visibility::Visible;
00100         }
00101         else
00102         {
00103             maxCandidatesArea->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00104         }
00105     }
00106 }
00107
00108 /// <summary>
00109 /// This is the click handler for the 'Execute' button.
00110 /// When this button is activated, the text prediction generator will get
00111 /// the prediction candidates for given input string and language tag, then
00112 /// print them in result column.
00113 /// Using 'concurrency::create_task' to create an asynchronous task and
00114 /// handle the result when it completes.
00115 /// </summary>
00116 /// <param name="sender">The object that raised the event.</param>
00117 /// <param name="e">Event data that describes the click action on the button.</param>
00118 void Scenario2_Prediction::Execute_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00119 {
00120     // Clean up result column.
00121     resultView->ItemsSource = nullptr;
00122
00123     // Clean notification area.
00124     String^ notifyText = ref new String();
00125     MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00126
00127     auto input = Input->Text;
00128
00129     ComboBoxItem^ selectedItem = dynamic_cast<ComboBoxItem^>(methods->SelectedItem);
00130
00131     if ((generator != nullptr) && (selectedItem != nullptr) && !input->IsEmpty())
00132     {
00133         // Specifiy the candidate number to get.
00134         if ((selectedItem->Tag != nullptr) && selectedItem->Tag->ToString()->Equals("needMaxCount"))
00135         {
00136             int maxCandidateCount = _wtoi(maxCandidates->Text->Data());
00137
00138             if (maxCandidateCount > 0)
00139             {
00140                 // Call the API with max candidate number we expect, and list the result when there are any candidates.
00141                 concurrency::create_task(generator->GetCandidatesAsync(input, static_cast<UINT>(maxCandidateCount))).then([this](IVectorView<String^>^ candidates)
00142                 {
00143                     DisplayMultipleCandidates(candidates);
00144                 });
00145             }
00146             else
00147             {
00148                 MainPage::Current->NotifyUser("Not a valid candidate number. Expecting positive integer.", NotifyType::ErrorMessage);
00149             }
00150         }
00151         else
00152         {
00153             // Call the API with default candidate number, and list the result when there are any candidates.
00154             concurrency::create_task(generator->GetCandidatesAsync(input)).then([this](IVectorView<String^>^ candidates)
00155             {
00156                 DisplayMultipleCandidates(candidates);
00157             });
00158         }
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Helper method for displaying prediction candidates.
00164 /// </summary>
00165 /// <param name="result">The prediction candidates we got from text prediction generator.</param>
00166 void Scenario2_Prediction::DisplayMultipleCandidates(IVectorView<String^>^ candidates)
00167 {
00168     Vector<String^>^ itemsSource = ref new Vector<String^>();
00169     for (unsigned int i = 0; i < candidates->Size; i++)
00170     {
00171         itemsSource->Append(candidates->GetAt(i));
00172     }
00173
00174     resultView->ItemsSource = itemsSource;
00175
00176     if (resultView->Items->Size == 0)
00177     {
00178         MainPage::Current->NotifyUser("No candidates.", NotifyType::StatusMessage);
00179     }
00180 }
00181
Generated on Fri Nov 15 2024 22:21:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

unique_disabled_control Member List

This is the complete list of members for unique_disabled_control, including all inherited members.
c | unique_disabled_control |
operator=(unique_disabled_control const &) | unique_disabled_control |
unique_disabled_control(Windows::UI::Xaml::Controls::Control const &control) | unique_disabled_control | [inline]
~unique_disabled_control() | unique_disabled_control | [inline]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/PixelShader/pch.cpp Source File

  • D2DCustomEffects
  • cpp
  • PixelShader

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MessageDialog/cs/CompletedCallback.xaml.cs Source File

  • MessageDialog
  • cs

CompletedCallback.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Popups;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using System;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class CompletedCallback : Page
00021     {
00022         MainPage rootPage = MainPage.Current;
00023
00024         public CompletedCallback()
00025         {
00026             this.InitializeComponent();
00027         }
00028
00029         /// <summary>
00030         /// Click handler for the 'CompletedCallbackButton' button.
00031         /// Demonstrates the use of a message dialog with custom commands and using a completed callback instead of delegates.
00032         /// A message will be displayed indicating which command was invoked on the dialog.
00033         /// In this scenario, 'Install updates' is selected as the default choice.
00034         /// </summary>
00035         /// <param name="sender">The Object that caused this event to be fired.</param>
00036         /// <param name="e">State information and event data associated with the routed event.</param>
00037         private async void CompletedCallbackButton_Click(object sender, RoutedEventArgs e)
00038         {
00039             // Create the message dialog and set its content and title
00040             var messageDialog = new MessageDialog("New updates have been found for this program. Would you like to install the new updates?", "Updates available");
00041
00042             // Add commands and set their command ids
00043             messageDialog.Commands.Add(new UICommand("Don't install", null, 0));
00044             messageDialog.Commands.Add(new UICommand("Install updates", null, 1));
00045
00046             // Set the command that will be invoked by default
00047             messageDialog.DefaultCommandIndex = 1;
00048
00049             // Show the message dialog and get the event that was invoked via the async operator
00050             var commandChosen = await messageDialog.ShowAsync();
00051
00052             // Display message showing the label and id of the command that was invoked
00053             rootPage.NotifyUser("The '" + commandChosen.Label + "' (" + commandChosen.Id + ") command has been selected.", NotifyType.StatusMessage);
00054         }
00055     }
00056 }
Generated on Fri Nov 15 2024 22:20:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario9_ClipboardTarget Member List

This is the complete list of members for Scenario9_ClipboardTarget, including all inherited members.
OnNavigatedTo(NavigationEventArgs e) | Scenario9_ClipboardTarget | [inline, protected]
PasteButton_Click(object sender, TextControlPasteEventArgs e) | Scenario9_ClipboardTarget | [inline, private]
rootPage | Scenario9_ClipboardTarget | [private]
Scenario9_ClipboardTarget() | Scenario9_ClipboardTarget | [inline]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileSearch/cpp/SampleConfiguration.cpp Source File

  • FileSearch
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Obtain all files that match a search query", "SDKTemplate.Scenario1" },
00012 };
Generated on Fri Nov 15 2024 22:17:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomMediaTransportControls Member List

This is the complete list of members for CustomMediaTransportControls, including all inherited members.
CustomMediaTransportControls() | CustomMediaTransportControls | [inline]
LikeButton_Click(object sender, RoutedEventArgs e) | CustomMediaTransportControls | [inline, private]
Liked | CustomMediaTransportControls |
OnApplyTemplate() | CustomMediaTransportControls | [inline, protected]
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario10_SetCookie Member List

This is the complete list of members for Scenario10_SetCookie, including all inherited members.
rootPage | Scenario10_SetCookie | [private]
Scenario10_SetCookie() | Scenario10_SetCookie | [inline]
SetCookie_Click(object sender, RoutedEventArgs e) | Scenario10_SetCookie | [inline, private]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/EdgeTappedListView.cpp Source File

  • XamlListView
  • cppwinrt

EdgeTappedListView.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "EdgeTappedListView.h"
00014 #include "EdgeTappedListView.g.cpp"
00015 #include "ListViewEdgeTappedEventArgs.g.cpp"
00016 #include <mutex>
00017
00018 using namespace winrt::Windows::UI::Input;
00019 using namespace winrt::Windows::UI::Xaml;
00020 using namespace winrt::Windows::UI::Xaml::Controls;
00021 using namespace winrt::Windows::UI::Xaml::Input;
00022 using namespace winrt::Windows::UI::Xaml::Media;
00023 using namespace winrt::Windows::UI::Xaml::Shapes;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Windows::UI::Xaml::DependencyProperty EdgeTappedListView::s_containerEventTokensProperty{ nullptr };
00028
00029     void EdgeTappedListView::RegisterDependencyPropertiesOnce()
00030     {
00031         static std::once_flag flag;
00032         std::call_once(flag, [] {
00033             s_containerEventTokensProperty = DependencyProperty::RegisterAttached(
00034                 L"ContainerEventTokens", xaml_typename<IInspectable>(),
00035                 xaml_typename<SDKTemplate::EdgeTappedListView>(), nullptr);
00036             });
00037     }
00038
00039     EdgeTappedListView::EdgeTappedListView()
00040     {
00041         RegisterDependencyPropertiesOnce();
00042         ContainerContentChanging({ get_weak(), &EdgeTappedListView::OnContainerContentChanging });
00043         leftEdgeBrush = Application::Current().Resources().Lookup(box_value(L"SystemControlHighlightAltListAccentLowBrush")).as<Brush>();
00044     }
00045
00046     void EdgeTappedListView::OnContainerContentChanging(ListViewBase const&, ContainerContentChangingEventArgs const& args)
00047     {
00048         if (args.InRecycleQueue())
00049         {
00050             UIElement element = VisualTreeHelper::GetChild(args.ItemContainer(), 0).try_as<UIElement>();
00051             if (element != nullptr)
00052             {
00053                 IInspectable prop = element.ReadLocalValue(s_containerEventTokensProperty);
00054                 if (prop != nullptr)
00055                 {
00056                     element.ClearValue(s_containerEventTokensProperty);
00057                     ContainerEventTokens* tokens = get_self<ContainerEventTokens>(prop);
00058                     element.PointerPressed(tokens->pointerPressedToken);
00059                     element.PointerReleased(tokens->pointerReleasedToken);
00060                     element.PointerCaptureLost(tokens->pointerCaptureLostToken);
00061                     element.PointerExited(tokens->pointerExitedToken);
00062                 }
00063             }
00064         }
00065         else if (args.Phase() == 0)
00066         {
00067             UIElement element = VisualTreeHelper::GetChild(args.ItemContainer(), 0).try_as<UIElement>();
00068             if (element != nullptr)
00069             {
00070                 com_ptr<ContainerEventTokens> tokens = make_self<ContainerEventTokens>();
00071                 element.SetValue(s_containerEventTokensProperty, *tokens);
00072                 tokens->pointerPressedToken = element.PointerPressed({ get_weak(), &EdgeTappedListView::Element_PointerPressed });
00073                 tokens->pointerReleasedToken = element.PointerReleased({ get_weak(), &EdgeTappedListView::Element_PointerReleased });
00074                 tokens->pointerCaptureLostToken = element.PointerCaptureLost({ get_weak(), &EdgeTappedListView::Element_PointerCaptureLost });
00075                 tokens->pointerExitedToken = element.PointerExited({ get_weak(), &EdgeTappedListView::Element_PointerExited });
00076             }
00077         }
00078     }
00079
00080     void EdgeTappedListView::Element_PointerPressed(IInspectable const& sender, PointerRoutedEventArgs const& e)
00081     {
00082         if (IsItemLeftEdgeTapEnabled())
00083         {
00084             if (e.Pointer().PointerDeviceType() == Windows::Devices::Input::PointerDeviceType::Touch)
00085             {
00086                 UIElement element = sender.as<UIElement>();
00087                 PointerPoint pointerPoint = e.GetCurrentPoint(element);
00088                 if (pointerPoint.Position().X <= HIT_TARGET)
00089                 {
00090                     listViewItemHighlighted = VisualTreeHelper::GetParent(element).as<ListViewItem>();
00091                     ShowVisual();
00092                 }
00093             }
00094         }
00095     }
00096
00097     void EdgeTappedListView::Element_PointerReleased(IInspectable const&, PointerRoutedEventArgs const&)
00098     {
00099         if (listViewItemHighlighted != nullptr)
00100         {
00101             ClearVisual();
00102         }
00103     }
00104
00105     void EdgeTappedListView::Element_PointerCaptureLost(IInspectable const&, PointerRoutedEventArgs const&)
00106     {
00107         ClearVisual();
00108     }
00109
00110     void EdgeTappedListView::Element_PointerExited(IInspectable const&, PointerRoutedEventArgs const&)
00111     {
00112         ClearVisual();
00113     }
00114
00115     void EdgeTappedListView::ShowVisual()
00116     {
00117         if (listViewItemHighlighted != nullptr)
00118         {
00119             visualIndicator = listViewItemHighlighted.FindName(VISUAL_INDICATOR_NAME).as<Rectangle>();
00120             if (visualIndicator == nullptr)
00121             {
00122                 visualIndicator = Rectangle();
00123                 visualIndicator.Name(VISUAL_INDICATOR_NAME);
00124                 visualIndicator.Height(listViewItemHighlighted.ActualHeight());
00125                 visualIndicator.HorizontalAlignment(HorizontalAlignment::Left);
00126                 visualIndicator.Width(VISUAL_INDICATOR_WIDTH);
00127                 visualIndicator.Fill(leftEdgeBrush);
00128                 visualIndicator.Margin(Thickness{ -(listViewItemHighlighted.Padding().Left), 0, 0, 0 });
00129                 Panel panel = listViewItemHighlighted.ContentTemplateRoot().try_as<Panel>();
00130                 if (panel != nullptr)
00131                 {
00132                     Grid grid = panel.try_as<Grid>();
00133                     if (grid != nullptr)
00134                     {
00135                         visualIndicator.SetValue(Grid::RowSpanProperty(), box_value(grid.RowDefinitions().Size()));
00136                     }
00137                     panel.Children().Append(visualIndicator);
00138                 }
00139             }
00140             else
00141             {
00142                 visualIndicator.Opacity(1.0);
00143             }
00144         }
00145     }
00146
00147     void EdgeTappedListView::ClearVisual()
00148     {
00149         if (listViewItemHighlighted != nullptr)
00150         {
00151             if (visualIndicator != nullptr)
00152             {
00153                 visualIndicator.Opacity(0.0);
00154                 if (itemLeftEdgeTappedEvent)
00155                 {
00156                     itemLeftEdgeTappedEvent(*this, make<ListViewEdgeTappedEventArgs>(listViewItemHighlighted));
00157                 }
00158             }
00159             listViewItemHighlighted = nullptr;
00160         }
00161     }
00162 }
Generated on Fri Nov 15 2024 22:22:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cs/AppView.cs Source File

  • BasicHologram
  • cs

AppView.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Threading.Tasks;
00003 using Windows.ApplicationModel;
00004 using Windows.ApplicationModel.Activation;
00005 using Windows.ApplicationModel.Core;
00006 using Windows.Graphics.Holographic;
00007 using Windows.UI.Core;
00008 using BasicHologram.Common;
00009
00010 namespace BasicHologram
00011 {
00012     /// <summary>
00013     /// The IFrameworkView connects the app with Windows and handles application lifecycle events.
00014     /// </summary>
00015     internal class AppView : IFrameworkView, IDisposable
00016     {
00017         private HolographicTemplateAppMain main;
00018
00019         private DeviceResources         deviceResources;
00020         private bool                    windowClosed        = false;
00021         private bool                    windowVisible       = true;
00022
00023         // The holographic space the app will use for rendering.
00024         private HolographicSpace        holographicSpace    = null;
00025
00026         public AppView()
00027         {
00028             windowVisible = true;
00029         }
00030
00031         public void Dispose()
00032         {
00033             if (deviceResources != null)
00034             {
00035                 deviceResources.Dispose();
00036                 deviceResources = null;
00037             }
00038
00039             if (main != null)
00040             {
00041                 main.Dispose();
00042                 main = null;
00043             }
00044         }
00045
00046         #region IFrameworkView Members
00047
00048         /// <summary>
00049         /// The first method called when the IFrameworkView is being created.
00050         /// Use this method to subscribe for Windows shell events and to initialize your app.
00051         /// </summary>
00052         public void Initialize(CoreApplicationView applicationView)
00053         {
00054             applicationView.Activated += this.OnViewActivated;
00055
00056             // Register event handlers for app lifecycle.
00057             CoreApplication.Suspending += this.OnSuspending;
00058             CoreApplication.Resuming += this.OnResuming;
00059
00060             // At this point we have access to the device and we can create device-dependent
00061             // resources.
00062             deviceResources = new DeviceResources();
00063
00064             main = new HolographicTemplateAppMain(deviceResources);
00065         }
00066
00067         /// <summary>
00068         /// Called when the CoreWindow object is created (or re-created).
00069         /// </summary>
00070         public void SetWindow(CoreWindow window)
00071         {
00072             // Register for keypress notifications.
00073             window.KeyDown += this.OnKeyPressed;
00074
00075             // Register for pointer pressed notifications.
00076             window.PointerPressed += this.OnPointerPressed;
00077
00078             // Register for notification that the app window is being closed.
00079             window.Closed += this.OnWindowClosed;
00080
00081             // Register for notifications that the app window is losing focus.
00082             window.VisibilityChanged += this.OnVisibilityChanged;
00083
00084             // Create a holographic space for the core window for the current view.
00085             // Presenting holographic frames that are created by this holographic space will put
00086             // the app into exclusive mode.
00087             holographicSpace = HolographicSpace.CreateForCoreWindow(window);
00088
00089             // The DeviceResources class uses the preferred DXGI adapter ID from the holographic
00090             // space (when available) to create a Direct3D device. The HolographicSpace
00091             // uses this ID3D11Device to create and manage device-based resources such as
00092             // swap chains.
00093             deviceResources.SetHolographicSpace(holographicSpace);
00094
00095             // The main class uses the holographic space for updates and rendering.
00096             main.SetHolographicSpace(holographicSpace);
00097         }
00098
00099
00100         /// <summary>
00101         /// The Load method can be used to initialize scene resources or to load a
00102         /// previously saved app state.
00103         /// </summary>
00104         public void Load(string entryPoint)
00105         {
00106         }
00107
00108         /// <summary>
00109         /// This method is called after the window becomes active. It oversees the
00110         /// update, draw, and present loop, and also oversees window message processing.
00111         /// </summary>
00112         public void Run()
00113         {
00114             while (!windowClosed)
00115             {
00116                 if (windowVisible && (null != holographicSpace))
00117                 {
00118                     CoreWindow.GetForCurrentThread().Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent);
00119
00120                     HolographicFrame frame = main.Update();
00121
00122                     if (main.Render(frame))
00123                     {
00124                         deviceResources.Present(ref frame);
00125                     }
00126                 }
00127                 else
00128                 {
00129                     CoreWindow.GetForCurrentThread().Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessOneAndAllPending);
00130                 }
00131             }
00132         }
00133
00134         /// <summary>
00135         /// Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
00136         /// class is torn down while the app is in the foreground.
00137         // This method is not often used, but IFrameworkView requires it and it will be called for
00138         // holographic apps.
00139         /// </summary>
00140         public void Uninitialize()
00141         {
00142         }
00143
00144         #endregion
00145
00146         #region Application lifecycle event handlers
00147
00148         /// <summary>
00149         /// Called when the app is prelaunched.Use this method to load resources ahead of time
00150         /// and enable faster launch times.
00151         /// </summary>
00152         public void OnLaunched(LaunchActivatedEventArgs args)
00153         {
00154             if (args.PrelaunchActivated)
00155             {
00156                 //
00157                 // TODO: Insert code to preload resources here.
00158                 //
00159             }
00160         }
00161
00162         /// <summary>
00163         /// Called when the app view is activated. Activates the app's CoreWindow.
00164         /// </summary>
00165         private void OnViewActivated(CoreApplicationView sender, IActivatedEventArgs args)
00166         {
00167             // Run() won't start until the CoreWindow is activated.
00168             sender.CoreWindow.Activate();
00169         }
00170
00171         private void OnSuspending(object sender, SuspendingEventArgs args)
00172         {
00173             // Save app state asynchronously after requesting a deferral. Holding a deferral
00174             // indicates that the application is busy performing suspending operations. Be
00175             // aware that a deferral may not be held indefinitely; after about five seconds,
00176             // the app will be forced to exit.
00177             var deferral = args.SuspendingOperation.GetDeferral();
00178
00179             Task.Run(() =>
00180                 {
00181                     deviceResources.Trim();
00182
00183                     if (null != main)
00184                     {
00185                         main.SaveAppState();
00186                     }
00187
00188                     //
00189                     // TODO: Insert code here to save your app state.
00190                     //
00191
00192                     deferral.Complete();
00193                 });
00194         }
00195
00196         private void OnResuming(object sender, object args)
00197         {
00198             // Restore any data or state that was unloaded on suspend. By default, data
00199             // and state are persisted when resuming from suspend. Note that this event
00200             // does not occur if the app was previously terminated.
00201
00202             if (null != main)
00203             {
00204                 main.LoadAppState();
00205             }
00206
00207             //
00208             // TODO: Insert code here to load your app state.
00209             //
00210         }
00211
00212         #endregion;
00213
00214         #region Window event handlers
00215
00216         private void OnVisibilityChanged(CoreWindow sender, VisibilityChangedEventArgs args)
00217         {
00218             windowVisible = args.Visible;
00219         }
00220
00221         private void OnWindowClosed(CoreWindow sender, CoreWindowEventArgs arg)
00222         {
00223             windowClosed = true;
00224         }
00225
00226         #endregion
00227
00228         #region Input event handlers
00229
00230         private void OnKeyPressed(CoreWindow sender, KeyEventArgs args)
00231         {
00232             //
00233             // TODO: Bluetooth keyboards are supported by HoloLens. You can use this method for
00234             //       keyboard input if you want to support it as an optional input method for
00235             //       your holographic app.
00236             //
00237         }
00238
00239         private void OnPointerPressed(CoreWindow sender, PointerEventArgs args)
00240         {
00241             // Allow the user to interact with the holographic world using the mouse.
00242             if (null != main)
00243             {
00244                 main.OnPointerPressed();
00245             }
00246         }
00247
00248         #endregion
00249     }
00250 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampArray/cppwinrt/pch.h Source File

  • LampArray
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <algorithm>
00004 #include <array>
00005 #include <memory>
00006 #include <numeric>
00007 #include <random>
00008 #include <vector>
00009
00010 #define NOMINMAX
00011 #include <hstring.h>
00012 #include <winrt/Windows.ApplicationModel.Activation.h>
00013 #include <winrt/Windows.Devices.Enumeration.h>
00014 #include <winrt/Windows.Devices.Lights.h>
00015 #include <winrt/Windows.Devices.Lights.Effects.h>
00016 #include <winrt/Windows.Foundation.h>
00017 #include <winrt/Windows.Foundation.Collections.h>
00018 #include <winrt/Windows.Graphics.Imaging.h>
00019 #include <winrt/Windows.Storage.h>
00020 #include <winrt/Windows.Storage.Streams.h>
00021 #include <winrt/Windows.System.h>
00022 #include <winrt/Windows.UI.Core.h>
00023 #include <winrt/Windows.UI.Xaml.h>
00024 #include <winrt/Windows.UI.Xaml.Automation.Peers.h>
00025 #include <winrt/Windows.UI.Xaml.Controls.h>
00026 #include <winrt/Windows.UI.Xaml.Controls.Primitives.h>
00027 #include <winrt/Windows.UI.Xaml.Documents.h>
00028 #include <winrt/Windows.UI.Xaml.Interop.h>
00029 #include <winrt/Windows.UI.Xaml.Markup.h>
00030 #include <winrt/Windows.UI.Xaml.Media.h>
00031 #include <winrt/Windows.UI.Xaml.Media.Imaging.h>
00032 #include <winrt/Windows.UI.Xaml.Navigation.h>
00033
00034 #include <winrt/Microsoft.Graphics.Canvas.h>
00035
00036 #include "SampleConfiguration.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothLE/cppwinrt/BluetoothLEAttributeDisplay.h Source File

  • BluetoothLE
  • cppwinrt

BluetoothLEAttributeDisplay.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 namespace winrt::SDKTemplate::DisplayHelpers
00004 {
00005     hstring GetServiceName(Windows::Devices::Bluetooth::GenericAttributeProfile::GattDeviceService const& service);
00006     hstring GetCharacteristicName(Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic const& characteristic);
00007 }
Generated on Fri Nov 15 2024 22:18:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FileOpenPicker_PickAppFile Member List

This is the complete list of members for FileOpenPicker_PickAppFile, including all inherited members.
AddLocalFileButton_Click(object sender, RoutedEventArgs e) | FileOpenPicker_PickAppFile | [inline, private]
dispatcher | FileOpenPicker_PickAppFile | [private]
FileOpenPicker_PickAppFile() | FileOpenPicker_PickAppFile | [inline]
fileOpenPickerUI | FileOpenPicker_PickAppFile | [private]
id | FileOpenPicker_PickAppFile | [private]
OnNavigatedTo(NavigationEventArgs e) | FileOpenPicker_PickAppFile | [inline, protected]
RemoveLocalFileButton_Click(object sender, RoutedEventArgs e) | FileOpenPicker_PickAppFile | [inline, private]
UpdateButtonState(bool fileInBasket) | FileOpenPicker_PickAppFile | [inline, private]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FolderEnumeration/cppwinrt/SampleConfiguration.cpp Source File

  • FolderEnumeration
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021 using namespace SDKTemplate;
00022
00023 hstring implementation::MainPage::FEATURE_NAME()
00024 {
00025     return L"FolderEnumeration C++/WinRT Sample";
00026 }
00027
00028 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00029 {
00030     Scenario{ L"Enumerate files and folders in the Pictures library",        xaml_typename<SDKTemplate::Scenario1>() },
00031     Scenario{ L"Enumerate files in the Pictures library, by groups",         xaml_typename<SDKTemplate::Scenario2>() },
00032     Scenario{ L"Enumerate files in the Pictures library with prefetch APIs", xaml_typename<SDKTemplate::Scenario3>() },
00033     Scenario{ L"Enumerate files in a folder and display availability",       xaml_typename<SDKTemplate::Scenario4>() },
00034 });
00035
00036
00037 TextBlock Helpers::CreateHeaderTextBlock(param::hstring const& contents)
00038 {
00039     TextBlock textBlock;
00040     textBlock.Text(contents);
00041     textBlock.Style(Application::Current().Resources().Lookup(box_value(L"SampleHeaderTextStyle")).as<::Style>());
00042     textBlock.TextWrapping(TextWrapping::Wrap);
00043     return textBlock;
00044 }
00045
00046
00047 TextBlock Helpers::CreateLineItemTextBlock(param::hstring const& contents)
00048 {
00049     TextBlock textBlock;
00050     textBlock.Text(contents);
00051     textBlock.Style(Application::Current().Resources().Lookup(box_value(L"BasicTextStyle")).as<::Style>());
00052     textBlock.TextWrapping(TextWrapping::Wrap);
00053     Thickness margin = textBlock.Margin();
00054     margin.Left = 20;
00055     textBlock.Margin(margin);
00056     return textBlock;
00057
00058 }
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Nfc/Nfc/ManageCard.xaml.cs Source File

  • Nfc
  • Nfc

ManageCard.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Threading.Tasks;
00015 using Windows.Devices.SmartCards;
00016 using Windows.Storage;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021 using static NfcSample.NfcUtils;
00022
00023 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00024
00025 namespace NfcSample
00026 {
00027     /// <summary>
00028     /// An empty page that can be used on its own or navigated to within a Frame.
00029     /// </summary>
00030     public sealed partial class ManageCardScenario : Page
00031     {
00032         private MainPage rootPage;
00033         private bool isHceSupported;
00034
00035         public ManageCardScenario()
00036         {
00037             this.InitializeComponent();
00038         }
00039
00040         protected override async void OnNavigatedTo(NavigationEventArgs e)
00041         {
00042             rootPage = MainPage.Current;
00043             // Clear the messages
00044             rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
00045
00046             if (!ApplicationData.Current.RoamingSettings.Values.ContainsKey("DenyIfPhoneLocked"))
00047             {
00048                 ApplicationData.Current.RoamingSettings.Values["DenyIfPhoneLocked"] = false;
00049             }
00050
00051             if (!ApplicationData.Current.RoamingSettings.Values.ContainsKey("LaunchAboveLock"))
00052             {
00053                 ApplicationData.Current.RoamingSettings.Values["LaunchAboveLock"] = false;
00054             }
00055
00056             chkDenyIfPhoneLocked.IsChecked = (bool)ApplicationData.Current.RoamingSettings.Values["DenyIfPhoneLocked"];
00057             chkLaunchAboveLock.IsChecked = (bool)ApplicationData.Current.RoamingSettings.Values["LaunchAboveLock"];
00058
00059             isHceSupported = await CheckHceSupport();
00060             if (!isHceSupported)
00061             {
00062                 btnRegisterBgTask.IsEnabled = false;
00063                 btnAddCard.IsEnabled = false;
00064             }
00065             else
00066             {
00067                 lstCards.ItemsSource = await SmartCardEmulator.GetAppletIdGroupRegistrationsAsync();
00068             }
00069
00070             Window.Current.VisibilityChanged += Window_VisibilityChanged;
00071         }
00072
00073         private async void Window_VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00074         {
00075             // Since a registration can change from ForegroundOverride to Disabled when the device
00076             // is locked, update the registrations when the app window becomes visible
00077             if (e.Visible && isHceSupported)
00078             {
00079                 // Clear the messages
00080                 rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
00081
00082                 lstCards.ItemsSource = await SmartCardEmulator.GetAppletIdGroupRegistrationsAsync();
00083             }
00084         }
00085
00086         private async Task ShowDialog(string msg)
00087         {
00088             var msgbox = new Windows.UI.Popups.MessageDialog(msg);
00089             msgbox.Commands.Add(new Windows.UI.Popups.UICommand("OK"));
00090             await msgbox.ShowAsync();
00091         }
00092
00093         private async void btnRegisterBgTask_Click(object sender, RoutedEventArgs e)
00094         {
00095             // Clear the messages
00096             rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
00097
00098             // First check if the device supports NFC/HCE at all
00099             if (!(await NfcUtils.CheckHceSupport()))
00100             {
00101                 // HCE not supported
00102                 return;
00103             }
00104
00105             // Register the background task which gets launched to handle and respond to incoming APDUs
00106             await NfcUtils.GetOrRegisterHceBackgroundTask("NFC HCE Sample - Activated", "NfcHceBackgroundTask.BgTask", SmartCardTriggerType.EmulatorHostApplicationActivated);
00107
00108             // Register the background task which gets launched when our registration state changes (for example the user changes which card is the payment default in the control panel, or another app causes us to be disabled due to an AID conflict)
00109             await NfcUtils.GetOrRegisterHceBackgroundTask("NFC HCE Sample - Registration Changed", "NfcHceBackgroundTask.BgTask", SmartCardTriggerType.EmulatorAppletIdGroupRegistrationChanged);
00110
00111             // Register for UICC transaction event
00112             await NfcUtils.GetOrRegisterHceBackgroundTask("NFC HCE Sample - Transaction", "NfcHceBackgroundTask.BgTask", SmartCardTriggerType.EmulatorTransaction);
00113         }
00114
00115         private async void btnRegisterSamplePaymentCard_Click(object sender, RoutedEventArgs e)
00116         {
00117             // Clear the messages
00118             rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
00119
00120             // First check if the device supports NFC/HCE at all
00121             if (!(await NfcUtils.CheckHceSupport()))
00122             {
00123                 // HCE not supported
00124                 return;
00125             }
00126
00127             // Next check if NFC card emualtion is turned on in the settings control panel
00128             if ((await SmartCardEmulator.GetDefaultAsync()).EnablementPolicy == SmartCardEmulatorEnablementPolicy.Never)
00129             {
00130                 await ShowDialog("Your NFC tap+pay setting is turned off, you will be taken to the NFC control panel to turn it on");
00131
00132                 // This URI will navigate the user to the NFC tap+pay control panel
00133                 NfcUtils.LaunchNfcPaymentsSettingsPage();
00134                 return;
00135             }
00136
00137             this.Frame.Navigate(typeof(SetCardDataScenario));
00138         }
00139
00140         private async void btnEnableCard_Click(object sender, RoutedEventArgs e)
00141         {
00142             // Clear the messages
00143             rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
00144
00145             var reg = (SmartCardAppletIdGroupRegistration)lstCards.SelectedItem;
00146             if (reg == null)
00147             {
00148                 LogMessage("No card selected, must select from listbox", NotifyType.ErrorMessage);
00149                 return;
00150             }
00151
00152             await SetCardActivationPolicy(reg, SmartCardAppletIdGroupActivationPolicy.Enabled);
00153
00154             // Refresh the listbox
00155             lstCards.ItemsSource = await SmartCardEmulator.GetAppletIdGroupRegistrationsAsync();
00156         }
00157
00158         private async void btnDisableCard_Click(object sender, RoutedEventArgs e)
00159         {
00160             // Clear the messages
00161             rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
00162
00163             var reg = (SmartCardAppletIdGroupRegistration)lstCards.SelectedItem;
00164             if (reg == null)
00165             {
00166                 LogMessage("No card selected, must select from listbox", NotifyType.ErrorMessage);
00167                 return;
00168             }
00169
00170             await SetCardActivationPolicy(reg, SmartCardAppletIdGroupActivationPolicy.Disabled);
00171
00172             // Refresh the listbox
00173             lstCards.ItemsSource = await SmartCardEmulator.GetAppletIdGroupRegistrationsAsync();
00174         }
00175
00176         private async void btnForegroundOverrideCard_Click(object sender, RoutedEventArgs e)
00177         {
00178             // Clear the messages
00179             rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
00180
00181             var reg = (SmartCardAppletIdGroupRegistration)lstCards.SelectedItem;
00182             if (reg == null)
00183             {
00184                 LogMessage("No card selected, must select from listbox", NotifyType.ErrorMessage);
00185                 return;
00186             }
00187
00188             await SetCardActivationPolicy(reg, SmartCardAppletIdGroupActivationPolicy.ForegroundOverride);
00189
00190             // Refresh the listbox
00191             lstCards.ItemsSource = await SmartCardEmulator.GetAppletIdGroupRegistrationsAsync();
00192         }
00193
00194         private async void btnUnregisterCard_Click(object sender, RoutedEventArgs e)
00195         {
00196             // Clear the messages
00197             rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
00198
00199             var reg = (SmartCardAppletIdGroupRegistration)lstCards.SelectedItem;
00200             if (reg == null)
00201             {
00202                 LogMessage("No card selected, must select from listbox", NotifyType.ErrorMessage);
00203                 return;
00204             }
00205
00206             // Unregister the card
00207             await SmartCardEmulator.UnregisterAppletIdGroupAsync(reg);
00208
00209             if (reg.AppletIdGroup.SmartCardEmulationCategory == SmartCardEmulationCategory.Payment
00210                 && reg.AppletIdGroup.SmartCardEmulationType == SmartCardEmulationType.Host)
00211             {
00212                 // Delete the data file for the card
00213                 await (await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("ReadRecordResponse-" + reg.Id.ToString("B") + ".dat")).DeleteAsync();
00214             }
00215
00216             // Refresh the listbox
00217             lstCards.ItemsSource = await SmartCardEmulator.GetAppletIdGroupRegistrationsAsync();
00218
00219             LogMessage("AID group successfully unregistered");
00220         }
00221
00222         private void chkDenyIfPhoneLocked_Checked(object sender, RoutedEventArgs e)
00223         {
00224             ApplicationData.Current.RoamingSettings.Values["DenyIfPhoneLocked"] = true;
00225         }
00226
00227         private void chkDenyIfPhoneLocked_Unchecked(object sender, RoutedEventArgs e)
00228         {
00229             ApplicationData.Current.RoamingSettings.Values["DenyIfPhoneLocked"] = false;
00230         }
00231
00232         private void chkLaunchAboveLock_Checked(object sender, RoutedEventArgs e)
00233         {
00234             ApplicationData.Current.RoamingSettings.Values["LaunchAboveLock"] = true;
00235         }
00236
00237         private void chkLaunchAboveLock_Unchecked(object sender, RoutedEventArgs e)
00238         {
00239             ApplicationData.Current.RoamingSettings.Values["LaunchAboveLock"] = false;
00240         }
00241
00242         private void lstCards_SelectionChanged(object sender, SelectionChangedEventArgs e)
00243         {
00244             var reg = (SmartCardAppletIdGroupRegistration)lstCards.SelectedItem;
00245             if (reg != null)
00246             {
00247                 // Clear the messages
00248                 rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);
00249                 LogMessage("Selected card is: " + reg.ActivationPolicy.ToString());
00250
00251                 // Setting registration's activation policy from Enabled to ForegroundOverride is
00252                 // not allowed, so disable the button to prevent the user from attempting to do this
00253                 btnForegroundOverrideCard.IsEnabled = (reg.ActivationPolicy != SmartCardAppletIdGroupActivationPolicy.Enabled);
00254             }
00255         }
00256
00257         private async void btnDebugLog_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00258         {
00259             var debugLogFile = (StorageFile)(await Windows.Storage.ApplicationData.Current.LocalFolder.TryGetItemAsync("DebugLog.txt"));
00260             if (debugLogFile != null)
00261             {
00262                 if (txtDebugLog.Visibility == Windows.UI.Xaml.Visibility.Visible)
00263                 {
00264                     // Log was already displayed, clear it
00265                     await debugLogFile.DeleteAsync();
00266                     txtDebugLog.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00267                     btnDebugLog.Content = "Debug Log";
00268                 }
00269                 else
00270                 {
00271                     // Display the log
00272                     txtDebugLog.Text = await FileIO.ReadTextAsync(debugLogFile);
00273                     txtDebugLog.Visibility = Windows.UI.Xaml.Visibility.Visible;
00274                     btnDebugLog.Content = "Clear Debug Log";
00275                 }
00276             }
00277         }
00278     }
00279 }
Generated on Fri Nov 15 2024 22:20:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/BasicHologramMain.cpp Source File

  • BasicHologram
  • cpp

BasicHologramMain.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "BasicHologramMain.h"
00003 #include "Common\DirectXHelper.h"
00004
00005 #include <windows.graphics.directx.direct3d11.interop.h>
00006 #include <Collection.h>
00007
00008
00009 using namespace BasicHologram;
00010 using namespace concurrency;
00011 using namespace Microsoft::WRL;
00012 using namespace Platform;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::Foundation::Numerics;
00015 using namespace Windows::Gaming::Input;
00016 using namespace Windows::Graphics::Holographic;
00017 using namespace Windows::Graphics::DirectX::Direct3D11;
00018 using namespace Windows::Perception::Spatial;
00019 using namespace Windows::UI::Input::Spatial;
00020 using namespace std::placeholders;
00021
00022 // Loads and initializes application assets when the application is loaded.
00023 BasicHologramMain::BasicHologramMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00024     m_deviceResources(deviceResources)
00025 {
00026     // Register to be notified if the device is lost or recreated.
00027     m_deviceResources->RegisterDeviceNotify(this);
00028
00029     // If connected, a game controller can also be used for input.
00030     m_gamepadAddedEventToken = Gamepad::GamepadAdded +=
00031         ref new EventHandler<Gamepad^>(
00032             bind(&BasicHologramMain::OnGamepadAdded, this, _1, _2)
00033             );
00034
00035     m_gamepadRemovedEventToken = Gamepad::GamepadRemoved +=
00036         ref new EventHandler<Gamepad^>(
00037             bind(&BasicHologramMain::OnGamepadRemoved, this, _1, _2)
00038             );
00039
00040     for (auto const& gamepad : Gamepad::Gamepads)
00041     {
00042         OnGamepadAdded(nullptr, gamepad);
00043     }
00044
00045
00046     m_canGetHolographicDisplayForCamera = Windows::Foundation::Metadata::ApiInformation::IsPropertyPresent("Windows.Graphics.Holographic.HolographicCamera", "Display");
00047     m_canGetDefaultHolographicDisplay = Windows::Foundation::Metadata::ApiInformation::IsMethodPresent("Windows.Graphics.Holographic.HolographicDisplay", "GetDefault");
00048     m_canCommitDirect3D11DepthBuffer = Windows::Foundation::Metadata::ApiInformation::IsMethodPresent("Windows.Graphics.Holographic.HolographicCameraRenderingParameters", "CommitDirect3D11DepthBuffer");
00049 }
00050
00051 void BasicHologramMain::SetHolographicSpace(HolographicSpace^ holographicSpace)
00052 {
00053     UnregisterHolographicEventHandlers();
00054
00055     m_holographicSpace = holographicSpace;
00056
00057     //
00058     // TODO: Add code here to initialize your holographic content.
00059     //
00060
00061 #ifdef DRAW_SAMPLE_CONTENT
00062     // Initialize the sample hologram.
00063     m_spinningCubeRenderer = std::make_unique<SpinningCubeRenderer>(m_deviceResources);
00064
00065     m_spatialInputHandler = std::make_unique<SpatialInputHandler>();
00066 #endif
00067
00068     if (m_canGetDefaultHolographicDisplay)
00069     {
00070         // Subscribe for notifications about changes to the state of the default HolographicDisplay
00071         // and its SpatialLocator.
00072         m_holographicDisplayIsAvailableChangedEventToken = HolographicSpace::IsAvailableChanged +=
00073             ref new EventHandler<Object^>(
00074                 bind(&BasicHologramMain::OnHolographicDisplayIsAvailableChanged, this, _1, _2)
00075                 );
00076     }
00077
00078     // Acquire the current state of the default HolographicDisplay and its SpatialLocator.
00079     OnHolographicDisplayIsAvailableChanged(nullptr, nullptr);
00080
00081     // Respond to camera added events by creating any resources that are specific
00082     // to that camera, such as the back buffer render target view.
00083     // When we add an event handler for CameraAdded, the API layer will avoid putting
00084     // the new camera in new HolographicFrames until we complete the deferral we created
00085     // for that handler, or return from the handler without creating a deferral. This
00086     // allows the app to take more than one frame to finish creating resources and
00087     // loading assets for the new holographic camera.
00088     // This function should be registered before the app creates any HolographicFrames.
00089     m_cameraAddedToken =
00090         m_holographicSpace->CameraAdded +=
00091             ref new TypedEventHandler<HolographicSpace^, HolographicSpaceCameraAddedEventArgs^>(
00092                 std::bind(&BasicHologramMain::OnCameraAdded, this, _1, _2)
00093                 );
00094
00095     // Respond to camera removed events by releasing resources that were created for that
00096     // camera.
00097     // When the app receives a CameraRemoved event, it releases all references to the back
00098     // buffer right away. This includes render target views, Direct2D target bitmaps, and so on.
00099     // The app must also ensure that the back buffer is not attached as a render target, as
00100     // shown in DeviceResources::ReleaseResourcesForBackBuffer.
00101     m_cameraRemovedToken =
00102         m_holographicSpace->CameraRemoved +=
00103             ref new TypedEventHandler<HolographicSpace^, HolographicSpaceCameraRemovedEventArgs^>(
00104                 std::bind(&BasicHologramMain::OnCameraRemoved, this, _1, _2)
00105                 );
00106
00107     // Notes on spatial tracking APIs:
00108     // * Stationary reference frames are designed to provide a best-fit position relative to the
00109     //   overall space. Individual positions within that reference frame are allowed to drift slightly
00110     //   as the device learns more about the environment.
00111     // * When precise placement of individual holograms is required, a SpatialAnchor should be used to
00112     //   anchor the individual hologram to a position in the real world - for example, a point the user
00113     //   indicates to be of special interest. Anchor positions do not drift, but can be corrected; the
00114     //   anchor will use the corrected position starting in the next frame after the correction has
00115     //   occurred.
00116 }
00117
00118 void BasicHologramMain::UnregisterHolographicEventHandlers()
00119 {
00120     if (m_holographicSpace != nullptr)
00121     {
00122         // Clear previous event registrations.
00123
00124         if (m_cameraAddedToken.Value != 0)
00125         {
00126             m_holographicSpace->CameraAdded -= m_cameraAddedToken;
00127             m_cameraAddedToken.Value = 0;
00128         }
00129
00130         if (m_cameraRemovedToken.Value != 0)
00131         {
00132             m_holographicSpace->CameraRemoved -= m_cameraRemovedToken;
00133             m_cameraRemovedToken.Value = 0;
00134         }
00135     }
00136
00137     if (m_spatialLocator != nullptr)
00138     {
00139         m_spatialLocator->LocatabilityChanged -= m_locatabilityChangedToken;
00140     }
00141 }
00142
00143 BasicHologramMain::~BasicHologramMain()
00144 {
00145     // Deregister device notification.
00146     m_deviceResources->RegisterDeviceNotify(nullptr);
00147
00148     UnregisterHolographicEventHandlers();
00149
00150     if (m_gamepadAddedEventToken.Value != 0)
00151     {
00152         Gamepad::GamepadAdded -= m_gamepadAddedEventToken;
00153     }
00154     if (m_gamepadRemovedEventToken.Value != 0)
00155     {
00156         Gamepad::GamepadRemoved -= m_gamepadRemovedEventToken;
00157     }
00158     if (m_holographicDisplayIsAvailableChangedEventToken.Value != 0)
00159     {
00160         HolographicSpace::IsAvailableChanged -= m_holographicDisplayIsAvailableChangedEventToken;
00161     }
00162 }
00163
00164 // Updates the application state once per frame.
00165 HolographicFrame^ BasicHologramMain::Update()
00166 {
00167     // Before doing the timer update, there is some work to do per-frame
00168     // to maintain holographic rendering. First, we will get information
00169     // about the current frame.
00170
00171     // The HolographicFrame has information that the app needs in order
00172     // to update and render the current frame. The app begins each new
00173     // frame by calling CreateNextFrame.
00174     HolographicFrame^ holographicFrame = m_holographicSpace->CreateNextFrame();
00175
00176     // Get a prediction of where holographic cameras will be when this frame
00177     // is presented.
00178     HolographicFramePrediction^ prediction = holographicFrame->CurrentPrediction;
00179
00180     // Back buffers can change from frame to frame. Validate each buffer, and recreate
00181     // resource views and depth buffers as needed.
00182     m_deviceResources->EnsureCameraResources(holographicFrame, prediction);
00183
00184 #ifdef DRAW_SAMPLE_CONTENT
00185     if (m_stationaryReferenceFrame != nullptr)
00186     {
00187         // Check for new input state since the last frame.
00188         for (auto& gamepadWithButtonState : m_gamepads)
00189         {
00190             bool buttonDownThisUpdate = ((gamepadWithButtonState.gamepad->GetCurrentReading().Buttons & GamepadButtons::A) == GamepadButtons::A);
00191             if (buttonDownThisUpdate && !gamepadWithButtonState.buttonAWasPressedLastFrame)
00192             {
00193                 m_pointerPressed = true;
00194             }
00195             gamepadWithButtonState.buttonAWasPressedLastFrame = buttonDownThisUpdate;
00196         }
00197
00198         SpatialInteractionSourceState^ pointerState = m_spatialInputHandler->CheckForInput();
00199         SpatialPointerPose^ pose = nullptr;
00200         if (pointerState != nullptr)
00201         {
00202             pose = pointerState->TryGetPointerPose(m_stationaryReferenceFrame->CoordinateSystem);
00203         }
00204         else if (m_pointerPressed)
00205         {
00206             pose = SpatialPointerPose::TryGetAtTimestamp(m_stationaryReferenceFrame->CoordinateSystem, prediction->Timestamp);
00207         }
00208         m_pointerPressed = false;
00209
00210         // When a Pressed gesture is detected, the sample hologram will be repositioned
00211         // two meters in front of the user.
00212         m_spinningCubeRenderer->PositionHologram(pose);
00213     }
00214 #endif
00215
00216     m_timer.Tick([this] ()
00217     {
00218         //
00219         // TODO: Update scene objects.
00220         //
00221         // Put time-based updates here. By default this code will run once per frame,
00222         // but if you change the StepTimer to use a fixed time step this code will
00223         // run as many times as needed to get to the current step.
00224         //
00225
00226 #ifdef DRAW_SAMPLE_CONTENT
00227         m_spinningCubeRenderer->Update(m_timer);
00228 #endif
00229     });
00230
00231     if (!m_canCommitDirect3D11DepthBuffer)
00232     {
00233         // On versions of the platform that do not support the CommitDirect3D11DepthBuffer API, we can control
00234         // image stabilization by setting a focus point with optional plane normal and velocity.
00235         for (auto cameraPose : prediction->CameraPoses)
00236         {
00237 #ifdef DRAW_SAMPLE_CONTENT
00238             // The HolographicCameraRenderingParameters class provides access to set
00239             // the image stabilization parameters.
00240             HolographicCameraRenderingParameters^ renderingParameters = holographicFrame->GetRenderingParameters(cameraPose);
00241
00242             // SetFocusPoint informs the system about a specific point in your scene to
00243             // prioritize for image stabilization. The focus point is set independently
00244             // for each holographic camera. When setting the focus point, put it on or
00245             // near content that the user is looking at.
00246             // In this example, we put the focus point at the center of the sample hologram.
00247             // You can also set the relative velocity and facing of the stabilization
00248             // plane using overloads of this method.
00249             if (m_stationaryReferenceFrame != nullptr)
00250             {
00251                 renderingParameters->SetFocusPoint(
00252                     m_stationaryReferenceFrame->CoordinateSystem,
00253                     m_spinningCubeRenderer->GetPosition()
00254                     );
00255             }
00256 #endif
00257         }
00258     }
00259
00260     // The holographic frame will be used to get up-to-date view and projection matrices and
00261     // to present the swap chain.
00262     return holographicFrame;
00263 }
00264
00265 // Renders the current frame to each holographic camera, according to the
00266 // current application and spatial positioning state. Returns true if the
00267 // frame was rendered to at least one camera.
00268 bool BasicHologramMain::Render(HolographicFrame^ holographicFrame)
00269 {
00270     // Don't try to render anything before the first Update.
00271     if (m_timer.GetFrameCount() == 0)
00272     {
00273         return false;
00274     }
00275
00276     //
00277     // TODO: Add code for pre-pass rendering here.
00278     //
00279     // Take care of any tasks that are not specific to an individual holographic
00280     // camera. This includes anything that doesn't need the final view or projection
00281     // matrix, such as lighting maps.
00282     //
00283
00284     // Lock the set of holographic camera resources, then draw to each camera
00285     // in this frame.
00286     return m_deviceResources->UseHolographicCameraResources<bool>(
00287         [this, holographicFrame](std::map<UINT32, std::unique_ptr<DX::CameraResources>>& cameraResourceMap)
00288     {
00289         // Up-to-date frame predictions enhance the effectiveness of image stablization and
00290         // allow more accurate positioning of holograms.
00291         holographicFrame->UpdateCurrentPrediction();
00292         HolographicFramePrediction^ prediction = holographicFrame->CurrentPrediction;
00293
00294         bool atLeastOneCameraRendered = false;
00295         for (auto cameraPose : prediction->CameraPoses)
00296         {
00297             // This represents the device-based resources for a HolographicCamera.
00298             DX::CameraResources* pCameraResources = cameraResourceMap[cameraPose->HolographicCamera->Id].get();
00299
00300             // Get the device context.
00301             const auto context = m_deviceResources->GetD3DDeviceContext();
00302             const auto depthStencilView = pCameraResources->GetDepthStencilView();
00303
00304             // Set render targets to the current holographic camera.
00305             ID3D11RenderTargetView *const targets[1] = { pCameraResources->GetBackBufferRenderTargetView() };
00306             context->OMSetRenderTargets(1, targets, depthStencilView);
00307
00308             // Clear the back buffer and depth stencil view.
00309             if (m_canGetHolographicDisplayForCamera &&
00310                 cameraPose->HolographicCamera->Display->IsOpaque)
00311             {
00312                 context->ClearRenderTargetView(targets[0], DirectX::Colors::CornflowerBlue);
00313             }
00314             else
00315             {
00316                 context->ClearRenderTargetView(targets[0], DirectX::Colors::Transparent);
00317             }
00318             context->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
00319
00320             //
00321             // TODO: Replace the sample content with your own content.
00322             //
00323             // Notes regarding holographic content:
00324             //    * For drawing, remember that you have the potential to fill twice as many pixels
00325             //      in a stereoscopic render target as compared to a non-stereoscopic render target
00326             //      of the same resolution. Avoid unnecessary or repeated writes to the same pixel,
00327             //      and only draw holograms that the user can see.
00328             //    * To help occlude hologram geometry, you can create a depth map using geometry
00329             //      data obtained via the surface mapping APIs. You can use this depth map to avoid
00330             //      rendering holograms that are intended to be hidden behind tables, walls,
00331             //      monitors, and so on.
00332             //    * On HolographicDisplays that are transparent, black pixels will appear transparent
00333             //      to the user. On such devices, you should clear the screen to Transparent as shown
00334             //      above. You should still use alpha blending to draw semitransparent holograms.
00335             //
00336
00337
00338             // The view and projection matrices for each holographic camera will change
00339             // every frame. This function refreshes the data in the constant buffer for
00340             // the holographic camera indicated by cameraPose.
00341             if (m_stationaryReferenceFrame)
00342             {
00343                 pCameraResources->UpdateViewProjectionBuffer(m_deviceResources, cameraPose, m_stationaryReferenceFrame->CoordinateSystem);
00344             }
00345
00346             // Attach the view/projection constant buffer for this camera to the graphics pipeline.
00347             bool cameraActive = pCameraResources->AttachViewProjectionBuffer(m_deviceResources);
00348
00349 #ifdef DRAW_SAMPLE_CONTENT
00350             // Only render world-locked content when positional tracking is active.
00351             if (cameraActive)
00352             {
00353                 // Draw the sample hologram.
00354                 m_spinningCubeRenderer->Render();
00355
00356                 if (m_canCommitDirect3D11DepthBuffer)
00357                 {
00358                     // On versions of the platform that support the CommitDirect3D11DepthBuffer API, we can
00359                     // provide the depth buffer to the system, and it will use depth information to stabilize
00360                     // the image at a per-pixel level.
00361                     HolographicCameraRenderingParameters^ renderingParameters = holographicFrame->GetRenderingParameters(cameraPose);
00362                     ComPtr<ID3D11Texture2D> spDepthStencil = pCameraResources->GetDepthStencilTexture2D();
00363
00364                     // Direct3D interop APIs are used to provide the buffer to the WinRT API.
00365                     ComPtr<IDXGIResource1> depthStencilResource;
00366                     DX::ThrowIfFailed(spDepthStencil.As(&depthStencilResource));
00367                     ComPtr<IDXGISurface2> depthDxgiSurface;
00368                     DX::ThrowIfFailed(depthStencilResource->CreateSubresourceSurface(0, &depthDxgiSurface));
00369                     IDirect3DSurface^ depthD3DSurface = CreateDirect3DSurface(depthDxgiSurface.Get());
00370
00371                     // Calling CommitDirect3D11DepthBuffer causes the system to queue Direct3D commands to
00372                     // read the depth buffer. It will then use that information to stabilize the image as
00373                     // the HolographicFrame is presented.
00374                     renderingParameters->CommitDirect3D11DepthBuffer(depthD3DSurface);
00375                 }
00376             }
00377 #endif
00378             atLeastOneCameraRendered = true;
00379         }
00380
00381         return atLeastOneCameraRendered;
00382     });
00383 }
00384
00385 void BasicHologramMain::SaveAppState()
00386 {
00387     //
00388     // TODO: Insert code here to save your app state.
00389     //       This method is called when the app is about to suspend.
00390     //
00391     //       For example, store information in the SpatialAnchorStore.
00392     //
00393 }
00394
00395 void BasicHologramMain::LoadAppState()
00396 {
00397     //
00398     // TODO: Insert code here to load your app state.
00399     //       This method is called when the app resumes.
00400     //
00401     //       For example, load information from the SpatialAnchorStore.
00402     //
00403 }
00404
00405 void BasicHologramMain::OnPointerPressed()
00406 {
00407     m_pointerPressed = true;
00408 }
00409
00410 // Notifies classes that use Direct3D device resources that the device resources
00411 // need to be released before this method returns.
00412 void BasicHologramMain::OnDeviceLost()
00413 {
00414 #ifdef DRAW_SAMPLE_CONTENT
00415     m_spinningCubeRenderer->ReleaseDeviceDependentResources();
00416 #endif
00417 }
00418
00419 // Notifies classes that use Direct3D device resources that the device resources
00420 // may now be recreated.
00421 void BasicHologramMain::OnDeviceRestored()
00422 {
00423 #ifdef DRAW_SAMPLE_CONTENT
00424     m_spinningCubeRenderer->CreateDeviceDependentResources();
00425 #endif
00426 }
00427
00428 void BasicHologramMain::OnLocatabilityChanged(SpatialLocator^ sender, Object^ args)
00429 {
00430     switch (sender->Locatability)
00431     {
00432     case SpatialLocatability::Unavailable:
00433         // Holograms cannot be rendered.
00434         {
00435             String^ message = L"Warning! Positional tracking is " +
00436                                         sender->Locatability.ToString() + L".\n";
00437             OutputDebugStringW(message->Data());
00438         }
00439         break;
00440
00441     // In the following three cases, it is still possible to place holograms using a
00442     // SpatialLocatorAttachedFrameOfReference.
00443     case SpatialLocatability::PositionalTrackingActivating:
00444         // The system is preparing to use positional tracking.
00445
00446     case SpatialLocatability::OrientationOnly:
00447         // Positional tracking has not been activated.
00448
00449     case SpatialLocatability::PositionalTrackingInhibited:
00450         // Positional tracking is temporarily inhibited. User action may be required
00451         // in order to restore positional tracking.
00452         break;
00453
00454     case SpatialLocatability::PositionalTrackingActive:
00455         // Positional tracking is active. World-locked content can be rendered.
00456         break;
00457     }
00458 }
00459
00460 void BasicHologramMain::OnCameraAdded(
00461     HolographicSpace^ sender,
00462     HolographicSpaceCameraAddedEventArgs^ args
00463     )
00464 {
00465     Deferral^ deferral = args->GetDeferral();
00466     HolographicCamera^ holographicCamera = args->Camera;
00467     create_task([this, deferral, holographicCamera] ()
00468     {
00469         //
00470         // TODO: Allocate resources for the new camera and load any content specific to
00471         //       that camera. Note that the render target size (in pixels) is a property
00472         //       of the HolographicCamera object, and can be used to create off-screen
00473         //       render targets that match the resolution of the HolographicCamera.
00474         //
00475
00476         // Create device-based resources for the holographic camera and add it to the list of
00477         // cameras used for updates and rendering. Notes:
00478         //   * Since this function may be called at any time, the AddHolographicCamera function
00479         //     waits until it can get a lock on the set of holographic camera resources before
00480         //     adding the new camera. At 60 frames per second this wait should not take long.
00481         //   * A subsequent Update will take the back buffer from the RenderingParameters of this
00482         //     camera's CameraPose and use it to create the ID3D11RenderTargetView for this camera.
00483         //     Content can then be rendered for the HolographicCamera.
00484         m_deviceResources->AddHolographicCamera(holographicCamera);
00485
00486         // Holographic frame predictions will not include any information about this camera until
00487         // the deferral is completed.
00488         deferral->Complete();
00489     });
00490 }
00491
00492 void BasicHologramMain::OnCameraRemoved(
00493     HolographicSpace^ sender,
00494     HolographicSpaceCameraRemovedEventArgs^ args
00495     )
00496 {
00497     create_task([this]()
00498     {
00499         //
00500         // TODO: Asynchronously unload or deactivate content resources (not back buffer
00501         //       resources) that are specific only to the camera that was removed.
00502         //
00503     });
00504
00505     // Before letting this callback return, ensure that all references to the back buffer
00506     // are released.
00507     // Since this function may be called at any time, the RemoveHolographicCamera function
00508     // waits until it can get a lock on the set of holographic camera resources before
00509     // deallocating resources for this camera. At 60 frames per second this wait should
00510     // not take long.
00511     m_deviceResources->RemoveHolographicCamera(args->Camera);
00512 }
00513
00514 void BasicHologramMain::OnGamepadAdded(Object^, Gamepad^ args)
00515 {
00516     for (auto const& gamepadWithButtonState : m_gamepads)
00517     {
00518         if (args == gamepadWithButtonState.gamepad)
00519         {
00520             // This gamepad is already in the list.
00521             return;
00522         }
00523     }
00524
00525     GamepadWithButtonState newGamepad = { args, false };
00526     m_gamepads.push_back(newGamepad);
00527 }
00528
00529 void BasicHologramMain::OnGamepadRemoved(Object^, Gamepad^ args)
00530 {
00531     m_gamepads.erase(std::remove_if(m_gamepads.begin(), m_gamepads.end(), [&](GamepadWithButtonState& gamepadWithState)
00532         {
00533             return gamepadWithState.gamepad == args;
00534         }),
00535         m_gamepads.end());
00536 }
00537
00538 void BasicHologramMain::OnHolographicDisplayIsAvailableChanged(Object^, Object^)
00539 {
00540     // Get the spatial locator for the default HolographicDisplay, if one is available.
00541     SpatialLocator^ spatialLocator = nullptr;
00542     if (m_canGetDefaultHolographicDisplay)
00543     {
00544         HolographicDisplay^ defaultHolographicDisplay = HolographicDisplay::GetDefault();
00545         if (defaultHolographicDisplay)
00546         {
00547             spatialLocator = defaultHolographicDisplay->SpatialLocator;
00548         }
00549     }
00550     else
00551     {
00552         spatialLocator = SpatialLocator::GetDefault();
00553     }
00554
00555     if (m_spatialLocator != spatialLocator)
00556     {
00557         // If the spatial locator is disconnected or replaced, we should discard all state that was
00558         // based on it.
00559         if (m_spatialLocator != nullptr)
00560         {
00561             m_spatialLocator->LocatabilityChanged -= m_locatabilityChangedToken;
00562             m_spatialLocator = nullptr;
00563         }
00564
00565         m_stationaryReferenceFrame = nullptr;
00566
00567         if (spatialLocator != nullptr)
00568         {
00569             // Use the SpatialLocator from the default HolographicDisplay to track the motion of the device.
00570             m_spatialLocator = spatialLocator;
00571
00572             // Respond to changes in the positional tracking state.
00573             m_locatabilityChangedToken =
00574                 m_spatialLocator->LocatabilityChanged +=
00575                 ref new TypedEventHandler<SpatialLocator^, Object^>(
00576                     std::bind(&BasicHologramMain::OnLocatabilityChanged, this, _1, _2)
00577                     );
00578
00579             // The simplest way to render world-locked holograms is to create a stationary reference frame
00580             // based on a SpatialLocator. This is roughly analogous to creating a "world" coordinate system
00581             // with the origin placed at the device's position as the app is launched.
00582             m_stationaryReferenceFrame = m_spatialLocator->CreateStationaryFrameOfReferenceAtCurrentLocation();
00583         }
00584     }
00585 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cpp/Scenario5_UnicodeExtensions.xaml.h Source File

  • DateTimeFormatting
  • cpp

Scenario5_UnicodeExtensions.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario5_UnicodeExtensions.g.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario5_UnicodeExtensions sealed
00021     {
00022     public:
00023         Scenario5_UnicodeExtensions();
00024         void Display();
00025     };
00026 }
Generated on Fri Nov 15 2024 22:19:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Material.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Material.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Material.h"
00014
00015 using namespace DirectX;
00016
00017 Material::Material(
00018     XMFLOAT4 meshColor,
00019     XMFLOAT4 diffuseColor,
00020     XMFLOAT4 specularColor,
00021     float specularExponent,
00022     _In_ ID3D11ShaderResourceView* textureResourceView,
00023     _In_ ID3D11VertexShader* vertexShader,
00024     _In_ ID3D11PixelShader* pixelShader
00025     )
00026 {
00027     m_meshColor = meshColor;
00028     m_diffuseColor = diffuseColor;
00029     m_specularColor = specularColor;
00030     m_specularExponent = specularExponent;
00031
00032     m_vertexShader.copy_from(vertexShader);
00033     m_pixelShader.copy_from(pixelShader);
00034     m_textureRV.copy_from(textureResourceView);
00035 }
00036
00037 void Material::RenderSetup(
00038     _In_ ID3D11DeviceContext* context,
00039     _Inout_ ConstantBufferChangesEveryPrim* constantBuffer
00040     )
00041 {
00042     constantBuffer->meshColor = m_meshColor;
00043     constantBuffer->specularColor = m_specularColor;
00044     constantBuffer->specularPower = m_specularExponent;
00045     constantBuffer->diffuseColor = m_diffuseColor;
00046
00047     ID3D11ShaderResourceView* textureRV = m_textureRV.get();
00048     context->PSSetShaderResources(0, 1, &textureRV);
00049     context->VSSetShader(m_vertexShader.get(), nullptr, 0);
00050     context->PSSetShader(m_pixelShader.get(), nullptr, 0);
00051 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GetUid Member List

This is the complete list of members for GetUid, including all inherited members.
ApduCommand(byte cla, byte ins, byte p1, byte p2, byte[] commandData, byte?le) | ApduCommand | [inline]
ApduResponseType | ApduCommand |
CLA | ApduCommand |
CommandData | ApduCommand |
GetBuffer() | ApduCommand | [inline]
GetData(GetDataDataType type) | GetData | [inline]
GetDataDataType enum name | GetData |
GetUid() | GetUid | [inline]
INS | ApduCommand |
Le | ApduCommand |
P1 | ApduCommand |
P2 | ApduCommand |
ToString() | ApduCommand | [inline]
Type | GetData |
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_InkingAndInteractionFeedback Member List

This is the complete list of members for Scenario5_InkingAndInteractionFeedback, including all inherited members.
GetSnappedPoint() | Scenario5_InkingAndInteractionFeedback | [private]
gridSize | Scenario5_InkingAndInteractionFeedback | [private]
InitializeGridLines() | Scenario5_InkingAndInteractionFeedback | [private]
InitializeManipulationTransforms() | Scenario5_InkingAndInteractionFeedback | [private]
IsInSnapRange() | Scenario5_InkingAndInteractionFeedback | [private]
MovableRect_Entered(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::Input::PointerRoutedEventArgs const &e) | Scenario5_InkingAndInteractionFeedback |
MovableRect_Exited(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::Input::PointerRoutedEventArgs const &e) | Scenario5_InkingAndInteractionFeedback |
MovableRect_ManipulationCompleted(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::Input::ManipulationCompletedRoutedEventArgs const &) | Scenario5_InkingAndInteractionFeedback |
MovableRect_ManipulationDelta(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::Input::ManipulationDeltaRoutedEventArgs const &e) | Scenario5_InkingAndInteractionFeedback |
MovableRect_ManipulationStarted(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::Input::ManipulationStartedRoutedEventArgs const &) | Scenario5_InkingAndInteractionFeedback |
Scenario5_InkingAndInteractionFeedback() | Scenario5_InkingAndInteractionFeedback |
snapDistance | Scenario5_InkingAndInteractionFeedback | [private]
SnapMovableRectToGridLines() | Scenario5_InkingAndInteractionFeedback | [private]
topLeft | Scenario5_InkingAndInteractionFeedback | [private]
UpdatePreviewRect() | Scenario5_InkingAndInteractionFeedback | [private]
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/Common/DirectXHelper.h Source File

  • ComplexInk
  • cpp
  • Common

DirectXHelper.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include <ppltasks.h>   // For create_task
00004
00005 namespace DX
00006 {
00007     inline void ThrowIfFailed(HRESULT hr)
00008     {
00009         if (FAILED(hr))
00010         {
00011             // Set a breakpoint on this line to catch Win32 API errors.
00012             throw Platform::Exception::CreateException(hr);
00013         }
00014     }
00015
00016 #if defined(_DEBUG)
00017     // Check for SDK Layer support.
00018     inline bool SdkLayersAvailable()
00019     {
00020         HRESULT hr = D3D11CreateDevice(
00021             nullptr,
00022             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00023             0,
00024             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00025             nullptr,                    // Any feature level will do.
00026             0,
00027             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00028             nullptr,                    // No need to keep the D3D device reference.
00029             nullptr,                    // No need to know the feature level.
00030             nullptr                     // No need to keep the D3D device context reference.
00031             );
00032
00033         return SUCCEEDED(hr);
00034     }
00035 #endif
00036 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/Content/ShaderStructures.h Source File

  • BasicHologram
  • cpp
  • Content

ShaderStructures.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 namespace BasicHologram
00004 {
00005     // Constant buffer used to send hologram position transform to the shader pipeline.
00006     struct ModelConstantBuffer
00007     {
00008         DirectX::XMFLOAT4X4 model;
00009     };
00010
00011     // Assert that the constant buffer remains 16-byte aligned (best practice).
00012     static_assert((sizeof(ModelConstantBuffer) % (sizeof(float) * 4)) == 0, "Model constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00013
00014
00015     // Used to send per-vertex data to the vertex shader.
00016     struct VertexPositionColor
00017     {
00018         DirectX::XMFLOAT3 pos;
00019         DirectX::XMFLOAT3 color;
00020     };
00021 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IMemoryBufferByteAccess Member List

This is the complete list of members for IMemoryBufferByteAccess, including all inherited members.
GetBuffer(out byte *buffer, out uint capacity) IMemoryBufferByteAccess
Generated on Fri Nov 15 2024 22:23:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario8_UpdateAsync Member List

This is the complete list of members for Scenario8_UpdateAsync, including all inherited members.
rootPage | Scenario8_UpdateAsync | [private]
Scenario8_UpdateAsync() | Scenario8_UpdateAsync | [inline]
UpdateDefaultLogo_Click(object sender, RoutedEventArgs e) | Scenario8_UpdateAsync | [inline, private]
Generated on Fri Nov 15 2024 22:24:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RelayCommand Member List

This is the complete list of members for RelayCommand, including all inherited members.
_canExecute | RelayCommand | [private]
_execute | RelayCommand | [private]
CanExecute(object parameter) | RelayCommand | [inline]
CanExecuteChanged | RelayCommand |
Execute(object parameter) | RelayCommand | [inline]
RaiseCanExecuteChanged() | RelayCommand | [inline]
RelayCommand(Action execute) | RelayCommand | [inline]
RelayCommand(Action execute, Func< bool > canExecute) | RelayCommand | [inline]
Generated on Fri Nov 15 2024 22:24:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cpp/Scenario5_VerifyResponse.xaml.cpp Source File

  • SmartCard
  • cpp

Scenario5_VerifyResponse.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario5_VerifyResponse.xaml.h"
00005 #include "ChallengeResponseAlgorithm.h"
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace concurrency;
00010 using namespace Platform;
00011 using namespace Windows::Devices::SmartCards;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::Storage::Streams;
00015 using namespace Windows::Security::Cryptography;
00016 using namespace Windows::Security::Cryptography::Core;
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Controls::Primitives;
00020 using namespace Windows::UI::Xaml::Data;
00021 using namespace Windows::UI::Xaml::Input;
00022 using namespace Windows::UI::Xaml::Media;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario5_VerifyResponse::Scenario5_VerifyResponse()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 void Scenario5_VerifyResponse::VerifyResponse_Click(Platform::Object^ sender,
00031     Windows::UI::Xaml::RoutedEventArgs^ e)
00032 {
00033     if (MainPage::Current->SmartCardReaderDeviceId == nullptr)
00034     {
00035         MainPage::Current->NotifyUser("Use Scenario One to create a TPM virtual smart card.", NotifyType::ErrorMessage);
00036         return;
00037     }
00038
00039     Button^ b = dynamic_cast<Button^>(sender);
00040     b->IsEnabled = false;
00041     MainPage::Current->NotifyUser("Verifying smart card response...", NotifyType::StatusMessage);
00042
00043     create_task(MainPage::Current->GetSmartCard()).then(
00044         [=](task<Windows::Devices::SmartCards::SmartCard^> getSmartCardTask)
00045     {
00046         Windows::Devices::SmartCards::SmartCard^ card = getSmartCardTask.get();
00047         return SmartCardProvisioning::FromSmartCardAsync(card);
00048     }).then(
00049         [=](task<SmartCardProvisioning^> getProvisioningTask)
00050     {
00051         SmartCardProvisioning^ provisioning = getProvisioningTask.get();
00052         return provisioning->GetChallengeContextAsync();
00053     }).then(
00054         [=](task<SmartCardChallengeContext^> getChallengeContextTask)
00055     {
00056         SmartCardChallengeContext^ context = getChallengeContextTask.get();
00057         IBuffer^ response = ChallengeResponseAlgorithm::CalculateResponse(context->Challenge, MainPage::Current->AdminKey);
00058         return context->VerifyResponseAsync(response);
00059     }).then(
00060         [=](task<bool> verifyResponseTask)
00061     {
00062         try
00063         {
00064             bool verifyResult = verifyResponseTask.get();
00065             MainPage::Current->NotifyUser("Smart card response verification completed. Result: " + verifyResult.ToString(), NotifyType::StatusMessage);
00066         }
00067         catch (COMException ^ex)
00068         {
00069             MainPage::Current->NotifyUser("Smart card response verification failed with exception: " + ex->ToString(), NotifyType::ErrorMessage);
00070         }
00071
00072         b->IsEnabled = true;
00073     });
00074 }
Generated on Fri Nov 15 2024 22:21:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/MainPage.xaml.cpp Source File

  • XamlBind
  • cpp

MainPage.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014
00015 using namespace SDKTemplate;
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021 using namespace Windows::UI::Xaml::Controls::Primitives;
00022 using namespace Windows::UI::Xaml::Data;
00023 using namespace Windows::UI::Xaml::Input;
00024 using namespace Windows::UI::Xaml::Media;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::UI::Xaml::Interop;
00027
00028 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00029
00030 //MainPage^ MainPage::Current = nullptr;
00031
00032 MainPage::MainPage()
00033 {
00034     InitializeComponent();
00035
00036     // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00037     // in order to call methods that are in this class.
00038     MainPage::Current = this;
00039 }
00040
00041 void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043     //// Populate the ListBox with the scenarios as defined in SampleConfiguration.cpp.
00044     //auto itemCollection = ref new Platform::Collections::Vector<Object^>();
00045     //int i = 1;
00046     //for (auto const& s : MainPage::Current->scenarios)
00047     //{
00048     //    // Create a textBlock to hold the content and apply the ListItemTextStyle from Styles.xaml
00049     //    TextBlock^ textBlock = ref new TextBlock();
00050     //    ListBoxItem^ item = ref new ListBoxItem();
00051     //    auto style = App::Current->Resources->Lookup("ListItemTextStyle");
00052
00053     //    textBlock->Text = (i++)->ToString() + ") " + s->Title;
00054     //    textBlock->Style = safe_cast<Windows::UI::Xaml::Style ^>(style);
00055
00056     //    item->Name = s->ClassName;
00057     //    item->Content = textBlock;
00058     //    itemCollection->Append(item);
00059     //}
00060
00061     // Set the newly created itemCollection as the ListBox ItemSource.
00062     ScenarioControl->ItemsSource = MainPage::Current->scenarios;
00063     int startingScenarioIndex;
00064
00065     if (Window::Current->Bounds.Width < 640)
00066     {
00067         startingScenarioIndex = -1;
00068     }
00069     else
00070     {
00071         startingScenarioIndex = 0;
00072     }
00073
00074     ScenarioControl->SelectedIndex = startingScenarioIndex;
00075     ScenarioControl->ScrollIntoView(ScenarioControl->SelectedItem);
00076 }
00077
00078
00079 void MainPage::ScenarioControl_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00080 {
00081     ListBox^ scenarioListBox = safe_cast<ListBox^>(sender); //as ListBox;
00082     Scenario^ item = dynamic_cast<Scenario^>(scenarioListBox->SelectedItem);
00083     if (item != nullptr)
00084     {
00085         // Clear the status block when changing scenarios
00086         NotifyUser("", NotifyType::StatusMessage);
00087
00088         // Navigate to the selected scenario.
00089         TypeName scenarioType = { item->ClassName, TypeKind::Custom };
00090         ScenarioFrame->Navigate(scenarioType, this);
00091
00092         if (Window::Current->Bounds.Width < 640)
00093         {
00094             Splitter->IsPaneOpen = false;
00095             StatusBorder->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00096         }
00097     }
00098 }
00099
00100 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00101 {
00102     switch (type)
00103     {
00104     case NotifyType::StatusMessage:
00105         StatusBorder->Background = ref new SolidColorBrush(Windows::UI::Colors::Green);
00106         break;
00107     case NotifyType::ErrorMessage:
00108         StatusBorder->Background = ref new SolidColorBrush(Windows::UI::Colors::Red);
00109         break;
00110     default:
00111         break;
00112     }
00113     StatusBlock->Text = strMessage;
00114
00115     // Collapse the StatusBlock if it has no text to conserve real estate.
00116     if (StatusBlock->Text != "")
00117     {
00118         StatusPanel->Visibility = Windows::UI::Xaml::Visibility::Visible;
00119     }
00120     else
00121     {
00122         StatusPanel->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00123     }
00124 }
00125
00126 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00127 {
00128     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00129     Windows::System::Launcher::LaunchUriAsync(uri);
00130 }
00131
00132 void MainPage::Button_Click(Object^ sender, RoutedEventArgs^ e)
00133 {
00134     Splitter->IsPaneOpen = !Splitter->IsPaneOpen;
00135     StatusBorder->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00136 }
00137
Generated on Fri Nov 15 2024 22:17:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DataReaderWriter/cpp/pch.cpp Source File

  • DataReaderWriter
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Audio/AudioStreamReader.cpp Source File

  • HolographicVoiceInput
  • cpp
  • Audio

AudioStreamReader.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012
00013 #include "AudioStreamReader.h"
00014
00015 using namespace Concurrency;
00016 using namespace Microsoft::WRL;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Media::SpeechSynthesis;
00019 using namespace Windows::Storage::Streams;
00020
00021 _Use_decl_annotations_
00022 HRESULT AudioStreamReader::Initialize(SpeechSynthesisStream^ speechSynthesisStream)
00023 {
00024     BOOL mfStarted = FALSE;
00025     auto hr = MFStartup(MF_VERSION);
00026     mfStarted = SUCCEEDED(hr);
00027
00028     ComPtr<IUnknown> streamUnknown = reinterpret_cast<IUnknown*>(speechSynthesisStream);
00029     ComPtr<IMFByteStream> byteStream;
00030     if (SUCCEEDED(hr))
00031     {
00032         hr = MFCreateMFByteStreamOnStreamEx(streamUnknown.Get(), &byteStream);
00033     }
00034
00035     ComPtr<IMFSourceReader> reader;
00036     if (SUCCEEDED(hr))
00037     {
00038         hr = MFCreateSourceReaderFromByteStream(byteStream.Get(), nullptr, &reader);
00039     }
00040
00041     // Select the first audio stream, and deselect all other streams.
00042     if (SUCCEEDED(hr))
00043     {
00044         hr = reader->SetStreamSelection(static_cast<DWORD>(MF_SOURCE_READER_ALL_STREAMS), FALSE);
00045     }
00046
00047     if (SUCCEEDED(hr))
00048     {
00049         hr = reader->SetStreamSelection(static_cast<DWORD>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), TRUE);
00050     }
00051
00052     // Create a partial media type that specifies uncompressed PCM audio.
00053     ComPtr<IMFMediaType> partialType;
00054     if (SUCCEEDED(hr))
00055     {
00056         hr = MFCreateMediaType(&partialType);
00057     }
00058
00059     if (SUCCEEDED(hr))
00060     {
00061         hr = partialType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio);
00062     }
00063
00064     if (SUCCEEDED(hr))
00065     {
00066         hr = partialType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM);
00067     }
00068
00069     // Set this type on the source reader. The source reader will load the necessary decoder.
00070     if (SUCCEEDED(hr))
00071     {
00072         hr = reader->SetCurrentMediaType(static_cast<DWORD>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), nullptr, partialType.Get());
00073     }
00074
00075     // Get the complete uncompressed format
00076     ComPtr<IMFMediaType> uncompressedAudioType;
00077     if (SUCCEEDED(hr))
00078     {
00079         hr = reader->GetCurrentMediaType(static_cast<DWORD>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), &uncompressedAudioType);
00080     }
00081
00082     // Ensure the stream is selected.
00083     if (SUCCEEDED(hr))
00084     {
00085         hr = reader->SetStreamSelection(static_cast<DWORD>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), TRUE);
00086     }
00087
00088     // Get the audio block size and number of bytes/second from the audio format.
00089     if (SUCCEEDED(hr))
00090     {
00091         WAVEFORMATEX* format = nullptr;
00092         UINT32 size = 0;
00093         hr = MFCreateWaveFormatExFromMFMediaType(uncompressedAudioType.Get(), &format, &size);
00094
00095         // Only mono PCM files are supported for HRTF processing
00096         if (SUCCEEDED(hr) && format->wFormatTag != WAVE_FORMAT_PCM && format->nChannels != 1)
00097         {
00098             hr = E_INVALIDARG;
00099         }
00100
00101         if (SUCCEEDED(hr))
00102         {
00103             CopyMemory(&_format, format, sizeof WAVEFORMATEX);
00104         }
00105
00106         if (format)
00107         {
00108             CoTaskMemFree(format);
00109         }
00110     }
00111
00112     // Get audio samples from the source reader.
00113     _audioData.resize(0);
00114     while (SUCCEEDED(hr))
00115     {
00116         DWORD dwFlags = 0;
00117
00118         // Read the next sample.
00119         ComPtr<IMFSample> sample;
00120         hr = reader->ReadSample(static_cast<DWORD>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), 0, nullptr, &dwFlags, nullptr, &sample);
00121
00122         if (SUCCEEDED(hr) && (dwFlags & MF_SOURCE_READERF_ENDOFSTREAM) != 0)
00123         {
00124             // End of stream
00125             break;
00126         }
00127
00128         if (SUCCEEDED(hr) && sample == nullptr)
00129         {
00130             // No sample, keep going
00131             continue;
00132         }
00133
00134         // Get a pointer to the audio data in the sample.
00135         ComPtr<IMFMediaBuffer> buffer;
00136         if (SUCCEEDED(hr))
00137         {
00138             hr = sample->ConvertToContiguousBuffer(&buffer);
00139         }
00140
00141         DWORD bufferSize = 0;
00142         if (SUCCEEDED(hr))
00143         {
00144             BYTE* data;
00145             hr = buffer->Lock(&data, nullptr, &bufferSize);
00146
00147             auto currentDataSize = _audioData.size();
00148             if (SUCCEEDED(hr))
00149             {
00150                 _audioData.resize(currentDataSize + bufferSize);
00151             }
00152
00153             if (SUCCEEDED(hr))
00154             {
00155                 CopyMemory(_audioData.data() + currentDataSize, data, bufferSize);
00156                 // Unlock the buffer
00157                 hr = buffer->Unlock();
00158             }
00159         }
00160     }
00161
00162     if (mfStarted)
00163     {
00164         MFShutdown();
00165     }
00166
00167     return hr;
00168 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_PinTile Member List

This is the complete list of members for Scenario1_PinTile, including all inherited members.
PinButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_PinTile
Scenario1_PinTile() | Scenario1_PinTile
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PhasingTests Member List

This is the complete list of members for PhasingTests, including all inherited members.
_dataSource | PhasingTests | [private]
ChangeFolderClick(object sender, RoutedEventArgs e) | PhasingTests | [inline, private]
CreateTestData() | PhasingTests | [inline, private]
dataSource | PhasingTests | [private]
DataSource_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) | PhasingTests | [inline, private]
Initialized | PhasingTests | [private]
myGridView_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args) | PhasingTests | [inline, private]
PhasedTemplate_Checked(object sender, RoutedEventArgs e) | PhasingTests | [inline, private]
PhasingTests() | PhasingTests | [inline]
Reset_Click(object sender, RoutedEventArgs e) | PhasingTests | [inline, private]
Sleep(int msTime) | PhasingTests | [inline, private]
SlowPhasing_Checked(object sender, RoutedEventArgs e) | PhasingTests | [inline, private]
SlowPhasing_UnChecked(object sender, RoutedEventArgs e) | PhasingTests | [inline, private]
Generated on Fri Nov 15 2024 22:24:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/scenario7.xaml.cpp Source File

  • ApplicationResources
  • cpp

scenario7.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario7.xaml.cpp
00013 // Implementation of the Scenario7 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario7.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Windows::ApplicationModel::Resources::Core;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Windows::System::Threading;
00027 using namespace Windows::Foundation;
00028 using namespace Platform;
00029
00030 Scenario7::Scenario7()
00031 {
00032     InitializeComponent();
00033     eventToken.Value = 0;
00034     defaultContextForCurrentView = ResourceContext::GetForCurrentView();
00035 }
00036
00037 /// <summary>
00038 /// Invoked when this page is about to be displayed in a Frame.
00039 /// </summary>
00040 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00041 /// property is typically used to configure the page.</param>
00042 void Scenario7::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00045     // as NotifyUser()
00046     rootPage = MainPage::Current;
00047 }
00048
00049 void Scenario7::OnNavigatedFrom(NavigationEventArgs^ e)
00050 {
00051     if (eventToken.Value != 0)
00052     {
00053         defaultContextForCurrentView->QualifierValues->MapChanged -= eventToken;
00054         eventToken.Value = 0;
00055     }
00056 }
00057
00058 void Scenario7::ContextChanged(IObservableMap<String^, String^>^ sender, IMapChangedEventArgs<String^>^ eventArg)
00059 {
00060     this->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
00061         ref new Windows::UI::Core::DispatchedHandler([this]()
00062         {
00063             this->Scenario7TextBlock->Text = ResourceManager::Current->MainResourceMap->GetValue("Resources/string1", defaultContextForCurrentView)->ValueAsString;
00064         }));
00065 }
00066 void Scenario7::Scenario7Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00067 {
00068     if (eventToken.Value == 0)
00069     {
00070         Scenario7TextBlock->Text = ResourceManager::Current->MainResourceMap->GetValue("Resources/string1", defaultContextForCurrentView)->ValueAsString;
00071         eventToken = defaultContextForCurrentView->QualifierValues->MapChanged += ref new MapChangedEventHandler<String^, String^>(this, &Scenario7::ContextChanged);
00072     }
00073 }
00074
Generated on Fri Nov 15 2024 22:18:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomHidDeviceAccess/cs/EventHandlerForDevice.cs Source File

  • CustomHidDeviceAccess
  • cs

EventHandlerForDevice.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using System;
00008 using System.Collections.Generic;
00009 using System.Linq;
00010 using System.Text;
00011 using System.Threading.Tasks;
00012 using Windows.ApplicationModel;
00013 using Windows.Devices.Enumeration;
00014 using Windows.Devices.HumanInterfaceDevice;
00015 using Windows.Foundation;
00016 using Windows.Storage;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using SDKTemplate;
00020
00021 namespace CustomHidDeviceAccess
00022 {
00023     /// <summary>
00024     /// The purpose of this class is to demonstrate what to do to a HidDevice when a specific app event
00025     /// is raised (app suspension and resume) or when the device is disconnected. In addition to handling
00026     /// the HidDevice, the app's state should also be saved upon app suspension (will not be demonstrated here).
00027     ///
00028     /// This class will also demonstrate how to handle device watcher events.
00029     ///
00030     /// For simplicity, this class will only allow at most one device to be connected at any given time. In order
00031     /// to make this class support multiple devices, make this class a non-singleton and create multiple instances
00032     /// of this class; each instance should watch one connected device.
00033     /// </summary>
00034     public class EventHandlerForDevice
00035     {
00036         /// <summary>
00037         /// Allows for singleton EventHandlerForDevice
00038         /// </summary>
00039         private static EventHandlerForDevice eventHandlerForDevice;
00040
00041         /// <summary>
00042         /// Used to synchronize threads to avoid multiple instantiations of eventHandlerForDevice.
00043         /// </summary>
00044         private static Object singletonCreationLock = new Object();
00045
00046         private String deviceSelector;
00047         private DeviceWatcher deviceWatcher;
00048
00049         private DeviceInformation deviceInformation;
00050         private DeviceAccessInformation deviceAccessInformation;
00051         private HidDevice device;
00052
00053         private SuspendingEventHandler appSuspendEventHandler;
00054         private EventHandler<Object> appResumeEventHandler;
00055
00056         private TypedEventHandler<EventHandlerForDevice, DeviceInformation> deviceCloseCallback;
00057         private TypedEventHandler<EventHandlerForDevice, OnDeviceConnectedEventArgs> deviceConnectedCallback;
00058
00059         private TypedEventHandler<DeviceWatcher, DeviceInformation> deviceAddedEventHandler;
00060         private TypedEventHandler<DeviceWatcher, DeviceInformationUpdate> deviceRemovedEventHandler;
00061         private TypedEventHandler<DeviceAccessInformation, DeviceAccessChangedEventArgs> deviceAccessEventHandler;
00062
00063         private Boolean watcherSuspended;
00064         private Boolean watcherStarted;
00065         private Boolean isEnabledAutoReconnect;
00066
00067         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00068         // as NotifyUser()
00069         private MainPage rootPage = MainPage.Current;
00070
00071         /// <summary>
00072         /// Enforces the singleton pattern so that there is only one object handling app events
00073         /// as it relates to the UsbDevice because this sample app only supports communicating with one device at a time.
00074         ///
00075         /// An instance of EventHandlerForDevice is globally available because the device needs to persist across scenario pages.
00076         ///
00077         /// If there is no instance of EventHandlerForDevice created before this property is called,
00078         /// an EventHandlerForDevice will be created.
00079         /// </summary>
00080         public static EventHandlerForDevice Current
00081         {
00082             get
00083             {
00084                 if (eventHandlerForDevice == null)
00085                 {
00086                     lock (singletonCreationLock)
00087                     {
00088                         if (eventHandlerForDevice == null)
00089                         {
00090                             CreateNewEventHandlerForDevice();
00091                         }
00092                     }
00093                 }
00094
00095                 return eventHandlerForDevice;
00096             }
00097         }
00098
00099         /// <summary>
00100         /// Creates a new instance of EventHandlerForDevice, enables auto reconnect, and uses it as the Current instance.
00101         /// </summary>
00102         public static void CreateNewEventHandlerForDevice()
00103         {
00104             eventHandlerForDevice = new EventHandlerForDevice();
00105         }
00106
00107         public TypedEventHandler<EventHandlerForDevice, DeviceInformation> OnDeviceClose
00108         {
00109             get
00110             {
00111                 return deviceCloseCallback;
00112             }
00113
00114             set
00115             {
00116                 deviceCloseCallback = value;
00117             }
00118         }
00119
00120         public TypedEventHandler<EventHandlerForDevice, OnDeviceConnectedEventArgs> OnDeviceConnected
00121         {
00122             get
00123             {
00124                 return deviceConnectedCallback;
00125             }
00126
00127             set
00128             {
00129                 deviceConnectedCallback = value;
00130             }
00131         }
00132
00133         public Boolean IsDeviceConnected
00134         {
00135             get
00136             {
00137                 return (device != null);
00138             }
00139         }
00140
00141         public HidDevice Device
00142         {
00143             get
00144             {
00145                 return device;
00146             }
00147         }
00148
00149         /// <summary>
00150         /// This DeviceInformation represents which device is connected or which device will be reconnected when
00151         /// the device is plugged in again (if IsEnabledAutoReconnect is true);.
00152         /// </summary>
00153         public DeviceInformation DeviceInformation
00154         {
00155             get
00156             {
00157                 return deviceInformation;
00158             }
00159         }
00160
00161         /// <summary>
00162         /// Returns DeviceAccessInformation for the device that is currently connected using this EventHandlerForDevice
00163         /// object.
00164         /// </summary>
00165         public DeviceAccessInformation DeviceAccessInformation
00166         {
00167             get
00168             {
00169                 return deviceAccessInformation;
00170             }
00171         }
00172
00173         /// <summary>
00174         /// DeviceSelector AQS used to find this device
00175         /// </summary>
00176         public String DeviceSelector
00177         {
00178             get
00179             {
00180                 return deviceSelector;
00181             }
00182         }
00183
00184         /// <summary>
00185         /// True if EventHandlerForDevice will attempt to reconnect to the device once it is plugged into the computer again
00186         /// </summary>
00187         public Boolean IsEnabledAutoReconnect
00188         {
00189             get
00190             {
00191                 return isEnabledAutoReconnect;
00192             }
00193             set
00194             {
00195                 isEnabledAutoReconnect = value;
00196             }
00197         }
00198
00199         /// <summary>
00200         /// This method opens the device using the WinRT Hid API. After the device is opened, save the device
00201         /// so that it can be used across scenarios.
00202         ///
00203         /// It is important that the FromIdAsync call is made on the UI thread because the consent prompt can only be displayed
00204         /// on the UI thread.
00205         ///
00206         /// This method is used to reopen the device after the device reconnects to the computer and when the app resumes.
00207         /// </summary>
00208         /// <param name="deviceInfo">Device information of the device to be opened</param>
00209         /// <param name="deviceSelector">The AQS used to find this device</param>
00210         /// <returns>True if the device was successfully opened, false if the device could not be opened for well known reasons.
00211         /// An exception may be thrown if the device could not be opened for extraordinary reasons.</returns>
00212         public async Task<Boolean> OpenDeviceAsync(DeviceInformation deviceInfo, String deviceSelector)
00213         {
00214             // This sample uses FileAccessMode.ReadWrite to open the device because we do not want other apps opening our device and
00215             // changing the state of our device. FileAccessMode.Read can be used instead.
00216             device = await HidDevice.FromIdAsync(deviceInfo.Id, FileAccessMode.ReadWrite);
00217
00218             Boolean successfullyOpenedDevice = false;
00219             NotifyType notificationStatus;
00220             String notificationMessage = null;
00221
00222             // Device could have been blocked by user or the device has already been opened by another app.
00223             if (device != null)
00224             {
00225                 successfullyOpenedDevice = true;
00226
00227                 deviceInformation = deviceInfo;
00228                 this.deviceSelector = deviceSelector;
00229
00230                 notificationStatus = NotifyType.StatusMessage;
00231                 notificationMessage = "Device " + deviceInformation.Id + " opened";
00232
00233                 if (appSuspendEventHandler == null || appResumeEventHandler == null)
00234                 {
00235                     RegisterForAppEvents();
00236                 }
00237
00238                 // User can block the device after it has been opened in the Settings charm. We can detect this by registering for the
00239                 // DeviceAccessInformation.AccessChanged event
00240                 if (deviceAccessEventHandler == null)
00241                 {
00242                     RegisterForDeviceAccessStatusChange();
00243                 }
00244
00245                 // Create and register device watcher events for the device to be opened unless we're reopening the device
00246                 if (deviceWatcher == null)
00247                 {
00248                     deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector);
00249
00250                     RegisterForDeviceWatcherEvents();
00251                 }
00252
00253                 if (!watcherStarted)
00254                 {
00255                     // Start the device watcher after we made sure that the device is opened.
00256                     StartDeviceWatcher();
00257                 }
00258             }
00259             else
00260             {
00261                 successfullyOpenedDevice = false;
00262
00263                 notificationStatus = NotifyType.ErrorMessage;
00264
00265                 var deviceAccessStatus = DeviceAccessInformation.CreateFromId(deviceInfo.Id).CurrentStatus;
00266
00267                 if (deviceAccessStatus == DeviceAccessStatus.DeniedByUser)
00268                 {
00269                     notificationMessage = "Access to the device was blocked by the user : " + deviceInfo.Id;
00270                 }
00271                 else if (deviceAccessStatus == DeviceAccessStatus.DeniedBySystem)
00272                 {
00273                     // This status is most likely caused by app permissions (did not declare the device in the app's package.appxmanifest)
00274                     // This status does not cover the case where the device is already opened by another app.
00275                     notificationMessage = "Access to the device was blocked by the system : " + deviceInfo.Id;
00276                 }
00277                 else
00278                 {
00279                     // Most likely the device is opened by another app, but cannot be sure
00280                     notificationMessage = "Unknown error, possibly opened by another app : " + deviceInfo.Id;
00281                 }
00282             }
00283
00284             MainPage.Current.NotifyUser(notificationMessage, notificationStatus);
00285
00286             // Notify registered callback handle that the device has been opened
00287             if (deviceConnectedCallback != null)
00288             {
00289                 var deviceConnectedEventArgs = new OnDeviceConnectedEventArgs(successfullyOpenedDevice, deviceInfo);
00290
00291                 deviceConnectedCallback(this, deviceConnectedEventArgs);
00292             }
00293
00294             return successfullyOpenedDevice;
00295         }
00296
00297         /// <summary>
00298         /// Closes the device, stops the device watcher, stops listening for app events, and resets object state to before a device
00299         /// was ever connected.
00300         /// </summary>
00301         public void CloseDevice()
00302         {
00303             if (IsDeviceConnected)
00304             {
00305                 CloseCurrentlyConnectedDevice();
00306             }
00307
00308             if (deviceWatcher != null)
00309             {
00310                 if (watcherStarted)
00311                 {
00312                     StopDeviceWatcher();
00313
00314                     UnregisterFromDeviceWatcherEvents();
00315                 }
00316
00317                 deviceWatcher = null;
00318             }
00319
00320             if (deviceAccessInformation != null)
00321             {
00322                 UnregisterFromDeviceAccessStatusChange();
00323
00324                 deviceAccessInformation = null;
00325             }
00326
00327             if (appSuspendEventHandler != null || appResumeEventHandler != null)
00328             {
00329                 UnregisterFromAppEvents();
00330             }
00331
00332             deviceInformation = null;
00333             deviceSelector = null;
00334
00335             deviceConnectedCallback= null;
00336             deviceCloseCallback = null;
00337
00338             isEnabledAutoReconnect = true;
00339         }
00340
00341         private EventHandlerForDevice()
00342         {
00343             watcherStarted = false;
00344             watcherSuspended = false;
00345             isEnabledAutoReconnect = true;
00346         }
00347
00348         /// <summary>
00349         /// This method demonstrates how to close the device properly using the WinRT Hid API.
00350         ///
00351         /// When the HidDevice is closing, it will cancel all IO operations that are still pending (not complete).
00352         /// The close will not wait for any IO completion callbacks to be called, so the close call may complete before any of
00353         /// the IO completion callbacks are called.
00354         /// The pending IO operations will still call their respective completion callbacks with either a task
00355         /// cancelled error or the operation completed.
00356         /// </summary>
00357         private async void CloseCurrentlyConnectedDevice()
00358         {
00359             if (device != null)
00360             {
00361                 // Notify callback that we're about to close the device
00362                 if (deviceCloseCallback != null)
00363                 {
00364                     deviceCloseCallback(this, deviceInformation);
00365                 }
00366
00367                 // This closes the handle to the device
00368                 device.Dispose();
00369
00370                 device = null;
00371
00372                 // Save the deviceInformation.Id in case deviceInformation is set to null when closing the
00373                 // device
00374                 String deviceId = deviceInformation.Id;
00375
00376                 await rootPage.Dispatcher.RunAsync(
00377                     CoreDispatcherPriority.Normal,
00378                     new DispatchedHandler(() =>
00379                     {
00380                         MainPage.Current.NotifyUser(deviceId + " is closed", NotifyType.StatusMessage);
00381                     }));
00382             }
00383         }
00384
00385         /// <summary>
00386         /// Register for app suspension/resume events. See the comments
00387         /// for the event handlers for more information on what is being done to the device.
00388         ///
00389         /// We will also register for when the app exists so that we may close the device handle.
00390         /// </summary>
00391         private void RegisterForAppEvents()
00392         {
00393             appSuspendEventHandler = new SuspendingEventHandler(EventHandlerForDevice.Current.OnAppSuspension);
00394             appResumeEventHandler = new EventHandler<Object>(EventHandlerForDevice.Current.OnAppResume);
00395
00396             // This event is raised when the app is exited and when the app is suspended
00397             App.Current.Suspending += appSuspendEventHandler;
00398
00399             App.Current.Resuming += appResumeEventHandler;
00400         }
00401
00402         private void UnregisterFromAppEvents()
00403         {
00404             // This event is raised when the app is exited and when the app is suspended
00405             App.Current.Suspending -= appSuspendEventHandler;
00406             appSuspendEventHandler = null;
00407
00408             App.Current.Resuming -= appResumeEventHandler;
00409             appResumeEventHandler = null;
00410         }
00411
00412         /// <summary>
00413         /// Register for Added and Removed events.
00414         /// Note that, when disconnecting the device, the device may be closed by the system before the OnDeviceRemoved callback is invoked.
00415         /// </summary>
00416         private void RegisterForDeviceWatcherEvents()
00417         {
00418             deviceAddedEventHandler = new TypedEventHandler<DeviceWatcher, DeviceInformation>(this.OnDeviceAdded);
00419
00420             deviceRemovedEventHandler = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(this.OnDeviceRemoved);
00421
00422             deviceWatcher.Added += deviceAddedEventHandler;
00423
00424             deviceWatcher.Removed += deviceRemovedEventHandler;
00425         }
00426
00427         private void UnregisterFromDeviceWatcherEvents()
00428         {
00429             deviceWatcher.Added -= deviceAddedEventHandler;
00430             deviceAddedEventHandler = null;
00431
00432             deviceWatcher.Removed -= deviceRemovedEventHandler;
00433             deviceRemovedEventHandler = null;
00434         }
00435
00436         /// <summary>
00437         /// Listen for any changed in device access permission. The user can block access to the device while the device is in use.
00438         /// If the user blocks access to the device while the device is opened, the device's handle will be closed automatically by
00439         /// the system; it is still a good idea to close the device explicitly so that resources are cleaned up.
00440         ///
00441         /// Note that by the time the AccessChanged event is raised, the device handle may already be closed by the system.
00442         /// </summary>
00443         private void RegisterForDeviceAccessStatusChange()
00444         {
00445             deviceAccessInformation = DeviceAccessInformation.CreateFromId(deviceInformation.Id);
00446
00447             deviceAccessEventHandler = new TypedEventHandler<DeviceAccessInformation, DeviceAccessChangedEventArgs>(this.OnDeviceAccessChanged);
00448             deviceAccessInformation.AccessChanged += deviceAccessEventHandler;
00449         }
00450
00451         private void UnregisterFromDeviceAccessStatusChange()
00452         {
00453             deviceAccessInformation.AccessChanged -= deviceAccessEventHandler;
00454
00455             deviceAccessEventHandler = null;
00456         }
00457
00458         private void StartDeviceWatcher()
00459         {
00460             watcherStarted = true;
00461
00462             if ((deviceWatcher.Status != DeviceWatcherStatus.Started)
00463                 && (deviceWatcher.Status != DeviceWatcherStatus.EnumerationCompleted))
00464             {
00465                 deviceWatcher.Start();
00466             }
00467         }
00468
00469         private void StopDeviceWatcher()
00470         {
00471             if ((deviceWatcher.Status == DeviceWatcherStatus.Started)
00472                 || (deviceWatcher.Status == DeviceWatcherStatus.EnumerationCompleted))
00473             {
00474                 deviceWatcher.Stop();
00475             }
00476
00477             watcherStarted = false;
00478         }
00479
00480         /// <summary>
00481         /// If a HidDevice object has been instantiated (a handle to the device is opened), we must close it before the app
00482         /// goes into suspension because the API automatically closes it for us if we don't. When resuming, the API will
00483         /// not reopen the device automatically, so we need to explicitly open the device in the app (Scenario1_DeviceConnect).
00484         ///
00485         /// Since we have to reopen the device ourselves when the app resumes, it is good practice to explicitly call the close
00486         /// in the app as well (For every open there is a close).
00487         ///
00488         /// We must stop the DeviceWatcher because it will continue to raise events even if
00489         /// the app is in suspension, which is not desired (drains battery). We resume the device watcher once the app resumes again.
00490         /// </summary>
00491         /// <param name="sender"></param>
00492         /// <param name="eventArgs"></param>
00493         private void OnAppSuspension(Object sender, SuspendingEventArgs args)
00494         {
00495             if (watcherStarted)
00496             {
00497                 watcherSuspended = true;
00498                 StopDeviceWatcher();
00499             }
00500             else
00501             {
00502                 watcherSuspended = false;
00503             }
00504
00505             CloseCurrentlyConnectedDevice();
00506         }
00507
00508         /// <summary>
00509         /// When resume into the application, we should reopen a handle to the Hid device again. This will automatically
00510         /// happen when we start the device watcher again; the device will be re-enumerated and we will attempt to reopen it
00511         /// if IsEnabledAutoReconnect property is enabled.
00512         ///
00513         /// See OnAppSuspension for why we are starting the device watcher again
00514         /// </summary>
00515         /// <param name="sender"></param>
00516         /// <param name="arg"></param>
00517         private void OnAppResume(Object sender, Object args)
00518         {
00519             if (watcherSuspended)
00520             {
00521                 watcherSuspended = false;
00522                 StartDeviceWatcher();
00523             }
00524         }
00525
00526         /// <summary>
00527         /// Close the device that is opened so that all pending operations are canceled properly.
00528         /// </summary>
00529         /// <param name="sender"></param>
00530         /// <param name="deviceInformationUpdate"></param>
00531         private void OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceInformationUpdate)
00532         {
00533             if (IsDeviceConnected && (deviceInformationUpdate.Id == deviceInformation.Id))
00534             {
00535                 // The main reasons to close the device explicitly is to clean up resources, to properly handle errors,
00536                 // and stop talking to the disconnected device.
00537                 CloseCurrentlyConnectedDevice();
00538             }
00539         }
00540
00541         /// <summary>
00542         /// Open the device that the user wanted to open if it hasn't been opened yet and auto reconnect is enabled.
00543         /// </summary>
00544         /// <param name="sender"></param>
00545         /// <param name="deviceInfo"></param>
00546         private async void OnDeviceAdded(DeviceWatcher sender, DeviceInformation deviceInfo)
00547         {
00548             if ((deviceInformation != null) && (deviceInfo.Id == deviceInformation.Id) && !IsDeviceConnected && isEnabledAutoReconnect)
00549             {
00550                 await rootPage.Dispatcher.RunAsync(
00551                     CoreDispatcherPriority.Normal,
00552                     new DispatchedHandler(async () =>
00553                     {
00554                         // If we failed to reconnect to the device, don't try to connect anymore
00555                         isEnabledAutoReconnect = await OpenDeviceAsync(deviceInformation, deviceSelector);
00556
00557                         // Any app specific device intialization should be done here because we don't know the state of the device when it is re-enumerated.
00558                     }));
00559             }
00560         }
00561
00562         /// <summary>
00563         /// Close the device if the device access was denied by anyone (system or the user) and reopen it if permissions are allowed again
00564         /// </summary>
00565         /// <param name="sender"></param>
00566         /// <param name="eventArgs"></param>
00567         private async void OnDeviceAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs eventArgs)
00568         {
00569             if ((eventArgs.Status == DeviceAccessStatus.DeniedBySystem)
00570                 || (eventArgs.Status == DeviceAccessStatus.DeniedByUser))
00571             {
00572                 CloseCurrentlyConnectedDevice();
00573             }
00574             else if ((eventArgs.Status == DeviceAccessStatus.Allowed) && (deviceInformation != null) && isEnabledAutoReconnect)
00575             {
00576                 await rootPage.Dispatcher.RunAsync(
00577                     CoreDispatcherPriority.Normal,
00578                     new DispatchedHandler(async () =>
00579                     {
00580                         // If we failed to reconnect to the device, don't try to connect anymore
00581                         isEnabledAutoReconnect = await OpenDeviceAsync(deviceInformation, deviceSelector);
00582
00583                         // Any app specific device intialization should be done here because we don't know the state of the device when it is re-enumerated.
00584                     }));
00585             }
00586         }
00587     }
00588 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Personalization/cpp/SampleConfiguration.h Source File

  • Personalization
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Lock screen personalization C++ sample";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cppwinrt/HistoryAndRoaming.h Source File

  • Clipboard
  • cppwinrt

HistoryAndRoaming.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "HistoryAndRoaming.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct HistoryAndRoaming : HistoryAndRoamingT<HistoryAndRoaming>
00020     {
00021         HistoryAndRoaming();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00025         fire_and_forget CopyButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026
00027     private:
00028         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00029         event_token historyEnabledToken;
00030         event_token roamingEnabledToken;
00031
00032         void OnHistoryEnabledChanged(Windows::Foundation::IInspectable const& sender, Windows::Foundation::IInspectable const& e);
00033         void OnRoamingEnabledChanged(Windows::Foundation::IInspectable const& sender, Windows::Foundation::IInspectable const& e);
00034         static void SelectVisibleElement(Windows::UI::Xaml::UIElement const& ifTrue, Windows::UI::Xaml::UIElement const& ifFalse, bool value);
00035         fire_and_forget CheckHistoryAndRoaming();
00036     };
00037 }
00038
00039 namespace winrt::SDKTemplate::factory_implementation
00040 {
00041     struct HistoryAndRoaming : HistoryAndRoamingT<HistoryAndRoaming, implementation::HistoryAndRoaming>
00042     {
00043     };
00044 }
Generated on Fri Nov 15 2024 22:18:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/Audio/Looping/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • Audio
  • Looping

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Xaml.Controls;
00002
00003 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00004
00005 namespace Notifications.ScenarioPages.Toasts.Audio.Looping
00006 {
00007     /// <summary>
00008     /// An empty page that can be used on its own or navigated to within a Frame.
00009     /// </summary>
00010     public sealed partial class ScenarioElement : UserControl
00011     {
00012         public ScenarioElement()
00013         {
00014             this.InitializeComponent();
00015
00016             Initialize();
00017         }
00018
00019         private void Initialize()
00020         {
00021             // Specify the toast payload
00022             popToastControl.Payload =
00023 $@"<toast scenario='incomingCall'>
00024     <visual>
00025         <binding template='ToastGeneric'>
00026             <text>Looping Audio Toast</text>
00027             <text>This toast uses looping audio, useful for scenarios like phone calls.</text>
00028         </binding>
00029     </visual>
00030     <actions>
00031         <action arguments = 'answer'
00032                 content = 'answer' />
00033         <action arguments = 'ignore'
00034                 content = 'ignore' />
00035     </actions>
00036
00037     <audio src='ms-winsoundevent:Notification.Looping.Call3' loop='true'/>
00038
00039 </toast>";
00040         }
00041     }
00042 }
Generated on Fri Nov 15 2024 22:20:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario2.xaml.h Source File

  • MapControl
  • cpp

Scenario2.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario2 sealed
00021     {
00022     public:
00023         Scenario2();
00024     private:
00025         MainPage^ rootPage = MainPage::Current;
00026         Windows::Storage::Streams::RandomAccessStreamReference^ mapIconStreamReference;
00027         Windows::Storage::Streams::RandomAccessStreamReference^ mapBillboardStreamReference;
00028         Windows::Storage::Streams::RandomAccessStreamReference^ mapModelStreamReference;
00029         void MyMap_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00030         void mapClearButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00031         void mapIconAddButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032         void mapBillboardAddButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033         void mapElement3DAddButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void mapPolygonAddButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         void mapPolylineAddButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036     };
00037 }
Generated on Fri Nov 15 2024 22:18:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cpp/Scenario4_Override.xaml.h Source File

  • DateTimeFormatting
  • cpp

Scenario4_Override.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario4_Override.g.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario4_Override sealed
00021     {
00022     public:
00023         Scenario4_Override();
00024         void Display();
00025     };
00026 }
Generated on Fri Nov 15 2024 22:19:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFont/Scenario_Document1.xaml.h Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFont

Scenario_Document1.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario_Document1.g.h"
00015 #include "MainPage.xaml.h"
00016 #include "DocumentPresenter.h"
00017
00018
00019 namespace SDKTemplate
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class Scenario_Document1 sealed
00023     {
00024     public:
00025         Scenario_Document1();
00026
00027     protected:
00028         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029
00030     private:
00031         DocumentPresenter^                              m_documentPresenter;
00032
00033         void TextLayoutFrame_SizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00034     };
00035 }
Generated on Fri Nov 15 2024 22:19:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PresenceSensor/cppwinrt/Scenario2_Polling.h Source File

  • PresenceSensor
  • cppwinrt

Scenario2_Polling.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Polling.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario2_Polling : Scenario2_PollingT<Scenario2_Polling>
00020     {
00021         Scenario2_Polling();
00022
00023         // These methods are public so they can be called by binding.
00024         fire_and_forget ScenarioGetSensor_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00025         void ScenarioGetData_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026
00027     private:
00028         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00029         Windows::Devices::Sensors::HumanPresenceSensor sensor{ nullptr };
00030     };
00031 }
00032
00033 namespace winrt::SDKTemplate::factory_implementation
00034 {
00035     struct Scenario2_Polling : Scenario2_PollingT<Scenario2_Polling, implementation::Scenario2_Polling>
00036     {
00037     };
00038 }
Generated on Fri Nov 15 2024 22:20:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cpp/Scenario5_UserCollection.xaml.h Source File

  • Store
  • cpp

Scenario5_UserCollection.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario5_UserCollection.g.h"
00016 #include "MainPage.xaml.h"
00017 #include "ItemsListViewModel.h"
00018
00019 namespace SDKTemplate
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class Scenario5_UserCollection sealed
00023     {
00024     public:
00025         Scenario5_UserCollection();
00026
00027     private:
00028         MainPage^ rootPage = MainPage::Current;
00029         Windows::Services::Store::StoreContext^ storeContext;
00030
00031         void GetUserCollectionButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032     };
00033 }
Generated on Fri Nov 15 2024 22:21:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cpp/Scenario5_DeviceReadWrite.xaml.cpp Source File

  • CustomCapability
  • cpp

Scenario5_DeviceReadWrite.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <sstream>
00014
00015 #include "MainPage.xaml.h"
00016 #include "Scenario5_DeviceReadWrite.xaml.h"
00017 #include "DeviceList.h"
00018 #include "Fx2Driver.h"
00019
00020
00021 using namespace Concurrency;
00022 using namespace Platform;
00023 using namespace SDKTemplate;
00024 using namespace Windows::Devices::Custom;
00025 using namespace Windows::Storage::Streams;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Documents;
00029
00030 DeviceReadWrite::DeviceReadWrite()
00031 {
00032     InitializeComponent();
00033 }
00034
00035 void DeviceReadWrite::ReadBlock_Click(Object^ sender, RoutedEventArgs^ e)
00036 {
00037     auto fx2Device = DeviceList::Current->GetSelectedDevice();
00038
00039     if (fx2Device == nullptr)
00040     {
00041         rootPage->NotifyUser("Fx2 device not connected or accessible", NotifyType::ErrorMessage);
00042         return;
00043     }
00044
00045     auto button = safe_cast<Button^>(sender);
00046     button->IsEnabled = false;
00047
00048     auto dataReader = ref new DataReader(fx2Device->InputStream);
00049
00050     int counter = readCounter++;
00051     LogMessage(L"Read " + counter.ToString() + L" begin");
00052
00053     // load the data reader from the stream.  For purposes of this
00054     // sample, assume all messages read are < 64 bytes
00055     create_task(dataReader->LoadAsync(64))
00056         .then([this, dataReader, counter, button](unsigned int count)
00057     {
00058         // Get the message out of the data reader
00059         String^ message = dataReader->ReadString(dataReader->UnconsumedBufferLength);
00060
00061         LogMessage(L"Read " + counter.ToString() + L" end: " + message);
00062
00063         button->IsEnabled = true;
00064     });
00065 }
00066
00067 void DeviceReadWrite::WriteBlock_Click(Object^ sender, RoutedEventArgs^ e)
00068 {
00069     auto fx2Device = DeviceList::Current->GetSelectedDevice();
00070
00071     if (fx2Device == nullptr)
00072     {
00073         rootPage->NotifyUser("Fx2 device not connected or accessible", NotifyType::ErrorMessage);
00074         return;
00075     }
00076
00077     auto button = safe_cast<Button^>(sender);
00078     button->IsEnabled = false;
00079
00080     // Generate a string to write to the device
00081     auto counter = writeCounter++;
00082
00083     auto dataWriter = ref new DataWriter();
00084
00085     auto message = ref new String(L"This is message ") + counter;
00086
00087     dataWriter->WriteString(message);
00088
00089     LogMessage(L"Write " + counter.ToString() + L" begin: " + message);
00090
00091     create_task(
00092         fx2Device->OutputStream->WriteAsync(dataWriter->DetachBuffer())
00093     ).then([this, counter, button](unsigned int bytesWritten)
00094     {
00095         LogMessage(L"Write " + counter.ToString() + L" end: " + bytesWritten.ToString() + L" bytes written");
00096         button->IsEnabled = true;
00097     });
00098 }
00099
00100
00101 void DeviceReadWrite::LogMessage(String^ message)
00102 {
00103     auto span = ref new Span();
00104     auto run = ref new Run();
00105
00106     run->Text = message;
00107
00108     span->Inlines->Append(run);
00109     span->Inlines->Append(ref new LineBreak());
00110
00111     OutputText->Inlines->InsertAt(0, span);
00112 }
Generated on Fri Nov 15 2024 22:19:03 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SampleDataModel Member List

This is the complete list of members for SampleDataModel, including all inherited members.
GetSampleData() | SampleDataModel | [inline, static]
ImagePath | SampleDataModel |
SampleDataModel(string title, string imagePath) | SampleDataModel | [inline]
Title | SampleDataModel |
ToString() | SampleDataModel |
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cpp/SampleConfiguration.cpp Source File

  • ResizeAppView
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Resizing the view", "SDKTemplate.Scenario1_Basic" },
00021     { "Launching at a custom size", "SDKTemplate.Scenario2_Launch" },
00022 };
Generated on Fri Nov 15 2024 22:17:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SerialArduino/cs/SampleConfiguration.cs Source File

  • SerialArduino
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using SerialArduino;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "SerialArduino";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Connect/Disconnect", ClassType=typeof(Scenario1_ConnectDisconnect)},
00026             new Scenario() { Title="LED/Temperature", ClassType=typeof(Scenario2_LEDTemp)}
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_PercentPermilleFormatting Member List

This is the complete list of members for Scenario1_PercentPermilleFormatting, including all inherited members.
Display_Click(object sender, RoutedEventArgs e) | Scenario1_PercentPermilleFormatting | [inline, private]
Scenario1_PercentPermilleFormatting() | Scenario1_PercentPermilleFormatting | [inline]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OrientationSensor/cpp/pch.h Source File

  • OrientationSensor
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteLineSpacingModes/cpp/DWriteLineSpacingModes/pch.cpp Source File

  • DWriteLineSpacingModes
  • cpp
  • DWriteLineSpacingModes

pch.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Include the standard header and generate the precompiled header.
00014 //
00015
00016 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationData/cppwinrt/pch.cpp Source File

  • ApplicationData
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialStage/cpp/HolographicSpatialStageMain.h Source File

  • HolographicSpatialStage
  • cpp

HolographicSpatialStageMain.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "Common\DeviceResources.h"
00004 #include "Common\StepTimer.h"
00005
00006 #include "Content\SceneController.h"
00007 #include "SpatialStageManager.h"
00008
00009 // Updates, renders, and presents holographic content using Direct3D.
00010 namespace HolographicSpatialStage
00011 {
00012     class HolographicSpatialStageMain : public DX::IDeviceNotify
00013     {
00014     public:
00015         HolographicSpatialStageMain(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00016         ~HolographicSpatialStageMain();
00017
00018         // Sets the holographic space. This is our closest analogue to setting a new window
00019         // for the app.
00020         void SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^ holographicSpace);
00021
00022         // Starts the holographic frame and updates the content.
00023         Windows::Graphics::Holographic::HolographicFrame^ Update();
00024
00025         // Renders holograms, including world-locked content.
00026         bool Render(Windows::Graphics::Holographic::HolographicFrame^ holographicFrame);
00027
00028         // IDeviceNotify
00029         virtual void OnDeviceLost();
00030         virtual void OnDeviceRestored();
00031
00032     private:
00033         // Asynchronously creates resources for new holographic cameras.
00034         void OnCameraAdded(
00035             Windows::Graphics::Holographic::HolographicSpace^ sender,
00036             Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs^ args);
00037
00038         // Synchronously releases resources for holographic cameras that are no longer
00039         // attached to the system.
00040         void OnCameraRemoved(
00041             Windows::Graphics::Holographic::HolographicSpace^ sender,
00042             Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs^ args);
00043
00044         // Used to notify the app when the positional tracking state changes.
00045         void OnLocatabilityChanged(
00046             Windows::Perception::Spatial::SpatialLocator^ sender,
00047             Platform::Object^ args);
00048
00049         // Clears event registration state. Used when changing to a new HolographicSpace
00050         // and when tearing down AppMain.
00051         void UnregisterHolographicEventHandlers();
00052
00053         std::shared_ptr<SceneController>                    m_sceneController;
00054
00055         // Cached pointer to device resources.
00056         std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00057
00058         std::shared_ptr<SpatialStageManager>                m_spatialStageManager;
00059
00060         // Render loop timer.
00061         DX::StepTimer                                       m_timer;
00062
00063         // Represents the holographic space around the user.
00064         Windows::Graphics::Holographic::HolographicSpace^   m_holographicSpace;
00065
00066         // Event registration tokens.
00067         Windows::Foundation::EventRegistrationToken         m_cameraAddedToken;
00068         Windows::Foundation::EventRegistrationToken         m_cameraRemovedToken;
00069         Windows::Foundation::EventRegistrationToken         m_locatabilityChangedToken;
00070         Windows::Foundation::EventRegistrationToken         m_gamepadAddedEventToken;
00071         Windows::Foundation::EventRegistrationToken         m_gamepadRemovedEventToken;
00072     };
00073 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInfo/cs/Scenario2_WatchUsers.xaml.cs Source File

  • UserInfo
  • cs

Scenario2_WatchUsers.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.ObjectModel;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using Windows.System;
00017 using Windows.UI.Core;
00018 using System.Threading.Tasks;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario2_WatchUsers : Page
00023     {
00024         MainPage rootPage = MainPage.Current;
00025         public ObservableCollection<UserViewModel> Users = new ObservableCollection<UserViewModel>();
00026         int userNumber = 1;
00027         UserWatcher userWatcher = null;
00028
00029         public Scenario2_WatchUsers()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             rootPage = MainPage.Current;
00037         }
00038
00039         protected override void OnNavigatedFrom(NavigationEventArgs e)
00040         {
00041             StopWatching();
00042         }
00043
00044         private void StartWatching()
00045         {
00046             rootPage.NotifyUser("", NotifyType.StatusMessage);
00047
00048             userNumber = 1;
00049             Users.Clear();
00050             userWatcher = User.CreateWatcher();
00051             userWatcher.Added += OnUserAdded;
00052             userWatcher.Updated += OnUserUpdated;
00053             userWatcher.Removed += OnUserRemoved;
00054             userWatcher.EnumerationCompleted += OnEnumerationCompleted;
00055             userWatcher.Stopped += OnWatcherStopped;
00056             userWatcher.Start();
00057             StartButton.IsEnabled = false;
00058             StopButton.IsEnabled = true;
00059         }
00060
00061
00062         private void StopWatching()
00063         {
00064             if (userWatcher != null)
00065             {
00066                 // Unregister all event handlers in case events are in flight.
00067                 userWatcher.Added -= OnUserAdded;
00068                 userWatcher.Updated -= OnUserUpdated;
00069                 userWatcher.Removed -= OnUserRemoved;
00070                 userWatcher.EnumerationCompleted -= OnEnumerationCompleted;
00071                 userWatcher.Stopped -= OnWatcherStopped;
00072                 userWatcher.Stop();
00073                 userWatcher = null;
00074                 Users.Clear();
00075                 StartButton.IsEnabled = true;
00076                 StopButton.IsEnabled = false;
00077             }
00078         }
00079
00080         private UserViewModel FindModelByUserId(string userId)
00081         {
00082             foreach (UserViewModel model in Users)
00083             {
00084                 if (model.UserId == userId)
00085                 {
00086                     return model;
00087                 }
00088             }
00089             return null;
00090         }
00091
00092         private async Task<String> GetDisplayNameOrGenericNameAsync(User user)
00093         {
00094             // Try to get the display name.
00095             string displayName = (string)await user.GetPropertyAsync(KnownUserProperties.DisplayName);
00096
00097             // Choose a generic name if we do not have access to the actual name.
00098             if (String.IsNullOrEmpty(displayName))
00099             {
00100                 displayName = "User #" + userNumber.ToString();
00101                 userNumber++;
00102             }
00103             return displayName;
00104         }
00105
00106         private async void OnUserAdded(UserWatcher sender, UserChangedEventArgs e)
00107         {
00108             User user = e.User;
00109
00110             // UI work must happen on the UI thread.
00111             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async () =>
00112             {
00113                 // Create the user with "..." as the temporary display name.
00114                 // Add it right away, because it might get removed while the
00115                 // "await GetDisplayNameOrGenericNameAsync()" is running.
00116                 var model = new UserViewModel(user.NonRoamableId, "\u2026");
00117                 Users.Add(model);
00118
00119                 // Try to get the display name.
00120                 model.DisplayName = await GetDisplayNameOrGenericNameAsync(user);
00121             });
00122         }
00123
00124         private async void OnUserUpdated(UserWatcher sender, UserChangedEventArgs e)
00125         {
00126             User user = e.User;
00127
00128             // UI work must happen on the UI thread.
00129             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async () =>
00130             {
00131                 // Look for the user in our collection and update the display name.
00132                 UserViewModel model = FindModelByUserId(user.NonRoamableId);
00133                 if (model != null)
00134                 {
00135                     model.DisplayName = await GetDisplayNameOrGenericNameAsync(user);
00136                 }
00137             });
00138         }
00139
00140         private async void OnUserRemoved(UserWatcher sender, UserChangedEventArgs e)
00141         {
00142             User user = e.User;
00143
00144             // UI work must happen on the UI thread.
00145             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
00146             {
00147                 // Look for the user in our collection and remove it.
00148                 UserViewModel model = FindModelByUserId(user.NonRoamableId);
00149                 if (model != null)
00150                 {
00151                     Users.Remove(model);
00152                 }
00153             });
00154         }
00155
00156         private async void OnEnumerationCompleted(UserWatcher sender, Object e)
00157         {
00158             // UI work must happen on the UI thread.
00159             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
00160             {
00161                 rootPage.NotifyUser("Enumeration complete. Watching for changes...", NotifyType.StatusMessage);
00162             });
00163         }
00164
00165         private async void OnWatcherStopped(UserWatcher sender, Object e)
00166         {
00167             // UI work must happen on the UI thread.
00168             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
00169             {
00170                 StopWatching();
00171             });
00172         }
00173     }
00174 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AssociationLaunching/cs/Scenario4_ReceiveUri.xaml.cs Source File

  • AssociationLaunching
  • cs

Scenario4_ReceiveUri.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.ApplicationModel.Activation;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     public sealed partial class Scenario4_ReceiveUri : Page
00023     {
00024         // A pointer back to the main page. This is needed if you want to call methods in MainPage such as NotifyUser()
00025         MainPage rootPage = MainPage.Current;
00026
00027         string Protocol = "alsdkcs";
00028
00029         public Scenario4_ReceiveUri()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         /// <summary>
00035         /// Invoked when this page is about to be displayed in a Frame.
00036         /// </summary>
00037         /// <param name="e">Event data that describes how this page was reached. The Parameter
00038         /// property is typically used to configure the page.</param>
00039         protected override void OnNavigatedTo(NavigationEventArgs e)
00040         {
00041             var args = e.Parameter as ProtocolActivatedEventArgs;
00042
00043             // Display the result of the protocol activation if we got here as a result of being activated for a protocol.
00044             if (args != null)
00045             {
00046                 rootPage.NotifyUser("Protocol activation received. The received URI is " + args.Uri.AbsoluteUri + ".", NotifyType.StatusMessage);
00047             }
00048         }
00049     }
00050 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PosPrinter/cs/Scenario1_FindClaimEnable.xaml.cs Source File

  • PosPrinter
  • cs

Scenario1_FindClaimEnable.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using Windows.Devices.PointOfService;
00016 using Windows.Devices.Enumeration;
00017 using Windows.Foundation;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Media;
00020
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario1_FindClaimEnable : Page
00025     {
00026         private MainPage rootPage = MainPage.Current;
00027         bool isBusy = false;
00028
00029         public Scenario1_FindClaimEnable()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             RetainDeviceCheckBox.IsChecked = rootPage.IsAnImportantTransaction;
00037             rootPage.StateChanged += UpdateButtons;
00038             UpdateButtons();
00039         }
00040
00041         protected override void OnNavigatedFrom(NavigationEventArgs e)
00042         {
00043             rootPage.StateChanged -= UpdateButtons;
00044         }
00045
00046         void UpdateButtons()
00047         {
00048             PrinterNameRun.Text = (rootPage.Printer == null) ? "None" : rootPage.deviceInfo.Name + " (" + rootPage.Printer.DeviceId + ")";
00049             if (isBusy)
00050             {
00051                 FindButton.IsEnabled = false;
00052                 ClaimAndEnableButton.IsEnabled = false;
00053                 ReleaseClaimedPrinterButton.IsEnabled = false;
00054                 ReleaseAllPrintersButton.IsEnabled = false;
00055             }
00056             else if (rootPage.Printer == null)
00057             {
00058                 FindButton.IsEnabled = true;
00059                 ClaimAndEnableButton.IsEnabled = false;
00060                 ReleaseClaimedPrinterButton.IsEnabled = false;
00061                 ReleaseAllPrintersButton.IsEnabled = false;
00062             }
00063             else
00064             {
00065                 FindButton.IsEnabled = false;
00066                 ReleaseAllPrintersButton.IsEnabled = true;
00067                 if (rootPage.ClaimedPrinter == null)
00068                 {
00069                     ClaimAndEnableButton.IsEnabled = true;
00070                     ReleaseClaimedPrinterButton.IsEnabled = false;
00071                 }
00072                 else
00073                 {
00074                     ClaimAndEnableButton.IsEnabled = false;
00075                     ReleaseClaimedPrinterButton.IsEnabled = true;
00076                 }
00077             }
00078         }
00079
00080         async void FindPrinter_Click()
00081         {
00082             isBusy = true;
00083             UpdateButtons();
00084             rootPage.NotifyUser("", NotifyType.StatusMessage);
00085
00086             rootPage.ReleaseAllPrinters();
00087
00088             // Select a PosPrinter device using the Device Picker.
00089             DevicePicker devicePicker = new DevicePicker();
00090             devicePicker.Filter.SupportedDeviceSelectors.Add(PosPrinter.GetDeviceSelector());
00091
00092             // Anchor the picker on the Find button.
00093             GeneralTransform ge = FindButton.TransformToVisual(Window.Current.Content as UIElement);
00094             Rect rect = ge.TransformBounds(new Rect(0, 0, FindButton.ActualWidth, FindButton.ActualHeight));
00095
00096             DeviceInformation deviceInfo = await devicePicker.PickSingleDeviceAsync(rect);
00097             rootPage.deviceInfo = deviceInfo;
00098             PosPrinter printer = null;
00099             if (deviceInfo != null)
00100             {
00101                 printer = await PosPrinter.FromIdAsync(deviceInfo.Id);
00102             }
00103             if (printer != null && printer.Capabilities.Receipt.IsPrinterPresent)
00104             {
00105                 rootPage.Printer = printer;
00106                 rootPage.NotifyUser("Found receipt printer.", NotifyType.StatusMessage);
00107             }
00108             else
00109             {
00110                 // Get rid of the printer we can't use.
00111                 printer?.Dispose();
00112                 rootPage.NotifyUser("Please select a device whose printer is present.", NotifyType.ErrorMessage);
00113             }
00114
00115             isBusy = false;
00116             UpdateButtons();
00117         }
00118
00119         async void ClaimAndEnable_Click()
00120         {
00121             isBusy = true;
00122             UpdateButtons();
00123             rootPage.ClaimedPrinter = await rootPage.Printer.ClaimPrinterAsync();
00124             if (rootPage.ClaimedPrinter == null)
00125             {
00126                 rootPage.NotifyUser("Unable to claim printer", NotifyType.ErrorMessage);
00127             }
00128             else
00129             {
00130                 rootPage.NotifyUser("Claimed printer", NotifyType.StatusMessage);
00131
00132                 // Register for the ReleaseDeviceRequested event so we know when somebody
00133                 // wants to claim the printer away from us.
00134                 rootPage.SubscribeToReleaseDeviceRequested();
00135
00136                 if (await rootPage.ClaimedPrinter.EnableAsync())
00137                 {
00138                     rootPage.NotifyUser("Enabled printer.", NotifyType.StatusMessage);
00139                 }
00140                 else
00141                 {
00142                     rootPage.NotifyUser("Could not enable printer", NotifyType.ErrorMessage);
00143                     rootPage.ReleaseClaimedPrinter();
00144                 }
00145             }
00146
00147             isBusy = false;
00148             UpdateButtons();
00149         }
00150
00151         void IsImportantTransaction_Click()
00152         {
00153             rootPage.IsAnImportantTransaction = RetainDeviceCheckBox.IsChecked.Value;
00154         }
00155
00156         void ReleaseClaim_Click()
00157         {
00158             rootPage.ReleaseClaimedPrinter();
00159         }
00160
00161         void ReleaseAll_Click()
00162         {
00163             rootPage.ReleaseAllPrinters();
00164         }
00165     }
00166 }
Generated on Fri Nov 15 2024 22:20:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_CharacterGrouping Member List

This is the complete list of members for Scenario4_CharacterGrouping, including all inherited members.
ActiveGroupings | Scenario4_CharacterGrouping | [private]
AddGroup(string label, UIElement element) | Scenario4_CharacterGrouping | [inline, private]
AssignGroup_Click(object sender, RoutedEventArgs e) | Scenario4_CharacterGrouping | [inline]
GetGroups_Click(object sender, RoutedEventArgs e) | Scenario4_CharacterGrouping | [inline]
GlobeString | Scenario4_CharacterGrouping | [private, static]
groups | Scenario4_CharacterGrouping | [private]
rootPage | Scenario4_CharacterGrouping | [private]
Scenario4_CharacterGrouping() | Scenario4_CharacterGrouping | [inline]
Generated on Fri Nov 15 2024 22:23:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/Trace.cpp Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

Trace.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "Trace.h"
00010
00011 DWORD g_dwLogLevel = TRACE_LEVEL_NORMAL;
00012
00013 void Trace(DWORD dwLevel, LPCWSTR pszFormat, ...)
00014 {
00015     if (g_dwLogLevel > dwLevel)
00016     {
00017         return;
00018     }
00019     WCHAR szTextBuf[256];
00020     va_list args;
00021     va_start(args, pszFormat);
00022
00023     StringCchVPrintf(szTextBuf, _countof(szTextBuf), pszFormat, args);
00024
00025     OutputDebugString(szTextBuf);
00026 }
00027
00028 void TraceError(LPCSTR pszFile, long nLine, LPCSTR pszFunc, Object ^pThis, HRESULT hr)
00029 {
00030     TraceError(pszFile, nLine, pszFunc, reinterpret_cast<IInspectable*>(pThis), hr);
00031 }
00032
00033 void TraceError(LPCSTR pszFile, long nLine, LPCSTR pszFunc, const void * pThis, HRESULT hr)
00034 {
00035     if (SUCCEEDED(hr))
00036     {
00037         return;
00038     }
00039     LPCSTR psz = pszFile + strlen(pszFile);
00040     for(;psz > pszFile; psz--)
00041     {
00042         if(*psz == '\\')
00043         {
00044             pszFile = psz+1;
00045             break;
00046         }
00047     }
00048     WCHAR szTextBuf[256];
00049     szTextBuf[0] = 0;
00050     StringCchPrintf(szTextBuf, _countof(szTextBuf), L"%S:%d (%S@%p) FAILED hr=%x\n", pszFile, nLine, pszFunc, pThis, hr);
00051     OutputDebugString(szTextBuf);
00052 }
00053
00054 void PrintSampleInfo(IMFSample *pSample)
00055 {
00056     ComPtr<IMFMediaBuffer> spBuffer;
00057     pSample->GetBufferByIndex(0, &spBuffer);
00058
00059     DWORD cbTotalLen;
00060     DWORD cbMaxLen;
00061     DWORD cbCurLen;
00062     LONGLONG llDur;
00063     LONGLONG llTs;
00064     pSample->GetTotalLength(&cbTotalLen);
00065     pSample->GetSampleDuration(&llDur);
00066     pSample->GetSampleTime(&llTs);
00067
00068     Trace(TRACE_LEVEL_HIGH, L"Sample - Ts: %I64d Dur: %I64d Len: %d\n", llTs, llDur, cbTotalLen);
00069     BYTE *pByte;
00070     spBuffer->Lock(&pByte, &cbMaxLen, &cbCurLen);
00071     if (cbCurLen >= sizeof(LONGLONG))
00072     {
00073         Trace(TRACE_LEVEL_HIGH, L"Sample beginning - Ts: 0x%I64x\n", *(LONGLONG*)pByte);
00074     }
00075
00076     PrintAttributes(pSample);
00077 }
00078
00079 void PrintAttributes(IMFAttributes *pAttributes)
00080 {
00081     UINT32 cAttr;
00082     pAttributes->GetCount(&cAttr);
00083     Trace(TRACE_LEVEL_HIGH, L"No attributes %d\n", cAttr);
00084
00085     for (UINT32 i = 0; i < cAttr; ++i)
00086     {
00087         const DWORD CHARS_IN_GUID = 39;
00088         PROPVARIANT var = {0};
00089         GUID gui;
00090         OLECHAR szAttrId[CHARS_IN_GUID];
00091
00092         pAttributes->GetItemByIndex(i, &gui, &var);
00093         StringFromGUID2(gui, szAttrId, CHARS_IN_GUID);
00094
00095         switch (var.vt)
00096         {
00097         case MF_ATTRIBUTE_UINT32:
00098             Trace(TRACE_LEVEL_HIGH, L"Attr: %s - %d\n", szAttrId, var.uintVal);
00099             break;
00100         case MF_ATTRIBUTE_UINT64:
00101             Trace(TRACE_LEVEL_HIGH, L"Attr: %s - %I64d\n", szAttrId, var.uhVal.QuadPart);
00102             break;
00103         case MF_ATTRIBUTE_DOUBLE:
00104             Trace(TRACE_LEVEL_HIGH, L"Attr: %s - %f\n", szAttrId, var.dblVal);
00105             break;
00106         case MF_ATTRIBUTE_GUID:
00107             OLECHAR szAttrVal[CHARS_IN_GUID];
00108             StringFromGUID2(*var.puuid, szAttrVal, CHARS_IN_GUID);
00109             Trace(TRACE_LEVEL_HIGH, L"Attr: %s - %s\n", szAttrId, szAttrVal);
00110             break;
00111         case MF_ATTRIBUTE_BLOB:
00112             if (var.caub.cElems >= 8)
00113             {
00114                 Trace(TRACE_LEVEL_HIGH, L"Attr: %s BLOB - %I64x\n", szAttrId, *(LONGLONG*)var.caub.pElems);
00115             }
00116             else if (var.caub.cElems > 0)
00117             {
00118                 Trace(TRACE_LEVEL_HIGH, L"Attr: %s BLOB - %c\n", szAttrId, var.caub.pElems[0]);
00119             }
00120             else
00121             {
00122                 Trace(TRACE_LEVEL_HIGH, L"Attr: %s empty blob\n", szAttrId, var.caub.pElems[0]);
00123             }
00124             break;
00125         case MF_ATTRIBUTE_STRING:
00126             Trace(TRACE_LEVEL_HIGH, L"Attr: %s %s\n", szAttrId, var.pwszVal);
00127             break;
00128         default:
00129             Trace(TRACE_LEVEL_HIGH, L"Attr: %s TYPE %hd\n", szAttrId, var.vt);
00130             break;
00131         }
00132
00133         PropVariantClear(&var);
00134     }
00135 }
Generated on Fri Nov 15 2024 22:21:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cpp/Scenario4.xaml.cpp Source File

  • FileThumbnails
  • cpp

Scenario4.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario4.xaml.cpp
00014 // Implementation of the Scenario4 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario4.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace concurrency;
00023 using namespace Platform;
00024 using namespace Windows::Storage;
00025 using namespace Windows::Storage::FileProperties;
00026 using namespace Windows::Storage::Pickers;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 Scenario4::Scenario4()
00032 {
00033     InitializeComponent();
00034     rootPage = MainPage::Current;
00035 }
00036
00037 void Scenario4::OnNavigatedTo(NavigationEventArgs^ e)
00038 {
00039     rootPage->ResetOutput(ThumbnailImage, OutputTextBlock, nullptr);
00040 }
00041
00042 void Scenario4::GetThumbnailButton_Click(Object^ sender, RoutedEventArgs^ e)
00043 {
00044     rootPage->ResetOutput(ThumbnailImage, OutputTextBlock, nullptr);
00045
00046     // Pick a folder
00047     FolderPicker^ folderPicker = ref new FolderPicker();
00048     Array<String^>^ extensions = FileExtensions::Image;
00049     for (unsigned int i = 0; i < extensions->Length; i++)
00050     {
00051         folderPicker->FileTypeFilter->Append(extensions[i]);
00052     }
00053
00054     create_task(folderPicker->PickSingleFolderAsync()).then([this](StorageFolder^ folder)
00055     {
00056         if (folder != nullptr)
00057         {
00058             const ThumbnailMode thumbnailMode = ThumbnailMode::PicturesView;
00059             const size_t size = 200;
00060             create_task(folder->GetThumbnailAsync(thumbnailMode, size)).then([this, folder, size](StorageItemThumbnail^ thumbnail)
00061             {
00062                 if (thumbnail != nullptr)
00063                 {
00064                     MainPage::DisplayResult(ThumbnailImage, OutputTextBlock, "PicturesView", size, folder, thumbnail, false);
00065                 }
00066                 else
00067                 {
00068                     rootPage->NotifyUser(Errors::NoImages, NotifyType::StatusMessage);
00069                 }
00070             });
00071         }
00072         else
00073         {
00074             rootPage->NotifyUser(Errors::Cancel, NotifyType::StatusMessage);
00075         }
00076     });
00077 }
Generated on Fri Nov 15 2024 22:18:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cpp/Scenario1_Create.xaml.h Source File

  • Playlists
  • cpp

Scenario1_Create.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario1_Create.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario1_Create sealed
00012     {
00013     public:
00014         Scenario1_Create();
00015     private:
00016         MainPage^ rootPage;
00017         void PickAudioButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00018     };
00019 }
Generated on Fri Nov 15 2024 22:19:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cs/cpp/pch.h Source File

  • ProxyStubsForWinRTComponents
  • cs
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <wrl\event.h>
00008 #include <wrl\implements.h>
00009 #include <wrl\wrappers\corewrappers.h>
00010 #include <collection.h>
00011 #include <ppltasks.h>
00012
00013 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cpp/Scenario2_History.xaml.h Source File

  • ActivitySensor
  • cpp

Scenario2_History.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_History.xaml.h
00014 // Declaration of the Scenario2_History class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario2_History.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario2_History sealed
00030     {
00031     public:
00032         Scenario2_History();
00033
00034     private:
00035         SDKTemplate::MainPage^ rootPage;
00036
00037         void ScenarioGetActivityHistory(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Fri Nov 15 2024 22:17:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cs/Scenario3_SeekerDiscover.xaml.cs Source File

  • WiFiDirectServices
  • cs

Scenario3_SeekerDiscover.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Devices.WiFiDirect.Services;
00015 using Windows.UI.Core;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00020
00021 namespace SDKTemplate
00022 {
00023     namespace WiFiDirectServices
00024     {
00025         /// <summary>
00026         /// UI that provides a way to discover any Wi-Fi Direct service by name
00027         /// A real application would likely hard-code the service name to a well-known service rather than expose this in the UI
00028         ///
00029         /// Most of the actual logic for Wi-Fi Direct Services is in WiFiDirectServicesManager.cs and WiFiDirectServicesWrappers.cs
00030         /// </summary>
00031         public sealed partial class Scenario3 : Page
00032         {
00033             private Object thisLock = new Object();
00034
00035             private MainPage rootPage;
00036
00037             private WiFiDirectServiceProvisioningInfo provisioningInfo;
00038
00039             public Scenario3()
00040             {
00041                 this.InitializeComponent();
00042             }
00043
00044             protected override void OnNavigatedTo(NavigationEventArgs e)
00045             {
00046                 lock (thisLock)
00047                 {
00048                     rootPage = MainPage.Current;
00049
00050                     // Cleanup past discoveries
00051                     DiscoveredServices.Items.Clear();
00052                     provisioningInfo = null;
00053
00054                     UpdateDiscoveryList(WiFiDirectServiceManager.Instance.DiscoveredDevices);
00055                 }
00056                 WiFiDirectServiceManager.Instance.Scenario3 = this;
00057             }
00058
00059             protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00060             {
00061                 WiFiDirectServiceManager.Instance.Scenario3 = null;
00062             }
00063
00064             public async void UpdateDiscoveryList(IList<DiscoveredDeviceWrapper> devices)
00065             {
00066                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00067                 {
00068                     lock (thisLock)
00069                     {
00070                         DiscoveredServices.Items.Clear();
00071                         foreach (var device in devices)
00072                         {
00073                             DiscoveredServices.Items.Add(device);
00074                         }
00075                     }
00076                 });
00077             }
00078
00079             public async void SessionConnected()
00080             {
00081                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00082                 {
00083                     // Force navigation to the next page for smoother experience
00084                     rootPage.GoToScenario(3);
00085                 });
00086             }
00087
00088             private void Discover_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00089             {
00090                 WiFiDirectServiceManager.Instance.DiscoverServicesAsync(
00091                     ServiceName.Text,
00092                     RequestedServiceInfo.Text
00093                     );
00094             }
00095
00096             // An application has two ways to connect over Wi-Fi Direct services
00097             // 1) First call GetProvisioningInfoAsync to begin connecting,
00098             //        a) if a PIN is required (group formation is required and selected config method is PinEntry or PinDisplay) then call ConnectAsync with the PIN
00099             //        b) else if no PIN is required then call ConnectAsync with no PIN
00100             // 2) Call ConnectAsync to connect without a PIN and prefer the Wi-Fi Direct Default config method, if possible
00101
00102             private async void GetProvisioningInfo_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00103             {
00104                 if (DiscoveredServices.Items.Count > 0)
00105                 {
00106                     int index = DiscoveredServices.SelectedIndex;
00107                     if (index >= 0)
00108                     {
00109                         DiscoveredDeviceWrapper service = (DiscoveredDeviceWrapper)DiscoveredServices.Items[index];
00110
00111                         WiFiDirectServiceConfigurationMethod configMethod = WiFiDirectServiceConfigurationMethod.Default;
00112                         if (((ComboBoxItem)SelectedConfigMethod.SelectedItem).Content.ToString() == "WFDS Default")
00113                         {
00114                             configMethod = WiFiDirectServiceConfigurationMethod.Default;
00115                         }
00116                         else if (((ComboBoxItem)SelectedConfigMethod.SelectedItem).Content.ToString() == "PIN Keypad")
00117                         {
00118                             configMethod = WiFiDirectServiceConfigurationMethod.PinEntry;
00119                         }
00120                         else if (((ComboBoxItem)SelectedConfigMethod.SelectedItem).Content.ToString() == "PIN Display")
00121                         {
00122                             configMethod = WiFiDirectServiceConfigurationMethod.PinDisplay;
00123                         }
00124
00125                         await service.OpenSessionAsync();
00126                         await service.SetServiceOptionsAsync(PreferGO.IsChecked ?? false, SessionInfo.Text);
00127                         provisioningInfo = await service.GetProvisioningInfoAsync(configMethod);
00128                     }
00129                 }
00130             }
00131
00132             private async void DoConnect_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00133             {
00134                 if (DiscoveredServices.Items.Count > 0)
00135                 {
00136                     int index = DiscoveredServices.SelectedIndex;
00137                     if (index >= 0)
00138                     {
00139                         DiscoveredDeviceWrapper service = (DiscoveredDeviceWrapper)DiscoveredServices.Items[index];
00140
00141                         await service.SetServiceOptionsAsync(PreferGO.IsChecked ?? false, SessionInfo.Text);
00142
00143                         if (provisioningInfo != null &&
00144                             provisioningInfo.IsGroupFormationNeeded &&
00145                             provisioningInfo.SelectedConfigurationMethod != WiFiDirectServiceConfigurationMethod.Default)
00146                         {
00147                             // These are the conditions under which a PIN is required
00148                             service.ConnectAsync(ConnectPin.Text);
00149                         }
00150                         else
00151                         {
00152                             // No PIN required
00153                             service.ConnectAsync();
00154                         }
00155                     }
00156                 }
00157             }
00158         }
00159     }
00160 }
Generated on Fri Nov 15 2024 22:22:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothLE/cppwinrt/BluetoothLEAttributeDisplay.cpp Source File

  • BluetoothLE
  • cppwinrt

BluetoothLEAttributeDisplay.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
00002 #include "BluetoothLEAttributeDisplay.h"
00003
00004 using namespace winrt;
00005 using namespace Windows::Devices::Bluetooth::GenericAttributeProfile;
00006
00007 namespace
00008 {
00009     /// <summary>
00010     ///  Determines whether the UUID was assigned by the Bluetooth SIG.
00011     ///  If so, extracts the assigned number.
00012     /// </summary>
00013
00014     bool TryParseSigDefinedUuid(guid const& uuid, uint16_t& shortId)
00015     {
00016         // UUIDs defined by the Bluetooth SIG are of the form
00017         // 0000xxxx-0000-1000-8000-00805F9B34FB.
00018         constexpr guid BluetoothGuid = { 0x00000000, 0x0000, 0x1000, { 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB } };
00019
00020         shortId = static_cast<uint16_t>(uuid.Data1);
00021         guid possibleBluetoothGuid = uuid;
00022         possibleBluetoothGuid.Data1 &= 0xFFFF0000;
00023         return possibleBluetoothGuid == BluetoothGuid;
00024     }
00025 }
00026
00027 namespace winrt::SDKTemplate::DisplayHelpers
00028 {
00029     hstring GetServiceName(GattDeviceService const& service)
00030     {
00031         uint16_t shortId;
00032
00033         guid uuid = service.Uuid();
00034         if (TryParseSigDefinedUuid(uuid, shortId))
00035         {
00036             // Reference: https://developer.bluetooth.org/gatt/services/Pages/ServicesHome.aspx
00037             const static std::map<uint32_t, const wchar_t*> knownServiceIds =
00038             {
00039                 { 0x0000, L"None" },
00040                 { 0x1811, L"AlertNotification" },
00041                 { 0x180F, L"Battery" },
00042                 { 0x1810, L"BloodPressure" },
00043                 { 0x1805, L"CurrentTimeService" },
00044                 { 0x1816, L"CyclingSpeedandCadence" },
00045                 { 0x180A, L"DeviceInformation" },
00046                 { 0x1800, L"GenericAccess" },
00047                 { 0x1801, L"GenericAttribute" },
00048                 { 0x1808, L"Glucose" },
00049                 { 0x1809, L"HealthThermometer" },
00050                 { 0x180D, L"HeartRate" },
00051                 { 0x1812, L"HumanInterfaceDevice" },
00052                 { 0x1802, L"ImmediateAlert" },
00053                 { 0x1803, L"LinkLoss" },
00054                 { 0x1807, L"NextDSTChange" },
00055                 { 0x180E, L"PhoneAlertStatus" },
00056                 { 0x1806, L"ReferenceTimeUpdateService" },
00057                 { 0x1814, L"RunningSpeedandCadence" },
00058                 { 0x1813, L"ScanParameters" },
00059                 { 0x1804, L"TxPower" },
00060                 { 0xFFE0, L"SimpleKeyService" },
00061             };
00062             auto it = knownServiceIds.find(shortId);
00063             if (it != knownServiceIds.end())
00064             {
00065                 return it->second;
00066             }
00067         }
00068         return L"Custom service: " + to_hstring(uuid);
00069     }
00070
00071     hstring GetCharacteristicName(GattCharacteristic const& characteristic)
00072     {
00073         uint16_t shortId;
00074
00075         guid uuid = characteristic.Uuid();
00076         if (TryParseSigDefinedUuid(uuid, shortId))
00077         {
00078             // Reference: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicsHome.aspx
00079             const static std::map<uint32_t, const wchar_t*> knownCharacteristicIds =
00080             {
00081                 { 0x0000, L"None" },
00082                 { 0x2A43, L"AlertCategoryID" },
00083                 { 0x2A42, L"AlertCategoryIDBitMask" },
00084                 { 0x2A06, L"AlertLevel" },
00085                 { 0x2A44, L"AlertNotificationControlPoint" },
00086                 { 0x2A3F, L"AlertStatus" },
00087                 { 0x2A01, L"Appearance" },
00088                 { 0x2A19, L"BatteryLevel" },
00089                 { 0x2A49, L"BloodPressureFeature" },
00090                 { 0x2A35, L"BloodPressureMeasurement" },
00091                 { 0x2A38, L"BodySensorLocation" },
00092                 { 0x2A22, L"BootKeyboardInputReport" },
00093                 { 0x2A32, L"BootKeyboardOutputReport" },
00094                 { 0x2A33, L"BootMouseInputReport" },
00095                 { 0x2A5C, L"CSCFeature" },
00096                 { 0x2A5B, L"CSCMeasurement" },
00097                 { 0x2A2B, L"CurrentTime" },
00098                 { 0x2A08, L"DateTime" },
00099                 { 0x2A0A, L"DayDateTime" },
00100                 { 0x2A09, L"DayofWeek" },
00101                 { 0x2A00, L"DeviceName" },
00102                 { 0x2A0D, L"DSTOffset" },
00103                 { 0x2A0C, L"ExactTime256" },
00104                 { 0x2A26, L"FirmwareRevisionString" },
00105                 { 0x2A51, L"GlucoseFeature" },
00106                 { 0x2A18, L"GlucoseMeasurement" },
00107                 { 0x2A34, L"GlucoseMeasurementContext" },
00108                 { 0x2A27, L"HardwareRevisionString" },
00109                 { 0x2A39, L"HeartRateControlPoint" },
00110                 { 0x2A37, L"HeartRateMeasurement" },
00111                 { 0x2A4C, L"HIDControlPoint" },
00112                 { 0x2A4A, L"HIDInformation" },
00113                 { 0x2A2A, L"IEEE11073_20601RegulatoryCertificationDataList" },
00114                 { 0x2A36, L"IntermediateCuffPressure" },
00115                 { 0x2A1E, L"IntermediateTemperature" },
00116                 { 0x2A0F, L"LocalTimeInformation" },
00117                 { 0x2A29, L"ManufacturerNameString" },
00118                 { 0x2A21, L"MeasurementInterval" },
00119                 { 0x2A24, L"ModelNumberString" },
00120                 { 0x2A46, L"NewAlert" },
00121                 { 0x2A04, L"PeripheralPreferredConnectionParameters" },
00122                 { 0x2A02, L"PeripheralPrivacyFlag" },
00123                 { 0x2A50, L"PnPID" },
00124                 { 0x2A4E, L"ProtocolMode" },
00125                 { 0x2A03, L"ReconnectionAddress" },
00126                 { 0x2A52, L"RecordAccessControlPoint" },
00127                 { 0x2A14, L"ReferenceTimeInformation" },
00128                 { 0x2A4D, L"Report" },
00129                 { 0x2A4B, L"ReportMap" },
00130                 { 0x2A40, L"RingerControlPoint" },
00131                 { 0x2A41, L"RingerSetting" },
00132                 { 0x2A54, L"RSCFeature" },
00133                 { 0x2A53, L"RSCMeasurement" },
00134                 { 0x2A55, L"SCControlPoint" },
00135                 { 0x2A4F, L"ScanIntervalWindow" },
00136                 { 0x2A31, L"ScanRefresh" },
00137                 { 0x2A5D, L"SensorLocation" },
00138                 { 0x2A25, L"SerialNumberString" },
00139                 { 0x2A05, L"ServiceChanged" },
00140                 { 0x2A28, L"SoftwareRevisionString" },
00141                 { 0x2A47, L"SupportedNewAlertCategory" },
00142                 { 0x2A48, L"SupportedUnreadAlertCategory" },
00143                 { 0x2A23, L"SystemID" },
00144                 { 0x2A1C, L"TemperatureMeasurement" },
00145                 { 0x2A1D, L"TemperatureType" },
00146                 { 0x2A12, L"TimeAccuracy" },
00147                 { 0x2A13, L"TimeSource" },
00148                 { 0x2A16, L"TimeUpdateControlPoint" },
00149                 { 0x2A17, L"TimeUpdateState" },
00150                 { 0x2A11, L"TimewithDST" },
00151                 { 0x2A0E, L"TimeZone" },
00152                 { 0x2A07, L"TxPowerLevel" },
00153                 { 0x2A45, L"UnreadAlertStatus" },
00154                 { 0x2A5A, L"AggregateInput" },
00155                 { 0x2A58, L"AnalogInput" },
00156                 { 0x2A59, L"AnalogOutput" },
00157                 { 0x2A66, L"CyclingPowerControlPoint" },
00158                 { 0x2A65, L"CyclingPowerFeature" },
00159                 { 0x2A63, L"CyclingPowerMeasurement" },
00160                 { 0x2A64, L"CyclingPowerVector" },
00161                 { 0x2A56, L"DigitalInput" },
00162                 { 0x2A57, L"DigitalOutput" },
00163                 { 0x2A0B, L"ExactTime100" },
00164                 { 0x2A6B, L"LNControlPoint" },
00165                 { 0x2A6A, L"LNFeature" },
00166                 { 0x2A67, L"LocationandSpeed" },
00167                 { 0x2A68, L"Navigation" },
00168                 { 0x2A3E, L"NetworkAvailability" },
00169                 { 0x2A69, L"PositionQuality" },
00170                 { 0x2A3C, L"ScientificTemperatureinCelsius" },
00171                 { 0x2A10, L"SecondaryTimeZone" },
00172                 { 0x2A3D, L"String" },
00173                 { 0x2A1F, L"TemperatureinCelsius" },
00174                 { 0x2A20, L"TemperatureinFahrenheit" },
00175                 { 0x2A15, L"TimeBroadcast" },
00176                 { 0x2A1B, L"BatteryLevelState" },
00177                 { 0x2A1A, L"BatteryPowerState" },
00178                 { 0x2A5F, L"PulseOximetryContinuousMeasurement" },
00179                 { 0x2A62, L"PulseOximetryControlPoint" },
00180                 { 0x2A61, L"PulseOximetryFeatures" },
00181                 { 0x2A60, L"PulseOximetryPulsatileEvent" },
00182                 { 0xFFE1, L"SimpleKeyState" },
00183             };
00184
00185             auto it = knownCharacteristicIds.find(shortId);
00186             if (it != knownCharacteristicIds.end())
00187             {
00188                 return it->second;
00189             }
00190         }
00191
00192         hstring userDescription = characteristic.UserDescription();
00193         if (!userDescription.empty())
00194         {
00195             return userDescription;
00196         }
00197
00198         return L"Custom Characteristic: " + to_hstring(uuid);
00199     }
00200 }
Generated on Fri Nov 15 2024 22:18:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cs/FileLoggingSessionScenario.cs Source File

  • Logging
  • cs

FileLoggingSessionScenario.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using System;
00008 using System.Threading.Tasks;
00009 using Windows.Foundation.Diagnostics;
00010 using Windows.Storage;
00011
00012 namespace SDKTemplate
00013 {
00014     /// <summary>
00015     /// FileLoggingSessionScenario is a central singleton class which contains the logging-specific
00016     /// sample code.
00017     /// </summary>
00018     internal class FileLoggingSessionScenario
00019         : IDisposable
00020     {
00021         #region Primary scenario code
00022
00023         private string GetTimeStamp()
00024         {
00025             DateTime now = DateTime.Now;
00026             return string.Format(System.Globalization.CultureInfo.InvariantCulture,
00027                                  "{0:D2}{1:D2}{2:D2}-{3:D2}{4:D2}{5:D2}{6:D3}",
00028                                  now.Year - 2000,
00029                                  now.Month,
00030                                  now.Day,
00031                                  now.Hour,
00032                                  now.Minute,
00033                                  now.Second,
00034                                  now.Millisecond);
00035         }
00036
00037         /// <summary>
00038         /// Toggle the enabled/disabled status of logging.
00039         /// </summary>
00040         /// <returns>True if the resulting new status is enabled, else false for disabled.</returns>
00041         public async Task<bool> ToggleLoggingEnabledDisabledAsync()
00042         {
00043             CheckDisposed();
00044
00045             IsBusy = true;
00046
00047             try
00048             {
00049                 bool enabled;
00050                 if (session != null)
00051                 {
00052                     string finalLogFilePath = await CloseSessionSaveFinalLogFile();
00053                     session.Dispose();
00054                     session = null;
00055                     if (StatusChanged != null)
00056                     {
00057                         StatusChanged.Invoke(this, new LoggingScenarioEventArgs(LoggingScenarioEventType.LogFileGeneratedAtDisable, finalLogFilePath));
00058                     }
00059                     ApplicationData.Current.LocalSettings.Values[LOGGING_ENABLED_SETTING_KEY_NAME] = false;
00060                     enabled = false;
00061                 }
00062                 else
00063                 {
00064                     StartLogging();
00065                     ApplicationData.Current.LocalSettings.Values[LOGGING_ENABLED_SETTING_KEY_NAME] = true;
00066                     enabled = true;
00067                 }
00068
00069                 if (StatusChanged != null)
00070                 {
00071                     StatusChanged.Invoke(this, new LoggingScenarioEventArgs(enabled));
00072                 }
00073
00074                 return enabled;
00075             }
00076             finally
00077             {
00078                 IsBusy = false;
00079             }
00080         }
00081
00082         /// <summary>
00083         /// The logging scenario. Log messages in a loop until 3 log files are created.
00084         /// </summary>
00085         /// <returns>The task.</returns>
00086         public async Task DoScenarioAsync()
00087         {
00088             CheckDisposed();
00089
00090             IsBusy = true;
00091
00092             try
00093             {
00094                 await Task.Run(async () =>
00095                 {
00096                     const int NUMBER_OF_LOG_FILES_TO_GENERATE = 3;
00097                     int messageIndex = 0;
00098                     int startFileCount = LogFileGeneratedCount;
00099
00100                     //
00101                     // Log large messages until the current log file hits the maximum size.
00102                     // When the current log file reaches its maximum size, LogFileGeneratedHandler
00103                     // will be called.
00104                     //
00105
00106                     while (LogFileGeneratedCount - startFileCount < NUMBER_OF_LOG_FILES_TO_GENERATE)
00107                     {
00108                         // Since the channel is added to the session at level Warning,
00109                         // the following is logged because it is logged at level LoggingLevel.Critical.
00110                         channel.LogMessage(
00111                             string.Format("Message={0}: Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ligula nisi, vehicula nec eleifend vel, rutrum non dolor. Vestibulum ante ipsum " +
00112                                           "primis in faucibus orci luctus et ultrices posuere cubilia Curae; Curabitur elementum scelerisque accumsan. In hac habitasse platea dictumst.",
00113                                           ++messageIndex),
00114                             LoggingLevel.Critical);
00115
00116                         // Since the channel is added to the session at level Warning,
00117                         // the following is *not* logged because it is logged at LoggingLevel.Information.
00118                         channel.LogMessage(
00119                             string.Format("Message={0}: Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ligula nisi, vehicula nec eleifend vel, rutrum non dolor. Vestibulum ante ipsum " +
00120                                           "primis in faucibus orci luctus et ultrices posuere cubilia Curae; Curabitur elementum scelerisque accumsan. In hac habitasse platea dictumst.",
00121                                           ++messageIndex),
00122                             LoggingLevel.Information);
00123
00124                         int value = 1000000; // one million, 7 digits, 4-bytes as an int, 14 bytes as a wide character string.
00125                         channel.LogMessage("Value #" + messageIndex.ToString() + "  " + value.ToString(), LoggingLevel.Critical); // value is logged as 14 byte wide character string.
00126                         channel.LogValuePair("Value #" + messageIndex.ToString(), value, LoggingLevel.Critical); // value is logged as a 4-byte integer.
00127
00128                         //
00129                         // Pause every once in a while to simulate application
00130                         // activity outside of logging.
00131                         //
00132
00133                         if (messageIndex % 50 == 0)
00134                         {
00135                             await Task.Delay(10);
00136                         }
00137                     }
00138                 });
00139             }
00140             finally
00141             {
00142                 IsBusy = false;
00143             }
00144         }
00145
00146         public void StartLogging()
00147         {
00148             CheckDisposed();
00149
00150             // If no session exists, create one.
00151             // NOTE: There are use cases where an application
00152             // may want to create only a channel for sessions outside
00153             // of the application itself. See MSDN for details. This
00154             // sample is the common scenario of an app logging events
00155             // which it wants to place in its own log file, so it creates
00156             // a session and channel as a pair. The channel is created
00157             // during construction of this LoggingScenario class so
00158             // it already exsits by the time this function is called.
00159             if (session == null)
00160             {
00161                 session = new FileLoggingSession(DEFAULT_SESSION_NAME);
00162                 session.LogFileGenerated += LogFileGeneratedHandler;
00163             }
00164
00165             // This sample adds the channel at level "warning" to
00166             // demonstrated how messages logged at more verbose levels
00167             // are ignored by the session.
00168             session.AddLoggingChannel(channel, LoggingLevel.Warning);
00169         }
00170
00171         /// <summary>
00172         // When the log file gets large, the system closes it and starts a new one.
00173         // The LogFileGenerated event is raised to give the app a chance to move
00174         // the recently-generated log file to a safe place. When the handler returns,
00175         // the FileLoggingSession may reuse the file name for a new log file.
00176         // This function moves the log file to an app-defined location.
00177         /// </summary>
00178         /// <param name="sender">The FileLoggingSession which has generated a new file.</param>
00179         /// <param name="args">Contains a StorageFile field LogFileGeneratedEventArgs.File representing the new log file.</param>
00180         private async void LogFileGeneratedHandler(IFileLoggingSession sender, LogFileGeneratedEventArgs args)
00181         {
00182             LogFileGeneratedCount++;
00183             StorageFolder sampleAppDefinedLogFolder =
00184                 await ApplicationData.Current.LocalFolder.CreateFolderAsync(OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME,
00185                                                                             CreationCollisionOption.OpenIfExists);
00186             string newLogFileName = "Log-" + GetTimeStamp() + ".etl";
00187             await args.File.MoveAsync(sampleAppDefinedLogFolder, newLogFileName);
00188             if (IsPreparingForSuspend == false)
00189             {
00190                 if (StatusChanged != null)
00191                 {
00192                     string newLogFileFullPathName = System.IO.Path.Combine(sampleAppDefinedLogFolder.Path, newLogFileName);
00193                     StatusChanged.Invoke(this, new LoggingScenarioEventArgs(LoggingScenarioEventType.LogFileGenerated, newLogFileFullPathName));
00194                 }
00195             }
00196         }
00197
00198         private async Task<string> CloseSessionSaveFinalLogFile()
00199         {
00200             // Save the final log file before closing the session.
00201             StorageFile finalFileBeforeSuspend = await session.CloseAndSaveToFileAsync();
00202             if (finalFileBeforeSuspend != null)
00203             {
00204                 LogFileGeneratedCount++;
00205                 // Get the the app-defined log file folder.
00206                 StorageFolder sampleAppDefinedLogFolder =
00207                     await ApplicationData.Current.LocalFolder.CreateFolderAsync(OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME,
00208                                                                                 CreationCollisionOption.OpenIfExists);
00209                 // Create a new log file name based on a date/time stamp.
00210                 string newLogFileName = "Log-" + GetTimeStamp() + ".etl";
00211                 // Move the final log into the app-defined log file folder.
00212                 await finalFileBeforeSuspend.MoveAsync(sampleAppDefinedLogFolder, newLogFileName);
00213                 // Return the path to the log folder.
00214                 return System.IO.Path.Combine(sampleAppDefinedLogFolder.Path, newLogFileName);
00215             }
00216             else
00217             {
00218                 return null;
00219             }
00220         }
00221
00222         #endregion
00223
00224         #region Scenario code for tracking a LoggingChannel's enablement status and related logging level.
00225
00226         /// <summary>
00227         /// This boolean tracks whether or not there are any
00228         /// sessions listening to the app's channel. This is
00229         /// adjusted as the channel's LoggingEnabled event is
00230         /// raised. Search for OnChannelLoggingEnabled for
00231         /// more information.
00232         /// </summary>
00233         private bool isChannelEnabled = false;
00234
00235         /// <summary>
00236         /// This is the current maximum level of listeners of
00237         /// the application's channel. It is adjusted as the
00238         /// channel's LoggingEnabled event is raised. Search
00239         /// for OnChannelLoggingEnabled for more information.
00240         /// </summary>
00241         private LoggingLevel channelLoggingLevel = LoggingLevel.Verbose;
00242
00243         void OnChannelLoggingEnabled(ILoggingChannel sender, object args)
00244         {
00245             // This method is called when the channel is informing us of channel-related state changes.
00246             // Save new channel state. These values can be used for advanced logging scenarios where,
00247             // for example, it's desired to skip blocks of logging code if the channel is not being
00248             // consumed by any sessions.
00249             isChannelEnabled = sender.Enabled;
00250             channelLoggingLevel = sender.Level;
00251         }
00252
00253         #endregion
00254
00255         #region Scenario code for suspend/resume.
00256
00257         private const string LOGGING_ENABLED_SETTING_KEY_NAME = Prefix + "LoggingEnabled";
00258         private const string LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME = Prefix + "LogFileGeneratedBeforeSuspend";
00259
00260         public bool IsPreparingForSuspend { get; private set; }
00261
00262         public bool IsLoggingEnabled
00263         {
00264             get
00265             {
00266                 return session != null;
00267             }
00268         }
00269
00270         /// <summary>
00271         /// Prepare this scenario for suspend.
00272         /// </summary>
00273         /// <returns></returns>
00274         public async Task PrepareToSuspendAsync()
00275         {
00276             CheckDisposed();
00277
00278             if (session != null)
00279             {
00280                 IsPreparingForSuspend = true;
00281
00282                 try
00283                 {
00284                     // Before suspend, save any final log file.
00285                     string finalFileBeforeSuspend = await CloseSessionSaveFinalLogFile();
00286                     session.Dispose();
00287                     session = null;
00288                     // Save values used when the app is resumed or started later.
00289                     // Logging is enabled.
00290                     ApplicationData.Current.LocalSettings.Values[LOGGING_ENABLED_SETTING_KEY_NAME] = true;
00291                     // Save the log file name saved at suspend so the sample UI can be
00292                     // updated on resume with that information.
00293                     ApplicationData.Current.LocalSettings.Values[LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME] = finalFileBeforeSuspend;
00294                 }
00295                 finally
00296                 {
00297                     IsPreparingForSuspend = false;
00298                 }
00299             }
00300             else
00301             {
00302                 // Save values used when the app is resumed or started later.
00303                 // Logging is not enabled and no log file was saved.
00304                 ApplicationData.Current.LocalSettings.Values[LOGGING_ENABLED_SETTING_KEY_NAME] = false;
00305                 ApplicationData.Current.LocalSettings.Values[LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME] = null;
00306             }
00307         }
00308
00309         /// <summary>
00310         /// This is called when the app is either resuming or starting.
00311         /// It will enable logging if the app has never been started before
00312         /// or if logging had been enabled the last time the app was running.
00313         /// </summary>
00314         public void ResumeLoggingIfApplicable()
00315         {
00316             CheckDisposed();
00317
00318             object loggingEnabled;
00319             if (ApplicationData.Current.LocalSettings.Values.TryGetValue(LOGGING_ENABLED_SETTING_KEY_NAME, out loggingEnabled) == false)
00320             {
00321                 ApplicationData.Current.LocalSettings.Values[LOGGING_ENABLED_SETTING_KEY_NAME] = true;
00322                 loggingEnabled = ApplicationData.Current.LocalSettings.Values[LOGGING_ENABLED_SETTING_KEY_NAME];
00323             }
00324
00325             if (loggingEnabled is bool && (bool)loggingEnabled == true)
00326             {
00327                 StartLogging();
00328             }
00329
00330             // When the sample suspends, it retains state as to whether or not it had
00331             // generated a new log file at the last suspension. This allows any
00332             // UI to be updated on resume to reflect that fact.
00333             object LogFileGeneratedBeforeSuspendObject;
00334             if (ApplicationData.Current.LocalSettings.Values.TryGetValue(LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME, out LogFileGeneratedBeforeSuspendObject) &&
00335                 LogFileGeneratedBeforeSuspendObject != null &&
00336                 LogFileGeneratedBeforeSuspendObject is string)
00337             {
00338                 if (StatusChanged != null)
00339                 {
00340                     StatusChanged.Invoke(this,
00341                                          new LoggingScenarioEventArgs(LoggingScenarioEventType.LogFileGeneratedAtSuspend,
00342                                                                     (string)LogFileGeneratedBeforeSuspendObject));
00343
00344                 }
00345                 ApplicationData.Current.LocalSettings.Values[LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME] = null;
00346             }
00347         }
00348
00349         #endregion
00350
00351         #region Helper functions/properties/events to support sample UI feedback.
00352
00353         public event EventHandler<LoggingScenarioEventArgs> StatusChanged;
00354
00355         private bool isBusy;
00356         /// <summary>
00357         /// True if the scenario is busy, or false if not busy.
00358         /// The UI can use this to affect UI controls.
00359         /// </summary>
00360         public bool IsBusy
00361         {
00362             get
00363             {
00364                 return isBusy;
00365             }
00366
00367             private set
00368             {
00369                 isBusy = value;
00370                 if (StatusChanged != null)
00371                 {
00372                     StatusChanged.Invoke(this, new LoggingScenarioEventArgs(LoggingScenarioEventType.BusyStatusChanged));
00373                 }
00374             }
00375         }
00376
00377         /// <summary>
00378         /// The number of times LogFileGeneratedHandler has been called.
00379         /// </summary>
00380
00381         public int LogFileGeneratedCount { get; private set; }
00382
00383         #endregion
00384
00385         #region LoggingScenario constants and privates.
00386
00387         private const string Prefix = "FileLoggingSessionScenario_";
00388         public const string DEFAULT_SESSION_NAME = Prefix + "Session";
00389         public const string DEFAULT_CHANNEL_NAME = Prefix + "Channel";
00390
00391         /// <summary>
00392         /// LoggingScenario moves generated logs files into the
00393         /// this folder under the LocalState folder.
00394         /// </summary>
00395         public const string OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME = Prefix + "LogFiles";
00396
00397         /// <summary>
00398         /// <summary>
00399         /// The sample's one session.
00400         /// </summary>
00401         private FileLoggingSession session;
00402
00403         /// <summary>
00404         /// The sample's one channel.
00405         /// </summary>
00406         private LoggingChannel channel;
00407
00408         #endregion
00409
00410         #region LoggingScenario constructor and singleton accessor.
00411
00412         /// <summary>
00413         /// Disallow creation of instances beyond the one instance for the process.
00414         /// The one instance is accessible via the Instance property (see below).
00415         /// </summary>
00416         private FileLoggingSessionScenario()
00417         {
00418             LogFileGeneratedCount = 0;
00419
00420             // This sample demonstrates LoggingSession using the Windows 8.1 LoggingChannel APIs.
00421 #pragma warning disable 618 // LoggingChannel is obsolete
00422             channel = new LoggingChannel(DEFAULT_CHANNEL_NAME);
00423 #pragma warning restore
00424
00425             channel.LoggingEnabled += OnChannelLoggingEnabled;
00426
00427             App.Current.Suspending += OnAppSuspending;
00428             App.Current.Resuming += OnAppResuming;
00429
00430             // If the app is being launched (not resumed), the
00431             // following call will activate logging if it had been
00432             // activated during the last suspend.
00433             ResumeLoggingIfApplicable();
00434         }
00435
00436         ~FileLoggingSessionScenario()
00437         {
00438             Dispose(false);
00439         }
00440
00441         async void OnAppSuspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
00442         {
00443             // Get a deferral before performing any async operations
00444             // to avoid suspension prior to LoggingScenario completing
00445             // PrepareToSuspendAsync().
00446             var deferral = e.SuspendingOperation.GetDeferral();
00447
00448             // Prepare logging for suspension.
00449             await PrepareToSuspendAsync();
00450
00451             // From LoggingScenario's perspective, it's now okay to
00452             // suspend, so release the deferral.
00453             deferral.Complete();
00454         }
00455
00456         void OnAppResuming(object sender, object e)
00457         {
00458             // If logging was active at the last suspend,
00459             // ResumeLoggingIfApplicable will re-activate
00460             // logging.
00461             ResumeLoggingIfApplicable();
00462         }
00463
00464         /// The app's one and only LoggingScenario instance.
00465         /// </summary>
00466         static private FileLoggingSessionScenario loggingScenario;
00467
00468         /// <summary>
00469         /// A method to allowing callers to access the app's one and only LoggingScenario instance.
00470         /// </summary>
00471         /// <returns>The logging helper.</returns>
00472         static public FileLoggingSessionScenario Instance
00473         {
00474             get
00475             {
00476                 if (loggingScenario == null)
00477                 {
00478                     loggingScenario = new FileLoggingSessionScenario();
00479                 }
00480                 return loggingScenario;
00481             }
00482         }
00483
00484         #endregion
00485
00486         #region IDisposable handling
00487
00488         public void Dispose()
00489         {
00490             Dispose(true);
00491             GC.SuppressFinalize(this);
00492         }
00493
00494         protected virtual void Dispose(bool disposing)
00495         {
00496             if (isDisposed == false)
00497             {
00498                 isDisposed = true;
00499
00500                 if (disposing)
00501                 {
00502                     if (channel != null)
00503                     {
00504                         channel.Dispose();
00505                         channel = null;
00506                     }
00507
00508                     if (session != null)
00509                     {
00510                         session.Dispose();
00511                         session = null;
00512                     }
00513                 }
00514             }
00515         }
00516
00517         /// <summary>
00518         /// Set to 'true' if Dispose() has been called.
00519         /// </summary>
00520         private bool isDisposed = false;
00521
00522         /// <summary>
00523         /// Helper function for other methods to call to check Dispose() state.
00524         /// </summary>
00525         private void CheckDisposed()
00526         {
00527             if (isDisposed)
00528             {
00529                 throw new ObjectDisposedException("LoggingScenario");
00530             }
00531         }
00532
00533         #endregion
00534     }
00535 }
Generated on Fri Nov 15 2024 22:20:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
App() | sealed |
Initialize(Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
Load(Platform::String^entryPoint) | sealed | [virtual]
m_deviceResources | sealed | [private]
m_main | sealed | [private]
m_windowClosed | sealed | [private]
m_windowVisible | sealed | [private]
OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | sealed | [protected]
OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnDpiChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnResuming(Platform::Object^sender, Platform::Object^args) | sealed | [protected]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [protected]
OnVisibilityChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::VisibilityChangedEventArgs^args) | sealed | [protected]
OnWindowClosed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::CoreWindowEventArgs^args) | sealed | [protected]
OnWindowSizeChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::WindowSizeChangedEventArgs^args) | sealed | [protected]
Run() | sealed | [virtual]
SetWindow(Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
Uninitialize() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LibraryManagement/cpp/S1_AddFolder.xaml.cpp Source File

  • LibraryManagement
  • cpp

S1_AddFolder.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1.xaml.cpp
00014 // Implementation of the Scenario1 class
00015 //
00016
00017 #include "pch.h"
00018 #include "S1_AddFolder.xaml.h"
00019 #include "MainPage.xaml.h"
00020
00021 using namespace SDKTemplate;
00022
00023 using namespace concurrency;
00024 using namespace Windows::Storage;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027
00028 Scenario1::Scenario1()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Displays the folder Picker to request that the user select a folder that will be added to the
00035 /// Pictures library.
00036 /// </summary>
00037 /// <param name="sender"></param>
00038 /// <param name="e"></param>
00039 void Scenario1::AddFolderButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00040 {
00041     create_task(StorageLibrary::GetLibraryAsync(KnownLibraryId::Pictures)).then([](StorageLibrary^ picturesLibrary)
00042     {
00043         return create_task(picturesLibrary->RequestAddFolderAsync());
00044     }).then([this](StorageFolder^ folderAdded)
00045     {
00046         if (folderAdded != nullptr)
00047         {
00048             OutputTextBlock->Text = folderAdded->DisplayName + " was added to the Pictures library.";
00049         }
00050         else
00051         {
00052             OutputTextBlock->Text = "Operation canceled.";
00053         }
00054     });
00055 }
Generated on Fri Nov 15 2024 22:20:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cs/ImagePage.xaml.cs Source File

  • XamlListView
  • cs

ImagePage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Core;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Media.Animation;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Page2 is simply a blank page with a button to navigate back to the MainPage.
00022     /// It's purpose is just to reset the list on the main page so that the implementation of ListViewPersistenceHelper can be demonstrated
00023     /// </summary>
00024     public sealed partial class ImagePage : Page
00025     {
00026         public ImagePage()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         protected override void OnNavigatedTo(NavigationEventArgs e)
00032         {
00033             // Register for hardware and software back request from the system
00034             SystemNavigationManager systemNavigationManager = SystemNavigationManager.GetForCurrentView();
00035             systemNavigationManager.BackRequested += OnBackRequested;
00036             systemNavigationManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
00037         }
00038
00039         protected override void OnNavigatedFrom(NavigationEventArgs e)
00040         {
00041             SystemNavigationManager systemNavigationManager = SystemNavigationManager.GetForCurrentView();
00042             systemNavigationManager.BackRequested -= OnBackRequested;
00043             systemNavigationManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
00044         }
00045
00046         private void OnBackRequested(object sender, BackRequestedEventArgs e)
00047         {
00048             // Mark event as handled so we don't leave the app.
00049             e.Handled = true;
00050             // Page above us will be our master view.
00051             // Make sure we are using the "drill out" animation in this transition.
00052             Frame.GoBack(new DrillInNavigationTransitionInfo());
00053         }
00054     }
00055 }
Generated on Fri Nov 15 2024 22:22:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SourceGroupCollection Member List

This is the complete list of members for SourceGroupCollection, including all inherited members.
_dispatcher | SourceGroupCollection | [private]
_sourceCollection | SourceGroupCollection | [private]
_watcher | SourceGroupCollection | [private]
AddDeviceAsync(string id) | SourceGroupCollection | [inline, private]
Dispose() | SourceGroupCollection | [inline]
FrameSourceGroups | SourceGroupCollection |
RemoveDevice(string id) | SourceGroupCollection | [inline, private]
SourceGroupCollection(CoreDispatcher uiDispatcher) | SourceGroupCollection | [inline]
Watcher_Added(DeviceWatcher sender, DeviceInformation args) | SourceGroupCollection | [inline, private]
Watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args) | SourceGroupCollection | [inline, private]
Watcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args) | SourceGroupCollection | [inline, private]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Status Member List

This is the complete list of members for Status, including all inherited members.
FileAdded | Status | [private, static]
FileAddFailed | Status | [private, static]
FileRemoved | Status | [private, static]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Package/cpp/scenario3_dependencies.xaml.h Source File

  • Package
  • cpp

scenario3_dependencies.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario1.xaml.h
00013 // Declaration of the Scenario1 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario3_Dependencies.g.h"
00020 #include "MainPage.xaml.h"
00021
00022     namespace SDKTemplate
00023     {
00024         /// <summary>
00025         /// An empty page that can be used on its own or navigated to within a Frame.
00026         /// </summary>
00027         [Windows::Foundation::Metadata::WebHostHidden]
00028         public ref class Scenario3 sealed
00029         {
00030         public:
00031             Scenario3();
00032
00033         protected:
00034             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035         private:
00036             MainPage^ rootPage;
00037
00038             void GetDependencies_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         };
00040 }
Generated on Fri Nov 15 2024 22:20:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cpp/Scenario5_UnicodeExtensions.xaml.cpp Source File

  • DateTimeFormatting
  • cpp

Scenario5_UnicodeExtensions.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario5_UnicodeExtensions.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Platform::Collections;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Globalization;
00022 using namespace Windows::Globalization::DateTimeFormatting;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 Scenario5_UnicodeExtensions::Scenario5_UnicodeExtensions()
00028 {
00029     InitializeComponent();
00030 }
00031
00032 void Scenario5_UnicodeExtensions::Display()
00033 {
00034     // This scenario uses the Windows.Globalization.DateTimeFormatting.DateTimeFormatter class
00035     // to format a date/time by using a formatter that uses unicode extenstion in the specified
00036     // language name
00037
00038     // Get the current application context language
00039     String^ currentLanguage = ApplicationLanguages::Languages->GetAt(0);
00040
00041     // Keep the results here
00042     String^ results = "";
00043     results += "Current application context language: " + currentLanguage + "\n\n";
00044
00045     // Formatters for dates and times
00046     Array<DateTimeFormatter^> ^dateFormatters = {
00047         // Default application context
00048         ref new DateTimeFormatter("longdate longtime"),
00049
00050         // Telugu language, Gregorian Calendar and Latin Numeral System
00051         ref new DateTimeFormatter("longdate longtime", ref new Vector<String^>({ "te-in-u-ca-gregory-nu-latn", "en-US" })),
00052
00053         // Hebrew language and Arabic Numeral System - calendar NOT specified in constructor
00054         ref new DateTimeFormatter(YearFormat::Default,
00055             MonthFormat::Default,
00056             DayFormat::Default,
00057             DayOfWeekFormat::Default,
00058             HourFormat::Default,
00059             MinuteFormat::Default,
00060             SecondFormat::Default,
00061             ref new Vector<String^>({ "he-IL-u-nu-arab", "en-US" })),
00062         // Hebrew language and calendar - calendar specified in constructor
00063         // also, which overrides the one specified in Unicode extension
00064         ref new DateTimeFormatter(YearFormat::Default,
00065             MonthFormat::Default,
00066             DayFormat::Default,
00067             DayOfWeekFormat::Default,
00068             HourFormat::Default,
00069             MinuteFormat::Default,
00070             SecondFormat::Default,
00071             ref new Vector<String^>({ "he-IL-u-ca-hebrew-co-phonebk", "en-US" }),
00072             "US",
00073             CalendarIdentifiers::Gregorian,
00074             ClockIdentifiers::TwentyFourHour),
00075     };
00076
00077     // Obtain the date that will be formatted.
00078     Windows::Globalization::Calendar^ cal = ref new Windows::Globalization::Calendar();
00079     Windows::Foundation::DateTime dateToFormat = cal->GetDateTime();
00080
00081     // Format and display date/time along with other relevant properites
00082     for (auto formatter : dateFormatters)
00083     {
00084         // Perform the actual formatting.
00085         results += "Result: " + formatter->Format(dateToFormat) + "\n";
00086
00087         String^ languages = "";
00088         for (auto language : formatter->Languages)
00089         {
00090             if (!languages->IsEmpty())
00091             {
00092                 languages += ", ";
00093             }
00094             languages += language;
00095         }
00096
00097         results += "    Language List: " + languages + "\n" +
00098                    "    Template: " + formatter->Template + "\n" +
00099                    "    Resolved Language: " + formatter->ResolvedLanguage + "\n" +
00100                    "    Calendar System: " + formatter->Calendar + "\n" +
00101                    "    Numeral System: " + formatter->NumeralSystem + "\n\n";
00102     }
00103
00104     // Display the results.
00105     OutputTextBlock->Text = results;
00106 }
Generated on Fri Nov 15 2024 22:19:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario2WinRTComponent/OnboardingServiceEventArgs.cpp Source File

  • AllJoyn
  • Common
  • Scenario2WinRTComponent

OnboardingServiceEventArgs.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #include "pch.h"
00022
00023 using namespace concurrency;
00024 using namespace Microsoft::WRL;
00025 using namespace Platform;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Foundation::Collections;
00028 using namespace Windows::Devices::AllJoyn;
00029 using namespace org::alljoyn::Onboarding;
00030 namespace org { namespace alljoyn { namespace Onboarding {
00031
00032 // Methods
00033 OnboardingConfigureWiFiCalledEventArgs::OnboardingConfigureWiFiCalledEventArgs(
00034     _In_ AllJoynMessageInfo^ info,
00035     _In_ Platform::String^ interfaceMemberSSID,
00036     _In_ Platform::String^ interfaceMemberPassphrase,
00037     _In_ int16 interfaceMemberAuthType)
00038     : m_raised(false),
00039     m_completionsRequired(0),
00040     m_messageInfo(info),
00041     m_interfaceMemberSSID(interfaceMemberSSID),
00042     m_interfaceMemberPassphrase(interfaceMemberPassphrase),
00043     m_interfaceMemberAuthType(interfaceMemberAuthType)
00044 {
00045     m_result = OnboardingConfigureWiFiResult::CreateFailureResult(ER_NOT_IMPLEMENTED);
00046 }
00047
00048 Deferral^ OnboardingConfigureWiFiCalledEventArgs::GetDeferral()
00049 {
00050     std::lock_guard<std::mutex> lockGuard(m_lock);
00051     if (m_raised)
00052     {
00053         // Cannot ask for a deferral after the event handler has returned.
00054         throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00055     }
00056
00057     m_completionsRequired++;
00058     auto handler = ref new DeferralCompletedHandler(this, &OnboardingConfigureWiFiCalledEventArgs::Complete);
00059     return ref new Deferral(handler);
00060 }
00061
00062 void OnboardingConfigureWiFiCalledEventArgs::InvokeAllFinished()
00063 {
00064     bool invokeNeeded;
00065
00066     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00067     {
00068         std::lock_guard<std::mutex> lockGuard(m_lock);
00069         m_raised = true;
00070         invokeNeeded = (m_completionsRequired == 0);
00071     }
00072
00073     if (invokeNeeded)
00074     {
00075         InvokeCompleteHandler();
00076     }
00077 }
00078
00079 void OnboardingConfigureWiFiCalledEventArgs::Complete()
00080 {
00081     bool invokeNeeded;
00082
00083     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00084     {
00085         std::lock_guard<std::mutex> lockGuard(m_lock);
00086         if (m_completionsRequired == 0)
00087         {
00088             // This should never happen since Complete() should only be called by Windows.Foundation.Deferral
00089             // which will only invoke our completion handler once.
00090             throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00091         }
00092         m_completionsRequired--;
00093         invokeNeeded = (m_raised && (m_completionsRequired == 0));
00094     }
00095
00096     if (invokeNeeded)
00097     {
00098         InvokeCompleteHandler();
00099     }
00100 }
00101
00102 void OnboardingConfigureWiFiCalledEventArgs::InvokeCompleteHandler()
00103 {
00104     if (m_result->Status == ER_NOT_IMPLEMENTED)
00105     {
00106         throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for ConfigureWiFiCalled.");
00107     }
00108     else
00109     {
00110         m_tce.set(m_result);
00111     }
00112 }
00113
00114 OnboardingConnectCalledEventArgs::OnboardingConnectCalledEventArgs(
00115     _In_ AllJoynMessageInfo^ info)
00116     : m_raised(false),
00117     m_completionsRequired(0),
00118     m_messageInfo(info)
00119 {
00120     m_result = OnboardingConnectResult::CreateFailureResult(ER_NOT_IMPLEMENTED);
00121 }
00122
00123 Deferral^ OnboardingConnectCalledEventArgs::GetDeferral()
00124 {
00125     std::lock_guard<std::mutex> lockGuard(m_lock);
00126     if (m_raised)
00127     {
00128         // Cannot ask for a deferral after the event handler has returned.
00129         throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00130     }
00131
00132     m_completionsRequired++;
00133     auto handler = ref new DeferralCompletedHandler(this, &OnboardingConnectCalledEventArgs::Complete);
00134     return ref new Deferral(handler);
00135 }
00136
00137 void OnboardingConnectCalledEventArgs::InvokeAllFinished()
00138 {
00139     bool invokeNeeded;
00140
00141     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00142     {
00143         std::lock_guard<std::mutex> lockGuard(m_lock);
00144         m_raised = true;
00145         invokeNeeded = (m_completionsRequired == 0);
00146     }
00147
00148     if (invokeNeeded)
00149     {
00150         InvokeCompleteHandler();
00151     }
00152 }
00153
00154 void OnboardingConnectCalledEventArgs::Complete()
00155 {
00156     bool invokeNeeded;
00157
00158     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00159     {
00160         std::lock_guard<std::mutex> lockGuard(m_lock);
00161         if (m_completionsRequired == 0)
00162         {
00163             // This should never happen since Complete() should only be called by Windows.Foundation.Deferral
00164             // which will only invoke our completion handler once.
00165             throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00166         }
00167         m_completionsRequired--;
00168         invokeNeeded = (m_raised && (m_completionsRequired == 0));
00169     }
00170
00171     if (invokeNeeded)
00172     {
00173         InvokeCompleteHandler();
00174     }
00175 }
00176
00177 void OnboardingConnectCalledEventArgs::InvokeCompleteHandler()
00178 {
00179     if (m_result->Status == ER_NOT_IMPLEMENTED)
00180     {
00181         throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for ConnectCalled.");
00182     }
00183     else
00184     {
00185         m_tce.set(m_result);
00186     }
00187 }
00188
00189 OnboardingOffboardCalledEventArgs::OnboardingOffboardCalledEventArgs(
00190     _In_ AllJoynMessageInfo^ info)
00191     : m_raised(false),
00192     m_completionsRequired(0),
00193     m_messageInfo(info)
00194 {
00195     m_result = OnboardingOffboardResult::CreateFailureResult(ER_NOT_IMPLEMENTED);
00196 }
00197
00198 Deferral^ OnboardingOffboardCalledEventArgs::GetDeferral()
00199 {
00200     std::lock_guard<std::mutex> lockGuard(m_lock);
00201     if (m_raised)
00202     {
00203         // Cannot ask for a deferral after the event handler has returned.
00204         throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00205     }
00206
00207     m_completionsRequired++;
00208     auto handler = ref new DeferralCompletedHandler(this, &OnboardingOffboardCalledEventArgs::Complete);
00209     return ref new Deferral(handler);
00210 }
00211
00212 void OnboardingOffboardCalledEventArgs::InvokeAllFinished()
00213 {
00214     bool invokeNeeded;
00215
00216     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00217     {
00218         std::lock_guard<std::mutex> lockGuard(m_lock);
00219         m_raised = true;
00220         invokeNeeded = (m_completionsRequired == 0);
00221     }
00222
00223     if (invokeNeeded)
00224     {
00225         InvokeCompleteHandler();
00226     }
00227 }
00228
00229 void OnboardingOffboardCalledEventArgs::Complete()
00230 {
00231     bool invokeNeeded;
00232
00233     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00234     {
00235         std::lock_guard<std::mutex> lockGuard(m_lock);
00236         if (m_completionsRequired == 0)
00237         {
00238             // This should never happen since Complete() should only be called by Windows.Foundation.Deferral
00239             // which will only invoke our completion handler once.
00240             throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00241         }
00242         m_completionsRequired--;
00243         invokeNeeded = (m_raised && (m_completionsRequired == 0));
00244     }
00245
00246     if (invokeNeeded)
00247     {
00248         InvokeCompleteHandler();
00249     }
00250 }
00251
00252 void OnboardingOffboardCalledEventArgs::InvokeCompleteHandler()
00253 {
00254     if (m_result->Status == ER_NOT_IMPLEMENTED)
00255     {
00256         throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for OffboardCalled.");
00257     }
00258     else
00259     {
00260         m_tce.set(m_result);
00261     }
00262 }
00263
00264 OnboardingGetScanInfoCalledEventArgs::OnboardingGetScanInfoCalledEventArgs(
00265     _In_ AllJoynMessageInfo^ info)
00266     : m_raised(false),
00267     m_completionsRequired(0),
00268     m_messageInfo(info)
00269 {
00270     m_result = OnboardingGetScanInfoResult::CreateFailureResult(ER_NOT_IMPLEMENTED);
00271 }
00272
00273 Deferral^ OnboardingGetScanInfoCalledEventArgs::GetDeferral()
00274 {
00275     std::lock_guard<std::mutex> lockGuard(m_lock);
00276     if (m_raised)
00277     {
00278         // Cannot ask for a deferral after the event handler has returned.
00279         throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00280     }
00281
00282     m_completionsRequired++;
00283     auto handler = ref new DeferralCompletedHandler(this, &OnboardingGetScanInfoCalledEventArgs::Complete);
00284     return ref new Deferral(handler);
00285 }
00286
00287 void OnboardingGetScanInfoCalledEventArgs::InvokeAllFinished()
00288 {
00289     bool invokeNeeded;
00290
00291     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00292     {
00293         std::lock_guard<std::mutex> lockGuard(m_lock);
00294         m_raised = true;
00295         invokeNeeded = (m_completionsRequired == 0);
00296     }
00297
00298     if (invokeNeeded)
00299     {
00300         InvokeCompleteHandler();
00301     }
00302 }
00303
00304 void OnboardingGetScanInfoCalledEventArgs::Complete()
00305 {
00306     bool invokeNeeded;
00307
00308     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00309     {
00310         std::lock_guard<std::mutex> lockGuard(m_lock);
00311         if (m_completionsRequired == 0)
00312         {
00313             // This should never happen since Complete() should only be called by Windows.Foundation.Deferral
00314             // which will only invoke our completion handler once.
00315             throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00316         }
00317         m_completionsRequired--;
00318         invokeNeeded = (m_raised && (m_completionsRequired == 0));
00319     }
00320
00321     if (invokeNeeded)
00322     {
00323         InvokeCompleteHandler();
00324     }
00325 }
00326
00327 void OnboardingGetScanInfoCalledEventArgs::InvokeCompleteHandler()
00328 {
00329     if (m_result->Status == ER_NOT_IMPLEMENTED)
00330     {
00331         throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for GetScanInfoCalled.");
00332     }
00333     else
00334     {
00335         m_tce.set(m_result);
00336     }
00337 }
00338
00339 // Readable Properties
00340 OnboardingGetVersionRequestedEventArgs::OnboardingGetVersionRequestedEventArgs(
00341     _In_ AllJoynMessageInfo^ info)
00342     : m_raised(false),
00343     m_completionsRequired(0),
00344     m_messageInfo(info)
00345 {
00346     m_result = OnboardingGetVersionResult::CreateFailureResult(ER_NOT_IMPLEMENTED);
00347 }
00348
00349 Deferral^ OnboardingGetVersionRequestedEventArgs::GetDeferral()
00350 {
00351     std::lock_guard<std::mutex> lockGuard(m_lock);
00352     if (m_raised)
00353     {
00354         // Cannot ask for a deferral after the event handler has returned.
00355         throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00356     }
00357
00358     m_completionsRequired++;
00359     auto handler = ref new DeferralCompletedHandler(this, &OnboardingGetVersionRequestedEventArgs::Complete);
00360     return ref new Deferral(handler);
00361 }
00362
00363 void OnboardingGetVersionRequestedEventArgs::InvokeAllFinished()
00364 {
00365     bool invokeNeeded;
00366
00367     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00368     {
00369         std::lock_guard<std::mutex> lockGuard(m_lock);
00370         m_raised = true;
00371         invokeNeeded = (m_completionsRequired == 0);
00372     }
00373
00374     if (invokeNeeded)
00375     {
00376         InvokeCompleteHandler();
00377     }
00378 }
00379
00380 void OnboardingGetVersionRequestedEventArgs::Complete()
00381 {
00382     bool invokeNeeded;
00383
00384     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00385     {
00386         std::lock_guard<std::mutex> lockGuard(m_lock);
00387         if (m_completionsRequired == 0)
00388         {
00389             // This should never happen since Complete() should only be called by Windows.Foundation.Deferral
00390             // which will only invoke our completion handler once.
00391             throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00392         }
00393         m_completionsRequired--;
00394         invokeNeeded = (m_raised && (m_completionsRequired == 0));
00395     }
00396
00397     if (invokeNeeded)
00398     {
00399         InvokeCompleteHandler();
00400     }
00401 }
00402
00403 void OnboardingGetVersionRequestedEventArgs::InvokeCompleteHandler()
00404 {
00405     if (m_result->Status == ER_NOT_IMPLEMENTED)
00406     {
00407         throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for GetVersionRequested.");
00408     }
00409     else
00410     {
00411         m_tce.set(m_result);
00412     }
00413 }
00414
00415 OnboardingGetStateRequestedEventArgs::OnboardingGetStateRequestedEventArgs(
00416     _In_ AllJoynMessageInfo^ info)
00417     : m_raised(false),
00418     m_completionsRequired(0),
00419     m_messageInfo(info)
00420 {
00421     m_result = OnboardingGetStateResult::CreateFailureResult(ER_NOT_IMPLEMENTED);
00422 }
00423
00424 Deferral^ OnboardingGetStateRequestedEventArgs::GetDeferral()
00425 {
00426     std::lock_guard<std::mutex> lockGuard(m_lock);
00427     if (m_raised)
00428     {
00429         // Cannot ask for a deferral after the event handler has returned.
00430         throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00431     }
00432
00433     m_completionsRequired++;
00434     auto handler = ref new DeferralCompletedHandler(this, &OnboardingGetStateRequestedEventArgs::Complete);
00435     return ref new Deferral(handler);
00436 }
00437
00438 void OnboardingGetStateRequestedEventArgs::InvokeAllFinished()
00439 {
00440     bool invokeNeeded;
00441
00442     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00443     {
00444         std::lock_guard<std::mutex> lockGuard(m_lock);
00445         m_raised = true;
00446         invokeNeeded = (m_completionsRequired == 0);
00447     }
00448
00449     if (invokeNeeded)
00450     {
00451         InvokeCompleteHandler();
00452     }
00453 }
00454
00455 void OnboardingGetStateRequestedEventArgs::Complete()
00456 {
00457     bool invokeNeeded;
00458
00459     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00460     {
00461         std::lock_guard<std::mutex> lockGuard(m_lock);
00462         if (m_completionsRequired == 0)
00463         {
00464             // This should never happen since Complete() should only be called by Windows.Foundation.Deferral
00465             // which will only invoke our completion handler once.
00466             throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00467         }
00468         m_completionsRequired--;
00469         invokeNeeded = (m_raised && (m_completionsRequired == 0));
00470     }
00471
00472     if (invokeNeeded)
00473     {
00474         InvokeCompleteHandler();
00475     }
00476 }
00477
00478 void OnboardingGetStateRequestedEventArgs::InvokeCompleteHandler()
00479 {
00480     if (m_result->Status == ER_NOT_IMPLEMENTED)
00481     {
00482         throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for GetStateRequested.");
00483     }
00484     else
00485     {
00486         m_tce.set(m_result);
00487     }
00488 }
00489
00490 OnboardingGetLastErrorRequestedEventArgs::OnboardingGetLastErrorRequestedEventArgs(
00491     _In_ AllJoynMessageInfo^ info)
00492     : m_raised(false),
00493     m_completionsRequired(0),
00494     m_messageInfo(info)
00495 {
00496     m_result = OnboardingGetLastErrorResult::CreateFailureResult(ER_NOT_IMPLEMENTED);
00497 }
00498
00499 Deferral^ OnboardingGetLastErrorRequestedEventArgs::GetDeferral()
00500 {
00501     std::lock_guard<std::mutex> lockGuard(m_lock);
00502     if (m_raised)
00503     {
00504         // Cannot ask for a deferral after the event handler has returned.
00505         throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00506     }
00507
00508     m_completionsRequired++;
00509     auto handler = ref new DeferralCompletedHandler(this, &OnboardingGetLastErrorRequestedEventArgs::Complete);
00510     return ref new Deferral(handler);
00511 }
00512
00513 void OnboardingGetLastErrorRequestedEventArgs::InvokeAllFinished()
00514 {
00515     bool invokeNeeded;
00516
00517     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00518     {
00519         std::lock_guard<std::mutex> lockGuard(m_lock);
00520         m_raised = true;
00521         invokeNeeded = (m_completionsRequired == 0);
00522     }
00523
00524     if (invokeNeeded)
00525     {
00526         InvokeCompleteHandler();
00527     }
00528 }
00529
00530 void OnboardingGetLastErrorRequestedEventArgs::Complete()
00531 {
00532     bool invokeNeeded;
00533
00534     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00535     {
00536         std::lock_guard<std::mutex> lockGuard(m_lock);
00537         if (m_completionsRequired == 0)
00538         {
00539             // This should never happen since Complete() should only be called by Windows.Foundation.Deferral
00540             // which will only invoke our completion handler once.
00541             throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00542         }
00543         m_completionsRequired--;
00544         invokeNeeded = (m_raised && (m_completionsRequired == 0));
00545     }
00546
00547     if (invokeNeeded)
00548     {
00549         InvokeCompleteHandler();
00550     }
00551 }
00552
00553 void OnboardingGetLastErrorRequestedEventArgs::InvokeCompleteHandler()
00554 {
00555     if (m_result->Status == ER_NOT_IMPLEMENTED)
00556     {
00557         throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for GetLastErrorRequested.");
00558     }
00559     else
00560     {
00561         m_tce.set(m_result);
00562     }
00563 }
00564
00565 // Writable Properties
00566 } } }
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/Actions/InputText/DefaultInput/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • Actions
  • InputText
  • DefaultInput

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Notifications;
00003 using Windows.UI.Popups;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00008
00009 namespace Notifications.ScenarioPages.Toasts.Actions.InputText.DefaultInput
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     public sealed partial class ScenarioElement : UserControl
00015     {
00016         public ScenarioElement()
00017         {
00018             this.InitializeComponent();
00019         }
00020
00021         private void UserControl_Loaded(object sender, RoutedEventArgs e)
00022         {
00023             Initialize();
00024         }
00025
00026         private void Initialize()
00027         {
00028             // Clear all existing notifications
00029             ToastNotificationManager.History.Clear();
00030
00031             // Pop notifications
00032             popToastControl.Payload =
00033                 $@"
00034                 <toast activationType='foreground' launch='args'>
00035                     <visual>
00036                         <binding template='ToastGeneric'>
00037                             <text>Input Text - Default Input</text>
00038                             <text>Make sure ""My default input"" is set as the text in the text box on this toast.</text>
00039                         </binding>
00040                     </visual>
00041                     <actions>
00042
00043                         <input
00044                             id = 'message'
00045                             type = 'text'
00046                             placeHolderContent = 'FAIL - this is placeholder content'
00047                             defaultInput = 'My default input' />
00048
00049                     </actions>
00050                 </toast>";
00051         }
00052
00053         private async void Error(string message)
00054         {
00055             await new MessageDialog(message, "ERROR").ShowAsync();
00056         }
00057     }
00058 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DAdvancedColorImages/cpp/D2DAdvancedColorImages/SdrOverlayEffect.cpp Source File

  • D2DAdvancedColorImages
  • cpp
  • D2DAdvancedColorImages

SdrOverlayEffect.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <initguid.h>
00014 #include "SdrOverlayEffect.h"
00015 #include "BasicReaderWriter.h"
00016
00017 #define XML(X) TEXT(#X)
00018
00019 SdrOverlayEffect::SdrOverlayEffect() :
00020     m_refCount(1),
00021     m_constants{}
00022 {
00023 }
00024
00025 HRESULT __stdcall SdrOverlayEffect::CreateSdrOverlayImpl(_Outptr_ IUnknown** ppEffectImpl)
00026 {
00027     // Since the object's refcount is initialized to 1, we don't need to AddRef here.
00028     *ppEffectImpl = static_cast<ID2D1EffectImpl*>(new (std::nothrow) SdrOverlayEffect());
00029
00030     if (*ppEffectImpl == nullptr)
00031     {
00032         return E_OUTOFMEMORY;
00033     }
00034     else
00035     {
00036         return S_OK;
00037     }
00038 }
00039
00040 HRESULT SdrOverlayEffect::Register(_In_ ID2D1Factory1* pFactory)
00041 {
00042     // The inspectable metadata of an effect is defined in XML. This can be passed in from an external source
00043     // as well, however for simplicity we just inline the XML.
00044     PCWSTR pszXml =
00045         XML(
00046             <?xml version='1.0'?>
00047             <Effect>
00048                 <!-- System Properties -->
00049                 <Property name='DisplayName' type='string' value='SdrOverlay'/>
00050                 <Property name='Author' type='string' value='Microsoft Corporation'/>
00051                 <Property name='Category' type='string' value='Source'/>
00052                 <Property name='Description' type='string' value='Emulates SDR behavior on an AC source'/>
00053                 <Inputs>
00054                     <Input name = 'Source'/>
00055                 </Inputs>
00056                 <!-- Custom Properties go here -->
00057             </Effect>
00058             );
00059
00060     // This registers the effect with the factory, which will make the effect
00061     // instantiatable.
00062     return pFactory->RegisterEffectFromString(
00063         CLSID_CustomSdrOverlayEffect,
00064         pszXml,
00065         nullptr, // No custom properties
00066         0,       // No custom properties
00067         CreateSdrOverlayImpl
00068         );
00069 }
00070
00071 IFACEMETHODIMP SdrOverlayEffect::Initialize(
00072     _In_ ID2D1EffectContext* pEffectContext,
00073     _In_ ID2D1TransformGraph* pTransformGraph
00074     )
00075 {
00076     // To maintain consistency across different DPIs, this effect needs to cover more pixels at
00077     // higher than normal DPIs. The context is saved here so the effect can later retrieve the DPI.
00078     m_effectContext = pEffectContext;
00079     BasicReaderWriter^ reader = ref new BasicReaderWriter();
00080     Platform::Array<unsigned char, 1U>^ data;
00081
00082     try
00083     {
00084         data = reader->ReadData("SdrOverlayEffect.cso");
00085     }
00086     catch (Platform::Exception^ e)
00087     {
00088         // Return error if file can not be read.
00089         return e->HResult;
00090     }
00091
00092     HRESULT hr = pEffectContext->LoadPixelShader(GUID_SdrOverlayPixelShader, data->Data, data->Length);
00093
00094     // This loads the shader into the Direct2D image effects system and associates it with the GUID passed in.
00095     // If this method is called more than once (say by other instances of the effect) with the same GUID,
00096     // the system will simply do nothing, ensuring that only one instance of a shader is stored regardless of how
00097     // many time it is used.
00098     if (SUCCEEDED(hr))
00099     {
00100         // The graph consists of a single transform. In fact, this class is the transform,
00101         // reducing the complexity of implementing an effect when all we need to
00102         // do is use a single pixel shader.
00103         hr = pTransformGraph->SetSingleTransformNode(this);
00104     }
00105
00106     return hr;
00107 }
00108
00109 HRESULT SdrOverlayEffect::UpdateConstants()
00110 {
00111     // Update the DPI if it has changed. This allows the effect to scale across different DPIs automatically.
00112     m_effectContext->GetDpi(&m_dpi, &m_dpi);
00113     m_constants.dpi = m_dpi;
00114
00115     return m_drawInfo->SetPixelShaderConstantBuffer(reinterpret_cast<BYTE*>(&m_constants), sizeof(m_constants));
00116 }
00117
00118 IFACEMETHODIMP SdrOverlayEffect::PrepareForRender(D2D1_CHANGE_TYPE changeType)
00119 {
00120     return UpdateConstants();
00121 }
00122
00123 // SetGraph is only called when the number of inputs changes. This never happens as we publish this effect
00124 // as a single input effect.
00125 IFACEMETHODIMP SdrOverlayEffect::SetGraph(_In_ ID2D1TransformGraph* pGraph)
00126 {
00127     return E_NOTIMPL;
00128 }
00129
00130 // Called to assign a new render info class, which is used to inform D2D on
00131 // how to set the state of the GPU.
00132 IFACEMETHODIMP SdrOverlayEffect::SetDrawInfo(_In_ ID2D1DrawInfo* pDrawInfo)
00133 {
00134     m_drawInfo = pDrawInfo;
00135
00136     return m_drawInfo->SetPixelShader(GUID_SdrOverlayPixelShader);
00137 }
00138
00139 // Calculates the mapping between the output and input rects.
00140 IFACEMETHODIMP SdrOverlayEffect::MapOutputRectToInputRects(
00141     _In_ const D2D1_RECT_L* pOutputRect,
00142     _Out_writes_(inputRectCount) D2D1_RECT_L* pInputRects,
00143     UINT32 inputRectCount
00144     ) const
00145 {
00146     // This effect has exactly 1 input.
00147     if (inputRectCount != 1)
00148     {
00149         return E_INVALIDARG;
00150     }
00151
00152     // 1:1 mapping of output to input rect.
00153     pInputRects[0].left = pOutputRect->left;
00154     pInputRects[0].top = pOutputRect->top;
00155     pInputRects[0].right = pOutputRect->right;
00156     pInputRects[0].bottom = pOutputRect->bottom;
00157
00158     return S_OK;
00159 }
00160
00161 IFACEMETHODIMP SdrOverlayEffect::MapInputRectsToOutputRect(
00162     _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputRects,
00163     _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputOpaqueSubRects,
00164     UINT32 inputRectCount,
00165     _Out_ D2D1_RECT_L* pOutputRect,
00166     _Out_ D2D1_RECT_L* pOutputOpaqueSubRect
00167     )
00168 {
00169     // This effect has exactly 1 input.
00170     if (inputRectCount != 1)
00171     {
00172         return E_INVALIDARG;
00173     }
00174
00175     // 1:1 mapping of input to output rect.
00176     *pOutputRect = pInputRects[0];
00177     m_inputRect = pInputRects[0];
00178
00179     // This effect always outputs fully opaque pixels.
00180     *pOutputOpaqueSubRect = pInputRects[0];
00181
00182     return S_OK;
00183 }
00184
00185 IFACEMETHODIMP SdrOverlayEffect::MapInvalidRect(
00186     UINT32 inputIndex,
00187     D2D1_RECT_L invalidInputRect,
00188     _Out_ D2D1_RECT_L* pInvalidOutputRect
00189     ) const
00190 {
00191     HRESULT hr = S_OK;
00192
00193     // Indicate that the entire output may be invalid.
00194     *pInvalidOutputRect = m_inputRect;
00195
00196     return hr;
00197 }
00198
00199 IFACEMETHODIMP_(UINT32) SdrOverlayEffect::GetInputCount() const
00200 {
00201     return 1;
00202 }
00203
00204 // D2D ensures that that effects are only referenced from one thread at a time.
00205 // To improve performance, we simply increment/decrement our reference count
00206 // rather than use atomic InterlockedIncrement()/InterlockedDecrement() functions.
00207 IFACEMETHODIMP_(ULONG) SdrOverlayEffect::AddRef()
00208 {
00209     m_refCount++;
00210     return m_refCount;
00211 }
00212
00213 IFACEMETHODIMP_(ULONG) SdrOverlayEffect::Release()
00214 {
00215     m_refCount--;
00216
00217     if (m_refCount == 0)
00218     {
00219         delete this;
00220         return 0;
00221     }
00222     else
00223     {
00224         return m_refCount;
00225     }
00226 }
00227
00228 // This enables the stack of parent interfaces to be queried. In the instance
00229 // of the SdrOverlay interface, this method simply enables the developer
00230 // to cast a SdrOverlay instance to an ID2D1EffectImpl or IUnknown instance.
00231 IFACEMETHODIMP SdrOverlayEffect::QueryInterface(
00232     _In_ REFIID riid,
00233     _Outptr_ void** ppOutput
00234     )
00235 {
00236     *ppOutput = nullptr;
00237     HRESULT hr = S_OK;
00238
00239     if (riid == __uuidof(ID2D1EffectImpl))
00240     {
00241         *ppOutput = reinterpret_cast<ID2D1EffectImpl*>(this);
00242     }
00243     else if (riid == __uuidof(ID2D1DrawTransform))
00244     {
00245         *ppOutput = static_cast<ID2D1DrawTransform*>(this);
00246     }
00247     else if (riid == __uuidof(ID2D1Transform))
00248     {
00249         *ppOutput = static_cast<ID2D1Transform*>(this);
00250     }
00251     else if (riid == __uuidof(ID2D1TransformNode))
00252     {
00253         *ppOutput = static_cast<ID2D1TransformNode*>(this);
00254     }
00255     else if (riid == __uuidof(IUnknown))
00256     {
00257         *ppOutput = this;
00258     }
00259     else
00260     {
00261         hr = E_NOINTERFACE;
00262     }
00263
00264     if (*ppOutput != nullptr)
00265     {
00266         AddRef();
00267     }
00268
00269     return hr;
00270 }
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: KeyCredentialManager/cpp/Account.h Source File

  • KeyCredentialManager
  • cpp

Account.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002 #pragma once
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005
00006 namespace SDKTemplate
00007 {
00008     public ref class Account sealed
00009     {
00010     public:
00011         property Platform::String^ Name
00012         {
00013             Platform::String^ get();
00014             void set(Platform::String^ value);
00015         };
00016
00017         property Platform::String^ Email;
00018         property bool UsesPassport;
00019
00020     private:
00021         Platform::String^ m_Name;
00022     };
00023 }
Generated on Fri Nov 15 2024 22:20:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

INetworkClient Member List

This is the complete list of members for INetworkClient, including all inherited members.
ConnectAsync(String^url, WORD wPort) INetworkClient
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteColorGlyph/cpp/DWriteColorTextRendererMain.h Source File

  • DWriteColorGlyph
  • cpp

DWriteColorTextRendererMain.h

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include "DeviceResources.h"
00011 #include "DWriteColorTextRendererRenderer.h"
00012 #include "SampleOverlay.h"
00013
00014 // Renders Direct2D and 3D content on the screen.
00015 namespace DWriteColorTextRenderer
00016 {
00017     class DWriteColorTextRendererMain : public DX::IDeviceNotify
00018     {
00019     public:
00020         DWriteColorTextRendererMain(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00021         ~DWriteColorTextRendererMain();
00022         void UpdateForWindowSizeChange();
00023         bool Render();
00024
00025         // IDeviceNotify
00026         virtual void OnDeviceLost();
00027         virtual void OnDeviceRestored();
00028
00029     private:
00030         // Cached pointer to device resources.
00031         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00032
00033         // Sample renderer class.
00034         std::unique_ptr<DWriteColorTextRendererRenderer> m_sceneRenderer;
00035
00036         // Sample overlay class.
00037         std::unique_ptr<SampleOverlay> m_sampleOverlay;
00038     };
00039 }
Generated on Fri Nov 15 2024 22:19:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LinguisticServices/cs/Scenario1_LanguageDetection.xaml.cs Source File

  • LinguisticServices
  • cs

Scenario1_LanguageDetection.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Sample;
00015 using System.Text;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario1_LanguageDetection : Page
00020     {
00021         public Scenario1_LanguageDetection()
00022         {
00023             InitializeComponent();
00024         }
00025
00026         public void Go_Click(object sender, RoutedEventArgs e)
00027         {
00028             StringBuilder output = new StringBuilder();
00029             foreach (string language in LinguisticServices.RecognizeTextLanguages(TextInput.Text))
00030             {
00031                 output.AppendLine(language);
00032             }
00033             TextOutput.Text = output.ToString();
00034         }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlTailoredMultipleViews/cs/TailoredMultipleViews/DisplaySizeHelper/DisplaySizeClass.cpp Source File

  • XamlTailoredMultipleViews
  • cs
  • TailoredMultipleViews
  • DisplaySizeHelper

DisplaySizeClass.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "DisplaySizeClass.h"
00003 #include "sysinfoapi.h"
00004
00005 using namespace DisplaySizeHelper;
00006 using namespace Platform;
00007
00008 DisplaySizeClass::DisplaySizeClass()
00009 {
00010 }
00011
00012 double DisplaySizeHelper::DisplaySizeClass::GetDisplaySizeInInches()
00013 {
00014     double sizeInInches = 7;
00015     HRESULT result = GetIntegratedDisplaySize(&sizeInInches);
00016     if (result == S_OK)
00017         return sizeInInches;
00018     else
00019         return -1; //This will happen for non-integrated displays like monitors, projection surfaces etc.,
00020 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/Scenario_ListConstraint.xaml.h Source File

  • SpeechRecognitionAndSynthesis
  • cpp

Scenario_ListConstraint.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario_ListConstraint.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario_ListConstraint sealed
00024     {
00025     public:
00026         Scenario_ListConstraint();
00027
00028     protected:
00029         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00031
00032     private:
00033         /// <summary>
00034         /// This HResult represents the scenario where a user is prompted to allow in-app speech, but
00035         /// declines. This should only happen on a Phone device, where speech is enabled for the entire device,
00036         /// not per-app.
00037         /// </summary>
00038         static const unsigned int HResultPrivacyStatementDeclined = 0x80045509;
00039         static const unsigned int HResultRecognizerNotFound = 0x8004503a;
00040
00041
00042         SDKTemplate::MainPage^ rootPage;
00043         Windows::UI::Core::CoreDispatcher^ dispatcher;
00044         Windows::Media::SpeechRecognition::SpeechRecognizer^ speechRecognizer;
00045         Windows::ApplicationModel::Resources::Core::ResourceContext^ speechContext;
00046         Windows::ApplicationModel::Resources::Core::ResourceMap^ speechResourceMap;
00047         bool isPopulatingLanguages = false;
00048
00049         void RecognizeWithUIListConstraint_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050         void RecognizeWithoutUIListConstraint_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00051
00052         void InitializeRecognizer(Windows::Globalization::Language^ recognizerLanguage);
00053         void PopulateLanguageDropdown();
00054
00055         Windows::Foundation::EventRegistrationToken stateChangedToken;
00056
00057         void SpeechRecognizer_StateChanged(Windows::Media::SpeechRecognition::SpeechRecognizer ^sender, Windows::Media::SpeechRecognition::SpeechRecognizerStateChangedEventArgs ^args);
00058         void cbLanguageSelection_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00059     };
00060 }
Generated on Fri Nov 15 2024 22:21:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario10 Member List

This is the complete list of members for Scenario10, including all inherited members.
Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario10 | [inline, private]
Scenario10() | Scenario10 | [inline]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

InvalidPageException Member List

This is the complete list of members for InvalidPageException, including all inherited members.
get_DisplayMessage() | InvalidPageException | [inline]
InvalidPageException(const std::wstring &message) | InvalidPageException | [inline]
m_displayMessage | InvalidPageException | [private]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/cpp/Scenario1_LowLatency.xaml.cpp Source File

  • SimpleCommunication
  • cpp

Scenario1_LowLatency.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_LowLatency.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Core;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Primitives;
00023 using namespace Windows::UI::Xaml::Data;
00024 using namespace Windows::UI::Xaml::Input;
00025 using namespace Windows::UI::Xaml::Media;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00029
00030 enum Action
00031 {
00032     previewButtonClicked,
00033     localClientButtonClicked,
00034     previewSetupCompleted,
00035     recordingStarted,
00036     latencyModeToggled,
00037 };
00038
00039 Scenario1_LowLatency::Scenario1_LowLatency()
00040     : _currentState(ScenarioOneStates::uninitialized)
00041     , _previousState(ScenarioOneStates::uninitialized)
00042     , _latencyMode(LatencyModes::uninitialized)
00043     , _initialized(false)
00044     , _navigationDisabled(FALSE)
00045 {
00046     InitializeComponent();
00047
00048     _sdkSample.Initialize();
00049     _dispatcher = Window::Current->Dispatcher;
00050
00051     _localHostVideo[LatencyModes::highLatency] = PlaybackVideo;
00052     _localHostVideo[LatencyModes::lowLatency] = RealTimePlaybackVideo;
00053
00054     _streamFilteringCriteria.aspectRatio = "1.333333333333333";
00055     _streamFilteringCriteria.horizontalResolution = 640;
00056     _streamFilteringCriteria.subType = "YUY2";
00057
00058     actionTransitionFunctions[ScenarioOneStates::initializing][Action::previewSetupCompleted] = ref new ActionTransition(this, &Scenario1_LowLatency::initializing_previewSetupCompleted);
00059     actionTransitionFunctions[ScenarioOneStates::waiting][Action::previewButtonClicked] = ref new ActionTransition(this, &Scenario1_LowLatency::waiting_previewButtonClicked);
00060     actionTransitionFunctions[ScenarioOneStates::previewing][Action::previewButtonClicked] = ref new ActionTransition(this, &Scenario1_LowLatency::previewing_previewButtonClicked);
00061     actionTransitionFunctions[ScenarioOneStates::previewing][Action::localClientButtonClicked] = ref new ActionTransition(this, &Scenario1_LowLatency::previewing_localClientButtonClicked);
00062     actionTransitionFunctions[ScenarioOneStates::previewing][Action::recordingStarted] = ref new ActionTransition(this, &Scenario1_LowLatency::previewing_recordingStarted);
00063     actionTransitionFunctions[ScenarioOneStates::streaming][Action::previewButtonClicked] = ref new ActionTransition(this, &Scenario1_LowLatency::streaming_previewButtonClicked);
00064     actionTransitionFunctions[ScenarioOneStates::streaming][Action::latencyModeToggled] = ref new ActionTransition(this, &Scenario1_LowLatency::streaming_latencyModeToggled);
00065     actionTransitionFunctions[ScenarioOneStates::streaming][Action::recordingStarted] = ref new ActionTransition(this, &Scenario1_LowLatency::streaming_recordingStarted);
00066
00067     MainPage::EnsureExtensionRegistration();
00068 }
00069
00070 /// <summary>
00071 /// Invoked when this page is about to be displayed in a Frame.
00072 /// </summary>
00073 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00074 /// property is typically used to configure the page.</param>
00075 void Scenario1_LowLatency::OnNavigatedTo(NavigationEventArgs^ e)
00076 {
00077     if (_initialized)
00078     {
00079         InitializeUIControls();
00080         return;
00081     }
00082     else
00083         if (_currentState == ScenarioOneStates::initializing || _device)
00084         {
00085             // We are already in intializing state.
00086             return;
00087         }
00088
00089     LockScenarioChange();
00090
00091     _sdkSample.DisplayStatus("Loading...Please wait.");
00092
00093     // Check for camera and init scenario if one is found
00094     task<DeviceInformationCollection^>(DeviceInformation::FindAllAsync(DeviceClass::VideoCapture)).then([this](DeviceInformationCollection^ devices)
00095     {
00096         return devices->Size > 0;
00097     }).then([this](bool success)
00098     {
00099         if (success)
00100         {
00101             if (_currentState == ScenarioOneStates::initializing || _device)
00102             {
00103                 // We are already in intializing state.
00104                 cancel_current_task();
00105             }
00106             else
00107             {
00108                 return Initialize().then([this](task<void> result)
00109                 {
00110                     try
00111                     {
00112                         result.get();
00113                         return create_task(_dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00114                         {
00115                             InitializeUIControls();
00116                             UnlockScenarioChange();
00117                             _initialized = true;
00118
00119                             m_visibilityEventRegistrationToken = Window::Current->VisibilityChanged += ref new Windows::UI::Xaml::WindowVisibilityChangedEventHandler(this, &Scenario1_LowLatency::VisibilityChanged);
00120                         })));
00121                     }
00122                     catch (Platform::Exception^ e)
00123                     {
00124                         Windows::Foundation::HResult hr;
00125                         hr.Value = e->HResult;
00126                         _sdkSample.FormatError(hr, "Initialization error: ", "");
00127                         UnlockScenarioChange();
00128                         return create_task([] {});
00129                     }
00130                 });
00131             }
00132         }
00133         else
00134         {
00135             _sdkSample.DisplayError("A machine with a camera is required to run this sample.");
00136             UnlockScenarioChange();
00137             cancel_current_task();
00138         }
00139     });
00140 }
00141
00142 void Scenario1_LowLatency::InitializeUIControls()
00143 {
00144     PreviewVideo->FlowDirection = Windows::UI::Xaml::FlowDirection::RightToLeft;
00145
00146     PlaybackVideo->AutoPlay = true;
00147     PlaybackVideo->FlowDirection = Windows::UI::Xaml::FlowDirection::RightToLeft;
00148     PlaybackVideo->MediaFailed += ref new Windows::UI::Xaml::ExceptionRoutedEventHandler(this, &Scenario1_LowLatency::OnMediaFailed);
00149
00150     RealTimePlaybackVideo->AutoPlay = true;
00151     RealTimePlaybackVideo->FlowDirection = Windows::UI::Xaml::FlowDirection::RightToLeft;
00152     RealTimePlaybackVideo->MediaFailed += ref new Windows::UI::Xaml::ExceptionRoutedEventHandler(this, &Scenario1_LowLatency::OnMediaFailed);
00153
00154     _latencyMode = LatencyModes::highLatency;
00155     LatencyModeToggle->IsOn = (_latencyMode == LatencyModes::lowLatency);
00156 };
00157
00158 void Scenario1_LowLatency::OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e)
00159 {
00160     if (InterlockedOr(&_navigationDisabled, 0))
00161     {
00162         e->Cancel = true;
00163     }
00164
00165     Window::Current->VisibilityChanged -= m_visibilityEventRegistrationToken;
00166 }
00167
00168 void Scenario1_LowLatency::OnNavigatedFrom(NavigationEventArgs^ e)
00169 {
00170     _sdkSample.Deinitialize();
00171     this->Cleanup();
00172     for (auto iter = _localHostVideo.begin(); iter != _localHostVideo.end(); iter++)
00173     {
00174         auto video = iter->second;
00175         if (video)
00176         {
00177             video->Source = nullptr;
00178         }
00179     }
00180     Reset();
00181 }
00182
00183 /// <summary>Handler for the camera 'failed' event</summary>
00184 void Scenario1_LowLatency::OnMediaCaptureFailed(CaptureDevice^ sender, CaptureFailedEventArgs^ errorEventArgs)
00185 {
00186     _sdkSample.FormatError(errorEventArgs, "Capture engine error code: ");
00187 }
00188
00189 void Scenario1_LowLatency::OnIncomingConnection(Microsoft::Samples::SimpleCommunication::StspMediaSinkProxy^ sender, Microsoft::Samples::SimpleCommunication::IncomingConnectionEventArgs^ args)
00190 {
00191     args->Accept();
00192 }
00193
00194 void Scenario1_LowLatency::VisibilityChanged(Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e)
00195 {
00196     if (e->Visible == true)
00197     {
00198         Initialize();
00199     }
00200     else
00201     {
00202         Cleanup();
00203     }
00204 }
00205
00206
00207 /// <summary>Initializes the scenario</summary>
00208 task<void> Scenario1_LowLatency::Initialize()
00209 {
00210     _ASSERT(_currentState != ScenarioOneStates::initializing);
00211
00212     _currentState = ScenarioOneStates::initializing;
00213     CaptureDevice ^device = ref new CaptureDevice();
00214
00215
00216     return device->InitializeAsync().then([this, device](task<void> asyncInfo)
00217     {
00218         try
00219         {
00220             asyncInfo.get();
00221         }
00222         catch (Platform::Exception^ e)
00223         {
00224             HandleError(e, "Initialization error: ", "CaptureManager::InitializeAsync");
00225             if (_device)
00226             {
00227                 _device->CleanupAsync().then([this]() {});
00228                 _device = nullptr;
00229             }
00230             return create_task([] {});
00231         }
00232
00233         _device = device;
00234         if (!_videoSettingsFilter)
00235         {
00236             _videoSettingsFilter = ref new VideoSettingsFilter([this](Windows::Media::MediaProperties::IMediaEncodingProperties^ encodingProp, unsigned int index)
00237             {
00238                 if (encodingProp->Type != L"Video")
00239                 {
00240                     return false;
00241                 }
00242
00243                 auto videoProp = static_cast<Windows::Media::MediaProperties::IVideoEncodingProperties^>(encodingProp);
00244                 if (videoProp->Height != 0 && videoProp->Width != 0)
00245                 {
00246                     return (videoProp->Width == _streamFilteringCriteria.horizontalResolution &&
00247                         videoProp->Subtype == _streamFilteringCriteria.subType);
00248                 }
00249                 return false;
00250             });
00251         }
00252
00253         return device->SelectPreferredCameraStreamSettingAsync(Windows::Media::Capture::MediaStreamType::VideoPreview, _videoSettingsFilter).then([this](task<void> asyncInfo)
00254         {
00255             try
00256             {
00257                 asyncInfo.get();
00258             }
00259             catch (Platform::Exception^ e)
00260             {
00261                 HandleError(e, "Initialization error: ", "CaptureDevice.SelectPreferredCameraStreamSettingAsync(): ");
00262                 if (_device)
00263                 {
00264                     _device->CleanupAsync().then([this]() {});
00265                     _device = nullptr;
00266                 }
00267                 return create_task([] {});
00268             }
00269
00270             return create_task(actionTransitionFunctions[ScenarioOneStates::initializing][Action::previewSetupCompleted]());
00271         });
00272     });
00273 }
00274
00275 task<void> Scenario1_LowLatency::StartRecordingToCustomSink()
00276 {
00277     //// Use the MP4 preset to an obtain H.264 video encoding profile
00278     auto mediaEncodingProfile = Windows::Media::MediaProperties::MediaEncodingProfile::CreateMp4(Windows::Media::MediaProperties::VideoEncodingQuality::Vga);
00279     mediaEncodingProfile->Audio = nullptr;
00280     mediaEncodingProfile->Container = nullptr;
00281
00282     return _device->StartRecordingAsync(mediaEncodingProfile).then([this](task<void> asyncInfo)
00283     {
00284         try
00285         {
00286             asyncInfo.get();
00287         }
00288         catch (Platform::Exception^ e)
00289         {
00290             HandleError(e, ": Local streaming initialization error: ", _currentState.ToString());
00291             return create_task([] {});
00292         }
00293
00294         return create_task(actionTransitionFunctions[_currentState][Action::recordingStarted]());
00295     });
00296 }
00297
00298 /// <summary>Cleans up.</summary>
00299 task<void> Scenario1_LowLatency::Cleanup()
00300 {
00301     _previousState = _currentState;
00302
00303     if (!_device)
00304     {
00305         return create_task([]()
00306         {
00307         });
00308     }
00309
00310     Reset();
00311     PreviewVideo->Source = nullptr;
00312
00313     _device->Failed -= _mediaCaptureFailedEventRegistrationToken;
00314     _device->IncomingConnectionEvent -= _incomingConnectionEventRegistrationToken;
00315     return _device->CleanupAsync().then([this]()
00316     {
00317         _device = nullptr;
00318         _currentState = ScenarioOneStates::end;
00319     });
00320 }
00321
00322 void Scenario1_LowLatency::PreviewButtonClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00323 {
00324     LockScenarioChange(); // Lock
00325
00326     _sdkSample.DisplayStatus("");
00327     create_task(actionTransitionFunctions[_currentState][Action::previewButtonClicked]()).then([this](task<void>& transitionTask)
00328     {
00329         try
00330         {
00331             transitionTask.get();
00332             UnlockScenarioChange(); // Unlock
00333         }
00334         catch (Exception^ e)
00335         {
00336             HandleError(e, "Transition error", "Scenario1_LowLatency::PreviewButtonClicked");
00337         }
00338     });
00339 }
00340
00341 void Scenario1_LowLatency::LocalClientButtonClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00342 {
00343     LockScenarioChange(); // Lock
00344
00345     _sdkSample.DisplayStatus("");
00346     PreviewButton->IsEnabled = false;
00347
00348     create_task(actionTransitionFunctions[ScenarioOneStates::previewing][Action::localClientButtonClicked]()).then([this]()
00349     {
00350         _dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00351         {
00352             UpdateLocalClientWindow();
00353             UnlockScenarioChange(); // Unlock
00354         }
00355         ));
00356     }).then([this](task<void>& transitionTask)
00357     {
00358         try
00359         {
00360             transitionTask.get();
00361         }
00362         catch (Exception^ e)
00363         {
00364             HandleError(e, "Transition error", "Scenario1_LowLatency::LocalClientButtonClicked");
00365         }
00366     });
00367 }
00368
00369 void Scenario1_LowLatency::LatencyModeToggled(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00370 {
00371     if (!LatencyModeToggle->IsEnabled)
00372     {
00373         // This is not a user operation.
00374         return;
00375     }
00376
00377     LockScenarioChange(); // Lock
00378
00379     _sdkSample.DisplayStatus("");
00380     PreviewButton->IsEnabled = false;
00381     LatencyModeToggle->IsEnabled = false;
00382
00383     create_task(actionTransitionFunctions[ScenarioOneStates::streaming][Action::latencyModeToggled]()).then([this]()
00384     {
00385         _dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00386         {
00387             UpdateLocalClientWindow();
00388             UnlockScenarioChange(); // Unlock
00389         }));
00390     }).then([this](task<void>& transitionTask)
00391     {
00392         try
00393         {
00394             transitionTask.get();
00395         }
00396         catch (Exception^ e)
00397         {
00398             HandleError(e, "Transition error", "Scenario1_LowLatency::LatencyModeToggled");
00399         }
00400     });
00401 }
00402
00403 void Scenario1_LowLatency::UpdateLocalClientWindow()
00404 {
00405     PreviewButton->IsEnabled = true;
00406     ClientButton->IsEnabled = false;
00407     LatencyModeToggle->IsEnabled = true;
00408
00409     if (_latencyMode == LatencyModes::highLatency)
00410     {
00411         RealTimePlaybackVideo->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00412         PlaybackVideo->Visibility = Windows::UI::Xaml::Visibility::Visible;
00413     }
00414     else
00415     {
00416         PlaybackVideo->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00417         RealTimePlaybackVideo->Visibility = Windows::UI::Xaml::Visibility::Visible;
00418     }
00419 }
00420
00421 void Scenario1_LowLatency::Reset()
00422 {
00423     _sdkSample.ClearLastStatus();
00424     PreviewVideo->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00425     WebcamPreviewPoster->Visibility = Windows::UI::Xaml::Visibility::Visible;
00426     PlaybackVideo->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00427     RealTimePlaybackVideo->Visibility = Windows::UI::Xaml::Visibility::Visible;
00428
00429     PreviewButton->Content = "Start Preview";
00430     ClientButton->IsEnabled = false;
00431     _latencyMode = LatencyModes::highLatency;
00432     LatencyModeToggle->IsEnabled = false;
00433     LatencyModeToggle->IsOn = (_latencyMode == LatencyModes::lowLatency);
00434
00435     if (_currentState == ScenarioOneStates::end)
00436     {
00437         PreviewButton->IsEnabled = false;
00438     }
00439 }
00440
00441 //initializing
00442 IAsyncAction^ Scenario1_LowLatency::initializing_previewSetupCompleted()
00443 {
00444     return create_async([this]() -> task<void>
00445     {
00446         _mediaCaptureFailedEventRegistrationToken = _device->Failed += ref new CaptureFailedHandler(this, &Scenario1_LowLatency::OnMediaCaptureFailed);
00447         _incomingConnectionEventRegistrationToken = _device->IncomingConnectionEvent += ref new IncomingConnectionEventHandler(this, &Scenario1_LowLatency::OnIncomingConnection);
00448         _previousState = _currentState;
00449         _currentState = ScenarioOneStates::waiting;
00450
00451         return create_task(_dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00452         {
00453             PreviewButton->IsEnabled = true;
00454             _sdkSample.DisplayStatus("Done. Tap or click 'Start Preview' button to start webcam preview");
00455         })));
00456     });
00457 }
00458
00459 //waiting
00460 /// <summary>
00461 /// Logic when preview button is clicked and the scenario is in "waiting" state.
00462 /// </summary>
00463 IAsyncAction^ Scenario1_LowLatency::waiting_previewButtonClicked()
00464 {
00465     return create_async([this]() -> task<void>
00466     {
00467         return create_task(_dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00468         {
00469             if (_previousState == ScenarioOneStates::initializing)
00470             {
00471                 PreviewVideo->Source = _device->MediaCapture.Get();
00472             }
00473         }
00474             ))).then([this]()
00475         {
00476             return create_task(_device->MediaCapture.Get()->StartPreviewAsync()).then([this]()
00477             {
00478                 _previousState = _currentState;
00479                 _currentState = ScenarioOneStates::previewing;
00480                 return _dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00481                 {
00482                     WebcamPreviewPoster->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00483                     PreviewVideo->Visibility = Windows::UI::Xaml::Visibility::Visible;
00484                     PreviewButton->Content = "Stop Preview";
00485                     ClientButton->IsEnabled = true;
00486                 }));
00487             });
00488         });
00489     });
00490 }
00491
00492 //previewing
00493 /// <summary>
00494 /// The logic when the "stop" preview button is clicked while the scenario is in "previewing" state.
00495 /// </summary>
00496 IAsyncAction^ Scenario1_LowLatency::previewing_previewButtonClicked()
00497 {
00498     return create_async([this]() -> task<void>
00499     {
00500         return create_task(_device->MediaCapture->StopPreviewAsync()).then([this]()
00501         {
00502             if (ScenarioOneStates::previewing == _currentState)
00503             {
00504                 _previousState = _currentState;
00505                 _currentState = ScenarioOneStates::waiting;
00506             }
00507             return _dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00508             {
00509                 Reset();
00510             }));
00511         });
00512     });
00513 }
00514
00515 IAsyncAction^ Scenario1_LowLatency::previewing_localClientButtonClicked()
00516 {
00517     return create_async([this]() -> task<void>
00518     {
00519         return StartRecordingToCustomSink();
00520     });
00521 }
00522
00523 IAsyncAction^ Scenario1_LowLatency::previewing_recordingStarted()
00524 {
00525     return create_async([this]() -> task<void>
00526     {
00527         return create_task(_dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00528         {
00529             _localHostVideo[_latencyMode]->Source = ref new Uri("stsp://localhost");
00530             _previousState = _currentState;
00531             _currentState = ScenarioOneStates::streaming;
00532         })));
00533     });
00534 }
00535
00536 //streaming
00537 /// <summary>
00538 /// The logic when the "stop" preview button is clicked while the scenario is in "streaming" state.
00539 /// </summary>
00540 IAsyncAction^ Scenario1_LowLatency::streaming_previewButtonClicked()
00541 {
00542     return create_async([this]() -> task<void>
00543     {
00544         return create_task(_dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00545         {
00546             //// stop localhost client video
00547             auto currLocalHostVideo = _localHostVideo[_latencyMode];
00548             currLocalHostVideo->Pause();
00549         }
00550             ))).then([this]()
00551         {
00552             LatencyModes latencyMode = _latencyMode;
00553
00554             //// stop streaming to network and close network sink
00555             return _device->StopRecordingAsync().then([this, latencyMode](task<void> asyncInfo)
00556             {
00557                 return create_task(_dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, asyncInfo, latencyMode]()
00558                 {
00559                     _localHostVideo[latencyMode]->Source = nullptr;
00560                     _latencyMode = LatencyModes::highLatency;
00561                 }
00562                     ))).then([this]()
00563                 {
00564                     return create_task(actionTransitionFunctions[ScenarioOneStates::previewing][Action::previewButtonClicked]()).then([this]()
00565                     {
00566                         _previousState = _currentState;
00567                         _currentState = ScenarioOneStates::waiting;
00568                     });
00569                 });
00570             });
00571         });
00572     });
00573 }
00574
00575 IAsyncAction^ Scenario1_LowLatency::streaming_latencyModeToggled()
00576 {
00577     return create_async([this]() -> task<void>
00578     {
00579         if (!_device)
00580         {
00581             throw ref new Platform::Exception(E_NOINTERFACE);
00582         }
00583
00584         return _device->StopRecordingAsync().then([this](task<void> asyncInfo)
00585         {
00586             try
00587             {
00588                 asyncInfo.get();
00589             }
00590             catch (Platform::Exception^ e)
00591             {
00592                 Windows::Foundation::HResult hr;
00593                 hr.Value = e->HResult;
00594                 _sdkSample.FormatError(hr, "Latency toggle error: ", "StopRecordingAsync: ");
00595                 _currentState = ScenarioOneStates::end;
00596                 throw e;
00597             }
00598
00599             return create_task(_dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00600             {
00601                 _localHostVideo[_latencyMode]->Source = nullptr;
00602             }
00603             )));
00604         }
00605             ).then([this]()
00606         {
00607             _latencyMode = (_latencyMode == LatencyModes::highLatency) ?
00608                 LatencyModes::lowLatency : LatencyModes::highLatency;
00609
00610             return StartRecordingToCustomSink();
00611         });
00612     });
00613 }
00614
00615 /// <summary>
00616 /// Logic when the scenario is in "streaming" state and "recordingStarted"
00617 /// event is triggered after toggling latency mode.
00618 /// </summary>
00619 IAsyncAction^ Scenario1_LowLatency::streaming_recordingStarted()
00620 {
00621     return create_async([this]() -> task<void>
00622     {
00623         return create_task(_dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00624         {
00625             _localHostVideo[_latencyMode]->Source = ref new Uri("stsp://localhost");
00626             _localHostVideo[_latencyMode]->Play();
00627         })));
00628     });
00629 }
00630
00631 /// <summary>
00632 /// Error handling
00633 /// </summary>
00634 void Scenario1_LowLatency::HandleError(Platform::Exception^ error, Platform::String^ msg, Platform::String^ prefix)
00635 {
00636     UnlockScenarioChange();
00637     Windows::Foundation::HResult hr;
00638     hr.Value = error->HResult;
00639     _sdkSample.FormatError(hr, msg, prefix);
00640     _currentState = ScenarioOneStates::end;
00641 }
00642
00643
00644 void Scenario1_LowLatency::OnMediaFailed(Platform::Object ^sender, Windows::UI::Xaml::ExceptionRoutedEventArgs ^e)
00645 {
00646     _sdkSample.DisplayError(e->ErrorMessage);
00647 }
00648
00649 void Scenario1_LowLatency::LockScenarioChange()
00650 {
00651     InterlockedCompareExchange(&_navigationDisabled, TRUE, FALSE);
00652 }
00653
00654 void Scenario1_LowLatency::UnlockScenarioChange()
00655 {
00656     InterlockedCompareExchange(&_navigationDisabled, FALSE, TRUE);
00657 }
Generated on Fri Nov 15 2024 22:21:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ViewLifetimeControl Member List

This is the complete list of members for ViewLifetimeControl, including all inherited members.
consolidated | ViewLifetimeControl | [private]
Consolidated | ViewLifetimeControl |
CreateForCurrentView() | ViewLifetimeControl | [inline, static]
Dispatcher | ViewLifetimeControl |
dispatcher | ViewLifetimeControl | [private]
FinalizeRelease() | ViewLifetimeControl | [inline, private]
Id | ViewLifetimeControl |
InternalReleased | ViewLifetimeControl | [private]
PropertyChanged | ViewLifetimeControl |
refCount | ViewLifetimeControl | [private]
RegisterForEvents() | ViewLifetimeControl | [inline, private]
released | ViewLifetimeControl | [private]
Released | ViewLifetimeControl |
StartViewInUse() | ViewLifetimeControl | [inline]
StopViewInUse() | ViewLifetimeControl | [inline]
Title | ViewLifetimeControl |
title | ViewLifetimeControl | [private]
UnregisterForEvents() | ViewLifetimeControl | [inline, private]
ViewConsolidated(ApplicationView sender, ApplicationViewConsolidatedEventArgs e) | ViewLifetimeControl | [inline, private]
viewId | ViewLifetimeControl | [private]
ViewLifetimeControl(CoreWindow newWindow) | ViewLifetimeControl | [inline, private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | ViewLifetimeControl | [inline, private]
window | ViewLifetimeControl | [private]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/ShareFiles.xaml.h Source File

  • ShareSource
  • cpp

ShareFiles.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ShareFiles.xaml.h
00014 // Declaration of the ShareFiles class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "SharePage.h"
00021 #include "ShareFiles.g.h"
00022 #include "MainPage.xaml.h"
00023
00024 namespace SDKTemplate
00025 {
00026     public ref class ShareFiles sealed
00027     {
00028     public:
00029         ShareFiles();
00030
00031     protected:
00032         virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request) override;
00033
00034     private:
00035         Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile^>^ storageItems;
00036
00037         void SelectFilesButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Fri Nov 15 2024 22:21:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/xBindSampleModel/Model.cs Source File

  • XamlBind
  • cpp
  • xBindSampleModel

Model.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.ComponentModel;
00004 using System.Linq;
00005 using System.Runtime.CompilerServices;
00006 using Windows.UI;
00007 using Windows.UI.Xaml;
00008
00009 namespace xBindSampleModel
00010 {
00011     public sealed class DataModel : DependencyObject, INotifyPropertyChanged
00012     {
00013         public DataModel()
00014         {
00015             InitializeValues();
00016         }
00017
00018         public string StringPropNoINPC { get; set; }
00019         public string StringPropAsInteger { get; set; }
00020         public int IntPropNoINPC { get; set; }
00021         public IEmployee EmployeePropNoINPC { get; set; }
00022
00023         private string _StringPropWithINPC;
00024         public string StringPropWithINPC
00025         {
00026             get { return _StringPropWithINPC; }
00027             set
00028             {
00029                 if (value != _StringPropWithINPC)
00030                 {
00031                     _StringPropWithINPC = value;
00032                     NotifyPropertyChanged();
00033                 }
00034             }
00035         }
00036
00037         private int _IntPropWithINPC;
00038         public int IntPropWithINPC
00039         {
00040             get { return _IntPropWithINPC; }
00041             set
00042             {
00043                 if (value != _IntPropWithINPC)
00044                 {
00045                     _IntPropWithINPC = value;
00046                     NotifyPropertyChanged();
00047                 }
00048             }
00049         }
00050
00051         private Color _ColorPropWithINPC;
00052         public Color ColorPropWithINPC
00053         {
00054             get { return _ColorPropWithINPC; }
00055             set
00056             {
00057                 if (value != _ColorPropWithINPC)
00058                 {
00059                     _ColorPropWithINPC = value;
00060                     NotifyPropertyChanged();
00061                 }
00062             }
00063         }
00064
00065         private IEmployee _EmployeePropWithINPC;
00066         public IEmployee EmployeePropWithINPC
00067         {
00068             get { return _EmployeePropWithINPC; }
00069             set
00070             {
00071                 if (value != _EmployeePropWithINPC)
00072                 {
00073                     _EmployeePropWithINPC = value;
00074                     NotifyPropertyChanged();
00075                 }
00076             }
00077         }
00078
00079         private EmployeeCollection _Employees;
00080         public EmployeeCollection Employees
00081         {
00082             get { return _Employees; }
00083             set
00084             {
00085                 if (value != _Employees)
00086                 {
00087                     _Employees = value;
00088                     NotifyPropertyChanged();
00089                 }
00090             }
00091         }
00092
00093         private Manager _ManagerProp;
00094         public Manager ManagerProp
00095         {
00096             get { return _ManagerProp; }
00097             set
00098             {
00099                 if (value != _ManagerProp)
00100                 {
00101                     _ManagerProp = value;
00102                     NotifyPropertyChanged();
00103                 }
00104             }
00105         }
00106
00107         private bool _BoolPropWithINPC;
00108         public bool BoolPropWithINPC
00109         {
00110             get { return _BoolPropWithINPC; }
00111             set
00112             {
00113                 if (value != _BoolPropWithINPC)
00114                 {
00115                     _BoolPropWithINPC = value;
00116                     NotifyPropertyChanged();
00117                 }
00118             }
00119         }
00120
00121         public int IntPropertyDP
00122         {
00123             get { return (int)GetValue(IntPropertyDPProperty); }
00124             set { SetValue(IntPropertyDPProperty, value); }
00125         }
00126         #region IntPropertyDP DP
00127         private const string IntPropertyDPName = "IntPropertyDP";
00128         private static readonly DependencyProperty _IntPropertyDPProperty =
00129             DependencyProperty.Register(IntPropertyDPName, typeof(int), typeof(DataModel), new PropertyMetadata(0));
00130         public static DependencyProperty IntPropertyDPProperty { get { return _IntPropertyDPProperty; } }
00131         #endregion
00132
00133         public string StringPropertyDP
00134         {
00135             get { return (string)GetValue(StringPropertyDPProperty); }
00136             set { SetValue(StringPropertyDPProperty, value); }
00137         }
00138         #region StringPropertyDP DP
00139         private const string StringPropertyDPName = "StringPropertyDP";
00140         private static readonly DependencyProperty _StringPropertyDPProperty =
00141             DependencyProperty.Register(StringPropertyDPName, typeof(string), typeof(DataModel), new PropertyMetadata(""));
00142         public static DependencyProperty StringPropertyDPProperty { get { return _StringPropertyDPProperty; } }
00143         #endregion
00144
00145         public IEmployee EmployeePropertyDP
00146         {
00147             get { return (IEmployee)GetValue(EmployeePropertyDPProperty); }
00148             set { SetValue(EmployeePropertyDPProperty, value); }
00149         }
00150         #region EmployeePropertyDP DP
00151         private const string EmployeePropertyDPName = "EmployeePropertyDP";
00152         private static readonly DependencyProperty _EmployeePropertyDPProperty =
00153             DependencyProperty.Register(EmployeePropertyDPName, typeof(IEmployee), typeof(DataModel), new PropertyMetadata(0));
00154         public static DependencyProperty EmployeePropertyDPProperty { get { return _EmployeePropertyDPProperty; } }
00155
00156         #endregion
00157
00158
00159         public void InitializeValues()
00160         {
00161             ManagerProp = CreateManagerEmployeeTree();
00162             Employees = ManagerProp.ReportsOC;
00163
00164             StringPropNoINPC = "String Property without INPC";
00165             StringPropWithINPC = "String Property with INPC";
00166             ColorPropWithINPC = Colors.Red;
00167             IntPropNoINPC = 42;
00168             IntPropWithINPC = 2;
00169             IntPropertyDP = 42;
00170             StringPropertyDP = "String Property as a DP";
00171             StringPropAsInteger = "65";
00172             EmployeePropNoINPC = Employees[0];
00173             EmployeePropWithINPC = Employees[1];
00174
00175         }
00176         public void UpdateValues()
00177         {
00178             this.BoolPropWithINPC = !this.BoolPropWithINPC;
00179             this.IntPropNoINPC = IntPropNoINPC + 10 % 100;
00180             this.IntPropWithINPC = IntPropWithINPC + 1 % 10;
00181             this.IntPropertyDP = IntPropertyDP + 10 % 100;
00182
00183             string name = ", " + lnames[(new Random()).Next(lnames.Length)];
00184             this.StringPropNoINPC += name;
00185             this.StringPropWithINPC += name;
00186             this.StringPropertyDP += name;
00187
00188             EmployeePropWithINPC = Employees[IntPropWithINPC % Employees.Count];
00189             EmployeePropertyDP = Employees[(IntPropWithINPC + 1) % Employees.Count];
00190             // Swap Manager Reports [0], [2]
00191             var temp = ManagerProp.ReportsOC[0];
00192             ManagerProp.ReportsOC[0] = ManagerProp.ReportsOC[2];
00193             ManagerProp.ReportsOC[2] = temp;
00194         }
00195
00196         public string SubString(string data, int startIndex)
00197         {
00198             return data.Substring(startIndex);
00199         }
00200
00201
00202         #region Employee Tree Creation
00203         private static string[] fnames = { "Alice", "Brian", "Chris", "David", "Emily", "Freda", "Garry", "Harriet", "Isobel", "John", "Keith", "Lisa", "Mark", "Nathan", "Olivia", "Penelope", "Quentin", "Robert", "Simon", "Tom", "Veronica", "Will", "Xavier", "Yvette", "Zach" };
00204         private static string[] lnames = { "Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Taylor", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Robinson", "Clark", "Rodriguez", "Lewis", "Lee", "Walker" };
00205
00206         public static Manager CreateManagerEmployeeTree()
00207         {
00208             Random rnd = new Random(4524); // Passing in a seed guarantees the same values each time
00209             Manager CEO = new Manager() { FirstName = fnames[rnd.Next(fnames.Length)], LastName = lnames[rnd.Next(lnames.Length)] };
00210             CreateReports(5, CEO, rnd);
00211             return CEO;
00212         }
00213
00214         private static void CreateReports(int depth, Manager m, Random rnd)
00215         {
00216             int count = rnd.Next(10) + 3;
00217             for (int i = 0; i < count; i++)
00218             {
00219                 int j = rnd.Next(10);
00220                 IEmployee e = (j > 2 && depth > 1) ? (IEmployee)new Manager() : (IEmployee)new Employee();
00221                 e.LastName = lnames[rnd.Next(lnames.Length)];
00222                 e.FirstName = fnames[rnd.Next(fnames.Length)];
00223                 e.DirectManager = m;
00224                 m.ReportsList.Add(e);
00225                 m.ReportsDict.Add(e.FirstName + i, e);
00226                 if (e.IsManager) CreateReports(depth - 1, (Manager)e, rnd);
00227             }
00228         }
00229
00230         #endregion
00231         #region INPC
00232
00233         public event PropertyChangedEventHandler PropertyChanged;
00234
00235         private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
00236         {
00237             if (PropertyChanged != null)
00238             {
00239                 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
00240             }
00241         }
00242         #endregion
00243
00244     }
00245
00246 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PersistentState Member List

This is the complete list of members for PersistentState, including all inherited members.
__pad0__ | PersistentState |
Initialize(_In_ winrt::Windows::Foundation::Collections::IPropertySet settingsValues, _In_ winrt::hstring const &key) | PersistentState |
key | PersistentState |
LoadBool(Platform::String^key, bool defaultValue) | PersistentState |
LoadBool(winrt::hstring const &key, bool defaultValue) | PersistentState |
LoadBool(Platform::String^key, bool defaultValue) | PersistentState |
LoadInt32(Platform::String^key, int defaultValue) | PersistentState |
LoadInt32(winrt::hstring const &key, int defaultValue) | PersistentState |
LoadInt32(Platform::String^key, int defaultValue) | PersistentState |
LoadSingle(Platform::String^key, float defaultValue) | PersistentState |
LoadSingle(winrt::hstring const &key, float defaultValue) | PersistentState |
LoadSingle(Platform::String^key, float defaultValue) | PersistentState |
LoadString(Platform::String^key, Platform::String^defaultValue) | PersistentState |
LoadString(winrt::hstring const &key, winrt::hstring const &defaultValue) | PersistentState |
LoadString(Platform::String^key, Platform::String^defaultValue) | PersistentState |
LoadXMFLOAT3(Platform::String^key, DirectX::XMFLOAT3 defaultValue) | PersistentState |
LoadXMFLOAT3(winrt::hstring const &key, DirectX::XMFLOAT3 defaultValue) | PersistentState |
LoadXMFLOAT3(Platform::String^key, DirectX::XMFLOAT3 defaultValue) | PersistentState |
m_keyName | PersistentState | [private]
m_keyName | PersistentState | [private]
m_settingsValues | PersistentState | [private]
m_settingsValues | PersistentState | [private]
SaveBool(Platform::String^key, bool value) | PersistentState |
SaveBool(winrt::hstring const &key, bool value) | PersistentState |
SaveBool(Platform::String^key, bool value) | PersistentState |
SaveInt32(Platform::String^key, int value) | PersistentState |
SaveInt32(winrt::hstring const &key, int value) | PersistentState |
SaveInt32(Platform::String^key, int value) | PersistentState |
SaveSingle(Platform::String^key, float value) | PersistentState |
SaveSingle(winrt::hstring const &key, float value) | PersistentState |
SaveSingle(Platform::String^key, float value) | PersistentState |
SaveString(Platform::String^key, Platform::String^string) | PersistentState |
SaveString(winrt::hstring const &key, winrt::hstring const &string) | PersistentState |
SaveString(Platform::String^key, Platform::String^string) | PersistentState |
SaveXMFLOAT3(Platform::String^key, DirectX::XMFLOAT3 value) | PersistentState |
SaveXMFLOAT3(winrt::hstring const &key, DirectX::XMFLOAT3 value) | PersistentState |
SaveXMFLOAT3(Platform::String^key, DirectX::XMFLOAT3 value) | PersistentState |
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TitleBar/cpp/SampleConfiguration.cpp Source File

  • TitleBar
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 using namespace Windows::ApplicationModel::Core;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::UI::Core;
00021 using namespace Windows::UI::ViewManagement;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024
00025 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00026 {
00027     { "Custom colors", "SDKTemplate.Scenario1_Colors" },
00028     { "Custom drawing", "SDKTemplate.Scenario2_Extend" },
00029 };
00030
00031 #pragma region Custom title bar
00032 void MainPage::AddCustomTitleBar()
00033 {
00034     if (customTitleBar == nullptr)
00035     {
00036         customTitleBar = ref new CustomTitleBar();
00037         customTitleBar->EnableControlsInTitleBar(areControlsInTitleBar);
00038
00039         // Make the main page's content a child of the title bar
00040         // and make the title bar the new page content.
00041         UIElement^ mainContent = this->Content;
00042         this->Content = nullptr;
00043         customTitleBar->SetPageContent(mainContent);
00044         this->Content = customTitleBar;
00045     }
00046 }
00047
00048 void MainPage::RemoveCustomTitleBar()
00049 {
00050     if (customTitleBar != nullptr)
00051     {
00052         // Take the title bar's page content and make it
00053         // the window content.
00054         this->Content = customTitleBar->SetPageContent(nullptr);
00055         customTitleBar = nullptr;
00056     }
00057 }
00058
00059
00060 void MainPage::AreControlsInTitleBar::set(bool value)
00061 {
00062     areControlsInTitleBar = value;
00063     if (customTitleBar != nullptr)
00064     {
00065         customTitleBar->EnableControlsInTitleBar(value);
00066     }
00067 }
00068 #pragma endregion
Generated on Fri Nov 15 2024 22:17:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cpp/pch.h Source File

  • NumberFormatting
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/Scenario3.h Source File

  • WindowsAudioSession
  • cppwinrt

Scenario3.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012 #include "pch.h"
00013 #include "Scenario3.g.h"
00014 #include "MainPage.h"
00015 #include "WASAPIRenderer.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario3 : Scenario3T<Scenario3>, MediaFoundationInitializer
00020     {
00021         Scenario3();
00022
00023         fire_and_forget OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025
00026         void btnPlay_Click(IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         void btnPause_Click(IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void btnPlayPause_Click(IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029         void btnStop_Click(IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00030         void btnFilePicker_Click(IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00031         void radioTone_Checked(IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00032         void radioFile_Checked(IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00033         void sliderFrequency_ValueChanged(IInspectable const& sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs const& e);
00034         void sliderVolume_ValueChanged(IInspectable const& sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs const& e);
00035
00036         // UI Helpers
00037         void DisableContentUI();
00038         void UpdateContentProps(hstring const& text);
00039         void UpdateContentUI();
00040         void UpdateMediaControlUI(DeviceState deviceState);
00041
00042         // Handlers
00043         fire_and_forget OnDeviceStateChange(IDeviceStateSource const& sender, SDKTemplate::DeviceStateChangedEventArgs e);
00044         fire_and_forget OnPickFileAsync();
00045         void OnSetVolume(double volume);
00046
00047         void InitializeDevice();
00048         void StartDevice();
00049         void StopDevice();
00050         void PauseDevice();
00051         void PlayPauseToggleDevice();
00052
00053         fire_and_forget MediaButtonPressed(Windows::Media::SystemMediaTransportControls const& sender, Windows::Media::SystemMediaTransportControlsButtonPressedEventArgs e);
00054
00055     private:
00056         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00057         Windows::Media::SystemMediaTransportControls m_systemMediaControls{ nullptr };
00058         event_token m_deviceStateChangeToken;
00059         event_token m_systemMediaControlsButtonToken;
00060
00061         bool m_deviceSupportsRawMode = false;
00062         bool m_isMinimumLatency = false;
00063
00064         Windows::Storage::Streams::IRandomAccessStream m_contentStream{ nullptr };
00065         ContentType m_contentType = ContentType::Tone;
00066         com_ptr<WASAPIRenderer> m_renderer;
00067     };
00068 }
00069
00070 namespace winrt::SDKTemplate::factory_implementation
00071 {
00072     struct Scenario3 : Scenario3T<Scenario3, implementation::Scenario3>
00073     {
00074     };
00075 }
Generated on Fri Nov 15 2024 22:19:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

WordOverlay Member List

This is the complete list of members for WordOverlay, including all inherited members.
CreateBinding(hstring const &propertyName) | WordOverlay | [private]
CreateBorder(Windows::UI::Xaml::Style const &style, Windows::UI::Xaml::UIElement const &child=nullptr) | WordOverlay |
m_propertyChanged | WordOverlay | [private]
m_wordBoundingBox | WordOverlay | [private]
OnPropertyChanged(hstring const &PropertyName) | WordOverlay | [private]
PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const &handler) | WordOverlay |
PropertyChanged(event_token const &token) noexcept | WordOverlay |
Transform(Windows::UI::Xaml::Media::ScaleTransform const &scale) | WordOverlay |
UpdateProps(Windows::Foundation::Rect const &wordBoundingBox) | WordOverlay | [private]
WordHeight() | WordOverlay | [inline]
WordOverlay(Windows::Media::Ocr::OcrWord const &ocrWord) | WordOverlay |
WordPosition() | WordOverlay | [inline]
WordWidth() | WordOverlay | [inline]
Generated on Fri Nov 15 2024 22:24:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisablingScreenCapture/cppwinrt/Scenario3_AppCapture.h Source File

  • DisablingScreenCapture
  • cppwinrt

Scenario3_AppCapture.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_AppCapture.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario3_AppCapture : Scenario3_AppCaptureT<Scenario3_AppCapture>
00019     {
00020         Scenario3_AppCapture();
00021
00022         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00023         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024
00025         fire_and_forget AllowAppCaptureCheckBox_Toggled(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00026         void AppCapture_CapturingChanged(Windows::Media::Capture::AppCapture const&, Windows::Foundation::IInspectable const&);
00027     private:
00028         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00029         Windows::Media::Capture::AppCapture appCapture{ nullptr };
00030         event_token capturingChangedToken{};
00031
00032         void UpdateCaptureStatus();
00033     };
00034 }
00035
00036 namespace winrt::SDKTemplate::factory_implementation
00037 {
00038     struct Scenario3_AppCapture : Scenario3_AppCaptureT<Scenario3_AppCapture, implementation::Scenario3_AppCapture>
00039     {
00040     };
00041 }
Generated on Fri Nov 15 2024 22:19:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FolderEnumeration/cs/Scenario4.xaml.cs Source File

  • FolderEnumeration
  • cs

Scenario4.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Collections.Generic;
00013 using System.Text;
00014 using System.Threading.Tasks;
00015 using Windows.Storage;
00016 using Windows.Storage.Pickers;
00017 using Windows.Storage.Search;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario4 : Page
00025     {
00026         public Scenario4()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         private async void GetFilesButton_Click(object sender, RoutedEventArgs e)
00032         {
00033             // Reset output.
00034             OutputPanel.Children.Clear();
00035
00036             // Ask the user to pick a folder.
00037             FolderPicker picker = new FolderPicker();
00038             picker.FileTypeFilter.Add("*");
00039             picker.ViewMode = PickerViewMode.List;
00040             picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
00041             StorageFolder folder = await picker.PickSingleFolderAsync();
00042             if (folder != null)
00043             {
00044                 // Query the folder.
00045                 var query = folder.CreateFileQuery();
00046                 var fileList = await query.GetFilesAsync();
00047
00048                 // Display file list with storage provider and availability.
00049                 foreach (StorageFile file in fileList)
00050                 {
00051                     // Create an entry in the list for the item.
00052                     var line = file.Name;
00053
00054                     // Show the item's provider (This PC, OneDrive, Network, or Application Content).
00055                     line += ": On " + file.Provider.DisplayName;
00056
00057                     // Show if the item is available (OneDrive items are usually available when
00058                     // online or when they are marked for "always available offline").
00059                     line += " (";
00060                     if (file.IsAvailable)
00061                     {
00062                         line += "available";
00063                     }
00064                     else
00065                     {
00066                         line += "not available";
00067                     }
00068                     line += ")";
00069                     OutputPanel.Children.Add(CreateLineItemTextBlock(line));
00070                 }
00071             }
00072         }
00073
00074         TextBlock CreateLineItemTextBlock(string contents)
00075         {
00076             TextBlock textBlock = new TextBlock();
00077             textBlock.Text = contents;
00078             textBlock.Style = (Style)Application.Current.Resources["BasicTextStyle"];
00079             textBlock.TextWrapping = TextWrapping.Wrap;
00080             return textBlock;
00081         }
00082     }
00083 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
App() | sealed |
Initialize(Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
Load(Platform::String^entryPoint) | sealed | [virtual]
m_deviceResources | sealed | [private]
m_main | sealed | [private]
m_windowClosed | sealed | [private]
m_windowVisible | sealed | [private]
OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | sealed | [protected]
OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnDpiChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnResuming(Platform::Object^sender, Platform::Object^args) | sealed | [protected]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [protected]
OnVisibilityChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::VisibilityChangedEventArgs^args) | sealed | [protected]
OnWindowClosed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::CoreWindowEventArgs^args) | sealed | [protected]
OnWindowSizeChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::WindowSizeChangedEventArgs^args) | sealed | [protected]
Run() | sealed | [virtual]
SetWindow(Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
Uninitialize() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

UpdateBinary Member List

This is the complete list of members for UpdateBinary, including all inherited members.
Address | UpdateBinary |
ApduCommand(byte cla, byte ins, byte p1, byte p2, byte[] commandData, byte?le) | ApduCommand | [inline]
ApduResponseType | ApduCommand |
CLA | ApduCommand |
CommandData | ApduCommand |
GetBuffer() | ApduCommand | [inline]
INS | ApduCommand |
Le | ApduCommand |
P1 | ApduCommand |
P2 | ApduCommand |
ToString() | ApduCommand | [inline]
UpdateBinary(ushort address, byte[] dataToWrite) | UpdateBinary | [inline]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/Controls/ProjectionViewBroker.cs Source File

  • AdvancedCasting
  • cs
  • Controls

ProjectionViewBroker.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using ScreenCasting.Controls;
00013 using ScreenCasting.Util;
00014 using System;
00015 using System.Collections.Generic;
00016 using System.Linq;
00017 using System.Text;
00018 using System.Threading.Tasks;
00019 using Windows.UI.Core;
00020 using Windows.UI.Xaml.Controls;
00021
00022 namespace ScreenCasting
00023 {
00024     // This is a simple container for a set of data used to comminicate between the main and the projection view
00025     internal class ProjectionViewBroker
00026     {
00027         public CoreDispatcher MainPageDispatcher;
00028         public ViewLifetimeControl ProjectionViewPageControl;
00029         public int MainViewId;
00030         public event EventHandler ProjectionStopping;
00031         public ProjectionViewPage ProjectedPage;
00032         public void NotifyProjectionStopping()
00033         {
00034             try
00035             {
00036                 if (ProjectionStopping != null)
00037                     ProjectionStopping(this, EventArgs.Empty);
00038             }
00039             catch { }
00040         }
00041
00042     }
00043 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Barometer/cpp/Scenario1_DataEvents.xaml.h Source File

  • Barometer
  • cpp

Scenario1_DataEvents.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_DataEvents.xaml.h
00014 // Declaration of the Scenario1_DataEvents class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario1_DataEvents.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario1_DataEvents sealed
00030     {
00031     public:
00032         Scenario1_DataEvents();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038     private:
00039         SDKTemplate::MainPage^ rootPage;
00040         Windows::Devices::Sensors::Barometer^ sensor;
00041         Windows::Foundation::EventRegistrationToken visibilityToken;
00042         Windows::Foundation::EventRegistrationToken readingToken;
00043         uint32 desiredReportIntervalMs;
00044
00045         void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00046         void ReadingChanged(Windows::Devices::Sensors::Barometer^ sender, Windows::Devices::Sensors::BarometerReadingChangedEventArgs^ e);
00047         void ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048         void ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049     };
00050 }
Generated on Fri Nov 15 2024 22:17:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/ConsumerExperiences/cs/RelayCommand.cs Source File

  • AllJoyn
  • ConsumerExperiences
  • cs

RelayCommand.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Windows.Input;
00014
00015 namespace AllJoynConsumerExperiences
00016 {
00017     /// <summary>
00018     /// Helpful class to execute the command logic (as defined by ViewModel's exposed ICommand properties) via delegates.
00019     /// </summary>
00020     public class RelayCommand : ICommand
00021     {
00022         readonly Action<object> execute;
00023         readonly Predicate<object> canExecute;
00024
00025         public RelayCommand(Action<object> execute)
00026             : this(execute, null)
00027         {
00028         }
00029
00030         public event EventHandler CanExecuteChanged
00031         {
00032             add { }
00033             remove { }
00034         }
00035
00036         public RelayCommand(Action<object> execute, Predicate<object> canExecute)
00037         {
00038             if (execute == null)
00039             {
00040                 throw new ArgumentNullException("execute");
00041             }
00042             this.execute = execute;
00043             this.canExecute = canExecute;
00044         }
00045
00046         public bool CanExecute(object parameter)
00047         {
00048             return canExecute == null ? true : canExecute(parameter);
00049         }
00050
00051         public void Execute(object parameter)
00052         {
00053             execute(parameter);
00054         }
00055     }
00056 }
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteColorGlyph/cpp/CustomTextRenderer.h Source File

  • DWriteColorGlyph
  • cpp

CustomTextRenderer.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009 #include "DeviceResources.h"
00010
00011 namespace DWriteColorTextRenderer
00012 {
00013     //  The IDWriteTextRenderer interface is an input parameter to
00014     //  IDWriteTextLayout::Draw.  This interfaces defines a number of
00015     //  callback functions that the client application implements for
00016     //  custom text rendering.
00017     class CustomTextRenderer : public IDWriteTextRenderer
00018     {
00019     public:
00020         CustomTextRenderer(
00021             Microsoft::WRL::ComPtr<ID2D1Factory> d2dFactory,
00022             Microsoft::WRL::ComPtr<ID2D1DeviceContext4> d2dDeviceContext
00023             );
00024
00025         IFACEMETHOD(IsPixelSnappingDisabled)(
00026             _In_opt_ void* clientDrawingContext,
00027             _Out_ BOOL* isDisabled
00028             );
00029
00030         IFACEMETHOD(GetCurrentTransform)(
00031             _In_opt_ void* clientDrawingContext,
00032             _Out_ DWRITE_MATRIX* transform
00033             );
00034
00035         IFACEMETHOD(GetPixelsPerDip)(
00036             _In_opt_ void* clientDrawingContext,
00037             _Out_ FLOAT* pixelsPerDip
00038             );
00039
00040         IFACEMETHOD(DrawGlyphRun)(
00041             _In_opt_ void* clientDrawingContext,
00042             FLOAT baselineOriginX,
00043             FLOAT baselineOriginY,
00044             DWRITE_MEASURING_MODE measuringMode,
00045             _In_ DWRITE_GLYPH_RUN const* glyphRun,
00046             _In_ DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
00047             IUnknown* clientDrawingEffect
00048             );
00049
00050         IFACEMETHOD(DrawUnderline)(
00051             _In_opt_ void* clientDrawingContext,
00052             FLOAT baselineOriginX,
00053             FLOAT baselineOriginY,
00054             _In_ DWRITE_UNDERLINE const* underline,
00055             IUnknown* clientDrawingEffect
00056             );
00057
00058         IFACEMETHOD(DrawStrikethrough)(
00059             _In_opt_ void* clientDrawingContext,
00060             FLOAT baselineOriginX,
00061             FLOAT baselineOriginY,
00062             _In_ DWRITE_STRIKETHROUGH const* strikethrough,
00063             IUnknown* clientDrawingEffect
00064             );
00065
00066         IFACEMETHOD(DrawInlineObject)(
00067             _In_opt_ void* clientDrawingContext,
00068             FLOAT originX,
00069             FLOAT originY,
00070             IDWriteInlineObject* inlineObject,
00071             BOOL isSideways,
00072             BOOL isRightToLeft,
00073             IUnknown* clientDrawingEffect
00074             );
00075
00076     public:
00077         IFACEMETHOD_(unsigned long, AddRef) ();
00078         IFACEMETHOD_(unsigned long, Release) ();
00079         IFACEMETHOD(QueryInterface) (
00080             IID const& riid,
00081             void** ppvObject
00082             );
00083
00084     private:
00085         unsigned long                                m_refCount;
00086         Microsoft::WRL::ComPtr<ID2D1Factory>         m_d2dFactory;
00087         Microsoft::WRL::ComPtr<IDWriteFactory4>      m_dwriteFactory;
00088         Microsoft::WRL::ComPtr<ID2D1DeviceContext4>  m_d2dDeviceContext;
00089         Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> m_outlineBrush;
00090         Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> m_tempBrush;
00091     };
00092 };
Generated on Fri Nov 15 2024 22:19:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ArticleViewModel Member List

This is the complete list of members for ArticleViewModel, including all inherited members.
_headline | ArticleViewModel | [private]
_imageUri | ArticleViewModel | [private]
ArticleViewModel() | ArticleViewModel | [inline]
FullText | ArticleViewModel |
Headline | ArticleViewModel |
ImageSource | ArticleViewModel |
s_random | ArticleViewModel | [private, static]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCoordinateMapper/cpp/App.h Source File

  • CameraStreamCoordinateMapper
  • cpp

App.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015
00016 namespace CameraStreamCoordinateMapper
00017 {
00018     class CameraStreamCoordinateMapperMain;
00019
00020     // Main entry point for our app. Connects the app with the Windows shell and handles application lifecycle events.
00021     ref class App sealed : public Windows::ApplicationModel::Core::IFrameworkView
00022     {
00023     public:
00024         App();
00025
00026         // IFrameworkView Methods.
00027         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00028         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00029         virtual void Load(Platform::String^ entryPoint);
00030         virtual void Run();
00031         virtual void Uninitialize();
00032
00033     protected:
00034         // Application lifecycle event handlers.
00035         void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00036         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00037         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00038
00039         // Window event handlers.
00040         void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args);
00041         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00042         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00043
00044         // DisplayInformation event handlers.
00045         void OnDpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00046         void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00047         void OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00048
00049     private:
00050         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00051         std::unique_ptr<CameraStreamCoordinateMapperMain> m_main;
00052         bool m_windowClosed;
00053         bool m_windowVisible;
00054     };
00055 }
00056
00057 ref class Direct3DApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00058 {
00059 public:
00060     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00061 };
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLOutOfProcessWinRTComponent/cpp/Server/module.cpp Source File

  • WRLOutOfProcessWinRTComponent
  • cpp
  • Server

module.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include "pch.h"
00008
00009 using namespace ABI::Windows::ApplicationModel::Core;
00010 using namespace ABI::Windows::Foundation;
00011 using namespace Microsoft::WRL;
00012 using namespace Microsoft::WRL::Wrappers;
00013
00014 class ExeServerGetActivationFactory WrlFinal : public RuntimeClass<IGetActivationFactory, FtmBase>
00015 {
00016 public:
00017     STDMETHODIMP GetActivationFactory(_In_ HSTRING activatableClassId, _COM_Outptr_ IInspectable** factory)
00018     {
00019         *factory = nullptr;
00020         ComPtr<IActivationFactory> activationFactory;
00021         HRESULT hr = Module<InProc>::GetModule().GetActivationFactory(activatableClassId, &activationFactory);
00022         if (SUCCEEDED(hr))
00023         {
00024             *factory = activationFactory.Detach();
00025         }
00026         return hr;
00027     }
00028 };
00029
00030 int CALLBACK WinMain(_In_  HINSTANCE, _In_  HINSTANCE, _In_  LPSTR, _In_  int)
00031 {
00032     Microsoft::WRL::Wrappers::RoInitializeWrapper roInit(RO_INIT_MULTITHREADED);
00033     if (FAILED(roInit)) return 0;
00034
00035     ComPtr<ICoreApplication> coreApp;
00036     if (FAILED(GetActivationFactory(HStringReference(RuntimeClass_Windows_ApplicationModel_Core_CoreApplication).Get(), &coreApp))) return 0;
00037
00038     auto activationFactory = Make<ExeServerGetActivationFactory>();
00039     if (!activationFactory) return 0;
00040
00041     coreApp->RunWithActivationFactories(activationFactory.Get());
00042
00043     return 0;
00044 }
Generated on Fri Nov 15 2024 22:22:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cpp/pch.cpp Source File

  • ResizeAppView
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/Project.idl Source File

  • XamlListView
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     runtimeclass Scenario1_SimpleListView : Windows.UI.Xaml.Controls.Page
00015     {
00016         Scenario1_SimpleListView();
00017         Windows.UI.Xaml.Data.CollectionViewSource ContactsCVS { get; };
00018     }
00019
00020     runtimeclass Scenario2_SimpleGridView : Windows.UI.Xaml.Controls.Page
00021     {
00022         Scenario2_SimpleGridView();
00023         Windows.UI.Xaml.Data.CollectionViewSource ContactsCVS { get; };
00024     }
00025
00026     runtimeclass Scenario3_MasterDetail : Windows.UI.Xaml.Controls.Page
00027     {
00028         Scenario3_MasterDetail();
00029         Windows.UI.Xaml.Controls.AppBarButton SelectItemsBtn { get; };
00030         Windows.UI.Xaml.Controls.AppBarButton AddItemBtn { get; };
00031         Windows.UI.Xaml.Controls.AppBarButton DeleteItemBtn { get; };
00032         Windows.UI.Xaml.Controls.AppBarButton DeleteItemsBtn { get; };
00033         Windows.UI.Xaml.Controls.AppBarButton CancelSelectionBtn { get; };
00034         Windows.UI.Xaml.Controls.ColumnDefinition MasterColumn { get; };
00035         Windows.UI.Xaml.Controls.ColumnDefinition DetailColumn { get; };
00036         Windows.UI.Xaml.Controls.ListView MasterListView{ get; };
00037     }
00038
00039     [default_interface]
00040     runtimeclass Scenario4_EdgeTappedListView : Windows.UI.Xaml.Controls.Page
00041     {
00042         Scenario4_EdgeTappedListView();
00043     }
00044
00045     runtimeclass Scenario5_RestoreScrollPosition : Windows.UI.Xaml.Controls.Page
00046     {
00047         Scenario5_RestoreScrollPosition();
00048         Windows.Foundation.Collections.IObservableVector<Item> _items { get; };
00049     }
00050
00051     runtimeclass Scenario6_ScrollIntoView : Windows.UI.Xaml.Controls.Page
00052     {
00053         Scenario6_ScrollIntoView();
00054         Windows.Foundation.Collections.IObservableVector<Item> _items { get; };
00055     }
00056
00057     runtimeclass Contact
00058     {
00059         String Id{ get; };
00060         String Initials { get; };
00061         String Name { get; };
00062         String LastName { get; };
00063         String FirstName { get; };
00064         String Position { get; };
00065         String PhoneNumber { get; };
00066         String Biography { get; };
00067     }
00068
00069     runtimeclass GroupInfoList : [default]IVector<Object>
00070     {
00071         GroupInfoList();
00072         String Key;
00073     }
00074
00075     runtimeclass DetailsPage : Windows.UI.Xaml.Controls.Page
00076     {
00077         DetailsPage();
00078         Contact SelectedContact { get; };
00079     }
00080
00081     [default_interface]
00082     runtimeclass ImagePage : Windows.UI.Xaml.Controls.Page
00083     {
00084         ImagePage();
00085     }
00086
00087     runtimeclass Item
00088     {
00089         String Id { get; };
00090         Windows.UI.Xaml.Media.ImageSource ImageSource { get; };
00091     }
00092
00093     runtimeclass ListViewEdgeTappedEventArgs
00094     {
00095         Windows.UI.Xaml.Controls.ListViewItem Item { get; };
00096     }
00097
00098     runtimeclass EdgeTappedListView : Windows.UI.Xaml.Controls.ListView
00099     {
00100         EdgeTappedListView();
00101         Boolean IsItemLeftEdgeTapEnabled;
00102         Windows.UI.Xaml.Media.Brush LeftEdgeBrush;
00103         event Windows.Foundation.TypedEventHandler<EdgeTappedListView, ListViewEdgeTappedEventArgs> ItemLeftEdgeTapped;
00104     }
00105 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PdfDocument/cs/Scenario1_Render.xaml.cs Source File

  • PdfDocument
  • cs

Scenario1_Render.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Data.Pdf;
00015 using Windows.Foundation;
00016 using Windows.Storage;
00017 using Windows.Storage.Pickers;
00018 using Windows.Storage.Streams;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Media.Imaging;
00022
00023 namespace SDKTemplate
00024 {
00025     public sealed partial class Scenario1_Render : Page
00026     {
00027         private MainPage rootPage = MainPage.Current;
00028         private PdfDocument pdfDocument;
00029
00030         const int WrongPassword = unchecked((int)0x8007052b); // HRESULT_FROM_WIN32(ERROR_WRONG_PASSWORD)
00031         const int GenericFail = unchecked((int)0x80004005);   // E_FAIL
00032
00033         public Scenario1_Render()
00034         {
00035             this.InitializeComponent();
00036         }
00037
00038         private async void LoadDocument(object sender, RoutedEventArgs args)
00039         {
00040             LoadButton.IsEnabled = false;
00041
00042             pdfDocument = null;
00043             Output.Source = null;
00044             PageNumberBox.Text = "1";
00045             RenderingPanel.Visibility = Visibility.Collapsed;
00046
00047             var picker = new FileOpenPicker();
00048             picker.FileTypeFilter.Add(".pdf");
00049             StorageFile file = await picker.PickSingleFileAsync();
00050             if (file != null)
00051             {
00052                 ProgressControl.Visibility = Visibility.Visible;
00053                 try
00054                 {
00055                     pdfDocument = await PdfDocument.LoadFromFileAsync(file, PasswordBox.Password);
00056                 }
00057                 catch (Exception ex)
00058                 {
00059                     switch (ex.HResult)
00060                     {
00061                         case WrongPassword:
00062                             rootPage.NotifyUser("Document is password-protected and password is incorrect.", NotifyType.ErrorMessage);
00063                             break;
00064
00065                         case GenericFail:
00066                             rootPage.NotifyUser("Document is not a valid PDF.", NotifyType.ErrorMessage);
00067                             break;
00068
00069                         default:
00070                             // File I/O errors are reported as exceptions.
00071                             rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
00072                             break;
00073                     }
00074                 }
00075
00076                 if (pdfDocument != null)
00077                 {
00078                     RenderingPanel.Visibility = Visibility.Visible;
00079                     if (pdfDocument.IsPasswordProtected)
00080                     {
00081                         rootPage.NotifyUser("Document is password protected.", NotifyType.StatusMessage);
00082                     }
00083                     else
00084                     {
00085                         rootPage.NotifyUser("Document is not password protected.", NotifyType.StatusMessage);
00086                     }
00087                     PageCountText.Text = pdfDocument.PageCount.ToString();
00088                 }
00089                 ProgressControl.Visibility = Visibility.Collapsed;
00090             }
00091             LoadButton.IsEnabled = true;
00092         }
00093
00094         private async void ViewPage(object sender, RoutedEventArgs args)
00095         {
00096             rootPage.NotifyUser("", NotifyType.StatusMessage);
00097
00098             uint pageNumber;
00099             if (!uint.TryParse(PageNumberBox.Text, out pageNumber) || (pageNumber < 1) || (pageNumber > pdfDocument.PageCount))
00100             {
00101                 rootPage.NotifyUser("Invalid page number.", NotifyType.ErrorMessage);
00102                 return;
00103             }
00104
00105             Output.Source = null;
00106             ProgressControl.Visibility = Visibility.Visible;
00107
00108             // Convert from 1-based page number to 0-based page index.
00109             uint pageIndex = pageNumber - 1;
00110
00111             using (PdfPage page = pdfDocument.GetPage(pageIndex))
00112             {
00113                 var stream = new InMemoryRandomAccessStream();
00114                 switch (Options.SelectedIndex)
00115                 {
00116                     // View actual size.
00117                     case 0:
00118                         await page.RenderToStreamAsync(stream);
00119                         break;
00120
00121                     // View half size on beige background.
00122                     case 1:
00123                         var options1 = new PdfPageRenderOptions();
00124                         options1.BackgroundColor = Windows.UI.Colors.Beige;
00125                         options1.DestinationHeight = (uint)(page.Size.Height / 2);
00126                         options1.DestinationWidth = (uint)(page.Size.Width / 2);
00127                         await page.RenderToStreamAsync(stream, options1);
00128                         break;
00129
00130                     // Crop to center.
00131                     case 2:
00132                         var options2 = new PdfPageRenderOptions();
00133                         var rect = page.Dimensions.TrimBox;
00134                         options2.SourceRect = new Rect(rect.X + rect.Width / 4, rect.Y + rect.Height / 4, rect.Width / 2, rect.Height / 2);
00135                         await page.RenderToStreamAsync(stream, options2);
00136                         break;
00137                 }
00138                 BitmapImage src = new BitmapImage();
00139                 Output.Source = src;
00140                 await src.SetSourceAsync(stream);
00141             }
00142             ProgressControl.Visibility = Visibility.Collapsed;
00143         }
00144     }
00145 }
Generated on Fri Nov 15 2024 22:20:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_ParameterizedTemplate Member List

This is the complete list of members for Scenario3_ParameterizedTemplate, including all inherited members.
Display_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario3_ParameterizedTemplate
Scenario3_ParameterizedTemplate() | Scenario3_ParameterizedTemplate
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HotspotAuthentication/cs/ScenarioCommon.cs Source File

  • HotspotAuthentication
  • cs

ScenarioCommon.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using HotspotAuthenticationTask;
00013 using System;
00014 using Windows.ApplicationModel.Background;
00015 using Windows.UI.Core;
00016
00017 namespace SDKTemplate
00018 {
00019     // A delegate type for hooking up foreground authentication notifications.
00020     public class BackgroundAuthenticationCompletedEventArgs
00021     {
00022         public BackgroundAuthenticationCompletedEventArgs(Exception exception)
00023         {
00024             ExtendedError = exception;
00025         }
00026         public bool Succeeded => ExtendedError == null;
00027         public Exception ExtendedError { get; private set; }
00028     }
00029
00030     public delegate void BackgroundAuthenticationCompletedEventHandler(ScenarioCommon sender, BackgroundAuthenticationCompletedEventArgs e);
00031
00032     // Shared code for all scenario pages
00033     public class ScenarioCommon
00034     {
00035         public static ScenarioCommon Instance { get; } = new ScenarioCommon();
00036
00037         // The entry point name of the background task handler:
00038
00039         public const string BackgroundTaskEntryPoint = "HotspotAuthenticationTask.AuthenticationTask";
00040
00041         // The (arbitrarily chosen) name assigned to the background task:
00042         public const string BackgroundTaskName = "AuthenticationBackgroundTask";
00043
00044         // A delegate for subscribing for foreground authentication events
00045         public BackgroundAuthenticationCompletedEventHandler BackgroundAuthenticationCompleted;
00046
00047         // A pointer back to the main page.  This is needed to call methods in MainPage such as NotifyUser()
00048         MainPage rootPage = MainPage.Current;
00049
00050         // A flag to remember if a background task handler has been registered
00051         private bool HasRegisteredBackgroundTaskHandler = false;
00052
00053         /// <summary>
00054         /// Register completion handler for registered background task on application startup.
00055         /// </summary>
00056         /// <returns>True if a registerd task was found</returns>
00057         public bool RegisteredCompletionHandlerForBackgroundTask()
00058         {
00059             if (!HasRegisteredBackgroundTaskHandler)
00060             {
00061                 try
00062                 {
00063                     // Associate background task completed event handler with background task.
00064                     foreach (var cur in BackgroundTaskRegistration.AllTasks)
00065                     {
00066                         if (cur.Value.Name == BackgroundTaskName)
00067                         {
00068                             cur.Value.Completed += new BackgroundTaskCompletedEventHandler(OnBackgroundTaskCompleted);
00069                             HasRegisteredBackgroundTaskHandler = true;
00070                             break;
00071                         }
00072                     }
00073                 }
00074                 catch (Exception ex)
00075                 {
00076                     rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
00077                 }
00078             }
00079             return HasRegisteredBackgroundTaskHandler;
00080         }
00081
00082         /// <summary>
00083         /// Background task completion handler. When authenticating through the foreground app, this triggers the authentication flow if the app is currently running.
00084         /// </summary>
00085         /// <param name="sender"></param>
00086         /// <param name="e"></param>
00087         public void OnBackgroundTaskCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
00088         {
00089             if (sender.Name == BackgroundTaskName)
00090             {
00091                 Exception exception = null;
00092                 try
00093                 {
00094                     // If the background task threw an exception, re-raise it here so we can pass it to the event handler.
00095                     e.CheckResult();
00096                 }
00097                 catch (Exception ex)
00098                 {
00099                     exception = ex;
00100                 }
00101
00102                 if (!ConfigStore.AuthenticateThroughBackgroundTask)
00103                 {
00104                     BackgroundAuthenticationCompleted?.Invoke(this, new BackgroundAuthenticationCompletedEventArgs(null));
00105                 }
00106             }
00107         }
00108     }
00109 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAccountManagement/cpp/Scenario3_AAD.xaml.h Source File

  • WebAccountManagement
  • cpp

Scenario3_AAD.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario3_Aad.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     /// <summary>
00011     /// The third scenario. Covers getting an AAD account and getting a token using that account.
00012     /// </summary>
00013     [Windows::Foundation::Metadata::WebHostHidden]
00014     public ref class Scenario3_Aad sealed
00015     {
00016     public:
00017         Scenario3_Aad();
00018     protected:
00019         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs ^ e) override;
00020     private:
00021         MainPage^ rootPage;
00022         void Button_SignIn_Click(Platform::Object ^ sender, Windows::UI::Xaml::RoutedEventArgs ^ e);
00023         void Button_GetTokenSilently_Click(Platform::Object ^ sender, Windows::UI::Xaml::RoutedEventArgs ^ e);
00024         void Button_ManageAccounts_Click(Platform::Object ^ sender, Windows::UI::Xaml::RoutedEventArgs ^ e);
00025         void Button_Reset_Click(Platform::Object ^ sender, Windows::UI::Xaml::RoutedEventArgs ^ e);
00026         void InitalizeAccountsControlDialog();
00027         void CleanupAccountsControlDialog();
00028         void OnAccountCommandsRequested(Windows::UI::ApplicationSettings::AccountsSettingsPane^ sender, Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^ e);
00029         void GetProvidersAndAccounts();
00030         void AddWebAccountProvider(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs ^ e);
00031         void AddWebAccount(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs ^ e);
00032         void AddLinks(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs ^ e);
00033         void WebAccountProviderCommandInvoked(Windows::UI::ApplicationSettings::WebAccountProviderCommand^ command);
00034         void WebAccountCommandInvoked(Windows::UI::ApplicationSettings::WebAccountCommand ^ command, Windows::UI::ApplicationSettings::WebAccountInvokedArgs^ args);
00035         void PrivacyPolicyInvoked(Windows::UI::Popups::IUICommand^ command);
00036         void OtherLinkInvoked(Windows::UI::Popups::IUICommand ^ command);
00037         void AuthenticateWithRequestToken(Windows::Security::Credentials::WebAccountProvider ^ provider, Platform::String^ scope, Platform::String^ clientID);
00038         void AuthenticateWithRequestTokenSilent(Windows::Security::Credentials::WebAccountProvider ^ provider, Platform::String^ scope, Platform::String^ clientID, Windows::Security::Credentials::WebAccount^ account);
00039         void OutputTokenResult(Windows::Security::Authentication::Web::Core::WebTokenRequestResult ^ result);
00040         void SaveAccount(Windows::Security::Credentials::WebAccount ^ account);
00041         void LogoffAndRemoveAccount();
00042
00043         Platform::String^ MICROSOFT_PROVIDER_ID = "https://login.microsoft.com";
00044         Platform::String^ ORGANIZATION_AUTHORITY = "organizations";
00045         Platform::String^ AAD_SCOPE_REQUESTED = "";
00046         Platform::String^ AAD_CLIENT_ID = "c8542080-6873-47b5-bf71-d56378567ceb";
00047         Platform::String^ STORED_ACCOUNT_ID_KEY = "accountid";
00048         Windows::Security::Credentials::WebAccountProvider^ m_provider;
00049         Windows::Security::Credentials::WebAccount^ m_account;
00050         Windows::Foundation::EventRegistrationToken m_accountCommandsRequestedRegistrationToken;
00051     };
00052 }
Generated on Fri Nov 15 2024 22:21:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/xBindSampleModel/DOModel.cs Source File

  • XamlBind
  • cs
  • xBindSampleModel

DOModel.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.ComponentModel;
00004 using System.Linq;
00005 using System.Runtime.CompilerServices;
00006 using System.Text;
00007 using System.Threading.Tasks;
00008 using Windows.UI.Xaml;
00009
00010 namespace xBindSampleModel
00011 {
00012     public sealed class DOModel : DependencyObject
00013     {
00014         public DOModel()
00015         {
00016             YangObj = new YangContainer(this);
00017         }
00018
00019         public void UpdateValues()
00020         {
00021             this.IntPropertyDP++;
00022             YinPropertyDP = 65;
00023         }
00024
00025         public YangContainer YangObj
00026         {
00027             get;
00028             set;
00029         }
00030
00031         public int IntPropertyDP
00032         {
00033             get { return (int)GetValue(IntPropertyDPProperty); }
00034             set { SetValue(IntPropertyDPProperty, value); }
00035         }
00036         #region IntPropertyDP DP
00037         private const string IntPropertyDPName = "IntPropertyDP";
00038         private static readonly DependencyProperty _IntPropertyDPProperty =
00039             DependencyProperty.Register(IntPropertyDPName, typeof(int), typeof(DataModel), new PropertyMetadata(0));
00040         public static DependencyProperty IntPropertyDPProperty {  get { return _IntPropertyDPProperty; } }
00041         #endregion
00042
00043         public double YinPropertyDP
00044         {
00045             get { return (double)GetValue(YinPropertyDPProperty); }
00046             set { SetValue(YinPropertyDPProperty, value); }
00047         }
00048         #region YinPropertyDP DP
00049         private const string YinPropertyDPName = "YinPropertyDP";
00050         private static readonly DependencyProperty _YinPropertyDPProperty =
00051             DependencyProperty.Register(YinPropertyDPName, typeof(double), typeof(DataModel), new PropertyMetadata(0, YinCallback));
00052         public static DependencyProperty YinPropertyDPProperty { get { return _YinPropertyDPProperty; } }
00053         #endregion
00054
00055
00056         public static void YinCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
00057         {
00058             DOModel inst = d as DOModel;
00059             double value = (double)e.NewValue;
00060             if (inst.YangObj.Value != value)
00061             {
00062                 inst.YangObj.Value = value;
00063             }
00064         }
00065     }
00066
00067     public sealed class YangContainer : INotifyPropertyChanged
00068     {
00069         private DOModel _parent;
00070
00071         public YangContainer(DOModel parent)
00072         {
00073             _parent = parent;
00074         }
00075
00076         private double _value;
00077         public double Value
00078         {
00079             get { return _value; }
00080             set
00081             {
00082                 if (value != _value)
00083                 {
00084                     _value = value;
00085                     NotifyPropertyChanged();
00086                     _parent.YinPropertyDP = value;
00087                 }
00088             }
00089         }
00090
00091
00092         #region INPC
00093
00094         public event PropertyChangedEventHandler PropertyChanged;
00095
00096         private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
00097         {
00098             if (PropertyChanged != null)
00099             {
00100                 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
00101             }
00102         }
00103         #endregion
00104     }
00105 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DftEffect Member List

This is the complete list of members for DftEffect, including all inherited members.
Create(_Outptr_ IUnknown **ppEffectImpl) | DftEffect | [static]
DftEffect() | DftEffect | [private]
IFACEMETHODIMP_(ULONG) AddRef() | DftEffect |
IFACEMETHODIMP_(ULONG) Release() | DftEffect |
Initialize(_In_ ID2D1EffectContext *pEffectContext, _In_ ID2D1TransformGraph *pTransformGraph) | DftEffect |
m_cRef | DftEffect | [private]
PrepareForRender(D2D1_CHANGE_TYPE changeType) | DftEffect |
QueryInterface(REFIID riid, _Outptr_ void **ppOutput) | DftEffect |
Register(_In_ ID2D1Factory1 *pFactory) | DftEffect | [static]
SetGraph(_In_ ID2D1TransformGraph *pTransformGraph) | DftEffect |
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AppView Member List

This is the complete list of members for AppView, including all inherited members.
AppView(Uri sourceUri) | AppView | [inline]
AppView_Consolidated(ApplicationView sender, ApplicationViewConsolidatedEventArgs args) | AppView | [inline, private]
appViewConsolidated | AppView | [private]
createdShaders | AppView | [private]
createShaders | AppView | [private]
deviceResources | AppView | [private]
Dispose() | AppView | [inline]
holographicSpace | AppView | [private]
Initialize(CoreApplicationView applicationView) | AppView | [inline]
Load(string entryPoint) | AppView | [inline]
main | AppView | [private]
mainWindowReactivated | AppView | [private]
mediaPlayer | AppView | [static]
MediaPlayer_MediaOpened(MediaPlayer sender, object args) | AppView | [inline, private]
OnKeyPressed(CoreWindow sender, KeyEventArgs args) | AppView | [inline, private]
OnmainWindowActivated(CoreWindow sender, WindowActivatedEventArgs args) | AppView | [inline, private]
OnResuming(object sender, object args) | AppView | [inline, private]
OnSuspending(object sender, SuspendingEventArgs args) | AppView | [inline, private]
OnViewActivated(CoreApplicationView sender, IActivatedEventArgs args) | AppView | [inline, private]
OnVisibilityChanged(CoreWindow sender, VisibilityChangedEventArgs args) | AppView | [inline, private]
OnWindowClosed(CoreWindow sender, CoreWindowEventArgs arg) | AppView | [inline, private]
Run() | AppView | [inline]
SetWindow(CoreWindow window) | AppView | [inline]
sourceUri | AppView | [private]
TryCloseWindow() | AppView | [inline, private]
Uninitialize() | AppView | [inline]
windowClosed | AppView | [private]
windowVisible | AppView | [private]
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario08_PostCustomContent Member List

This is the complete list of members for Scenario08_PostCustomContent, including all inherited members.
Cancel_Click(object sender, RoutedEventArgs e) | Scenario08_PostCustomContent | [inline, private]
cts | Scenario08_PostCustomContent | [private]
httpClient | Scenario08_PostCustomContent | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario08_PostCustomContent | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario08_PostCustomContent | [inline, protected]
rootPage | Scenario08_PostCustomContent | [private]
Scenario08_PostCustomContent() | Scenario08_PostCustomContent | [inline]
Start_Click(object sender, RoutedEventArgs e) | Scenario08_PostCustomContent | [inline, private]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RelayCommand Member List

This is the complete list of members for RelayCommand, including all inherited members.
canExecute | RelayCommand | [private]
CanExecute(object parameter) | RelayCommand | [inline]
CanExecuteChanged | RelayCommand |
Execute(object parameter) | RelayCommand | [inline]
execute | RelayCommand | [private]
RelayCommand(Action< object > execute) | RelayCommand | [inline]
RelayCommand(Action< object > execute, Predicate< object > canExecute) | RelayCommand | [inline]
Generated on Fri Nov 15 2024 22:23:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DirectXApplicationSource Member List

This is the complete list of members for DirectXApplicationSource, including all inherited members.
CreateView() DirectXApplicationSource [virtual]
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/Renderers/InkRenderer.cpp Source File

  • ComplexInk
  • cpp
  • Renderers

InkRenderer.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "InkRenderer.h"
00005
00006 using namespace SDKTemplate;
00007 using namespace Microsoft::WRL;
00008 using namespace Windows::Foundation::Numerics;
00009
00010 InkRenderer::InkRenderer()
00011 {
00012     _strokeContainer = ref new Windows::UI::Input::Inking::InkStrokeContainer();
00013
00014     _selectionRect = Windows::Foundation::Rect::Empty;
00015
00016     CoCreateInstance(__uuidof(InkD2DRenderer),
00017         nullptr,
00018         CLSCTX_INPROC_SERVER,
00019         IID_PPV_ARGS(&_spInkD2DRenderer));
00020 }
00021
00022 void InkRenderer::Clear()
00023 {
00024     if (_strokeContainer != nullptr)
00025     {
00026         _strokeContainer->Clear();
00027     }
00028     _selectionRect = Windows::Foundation::Rect::Empty;
00029 }
00030
00031 void InkRenderer::DrawSelectionRect(Microsoft::WRL::ComPtr<ID2D1DeviceContext> d2dContext, Microsoft::WRL::ComPtr<ID2D1Factory> d2dFactory)
00032 {
00033     if (!_selectionRect.IsEmpty  &&
00034         _selectionRect.Bottom > _selectionRect.Top &&
00035         _selectionRect.Right > _selectionRect.Left &&
00036         d2dContext != nullptr)
00037     {
00038         Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> shapeBrush;
00039         DX::ThrowIfFailed(d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Blue, 0.2f), &shapeBrush));
00040
00041         D2D1_RECT_F rectangle = D2D1::RectF(_selectionRect.Left, _selectionRect.Top, _selectionRect.Right, _selectionRect.Bottom);
00042         d2dContext->FillRectangle(&rectangle, shapeBrush.Get());
00043
00044         shapeBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Black, 0.5f));
00045         d2dContext->DrawRectangle(&rectangle, shapeBrush.Get());
00046     }
00047 }
00048
00049 void InkRenderer::Render(Platform::Collections::Vector<Windows::UI::Input::Inking::InkStroke^>^ strokes,
00050                          Microsoft::WRL::ComPtr<ID2D1DeviceContext> d2dContext)
00051 {
00052     HRESULT hr = S_OK;
00053     if (_spInkD2DRenderer != nullptr)
00054     {
00055         if (strokes != nullptr && strokes->Size > 0)
00056         {
00057             // Cast the stroke collection into IUnknown to call the Inkd2dRenderer
00058             ComPtr<IUnknown> spUnkStrokes = reinterpret_cast<IUnknown*>(reinterpret_cast<__abi_IUnknown*>(strokes));
00059             hr = _spInkD2DRenderer->Draw(d2dContext.Get(), spUnkStrokes.Get(), false);
00060             if (FAILED(hr))
00061             {
00062                 DX::ThrowIfFailed(hr);
00063             }
00064         }
00065     }
00066 }
00067
00068
00069 void InkRenderer::Select(Windows::Foundation::Collections::IVector<Windows::Foundation::Point>^ selectionPoints)
00070 {
00071     if (selectionPoints != nullptr && _strokeContainer != nullptr)
00072     {
00073         _selectionRect = _strokeContainer->SelectWithPolyLine(selectionPoints);
00074
00075         if (_StrokeContainerForTemp == nullptr && !IsEmptyRect(_selectionRect))
00076         {
00077             // Create a stroke container to hold the temporarily created strokes for selection hollow effect
00078             _StrokeContainerForTemp = ref new Windows::UI::Input::Inking::InkStrokeContainer();
00079         }
00080     }
00081 }
00082
00083 void InkRenderer::UnselectAll()
00084 {
00085     if (_strokeContainer != nullptr)
00086     {
00087         Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ inkStrokes = _strokeContainer->GetStrokes();
00088         for (unsigned int i = 0; i < inkStrokes->Size; i++)
00089         {
00090             inkStrokes->GetAt(i)->Selected = false;
00091         }
00092     }
00093     _selectionRect = Windows::Foundation::Rect::Empty;
00094 }
00095
00096 bool InkRenderer::HasStrokesToErase(Windows::Foundation::Point prevPt, Windows::Foundation::Point currPt)
00097 {
00098     Windows::Foundation::Rect updateRect = Windows::Foundation::Rect::Empty;
00099     if (_strokeContainer != nullptr)
00100     {
00101         updateRect = _strokeContainer->SelectWithLine(prevPt, currPt);
00102     }
00103
00104     return !IsEmptyRect(updateRect);
00105 }
00106
00107 Windows::Foundation::Rect InkRenderer::DeleteSelectedStrokes()
00108 {
00109     Windows::Foundation::Rect updateRect = Windows::Foundation::Rect::Empty;
00110     if (_strokeContainer != nullptr)
00111     {
00112         updateRect = _strokeContainer->DeleteSelected();
00113     }
00114
00115     return updateRect;
00116 }
00117
00118 Platform::Collections::Vector<Windows::UI::Input::Inking::InkStroke^>^ InkRenderer::GetSelectedStrokes()
00119 {
00120     Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ strokesInContainer = _strokeContainer->GetStrokes();
00121     Platform::Collections::Vector<Windows::UI::Input::Inking::InkStroke^>^ strokes = ref new Platform::Collections::Vector<Windows::UI::Input::Inking::InkStroke^>();
00122     for (unsigned int index = 0; index < strokesInContainer->Size; index++)
00123     {
00124         if (strokesInContainer->GetAt(index)->Selected)
00125         {
00126             strokes->Append(strokesInContainer->GetAt(index));
00127         }
00128     }
00129     return strokes;
00130 }
00131
00132 void InkRenderer::Update(Windows::UI::Input::Inking::InkStroke^ stroke)
00133 {
00134     if (stroke != nullptr && _strokeContainer != nullptr)
00135     {
00136         _strokeContainer->AddStroke(stroke);
00137     }
00138 }
00139
00140 void InkRenderer::UpdateSelectionRectangle(Windows::Foundation::Rect newSelectionRect)
00141 {
00142     _selectionRect = newSelectionRect;
00143 }
Generated on Fri Nov 15 2024 22:18:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LocationTrackingReason Member List

This is the complete list of members for LocationTrackingReason, including all inherited members.
BeginExtendedExecution() | LocationTrackingReason | [inline, private]
ClearExtendedExecution() | LocationTrackingReason | [inline, private]
EndExtendedExecution() | LocationTrackingReason | [inline, private]
LocationTrackingReason() | LocationTrackingReason | [inline]
OnNavigatingFrom(NavigatingCancelEventArgs e) | LocationTrackingReason | [inline, protected]
OnTimer(object state) | LocationTrackingReason | [inline, private]
periodicTimer | LocationTrackingReason | [private]
rootPage | LocationTrackingReason | [private]
session | LocationTrackingReason | [private]
SessionRevoked(object sender, ExtendedExecutionRevokedEventArgs args) | LocationTrackingReason | [inline, private]
StartLocationTrackingAsync() | LocationTrackingReason | [inline, private]
UpdateUI() | LocationTrackingReason | [inline, private]
Generated on Fri Nov 15 2024 22:23:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/Common/BasicReaderWriter.h Source File

  • Simple3DGameXaml
  • cpp
  • Common

BasicReaderWriter.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include <ppltasks.h>
00011
00012 // A simple reader/writer class that provides support for reading and writing
00013 // files on disk. Provides synchronous and asynchronous methods.
00014 ref class BasicReaderWriter
00015 {
00016 private:
00017     Windows::Storage::StorageFolder^ m_location;
00018
00019 internal:
00020     BasicReaderWriter();
00021     BasicReaderWriter(
00022         _In_ Windows::Storage::StorageFolder^ folder
00023         );
00024
00025     Platform::Array<byte>^ ReadData(
00026         _In_ Platform::String^ filename
00027         );
00028
00029     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00030         _In_ Platform::String^ filename
00031         );
00032
00033     uint32 WriteData(
00034         _In_ Platform::String^ filename,
00035         _In_ const Platform::Array<byte>^ fileData
00036         );
00037
00038     concurrency::task<void> WriteDataAsync(
00039         _In_ Platform::String^ filename,
00040         _In_ const Platform::Array<byte>^ fileData
00041         );
00042 };
Generated on Fri Nov 15 2024 22:19:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario10 Member List

This is the complete list of members for Scenario10, including all inherited members.
DeleteFileButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario10
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario10
Scenario10() | Scenario10
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SmartCardListItem Member List

This is the complete list of members for SmartCardListItem, including all inherited members.
CardName() | SmartCardListItem | [inline]
m_cardName | SmartCardListItem | [private]
m_readerName | SmartCardListItem | [private]
ReaderName() | SmartCardListItem | [inline]
SmartCardListItem(hstring const &readerName, hstring const &cardName) | SmartCardListItem | [inline]
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisplayOrientation/cppwinrt/SampleConfiguration.cpp Source File

  • DisplayOrientation
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation::Collections;
00019 using namespace winrt::SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"Display Orientation C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Show and lock orientation", xaml_typename<SDKTemplate::Scenario1_Orientation>() },
00029 });
Generated on Fri Nov 15 2024 22:17:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisablingScreenCapture/cppwinrt/Scenario1_Enable.h Source File

  • DisablingScreenCapture
  • cppwinrt

Scenario1_Enable.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Enable.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_Enable : Scenario1_EnableT<Scenario1_Enable>
00019     {
00020         Scenario1_Enable();
00021     };
00022 }
00023
00024 namespace winrt::SDKTemplate::factory_implementation
00025 {
00026     struct Scenario1_Enable : Scenario1_EnableT<Scenario1_Enable, implementation::Scenario1_Enable>
00027     {
00028     };
00029 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/MyUserControl1.xaml.h Source File

  • XamlBind
  • cpp

MyUserControl1.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // MyUserControl1.xaml.h
00003 // Declaration of the MyUserControl1 class
00004 //
00005
00006 #pragma once
00007
00008 #include "MyUserControl1.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     [Windows::Foundation::Metadata::WebHostHidden]
00013     public ref class MyUserControl1 sealed : Windows::UI::Xaml::Data::INotifyPropertyChanged
00014     {
00015     public:
00016         MyUserControl1();
00017
00018         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
00019
00020         property Platform::String^ NonDPProperty
00021         {
00022             Platform::String^ get()
00023             {
00024                 return _nonDPProperty;
00025             }
00026             void set(Platform::String^ value)
00027             {
00028                 if (NonDPProperty != value)
00029                 {
00030                     _nonDPProperty = value;
00031                     PropertyChanged(this, ref new Windows::UI::Xaml::Data::PropertyChangedEventArgs("NonDPProperty"));
00032                 }
00033             }
00034         }
00035
00036     private:
00037         Platform::String^ _nonDPProperty;
00038     };
00039 }
Generated on Fri Nov 15 2024 22:22:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BaseControl Member List

This is the complete list of members for BaseControl, including all inherited members.
AllocateTexture() | BaseControl | [private]
ApplyPixelShader() | BaseControl | [private]
ApplyShaders() | BaseControl |
BaseControl(const std::shared_ptr< DX::MeshGeometry > geometry=MeshGeometry::MakeTexturedCube()) | BaseControl |
CalculateInitialSize() | BaseControl | [private, virtual]
Initialize() | BaseControl |
InitializeFocusPoint() | BaseControl | [private]
IsFocused() | BaseControl | [inline]
IsFocusOnControl(const DirectX::XMMATRIX &transform, Windows::UI::Input::Spatial::SpatialPointerPose^cameraPose) | BaseControl | [private]
m_calculateTextureDimensionsFromScale | BaseControl | [private]
m_d2dContextTargetToRestore | BaseControl | [private]
m_deviceResources | BaseControl | [private]
m_focusPointConstantBuffer | BaseControl | [private]
m_focusPointConstantBufferData | BaseControl | [private]
m_geometry | BaseControl | [private]
m_geometryShader | BaseControl | [private]
m_inputLayout | BaseControl | [private]
m_isFocused | BaseControl | [private]
m_isInitialized | BaseControl | [private]
m_isUITextureRenderNeeded | BaseControl | [private]
m_isVisible | BaseControl | [private]
m_modelConstantBuffer | BaseControl | [private]
m_modelConstantBufferData | BaseControl | [private]
m_parentTransform | BaseControl | [private]
m_pixelShader | BaseControl | [private]
m_position | BaseControl | [private]
m_relativeIntersectionPoint | BaseControl | [private]
m_renderItem | BaseControl | [private]
m_rotation | BaseControl | [private]
m_sampler | BaseControl | [private]
m_scale | BaseControl | [private]
m_snapSizeToRootElement | BaseControl | [private]
m_stateBlock | BaseControl | [private]
m_texture | BaseControl | [private]
m_textureHeight | BaseControl | [private]
m_textureShaderResourceView | BaseControl | [private]
m_textureTarget | BaseControl | [private]
m_textureWidth | BaseControl | [private]
m_transform | BaseControl | [private]
m_vertexShader | BaseControl | [private]
PerformPressedAction() | BaseControl |
Render() | BaseControl |
SetIsVisible(bool value) | BaseControl |
SetParentTransform(Windows::Foundation::Numerics::float4x4 transform) | BaseControl |
SetPosition(Windows::Foundation::Numerics::float3 value) | BaseControl |
SetRenderElement(std::shared_ptr< DX::FocusableElement > renderItem) | BaseControl |
SetScale(Windows::Foundation::Numerics::float3 value) | BaseControl |
SetTextureHeight(UINT height) | BaseControl | [inline]
SetTextureWidth(UINT width) | BaseControl | [inline]
SnapInitialSizeToRootElement() | BaseControl |
Update(const DX::StepTimer &timer, Windows::UI::Input::Spatial::SpatialPointerPose^cameraPose) | BaseControl |
UploadGeometryAndShaders() | BaseControl | [private]
Generated on Fri Nov 15 2024 22:23:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OrientationSensor/cs/Scenario1_DataEvents.xaml.cs Source File

  • OrientationSensor
  • cs

Scenario1_DataEvents.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Devices.Sensors;
00014 using Windows.Foundation;
00015 using Windows.UI.Core;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario1_DataEvents : Page
00023     {
00024         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00025         // as NotifyUser()
00026         MainPage rootPage = MainPage.Current;
00027
00028         private OrientationSensor _sensor;
00029
00030         public Scenario1_DataEvents()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         protected override void OnNavigatedTo(NavigationEventArgs e)
00036         {
00037             _sensor = OrientationSensor.GetDefault(rootPage.SensorReadingType, rootPage.SensorOptimizationGoal);
00038             if (_sensor != null)
00039             {
00040                 rootPage.NotifyUser(rootPage.SensorDescription + " is ready", NotifyType.StatusMessage);
00041                 ScenarioEnableButton.IsEnabled = true;
00042             }
00043             else
00044             {
00045                 rootPage.NotifyUser(rootPage.SensorDescription + " not found", NotifyType.ErrorMessage);
00046             }
00047         }
00048
00049         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00050         {
00051             if (ScenarioDisableButton.IsEnabled)
00052             {
00053                 ScenarioDisable();
00054             }
00055         }
00056
00057         /// <summary>
00058         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00059         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00060         /// </summary>
00061         /// <param name="sender"></param>
00062         /// <param name="e">
00063         /// Event data that can be examined for the current visibility state.
00064         /// </param>
00065         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00066         {
00067             if (ScenarioDisableButton.IsEnabled)
00068             {
00069                 if (e.Visible)
00070                 {
00071                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00072                     _sensor.ReadingChanged += ReadingChanged;
00073                 }
00074                 else
00075                 {
00076                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00077                     _sensor.ReadingChanged -= ReadingChanged;
00078                 }
00079             }
00080         }
00081
00082         /// <summary>
00083         /// This is the event handler for ReadingChanged events.
00084         /// </summary>
00085         /// <param name="sender"></param>
00086         /// <param name="e"></param>
00087         async private void ReadingChanged(object sender, OrientationSensorReadingChangedEventArgs e)
00088         {
00089             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00090             {
00091                 MainPage.SetReadingText(ScenarioOutput, e.Reading);
00092             });
00093         }
00094
00095         /// <summary>
00096         /// This is the click handler for the 'Enable' button.
00097         /// </summary>
00098         private void ScenarioEnable()
00099         {
00100             // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00101             _sensor.ReportInterval = Math.Max(_sensor.MinimumReportInterval, 16);
00102
00103             Window.Current.VisibilityChanged += VisibilityChanged;
00104             _sensor.ReadingChanged += ReadingChanged;
00105
00106             ScenarioEnableButton.IsEnabled = false;
00107             ScenarioDisableButton.IsEnabled = true;
00108         }
00109
00110         /// <summary>
00111         /// This is the click handler for the 'Disable' button.
00112         /// </summary>
00113         private void ScenarioDisable()
00114         {
00115             Window.Current.VisibilityChanged -= VisibilityChanged;
00116             _sensor.ReadingChanged -= ReadingChanged;
00117
00118             // Restore the default report interval to release resources while the sensor is not in use
00119             _sensor.ReportInterval = 0;
00120
00121             ScenarioEnableButton.IsEnabled = true;
00122             ScenarioDisableButton.IsEnabled = false;
00123         }
00124     }
00125 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/DeviceWatcherHelper.cpp Source File

  • DeviceEnumerationAndPairing
  • cpp

DeviceWatcherHelper.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "DeviceWatcherHelper.h"
00005 #include "MainPage.xaml.h"
00006
00007 using namespace SDKTemplate;
00008 using namespace Platform;
00009 using namespace Windows::Foundation;
00010 using namespace Windows::UI::Core;
00011 using namespace Windows::Devices::Enumeration;
00012
00013 void DeviceWatcherHelper::StartWatcher(DeviceWatcher^ deviceWatcherArg)
00014 {
00015     deviceWatcher = deviceWatcherArg;
00016
00017     // Connect events to update our collection as the watcher report results.
00018     deviceWatcher->Added += ref new TypedEventHandler<DeviceWatcher^, DeviceInformation^>(this, &DeviceWatcherHelper::Watcher_DeviceAdded);
00019     deviceWatcher->Updated += ref new TypedEventHandler<DeviceWatcher^, DeviceInformationUpdate^>(this, &DeviceWatcherHelper::Watcher_DeviceUpdated);
00020     deviceWatcher->Removed += ref new TypedEventHandler<DeviceWatcher^, DeviceInformationUpdate^>(this, &DeviceWatcherHelper::Watcher_DeviceRemoved);
00021     deviceWatcher->EnumerationCompleted += ref new TypedEventHandler<DeviceWatcher^, Object^>(this, &DeviceWatcherHelper::Watcher_EnumerationCompleted);
00022     deviceWatcher->Stopped += ref new TypedEventHandler<DeviceWatcher^, Object^>(this, &DeviceWatcherHelper::Watcher_Stopped);
00023
00024     deviceWatcher->Start();
00025 }
00026
00027 void DeviceWatcherHelper::StopWatcher()
00028 {
00029     // Since the device watcher runs in the background, it is possible that
00030     // a notification is "in flight" at the time we stop the watcher.
00031     // In other words, it is possible for the watcher to become stopped while a
00032     // handler is running, or for a handler to run after the watcher has stopped.
00033
00034     if (IsWatcherStarted(deviceWatcher))
00035     {
00036         // We do not null out the deviceWatcher yet because we want to receive
00037         // the Stopped event.
00038         deviceWatcher->Stop();
00039     }
00040 }
00041
00042 void DeviceWatcherHelper::Reset()
00043 {
00044     if (deviceWatcher != nullptr)
00045     {
00046         StopWatcher();
00047         deviceWatcher = nullptr;
00048     }
00049 }
00050
00051 bool DeviceWatcherHelper::IsWatcherStarted(DeviceWatcher^ watcher)
00052 {
00053     DeviceWatcherStatus status = watcher->Status;
00054     return (status == DeviceWatcherStatus::Started) ||
00055         (status == DeviceWatcherStatus::EnumerationCompleted);
00056 }
00057
00058 bool DeviceWatcherHelper::IsWatcherRunning()
00059 {
00060     if (deviceWatcher == nullptr)
00061     {
00062         return false;
00063     }
00064
00065     DeviceWatcherStatus status = deviceWatcher->Status;
00066     return (status == DeviceWatcherStatus::Started) ||
00067         (status == DeviceWatcherStatus::EnumerationCompleted) ||
00068         (status == DeviceWatcherStatus::Stopping);
00069 }
00070
00071 void DeviceWatcherHelper::Watcher_DeviceAdded(DeviceWatcher^ sender, DeviceInformation^ deviceInfo)
00072 {
00073     // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
00074     dispatcher->RunAsync(CoreDispatcherPriority::Low, ref new DispatchedHandler(
00075         [this, sender, deviceInfo]()
00076     {
00077         // Watcher may have stopped while we were waiting for our chance to run.
00078         if (IsWatcherStarted(sender))
00079         {
00080             resultCollection->Append(ref new DeviceInformationDisplay(deviceInfo));
00081             RaiseDeviceChanged(sender, deviceInfo->Id);
00082         }
00083     }));
00084 }
00085
00086 void DeviceWatcherHelper::Watcher_DeviceUpdated(DeviceWatcher^ sender, DeviceInformationUpdate^ deviceInfoUpdate)
00087 {
00088     // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
00089     dispatcher->RunAsync(CoreDispatcherPriority::Low, ref new DispatchedHandler(
00090         [this, sender, deviceInfoUpdate]()
00091     {
00092         // Watcher may have stopped while we were waiting for our chance to run.
00093         if (IsWatcherStarted(sender))
00094         {
00095             // Find the corresponding updated DeviceInformation in the collection and pass the update object
00096             // to the Update method of the existing DeviceInformation. This automatically updates the object
00097             // for us.
00098             auto foundDeviceInfo = std::find_if(begin(resultCollection), end(resultCollection), [&](DeviceInformationDisplay^ di) { return (di->Id == deviceInfoUpdate->Id); });
00099
00100             if (foundDeviceInfo != end(resultCollection))
00101             {
00102                 (*foundDeviceInfo)->Update(deviceInfoUpdate);
00103                 RaiseDeviceChanged(sender, deviceInfoUpdate->Id);
00104             }
00105         }
00106     }));
00107 }
00108
00109 void DeviceWatcherHelper::Watcher_DeviceRemoved(DeviceWatcher^ sender, DeviceInformationUpdate^ deviceInfoUpdate)
00110 {
00111     // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
00112     dispatcher->RunAsync(CoreDispatcherPriority::Low, ref new DispatchedHandler(
00113         [this, sender, deviceInfoUpdate]()
00114     {
00115         // Watcher may have stopped while we were waiting for our chance to run.
00116         if (IsWatcherStarted(sender))
00117         {
00118             // Find the corresponding DeviceInformation in the collection and remove it
00119             auto foundDeviceInfo = std::find_if(begin(resultCollection), end(resultCollection), [&](DeviceInformationDisplay^ di) {return (di->Id == deviceInfoUpdate->Id); });
00120
00121             uint32 index = 0;
00122             if (foundDeviceInfo != end(resultCollection) &&
00123                 resultCollection->IndexOf(*foundDeviceInfo, &index))
00124             {
00125                 resultCollection->RemoveAt(index);
00126             }
00127
00128             RaiseDeviceChanged(sender, deviceInfoUpdate->Id);
00129         }
00130     }));
00131 }
00132
00133 void DeviceWatcherHelper::Watcher_EnumerationCompleted(DeviceWatcher^ sender, Object^ e)
00134 {
00135     dispatcher->RunAsync(CoreDispatcherPriority::Low, ref new DispatchedHandler(
00136         [this, sender]()
00137     {
00138         RaiseDeviceChanged(sender, nullptr);
00139     }));
00140 }
00141
00142 void DeviceWatcherHelper::Watcher_Stopped(DeviceWatcher^ sender, Object^ e)
00143 {
00144     dispatcher->RunAsync(CoreDispatcherPriority::Low, ref new DispatchedHandler(
00145         [this, sender]()
00146     {
00147         RaiseDeviceChanged(sender, nullptr);
00148     }));
00149 }
00150
00151 void DeviceWatcherHelper::RaiseDeviceChanged(DeviceWatcher^ sender, String^ id)
00152 {
00153     if (UpdateStatus)
00154     {
00155         // Display a default status message.
00156         String^ message = resultCollection->Size.ToString() + " devices found.";
00157         switch (sender->Status)
00158         {
00159         case DeviceWatcherStatus::Started:
00160             break;
00161
00162         case DeviceWatcherStatus::EnumerationCompleted:
00163             message = message + " Enumeration completed. Watching for updates...";
00164             break;
00165
00166         case DeviceWatcherStatus::Stopped:
00167             message = message + " Watcher stopped.";
00168             break;
00169
00170         case DeviceWatcherStatus::Aborted:
00171             message = message + " Watcher aborted.";
00172             break;
00173         }
00174
00175         MainPage::Current->NotifyUser(message, NotifyType::StatusMessage);
00176     }
00177
00178     DeviceChanged(sender, id);
00179 }
00180
Generated on Fri Nov 15 2024 22:19:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaEditing/cpp/Scenario3_AddAudioTracks.xaml.h Source File

  • MediaEditing
  • cpp

Scenario3_AddAudioTracks.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_AddAudioTracks.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario3_AddAudioTracks sealed
00024     {
00025     public:
00026         Scenario3_AddAudioTracks();
00027
00028     protected:
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         SDKTemplate::MainPage^ rootPage;
00033         Windows::Media::Editing::MediaComposition^ composition;
00034         Windows::Storage::StorageFile^ pickedFile;
00035         Windows::Media::Core::MediaStreamSource^ mediaStreamSource;
00036
00037         void ChooseVideo_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         void AddAudio_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039     };
00040 }
Generated on Fri Nov 15 2024 22:20:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_NetworkConnectivity Member List

This is the complete list of members for Scenario1_NetworkConnectivity, including all inherited members.
QueryCurrentNetworkConnectivityButton_Click(object sender, RoutedEventArgs e) | Scenario1_NetworkConnectivity | [inline, private]
Scenario1_NetworkConnectivity() | Scenario1_NetworkConnectivity | [inline]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

OpenCloseConnectionScenario Member List

This is the complete list of members for OpenCloseConnectionScenario, including all inherited members.
GenerateRandomNumber_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | OpenCloseConnectionScenario
OpenCloseConnectionScenario() | OpenCloseConnectionScenario
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_BackgroundProximitySensor Member List

This is the complete list of members for Scenario4_BackgroundProximitySensor, including all inherited members.
OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) | Scenario4_BackgroundProximitySensor | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario4_BackgroundProximitySensor | [inline, protected]
OnProximitySensorAdded(DeviceWatcher sender, DeviceInformation device) | Scenario4_BackgroundProximitySensor | [inline, private]
RegisterBackgroundTask() | Scenario4_BackgroundProximitySensor | [inline, private]
registered | Scenario4_BackgroundProximitySensor | [private]
rootPage | Scenario4_BackgroundProximitySensor | [private]
SampleBackgroundTaskEntryPoint | Scenario4_BackgroundProximitySensor |
SampleBackgroundTaskName | Scenario4_BackgroundProximitySensor |
Scenario4_BackgroundProximitySensor() | Scenario4_BackgroundProximitySensor | [inline]
ScenarioRegisterTask_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario4_BackgroundProximitySensor | [inline, private]
ScenarioUnregisterTask_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario4_BackgroundProximitySensor | [inline, private]
sensor | Scenario4_BackgroundProximitySensor | [private]
UpdateUIAsync(string status) | Scenario4_BackgroundProximitySensor | [inline, private]
watcher | Scenario4_BackgroundProximitySensor | [private]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MicrosoftPassport/Server/Global.asax.cs Source File

  • MicrosoftPassport
  • Server

Global.asax.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 // Please refer to the Microsoft Passport and Windows Hello
00012 // whitepaper on the Windows Dev Center for a complete
00013 // explanation of Microsoft Passport and Windows Hello
00014 // implementation:
00015 // http://go.microsoft.com/fwlink/p/?LinkId=522066
00016 //*********************************************************
00017 using System.Web.Http;
00018 using System.Web.Mvc;
00019 using System.Web.Routing;
00020
00021 namespace MicrosoftPassport.Server
00022 {
00023     public class WebApiApplication : System.Web.HttpApplication
00024     {
00025         protected void Application_Start()
00026         {
00027             AreaRegistration.RegisterAllAreas();
00028             GlobalConfiguration.Configure(WebApiConfig.Register);
00029             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
00030             RouteConfig.RegisterRoutes(RouteTable.Routes);
00031         }
00032     }
00033 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/Common/CameraResources.h Source File

  • BasicHologram
  • cpp
  • Common

CameraResources.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 namespace DX
00004 {
00005     class DeviceResources;
00006
00007     // Constant buffer used to send the view-projection matrices to the shader pipeline.
00008     struct ViewProjectionConstantBuffer
00009     {
00010         DirectX::XMFLOAT4X4 viewProjection[2];
00011     };
00012
00013     // Assert that the constant buffer remains 16-byte aligned (best practice).
00014     static_assert((sizeof(ViewProjectionConstantBuffer) % (sizeof(float) * 4)) == 0, "ViewProjection constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00015
00016     // Manages DirectX device resources that are specific to a holographic camera, such as the
00017     // back buffer, ViewProjection constant buffer, and viewport.
00018     class CameraResources
00019     {
00020     public:
00021         CameraResources(Windows::Graphics::Holographic::HolographicCamera^ holographicCamera);
00022
00023         void CreateResourcesForBackBuffer(
00024             DX::DeviceResources* pDeviceResources,
00025             Windows::Graphics::Holographic::HolographicCameraRenderingParameters^ cameraParameters
00026             );
00027         void ReleaseResourcesForBackBuffer(
00028             DX::DeviceResources* pDeviceResources
00029             );
00030
00031         void UpdateViewProjectionBuffer(
00032             std::shared_ptr<DX::DeviceResources> deviceResources,
00033             Windows::Graphics::Holographic::HolographicCameraPose^ cameraPose,
00034             Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem);
00035
00036         bool AttachViewProjectionBuffer(
00037             std::shared_ptr<DX::DeviceResources> deviceResources);
00038
00039         // Direct3D device resources.
00040         ID3D11RenderTargetView* GetBackBufferRenderTargetView()     const { return m_d3dRenderTargetView.Get();     }
00041         ID3D11DepthStencilView* GetDepthStencilView()               const { return m_d3dDepthStencilView.Get();     }
00042         ID3D11Texture2D*        GetBackBufferTexture2D()            const { return m_d3dBackBuffer.Get();           }
00043         ID3D11Texture2D*        GetDepthStencilTexture2D()          const { return m_d3dDepthStencil.Get();         }
00044         D3D11_VIEWPORT          GetViewport()                       const { return m_d3dViewport;                   }
00045         DXGI_FORMAT             GetBackBufferDXGIFormat()           const { return m_dxgiFormat;                    }
00046
00047         // Render target properties.
00048         Windows::Foundation::Size GetRenderTargetSize()             const { return m_d3dRenderTargetSize;           }
00049         bool                    IsRenderingStereoscopic()           const { return m_isStereo;                      }
00050
00051         // The holographic camera these resources are for.
00052         Windows::Graphics::Holographic::HolographicCamera^ GetHolographicCamera() const { return m_holographicCamera; }
00053
00054     private:
00055         // Direct3D rendering objects. Required for 3D.
00056         Microsoft::WRL::ComPtr<ID3D11RenderTargetView>      m_d3dRenderTargetView;
00057         Microsoft::WRL::ComPtr<ID3D11DepthStencilView>      m_d3dDepthStencilView;
00058         Microsoft::WRL::ComPtr<ID3D11Texture2D>             m_d3dBackBuffer;
00059         Microsoft::WRL::ComPtr<ID3D11Texture2D>             m_d3dDepthStencil;
00060
00061         // Device resource to store view and projection matrices.
00062         Microsoft::WRL::ComPtr<ID3D11Buffer>                m_viewProjectionConstantBuffer;
00063
00064         // Direct3D rendering properties.
00065         DXGI_FORMAT                                         m_dxgiFormat;
00066         Windows::Foundation::Size                           m_d3dRenderTargetSize;
00067         D3D11_VIEWPORT                                      m_d3dViewport;
00068
00069         // Indicates whether the camera supports stereoscopic rendering.
00070         bool                                                m_isStereo = false;
00071
00072         // Indicates whether this camera has a pending frame.
00073         bool                                                m_framePending = false;
00074
00075         // Pointer to the holographic camera these resources are for.
00076         Windows::Graphics::Holographic::HolographicCamera^  m_holographicCamera = nullptr;
00077     };
00078 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cs/Scenario12.xaml.cs Source File

  • MapControl
  • cs

Scenario12.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Devices.Geolocation;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Controls.Maps;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     public sealed partial class Scenario12 : Page
00024     {
00025         // The data source is contributed by Iowa Environmental Mesonet of Iowa State University.
00026         private string urlTemplate = "http://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-{timestamp}/{zoomlevel}/{x}/{y}.png";
00027         //The time stamps values for the IEM service for the last 50 minutes broken up into 5 minute increments.
00028         private string[] timestamps = { "900913-m50m", "900913-m45m", "900913-m40m", "900913-m35m", "900913-m30m", "900913-m25m", "900913-m20m", "900913-m15m", "900913-m10m", "900913-m05m", "900913" };
00029         private MapTileSource httpTileSource = null;
00030
00031         public Scenario12()
00032         {
00033             this.InitializeComponent();
00034         }
00035
00036         private void MyMapLoaded(object sender, RoutedEventArgs e)
00037         {
00038             myMap.Center = new Geopoint(new BasicGeoposition() { Latitude = 39.1887643719098, Longitude = -92.8261546188403 });
00039             myMap.ZoomLevel = 5;
00040         }
00041
00042         private void AddAnimatedTilesClick(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00043         {
00044             if (httpTileSource == null)
00045             {
00046                 var httpMapTileDataSource = new HttpMapTileDataSource();
00047                 httpMapTileDataSource.UriRequested += HttpMapTileDataSourceUriRequested;
00048                 httpTileSource = new MapTileSource()
00049                 {
00050                     DataSource = httpMapTileDataSource,
00051                     FrameCount = timestamps.Length,
00052                     FrameDuration = TimeSpan.FromMilliseconds(500),
00053                 };
00054
00055                 myMap.TileSources.Add(httpTileSource);
00056             }
00057         }
00058
00059         private void ClearMapClick(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00060         {
00061             myMap.TileSources.Clear();
00062             httpTileSource = null;
00063         }
00064
00065         private void HttpMapTileDataSourceUriRequested(HttpMapTileDataSource sender, MapTileUriRequestedEventArgs args)
00066         {
00067             args.Request.Uri = new Uri(urlTemplate.Replace("{timestamp}", timestamps[args.FrameIndex]));
00068         }
00069
00070         private void PlayAnimationTapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
00071         {
00072             if (httpTileSource != null)
00073             {
00074                 httpTileSource.Play();
00075             }
00076         }
00077
00078         private void PauseAnimationTapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
00079         {
00080             if (httpTileSource != null)
00081             {
00082                 httpTileSource.Pause();
00083             }
00084         }
00085
00086         private void StopAnimationTapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
00087         {
00088             if (httpTileSource != null)
00089             {
00090                 httpTileSource.Stop();
00091             }
00092         }
00093     }
00094 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: EnterpriseDataProtection/cs/Scenario10_CpToClipboard.xaml.cs Source File

  • EnterpriseDataProtection
  • cs

Scenario10_CpToClipboard.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using System.Threading.Tasks;
00017 using SDKTemplate;
00018 using Windows.Security.EnterpriseData;
00019
00020 namespace EdpSample
00021 {
00022     public sealed partial class Scenario10_CpToClipboard : Page
00023     {
00024         private MainPage rootPage;
00025
00026         public Scenario10_CpToClipboard()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         protected override void OnNavigatedTo(NavigationEventArgs e)
00032         {
00033             rootPage = MainPage.Current;
00034             InputTxtBox.Text = "Text here will be copied to clipboard";
00035         }
00036
00037         private void CopyToClipboard_Click(object sender, RoutedEventArgs e)
00038         {
00039             var dataPackage = new Windows.ApplicationModel.DataTransfer.DataPackage();
00040             dataPackage.SetText(InputTxtBox.Text);
00041             dataPackage.Properties.EnterpriseId = Scenario1.m_enterpriseId;
00042             Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage);
00043             if (dataPackage.Properties.EnterpriseId != Scenario1.m_enterpriseId)
00044             {
00045                 rootPage.NotifyUser("Failed to mark data package to EnterpiseId=" + Scenario1.m_enterpriseId, NotifyType.ErrorMessage);
00046             }
00047             else
00048             {
00049                 rootPage.NotifyUser("Successfully SetContent to clipboard using EnterpriseId=" + Scenario1.m_enterpriseId, NotifyType.StatusMessage);
00050             }
00051         }
00052     }
00053 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario08_PostCustomContent.cpp Source File

  • HttpClient
  • cppwinrt

Scenario08_PostCustomContent.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario08_PostCustomContent.h"
00014 #include "Scenario08_PostCustomContent.g.cpp"
00015 #include "Helpers.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Data::Json;
00019 using namespace winrt::Windows::Foundation;
00020 using namespace winrt::Windows::UI::Xaml;
00021 using namespace winrt::Windows::UI::Xaml::Navigation;
00022 using namespace winrt::Windows::Web::Http;
00023
00024 namespace winrt::SDKTemplate::implementation
00025 {
00026     Scenario08_PostCustomContent::Scenario08_PostCustomContent()
00027     {
00028         InitializeComponent();
00029     }
00030
00031     void Scenario08_PostCustomContent::OnNavigatedTo(NavigationEventArgs const&)
00032     {
00033         httpClient = Helpers::CreateHttpClientWithCustomHeaders();
00034     }
00035
00036     void Scenario08_PostCustomContent::OnNavigatedFrom(NavigationEventArgs const&)
00037     {
00038         httpClient.Close();
00039     }
00040
00041     fire_and_forget Scenario08_PostCustomContent::Start_Click(IInspectable const&, RoutedEventArgs const&)
00042     {
00043         auto lifetime = get_strong();
00044
00045         // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00046         // valid, absolute URI, we'll notify the user about the incorrect input.
00047         Uri resourceUri = Helpers::TryParseHttpUri(AddressField().Text());
00048         if (!resourceUri)
00049         {
00050             rootPage.NotifyUser(L"Invalid URI.", NotifyType::ErrorMessage);
00051             return;
00052         }
00053
00054         Helpers::ScenarioStarted(StartButton(), CancelButton(), OutputField());
00055         rootPage.NotifyUser(L"In progress", NotifyType::StatusMessage);
00056
00057         HttpJsonContent jsonContent(JsonValue::Parse(L"{\"score\": 100, \"enabled\": false}"));
00058
00059         // This sample uses a "try" in order to support cancellation.
00060         // If you don't need to support cancellation, then the "try" is not needed.
00061         try
00062         {
00063             pendingAction = CancelableRequestAsync(resourceUri, jsonContent);
00064             co_await pendingAction;
00065         }
00066         catch (hresult_canceled const&)
00067         {
00068             rootPage.NotifyUser(L"Request canceled.", NotifyType::ErrorMessage);
00069         }
00070
00071         Helpers::ScenarioCompleted(StartButton(), CancelButton());
00072     }
00073
00074     IAsyncAction Scenario08_PostCustomContent::CancelableRequestAsync(Uri resourceUri, IHttpContent content)
00075     {
00076         auto lifetime = get_strong();
00077         auto cancellation = co_await get_cancellation_token();
00078         cancellation.enable_propagation();
00079
00080         HttpRequestResult result = co_await httpClient.TryPostAsync(resourceUri, content);
00081
00082         if (result.Succeeded())
00083         {
00084             co_await Helpers::DisplayTextResultAsync(result.ResponseMessage(), OutputField());
00085
00086             rootPage.NotifyUser(L"Completed", NotifyType::StatusMessage);
00087         }
00088         else
00089         {
00090             Helpers::DisplayWebError(rootPage, result.ExtendedError());
00091         }
00092     }
00093
00094     void Scenario08_PostCustomContent::Cancel_Click(IInspectable const&, RoutedEventArgs const&)
00095     {
00096         if (pendingAction)
00097         {
00098             pendingAction.Cancel();
00099         }
00100     }
00101 }
Generated on Fri Nov 15 2024 22:19:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AnimateCirclePosition Member List

This is the complete list of members for AnimateCirclePosition, including all inherited members.
Animate() | Animate |
AnimateCirclePosition(_In_ DirectX::XMFLOAT3 center, _In_ DirectX::XMFLOAT3 startPosition, _In_ DirectX::XMFLOAT3 planeNormal, _In_ float duration, _In_ bool continuous, _In_ bool clockwise) | AnimateCirclePosition |
Continuous() | Animate |
Continuous(_In_ bool continuous) | Animate |
Duration() | Animate |
Duration(_In_ float duration) | Animate |
Evaluate(_In_ float t) override | AnimateCirclePosition | [virtual]
IsActive(_In_ float t) | Animate | [inline]
IsFinished(_In_ float t) | Animate | [inline]
m_center | AnimateCirclePosition | [private]
m_clockwise | AnimateCirclePosition | [private]
m_continuous | Animate | [protected]
m_duration | Animate | [protected]
m_planeNormal | AnimateCirclePosition | [private]
m_radius | AnimateCirclePosition | [private]
m_rotationMatrix | AnimateCirclePosition | [private]
m_startPosition | AnimateCirclePosition | [private]
m_startTime | Animate | [protected]
Start() | Animate |
Start(_In_ float start) | Animate |
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario Member List

This is the complete list of members for Scenario, including all inherited members.
_name | Scenario | [private]
Contains(Type scenarioType) | Scenario | [inline]
FindScenario(Type scenarioType) | Scenario | [inline]
Id | Scenario |
Name | Scenario |
OnPropertyChanged([CallerMemberName] string propertyName=null) | BindableBase | [inline, protected]
PropertyChanged | BindableBase |
Scenario(string name, Type uiElementType) | Scenario | [inline]
SetProperty< T >(ref T storage, T value,[CallerMemberName] String propertyName=null) | BindableBase | [inline, protected]
ToString() | Scenario | [inline]
UIElementType | Scenario |
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundMediaPlayback/cs/ViewModels/PlaybackStateToButtonIconConverter.cs Source File

  • BackgroundMediaPlayback
  • cs
  • ViewModels

PlaybackStateToButtonIconConverter.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Threading.Tasks;
00004 using Windows.Media.Playback;
00005 using Windows.UI.Xaml.Controls;
00006 using Windows.UI.Xaml.Data;
00007
00008 namespace BackgroundMediaPlayback.ViewModels
00009 {
00010     public class PlaybackStateToButtonIconConverter : IValueConverter
00011     {
00012         public object Convert(object value, Type targetType, object parameter, string language)
00013         {
00014             if (value is MediaPlaybackState)
00015             {
00016                 var state = (MediaPlaybackState)value;
00017
00018                 if (state == MediaPlaybackState.Playing)
00019                 {
00020                     return Symbol.Pause;
00021                 }
00022                 else
00023                 {
00024                     return Symbol.Play;
00025                 }
00026             }
00027             return null;
00028         }
00029
00030         public object ConvertBack(object value, Type targetType, object parameter, string language)
00031         {
00032             throw new NotImplementedException();
00033         }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/HandHandler.cpp Source File

  • SpatialInteractionSource
  • cpp

HandHandler.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "HandHandler.h"
00003 #include "Common\DirectXHelper.h"
00004
00005 using namespace HolographicPaint;
00006 using namespace DirectX;
00007 using namespace Windows::Foundation;
00008 using namespace Windows::Foundation::Numerics;
00009 using namespace Windows::Devices::Haptics;
00010 using namespace Windows::Perception::Spatial;
00011 using namespace Windows::UI::Input::Spatial;
00012 using namespace std::placeholders;
00013
00014 static const double NavigationThreshold = .3;
00015
00016 HandHandler::HandHandler(SpatialInteractionSource^ source, ISourceCommandHandler* eventsHandler, std::shared_ptr<Whiteboard>& target)
00017     : SourceHandler(source, eventsHandler, target)
00018 {
00019     // Because Hands are Detected and Lost easily, we send all our feedback with a special SourceId
00020     m_sourceId = AnyHandSourceId;
00021     m_gestureRecognizer = ref new SpatialGestureRecognizer(SpatialGestureSettings::Tap | SpatialGestureSettings::ManipulationTranslate);
00022     // Handle Tapped gesture to switch mode
00023     m_tappedToken =
00024         m_gestureRecognizer->Tapped +=
00025             ref new TypedEventHandler<SpatialGestureRecognizer^, SpatialTappedEventArgs^>(
00026                 std::bind(&HandHandler::OnTapped, this, _1, _2));
00027
00028     // Handle Navigation gesture to switch tool
00029     m_navigationStartedToken =
00030         m_gestureRecognizer->NavigationStarted +=
00031             ref new TypedEventHandler<SpatialGestureRecognizer^, SpatialNavigationStartedEventArgs^>(
00032                 std::bind(&HandHandler::OnNavigationStarted, this, _1, _2));
00033     m_navigationCompletedToken =
00034         m_gestureRecognizer->NavigationCompleted +=
00035             ref new TypedEventHandler<SpatialGestureRecognizer^, SpatialNavigationCompletedEventArgs^>(
00036                 std::bind(&HandHandler::OnNavigationCompleted, this, _1, _2));
00037
00038     // Handle Manipulation gesture to draw
00039     m_manipulationStartedToken =
00040         m_gestureRecognizer->ManipulationStarted +=
00041             ref new TypedEventHandler<SpatialGestureRecognizer ^, SpatialManipulationStartedEventArgs ^>(
00042                 std::bind(&HandHandler::OnManipulationStarted, this, _1, _2));
00043     m_manipulationCanceledToken =
00044         m_gestureRecognizer->ManipulationCanceled +=
00045             ref new TypedEventHandler<SpatialGestureRecognizer ^, SpatialManipulationCanceledEventArgs ^>(
00046                 std::bind(&HandHandler::OnManipulationCanceled, this, _1, _2));
00047     m_manipulationCompletedToken =
00048         m_gestureRecognizer->ManipulationCompleted +=
00049             ref new TypedEventHandler<SpatialGestureRecognizer ^, SpatialManipulationCompletedEventArgs ^>(
00050                 std::bind(&HandHandler::OnManipulationCompleted, this, _1, _2));
00051     m_manipulationUpdatedToken =
00052         m_gestureRecognizer->ManipulationUpdated +=
00053             ref new TypedEventHandler<SpatialGestureRecognizer ^, SpatialManipulationUpdatedEventArgs ^>(
00054                 std::bind(&HandHandler::OnManipulationUpdated, this, _1, _2));
00055 }
00056
00057 HandHandler::~HandHandler()
00058 {
00059     m_gestureRecognizer->Tapped -= m_tappedToken;
00060     m_gestureRecognizer->NavigationStarted -= m_navigationStartedToken;
00061     m_gestureRecognizer->NavigationCompleted -= m_navigationCompletedToken;
00062     m_gestureRecognizer->ManipulationStarted -= m_manipulationStartedToken;
00063     m_gestureRecognizer->ManipulationCanceled -= m_manipulationCanceledToken;
00064     m_gestureRecognizer->ManipulationCompleted -= m_manipulationCompletedToken;
00065     m_gestureRecognizer->ManipulationUpdated -= m_manipulationUpdatedToken;
00066 }
00067
00068 void HandHandler::OnInteractionDetected(SpatialInteraction^ interaction, SpatialCoordinateSystem^ coordinateSystem)
00069 {
00070     switch (m_currentMode)
00071     {
00072     case ApplicationMode::Drawing:
00073         m_gestureRecognizer->TrySetGestureSettings(SpatialGestureSettings::Tap | SpatialGestureSettings::ManipulationTranslate);
00074         break;
00075     case ApplicationMode::ChooseTool:
00076         m_gestureRecognizer->TrySetGestureSettings(SpatialGestureSettings::Tap | SpatialGestureSettings::NavigationX);
00077         break;
00078     }
00079     m_coordinateSystem = coordinateSystem;
00080     m_gestureRecognizer->CaptureInteraction(interaction);
00081 }
00082
00083 void HandHandler::OnNavigationStarted(SpatialGestureRecognizer ^sender, SpatialNavigationStartedEventArgs ^args)
00084 {
00085     HitTestTargetWithGaze(args->TryGetPointerPose(m_coordinateSystem));
00086     if (m_toolPosition.IsCurrent)
00087     {
00088         ComposeStroke();
00089     }
00090     else
00091     {
00092         // If the gaze is not hitting the board, cancel the current drawing operation
00093         m_gestureRecognizer->CancelPendingGestures();
00094     }
00095 }
00096
00097 void HandHandler::OnManipulationStarted(SpatialGestureRecognizer ^sender, SpatialManipulationStartedEventArgs ^args)
00098 {
00099     HitTestTargetWithGaze(args->TryGetPointerPose(m_coordinateSystem));
00100     if (m_toolPosition.IsCurrent)
00101     {
00102         m_initialPosition = m_toolPosition.Position;
00103         ComposeStroke();
00104     }
00105     else
00106     {
00107         // If the gaze is not hitting the board, cancel the current drawing operation
00108         m_gestureRecognizer->CancelPendingGestures();
00109     }
00110 }
00111
00112
00113 void HandHandler::OnManipulationCanceled(SpatialGestureRecognizer ^sender, SpatialManipulationCanceledEventArgs ^args)
00114 {
00115     TerminateStroke();
00116 }
00117
00118
00119 void HandHandler::OnManipulationCompleted(SpatialGestureRecognizer ^sender, SpatialManipulationCompletedEventArgs ^args)
00120 {
00121     TerminateStroke();
00122 }
00123
00124
00125 void HandHandler::OnManipulationUpdated(SpatialGestureRecognizer ^sender, SpatialManipulationUpdatedEventArgs ^args)
00126 {
00127     auto delta = args->TryGetCumulativeDelta(m_coordinateSystem);
00128     auto translation = delta->Translation;
00129     translation.z = 0;
00130     m_toolPosition.Position = m_initialPosition + translation;
00131     if (m_targetBoard->IsValidPosition(m_toolPosition.Position))
00132     {
00133         m_refreshModelConstantBufferData = true;
00134         ComposeStroke();
00135     }
00136     else
00137     {
00138         m_gestureRecognizer->CancelPendingGestures();
00139     }
00140 }
00141
00142 void HandHandler::OnNavigationCompleted(SpatialGestureRecognizer ^sender, SpatialNavigationCompletedEventArgs ^args)
00143 {
00144     float3 delta = args->NormalizedOffset;
00145     DPadAction action = DPadAction::None;
00146     if (delta.x < -NavigationThreshold)
00147     {
00148         action = DPadAction::Left;
00149     }
00150     else if (delta.x > NavigationThreshold)
00151     {
00152         action = DPadAction::Right;
00153     }
00154     if (action != DPadAction::None)
00155     {
00156         m_eventsHandler->OnDPadAction(this, action);
00157     }
00158 }
00159
00160 void HandHandler::OnTapped(SpatialGestureRecognizer ^sender, SpatialTappedEventArgs ^args)
00161 {
00162     if (m_eventsHandler != nullptr)
00163     {
00164         switch (m_currentMode)
00165         {
00166         case ApplicationMode::ChooseTool:
00167             m_eventsHandler->OnSelectTool(this);
00168             break;
00169         case ApplicationMode::Drawing:
00170         {
00171             SpatialPointerPose^ pointerPose = args->TryGetPointerPose(m_coordinateSystem);
00172             if (pointerPose != nullptr)
00173             {
00174                 m_eventsHandler->OnEnterToolChoice(this, pointerPose->Timestamp);
00175             }
00176         }
00177         break;
00178         }
00179     }
00180 }
00181
00182
00183 void HandHandler::OnSourceUpdated(SpatialInteractionSourceState^ state, SpatialCoordinateSystem^ coordinateSystem)
00184 {
00185     // Update the source position
00186     __super::OnSourceUpdated(state, coordinateSystem);
00187
00188     switch (m_currentMode)
00189     {
00190         case ApplicationMode::Drawing:
00191         {
00192             // If we are not already drawing, use Head Gaze to hit test the wall
00193             if (!m_currentStroke)
00194             {
00195                 // Try to get the pointing ray and hit test the wall
00196                 SpatialPointerPose^ pointerPose = state->TryGetPointerPose(coordinateSystem);
00197                 if (pointerPose != nullptr)
00198                 {
00199                     HitTestTargetWithGaze(pointerPose);
00200
00201                     m_refreshModelConstantBufferData = m_toolPosition.IsCurrent;
00202                 }
00203                 m_toolPosition.CheckIfObsolete(state->Timestamp->TargetTime.UniversalTime);
00204             }
00205         }
00206         break;
00207     }
00208 }
00209
00210 void HandHandler::HitTestTargetWithGaze(SpatialPointerPose^ pointerPose)
00211 {
00212     m_toolPosition.IsCurrent = false;
00213
00214     auto headPose = pointerPose->Head;
00215     const float3& forwardDirection = headPose->ForwardDirection;
00216     float targetDistance = 0.0f;
00217
00218     if (m_targetBoard->Intersects(headPose->Position, forwardDirection, &targetDistance))
00219     {
00220         m_toolPosition.HasValue = true;
00221         m_toolPosition.IsCurrent = true;
00222         m_toolPosition.Position = headPose->Position + targetDistance * forwardDirection;
00223
00224         // Compute the orientation based on the ray
00225         const XMVECTOR orientationVector = DX::GetQuaternionVectorFromRay(forwardDirection, headPose->UpDirection);
00226         XMStoreQuaternion(&m_toolPosition.Orientation, orientationVector);
00227     }
00228 }
00229
00230
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cs/SampleConfiguration.cs Source File

  • HttpClient
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml;
00016 using Windows.ApplicationModel.Activation;
00017
00018 namespace SDKTemplate
00019 {
00020     public partial class MainPage : Page
00021     {
00022         public const string FEATURE_NAME = "HttpClient sample";
00023
00024         List<Scenario> scenarios = new List<Scenario>
00025         {
00026             new Scenario() { Title = "GET Text With Cache Control", ClassType = typeof(Scenario01_GetText) },
00027             new Scenario() { Title = "GET Stream", ClassType = typeof(Scenario02_GetStream) },
00028             new Scenario() { Title = "GET List", ClassType = typeof(Scenario03_GetList) },
00029             new Scenario() { Title = "POST Text", ClassType = typeof(Scenario04_PostText) },
00030             new Scenario() { Title = "POST Stream", ClassType = typeof(Scenario05_PostStream) },
00031             new Scenario() { Title = "POST Multipart", ClassType = typeof(Scenario06_PostMultipart) },
00032             new Scenario() { Title = "POST Stream With Progress", ClassType = typeof(Scenario07_PostStreamWithProgress) },
00033             new Scenario() { Title = "POST Custom Content", ClassType = typeof(Scenario08_PostCustomContent) },
00034             new Scenario() { Title = "Get Cookies", ClassType = typeof(Scenario09_GetCookie) },
00035             new Scenario() { Title = "Set Cookie", ClassType = typeof(Scenario10_SetCookie) },
00036             new Scenario() { Title = "Delete Cookie", ClassType = typeof(Scenario11_DeleteCookie) },
00037             new Scenario() { Title = "Disable Cookies", ClassType = typeof(Scenario12_DisableCookies) },
00038             new Scenario() { Title = "Retry Filter", ClassType = typeof(Scenario13_RetryFilter) },
00039             new Scenario() { Title = "Metered Connection Filter", ClassType = typeof(Scenario14_MeteredConnectionFilter) },
00040             new Scenario() { Title = "Server Certificate Validation", ClassType = typeof(Scenario15_ServerCertificateValidation) },
00041         };
00042     }
00043
00044     public class Scenario
00045     {
00046         public string Title { get; set; }
00047         public Type ClassType { get; set; }
00048     }
00049
00050 }
00051
00052
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ImportableItemWrapper Member List

This is the complete list of members for ImportableItemWrapper, including all inherited members.
ImportableItem | ImportableItemWrapper |
ImportableItemWrapper(PhotoImportItem importableItem) | ImportableItemWrapper | [inline]
LoadThumbnail() | ImportableItemWrapper | [inline]
NotifyProperty(string propertyName) | ImportableItemWrapper | [inline, private]
PropertyChanged | ImportableItemWrapper |
thumbnail | ImportableItemWrapper | [private]
Thumbnail | ImportableItemWrapper |
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/OpQueue.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

OpQueue.h

Go to the documentation of this file.
00001 //////////////////////////////////////////////////////////////////////////
00002 //
00003 // OpQueue.h
00004 // Async operation queue.
00005 //
00006 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00007 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00008 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00009 // PARTICULAR PURPOSE.
00010 //
00011 // Copyright (c) Microsoft Corporation. All rights reserved.
00012 //
00013 //////////////////////////////////////////////////////////////////////////
00014
00015 #pragma once
00016
00017 #pragma warning( push )
00018 #pragma warning( disable : 4355 )  // 'this' used in base member initializer list
00019
00020 /*
00021     This header file defines an object to help queue and serialize
00022     asynchronous operations.
00023
00024     Background:
00025
00026     To perform an operation asynchronously in Media Foundation, an object
00027     does one of the following:
00028
00029         1. Calls MFPutWorkItem(Ex), using either a standard work queue
00030            identifier or a caller-allocated work queue. The work-queue
00031            thread invokes the object's callback.
00032
00033         2. Creates an async result object (IMFAsyncResult) and calls
00034            MFInvokeCallback to invoke the object's callback.
00035
00036     Ultimately, either of these cause the object's callback to be invoked
00037     from a work-queue thread. The object can then complete the operation
00038     inside the callback.
00039
00040     However, the Media Foundation platform may dispatch async callbacks in
00041     parallel on several threads. Putting an item on a work queue does NOT
00042     guarantee that one operation will complete before the next one starts,
00043     or even that work items will be dispatched in the same order they were
00044     called.
00045
00046     To serialize async operations that should not overlap, an object should
00047     use a queue. While one operation is pending, subsequent operations are
00048     put on the queue, and only dispatched after the previous operation is
00049     complete.
00050
00051     The granularity of a single "operation" depends on the requirements of
00052     that particular object. A single operation might involve several
00053     asynchronous calls before the object dispatches the next operation on
00054     the queue.
00055
00056
00057 */
00058
00059
00060
00061 //-------------------------------------------------------------------
00062 // OpQueue class template
00063 //
00064 // Base class for an async operation queue.
00065 //
00066 // TOperation: The class used to describe operations. This class must
00067 //          implement IUnknown.
00068 //
00069 // The OpQueue class is an abstract class. The derived class must
00070 // implement the following pure-virtual methods:
00071 //
00072 // - IUnknown methods (AddRef, Release, QI)
00073 //
00074 // - DispatchOperation:
00075 //
00076 //      Performs the asynchronous operation specified by pOp.
00077 //
00078 //      At the end of each operation, the derived class must call
00079 //      ProcessQueue to process the next operation in the queue.
00080 //
00081 //      NOTE: An operation is not required to complete inside the
00082 //      DispatchOperation method. A single operation might consist
00083 //      of several asynchronous method calls.
00084 //
00085 // - ValidateOperation:
00086 //
00087 //      Checks whether the object can perform the operation specified
00088 //      by pOp at this time.
00089 //
00090 //      If the object cannot perform the operation now (e.g., because
00091 //      another operation is still in progress) the method should
00092 //      return MF_E_NOTACCEPTING.
00093 //
00094 //-------------------------------------------------------------------
00095 #include "linklist.h"
00096 #include "AsyncCB.h"
00097
00098 template <class T, class TOperation>
00099 class OpQueue //: public IUnknown
00100 {
00101 public:
00102
00103     typedef ComPtrList<TOperation>   OpList;
00104
00105     HRESULT QueueOperation(TOperation *pOp);
00106
00107 protected:
00108
00109     HRESULT ProcessQueue();
00110     HRESULT ProcessQueueAsync(IMFAsyncResult *pResult);
00111
00112     virtual HRESULT DispatchOperation(TOperation *pOp) = 0;
00113     virtual HRESULT ValidateOperation(TOperation *pOp) = 0;
00114
00115     OpQueue(CRITICAL_SECTION& critsec)
00116         : m_OnProcessQueue(static_cast<T *>(this), &OpQueue::ProcessQueueAsync),
00117           m_critsec(critsec)
00118     {
00119     }
00120
00121     virtual ~OpQueue()
00122     {
00123     }
00124
00125 protected:
00126     OpList                  m_OpQueue;         // Queue of operations.
00127     CRITICAL_SECTION&       m_critsec;         // Protects the queue state.
00128     AsyncCallback<T>  m_OnProcessQueue;  // ProcessQueueAsync callback.
00129 };
00130
00131
00132
00133 //-------------------------------------------------------------------
00134 // Place an operation on the queue.
00135 // Public method.
00136 //-------------------------------------------------------------------
00137
00138 template <class T, class TOperation>
00139 HRESULT OpQueue<T, TOperation>::QueueOperation(TOperation *pOp)
00140 {
00141     HRESULT hr = S_OK;
00142
00143     EnterCriticalSection(&m_critsec);
00144
00145     hr = m_OpQueue.InsertBack(pOp);
00146     if (SUCCEEDED(hr))
00147     {
00148         hr = ProcessQueue();
00149     }
00150
00151     LeaveCriticalSection(&m_critsec);
00152     return hr;
00153 }
00154
00155
00156 //-------------------------------------------------------------------
00157 // Process the next operation on the queue.
00158 // Protected method.
00159 //
00160 // Note: This method dispatches the operation to a work queue.
00161 //-------------------------------------------------------------------
00162
00163 template <class T, class TOperation>
00164 HRESULT OpQueue<T, TOperation>::ProcessQueue()
00165 {
00166     HRESULT hr = S_OK;
00167     if (m_OpQueue.GetCount() > 0)
00168     {
00169         hr = MFPutWorkItem2(
00170             MFASYNC_CALLBACK_QUEUE_STANDARD,    // Use the standard work queue.
00171             0,                                  // Default priority
00172             &m_OnProcessQueue,                  // Callback method.
00173             nullptr                             // State object.
00174             );
00175     }
00176     return hr;
00177 }
00178
00179
00180 //-------------------------------------------------------------------
00181 // Process the next operation on the queue.
00182 // Protected method.
00183 //
00184 // Note: This method is called from a work-queue thread.
00185 //-------------------------------------------------------------------
00186
00187 template <class T, class TOperation>
00188 HRESULT OpQueue<T, TOperation>::ProcessQueueAsync(IMFAsyncResult *pResult)
00189 {
00190     HRESULT hr = S_OK;
00191     TOperation *pOp = nullptr;
00192
00193     EnterCriticalSection(&m_critsec);
00194
00195     if (m_OpQueue.GetCount() > 0)
00196     {
00197         hr = m_OpQueue.GetFront(&pOp);
00198
00199         if (SUCCEEDED(hr))
00200         {
00201             hr = ValidateOperation(pOp);
00202         }
00203         if (SUCCEEDED(hr))
00204         {
00205             hr = m_OpQueue.RemoveFront(nullptr);
00206         }
00207         if (SUCCEEDED(hr))
00208         {
00209             (void)DispatchOperation(pOp);
00210         }
00211     }
00212
00213     if (pOp != nullptr)
00214     {
00215         pOp->Release();
00216     }
00217
00218     LeaveCriticalSection(&m_critsec);
00219     return hr;
00220 }
00221
00222 #pragma warning( pop )
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PoseTrackingEntityData Member List

This is the complete list of members for PoseTrackingEntityData, including all inherited members.
DataSizeInBytes | PoseTrackingEntityData
EntityId | PoseTrackingEntityData
IsTracked | PoseTrackingEntityData
Poses | PoseTrackingEntityData
PosesCount | PoseTrackingEntityData
PoseSet | PoseTrackingEntityData
Generated on Fri Nov 15 2024 22:23:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cs/Server/Properties/AssemblyInfo.cs Source File

  • ProxyStubsForWinRTComponents
  • cs
  • Server
  • Properties

AssemblyInfo.cs

Go to the documentation of this file.
00001 ﻿using System.Reflection;
00002 using System.Runtime.CompilerServices;
00003 using System.Runtime.InteropServices;
00004
00005 // General Information about an assembly is controlled through the following
00006 // set of attributes. Change these attribute values to modify the information
00007 // associated with an assembly.
00008 [assembly: AssemblyTitle("ProxyStubsForWinRTComponents C# client sample")]
00009 [assembly: AssemblyDescription("")]
00010 [assembly: AssemblyConfiguration("")]
00011 [assembly: AssemblyCompany("Microsoft Corporation")]
00012 [assembly: AssemblyProduct("")]
00013 [assembly: AssemblyCopyright("")]
00014 [assembly: AssemblyTrademark("")]
00015 [assembly: AssemblyCulture("")]
00016
00017 // Version information for an assembly consists of the following four values:
00018 //
00019 //      Major Version
00020 //      Minor Version
00021 //      Build Number
00022 //      Revision
00023 //
00024 // You can specify all the values or you can default the Build and Revision Numbers
00025 // by using the '*' as shown below:
00026 // [assembly: AssemblyVersion("1.0.*")]
00027 [assembly: AssemblyVersion("1.0.0.0")]
00028 [assembly: AssemblyFileVersion("1.0.0.0")]
00029 [assembly: ComVisible(false)]
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/Simple3DGame.cpp Source File

  • Simple3DGameDX
  • cppwinrt

Simple3DGame.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "GameRenderer.h"
00014 #include "Level1.h"
00015 #include "Level2.h"
00016 #include "Level3.h"
00017 #include "Level4.h"
00018 #include "Level5.h"
00019 #include "Level6.h"
00020 #include "Cylinder.h"
00021 #include "Face.h"
00022 #include "MediaReader.h"
00023
00024 using namespace DirectX;
00025 using namespace winrt::Windows::Storage;
00026
00027 Simple3DGame::Simple3DGame() :
00028     m_ammoCount(0),
00029     m_ammoNext(0),
00030     m_gameActive(false),
00031     m_levelActive(false),
00032     m_totalHits(0),
00033     m_totalShots(0),
00034     m_levelBonusTime(0.0),
00035     m_levelTimeRemaining(0.0),
00036     m_levelCount(0),
00037     m_currentLevel(0)
00038 {
00039 }
00040
00041 void Simple3DGame::Initialize(
00042     _In_ std::shared_ptr<MoveLookController> const& controller,
00043     _In_ std::shared_ptr<GameRenderer> const& renderer
00044     )
00045 {
00046     // This method is expected to be called as an asynchronous task.
00047     // Care should be taken to not call rendering methods on the
00048     // m_renderer as this would result in the D3D Context being
00049     // used in multiple threads, which is not allowed.
00050
00051     m_controller = controller;
00052     m_renderer = renderer;
00053
00054     m_audioController.CreateDeviceIndependentResources();
00055
00056     m_ammo.resize(GameConstants::MaxAmmo);
00057
00058     m_savedState.Initialize(ApplicationData::Current().LocalSettings().Values(), L"Game");
00059
00060     // Create a sphere primitive to represent the player.
00061     // The sphere will be used to handle collisions and constrain the player in the world.
00062     // It is not rendered so it is not added to the list of render objects.
00063     // It is added to the object list so it will be included in intersection calculations.
00064     m_player = std::make_shared<Sphere>(XMFLOAT3(0.0f, -1.3f, 4.0f), 0.2f);
00065     m_objects.push_back(m_player);
00066     m_player->Active(true);
00067
00068     m_camera.SetProjParams(XM_PI / 2, 1.0f, 0.01f, 100.0f);
00069     m_camera.SetViewParams(
00070         m_player->Position(),            // Eye point in world coordinates.
00071         XMFLOAT3(0.0f, 0.7f, 0.0f),     // Look at point in world coordinates.
00072         XMFLOAT3(0.0f, 1.0f, 0.0f)      // The Up vector for the camera.
00073         );
00074
00075     m_controller->Pitch(m_camera.Pitch());
00076     m_controller->Yaw(m_camera.Yaw());
00077
00078     // Instantiate a set of primitives to represent the containing world. These objects
00079     // maintain the geometry and material properties of the walls, floor and ceiling.
00080     // The TargetId is used to identify the world objects so that the right geometry
00081     // and textures can be associated with them later after those resources have
00082     // been created.
00083     std::shared_ptr<GameObject> world = std::make_shared<GameObject>();
00084     world->TargetId(GameConstants::WorldFloorId);
00085     world->Active(true);
00086     m_renderObjects.push_back(world);
00087
00088     world = std::make_shared<GameObject>();
00089     world->TargetId(GameConstants::WorldCeilingId);
00090     world->Active(true);
00091     m_renderObjects.push_back(world);
00092
00093     world = std::make_shared<GameObject>();
00094     world->TargetId(GameConstants::WorldWallsId);
00095     world->Active(true);
00096     m_renderObjects.push_back(world);
00097
00098     // Min and max Bound are defining the world space of the game.
00099     // All camera motion and dynamics are confined to this space.
00100     m_minBound = XMFLOAT3(-4.0f, -3.0f, -6.0f);
00101     m_maxBound = XMFLOAT3(4.0f, 3.0f, 6.0f);
00102
00103     // Instantiate the Cylinders for use in the various game levels.
00104     // Each cylinder has a different initial position, radius and direction vector,
00105     // but share a common set of material properties.
00106     for (int a = 0; a < GameConstants::MaxCylinders; a++)
00107     {
00108         std::shared_ptr<Cylinder> cylinder;
00109         switch (a)
00110         {
00111         case 0:
00112             cylinder = std::make_shared<Cylinder>(XMFLOAT3(-2.0f, -3.0f, 0.0f), 0.25f, XMFLOAT3(0.0f, 6.0f, 0.0f));
00113             break;
00114         case 1:
00115             cylinder = std::make_shared<Cylinder>(XMFLOAT3(2.0f, -3.0f, 0.0f), 0.25f, XMFLOAT3(0.0f, 6.0f, 0.0f));
00116             break;
00117         case 2:
00118             cylinder = std::make_shared<Cylinder>(XMFLOAT3(0.0f, -3.0f, -2.0f), 0.25f, XMFLOAT3(0.0f, 6.0f, 0.0f));
00119             break;
00120         case 3:
00121             cylinder = std::make_shared<Cylinder>(XMFLOAT3(-1.5f, -3.0f, -4.0f), 0.25f, XMFLOAT3(0.0f, 6.0f, 0.0f));
00122             break;
00123         case 4:
00124             cylinder = std::make_shared<Cylinder>(XMFLOAT3(1.5f, -3.0f, -4.0f), 0.50f, XMFLOAT3(0.0f, 6.0f, 0.0f));
00125             break;
00126         }
00127         cylinder->Active(true);
00128         m_objects.push_back(cylinder);
00129         m_renderObjects.push_back(cylinder);
00130     }
00131
00132     MediaReader mediaReader;
00133     auto targetHitSoundX = mediaReader.LoadMedia(L"Assets\\hit.wav");
00134
00135     // Instantiate the targets for use in the game.
00136     // Each target has a different initial position, size and orientation,
00137     // but share a common set of material properties.
00138     // The target is defined by a position and two vectors that define both
00139     // the plane of the target in world space and the size of the parallelogram
00140     // based on the lengths of the vectors.
00141     // Each target is assigned a number for identification purposes.
00142     // The Target ID number is 1 based.
00143     // All targets have the same material properties.
00144     for (int a = 1; a < GameConstants::MaxTargets; a++)
00145     {
00146         std::shared_ptr<Face> target;
00147         switch (a)
00148         {
00149         case 1:
00150             target = std::make_shared<Face>(XMFLOAT3(-2.5f, -1.0f, -1.5f), XMFLOAT3(-1.5f, -1.0f, -2.0f), XMFLOAT3(-2.5f, 1.0f, -1.5f));
00151             break;
00152         case 2:
00153             target = std::make_shared<Face>(XMFLOAT3(-1.0f, 1.0f, -3.0f), XMFLOAT3(0.0f, 1.0f, -3.0f), XMFLOAT3(-1.0f, 2.0f, -3.0f));
00154             break;
00155         case 3:
00156             target = std::make_shared<Face>(XMFLOAT3(1.5f, 0.0f, -3.0f), XMFLOAT3(2.5f, 0.0f, -2.0f), XMFLOAT3(1.5f, 2.0f, -3.0f));
00157             break;
00158         case 4:
00159             target = std::make_shared<Face>(XMFLOAT3(-2.5f, -1.0f, -5.5f), XMFLOAT3(-0.5f, -1.0f, -5.5f), XMFLOAT3(-2.5f, 1.0f, -5.5f));
00160             break;
00161         case 5:
00162             target = std::make_shared<Face>(XMFLOAT3(0.5f, -2.0f, -5.0f), XMFLOAT3(1.5f, -2.0f, -5.0f), XMFLOAT3(0.5f, 0.0f, -5.0f));
00163             break;
00164         case 6:
00165             target = std::make_shared<Face>(XMFLOAT3(1.5f, -2.0f, -5.5f), XMFLOAT3(2.5f, -2.0f, -5.0f), XMFLOAT3(1.5f, 0.0f, -5.5f));
00166             break;
00167         case 7:
00168             target = std::make_shared<Face>(XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.5f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.5f, 0.0f));
00169             break;
00170         case 8:
00171             target = std::make_shared<Face>(XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.5f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.5f, 0.0f));
00172             break;
00173         case 9:
00174             target = std::make_shared<Face>(XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.5f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.5f, 0.0f));
00175             break;
00176         }
00177
00178         target->Target(true);
00179         target->TargetId(a);
00180         target->Active(true);
00181         target->HitSound(std::make_shared<SoundEffect>());
00182         target->HitSound()->Initialize(
00183             m_audioController.SoundEffectEngine(),
00184             mediaReader.GetOutputWaveFormatEx(),
00185             targetHitSoundX
00186             );
00187
00188         m_objects.push_back(target);
00189         m_renderObjects.push_back(target);
00190     }
00191
00192     // Instantiate a set of spheres to be used as ammunition for the game
00193     // and set the material properties of the spheres.
00194     auto ammoHitSound = mediaReader.LoadMedia(L"Assets\\bounce.wav");
00195
00196     for (int a = 0; a < GameConstants::MaxAmmo; a++)
00197     {
00198         m_ammo[a] = std::make_shared<Sphere>();
00199         m_ammo[a]->Radius(GameConstants::AmmoRadius);
00200         m_ammo[a]->HitSound(std::make_shared<SoundEffect>());
00201         m_ammo[a]->HitSound()->Initialize(
00202             m_audioController.SoundEffectEngine(),
00203             mediaReader.GetOutputWaveFormatEx(),
00204             ammoHitSound
00205             );
00206         m_ammo[a]->Active(false);
00207         m_renderObjects.push_back(m_ammo[a]);
00208     }
00209
00210     // Instantiate each of the game levels. The Level class contains methods
00211     // that initialize the objects in the world for the given level and also
00212     // define any motion paths for the objects in that level.
00213
00214     m_level.push_back(std::make_shared<Level1>());
00215     m_level.push_back(std::make_shared<Level2>());
00216     m_level.push_back(std::make_shared<Level3>());
00217     m_level.push_back(std::make_shared<Level4>());
00218     m_level.push_back(std::make_shared<Level5>());
00219     m_level.push_back(std::make_shared<Level6>());
00220     m_levelCount = static_cast<uint32_t>(m_level.size());
00221
00222     // Load the top score from disk if it exists.
00223     LoadHighScore();
00224
00225     // Load the currentScore for saved state if it exists.
00226     LoadState();
00227
00228     m_controller->Active(false);
00229 }
00230
00231 void Simple3DGame::LoadGame()
00232 {
00233     m_player->Position(XMFLOAT3(0.0f, -1.3f, 4.0f));
00234
00235     m_camera.SetViewParams(
00236         m_player->Position(),            // Eye point in world coordinates.
00237         XMFLOAT3(0.0f, 0.7f, 0.0f),     // Look at point in world coordinates.
00238         XMFLOAT3(0.0f, 1.0f, 0.0f)      // The Up vector for the camera.
00239         );
00240
00241     m_controller->Pitch(m_camera.Pitch());
00242     m_controller->Yaw(m_camera.Yaw());
00243     m_currentLevel = 0;
00244     m_levelTimeRemaining = 0.0f;
00245     m_levelBonusTime = m_levelTimeRemaining;
00246     m_levelDuration = m_level[m_currentLevel]->TimeLimit() + m_levelBonusTime;
00247     InitializeAmmo();
00248     m_totalHits = 0;
00249     m_totalShots = 0;
00250     m_gameActive = false;
00251     m_levelActive = false;
00252     m_timer.Reset();
00253 }
00254
00255 winrt::Windows::Foundation::IAsyncAction Simple3DGame::LoadLevelAsync()
00256 {
00257     // Initialize the level and spin up the async loading of the rendering
00258     // resources for the level.
00259     // This will run in a separate thread, so for Direct3D 11, only Device
00260     // methods are allowed. Any DeviceContext method calls need to be
00261     // done in FinalizeLoadLevel.
00262
00263     m_level[m_currentLevel]->Initialize(m_objects);
00264     m_levelDuration = m_level[m_currentLevel]->TimeLimit() + m_levelBonusTime;
00265
00266     co_await m_renderer->LoadLevelResourcesAsync();
00267 }
00268
00269 void Simple3DGame::FinalizeLoadLevel()
00270 {
00271     // This method is called on the main thread, so Direct3D 11 DeviceContext
00272     // method calls are allowable here.
00273
00274     // Finalize the Level loading.
00275     m_renderer->FinalizeLoadLevelResources();
00276 }
00277
00278 void Simple3DGame::StartLevel()
00279 {
00280     m_timer.Reset();
00281     m_timer.Start();
00282     if (m_currentLevel == 0)
00283     {
00284         m_gameActive = true;
00285     }
00286     m_levelActive = true;
00287     m_controller->Active(true);
00288 }
00289
00290 void Simple3DGame::PauseGame()
00291 {
00292     m_timer.Stop();
00293     SaveState();
00294 }
00295
00296 void Simple3DGame::ContinueGame()
00297 {
00298     m_timer.Start();
00299     m_controller->Active(true);
00300 }
00301
00302 GameState Simple3DGame::RunGame()
00303 {
00304     // This method is called to execute a single time interval for active game play.
00305     // It returns the resulting state of game play after the interval has been executed.
00306
00307     m_timer.Update();
00308
00309     m_levelTimeRemaining = m_levelDuration - m_timer.PlayingTime();
00310
00311     if (m_levelTimeRemaining <= 0.0f)
00312     {
00313         // Time expired, so the game is over.
00314         m_levelTimeRemaining = 0.0f;
00315         InitializeAmmo();
00316         m_timer.Reset();
00317         m_gameActive = false;
00318         m_levelActive = false;
00319         SaveState();
00320
00321         if (m_totalHits > m_topScore.totalHits)
00322         {
00323             // There is a new high score so save it.
00324             m_topScore.totalHits = m_totalHits;
00325             m_topScore.totalShots = m_totalShots;
00326             m_topScore.levelCompleted = m_currentLevel;
00327
00328             SaveHighScore();
00329         }
00330         return GameState::TimeExpired;
00331     }
00332     else
00333     {
00334         // Time has not expired, so run one frame of game play.
00335         m_player->Velocity(m_controller->Velocity());
00336         m_camera.LookDirection(m_controller->LookDirection());
00337
00338         UpdateDynamics();
00339
00340         // Update the Camera with the player position updates from the dynamics calculations.
00341         m_camera.Eye(m_player->Position());
00342         m_camera.LookDirection(m_controller->LookDirection());
00343
00344         if (m_level[m_currentLevel]->Update(m_timer.PlayingTime(), m_timer.DeltaTime(), m_levelTimeRemaining, m_objects))
00345         {
00346             // The level has been completed.
00347             m_levelActive = false;
00348             InitializeAmmo();
00349
00350             if (m_currentLevel < m_levelCount - 1)
00351             {
00352                 // More levels to go so increment the level number.
00353                 // Actual level loading will occur in the LoadLevelAsync / FinalizeLoadLevel
00354                 // methods.
00355                 m_timer.Reset();
00356                 m_currentLevel++;
00357                 m_levelBonusTime = m_levelTimeRemaining;
00358                 SaveState();
00359                 return GameState::LevelComplete;
00360             }
00361             else
00362             {
00363                 // All levels have been completed.
00364                 m_timer.Reset();
00365                 m_gameActive = false;
00366                 m_levelActive = false;
00367                 SaveState();
00368
00369                 if (m_totalHits > m_topScore.totalHits)
00370                 {
00371                     // There is a new high score so save it.
00372                     m_topScore.totalHits = m_totalHits;
00373                     m_topScore.totalShots = m_totalShots;
00374                     m_topScore.levelCompleted = m_currentLevel;
00375
00376                     SaveHighScore();
00377                 }
00378                 return GameState::GameComplete;
00379             }
00380         }
00381     }
00382     return GameState::Active;
00383 }
00384
00385 void Simple3DGame::OnSuspending()
00386 {
00387     m_audioController.SuspendAudio();
00388 }
00389
00390 void Simple3DGame::OnResuming()
00391 {
00392     m_audioController.ResumeAudio();
00393 }
00394
00395 void Simple3DGame::UpdateDynamics()
00396 {
00397     float timeTotal = m_timer.PlayingTime();
00398     float timeFrame = m_timer.DeltaTime();
00399     bool fire = m_controller->IsFiring();
00400
00401 #pragma region Shoot Ammo
00402     // Shoot ammo.
00403     if (fire)
00404     {
00405         static float lastFired;  // Timestamp of last ammo fired.
00406
00407         if (timeTotal < lastFired)
00408         {
00409             // timeTotal is not guarenteed to be monotomically increasing because it is
00410             // reset at each level.
00411             lastFired = timeTotal - GameConstants::Physics::AutoFireDelay;
00412         }
00413
00414         if (timeTotal - lastFired >= GameConstants::Physics::AutoFireDelay)
00415         {
00416             // Get inverse view matrix.
00417             XMMATRIX invView;
00418             XMVECTOR det;
00419             invView = XMMatrixInverse(&det, m_camera.View());
00420
00421             // Compute initial velocity in world space from camera space.
00422             XMFLOAT4 initialVelocity(0.0f, 0.0f, 15.0f, 0.0f);
00423             m_ammo[m_ammoNext]->Velocity(XMVector4Transform(XMLoadFloat4(&initialVelocity), invView));
00424
00425             // Set the initial position of the ammo to be fired. The position is offset from the player
00426             // to avoid an initial collision with the player object.
00427             XMFLOAT4 initialPosition(0.0f, -0.15f, m_player->Radius() + GameConstants::AmmoSize, 1.0f);
00428             m_ammo[m_ammoNext]->Position(XMVector4Transform(XMLoadFloat4(&initialPosition), invView));
00429
00430             // Initially not laying on ground.
00431             m_ammo[m_ammoNext]->OnGround(false);
00432             m_ammo[m_ammoNext]->Active(true);
00433
00434             // Set position in array of next Ammo to use.
00435             // We will re-use ammo taking the least recently used once we have hit the
00436             // MaxAmmo in use.
00437             m_ammoNext = (m_ammoNext + 1) % GameConstants::MaxAmmo;
00438             m_ammoCount = min(m_ammoCount + 1, GameConstants::MaxAmmo);
00439
00440             lastFired = timeTotal;
00441             m_totalShots++;
00442         }
00443     }
00444 #pragma endregion
00445
00446 #pragma region Animate Objects
00447     // Walk the list of objects looking for any objects that have an animation associated with it.
00448     // Update the position of the object based on evaluating the animation object with the current time.
00449     // Once the current time (timeTotal) is past the end of the animation time remove
00450     // the animation object since it is no longer needed.
00451     for (uint32_t i = 0; i < m_objects.size(); i++)
00452     {
00453         if (m_objects[i]->AnimatePosition())
00454         {
00455             m_objects[i]->Position(m_objects[i]->AnimatePosition()->Evaluate(timeTotal));
00456             if (m_objects[i]->AnimatePosition()->IsFinished(timeTotal))
00457             {
00458                 m_objects[i]->AnimatePosition(nullptr);
00459             }
00460         }
00461     }
00462 #pragma endregion
00463
00464     // If the elapsed time is too long, we slice up the time and handle physics over several
00465     // smaller time steps to avoid missing collisions.
00466     float timeLeft = timeFrame;
00467     float elapsedFrameTime;
00468     while (timeLeft > 0.0f)
00469     {
00470         elapsedFrameTime = min(timeLeft, GameConstants::Physics::FrameLength);
00471         timeLeft -= elapsedFrameTime;
00472
00473         // Update the player position.
00474         m_player->Position(m_player->VectorPosition() + m_player->VectorVelocity() * elapsedFrameTime);
00475
00476         // Do m_player / object intersections.
00477         for (uint32_t a = 0; a < m_objects.size(); a++)
00478         {
00479             if (m_objects[a]->Active() && m_objects[a] != m_player)
00480             {
00481                 XMFLOAT3 contact;
00482                 XMFLOAT3 normal;
00483
00484                 if (m_objects[a]->IsTouching(m_player->Position(), m_player->Radius(), &contact, &normal))
00485                 {
00486                     // Player is in contact with m_objects[a].
00487                     XMVECTOR oneToTwo;
00488                     oneToTwo = -XMLoadFloat3(&normal);
00489
00490                     float impact = XMVectorGetX(
00491                         XMVector3Dot(oneToTwo, m_player->VectorVelocity())
00492                         );
00493                     // Make sure that the player is actually headed towards the object. At grazing angles there
00494                     // could appear to be an impact when the player is actually already hit and moving away.
00495                     if (impact > 0.0f)
00496                     {
00497                         // Compute the normal and tangential components of the player's velocity.
00498                         XMVECTOR velocityOneNormal = XMVector3Dot(oneToTwo, m_player->VectorVelocity()) * oneToTwo;
00499                         XMVECTOR velocityOneTangent = m_player->VectorVelocity() - velocityOneNormal;
00500
00501                         // Compute post-collision velocity.
00502                         m_player->Velocity(velocityOneTangent - velocityOneNormal);
00503
00504                         // Fix the positions so that the player is just touching the object.
00505                         float distanceToMove = m_player->Radius();
00506                         m_player->Position(XMLoadFloat3(&contact) - (oneToTwo * distanceToMove));
00507                     }
00508                 }
00509             }
00510         }
00511         {
00512             // Do collision detection of the player with the bounding world.
00513             XMFLOAT3 position = m_player->Position();
00514             XMFLOAT3 velocity = m_player->Velocity();
00515             float radius = m_player->Radius();
00516
00517             // Check for player collisions with the walls floor or ceiling and adjust the position.
00518             float limit = m_minBound.x + radius;
00519             if (position.x < limit)
00520             {
00521                 position.x = limit;
00522                 velocity.x = -velocity.x * GameConstants::Physics::GroundRestitution;
00523             }
00524             limit = m_maxBound.x - radius;
00525             if (position.x > limit)
00526             {
00527                 position.x = limit;
00528                 velocity.x = -velocity.x + GameConstants::Physics::GroundRestitution;
00529             }
00530             limit = m_minBound.y + radius;
00531             if (position.y < limit)
00532             {
00533                 position.y = limit;
00534                 velocity.y = -velocity.y * GameConstants::Physics::GroundRestitution;
00535             }
00536             limit = m_maxBound.y - radius;
00537             if (position.y > limit)
00538             {
00539                 position.y = limit;
00540                 velocity.y = -velocity.y * GameConstants::Physics::GroundRestitution;
00541             }
00542             limit = m_minBound.z + radius;
00543             if (position.z < limit)
00544             {
00545                 position.z = limit;
00546                 velocity.z = -velocity.z * GameConstants::Physics::GroundRestitution;
00547             }
00548             limit = m_maxBound.z - radius;
00549             if (position.z > limit)
00550             {
00551                 position.z = limit;
00552                 velocity.z = -velocity.z * GameConstants::Physics::GroundRestitution;
00553             }
00554             m_player->Position(position);
00555             m_player->Velocity(velocity);
00556         }
00557
00558         // Animate the ammo.
00559         if (m_ammoCount > 0)
00560         {
00561             // Check for collisions between ammo.
00562 #pragma region inter-ammo collision detection
00563             if (m_ammoCount > 1)
00564             {
00565                 for (uint32_t one = 0; one < m_ammoCount; one++)
00566                 {
00567                     for (uint32_t two = (one + 1); two < m_ammoCount; two++)
00568                     {
00569                         // Check collision between instances One and Two.
00570                         // OneToTwo is the vector between the centers of the two ammo that are being checked.
00571                         XMVECTOR oneToTwo;
00572                         oneToTwo = m_ammo[two]->VectorPosition() - m_ammo[one]->VectorPosition();
00573                         float distanceSquared;
00574                         distanceSquared = XMVectorGetX(
00575                             XMVector3LengthSq(oneToTwo)
00576                             );
00577                         if (distanceSquared < (GameConstants::AmmoSize * GameConstants::AmmoSize))
00578                         {
00579                             // The two ammo are intersecting.
00580                             oneToTwo = XMVector3Normalize(oneToTwo);
00581
00582                             // Check if the two instances are already moving away from each other.
00583                             // If so, skip collision. This can happen when a lot of instances are
00584                             // bunched up next to each other.
00585                             float impact;
00586                             impact = XMVectorGetX(
00587                                 XMVector3Dot(oneToTwo, m_ammo[one]->VectorVelocity()) -
00588                                 XMVector3Dot(oneToTwo, m_ammo[two]->VectorVelocity())
00589                                 );
00590                             if (impact > 0.0f)
00591                             {
00592                                 // Compute the normal and tangential components of one's velocity.
00593                                 XMVECTOR velocityOne = (1 - GameConstants::Physics::BounceLost) * m_ammo[one]->VectorVelocity();
00594                                 XMVECTOR velocityOneNormal = XMVector3Dot(oneToTwo, velocityOne) * oneToTwo;
00595                                 XMVECTOR velocityOneTangent = velocityOne - velocityOneNormal;
00596                                 // Compute the normal and tangential components of two's velocity.
00597                                 XMVECTOR velocityTwo = (1 - GameConstants::Physics::BounceLost) * m_ammo[two]->VectorVelocity();
00598                                 XMVECTOR velocityTwoNormal = XMVector3Dot(oneToTwo, velocityTwo) * oneToTwo;
00599                                 XMVECTOR velocityTwoTangent = velocityTwo - velocityTwoNormal;
00600
00601                                 // Compute the post-collision velocities.
00602                                 m_ammo[one]->Velocity(velocityOneTangent - velocityOneNormal * (1 - GameConstants::Physics::BounceTransfer) +
00603                                     velocityTwoNormal * GameConstants::Physics::BounceTransfer
00604                                     );
00605                                 m_ammo[two]->Velocity(velocityTwoTangent - velocityTwoNormal * (1 - GameConstants::Physics::BounceTransfer) +
00606                                     velocityOneNormal * GameConstants::Physics::BounceTransfer
00607                                     );
00608
00609                                 // Fix the positions so that the two balls are exactly GameConstants::AmmoSize apart.
00610                                 float distanceToMove = (GameConstants::AmmoSize - sqrtf(distanceSquared)) * 0.5f;
00611                                 m_ammo[one]->Position(m_ammo[one]->VectorPosition() - (oneToTwo * distanceToMove));
00612                                 m_ammo[two]->Position(m_ammo[two]->VectorPosition() + (oneToTwo * distanceToMove));
00613
00614                                 // Flag the two instances so that they are not laying on ground.
00615                                 m_ammo[one]->OnGround(false);
00616                                 m_ammo[two]->OnGround(false);
00617
00618                                 // Start playing the sounds for the impact between the two balls.
00619                                 m_ammo[one]->PlaySound(impact, m_player->Position());
00620                                 m_ammo[two]->PlaySound(impact, m_player->Position());
00621                             }
00622                         }
00623                     }
00624                 }
00625             }
00626 #pragma endregion
00627
00628 #pragma region Ammo-Object intersections
00629             // Check for intersections between the ammo and the other objects in the scene.
00630             for (uint32_t one = 0; one < m_ammoCount; one++)
00631             {
00632                 if (m_objects.size() > 0)
00633                 {
00634                     if (!m_ammo[one]->OnGround())
00635                     {
00636                         for (uint32_t i = 0; i < m_objects.size(); i++)
00637                         {
00638                             if (m_objects[i]->Active())
00639                             {
00640                                 // The object is currently active in the scene. There may be objects in the list
00641                                 // that are currently inactive, so those are skipped.
00642                                 XMFLOAT3 contact;
00643                                 XMFLOAT3 normal;
00644
00645                                 if (m_objects[i]->IsTouching(m_ammo[one]->Position(), GameConstants::AmmoRadius, &contact, &normal))
00646                                 {
00647                                     // Ball is in contact with Object.
00648                                     XMVECTOR oneToTwo;
00649                                     oneToTwo = -XMLoadFloat3(&normal);
00650
00651                                     float impact;
00652                                     impact = XMVectorGetX(
00653                                         XMVector3Dot(oneToTwo, m_ammo[one]->VectorVelocity())
00654                                         );
00655                                     // Make sure that the ball is actually headed towards the object. At grazing angles there
00656                                     // could appear to be an impact when the ball is actually already hit and moving away.
00657                                     if (impact > 0.0f)
00658                                     {
00659                                         // Compute the normal and tangential components of the ammo's velocity.
00660                                         XMVECTOR velocityOne = (1 - GameConstants::Physics::BounceLost) * m_ammo[one]->VectorVelocity();
00661                                         XMVECTOR velocityOneNormal = XMVector3Dot(oneToTwo, velocityOne) * oneToTwo;
00662                                         XMVECTOR velocityOneTangent = velocityOne - velocityOneNormal;
00663
00664                                         // Compute post-collision velocity of the ammo.
00665                                         m_ammo[one]->Velocity(velocityOneTangent - velocityOneNormal * (1 - GameConstants::Physics::BounceTransfer));
00666
00667                                         // Fix the position so that the ball is exactly GameConstants::AmmoRadius from target.
00668                                         float distanceToMove = GameConstants::AmmoSize;
00669                                         m_ammo[one]->Position(XMLoadFloat3(&contact) - (oneToTwo * distanceToMove));
00670
00671                                         // Flag the Ammo as not laying on ground.
00672                                         m_ammo[one]->OnGround(false);
00673
00674                                         // Play the sound associated with the Ammo hitting something.
00675                                         m_ammo[one]->PlaySound(impact, m_player->Position());
00676
00677                                         if (m_objects[i]->Target() && !m_objects[i]->Hit())
00678                                         {
00679                                             // The object is a target and isn't currently hit, so mark it as hit and
00680                                             // play the sound associated with the impact.
00681                                             m_objects[i]->Hit(true);
00682                                             m_objects[i]->HitTime(timeTotal);
00683                                             m_totalHits++;
00684
00685                                             m_objects[i]->PlaySound(impact, m_player->Position());
00686                                         }
00687                                     }
00688                                 }
00689                             }
00690                         }
00691                     }
00692                 }
00693             }
00694 #pragma endregion
00695
00696 #pragma region Apply Gravity and world intersection
00697             // Apply gravity and check for collision against enclosing volume.
00698             for (uint32_t i = 0; i < m_ammoCount; i++)
00699             {
00700                 // Update the position and velocity of the ammo instance.
00701                 m_ammo[i]->Position(m_ammo[i]->VectorPosition() + m_ammo[i]->VectorVelocity() * elapsedFrameTime);
00702
00703                 XMFLOAT3 velocity = m_ammo[i]->Velocity();
00704                 XMFLOAT3 position = m_ammo[i]->Position();
00705
00706                 velocity.x -= velocity.x * 0.1f * elapsedFrameTime;
00707                 velocity.z -= velocity.z * 0.1f * elapsedFrameTime;
00708                 if (!m_ammo[i]->OnGround())
00709                 {
00710                     // Apply gravity if the ammo instance is not already resting on the ground.
00711                     velocity.y -= GameConstants::Physics::Gravity * elapsedFrameTime;
00712                 }
00713
00714                 if (!m_ammo[i]->OnGround())
00715                 {
00716                     float limit = m_minBound.y + GameConstants::AmmoRadius;
00717                     if (position.y < limit)
00718                     {
00719                         // The ammo instance hit the ground.
00720                         // Align the ammo instance to the ground, invert the Y component of the velocity and
00721                         // play the impact sound. The X and Z velocity components will be reduced
00722                         // because of friction.
00723                         position.y = limit;
00724                         m_ammo[i]->PlaySound(-velocity.y, m_player->Position());
00725
00726                         velocity.y = -velocity.y * GameConstants::Physics::GroundRestitution;
00727                         velocity.x *= GameConstants::Physics::Friction;
00728                         velocity.z *= GameConstants::Physics::Friction;
00729                     }
00730                 }
00731                 else
00732                 {
00733                     // The ammo instance is resting or rolling on ground.
00734                     // X and Z velocity components are reduced because of friction.
00735                     velocity.x *= GameConstants::Physics::Friction;
00736                     velocity.z *= GameConstants::Physics::Friction;
00737                 }
00738
00739                 float limit = m_maxBound.y - GameConstants::AmmoRadius;
00740                 if (position.y > limit)
00741                 {
00742                     // The ammo instance hit the ceiling.
00743                     // Align the ammo instance to the ceiling, invert the Y component of the velocity and
00744                     // play the impact sound. The X and Z velocity components will be reduced
00745                     // because of friction.
00746                     position.y = limit;
00747                     m_ammo[i]->PlaySound(-velocity.y, m_player->Position());
00748
00749                     velocity.y = -velocity.y * GameConstants::Physics::GroundRestitution;
00750                     velocity.x *= GameConstants::Physics::Friction;
00751                     velocity.z *= GameConstants::Physics::Friction;
00752                 }
00753
00754                 limit = m_minBound.y + GameConstants::AmmoRadius;
00755                 if ((GameConstants::Physics::Gravity * (position.y - limit) + 0.5f * velocity.y * velocity.y) < GameConstants::Physics::RestThreshold)
00756                 {
00757                     // The Y velocity component is below the resting threshold so flag the instance as
00758                     // laying on the ground and set the Y velocity component to zero.
00759                     position.y = limit;
00760                     velocity.y = 0.0f;
00761                     m_ammo[i]->OnGround(true);
00762                 }
00763
00764                 limit = m_minBound.z + GameConstants::AmmoRadius;
00765                 if (position.z < limit)
00766                 {
00767                     // The ammo instance hit the a wall in the min Z direction.
00768                     // Align the ammo instance to the wall, invert the Z component of the velocity and
00769                     // play the impact sound.
00770                     position.z = limit;
00771                     m_ammo[i]->PlaySound(-velocity.z, m_player->Position());
00772                     velocity.z = -velocity.z * GameConstants::Physics::GroundRestitution;
00773                 }
00774
00775                 limit = m_maxBound.z - GameConstants::AmmoRadius;
00776                 if (position.z > limit)
00777                 {
00778                     // The ammo instance hit the a wall in the max Z direction.
00779                     // Align the ammo instance to the wall, invert the Z component of the velocity and
00780                     // play the impact sound.
00781                     position.z = limit;
00782                     m_ammo[i]->PlaySound(-velocity.z, m_player->Position());
00783                     velocity.z = -velocity.z * GameConstants::Physics::GroundRestitution;
00784                 }
00785
00786                 limit = m_minBound.x + GameConstants::AmmoRadius;
00787                 if (position.x < limit)
00788                 {
00789                     // The ammo instance hit the a wall in the min X direction.
00790                     // Align the ammo instance to the wall, invert the X component of the velocity and
00791                     // play the impact sound.
00792                     position.x = limit;
00793                     m_ammo[i]->PlaySound(-velocity.x, m_player->Position());
00794                     velocity.x = -velocity.x * GameConstants::Physics::GroundRestitution;
00795                 }
00796
00797                 limit = m_maxBound.x - GameConstants::AmmoRadius;
00798                 if (position.x > limit)
00799                 {
00800                     // The ammo instance hit the a wall in the max X direction.
00801                     // Align the ammo instance to the wall, invert the X component of the velocity and
00802                     // play the impact sound.
00803                     position.x = limit;
00804                     m_ammo[i]->PlaySound(-velocity.x, m_player->Position());
00805                     velocity.x = -velocity.x * GameConstants::Physics::GroundRestitution;
00806                 }
00807
00808                 // Save the updated velocity and position for the ammo instance.
00809                 m_ammo[i]->Velocity(velocity);
00810                 m_ammo[i]->Position(position);
00811             }
00812         }
00813     }
00814 #pragma endregion
00815 }
00816
00817 void Simple3DGame::SaveState()
00818 {
00819     // Save basic state of the game.
00820     m_savedState.SaveBool(L":GameActive", m_gameActive);
00821     m_savedState.SaveBool(L":LevelActive", m_levelActive);
00822     m_savedState.SaveInt32(L":LevelCompleted", m_currentLevel);
00823     m_savedState.SaveInt32(L":TotalShots", m_totalShots);
00824     m_savedState.SaveInt32(L":TotalHits", m_totalHits);
00825     m_savedState.SaveSingle(L":BonusRoundTime", m_levelBonusTime);
00826     m_savedState.SaveXMFLOAT3(L":PlayerPosition", m_player->Position());
00827     m_savedState.SaveXMFLOAT3(L":PlayerLookDirection", m_controller->LookDirection());
00828
00829     if (m_levelActive)
00830     {
00831         // The game is currently in the middle of a level, so save the extended state of
00832         // the game.
00833         m_savedState.SaveSingle(L":LevelDuration", m_levelDuration);
00834         m_savedState.SaveSingle(L":LevelPlayingTime", m_timer.PlayingTime());
00835
00836         m_savedState.SaveInt32(L":AmmoCount", m_ammoCount);
00837         m_savedState.SaveInt32(L":AmmoNext", m_ammoNext);
00838
00839         const int bufferLength = 16;
00840         wchar_t str[bufferLength];
00841
00842         for (uint32_t i = 0; i < m_ammoCount; i++)
00843         {
00844             int len = swprintf_s(str, bufferLength, L"%d", i);
00845             auto string{ winrt::hstring(str, len) };
00846
00847             m_savedState.SaveBool(L":AmmoActive" + string, m_ammo[i]->Active());
00848             m_savedState.SaveXMFLOAT3(L":AmmoPosition" + string, m_ammo[i]->Position());
00849             m_savedState.SaveXMFLOAT3(L":AmmoVelocity" + string, m_ammo[i]->Velocity());
00850         }
00851
00852         m_savedState.SaveInt32(L":ObjectCount", static_cast<int>(m_objects.size()));
00853
00854         for (uint32_t i = 0; i < m_objects.size(); i++)
00855         {
00856             int len = swprintf_s(str, bufferLength, L"%d", i);
00857             auto string{ winrt::hstring(str, len) };
00858
00859             m_savedState.SaveBool(L":ObjectActive" + string, m_objects[i]->Active());
00860             m_savedState.SaveBool(L":ObjectTarget" + string, m_objects[i]->Target());
00861             m_savedState.SaveXMFLOAT3(L":ObjectPosition" + string, m_objects[i]->Position());
00862         }
00863
00864         m_level[m_currentLevel]->SaveState(m_savedState);
00865     }
00866 }
00867
00868 void Simple3DGame::LoadState()
00869 {
00870     m_gameActive = m_savedState.LoadBool(L":GameActive", m_gameActive);
00871     m_levelActive = m_savedState.LoadBool(L":LevelActive", m_levelActive);
00872
00873     if (m_gameActive)
00874     {
00875         // Loading from the last known state means the game wasn't finished when it was last played,
00876         // so set the current level.
00877
00878         m_totalShots = m_savedState.LoadInt32(L":TotalShots", 0);
00879         m_totalHits = m_savedState.LoadInt32(L":TotalHits", 0);
00880         m_currentLevel = m_savedState.LoadInt32(L":LevelCompleted", 0);
00881         m_levelBonusTime = m_savedState.LoadSingle(L":BonusRoundTime", 0.0f);
00882
00883         m_levelTimeRemaining = m_levelBonusTime;
00884
00885         // Reload the current player position and set both the camera and the controller
00886         // with the current Look Direction.
00887         m_player->Position(
00888             m_savedState.LoadXMFLOAT3(L":PlayerPosition", XMFLOAT3(0.0f, 0.0f, 0.0f))
00889             );
00890         m_camera.Eye(m_player->Position());
00891         m_camera.LookDirection(
00892             m_savedState.LoadXMFLOAT3(L":PlayerLookDirection", XMFLOAT3(0.0f, 0.0f, 1.0f))
00893             );
00894         m_controller->Pitch(m_camera.Pitch());
00895         m_controller->Yaw(m_camera.Yaw());
00896     }
00897     else
00898     {
00899         // The game was not being played when it was last saved, so initialize to the beginning.
00900         m_currentLevel = 0;
00901         m_levelBonusTime = 0;
00902     }
00903 }
00904
00905 void Simple3DGame::SetCurrentLevelToSavedState()
00906 {
00907     if (m_gameActive)
00908     {
00909         if (m_levelActive)
00910         {
00911             // Middle of a level so restart where left off.
00912             m_levelDuration = m_savedState.LoadSingle(L":LevelDuration", 0.0f);
00913
00914             m_timer.Reset();
00915             m_timer.PlayingTime(m_savedState.LoadSingle(L":LevelPlayingTime", 0.0f));
00916
00917             m_ammoCount = m_savedState.LoadInt32(L":AmmoCount", 0);
00918
00919             m_ammoNext = m_savedState.LoadInt32(L":AmmoNext", 0);
00920
00921             const int bufferLength = 16;
00922             wchar_t str[bufferLength];
00923
00924             for (uint32_t i = 0; i < m_ammoCount; i++)
00925             {
00926                 int len = swprintf_s(str, bufferLength, L"%d", i);
00927                 auto string{ winrt::hstring(str, len) };
00928
00929                 m_ammo[i]->Active(
00930                     m_savedState.LoadBool(
00931                         L":AmmoActive" + string,
00932                         m_ammo[i]->Active()
00933                         )
00934                     );
00935                 if (m_ammo[i]->Active())
00936                 {
00937                     m_ammo[i]->OnGround(false);
00938                 }
00939
00940                 m_ammo[i]->Position(
00941                     m_savedState.LoadXMFLOAT3(
00942                         L":AmmoPosition" + string,
00943                         m_ammo[i]->Position()
00944                         )
00945                     );
00946
00947                 m_ammo[i]->Velocity(
00948                     m_savedState.LoadXMFLOAT3(
00949                         L":AmmoVelocity" + string,
00950                         m_ammo[i]->Velocity()
00951                         )
00952                     );
00953             }
00954
00955             int storedObjectCount = 0;
00956             storedObjectCount = m_savedState.LoadInt32(L":ObjectCount", 0);
00957
00958             storedObjectCount = min(storedObjectCount, static_cast<int>(m_objects.size()));
00959
00960             for (int i = 0; i < storedObjectCount; i++)
00961             {
00962                 int len = swprintf_s(str, bufferLength, L"%d", i);
00963                 auto string{ winrt::hstring(str, len) };
00964
00965                 m_objects[i]->Active(
00966                     m_savedState.LoadBool(
00967                         L":ObjectActive" + string,
00968                         m_objects[i]->Active()
00969                         )
00970                     );
00971
00972                 m_objects[i]->Target(
00973                     m_savedState.LoadBool(
00974                         L":ObjectTarget" + string,
00975                         m_objects[i]->Target()
00976                         )
00977                     );
00978
00979                 m_objects[i]->Position(
00980                     m_savedState.LoadXMFLOAT3(
00981                         L":ObjectPosition" + string,
00982                         m_objects[i]->Position()
00983                         )
00984                     );
00985             }
00986
00987             m_level[m_currentLevel]->LoadState(m_savedState);
00988             m_levelTimeRemaining = m_level[m_currentLevel]->TimeLimit() + m_levelBonusTime - m_timer.PlayingTime();
00989         }
00990     }
00991 }
00992
00993 void Simple3DGame::SaveHighScore()
00994 {
00995     m_savedState.SaveInt32(L":HighScore:LevelCompleted", m_topScore.levelCompleted);
00996     m_savedState.SaveInt32(L":HighScore:TotalShots", m_topScore.totalShots);
00997     m_savedState.SaveInt32(L":HighScore:TotalHits", m_topScore.totalHits);
00998 }
00999
01000 void Simple3DGame::LoadHighScore()
01001 {
01002     m_topScore.levelCompleted = m_savedState.LoadInt32(L":HighScore:LevelCompleted", 0);
01003     m_topScore.totalShots = m_savedState.LoadInt32(L":HighScore:TotalShots", 0);
01004     m_topScore.totalHits = m_savedState.LoadInt32(L":HighScore:TotalHits", 0);
01005 }
01006
01007 void Simple3DGame::InitializeAmmo()
01008 {
01009     m_ammoCount = 0;
01010     m_ammoNext = 0;
01011     for (uint32_t i = 0; i < GameConstants::MaxAmmo; i++)
01012     {
01013         m_ammo[i]->Active(false);
01014     }
01015 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_WatchUsers Member List

This is the complete list of members for Scenario2_WatchUsers, including all inherited members.
FindModelByUserId(hstring const &userId) | Scenario2_WatchUsers | [private]
GetDisplayNameOrGenericNameAsync(Windows::System::User user) | Scenario2_WatchUsers | [private]
OnEnumerationCompleted(Windows::System::UserWatcher const &, IInspectable const &e) | Scenario2_WatchUsers | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario2_WatchUsers |
OnUserAdded(Windows::System::UserWatcher const &, Windows::System::UserChangedEventArgs const &e) | Scenario2_WatchUsers | [private]
OnUserRemoved(Windows::System::UserWatcher const &, Windows::System::UserChangedEventArgs const &e) | Scenario2_WatchUsers | [private]
OnUserUpdated(Windows::System::UserWatcher const &, Windows::System::UserChangedEventArgs const &e) | Scenario2_WatchUsers | [private]
OnWatcherStopped(Windows::System::UserWatcher const &, IInspectable const &e) | Scenario2_WatchUsers | [private]
Scenario2_WatchUsers() | Scenario2_WatchUsers |
StartWatching() | Scenario2_WatchUsers |
StopWatching() | Scenario2_WatchUsers |
userNumber | Scenario2_WatchUsers | [private]
users | Scenario2_WatchUsers | [private]
Users() | Scenario2_WatchUsers | [inline]
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Scenario8_VisitsBackgroundTask.cpp Source File

  • Geolocation
  • cppwinrt

Scenario8_VisitsBackgroundTask.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SampleConfiguration.h"
00014 #include "Scenario8_VisitsBackgroundTask.h"
00015 #include "Scenario8_VisitsBackgroundTask.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::ApplicationModel::Background;
00019 using namespace winrt::Windows::Foundation;
00020 using namespace winrt::Windows::Devices::Geolocation;
00021 using namespace winrt::Windows::UI::Xaml;
00022 using namespace winrt::Windows::UI::Xaml::Navigation;
00023
00024 namespace winrt::SDKTemplate::implementation
00025 {
00026     Scenario8_VisitsBackgroundTask::Scenario8_VisitsBackgroundTask()
00027     {
00028         InitializeComponent();
00029     }
00030
00031     void Scenario8_VisitsBackgroundTask::OnNavigatedTo(NavigationEventArgs const&)
00032     {
00033         // See if our background task is already registered.
00034         m_visitTask = LookupBackgroundTask(BackgroundTaskName);
00035
00036         if (m_visitTask != nullptr)
00037         {
00038             // Associate an event handler with the existing background task
00039             m_taskCompletedToken = m_visitTask.Completed({ get_weak(), &Scenario8_VisitsBackgroundTask::OnCompleted });
00040         }
00041         FillEventListBoxWithExistingEvents();
00042         UpdateButtonStates();
00043     }
00044
00045     void Scenario8_VisitsBackgroundTask::RegisterBackgroundTask(IInspectable const&, RoutedEventArgs const&)
00046     {
00047         // Register the background task without checking whether the user has enabled background execution.
00048         // If it's disabled, and then the user later enables background execution, the background task will be ready to run.
00049         // Create a new background task builder
00050         BackgroundTaskBuilder visitTaskBuilder;
00051
00052         visitTaskBuilder.Name(BackgroundTaskName);
00053         visitTaskBuilder.TaskEntryPoint(BackgroundTaskEntryPoint);
00054
00055         // Create a new location trigger
00056         GeovisitTrigger trigger;
00057
00058         // Set the desired monitoring scope.
00059         // For higher granularity such as venue/building level changes, choose venue.
00060         // For lower granularity more or less in the range of zipcode level changes, choose city.
00061         // Choosing Venue here as an example.
00062         trigger.MonitoringScope(VisitMonitoringScope::Venue);
00063
00064         // Associate the trigger with the background task builder
00065         visitTaskBuilder.SetTrigger(trigger);
00066
00067         // Register the background task
00068         m_visitTask = visitTaskBuilder.Register();
00069
00070         // Associate an event handler with the new background task
00071         m_taskCompletedToken = m_visitTask.Completed({ get_weak(), &Scenario8_VisitsBackgroundTask::OnCompleted });
00072
00073         UpdateButtonStates();
00074         CheckBackgroundAndRequestLocationAccess();
00075     }
00076
00077     void Scenario8_VisitsBackgroundTask::UnregisterBackgroundTask(IInspectable const&, RoutedEventArgs const&)
00078     {
00079         // Unregister the background task
00080         if (m_visitTask != nullptr)
00081         {
00082             m_visitTask.Unregister(true);
00083             m_visitTask.Completed(m_taskCompletedToken);
00084             m_visitTask = nullptr;
00085         }
00086
00087         m_rootPage.NotifyUser(L"Geofence background task unregistered", NotifyType::StatusMessage);
00088         UpdateButtonStates();
00089     }
00090
00091     // This event handler is called when the background task is completed.
00092     fire_and_forget Scenario8_VisitsBackgroundTask::OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
00093     {
00094         auto lifetime = get_strong();
00095
00096         // Update the UI with progress reported by the background task
00097         co_await resume_foreground(Dispatcher());
00098
00099         try
00100         {
00101             // Rethrow any exception that occurred in the background task.
00102             e.CheckResult();
00103
00104             // Update the UI with the completion status of the background task
00105             ReportSavedStatus();
00106             FillEventListBoxWithExistingEvents();
00107         }
00108         catch (...)
00109         {
00110             // The background task had an error
00111             m_rootPage.NotifyUser(to_message(), NotifyType::ErrorMessage);
00112         }
00113     }
00114
00115     // Update the enable state of the register/unregister buttons
00116     // based on whether we have already registered a task.
00117     void Scenario8_VisitsBackgroundTask::UpdateButtonStates()
00118     {
00119         bool registered = (m_visitTask != nullptr);
00120         RegisterBackgroundTaskButton().IsEnabled(!registered);
00121         UnregisterBackgroundTaskButton().IsEnabled(registered);
00122     }
00123
00124     void Scenario8_VisitsBackgroundTask::FillEventListBoxWithExistingEvents()
00125     {
00126         FillItemsFromSavedJson(VisitBackgroundEventsListBox(), L"BackgroundVisitEventCollection");
00127     }
00128 }
Generated on Fri Nov 15 2024 22:19:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

UnspecifiedReason Member List

This is the complete list of members for UnspecifiedReason, including all inherited members.
BeginExtendedExecution() | UnspecifiedReason | [inline, private]
ClearExtendedExecution() | UnspecifiedReason | [inline, private]
EndExtendedExecution() | UnspecifiedReason | [inline, private]
OnNavigatingFrom(NavigatingCancelEventArgs e) | UnspecifiedReason | [inline, protected]
OnTimer(object state) | UnspecifiedReason | [inline, private]
periodicTimer | UnspecifiedReason | [private]
rootPage | UnspecifiedReason | [private]
session | UnspecifiedReason | [private]
SessionRevoked(object sender, ExtendedExecutionRevokedEventArgs args) | UnspecifiedReason | [inline, private]
UnspecifiedReason() | UnspecifiedReason | [inline]
UpdateUI() | UnspecifiedReason | [inline, private]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDataVirtualization/cs/MainPage.xaml.cs Source File

  • XamlDataVirtualization
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Data;
00017 using Windows.UI.Xaml.Media;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class MainPage : Page
00028     {
00029         public static MainPage Current;
00030
00031         public MainPage()
00032         {
00033             this.InitializeComponent();
00034
00035             // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00036             // in order to call methods that are in this class.
00037             Current = this;
00038             SampleTitle.Text = FEATURE_NAME;
00039         }
00040
00041         protected override void OnNavigatedTo(NavigationEventArgs e)
00042         {
00043             // Populate the scenario list from the SampleConfiguration.cs file
00044             ScenarioControl.ItemsSource = scenarios;
00045             if (Window.Current.Bounds.Width < 640)
00046             {
00047                 ScenarioControl.SelectedIndex = -1;
00048             }
00049             else
00050             {
00051                 ScenarioControl.SelectedIndex = 0;
00052             }
00053         }
00054
00055         /// <summary>
00056         /// Called whenever the user changes selection in the scenarios list.  This method will navigate to the respective
00057         /// sample scenario page.
00058         /// </summary>
00059         /// <param name="sender"></param>
00060         /// <param name="e"></param>
00061         private void ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
00062         {
00063             // Clear the status block when navigating scenarios.
00064             NotifyUser(String.Empty, NotifyType.StatusMessage);
00065
00066             ListBox scenarioListBox = sender as ListBox;
00067             Scenario s = scenarioListBox.SelectedItem as Scenario;
00068             if (s != null)
00069             {
00070                 ScenarioFrame.Navigate(s.ClassType);
00071                 if (Window.Current.Bounds.Width < 640)
00072                 {
00073                     Splitter.IsPaneOpen = false;
00074                     StatusBorder.Visibility = Visibility.Collapsed;
00075                 }
00076             }
00077         }
00078
00079         public List<Scenario> Scenarios
00080         {
00081             get { return this.scenarios; }
00082         }
00083
00084         /// <summary>
00085         /// Used to display messages to the user
00086         /// </summary>
00087         /// <param name="strMessage"></param>
00088         /// <param name="type"></param>
00089         public void NotifyUser(string strMessage, NotifyType type)
00090         {
00091             switch (type)
00092             {
00093                 case NotifyType.StatusMessage:
00094                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green);
00095                     break;
00096                 case NotifyType.ErrorMessage:
00097                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red);
00098                     break;
00099             }
00100             StatusBlock.Text = strMessage;
00101
00102             // Collapse the StatusBlock if it has no text to conserve real estate.
00103             StatusBorder.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed;
00104         }
00105
00106         async void Footer_Click(object sender, RoutedEventArgs e)
00107         {
00108             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00109         }
00110
00111         private void Button_Click(object sender, RoutedEventArgs e)
00112         {
00113             Splitter.IsPaneOpen = !Splitter.IsPaneOpen;
00114             StatusBorder.Visibility = Visibility.Collapsed;
00115         }
00116     }
00117     public enum NotifyType
00118     {
00119         StatusMessage,
00120         ErrorMessage
00121     };
00122
00123     public class ScenarioBindingConverter : IValueConverter
00124     {
00125         public object Convert(object value, Type targetType, object parameter, string language)
00126         {
00127             Scenario s = value as Scenario;
00128             return (MainPage.Current.Scenarios.IndexOf(s) + 1) + ") " + s.Title;
00129         }
00130
00131         public object ConvertBack(object value, Type targetType, object parameter, string language)
00132         {
00133             return true;
00134         }
00135     }
00136 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FullScreenMode/cppwinrt/pch.cpp Source File

  • FullScreenMode
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/Data/Common/VideoMetaData.cs Source File

  • AdvancedCasting
  • cs
  • Data
  • Common

VideoMetaData.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017
00018 namespace ScreenCasting.Data.Common
00019 {
00020     public class VideoMetaData
00021     {
00022         public string Id { get; set; }
00023         public string Title { get; set; }
00024         public DateTime PubDate { get; set; }
00025         public string License { get; set; }
00026         public Uri WebPageLink { get; set; }
00027         public Uri VideoLink { get; set; }
00028         public Uri Thumbnail { get; set; }
00029     }
00030 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/cs/Scenario1_LowLatency.xaml.cs Source File

  • SimpleCommunication
  • cs

Scenario1_LowLatency.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Microsoft.Samples.SimpleCommunication;
00013 using SDKTemplate;
00014 using System;
00015 using System.Threading.Tasks;
00016 using Windows.Media.Capture;
00017 using Windows.Media.MediaProperties;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00023
00024 namespace SimpleCommunication
00025 {
00026     /// <summary>
00027     /// An empty page that can be used on its own or navigated to within a Frame.
00028     /// </summary>
00029     public sealed partial class LowLatency : Page
00030     {
00031         private enum State
00032         {
00033             Initializing,
00034             Waiting,
00035             Previewing,
00036             Streaming,
00037             End
00038         }
00039
00040         private enum LatencyMode
00041         {
00042             NormalLatency,
00043             LowLatency
00044         }
00045
00046         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00047         // as NotifyUser()
00048         MainPage rootPage = MainPage.Current;
00049
00050         CaptureDevice device = null;
00051         State? currentState = null;
00052         State? previousState = null;
00053         VideoEncodingProperties previewEncodingProperties = null;
00054         LatencyMode? mode = null;
00055         const LatencyMode defaultMode = LatencyMode.NormalLatency;
00056
00057         public LowLatency()
00058         {
00059             this.InitializeComponent();
00060
00061             rootPage.EnsureMediaExtensionManager();
00062
00063             mode = LatencyMode.NormalLatency;
00064             LatencyModeToggle.IsOn = (mode == LatencyMode.LowLatency);
00065             rootPage.NotifyUser("Initializing...Please wait.", NotifyType.StatusMessage);
00066         }
00067
00068         /// <summary>
00069         /// The media element visible in the local host client area
00070         /// </summary>
00071         private MediaElement LocalhostVideo
00072         {
00073             get
00074             {
00075                 return (mode == LatencyMode.NormalLatency) ? PlaybackVideo : RealTimePlaybackVideo;
00076             }
00077         }
00078
00079         /// <summary>
00080         /// The media element hidden in the local host client area
00081         /// </summary>
00082         private MediaElement HiddenVideo
00083         {
00084             get
00085             {
00086                 return (mode == LatencyMode.NormalLatency) ? RealTimePlaybackVideo : PlaybackVideo;
00087             }
00088         }
00089
00090         /// <summarycancel
00091         /// Initializes the scenario
00092         /// </summary>
00093         /// <returns></returns>
00094         private async Task InitializeAsync()
00095         {
00096             var streamFilteringCriteria = new
00097             {
00098                 HorizontalResolution = (uint)480,
00099                 SubType = "YUY2"
00100             };
00101             currentState = State.Initializing;
00102             device = new CaptureDevice();
00103
00104             PreviewVideo.Visibility = Visibility.Collapsed;
00105             WebcamPreviewPoster.Visibility = Visibility.Visible;
00106             PreviewButton.Content = "Start Preview";
00107             LoopbackClientButton.IsEnabled = false;
00108
00109             mode = defaultMode;
00110             LatencyModeToggle.IsOn = (mode == LatencyMode.LowLatency);
00111             LatencyModeToggle.IsEnabled = false;
00112
00113             await device.InitializeAsync();
00114             var setting = await device.SelectPreferredCameraStreamSettingAsync(MediaStreamType.VideoPreview, ((x) =>
00115             {
00116                 var previewStreamEncodingProperty = x as Windows.Media.MediaProperties.VideoEncodingProperties;
00117
00118                 return (previewStreamEncodingProperty.Width >= streamFilteringCriteria.HorizontalResolution &&
00119                     previewStreamEncodingProperty.Subtype == streamFilteringCriteria.SubType);
00120             }));
00121
00122             previewEncodingProperties = setting as VideoEncodingProperties;
00123
00124             PreviewSetupCompleted();
00125         }
00126
00127         private void PreviewSetupCompleted()
00128         {
00129             device.CaptureFailed += Device_CaptureFailed;
00130             device.IncomingConnectionArrived += Device_IncomingConnectionArrived;
00131             previousState = currentState;
00132             PreviewButton.IsEnabled = true;
00133             rootPage.NotifyUser("Done. Tap or click 'Start Preview' button to start webcam preview", NotifyType.StatusMessage);
00134
00135             currentState = State.Waiting;
00136         }
00137
00138
00139         void Device_IncomingConnectionArrived(object sender, IncomingConnectionEventArgs e)
00140         {
00141             e.Accept();
00142         }
00143
00144         async void Device_CaptureFailed(object sender, MediaCaptureFailedEventArgs e)
00145         {
00146             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, (() =>
00147             {
00148                 rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage);
00149             }));
00150         }
00151
00152         async void Window_VisibilityChanged(object sender, Windows.UI.Core.VisibilityChangedEventArgs e)
00153         {
00154             if (!e.Visible)
00155             {
00156                 await CleanupAsync();
00157             }
00158             else
00159             {
00160                 try
00161                 {
00162                     await InitializeAsync();
00163                 }
00164                 catch (Exception err)
00165                 {
00166                     rootPage.NotifyUser("Camera initialization error: " + err.Message + "\n Try restarting the sample.", NotifyType.ErrorMessage);
00167                 }
00168             }
00169         }
00170
00171         /// <summary>
00172         /// Invoked when this page is about to be displayed in a Frame.
00173         /// </summary>
00174         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00175         /// property is typically used to configure the page.</param>
00176         protected async override void OnNavigatedTo(NavigationEventArgs e)
00177         {
00178             var cameraEnumTask = CaptureDevice.CheckForRecordingDeviceAsync();
00179
00180             var cameraFound = await cameraEnumTask;
00181
00182             if (cameraFound)
00183             {
00184                 try
00185                 {
00186                     await InitializeAsync();
00187
00188                     Window.Current.VisibilityChanged += Window_VisibilityChanged;
00189                 }
00190                 catch (Exception err)
00191                 {
00192                     rootPage.NotifyUser("Camera initialization error: " + err.Message + "\n Try restarting the sample.", NotifyType.ErrorMessage);
00193                 }
00194             }
00195             else
00196             {
00197                 rootPage.NotifyUser("A machine with a camera and a microphone is required to run this sample.", NotifyType.ErrorMessage);
00198             }
00199         }
00200
00201         protected async override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00202         {
00203             Window.Current.VisibilityChanged -= Window_VisibilityChanged;
00204             await CleanupAsync();
00205
00206             base.OnNavigatingFrom(e);
00207         }
00208
00209         /// <summary>
00210         /// This is the click handler for the 'Preview' button.  It starts or stops
00211         /// camera preview and streaming
00212         /// </summary>
00213         /// <param name="sender"></param>
00214         /// <param name="e"></param>
00215         private async void PreviewButton_Click(object sender, RoutedEventArgs e)
00216         {
00217             Button b = sender as Button;
00218             if (b != null && device != null)
00219             {
00220                 previousState = currentState;
00221                 try
00222                 {
00223                     switch (currentState)
00224                     {
00225                         case State.Waiting:
00226                             await Waiting_PreviewButtonClicked();
00227                             break;
00228                         case State.Previewing:
00229                             await Previewing_PreviewButtonClicked();
00230                             break;
00231                         case State.Streaming:
00232                             await Streaming_PreviewButtonClicked();
00233                             break;
00234                         default:
00235                             break;
00236                     }
00237                 }
00238                 catch (Exception exc)
00239                 {
00240                     rootPage.NotifyUser(exc.Message, NotifyType.ErrorMessage);
00241                 }
00242             }
00243         }
00244
00245         private async Task Previewing_PreviewButtonClicked()
00246         {
00247             Task stopPreviewTask = device.CaptureSource.StopPreviewAsync().AsTask();
00248
00249             PreviewVideo.Visibility = Visibility.Collapsed;
00250             WebcamPreviewPoster.Visibility = Visibility.Visible;
00251             PreviewButton.Content = "Start Preview";
00252             LoopbackClientButton.IsEnabled = false;
00253
00254             await stopPreviewTask;
00255             currentState = State.Waiting;
00256         }
00257
00258         private async Task Waiting_PreviewButtonClicked()
00259         {
00260             rootPage.NotifyUser("", NotifyType.StatusMessage);
00261             PreviewVideo.Source = device.CaptureSource;
00262             await device.CaptureSource.StartPreviewAsync();
00263
00264             WebcamPreviewPoster.Visibility = Visibility.Collapsed;
00265             PreviewVideo.Visibility = Visibility.Visible;
00266             PreviewButton.Content = "Stop Preview";
00267             LoopbackClientButton.IsEnabled = true;
00268
00269             currentState = State.Previewing;
00270         }
00271
00272         private async Task Streaming_PreviewButtonClicked()
00273         {
00274             LocalhostVideo.Stop();
00275             await device.StopRecordingAsync();
00276             LocalhostVideo.Source = null;
00277             await Previewing_PreviewButtonClicked();
00278
00279             mode = defaultMode;
00280             LatencyModeToggle.IsOn = (mode == LatencyMode.LowLatency);
00281             LatencyModeToggle.IsEnabled = false;
00282
00283             LocalhostVideo.Visibility = Windows.UI.Xaml.Visibility.Visible;
00284             HiddenVideo.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00285         }
00286
00287         /// <summary>
00288         /// This is the click handler for the 'LoopbackClient' button.  It displays captured video
00289         /// recieved over the localhost network interface using a custom network media sink and media
00290         /// sources via a custom scheme
00291         /// </summary>
00292         /// <param name="sender">The LoopbackClient button</param>
00293         /// <param name="e">The button click routed event arguments</param>
00294         private async void LoopbackClientButton_Click(object sender, RoutedEventArgs e)
00295         {
00296             Button b = sender as Button;
00297             if (b != null)
00298             {
00299                 previousState = currentState;
00300                 await StartRecordingToCustomSink();
00301
00302                 if (currentState == State.Previewing)
00303                 {
00304                     LocalhostVideo.Source = new Uri("stsp://localhost");
00305                     LatencyModeToggle.IsEnabled = true;
00306                     LoopbackClientButton.IsEnabled = false;
00307
00308                     currentState = State.Streaming;
00309                 }
00310             }
00311         }
00312
00313         private async Task StartRecordingToCustomSink()
00314         {
00315             // Use the MP4 preset to an obtain H.264 video encoding profile
00316             var mep = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga);
00317             mep.Audio = null;
00318             mep.Container = null;
00319             if (previewEncodingProperties != null)
00320             {
00321                 mep.Video.Width = previewEncodingProperties.Width;
00322                 mep.Video.Height = previewEncodingProperties.Height;
00323             }
00324
00325             await device.StartRecordingAsync(mep);
00326         }
00327
00328         private async void LatencyModeToggle_Toggled(object sender, RoutedEventArgs e)
00329         {
00330             if (currentState == State.Streaming)
00331             {
00332                 try
00333                 {
00334                     LocalhostVideo.Stop();
00335
00336                     await device.StopRecordingAsync();
00337                     mode = (mode == LatencyMode.NormalLatency) ? LatencyMode.LowLatency : LatencyMode.NormalLatency;
00338                     await StartRecordingToCustomSink();
00339
00340                     HiddenVideo.Source = null;
00341                     LocalhostVideo.Source = new Uri("stsp://localhost");
00342
00343                     LocalhostVideo.Visibility = Windows.UI.Xaml.Visibility.Visible;
00344                     HiddenVideo.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00345                 }
00346                 catch (Exception exc)
00347                 {
00348                     rootPage.NotifyUser(exc.Message, NotifyType.ErrorMessage);
00349                 }
00350             }
00351         }
00352
00353         private async Task CleanupAsync()
00354         {
00355             try
00356             {
00357                 if (currentState == State.Previewing || currentState == State.Streaming)
00358                 {
00359                     await device.CaptureSource.StopPreviewAsync();
00360
00361                     if (currentState == State.Streaming)
00362                     {
00363                         LocalhostVideo.Stop();
00364                     }
00365                 }
00366
00367
00368                 await device.CleanUpAsync();
00369             }
00370             catch (Exception)
00371             {
00372             }
00373             finally
00374             {
00375                 LocalhostVideo.Source = null;
00376             }
00377         }
00378     }
00379 }
Generated on Fri Nov 15 2024 22:21:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario2WinRTComponent/IOnboardingService.h Source File

  • AllJoyn
  • Common
  • Scenario2WinRTComponent

IOnboardingService.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #pragma once
00022
00023 namespace org { namespace alljoyn { namespace Onboarding {
00024
00025 public interface class IOnboardingService
00026 {
00027 public:
00028     // "Sends the personal AP information to the onboardee"
00029     // Implement this function to handle calls to the ConfigureWiFi method.
00030     Windows::Foundation::IAsyncOperation<OnboardingConfigureWiFiResult^>^ ConfigureWiFiAsync(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info , _In_ Platform::String^ interfaceMemberSSID, _In_ Platform::String^ interfaceMemberPassphrase, _In_ int16 interfaceMemberAuthType);
00031
00032     // "Tells the onboardee to connect to the personal AP"
00033     // Implement this function to handle calls to the Connect method.
00034     Windows::Foundation::IAsyncOperation<OnboardingConnectResult^>^ ConnectAsync(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info );
00035
00036     // "Tells the onboardee to disconnect from the personal AP"
00037     // Implement this function to handle calls to the Offboard method.
00038     Windows::Foundation::IAsyncOperation<OnboardingOffboardResult^>^ OffboardAsync(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info );
00039
00040     // "Scans all the Wi-Fi access points in the onboardee's proximity"
00041     // Implement this function to handle calls to the GetScanInfo method.
00042     Windows::Foundation::IAsyncOperation<OnboardingGetScanInfoResult^>^ GetScanInfoAsync(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info );
00043
00044     // "Interface version number"
00045     // Implement this function to handle requests for the value of the Version property.
00046     //
00047     // Currently, info will always be null, because no information is available about the requestor.
00048     Windows::Foundation::IAsyncOperation<OnboardingGetVersionResult^>^ GetVersionAsync(Windows::Devices::AllJoyn::AllJoynMessageInfo^ info);
00049
00050     // "The configuration state"
00051     // Implement this function to handle requests for the value of the State property.
00052     //
00053     // Currently, info will always be null, because no information is available about the requestor.
00054     Windows::Foundation::IAsyncOperation<OnboardingGetStateResult^>^ GetStateAsync(Windows::Devices::AllJoyn::AllJoynMessageInfo^ info);
00055
00056     // "The last error code and error message"
00057     // Implement this function to handle requests for the value of the LastError property.
00058     //
00059     // Currently, info will always be null, because no information is available about the requestor.
00060     Windows::Foundation::IAsyncOperation<OnboardingGetLastErrorResult^>^ GetLastErrorAsync(Windows::Devices::AllJoyn::AllJoynMessageInfo^ info);
00061
00062 };
00063
00064 } } }
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/ShareImage.xaml.cpp Source File

  • ShareSource
  • cpp

ShareImage.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ShareImage.xaml.cpp
00014 // Implementation of the ShareImage class
00015 //
00016
00017 #include "pch.h"
00018 #include "ShareImage.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Platform::Collections;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Media::Imaging;
00026 using namespace Windows::Storage;
00027 using namespace Windows::Storage::Streams;
00028 using namespace Windows::Storage::Pickers;
00029 using namespace concurrency;
00030 using namespace Windows::ApplicationModel::DataTransfer;
00031
00032 ShareImage::ShareImage()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 bool ShareImage::GetShareContent(DataRequest^ request)
00038 {
00039     bool succeeded = false;
00040
00041     if (imageFile != nullptr)
00042     {
00043         auto requestData = request->Data;
00044         requestData->Properties->Title = TitleInputBox->Text;
00045         requestData->Properties->Description = DescriptionInputBox->Text; // The description is optional.
00046         requestData->Properties->ContentSourceApplicationLink = ApplicationLink;
00047
00048         // It's recommended to use both SetBitmap and SetStorageItems for sharing a single image
00049         // since the target app may only support one or the other.
00050
00051         auto imageItems = ref new Vector<IStorageItem^>();
00052         imageItems->Append(imageFile);
00053         requestData->SetStorageItems(imageItems);
00054
00055         auto imageStreamRef = RandomAccessStreamReference::CreateFromFile(imageFile);
00056         requestData->Properties->Thumbnail = imageStreamRef;
00057         requestData->SetBitmap(imageStreamRef);
00058         succeeded = true;
00059     }
00060     else
00061     {
00062         request->FailWithDisplayText("Select an image you would like to share and try again.");
00063     }
00064     return succeeded;
00065 }
00066
00067 void ShareImage::SelectImageButton_Click(Object^ sender, RoutedEventArgs^ e)
00068 {
00069     auto imagePicker = ref new FileOpenPicker();
00070     imagePicker->ViewMode = PickerViewMode::Thumbnail;
00071     imagePicker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00072     imagePicker->FileTypeFilter->Append(".jpg");
00073     imagePicker->FileTypeFilter->Append(".png");
00074     imagePicker->FileTypeFilter->Append(".bmp");
00075     imagePicker->FileTypeFilter->Append(".gif");
00076     imagePicker->FileTypeFilter->Append(".tif");
00077
00078     create_task(imagePicker->PickSingleFileAsync()).then([this](StorageFile^ pickedFile)
00079     {
00080         if (pickedFile != nullptr)
00081         {
00082             imageFile = pickedFile;
00083
00084             // Display the image in the UI.
00085             create_task(pickedFile->OpenAsync(FileAccessMode::Read)).then([this](IRandomAccessStream^ displayStream)
00086             {
00087                 auto bitmapImage = ref new BitmapImage();
00088                 bitmapImage->SetSource(displayStream);
00089                 ImageHolder->Source = bitmapImage;
00090             });
00091             MainPage::Current->NotifyUser("Selected " + imageFile->Name + ".", NotifyType::StatusMessage);
00092
00093             ShareStep->Visibility = Windows::UI::Xaml::Visibility::Visible;
00094         }
00095     });
00096 }
Generated on Fri Nov 15 2024 22:21:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cpp/MainPage.xaml.cpp Source File

  • 360VideoPlayback
  • cpp

MainPage.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // MainPage.xaml.cpp
00003 // Implementation of the MainPage class
00004 //
00005
00006 #include "pch.h"
00007 #include "MainPage.xaml.h"
00008 #include "VideoGallery.xaml.h"
00009
00010 using namespace _360VideoPlayback;
00011
00012 using namespace Platform;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::UI::Core;
00015 using namespace Windows::UI::Xaml::Interop;
00016
00017 // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
00018
00019 MainPage::MainPage()
00020 {
00021     InitializeComponent();
00022     SystemNavigationManager::GetForCurrentView()->BackRequested += ref new EventHandler<BackRequestedEventArgs^>(this, &MainPage::OnBackRequested);
00023     this->contentFrame->Navigate(TypeName(VideoGallery::typeid));
00024 }
00025
00026 void MainPage::OnBackRequested(Object^ sender, BackRequestedEventArgs^ args)
00027 {
00028     if (this->contentFrame->CanGoBack)
00029     {
00030         this->contentFrame->GoBack();
00031     }
00032 }
Generated on Fri Nov 15 2024 22:16:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStarterKit/cpp/MainPage.xaml.cpp Source File

  • CameraStarterKit
  • cpp

MainPage.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include <sstream>
00015
00016 using namespace Concurrency;
00017 using namespace Platform;
00018 using namespace CameraStarterKit;
00019 using namespace Windows::Devices::Enumeration;
00020 using namespace Windows::Devices::Sensors;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::Graphics::Imaging;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::Media;
00026 using namespace Windows::Phone::UI::Input;
00027 using namespace Windows::Storage;
00028 using namespace Windows::UI::Xaml;
00029 using namespace Windows::UI::Xaml::Controls;
00030 using namespace Windows::UI::Xaml::Controls::Primitives;
00031 using namespace Windows::UI::Xaml::Data;
00032 using namespace Windows::UI::Xaml::Input;
00033 using namespace Windows::UI::Xaml::Media;
00034 using namespace Windows::UI::Xaml::Navigation;
00035
00036 MainPage::MainPage()
00037     : _mediaCapture(nullptr)
00038     , _isInitialized(false)
00039     , _isPreviewing(false)
00040     , _isRecording(false)
00041     , _externalCamera(false)
00042     , _mirroringPreview(false)
00043     , _displayRequest(ref new Windows::System::Display::DisplayRequest())
00044     , RotationKey({ 0xC380465D, 0x2271, 0x428C,{ 0x9B, 0x83, 0xEC, 0xEA, 0x3B, 0x4A, 0x85, 0xC1 } })
00045     , _captureFolder(nullptr)
00046     , _rotationHelper(nullptr)
00047 {
00048     InitializeComponent();
00049
00050     _systemMediaControls = SystemMediaTransportControls::GetForCurrentView();
00051
00052     // Do not cache the state of the UI when suspending/navigating
00053     Page::NavigationCacheMode = Navigation::NavigationCacheMode::Disabled;
00054 }
00055
00056 MainPage::~MainPage()
00057 {
00058 }
00059
00060 /// <summary>
00061 /// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI
00062 /// </summary>
00063 /// <returns></returns>
00064 task<void> MainPage::InitializeCameraAsync()
00065 {
00066     WriteLine("InitializeCameraAsync");
00067
00068     // Get available devices for capturing pictures
00069     return FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel::Back)
00070         .then([this](DeviceInformation^ camera)
00071     {
00072         if (camera == nullptr)
00073         {
00074             WriteLine("No camera device found!");
00075             return;
00076         }
00077         // Figure out where the camera is located
00078         if (camera->EnclosureLocation == nullptr || camera->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Unknown)
00079         {
00080             // No information on the location of the camera, assume it's an external camera, not integrated on the device
00081             _externalCamera = true;
00082         }
00083         else
00084         {
00085             // Camera is fixed on the device
00086             _externalCamera = false;
00087
00088             // Only mirror the preview if the camera is on the front panel
00089             _mirroringPreview = (camera->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Front);
00090         }
00091
00092         // Initialize rotationHelper
00093         _rotationHelper = ref new CameraRotationHelper(camera->EnclosureLocation);
00094         _orientationChangedEventToken = _rotationHelper->OrientationChanged += ref new EventHandler<bool>(this, &MainPage::RotationHelper_OrientationChanged);
00095
00096         _mediaCapture = ref new Capture::MediaCapture();
00097
00098         // Register for a notification when video recording has reached the maximum time and when something goes wrong
00099         _recordLimitationExceededEventToken =
00100             _mediaCapture->RecordLimitationExceeded += ref new Capture::RecordLimitationExceededEventHandler(this, &MainPage::MediaCapture_RecordLimitationExceeded);
00101         _mediaCaptureFailedEventToken =
00102             _mediaCapture->Failed += ref new Capture::MediaCaptureFailedEventHandler(this, &MainPage::MediaCapture_Failed);
00103
00104         auto settings = ref new Capture::MediaCaptureInitializationSettings();
00105         settings->VideoDeviceId = camera->Id;
00106         settings->StreamingCaptureMode = Capture::StreamingCaptureMode::AudioAndVideo;
00107
00108         // Initialize media capture and start the preview
00109         create_task(_mediaCapture->InitializeAsync(settings))
00110             .then([this]()
00111         {
00112             _isInitialized = true;
00113
00114             return StartPreviewAsync()
00115                 .then([this]()
00116             {
00117                 UpdateCaptureControls();
00118             });
00119         }).then([this](task<void> previousTask)
00120         {
00121             try
00122             {
00123                 previousTask.get();
00124             }
00125             catch (AccessDeniedException^)
00126             {
00127                 WriteLine("The app was denied access to the camera");
00128             }
00129         });
00130     });
00131 }
00132
00133 /// <summary>
00134 /// Cleans up the camera resources (after stopping any video recording and/or preview if necessary) and unregisters from MediaCapture events
00135 /// </summary>
00136 /// <returns></returns>
00137 Concurrency::task<void> MainPage::CleanupCameraAsync()
00138 {
00139     WriteLine("CleanupCameraAsync");
00140
00141     std::vector<task<void>> taskList;
00142
00143     if (_isInitialized)
00144     {
00145         // If a recording is in progress during cleanup, stop it to save the recording
00146         if (_isRecording)
00147         {
00148             auto stopRecordTask = create_task(StopRecordingAsync());
00149             taskList.push_back(stopRecordTask);
00150         }
00151
00152         if (_isPreviewing)
00153         {
00154             auto stopPreviewTask = create_task(StopPreviewAsync());
00155             taskList.push_back(stopPreviewTask);
00156         }
00157
00158         _isInitialized = false;
00159     }
00160
00161     // When all our tasks complete, clean up MediaCapture
00162     return when_all(taskList.begin(), taskList.end())
00163         .then([this]()
00164     {
00165         if (_mediaCapture != nullptr)
00166         {
00167             _mediaCapture->RecordLimitationExceeded -= _recordLimitationExceededEventToken;
00168             _mediaCapture->Failed -= _mediaCaptureFailedEventToken;
00169             _mediaCapture = nullptr;
00170         }
00171
00172         if (_rotationHelper != nullptr)
00173         {
00174             _rotationHelper->OrientationChanged -= _orientationChangedEventToken;
00175             _rotationHelper = nullptr;
00176         }
00177     });
00178 }
00179
00180 /// <summary>
00181 /// Starts the preview and adjusts it for for rotation and mirroring after making a request to keep the screen on
00182 /// </summary>
00183 /// <returns></returns>
00184 task<void> MainPage::StartPreviewAsync()
00185 {
00186     // Prevent the device from sleeping while the preview is running
00187     _displayRequest->RequestActive();
00188
00189     // Set the preview source in the UI and mirror it if necessary
00190     PreviewControl->Source = _mediaCapture.Get();
00191     PreviewControl->FlowDirection = _mirroringPreview ? Windows::UI::Xaml::FlowDirection::RightToLeft : Windows::UI::Xaml::FlowDirection::LeftToRight;
00192
00193     // Start the preview
00194     return create_task(_mediaCapture->StartPreviewAsync())
00195         .then([this](task<void> previousTask)
00196     {
00197         _isPreviewing = true;
00198
00199         // Only need to update the orientation if the camera is mounted on the device
00200         if (!_externalCamera)
00201         {
00202             return SetPreviewRotationAsync();
00203         }
00204
00205         // Not external, just return the previous task
00206         return previousTask;
00207     });
00208 }
00209
00210 /// <summary>
00211 /// Gets the current orientation of the UI in relation to the device (when AutoRotationPreferences cannot be honored) and applies a corrective rotation to the preview
00212 /// </summary>
00213 /// <returns></returns>
00214 task<void> MainPage::SetPreviewRotationAsync()
00215 {
00216     // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames
00217     auto rotation = _rotationHelper->GetCameraPreviewOrientation();
00218     auto props = _mediaCapture->VideoDeviceController->GetMediaStreamProperties(Capture::MediaStreamType::VideoPreview);
00219     props->Properties->Insert(RotationKey, CameraRotationHelper::ConvertSimpleOrientationToClockwiseDegrees(rotation));
00220     return create_task(_mediaCapture->SetEncodingPropertiesAsync(Capture::MediaStreamType::VideoPreview, props, nullptr));
00221 }
00222
00223 /// <summary>
00224 /// Stops the preview and deactivates a display request, to allow the screen to go into power saving modes
00225 /// </summary>
00226 /// <returns></returns>
00227 task<void> MainPage::StopPreviewAsync()
00228 {
00229     _isPreviewing = false;
00230
00231     return create_task(_mediaCapture->StopPreviewAsync())
00232         .then([this]()
00233     {
00234         // Use the dispatcher because this method is sometimes called from non-UI threads
00235         return Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00236         {
00237             // Cleanup the UI
00238             PreviewControl->Source = nullptr;
00239             // Allow the device screen to sleep now that the preview is stopped
00240             _displayRequest->RequestRelease();
00241         }));
00242     });
00243 }
00244
00245 /// <summary>
00246 /// Takes a photo to a StorageFile and adds rotation metadata to it
00247 /// </summary>
00248 /// <returns></returns>
00249 task<void> MainPage::TakePhotoAsync()
00250 {
00251     // While taking a photo, keep the video button enabled only if the camera supports simultaneously taking pictures and recording video
00252     VideoButton->IsEnabled = _mediaCapture->MediaCaptureSettings->ConcurrentRecordAndPhotoSupported;
00253     // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
00254     VideoButton->Opacity = VideoButton->IsEnabled ? 1 : 0;
00255
00256     auto inputStream = ref new Streams::InMemoryRandomAccessStream();
00257
00258     // Take the picture
00259     WriteLine("Taking photo...");
00260     return create_task(_mediaCapture->CapturePhotoToStreamAsync(Windows::Media::MediaProperties::ImageEncodingProperties::CreateJpeg(), inputStream))
00261         .then([this, inputStream]()
00262     {
00263         return create_task(_captureFolder->CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption::GenerateUniqueName));
00264     }).then([this, inputStream](StorageFile^ file)
00265     {
00266         WriteLine("Photo taken! Saving to " + file->Path);
00267
00268         // Done taking a photo, so re-enable the button
00269         VideoButton->IsEnabled = true;
00270         VideoButton->Opacity = 1;
00271
00272         auto photoOrientation = CameraRotationHelper::ConvertSimpleOrientationToPhotoOrientation(_rotationHelper->GetCameraCaptureOrientation());
00273         return ReencodeAndSavePhotoAsync(inputStream, file, photoOrientation);
00274     }).then([this](task<void> previousTask)
00275     {
00276         try
00277         {
00278             previousTask.get();
00279         }
00280         catch (Exception^ ex)
00281         {
00282             // File I/O errors are reported as exceptions
00283             WriteException(ex);
00284         }
00285     });
00286 }
00287
00288 /// <summary>
00289 /// Records an MP4 video to a StorageFile and adds rotation metadata to it
00290 /// </summary>
00291 /// <returns></returns>
00292 task<void> MainPage::StartRecordingAsync()
00293 {
00294     // Create storage file for the capture
00295     return create_task(_captureFolder->CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption::GenerateUniqueName))
00296         .then([this](StorageFile^ file)
00297     {
00298         // Calculate rotation angle, taking mirroring into account if necessary
00299         auto rotationAngle = CameraRotationHelper::ConvertSimpleOrientationToClockwiseDegrees(_rotationHelper->GetCameraCaptureOrientation());
00300         auto encodingProfile = MediaProperties::MediaEncodingProfile::CreateMp4(MediaProperties::VideoEncodingQuality::Auto);
00301         encodingProfile->Video->Properties->Insert(RotationKey, rotationAngle);
00302
00303         return create_task(_mediaCapture->StartRecordToStorageFileAsync(encodingProfile, file))
00304             .then([this, file]()
00305         {
00306             _isRecording = true;
00307             WriteLine("Started recording to " + file->Path);
00308         });
00309     }).then([this](task<void> previousTask)
00310     {
00311         try
00312         {
00313             previousTask.get();
00314         }
00315         catch (Exception^ ex)
00316         {
00317             // File I/O errors are reported as exceptions
00318             WriteException(ex);
00319         }
00320     });
00321 }
00322
00323 /// <summary>
00324 /// Stops recording a video
00325 /// </summary>
00326 /// <returns></returns>
00327 task<void> MainPage::StopRecordingAsync()
00328 {
00329     _isRecording = false;
00330
00331     WriteLine("Stopping recording...");
00332     return create_task(_mediaCapture->StopRecordAsync())
00333         .then([this]()
00334     {
00335         WriteLine("Stopped recording!");
00336     });
00337 }
00338
00339 /// <summary>
00340 /// Attempts to find and return a device mounted on the panel specified, and on failure to find one it will return the first device listed
00341 /// </summary>
00342 /// <param name="panel">The desired panel on which the returned device should be mounted, if available</param>
00343 /// <returns></returns>
00344 task<DeviceInformation^> MainPage::FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel panel)
00345 {
00346     // Get available devices for capturing pictures
00347     auto allVideoDevices = DeviceInformation::FindAllAsync(DeviceClass::VideoCapture);
00348
00349     auto deviceEnumTask = create_task(allVideoDevices);
00350     return deviceEnumTask.then([panel](DeviceInformationCollection^ devices)
00351     {
00352         for (auto cameraDeviceInfo : devices)
00353         {
00354             if (cameraDeviceInfo->EnclosureLocation != nullptr && cameraDeviceInfo->EnclosureLocation->Panel == panel)
00355             {
00356                 return cameraDeviceInfo;
00357             }
00358         }
00359
00360         // Nothing matched, just return the first
00361         if (devices->Size > 0)
00362         {
00363             return devices->GetAt(0);
00364         }
00365
00366         // We didn't find any devices, so return a null instance
00367         DeviceInformation^ camera = nullptr;
00368         return camera;
00369     });
00370 }
00371
00372 /// <summary>
00373 /// Applies the given orientation to a photo stream and saves it as a StorageFile
00374 /// </summary>
00375 /// <param name="stream">The photo stream</param>
00376 /// <param name="file">The StorageFile in which the photo stream will be saved</param>
00377 /// <param name="photoOrientation">The orientation metadata to apply to the photo</param>
00378 /// <returns></returns>
00379 task<void> MainPage::ReencodeAndSavePhotoAsync(Streams::IRandomAccessStream^ stream, StorageFile^ file, FileProperties::PhotoOrientation photoOrientation)
00380 {
00381     // Using this state variable to pass multiple values through our task chain
00382     ReencodeState^ state = ref new ReencodeState();
00383     state->File = file;
00384     state->Orientation = photoOrientation;
00385
00386     return create_task(BitmapDecoder::CreateAsync(stream))
00387         .then([state](BitmapDecoder^ decoder)
00388     {
00389         state->Decoder = decoder;
00390         return create_task(state->File->OpenAsync(FileAccessMode::ReadWrite));
00391     }).then([state](Streams::IRandomAccessStream^ outputStream)
00392     {
00393         return create_task(BitmapEncoder::CreateForTranscodingAsync(outputStream, state->Decoder));
00394     }).then([state](BitmapEncoder^ encoder)
00395     {
00396         state->Encoder = encoder;
00397         auto properties = ref new Windows::Graphics::Imaging::BitmapPropertySet();
00398         properties->Insert("System.Photo.Orientation", ref new BitmapTypedValue((unsigned short)state->Orientation, Windows::Foundation::PropertyType::UInt16));
00399
00400         return create_task(state->Encoder->BitmapProperties->SetPropertiesAsync(properties));
00401     }).then([state]()
00402     {
00403         return state->Encoder->FlushAsync();
00404     });
00405 }
00406
00407 /// <summary>
00408 /// This method will update the icons, enable/disable and show/hide the photo/video buttons depending on the current state of the app and the capabilities of the device
00409 /// </summary>
00410 void MainPage::UpdateCaptureControls()
00411 {
00412     // The buttons should only be enabled if the preview started sucessfully
00413     PhotoButton->IsEnabled = _isPreviewing;
00414     VideoButton->IsEnabled = _isPreviewing;
00415
00416     // Update recording button to show "Stop" icon instead of red "Record" icon
00417     StartRecordingIcon->Visibility = _isRecording ? Windows::UI::Xaml::Visibility::Collapsed : Windows::UI::Xaml::Visibility::Visible;
00418     StopRecordingIcon->Visibility = _isRecording ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00419
00420     // If the camera doesn't support simultaneously taking pictures and recording video, disable the photo button on record
00421     if (_isInitialized && !_mediaCapture->MediaCaptureSettings->ConcurrentRecordAndPhotoSupported)
00422     {
00423         PhotoButton->IsEnabled = !_isRecording;
00424
00425         // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
00426         PhotoButton->Opacity = PhotoButton->IsEnabled ? 1 : 0;
00427     }
00428 }
00429
00430 /// <summary>
00431 /// Initialize or clean up the camera and our UI,
00432 /// depending on the page state.
00433 /// </summary>
00434 /// <returns></returns>
00435 Concurrency::task<void> MainPage::SetUpBasedOnStateAsync()
00436 {
00437     // Avoid reentrancy: Wait until nobody else is in this function.
00438     while (!_setupTask.is_done())
00439     {
00440         return _setupTask.then([this]() { return SetUpBasedOnStateAsync(); },
00441             task_continuation_context::get_current_winrt_context());
00442     }
00443
00444     // We want our UI to be active if
00445     // * We are the current active page.
00446     // * The window is visible.
00447     // * The app is not suspending.
00448     bool wantUIActive = _isActivePage && Window::Current->Visible && !_isSuspending;
00449
00450     if (_isUIActive != wantUIActive)
00451     {
00452         _isUIActive = wantUIActive;
00453
00454         if (wantUIActive)
00455         {
00456             _setupTask = SetupUiAsync().then([this]()
00457             {
00458                 return InitializeCameraAsync();
00459             }, task_continuation_context::get_current_winrt_context());
00460         }
00461         else
00462         {
00463             _setupTask = CleanupCameraAsync().then([this]()
00464             {
00465                 return CleanupUiAsync();
00466             }, task_continuation_context::get_current_winrt_context());
00467         }
00468     }
00469     return _setupTask;
00470 }
00471
00472 /// <summary>
00473 /// Attempts to lock the page orientation, hide the StatusBar (on Phone) and registers event handlers for hardware buttons and orientation sensors
00474 /// </summary>
00475 /// <returns></returns>
00476 task<void> MainPage::SetupUiAsync()
00477 {
00478     // Attempt to lock page to landscape orientation to prevent the CaptureElement from rotating, as this gives a better experience
00479     DisplayInformation::AutoRotationPreferences = DisplayOrientations::Landscape;
00480
00481     RegisterEventHandlers();
00482
00483     create_task(StorageLibrary::GetLibraryAsync(KnownLibraryId::Pictures))
00484         .then([this](StorageLibrary^ picturesLibrary)
00485     {
00486         _captureFolder = picturesLibrary->SaveFolder;
00487         if (_captureFolder == nullptr)
00488         {
00489             // In this case fall back to the local app storage since the Pictures Library is not available
00490             _captureFolder = ApplicationData::Current->LocalFolder;
00491         }
00492     });
00493
00494     // Hide the status bar
00495     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00496     {
00497         return create_task(Windows::UI::ViewManagement::StatusBar::GetForCurrentView()->HideAsync());
00498     }
00499     else
00500     {
00501         return task_from_result();
00502     }
00503 }
00504
00505 /// <summary>
00506 /// Unregisters event handlers for hardware buttons and orientation sensors, allows the StatusBar (on Phone) to show, and removes the page orientation lock
00507 /// </summary>
00508 /// <returns></returns>
00509 task<void> MainPage::CleanupUiAsync()
00510 {
00511     UnregisterEventHandlers();
00512
00513     // Revert orientation preferences
00514     DisplayInformation::AutoRotationPreferences = DisplayOrientations::None;
00515
00516     // Show the status bar
00517     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00518     {
00519         return create_task(Windows::UI::ViewManagement::StatusBar::GetForCurrentView()->ShowAsync());
00520     }
00521     else
00522     {
00523         return task_from_result();
00524     }
00525 }
00526
00527 /// <summary>
00528 /// Registers event handlers for hardware buttons and orientation sensors, and performs an initial update of the UI rotation
00529 /// </summary>
00530 void MainPage::RegisterEventHandlers()
00531 {
00532     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00533     {
00534         _hardwareCameraButtonEventToken =
00535             HardwareButtons::CameraPressed += ref new Windows::Foundation::EventHandler<CameraEventArgs^>(this, &MainPage::HardwareButtons_CameraPress);
00536     }
00537
00538     _mediaControlPropChangedEventToken =
00539         _systemMediaControls->PropertyChanged += ref new TypedEventHandler<SystemMediaTransportControls^, SystemMediaTransportControlsPropertyChangedEventArgs^>(this, &MainPage::SystemMediaControls_PropertyChanged);
00540 }
00541
00542 /// <summary>
00543 /// Unregisters event handlers for hardware buttons and orientation sensors
00544 /// </summary>
00545 void MainPage::UnregisterEventHandlers()
00546 {
00547     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00548     {
00549         HardwareButtons::CameraPressed -= _hardwareCameraButtonEventToken;
00550     }
00551
00552     _systemMediaControls->PropertyChanged -= _mediaControlPropChangedEventToken;
00553 }
00554
00555 /// <summary>
00556 /// Writes a given string to the output window
00557 /// </summary>
00558 /// <param name="str">String to be written</param>
00559 void MainPage::WriteLine(String^ str)
00560 {
00561     std::wstringstream wStringstream;
00562     wStringstream << str->Data() << "\n";
00563     OutputDebugString(wStringstream.str().c_str());
00564 }
00565
00566 /// <summary>
00567 /// Writes a given exception message and hresult to the output window
00568 /// </summary>
00569 /// <param name="ex">Exception to be written</param>
00570 void MainPage::WriteException(Exception^ ex)
00571 {
00572     std::wstringstream wStringstream;
00573     wStringstream << "0x" << ex->HResult << ": " << ex->Message->Data();
00574     OutputDebugString(wStringstream.str().c_str());
00575 }
00576
00577 /// <summary>
00578 /// Uses the current device orientation in space and page orientation on the screen to calculate the rotation
00579 /// transformation to apply to the controls
00580 /// </summary>
00581 void MainPage::UpdateButtonOrientation()
00582 {
00583     // Rotate the buttons in the UI to match the rotation of the device
00584     auto angle = CameraRotationHelper::ConvertSimpleOrientationToClockwiseDegrees(_rotationHelper->GetUIOrientation());
00585
00586     // Rotate the buttons in the UI to match the rotation of the device
00587     auto transform = ref new RotateTransform();
00588     transform->Angle = angle;
00589
00590     // The RenderTransform is safe to use (i.e. it won't cause layout issues) in this case, because these buttons have a 1:1 aspect ratio
00591     PhotoButton->RenderTransform = transform;
00592     VideoButton->RenderTransform = transform;
00593 }
00594
00595 void MainPage::Application_Suspending(Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e)
00596 {
00597     _isSuspending = true;
00598
00599     auto deferral = e->SuspendingOperation->GetDeferral();
00600     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this, deferral]()
00601     {
00602         SetUpBasedOnStateAsync().then([deferral]()
00603         {
00604             deferral->Complete();
00605         });
00606     }));
00607 }
00608
00609 void MainPage::Application_Resuming(Platform::Object^ sender, Platform::Object^ args)
00610 {
00611     _isSuspending = false;
00612
00613     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([this]()
00614     {
00615         SetUpBasedOnStateAsync();
00616     }));
00617 }
00618
00619 void MainPage::Window_VisibilityChanged(Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e)
00620 {
00621     SetUpBasedOnStateAsync();
00622 }
00623
00624 void MainPage::PhotoButton_Click(Object^, Windows::UI::Xaml::RoutedEventArgs^)
00625 {
00626     TakePhotoAsync();
00627 }
00628
00629 void MainPage::VideoButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00630 {
00631     task<void> taskToExecute;
00632     if (!_isRecording)
00633     {
00634         taskToExecute = StartRecordingAsync();
00635     }
00636     else
00637     {
00638         taskToExecute = StopRecordingAsync();
00639     }
00640
00641     taskToExecute.then([this](task<void> previousTask)
00642     {
00643         // After starting or stopping video recording, update the UI to reflect the MediaCapture state
00644         UpdateCaptureControls();
00645     });
00646 }
00647
00648 /// <summary>
00649 /// In the event of the app being minimized this method handles media property change events. If the app receives a mute
00650 /// notification, it is no longer in the foregroud.
00651 /// </summary>
00652 /// <param name="sender"></param>
00653 /// <param name="args"></param>
00654 void MainPage::SystemMediaControls_PropertyChanged(SystemMediaTransportControls^ sender, SystemMediaTransportControlsPropertyChangedEventArgs^ args)
00655 {
00656     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, sender, args]()
00657     {
00658         // Only handle this event if this page is currently being displayed
00659         if (args->Property == SystemMediaTransportControlsProperty::SoundLevel && Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name)
00660         {
00661             // Check to see if the app is being muted. If so, it is being minimized.
00662             // Otherwise if it is not initialized, it is being brought into focus.
00663             if (sender->SoundLevel == SoundLevel::Muted)
00664             {
00665                 CleanupCameraAsync();
00666             }
00667             else if (!_isInitialized)
00668             {
00669                 InitializeCameraAsync();
00670             }
00671         }
00672     }));
00673 }
00674
00675 /// <summary>
00676 /// Handles an orientation changed event
00677 /// </summary>
00678 void MainPage::RotationHelper_OrientationChanged(Object^, bool updatePreview)
00679 {
00680     Concurrency::task<void> task = create_task([]() {});
00681     if (updatePreview)
00682     {
00683         task = create_task(SetPreviewRotationAsync());
00684     }
00685
00686     task.then([this]()
00687     {
00688         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00689         {
00690             UpdateButtonOrientation();
00691         }));
00692     });
00693 }
00694
00695 void MainPage::HardwareButtons_CameraPress(Platform::Object^, Windows::Phone::UI::Input::CameraEventArgs^)
00696 {
00697     TakePhotoAsync();
00698 }
00699
00700 /// <summary>
00701 /// This is a notification that recording has to stop, and the app is expected to finalize the recording
00702 /// </summary>
00703 /// <param name="args">The event data.</param>
00704 void MainPage::MediaCapture_RecordLimitationExceeded(Capture::MediaCapture^)
00705 {
00706     StopRecordingAsync()
00707         .then([this]()
00708     {
00709         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00710         {
00711             UpdateCaptureControls();
00712         }));
00713     });
00714 }
00715
00716 void MainPage::MediaCapture_Failed(Capture::MediaCapture ^currentCaptureObject, Capture::MediaCaptureFailedEventArgs^ errorEventArgs)
00717 {
00718     std::wstringstream ss;
00719     ss << "MediaCapture_Failed: 0x" << errorEventArgs->Code << ": " << errorEventArgs->Message->Data();
00720     WriteLine(ref new String(ss.str().c_str()));
00721
00722     CleanupCameraAsync()
00723         .then([this]()
00724     {
00725         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00726         {
00727             UpdateCaptureControls();
00728         }));
00729     });
00730 }
00731
00732 void MainPage::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00733 {
00734
00735     // Useful to know when to initialize/clean up the camera
00736     _applicationSuspendingEventToken =
00737         Application::Current->Suspending += ref new SuspendingEventHandler(this, &MainPage::Application_Suspending);
00738     _applicationResumingEventToken =
00739         Application::Current->Resuming += ref new EventHandler<Object^>(this, &MainPage::Application_Resuming);
00740     _windowVisibilityChangedEventToken =
00741         Window::Current->VisibilityChanged += ref new WindowVisibilityChangedEventHandler(this, &MainPage::Window_VisibilityChanged);
00742
00743     _isActivePage = true;
00744     SetUpBasedOnStateAsync();
00745 }
00746
00747 void MainPage::OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e)
00748 {
00749     // Handling of this event is included for completeness, as it will only fire when navigating between pages and this sample only includes one page
00750     Application::Current->Suspending -= _applicationSuspendingEventToken;
00751     Application::Current->Resuming -= _applicationResumingEventToken;
00752     Window::Current->VisibilityChanged -= _windowVisibilityChangedEventToken;
00753
00754     _isActivePage = false;
00755     SetUpBasedOnStateAsync();
00756 }
Generated on Fri Nov 15 2024 22:17:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundMediaPlayback/cs/ViewModels/SettingsViewModel.cs Source File

  • BackgroundMediaPlayback
  • cs
  • ViewModels

SettingsViewModel.cs

Go to the documentation of this file.
00001 ﻿using BackgroundMediaPlayback.Services;
00002 using System;
00003 using System.Collections.Generic;
00004 using System.ComponentModel;
00005 using System.Linq;
00006 using System.Text;
00007 using System.Threading.Tasks;
00008 using Windows.Foundation.Collections;
00009 using Windows.Storage;
00010 using Windows.UI.Xaml;
00011
00012 namespace BackgroundMediaPlayback.ViewModels
00013 {
00014     public class SettingsViewModel : INotifyPropertyChanged
00015     {
00016         public event PropertyChangedEventHandler PropertyChanged;
00017
00018         public bool ToastOnAppEvents
00019         {
00020             get
00021             {
00022                 return SettingsService.Instance.ToastOnAppEvents;
00023             }
00024             set
00025             {
00026                 if (SettingsService.Instance.ToastOnAppEvents != value)
00027                 {
00028                     SettingsService.Instance.ToastOnAppEvents = value;
00029                     RaisePropertyChanged("ToastOnAppEvents");
00030                 }
00031             }
00032         }
00033
00034         public bool UseCustomControls
00035         {
00036             get
00037             {
00038                 return SettingsService.Instance.UseCustomControls;
00039             }
00040             set
00041             {
00042                 if (SettingsService.Instance.UseCustomControls != value)
00043                 {
00044                     SettingsService.Instance.UseCustomControls = value;
00045                     RaisePropertyChanged("UseCustomControls");
00046                 }
00047             }
00048         }
00049
00050         private void RaisePropertyChanged(string propertyName)
00051         {
00052             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
00053         }
00054     }
00055 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
_PropertyChanged | sealed |
DeleteTripAsync(Trip^trip) | sealed |
description | sealed |
destination | sealed |
endDate | sealed |
loaded | sealed | [private]
LoadTripsAsync() | sealed |
LoadTripsSync() | sealed |
LoadTripsTask() | sealed | [private]
notes | sealed |
NotifyPropertyChanged(Platform::String^propertyName) | sealed |
ReadXml(Windows::Storage::Streams::IRandomAccessStream^randomAccessReadStream) | sealed | [private]
SaveTripAsync(Trip^trip) | sealed |
startDate | sealed |
Trip() | sealed |
trips | sealed | [private]
TripStore() | sealed |
WriteTrips() | sealed | [private]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cpp/5-GestureRecognizer.xaml.h Source File

  • BasicInput
  • cpp

5-GestureRecognizer.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "5-GestureRecognizer.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     ref class ManipulationInputProcessor sealed
00020     {
00021     public:
00022         ManipulationInputProcessor(Windows::UI::Input::GestureRecognizer^ gestureRecognizer, Windows::UI::Xaml::UIElement^ target, Windows::UI::Xaml::UIElement^ referenceFrame);
00023         void LockToXAxis();
00024         void LockToYAxis();
00025         void MoveOnXAndYAxes();
00026         void UseInertia(bool inertia);
00027         void Reset();
00028
00029     private:
00030         void InitializeTransforms();
00031         Windows::UI::Input::GestureSettings GenerateDefaultSettings();
00032         void OnPointerPressed(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args);
00033         void OnPointerMoved(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args);
00034         void OnPointerReleased(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args);
00035         void OnPointerCanceled(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args);
00036         void OnManipulationStarted(Windows::UI::Input::GestureRecognizer^, Windows::UI::Input::ManipulationStartedEventArgs^ e);
00037         void OnManipulationUpdated(Windows::UI::Input::GestureRecognizer^, Windows::UI::Input::ManipulationUpdatedEventArgs^ e);
00038         void OnManipulationInertiaStarting(Windows::UI::Input::GestureRecognizer^r, Windows::UI::Input::ManipulationInertiaStartingEventArgs^ e);
00039         void OnManipulationCompleted(Windows::UI::Input::GestureRecognizer^, Windows::UI::Input::ManipulationCompletedEventArgs^ e);
00040
00041         Windows::UI::Input::GestureRecognizer^ recognizer;
00042         Windows::UI::Xaml::UIElement^ element;
00043         Windows::UI::Xaml::UIElement^ reference;
00044         Windows::UI::Xaml::Media::TransformGroup^ cumulativeTransform;
00045         Windows::UI::Xaml::Media::MatrixTransform^ previousTransform;
00046         Windows::UI::Xaml::Media::CompositeTransform^ deltaTransform;
00047     };
00048
00049     /// <summary>
00050     /// An empty page that can be used on its own or navigated to within a Frame.
00051     /// </summary>
00052     [Windows::Foundation::Metadata::WebHostHidden]
00053     public ref class Scenario5 sealed
00054     {
00055     public:
00056         Scenario5();
00057
00058     private:
00059         void InitOptions();
00060         void movementAxis_Changed(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00061         void InertiaSwitch_Toggled(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062         void resetButton_Pressed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063
00064         MainPage^ rootPage = MainPage::Current;
00065         Windows::UI::Input::GestureRecognizer^ recognizer;
00066         ManipulationInputProcessor^ manipulationProcessor;
00067     };
00068 }
Generated on Fri Nov 15 2024 22:18:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothAdvertisement/cs/Scenario1_Watcher.xaml.cs Source File

  • BluetoothAdvertisement
  • cs

Scenario1_Watcher.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Storage.Streams;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 using Windows.Devices.Bluetooth.Advertisement;
00020
00021 using SDKTemplate;
00022
00023 namespace BluetoothAdvertisement
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class Scenario1_Watcher : Page
00029     {
00030         // The Bluetooth LE advertisement watcher class is used to control and customize Bluetooth LE scanning.
00031         private BluetoothLEAdvertisementWatcher watcher;
00032
00033         // A pointer back to the main page is required to display status messages.
00034         private MainPage rootPage;
00035
00036         /// <summary>
00037         /// Initializes the singleton application object.  This is the first line of authored code
00038         /// executed, and as such is the logical equivalent of main() or WinMain().
00039         /// </summary>
00040         public Scenario1_Watcher()
00041         {
00042             this.InitializeComponent();
00043
00044             // Create and initialize a new watcher instance.
00045             watcher = new BluetoothLEAdvertisementWatcher();
00046
00047             // Begin of watcher configuration. Configure the advertisement filter to look for the data advertised by the publisher
00048             // in Scenario 2 or 4. You need to run Scenario 2 on another Windows platform within proximity of this one for Scenario 1 to
00049             // take effect. The APIs shown in this Scenario are designed to operate only if the App is in the foreground. For background
00050             // watcher operation, please refer to Scenario 3.
00051
00052             // Please comment out this following section (watcher configuration) if you want to remove all filters. By not specifying
00053             // any filters, all advertisements received will be notified to the App through the event handler. You should comment out the following
00054             // section if you do not have another Windows platform to run Scenario 2 alongside Scenario 1 or if you want to scan for
00055             // all LE advertisements around you.
00056
00057             // For determining the filter restrictions programatically across APIs, use the following properties:
00058             //      MinSamplingInterval, MaxSamplingInterval, MinOutOfRangeTimeout, MaxOutOfRangeTimeout
00059
00060             // Part 1A: Configuring the advertisement filter to watch for a particular advertisement payload
00061
00062             // First, let create a manufacturer data section we wanted to match for. These are the same as the one
00063             // created in Scenario 2 and 4.
00064             var manufacturerData = new BluetoothLEManufacturerData();
00065
00066             // Then, set the company ID for the manufacturer data. Here we picked an unused value: 0xFFFE
00067             manufacturerData.CompanyId = 0xFFFE;
00068
00069             // Finally set the data payload within the manufacturer-specific section
00070             // Here, use a 16-bit UUID: 0x1234 -> {0x34, 0x12} (little-endian)
00071             var writer = new DataWriter();
00072             writer.WriteUInt16(0x1234);
00073
00074             // Make sure that the buffer length can fit within an advertisement payload. Otherwise you will get an exception.
00075             manufacturerData.Data = writer.DetachBuffer();
00076
00077             // Add the manufacturer data to the advertisement filter on the watcher:
00078             watcher.AdvertisementFilter.Advertisement.ManufacturerData.Add(manufacturerData);
00079
00080
00081             // Part 1B: Configuring the signal strength filter for proximity scenarios
00082
00083             // Configure the signal strength filter to only propagate events when in-range
00084             // Please adjust these values if you cannot receive any advertisement
00085             // Set the in-range threshold to -70dBm. This means advertisements with RSSI >= -70dBm
00086             // will start to be considered "in-range".
00087             watcher.SignalStrengthFilter.InRangeThresholdInDBm = -70;
00088
00089             // Set the out-of-range threshold to -75dBm (give some buffer). Used in conjunction with OutOfRangeTimeout
00090             // to determine when an advertisement is no longer considered "in-range"
00091             watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -75;
00092
00093             // Set the out-of-range timeout to be 2 seconds. Used in conjunction with OutOfRangeThresholdInDBm
00094             // to determine when an advertisement is no longer considered "in-range"
00095             watcher.SignalStrengthFilter.OutOfRangeTimeout = TimeSpan.FromMilliseconds(2000);
00096
00097             // By default, the sampling interval is set to zero, which means there is no sampling and all
00098             // the advertisement received is returned in the Received event
00099
00100             // End of watcher configuration. There is no need to comment out any code beyond this point.
00101         }
00102
00103         /// <summary>
00104         /// Invoked when this page is about to be displayed in a Frame.
00105         ///
00106         /// We will enable/disable parts of the UI if the device doesn't support it.
00107         /// </summary>
00108         /// <param name="eventArgs">Event data that describes how this page was reached. The Parameter
00109         /// property is typically used to configure the page.</param>
00110         protected override void OnNavigatedTo(NavigationEventArgs e)
00111         {
00112             rootPage = MainPage.Current;
00113
00114             // Attach a handler to process the received advertisement.
00115             // The watcher cannot be started without a Received handler attached
00116             watcher.Received += OnAdvertisementReceived;
00117
00118             // Attach a handler to process watcher stopping due to various conditions,
00119             // such as the Bluetooth radio turning off or the Stop method was called
00120             watcher.Stopped += OnAdvertisementWatcherStopped;
00121
00122             // Attach handlers for suspension to stop the watcher when the App is suspended.
00123             App.Current.Suspending += App_Suspending;
00124             App.Current.Resuming += App_Resuming;
00125
00126             rootPage.NotifyUser("Press Run to start watcher.", NotifyType.StatusMessage);
00127         }
00128
00129         /// <summary>
00130         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00131         /// </summary>
00132         /// <param name="e">
00133         /// Event data that can be examined by overriding code. The event data is representative
00134         /// of the navigation that will unload the current Page unless canceled. The
00135         /// navigation can potentially be canceled by setting Cancel.
00136         /// </param>
00137         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00138         {
00139             // Remove local suspension handlers from the App since this page is no longer active.
00140             App.Current.Suspending -= App_Suspending;
00141             App.Current.Resuming -= App_Resuming;
00142
00143             // Make sure to stop the watcher when leaving the context. Even if the watcher is not stopped,
00144             // scanning will be stopped automatically if the watcher is destroyed.
00145             watcher.Stop();
00146             // Always unregister the handlers to release the resources to prevent leaks.
00147             watcher.Received -= OnAdvertisementReceived;
00148             watcher.Stopped -= OnAdvertisementWatcherStopped;
00149
00150             rootPage.NotifyUser("Navigating away. Watcher stopped.", NotifyType.StatusMessage);
00151             base.OnNavigatingFrom(e);
00152         }
00153
00154         /// <summary>
00155         /// Invoked when application execution is being suspended.  Application state is saved
00156         /// without knowing whether the application will be terminated or resumed with the contents
00157         /// of memory still intact.
00158         /// </summary>
00159         /// <param name="sender">The source of the suspend request.</param>
00160         /// <param name="e">Details about the suspend request.</param>
00161         private void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
00162         {
00163             // Make sure to stop the watcher on suspend.
00164             watcher.Stop();
00165             // Always unregister the handlers to release the resources to prevent leaks.
00166             watcher.Received -= OnAdvertisementReceived;
00167             watcher.Stopped -= OnAdvertisementWatcherStopped;
00168
00169             rootPage.NotifyUser("App suspending. Watcher stopped.", NotifyType.StatusMessage);
00170         }
00171
00172         /// <summary>
00173         /// Invoked when application execution is being resumed.
00174         /// </summary>
00175         /// <param name="sender">The source of the resume request.</param>
00176         /// <param name="e"></param>
00177         private void App_Resuming(object sender, object e)
00178         {
00179             watcher.Received += OnAdvertisementReceived;
00180             watcher.Stopped += OnAdvertisementWatcherStopped;
00181         }
00182
00183         /// <summary>
00184         /// Invoked as an event handler when the Run button is pressed.
00185         /// </summary>
00186         /// <param name="sender">Instance that triggered the event.</param>
00187         /// <param name="e">Event data describing the conditions that led to the event.</param>
00188         private void RunButton_Click(object sender, RoutedEventArgs e)
00189         {
00190             // Calling watcher start will start the scanning if not already initiated by another client
00191             watcher.Start();
00192
00193             rootPage.NotifyUser("Watcher started.", NotifyType.StatusMessage);
00194         }
00195
00196         /// <summary>
00197         /// Invoked as an event handler when the Stop button is pressed.
00198         /// </summary>
00199         /// <param name="sender">Instance that triggered the event.</param>
00200         /// <param name="e">Event data describing the conditions that led to the event.</param>
00201         private void StopButton_Click(object sender, RoutedEventArgs e)
00202         {
00203             // Stopping the watcher will stop scanning if this is the only client requesting scan
00204             watcher.Stop();
00205
00206             rootPage.NotifyUser("Watcher stopped.", NotifyType.StatusMessage);
00207         }
00208
00209         /// <summary>
00210         /// Invoked as an event handler when an advertisement is received.
00211         /// </summary>
00212         /// <param name="watcher">Instance of watcher that triggered the event.</param>
00213         /// <param name="eventArgs">Event data containing information about the advertisement event.</param>
00214         private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
00215         {
00216             // We can obtain various information about the advertisement we just received by accessing
00217             // the properties of the EventArgs class
00218
00219             // The timestamp of the event
00220             DateTimeOffset timestamp = eventArgs.Timestamp;
00221
00222             // The type of advertisement
00223             BluetoothLEAdvertisementType advertisementType = eventArgs.AdvertisementType;
00224
00225             // The received signal strength indicator (RSSI)
00226             Int16 rssi = eventArgs.RawSignalStrengthInDBm;
00227
00228             // The local name of the advertising device contained within the payload, if any
00229             string localName = eventArgs.Advertisement.LocalName;
00230
00231             // Check if there are any manufacturer-specific sections.
00232             // If there is, print the raw data of the first manufacturer section (if there are multiple).
00233             string manufacturerDataString = "";
00234             var manufacturerSections = eventArgs.Advertisement.ManufacturerData;
00235             if (manufacturerSections.Count > 0)
00236             {
00237                 // Only print the first one of the list
00238                 var manufacturerData = manufacturerSections[0];
00239                 var data = new byte[manufacturerData.Data.Length];
00240                 using (var reader = DataReader.FromBuffer(manufacturerData.Data))
00241                 {
00242                     reader.ReadBytes(data);
00243                 }
00244                 // Print the company ID + the raw data in hex format
00245                 manufacturerDataString = string.Format("0x{0}: {1}",
00246                     manufacturerData.CompanyId.ToString("X"),
00247                     BitConverter.ToString(data));
00248             }
00249
00250             // Serialize UI update to the main UI thread
00251             await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00252             {
00253                 // Display these information on the list
00254                 ReceivedAdvertisementListBox.Items.Add(string.Format("[{0}]: type={1}, rssi={2}, name={3}, manufacturerData=[{4}]",
00255                     timestamp.ToString("hh\\:mm\\:ss\\.fff"),
00256                     advertisementType.ToString(),
00257                     rssi.ToString(),
00258                     localName,
00259                     manufacturerDataString));
00260             });
00261         }
00262
00263         /// <summary>
00264         /// Invoked as an event handler when the watcher is stopped or aborted.
00265         /// </summary>
00266         /// <param name="watcher">Instance of watcher that triggered the event.</param>
00267         /// <param name="eventArgs">Event data containing information about why the watcher stopped or aborted.</param>
00268         private async void OnAdvertisementWatcherStopped(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementWatcherStoppedEventArgs eventArgs)
00269         {
00270             // Notify the user that the watcher was stopped
00271             await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00272             {
00273                 rootPage.NotifyUser(string.Format("Watcher stopped or aborted: {0}", eventArgs.Error.ToString()), NotifyType.StatusMessage);
00274             });
00275         }
00276     }
00277 }
Generated on Fri Nov 15 2024 22:18:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserConsentVerifier/cs/Scenario2_RequestConsent.xaml.cs Source File

  • UserConsentVerifier
  • cs

Scenario2_RequestConsent.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using Windows.Security.Credentials.UI;
00016 using System;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class Scenario2_RequestConsent : Page
00021     {
00022         private MainPage rootPage = MainPage.Current;
00023
00024         public Scenario2_RequestConsent()
00025         {
00026             this.InitializeComponent();
00027         }
00028
00029         private async void RequestConsent_Click(object sender, RoutedEventArgs e)
00030         {
00031             RequestConsentButton.IsEnabled = false;
00032
00033             // Request the user's consent using Windows Hello via biometric verification or a PIN.
00034             string message = "Please confirm your identity to complete this (pretend) in-app purchase.";
00035             UserConsentVerificationResult consentResult = await UserConsentVerifier.RequestVerificationAsync(message);
00036             switch (consentResult)
00037             {
00038                 case UserConsentVerificationResult.Verified:
00039                     rootPage.NotifyUser("Pretend in-app purchase was successful.", NotifyType.StatusMessage);
00040                     break;
00041
00042                 case UserConsentVerificationResult.DeviceNotPresent:
00043                     rootPage.NotifyUser("No PIN or biometric found, please set one up.", NotifyType.ErrorMessage);
00044                     break;
00045
00046                 case UserConsentVerificationResult.Canceled:
00047                     rootPage.NotifyUser("User consent verification canceled.", NotifyType.ErrorMessage);
00048                     break;
00049
00050                 default:
00051                     rootPage.NotifyUser("User consent verification is currently unavailable.", NotifyType.ErrorMessage);
00052                     break;
00053             }
00054             RequestConsentButton.IsEnabled = true;
00055         }
00056     }
00057 }
Generated on Fri Nov 15 2024 22:21:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Tasks/BackgroundDeviceWatcher.h Source File

  • DeviceEnumerationAndPairing
  • cppwinrt
  • Tasks

BackgroundDeviceWatcher.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include "BackgroundDeviceWatcher.g.h"
00004
00005 namespace winrt::BackgroundDeviceWatcherTask::implementation
00006 {
00007     struct BackgroundDeviceWatcher : BackgroundDeviceWatcherT<BackgroundDeviceWatcher>
00008     {
00009         BackgroundDeviceWatcher() = default;
00010
00011         void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance const& taskInstance);
00012     };
00013 }
00014
00015 namespace winrt::BackgroundDeviceWatcherTask::factory_implementation
00016 {
00017     struct BackgroundDeviceWatcher : BackgroundDeviceWatcherT<BackgroundDeviceWatcher, implementation::BackgroundDeviceWatcher>
00018     {
00019     };
00020 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/Simple3DGame.h Source File

  • Simple3DGameDX
  • cpp

Simple3DGame.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Simple3DGame:
00015 // This is the main game class.  It controls game play logic and game state.
00016 // Some of the key object classes used by Simple3DGame are:
00017 //     MoveLookController - for handling all input to control player movement, aiming,
00018 //         and firing.
00019 //     GameRenderer - for handling all graphics presentation.
00020 //     Camera - for handling view projections.
00021 //     Audio - for handling sound output.
00022 // This class maintains several lists of objects:
00023 //     m_ammo <Sphere> - is the list of the balls used to throw at targets.  Simple3DGame
00024 //         cycles through the list in a LRU fashion each time a ball is thrown by the player.
00025 //     m_objects <GameObject> - is the list of all objects in the scene that participate in
00026 //         game physics.  This includes m_player <Sphere> to represent the player in the scene.
00027 //         The player object (m_player) is not visible in the scene so it is not rendered.
00028 //     m_renderObjects <GameObject> - is the list of all objects in the scene that may be
00029 //         rendered.  It includes both the m_ammo list, most of the m_objects list excluding m_player
00030 //         object and the objects representing the bounding world.
00031
00032 #include "GameConstants.h"
00033 #include "Audio.h"
00034 #include "Camera.h"
00035 #include "Level.h"
00036 #include "GameObject.h"
00037 #include "GameTimer.h"
00038 #include "MoveLookController.h"
00039 #include "PersistentState.h"
00040 #include "Sphere.h"
00041 #include "GameRenderer.h"
00042
00043 //--------------------------------------------------------------------------------------
00044
00045 enum class GameState
00046 {
00047     Waiting,
00048     Active,
00049     LevelComplete,
00050     TimeExpired,
00051     GameComplete,
00052 };
00053
00054 typedef struct
00055 {
00056     Platform::String^ tag;
00057     int totalHits;
00058     int totalShots;
00059     int levelCompleted;
00060 } HighScoreEntry;
00061
00062 typedef std::vector<HighScoreEntry> HighScoreEntries;
00063
00064 //--------------------------------------------------------------------------------------
00065
00066 ref class GameRenderer;
00067
00068 ref class Simple3DGame
00069 {
00070 internal:
00071     Simple3DGame();
00072
00073     void Initialize(
00074         _In_ MoveLookController^ controller,
00075         _In_ GameRenderer^ renderer
00076         );
00077
00078     void LoadGame();
00079     concurrency::task<void> LoadLevelAsync();
00080     void FinalizeLoadLevel();
00081     void StartLevel();
00082     void PauseGame();
00083     void ContinueGame();
00084     GameState RunGame();
00085     void SetCurrentLevelToSavedState();
00086
00087     void OnSuspending();
00088     void OnResuming();
00089
00090     bool IsActivePlay()                         { return m_timer->Active(); }
00091     int LevelCompleted()                        { return m_currentLevel; };
00092     int TotalShots()                            { return m_totalShots; };
00093     int TotalHits()                             { return m_totalHits; };
00094     float BonusTime()                           { return m_levelBonusTime; };
00095     bool GameActive()                           { return m_gameActive; };
00096     bool LevelActive()                          { return m_levelActive; };
00097     HighScoreEntry HighScore()                  { return m_topScore; };
00098     Level^ CurrentLevel()                       { return m_level[m_currentLevel]; };
00099     float TimeRemaining()                       { return m_levelTimeRemaining; };
00100     Camera^ GameCamera()                        { return m_camera; };
00101     std::vector<GameObject^> RenderObjects()    { return m_renderObjects; };
00102
00103 private:
00104     void LoadState();
00105     void SaveState();
00106     void SaveHighScore();
00107     void LoadHighScore();
00108     void InitializeAmmo();
00109     void UpdateDynamics();
00110
00111     MoveLookController^                         m_controller;
00112     GameRenderer^                               m_renderer;
00113     Camera^                                     m_camera;
00114
00115     Audio^                                      m_audioController;
00116
00117     std::vector<Sphere^>                        m_ammo;
00118     uint32                                      m_ammoCount;
00119     uint32                                      m_ammoNext;
00120
00121     HighScoreEntry                              m_topScore;
00122     PersistentState^                            m_savedState;
00123
00124     GameTimer^                                  m_timer;
00125     bool                                        m_gameActive;
00126     bool                                        m_levelActive;
00127     int                                         m_totalHits;
00128     int                                         m_totalShots;
00129     float                                       m_levelDuration;
00130     float                                       m_levelBonusTime;
00131     float                                       m_levelTimeRemaining;
00132     std::vector<Level^>                         m_level;
00133     uint32                                      m_levelCount;
00134     uint32                                      m_currentLevel;
00135
00136     Sphere^                                     m_player;
00137     std::vector<GameObject^>                    m_objects;           // List of all objects to be included in intersection calculations.
00138     std::vector<GameObject^>                    m_renderObjects;     // List of all objects to be rendered.
00139
00140     DirectX::XMFLOAT3                           m_minBound;
00141     DirectX::XMFLOAT3                           m_maxBound;
00142 };
00143
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LowLatencyInput/cpp/SampleConfiguration.h Source File

  • LowLatencyInput
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Low latency input sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/Scenario3_BackgroundDeviceWatcher.xaml.cpp Source File

  • DeviceEnumerationAndPairing
  • cpp

Scenario3_BackgroundDeviceWatcher.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario3_BackgroundDeviceWatcher.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Platform::Collections;
00010 using namespace Windows::ApplicationModel::Background;
00011 using namespace Windows::Devices::Enumeration;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::Storage;
00015 using namespace Windows::UI::Core;
00016 using namespace Windows::UI::Xaml;
00017 using namespace Windows::UI::Xaml::Controls;
00018 using namespace Windows::UI::Xaml::Navigation;
00019
00020 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00021
00022 Scenario3_BackgroundDeviceWatcher::Scenario3_BackgroundDeviceWatcher()
00023 {
00024     InitializeComponent();
00025 }
00026
00027 void Scenario3_BackgroundDeviceWatcher::OnNavigatedTo(NavigationEventArgs^ e)
00028 {
00029     selectorComboBox->ItemsSource = DeviceSelectorChoices::BackgroundDeviceWatcherSelectors;
00030     selectorComboBox->SelectedIndex = 0;
00031
00032     // Determine if the background task is already active
00033     std::for_each(begin(BackgroundTaskRegistration::AllTasks), end(BackgroundTaskRegistration::AllTasks), [&](IKeyValuePair<Guid, IBackgroundTaskRegistration^>^ task)
00034     {
00035         if (backgroundTaskName == task->Value->Name)
00036         {
00037             backgroundTaskRegistration = task->Value;
00038             startWatcherButton->IsEnabled = false;
00039             stopWatcherButton->IsEnabled = true;
00040         }
00041     });
00042 }
00043
00044 void Scenario3_BackgroundDeviceWatcher::OnNavigatedFrom(NavigationEventArgs^ e)
00045 {
00046     if (backgroundTaskCompletedToken.Value)
00047     {
00048         backgroundTaskRegistration->Completed -= backgroundTaskCompletedToken;
00049         backgroundTaskCompletedToken = {};
00050     }
00051     backgroundTaskRegistration = nullptr;
00052 }
00053
00054 void Scenario3_BackgroundDeviceWatcher::StartWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00055 {
00056     StartWatcher();
00057 }
00058
00059 void Scenario3_BackgroundDeviceWatcher::StopWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00060 {
00061     StopWatcher();
00062 }
00063
00064 void Scenario3_BackgroundDeviceWatcher::StartWatcher()
00065 {
00066     Vector<DeviceWatcherEventKind>^ triggerEventKinds = ref new Vector<DeviceWatcherEventKind>({
00067         DeviceWatcherEventKind::Add,
00068         DeviceWatcherEventKind::Remove,
00069         DeviceWatcherEventKind::Update });
00070     DeviceWatcher^ deviceWatcher = nullptr;
00071
00072     startWatcherButton->IsEnabled = false;
00073
00074     // First get the device selector chosen by the UI.
00075     DeviceSelectorInfo^ deviceSelectorInfo = safe_cast<DeviceSelectorInfo^>(selectorComboBox->SelectedItem);
00076
00077     if (nullptr == deviceSelectorInfo->Selector)
00078     {
00079         // If the a pre-canned device class selector was chosen, call the DeviceClass overload
00080         deviceWatcher = DeviceInformation::CreateWatcher(deviceSelectorInfo->DeviceClassSelector);
00081     }
00082     else if (deviceSelectorInfo->Kind == DeviceInformationKind::Unknown)
00083     {
00084         // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
00085         // Kind will be determined by the selector
00086         deviceWatcher = DeviceInformation::CreateWatcher(
00087             deviceSelectorInfo->Selector,
00088             nullptr // don't request additional properties for this sample
00089             );
00090     }
00091     else
00092     {
00093         // Kind is specified in the selector info
00094         deviceWatcher = DeviceInformation::CreateWatcher(
00095             deviceSelectorInfo->Selector,
00096             nullptr, // don't request additional properties for this sample
00097             deviceSelectorInfo->Kind);
00098     }
00099
00100     // Get the background trigger for this watcher
00101     DeviceWatcherTrigger^ deviceWatcherTrigger = deviceWatcher->GetBackgroundTrigger(triggerEventKinds);
00102
00103     rootPage->NotifyUser("Starting Watcher...", NotifyType::StatusMessage);
00104
00105     // Register this trigger for our background task
00106     RegisterBackgroundTask(deviceWatcherTrigger);
00107
00108     stopWatcherButton->IsEnabled = true;
00109
00110     rootPage->NotifyUser("Watcher started...", NotifyType::StatusMessage);
00111 }
00112
00113 void Scenario3_BackgroundDeviceWatcher::RegisterBackgroundTask(DeviceWatcherTrigger^ deviceWatcherTrigger)
00114 {
00115     BackgroundTaskBuilder^ taskBuilder = nullptr;
00116
00117     // First see if we already have this background task registered. If so, unregister
00118     // it before we register it with the new trigger.
00119
00120     std::for_each(begin(BackgroundTaskRegistration::AllTasks), end(BackgroundTaskRegistration::AllTasks), [&](IKeyValuePair<Guid, IBackgroundTaskRegistration^>^ task)
00121     {
00122         if (backgroundTaskName == task->Value->Name)
00123         {
00124             UnregisterBackgroundTask(task->Value);
00125         }
00126     });
00127
00128     taskBuilder = ref new BackgroundTaskBuilder();
00129     taskBuilder->Name = backgroundTaskName;
00130     taskBuilder->TaskEntryPoint = "BackgroundDeviceWatcherTaskCpp.BackgroundDeviceWatcher";
00131     taskBuilder->SetTrigger(deviceWatcherTrigger);
00132
00133     backgroundTaskRegistration = taskBuilder->Register();
00134     backgroundTaskCompletedToken = backgroundTaskRegistration->Completed += ref new BackgroundTaskCompletedEventHandler(
00135         [this](BackgroundTaskRegistration^ sender, BackgroundTaskCompletedEventArgs^ args)
00136     {
00137         rootPage->Dispatcher->RunAsync(CoreDispatcherPriority::Low, ref new DispatchedHandler(
00138             [this]()
00139         {
00140             rootPage->NotifyUser("Background task completed", NotifyType::StatusMessage);
00141         }));
00142     });
00143 }
00144
00145 void Scenario3_BackgroundDeviceWatcher::StopWatcher()
00146 {
00147     stopWatcherButton->IsEnabled = false;
00148     if (nullptr != backgroundTaskRegistration)
00149     {
00150         UnregisterBackgroundTask(backgroundTaskRegistration);
00151     }
00152     startWatcherButton->IsEnabled = true;
00153 }
00154
00155 void Scenario3_BackgroundDeviceWatcher::UnregisterBackgroundTask(IBackgroundTaskRegistration^ taskReg)
00156 {
00157     taskReg->Unregister(true);
00158     ApplicationDataContainer^ settings = ApplicationData::Current->LocalSettings;
00159     settings->Values->Insert("eventCount", nullptr);
00160 }
Generated on Fri Nov 15 2024 22:19:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLInProcessWinRTComponent/cpp/Server/OvenServer.cpp Source File

  • WRLInProcessWinRTComponent
  • cpp
  • Server

OvenServer.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include <wrl.h>
00008 #include <winerror.h>
00009 #include <Windows.Foundation.h>
00010 #include <wrl\implements.h>
00011 #include <wrl\event.h>
00012 #include <windows.system.threading.h>
00013
00014 #include "Microsoft.SDKSamples.Kitchen.h"
00015
00016 using namespace Microsoft::WRL;
00017 using namespace Microsoft::WRL::Wrappers;
00018 using namespace ABI::Microsoft::SDKSamples::Kitchen;
00019 using namespace ABI::Windows::Foundation;
00020 using namespace ABI::Windows::System::Threading;
00021
00022 namespace ABI { namespace Microsoft { namespace SDKSamples { namespace Kitchen {
00023
00024     class Bread WrlFinal : public RuntimeClass<IBread>
00025     {
00026         InspectableClass(RuntimeClass_Microsoft_SDKSamples_Kitchen_Bread, TrustLevel::BaseTrust);
00027     public:
00028         HRESULT RuntimeClassInitialize(HSTRING flavor)
00029         {
00030             return m_flavor.Set(flavor);
00031         }
00032
00033         // IBread
00034         STDMETHODIMP get_Flavor(_COM_Outptr_ HSTRING* value) override
00035         {
00036             return m_flavor.CopyTo(value);
00037         }
00038         HString m_flavor;
00039     };
00040
00041     class Oven WrlFinal : public RuntimeClass<IOven, IAppliance>
00042     {
00043         InspectableClass(RuntimeClass_Microsoft_SDKSamples_Kitchen_Oven, TrustLevel::BaseTrust);
00044
00045     public:
00046         HRESULT RuntimeClassInitialize()
00047         {
00048             return S_OK;
00049         }
00050
00051         HRESULT RuntimeClassInitialize(_In_ Dimensions dimensions)
00052         {
00053             _dims = dimensions;
00054             return S_OK;
00055         }
00056
00057         // IAppliance
00058         STDMETHODIMP get_Volume(_Out_ double* value) override;
00059
00060         // IOven
00061         STDMETHODIMP ConfigurePreheatTemperature(_In_ OvenTemperature temperature) override;
00062         STDMETHODIMP BakeBread(_In_ HSTRING flavor) override;
00063         STDMETHODIMP add_BreadBaked(_In_ ITypedEventHandler<Oven*, BreadBakedEventArgs*>* handler, _Out_ EventRegistrationToken *token) override;
00064         STDMETHODIMP remove_BreadBaked(_In_ EventRegistrationToken token) override;
00065
00066     private:
00067         AgileEventSource<ITypedEventHandler<Oven*, BreadBakedEventArgs*>> _breadBaked;
00068         Dimensions _dims = { 1.0, 1.0, 1.0 };
00069         OvenTemperature _temperature = OvenTemperature::Medium;
00070     };
00071
00072     class BreadBakedEventArgs WrlFinal : public RuntimeClass<IBreadBakedEventArgs>
00073     {
00074         InspectableClass(RuntimeClass_Microsoft_SDKSamples_Kitchen_BreadBakedEventArgs, TrustLevel::BaseTrust)
00075
00076     public:
00077         HRESULT RuntimeClassInitialize(_In_ Bread* bread)
00078         {
00079             m_bread = bread;
00080             return S_OK;
00081         }
00082
00083         // IBreadBakedEventArgs
00084         STDMETHODIMP get_Bread(_COM_Outptr_ IBread** value) override
00085         {
00086             return m_bread.CopyTo(value);
00087         }
00088
00089     private:
00090         ComPtr<Bread> m_bread;
00091     };
00092
00093     class OvenFactory WrlFinal : public ActivationFactory<IOvenFactory>
00094     {
00095     public:
00096         // IActivationFactory
00097         STDMETHODIMP ActivateInstance(_COM_Outptr_ IInspectable** oven) override
00098         {
00099             return MakeAndInitialize<Oven>(oven);
00100         }
00101
00102         // IOvenFactory
00103         STDMETHODIMP CreateOven(_In_ Dimensions dimensions, _COM_Outptr_ IOven** oven) override
00104         {
00105             return MakeAndInitialize<Oven>(oven, dimensions);
00106         }
00107     };
00108
00109     STDMETHODIMP Oven::get_Volume(_Out_ double* value)
00110     {
00111         *value = _dims.Height * _dims.Width * _dims.Depth;
00112         return S_OK;
00113     }
00114
00115     STDMETHODIMP Oven::ConfigurePreheatTemperature(_In_ OvenTemperature temperature)
00116     {
00117         HRESULT hr = S_OK;
00118         if (temperature >= OvenTemperature::Low && temperature <= OvenTemperature::High)
00119         {
00120             _temperature = temperature;
00121         }
00122         else
00123         {
00124             hr = E_INVALIDARG;
00125             ::RoOriginateErrorW(hr, 0, L"Temperature is out of range. The temperature should be low, medium, or high.");
00126         }
00127         return hr;
00128     }
00129
00130     STDMETHODIMP Oven::BakeBread(_In_ HSTRING flavor)
00131     {
00132         HRESULT hr = S_OK;
00133         Windows::Foundation::TimeSpan preheatTime;
00134
00135         // Determine how long we need to wait for the oven to get to temperature
00136         switch (_temperature)
00137         {
00138         case OvenTemperature::Low:
00139             preheatTime.Duration = 1000000;    // preheat time to 100ms
00140             break;
00141
00142         case OvenTemperature::Medium:
00143             preheatTime.Duration = 2000000;    // preheat time to 200ms
00144             break;
00145
00146         case OvenTemperature::High:
00147             preheatTime.Duration = 3000000;    // preheat time to 300ms
00148             break;
00149
00150         default:
00151             hr = E_INVALIDARG;
00152             ::RoOriginateErrorW(hr, 0, L"Temperature is out of range. The temperature should be low, medium, or high.");
00153         }
00154
00155         if (SUCCEEDED(hr))
00156         {
00157             ComPtr<IThreadPoolTimerStatics> threadPoolTimer;
00158             hr = GetActivationFactory(HStringReference(RuntimeClass_Windows_System_Threading_ThreadPoolTimer).Get(), &threadPoolTimer);
00159             if (SUCCEEDED(hr))
00160             {
00161                 // Oven makes bread
00162                 ComPtr<Bread> bread;
00163                 hr = MakeAndInitialize<Bread>(&bread, flavor);
00164                 if (SUCCEEDED(hr))
00165                 {
00166                     ComPtr<BreadBakedEventArgs> eventArg;
00167                     hr = MakeAndInitialize<BreadBakedEventArgs>(&eventArg, bread.Get());
00168                     if (SUCCEEDED(hr))
00169                     {
00170                         ComPtr<Oven> thisRef(this);
00171                         auto spTimerCallback = Callback<ITimerElapsedHandler>([thisRef, eventArg](IThreadPoolTimer*) -> HRESULT
00172                         {
00173                             return thisRef->_breadBaked.InvokeAll(thisRef.Get(), eventArg.Get());
00174                         });
00175
00176                         hr = spTimerCallback ? S_OK : E_OUTOFMEMORY;
00177                         if (SUCCEEDED(hr))
00178                         {
00179                             ComPtr<IThreadPoolTimer> timer; // unused but required out param
00180                             hr = threadPoolTimer->CreateTimer(spTimerCallback.Get(), preheatTime, &timer);
00181                         }
00182                     }
00183                 }
00184             }
00185         }
00186         return hr;
00187     }
00188
00189     STDMETHODIMP Oven::add_BreadBaked(_In_ ITypedEventHandler<Oven*, BreadBakedEventArgs*>* handler, _Out_ EventRegistrationToken* token)
00190     {
00191         return _breadBaked.Add(handler, token);
00192     }
00193
00194     STDMETHODIMP Oven::remove_BreadBaked(_In_ EventRegistrationToken token)
00195     {
00196         return _breadBaked.Remove(token);
00197     }
00198
00199     ActivatableClassWithFactory(Oven, OvenFactory)
00200
00201 } /* Kitchen */ } /* SDKSamples */ } /* Microsoft */ } /* ABI */
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Publisher Member List

This is the complete list of members for Scenario2_Publisher, including all inherited members.
App_Resuming(object sender, object e) | Scenario2_Publisher | [inline, private]
App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) | Scenario2_Publisher | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_Publisher | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario2_Publisher | [inline, protected]
OnPublisherStatusChanged(BluetoothLEAdvertisementPublisher publisher, BluetoothLEAdvertisementPublisherStatusChangedEventArgs eventArgs) | Scenario2_Publisher | [inline, private]
publisher | Scenario2_Publisher | [private]
rootPage | Scenario2_Publisher | [private]
RunButton_Click(object sender, RoutedEventArgs e) | Scenario2_Publisher | [inline, private]
Scenario2_Publisher() | Scenario2_Publisher | [inline]
StopButton_Click(object sender, RoutedEventArgs e) | Scenario2_Publisher | [inline, private]
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-SPI/cppwinrt/pch.cpp Source File

  • IoT-SPI
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Json/cppwinrt/SampleConfiguration.cpp Source File

  • Json
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation::Collections;
00019 using namespace winrt::SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"Json C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Parse and Stringify", xaml_typename<SDKTemplate::Scenario1_ParseAndStringify>() },
00029 });
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_CharacterGrouping Member List

This is the complete list of members for Scenario4_CharacterGrouping, including all inherited members.
AddGroup(hstring const &label, Windows::UI::Xaml::UIElement const &element) | Scenario4_CharacterGrouping | [private]
AssignGroup_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario4_CharacterGrouping |
GetGroups_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario4_CharacterGrouping |
GlobeString | Scenario4_CharacterGrouping | [private, static]
Groups | Scenario4_CharacterGrouping | [private]
Scenario4_CharacterGrouping() | Scenario4_CharacterGrouping |
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cppwinrt/SampleConfiguration.cpp Source File

  • Logging
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SampleConfiguration.h"
00014 #include "MainPage.h"
00015 #include <winrt/SDKTemplate.h>
00016
00017 using namespace winrt;
00018 using namespace winrt::SDKTemplate::implementation;
00019
00020 winrt::hstring
00021 MainPage::FEATURE_NAME()
00022 {
00023     return L"Logging C++/WinRT Sample";
00024 }
00025
00026 Windows::Foundation::Collections::IVector<SDKTemplate::Scenario>
00027 MainPage::scenariosInner = winrt::single_threaded_observable_vector<SDKTemplate::Scenario>(
00028 {
00029     Scenario{ L"LoggingChannel", winrt::xaml_typename<SDKTemplate::Scenario1>() },
00030     Scenario{ L"LoggingSession", winrt::xaml_typename<SDKTemplate::Scenario2>() },
00031     Scenario{ L"FileLoggingSession", winrt::xaml_typename<SDKTemplate::Scenario3>() },
00032 });
Generated on Fri Nov 15 2024 22:17:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-I2C/cppwinrt/Scenario1_ReadData.cpp Source File

  • IoT-I2C
  • cppwinrt

Scenario1_ReadData.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_ReadData.h"
00014 #include "Scenario1_ReadData.g.cpp"
00015
00016 using namespace std::literals::chrono_literals;
00017 using namespace winrt;
00018 using namespace winrt::Windows::Devices::Enumeration;
00019 using namespace winrt::Windows::Devices::I2c;
00020 using namespace winrt::Windows::Foundation;
00021 using namespace winrt::Windows::Foundation::Collections;
00022 using namespace winrt::Windows::UI::Xaml;
00023
00024 namespace winrt::SDKTemplate::implementation
00025 {
00026     Scenario1_ReadData::Scenario1_ReadData()
00027     {
00028         InitializeComponent();
00029     }
00030
00031     void Scenario1_ReadData::OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&)
00032     {
00033         StopScenario();
00034     }
00035
00036     IAsyncAction Scenario1_ReadData::StartScenarioAsync()
00037     {
00038         auto lifetime = get_strong();
00039
00040         hstring i2cDeviceSelector = I2cDevice::GetDeviceSelector();
00041         IVectorView<DeviceInformation> devices = co_await DeviceInformation::FindAllAsync(i2cDeviceSelector);
00042
00043         // 0x40 was determined by looking at the datasheet for the HTU21D sensor
00044         I2cConnectionSettings HTU21D_settings(0x40);
00045
00046         // If this next line crashes with an OutOfBoundsException,
00047         // then the problem is that no I2C devices were found.
00048         //
00049         // If the next line crashes with Access Denied, then the problem is
00050         // that access to the I2C device (HTU21D) is denied.
00051         //
00052         // The call to FromIdAsync will also crash if the settings are invalid.
00053         //
00054         // FromIdAsync produces null if there is a sharing violation on the device.
00055         // This will result in a NullReferenceException in Timer_Tick below.
00056         htu21dSensor = co_await I2cDevice::FromIdAsync(devices.GetAt(0).Id(), HTU21D_settings);
00057
00058         // Start the polling timer.
00059         timer = DispatcherTimer();
00060         timer.Interval(500ms);
00061         timerEventToken = timer.Tick({ get_weak(), &Scenario1_ReadData::Timer_Tick });
00062         timer.Start();
00063     }
00064
00065     void Scenario1_ReadData::StopScenario()
00066     {
00067         if (timer != nullptr)
00068         {
00069             timer.Tick(timerEventToken);
00070             timer.Stop();
00071             timer = nullptr;
00072         }
00073
00074         // Release the I2C sensor.
00075         if (htu21dSensor != nullptr)
00076         {
00077             htu21dSensor.Close();
00078             htu21dSensor = nullptr;
00079         }
00080     }
00081
00082     fire_and_forget Scenario1_ReadData::StartStopScenario_Click(IInspectable const&, RoutedEventArgs const&)
00083     {
00084         auto lifetime = get_strong();
00085
00086         if (timer != nullptr)
00087         {
00088             StopScenario();
00089             StartStopButton().Content(box_value(L"Start"));
00090             ScenarioControls().Visibility(Visibility::Collapsed);
00091         }
00092         else
00093         {
00094             StartStopButton().IsEnabled(false);
00095             co_await StartScenarioAsync();
00096             StartStopButton().IsEnabled(true);
00097             StartStopButton().Content(box_value(L"Stop"));
00098             ScenarioControls().Visibility(Visibility::Visible);
00099         }
00100     }
00101
00102     void Scenario1_ReadData::Timer_Tick(IInspectable const&, IInspectable const&)
00103     {
00104         // Read data from I2C.
00105         uint8_t command[1];
00106         uint8_t humidityData[2];
00107         uint8_t temperatureData[2];
00108
00109         // Read humidity.
00110         command[0] = 0xE5;
00111
00112         // If this next line crashes with a NullReferenceException, then
00113         // there was a sharing violation on the device. (See StartScenarioAsync above.)
00114         //
00115         // If this next line crashes for some other reason, then there was
00116         // an error accessing the device.
00117         htu21dSensor.WriteRead(command, humidityData);
00118
00119         // Read temperature.
00120         command[0] = 0xE3;
00121         // If this next line crashes, then there was an error accessing the sensor.
00122         htu21dSensor.WriteRead(command, temperatureData);
00123
00124         // Calculate and report the humidity.
00125         auto rawHumidityReading = (humidityData[0] << 8) | humidityData[1];
00126         auto humidityRatio = rawHumidityReading / (float)65536;
00127         double humidity = -6.0 + (125.0 * humidityRatio);
00128         CurrentHumidity().Text(to_hstring(humidity));
00129
00130         // Calculate and report the temperature.
00131         auto rawTempReading = (temperatureData[0] << 8) | temperatureData[1];
00132         auto tempRatio = rawTempReading / (float)65536;
00133         double temperature = (-46.85 + (175.72 * tempRatio)) * 9 / 5 + 32;
00134         CurrentTemp().Text(to_hstring(temperature));
00135     }
00136 }
Generated on Fri Nov 15 2024 22:20:03 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactCards/cpp/pch.cpp Source File

  • ContactCards
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IScenario Member List

This is the complete list of members for IScenario, including all inherited members.
Contains(Type scenarioType) | IScenario
FindScenario(Type scenarioType) | IScenario
Name | IScenario
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cppwinrt/pch.cpp Source File

  • ResizeAppView
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Choosing Member List

This is the complete list of members for Scenario3_Choosing, including all inherited members.
OnHumanPresenceSensorAdded(Windows::Devices::Enumeration::DeviceWatcher const &sender, Windows::Devices::Enumeration::DeviceInformation deviceInfo) | Scenario3_Choosing | [private]
OnHumanPresenceSensorEnumerationCompleted(Windows::Devices::Enumeration::DeviceWatcher const &sender, Windows::Foundation::IInspectable const &e) | Scenario3_Choosing | [private]
OnHumanPresenceSensorRemoved(Windows::Devices::Enumeration::DeviceWatcher const &sender, Windows::Devices::Enumeration::DeviceInformationUpdate update) | Scenario3_Choosing | [private]
OnHumanPresenceSensorUpdated(Windows::Devices::Enumeration::DeviceWatcher const &sender, Windows::Devices::Enumeration::DeviceInformationUpdate update) | Scenario3_Choosing | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario3_Choosing |
ReadOneReadingFromSensorAsync(Windows::Devices::Enumeration::DeviceInformation deviceInfo) | Scenario3_Choosing | [private]
Scenario3_Choosing() | Scenario3_Choosing |
ScenarioPick_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario3_Choosing |
ScenarioReadSelected_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario3_Choosing |
ScenarioStart_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario3_Choosing |
ScenarioStop_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario3_Choosing |
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PlayReady/cs/Scenario4_SecureStop.xaml.cs Source File

  • PlayReady
  • cs

Scenario4_SecureStop.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate.ViewModels;
00013 using Windows.UI.Xaml.Controls;
00014
00015 namespace SDKTemplate
00016 {
00017     public sealed partial class Scenario4_SecureStop : Page
00018     {
00019         public Scenario4_SecureStop()
00020         {
00021             this.InitializeComponent();
00022             this.DataContext = new SecureStopViewModel(mediaElement);
00023         }
00024     }
00025 }
Generated on Fri Nov 15 2024 22:20:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario01_GetText Member List

This is the complete list of members for Scenario01_GetText, including all inherited members.
Cancel_Click(object sender, RoutedEventArgs e) | Scenario01_GetText | [inline, private]
cts | Scenario01_GetText | [private]
filter | Scenario01_GetText | [private]
httpClient | Scenario01_GetText | [private]
isFilterUsed | Scenario01_GetText | [private]
MaxHttpVersionToggle_Toggled(object sender, RoutedEventArgs e) | Scenario01_GetText | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario01_GetText | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario01_GetText | [inline, protected]
rootPage | Scenario01_GetText | [private]
Scenario01_GetText() | Scenario01_GetText | [inline]
Start_Click(object sender, RoutedEventArgs e) | Scenario01_GetText | [inline, private]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5 Member List

This is the complete list of members for Scenario5, including all inherited members.
abortButtonId | Scenario5 | [private]
ConnectSocket_Click(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
continueButtonId | Scenario5 | [private]
GetCertificateInformation(Certificate serverCert, IReadOnlyList< Certificate > intermediateCertificates) | Scenario5 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario5 | [inline, protected]
rootPage | Scenario5 | [private]
Scenario5() | Scenario5 | [inline]
ShouldIgnoreCertificateErrorsAsync(IReadOnlyList< ChainValidationResult > serverCertificateErrors) | Scenario5 | [inline, private]
TryConnectSocketWithRetryAsync(StreamSocket socket, HostName hostName) | Scenario5 | [inline, private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundSensors/cs/SampleConfiguration.cs Source File

  • BackgroundSensors
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 using System;
00004 using System.Collections.Generic;
00005 using Windows.UI.Xaml.Controls;
00006
00007 namespace SDKTemplate
00008 {
00009     public partial class MainPage : Page
00010     {
00011         public const string FEATURE_NAME = "Background sensors";
00012
00013         List<Scenario> scenarios = new List<Scenario>
00014         {
00015             new Scenario() { Title="Accelerometer DeviceUse", ClassType=typeof(Scenario1_DeviceUse)}
00016         };
00017     }
00018
00019     public class Scenario
00020     {
00021         public string Title { get; set; }
00022         public Type ClassType { get; set; }
00023     }
00024
00025     public struct SampleConstants
00026     {
00027         public const string Scenario1_DeviceUse_TaskName = "Scenario1_DeviceUse BackgroundTask";
00028         public const string Scenario1_DeviceUse_TaskEntryPoint = "BackgroundTask.Scenario1_BackgroundTask";
00029     }
00030 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cpp/Scenario8_Transmit.xaml.cpp Source File

  • SmartCard
  • cpp

Scenario8_Transmit.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario8_Transmit.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace concurrency;
00009 using namespace Platform;
00010 using namespace Windows::Devices::SmartCards;
00011 using namespace Windows::Foundation;
00012 using namespace Windows::Foundation::Collections;
00013 using namespace Windows::Storage::Streams;
00014 using namespace Windows::Security::Cryptography;
00015 using namespace Windows::Security::Cryptography::Core;
00016 using namespace Windows::UI::Xaml;
00017 using namespace Windows::UI::Xaml::Controls;
00018 using namespace Windows::UI::Xaml::Controls::Primitives;
00019 using namespace Windows::UI::Xaml::Data;
00020 using namespace Windows::UI::Xaml::Input;
00021 using namespace Windows::UI::Xaml::Media;
00022 using namespace Windows::UI::Xaml::Navigation;
00023
00024 Scenario8_Transmit::Scenario8_Transmit()
00025 {
00026     InitializeComponent();
00027 }
00028
00029 void Scenario8_Transmit::Transmit_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00030 {
00031     if (MainPage::Current->SmartCardReaderDeviceId == nullptr)
00032     {
00033         MainPage::Current->NotifyUser("Use Scenario One to create a TPM virtual smart card.", NotifyType::ErrorMessage);
00034         return;
00035     }
00036
00037     Button^ b = dynamic_cast<Button^>(sender);
00038     b->IsEnabled = false;
00039
00040     MainPage::Current->NotifyUser("Transmitting APDU...", NotifyType::StatusMessage);
00041
00042     // Read EF.ATR file
00043     // The command is meant specifically for GIDS cards (such as TPM VSCs),
00044     // and will fail on other types.
00045     Platform::Array<unsigned char>^ readEfAtrBytes = { 0x00, 0xCB, 0x2F, 0x01, 0x02, 0x5C, 0x00, 0xFF };
00046
00047     create_task(MainPage::Current->GetSmartCard()).then(
00048         [=](task<Windows::Devices::SmartCards::SmartCard^> getCardTask)
00049     {
00050         Windows::Devices::SmartCards::SmartCard^ card = getCardTask.get();
00051         return card->ConnectAsync();
00052     }).then(
00053         [=](task<SmartCardConnection^> getConnectionTask)
00054     {
00055         SmartCardConnection^ connection = getConnectionTask.get();
00056
00057         IBuffer^ readEfAtr = CryptographicBuffer::CreateFromByteArray(readEfAtrBytes);
00058
00059         return connection->TransmitAsync(readEfAtr);
00060     }).then(
00061         [=](task<IBuffer^> getResultTask)
00062     {
00063         try
00064         {
00065             IBuffer^ result = getResultTask.get();
00066
00067             MainPage::Current->NotifyUser("Response received: " + CryptographicBuffer::EncodeToHexString(result), NotifyType::StatusMessage);
00068         }
00069         catch (COMException ^ex)
00070         {
00071             MainPage::Current->NotifyUser("Transmit APDU failed with exception: " + ex->ToString(), NotifyType::ErrorMessage);
00072         }
00073
00074         b->IsEnabled = true;
00075     });
00076 }
Generated on Fri Nov 15 2024 22:21:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: GlobalizationPreferences/cs/Scenario4_Input.xaml.cs Source File

  • GlobalizationPreferences
  • cs

Scenario4_Input.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.Foundation;
00013 using Windows.Globalization;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario4_Input : Page
00020     {
00021         public Scenario4_Input()
00022         {
00023             this.InitializeComponent();
00024         }
00025
00026         private void ShowResults_Click(object sender, RoutedEventArgs e)
00027         {
00028             // This scenario uses the Windows.Globalization.Language class to obtain the user's current
00029             // input language.  The language tag returned reflects the current input language specified
00030             // by the user.
00031             var userInputLanguage = Windows.Globalization.Language.CurrentInputMethodLanguageTag;
00032
00033             // Display the results
00034             OutputTextBlock.Text = "User's current input language: " + userInputLanguage;
00035         }
00036     }
00037 }
Generated on Fri Nov 15 2024 22:19:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AssociationLaunching/cs/Scenario2_LaunchUri.xaml.cs Source File

  • AssociationLaunching
  • cs

Scenario2_LaunchUri.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Foundation;
00014 using Windows.System;
00015 using Windows.UI.ViewManagement;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class Scenario2_LaunchUri : Page
00026     {
00027         // A pointer back to the main page. This is needed if you want to call methods in MainPage such as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         public Scenario2_LaunchUri()
00031         {
00032             this.InitializeComponent();
00033             ViewPreference.ItemsSource = MainPage.ViewSizePreferences;
00034             ViewPreference.SelectedIndex = 0;
00035         }
00036
00037         /// <summary>
00038         // Launch a URI.
00039         /// </summary>
00040         private async void LaunchUriDefault()
00041         {
00042             // Create the URI to launch from a string.
00043             var uri = new Uri(UriToLaunch.Text);
00044
00045             // Launch the URI.
00046             bool success = await Launcher.LaunchUriAsync(uri);
00047             if (success)
00048             {
00049                 rootPage.NotifyUser("URI launched: " + uri.AbsoluteUri, NotifyType.StatusMessage);
00050             }
00051             else
00052             {
00053                 rootPage.NotifyUser("URI launch failed.", NotifyType.ErrorMessage);
00054             }
00055         }
00056
00057         /// <summary>
00058         // Launch a URI. Show a warning prompt.
00059         /// </summary>
00060         private async void LaunchUriWithWarning()
00061         {
00062             // Create the URI to launch from a string.
00063             var uri = new Uri(UriToLaunch.Text);
00064
00065             // Configure the warning prompt.
00066             var options = new LauncherOptions() { TreatAsUntrusted = true };
00067
00068             // Launch the URI.
00069             bool success = await Launcher.LaunchUriAsync(uri, options);
00070             if (success)
00071             {
00072                 rootPage.NotifyUser("URI launched: " + uri.AbsoluteUri, NotifyType.StatusMessage);
00073             }
00074             else
00075             {
00076                 rootPage.NotifyUser("URI launch failed.", NotifyType.ErrorMessage);
00077             }
00078         }
00079
00080         /// <summary>
00081         // Launch a URI. Show an Open With dialog that lets the user chose the handler to use.
00082         /// </summary>
00083         private async void LaunchUriOpenWith(object sender, RoutedEventArgs e)
00084         {
00085             // Create the URI to launch from a string.
00086             var uri = new Uri(UriToLaunch.Text);
00087
00088             // Calulcate the position for the Open With dialog.
00089             // An alternative to using the point is to set the rect of the UI element that triggered the launch.
00090             Point openWithPosition = MainPage.GetElementLocation(sender);
00091
00092             // Next, configure the Open With dialog.
00093             var options = new LauncherOptions();
00094             options.DisplayApplicationPicker = true;
00095             options.UI.InvocationPoint = openWithPosition;
00096             options.UI.PreferredPlacement = Windows.UI.Popups.Placement.Below;
00097
00098             // Launch the URI.
00099             bool success = await Launcher.LaunchUriAsync(uri, options);
00100             if (success)
00101             {
00102                 rootPage.NotifyUser("URI launched: " + uri.AbsoluteUri, NotifyType.StatusMessage);
00103             }
00104             else
00105             {
00106                 rootPage.NotifyUser("URI launch failed.", NotifyType.ErrorMessage);
00107             }
00108         }
00109
00110         /// <summary>
00111         // Launch a URI. Request to share the screen with the launched app.
00112         /// </summary>
00113         private async void LaunchUriSplitScreen()
00114         {
00115             // Create the URI to launch from a string.
00116             var uri = new Uri(UriToLaunch.Text);
00117
00118             // Configure the request for split screen launch.
00119             var options = new LauncherOptions() { DesiredRemainingView = (ViewSizePreference)ViewPreference.SelectedValue };
00120
00121             // Launch the URI.
00122             bool success = await Launcher.LaunchUriAsync(uri, options);
00123             if (success)
00124             {
00125                 rootPage.NotifyUser("URI launched: " + uri.AbsoluteUri, NotifyType.StatusMessage);
00126             }
00127             else
00128             {
00129                 rootPage.NotifyUser("URI launch failed.", NotifyType.ErrorMessage);
00130             }
00131         }
00132     }
00133 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PosPrinter/cpp/Scenario3_MultipleClaims.xaml.h Source File

  • PosPrinter
  • cpp

Scenario3_MultipleClaims.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_MultipleClaims.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario3_MultipleClaims sealed
00024     {
00025     public:
00026         Scenario3_MultipleClaims();
00027
00028     protected:
00029         void ClaimSamePrinter_Click();
00030
00031     private:
00032         MainPage^ rootPage = MainPage::Current;
00033     };
00034 }
Generated on Fri Nov 15 2024 22:20:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PersonalDataEncryption/cppwinrt/Project.idl Source File

  • PersonalDataEncryption
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_Files : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_Files();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_Memory : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_Memory();
00024     }
00025 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaEditing/cpp/SampleConfiguration.cpp Source File

  • MediaEditing
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Trimming and Saving a clip", "SDKTemplate.Scenario1_TrimAndSaveClip" },
00021     { "Appending multiple clips", "SDKTemplate.Scenario2_AppendClips" },
00022     { "Adding background audio tracks", "SDKTemplate.Scenario3_AddAudioTracks" },
00023     { "Adding overlays to a clip", "SDKTemplate.Scenario4_AddOverlays" }
00024 };
Generated on Fri Nov 15 2024 22:17:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraManualControls/cs/MainPage.WhiteBalance.xaml.cs Source File

  • CameraManualControls
  • cs

MainPage.WhiteBalance.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017 using Windows.Media.Devices;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml;
00020
00021 namespace CameraManualControls
00022 {
00023     public sealed partial class MainPage : Page
00024     {
00025
00026         private void UpdateWbControlCapabilities()
00027         {
00028             var whiteBalanceControl = _mediaCapture.VideoDeviceController.WhiteBalanceControl;
00029
00030             if (whiteBalanceControl.Supported)
00031             {
00032                 WbButton.Tag = Visibility.Visible;
00033
00034                 if (WbComboBox.ItemsSource == null)
00035                 {
00036                     WbComboBox.ItemsSource = Enum.GetValues(typeof(ColorTemperaturePreset)).Cast<ColorTemperaturePreset>();
00037                 }
00038
00039                 WbComboBox.SelectedItem = whiteBalanceControl.Preset;
00040
00041                 if (whiteBalanceControl.Max - whiteBalanceControl.Min > whiteBalanceControl.Step)
00042                 {
00043                     // Unhook the event handler, so that changing properties on the slider won't trigger an API call
00044                     WbSlider.ValueChanged -= WbSlider_ValueChanged;
00045
00046                     var value = whiteBalanceControl.Value;
00047                     WbSlider.Minimum = whiteBalanceControl.Min;
00048                     WbSlider.Maximum = whiteBalanceControl.Max;
00049                     WbSlider.StepFrequency = whiteBalanceControl.Step;
00050                     WbSlider.Value = value;
00051
00052                     WbSlider.ValueChanged += WbSlider_ValueChanged;
00053                 }
00054                 else
00055                 {
00056                     WbSlider.Visibility = Visibility.Collapsed;
00057                     WbTextBox.Visibility = Visibility.Collapsed;
00058                 }
00059             }
00060             else
00061             {
00062                 WbButton.Visibility = Visibility.Collapsed;
00063                 WbButton.Tag = Visibility.Collapsed;
00064             }
00065         }
00066
00067         private async void WbComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
00068         {
00069             var selected = (ColorTemperaturePreset)WbComboBox.SelectedItem;
00070
00071             WbSlider.IsEnabled = (selected == ColorTemperaturePreset.Manual);
00072
00073             await _mediaCapture.VideoDeviceController.WhiteBalanceControl.SetPresetAsync(selected);
00074
00075             // Note: Automatic white balance can be locked to the current value by setting the preset to manual and not passing in a value to the control
00076         }
00077
00078         private async void WbSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e)
00079         {
00080             if (_settingUpUi) return;
00081
00082             var value = (sender as Slider).Value;
00083
00084             await _mediaCapture.VideoDeviceController.WhiteBalanceControl.SetValueAsync((uint)value);
00085         }
00086
00087     }
00088 }
Generated on Fri Nov 15 2024 22:18:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TitleBar/cpp/SampleConfiguration.h Source File

  • TitleBar
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "CustomTitleBar.xaml.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Title bar";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038         void AddCustomTitleBar();
00039         void RemoveCustomTitleBar();
00040         property bool AreControlsInTitleBar
00041         {
00042             bool get()
00043             {
00044                 return areControlsInTitleBar;
00045             }
00046             void set(bool value);
00047         }
00048
00049     private:
00050         static Platform::Array<Scenario>^ scenariosInner;
00051
00052         CustomTitleBar^ customTitleBar = nullptr;
00053         bool areControlsInTitleBar = false;
00054     };
00055
00056     public value struct Scenario
00057     {
00058         Platform::String^ Title;
00059         Platform::String^ ClassName;
00060     };
00061 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_AppendClips Member List

This is the complete list of members for Scenario2_AppendClips, including all inherited members.
AppendVideos_Click(object sender, RoutedEventArgs e) | Scenario2_AppendClips | [inline, private]
ChooseFirstVideo_Click(object sender, RoutedEventArgs e) | Scenario2_AppendClips | [inline, private]
ChooseSecondVideo_Click(object sender, RoutedEventArgs e) | Scenario2_AppendClips | [inline, private]
composition | Scenario2_AppendClips | [private]
firstVideoFile | Scenario2_AppendClips | [private]
mediaStreamSource | Scenario2_AppendClips | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_AppendClips | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_AppendClips | [inline, protected]
rootPage | Scenario2_AppendClips | [private]
Scenario2_AppendClips() | Scenario2_AppendClips | [inline]
secondVideoFile | Scenario2_AppendClips | [private]
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cppwinrt/pch.h Source File

  • FilePicker
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Storage.h"
00008 #include "winrt/Windows.Storage.AccessCache.h"
00009 #include "winrt/Windows.Storage.Pickers.h"
00010 #include "winrt/Windows.Storage.Pickers.Provider.h"
00011 #include "winrt/Windows.System.h"
00012 #include "winrt/Windows.UI.Core.h"
00013 #include "winrt/Windows.UI.Xaml.h"
00014 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00015 #include "winrt/Windows.UI.Xaml.Controls.h"
00016 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00017 #include "winrt/Windows.UI.Xaml.Documents.h"
00018 #include "winrt/Windows.UI.Xaml.Interop.h"
00019 #include "winrt/Windows.UI.Xaml.Markup.h"
00020 #include "winrt/Windows.UI.Xaml.Media.h"
00021 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Scenario5_GetSingleDevice.h Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

Scenario5_GetSingleDevice.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario5_GetSingleDevice.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario5_GetSingleDevice : Scenario5_GetSingleDeviceT<Scenario5_GetSingleDevice>
00020     {
00021         Scenario5_GetSingleDevice();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024
00025         fire_and_forget Page_Loaded(IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026         fire_and_forget GetButton_Click(IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027
00028     private:
00029         SDKTemplate::MainPage rootPage{ SDKTemplate::implementation::MainPage::Current() };
00030         Windows::Devices::Enumeration::DeviceInformationKind deviceInformationKind;
00031         Windows::Foundation::Collections::IObservableVector<SDKTemplate::DeviceInformationDisplay> resultCollection = winrt::single_threaded_observable_vector<SDKTemplate::DeviceInformationDisplay>();
00032     };
00033 }
00034
00035 namespace winrt::SDKTemplate::factory_implementation
00036 {
00037     struct Scenario5_GetSingleDevice : Scenario5_GetSingleDeviceT<Scenario5_GetSingleDevice, implementation::Scenario5_GetSingleDevice>
00038     {
00039     };
00040 }
Generated on Fri Nov 15 2024 22:19:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cpp/WiFiDirectServicesWrappers.h Source File

  • WiFiDirectServices
  • cpp

WiFiDirectServicesWrappers.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <condition_variable>
00015
00016 namespace SDKTemplate
00017 {
00018     namespace WiFiDirectServices
00019     {
00020         ref class WiFiDirectServiceManager;
00021
00022         /// <summary>
00023         /// Wraps WiFiDirectServiceAdvertiser and handles callbacks and related state
00024         /// </summary>
00025         [Windows::UI::Xaml::Data::Bindable]
00026         public ref class AdvertisementWrapper sealed
00027         {
00028         private:
00029             Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser^ _advertiser = nullptr;
00030             // Used to update main state
00031             WiFiDirectServiceManager^ _manager = nullptr;
00032
00033             std::mutex _advertiserMutex;
00034
00035             // PIN to use for display config method (if selected)
00036             Platform::String^ _pin = "";
00037
00038             // Keep track of incoming service requests that need to be accepted or rejected
00039             Windows::Foundation::Collections::IVector<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionRequest^>^ _requestList
00040                 = ref new Platform::Collections::Vector<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionRequest^>();
00041
00042             // Keep internal identifier
00043             int _uniqueInternalId;
00044             static int _nextId;
00045
00046             // Keep tokens to cleanup event handlers
00047             Windows::Foundation::EventRegistrationToken _advertisementStatusChangedToken;
00048             Windows::Foundation::EventRegistrationToken _autoAcceptSessionConnectedToken;
00049             Windows::Foundation::EventRegistrationToken _sessionRequestedToken;
00050
00051         public:
00052             AdvertisementWrapper(
00053                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser^ advertiser,
00054                 WiFiDirectServiceManager^ manager,
00055                 Platform::String^ pin
00056                 );
00057             virtual ~AdvertisementWrapper();
00058
00059             property Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser^ Advertiser
00060             {
00061                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser^ get() { return _advertiser; }
00062             }
00063
00064             property int InternalId
00065             {
00066                 int get() { return _uniqueInternalId; }
00067             }
00068
00069             property Platform::String^ Pin
00070             {
00071                 Platform::String^ get() { return _pin; }
00072             }
00073
00074             property Platform::String^ Name
00075             {
00076                 Platform::String^ get() { return _advertiser->ServiceName; }
00077             }
00078
00079             property Platform::String^ Status
00080             {
00081                 Platform::String^ get() { return _advertiser->AdvertisementStatus.ToString(); }
00082             }
00083
00084             property Windows::Foundation::Collections::IVector<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionRequest^>^ SessionRequestList
00085             {
00086                 Windows::Foundation::Collections::IVector<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionRequest^>^ get()
00087                 {
00088                     return _requestList;
00089                 }
00090             }
00091
00092         internal:
00093             void AcceptSessionRequest(Platform::String^ id, Platform::String^ pin = "");
00094
00095             void DeclineSessionRequest(Platform::String^ id);
00096
00097         private:
00098             // NOTE: this is mutually exclusive with OnAutoAcceptSessionConnected
00099             void OnSessionRequested(
00100                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser^ sender,
00101                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionRequestedEventArgs^ args
00102                 );
00103
00104             // NOTE: this is mutually exclusive with OnSessionRequested
00105             void OnAutoAcceptSessionConnected(
00106                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser^ sender,
00107                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAutoAcceptSessionConnectedEventArgs^ args
00108                 );
00109
00110             void OnAdvertisementStatusChanged(
00111                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceAdvertiser^ sender,
00112                 Platform::Object^ args
00113                 );
00114         };
00115
00116         [Windows::UI::Xaml::Data::Bindable]
00117         public ref class DiscoveredDeviceWrapper sealed
00118         {
00119         private:
00120             Windows::Devices::Enumeration::DeviceInformation^ _deviceInfo;
00121             // Used to update main state
00122             WiFiDirectServiceManager^ _manager = nullptr;
00123
00124             // When we start opening/connecting to a session we store this (only used for a single connect)
00125             Windows::Devices::WiFiDirect::Services::WiFiDirectService^ _service = nullptr;
00126
00127             // Keep tokens to cleanup event handlers
00128             Windows::Foundation::EventRegistrationToken _sessionDeferredToken;
00129         public:
00130             DiscoveredDeviceWrapper(
00131                 Windows::Devices::Enumeration::DeviceInformation^ deviceInfo,
00132                 WiFiDirectServiceManager^ manager
00133                 );
00134             virtual ~DiscoveredDeviceWrapper();
00135
00136             // Expose properties from the discovered device
00137             property Platform::String^ ServiceName;
00138             property Platform::String^ ServiceAddress;
00139             property unsigned int AdvertisementId;
00140             property unsigned int ConfigMethods;
00141             property Platform::String^ ServiceInfo;
00142
00143         internal:
00144             /// <summary>
00145             /// Calls WiFiDirectService.FromId to open the seeker session
00146             /// Caller can then use this.Service to modify settings before connecting
00147             /// </summary>
00148             Concurrency::task<void> OpenSessionAsync();
00149
00150             /// <summary>
00151             /// Call this to set options before doing the actual connect
00152             /// </summary>
00153             /// <param name="preferGO">If true, this peer will prefer to be the group owner (GO) of the connection</param>
00154             /// <param name="sessionInfo">Optional 144 byte buffer to send with the request to the advertising peer</param>
00155             Concurrency::task<void> SetServiceOptionsAsync(bool preferGO, Platform::String^ sessionInfo);
00156
00157             /// <summary>
00158             /// Calls service.GetProvisioningInfoAsync to begin provision discovery and
00159             /// determine if a PIN will be needed to connect
00160             /// </summary>
00161             /// <param name="configMethod">Selected Config Method to use, based on supported config methods of discovered device</param>
00162             Concurrency::task<Windows::Devices::WiFiDirect::Services::WiFiDirectServiceProvisioningInfo^> GetProvisioningInfoAsync(
00163                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceConfigurationMethod configMethod
00164                 );
00165
00166             /// <summary>
00167             /// Calls service.ConnectAsync() to connect the session
00168             /// If the session is not already opened, it calls OpenSession
00169             /// </summary>
00170             /// <param name="pin">Optional PIN if needed</param>
00171             Concurrency::task<void> ConnectAsync(Platform::String^ pin = "");
00172
00173         private:
00174             void OnSessionDeferred(
00175                 Windows::Devices::WiFiDirect::Services::WiFiDirectService^ sender,
00176                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionDeferredEventArgs^ args
00177                 );
00178
00179             void ParseProperties();
00180         };
00181
00182         ref class SessionWrapper;
00183
00184         public ref class StreamSocketListenerWrapper sealed
00185         {
00186         private:
00187             Windows::Networking::Sockets::StreamSocketListener^ _streamSocketListener;
00188             // Used to update main state
00189             WiFiDirectServiceManager^ _manager = nullptr;
00190
00191             SessionWrapper^ _session = nullptr;
00192
00193             // Keep tokens to cleanup event handlers
00194             Windows::Foundation::EventRegistrationToken _connectionReceivedToken;
00195
00196         public:
00197             StreamSocketListenerWrapper(
00198                 WiFiDirectServiceManager^ manager,
00199                 Windows::Networking::Sockets::StreamSocketListener^ streamSocketListener,
00200                 SessionWrapper^ session
00201                 );
00202             virtual ~StreamSocketListenerWrapper();
00203
00204         private:
00205             void OnConnectionReceived(
00206                 Windows::Networking::Sockets::StreamSocketListener^ sender,
00207                 Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs^ args
00208                 );
00209         };
00210
00211         // Generic wrapper for TCP (Stream) or UDP (Datagram) socket
00212         // For this sample, this just allows messages to be sent between connected peers,
00213         // real application would handle higher level logic over the connected socket(s)
00214         [Windows::UI::Xaml::Data::Bindable]
00215         public ref class SocketWrapper sealed
00216         {
00217         private:
00218             Windows::Networking::Sockets::StreamSocket^ _streamSocket = nullptr;
00219             Windows::Networking::Sockets::DatagramSocket^ _datagramSocket = nullptr;
00220             // Used to update main state
00221             WiFiDirectServiceManager^ _manager = nullptr;
00222
00223             Windows::Storage::Streams::DataReader^ _reader = nullptr;
00224             Windows::Storage::Streams::DataWriter^ _writer = nullptr;
00225
00226             // Keep tokens to cleanup event handlers
00227             Windows::Foundation::EventRegistrationToken _datagramMessageReceivedToken;
00228
00229         public:
00230             SocketWrapper(
00231                 WiFiDirectServiceManager^ manager,
00232                 Windows::Networking::Sockets::StreamSocket^ streamSocket,
00233                 Windows::Networking::Sockets::DatagramSocket^ datagramSocket,
00234                 bool canSend
00235                 );
00236             virtual ~SocketWrapper();
00237
00238             property Platform::String^ Protocol
00239             {
00240                 Platform::String^ get();
00241             }
00242             property Platform::String^ Port
00243             {
00244                 Platform::String^ get();
00245             }
00246
00247         internal:
00248             /// <summary>
00249             /// Send a string over the socket (TCP or UDP)
00250             /// Will send as a uint32 size followed by the message
00251             /// </summary>
00252             /// <param name="message">Message to send</param>
00253             Concurrency::task<void> SendMessageAsync(Platform::String^ message);
00254
00255             void StartReceiveLoop();
00256
00257             /// <summary>
00258             /// Read strings sent over the TCP socket
00259             /// Reads the uint32 size then the actual string
00260             /// </summary>
00261             Concurrency::task<void> ReceiveMessageAsync();
00262
00263         private:
00264
00265             void OnUDPMessageReceived(
00266                 Windows::Networking::Sockets::DatagramSocket^ sender,
00267                 Windows::Networking::Sockets::DatagramSocketMessageReceivedEventArgs^ args
00268                 );
00269         };
00270
00271         [Windows::UI::Xaml::Data::Bindable]
00272         public ref class SessionWrapper sealed
00273         {
00274         private:
00275             Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession^ _session;
00276             // Used to update main state
00277             WiFiDirectServiceManager^ _manager = nullptr;
00278
00279             // Stream Socket Listeners are created when locally opening TCP ports
00280             Windows::Foundation::Collections::IVector<StreamSocketListenerWrapper^>^ _streamSocketListeners
00281                 = ref new Platform::Collections::Vector<StreamSocketListenerWrapper^>();
00282
00283             // Keep a list of connected sockets
00284             Windows::Foundation::Collections::IVector<SocketWrapper^>^ _socketList
00285                 = ref new Platform::Collections::Vector<SocketWrapper^>();
00286
00287             // Keep tokens to cleanup event handlers
00288             Windows::Foundation::EventRegistrationToken _remotePortAddedToken;
00289             Windows::Foundation::EventRegistrationToken _sessionStatusChangedToken;
00290
00291             // Used to wait for the session to close before cleaning up the wrapper
00292             Concurrency::event _sessionClosedEvent;
00293
00294             // Protect changes to the _session member
00295             std::mutex _sessionMutex;
00296
00297         public:
00298             SessionWrapper(
00299                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession^ session,
00300                 WiFiDirectServiceManager^ manager);
00301             virtual ~SessionWrapper();
00302
00303             property Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession^ Session
00304             {
00305                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession^ get()
00306                 {
00307                     std::lock_guard<std::mutex> lock(_sessionMutex);
00308                     return _session;
00309                 }
00310             }
00311
00312             property unsigned int AdvertisementId
00313             {
00314                 unsigned int get() { return _session->AdvertisementId; }
00315             }
00316             property unsigned int SessionId
00317             {
00318                 unsigned int get() { return _session->SessionId; }
00319             }
00320
00321             property Platform::String^ ServiceAddress
00322             {
00323                 Platform::String^ get() { return _session->ServiceAddress; }
00324             }
00325
00326             property Platform::String^ SessionAddress
00327             {
00328                 Platform::String^ get() { return _session->SessionAddress; }
00329             }
00330
00331             property Windows::Foundation::Collections::IVector<SocketWrapper^>^ SocketList
00332             {
00333                 Windows::Foundation::Collections::IVector<SocketWrapper^>^ get() { return _socketList; }
00334             }
00335
00336         internal:
00337             void Close();
00338
00339             Concurrency::task<void> AddStreamSocketListenerAsync(uint16 port);
00340
00341             Concurrency::task<void> AddDatagramSocketAsync(uint16 port);
00342
00343             void AddStreamSocketInternal(Windows::Networking::Sockets::StreamSocket^ socket);
00344
00345         private:
00346             // This will fire when the connected peer attempts to open a port for this connection
00347             // The peer should start a stream socket listener (for TCP)
00348             void OnRemotePortAdded(
00349                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession^ sender,
00350                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceRemotePortAddedEventArgs^ args
00351                 );
00352
00353             void OnSessionStatusChanged(
00354                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession^ sender,
00355                 Platform::Object^ args
00356                 );
00357         };
00358
00359     }
00360 }
Generated on Fri Nov 15 2024 22:22:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cppwinrt/pch.h Source File

  • JumpList
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <unknwn.h>
00015 #include "winrt/Windows.Foundation.h"
00016 #include "winrt/Windows.Foundation.Collections.h"
00017 #include "winrt/Windows.ApplicationModel.Activation.h"
00018 #include "winrt/Windows.Storage.h"
00019 #include "winrt/Windows.Storage.AccessCache.h"
00020 #include "winrt/Windows.System.h"
00021 #include "winrt/Windows.UI.Core.h"
00022 #include "winrt/Windows.UI.StartScreen.h"
00023 #include "winrt/Windows.UI.Xaml.h"
00024 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00025 #include "winrt/Windows.UI.Xaml.Controls.h"
00026 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00027 #include "winrt/Windows.UI.Xaml.Documents.h"
00028 #include "winrt/Windows.UI.Xaml.Interop.h"
00029 #include "winrt/Windows.UI.Xaml.Markup.h"
00030 #include "winrt/Windows.UI.Xaml.Media.h"
00031 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationData/cppwinrt/SampleConfiguration.h Source File

  • ApplicationData
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017 }
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFont/Scenario_Document2.xaml.h Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFont

Scenario_Document2.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario_Document2.g.h"
00015 #include "MainPage.xaml.h"
00016 #include "DocumentPresenter.h"
00017
00018
00019 namespace SDKTemplate
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class Scenario_Document2 sealed
00023     {
00024     public:
00025         Scenario_Document2();
00026
00027     protected:
00028         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029
00030     private:
00031         DocumentPresenter^                              m_documentPresenter;
00032
00033         void TextLayoutFrame_SizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00034     };
00035 }
Generated on Fri Nov 15 2024 22:19:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RegisterWithBackgroundTask Member List

This is the complete list of members for RegisterWithBackgroundTask, including all inherited members.
BackgroundTaskEntryPoint | RegisterWithBackgroundTask | [private]
BackgroundTaskName | RegisterWithBackgroundTask | [private]
InitializeRegisteredSmsBackgroundTasks() | RegisterWithBackgroundTask | [inline]
OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e) | RegisterWithBackgroundTask | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | RegisterWithBackgroundTask | [inline, protected]
Register_Click(object sender, RoutedEventArgs e) | RegisterWithBackgroundTask | [inline, private]
RegisterWithBackgroundTask() | RegisterWithBackgroundTask | [inline]
rootPage | RegisterWithBackgroundTask | [private]
sampleDispatcher | RegisterWithBackgroundTask | [private]
Unregister_Click(object sender, RoutedEventArgs e) | RegisterWithBackgroundTask | [inline, private]
UpdateBackgroundTaskUIState(bool Registered) | RegisterWithBackgroundTask | [inline, private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AudioCapturePermissions Member List

This is the complete list of members for AudioCapturePermissions, including all inherited members.
NoCaptureDevicesHResult | AudioCapturePermissions | [private, static]
RequestMicrophonePermission() | AudioCapturePermissions | [inline, static]
Generated on Fri Nov 15 2024 22:23:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialStage/cpp/SpatialStageManager.cpp Source File

  • HolographicSpatialStage
  • cpp

SpatialStageManager.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "SpatialStageManager.h"
00003
00004 using namespace HolographicSpatialStage;
00005
00006 using namespace DirectX;
00007 using namespace Platform;
00008 using namespace std::placeholders;
00009 using namespace Windows::Foundation;
00010 using namespace Windows::Perception::Spatial;
00011 using namespace Windows::Foundation::Numerics;
00012
00013 SpatialStageManager::SpatialStageManager(
00014     const std::shared_ptr<DX::DeviceResources>& deviceResources,
00015     const std::shared_ptr<SceneController>& sceneController)
00016     : m_deviceResources(deviceResources), m_sceneController(sceneController)
00017 {
00018     // Get notified when the stage is updated.
00019     m_spatialStageChangedEventToken = SpatialStageFrameOfReference::CurrentChanged +=
00020         ref new EventHandler<Object^>(std::bind(&SpatialStageManager::OnCurrentChanged, this, _1));
00021
00022     // Make sure to get the current spatial stage.
00023     OnCurrentChanged(nullptr);
00024 }
00025
00026 SpatialStageManager::~SpatialStageManager()
00027 {
00028     SpatialStageFrameOfReference::CurrentChanged -= m_spatialStageChangedEventToken;
00029 }
00030
00031 void SpatialStageManager::OnCurrentChanged(Object^ /*o*/)
00032 {
00033     // The event notifies us that a new stage is available.
00034     // Get the current stage.
00035     m_currentStage = SpatialStageFrameOfReference::Current;
00036     m_currentCoordinateSystem = nullptr;
00037     m_stationaryFrameOfReference = nullptr;
00038
00039     // Clear previous content.
00040     m_sceneController->ClearSceneObjects();
00041
00042     XMFLOAT3 visibleAreaColor;
00043     std::vector<float3> visibleAreaIndicatorVertices;
00044
00045     if (m_currentStage != nullptr)
00046     {
00047         // Obtain stage geometry.
00048         m_currentCoordinateSystem = m_currentStage->CoordinateSystem;
00049         auto boundsVertexArray = m_currentStage->TryGetMovementBounds(m_currentCoordinateSystem);
00050         if (boundsVertexArray->Length > 0)
00051         {
00052             // Visualize the area where the user can move around.
00053             std::vector<float3> boundsVertices;
00054             boundsVertices.resize(boundsVertexArray->Length);
00055             memcpy(boundsVertices.data(), boundsVertexArray->Data, boundsVertexArray->Length * sizeof(float3));
00056             std::vector<unsigned short> indices = TriangulatePoints(boundsVertices);
00057             m_stageBoundsShape =
00058                 std::make_shared<SceneObject>(
00059                     m_deviceResources,
00060                     reinterpret_cast<std::vector<XMFLOAT3>&>(boundsVertices),
00061                     indices,
00062                     XMFLOAT3(DirectX::Colors::SeaGreen),
00063                     m_currentCoordinateSystem);
00064             m_sceneController->AddSceneObject(m_stageBoundsShape);
00065         }
00066
00067         // In this sample, we draw a visual indicator for some spatial stage properties.
00068         // If the view is forward-only, the indicator is a half circle pointing forward - otherwise, it
00069         // is a full circle.
00070         // If the user can walk around, the indicator is blue. If the user is seated, it is red.
00071
00072         // The indicator is rendered at the origin - which is where the user declared the center of the
00073         // stage to be during setup - above the plane of the stage bounds object.
00074         float3 visibleAreaCenter = float3(0.f, 0.001f, 0.f);
00075
00076         // Its shape depends on the look direction range.
00077         if (m_currentStage->LookDirectionRange == SpatialLookDirectionRange::ForwardOnly)
00078         {
00079             // Half circle for forward-only look direction range.
00080             visibleAreaIndicatorVertices = CreateCircle(visibleAreaCenter, 0.25f, 9, XM_PI);
00081         }
00082         else
00083         {
00084             // Full circle for omnidirectional look direction range.
00085             visibleAreaIndicatorVertices = CreateCircle(visibleAreaCenter, 0.25f, 16, XM_2PI);
00086         }
00087
00088         // Its color depends on the movement range.
00089         if (m_currentStage->MovementRange == SpatialMovementRange::NoMovement)
00090         {
00091             visibleAreaColor = XMFLOAT3(DirectX::Colors::OrangeRed);
00092         }
00093         else
00094         {
00095             visibleAreaColor = XMFLOAT3(DirectX::Colors::Aqua);
00096         }
00097     }
00098     else
00099     {
00100         // No spatial stage was found.
00101         // Fall back to a stationary coordinate system.
00102         auto locator = SpatialLocator::GetDefault();
00103         if (locator)
00104         {
00105             m_stationaryFrameOfReference = locator->CreateStationaryFrameOfReferenceAtCurrentLocation(float3(0.f, -0.5f, 0.f));
00106             if (m_stationaryFrameOfReference)
00107             {
00108                 m_currentCoordinateSystem = m_stationaryFrameOfReference->CoordinateSystem;
00109
00110                 // Render an indicator, so that we know we fell back to a mode without a stage.
00111                 visibleAreaIndicatorVertices = CreateCircle(float3(0.f), 0.125f, 16, XM_2PI);
00112                 visibleAreaColor = XMFLOAT3(DirectX::Colors::LightSlateGray);
00113             }
00114         }
00115     }
00116
00117     if (m_currentCoordinateSystem != nullptr)
00118     {
00119         std::vector<unsigned short> visibleAreaIndicatorIndices = TriangulatePoints(visibleAreaIndicatorVertices);
00120         m_stageVisibleAreaIndicatorShape =
00121             std::make_shared<SceneObject>(
00122                 m_deviceResources,
00123                 reinterpret_cast<std::vector<XMFLOAT3>&>(visibleAreaIndicatorVertices),
00124                 visibleAreaIndicatorIndices,
00125                 visibleAreaColor,
00126                 m_currentCoordinateSystem);
00127         m_sceneController->AddSceneObject(m_stageVisibleAreaIndicatorShape);
00128     }
00129 }
00130
00131 SpatialCoordinateSystem^ SpatialStageManager::GetCoordinateSystemForCurrentStage()
00132 {
00133     return m_currentCoordinateSystem;
00134 }
00135
00136 // Creates a 2D circle in the x-z plane, with the specified properties.
00137 std::vector<float3> SpatialStageManager::CreateCircle(float3 center, float radius, int divisions, float radians)
00138 {
00139     std::vector<float3> vertices(divisions);
00140
00141     for (int i = 0; i < divisions; ++i)
00142     {
00143         float radiansThisIteration = radians * float(i) / float(divisions);
00144         vertices[i] =
00145             {
00146                 center.x + (radius * -cos(radiansThisIteration)),
00147                 center.y,
00148                 center.z + (radius * -sin(radiansThisIteration))
00149             };
00150     }
00151
00152     return vertices;
00153 }
00154
00155 // Triangulates a 2D shape, such as the spatial stage movement bounds.
00156 // This function expects a set of vertices that define the boundaries of a shape, in
00157 // clockwise order.
00158 std::vector<unsigned short> SpatialStageManager::TriangulatePoints(std::vector<float3> const& vertices)
00159 {
00160     size_t const& vertexCount = vertices.size();
00161
00162     // Segments of the shape are removed as they are triangularized.
00163     std::vector<bool> vertexRemoved;
00164     vertexRemoved.resize(vertexCount, false);
00165     unsigned int vertexRemovedCount = 0;
00166
00167     // Indices are used to define triangles.
00168     std::vector<unsigned short> indices;
00169
00170     // Decompose into convex segments.
00171     unsigned short currentVertex = 0;
00172     while (vertexRemovedCount < (vertexCount - 2))
00173     {
00174         // Get next triangle:
00175         // Start with the current vertex.
00176         unsigned short index1 = currentVertex;
00177
00178         // Get the next available vertex.
00179         unsigned short index2 = index1 + 1;
00180
00181         // This cycles to the next available index.
00182         auto CycleIndex = [=](unsigned short indexToCycle, unsigned short stopIndex)
00183         {
00184             // Make sure the index does not exceed bounds.
00185             if (indexToCycle >= unsigned short(vertexCount))
00186             {
00187                 indexToCycle -= unsigned short(vertexCount);
00188             }
00189
00190             while (vertexRemoved[indexToCycle])
00191             {
00192                 // If the vertex is removed, go to the next available one.
00193                 ++indexToCycle;
00194
00195                 // Make sure the index does not exceed bounds.
00196                 if (indexToCycle >= unsigned short(vertexCount))
00197                 {
00198                     indexToCycle -= unsigned short(vertexCount);
00199                 }
00200
00201                 // Prevent cycling all the way around.
00202                 // Should not be needed, as we limit with the vertex count.
00203                 if (indexToCycle == stopIndex)
00204                 {
00205                     break;
00206                 }
00207             }
00208
00209             return indexToCycle;
00210         };
00211         index2 = CycleIndex(index2, index1);
00212
00213         // Get the next available vertex after that.
00214         unsigned short index3 = index2 + 1;
00215         index3 = CycleIndex(index3, index1);
00216
00217         // Vertices that may define a triangle inside the 2D shape.
00218         auto& v1 = vertices[index1];
00219         auto& v2 = vertices[index2];
00220         auto& v3 = vertices[index3];
00221
00222         // If the projection of the first segment (in clockwise order) onto the second segment is
00223         // positive, we know that the clockwise angle is less than 180 degrees, which tells us
00224         // that the triangle formed by the two segments is contained within the bounding shape.
00225         auto v2ToV1 = v1 - v2;
00226         auto v2ToV3 = v3 - v2;
00227         float3 normalToV2ToV3 = { -v2ToV3.z, 0.f, v2ToV3.x };
00228         float projectionOntoNormal = dot(v2ToV1, normalToV2ToV3);
00229         if (projectionOntoNormal >= 0)
00230         {
00231             // Triangle is contained within the 2D shape.
00232
00233             // Remove peak vertex from the list.
00234             vertexRemoved[index2] = true;
00235             ++vertexRemovedCount;
00236
00237             // Create the triangle.
00238             indices.push_back(index1);
00239             indices.push_back(index2);
00240             indices.push_back(index3);
00241
00242             // Continue on to the next outer triangle.
00243             currentVertex = index3;
00244         }
00245         else
00246         {
00247             // Triangle is a cavity in the 2D shape.
00248             // The next triangle starts at the inside corner.
00249             currentVertex = index2;
00250         }
00251     }
00252
00253     indices.shrink_to_fit();
00254     return indices;
00255 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SampleHelpers Member List

This is the complete list of members for SampleHelpers, including all inherited members.
AppBarTileId | SampleHelpers | [static]
CurrentTimeAsString() | SampleHelpers | [static]
DynamicTileId | SampleHelpers | [static]
GetElementRect(Windows::Foundation::IInspectable const &e) | SampleHelpers | [static]
LogoSecondaryTileId | SampleHelpers | [static]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CAPTUREDEVICEPROPS Member List

This is the complete list of members for CAPTUREDEVICEPROPS, including all inherited members.
IsLowLatency CAPTUREDEVICEPROPS
Generated on Fri Nov 15 2024 22:23:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Notifications Member List

This is the complete list of members for Scenario2_Notifications, including all inherited members.
ClearBadge_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Notifications
ClearTile_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Notifications
Scenario2_Notifications() | Scenario2_Notifications
SendBadge_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Notifications
SendBadgeWithStringManipulation_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Notifications
SendTile_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Notifications
SendTileWithStringManipulation_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Notifications
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAccountManagement/cpp/Scenario4_ManyProviders.xaml.cpp Source File

  • WebAccountManagement
  • cpp

Scenario4_ManyProviders.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario4_ManyProviders.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Platform::Collections;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::Security::Authentication::Web::Core;
00013 using namespace Windows::Security::Credentials;
00014 using namespace Windows::Storage;
00015 using namespace Windows::UI::Popups;
00016 using namespace Windows::UI::Xaml;
00017 using namespace Windows::UI::Xaml::Controls;
00018 using namespace Windows::UI::Xaml::Controls::Primitives;
00019 using namespace Windows::UI::Xaml::Data;
00020 using namespace Windows::UI::Xaml::Input;
00021 using namespace Windows::UI::Xaml::Media;
00022 using namespace Windows::UI::Xaml::Navigation;
00023 using namespace Windows::UI::ApplicationSettings;
00024
00025 Scenario4_ManyProviders::Scenario4_ManyProviders() : rootPage(MainPage::Current)
00026 {
00027     InitializeComponent();
00028     InitalizeAccountsControlDialog();
00029 }
00030
00031 void Scenario4_ManyProviders::OnNavigatedFrom(NavigationEventArgs^ e)
00032 {
00033     CleanupAccountsControlDialog();
00034     LogoffAndRemoveAccount();
00035 }
00036
00037 void SDKTemplate::Scenario4_ManyProviders::Button_SignIn_Click(Object^ sender, RoutedEventArgs^ e)
00038 {
00039     // Inside OnAccountCommandsRequested we will determine that we need to show accounts
00040     // and providers eligible for sign in because there is no signed in account
00041     AccountsSettingsPane::Show();
00042 }
00043
00044 void SDKTemplate::Scenario4_ManyProviders::Button_GetTokenSilently_Click(Object^ sender, RoutedEventArgs^ e)
00045 {
00046     AuthenticateWithRequestTokenSilent(m_account->WebAccountProvider, MSA_SCOPE_REQUESTED, MSA_CLIENT_ID, m_account);
00047 }
00048
00049 void SDKTemplate::Scenario4_ManyProviders::Button_ManageAccounts_Click(Object^ sender, RoutedEventArgs^ e)
00050 {
00051     // Inside OnAccountCommandsRequested we will determine that we need to show the
00052     // active account since are signed into an account right now
00053     AccountsSettingsPane::Show();
00054 }
00055
00056 void SDKTemplate::Scenario4_ManyProviders::Button_Reset_Click(Object^ sender, RoutedEventArgs^ e)
00057 {
00058     rootPage->NotifyUser("Resetting", NotifyType::StatusMessage);
00059
00060     LogoffAndRemoveAccount();
00061
00062     rootPage->NotifyUser("Done Resetting", NotifyType::StatusMessage);
00063 }
00064
00065 void SDKTemplate::Scenario4_ManyProviders::InitalizeAccountsControlDialog()
00066 {
00067     // Add to the event AccountCommandsRequested to load our list of providers into the AccountSettingsPane
00068     m_accountCommandsRequestedRegistrationToken = AccountsSettingsPane::GetForCurrentView()->AccountCommandsRequested::add(
00069         ref new TypedEventHandler<AccountsSettingsPane^, AccountsSettingsPaneCommandsRequestedEventArgs^>(
00070             this,
00071             &SDKTemplate::Scenario4_ManyProviders::OnAccountCommandsRequested)
00072         );
00073
00074     // Populate our Map of providers (MSA, AAD, and 3rd Party)
00075     // and load our account if we have one saved.
00076     GetProvidersAndAccounts();
00077 }
00078
00079 void SDKTemplate::Scenario4_ManyProviders::CleanupAccountsControlDialog()
00080 {
00081     // Remove the event handler from the AccountCommandsRequested
00082     AccountsSettingsPane::GetForCurrentView()->AccountCommandsRequested::remove(m_accountCommandsRequestedRegistrationToken);
00083 }
00084
00085 void SDKTemplate::Scenario4_ManyProviders::OnAccountCommandsRequested(
00086     AccountsSettingsPane^ sender,
00087     AccountsSettingsPaneCommandsRequestedEventArgs^ e)
00088 {
00089     // This scenario only supports a single account at one time.
00090     // If there already is an account, we do not include a provider in the list
00091     // This will prevent the add account button from showing up.
00092     if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
00093     {
00094         AddWebAccount(e);
00095     }
00096     else
00097     {
00098         AddWebAccountProviders(e);
00099     }
00100
00101     AddLinksAndDescription(e);
00102 }
00103
00104 // Function to create our Map of providers and load an account if an account id is saved
00105 void SDKTemplate::Scenario4_ManyProviders::GetProvidersAndAccounts()
00106 {
00107     //Instantiate the provider list
00108     m_providers = ref new Map<String^, WebAccountProvider^>();
00109
00110     // Make tasks to get the MSA and AAD providers by their IDs
00111     auto appSpecificProvider = ref new WebAccountProvider(APP_SPECIFIC_PROVIDER_ID, APP_SPECIFIC_PROVIDER_NAME, ref new Uri(this->BaseUri->ToString(), "Assets/smallTile-sdk.png"));
00112
00113     // When that task completes, save the respective providers found to the provider list
00114     concurrency::create_task(WebAuthenticationCoreManager::FindAccountProviderAsync(MICROSOFT_PROVIDER_ID, CONSUMER_AUTHORITY)).
00115         then([this](WebAccountProvider^ foundMsaProvider)
00116         {
00117             if (foundMsaProvider)
00118             {
00119                 m_providers->Insert(foundMsaProvider->Id + foundMsaProvider->Authority, foundMsaProvider);
00120             }
00121         });
00122
00123     concurrency::create_task(WebAuthenticationCoreManager::FindAccountProviderAsync(MICROSOFT_PROVIDER_ID, ORGANIZATION_AUTHORITY)).
00124         then([this](WebAccountProvider^ foundAadProvider)
00125         {
00126             if (foundAadProvider)
00127             {
00128                 m_providers->Insert(foundAadProvider->Id + foundAadProvider->Authority, foundAadProvider);
00129             }
00130         });
00131
00132     m_providers->Insert(appSpecificProvider->Id, appSpecificProvider);
00133
00134     if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
00135     {
00136         LoadAccount();
00137     }
00138 }
00139
00140 // We've found that we have some key information saved about a previous
00141 // account, so we will call FindAccountAsync to grab the WebAccount and save it
00142 void SDKTemplate::Scenario4_ManyProviders::LoadAccount()
00143 {
00144     auto accountID = safe_cast<String^>(ApplicationData::Current->LocalSettings->Values->Lookup(STORED_ACCOUNT_ID_KEY));
00145     auto providerID = safe_cast<String^>(ApplicationData::Current->LocalSettings->Values->Lookup(STORED_PROVIDER_ID_KEY));
00146     auto authority = safe_cast<String^>(ApplicationData::Current->LocalSettings->Values->Lookup(STORED_AUTHORITY_ID_KEY));
00147
00148     if (accountID == nullptr || providerID == nullptr || authority == nullptr)
00149     {
00150         return;
00151     }
00152
00153     if (providerID == APP_SPECIFIC_PROVIDER_ID)
00154     {
00155         WebAccountProvider^ appSpecificProvider = ref new WebAccountProvider(APP_SPECIFIC_PROVIDER_ID, APP_SPECIFIC_PROVIDER_NAME, ref new Uri(this->BaseUri->ToString(), "Assets/smallTile-sdk.png"));
00156         WebAccount^ account = ref new WebAccount(appSpecificProvider, accountID, WebAccountState::None);
00157         SaveAccount(account->WebAccountProvider, account);
00158     }
00159     else
00160     {
00161         concurrency::create_task(WebAuthenticationCoreManager::FindAccountProviderAsync(providerID))
00162             .then([this, providerID, accountID, authority](WebAccountProvider^ provider)
00163             {
00164                 concurrency::create_task(WebAuthenticationCoreManager::FindAccountAsync(provider, accountID))
00165                     .then([this](WebAccount^ foundAccount)
00166                     {
00167                         SaveAccount(foundAccount->WebAccountProvider, foundAccount);
00168                     });
00169             });
00170     }
00171 }
00172
00173 // Similar to Scenario 1, but with a loop for the different providers we now support and declared earlier
00174 void SDKTemplate::Scenario4_ManyProviders::AddWebAccountProviders(AccountsSettingsPaneCommandsRequestedEventArgs^ e)
00175 {
00176     e->WebAccountProviderCommands->Clear();
00177
00178     for (const auto& pair : m_providers)
00179     {
00180         // Create a new WebAccountProviderCommandInvokedHandler for the event fired when a user clicks on a provider in the AccountSettingsPane
00181         WebAccountProviderCommandInvokedHandler^ handler = ref new WebAccountProviderCommandInvokedHandler(this, &SDKTemplate::Scenario4_ManyProviders::WebAccountProviderCommandInvoked);
00182
00183         // Make a new command based on the provider and the click handler we just created
00184         WebAccountProviderCommand^ providerCommand = ref new WebAccountProviderCommand(pair->Value, handler);
00185
00186         // Append that command to the WebAccountProviderCommands list for the AccountSettingsPane
00187         e->WebAccountProviderCommands->Append(providerCommand);
00188     }
00189 }
00190
00191 //Creates a web account command object for our account, if we have one saved, and adds it to the AccountsControl list of web account commands
00192 void SDKTemplate::Scenario4_ManyProviders::AddWebAccount(AccountsSettingsPaneCommandsRequestedEventArgs^ e)
00193 {
00194     // Create a new WebAccountCommandInvokedHandler for the event fired when a user clicks on an account in the AccountSettingsPane
00195     WebAccountCommandInvokedHandler^ handler = ref new WebAccountCommandInvokedHandler(this, &SDKTemplate::Scenario4_ManyProviders::WebAccountCommandInvoked);
00196
00197     // Make a new command based on the account and the click handler we just created
00198     WebAccountCommand^ accountCommand = ref new WebAccountCommand(SDKTemplate::Scenario4_ManyProviders::m_account, handler, SupportedWebAccountActions::Remove);
00199
00200     // Append that command to the WebAccountProviderCommands list for the AccountSettingsPane
00201     e->WebAccountCommands->Append(accountCommand);
00202 }
00203
00204 // You can add links and descriptive text such as privacy policy, help, general account settings
00205 void SDKTemplate::Scenario4_ManyProviders::AddLinksAndDescription(AccountsSettingsPaneCommandsRequestedEventArgs^ e)
00206 {
00207     e->HeaderText = "Describe what adding an account to your application will do for the user.";
00208
00209     e->Commands->Append(ref new SettingsCommand("privacypolicy", "Privacy Policy", ref new UICommandInvokedHandler(this, &SDKTemplate::Scenario4_ManyProviders::PrivacyPolicyInvoked)));
00210     e->Commands->Append(ref new SettingsCommand("otherlink", "Other Link", ref new UICommandInvokedHandler(this, &SDKTemplate::Scenario4_ManyProviders::OtherLinkInvoked)));
00211 }
00212
00213 void SDKTemplate::Scenario4_ManyProviders::WebAccountProviderCommandInvoked(WebAccountProviderCommand^ command)
00214 {
00215     // The function that will be called with the WebAccountProviderCommand passed from AccountSettingsPane
00216     if (command->WebAccountProvider->Authority == "organizations")
00217     {
00218         AuthenticateWithRequestToken(command->WebAccountProvider, AAD_SCOPE_REQUESTED, AAD_CLIENT_ID);
00219     }
00220     else
00221     {
00222         AuthenticateWithRequestToken(command->WebAccountProvider, MSA_SCOPE_REQUESTED, MSA_CLIENT_ID);
00223     }
00224 }
00225
00226 // The function that will be called from AccountSettingsPane with the WebAccount
00227 // that was selected by the user.
00228 void SDKTemplate::Scenario4_ManyProviders::WebAccountCommandInvoked(WebAccountCommand^ command, WebAccountInvokedArgs^ args)
00229 {
00230     if (args->Action == WebAccountAction::Remove)
00231     {
00232         LogoffAndRemoveAccount();
00233     }
00234 }
00235
00236 // Displays privacy policy message on clicking it in the AccountsControl
00237 void SDKTemplate::Scenario4_ManyProviders::PrivacyPolicyInvoked(IUICommand^ command)
00238 {
00239     rootPage->NotifyUser("Privacy policy clicked by user", NotifyType::StatusMessage);
00240 }
00241
00242 // Displays other link message on clicking it in the AccountsControl
00243 void SDKTemplate::Scenario4_ManyProviders::OtherLinkInvoked(IUICommand^ command)
00244 {
00245     rootPage->NotifyUser("Other link pressed by user", NotifyType::StatusMessage);
00246 }
00247
00248 // Create a new WebAccountManager WebTokenRequest based on the Provider, Scope, ClientID and then create a task to send
00249 // that request asynchronously to WebAccountManager's RequestTokenAsync
00250 //
00251 // WebAccountManager will then try three steps, in order:
00252 //        (1): Check it's local cache to see if it has a valid token
00253 //        (2): Try to silently request a new token from the MSA service
00254 //        (3): Show the MSA UI for user interaction required (user credentials) before it may return a token.
00255 //
00256 // Because of WebAccountManager's ability to cache tokens, you should only need to call WebAccountManager when making token
00257 // based requests and not require the ability to store a cached token within your app.
00258 void SDKTemplate::Scenario4_ManyProviders::AuthenticateWithRequestToken(WebAccountProvider^ provider, String^ scope, String^ clientID)
00259 {
00260     rootPage->NotifyUser("Requested " + provider->DisplayName + " from AccountsManager dialog.", NotifyType::StatusMessage);
00261
00262     auto wtr = ref new WebTokenRequest(provider, scope, clientID);
00263     wtr->Properties->Insert("authority", "https://login.windows.net/common");
00264     wtr->Properties->Insert("resource", "https://sharepoint.com");
00265
00266     // When our task finishes it will return result of the operation, and if successful it will contain a token
00267     // and WebAccount. We save the WebAccount as the "active" account.
00268     concurrency::create_task(WebAuthenticationCoreManager::RequestTokenAsync(wtr))
00269         .then([this, provider](WebTokenRequestResult^ webTokenRequestResult)
00270     {
00271         if (webTokenRequestResult->ResponseStatus == WebTokenRequestStatus::Success)
00272         {
00273             if (webTokenRequestResult->ResponseData->GetAt(0)->WebAccount)
00274             {
00275                 if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
00276                 {
00277                     ApplicationData::Current->LocalSettings->Values->Remove(STORED_ACCOUNT_ID_KEY);
00278                 }
00279
00280                 WebAccount^ account = webTokenRequestResult->ResponseData->GetAt(0)->WebAccount;
00281                 SaveAccount(provider, account);
00282             }
00283         }
00284
00285         OutputTokenResult(webTokenRequestResult);
00286     });
00287 }
00288
00289 // Create a new WebAccountManager WebTokenRequest based on the Provider, Scope, ClientID and then create a task to send
00290 // that request and the account to get the token for asynchronously to WebAccountManager's GetTokenSilentlyAsync API
00291 //
00292 // WebAccountManager's GetTokenSilentlyAsync will then try :
00293 //        (1): Check it's local cache to see if it has a valid token
00294 //        (2): Try to silently request a new token from the MSA service
00295 //        (3): Return a status of UserInteractionRequired if we need the user credentials
00296 //
00297 // Because of WebAccountManager's ability to cache tokens, you should only need to call WebAccountManager when making token
00298 // based requests and not require the ability to store a cached token within your app.
00299 void SDKTemplate::Scenario4_ManyProviders::AuthenticateWithRequestTokenSilent(WebAccountProvider^ provider, String^ scope, String^ clientID, WebAccount^ account)
00300 {
00301     rootPage->NotifyUser("Requested " + provider->DisplayName + " from AccountsManager dialog.", NotifyType::StatusMessage);
00302
00303     auto wtr = ref new WebTokenRequest(provider, scope, clientID);
00304
00305     // When our task finishes it will return result of the operation, and if successful it will contain a token
00306     // and WebAccount. We save the WebAccount as the "active" account.
00307     concurrency::create_task(WebAuthenticationCoreManager::GetTokenSilentlyAsync(wtr, account)).then([this](WebTokenRequestResult^ webTokenRequestResult)
00308     {
00309         if (webTokenRequestResult->ResponseStatus == WebTokenRequestStatus::Success)
00310         {
00311             // Perform an operation with the token you just got
00312         }
00313
00314         OutputTokenResult(webTokenRequestResult);
00315     });
00316 }
00317
00318 // Displays the result of requesting a token asynchronously to the main page
00319 void SDKTemplate::Scenario4_ManyProviders::OutputTokenResult(WebTokenRequestResult^ result)
00320 {
00321     if (result->ResponseStatus == WebTokenRequestStatus::Success)
00322     {
00323         rootPage->NotifyUser(result->ResponseStatus.ToString() + "!\nUser: " + result->ResponseData->GetAt(0)->WebAccount->Id + "\n    Token returned was: " + result->ResponseData->GetAt(0)->Token, NotifyType::StatusMessage);
00324     }
00325     else if (result->ResponseStatus == WebTokenRequestStatus::ProviderError)
00326     {
00327         // The account provider has passed us an error and we should handle it.
00328         rootPage->NotifyUser(result->ResponseStatus.ToString() + " " + result->ResponseError->ErrorCode + ": " + result->ResponseError->ErrorMessage, NotifyType::ErrorMessage);
00329     }
00330     else if (result->ResponseStatus == WebTokenRequestStatus::AccountProviderNotAvailable)
00331     {
00332         // The account provider is unavailable, this is a temporary error.
00333         rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::ErrorMessage);
00334     }
00335     else if (result->ResponseStatus == WebTokenRequestStatus::UserInteractionRequired)
00336     {
00337         // The account provider needs to display a UI, since we called request token silently we should call it
00338         // with RequestTokenAsync.
00339         rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::StatusMessage);
00340     }
00341     else if (result->ResponseStatus == WebTokenRequestStatus::UserCancel)
00342     {
00343         // The user cancelled the sign in process for the account provider, handle
00344         // that how you need to.
00345         rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::StatusMessage);
00346     }
00347     else
00348     {
00349         // An unexpected error was encountered
00350         rootPage->NotifyUser(result->ResponseStatus.ToString() + " " + result->ResponseError->ErrorCode + ": " + result->ResponseError->ErrorMessage, NotifyType::ErrorMessage);
00351     }
00352 }
00353
00354 // Saves the ProviderId, Authority, and AccountId in LocalSettings as we can handle
00355 // different types of account providers in Scenario 2.
00356 void SDKTemplate::Scenario4_ManyProviders::SaveAccount(WebAccountProvider^ provider, WebAccount^ account)
00357 {
00358     m_account = account;
00359     ApplicationData::Current->LocalSettings->Values->Insert(STORED_PROVIDER_ID_KEY, m_account->WebAccountProvider->Id);
00360     ApplicationData::Current->LocalSettings->Values->Insert(STORED_AUTHORITY_ID_KEY, m_account->WebAccountProvider->Authority);
00361     ApplicationData::Current->LocalSettings->Values->Insert(STORED_ACCOUNT_ID_KEY, m_account->Id);
00362
00363     // Update the UI
00364     button_SignIn->IsEnabled = false;
00365     button_GetTokenSilently->IsEnabled = true;
00366     button_ManageAccounts->IsEnabled = true;
00367     textblock_SignedInStatus->Text = "Signed in with:";
00368     textblock_SignedInStatus->Foreground = ref new SolidColorBrush(Windows::UI::Colors::Green);
00369     listview_SignedInAccounts->Items->Append(account->Id);
00370 }
00371
00372 // When we sign out, then remove all our saved keys as well.
00373 void SDKTemplate::Scenario4_ManyProviders::LogoffAndRemoveAccount()
00374 {
00375     if (m_account)
00376     {
00377         //concurrency::create_task(account->SignOutAsync( MSA_SCOPE_REQUESTED));
00378     }
00379
00380     if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
00381     {
00382         ApplicationData::Current->LocalSettings->Values->Remove(STORED_ACCOUNT_ID_KEY);
00383     }
00384
00385     if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_PROVIDER_ID_KEY))
00386     {
00387         ApplicationData::Current->LocalSettings->Values->Remove(STORED_PROVIDER_ID_KEY);
00388     }
00389
00390     if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_AUTHORITY_ID_KEY))
00391     {
00392         ApplicationData::Current->LocalSettings->Values->Remove(STORED_AUTHORITY_ID_KEY);
00393     }
00394
00395     // Update UI
00396     button_SignIn->IsEnabled = true;
00397     button_GetTokenSilently->IsEnabled = false;
00398     button_ManageAccounts->IsEnabled = false;
00399     textblock_SignedInStatus->Text = "Not signed in.";
00400     textblock_SignedInStatus->Foreground = ref new SolidColorBrush(Windows::UI::Colors::Red);
00401     listview_SignedInAccounts->Items->Clear();
00402 }
Generated on Fri Nov 15 2024 22:21:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FileExtensions Member List

This is the complete list of members for FileExtensions, including all inherited members.
Document | FileExtensions | [static]
Document | FileExtensions | [static]
Image | FileExtensions | [static]
Image | FileExtensions | [static]
Music | FileExtensions | [static]
Music | FileExtensions | [static]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NetworkConnectivity/cs/Scenario2_NetworkCost.xaml.cs Source File

  • NetworkConnectivity
  • cs

Scenario2_NetworkCost.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.Networking.Connectivity;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public sealed partial class Scenario2_NetworkCost : Page
00019     {
00020         public Scenario2_NetworkCost()
00021         {
00022             this.InitializeComponent();
00023         }
00024
00025         private void GetNetworkCost_Click(object sender, RoutedEventArgs e)
00026         {
00027             ResultsText.Text = string.Empty;
00028
00029             ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile();
00030             if (profile != null)
00031             {
00032                 ConnectionCost connectionCost = profile.GetConnectionCost();
00033                 Helpers.AppendLine(ResultsText, $"Network cost is {connectionCost.NetworkCostType}.");
00034
00035                 Helpers.EvaluateAndReportConnectionCost(connectionCost, ResultsText);
00036             }
00037             else
00038             {
00039                 Helpers.AppendLine(ResultsText, "No internet connection profile.");
00040             }
00041         }
00042     }
00043 }
Generated on Fri Nov 15 2024 22:20:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Disposer Member List

This is the complete list of members for Disposer, including all inherited members.
Dispose() | Disposer | [inline]
Dispose(bool disposeManagedResources) | Disposer | [inline, protected, virtual]
DisposeCollector | Disposer | [private]
Disposer() | Disposer | [inline, protected]
IsDisposed | Disposer | [protected]
RemoveAndDispose< T >(ref T objectToDispose) | Disposer | [inline, protected]
RemoveToDispose< T >(T objectToRemove) | Disposer | [inline, protected]
ToDispose< T >(T objectToDispose) | Disposer | [inline, protected]
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4 Member List

This is the complete list of members for Scenario4, including all inherited members.
Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario4 | [inline, private]
Scenario4() | Scenario4 | [inline]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario8_ClipboardSource Member List

This is the complete list of members for Scenario8_ClipboardSource, including all inherited members.
OnNavigatedTo(NavigationEventArgs e) | Scenario8_ClipboardSource | [inline, protected]
rootPage | Scenario8_ClipboardSource | [private]
Scenario8_ClipboardSource() | Scenario8_ClipboardSource | [inline]
Set_ClipboardSource(object sender, RoutedEventArgs e) | Scenario8_ClipboardSource | [inline, private]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario13_RetryFilter Member List

This is the complete list of members for Scenario13_RetryFilter, including all inherited members.
Cancel_Click(object sender, RoutedEventArgs e) | Scenario13_RetryFilter | [inline, private]
cts | Scenario13_RetryFilter | [private]
httpClient | Scenario13_RetryFilter | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario13_RetryFilter | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario13_RetryFilter | [inline, protected]
RetryAfterSwitch_Toggled(object sender, RoutedEventArgs e) | Scenario13_RetryFilter | [inline, private]
rootPage | Scenario13_RetryFilter | [private]
Scenario13_RetryFilter() | Scenario13_RetryFilter | [inline]
Start_Click(object sender, RoutedEventArgs e) | Scenario13_RetryFilter | [inline, private]
UpdateAddressField() | Scenario13_RetryFilter | [inline, private]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Scenario9_CustomPairDevice.cpp Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

Scenario9_CustomPairDevice.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario9_CustomPairDevice.h"
00014 #include "DeviceHelpers.h"
00015 #include "SampleConfiguration.h"
00016 #include "Scenario9_CustomPairDevice.g.cpp"
00017
00018 using namespace winrt;
00019 using namespace winrt::Windows::Devices::Enumeration;
00020 using namespace winrt::Windows::Foundation;
00021 using namespace winrt::Windows::Security::Credentials;
00022 using namespace winrt::Windows::UI::Xaml;
00023 using namespace winrt::Windows::UI::Xaml::Controls;
00024 using namespace winrt::Windows::UI::Xaml::Navigation;
00025
00026 namespace winrt::SDKTemplate::implementation
00027 {
00028     Scenario9_CustomPairDevice::Scenario9_CustomPairDevice()
00029     {
00030         InitializeComponent();
00031         deviceWatcherHelper->DeviceChanged({ get_weak(), &Scenario9_CustomPairDevice::OnDeviceListChanged });
00032     }
00033
00034     void Scenario9_CustomPairDevice::OnNavigatedTo(NavigationEventArgs const&)
00035     {
00036         resultsListView().ItemsSource(resultCollection);
00037
00038         selectorComboBox().ItemsSource(DeviceSelectorChoices::PairingSelectors());
00039         selectorComboBox().SelectedIndex(0);
00040
00041         protectionLevelComboBox().ItemsSource(ProtectionSelectorChoices::Selectors());
00042         protectionLevelComboBox().SelectedIndex(0);
00043     }
00044
00045     void Scenario9_CustomPairDevice::OnNavigatedFrom(NavigationEventArgs const&)
00046     {
00047         deviceWatcherHelper->Reset();
00048         CompleteProvidePinTask(); // Abandon any previous pin request.
00049         CompletePasswordCredential(); // Abandon any previous pin request.
00050         CompleteConfirmPinTask(false); // Abandon any previous request.
00051     }
00052
00053     void Scenario9_CustomPairDevice::StartWatcherButton_Click(IInspectable const&, RoutedEventArgs const&)
00054     {
00055         StartWatcher();
00056     }
00057
00058     void Scenario9_CustomPairDevice::StopWatcherButton_Click(IInspectable const&, RoutedEventArgs const&)
00059     {
00060         StopWatcher();
00061     }
00062
00063     void Scenario9_CustomPairDevice::StartWatcher()
00064     {
00065         startWatcherButton().IsEnabled(false);
00066         resultCollection.Clear();
00067
00068         // Get the device selector chosen by the UI then add additional constraints for devices that
00069         // can be paired or are already paired.
00070         DeviceSelectorInfo* deviceSelectorInfo = FromInspectable<DeviceSelectorInfo>(selectorComboBox().SelectedItem());
00071         hstring selector = L"(" + deviceSelectorInfo->Selector() + L") AND (System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True)";
00072
00073         DeviceWatcher deviceWatcher{ nullptr };
00074         if (deviceSelectorInfo->Kind() == DeviceInformationKind::Unknown)
00075         {
00076             // Kind will be determined by the selector
00077             deviceWatcher = DeviceInformation::CreateWatcher(
00078                 selector,
00079                 nullptr // don't request additional properties for this sample
00080             );
00081         }
00082         else
00083         {
00084             // Kind is specified in the selector info
00085             deviceWatcher = DeviceInformation::CreateWatcher(
00086                 selector,
00087                 nullptr, // don't request additional properties for this sample
00088                 deviceSelectorInfo->Kind());
00089         }
00090
00091         rootPage.NotifyUser(L"Starting Watcher...", NotifyType::StatusMessage);
00092         deviceWatcherHelper->StartWatcher(deviceWatcher);
00093         stopWatcherButton().IsEnabled(true);
00094     }
00095
00096     void Scenario9_CustomPairDevice::StopWatcher()
00097     {
00098         stopWatcherButton().IsEnabled(false);
00099
00100         deviceWatcherHelper->StopWatcher();
00101
00102         startWatcherButton().IsEnabled(true);
00103     }
00104
00105     void Scenario9_CustomPairDevice::OnDeviceListChanged(DeviceWatcher const&, hstring const& id)
00106     {
00107         // If the item being updated is currently "selected", then update the pairing buttons
00108         auto item = resultsListView().SelectedItem();
00109         DeviceInformationDisplay* deviceInformationDisplay = FromInspectable<DeviceInformationDisplay>(item);
00110         if ((deviceInformationDisplay != nullptr) && (deviceInformationDisplay->Id() == id))
00111         {
00112             UpdatePairingButtons();
00113         }
00114     }
00115
00116     fire_and_forget Scenario9_CustomPairDevice::PairButton_Click(IInspectable const&, RoutedEventArgs const&)
00117     {
00118         auto lifetime = get_strong();
00119
00120         PasswordCredential credential = co_await GetPasswordCredentialFromUserAsync();
00121         if (credential)
00122         {
00123             rootPage.NotifyUser(L"Entered", NotifyType::StatusMessage);
00124         }
00125
00126         // Gray out the pair button and results view while pairing is in progress.
00127         resultsListView().IsEnabled(false);
00128         pairButton().IsEnabled(false);
00129         rootPage.NotifyUser(L"Pairing started. Please wait...", NotifyType::StatusMessage);
00130
00131         // Get the device selected for pairing
00132         IInspectable item = resultsListView().SelectedItem();
00133         DeviceInformationDisplay* deviceInfoDisp = FromInspectable<DeviceInformationDisplay>(item);
00134
00135         // Get ceremony type and protection level selections
00136         DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies();
00137         IInspectable protectionItem = protectionLevelComboBox().SelectedItem();
00138         ProtectionLevelSelectorInfo* protectionLevelInfo = FromInspectable<ProtectionLevelSelectorInfo>(protectionItem);
00139         DevicePairingProtectionLevel protectionLevel = protectionLevelInfo->ProtectionLevel();
00140
00141         DeviceInformationCustomPairing customPairing = deviceInfoDisp->DeviceInformation().Pairing().Custom();
00142
00143         event_token token = customPairing.PairingRequested({ get_weak(), &Scenario9_CustomPairDevice::PairingRequestedHandler });
00144         DevicePairingResult result = co_await customPairing.PairAsync(ceremoniesSelected, protectionLevel);
00145         customPairing.PairingRequested(token);
00146
00147         rootPage.NotifyUser(
00148             L"Pairing result = " + to_hstring(result.Status()),
00149             result.Status() == DevicePairingResultStatus::Paired ? NotifyType::StatusMessage : NotifyType::ErrorMessage);
00150
00151         HidePairingPanel();
00152         UpdatePairingButtons();
00153         resultsListView().IsEnabled(true);
00154     }
00155
00156     fire_and_forget Scenario9_CustomPairDevice::UnpairButton_Click(IInspectable const&, RoutedEventArgs const&)
00157     {
00158         auto lifetime = get_strong();
00159
00160         // Gray out the pair button and results view while unpairing is in progress.
00161         resultsListView().IsEnabled(false);
00162         unpairButton().IsEnabled(false);
00163         rootPage.NotifyUser(L"Unpairing started. Please wait...", NotifyType::StatusMessage);
00164
00165         IInspectable item = resultsListView().SelectedItem();
00166         DeviceInformationDisplay* deviceInfoDisp = FromInspectable<DeviceInformationDisplay>(item);
00167
00168         DeviceUnpairingResult result = co_await deviceInfoDisp->DeviceInformation().Pairing().UnpairAsync();
00169
00170         rootPage.NotifyUser(
00171             L"Unpairing result = " + to_hstring(result.Status()),
00172             result.Status() == DeviceUnpairingResultStatus::Unpaired ? NotifyType::StatusMessage : NotifyType::ErrorMessage);
00173
00174         UpdatePairingButtons();
00175         resultsListView().IsEnabled(true);
00176     }
00177
00178     void Scenario9_CustomPairDevice::ResultsListView_SelectionChanged(IInspectable const&, SelectionChangedEventArgs const&)
00179     {
00180         UpdatePairingButtons();
00181     }
00182
00183     fire_and_forget Scenario9_CustomPairDevice::PairingRequestedHandler(DeviceInformationCustomPairing const&, DevicePairingRequestedEventArgs args)
00184     {
00185         auto lifetime = get_strong();
00186
00187         switch (args.PairingKind())
00188         {
00189         case DevicePairingKinds::ConfirmOnly:
00190             // Windows itself will pop the confirmation dialog as part of "consent" if this is running on Desktop or Mobile
00191             // If this is an App for 'Windows IoT Core' where there is no Windows Consent UX, you may want to provide your own confirmation.
00192             args.Accept();
00193             break;
00194
00195         case DevicePairingKinds::DisplayPin:
00196             // We just show the PIN on this side. The ceremony is actually completed when the user enters the PIN
00197             // on the target device. We automatically accept here since we can't really "cancel" the operation
00198             // from this side.
00199             args.Accept();
00200
00201             // No need for a deferral since we don't need any decision from the user
00202             co_await resume_foreground(Dispatcher());
00203
00204             ShowPairingPanel(
00205                 L"Please enter this PIN on the device you are pairing with: " + args.Pin(),
00206                 args.PairingKind());
00207
00208             break;
00209
00210         case DevicePairingKinds::ProvidePin:
00211         {
00212             // A PIN may be shown on the target device and the user needs to enter the matching PIN on
00213             // this Windows device. Get a deferral so we can perform the async request to the user.
00214             auto collectPinDeferral = args.GetDeferral();
00215
00216             co_await resume_foreground(Dispatcher());
00217
00218             hstring pin = co_await GetPinFromUserAsync();
00219             if (!pin.empty())
00220             {
00221                 args.Accept(pin);
00222             }
00223
00224             collectPinDeferral.Complete();
00225             break;
00226         }
00227
00228         case DevicePairingKinds::ProvidePasswordCredential:
00229         {
00230             auto collectCredentialDeferral = args.GetDeferral();
00231             co_await resume_foreground(Dispatcher());
00232
00233             PasswordCredential credential = co_await GetPasswordCredentialFromUserAsync();
00234             if (credential != nullptr)
00235             {
00236                 args.AcceptWithPasswordCredential(credential);
00237             }
00238             collectCredentialDeferral.Complete();
00239             break;
00240         }
00241
00242         case DevicePairingKinds::ConfirmPinMatch:
00243         {
00244             // We show the PIN here and the user responds with whether the PIN matches what they see
00245             // on the target device. Response comes back and we set it on the PinComparePairingRequestedData
00246             // then complete the deferral.
00247             auto displayMessageDeferral = args.GetDeferral();
00248
00249             co_await resume_foreground(Dispatcher());
00250             bool accept = co_await GetUserConfirmationAsync(args.Pin());
00251             if (accept)
00252             {
00253                 args.Accept();
00254             }
00255
00256             displayMessageDeferral.Complete();
00257             break;
00258         }
00259         }
00260     }
00261
00262     void Scenario9_CustomPairDevice::ShowPairingPanel(hstring const& text, DevicePairingKinds pairingKind)
00263     {
00264         pairingPanel().Visibility(Visibility::Collapsed);
00265         pinEntryTextBox().Visibility(Visibility::Collapsed);
00266         okButton().Visibility(Visibility::Collapsed);
00267         usernameEntryTextBox().Visibility(Visibility::Collapsed);
00268         passwordEntryTextBox().Visibility(Visibility::Collapsed);
00269         verifyButton().Visibility(Visibility::Collapsed);
00270         yesButton().Visibility(Visibility::Collapsed);
00271         noButton().Visibility(Visibility::Collapsed);
00272         pairingTextBlock().Text(text);
00273
00274         switch (pairingKind)
00275         {
00276         case DevicePairingKinds::ConfirmOnly:
00277         case DevicePairingKinds::DisplayPin:
00278             // Don't need any buttons
00279             break;
00280         case DevicePairingKinds::ProvidePin:
00281             pinEntryTextBox().Text({});
00282             pinEntryTextBox().Visibility(Visibility::Visible);
00283             okButton().Visibility(Visibility::Visible);
00284             break;
00285         case DevicePairingKinds::ConfirmPinMatch:
00286             yesButton().Visibility(Visibility::Visible);
00287             noButton().Visibility(Visibility::Visible);
00288             break;
00289         case DevicePairingKinds::ProvidePasswordCredential:
00290             usernameEntryTextBox().Text({});
00291             passwordEntryTextBox().Text({});
00292             passwordEntryTextBox().Visibility(Visibility::Visible);
00293             usernameEntryTextBox().Visibility(Visibility::Visible);
00294             verifyButton().Visibility(Visibility::Visible);
00295             break;
00296         }
00297
00298         pairingPanel().Visibility(Visibility::Visible);
00299     }
00300
00301     void Scenario9_CustomPairDevice::HidePairingPanel()
00302     {
00303         pairingPanel().Visibility(Visibility::Collapsed);
00304         pairingTextBlock().Text({});
00305     }
00306
00307     IAsyncOperation<hstring> Scenario9_CustomPairDevice::GetPinFromUserAsync()
00308     {
00309         HidePairingPanel();
00310         CompleteProvidePinTask(); // Abandon any previous pin request.
00311
00312         ShowPairingPanel(
00313             L"Please enter the PIN shown on the device you're pairing with",
00314             DevicePairingKinds::ProvidePin);
00315
00316         providePinTaskSrc = SimpleTaskCompletionSource<hstring>();
00317
00318         return co_await providePinTaskSrc.Task();
00319     }
00320
00321     // If pin is not provided, then any pending pairing request is abandoned.
00322     void Scenario9_CustomPairDevice::CompleteProvidePinTask(hstring pin)
00323     {
00324         providePinTaskSrc.SetResult(pin);
00325     }
00326
00327     IAsyncOperation<PasswordCredential> Scenario9_CustomPairDevice::GetPasswordCredentialFromUserAsync()
00328     {
00329         HidePairingPanel();
00330         CompletePasswordCredential(); // Abandon any previous pin request.
00331
00332         ShowPairingPanel(
00333             L"Please enter the username and password",
00334             DevicePairingKinds::ProvidePasswordCredential);
00335
00336         providePasswordCredentialTaskSrc = SimpleTaskCompletionSource<PasswordCredential>();
00337
00338         return co_await providePasswordCredentialTaskSrc.Task();
00339     }
00340
00341     void Scenario9_CustomPairDevice::CompletePasswordCredential(hstring username, hstring password)
00342     {
00343         if (username.empty())// || password.empty())
00344         {
00345             providePasswordCredentialTaskSrc.SetResult(nullptr);
00346         }
00347         else
00348         {
00349             PasswordCredential passwordCredential;
00350             passwordCredential.UserName(username);
00351             passwordCredential.Password(password);
00352             providePasswordCredentialTaskSrc.SetResult(passwordCredential);
00353         }
00354     }
00355
00356     IAsyncOperation<bool> Scenario9_CustomPairDevice::GetUserConfirmationAsync(hstring const& pin)
00357     {
00358         HidePairingPanel();
00359         CompleteConfirmPinTask(false); // Abandon any previous request.
00360
00361         ShowPairingPanel(
00362             L"Does the following PIN match the one shown on the device you are pairing?: " + pin,
00363             DevicePairingKinds::ConfirmPinMatch);
00364
00365         confirmPinTaskSrc = SimpleTaskCompletionSource<bool>();
00366
00367         return co_await confirmPinTaskSrc.Task();
00368     }
00369
00370     // If pin is not provided, then any pending pairing request is abandoned.
00371     void Scenario9_CustomPairDevice::CompleteConfirmPinTask(bool accept)
00372     {
00373         confirmPinTaskSrc.SetResult(accept);
00374     }
00375
00376
00377     void Scenario9_CustomPairDevice::okButton_Click(IInspectable const&, RoutedEventArgs const&)
00378     {
00379         // OK button is only used for the ProvidePin scenario
00380         CompleteProvidePinTask(pinEntryTextBox().Text());
00381         HidePairingPanel();
00382     }
00383
00384     void Scenario9_CustomPairDevice::verifyButton_Click(IInspectable const&, RoutedEventArgs const&)
00385     {
00386         // verify button is only used for the ProvidePin scenario
00387         CompletePasswordCredential(usernameEntryTextBox().Text(), passwordEntryTextBox().Text());
00388         HidePairingPanel();
00389     }
00390
00391     void Scenario9_CustomPairDevice::yesButton_Click(IInspectable const&, RoutedEventArgs const&)
00392     {
00393         CompleteConfirmPinTask(true);
00394         HidePairingPanel();
00395     }
00396
00397     void Scenario9_CustomPairDevice::noButton_Click(IInspectable const&, RoutedEventArgs const&)
00398     {
00399         CompleteConfirmPinTask(false);
00400         HidePairingPanel();
00401     }
00402
00403     DevicePairingKinds Scenario9_CustomPairDevice::GetSelectedCeremonies()
00404     {
00405         DevicePairingKinds ceremonySelection = DevicePairingKinds::None;
00406         if (confirmOnlyOption().IsChecked().Value()) ceremonySelection |= DevicePairingKinds::ConfirmOnly;
00407         if (displayPinOption().IsChecked().Value()) ceremonySelection |= DevicePairingKinds::DisplayPin;
00408         if (providePinOption().IsChecked().Value()) ceremonySelection |= DevicePairingKinds::ProvidePin;
00409         if (confirmPinMatchOption().IsChecked().Value()) ceremonySelection |= DevicePairingKinds::ConfirmPinMatch;
00410         if (passwordCredentialOption().IsChecked().Value()) ceremonySelection |= DevicePairingKinds::ProvidePasswordCredential;
00411         return ceremonySelection;
00412     }
00413
00414     void Scenario9_CustomPairDevice::UpdatePairingButtons()
00415     {
00416         auto item = resultsListView().SelectedItem();
00417         DeviceInformationDisplay* deviceInfoDisp = FromInspectable<DeviceInformationDisplay>(item);
00418         if (deviceInfoDisp != nullptr &&
00419             deviceInfoDisp->DeviceInformation().Pairing().CanPair() &&
00420             !deviceInfoDisp->DeviceInformation().Pairing().IsPaired())
00421         {
00422             pairButton().IsEnabled(true);
00423         }
00424         else
00425         {
00426             pairButton().IsEnabled(false);
00427         }
00428
00429         if (deviceInfoDisp != nullptr &&
00430             deviceInfoDisp->DeviceInformation().Pairing().IsPaired())
00431         {
00432             unpairButton().IsEnabled(true);
00433         }
00434         else
00435         {
00436             unpairButton().IsEnabled(false);
00437         }
00438     }
00439 }
00440
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cs/Scenario_ContinuousRecognitionListGrammar.xaml.cs Source File

  • SpeechRecognitionAndSynthesis
  • cs

Scenario_ContinuousRecognitionListGrammar.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Threading.Tasks;
00016 using Windows.ApplicationModel.Resources.Core;
00017 using Windows.Globalization;
00018 using Windows.Media.SpeechRecognition;
00019 using Windows.UI.Core;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Navigation;
00023
00024 namespace SDKTemplate
00025 {
00026     public sealed partial class Scenario_ContinuousRecognitionListGrammar : Page
00027     {
00028         // Reference to the main sample page in order to post status messages.
00029         private MainPage rootPage;
00030
00031         // The speech recognizer used throughout this sample.
00032         private SpeechRecognizer speechRecognizer;
00033
00034         /// <summary>
00035         /// the HResult 0x8004503a typically represents the case where a recognizer for a particular language cannot
00036         /// be found. This may occur if the language is installed, but the speech pack for that language is not.
00037         /// See Settings -> Time & Language -> Region & Language -> *Language* -> Options -> Speech Language Options.
00038         /// </summary>
00039         private static uint HResultRecognizerNotFound = 0x8004503a;
00040
00041         private ResourceContext speechContext;
00042         private ResourceMap speechResourceMap;
00043
00044         private bool isPopulatingLanguages = false;
00045
00046         // Keep track of whether the continuous recognizer is currently running, so it can be cleaned up appropriately.
00047         private bool isListening;
00048
00049         public Scenario_ContinuousRecognitionListGrammar()
00050         {
00051             this.InitializeComponent();
00052             isListening = false;
00053         }
00054
00055         /// <summary>
00056         /// Upon entering the scenario, ensure that we have permissions to use the Microphone. This may entail popping up
00057         /// a dialog to the user on Desktop systems. Only enable functionality once we've gained that permission in order to
00058         /// prevent errors from occurring when using the SpeechRecognizer. If speech is not a primary input mechanism, developers
00059         /// should consider disabling appropriate parts of the UI if the user does not have a recording device, or does not allow
00060         /// audio input.
00061         /// </summary>
00062         /// <param name="e">Unused navigation parameters</param>
00063         protected async override void OnNavigatedTo(NavigationEventArgs e)
00064         {
00065             rootPage = MainPage.Current;
00066
00067             // Prompt the user for permission to access the microphone. This request will only happen
00068             // once, it will not re-prompt if the user rejects the permission.
00069             bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
00070             if (permissionGained)
00071             {
00072                 btnContinuousRecognize.IsEnabled = true;
00073
00074                 // Initialize resource map to retrieve localized speech strings.
00075                 Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
00076                 string langTag = speechLanguage.LanguageTag;
00077                 speechContext = ResourceContext.GetForCurrentView();
00078                 speechContext.Languages = new string[] { langTag };
00079
00080                 speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");
00081
00082                 PopulateLanguageDropdown();
00083                 await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
00084             }
00085             else
00086             {
00087                 this.resultTextBlock.Visibility = Visibility.Visible;
00088                 this.resultTextBlock.Text = "Permission to access capture resources was not given by the user, reset the application setting in Settings->Privacy->Microphone.";
00089                 btnContinuousRecognize.IsEnabled = false;
00090                 cbLanguageSelection.IsEnabled = false;
00091             }
00092         }
00093
00094         /// <summary>
00095         /// Look up the supported languages for this speech recognition scenario,
00096         /// that are installed on this machine, and populate a dropdown with a list.
00097         /// </summary>
00098         private void PopulateLanguageDropdown()
00099         {
00100             // disable the callback so we don't accidentally trigger initialization of the recognizer
00101             // while initialization is already in progress.
00102             isPopulatingLanguages = true;
00103
00104             Language defaultLanguage = SpeechRecognizer.SystemSpeechLanguage;
00105             IEnumerable<Language> supportedLanguages = SpeechRecognizer.SupportedGrammarLanguages;
00106             foreach (Language lang in supportedLanguages)
00107             {
00108                 ComboBoxItem item = new ComboBoxItem();
00109                 item.Tag = lang;
00110                 item.Content = lang.DisplayName;
00111
00112                 cbLanguageSelection.Items.Add(item);
00113                 if (lang.LanguageTag == defaultLanguage.LanguageTag)
00114                 {
00115                     item.IsSelected = true;
00116                     cbLanguageSelection.SelectedItem = item;
00117                 }
00118             }
00119
00120             isPopulatingLanguages = false;
00121         }
00122
00123         /// <summary>
00124         /// When a user changes the speech recognition language, trigger re-initialization of the
00125         /// speech engine with that language, and change any speech-specific UI assets.
00126         /// </summary>
00127         /// <param name="sender">Ignored</param>
00128         /// <param name="e">Ignored</param>
00129         private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
00130         {
00131             if (isPopulatingLanguages)
00132             {
00133                 return;
00134             }
00135
00136             ComboBoxItem item = (ComboBoxItem)(cbLanguageSelection.SelectedItem);
00137             Language newLanguage = (Language)item.Tag;
00138             if (speechRecognizer != null)
00139             {
00140                 if (speechRecognizer.CurrentLanguage == newLanguage)
00141                 {
00142                     return;
00143                 }
00144             }
00145
00146             // trigger cleanup and re-initialization of speech.
00147             try
00148             {
00149                 // update the context for resource lookup
00150                 speechContext.Languages = new string[] { newLanguage.LanguageTag };
00151
00152                 await InitializeRecognizer(newLanguage);
00153             }
00154             catch (Exception exception)
00155             {
00156                 var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
00157                 await messageDialog.ShowAsync();
00158             }
00159         }
00160
00161         /// <summary>
00162         /// Initialize Speech Recognizer and compile constraints.
00163         /// </summary>
00164         /// <param name="recognizerLanguage">Language to use for the speech recognizer</param>
00165         /// <returns>Awaitable task.</returns>
00166         private async Task InitializeRecognizer(Language recognizerLanguage)
00167         {
00168             if (speechRecognizer != null)
00169             {
00170                 // cleanup prior to re-initializing this scenario.
00171                 speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
00172                 speechRecognizer.ContinuousRecognitionSession.Completed -= ContinuousRecognitionSession_Completed;
00173                 speechRecognizer.ContinuousRecognitionSession.ResultGenerated -= ContinuousRecognitionSession_ResultGenerated;
00174
00175                 this.speechRecognizer.Dispose();
00176                 this.speechRecognizer = null;
00177             }
00178
00179             try {
00180                 this.speechRecognizer = new SpeechRecognizer(recognizerLanguage);
00181
00182                 // Provide feedback to the user about the state of the recognizer. This can be used to provide visual feedback in the form
00183                 // of an audio indicator to help the user understand whether they're being heard.
00184                 speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
00185
00186                 // Build a command-list grammar. Commands should ideally be drawn from a resource file for localization, and
00187                 // be grouped into tags for alternate forms of the same command.
00188                 speechRecognizer.Constraints.Add(
00189                     new SpeechRecognitionListConstraint(
00190                         new List<string>()
00191                         {
00192                         speechResourceMap.GetValue("ListGrammarGoHome", speechContext).ValueAsString
00193                         }, "Home"));
00194                 speechRecognizer.Constraints.Add(
00195                     new SpeechRecognitionListConstraint(
00196                         new List<string>()
00197                         {
00198                         speechResourceMap.GetValue("ListGrammarGoToContosoStudio", speechContext).ValueAsString
00199                         }, "GoToContosoStudio"));
00200                 speechRecognizer.Constraints.Add(
00201                     new SpeechRecognitionListConstraint(
00202                         new List<string>()
00203                         {
00204                         speechResourceMap.GetValue("ListGrammarShowMessage", speechContext).ValueAsString,
00205                         speechResourceMap.GetValue("ListGrammarOpenMessage", speechContext).ValueAsString
00206                         }, "Message"));
00207                 speechRecognizer.Constraints.Add(
00208                     new SpeechRecognitionListConstraint(
00209                         new List<string>()
00210                         {
00211                         speechResourceMap.GetValue("ListGrammarSendEmail", speechContext).ValueAsString,
00212                         speechResourceMap.GetValue("ListGrammarCreateEmail", speechContext).ValueAsString
00213                         }, "Email"));
00214                 speechRecognizer.Constraints.Add(
00215                     new SpeechRecognitionListConstraint(
00216                         new List<string>()
00217                         {
00218                         speechResourceMap.GetValue("ListGrammarCallNitaFarley", speechContext).ValueAsString,
00219                         speechResourceMap.GetValue("ListGrammarCallNita", speechContext).ValueAsString
00220                         }, "CallNita"));
00221                 speechRecognizer.Constraints.Add(
00222                     new SpeechRecognitionListConstraint(
00223                         new List<string>()
00224                         {
00225                         speechResourceMap.GetValue("ListGrammarCallWayneSigmon", speechContext).ValueAsString,
00226                         speechResourceMap.GetValue("ListGrammarCallWayne", speechContext).ValueAsString
00227                         }, "CallWayne"));
00228
00229                 // Update the help text in the UI to show localized examples
00230                 string uiOptionsText = string.Format("Try saying '{0}', '{1}' or '{2}'",
00231                     speechResourceMap.GetValue("ListGrammarGoHome", speechContext).ValueAsString,
00232                     speechResourceMap.GetValue("ListGrammarGoToContosoStudio", speechContext).ValueAsString,
00233                     speechResourceMap.GetValue("ListGrammarShowMessage", speechContext).ValueAsString);
00234                 listGrammarHelpText.Text = string.Format("{0}\n{1}",
00235                     speechResourceMap.GetValue("ListGrammarHelpText", speechContext).ValueAsString,
00236                     uiOptionsText);
00237
00238                 SpeechRecognitionCompilationResult result = await speechRecognizer.CompileConstraintsAsync();
00239                 if (result.Status != SpeechRecognitionResultStatus.Success)
00240                 {
00241                     // Disable the recognition buttons.
00242                     btnContinuousRecognize.IsEnabled = false;
00243
00244                     // Let the user know that the grammar didn't compile properly.
00245                     resultTextBlock.Visibility = Visibility.Visible;
00246                     resultTextBlock.Text = "Unable to compile grammar.";
00247                 }
00248                 else
00249                 {
00250                     btnContinuousRecognize.IsEnabled = true;
00251
00252                     resultTextBlock.Visibility = Visibility.Collapsed;
00253
00254
00255                     // Handle continuous recognition events. Completed fires when various error states occur. ResultGenerated fires when
00256                     // some recognized phrases occur, or the garbage rule is hit.
00257                     speechRecognizer.ContinuousRecognitionSession.Completed += ContinuousRecognitionSession_Completed;
00258                     speechRecognizer.ContinuousRecognitionSession.ResultGenerated += ContinuousRecognitionSession_ResultGenerated;
00259                 }
00260             }
00261             catch (Exception ex)
00262             {
00263                 if ((uint)ex.HResult == HResultRecognizerNotFound)
00264                 {
00265                     btnContinuousRecognize.IsEnabled = false;
00266
00267                     resultTextBlock.Visibility = Visibility.Visible;
00268                     resultTextBlock.Text = "Speech Language pack for selected language not installed.";
00269                 }
00270                 else
00271                 {
00272                     var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
00273                     await messageDialog.ShowAsync();
00274                 }
00275             }
00276
00277         }
00278
00279         /// <summary>
00280         /// Upon leaving, clean up the speech recognizer. Ensure we aren't still listening, and disable the event
00281         /// handlers to prevent leaks.
00282         /// </summary>
00283         /// <param name="e">Unused navigation parameters.</param>
00284         protected async override void OnNavigatedFrom(NavigationEventArgs e)
00285         {
00286             if (this.speechRecognizer != null)
00287             {
00288                 if (isListening)
00289                 {
00290                     await this.speechRecognizer.ContinuousRecognitionSession.CancelAsync();
00291                     isListening = false;
00292                 }
00293                 heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;
00294
00295                 speechRecognizer.ContinuousRecognitionSession.Completed -= ContinuousRecognitionSession_Completed;
00296                 speechRecognizer.ContinuousRecognitionSession.ResultGenerated -= ContinuousRecognitionSession_ResultGenerated;
00297                 speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
00298
00299                 this.speechRecognizer.Dispose();
00300                 this.speechRecognizer = null;
00301             }
00302         }
00303
00304         /// <summary>
00305         /// Handle events fired when error conditions occur, such as the microphone becoming unavailable, or if
00306         /// some transient issues occur.
00307         /// </summary>
00308         /// <param name="sender">The continuous recognition session</param>
00309         /// <param name="args">The state of the recognizer</param>
00310         private async void ContinuousRecognitionSession_Completed(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionCompletedEventArgs args)
00311         {
00312             if (args.Status != SpeechRecognitionResultStatus.Success)
00313             {
00314                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00315                 {
00316                     rootPage.NotifyUser("Continuous Recognition Completed: " + args.Status.ToString(), NotifyType.StatusMessage);
00317                     ContinuousRecoButtonText.Text = " Continuous Recognition";
00318                     cbLanguageSelection.IsEnabled = true;
00319                     isListening = false;
00320                 });
00321             }
00322         }
00323
00324         /// <summary>
00325         /// Handle events fired when a result is generated. This may include a garbage rule that fires when general room noise
00326         /// or side-talk is captured (this will have a confidence of Rejected typically, but may occasionally match a rule with
00327         /// low confidence).
00328         /// </summary>
00329         /// <param name="sender">The Recognition session that generated this result</param>
00330         /// <param name="args">Details about the recognized speech</param>
00331         private async void ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionResultGeneratedEventArgs args)
00332         {
00333             // The garbage rule will not have a tag associated with it, the other rules will return a string matching the tag provided
00334             // when generating the grammar.
00335             string tag = "unknown";
00336             if (args.Result.Constraint != null)
00337             {
00338                 tag = args.Result.Constraint.Tag;
00339             }
00340
00341             // Developers may decide to use per-phrase confidence levels in order to tune the behavior of their
00342             // grammar based on testing.
00343             if (args.Result.Confidence == SpeechRecognitionConfidence.Medium ||
00344                 args.Result.Confidence == SpeechRecognitionConfidence.High)
00345             {
00346                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00347                 {
00348                     heardYouSayTextBlock.Visibility = Visibility.Visible;
00349                     resultTextBlock.Visibility = Visibility.Visible;
00350                     resultTextBlock.Text = string.Format("Heard: '{0}', (Tag: '{1}', Confidence: {2})", args.Result.Text, tag, args.Result.Confidence.ToString());
00351                 });
00352             }
00353             else
00354             {
00355                 // In some scenarios, a developer may choose to ignore giving the user feedback in this case, if speech
00356                 // is not the primary input mechanism for the application.
00357                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00358                 {
00359                     heardYouSayTextBlock.Visibility = Visibility.Collapsed;
00360                     resultTextBlock.Visibility = Visibility.Visible;
00361                     resultTextBlock.Text = string.Format("Sorry, I didn't catch that. (Heard: '{0}', Tag: {1}, Confidence: {2})", args.Result.Text, tag, args.Result.Confidence.ToString());
00362                 });
00363             }
00364         }
00365
00366         /// <summary>
00367         /// Provide feedback to the user based on whether the recognizer is receiving their voice input.
00368         /// </summary>
00369         /// <param name="sender">The recognizer that is currently running.</param>
00370         /// <param name="args">The current state of the recognizer.</param>
00371         private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args)
00372         {
00373             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
00374                 rootPage.NotifyUser(args.State.ToString(), NotifyType.StatusMessage);
00375             });
00376         }
00377
00378         /// <summary>
00379         /// Begin recognition, or finish the recognition session.
00380         /// </summary>
00381         /// <param name="sender">The button that generated this event</param>
00382         /// <param name="e">Unused event details</param>
00383         public async void ContinuousRecognize_Click(object sender, RoutedEventArgs e)
00384         {
00385             btnContinuousRecognize.IsEnabled = false;
00386             if (isListening == false)
00387             {
00388                 // The recognizer can only start listening in a continuous fashion if the recognizer is currently idle.
00389                 // This prevents an exception from occurring.
00390                 if (speechRecognizer.State == SpeechRecognizerState.Idle)
00391                 {
00392                     try
00393                     {
00394                         await speechRecognizer.ContinuousRecognitionSession.StartAsync();
00395                         ContinuousRecoButtonText.Text = " Stop Continuous Recognition";
00396                         cbLanguageSelection.IsEnabled = false;
00397                         isListening = true;
00398                     }
00399                     catch (Exception ex)
00400                     {
00401                         var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
00402                         await messageDialog.ShowAsync();
00403                     }
00404                 }
00405             }
00406             else
00407             {
00408                 isListening = false;
00409                 ContinuousRecoButtonText.Text = " Continuous Recognition";
00410                 cbLanguageSelection.IsEnabled = true;
00411
00412                 heardYouSayTextBlock.Visibility = Visibility.Collapsed;
00413                 resultTextBlock.Visibility = Visibility.Collapsed;
00414                 if (speechRecognizer.State != SpeechRecognizerState.Idle)
00415                 {
00416                     try
00417                     {
00418                         // Cancelling recognition prevents any currently recognized speech from
00419                         // generating a ResultGenerated event. StopAsync() will allow the final session to
00420                         // complete.
00421                         await speechRecognizer.ContinuousRecognitionSession.CancelAsync();
00422                     }
00423                     catch (Exception ex)
00424                     {
00425                         var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
00426                         await messageDialog.ShowAsync();
00427                     }
00428                 }
00429             }
00430
00431             btnContinuousRecognize.IsEnabled = true;
00432         }
00433     }
00434 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ModelConstantBuffer Member List

This is the complete list of members for ModelConstantBuffer, including all inherited members.
color | ModelConstantBuffer
model | ModelConstantBuffer
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cppwinrt/SampleConfiguration.cpp Source File

  • FilePicker
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"File picker C++/WinRT sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Pick a single photo",   xaml_typename<SDKTemplate::Scenario1_SingleFile>() },
00029     Scenario{ L"Pick multiple files",   xaml_typename<SDKTemplate::Scenario2_MultiFile>() },
00030     Scenario{ L"Pick a folder",         xaml_typename<SDKTemplate::Scenario3_SingleFolder>() },
00031     Scenario{ L"Save a file",           xaml_typename<SDKTemplate::Scenario4_SaveFile>() },
00032     Scenario{ L"Trigger CFU",           xaml_typename<SDKTemplate::Scenario5_TriggerCFU>() },
00033 });
Generated on Fri Nov 15 2024 22:17:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cs/Scenario6_ManipulatingCursorAttributes.xaml.cs Source File

  • LineDisplay
  • cs

Scenario6_ManipulatingCursorAttributes.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.ObjectModel;
00014 using System.Threading.Tasks;
00015 using Windows.Devices.PointOfService;
00016 using Windows.Foundation;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario6_ManipulatingCursorAttributes : Page
00024     {
00025         private MainPage rootPage = MainPage.Current;
00026         private ClaimedLineDisplay lineDisplay;
00027
00028         public Scenario6_ManipulatingCursorAttributes()
00029         {
00030             this.InitializeComponent();
00031             this.DataContext = this;
00032         }
00033
00034         protected override async void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             await InitializeAsync();
00037         }
00038
00039         protected override void OnNavigatedFrom(NavigationEventArgs e)
00040         {
00041             lineDisplay?.Dispose();
00042             lineDisplay = null;
00043         }
00044
00045         private async Task InitializeAsync()
00046         {
00047             UpdateButton.IsEnabled = false;
00048             DisplayTextButton.IsEnabled = false;
00049             ResetButton.IsEnabled = false;
00050             CursorTypeComboBox.Items.Clear();
00051
00052             lineDisplay = await rootPage.ClaimScenarioLineDisplayAsync();
00053
00054             CursorTypeComboBox.IsEnabled = (lineDisplay != null) && lineDisplay.DefaultWindow.Cursor.CanCustomize;
00055             if (CursorTypeComboBox.IsEnabled)
00056             {
00057                 if (lineDisplay.DefaultWindow.Cursor.IsBlockSupported)
00058                 {
00059                     CursorTypeComboBox.Items.Add(LineDisplayCursorType.Block);
00060                 }
00061
00062                 if (lineDisplay.DefaultWindow.Cursor.IsHalfBlockSupported)
00063                 {
00064                     CursorTypeComboBox.Items.Add(LineDisplayCursorType.HalfBlock);
00065                 }
00066
00067                 if (lineDisplay.DefaultWindow.Cursor.IsOtherSupported)
00068                 {
00069                     CursorTypeComboBox.Items.Add(LineDisplayCursorType.Other);
00070                 }
00071
00072                 if (lineDisplay.DefaultWindow.Cursor.IsReverseSupported)
00073                 {
00074                     CursorTypeComboBox.Items.Add(LineDisplayCursorType.Reverse);
00075                 }
00076
00077                 if (lineDisplay.DefaultWindow.Cursor.IsUnderlineSupported)
00078                 {
00079                     CursorTypeComboBox.Items.Add(LineDisplayCursorType.Underline);
00080                 }
00081
00082                 if (CursorTypeComboBox.Items.Count > 0)
00083                 {
00084                     CursorTypeComboBox.SelectedIndex = 0;
00085                 }
00086             }
00087
00088             IsAutoAdvanceEnabledCheckbox.IsEnabled = (lineDisplay != null);
00089
00090             IsBlinkEnabledCheckbox.IsEnabled = (lineDisplay != null) && lineDisplay.DefaultWindow.Cursor.IsBlinkSupported;
00091             SetCursorPositionCheckbox.IsEnabled = (lineDisplay != null);
00092             UpdateButton.IsEnabled = (lineDisplay != null);
00093             DisplayTextButton.IsEnabled = (lineDisplay != null);
00094
00095             ResetButton.IsEnabled = true;
00096         }
00097
00098         private async void UpdateButton_Click(object sender, RoutedEventArgs e)
00099         {
00100             LineDisplayCursorAttributes cursorAttributes = lineDisplay.DefaultWindow.Cursor.GetAttributes();
00101             cursorAttributes.IsAutoAdvanceEnabled = IsAutoAdvanceEnabledCheckbox.IsChecked.Value;
00102
00103             if (lineDisplay.DefaultWindow.Cursor.CanCustomize && (CursorTypeComboBox.SelectedItem != null))
00104             {
00105                 cursorAttributes.CursorType = (LineDisplayCursorType)CursorTypeComboBox.SelectedItem;
00106             }
00107
00108             if (lineDisplay.DefaultWindow.Cursor.IsBlinkSupported)
00109             {
00110                 cursorAttributes.IsBlinkEnabled = IsBlinkEnabledCheckbox.IsChecked.Value;
00111             }
00112
00113             if (SetCursorPositionCheckbox.IsChecked.Value)
00114             {
00115                 Point position = new Point()
00116                 {
00117                     X = Helpers.ParseUIntWithFallback(CursorPositionXTextBox, -1.0),
00118                     Y = Helpers.ParseUIntWithFallback(CursorPositionYTextBox, -1.0),
00119                 };
00120
00121                 Size windowSizeInCharacters = lineDisplay.DefaultWindow.SizeInCharacters;
00122                 if ((position.X < 0) || (position.X >= windowSizeInCharacters.Width) ||
00123                     (position.Y < 0) || (position.Y >= windowSizeInCharacters.Height))
00124                 {
00125                     rootPage.NotifyUser("Cursor position must be within the window.", NotifyType.ErrorMessage);
00126                     return;
00127                 }
00128
00129                 cursorAttributes.Position = position;
00130             }
00131
00132             if (await lineDisplay.DefaultWindow.Cursor.TryUpdateAttributesAsync(cursorAttributes))
00133             {
00134                 rootPage.NotifyUser("Cursor updated.", NotifyType.StatusMessage);
00135             }
00136             else
00137             {
00138                 rootPage.NotifyUser("Failed to update the cursor.", NotifyType.ErrorMessage);
00139             }
00140         }
00141
00142         private async void DisplayTextButton_Click(object sender, RoutedEventArgs e)
00143         {
00144             if (await lineDisplay.DefaultWindow.TryDisplayTextAsync("Text"))
00145             {
00146                 rootPage.NotifyUser("Text displayed.", NotifyType.StatusMessage);
00147             }
00148             else
00149             {
00150                 rootPage.NotifyUser("Failed to display text.", NotifyType.ErrorMessage);
00151             }
00152         }
00153
00154         private async void ResetButton_Click(object sender, RoutedEventArgs e)
00155         {
00156             lineDisplay?.Dispose();
00157             await InitializeAsync();
00158         }
00159     }
00160 }
Generated on Fri Nov 15 2024 22:20:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-I2C/cpp/Scenario1_ReadData.xaml.cpp Source File

  • IoT-I2C
  • cpp

Scenario1_ReadData.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_ReadData.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Devices::I2c;
00020 using namespace Windows::Devices::Enumeration;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Controls::Primitives;
00027 using namespace Windows::UI::Xaml::Data;
00028 using namespace Windows::UI::Xaml::Input;
00029 using namespace Windows::UI::Xaml::Media;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 Scenario1_ReadData::Scenario1_ReadData()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 void Scenario1_ReadData::OnNavigatedFrom(NavigationEventArgs^ e)
00038 {
00039     StopScenario();
00040 }
00041
00042 task<void> Scenario1_ReadData::StartScenarioAsync()
00043 {
00044     String^ i2cDeviceSelector = I2cDevice::GetDeviceSelector();
00045
00046     return create_task(DeviceInformation::FindAllAsync(i2cDeviceSelector))
00047         .then([this](DeviceInformationCollection^ devices) {
00048
00049         // 0x40 was determined by looking at the datasheet for the HTU21D sensor
00050         auto HTU21D_settings = ref new I2cConnectionSettings(0x40);
00051
00052         // If this next line crashes with an OutOfBoundsException,
00053         // then the problem is that no I2C devices were found.
00054         //
00055         // If the next line crashes with Access Denied, then the problem is
00056         // that access to the I2C device (HTU21D) is denied.
00057         //
00058         // The call to FromIdAsync will also crash if the settings are invalid.
00059         return I2cDevice::FromIdAsync(devices->GetAt(0)->Id, HTU21D_settings);
00060     }).then([this](I2cDevice^ i2cDevice) {
00061
00062         // i2cDevice will be nullptr if there is a sharing violation on the device.
00063         // This will result in an access violation in Timer_Tick below.
00064         htu21dSensor = i2cDevice;
00065
00066         // Start the polling timer.
00067         timer = ref new DispatcherTimer();
00068         timer->Interval = TimeSpan{ 500 * 1000 * 10 }; // 500ms
00069         timerToken = timer->Tick += ref new EventHandler<Object^>(this, &SDKTemplate::Scenario1_ReadData::Timer_Tick);
00070         timer->Start();
00071     });
00072 }
00073
00074 void Scenario1_ReadData::StopScenario()
00075 {
00076     if (timer != nullptr)
00077     {
00078         timer->Tick -= timerToken;
00079         timer->Stop();
00080         timer = nullptr;
00081     }
00082
00083     // Release the I2C sensor.
00084     delete htu21dSensor;
00085     htu21dSensor = nullptr;
00086 }
00087
00088 void Scenario1_ReadData::StartStopScenario_Click(Object^ sender, RoutedEventArgs^ e)
00089 {
00090     if (timer != nullptr)
00091     {
00092         StopScenario();
00093         StartStopButton->Content = "Start";
00094         ScenarioControls->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00095     }
00096     else
00097     {
00098         StartStopButton->IsEnabled = false;
00099         StartScenarioAsync().then([this]()
00100         {
00101             StartStopButton->IsEnabled = true;
00102             StartStopButton->Content = "Stop";
00103             ScenarioControls->Visibility = Windows::UI::Xaml::Visibility::Visible;
00104         });
00105     }
00106 }
00107
00108 void Scenario1_ReadData::Timer_Tick(Object^ sender, Object^ e)
00109 {
00110     // Read data from I2C.
00111     auto command = ref new Array<byte>(1);
00112     auto humidityData = ref new Array<byte>(2);
00113     auto temperatureData = ref new Array<byte>(2);
00114
00115
00116     // Read humidity.
00117     command[0] = 0xE5;
00118
00119     // If this next line crashes with an access violation reading location 0x00000000,
00120     // then there was a sharing violation on the device. (See StartScenarioAsync above.)
00121     //
00122     // If this next line crashes for some other reason, then there was
00123     // an error accessing the sensor.
00124     htu21dSensor->WriteRead(command, humidityData);
00125
00126     // Read temperature.
00127     command[0] = 0xE3;
00128     // If this next line crashes, then there was an error accessing the sensor.
00129     htu21dSensor->WriteRead(command, temperatureData);
00130
00131     // Calculate and report humidity.
00132     auto rawReadingH = humidityData[0] << 8 | humidityData[1];
00133     auto ratioH = rawReadingH / (float)65536;
00134     double humidity = -6 + (125 * ratioH);
00135     CurrentHumidity->Text = humidity.ToString();
00136
00137     //Calculate and report temperature.
00138     auto rawReadingT = temperatureData[0] << 8 | temperatureData[1];
00139     auto ratioT = rawReadingT / (float)65536;
00140     double temperature = (-46.85 + (175.72 * ratioT)) * 9 / 5 + 32;
00141     CurrentTemp->Text = temperature.ToString();
00142 }
Generated on Fri Nov 15 2024 22:20:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_DocumentFonts Member List

This is the complete list of members for Scenario2_DocumentFonts, including all inherited members.
ApplyFonts_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_DocumentFonts
Scenario2_DocumentFonts() | Scenario2_DocumentFonts
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareTarget/cs/ShareTarget.xaml.cs Source File

  • ShareTarget
  • cs

ShareTarget.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Collections.Generic;
00013 using System.Text;
00014 using System.Threading.Tasks;
00015 using Windows.ApplicationModel;
00016 using Windows.ApplicationModel.DataTransfer;
00017 using Windows.ApplicationModel.DataTransfer.ShareTarget;
00018 using Windows.Data.Json;
00019 using Windows.Storage;
00020 using Windows.Storage.Streams;
00021 using Windows.UI;
00022 using Windows.UI.Core;
00023 using Windows.UI.Text;
00024 using Windows.UI.Xaml;
00025 using Windows.UI.Xaml.Controls;
00026 using Windows.UI.Xaml.Documents;
00027 using Windows.UI.Xaml.Input;
00028 using Windows.UI.Xaml.Media;
00029 using Windows.UI.Xaml.Media.Imaging;
00030 using Windows.UI.Xaml.Navigation;
00031
00032 namespace SDKTemplate
00033 {
00034     public sealed partial class ShareTarget : Page
00035     {
00036         ShareOperation shareOperation;
00037         private string sharedDataTitle;
00038         private string sharedDataDescription;
00039         private string sharedDataPackageFamilyName;
00040         private Uri sharedDataContentSourceWebLink;
00041         private Uri sharedDataContentSourceApplicationLink;
00042         private Color sharedDataLogoBackgroundColor;
00043         private IRandomAccessStreamReference sharedDataSquare30x30Logo;
00044         private string shareQuickLinkId;
00045         private string sharedText;
00046         private Uri sharedWebLink;
00047         private Uri sharedApplicationLink;
00048         private IReadOnlyList<IStorageItem> sharedStorageItems;
00049         private string sharedCustomData;
00050         private string sharedHtmlFormat;
00051         private IReadOnlyDictionary<string, RandomAccessStreamReference> sharedResourceMap;
00052         private IRandomAccessStreamReference sharedBitmapStreamRef;
00053         private IRandomAccessStreamReference sharedThumbnailStreamRef;
00054         private const string dataFormatName = "http://schema.org/Book";
00055
00056         public ShareTarget()
00057         {
00058             this.InitializeComponent();
00059         }
00060
00061         protected override async void OnNavigatedTo(NavigationEventArgs e)
00062         {
00063             // It is recommended to only retrieve the ShareOperation object in the activation handler, return as
00064             // quickly as possible, and retrieve all data from the share target asynchronously.
00065
00066             this.shareOperation = (ShareOperation)e.Parameter;
00067
00068             await Task.Factory.StartNew(async () =>
00069             {
00070                 // Retrieve the data package properties.
00071                 this.sharedDataTitle = this.shareOperation.Data.Properties.Title;
00072                 this.sharedDataDescription = this.shareOperation.Data.Properties.Description;
00073                 this.sharedDataPackageFamilyName = this.shareOperation.Data.Properties.PackageFamilyName;
00074                 this.sharedDataContentSourceWebLink = this.shareOperation.Data.Properties.ContentSourceWebLink;
00075                 this.sharedDataContentSourceApplicationLink = this.shareOperation.Data.Properties.ContentSourceApplicationLink;
00076                 this.sharedDataLogoBackgroundColor = this.shareOperation.Data.Properties.LogoBackgroundColor;
00077                 this.sharedDataSquare30x30Logo = this.shareOperation.Data.Properties.Square30x30Logo;
00078                 this.sharedThumbnailStreamRef = this.shareOperation.Data.Properties.Thumbnail;
00079                 this.shareQuickLinkId = this.shareOperation.QuickLinkId;
00080
00081                 // Retrieve the data package content.
00082                 // The GetWebLinkAsync(), GetTextAsync(), GetStorageItemsAsync(), etc. APIs will throw if there was an error retrieving the data from the source app.
00083                 // In this sample, we just display the error. It is recommended that a share target app handles these in a way appropriate for that particular app.
00084                 if (this.shareOperation.Data.Contains(StandardDataFormats.WebLink))
00085                 {
00086                     try
00087                     {
00088                         this.sharedWebLink = await this.shareOperation.Data.GetWebLinkAsync();
00089                     }
00090                     catch (Exception ex)
00091                     {
00092                         NotifyUserBackgroundThread("Failed GetWebLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
00093                     }
00094                 }
00095                 if (this.shareOperation.Data.Contains(StandardDataFormats.ApplicationLink))
00096                 {
00097                     try
00098                     {
00099                         this.sharedApplicationLink = await this.shareOperation.Data.GetApplicationLinkAsync();
00100                     }
00101                     catch (Exception ex)
00102                     {
00103                         NotifyUserBackgroundThread("Failed GetApplicationLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
00104                     }
00105                 }
00106                 if (this.shareOperation.Data.Contains(StandardDataFormats.Text))
00107                 {
00108                     try
00109                     {
00110                         this.sharedText = await this.shareOperation.Data.GetTextAsync();
00111                     }
00112                     catch (Exception ex)
00113                     {
00114                         NotifyUserBackgroundThread("Failed GetTextAsync - " + ex.Message, NotifyType.ErrorMessage);
00115                     }
00116                 }
00117                 if (this.shareOperation.Data.Contains(StandardDataFormats.StorageItems))
00118                 {
00119                     try
00120                     {
00121                         this.sharedStorageItems = await this.shareOperation.Data.GetStorageItemsAsync();
00122                     }
00123                     catch (Exception ex)
00124                     {
00125                         NotifyUserBackgroundThread("Failed GetStorageItemsAsync - " + ex.Message, NotifyType.ErrorMessage);
00126                     }
00127                 }
00128                 if (this.shareOperation.Data.Contains(dataFormatName))
00129                 {
00130                     try
00131                     {
00132                         this.sharedCustomData = await this.shareOperation.Data.GetTextAsync(dataFormatName);
00133                     }
00134                     catch (Exception ex)
00135                     {
00136                         NotifyUserBackgroundThread("Failed GetTextAsync(" + dataFormatName + ") - " + ex.Message, NotifyType.ErrorMessage);
00137                     }
00138                 }
00139                 if (this.shareOperation.Data.Contains(StandardDataFormats.Html))
00140                 {
00141                     try
00142                     {
00143                         this.sharedHtmlFormat = await this.shareOperation.Data.GetHtmlFormatAsync();
00144                     }
00145                     catch (Exception ex)
00146                     {
00147                         NotifyUserBackgroundThread("Failed GetHtmlFormatAsync - " + ex.Message, NotifyType.ErrorMessage);
00148                     }
00149
00150                     try
00151                     {
00152                         this.sharedResourceMap = await this.shareOperation.Data.GetResourceMapAsync();
00153                     }
00154                     catch (Exception ex)
00155                     {
00156                         NotifyUserBackgroundThread("Failed GetResourceMapAsync - " + ex.Message, NotifyType.ErrorMessage);
00157                     }
00158                 }
00159                 if (this.shareOperation.Data.Contains(StandardDataFormats.Bitmap))
00160                 {
00161                     try
00162                     {
00163                         this.sharedBitmapStreamRef = await this.shareOperation.Data.GetBitmapAsync();
00164                     }
00165                     catch (Exception ex)
00166                     {
00167                         NotifyUserBackgroundThread("Failed GetBitmapAsync - " + ex.Message, NotifyType.ErrorMessage);
00168                     }
00169                 }
00170
00171                 // In this sample, we just display the shared data content.
00172
00173                 // Get back to the UI thread using the dispatcher.
00174                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
00175                 {
00176                     DataPackageTitle.Text = this.sharedDataTitle;
00177                     DataPackageDescription.Text = this.sharedDataDescription;
00178                     DataPackagePackageFamilyName.Text = this.sharedDataPackageFamilyName;
00179                     if (this.sharedDataContentSourceWebLink != null)
00180                     {
00181                         DataPackageContentSourceWebLink.Text = this.sharedDataContentSourceWebLink.AbsoluteUri;
00182                     }
00183                     if (this.sharedDataContentSourceApplicationLink != null)
00184                     {
00185                         DataPackageContentSourceApplicationLink.Text = this.sharedDataContentSourceApplicationLink.AbsoluteUri;
00186                     }
00187
00188                     if (this.sharedDataSquare30x30Logo != null)
00189                     {
00190                         IRandomAccessStreamWithContentType logoStream = await this.sharedDataSquare30x30Logo.OpenReadAsync();
00191                         BitmapImage bitmapImage = new BitmapImage();
00192                         bitmapImage.SetSource(logoStream);
00193                         LogoHolder.Source = bitmapImage;
00194                         LogoBackground.Background = new SolidColorBrush(this.sharedDataLogoBackgroundColor);
00195                         LogoArea.Visibility = Visibility.Visible;
00196                     }
00197
00198                     if (!String.IsNullOrEmpty(this.shareOperation.QuickLinkId))
00199                     {
00200                         SelectedQuickLinkId.Text = this.shareQuickLinkId;
00201                     }
00202
00203                     if (this.sharedThumbnailStreamRef != null)
00204                     {
00205                         IRandomAccessStreamWithContentType thumbnailStream = await this.sharedThumbnailStreamRef.OpenReadAsync();
00206                         BitmapImage bitmapImage = new BitmapImage();
00207                         bitmapImage.SetSource(thumbnailStream);
00208                         ThumbnailHolder.Source = bitmapImage;
00209                         ThumbnailArea.Visibility = Visibility.Visible;
00210                     }
00211
00212                     if (this.sharedWebLink != null)
00213                     {
00214                         AddContentValue("WebLink: ", this.sharedWebLink.AbsoluteUri);
00215                     }
00216                     if (this.sharedApplicationLink != null)
00217                     {
00218                         AddContentValue("ApplicationLink: ", this.sharedApplicationLink.AbsoluteUri);
00219                     }
00220                     if (this.sharedText != null)
00221                     {
00222                         AddContentValue("Text: ", this.sharedText);
00223                     }
00224                     if (this.sharedStorageItems != null)
00225                     {
00226                         // Display the name of the files being shared.
00227                         StringBuilder fileNames = new StringBuilder();
00228                         for (int index = 0; index < this.sharedStorageItems.Count; index++)
00229                         {
00230                             fileNames.Append(this.sharedStorageItems[index].Name);
00231                             if (index < this.sharedStorageItems.Count - 1)
00232                             {
00233                                 fileNames.Append(", ");
00234                             }
00235                         }
00236                         fileNames.Append(".");
00237
00238                         AddContentValue("StorageItems: ", fileNames.ToString());
00239                     }
00240                     if (this.sharedCustomData != null)
00241                     {
00242                         // This is an area to be especially careful parsing data from the source app to avoid buffer overruns.
00243                         // This sample doesn't perform data validation but will catch any exceptions thrown.
00244                         try
00245                         {
00246                             StringBuilder receivedStrings = new StringBuilder();
00247                             JsonObject customObject = JsonObject.Parse(this.sharedCustomData);
00248                             if (customObject.ContainsKey("type"))
00249                             {
00250                                 if (customObject["type"].GetString() == "http://schema.org/Book")
00251                                 {
00252                                     // This sample expects the custom format to be of type http://schema.org/Book
00253                                     receivedStrings.AppendLine("Type: " + customObject["type"].Stringify());
00254                                     JsonObject properties = customObject["properties"].GetObject();
00255                                     receivedStrings.AppendLine("Image: " + properties["image"].Stringify());
00256                                     receivedStrings.AppendLine("Name: " + properties["name"].Stringify());
00257                                     receivedStrings.AppendLine("Book Format: " + properties["bookFormat"].Stringify());
00258                                     receivedStrings.AppendLine("Author: " + properties["author"].Stringify());
00259                                     receivedStrings.AppendLine("Number of Pages: " + properties["numberOfPages"].Stringify());
00260                                     receivedStrings.AppendLine("Publisher: " + properties["publisher"].Stringify());
00261                                     receivedStrings.AppendLine("Date Published: " + properties["datePublished"].Stringify());
00262                                     receivedStrings.AppendLine("In Language: " + properties["inLanguage"].Stringify());
00263                                     receivedStrings.Append("ISBN: " + properties["isbn"].Stringify());
00264
00265                                     AddContentValue("Custom format data:" + Environment.NewLine, receivedStrings.ToString());
00266                                 }
00267                                 else
00268                                 {
00269                                     NotifyUser("The custom format from the source app is not of type http://schema.org/Book", NotifyType.ErrorMessage);
00270                                 }
00271                             }
00272                             else
00273                             {
00274                                 NotifyUser("The custom format from the source app doesn't contain a type", NotifyType.ErrorMessage);
00275                             }
00276                         }
00277                         catch (Exception ex)
00278                         {
00279                             NotifyUser("Failed to parse the custom data - " + ex.Message, NotifyType.ErrorMessage);
00280                         }
00281                     }
00282                     if (this.sharedHtmlFormat != null)
00283                     {
00284                         string htmlFragment = HtmlFormatHelper.GetStaticFragment(this.sharedHtmlFormat);
00285                         if (!String.IsNullOrEmpty(htmlFragment))
00286                         {
00287                             AddContentValue("HTML: ");
00288                             ShareWebView.Visibility = Visibility.Visible;
00289                             ShareWebView.NavigateToString("<html><body>" + htmlFragment + "</body></html>");
00290                         }
00291                         else
00292                         {
00293                             NotifyUser("GetStaticFragment failed to parse the HTML from the source app", NotifyType.ErrorMessage);
00294                         }
00295
00296                         // Check if there are any local images in the resource map.
00297                         if (this.sharedResourceMap.Count > 0)
00298                         {
00299                             ResourceMapValue.Text = "";
00300                             foreach (KeyValuePair<string, RandomAccessStreamReference> item in this.sharedResourceMap)
00301                             {
00302                                 ResourceMapValue.Text += "\nKey: " + item.Key;
00303                             }
00304                             ResourceMapArea.Visibility = Visibility.Visible;
00305                         }
00306                     }
00307                     if (this.sharedBitmapStreamRef != null)
00308                     {
00309                         IRandomAccessStreamWithContentType bitmapStream = await this.sharedBitmapStreamRef.OpenReadAsync();
00310                         BitmapImage bitmapImage = new BitmapImage();
00311                         bitmapImage.SetSource(bitmapStream);
00312                         ImageHolder.Source = bitmapImage;
00313                         ImageArea.Visibility = Visibility.Visible;
00314                     }
00315                 });
00316             });
00317         }
00318
00319         private void QuickLinkSectionLabel_Tapped(object sender, TappedRoutedEventArgs e)
00320         {
00321             // Trigger the appropriate Checked/Unchecked event if the user taps on the text instead of the checkbox.
00322             AddQuickLink.IsChecked = !AddQuickLink.IsChecked;
00323         }
00324
00325         private void AddQuickLink_Checked(object sender, RoutedEventArgs e)
00326         {
00327             QuickLinkCustomization.Visibility = Visibility.Visible;
00328         }
00329
00330         private void AddQuickLink_Unchecked(object sender, RoutedEventArgs e)
00331         {
00332             QuickLinkCustomization.Visibility = Visibility.Collapsed;
00333         }
00334
00335         async void ReportCompleted_Click(object sender, RoutedEventArgs e)
00336         {
00337             if (AddQuickLink.IsChecked.Equals(true))
00338             {
00339                 QuickLink quickLinkInfo = new QuickLink
00340                 {
00341                     Id = QuickLinkId.Text,
00342                     Title = QuickLinkTitle.Text,
00343
00344                     // For QuickLinks, the supported FileTypes and DataFormats are set independently from the manifest.
00345                     SupportedFileTypes = { "*" },
00346                     SupportedDataFormats =
00347                     {
00348                         StandardDataFormats.Text,
00349                         StandardDataFormats.WebLink,
00350                         StandardDataFormats.ApplicationLink,
00351                         StandardDataFormats.Bitmap,
00352                         StandardDataFormats.StorageItems,
00353                         StandardDataFormats.Html,
00354                         dataFormatName
00355                     }
00356                 };
00357
00358                 try
00359                 {
00360                     StorageFile iconFile = await Package.Current.InstalledLocation.CreateFileAsync("assets\\squareTile-sdk.png", CreationCollisionOption.OpenIfExists);
00361                     quickLinkInfo.Thumbnail = RandomAccessStreamReference.CreateFromFile(iconFile);
00362                     this.shareOperation.ReportCompleted(quickLinkInfo);
00363                 }
00364                 catch (Exception)
00365                 {
00366                     // Even if the QuickLink cannot be created it is important to call ReportCompleted. Otherwise, if this is a long-running share,
00367                     // the app will stick around in the long-running share progress list.
00368                     this.shareOperation.ReportCompleted();
00369                     throw;
00370                 }
00371             }
00372             else
00373             {
00374                 this.shareOperation.ReportCompleted();
00375             }
00376         }
00377
00378         private void DismissUI_Click(object sender, RoutedEventArgs e)
00379         {
00380             this.shareOperation.DismissUI();
00381         }
00382
00383         private void OtherShareOperations_Tapped(object sender, TappedRoutedEventArgs e)
00384         {
00385             // Trigger the appropriate Checked/Unchecked event if the user taps on the text instead of the checkbox.
00386             OtherShareOperationMethodsSection.IsChecked = !OtherShareOperationMethodsSection.IsChecked;
00387         }
00388
00389         private void OtherShareOperationMethodsSection_Unchecked(object sender, RoutedEventArgs e)
00390         {
00391             ExtendedSharingArea.Visibility = Visibility.Collapsed;
00392         }
00393
00394         private void OtherShareOperationMethodsSection_Checked(object sender, RoutedEventArgs e)
00395         {
00396             ExtendedSharingArea.Visibility = Visibility.Visible;
00397         }
00398
00399         private void ReportDataRetrieved_Click(object sender, RoutedEventArgs e)
00400         {
00401             this.shareOperation.ReportDataRetrieved();
00402             this.NotifyUser("Data retrieved...", NotifyType.StatusMessage);
00403         }
00404
00405         private void ReportErrorButton_Click(object sender, RoutedEventArgs e)
00406         {
00407             this.shareOperation.ReportError(ReportError.Text);
00408         }
00409
00410         async private void Footer_Click(object sender, RoutedEventArgs e)
00411         {
00412             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00413         }
00414
00415         private void NotifyUser(string strMessage, NotifyType type)
00416         {
00417             switch (type)
00418             {
00419                 // Use the status message style.
00420                 case NotifyType.StatusMessage:
00421                     StatusBlock.Style = Resources["StatusStyle"] as Style;
00422                     break;
00423                 // Use the error message style.
00424                 case NotifyType.ErrorMessage:
00425                     StatusBlock.Style = Resources["ErrorStyle"] as Style;
00426                     break;
00427             }
00428             StatusBlock.Text = strMessage;
00429         }
00430
00431         async private void NotifyUserBackgroundThread(string message, NotifyType type)
00432         {
00433             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00434             {
00435                 NotifyUser(message, type);
00436             });
00437         }
00438
00439         private void AddContentValue(string title, string description = null)
00440         {
00441             Run contentType = new Run();
00442             contentType.FontWeight = FontWeights.Bold;
00443             contentType.Text = title;
00444             ContentValue.Inlines.Add(contentType);
00445
00446             if (description != null)
00447             {
00448                 Run contentValue = new Run();
00449                 contentValue.Text = description + Environment.NewLine;
00450                 ContentValue.Inlines.Add(contentValue);
00451             }
00452         }
00453     }
00454 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: VideoPlayback/cs/Scenario4_SelectingVideoTracks.xaml.cs Source File

  • VideoPlayback
  • cs

Scenario4_SelectingVideoTracks.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate.Logging;
00013 using System;
00014 using Windows.Media.Core;
00015 using Windows.Media.Playback;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// Demonstrates multi-track video playback and camera selection.
00025     /// </summary>
00026     public sealed partial class Scenario4 : Page
00027     {
00028         MainPage rootPage = MainPage.Current;
00029         private MediaPlaybackItemLogger mpiLogger;
00030         MediaPlaybackItem item;
00031
00032         public Scenario4()
00033         {
00034             this.InitializeComponent();
00035         }
00036
00037         protected override void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039             this.item = new MediaPlaybackItem(MediaSource.CreateFromUri(rootPage.MultiTrackVideoMediaUri));
00040             mpiLogger = new MediaPlaybackItemLogger(LoggerControl, item);
00041
00042             item.VideoTracks.SelectedIndexChanged += VideoTracks_SelectedIndexChanged;
00043
00044             this.mediaPlayerElement.Source = item;
00045             LoggerControl.Log($"Loaded: {rootPage.MultiTrackVideoMediaUri}");
00046         }
00047
00048         protected override void OnNavigatedFrom(NavigationEventArgs e)
00049         {
00050             mpiLogger?.Dispose();
00051             mpiLogger = null;
00052             MediaPlayerHelper.CleanUpMediaPlayerSource(mediaPlayerElement.MediaPlayer);
00053         }
00054
00055         private void TrackButton_Click(object sender, RoutedEventArgs e)
00056         {
00057             // Get the video track index based on value of the 'tag' field
00058             var button = sender as Button;
00059             int videoTrackIndex = int.Parse(button.Tag as string);
00060
00061             // Select the clicked camera track
00062             if (this.item != null && this.item.VideoTracks != null && this.item.VideoTracks.Count -1 >= videoTrackIndex)
00063             {
00064                 this.item.VideoTracks.SelectedIndex = videoTrackIndex;
00065             }
00066         }
00067
00068         private async void VideoTracks_SelectedIndexChanged(ISingleSelectMediaTrackList sender, object args)
00069         {
00070             var videoTrackIndex = sender.SelectedIndex;
00071
00072             LoggerControl.Log("Switched to video track #" + (videoTrackIndex + 1)
00073                     + " | Id: " + this.item.VideoTracks[videoTrackIndex].Id
00074                     + " | Label: " + this.item.VideoTracks[videoTrackIndex].Label);
00075
00076             // Forces a new frame to be rendered when we are paused.
00077             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00078             {
00079                 //Make sure to call the mediaPlayerElement on the UI thread:
00080                 if (mediaPlayerElement.MediaPlayer.PlaybackSession.PlaybackState == MediaPlaybackState.Paused)
00081                     mediaPlayerElement.MediaPlayer.StepForwardOneFrame();
00082             });
00083         }
00084     }
00085 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAccountManagement/cpp/SampleConfiguration.cpp Source File

  • WebAccountManagement
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 // Important Note for running this sample:
00010 // The sample as-is will not be able to get tokens without having it's app manifest being
00011 // modified to use the App Identity of a registered Microsoft Store/registered AAD app.
00012 //
00013 // See 'Related Topics' in the README.md for instructions on how to register an app.
00014
00015 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00016 {
00017     { "Default Account", "SDKTemplate.Scenario1_DefaultAccount" },
00018     { "Microsoft account", "SDKTemplate.Scenario2_Msa" },
00019     { "Azure Active Directory", "SDKTemplate.Scenario3_Aad" },
00020     { "Many Providers, One Signed In Account", "SDKTemplate.Scenario4_ManyProviders" },
00021     { "Many Providers, Many Signed In Accounts", "SDKTemplate.Scenario5_ManyProvidersManyAccounts" },
00022     { "Custom Provider", "SDKTemplate.Scenario6_CustomProvider" }
00023 };
Generated on Fri Nov 15 2024 22:17:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cpp/Scenario2_DeviceConnect.xaml.cpp Source File

  • CustomCapability
  • cpp

Scenario2_DeviceConnect.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "Scenario2_DeviceConnect.xaml.h"
00015 #include "DeviceList.h"
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace SDKTemplate;
00020 using namespace Windows::Devices::Custom;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 DeviceConnect::DeviceConnect()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 void DeviceConnect::OnNavigatedTo(NavigationEventArgs^ e)
00031 {
00032     listSource->Source = DeviceList::Current->Fx2Devices;
00033     UpdateStartStopButtons();
00034 }
00035
00036 void DeviceConnect::deviceConnectStart_Click(Object^ sender, RoutedEventArgs^ e)
00037 {
00038     // The DeviceWatcher is in the DeviceList class.
00039     DeviceList::Current->StartFx2Watcher();
00040     UpdateStartStopButtons();
00041 }
00042
00043
00044 void DeviceConnect::deviceConnectStop_Click(Object^ sender, RoutedEventArgs^ e)
00045 {
00046     DeviceList::Current->StopFx2Watcher();
00047     UpdateStartStopButtons();
00048 }
00049
00050 void DeviceConnect::deviceConnectDevices_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00051 {
00052     auto entry = safe_cast<DeviceListEntry^>(deviceConnectDevices->SelectedItem);
00053
00054     String^ currentlySelectedId = DeviceList::Current->GetSelectedDeviceId();
00055     String^ newlySelectedId = entry ? entry->Id : nullptr;
00056
00057     if (currentlySelectedId != nullptr)
00058     {
00059         CloseFx2Device();
00060     }
00061
00062     if (newlySelectedId != nullptr)
00063     {
00064         OpenFx2DeviceAsync(newlySelectedId);
00065     }
00066 }
00067
00068 void DeviceConnect::UpdateStartStopButtons()
00069 {
00070     this->deviceConnectStart->IsEnabled = !DeviceList::Current->WatcherStarted;
00071     this->deviceConnectStop->IsEnabled = DeviceList::Current->WatcherStarted;
00072 }
00073
00074 task<void> DeviceConnect::OpenFx2DeviceAsync(String^ id)
00075 {
00076     return
00077         create_task(CustomDevice::FromIdAsync(id, DeviceAccessMode::ReadWrite, DeviceSharingMode::Exclusive)).
00078         then([this, id](task<CustomDevice^> result)
00079     {
00080         try
00081         {
00082             CustomDevice^ device = result.get();
00083
00084             DeviceList::Current->SetSelectedDevice(id, device);
00085
00086             rootPage->NotifyUser("Fx2 " + id + " opened", NotifyType::StatusMessage);
00087         }
00088         catch (Exception^ ex)
00089         {
00090             rootPage->NotifyUser("Error opening Fx2 device @" + id + ": " + ex->Message, NotifyType::ErrorMessage);
00091         }
00092     });
00093 }
00094
00095 void DeviceConnect::CloseFx2Device()
00096 {
00097     if (DeviceList::Current->GetSelectedDevice() != nullptr)
00098     {
00099         rootPage->NotifyUser("Fx2 " + DeviceList::Current->GetSelectedDeviceId() + " closed", NotifyType::StatusMessage);
00100         DeviceList::Current->ClearSelectedDevice();
00101     }
00102 }
Generated on Fri Nov 15 2024 22:19:03 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFontImplementation/FontNameCollector.cpp Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFontImplementation

FontNameCollector.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "FontNameCollector.h"
00014 #include "DirectXHelper.h"
00015
00016 using namespace DWriteTextLayoutCloudFontImplementation;
00017 using namespace Microsoft::WRL;
00018
00019
00020 std::wstring FontNameCollector::GetFontNames()
00021 {
00022     std::wstring result;
00023     for (auto& name : m_uniqueFontNames)
00024     {
00025         if (!result.empty())
00026         {
00027             result += L", ";
00028         }
00029         result += name;
00030     }
00031
00032     return result;
00033 }
00034
00035
00036 void FontNameCollector::ClearNames()
00037 {
00038     // Clear any names to allow the collector to be re-used with a different layout.
00039     m_uniqueFontNames.clear();
00040 }
00041
00042
00043 // This is the one significant IDWriteTextRenderer method that will get
00044 // called and that we'll use to find out what fonts have been used in
00045 // the text layout.
00046 HRESULT STDMETHODCALLTYPE FontNameCollector::DrawGlyphRun(
00047     _In_opt_ void* clientDrawingContext,
00048     FLOAT baselineOriginX,
00049     FLOAT baselineOriginY,
00050     DWRITE_MEASURING_MODE measuringMode,
00051     _In_ DWRITE_GLYPH_RUN const* glyphRun,
00052     _In_ DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
00053     _In_opt_ IUnknown* clientDrawingEffect
00054     )
00055 {
00056     // Since this is a platform callback that doesn't expect exceptions,
00057     // we shouldn't leave any exceptions unhandled.
00058     try
00059     {
00060         // The glyph run has a font face, which is what we need to get the font
00061         // name for this run. Specifically, we want an IDWriteFontFace3 object.
00062
00063         ComPtr<IDWriteFontFace3> fontFace3;
00064         DX::ThrowIfFailed(glyphRun->fontFace->QueryInterface(fontFace3.GetAddressOf()));
00065
00066         ComPtr<IDWriteLocalizedStrings> familyNames;
00067         DX::ThrowIfFailed(fontFace3->GetFamilyNames(&familyNames));
00068
00069         // There may be family names in multiple languages, and in a different
00070         // situation we might want to look for a string that matches the app's UI
00071         // language (using Windows::Globalization::ApplicationLanguages::Languages).
00072         // For our purposes here, though, we know that the fonts used will have
00073         // family names for en-US, and that's sufficient since that's what we used
00074         // when we created the text format used in the layout.
00075
00076         UINT32 nameStringIndex = 0;
00077         BOOL exists = false;
00078         DX::ThrowIfFailed(familyNames->FindLocaleName(L"en-US", &nameStringIndex, &exists));
00079
00080         // Given the fonts that will be used, exists should always be true. If for
00081         // some reason it's false, nameStringIndex will be UINT32_MAX. We want to
00082         // make sure it's 0: If there's no en-US string, we'll just used the first
00083         // string.)
00084         if (!exists)
00085         {
00086             nameStringIndex = 0;
00087         }
00088
00089         // Need a buffer to get the string.
00090         std::wstring fontName;
00091         UINT32 length = 0;
00092         DX::ThrowIfFailed(familyNames->GetStringLength(nameStringIndex, &length));
00093         fontName.resize(length);
00094
00095         // Now get the name and add to the set of names.
00096         DX::ThrowIfFailed(familyNames->GetString(nameStringIndex, &fontName[0], length + 1));
00097         m_uniqueFontNames.insert(fontName);
00098
00099         return S_OK;
00100     }
00101     catch (Platform::Exception^ e)
00102     {
00103         return e->HResult;
00104     }
00105     catch (const std::bad_alloc&)
00106     {
00107         return E_OUTOFMEMORY;
00108     }
00109     catch (...)
00110     {
00111         return E_FAIL;
00112     }
00113 }
00114
00115
00116 // IDWritePixelSnapping methods won't actually get used in this sample
00117 // and require only simple implementations:
00118
00119 HRESULT STDMETHODCALLTYPE FontNameCollector::GetCurrentTransform(
00120     _In_opt_ void* clientDrawingContext,
00121     _Out_ DWRITE_MATRIX* transform
00122     )
00123 {
00124     static const DWRITE_MATRIX identity = {
00125         1.0f, 0.0f,
00126         0.0f, 1.0f,
00127         0.0f, 0.0f
00128         };
00129     *transform = identity;
00130     return S_OK;
00131 }
00132
00133
00134 HRESULT STDMETHODCALLTYPE FontNameCollector::GetPixelsPerDip(
00135     _In_opt_ void* clientDrawingContext,
00136     _Out_ FLOAT* pixelsPerDip
00137     )
00138 {
00139     *pixelsPerDip = 1.0f;
00140     return S_OK;
00141 }
00142
00143
00144 HRESULT STDMETHODCALLTYPE FontNameCollector::IsPixelSnappingDisabled(
00145     _In_opt_ void* clientDrawingContext,
00146     _Out_ BOOL* isDisabled
00147     )
00148 {
00149     *isDisabled = false;
00150     return S_OK;
00151 }
00152
00153
00154 // IUnknown methods will be used and require implementations:
00155
00156 HRESULT STDMETHODCALLTYPE FontNameCollector::QueryInterface(
00157     REFIID riid,
00158     _COM_Outptr_ void **obj
00159     )
00160 {
00161     *obj = nullptr;
00162     if (riid == __uuidof(IDWriteTextRenderer) || riid == __uuidof(IDWritePixelSnapping) || riid == __uuidof(IUnknown))
00163     {
00164         AddRef();
00165         *obj = this;
00166         return S_OK;
00167     }
00168     return E_NOINTERFACE;
00169 }
00170
00171
00172 ULONG STDMETHODCALLTYPE FontNameCollector::AddRef()
00173 {
00174     return InterlockedIncrement(&m_refCount);
00175 }
00176
00177 ULONG STDMETHODCALLTYPE FontNameCollector::Release()
00178 {
00179     uint32 newCount = InterlockedDecrement(&m_refCount);
00180     if (newCount == 0)
00181         delete this;
00182     return newCount;
00183 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BackgroundTaskInformation Member List

This is the complete list of members for BackgroundTaskInformation, including all inherited members.
TaskCanceled | BackgroundTaskInformation
TaskCompleted | BackgroundTaskInformation
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/pch.h Source File

  • ComplexInk
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009 #include <wrl.h>
00010 #include <wrl/client.h>
00011 #include <d3d11_2.h>
00012 #include <d2d1_2.h>
00013 #include <d2d1effects_1.h>
00014 #include <dwrite_2.h>
00015 #include <wincodec.h>
00016 #include <DirectXColors.h>
00017 #include <DirectXMath.h>
00018 #include <memory>
00019 #include <agile.h>
00020 #include <concrt.h>
00021
00022
00023 #include "App.xaml.h"
00024 #include <dxgi.h>
00025 #include <dxgi1_2.h>
00026 #include <d2d1_1.h>
00027 #include <d3d11.h>
00028 #include <d2d1.h>
00029 #include <vector>
00030 #include <debugapi.h>
00031 #include <d3d11_1.h>
00032 #include <dwrite.h>
00033 #include "windows.ui.xaml.media.dxinterop.h"
00034
00035 const Windows::UI::Color CanvasBackgroundColor = Windows::UI::Colors::CornflowerBlue;
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/_360VideoPlaybackMain.cs Source File

  • 360VideoPlayback
  • cs

_360VideoPlaybackMain.cs

Go to the documentation of this file.
00001 ﻿//
00002 // Comment out this preprocessor definition to disable all of the
00003 // sample content.
00004 //
00005 // To remove the content after disabling it:
00006 //     * Remove the unused code from this file.
00007 //     * Delete the Content folder provided with this template.
00008 //
00009 #define DRAW_SAMPLE_CONTENT
00010
00011 using System;
00012 using System.Numerics;
00013 using System.Diagnostics;
00014 using Windows.Graphics.Holographic;
00015 using Windows.Perception.Spatial;
00016 using Windows.UI.Input.Spatial;
00017
00018 using _360VideoPlayback.Common;
00019 using System.Threading.Tasks;
00020 using Windows.Foundation;
00021 using System.Collections.Generic;
00022
00023 #if DRAW_SAMPLE_CONTENT
00024 using _360VideoPlayback.Content;
00025 #endif
00026
00027 namespace _360VideoPlayback
00028 {
00029     /// <summary>
00030     /// Updates, renders, and presents holographic content using Direct3D.
00031     /// </summary>
00032     internal class _360VideoPlaybackMain : IDisposable
00033     {
00034
00035 #if DRAW_SAMPLE_CONTENT
00036         // Renders a SPherical Video Playback . This sample content
00037         // is used to demonstrate world-locked rendering.
00038         private VideoRenderer videoRenderer;
00039
00040         private SpatialInputHandler spatialInputHandler;
00041 #endif
00042
00043         // Cached reference to device resources.
00044         private DeviceResources deviceResources;
00045
00046         // Render loop timer.
00047         private StepTimer timer = new StepTimer();
00048
00049         // Represents the holographic space around the user.
00050         HolographicSpace holographicSpace;
00051
00052         // SpatialLocator that is attached to the primary camera.
00053         SpatialLocator locator;
00054
00055         // A reference frame attached to the holographic camera.
00056         SpatialLocatorAttachedFrameOfReference attachreferenceFrame;
00057
00058         /// <summary>
00059         /// Loads and initializes application assets when the application is loaded.
00060         /// </summary>
00061         /// <param name="deviceResources"></param>
00062         public _360VideoPlaybackMain(DeviceResources deviceResources)
00063         {
00064             this.deviceResources = deviceResources;
00065
00066             // Register to be notified if the Direct3D device is lost.
00067             this.deviceResources.DeviceLost += this.OnDeviceLost;
00068             this.deviceResources.DeviceRestored += this.OnDeviceRestored;
00069         }
00070
00071         public void SetHolographicSpace(HolographicSpace holographicSpace)
00072         {
00073             this.holographicSpace = holographicSpace;
00074
00075             //
00076             // TODO: Add code here to initialize your content.
00077             //
00078
00079 #if DRAW_SAMPLE_CONTENT
00080             // Initialize the sample hologram.
00081             videoRenderer = new VideoRenderer(deviceResources);
00082
00083             spatialInputHandler = new SpatialInputHandler();
00084 #endif
00085
00086             // Use the default SpatialLocator to track the motion of the device.
00087             locator = SpatialLocator.GetDefault();
00088
00089             // Be able to respond to changes in the positional tracking state.
00090             locator.LocatabilityChanged += this.OnLocatabilityChanged;
00091
00092             // Respond to camera added events by creating any resources that are specific
00093             // to that camera, such as the back buffer render target view.
00094             // When we add an event handler for CameraAdded, the API layer will avoid putting
00095             // the new camera in new HolographicFrames until we complete the deferral we created
00096             // for that handler, or return from the handler without creating a deferral. This
00097             // allows the app to take more than one frame to finish creating resources and
00098             // loading assets for the new holographic camera.
00099             // This function should be registered before the app creates any HolographicFrames.
00100             holographicSpace.CameraAdded += this.OnCameraAdded;
00101
00102             // Respond to camera removed events by releasing resources that were created for that
00103             // camera.
00104             // When the app receives a CameraRemoved event, it releases all references to the back
00105             // buffer right away. This includes render target views, Direct2D target bitmaps, and so on.
00106             // The app must also ensure that the back buffer is not attached as a render target, as
00107             // shown in DeviceResources.ReleaseResourcesForBackBuffer.
00108             holographicSpace.CameraRemoved += this.OnCameraRemoved;
00109
00110             // The simplest way to render video Frame is to create a stationary reference frame
00111             // when the app is launched. This is roughly analogous to creating a "world" coordinate system
00112             // with the origin placed at the device's position as the app is launched.
00113             attachreferenceFrame = locator.CreateAttachedFrameOfReferenceAtCurrentHeading();
00114
00115             // Notes on spatial tracking APIs:
00116             // * Stationary reference frames are designed to provide a best-fit position relative to the
00117             //   overall space. Individual positions within that reference frame are allowed to drift slightly
00118             //   as the device learns more about the environment.
00119             // * When precise placement of individual holograms is required, a SpatialAnchor should be used to
00120             //   anchor the individual hologram to a position in the real world - for example, a point the user
00121             //   indicates to be of special interest. Anchor positions do not drift, but can be corrected; the
00122             //   anchor will use the corrected position starting in the next frame after the correction has
00123             //   occurred.
00124         }
00125
00126         public void Dispose()
00127         {
00128 #if DRAW_SAMPLE_CONTENT
00129             if (videoRenderer != null)
00130             {
00131                 videoRenderer.ReleaseDeviceDependentResources();
00132                 videoRenderer.Dispose();
00133                 videoRenderer = null;
00134             }
00135 #endif
00136         }
00137
00138         /// <summary>
00139         /// Updates the application state once per frame.
00140         /// </summary>
00141         public HolographicFrame Update()
00142         {
00143             // Before doing the timer update, there is some work to do per-frame
00144             // to maintain holographic rendering. First, we will get information
00145             // about the current frame.
00146
00147             // The HolographicFrame has information that the app needs in order
00148             // to update and render the current frame. The app begins each new
00149             // frame by calling CreateNextFrame.
00150             HolographicFrame holographicFrame = holographicSpace.CreateNextFrame();
00151
00152             // Get a prediction of where holographic cameras will be when this frame
00153             // is presented.
00154             HolographicFramePrediction prediction = holographicFrame.CurrentPrediction;
00155
00156             // Back buffers can change from frame to frame. Validate each buffer, and recreate
00157             // resource views and depth buffers as needed.
00158             deviceResources.EnsureCameraResources(holographicFrame, prediction);
00159
00160             // Next, we get a coordinate system from the attached frame of reference that is
00161             // associated with the current frame. Later, this coordinate system is used for
00162             // for creating the stereo view matrices when rendering the sample content.
00163             SpatialCoordinateSystem currentCoordinateSystem = attachreferenceFrame.GetStationaryCoordinateSystemAtTimestamp(prediction.Timestamp);//referenceFrame.CoordinateSystem;
00164
00165             timer.Tick(() =>
00166             {
00167                 //
00168                 // TODO: Update scene objects.
00169                 //
00170                 // Put time-based updates here. By default this code will run once per frame,
00171                 // but if you change the StepTimer to use a fixed time step this code will
00172                 // run as many times as needed to get to the current step.
00173                 //
00174
00175 #if DRAW_SAMPLE_CONTENT
00176                 videoRenderer.Update(timer);
00177 #endif
00178             });
00179
00180             // We complete the frame update by using information about our content positioning
00181             // to set the focus point.
00182             foreach (var cameraPose in prediction.CameraPoses)
00183             {
00184 #if DRAW_SAMPLE_CONTENT
00185                 // The HolographicCameraRenderingParameters class provides access to set
00186                 // the image stabilization parameters.
00187                 HolographicCameraRenderingParameters renderingParameters = holographicFrame.GetRenderingParameters(cameraPose);
00188
00189                 // SetFocusPoint informs the system about a specific point in your scene to
00190                 // prioritize for image stabilization. The focus point is set independently
00191                 // for each holographic camera.
00192                 // You should set the focus point near the content that the user is looking at.
00193                 // In this example, we put the focus point at the center of the sample hologram,
00194                 // since that is the only hologram available for the user to focus on.
00195                 // You can also set the relative velocity and facing of that content; the sample
00196                 // hologram is at a fixed point so we only need to indicate its position.
00197                 Vector3 position = new Vector3(0.0f, 0.0f, 0.0f);
00198                 renderingParameters.SetFocusPoint(
00199                 currentCoordinateSystem, position
00200                 );
00201 #endif
00202             }
00203
00204             // The holographic frame will be used to get up-to-date view and projection matrices and
00205             // to present the swap chain.
00206             return holographicFrame;
00207         }
00208
00209         /// <summary>
00210         /// Renders the current frame to each holographic display, according to the
00211         /// current application and spatial positioning state. Returns true if the
00212         /// frame was rendered to at least one display.
00213         /// </summary>
00214         public bool Render(ref HolographicFrame holographicFrame)
00215         {
00216             // Don't try to render anything before the first Update.
00217             if (timer.FrameCount == 0)
00218             {
00219                 return false;
00220             }
00221
00222             // Up-to-date frame predictions enhance the effectiveness of image stablization and
00223             // allow more accurate positioning of holograms.
00224             holographicFrame.UpdateCurrentPrediction();
00225             HolographicFramePrediction prediction = holographicFrame.CurrentPrediction;
00226
00227             // Lock the set of holographic camera resources, then draw to each camera
00228             // in this frame.
00229             return deviceResources.UseHolographicCameraResources(
00230                 (Dictionary<uint, CameraResources> cameraResourceDictionary) =>
00231                 {
00232                     bool atLeastOneCameraRendered = false;
00233
00234                     foreach (var cameraPose in prediction.CameraPoses)
00235                     {
00236                         // This represents the device-based resources for a HolographicCamera.
00237                         CameraResources cameraResources = cameraResourceDictionary[cameraPose.HolographicCamera.Id];
00238
00239                         // Get the device context.
00240                         var context = deviceResources.D3DDeviceContext;
00241                         var renderTargetView = cameraResources.BackBufferRenderTargetView;
00242                         var depthStencilView = cameraResources.DepthStencilView;
00243
00244                         // Set render targets to the current holographic camera.
00245                         context.OutputMerger.SetRenderTargets(depthStencilView, renderTargetView);
00246
00247                         // Clear the back buffer and depth stencil view.
00248                         SharpDX.Mathematics.Interop.RawColor4 transparent = new SharpDX.Mathematics.Interop.RawColor4(0.0f, 0.0f, 0.0f, 0.0f);
00249                         context.ClearRenderTargetView(renderTargetView, transparent);
00250                         context.ClearDepthStencilView(
00251                             depthStencilView,
00252                             SharpDX.Direct3D11.DepthStencilClearFlags.Depth | SharpDX.Direct3D11.DepthStencilClearFlags.Stencil,
00253                             1.0f,
00254                             0);
00255
00256                         //
00257                         // TODO: Replace the sample content with your own content.
00258                         //
00259                         // Notes regarding holographic content:
00260                         //    * For drawing, remember that you have the potential to fill twice as many pixels
00261                         //      in a stereoscopic render target as compared to a non-stereoscopic render target
00262                         //      of the same resolution. Avoid unnecessary or repeated writes to the same pixel,
00263                         //      and only draw holograms that the user can see.
00264                         //    * To help occlude hologram geometry, you can create a depth map using geometry
00265                         //      data obtained via the surface mapping APIs. You can use this depth map to avoid
00266                         //      rendering holograms that are intended to be hidden behind tables, walls,
00267                         //      monitors, and so on.
00268                         //    * Black pixels will appear transparent to the user wearing the device, but you
00269                         //      should still use alpha blending to draw semitransparent holograms. You should
00270                         //      also clear the screen to Transparent as shown above.
00271                         //
00272
00273
00274                         // The view and projection matrices for each holographic camera will change
00275                         // every frame. This function refreshes the data in the constant buffer for
00276                         // the holographic camera indicated by cameraPose.
00277                         cameraResources.UpdateViewProjectionBuffer(deviceResources, cameraPose, attachreferenceFrame.GetStationaryCoordinateSystemAtTimestamp(prediction.Timestamp)/*referenceFrame.CoordinateSystem*/);
00278
00279                         // Attach the view/projection constant buffer for this camera to the graphics pipeline.
00280                         bool cameraActive = cameraResources.AttachViewProjectionBuffer(deviceResources);
00281
00282 #if DRAW_SAMPLE_CONTENT
00283                         // Only render world-locked content when positional tracking is active.
00284                         if (cameraActive)
00285                         {
00286                             // Draw the sample hologram.
00287                             videoRenderer.Render();
00288                         }
00289 #endif
00290                         atLeastOneCameraRendered = true;
00291                     }
00292
00293                     return atLeastOneCameraRendered;
00294                 });
00295         }
00296
00297         public void SaveAppState()
00298         {
00299             //
00300             // TODO: Insert code here to save your app state.
00301             //       This method is called when the app is about to suspend.
00302             //
00303             //       For example, store information in the SpatialAnchorStore.
00304             //
00305         }
00306
00307         public void LoadAppState()
00308         {
00309             //
00310             // TODO: Insert code here to load your app state.
00311             //       This method is called when the app resumes.
00312             //
00313             //       For example, load information from the SpatialAnchorStore.
00314             //
00315         }
00316
00317
00318         /// <summary>
00319         /// Notifies renderers that device resources need to be released.
00320         /// </summary>
00321         public void OnDeviceLost(Object sender, EventArgs e)
00322         {
00323
00324 #if DRAW_SAMPLE_CONTENT
00325             videoRenderer.ReleaseDeviceDependentResources();
00326 #endif
00327
00328         }
00329
00330         /// <summary>
00331         /// Notifies renderers that device resources may now be recreated.
00332         /// </summary>
00333         public void OnDeviceRestored(Object sender, EventArgs e)
00334         {
00335 #if DRAW_SAMPLE_CONTENT
00336             videoRenderer.CreateDeviceDependentResourcesAsync();
00337 #endif
00338         }
00339
00340         void OnLocatabilityChanged(SpatialLocator sender, Object args)
00341         {
00342             switch (sender.Locatability)
00343             {
00344                 case SpatialLocatability.Unavailable:
00345                     // Holograms cannot be rendered.
00346                     {
00347                         String message = "Warning! Positional tracking is " + sender.Locatability + ".";
00348                         Debug.WriteLine(message);
00349                     }
00350                     break;
00351
00352                 // In the following three cases, it is still possible to place holograms using a
00353                 // SpatialLocatorAttachedFrameOfReference.
00354                 case SpatialLocatability.PositionalTrackingActivating:
00355                 // The system is preparing to use positional tracking.
00356
00357                 case SpatialLocatability.OrientationOnly:
00358                 // Positional tracking has not been activated.
00359
00360                 case SpatialLocatability.PositionalTrackingInhibited:
00361                     // Positional tracking is temporarily inhibited. User action may be required
00362                     // in order to restore positional tracking.
00363                     break;
00364
00365                 case SpatialLocatability.PositionalTrackingActive:
00366                     // Positional tracking is active. World-locked content can be rendered.
00367                     break;
00368             }
00369         }
00370
00371         public void OnCameraAdded(
00372             HolographicSpace sender,
00373             HolographicSpaceCameraAddedEventArgs args
00374             )
00375         {
00376             Deferral deferral = args.GetDeferral();
00377             HolographicCamera holographicCamera = args.Camera;
00378
00379             Task task1 = new Task(() =>
00380             {
00381                 //
00382                 // TODO: Allocate resources for the new camera and load any content specific to
00383                 //       that camera. Note that the render target size (in pixels) is a property
00384                 //       of the HolographicCamera object, and can be used to create off-screen
00385                 //       render targets that match the resolution of the HolographicCamera.
00386                 //
00387
00388                 // Create device-based resources for the holographic camera and add it to the list of
00389                 // cameras used for updates and rendering. Notes:
00390                 //   * Since this function may be called at any time, the AddHolographicCamera function
00391                 //     waits until it can get a lock on the set of holographic camera resources before
00392                 //     adding the new camera. At 60 frames per second this wait should not take long.
00393                 //   * A subsequent Update will take the back buffer from the RenderingParameters of this
00394                 //     camera's CameraPose and use it to create the ID3D11RenderTargetView for this camera.
00395                 //     Content can then be rendered for the HolographicCamera.
00396                 deviceResources.AddHolographicCamera(holographicCamera);
00397
00398                 // Holographic frame predictions will not include any information about this camera until
00399                 // the deferral is completed.
00400                 deferral.Complete();
00401             });
00402             task1.Start();
00403         }
00404
00405         public void OnCameraRemoved(
00406             HolographicSpace sender,
00407             HolographicSpaceCameraRemovedEventArgs args
00408             )
00409         {
00410             Task task2 = new Task(() =>
00411             {
00412                 //
00413                 // TODO: Asynchronously unload or deactivate content resources (not back buffer
00414                 //       resources) that are specific only to the camera that was removed.
00415                 //
00416             });
00417             task2.Start();
00418
00419             // Before letting this callback return, ensure that all references to the back buffer
00420             // are released.
00421             // Since this function may be called at any time, the RemoveHolographicCamera function
00422             // waits until it can get a lock on the set of holographic camera resources before
00423             // deallocating resources for this camera. At 60 frames per second this wait should
00424             // not take long.
00425             deviceResources.RemoveHolographicCamera(args.Camera);
00426         }
00427         public void CreateVideoShaders()
00428         {
00429             videoRenderer.CreateDeviceDependentResourcesAsync();
00430         }
00431     }
00432 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/Content/SpinningCubeRenderer.cpp Source File

  • BasicHologram
  • cpp
  • Content

SpinningCubeRenderer.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "SpinningCubeRenderer.h"
00003 #include "Common\DirectXHelper.h"
00004
00005 using namespace BasicHologram;
00006 using namespace Concurrency;
00007 using namespace DirectX;
00008 using namespace Windows::Foundation::Numerics;
00009 using namespace Windows::UI::Input::Spatial;
00010
00011 // Loads vertex and pixel shaders from files and instantiates the cube geometry.
00012 SpinningCubeRenderer::SpinningCubeRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00013     m_deviceResources(deviceResources)
00014 {
00015     CreateDeviceDependentResources();
00016 }
00017
00018 // This function uses a SpatialPointerPose to position the world-locked hologram
00019 // two meters in front of the user's heading.
00020 void SpinningCubeRenderer::PositionHologram(SpatialPointerPose^ pointerPose)
00021 {
00022     if (pointerPose != nullptr)
00023     {
00024         // Get the gaze direction relative to the given coordinate system.
00025         const float3 headPosition    = pointerPose->Head->Position;
00026         const float3 headDirection   = pointerPose->Head->ForwardDirection;
00027
00028         // The hologram is positioned two meters along the user's gaze direction.
00029         constexpr float distanceFromUser    = 2.0f; // meters
00030         const float3 gazeAtTwoMeters        = headPosition + (distanceFromUser * headDirection);
00031
00032         // This will be used as the translation component of the hologram's
00033         // model transform.
00034         SetPosition(gazeAtTwoMeters);
00035     }
00036 }
00037
00038 // Called once per frame. Rotates the cube, and calculates and sets the model matrix
00039 // relative to the position transform indicated by hologramPositionTransform.
00040 void SpinningCubeRenderer::Update(const DX::StepTimer& timer)
00041 {
00042     // Rotate the cube.
00043     // Convert degrees to radians, then convert seconds to rotation angle.
00044     const float    radiansPerSecond = XMConvertToRadians(m_degreesPerSecond);
00045     const double   totalRotation    = timer.GetTotalSeconds() * radiansPerSecond;
00046     const float    radians          = static_cast<float>(fmod(totalRotation, XM_2PI));
00047     const XMMATRIX modelRotation    = XMMatrixRotationY(-radians);
00048
00049     // Position the cube.
00050     const XMMATRIX modelTranslation = XMMatrixTranslationFromVector(XMLoadFloat3(&m_position));
00051
00052     // Multiply to get the transform matrix.
00053     // Note that this transform does not enforce a particular coordinate system. The calling
00054     // class is responsible for rendering this content in a consistent manner.
00055     const XMMATRIX modelTransform   = XMMatrixMultiply(modelRotation, modelTranslation);
00056
00057     // The view and projection matrices are provided by the system; they are associated
00058     // with holographic cameras, and updated on a per-camera basis.
00059     // Here, we provide the model transform for the sample hologram. The model transform
00060     // matrix is transposed to prepare it for the shader.
00061     XMStoreFloat4x4(&m_modelConstantBufferData.model, XMMatrixTranspose(modelTransform));
00062
00063     // Loading is asynchronous. Resources must be created before they can be updated.
00064     if (!m_loadingComplete)
00065     {
00066         return;
00067     }
00068
00069     // Use the D3D device context to update Direct3D device-based resources.
00070     const auto context = m_deviceResources->GetD3DDeviceContext();
00071
00072     // Update the model transform buffer for the hologram.
00073     context->UpdateSubresource(
00074         m_modelConstantBuffer.Get(),
00075         0,
00076         nullptr,
00077         &m_modelConstantBufferData,
00078         0,
00079         0
00080         );
00081 }
00082
00083 // Renders one frame using the vertex and pixel shaders.
00084 // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00085 // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00086 // a pass-through geometry shader is also used to set the render
00087 // target array index.
00088 void SpinningCubeRenderer::Render()
00089 {
00090     // Loading is asynchronous. Resources must be created before drawing can occur.
00091     if (!m_loadingComplete)
00092     {
00093         return;
00094     }
00095
00096     const auto context = m_deviceResources->GetD3DDeviceContext();
00097
00098     // Each vertex is one instance of the VertexPositionColor struct.
00099     const UINT stride = sizeof(VertexPositionColor);
00100     const UINT offset = 0;
00101     context->IASetVertexBuffers(
00102         0,
00103         1,
00104         m_vertexBuffer.GetAddressOf(),
00105         &stride,
00106         &offset
00107         );
00108     context->IASetIndexBuffer(
00109         m_indexBuffer.Get(),
00110         DXGI_FORMAT_R16_UINT, // Each index is one 16-bit unsigned integer (short).
00111         0
00112         );
00113     context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00114     context->IASetInputLayout(m_inputLayout.Get());
00115
00116     // Attach the vertex shader.
00117     context->VSSetShader(
00118         m_vertexShader.Get(),
00119         nullptr,
00120         0
00121         );
00122     // Apply the model constant buffer to the vertex shader.
00123     context->VSSetConstantBuffers(
00124         0,
00125         1,
00126         m_modelConstantBuffer.GetAddressOf()
00127         );
00128
00129     if (!m_usingVprtShaders)
00130     {
00131         // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00132         // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00133         // a pass-through geometry shader is used to set the render target
00134         // array index.
00135         context->GSSetShader(
00136             m_geometryShader.Get(),
00137             nullptr,
00138             0
00139             );
00140     }
00141
00142     // Attach the pixel shader.
00143     context->PSSetShader(
00144         m_pixelShader.Get(),
00145         nullptr,
00146         0
00147         );
00148
00149     // Draw the objects.
00150     context->DrawIndexedInstanced(
00151         m_indexCount,   // Index count per instance.
00152         2,              // Instance count.
00153         0,              // Start index location.
00154         0,              // Base vertex location.
00155         0               // Start instance location.
00156         );
00157 }
00158
00159 void SpinningCubeRenderer::CreateDeviceDependentResources()
00160 {
00161     m_usingVprtShaders = m_deviceResources->GetDeviceSupportsVprt();
00162
00163     // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3::
00164     // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature
00165     // we can avoid using a pass-through geometry shader to set the render
00166     // target array index, thus avoiding any overhead that would be
00167     // incurred by setting the geometry shader stage.
00168     std::wstring vertexShaderFileName = m_usingVprtShaders ? L"ms-appx:///VprtVertexShader.cso" : L"ms-appx:///VertexShader.cso";
00169
00170     // Load shaders asynchronously.
00171     task<std::vector<byte>> loadVSTask = DX::ReadDataAsync(vertexShaderFileName);
00172     task<std::vector<byte>> loadPSTask = DX::ReadDataAsync(L"ms-appx:///PixelShader.cso");
00173
00174     task<std::vector<byte>> loadGSTask;
00175     if (!m_usingVprtShaders)
00176     {
00177         // Load the pass-through geometry shader.
00178         loadGSTask = DX::ReadDataAsync(L"ms-appx:///GeometryShader.cso");
00179     }
00180
00181     // After the vertex shader file is loaded, create the shader and input layout.
00182     task<void> createVSTask = loadVSTask.then([this] (const std::vector<byte>& fileData)
00183     {
00184         DX::ThrowIfFailed(
00185             m_deviceResources->GetD3DDevice()->CreateVertexShader(
00186                 fileData.data(),
00187                 fileData.size(),
00188                 nullptr,
00189                 &m_vertexShader
00190                 )
00191             );
00192
00193         constexpr std::array<D3D11_INPUT_ELEMENT_DESC, 2> vertexDesc =
00194         {{
00195             { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00196             { "COLOR",    0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00197         }};
00198
00199         DX::ThrowIfFailed(
00200             m_deviceResources->GetD3DDevice()->CreateInputLayout(
00201                 vertexDesc.data(),
00202                 static_cast<UINT>(vertexDesc.size()),
00203                 fileData.data(),
00204                 static_cast<UINT>(fileData.size()),
00205                 &m_inputLayout
00206                 )
00207             );
00208     });
00209
00210     // After the pixel shader file is loaded, create the shader and constant buffer.
00211     task<void> createPSTask = loadPSTask.then([this] (const std::vector<byte>& fileData)
00212     {
00213         DX::ThrowIfFailed(
00214             m_deviceResources->GetD3DDevice()->CreatePixelShader(
00215                 fileData.data(),
00216                 fileData.size(),
00217                 nullptr,
00218                 &m_pixelShader
00219                 )
00220             );
00221
00222         const CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00223         DX::ThrowIfFailed(
00224             m_deviceResources->GetD3DDevice()->CreateBuffer(
00225                 &constantBufferDesc,
00226                 nullptr,
00227                 &m_modelConstantBuffer
00228                 )
00229             );
00230     });
00231
00232     task<void> createGSTask;
00233     if (!m_usingVprtShaders)
00234     {
00235         // After the pass-through geometry shader file is loaded, create the shader.
00236         createGSTask = loadGSTask.then([this] (const std::vector<byte>& fileData)
00237         {
00238             DX::ThrowIfFailed(
00239                 m_deviceResources->GetD3DDevice()->CreateGeometryShader(
00240                     fileData.data(),
00241                     fileData.size(),
00242                     nullptr,
00243                     &m_geometryShader
00244                     )
00245                 );
00246         });
00247     }
00248
00249     // Once all shaders are loaded, create the mesh.
00250     task<void> shaderTaskGroup = m_usingVprtShaders ? (createPSTask && createVSTask) : (createPSTask && createVSTask && createGSTask);
00251     task<void> createCubeTask  = shaderTaskGroup.then([this] ()
00252     {
00253         // Load mesh vertices. Each vertex has a position and a color.
00254         // Note that the cube size has changed from the default DirectX app
00255         // template. Windows Holographic is scaled in meters, so to draw the
00256         // cube at a comfortable size we made the cube width 0.2 m (20 cm).
00257         static const std::array<VertexPositionColor, 8> cubeVertices =
00258         {{
00259             { XMFLOAT3(-0.1f, -0.1f, -0.1f), XMFLOAT3(0.0f, 0.0f, 0.0f) },
00260             { XMFLOAT3(-0.1f, -0.1f,  0.1f), XMFLOAT3(0.0f, 0.0f, 1.0f) },
00261             { XMFLOAT3(-0.1f,  0.1f, -0.1f), XMFLOAT3(0.0f, 1.0f, 0.0f) },
00262             { XMFLOAT3(-0.1f,  0.1f,  0.1f), XMFLOAT3(0.0f, 1.0f, 1.0f) },
00263             { XMFLOAT3( 0.1f, -0.1f, -0.1f), XMFLOAT3(1.0f, 0.0f, 0.0f) },
00264             { XMFLOAT3( 0.1f, -0.1f,  0.1f), XMFLOAT3(1.0f, 0.0f, 1.0f) },
00265             { XMFLOAT3( 0.1f,  0.1f, -0.1f), XMFLOAT3(1.0f, 1.0f, 0.0f) },
00266             { XMFLOAT3( 0.1f,  0.1f,  0.1f), XMFLOAT3(1.0f, 1.0f, 1.0f) },
00267         }};
00268
00269         D3D11_SUBRESOURCE_DATA vertexBufferData = {0};
00270         vertexBufferData.pSysMem                = cubeVertices.data();
00271         vertexBufferData.SysMemPitch            = 0;
00272         vertexBufferData.SysMemSlicePitch       = 0;
00273         const CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(VertexPositionColor) * static_cast<UINT>(cubeVertices.size()), D3D11_BIND_VERTEX_BUFFER);
00274         DX::ThrowIfFailed(
00275             m_deviceResources->GetD3DDevice()->CreateBuffer(
00276                 &vertexBufferDesc,
00277                 &vertexBufferData,
00278                 &m_vertexBuffer
00279                 )
00280             );
00281
00282         // Load mesh indices. Each trio of indices represents
00283         // a triangle to be rendered on the screen.
00284         // For example: 2,1,0 means that the vertices with indexes
00285         // 2, 1, and 0 from the vertex buffer compose the
00286         // first triangle of this mesh.
00287         // Note that the winding order is clockwise by default.
00288         constexpr std::array<unsigned short, 36> cubeIndices =
00289         {{
00290             2,1,0, // -x
00291             2,3,1,
00292
00293             6,4,5, // +x
00294             6,5,7,
00295
00296             0,1,5, // -y
00297             0,5,4,
00298
00299             2,6,7, // +y
00300             2,7,3,
00301
00302             0,4,6, // -z
00303             0,6,2,
00304
00305             1,3,7, // +z
00306             1,7,5,
00307         }};
00308
00309         m_indexCount = static_cast<unsigned int>(cubeIndices.size());
00310
00311         D3D11_SUBRESOURCE_DATA indexBufferData  = {0};
00312         indexBufferData.pSysMem                 = cubeIndices.data();
00313         indexBufferData.SysMemPitch             = 0;
00314         indexBufferData.SysMemSlicePitch        = 0;
00315         CD3D11_BUFFER_DESC indexBufferDesc(sizeof(unsigned short) * static_cast<UINT>(cubeIndices.size()), D3D11_BIND_INDEX_BUFFER);
00316         DX::ThrowIfFailed(
00317         m_deviceResources->GetD3DDevice()->CreateBuffer(
00318                 &indexBufferDesc,
00319                 &indexBufferData,
00320                 &m_indexBuffer
00321                 )
00322             );
00323     });
00324
00325     // Once the cube is loaded, the object is ready to be rendered.
00326     createCubeTask.then([this] ()
00327     {
00328         m_loadingComplete = true;
00329     });
00330 }
00331
00332 void SpinningCubeRenderer::ReleaseDeviceDependentResources()
00333 {
00334     m_loadingComplete  = false;
00335     m_usingVprtShaders = false;
00336     m_vertexShader.Reset();
00337     m_inputLayout.Reset();
00338     m_pixelShader.Reset();
00339     m_geometryShader.Reset();
00340     m_modelConstantBuffer.Reset();
00341     m_vertexBuffer.Reset();
00342     m_indexBuffer.Reset();
00343 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TitleBar/cpp/CustomTitleBar.xaml.h Source File

  • TitleBar
  • cpp

CustomTitleBar.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // CustomTitleBar.xaml.h
00003 // Declaration of the CustomTitleBar class
00004 //
00005
00006 #pragma once
00007
00008 #include "CustomTitleBar.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     // The CustomTitleBar class derives from DependencyObject, which has UI thread affinity.
00013     // Therefore, it is okay to keep a reference to a non-marshalable object in a member variable.
00014 #pragma warning(push)
00015 #pragma warning(disable:4451)
00016
00017     [Windows::Foundation::Metadata::WebHostHidden]
00018     public ref class CustomTitleBar sealed : public Windows::UI::Xaml::Data::INotifyPropertyChanged
00019     {
00020     public:
00021         CustomTitleBar();
00022
00023 #pragma region Data binding
00024         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
00025
00026         // The SystemOverlayLeftInset and SystemOverlayRightInset values are
00027         // in terms of physical left and right. Our OverlayLogicalLeftInset and
00028         // OverlayLogicalRightInset properties flip the values if the flow direction
00029         // is RTL.
00030         property Windows::UI::Xaml::Thickness CoreTitleBarPadding
00031         {
00032             Windows::UI::Xaml::Thickness get()
00033             {
00034                 // The SystemOverlayLeftInset and SystemOverlayRightInset values are
00035                 // in terms of physical left and right. Therefore, we need to flip
00036                 // then when our flow direction is RTL.
00037                 if (FlowDirection == Windows::UI::Xaml::FlowDirection::LeftToRight)
00038                 {
00039                     return Windows::UI::Xaml::ThicknessHelper::FromLengths(coreTitleBar->SystemOverlayLeftInset, 0, coreTitleBar->SystemOverlayRightInset, 0);
00040                 }
00041                 else
00042                 {
00043                     return Windows::UI::Xaml::ThicknessHelper::FromLengths(coreTitleBar->SystemOverlayRightInset, 0, coreTitleBar->SystemOverlayLeftInset, 0);
00044                 }
00045             }
00046         }
00047
00048         property double CoreTitleBarHeight
00049         {
00050             double get()
00051             {
00052                 return coreTitleBar->Height;
00053             }
00054         }
00055
00056 #pragma endregion
00057
00058         Windows::UI::Xaml::UIElement^ SetPageContent(Windows::UI::Xaml::UIElement^ newContent);
00059         void EnableControlsInTitleBar(bool enable);
00060
00061     private:
00062         void CustomTitleBar_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
00063         void CustomTitleBar_Unloaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
00064         void OnLayoutMetricsChanged(Windows::ApplicationModel::Core::CoreApplicationViewTitleBar^ sender, Platform::Object^ args);
00065         void OnIsVisibleChanged(Windows::ApplicationModel::Core::CoreApplicationViewTitleBar^ sender, Platform::Object^ args);
00066         void OnWindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args);
00067         void UpdateLayoutMetrics();
00068         void UpdatePositionAndVisibility();
00069
00070     private:
00071         Windows::ApplicationModel::Core::CoreApplicationViewTitleBar^ coreTitleBar = Windows::ApplicationModel::Core::CoreApplication::GetCurrentView()->TitleBar;
00072         Windows::UI::Xaml::UIElement^ pageContent = nullptr;
00073
00074         Windows::Foundation::EventRegistrationToken layoutMetricsChangedToken{};
00075         Windows::Foundation::EventRegistrationToken isVisibleChangedToken{};
00076         Windows::Foundation::EventRegistrationToken windowSizeChangedToken{};
00077
00078     };
00079 #pragma warning(pop)
00080 }
Generated on Fri Nov 15 2024 22:21:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProximitySensor/cpp/Tasks/pch.h Source File

  • ProximitySensor
  • cpp
  • Tasks

pch.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include <collection.h>
00004 #include <ppltasks.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPage.xaml.cs Source File

  • Notifications
  • cs
  • Notifications

ScenarioPage.xaml.cs

Go to the documentation of this file.
00001 ﻿using Notifications.Helpers;
00002 using Notifications.Model;
00003 using Windows.UI.ViewManagement;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Navigation;
00006
00007 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00008
00009 namespace Notifications
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     public sealed partial class ScenarioPage : BackButtonPage
00015     {
00016         public ScenarioPage()
00017         {
00018             this.InitializeComponent();
00019         }
00020
00021         protected override void OnNavigatedTo(NavigationEventArgs e)
00022         {
00023             Scenario = e.Parameter as Scenario;
00024
00025             if (!base.Frame.CanGoBack)
00026                 base.Frame.BackStack.Add(new PageStackEntry(typeof(MainPage), Scenario, null));
00027
00028             if (Scenario == null)
00029             {
00030                 base.Frame.GoBack();
00031                 return;
00032             }
00033
00034             // Handle keyboard showing up
00035             ApplicationView.GetForCurrentView().VisibleBoundsChanged += ScenarioTestPage_VisibleBoundsChanged;
00036
00037             base.OnNavigatedTo(e);
00038         }
00039
00040         protected override void OnNavigatedFrom(NavigationEventArgs e)
00041         {
00042             base.OnNavigatedFrom(e);
00043
00044             ApplicationView.GetForCurrentView().VisibleBoundsChanged -= ScenarioTestPage_VisibleBoundsChanged;
00045         }
00046
00047         private void ScenarioTestPage_VisibleBoundsChanged(ApplicationView sender, object args)
00048         {
00049             base.Width = sender.VisibleBounds.Width;
00050             base.Height = sender.VisibleBounds.Height;
00051         }
00052
00053         public static readonly DependencyProperty ScenarioProperty = DependencyProperty.Register("Scenario", typeof(Scenario), typeof(ScenarioPage), new PropertyMetadata(null));
00054
00055         public Scenario Scenario
00056         {
00057             get { return GetValue(ScenarioProperty) as Scenario; }
00058             set { SetValue(ScenarioProperty, value); }
00059         }
00060     }
00061 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GetData Member List

This is the complete list of members for GetData, including all inherited members.
ApduCommand(byte cla, byte ins, byte p1, byte p2, byte[] commandData, byte?le) | ApduCommand | [inline]
ApduResponseType | ApduCommand |
CLA | ApduCommand |
CommandData | ApduCommand |
GetBuffer() | ApduCommand | [inline]
GetData(GetDataDataType type) | GetData | [inline]
GetDataDataType enum name | GetData |
INS | ApduCommand |
Le | ApduCommand |
P1 | ApduCommand |
P2 | ApduCommand |
ToString() | ApduCommand | [inline]
Type | GetData |
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/BackgroundTask/Scenario6_GroupedTask.xaml.cpp Source File

  • BackgroundTask
  • cpp
  • BackgroundTask

Scenario6_GroupedTask.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario6_GroupedTask.xaml.cpp
00013 // Implementation of the GroupedBackgroundTask class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario6_GroupedTask.xaml.h"
00018 #include "SampleConfiguration.h"
00019
00020 using namespace SDKTemplate;
00021 using namespace concurrency;
00022 using namespace Windows::ApplicationModel::Background;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 GroupedBackgroundTask::GroupedBackgroundTask()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Invoked when this page is about to be displayed in a Frame.
00035 /// </summary>
00036 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037 /// property is typically used to configure the page.</param>
00038 void GroupedBackgroundTask::OnNavigatedTo(NavigationEventArgs^ e)
00039 {
00040     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00041     // as NotifyUser()
00042     rootPage = MainPage::Current;
00043
00044     group = BackgroundTaskSample::GetTaskGroup(BackgroundTaskGroupId, BackgroundTaskGroupFriendlyName);
00045
00046     //
00047     // Attach progress and completed handlers to any existing tasks.
00048     //
00049     for (auto pair : group->AllTasks)
00050     {
00051         auto task = pair->Value;
00052         if (task->Name == GroupedBackgroundTaskName)
00053         {
00054             BackgroundTaskSample::UpdateBackgroundTaskRegistrationStatus(task->Name, true);
00055             AttachProgressAndCompletedHandlers(task);
00056             break;
00057         }
00058     }
00059
00060     UpdateUI();
00061 }
00062
00063 /// <summary>
00064 /// Attach progress and completed handers to a background task.
00065 /// </summary>
00066 /// <param name="task">The task to attach progress and completed handlers to.</param>
00067 void GroupedBackgroundTask::AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration^ task)
00068 {
00069     task->Progress += ref new BackgroundTaskProgressEventHandler(this, &GroupedBackgroundTask::OnProgress);
00070     task->Completed += ref new BackgroundTaskCompletedEventHandler(this, &GroupedBackgroundTask::OnCompleted);
00071 }
00072
00073 /// <summary>
00074 /// Register a Grouped Background Task.
00075 /// </summary>
00076 /// <param name="sender"></param>
00077 /// <param name="e"></param>
00078 void GroupedBackgroundTask::RegisterGroupedBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00079 {
00080     auto task = BackgroundTaskSample::RegisterBackgroundTask(SampleBackgroundTaskEntryPoint,
00081         GroupedBackgroundTaskName,
00082         ref new SystemTrigger(SystemTriggerType::TimeZoneChange, false),
00083         nullptr,
00084         group);
00085     AttachProgressAndCompletedHandlers(task);
00086     UpdateUI();
00087 }
00088
00089 /// <summary>
00090 /// Unregister a Grouped Background Task.
00091 /// </summary>
00092 /// <param name="sender"></param>
00093 /// <param name="e"></param>
00094 void GroupedBackgroundTask::UnregisterGroupedTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00095 {
00096     BackgroundTaskSample::UnregisterBackgroundTasks(GroupedBackgroundTaskName, group);
00097     UpdateUI();
00098 }
00099
00100 /// <summary>
00101 /// Unregister all Background Tasks that are not grouped.
00102 /// </summary>
00103 /// <param name="sender"></param>
00104 /// <param name="e"></param>
00105 void GroupedBackgroundTask::UnregisterUngroupedTasks(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00106 {
00107     for (auto pair : BackgroundTaskRegistration::AllTasks)
00108     {
00109         auto task = pair->Value;
00110         task->Unregister(true);
00111         BackgroundTaskSample::UpdateBackgroundTaskRegistrationStatus(task->Name, false);
00112     }
00113 }
00114
00115 /// <summary>
00116 /// Handle background task progress.
00117 /// </summary>
00118 /// <param name="task">The task that is reporting progress.</param>
00119 /// <param name="args">Arguments of the progress report.</param>
00120 void GroupedBackgroundTask::OnProgress(BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
00121 {
00122     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00123     {
00124         auto progress = "Progress: " + args->Progress + "%";
00125         BackgroundTaskSample::GroupedBackgroundTaskProgress = progress;
00126         UpdateUI();
00127     }));
00128 }
00129
00130 /// <summary>
00131 /// Handle background task completion.
00132 /// </summary>
00133 /// <param name="task">The task that is reporting completion.</param>
00134 /// <param name="args">Arguments of the completion report.</param>
00135 void GroupedBackgroundTask::OnCompleted(BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
00136 {
00137     UpdateUI();
00138 }
00139
00140 /// <summary>
00141 /// Update the scenario UI.
00142 /// </summary>
00143 void GroupedBackgroundTask::UpdateUI()
00144 {
00145     auto uiDelegate = [this]()
00146     {
00147         RegisterButton->IsEnabled = !BackgroundTaskSample::GroupedBackgroundTaskRegistered;
00148         UnregisterGroupedButton->IsEnabled = BackgroundTaskSample::GroupedBackgroundTaskRegistered;
00149         Progress->Text = BackgroundTaskSample::GroupedBackgroundTaskProgress;
00150         Status->Text = BackgroundTaskSample::GetBackgroundTaskStatus(GroupedBackgroundTaskName);
00151     };
00152     auto handler = ref new Windows::UI::Core::DispatchedHandler(uiDelegate, Platform::CallbackContext::Any);
00153
00154     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, handler);
00155 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiScan/cpp/DisplayHelpers.cpp Source File

  • WiFiScan
  • cpp

DisplayHelpers.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <ppltasks.h>
00014 #include "DisplayHelpers.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::Devices::WiFi;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Networking::Connectivity;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::UI::Xaml::Media::Imaging;
00027
00028 using namespace SDKTemplate::WiFiScan;
00029 namespace SDKTemplate {
00030     namespace WiFiScan {
00031
00032         // WiFiNetworkDisplay
00033
00034         WiFiNetworkDisplay::WiFiNetworkDisplay(WiFiAvailableNetwork^ availableNetwork, WiFiAdapter^ adapter)
00035         {
00036             AvailableNetwork = availableNetwork;
00037             this->adapter = adapter;
00038             UpdateWiFiImage();
00039         }
00040
00041         void WiFiNetworkDisplay::UpdateWiFiImage()
00042         {
00043             Platform::String^ imageFileNamePrefix;
00044             if (AvailableNetwork->SecuritySettings->NetworkAuthenticationType == NetworkAuthenticationType::Open80211)
00045             {
00046                 imageFileNamePrefix = L"open";
00047             }
00048             else
00049             {
00050                 imageFileNamePrefix = L"secure";
00051             }
00052
00053             Platform::String^ imageFileName = L"ms-appx:/Assets/" + imageFileNamePrefix + "_" + AvailableNetwork->SignalBars + "bar.png";
00054
00055             WiFiImage = ref new BitmapImage(ref new Uri(imageFileName));
00056
00057             OnPropertyChanged("WiFiImage");
00058         }
00059
00060         task<void> WiFiNetworkDisplay::UpdateConnectivityLevels(IObservableVector<WiFiNetworkDisplay^>^ networkCollection, UINT current)
00061         {
00062             if (current < networkCollection->Size)
00063             {
00064                 try {
00065                     return networkCollection->GetAt(current)->UpdateConnectivityLevel().then([networkCollection, current]()
00066                     {
00067                         // Wait until the first task is done, then recursively call the next one
00068                         // This way we won't call GetConnectedProfileAsync() too many times
00069                         // which may exhaust the available wlan handles
00070                         return UpdateConnectivityLevels(networkCollection, current + 1);
00071                     });
00072                 }
00073                 catch (...)
00074                 {
00075                     // The network collection may have changed. If that happens,
00076                     // return an empty task to terminate the recusrsion
00077                     return create_task([]()
00078                     {
00079                     });
00080                 }
00081             }
00082             else
00083             {
00084                 return create_task([]()
00085                 {
00086                 });
00087             }
00088         }
00089
00090         task<void> WiFiNetworkDisplay::UpdateConnectivityLevel()
00091         {
00092             auto connectionProfileOperation = adapter->NetworkAdapter->GetConnectedProfileAsync();
00093             auto connectionProfileTask = create_task(connectionProfileOperation);
00094
00095             return connectionProfileTask.then([this](ConnectionProfile^ connectedProfile)
00096             {
00097                 Platform::String^ connectedSsid = nullptr;
00098
00099                 if (connectedProfile != nullptr &&
00100                     connectedProfile->IsWlanConnectionProfile &&
00101                     connectedProfile->WlanConnectionProfileDetails != nullptr)
00102                 {
00103                     connectedSsid = connectedProfile->WlanConnectionProfileDetails->GetConnectedSsid();
00104                 }
00105
00106                 if (connectedSsid != nullptr &&
00107                     AvailableNetwork->Ssid != nullptr &&
00108                     connectedSsid->Equals(AvailableNetwork->Ssid))
00109                 {
00110                     ConnectivityLevel = WiFiNetworkDisplay::GetConnectivityLevelAsString(connectedProfile->GetNetworkConnectivityLevel());
00111                 }
00112                 else
00113                 {
00114                     ConnectivityLevel = L"Not Connected";
00115                 }
00116
00117                 OnPropertyChanged("ConnectivityLevel");
00118             });
00119         }
00120
00121         Platform::String^ WiFiNetworkDisplay::GetNetworkAuthenticationTypeAsString(NetworkAuthenticationType authenticationType)
00122         {
00123             switch (authenticationType)
00124             {
00125             case NetworkAuthenticationType::None:
00126                 return L"None";
00127             case NetworkAuthenticationType::Unknown:
00128                 return L"Unknown";
00129             case NetworkAuthenticationType::Open80211:
00130                 return L"Open80211";
00131             case NetworkAuthenticationType::SharedKey80211:
00132                 return L"SharedKey80211";
00133             case NetworkAuthenticationType::Wpa:
00134                 return L"Wpa";
00135             case NetworkAuthenticationType::WpaPsk:
00136                 return L"WpaPsk";
00137             case NetworkAuthenticationType::WpaNone:
00138                 return L"WpaNone";
00139             case NetworkAuthenticationType::Rsna:
00140                 return L"Rsna";
00141             case NetworkAuthenticationType::RsnaPsk:
00142                 return L"RsnaPsk";
00143             default:
00144                 return L"Error getting Network Authentication Type";
00145             }
00146         }
00147
00148         Platform::String^ WiFiNetworkDisplay::GetNetworkEncryptionTypeAsString(NetworkEncryptionType encryptionType)
00149         {
00150             switch (encryptionType)
00151             {
00152             case NetworkEncryptionType::None:
00153                 return L"None";
00154             case NetworkEncryptionType::Unknown:
00155                 return L"Unknown";
00156             case NetworkEncryptionType::Wep:
00157                 return L"Wep";
00158             case NetworkEncryptionType::Wep40:
00159                 return L"Wep40";
00160             case NetworkEncryptionType::Wep104:
00161                 return L"Wep104";
00162             case NetworkEncryptionType::Tkip:
00163                 return L"Tkip";
00164             case NetworkEncryptionType::Ccmp:
00165                 return L"Ccmp";
00166             case NetworkEncryptionType::WpaUseGroup:
00167                 return L"WpaUseGroup";
00168             case NetworkEncryptionType::RsnUseGroup:
00169                 return L"RsnUseGroup";
00170             default:
00171                 return L"Error getting Network Encryption Type";
00172             }
00173         }
00174
00175         Platform::String^ WiFiNetworkDisplay::GetConnectionStatusAsString(WiFiConnectionStatus connectionStatus)
00176         {
00177             switch (connectionStatus)
00178             {
00179             case WiFiConnectionStatus::UnspecifiedFailure:
00180                 return L"UnspecifiedFailure";
00181             case WiFiConnectionStatus::Success:
00182                 return L"Success";
00183             case WiFiConnectionStatus::AccessRevoked:
00184                 return L"AccessRevoked";
00185             case WiFiConnectionStatus::InvalidCredential:
00186                 return L"InvalidCredential";
00187             case WiFiConnectionStatus::NetworkNotAvailable:
00188                 return L"NetworkNotAvailable";
00189             case WiFiConnectionStatus::Timeout:
00190                 return L"Timeout";
00191             case WiFiConnectionStatus::UnsupportedAuthenticationProtocol:
00192                 return L"UnsupportedAuthenticationProtocol";
00193             default:
00194                 return L"Error getting Connection Status";
00195             }
00196         }
00197
00198         Platform::String^ WiFiNetworkDisplay::GetConnectivityLevelAsString(NetworkConnectivityLevel conectivityLevel)
00199         {
00200             switch (conectivityLevel)
00201             {
00202             case NetworkConnectivityLevel::ConstrainedInternetAccess:
00203                 return L"ConstrainedInternetAccess";
00204             case NetworkConnectivityLevel::InternetAccess:
00205                 return L"InternetAccess";
00206             case NetworkConnectivityLevel::LocalAccess:
00207                 return  L"LocalAccess";
00208             case NetworkConnectivityLevel::None:
00209                 return  L"Not Connected";
00210             default:
00211                 return L"Not Connected";
00212             }
00213         }
00214
00215         void WiFiNetworkDisplay::OnPropertyChanged(String^ name)
00216         {
00217             MainPage::Current->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([=]()
00218             {
00219                 PropertyChanged(this, ref new PropertyChangedEventArgs(name));
00220             }));
00221         }
00222     }
00223 }
Generated on Fri Nov 15 2024 22:19:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cs/Scenario5_GetSingleDevice.xaml.cs Source File

  • DeviceEnumerationAndPairing
  • cs

Scenario5_GetSingleDevice.xaml.cs

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 using System;
00004 using System.Collections.ObjectModel;
00005 using System.IO;
00006 using Windows.Devices.Enumeration;
00007 using Windows.UI.Xaml;
00008 using Windows.UI.Xaml.Controls;
00009 using Windows.UI.Xaml.Navigation;
00010
00011 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00012
00013 namespace SDKTemplate
00014 {
00015     /// <summary>
00016     /// An empty page that can be used on its own or navigated to within a Frame.
00017     /// </summary>
00018     public sealed partial class Scenario5_GetSingleDevice : Page
00019     {
00020         private MainPage rootPage = MainPage.Current;
00021         private DeviceInformationKind deviceInformationKind;
00022
00023         private ObservableCollection<DeviceInformationDisplay> resultCollection = new ObservableCollection<DeviceInformationDisplay>();
00024
00025         public Scenario5_GetSingleDevice()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         protected override void OnNavigatedTo(NavigationEventArgs e)
00031         {
00032             resultsListView.ItemsSource = resultCollection;
00033         }
00034
00035         private async void Page_Loaded(object sender, RoutedEventArgs e)
00036         {
00037             DeviceInformationCollection deviceInfoCollection;
00038
00039             // Pre-populate the text box with an interface id.
00040             deviceInfoCollection = await DeviceInformation.FindAllAsync(DeviceClass.AudioRender);
00041             if (deviceInfoCollection.Count > 0)
00042             {
00043                 // When you want to "save" a DeviceInformation to get it back again later,
00044                 // use both the DeviceInformation.Kind and the DeviceInformation.Id.
00045                 interfaceIdTextBox.Text = deviceInfoCollection[0].Id;
00046                 deviceInformationKind = deviceInfoCollection[0].Kind;
00047                 InformationKindTextBox.Text = deviceInformationKind.ToString();
00048                 getButton.IsEnabled = true;
00049             }
00050         }
00051
00052         private async void GetButton_Click(object sender, RoutedEventArgs e)
00053         {
00054             resultCollection.Clear();
00055
00056             string interfaceId = interfaceIdTextBox.Text;
00057             getButton.IsEnabled = false;
00058
00059             rootPage.NotifyUser("CreateFromIdAsync operation started...", NotifyType.StatusMessage);
00060
00061             try
00062             {
00063                 // When you want to "save" a DeviceInformation to get it back again later,
00064                 // use both the DeviceInformation.Kind and the DeviceInformation.Id.
00065                 DeviceInformation deviceInfo = await DeviceInformation.CreateFromIdAsync(interfaceId, null, deviceInformationKind);
00066
00067                 rootPage.NotifyUser("CreateFromIdAsync operation completed.", NotifyType.StatusMessage);
00068
00069                 resultCollection.Add(new DeviceInformationDisplay(deviceInfo));
00070             }
00071             catch (FileNotFoundException)
00072             {
00073                 rootPage.NotifyUser("Invalid Interface Id", NotifyType.ErrorMessage);
00074             }
00075
00076             getButton.IsEnabled = true;
00077             getButton.Focus(FocusState.Keyboard);
00078         }
00079     }
00080 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/Scenario5_VerifyResponse.h Source File

  • SmartCard
  • cppwinrt

Scenario5_VerifyResponse.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once;
00013
00014 #include "Scenario5_VerifyResponse.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario5_VerifyResponse : Scenario5_VerifyResponseT<Scenario5_VerifyResponse>
00019     {
00020         SDKTemplate::MainPage m_rootPage{ SDKTemplate::MainPage::Current() };
00021
00022         Scenario5_VerifyResponse();
00023
00024         fire_and_forget VerifyResponse_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const&);
00025     };
00026 }
00027
00028 namespace winrt::SDKTemplate::factory_implementation
00029 {
00030     struct Scenario5_VerifyResponse : Scenario5_VerifyResponseT<Scenario5_VerifyResponse, implementation::Scenario5_VerifyResponse>
00031     {
00032     };
00033 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-SPI/cppwinrt/SampleConfiguration.h Source File

  • IoT-SPI
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cppwinrt/Scenario4_SymbologyAttributes.cpp Source File

  • BarcodeScanner
  • cppwinrt

Scenario4_SymbologyAttributes.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario4_SymbologyAttributes.h"
00014 #include "Scenario4_SymbologyAttributes.g.cpp"
00015
00016 namespace winrt
00017 {
00018     using namespace Windows::Foundation;
00019     using namespace Windows::Foundation::Collections;
00020     using namespace Windows::Devices::PointOfService;
00021     using namespace Windows::UI::Xaml;
00022     using namespace Windows::UI::Xaml::Controls;
00023     using namespace Windows::UI::Xaml::Data;
00024     using namespace Windows::UI::Xaml::Navigation;
00025 }
00026
00027 namespace winrt::SDKTemplate::implementation
00028 {
00029     Scenario4_SymbologyAttributes::Scenario4_SymbologyAttributes()
00030     {
00031         InitializeComponent();
00032
00033         m_listOfSymbologies = single_threaded_observable_vector<SymbologyListEntry>();
00034         SymbologyListSource().Source(m_listOfSymbologies);
00035     }
00036
00037     void Scenario4_SymbologyAttributes::OnNavigatedTo(NavigationEventArgs const&)
00038     {
00039         ResetTheScenarioState();
00040     }
00041
00042     void Scenario4_SymbologyAttributes::OnNavigatedFrom(NavigationEventArgs const&)
00043     {
00044         ResetTheScenarioState();
00045     }
00046
00047     /// <summary>
00048     /// Event Handler for Start Scan Button Click.
00049     /// Sets up the barcode scanner to be ready to receive the data events from the scan.
00050     /// </summary>
00051     fire_and_forget Scenario4_SymbologyAttributes::ScenarioStartScanButton_Click(IInspectable const&, RoutedEventArgs const&)
00052     {
00053         auto lifetime = get_strong();
00054
00055         ScenarioStartScanButton().IsEnabled(false);
00056
00057         m_rootPage.NotifyUser(L"Acquiring barcode scanner IInspectable const&.", NotifyType::StatusMessage);
00058
00059         // create the barcode scanner.
00060         m_scanner = co_await BarcodeScanner::GetDefaultAsync();
00061
00062         if (m_scanner)
00063         {
00064             // claim the scanner for exclusive use and enable it so that data received events are received.
00065             m_claimedScanner = co_await m_scanner.ClaimScannerAsync();
00066             if (m_claimedScanner)
00067             {
00068                 // It is always a good idea to have a release device requested event handler. If this event is not handled, there are chances of another app can
00069                 // claim ownership of the barcode scanner.
00070                 m_scannerReleaseRequestedToken = m_claimedScanner.ReleaseDeviceRequested(auto_revoke, { get_weak(), &Scenario4_SymbologyAttributes::claimedScanner_ReleaseDeviceRequested });
00071
00072                 // after successfully claiming, attach the datareceived event handler.
00073                 m_scannerDataReceivedToken = m_claimedScanner.DataReceived(auto_revoke, { get_weak(), &Scenario4_SymbologyAttributes::claimedScanner_DataReceived });
00074
00075                 // Ask the API to decode the data by default. By setting this, API will decode the raw data from the barcode scanner and
00076                 // send the ScanDataLabel and ScanDataType in the DataReceived event
00077                 m_claimedScanner.IsDecodeDataEnabled(true);
00078
00079                 // enable the scanner.
00080                 // Note: If the scanner is not enabled (i.e. EnableAsync not called), attaching the event handler will not be any useful because the API will not fire the event
00081                 // if the claimedScanner has not been Enabled
00082                 co_await m_claimedScanner.EnableAsync();
00083
00084                 // after successful claim, list supported symbologies
00085                 auto supportedSymbologies = co_await m_scanner.GetSupportedSymbologiesAsync();
00086                 for (uint32_t symbology : supportedSymbologies)
00087                 {
00088                     m_listOfSymbologies.Append(SymbologyListEntry{ symbology });
00089                 }
00090
00091                 // reset the button state
00092                 ScenarioEndScanButton().IsEnabled(true);
00093
00094                 m_rootPage.NotifyUser(L"Ready to scan. Device ID: " + m_claimedScanner.DeviceId(), NotifyType::StatusMessage);
00095             }
00096             else
00097             {
00098                 m_scanner.Close();
00099                 m_scanner = nullptr;
00100                 ScenarioStartScanButton().IsEnabled(true);
00101                 m_rootPage.NotifyUser(L"Claim barcode scanner failed.", NotifyType::ErrorMessage);
00102             }
00103         }
00104         else
00105         {
00106             ScenarioStartScanButton().IsEnabled(true);
00107             m_rootPage.NotifyUser(L"Barcode scanner not found. Please connect a barcode scanner.", NotifyType::ErrorMessage);
00108         }
00109     }
00110
00111     /// <summary>
00112     /// Event handler for the Release Device Requested event fired when barcode scanner receives Claim request from another application
00113     /// </summary>
00114     /// <param name="args"> Contains the ClamiedBarcodeScanner that is sending this request</param>
00115     void Scenario4_SymbologyAttributes::claimedScanner_ReleaseDeviceRequested(IInspectable const&, ClaimedBarcodeScanner const& args)
00116     {
00117         // always retain the device
00118         args.RetainDevice();
00119         m_rootPage.NotifyUser(L"Event ReleaseDeviceRequested received. Retaining the barcode scanner.", NotifyType::StatusMessage);
00120     }
00121
00122     /// <summary>
00123     /// Event handler for the DataReceived event fired when a barcode is scanned by the barcode scanner
00124     /// </summary>
00125     /// <param name="args"> Contains the BarcodeScannerReport which contains the data obtained in the scan</param>
00126     fire_and_forget Scenario4_SymbologyAttributes::claimedScanner_DataReceived(ClaimedBarcodeScanner const&, BarcodeScannerDataReceivedEventArgs args)
00127     {
00128         auto lifetime = get_strong();
00129         co_await resume_foreground(Dispatcher());
00130
00131         // read the data from the buffer and convert to string.
00132         ScenarioOutputScanDataLabel().Text(GetDataLabelString(args.Report().ScanDataLabel(), args.Report().ScanDataType()));
00133         ScenarioOutputScanData().Text(GetDataString(args.Report().ScanData()));
00134         ScenarioOutputScanDataType().Text(BarcodeSymbologies::GetName(args.Report().ScanDataType()));
00135     }
00136
00137     /// <summary>
00138     /// Reset the Scenario state
00139     /// </summary>
00140     void Scenario4_SymbologyAttributes::ResetTheScenarioState()
00141     {
00142         if (m_claimedScanner)
00143         {
00144             // Detach the event handlers
00145             m_scannerDataReceivedToken.revoke();
00146             m_scannerReleaseRequestedToken.revoke();
00147             // Release the Barcode Scanner and set to nullptr
00148             m_claimedScanner.Close();
00149             m_claimedScanner = nullptr;
00150         }
00151
00152         if (m_scanner)
00153         {
00154             m_scanner.Close();
00155             m_scanner = nullptr;
00156         }
00157
00158         m_symbologyAttributes = nullptr;
00159
00160         // Reset the UI if we are still the current page.
00161         if (Frame().Content() == *this)
00162         {
00163             m_rootPage.NotifyUser(L"Click the start scanning button to begin.", NotifyType::StatusMessage);
00164             ScenarioOutputScanData().Text(L"No data");
00165             ScenarioOutputScanDataLabel().Text(L"No data");
00166             ScenarioOutputScanDataType().Text(L"No data");
00167
00168             // reset the button state
00169             ScenarioEndScanButton().IsEnabled(false);
00170             ScenarioStartScanButton().IsEnabled(true);
00171             SetSymbologyAttributesButton().IsEnabled(false);
00172             EnableCheckDigit().IsEnabled(false);
00173             TransmitCheckDigit().IsEnabled(false);
00174             SetDecodeRangeLimits().IsEnabled(false);
00175
00176             // reset symbology list
00177             m_listOfSymbologies.Clear();
00178         }
00179     }
00180
00181     /// <summary>
00182     /// Event handler for End Scan Button Click.
00183     /// Releases the Barcode Scanner and resets the text in the UI
00184     /// </summary>
00185     void Scenario4_SymbologyAttributes::ScenarioEndScanButton_Click(IInspectable const&, RoutedEventArgs const&)
00186     {
00187         // reset the scenario state
00188         ResetTheScenarioState();
00189     }
00190
00191     /// <summary>
00192     /// Event handler for Symbology listbox selection changed.
00193     /// Get symbology attributes and populate attribute UI components
00194     /// </summary>
00195     fire_and_forget Scenario4_SymbologyAttributes::SymbologySelection_Changed(IInspectable const&, SelectionChangedEventArgs const&)
00196     {
00197         auto lifetime = get_strong();
00198
00199         if (m_claimedScanner)
00200         {
00201             auto symbologyListEntry = SymbologyListBox().SelectedItem().as<SymbologyListEntry>();
00202             if (symbologyListEntry)
00203             {
00204                 SetSymbologyAttributesButton().IsEnabled(false);
00205                 try
00206                 {
00207                     m_symbologyAttributes = co_await m_claimedScanner.GetSymbologyAttributesAsync(symbologyListEntry.Id());
00208                 }
00209                 catch (hresult_error const&)
00210                 {
00211                     m_symbologyAttributes = nullptr;
00212                 }
00213
00214                 if (m_symbologyAttributes)
00215                 {
00216                     SetSymbologyAttributesButton().IsEnabled(true);
00217
00218                     // initialize attributes UIs
00219                     EnableCheckDigit().IsEnabled(m_symbologyAttributes.IsCheckDigitValidationSupported());
00220                     EnableCheckDigit().IsChecked(m_symbologyAttributes.IsCheckDigitValidationEnabled());
00221                     TransmitCheckDigit().IsEnabled(m_symbologyAttributes.IsCheckDigitTransmissionSupported());
00222                     TransmitCheckDigit().IsChecked(m_symbologyAttributes.IsCheckDigitTransmissionEnabled());
00223                     SetDecodeRangeLimits().IsEnabled(m_symbologyAttributes.IsDecodeLengthSupported());
00224                     bool decodeLengthEnabled = (m_symbologyAttributes.DecodeLengthKind() == BarcodeSymbologyDecodeLengthKind::Range);
00225                     SetDecodeRangeLimits().IsChecked(decodeLengthEnabled);
00226                     if (decodeLengthEnabled)
00227                     {
00228                         MinimumDecodeLength().Value((std::min)(m_symbologyAttributes.DecodeLength1(), m_symbologyAttributes.DecodeLength2()));
00229                         MaximumDecodeLength().Value((std::max)(m_symbologyAttributes.DecodeLength1(), m_symbologyAttributes.DecodeLength2()));
00230                     }
00231                 }
00232                 else
00233                 {
00234                     m_rootPage.NotifyUser(L"Symbology attributes are not available.", NotifyType::ErrorMessage);
00235                     EnableCheckDigit().IsEnabled(false);
00236                     TransmitCheckDigit().IsEnabled(false);
00237                     SetDecodeRangeLimits().IsEnabled(false);
00238                 }
00239             }
00240         }
00241     }
00242
00243     fire_and_forget Scenario4_SymbologyAttributes::SetSymbologyAttributes_Click(IInspectable const&, RoutedEventArgs const&)
00244     {
00245         auto lifetime = get_strong();
00246
00247         if (m_claimedScanner && m_symbologyAttributes)
00248         {
00249             // populate attributes
00250             if (m_symbologyAttributes.IsCheckDigitValidationSupported())
00251             {
00252                 m_symbologyAttributes.IsCheckDigitValidationEnabled(EnableCheckDigit().IsChecked().Value());
00253             }
00254             if (m_symbologyAttributes.IsCheckDigitTransmissionSupported())
00255             {
00256                 m_symbologyAttributes.IsCheckDigitTransmissionEnabled(TransmitCheckDigit().IsChecked().Value());
00257             }
00258             if (m_symbologyAttributes.IsDecodeLengthSupported())
00259             {
00260                 if (SetDecodeRangeLimits().IsChecked().Value())
00261                 {
00262                     m_symbologyAttributes.DecodeLengthKind(BarcodeSymbologyDecodeLengthKind::Range);
00263                     m_symbologyAttributes.DecodeLength1(static_cast<uint32_t>(MinimumDecodeLength().Value()));
00264                     m_symbologyAttributes.DecodeLength2(static_cast<uint32_t>(MaximumDecodeLength().Value()));
00265                 }
00266                 else
00267                 {
00268                     m_symbologyAttributes.DecodeLengthKind(BarcodeSymbologyDecodeLengthKind::AnyLength);
00269                 }
00270             }
00271
00272             auto symbologyListEntry = SymbologyListBox().SelectedItem().as<SymbologyListEntry>();
00273             if (symbologyListEntry)
00274             {
00275                 bool attributesSet = false;
00276
00277                 try
00278                 {
00279                     attributesSet = co_await m_claimedScanner.SetSymbologyAttributesAsync(symbologyListEntry.Id(), m_symbologyAttributes);
00280                 }
00281                 catch (hresult_error const&)
00282                 {
00283                     // Scanner could not set the attributes.
00284                 }
00285
00286                 if (attributesSet)
00287                 {
00288                     m_rootPage.NotifyUser(L"Attributes set for symbology '" + symbologyListEntry.Name() + L"'", NotifyType::StatusMessage);
00289                 }
00290                 else
00291                 {
00292                     m_rootPage.NotifyUser(L"Attributes could not be set for symbology '" + symbologyListEntry.Name() + L"'.", NotifyType::ErrorMessage);
00293                 }
00294             }
00295             else
00296             {
00297                 m_rootPage.NotifyUser(L"Select a symbology from the list.", NotifyType::ErrorMessage);
00298             }
00299         }
00300     }
00301 }
Generated on Fri Nov 15 2024 22:18:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DAdvancedColorImages/cpp/D2DAdvancedColorImages/LuminanceHeatmapEffect.cpp Source File

  • D2DAdvancedColorImages
  • cpp
  • D2DAdvancedColorImages

LuminanceHeatmapEffect.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <initguid.h>
00014 #include "LuminanceHeatmapEffect.h"
00015 #include "BasicReaderWriter.h"
00016
00017 #define XML(X) TEXT(#X)
00018
00019 LuminanceHeatmapEffect::LuminanceHeatmapEffect() :
00020     m_refCount(1),
00021     m_constants{}
00022 {
00023 }
00024
00025 HRESULT __stdcall LuminanceHeatmapEffect::CreateLuminanceHeatmapImpl(_Outptr_ IUnknown** ppEffectImpl)
00026 {
00027     // Since the object's refcount is initialized to 1, we don't need to AddRef here.
00028     *ppEffectImpl = static_cast<ID2D1EffectImpl*>(new (std::nothrow) LuminanceHeatmapEffect());
00029
00030     if (*ppEffectImpl == nullptr)
00031     {
00032         return E_OUTOFMEMORY;
00033     }
00034     else
00035     {
00036         return S_OK;
00037     }
00038 }
00039
00040 HRESULT LuminanceHeatmapEffect::Register(_In_ ID2D1Factory1* pFactory)
00041 {
00042     // The inspectable metadata of an effect is defined in XML. This can be passed in from an external source
00043     // as well, however for simplicity we just inline the XML.
00044     PCWSTR pszXml =
00045         XML(
00046             <?xml version='1.0'?>
00047             <Effect>
00048                 <!-- System Properties -->
00049                 <Property name='DisplayName' type='string' value='LuminanceHeatmap'/>
00050                 <Property name='Author' type='string' value='Microsoft Corporation'/>
00051                 <Property name='Category' type='string' value='Source'/>
00052                 <Property name='Description' type='string' value='Emulates SDR behavior on an AC source'/>
00053                 <Inputs>
00054                     <Input name = 'Source'/>
00055                 </Inputs>
00056                 <!-- Custom Properties go here -->
00057             </Effect>
00058             );
00059
00060     // This registers the effect with the factory, which will make the effect
00061     // instantiatable.
00062     return pFactory->RegisterEffectFromString(
00063         CLSID_CustomLuminanceHeatmapEffect,
00064         pszXml,
00065         nullptr, // No custom properties
00066         0,       // No custom properties
00067         CreateLuminanceHeatmapImpl
00068         );
00069 }
00070
00071 IFACEMETHODIMP LuminanceHeatmapEffect::Initialize(
00072     _In_ ID2D1EffectContext* pEffectContext,
00073     _In_ ID2D1TransformGraph* pTransformGraph
00074     )
00075 {
00076     // To maintain consistency across different DPIs, this effect needs to cover more pixels at
00077     // higher than normal DPIs. The context is saved here so the effect can later retrieve the DPI.
00078     m_effectContext = pEffectContext;
00079     BasicReaderWriter^ reader = ref new BasicReaderWriter();
00080     Platform::Array<unsigned char, 1U>^ data;
00081
00082     try
00083     {
00084         data = reader->ReadData("LuminanceHeatmapEffect.cso");
00085     }
00086     catch (Platform::Exception^ e)
00087     {
00088         // Return error if file can not be read.
00089         return e->HResult;
00090     }
00091
00092     HRESULT hr = pEffectContext->LoadPixelShader(GUID_LuminanceHeatmapPixelShader, data->Data, data->Length);
00093
00094     // This loads the shader into the Direct2D image effects system and associates it with the GUID passed in.
00095     // If this method is called more than once (say by other instances of the effect) with the same GUID,
00096     // the system will simply do nothing, ensuring that only one instance of a shader is stored regardless of how
00097     // many time it is used.
00098     if (SUCCEEDED(hr))
00099     {
00100         // The graph consists of a single transform. In fact, this class is the transform,
00101         // reducing the complexity of implementing an effect when all we need to
00102         // do is use a single pixel shader.
00103         hr = pTransformGraph->SetSingleTransformNode(this);
00104     }
00105
00106     return hr;
00107 }
00108
00109 HRESULT LuminanceHeatmapEffect::UpdateConstants()
00110 {
00111     // Update the DPI if it has changed. This allows the effect to scale across different DPIs automatically.
00112     m_effectContext->GetDpi(&m_dpi, &m_dpi);
00113     m_constants.dpi = m_dpi;
00114
00115     return m_drawInfo->SetPixelShaderConstantBuffer(reinterpret_cast<BYTE*>(&m_constants), sizeof(m_constants));
00116 }
00117
00118 IFACEMETHODIMP LuminanceHeatmapEffect::PrepareForRender(D2D1_CHANGE_TYPE changeType)
00119 {
00120     return UpdateConstants();
00121 }
00122
00123 // SetGraph is only called when the number of inputs changes. This never happens as we publish this effect
00124 // as a single input effect.
00125 IFACEMETHODIMP LuminanceHeatmapEffect::SetGraph(_In_ ID2D1TransformGraph* pGraph)
00126 {
00127     return E_NOTIMPL;
00128 }
00129
00130 // Called to assign a new render info class, which is used to inform D2D on
00131 // how to set the state of the GPU.
00132 IFACEMETHODIMP LuminanceHeatmapEffect::SetDrawInfo(_In_ ID2D1DrawInfo* pDrawInfo)
00133 {
00134     m_drawInfo = pDrawInfo;
00135
00136     return m_drawInfo->SetPixelShader(GUID_LuminanceHeatmapPixelShader);
00137 }
00138
00139 // Calculates the mapping between the output and input rects.
00140 IFACEMETHODIMP LuminanceHeatmapEffect::MapOutputRectToInputRects(
00141     _In_ const D2D1_RECT_L* pOutputRect,
00142     _Out_writes_(inputRectCount) D2D1_RECT_L* pInputRects,
00143     UINT32 inputRectCount
00144     ) const
00145 {
00146     // This effect has exactly 1 input.
00147     if (inputRectCount != 1)
00148     {
00149         return E_INVALIDARG;
00150     }
00151
00152     // 1:1 mapping of output to input rect.
00153     pInputRects[0].left = pOutputRect->left;
00154     pInputRects[0].top = pOutputRect->top;
00155     pInputRects[0].right = pOutputRect->right;
00156     pInputRects[0].bottom = pOutputRect->bottom;
00157
00158     return S_OK;
00159 }
00160
00161 IFACEMETHODIMP LuminanceHeatmapEffect::MapInputRectsToOutputRect(
00162     _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputRects,
00163     _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputOpaqueSubRects,
00164     UINT32 inputRectCount,
00165     _Out_ D2D1_RECT_L* pOutputRect,
00166     _Out_ D2D1_RECT_L* pOutputOpaqueSubRect
00167     )
00168 {
00169     // This effect has exactly 1 input.
00170     if (inputRectCount != 1)
00171     {
00172         return E_INVALIDARG;
00173     }
00174
00175     // 1:1 mapping of input to output rect.
00176     *pOutputRect = pInputRects[0];
00177     m_inputRect = pInputRects[0];
00178
00179     // This effect always outputs fully opaque pixels.
00180     *pOutputOpaqueSubRect = pInputRects[0];
00181
00182     return S_OK;
00183 }
00184
00185 IFACEMETHODIMP LuminanceHeatmapEffect::MapInvalidRect(
00186     UINT32 inputIndex,
00187     D2D1_RECT_L invalidInputRect,
00188     _Out_ D2D1_RECT_L* pInvalidOutputRect
00189     ) const
00190 {
00191     HRESULT hr = S_OK;
00192
00193     // Indicate that the entire output may be invalid.
00194     *pInvalidOutputRect = m_inputRect;
00195
00196     return hr;
00197 }
00198
00199 IFACEMETHODIMP_(UINT32) LuminanceHeatmapEffect::GetInputCount() const
00200 {
00201     return 1;
00202 }
00203
00204 // D2D ensures that that effects are only referenced from one thread at a time.
00205 // To improve performance, we simply increment/decrement our reference count
00206 // rather than use atomic InterlockedIncrement()/InterlockedDecrement() functions.
00207 IFACEMETHODIMP_(ULONG) LuminanceHeatmapEffect::AddRef()
00208 {
00209     m_refCount++;
00210     return m_refCount;
00211 }
00212
00213 IFACEMETHODIMP_(ULONG) LuminanceHeatmapEffect::Release()
00214 {
00215     m_refCount--;
00216
00217     if (m_refCount == 0)
00218     {
00219         delete this;
00220         return 0;
00221     }
00222     else
00223     {
00224         return m_refCount;
00225     }
00226 }
00227
00228 // This enables the stack of parent interfaces to be queried. In the instance
00229 // of the LuminanceHeatmap interface, this method simply enables the developer
00230 // to cast a LuminanceHeatmap instance to an ID2D1EffectImpl or IUnknown instance.
00231 IFACEMETHODIMP LuminanceHeatmapEffect::QueryInterface(
00232     _In_ REFIID riid,
00233     _Outptr_ void** ppOutput
00234     )
00235 {
00236     *ppOutput = nullptr;
00237     HRESULT hr = S_OK;
00238
00239     if (riid == __uuidof(ID2D1EffectImpl))
00240     {
00241         *ppOutput = reinterpret_cast<ID2D1EffectImpl*>(this);
00242     }
00243     else if (riid == __uuidof(ID2D1DrawTransform))
00244     {
00245         *ppOutput = static_cast<ID2D1DrawTransform*>(this);
00246     }
00247     else if (riid == __uuidof(ID2D1Transform))
00248     {
00249         *ppOutput = static_cast<ID2D1Transform*>(this);
00250     }
00251     else if (riid == __uuidof(ID2D1TransformNode))
00252     {
00253         *ppOutput = static_cast<ID2D1TransformNode*>(this);
00254     }
00255     else if (riid == __uuidof(IUnknown))
00256     {
00257         *ppOutput = this;
00258     }
00259     else
00260     {
00261         hr = E_NOINTERFACE;
00262     }
00263
00264     if (*ppOutput != nullptr)
00265     {
00266         AddRef();
00267     }
00268
00269     return hr;
00270 }
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HardwareDRMViewModel Member List

This is the complete list of members for HardwareDRMViewModel, including all inherited members.
CmdPlayMovie | HardwareDRMViewModel |
CmdStopMovie | HardwareDRMViewModel |
CmdUseHardware | HardwareDRMViewModel |
CmdUseSoftware | HardwareDRMViewModel |
ConfigureHardwareDRM(MediaElement mediaElement) | HardwareDRMViewModel | [inline, private]
ConfigureSoftwareDRM(MediaElement mediaElement) | HardwareDRMViewModel | [inline, private]
HardwareDRMViewModel(MediaElement mediaElement) | HardwareDRMViewModel | [inline]
Individualize() | HardwareDRMViewModel | [inline, private]
licenseUrl | HardwareDRMViewModel | [private]
Log(string message) | ViewModelBase | [inline, static]
modeSelected | HardwareDRMViewModel | [private]
moviePath | HardwareDRMViewModel | [private]
MoviePath | HardwareDRMViewModel |
OutputLog | ViewModelBase |
PlaybackEnabled | ViewModelBase |
PlayReadyInfo | HardwareDRMViewModel |
ProcessServiceRequest(IMediaProtectionServiceRequest serviceRequest) | HardwareDRMViewModel | [inline, private]
PropertyChanged | ViewModelBase |
ProtectionManager | ViewModelBase |
RaisePropertyChanged([CallerMemberName] string propertyName="") | ViewModelBase | [inline, protected]
serviceCompletionNotifier | HardwareDRMViewModel | [private]
ServiceRequested(MediaProtectionManager sender, ServiceRequestedEventArgs srEvent) | HardwareDRMViewModel | [inline, private]
SetPlaybackEnabled(bool enabled) | ViewModelBase | [inline]
Generated on Fri Nov 15 2024 22:24:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cppwinrt/HistoryAndRoaming.cpp Source File

  • Clipboard
  • cppwinrt

HistoryAndRoaming.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "HistoryAndRoaming.h"
00014 #include "HistoryAndRoaming.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::ApplicationModel::DataTransfer;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::Graphics::Imaging;
00021 using namespace Windows::Storage::Streams;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Media::Imaging;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 namespace winrt::SDKTemplate::implementation
00028 {
00029     HistoryAndRoaming::HistoryAndRoaming()
00030     {
00031         InitializeComponent();
00032     }
00033
00034     void HistoryAndRoaming::OnNavigatedTo(NavigationEventArgs const&)
00035     {
00036         historyEnabledToken = Clipboard::HistoryEnabledChanged({ get_weak(), &HistoryAndRoaming::OnHistoryEnabledChanged });
00037         roamingEnabledToken = Clipboard::RoamingEnabledChanged({ get_weak(), &HistoryAndRoaming::OnRoamingEnabledChanged });
00038         CheckHistoryAndRoaming();
00039     }
00040
00041     void HistoryAndRoaming::OnNavigatedFrom(NavigationEventArgs const&)
00042     {
00043          Clipboard::HistoryEnabledChanged(historyEnabledToken);
00044          Clipboard::RoamingEnabledChanged(roamingEnabledToken);
00045     }
00046
00047     fire_and_forget HistoryAndRoaming::CopyButton_Click(IInspectable const&, RoutedEventArgs const&)
00048     {
00049         auto lifetime = get_strong();
00050
00051         // Generate a bitmap for our clipboard content.
00052         RenderTargetBitmap target;
00053         co_await target.RenderAsync(ClipboardContent());
00054         IBuffer buffer = co_await target.GetPixelsAsync();
00055         SoftwareBitmap bitmap = SoftwareBitmap::CreateCopyFromBuffer(buffer, BitmapPixelFormat::Bgra8, target.PixelWidth(), target.PixelHeight(), BitmapAlphaMode::Premultiplied);
00056
00057         // Save the bitmap to a stream.
00058         InMemoryRandomAccessStream stream;
00059         BitmapEncoder encoder = co_await BitmapEncoder::CreateAsync(BitmapEncoder::PngEncoderId(), stream);
00060         encoder.SetSoftwareBitmap(bitmap);
00061         co_await encoder.FlushAsync();
00062         stream.Seek(0);
00063
00064         // Create a DataPackage to hold the bitmap and text.
00065         DataPackage dataPackage;
00066         dataPackage.SetBitmap(RandomAccessStreamReference::CreateFromStream(stream));
00067         dataPackage.SetText(ClipboardContent().Text());
00068
00069         ClipboardContentOptions options;
00070
00071         // Customize clipboard history.
00072         if (IncludeAllInHistory().IsChecked().Value())
00073         {
00074             // This is the default, but set it explicitly for expository purposes.
00075             options.IsAllowedInHistory(true);
00076         }
00077         else if (IncludeTextInHistory().IsChecked().Value())
00078         {
00079             // This is the default, but set it explicitly for expository purposes.
00080             options.IsAllowedInHistory(true);
00081             // Allow only text to go into the history.
00082             options.HistoryFormats().Append(StandardDataFormats::Text());
00083         }
00084         else
00085         {
00086             // Exclude from history.
00087             options.IsAllowedInHistory(false);
00088         }
00089
00090         // Customize clipboard roaming.
00091         if (AllowAllToRoam().IsChecked().Value())
00092         {
00093             // This is the default, but set it explicitly for expository purposes.
00094             options.IsRoamable(true);
00095         }
00096         else if (AllowTextToRoam().IsChecked().Value())
00097         {
00098             // This is the default, but set it explicitly for expository purposes.
00099             options.IsRoamable(true);
00100             // Allow only text to roam.
00101             options.RoamingFormats().Append(StandardDataFormats::Text());
00102         }
00103         else
00104         {
00105             // Exclude from roaming.
00106             options.IsRoamable(false);
00107         }
00108
00109         // Set the data package to the clipboard with our custom options.
00110         if (Clipboard::SetContentWithOptions(dataPackage, options))
00111         {
00112             rootPage.NotifyUser(L"Text and bitmap have been copied to clipboard.", NotifyType::StatusMessage);
00113         }
00114         else
00115         {
00116             // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
00117             rootPage.NotifyUser(L"Error copying content to clipboard.", NotifyType::ErrorMessage);
00118         }
00119     }
00120
00121     void HistoryAndRoaming::OnHistoryEnabledChanged(IInspectable const&, IInspectable const&)
00122     {
00123         CheckHistoryAndRoaming();
00124     }
00125
00126     void HistoryAndRoaming::OnRoamingEnabledChanged(IInspectable const&, IInspectable const&)
00127     {
00128         CheckHistoryAndRoaming();
00129     }
00130
00131     void HistoryAndRoaming::SelectVisibleElement(UIElement const& ifTrue, UIElement const& ifFalse, bool value)
00132     {
00133         ifTrue.Visibility(value ? Visibility::Visible : Visibility::Collapsed);
00134         ifFalse.Visibility(!value ? Visibility::Visible : Visibility::Collapsed);
00135     }
00136
00137     fire_and_forget HistoryAndRoaming::CheckHistoryAndRoaming()
00138     {
00139         auto lifetime = get_strong();
00140         co_await Dispatcher();
00141         SelectVisibleElement(ClipboardHistoryBlock(), ClipboardHistoryUnavailableBlock(), Clipboard::IsHistoryEnabled());
00142         SelectVisibleElement(ClipboardRoamingBlock(), ClipboardRoamingUnavailableBlock(), Clipboard::IsRoamingEnabled());
00143     }
00144 }
00145
Generated on Fri Nov 15 2024 22:18:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/Model/Scenario.cs Source File

  • Notifications
  • cs
  • Notifications
  • Model

Scenario.cs

Go to the documentation of this file.
00001 ﻿using Notifications.Helpers;
00002 using System;
00003
00004 namespace Notifications.Model
00005 {
00006     public class Scenario : BindableBase, IScenario
00007     {
00008         /// <summary>
00009         /// Simply returns the PageUri, since that's guaranteed to be unique
00010         /// </summary>
00011         public string Id
00012         {
00013             get { return UIElementType.FullName; }
00014         }
00015
00016         private string _name;
00017         public string Name
00018         {
00019             get { return _name; }
00020         }
00021
00022         public Type UIElementType { get; private set; }
00023
00024         public Scenario(string name, Type uiElementType)
00025         {
00026             _name = name;
00027             UIElementType = uiElementType;
00028         }
00029
00030         public override string ToString()
00031         {
00032             return Name + " - " + Id;
00033         }
00034
00035         public bool Contains(Type scenarioType)
00036         {
00037             return FindScenario(scenarioType) != null;
00038         }
00039
00040         public Scenario FindScenario(Type scenarioType)
00041         {
00042             if (UIElementType == scenarioType)
00043                 return this;
00044
00045             return null;
00046         }
00047     }
00048 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SubPage Member List

This is the complete list of members for SubPage, including all inherited members.
LoadState(object sender, LoadStateEventArgs e) | SubPage | [inline, private]
Navigation_BackRequested(object sender, BackRequestedEventArgs e) | SubPage | [inline, private]
navigationHelper | SubPage | [private]
OnNavigatedFrom(NavigationEventArgs e) | SubPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | SubPage | [inline, protected]
Page_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) | SubPage | [inline, private]
SaveState(object sender, SaveStateEventArgs e) | SubPage | [inline, private]
SubPage() | SubPage | [inline]
tapCount | SubPage | [private]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cppwinrt/Scenario4_UnicodeExtensions.cpp Source File

  • Calendar
  • cppwinrt

Scenario4_UnicodeExtensions.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario4_UnicodeExtensions.h"
00014 #include "Scenario4_UnicodeExtensions.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Globalization;
00019 using namespace Windows::UI::Xaml;
00020
00021 namespace
00022 {
00023     void ReportCalendarData(std::wostream& results, Calendar const& calendar, PCWSTR calendarLabel)
00024     {
00025         results <<
00026             calendarLabel << L": " << std::wstring_view(calendar.GetCalendarSystem()) << "\n" <<
00027             L"Calendar system: " << std::wstring_view(calendar.GetCalendarSystem()) << L"\n" <<
00028             L"Numeral System: " << std::wstring_view(calendar.NumeralSystem()) << L"\n" <<
00029             L"Resolved Language " << std::wstring_view(calendar.ResolvedLanguage()) << L"\n" <<
00030             L"Name of Month: " << std::wstring_view(calendar.MonthAsSoloString()) << L"\n" <<
00031             L"Day of Month: " << std::wstring_view(calendar.DayAsPaddedString(2)) << L"\n" <<
00032             L"Day of Week: " << std::wstring_view(calendar.DayOfWeekAsSoloString()) << L"\n" <<
00033             L"Year: " << std::wstring_view(calendar.YearAsString()) << L"\n" <<
00034             L"\n";
00035     }
00036
00037 }
00038
00039 namespace winrt::SDKTemplate::implementation
00040 {
00041     Scenario4_UnicodeExtensions::Scenario4_UnicodeExtensions()
00042     {
00043         InitializeComponent();
00044     }
00045
00046     void Scenario4_UnicodeExtensions::ShowResults_Click(IInspectable const&, RoutedEventArgs const&)
00047     {
00048         // This scenario uses the Windows.Globalization.Calendar class to display the parts of a date.
00049
00050         // Create Calendar objects using different Unicode extensions for different languages.
00051         // NOTE: Calendar (ca) and numeral system (nu) are the only supported extensions with any others being ignored.
00052         // Note that collation (co) extension is ignored in the last example.
00053         Calendar cal1;
00054         Calendar cal2({ L"ar-SA-u-ca-gregory-nu-Latn" });
00055         Calendar cal3({ L"he-IL-u-nu-arab" });
00056         Calendar cal4({ L"he-IL-u-ca-hebrew-co-phonebk" });
00057
00058         // Generate the results
00059         std::wostringstream results;
00060         ReportCalendarData(results, cal1, L"User's default calendar system");
00061         ReportCalendarData(results, cal2, L"Calendar object with Arabic language, Gregorian Calendar and Latin Numeral System (ar-SA-ca-gregory-nu-Latn)");
00062         ReportCalendarData(results, cal3, L"Calendar object with Hebrew language, Default Calendar for that language and Arab Numeral System (he-IL-u-nu-arab)");
00063         ReportCalendarData(results, cal4, L"Calendar object with Hebrew language, Hebrew Calendar, Default Numeral System for that language and Phonebook collation (he-IL-u-ca-hebrew-co-phonebk)");
00064         OutputTextBlock().Text(results.str());
00065     }
00066 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/Scenario6.xaml.h Source File

  • SimpleInk
  • cpp

Scenario6.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario6.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario6 sealed
00024     {
00025     public:
00026         Scenario6();
00027     private:
00028         void UnprocessedInput_PointerEntered(Windows::UI::Input::Inking::InkUnprocessedInput^ sender, Windows::UI::Core::PointerEventArgs^ args);
00029         void UnprocessedInput_PointerEntered1(Windows::UI::Input::Inking::InkUnprocessedInput^ sender, Windows::UI::Core::PointerEventArgs^ args);
00030
00031         void OnSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00032         void SetCanvasSize();
00033         void ToggleLogs(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void InkToolbar_IsStencilButtonCheckedChanged(Windows::UI::Xaml::Controls::InkToolbar^ sender, Windows::UI::Xaml::Controls::InkToolbarIsStencilButtonCheckedChangedEventArgs^ args);
00035         void InkToolbar_SelectedStencilChanged(Windows::UI::Xaml::DependencyObject^ sender, Windows::UI::Xaml::DependencyProperty^ dp);
00036         void InkToolbar_EraseAllClicked(Windows::UI::Xaml::Controls::InkToolbar^ sender, Platform::Object^ args);
00037         void InkToolbar_InkDrawingAttributesChanged(Windows::UI::Xaml::Controls::InkToolbar^ sender, Platform::Object^ args);
00038         void InkToolbar_ActiveToolChanged(Windows::UI::Xaml::Controls::InkToolbar^ sender, Platform::Object^ args);
00039         Windows::Foundation::EventRegistrationToken stencilButtonCheckedChangedToken;
00040         Windows::Foundation::EventRegistrationToken eraseAllClickedToken;
00041         Windows::Foundation::EventRegistrationToken inkDrawingAttributesChangedToken;
00042         Windows::Foundation::EventRegistrationToken activeToolChangedToken;
00043         int64_t selectedStencilChangedToken;
00044
00045         MainPage^ rootPage;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:19:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/xBindSampleModel/Manager.cs Source File

  • XamlBind
  • cpp
  • xBindSampleModel

Manager.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using Windows.UI.Xaml.Data;
00005 using System.ComponentModel;
00006 using System.Runtime.CompilerServices;
00007 using System.Collections.ObjectModel;
00008
00009 using Windows.Foundation.Collections;
00010 using System.Collections;
00011 using System.Collections.Specialized;
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Popups;
00014
00015 namespace xBindSampleModel
00016 {
00017     public sealed class Manager : IEmployee, INotifyPropertyChanged
00018     {
00019         private Employee _employee;
00020         private EmployeeCollection _reports;
00021         private EmployeeDictionary _reportsDictionary;
00022
00023         public Manager()
00024         {
00025             _employee = new Employee();
00026             _reports = new EmployeeCollection();
00027             _reportsDictionary = new EmployeeDictionary();
00028         }
00029
00030         public IEnumerable<IEmployee> ReportsEnum { get { return _reports; } }
00031         public IList<IEmployee> ReportsList { get { return _reports; } }
00032         public EmployeeCollection ReportsOC { get { return _reports; } }
00033         public EmployeeDictionary ReportsDict {  get { return _reportsDictionary; } }
00034
00035         public string NullStringProperty { get; set; }
00036         public Windows.UI.Xaml.Media.ImageSource NullImageSource
00037         {
00038             get { return null; }
00039             set { }
00040         }
00041
00042         public bool Visibility
00043         {
00044             get { return _employee.Visibility; }
00045             set
00046             {
00047                 if (_employee.Visibility != value)
00048                 {
00049                     _employee.Visibility = value;
00050                     NotifyPropertyChanged("Visibility");
00051                 }
00052             }
00053         }
00054         public string FirstName
00055         {
00056             get { return _employee.FirstName; }
00057             set
00058             {
00059                 if (value != _employee.FirstName)
00060                 {
00061                     _employee.FirstName = value;
00062                     NotifyPropertyChanged();
00063                     NotifyPropertyChanged("Name");
00064                 }
00065             }
00066         }
00067
00068         public string LastName
00069         {
00070             get { return _employee.LastName; }
00071             set
00072             {
00073                 if (value != _employee.LastName)
00074                 {
00075                     _employee.LastName = value;
00076                     NotifyPropertyChanged();
00077                     NotifyPropertyChanged("Name");
00078                 }
00079             }
00080         }
00081
00082         public Manager DirectManager
00083         {
00084             get { return _employee.DirectManager; }
00085             set
00086             {
00087                 if (value != _employee.DirectManager)
00088                 {
00089                     _employee.DirectManager = value;
00090                     NotifyPropertyChanged();
00091                 }
00092             }
00093         }
00094
00095         public void Poke(object sender, RoutedEventArgs e)
00096         {
00097             MessageDialog dlg = new MessageDialog("Employees of " + Name + " have been poked.");
00098             var t = dlg.ShowAsync();
00099         }
00100
00101         public bool IsManager { get { return true; } }
00102
00103         public String Title
00104         {
00105             get
00106             {
00107                 return "Manager";
00108             }
00109         }
00110
00111         public string Name { get { return FirstName + " " + LastName; } }
00112
00113         public string FullName() {  return FirstName + " " + LastName; }
00114
00115         #region INPC
00116
00117         public event PropertyChangedEventHandler PropertyChanged;
00118
00119         private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
00120         {
00121             if (PropertyChanged != null)
00122             {
00123                 PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
00124             }
00125         }
00126         #endregion
00127     }
00128 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ConnectTask Member List

This is the complete list of members for ConnectTask, including all inherited members.
DisplayToast(string ssid) | ConnectTask | [inline, private]
Run(IBackgroundTaskInstance taskInstance) | ConnectTask | [inline]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/PixelShader/App.h Source File

  • D2DCustomEffects
  • cpp
  • PixelShader

App.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "DeviceResources.h"
00016 #include "CustomPixelShaderMain.h"
00017
00018 namespace CustomPixelShader
00019 {
00020     // Main entry point for our app. Connects the app with the Windows shell and handles application lifecycle events.
00021     ref class App sealed : public Windows::ApplicationModel::Core::IFrameworkView
00022     {
00023     public:
00024         App();
00025
00026         // IFrameworkView Methods.
00027         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00028         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00029         virtual void Load(Platform::String^ entryPoint);
00030         virtual void Run();
00031         virtual void Uninitialize();
00032
00033     protected:
00034         // Application lifecycle event handlers.
00035         void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00036         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00037         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00038
00039         // Window event handlers.
00040         void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args);
00041         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00042         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00043         void OnPointerPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
00044
00045         // DisplayInformation event handlers.
00046         void OnDpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00047         void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00048         void OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00049
00050     private:
00051         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00052         std::unique_ptr<CustomPixelShaderMain> m_main;
00053         bool m_windowClosed;
00054         bool m_windowVisible;
00055     };
00056 }
00057
00058 ref class Direct3DApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00059 {
00060 public:
00061     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00062 };
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario11_DeleteCookie.cpp Source File

  • HttpClient
  • cppwinrt

Scenario11_DeleteCookie.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario11_DeleteCookie.h"
00014 #include "Scenario11_DeleteCookie.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace winrt::Windows::Foundation;
00018 using namespace winrt::Windows::UI::Xaml;
00019 using namespace winrt::Windows::Web::Http;
00020 using namespace winrt::Windows::Web::Http::Filters;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     Scenario11_DeleteCookie::Scenario11_DeleteCookie()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     void Scenario11_DeleteCookie::DeleteCookie_Click(IInspectable const&, RoutedEventArgs const&)
00030     {
00031         hstring name = NameField().Text();
00032         hstring domain = DomainField().Text();
00033         hstring path = PathField().Text();
00034
00035         if (name.empty() || domain.empty() || path.empty())
00036         {
00037             rootPage.NotifyUser(L"Invalid name, domain, or path value.", NotifyType::ErrorMessage);
00038             return;
00039         }
00040
00041         try
00042         {
00043             HttpCookie cookie(name, domain, path);
00044
00045             HttpBaseProtocolFilter filter;
00046             filter.CookieManager().DeleteCookie(cookie);
00047
00048             rootPage.NotifyUser(L"Cookie deleted.", NotifyType::StatusMessage);
00049         }
00050         catch (hresult_invalid_argument const& ex)
00051         {
00052             rootPage.NotifyUser(ex.message(), NotifyType::StatusMessage);
00053         }
00054         catch (hresult_error const& ex)
00055         {
00056             rootPage.NotifyUser(L"Error: " + ex.message(), NotifyType::ErrorMessage);
00057         }
00058     }
00059 }
Generated on Fri Nov 15 2024 22:19:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FolderEnumeration/cppwinrt/Project.idl Source File

  • FolderEnumeration
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1 : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2 : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3 : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3();
00030     }
00031
00032     [default_interface]
00033     runtimeclass Scenario4 : Windows.UI.Xaml.Controls.Page
00034     {
00035         Scenario4();
00036     }
00037 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Nfc/Nfc/ReceiptView.xaml.cs Source File

  • Nfc
  • Nfc

ReceiptView.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using Windows.Storage;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Media;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00020
00021 namespace NfcSample
00022 {
00023     /// <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026     public sealed partial class ReceiptView : Page
00027     {
00028         public ReceiptView()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         protected override void OnNavigatedTo(NavigationEventArgs e)
00034         {
00035             lblIcon.Text = "";
00036             lblStatus.Text = System.DateTime.Now.ToString() + "\r\n";
00037             lblResult.Text = "";
00038             if (e.Parameter is string)
00039             {
00040                 var args = ((string)e.Parameter).Split('^');
00041
00042                 if (args.Length >= 2)
00043                 {
00044                     lblResult.Text = args[1].ToUpper();
00045                     if (args[1] == "Failed")
00046                     {
00047                         // X
00048                         lblIcon.Text = "\uE10A";
00049                         lblIcon.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
00050                     }
00051                     else if (args[1] == "Complete")
00052                     {
00053                         // Checkmark
00054                         lblIcon.Text = "\uE001";
00055                         lblIcon.Foreground = new SolidColorBrush(Windows.UI.Colors.Green);
00056                     }
00057                     else if (args[1] == "Denied")
00058                     {
00059                         // !
00060                         lblIcon.Text = "\uE1DE";
00061                         lblIcon.Foreground = new SolidColorBrush(Windows.UI.Colors.Orange);
00062                     }
00063
00064                     if (args.Length >= 3)
00065                     {
00066                         lblStatus.Text += args[2];
00067                     }
00068                 }
00069             }
00070         }
00071
00072         private void btnMainMenu_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00073         {
00074             ((Frame)Windows.UI.Xaml.Window.Current.Content).Navigate(typeof(MainPage));
00075         }
00076
00077         private async void btnDebugLog_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00078         {
00079             var debugLogFile = (StorageFile)(await Windows.Storage.ApplicationData.Current.LocalFolder.TryGetItemAsync("DebugLog.txt"));
00080             if (debugLogFile != null)
00081             {
00082                 if (txtDebugLog.Visibility == Windows.UI.Xaml.Visibility.Visible)
00083                 {
00084                     // Log was already displayed, clear it
00085                     await debugLogFile.DeleteAsync();
00086                     txtDebugLog.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00087                     btnDebugLog.Content = "Debug Log";
00088                 }
00089                 else
00090                 {
00091                     // Display the log
00092                     txtDebugLog.Text = await FileIO.ReadTextAsync(debugLogFile);
00093                     txtDebugLog.Visibility = Windows.UI.Xaml.Visibility.Visible;
00094                     btnDebugLog.Content = "Clear Debug Log";
00095                 }
00096             }
00097         }
00098     }
00099 }
Generated on Fri Nov 15 2024 22:20:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cpp/BackgroundTransfer/Scenario2_Upload.xaml.h Source File

  • BackgroundTransfer
  • cpp
  • BackgroundTransfer

Scenario2_Upload.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_Upload.xaml.h
00014 // Declaration of the Scenario2_Upload class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario2_Upload.g.h"
00021 #include "MainPage.xaml.h"
00022 #include "Collection.h"
00023
00024 namespace SDKTemplate
00025 {
00026     /// <summary>
00027     /// An empty page that can be used on its own or navigated to within a Frame.
00028     /// </summary>
00029     [Windows::Foundation::Metadata::WebHostHidden]
00030     public ref class Scenario2_Upload sealed
00031     {
00032     public:
00033         Scenario2_Upload();
00034
00035     protected:
00036         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038     private:
00039         SDKTemplate::MainPage^ rootPage;
00040         Concurrency::cancellation_token_source* cancellationToken;
00041
00042         static const UINT32 maxUploadFileSize = 100 * 1024 * 1024; // 100 MB (arbitrary limit chosen for this sample)
00043
00044         ref class SizeCounter sealed
00045         {
00046         public:
00047             SizeCounter();
00048
00049             void Add(INT64 sizeValue);
00050
00051             INT64 GetSize();
00052
00053         private:
00054             INT64 size;
00055         };
00056
00057         void StartUpload_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00058         void StartMultipartUpload_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00059         void CancelAll_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00060         void DiscoverActiveUploads();
00061         void UploadProgress(
00062             Windows::Foundation::IAsyncOperationWithProgress<Windows::Networking::BackgroundTransfer::UploadOperation^, Windows::Networking::BackgroundTransfer::UploadOperation^>^ operation,
00063             Windows::Networking::BackgroundTransfer::UploadOperation^);
00064         void HandleUploadAsync(Windows::Networking::BackgroundTransfer::UploadOperation^ upload, bool start);
00065         void LogException(Platform::String^ title, Platform::Exception^ ex);
00066         void MarshalLog(Platform::String^ value);
00067         void Log(Platform::String^ message);
00068         void LogStatus(Platform::String^ message, SDKTemplate::NotifyType type);
00069
00070         Concurrency::task<void> UploadSingleFileAsync(Windows::Foundation::Uri^ uri, Windows::Storage::IStorageFile^ file);
00071         Concurrency::task<void> UploadMultipleFilesAsync(
00072             Windows::Foundation::Uri^ uri,
00073             Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile^>^ files);
00074         Concurrency::task<Platform::Collections::Vector<Windows::Networking::BackgroundTransfer::BackgroundTransferContentPart^>^> CreatePartsAsync(
00075             Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile^>^ files);
00076
00077         ~Scenario2_Upload();
00078     };
00079 }
Generated on Fri Nov 15 2024 22:18:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cpp/Scenario1_Events.xaml.cpp Source File

  • Pedometer
  • cpp

Scenario1_Events.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_Events.xaml.h"
00014
00015 const unsigned int HundredNanoSecondsToMilliseconds = 10000;
00016
00017 using namespace SDKTemplate;
00018
00019 using namespace Concurrency;
00020 using namespace Platform;
00021 using namespace Windows::Devices::Enumeration;
00022 using namespace Windows::Devices::Sensors;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::Globalization::DateTimeFormatting;
00026 using namespace Windows::UI::Core;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Controls::Primitives;
00030 using namespace Windows::UI::Xaml::Data;
00031 using namespace Windows::UI::Xaml::Input;
00032 using namespace Windows::UI::Xaml::Media;
00033 using namespace Windows::UI::Xaml::Navigation;
00034
00035 Scenario1_Events::Scenario1_Events() : rootPage(MainPage::Current)
00036 {
00037     InitializeComponent();
00038
00039     // Disable the 'Register' button until we have a pedometer
00040     RegisterButton->IsEnabled = false;
00041
00042     // Determine if we can access pedometers
00043     deviceAccessInfo = DeviceAccessInformation::CreateFromDeviceClassId(GUID_Pedometer_ClassId);
00044     if (deviceAccessInfo->CurrentStatus == DeviceAccessStatus::Allowed)
00045     {
00046         // Access is allowed. Register for access change notifications
00047         deviceAccessInfo->AccessChanged += ref new TypedEventHandler<DeviceAccessInformation ^, DeviceAccessChangedEventArgs ^>(this, &Scenario1_Events::OnAccessChanged);
00048
00049         rootPage->NotifyUser("Waiting for Default Pedometer (Pedometer::GetDefaultAsync)", NotifyType::StatusMessage);
00050
00051         // Get the default pedometer asynchronously
00052         create_task(Pedometer::GetDefaultAsync).then([this](task<Pedometer^> task)
00053         {
00054             pedometer = task.get();
00055             if (nullptr != pedometer)
00056             {
00057                 rootPage->NotifyUser("Pedometer available - Not registered for events", NotifyType::StatusMessage);
00058                 RegisterButton->IsEnabled = true;
00059             }
00060             else
00061             {
00062                 rootPage->NotifyUser("No pedometers available", NotifyType::ErrorMessage);
00063                 RegisterButton->IsEnabled = false;
00064             }
00065         });
00066     }
00067     else
00068     {
00069         rootPage->NotifyUser("Access to pedometer is denied", NotifyType::ErrorMessage);
00070         RegisterButton->IsEnabled = false;
00071     }
00072
00073     registeredForEvents = false;
00074 }
00075
00076 /// <summary>
00077 /// 'Register ReadingChanged' button click handler. Registers for the '
00078 /// ReadingChanged' event of the default pedometer opened earlier.
00079 /// </summary>
00080 /// <param name="sender">unused</param>
00081 /// <param name="e">unused</param>
00082 void Scenario1_Events::Button_Click(Platform::Object^ /*sender*/, Windows::UI::Xaml::RoutedEventArgs^ /*e*/)
00083 {
00084     UpdateEventRegistration(!registeredForEvents);
00085 }
00086
00087 /// <summary>
00088 /// Invoked when navigating away from this page - unregisters for 'ReadingChanged' event.
00089 /// </summary>
00090 /// <param name="e">unused</param>
00091 void Scenario1_Events::OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ /*e*/)
00092 {
00093     if (registeredForEvents)
00094     {
00095         UpdateEventRegistration(false);
00096     }
00097 }
00098
00099 /// <summary>
00100 /// Invoked when the access to pedometers has changed
00101 /// </summary>
00102 /// <param name="sender"></param>
00103 /// <param name="e"></param>
00104 void Scenario1_Events::OnAccessChanged(DeviceAccessInformation ^sender, DeviceAccessChangedEventArgs ^args)
00105 {
00106     if (args->Status != DeviceAccessStatus::Allowed)
00107     {
00108         pedometer = nullptr;
00109
00110         Dispatcher->RunAsync(
00111             CoreDispatcherPriority::Normal,
00112             ref new DispatchedHandler(
00113                 [this]()
00114         {
00115             if (registeredForEvents)
00116             {
00117                 UpdateEventRegistration(false);
00118             }
00119
00120             rootPage->NotifyUser("Access to the pedometer has been denied", NotifyType::ErrorMessage);
00121         },
00122         CallbackContext::Any));
00123     }
00124 }
00125
00126 /// <summary>
00127 /// Invoked when the underlying Pedometer sees a change in the step count for a step kind
00128 /// </summary>
00129 /// <param name="sender">unused</param>
00130 /// <param name="args">Pedometer reading that is being notified</param>
00131 void Scenario1_Events::OnReadingChanged(Windows::Devices::Sensors::Pedometer ^/*sender*/, Windows::Devices::Sensors::PedometerReadingChangedEventArgs ^args)
00132 {
00133     // We need to dispatch to the UI thread to display the output
00134     Dispatcher->RunAsync(
00135         CoreDispatcherPriority::Normal,
00136         ref new DispatchedHandler(
00137         [this, args]()
00138         {
00139             PedometerReading^ reading = args->Reading;
00140             int32 newCount = 0;
00141             long long duration = 0;
00142
00143             // update step counts based on the step kind
00144             switch (reading->StepKind)
00145             {
00146             case PedometerStepKind::Unknown:
00147                 if (reading->CumulativeSteps < unknownStepCount)
00148                 {
00149                     unknownStepCount = 0;
00150                 }
00151                 newCount = reading->CumulativeSteps - unknownStepCount;
00152                 unknownStepCount = reading->CumulativeSteps;
00153                 ScenarioOutput_UnknownCount->Text = unknownStepCount.ToString();
00154                 duration = reading->CumulativeStepsDuration.Duration / HundredNanoSecondsToMilliseconds;
00155                 ScenarioOutput_UnknownDuration->Text = duration.ToString();
00156                 break;
00157             case PedometerStepKind::Walking:
00158                 if (reading->CumulativeSteps < walkingStepCount)
00159                 {
00160                     walkingStepCount = 0;
00161                 }
00162                 newCount = reading->CumulativeSteps - walkingStepCount;
00163                 walkingStepCount = reading->CumulativeSteps;
00164                 ScenarioOutput_WalkingCount->Text = walkingStepCount.ToString();
00165                 duration = reading->CumulativeStepsDuration.Duration / HundredNanoSecondsToMilliseconds;
00166                 ScenarioOutput_WalkingDuration->Text = duration.ToString();
00167                 break;
00168             case PedometerStepKind::Running:
00169                 if (reading->CumulativeSteps < runningStepCount)
00170                 {
00171                     runningStepCount = 0;
00172                 }
00173                 newCount = reading->CumulativeSteps - runningStepCount;
00174                 runningStepCount = reading->CumulativeSteps;
00175                 ScenarioOutput_RunningCount->Text = runningStepCount.ToString();
00176                 duration = reading->CumulativeStepsDuration.Duration / HundredNanoSecondsToMilliseconds;
00177                 ScenarioOutput_RunningDuration->Text = duration.ToString();
00178                 break;
00179             default:
00180                 break;
00181             }
00182
00183             totalCumulativeSteps += newCount;
00184             ScenarioOutput_TotalStepCount->Text = totalCumulativeSteps.ToString();
00185
00186             auto timestampFormatter = ref new DateTimeFormatter("day month year hour minute second");
00187             ScenarioOutput_Timestamp->Text = timestampFormatter->Format(reading->Timestamp);
00188         },
00189         CallbackContext::Any
00190         )
00191     );
00192 }
00193
00194 /// <summary>
00195 /// Helper function to register/un-register to the 'ReadingChanged' event of the default pedometer
00196 /// </summary>
00197 /// <param name="registerForEvents">tell if a registration or un-registration actions needs to be taken</param>
00198 void Scenario1_Events::UpdateEventRegistration(bool registerForEvents)
00199 {
00200     if (registerForEvents)
00201     {
00202         if (pedometer != nullptr)
00203         {
00204             pedometer->ReportInterval = pedometer->MinimumReportInterval;
00205             readingToken = (pedometer->ReadingChanged += ref new Windows::Foundation::TypedEventHandler<Windows::Devices::Sensors::Pedometer ^, Windows::Devices::Sensors::PedometerReadingChangedEventArgs ^>(this, &Scenario1_Events::OnReadingChanged));
00206             rootPage->NotifyUser("Registered for step count changes", NotifyType::StatusMessage);
00207             registeredForEvents = true;
00208             RegisterButton->Content = "Un-Register ReadingChanged";
00209         }
00210     }
00211     else
00212     {
00213         if (pedometer != nullptr)
00214         {
00215             pedometer->ReadingChanged -= readingToken;
00216             rootPage->NotifyUser("Pedometer available - Not registered for events", NotifyType::StatusMessage);
00217         }
00218
00219         registeredForEvents = false;
00220         RegisterButton->Content = "Register ReadingChanged";
00221     }
00222 }
Generated on Fri Nov 15 2024 22:20:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSegmentation/cppwinrt/Scenario1_ExtractTextSegments.cpp Source File

  • TextSegmentation
  • cppwinrt

Scenario1_ExtractTextSegments.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_ExtractTextSegments.h"
00014 #include "Scenario1_ExtractTextSegments.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace winrt::Windows::Foundation;
00018 using namespace winrt::Windows::UI::Xaml;
00019
00020 namespace winrt::SDKTemplate::implementation
00021 {
00022     Scenario1_ExtractTextSegments::Scenario1_ExtractTextSegments()
00023     {
00024         InitializeComponent();
00025     }
00026
00027     // This is the click handler for the 'Word Segments' button.
00028     //
00029     // When this button is activated, the Text Segmentation API will calculate
00030     // the word segments from the given input string and language tag, and then
00031     // print out the word and alternate-form segments for that language.
00032     void Scenario1_ExtractTextSegments::WordSegmentsButton_Click(IInspectable const&, RoutedEventArgs const&)
00033     {
00034         std::wostringstream result;
00035
00036         // Obtain the input string value, check for non-emptiness
00037         hstring inputStringText = inputStringBox().Text();
00038         if (inputStringText.empty())
00039         {
00040             rootPage.NotifyUser(L"Cannot compute word selection segments: input string is empty.", NotifyType::ErrorMessage);
00041             return;
00042         }
00043
00044         // Obtain the language tag value, check for non-emptiness
00045         // Ex. Valid Values:
00046         //     "en-US" (English (United States))
00047         //     "fr-FR" (French (France))
00048         //     "de-DE" (German (Germany))
00049         //     "ja-JP" (Japanese (Japan))
00050         //     "ar-SA" (Arabic (Saudi Arabia))
00051         //     "zh-CN" (China (PRC))
00052         hstring languageTagText = languageTagBox().Text();
00053         if (languageTagText.empty())
00054         {
00055             result << L"Language tag input is empty ... using generic-language segmentation rules.\n";
00056             languageTagText = L"und";   // This is used for non language-specific locales. 'und' is short for 'undetermined'.
00057         }
00058         else
00059         {
00060             if (!Windows::Globalization::Language::IsWellFormed(languageTagText))
00061             {
00062                 rootPage.NotifyUser(L"Language tag is not well formed: \"" + languageTagText + L"\"", NotifyType::ErrorMessage);
00063                 return;
00064             }
00065         }
00066
00067         // Notify that we are going to calculate word segments
00068         result
00069             << L"\nCalculating word segments ...\n\n"
00070             << L"Input: \"" << std::wstring_view(inputStringText) << L"\"\n"
00071             << L"Language Tag: \"" << std::wstring_view(languageTagText) << L"\"\n";
00072
00073         // Construct the WordsSegmenter instance
00074         Windows::Data::Text::WordsSegmenter segmenter(languageTagText);
00075         auto wordSegments = segmenter.GetTokens(inputStringText);
00076
00077         // Iterate over the tokenized segments
00078         for (auto&& wordSegment : wordSegments)
00079         {
00080             result << L"\tWord---->\"" << std::wstring_view(wordSegment.Text()) << L"\"\n";
00081             for  (auto&& alternateForm : wordSegment.AlternateForms())
00082             {
00083                 result << L"\t\tAlternate---->\"" << std::wstring_view(alternateForm.AlternateText()) << L"\"\n";
00084             }
00085         }
00086
00087         // Set results to output box
00088         rootPage.NotifyUser(result.str(), NotifyType::StatusMessage);
00089     }
00090
00091     // This is the click handler for the 'Selection Segments' button.
00092     //
00093     // When this button is activated, the Text Segmentation API will calculate
00094     // the selection segments from the given input string and language tag, and then
00095     // print out the word and alternate-form segments for that language.
00096     //
00097     // Selection segments differ from word segments in that they describe the bounds
00098     // between active-selection snapping behavior.
00099     void Scenario1_ExtractTextSegments::SelectionSegmentsButton_Click(IInspectable const&, RoutedEventArgs const&)
00100     {
00101         std::wostringstream result;
00102
00103         // Obtain the input string value, check for non-emptiness
00104         hstring inputStringText = inputStringBox().Text();
00105         if (inputStringText.empty())
00106         {
00107             rootPage.NotifyUser(L"Cannot compute selection segments: input string is empty.", NotifyType::ErrorMessage);
00108             return;
00109         }
00110
00111         // Obtain the language tag value, check for non-emptiness
00112         // Ex. Valid Values:
00113         //     "en-US" (English (United States))
00114         //     "fr-FR" (French (France))
00115         //     "de-DE" (German (Germany))
00116         //     "ja-JP" (Japanese (Japan))
00117         //     "ar-SA" (Arabic (Saudi Arabia))
00118         //     "zh-CN" (China (PRC))
00119         hstring languageTagText = languageTagBox().Text();
00120         if (languageTagText.empty())
00121         {
00122             result << L"Language tag input is empty ... using generic-language segmentation rules.\n";
00123             languageTagText = L"und";   // This is used for non language-specific locales. 'und' is short for 'undetermined'.
00124         }
00125         else
00126         {
00127             if (!Windows::Globalization::Language::IsWellFormed(languageTagText))
00128             {
00129                 rootPage.NotifyUser(L"Language tag is not well formed: \"" + languageTagText + L"\"", NotifyType::ErrorMessage);
00130                 return;
00131             }
00132         }
00133
00134         // Notify that we are going to calculate selection segments
00135         result
00136             << L"\nCalculating selection segments ...\n\n"
00137             << L"Input: \"" << std::wstring_view(inputStringText) << L"\"\n"
00138             << L"Language Tag: \"" << std::wstring_view(languageTagText) << L"\"\n";
00139
00140         // Construct the SelectableWordsSegmenter instance
00141         Windows::Data::Text::SelectableWordsSegmenter segmenter(languageTagText);
00142         auto selectionSegments = segmenter.GetTokens(inputStringText);
00143
00144         // Iterate over the tokenized segments
00145         for (auto&& selectionSegment : selectionSegments)
00146         {
00147             result << L"\tWord---->\"" << std::wstring_view(selectionSegment.Text()) << L"\"\n";
00148         }
00149
00150         // Set results to output box
00151         rootPage.NotifyUser(result.str(), NotifyType::StatusMessage);
00152     }
00153 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/OtherBindings.xaml.cpp Source File

  • XamlBind
  • cpp

OtherBindings.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // OtherBindings.xaml.cpp
00003 // Implementation of the OtherBindings class
00004 //
00005
00006 #include "pch.h"
00007 #include "OtherBindings.xaml.h"
00008
00009 using namespace SDKTemplate;
00010
00011 using namespace Platform;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::UI::Xaml;
00015 using namespace Windows::UI::Xaml::Controls;
00016 using namespace Windows::UI::Xaml::Controls::Primitives;
00017 using namespace Windows::UI::Xaml::Data;
00018 using namespace Windows::UI::Xaml::Input;
00019 using namespace Windows::UI::Xaml::Media;
00020 using namespace Windows::UI::Xaml::Navigation;
00021 using namespace Windows::UI::Xaml::Interop;
00022
00023 using namespace xBindSampleModel;
00024
00025 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00026
00027 OtherBindings::OtherBindings()
00028 {
00029     Model = ref new DataModel();
00030     InitializeComponent();
00031     InitializeValues();
00032 }
00033
00034 DependencyProperty^ OtherBindings::_DPOnPage = DependencyProperty::Register("DPOnPage", TypeName(::Platform::String::typeid), TypeName(OtherBindings::typeid), nullptr);
00035
00036
00037 void OtherBindings::InitializeValues()
00038 {
00039     this->DPOnPage = "DP on page";
00040 }
00041
00042 void OtherBindings::UpdateValuesClick(Object^ sender, ::Windows::UI::Xaml::RoutedEventArgs^ e)
00043 {
00044     this->Model->UpdateValues();
00045     this->DPOnPage += "-";
00046     this->MyInt += 1;
00047 }
00048
00049 void OtherBindings::ResetValuesClick(Object^ sender, ::Windows::UI::Xaml::RoutedEventArgs^ e)
00050 {
00051     this->Model->InitializeValues();
00052     this->InitializeValues();
00053     this->MyInt = 0;
00054 }
00055
00056 void OtherBindings::UndeferElementClick(Object^ sender, ::Windows::UI::Xaml::RoutedEventArgs^ e)
00057 {
00058     this->FindName("deferedTextBlock");
00059 }
Generated on Fri Nov 15 2024 22:22:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_UserCollection Member List

This is the complete list of members for Scenario5_UserCollection, including all inherited members.
GetUserCollectionButton_Click(object sender, RoutedEventArgs e) | Scenario5_UserCollection | [inline, private]
rootPage | Scenario5_UserCollection | [private]
Scenario5_UserCollection() | Scenario5_UserCollection | [inline]
storeContext | Scenario5_UserCollection | [private]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MultipleViews/cppwinrt/Scenario1.h Source File

  • MultipleViews
  • cppwinrt

Scenario1.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1 : Scenario1T<Scenario1>
00020     {
00021         Scenario1();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00024
00025         fire_and_forget CreateView_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00026         fire_and_forget ShowAsStandalone_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00027
00028     private:
00029         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00030
00031         static Windows::Foundation::Collections::IObservableVector<Windows::Foundation::IInspectable> GenerateSizePreferenceBinding();
00032     };
00033 }
00034
00035 namespace winrt::SDKTemplate::factory_implementation
00036 {
00037     struct Scenario1 : Scenario1T<Scenario1, implementation::Scenario1>
00038     {
00039     };
00040 }
Generated on Fri Nov 15 2024 22:19:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Json/cppwinrt/User.h Source File

  • Json
  • cppwinrt

User.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include <winrt/SDKTemplate.h>
00014 #include "User.g.h"
00015
00016 using namespace winrt;
00017 using namespace winrt::Windows::Data::Json;
00018 using namespace winrt::Windows::Foundation::Collections;
00019
00020 namespace winrt::SDKTemplate::implementation
00021 {
00022     struct User : UserT<User>
00023     {
00024         User() = default;
00025         User(hstring const& jsonString);
00026
00027         hstring Id() { return m_id; }
00028         void Id(hstring const& value) { m_id = value; }
00029         hstring Phone() { return m_phone; }
00030         void Phone(hstring const& value) { m_phone = value; }
00031         hstring Name() { return m_name; }
00032         void Name(hstring const& value) { m_name = value; }
00033         Windows::Foundation::Collections::IObservableVector<SDKTemplate::School> Education() { return m_education; }
00034         double Timezone() { return m_timezone; }
00035         void Timezone(double value) { m_timezone = value; }
00036         bool Verified() { return m_verified; }
00037         void Verified(bool value) { m_verified = value; }
00038         hstring Stringify();
00039
00040     private:
00041         static constexpr inline wchar_t idKey[] = L"id";
00042         static constexpr inline wchar_t phoneKey[] = L"phone";
00043         static constexpr inline wchar_t nameKey[] = L"name";
00044         static constexpr inline wchar_t educationKey[] = L"education";
00045         static constexpr inline wchar_t timezoneKey[] = L"timezone";
00046         static constexpr inline wchar_t verifiedKey[] = L"verified";
00047
00048         hstring m_id;
00049         hstring m_phone;
00050         hstring m_name;
00051         Windows::Foundation::Collections::IObservableVector<winrt::SDKTemplate::School> m_education = single_threaded_observable_vector<SDKTemplate::School>();
00052         double m_timezone = 0.0;
00053         bool m_verified = false;
00054     };
00055 }
00056 namespace winrt::SDKTemplate::factory_implementation
00057 {
00058     struct User : UserT<User, implementation::User>
00059     {
00060     };
00061 }
Generated on Fri Nov 15 2024 22:20:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AudioFileReader Member List

This is the complete list of members for AudioFileReader, including all inherited members.
_audioData | AudioFileReader | [private]
_format | AudioFileReader | [private]
GetData() const | AudioFileReader | [inline]
GetData() const | AudioFileReader | [inline]
GetFormat() const | AudioFileReader | [inline]
GetFormat() const | AudioFileReader | [inline]
GetSize() const | AudioFileReader | [inline]
GetSize() const | AudioFileReader | [inline]
Initialize(_In_ LPCWSTR filename) | AudioFileReader |
Initialize(_In_ LPCWSTR filename) | AudioFileReader |
~AudioFileReader() | AudioFileReader | [inline, virtual]
~AudioFileReader() | AudioFileReader | [inline, virtual]
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ProtectionLevelSelectorInfo Member List

This is the complete list of members for ProtectionLevelSelectorInfo, including all inherited members.
displayName | ProtectionLevelSelectorInfo | [private]
DisplayName() | ProtectionLevelSelectorInfo | [inline]
protectionLevel | ProtectionLevelSelectorInfo | [private]
ProtectionLevel() | ProtectionLevelSelectorInfo | [inline]
ProtectionLevelSelectorInfo(hstring displayName, Windows::Devices::Enumeration::DevicePairingProtectionLevel protectionLevel) | ProtectionLevelSelectorInfo | [inline]
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCorrelation/cpp/SampleConfiguration.h Source File

  • CameraStreamCorrelation
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Camera Stream Correlation C++/cx Sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 } // SDKTemplate
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_ConnectDisconnect Member List

This is the complete list of members for Scenario1_ConnectDisconnect, including all inherited members.
AddDeviceToList(DeviceInformation deviceInformation, String deviceSelector) | Scenario1_ConnectDisconnect | [inline, private]
AddDeviceWatcher(DeviceWatcher deviceWatcher, String deviceSelector) | Scenario1_ConnectDisconnect | [inline, private]
appResumeEventHandler | Scenario1_ConnectDisconnect | [private]
appSuspendEventHandler | Scenario1_ConnectDisconnect | [private]
ButtonNameDisableReconnectToDevice | Scenario1_ConnectDisconnect | [private]
ButtonNameDisconnectFromDevice | Scenario1_ConnectDisconnect | [private]
ClearDeviceEntries() | Scenario1_ConnectDisconnect | [inline, private]
ConnectToDevice_Click(Object sender, RoutedEventArgs eventArgs) | Scenario1_ConnectDisconnect | [inline, private]
DisconnectFromDevice_Click(Object sender, RoutedEventArgs eventArgs) | Scenario1_ConnectDisconnect | [inline, private]
FindDevice(String deviceId) | Scenario1_ConnectDisconnect | [inline, private]
InitializeDeviceWatchers() | Scenario1_ConnectDisconnect | [inline, private]
isAllDevicesEnumerated | Scenario1_ConnectDisconnect | [private]
listOfDevices | Scenario1_ConnectDisconnect | [private]
mapDeviceWatchersToDeviceSelector | Scenario1_ConnectDisconnect | [private]
OnAppResume(Object sender, Object args) | Scenario1_ConnectDisconnect | [inline, private]
OnAppSuspension(Object sender, SuspendingEventArgs args) | Scenario1_ConnectDisconnect | [inline, private]
OnDeviceAdded(DeviceWatcher sender, DeviceInformation deviceInformation) | Scenario1_ConnectDisconnect | [inline, private]
OnDeviceClosing(EventHandlerForDevice sender, DeviceInformation deviceInformation) | Scenario1_ConnectDisconnect | [inline, private]
OnDeviceConnected(EventHandlerForDevice sender, DeviceInformation deviceInformation) | Scenario1_ConnectDisconnect | [inline, private]
OnDeviceEnumerationComplete(DeviceWatcher sender, Object args) | Scenario1_ConnectDisconnect | [inline, private]
OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceInformationUpdate) | Scenario1_ConnectDisconnect | [inline, private]
OnNavigatedFrom(NavigationEventArgs eventArgs) | Scenario1_ConnectDisconnect | [inline, protected]
OnNavigatedTo(NavigationEventArgs eventArgs) | Scenario1_ConnectDisconnect | [inline, protected]
RemoveDeviceFromList(String deviceId) | Scenario1_ConnectDisconnect | [inline, private]
rootPage | Scenario1_ConnectDisconnect | [private]
Scenario1_ConnectDisconnect() | Scenario1_ConnectDisconnect | [inline]
SelectDeviceInList(String deviceIdToSelect) | Scenario1_ConnectDisconnect | [inline, private]
StartDeviceWatchers() | Scenario1_ConnectDisconnect | [inline, private]
StartHandlingAppEvents() | Scenario1_ConnectDisconnect | [inline, private]
StopDeviceWatchers() | Scenario1_ConnectDisconnect | [inline, private]
StopHandlingAppEvents() | Scenario1_ConnectDisconnect | [inline, private]
UpdateConnectDisconnectButtonsAndList(Boolean enableConnectButton) | Scenario1_ConnectDisconnect | [inline, private]
watchersStarted | Scenario1_ConnectDisconnect | [private]
watchersSuspended | Scenario1_ConnectDisconnect | [private]
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlFocusVisuals/cs/SampleConfiguration.cs Source File

  • XamlFocusVisuals
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using FocusVisualsSample;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Focus Visuals Sample";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Using custom focus visuals", ClassType=typeof(CustomFocusVisuals)},
00026             new Scenario() { Title="Applying to custom controls", ClassType=typeof(CustomControlUsage)}
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDragAndDrop/cpp/SampleConfiguration.cpp Source File

  • XamlDragAndDrop
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "ListView Drag and Drop and Reorder", "SDKTemplate.Scenario1_ListView" },
00021     { "Drag UI Customization", "SDKTemplate.Scenario2_DragUICustomization" },
00022     { "StartDragAsync", "SDKTemplate.Scenario3_StartDragAsync" }
00023 };
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicFaceDetection/cppwinrt/Scenario2_DetectInWebcam.cpp Source File

  • BasicFaceDetection
  • cppwinrt

Scenario2_DetectInWebcam.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_DetectInWebcam.h"
00014 #include "Scenario2_DetectInWebcam.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::ApplicationModel;
00019 using namespace winrt::Windows::Foundation;
00020 using namespace winrt::Windows::Foundation::Collections;
00021 using namespace winrt::Windows::Graphics::Imaging;
00022 using namespace winrt::Windows::Media;
00023 using namespace winrt::Windows::Media::Capture;
00024 using namespace winrt::Windows::Media::FaceAnalysis;
00025 using namespace winrt::Windows::Media::MediaProperties;
00026 using namespace winrt::Windows::UI::Xaml;
00027 using namespace winrt::Windows::UI::Xaml::Media;
00028 using namespace winrt::Windows::UI::Xaml::Media::Imaging;
00029 using namespace winrt::Windows::UI::Xaml::Navigation;
00030
00031 namespace winrt::SDKTemplate::implementation
00032 {
00033     Scenario2_DetectInWebcam::Scenario2_DetectInWebcam()
00034     {
00035         InitializeComponent();
00036     }
00037
00038     void Scenario2_DetectInWebcam::OnNavigatedTo(NavigationEventArgs const&)
00039     {
00040         suspendingEventToken = Application::Current().Suspending({ get_weak(), &Scenario2_DetectInWebcam::OnSuspending });
00041     }
00042
00043     void Scenario2_DetectInWebcam::OnNavigatedFrom(NavigationEventArgs const&)
00044     {
00045         Application::Current().Suspending(suspendingEventToken);
00046     }
00047
00048     // Responds to App Suspend event to stop/release MediaCapture object if it's running and return to Idle state.
00049     fire_and_forget Scenario2_DetectInWebcam::OnSuspending(IInspectable const&, SuspendingEventArgs const& e)
00050     {
00051         auto lifetime = get_strong();
00052
00053         if (currentState == ScenarioState::Streaming)
00054         {
00055             auto deferral = e.SuspendingOperation().GetDeferral();
00056             co_await ChangeScenarioStateAsync(ScenarioState::Idle);
00057             deferral.Complete();
00058         }
00059     }
00060
00061     // Creates the FaceDetector object which we will use for face detection.
00062     // Initializes a new MediaCapture instance and starts the Preview streaming to the CamPreview UI element.
00063     // Completes with true if initialization and streaming were successful and false if an exception occurred.
00064     IAsyncOperation<bool> Scenario2_DetectInWebcam::StartWebcamStreamingAsync()
00065     {
00066         auto lifetime = get_strong();
00067
00068         bool successful;
00069
00070         faceDetector = co_await FaceDetector::CreateAsync();
00071         try
00072         {
00073             MediaCapture mediaCapture;
00074             agileMediaCapture = mediaCapture;
00075             MediaCaptureInitializationSettings settings;
00076
00077             // For this scenario, we only need Video (not microphone) so specify this in the initializer.
00078             // NOTE: the appxmanifest only declares "webcam" under capabilities and if this is changed to include
00079             // microphone (default constructor) you must add "microphone" to the manifest or initialization will fail.
00080             settings.StreamingCaptureMode(StreamingCaptureMode::Video);
00081
00082             co_await mediaCapture.InitializeAsync(settings);
00083             mediaCapture.CameraStreamStateChanged({ get_weak(), &Scenario2_DetectInWebcam::MediaCapture_CameraStreamStateChanged });
00084
00085             // Cache the media properties as we'll need them later.
00086             auto deviceController = mediaCapture.VideoDeviceController();
00087             videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType::VideoPreview).as<VideoEncodingProperties>();
00088
00089             // Immediately start streaming to our CaptureElement UI.
00090             // NOTE: CaptureElement's Source must be set before streaming is started.
00091             CamPreview().Source(mediaCapture);
00092             co_await mediaCapture.StartPreviewAsync();
00093
00094             successful = true;
00095         }
00096         catch (hresult_access_denied const&)
00097         {
00098             // If the user has disabled their webcam this exception is thrown; provide a descriptive message to inform the user of this fact.
00099             rootPage.NotifyUser(L"Webcam is disabled or access to the webcam is disabled for this app.\nEnsure Privacy Settings allow webcam usage.", NotifyType::ErrorMessage);
00100             successful = false;
00101         }
00102         catch (hresult_error const& ex)
00103         {
00104             rootPage.NotifyUser(ex.message(), NotifyType::ErrorMessage);
00105             successful = false;
00106         }
00107
00108         co_return successful;
00109     }
00110
00111     // Safely stops webcam streaming (if running) and releases MediaCapture object.
00112     IAsyncAction Scenario2_DetectInWebcam::ShutdownWebcamAsync()
00113     {
00114         auto lifetime = get_strong();
00115
00116         if (agileMediaCapture)
00117         {
00118             auto mediaCapture = agileMediaCapture.get();
00119             if (mediaCapture.CameraStreamState() == Windows::Media::Devices::CameraStreamState::Streaming)
00120             {
00121                 try
00122                 {
00123                     co_await mediaCapture.StopPreviewAsync();
00124                 }
00125                 catch (hresult_error const&)
00126                 {
00127                     // Since we're going to destroy the MediaCapture object there's nothing to do here
00128                 }
00129             }
00130             mediaCapture.Close();
00131         }
00132
00133         CamPreview().Source(nullptr);
00134         agileMediaCapture = nullptr;
00135     }
00136
00137     // Captures a single frame from the running webcam stream and executes the FaceDetector on the image. If successful calls SetupVisualization to display the results.
00138     IAsyncOperation<bool> Scenario2_DetectInWebcam::TakeSnapshotAndFindFacesAsync()
00139     {
00140         auto lifetime = get_strong();
00141
00142         if (currentState != ScenarioState::Streaming)
00143         {
00144             co_return false;
00145         }
00146
00147         bool successful = false;
00148
00149         try
00150         {
00151             // Create a VideoFrame object specifying the pixel format we want our capture image to be (NV12 bitmap in this case).
00152             // GetPreviewFrame will convert the native webcam frame into this format.
00153             static constexpr BitmapPixelFormat InputPixelFormat = BitmapPixelFormat::Nv12;
00154             VideoFrame previewFrame(InputPixelFormat, (int)videoProperties.Width(), (int)videoProperties.Height());
00155
00156             co_await agileMediaCapture.get().GetPreviewFrameAsync(previewFrame);
00157
00158             // The returned VideoFrame should be in the supported NV12 format but we need to verify
00159             if (FaceDetector::IsBitmapPixelFormatSupported(previewFrame.SoftwareBitmap().BitmapPixelFormat()))
00160             {
00161                 IVector<DetectedFace> faces = co_await faceDetector.DetectFacesAsync(previewFrame.SoftwareBitmap());
00162
00163                 // Create a WritableBitmap for our visualization display; copy the original bitmap pixels to wb's buffer.
00164                 // Note that WriteableBitmap doesn't support NV12 and we have to convert it to 32-bit BGRA.
00165                 SoftwareBitmap convertedSource = SoftwareBitmap::Convert(previewFrame.SoftwareBitmap(), BitmapPixelFormat::Bgra8);
00166                 WriteableBitmap displaySource(convertedSource.PixelWidth(), convertedSource.PixelHeight());
00167                 convertedSource.CopyToBuffer(displaySource.PixelBuffer());
00168
00169                 // Create our display using the available image and face results.
00170                 SetupVisualization(displaySource, faces);
00171
00172                 successful = true;
00173             }
00174             else
00175             {
00176                 rootPage.NotifyUser(L"PixelFormat 'NV12' is not supported by FaceDetector", NotifyType::ErrorMessage);
00177             }
00178         }
00179         catch (hresult_error const& ex)
00180         {
00181             rootPage.NotifyUser(ex.message(), NotifyType::ErrorMessage);
00182         }
00183
00184         co_return successful;
00185     }
00186
00187     // Takes the webcam image and FaceTracker results and assembles the visualization onto the Canvas.
00188     void Scenario2_DetectInWebcam::SetupVisualization(WriteableBitmap const& displaySource, IVector<DetectedFace> const& foundFaces)
00189     {
00190         ImageBrush brush;
00191         brush.ImageSource(displaySource);
00192         brush.Stretch(Stretch::Fill);
00193         SnapshotCanvas().Background(brush);
00194
00195         SampleHelpers::HighlightFaces(displaySource, foundFaces, SnapshotCanvas(), HighlightedFaceBox());
00196     }
00197
00198     // Manages the scenario's internal state. Invokes the internal methods and updates the UI according to the
00199     // passed in state value. Handles failures and resets the state if necessary.
00200     IAsyncAction Scenario2_DetectInWebcam::ChangeScenarioStateAsync(ScenarioState newState)
00201     {
00202         auto lifetime = get_strong();
00203
00204         switch (newState)
00205         {
00206         case ScenarioState::Idle:
00207
00208             CameraSnapshotButton().IsEnabled(false);
00209             currentState = newState;
00210             co_await ShutdownWebcamAsync();
00211
00212             SnapshotCanvas().Background(nullptr);
00213             SnapshotCanvas().Children().Clear();
00214             CameraStreamingButton().Content(box_value(L"Start Streaming"));
00215             CameraSnapshotButton().Content(box_value(L"Take Snapshot"));
00216             break;
00217
00218         case ScenarioState::Streaming:
00219
00220             if (!co_await StartWebcamStreamingAsync())
00221             {
00222                 co_await ChangeScenarioStateAsync(ScenarioState::Idle);
00223                 break;
00224             }
00225
00226             SnapshotCanvas().Background(nullptr);
00227             SnapshotCanvas().Children().Clear();
00228             CameraSnapshotButton().IsEnabled(true);
00229             CameraStreamingButton().Content(box_value(L"Stop Streaming"));
00230             CameraSnapshotButton().Content(box_value(L"Take Snapshot"));
00231             currentState = newState;
00232             break;
00233
00234         case ScenarioState::Snapshot:
00235
00236             if (!co_await TakeSnapshotAndFindFacesAsync())
00237             {
00238                 co_await ChangeScenarioStateAsync(ScenarioState::Idle);
00239                 break;
00240             }
00241
00242             co_await ShutdownWebcamAsync();
00243
00244             CameraSnapshotButton().IsEnabled(true);
00245             CameraStreamingButton().Content(box_value(L"Start Streaming"));
00246             CameraSnapshotButton().Content(box_value(L"Clear Display"));
00247             currentState = newState;
00248             break;
00249         }
00250     }
00251
00252     // Handles MediaCapture changes by shutting down streaming and returning to Idle state.
00253     fire_and_forget Scenario2_DetectInWebcam::MediaCapture_CameraStreamStateChanged(MediaCapture const&, IInspectable const& args)
00254     {
00255         auto lifetime = get_strong();
00256
00257         // MediaCapture is not Agile and so we cannot invoke it's methods on this caller's thread
00258         // and instead need to schedule the state change on the UI thread.
00259         co_await resume_foreground(Dispatcher());
00260         co_await ChangeScenarioStateAsync(ScenarioState::Idle);
00261     }
00262
00263     // Handles "streaming" button clicks to start/stop webcam streaming.
00264     fire_and_forget Scenario2_DetectInWebcam::CameraStreamingButton_Click(IInspectable const&, RoutedEventArgs const&)
00265     {
00266         auto lifetime = get_strong();
00267
00268         rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00269         if (currentState == ScenarioState::Streaming)
00270         {
00271             co_await ChangeScenarioStateAsync(ScenarioState::Idle);
00272         }
00273         else
00274         {
00275             co_await ChangeScenarioStateAsync(ScenarioState::Streaming);
00276         }
00277     }
00278
00279     // Handles "snapshot" button clicks to take a snapshot or clear the current display.
00280     fire_and_forget Scenario2_DetectInWebcam::CameraSnapshotButton_Click(IInspectable const&, RoutedEventArgs const&)
00281     {
00282         auto lifetime = get_strong();
00283
00284         rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00285         if (currentState == ScenarioState::Streaming)
00286         {
00287             co_await ChangeScenarioStateAsync(ScenarioState::Snapshot);
00288         }
00289         else
00290         {
00291             co_await ChangeScenarioStateAsync(ScenarioState::Idle);
00292         }
00293     }
00294
00295     // Updates any existing face bounding boxes in response to changes in the size of the Canvas.
00296     void Scenario2_DetectInWebcam::SnapshotCanvas_SizeChanged(IInspectable const&, SizeChangedEventArgs const&)
00297     {
00298         // If the Canvas is resized we must recompute a new scaling factor and
00299         // apply it to each face box.
00300         ImageBrush brush = SnapshotCanvas().Background().try_as<ImageBrush>();
00301         if (brush != nullptr)
00302         {
00303             WriteableBitmap displaySource = brush.ImageSource().as<WriteableBitmap>();
00304             SampleHelpers::RepositionFaces(displaySource, SnapshotCanvas());
00305         }
00306     }
00307 }
Generated on Fri Nov 15 2024 22:18:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cppwinrt/LoggingChannelScenario.cpp Source File

  • Logging
  • cppwinrt

LoggingChannelScenario.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "LoggingChannelScenario.h"
00014
00015 using namespace winrt;
00016 using namespace winrt::Windows::Foundation;
00017 using namespace winrt::Windows::Foundation::Diagnostics;
00018 using namespace winrt::SDKTemplate;
00019
00020 /// <summary>
00021 /// Construct a LoggingChannel with the Windows 8.1 constructor, then
00022 /// use the LoggingChannel for the scenario.
00023 /// See this sample's README for further discussion.
00024 /// </summary>
00025 void
00026 LoggingChannelScenario::LogWithWin81Constructor()
00027 {
00028     // The 1-parameter constructor creates a channel with Windows 8.1 semantics.
00029     LoggingChannel channel(L"SampleProvider");
00030     DemonstrateLogging(channel);
00031 }
00032
00033 /// <summary>
00034 /// Construct a LoggingChannel with the Windows 10 constructor, then
00035 /// use the LoggingChannel for the scenario. Also show the use cases
00036 /// for the two Windows 10 constructors.
00037 // See this sample's README for further discussion.
00038 /// </summary>
00039 void
00040 LoggingChannelScenario::LogWithWin10Constructor()
00041 {
00042     {
00043         // The 2-parameter constructor creates a channel with Windows 10 semantics.
00044         LoggingChannel channel(
00045             L"SampleProvider",
00046             nullptr); // null means use default options.
00047
00048         // The Id is generated by hashing the string "SampleProvider".
00049         // channel.Id == eff1e128-4903-5093-096a-bdc29b38456f
00050         DemonstrateLogging(channel);
00051     }
00052
00053     /*
00054     Demonstrate other (less-common) constructor scenarios:
00055     */
00056
00057     {
00058         // This creates a channel with Windows 10 semantics and declared
00059         // membership in a provider group.
00060         GUID g = { 0x2e0582f3,0xd1b6,0x516a,0x9d,0xe3,0x9f,0xd7,0x9e,0xf9,0x52,0xf8 };
00061         LoggingChannel channel(
00062             L"SampleProvider",
00063             Windows::Foundation::Diagnostics::LoggingChannelOptions(g)); // Join a provider group
00064         // The Id is generated by hashing the string "SampleProvider".
00065         // channel.Id == eff1e128-4903-5093-096a-bdc29b38456f
00066     }
00067
00068     {
00069         // This creates a channel with Windows 10 semantics and a specific
00070         // provider Id.
00071         GUID g = { 0x2e0582f3,0xd1b6,0x516a,0x9d,0xe3,0x9f,0xd7,0x9e,0xf9,0x52,0xf8 };
00072         LoggingChannel channel(
00073             L"SampleProvider",
00074             nullptr,
00075             g);
00076         // channel.Id == 2e0582f3-d1b6-516a-9de3-9fd79ef952f8
00077     }
00078 }
00079
00080 /// <summary>
00081 /// This method demonstrates the LoggingChannel and LoggingActivity APIs.
00082 /// </summary>
00083 /// <param name="channel">
00084 /// The channel to use for the demonstration. This channel may have been
00085 /// constructed using a Windows 8.1 constructor or a Windows 10 constructor.
00086 /// The same APIs are supported in both cases, but the ETL events will be
00087 /// formatted a bit differently depending on how the channel was constructed.
00088 /// </param>
00089 void
00090 LoggingChannelScenario::DemonstrateLogging(
00091     LoggingChannel const& channel)
00092 {
00093     // Whenever any ETW session changes the way it is listening to this
00094     // channel, the LoggingEnable event is fired. For example, this might
00095     // be called when a session begins listening, changes the level at
00096     // which it is listening, or stops listening.
00097     event_token loggingEnabledToken = channel.LoggingEnabled({ this, &LoggingChannelScenario::OnLoggingEnabled });
00098
00099     // Log simple string events
00100     channel.LogMessage(L"Simple message"); // default level is Verbose
00101     channel.LogMessage(L"Simple error", Windows::Foundation::Diagnostics::LoggingLevel::Error);
00102
00103     // Log simple string + integer events.
00104     channel.LogValuePair(L"Simple message", 123); // default level is Verbose
00105     channel.LogValuePair(L"Simple error", 456, LoggingLevel::Error);
00106
00107     // The channel.Name property returns the name that was used when the
00108     // channel was constructed. When running in Windows 10 mode, the name
00109     // is already set as the provider name, so no LoggingChannelName is
00110     // automatically added to the event.
00111     channel.LogMessage(channel.Name());
00112
00113     // The channel.Id property is new to Windows 10.
00114     channel.LogMessage(to_hstring(channel.Id()));
00115
00116     // If you want to avoid the overhead of collecting data when nobody is
00117     // listening to your channel, check the Enabled property before logging.
00118     if (channel.Enabled())
00119     {
00120         channel.LogMessage(CollectExpensiveData());
00121     }
00122
00123     // The IsEnabled() method is exactly the same as the Enabled property,
00124     // except that it is a new Windows 10 API.
00125     if (channel.IsEnabled())
00126     {
00127         channel.LogMessage(CollectExpensiveData());
00128     }
00129
00130     // If you want to only collect data if somebody is listening at a specific
00131     // level, you need to check both Enabled and Level. Note that the value of
00132     // the Level is unspecified when Enabled is false.
00133     if (channel.Enabled() && channel.Level() <= LoggingLevel::Warning)
00134     {
00135         channel.LogMessage(CollectExpensiveData(), LoggingLevel::Warning);
00136     }
00137
00138     // The IsEnabled(LoggingLevel) method is a bit nicer than checking both
00139     // Enabled and Level, but it is only available on Windows 10 or later.
00140     if (channel.IsEnabled(LoggingLevel::Warning))
00141     {
00142         channel.LogMessage(CollectExpensiveData(), LoggingLevel::Warning);
00143     }
00144
00145     // You can also use IsEnabled to check for keywords.
00146     if (channel.IsEnabled(LoggingLevel::Information, 0x10))
00147     {
00148         channel.LogMessage(CollectExpensiveData(), LoggingLevel::Information);
00149     }
00150
00151     // Use LoggingFields with the LogEvent method to write complex events.
00152     Windows::Foundation::Diagnostics::LoggingFields fields;
00153     fields.AddDouble(L"pi", 3.14159);
00154     channel.LogEvent(
00155         L"ComplexEvent",
00156         fields,
00157         LoggingLevel::Verbose,
00158         LoggingOptions(0x10)); // Keywords = 0x10
00159
00160     // You can add any number of name-value pairs to a fields object, though
00161     // you may encounter ETW limitations if you add too many. For example,
00162     // ETW is limited to a maximum event size of 64KB, and the current
00163     // TraceLogging decoder can handle no more than 128 fields.
00164
00165     // Performance optimization: You can reuse a LoggingFields object to
00166     // avoid unnecessary allocations. Don't forget to call Clear()
00167     // between uses, and don't try to share a LoggingFields object between
00168     // threads.
00169     DateTime now = clock::now();
00170     fields.Clear();
00171     fields.AddInt64(L"Date", clock::to_file_time(now).value, LoggingFieldFormat::FileTime);
00172     channel.LogEvent(L"Now", fields);
00173
00174     fields.Clear();
00175
00176     // You can add a formatting hint to affect the way a value is decoded.
00177     // Not all combinations are useful, and the hint may be ignored.
00178     // For example, you can encode an MBCS string by writing a byte array
00179     // with a String hint.
00180     uint8_t abc123[] = { 65, 66, 67, 49, 50, 51 }; // "ABC123"
00181     fields.AddUInt8Array(
00182         L"AnsiString",
00183         abc123,
00184         LoggingFieldFormat::String);
00185
00186     // You can add "tag" bits to a field. These are user-defined bits that
00187     // can be used to communicate with an event processing tool. For example,
00188     // you might define a tag bit to indicate that a field contains private
00189     // data that should not be displayed on-screen.
00190     fields.AddString(L"Password", L"12345", LoggingFieldFormat::Default, 0x10);
00191
00192     // You can add a "structure" to an event. A structure is a name for a
00193     // group of fields. Structures can nest. Call BeginStruct to add a level
00194     // of nesting, and call EndStruct after the last field of the structure.
00195     fields.BeginStruct(L"Nested");
00196     fields.AddInt16(L"Nested-1", 1);
00197     fields.AddInt16(L"Nested-2", 2);
00198     fields.BeginStruct(L"Nested-Nested");
00199     fields.AddInt16(L"Nested-Nested-3", 3);
00200     fields.EndStruct();
00201     fields.AddInt16(L"Nested-4", 4);
00202     fields.EndStruct();
00203
00204     // Advanced scenarios: you can use a LoggingOptions object to control
00205     // detailed event settings such as keywords, opcodes, and activity Ids.
00206     // These have their normal ETW semantics. You can also set event tags,
00207     // which are bit values that can be used to communicate with the event
00208     // processor.
00209     LoggingOptions options;
00210     options.Keywords(0x123);
00211     options.Tags(0x10);
00212     channel.LogEvent(
00213         L"VeryComplexEvent",
00214         fields,
00215         LoggingLevel::Information,
00216         options);
00217
00218     // Windows 10 introduces the ILoggingTarget interface. LoggingChannel
00219     // implements this interface. This interface allows components to accept
00220     // a logger as an parameter.
00221     DoSomething(channel);
00222
00223     /*
00224     If a LoggingActivity is created using a LoggingActivity constructor,
00225     it will use Windows 8.1 semantics:
00226
00227     - If an activity is destroyed (garbage-collected) without being closed
00228     and the associated LoggingChannel is still open, the activity will
00229     write a default Stop event.
00230     - The default Stop event (written by the destructor or by the Close()
00231     method) is encoded as a "simple" event.
00232
00233     The 8.1 semantics are deprecated because the automatic generation of
00234     a Stop event at garbage-collection can be misleading. The Stop event
00235     is intended to mark the a precise point at which an activity is
00236     completed, while the garbage-collection of an abandoned activity is
00237     inherently imprecise and unpredictable.
00238
00239     If a LoggingActivity is created using a StartActivity method, it will
00240     use Windows 10 semantics:
00241
00242     - If an activity is destroyed (garbage-collected) without being closed,
00243       there will be no Stop event for the activity.
00244     - The default Stop event (written by the Close() method) is encoded as
00245       a TraceLogging event with name "ActivityClosed".
00246     */
00247
00248     {
00249         // This activity is created with Windows 8.1 semantics.
00250         LoggingActivity a1(L"Activity1", channel);
00251
00252         // The activity Start event is written by the LoggingActivity constructor.
00253         // You would do your activity's work here.
00254         // The activity Stop event is written when the activity is closed (disposed).
00255
00256         // The Windows 10 LoggingActivity adds new methods for writing events
00257         // that are marked as associated with the activity.
00258         a1.LogEvent(L"Activity event");
00259
00260         // LoggingActivity also implements the ILoggingTarget interface, so you can
00261         // use either a channel or an activity as a logging target.
00262         DoSomething(a1);
00263
00264         {
00265             // The Windows 10 LoggingActivity adds new methods for creating nested activities.
00266             // Note that nested activities are always created with Windows 10 semantics,
00267             // even when nested under an activity that is using Windows 8.1 semantics.
00268             LoggingActivity a2 = a1.StartActivity(L"Activity2");
00269
00270             // Nested task occurs here.
00271
00272             // The Windows 10 LoggingActivity allows you to customize the Stop event.
00273             a2.StopActivity(L"Activity 2 stop");
00274         }
00275
00276         // Because a1 is using Windows 8.1 semantics, it will write a Stop event when
00277         // it goes out of scope.
00278     }
00279
00280     {
00281         // The Windows 10 StartActivity method creates a new activity, optionally with
00282         // specified fields and characteristics.
00283         // This activity is created with Windows 10 semantics.
00284         LoggingActivity a3 = channel.StartActivity(L"Activity3");
00285
00286         // Because a3 is using Windows 10 semantics, if we did not call StopActivity(),
00287         // there would be no Stop event (not even when the activity is garbage
00288         // collected). To get a Stop event, be sure to stop, close, or dispose the
00289         // activity.
00290         a3.StopActivity(L"ActivityClosed");
00291     }
00292
00293     // Unregister from the event.
00294     channel.LoggingEnabled(loggingEnabledToken);
00295 }
00296
00297 hstring
00298 LoggingChannelScenario::CollectExpensiveData()
00299 {
00300     return L"ExpensiveData";
00301 }
00302
00303 void
00304 LoggingChannelScenario::DoSomething(
00305     ILoggingTarget const& logger)
00306 {
00307     logger.LogEvent(L"Did something");
00308 }
00309
00310 void
00311 LoggingChannelScenario::OnLoggingEnabled(
00312     ILoggingChannel const&,
00313     IInspectable const&)
00314 {
00315     // Here, you could note a change in the level or keywords.
00316 }
Generated on Fri Nov 15 2024 22:20:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Altimeter/cpp/Scenario2_Polling.xaml.cpp Source File

  • Altimeter
  • cpp

Scenario2_Polling.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_Polling.xaml.cpp
00014 // Implementation of the Scenario2_Polling class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario2_Polling.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Windows::Devices::Sensors;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::UI::Core;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 Scenario2_Polling::Scenario2_Polling() : rootPage(MainPage::Current)
00031 {
00032     InitializeComponent();
00033
00034     sensor = Altimeter::GetDefault();
00035     if (nullptr == sensor)
00036     {
00037         rootPage->NotifyUser("No altimeter found", NotifyType::ErrorMessage);
00038     }
00039 }
00040
00041 void Scenario2_Polling::ScenarioGetData(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00042 {
00043     if (nullptr != sensor)
00044     {
00045         AltimeterReading^ reading = sensor->GetCurrentReading();
00046         if (nullptr != reading)
00047         {
00048             ScenarioOutput_M->Text = reading->AltitudeChangeInMeters.ToString();
00049         }
00050     }
00051     else
00052     {
00053         rootPage->NotifyUser("No altimeter found", NotifyType::ErrorMessage);
00054     }
00055 }
Generated on Fri Nov 15 2024 22:17:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

abstract Member List

This is the complete list of members for abstract, including all inherited members.
__pad0__ | abstract |
Close()=0 | abstract | [pure virtual]
Disconnect()=0 | abstract | [pure virtual]
ReceiveAsync(_In_ IMediaBufferWrapper *pBuffer)=0 | abstract | [pure virtual]
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppWindow/cppwinrt/pch.h Source File

  • AppWindow
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <unknwn.h>
00004 #include "winrt/coroutine.h"
00005 #include "winrt/Windows.Foundation.h"
00006 #include "winrt/Windows.Foundation.Collections.h"
00007 #include "winrt/Windows.ApplicationModel.Activation.h"
00008 #include "winrt/Windows.System.h"
00009 #include "winrt/Windows.UI.Core.h"
00010 #include "winrt/Windows.UI.ViewManagement.h"
00011 #include "winrt/Windows.UI.WindowManagement.h"
00012 #include "winrt/Windows.UI.WindowManagement.Preview.h"
00013 #include "winrt/Windows.UI.Xaml.h"
00014 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00015 #include "winrt/Windows.UI.Xaml.Controls.h"
00016 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00017 #include "winrt/Windows.UI.Xaml.Documents.h"
00018 #include "winrt/Windows.UI.Xaml.Hosting.h"
00019 #include "winrt/Windows.UI.Xaml.Interop.h"
00020 #include "winrt/Windows.UI.Xaml.Markup.h"
00021 #include "winrt/Windows.UI.Xaml.Media.h"
00022 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AssociationLaunching/cs/SampleConfiguration.cs Source File

  • AssociationLaunching
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.ApplicationModel.Activation;
00015 using Windows.Foundation;
00016 using Windows.UI.ViewManagement;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019
00020 namespace SDKTemplate
00021 {
00022     public partial class MainPage : Page
00023     {
00024         public const string FEATURE_NAME = "Association Launching C# Sample";
00025
00026         List<Scenario> scenarios = new List<Scenario>
00027         {
00028             new Scenario() { Title = "Launching a file", ClassType = typeof(Scenario1_LaunchFile) },
00029             new Scenario() { Title = "Launching a URI", ClassType = typeof(Scenario2_LaunchUri) },
00030             new Scenario() { Title = "Receiving a file", ClassType = typeof(Scenario3_ReceiveFile) },
00031             new Scenario() { Title = "Receiving a URI", ClassType = typeof(Scenario4_ReceiveUri) }
00032         };
00033
00034         static public List<ViewSizePreference> ViewSizePreferences = new List<ViewSizePreference>
00035         {
00036             ViewSizePreference.Default,
00037             ViewSizePreference.UseLess,
00038             ViewSizePreference.UseHalf,
00039             ViewSizePreference.UseMore,
00040             ViewSizePreference.UseMinimum,
00041             ViewSizePreference.UseNone,
00042         };
00043
00044         public void NavigateToPageWithParameter(int pageIndex, object parameter)
00045         {
00046             ScenarioControl.SelectedIndex = pageIndex;
00047             ScenarioFrame.Navigate(scenarios[pageIndex].ClassType, parameter);
00048         }
00049
00050         static public Point GetElementLocation(object e)
00051         {
00052             var element = (FrameworkElement)e;
00053             Windows.UI.Xaml.Media.GeneralTransform buttonTransform = element.TransformToVisual(null);
00054
00055             Point desiredLocation = buttonTransform.TransformPoint(new Point());
00056             desiredLocation.Y = desiredLocation.Y + element.ActualHeight;
00057
00058             return desiredLocation;
00059         }
00060     }
00061
00062     public class Scenario
00063     {
00064         public string Title { get; set; }
00065
00066         public Type ClassType { get; set; }
00067
00068         public override string ToString()
00069         {
00070             return Title;
00071         }
00072     }
00073
00074     public partial class App : Application
00075     {
00076         /// <summary>
00077         // Handle file activations.
00078         /// </summary>
00079         protected override void OnFileActivated(FileActivatedEventArgs e)
00080         {
00081             Frame rootFrame = CreateRootFrame();
00082
00083             if (rootFrame.Content == null)
00084             {
00085                 if (!rootFrame.Navigate(typeof(MainPage)))
00086                 {
00087                     throw new Exception("Failed to create initial page");
00088                 }
00089             }
00090
00091             var p = rootFrame.Content as MainPage;
00092             p.NavigateToPageWithParameter(2, e);
00093
00094             // Ensure the current window is active
00095             Window.Current.Activate();
00096         }
00097
00098         /// <summary>
00099         // Handle protocol activations.
00100         /// </summary>
00101         protected override void OnActivated(IActivatedEventArgs e)
00102         {
00103             if (e.Kind == ActivationKind.Protocol)
00104             {
00105                 Frame rootFrame = CreateRootFrame();
00106
00107                 if (rootFrame.Content == null)
00108                 {
00109                     if (!rootFrame.Navigate(typeof(MainPage)))
00110                     {
00111                         throw new Exception("Failed to create initial page");
00112                     }
00113                 }
00114
00115                 var p = rootFrame.Content as MainPage;
00116                 p.NavigateToPageWithParameter(3, e);
00117
00118                 // Ensure the current window is active
00119                 Window.Current.Activate();
00120             }
00121         }
00122
00123     }
00124 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/BackgroundTasks/Helpers/ToastHelper.cs Source File

  • Notifications
  • cs
  • BackgroundTasks
  • Helpers

ToastHelper.cs

Go to the documentation of this file.
00001 ﻿using System.Text;
00002 using Windows.Data.Xml.Dom;
00003 using Windows.Foundation.Collections;
00004 using Windows.Foundation.Metadata;
00005 using Windows.UI.Notifications;
00006
00007 namespace BackgroundTasks.Helpers
00008 {
00009     public static class ToastHelper
00010     {
00011         public static ToastNotification PopToast(string title, string content)
00012         {
00013             return PopToast(title, content, null, null);
00014         }
00015
00016         public static ToastNotification PopToast(string title, string content, string tag, string group)
00017         {
00018             string xml = $@"<toast activationType='foreground'>
00019                                             <visual>
00020                                                 <binding template='ToastGeneric'>
00021                                                 </binding>
00022                                             </visual>
00023                                         </toast>";
00024
00025             XmlDocument doc = new XmlDocument();
00026             doc.LoadXml(xml);
00027
00028             var binding = doc.SelectSingleNode("//binding");
00029
00030             var el = doc.CreateElement("text");
00031             el.InnerText = title;
00032
00033             binding.AppendChild(el);
00034
00035             el = doc.CreateElement("text");
00036             el.InnerText = content;
00037             binding.AppendChild(el);
00038
00039             return PopCustomToast(doc, tag, group);
00040         }
00041
00042         public static ToastNotification PopCustomToast(string xml)
00043         {
00044             return PopCustomToast(xml, null, null);
00045         }
00046
00047         public static ToastNotification PopCustomToast(string xml, string tag, string group)
00048         {
00049             XmlDocument doc = new XmlDocument();
00050             doc.LoadXml(xml);
00051
00052
00053             return PopCustomToast(doc, tag, group);
00054         }
00055
00056         [DefaultOverloadAttribute]
00057         public static ToastNotification PopCustomToast(XmlDocument doc, string tag, string group)
00058         {
00059             var toast = new ToastNotification(doc);
00060
00061             if (tag != null)
00062                 toast.Tag = tag;
00063
00064             if (group != null)
00065                 toast.Group = group;
00066
00067             ToastNotificationManager.CreateToastNotifier().Show(toast);
00068
00069             return toast;
00070         }
00071
00072         public static string ToString(ValueSet valueSet)
00073         {
00074             StringBuilder builder = new StringBuilder();
00075
00076             foreach (var pair in valueSet)
00077             {
00078                 if (builder.Length != 0)
00079                     builder.Append('\n');
00080
00081                 builder.Append(pair.Key);
00082                 builder.Append(": ");
00083                 builder.Append(pair.Value);
00084             }
00085
00086             return builder.ToString();
00087         }
00088     }
00089 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

_360VideoPlaybackMain Member List

This is the complete list of members for _360VideoPlaybackMain, including all inherited members.
_360VideoPlaybackMain() | _360VideoPlaybackMain |
_360VideoPlaybackMain(DeviceResources deviceResources) | _360VideoPlaybackMain | [inline]
attachreferenceFrame | _360VideoPlaybackMain | [private]
CreateVideoShaders() | _360VideoPlaybackMain |
CreateVideoShaders() | _360VideoPlaybackMain | [inline]
deviceResources | _360VideoPlaybackMain | [private]
Dispose() | _360VideoPlaybackMain | [inline]
GetDeviceResources() | _360VideoPlaybackMain | [static]
holographicSpace | _360VideoPlaybackMain | [private]
LoadAppState() | _360VideoPlaybackMain |
LoadAppState() | _360VideoPlaybackMain | [inline]
locator | _360VideoPlaybackMain | [private]
m_cameraAddedToken | _360VideoPlaybackMain | [private]
m_cameraRemovedToken | _360VideoPlaybackMain | [private]
m_deviceResources | _360VideoPlaybackMain | [private, static]
m_holographicSpace | _360VideoPlaybackMain | [private]
m_isGamepadPressed | _360VideoPlaybackMain | [private]
m_isMouseLeftKeyPressed | _360VideoPlaybackMain | [private]
m_locatabilityChangedToken | _360VideoPlaybackMain | [private]
m_locator | _360VideoPlaybackMain | [private]
m_mediaTransportControls | _360VideoPlaybackMain | [private]
m_referenceFrame | _360VideoPlaybackMain | [private]
m_spatialInputHandler | _360VideoPlaybackMain | [private]
m_timer | _360VideoPlaybackMain | [private]
m_videoRenderer | _360VideoPlaybackMain | [private]
OnCameraAdded(Windows::Graphics::Holographic::HolographicSpace^sender, Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs^args) | _360VideoPlaybackMain | [private]
OnCameraAdded(HolographicSpace sender, HolographicSpaceCameraAddedEventArgs args) | _360VideoPlaybackMain | [inline]
OnCameraRemoved(Windows::Graphics::Holographic::HolographicSpace^sender, Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs^args) | _360VideoPlaybackMain | [private]
OnCameraRemoved(HolographicSpace sender, HolographicSpaceCameraRemovedEventArgs args) | _360VideoPlaybackMain | [inline]
OnDeviceLost() | _360VideoPlaybackMain | [virtual]
OnDeviceLost(Object sender, EventArgs e) | _360VideoPlaybackMain | [inline]
OnDeviceRestored() | _360VideoPlaybackMain | [virtual]
OnDeviceRestored(Object sender, EventArgs e) | _360VideoPlaybackMain | [inline]
OnLocatabilityChanged(Windows::Perception::Spatial::SpatialLocator^sender, Platform::Object^args) | _360VideoPlaybackMain | [private]
OnLocatabilityChanged(SpatialLocator sender, Object args) | _360VideoPlaybackMain | [inline, private]
Render(Windows::Graphics::Holographic::HolographicFrame^holographicFrame) | _360VideoPlaybackMain |
Render(ref HolographicFrame holographicFrame) | _360VideoPlaybackMain | [inline]
SaveAppState() | _360VideoPlaybackMain |
SaveAppState() | _360VideoPlaybackMain | [inline]
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^holographicSpace) | _360VideoPlaybackMain |
SetHolographicSpace(HolographicSpace holographicSpace) | _360VideoPlaybackMain | [inline]
timer | _360VideoPlaybackMain | [private]
UnregisterHolographicEventHandlers() | _360VideoPlaybackMain |
Update() | _360VideoPlaybackMain |
Update() | _360VideoPlaybackMain | [inline]
~_360VideoPlaybackMain() | _360VideoPlaybackMain |
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_Settings Member List

This is the complete list of members for Scenario4_Settings, including all inherited members.
CheckNow_Clicked(object sender, RoutedEventArgs e) | Scenario4_Settings | [inline, private]
Scenario4_Settings() | Scenario4_Settings | [inline]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LinguisticServices/RuntimeComponent/pch.h Source File

  • LinguisticServices
  • RuntimeComponent

pch.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002 #include <unknwn.h>
00003 #include <winrt/Windows.Foundation.h>
00004 #include <winrt/Windows.Foundation.Collections.h>
00005 #include <elsutil.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cpp/Scenario3_CurrencyFormatting.xaml.cpp Source File

  • NumberFormatting
  • cpp

Scenario3_CurrencyFormatting.xaml.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario3_CurrencyFormatting.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Windows::UI::Xaml;
00010 using namespace Windows::UI::Xaml::Controls;
00011 using namespace Windows::UI::Xaml::Navigation;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::Globalization;
00015 using namespace Windows::Globalization::NumberFormatting;
00016
00017 Scenario3_CurrencyFormatting::Scenario3_CurrencyFormatting()
00018 {
00019     InitializeComponent();
00020 }
00021
00022 void Scenario3_CurrencyFormatting::Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00023 {
00024     // This scenario uses the Windows.Globalization.NumberFormatting.CurrencyFormatter class
00025     // to format a number as a currency.
00026
00027     // Determine the current user's default currency.
00028     auto userCurrency = Windows::System::UserProfile::GlobalizationPreferences::Currencies->First()->Current;
00029
00030     // Generate numbers used for formatting.
00031     long long wholeNumber      = 12345;
00032     double fractionalNumber = 12345.67;
00033
00034     // Create formatter initialized using the current user's preference settings for number formatting.
00035     CurrencyFormatter^ userCurrencyFormat = ref new CurrencyFormatter(userCurrency);
00036     String^ currencyDefault = userCurrencyFormat->Format(fractionalNumber);
00037
00038     // Create a formatter initialized to a specific currency, in this case it's the US Dollar, but with the default number formatting for the current user.
00039     CurrencyFormatter^ currencyFormatUSD = ref new CurrencyFormatter(CurrencyIdentifiers::USD);  // Specified as an ISO 4217 code.
00040     String^ currencyUSD = currencyFormatUSD->Format(fractionalNumber);
00041
00042     // Create a formatter initialized to a specific currency, in this case it's the Euro with the default number formatting for France.
00043     auto fr = ref new Platform::Collections::Vector<String^>();
00044     fr->Append("fr-FR");
00045     CurrencyFormatter^ currencyFormatEuroFR = ref new CurrencyFormatter(CurrencyIdentifiers::EUR, fr, "FR");
00046     String^ currencyEuroFR = currencyFormatEuroFR->Format(fractionalNumber);
00047
00048     // Create a formatter initialized to a specific currency, in this case it's the Euro with the default number formatting for Ireland.
00049     auto gd = ref new Platform::Collections::Vector<String^>();
00050     gd->Append("gd-IE");
00051     CurrencyFormatter^ currencyFormatEuroIE = ref new CurrencyFormatter(CurrencyIdentifiers::EUR, gd, "IE");
00052     String^ currencyEuroIE = currencyFormatEuroIE->Format(fractionalNumber);
00053
00054     // Formatted so that fraction digits are always included.
00055     CurrencyFormatter^ currencyFormatUSD1 = ref new CurrencyFormatter(CurrencyIdentifiers::USD);
00056     currencyFormatUSD1->FractionDigits = 2;
00057     String^ currencyUSD1 = currencyFormatUSD1->Format(wholeNumber);
00058
00059     // Formatted so that integer grouping separators are included.
00060     CurrencyFormatter^ currencyFormatUSD2 = ref new CurrencyFormatter(CurrencyIdentifiers::USD);
00061     currencyFormatUSD2->IsGrouped = 1;
00062     String^ currencyUSD2 = currencyFormatUSD2->Format(fractionalNumber);
00063
00064     // Formatted using currency code instead of currency symbol
00065     CurrencyFormatter^ currencyFormatEuroModeSwitch = ref new CurrencyFormatter(CurrencyIdentifiers::EUR);
00066     currencyFormatEuroModeSwitch->Mode = CurrencyFormatterMode::UseCurrencyCode;
00067     String^ currencyEuroCode = currencyFormatEuroModeSwitch->Format(fractionalNumber);
00068
00069     // Return back to currency symbol
00070     currencyFormatEuroModeSwitch->Mode = CurrencyFormatterMode::UseSymbol;
00071     String^ currencyEuroSymbol = currencyFormatEuroModeSwitch->Format(fractionalNumber);
00072
00073     // Display the results.
00074     String^ results =
00075         "Fixed number ("                                   + fractionalNumber + ")\n" +
00076         "With user's default currency: "                   + currencyDefault  + "\n" +
00077         "Formatted US Dollar: "                            + currencyUSD      + "\n" +
00078         "Formatted Euro (fr-FR defaults): "                + currencyEuroFR   + "\n" +
00079         "Formatted Euro (gd-IE defaults): "                + currencyEuroIE   + "\n" +
00080         "Formatted US Dollar (with fractional digits): "   + currencyUSD1     + "\n" +
00081         "Formatted US Dollar (with grouping separators): " + currencyUSD2     + "\n" +
00082         "Formatted Euro (as currency code): "              + currencyEuroCode + "\n" +
00083         "Formatted Euro (as symbol): "                     + currencyEuroSymbol;
00084
00085     OutputTextBlock->Text = results;
00086 }
Generated on Fri Nov 15 2024 22:20:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/ShareHtml.xaml.h Source File

  • ShareSource
  • cpp

ShareHtml.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ShareHtml.xaml.h
00014 // Declaration of the ShareHtml class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "SharePage.h"
00021 #include "ShareHtml.g.h"
00022 #include "MainPage.xaml.h"
00023
00024 namespace SDKTemplate
00025 {
00026     public ref class ShareHtml sealed
00027     {
00028     public:
00029         ShareHtml();
00030
00031     protected:
00032         virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request) override;
00033
00034     private:
00035         void ShareWebView_NavigationCompleted(Platform::Object^ sender, Windows::UI::Xaml::Controls::WebViewNavigationCompletedEventArgs^ e);
00036     };
00037 }
Generated on Fri Nov 15 2024 22:21:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cs/WiFiDirectServiceManager.cs Source File

  • WiFiDirectServices
  • cs

WiFiDirectServiceManager.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Devices.WiFiDirect.Services;
00015 using Windows.Devices.Enumeration;
00016 using Windows.UI.Core;
00017 using Windows.Storage.Streams;
00018 using System.Globalization;
00019
00020 namespace SDKTemplate
00021 {
00022     namespace WiFiDirectServices
00023     {
00024
00025         /// <summary>
00026         /// Common class to wrap all of the services objects and state behind the UI
00027         /// </summary>
00028         public class WiFiDirectServiceManager : IDisposable
00029         {
00030             private Object thisLock = new Object();
00031
00032             private MainPage rootPage;
00033
00034             // UI Integration
00035             // Keep track of known UI frames and update them when we have any changes
00036             // NOTE: UI pages may not exist and the UI will need to update itself when it initializes
00037             private Scenario1 scenario1 = null;
00038             private Scenario2 scenario2 = null;
00039             private Scenario3 scenario3 = null;
00040             private Scenario4 scenario4 = null;
00041             private Scenario5 scenario5 = null;
00042
00043             // Keep list of all advertised services currently active
00044             private IList<AdvertisementWrapper> advertisers = new List<AdvertisementWrapper>();
00045
00046             // Keep track of all devices found during previous discovery
00047             private IList<DiscoveredDeviceWrapper> discoveredDevices = new List<DiscoveredDeviceWrapper>();
00048
00049             // Keep track of all sessions that are connected to this device
00050             // NOTE: it may make sense to track sessions per-advertiser and a second list for the seeker, but this sample keeps a global list
00051             private IList<SessionWrapper> connectedSessions = new List<SessionWrapper>();
00052
00053             // Keep track of the selected session for the UI
00054             // The UI will choose this session from the session list and use it for sending/receiving data
00055             private int selectedSession = -1;
00056
00057             // Singleton
00058             private static WiFiDirectServiceManager instance;
00059             private WiFiDirectServiceManager()
00060             {
00061                 instance = this;
00062                 this.rootPage = MainPage.Current;
00063             }
00064
00065             // Singleton access
00066             public static WiFiDirectServiceManager Instance
00067             {
00068                 get
00069                 {
00070                     if (instance == null)
00071                     {
00072                         instance = new WiFiDirectServiceManager();
00073                     }
00074                     return instance;
00075                 }
00076             }
00077
00078             public async void NotifyUser(string message, NotifyType type)
00079             {
00080                 // Always dispatch to UI thread
00081                 await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00082                 {
00083                     rootPage.NotifyUser(message, type);
00084                 });
00085             }
00086
00087             #region UI Page Accessors
00088             public MainPage RootPage
00089             {
00090                 get
00091                 {
00092                     if (rootPage == null)
00093                     {
00094                         rootPage = MainPage.Current;
00095                     }
00096                     return rootPage;
00097                 }
00098             }
00099
00100             public Scenario1 Scenario1
00101             {
00102                 get { return scenario1; }
00103                 set { scenario1 = value; }
00104             }
00105
00106             public Scenario2 Scenario2
00107             {
00108                 get { return scenario2; }
00109                 set { scenario2 = value; }
00110             }
00111
00112             public Scenario3 Scenario3
00113             {
00114                 get { return scenario3; }
00115                 set { scenario3 = value; }
00116             }
00117
00118             public Scenario4 Scenario4
00119             {
00120                 get { return scenario4; }
00121                 set { scenario4 = value; }
00122             }
00123
00124             public Scenario5 Scenario5
00125             {
00126                 get { return scenario5; }
00127                 set { scenario5 = value; }
00128             }
00129             #endregion
00130
00131             public IList<AdvertisementWrapper> Advertisers
00132             {
00133                 get { return advertisers; }
00134             }
00135
00136             public SessionWrapper CurrentSession
00137             {
00138                 get
00139                 {
00140                     if (selectedSession >= 0 && selectedSession < connectedSessions.Count)
00141                     {
00142                         return connectedSessions[selectedSession];
00143                     }
00144                     return null;
00145                 }
00146             }
00147
00148             public IList<DiscoveredDeviceWrapper> DiscoveredDevices
00149             {
00150                 get { return discoveredDevices; }
00151             }
00152
00153             public IList<SessionWrapper> ConnectedSessionList
00154             {
00155                 get { return connectedSessions; }
00156             }
00157
00158             #region Advertiser
00159             public void StartAdvertisement(
00160                 string serviceName,
00161                 bool autoAccept,
00162                 bool preferGO,
00163                 string pin,
00164                 IList<WiFiDirectServiceConfigurationMethod> configMethods,
00165                 WiFiDirectServiceStatus status,
00166                 uint customStatus,
00167                 string serviceInfo,
00168                 string deferredServiceInfo,
00169                 IList<String> prefixList
00170                 )
00171             {
00172                 ThrowIfDisposed();
00173
00174                 // Create Advertiser object for the service
00175                 // NOTE: service name is internally limited to up to 255 bytes in UTF-8 encoding
00176                 // Valid characters include alpha-numeric, '.', '-', and any multi-byte character
00177                 // characters a-z, A-Z are case-insensitive when discovering services
00178                 WiFiDirectServiceAdvertiser advertiser = new WiFiDirectServiceAdvertiser(serviceName);
00179
00180                 // Auto-accept services will connect without interaction from advertiser
00181                 // NOTE: if the config method used for a connection requires a PIN, then the advertiser will have to accept the connection
00182                 advertiser.AutoAcceptSession = autoAccept;
00183
00184                 // Set the Group Owner intent to a large value so that the advertiser will try to become the group owner (GO)
00185                 // NOTE: The GO of a P2P connection can connect to multiple clients while the client can connect to a single GO only
00186                 advertiser.PreferGroupOwnerMode = preferGO;
00187
00188                 // Default status is "Available", but services may use a custom status code (value > 1) if applicable
00189                 advertiser.ServiceStatus = status;
00190                 advertiser.CustomServiceStatusCode = customStatus;
00191
00192                 // Service information can be up to 65000 bytes.
00193                 // Service Seeker may explicitly discover this by specifying a short buffer that is a subset of this buffer.
00194                 // If seeker portion matches, then entire buffer is returned, otherwise, the service information is not returned to the seeker
00195                 // This sample uses a string for the buffer but it can be any data
00196                 if (serviceInfo != null && serviceInfo.Length > 0)
00197                 {
00198                     using (var tempStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
00199                     {
00200                         using (var serviceInfoDataWriter = new Windows.Storage.Streams.DataWriter(tempStream))
00201                         {
00202                             serviceInfoDataWriter.WriteString(serviceInfo);
00203                             advertiser.ServiceInfo = serviceInfoDataWriter.DetachBuffer();
00204                         }
00205                     }
00206                 }
00207                 else
00208                 {
00209                     advertiser.ServiceInfo = null;
00210                 }
00211
00212                 // This is a buffer of up to 144 bytes that is sent to the seeker in case the connection is "deferred" (i.e. not auto-accepted)
00213                 // This buffer will be sent when auto-accept is false, or if a PIN is required to complete the connection
00214                 // For the sample, we use a string, but it can contain any data
00215                 if (deferredServiceInfo != null && deferredServiceInfo.Length > 0)
00216                 {
00217                     using (var tempStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
00218                     {
00219                         using (var deferredSessionInfoDataWriter = new Windows.Storage.Streams.DataWriter(tempStream))
00220                         {
00221                             deferredSessionInfoDataWriter.WriteString(deferredServiceInfo);
00222                             advertiser.DeferredSessionInfo = deferredSessionInfoDataWriter.DetachBuffer();
00223                         }
00224                     }
00225                 }
00226                 else
00227                 {
00228                     advertiser.DeferredSessionInfo = null;
00229                 }
00230
00231                 // The advertiser supported configuration methods
00232                 // Valid values are PIN-only (either keypad entry, display, or both), or PIN (keypad entry, display, or both) and WFD Services default
00233                 // WFD Services Default config method does not require explicit PIN entry and offers a more seamless connection experience
00234                 // Typically, an advertiser will support PIN display (and WFD Services Default), and a seeker will connect with either PIN entry or WFD Services Default
00235                 if (configMethods != null)
00236                 {
00237                     advertiser.PreferredConfigurationMethods.Clear();
00238                     foreach (var configMethod in configMethods)
00239                     {
00240                         advertiser.PreferredConfigurationMethods.Add(configMethod);
00241                     }
00242                 }
00243
00244                 // Advertiser may also be discoverable by a prefix of the service name. Must explicitly specify prefixes allowed here.
00245                 if (prefixList != null && prefixList.Count > 0)
00246                 {
00247                     advertiser.ServiceNamePrefixes.Clear();
00248                     foreach (var prefix in prefixList)
00249                     {
00250                         advertiser.ServiceNamePrefixes.Add(prefix);
00251                     }
00252                 }
00253
00254                 // For this sample, we wrap the advertiser in our own object which handles the advertiser events
00255                 AdvertisementWrapper advertiserWrapper = new AdvertisementWrapper(advertiser, this, pin);
00256
00257                 AddAdvertiser(advertiserWrapper);
00258
00259                 RootPage.NotifyUser("Starting service...", NotifyType.StatusMessage);
00260
00261                 try
00262                 {
00263                     // This may fail if the driver is unable to handle the request or if services is not supported
00264                     // NOTE: this must be called from the UI thread of the app
00265                     advertiser.Start();
00266                 }
00267                 catch (Exception ex)
00268                 {
00269                     RootPage.NotifyUser(String.Format(CultureInfo.InvariantCulture, "Failed to start service: {0}", ex.Message), NotifyType.ErrorMessage);
00270                     throw;
00271                 }
00272             }
00273
00274             public void UnpublishService(int index)
00275             {
00276                 ThrowIfDisposed();
00277
00278                 AdvertisementWrapper advertiser = null;
00279
00280                 lock (thisLock)
00281                 {
00282                     if (index > advertisers.Count - 1)
00283                     {
00284                         throw new IndexOutOfRangeException("Attempted to stop service not found in list");
00285                     }
00286
00287                     advertiser = advertisers[index];
00288                 }
00289
00290                 try
00291                 {
00292                     advertiser.Advertiser.Stop();
00293                 }
00294                 catch (Exception ex)
00295                 {
00296                     RootPage.NotifyUser("Stop Advertisement Failed: " + ex.Message, NotifyType.ErrorMessage);
00297                 }
00298             }
00299             #endregion
00300
00301             #region Seeker
00302             public async void DiscoverServicesAsync(string serviceName, string requestedServiceInfo)
00303             {
00304                 try
00305                 {
00306                     ThrowIfDisposed();
00307
00308                     RootPage.NotifyUser("Discover services... (name='" + serviceName + "', requestedInfo='" + requestedServiceInfo + "')", NotifyType.StatusMessage);
00309
00310                     // Clear old results
00311                     discoveredDevices.Clear();
00312
00313                     // Discovery depends on whether service information is requested
00314                     string serviceSelector = "";
00315                     if (requestedServiceInfo == "")
00316                     {
00317                         // Just search by name
00318                         serviceSelector = WiFiDirectService.GetSelector(serviceName);
00319                     }
00320                     else
00321                     {
00322                         using (var serviceInfoDataWriter = new DataWriter(new InMemoryRandomAccessStream()))
00323                         {
00324                             serviceInfoDataWriter.WriteString(requestedServiceInfo);
00325                             // Discover by name and try to discover service information
00326                             serviceSelector = WiFiDirectService.GetSelector(serviceName, serviceInfoDataWriter.DetachBuffer());
00327                         }
00328                     }
00329
00330                     List<string> additionalProperties = new List<string>();
00331                     additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceAddress");
00332                     additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceName");
00333                     additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceInformation");
00334                     additionalProperties.Add("System.Devices.WiFiDirectServices.AdvertisementId");
00335                     additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceConfigMethods");
00336
00337                     // Note: This sample demonstrates finding services with FindAllAsync, which does a discovery and returns a list
00338                     // It is also possible to use DeviceWatcher to receive updates as soon as services are found and to continue the discovery until it is stopped
00339                     // See the DeviceWatcher sample for an example on how to use that class instead of DeviceInformation.FindAllAsync
00340                     DeviceInformationCollection deviceInfoCollection = await DeviceInformation.FindAllAsync(serviceSelector, additionalProperties);
00341
00342                     if (deviceInfoCollection != null && deviceInfoCollection.Count > 0)
00343                     {
00344                         RootPage.NotifyUser("Done discovering services, found " + deviceInfoCollection.Count + " services", NotifyType.StatusMessage);
00345
00346                         foreach (var device in deviceInfoCollection)
00347                         {
00348                             discoveredDevices.Add(new DiscoveredDeviceWrapper(device, this));
00349                         }
00350                     }
00351                     else
00352                     {
00353                         RootPage.NotifyUser("Done discovering services, No services found", NotifyType.StatusMessage);
00354                     }
00355
00356                     // Update UI list
00357                     if (scenario3 != null)
00358                     {
00359                         scenario3.UpdateDiscoveryList(discoveredDevices);
00360                     }
00361                 }
00362                 catch (Exception ex)
00363                 {
00364                     RootPage.NotifyUser(String.Format("Failed to discover services: {0}", ex.Message), NotifyType.ErrorMessage);
00365                     throw ex;
00366                 }
00367             }
00368             #endregion
00369
00370             #region ListManagement
00371             private void AddAdvertiser(AdvertisementWrapper advertiser)
00372             {
00373                 lock (thisLock)
00374                 {
00375                     advertisers.Add(advertiser);
00376                 }
00377
00378                 // Update UI to add this to list
00379                 if (scenario2 != null)
00380                 {
00381                     scenario2.AddAdvertiser(advertiser);
00382                 }
00383             }
00384
00385             private void RemoveAdvertiser(int index)
00386             {
00387                 lock (thisLock)
00388                 {
00389                     advertisers.RemoveAt(index);
00390                 }
00391
00392                 // Update UI to remove from list
00393                 if (scenario2 != null)
00394                 {
00395                     scenario2.RemoveAdvertiser(index);
00396                 }
00397             }
00398
00399             public void RemoveAdvertiser(AdvertisementWrapper advertiser)
00400             {
00401                 int index = 0;
00402                 bool fFound = false;
00403
00404                 lock (thisLock)
00405                 {
00406                     // Lookup the index
00407                     foreach (var a in advertisers)
00408                     {
00409                         if (a.InternalId == advertiser.InternalId)
00410                         {
00411                             fFound = true;
00412                             break;
00413                         }
00414                         ++index;
00415                     }
00416                 }
00417
00418                 if (fFound)
00419                 {
00420                     RemoveAdvertiser(index);
00421                 }
00422                 else
00423                 {
00424                     NotifyUser("Advertiser not found in list", NotifyType.ErrorMessage);
00425                 }
00426             }
00427
00428             public void AddSessionRequest(WiFiDirectServiceSessionRequest request, AdvertisementWrapper advertiser)
00429             {
00430                 // Update UI to add this to list
00431                 if (scenario2 != null)
00432                 {
00433                     scenario2.AddSessionRequest(request, advertiser);
00434                 }
00435             }
00436
00437             public void RemoveSessionRequest(WiFiDirectServiceSessionRequest request, AdvertisementWrapper advertiser)
00438             {
00439                 // Update UI to remove from list
00440                 if (scenario2 != null)
00441                 {
00442                     scenario2.RemoveSessionRequest(request, advertiser);
00443                 }
00444             }
00445
00446             public void AdvertiserStatusChanged(AdvertisementWrapper advertiser)
00447             {
00448                 if (advertiser.Advertiser.AdvertisementStatus == WiFiDirectServiceAdvertisementStatus.Aborted ||
00449                     advertiser.Advertiser.AdvertisementStatus == WiFiDirectServiceAdvertisementStatus.Stopped)
00450                 {
00451                     RemoveAdvertiser(advertiser);
00452                 }
00453                 else
00454                 {
00455                     if (scenario2 != null)
00456                     {
00457                         scenario2.UpdateAdvertiserStatus(advertiser);
00458                     }
00459                 }
00460             }
00461
00462             public void AddSession(SessionWrapper session)
00463             {
00464                 lock (thisLock)
00465                 {
00466                     connectedSessions.Add(session);
00467                 }
00468
00469                 // Update UI to add this to list
00470                 if (scenario2 != null)
00471                 {
00472                     scenario2.AddSession(session);
00473                 }
00474                 if (scenario4 != null)
00475                 {
00476                     scenario4.AddSession(session);
00477                 }
00478
00479                 if (scenario3 != null)
00480                 {
00481                     scenario3.SessionConnected();
00482                 }
00483             }
00484
00485             public void RemoveSession(int index)
00486             {
00487                 lock (thisLock)
00488                 {
00489                     // Invalidate selection
00490                     selectedSession = -1;
00491                     connectedSessions.RemoveAt(index);
00492                 }
00493
00494                 // Update UI to remove from list
00495                 if (scenario2 != null)
00496                 {
00497                     scenario2.RemoveSession(index);
00498                 }
00499                 if (scenario4 != null)
00500                 {
00501                     scenario4.RemoveSession(index);
00502                 }
00503             }
00504
00505             public void RemoveSession(SessionWrapper session)
00506             {
00507                 int index = 0;
00508                 bool fFound = false;
00509
00510                 lock (thisLock)
00511                 {
00512                     // Lookup the index
00513                     foreach (var s in connectedSessions)
00514                     {
00515                         if (s.Session.SessionId == session.Session.SessionId &&
00516                             s.Session.SessionAddress == session.Session.SessionAddress &&
00517                             s.Session.AdvertisementId == session.Session.AdvertisementId &&
00518                             s.Session.ServiceAddress == session.Session.ServiceAddress)
00519                         {
00520                             fFound = true;
00521                             break;
00522                         }
00523                         ++index;
00524                     }
00525                 }
00526
00527                 if (fFound)
00528                 {
00529                     RemoveSession(index);
00530                 }
00531                 else
00532                 {
00533                     NotifyUser("Session not found in list", NotifyType.ErrorMessage);
00534                 }
00535             }
00536
00537             public void CloseSession(int index)
00538             {
00539                 SessionWrapper session = null;
00540
00541                 // First remove from list
00542                 lock (thisLock)
00543                 {
00544                     if (index > connectedSessions.Count - 1)
00545                     {
00546                         throw new IndexOutOfRangeException("Attempted to close session not found in list");
00547                     }
00548
00549                     session = connectedSessions[index];
00550                     // Session will remove self from list when its status changes
00551                 }
00552
00553                 // Close session by disposing underlying WiFiDirectServiceSession
00554                 session.Close();
00555                 RootPage.NotifyUser("Closed Session", NotifyType.StatusMessage);
00556             }
00557
00558             public void SelectSession(int index)
00559             {
00560                 lock (thisLock)
00561                 {
00562                     if (index > connectedSessions.Count - 1)
00563                     {
00564                         throw new IndexOutOfRangeException("Attempted to select session not found in list");
00565                     }
00566                     selectedSession = index;
00567                 }
00568             }
00569
00570             public void AddSocket(SocketWrapper socket)
00571             {
00572                 // Update UI to add this to list
00573                 if (scenario5 != null)
00574                 {
00575                     scenario5.AddSocket(socket);
00576                 }
00577             }
00578             #endregion
00579
00580             #region Dispose
00581             bool disposed = false;
00582
00583             ~WiFiDirectServiceManager()
00584             {
00585                 Dispose(false);
00586             }
00587
00588             public void Dispose()
00589             {
00590                 Dispose(true);
00591                 GC.SuppressFinalize(this);
00592             }
00593
00594             protected virtual void Dispose(bool disposing)
00595             {
00596                 if (disposed)
00597                 {
00598                     return;
00599                 }
00600
00601                 if (disposing)
00602                 {
00603                     foreach (var advertiser in advertisers)
00604                     {
00605                         advertiser.Dispose();
00606                     }
00607                     advertisers.Clear();
00608
00609                     foreach (var device in discoveredDevices)
00610                     {
00611                         device.Dispose();
00612                     }
00613                     discoveredDevices.Clear();
00614
00615                     foreach (var session in connectedSessions)
00616                     {
00617                         session.Dispose();
00618                     }
00619                     connectedSessions.Clear();
00620                 }
00621
00622                 disposed = true;
00623             }
00624
00625             private void ThrowIfDisposed()
00626             {
00627                 if (disposed)
00628                 {
00629                     throw new ObjectDisposedException("WiFiDirectServiceManager");
00630                 }
00631             }
00632             #endregion
00633         }
00634     }
00635 }
Generated on Fri Nov 15 2024 22:22:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: EnterpriseDataProtection/cs/Scenario1_Setup.xaml.cs Source File

  • EnterpriseDataProtection
  • cs

Scenario1_Setup.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using Windows.Security.EnterpriseData;
00017
00018 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00019
00020 namespace EdpSample
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class Scenario1 : Page
00026     {
00027         private MainPage rootPage;
00028         private static string m_EnterpriseId = "microsoft.com";
00029         public static string m_enterpriseId
00030         {
00031             get
00032             {
00033                 return m_EnterpriseId;
00034             }
00035         }
00036
00037         public Scenario1()
00038         {
00039             this.InitializeComponent();
00040         }
00041
00042         protected override void OnNavigatedTo(NavigationEventArgs e)
00043         {
00044             rootPage = MainPage.Current;
00045         }
00046
00047         private void Setup_Click(object sender, RoutedEventArgs e)
00048         {
00049             m_EnterpriseId = EnterpriseIdentity.Text;
00050             rootPage.NotifyUser("Enterprise Identity is set to: " + m_enterpriseId, NotifyType.StatusMessage);
00051         }
00052     }
00053 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

InkEventLogger Member List

This is the complete list of members for InkEventLogger, including all inherited members.
_countOfCoalescedIndependentInput | InkEventLogger | [private]
_countOfCoalescedStrokeMessages | InkEventLogger | [private]
_countOfCoalescedUnprocessedInput | InkEventLogger | [private]
_currentConfig | InkEventLogger | [private]
_log | InkEventLogger | [private]
ClearLog() | InkEventLogger | [inline]
EnableLoggingConfiguration(LogEventTypes type, bool addConfig) | InkEventLogger |
GetLog() | InkEventLogger | [inline]
InkEventLogger() | InkEventLogger |
Log(LogEventAction eventAction) | InkEventLogger |
SetConfiguration(LogEventTypes config) | InkEventLogger |
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

S2_UpdateAndDeleteWithAPI Member List

This is the complete list of members for S2_UpdateAndDeleteWithAPI, including all inherited members.
AddToIndex_Click(object sender, RoutedEventArgs e) | S2_UpdateAndDeleteWithAPI | [inline, private]
DeleteAllItems_Click(object sender, RoutedEventArgs e) | S2_UpdateAndDeleteWithAPI | [inline, private]
DeleteFunction(Windows.Storage.Search.ContentIndexer indexer) | S2_UpdateAndDeleteWithAPI | [private]
DeleteItemsHelper(DeleteFunction deleteFunction) | S2_UpdateAndDeleteWithAPI | [inline, private]
DeleteKeywords_Click(object sender, RoutedEventArgs e) | S2_UpdateAndDeleteWithAPI | [inline, private]
DeleteMultipleItems_Click(object sender, RoutedEventArgs e) | S2_UpdateAndDeleteWithAPI | [inline, private]
DeleteSingleItem_Click(object sender, RoutedEventArgs e) | S2_UpdateAndDeleteWithAPI | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | S2_UpdateAndDeleteWithAPI | [inline, protected]
rootPage | S2_UpdateAndDeleteWithAPI | [private]
S2_UpdateAndDeleteWithAPI() | S2_UpdateAndDeleteWithAPI | [inline]
UpdateName_Click(object sender, RoutedEventArgs e) | S2_UpdateAndDeleteWithAPI | [inline, private]
UpdatePropertyHelper(string itemKey, string propertyKey, string propertyName, object newValue) | S2_UpdateAndDeleteWithAPI | [inline, private]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PersonalDataEncryption/cppwinrt/Scenario1_Files.h Source File

  • PersonalDataEncryption
  • cppwinrt

Scenario1_Files.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Files.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1_Files : Scenario1_FilesT<Scenario1_Files>
00020     {
00021         Scenario1_Files();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024
00025         fire_and_forget ChooseFile_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026         fire_and_forget ChooseFolder_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         fire_and_forget ProtectL1_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         fire_and_forget ProtectL2_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029         fire_and_forget Unprotect_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00030
00031     private:
00032         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00033         winrt::Windows::Security::DataProtection::UserDataProtectionManager userDataProtectionManager{ nullptr };
00034         winrt::Windows::Storage::IStorageItem selectedItem{ nullptr };
00035
00036         void UpdateItem(winrt::Windows::Storage::IStorageItem const& item);
00037         void ReportStatus(winrt::hstring const& operation, winrt::Windows::Security::DataProtection::UserDataStorageItemProtectionStatus status);
00038
00039     };
00040 }
00041
00042 namespace winrt::SDKTemplate::factory_implementation
00043 {
00044     struct Scenario1_Files : Scenario1_FilesT<Scenario1_Files, implementation::Scenario1_Files>
00045     {
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/ImagePage.cpp Source File

  • XamlListView
  • cppwinrt

ImagePage.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "ImagePage.h"
00014 #include "ImagePage.g.cpp"
00015
00016 using namespace winrt::Windows::UI::Core;
00017 using namespace winrt::Windows::UI::Xaml;
00018 using namespace winrt::Windows::UI::Xaml::Controls;
00019 using namespace winrt::Windows::UI::Xaml::Media::Animation;
00020 using namespace winrt::Windows::UI::Xaml::Navigation;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     ImagePage::ImagePage()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     void ImagePage::OnNavigatedTo(NavigationEventArgs const&)
00030     {
00031         // Register for hardware and software back request from the system
00032         SystemNavigationManager systemNavigationManager = SystemNavigationManager::GetForCurrentView();
00033         backRequestedToken = systemNavigationManager.BackRequested({ get_weak(), &ImagePage::OnBackRequested });
00034         systemNavigationManager.AppViewBackButtonVisibility(AppViewBackButtonVisibility::Visible);
00035     }
00036
00037     void ImagePage::OnNavigatedFrom(NavigationEventArgs const&)
00038     {
00039         SystemNavigationManager systemNavigationManager = SystemNavigationManager::GetForCurrentView();
00040         systemNavigationManager.BackRequested(backRequestedToken);
00041         systemNavigationManager.AppViewBackButtonVisibility(AppViewBackButtonVisibility::Collapsed);
00042     }
00043
00044     void ImagePage::OnBackRequested(IInspectable const&, BackRequestedEventArgs const& e)
00045     {
00046         // Mark event as handled so we don't leave the app.
00047         e.Handled(true);
00048         // Page above us will be our master view.
00049         // Make sure we are using the "drill out" animation in this transition.
00050         Frame().GoBack(DrillInNavigationTransitionInfo());
00051     }
00052
00053 }
Generated on Fri Nov 15 2024 22:22:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cs/Scenario1.xaml.cs Source File

  • FileThumbnails
  • cs

Scenario1.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Storage;
00014 using Windows.Storage.FileProperties;
00015 using Windows.Storage.Pickers;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario1 : Page
00023     {
00024         MainPage rootPage = MainPage.Current;
00025
00026         public Scenario1()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         protected override void OnNavigatedTo(NavigationEventArgs e)
00032         {
00033             rootPage.ResetOutput(ThumbnailImage, OutputTextBlock);
00034         }
00035
00036         private async void GetThumbnailButton_Click(object sender, RoutedEventArgs e)
00037         {
00038             rootPage.ResetOutput(ThumbnailImage, OutputTextBlock);
00039
00040             // Pick a photo
00041             FileOpenPicker openPicker = new FileOpenPicker();
00042             foreach (string extension in FileExtensions.Image)
00043             {
00044                 openPicker.FileTypeFilter.Add(extension);
00045             }
00046
00047             StorageFile file = await openPicker.PickSingleFileAsync();
00048             if (file != null)
00049             {
00050                 string thumbnailModeName = ((ComboBoxItem)ModeComboBox.SelectedItem).Name;
00051                 ThumbnailMode thumbnailMode = (ThumbnailMode)Enum.Parse(typeof(ThumbnailMode), thumbnailModeName);
00052
00053                 bool fastThumbnail = FastThumbnailCheckBox.IsChecked.Value;
00054                 ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale;
00055                 if (fastThumbnail)
00056                 {
00057                     thumbnailOptions |= ThumbnailOptions.ReturnOnlyIfCached;
00058                 }
00059
00060                 const uint size = 200;
00061                 using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(thumbnailMode, size, thumbnailOptions))
00062                 {
00063                     if (thumbnail != null)
00064                     {
00065                         MainPage.DisplayResult(ThumbnailImage, OutputTextBlock, thumbnailModeName, size, file, thumbnail, false);
00066                     }
00067                     else if (fastThumbnail)
00068                     {
00069                         rootPage.NotifyUser(Errors.NoExifThumbnail, NotifyType.StatusMessage);
00070                     }
00071                     else
00072                     {
00073                         rootPage.NotifyUser(Errors.NoThumbnail, NotifyType.StatusMessage);
00074                     }
00075                 }
00076             }
00077             else
00078             {
00079                 rootPage.NotifyUser(Errors.Cancel, NotifyType.StatusMessage);
00080             }
00081         }
00082     }
00083 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SplashScreen/cs/App.xaml.cs Source File

  • SplashScreen
  • cs

App.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate.Common;
00013
00014 using SplashScreenSample;
00015
00016 using System;
00017 using System.Collections.Generic;
00018 using System.IO;
00019 using System.Linq;
00020 using System.Runtime.InteropServices.WindowsRuntime;
00021 using Windows.ApplicationModel;
00022 using Windows.ApplicationModel.Activation;
00023 using Windows.Foundation;
00024 using Windows.Foundation.Collections;
00025 using Windows.UI.Xaml;
00026 using Windows.UI.Xaml.Controls;
00027 using Windows.UI.Xaml.Controls.Primitives;
00028 using Windows.UI.Xaml.Data;
00029 using Windows.UI.Xaml.Input;
00030 using Windows.UI.Xaml.Media;
00031 using Windows.UI.Xaml.Navigation;
00032
00033 namespace SDKTemplate
00034 {
00035     /// <summary>
00036     /// Provides application-specific behavior to supplement the default Application class.
00037     /// </summary>
00038     sealed partial class App : Application
00039     {
00040         /// <summary>
00041         /// Initializes the singleton Application object.  This is the first line of authored code
00042         /// executed, and as such is the logical equivalent of main() or WinMain().
00043         /// </summary>
00044         public App()
00045         {
00046             this.InitializeComponent();
00047             this.Suspending += OnSuspending;
00048         }
00049
00050         /// <summary>
00051         /// Invoked when the application is launched normally by the end user.  Other entry points
00052         /// will be used such as when the application is launched to open a specific file.
00053         /// </summary>
00054         /// <param name="e">Details about the launch request and process.</param>
00055         protected override void OnLaunched(LaunchActivatedEventArgs e)
00056         {
00057             if (e.PreviousExecutionState != ApplicationExecutionState.Running)
00058             {
00059                 bool loadState = (e.PreviousExecutionState == ApplicationExecutionState.Terminated);
00060                 ExtendedSplash extendedSplash = new ExtendedSplash(e.SplashScreen, loadState);
00061                 Window.Current.Content = extendedSplash;
00062             }
00063
00064             Window.Current.Activate();
00065         }
00066
00067         /// <summary>
00068         /// Invoked when Navigation to a certain page fails
00069         /// </summary>
00070         /// <param name="sender">The Frame which failed navigation</param>
00071         /// <param name="e">Details about the navigation failure</param>
00072         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00073         {
00074             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00075         }
00076
00077         /// <summary>
00078         /// Invoked when application execution is being suspended.  Application state is saved
00079         /// without knowing whether the application will be terminated or resumed with the contents
00080         /// of memory still intact.
00081         /// </summary>
00082         /// <param name="sender">The source of the suspend request.</param>
00083         /// <param name="e">Details about the suspend request.</param>
00084         private async void OnSuspending(object sender, SuspendingEventArgs e)
00085         {
00086             var deferral = e.SuspendingOperation.GetDeferral();
00087             await SuspensionManager.SaveAsync();
00088             deferral.Complete();
00089         }
00090     }
00091 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cppwinrt/Scenario4_Override.h Source File

  • DateTimeFormatting
  • cppwinrt

Scenario4_Override.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_Override.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario4_Override : Scenario4_OverrideT<Scenario4_Override>
00019     {
00020         Scenario4_Override();
00021
00022         void Display_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario4_Override : Scenario4_OverrideT<Scenario4_Override, implementation::Scenario4_Override>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:19:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LinguisticServices/cppwinrt/pch.cpp Source File

  • LinguisticServices
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PresenceSensor/cppwinrt/SampleConfiguration.cpp Source File

  • PresenceSensor
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Devices::Sensors;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace SDKTemplate;
00021
00022 hstring implementation::MainPage::FEATURE_NAME()
00023 {
00024     return L"Presence Sensor";
00025 }
00026
00027 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00028 {
00029     Scenario{ L"Data Events", xaml_typename<SDKTemplate::Scenario1_DataEvents>() },
00030     Scenario{ L"Polling", xaml_typename<SDKTemplate::Scenario2_Polling>() },
00031     Scenario{ L"Choosing", xaml_typename<SDKTemplate::Scenario3_Choosing>() },
00032 });
00033
00034 hstring winrt::to_hstring(HumanPresence value)
00035 {
00036     switch (value)
00037     {
00038     case HumanPresence::Unknown:
00039         return L"Unknown";
00040     case HumanPresence::Present:
00041         return L"Present";
00042     case HumanPresence::NotPresent:
00043         return L"NotPresent";
00044     }
00045     return to_hstring(static_cast<uint32_t>(value));
00046 }
00047
00048 hstring winrt::to_hstring(HumanEngagement value)
00049 {
00050     switch (value)
00051     {
00052     case HumanEngagement::Unknown:
00053         return L"Unknown";
00054     case HumanEngagement::Engaged:
00055         return L"Engaged";
00056     case HumanEngagement::Unengaged:
00057         return L"Unengaged";
00058     }
00059     return to_hstring(static_cast<uint32_t>(value));
00060 }
Generated on Fri Nov 15 2024 22:17:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cs/SampleConfiguration.cs Source File

  • PenHaptics
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Devices.Haptics;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "PenHaptics C# Sample";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Ink Canvas Tactile Feedback", ClassType=typeof(Scenario1_InkCanvasTactileFeedback)},
00026             new Scenario() { Title="Query Tactile Feedback Support", ClassType=typeof(Scenario2_SupportedTactileFeedback)},
00027             new Scenario() { Title="Inking Feedback", ClassType=typeof(Scenario3_InkingFeedback)},
00028             new Scenario() { Title="Interaction Feedback", ClassType=typeof(Scenario4_InteractionFeedback)},
00029             new Scenario() { Title="Inking and Interaction Feedback", ClassType=typeof(Scenario5_InkingAndInteractionFeedback)},
00030         };
00031
00032         // Mapping between waveform names and waveform values.
00033         public static IReadOnlyDictionary<string, ushort> WaveformNamesMap { get; } = new Dictionary<string, ushort>()
00034             {
00035                 ["BrushContinuous"] = KnownSimpleHapticsControllerWaveforms.BrushContinuous,
00036                 ["BuzzContinuous"] = KnownSimpleHapticsControllerWaveforms.BuzzContinuous,
00037                 ["ChiselMarkerContinuous"] = KnownSimpleHapticsControllerWaveforms.ChiselMarkerContinuous,
00038                 ["Click"] = KnownSimpleHapticsControllerWaveforms.Click,
00039                 ["EraserContinuous"] = KnownSimpleHapticsControllerWaveforms.EraserContinuous,
00040                 ["Error"] = KnownSimpleHapticsControllerWaveforms.Error,
00041                 ["GalaxyPenContinuous"] = KnownSimpleHapticsControllerWaveforms.GalaxyPenContinuous,
00042                 ["Hover"] = KnownSimpleHapticsControllerWaveforms.Hover,
00043                 ["InkContinuous"] = KnownSimpleHapticsControllerWaveforms.InkContinuous,
00044                 ["MarkerContinuous"] = KnownSimpleHapticsControllerWaveforms.MarkerContinuous,
00045                 ["PencilContinuous"] = KnownSimpleHapticsControllerWaveforms.PencilContinuous,
00046                 ["Press"] = KnownSimpleHapticsControllerWaveforms.Press,
00047                 ["Release"] = KnownSimpleHapticsControllerWaveforms.Release,
00048                 ["RumbleContinuous"] = KnownSimpleHapticsControllerWaveforms.RumbleContinuous,
00049                 ["Success"] = KnownSimpleHapticsControllerWaveforms.Success,
00050             };
00051
00052         // Returns the first SimpleHapticsControllerFeedback supported by the provided SimpleHapticsController
00053         // which supports the specified waveform.
00054         public static SimpleHapticsControllerFeedback FindSupportedFeedback(SimpleHapticsController hapticsController, ushort waveform)
00055         {
00056             foreach (SimpleHapticsControllerFeedback feedback in hapticsController.SupportedFeedback)
00057             {
00058                 if (feedback.Waveform == waveform)
00059                 {
00060                     return feedback;
00061                 }
00062             }
00063             return null;
00064         }
00065     }
00066
00067     public class Scenario
00068     {
00069         public string Title { get; set; }
00070         public Type ClassType { get; set; }
00071     }
00072 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSegmentation/cppwinrt/pch.cpp Source File

  • TextSegmentation
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/Scenario1Basic.xaml.cpp Source File

  • Printing
  • cpp

Scenario1Basic.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario1Basic.xaml.h"
00005 #include "PageToPrint.xaml.h"
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace Platform;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::Graphics::Printing;
00013 using namespace Windows::UI::Xaml;
00014 using namespace Windows::UI::Xaml::Controls;
00015 using namespace Windows::UI::Xaml::Controls::Primitives;
00016 using namespace Windows::UI::Xaml::Data;
00017 using namespace Windows::UI::Xaml::Input;
00018 using namespace Windows::UI::Xaml::Media;
00019 using namespace Windows::UI::Xaml::Navigation;
00020
00021 Scenario1Basic::Scenario1Basic()
00022 {
00023     InitializeComponent();
00024 }
00025
00026 void Scenario1Basic::OnPrintButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00027 {
00028     printHelper->ShowPrintUIAsync();
00029 }
00030
00031 void Scenario1Basic::OnNavigatedTo(NavigationEventArgs^ e)
00032 {
00033     if (PrintManager::IsSupported())
00034     {
00035         // Tell the user how to print
00036         MainPage::Current->NotifyUser("Print contract registered with customization, use the Print button to print.", NotifyType::StatusMessage);
00037     }
00038     else
00039     {
00040         // Remove the print button
00041         InvokePrintingButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00042
00043         // Inform user that Printing is not supported
00044         MainPage::Current->NotifyUser("Printing is not supported.", NotifyType::ErrorMessage);
00045
00046         // Printing-related event handlers will never be called if printing
00047         // is not supported, but it's okay to register for them anyway.
00048     }
00049
00050     // Initalize common helper class and register for printing
00051     printHelper = ref new PrintHelper(this);
00052     printHelper->RegisterForPrinting();
00053
00054     // Initialize print content for this scenario
00055     printHelper->PreparePrintContent(ref new PageToPrint());
00056 }
00057
00058 void Scenario1Basic::OnNavigatedFrom(NavigationEventArgs^ e)
00059 {
00060     if (printHelper)
00061     {
00062         printHelper->UnregisterForPrinting();
00063     }
00064 }
Generated on Fri Nov 15 2024 22:21:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CashDrawer/cpp/pch.h Source File

  • CashDrawer
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cs/Scenario1_SelectDisplay.xaml.cs Source File

  • LineDisplay
  • cs

Scenario1_SelectDisplay.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.Core;
00014 using Windows.Devices.Enumeration;
00015 using Windows.Devices.PointOfService;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario1_SelectDisplay : Page
00024     {
00025         private MainPage rootPage = MainPage.Current;
00026         private DeviceWatcher watcher;
00027
00028         public Scenario1_SelectDisplay()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         protected override void OnNavigatedTo(NavigationEventArgs e)
00034         {
00035             RestartWatcher();
00036         }
00037
00038         protected override void OnNavigatedFrom(NavigationEventArgs e)
00039         {
00040             StopWatcher();
00041         }
00042
00043         private void RestartWatcher()
00044         {
00045             StopWatcher();
00046
00047             // Clear any old LineDisplay devices from the list box.
00048             DisplaysListBox.Items.Clear();
00049
00050             // Enumerate the LineDisplay devices and put them in our list box.
00051             watcher = DeviceInformation.CreateWatcher(LineDisplay.GetDeviceSelector(PosConnectionTypes.All));
00052             watcher.Added += Watcher_Added;
00053             watcher.EnumerationCompleted += Watcher_EnumerationCompleted;
00054             watcher.Start();
00055         }
00056
00057         private void StopWatcher()
00058         {
00059             if (watcher != null && (watcher.Status == DeviceWatcherStatus.Started))
00060             {
00061                 watcher.Stop();
00062             }
00063             watcher = null;
00064         }
00065
00066         private async void Watcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo)
00067         {
00068             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00069             {
00070                 var item = new ListBoxItem();
00071                 item.Content = deviceInfo.Name;
00072                 item.Tag = deviceInfo.Id;
00073                 DisplaysListBox.Items.Add(item);
00074             });
00075         }
00076
00077         private void Watcher_EnumerationCompleted(DeviceWatcher sender, object e)
00078         {
00079             sender.Stop();
00080         }
00081
00082         private async void SelectButton_Click(object sender, RoutedEventArgs e)
00083         {
00084             var item = (ListBoxItem)DisplaysListBox.SelectedValue;
00085             SelectButton.IsEnabled = false;
00086
00087             var name = (string)item.Content;
00088             var deviceId = (string)item.Tag;
00089             using (ClaimedLineDisplay lineDisplay = await ClaimedLineDisplay.FromIdAsync(deviceId))
00090                 {
00091                     if (lineDisplay != null)
00092                     {
00093                         await lineDisplay.DefaultWindow.TryClearTextAsync();
00094                         rootPage.NotifyUser($"Selected: {name}", NotifyType.StatusMessage);
00095
00096                         // Save this device ID for other scenarios.
00097                         rootPage.LineDisplayId = deviceId;
00098                     }
00099                     else
00100                     {
00101                         rootPage.NotifyUser("Unable to claim the Line Display", NotifyType.ErrorMessage);
00102                     }
00103
00104                 SelectButton.IsEnabled = true;
00105             }
00106         }
00107
00108         private void RefreshButton_Click(object sender, RoutedEventArgs e)
00109         {
00110             RestartWatcher();
00111         }
00112
00113         // Helpers that are used by XAML binding to enable and disable buttons.
00114         public bool IsNonNull(object item) => item != null;
00115     }
00116 }
Generated on Fri Nov 15 2024 22:20:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cpp/Tasks/PedometerBackgroundTask.h Source File

  • Pedometer
  • cpp
  • Tasks

PedometerBackgroundTask.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // PedometerBackgroundTask.h
00014 // Declaration of the PedometerBackgroundTask class
00015 //
00016
00017 #pragma once
00018
00019 namespace Tasks
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class PedometerBackgroundTask sealed : public Windows::ApplicationModel::Background::IBackgroundTask
00023     {
00024
00025     public:
00026         PedometerBackgroundTask() {}
00027
00028         virtual void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance);
00029         void OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason);
00030
00031     private:
00032         ~PedometerBackgroundTask() {}
00033
00034         Windows::ApplicationModel::Background::IBackgroundTaskInstance^ TaskInstance;
00035     };
00036 }
Generated on Fri Nov 15 2024 22:20:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2 Member List

This is the complete list of members for Scenario2, including all inherited members.
m_scenario2ViewModel | Scenario2 | [private]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario2 | [inline, protected]
Scenario2() | Scenario2 | [inline]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2ViewModel Member List

This is the complete list of members for Scenario2ViewModel, including all inherited members.
AlljoynBusAttachment_AuthenticationComplete(AllJoynBusAttachment sender, AllJoynAuthenticationCompleteEventArgs args) | Scenario2ViewModel | [inline, private]
AlljoynBusAttachment_CredentialsRequested(AllJoynBusAttachment sender, AllJoynCredentialsRequestedEventArgs args) | Scenario2ViewModel | [inline, private]
AlljoynBusAttachment_StateChanged(AllJoynBusAttachment sender, AllJoynBusAttachmentStateChangedEventArgs args) | Scenario2ViewModel | [inline, private]
ConvertUtf8ToHex(string inputString) | Scenario2ViewModel | [inline, private, static]
Key | Scenario2ViewModel |
LaunchProducer | Scenario2ViewModel |
m_busAttachment | Scenario2ViewModel | [private]
m_dispatcher | Scenario2ViewModel | [private]
m_isBusAttachmentConnected | Scenario2ViewModel | [private]
m_key | Scenario2ViewModel | [private]
m_producer | Scenario2ViewModel | [private]
m_rootPage | Scenario2ViewModel | [private]
m_sampleNetworkInfoVisibility | Scenario2ViewModel | [private]
m_selectedSampleNetwork | Scenario2ViewModel | [private]
OnboardingService_ConnectRequestRecieved(object sender, EventArgs e) | Scenario2ViewModel | [inline, private]
PropertyChanged | Scenario2ViewModel |
RaisePropertyChangedEventAsync([CallerMemberName]string name="") | Scenario2ViewModel | [inline, protected]
SampleNetworkInfoVisibility | Scenario2ViewModel |
SampleNetworkList | Scenario2ViewModel |
Scenario2ViewModel() | Scenario2ViewModel | [inline]
ScenarioCleanup() | Scenario2ViewModel | [inline]
SelectedSampleNetwork | Scenario2ViewModel |
SelectedSampleNetworkAuthentication | Scenario2ViewModel |
SelectedSampleNetworkPassword | Scenario2ViewModel |
Start() | Scenario2ViewModel | [inline, private]
UpdateStatusAsync(string status, NotifyType statusType) | Scenario2ViewModel | [inline, private]
Generated on Fri Nov 15 2024 22:23:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Item Member List

This is the complete list of members for Item, including all inherited members.
GenerateImageSource(int i) | Item | [inline, private, static]
GetItems(int count) | Item | [inline, static]
GetNewItem(int i, int j) | Item | [inline, static]
Id | Item |
ImageSource | Item |
Name | Item |
sources | Item | [private, static]
ToString() | Item | [inline]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cs/SampleConfiguration.cs Source File

  • SecondaryTiles
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using Windows.UI.Xaml.Controls;
00013 using System.Collections.Generic;
00014 using Windows.Foundation;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Media;
00017 using Windows.ApplicationModel.Activation;
00018
00019 namespace SDKTemplate
00020 {
00021     public partial class App
00022     {
00023         partial void LaunchCompleted(LaunchActivatedEventArgs e)
00024         {
00025             MainPage.Current.LaunchParam = e.Arguments;
00026         }
00027     }
00028
00029     public partial class MainPage : Page
00030     {
00031         public const string FEATURE_NAME = "Secondary Tile C#";
00032
00033         #region Secondary Tile scenario specific variables
00034
00035         public const string logoSecondaryTileId = "SecondaryTile.Logo";
00036         public const string dynamicTileId = "SecondaryTile.LiveTile";
00037         public const string appbarTileId = "SecondaryTile.AppBar";
00038
00039         #endregion
00040
00041         List<Scenario> scenarios = new List<Scenario>
00042         {
00043             new Scenario() { Title = "Pin Tile",                            ClassType = typeof(SDKTemplate.Scenario1_PinTile) },
00044             new Scenario() { Title = "Unpin Tile",                          ClassType = typeof(SDKTemplate.Scenario2_UnpinTile) },
00045             new Scenario() { Title = "Enumerate Tiles",                     ClassType = typeof(SDKTemplate.Scenario3_EnumerateTiles) },
00046             new Scenario() { Title = "Is Tile Pinned?",                     ClassType = typeof(SDKTemplate.Scenario4_TilePinned) },
00047             new Scenario() { Title = "Show Activation Arguments",           ClassType = typeof(SDKTemplate.Scenario5_LaunchedFromSecondaryTile) },
00048             new Scenario() { Title = "Secondary Tile Notifications",        ClassType = typeof(SDKTemplate.Scenario6_SecondaryTileNotification) },
00049             new Scenario() { Title = "Pin/Unpin Through Appbar",            ClassType = typeof(SDKTemplate.Scenario7_PinFromAppbar) },
00050             new Scenario() { Title = "Update Secondary Tile Default Logo",  ClassType = typeof(SDKTemplate.Scenario8_UpdateAsync) },
00051         };
00052
00053         #region Secondary Tile specific methods
00054
00055         // Gets the rectangle of the element
00056         public static Rect GetElementRect(object e)
00057         {
00058             var element = (FrameworkElement)e;
00059             GeneralTransform buttonTransform = element.TransformToVisual(null);
00060             return buttonTransform.TransformBounds(new Rect(0, 0, element.ActualWidth, element.ActualHeight));
00061         }
00062
00063         string launchParam;
00064         public string LaunchParam
00065         {
00066             get => launchParam;
00067             set
00068             {
00069                 launchParam = value;
00070                 if (!string.IsNullOrEmpty(launchParam))
00071                 {
00072                     // Force a navigation to the secondary tile launch page.
00073                     for (int index = 0; index < scenarios.Count; index++)
00074                     {
00075                         if (scenarios[index].ClassType == typeof(SDKTemplate.Scenario5_LaunchedFromSecondaryTile))
00076                         {
00077                             if (ScenarioControl.SelectedIndex == index)
00078                             {
00079                                 ScenarioControl.SelectedIndex = -1;
00080                             }
00081                             ScenarioControl.SelectedIndex = index;
00082                         }
00083                     }
00084                 }
00085             }
00086         }
00087         #endregion
00088     }
00089
00090     public class Scenario
00091     {
00092         public string Title { get; set; }
00093         public Type ClassType { get; set; }
00094     }
00095 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContextMenu/cpp/Scenario1.xaml.h Source File

  • ContextMenu
  • cpp

Scenario1.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario1.xaml.h
00013 // Declaration of the Scenario1 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario1.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024     public ref class Scenario1 sealed
00025     {
00026     public:
00027         Scenario1();
00028
00029     private:
00030         MainPage^ rootPage;
00031
00032         void AttachmentImage_RightTapped(Platform::Object^ sender, Windows::UI::Xaml::Input::RightTappedRoutedEventArgs^ e);
00033         Windows::Foundation::Rect Scenario1::GetElementRect(Windows::UI::Xaml::FrameworkElement^ element);
00034     };
00035 }
Generated on Fri Nov 15 2024 22:17:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_PreviewSettings Member List

This is the complete list of members for Scenario1_PreviewSettings, including all inherited members.
_previewer | Scenario1_PreviewSettings | [private]
ComboBoxSettings_Changed(object sender, RoutedEventArgs e) | Scenario1_PreviewSettings | [inline, private]
InitializeCameraButton_Click(object sender, RoutedEventArgs e) | Scenario1_PreviewSettings | [inline, private]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario1_PreviewSettings | [inline, protected]
PopulateSettingsComboBox() | Scenario1_PreviewSettings | [inline, private]
rootPage | Scenario1_PreviewSettings | [private]
Scenario1_PreviewSettings() | Scenario1_PreviewSettings | [inline]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cs/Scenario4_EdgeTappedListView.xaml.cs Source File

  • XamlListView
  • cs

Scenario4_EdgeTappedListView.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.Collections.Generic;
00013 using System.Collections.ObjectModel;
00014 using Windows.UI.Core;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class Scenario4_EdgeTappedListView : Page
00021     {
00022         private ObservableCollection<Contact> Contacts;
00023
00024         public Scenario4_EdgeTappedListView()
00025         {
00026             InitializeComponent();
00027
00028             Contacts = Contact.GetContacts(50);
00029             MyListView.ItemsSource = Contacts;
00030
00031             // We set the state of the commands on the appbar
00032             SetCommandsVisibility(MyListView);
00033         }
00034         protected override void OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
00035         {
00036             // This is how devs can handle the back button
00037             SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
00038         }
00039         protected override void OnNavigatedFrom(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
00040         {
00041             SystemNavigationManager.GetForCurrentView().BackRequested -= OnBackRequested;
00042         }
00043         private void OnEdgeTapped(ListView sender, ListViewEdgeTappedEventArgs e)
00044         {
00045             // When user releases the pointer after pressing on the left edge of the item,
00046             // the ListView will switch to Multiple Selection
00047             MyListView.SelectionMode = ListViewSelectionMode.Multiple;
00048             // Also, we want the Left Edge Tap funcionality will be no longer enable.
00049             MyListView.IsItemLeftEdgeTapEnabled = false;
00050             // It's desirable that the Appbar shows the actions available for multiselect
00051             SetCommandsVisibility(MyListView);
00052         }
00053         private void UpdateSelectionUI()
00054         {
00055             // When there are no selected items, the list returns to None selection mode.
00056             if (MyListView.SelectedItems.Count == 0)
00057             {
00058                 MyListView.SelectionMode = ListViewSelectionMode.None;
00059                 MyListView.IsItemLeftEdgeTapEnabled = true;
00060                 SetCommandsVisibility(MyListView);
00061             }
00062         }
00063         private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
00064         {
00065             UpdateSelectionUI();
00066         }
00067         private void OnBackRequested(object sender, BackRequestedEventArgs e)
00068         {
00069             // We want to exit from the multiselect mode when pressing back button
00070             if (!e.Handled && MyListView.SelectionMode == ListViewSelectionMode.Multiple)
00071             {
00072                 MyListView.SelectedItems.Clear();
00073                 UpdateSelectionUI();
00074                 e.Handled = true;
00075             }
00076         }
00077         private void SetCommandsVisibility(ListView listView)
00078         {
00079             if (listView.SelectionMode == ListViewSelectionMode.Multiple || listView.SelectedItems.Count > 1)
00080             {
00081                 SelectAppBarBtn.Visibility = Visibility.Collapsed;
00082                 CancelSelectionAppBarBtn.Visibility = Visibility.Visible;
00083                 AddItemAppBarBtn.Visibility = Visibility.Collapsed;
00084                 RemoveItemAppBarBtn.Visibility = Visibility.Visible;
00085                 SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
00086             }
00087             else
00088             {
00089                 SelectAppBarBtn.Visibility = Visibility.Visible;
00090                 CancelSelectionAppBarBtn.Visibility = Visibility.Collapsed;
00091                 AddItemAppBarBtn.Visibility = Visibility.Visible;
00092                 RemoveItemAppBarBtn.Visibility = Visibility.Collapsed;
00093                 SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
00094             }
00095         }
00096         private void SelectItems(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00097         {
00098             MyListView.SelectionMode = ListViewSelectionMode.Multiple;
00099             MyListView.IsItemLeftEdgeTapEnabled = false;
00100             SetCommandsVisibility(MyListView);
00101         }
00102         private void AddItem(object sender, RoutedEventArgs e)
00103         {
00104             Contacts.Add(Contact.GetNewContact());
00105         }
00106         private void RemoveItem(object sender, RoutedEventArgs e)
00107         {
00108             if (MyListView.SelectedIndex != -1)
00109             {
00110                 // When an item is removed from the underlying collection, the Listview is updated,
00111                 // hence the this.SelectedItems is updated as well.
00112                 // It's needed to copy the selected items collection to iterate over other collection that
00113                 // is not updated.
00114                 List<Contact> selectedItems = new List<Contact>();
00115                 foreach (Contact item in MyListView.SelectedItems)
00116                 {
00117                     selectedItems.Add(item);
00118                 }
00119                 foreach (Contact item in selectedItems)
00120                 {
00121                     Contacts.Remove(item);
00122                 }
00123             }
00124         }
00125         private void CancelSelection(object sender, RoutedEventArgs e)
00126         {
00127             // If the list is multiple selection mode but there is no items selected,
00128             // then the list should return to the initial selection mode.
00129             if (MyListView.SelectedItems.Count == 0)
00130             {
00131                 MyListView.SelectionMode = ListViewSelectionMode.None;
00132                 MyListView.IsItemLeftEdgeTapEnabled = true;
00133                 SetCommandsVisibility(MyListView);
00134             }
00135             else
00136             {
00137                 MyListView.SelectedItems.Clear();
00138             }
00139         }
00140     }
00141 }
Generated on Fri Nov 15 2024 22:22:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3 Member List

This is the complete list of members for Scenario3, including all inherited members.
castingDevicesList_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario3 | [inline, private]
connection | Scenario3 | [private]
Connection_ErrorOccurred(CastingConnection sender, CastingConnectionErrorOccurredEventArgs args) | Scenario3 | [inline, private]
Connection_StateChanged(CastingConnection sender, object args) | Scenario3 | [inline, private]
disconnectButton_Click(object sender, RoutedEventArgs e) | Scenario3 | [inline, private]
loadButton_Click(object sender, RoutedEventArgs e) | Scenario3 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3 | [inline, protected]
rootPage | Scenario3 | [private]
Scenario3() | Scenario3 | [inline]
watcher | Scenario3 | [private]
Watcher_Added(DeviceWatcher sender, DeviceInformation args) | Scenario3 | [inline, private]
Watcher_EnumerationCompleted(DeviceWatcher sender, object args) | Scenario3 | [inline, private]
Watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args) | Scenario3 | [inline, private]
Watcher_Stopped(DeviceWatcher sender, object args) | Scenario3 | [inline, private]
watcherControlButton_Click(object sender, RoutedEventArgs e) | Scenario3 | [inline, private]
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Personalization/cs/SetLockScreenImage.xaml.cs Source File

  • Personalization
  • cs

SetLockScreenImage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Storage;
00014 using Windows.Storage.Pickers;
00015 using Windows.Storage.Streams;
00016 using Windows.System.UserProfile;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Media.Imaging;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class SetLockScreenImage : Page
00025     {
00026         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00027         // as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         public SetLockScreenImage()
00031         {
00032             InitializeComponent();
00033         }
00034
00035         /// <summary>
00036         /// Invoked when this page is about to be displayed in a Frame.
00037         /// </summary>
00038         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00039         /// property is typically used to configure the page.</param>
00040         protected override void OnNavigatedTo(NavigationEventArgs e)
00041         {
00042         }
00043
00044         private async void PickAndSetButton_Click(object sender, RoutedEventArgs e)
00045         {
00046             rootPage.NotifyUser("", NotifyType.StatusMessage);
00047             FileOpenPicker imagePicker = new FileOpenPicker
00048             {
00049                 ViewMode = PickerViewMode.Thumbnail,
00050                 SuggestedStartLocation = PickerLocationId.PicturesLibrary,
00051                 FileTypeFilter = { ".jpg", ".jpeg", ".png", ".bmp" }
00052             };
00053
00054             StorageFile imageFile = await imagePicker.PickSingleFileAsync();
00055             if (imageFile != null)
00056             {
00057                 try
00058                 {
00059                     // Application now has access to the picked file, setting image to lockscreen.  This will fail if the file is an invalid format.
00060                     await LockScreen.SetImageFileAsync(imageFile);
00061
00062                     // Retrieve the lock screen image that was set
00063                     IRandomAccessStream imageStream = LockScreen.GetImageStream();
00064                     if (imageStream != null)
00065                     {
00066                         BitmapImage lockScreen = new BitmapImage();
00067                         lockScreen.SetSource(imageStream);
00068                         LockScreenImage.Source = lockScreen;
00069                         LockScreenImage.Visibility = Visibility.Visible;
00070                     }
00071                     else
00072                     {
00073                         LockScreenImage.Visibility = Visibility.Collapsed;
00074                         rootPage.NotifyUser("Setting the lock screen image failed.", NotifyType.StatusMessage);
00075                     }
00076                 }
00077                 catch (Exception)
00078                 {
00079                     LockScreenImage.Visibility = Visibility.Collapsed;
00080                     rootPage.NotifyUser("Invalid image selected or error opening stream.", NotifyType.ErrorMessage);
00081                 }
00082             }
00083             else
00084             {
00085                 LockScreenImage.Visibility = Visibility.Collapsed;
00086                 rootPage.NotifyUser("No file was selected using the picker.", NotifyType.StatusMessage);
00087             }
00088         }
00089     }
00090 }
Generated on Fri Nov 15 2024 22:20:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cs/constants.cs Source File

  • ApplicationResources
  • cs

constants.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System.Collections.Generic;
00012 using System;
00013 using SDKTemplate;
00014
00015 namespace SDKTemplate
00016 {
00017     public partial class MainPage
00018     {
00019         // Change the string below to reflect the name of your sample.
00020         // This is used on the main page as the title of the sample.
00021         public const string FEATURE_NAME = "Application Resources C# sample";
00022
00023         // Change the array below to reflect the name of your scenarios.
00024         // This will be used to populate the list of scenarios on the main page with
00025         // which the user will choose the specific scenario that they are interested in.
00026         // These should be in the form: "Navigating to a web page".
00027         // The code in MainPage will take care of turning this into: "1) Navigating to a web page"
00028         List<Scenario> scenarios = new List<Scenario>
00029         {
00030             new Scenario() { Title = "String Resources In XAML", ClassType = typeof(Scenario1) },
00031             new Scenario() { Title = "File Resources In XAML", ClassType = typeof(Scenario2) },
00032             new Scenario() { Title = "String Resources In Code", ClassType = typeof(Scenario3) },
00033             new Scenario() { Title = "Resources in the AppX manifest", ClassType = typeof(Scenario4) },
00034             new Scenario() { Title = "Additional Resource Files", ClassType = typeof(Scenario5) },
00035             new Scenario() { Title = "Class Library Resources", ClassType = typeof(Scenario6) },
00036             new Scenario() { Title = "Runtime Changes/Events", ClassType = typeof(Scenario7) },
00037             new Scenario() { Title = "Application Languages", ClassType = typeof(Scenario8) },
00038             new Scenario() { Title = "Override Languages", ClassType = typeof(Scenario9) },
00039             new Scenario() { Title = "Multi-dimensional fallback", ClassType = typeof(Scenario10) },
00040             new Scenario() { Title = "Working with webservices", ClassType = typeof(Scenario11) },
00041             new Scenario() { Title = "Retrieving resources in non-UI threads", ClassType = typeof(Scenario12) },
00042             new Scenario() { Title = "File resources in code", ClassType = typeof(Scenario13) },
00043         };
00044     }
00045
00046     public class Scenario
00047     {
00048         public string Title { get; set; }
00049
00050         public Type ClassType { get; set; }
00051
00052         public override string ToString()
00053         {
00054             return Title;
00055         }
00056     }
00057 }
Generated on Fri Nov 15 2024 22:18:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CylinderMesh Member List

This is the complete list of members for CylinderMesh, including all inherited members.
CylinderMesh(_In_ winrt::com_ptr< ID3D11Device3 > const &device, uint16_t segments) | CylinderMesh |
m_indexBuffer | MeshObject | [protected]
m_indexCount | MeshObject | [protected]
m_vertexBuffer | MeshObject | [protected]
m_vertexCount | MeshObject | [protected]
MeshObject() | MeshObject |
Render(_In_ ID3D11DeviceContext *context) | MeshObject | [virtual]
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SurfaceMeshProperties Member List

This is the complete list of members for SurfaceMeshProperties, including all inherited members.
coordinateSystem | SurfaceMeshProperties
indexCount | SurfaceMeshProperties
indexFormat | SurfaceMeshProperties
normalStride | SurfaceMeshProperties
vertexPositionScale | SurfaceMeshProperties
vertexStride | SurfaceMeshProperties
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/Common/DeviceResources.cpp Source File

  • ComplexInk
  • cpp
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
00002 #include "DeviceResources.h"
00003
00004 using namespace D2D1;
00005 using namespace DirectX;
00006 using namespace Microsoft::WRL;
00007 using namespace Windows::UI::Xaml::Media::Imaging;
00008
00009 DX::DeviceResources::DeviceResources(Windows::Foundation::Size size, Windows::Foundation::Size sizeViewport) :
00010     _beginDrawStarted(false),
00011     _contentZoomFactor(1.0f)
00012 {
00013     SetContentSize(size);
00014     SetViewSize(sizeViewport);
00015     _logicalDPI = Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->LogicalDpi;
00016     _dpiAdjustmentRatio = _logicalDPI / DEFAULT_DPI;
00017     CreateDeviceResources();
00018 }
00019
00020 // Initialize hardware-dependent resources.
00021 void DX::DeviceResources::CreateDeviceResources()
00022 {
00023     // This flag adds support for surfaces with a different color channel ordering
00024     // than the API default. It is required for compatibility with Direct2D.
00025     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00026     ComPtr<ID3D11DeviceContext> context;
00027     D3D_FEATURE_LEVEL d3dFeatureLevel;
00028
00029     // Initialize Direct2D resources.
00030     D2D1_FACTORY_OPTIONS options;
00031     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00032
00033     // Initialize the Direct2D Factory.
00034     DX::ThrowIfFailed(
00035         D2D1CreateFactory(
00036         D2D1_FACTORY_TYPE_SINGLE_THREADED,
00037         __uuidof(ID2D1Factory2),
00038         &options,
00039         &_d2dFactory
00040         )
00041         );
00042
00043
00044     // Create the Direct3D 11 API device object.
00045     DX::ThrowIfFailed(
00046         D3D11CreateDevice(
00047         nullptr,                        // Specify nullptr to use the default adapter.
00048         D3D_DRIVER_TYPE_HARDWARE,
00049         nullptr,
00050         creationFlags,                  // Set debug and Direct2D compatibility flags.
00051         nullptr,                        // List of feature levels this app can support.
00052         0,
00053         D3D11_SDK_VERSION,              // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00054         &_d3dDevice,                   // Returns the Direct3D device created.
00055         &d3dFeatureLevel,
00056         &context
00057         )
00058         );
00059
00060     // Get the Direct3D 11.1 API device.
00061     ComPtr<IDXGIDevice> dxgiDevice;
00062     DX::ThrowIfFailed(
00063         _d3dDevice.As(&dxgiDevice)
00064         );
00065
00066     DX::ThrowIfFailed(
00067         context.As(&_d3dContext)
00068         );
00069
00070     // Create the Direct2D device object and a corresponding context.
00071     DX::ThrowIfFailed(
00072         _d2dFactory->CreateDevice(
00073         dxgiDevice.Get(),
00074         &_d2dDevice
00075         )
00076         );
00077
00078     DX::ThrowIfFailed(
00079         _d2dDevice->CreateDeviceContext(
00080         D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00081         &_d2dContext
00082         )
00083         );
00084
00085     // By default, D2D will treat incoming values as DIPs instead of pixels. By setting the
00086     // logical DPI the application operates on, D2D will use it as a transform factor to scale
00087     // the content. Since the XAML virtual surface image source uses pixel unit instead of DIP,
00088     // such scale will in fact ensure the rendered graphics locate at the right physical pixels
00089     // of the VSIS.
00090     float logicalDPI = _logicalDPI * GetContentZoomFactor();
00091     _d2dContext->SetDpi(logicalDPI, logicalDPI);
00092
00093     // When an application performs animation or image composition of graphics content, it is important
00094     // to use Direct2D grayscale text rendering mode rather than ClearType. The ClearType technique
00095     // operates on the color channels and not the alpha channel, and therefore unable to correctly perform
00096     // image composition or sub-pixel animation of text. ClearType is still a method of choice when it
00097     // comes to direct rendering of text to the destination surface with no subsequent composition required.
00098     _d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00099
00100     // Set content zoom as a scale transform on D2D's device context. That will ensure ink will be
00101     // rendered will appropriate quality when being zoomed.
00102     _dpiAdjustmentRatio *= GetContentZoomFactor();
00103
00104     // Create an image source at the given content size with DPI adjustment. This ensures that we get VSIS image size in physical pixels instead of DIPs.
00105     int pixelWidth = static_cast<int>(ConvertFromDIPToPixelUnit(_contentSize.Width));
00106     int pixelHeight = static_cast<int>(ConvertFromDIPToPixelUnit(_contentSize.Height));
00107     _vsis = ref new VirtualSurfaceImageSource(pixelWidth, pixelHeight);
00108
00109     ComPtr<IUnknown> unknown(reinterpret_cast<IUnknown*>(_vsis));
00110     unknown.As(&_vsisNative);
00111
00112     DX::ThrowIfFailed(
00113         _vsisNative->SetDevice(dxgiDevice.Get())
00114         );
00115 }
00116
00117 // Update logical DPI and invalidate VSIS if needed.
00118 void DX::DeviceResources::SetDPI(float dpi)
00119 {
00120     if (dpi != _logicalDPI)
00121     {
00122         _logicalDPI = dpi;
00123         RefreshScaleFactor();
00124     }
00125 }
00126
00127 // Update content zoom factor and invalidate VSIS if needed.
00128 void DX::DeviceResources::SetContentZoomFactor(float contentZoomFactor)
00129 {
00130     if (ShouldApplyContentZoomFactor(contentZoomFactor))
00131     {
00132         _contentZoomFactor = contentZoomFactor;
00133         RefreshScaleFactor();
00134     }
00135 }
00136
00137 // Call this method when the app suspends. It provides a hint to the driver that the app
00138 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00139 void DX::DeviceResources::Trim()
00140 {
00141     ComPtr<IDXGIDevice3> dxgiDevice;
00142     _d3dDevice.As(&dxgiDevice);
00143     dxgiDevice->Trim();
00144 }
00145
00146 void DX::DeviceResources::RefreshScaleFactor()
00147 {
00148     float logicalDPI = GetDPI() * GetContentZoomFactor();
00149     _dpiAdjustmentRatio = logicalDPI / DEFAULT_DPI;
00150
00151     if (_d2dContext != nullptr)
00152     {
00153         _d2dContext->SetDpi(logicalDPI, logicalDPI);
00154         InvalidateAndResizeVSIS();
00155     }
00156 }
00157
00158 void DX::DeviceResources::GetUpdateRects(_Outptr_ RECT** ppUpdateRects, _Out_ ULONG* pUpdateRectsCount)
00159 {
00160     assert(_vsisNative != nullptr);
00161     *pUpdateRectsCount = 0;
00162
00163     DX::ThrowIfFailed(
00164         _vsisNative->GetUpdateRectCount(pUpdateRectsCount)
00165         );
00166
00167     *ppUpdateRects = new RECT[*pUpdateRectsCount];
00168
00169     if (*ppUpdateRects != nullptr)
00170     {
00171         DX::ThrowIfFailed(
00172             _vsisNative->GetUpdateRects(*ppUpdateRects, *pUpdateRectsCount)
00173             );
00174     }
00175     else
00176     {
00177         DX::ThrowIfFailed(E_OUTOFMEMORY);
00178     }
00179 }
00180
00181 void DX::DeviceResources::InvalidateRect(RECT const& updateRect)
00182 {
00183     assert(_vsisNative != nullptr);
00184     DX::ThrowIfFailed(
00185         _vsisNative->Invalidate(updateRect)
00186         );
00187 }
00188
00189 void DX::DeviceResources::InvalidateContentRect()
00190 {
00191     long pixelContentWidth = static_cast<long>(ConvertFromDIPToPixelUnit(_contentSize.Width));
00192     long pixelContentHeight = static_cast<long>(ConvertFromDIPToPixelUnit(_contentSize.Height));
00193     RECT bounds = {0, 0, pixelContentWidth, pixelContentHeight};
00194     InvalidateRect(bounds);
00195 }
00196
00197 // If an update rect is passed in through the input parameter, assume it is
00198 // in DIP units and we need to internally convert it to physical pixel units.
00199 void  DX::DeviceResources::BeginDraw(_In_opt_ const RECT* pUpdateRect)
00200 {
00201     assert(_vsisNative != nullptr);
00202     long pixelViewWidth = static_cast<long>(ConvertFromDIPToPixelUnit(_viewSize.Width));
00203     long pixelViewHeight = static_cast<long>(ConvertFromDIPToPixelUnit(_viewSize.Height));
00204     RECT updateRect = { 0, 0, pixelViewWidth, pixelViewHeight };
00205     RECT emptyRect = { 0, 0, 0, 0 };
00206
00207     if (pUpdateRect == nullptr)
00208     {
00209         RECT visibleRect = {};
00210
00211         DX::ThrowIfFailed(
00212             _vsisNative->GetVisibleBounds(&visibleRect)
00213             );
00214
00215         if (visibleRect != emptyRect) { updateRect = visibleRect; }
00216     }
00217     else
00218     {
00219         if (*pUpdateRect != emptyRect)
00220         {
00221             updateRect = *pUpdateRect;
00222         }
00223     }
00224
00225     POINT offset;
00226     ComPtr<IDXGISurface> surface;
00227
00228     // Returns a target surface and an offset to use as the top left origin when drawing.
00229     DX::ThrowIfFailed(
00230         _vsisNative->BeginDraw(updateRect, &surface, &offset)
00231     );
00232
00233     // Create render target.
00234     ComPtr<ID2D1Bitmap1> bitmap;
00235     DX::ThrowIfFailed(
00236         _d2dContext->CreateBitmapFromDxgiSurface(
00237         surface.Get(),
00238         nullptr,
00239         &bitmap
00240         )
00241         );
00242
00243     _d2dContext->BeginDraw();
00244
00245     // Set the context transformation based on the offset (in physical pixel units) returned by VSIS's BeginDraw.
00246     // Since D2D operates on DIP units, we need to do the inverse DPI adjustment to make the coordinates match.
00247     // Note that we don't round the return value because D2D will scale everything back up by the DPI scale factor
00248     // and the result should land on the correct pixel as we operate in physical pixels.
00249     _d2dContext->SetTransform(
00250         D2D1::Matrix3x2F::Translation(
00251         ConvertFromPixelToDIPUnit(static_cast<float>(offset.x - updateRect.left), false/*rounded*/),
00252         ConvertFromPixelToDIPUnit(static_cast<float>(offset.y - updateRect.top), false/*rounded*/)
00253         )
00254         );
00255
00256     _d2dContext->SetTarget(bitmap.Get());
00257
00258     _beginDrawStarted = true;
00259 }
00260
00261 void DX::DeviceResources::EndDraw()
00262 {
00263     if (_beginDrawStarted)
00264     {
00265         _beginDrawStarted = false;
00266
00267         _d2dContext->SetTarget(nullptr);
00268
00269         // End the drawing
00270         DX::ThrowIfFailed(
00271             _d2dContext->EndDraw()
00272             );
00273
00274         DX::ThrowIfFailed(
00275             _vsisNative->EndDraw()
00276             );
00277     }
00278 }
00279
00280 void DX::DeviceResources::ClearTarget()
00281 {
00282     // Set the background on which objects will be rendered on top
00283     Windows::UI::Color color = CanvasBackgroundColor;
00284
00285     _d2dContext->Clear(D2D1::ColorF(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f));
00286
00287 }
00288
00289 void DX::DeviceResources::SetContentSize(Windows::Foundation::Size size)
00290 {
00291     _contentSize = size;
00292     InvalidateAndResizeVSIS();
00293 }
00294
00295 void DX::DeviceResources::InvalidateAndResizeVSIS()
00296 {
00297     if (_vsisNative != nullptr)
00298     {
00299         int pixelWidth = static_cast<int>(ConvertFromDIPToPixelUnit(_contentSize.Width));
00300         int pixelHeight = static_cast<int>(ConvertFromDIPToPixelUnit(_contentSize.Height));
00301
00302         DX::ThrowIfFailed(
00303             _vsisNative->Resize(pixelWidth, pixelHeight)
00304             );
00305         RECT rect = { 0, 0, pixelWidth, pixelHeight };
00306         DX::ThrowIfFailed(
00307             _vsisNative->Invalidate(rect)
00308             );
00309     }
00310 }
00311
00312 void DX::DeviceResources::SetViewSize(Windows::Foundation::Size size)
00313 {
00314     _viewSize = size;
00315 }
00316
00317 RECT DX::DeviceResources::AdjustUpdateRect(RECT const& updateRect)
00318 {
00319     RECT newUpdateRect = { 0, 0, 0, 0 };
00320     // Ensure update rect is within content rect's boundary and do DPI adjustment as needed.
00321     // We also inflate the rect further by rounding down the top/left position and rounding up
00322     // the bottom/right position.
00323     newUpdateRect.left = static_cast<long>(ConvertFromDIPToPixelUnit(updateRect.left < 0 ? 0 : static_cast<float>(updateRect.left), false/*rounded*/));
00324     newUpdateRect.top = static_cast<long>(ConvertFromDIPToPixelUnit(updateRect.top < 0 ? 0 : static_cast<float>(updateRect.top), false/*rounded*/));
00325     newUpdateRect.right = static_cast<long>(ConvertFromDIPToPixelUnit(updateRect.right > _contentSize.Width ? _contentSize.Width : static_cast<float>(updateRect.right)));
00326     newUpdateRect.bottom = static_cast<long>(ConvertFromDIPToPixelUnit(updateRect.bottom > _contentSize.Height ? _contentSize.Height : static_cast<float>(updateRect.bottom)));
00327
00328     return newUpdateRect;
00329 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
__pad0__ | sealed |
_dims | sealed | [private]
_temperature | sealed | [private]
BakeBread(Platform::String^flavor) | sealed | [virtual]
BreadBaked | sealed |
Oven(Dimensions dimensions) | sealed | [inline]
Oven() | sealed | [inline]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_OpenDrawer Member List

This is the complete list of members for Scenario1_OpenDrawer, including all inherited members.
ClaimCashDrawer() | Scenario1_OpenDrawer | [inline, private]
claimedDrawer | Scenario1_OpenDrawer | [private]
CreateDefaultCashDrawerObject() | Scenario1_OpenDrawer | [inline, private]
drawer | Scenario1_OpenDrawer | [private]
EnableCashDrawer() | Scenario1_OpenDrawer | [inline, private]
InitDrawerButton_Click(object sender, RoutedEventArgs e) | Scenario1_OpenDrawer | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_OpenDrawer | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_OpenDrawer | [inline, protected]
OpenCashDrawer() | Scenario1_OpenDrawer | [inline, private]
OpenDrawerButton_Click(object sender, RoutedEventArgs e) | Scenario1_OpenDrawer | [inline, private]
ResetScenarioState() | Scenario1_OpenDrawer | [inline, private]
rootPage | Scenario1_OpenDrawer | [private]
Scenario1_OpenDrawer() | Scenario1_OpenDrawer | [inline]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppWindow/cs/Scenario1_SecondaryWindow.xaml.cs Source File

  • AppWindow
  • cs

Scenario1_SecondaryWindow.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.WindowManagement;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Hosting;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario1_SecondaryWindow : Page
00022     {
00023         private AppWindow appWindow;
00024         private Frame appWindowFrame = new Frame();
00025
00026         public Scenario1_SecondaryWindow()
00027         {
00028             InitializeComponent();
00029         }
00030
00031         protected override async void OnNavigatedFrom(NavigationEventArgs e)
00032         {
00033             if (appWindow != null)
00034             {
00035                 await appWindow.CloseAsync();
00036             }
00037         }
00038
00039         private async void Button_Click(object sender, RoutedEventArgs e)
00040         {
00041             showWindowBtn.IsEnabled = false;
00042
00043             // Only ever create one window. If the AppWindow already exists call TryShow on it to bring it to foreground.
00044             if (appWindow == null)
00045             {
00046                 // Create a new window
00047                 appWindow = await AppWindow.TryCreateAsync();
00048                 // Make sure we release the reference to this window, and release XAML resources, when it's closed
00049                 appWindow.Closed += delegate { appWindow = null; appWindowFrame.Content = null; };
00050                 // Navigate the frame to the page we want to show in the new window
00051                 appWindowFrame.Navigate(typeof(SecondaryAppWindowPage));
00052                 // Attach the XAML content to our window
00053                 ElementCompositionPreview.SetAppWindowContent(appWindow, appWindowFrame);
00054             }
00055
00056             // Now show the window
00057             await appWindow.TryShowAsync();
00058
00059             showWindowBtn.IsEnabled = true;
00060         }
00061     }
00062 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisablingScreenCapture/cppwinrt/Scenario2_Disable.h Source File

  • DisablingScreenCapture
  • cppwinrt

Scenario2_Disable.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Disable.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_Disable : Scenario2_DisableT<Scenario2_Disable>
00019     {
00020         Scenario2_Disable();
00021         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00022         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario2_Disable : Scenario2_DisableT<Scenario2_Disable, implementation::Scenario2_Disable>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cpp/Scenario2_DisplayText.xaml.h Source File

  • LineDisplay
  • cpp

Scenario2_DisplayText.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_DisplayText.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario2_DisplayText sealed
00024     {
00025     public:
00026         Scenario2_DisplayText();
00027
00028     protected:
00029         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030         void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00031
00032     private:
00033         MainPage^ rootPage = MainPage::Current;
00034         Windows::Devices::PointOfService::ClaimedLineDisplay^ lineDisplay;
00035
00036         Concurrency::task<void> InitializeAsync();
00037
00038         void DisplayTextButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039     };
00040 }
Generated on Fri Nov 15 2024 22:20:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/CylinderMesh.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

CylinderMesh.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "CylinderMesh.h"
00014 #include "ConstantBuffers.h"
00015
00016 using namespace DirectX;
00017
00018 CylinderMesh::CylinderMesh(_In_ winrt::com_ptr<ID3D11Device3> const& device, uint16_t segments)
00019 {
00020     D3D11_BUFFER_DESC bd = { 0 };
00021     D3D11_SUBRESOURCE_DATA initData = { 0 };
00022
00023     uint16_t numVertices = 6 * (segments + 1) + 1;
00024     uint16_t numIndices = 3 * segments * 3 * 2;
00025
00026     std::vector<PNTVertex> point(numVertices);
00027     std::vector<uint16_t> index(numIndices);
00028
00029     uint16_t p = 0;
00030     // Top center point (multiple points for texture coordinates).
00031     for (uint16_t a = 0; a <= segments; a++)
00032     {
00033         point[p].position = XMFLOAT3(0.0f, 0.0f, 1.0f);
00034         point[p].normal = XMFLOAT3(0.0f, 0.0f, 1.0f);
00035         point[p].textureCoordinate = XMFLOAT2(static_cast<float>(a) / static_cast<float>(segments), 0.0f);
00036         p++;
00037     }
00038     // Top edge of cylinder: Normals point up for lighting of top surface.
00039     for (uint16_t a = 0; a <= segments; a++)
00040     {
00041         float angle = static_cast<float>(a) / static_cast<float>(segments) * XM_2PI;
00042         point[p].position = XMFLOAT3(cos(angle), sin(angle), 1.0f);
00043         point[p].normal = XMFLOAT3(0.0f, 0.0f, 1.0f);
00044         point[p].textureCoordinate = XMFLOAT2(static_cast<float>(a) / static_cast<float>(segments), 0.0f);
00045         p++;
00046     }
00047     // Top edge of cylinder: Normals point out for lighting of the side surface.
00048     for (uint16_t a = 0; a <= segments; a++)
00049     {
00050         float angle = static_cast<float>(a) / static_cast<float>(segments) * XM_2PI;
00051         point[p].position = XMFLOAT3(cos(angle), sin(angle), 1.0f);
00052         point[p].normal = XMFLOAT3(cos(angle), sin(angle), 0.0f);
00053         point[p].textureCoordinate = XMFLOAT2(static_cast<float>(a) / static_cast<float>(segments), 0.0f);
00054         p++;
00055     }
00056     // Bottom edge of cylinder: Normals point out for lighting of the side surface.
00057     for (uint16_t a = 0; a <= segments; a++)
00058     {
00059         float angle = static_cast<float>(a) / static_cast<float>(segments) * XM_2PI;
00060         point[p].position = XMFLOAT3(cos(angle), sin(angle), 0.0f);
00061         point[p].normal = XMFLOAT3(cos(angle), sin(angle), 0.0f);
00062         point[p].textureCoordinate = XMFLOAT2(static_cast<float>(a) / static_cast<float>(segments), 1.0f);
00063         p++;
00064     }
00065     // Bottom edge of cylinder: Normals point down for lighting of the bottom surface.
00066     for (uint16_t a = 0; a <= segments; a++)
00067     {
00068         float angle = static_cast<float>(a) / static_cast<float>(segments) * XM_2PI;
00069         point[p].position = XMFLOAT3(cos(angle), sin(angle), 0.0f);
00070         point[p].normal = XMFLOAT3(0.0f, 0.0f, -1.0f);
00071         point[p].textureCoordinate = XMFLOAT2(static_cast<float>(a) / static_cast<float>(segments), 1.0f);
00072         p++;
00073     }
00074     // Bottom center of cylinder: Normals point down for lighting on the bottom surface.
00075     for (uint16_t a = 0; a <= segments; a++)
00076     {
00077         point[p].position = XMFLOAT3(0.0f, 0.0f, 0.0f);
00078         point[p].normal = XMFLOAT3(0.0f, 0.0f, -1.0f);
00079         point[p].textureCoordinate = XMFLOAT2(static_cast<float>(a) / static_cast<float>(segments), 1.0f);
00080         p++;
00081     }
00082     m_vertexCount = p;
00083
00084     p = 0;
00085     for (uint16_t a = 0; a < 6; a += 2)
00086     {
00087         uint16_t p1 = a * (segments + 1);
00088         uint16_t p2 = (a + 1) * (segments + 1);
00089         for (uint16_t b = 0; b < segments; b++)
00090         {
00091             if (a < 4)
00092             {
00093                 index[p] = b + p1;
00094                 index[p + 1] = b + p2;
00095                 index[p + 2] = b + p2 + 1;
00096                 p = p + 3;
00097             }
00098             if (a > 0)
00099             {
00100                 index[p] = b + p1;
00101                 index[p + 1] = b + p2 + 1;
00102                 index[p + 2] = b + p1 + 1;
00103                 p = p + 3;
00104             }
00105         }
00106     }
00107     m_indexCount = p;
00108
00109     bd.Usage = D3D11_USAGE_DEFAULT;
00110     bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount;
00111     bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00112     bd.CPUAccessFlags = 0;
00113     initData.pSysMem = point.data();
00114     winrt::check_hresult(
00115         device->CreateBuffer(&bd, &initData, m_vertexBuffer.put())
00116         );
00117
00118     bd.Usage = D3D11_USAGE_DEFAULT;
00119     bd.ByteWidth = sizeof(uint16_t) * m_indexCount;
00120     bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
00121     bd.CPUAccessFlags = 0;
00122     initData.pSysMem = index.data();
00123     winrt::check_hresult(
00124         device->CreateBuffer(&bd, &initData, m_indexBuffer.put())
00125         );
00126 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DecodeResult Member List

This is the complete list of members for DecodeResult, including all inherited members.
__pad0__ | DecodeResult |
__pad1__ | DecodeResult |
Equals(Object obj) | DecodeResult | [inline]
GetHashCode() | DecodeResult | [inline]
m_text | DecodeResult |
Symbology | DecodeResult |
Text | DecodeResult |
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cs/Server/OvenServer.cs Source File

  • ProxyStubsForWinRTComponents
  • cs
  • Server

OvenServer.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using System;
00008 using System.Collections.Generic;
00009 using System.Text;
00010 using System.Threading;
00011 using Windows.Foundation;
00012 using Windows.Foundation.Metadata;
00013 using Windows.System.Threading;
00014
00015 namespace Microsoft.SDKSamples.Kitchen
00016 {
00017     public struct Dimensions
00018     {
00019         public double Depth;
00020         public double Height;
00021         public double Width;
00022     }
00023
00024     public enum OvenTemperature
00025     {
00026         Low,
00027         Medium,
00028         High
00029     }
00030
00031     // Explicitly declare IIDs to make it easier to author the proxy stub interface registration
00032     [Guid(0x332FD2F1, 0x1C69, 0x4C91, 0x94, 0x9E, 0x4B, 0xB6, 0x7A, 0x85, 0xBD, 0xC5)]
00033     public interface IAppliance
00034     {
00035         double Volume { get; }
00036     }
00037
00038     // Explicitly declare IIDs to make it easier to author the proxy stub interface registration
00039     [Guid(0x6A112353, 0x4F87, 0x4460, 0xA9, 0x08, 0x29, 0x44, 0xE9, 0x26, 0x86, 0xF3)]
00040     public interface IOven : IAppliance
00041     {
00042         void ConfigurePreheatTemperature(OvenTemperature level);
00043         void BakeBread(String flavor);
00044         event TypedEventHandler<Oven, Bread> BreadBaked;
00045     }
00046
00047     public sealed class Oven : IOven
00048     {
00049         public Oven(Dimensions dimensions)
00050         {
00051             _dimensions = dimensions;
00052         }
00053
00054         public Oven()
00055         {
00056             _dimensions.Height = 1.0;
00057             _dimensions.Width = 1.0;
00058             _dimensions.Depth = 1.0;
00059         }
00060
00061         public double Volume
00062         {
00063             get
00064             {
00065                 return _dimensions.Depth * _dimensions.Height * _dimensions.Width;
00066             }
00067         }
00068
00069         public event TypedEventHandler<Oven, Bread> BreadBaked;
00070
00071         public void BakeBread(String flavor)
00072         {
00073             TimeSpan preheatTime;
00074
00075             // Determine how long to wait for the oven to get to temperature
00076             switch (_temperature)
00077             {
00078                 case OvenTemperature.Low:
00079                     // Set the preheat time to 100ms
00080                     preheatTime = new TimeSpan(1000);
00081                     break;
00082
00083                 case OvenTemperature.Medium:
00084                     // Set the preheat time to 200ms
00085                     preheatTime = new TimeSpan(2000);
00086                     break;
00087
00088                 case OvenTemperature.High:
00089                     // Set the preheat time to 300ms
00090                     preheatTime = new TimeSpan(3000);
00091                     break;
00092
00093                 default:
00094                     throw new ArgumentException("Temperature is out of range. The temperature should be low, medium, or high.");
00095             }
00096
00097             // Set up a threadpool work item to bake the bread and notify listeners after the oven has preheated
00098             ThreadPoolTimer.CreateTimer(new TimerElapsedHandler(
00099                 (ThreadPoolTimer timer) =>
00100                 {
00101                     Bread bread = new Bread(flavor);
00102                     if (BreadBaked != null)
00103                     {
00104                         BreadBaked(this, bread);
00105                     }
00106                 }),
00107                 preheatTime);
00108         }
00109
00110         public void ConfigurePreheatTemperature(OvenTemperature level)
00111         {
00112             if (level >= OvenTemperature.Low && level <= OvenTemperature.High)
00113             {
00114                 _temperature = level;
00115             }
00116             else
00117             {
00118                 throw new ArgumentException("Temperature is out of range. The temperature should be low, medium, or high.");
00119             }
00120         }
00121
00122         private Dimensions _dimensions;
00123         private OvenTemperature _temperature = OvenTemperature.Medium;
00124     }
00125 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cppwinrt/Scenario1_GetAndSetPin.h Source File

  • IoT-GPIO
  • cppwinrt

Scenario1_GetAndSetPin.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_GetAndSetPin.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_GetAndSetPin : Scenario1_GetAndSetPinT<Scenario1_GetAndSetPin>
00019     {
00020         Scenario1_GetAndSetPin();
00021         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00022
00023         void StartStopScenario_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024         void SetPinHigh_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00025         void SetPinLow_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026         void GetPinValue_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027
00028     private:
00029         // Use GPIO pin 5 to set values
00030         static constexpr int LED_PIN = 5;
00031         Windows::Devices::Gpio::GpioPin pin{ nullptr };
00032
00033         void StartScenario();
00034         void StopScenario();
00035
00036     };
00037 }
00038
00039 namespace winrt::SDKTemplate::factory_implementation
00040 {
00041     struct Scenario1_GetAndSetPin : Scenario1_GetAndSetPinT<Scenario1_GetAndSetPin, implementation::Scenario1_GetAndSetPin>
00042     {
00043     };
00044 }
Generated on Fri Nov 15 2024 22:20:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Compass/cs/Scenario2_Polling.xaml.cs Source File

  • Compass
  • cs

Scenario2_Polling.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Devices.Sensors;
00015 using Windows.Foundation;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario2_Polling : Page
00024     {
00025         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00026         // as NotifyUser()
00027         MainPage rootPage = MainPage.Current;
00028
00029         private Compass _compass;
00030         private uint _desiredReportInterval;
00031         private DispatcherTimer _dispatcherTimer;
00032
00033         public Scenario2_Polling()
00034         {
00035             this.InitializeComponent();
00036
00037             _compass = Compass.GetDefault();
00038             if (_compass != null)
00039             {
00040                 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00041                 // This value will be used later to activate the sensor.
00042                 uint minReportInterval = _compass.MinimumReportInterval;
00043                 _desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00044
00045                 // Set up a DispatchTimer
00046                 _dispatcherTimer = new DispatcherTimer();
00047                 _dispatcherTimer.Tick += DisplayCurrentReading;
00048                 _dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, (int)_desiredReportInterval);
00049             }
00050             else
00051             {
00052                 rootPage.NotifyUser("No compass found", NotifyType.ErrorMessage);
00053             }
00054         }
00055
00056         /// <summary>
00057         /// Invoked when this page is about to be displayed in a Frame.
00058         /// </summary>
00059         /// <param name="e">Event data that describes how this page was reached. The Parameter
00060         /// property is typically used to configure the page.</param>
00061         protected override void OnNavigatedTo(NavigationEventArgs e)
00062         {
00063             ScenarioEnableButton.IsEnabled = true;
00064             ScenarioDisableButton.IsEnabled = false;
00065         }
00066
00067         /// <summary>
00068         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00069         /// </summary>
00070         /// <param name="e">
00071         /// Event data that can be examined by overriding code. The event data is representative
00072         /// of the navigation that will unload the current Page unless canceled. The
00073         /// navigation can potentially be canceled by setting Cancel.
00074         /// </param>
00075         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00076         {
00077             if (ScenarioDisableButton.IsEnabled)
00078             {
00079                 Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00080
00081                 // Stop the dispatcher
00082                 _dispatcherTimer.Stop();
00083
00084                 // Restore the default report interval to release resources while the sensor is not in use
00085                 _compass.ReportInterval = 0;
00086             }
00087
00088             base.OnNavigatingFrom(e);
00089         }
00090
00091         /// <summary>
00092         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00093         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00094         /// </summary>
00095         /// <param name="sender"></param>
00096         /// <param name="e">
00097         /// Event data that can be examined for the current visibility state.
00098         /// </param>
00099         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00100         {
00101             if (ScenarioDisableButton.IsEnabled)
00102             {
00103                 if (e.Visible)
00104                 {
00105                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00106                     _dispatcherTimer.Start();
00107                 }
00108                 else
00109                 {
00110                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00111                     _dispatcherTimer.Stop();
00112                 }
00113             }
00114         }
00115
00116         /// <summary>
00117         /// This is the dispatcher callback.
00118         /// </summary>
00119         /// <param name="sender"></param>
00120         /// <param name="args"></param>
00121         private void DisplayCurrentReading(object sender, object args)
00122         {
00123             CompassReading reading = _compass.GetCurrentReading();
00124             if (reading != null)
00125             {
00126                 ScenarioOutput_MagneticNorth.Text = String.Format("{0,5:0.00}", reading.HeadingMagneticNorth);
00127                 if (reading.HeadingTrueNorth != null)
00128                 {
00129                     ScenarioOutput_TrueNorth.Text = String.Format("{0,5:0.00}", reading.HeadingTrueNorth);
00130                 }
00131                 else
00132                 {
00133                     ScenarioOutput_TrueNorth.Text = "No data";
00134                 }
00135                 switch (reading.HeadingAccuracy)
00136                 {
00137                     case MagnetometerAccuracy.Unknown:
00138                         ScenarioOutput_HeadingAccuracy.Text = "Unknown";
00139                         break;
00140                     case MagnetometerAccuracy.Unreliable:
00141                         ScenarioOutput_HeadingAccuracy.Text = "Unreliable";
00142                         break;
00143                     case MagnetometerAccuracy.Approximate:
00144                         ScenarioOutput_HeadingAccuracy.Text = "Approximate";
00145                         break;
00146                     case MagnetometerAccuracy.High:
00147                         ScenarioOutput_HeadingAccuracy.Text = "High";
00148                         break;
00149                     default:
00150                         ScenarioOutput_HeadingAccuracy.Text = "No data";
00151                         break;
00152                 }
00153             }
00154         }
00155
00156         /// <summary>
00157         /// This is the click handler for the 'Enable' button.
00158         /// </summary>
00159         /// <param name="sender"></param>
00160         /// <param name="e"></param>
00161         private void ScenarioEnable(object sender, RoutedEventArgs e)
00162         {
00163             if (_compass != null)
00164             {
00165                 // Set the report interval to enable the sensor for polling
00166                 _compass.ReportInterval = _desiredReportInterval;
00167
00168                 Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged);
00169                 _dispatcherTimer.Start();
00170
00171                 ScenarioEnableButton.IsEnabled = false;
00172                 ScenarioDisableButton.IsEnabled = true;
00173             }
00174             else
00175             {
00176                 rootPage.NotifyUser("No compass found", NotifyType.ErrorMessage);
00177             }
00178         }
00179
00180         /// <summary>
00181         /// This is the click handler for the 'Disable' button.
00182         /// </summary>
00183         /// <param name="sender"></param>
00184         /// <param name="e"></param>
00185         private void ScenarioDisable(object sender, RoutedEventArgs e)
00186         {
00187             Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00188
00189             // Stop the dispatcher
00190             _dispatcherTimer.Stop();
00191
00192             // Restore the default report interval to release resources while the sensor is not in use
00193             _compass.ReportInterval = 0;
00194
00195             ScenarioEnableButton.IsEnabled = true;
00196             ScenarioDisableButton.IsEnabled = false;
00197         }
00198     }
00199 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cpp/Scenario1_TrialMode.xaml.cpp Source File

  • Store
  • cpp

Scenario1_TrialMode.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_TrialMode.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Services::Store;
00021 using namespace Windows::UI::Core;
00022 using namespace Windows::UI::Xaml::Navigation;
00023
00024 Scenario1_TrialMode::Scenario1_TrialMode()
00025 {
00026     InitializeComponent();
00027 }
00028
00029 void Scenario1_TrialMode::OnNavigatedTo(NavigationEventArgs^ e)
00030 {
00031     storeContext = StoreContext::GetDefault();
00032     eventRegistrationToken = storeContext->OfflineLicensesChanged += ref new TypedEventHandler<StoreContext^, Object^>(this, &Scenario1_TrialMode::OfflineLicensesChanged);
00033
00034     create_task(storeContext->GetStoreProductForCurrentAppAsync()).then([this](StoreProductResult^ result)
00035     {
00036         if (result->ExtendedError.Value == S_OK)
00037         {
00038             PurchasePrice->Text = result->Product->Price->FormattedPrice;
00039         }
00040     });
00041
00042     GetLicenseState();
00043 }
00044
00045 void Scenario1_TrialMode::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00046 {
00047     storeContext->OfflineLicensesChanged -= eventRegistrationToken;
00048 }
00049
00050 void Scenario1_TrialMode::OfflineLicensesChanged(StoreContext^ sender, Object^ args)
00051 {
00052     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00053     {
00054         GetLicenseState();
00055     }));
00056 }
00057
00058 void Scenario1_TrialMode::GetLicenseState()
00059 {
00060     create_task(storeContext->GetAppLicenseAsync()).then([this](StoreAppLicense^ license)
00061     {
00062         if (license->IsActive)
00063         {
00064             if (license->IsTrial)
00065             {
00066                 LicenseMode->Text = "Trial license";
00067             }
00068             else
00069             {
00070                 LicenseMode->Text = "Full license";
00071             }
00072         }
00073         else
00074         {
00075             LicenseMode->Text = "Inactive license";
00076         }
00077     }, task_continuation_context::get_current_winrt_context());
00078 }
00079
00080 void Scenario1_TrialMode::ShowTrialPeriodInformation()
00081 {
00082     create_task(storeContext->GetAppLicenseAsync()).then([this](StoreAppLicense^ license)
00083     {
00084         if (license->IsActive)
00085         {
00086             if (license->IsTrial)
00087             {
00088                 rootPage->NotifyUser("You can use this app for " + Utils::DaysUntil(license->ExpirationDate) + " more days before the trial period ends.", NotifyType::StatusMessage);
00089             }
00090             else
00091             {
00092                 rootPage->NotifyUser("You have a full license. The trial time is not meaningful.", NotifyType::ErrorMessage);
00093             }
00094         }
00095         else
00096         {
00097             rootPage->NotifyUser("You don't have a license. The trial time can't be determined.", NotifyType::ErrorMessage);
00098         }
00099     }, task_continuation_context::get_current_winrt_context());
00100 }
00101
00102 void Scenario1_TrialMode::PurchaseFullLicense()
00103 {
00104     create_task(storeContext->GetStoreProductForCurrentAppAsync()).then([this](StoreProductResult^ productResult)
00105     {
00106         if (productResult->ExtendedError.Value != S_OK)
00107         {
00108             Utils::ReportExtendedError(productResult->ExtendedError);
00109             return;
00110         }
00111
00112         rootPage->NotifyUser("Buying the full license...", NotifyType::StatusMessage);
00113         create_task(storeContext->GetAppLicenseAsync()).then([this, productResult](StoreAppLicense^ license)
00114         {
00115             if (license->IsTrial)
00116             {
00117                 create_task(productResult->Product->RequestPurchaseAsync()).then([this](StorePurchaseResult^ result)
00118                 {
00119                     switch (result->Status)
00120                     {
00121                     case StorePurchaseStatus::AlreadyPurchased:
00122                         rootPage->NotifyUser("You already bought this app and have a fully-licensed version.", NotifyType::ErrorMessage);
00123                         break;
00124
00125                     case StorePurchaseStatus::Succeeded:
00126                         // License will refresh automatically using the StoreContext.OfflineLicensesChanged event
00127                         break;
00128
00129                     case StorePurchaseStatus::NotPurchased:
00130                         rootPage->NotifyUser("Product was not purchased, it may have been canceled.", NotifyType::ErrorMessage);
00131                         break;
00132
00133                     case StorePurchaseStatus::NetworkError:
00134                         rootPage->NotifyUser("Product was not purchased due to a Network Error.", NotifyType::ErrorMessage);
00135                         break;
00136
00137                     case StorePurchaseStatus::ServerError:
00138                         rootPage->NotifyUser("Product was not purchased due to a Server Error.", NotifyType::ErrorMessage);
00139                         break;
00140
00141                     default:
00142                         rootPage->NotifyUser("Product was not purchased due to an Unknown Error.", NotifyType::ErrorMessage);
00143                         break;
00144                     }
00145                 });
00146             }
00147             else
00148             {
00149                 rootPage->NotifyUser("You already bought this app and have a fully-licensed version.", NotifyType::ErrorMessage);
00150             }
00151         }, task_continuation_context::get_current_winrt_context());
00152     }, task_continuation_context::get_current_winrt_context());
00153 }
Generated on Fri Nov 15 2024 22:21:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceInformationKindChoice Member List

This is the complete list of members for DeviceInformationKindChoice, including all inherited members.
DeviceInformationKinds | DeviceInformationKindChoice
DisplayName | DeviceInformationKindChoice
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cppwinrt/Project.idl Source File

  • FileThumbnails
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1 : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2 : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3 : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3();
00030     }
00031
00032     [default_interface]
00033     runtimeclass Scenario4 : Windows.UI.Xaml.Controls.Page
00034     {
00035         Scenario4();
00036     }
00037
00038     [default_interface]
00039     runtimeclass Scenario5 : Windows.UI.Xaml.Controls.Page
00040     {
00041         Scenario5();
00042     }
00043
00044     [default_interface]
00045     runtimeclass Scenario6 : Windows.UI.Xaml.Controls.Page
00046     {
00047         Scenario6();
00048     }
00049 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geotag/cs/SampleConfiguration.cs Source File

  • Geotag
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Geotag C# Sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Geotag a file", ClassType=typeof(Scenario1_Geotag)}
00025         };
00026     }
00027
00028     public class Scenario
00029     {
00030         public string Title { get; set; }
00031         public Type ClassType { get; set; }
00032     }
00033 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HolographicVoiceInputMain Member List

This is the complete list of members for HolographicVoiceInputMain, including all inherited members.
BeginVoiceUIPrompt() | HolographicVoiceInputMain | [private]
HolographicVoiceInputMain(const std::shared_ptr< DX::DeviceResources > &deviceResources) | HolographicVoiceInputMain |
InitializeSpeechCommandList() | HolographicVoiceInputMain | [private]
InitializeSpeechRecognizer() | HolographicVoiceInputMain | [private]
LoadAppState() | HolographicVoiceInputMain |
m_cameraAddedToken | HolographicVoiceInputMain | [private]
m_cameraRemovedToken | HolographicVoiceInputMain | [private]
m_deviceResources | HolographicVoiceInputMain | [private]
m_holographicSpace | HolographicVoiceInputMain | [private]
m_lastCommand | HolographicVoiceInputMain | [private]
m_listening | HolographicVoiceInputMain | [private]
m_locatabilityChangedToken | HolographicVoiceInputMain | [private]
m_locator | HolographicVoiceInputMain | [private]
m_recognitionSound | HolographicVoiceInputMain | [private]
m_referenceFrame | HolographicVoiceInputMain | [private]
m_secondsUntilSoundIsComplete | HolographicVoiceInputMain | [private]
m_spatialInputHandler | HolographicVoiceInputMain | [private]
m_speechCommandData | HolographicVoiceInputMain | [private]
m_speechRecognitionQualityDegradedToken | HolographicVoiceInputMain | [private]
m_speechRecognizer | HolographicVoiceInputMain | [private]
m_speechRecognizerResultEventToken | HolographicVoiceInputMain | [private]
m_speechSynthesisSound | HolographicVoiceInputMain | [private]
m_spinningCubeRenderer | HolographicVoiceInputMain | [private]
m_startRecognitionSound | HolographicVoiceInputMain | [private]
m_timer | HolographicVoiceInputMain | [private]
m_waitingForSpeechCue | HolographicVoiceInputMain | [private]
m_waitingForSpeechPrompt | HolographicVoiceInputMain | [private]
OnCameraAdded(Windows::Graphics::Holographic::HolographicSpace^sender, Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs^args) | HolographicVoiceInputMain | [private]
OnCameraRemoved(Windows::Graphics::Holographic::HolographicSpace^sender, Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs^args) | HolographicVoiceInputMain | [private]
OnDeviceLost() | HolographicVoiceInputMain | [virtual]
OnDeviceRestored() | HolographicVoiceInputMain | [virtual]
OnLocatabilityChanged(Windows::Perception::Spatial::SpatialLocator^sender, Platform::Object^args) | HolographicVoiceInputMain | [private]
OnResultGenerated(Windows::Media::SpeechRecognition::SpeechContinuousRecognitionSession^sender, Windows::Media::SpeechRecognition::SpeechContinuousRecognitionResultGeneratedEventArgs^args) | HolographicVoiceInputMain | [private]
OnSpeechQualityDegraded(Windows::Media::SpeechRecognition::SpeechRecognizer^recognizer, Windows::Media::SpeechRecognition::SpeechRecognitionQualityDegradingEventArgs^args) | HolographicVoiceInputMain | [private]
PlayRecognitionBeginSound() | HolographicVoiceInputMain | [private]
PlayRecognitionSound() | HolographicVoiceInputMain | [private]
Render(Windows::Graphics::Holographic::HolographicFrame^holographicFrame) | HolographicVoiceInputMain |
SaveAppState() | HolographicVoiceInputMain |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^holographicSpace) | HolographicVoiceInputMain |
StartRecognizeSpeechCommands() | HolographicVoiceInputMain | [private]
StopCurrentRecognizerIfExists() | HolographicVoiceInputMain | [private]
UnregisterHolographicEventHandlers() | HolographicVoiceInputMain | [private]
Update() | HolographicVoiceInputMain |
~HolographicVoiceInputMain() | HolographicVoiceInputMain |
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/pch.h Source File

  • HolographicFaceTracking
  • cpp

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Windows
00015 #include <agile.h>
00016 #include <collection.h>
00017 #include <concrt.h>
00018 #include <ppltasks.h>
00019 #include <wincodec.h>
00020 #include <wrl.h>
00021 #include <WindowsNumerics.h>
00022
00023 // DirectX
00024 #include <d2d1_2.h>
00025 #include <d2d1effects_1.h>
00026 #include <d3d11_4.h>
00027 #include <DirectXColors.h>
00028 #include <DirectXMath.h>
00029 #include <dwrite_2.h>
00030 #include <dxgi1_5.h>
00031
00032 // STL
00033 #include <memory>
00034 #include <map>
00035 #include <vector>
00036 #include <mutex>
00037 #include <shared_mutex>
00038 #include <string>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAccountManagement/cpp/Scenario6_CustomProvider.xaml.cpp Source File

  • WebAccountManagement
  • cpp

Scenario6_CustomProvider.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario6_CustomProvider.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Platform::Collections;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::Security::Authentication::Web::Core;
00013 using namespace Windows::Security::Credentials;
00014 using namespace Windows::Storage;
00015 using namespace Windows::UI::Popups;
00016 using namespace Windows::UI::Xaml;
00017 using namespace Windows::UI::Xaml::Controls;
00018 using namespace Windows::UI::Xaml::Controls::Primitives;
00019 using namespace Windows::UI::Xaml::Data;
00020 using namespace Windows::UI::Xaml::Input;
00021 using namespace Windows::UI::Xaml::Media;
00022 using namespace Windows::UI::Xaml::Navigation;
00023 using namespace Windows::UI::ApplicationSettings;
00024
00025 Scenario6_CustomProvider::Scenario6_CustomProvider() : rootPage(MainPage::Current)
00026 {
00027     InitializeComponent();
00028     InitalizeAccountsControlDialog();
00029 }
00030
00031 void Scenario6_CustomProvider::OnNavigatedFrom(NavigationEventArgs^ e)
00032 {
00033     CleanupAccountsControlDialog();
00034 }
00035
00036 void SDKTemplate::Scenario6_CustomProvider::Button_SignIn_Click(Object^ sender, RoutedEventArgs^ e)
00037 {
00038     AccountsSettingsPane::Show();
00039 }
00040
00041 void SDKTemplate::Scenario6_CustomProvider::Button_GetTokenSilently_Click(Object^ sender, RoutedEventArgs^ e)
00042 {
00043     AuthenticateWithRequestTokenSilent(m_account->WebAccountProvider, MSA_SCOPE_REQUESTED, MSA_CLIENT_ID, m_account);
00044 }
00045
00046 void SDKTemplate::Scenario6_CustomProvider::Button_ManageAccount_Click(Object^ sender, RoutedEventArgs^ e)
00047 {
00048     AccountsSettingsPane::Show();
00049 }
00050
00051 void SDKTemplate::Scenario6_CustomProvider::Button_Reset_Click(Object^ sender, RoutedEventArgs^ e)
00052 {
00053     rootPage->NotifyUser("Resetting", NotifyType::StatusMessage);
00054
00055     RemoveCustomProviders();
00056     LogoffAndRemoveAccount();
00057
00058     rootPage->NotifyUser("Done Resetting", NotifyType::StatusMessage);
00059 }
00060
00061 void SDKTemplate::Scenario6_CustomProvider::Button_AddProvider_Click(Object^ sender, RoutedEventArgs^ e)
00062 {
00063     AddCustomProvider(textBox_ProviderId->Text, textBox_Authority->Text);
00064 }
00065
00066 void SDKTemplate::Scenario6_CustomProvider::InitalizeAccountsControlDialog()
00067 {
00068     // Add to the event AccountCommandsRequested to load our list of providers into the AccountSettingsPane
00069     m_accountCommandsRequestedRegistrationToken = AccountsSettingsPane::GetForCurrentView()->AccountCommandsRequested::add(
00070         ref new TypedEventHandler<AccountsSettingsPane^, AccountsSettingsPaneCommandsRequestedEventArgs^>(
00071         this,
00072         &SDKTemplate::Scenario6_CustomProvider::OnAccountCommandsRequested)
00073         );
00074
00075     // Populate our list of providers with the MSA provider, and attempt to find any accounts saved.
00076     GetProvidersAndAccounts();
00077 }
00078
00079 void SDKTemplate::Scenario6_CustomProvider::CleanupAccountsControlDialog()
00080 {
00081     // Remove the event handler from the AccountCommandsRequested
00082     AccountsSettingsPane::GetForCurrentView()->AccountCommandsRequested::remove(m_accountCommandsRequestedRegistrationToken);
00083
00084     // Clean up any account that may still be logged in
00085     LogoffAndRemoveAccount();
00086 }
00087
00088 void SDKTemplate::Scenario6_CustomProvider::OnAccountCommandsRequested(
00089     AccountsSettingsPane^ sender,
00090     AccountsSettingsPaneCommandsRequestedEventArgs^ e)
00091 {
00092     // This scenario only supports a single account at one time.
00093     // If there already is an account, we do not include a provider in the list
00094     // This will prevent the add account button from showing up.
00095     if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
00096     {
00097         AddWebAccount(e);
00098     }
00099     else
00100     {
00101         AddWebAccountProviders(e);
00102     }
00103
00104     AddLinksAndDescription(e);
00105 }
00106
00107 // Function to create our Map of providers and load an account if an account id is saved
00108 void SDKTemplate::Scenario6_CustomProvider::GetProvidersAndAccounts()
00109 {
00110     //Instantiate the provider list
00111     m_providers = ref new Map<String^, WebAccountProvider^>();
00112
00113     if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
00114     {
00115         LoadAccount();
00116     }
00117 }
00118
00119 // We've found that we have some key information saved about a previous
00120 // account, so we will call FindAccountAsync to grab the WebAccount and save it
00121 void SDKTemplate::Scenario6_CustomProvider::LoadAccount()
00122 {
00123     auto accountID = safe_cast<String^>(ApplicationData::Current->LocalSettings->Values->Lookup(STORED_ACCOUNT_ID_KEY));
00124     auto providerID = safe_cast<String^>(ApplicationData::Current->LocalSettings->Values->Lookup(STORED_PROVIDER_ID_KEY));
00125     auto authority = safe_cast<String^>(ApplicationData::Current->LocalSettings->Values->Lookup(STORED_AUTHORITY_ID_KEY));
00126
00127     if (accountID == nullptr || providerID == nullptr || authority == nullptr)
00128     {
00129         return;
00130     }
00131
00132     concurrency::create_task(WebAuthenticationCoreManager::FindAccountProviderAsync(providerID))
00133         .then([this, providerID, accountID, authority](WebAccountProvider^ provider)
00134     {
00135         concurrency::create_task(WebAuthenticationCoreManager::FindAccountAsync(provider, accountID))
00136             .then([this](WebAccount^ foundAccount)
00137         {
00138             if (foundAccount)
00139             {
00140                 SaveAccount(foundAccount);
00141             }
00142         });
00143     });
00144 }
00145
00146 // This function takes the passed in strings from the textboxes for adding a custom provider.
00147 // It will check to make sure the provider is found, then add the provider to our list of providers and
00148 // clear the textboxes.
00149 void SDKTemplate::Scenario6_CustomProvider::AddCustomProvider(String^ providerId, String^ authority)
00150 {
00151     if (providerId)
00152     {
00153         (authority ?
00154             concurrency::create_task(WebAuthenticationCoreManager::FindAccountProviderAsync(providerId, authority)) :
00155             concurrency::create_task(WebAuthenticationCoreManager::FindAccountProviderAsync(providerId)))
00156             .then([this, providerId](WebAccountProvider^ provider)
00157         {
00158             if (provider)
00159             {
00160                 m_providers->Insert(provider->Id, provider);
00161                 textBox_ProviderId->Text = "";
00162                 textBox_Authority->Text = "";
00163                 rootPage->NotifyUser("Provider was found and added for id: " + providerId + ".", NotifyType::StatusMessage);
00164             }
00165             else
00166             {
00167                 rootPage->NotifyUser("Provider was not found for that provider id: " + providerId + ".", NotifyType::ErrorMessage);
00168             }
00169         });
00170     }
00171     else
00172     {
00173         rootPage->NotifyUser("A provided must be specified.", NotifyType::StatusMessage);
00174     }
00175 }
00176
00177 // Similar to Scenario 1, but with a loop for the different providers we now support and declared earlier
00178 void SDKTemplate::Scenario6_CustomProvider::AddWebAccountProviders(AccountsSettingsPaneCommandsRequestedEventArgs^ e)
00179 {
00180     for (auto pair : m_providers)
00181     {
00182         // Create a new WebAccountProviderCommandInvokedHandler for the event fired when a user clicks on a provider in the AccountSettingsPane
00183         WebAccountProviderCommandInvokedHandler^ handler = ref new WebAccountProviderCommandInvokedHandler(this, &SDKTemplate::Scenario6_CustomProvider::WebAccountProviderCommandInvoked);
00184
00185         // Make a new command based on the provider and the click handler we just created
00186         WebAccountProviderCommand^ ProviderCommand = ref new WebAccountProviderCommand(pair->Value, handler);
00187
00188         // Append that command to the WebAccountProviderCommands list for the AccountSettingsPane
00189         e->WebAccountProviderCommands->Append(ProviderCommand);
00190     }
00191 }
00192
00193 //Creates a web account command object for our account, if we have one saved, and adds it to the AccountsControl list of web account commands
00194 void SDKTemplate::Scenario6_CustomProvider::AddWebAccount(AccountsSettingsPaneCommandsRequestedEventArgs^ e)
00195 {
00196     // Create a new WebAccountCommandInvokedHandler for the event fired when a user clicks on an account in the AccountSettingsPane
00197     WebAccountCommandInvokedHandler^ handler = ref new WebAccountCommandInvokedHandler(this, &SDKTemplate::Scenario6_CustomProvider::WebAccountCommandInvoked);
00198
00199     // Make a new command based on the account and the click handler we just created
00200     WebAccountCommand^ AccountCommand = ref new WebAccountCommand(SDKTemplate::Scenario6_CustomProvider::m_account, handler, SupportedWebAccountActions::Remove);
00201
00202     // Append that command to the WebAccountProviderCommands list for the AccountSettingsPane
00203     e->WebAccountCommands->Append(AccountCommand);
00204 }
00205
00206 // You can add links and descriptive text such as privacy policy, help, general account settings
00207 void SDKTemplate::Scenario6_CustomProvider::AddLinksAndDescription(AccountsSettingsPaneCommandsRequestedEventArgs^ e)
00208 {
00209     e->HeaderText = "Describe what adding an account to your application will do for the user.";
00210
00211     e->Commands->Append(ref new SettingsCommand("privacypolicy", "Privacy Policy", ref new UICommandInvokedHandler(this, &SDKTemplate::Scenario6_CustomProvider::PrivacyPolicyInvoked)));
00212     e->Commands->Append(ref new SettingsCommand("otherlink", "Other Link", ref new UICommandInvokedHandler(this, &SDKTemplate::Scenario6_CustomProvider::OtherLinkInvoked)));
00213 }
00214
00215 // The function that will be called from AccountSettingsPane with the WebAccountProvider
00216 // that was clicked by the user
00217 void SDKTemplate::Scenario6_CustomProvider::WebAccountProviderCommandInvoked(WebAccountProviderCommand^ command)
00218 {
00219     if (command->WebAccountProvider->Authority == "organizations")
00220     {
00221         AuthenticateWithRequestToken(command->WebAccountProvider, AAD_SCOPE_REQUESTED, AAD_CLIENT_ID);
00222     }
00223     else
00224     {
00225         AuthenticateWithRequestToken(command->WebAccountProvider, MSA_SCOPE_REQUESTED, MSA_CLIENT_ID);
00226     }
00227 }
00228
00229 // Handler function for when users select different commands for accounts in the AccountControl
00230 void SDKTemplate::Scenario6_CustomProvider::WebAccountCommandInvoked(WebAccountCommand^ command, WebAccountInvokedArgs^ args)
00231 {
00232     if (args->Action == WebAccountAction::Remove)
00233     {
00234         LogoffAndRemoveAccount();
00235     }
00236 }
00237
00238 // Displays privacy policy message on clicking it in the AccountsControl
00239 void SDKTemplate::Scenario6_CustomProvider::PrivacyPolicyInvoked(IUICommand^ command)
00240 {
00241     rootPage->NotifyUser("Privacy policy clicked by user", NotifyType::StatusMessage);
00242 }
00243
00244 // Displays other link message on clicking it in the AccountsControl
00245 void SDKTemplate::Scenario6_CustomProvider::OtherLinkInvoked(IUICommand^ command)
00246 {
00247     rootPage->NotifyUser("Other link pressed by user", NotifyType::StatusMessage);
00248 }
00249
00250 // Create a new WebAccountManager WebTokenRequest based on the Provider, Scope, ClientID and then create a task to send
00251 // that request asynchronously to WebAccountManager's RequestTokenAsync API
00252 //
00253 // WebAccountManager will then try three steps, in order:
00254 //        (1): Check it's local cache to see if it has a valid token
00255 //        (2): Try to silently request a new token from the MSA service
00256 //        (3): Show the MSA UI for user interaction required (user credentials) before it may return a token.
00257 //
00258 // Because of WebAccountManager's ability to cache tokens, you should only need to call WebAccountManager when making token
00259 // based requests and not require the ability to store a cached token within your app.
00260 void SDKTemplate::Scenario6_CustomProvider::AuthenticateWithRequestToken(WebAccountProvider^ provider, String^ scope, String^ clientID)
00261 {
00262     rootPage->NotifyUser("Requested " + provider->DisplayName + " from AccountsManager dialog.", NotifyType::StatusMessage);
00263
00264     auto wtr = ref new WebTokenRequest(provider, scope, clientID);
00265
00266     // When our task finishes it will return result of the operation, and if successful it will contain a token
00267     // and WebAccount. We save the WebAccount as the "active" account.
00268     concurrency::create_task(WebAuthenticationCoreManager::RequestTokenAsync(wtr)).then([this, provider](WebTokenRequestResult^ webTokenRequestResult)
00269     {
00270         if (webTokenRequestResult->ResponseStatus == WebTokenRequestStatus::Success)
00271         {
00272             if (webTokenRequestResult->ResponseData->GetAt(0)->WebAccount)
00273             {
00274                 if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
00275                 {
00276                     ApplicationData::Current->LocalSettings->Values->Remove(STORED_ACCOUNT_ID_KEY);
00277                 }
00278
00279                 WebAccount^ account = webTokenRequestResult->ResponseData->GetAt(0)->WebAccount;
00280                 SaveAccount(account);
00281             }
00282         }
00283
00284         OutputTokenResult(webTokenRequestResult);
00285     });
00286 }
00287
00288 // Create a new WebAccountManager WebTokenRequest based on the Provider, Scope, ClientID and then create a task to send
00289 // that request and the account to get the token for asynchronously to WebAccountManager's GetTokenSilentlyAsync API
00290 //
00291 // WebAccountManager's GetTokenSilentlyAsync will then try :
00292 //        (1): Check it's local cache to see if it has a valid token
00293 //        (2): Try to silently request a new token from the MSA service
00294 //        (3): Return a status of UserInteractionRequired if we need the user credentials
00295 //
00296 // Because of WebAccountManager's ability to cache tokens, you should only need to call WebAccountManager when making token
00297 // based requests and not require the ability to store a cached token within your app.
00298 void SDKTemplate::Scenario6_CustomProvider::AuthenticateWithRequestTokenSilent(WebAccountProvider^ provider, String^ scope, String^ clientID, WebAccount^ account)
00299 {
00300     rootPage->NotifyUser("Requested " + provider->DisplayName + " from AccountsManager dialog.", NotifyType::StatusMessage);
00301
00302     auto wtr = ref new WebTokenRequest(provider, scope, clientID);
00303
00304     // When our task finishes it will return result of the operation, and if successful it will contain a token
00305     // and WebAccount. We save the WebAccount as the "active" account.
00306     concurrency::create_task(WebAuthenticationCoreManager::GetTokenSilentlyAsync(wtr, account)).then([this](WebTokenRequestResult^ webTokenRequestResult)
00307     {
00308         if (webTokenRequestResult->ResponseStatus == WebTokenRequestStatus::Success)
00309         {
00310             // Perform an operation with the token you just got
00311         }
00312
00313         OutputTokenResult(webTokenRequestResult);
00314     });
00315 }
00316
00317 // Displays the result of requesting a token asynchronously to the main page
00318 void SDKTemplate::Scenario6_CustomProvider::OutputTokenResult(WebTokenRequestResult^ result)
00319 {
00320     if (result->ResponseStatus == WebTokenRequestStatus::Success)
00321     {
00322         rootPage->NotifyUser(result->ResponseStatus.ToString() + "!\nUser: " + result->ResponseData->GetAt(0)->WebAccount->Id + "\n    Token returned was: " + result->ResponseData->GetAt(0)->Token, NotifyType::StatusMessage);
00323     }
00324     else if (result->ResponseStatus == WebTokenRequestStatus::ProviderError)
00325     {
00326         // The account provider has passed us an error and we should handle it.
00327         rootPage->NotifyUser(result->ResponseStatus.ToString() + " " + result->ResponseError->ErrorCode + ": " + result->ResponseError->ErrorMessage, NotifyType::ErrorMessage);
00328     }
00329     else if (result->ResponseStatus == WebTokenRequestStatus::AccountProviderNotAvailable)
00330     {
00331         // The account provider is unavailable, this is a temporary error.
00332         rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::ErrorMessage);
00333     }
00334     else if (result->ResponseStatus == WebTokenRequestStatus::UserInteractionRequired)
00335     {
00336         // The account provider needs to display a UI, since we called request token silently we should call it
00337         // with RequestTokenAsync.
00338         rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::StatusMessage);
00339     }
00340     else if (result->ResponseStatus == WebTokenRequestStatus::UserCancel)
00341     {
00342         // The user cancelled the sign in process for the account provider, handle
00343         // that how you need to.
00344         rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::StatusMessage);
00345     }
00346     else
00347     {
00348         // An unexpected error was encountered
00349         rootPage->NotifyUser(result->ResponseStatus.ToString() + " " + result->ResponseError->ErrorCode + ": " + result->ResponseError->ErrorMessage, NotifyType::ErrorMessage);
00350     }
00351 }
00352
00353 // Saves the AccountId in LocalSettings and keeps an instance
00354 // of the WebAccount saved
00355 void SDKTemplate::Scenario6_CustomProvider::SaveAccount(WebAccount^ account)
00356 {
00357     ApplicationData::Current->LocalSettings->Values->Insert(STORED_ACCOUNT_ID_KEY, account->Id);
00358     m_account = account;
00359
00360     // Update the UI
00361     button_SignIn->IsEnabled = false;
00362     button_GetTokenSilently->IsEnabled = true;
00363     button_ManageAccount->IsEnabled = true;
00364     textblock_SignedInStatus->Text = "Signed in with:";
00365     textblock_SignedInStatus->Foreground = ref new SolidColorBrush(Windows::UI::Colors::Green);
00366     listview_SignedInAccounts->Items->Append(account->Id);
00367 }
00368
00369 // Signs out the account using the SignOutAsync Token Broker API
00370 // and removes our saved AccountId as it won't be valid when SignOutAsync finishes.
00371 void SDKTemplate::Scenario6_CustomProvider::LogoffAndRemoveAccount()
00372 {
00373     if (m_account)
00374     {
00375         //concurrency::create_task(account->SignOutAsync( MSA_SCOPE_REQUESTED));
00376     }
00377
00378     if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
00379     {
00380         ApplicationData::Current->LocalSettings->Values->Remove(STORED_ACCOUNT_ID_KEY);
00381     }
00382
00383     // Update UI
00384     button_SignIn->IsEnabled = true;
00385     button_GetTokenSilently->IsEnabled = false;
00386     button_ManageAccount->IsEnabled = false;
00387     textblock_SignedInStatus->Text = "Not signed in.";
00388     textblock_SignedInStatus->Foreground = ref new SolidColorBrush(Windows::UI::Colors::Red);
00389     listview_SignedInAccounts->Items->Clear();
00390 }
00391
00392 void SDKTemplate::Scenario6_CustomProvider::RemoveCustomProviders()
00393 {
00394     m_providers->Clear();
00395     GetProvidersAndAccounts();
00396 }
Generated on Fri Nov 15 2024 22:21:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cpp/Scenario4_UnicodeExtensions.xaml.cpp Source File

  • Calendar
  • cpp

Scenario4_UnicodeExtensions.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario4_UnicodeExtensions.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Platform::Collections;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::Globalization;
00021
00022 Scenario4_UnicodeExtensions::Scenario4_UnicodeExtensions()
00023 {
00024     InitializeComponent();
00025 }
00026
00027 String^ Scenario4_UnicodeExtensions::ReportCalendarData(Calendar^ calendar, String^ calendarLabel)
00028 {
00029     String^ results = calendarLabel + ": " + calendar->GetCalendarSystem() + "\n";
00030     results += "Calendar system: " + calendar->GetCalendarSystem() + "\n";
00031     results += "Numeral System: " + calendar->NumeralSystem + "\n";
00032     results += "Resolved Language " + calendar->ResolvedLanguage + "\n";
00033     results += "Name of Month: " + calendar->MonthAsSoloString() + "\n";
00034     results += "Day of Month: " + calendar->DayAsPaddedString(2) + "\n";
00035     results += "Day of Week: " + calendar->DayOfWeekAsSoloString() + "\n";
00036     results += "Year: " + calendar->YearAsString() + "\n";
00037     results += "\n";
00038     return results;
00039 }
00040
00041 void Scenario4_UnicodeExtensions::ShowResults_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00042 {
00043     // This scenario uses the Windows.Globalization.Calendar class to display the parts of a date.
00044
00045     // Create Calendar objects using different Unicode extensions for different languages.
00046     // NOTE: Calendar (ca) and numeral system (nu) are the only supported extensions with any others being ignored.
00047     // Note that collation (co) extension is ignored in the last example.
00048     Calendar^ cal1 = ref new Calendar();
00049     Calendar^ cal2 = ref new Calendar(ref new Vector<String^>({ "ar-SA-u-ca-gregory-nu-Latn" }));
00050     Calendar^ cal3 = ref new Calendar(ref new Vector<String^>({ "he-IL-u-nu-arab" }));
00051     Calendar^ cal4 = ref new Calendar(ref new Vector<String^>({ "he-IL-u-ca-hebrew-co-phonebk" }));
00052
00053     // Display individual date/time elements.
00054     OutputTextBlock->Text =
00055         ReportCalendarData(cal1, "User's default Calendar object") +
00056         ReportCalendarData(cal2, "Calendar object with Arabic language, Gregorian Calendar and Latin Numeral System (ar-SA-ca-gregory-nu-Latn)") +
00057         ReportCalendarData(cal3, "Calendar object with Hebrew language, Default Calendar for that language and Arab Numeral System (he-IL-u-nu-arab)") +
00058         ReportCalendarData(cal4, "Calendar object with Hebrew language, Hebrew Calendar, Default Numeral System for that language and Phonebook collation (he-IL-u-ca-hebrew-co-phonebk)");
00059 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario8_Copy.xaml.cpp Source File

  • FileAccess
  • cpp

Scenario8_Copy.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario8_Copy.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Storage;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Navigation;
00022
00023 Scenario8::Scenario8()
00024 {
00025     InitializeComponent();
00026 }
00027
00028 void Scenario8::OnNavigatedTo(NavigationEventArgs^ e)
00029 {
00030     rootPage->ValidateFile();
00031 }
00032
00033 void Scenario8::CopyFileButton_Click(Object^ sender, RoutedEventArgs^ e)
00034 {
00035     StorageFile^ file = rootPage->SampleFile;
00036     if (file != nullptr)
00037     {
00038         // Get the returned file and copy it
00039         create_task(KnownFolders::GetFolderForUserAsync(nullptr /* current user */, KnownFolderId::PicturesLibrary)).then([this, file](StorageFolder^ picturesFolder)
00040         {
00041             return file->CopyAsync(picturesFolder, "sample - Copy.dat", NameCollisionOption::ReplaceExisting);
00042         }).then([this, file](task<StorageFile^> task)
00043         {
00044             try
00045             {
00046                 StorageFile^ sampleFileCopy = task.get();
00047                 rootPage->NotifyUser("The file '" + file->Name + "' was copied and the new file was named '" + sampleFileCopy->Name + "'.", NotifyType::StatusMessage);
00048             }
00049             catch (COMException^ ex)
00050             {
00051                 // I/O errors are reported as exceptions.
00052                 rootPage->HandleIoException(ex, "Error copying file '" + file->Name + "'");
00053             }
00054         });
00055     }
00056     else
00057     {
00058         rootPage->NotifyUserFileNotExist();
00059     }
00060 }
Generated on Fri Nov 15 2024 22:19:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
_tileId | ScenarioElement | [private]
ButtonPinSecondaryTile_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ButtonSendNotification_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
Generated on Fri Nov 15 2024 22:23:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Scenario2_GetPosition.cpp Source File

  • Geolocation
  • cppwinrt

Scenario2_GetPosition.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_GetPosition.h"
00014 #include "Scenario2_GetPosition.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Devices::Geolocation;
00019 using namespace winrt::Windows::Foundation;
00020 using namespace winrt::Windows::UI::Xaml;
00021 using namespace winrt::Windows::UI::Xaml::Navigation;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario2_GetPosition::Scenario2_GetPosition()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     void Scenario2_GetPosition::OnNavigatedFrom(NavigationEventArgs const&)
00031     {
00032         if (m_pendingOperation)
00033         {
00034             m_pendingOperation.Cancel();
00035             m_pendingOperation = nullptr;
00036         }
00037     }
00038
00039     fire_and_forget Scenario2_GetPosition::GetGeolocationButtonClicked(IInspectable const&, RoutedEventArgs const&)
00040     {
00041         auto lifetime = get_strong();
00042
00043         GetGeolocationButton().IsEnabled(false);
00044         CancelGetGeolocationButton().IsEnabled(true);
00045         LocationDisabledMessage().Visibility(Visibility::Collapsed);
00046
00047         try
00048         {
00049             // Request permission to access location
00050             auto accessStatus = co_await Geolocator::RequestAccessAsync();
00051
00052             switch (accessStatus)
00053             {
00054             case GeolocationAccessStatus::Allowed:
00055             {
00056                 m_rootPage.NotifyUser(L"Waiting for update...", NotifyType::StatusMessage);
00057
00058                 // If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used.
00059                 Geolocator geolocator;
00060                 uint32_t desiredAccuracyInMetersValue;
00061                 if (TryParseUInt(DesiredAccuracyInMeters().Text().c_str(), desiredAccuracyInMetersValue))
00062                 {
00063                     geolocator.DesiredAccuracyInMeters(desiredAccuracyInMetersValue);
00064                 }
00065
00066                 // Carry out the operation
00067                 m_pendingOperation = geolocator.GetGeopositionAsync();
00068                 Geoposition pos = co_await m_pendingOperation;
00069
00070                 UpdateLocationData(pos);
00071                 m_rootPage.NotifyUser(L"Location updated.", NotifyType::StatusMessage);
00072             }
00073                 break;
00074
00075             case GeolocationAccessStatus::Denied:
00076                 m_rootPage.NotifyUser(L"Access to location is denied.", NotifyType::ErrorMessage);
00077                 LocationDisabledMessage().Visibility(Visibility::Visible);
00078                 UpdateLocationData(nullptr);
00079                 break;
00080
00081             case GeolocationAccessStatus::Unspecified:
00082                 m_rootPage.NotifyUser(L"Unspecified error.", NotifyType::ErrorMessage);
00083                 UpdateLocationData(nullptr);
00084                 break;
00085             }
00086         }
00087         catch (hresult_canceled const&)
00088         {
00089             m_rootPage.NotifyUser(L"Canceled.", NotifyType::StatusMessage);
00090         }
00091         catch (...)
00092         {
00093             m_rootPage.NotifyUser(to_message(), NotifyType::ErrorMessage);
00094         }
00095
00096         m_pendingOperation = nullptr;
00097         GetGeolocationButton().IsEnabled(true);
00098         CancelGetGeolocationButton().IsEnabled(false);
00099     }
00100
00101     void Scenario2_GetPosition::CancelGetGeolocationButtonClicked(IInspectable const&, RoutedEventArgs const&)
00102     {
00103         if (m_pendingOperation)
00104         {
00105             m_pendingOperation.Cancel();
00106             m_pendingOperation = nullptr;
00107         }
00108         GetGeolocationButton().IsEnabled(true);
00109         CancelGetGeolocationButton().IsEnabled(false);
00110     }
00111
00112     // Updates the user interface with the Geoposition data provided
00113     void Scenario2_GetPosition::UpdateLocationData(Geoposition const& position)
00114     {
00115         if (position == nullptr)
00116         {
00117             ScenarioOutput_Latitude().Text(L"No data");
00118             ScenarioOutput_Longitude().Text(L"No data");
00119             ScenarioOutput_Accuracy().Text(L"No data");
00120             ScenarioOutput_Source().Text(L"No data");
00121             ScenarioOutput_IsRemoteSource().Text(L"No data");
00122             ShowSatelliteData(false);
00123         }
00124         else
00125         {
00126             ScenarioOutput_Latitude().Text(to_hstring(position.Coordinate().Point().Position().Latitude));
00127             ScenarioOutput_Longitude().Text(to_hstring(position.Coordinate().Point().Position().Longitude));
00128             ScenarioOutput_Accuracy().Text(to_hstring(position.Coordinate().Accuracy()));
00129             ScenarioOutput_Source().Text(to_hstring(position.Coordinate().PositionSource()));
00130             ScenarioOutput_IsRemoteSource().Text(to_hstring(position.Coordinate().IsRemoteSource()));
00131
00132             if (position.Coordinate().PositionSource() == PositionSource::Satellite)
00133             {
00134                 // Show labels and satellite data when available
00135                 GeocoordinateSatelliteData satelliteData = position.Coordinate().SatelliteData();
00136                 ScenarioOutput_PosPrecision().Text(to_hstring(satelliteData.PositionDilutionOfPrecision()));
00137                 ScenarioOutput_HorzPrecision().Text(to_hstring(satelliteData.HorizontalDilutionOfPrecision()));
00138                 ScenarioOutput_VertPrecision().Text(to_hstring(satelliteData.VerticalDilutionOfPrecision()));;
00139                 ScenarioOutput_GeomPrecision().Text(to_hstring(satelliteData.GeometricDilutionOfPrecision()));;
00140                 ScenarioOutput_TimePrecision().Text(to_hstring(satelliteData.TimeDilutionOfPrecision()));;
00141                 ShowSatelliteData(true);
00142             }
00143             else
00144             {
00145                 // Hide labels and satellite data
00146                 ShowSatelliteData(false);
00147             }
00148         }
00149     }
00150
00151     void Scenario2_GetPosition::ShowSatelliteData(bool isVisible)
00152     {
00153         auto visibility = isVisible ? Visibility::Visible : Visibility::Collapsed;
00154         ScenarioOutput_PosPrecision().Visibility(visibility);
00155         ScenarioOutput_HorzPrecision().Visibility(visibility);
00156         ScenarioOutput_VertPrecision().Visibility(visibility);
00157         ScenarioOutput_GeomPrecision().Visibility(visibility);
00158         ScenarioOutput_TimePrecision().Visibility(visibility);
00159     }
00160
00161 }
Generated on Fri Nov 15 2024 22:19:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-I2C/cs/Scenario1_ReadData.xaml.cs Source File

  • IoT-I2C
  • cs

Scenario1_ReadData.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using System.Collections.Generic;
00015 using Windows.Devices.I2c;
00016 using Windows.Devices.Enumeration;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Media;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace SDKTemplate
00024 {
00025     public sealed partial class Scenario1_ReadData : Page
00026     {
00027         private I2cDevice htu21dSensor;
00028         private DispatcherTimer timer;
00029
00030         public Scenario1_ReadData()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         protected override void OnNavigatedFrom(NavigationEventArgs e)
00036         {
00037             StopScenario();
00038         }
00039
00040         private async Task StartScenarioAsync()
00041         {
00042             string i2cDeviceSelector = I2cDevice.GetDeviceSelector();
00043             IReadOnlyList<DeviceInformation> devices = await DeviceInformation.FindAllAsync(i2cDeviceSelector);
00044
00045             // 0x40 was determined by looking at the datasheet for the HTU21D sensor.
00046             var HTU21D_settings = new I2cConnectionSettings(0x40);
00047
00048             // If this next line crashes with an ArgumentOutOfRangeException,
00049             // then the problem is that no I2C devices were found.
00050             //
00051             // If the next line crashes with Access Denied, then the problem is
00052             // that access to the I2C device (HTU21D) is denied.
00053             //
00054             // The call to FromIdAsync will also crash if the settings are invalid.
00055             //
00056             // FromIdAsync produces null if there is a sharing violation on the device.
00057             // This will result in a NullReferenceException in Timer_Tick below.
00058             htu21dSensor = await I2cDevice.FromIdAsync(devices[0].Id, HTU21D_settings);
00059
00060             // Start the polling timer.
00061             timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(500) };
00062             timer.Tick += Timer_Tick;
00063             timer.Start();
00064         }
00065
00066         void StopScenario()
00067         {
00068             if (timer != null)
00069             {
00070                 timer.Tick -= Timer_Tick;
00071                 timer.Stop();
00072                 timer = null;
00073             }
00074
00075             // Release the I2C sensor.
00076             if (htu21dSensor != null)
00077             {
00078                 htu21dSensor.Dispose();
00079                 htu21dSensor = null;
00080             }
00081         }
00082
00083         async void StartStopScenario_Click(object sender, RoutedEventArgs e)
00084         {
00085             if (timer != null)
00086             {
00087                 StopScenario();
00088                 StartStopButton.Content = "Start";
00089                 ScenarioControls.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00090             }
00091             else
00092             {
00093                 StartStopButton.IsEnabled = false;
00094                 await StartScenarioAsync();
00095                 StartStopButton.IsEnabled = true;
00096                 StartStopButton.Content = "Stop";
00097                 ScenarioControls.Visibility = Windows.UI.Xaml.Visibility.Visible;
00098             }
00099         }
00100
00101         private void Timer_Tick(object sender, object e)
00102         {
00103             // Read data from I2C.
00104             var command = new byte[1];
00105             var humidityData = new byte[2];
00106             var temperatureData = new byte[2];
00107
00108             // Read humidity.
00109             command[0] = 0xE5;
00110
00111             // If this next line crashes with a NullReferenceException, then
00112             // there was a sharing violation on the device. (See StartScenarioAsync above.)
00113             //
00114             // If this next line crashes for some other reason, then there was
00115             // an error accessing the device.
00116             htu21dSensor.WriteRead(command, humidityData);
00117
00118             // Read temperature.
00119             command[0] = 0xE3;
00120             // If this next line crashes, then there was an error accessing the sensor.
00121             htu21dSensor.WriteRead(command, temperatureData);
00122
00123             // Calculate and report the humidity.
00124             var rawHumidityReading = humidityData[0] << 8 | humidityData[1];
00125             var humidityRatio = rawHumidityReading / (float)65536;
00126             double humidity = -6 + (125 * humidityRatio);
00127             CurrentHumidity.Text = humidity.ToString();
00128
00129             // Calculate and report the temperature.
00130             var rawTempReading = temperatureData[0] << 8 | temperatureData[1];
00131             var tempRatio = rawTempReading / (float)65536;
00132             double temperature = (-46.85 + (175.72 * tempRatio)) * 9 / 5 + 32;
00133             CurrentTemp.Text = temperature.ToString();
00134         }
00135     }
00136 }
Generated on Fri Nov 15 2024 22:20:03 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5 Member List

This is the complete list of members for Scenario5, including all inherited members.
Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario5 | [inline, private]
Scenario5() | Scenario5 | [inline]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Scenario7_DeviceInformationKind.cpp Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

Scenario7_DeviceInformationKind.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario7_DeviceInformationKind.h"
00014 #include "DeviceHelpers.h"
00015 #include "SampleConfiguration.h"
00016 #include "Scenario7_DeviceInformationKind.g.cpp"
00017
00018 using namespace winrt;
00019 using namespace winrt::Windows::Devices::Enumeration;
00020 using namespace winrt::Windows::Foundation;
00021 using namespace winrt::Windows::UI::Xaml;
00022 using namespace winrt::Windows::UI::Xaml::Navigation;
00023
00024 namespace winrt::SDKTemplate::implementation
00025 {
00026     Scenario7_DeviceInformationKind::Scenario7_DeviceInformationKind()
00027     {
00028         InitializeComponent();
00029     }
00030
00031     void Scenario7_DeviceInformationKind::OnNavigatedTo(NavigationEventArgs const&)
00032     {
00033         resultsListView().ItemsSource(resultCollection);
00034
00035         kindComboBox().ItemsSource(DeviceInformationKindChoices::Choices());
00036         kindComboBox().SelectedIndex(0);
00037     }
00038
00039     void Scenario7_DeviceInformationKind::OnNavigatedFrom(NavigationEventArgs const&)
00040     {
00041         StopWatchers(/* reset */ true);
00042     }
00043
00044     void Scenario7_DeviceInformationKind::StartWatcherButton_Click(IInspectable const&, RoutedEventArgs const&)
00045     {
00046         StartWatchers();
00047     }
00048
00049     void Scenario7_DeviceInformationKind::StopWatcherButton_Click(IInspectable const&, RoutedEventArgs const&)
00050     {
00051         StopWatchers();
00052     }
00053
00054     void Scenario7_DeviceInformationKind::StartWatchers()
00055     {
00056         startWatcherButton().IsEnabled(false);
00057         resultCollection.Clear();
00058
00059         // Create a watcher for each DeviceInformationKind selected by the user
00060         IInspectable item = kindComboBox().SelectedItem();
00061         DeviceInformationKindChoice* choice = FromInspectable<DeviceInformationKindChoice>(item);
00062
00063         for (DeviceInformationKind deviceInfoKind : choice->Kinds())
00064         {
00065             DeviceWatcher deviceWatcher = DeviceInformation::CreateWatcher(
00066                 {}, // AQS Filter string
00067                 nullptr, // requested properties
00068                 deviceInfoKind);
00069             com_ptr<DeviceWatcherHelper> deviceWatcherHelper = make_self<DeviceWatcherHelper>(resultCollection, Dispatcher());
00070             deviceWatcherHelper->UpdateStatus(false); // we will show our own status messages
00071             deviceWatcherHelper->DeviceChanged({ get_weak(), &Scenario7_DeviceInformationKind::OnDeviceListChanged });
00072             deviceWatcherHelpers.push_back(deviceWatcherHelper);
00073
00074             deviceWatcherHelper->StartWatcher(deviceWatcher);
00075         }
00076
00077         stopWatcherButton().IsEnabled(true);
00078         stopWatcherButton().Focus(FocusState::Keyboard);
00079     }
00080
00081     void Scenario7_DeviceInformationKind::StopWatchers(bool reset)
00082     {
00083         stopWatcherButton().IsEnabled(false);
00084
00085         for (com_ptr<DeviceWatcherHelper>& deviceWatcherHelper : deviceWatcherHelpers)
00086         {
00087             if (deviceWatcherHelper->IsWatcherRunning())
00088             {
00089                 deviceWatcherHelper->StopWatcher();
00090                 if (reset)
00091                 {
00092                     deviceWatcherHelper->Reset();
00093                 }
00094             }
00095         }
00096         deviceWatcherHelpers.clear();
00097
00098         startWatcherButton().IsEnabled(true);
00099         startWatcherButton().Focus(FocusState::Keyboard);
00100     }
00101
00102     void Scenario7_DeviceInformationKind::OnDeviceListChanged(DeviceWatcher const&, hstring const&)
00103     {
00104         int watchersRunning = 0;
00105
00106         // Count running watchers
00107         for (com_ptr<DeviceWatcherHelper> const& deviceWatcherHelper : deviceWatcherHelpers)
00108         {
00109             if (deviceWatcherHelper->IsWatcherRunning())
00110             {
00111                 watchersRunning++;
00112             }
00113         }
00114
00115         hstring message = to_hstring(watchersRunning) + L"/" + to_hstring(deviceWatcherHelpers.size()) +
00116             L" watchers running. " +
00117             to_hstring(resultCollection.Size()) + L" devices found.";
00118         rootPage.NotifyUser(message, NotifyType::StatusMessage);
00119     }
00120 }
00121
Generated on Fri Nov 15 2024 22:19:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampDevice/cpp/Scenario2_EnableSettings.xaml.cpp Source File

  • LampDevice
  • cpp

Scenario2_EnableSettings.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_EnableSettings.xaml.h"
00014 #include <sstream>
00015
00016 using namespace Concurrency;
00017 using namespace Platform;
00018 using namespace SDKTemplate;
00019 using namespace Windows::Devices;
00020 using namespace Windows::Devices::Enumeration;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Media::Capture;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Controls::Primitives;
00028 using namespace Windows::UI::Xaml::Data;
00029 using namespace Windows::UI::Xaml::Input;
00030 using namespace Windows::UI::Xaml::Media;
00031 using namespace Windows::UI::Xaml::Navigation;
00032
00033 /// <summary>
00034 /// Initializes a new instance of the <see cref="Scenario2_EnableSettings"/> class.
00035 /// </summary>
00036 Scenario2_EnableSettings::Scenario2_EnableSettings() : _rootPage(MainPage::Current)
00037 {
00038     InitializeComponent();
00039 }
00040
00041 /// <summary>
00042 /// Event handler for the OnNavigatedTo event. In this scenario, we want
00043 /// to get a lamp object for the lifetime of the page, so when we first
00044 /// navigate to the page, we Initialize a private lamp object
00045 /// </summary>
00046 /// <param name="e">Contains state information and event data associated with the event</param>
00047 void Scenario2_EnableSettings::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00048 {
00049     _rootPage = MainPage::Current;
00050     Windows::UI::Xaml::Controls::Page::OnNavigatedTo(e);
00051 }
00052
00053 /// <summary>
00054 /// Event Handler for Brightness Button Click
00055 /// </summary>
00056 /// <param name="sender">Contains information regarding button that fired event</param>
00057 /// <param name="e">Contains state information and event data associated with the event</param>
00058 void Scenario2_EnableSettings::BrightnessBtn_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00059 {
00060     LogStatusToOutputBoxAsync("Initializing lamp");
00061     _rootPage->NotifyUser("Initializing lamp", NotifyType::StatusMessage);
00062
00063     create_task(Lights::Lamp::GetDefaultAsync())
00064         .then([this](Lights::Lamp^ lamp)
00065     {
00066         if (lamp == nullptr)
00067         {
00068             LogStatusAsync("Error: No lamp device was found", NotifyType::ErrorMessage);
00069             return;
00070         }
00071
00072         std::wstringstream ss;
00073         ss << "Default lamp instance acquired, Device Id: " << lamp->DeviceId->Data();
00074         LogStatusAsync(ref new String(ss.str().c_str()), NotifyType::StatusMessage);
00075         LogStatusToOutputBoxAsync("Lamp Default settings:");
00076         ss.str(std::wstring());
00077         ss << "Lamp Enabled: " << lamp->IsEnabled << ", Brightness: " << lamp->BrightnessLevel;
00078         LogStatusToOutputBoxAsync(ref new String(ss.str().c_str()));
00079
00080         // Set the Brightness Level
00081         LogStatusToOutputBoxAsync("Adjusting Brightness");
00082         lamp->BrightnessLevel = 0.5F;
00083         ss.str(std::wstring());
00084         ss << "Lamp Settings After Brightness Adjustment: Brightness: " << lamp->BrightnessLevel;
00085         LogStatusAsync(ref new String(ss.str().c_str()), NotifyType::StatusMessage);
00086
00087         // Turn Lamp on
00088         LogStatusToOutputBoxAsync("Turning Lamp on");
00089         lamp->IsEnabled = true;
00090         ss.str(std::wstring());
00091         ss << "Lamp Enabled: " << lamp->IsEnabled;
00092         LogStatusToOutputBoxAsync(ref new String(ss.str().c_str()));
00093
00094         // Turn Lamp off
00095         LogStatusToOutputBoxAsync("Turning Lamp off");
00096         lamp->IsEnabled = false;
00097         ss.str(std::wstring());
00098         ss << "Lamp Enabled: " << lamp->IsEnabled;
00099         LogStatusToOutputBoxAsync(ref new String(ss.str().c_str()));
00100     });
00101 }
00102
00103 /// <summary>
00104 /// Event handler for Color Lamp Button. Queries the lamp device for color adjustment
00105 /// support and if device supports being color settable, it sets lamp color to blue.
00106 /// Click Event
00107 /// </summary>
00108 /// <param name="sender">Contains information regarding button that fired event</param>
00109 /// <param name="e">Contains state information and event data associated with the event</param>
00110 void Scenario2_EnableSettings::ColorLampBtn_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00111 {
00112     LogStatusToOutputBoxAsync("Initializing lamp");
00113
00114     create_task(Lights::Lamp::GetDefaultAsync())
00115         .then([this](Lights::Lamp^ lamp)
00116     {
00117         if (lamp == nullptr)
00118         {
00119             LogStatusAsync("Error: No lamp device was found", NotifyType::ErrorMessage);
00120             return;
00121         }
00122
00123         // With Lamp instance required, query for the default settings of the Lamp
00124         LogStatusAsync("Default lamp instance acquired", NotifyType::StatusMessage);
00125         LogStatusToOutputBoxAsync("Lamp Default settings:");
00126         std::wstringstream ss;
00127         ss << "Lamp Enabled: " << lamp->IsEnabled << ", Is Color Settable: " << lamp->IsColorSettable;;
00128         LogStatusToOutputBoxAsync(ref new String(ss.str().c_str()));
00129
00130         // If this lamp device is not Color Settable exit color lamp adjustment
00131         if (lamp->IsColorSettable == false)
00132         {
00133             LogStatusAsync("Selected Lamp device doesn't support Color lamp adjustment", NotifyType::ErrorMessage);
00134             return;
00135         }
00136
00137         // Change Lamp Color
00138         LogStatusToOutputBoxAsync("Adjusting Color");
00139         lamp->Color = Windows::UI::Colors::Blue;
00140         LogStatusAsync("Lamp color has been changed", NotifyType::StatusMessage);
00141
00142         // Turn Lamp on
00143         LogStatusToOutputBoxAsync("Turning Lamp on");
00144         lamp->IsEnabled = true;
00145         ss.str(std::wstring());
00146         ss << "Lamp Enabled: " << lamp->IsEnabled;
00147         LogStatusToOutputBoxAsync(ref new String(ss.str().c_str()));
00148
00149         // Turn Lamp off
00150         LogStatusToOutputBoxAsync("Turning Lamp off");
00151         lamp->IsEnabled = false;
00152         ss.str(std::wstring());
00153         ss << "Lamp Enabled: " << lamp->IsEnabled;
00154         LogStatusToOutputBoxAsync(ref new String(ss.str().c_str()));
00155     });
00156 }
00157
00158 /// <summary>
00159 /// Marshall log message to the UI thread and update outputBox, this method is for more general messages
00160 /// Note: This method is asynchronous and is not guaranteed to display messages in the order in
00161 /// which they were called without task chaining
00162 /// </summary>
00163 /// <param name="message">Message to log to the outputBox</param>
00164 task<void> Scenario2_EnableSettings::LogStatusToOutputBoxAsync(String^ message)
00165 {
00166     return create_task(Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, message]()
00167     {
00168         outputBox->Text += message + "\r\n";
00169         outputScrollViewer->ChangeView(0.0, outputBox->ActualHeight, 1.0f);
00170     })));
00171 }
00172
00173 /// <summary>
00174 /// Method to log Status to Main Status block, this method is for important status messages to be
00175 /// displayed at bottom of scenario page
00176 /// Note: This method is asynchronous and is not guaranteed to display messages in the order in
00177 /// which they were called without task chaining
00178 /// </summary>
00179 /// <param name="message">Message to log to the output box</param>
00180 /// <param name="type">Notification Type for status message</param>
00181 task<void> Scenario2_EnableSettings::LogStatusAsync(String^ message, NotifyType type)
00182 {
00183     return create_task(Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, message, type]()
00184     {
00185         _rootPage->NotifyUser(message, type);
00186     }))).then([this, message]()
00187     {
00188         return LogStatusToOutputBoxAsync(message);
00189     });
00190 }
Generated on Fri Nov 15 2024 22:20:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomTextRenderer Member List

This is the complete list of members for CustomTextRenderer, including all inherited members.
CustomTextRenderer(Microsoft::WRL::ComPtr< ID2D1Factory > d2dFactory, Microsoft::WRL::ComPtr< ID2D1DeviceContext4 > d2dDeviceContext) | CustomTextRenderer |
DrawGlyphRun(_In_opt_ void *clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_MEASURING_MODE measuringMode, _In_ DWRITE_GLYPH_RUN const *glyphRun, _In_ DWRITE_GLYPH_RUN_DESCRIPTION const *glyphRunDescription, IUnknown *clientDrawingEffect) | CustomTextRenderer |
DrawInlineObject(_In_opt_ void *clientDrawingContext, FLOAT originX, FLOAT originY, IDWriteInlineObject *inlineObject, BOOL isSideways, BOOL isRightToLeft, IUnknown *clientDrawingEffect) | CustomTextRenderer |
DrawStrikethrough(_In_opt_ void *clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, _In_ DWRITE_STRIKETHROUGH const *strikethrough, IUnknown *clientDrawingEffect) | CustomTextRenderer |
DrawUnderline(_In_opt_ void *clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, _In_ DWRITE_UNDERLINE const *underline, IUnknown *clientDrawingEffect) | CustomTextRenderer |
GetCurrentTransform(_In_opt_ void *clientDrawingContext, _Out_ DWRITE_MATRIX *transform) | CustomTextRenderer |
GetPixelsPerDip(_In_opt_ void *clientDrawingContext, _Out_ FLOAT *pixelsPerDip) | CustomTextRenderer |
IFACEMETHOD_(unsigned long, AddRef)() | CustomTextRenderer |
IFACEMETHOD_(unsigned long, Release)() | CustomTextRenderer |
IsPixelSnappingDisabled(_In_opt_ void *clientDrawingContext, _Out_ BOOL *isDisabled) | CustomTextRenderer |
m_d2dDeviceContext | CustomTextRenderer | [private]
m_d2dFactory | CustomTextRenderer | [private]
m_dwriteFactory | CustomTextRenderer | [private]
m_outlineBrush | CustomTextRenderer | [private]
m_refCount | CustomTextRenderer | [private]
m_tempBrush | CustomTextRenderer | [private]
QueryInterface(IID const &riid, void **ppvObject) | CustomTextRenderer |
Generated on Fri Nov 15 2024 22:23:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScannerProvider/cpp/BarcodeDecoder/Provider.h Source File

  • BarcodeScannerProvider
  • cpp
  • BarcodeDecoder

Provider.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012
00013 #include "pch.h"
00014 #include "DecodeEngine.h"
00015
00016 namespace BarcodeDecoder
00017 {
00018     ref class Provider sealed
00019     {
00020     public:
00021         Provider(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ backgroundTask);
00022         virtual ~Provider();
00023
00024     private:
00025         Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^ m_connection;
00026         bool m_scannerEnabled = false;
00027         std::map <UINT, Windows::Devices::PointOfService::BarcodeSymbologyAttributes^> m_symbologyAttributes;
00028
00029         Windows::ApplicationModel::Background::IBackgroundTaskInstance^ m_backgroundTask;
00030         Platform::Agile<Windows::ApplicationModel::Background::BackgroundTaskDeferral> m_deferral;
00031
00032         Windows::Devices::PointOfService::Provider::BarcodeScannerFrameReader^ m_frameReader;
00033         DecodeEngine^ m_decodeEngine;
00034
00035         DecodeResult^ m_previousDecodeResult;
00036
00037         Windows::Foundation::EventRegistrationToken m_frameArrivedToken;
00038         Windows::Foundation::EventRegistrationToken m_enableScannerRequestedToken;
00039         Windows::Foundation::EventRegistrationToken m_disableScannerRequestedToken;
00040         Windows::Foundation::EventRegistrationToken m_getBarcodeSymbologyAttributesRequestedToken;
00041         Windows::Foundation::EventRegistrationToken m_setBarcodeSymbologyAttributesRequestedToken;
00042         Windows::Foundation::EventRegistrationToken m_startSoftwareTriggerRequestedToken;
00043         Windows::Foundation::EventRegistrationToken m_stopSoftwareTriggerRequestedToken;
00044         Windows::Foundation::EventRegistrationToken m_hideVideoPreviewRequestedToken;
00045         Windows::Foundation::EventRegistrationToken m_getActiveSymbologiesRequestedToken;
00046
00047         void Initialize();
00048         void CleanUp();
00049         void RegisterEventHandlers();
00050         Windows::Devices::PointOfService::BarcodeScannerReport^ CreateBarcodeScannerReportFromString(Platform::String^ barcodeString, UINT barcodeSymbology);
00051
00052         void FrameReader_FrameArrived(Windows::Devices::PointOfService::Provider::BarcodeScannerFrameReader^ sender, Windows::Devices::PointOfService::Provider::BarcodeScannerFrameReaderFrameArrivedEventArgs^ args);
00053
00054         void Task_Completed(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ sender, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ args);
00055         void BackgroundTask_Canceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ sender, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason args);
00056
00057         void BarcodeScannerProviderConnection_EnableScannerRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^ sender, Windows::Devices::PointOfService::Provider::BarcodeScannerEnableScannerRequestEventArgs^ args);
00058         void BarcodeScannerProviderConnection_DisableScannerRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^ sender, Windows::Devices::PointOfService::Provider::BarcodeScannerDisableScannerRequestEventArgs^ args);
00059         void BarcodeScannerProviderConnection_GetBarcodeSymbologyAttributesRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^ sender, Windows::Devices::PointOfService::Provider::BarcodeScannerGetSymbologyAttributesRequestEventArgs^ args);
00060         void BarcodeScannerProviderConnection_SetBarcodeSymbologyAttributesRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^ sender, Windows::Devices::PointOfService::Provider::BarcodeScannerSetSymbologyAttributesRequestEventArgs^ args);
00061         void BarcodeScannerProviderConnection_StartSoftwareTriggerRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^ sender, Windows::Devices::PointOfService::Provider::BarcodeScannerStartSoftwareTriggerRequestEventArgs^ args);
00062         void BarcodeScannerProviderConnection_StopSoftwareTriggerRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^ sender, Windows::Devices::PointOfService::Provider::BarcodeScannerStopSoftwareTriggerRequestEventArgs^ args);
00063         void BarcodeScannerProviderConnection_HideVideoPreviewRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^ sender, Windows::Devices::PointOfService::Provider::BarcodeScannerHideVideoPreviewRequestEventArgs^ args);
00064         void BarcodeScannerProviderConnection_SetActiveSymbologiesRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^ sender, Windows::Devices::PointOfService::Provider::BarcodeScannerSetActiveSymbologiesRequestEventArgs^ args);
00065     };
00066 }
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ReinhardEffect Member List

This is the complete list of members for ReinhardEffect, including all inherited members.
Clamp(float v, float low, float high) | ReinhardEffect | [inline, private, static]
CreateReinhardImpl(_Outptr_ IUnknown **ppEffectImpl) | ReinhardEffect | [static]
dpi | ReinhardEffect |
IFACEMETHODIMP_(UINT32) GetInputCount() const | ReinhardEffect |
IFACEMETHODIMP_(ULONG) AddRef() | ReinhardEffect |
IFACEMETHODIMP_(ULONG) Release() | ReinhardEffect |
Initialize(_In_ ID2D1EffectContext *pContextInternal, _In_ ID2D1TransformGraph *pTransformGraph) | ReinhardEffect |
m_constants | ReinhardEffect | [private]
m_dpi | ReinhardEffect | [private]
m_drawInfo | ReinhardEffect | [private]
m_effectContext | ReinhardEffect | [private]
m_inputRect | ReinhardEffect | [private]
m_refCount | ReinhardEffect | [private]
MapInputRectsToOutputRect(_In_reads_(inputRectCount) CONST D2D1_RECT_L *pInputRects, _In_reads_(inputRectCount) CONST D2D1_RECT_L *pInputOpaqueSubRects, UINT32 inputRectCount, _Out_ D2D1_RECT_L *pOutputRect, _Out_ D2D1_RECT_L *pOutputOpaqueSubRect) | ReinhardEffect |
MapInvalidRect(UINT32 inputIndex, D2D1_RECT_L invalidInputRect, _Out_ D2D1_RECT_L *pInvalidOutputRect) const | ReinhardEffect |
MapOutputRectToInputRects(_In_ const D2D1_RECT_L *pOutputRect, _Out_writes_(inputRectCount) D2D1_RECT_L *pInputRects, UINT32 inputRectCount) const | ReinhardEffect |
PrepareForRender(D2D1_CHANGE_TYPE changeType) | ReinhardEffect |
QueryInterface(_In_ REFIID riid, _Outptr_ void **ppOutput) | ReinhardEffect |
Register(_In_ ID2D1Factory1 *pFactory) | ReinhardEffect | [static]
ReinhardEffect() | ReinhardEffect | [private]
Round(float v) | ReinhardEffect | [inline, private, static]
SafeAdd(long base, long valueToAdd) | ReinhardEffect | [inline, private, static]
SetDrawInfo(_In_ ID2D1DrawInfo *pRenderInfo) | ReinhardEffect |
SetGraph(_In_ ID2D1TransformGraph *pGraph) | ReinhardEffect |
UpdateConstants() | ReinhardEffect | [private]
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserConsentVerifier/cppwinrt/pch.h Source File

  • UserConsentVerifier
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Security.Credentials.UI.h"
00008 #include "winrt/Windows.System.h"
00009 #include "winrt/Windows.UI.Core.h"
00010 #include "winrt/Windows.UI.Xaml.h"
00011 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00012 #include "winrt/Windows.UI.Xaml.Controls.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00014 #include "winrt/Windows.UI.Xaml.Documents.h"
00015 #include "winrt/Windows.UI.Xaml.Interop.h"
00016 #include "winrt/Windows.UI.Xaml.Markup.h"
00017 #include "winrt/Windows.UI.Xaml.Media.h"
00018 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DatagramSocket/cpp/Scenario1.xaml.h Source File

  • DatagramSocket
  • cpp

Scenario1.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1.xaml.h
00014 // Declaration of the Scenario1 class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario1.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     namespace DatagramSocketSample
00026     {
00027         [Windows::Foundation::Metadata::WebHostHidden]
00028         // In c++, adding this attribute to ref classes enables data binding.
00029         // For more info search for 'Bindable' on the page http://go.microsoft.com/fwlink/?LinkId=254639
00030         [Windows::UI::Xaml::Data::Bindable]
00031         public ref class LocalHostItem sealed
00032         {
00033         public:
00034             LocalHostItem(Windows::Networking::HostName^ localHostName);
00035             property Platform::String^ DisplayString { Platform::String^ get() { return displayString; } }
00036             property Windows::Networking::HostName^ LocalHost { Windows::Networking::HostName^ get() { return localHost; } }
00037
00038         private:
00039             Platform::String^ displayString;
00040             Windows::Networking::HostName^ localHost;
00041         };
00042
00043         [Windows::Foundation::Metadata::WebHostHidden]
00044         public ref class Scenario1 sealed
00045         {
00046         public:
00047             Scenario1();
00048
00049         protected:
00050             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00051         private:
00052             MainPage^ rootPage;
00053
00054             // Vector containing all available local HostName endpoints
00055             Platform::Collections::Vector<LocalHostItem^>^ localHostItems;
00056             void StartListener_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00057             void BindToAny_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00058             void BindToAny_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00059             void PopulateAdapterList();
00060         };
00061
00062         [Windows::Foundation::Metadata::WebHostHidden]
00063         public ref class ListenerContext sealed
00064         {
00065         public:
00066             ListenerContext(MainPage^ rootPage, Windows::Networking::Sockets::DatagramSocket^ listener);
00067
00068             void OnMessage(
00069                 Windows::Networking::Sockets::DatagramSocket^ socket,
00070                 Windows::Networking::Sockets::DatagramSocketMessageReceivedEventArgs^ eventArguments);
00071             bool IsMatching(Windows::Networking::HostName^ hostName, Platform::String^ port);
00072
00073         private:
00074             ~ListenerContext();
00075             CRITICAL_SECTION lock;
00076             MainPage^ rootPage;
00077             Windows::Networking::Sockets::DatagramSocket^ listener;
00078             Windows::Storage::Streams::IOutputStream^ outputStream;
00079             Windows::Networking::HostName^ hostName;
00080             Platform::String^ port;
00081
00082             void NotifyUserFromAsyncThread(Platform::String^ message, NotifyType type);
00083             void EchoMessage(Windows::Networking::Sockets::DatagramSocketMessageReceivedEventArgs^ eventArguments);
00084         };
00085     }
00086 }
Generated on Fri Nov 15 2024 22:17:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario3_Text.xaml.h Source File

  • FileAccess
  • cpp

Scenario3_Text.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario3_Text.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Writing and reading text in a file.
00022     /// </summary>
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class Scenario3 sealed
00025     {
00026     public:
00027         Scenario3();
00028         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029
00030     private:
00031         MainPage^ rootPage = MainPage::Current;
00032
00033         void WriteTextButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void ReadTextButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035     };
00036 }
Generated on Fri Nov 15 2024 22:19:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/Scenario8.cpp Source File

  • FileAccess
  • cppwinrt

Scenario8.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario8.h"
00014 #include "Scenario8.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Storage;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Navigation;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario8::Scenario8()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     void Scenario8::OnNavigatedTo(NavigationEventArgs const&)
00031     {
00032         SampleState::ValidateFile();
00033     }
00034
00035     fire_and_forget Scenario8::CopyFileButton_Click(IInspectable const&, RoutedEventArgs const&)
00036     {
00037         auto lifetime = get_strong();
00038
00039         StorageFile file = SampleState::SampleFile();
00040         if (file != nullptr)
00041         {
00042             try
00043             {
00044                 StorageFolder picturesLibrary = co_await KnownFolders::GetFolderForUserAsync(nullptr /* current user */, KnownFolderId::PicturesLibrary);
00045                 StorageFile fileCopy = co_await file.CopyAsync(picturesLibrary, L"sample - Copy.dat", NameCollisionOption::ReplaceExisting);
00046                 rootPage.NotifyUser(L"The file '" + file.Name() + L"' was copied and the new file was named '" + fileCopy.Name() + L"'.", NotifyType::StatusMessage);
00047             }
00048             catch (const hresult_error& ex)
00049             {
00050                 // I/O errors are reported as exceptions.
00051                 rootPage.NotifyUser(L"Error copying file '" + file.Name() + L"': " + ex.message(), NotifyType::ErrorMessage);
00052             }
00053         }
00054         else
00055         {
00056             SampleState::NotifyUserFileNotExist();
00057         }
00058     }
00059 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Content/ShaderStructures.h Source File

  • HolographicVoiceInput
  • cpp
  • Content

ShaderStructures.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 namespace HolographicVoiceInput
00014 {
00015     // Constant buffer used to send hologram position transform to the shader pipeline.
00016     struct ModelColorConstantBuffer
00017     {
00018         DirectX::XMFLOAT4X4 model;
00019         DirectX::XMFLOAT4   color;
00020     };
00021
00022     // Assert that the constant buffer remains 16-byte aligned (best practice).
00023     static_assert((sizeof(ModelColorConstantBuffer) % (sizeof(float) * 4)) == 0, "Model constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00024
00025
00026     // Used to send per-vertex data to the vertex shader.
00027     struct VertexPositionColor
00028     {
00029         DirectX::XMFLOAT3 pos;
00030         DirectX::XMFLOAT3 color;
00031     };
00032 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSensors/cs/Scenario2_Polling.xaml.cs Source File

  • CustomSensors
  • cs

Scenario2_Polling.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using Windows.Devices.Enumeration;
00015 using Windows.Devices.Sensors.Custom;
00016 using Windows.Foundation;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020
00021 namespace CustomSensors
00022 {
00023     public sealed partial class Scenario2_Polling : Page
00024     {
00025         // The following ID is defined by vendors and is unique to a custom sensor type. Each custom sensor driver should define one unique ID.
00026         //
00027         // The ID below is defined in the custom sensor driver sample available in the SDK. It identifies the custom sensor CO2 emulation sample driver.
00028         Guid GUIDCustomSensorDeviceVendorDefinedTypeID = new Guid("4025a865-638c-43aa-a688-98580961eeae");
00029
00030         // A property key is defined by vendors for each datafield property a custom sensor driver exposes. Property keys are defined
00031         // per custom sensor driver and is unique to each custom sensor type.
00032         //
00033         // The following property key represents the CO2 level as defined in the custom sensor CO2 emulation driver sample available in the WDK.
00034         // In this example only one key is defined, but other drivers may define more than one key by rev'ing up the property key index.
00035         const String CO2LevelKey = "{74879888-a3cc-45c6-9ea9-058838256433} 1";
00036
00037         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00038         // as NotifyUser()
00039         MainPage rootPage = MainPage.Current;
00040
00041         private CustomSensor customSensor;
00042         private DeviceWatcher watcher;
00043         private DeviceAccessInformation deviceAccessInformation;
00044
00045         public Scenario2_Polling()
00046         {
00047             String customSensorSelector = "";
00048
00049             this.InitializeComponent();
00050
00051             customSensorSelector = CustomSensor.GetDeviceSelector(GUIDCustomSensorDeviceVendorDefinedTypeID);
00052             watcher = DeviceInformation.CreateWatcher(customSensorSelector);
00053             watcher.Added += OnCustomSensorAdded;
00054             watcher.Start();
00055
00056             // Register to be notified when the user disables access to the custom sensor through privacy settings.
00057             deviceAccessInformation = DeviceAccessInformation.CreateFromDeviceClassId(GUIDCustomSensorDeviceVendorDefinedTypeID);
00058             deviceAccessInformation.AccessChanged += new TypedEventHandler<DeviceAccessInformation, DeviceAccessChangedEventArgs>(OnAccessChanged);
00059         }
00060
00061         /// <summary>
00062         /// Invoked when the device watcher finds a matching custom sensor device
00063         /// </summary>
00064         /// <param name="watcher">device watcher</param>
00065         /// <param name="customSensorDevice">device information for the custom sensor that was found</param>
00066         public async void OnCustomSensorAdded(DeviceWatcher watcher, DeviceInformation customSensorDevice)
00067         {
00068             try
00069             {
00070                 customSensor = await CustomSensor.FromIdAsync(customSensorDevice.Id);
00071                 if (customSensor != null)
00072                 {
00073                     CustomSensorReading reading = customSensor.GetCurrentReading();
00074                     if (!reading.Properties.ContainsKey(CO2LevelKey))
00075                     {
00076                         rootPage.NotifyUser("The found custom sensor doesn't provide CO2 reading", NotifyType.ErrorMessage);
00077                         customSensor = null;
00078                     }
00079                 }
00080                 else
00081                 {
00082                     rootPage.NotifyUser("No custom sensor found", NotifyType.ErrorMessage);
00083                 }
00084             }
00085             catch (Exception e)
00086             {
00087                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00088                 {
00089                     rootPage.NotifyUser("The user may have denied access to the custom sensor. Error: " + e.Message, NotifyType.ErrorMessage);
00090                 });
00091             }
00092         }
00093
00094         /// <summary>
00095         /// This is the event handler for AccessChanged events.
00096         /// </summary>
00097         /// <param name="sender"></param>
00098         /// <param name="e"></param>
00099         private async void OnAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs e)
00100         {
00101             var status = e.Status;
00102             if (status != DeviceAccessStatus.Allowed)
00103             {
00104                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00105                 {
00106                     rootPage.NotifyUser("Custom sensor access denied", NotifyType.ErrorMessage);
00107                     customSensor = null;
00108                 });
00109             }
00110         }
00111
00112         /// <summary>
00113         /// This is the dispatcher callback.
00114         /// </summary>
00115         /// <param name="sender"></param>
00116         /// <param name="args"></param>
00117         private void GetCO2Level(object sender, RoutedEventArgs e)
00118         {
00119             if (customSensor != null)
00120             {
00121                 CustomSensorReading reading = customSensor.GetCurrentReading();
00122
00123                 string CO2LevelString = String.Format("{0,5:0.00}", reading.Properties[CO2LevelKey]);
00124                 ScenarioOutputCO2Level.Text = CO2LevelString;
00125             }
00126             else
00127             {
00128                 rootPage.NotifyUser("No custom sensor found", NotifyType.ErrorMessage);
00129             }
00130         }
00131     }
00132 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/ComputeShader/DftEffect.h Source File

  • D2DCustomEffects
  • cpp
  • ComputeShader

DftEffect.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "DftTransform.h"
00015
00016 // Define a unique GUID for the effect.
00017 DEFINE_GUID(CLSID_CustomDftEffect, 0x88F0F871, 0x18A3, 0x4C55, 0xB5, 0x28, 0xE7, 0x38, 0xA7, 0x81, 0x35, 0x1F);
00018
00019 class DftEffect : public ID2D1EffectImpl
00020 {
00021 public:
00022     // Effect Registration
00023     static HRESULT Register(_In_ ID2D1Factory1* pFactory);
00024     static HRESULT __stdcall Create(_Outptr_ IUnknown** ppEffectImpl);
00025
00026     // ID2D1EffectImpl Methods:
00027     IFACEMETHODIMP Initialize(
00028         _In_ ID2D1EffectContext* pEffectContext,
00029         _In_ ID2D1TransformGraph* pTransformGraph
00030         );
00031
00032     IFACEMETHODIMP PrepareForRender(D2D1_CHANGE_TYPE changeType);
00033     IFACEMETHODIMP SetGraph(_In_ ID2D1TransformGraph* pTransformGraph);
00034
00035     // IUnknown Methods:
00036     IFACEMETHODIMP_(ULONG) AddRef();
00037     IFACEMETHODIMP_(ULONG) Release();
00038     IFACEMETHODIMP QueryInterface(REFIID riid, _Outptr_ void** ppOutput);
00039
00040 private:
00041     DftEffect();
00042
00043     LONG m_cRef;
00044 };
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cppwinrt/Scenario3_CurrencyFormatting.h Source File

  • NumberFormatting
  • cppwinrt

Scenario3_CurrencyFormatting.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_CurrencyFormatting.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario3_CurrencyFormatting : Scenario3_CurrencyFormattingT<Scenario3_CurrencyFormatting>
00019     {
00020         Scenario3_CurrencyFormatting();
00021
00022         void Display_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario3_CurrencyFormatting : Scenario3_CurrencyFormattingT<Scenario3_CurrencyFormatting, implementation::Scenario3_CurrencyFormatting>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:20:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampArray/cs/Scenario1_Basics.xaml.cs Source File

  • LampArray
  • cs

Scenario1_Basics.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using Windows.Devices.Enumeration;
00016 using Windows.Devices.Lights;
00017 using Windows.System;
00018 using Windows.UI;
00019 using Windows.UI.Core;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Navigation;
00023
00024 namespace SDKTemplate
00025 {
00026     public sealed partial class Scenario1_Basics : Page
00027     {
00028         private MainPage rootPage = MainPage.Current;
00029
00030         private DeviceWatcher m_deviceWatcher;
00031
00032         // Currently attached LampArrays
00033         private readonly List<LampArrayInfo> m_attachedLampArrays = new List<LampArrayInfo>();
00034
00035         public Scenario1_Basics()
00036         {
00037             InitializeComponent();
00038         }
00039
00040         protected override void OnNavigatedTo(NavigationEventArgs e)
00041         {
00042             UpdateLampArrayList();
00043
00044             // Start watching for newly attached LampArrays.
00045             m_deviceWatcher = DeviceInformation.CreateWatcher(LampArray.GetDeviceSelector());
00046
00047             m_deviceWatcher.Added += Watcher_Added;
00048             m_deviceWatcher.Removed += Watcher_Removed;
00049
00050             m_deviceWatcher.Start();
00051         }
00052
00053         protected override void OnNavigatedFrom(NavigationEventArgs e)
00054         {
00055             m_deviceWatcher.Stop();
00056         }
00057
00058         private async void Watcher_Added(DeviceWatcher sender, DeviceInformation args)
00059         {
00060             var info = new LampArrayInfo(args.Id, args.Name, await LampArray.FromIdAsync(args.Id));
00061
00062             // DeviceWatcher events are invoked on a background thread.
00063             // We need to switch to the foreground thread to update our app UI
00064             // and access member variables without race conditions.
00065             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00066             {
00067                 if (info.lampArray == null)
00068                 {
00069                     // A LampArray was found, but Windows couldn't initialize it.
00070                     // This suggests a device error.
00071                     rootPage.NotifyUser($"Problem with LampArray {info.displayName}.", NotifyType.ErrorMessage);
00072                     return;
00073                 }
00074
00075                 // Set up the AvailabilityChanged event callback for being notified whether this process can control
00076                 // RGB lighting for the newly attached LampArray.
00077                 info.lampArray.AvailabilityChanged += LampArray_AvailabilityChanged;
00078
00079                 // Remember this new LampArray and add it to the list.
00080                 m_attachedLampArrays.Add(info);
00081                 UpdateLampArrayList();
00082             });
00083         }
00084
00085         private async void Watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
00086         {
00087             // DeviceWatcher events are invoked on a background thread.
00088             // We need to switch to the foreground thread to update our app UI
00089             // and access member variables without race conditions.
00090             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00091             {
00092                 m_attachedLampArrays.RemoveAll(info => info.id == args.Id);
00093                 UpdateLampArrayList();
00094             });
00095         }
00096
00097         // The AvailabilityChanged event will fire when this calling process gains or loses control of RGB lighting
00098         // for the specified LampArray.
00099         private async void LampArray_AvailabilityChanged(LampArray sender, object args)
00100         {
00101             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00102             {
00103                 UpdateLampArrayList();
00104             });
00105         }
00106
00107         private void UpdateLampArrayList()
00108         {
00109             string message = $"Attached LampArrays: {m_attachedLampArrays.Count}\n";
00110             foreach (LampArrayInfo info in m_attachedLampArrays)
00111             {
00112                 message += $"\t{info.displayName} ({info.lampArray.LampArrayKind.ToString()}, {info.lampArray.LampCount} lamps, " +
00113                            $"{(info.lampArray.IsAvailable ? "Available" : "Unavailable")})\n";
00114             }
00115             LampArraysSummary.Text = message;
00116         }
00117
00118         private void Apply_Clicked(object sender, RoutedEventArgs e)
00119         {
00120             foreach (LampArrayInfo info in m_attachedLampArrays)
00121             {
00122                 ApplySettingsToLampArray(info.lampArray);
00123             }
00124         }
00125
00126         private void ApplySettingsToLampArray(LampArray lampArray)
00127         {
00128             // Apply the light pattern.
00129             if (OffButton.IsChecked.Value)
00130             {
00131                 // Set all Lamps on the LampArray to black, turning them off.
00132                 lampArray.SetColor(Colors.Black);
00133             }
00134             else if (SetColorButton.IsChecked.Value)
00135             {
00136                 // Set all Lamps on the LampArray to green.
00137                 lampArray.SetColor(Colors.Green);
00138             }
00139             else if (GradientButton.IsChecked.Value)
00140             {
00141                 SetGradientPatternToLampArray(lampArray);
00142             }
00143             else if (WasdButton.IsChecked.Value)
00144             {
00145                 SetWasdPatternToLampArray(lampArray);
00146             }
00147
00148             // Apply the brightness. Convert the percentage value in the slider to the range [0, 1] expected by BrightnessLevel.
00149             lampArray.BrightnessLevel = BrightnessSlider.Value / BrightnessSlider.Maximum;
00150         }
00151
00152         private void SetGradientPatternToLampArray(LampArray lampArray)
00153         {
00154             // Create a static gradient on the LampArray from black to red, blending from left to right.
00155
00156             // For this effect, we want to set the colors of all Lamps. Create an array containing all the Lamp indices
00157             // and an array of Colors. Both arrays must be of the same length. We will use these for SetColorsForIndices later.
00158             int[] indices = Enumerable.Range(0, lampArray.LampCount).ToArray();
00159             var colors = new Color[lampArray.LampCount];
00160
00161             // A LampArray provides information about its size using a three-dimensional logical bounding box,
00162             // as well as the location of each of its Lamps within that bounding box.
00163             // The origin point of the bounding box is the leftmost (X), farthest (Y), uppermost (Z) corner relative to the user.
00164             // LampArray bounding boxes and Lamp positions are measured in meters.
00165
00166             // Because our gradient will blend from left to right, we will set the Lamp colors according to each Lamp's X position.
00167             // We will make two passes over the LampArray. First, calculate the minimum and maximum X position values of all Lamps.
00168             // This is to "trim" the margins of the bounding box where no Lamps are present.
00169             double maxX = 0;
00170             double minX = lampArray.BoundingBox.X;
00171
00172             foreach (int i in indices)
00173             {
00174                 LampInfo lampInfo = lampArray.GetLampInfo(i);
00175
00176                 if (lampInfo.Position.X > maxX)
00177                 {
00178                     maxX = lampInfo.Position.X;
00179                 }
00180
00181                 if (lampInfo.Position.X < minX)
00182                 {
00183                     minX = lampInfo.Position.X;
00184                 }
00185             }
00186
00187             // In the second pass, we will calculate the gradient colors for each Lamp.
00188             foreach (int i in indices)
00189             {
00190                 LampInfo lampInfo = lampArray.GetLampInfo(i);
00191
00192                 // Calculate the X position for this Lamp relative to the rightmost Lamp. We will scale the Lamp's color by this relative value below.
00193                 // (We also want to avoid dividing by zero here in case all Lamps share the same X position, including the single-Lamp case.)
00194                 double xProgress = 1.0;
00195                 if (maxX != minX)
00196                 {
00197                     xProgress = (lampInfo.Position.X - minX) / (maxX - minX);
00198                 }
00199
00200                 // Apply that value to the expected color for the lamp.
00201                 // Maximize the Alpha value to give the color full opacity.
00202                 colors[i].A = byte.MaxValue;
00203
00204                 // Set the color's R value based on the Lamp's X position.
00205                 // As the X position of the Lamp increases (i.e., is further to the right),
00206                 // the Red value of the Lamp's color will also increase.
00207                 // This means that the leftmost Lamp(s) will be black (turned off), and the rightmost Lamp(s) will be the brightest red.
00208                 colors[i].R = (byte)(xProgress * byte.MaxValue);
00209             }
00210
00211             // Apply the colors to the LampArray.
00212             lampArray.SetColorsForIndices(colors, indices);
00213         }
00214
00215         private void SetWasdPatternToLampArray(LampArray lampArray)
00216         {
00217             // Set a background color of blue for the whole LampArray.
00218             lampArray.SetColor(Colors.Blue);
00219
00220             // Highlight the WASD keys in white, if the LampArray supports addressing its Lamps using a virtual key to Lamp mapping.
00221             // This is typically found on keyboard LampArrays. Other LampArrays will not usually support virtual key based lighting.
00222             if (lampArray.SupportsVirtualKeys)
00223             {
00224                 Color[] colors = Enumerable.Repeat(Colors.White, 4).ToArray();
00225                 VirtualKey[] virtualKeys = { VirtualKey.W, VirtualKey.A, VirtualKey.S, VirtualKey.D };
00226
00227                 lampArray.SetColorsForKeys(colors, virtualKeys);
00228             }
00229         }
00230     }
00231 }
Generated on Fri Nov 15 2024 22:20:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/StspSchemeHandler.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

StspSchemeHandler.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 namespace Microsoft { namespace Samples { namespace SimpleCommunication {
00011
00012 class CSchemeHandler
00013     : public Microsoft::WRL::RuntimeClass<
00014            Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >,
00015            ABI::Windows::Media::IMediaExtension,
00016            IMFSchemeHandler >
00017 {
00018     InspectableClass(L"Microsoft.Samples.SimpleCommunication.StspSchemeHandler",BaseTrust)
00019
00020 public:
00021     CSchemeHandler(void);
00022     ~CSchemeHandler(void);
00023
00024     // IMediaExtension
00025     IFACEMETHOD (SetProperties) (ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration);
00026
00027     // IMFSchemeHandler
00028     IFACEMETHOD (BeginCreateObject) (
00029             _In_ LPCWSTR pwszURL,
00030             _In_ DWORD dwFlags,
00031             _In_ IPropertyStore *pProps,
00032             _COM_Outptr_opt_  IUnknown **ppIUnknownCancelCookie,
00033             _In_ IMFAsyncCallback *pCallback,
00034             _In_ IUnknown *punkState);
00035
00036     IFACEMETHOD (EndCreateObject) (
00037             _In_ IMFAsyncResult *pResult,
00038             _Out_  MF_OBJECT_TYPE *pObjectType,
00039             _Out_  IUnknown **ppObject);
00040
00041     IFACEMETHOD (CancelObjectCreation) (
00042             _In_ IUnknown *pIUnknownCancelCookie);
00043 };
00044
00045 }}} // namespace Microsoft::Samples::SimpleCommunication
Generated on Fri Nov 15 2024 22:21:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/Scenario_ContinuousRecognitionSRGSGrammar.xaml.cpp Source File

  • SpeechRecognitionAndSynthesis
  • cpp

Scenario_ContinuousRecognitionSRGSGrammar.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario_ContinuousRecognitionSRGSGrammar.xaml.h"
00014 #include "AudioCapturePermissions.h"
00015
00016 using namespace SDKTemplate;
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::ApplicationModel;
00021 using namespace Windows::ApplicationModel::Resources::Core;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::Media::SpeechRecognition;
00025 using namespace Windows::Storage;
00026 using namespace Windows::UI;
00027 using namespace Windows::UI::Core;
00028 using namespace Windows::UI::Xaml;
00029 using namespace Windows::UI::Xaml::Controls;
00030 using namespace Windows::UI::Xaml::Controls::Primitives;
00031 using namespace Windows::UI::Xaml::Data;
00032 using namespace Windows::UI::Xaml::Input;
00033 using namespace Windows::UI::Xaml::Media;
00034 using namespace Windows::UI::Xaml::Navigation;
00035
00036 Scenario_ContinuousRecognitionSRGSGrammar::Scenario_ContinuousRecognitionSRGSGrammar() : rootPage(MainPage::Current)
00037 {
00038     InitializeComponent();
00039
00040     colorLookup = ref new Map<String^, Color>(
00041     {
00042         { "COLOR_RED",   Colors::Red },    { "COLOR_BLUE",  Colors::Blue },   { "COLOR_BLACK",  Colors::Black },
00043         { "COLOR_BROWN", Colors::Brown },  { "COLOR_PURPLE",Colors::Purple }, { "COLOR_GREEN",  Colors::Green },
00044         { "COLOR_YELLOW",Colors::Yellow }, { "COLOR_CYAN",  Colors::Cyan },   { "COLOR_MAGENTA",Colors::Magenta },
00045         { "COLOR_ORANGE",Colors::Orange }, { "COLOR_GRAY",  Colors::Gray },   { "COLOR_WHITE",  Colors::White }
00046     });
00047 }
00048
00049 /// <summary>
00050 /// Upon entering the scenario, ensure that we have permissions to use the Microphone. This may entail popping up
00051 /// a dialog to the user on Desktop systems. Only enable functionality once we've gained that permission in order to
00052 /// prevent errors from occurring when using the SpeechRecognizer. If speech is not a primary input mechanism, developers
00053 /// should consider disabling appropriate parts of the UI if the user does not have a recording device, or does not allow
00054 /// audio input.
00055 /// </summary>
00056 /// <param name="e">Unused navigation parameters</param>
00057 void Scenario_ContinuousRecognitionSRGSGrammar::OnNavigatedTo(NavigationEventArgs^ e)
00058 {
00059     Page::OnNavigatedTo(e);
00060
00061     // Save the UI thread dispatcher to allow speech status messages to be shown on the UI.
00062     dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
00063
00064     create_task(AudioCapturePermissions::RequestMicrophonePermissionAsync(), task_continuation_context::use_current())
00065         .then([this](bool permissionGained)
00066     {
00067         if (permissionGained)
00068         {
00069             // Enable the recognition buttons.
00070             this->btnContinuousRecognize->IsEnabled = true;
00071
00072       Windows::Globalization::Language^ speechLanguage = SpeechRecognizer::SystemSpeechLanguage;
00073       speechContext = ResourceContext::GetForCurrentView();
00074       speechContext->Languages = ref new VectorView<String^>(1, speechLanguage->LanguageTag);
00075
00076       speechResourceMap = ResourceManager::Current->MainResourceMap->GetSubtree(L"LocalizationSpeechResources");
00077
00078       PopulateLanguageDropdown();
00079       InitializeRecognizer(SpeechRecognizer::SystemSpeechLanguage);
00080         }
00081         else
00082         {
00083             this->resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00084             this->resultTextBlock->Text = L"Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
00085       this->cbLanguageSelection->IsEnabled = false;
00086         }
00087     });
00088 }
00089
00090 /// <summary>
00091 /// Creates a SpeechRecognizer instance and initializes the grammar.
00092 /// </summary>
00093 void Scenario_ContinuousRecognitionSRGSGrammar::InitializeRecognizer(Windows::Globalization::Language^ recognizerLanguage)
00094 {
00095     // If reinitializing the recognizer (ie, changing the speech language), clean up the old recognizer first.
00096     // Avoid doing this while the recognizer is active by disabling the ability to change languages while listening.
00097     if (this->speechRecognizer != nullptr)
00098     {
00099         speechRecognizer->StateChanged -= stateChangedToken;
00100         speechRecognizer->ContinuousRecognitionSession->Completed -= continuousRecognitionCompletedToken;
00101         speechRecognizer->ContinuousRecognitionSession->ResultGenerated -= continuousRecognitionResultGeneratedToken;
00102
00103         delete this->speechRecognizer;
00104         this->speechRecognizer = nullptr;
00105     }
00106
00107     try
00108     {
00109         // Initialize the SpeechRecognizer and add the grammar.
00110         this->speechRecognizer = ref new SpeechRecognizer(recognizerLanguage);
00111
00112         // Provide feedback to the user about the state of the recognizer. This can be used to provide
00113         // visual feedback to help the user understand whether they're being heard.
00114         stateChangedToken = speechRecognizer->StateChanged +=
00115             ref new TypedEventHandler<
00116             SpeechRecognizer ^,
00117             SpeechRecognizerStateChangedEventArgs ^>(
00118                 this,
00119                 &Scenario_ContinuousRecognitionSRGSGrammar::SpeechRecognizer_StateChanged);
00120
00121         // Initialize the SRGS-compliant XML file.
00122         // For more information about grammars for Windows apps and how to
00123         // define and use SRGS-compliant grammars in your app, see
00124         // https://msdn.microsoft.com/en-us/library/dn596121.aspx
00125         String^ fileName = L"SRGS\\" + recognizerLanguage->LanguageTag + L"\\SRGSColors.xml";
00126         resultTextBlock->Text = speechResourceMap->GetValue("SRGSHelpText", speechContext)->ValueAsString;
00127
00128         create_task(Package::Current->InstalledLocation->GetFileAsync(fileName), task_continuation_context::use_current())
00129             .then([this](task<StorageFile^> getFileTask)
00130         {
00131             StorageFile^ grammarContentFile = getFileTask.get();
00132             SpeechRecognitionGrammarFileConstraint^ grammarConstraint = ref new SpeechRecognitionGrammarFileConstraint(grammarContentFile);
00133             speechRecognizer->Constraints->Append(grammarConstraint);
00134
00135             return create_task(speechRecognizer->CompileConstraintsAsync(), task_continuation_context::use_current());
00136
00137         }).then([this](task<SpeechRecognitionCompilationResult^> previousTask)
00138         {
00139             SpeechRecognitionCompilationResult^ compilationResult = previousTask.get();
00140
00141             // Check to make sure that the constraints were in a proper format and the recognizer was able to compile them.
00142             if (compilationResult->Status != SpeechRecognitionResultStatus::Success)
00143             {
00144                 // Disable the recognition button.
00145                 btnContinuousRecognize->IsEnabled = false;
00146
00147                 // Let the user know that the grammar didn't compile properly.
00148                 rootPage->NotifyUser("Grammar Compilation Failed: " + compilationResult->Status.ToString(), NotifyType::ErrorMessage);
00149             }
00150             else
00151             {
00152                 btnContinuousRecognize->IsEnabled = true;
00153
00154                 resultTextBlock->Text = speechResourceMap->GetValue("SRGSHelpText", speechContext)->ValueAsString;
00155                 resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00156
00157                 // Set EndSilenceTimeout to give users more time to complete speaking a phrase.
00158                 TimeSpan endSilenceTime;
00159                 endSilenceTime.Duration = 12000000L;
00160                 speechRecognizer->Timeouts->EndSilenceTimeout = endSilenceTime; // (1.2 seconds in nanoseconds)
00161
00162
00163                                                                                 // Handle continuous recognition events. Completed fires when various error states occur. ResultGenerated fires when
00164                                                                                 // some recognized phrases occur, or the garbage rule is hit.
00165                 continuousRecognitionCompletedToken = speechRecognizer->ContinuousRecognitionSession->Completed +=
00166                     ref new TypedEventHandler<
00167                     SpeechContinuousRecognitionSession ^,
00168                     SpeechContinuousRecognitionCompletedEventArgs ^>(
00169                         this,
00170                         &Scenario_ContinuousRecognitionSRGSGrammar::ContinuousRecognitionSession_Completed);
00171                 continuousRecognitionResultGeneratedToken = speechRecognizer->ContinuousRecognitionSession->ResultGenerated +=
00172                     ref new TypedEventHandler<
00173                     SpeechContinuousRecognitionSession ^,
00174                     SpeechContinuousRecognitionResultGeneratedEventArgs ^>(
00175                         this,
00176                         &Scenario_ContinuousRecognitionSRGSGrammar::ContinuousRecognitionSession_ResultGenerated);
00177             }
00178         }, task_continuation_context::use_current());
00179
00180
00181     }
00182     catch (Platform::Exception^ ex)
00183     {
00184         if ((unsigned int)ex->HResult == HResultRecognizerNotFound)
00185         {
00186             btnContinuousRecognize->IsEnabled = false;
00187
00188             resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00189             resultTextBlock->Text = L"Speech Language pack for selected language not installed.";
00190         }
00191         else
00192         {
00193             auto messageDialog = ref new Windows::UI::Popups::MessageDialog(ex->Message, "Exception");
00194             create_task(messageDialog->ShowAsync());
00195         }
00196     }
00197 }
00198
00199 /// <summary>
00200 /// Upon leaving, clean up the speech recognizer. Ensure we aren't still listening, and disable the event
00201 /// handlers to prevent leaks.
00202 /// </summary>
00203 /// <param name="e">Unused navigation parameters.</param>
00204 void Scenario_ContinuousRecognitionSRGSGrammar::OnNavigatedFrom(NavigationEventArgs^ e)
00205 {
00206     Page::OnNavigatedFrom(e);
00207
00208     if (speechRecognizer != nullptr)
00209     {
00210         // If we're currently active, start a cancellation task, and wait for it to finish before shutting down
00211         // the recognizer.
00212         Concurrency::task<void> cleanupTask;
00213         if (speechRecognizer->State != SpeechRecognizerState::Idle)
00214         {
00215             cleanupTask = create_task(speechRecognizer->ContinuousRecognitionSession->CancelAsync(), task_continuation_context::use_current());
00216         }
00217         else
00218         {
00219             cleanupTask = create_task([]() {}, task_continuation_context::use_current());
00220         }
00221
00222         cleanupTask.then([this]()
00223         {
00224             ContinuousRecoButtonText->Text = L" Continuous Recognition";
00225
00226             speechRecognizer->StateChanged -= stateChangedToken;
00227             speechRecognizer->ContinuousRecognitionSession->Completed -= continuousRecognitionCompletedToken;
00228             speechRecognizer->ContinuousRecognitionSession->ResultGenerated -= continuousRecognitionResultGeneratedToken;
00229
00230             delete speechRecognizer;
00231             speechRecognizer = nullptr;
00232         }, task_continuation_context::use_current());
00233     }
00234 }
00235
00236 /// <summary>
00237 /// Begin recognition or finish the recognition session.
00238 /// </summary>
00239 /// <param name="sender">The button that generated this event</param>
00240 /// <param name="e">Unused event details</param>
00241 void Scenario_ContinuousRecognitionSRGSGrammar::ContinuousRecognize_Click(Object^ sender, RoutedEventArgs^ e)
00242 {
00243   btnContinuousRecognize->IsEnabled = false;
00244     // The recognizer can only start listening in a continuous fashion if the recognizer is currently idle.
00245     // This prevents an exception from occurring.
00246     if (speechRecognizer->State == SpeechRecognizerState::Idle)
00247     {
00248         // Reset the text to prompt the user.
00249         ContinuousRecoButtonText->Text = L" Stop Continuous Recognition";
00250         resultTextBlock->Text = speechResourceMap->GetValue("SRGSHelpText", speechContext)->ValueAsString;
00251         cbLanguageSelection->IsEnabled = false;
00252
00253         create_task(speechRecognizer->ContinuousRecognitionSession->StartAsync(), task_continuation_context::use_current())
00254             .then([this](task<void> startAsyncTask)
00255         {
00256             try
00257             {
00258                 // Retreive any exceptions that may have been generated by StartAsync.
00259                 startAsyncTask.get();
00260             }
00261             catch (Exception^ exception)
00262             {
00263                 ContinuousRecoButtonText->Text = L" Continuous Recognition";
00264                 cbLanguageSelection->IsEnabled = true;
00265                 resultTextBlock->Text = speechResourceMap->GetValue("SRGSHelpText", speechContext)->ValueAsString;
00266
00267                 auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00268                 create_task(messageDialog->ShowAsync());
00269             }
00270     }).then([this]() {
00271       btnContinuousRecognize->IsEnabled = true;
00272     });
00273     }
00274     else
00275     {
00276         // Reset the text to prompt the user.
00277         ContinuousRecoButtonText->Text = L" Continuous Recognition";
00278         resultTextBlock->Text = speechResourceMap->GetValue("SRGSHelpText", speechContext)->ValueAsString;
00279         cbLanguageSelection->IsEnabled = true;
00280
00281         // Cancelling recognition prevents any currently recognized speech from
00282         // generating a ResultGenerated event. StopAsync() will allow the final session to
00283         // complete
00284         create_task(speechRecognizer->ContinuousRecognitionSession->CancelAsync()).then([this]() {
00285       btnContinuousRecognize->IsEnabled = true;
00286     });
00287     }
00288 }
00289
00290 /// <summary>
00291 /// Provide feedback to the user based on whether the recognizer is receiving their voice input.
00292 /// </summary>
00293 /// <param name="sender">The recognizer that is currently running.</param>
00294 /// <param name="args">The current state of the recognizer.</param>
00295 void Scenario_ContinuousRecognitionSRGSGrammar::SpeechRecognizer_StateChanged(SpeechRecognizer ^sender, SpeechRecognizerStateChangedEventArgs ^args)
00296 {
00297     dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00298     {
00299         rootPage->NotifyUser("Speech recognizer state: " + args->State.ToString(), NotifyType::StatusMessage);
00300     }));
00301
00302 }
00303
00304 /// <summary>
00305 /// Handle events fired when the session ends, either from a call to
00306 /// CancelAsync() or StopAsync(), or an error condition, such as the
00307 /// microphone becoming unavailable or some transient issues occuring.
00308 /// </summary>
00309 /// <param name="sender">The continuous recognition session</param>
00310 /// <param name="args">The state of the recognizer</param>
00311 void Scenario_ContinuousRecognitionSRGSGrammar::ContinuousRecognitionSession_Completed(SpeechContinuousRecognitionSession ^sender, SpeechContinuousRecognitionCompletedEventArgs ^args)
00312 {
00313     if (args->Status != SpeechRecognitionResultStatus::Success)
00314     {
00315         dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00316         {
00317             rootPage->NotifyUser("Continuous Recognition Completed: " + args->Status.ToString(), NotifyType::ErrorMessage);
00318             ContinuousRecoButtonText->Text = " Continuous Recognition";
00319         }));
00320     }
00321 }
00322
00323 /// <summary>
00324 /// Handle events fired when a result is generated. This may include a garbage rule that fires when general room noise
00325 /// or side-talk is captured (this will have a confidence of Rejected typically, but may occasionally match a rule with
00326 /// low confidence).
00327 /// </summary>
00328 /// <param name="sender">The Recognition session that generated this result</param>
00329 /// <param name="args">Details about the recognized speech</param>
00330 void Scenario_ContinuousRecognitionSRGSGrammar::ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession ^sender, SpeechContinuousRecognitionResultGeneratedEventArgs ^args)
00331 {
00332     dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00333     {
00334         HandleRecognitionResult(args->Result);
00335     }));
00336 }
00337
00338
00339 /// <summary>
00340 /// Uses the result from the speech recognizer to change the colors of the shapes.
00341 /// </summary>
00342 /// <param name="recoResult">The result from the recognition event</param>
00343 void Scenario_ContinuousRecognitionSRGSGrammar::HandleRecognitionResult(SpeechRecognitionResult^ recoResult)
00344 {
00345     if (recoResult->Confidence == SpeechRecognitionConfidence::High ||
00346         recoResult->Confidence == SpeechRecognitionConfidence::Medium)
00347     {
00348         String^ garbagePrompt = "";
00349
00350
00351         // BACKGROUND: Check to see if the recognition result contains the semantic key for the background color,
00352         // and not a match for the GARBAGE rule, and change the color.
00353         if (recoResult->SemanticInterpretation->Properties->HasKey("KEY_BACKGROUND") && recoResult->SemanticInterpretation->Properties->Lookup("KEY_BACKGROUND")->GetAt(0) != "...")
00354         {
00355             String^ backgroundColor = recoResult->SemanticInterpretation->Properties->Lookup("KEY_BACKGROUND")->GetAt(0);
00356             colorRectangle->Fill = ref new SolidColorBrush(getColor(backgroundColor));
00357         }
00358
00359         // If "background" was matched, but the color rule matched GARBAGE, prompt the user.
00360         else if (recoResult->SemanticInterpretation->Properties->HasKey("KEY_BACKGROUND") && recoResult->SemanticInterpretation->Properties->Lookup("KEY_BACKGROUND")->GetAt(0) == "...")
00361         {
00362             garbagePrompt += speechResourceMap->GetValue("SRGSBackgroundGarbagePromptText", speechContext)->ValueAsString;
00363             resultTextBlock->Text = garbagePrompt;
00364         }
00365
00366         // BORDER: Check to see if the recognition result contains the semantic key for the border color,
00367         // and not a match for the GARBAGE rule, and change the color.
00368         if (recoResult->SemanticInterpretation->Properties->HasKey("KEY_BORDER") && recoResult->SemanticInterpretation->Properties->Lookup("KEY_BORDER")->GetAt(0) != "...")
00369         {
00370             String^ borderColor = recoResult->SemanticInterpretation->Properties->Lookup("KEY_BORDER")->GetAt(0);
00371             colorRectangle->Stroke = ref new SolidColorBrush(getColor(borderColor));
00372         }
00373
00374         // If "border" was matched, but the color rule matched GARBAGE, prompt the user.
00375         else if (recoResult->SemanticInterpretation->Properties->HasKey("KEY_BORDER") && recoResult->SemanticInterpretation->Properties->Lookup("KEY_BORDER")->GetAt(0) == "...")
00376         {
00377             garbagePrompt += speechResourceMap->GetValue("SRGSBorderGarbagePromptText", speechContext)->ValueAsString;
00378             resultTextBlock->Text = garbagePrompt;
00379         }
00380
00381         // CIRCLE: Check to see if the recognition result contains the semantic key for the circle color,
00382         // and not a match for the GARBAGE rule, and change the color.
00383         if (recoResult->SemanticInterpretation->Properties->HasKey("KEY_CIRCLE") && recoResult->SemanticInterpretation->Properties->Lookup("KEY_CIRCLE")->GetAt(0) != "...")
00384         {
00385             String^ circleColor = recoResult->SemanticInterpretation->Properties->Lookup("KEY_CIRCLE")->GetAt(0);
00386             colorCircle->Fill = ref new SolidColorBrush(getColor(circleColor));
00387         }
00388
00389         // If "circle" was matched, but the color rule matched GARBAGE, prompt the user.
00390         else if (recoResult->SemanticInterpretation->Properties->HasKey("KEY_CIRCLE") && recoResult->SemanticInterpretation->Properties->Lookup("KEY_CIRCLE")->GetAt(0) == "...")
00391         {
00392             garbagePrompt += speechResourceMap->GetValue("SRGSCircleGarbagePromptText", speechContext)->ValueAsString;
00393             resultTextBlock->Text = garbagePrompt;
00394         }
00395
00396         // Initialize a string that will describe the user's color choices.
00397         String^ textBoxColors = "You selected (Semantic Properties) -> \n";
00398
00399         std::for_each(begin(recoResult->SemanticInterpretation->Properties),
00400             end(recoResult->SemanticInterpretation->Properties),
00401             [&](IKeyValuePair<String^, IVectorView<String^>^>^ child)
00402         {
00403             // Check to see if any of the semantic values in recognition result contains a match for the GARBAGE rule.
00404             if (!child->Value->Equals("..."))
00405             {
00406                 textBoxColors += child->Value->GetAt(0) + " ";
00407                 if (child->Key != nullptr)
00408                 {
00409                     textBoxColors += child->Key;
00410                 }
00411                 else
00412                 {
00413                     textBoxColors += "null";
00414                 }
00415                 textBoxColors += "\n";
00416
00417                 resultTextBlock->Text = textBoxColors;
00418             }
00419
00420             // If there was no match to the colors rule or if it matched GARBAGE, prompt the user.
00421             else
00422             {
00423                 resultTextBlock->Text = garbagePrompt;
00424             }
00425         });
00426     }
00427     else
00428     {
00429         resultTextBlock->Text = speechResourceMap->GetValue("SRGSGarbagePromptText", speechContext)->ValueAsString;
00430     }
00431 }
00432
00433
00434 /// <summary>
00435 /// Creates a color object from the passed in string.
00436 /// </summary>
00437 /// <param name="colorString">The name of the color</param>
00438 Windows::UI::Color Scenario_ContinuousRecognitionSRGSGrammar::getColor(Platform::String^ colorString)
00439 {
00440     Color newColor = Colors::Transparent;
00441
00442     if (colorLookup->HasKey(colorString))
00443     {
00444         newColor = colorLookup->Lookup(colorString);
00445     }
00446
00447     return newColor;
00448 }
00449
00450
00451 /// <summary>
00452 /// Populate language dropdown with supported Dictation languages.
00453 /// </summary>
00454 void Scenario_ContinuousRecognitionSRGSGrammar::PopulateLanguageDropdown()
00455 {
00456     // disable callback temporarily.
00457     isPopulatingLanguages = true;
00458
00459     Windows::Globalization::Language^ defaultLanguage = SpeechRecognizer::SystemSpeechLanguage;
00460     auto supportedLanguages = SpeechRecognizer::SupportedGrammarLanguages;
00461     std::for_each(begin(supportedLanguages), end(supportedLanguages), [&](Windows::Globalization::Language^ lang)
00462     {
00463         ComboBoxItem^ item = ref new ComboBoxItem();
00464         item->Tag = lang;
00465         item->Content = lang->DisplayName;
00466
00467         cbLanguageSelection->Items->Append(item);
00468         if (lang->LanguageTag == defaultLanguage->LanguageTag)
00469         {
00470             item->IsSelected = true;
00471             cbLanguageSelection->SelectedItem = item;
00472         }
00473     });
00474
00475     isPopulatingLanguages = false;
00476 }
00477
00478 /// <summary>
00479 /// Re-initialize the recognizer based on selections from the language combobox.
00480 /// </summary>
00481 void Scenario_ContinuousRecognitionSRGSGrammar::cbLanguageSelection_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00482 {
00483     if (isPopulatingLanguages)
00484     {
00485         return;
00486     }
00487
00488     ComboBoxItem^ item = (ComboBoxItem^)(cbLanguageSelection->SelectedItem);
00489     Windows::Globalization::Language^ newLanguage = (Windows::Globalization::Language^)item->Tag;
00490
00491     if (this->speechRecognizer != nullptr)
00492     {
00493         if (speechRecognizer->CurrentLanguage == newLanguage)
00494         {
00495             return;
00496         }
00497     }
00498
00499     try
00500     {
00501         speechContext->Languages = ref new VectorView<String^>(1, newLanguage->LanguageTag);
00502
00503         InitializeRecognizer(newLanguage);
00504     }
00505     catch (Exception^ exception)
00506     {
00507         auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00508         create_task(messageDialog->ShowAsync());
00509     }
00510
00511 }
Generated on Fri Nov 15 2024 22:21:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HistoryRecord Member List

This is the complete list of members for HistoryRecord, including all inherited members.
HistoryRecord(PedometerReading reading) | HistoryRecord | [inline]
recordTimestamp | HistoryRecord | [private]
StepKind | HistoryRecord |
stepKind | HistoryRecord | [private]
StepsCount | HistoryRecord |
stepsCount | HistoryRecord | [private]
stepsDuration | HistoryRecord | [private]
StepsDuration | HistoryRecord |
TimeStamp | HistoryRecord |
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DPhotoAdjustment/cpp/Common/DirectXHelper.h Source File

  • D2DPhotoAdjustment
  • cpp
  • Common

DirectXHelper.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <ppltasks.h>
00015
00016 namespace DX
00017 {
00018     inline void ThrowIfFailed(HRESULT hr)
00019     {
00020         if (FAILED(hr))
00021         {
00022             // Set a breakpoint on this line to catch Win32 API errors.
00023             throw Platform::Exception::CreateException(hr);
00024         }
00025     }
00026
00027     // Function that reads from a binary file asynchronously.
00028     inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename)
00029     {
00030         using namespace Windows::Storage;
00031         using namespace Concurrency;
00032
00033         auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
00034
00035         return create_task(folder->GetFileAsync(Platform::StringReference(filename.c_str()))).then([] (StorageFile^ file)
00036         {
00037             return FileIO::ReadBufferAsync(file);
00038         }).then([] (Streams::IBuffer^ fileBuffer) -> std::vector<byte>
00039         {
00040             std::vector<byte> returnBuffer;
00041             returnBuffer.resize(fileBuffer->Length);
00042             Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), fileBuffer->Length));
00043             return returnBuffer;
00044         });
00045     }
00046
00047     // Converts a length in device-independent pixels (DIPs) to a length in physical pixels.
00048     inline float ConvertDipsToPixels(float dips, float dpi)
00049     {
00050         static const float dipsPerInch = 96.0f;
00051         return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00052     }
00053
00054     // Converts a length in physical pixels to a length in device-independent pixels (DIPs).
00055     inline float ConvertPixelsToDips(float pixels)
00056     {
00057         static const float dipsPerInch = 96.0f;
00058         return pixels * dipsPerInch / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->LogicalDpi; // Do not round.
00059     }
00060
00061     // Converts a length in physical pixels to a length in device-independent pixels (DIPs) using the provided DPI. This removes the need
00062     // to call this function from a thread associated with a CoreWindow, which is required by DisplayInformation::GetForCurrentView().
00063     inline float ConvertPixelsToDips(float pixels, float dpi)
00064     {
00065         static const float dipsPerInch = 96.0f;
00066         return pixels * dipsPerInch / dpi; // Do not round.
00067     }
00068
00069 #if defined(_DEBUG)
00070     // Check for SDK Layer support.
00071     inline bool SdkLayersAvailable()
00072     {
00073         HRESULT hr = D3D11CreateDevice(
00074             nullptr,
00075             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00076             0,
00077             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00078             nullptr,                    // Any feature level will do.
00079             0,
00080             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00081             nullptr,                    // No need to keep the D3D device reference.
00082             nullptr,                    // No need to know the feature level.
00083             nullptr                     // No need to keep the D3D device context reference.
00084             );
00085
00086         return SUCCEEDED(hr);
00087     }
00088 #endif
00089 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LiveDash/cs/LiveDash/LiveSourceBufferManager.cs Source File

  • LiveDash
  • cs
  • LiveDash

LiveSourceBufferManager.cs

Go to the documentation of this file.
00001 ﻿using LiveDash.Models;
00002 using LiveDash.Util;
00003 using System;
00004 using System.Collections.Generic;
00005 using System.Linq;
00006 using System.Threading.Tasks;
00007 using Windows.Web.Http;
00008
00009 namespace LiveDash
00010 {
00011     /// <summary>
00012     /// This class extends a source buffer manager but handles cases for
00013     /// live playback such as setting a live offset and the logic
00014     /// to pick the next segment to play
00015     /// </summary>
00016     class LiveSourceBufferManager : SourceBufferManager
00017     {
00018         private bool determinedStartingSegmentIndex = false;
00019         private int nextSegmentIndex = 0;
00020         private Manifest manifest;
00021         private ulong hnsDesiredLiveOffset = 300000000;
00022
00023         private ulong nextSegmentNumber;
00024         private int totalSegmentCount;
00025
00026         internal LiveSourceBufferManager(string mimeType, MediaStream stream) : base(mimeType, stream)
00027         {
00028             isFirstSegment = true;
00029         }
00030
00031         #region properties
00032
00033         internal Manifest Manifest
00034         {
00035             get { return manifest; }
00036             set { manifest = value; }
00037         }
00038
00039         internal int NextSegmentIndex
00040         {
00041             get { return nextSegmentIndex; }
00042             set { nextSegmentIndex = value; }
00043         }
00044
00045         internal ulong NextSegmentNumber
00046         {
00047             get { return nextSegmentNumber; }
00048             set { nextSegmentNumber = value; }
00049         }
00050
00051         public ulong DesiredLiveOffset
00052         {
00053             get { return hnsDesiredLiveOffset; }
00054
00055             set { hnsDesiredLiveOffset = value; }
00056         }
00057         #endregion
00058
00059         internal override void UpdateData(TimeSpan now)
00060         {
00061             if (sb != null)
00062             {
00063                 SendInitSegment(now);
00064                 CleanBuffer(now);
00065                 SendMediaSegment(now);
00066             }
00067
00068         }
00069
00070         protected override async void SendMediaSegment(TimeSpan now)
00071         {
00072             try
00073             {
00074                 var end = now;
00075
00076                 if (!isInitialized || Appending || isEndOfStream)
00077                 {
00078                     return;
00079                 }
00080
00081                 //if the next segment is out of range from the manifest, then
00082                 //try to redownload the manifest and pick up where we left off.
00083                 //this is the case where a manifest reload didn't come in time,
00084                 //we don't have a mediaPresentationDuration present, and we cannot generate
00085                 //segments dynamically.the new manifest does not contain the segment,
00086                 //then it is the end of stream.
00087                 if (manifest.HasPresentationDuration && nextSegmentIndex > totalSegmentCount)
00088                 {
00089                     //nextSegmentIndex = await GetNewSegmentIndexFromNewStream();
00090
00091                     //if (nextSegmentIndex == -1)
00092                     //{
00093                         isEndOfStream = true;
00094                         return;
00095                     //}
00096                 }
00097
00098                 foreach (var range in sb.Buffered)
00099                 {
00100                     if (range.Start <= end + MaxGap && range.End > end)
00101                     {
00102                         end = range.End;
00103                     }
00104                     else if (range.Start > end)
00105                     {
00106                         break;
00107                     }
00108                 }
00109
00110                 var stream = base.stream;
00111
00112                 MediaSegment segment = GetNextSegment();
00113
00114                 if (now + MaxBuffering <= end)
00115                 {
00116                     return;
00117                 }
00118
00119                 string url = segment.SegmentUrl;
00120                 internalAppending = true;
00121 #if DEBUG
00122                 Logger.Log("Loading segment url " + url);
00123 #endif
00124                 Uri mediaSegmentUrl = null;
00125                 try
00126                 {
00127                     mediaSegmentUrl = new Uri(url);
00128                 }
00129                 catch (Exception e)
00130                 {
00131 #if DEBUG
00132                     Logger.Log("malformed media segment: " + url + Logger.Display(e));
00133 #endif
00134                 }
00135
00136                 bool firstDownloadSucceded = await TryDownloadBuffer(mediaSegmentUrl);
00137                 if (firstDownloadSucceded && isFirstSegment)
00138                 {
00139                     var bufferedRange = sb.Buffered;
00140
00141                     TimeSpan startingTimestamp = bufferedRange.First().Start;
00142                     TimeSpan endingTimestamp = bufferedRange.Last().End;
00143
00144                     if (sb.Buffered.Count != 0)
00145                     {
00146                         sb.Remove(TimeSpan.Zero, endingTimestamp);
00147 #if DEBUG
00148                         Logger.Log("Removing buffered Range from 0 to " + endingTimestamp);
00149 #endif
00150                     }
00151                     sb.TimestampOffset = -startingTimestamp;
00152 #if DEBUG
00153                     Logger.Log("Setting Timestamp to " + sb.TimestampOffset);
00154 #endif
00155
00156                     sb.AppendBuffer(activeDownload.Result);
00157                     isFirstSegment = false;
00158                 }
00159                 else if (!firstDownloadSucceded)
00160                 {
00161                     bool searchSucceeded = await SearchForSegment();
00162                     if (!searchSucceeded)
00163                     {
00164 #if DEBUG
00165                         Logger.Log("Calling end of stream");
00166 #endif
00167                         // Failed - should send EndOfStream
00168                         sb.Abort();
00169                         isEndOfStream = true;
00170
00171                     }
00172
00173                 }
00174             }
00175             catch (Exception e)
00176             {
00177 #if DEBUG
00178                 Logger.Log("Error when sending media segment: " + e.Message);
00179 #endif
00180             }
00181
00182         }
00183
00184         internal void HandleManifestReload()
00185         {
00186             if (!stream.CanGenerateSegmentsDynamically)
00187             {
00188                 for (int x = 0; x < stream.Segments.Count(); x++)
00189                 {
00190                     if (stream.Segments.ElementAt(x).Number == nextSegmentNumber)
00191                     {
00192                         nextSegmentIndex = x;
00193                         return;
00194                     }
00195                 }
00196                 determinedStartingSegmentIndex = false;
00197                 DetermineStartingSegmentIndex();
00198             }
00199         }
00200
00201         internal MediaSegment GetNextSegment()
00202         {
00203             DetermineStartingSegmentIndex();
00204             bool isEndOfStream = false;
00205             if (manifest.HasPresentationDuration)
00206             {
00207                 if (isFirstSegment)
00208                 {
00209                     var segmentInfo = stream.SegmentInformation;
00210                     var presentationDuration = (ulong)manifest.MediaPresentationDuration.TotalMilliseconds * segmentInfo.Timescale / 1000;
00211
00212                     var segmentDuration = segmentInfo.Duration;
00213
00214                     totalSegmentCount = (int)presentationDuration / (int)segmentDuration;
00215                 }
00216             }
00217
00218             MediaSegment segment;
00219             if (stream.CanGenerateSegmentsDynamically && !isEndOfStream)
00220             {
00221                 //create new segment based on media segment info given
00222                 segment = new MediaSegment();
00223                 var segmentInfo = stream.SegmentInformation;
00224
00225                 var format = segmentInfo.UrlTemplate;
00226                 var bitrate = segmentInfo.Bitrate;
00227                 var repID = segmentInfo.RepresentationID;
00228                 var number = segmentInfo.StartNumber + (ulong)nextSegmentIndex;
00229                 var time = segmentInfo.StartTimestamp + (ulong)nextSegmentIndex;
00230
00231                 string mediaUrl;
00232                 DashManifestParser.ExpandDASHUrlSegmentTemplate(format, manifest.BaseUrl, bitrate, repID, number, time, out mediaUrl);
00233
00234                 segment.Duration = segmentInfo.Duration;
00235                 segment.Number = number;
00236                 segment.Timestamp = time;
00237                 segment.SegmentUrl = mediaUrl;
00238
00239             }
00240             else //populated by a list of segments
00241             {
00242                 segment = stream.Segments.ElementAt(nextSegmentIndex);
00243             }
00244             nextSegmentNumber = segment.Number + 1;
00245
00246             return segment;
00247         }
00248
00249         private async Task<bool> ReloadManifest()
00250         {
00251             try
00252             {
00253                 //Redownload manifest to pick up where it left off
00254                 var mpdUrl = manifest.SourceUrl;
00255                 manifest = new Manifest(mpdUrl);
00256                 var document = await manifest.LoadManifestAsync(mpdUrl);
00257
00258                 DashManifestParser mpdParser = new DashManifestParser(document, ref manifest);
00259
00260                 return mpdParser.Parse();
00261             }
00262             catch (Exception e)
00263             {
00264 #if DEBUG
00265                 Logger.Log("Error reloading manifest in the Live Source Buffer: " + e.Message);
00266 #endif
00267                 return false;
00268             }
00269         }
00270
00271         private async Task<int> GetNewSegmentIndexFromNewStream()
00272         {
00273             //Get latest segment info and find out the next segment number
00274             if (!stream.CanGenerateSegmentsDynamically)
00275             {
00276                 var nextSegmentnumber = stream.Segments.Last().Number + 1;
00277
00278                 bool reloadAndParseSucceded = await ReloadManifest();
00279
00280                 if (reloadAndParseSucceded)
00281                 {
00282
00283                     Period selectedPeriod = manifest.GetSelectedPeriod();
00284                     //CMediaStream newStream = null;
00285                     if (IsVideo)
00286                     {
00287                         stream = selectedPeriod.GetVideoStream();
00288                     }
00289                     else if (IsAudio)
00290                     {
00291                         stream = selectedPeriod.GetAudioStream();
00292                     }
00293                     else
00294                     {
00295                         //Is not an audio or video stream...return -1
00296                         return -1;
00297                     }
00298                     for (int i = stream.Segments.Count() - 1; i >= 0; i--)
00299                     {
00300                         if (stream.Segments.ElementAt(i).Number == nextSegmentnumber)
00301                         {
00302                             return i;
00303                         }
00304                     }
00305                 }
00306             }
00307             //The segment where we left off at is not on the server
00308             return -1;
00309         }
00310
00311         private async Task<bool> SearchForSegment()
00312         {
00313             try
00314             {
00315
00316                 if (stream.CanGenerateSegmentsDynamically)
00317                 {
00318                     //Does not search for now.
00319                     return false;
00320                 }
00321                 else
00322                 {
00323                     var segmentList = stream.Segments;
00324                     int min = 0;
00325                     int max = (segmentList.Count()) - 1;
00326
00327                     //five tries forward and backward?
00328                     //need to do it in steps of availibilityWindowDuration / 2.
00329                     ulong increment = ((ulong)max / 2) / 5;
00330
00331                     int foundIndex = -1;
00332                     //Forward Search
00333                     foundIndex = await IterativeSearch(segmentList, nextSegmentIndex, max, increment, true);
00334                     //Backward Search
00335                     if (foundIndex == -1)
00336                     {
00337                         foundIndex = await IterativeSearch(segmentList, min, nextSegmentIndex, increment, false);
00338                     }
00339
00340                     if (foundIndex == -1)
00341                     {
00342 #if DEBUG
00343                         Logger.Log("No segment from the manifest was found for stream " + stream.MimeType);
00344 #endif
00345                         return false;
00346                     }
00347                     else
00348                     {
00349                         nextSegmentIndex = foundIndex;
00350                         return true;
00351                     }
00352
00353                 }
00354             }
00355             catch (Exception e)
00356             {
00357 #if DEBUG
00358                 Logger.Log("Exception while searching for available segment: " + Logger.Display(e));
00359 #endif
00360                 return false;
00361             }
00362         }
00363
00364         private async Task<int> IterativeSearch(List<MediaSegment> segmentList, int minIndex, int maxIndex, ulong increment, bool isForwardSearch)
00365         {
00366             while (minIndex <= maxIndex)
00367             {
00368                 int next;
00369                 if (isForwardSearch)
00370                 {
00371                     next = minIndex + (int)increment;
00372                 }
00373                 else
00374                 {
00375                     next = maxIndex - (int)increment;
00376                 }
00377
00378                 if (next < minIndex || next > maxIndex)
00379                 {
00380                     return -1;
00381                 }
00382
00383                 Uri segmentUri = new Uri(segmentList.ElementAt(next).SegmentUrl);
00384                 HttpResponseMessage response = await Downloader.SendHeadRequestAsync(segmentUri);
00385
00386                 if (response.IsSuccessStatusCode)
00387                 {
00388                     bool downloadSucceeded = await TryDownloadBuffer(segmentUri);
00389                     return next;
00390                 }
00391                 else
00392                 {
00393                     if (isForwardSearch)
00394                     {
00395                         minIndex = next;
00396                     }
00397                     else
00398                     {
00399                         maxIndex = next;
00400                     }
00401                 }
00402             }
00403             return -1;
00404         }
00405
00406         private async Task<bool> TryDownloadBuffer(Uri url)
00407         {
00408             bool success = false;
00409             var activeDownload = Downloader.DownloadBufferAsync(url);
00410             base.activeDownload = activeDownload;
00411             await activeDownload.ContinueWith(
00412             task =>
00413                  {
00414                      try
00415                      {
00416                          internalAppending = false;
00417                          bool resultIsPresent = task.Result != null;
00418
00419                          if (resultIsPresent)
00420                          {
00421                              isEndOfStream = false;
00422                              try
00423                              {
00424                                  sb.AppendBuffer(task.Result);
00425 #if DEBUG
00426                                  Logger.Log("Appended media segment");
00427 #endif
00428                                  nextSegmentIndex++;
00429                              }
00430                              catch (Exception e)
00431                              {
00432 #if DEBUG
00433                                  Logger.Log("Append segment exception HRESULT 0x" + e.HResult.ToString("x") + " for the " + mimeType + " source buffer");
00434 #endif
00435                              }
00436
00437                              success = true;
00438                          }
00439                          else
00440                          {
00441                              if (task.Status != TaskStatus.Canceled)
00442                              {
00443                                  success = false;
00444                              }
00445                          }
00446
00447                          //m_activeDownload = null;
00448                      }
00449                      catch (Exception e)
00450                      {
00451 #if DEBUG
00452                          Logger.Log("Error in Trying download HRESULT 0x" + e.HResult.ToString("x") + " for the " + mimeType + " source buffer");
00453 #endif
00454                      }
00455                  });
00456             return success;
00457         }
00458
00459         private void DetermineStartingSegmentIndex()
00460         {
00461             if (!determinedStartingSegmentIndex && !manifest.TreatAsOnDemand && manifest.IsLive)
00462             {
00463                 //Can't have a live offset lower than 30 seconds
00464                 if (hnsDesiredLiveOffset < 300000000)
00465                 {
00466                     hnsDesiredLiveOffset = 300000000;
00467                 }
00468                 nextSegmentIndex = stream.GetStartingSegmentIndexForLive(hnsDesiredLiveOffset);
00469                 determinedStartingSegmentIndex = true;
00470             }
00471         }
00472
00473
00474         internal void GoToLiveEdge()
00475         {
00476             //m_isFirstSegment = true;
00477             determinedStartingSegmentIndex = false;
00478             DetermineStartingSegmentIndex();
00479         }
00480
00481     }
00482 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlWebView/cs/Scenario7_Share.xaml.cs Source File

  • XamlWebView
  • cs

Scenario7_Share.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using System;
00017 using Windows.ApplicationModel.DataTransfer;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class Scenario7_Share : Page
00025     {
00026         private MainPage rootPage;
00027
00028         public Scenario7_Share()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         /// <summary>
00034         /// Invoked when this page is about to be displayed in a Frame.
00035         /// </summary>
00036         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037         /// property is typically used to configure the page.</param>
00038         protected override void OnNavigatedTo(NavigationEventArgs e)
00039         {
00040             rootPage = MainPage.Current;
00041
00042             WebViewControl.Navigate(new Uri("http://www.microsoft.com"));
00043
00044             // Register for the share event
00045             DataTransferManager.GetForCurrentView().DataRequested += DataTransferManager_DataRequested;
00046         }
00047
00048         protected override void OnNavigatedFrom(NavigationEventArgs e)
00049         {
00050             // Unregister for the share event
00051             DataTransferManager.GetForCurrentView().DataRequested -= DataTransferManager_DataRequested;
00052         }
00053
00054         void WebViewControl_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
00055         {
00056             ProgressControl.IsActive = true;
00057         }
00058
00059         void WebViewControl_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
00060         {
00061             ProgressControl.IsActive = false;
00062         }
00063
00064         private void ShareContent_Click(object sender, RoutedEventArgs e)
00065         {
00066             // Show the share UI
00067             DataTransferManager.ShowShareUI();
00068         }
00069
00070         /// <summary>
00071         /// Raised when the user initiates a Share operation.
00072         /// </summary>
00073         /// <param name="sender"></param>
00074         /// <param name="args"></param>
00075         async void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
00076         {
00077             DataRequest request = args.Request;
00078             // We are going to use an async API to talk to the webview, so get a deferral to give
00079             // us time to generate the results.
00080             DataRequestDeferral deferral = request.GetDeferral();
00081             DataPackage dp = await WebViewControl.CaptureSelectedContentToDataPackageAsync();
00082
00083             // Determine whether there was any selected content.
00084             bool hasSelection = false;
00085             try
00086             {
00087                 hasSelection = (dp != null) && (dp.GetView().AvailableFormats.Count > 0);
00088             }
00089             catch (Exception ex)
00090             {
00091                 switch (ex.HResult)
00092                 {
00093                     case unchecked((int)0x80070490):
00094                         // Mobile does not generate a data package with AvailableFormats
00095                         // and results in an exception. Sorry. Handle the case by acting as
00096                         // if we had no selected content.
00097                         hasSelection = false;
00098                         break;
00099
00100                     default:
00101                         // All other exceptions are unexpected. Let them propagate.
00102                         throw;
00103                 }
00104             }
00105
00106             if (hasSelection)
00107             {
00108                 // Webview has a selection, so we'll share its data package.
00109                 dp.Properties.Title = "WebView sample selected content";
00110             }
00111             else
00112             {
00113                 // No selection, so we'll share the url of the webview.
00114                 dp = new DataPackage();
00115                 dp.SetWebLink(WebViewControl.Source);
00116                 dp.Properties.Title = "WebView sample page";
00117             }
00118             dp.Properties.Description = WebViewControl.Source.ToString();
00119             request.Data = dp;
00120
00121             deferral.Complete();
00122         }
00123     }
00124 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SemanticTextQuery/cpp/FindInProperty.xaml.h Source File

  • SemanticTextQuery
  • cpp

FindInProperty.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2.xaml.h
00014 // Declaration of the Scenario2 class
00015 //
00016
00017 #pragma once
00018 #include "FindInProperty.g.h"
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public ref class Scenario2 sealed
00026     {
00027     public:
00028         Scenario2();
00029
00030     private:
00031         void Find_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032     };
00033 }
Generated on Fri Nov 15 2024 22:21:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/Content/Stroke.cpp Source File

  • SpatialInteractionSource
  • cpp
  • Content

Stroke.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "stroke.h"
00003 #include "Common\DirectXHelper.h"
00004
00005 using namespace HolographicPaint;
00006 using namespace DirectX;
00007 using namespace Windows::Foundation::Numerics;
00008 using namespace Windows::UI::Input::Spatial;
00009
00010
00011 Stroke::Stroke(Windows::UI::Color color)
00012 {
00013     m_modelConstantBufferData.color = DX::GetDXColor(color);
00014     XMStoreFloat4x4(&m_modelConstantBufferData.model, XMMatrixIdentity());
00015 }
00016
00017 void Stroke::AddPosition(float3 position, quaternion orientation, float diameter)
00018 {
00019     const XMMATRIX translation = XMMatrixTranslationFromVector(XMLoadFloat3(&position));
00020     const XMMATRIX rotation = XMMatrixRotationQuaternion(XMLoadQuaternion(&orientation));
00021     const XMMATRIX transformationMatrix = rotation * translation;
00022     Square square;
00023     const float radius = diameter / 2.0f;
00024     XMFLOAT3 pos(-radius, 0.0f, radius);
00025     XMStoreFloat3(&square.TopLeft, XMVector3TransformCoord(XMLoadFloat3(&pos), transformationMatrix));
00026     pos.x = radius;
00027     XMStoreFloat3(&square.TopRight, XMVector3TransformCoord(XMLoadFloat3(&pos), transformationMatrix));
00028     pos.z = -radius;
00029     XMStoreFloat3(&square.BottomRight, XMVector3TransformCoord(XMLoadFloat3(&pos), transformationMatrix));
00030     pos.x = -radius;
00031     XMStoreFloat3(&square.BottomLeft, XMVector3TransformCoord(XMLoadFloat3(&pos), transformationMatrix));
00032     m_squares.push_back(square);
00033     m_resetBuffers = true;
00034 }
00035
00036 void Stroke::Update(ID3D11DeviceContext* pDeviceContext)
00037 {
00038     if (m_resetBuffers)
00039     {
00040         if (m_squares.size() > 0)
00041         {
00042             Microsoft::WRL::ComPtr<ID3D11Device> spDevice;
00043             pDeviceContext->GetDevice(spDevice.ReleaseAndGetAddressOf());
00044             std::vector<VertexPosition> vertices;
00045             for (auto& it : m_squares)
00046             {
00047                 vertices.push_back({ it.TopLeft });
00048                 vertices.push_back({ it.TopRight });
00049                 vertices.push_back({ it.BottomRight });
00050                 vertices.push_back({ it.BottomLeft });
00051             }
00052
00053             D3D11_SUBRESOURCE_DATA vertexBufferData = { 0 };
00054             vertexBufferData.pSysMem = vertices.data();
00055             vertexBufferData.SysMemPitch = 0;
00056             vertexBufferData.SysMemSlicePitch = 0;
00057             const CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(VertexPosition) * static_cast<UINT>(vertices.size()), D3D11_BIND_VERTEX_BUFFER);
00058             DX::ThrowIfFailed(
00059                 spDevice->CreateBuffer(
00060                     &vertexBufferDesc,
00061                     &vertexBufferData,
00062                     m_vertexBuffer.ReleaseAndGetAddressOf()
00063                 )
00064             );
00065
00066
00067             std::vector<VertexIndex_t> indices;
00068             auto makeSquare = [&indices](VertexIndex_t tl, VertexIndex_t tr, VertexIndex_t br, VertexIndex_t bl)
00069             {
00070                 indices.push_back(tl); indices.push_back(tr); indices.push_back(br);
00071                 indices.push_back(tl); indices.push_back(br); indices.push_back(bl);
00072             };
00073             // Back face
00074             makeSquare(1, 0, 3, 2);
00075             // Front face
00076             VertexIndex_t start = static_cast<VertexIndex_t>(4 * (m_squares.size() - 1));
00077             makeSquare(start, start + 1, start + 2, start + 3);
00078             // Now, sides
00079             unsigned int sidesCount = static_cast<unsigned int>(m_squares.size() - 1);
00080             for (unsigned int sideIndex = 0; sideIndex < sidesCount; sideIndex++)
00081             {
00082                 start = static_cast<VertexIndex_t>(4 * sideIndex);
00083                 // +0 = back / top / left
00084                 // +1 = back / top / right
00085                 // +2 = back / bottom / right
00086                 // +3 = back / bottom / left
00087                 // +4 = front / top / left
00088                 // +5 = front / top / right
00089                 // +6 = front / bottom / right
00090                 // +7 = front / bottom / left
00091
00092                 makeSquare(start + 0, start + 1, start + 5, start + 4); // Top
00093                 makeSquare(start + 5, start + 1, start + 2, start + 6); // Right
00094                 makeSquare(start + 0, start + 4, start + 7, start + 3); // Left
00095                 makeSquare(start + 7, start + 6, start + 2, start + 3); // Bottom
00096             }
00097
00098             m_indexCount = static_cast<unsigned int>(indices.size());
00099
00100             D3D11_SUBRESOURCE_DATA indexBufferData = { 0 };
00101             indexBufferData.pSysMem = indices.data();
00102             indexBufferData.SysMemPitch = 0;
00103             indexBufferData.SysMemSlicePitch = 0;
00104             CD3D11_BUFFER_DESC indexBufferDesc(sizeof(VertexIndex_t) * static_cast<UINT>(indices.size()), D3D11_BIND_INDEX_BUFFER);
00105             DX::ThrowIfFailed(
00106                 spDevice->CreateBuffer(
00107                     &indexBufferDesc,
00108                     &indexBufferData,
00109                     m_indexBuffer.ReleaseAndGetAddressOf()
00110                 )
00111             );
00112         }
00113         m_resetBuffers = false;
00114     }
00115 }
00116
00117 void Stroke::Render(ID3D11DeviceContext* pDeviceContext, IRenderer* pRenderingHelper)
00118 {
00119     if (m_squares.size() > 0)
00120     {
00121         const UINT stride = sizeof(VertexPosition);
00122         const UINT offset = 0;
00123         pRenderingHelper->SetConstantBuffer(&m_modelConstantBufferData);
00124         pDeviceContext->IASetVertexBuffers(0, 1, m_vertexBuffer.GetAddressOf(), &stride, &offset);
00125         pDeviceContext->IASetIndexBuffer(m_indexBuffer.Get(), DX::GetDxgiFormat(), 0);
00126         pDeviceContext->DrawIndexedInstanced(m_indexCount, 2, 0, 0, 0);
00127     }
00128 }
00129
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
_changeEvents | ScenarioElement | [private]
_step | ScenarioElement | [private]
_timerStep3 | ScenarioElement | [private]
_timerStep3_Tick(object sender, object e) | ScenarioElement | [inline, private]
BACKGROUND_TASK_NAME | ScenarioElement | [private, static]
BackgroundTask_Progress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args) | ScenarioElement | [inline, private]
Initialize() | ScenarioElement | [inline, private]
OnHistoryChanged(ToastHistoryChangedType changedType) | ScenarioElement | [inline, private]
RegisterBackgroundTask() | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
UnregisterBackgroundTask() | ScenarioElement | [inline, private, static]
Generated on Fri Nov 15 2024 22:23:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundMediaPlayback/cs/Settings.xaml.cs Source File

  • BackgroundMediaPlayback
  • cs

Settings.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using BackgroundMediaPlayback.DataModels;
00013 using BackgroundMediaPlayback.Services;
00014 using BackgroundMediaPlayback.ViewModels;
00015 using SDKTemplate;
00016 using System;
00017 using System.Collections.Generic;
00018 using System.ComponentModel;
00019 using System.Diagnostics;
00020 using System.Linq;
00021 using System.Threading;
00022 using System.Threading.Tasks;
00023 using Windows.Foundation;
00024 using Windows.Foundation.Collections;
00025 using Windows.Media;
00026 using Windows.Media.Core;
00027 using Windows.Media.Playback;
00028 using Windows.Storage.Streams;
00029 using Windows.UI.Core;
00030 using Windows.UI.Popups;
00031 using Windows.UI.Xaml;
00032 using Windows.UI.Xaml.Controls;
00033 using Windows.UI.Xaml.Media.Imaging;
00034 using Windows.UI.Xaml.Navigation;
00035
00036 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00037
00038 namespace BackgroundMediaPlayback
00039 {
00040     /// <summary>
00041     /// An empty page that can be used on its own or navigated to within a Frame.
00042     /// </summary>
00043     public sealed partial class Settings : Page
00044     {
00045         public SettingsViewModel ViewModel { get; set; }
00046
00047         public Settings()
00048         {
00049             ViewModel = new SettingsViewModel();
00050
00051             this.InitializeComponent();
00052
00053             // Always use the cached page
00054             this.NavigationCacheMode = NavigationCacheMode.Required;
00055         }
00056     }
00057 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cpp/pch.h Source File

  • ActivitySensor
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
00011
00012 // Common class ID for activity sensors
00013 const GUID GUID_ActivitySensor_ClassId = { 0X9D9E0118, 0X1807, 0X4F2E, 0X96, 0XE4, 0X2C, 0XE5, 0X71, 0X42, 0XE1, 0X96 };
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

WiFiNetworkDisplay Member List

This is the complete list of members for WiFiNetworkDisplay, including all inherited members.
adapter | WiFiNetworkDisplay | [private]
availableNetwork | WiFiNetworkDisplay | [private]
AvailableNetwork | WiFiNetworkDisplay |
Bssid | WiFiNetworkDisplay |
ChannelCenterFrequency | WiFiNetworkDisplay |
ConnectivityLevel | WiFiNetworkDisplay |
OnPropertyChanged(string name) | WiFiNetworkDisplay | [inline, protected]
PropertyChanged | WiFiNetworkDisplay |
Rssi | WiFiNetworkDisplay |
SecuritySettings | WiFiNetworkDisplay |
Ssid | WiFiNetworkDisplay |
UpdateConnectivityLevel() | WiFiNetworkDisplay | [inline]
UpdateWiFiImage() | WiFiNetworkDisplay | [inline, private]
WiFiImage | WiFiNetworkDisplay |
WiFiNetworkDisplay(WiFiAvailableNetwork availableNetwork, WiFiAdapter adapter) | WiFiNetworkDisplay | [inline]
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario6_Properties.xaml.cpp Source File

  • FileAccess
  • cpp

Scenario6_Properties.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario6_Properties.xaml.h"
00014 #include <sstream>
00015
00016 using namespace SDKTemplate;
00017
00018 using namespace concurrency;
00019 using namespace Platform;
00020 using namespace Platform::Collections;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Globalization::DateTimeFormatting;
00024 using namespace Windows::Storage;
00025 using namespace Windows::Storage::FileProperties;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 Scenario6::Scenario6()
00030 {
00031     InitializeComponent();
00032 }
00033
00034 void Scenario6::OnNavigatedTo(NavigationEventArgs^ e)
00035 {
00036     rootPage->ValidateFile();
00037 }
00038
00039 void Scenario6::ShowPropertiesButton_Click(Object^ sender, RoutedEventArgs^ e)
00040 {
00041     StorageFile^ file = rootPage->SampleFile;
00042     if (file != nullptr)
00043     {
00044         struct State
00045         {
00046             std::wstringstream outputText;
00047             DateTimeFormatter^ dateFormatter = ref new DateTimeFormatter("shortdate longtime");
00048             String^ dateAccessedProperty = "System.DateAccessed";
00049             String^ fileOwnerProperty = "System.FileOwner";
00050         };
00051
00052         // Get top level file properties
00053         auto state = std::make_shared<State>();
00054         state->outputText << L"File name: " << file->Name->Data() << std::endl;
00055         state->outputText << L"File type: " << file->FileType->Data() << std::endl;
00056
00057         // Get basic properties
00058         create_task(file->GetBasicPropertiesAsync()).then([this, file, state](BasicProperties^ basicProperties)
00059         {
00060             state->outputText << L"File size: " << basicProperties->Size << L" bytes" << std::endl;
00061             state->outputText << L"Date modified: " << state->dateFormatter->Format(basicProperties->DateModified)->Data() << std::endl;
00062
00063             // Get extra properties
00064             auto propertiesName = ref new Vector<String^>({ state->dateAccessedProperty , state->fileOwnerProperty });
00065             return file->Properties->RetrievePropertiesAsync(propertiesName);
00066         }).then([this, state](IMap<String^, Object^>^ extraProperties)
00067         {
00068             auto propValue = extraProperties->Lookup(state->dateAccessedProperty);
00069             if (propValue != nullptr)
00070             {
00071                 DateTime dateAccessed = (DateTime)propValue;
00072                 state->outputText << L"Date accessed: " << state->dateFormatter->Format(dateAccessed)->Data() << std::endl;
00073             }
00074             propValue = extraProperties->Lookup(state->fileOwnerProperty);
00075             if (propValue != nullptr)
00076             {
00077                 state->outputText << L"File owner: " << ((String^)propValue)->Data();
00078             }
00079
00080             rootPage->NotifyUser(ref new String(state->outputText.str().c_str()), NotifyType::StatusMessage);
00081         }).then([this, file](task<void> task)
00082         {
00083             try
00084             {
00085                 task.get();
00086             }
00087             catch (COMException^ ex)
00088             {
00089                 // I/O errors are reported as exceptions.
00090                 rootPage->HandleIoException(ex, "Error retrieving properties for '" + file->Name + "'");
00091             }
00092         });
00093     }
00094     else
00095     {
00096         rootPage->NotifyUserFileNotExist();
00097     }
00098 }
Generated on Fri Nov 15 2024 22:19:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: VideoPlayback/cs/Scenario6_PlayingVideoLists.xaml.cs Source File

  • VideoPlayback
  • cs

Scenario6_PlayingVideoLists.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate.Logging;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Diagnostics;
00016 using Windows.Foundation;
00017 using Windows.Media.Core;
00018 using Windows.Media.Playback;
00019 using Windows.UI.Core;
00020 using Windows.UI.Popups;
00021 using Windows.UI.Xaml;
00022 using Windows.UI.Xaml.Controls;
00023 using Windows.UI.Xaml.Navigation;
00024
00025 namespace SDKTemplate
00026 {
00027     /// <summary>
00028     /// Demonstrates playing video lists using MediaPlaybackList.
00029     /// </summary>
00030     public sealed partial class Scenario6 : Page
00031     {
00032         private MainPage rootPage = MainPage.Current;
00033         private MediaPlaybackList playbackList = new MediaPlaybackList();
00034         private MediaPlayer mp;
00035         private MediaPlayerLogger mpLogger;
00036         private MediaPlaybackListLogger mplLogger;
00037         private List<MediaPlaybackItemLogger> mpiLoggerList = new List<MediaPlaybackItemLogger>();
00038
00039         public Scenario6()
00040         {
00041             this.InitializeComponent();
00042         }
00043
00044         protected override void OnNavigatedTo(NavigationEventArgs e)
00045         {
00046             // Create a static playback list
00047             mplLogger = new MediaPlaybackListLogger(LoggerControl, playbackList);
00048             InitializePlaybackList();
00049
00050             //Create the MediaPlayer:
00051             mp = new MediaPlayer();
00052             mpLogger = new MediaPlayerLogger(LoggerControl, mp);
00053
00054             // Subscribe to MediaPlayer PlaybackState changed events
00055             mp.PlaybackSession.PlaybackStateChanged += PlaybackSession_PlaybackStateChanged;
00056
00057             // Subscribe to MediaPlayer PlaybackRate changed events
00058             mp.PlaybackSession.PlaybackRateChanged += PlaybackSession_PlaybackRateChanged;
00059
00060            // Subscribe to list UI changes
00061            playlistView.ItemClick += PlaylistView_ItemClick;
00062
00063             //Attach the player to the MediaPlayerElement:
00064             mediaPlayerElement.SetMediaPlayer(mp);
00065
00066             // Set list for playback
00067             mp.Source = playbackList;
00068         }
00069
00070
00071         void InitializePlaybackList()
00072         {
00073             // Initialize the playlist data/view model.
00074             // In a production app your data would be sourced from a data store or service.
00075
00076             // Add content to the ListView and to the MediaPlaybackList.
00077             MediaModel media = new MediaModel(rootPage.MultiTrackVideoMediaUri)
00078             {
00079                 Title = "Fitness",
00080                 ArtUri = new Uri("ms-appx:///Assets/Media/multivideo.jpg")
00081             };
00082             playlistView.Items.Add(media);
00083             playbackList.Items.Add(media.MediaPlaybackItem);
00084             mpiLoggerList.Add(new MediaPlaybackItemLogger(LoggerControl, media.MediaPlaybackItem));
00085
00086             media = new MediaModel(rootPage.CaptionedMediaUri)
00087             {
00088                 Title = "Elephant's Dream",
00089                 ArtUri = new Uri("ms-appx:///Assets/Media/ElephantsDream.jpg")
00090             };
00091             playlistView.Items.Add(media);
00092             playbackList.Items.Add(media.MediaPlaybackItem);
00093             mpiLoggerList.Add(new MediaPlaybackItemLogger(LoggerControl, media.MediaPlaybackItem));
00094
00095             media = new MediaModel(rootPage.SintelMediaUri)
00096             {
00097                 Title = "Sintel",
00098                 ArtUri = new Uri("ms-appx:///Assets/Media/sintel.jpg")
00099             };
00100             playlistView.Items.Add(media);
00101             playbackList.Items.Add(media.MediaPlaybackItem);
00102             mpiLoggerList.Add(new MediaPlaybackItemLogger(LoggerControl, media.MediaPlaybackItem));
00103
00104             // Subscribe for changes
00105             playbackList.CurrentItemChanged += PlaybackList_CurrentItemChanged;
00106
00107             // Loop
00108             playbackList.AutoRepeatEnabled = true;
00109         }
00110
00111         protected override void OnNavigatedFrom(NavigationEventArgs e)
00112         {
00113             foreach (var mpiLogger in mpiLoggerList)
00114             {
00115                 mpiLogger.Dispose();
00116             }
00117             mpiLoggerList.Clear();
00118             mpLogger?.Dispose();
00119             mpLogger = null;
00120
00121             MediaPlayerHelper.CleanUpMediaPlayerSource(mp);
00122             playbackList.Items.Clear();
00123             playlistView.Items.Clear();
00124         }
00125
00126         private void PlaybackList_CurrentItemChanged(MediaPlaybackList sender, CurrentMediaPlaybackItemChangedEventArgs args)
00127         {
00128             LoggerControl.Log($"Current item changed to index: {sender.CurrentItemIndex}");
00129             var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00130             {
00131                 // Synchronize our UI with the currently-playing item.
00132                 playlistView.SelectedIndex = (int)sender.CurrentItemIndex;
00133             });
00134         }
00135
00136         /// <summary>
00137         /// MediaPlayer state changed event handlers.
00138         /// Note that we can subscribe to events even if Media Player is playing media in background
00139         /// </summary>
00140         /// <param name="sender"></param>
00141         /// <param name="args"></param>
00142         ///
00143         private async void PlaybackSession_PlaybackStateChanged(MediaPlaybackSession sender, object args)
00144         {
00145             LoggerControl.Log($"Current playback state changed to: {sender.PlaybackState}");
00146
00147             await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00148             {
00149                 var currentState = sender.PlaybackState;
00150
00151                 // Update state label
00152                 txtCurrentState.Text = currentState.ToString();
00153
00154                 // Update controls
00155                 UpdateTransportControls(currentState);
00156             });
00157         }
00158
00159         private void PlaylistView_ItemClick(object sender, ItemClickEventArgs e)
00160         {
00161             var item = e.ClickedItem as MediaModel;
00162             LoggerControl.Log("Clicked item: " + item.Title);
00163
00164             // Start the background task if it wasn't running
00165             playbackList.MoveTo((uint)playbackList.Items.IndexOf(item.MediaPlaybackItem));
00166
00167             if (MediaPlaybackState.Paused == mp.PlaybackSession.PlaybackState)
00168             {
00169                 mp.Play();
00170             }
00171         }
00172
00173         /// <summary>
00174         /// Sends message to the background task to skip to the previous track.
00175         /// </summary>
00176         private void prevButton_Click(object sender, RoutedEventArgs e)
00177         {
00178             playbackList.MovePrevious();
00179         }
00180
00181         /// <summary>
00182         /// If the task is already running, it will just play/pause MediaPlayer Instance
00183         /// Otherwise, initializes MediaPlayer Handlers and starts playback
00184         /// track or to pause if we're already playing.
00185         /// </summary>
00186         private void playButton_Click(object sender, RoutedEventArgs e)
00187         {
00188             if (MediaPlaybackState.Playing == mp.PlaybackSession.PlaybackState)
00189             {
00190                 mp.Pause();
00191             }
00192             else if (MediaPlaybackState.Paused == mp.PlaybackSession.PlaybackState)
00193             {
00194                 mp.Play();
00195             }
00196         }
00197
00198         /// <summary>
00199         /// Tells the background audio agent to skip to the next track.
00200         /// </summary>
00201         /// <param name="sender">The button</param>
00202         /// <param name="e">Click event args</param>
00203         private void nextButton_Click(object sender, RoutedEventArgs e)
00204         {
00205             playbackList.MoveNext();
00206         }
00207
00208         private async void speedButton_Click(object sender, RoutedEventArgs e)
00209         {
00210             // Create menu and add commands
00211             var popupMenu = new PopupMenu();
00212
00213             popupMenu.Commands.Add(new UICommand("4.0x", command => mp.PlaybackSession.PlaybackRate = 4.0));
00214             popupMenu.Commands.Add(new UICommand("2.0x", command => mp.PlaybackSession.PlaybackRate = 2.0));
00215             popupMenu.Commands.Add(new UICommand("1.5x", command => mp.PlaybackSession.PlaybackRate = 1.5));
00216             popupMenu.Commands.Add(new UICommand("1.0x", command => mp.PlaybackSession.PlaybackRate = 1.0));
00217             popupMenu.Commands.Add(new UICommand("0.5x", command => mp.PlaybackSession.PlaybackRate = 0.5));
00218
00219             // Get button transform and then offset it by half the button
00220             // width to center. This will show the popup just above the button.
00221             var button = (Button)sender;
00222             var transform = button.TransformToVisual(null);
00223             var point = transform.TransformPoint(new Point(button.ActualWidth / 2, 0));
00224
00225             // Show popup
00226             IUICommand result = await popupMenu.ShowAsync(point);
00227             if (result != null)
00228             {
00229                 button.Content = result.Label;
00230             }
00231         }
00232
00233         private void PlaybackSession_PlaybackRateChanged(MediaPlaybackSession sender, object args)
00234         {
00235             LoggerControl.Log($"Current playback rate changed to: {sender.PlaybackRate}");
00236         }
00237
00238         private void UpdateTransportControls(MediaPlaybackState state)
00239         {
00240             nextButton.IsEnabled = true;
00241             prevButton.IsEnabled = true;
00242             if (state == MediaPlaybackState.Playing)
00243             {
00244                 playButtonSymbol.Symbol = Symbol.Pause;
00245             }
00246             else
00247             {
00248                 playButtonSymbol.Symbol = Symbol.Play;
00249             }
00250         }
00251     }
00252
00253     public class MediaModel
00254     {
00255         public MediaModel(Uri mediaUri)
00256         {
00257             MediaPlaybackItem = new MediaPlaybackItem(MediaSource.CreateFromUri(mediaUri));
00258         }
00259
00260         public string Title { get; set; }
00261         public Uri ArtUri { get; set; }
00262         public MediaPlaybackItem MediaPlaybackItem { get; private set; }
00263     }
00264 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisablingScreenCapture/cppwinrt/SampleConfiguration.h Source File

  • DisablingScreenCapture
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MicrosoftPassport/Server/App_Start/FilterConfig.cs Source File

  • MicrosoftPassport
  • Server
  • App_Start

FilterConfig.cs

Go to the documentation of this file.
00001 ﻿using System.Web;
00002 using System.Web.Mvc;
00003
00004 namespace MicrosoftPassport.Server
00005 {
00006     public class FilterConfig
00007     {
00008         public static void RegisterGlobalFilters(GlobalFilterCollection filters)
00009         {
00010             filters.Add(new HandleErrorAttribute());
00011         }
00012     }
00013 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_ConcurrentProfile Member List

This is the complete list of members for Scenario2_ConcurrentProfile, including all inherited members.
CheckConcurrentProfileBtn_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_ConcurrentProfile | [inline, private]
GetVideoProfileSupportedDeviceIdAsync(Windows.Devices.Enumeration.Panel panel) | Scenario2_ConcurrentProfile | [inline]
LogStatus(string message, NotifyType type) | Scenario2_ConcurrentProfile | [inline, private]
LogStatusToOutputBox(string message) | Scenario2_ConcurrentProfile | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_ConcurrentProfile | [inline, protected]
rootPage | Scenario2_ConcurrentProfile | [private]
Scenario2_ConcurrentProfile() | Scenario2_ConcurrentProfile | [inline]
Generated on Fri Nov 15 2024 22:23:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/LiveTiles/Updating/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • LiveTiles
  • Updating

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Linq;
00003 using Windows.UI.Popups;
00004 using Windows.UI.StartScreen;
00005 using Windows.UI.Xaml;
00006 using Windows.UI.Xaml.Controls;
00007
00008 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00009
00010 namespace Notifications.ScenarioPages.LiveTiles.Updating
00011 {
00012     /// <summary>
00013     /// An empty page that can be used on its own or navigated to within a Frame.
00014     /// </summary>
00015     public sealed partial class ScenarioElement : UserControl
00016     {
00017         public ScenarioElement()
00018         {
00019             this.InitializeComponent();
00020         }
00021
00022         private string _tileId;
00023
00024         private async void ButtonPinSecondaryTile_Click(object sender, RoutedEventArgs e)
00025         {
00026             base.IsEnabled = false;
00027
00028             // Generate a unique tile ID for the purposes of the sample
00029             _tileId = DateTime.Now.Ticks.ToString();
00030
00031             // Initialize and pin a new secondary tile that we will later update
00032             SecondaryTile tile = new SecondaryTile(_tileId, "Original", "args", new Uri("ms-appx:///Assets/cancel.png"), TileSize.Default);
00033             tile.VisualElements.Square71x71Logo = new Uri("ms-appx:///Assets/cancel.png");
00034             tile.VisualElements.Wide310x150Logo = new Uri("ms-appx:///Assets/cancel.png");
00035             tile.VisualElements.Square310x310Logo = new Uri("ms-appx:///Assets/cancel.png");
00036             tile.VisualElements.ShowNameOnSquare150x150Logo = true;
00037             tile.VisualElements.ShowNameOnSquare310x310Logo = true;
00038             tile.VisualElements.ShowNameOnWide310x150Logo = true;
00039             await tile.RequestCreateAsync();
00040
00041             // And move to the next step
00042             stepsControl.Step++;
00043
00044             base.IsEnabled = true;
00045         }
00046
00047         private async void ButtonUpdateTile_Click(object sender, RoutedEventArgs e)
00048         {
00049             base.IsEnabled = false;
00050
00051             // Grab the existing tile
00052             SecondaryTile tile = (await SecondaryTile.FindAllAsync()).FirstOrDefault(i => i.TileId.Equals(_tileId));
00053             if (tile == null)
00054             {
00055                 await new MessageDialog("The secondary tile that was previously pinned could not be found. Has it been removed from Start?", "Error").ShowAsync();
00056                 return;
00057             }
00058
00059             // Change its name and logos
00060             tile.DisplayName = "Updated";
00061             tile.VisualElements.Square150x150Logo = new Uri("ms-appx:///Assets/check.png");
00062             tile.VisualElements.Square71x71Logo = new Uri("ms-appx:///Assets/check.png");
00063             tile.VisualElements.Square310x310Logo = new Uri("ms-appx:///Assets/check.png");
00064             tile.VisualElements.Wide310x150Logo = new Uri("ms-appx:///Assets/check.png");
00065
00066             // And request its properties to be updated
00067             await tile.UpdateAsync();
00068
00069             stepsControl.Step++;
00070
00071             base.IsEnabled = true;
00072         }
00073
00074         private void stepsControl_StepChanged(object sender, int e)
00075         {
00076             switch (e)
00077             {
00078                 case 1:
00079                     stepsControl.IsNextEnabled = true;
00080                     break;
00081
00082                 case 2:
00083                     stepsControl.IsNextEnabled = false;
00084                     break;
00085
00086                 case 3:
00087                     stepsControl.IsNextEnabled = true;
00088                     break;
00089
00090                 case 4:
00091                     stepsControl.IsNextEnabled = false;
00092                     break;
00093
00094                 default:
00095                     stepsControl.IsNextEnabled = true;
00096                     break;
00097             }
00098         }
00099     }
00100 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cpp/pch.h Source File

  • ResizeAppView
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cs/Scenario8.xaml.cs Source File

  • XamlCommanding
  • cs

Scenario8.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013
00014 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00015
00016 namespace Commanding
00017 {
00018     /// <summary>
00019     /// An empty page that can be used on its own or navigated to within a Frame.
00020     /// </summary>
00021     public sealed partial class Scenario8 : Page
00022     {
00023         public Scenario8()
00024         {
00025             this.InitializeComponent();
00026         }
00027     }
00028 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserConsentVerifier/cppwinrt/pch.cpp Source File

  • UserConsentVerifier
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario2_GetParent.xaml.h Source File

  • FileAccess
  • cpp

Scenario2_GetParent.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario2_GetParent.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Getting a file's parent folder.
00022     /// </summary>
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class Scenario2 sealed
00025     {
00026     public:
00027         Scenario2();
00028         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029
00030     private:
00031         MainPage^ rootPage = MainPage::Current;
00032
00033         void GetParent_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034     };
00035 }
Generated on Fri Nov 15 2024 22:19:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cs/cpp/Scenario1_OvenClient.xaml.cpp Source File

  • ProxyStubsForWinRTComponents
  • cs
  • cpp

Scenario1_OvenClient.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include "pch.h"
00008 #include "Scenario1_OvenClient.xaml.h"
00009 #include "MainPage.xaml.h"
00010 #include "..\Server\Microsoft.SDKSamples.Kitchen.h"
00011
00012 using namespace SDKSample;
00013 using namespace SDKSample::ProxyStubsForWinRTComponents;
00014
00015 using namespace Microsoft::SDKSamples::Kitchen;
00016 using namespace Windows::Foundation;
00017
00018 using namespace Windows::UI::Xaml;
00019 using namespace Windows::UI::Xaml::Controls;
00020
00021 OvenClient::OvenClient()
00022 {
00023     InitializeComponent();
00024 }
00025
00026 void SDKSample::ProxyStubsForWinRTComponents::OvenClient::Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00027 {
00028     Dimensions dimensions;
00029     dimensions.Width = 2;
00030     dimensions.Height = 2;
00031     dimensions.Depth = 2;
00032
00033     // Component Creation
00034     Oven^ myOven = ref new Oven(dimensions);
00035
00036     // Getters and setters are accessed using property syntax
00037     OvenClientOutput->Text += "Oven volume is: " + (myOven->Volume).ToString() + "\n";
00038
00039     // Registering event listeners
00040     myOven->BreadBaked += ref new TypedEventHandler<Oven^, Bread^>(this, &OvenClient::BreadCompletedHandler1);
00041     myOven->BreadBaked += ref new TypedEventHandler<Oven^, Bread^>(this, &OvenClient::BreadCompletedHandler2);
00042
00043     // C++ projections expose the tokens used to register and remove event handlers
00044     auto eventRegistrationToken = (myOven->BreadBaked += ref new TypedEventHandler<Oven^, Bread^>(this, &OvenClient::BreadCompletedHandler3));
00045     myOven->BreadBaked -= eventRegistrationToken;
00046
00047     // Bake a loaf of bread. This will trigger the BreadBaked event.
00048     myOven->BakeBread("Sourdough");
00049
00050     // Trigger the event again with a different preheat time
00051     myOven->ConfigurePreheatTemperature(OvenTemperature::High);
00052     myOven->BakeBread("Wheat");
00053 }
00054
00055 void OvenClient::BreadCompletedHandler1(Oven^ oven, Bread^ bread)
00056 {
00057     auto updateOutputText = [this, oven, bread]() -> void
00058     {
00059         OvenClientOutput->Text += "Event Handler 1: Invoked\n";
00060         OvenClientOutput->Text += "Event Handler 1: Oven volume is: " + oven->Volume.ToString() + "\n";
00061         OvenClientOutput->Text += "Event Handler 1: Bread flavor is: " + bread->Flavor + "\n";
00062     };
00063
00064     if (OvenClientOutput->Dispatcher->HasThreadAccess)
00065     {
00066         // If the current thread is the UI thread then execute the lambda.
00067         updateOutputText();
00068     }
00069     else
00070     {
00071         // If the current thread is not the UI thread use the dispatcher to execute the lambda on the UI thread.
00072         OvenClientOutput->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(updateOutputText));
00073     }
00074 }
00075
00076 void OvenClient::BreadCompletedHandler2(Oven^ oven, Bread^ bread)
00077 {
00078     auto updateOutputText = [this, oven, bread]() -> void
00079     {
00080         OvenClientOutput->Text += "Event Handler 2: Invoked\n";
00081     };
00082
00083     if (OvenClientOutput->Dispatcher->HasThreadAccess)
00084     {
00085         // If we are running on the UI thread then just execute the lambda.
00086         updateOutputText();
00087     }
00088     else
00089     {
00090         // If the current thread is not the UI thread use the dispatcher to execute the lambda on the UI thread.
00091         OvenClientOutput->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(updateOutputText));
00092     }
00093 }
00094
00095 void OvenClient::BreadCompletedHandler3(Oven^ oven, Bread^ bread)
00096 {
00097     // Event handler 3 was removed and will not be invoked
00098     auto updateOutputText = [this, oven, bread]() -> void
00099     {
00100         OvenClientOutput->Text += "Event Handler 3: Invoked\n";
00101     };
00102
00103     if (OvenClientOutput->Dispatcher->HasThreadAccess)
00104     {
00105         // If running on the UI thread then just execute the lambda.
00106         updateOutputText();
00107     }
00108     else
00109     {
00110         // If the current thread is not the UI thread use the dispatcher to execute the lambda on the UI thread.
00111         OvenClientOutput->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(updateOutputText));
00112     }
00113 }
00114
Generated on Fri Nov 15 2024 22:21:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScannerProvider/cpp/BarcodeScannerProvider/pch.cpp Source File

  • BarcodeScannerProvider
  • cpp
  • BarcodeScannerProvider

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Helpers::ServiceStatusConverter Member List

This is the complete list of members for Helpers::ServiceStatusConverter, including all inherited members.
Convert(object value, Type targetType, object parameter, string language) | Helpers::ServiceStatusConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | Helpers::ServiceStatusConverter | [inline]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Helpers.h Source File

  • HttpClient
  • cppwinrt

Helpers.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate::Helpers
00016 {
00017     hstring ToSimpleString(Windows::Foundation::DateTime time);
00018
00019     Windows::Foundation::IAsyncAction DisplayTextResultAsync(
00020         Windows::Web::Http::HttpResponseMessage response,
00021         Windows::UI::Xaml::Controls::TextBox output);
00022
00023     void DisplayWebError(MainPage const& rootPage, hresult const& exception);
00024
00025     hstring SerializeHeaders(Windows::Web::Http::HttpResponseMessage const& response);
00026
00027     Windows::Web::Http::HttpClient CreateHttpClientWithCustomHeaders();
00028
00029     void ScenarioStarted(
00030         Windows::UI::Xaml::Controls::Button const& startButton,
00031         Windows::UI::Xaml::Controls::Button const& cancelButton,
00032         Windows::UI::Xaml::Controls::TextBox const& outputField);
00033
00034     void ScenarioCompleted(
00035         Windows::UI::Xaml::Controls::Button const& startButton,
00036         Windows::UI::Xaml::Controls::Button const& cancelButton);
00037
00038     void ReplaceQueryString(Windows::UI::Xaml::Controls::TextBox const& addressField, hstring const& newQueryString);
00039     Windows::Foundation::Uri TryParseHttpUri(hstring const& uriString);
00040 }
Generated on Fri Nov 15 2024 22:18:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: EnterpriseDataProtection/cs/Scenario12_ShareData.xaml.cs Source File

  • EnterpriseDataProtection
  • cs

Scenario12_ShareData.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using System.Threading.Tasks;
00017 using SDKTemplate;
00018 using Windows.Security.EnterpriseData;
00019 using Windows.ApplicationModel.DataTransfer;
00020 using Windows.Foundation;
00021
00022 namespace EdpSample
00023 {
00024
00025     public sealed partial class Scenario12_ShareData : Page
00026     {
00027         private MainPage rootPage;
00028         private DataTransferManager m_dTransferMgr;
00029         private string m_ShareContent = "Content to share from EdpSamples";
00030
00031         public Scenario12_ShareData()
00032         {
00033             this.InitializeComponent();
00034         }
00035
00036         protected override void OnNavigatedTo(NavigationEventArgs e)
00037         {
00038             rootPage = MainPage.Current;
00039
00040             // Register the current page as a share source.
00041             m_dTransferMgr = DataTransferManager.GetForCurrentView();
00042             m_dTransferMgr.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.OnDataRequested);
00043             InputTxtBox.Text = m_ShareContent;
00044         }
00045
00046         private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
00047         {
00048             DataRequest request = e.Request;
00049             request.Data.Properties.Title = "EdpSample share";
00050             request.Data.Properties.Description = "An example of how to share text from an enterprise app";
00051             request.Data.Properties.EnterpriseId = Scenario1.m_enterpriseId;
00052             request.Data.SetText(InputTxtBox.Text);
00053             rootPage.NotifyUser("Set data to share", NotifyType.StatusMessage);
00054         }
00055
00056         private void Share_Click(object sender, RoutedEventArgs e)
00057         {
00058             DataTransferManager.ShowShareUI();
00059         }
00060     }
00061 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cs/Scenario15_ServerCertificateValidation.xaml.cs Source File

  • HttpClient
  • cs

Scenario15_ServerCertificateValidation.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Threading;
00016 using System.Threading.Tasks;
00017 using Windows.Foundation;
00018 using Windows.Security.Cryptography.Certificates;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Navigation;
00022 using Windows.Web.Http;
00023 using Windows.Web.Http.Filters;
00024
00025
00026 namespace SDKTemplate
00027 {
00028     public sealed partial class Scenario15_ServerCertificateValidation : Page
00029     {
00030         MainPage rootPage = MainPage.Current;
00031
00032         private HttpBaseProtocolFilter filter;
00033         private HttpClient httpClient;
00034         private CancellationTokenSource cts;
00035
00036         public Scenario15_ServerCertificateValidation()
00037         {
00038             this.InitializeComponent();
00039         }
00040
00041         protected override void OnNavigatedTo(NavigationEventArgs e)
00042         {
00043             // In this scenario we just create an HttpClient instance with default settings. I.e. no custom filters.
00044             // For examples on how to use custom filters see other scenarios.
00045             filter = new HttpBaseProtocolFilter();
00046             httpClient = new HttpClient(filter);
00047             cts = new CancellationTokenSource();
00048         }
00049
00050         protected override void OnNavigatedFrom(NavigationEventArgs e)
00051         {
00052             cts.Dispose();
00053             httpClient.Dispose();
00054             filter.Dispose();
00055         }
00056
00057         private async void Start_Click(object sender, RoutedEventArgs e)
00058         {
00059             // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00060             // valid, absolute URI, we'll notify the user about the incorrect input.
00061             Uri resourceUri = Helpers.TryParseHttpUri(AddressField.Text);
00062             if (resourceUri == null)
00063             {
00064                 rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
00065                 return;
00066             }
00067
00068             Helpers.ScenarioStarted(StartButton, CancelButton, null);
00069             rootPage.NotifyUser("In progress", NotifyType.StatusMessage);
00070
00071             bool isUsingCustomValidation = false;
00072             if (DefaultOSValidation.IsChecked.Value)
00073             {
00074                 //Do nothing
00075             }
00076             else if (DefaultAndCustomValidation.IsChecked.Value)
00077             {
00078                 // Add event handler to listen to the ServerCustomValidationRequested event. By default, OS validation
00079                 // will be performed before the event is raised.
00080                 filter.ServerCustomValidationRequested += MyCustomServerCertificateValidator;
00081                 isUsingCustomValidation = true;
00082             }
00083             else if (IgnoreErrorsAndCustomValidation.IsChecked.Value)
00084             {
00085                 // ---------------------------------------------------------------------------
00086                 // WARNING: Only test applications should ignore SSL errors.
00087                 // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle
00088                 // attacks (while the connection is secure, the server is not authenticated).
00089                 // Note that not all certificate validation errors can be ignored.
00090                 // ---------------------------------------------------------------------------
00091                 filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
00092                 filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
00093
00094                 // Add event handler to listen to the ServerCustomValidationRequested event.
00095                 // This event handler must implement the desired custom certificate validation logic.
00096                 filter.ServerCustomValidationRequested += MyCustomServerCertificateValidator;
00097                 isUsingCustomValidation = true;
00098             }
00099
00100             // Here, we turn off writing to and reading from the cache to ensure that each request actually
00101             // hits the network and tries to establish an SSL/TLS connection with the server.
00102             filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
00103             filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.NoCache;
00104
00105             HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, resourceUri);
00106
00107             // This sample uses a "try" in order to support TaskCanceledException.
00108             // If you don't need to support cancellation, then the "try" is not needed.
00109             try
00110             {
00111
00112                 HttpRequestResult result = await httpClient.TrySendRequestAsync(
00113                     request,
00114                     HttpCompletionOption.ResponseHeadersRead).AsTask(cts.Token);
00115
00116                 if (result.Succeeded)
00117                 {
00118                     rootPage.NotifyUser("Success - response received from server. Server certificate was valid.", NotifyType.StatusMessage);
00119                 }
00120                 else
00121                 {
00122                     Helpers.DisplayWebError(rootPage, result.ExtendedError);
00123                 }
00124             }
00125             catch (TaskCanceledException)
00126             {
00127                 rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
00128             }
00129
00130             if (isUsingCustomValidation)
00131             {
00132                 // Unregister the event handler after we are done validating.
00133                 filter.ServerCustomValidationRequested -= MyCustomServerCertificateValidator;
00134             }
00135
00136             Helpers.ScenarioCompleted(StartButton, CancelButton);
00137         }
00138
00139         private void Cancel_Click(object sender, RoutedEventArgs e)
00140         {
00141             cts.Cancel();
00142             cts.Dispose();
00143
00144             // Re-create the CancellationTokenSource.
00145             cts = new CancellationTokenSource();
00146         }
00147
00148         // This event handler for server certificate validation executes synchronously as part of the SSL/TLS handshake.
00149         // An app should not perform lengthy operations inside this handler. Otherwise, the remote server may terminate the connection abruptly.
00150         private async void MyCustomServerCertificateValidator(HttpBaseProtocolFilter sender, HttpServerCustomValidationRequestedEventArgs args)
00151         {
00152             // Get the server certificate and certificate chain from the args parameter.
00153             Certificate serverCert = args.ServerCertificate;
00154             IReadOnlyList<Certificate> serverCertChain = args.ServerIntermediateCertificates;
00155
00156             // To illustrate the use of async APIs, we use the IsCertificateValidAsync method.
00157             // In order to call async APIs in this handler, you must first take a deferral and then
00158             // release it once you are done with the operation. The "using" statement
00159             // ensures that the deferral completes when control leaves the method.
00160             using (Deferral deferral = args.GetDeferral())
00161             {
00162                 try
00163                 {
00164                     bool isCertificateValid = await IsCertificateValidAsync(serverCert);
00165                     if (!isCertificateValid)
00166                     {
00167                         args.Reject();
00168                     }
00169                 }
00170                 catch
00171                 {
00172                     // If we get an exception from IsCertificateValidAsync, we reject the certificate
00173                     // (secure by default).
00174                     args.Reject();
00175                 }
00176             }
00177         }
00178
00179         private async Task<bool> IsCertificateValidAsync(Certificate serverCert)
00180         {
00181             // This is a placeholder call to simulate long-running async calls. Note that this code runs synchronously as part of the SSL/TLS handshake.
00182             // Avoid performing lengthy operations here - else, the remote server may terminate the connection abruptly.
00183             await Task.Delay(100);
00184
00185             // In this sample, we compare the hash code of the certificate to a specific hash - this is purely
00186             // for illustration purposes and should not be considered as a recommendation for certificate validation.
00187             var trustedHash = new byte[] {
00188                 0x28, 0xb8, 0x85, 0x04, 0xf6, 0x09, 0xf6, 0x85, 0xf1, 0x68,
00189                 0xb9, 0xa4, 0x9c, 0x8f, 0x0e, 0xc4, 0x9e, 0xad, 0x8b, 0xc2
00190             };
00191             if (serverCert.GetHashValue().SequenceEqual(trustedHash))
00192             {
00193                 // If certificate satisfies the criteria, return true.
00194                 return true;
00195             }
00196             else
00197             {
00198                 // If certificate does not meet the required criteria,return false.
00199                 return false;
00200             }
00201         }
00202
00203         private void DefaultOSValidation_Checked(object sender, RoutedEventArgs e)
00204         {
00205             AddressField.Text = "https://www.microsoft.com";
00206         }
00207
00208         private void DefaultAndCustomValidation_Checked(object sender, RoutedEventArgs e)
00209         {
00210             AddressField.Text = "https://www.microsoft.com";
00211         }
00212
00213         private void IgnoreErrorsAndCustomValidation_Checked(object sender, RoutedEventArgs e)
00214         {
00215             AddressField.Text = "https://localhost/HttpClientSample/default.aspx";
00216         }
00217     }
00218 }
Generated on Fri Nov 15 2024 22:20:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HolographicMRCSampleMain Member List

This is the complete list of members for HolographicMRCSampleMain, including all inherited members.
DisableAllButtons() | HolographicMRCSampleMain | [private]
HolographicMRCSampleMain(const std::shared_ptr< DX::DeviceResources > &deviceResources) | HolographicMRCSampleMain |
LoadAppState() | HolographicMRCSampleMain |
m_cameraAddedToken | HolographicMRCSampleMain | [private]
m_cameraRemovedToken | HolographicMRCSampleMain | [private]
m_deviceResources | HolographicMRCSampleMain | [private]
m_holographicSpace | HolographicMRCSampleMain | [private]
m_locatabilityChangedToken | HolographicMRCSampleMain | [private]
m_locator | HolographicMRCSampleMain | [private]
m_mediaCapture | HolographicMRCSampleMain | [private]
m_recording | HolographicMRCSampleMain | [private]
m_referenceFrame | HolographicMRCSampleMain | [private]
m_timer | HolographicMRCSampleMain | [private]
OnButtonHologramTapped() | HolographicMRCSampleMain | [private]
OnButtonInitTapped() | HolographicMRCSampleMain | [private]
OnButtonPhotoTapped() | HolographicMRCSampleMain | [private]
OnButtonSysAudioTapped() | HolographicMRCSampleMain | [private]
OnButtonVideoTapped() | HolographicMRCSampleMain | [private]
OnCameraAdded(Windows::Graphics::Holographic::HolographicSpace^sender, Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs^args) | HolographicMRCSampleMain | [private]
OnCameraRemoved(Windows::Graphics::Holographic::HolographicSpace^sender, Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs^args) | HolographicMRCSampleMain | [private]
OnDeviceLost() | HolographicMRCSampleMain | [virtual]
OnDeviceRestored() | HolographicMRCSampleMain | [virtual]
OnLocatabilityChanged(Windows::Perception::Spatial::SpatialLocator^sender, Platform::Object^args) | HolographicMRCSampleMain | [private]
Render(Windows::Graphics::Holographic::HolographicFrame^holographicFrame) | HolographicMRCSampleMain |
SaveAppState() | HolographicMRCSampleMain |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^holographicSpace) | HolographicMRCSampleMain |
UnregisterHolographicEventHandlers() | HolographicMRCSampleMain | [private]
Update() | HolographicMRCSampleMain |
~HolographicMRCSampleMain() | HolographicMRCSampleMain |
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareTarget/cs/Scenario1_Welcome.xaml.cs Source File

  • ShareTarget
  • cs

Scenario1_Welcome.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using Windows.UI.Core.AnimationMetrics;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario1_Welcome : Page
00020     {
00021         private MainPage rootPage;
00022
00023         public Scenario1_Welcome()
00024         {
00025             this.InitializeComponent();
00026         }
00027     }
00028 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

StspOperationHeader Member List

This is the complete list of members for StspOperationHeader, including all inherited members.
cbDataSize | StspOperationHeader
eOperation | StspOperationHeader
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario08_PostCustomContent Member List

This is the complete list of members for Scenario08_PostCustomContent, including all inherited members.
Cancel_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario08_PostCustomContent |
CancelableRequestAsync(Windows::Foundation::Uri resourceUri, Windows::Web::Http::IHttpContent content) | Scenario08_PostCustomContent | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario08_PostCustomContent |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario08_PostCustomContent |
Scenario08_PostCustomContent() | Scenario08_PostCustomContent |
Start_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario08_PostCustomContent |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Syndication/cpp/pch.cpp Source File

  • Syndication
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Include the standard header and generate the precompiled header.
00014 //
00015
00016 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: StreamSocket/cpp/SampleConfiguration.cpp Source File

  • StreamSocket
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     // The format here is the following:
00021     //     { "Description for the sample", "Fully qualified name for the class that implements the scenario" }
00022     { "Start StreamSocketListener", "SDKTemplate.StreamSocketSample.Scenario1" },
00023     { "Connect to Listener", "SDKTemplate.StreamSocketSample.Scenario2" },
00024     { "Send Data", "SDKTemplate.StreamSocketSample.Scenario3" },
00025     { "Close Socket", "SDKTemplate.StreamSocketSample.Scenario4" },
00026     { "SSL/TLS Server Certificates", "SDKTemplate.StreamSocketSample.Scenario5" }
00027 };
Generated on Fri Nov 15 2024 22:17:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

S3_RetrieveWithAPI Member List

This is the complete list of members for S3_RetrieveWithAPI, including all inherited members.
AddToIndex_Click(object sender, RoutedEventArgs e) | S3_RetrieveWithAPI | [inline, private]
ExecuteQueryHelper(string queryString) | S3_RetrieveWithAPI | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | S3_RetrieveWithAPI | [inline, protected]
RetrieveAllItems_Click(object sender, RoutedEventArgs e) | S3_RetrieveWithAPI | [inline, private]
RetrieveMatchingItems_Click(object sender, RoutedEventArgs e) | S3_RetrieveWithAPI | [inline, private]
rootPage | S3_RetrieveWithAPI | [private]
S3_RetrieveWithAPI() | S3_RetrieveWithAPI | [inline]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VertexPositionColor Member List

This is the complete list of members for VertexPositionColor, including all inherited members.
color | VertexPositionColor
pos | VertexPositionColor
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/ShareCustomProvider.xaml.cpp Source File

  • ShareSource
  • cpp

ShareCustomProvider.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ShareCustomProvider.xaml.cpp
00014 // Implementation of the ShareCustomProvider class
00015 //
00016
00017 #include "pch.h"
00018 #include "ShareCustomProvider.xaml.h"
00019
00020 using namespace Concurrency;
00021 using namespace Platform;
00022 using namespace SDKTemplate;
00023 using namespace Windows::ApplicationModel::DataTransfer;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Storage::Streams;
00026 using namespace Windows::UI::Core;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 ShareCustomProvider::ShareCustomProvider()
00030 {
00031     InitializeComponent();
00032 }
00033
00034 void ShareCustomProvider::OnNavigatedTo(NavigationEventArgs^ e)
00035 {
00036     SharePage::OnNavigatedTo(e);
00037
00038     // Register the event to add a Share Provider
00039     DataTransferManager^ dataTransferManager = DataTransferManager::GetForCurrentView();
00040     shareProvidersRequestedToken = dataTransferManager->ShareProvidersRequested +=
00041         ref new TypedEventHandler<DataTransferManager^, ShareProvidersRequestedEventArgs^>(this, &ShareCustomProvider::OnShareProvidersRequested);
00042 }
00043
00044 void ShareCustomProvider::OnNavigatedFrom(NavigationEventArgs^ e)
00045 {
00046     DataTransferManager^ dataTransferManager = DataTransferManager::GetForCurrentView();
00047     dataTransferManager->ShareProvidersRequested -= shareProvidersRequestedToken;
00048     SharePage::OnNavigatedFrom(e);
00049 }
00050
00051 bool ShareCustomProvider::GetShareContent(DataRequest^ request)
00052 {
00053     DataPackage^ requestData = request->Data;
00054     requestData->Properties->Title = "I got a new high score!";
00055     requestData->Properties->ContentSourceApplicationLink = ApplicationLink;
00056     requestData->SetText("I got a high score of 15063!");
00057     return true;
00058 }
00059
00060 void ShareCustomProvider::OnShareProvidersRequested(DataTransferManager^ s, ShareProvidersRequestedEventArgs^ e)
00061 {
00062     // Take a deferral so that we can perform async operations. (This sample
00063     // doesn't perform any async operations in the ShareProvidersRequested
00064     // event handler, but we take the deferral anyway to demonstrate the pattern.)
00065     auto deferral = e->GetDeferral();
00066
00067     // Create the custom share provider and add it.
00068     RandomAccessStreamReference^ icon = RandomAccessStreamReference::CreateFromUri(ref new Uri("ms-appx:///Assets/windows-sdk.png"));
00069     ShareProvider^ provider = ref new ShareProvider("Contoso Chat", icon, Windows::UI::Colors::LightGray,
00070         ref new ShareProviderHandler(this, &ShareCustomProvider::OnShareToContosoChat));
00071     e->Providers->Append(provider);
00072
00073     deferral->Complete();
00074 }
00075
00076 void ShareCustomProvider::OnShareToContosoChat(ShareProviderOperation^ operation)
00077 {
00078     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, operation]()
00079     {
00080         ShareCompletedText->Text = "";
00081
00082         // Obtain the text from the data package. This should match
00083         // the information placed in it by the GetShareContent method.
00084         create_task(operation->Data->GetTextAsync()).then([this, operation](String^ text)
00085         {
00086             // The app can display custom UI to complete the Share operation.
00087             // Here, we simply display a progress control and delay for a while,
00088             // to simulate posting to the Contoso Chat service.
00089             ProgressControl->Visibility = Windows::UI::Xaml::Visibility::Visible;
00090
00091             auto timer = ref new Windows::UI::Xaml::DispatcherTimer();
00092             timer->Interval = TimeSpan{ 2 * 1000 * 10000 }; // 2 seconds
00093             timer->Tick += ref new EventHandler<Object^>([this, timer, text, operation](Object^, Object^)
00094             {
00095                 timer->Stop();
00096
00097                 // All done. Show the success message.
00098                 ProgressControl->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00099                 ShareCompletedText->Text = "Your message '" + text + "' has been shared with Contoso Chat.";
00100
00101                 // Completing the operation causes ShareCompleted to be raised.
00102                 operation->ReportCompleted();
00103             });
00104             timer->Start();
00105         });
00106     }));
00107 }
00108
Generated on Fri Nov 15 2024 22:21:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/SampleConfiguration.h Source File

  • ApplicationResources
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Application Resources C++ Sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cs/SampleConfiguration.cs Source File

  • DeviceEnumerationAndPairing
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using SDKTemplate;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Device Enumeration and Pairing C# Sample";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Device Picker Common Control", ClassType=typeof(Scenario1_DevicePicker)},
00026             new Scenario() { Title="Enumerate and Watch Devices", ClassType=typeof(Scenario2_DeviceWatcher)},
00027             new Scenario() { Title="Enumerate and Watch Devices in a Background Task", ClassType=typeof(Scenario3_BackgroundDeviceWatcher)},
00028             new Scenario() { Title="Enumerate Snapshot of Devices", ClassType=typeof(Scenario4_Snapshot)},
00029             new Scenario() { Title="Get Single Device", ClassType=typeof(Scenario5_GetSingleDevice)},
00030             new Scenario() { Title= "Custom Filter with Additional Properties", ClassType=typeof(Scenario6_CustomFilterAddedProps)},
00031             new Scenario() { Title= "Request Specific DeviceInformationKind", ClassType=typeof(Scenario7_DeviceInformationKind)},
00032             new Scenario() { Title= "Basic Device Pairing", ClassType=typeof(Scenario8_PairDevice)},
00033             new Scenario() { Title= "Custom Device Pairing", ClassType=typeof(Scenario9_CustomPairDevice)}
00034         };
00035     }
00036
00037     public class Scenario
00038     {
00039         public string Title { get; set; }
00040         public Type ClassType { get; set; }
00041     }
00042 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cs/Scenario_PredefinedDictationGrammar.xaml.cs Source File

  • SpeechRecognitionAndSynthesis
  • cs

Scenario_PredefinedDictationGrammar.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Threading.Tasks;
00016 using Windows.ApplicationModel.Resources.Core;
00017 using Windows.Globalization;
00018 using Windows.Media.SpeechRecognition;
00019 using Windows.UI.Core;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Documents;
00023 using Windows.UI.Xaml.Navigation;
00024 using Windows.Foundation;
00025
00026 namespace SDKTemplate
00027 {
00028     public sealed partial class Scenario_PredefinedDictationGrammar : Page
00029     {
00030         /// <summary>
00031         /// This HResult represents the scenario where a user is prompted to allow in-app speech, but
00032         /// declines. This should only happen on a Phone device, where speech is enabled for the entire device,
00033         /// not per-app.
00034         /// </summary>
00035         private static uint HResultPrivacyStatementDeclined = 0x80045509;
00036
00037         private SpeechRecognizer speechRecognizer;
00038         private IAsyncOperation<SpeechRecognitionResult> recognitionOperation;
00039         private ResourceContext speechContext;
00040         private ResourceMap speechResourceMap;
00041
00042         public Scenario_PredefinedDictationGrammar()
00043         {
00044             InitializeComponent();
00045         }
00046
00047         /// <summary>
00048         /// When activating the scenario, ensure we have permission from the user to access their microphone, and
00049         /// provide an appropriate path for the user to enable access to the microphone if they haven't
00050         /// given explicit permission for it.
00051         /// </summary>
00052         /// <param name="e">The navigation event details</param>
00053         protected async override void OnNavigatedTo(NavigationEventArgs e)
00054         {
00055             bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
00056             if (permissionGained)
00057             {
00058                 // Enable the recognition buttons.
00059                 btnRecognizeWithUI.IsEnabled = true;
00060                 btnRecognizeWithoutUI.IsEnabled = true;
00061
00062                 Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
00063                 speechContext = ResourceContext.GetForCurrentView();
00064                 speechContext.Languages = new string[] { speechLanguage.LanguageTag };
00065
00066                 speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");
00067
00068                 PopulateLanguageDropdown();
00069                 await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
00070             }
00071             else
00072             {
00073                 resultTextBlock.Visibility = Visibility.Visible;
00074                 resultTextBlock.Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
00075                 btnRecognizeWithUI.IsEnabled = false;
00076                 btnRecognizeWithoutUI.IsEnabled = false;
00077                 cbLanguageSelection.IsEnabled = false;
00078
00079             }
00080         }
00081
00082         /// <summary>
00083         /// Look up the supported languages for this speech recognition scenario,
00084         /// that are installed on this machine, and populate a dropdown with a list.
00085         /// </summary>
00086         private void PopulateLanguageDropdown()
00087         {
00088             Language defaultLanguage = SpeechRecognizer.SystemSpeechLanguage;
00089             IEnumerable<Language> supportedLanguages = SpeechRecognizer.SupportedTopicLanguages;
00090             foreach (Language lang in supportedLanguages)
00091             {
00092                 ComboBoxItem item = new ComboBoxItem();
00093                 item.Tag = lang;
00094                 item.Content = lang.DisplayName;
00095
00096                 cbLanguageSelection.Items.Add(item);
00097                 if (lang.LanguageTag == defaultLanguage.LanguageTag)
00098                 {
00099                     item.IsSelected = true;
00100                     cbLanguageSelection.SelectedItem = item;
00101                 }
00102             }
00103         }
00104
00105         /// <summary>
00106         /// When a user changes the speech recognition language, trigger re-initialization of the
00107         /// speech engine with that language, and change any speech-specific UI assets.
00108         /// </summary>
00109         /// <param name="sender">Ignored</param>
00110         /// <param name="e">Ignored</param>
00111         private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
00112         {
00113             if (speechRecognizer != null)
00114             {
00115                 ComboBoxItem item = (ComboBoxItem)(cbLanguageSelection.SelectedItem);
00116                 Language newLanguage = (Language)item.Tag;
00117                 if (speechRecognizer.CurrentLanguage != newLanguage)
00118                 {
00119                     // trigger cleanup and re-initialization of speech.
00120                     try
00121                     {
00122                         speechContext.Languages = new string[] { newLanguage.LanguageTag };
00123
00124                         await InitializeRecognizer(newLanguage);
00125                     }
00126                     catch (Exception exception)
00127                     {
00128                         var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
00129                         await messageDialog.ShowAsync();
00130                     }
00131                 }
00132             }
00133         }
00134
00135         /// <summary>
00136         /// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks.
00137         /// </summary>
00138         /// <param name="e">Details about the navigation event</param>
00139         protected override void OnNavigatedFrom(NavigationEventArgs e)
00140         {
00141             base.OnNavigatedFrom(e);
00142
00143             if (speechRecognizer != null)
00144             {
00145                 if (speechRecognizer.State != SpeechRecognizerState.Idle)
00146                 {
00147                     if (recognitionOperation != null)
00148                     {
00149                         recognitionOperation.Cancel();
00150                         recognitionOperation = null;
00151                     }
00152                 }
00153
00154                 speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
00155
00156                 this.speechRecognizer.Dispose();
00157                 this.speechRecognizer = null;
00158             }
00159         }
00160
00161         /// <summary>
00162         /// Initialize Speech Recognizer and compile constraints.
00163         /// </summary>
00164         /// <param name="recognizerLanguage">Language to use for the speech recognizer</param>
00165         /// <returns>Awaitable task.</returns>
00166         private async Task InitializeRecognizer(Language recognizerLanguage)
00167         {
00168             if (speechRecognizer != null)
00169             {
00170                 // cleanup prior to re-initializing this scenario.
00171                 speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
00172
00173                 this.speechRecognizer.Dispose();
00174                 this.speechRecognizer = null;
00175             }
00176
00177             // Create an instance of SpeechRecognizer.
00178             speechRecognizer = new SpeechRecognizer(recognizerLanguage);
00179
00180             // Provide feedback to the user about the state of the recognizer.
00181             speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
00182
00183             // Compile the dictation topic constraint, which optimizes for dictated speech.
00184             var dictationConstraint = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.Dictation, "dictation");
00185             speechRecognizer.Constraints.Add(dictationConstraint);
00186             SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync();
00187
00188             // RecognizeWithUIAsync allows developers to customize the prompts.
00189             speechRecognizer.UIOptions.AudiblePrompt = "Dictate a phrase or sentence...";
00190             speechRecognizer.UIOptions.ExampleText = speechResourceMap.GetValue("DictationUIOptionsExampleText", speechContext).ValueAsString;
00191
00192             // Check to make sure that the constraints were in a proper format and the recognizer was able to compile it.
00193             if (compilationResult.Status != SpeechRecognitionResultStatus.Success)
00194             {
00195                 // Disable the recognition buttons.
00196                 btnRecognizeWithUI.IsEnabled = false;
00197                 btnRecognizeWithoutUI.IsEnabled = false;
00198
00199                 // Let the user know that the grammar didn't compile properly.
00200                 resultTextBlock.Visibility = Visibility.Visible;
00201                 resultTextBlock.Text = "Unable to compile grammar.";
00202             }
00203         }
00204
00205         /// <summary>
00206         /// Handle SpeechRecognizer state changed events by updating a UI component.
00207         /// </summary>
00208         /// <param name="sender">Speech recognizer that generated this status event</param>
00209         /// <param name="args">The recognizer's status</param>
00210         private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args)
00211         {
00212             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00213             {
00214                 MainPage.Current.NotifyUser("Speech recognizer state: " + args.State.ToString(), NotifyType.StatusMessage);
00215             });
00216         }
00217
00218         /// <summary>
00219         /// Uses the recognizer constructed earlier to listen for speech from the user before displaying
00220         /// it back on the screen. Uses the built-in speech recognition UI.
00221         /// </summary>
00222         /// <param name="sender">Button that triggered this event</param>
00223         /// <param name="e">State information about the routed event</param>
00224         private async void RecognizeWithUIDictationGrammar_Click(object sender, RoutedEventArgs e)
00225         {
00226             heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;
00227             hlOpenPrivacySettings.Visibility = Visibility.Collapsed;
00228
00229             // Start recognition.
00230             try
00231             {
00232                 recognitionOperation = speechRecognizer.RecognizeWithUIAsync();
00233                 SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
00234                 // If successful, display the recognition result.
00235                 if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
00236                 {
00237                     heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible;
00238                     resultTextBlock.Text = speechRecognitionResult.Text;
00239                 }
00240                 else
00241                 {
00242                     resultTextBlock.Visibility = Visibility.Visible;
00243                     resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString());
00244                 }
00245             }
00246             catch (TaskCanceledException exception)
00247             {
00248                 // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
00249                 // processing speech. Since this happens here when we navigate out of the scenario, don't try to
00250                 // show a message dialog for this exception.
00251                 System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
00252                 System.Diagnostics.Debug.WriteLine(exception.ToString());
00253             }
00254             catch (Exception exception)
00255             {
00256                 // Handle the speech privacy policy error.
00257                 if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
00258                 {
00259                     hlOpenPrivacySettings.Visibility = Visibility.Visible;
00260                 }
00261                 else
00262                 {
00263                     var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
00264                     await messageDialog.ShowAsync();
00265                 }
00266             }
00267         }
00268
00269         /// <summary>
00270         /// Uses the recognizer constructed earlier to listen for speech from the user before displaying
00271         /// it back on the screen. Uses developer-provided UI for user feedback.
00272         /// </summary>
00273         /// <param name="sender">Button that triggered this event</param>
00274         /// <param name="e">State information about the routed event</param>
00275         private async void RecognizeWithoutUIDictationGrammar_Click(object sender, RoutedEventArgs e)
00276         {
00277             heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;
00278
00279             // Disable the UI while recognition is occurring, and provide feedback to the user about current state.
00280             btnRecognizeWithUI.IsEnabled = false;
00281             btnRecognizeWithoutUI.IsEnabled = false;
00282             cbLanguageSelection.IsEnabled = false;
00283             hlOpenPrivacySettings.Visibility = Visibility.Collapsed;
00284             listenWithoutUIButtonText.Text = " listening for speech...";
00285
00286             // Start recognition.
00287             try
00288             {
00289                 recognitionOperation = speechRecognizer.RecognizeAsync();
00290                 SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
00291                 // If successful, display the recognition result.
00292                 if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
00293                 {
00294                     heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible;
00295                     resultTextBlock.Text = speechRecognitionResult.Text;
00296                 }
00297                 else
00298                 {
00299                     resultTextBlock.Visibility = Visibility.Visible;
00300                     resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString());
00301                 }
00302             }
00303             catch (TaskCanceledException exception)
00304             {
00305                 // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
00306                 // processing speech. Since this happens here when we navigate out of the scenario, don't try to
00307                 // show a message dialog for this exception.
00308                 System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
00309                 System.Diagnostics.Debug.WriteLine(exception.ToString());
00310             }
00311             catch (Exception exception)
00312             {
00313                 // Handle the speech privacy policy error.
00314                 if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
00315                 {
00316                     hlOpenPrivacySettings.Visibility = Visibility.Visible;
00317                 }
00318                 else
00319                 {
00320                     var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
00321                     await messageDialog.ShowAsync();
00322                 }
00323             }
00324
00325             // Reset UI state.
00326             listenWithoutUIButtonText.Text = " without UI";
00327             cbLanguageSelection.IsEnabled = true;
00328             btnRecognizeWithUI.IsEnabled = true;
00329             btnRecognizeWithoutUI.IsEnabled = true;
00330         }
00331
00332         /// <summary>
00333         /// Open the Speech, Inking and Typing page under Settings -> Privacy, enabling a user to accept the
00334         /// Microsoft Privacy Policy, and enable personalization.
00335         /// </summary>
00336         /// <param name="sender">Ignored</param>
00337         /// <param name="args">Ignored</param>
00338         private async void openPrivacySettings_Click(Hyperlink sender, HyperlinkClickEventArgs args)
00339         {
00340             await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-speech"));
00341         }
00342     }
00343 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FontNameCollector Member List

This is the complete list of members for FontNameCollector, including all inherited members.
AddRef(void) override | FontNameCollector |
ClearNames() | FontNameCollector |
DrawGlyphRun(_In_opt_ void *clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_MEASURING_MODE measuringMode, _In_ DWRITE_GLYPH_RUN const *glyphRun, _In_ DWRITE_GLYPH_RUN_DESCRIPTION const *glyphRunDescription, _In_opt_ IUnknown *clientDrawingEffect) override | FontNameCollector |
DrawInlineObject(_In_opt_ void *clientDrawingContext, FLOAT originX, FLOAT originY, _In_ IDWriteInlineObject *inlineObject, BOOL isSideways, BOOL isRightToLeft, _In_opt_ IUnknown *clientDrawingEffect) override | FontNameCollector | [inline]
DrawStrikethrough(_In_opt_ void *clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, _In_ DWRITE_STRIKETHROUGH const *strikethrough, _In_opt_ IUnknown *clientDrawingEffect) override | FontNameCollector | [inline]
DrawUnderline(_In_opt_ void *clientDrawingContext, FLOAT baselineOriginX, FLOAT baselineOriginY, _In_ DWRITE_UNDERLINE const *underline, _In_opt_ IUnknown *clientDrawingEffect) override | FontNameCollector | [inline]
GetCurrentTransform(_In_opt_ void *clientDrawingContext, _Out_ DWRITE_MATRIX *transform) override | FontNameCollector |
GetFontNames() | FontNameCollector |
GetPixelsPerDip(_In_opt_ void *clientDrawingContext, _Out_ FLOAT *pixelsPerDip) override | FontNameCollector |
IsPixelSnappingDisabled(_In_opt_ void *clientDrawingContext, _Out_ BOOL *isDisabled) override | FontNameCollector |
m_refCount | FontNameCollector | [private]
m_uniqueFontNames | FontNameCollector | [private]
QueryInterface(REFIID riid, _COM_Outptr_ void **obj) override | FontNameCollector |
Release(void) override | FontNameCollector |
Generated on Fri Nov 15 2024 22:23:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Scenario2_GetPosition.h Source File

  • Geolocation
  • cppwinrt

Scenario2_GetPosition.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_GetPosition.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_GetPosition : Scenario2_GetPositionT<Scenario2_GetPosition>
00019     {
00020         Scenario2_GetPosition();
00021
00022         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00023         fire_and_forget GetGeolocationButtonClicked(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00024         void CancelGetGeolocationButtonClicked(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00025
00026
00027     private:
00028         SDKTemplate::MainPage m_rootPage{ MainPage::Current() };
00029         Windows::Foundation::IAsyncOperation<Windows::Devices::Geolocation::Geoposition> m_pendingOperation;
00030
00031         void UpdateLocationData(Windows::Devices::Geolocation::Geoposition const& position);
00032         void ShowSatelliteData(bool isVisible);
00033     };
00034 }
00035
00036 namespace winrt::SDKTemplate::factory_implementation
00037 {
00038     struct Scenario2_GetPosition : Scenario2_GetPositionT<Scenario2_GetPosition, implementation::Scenario2_GetPosition>
00039     {
00040     };
00041 }
Generated on Fri Nov 15 2024 22:19:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/BackgroundTasks/ToastNotificationHistoryChangedTriggerTask.cs Source File

  • Notifications
  • cs
  • BackgroundTasks

ToastNotificationHistoryChangedTriggerTask.cs

Go to the documentation of this file.
00001 ﻿using Windows.ApplicationModel.Background;
00002 using Windows.UI.Notifications;
00003
00004 namespace BackgroundTasks
00005 {
00006     public sealed class ToastNotificationHistoryChangedTriggerTask : IBackgroundTask
00007     {
00008         public void Run(IBackgroundTaskInstance taskInstance)
00009         {
00010             var details = taskInstance.TriggerDetails as ToastNotificationHistoryChangedTriggerDetail;
00011             if (details == null)
00012                 return;
00013
00014             // We send back the change type, the UI listens to the progress and parses the change type
00015             taskInstance.Progress = (uint)details.ChangeType;
00016         }
00017     }
00018 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario1WinRTComponent/SecureInterfaceMethodResults.h Source File

  • AllJoyn
  • Common
  • Scenario1WinRTComponent

SecureInterfaceMethodResults.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #pragma once
00022
00023 using namespace concurrency;
00024
00025 namespace com { namespace microsoft { namespace Samples { namespace SecureInterface {
00026
00027 ref class SecureInterfaceConsumer;
00028
00029 public ref class SecureInterfaceConcatenateResult sealed
00030 {
00031 public:
00032     property int32 Status
00033     {
00034         int32 get() { return m_status; }
00035     internal:
00036         void set(_In_ int32 value) { m_status = value; }
00037     }
00038
00039     property Platform::String^ OutStr
00040     {
00041         Platform::String^ get() { return m_interfaceMemberOutStr; }
00042     internal:
00043         void set(_In_ Platform::String^ value) { m_interfaceMemberOutStr = value; }
00044     }
00045
00046     static SecureInterfaceConcatenateResult^ CreateSuccessResult(_In_ Platform::String^ interfaceMemberOutStr)
00047     {
00048         auto result = ref new SecureInterfaceConcatenateResult();
00049         result->Status = Windows::Devices::AllJoyn::AllJoynStatus::Ok;
00050         result->OutStr = interfaceMemberOutStr;
00051         result->m_creationContext = Concurrency::task_continuation_context::use_current();
00052         return result;
00053     }
00054
00055     static SecureInterfaceConcatenateResult^ CreateFailureResult(_In_ int32 status)
00056     {
00057         auto result = ref new SecureInterfaceConcatenateResult();
00058         result->Status = status;
00059         return result;
00060     }
00061 internal:
00062     Concurrency::task_continuation_context m_creationContext = Concurrency::task_continuation_context::use_default();
00063
00064 private:
00065     int32 m_status;
00066     Platform::String^ m_interfaceMemberOutStr;
00067 };
00068
00069 public ref class SecureInterfaceJoinSessionResult sealed
00070 {
00071 public:
00072     property int32 Status
00073     {
00074         int32 get() { return m_status; }
00075     internal:
00076         void set(_In_ int32 value) { m_status = value; }
00077     }
00078
00079     property SecureInterfaceConsumer^ Consumer
00080     {
00081         SecureInterfaceConsumer^ get() { return m_consumer; }
00082     internal:
00083         void set(_In_ SecureInterfaceConsumer^ value) { m_consumer = value; }
00084     };
00085
00086 private:
00087     int32 m_status;
00088     SecureInterfaceConsumer^ m_consumer;
00089 };
00090
00091 public ref class SecureInterfaceGetIsUpperCaseEnabledResult sealed
00092 {
00093 public:
00094     property int32 Status
00095     {
00096         int32 get() { return m_status; }
00097     internal:
00098         void set(_In_ int32 value) { m_status = value; }
00099     }
00100
00101     // "Determine if the output of the Concatenate method is returned as upper case string or not"
00102     property bool IsUpperCaseEnabled
00103     {
00104         bool get() { return m_value; }
00105     internal:
00106         void set(_In_ bool value) { m_value = value; }
00107     }
00108
00109     static SecureInterfaceGetIsUpperCaseEnabledResult^ CreateSuccessResult(_In_ bool value)
00110     {
00111         auto result = ref new SecureInterfaceGetIsUpperCaseEnabledResult();
00112         result->Status = Windows::Devices::AllJoyn::AllJoynStatus::Ok;
00113         result->IsUpperCaseEnabled = value;
00114         result->m_creationContext = Concurrency::task_continuation_context::use_current();
00115         return result;
00116     }
00117
00118     static SecureInterfaceGetIsUpperCaseEnabledResult^ CreateFailureResult(_In_ int32 status)
00119     {
00120         auto result = ref new SecureInterfaceGetIsUpperCaseEnabledResult();
00121         result->Status = status;
00122         return result;
00123     }
00124 internal:
00125     Concurrency::task_continuation_context m_creationContext = Concurrency::task_continuation_context::use_default();
00126
00127 private:
00128     int32 m_status;
00129     bool m_value;
00130 };
00131
00132 public ref class SecureInterfaceSetIsUpperCaseEnabledResult sealed
00133 {
00134 public:
00135     property int32 Status
00136     {
00137         int32 get() { return m_status; }
00138     internal:
00139         void set(_In_ int32 value) { m_status = value; }
00140     }
00141
00142     static SecureInterfaceSetIsUpperCaseEnabledResult^ CreateSuccessResult()
00143     {
00144         auto result = ref new SecureInterfaceSetIsUpperCaseEnabledResult();
00145         result->Status = Windows::Devices::AllJoyn::AllJoynStatus::Ok;
00146         result->m_creationContext = Concurrency::task_continuation_context::use_current();
00147         return result;
00148     }
00149
00150     static SecureInterfaceSetIsUpperCaseEnabledResult^ CreateFailureResult(_In_ int32 status)
00151     {
00152         auto result = ref new SecureInterfaceSetIsUpperCaseEnabledResult();
00153         result->Status = status;
00154         return result;
00155     }
00156 internal:
00157     Concurrency::task_continuation_context m_creationContext = Concurrency::task_continuation_context::use_default();
00158
00159 private:
00160     int32 m_status;
00161 };
00162
00163 } } } }
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Content/SpinningCubeRenderer.cpp Source File

  • HolographicVoiceInput
  • cpp
  • Content

SpinningCubeRenderer.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
00012 #include "SpinningCubeRenderer.h"
00013 #include "Common\DirectXHelper.h"
00014
00015 using namespace HolographicVoiceInput;
00016 using namespace Concurrency;
00017 using namespace DirectX;
00018 using namespace Windows::Foundation::Numerics;
00019 using namespace Windows::UI::Input::Spatial;
00020
00021 // Loads vertex and pixel shaders from files and instantiates the cube geometry.
00022 SpinningCubeRenderer::SpinningCubeRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00023     m_deviceResources(deviceResources)
00024 {
00025     // For speech example.
00026     // Set the initial color to white.
00027     m_modelConstantBufferData.color = { 1.f, 1.f, 0.f, 1.f };
00028
00029     CreateDeviceDependentResources();
00030 }
00031
00032 // This function uses a SpatialPointerPose to position the world-locked hologram
00033 // two meters in front of the user's heading.
00034 void SpinningCubeRenderer::PositionHologram(SpatialPointerPose^ pointerPose)
00035 {
00036     if (pointerPose != nullptr)
00037     {
00038         // Get the gaze direction relative to the given coordinate system.
00039         const float3 headPosition    = pointerPose->Head->Position;
00040         const float3 headDirection   = pointerPose->Head->ForwardDirection;
00041
00042         // The hologram is positioned two meters along the user's gaze direction.
00043         constexpr float distanceFromUser    = 2.0f; // meters
00044         const float3 gazeAtTwoMeters        = headPosition + (distanceFromUser * headDirection);
00045
00046         // This will be used as the translation component of the hologram's
00047         // model transform.
00048         SetPosition(gazeAtTwoMeters);
00049     }
00050 }
00051
00052 // Called once per frame. Rotates the cube, and calculates and sets the model matrix
00053 // relative to the position transform indicated by hologramPositionTransform.
00054 void SpinningCubeRenderer::Update(const DX::StepTimer& timer)
00055 {
00056     // Rotate the cube.
00057     // Convert degrees to radians, then convert seconds to rotation angle.
00058     const float    radiansPerSecond = XMConvertToRadians(m_degreesPerSecond);
00059     const double   totalRotation    = timer.GetTotalSeconds() * radiansPerSecond;
00060     const float    radians          = static_cast<float>(fmod(totalRotation, XM_2PI));
00061     const XMMATRIX modelRotation    = XMMatrixRotationY(-radians);
00062
00063     // Position the cube.
00064     const XMMATRIX modelTranslation = XMMatrixTranslationFromVector(XMLoadFloat3(&m_position));
00065
00066     // Multiply to get the transform matrix.
00067     // Note that this transform does not enforce a particular coordinate system. The calling
00068     // class is responsible for rendering this content in a consistent manner.
00069     const XMMATRIX modelTransform   = XMMatrixMultiply(modelRotation, modelTranslation);
00070
00071     // The view and projection matrices are provided by the system; they are associated
00072     // with holographic cameras, and updated on a per-camera basis.
00073     // Here, we provide the model transform for the sample hologram. The model transform
00074     // matrix is transposed to prepare it for the shader.
00075     XMStoreFloat4x4(&m_modelConstantBufferData.model, XMMatrixTranspose(modelTransform));
00076
00077     // Loading is asynchronous. Resources must be created before they can be updated.
00078     if (!m_loadingComplete)
00079     {
00080         return;
00081     }
00082
00083     // Use the D3D device context to update Direct3D device-based resources.
00084     const auto context = m_deviceResources->GetD3DDeviceContext();
00085
00086     // Update the model transform buffer for the hologram.
00087     context->UpdateSubresource(
00088         m_modelConstantBuffer.Get(),
00089         0,
00090         nullptr,
00091         &m_modelConstantBufferData,
00092         0,
00093         0
00094         );
00095 }
00096
00097 // Renders one frame using the vertex and pixel shaders.
00098 // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00099 // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00100 // a pass-through geometry shader is also used to set the render
00101 // target array index.
00102 void SpinningCubeRenderer::Render()
00103 {
00104     // Loading is asynchronous. Resources must be created before drawing can occur.
00105     if (!m_loadingComplete)
00106     {
00107         return;
00108     }
00109
00110     const auto context = m_deviceResources->GetD3DDeviceContext();
00111
00112     // Each vertex is one instance of the VertexPositionColor struct.
00113     const UINT stride = sizeof(VertexPositionColor);
00114     const UINT offset = 0;
00115     context->IASetVertexBuffers(
00116         0,
00117         1,
00118         m_vertexBuffer.GetAddressOf(),
00119         &stride,
00120         &offset
00121         );
00122     context->IASetIndexBuffer(
00123         m_indexBuffer.Get(),
00124         DXGI_FORMAT_R16_UINT, // Each index is one 16-bit unsigned integer (short).
00125         0
00126         );
00127     context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00128     context->IASetInputLayout(m_inputLayout.Get());
00129
00130     // Attach the vertex shader.
00131     context->VSSetShader(
00132         m_vertexShader.Get(),
00133         nullptr,
00134         0
00135         );
00136     // Apply the model constant buffer to the vertex shader.
00137     context->VSSetConstantBuffers(
00138         0,
00139         1,
00140         m_modelConstantBuffer.GetAddressOf()
00141         );
00142
00143     if (!m_usingVprtShaders)
00144     {
00145         // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00146         // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00147         // a pass-through geometry shader is used to set the render target
00148         // array index.
00149         context->GSSetShader(
00150             m_geometryShader.Get(),
00151             nullptr,
00152             0
00153             );
00154     }
00155
00156     // Attach the pixel shader.
00157     context->PSSetShader(
00158         m_pixelShader.Get(),
00159         nullptr,
00160         0
00161         );
00162
00163     // Draw the objects.
00164     context->DrawIndexedInstanced(
00165         m_indexCount,   // Index count per instance.
00166         2,              // Instance count.
00167         0,              // Start index location.
00168         0,              // Base vertex location.
00169         0               // Start instance location.
00170         );
00171 }
00172
00173 void SpinningCubeRenderer::CreateDeviceDependentResources()
00174 {
00175     m_usingVprtShaders = m_deviceResources->GetDeviceSupportsVprt();
00176
00177     // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3::
00178     // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature
00179     // we can avoid using a pass-through geometry shader to set the render
00180     // target array index, thus avoiding any overhead that would be
00181     // incurred by setting the geometry shader stage.
00182     std::wstring vertexShaderFileName = m_usingVprtShaders ? L"ms-appx:///VprtVertexShader.cso" : L"ms-appx:///VertexShader.cso";
00183
00184     // Load shaders asynchronously.
00185     task<std::vector<byte>> loadVSTask = DX::ReadDataAsync(vertexShaderFileName);
00186     task<std::vector<byte>> loadPSTask = DX::ReadDataAsync(L"ms-appx:///PixelShader.cso");
00187
00188     task<std::vector<byte>> loadGSTask;
00189     if (!m_usingVprtShaders)
00190     {
00191         // Load the pass-through geometry shader.
00192         loadGSTask = DX::ReadDataAsync(L"ms-appx:///GeometryShader.cso");
00193     }
00194
00195     // After the vertex shader file is loaded, create the shader and input layout.
00196     task<void> createVSTask = loadVSTask.then([this] (const std::vector<byte>& fileData)
00197     {
00198         DX::ThrowIfFailed(
00199             m_deviceResources->GetD3DDevice()->CreateVertexShader(
00200                 fileData.data(),
00201                 fileData.size(),
00202                 nullptr,
00203                 &m_vertexShader
00204                 )
00205             );
00206
00207         constexpr std::array<D3D11_INPUT_ELEMENT_DESC, 2> vertexDesc =
00208         {{
00209             { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00210             { "COLOR",    0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00211         }};
00212
00213         DX::ThrowIfFailed(
00214             m_deviceResources->GetD3DDevice()->CreateInputLayout(
00215                 vertexDesc.data(),
00216                 vertexDesc.size(),
00217                 fileData.data(),
00218                 fileData.size(),
00219                 &m_inputLayout
00220                 )
00221             );
00222     });
00223
00224     // After the pixel shader file is loaded, create the shader and constant buffer.
00225     task<void> createPSTask = loadPSTask.then([this] (const std::vector<byte>& fileData)
00226     {
00227         DX::ThrowIfFailed(
00228             m_deviceResources->GetD3DDevice()->CreatePixelShader(
00229                 fileData.data(),
00230                 fileData.size(),
00231                 nullptr,
00232                 &m_pixelShader
00233                 )
00234             );
00235
00236         const CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelColorConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00237         DX::ThrowIfFailed(
00238             m_deviceResources->GetD3DDevice()->CreateBuffer(
00239                 &constantBufferDesc,
00240                 nullptr,
00241                 &m_modelConstantBuffer
00242                 )
00243             );
00244     });
00245
00246     task<void> createGSTask;
00247     if (!m_usingVprtShaders)
00248     {
00249         // After the pass-through geometry shader file is loaded, create the shader.
00250         createGSTask = loadGSTask.then([this] (const std::vector<byte>& fileData)
00251         {
00252             DX::ThrowIfFailed(
00253                 m_deviceResources->GetD3DDevice()->CreateGeometryShader(
00254                     fileData.data(),
00255                     fileData.size(),
00256                     nullptr,
00257                     &m_geometryShader
00258                     )
00259                 );
00260         });
00261     }
00262
00263     // Once all shaders are loaded, create the mesh.
00264     task<void> shaderTaskGroup = m_usingVprtShaders ? (createPSTask && createVSTask) : (createPSTask && createVSTask && createGSTask);
00265     task<void> createCubeTask  = shaderTaskGroup.then([this] ()
00266     {
00267         // Load mesh vertices. Each vertex has a position and a color.
00268         // Note that the cube size has changed from the default DirectX app
00269         // template. Windows Holographic is scaled in meters, so to draw the
00270         // cube at a comfortable size we made the cube width 0.2 m (20 cm).
00271         static const std::array<VertexPositionColor, 8> cubeVertices =
00272         {{
00273             { XMFLOAT3(-0.1f, -0.1f, -0.1f), XMFLOAT3(0.0f, 0.0f, 0.0f) },
00274             { XMFLOAT3(-0.1f, -0.1f,  0.1f), XMFLOAT3(0.0f, 0.0f, 1.0f) },
00275             { XMFLOAT3(-0.1f,  0.1f, -0.1f), XMFLOAT3(0.0f, 1.0f, 0.0f) },
00276             { XMFLOAT3(-0.1f,  0.1f,  0.1f), XMFLOAT3(0.0f, 1.0f, 1.0f) },
00277             { XMFLOAT3( 0.1f, -0.1f, -0.1f), XMFLOAT3(1.0f, 0.0f, 0.0f) },
00278             { XMFLOAT3( 0.1f, -0.1f,  0.1f), XMFLOAT3(1.0f, 0.0f, 1.0f) },
00279             { XMFLOAT3( 0.1f,  0.1f, -0.1f), XMFLOAT3(1.0f, 1.0f, 0.0f) },
00280             { XMFLOAT3( 0.1f,  0.1f,  0.1f), XMFLOAT3(1.0f, 1.0f, 1.0f) },
00281         }};
00282
00283         D3D11_SUBRESOURCE_DATA vertexBufferData = {0};
00284         vertexBufferData.pSysMem                = cubeVertices.data();
00285         vertexBufferData.SysMemPitch            = 0;
00286         vertexBufferData.SysMemSlicePitch       = 0;
00287         const CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(VertexPositionColor) * cubeVertices.size(), D3D11_BIND_VERTEX_BUFFER);
00288         DX::ThrowIfFailed(
00289             m_deviceResources->GetD3DDevice()->CreateBuffer(
00290                 &vertexBufferDesc,
00291                 &vertexBufferData,
00292                 &m_vertexBuffer
00293                 )
00294             );
00295
00296         // Load mesh indices. Each trio of indices represents
00297         // a triangle to be rendered on the screen.
00298         // For example: 2,1,0 means that the vertices with indexes
00299         // 2, 1, and 0 from the vertex buffer compose the
00300         // first triangle of this mesh.
00301         // Note that the winding order is clockwise by default.
00302         constexpr std::array<unsigned short, 36> cubeIndices =
00303         {{
00304             2,1,0, // -x
00305             2,3,1,
00306
00307             6,4,5, // +x
00308             6,5,7,
00309
00310             0,1,5, // -y
00311             0,5,4,
00312
00313             2,6,7, // +y
00314             2,7,3,
00315
00316             0,4,6, // -z
00317             0,6,2,
00318
00319             1,3,7, // +z
00320             1,7,5,
00321         }};
00322
00323         m_indexCount = cubeIndices.size();
00324
00325         D3D11_SUBRESOURCE_DATA indexBufferData  = {0};
00326         indexBufferData.pSysMem                 = cubeIndices.data();
00327         indexBufferData.SysMemPitch             = 0;
00328         indexBufferData.SysMemSlicePitch        = 0;
00329         CD3D11_BUFFER_DESC indexBufferDesc(sizeof(unsigned short) * cubeIndices.size(), D3D11_BIND_INDEX_BUFFER);
00330         DX::ThrowIfFailed(
00331         m_deviceResources->GetD3DDevice()->CreateBuffer(
00332                 &indexBufferDesc,
00333                 &indexBufferData,
00334                 &m_indexBuffer
00335                 )
00336             );
00337     });
00338
00339     // Once the cube is loaded, the object is ready to be rendered.
00340     createCubeTask.then([this] ()
00341     {
00342         m_loadingComplete = true;
00343     });
00344 }
00345
00346 void SpinningCubeRenderer::ReleaseDeviceDependentResources()
00347 {
00348     m_loadingComplete  = false;
00349     m_usingVprtShaders = false;
00350     m_vertexShader.Reset();
00351     m_inputLayout.Reset();
00352     m_pixelShader.Reset();
00353     m_geometryShader.Reset();
00354     m_modelConstantBuffer.Reset();
00355     m_vertexBuffer.Reset();
00356     m_indexBuffer.Reset();
00357 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PdfDocument/cpp/Scenario1_Render.xaml.cpp Source File

  • PdfDocument
  • cpp

Scenario1_Render.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_Render.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Concurrency;
00017 using namespace Platform;
00018 using namespace Windows::Data::Pdf;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Storage;
00022 using namespace Windows::Storage::Pickers;
00023 using namespace Windows::Storage::Streams;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::UI::ViewManagement;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Input;
00029 using namespace Windows::UI::Xaml::Media::Imaging;
00030
00031 Scenario1_Render::Scenario1_Render()
00032 {
00033     InitializeComponent();
00034 }
00035
00036 void Scenario1_Render::LoadDocument()
00037 {
00038     LoadButton->IsEnabled = false;
00039
00040     pdfDocument = nullptr;
00041     Output->Source = nullptr;
00042     PageNumberBox->Text = "1";
00043     RenderingPanel->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00044
00045     auto picker = ref new FileOpenPicker();
00046     picker->FileTypeFilter->Append(".pdf");
00047     create_task(picker->PickSingleFileAsync()).then([this](StorageFile^ file)
00048     {
00049         if (file != nullptr)
00050         {
00051             ProgressControl->Visibility = Windows::UI::Xaml::Visibility::Visible;
00052             return create_task(PdfDocument::LoadFromFileAsync(file, PasswordBox->Password));
00053         }
00054         else
00055         {
00056             return task_from_result(static_cast<PdfDocument^>(nullptr));
00057         }
00058     }).then([this](task<PdfDocument^> task)
00059     {
00060         try
00061         {
00062             pdfDocument = task.get();
00063         }
00064         catch (Exception^ ex)
00065         {
00066             switch (ex->HResult)
00067             {
00068             case __HRESULT_FROM_WIN32(ERROR_WRONG_PASSWORD):
00069                 rootPage->NotifyUser("Document is password-protected and password is incorrect.", NotifyType::ErrorMessage);
00070                 break;
00071
00072             case E_FAIL:
00073                 rootPage->NotifyUser("Document is not a valid PDF.", NotifyType::ErrorMessage);
00074                 break;
00075
00076             default:
00077                 // File I/O errors are reported as exceptions.
00078                 rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00079                 break;
00080             }
00081         }
00082
00083         if (pdfDocument != nullptr)
00084         {
00085             RenderingPanel->Visibility = Windows::UI::Xaml::Visibility::Visible;
00086             if (pdfDocument->IsPasswordProtected)
00087             {
00088                 rootPage->NotifyUser("Document is password protected.", NotifyType::StatusMessage);
00089             }
00090             else
00091             {
00092                 rootPage->NotifyUser("Document is not password protected.", NotifyType::StatusMessage);
00093             }
00094             PageCountText->Text = pdfDocument->PageCount.ToString();
00095         }
00096         ProgressControl->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00097         LoadButton->IsEnabled = true;
00098     });
00099 }
00100
00101 void Scenario1_Render::ViewPage()
00102 {
00103     rootPage->NotifyUser("", NotifyType::StatusMessage);
00104
00105     // If the text is not a valid number, then wcstoul returns 0, which is an invalid
00106     // page number, so we don't need to special-case that possibility.
00107     unsigned long pageNumber = wcstoul(PageNumberBox->Text->Data(), nullptr, 10);
00108
00109     if ((pageNumber < 1) || (pageNumber > pdfDocument->PageCount))
00110     {
00111         rootPage->NotifyUser("Invalid page number.", NotifyType::ErrorMessage);
00112         return;
00113     }
00114
00115     Output->Source = nullptr;
00116     ProgressControl->Visibility = Windows::UI::Xaml::Visibility::Visible;
00117
00118     // Convert from 1-based page number to 0-based page index.
00119     unsigned long pageIndex = pageNumber - 1;
00120
00121     PdfPage^ page = pdfDocument->GetPage(pageIndex);
00122
00123     auto stream = ref new InMemoryRandomAccessStream();
00124
00125     IAsyncAction^ renderAction;
00126
00127     switch (Options->SelectedIndex)
00128     {
00129     // View actual size.
00130     case 0:
00131         renderAction = page->RenderToStreamAsync(stream);
00132         break;
00133
00134     // View half size on beige background.
00135     case 1:
00136     {
00137         auto options1 = ref new PdfPageRenderOptions();
00138         options1->BackgroundColor = Windows::UI::Colors::Beige;
00139         options1->DestinationHeight = static_cast<unsigned int>(page->Size.Height / 2);
00140         options1->DestinationWidth = static_cast<unsigned int>(page->Size.Width / 2);
00141         renderAction = page->RenderToStreamAsync(stream, options1);
00142         break;
00143     }
00144
00145     // Crop to center.
00146     case 2:
00147     {
00148         auto options2 = ref new PdfPageRenderOptions();
00149         auto rect = page->Dimensions->TrimBox;
00150         options2->SourceRect = Rect(rect.X + rect.Width / 4, rect.Y + rect.Height / 4, rect.Width / 2, rect.Height / 2);
00151         renderAction = page->RenderToStreamAsync(stream, options2);
00152         break;
00153     }
00154     }
00155
00156     create_task(renderAction).then([this, stream]()
00157     {
00158         // Put the stream in the image.
00159         auto src = ref new BitmapImage();
00160         Output->Source = src;
00161         return create_task(src->SetSourceAsync(stream));
00162     }).then([this]()
00163     {
00164         ProgressControl->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00165     });
00166 }
Generated on Fri Nov 15 2024 22:20:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Launch Member List

This is the complete list of members for Scenario1_Launch, including all inherited members.
Scenario1_Launch() Scenario1_Launch
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cpp/BackgroundTransfer/SampleConfiguration.h Source File

  • BackgroundTransfer
  • cpp
  • BackgroundTransfer

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "BackgroundTransfer";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038         bool TryGetUri(Platform::String^ uriString, Windows::Foundation::Uri^* uri)
00039         {
00040             // Create a Uri instance and catch exceptions related to invalid input. This method returns 'true'
00041             // if the Uri instance was successfully created and 'false' otherwise.
00042             try
00043             {
00044                 *uri = ref new Windows::Foundation::Uri(StringTrimmer::Trim(uriString));
00045                 return true;
00046             }
00047             catch (Platform::NullReferenceException^ exception)
00048             {
00049                 NotifyUser("Error: URI must not be null or empty.", NotifyType::ErrorMessage);
00050             }
00051             catch (Platform::InvalidArgumentException^ exception)
00052             {
00053                 NotifyUser("Error: Invalid URI", NotifyType::ErrorMessage);
00054             }
00055
00056             return false;
00057         }
00058
00059     private:
00060         static Platform::Array<Scenario>^ scenariosInner;
00061     };
00062
00063     public value struct Scenario
00064     {
00065         Platform::String^ Title;
00066         Platform::String^ ClassName;
00067     };
00068 }
00069
00070 class StringTrimmer
00071 {
00072 public:
00073     static Platform::String^ Trim(Platform::String^ s)
00074     {
00075         const WCHAR* first = s->Begin();
00076         const WCHAR* last = s->End();
00077
00078         while (first != last && iswspace(*first))
00079         {
00080             ++first;
00081         }
00082
00083         while (first != last && iswspace(last[-1]))
00084         {
00085             --last;
00086         }
00087
00088         return ref new Platform::String(first, static_cast<unsigned int>(last - first));
00089     }
00090 };
00091
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario04_PostText.cpp Source File

  • HttpClient
  • cppwinrt

Scenario04_PostText.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario04_PostText.h"
00014 #include "Scenario04_PostText.g.cpp"
00015 #include "Helpers.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::UI::Xaml;
00020 using namespace winrt::Windows::UI::Xaml::Navigation;
00021 using namespace winrt::Windows::Web::Http;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario04_PostText::Scenario04_PostText()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     void Scenario04_PostText::OnNavigatedTo(NavigationEventArgs const&)
00031     {
00032         httpClient = Helpers::CreateHttpClientWithCustomHeaders();
00033     }
00034
00035     void Scenario04_PostText::OnNavigatedFrom(NavigationEventArgs const&)
00036     {
00037         httpClient.Close();
00038     }
00039
00040     fire_and_forget Scenario04_PostText::Start_Click(IInspectable const&, RoutedEventArgs const&)
00041     {
00042         auto lifetime = get_strong();
00043
00044         // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00045         // valid, absolute URI, we'll notify the user about the incorrect input.
00046         Uri resourceUri = Helpers::TryParseHttpUri(AddressField().Text());
00047         if (!resourceUri)
00048         {
00049             rootPage.NotifyUser(L"Invalid URI.", NotifyType::ErrorMessage);
00050             return;
00051         }
00052
00053         Helpers::ScenarioStarted(StartButton(), CancelButton(), OutputField());
00054         rootPage.NotifyUser(L"In progress", NotifyType::StatusMessage);
00055
00056         // This sample uses a "try" in order to support cancellation.
00057         // If you don't need to support cancellation, then the "try" is not needed.
00058         try
00059         {
00060             pendingAction = CancelableRequestAsync(resourceUri);
00061             co_await pendingAction;
00062         }
00063         catch (hresult_canceled const&)
00064         {
00065             rootPage.NotifyUser(L"Request canceled.", NotifyType::ErrorMessage);
00066         }
00067
00068         Helpers::ScenarioCompleted(StartButton(), CancelButton());
00069     }
00070
00071     IAsyncAction Scenario04_PostText::CancelableRequestAsync(Uri resourceUri)
00072     {
00073         auto lifetime = get_strong();
00074         auto cancellation = co_await get_cancellation_token();
00075         cancellation.enable_propagation();
00076
00077         HttpRequestResult result = co_await httpClient.TryPostAsync(resourceUri, HttpStringContent(RequestBodyField().Text()));
00078
00079         if (result.Succeeded())
00080         {
00081             co_await Helpers::DisplayTextResultAsync(result.ResponseMessage(), OutputField());
00082
00083             rootPage.NotifyUser(L"Completed", NotifyType::StatusMessage);
00084         }
00085         else
00086         {
00087             Helpers::DisplayWebError(rootPage, result.ExtendedError());
00088         }
00089     }
00090
00091     void Scenario04_PostText::Cancel_Click(IInspectable const&, RoutedEventArgs const&)
00092     {
00093         if (pendingAction)
00094         {
00095             pendingAction.Cancel();
00096         }
00097     }
00098 }
Generated on Fri Nov 15 2024 22:19:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ClientDeviceInformation/cpp/pch.h Source File

  • ClientDeviceInformation
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiScan/cpp/pch.h Source File

  • WiFiScan
  • cpp

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020
00021 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/NetworkChannel.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

NetworkChannel.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007 #pragma once
00008 #include "StspNetwork.h"
00009
00010 namespace Microsoft { namespace Samples { namespace SimpleCommunication { namespace Network {
00011
00012     ref class CNetworkChannel: public INetworkChannel
00013     {
00014     public:
00015         virtual ~CNetworkChannel();
00016
00017     internal:
00018         CNetworkChannel();
00019
00020         // INetworkChannel
00021         virtual Windows::Foundation::IAsyncAction ^SendAsync(_In_ IBufferPacket *pPacket) override;
00022         virtual Windows::Foundation::IAsyncAction ^ReceiveAsync(_In_ IMediaBufferWrapper *pBuffer) override;
00023         virtual void Close() override;
00024         virtual void Disconnect() override;
00025
00026     private protected:
00027
00028         virtual void OnClose() {}
00029
00030         void SetSocket(IStreamSocket ^socket) { _socket = socket; }
00031         IStreamSocket ^GetSocket() { return _socket; }
00032
00033         void CheckClosed()
00034         {
00035             if (_isClosed)
00036             {
00037                 throw ref new Exception(MF_E_SHUTDOWN);
00038             }
00039         }
00040
00041         CritSec _critSec;                // critical section for thread safety
00042
00043     private:
00044         bool _isClosed;
00045         IStreamSocket ^_socket;
00046     };
00047 }}}}
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario04_PostText Member List

This is the complete list of members for Scenario04_PostText, including all inherited members.
Cancel_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario04_PostText |
CancelableRequestAsync(Windows::Foundation::Uri resourceUri) | Scenario04_PostText | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario04_PostText |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario04_PostText |
Scenario04_PostText() | Scenario04_PostText |
Start_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario04_PostText |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Camera.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Camera.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Camera:
00015 // This class defines the position, orientation, and viewing frustum of a camera looking into
00016 // a 3D world. It will generate both the View matrix and Projection matrix. It can also
00017 // provide a pair of Projection matrices to be used when stereoscopic 3D is used.
00018
00019 class Camera
00020 {
00021 public:
00022     Camera();
00023     Camera(Camera const&) = delete;
00024     void operator=(Camera const&) = delete;
00025
00026     void SetViewParams(_In_ DirectX::XMFLOAT3 eye, _In_ DirectX::XMFLOAT3 lookAt, _In_ DirectX::XMFLOAT3 up);
00027     void SetProjParams(_In_ float fieldOfView, _In_ float aspectRatio, _In_ float nearPlane, _In_ float farPlane);
00028
00029     void LookDirection(_In_ DirectX::XMFLOAT3 lookDirection);
00030     void Eye(_In_ DirectX::XMFLOAT3 position);
00031
00032     DirectX::XMMATRIX View();
00033     DirectX::XMMATRIX Projection();
00034     DirectX::XMMATRIX LeftEyeProjection();
00035     DirectX::XMMATRIX RightEyeProjection();
00036     DirectX::XMMATRIX World();
00037     DirectX::XMFLOAT3 Eye();
00038     DirectX::XMFLOAT3 LookAt();
00039     DirectX::XMFLOAT3 Up();
00040     float NearClipPlane();
00041     float FarClipPlane();
00042     float Pitch();
00043     float Yaw();
00044
00045 private:
00046     DirectX::XMFLOAT4X4 m_viewMatrix;
00047     DirectX::XMFLOAT4X4 m_projectionMatrix;
00048     DirectX::XMFLOAT4X4 m_projectionMatrixLeft;
00049     DirectX::XMFLOAT4X4 m_projectionMatrixRight;
00050
00051     DirectX::XMFLOAT4X4 m_inverseView;
00052
00053     DirectX::XMFLOAT3 m_eye;
00054     DirectX::XMFLOAT3 m_lookAt;
00055     DirectX::XMFLOAT3 m_up;
00056     float             m_cameraYawAngle;
00057     float             m_cameraPitchAngle;
00058
00059     float             m_fieldOfView;
00060     float             m_aspectRatio;
00061     float             m_nearPlane;
00062     float             m_farPlane;
00063 };
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 3DPrinting/cppwinrt/SampleConfiguration.cpp Source File

  • 3DPrinting
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation::Collections;
00019 using namespace winrt::SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"3D Printing C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Print a model", xaml_typename<SDKTemplate::Scenario1_Print>() },
00029     Scenario{ L"Launch 3D Builder", xaml_typename<SDKTemplate::Scenario2_Launch>() },
00030 });
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDataVirtualization/cs/SampleConfiguration.cs Source File

  • XamlDataVirtualization
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using DataVirtualizationSample;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Data Virtualization Sample";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Data Virtualization", ClassType=typeof(Scenario1)},
00026             new Scenario() { Title="Selection Management", ClassType=typeof(Scenario2)},
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlMasterDetail/cppwinrt/ItemsDataSource.h Source File

  • XamlMasterDetail
  • cppwinrt

ItemsDataSource.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 namespace winrt::MasterDetailApp
00014 {
00015     struct ItemsDataSource
00016     {
00017         static Windows::Foundation::Collections::IVector<Data::Item> GetAllItems()
00018         {
00019             static auto items = CreateItems();
00020             return items;
00021         }
00022
00023         static Data::Item GetItemById(int id)
00024         {
00025             return GetAllItems().GetAt(id);
00026         }
00027
00028     private:
00029         static Windows::Foundation::Collections::IVector<Data::Item> CreateItems()
00030         {
00031             auto now = winrt::clock::now();
00032
00033             return winrt::single_threaded_vector<Data::Item>({
00034                 Data::Item(0, now, L"Item 1",
00035                     LR"(Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer id facilisis lectus. Cras nec convallis ante, quis pulvinar tellus. Integer dictum accumsan pulvinar. Pellentesque eget enim sodales sapien vestibulum consequat.
00036
00037 Maecenas eu sapien ac urna aliquam dictum.
00038
00039 Nullam eget mattis metus.Donec pharetra, tellus in mattis tincidunt, magna ipsum gravida nibh, vitae lobortis ante odio vel quam.)"),
00040                 Data::Item(1, now, L"Item 2",
00041                 LR"(Quisque accumsan pretium ligula in faucibus. Mauris sollicitudin augue vitae lorem cursus condimentum quis ac mauris. Pellentesque quis turpis non nunc pretium sagittis. Nulla facilisi. Maecenas eu lectus ante. Proin eleifend vel lectus non tincidunt. Fusce condimentum luctus nisi, in elementum ante tincidunt nec.
00042
00043 Aenean in nisl at elit venenatis blandit ut vitae lectus.Praesent in sollicitudin nunc.Pellentesque justo augue, pretium at sem lacinia, scelerisque semper erat.Ut cursus tortor at metus lacinia dapibus.)"),
00044                 Data::Item(2, now, L"Item 3",
00045                 LR"(Ut consequat magna luctus justo egestas vehicula. Integer pharetra risus libero, et posuere justo mattis et.
00046
00047 Proin malesuada, libero vitae aliquam venenatis, diam est faucibus felis, vitae efficitur erat nunc non mauris.Suspendisse at sodales erat.
00048 Aenean vulputate, turpis non tincidunt ornare, metus est sagittis erat, id lobortis orci odio eget quam.Suspendisse ex purus, lobortis quis suscipit a, volutpat vitae turpis.)"),
00049                 Data::Item(3, now, L"Item 4",
00050                 LR"(Duis facilisis, quam ut laoreet commodo, elit ex aliquet massa, non varius tellus lectus et nunc. Donec vitae risus ut ante pretium semper. Phasellus consectetur volutpat orci, eu dapibus turpis. Fusce varius sapien eu mattis pharetra.
00051
00052 Nam vulputate eu erat ornare blandit.Proin eget lacinia erat.Praesent nisl lectus, pretium eget leo et, dapibus dapibus velit.Integer at bibendum mi, et fringilla sem.)"),
00053                 });
00054         }
00055     };
00056 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MultipleViews/cppwinrt/SizePreferenceString.h Source File

  • MultipleViews
  • cppwinrt

SizePreferenceString.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include "SizePreferenceString.g.h"
00004
00005 namespace winrt::SDKTemplate::implementation
00006 {
00007     struct SizePreferenceString : SizePreferenceStringT<SizePreferenceString>
00008     {
00009         SizePreferenceString(Windows::UI::ViewManagement::ViewSizePreference preference, hstring title)
00010             : m_preference(preference), m_title(title)
00011         {
00012         }
00013
00014         hstring Title()
00015         {
00016             return m_title;
00017         }
00018
00019         Windows::UI::ViewManagement::ViewSizePreference Preference()
00020         {
00021             return m_preference;
00022         }
00023
00024     private:
00025         hstring m_title;
00026         Windows::UI::ViewManagement::ViewSizePreference m_preference;
00027     };
00028 }
Generated on Fri Nov 15 2024 22:20:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ControlBase Member List

This is the complete list of members for ControlBase, including all inherited members.
AddChild(const std::shared_ptr< IControl > &object) | ControlBase | [inline, virtual]
ControlBase() | ControlBase |
CreateDeviceDependentResources() | ControlBase | [virtual]
DoCreateDeviceDependentResources()=0 | ControlBase | [protected, pure virtual]
DoReleaseDeviceDependentResources()=0 | ControlBase | [protected, pure virtual]
DoRender()=0 | ControlBase | [protected, pure virtual]
DoUpdate(const DX::StepTimer &timer, HolographicFrame^holographicFrame, SpatialCoordinateSystem^currentCoordinateSystem, SpatialInteractionSourceState^interactionSource, const DirectX::XMMATRIX &parentTransform)=0 | ControlBase | [protected, pure virtual]
GetBoundingBox(DirectX::BoundingOrientedBox &boundingBox) | ControlBase | [inline, virtual]
GetPosition() | ControlBase | [inline, virtual]
GetRotation() | ControlBase | [inline, virtual]
GetScale() | ControlBase | [inline, virtual]
Initialize(const std::shared_ptr< DX::DeviceResources > &deviceResources) | ControlBase | [virtual]
IsEnabled() | ControlBase | [inline, virtual]
IsFocused() | ControlBase | [inline, virtual]
m_boundingBox | ControlBase | [protected]
m_children | ControlBase | [protected]
m_deviceResources | ControlBase | [protected]
m_enabled | ControlBase | [protected]
m_focused | ControlBase | [protected]
m_onAirTapCallback | ControlBase | [protected]
m_position | ControlBase | [protected]
m_rotation | ControlBase | [protected]
m_scale | ControlBase | [protected]
m_transform | ControlBase | [protected]
m_type | ControlBase | [protected]
ReleaseDeviceDependentResources() | ControlBase | [virtual]
Render() | ControlBase | [virtual]
SetEnabled(const bool enabled) | ControlBase | [inline, virtual]
SetOnAirTapCallback(std::function< void()> callback) | ControlBase | [inline, virtual]
SetPosition(Windows::Foundation::Numerics::float3 pos) | ControlBase | [inline, virtual]
SetRotation(Windows::Foundation::Numerics::float3 rot) | ControlBase | [inline, virtual]
SetScale(Windows::Foundation::Numerics::float3 scale) | ControlBase | [inline, virtual]
Type() | ControlBase | [inline, virtual]
Update(const DX::StepTimer &timer, HolographicFrame^holographicFrame, SpatialCoordinateSystem^currentCoordinateSystem, SpatialInteractionSourceState^interactionSource) | ControlBase | [virtual]
Update(const DX::StepTimer &timer, HolographicFrame^holographicFrame, SpatialCoordinateSystem^currentCoordinateSystem, SpatialInteractionSourceState^interactionSource, const DirectX::XMMATRIX &parentTransform) | ControlBase | [virtual]
HolographicMRCSample::IControl::Update(const DX::StepTimer &timer, Windows::Graphics::Holographic::HolographicFrame^holographicFrame, Windows::Perception::Spatial::SpatialCoordinateSystem^currentCoordinateSystem, Windows::UI::Input::Spatial::SpatialInteractionSourceState^interactionSource)=0 | IControl | [pure virtual]
HolographicMRCSample::IControl::Update(const DX::StepTimer &timer, Windows::Graphics::Holographic::HolographicFrame^holographicFrame, Windows::Perception::Spatial::SpatialCoordinateSystem^currentCoordinateSystem, Windows::UI::Input::Spatial::SpatialInteractionSourceState^interactionSource, const DirectX::XMMATRIX &parentTransform)=0 | IControl | [pure virtual]
~ControlBase() | ControlBase | [virtual]
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6_NavToStream Member List

This is the complete list of members for Scenario6_NavToStream, including all inherited members.
myResolver | Scenario6_NavToStream | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario6_NavToStream | [inline, protected]
Scenario6_NavToStream() | Scenario6_NavToStream | [inline]
Generated on Fri Nov 15 2024 22:23:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_AppCapture Member List

This is the complete list of members for Scenario3_AppCapture, including all inherited members.
AllowAppCaptureCheckBox_Toggled(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_AppCapture |
AppCapture_CapturingChanged(Windows::Media::Capture::AppCapture const &, Windows::Foundation::IInspectable const &) | Scenario3_AppCapture |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario3_AppCapture |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario3_AppCapture |
Scenario3_AppCapture() | Scenario3_AppCapture |
UpdateCaptureStatus() | Scenario3_AppCapture | [private]
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MultipleViews/cppwinrt/ViewLifetimeControl.h Source File

  • MultipleViews
  • cppwinrt

ViewLifetimeControl.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "ViewLifetimeControl.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct ViewLifetimeControl : ViewLifetimeControlT<ViewLifetimeControl>
00019     {
00020         ViewLifetimeControl(Windows::UI::Core::CoreWindow const& newWindow);
00021
00022         // Dispatcher for this view. Kept here for sending messages between this view and the main view.
00023         Windows::UI::Core::CoreDispatcher Dispatcher()
00024         {
00025             // This property never changes, so there's no need to lock
00026             return m_dispatcher;
00027         }
00028
00029         // Each view has a unique Id, found using the ApplicationView.Id property or
00030         // ApplicationView.GetApplicationViewIdForCoreWindow method. This id is used in all of the ApplicationViewSwitcher
00031         // and ProjectionManager APIs.
00032         int32_t Id()
00033         {
00034             // This property never changes, so there's no need to lock
00035             return m_viewId;
00036         }
00037
00038         hstring Title();
00039         void Title(hstring const& value);
00040
00041         int32_t StartViewInUse();
00042         int32_t StopViewInUse();
00043
00044         event_token Released(Windows::Foundation::TypedEventHandler<SDKTemplate::ViewLifetimeControl, Windows::Foundation::IInspectable> const& handler);
00045         void Released(event_token const& token);
00046         event_token PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler);
00047         void PropertyChanged(event_token const& token);
00048
00049         static SDKTemplate::ViewLifetimeControl CreateForCurrentView();
00050
00051     private:
00052         // Dispatcher for this view. Kept here for sending messages between this view and the main view.
00053         Windows::UI::Core::CoreDispatcher m_dispatcher{ nullptr };
00054
00055         // Window for this particular view. Used to register and unregister for events
00056         agile_ref<Windows::UI::Core::CoreWindow> m_window;
00057
00058         // Each view has a unique Id, found using the ApplicationView.Id property or
00059         // ApplicationView.GetApplicationViewIdForCoreWindow method. This id is used in all of the ApplicationViewSwitcher
00060         // and ProjectionManager APIs.
00061         int32_t m_viewId;
00062
00063         // The title for the view shown in the list of recently used apps (by setting the title on
00064         // ApplicationView)
00065         hstring m_title;
00066
00067         event<Windows::Foundation::TypedEventHandler<SDKTemplate::ViewLifetimeControl, Windows::Foundation::IInspectable>> m_internalReleased;
00068         event<Windows::UI::Xaml::Data::PropertyChangedEventHandler> m_propertyChanged;
00069
00070         // Tracks if this ViewLifetimeControl object is still valid. If this is true, then the view is in the process
00071         // of closing itself down
00072         bool m_released = false;
00073
00074         // This class uses reference counts to make sure the secondary views isn't closed prematurely.
00075         // Whenever the main view is about to interact with the secondary view, it should take a reference
00076         // by calling "StartViewInUse" on this object. When finished interacting, it should release the reference
00077         // by calling "StopViewInUse". You can see examples of this throughout the sample, especially in
00078         // scenario 1.
00079         int m_refCount = 0;
00080
00081         event_token m_consolidatedToken;
00082
00083         std::mutex m_mutex;
00084
00085         void RegisterForEvents();
00086         void UnregisterForEvents();
00087         void FinalizeRelease();
00088         void ViewConsolidated(Windows::UI::ViewManagement::ApplicationView const& sender, Windows::UI::ViewManagement::ApplicationViewConsolidatedEventArgs const& e);
00089     };
00090 }
00091
00092 namespace winrt::SDKTemplate::factory_implementation
00093 {
00094     struct ViewLifetimeControl : ViewLifetimeControlT<ViewLifetimeControl, implementation::ViewLifetimeControl>
00095     {
00096     };
00097 }
Generated on Fri Nov 15 2024 22:20:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LocalSettingKeys Member List

This is the complete list of members for LocalSettingKeys, including all inherited members.
SyncBackgroundTaskResult | LocalSettingKeys
SyncBackgroundTaskStatus | LocalSettingKeys
Generated on Fri Nov 15 2024 22:23:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ConstantBufferChangeOnResize Member List

This is the complete list of members for ConstantBufferChangeOnResize, including all inherited members.
projection ConstantBufferChangeOnResize
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePickerContracts/cs/FileOpenPicker_PickURLFile.xaml.cs Source File

  • FilePickerContracts
  • cs

FileOpenPicker_PickURLFile.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using SDKTemplate;
00012
00013 using System;
00014 using Windows.Foundation;
00015 using Windows.Storage;
00016 using Windows.Storage.Pickers.Provider;
00017 using Windows.Storage.Streams;
00018 using Windows.UI.Core;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace FilePickerContracts
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class FileOpenPicker_PickURLFile : Page
00029     {
00030         private const string id = "MyUrlFile";
00031         FileOpenPickerUI fileOpenPickerUI = FileOpenPickerPage.Current.fileOpenPickerUI;
00032         CoreDispatcher dispatcher = Window.Current.Dispatcher;
00033
00034         public FileOpenPicker_PickURLFile()
00035         {
00036             this.InitializeComponent();
00037             AddURLFileButton.Click += new RoutedEventHandler(AddUriFileButton_Click);
00038             RemoveURLFileButton.Click += new RoutedEventHandler(RemoveUriFileButton_Click);
00039         }
00040
00041         private void UpdateButtonState(bool fileInBasket)
00042         {
00043             AddURLFileButton.IsEnabled = !fileInBasket;
00044             RemoveURLFileButton.IsEnabled = fileInBasket;
00045         }
00046
00047         protected override void OnNavigatedTo(NavigationEventArgs e)
00048         {
00049             UpdateButtonState(fileOpenPickerUI.ContainsFile(id));
00050         }
00051
00052         private async void AddUriFileButton_Click(object sender, RoutedEventArgs e)
00053         {
00054             const string filename = @"URI.png"; // This will be used as the filename of the StorageFile object that references the specified URI
00055
00056             FileOpenPickerPage.Current.NotifyUser("", NotifyType.StatusMessage);
00057
00058             Uri uri = null;
00059             try
00060             {
00061                 uri = new Uri(URLInput.Text);
00062             }
00063             catch (FormatException)
00064             {
00065                 FileOpenPickerPage.Current.NotifyUser("Please enter a valid URL.", NotifyType.ErrorMessage);
00066             }
00067
00068             if (uri != null)
00069             {
00070                 StorageFile file = await StorageFile.CreateStreamedFileFromUriAsync(filename, uri, RandomAccessStreamReference.CreateFromUri(uri));
00071                 bool inBasket;
00072                 switch (fileOpenPickerUI.AddFile(id, file))
00073                 {
00074                     case AddFileResult.Added:
00075                     case AddFileResult.AlreadyAdded:
00076                         inBasket = true;
00077                         OutputTextBlock.Text = Status.FileAdded;
00078                         break;
00079
00080                     default:
00081                         inBasket = false;
00082                         OutputTextBlock.Text = Status.FileAddFailed;
00083                         break;
00084                 }
00085                 UpdateButtonState(inBasket);
00086             }
00087         }
00088
00089         private void RemoveUriFileButton_Click(object sender, RoutedEventArgs e)
00090         {
00091             if (fileOpenPickerUI.ContainsFile(id))
00092             {
00093                 fileOpenPickerUI.RemoveFile(id);
00094                 OutputTextBlock.Text = Status.FileRemoved;
00095             }
00096             UpdateButtonState(false);
00097         }
00098     }
00099 }
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-I2C/cpp/pch.h Source File

  • IoT-I2C
  • cpp

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020
00021 #include "SampleConfiguration.h"
00022 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialSound/cpp/CardioidSound.cpp Source File

  • SpatialSound
  • cpp

CardioidSound.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013
00014 _Use_decl_annotations_
00015 HRESULT CardioidSound::Initialize(LPCWSTR filename)
00016 {
00017     auto hr = _audioFile.Initialize(filename);
00018     if (SUCCEEDED(hr))
00019     {
00020         // Initialize with "Scaling" fully directional and "Order" with broad radiation pattern.
00021         // As the order goes higher, the cardioid directivity region becomes narrower.
00022         // Any direct path signal outside of the directivity region will be attenuated based on the scaling factor.
00023         // For example, if scaling is set to 1 (fully directional) the direct path signal outside of the directivity
00024         // region will be fully attenuated and only the reflections from the environment will be audible.
00025         hr = ConfigureApo(1.0f, 4.0f);
00026     }
00027     return hr;
00028 }
00029
00030 CardioidSound::~CardioidSound()
00031 {
00032     if (_sourceVoice)
00033     {
00034         _sourceVoice->DestroyVoice();
00035     }
00036 }
00037
00038 _Use_decl_annotations_
00039 HRESULT CardioidSound::ConfigureApo(float scaling, float order)
00040 {
00041     // Directivity is specified at xAPO instance initialization and cannot be changed per frame.
00042     // To change directivity, we'll need to stop audio processing and reinitialize another APO instance with the new directivity.
00043     if (_xaudio2)
00044     {
00045         _xaudio2->StopEngine();
00046         _xaudio2.Reset();
00047     }
00048
00049     if (_hrtfParams)
00050     {
00051         _hrtfParams.Reset();
00052     }
00053
00054     // Cardioid directivity configuration
00055     HrtfDirectivityCardioid cardioid;
00056     cardioid.directivity.type = HrtfDirectivityType::Cardioid;
00057     cardioid.directivity.scaling = scaling;
00058     cardioid.order = order;
00059
00060     // APO intialization
00061     HrtfApoInit apoInit;
00062     apoInit.directivity = &cardioid.directivity;
00063     apoInit.distanceDecay = nullptr;                // This specifies natural distance decay behavior (simulates real world)
00064
00065     // CreateHrtfApo will fail with E_NOTIMPL on unsupported platforms.
00066     ComPtr<IXAPO> xapo;
00067     auto hr = CreateHrtfApo(&apoInit, &xapo);
00068
00069     if (SUCCEEDED(hr))
00070     {
00071         hr = xapo.As(&_hrtfParams);
00072     }
00073
00074     // Set the initial environment.
00075     // Environment settings configure the "distance cues" used to compute the early and late reverberations.
00076     if (SUCCEEDED(hr))
00077     {
00078         hr = _hrtfParams->SetEnvironment(_environment);
00079     }
00080
00081     // Initialize an XAudio2 graph that hosts the HRTF xAPO.
00082     // The source voice is used to submit audio data and control playback.
00083     if (SUCCEEDED(hr))
00084     {
00085         hr = SetupXAudio2(_audioFile.GetFormat(), xapo.Get(), &_xaudio2, &_sourceVoice);
00086     }
00087
00088     // Submit audio data to the source voice
00089     if (SUCCEEDED(hr))
00090     {
00091         XAUDIO2_BUFFER buffer{};
00092         buffer.AudioBytes = static_cast<UINT32>(_audioFile.GetSize());
00093         buffer.pAudioData = _audioFile.GetData();
00094         buffer.LoopCount = XAUDIO2_LOOP_INFINITE;
00095         hr = _sourceVoice->SubmitSourceBuffer(&buffer);
00096     }
00097
00098     return hr;
00099 }
00100
00101 HRESULT CardioidSound::Start()
00102 {
00103     return _sourceVoice->Start();
00104 }
00105
00106 HRESULT CardioidSound::Stop()
00107 {
00108     return _sourceVoice->Stop();
00109 }
00110
00111 _Use_decl_annotations_
00112 HRESULT CardioidSound::SetEnvironment(HrtfEnvironment environment)
00113 {
00114     // Environment can be changed at any time.
00115     return _hrtfParams->SetEnvironment(environment);
00116 }
00117
00118 //
00119 // This method is called on every dispatcher timer tick.
00120 // Source position is provided in right-handed coordinate system and
00121 // source orientation as Yaw, Pitch, Roll in radians. This information
00122 // is relative to the listener's head (listener is always at {0, 0, 0}).
00123 //
00124 _Use_decl_annotations_
00125 HRESULT CardioidSound::OnUpdate(float x, float y, float z, float pitch, float yaw, float roll)
00126 {
00127     auto hr = S_OK;
00128     if (_hrtfParams)
00129     {
00130         auto position = HrtfPosition{ x, y, z };
00131         hr = _hrtfParams->SetSourcePosition(&position);
00132         if (SUCCEEDED(hr))
00133         {
00134             auto sourceOrientation = OrientationFromAngles(pitch, yaw, roll);
00135             hr = _hrtfParams->SetSourceOrientation(&sourceOrientation);
00136         }
00137     }
00138     return hr;
00139 }
00140
00141 // Helper to translate from pitch, yaw, roll to the rotation matrix.
00142 _Use_decl_annotations_
00143 HrtfOrientation CardioidSound::OrientationFromAngles(float pitch, float yaw, float roll)
00144 {
00145     // Negate all angles for right handed coordinate system.
00146     DirectX::XMFLOAT3 angles{ -pitch, -yaw, -roll };
00147     DirectX::XMVECTOR vector = DirectX::XMLoadFloat3(&angles);
00148     DirectX::XMMATRIX rm = DirectX::XMMatrixRotationRollPitchYawFromVector(vector);
00149     DirectX::XMFLOAT3X3 rm33{};
00150     DirectX::XMStoreFloat3x3(&rm33, rm);
00151     return HrtfOrientation{ rm33._11, rm33._12, rm33._13, rm33._21, rm33._22, rm33._23, rm33._31, rm33._32, rm33._33 };
00152 }
00153
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cs/Scenario5_TriggerCFU.xaml.cs Source File

  • FilePicker
  • cs

Scenario5_TriggerCFU.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Storage;
00014 using Windows.Storage.AccessCache;
00015 using Windows.Storage.Pickers;
00016 using Windows.Storage.Provider;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario5_TriggerCFU : Page
00023     {
00024         MainPage rootPage = MainPage.Current;
00025
00026         StorageFile m_afterWriteFile = null;
00027         StorageFile m_beforeReadFile = null;
00028         string m_faToken;
00029
00030         public Scenario5_TriggerCFU()
00031         {
00032             this.InitializeComponent();
00033             UpdateButtons();
00034         }
00035
00036         private void UpdateButtons()
00037         {
00038             WriteToFileButton.IsEnabled = (m_afterWriteFile != null);
00039             WriteToFileWithCFUButton.IsEnabled = (m_afterWriteFile != null);
00040
00041             SaveToFutureAccessListButton.IsEnabled = (m_beforeReadFile != null);
00042             GetFileFromFutureAccessListButton.IsEnabled = !string.IsNullOrEmpty(m_faToken);
00043         }
00044
00045         private async void CreateFileButton_Click(object sender, RoutedEventArgs e)
00046         {
00047             rootPage.NotifyUser("", NotifyType.StatusMessage);
00048
00049             FileSavePicker savePicker = new FileSavePicker();
00050             savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
00051
00052             savePicker.FileTypeChoices.Add("Plain Text", new string[] { ".txt" });
00053             savePicker.SuggestedFileName = "New Document";
00054
00055             m_afterWriteFile = await savePicker.PickSaveFileAsync();
00056             if (m_afterWriteFile != null)
00057             {
00058                 rootPage.NotifyUser("File created.", NotifyType.StatusMessage);
00059             }
00060             else
00061             {
00062                 rootPage.NotifyUser("Operation cancelled.", NotifyType.ErrorMessage);
00063             }
00064             UpdateButtons();
00065         }
00066
00067         private async void WriteToFileButton_Click(Object sender, RoutedEventArgs e)
00068         {
00069             await FileIO.WriteTextAsync(m_afterWriteFile, "The File Picker App just wrote to the file!");
00070             rootPage.NotifyUser("File write complete. If applicable, a WriteActivationMode.AfterWrite activation will occur in approximately 60 seconds on desktop.", NotifyType.StatusMessage);
00071         }
00072
00073         private async void WriteToFileWithExplicitCFUButton_Click(Object sender, RoutedEventArgs e)
00074         {
00075             StorageFile file = m_afterWriteFile;
00076             CachedFileManager.DeferUpdates(file);
00077             await FileIO.WriteTextAsync(file, "The File Picker App just wrote to the file!");
00078             rootPage.NotifyUser("File write complete. Explicitly completing updates.", NotifyType.StatusMessage);
00079             FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
00080             switch (status)
00081             {
00082                 case FileUpdateStatus.Complete:
00083                     rootPage.NotifyUser($"File {file.Name} was saved.", NotifyType.StatusMessage);
00084                     break;
00085
00086                 case FileUpdateStatus.CompleteAndRenamed:
00087                     rootPage.NotifyUser($"File ${file.Name} was renamed and saved.", NotifyType.StatusMessage);
00088                     break;
00089
00090                 default:
00091                     rootPage.NotifyUser($"File ${file.Name} couldn't be saved.", NotifyType.ErrorMessage);
00092                     break;
00093             }
00094         }
00095
00096         private async void PickAFileButton_Click(Object sender, RoutedEventArgs e)
00097         {
00098             rootPage.NotifyUser("", NotifyType.StatusMessage);
00099
00100             FileOpenPicker openPicker = new FileOpenPicker();
00101             openPicker.ViewMode = PickerViewMode.Thumbnail;
00102             openPicker.FileTypeFilter.Add(".txt");
00103
00104             StorageFile file = await openPicker.PickSingleFileAsync();
00105             if (file != null)
00106             {
00107                 m_beforeReadFile = file;
00108                 rootPage.NotifyUser($"Picked file: {file.Name}", NotifyType.StatusMessage);
00109             }
00110             else
00111             {
00112                 m_beforeReadFile = null;
00113                 rootPage.NotifyUser("Operation cancelled.", NotifyType.ErrorMessage);
00114             }
00115             UpdateButtons();
00116         }
00117
00118         private void SaveToFutureAccessListButton_Click(Object sender, RoutedEventArgs e)
00119         {
00120             m_faToken = StorageApplicationPermissions.FutureAccessList.Add(m_beforeReadFile);
00121             rootPage.NotifyUser("Saved to Future Access List", NotifyType.StatusMessage);
00122             m_beforeReadFile = null;
00123             UpdateButtons();
00124         }
00125
00126         private async void GetFileFromFutureAccessListButton_Click(Object sender, RoutedEventArgs e)
00127         {
00128             rootPage.NotifyUser("Getting the file from the Future Access List. If applicable, a ReadActivationMode.BeforeAccess activation will occur in approximately 60 seconds on desktop.", NotifyType.StatusMessage);
00129             StorageFile file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(m_faToken);
00130             if (file != null)
00131             {
00132                 rootPage.NotifyUser($"Retrieved file from Future Access List: {file.Name}", NotifyType.StatusMessage);
00133                 m_beforeReadFile = file;
00134             }
00135             else
00136             {
00137                 rootPage.NotifyUser("Unable to retrieve file from Future Access List.", NotifyType.ErrorMessage);
00138             }
00139             UpdateButtons();
00140         }
00141     }
00142 }
00143
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ExtendedExecution/cpp/Scenario3_LocationTrackingReason.xaml.h Source File

  • ExtendedExecution
  • cpp

Scenario3_LocationTrackingReason.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_LocationTrackingReason.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// Page containing the Extended Execution LocationTracking Reason scenario functions.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class LocationTrackingReason sealed
00024     {
00025     public:
00026         LocationTrackingReason();
00027
00028     protected:
00029         void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00030         void BeginExtendedExecution();
00031         void EndExtendedExecution();
00032
00033     private:
00034         MainPage^ rootPage = MainPage::Current;
00035         Windows::ApplicationModel::ExtendedExecution::ExtendedExecutionSession^ session;
00036         Windows::System::Threading::ThreadPoolTimer^ periodicTimer;
00037         Windows::Foundation::EventRegistrationToken sessionRevokedToken;
00038         Windows::Devices::Geolocation::Geolocator^ geolocator;
00039
00040         void ClearExtendedExecution();
00041         void UpdateUI();
00042         Concurrency::task<void> StartLocationTrackingAsync();
00043         void OnTimer(Windows::System::Threading::ThreadPoolTimer^ timer);
00044         void SessionRevoked(Platform::Object^ sender, Windows::ApplicationModel::ExtendedExecution::ExtendedExecutionRevokedEventArgs^ args);
00045     };
00046 }
Generated on Fri Nov 15 2024 22:19:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cs/Scenario6_ScrollIntoView.xaml.cs Source File

  • XamlListView
  • cs

Scenario6_ScrollIntoView.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.ObjectModel;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario6_ScrollIntoView : Page
00020     {
00021         private ObservableCollection<Item> _items = Item.GetItems(1000);
00022
00023         public Scenario6_ScrollIntoView()
00024         {
00025             InitializeComponent();
00026         }
00027
00028         private void Scroll_Click(object sender, RoutedEventArgs e)
00029         {
00030             int numVal;
00031             if (Int32.TryParse(scrollId.Text, out numVal) && numVal >= 0 && numVal < ItemsListView.Items.Count)
00032             {
00033                 var item = (ComboBoxItem)ScrollAlignment.SelectedItem;
00034                 var Alignment = (ScrollIntoViewAlignment)item.Tag;
00035                 ItemsListView.ScrollIntoView(ItemsListView.Items[numVal], Alignment);
00036                 scrollId.BorderBrush = ValidFormatBrush;
00037             }
00038             else
00039             {
00040                 scrollId.BorderBrush = InvalidFormatBrush;
00041             }
00042         }
00043     }
00044 }
Generated on Fri Nov 15 2024 22:22:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MainPage Member List

This is the complete list of members for MainPage, including all inherited members.
_advancedCapture | MainPage | [private]
_advancedCaptureMode | MainPage | [private]
_captureFolder | MainPage | [private]
_deviceOrientation | MainPage | [private]
_displayInformation | MainPage | [private]
_displayOrientation | MainPage | [private]
_displayRequest | MainPage | [private]
_externalCamera | MainPage | [private]
_isInitialized | MainPage | [private]
_isPreviewing | MainPage | [private]
_mediaCapture | MainPage | [private]
_mirroringPreview | MainPage | [private]
_orientationSensor | MainPage | [private]
_sceneAnalysisEffect | MainPage | [private]
_systemMediaControls | MainPage | [private]
AdvancedCapture_AllPhotosCaptured(AdvancedPhotoCapture sender, object args) | MainPage | [inline, private]
AdvancedCapture_OptionalReferencePhotoCaptured(AdvancedPhotoCapture sender, OptionalReferencePhotoCapturedEventArgs args) | MainPage | [inline, private]
Application_Resuming(object sender, object o) | MainPage | [inline, private]
Application_Suspending(object sender, SuspendingEventArgs e) | MainPage | [inline, private]
CERTAINTY_CAP | MainPage | [private]
CleanSceneAnalysisEffectAsync() | MainPage | [inline, private]
CleanupCameraAsync() | MainPage | [inline, private]
CleanupUiAsync() | MainPage | [inline, private]
ConvertDeviceOrientationToDegrees(SimpleOrientation orientation) | MainPage | [inline, private, static]
ConvertDisplayOrientationToDegrees(DisplayOrientations orientation) | MainPage | [inline, private, static]
ConvertOrientationToPhotoOrientation(SimpleOrientation orientation) | MainPage | [inline, private, static]
CreateSceneAnalysisEffectAsync() | MainPage | [inline, private]
CycleAdvancedCaptureMode() | MainPage | [inline, private]
DisableAdvancedCaptureAsync() | MainPage | [inline, private]
DisplayInformation_OrientationChanged(DisplayInformation sender, object args) | MainPage | [inline, private]
EnableAdvancedCaptureAsync() | MainPage | [inline, private]
FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel) | MainPage | [inline, private, static]
GetCameraOrientation() | MainPage | [inline, private]
HardwareButtons_CameraPressed(object sender, CameraEventArgs e) | MainPage | [inline, private]
InitializeCameraAsync() | MainPage | [inline, private]
MainPage() | MainPage | [inline]
MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) | MainPage | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | MainPage | [inline, protected]
OrientationSensor_OrientationChanged(SimpleOrientationSensor sender, SimpleOrientationSensorOrientationChangedEventArgs args) | MainPage | [inline, private]
PhotoButton_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation) | MainPage | [inline, private, static]
RegisterEventHandlers() | MainPage | [inline, private]
RotationKey | MainPage | [private, static]
SceneAnalysisEffect_SceneAnalyzed(SceneAnalysisEffect sender, SceneAnalyzedEventArgs args) | MainPage | [inline, private]
SetPreviewRotationAsync() | MainPage | [inline, private]
SetupUiAsync() | MainPage | [inline, private]
StartPreviewAsync() | MainPage | [inline, private]
StopPreviewAsync() | MainPage | [inline, private]
SystemMediaControls_PropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs args) | MainPage | [inline, private]
TakeAdvancedCapturePhotoAsync() | MainPage | [inline, private]
UnregisterEventHandlers() | MainPage | [inline, private]
UpdateControlOrientation() | MainPage | [inline, private]
UpdateUi() | MainPage | [inline, private]
Generated on Fri Nov 15 2024 22:23:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7_SyncDevice Member List

This is the complete list of members for Scenario7_SyncDevice, including all inherited members.
backgroundSyncTaskRegistration | Scenario7_SyncDevice | [private]
CancelSync_Click(object sender, RoutedEventArgs e) | Scenario7_SyncDevice | [inline, private]
CancelSyncWithDevice() | Scenario7_SyncDevice | [inline, private]
FindSyncTask() | Scenario7_SyncDevice | [inline, private]
isSyncing | Scenario7_SyncDevice | [private]
navigatedAway | Scenario7_SyncDevice | [private]
OnNavigatedFrom(NavigationEventArgs eventArgs) | Scenario7_SyncDevice | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario7_SyncDevice | [inline, protected]
OnSyncWithDeviceCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args) | Scenario7_SyncDevice | [inline, private]
OnSyncWithDeviceProgress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args) | Scenario7_SyncDevice | [inline, private]
rootPage | Scenario7_SyncDevice | [private]
Scenario7_SyncDevice() | Scenario7_SyncDevice | [inline]
SetupBackgroundTask() | Scenario7_SyncDevice | [inline, private]
StartSyncBackgroundTaskAsync() | Scenario7_SyncDevice | [inline, private]
Sync_Click(object sender, RoutedEventArgs e) | Scenario7_SyncDevice | [inline, private]
syncBackgroundTaskTrigger | Scenario7_SyncDevice | [private, static]
syncDeviceInformation | Scenario7_SyncDevice | [private]
syncDeviceSelector | Scenario7_SyncDevice | [private]
SyncWithDeviceAsync() | Scenario7_SyncDevice | [inline, private]
TaskRequiresBackgroundAccess() | Scenario7_SyncDevice | [inline, static]
UpdateButtonStates() | Scenario7_SyncDevice | [inline, private]
Generated on Fri Nov 15 2024 22:23:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cs/Scenario1_InkCanvasTactileFeedback.xaml.cs Source File

  • PenHaptics
  • cs

Scenario1_InkCanvasTactileFeedback.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014
00015 // This sample shows how the default InkCanvas supports tactile signals.
00016 // Simply begin inking in the InkCanvas with a supported pen and tactile signals
00017 // will automatically be played for each of the different brush types.
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class Scenario1_InkCanvasTactileFeedback : Page
00021     {
00022
00023         public Scenario1_InkCanvasTactileFeedback()
00024         {
00025             InitializeComponent();
00026         }
00027
00028         private void OnSizeChanged(object sender, SizeChangedEventArgs e)
00029         {
00030             outputGrid.Width = RootGrid.ActualWidth;
00031             outputGrid.Height = RootGrid.ActualHeight / 2;
00032         }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:20:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

EventHandlerForDevice Member List

This is the complete list of members for EventHandlerForDevice, including all inherited members.
appResumeEventHandler | EventHandlerForDevice | [private]
appSuspendCallback | EventHandlerForDevice | [private]
appSuspendEventHandler | EventHandlerForDevice | [private]
CloseCurrentlyConnectedDevice() | EventHandlerForDevice | [inline, private]
CloseDevice() | EventHandlerForDevice | [inline]
CreateNewEventHandlerForDevice() | EventHandlerForDevice | [inline, static]
Current | EventHandlerForDevice | [static]
device | EventHandlerForDevice | [private]
Device | EventHandlerForDevice |
deviceAccessEventHandler | EventHandlerForDevice | [private]
DeviceAccessInformation | EventHandlerForDevice |
deviceAccessInformation | EventHandlerForDevice | [private]
deviceAddedEventHandler | EventHandlerForDevice | [private]
deviceCloseCallback | EventHandlerForDevice | [private]
deviceConnectedCallback | EventHandlerForDevice | [private]
DeviceInformation | EventHandlerForDevice |
deviceInformation | EventHandlerForDevice | [private]
deviceRemovedEventHandler | EventHandlerForDevice | [private]
deviceSelector | EventHandlerForDevice | [private]
DeviceSelector | EventHandlerForDevice |
deviceWatcher | EventHandlerForDevice | [private]
EventHandlerForDevice() | EventHandlerForDevice | [inline, private]
eventHandlerForDevice | EventHandlerForDevice | [private, static]
IsDeviceConnected | EventHandlerForDevice |
isEnabledAutoReconnect | EventHandlerForDevice | [private]
IsEnabledAutoReconnect | EventHandlerForDevice |
OnAppResume(Object sender, Object args) | EventHandlerForDevice | [inline, private]
OnAppSuspendCallback | EventHandlerForDevice |
OnAppSuspension(Object sender, SuspendingEventArgs args) | EventHandlerForDevice | [inline, private]
OnDeviceAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs eventArgs) | EventHandlerForDevice | [inline, private]
OnDeviceAdded(DeviceWatcher sender, DeviceInformation deviceInfo) | EventHandlerForDevice | [inline, private]
OnDeviceClose | EventHandlerForDevice |
OnDeviceConnected | EventHandlerForDevice |
OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceInformationUpdate) | EventHandlerForDevice | [inline, private]
OpenDeviceAsync(DeviceInformation deviceInfo, String deviceSelector) | EventHandlerForDevice | [inline]
RegisterForAppEvents() | EventHandlerForDevice | [inline, private]
RegisterForDeviceAccessStatusChange() | EventHandlerForDevice | [inline, private]
RegisterForDeviceWatcherEvents() | EventHandlerForDevice | [inline, private]
rootPage | EventHandlerForDevice | [private]
singletonCreationLock | EventHandlerForDevice | [private, static]
StartDeviceWatcher() | EventHandlerForDevice | [inline, private]
StopDeviceWatcher() | EventHandlerForDevice | [inline, private]
UnregisterFromAppEvents() | EventHandlerForDevice | [inline, private]
UnregisterFromDeviceAccessStatusChange() | EventHandlerForDevice | [inline, private]
UnregisterFromDeviceWatcherEvents() | EventHandlerForDevice | [inline, private]
watcherStarted | EventHandlerForDevice | [private]
watcherSuspended | EventHandlerForDevice | [private]
Generated on Fri Nov 15 2024 22:23:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cppwinrt/pch.cpp Source File

  • DateTimeFormatting
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cppwinrt/SampleConfiguration.h Source File

  • DateTimeFormatting
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     hstring StringJoin(std::wstring const& delimiter, Windows::Foundation::Collections::IVectorView<hstring> const& vector);
00018 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
ButtonClearAll_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ButtonPopToasts_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
Generated on Fri Nov 15 2024 22:23:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

School Member List

This is the complete list of members for School, including all inherited members.
Id() | School | [inline]
Id(hstring const &value) | School | [inline]
idKey | School | [inline, private, static]
m_id | School | [private]
m_name | School | [private]
m_type | School | [private]
Name() | School | [inline]
Name(hstring const &value) | School | [inline]
nameKey | School | [inline, private, static]
School() | School |
School(winrt::Windows::Data::Json::JsonObject const &jsonObject) | School |
schoolKey | School | [inline, private, static]
ToJsonObject() | School |
Type() | School | [inline]
Type(hstring const &value) | School | [inline]
typeKey | School | [inline, private, static]
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AnimationMetrics/cpp/Scenario1_Metrics.xaml.cpp Source File

  • AnimationMetrics
  • cpp

Scenario1_Metrics.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario1_Metrics.xaml.h"
00005 #include <sstream>
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace Platform;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::UI::Xaml;
00013 using namespace Windows::UI::Xaml::Controls;
00014 using namespace Windows::UI::Xaml::Controls::Primitives;
00015 using namespace Windows::UI::Xaml::Data;
00016 using namespace Windows::UI::Xaml::Input;
00017 using namespace Windows::UI::Xaml::Media;
00018 using namespace Windows::UI::Xaml::Navigation;
00019 using namespace Windows::UI::Core::AnimationMetrics;
00020
00021 Scenario1_Metrics::Scenario1_Metrics() : rootPage(MainPage::Current)
00022 {
00023     InitializeComponent();
00024 }
00025
00026 double TimeSpanToMilliseconds(Windows::Foundation::TimeSpan timeSpan)
00027 {
00028     return timeSpan.Duration / 10000.0f;
00029 }
00030
00031 void Scenario1_Metrics::DisplayMetrics(AnimationEffect effect, AnimationEffectTarget target)
00032 {
00033     std::wostringstream ss;
00034     AnimationDescription^ animationDescription = ref new AnimationDescription(effect, target);
00035     ss << "Stagger delay = " << TimeSpanToMilliseconds(animationDescription->StaggerDelay) << "ms" << std::endl;
00036     ss << "Stagger delay factor = " << animationDescription->StaggerDelayFactor << std::endl;
00037     ss << "Delay limit = " << TimeSpanToMilliseconds(animationDescription->DelayLimit) << "ms" << std::endl;
00038     ss << "ZOrder = " << animationDescription->ZOrder << std::endl;
00039     ss << std::endl;
00040     auto animations = animationDescription->Animations;
00041     for (unsigned int i = 0; i < animations->Size; i++)
00042     {
00043         ss << "Animation #" << (i + 1) << ":" << std::endl;
00044         IPropertyAnimation^ animation = animations->GetAt(i);
00045         switch (animation->Type)
00046         {
00047         case PropertyAnimationType::Scale:
00048             {
00049                 ScaleAnimation^ scale = dynamic_cast<ScaleAnimation^>(animation);
00050                 ss << "Type = Scale" << std::endl;
00051                 if (scale->InitialScaleX != nullptr)
00052                 {
00053                     ss << "InitialScaleX = " << scale->InitialScaleX->Value << std::endl;
00054                 }
00055                 if (scale->InitialScaleY != nullptr)
00056                 {
00057                     ss << "InitialScaleY = " << scale->InitialScaleY->Value << std::endl;
00058                 }
00059                 ss << "FinalScaleX = " << scale->FinalScaleX << std::endl;
00060                 ss << "FinalScaleY = " << scale->FinalScaleY << std::endl;
00061                 ss << "Origin = " << scale->NormalizedOrigin.X << ", " << scale->NormalizedOrigin.Y << std::endl;
00062             }
00063             break;
00064         case PropertyAnimationType::Translation:
00065                 ss << "Type = Translation" << std::endl;
00066             break;
00067         case PropertyAnimationType::Opacity:
00068             {
00069                 OpacityAnimation^ opacity = dynamic_cast<OpacityAnimation^>(animation);
00070                 ss << "Type = Opacity" << std::endl;
00071                 if (opacity->InitialOpacity != nullptr)
00072                 {
00073                     ss << "InitialOpacity = " << opacity->InitialOpacity->Value << std::endl;
00074                 }
00075                 ss << "FinalOpacity = " << opacity->FinalOpacity << std::endl;
00076             }
00077             break;
00078         }
00079         ss << "Delay = " << TimeSpanToMilliseconds(animation->Delay) << "ms" << std::endl;
00080         ss << "Duration = " << TimeSpanToMilliseconds(animation->Duration) << "ms" << std::endl;
00081         ss << "Cubic Bezier control points" << std::endl;
00082         ss << "    X1 = " << animation->Control1.X << ", Y1 = " << animation->Control1.Y << std::endl;
00083         ss << "    X2 = " << animation->Control2.X << ", Y2 = " << animation->Control2.Y << std::endl;
00084         ss << std::endl;
00085     }
00086     std::wstring s = ss.str();
00087     auto str = ref new Platform::String(s.c_str());
00088     Metrics->Text = str;
00089 }
00090
00091 void Scenario1_Metrics::Animations_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00092 {
00093     ListBoxItem^ selectedListBoxItem = dynamic_cast<ListBoxItem^>(Animations->SelectedItem);
00094     if (selectedListBoxItem == AddToListAdded)
00095     {
00096         DisplayMetrics(AnimationEffect::AddToList, AnimationEffectTarget::Added);
00097     }
00098     else if (selectedListBoxItem == AddToListAffected)
00099     {
00100         DisplayMetrics(AnimationEffect::AddToList, AnimationEffectTarget::Affected);
00101     }
00102     else if (selectedListBoxItem == EnterPage)
00103     {
00104         DisplayMetrics(AnimationEffect::EnterPage, AnimationEffectTarget::Primary);
00105     }
00106 }
Generated on Fri Nov 15 2024 22:17:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSerialDeviceAccess/cs/Scenario4_Events.xaml.cs Source File

  • CustomSerialDeviceAccess
  • cs

Scenario4_Events.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using Windows.Devices.SerialCommunication;
00016 using SDKTemplate;
00017 using CustomSerialDeviceAccess;
00018
00019 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00020
00021 namespace CustomSerialDeviceAccess
00022 {
00023     /// <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026     public sealed partial class Scenario4_Events : Page
00027     {
00028
00029         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00030         // as NotifyUser()
00031         private MainPage rootPage = MainPage.Current;
00032         public Scenario4_Events()
00033         {
00034             this.InitializeComponent();
00035         }
00036
00037         /// <summary>
00038         /// Invoked when this page is about to be displayed in a Frame.
00039         ///
00040         /// We will enable/disable parts of the UI if the device doesn't support it.
00041         /// </summary>
00042         /// <param name="eventArgs">Event data that describes how this page was reached.  The Parameter
00043         /// property is typically used to configure the page.</param>
00044         protected override void OnNavigatedTo(NavigationEventArgs eventArgs)
00045         {
00046
00047             if (EventHandlerForDevice.Current.Device == null)
00048             {
00049                 EventsScrollViewer.Visibility = Visibility.Collapsed;
00050                 MainPage.Current.NotifyUser("Device is not connected", NotifyType.ErrorMessage);
00051             }
00052             else
00053             {
00054                 if (EventHandlerForDevice.Current.Device.PortName != "")
00055                 {
00056                     MainPage.Current.NotifyUser("Connected to " + EventHandlerForDevice.Current.Device.PortName,
00057                                                 NotifyType.StatusMessage);
00058                 }
00059             }
00060         }
00061
00062         protected override void OnNavigatedFrom(NavigationEventArgs eventArgs)
00063         {
00064             PinChangedToggleSwitch.IsOn = false;
00065             ErrorReceivedToggleSwitch.IsOn = false;
00066         }
00067
00068         private Windows.Foundation.TypedEventHandler<SerialDevice, PinChangedEventArgs> PinChangedEventHandler;
00069         private Windows.Foundation.TypedEventHandler<SerialDevice, ErrorReceivedEventArgs> ErrorReceivedEventHandler;
00070
00071         private void PinChangedEvent(SerialDevice sender, PinChangedEventArgs eventArgs)
00072         {
00073             rootPage.NotifyUser("Pin Changed Event Received", NotifyType.StatusMessage);
00074         }
00075
00076
00077         private void ErrorReceivedEvent(SerialDevice sender, ErrorReceivedEventArgs eventArgs)
00078         {
00079             rootPage.NotifyUser("Error Received Event Received", NotifyType.ErrorMessage);
00080         }
00081
00082         private void PinChangedToggleSwitch_Toggled(object sender, RoutedEventArgs e)
00083         {
00084             if (PinChangedToggleSwitch.IsOn)
00085             {
00086                 PinChangedEventHandler = new Windows.Foundation.TypedEventHandler<SerialDevice, PinChangedEventArgs>(this.PinChangedEvent);
00087                 rootPage.NotifyUser("Pin Changed Event registered", NotifyType.StatusMessage);
00088                 EventHandlerForDevice.Current.Device.PinChanged += PinChangedEventHandler;
00089                 PinChangedValue.Text = "On";
00090             }
00091             else
00092             {
00093                 rootPage.NotifyUser("Pin Changed Event unregistered", NotifyType.StatusMessage);
00094                 EventHandlerForDevice.Current.Device.PinChanged += PinChangedEventHandler;
00095                 PinChangedValue.Text = "Off";
00096             }
00097         }
00098
00099         private void ErrorReceivedToggleSwitch_Toggled(object sender, RoutedEventArgs e)
00100         {
00101             if (ErrorReceivedToggleSwitch.IsOn)
00102             {
00103                 ErrorReceivedEventHandler = new Windows.Foundation.TypedEventHandler<SerialDevice, ErrorReceivedEventArgs>(this.ErrorReceivedEvent);
00104                 rootPage.NotifyUser("Error Received Event registered", NotifyType.StatusMessage);
00105                 EventHandlerForDevice.Current.Device.ErrorReceived += ErrorReceivedEventHandler;
00106                 ErrorReceivedValue.Text = "On";
00107             }
00108             else
00109             {
00110                 rootPage.NotifyUser("Error Received Event unregistered", NotifyType.StatusMessage);
00111                 EventHandlerForDevice.Current.Device.ErrorReceived -= ErrorReceivedEventHandler;
00112                 ErrorReceivedValue.Text = "Off";
00113             }
00114         }
00115     }
00116 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cs/Scenario01_GetText.xaml.cs Source File

  • HttpClient
  • cs

Scenario01_GetText.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading;
00014 using System.Threading.Tasks;
00015 using Windows.Security.Cryptography.Certificates;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019 using Windows.Web.Http;
00020 using Windows.Web.Http.Filters;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario01_GetText : Page
00025     {
00026         MainPage rootPage = MainPage.Current;
00027
00028         private HttpBaseProtocolFilter filter;
00029         private HttpClient httpClient;
00030         private CancellationTokenSource cts;
00031         private bool isFilterUsed;
00032
00033         public Scenario01_GetText()
00034         {
00035             this.InitializeComponent();
00036         }
00037
00038         protected override void OnNavigatedTo(NavigationEventArgs e)
00039         {
00040             // In this scenario we just create an HttpClient instance with default settings. I.e. no custom filters.
00041             // For examples on how to use custom filters see other scenarios.
00042             filter = new HttpBaseProtocolFilter();
00043
00044             // Setting the starting state of the toggle based on the default HTTP version in the OS
00045             if (filter.MaxVersion == HttpVersion.Http20)
00046             {
00047                 MaxHttpVersionToggle.IsOn = true;
00048             }
00049             else
00050             {
00051                 MaxHttpVersionToggle.IsOn = false;
00052             }
00053
00054             httpClient = new HttpClient(filter);
00055             cts = new CancellationTokenSource();
00056             isFilterUsed = false;
00057         }
00058
00059         protected override void OnNavigatedFrom(NavigationEventArgs e)
00060         {
00061             cts.Cancel();
00062             cts.Dispose();
00063             httpClient.Dispose();
00064             filter.Dispose();
00065         }
00066
00067         private async void Start_Click(object sender, RoutedEventArgs e)
00068         {
00069             // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00070             // valid, absolute URI, we'll notify the user about the incorrect input.
00071             Uri resourceUri = Helpers.TryParseHttpUri(AddressField.Text);
00072             if (resourceUri == null)
00073             {
00074                 rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
00075                 return;
00076             }
00077
00078             Helpers.ScenarioStarted(StartButton, CancelButton, OutputField);
00079             rootPage.NotifyUser("In progress", NotifyType.StatusMessage);
00080
00081             if (ReadDefaultRadio.IsChecked.Value)
00082             {
00083                 filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.Default;
00084             }
00085             else if (ReadMostRecentRadio.IsChecked.Value)
00086             {
00087                 filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
00088             }
00089             else if (ReadOnlyFromCacheRadio.IsChecked.Value)
00090             {
00091                 filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.OnlyFromCache;
00092             }
00093             else if (ReadNoCacheRadio.IsChecked.Value)
00094             {
00095                 filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.NoCache;
00096             }
00097
00098             if (WriteDefaultRadio.IsChecked.Value)
00099             {
00100                 filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.Default;
00101             }
00102             else if (WriteNoCacheRadio.IsChecked.Value)
00103             {
00104                 filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
00105             }
00106
00107             // ---------------------------------------------------------------------------
00108             // WARNING: Only test applications should ignore SSL errors.
00109             // In real applications, ignoring server certificate errors can lead to MITM
00110             // attacks (while the connection is secure, the server is not authenticated).
00111             //
00112             // The SetupServer script included with this sample creates a server certificate that is self-signed
00113             // and issued to fabrikam.com, and hence we need to ignore these errors here.
00114             // ---------------------------------------------------------------------------
00115             filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
00116             filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
00117
00118             // This sample uses a "try" in order to support TaskCanceledException.
00119             // If you don't need to support cancellation, then the "try" is not needed.
00120             try
00121             {
00122                 isFilterUsed = true;
00123                 HttpRequestResult result = await httpClient.TryGetAsync(resourceUri).AsTask(cts.Token);
00124
00125                 if (result.Succeeded)
00126                 {
00127                     await Helpers.DisplayTextResultAsync(result.ResponseMessage, OutputField, cts.Token);
00128
00129                     rootPage.NotifyUser(
00130                         "Completed. Response came from " + result.ResponseMessage.Source + ". HTTP version used: " + result.ResponseMessage.Version.ToString() + ".",
00131                         NotifyType.StatusMessage);
00132                 }
00133                 else
00134                 {
00135                     Helpers.DisplayWebError(rootPage, result.ExtendedError);
00136                 }
00137             }
00138             catch (TaskCanceledException)
00139             {
00140                 rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
00141             }
00142
00143             Helpers.ScenarioCompleted(StartButton, CancelButton);
00144         }
00145
00146         private void Cancel_Click(object sender, RoutedEventArgs e)
00147         {
00148             cts.Cancel();
00149             cts.Dispose();
00150
00151             // Re-create the CancellationTokenSource.
00152             cts = new CancellationTokenSource();
00153         }
00154
00155         private void MaxHttpVersionToggle_Toggled(object sender, RoutedEventArgs e)
00156         {
00157             HttpVersion httpVersion = HttpVersion.Http11;
00158             if (MaxHttpVersionToggle.IsOn)
00159             {
00160                 httpVersion = HttpVersion.Http20;
00161             }
00162
00163             // In general, for best memory utilization, HttpBaseProtocolFilter and HttpClient objects should be reused for multiple requests.
00164             // However, if the user has already used the filter object to send at least one request, the HTTP version of the filter cannot be changed.
00165             // Hence, we need to create new client and filter objects.
00166             if (isFilterUsed)
00167             {
00168                 filter.Dispose();
00169                 httpClient.Dispose();
00170                 filter = new HttpBaseProtocolFilter();
00171                 httpClient = new HttpClient(filter);
00172                 isFilterUsed = false;
00173             }
00174             filter.MaxVersion = httpVersion;
00175         }
00176     }
00177 }
Generated on Fri Nov 15 2024 22:19:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cpp/Scenario1_UTF8.xaml.cpp Source File

  • WebSocket
  • cpp

Scenario1_UTF8.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1.xaml.cpp
00014 // Implementation of the Scenario1 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario1_UTF8.xaml.h"
00019
00020 using namespace concurrency;
00021 using namespace Platform;
00022 using namespace SDKTemplate;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::Networking::Sockets;
00026 using namespace Windows::Security::Cryptography::Certificates;
00027 using namespace Windows::Storage::Streams;
00028 using namespace Windows::UI::Core;
00029 using namespace Windows::UI::Xaml;
00030 using namespace Windows::UI::Xaml::Controls;
00031 using namespace Windows::UI::Xaml::Navigation;
00032 using namespace Windows::Web;
00033
00034 Scenario1::Scenario1()
00035 {
00036     InitializeComponent();
00037     UpdateVisualState();
00038 }
00039
00040 void Scenario1::OnNavigatedFrom(NavigationEventArgs^ e)
00041 {
00042     CloseSocket();
00043 }
00044
00045 void Scenario1::UpdateVisualState()
00046 {
00047     if (busy)
00048     {
00049         VisualStateManager::GoToState(this, "Busy", false);
00050     }
00051     else
00052     {
00053         bool connected = (messageWebSocket != nullptr);
00054         VisualStateManager::GoToState(this, connected ? "Connected" : "Disconnected", false);
00055     }
00056 }
00057
00058 void Scenario1::SetBusy(bool value)
00059 {
00060     busy = value;
00061     UpdateVisualState();
00062 }
00063
00064 void Scenario1::OnConnect()
00065 {
00066     SetBusy(true);
00067     ConnectAsync().then([this]()
00068     {
00069         SetBusy(false);
00070     });
00071 }
00072
00073 task<void> Scenario1::ConnectAsync()
00074 {
00075     if (InputField->Text == "")
00076     {
00077         rootPage->NotifyUser("Please specify text to send", NotifyType::ErrorMessage);
00078         return task_from_result();
00079     }
00080
00081     // Validating the URI is required since it was received from an untrusted source (user input).
00082     // The URI is validated by calling TryGetUri() that will return 'nullptr' for strings that are not
00083     // valid WebSocket URIs.
00084     // Note that when enabling the text box users may provide URIs to machines on the intrAnet or intErnet. In
00085     // these cases the app requires the "Private Networks (Client and Server)" or "Internet (Client)" capability respectively.
00086     Uri^ server = rootPage->TryGetUri(ServerAddressField->Text);
00087     if (!server)
00088     {
00089         return task_from_result();
00090     }
00091
00092     messageWebSocket = ref new MessageWebSocket();
00093     messageWebSocket->Control->MessageType = SocketMessageType::Utf8;
00094     messageWebSocket->MessageReceived +=
00095         ref new TypedEventHandler<
00096         MessageWebSocket^,
00097         MessageWebSocketMessageReceivedEventArgs^>(this, &Scenario1::MessageReceived);
00098     messageWebSocket->Closed += ref new TypedEventHandler<IWebSocket^, WebSocketClosedEventArgs^>(this, &Scenario1::OnClosed);
00099
00100     // When connecting to wss:// endpoint, the OS by default performs validation of
00101     // the server certificate based on well-known trusted CAs. We can perform additional custom
00102     // validation if needed.
00103     if (SecureWebSocketCheckBox->IsChecked->Value)
00104     {
00105         // WARNING: Only test applications should ignore SSL errors.
00106         // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle
00107         // attacks. (Although the connection is secure, the server is not authenticated.)
00108         // Note that not all certificate validation errors can be ignored.
00109         // In this case, we are ignoring these errors since the certificate assigned to the localhost
00110         // URI is self-signed and has subject name = fabrikam.com
00111         messageWebSocket->Control->IgnorableServerCertificateErrors->Append(ChainValidationResult::Untrusted);
00112         messageWebSocket->Control->IgnorableServerCertificateErrors->Append(ChainValidationResult::InvalidName);
00113
00114         // Add event handler to listen to the ServerCustomValidationRequested event. This enables performing
00115         // custom validation of the server certificate. The event handler must implement the desired
00116         // custom certificate validation logic.
00117         messageWebSocket->ServerCustomValidationRequested +=
00118             ref new TypedEventHandler<
00119             MessageWebSocket^,
00120             WebSocketServerCustomValidationRequestedEventArgs^>(
00121                 this,
00122                 &Scenario1::OnServerCustomValidationRequested);
00123
00124         // Certificate validation occurs only for secure connections.
00125         if (server->SchemeName != "wss")
00126         {
00127             AppendOutputLine("Note: Certificate validation is performed only for the wss: scheme.");
00128         }
00129     }
00130
00131     AppendOutputLine("Connecting to " + server->DisplayUri + "...");
00132
00133     return create_task(messageWebSocket->ConnectAsync(server))
00134         .then([this](task<void> previousTask)
00135     {
00136         try
00137         {
00138             // Reraise any exception that occurred in the task.
00139             previousTask.get();
00140         }
00141         catch (Exception^ ex)
00142         {
00143             // Error happened during connect operation.
00144             delete messageWebSocket;
00145             messageWebSocket = nullptr;
00146
00147             AppendOutputLine(MainPage::BuildWebSocketError(ex));
00148             AppendOutputLine(ex->Message);
00149             return;
00150         }
00151
00152         // The default DataWriter encoding is Utf8.
00153         messageWriter = ref new DataWriter(messageWebSocket->OutputStream);
00154         rootPage->NotifyUser("Connected", NotifyType::StatusMessage);
00155     });
00156 }
00157
00158 void Scenario1::OnServerCustomValidationRequested(
00159     MessageWebSocket^ sender,
00160     WebSocketServerCustomValidationRequestedEventArgs^ args)
00161 {
00162     // In order to call async APIs in this handler, you must first take a deferral and then
00163     // complete it once you are done validating the certificate.
00164     auto deferral = args->GetDeferral();
00165
00166     // Get the server certificate and certificate chain from the args parameter.
00167     MainPage::AreCertificateAndCertChainValidAsync(args->ServerCertificate, args->ServerIntermediateCertificates)
00168         .then([this, args, deferral](bool isValid)
00169     {
00170         if (!isValid)
00171         {
00172             args->Reject();
00173         }
00174         deferral->Complete();
00175
00176         // Continue on the UI thread so we can update UI.
00177         Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, isValid]()
00178         {
00179             if (isValid)
00180             {
00181                 AppendOutputLine("Custom validation of server certificate passed.");
00182             }
00183             else
00184             {
00185                 AppendOutputLine("Custom validation of server certificate failed.");
00186             }
00187         }));
00188     });
00189 }
00190
00191 void Scenario1::OnSend()
00192 {
00193     SetBusy(true);
00194     SendAsync().then([this]()
00195     {
00196         SetBusy(false);
00197     });
00198 }
00199
00200 task<void> Scenario1::SendAsync()
00201 {
00202     String^ message = InputField->Text;
00203     if (message == "")
00204     {
00205         rootPage->NotifyUser("Please specify text to send", NotifyType::ErrorMessage);
00206         return task_from_result();
00207     }
00208
00209     AppendOutputLine("Sending Message: " + message);
00210
00211     // Buffer any data we want to send.
00212     messageWriter->WriteString(message);
00213
00214     // Send the data as one complete message.
00215     return create_task(messageWriter->StoreAsync())
00216         .then([this](task<unsigned int> previousTask)
00217     {
00218         try
00219         {
00220             // Reraise any exception that occurred in the task.
00221             previousTask.get();
00222         }
00223         catch (Exception^ ex)
00224         {
00225             AppendOutputLine(MainPage::BuildWebSocketError(ex));
00226             AppendOutputLine(ex->Message);
00227             return;
00228         }
00229
00230         rootPage->NotifyUser("Send Complete", NotifyType::StatusMessage);
00231     });
00232 }
00233
00234 void Scenario1::MessageReceived(MessageWebSocket^ sender, MessageWebSocketMessageReceivedEventArgs^ args)
00235 {
00236     // Dispatch the event to the UI thread so we can update UI.
00237     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00238     {
00239         AppendOutputLine("Message Received; Type: " + args->MessageType.ToString());
00240         DataReader^ reader = args->GetDataReader();
00241         reader->UnicodeEncoding = UnicodeEncoding::Utf8;
00242         try
00243         {
00244             String^ read = reader->ReadString(reader->UnconsumedBufferLength);
00245             AppendOutputLine(read);
00246         }
00247         catch (Exception^ ex)
00248         {
00249             AppendOutputLine(MainPage::BuildWebSocketError(ex));
00250             AppendOutputLine(ex->Message);
00251         }
00252         delete reader;
00253     }));
00254 }
00255
00256 void Scenario1::OnDisconnect()
00257 {
00258     SetBusy(true);
00259     rootPage->NotifyUser("Closing", NotifyType::StatusMessage);
00260     CloseSocket();
00261     SetBusy(false);
00262     rootPage->NotifyUser("Closed", NotifyType::StatusMessage);
00263 }
00264
00265 // The method may be triggered remotely by the server sending unsolicited close frame or locally by Close()/delete operator.
00266 void Scenario1::OnClosed(IWebSocket^ sender, WebSocketClosedEventArgs^ args)
00267 {
00268     // Dispatch the event to the UI thread so we do not need to synchronize access to messageWebSocket.
00269     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, sender, args] ()
00270     {
00271         AppendOutputLine("Closed; Code: " + args->Code.ToString() + ", Reason: " + args->Reason);
00272
00273         if (messageWebSocket == sender)
00274         {
00275             CloseSocket();
00276             UpdateVisualState();
00277         }
00278     }));
00279 }
00280
00281 void Scenario1::CloseSocket()
00282 {
00283     if (messageWriter != nullptr)
00284     {
00285         // In order to reuse the socket with another DataWriter, the socket's output stream needs to be detached.
00286         // Otherwise, the DataWriter's destructor will automatically close the stream and all subsequent I/O operations
00287         // invoked on the socket's output stream will fail with ObjectDisposedException.
00288         //
00289         // This is only added for completeness, as this sample closes the socket in the very next code block.
00290         messageWriter->DetachStream();
00291         delete messageWriter;
00292         messageWriter = nullptr;
00293     }
00294
00295     if (messageWebSocket != nullptr)
00296     {
00297         try
00298         {
00299             messageWebSocket->Close(1000, "Closed due to user request.");
00300         }
00301         catch (Exception^ ex)
00302         {
00303             AppendOutputLine(MainPage::BuildWebSocketError(ex));
00304             AppendOutputLine(ex->Message);
00305         }
00306         messageWebSocket = nullptr;
00307     }
00308 }
00309
00310 void Scenario1::AppendOutputLine(String^ value)
00311 {
00312     OutputField->Text += value + "\r\n";
00313 }
Generated on Fri Nov 15 2024 22:22:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialMapping/cpp/HolographicSpatialMappingMain.cpp Source File

  • HolographicSpatialMapping
  • cpp

HolographicSpatialMappingMain.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "HolographicSpatialMappingMain.h"
00014 #include "Common\DirectXHelper.h"
00015
00016 #include <windows.graphics.directx.direct3d11.interop.h>
00017 #include <Collection.h>
00018
00019
00020 using namespace HolographicSpatialMapping;
00021 using namespace WindowsHolographicCodeSamples;
00022
00023 using namespace concurrency;
00024 using namespace Microsoft::WRL;
00025 using namespace Platform;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Foundation::Collections;
00028 using namespace Windows::Foundation::Numerics;
00029 using namespace Windows::Graphics::DirectX;
00030 using namespace Windows::Graphics::DirectX::Direct3D11;
00031 using namespace Windows::Graphics::Holographic;
00032 using namespace Windows::Perception::Spatial;
00033 using namespace Windows::Perception::Spatial::Surfaces;
00034 using namespace Windows::UI::Input::Spatial;
00035 using namespace std::placeholders;
00036
00037 // Loads and initializes application assets when the application is loaded.
00038 HolographicSpatialMappingMain::HolographicSpatialMappingMain(
00039     const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00040     m_deviceResources(deviceResources)
00041 {
00042     // Register to be notified if the device is lost or recreated.
00043     m_deviceResources->RegisterDeviceNotify(this);
00044 }
00045
00046 void HolographicSpatialMappingMain::SetHolographicSpace(
00047     HolographicSpace^ holographicSpace)
00048 {
00049     UnregisterHolographicEventHandlers();
00050
00051     m_holographicSpace = holographicSpace;
00052
00053 #ifdef DRAW_SAMPLE_CONTENT
00054     // Initialize the sample hologram.
00055     m_meshRenderer = std::make_unique<RealtimeSurfaceMeshRenderer>(m_deviceResources);
00056
00057     m_spatialInputHandler = std::make_unique<SpatialInputHandler>();
00058 #endif
00059
00060     // Use the default SpatialLocator to track the motion of the device.
00061     m_locator = SpatialLocator::GetDefault();
00062
00063     // This sample responds to changes in the positional tracking state by cancelling deactivation
00064     // of positional tracking.
00065     m_positionalTrackingDeactivatingToken =
00066         m_locator->PositionalTrackingDeactivating +=
00067             ref new Windows::Foundation::TypedEventHandler<SpatialLocator^, SpatialLocatorPositionalTrackingDeactivatingEventArgs^>(
00068                 std::bind(&HolographicSpatialMappingMain::OnPositionalTrackingDeactivating, this, _1, _2)
00069                 );
00070
00071
00072     // Respond to camera added events by creating any resources that are specific
00073     // to that camera, such as the back buffer render target view.
00074     // When we add an event handler for CameraAdded, the API layer will avoid putting
00075     // the new camera in new HolographicFrames until we complete the deferral we created
00076     // for that handler, or return from the handler without creating a deferral. This
00077     // allows the app to take more than one frame to finish creating resources and
00078     // loading assets for the new holographic camera.
00079     // This function should be registered before the app creates any HolographicFrames.
00080     m_cameraAddedToken =
00081         m_holographicSpace->CameraAdded +=
00082             ref new Windows::Foundation::TypedEventHandler<HolographicSpace^, HolographicSpaceCameraAddedEventArgs^>(
00083                 std::bind(&HolographicSpatialMappingMain::OnCameraAdded, this, _1, _2)
00084                 );
00085
00086     // Respond to camera removed events by releasing resources that were created for that
00087     // camera.
00088     // When the app receives a CameraRemoved event, it releases all references to the back
00089     // buffer right away. This includes render target views, Direct2D target bitmaps, and so on.
00090     // The app must also ensure that the back buffer is not attached as a render target, as
00091     // shown in DeviceResources::ReleaseResourcesForBackBuffer.
00092     m_cameraRemovedToken =
00093         m_holographicSpace->CameraRemoved +=
00094             ref new Windows::Foundation::TypedEventHandler<HolographicSpace^, HolographicSpaceCameraRemovedEventArgs^>(
00095                 std::bind(&HolographicSpatialMappingMain::OnCameraRemoved, this, _1, _2)
00096                 );
00097
00098     // This code sample uses a DeviceAttachedFrameOfReference to have the Spatial Mapping surface observer
00099     // follow along with the device's location.
00100     m_referenceFrame = m_locator->CreateAttachedFrameOfReferenceAtCurrentHeading();
00101
00102     // Notes on spatial tracking APIs:
00103     // * Stationary reference frames are designed to provide a best-fit position relative to the
00104     //   overall space. Individual positions within that reference frame are allowed to drift slightly
00105     //   as the device learns more about the environment.
00106     // * When precise placement of individual holograms is required, a SpatialAnchor should be used to
00107     //   anchor the individual hologram to a position in the real world - for example, a point the user
00108     //   indicates to be of special interest. Anchor positions do not drift, but can be corrected; the
00109     //   anchor will use the corrected position starting in the next frame after the correction has
00110     //   occurred.
00111 }
00112
00113 void HolographicSpatialMappingMain::UnregisterHolographicEventHandlers()
00114 {
00115     if (m_holographicSpace != nullptr)
00116     {
00117         // Clear previous event registrations.
00118
00119         if (m_cameraAddedToken.Value != 0)
00120         {
00121             m_holographicSpace->CameraAdded -= m_cameraAddedToken;
00122             m_cameraAddedToken.Value = 0;
00123         }
00124
00125         if (m_cameraRemovedToken.Value != 0)
00126         {
00127             m_holographicSpace->CameraRemoved -= m_cameraRemovedToken;
00128             m_cameraRemovedToken.Value = 0;
00129         }
00130     }
00131
00132     if (m_locator != nullptr)
00133     {
00134         m_locator->PositionalTrackingDeactivating -= m_positionalTrackingDeactivatingToken;
00135     }
00136
00137     if (m_surfaceObserver != nullptr)
00138     {
00139         m_surfaceObserver->ObservedSurfacesChanged -= m_surfacesChangedToken;
00140     }
00141 }
00142
00143 HolographicSpatialMappingMain::~HolographicSpatialMappingMain()
00144 {
00145     // Deregister device notification.
00146     m_deviceResources->RegisterDeviceNotify(nullptr);
00147
00148     UnregisterHolographicEventHandlers();
00149 }
00150
00151 void HolographicSpatialMappingMain::OnSurfacesChanged(
00152     SpatialSurfaceObserver^ sender,
00153     Object^ args)
00154 {
00155     IMapView<Guid, SpatialSurfaceInfo^>^ const& surfaceCollection = sender->GetObservedSurfaces();
00156
00157     // Process surface adds and updates.
00158     for (const auto& pair : surfaceCollection)
00159     {
00160         auto id = pair->Key;
00161         auto surfaceInfo = pair->Value;
00162
00163         // Choose whether to add, or update the surface.
00164         // In this example, new surfaces are treated differently by highlighting them in a different
00165         // color. This allows you to observe changes in the spatial map that are due to new meshes,
00166         // as opposed to mesh updates.
00167         // In your app, you might choose to process added surfaces differently than updated
00168         // surfaces. For example, you might prioritize processing of added surfaces, and
00169         // defer processing of updates to existing surfaces.
00170         if (m_meshRenderer->HasSurface(id))
00171         {
00172             if (m_meshRenderer->GetLastUpdateTime(id).UniversalTime < surfaceInfo->UpdateTime.UniversalTime)
00173             {
00174                 // Update existing surface.
00175                 m_meshRenderer->UpdateSurface(id, surfaceInfo);
00176             }
00177         }
00178         else
00179         {
00180             // New surface.
00181             m_meshRenderer->AddSurface(id, surfaceInfo);
00182         }
00183     }
00184
00185     // Sometimes, a mesh will fall outside the area that is currently visible to
00186     // the surface observer. In this code sample, we "sleep" any meshes that are
00187     // not included in the surface collection to avoid rendering them.
00188     // The system can including them in the collection again later, in which case
00189     // they will no longer be hidden.
00190     m_meshRenderer->HideInactiveMeshes(surfaceCollection);
00191 }
00192
00193 // Updates the application state once per frame.
00194 HolographicFrame^ HolographicSpatialMappingMain::Update()
00195 {
00196     // Before doing the timer update, there is some work to do per-frame
00197     // to maintain holographic rendering. First, we will get information
00198     // about the current frame.
00199
00200     // The HolographicFrame has information that the app needs in order
00201     // to update and render the current frame. The app begins each new
00202     // frame by calling CreateNextFrame.
00203     HolographicFrame^ holographicFrame = m_holographicSpace->CreateNextFrame();
00204
00205     // Get a prediction of where holographic cameras will be when this frame
00206     // is presented.
00207     HolographicFramePrediction^ prediction = holographicFrame->CurrentPrediction;
00208
00209     // Back buffers can change from frame to frame. Validate each buffer, and recreate
00210     // resource views and depth buffers as needed.
00211     m_deviceResources->EnsureCameraResources(holographicFrame, prediction);
00212
00213     // Next, we get a coordinate system from the attached frame of reference that is
00214     // associated with the current frame. Later, this coordinate system is used for
00215     // for creating the stereo view matrices when rendering the sample content.
00216     SpatialCoordinateSystem^ currentCoordinateSystem = m_referenceFrame->GetStationaryCoordinateSystemAtTimestamp(prediction->Timestamp);
00217
00218     // Only create a surface observer when you need to - do not create a new one each frame.
00219     if (m_surfaceObserver == nullptr)
00220     {
00221         // Initialize the Surface Observer using a valid coordinate system.
00222         if (!m_spatialPerceptionAccessRequested)
00223         {
00224             // The spatial mapping API reads information about the user's environment. The user must
00225             // grant permission to the app to use this capability of the Windows Holographic device.
00226             auto initSurfaceObserverTask = create_task(SpatialSurfaceObserver::RequestAccessAsync());
00227             initSurfaceObserverTask.then([this, currentCoordinateSystem](Windows::Perception::Spatial::SpatialPerceptionAccessStatus status)
00228             {
00229                 switch (status)
00230                 {
00231                 case SpatialPerceptionAccessStatus::Allowed:
00232                     m_surfaceAccessAllowed = true;
00233                     break;
00234                 default:
00235                     // Access was denied. This usually happens because your AppX manifest file does not declare the
00236                     // spatialPerception capability.
00237                     // For info on what else can cause this, see: http://msdn.microsoft.com/library/windows/apps/mt621422.aspx
00238                     m_surfaceAccessAllowed = false;
00239                     break;
00240                 }
00241             });
00242
00243             m_spatialPerceptionAccessRequested = true;
00244         }
00245     }
00246
00247     if (m_surfaceAccessAllowed)
00248     {
00249         SpatialBoundingBox axisAlignedBoundingBox =
00250         {
00251             {  0.f,  0.f, 0.f },
00252             { 20.f, 20.f, 5.f },
00253         };
00254         SpatialBoundingVolume^ bounds = SpatialBoundingVolume::FromBox(currentCoordinateSystem, axisAlignedBoundingBox);
00255
00256         // If status is Allowed, we can create the surface observer.
00257         if (m_surfaceObserver == nullptr)
00258         {
00259             // First, we'll set up the surface observer to use our preferred data formats.
00260             // In this example, a "preferred" format is chosen that is compatible with our precompiled shader pipeline.
00261             m_surfaceMeshOptions = ref new SpatialSurfaceMeshOptions();
00262             IVectorView<DirectXPixelFormat>^ supportedVertexPositionFormats = m_surfaceMeshOptions->SupportedVertexPositionFormats;
00263             unsigned int formatIndex = 0;
00264             if (supportedVertexPositionFormats->IndexOf(DirectXPixelFormat::R16G16B16A16IntNormalized, &formatIndex))
00265             {
00266                 m_surfaceMeshOptions->VertexPositionFormat = DirectXPixelFormat::R16G16B16A16IntNormalized;
00267             }
00268             IVectorView<DirectXPixelFormat>^ supportedVertexNormalFormats = m_surfaceMeshOptions->SupportedVertexNormalFormats;
00269             if (supportedVertexNormalFormats->IndexOf(DirectXPixelFormat::R8G8B8A8IntNormalized, &formatIndex))
00270             {
00271                 m_surfaceMeshOptions->VertexNormalFormat = DirectXPixelFormat::R8G8B8A8IntNormalized;
00272             }
00273
00274             // If you are using a very high detail setting with spatial mapping, it can be beneficial
00275             // to use a 32-bit unsigned integer format for indices instead of the default 16-bit.
00276             // Uncomment the following code to enable 32-bit indices.
00277             //IVectorView<DirectXPixelFormat>^ supportedTriangleIndexFormats = m_surfaceMeshOptions->SupportedTriangleIndexFormats;
00278             //if (supportedTriangleIndexFormats->IndexOf(DirectXPixelFormat::R32UInt, &formatIndex))
00279             //{
00280             //    m_surfaceMeshOptions->TriangleIndexFormat = DirectXPixelFormat::R32UInt;
00281             //}
00282
00283             // Create the observer.
00284             m_surfaceObserver = ref new SpatialSurfaceObserver();
00285             if (m_surfaceObserver)
00286             {
00287                 m_surfaceObserver->SetBoundingVolume(bounds);
00288
00289                 // If the surface observer was successfully created, we can initialize our
00290                 // collection by pulling the current data set.
00291                 auto mapContainingSurfaceCollection = m_surfaceObserver->GetObservedSurfaces();
00292                 for (auto const& pair : mapContainingSurfaceCollection)
00293                 {
00294                     // Store the ID and metadata for each surface.
00295                     auto const& id = pair->Key;
00296                     auto const& surfaceInfo = pair->Value;
00297                     m_meshRenderer->AddSurface(id, surfaceInfo);
00298                 }
00299
00300                 // We then subcribe to an event to receive up-to-date data.
00301                 m_surfacesChangedToken = m_surfaceObserver->ObservedSurfacesChanged +=
00302                     ref new TypedEventHandler<SpatialSurfaceObserver^, Platform::Object^>(
00303                         bind(&HolographicSpatialMappingMain::OnSurfacesChanged, this, _1, _2)
00304                         );
00305             }
00306         }
00307
00308         // Keep the surface observer positioned at the device's location.
00309         m_surfaceObserver->SetBoundingVolume(bounds);
00310
00311         // Note that it is possible to set multiple bounding volumes. Pseudocode:
00312         //     m_surfaceObserver->SetBoundingVolumes(/* iterable collection of bounding volumes*/);
00313         //
00314         // It is also possible to use other bounding shapes - such as a view frustum. Pseudocode:
00315         //     SpatialBoundingVolume^ bounds = SpatialBoundingVolume::FromFrustum(coordinateSystem, viewFrustum);
00316         //     m_surfaceObserver->SetBoundingVolume(bounds);
00317     }
00318
00319 #ifdef DRAW_SAMPLE_CONTENT
00320     // Check for new input state since the last frame.
00321     SpatialInteractionSourceState^ pointerState = m_spatialInputHandler->CheckForInput();
00322     if (pointerState != nullptr)
00323     {
00324         // When a Pressed gesture is detected, the rendering mode will be changed to wireframe.
00325         m_drawWireframe = !m_drawWireframe;
00326     }
00327 #endif
00328
00329     m_timer.Tick([&] ()
00330     {
00331 #ifdef DRAW_SAMPLE_CONTENT
00332         m_meshRenderer->Update(m_timer, currentCoordinateSystem);
00333 #endif
00334     });
00335
00336     // This sample uses default image stabilization settings, and does not set the focus point.
00337
00338     // The holographic frame will be used to get up-to-date view and projection matrices and
00339     // to present the swap chain.
00340     return holographicFrame;
00341 }
00342
00343 // Renders the current frame to each holographic camera, according to the
00344 // current application and spatial positioning state. Returns true if the
00345 // frame was rendered to at least one camera.
00346 bool HolographicSpatialMappingMain::Render(
00347     HolographicFrame^ holographicFrame)
00348 {
00349     // Don't try to render anything before the first Update.
00350     if (m_timer.GetFrameCount() == 0)
00351     {
00352         return false;
00353     }
00354
00355     // Lock the set of holographic camera resources, then draw to each camera
00356     // in this frame.
00357     return m_deviceResources->UseHolographicCameraResources<bool>(
00358         [this, holographicFrame](std::map<UINT32, std::unique_ptr<DX::CameraResources>>& cameraResourceMap)
00359     {
00360         // Up-to-date frame predictions enhance the effectiveness of image stablization and
00361         // allow more accurate positioning of holograms.
00362         holographicFrame->UpdateCurrentPrediction();
00363         HolographicFramePrediction^ prediction = holographicFrame->CurrentPrediction;
00364         SpatialCoordinateSystem^ currentCoordinateSystem = m_referenceFrame->GetStationaryCoordinateSystemAtTimestamp(prediction->Timestamp);
00365
00366         bool atLeastOneCameraRendered = false;
00367         for (auto cameraPose : prediction->CameraPoses)
00368         {
00369             // This represents the device-based resources for a HolographicCamera.
00370             DX::CameraResources* pCameraResources = cameraResourceMap[cameraPose->HolographicCamera->Id].get();
00371
00372             // Get the device context.
00373             const auto context = m_deviceResources->GetD3DDeviceContext();
00374             const auto depthStencilView = pCameraResources->GetDepthStencilView();
00375
00376             // Set render targets to the current holographic camera.
00377             ID3D11RenderTargetView *const targets[1] = { pCameraResources->GetBackBufferRenderTargetView() };
00378             context->OMSetRenderTargets(1, targets, depthStencilView);
00379
00380             // Clear the back buffer and depth stencil view.
00381             context->ClearRenderTargetView(targets[0], DirectX::Colors::Transparent);
00382             context->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
00383
00384             // The view and projection matrices for each holographic camera will change
00385             // every frame. This function refreshes the data in the constant buffer for
00386             // the holographic camera indicated by cameraPose.
00387             pCameraResources->UpdateViewProjectionBuffer(m_deviceResources, cameraPose, currentCoordinateSystem);
00388
00389             // Attach the view/projection constant buffer for this camera to the graphics pipeline.
00390             bool cameraActive = pCameraResources->AttachViewProjectionBuffer(m_deviceResources);
00391
00392 #ifdef DRAW_SAMPLE_CONTENT
00393             // Only render world-locked content when positional tracking is active.
00394             if (cameraActive)
00395             {
00396                 // Draw the sample hologram.
00397                 m_meshRenderer->Render(pCameraResources->IsRenderingStereoscopic(), m_drawWireframe);
00398
00399                 // On versions of the platform that support the CommitDirect3D11DepthBuffer API, we can
00400                 // provide the depth buffer to the system, and it will use depth information to stabilize
00401                 // the image at a per-pixel level.
00402                 static const bool canCommitDirect3D11DepthBuffer =
00403                     Windows::Foundation::Metadata::ApiInformation::IsMethodPresent("Windows.Graphics.Holographic.HolographicCameraRenderingParameters", "CommitDirect3D11DepthBuffer");
00404
00405                 if (canCommitDirect3D11DepthBuffer)
00406                 {
00407                     HolographicCameraRenderingParameters^ renderingParameters = holographicFrame->GetRenderingParameters(cameraPose);
00408                     ComPtr<ID3D11Texture2D> spDepthStencil = pCameraResources->GetDepthStencilTexture2D();
00409
00410                     // Direct3D interop APIs are used to provide the buffer to the WinRT API.
00411                     ComPtr<IDXGIResource1> depthStencilResource;
00412                     DX::ThrowIfFailed(spDepthStencil.As(&depthStencilResource));
00413                     ComPtr<IDXGISurface2> depthDxgiSurface;
00414                     DX::ThrowIfFailed(depthStencilResource->CreateSubresourceSurface(0, &depthDxgiSurface));
00415                     IDirect3DSurface^ depthD3DSurface = CreateDirect3DSurface(depthDxgiSurface.Get());
00416
00417                     // Calling CommitDirect3D11DepthBuffer causes the system to queue Direct3D commands to
00418                     // read the depth buffer. It will then use that information to stabilize the image as
00419                     // the HolographicFrame is presented.
00420                     renderingParameters->CommitDirect3D11DepthBuffer(depthD3DSurface);
00421                 }
00422             }
00423 #endif
00424             atLeastOneCameraRendered = true;
00425         }
00426
00427         return atLeastOneCameraRendered;
00428     });
00429 }
00430
00431 void HolographicSpatialMappingMain::SaveAppState()
00432 {
00433     // This sample does not persist any state between sessions.
00434 }
00435
00436 void HolographicSpatialMappingMain::LoadAppState()
00437 {
00438     // This sample does not persist any state between sessions.
00439 }
00440
00441 // Notifies classes that use Direct3D device resources that the device resources
00442 // need to be released before this method returns.
00443 void HolographicSpatialMappingMain::OnDeviceLost()
00444 {
00445 #ifdef DRAW_SAMPLE_CONTENT
00446     m_meshRenderer->ReleaseDeviceDependentResources();
00447 #endif
00448 }
00449
00450 // Notifies classes that use Direct3D device resources that the device resources
00451 // may now be recreated.
00452 void HolographicSpatialMappingMain::OnDeviceRestored()
00453 {
00454 #ifdef DRAW_SAMPLE_CONTENT
00455     m_meshRenderer->CreateDeviceDependentResources();
00456 #endif
00457 }
00458
00459 void HolographicSpatialMappingMain::OnPositionalTrackingDeactivating(
00460     SpatialLocator^ sender,
00461     SpatialLocatorPositionalTrackingDeactivatingEventArgs^ args)
00462 {
00463     // Without positional tracking, spatial meshes will not be locatable.
00464     args->Canceled = true;
00465 }
00466
00467 void HolographicSpatialMappingMain::OnCameraAdded(
00468     HolographicSpace^ sender,
00469     HolographicSpaceCameraAddedEventArgs^ args)
00470 {
00471     Deferral^ deferral = args->GetDeferral();
00472     HolographicCamera^ holographicCamera = args->Camera;
00473     create_task([this, deferral, holographicCamera] ()
00474     {
00475         // Create device-based resources for the holographic camera and add it to the list of
00476         // cameras used for updates and rendering. Notes:
00477         //   * Since this function may be called at any time, the AddHolographicCamera function
00478         //     waits until it can get a lock on the set of holographic camera resources before
00479         //     adding the new camera. At 60 frames per second this wait should not take long.
00480         //   * A subsequent Update will take the back buffer from the RenderingParameters of this
00481         //     camera's CameraPose and use it to create the ID3D11RenderTargetView for this camera.
00482         //     Content can then be rendered for the HolographicCamera.
00483         m_deviceResources->AddHolographicCamera(holographicCamera);
00484
00485         // Holographic frame predictions will not include any information about this camera until
00486         // the deferral is completed.
00487         deferral->Complete();
00488     });
00489 }
00490
00491 void HolographicSpatialMappingMain::OnCameraRemoved(
00492     HolographicSpace^ sender,
00493     HolographicSpaceCameraRemovedEventArgs^ args)
00494 {
00495     // Before letting this callback return, ensure that all references to the back buffer
00496     // are released.
00497     // Since this function may be called at any time, the RemoveHolographicCamera function
00498     // waits until it can get a lock on the set of holographic camera resources before
00499     // deallocating resources for this camera. At 60 frames per second this wait should
00500     // not take long.
00501     m_deviceResources->RemoveHolographicCamera(args->Camera);
00502 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Nfc/PcscSdk/MifareUltralightAccessHandler.cs Source File

  • Nfc
  • PcscSdk

MifareUltralightAccessHandler.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.Threading.Tasks;
00013 using Windows.Devices.SmartCards;
00014 using System.Runtime.InteropServices.WindowsRuntime;
00015 using Windows.Storage.Streams;
00016
00017 using Pcsc;
00018 using System;
00019
00020 namespace MifareUltralight
00021 {
00022     /// <summary>
00023     /// Access handler class for MifareUL based ICC. It provides wrappers for different MifareUL
00024     /// commands
00025     /// </summary>
00026     public class AccessHandler
00027     {
00028         /// <summary>
00029         /// connection object to smart card
00030         /// </summary>
00031         private SmartCardConnection connectionObject { set; get; }
00032         /// <summary>
00033         /// Class constructor
00034         /// </summary>
00035         /// <param name="ScConnection">
00036         /// connection object to a MifareUL ICC
00037         /// </param>
00038         public AccessHandler(SmartCardConnection ScConnection)
00039         {
00040             connectionObject = ScConnection;
00041         }
00042         /// <summary>
00043         /// Wrapper method to read 16 bytes (4 pages) starting at pageAddress
00044         /// </summary>
00045         /// <param name="pageAddress">
00046         /// start page to read
00047         /// </param>
00048         /// <returns>
00049         /// byte array of 16 bytes
00050         /// </returns>
00051         public async Task<byte[]> ReadAsync(byte pageAddress)
00052         {
00053             var apduRes = await connectionObject.TransceiveAsync(new MifareUltralight.Read(pageAddress));
00054
00055             if (!apduRes.Succeeded)
00056             {
00057                 throw new Exception("Failure reading MIFARE Ultralight card, " + apduRes.ToString());
00058             }
00059
00060             return apduRes.ResponseData;
00061         }
00062         /// <summary>
00063         /// Wrapper method write 4 bytes at the pageAddress
00064         /// </param name="pageAddress">
00065         /// page address to write
00066         /// </param>
00067         /// byte array of the data to write
00068         /// </returns>
00069         public async void WriteAsync(byte pageAddress, byte[] data)
00070         {
00071             if (data.Length != 4)
00072             {
00073                 throw new NotSupportedException();
00074             }
00075
00076             var apduRes = await connectionObject.TransceiveAsync(new MifareUltralight.Write(pageAddress, ref data));
00077
00078             if (!apduRes.Succeeded)
00079             {
00080                 throw new Exception("Failure writing MIFARE Ultralight card, " + apduRes.ToString());
00081             }
00082         }
00083         /// <summary>
00084         /// Wrapper method to perform transparent transceive data to the MifareUL card
00085         /// </summary>
00086         /// <param name="commandData">
00087         /// The command to send to the MifareUL card
00088         /// </param>
00089         /// <returns>
00090         /// byte array of the read data
00091         /// </returns>
00092         public async Task<byte[]> TransparentExchangeAsync(byte[] commandData)
00093         {
00094             byte[] responseData = await connectionObject.TransparentExchangeAsync(commandData);
00095
00096             return responseData;
00097         }
00098         /// <summary>
00099         /// Wrapper method get the MifareUL ICC UID
00100         /// </summary>
00101         /// <returns>
00102         /// byte array UID
00103         /// </returns>
00104         public async Task<byte[]> GetUidAsync()
00105         {
00106             var apduRes = await connectionObject.TransceiveAsync(new MifareUltralight.GetUid());
00107
00108             if (!apduRes.Succeeded)
00109             {
00110                 throw new Exception("Failure getting UID of MIFARE Ultralight card, " + apduRes.ToString());
00111             }
00112
00113             return apduRes.ResponseData;
00114         }
00115     }
00116 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cs/Scenario7.xaml.cs Source File

  • SimpleInk
  • cs

Scenario7.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.Numerics;
00013 using Windows.UI.Core;
00014 using Windows.UI.Input.Inking;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     ///   This scenario demonstrates how to work with InkPresenterStencil objects in a ScrollViewer.
00023     ///   -- Repositioning the InkPresenterStencil on demand
00024     ///   -- Integrating a custom button with stencil functionality alongside the InkToolbar
00025     /// </summary>
00026     public sealed partial class Scenario7 : Page
00027     {
00028         public Scenario7()
00029         {
00030             this.InitializeComponent();
00031
00032             inkCanvas.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Pen;
00033
00034             // Customize the ruler
00035             var ruler = new InkPresenterRuler(inkCanvas.InkPresenter);
00036             ruler.BackgroundColor = Windows.UI.Colors.PaleTurquoise;
00037             ruler.ForegroundColor = Windows.UI.Colors.MidnightBlue;
00038             ruler.Length = 800;
00039             ruler.AreTickMarksVisible = false;
00040             ruler.IsCompassVisible = false;
00041
00042             // Customize the protractor
00043             var protractor = new InkPresenterProtractor(inkCanvas.InkPresenter);
00044             protractor.BackgroundColor = Windows.UI.Colors.Bisque;
00045             protractor.ForegroundColor = Windows.UI.Colors.DarkGreen;
00046             protractor.AccentColor = Windows.UI.Colors.Firebrick;
00047             protractor.AreRaysVisible = false;
00048             protractor.AreTickMarksVisible = false;
00049             protractor.IsAngleReadoutVisible = false;
00050             protractor.IsCenterMarkerVisible = false;
00051         }
00052
00053         private void InkToolbar_IsStencilButtonCheckedChanged(InkToolbar sender, InkToolbarIsStencilButtonCheckedChangedEventArgs args)
00054         {
00055             var stencilButton = (InkToolbarStencilButton)inkToolbar.GetMenuButton(InkToolbarMenuKind.Stencil);
00056             BringIntoViewButton.IsEnabled = stencilButton.IsChecked.Value;
00057         }
00058
00059         protected override void OnNavigatedTo(NavigationEventArgs e)
00060         {
00061             // Make the ink canvas larger than the window, so that we can demonstrate
00062             // scrolling and zooming.
00063             inkCanvas.Width = Window.Current.Bounds.Width * 2;
00064             inkCanvas.Height = Window.Current.Bounds.Height * 2;
00065         }
00066
00067         void OnBringIntoView(object sender, RoutedEventArgs e)
00068         {
00069             // Set stencil origin to Scrollviewer Viewport origin.
00070             // The purpose of this behavior is to allow the user to "grab" the
00071             // stencil and bring it into view no matter where the scrollviewer viewport
00072             // happens to be.  Note that this is accomplished by a simple translation
00073             // that adjusts to the zoom factor.  The additional ZoomFactor term is to
00074             // ensure the scale of the InkPresenterStencil is invariant to Zoom.
00075             Matrix3x2 viewportTransform =
00076                 Matrix3x2.CreateScale(ScrollViewer.ZoomFactor) *
00077                 Matrix3x2.CreateTranslation(
00078                    (float)ScrollViewer.HorizontalOffset,
00079                    (float)ScrollViewer.VerticalOffset) *
00080                 Matrix3x2.CreateScale(1.0f / ScrollViewer.ZoomFactor);
00081
00082             var stencilButton = (InkToolbarStencilButton)inkToolbar.GetMenuButton(InkToolbarMenuKind.Stencil);
00083             switch (stencilButton.SelectedStencil)
00084             {
00085                 case InkToolbarStencilKind.Protractor:
00086                     stencilButton.Protractor.Transform = viewportTransform;
00087                     break;
00088
00089                 case InkToolbarStencilKind.Ruler:
00090                     stencilButton.Ruler.Transform = viewportTransform;
00091                     break;
00092             }
00093         }
00094     }
00095 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cs/BackgroundTask/Scenario5_ApplicationTriggerTask.xaml.cs Source File

  • BackgroundTask
  • cs
  • BackgroundTask

Scenario5_ApplicationTriggerTask.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using SDKTemplate;
00014 using Windows.ApplicationModel.Background;
00015 using Windows.Storage;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class ApplicationTriggerTask : Page
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         MainPage rootPage = MainPage.Current;
00033
00034         // A pointer to the ApplicationTrigger so we can signal it later
00035         ApplicationTrigger trigger = null;
00036
00037         public ApplicationTriggerTask()
00038         {
00039             this.InitializeComponent();
00040         }
00041
00042         /// <summary>
00043         /// Invoked when this page is about to be displayed in a Frame.
00044         /// </summary>
00045         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00046         /// property is typically used to configure the page.</param>
00047         protected override void OnNavigatedTo(NavigationEventArgs e)
00048         {
00049             foreach (var task in BackgroundTaskRegistration.AllTasks)
00050             {
00051                 if (task.Value.Name == BackgroundTaskSample.ApplicationTriggerTaskName)
00052                 {
00053                     AttachProgressAndCompletedHandlers(task.Value);
00054                     BackgroundTaskSample.UpdateBackgroundTaskRegistrationStatus(BackgroundTaskSample.ApplicationTriggerTaskName, true);
00055                     break;
00056                 }
00057             }
00058
00059             trigger = new ApplicationTrigger();
00060             UpdateUI();
00061         }
00062
00063         /// <summary>
00064         /// Register a ApplicationTriggerTask.
00065         /// </summary>
00066         /// <param name="sender"></param>
00067         /// <param name="e"></param>
00068         private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
00069         {
00070             var task = BackgroundTaskSample.RegisterBackgroundTask(BackgroundTaskSample.SampleBackgroundTaskEntryPoint,
00071                                                                    BackgroundTaskSample.ApplicationTriggerTaskName,
00072                                                                    trigger,
00073                                                                    null);
00074             AttachProgressAndCompletedHandlers(task);
00075             UpdateUI();
00076         }
00077
00078         /// <summary>
00079         /// Unregister a ApplicationTriggerTask.
00080         /// </summary>
00081         /// <param name="sender"></param>
00082         /// <param name="e"></param>
00083         private void UnregisterBackgroundTask(object sender, RoutedEventArgs e)
00084         {
00085             BackgroundTaskSample.UnregisterBackgroundTasks(BackgroundTaskSample.ApplicationTriggerTaskName);
00086             BackgroundTaskSample.ApplicationTriggerTaskResult = "";
00087             UpdateUI();
00088         }
00089
00090         /// <summary>
00091         /// Signal a ApplicationTriggerTask.
00092         /// </summary>
00093         /// <param name="sender"></param>
00094         /// <param name="e"></param>
00095         private async void SignalBackgroundTask(object sender, RoutedEventArgs e)
00096         {
00097             // Reset the completion status
00098             var settings = ApplicationData.Current.LocalSettings;
00099             settings.Values.Remove(BackgroundTaskSample.ApplicationTriggerTaskName);
00100
00101             //Signal the ApplicationTrigger
00102             var result = await trigger.RequestAsync();
00103             BackgroundTaskSample.ApplicationTriggerTaskResult = "Signal result: " + result.ToString();
00104             UpdateUI();
00105         }
00106
00107         /// <summary>
00108         /// Attach progress and completed handers to a background task.
00109         /// </summary>
00110         /// <param name="task">The task to attach progress and completed handlers to.</param>
00111         private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
00112         {
00113             task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
00114             task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
00115         }
00116
00117         /// <summary>
00118         /// Handle background task progress.
00119         /// </summary>
00120         /// <param name="task">The task that is reporting progress.</param>
00121         /// <param name="e">Arguments of the progress report.</param>
00122         private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
00123         {
00124             var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00125             {
00126                 var progress = "Progress: " + args.Progress + "%";
00127                 BackgroundTaskSample.ApplicationTriggerTaskProgress = progress;
00128                 UpdateUI();
00129             });
00130         }
00131
00132         /// <summary>
00133         /// Handle background task completion.
00134         /// </summary>
00135         /// <param name="task">The task that is reporting completion.</param>
00136         /// <param name="e">Arguments of the completion report.</param>
00137         private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
00138         {
00139             UpdateUI();
00140         }
00141
00142         /// <summary>
00143         /// Update the scenario UI.
00144         /// </summary>
00145         private async void UpdateUI()
00146         {
00147             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00148             () =>
00149             {
00150                 RegisterButton.IsEnabled = !BackgroundTaskSample.ApplicationTriggerTaskRegistered;
00151                 UnregisterButton.IsEnabled = BackgroundTaskSample.ApplicationTriggerTaskRegistered;
00152                 SignalButton.IsEnabled = BackgroundTaskSample.ApplicationTriggerTaskRegistered & (trigger != null);
00153                 Progress.Text = BackgroundTaskSample.ApplicationTriggerTaskProgress;
00154                 Result.Text = BackgroundTaskSample.ApplicationTriggerTaskResult;
00155                 Status.Text = BackgroundTaskSample.GetBackgroundTaskStatus(BackgroundTaskSample.ApplicationTriggerTaskName);
00156             });
00157         }
00158
00159     }
00160 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SdrOverlayEffect Member List

This is the complete list of members for SdrOverlayEffect, including all inherited members.
CreateSdrOverlayImpl(_Outptr_ IUnknown **ppEffectImpl) | SdrOverlayEffect | [static]
dpi | SdrOverlayEffect |
IFACEMETHODIMP_(UINT32) GetInputCount() const | SdrOverlayEffect |
IFACEMETHODIMP_(ULONG) AddRef() | SdrOverlayEffect |
IFACEMETHODIMP_(ULONG) Release() | SdrOverlayEffect |
Initialize(_In_ ID2D1EffectContext *pContextInternal, _In_ ID2D1TransformGraph *pTransformGraph) | SdrOverlayEffect |
m_constants | SdrOverlayEffect | [private]
m_dpi | SdrOverlayEffect | [private]
m_drawInfo | SdrOverlayEffect | [private]
m_effectContext | SdrOverlayEffect | [private]
m_inputRect | SdrOverlayEffect | [private]
m_refCount | SdrOverlayEffect | [private]
MapInputRectsToOutputRect(_In_reads_(inputRectCount) CONST D2D1_RECT_L *pInputRects, _In_reads_(inputRectCount) CONST D2D1_RECT_L *pInputOpaqueSubRects, UINT32 inputRectCount, _Out_ D2D1_RECT_L *pOutputRect, _Out_ D2D1_RECT_L *pOutputOpaqueSubRect) | SdrOverlayEffect |
MapInvalidRect(UINT32 inputIndex, D2D1_RECT_L invalidInputRect, _Out_ D2D1_RECT_L *pInvalidOutputRect) const | SdrOverlayEffect |
MapOutputRectToInputRects(_In_ const D2D1_RECT_L *pOutputRect, _Out_writes_(inputRectCount) D2D1_RECT_L *pInputRects, UINT32 inputRectCount) const | SdrOverlayEffect |
PrepareForRender(D2D1_CHANGE_TYPE changeType) | SdrOverlayEffect |
QueryInterface(_In_ REFIID riid, _Outptr_ void **ppOutput) | SdrOverlayEffect |
Register(_In_ ID2D1Factory1 *pFactory) | SdrOverlayEffect | [static]
SdrOverlayEffect() | SdrOverlayEffect | [private]
SetDrawInfo(_In_ ID2D1DrawInfo *pRenderInfo) | SdrOverlayEffect |
SetGraph(_In_ ID2D1TransformGraph *pGraph) | SdrOverlayEffect |
UpdateConstants() | SdrOverlayEffect | [private]
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/SampleConfiguration.cpp Source File

  • WindowsAudioSession
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::SDKTemplate;
00019 using namespace winrt::Windows::Foundation::Collections;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"Windows Audio Session API (WASAPI) Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Device Enumeration", xaml_typename <SDKTemplate::Scenario1>() },
00029     Scenario{ L"Audio Rendering with Hardware Offload", xaml_typename<SDKTemplate::Scenario2>() },
00030     Scenario{ L"Audio Rendering with Low Latency", xaml_typename<SDKTemplate::Scenario3>() },
00031     Scenario{ L"PCM Audio Capture", xaml_typename<SDKTemplate::Scenario4>() },
00032 });
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Level.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Level.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Level.h"
00014
00015 bool Level::Update(
00016     float /* time */,
00017     float /* elapsedTime */,
00018     float /* timeRemaining*/,
00019     std::vector<std::shared_ptr<GameObject>> const& objects
00020     )
00021 {
00022     int left = 0;
00023
00024     for (auto&& object : objects)
00025     {
00026         if (object->Active() && object->Target())
00027         {
00028             if (object->Hit())
00029             {
00030                 object->Active(false);
00031             }
00032             else
00033             {
00034                 left++;
00035             }
00036         }
00037     }
00038     return (left == 0);
00039 }
00040
00041 void Level::SaveState(PersistentState& /* state */)
00042 {
00043 }
00044
00045 void Level::LoadState(PersistentState& /* state */)
00046 {
00047 }
00048
00049 std::wstring const& Level::Objective()
00050 {
00051     return m_objective;
00052 }
00053
00054 float Level::TimeLimit()
00055 {
00056     return m_timeLimit;
00057 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAccountManagement/cpp/Scenario2_MSA.xaml.h Source File

  • WebAccountManagement
  • cpp

Scenario2_MSA.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario2_Msa.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     /// <summary>
00011     /// The second scenario. Covers getting an MSA account and getting a token using that account.
00012     /// </summary>
00013     [Windows::Foundation::Metadata::WebHostHidden]
00014     public ref class Scenario2_Msa sealed
00015     {
00016     public:
00017         Scenario2_Msa();
00018     protected:
00019         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs ^ e) override;
00020     private:
00021         MainPage^ rootPage;
00022         void Button_SignIn_Click(Platform::Object ^ sender, Windows::UI::Xaml::RoutedEventArgs ^ e);
00023         void Button_GetTokenSilently_Click(Platform::Object ^ sender, Windows::UI::Xaml::RoutedEventArgs ^ e);
00024         void Button_ManageAccounts_Click(Platform::Object ^ sender, Windows::UI::Xaml::RoutedEventArgs ^ e);
00025         void Button_Reset_Click(Platform::Object ^ sender, Windows::UI::Xaml::RoutedEventArgs ^ e);
00026         void InitalizeAccountsControlDialog();
00027         void CleanupAccountsControlDialog();
00028         void OnAccountCommandsRequested(Windows::UI::ApplicationSettings::AccountsSettingsPane^ sender, Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^ e);
00029         void GetProvidersAndAccounts();
00030         void AddWebAccountProvider(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs ^ e);
00031         void AddWebAccount(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs ^ e);
00032         void AddLinks(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs ^ e);
00033         void WebAccountProviderCommandInvoked(Windows::UI::ApplicationSettings::WebAccountProviderCommand^ command);
00034         void WebAccountCommandInvoked(Windows::UI::ApplicationSettings::WebAccountCommand ^ command, Windows::UI::ApplicationSettings::WebAccountInvokedArgs^ args);
00035         void PrivacyPolicyInvoked(Windows::UI::Popups::IUICommand^ command);
00036         void OtherLinkInvoked(Windows::UI::Popups::IUICommand ^ command);
00037         void AuthenticateWithRequestToken(Windows::Security::Credentials::WebAccountProvider ^ provider, Platform::String^ scope, Platform::String^ clientID);
00038         void AuthenticateWithRequestTokenSilent(Windows::Security::Credentials::WebAccountProvider ^ provider, Platform::String^ scope, Platform::String^ clientID, Windows::Security::Credentials::WebAccount^ account);
00039         void OutputTokenResult(Windows::Security::Authentication::Web::Core::WebTokenRequestResult ^ result);
00040         void SaveAccount(Windows::Security::Credentials::WebAccount ^ account);
00041         void LogoffAndRemoveAccount();
00042
00043         Platform::String^ MICROSOFT_PROVIDER_ID = "https://login.microsoft.com";
00044         Platform::String^ CONSUMER_AUTHORITY = "consumers";
00045         Platform::String^ MSA_SCOPE_REQUESTED = "wl.basic";
00046         Platform::String^ MSA_CLIENT_ID = "none";
00047         Platform::String^ STORED_ACCOUNT_ID_KEY = "accountid";
00048         Windows::Security::Credentials::WebAccountProvider^ m_provider;
00049         Windows::Security::Credentials::WebAccount^ m_account;
00050         Windows::Foundation::EventRegistrationToken m_accountCommandsRequestedRegistrationToken;
00051     };
00052 }
Generated on Fri Nov 15 2024 22:21:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProximitySensor/cpp/SampleConfiguration.h Source File

  • ProximitySensor
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Proximity sensor";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cs/Scenario10.xaml.cs Source File

  • SimpleInk
  • cs

Scenario10.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.IO;
00014 using System.Runtime.InteropServices.WindowsRuntime;
00015 using System.Threading.Tasks;
00016 using Windows.Graphics.Imaging;
00017 using Windows.Storage;
00018 using Windows.Storage.Streams;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Media;
00022 using Windows.UI.Xaml.Media.Imaging;
00023
00024 namespace SDKTemplate
00025 {
00026     public sealed partial class Scenario10 : Page
00027     {
00028         public Scenario10()
00029         {
00030             this.InitializeComponent();
00031
00032             // Initialize the InkCanvas
00033             inkCanvas.InkPresenter.InputDeviceTypes =
00034                 Windows.UI.Core.CoreInputDeviceTypes.Mouse |
00035                 Windows.UI.Core.CoreInputDeviceTypes.Pen;
00036         }
00037
00038         async Task ColorizeCustomButtonAsync(Windows.UI.Color newColor)
00039         {
00040             // Get the bitmap from the png
00041             var sourceUri = new Uri("ms-appx:///Assets/ButtonIconFill.png");
00042             StorageFile storageFile = await StorageFile.GetFileFromApplicationUriAsync(sourceUri);
00043             using (IRandomAccessStream readableStream = await storageFile.OpenAsync(FileAccessMode.Read))
00044             {
00045                 BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(readableStream);
00046
00047                 // Get the raw pixel data from the bitmap
00048                 var dummyTransform = new BitmapTransform();
00049                 PixelDataProvider pixelDataProvider = await bitmapDecoder.GetPixelDataAsync(
00050                     BitmapPixelFormat.Bgra8,
00051                     BitmapAlphaMode.Straight,
00052                     dummyTransform,
00053                     ExifOrientationMode.RespectExifOrientation,
00054                     ColorManagementMode.DoNotColorManage);
00055
00056                 byte[] pixelData = pixelDataProvider.DetachPixelData();
00057
00058                 // We now have direct access to the pixels.
00059                 for (uint row = 0; row < bitmapDecoder.PixelHeight; row++)
00060                 {
00061                     for (uint col = 0; col < bitmapDecoder.PixelWidth; col++)
00062                     {
00063                         var offset = (row * (int)bitmapDecoder.PixelWidth * 4) + (col * 4);
00064
00065                         // Replace the pixel with newColor if it is our color key.
00066                         if ((pixelData[offset] <= 0x01) &&
00067                             (pixelData[offset + 1] <= 0x01) &&
00068                             (pixelData[offset + 2] <= 0x01) &&
00069                             (pixelData[offset + 3] != 0x00))
00070                         {
00071                             pixelData[offset] = newColor.B;
00072                             pixelData[offset + 1] = newColor.G;
00073                             pixelData[offset + 2] = newColor.R;
00074                             pixelData[offset + 3] = newColor.A;
00075                         }
00076                     }
00077                 }
00078
00079                 // Create a bitmap from our modified pixel data.
00080                 var bitmap = new WriteableBitmap((int)bitmapDecoder.PixelWidth, (int)bitmapDecoder.PixelHeight);
00081
00082                 using (Stream pixelStream = bitmap.PixelBuffer.AsStream())
00083                 {
00084                     await pixelStream.WriteAsync(pixelData, 0, pixelData.Length);
00085                     pixelStream.Flush();
00086                     bitmap.Invalidate();
00087                 }
00088
00089                 CustomButtonFill.Source = bitmap;
00090             }
00091         }
00092
00093         private async void inkToolbar_InkDrawingAttributesChanged(InkToolbar sender, object args)
00094         {
00095             // Change the color of the button icon for the calligraphic pen button
00096             if (CalligraphicPenButton == inkToolbar.ActiveTool)
00097             {
00098                 await ColorizeCustomButtonAsync(sender.InkDrawingAttributes.Color);
00099             }
00100         }
00101
00102         private async void inkToolbar_Loaded(object sender, RoutedEventArgs e)
00103         {
00104             var selectedBrush = (SolidColorBrush)CalligraphicPenButton.SelectedBrush;
00105             await ColorizeCustomButtonAsync(selectedBrush.Color);
00106         }
00107
00108         private void OnSizeChanged(object sender, SizeChangedEventArgs e)
00109         {
00110             HelperFunctions.UpdateCanvasSize(RootGrid, outputGrid, inkCanvas);
00111         }
00112     }
00113 }
Generated on Fri Nov 15 2024 22:18:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ToneSampleGenerator Member List

This is the complete list of members for ToneSampleGenerator, including all inherited members.
FillSampleBuffer(UINT32 BytesToRead, BYTE *Data) | ToneSampleGenerator |
Flush() | ToneSampleGenerator |
GenerateSampleBuffer(DWORD Frequency, UINT32 FramesPerPeriod, WAVEFORMATEX *wfx) | ToneSampleGenerator |
GenerateSineSamples(BYTE *Buffer, size_t BufferLength, DWORD Frequency, WORD ChannelCount, DWORD SamplesPerSecond, double Amplitude, double *InitialTheta) | ToneSampleGenerator | [private]
GetBufferLength() | ToneSampleGenerator | [inline]
IsEOF() | ToneSampleGenerator | [inline]
m_SampleQueue | ToneSampleGenerator | [private]
m_SampleQueueTail | ToneSampleGenerator | [private]
ToneSampleGenerator() | ToneSampleGenerator |
~ToneSampleGenerator() | ToneSampleGenerator |
Generated on Fri Nov 15 2024 22:23:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AnimationMetrics/cpp/pch.h Source File

  • AnimationMetrics
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Personalization/cpp/SampleConfiguration.cpp Source File

  • Personalization
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Set lock screen image", "SDKTemplate.SetLockScreenImage" },
00012 };
Generated on Fri Nov 15 2024 22:17:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cpp/Scenario1_CurrentActivity.xaml.cpp Source File

  • ActivitySensor
  • cpp

Scenario1_CurrentActivity.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_CurrentActivity.xaml.cpp
00014 // Implementation of the Scenario1_CurrentActivity class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario1_CurrentActivity.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Concurrency;
00023 using namespace Platform;
00024 using namespace Windows::Devices::Enumeration;
00025 using namespace Windows::Devices::Sensors;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Globalization::DateTimeFormatting;
00028 using namespace Windows::UI::Core;
00029 using namespace Windows::UI::Xaml;
00030 using namespace Windows::UI::Xaml::Controls;
00031
00032 Scenario1_CurrentActivity::Scenario1_CurrentActivity() : rootPage(MainPage::Current)
00033 {
00034     InitializeComponent();
00035 }
00036
00037 void Scenario1_CurrentActivity::ScenarioGetCurrentActivity(Object^ sender, RoutedEventArgs^ e)
00038 {
00039     // Reset fields and status
00040     ScenarioOutput_Activity->Text = "No data";
00041     ScenarioOutput_Confidence->Text = "No data";
00042     ScenarioOutput_Timestamp->Text = "No data";
00043     rootPage->NotifyUser("", NotifyType::StatusMessage);
00044
00045     // Determine if we can access activity sensors
00046     auto deviceAccessInfo = DeviceAccessInformation::CreateFromDeviceClassId(GUID_ActivitySensor_ClassId);
00047     if (deviceAccessInfo->CurrentStatus == DeviceAccessStatus::Allowed)
00048     {
00049         // Get the default activity sensor
00050         create_task(ActivitySensor::GetDefaultAsync()).then([this](ActivitySensor^ activitySensor)
00051         {
00052             if (activitySensor != nullptr)
00053             {
00054                 create_task(activitySensor->GetCurrentReadingAsync()).then([this](task<ActivitySensorReading^> task)
00055                 {
00056                     try
00057                     {
00058                         auto reading = task.get();
00059                         if (reading != nullptr)
00060                         {
00061                             ScenarioOutput_Activity->Text = reading->Activity.ToString();
00062                             ScenarioOutput_Confidence->Text = reading->Confidence.ToString();
00063
00064                             auto timestampFormatter = ref new DateTimeFormatter("day month year hour minute second");
00065                             ScenarioOutput_Timestamp->Text = timestampFormatter->Format(reading->Timestamp);
00066                         }
00067                     }
00068                     catch (Platform::COMException ^ e)
00069                     {
00070                         // Some activity sensors may occassionally time out when determining the initial
00071                         // reading. If this happens frequently, use events instead of GetCurrentReadingAsync.
00072                         rootPage->NotifyUser("Could not get the current reading (likely a timeout)", NotifyType::ErrorMessage);
00073                     }
00074                 });
00075             }
00076             else
00077             {
00078                 rootPage->NotifyUser("No activity sensors found", NotifyType::ErrorMessage);
00079             }
00080         });
00081     }
00082     else
00083     {
00084         rootPage->NotifyUser("Access denied to activity sensors", NotifyType::ErrorMessage);
00085     }
00086 }
00087
Generated on Fri Nov 15 2024 22:17:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothLE/cppwinrt/PresentationFormats.h Source File

  • BluetoothLE
  • cppwinrt

PresentationFormats.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     struct PresentationFormats
00018     {
00019         /// <summary>
00020         /// Units are established international standards for the measurement of physical quantities.
00021         /// </summary>
00022         /// <remarks>Please refer https://www.bluetooth.com/specifications/assigned-numbers/units </remarks>
00023         enum class Units : uint16_t
00024         {
00025             Unitless = 0x2700,
00026             LengthMetre = 0x2701,
00027             MassKilogram = 0x2702,
00028             TimeSecond = 0x2703,
00029             ElectricCurrentAmpere = 0x2704,
00030             ThermodynamicTemperatureKelvin = 0x2705,
00031             AmountOfSubstanceMole = 0x2706,
00032             LuminousIntensityCandela = 0x2707,
00033             AreaSquareMetres = 0x2710,
00034             VolumeCubicMetres = 0x2711,
00035             VelocityMetresPerSecond = 0x2712,
00036             AccelerationMetresPerSecondSquared = 0x2713,
00037             WaveNumberReciprocalMetre = 0x2714,
00038             DensityKilogramperCubicMetre = 0x2715,
00039             SurfaceDensityKilogramPerSquareMetre = 0x2716,
00040             SpecificVolumeCubicMetrePerKilogram = 0x2717,
00041             CurrentDensityAmperePerSquareMetre = 0x2718,
00042             MagneticFieldStrengthAmperePerMetre = 0x2719,
00043             AmountConcentrationMolePerCubicMetre = 0x271A,
00044             MassConcentrationKilogramPerCubicMetre = 0x271B,
00045             LuminanceCandelaPerSquareMetre = 0x271C,
00046             RefractiveIndex = 0x271D,
00047             RelativePermeability = 0x271E,
00048             PlaneAngleRadian = 0x2720,
00049             SolidAngleSteradian = 0x2721,
00050             FrequencyHertz = 0x2722,
00051             ForceNewton = 0x2723,
00052             PressurePascal = 0x2724,
00053             EnergyJoule = 0x2725,
00054             PowerWatt = 0x2726,
00055             ElectricChargeCoulomb = 0x2727,
00056             ElectricPotentialDifferenceVolt = 0x2728,
00057             CapacitanceFarad = 0x2729,
00058             ElectricResistanceOhm = 0x272A,
00059             ElectricConductanceSiemens = 0x272B,
00060             MagneticFluxWeber = 0x272C,
00061             MagneticFluxDensityTesla = 0x272D,
00062             InductanceHenry = 0x272E,
00063             CelsiusTemperatureDegreeCelsius = 0x272F,
00064             LuminousFluxLumen = 0x2730,
00065             IlluminanceLux = 0x2731,
00066             ActivityReferredToARadioNuclideBecquerel = 0x2732,
00067             AbsorbedDoseGray = 0x2733,
00068             DoseEquivalentSievert = 0x2734,
00069             CatalyticActivityKatal = 0x2735,
00070             DynamicViscosityPascalSecond = 0x2740,
00071             MomentOfForceNewtonMetre = 0x2741,
00072             SurfaceTensionNewtonPerMetre = 0x2742,
00073             AngularVelocityRadianPerSecond = 0x2743,
00074             AngularAccelerationRadianPerSecondSquared = 0x2744,
00075             HeatFluxDensityWattPerSquareMetre = 0x2745,
00076             HeatCapacityJoulePerKelvin = 0x2746,
00077             SpecificHeatCapacityJoulePerKilogramKelvin = 0x2747,
00078             SpecificEnergyJoulePerKilogram = 0x2748,
00079             ThermalConductivityWattPerMetreKelvin = 0x2749,
00080             EnergyDensityJoulePerCubicMetre = 0x274A,
00081             ElectricfieldstrengthVoltPerMetre = 0x274B,
00082             ElectricchargeDensityCoulombPerCubicMetre = 0x274C,
00083             SurfacechargeDensityCoulombPerSquareMetre = 0x274D,
00084             ElectricFluxDensityCoulombPerSquareMetre = 0x274E,
00085             PermittivityFaradPerMetre = 0x274F,
00086             PermeabilityHenryPerMetre = 0x2750,
00087             MolarEnergyJoulePermole = 0x2751,
00088             MolarentropyJoulePermoleKelvin = 0x2752,
00089             ExposureCoulombPerKilogram = 0x2753,
00090             AbsorbeddoserateGrayPerSecond = 0x2754,
00091             RadiantintensityWattPerSteradian = 0x2755,
00092             RadianceWattPerSquareMetreSteradian = 0x2756,
00093             CatalyticActivityConcentrationKatalPerCubicMetre = 0x2757,
00094             TimeMinute = 0x2760,
00095             TimeHour = 0x2761,
00096             TimeDay = 0x2762,
00097             PlaneAngleDegree = 0x2763,
00098             PlaneAngleMinute = 0x2764,
00099             PlaneAngleSecond = 0x2765,
00100             AreaHectare = 0x2766,
00101             VolumeLitre = 0x2767,
00102             MassTonne = 0x2768,
00103             PressureBar = 0x2780,
00104             PressureMilliMetreofmercury = 0x2781,
00105             LengthAngstrom = 0x2782,
00106             LengthNauticalMile = 0x2783,
00107             AreaBarn = 0x2784,
00108             VelocityKnot = 0x2785,
00109             LogarithmicRadioQuantityNeper = 0x2786,
00110             LogarithmicRadioQuantityBel = 0x2787,
00111             LengthYard = 0x27A0,
00112             LengthParsec = 0x27A1,
00113             LengthInch = 0x27A2,
00114             LengthFoot = 0x27A3,
00115             LengthMile = 0x27A4,
00116             PressurePoundForcePerSquareinch = 0x27A5,
00117             VelocityKiloMetrePerHour = 0x27A6,
00118             VelocityMilePerHour = 0x27A7,
00119             AngularVelocityRevolutionPerminute = 0x27A8,
00120             EnergyGramcalorie = 0x27A9,
00121             EnergyKilogramcalorie = 0x27AA,
00122             EnergyKiloWattHour = 0x27AB,
00123             ThermodynamicTemperatureDegreeFahrenheit = 0x27AC,
00124             Percentage = 0x27AD,
00125             PerMille = 0x27AE,
00126             PeriodBeatsPerMinute = 0x27AF,
00127             ElectricchargeAmpereHours = 0x27B0,
00128             MassDensityMilligramPerdeciLitre = 0x27B1,
00129             MassDensityMillimolePerLitre = 0x27B2,
00130             TimeYear = 0x27B3,
00131             TimeMonth = 0x27B4,
00132             ConcentrationCountPerCubicMetre = 0x27B5,
00133             IrradianceWattPerSquareMetre = 0x27B6,
00134             MilliliterPerKilogramPerminute = 0x27B7,
00135             MassPound = 0x27B8,
00136         };
00137
00138         /// <summary>
00139         /// The Name Space field is used to identify the organization that is responsible for defining the enumerations for the description field.
00140         /// </summary>
00141         /// <remarks>
00142         /// Please refer https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml
00143         /// </remarks>
00144         enum class NamespaceId : uint8_t
00145         {
00146             BluetoothSigAssignedNumber = 1,
00147             ReservedForFutureUse,
00148         };
00149
00150         /// <summary>
00151         /// The Description is an enumerated value from the organization identified by the Name Space field.
00152         /// </summary>
00153         /// <remarks>
00154         /// Please refer https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml
00155         /// </remarks>
00156         static constexpr uint16_t Description = 0x0000;
00157
00158         /// <summary>
00159         /// Exponent value for the characteristics
00160         /// </summary>
00161         static constexpr int Exponent = 0;
00162
00163     };
00164 }
00165
Generated on Fri Nov 15 2024 22:18:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePickerContracts/cs/CachedFileUpdater_Remote.xaml.cs Source File

  • FilePickerContracts
  • cs

CachedFileUpdater_Remote.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using SDKTemplate;
00012
00013 using System;
00014 using Windows.Storage;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.Storage.Provider;
00018
00019 namespace FilePickerContracts
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class CachedFileUpdater_Remote : Page
00025     {
00026         public CachedFileUpdater_Remote()
00027         {
00028             this.InitializeComponent();
00029             OverwriteButton.Click += new RoutedEventHandler(OverwriteButton_Click);
00030             RenameButton.Click += new RoutedEventHandler(RenameButton_Click);
00031         }
00032
00033         private async void OutputFileAsync(StorageFile file)
00034         {
00035             string fileContent = await FileIO.ReadTextAsync(file);
00036             OutputFileName.Text = String.Format(@"File Name: {0}", file.Name);
00037             OutputFileContent.Text = String.Format(@"File Content:{0}{1}", System.Environment.NewLine, fileContent);
00038         }
00039
00040         private void UpdateUI()
00041         {
00042             OverwriteButton.IsEnabled = false;
00043             RenameButton.IsEnabled = false;
00044         }
00045
00046         private void OverwriteButton_Click(object sender, RoutedEventArgs e)
00047         {
00048             FileUpdateRequest fileUpdateRequest = CachedFileUpdaterPage.Current.fileUpdateRequest;
00049             FileUpdateRequestDeferral fileUpdateRequestDeferral = CachedFileUpdaterPage.Current.fileUpdateRequestDeferral;
00050
00051             // update the remote version of file...
00052             // Printing the file content
00053             this.OutputFileAsync(fileUpdateRequest.File);
00054
00055             fileUpdateRequest.Status = FileUpdateStatus.Complete;
00056             fileUpdateRequestDeferral.Complete();
00057
00058             UpdateUI();
00059         }
00060
00061         private async void RenameButton_Click(object sender, RoutedEventArgs e)
00062         {
00063             FileUpdateRequest fileUpdateRequest = CachedFileUpdaterPage.Current.fileUpdateRequest;
00064             FileUpdateRequestDeferral fileUpdateRequestDeferral = CachedFileUpdaterPage.Current.fileUpdateRequestDeferral;
00065
00066             StorageFile file = await fileUpdateRequest.File.CopyAsync(ApplicationData.Current.LocalFolder, fileUpdateRequest.File.Name, NameCollisionOption.GenerateUniqueName);
00067             CachedFileUpdater.SetUpdateInformation(file, "CachedFile", ReadActivationMode.NotNeeded, WriteActivationMode.AfterWrite, CachedFileOptions.RequireUpdateOnAccess);
00068             fileUpdateRequest.UpdateLocalFile(file);
00069
00070             this.OutputFileAsync(file);
00071
00072             fileUpdateRequest.Status = FileUpdateStatus.CompleteAndRenamed;
00073             fileUpdateRequestDeferral.Complete();
00074
00075             UpdateUI();
00076         }
00077     }
00078 }
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampDevice/cpp/Scenario2_EnableSettings.xaml.h Source File

  • LampDevice
  • cpp

Scenario2_EnableSettings.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_EnableSettings.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario2_EnableSettings sealed
00021     {
00022     public:
00023         Scenario2_EnableSettings();
00024
00025     protected:
00026         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00027
00028     private:
00029         MainPage^ _rootPage;
00030
00031         void BrightnessBtn_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032         void ColorLampBtn_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033
00034         Concurrency::task<void> LogStatusToOutputBoxAsync(Platform::String^ message);
00035         Concurrency::task<void> LogStatusAsync(Platform::String^ message, NotifyType type);
00036     };
00037 }
Generated on Fri Nov 15 2024 22:20:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-SPI/cppwinrt/Project.idl Source File

  • IoT-SPI
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_ReadData : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_ReadData();
00018     }
00019 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DSvgImage/cpp/Common/DeviceResources.cpp Source File

  • D2DSvgImage
  • cpp
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DeviceResources.h"
00014 #include "DirectXHelper.h"
00015 #include <windows.ui.xaml.media.dxinterop.h>
00016
00017 using namespace D2D1;
00018 using namespace DirectX;
00019 using namespace Microsoft::WRL;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::UI::Core;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Platform;
00025
00026 // Constants used to calculate screen rotations
00027 namespace ScreenRotation
00028 {
00029     // 0-degree Z-rotation
00030     static const XMFLOAT4X4 Rotation0(
00031         1.0f, 0.0f, 0.0f, 0.0f,
00032         0.0f, 1.0f, 0.0f, 0.0f,
00033         0.0f, 0.0f, 1.0f, 0.0f,
00034         0.0f, 0.0f, 0.0f, 1.0f
00035         );
00036
00037     // 90-degree Z-rotation
00038     static const XMFLOAT4X4 Rotation90(
00039         0.0f, 1.0f, 0.0f, 0.0f,
00040         -1.0f, 0.0f, 0.0f, 0.0f,
00041         0.0f, 0.0f, 1.0f, 0.0f,
00042         0.0f, 0.0f, 0.0f, 1.0f
00043         );
00044
00045     // 180-degree Z-rotation
00046     static const XMFLOAT4X4 Rotation180(
00047         -1.0f, 0.0f, 0.0f, 0.0f,
00048         0.0f, -1.0f, 0.0f, 0.0f,
00049         0.0f, 0.0f, 1.0f, 0.0f,
00050         0.0f, 0.0f, 0.0f, 1.0f
00051         );
00052
00053     // 270-degree Z-rotation
00054     static const XMFLOAT4X4 Rotation270(
00055         0.0f, -1.0f, 0.0f, 0.0f,
00056         1.0f, 0.0f, 0.0f, 0.0f,
00057         0.0f, 0.0f, 1.0f, 0.0f,
00058         0.0f, 0.0f, 0.0f, 1.0f
00059         );
00060 };
00061
00062 // Constructor for DeviceResources.
00063 DX::DeviceResources::DeviceResources() :
00064     m_screenViewport(),
00065     m_d3dFeatureLevel(D3D_FEATURE_LEVEL_9_1),
00066     m_d3dRenderTargetSize(),
00067     m_outputSize(),
00068     m_logicalSize(),
00069     m_nativeOrientation(DisplayOrientations::None),
00070     m_currentOrientation(DisplayOrientations::None),
00071     m_dpi(-1.0f),
00072     m_compositionScaleX(1.0f),
00073     m_compositionScaleY(1.0f),
00074     m_deviceNotify(nullptr)
00075 {
00076     CreateDeviceIndependentResources();
00077     CreateDeviceResources();
00078 }
00079
00080 // Configures resources that don't depend on the Direct3D device.
00081 void DX::DeviceResources::CreateDeviceIndependentResources()
00082 {
00083     // Initialize Direct2D resources.
00084     D2D1_FACTORY_OPTIONS options;
00085     ZeroMemory(&options, sizeof(options));
00086
00087 #if defined(_DEBUG)
00088     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00089     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00090 #endif
00091
00092     // Initialize the Direct2D Factory.
00093     DX::ThrowIfFailed(
00094         D2D1CreateFactory(
00095             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00096             __uuidof(ID2D1Factory6),
00097             &options,
00098             &m_d2dFactory
00099             )
00100         );
00101
00102     // Initialize the DirectWrite Factory.
00103     DX::ThrowIfFailed(
00104         DWriteCreateFactory(
00105             DWRITE_FACTORY_TYPE_SHARED,
00106             __uuidof(IDWriteFactory2),
00107             &m_dwriteFactory
00108             )
00109         );
00110
00111     // Initialize the Windows Imaging Component (WIC) Factory.
00112     DX::ThrowIfFailed(
00113         CoCreateInstance(
00114             CLSID_WICImagingFactory2,
00115             nullptr,
00116             CLSCTX_INPROC_SERVER,
00117             IID_PPV_ARGS(&m_wicFactory)
00118             )
00119         );
00120 }
00121
00122 // Configures the Direct3D device, and stores handles to it and the device context.
00123 void DX::DeviceResources::CreateDeviceResources()
00124 {
00125     // This flag adds support for surfaces with a different color channel ordering
00126     // than the API default. It is required for compatibility with Direct2D.
00127     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00128
00129 #if defined(_DEBUG)
00130     if (DX::SdkLayersAvailable())
00131     {
00132         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00133         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00134     }
00135 #endif
00136
00137     // This array defines the set of DirectX hardware feature levels this app will support.
00138     // Note the ordering should be preserved.
00139     // Don't forget to declare your application's minimum required feature level in its
00140     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00141     D3D_FEATURE_LEVEL featureLevels[] =
00142     {
00143         D3D_FEATURE_LEVEL_11_1,
00144         D3D_FEATURE_LEVEL_11_0,
00145         D3D_FEATURE_LEVEL_10_1,
00146         D3D_FEATURE_LEVEL_10_0,
00147         D3D_FEATURE_LEVEL_9_3,
00148         D3D_FEATURE_LEVEL_9_2,
00149         D3D_FEATURE_LEVEL_9_1
00150     };
00151
00152     // Create the Direct3D 11 API device object and a corresponding context.
00153     ComPtr<ID3D11Device> device;
00154     ComPtr<ID3D11DeviceContext> context;
00155
00156     HRESULT hr = D3D11CreateDevice(
00157         nullptr,                    // Specify nullptr to use the default adapter.
00158         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00159         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00160         creationFlags,              // Set debug and Direct2D compatibility flags.
00161         featureLevels,              // List of feature levels this app can support.
00162         ARRAYSIZE(featureLevels),   // Size of the list above.
00163         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00164         &device,                    // Returns the Direct3D device created.
00165         &m_d3dFeatureLevel,         // Returns feature level of device created.
00166         &context                    // Returns the device immediate context.
00167         );
00168
00169     if (FAILED(hr))
00170     {
00171         // If the initialization fails, fall back to the WARP device.
00172         // For more information on WARP, see:
00173         // http://go.microsoft.com/fwlink/?LinkId=286690
00174         DX::ThrowIfFailed(
00175             D3D11CreateDevice(
00176                 nullptr,
00177                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00178                 0,
00179                 creationFlags,
00180                 featureLevels,
00181                 ARRAYSIZE(featureLevels),
00182                 D3D11_SDK_VERSION,
00183                 &device,
00184                 &m_d3dFeatureLevel,
00185                 &context
00186                 )
00187             );
00188     }
00189
00190     // Store pointers to the Direct3D 11.1 API device and immediate context.
00191     DX::ThrowIfFailed(
00192         device.As(&m_d3dDevice)
00193         );
00194
00195     DX::ThrowIfFailed(
00196         context.As(&m_d3dContext)
00197         );
00198
00199     // Create the Direct2D device object and a corresponding context.
00200     ComPtr<IDXGIDevice3> dxgiDevice;
00201     DX::ThrowIfFailed(
00202         m_d3dDevice.As(&dxgiDevice)
00203         );
00204
00205     DX::ThrowIfFailed(
00206         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00207         );
00208
00209     DX::ThrowIfFailed(
00210         m_d2dDevice->CreateDeviceContext(
00211             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00212             &m_d2dContext
00213             )
00214         );
00215 }
00216
00217 // These resources need to be recreated every time the window size is changed.
00218 void DX::DeviceResources::CreateWindowSizeDependentResources()
00219 {
00220     // Clear the previous window size specific context.
00221     ID3D11RenderTargetView* nullViews[] = {nullptr};
00222     m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00223     m_d3dRenderTargetView = nullptr;
00224     m_d2dContext->SetTarget(nullptr);
00225     m_d2dTargetBitmap = nullptr;
00226     m_d3dDepthStencilView = nullptr;
00227     m_d3dContext->Flush();
00228
00229     // Calculate the necessary swap chain and render target size in pixels.
00230     m_outputSize.Width = m_logicalSize.Width * m_compositionScaleX;
00231     m_outputSize.Height = m_logicalSize.Height * m_compositionScaleY;
00232
00233     // Prevent zero size DirectX content from being created.
00234     m_outputSize.Width = max(m_outputSize.Width, 1);
00235     m_outputSize.Height = max(m_outputSize.Height, 1);
00236
00237     // The width and height of the swap chain must be based on the window's
00238     // natively-oriented width and height. If the window is not in the native
00239     // orientation, the dimensions must be reversed.
00240     DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation();
00241
00242     bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270;
00243     m_d3dRenderTargetSize.Width = swapDimensions ? m_outputSize.Height : m_outputSize.Width;
00244     m_d3dRenderTargetSize.Height = swapDimensions ? m_outputSize.Width : m_outputSize.Height;
00245
00246     if (m_swapChain != nullptr)
00247     {
00248         // If the swap chain already exists, resize it.
00249         HRESULT hr = m_swapChain->ResizeBuffers(
00250             2, // Double-buffered swap chain.
00251             lround(m_d3dRenderTargetSize.Width),
00252             lround(m_d3dRenderTargetSize.Height),
00253             DXGI_FORMAT_B8G8R8A8_UNORM,
00254             0
00255             );
00256
00257         if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00258         {
00259             // If the device was removed for any reason, a new device and swap chain will need to be created.
00260             HandleDeviceLost();
00261
00262             // Everything is set up now. Do not continue execution of this method. HandleDeviceLost will reenter this method
00263             // and correctly set up the new device.
00264             return;
00265         }
00266         else
00267         {
00268             DX::ThrowIfFailed(hr);
00269         }
00270     }
00271     else
00272     {
00273         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00274         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00275
00276         swapChainDesc.Width = lround(m_d3dRenderTargetSize.Width); // Match the size of the window.
00277         swapChainDesc.Height = lround(m_d3dRenderTargetSize.Height);
00278         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swap chain format.
00279         swapChainDesc.Stereo = false;
00280         swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling.
00281         swapChainDesc.SampleDesc.Quality = 0;
00282         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00283         swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency.
00284         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Runtime apps must use this SwapEffect.
00285         swapChainDesc.Flags = 0;
00286         swapChainDesc.Scaling = DXGI_SCALING_STRETCH;
00287         swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
00288
00289         // This sequence obtains the DXGI factory that was used to create the Direct3D device above.
00290         ComPtr<IDXGIDevice3> dxgiDevice;
00291         DX::ThrowIfFailed(
00292             m_d3dDevice.As(&dxgiDevice)
00293             );
00294
00295         ComPtr<IDXGIAdapter> dxgiAdapter;
00296         DX::ThrowIfFailed(
00297             dxgiDevice->GetAdapter(&dxgiAdapter)
00298             );
00299
00300         ComPtr<IDXGIFactory2> dxgiFactory;
00301         DX::ThrowIfFailed(
00302             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00303             );
00304
00305         // When using XAML interop, the swap chain must be created for composition.
00306         DX::ThrowIfFailed(
00307             dxgiFactory->CreateSwapChainForComposition(
00308                 m_d3dDevice.Get(),
00309                 &swapChainDesc,
00310                 nullptr,
00311                 &m_swapChain
00312                 )
00313             );
00314
00315         // Associate the swap chain with SwapChainPanel.
00316         // UI changes will need to be dispatched back to the UI thread.
00317         m_swapChainPanel->Dispatcher->RunAsync(CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
00318         {
00319             // Get backing native interface for SwapChainPanel.
00320             ComPtr<ISwapChainPanelNative> panelNative;
00321             DX::ThrowIfFailed(
00322                 reinterpret_cast<IUnknown*>(m_swapChainPanel)->QueryInterface(IID_PPV_ARGS(&panelNative))
00323                 );
00324
00325             DX::ThrowIfFailed(
00326                 panelNative->SetSwapChain(m_swapChain.Get())
00327                 );
00328         }, CallbackContext::Any));
00329
00330         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00331         // ensures that the application will only render after each VSync, minimizing power consumption.
00332         DX::ThrowIfFailed(
00333             dxgiDevice->SetMaximumFrameLatency(1)
00334             );
00335     }
00336
00337     // Set the proper orientation for the swap chain, and generate 2D and
00338     // 3D matrix transformations for rendering to the rotated swap chain.
00339     // Note the rotation angle for the 2D and 3D transforms are different.
00340     // This is due to the difference in coordinate spaces.  Additionally,
00341     // the 3D matrix is specified explicitly to avoid rounding errors.
00342
00343     switch (displayRotation)
00344     {
00345     case DXGI_MODE_ROTATION_IDENTITY:
00346         m_orientationTransform2D = Matrix3x2F::Identity();
00347         m_orientationTransform3D = ScreenRotation::Rotation0;
00348         break;
00349
00350     case DXGI_MODE_ROTATION_ROTATE90:
00351         m_orientationTransform2D =
00352             Matrix3x2F::Rotation(90.0f) *
00353             Matrix3x2F::Translation(m_logicalSize.Height, 0.0f);
00354         m_orientationTransform3D = ScreenRotation::Rotation270;
00355         break;
00356
00357     case DXGI_MODE_ROTATION_ROTATE180:
00358         m_orientationTransform2D =
00359             Matrix3x2F::Rotation(180.0f) *
00360             Matrix3x2F::Translation(m_logicalSize.Width, m_logicalSize.Height);
00361         m_orientationTransform3D = ScreenRotation::Rotation180;
00362         break;
00363
00364     case DXGI_MODE_ROTATION_ROTATE270:
00365         m_orientationTransform2D =
00366             Matrix3x2F::Rotation(270.0f) *
00367             Matrix3x2F::Translation(0.0f, m_logicalSize.Width);
00368         m_orientationTransform3D = ScreenRotation::Rotation90;
00369         break;
00370
00371     default:
00372         throw ref new FailureException();
00373     }
00374
00375     DX::ThrowIfFailed(
00376         m_swapChain->SetRotation(displayRotation)
00377         );
00378
00379     // Set an inverse scale on the swap chain.
00380     DXGI_MATRIX_3X2_F inverseScale = { 0 };
00381     inverseScale._11 = 1.0f / m_compositionScaleX;
00382     inverseScale._22 = 1.0f / m_compositionScaleY;
00383     ComPtr<IDXGISwapChain2> spSwapChain2;
00384     DX::ThrowIfFailed(
00385         m_swapChain.As<IDXGISwapChain2>(&spSwapChain2)
00386         );
00387
00388     DX::ThrowIfFailed(
00389         spSwapChain2->SetMatrixTransform(&inverseScale)
00390         );
00391
00392
00393     // Create a render target view of the swap chain back buffer.
00394     ComPtr<ID3D11Texture2D> backBuffer;
00395     DX::ThrowIfFailed(
00396         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00397         );
00398
00399     DX::ThrowIfFailed(
00400         m_d3dDevice->CreateRenderTargetView(
00401             backBuffer.Get(),
00402             nullptr,
00403             &m_d3dRenderTargetView
00404             )
00405         );
00406
00407     // Create a depth stencil view for use with 3D rendering if needed.
00408     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00409         DXGI_FORMAT_D24_UNORM_S8_UINT,
00410         lround(m_d3dRenderTargetSize.Width),
00411         lround(m_d3dRenderTargetSize.Height),
00412         1, // This depth stencil view has only one texture.
00413         1, // Use a single mipmap level.
00414         D3D11_BIND_DEPTH_STENCIL
00415         );
00416
00417     ComPtr<ID3D11Texture2D> depthStencil;
00418     DX::ThrowIfFailed(
00419         m_d3dDevice->CreateTexture2D(
00420             &depthStencilDesc,
00421             nullptr,
00422             &depthStencil
00423             )
00424         );
00425
00426     CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
00427     DX::ThrowIfFailed(
00428         m_d3dDevice->CreateDepthStencilView(
00429             depthStencil.Get(),
00430             &depthStencilViewDesc,
00431             &m_d3dDepthStencilView
00432             )
00433         );
00434
00435     // Set the 3D rendering viewport to target the entire window.
00436     m_screenViewport = CD3D11_VIEWPORT(
00437         0.0f,
00438         0.0f,
00439         m_d3dRenderTargetSize.Width,
00440         m_d3dRenderTargetSize.Height
00441         );
00442
00443     m_d3dContext->RSSetViewports(1, &m_screenViewport);
00444
00445     // Create a Direct2D target bitmap associated with the
00446     // swap chain back buffer and set it as the current target.
00447     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00448         D2D1::BitmapProperties1(
00449             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00450             D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00451             m_dpi,
00452             m_dpi
00453             );
00454
00455     ComPtr<IDXGISurface2> dxgiBackBuffer;
00456     DX::ThrowIfFailed(
00457         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00458         );
00459
00460     DX::ThrowIfFailed(
00461         m_d2dContext->CreateBitmapFromDxgiSurface(
00462             dxgiBackBuffer.Get(),
00463             &bitmapProperties,
00464             &m_d2dTargetBitmap
00465             )
00466         );
00467
00468     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00469
00470     // Grayscale text anti-aliasing is recommended for all Windows Runtime apps.
00471     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00472 }
00473
00474 // This method is called when the XAML control is created (or re-created).
00475 void DX::DeviceResources::SetSwapChainPanel(SwapChainPanel^ panel)
00476 {
00477     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00478
00479     m_swapChainPanel = panel;
00480     m_logicalSize = Windows::Foundation::Size(static_cast<float>(panel->ActualWidth), static_cast<float>(panel->ActualHeight));
00481     m_nativeOrientation = currentDisplayInformation->NativeOrientation;
00482     m_currentOrientation = currentDisplayInformation->CurrentOrientation;
00483     m_compositionScaleX = panel->CompositionScaleX;
00484     m_compositionScaleY = panel->CompositionScaleY;
00485     m_dpi = currentDisplayInformation->LogicalDpi;
00486     m_d2dContext->SetDpi(m_dpi, m_dpi);
00487
00488     CreateWindowSizeDependentResources();
00489 }
00490
00491 // This method is called in the event handler for the SizeChanged event.
00492 void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize)
00493 {
00494     if (m_logicalSize != logicalSize)
00495     {
00496         m_logicalSize = logicalSize;
00497         CreateWindowSizeDependentResources();
00498     }
00499 }
00500
00501 // This method is called in the event handler for the DpiChanged event.
00502 void DX::DeviceResources::SetDpi(float dpi)
00503 {
00504     if (dpi != m_dpi)
00505     {
00506         m_dpi = dpi;
00507
00508         m_d2dContext->SetDpi(m_dpi, m_dpi);
00509         CreateWindowSizeDependentResources();
00510     }
00511 }
00512
00513 // This method is called in the event handler for the OrientationChanged event.
00514 void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation)
00515 {
00516     if (m_currentOrientation != currentOrientation)
00517     {
00518         m_currentOrientation = currentOrientation;
00519         CreateWindowSizeDependentResources();
00520     }
00521 }
00522
00523 // This method is called in the event handler for the CompositionScaleChanged event.
00524 void DX::DeviceResources::SetCompositionScale(float compositionScaleX, float compositionScaleY)
00525 {
00526     if (m_compositionScaleX != compositionScaleX ||
00527         m_compositionScaleY != compositionScaleY)
00528     {
00529         m_compositionScaleX = compositionScaleX;
00530         m_compositionScaleY = compositionScaleY;
00531         CreateWindowSizeDependentResources();
00532     }
00533 }
00534
00535 // This method is called in the event handler for the DisplayContentsInvalidated event.
00536 void DX::DeviceResources::ValidateDevice()
00537 {
00538     // The D3D Device is no longer valid if the default adapter changed since the device
00539     // was created or if the device has been removed.
00540
00541     // First, get the information for the default adapter from when the device was created.
00542
00543     ComPtr<IDXGIDevice3> dxgiDevice;
00544     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00545
00546     ComPtr<IDXGIAdapter> deviceAdapter;
00547     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00548
00549     ComPtr<IDXGIFactory2> deviceFactory;
00550     DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory)));
00551
00552     ComPtr<IDXGIAdapter1> previousDefaultAdapter;
00553     DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter));
00554
00555     DXGI_ADAPTER_DESC previousDesc;
00556     DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc));
00557
00558     // Next, get the information for the current default adapter.
00559
00560     ComPtr<IDXGIFactory2> currentFactory;
00561     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&currentFactory)));
00562
00563     ComPtr<IDXGIAdapter1> currentDefaultAdapter;
00564     DX::ThrowIfFailed(currentFactory->EnumAdapters1(0, &currentDefaultAdapter));
00565
00566     DXGI_ADAPTER_DESC currentDesc;
00567     DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(&currentDesc));
00568
00569     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00570     // a new D3D device must be created.
00571
00572     if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart ||
00573         previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart ||
00574         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00575     {
00576         // Release references to resources related to the old device.
00577         dxgiDevice = nullptr;
00578         deviceAdapter = nullptr;
00579         deviceFactory = nullptr;
00580         previousDefaultAdapter = nullptr;
00581
00582         // Create a new device and swap chain.
00583         HandleDeviceLost();
00584     }
00585 }
00586
00587 // Recreate all device resources and set them back to the current state.
00588 void DX::DeviceResources::HandleDeviceLost()
00589 {
00590     m_swapChain = nullptr;
00591
00592     if (m_deviceNotify != nullptr)
00593     {
00594         m_deviceNotify->OnDeviceLost();
00595     }
00596
00597     CreateDeviceResources();
00598     m_d2dContext->SetDpi(m_dpi, m_dpi);
00599     CreateWindowSizeDependentResources();
00600
00601     if (m_deviceNotify != nullptr)
00602     {
00603         m_deviceNotify->OnDeviceRestored();
00604     }
00605 }
00606
00607 // Register our DeviceNotify to be informed on device lost and creation.
00608 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00609 {
00610     m_deviceNotify = deviceNotify;
00611 }
00612
00613 // Call this method when the app suspends. It provides a hint to the driver that the app
00614 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00615 void DX::DeviceResources::Trim()
00616 {
00617     ComPtr<IDXGIDevice3> dxgiDevice;
00618     m_d3dDevice.As(&dxgiDevice);
00619
00620     dxgiDevice->Trim();
00621 }
00622
00623 // Present the contents of the swap chain to the screen.
00624 void DX::DeviceResources::Present()
00625 {
00626     // The first argument instructs DXGI to block until VSync, putting the application
00627     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00628     // frames that will never be displayed to the screen.
00629     HRESULT hr = m_swapChain->Present(1, 0);
00630
00631     // Discard the contents of the render target.
00632     // This is a valid operation only when the existing contents will be entirely
00633     // overwritten. If dirty or scroll rects are used, this call should be removed.
00634     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00635
00636     // Discard the contents of the depth stencil.
00637     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00638
00639     // If the device was removed either by a disconnection or a driver upgrade, we
00640     // must recreate all device resources.
00641     if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00642     {
00643         HandleDeviceLost();
00644     }
00645     else
00646     {
00647         DX::ThrowIfFailed(hr);
00648     }
00649 }
00650
00651 // This method determines the rotation between the display device's native Orientation and the
00652 // current display orientation.
00653 DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation()
00654 {
00655     DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
00656
00657     // Note: NativeOrientation can only be Landscape or Portrait even though
00658     // the DisplayOrientations enum has other values.
00659     switch (m_nativeOrientation)
00660     {
00661     case DisplayOrientations::Landscape:
00662         switch (m_currentOrientation)
00663         {
00664         case DisplayOrientations::Landscape:
00665             rotation = DXGI_MODE_ROTATION_IDENTITY;
00666             break;
00667
00668         case DisplayOrientations::Portrait:
00669             rotation = DXGI_MODE_ROTATION_ROTATE270;
00670             break;
00671
00672         case DisplayOrientations::LandscapeFlipped:
00673             rotation = DXGI_MODE_ROTATION_ROTATE180;
00674             break;
00675
00676         case DisplayOrientations::PortraitFlipped:
00677             rotation = DXGI_MODE_ROTATION_ROTATE90;
00678             break;
00679         }
00680         break;
00681
00682     case DisplayOrientations::Portrait:
00683         switch (m_currentOrientation)
00684         {
00685         case DisplayOrientations::Landscape:
00686             rotation = DXGI_MODE_ROTATION_ROTATE90;
00687             break;
00688
00689         case DisplayOrientations::Portrait:
00690             rotation = DXGI_MODE_ROTATION_IDENTITY;
00691             break;
00692
00693         case DisplayOrientations::LandscapeFlipped:
00694             rotation = DXGI_MODE_ROTATION_ROTATE270;
00695             break;
00696
00697         case DisplayOrientations::PortraitFlipped:
00698             rotation = DXGI_MODE_ROTATION_ROTATE180;
00699             break;
00700         }
00701         break;
00702     }
00703     return rotation;
00704 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Common/DeviceResources.h Source File

  • HolographicFaceTracking
  • cpp
  • Common

DeviceResources.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "CameraResources.h"
00015
00016 namespace DX
00017 {
00018     // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created.
00019     interface IDeviceNotify
00020     {
00021         virtual void OnDeviceLost()     = 0;
00022         virtual void OnDeviceRestored() = 0;
00023     };
00024
00025     // Creates and manages a Direct3D device and immediate context, Direct2D device and context (for debug), and the holographic swap chain.
00026     class DeviceResources
00027     {
00028     public:
00029         DeviceResources();
00030
00031         // Public methods related to Direct3D devices.
00032         void HandleDeviceLost();
00033         void RegisterDeviceNotify(IDeviceNotify* deviceNotify);
00034         void Trim();
00035         void Present(Windows::Graphics::Holographic::HolographicFrame^ frame);
00036
00037         // Public methods related to holographic devices.
00038         void SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^ space);
00039         void EnsureCameraResources(
00040             Windows::Graphics::Holographic::HolographicFrame^ frame,
00041             Windows::Graphics::Holographic::HolographicFramePrediction^ prediction);
00042
00043         void AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^ camera);
00044         void RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^ camera);
00045
00046         // Holographic accessors.
00047         template<typename RetType, typename LCallback>
00048         RetType                 UseHolographicCameraResources(const LCallback& callback);
00049
00050         Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^
00051                                 GetD3DInteropDevice() const             { return m_d3dInteropDevice;    }
00052
00053         // D3D accessors.
00054         ID3D11Device4*          GetD3DDevice() const                    { return m_d3dDevice.Get();     }
00055         ID3D11DeviceContext3*   GetD3DDeviceContext() const             { return m_d3dContext.Get();    }
00056         D3D_FEATURE_LEVEL       GetDeviceFeatureLevel() const           { return m_d3dFeatureLevel;     }
00057         bool                    GetDeviceSupportsVprt() const           { return m_supportsVprt;        }
00058
00059         // DXGI acessors.
00060         IDXGIAdapter3*          GetDXGIAdapter() const                  { return m_dxgiAdapter.Get();   }
00061
00062         // D2D accessors.
00063         ID2D1Factory2*          GetD2DFactory() const                   { return m_d2dFactory.Get();    }
00064         IDWriteFactory2*        GetDWriteFactory() const                { return m_dwriteFactory.Get(); }
00065         IWICImagingFactory2*    GetWicImagingFactory() const            { return m_wicFactory.Get();    }
00066
00067     private:
00068         // Private methods related to the Direct3D device, and resources based on that device.
00069         void CreateDeviceIndependentResources();
00070         void InitializeUsingHolographicSpace();
00071         void CreateDeviceResources();
00072
00073         // Direct3D objects.
00074         Microsoft::WRL::ComPtr<ID3D11Device4>                   m_d3dDevice;
00075         Microsoft::WRL::ComPtr<ID3D11DeviceContext3>            m_d3dContext;
00076         Microsoft::WRL::ComPtr<IDXGIAdapter3>                   m_dxgiAdapter;
00077
00078         // Direct3D interop objects.
00079         Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^ m_d3dInteropDevice;
00080
00081         // Direct2D factories.
00082         Microsoft::WRL::ComPtr<ID2D1Factory2>                   m_d2dFactory;
00083         Microsoft::WRL::ComPtr<IDWriteFactory2>                 m_dwriteFactory;
00084         Microsoft::WRL::ComPtr<IWICImagingFactory2>             m_wicFactory;
00085
00086         // The holographic space provides a preferred DXGI adapter ID.
00087         Windows::Graphics::Holographic::HolographicSpace^       m_holographicSpace = nullptr;
00088
00089         // Properties of the Direct3D device currently in use.
00090         D3D_FEATURE_LEVEL                                       m_d3dFeatureLevel = D3D_FEATURE_LEVEL_10_0;
00091
00092         // The IDeviceNotify can be held directly as it owns the DeviceResources.
00093         IDeviceNotify*                                          m_deviceNotify = nullptr;
00094
00095         // Whether or not the current Direct3D device supports the optional feature
00096         // for setting the render target array index from the vertex shader stage.
00097         bool                                                    m_supportsVprt = false;
00098
00099         // Back buffer resources, etc. for attached holographic cameras.
00100         std::map<UINT32, std::unique_ptr<CameraResources>>      m_cameraResources;
00101         std::mutex                                              m_cameraResourcesLock;
00102     };
00103
00104     // A small base class used by new classes which manage DirectX resources
00105     class Resource
00106     {
00107     public:
00108         Resource(std::shared_ptr<DeviceResources> deviceResources)
00109             : m_deviceResources(std::move(deviceResources))
00110         {}
00111
00112         virtual ~Resource() = default;
00113
00114         virtual concurrency::task<void> CreateDeviceDependentResourcesAsync() = 0;
00115         virtual void                    ReleaseDeviceDependentResources() = 0;
00116
00117     protected:
00118         std::shared_ptr<DeviceResources> m_deviceResources;
00119     };
00120
00121     template<typename ObjectType, typename... Args>
00122     concurrency::task<void> CreateAndInitializeAsync(std::shared_ptr<ObjectType>& target, Args&&... args)
00123     {
00124         // Forward the arguments to std::make_shared, which will call the ObjectType's matching constructor
00125         target = std::make_shared<ObjectType>(std::forward<Args>(args)...);
00126
00127         // Then we initialize the resources asynchronously
00128         return target->CreateDeviceDependentResourcesAsync();
00129     }
00130 }
00131
00132 // Device-based resources for holographic cameras are stored in a std::map. Access this list by providing a
00133 // callback to this function, and the std::map will be guarded from add and remove
00134 // events until the callback returns. The callback is processed immediately and must
00135 // not contain any nested calls to UseHolographicCameraResources.
00136 // The callback takes a parameter of type std::map<UINT32, std::unique_ptr<DX::CameraResources>>&
00137 // through which the list of cameras will be accessed.
00138 template<typename RetType, typename LCallback>
00139 RetType DX::DeviceResources::UseHolographicCameraResources(const LCallback& callback)
00140 {
00141     std::lock_guard<std::mutex> guard(m_cameraResourcesLock);
00142     return callback(m_cameraResources);
00143 }
00144
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CaptureDevice Member List

This is the complete list of members for CaptureDevice, including all inherited members.
CaptureDevice() | CaptureDevice | [inline]
CaptureFailed | CaptureDevice |
CaptureSource | CaptureDevice |
CheckForRecordingDeviceAsync() | CaptureDevice | [inline, static]
CleanUpAsync() | CaptureDevice | [inline]
CleanupSink() | CaptureDevice | [inline, private]
DoCleanup() | CaptureDevice | [inline, private]
forwardEvents | CaptureDevice | [private]
IncomingConnectionArrived | CaptureDevice |
InitializeAsync() | CaptureDevice | [inline]
mediaCapture | CaptureDevice | [private]
mediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) | CaptureDevice | [inline, private]
mediaSink | CaptureDevice | [private]
mediaSink_IncomingConnectionEvent(object sender, object args) | CaptureDevice | [inline, private]
recordingStarted | CaptureDevice | [private]
SelectPreferredCameraStreamSettingAsync(MediaStreamType mediaStreamType, Func< IMediaEncodingProperties, bool > filterSettings) | CaptureDevice | [inline]
StartRecordingAsync(MediaEncodingProfile encodingProfile) | CaptureDevice | [inline]
StopRecordingAsync() | CaptureDevice | [inline]
Generated on Fri Nov 15 2024 22:24:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/StspMediaStream.cpp Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

StspMediaStream.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "StspMediaStream.h"
00010 #include "StspMediaSource.h"
00011
00012 using namespace Microsoft::Samples::SimpleCommunication;
00013 using namespace Microsoft::Samples::SimpleCommunication::Network;
00014
00015 #define SET_SAMPLE_ATTRIBUTE(flag, mask, pSample, flagName) \
00016     if ((StspSampleFlag_##flagName & mask) == StspSampleFlag_##flagName) \
00017 { \
00018     ThrowIfError(pSample->SetUINT32(MFSampleExtension_##flagName, (StspSampleFlag_##flagName & flag) == StspSampleFlag_##flagName)); \
00019 }
00020
00021 // RAII object locking the the source on initialization and unlocks it on deletion
00022 class CMediaStream::CSourceLock
00023 {
00024 public:
00025     CSourceLock(CMediaSource *pSource)
00026         : _spSource(pSource)
00027     {
00028         if (_spSource)
00029         {
00030             _spSource->Lock();
00031         }
00032     }
00033
00034     ~CSourceLock()
00035     {
00036         if (_spSource)
00037         {
00038             _spSource->Unlock();
00039         }
00040     }
00041
00042 private:
00043     ComPtr<CMediaSource> _spSource;
00044 };
00045
00046 HRESULT CMediaStream::CreateInstance(StspStreamDescription *pStreamDescription, IBufferPacket *pAttributesBuffer, CMediaSource *pSource, CMediaStream **ppStream)
00047 {
00048     if (pStreamDescription == nullptr || pSource == nullptr || ppStream == nullptr)
00049     {
00050         return E_INVALIDARG;
00051     }
00052
00053     HRESULT hr = S_OK;
00054     try
00055     {
00056         ComPtr<CMediaStream> spStream;
00057         spStream.Attach(new (std::nothrow) CMediaStream(pSource));
00058         if (!spStream)
00059         {
00060             Throw(E_OUTOFMEMORY);
00061         }
00062
00063         spStream->Initialize(pStreamDescription, pAttributesBuffer);
00064
00065
00066         (*ppStream) = spStream.Detach();
00067     }
00068     catch(Exception ^exc)
00069     {
00070         hr = exc->HResult;
00071     }
00072
00073     TRACEHR_RET(hr);
00074 }
00075
00076 CMediaStream::CMediaStream(CMediaSource *pSource)
00077     : _cRef(1)
00078     , _spSource(pSource)
00079     , _eSourceState(SourceState_Invalid)
00080     , _fActive(false)
00081     , _flRate(1.0f)
00082     , _fVideo(false)
00083     , _eDropMode(MF_DROP_MODE_NONE)
00084     , _fDiscontinuity(false)
00085     , _fDropTime(false)
00086     , _fInitDropTime(false)
00087     , _fWaitingForCleanPoint(true)
00088     , _hnsStartDroppingAt(0)
00089     , _hnsAmountToDrop(0)
00090 {
00091 }
00092
00093 CMediaStream::~CMediaStream(void)
00094 {
00095 }
00096
00097 // IUnknown methods
00098
00099 IFACEMETHODIMP CMediaStream::QueryInterface(REFIID riid, void **ppv)
00100 {
00101     if (ppv == nullptr)
00102     {
00103         return E_POINTER;
00104     }
00105     (*ppv) = nullptr;
00106
00107     HRESULT hr = S_OK;
00108     if (riid == IID_IUnknown ||
00109         riid == IID_IMFMediaStream ||
00110         riid == IID_IMFMediaEventGenerator)
00111     {
00112         (*ppv) = static_cast<IMFMediaStream*>(this);
00113         AddRef();
00114     }
00115     else if (riid == IID_IMFQualityAdvise || riid == IID_IMFQualityAdvise2)
00116     {
00117         (*ppv) = static_cast<IMFQualityAdvise2*>(this);
00118         AddRef();
00119     }
00120     else if (riid == IID_IMFGetService)
00121     {
00122         (*ppv) = static_cast<IMFGetService*>(this);
00123         AddRef();
00124     }
00125     else
00126     {
00127         hr = E_NOINTERFACE;
00128     }
00129
00130     return hr;
00131 }
00132
00133 IFACEMETHODIMP_(ULONG) CMediaStream::AddRef()
00134 {
00135     return InterlockedIncrement(&_cRef);
00136 }
00137
00138 IFACEMETHODIMP_(ULONG) CMediaStream::Release()
00139 {
00140     long cRef = InterlockedDecrement(&_cRef);
00141     if (cRef == 0)
00142     {
00143         delete this;
00144     }
00145     return cRef;
00146 }
00147
00148 // IMFMediaEventGenerator methods.
00149 // Note: These methods call through to the event queue helper object.
00150
00151 IFACEMETHODIMP CMediaStream::BeginGetEvent(IMFAsyncCallback *pCallback, IUnknown *punkState)
00152 {
00153     HRESULT hr = S_OK;
00154
00155     CSourceLock lock(_spSource.Get());
00156
00157     hr = CheckShutdown();
00158
00159     if (SUCCEEDED(hr))
00160     {
00161         hr = _spEventQueue->BeginGetEvent(pCallback, punkState);
00162     }
00163
00164     TRACEHR_RET(hr);
00165 }
00166
00167 IFACEMETHODIMP CMediaStream::EndGetEvent(IMFAsyncResult *pResult, IMFMediaEvent **ppEvent)
00168 {
00169     HRESULT hr = S_OK;
00170
00171     CSourceLock lock(_spSource.Get());
00172
00173     hr = CheckShutdown();
00174
00175     if (SUCCEEDED(hr))
00176     {
00177         hr = _spEventQueue->EndGetEvent(pResult, ppEvent);
00178     }
00179
00180     TRACEHR_RET(hr);
00181 }
00182
00183 IFACEMETHODIMP CMediaStream::GetEvent(DWORD dwFlags, IMFMediaEvent **ppEvent)
00184 {
00185     // NOTE:
00186     // GetEvent can block indefinitely, so we don't hold the lock.
00187     // This requires some juggling with the event queue pointer.
00188
00189     HRESULT hr = S_OK;
00190
00191     ComPtr<IMFMediaEventQueue> spQueue;
00192
00193     {
00194         CSourceLock lock(_spSource.Get());
00195
00196         // Check shutdown
00197         hr = CheckShutdown();
00198
00199         // Get the pointer to the event queue.
00200         if (SUCCEEDED(hr))
00201         {
00202             spQueue = _spEventQueue;
00203         }
00204     }
00205
00206     // Now get the event.
00207     if (SUCCEEDED(hr))
00208     {
00209         hr = spQueue->GetEvent(dwFlags, ppEvent);
00210     }
00211
00212
00213     TRACEHR_RET(hr);
00214 }
00215
00216 IFACEMETHODIMP CMediaStream::QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, PROPVARIANT const *pvValue)
00217 {
00218     HRESULT hr = S_OK;
00219
00220     CSourceLock lock(_spSource.Get());
00221
00222     hr = CheckShutdown();
00223
00224     if (SUCCEEDED(hr))
00225     {
00226         hr = _spEventQueue->QueueEventParamVar(met, guidExtendedType, hrStatus, pvValue);
00227     }
00228
00229     TRACEHR_RET(hr);
00230 }
00231
00232 // IMFMediaStream methods
00233
00234 IFACEMETHODIMP CMediaStream::GetMediaSource(IMFMediaSource **ppMediaSource)
00235 {
00236     if (ppMediaSource == nullptr)
00237     {
00238         return E_INVALIDARG;
00239     }
00240
00241     HRESULT hr = S_OK;
00242
00243     CSourceLock lock(_spSource.Get());
00244
00245     hr = CheckShutdown();
00246
00247     if (SUCCEEDED(hr))
00248     {
00249         *ppMediaSource = _spSource.Get();
00250         (*ppMediaSource)->AddRef();
00251     }
00252
00253     TRACEHR_RET(hr);
00254 }
00255
00256 IFACEMETHODIMP CMediaStream::GetStreamDescriptor(IMFStreamDescriptor **ppStreamDescriptor)
00257 {
00258     if (ppStreamDescriptor == nullptr)
00259     {
00260         return E_INVALIDARG;
00261     }
00262
00263     HRESULT hr = S_OK;
00264
00265     CSourceLock lock(_spSource.Get());
00266
00267     hr = CheckShutdown();
00268
00269     if (SUCCEEDED(hr))
00270     {
00271         *ppStreamDescriptor = _spStreamDescriptor.Get();
00272         (*ppStreamDescriptor)->AddRef();
00273     }
00274
00275     TRACEHR_RET(hr);
00276 }
00277
00278 IFACEMETHODIMP CMediaStream::RequestSample(IUnknown *pToken)
00279 {
00280     CSourceLock lock(_spSource.Get());
00281
00282     try
00283     {
00284         ThrowIfError(CheckShutdown());
00285
00286         if (_eSourceState != SourceState_Started)
00287         {
00288             // We cannot be asked for a sample unless we are in started state
00289             Throw(MF_E_INVALIDREQUEST);
00290         }
00291
00292         // Put token onto the list to return it when we have a sample ready
00293         ThrowIfError(_tokens.InsertBack(pToken));
00294
00295         // Trigger sample delivery
00296         DeliverSamples();
00297     }
00298     catch(Exception ^exc)
00299     {
00300         HandleError(exc->HResult);
00301     }
00302
00303     TRACEHR_RET(S_OK);
00304 }
00305
00306 // IMFQualityAdvise methods
00307
00308 IFACEMETHODIMP CMediaStream::SetDropMode(
00309     _In_ MF_QUALITY_DROP_MODE eDropMode )
00310 {
00311     HRESULT hr = S_OK;
00312     CSourceLock lock(_spSource.Get());
00313
00314     hr = CheckShutdown();
00315
00316     //
00317     // Only support one drop mode
00318     //
00319     if( SUCCEEDED(hr) &&
00320         ((eDropMode < MF_DROP_MODE_NONE) || (eDropMode >= MF_DROP_MODE_2)))
00321     {
00322         hr = MF_E_NO_MORE_DROP_MODES;
00323     }
00324
00325     if (SUCCEEDED(hr) && _eDropMode != eDropMode)
00326     {
00327         _eDropMode = eDropMode;
00328         _fWaitingForCleanPoint = true;
00329
00330         TRACE(TRACE_LEVEL_NORMAL, L"Setting drop mode to %d\n", _eDropMode);
00331     }
00332
00333     return( hr );
00334 }
00335
00336 IFACEMETHODIMP CMediaStream::SetQualityLevel(
00337     _In_ MF_QUALITY_LEVEL eQualityLevel )
00338 {
00339     return( MF_E_NO_MORE_QUALITY_LEVELS );
00340 }
00341
00342 IFACEMETHODIMP CMediaStream::GetDropMode(
00343     _Out_  MF_QUALITY_DROP_MODE *peDropMode )
00344 {
00345     HRESULT hr = S_OK;
00346
00347     if (peDropMode == nullptr)
00348     {
00349         return E_POINTER;
00350     }
00351
00352     CSourceLock lock(_spSource.Get());
00353
00354     hr = CheckShutdown();
00355
00356     if (SUCCEEDED(hr))
00357     {
00358         *peDropMode = _eDropMode;
00359     }
00360
00361     TRACEHR_RET(hr);
00362 }
00363
00364 IFACEMETHODIMP CMediaStream::GetQualityLevel(
00365     _Out_  MF_QUALITY_LEVEL *peQualityLevel )
00366 {
00367     return( E_NOTIMPL );
00368 }
00369
00370 IFACEMETHODIMP CMediaStream::DropTime( _In_ LONGLONG hnsAmountToDrop )
00371 {
00372     HRESULT hr = S_OK;
00373     CSourceLock lock(_spSource.Get());
00374
00375     hr = CheckShutdown();
00376
00377     if (SUCCEEDED(hr))
00378     {
00379         if (hnsAmountToDrop > 0)
00380         {
00381             _fDropTime = true;
00382             _fInitDropTime = true;
00383             _hnsAmountToDrop = hnsAmountToDrop;
00384             TRACE(TRACE_LEVEL_NORMAL, L"Dropping time hnsAmountToDrop=%I64d\n", hnsAmountToDrop);
00385         }
00386         else if (hnsAmountToDrop == 0)
00387         {
00388             // Reset time dropping
00389             TRACE(TRACE_LEVEL_NORMAL, L"Disabling dropping time\n");
00390             ResetDropTime();
00391         }
00392         else
00393         {
00394             hr = E_INVALIDARG;
00395         }
00396     }
00397
00398     TRACEHR_RET(hr);
00399 }
00400
00401 // IMFQualityAdvise2 methods
00402
00403 IFACEMETHODIMP CMediaStream::NotifyQualityEvent(_In_opt_ IMFMediaEvent *pEvent, _Out_ DWORD *pdwFlags)
00404 {
00405     HRESULT hr = S_OK;
00406     CSourceLock lock(_spSource.Get());
00407
00408     if (pdwFlags == nullptr || pEvent == nullptr)
00409     {
00410         return E_POINTER;
00411     }
00412
00413     *pdwFlags = 0;
00414
00415     hr = CheckShutdown();
00416
00417     if (SUCCEEDED(hr))
00418     {
00419         MediaEventType met;
00420         hr = pEvent->GetType(&met);
00421
00422         if (SUCCEEDED(hr) && met == MEQualityNotify)
00423         {
00424             GUID guiExtendedType;
00425             hr = pEvent->GetExtendedType(&guiExtendedType);
00426
00427             if (SUCCEEDED(hr) && guiExtendedType == MF_QUALITY_NOTIFY_SAMPLE_LAG)
00428             {
00429                 PROPVARIANT var;
00430                 PropVariantInit(&var);
00431
00432                 hr = pEvent->GetValue(&var);
00433                 LONGLONG hnsSampleLatency = var.hVal.QuadPart;
00434
00435                 if (SUCCEEDED(hr))
00436                 {
00437                     if (_eDropMode == MF_DROP_MODE_NONE && hnsSampleLatency > 30000000)
00438                     {
00439                         TRACE(TRACE_LEVEL_NORMAL, L"Entering drop mode\n");
00440                         hr = SetDropMode(MF_DROP_MODE_1);
00441                     }
00442                     else if (_eDropMode == MF_DROP_MODE_1 && hnsSampleLatency < 0)
00443                     {
00444                         TRACE(TRACE_LEVEL_NORMAL, L": Leaving drop mode\n");
00445                         hr = SetDropMode(MF_DROP_MODE_NONE);
00446                     }
00447                     else
00448                     {
00449                         TRACE(TRACE_LEVEL_NORMAL, L": Sample latency = %I64d\n", hnsSampleLatency);
00450                     }
00451                 }
00452
00453                 PropVariantClear(&var);
00454             }
00455         }
00456     }
00457
00458     TRACEHR_RET(hr);
00459 }
00460
00461 // IMFGetService methods
00462
00463 IFACEMETHODIMP CMediaStream::GetService(
00464     _In_ REFGUID guidService,
00465     _In_ REFIID riid,
00466     _Out_ LPVOID *ppvObject )
00467 {
00468     HRESULT hr = S_OK;
00469     CSourceLock lock(_spSource.Get());
00470
00471     if (ppvObject == nullptr)
00472     {
00473         return E_POINTER;
00474     }
00475     *ppvObject = NULL;
00476
00477     hr = CheckShutdown();
00478
00479     if (SUCCEEDED(hr))
00480     {
00481         if( MF_QUALITY_SERVICES == guidService )
00482         {
00483             hr = QueryInterface(riid, ppvObject);
00484         }
00485         else
00486         {
00487             hr = MF_E_UNSUPPORTED_SERVICE;
00488         }
00489     }
00490
00491     TRACEHR_RET(hr);
00492 }
00493
00494 HRESULT CMediaStream::Start()
00495 {
00496     HRESULT hr = S_OK;
00497     CSourceLock lock(_spSource.Get());
00498
00499     hr = CheckShutdown();
00500
00501     if (SUCCEEDED(hr))
00502     {
00503         if (_eSourceState == SourceState_Stopped ||
00504             _eSourceState == SourceState_Started)
00505         {
00506             _eSourceState = SourceState_Started;
00507             // Inform the client that we've started
00508             hr = QueueEvent(MEStreamStarted, GUID_NULL, S_OK, nullptr);
00509         }
00510         else
00511         {
00512             hr = MF_E_INVALID_STATE_TRANSITION;
00513         }
00514     }
00515
00516     if (FAILED(hr))
00517     {
00518         HandleError(hr);
00519     }
00520
00521     return S_OK;
00522 }
00523
00524 HRESULT CMediaStream::Stop()
00525 {
00526     HRESULT hr = S_OK;
00527     CSourceLock lock(_spSource.Get());
00528
00529     hr = CheckShutdown();
00530
00531     if (SUCCEEDED(hr))
00532     {
00533         if (_eSourceState == SourceState_Started)
00534         {
00535             _eSourceState = SourceState_Stopped;
00536             _tokens.Clear();
00537             _samples.Clear();
00538             // Inform the client that we've stopped.
00539             hr = QueueEvent(MEStreamStopped, GUID_NULL, S_OK, nullptr);
00540         }
00541         else
00542         {
00543             hr = MF_E_INVALID_STATE_TRANSITION;
00544         }
00545     }
00546
00547     if (FAILED(hr))
00548     {
00549         HandleError(hr);
00550     }
00551
00552     return S_OK;
00553 }
00554
00555 HRESULT CMediaStream::SetRate(float flRate)
00556 {
00557     HRESULT hr = S_OK;
00558     CSourceLock lock(_spSource.Get());
00559
00560     try
00561     {
00562         ThrowIfError(CheckShutdown());
00563
00564         _flRate = flRate;
00565         if (_flRate != 1.0f)
00566         {
00567             CleanSampleQueue();
00568         }
00569     }
00570     catch(Exception ^exc)
00571     {
00572         HandleError(exc->HResult);
00573     }
00574
00575     return S_OK;
00576 }
00577
00578 HRESULT CMediaStream::Flush()
00579 {
00580     CSourceLock lock(_spSource.Get());
00581
00582     _tokens.Clear();
00583     _samples.Clear();
00584
00585     _fDiscontinuity = false;
00586     _eDropMode = MF_DROP_MODE_NONE;
00587     ResetDropTime();
00588
00589     return S_OK;
00590 }
00591
00592 HRESULT CMediaStream::Shutdown()
00593 {
00594     CSourceLock lock(_spSource.Get());
00595
00596     HRESULT hr = CheckShutdown();
00597
00598     if (SUCCEEDED(hr))
00599     {
00600         Flush();
00601
00602         if (_spEventQueue)
00603         {
00604             _spEventQueue->Shutdown();
00605             _spEventQueue.Reset();
00606         }
00607
00608         _spStreamDescriptor.Reset();
00609         _eSourceState = SourceState_Shutdown;
00610     }
00611
00612     TRACEHR_RET(hr);
00613 }
00614
00615 // Processes media sample received from the header
00616 void CMediaStream::ProcessSample(StspSampleHeader *pSampleHeader, IMFSample *pSample)
00617 {
00618     assert(pSample);
00619
00620     try
00621     {
00622         ThrowIfError(CheckShutdown());
00623         // Set sample attributes
00624         SetSampleAttributes(pSampleHeader, pSample);
00625
00626         // Check if we are in propper state if so deliver the sample otherwise just skip it and don't treat it as an error.
00627         if (_eSourceState == SourceState_Started)
00628         {
00629             // Put sample on the list
00630             ThrowIfError(_samples.InsertBack(pSample));
00631             // Deliver samples
00632             DeliverSamples();
00633         }
00634         else
00635         {
00636             Throw(MF_E_UNEXPECTED);
00637         }
00638     }
00639     catch(Exception ^exc)
00640     {
00641         HandleError(exc->HResult);
00642     }
00643 }
00644
00645 void CMediaStream::ProcessFormatChange(IMFMediaType *pMediaType)
00646 {
00647     assert(pMediaType);
00648
00649     try
00650     {
00651         ThrowIfError(CheckShutdown());
00652
00653         // Check if we are in proper state if so deliver the sample otherwise just skip it and don't treat it as an error.
00654         if (_eSourceState == SourceState_Started)
00655         {
00656             // Put sample on the list
00657             ThrowIfError(_samples.InsertBack(pMediaType));
00658             // Deliver samples
00659             DeliverSamples();
00660         }
00661         else
00662         {
00663             Throw(MF_E_UNEXPECTED);
00664         }
00665     }
00666     catch(Exception ^exc)
00667     {
00668         HandleError(exc->HResult);
00669     }
00670 }
00671
00672 HRESULT CMediaStream::SetActive(bool fActive)
00673 {
00674     CSourceLock lock(_spSource.Get());
00675
00676     HRESULT hr = CheckShutdown();
00677
00678     if (SUCCEEDED(hr))
00679     {
00680         if (_eSourceState != SourceState_Stopped &&
00681             _eSourceState != SourceState_Started)
00682         {
00683             hr = MF_E_INVALIDREQUEST;
00684         }
00685     }
00686
00687     if (SUCCEEDED(hr))
00688     {
00689         _fActive = fActive;
00690     }
00691
00692     TRACEHR_RET(hr);
00693 }
00694
00695 void CMediaStream::Initialize(StspStreamDescription *pStreamDescription, IBufferPacket *pAttributesBuffer)
00696 {
00697     // Create the media event queue.
00698     Exception ^error = nullptr;
00699     BYTE *pAttributes = nullptr;
00700
00701     try
00702     {
00703         ThrowIfError(MFCreateEventQueue(&_spEventQueue));
00704         ComPtr<IMFMediaType> spMediaType;
00705         ComPtr<IMFStreamDescriptor> spSD;
00706         ComPtr<IMFMediaTypeHandler> spMediaTypeHandler;
00707         DWORD cbAttributesSize = 0;
00708
00709         _fVideo = (pStreamDescription->guiMajorType == MFMediaType_Video);
00710
00711         // Create a media type object.
00712         ThrowIfError(MFCreateMediaType(&spMediaType));
00713         ThrowIfError(pAttributesBuffer->GetTotalLength(&cbAttributesSize));
00714
00715         if (cbAttributesSize < pStreamDescription->cbAttributesSize || pStreamDescription->cbAttributesSize == 0)
00716         {
00717             // Invalid stream description
00718             Throw(MF_E_UNSUPPORTED_FORMAT);
00719         }
00720
00721         // Prepare buffer where we will copy attributes to
00722         pAttributes = new(std::nothrow) BYTE[pStreamDescription->cbAttributesSize];
00723         if (pAttributes == nullptr)
00724         {
00725             Throw(E_OUTOFMEMORY);
00726         }
00727
00728         // Move the memory
00729         ThrowIfError(pAttributesBuffer->MoveLeft(pStreamDescription->cbAttributesSize, pAttributes));
00730         // Initialize media type's attributes
00731         ThrowIfError(MFInitAttributesFromBlob(spMediaType.Get(), pAttributes, pStreamDescription->cbAttributesSize));
00732         ValidateInputMediaType(pStreamDescription->guiMajorType, pStreamDescription->guiSubType, spMediaType.Get());
00733         ThrowIfError(spMediaType->SetGUID(MF_MT_MAJOR_TYPE, pStreamDescription->guiMajorType));
00734
00735         ThrowIfError(spMediaType->SetGUID(MF_MT_SUBTYPE, pStreamDescription->guiSubType));
00736
00737         // Now we can create MF stream descriptor.
00738         ThrowIfError(MFCreateStreamDescriptor(pStreamDescription->dwStreamId, 1, spMediaType.GetAddressOf(), &spSD));
00739         ThrowIfError(spSD->GetMediaTypeHandler(&spMediaTypeHandler));
00740
00741         // Set current media type
00742         ThrowIfError(spMediaTypeHandler->SetCurrentMediaType(spMediaType.Get()));
00743
00744         _spStreamDescriptor = spSD;
00745         _dwId = pStreamDescription->dwStreamId;
00746         // State of the stream is started.
00747         _eSourceState = SourceState_Stopped;
00748     }
00749     catch(Exception ^exc)
00750     {
00751         error = exc;
00752     }
00753
00754     delete[] pAttributes;
00755
00756     if (error != nullptr)
00757     {
00758         throw error;
00759     }
00760 }
00761
00762 // Deliver samples for every request client made
00763 void CMediaStream::DeliverSamples()
00764 {
00765     // Check if we have both: samples available in the queue and requests in request list.
00766     while (!_samples.IsEmpty() && !_tokens.IsEmpty())
00767     {
00768         ComPtr<IUnknown> spEntry;
00769         ComPtr<IMFSample> spSample;
00770         ComPtr<IUnknown> spToken;
00771         BOOL fDrop = FALSE;
00772         // Get the entry
00773         ThrowIfError(_samples.RemoveFront(&spEntry));
00774
00775         if (SUCCEEDED(spEntry.As(&spSample)))
00776         {
00777             fDrop = ShouldDropSample(spSample.Get());
00778
00779             if (!fDrop)
00780             {
00781                 // Get the request token
00782                 ThrowIfError(_tokens.RemoveFront(&spToken));
00783
00784                 if (spToken)
00785                 {
00786                     // If token was not null set the sample attribute.
00787                     ThrowIfError(spSample->SetUnknown(MFSampleExtension_Token, spToken.Get()));
00788                 }
00789
00790                 if (_fDiscontinuity)
00791                 {
00792                     // If token was not null set the sample attribute.
00793                     ThrowIfError(spSample->SetUINT32(MFSampleExtension_Discontinuity, TRUE));
00794                     _fDiscontinuity = false;
00795                 }
00796
00797                 // Send a sample event.
00798                 ThrowIfError(_spEventQueue->QueueEventParamUnk(MEMediaSample, GUID_NULL, S_OK, spSample.Get()));
00799             }
00800             else
00801             {
00802                 _fDiscontinuity = true;
00803             }
00804         }
00805         else
00806         {
00807             ComPtr<IMFMediaType> spMediaType;
00808             ThrowIfError(spEntry.As(&spMediaType));
00809             // Send a sample event.
00810             ThrowIfError(_spEventQueue->QueueEventParamUnk(MEStreamFormatChanged, GUID_NULL, S_OK, spMediaType.Get()));
00811         }
00812     }
00813 }
00814
00815 void CMediaStream::HandleError(HRESULT hErrorCode)
00816 {
00817     if (hErrorCode != MF_E_SHUTDOWN)
00818     {
00819         // Send MEError to the client
00820         hErrorCode = QueueEvent(MEError, GUID_NULL, hErrorCode, nullptr);
00821     }
00822 }
00823
00824 void CMediaStream::SetSampleAttributes(StspSampleHeader *pSampleHeader, IMFSample *pSample)
00825 {
00826     ThrowIfError(pSample->SetSampleTime(pSampleHeader->ullTimestamp));
00827     ThrowIfError(pSample->SetSampleDuration(pSampleHeader->ullDuration));
00828
00829     SET_SAMPLE_ATTRIBUTE(pSampleHeader->dwFlags, pSampleHeader->dwFlagMasks, pSample, BottomFieldFirst);
00830     SET_SAMPLE_ATTRIBUTE(pSampleHeader->dwFlags, pSampleHeader->dwFlagMasks, pSample, CleanPoint);
00831     SET_SAMPLE_ATTRIBUTE(pSampleHeader->dwFlags, pSampleHeader->dwFlagMasks, pSample, DerivedFromTopField);
00832     SET_SAMPLE_ATTRIBUTE(pSampleHeader->dwFlags, pSampleHeader->dwFlagMasks, pSample, Discontinuity);
00833     SET_SAMPLE_ATTRIBUTE(pSampleHeader->dwFlags, pSampleHeader->dwFlagMasks, pSample, Interlaced);
00834     SET_SAMPLE_ATTRIBUTE(pSampleHeader->dwFlags, pSampleHeader->dwFlagMasks, pSample, RepeatFirstField);
00835     SET_SAMPLE_ATTRIBUTE(pSampleHeader->dwFlags, pSampleHeader->dwFlagMasks, pSample, SingleField);
00836
00837     DWORD cbTotalLen;
00838     pSample->GetTotalLength(&cbTotalLen);
00839     TRACE(TRACE_LEVEL_LOW, L"Received sample TS-%I64d Duration-%I64d Length-%d %S\n", pSampleHeader->ullTimestamp, pSampleHeader->ullDuration, cbTotalLen, (pSampleHeader->dwFlags & StspSampleFlag_CleanPoint) ? "key frame" : "");
00840 }
00841
00842 bool CMediaStream::ShouldDropSample(IMFSample *pSample)
00843 {
00844     if (!_fVideo)
00845     {
00846         return false;
00847     }
00848
00849     bool fCleanPoint = MFGetAttributeUINT32( pSample, MFSampleExtension_CleanPoint, 0 ) > 0;
00850     bool fDrop = _flRate != 1.0f && !fCleanPoint;
00851
00852     LONGLONG hnsTimeStamp = 0;
00853     ThrowIfError(pSample->GetSampleTime(&hnsTimeStamp));
00854
00855     if (!fDrop && _fDropTime)
00856     {
00857         if (_fInitDropTime)
00858         {
00859             _hnsStartDroppingAt = hnsTimeStamp;
00860             _fInitDropTime = false;
00861         }
00862
00863         fDrop = hnsTimeStamp < (_hnsStartDroppingAt + _hnsAmountToDrop);
00864         if (!fDrop)
00865         {
00866             TRACE(TRACE_LEVEL_LOW, L"Ending dropping time on sample ts=%I64d _hnsStartDroppingAt=%I64d _hnsAmountToDrop=%I64d\n",
00867                 hnsTimeStamp, _hnsStartDroppingAt, _hnsAmountToDrop);
00868             ResetDropTime();
00869         }
00870         else
00871         {
00872             TRACE(TRACE_LEVEL_LOW, L": Dropping sample ts=%I64d _hnsStartDroppingAt=%I64d _hnsAmountToDrop=%I64d\n",
00873                 hnsTimeStamp, _hnsStartDroppingAt, _hnsAmountToDrop);
00874         }
00875     }
00876
00877     if (!fDrop && (_eDropMode == MF_DROP_MODE_1 || _fWaitingForCleanPoint))
00878     {
00879         // Only key frames
00880         fDrop = !fCleanPoint;
00881         if (fCleanPoint)
00882         {
00883             _fWaitingForCleanPoint = false;
00884         }
00885
00886         if (fDrop)
00887         {
00888             TRACE(TRACE_LEVEL_LOW, L": Dropping sample ts=%I64d\n",
00889                 hnsTimeStamp, _hnsStartDroppingAt, _hnsAmountToDrop);
00890         }
00891     }
00892
00893     return fDrop;
00894 }
00895
00896 void CMediaStream::CleanSampleQueue()
00897 {
00898     auto pos = _samples.FrontPosition();
00899     ComPtr<IUnknown> spEntry;
00900     ComPtr<IMFSample> spSample;
00901
00902     if (_fVideo)
00903     {
00904         // For video streams leave first key frame.
00905         for (;SUCCEEDED(_samples.GetItemPos(pos, spEntry.ReleaseAndGetAddressOf())); pos = _samples.Next(pos))
00906         {
00907             if (SUCCEEDED(spEntry.As(&spSample)) && MFGetAttributeUINT32(spSample.Get(), MFSampleExtension_CleanPoint, 0))
00908             {
00909                 break;
00910             }
00911         }
00912     }
00913
00914     _samples.Clear();
00915
00916     if (spSample != nullptr)
00917     {
00918         ThrowIfError(_samples.InsertFront(spSample.Get()));
00919     }
00920 }
00921
00922 void CMediaStream::ResetDropTime()
00923 {
00924     _fDropTime = false;
00925     _fInitDropTime = false;
00926     _hnsStartDroppingAt = 0;
00927     _hnsAmountToDrop = 0;
00928     _fWaitingForCleanPoint = true;
00929 }
Generated on Fri Nov 15 2024 22:21:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cpp/Scenario7_B2B.xaml.h Source File

  • Store
  • cpp

Scenario7_B2B.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario7_B2B.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class Scenario7_B2B sealed
00022     {
00023     public:
00024         Scenario7_B2B();
00025
00026     protected:
00027         void GetCustomerCollectionsId(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00028         void GetCustomerPurchaseId(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029
00030     private:
00031         MainPage^ rootPage = MainPage::Current;
00032         Windows::Services::Store::StoreContext^ storeContext;
00033
00034         Concurrency::task<Platform::String^> GetTokenFromAzureOAuthAsync();
00035     };
00036 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Level4 Member List

This is the complete list of members for Level4, including all inherited members.
Initialize(std::vector< std::shared_ptr< GameObject >> const &objects) override | Level4 | [virtual]
Level3() | Level3 |
Level4() | Level4 |
LoadState(PersistentState &state) override | Level4 | [virtual]
m_nextId | Level4 | [private]
m_objective | Level | [protected]
m_timeLimit | Level | [protected]
Objective() | Level |
SaveState(PersistentState &state) override | Level4 | [virtual]
TimeLimit() | Level |
Update(float time, float elapsedTime, float timeRemaining, std::vector< std::shared_ptr< GameObject >> const &objects) override | Level4 | [virtual]
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Polling Member List

This is the complete list of members for Scenario2_Polling, including all inherited members.
CO2LevelKey | Scenario2_Polling | [private]
customSensor | Scenario2_Polling | [private]
deviceAccessInformation | Scenario2_Polling | [private]
GetCO2Level(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
GUIDCustomSensorDeviceVendorDefinedTypeID | Scenario2_Polling | [private]
OnAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs e) | Scenario2_Polling | [inline, private]
OnCustomSensorAdded(DeviceWatcher watcher, DeviceInformation customSensorDevice) | Scenario2_Polling | [inline]
rootPage | Scenario2_Polling | [private]
Scenario2_Polling() | Scenario2_Polling | [inline]
watcher | Scenario2_Polling | [private]
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_ReverseConversion Member List

This is the complete list of members for Scenario3_ReverseConversion, including all inherited members.
CreateGeneratorButton_Click(object sender, RoutedEventArgs e) | Scenario3_ReverseConversion | [inline, private]
Execute_Click(object sender, RoutedEventArgs e) | Scenario3_ReverseConversion | [inline, private]
generator | Scenario3_ReverseConversion | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_ReverseConversion | [inline, protected]
rootPage | Scenario3_ReverseConversion | [private]
Scenario3_ReverseConversion() | Scenario3_ReverseConversion | [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario8_PairDevice Member List

This is the complete list of members for Scenario8_PairDevice, including all inherited members.
deviceWatcherHelper | Scenario8_PairDevice | [private]
OnDeviceListChanged(Windows::Devices::Enumeration::DeviceWatcher const &sender, hstring const &id) | Scenario8_PairDevice | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario8_PairDevice |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario8_PairDevice |
PairButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario8_PairDevice |
resultCollection | Scenario8_PairDevice | [private]
ResultsListView_SelectionChanged(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs const &e) | Scenario8_PairDevice |
Scenario8_PairDevice() | Scenario8_PairDevice |
StartWatcher() | Scenario8_PairDevice | [private]
StartWatcherButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario8_PairDevice |
StopWatcher() | Scenario8_PairDevice | [private]
StopWatcherButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario8_PairDevice |
UnpairButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario8_PairDevice |
UpdatePairingButtons() | Scenario8_PairDevice | [private]
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Unicode/cs/SampleConfiguration.cs Source File

  • Unicode
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Unicode tokenization C# sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title = "Tokenize lexical identifiers within a string", ClassType = typeof(Scenario1_FindId) },
00025         };
00026     }
00027
00028     public class Scenario
00029     {
00030         public string Title { get; set; }
00031         public Type ClassType { get; set; }
00032     }
00033 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AuthenticationController Member List

This is the complete list of members for AuthenticationController, including all inherited members.
Register(RegisterMessage message) | AuthenticationController | [inline]
RemoveRegisteredKey(UserAndKeyHintMessage message) | AuthenticationController | [inline]
RequestChallenge(UserAndKeyHintMessage message) | AuthenticationController | [inline]
SubmitResponse(SignatureMessage message) | AuthenticationController | [inline]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/DirectXPage.xaml.h Source File

  • Simple3DGameXaml
  • cpp

DirectXPage.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "DirectXPage.g.h"
00015 #include "GameMain.h"
00016 #include "ProductItem.h"
00017
00018 // When submitting the app to the Microsoft Store, disable the Store Simulator by commenting out this definition.
00019 #define USE_STORE_SIMULATOR 1
00020
00021 namespace Simple3DGameXaml
00022 {
00023     /// <summary>
00024     /// A page that hosts a DirectX SwapChainPanel.
00025     /// </summary>
00026     [Windows::Foundation::Metadata::WebHostHidden]
00027     public ref class DirectXPage sealed : Simple3DGameXaml::IGameUIControl
00028     {
00029     public:
00030         DirectXPage();
00031
00032         void OnSuspending();
00033         void OnResuming();
00034
00035         // IGameUIControl methods.
00036         virtual void SetGameLoading();
00037         virtual void SetGameStats(int maxLevel, int hitCount, int shotCount);
00038         virtual void SetGameOver(bool win, int maxLevel, int hitCount, int shotCount, int highScore);
00039         virtual void SetLevelStart(int level, Platform::String^ objective, float timeLimit, float bonusTime);
00040         virtual void SetPause(int level, int hitCount, int shotCount, float timeRemaining);
00041         virtual void ShowTooSmall();
00042         virtual void HideTooSmall();
00043         virtual void SetAction(GameInfoOverlayCommand action);
00044         virtual void HideGameInfoOverlay();
00045         virtual void ShowGameInfoOverlay();
00046
00047     private:
00048         // Window event handlers.
00049         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00050         void OnWindowActivationChanged(
00051             _In_ Platform::Object^ sender,
00052             _In_ Windows::UI::Core::WindowActivatedEventArgs^ args
00053             );
00054
00055         // DisplayInformation event handlers.
00056         void OnDpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00057         void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00058         void OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00059         void OnStereoEnabledChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00060
00061         // Other event handlers.
00062         void OnCompositionScaleChanged(Windows::UI::Xaml::Controls::SwapChainPanel^ sender, Object^ args);
00063         void OnSwapChainPanelSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00064         void OnWindowSizeChanged(
00065             _In_ Windows::UI::Core::CoreWindow^ sender,
00066             _In_ Windows::UI::Core::WindowSizeChangedEventArgs^ args
00067             );
00068
00069         // License handlers.
00070         void InitializeLicense();
00071         void InitializeLicenseCore();
00072         void OnLicenseChanged();
00073         void SetProductItems(
00074             Windows::ApplicationModel::Store::ListingInformation^ listing,
00075             Windows::ApplicationModel::Store::LicenseInformation^ license
00076             );
00077 #ifdef USE_STORE_SIMULATOR
00078         void ResetLicenseFromFile();
00079 #endif
00080
00081         // Page code behind.
00082         void OnPlayButtonClicked(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
00083         void OnResetButtonClicked(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
00084         void OnBuyAppButtonTapped(Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ args);
00085         void OnBuySelectorClicked(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
00086         void OnChangeBackgroundButtonClicked(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
00087         void OnResetLicenseButtonClicked(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
00088         void OnGameInfoOverlayTapped(Object^ sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^ args);
00089         void OnAppBarOpened(Object^ sender, Object^ args);
00090         void OnStoreReturnClicked(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
00091         void OnLoadStoreClicked(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
00092
00093         void OptionalTrialUpgrade();
00094         void ShowStoreFlyout();
00095
00096     private:
00097         // Resources used to render the DirectX content in the XAML page background.
00098         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00099         std::unique_ptr<GameMain> m_main;
00100         bool m_windowVisible;
00101         bool m_playActive;
00102
00103         Windows::ApplicationModel::Store::LicenseInformation^ m_licenseInformation;
00104         Windows::ApplicationModel::Store::ListingInformation^ m_listingInformation;
00105         bool m_possiblePurchaseUpgrade;
00106 #ifdef USE_STORE_SIMULATOR
00107         PersistentState^                                    m_licenseState;
00108         bool                                                m_isTrial;
00109 #endif
00110     };
00111 }
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario11 Member List

This is the complete list of members for Scenario11, including all inherited members.
accessibility | Scenario11 | [private]
Accessibility_HighContrastChanged(AccessibilitySettings sender, object args) | Scenario11 | [inline, private]
AddLayer1() | Scenario11 | [inline, private]
AddLayer2() | Scenario11 | [inline, private]
ContrastingColorButtonCheckedChanged(object sender, RoutedEventArgs e) | Scenario11 | [inline, private]
GetFileButton_Click(object sender, RoutedEventArgs e) | Scenario11 | [inline, private]
MapIconState enum name | Scenario11 | [private]
MapIconStateToStyleEntryState(MapIconState state) | Scenario11 | [private]
myLayer1 | Scenario11 | [private]
myLayer2 | Scenario11 | [private]
myLayers | Scenario11 | [private]
MyMap_Loaded(object sender, RoutedEventArgs e) | Scenario11 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario11 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario11 | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario11 | [inline, protected]
OnSizeChanged(object sender, SizeChangedEventArgs e) | Scenario11 | [inline, private]
rootPage | Scenario11 | [private]
Scenario11() | Scenario11 | [inline]
Scenario11() | Scenario11 | [inline]
Scenario11() | Scenario11 | [inline]
Scenario11() | Scenario11 | [inline]
Scenario11Button_Show_Click(object sender, RoutedEventArgs e) | Scenario11 | [inline, private]
SetStyleSheetStateCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario11 | [inline, private]
ToCustomStyleEntryState(MapIconState state) | Scenario11 | [inline, private, static]
ToDefaultStyleEntryState(MapIconState state) | Scenario11 | [inline, private, static]
UpdateMapElementOnClick(MapElement mapElement, MapIconStateToStyleEntryState toStyleEntryState) | Scenario11 | [inline, private, static]
UpdateMapElementOnPointerEntered(MapElement mapElement, MapIconStateToStyleEntryState toStyleEntryState) | Scenario11 | [inline, private, static]
UpdateMapElementOnPointerExited(MapElement mapElement, MapIconStateToStyleEntryState toStyleEntryState) | Scenario11 | [inline, private, static]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/Common/StepTimer.h Source File

  • BasicHologram
  • cpp
  • Common

StepTimer.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 namespace DX
00004 {
00005     // Helper class for animation and simulation timing.
00006     class StepTimer
00007     {
00008     public:
00009         StepTimer() :
00010             m_elapsedTicks(0),
00011             m_totalTicks(0),
00012             m_leftOverTicks(0),
00013             m_frameCount(0),
00014             m_framesPerSecond(0),
00015             m_framesThisSecond(0),
00016             m_qpcSecondCounter(0),
00017             m_isFixedTimeStep(false),
00018             m_targetElapsedTicks(TicksPerSecond / 60)
00019         {
00020             m_qpcFrequency = GetPerformanceFrequency();
00021
00022             // Initialize max delta to 1/10 of a second.
00023             m_qpcMaxDelta = m_qpcFrequency / 10;
00024         }
00025
00026         // Get elapsed time since the previous Update call.
00027         uint64 GetElapsedTicks() const                        { return m_elapsedTicks;                  }
00028         double GetElapsedSeconds() const                      { return TicksToSeconds(m_elapsedTicks);  }
00029
00030         // Get total time since the start of the program.
00031         uint64 GetTotalTicks() const                          { return m_totalTicks;                    }
00032         double GetTotalSeconds() const                        { return TicksToSeconds(m_totalTicks);    }
00033
00034         // Get total number of updates since start of the program.
00035         uint32 GetFrameCount() const                          { return m_frameCount;                    }
00036
00037         // Get the current framerate.
00038         uint32 GetFramesPerSecond() const                     { return m_framesPerSecond;               }
00039
00040         // Set whether to use fixed or variable timestep mode.
00041         void SetFixedTimeStep(bool isFixedTimestep)           { m_isFixedTimeStep = isFixedTimestep;    }
00042
00043         // Set how often to call Update when in fixed timestep mode.
00044         void SetTargetElapsedTicks(uint64 targetElapsed)      { m_targetElapsedTicks = targetElapsed;   }
00045         void SetTargetElapsedSeconds(double targetElapsed)    { m_targetElapsedTicks = SecondsToTicks(targetElapsed);   }
00046
00047         // Integer format represents time using 10,000,000 ticks per second.
00048         static const uint64 TicksPerSecond = 10'000'000;
00049
00050         static double TicksToSeconds(uint64 ticks)            { return static_cast<double>(ticks) / TicksPerSecond;     }
00051         static uint64 SecondsToTicks(double seconds)          { return static_cast<uint64>(seconds * TicksPerSecond);   }
00052
00053         // Convenient wrapper for QueryPerformanceFrequency. Throws an exception if
00054         // the call to QueryPerformanceFrequency fails.
00055         static inline uint64 GetPerformanceFrequency()
00056         {
00057             LARGE_INTEGER freq;
00058             if (!QueryPerformanceFrequency(&freq))
00059             {
00060                 throw ref new Platform::FailureException();
00061             }
00062             return freq.QuadPart;
00063         }
00064
00065         // Gets the current number of ticks from QueryPerformanceCounter. Throws an
00066         // exception if the call to QueryPerformanceCounter fails.
00067         static inline int64 GetTicks()
00068         {
00069             LARGE_INTEGER ticks;
00070             if (!QueryPerformanceCounter(&ticks))
00071             {
00072                 throw ref new Platform::FailureException();
00073             }
00074             return ticks.QuadPart;
00075         }
00076
00077         // After an intentional timing discontinuity (for instance a blocking IO operation)
00078         // call this to avoid having the fixed timestep logic attempt a set of catch-up
00079         // Update calls.
00080
00081         void ResetElapsedTime()
00082         {
00083             m_qpcLastTime = GetTicks();
00084
00085             m_leftOverTicks    = 0;
00086             m_framesPerSecond  = 0;
00087             m_framesThisSecond = 0;
00088             m_qpcSecondCounter = 0;
00089         }
00090
00091         // Update timer state, calling the specified Update function the appropriate number of times.
00092         template<typename TUpdate>
00093         void Tick(const TUpdate& update)
00094         {
00095             // Query the current time.
00096             uint64 currentTime = GetTicks();
00097             uint64 timeDelta   = currentTime - m_qpcLastTime;
00098
00099             m_qpcLastTime      = currentTime;
00100             m_qpcSecondCounter += timeDelta;
00101
00102             // Clamp excessively large time deltas (e.g. after paused in the debugger).
00103             if (timeDelta > m_qpcMaxDelta)
00104             {
00105                 timeDelta = m_qpcMaxDelta;
00106             }
00107
00108             // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp.
00109             timeDelta *= TicksPerSecond;
00110             timeDelta /= m_qpcFrequency;
00111
00112             uint32 lastFrameCount = m_frameCount;
00113
00114             if (m_isFixedTimeStep)
00115             {
00116                 // Fixed timestep update logic
00117
00118                 // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp
00119                 // the clock to exactly match the target value. This prevents tiny and irrelevant errors
00120                 // from accumulating over time. Without this clamping, a game that requested a 60 fps
00121                 // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually
00122                 // accumulate enough tiny errors that it would drop a frame. It is better to just round
00123                 // small deviations down to zero to leave things running smoothly.
00124
00125                 if (abs(static_cast<int64>(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000)
00126                 {
00127                     timeDelta = m_targetElapsedTicks;
00128                 }
00129
00130                 m_leftOverTicks += timeDelta;
00131
00132                 while (m_leftOverTicks >= m_targetElapsedTicks)
00133                 {
00134                     m_elapsedTicks   = m_targetElapsedTicks;
00135                     m_totalTicks    += m_targetElapsedTicks;
00136                     m_leftOverTicks -= m_targetElapsedTicks;
00137                     m_frameCount++;
00138
00139                     update();
00140                 }
00141             }
00142             else
00143             {
00144                 // Variable timestep update logic.
00145                 m_elapsedTicks  = timeDelta;
00146                 m_totalTicks   += timeDelta;
00147                 m_leftOverTicks = 0;
00148                 m_frameCount++;
00149
00150                 update();
00151             }
00152
00153             // Track the current framerate.
00154             if (m_frameCount != lastFrameCount)
00155             {
00156                 m_framesThisSecond++;
00157             }
00158
00159             if (m_qpcSecondCounter >= static_cast<uint64>(m_qpcFrequency))
00160             {
00161                 m_framesPerSecond   = m_framesThisSecond;
00162                 m_framesThisSecond  = 0;
00163                 m_qpcSecondCounter %= m_qpcFrequency;
00164             }
00165         }
00166
00167     private:
00168
00169         // Source timing data uses QPC units.
00170         uint64 m_qpcFrequency;
00171         uint64 m_qpcLastTime;
00172         uint64 m_qpcMaxDelta;
00173
00174         // Derived timing data uses a canonical tick format.
00175         uint64 m_elapsedTicks;
00176         uint64 m_totalTicks;
00177         uint64 m_leftOverTicks;
00178
00179         // Members for tracking the framerate.
00180         uint32 m_frameCount;
00181         uint32 m_framesPerSecond;
00182         uint32 m_framesThisSecond;
00183         uint64 m_qpcSecondCounter;
00184
00185         // Members for configuring fixed timestep mode.
00186         bool   m_isFixedTimeStep;
00187         uint64 m_targetElapsedTicks;
00188     };
00189 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/Scenario3.cpp Source File

  • WindowsAudioSession
  • cppwinrt

Scenario3.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
00012 #include "Scenario3.h"
00013 #include "Scenario3.g.cpp"
00014
00015 using namespace winrt;
00016 using namespace winrt::Windows::Devices::Enumeration;
00017 using namespace winrt::Windows::Media;
00018 using namespace winrt::Windows::Media::Devices;
00019 using namespace winrt::Windows::Storage;
00020 using namespace winrt::Windows::Storage::Pickers;
00021 using namespace winrt::Windows::Storage::Streams;
00022 using namespace winrt::Windows::UI::Xaml::Controls::Primitives;
00023 using namespace winrt::Windows::UI::Xaml::Media;
00024 using namespace winrt::Windows::UI::Xaml::Navigation;
00025
00026 namespace winrt::SDKTemplate::implementation
00027 {
00028     Scenario3::Scenario3()
00029     {
00030         InitializeComponent();
00031     }
00032
00033     fire_and_forget Scenario3::OnNavigatedTo(NavigationEventArgs const&)
00034     {
00035         auto lifetime = get_strong();
00036
00037         // Register for Media Transport controls.  This is required to support background
00038         // audio scenarios.
00039         m_systemMediaControls = SystemMediaTransportControls::GetForCurrentView();
00040         m_systemMediaControlsButtonToken = m_systemMediaControls.ButtonPressed({ get_weak(), &Scenario3::MediaButtonPressed });
00041         m_systemMediaControls.IsPlayEnabled(true);
00042         m_systemMediaControls.IsPauseEnabled(true);
00043         m_systemMediaControls.IsStopEnabled(true);
00044
00045         UpdateContentUI();
00046
00047         // Get a string representing the Default Audio Render Device
00048         hstring deviceId = MediaDevice::GetDefaultAudioRenderId(AudioDeviceRole::Default);
00049
00050         // The string is empty if there is no such device.
00051         if (deviceId.empty())
00052         {
00053             rootPage.NotifyUser(L"No audio devices available", NotifyType::StatusMessage);
00054             co_return;
00055         }
00056
00057         // read property store to see if the device supports a RAW processing mode
00058         static constexpr wchar_t PKEY_AudioDevice_RawProcessingSupported[] = L"System.Devices.AudioDevice.RawProcessingSupported";
00059         DeviceInformation deviceInformation = co_await DeviceInformation::CreateFromIdAsync(deviceId, { PKEY_AudioDevice_RawProcessingSupported });
00060
00061         std::optional<bool> obj = deviceInformation.Properties().TryLookup(PKEY_AudioDevice_RawProcessingSupported).try_as<bool>();
00062         m_deviceSupportsRawMode = (obj == true);
00063         toggleRawAudio().IsEnabled(m_deviceSupportsRawMode);
00064
00065         if (m_deviceSupportsRawMode)
00066         {
00067             rootPage.NotifyUser(L"Raw Supported", NotifyType::StatusMessage);
00068         }
00069         else
00070         {
00071             rootPage.NotifyUser(L"Raw Not Supported", NotifyType::StatusMessage);
00072         }
00073     }
00074
00075     void Scenario3::OnNavigatedFrom(NavigationEventArgs const&)
00076     {
00077         StopDevice();
00078
00079         if (m_deviceStateChangeToken)
00080         {
00081             m_renderer->DeviceStateChanged(std::exchange(m_deviceStateChangeToken, {}));
00082         }
00083
00084         if (m_systemMediaControlsButtonToken)
00085         {
00086             m_systemMediaControls.ButtonPressed(m_systemMediaControlsButtonToken);
00087             m_systemMediaControls.IsPlayEnabled(false);
00088             m_systemMediaControls.IsPauseEnabled(false);
00089             m_systemMediaControls.IsStopEnabled(false);
00090             m_systemMediaControls.PlaybackStatus(MediaPlaybackStatus::Closed);
00091         }
00092     }
00093
00094 #pragma region UI Related Code
00095
00096     void Scenario3::DisableContentUI()
00097     {
00098         btnFilePicker().IsEnabled(false);
00099         sliderFrequency().IsEnabled(false);
00100         radioFile().IsEnabled(false);
00101         radioTone().IsEnabled(false);
00102     }
00103
00104     // Updates content controls based on selected option
00105     void Scenario3::UpdateContentUI()
00106     {
00107         // Ignore calls triggered by binding before construction is complete.
00108         if (radioFile() == nullptr)
00109         {
00110             return;
00111         }
00112
00113         radioFile().IsEnabled(true);
00114         radioTone().IsEnabled(true);
00115
00116         switch (m_contentType)
00117         {
00118         case ContentType::Tone:
00119             btnFilePicker().IsEnabled(false);
00120             sliderFrequency().IsEnabled(true);
00121             UpdateContentProps(to_hstring(sliderFrequency().Value()) + L" Hz");
00122             break;
00123
00124         case ContentType::File:
00125             btnFilePicker().IsEnabled(true);
00126             sliderFrequency().IsEnabled(false);
00127             break;
00128
00129         default:
00130             break;
00131         }
00132     }
00133
00134     // Updates transport controls based on current playstate
00135     void Scenario3::UpdateMediaControlUI(DeviceState deviceState)
00136     {
00137         switch (deviceState)
00138         {
00139         case DeviceState::Playing:
00140             btnPlay().IsEnabled(false);
00141             btnStop().IsEnabled(true);
00142             btnPlayPause().IsEnabled(true);
00143             btnPause().IsEnabled(true);
00144             toggleMinimumLatency().IsEnabled(false);
00145             break;
00146
00147         case DeviceState::Stopped:
00148         case DeviceState::Error:
00149             btnPlay().IsEnabled(true);
00150             btnStop().IsEnabled(false);
00151             btnPlayPause().IsEnabled(true);
00152             btnPause().IsEnabled(false);
00153             toggleMinimumLatency().IsEnabled(true);
00154
00155             UpdateContentUI();
00156             break;
00157
00158         case DeviceState::Paused:
00159             btnPlay().IsEnabled(true);
00160             btnStop().IsEnabled(true);
00161             btnPlayPause().IsEnabled(true);
00162             btnPause().IsEnabled(false);
00163             break;
00164
00165         case DeviceState::Starting:
00166         case DeviceState::Stopping:
00167             btnPlay().IsEnabled(false);
00168             btnStop().IsEnabled(false);
00169             btnPlayPause().IsEnabled(false);
00170             btnPause().IsEnabled(false);
00171
00172             DisableContentUI();
00173             break;
00174         }
00175     }
00176
00177     // Updates textbox
00178     void Scenario3::UpdateContentProps(hstring const& text)
00179     {
00180         // Ignore calls triggered by binding before construction is complete.
00181         if (txtContentProps() == nullptr)
00182         {
00183             return;
00184         }
00185
00186         txtContentProps().Text(text);
00187
00188         if (text.empty() && (m_contentType == ContentType::File))
00189         {
00190             txtContentProps().Background(SolidColorBrush({ 0xCC, 0xFF, 0x00, 0x00 }));
00191         }
00192         else
00193         {
00194             txtContentProps().Background(nullptr);
00195         }
00196     }
00197
00198 #pragma endregion
00199
00200 #pragma region UI Event Handlers
00201     void Scenario3::sliderFrequency_ValueChanged(IInspectable const&, RangeBaseValueChangedEventArgs const& e)
00202     {
00203         UpdateContentProps(to_hstring(e.NewValue()) + L" Hz");
00204     }
00205
00206     void Scenario3::sliderVolume_ValueChanged(IInspectable const&, RangeBaseValueChangedEventArgs const& e)
00207     {
00208         OnSetVolume(e.NewValue());
00209     }
00210
00211     void Scenario3::radioTone_Checked(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00212     {
00213         m_contentType = ContentType::Tone;
00214         UpdateContentProps(L"");
00215         m_contentStream = nullptr;
00216         UpdateContentUI();
00217     }
00218
00219     void Scenario3::radioFile_Checked(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00220     {
00221         m_contentType = ContentType::File;
00222         UpdateContentProps(L"");
00223         m_contentStream = nullptr;
00224         UpdateContentUI();
00225     }
00226
00227     void Scenario3::btnPlay_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00228     {
00229         StartDevice();
00230     }
00231
00232     void Scenario3::btnPause_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00233     {
00234         PauseDevice();
00235     }
00236
00237     void Scenario3::btnPlayPause_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00238     {
00239         PlayPauseToggleDevice();
00240     }
00241
00242     void Scenario3::btnStop_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00243     {
00244         StopDevice();
00245     }
00246
00247     void Scenario3::btnFilePicker_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00248     {
00249         OnPickFileAsync();
00250     }
00251
00252 #pragma endregion
00253
00254     // Event callback from WASAPI renderer for changes in device state
00255     fire_and_forget Scenario3::OnDeviceStateChange(IDeviceStateSource const&, SDKTemplate::DeviceStateChangedEventArgs e)
00256     {
00257         auto lifetime = get_strong();
00258
00259         // Handle state specific messages
00260         switch (e.DeviceState())
00261         {
00262         case DeviceState::Initialized:
00263             StartDevice();
00264             m_systemMediaControls.PlaybackStatus(MediaPlaybackStatus::Closed);
00265             break;
00266
00267         case DeviceState::Playing:
00268             if (m_isMinimumLatency == true)
00269             {
00270                 rootPage.NotifyUser(L"Playback Started (minimum latency)", NotifyType::StatusMessage);
00271             }
00272             else
00273             {
00274                 rootPage.NotifyUser(L"Playback Started (normal latency)", NotifyType::StatusMessage);
00275             }
00276             m_systemMediaControls.PlaybackStatus(MediaPlaybackStatus::Playing);
00277             break;
00278
00279         case DeviceState::Paused:
00280             rootPage.NotifyUser(L"Playback Paused", NotifyType::StatusMessage);
00281             m_systemMediaControls.PlaybackStatus(MediaPlaybackStatus::Paused);
00282             break;
00283
00284         case DeviceState::Stopped:
00285             if (m_deviceStateChangeToken)
00286             {
00287                 m_renderer->DeviceStateChanged(std::exchange(m_deviceStateChangeToken, {}));
00288             }
00289             m_renderer = nullptr;
00290
00291             rootPage.NotifyUser(L"Playback Stopped", NotifyType::StatusMessage);
00292             m_systemMediaControls.PlaybackStatus(MediaPlaybackStatus::Stopped);
00293             break;
00294
00295         case DeviceState::Error:
00296             if (m_deviceStateChangeToken)
00297             {
00298                 m_renderer->DeviceStateChanged(std::exchange(m_deviceStateChangeToken, {}));
00299             }
00300             m_renderer = nullptr;
00301
00302             m_systemMediaControls.PlaybackStatus(MediaPlaybackStatus::Closed);
00303
00304             // Specifically handle a couple of known errors
00305             auto error = e.ExtendedError();
00306             switch (error)
00307             {
00308             case AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE:
00309                 rootPage.NotifyUser(L"ERROR: Endpoint Does Not Support HW Offload", NotifyType::ErrorMessage);
00310                 break;
00311
00312             case AUDCLNT_E_RESOURCES_INVALIDATED:
00313                 rootPage.NotifyUser(L"ERROR: Endpoint Lost Access To Resources", NotifyType::ErrorMessage);
00314                 break;
00315
00316             default:
00317                 rootPage.NotifyUser(L"ERROR: " + hresult_error(error).message(), NotifyType::ErrorMessage);
00318                 break;
00319             }
00320         }
00321
00322         // Update Control Buttons
00323         co_await resume_foreground(Dispatcher());
00324         UpdateMediaControlUI(e.DeviceState());
00325     }
00326
00327     //
00328     //  OnPickFileAsync()
00329     //
00330     //  File chooser for MF Source playback.  Retrieves a pointer to IRandomAccessStream
00331     //
00332     fire_and_forget Scenario3::OnPickFileAsync()
00333     {
00334         auto lifetime = get_strong();
00335         FileOpenPicker filePicker;
00336         filePicker.ViewMode(PickerViewMode::List);
00337         filePicker.SuggestedStartLocation(PickerLocationId::MusicLibrary);
00338         filePicker.FileTypeFilter().ReplaceAll({ L".wav", L".mp3", L".wma" });
00339
00340         StorageFile file = co_await filePicker.PickSingleFileAsync();
00341         if (file != nullptr)
00342         {
00343             // Open the stream
00344             IRandomAccessStream stream = co_await file.OpenAsync(FileAccessMode::Read);
00345             if (stream != nullptr)
00346             {
00347                 m_contentStream = stream;
00348                 UpdateContentProps(file.Path());
00349             }
00350         }
00351     }
00352
00353     //
00354     //  OnSetVolume()
00355     //
00356     //  Updates the session volume
00357     //
00358     void Scenario3::OnSetVolume(double volume)
00359     {
00360         if (m_renderer)
00361         {
00362             // Updates the Session volume on the AudioClient
00363             m_renderer->SetVolumeOnSession(volume);
00364         }
00365     }
00366
00367     //
00368     //  InitializeDevice()
00369     //
00370     //  Sets up a new instance of the WASAPI renderer
00371     //
00372     void Scenario3::InitializeDevice()
00373     {
00374         if (m_renderer)
00375         {
00376             // Already initialized.
00377             return;
00378         }
00379
00380         // Create a new WASAPI instance
00381         m_renderer = make_self<WASAPIRenderer>();
00382
00383         // Register for events
00384         m_deviceStateChangeToken = m_renderer->DeviceStateChanged({ get_weak(), &Scenario3::OnDeviceStateChange });
00385
00386         // Configure user based properties
00387         m_renderer->SetContentType(m_contentType);
00388         m_renderer->SetFrequency(sliderFrequency().Value());
00389         m_renderer->SetContentStream(m_contentStream);
00390
00391         m_isMinimumLatency = toggleMinimumLatency().IsOn();
00392         m_renderer->SetLowLatency(m_isMinimumLatency);
00393         m_renderer->SetHWOffload(false);
00394         m_renderer->SetBackgroundAudio(false);
00395         m_renderer->SetRawAudio(m_deviceSupportsRawMode && toggleRawAudio().IsOn());
00396
00397         // Selects the Default Audio Device
00398         m_renderer->AsyncInitializeAudioDevice();
00399
00400         // Set the initial volume.
00401         OnSetVolume(sliderVolume().Value());
00402     }
00403
00404     void Scenario3::StartDevice()
00405     {
00406         if (m_renderer == nullptr)
00407         {
00408             // Call from main UI thread
00409             InitializeDevice();
00410         }
00411         else
00412         {
00413             // Starts a work item to begin playback, likely in the paused state
00414             m_renderer->StartPlayback();
00415         }
00416     }
00417
00418     void Scenario3::StopDevice()
00419     {
00420         if (m_renderer)
00421         {
00422             // Set the event to stop playback
00423             m_renderer->StopPlaybackAsync();
00424         }
00425     }
00426
00427     void Scenario3::PauseDevice()
00428     {
00429         if (m_renderer)
00430         {
00431             if (m_renderer->DeviceState() == DeviceState::Playing)
00432             {
00433                 // Starts a work item to pause playback
00434                 m_renderer->PausePlaybackAsync();
00435             }
00436         }
00437     }
00438
00439     //
00440     //  PlayPauseToggleDevice()
00441     //
00442     void Scenario3::PlayPauseToggleDevice()
00443     {
00444         if (m_renderer)
00445         {
00446             DeviceState deviceState = m_renderer->DeviceState();
00447
00448             if (deviceState == DeviceState::Playing)
00449             {
00450                 // Starts a work item to pause playback
00451                 m_renderer->PausePlaybackAsync();
00452             }
00453             else if (deviceState == DeviceState::Paused)
00454             {
00455                 // Starts a work item to pause playback
00456                 m_renderer->StartPlayback();
00457             }
00458         }
00459         else
00460         {
00461             StartDevice();
00462         }
00463     }
00464
00465     //
00466     //   MediaButtonPressed
00467     //
00468     fire_and_forget Scenario3::MediaButtonPressed(SystemMediaTransportControls const&, SystemMediaTransportControlsButtonPressedEventArgs e)
00469     {
00470         auto lifetime = get_strong();
00471         co_await resume_foreground(Dispatcher());
00472
00473         switch (e.Button())
00474         {
00475         case SystemMediaTransportControlsButton::Play:
00476             StartDevice();
00477             break;
00478
00479         case SystemMediaTransportControlsButton::Pause:
00480             PauseDevice();
00481             break;
00482
00483         case SystemMediaTransportControlsButton::Stop:
00484             StopDevice();
00485             break;
00486
00487         default:
00488             break;
00489         }
00490     }
00491 }
Generated on Fri Nov 15 2024 22:19:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceStateSourceT< D > Member List

This is the complete list of members for DeviceStateSourceT< D >, including all inherited members.
DeviceState() | DeviceStateSourceT< D > | [inline]
DeviceStateChanged(Windows::Foundation::TypedEventHandler< IDeviceStateSource, SDKTemplate::DeviceStateChangedEventArgs > const &handler) | DeviceStateSourceT< D > | [inline]
DeviceStateChanged(event_token token) | DeviceStateSourceT< D > | [inline]
m_deviceState | DeviceStateSourceT< D > | [protected]
m_deviceStateChanged | DeviceStateSourceT< D > | [protected]
SetState(enum DeviceState state, HRESULT error=S_OK) | DeviceStateSourceT< D > | [inline, protected]
SetStateNoNotify(enum DeviceState state) | DeviceStateSourceT< D > | [inline, protected]
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/Common/DeviceResources.h Source File

  • BasicHologram
  • cpp
  • Common

DeviceResources.h

Go to the documentation of this file.
00001 ﻿
00002 #pragma once
00003
00004 #include "CameraResources.h"
00005
00006 namespace DX
00007 {
00008     // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created.
00009     interface IDeviceNotify
00010     {
00011         virtual void OnDeviceLost()     = 0;
00012         virtual void OnDeviceRestored() = 0;
00013     };
00014
00015     // Creates and manages a Direct3D device and immediate context, Direct2D device and context (for debug), and the holographic swap chain.
00016     class DeviceResources
00017     {
00018     public:
00019         DeviceResources();
00020
00021         // Public methods related to Direct3D devices.
00022         void HandleDeviceLost();
00023         void RegisterDeviceNotify(IDeviceNotify* deviceNotify);
00024         void Trim();
00025         void Present(Windows::Graphics::Holographic::HolographicFrame^ frame);
00026
00027         // Public methods related to holographic devices.
00028         void SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^ space);
00029         void EnsureCameraResources(
00030             Windows::Graphics::Holographic::HolographicFrame^ frame,
00031             Windows::Graphics::Holographic::HolographicFramePrediction^ prediction);
00032
00033         void AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^ camera);
00034         void RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^ camera);
00035
00036         // Holographic accessors.
00037         template<typename RetType, typename LCallback>
00038         RetType                 UseHolographicCameraResources(const LCallback& callback);
00039
00040         Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^
00041                                 GetD3DInteropDevice() const             { return m_d3dInteropDevice;    }
00042
00043         // D3D accessors.
00044         ID3D11Device4*          GetD3DDevice() const                    { return m_d3dDevice.Get();     }
00045         ID3D11DeviceContext3*   GetD3DDeviceContext() const             { return m_d3dContext.Get();    }
00046         D3D_FEATURE_LEVEL       GetDeviceFeatureLevel() const           { return m_d3dFeatureLevel;     }
00047         bool                    GetDeviceSupportsVprt() const           { return m_supportsVprt;        }
00048
00049         // DXGI acessors.
00050         IDXGIAdapter3*          GetDXGIAdapter() const                  { return m_dxgiAdapter.Get();   }
00051
00052         // D2D accessors.
00053         ID2D1Factory2*          GetD2DFactory() const                   { return m_d2dFactory.Get();    }
00054         IDWriteFactory2*        GetDWriteFactory() const                { return m_dwriteFactory.Get(); }
00055         IWICImagingFactory2*    GetWicImagingFactory() const            { return m_wicFactory.Get();    }
00056
00057     private:
00058         // Private methods related to the Direct3D device, and resources based on that device.
00059         void CreateDeviceIndependentResources();
00060         void InitializeUsingHolographicSpace();
00061         void CreateDeviceResources();
00062
00063         // Direct3D objects.
00064         Microsoft::WRL::ComPtr<ID3D11Device4>                   m_d3dDevice;
00065         Microsoft::WRL::ComPtr<ID3D11DeviceContext3>            m_d3dContext;
00066         Microsoft::WRL::ComPtr<IDXGIAdapter3>                   m_dxgiAdapter;
00067
00068         // Direct3D interop objects.
00069         Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^ m_d3dInteropDevice;
00070
00071         // Direct2D factories.
00072         Microsoft::WRL::ComPtr<ID2D1Factory2>                   m_d2dFactory;
00073         Microsoft::WRL::ComPtr<IDWriteFactory2>                 m_dwriteFactory;
00074         Microsoft::WRL::ComPtr<IWICImagingFactory2>             m_wicFactory;
00075
00076         // The holographic space provides a preferred DXGI adapter ID.
00077         Windows::Graphics::Holographic::HolographicSpace^       m_holographicSpace = nullptr;
00078
00079         // Properties of the Direct3D device currently in use.
00080         D3D_FEATURE_LEVEL                                       m_d3dFeatureLevel = D3D_FEATURE_LEVEL_10_0;
00081
00082         // The IDeviceNotify can be held directly as it owns the DeviceResources.
00083         IDeviceNotify*                                          m_deviceNotify = nullptr;
00084
00085         // Whether or not the current Direct3D device supports the optional feature
00086         // for setting the render target array index from the vertex shader stage.
00087         bool                                                    m_supportsVprt = false;
00088
00089         // Back buffer resources, etc. for attached holographic cameras.
00090         std::map<UINT32, std::unique_ptr<CameraResources>>      m_cameraResources;
00091         std::mutex                                              m_cameraResourcesLock;
00092     };
00093 }
00094
00095 // Device-based resources for holographic cameras are stored in a std::map. Access this list by providing a
00096 // callback to this function, and the std::map will be guarded from add and remove
00097 // events until the callback returns. The callback is processed immediately and must
00098 // not contain any nested calls to UseHolographicCameraResources.
00099 // The callback takes a parameter of type std::map<UINT32, std::unique_ptr<DX::CameraResources>>&
00100 // through which the list of cameras will be accessed.
00101 template<typename RetType, typename LCallback>
00102 RetType DX::DeviceResources::UseHolographicCameraResources(const LCallback& callback)
00103 {
00104     std::lock_guard<std::mutex> guard(m_cameraResourcesLock);
00105     return callback(m_cameraResources);
00106 }
00107
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/PixelShader/SampleOverlay.h Source File

  • D2DCustomEffects
  • cpp
  • PixelShader

SampleOverlay.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "DirectXHelper.h"
00015 #include "DeviceResources.h"
00016
00017 // This class is responsible for initializing and rendering the title overlay visible
00018 // at the top of the DirectX SDK samples.
00019 namespace CustomPixelShader
00020 {
00021     class SampleOverlay
00022     {
00023     public:
00024         SampleOverlay(const std::shared_ptr<DX::DeviceResources>& deviceResources, const std::wstring& caption);
00025         void CreateDeviceDependentResources();
00026         void CreateWindowSizeDependentResources();
00027         void ReleaseDeviceDependentResources();
00028         void Render();
00029         float GetTitleHeightInDips();
00030
00031     private:
00032         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00033
00034         Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00035         Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00036
00037         Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00038         Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00039
00040         UINT                                            m_idIncrement;
00041         bool                                            m_drawOverlay;
00042         std::wstring                                    m_caption;
00043         float                                           m_padding;
00044         float                                           m_textVerticalOffset;
00045         D2D1_SIZE_F                                     m_logoSize;
00046         float                                           m_overlayWidth;
00047     };
00048 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ComPtrList< T, NULLABLE > Member List

This is the complete list of members for ComPtrList< T, NULLABLE >, including all inherited members.
Back() const | List< T * > | [inline, protected]
Clear() | ComPtrList< T, NULLABLE > | [inline, virtual]
List< T * >::Clear(FN &clear_fn) | List< T * > | [inline]
EndPosition() const | List< T * > | [inline]
Front() const | List< T * > | [inline, protected]
FrontPosition() | List< T * > | [inline]
GetBack(T **ppItem) | List< T * > | [inline]
GetCount() const | List< T * > | [inline]
GetFront(T **ppItem) | List< T * > | [inline]
GetItem(const Node *pNode, Ptr *ppItem) | ComPtrList< T, NULLABLE > | [inline, protected]
List< T * >::GetItem(const Node *pNode, T **ppItem) | List< T * > | [inline, protected, virtual]
GetItemPos(POSITION pos, T **ppItem) | List< T * > | [inline]
InsertAfter(Ptr item, Node *pBefore) | ComPtrList< T, NULLABLE > | [inline, protected]
List< T * >::InsertAfter(T *item, Node *pBefore) | List< T * > | [inline, protected, virtual]
InsertBack(T *item) | List< T * > | [inline]
InsertFront(T *item) | List< T * > | [inline]
InsertPos(POSITION pos, T *item) | List< T * > | [inline]
IsEmpty() const | List< T * > | [inline]
List() | List< T * > | [inline]
m_anchor | List< T * > | [protected]
m_count | List< T * > | [protected]
Next(const POSITION pos) | List< T * > | [inline]
Ptr typedef | ComPtrList< T, NULLABLE > |
Remove(POSITION &pos, T **ppItem) | List< T * > | [inline]
RemoveBack(T **ppItem) | List< T * > | [inline]
RemoveFront(T **ppItem) | List< T * > | [inline]
RemoveItem(Node *pNode, Ptr *ppItem) | ComPtrList< T, NULLABLE > | [inline, protected]
List< T * >::RemoveItem(Node *pNode, T **ppItem) | List< T * > | [inline, protected, virtual]
~ComPtrList() | ComPtrList< T, NULLABLE > | [inline]
~List() | List< T * > | [inline, virtual]
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Client/RpcClient.h Source File

  • CustomCapability
  • Service
  • Client

RpcClient.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012
00013 #define RPC_STATIC_ENDPOINT L"HsaSampleRpcEndpoint"
00014
00015 #include "RpcInterface_h.h"
00016
00017
00018 /// <summary>
00019 /// Client side RPC implementation
00020 /// </summary>
00021 class RpcClient sealed
00022 {
00023 public:
00024     ~RpcClient();
00025     __int64 Initialize();
00026     __int64 StartMeteringAndWaitForStop(__int64 samplePeriod);
00027     __int64 StopMetering();
00028     __int64 SetSampleRate(int rate);
00029     int CallbackCount;
00030     __int64 MeteringData;
00031 private:
00032     handle_t hRpcBinding;
00033     PCONTEXT_HANDLE_TYPE phContext;
00034 };
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PasswordVault/cppwinrt/Scenario1_Save.cpp Source File

  • PasswordVault
  • cppwinrt

Scenario1_Save.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_Save.h"
00014 #include "Scenario1_Save.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::UI::Xaml;
00019 using namespace Windows::Security::Credentials;
00020
00021 namespace winrt::SDKTemplate::implementation
00022 {
00023     Scenario1_Save::Scenario1_Save()
00024     {
00025         InitializeComponent();
00026     }
00027
00028     void Scenario1_Save::SaveCredential_Click(IInspectable const&, IInspectable const&)
00029     {
00030         auto resource = InputResourceValue().Text();
00031         auto userName = InputUserNameValue().Text();
00032         auto password = InputPasswordValue().Password();
00033
00034         if (resource.empty() || userName.empty() || password.empty())
00035         {
00036             rootPage.NotifyUser(L"All fields are required when saving a credential.", NotifyType::ErrorMessage);
00037         }
00038         else
00039         {
00040             // Add a credential to PasswordVault with provided resource, user name, and password.
00041             // Replaces any existing credential with the same resource and user name.
00042             PasswordVault vault;
00043             PasswordCredential cred{ resource, userName, password };
00044             vault.Add(cred);
00045
00046             rootPage.NotifyUser(L"Credential saved successfully. Resource: " + cred.Resource() + L" Username: " + cred.UserName() + L" Password: " + cred.Password(), NotifyType::StatusMessage);
00047         }
00048     }
00049 }
00050
Generated on Fri Nov 15 2024 22:20:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cppwinrt/Scenario2_Launch.h Source File

  • ResizeAppView
  • cppwinrt

Scenario2_Launch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Launch.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_Launch : Scenario2_LaunchT<Scenario2_Launch>
00019     {
00020         Scenario2_Launch();
00021
00022         // These methods are public so they can be called by binding.
00023         void LaunchAtSize_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024     };
00025 }
00026
00027 namespace winrt::SDKTemplate::factory_implementation
00028 {
00029     struct Scenario2_Launch : Scenario2_LaunchT<Scenario2_Launch, implementation::Scenario2_Launch>
00030     {
00031     };
00032 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LowLatencyInput/cpp/Scenario1_LowLatencyInput.xaml.h Source File

  • LowLatencyInput
  • cpp

Scenario1_LowLatencyInput.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_LowLatencyInput.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 #include "Common\DeviceResources.h"
00018 #include "LowLatencyInputMain.h"
00019 #include "Common\Constants.h"
00020
00021 namespace SDKTemplate
00022 {
00023     // <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026
00027     [Windows::Foundation::Metadata::WebHostHidden]
00028     public ref class ManipulationProcessor sealed
00029     {
00030     public:
00031         ManipulationProcessor(Windows::UI::Input::GestureRecognizer^ gestureRecognizer, Windows::UI::Xaml::Controls::Border^ target, Windows::UI::Xaml::UIElement^ referenceFrame);
00032         void InitializeTransforms();
00033         void ResetRect();
00034
00035     private:
00036         Windows::UI::Input::GestureRecognizer^ xamlGestureRecognizer;
00037         Windows::UI::Xaml::Controls::Border^ element;
00038         Windows::UI::Xaml::UIElement^ reference;
00039         Windows::UI::Xaml::Media::TransformGroup^ cumulativeTransform;
00040         Windows::UI::Xaml::Media::MatrixTransform^ previousTransform;
00041         Windows::UI::Xaml::Media::CompositeTransform^ deltaTransform;
00042
00043         void OnPointerPressed(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args);
00044         void OnPointerMoved(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args);
00045         void OnPointerReleased(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args);
00046         void OnPointerCanceled(Platform::Object^ sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args);
00047         void OnManipulationStarted(Windows::UI::Input::GestureRecognizer^ sender, Windows::UI::Input::ManipulationStartedEventArgs^ args);
00048         void OnManipulationUpdated(Windows::UI::Input::GestureRecognizer^ sender, Windows::UI::Input::ManipulationUpdatedEventArgs^ args);
00049         void OnManipulationInertiaStarting(Windows::UI::Input::GestureRecognizer^ sender, Windows::UI::Input::ManipulationInertiaStartingEventArgs^ args);
00050         void OnManipulationCompleted(Windows::UI::Input::GestureRecognizer^ sender, Windows::UI::Input::ManipulationCompletedEventArgs^ args);
00051     };
00052
00053     [Windows::Foundation::Metadata::WebHostHidden]
00054     public ref class Scenario1_LowLatencyInput sealed
00055     {
00056         public:
00057             Scenario1_LowLatencyInput();
00058             virtual ~Scenario1_LowLatencyInput();
00059
00060         private:
00061             MainPage^ rootPage;
00062             // XAML low-level rendering event handler.
00063             void OnRendering(Platform::Object^ sender, Platform::Object^ args);
00064
00065             // Window event handlers.
00066             void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00067             void OnSizeChanged(Windows::UI::Core::CoreWindow ^sender, Windows::UI::Core::WindowSizeChangedEventArgs ^args);
00068
00069             // DisplayInformation event handlers.
00070             void OnDpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00071             void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00072             void OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00073
00074             // Other event handlers.
00075             void OnCompositionScaleChanged(Windows::UI::Xaml::Controls::SwapChainPanel^ sender, Object^ args);
00076             void OnSwapChainPanelSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ args);
00077             void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
00078
00079             // Track our independent input on a background worker thread.
00080             Windows::Foundation::IAsyncAction^ inputLoopWorker;
00081             Windows::UI::Core::CoreIndependentInputSource^ coreInput;
00082
00083             // Independent input handling functions.
00084             void OnPointerPressed(Platform::Object^ sender, Windows::UI::Core::PointerEventArgs^ args);
00085             void OnPointerMoved(Platform::Object^ sender, Windows::UI::Core::PointerEventArgs^ args);
00086             void OnPointerReleased(Platform::Object^ sender, Windows::UI::Core::PointerEventArgs^ args);
00087             void OnPointerExited(Platform::Object^ sender, Windows::UI::Core::PointerEventArgs^ args);
00088
00089             // Gesture recognizer event handlers
00090             void OnManipulationStarted(
00091                  Windows::UI::Input::GestureRecognizer^ sender,  Windows::UI::Input::ManipulationStartedEventArgs^ args);
00092             void OnManipulationUpdated(
00093                  Windows::UI::Input::GestureRecognizer^ sender,  Windows::UI::Input::ManipulationUpdatedEventArgs^ args);
00094             void OnManipulationInertiaStarting(
00095                  Windows::UI::Input::GestureRecognizer^ sender,  Windows::UI::Input::ManipulationInertiaStartingEventArgs^ args);
00096             void OnManipulationCompleted(
00097                  Windows::UI::Input::GestureRecognizer^ sender,  Windows::UI::Input::ManipulationCompletedEventArgs^ args);
00098
00099             // Resources used to render the DirectX content in the XAML page background.
00100             std::shared_ptr<DX::DeviceResources> deviceResources;
00101             std::unique_ptr<SDKTemplate::LowLatencyInputMain> main;
00102             bool windowVisible;
00103
00104             Windows::UI::Xaml::DispatcherTimer^ dispatcherTimer;
00105
00106             //Gesture recognizers for the XAML rect and DirectX rendered rect
00107             Windows::UI::Input::GestureRecognizer^ directXGestureRecognizer;
00108             Windows::UI::Input::GestureRecognizer^ xamlGestureRecognizer;
00109             SDKTemplate::ManipulationProcessor^ manipulationProcessor;
00110
00111             // UI button event handlers
00112             void ResetButton_Pressed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00113             void BlockUIThread_Toggled(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00114             void DispatcherTimer_Tick(Platform::Object^ sender, Platform::Object^ e);
00115     };
00116 }
00117
Generated on Fri Nov 15 2024 22:20:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MicrosoftPassport/Server/Controllers/HomeController.cs Source File

  • MicrosoftPassport
  • Server
  • Controllers

HomeController.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 // Please refer to the Microsoft Passport and Windows Hello
00012 // whitepaper on the Windows Dev Center for a complete
00013 // explanation of Microsoft Passport and Windows Hello
00014 // implementation:
00015 // http://go.microsoft.com/fwlink/p/?LinkId=522066
00016 //*********************************************************
00017 using System.Web.Mvc;
00018
00019 namespace MicrosoftPassport.Server.Controllers
00020 {
00021     public class HomeController : Controller
00022     {
00023         // GET: Home
00024         public ActionResult Index()
00025         {
00026             return View();
00027         }
00028     }
00029 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HttpJsonContent Member List

This is the complete list of members for HttpJsonContent, including all inherited members.
BufferAllAsync() | HttpJsonContent |
Close() | HttpJsonContent | [inline]
GetLength() | HttpJsonContent | [private]
Headers() | HttpJsonContent | [inline]
HttpJsonContent(Windows::Data::Json::IJsonValue const &jsonValue) | HttpJsonContent |
m_headers | HttpJsonContent | [private]
m_jsonValue | HttpJsonContent | [private]
ReadAsBufferAsync() | HttpJsonContent |
ReadAsInputStreamAsync() | HttpJsonContent |
ReadAsStringAsync() | HttpJsonContent |
ToBuffer() | HttpJsonContent | [private]
TryComputeLength(uint64_t &length) | HttpJsonContent |
WriteToStreamAsync(Windows::Storage::Streams::IOutputStream outputStream) | HttpJsonContent |
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialSound/cpp/SampleConfiguration.cpp Source File

  • SpatialSound
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012
00013 #include "pch.h"
00014 #include "MainPage.xaml.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace SDKTemplate;
00018
00019 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00020 {
00021     { "Omnidirectional source", "SDKTemplate.Scenario1_OmnidirectionalSound" },
00022     { "Cardioid source", "SDKTemplate.Scenario2_CardioidSound" },
00023     { "Custom decay", "SDKTemplate.Scenario3_CustomDecay" }
00024 };
Generated on Fri Nov 15 2024 22:17:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cs/Scenario5_VerifyResponse.xaml.cs Source File

  • SmartCard
  • cs

Scenario5_VerifyResponse.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.Devices.SmartCards;
00003 using Windows.Storage.Streams;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 namespace SDKTemplate
00008 {
00009     public sealed partial class Scenario5_VerifyResponse : Page
00010     {
00011         MainPage rootPage = MainPage.Current;
00012
00013         public Scenario5_VerifyResponse()
00014         {
00015             this.InitializeComponent();
00016         }
00017
00018         /// <summary>
00019         /// Click handler for the 'VerifyResponse' button.
00020         /// </summary>
00021         /// <param name="sender"></param>
00022         /// <param name="e"></param>
00023         private async void VerifyResponse_Click(object sender, RoutedEventArgs e)
00024         {
00025             if (!rootPage.ValidateTPMSmartCard())
00026             {
00027                 rootPage.NotifyUser("Use Scenario One to create a TPM virtual smart card.", NotifyType.ErrorMessage);
00028                 return;
00029             }
00030
00031             Button b = sender as Button;
00032             b.IsEnabled = false;
00033
00034             try
00035             {
00036                 bool verifyResult = false;
00037                 SmartCard card = await rootPage.GetSmartCard();
00038                 SmartCardProvisioning provisioning = await SmartCardProvisioning.FromSmartCardAsync(card);
00039
00040                 rootPage.NotifyUser("Verifying smart card response...", NotifyType.StatusMessage);
00041
00042                 using (SmartCardChallengeContext context = await provisioning.GetChallengeContextAsync())
00043                 {
00044                     IBuffer response = ChallengeResponseAlgorithm.CalculateResponse(context.Challenge, rootPage.AdminKey);
00045                     verifyResult = await context.VerifyResponseAsync(response);
00046                 }
00047
00048                 rootPage.NotifyUser("Smart card response verification completed. Result: " + verifyResult.ToString(), NotifyType.StatusMessage);
00049             }
00050             catch (Exception ex)
00051             {
00052                 rootPage.NotifyUser( "Verifying smart card response operation failed with exception: " + ex.ToString(), NotifyType.ErrorMessage);
00053             }
00054             finally
00055             {
00056                 b.IsEnabled = true;
00057             }
00058         }
00059     }
00060 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
BackgroundTask_Canceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^sender, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason args) | sealed | [private]
BarcodeScannerProviderConnection_DisableScannerRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^sender, Windows::Devices::PointOfService::Provider::BarcodeScannerDisableScannerRequestEventArgs^args) | sealed | [private]
BarcodeScannerProviderConnection_EnableScannerRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^sender, Windows::Devices::PointOfService::Provider::BarcodeScannerEnableScannerRequestEventArgs^args) | sealed | [private]
BarcodeScannerProviderConnection_GetBarcodeSymbologyAttributesRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^sender, Windows::Devices::PointOfService::Provider::BarcodeScannerGetSymbologyAttributesRequestEventArgs^args) | sealed | [private]
BarcodeScannerProviderConnection_HideVideoPreviewRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^sender, Windows::Devices::PointOfService::Provider::BarcodeScannerHideVideoPreviewRequestEventArgs^args) | sealed | [private]
BarcodeScannerProviderConnection_SetActiveSymbologiesRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^sender, Windows::Devices::PointOfService::Provider::BarcodeScannerSetActiveSymbologiesRequestEventArgs^args) | sealed | [private]
BarcodeScannerProviderConnection_SetBarcodeSymbologyAttributesRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^sender, Windows::Devices::PointOfService::Provider::BarcodeScannerSetSymbologyAttributesRequestEventArgs^args) | sealed | [private]
BarcodeScannerProviderConnection_StartSoftwareTriggerRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^sender, Windows::Devices::PointOfService::Provider::BarcodeScannerStartSoftwareTriggerRequestEventArgs^args) | sealed | [private]
BarcodeScannerProviderConnection_StopSoftwareTriggerRequested(Windows::Devices::PointOfService::Provider::BarcodeScannerProviderConnection^sender, Windows::Devices::PointOfService::Provider::BarcodeScannerStopSoftwareTriggerRequestEventArgs^args) | sealed | [private]
CleanUp() | sealed | [private]
CreateBarcodeScannerReportFromString(Platform::String^barcodeString, UINT barcodeSymbology) | sealed | [private]
FrameReader_FrameArrived(Windows::Devices::PointOfService::Provider::BarcodeScannerFrameReader^sender, Windows::Devices::PointOfService::Provider::BarcodeScannerFrameReaderFrameArrivedEventArgs^args) | sealed | [private]
Initialize() | sealed | [private]
m_backgroundTask | sealed | [private]
m_connection | sealed | [private]
m_decodeEngine | sealed | [private]
m_deferral | sealed | [private]
m_disableScannerRequestedToken | sealed | [private]
m_enableScannerRequestedToken | sealed | [private]
m_frameArrivedToken | sealed | [private]
m_frameReader | sealed | [private]
m_getActiveSymbologiesRequestedToken | sealed | [private]
m_getBarcodeSymbologyAttributesRequestedToken | sealed | [private]
m_hideVideoPreviewRequestedToken | sealed | [private]
m_previousDecodeResult | sealed | [private]
m_scannerEnabled | sealed | [private]
m_setBarcodeSymbologyAttributesRequestedToken | sealed | [private]
m_startSoftwareTriggerRequestedToken | sealed | [private]
m_stopSoftwareTriggerRequestedToken | sealed | [private]
m_symbologyAttributes | sealed | [private]
Provider(Windows::ApplicationModel::Background::IBackgroundTaskInstance^backgroundTask) | sealed |
RegisterEventHandlers() | sealed | [private]
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance) | sealed | [virtual]
Task_Completed(Windows::ApplicationModel::Background::BackgroundTaskRegistration^sender, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
~Provider() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContentIndexer/cpp/S1_AddWithAPI.xaml.h Source File

  • ContentIndexer
  • cpp

S1_AddWithAPI.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // S1_AddWithAPI.xaml.h
00014 // Declaration of the S1_AddWithAPI class
00015 //
00016
00017 #pragma once
00018 #include "S1_AddWithAPI.g.h"
00019
00020 namespace SDKTemplate
00021 {
00022     public ref class S1_AddWithAPI sealed
00023     {
00024     public:
00025         S1_AddWithAPI();
00026
00027     private:
00028         void AddToIndex_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029     };
00030 }
Generated on Fri Nov 15 2024 22:18:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BasicVertex Member List

This is the complete list of members for BasicVertex, including all inherited members.
norm | BasicVertex
pos | BasicVertex
tex | BasicVertex
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_ReadData Member List

This is the complete list of members for Scenario1_ReadData, including all inherited members.
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_ReadData |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_ReadData |
Scenario1_ReadData() | Scenario1_ReadData |
Scenario1_ReadData() | Scenario1_ReadData |
StartScenarioAsync() | Scenario1_ReadData | [private]
StartScenarioAsync() | Scenario1_ReadData | [private]
StartStopScenario_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_ReadData |
StartStopScenario_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_ReadData |
StopScenario() | Scenario1_ReadData | [private]
StopScenario() | Scenario1_ReadData | [private]
Timer_Tick(Windows::Foundation::IInspectable const &sender, Windows::Foundation::IInspectable const &e) | Scenario1_ReadData | [private]
Timer_Tick(Windows::Foundation::IInspectable const &sender, Windows::Foundation::IInspectable const &e) | Scenario1_ReadData | [private]
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/Content/SpatialInputHandler.cpp Source File

  • BasicHologram
  • cpp
  • Content

SpatialInputHandler.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "SpatialInputHandler.h"
00003 #include <functional>
00004
00005 using namespace BasicHologram;
00006 using namespace Windows::Foundation;
00007 using namespace Windows::UI::Input::Spatial;
00008 using namespace std::placeholders;
00009
00010 // Creates and initializes a GestureRecognizer that listens to a Person.
00011 SpatialInputHandler::SpatialInputHandler()
00012 {
00013     // The interaction manager provides an event that informs the app when
00014     // spatial interactions are detected.
00015     m_interactionManager = SpatialInteractionManager::GetForCurrentView();
00016
00017     // Bind a handler to the SourcePressed event.
00018     m_sourcePressedEventToken =
00019         m_interactionManager->SourcePressed +=
00020             ref new TypedEventHandler<SpatialInteractionManager^, SpatialInteractionSourceEventArgs^>(
00021                 bind(&SpatialInputHandler::OnSourcePressed, this, _1, _2)
00022                 );
00023
00024     //
00025     // TODO: Expand this class to use other gesture-based input events as applicable to
00026     //       your app.
00027     //
00028 }
00029
00030 SpatialInputHandler::~SpatialInputHandler()
00031 {
00032     // Unregister our handler for the OnSourcePressed event.
00033     m_interactionManager->SourcePressed -= m_sourcePressedEventToken;
00034 }
00035
00036 // Checks if the user performed an input gesture since the last call to this method.
00037 // Allows the main update loop to check for asynchronous changes to the user
00038 // input state.
00039 SpatialInteractionSourceState^ SpatialInputHandler::CheckForInput()
00040 {
00041     SpatialInteractionSourceState^ sourceState = m_sourceState;
00042     m_sourceState = nullptr;
00043     return sourceState;
00044 }
00045
00046 void SpatialInputHandler::OnSourcePressed(SpatialInteractionManager^ sender, SpatialInteractionSourceEventArgs^ args)
00047 {
00048     m_sourceState = args->State;
00049
00050     //
00051     // TODO: In your app or game engine, rewrite this method to queue
00052     //       input events in your input class or event handler.
00053     //
00054 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDragAndDrop/cs/SampleConfiguration.cs Source File

  • XamlDragAndDrop
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using DragAndDropSampleManaged;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "XAML Drag and Drop";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="ListView Drag and Drop and Reorder", ClassType=typeof(Scenario1_ListView)},
00026             new Scenario() { Title="Drag UI Customization", ClassType=typeof(Scenario2_DragUICustomization)},
00027             new Scenario() { Title="StartDragAsync", ClassType=typeof(Scenario3_StartDragAsync)}
00028         };
00029     }
00030
00031     public class Scenario
00032     {
00033         public string Title { get; set; }
00034         public Type ClassType { get; set; }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cs/Scenario7_FutureAccess.xaml.cs Source File

  • FileAccess
  • cs

Scenario7_FutureAccess.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.IO;
00015 using System.Text;
00016 using Windows.Storage;
00017 using Windows.Storage.AccessCache;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// Persisting access to a storage item for future use.
00026     /// </summary>
00027     public sealed partial class Scenario7 : Page
00028     {
00029         MainPage rootPage = MainPage.Current;
00030
00031         const int FA_E_MAX_PERSISTED_ITEMS_REACHED = unchecked((int)0x80270220);
00032
00033         public Scenario7()
00034         {
00035             this.InitializeComponent();
00036         }
00037
00038         protected override void OnNavigatedTo(NavigationEventArgs e)
00039         {
00040             rootPage.ValidateFile();
00041         }
00042
00043         private void AddToListButton_Click(object sender, RoutedEventArgs e)
00044         {
00045             StorageFile file = rootPage.sampleFile;
00046             if (file != null)
00047             {
00048                 if (MRURadioButton.IsChecked.Value)
00049                 {
00050                     // Add the file to app MRU and possibly system MRU
00051                     RecentStorageItemVisibility visibility = SystemMRUCheckBox.IsChecked.Value ? RecentStorageItemVisibility.AppAndSystem : RecentStorageItemVisibility.AppOnly;
00052                     rootPage.mruToken = StorageApplicationPermissions.MostRecentlyUsedList.Add(file, file.Name, visibility);
00053                     rootPage.NotifyUser($"The file '{file.Name}' was added to the MRU list and a token was stored.", NotifyType.StatusMessage);
00054                 }
00055                 else
00056                 {
00057                     try
00058                     {
00059                         rootPage.falToken = StorageApplicationPermissions.FutureAccessList.Add(file, file.Name);
00060                         rootPage.NotifyUser($"The file '{file.Name}' was added to the FAL list and a token was stored.", NotifyType.StatusMessage);
00061                     }
00062                     catch (Exception ex) when (ex.HResult == FA_E_MAX_PERSISTED_ITEMS_REACHED)
00063                     {
00064                         // A real program would call Remove() to create room in the FAL.
00065                         rootPage.NotifyUser($"The file '{file.Name}' was not added to the FAL list because the FAL list is full.", NotifyType.ErrorMessage);
00066                     }
00067                 }
00068             }
00069             else
00070             {
00071                 rootPage.NotifyUserFileNotExist();
00072             }
00073         }
00074
00075         private void ShowListButton_Click(object sender, RoutedEventArgs e)
00076         {
00077             AccessListEntryView entries;
00078             string listName;
00079             if (MRURadioButton.IsChecked.Value)
00080             {
00081                 listName = "MRU";
00082                 entries = StorageApplicationPermissions.MostRecentlyUsedList.Entries;
00083             }
00084             else
00085             {
00086                 listName = "FAL";
00087                 entries = StorageApplicationPermissions.FutureAccessList.Entries;
00088             }
00089
00090             if (entries.Count > 0)
00091             {
00092                 StringBuilder outputText = new StringBuilder($"The {listName} list contains the following item(s):");
00093                 foreach (AccessListEntry entry in entries)
00094                 {
00095                     outputText.AppendLine();
00096                     outputText.Append(entry.Metadata); // Application previously chose to store file.Name in this field
00097                 }
00098
00099                 rootPage.NotifyUser(outputText.ToString(), NotifyType.StatusMessage);
00100             }
00101             else
00102             {
00103                 rootPage.NotifyUser($"The {listName} list is empty.", NotifyType.ErrorMessage);
00104             }
00105         }
00106
00107         private async void OpenFromListButton_Click(object sender, RoutedEventArgs e)
00108         {
00109             StorageFile file = null;
00110
00111             if (MRURadioButton.IsChecked.Value)
00112             {
00113                 if (rootPage.mruToken != null)
00114                 {
00115                     // When the MRU becomes full, older entries are automatically deleted, so check if the
00116                     // token is still valid before using it.
00117                     if (StorageApplicationPermissions.MostRecentlyUsedList.ContainsItem(rootPage.mruToken))
00118                     {
00119                         // Open the file via the token that was stored when adding this file into the MRU list
00120                         file = await StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(rootPage.mruToken);
00121                     }
00122                     else
00123                     {
00124                         rootPage.NotifyUser("The token is no longer valid.", NotifyType.ErrorMessage);
00125                     }
00126                 }
00127                 else
00128                 {
00129                     rootPage.NotifyUser("This operation requires a token. Add file to the MRU list first.", NotifyType.ErrorMessage);
00130                 }
00131             }
00132             else
00133             {
00134                 if (rootPage.falToken != null)
00135                 {
00136                     // Open the file via the token that was stored when adding this file into the FAL list.
00137                     // The token remains valid until we explicitly remove it.
00138                     file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(rootPage.falToken);
00139                 }
00140                 else
00141                 {
00142                     rootPage.NotifyUser("This operation requires a token. Add file to the FAL list first.", NotifyType.ErrorMessage);
00143                 }
00144             }
00145
00146             if (file != null)
00147             {
00148                 try
00149                 {
00150                     // Read the file
00151                     string fileContent = await FileIO.ReadTextAsync(file);
00152                     rootPage.NotifyUser($"The file '{file.Name}' was opened by a stored token. It contains the following text:\b{fileContent}", NotifyType.StatusMessage);
00153
00154                 }
00155                 catch (Exception ex)
00156                 {
00157                     // I/O errors are reported as exceptions.
00158                     rootPage.NotifyUser($"Error reading file opened from list: {ex.Message}", NotifyType.ErrorMessage);
00159                 }
00160             }
00161         }
00162     }
00163 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Tasks/pch.h Source File

  • DeviceEnumerationAndPairing
  • cppwinrt
  • Tasks

pch.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002 #include <unknwn.h>
00003 #include <winrt/Windows.ApplicationModel.Background.h>
00004 #include <winrt/Windows.Devices.Enumeration.h>
00005 #include <winrt/Windows.Foundation.h>
00006 #include <winrt/Windows.Foundation.Collections.h>
00007 #include <winrt/Windows.Storage.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cs/Scenario8_TransmitAPDU.xaml.cs Source File

  • SmartCard
  • cs

Scenario8_TransmitAPDU.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Xaml;
00003 using Windows.UI.Xaml.Controls;
00004 using Windows.Storage.Streams;
00005 using Windows.Security.Cryptography;
00006 using Windows.Devices.SmartCards;
00007
00008 namespace SDKTemplate
00009 {
00010     public sealed partial class Scenario8_TransmitAPDU : Page
00011     {
00012         MainPage rootPage = MainPage.Current;
00013
00014         public Scenario8_TransmitAPDU()
00015         {
00016             this.InitializeComponent();
00017         }
00018
00019         /// <summary>
00020         /// Click handler for the 'TransmitAPDU' button.
00021         /// </summary>
00022         /// <param name="sender"></param>
00023         /// <param name="e"></param>
00024         private async void Transmit_Click(object sender, RoutedEventArgs e)
00025         {
00026             if (!rootPage.ValidateTPMSmartCard())
00027             {
00028                 rootPage.NotifyUser("Use Scenario One to create a TPM virtual smart card.", NotifyType.ErrorMessage);
00029                 return;
00030             }
00031
00032             Button b = sender as Button;
00033             b.IsEnabled = false;
00034
00035             try
00036             {
00037                 SmartCard card = await rootPage.GetSmartCard();
00038
00039                 IBuffer result = null;
00040
00041                 using (SmartCardConnection connection = await card.ConnectAsync())
00042                 {
00043                     // Read EF.ATR file
00044                     // The command is meant specifically for GIDS cards
00045                     // (such as TPM VSCs), and will fail on other types.
00046                     byte[] readEfAtrBytes = { 0x00, 0xCB, 0x2F, 0x01, 0x02, 0x5C, 0x00, 0xFF };
00047
00048                     IBuffer readEfAtr = CryptographicBuffer.CreateFromByteArray(readEfAtrBytes);
00049
00050                     result = await connection.TransmitAsync(readEfAtr);
00051
00052                     rootPage.NotifyUser("Response: " + CryptographicBuffer.EncodeToHexString(result), NotifyType.StatusMessage);
00053                 }
00054             }
00055             catch (Exception ex)
00056             {
00057                 rootPage.NotifyUser("Transmitting APDU to card failed with exception: " + ex.ToString(), NotifyType.ErrorMessage);
00058             }
00059             finally
00060             {
00061                 b.IsEnabled = true;
00062             }
00063         }
00064     }
00065 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
__pad0__ | sealed | [protected]
_aamvaCardDataReceivedToken | sealed | [private]
_accelerometer | sealed | [private]
_active | sealed | [private]
_angularVelocity | sealed | [private]
_bankCardDataReceivedToken | sealed | [private]
_barDismissed | sealed | [private]
_calibrationTimer | sealed | [private]
_captureFolder | sealed | [private]
_cardioidSound | sealed | [private]
_CCCToken | sealed | [private]
_CCToken | sealed | [private]
_channel | sealed | [private]
_channelLoggingLevel | sealed | [private]
_claimedReader | sealed | [private]
_config | sealed | [private]
_connectedDevices | sealed |
_connectionRequestedToken | sealed | [private]
_contextMenuFlyout | sealed | [private]
_criticalSection | sealed | [private]
_CTS | sealed | [private]
_Current | sealed | [private, static]
_currentHitTestState | sealed | [private]
_currentHitTestSubState | sealed | [private]
_currentMessage | sealed | [private]
_currentState | sealed | [private]
_customDecaySound | sealed | [private]
_dataSource | sealed | [private]
_deletedItem | sealed | [private]
_device | sealed | [private]
_deviceAddedToken | sealed | [private]
_deviceRemovedToken | sealed | [private]
_deviceUpdatedToken | sealed | [private]
_deviceUseBackgroundTaskRegistration | sealed | [private]
_deviceUseTrigger | sealed | [private]
_deviceWatcher | sealed | [private]
_deviceWatcherEnumerationCompletedToken | sealed | [private]
_deviceWatcherStoppedToken | sealed | [private]
_discoveredDevices | sealed |
_discoveryMutex | sealed | [private]
_dispatcher | sealed | [private]
_displayTime | sealed |
_downloadCollection | sealed | [private]
_DPOnPage | sealed | [private, static]
_dragOperation | sealed | [private]
_dropHere | sealed | [private]
_enabled | sealed | [private]
_encodingProperties | sealed | [private]
_eventLogger | sealed | [private]
_fWatcherStarted | sealed | [private]
_gestureRecognizer | sealed | [private]
_height | sealed | [private]
_imageSource | sealed | [private]
_incomingConnectionEventRegistrationToken | sealed | [private]
_independentInput | sealed | [private]
_independentInputEnteringToken | sealed | [private]
_independentInputExitingToken | sealed | [private]
_independentInputHoveringToken | sealed | [private]
_independentInputLostToken | sealed | [private]
_independentInputMovingToken | sealed | [private]
_independentInputPressingToken | sealed | [private]
_independentInputReleasingToken | sealed | [private]
_initialization | sealed | [private]
_initialized | sealed | [private]
_initialPointerPoint | sealed | [private]
_InputFile | sealed | [private]
_inputMode | sealed | [private]
_insideName | sealed | [private]
_instance | sealed | [private, static]
_instance | sealed | [private, static]
_isActive | sealed | [private]
_isBusy | sealed | [private]
_isChannelEnabled | sealed | [private]
_isLoggingEnabled | sealed | [private]
_isPreparingForSuspend | sealed | [private]
_isPreviewing | sealed | [private]
_isRecording | sealed | [private]
_isSent | sealed |
_isTerminator | sealed | [private]
_lamp | sealed | [private]
_lampAvailabilutyChangedEventToken | sealed | [private]
_lastCalibrationTime | sealed | [private]
_latencyMode | sealed | [private]
_listener | sealed | [private]
_listenerSocket | sealed | [private]
_localHostVideo | sealed | [private]
_logFileFullPath | sealed | [private]
_logFileGeneratedCount | sealed | [private]
_longTimeFormatter | sealed | [private]
_mediaCapture | sealed | [private]
_mediaCapture | sealed | [private]
_mediaCaptureFailedEventRegistrationToken | sealed | [private]
_mediaCaptureFailedEventToken | sealed | [private]
_mediaElementFailedEventRegistrationToken | sealed | [private]
_mediaSink | sealed | [private]
_mediaSinkIncomingConnectionEventRegistrationToken | sealed | [private]
_moreButton | sealed |
_navigationDisabled | sealed | [private]
_omnidirectionalSound | sealed | [private]
_onChannelLoggingEnabledToken | sealed | [private]
_onLogFileGeneratedToken | sealed | [private]
_OutputFile | sealed | [private]
_OutputFileExtension | sealed | [private]
_OutputFileName | sealed | [private]
_OutputType | sealed | [private]
_outsideName | sealed | [private]
_pastePosition | sealed | [private]
_percentComplete | sealed |
_pitch | sealed | [private]
_pointerId | sealed | [private]
_prevErasingPoint | sealed | [private]
_previousState | sealed | [private]
_Profile | sealed | [private]
_publisher | sealed | [private]
_radius | sealed | [private]
_reader | sealed | [private]
_recordingStarted | sealed | [private]
_reference | sealed | [private]
_refreshTimer | sealed | [private]
_releaseDeviceRequestedToken | sealed | [private]
_rnd | sealed | [private]
_role | sealed | [private]
_roll | sealed | [private]
_rootPage | sealed | [private]
_rootPage | sealed | [private]
_sceneComposer | sealed | [private]
_sdkSample | sealed | [private]
_selection | sealed | [private]
_selectionPoints | sealed | [private]
_session | sealed | [private]
_session | sealed | [private]
_socketReader | sealed | [private]
_socketWriter | sealed | [private]
_start | sealed | [private]
_state | sealed | [private]
_stateText | sealed |
_statusChangedToken | sealed | [private]
_stokeContinuedToken | sealed | [private]
_stop | sealed | [private]
_storage | sealed |
_storageChanged | sealed |
_streamFilteringCriteria | sealed | [private]
_streamSocket | sealed | [private]
_strokeCanceledToken | sealed | [private]
_strokeEndedToken | sealed | [private]
_strokesCollectedToken | sealed | [private]
_strokeStartedToken | sealed | [private]
_symbol | sealed | [private]
_symbols | sealed | [private]
_taskCompletionToken | sealed | [private]
_timer | sealed | [private]
_timer | sealed | [private]
_timerEventToken | sealed | [private]
_token | sealed |
_Transcoder | sealed | [private]
_type | sealed | [private]
_type | sealed | [private]
_unprocessedInputEnteredToken | sealed | [private]
_unprocessedInputExitedToken | sealed | [private]
_unprocessedInputHoveredToken | sealed | [private]
_unprocessedInputLostToken | sealed | [private]
_unprocessedInputMovedToken | sealed | [private]
_unprocessedInputPressedToken | sealed | [private]
_unprocessedInputReleasedToken | sealed | [private]
_UseMp4 | sealed | [private]
_videoSettingsFilter | sealed | [private]
_visibilityToken | sealed | [private]
_windowSizeEventToken | sealed | [private]
_x | sealed | [private]
_y | sealed | [private]
_yaw | sealed | [private]
_z | sealed | [private]
AAD_CLIENT_ID | sealed | [private]
AAD_SCOPE_REQUESTED | sealed | [private]
accelerometer | sealed | [private]
accelerometerOriginal | sealed | [private]
accelerometerReadingTransform | sealed | [private]
AccessChanged(Windows::Devices::Enumeration::DeviceAccessInformation^sender, Windows::Devices::Enumeration::DeviceAccessChangedEventArgs^args) | sealed | [private]
accessibility | sealed | [private]
Accessibility_HighContrastChanged(Windows::UI::ViewManagement::AccessibilitySettings^sender, Platform::Object^args) | sealed | [private]
AccountAction enum name | sealed | [private]
ACCOUNTS_CONTAINER | sealed | [private]
ActionTransition() | sealed | [private]
actionTransitionFunctions | sealed | [private]
active enum value | sealed | [private]
activeDownloads | sealed | [private]
activeItemIndex | sealed | [private]
activeToolChangedToken | sealed | [private]
actualRpcCallbackRate | sealed | [private]
AddAccount enum value | sealed | [private]
AddAccount_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
addAccountLaunched | sealed | [private]
AddAnimatedTilesClick(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AddAudio_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AddAudio_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AddAudio_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AddCustomIconItems() | sealed | [private]
AddCustomProvider(Platform::String^providerId, Platform::String^authority) | sealed | [private]
AddDeviceAsync(Platform::String^id) | sealed | [private]
AddDeviceToList(Windows::Devices::Enumeration::DeviceInformation^deviceInformation, Platform::String^deviceSelector) | sealed | [private]
AddDeviceWatcher(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher, Platform::String^deviceSelector) | sealed | [private]
AddFolderButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AddFontGlyphItems() | sealed | [private]
AddImageFeedScenario() | sealed |
AddItem(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | sealed | [private]
AddItemForLanguageTag(Platform::String^languageTag) | sealed | [private]
AddItemToEnd() | sealed | [protected]
AddKnownIconItems() | sealed | [private]
AddLayer1() | sealed | [private]
AddLayer1() | sealed | [private]
AddLayer2() | sealed | [private]
AddLayer2() | sealed | [private]
AddLinks(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddLinks(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddLinksAndDescription(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddLinksAndDescription(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddLinksAndDescription(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddLogFileMessageDispatch(Platform::String^message, const std::wstring &logFileFullPath) | sealed | [private]
AddLogFileMessageDispatch(Platform::String^message, const std::wstring &logFileFullPath) | sealed | [private]
AddMessage(Platform::String^message) | sealed | [private]
AddMessage(Platform::String^message) | sealed | [private]
AddMessageDispatch(Platform::String^message) | sealed | [private]
AddMessageDispatch(Platform::String^message) | sealed | [private]
AddOnePrintPreviewPage(Windows::UI::Xaml::Controls::RichTextBlockOverflow^lastRTBOAdded, Windows::Graphics::Printing::PrintPageDescription printPageDescription) override | sealed | [protected, virtual]
SDKTemplate::PrintHelper::AddOnePrintPreviewPage(RichTextBlockOverflow^lastRTBOAdded, Windows::Graphics::Printing::PrintPageDescription printPageDescription) | PrintHelper | [protected, virtual]
AddOptimizationGoal(Windows::Devices::Sensors::SensorOptimizationGoal optimizationGoal) | sealed | [private]
AddPassportToAccountOnServerAsync() | sealed | [private]
AddPrintPages(Platform::Object^sender, Windows::UI::Xaml::Printing::AddPagesEventArgs^e) override | sealed | [protected, virtual]
AddPrintPages(Object^sender, AddPagesEventArgs^e) override | sealed | [protected, virtual]
AddPrintPages(Object^sender, AddPagesEventArgs^e) override | sealed | [protected, virtual]
AddReadingType(Windows::Devices::Sensors::AccelerometerReadingType readingType) | sealed | [private]
AddReadingType(Windows::Devices::Sensors::SensorReadingType readingType) | sealed | [private]
AddToIndex_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AddToIndex_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AddToIndex_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AddToIndex_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AddToIndex_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AddToIndex_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AddToJumpList_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AddToListButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
addToResultGrid(Windows::Services::Maps::OfflineMaps::OfflineMapPackage^package) | sealed | [private]
AddWebAccount(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddWebAccount(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddWebAccount(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddWebAccount(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddWebAccountProvider(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddWebAccountProvider(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddWebAccountProviders(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddWebAccountProviders(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddWebAccountProviders(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
AddWebAccounts(Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
addXamlChildrenButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
adxl345Sensor | sealed | [private]
AllHistory_Checked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AllItems | sealed |
AnalyzeButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
AngularVelocitySlider_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
Animations_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
App() | sealed |
App_BackRequested(Platform::Object^sender, Windows::UI::Core::BackRequestedEventArgs^e) | sealed | [private]
APP_SPECIFIC_PROVIDER_ID | sealed | [private]
APP_SPECIFIC_PROVIDER_NAME | sealed | [private]
AppendOutputLine(Platform::String^value) | sealed | [private]
AppendOutputLine(Platform::String^value) | sealed | [private]
AppendOutputLine(Platform::String^value) | sealed | [private]
AppendOutputLine(Platform::String^value) | sealed | [private]
AppendVideos_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Application_Resuming(Platform::Object^sender, Platform::Object^o) | sealed | [private]
Application_Suspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^e) | sealed | [private]
ApplicationTriggerTask() | sealed |
ApplicationTriggerTask() | sealed |
ApplyRotationLock_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
appResumeEventToken | sealed | [private]
appSuspendEventToken | sealed | [private]
ArchitectureString(Windows::System::ProcessorArchitecture architecture) | sealed | [private]
AreaNone enum value | sealed | [private]
ArePointsNear(Windows::Foundation::Point point1, Windows::Foundation::Point point2, double threshold) | sealed | [private, static]
ArrangeOverride(Windows::Foundation::Size finalSize) override | sealed | [protected]
AspectRatio() | sealed |
AttachDownloads() | sealed | [private]
AttachmentImage_RightTapped(Platform::Object^sender, Windows::UI::Xaml::Input::RightTappedRoutedEventArgs^e) | sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | sealed | [private]
AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^task) | sealed | [private]
AuthenticatePassportAsync() | sealed | [private]
AuthenticatePasswordCredentialsAsync() | sealed | [private]
AuthenticateWithRequestToken(Windows::Security::Credentials::WebAccountProvider^Provider, Platform::String^Scope, Platform::String^ClientID) | sealed | [private]
AuthenticateWithRequestToken(Windows::Security::Credentials::WebAccountProvider^provider, Platform::String^scope, Platform::String^clientID) | sealed | [private]
AuthenticateWithRequestToken(Windows::Security::Credentials::WebAccountProvider^provider, Platform::String^scope, Platform::String^clientID) | sealed | [private]
AuthenticateWithRequestToken(Windows::Security::Credentials::WebAccountProvider^provider, Platform::String^scope, Platform::String^clientID) | sealed | [private]
AuthenticateWithRequestToken(Windows::Security::Credentials::WebAccountProvider^provider, Platform::String^scope, Platform::String^clientID) | sealed | [private]
AuthenticateWithRequestToken(Windows::Security::Credentials::WebAccountProvider^provider, Platform::String^scope, Platform::String^clientID) | sealed | [private]
AuthenticateWithRequestTokenSilent(Windows::Security::Credentials::WebAccountProvider^provider, Platform::String^scope, Platform::String^clientID, Windows::Security::Credentials::WebAccount^account) | sealed | [private]
AuthenticateWithRequestTokenSilent(Windows::Security::Credentials::WebAccountProvider^provider, Platform::String^scope, Platform::String^clientID, Windows::Security::Credentials::WebAccount^account) | sealed | [private]
AuthenticateWithRequestTokenSilent(Windows::Security::Credentials::WebAccountProvider^provider, Platform::String^scope, Platform::String^clientID, Windows::Security::Credentials::WebAccount^account) | sealed | [private]
AuthenticateWithRequestTokenSilent(Windows::Security::Credentials::WebAccountProvider^provider, Platform::String^scope, Platform::String^clientID, Windows::Security::Credentials::WebAccount^account) | sealed | [private]
AuthenticateWithRequestTokenSilent(Windows::Security::Credentials::WebAccountProvider^provider, Platform::String^scope, Platform::String^clientID, Windows::Security::Credentials::WebAccount^account) | sealed | [private]
AUTHORITY_SUBCONTAINER | sealed | [private]
averageContainerHeight | sealed | [private]
backgroundTaskName | sealed | [private]
backgroundTaskRegistered | sealed | [private]
backgroundTaskRegistration | sealed | [private]
baseVideoFile | sealed | [private]
BasicTests() | sealed |
Bcp47ToRecognizerNameDictionary | sealed | [private, static]
BeginExtendedExecution() | sealed | [protected]
BeginExtendedExecution() | sealed | [protected]
BeginExtendedExecution() | sealed | [protected]
beginTimeOfRecordedSession | sealed | [private]
beginTimeOfReplay | sealed | [private]
BindableNode(Platform::String^nodeName, Platform::String^nodeNamespace, Platform::String^nodeValue) | sealed | [inline]
bitmap | sealed | [private]
BlockUIThread_Toggled(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
boundingRect | sealed | [private]
BrightnessBtn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Brushify(Windows::UI::Color c) | sealed | [inline]
btnAddIe_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
btnClearText_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
btnClose_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
btnClose_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
btnFromId_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
btnIe_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
btnSendMessage_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
btnSendMessage_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
btnStartAdvertisement_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
btnStopAdvertisement_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
btnWatcher_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
BuildClustersForZoomLevel(int zoomLevel) | sealed | [private]
busy | sealed | [private]
Button_AddNewAccount_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_AddProvider_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_AddUser_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Click_1(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Click_2(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Click_3(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
button_Click_StartMetering(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
button_Click_StopMetering(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_DefaultSignIn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Forget_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_GetTokenSilently_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_GetTokenSilently_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_GetTokenSilently_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_GetTokenSilently_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_GetTokenSilently_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_ManageAccount_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_ManageAccounts_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_ManageAccounts_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_ManageAccounts_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_ManageSignedInAccounts_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Passport_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Reset_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Reset_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Reset_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Reset_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Reset_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Reset_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_Restart_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_SelectUser_Click(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
Button_SignIn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_SignIn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_SignIn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_SignIn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Button_SignIn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ButtonNameDisableReconnectToDevice | sealed | [private, static]
ButtonNameDisconnectFromDevice | sealed | [private, static]
BytesPerMegaByte | sealed | [private, static]
bytesPerRow | sealed | [private, static]
bytesPerSegment | sealed | [private, static]
CalculateCenter(const std::vector< PlaceInfo > &places) | sealed | [private]
CalculatePreviewRotation() | sealed | [private]
CalculateResponse(IBuffer^challenge, IBuffer^adminkey) | sealed | [static]
CALIBRATION_POPUP_AUTO_DISMISS_TIME_TICKS | sealed | [private, static]
CalibrationBar() | sealed |
CalibrationBar() | sealed |
CalibrationBar() | sealed |
calibrationBar | sealed | [private]
CallButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CameraButton_Tapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | sealed | [private]
CancelActiveDownloads() | sealed | [private]
CancelActiveDownloadsAsync() | sealed | [private]
CancelActiveDownloadsAsync() | sealed | [private]
CancelActiveDownloadsAsync() | sealed | [private]
CancelAll_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CancelAll_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CancelCommand() | sealed |
CancelCommandButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
cancellationToken | sealed | [private]
cancellationTokenSource | sealed | [private]
CancelReason | sealed | [private]
CancelRequested | sealed | [private]
cancelSource | sealed | [private]
canDownload(Windows::Services::Maps::OfflineMaps::OfflineMapPackage^package) | sealed | [private, static]
CanShowCalibrationBar(Windows::Devices::Sensors::MagnetometerAccuracy accuracy) | sealed | [private]
CanShowCalibrationBar(Windows::Devices::Sensors::MagnetometerAccuracy accuracy) | sealed | [private]
CanShowCalibrationBar(Windows::Devices::Sensors::MagnetometerAccuracy accuracy) | sealed | [private]
CaptureDevice() | sealed | [private]
cardName | sealed |
CashDrawerInstance enum name | sealed | [private]
cashDrawerInstance1 | sealed | [private]
cashDrawerInstance2 | sealed | [private]
cbLanguageSelection_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
cbLanguageSelection_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
cbLanguageSelection_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
cbLanguageSelection_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
cbLanguageSelection_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
cbLanguageSelection_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
cbLanguageSelection_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
CCCEventHandler typedef | sealed | [private]
ChangeAdminKey_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChangeFolderClick(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChangeMediaFormatAsync(FrameFormatModel^format) | sealed | [private]
ChangePin_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChatListView() | sealed |
CheckAvailability_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CheckBox_Toggle(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs e) | sealed | [private]
checkBoxStyle | sealed | [private]
CheckConcurrentProfileBtn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
CheckHdrSupportBtn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
CheckIfStreamsAreIdentical() | sealed | [private]
CheckIfStreamsAreIdentical() | sealed | [private]
CheckIndexRevision_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChooseBaseVideo_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChooseBaseVideo_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChooseFile_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChooseFileButton_Click() | sealed | [protected]
ChooseFirstVideo_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChooseOverlayVideo_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChooseOverlayVideo_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChooseSecondVideo_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChooseVideo_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChooseVideo_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ChooseVideo_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
chunkSize | sealed | [private, static]
circleCenter | sealed | [private]
circleStrokeThickness | sealed | [private, static]
ClaimAndEnable_Click() | sealed | [protected]
ClaimButton1_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ClaimButton2_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ClaimCashDrawer() | sealed | [private]
ClaimCashDrawer() | sealed | [private]
ClaimCashDrawer(CashDrawerInstance instance) | sealed | [private]
claimedCashDrawerInstance1 | sealed | [private]
claimedCashDrawerInstance1_ReleaseDeviceRequested(Windows::Devices::PointOfService::ClaimedCashDrawer^sender, Platform::Object^e) | sealed | [private]
claimedCashDrawerInstance2 | sealed | [private]
claimedCashDrawerInstance2_ReleaseDeviceRequested(Windows::Devices::PointOfService::ClaimedCashDrawer^sender, Platform::Object^e) | sealed | [private]
claimedDrawer | sealed | [private]
claimedPrinter | sealed | [private]
ClaimedPrinter_ReleaseDeviceRequested(ClaimedPosPrinter^claimedInstance, PosPrinterReleaseDeviceRequestedEventArgs^args) | sealed | [private]
ClaimPrinter() | sealed | [private]
ClaimReader() | sealed | [private]
ClaimReader() | sealed | [private]
ClaimSamePrinter_Click() | sealed | [protected]
ClassName | sealed |
Cleanup() | sealed | [private]
CleanUp() | sealed | [private]
CleanupAccountsControlDialog() | sealed | [private]
CleanupAccountsControlDialog() | sealed | [private]
CleanupAccountsControlDialog() | sealed | [private]
CleanupAccountsControlDialog() | sealed | [private]
CleanupAccountsControlDialog() | sealed | [private]
CleanupAsync() | sealed | [private]
CleanupCameraAsync() | sealed | [private]
CleanupCameraAsync() | sealed | [private]
CleanupCameraAsync() | sealed | [private]
CleanupCameraAsync() | sealed | [private]
CleanupMediaCaptureAsync() | sealed | [private]
CleanupMediaCaptureAsync() | sealed | [private]
CleanupSink() | sealed | [private]
Clear() | sealed |
ClearCanvasStrokeCache() | sealed | [private]
ClearColorsClick(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
ClearDeviceEntries(void) | sealed | [private]
ClearDrawnBoundingRect() | sealed | [private]
ClearExtendedExecution() | sealed | [private]
ClearExtendedExecution() | sealed | [private]
ClearExtendedExecution() | sealed | [private]
ClearMapClick(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ClearOutputs() | sealed | [private]
ClearOutputs() | sealed | [private]
ClearPageCollection() | sealed | [protected]
ClearResults() | sealed | [private]
ClearSelection() | sealed | [private]
ClearSwitchStateTable() | sealed | [private]
Click_BaseArgs(Platform::Object^sender, Platform::Object^e) | sealed |
Click_NoArgs() | sealed |
Click_RegularArgs(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
ClickToPlaySource_ImageOpened(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [protected]
Close() | sealed |
CloseCurrentlyConnectedDevice(void) | sealed | [private]
CloseDevice(void) | sealed |
CloseFx2Device(void) | sealed | [private]
CloseSessionSaveFinalLogFile() | sealed | [private]
CloseSocket() | sealed | [private]
CloseSocket() | sealed | [private]
CloseSocket() | sealed | [private]
CloseSocket() | sealed | [private]
clustersForZoomLevel | sealed | [private]
CollapsedIf(bool value) | sealed | [inline, static]
CollectExpensiveData() | sealed | [private]
Color | sealed |
ColorEntries | sealed |
ColorizeCustomButtonAsync(Windows::UI::Color newColor) | sealed | [private]
ColorLampBtn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
colorLookup | sealed | [private]
ColorName | sealed |
ColorSpaceProperty | sealed | [private, static]
ColorValue(double red, double green, double blue) | sealed |
ComboBoxSettings_Changed(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CommandBar_Closed(Platform::Object^sender, Platform::Object^e) | sealed | [private]
CommandBar_Closed(Platform::Object^sender, Platform::Object^e) | sealed | [private]
CommandBar_Closing(Platform::Object^sender, Platform::Object^e) | sealed | [private]
CommandBar_Opened(Platform::Object^sender, Platform::Object^e) | sealed | [private]
CommandBar_Opening(Platform::Object^sender, Platform::Object^e) | sealed | [private]
CommandBar_Opening(Platform::Object^sender, Platform::Object^e) | sealed | [private]
CommandInvokedHandler(Windows::UI::Popups::IUICommand^command) | sealed | [private]
CompareFilesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
compass | sealed | [private]
CompleteConfirmPinTask(bool accept) | sealed | [private]
CompletedCallback() | sealed |
CompletedCallbackButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CompletePasswordCredential(Platform::String^username=nullptr, Platform::String^password=nullptr) | sealed | [private]
CompleteProvidePinTask(Platform::String^pin=nullptr) | sealed | [private]
composition | sealed | [private]
confirmPinTaskSrc | sealed | [private]
ConnectAsync() | sealed | [private]
ConnectAsync() | sealed | [private]
ConnectedDevice(Platform::String^displayName, Windows::Devices::WiFiDirect::WiFiDirectDevice^wfdDevice, SocketReaderWriter^socketRW) | sealed |
ConnectToDevice_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^eventArgs) | sealed | [private]
ConnectWebSocketAsync() | sealed | [private]
CONSUMER_AUTHORITY | sealed | [private]
Content() | sealed |
ContextChanged(Windows::Foundation::Collections::IObservableMap< Platform::String^, Platform::String^>^sender, Windows::Foundation::Collections::IMapChangedEventArgs< Platform::String^>^eventArg) | sealed | [private]
ContinuationPage(Windows::UI::Xaml::Controls::RichTextBlockOverflow^textLinkContainer) | sealed |
continuousRecognitionCompletedToken | sealed | [private]
continuousRecognitionResultGeneratedToken | sealed | [private]
ContinuousRecognitionSession_Completed(Windows::Media::SpeechRecognition::SpeechContinuousRecognitionSession^sender, Windows::Media::SpeechRecognition::SpeechContinuousRecognitionCompletedEventArgs^args) | sealed | [private]
ContinuousRecognitionSession_Completed(Windows::Media::SpeechRecognition::SpeechContinuousRecognitionSession^sender, Windows::Media::SpeechRecognition::SpeechContinuousRecognitionCompletedEventArgs^args) | sealed | [private]
ContinuousRecognitionSession_Completed(Windows::Media::SpeechRecognition::SpeechContinuousRecognitionSession^sender, Windows::Media::SpeechRecognition::SpeechContinuousRecognitionCompletedEventArgs^args) | sealed | [private]
ContinuousRecognitionSession_Completed(Windows::Media::SpeechRecognition::SpeechContinuousRecognitionSession^sender, Windows::Media::SpeechRecognition::SpeechContinuousRecognitionCompletedEventArgs^args) | sealed | [private]
ContinuousRecognitionSession_ResultGenerated(Windows::Media::SpeechRecognition::SpeechContinuousRecognitionSession^sender, Windows::Media::SpeechRecognition::SpeechContinuousRecognitionResultGeneratedEventArgs^args) | sealed | [private]
ContinuousRecognitionSession_ResultGenerated(Windows::Media::SpeechRecognition::SpeechContinuousRecognitionSession^sender, Windows::Media::SpeechRecognition::SpeechContinuousRecognitionResultGeneratedEventArgs^args) | sealed | [private]
ContinuousRecognitionSession_ResultGenerated(Windows::Media::SpeechRecognition::SpeechContinuousRecognitionSession^sender, Windows::Media::SpeechRecognition::SpeechContinuousRecognitionResultGeneratedEventArgs^args) | sealed | [private]
ContinuousRecognitionSession_ResultGenerated(Windows::Media::SpeechRecognition::SpeechContinuousRecognitionSession^sender, Windows::Media::SpeechRecognition::SpeechContinuousRecognitionResultGeneratedEventArgs^args) | sealed | [private]
ContinuousRecognize_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ContinuousRecognize_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ContinuousRecognize_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ContrastingColorButtonCheckedChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
controller | sealed | [private]
Conversation() | sealed | [inline]
conversation | sealed | [private]
Convert(Platform::Object^value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^parameter, Platform::String^language) | sealed | [virtual]
Convert(Platform::Object^value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^parameter, Platform::String^language) | sealed | [inline, virtual]
ConvertBack(Platform::Object^value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^parameter, Platform::String^language) | sealed | [inline, virtual]
ConvertBack(Platform::Object^value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^parameter, Platform::String^language) | sealed | [inline, virtual]
ConvertToDisplayableImage(Windows::Media::Capture::Frames::VideoMediaFrame^inputFrame) | sealed | [private, static]
CopyFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CopyFlyoutItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CopyrightProperty | sealed | [private, static]
coreInput | sealed | [private]
coreTitleBar | sealed | [private]
coreWetStrokeUpdateSource | sealed | [private]
CoreWetStrokeUpdateSource_WetStrokeCanceled(Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateSource^sender, Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateEventArgs^args) | sealed | [private]
CoreWetStrokeUpdateSource_WetStrokeCompleted(Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateSource^sender, Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateEventArgs^args) | sealed | [private]
CoreWetStrokeUpdateSource_WetStrokeContinuing(Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateSource^sender, Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateEventArgs^args) | sealed | [private]
CoreWetStrokeUpdateSource_WetStrokeStarting(Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateSource^sender, Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateEventArgs^args) | sealed | [private]
CoreWetStrokeUpdateSource_WetStrokeStopping(Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateSource^sender, Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateEventArgs^args) | sealed | [private]
CountEmployees(xBindSampleModel::IEmployee^e) | sealed |
countVowels(String^words) | sealed |
Create_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CreateDefaultCashDrawerObject() | sealed | [private]
CreateDefaultCashDrawerObject() | sealed | [private]
CreateDefaultCashDrawerObject(CashDrawerInstance instance) | sealed | [private]
CreateDefaultReaderObject() | sealed | [private]
CreateDefaultReaderObject() | sealed | [private]
CreateDownloadAsync(Windows::Networking::BackgroundTransfer::BackgroundDownloader^downloader, Platform::String^remoteAddress, Platform::String^fileName) | sealed | [private]
CreateFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CreateFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CreateGeneratorButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CreateGeneratorButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CreateGeneratorButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CreateHeaderTextBlock(Platform::String^contents) | sealed | [private]
CreateHeaderTextBlock(Platform::String^contents) | sealed | [protected]
CreateInkDrawingAttributesCore(Windows::UI::Xaml::Media::Brush^brush, double strokeWidth) override | sealed | [protected]
CreateLayers() | sealed | [private]
CreateLineItemTextBlock(Platform::String^contents) | sealed | [private]
CreateLineItemTextBlock() | sealed | [protected]
CreateLineItemTextBlock(Platform::String^contents) | sealed | [protected]
CreateLocalDataContainers() | sealed | [private]
CreateMenuItems() | sealed | [private]
CreateOrUpdatePropertyPopUp(Windows::UI::Input::PointerPoint^currentPoint) | sealed | [private]
CreateOverlays() | sealed | [private]
CreateOverlays() | sealed | [private]
CreatePartsAsync(Windows::Foundation::Collections::IVectorView< Windows::Storage::StorageFile^>^files) | sealed | [private]
CreatePassportKeyAsync(Platform::String^accountId) | sealed | [private]
CreatePlaceholderContact() | sealed | [private, static]
CreatePrintPreviewPages(Object^sender, Windows::UI::Xaml::Printing::PaginateEventArgs^e) override | sealed | [protected, virtual]
CreatePrintPreviewPages(Object^sender, PaginateEventArgs^e) override | sealed | [protected, virtual]
CreateReaderAsync() | sealed | [private]
CreateReaderAsync(Windows::Media::Capture::Frames::MediaFrameSourceInfo^sourceInfo) | sealed | [private]
CreateSolidGlyphBuffer(int widthInPixels, int heightInPixels) | sealed | [private]
CreateSwitchStateArray(byte output[]) | sealed | [inline, private]
CreateWordHeightBinding() | sealed |
CreateWordPositionBinding() | sealed |
CreateWordWidthBinding() | sealed |
cumulativeTransform | sealed | [private]
currChunk | sealed | [private]
CurrentToolChanged(Windows::UI::Xaml::Controls::InkToolbar^sender, Platform::Object^args) | sealed | [private]
currentValue | sealed | [private]
CustomCommand() | sealed |
CustomCommandButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CustomOptionsPrintHelper(Page^scenarioPage) | sealed |
CustomTitleBar() | sealed |
CustomTitleBar_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | sealed | [private]
CustomTitleBar_Unloaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | sealed | [private]
CustomTrigger() | sealed |
CutFlyoutItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DataSource_VectorChanged(Windows::Foundation::Collections::IObservableVector< xBindSampleModel::FileItem^>^sender, Windows::Foundation::Collections::IVectorChangedEventArgs^e) | sealed | [private]
Deactivate() | sealed | [private]
DEFAULT_ACCOUNT_PROVIDER_ID | sealed | [private]
DefaultCloseCommand() | sealed |
DefaultCloseCommandButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
defaultContextForCurrentView | sealed | [private]
DefineGlyphButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Delete_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeleteAllItems_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeleteAllItems_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeleteFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeleteItemsHelper(std::function< Windows::Foundation::IAsyncAction^(Windows::Storage::Search::ContentIndexer^)> deleteFunction) | sealed | [private]
DeleteKeywords_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeleteMenuItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeleteMenuItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeleteMenuItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeleteMultipleItems_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeletePassportServerSide() | sealed | [private]
DeleteSelectedItem() | sealed | [protected]
DeleteSingleItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeleteSingleItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
deltaTransform | sealed | [private]
DemonstrateLogging(Windows::Foundation::Diagnostics::LoggingChannel^channel) | sealed | [private]
Description | sealed |
DescriptionLocalizedResource_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
desiredReportInterval | sealed | [private]
desiredReportIntervalMs | sealed | [private]
desiredReportLatency | sealed | [private]
DestroyWindowButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
device | sealed | [private]
device | sealed | [private]
deviceAccessChangedEventToken | sealed | [private]
deviceAccessInfo | sealed | [private]
deviceAccessInformation | sealed | [private]
deviceAddedEventToken | sealed | [private]
DeviceChanged | sealed |
DeviceClassSelector | sealed |
deviceCloseCallback | sealed | [private]
DeviceConnect() | sealed |
DeviceConnect(void) | sealed |
deviceConnectDevices_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
deviceConnectedCallback | sealed | [private]
deviceConnectStart_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
deviceConnectStop_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeviceEvents() | sealed |
deviceEventsBegin_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
deviceEventsCancel_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
deviceEventsGet_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
deviceId | sealed |
deviceInfo | sealed | [private]
deviceInformation | sealed | [private]
DeviceInformationDisplay(Windows::Devices::Enumeration::DeviceInformation^deviceInfoIn) | sealed |
deviceInformationKind | sealed | [private]
DeviceInformationKindChoice(Platform::String^displayName, Windows::Foundation::Collections::IVectorView< Windows::Devices::Enumeration::DeviceInformationKind >^deviceInformationKinds) | sealed | [inline]
DeviceInformationKinds | sealed |
DeviceIO() | sealed |
DeviceIOGet_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeviceIOSet_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DeviceListEntry(Windows::Devices::Enumeration::DeviceInformation^DeviceInterface) | sealed | [inline]
DeviceReadWrite() | sealed |
deviceRemovedEventToken | sealed | [private]
deviceResources | sealed | [private]
deviceSelector | sealed | [private]
DeviceSelectorInfo(Platform::String^displayName, Windows::Devices::Enumeration::DeviceClass deviceClassSelector, Platform::String^selector) | sealed | [inline]
DeviceSelectorInfo(Platform::String^displayName, Windows::Devices::Enumeration::DeviceClass deviceClassSelector, Platform::String^selector, Windows::Devices::Enumeration::DeviceInformationKind kind) | sealed | [inline]
deviceWatcher | sealed | [private]
deviceWatcherHelper | sealed | [private]
DeviceWatcherHelper(Windows::Foundation::Collections::IObservableVector< DeviceInformationDisplay^>^resultCollection, Windows::UI::Core::CoreDispatcher^dispatcher) | sealed | [inline]
deviceWatcherHelpers | sealed | [private]
deviceWatchers | sealed | [private]
dictatedTextBuilder | sealed | [private]
dictationTextBox_TextChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::TextChangedEventArgs^e) | sealed | [private]
directXGestureRecognizer | sealed | [private]
DirectXPage() | sealed |
DisableButtons() | sealed | [private]
DisableButtons() | sealed | [private]
DisableButtons() | sealed | [private]
Disabled enum value | sealed | [private]
disableFollowCircle | sealed | [private]
DisableNonSquarePARProfiles() | sealed | [private]
DisableNonSquarePARProfiles() | sealed | [private]
DisconnectFromDevice_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^eventArgs) | sealed | [private]
discontinueStroke | sealed | [private]
DiscoverActiveDownloads() | sealed | [private]
DiscoverActiveUploads() | sealed | [private]
DiscoveredDevice(Windows::Devices::Enumeration::DeviceInformation^deviceInfoIn) | sealed |
DismissPopup_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DismissPopup_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DismissPopup_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
dispatcher | sealed | [private]
dispatcher | sealed | [private]
dispatcherTimer | sealed | [private]
DispatcherTimer_Tick(Platform::Object^sender, Platform::Object^e) | sealed | [private]
Display() | sealed |
Display() | sealed |
Display() | sealed |
Display() | sealed |
Display() | sealed |
Display() | sealed |
Display(String^stringArg, int intArg, double floatArg, bool boolArg) | sealed |
Display_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Display_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Display_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Display_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Display_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Display_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Display_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
displayController | sealed | [private]
DisplayCurrentReading(Platform::Object^sender, Platform::Object^e) | sealed | [private]
DisplayCurrentReading(Platform::Object^sender, Platform::Object^e) | sealed | [private]
DisplayCurrentReading(Platform::Object^sender, Platform::Object^e) | sealed | [private]
DisplayCurrentReading(Platform::Object^sender, Platform::Object^e) | sealed | [private]
DisplayCurrentReading(Platform::Object^sender, Platform::Object^e) | sealed | [private]
DisplayCurrentReading(Platform::Object^sender, Platform::Object^e) | sealed | [private]
displayInfo | sealed | [private]
displayInformation | sealed | [private]
displayInformation | sealed | [private]
DisplayInformation_DpiChanged(Windows::Graphics::Display::DisplayInformation^displayInformation, Platform::Object^e) | sealed | [private]
DisplayInformation_OrientationChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [private]
DisplayLink(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [protected]
DisplayMetrics(Windows::UI::Core::AnimationMetrics::AnimationEffect effect, Windows::UI::Core::AnimationMetrics::AnimationEffectTarget target) | sealed | [private]
DisplayMultipleCandidates(Windows::Foundation::Collections::IVectorView< Platform::String^>^candidates) | sealed | [private]
DisplayMultipleCandidates(Windows::Foundation::Collections::IVectorView< Platform::String^>^candidates) | sealed | [private]
displayName | sealed | [private]
DisplayName | sealed |
DisplayNameLocalizedResource_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DisplayOrientation(Windows::Devices::Sensors::SimpleOrientation orientation) | sealed | [private]
DisplayOrientation(Windows::Devices::Sensors::SimpleOrientation orientation) | sealed | [private]
DisplayProperties_DpiChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [private]
DisplayProperties_DpiChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [private]
displayRequest | sealed | [private]
DisplayRoundingAlgorithmAsString(Windows::Globalization::NumberFormatting::RoundingAlgorithm roundingAlgorithm) | sealed | [private]
DisplayTextButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DisplayTextButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DisplayTextButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DisplayUserInformationAsync(Platform::String^userID) | sealed | [private]
DisposeLamp() | sealed | [private]
DisposeMediaCapture() | sealed | [private]
DistanceFromCenter(Windows::Foundation::Point position) | sealed | [private]
DoCleanup() | sealed | [private]
DocumentPresenter(Platform::String^text, Platform::String^downloadableFontName, Platform::String^languageTag, Windows::UI::Color textColor, Windows::UI::Color textBackgroundColor, Windows::UI::Xaml::Controls::Image^imageTarget) | sealed |
DoCurrencyRoundingScenarios(Platform::String^currencyCode, Windows::Globalization::NumberFormatting::RoundingAlgorithm roundingAlgorithm) | sealed | [private]
DoIncrementRoundingScenarios(Windows::Globalization::NumberFormatting::RoundingAlgorithm roundingAlgorithm) | sealed | [private]
DoPaddingAndRoundingScenarios(Windows::Globalization::NumberFormatting::RoundingAlgorithm roundingAlgorithm, unsigned int significantDigits, int integerDigits, int fractionalDigits) | sealed | [private]
DoPaddingScenarios(Windows::Globalization::NumberFormatting::INumberFormatter^formatter) | sealed | [private]
DoScenario(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DoScenario(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DoScenarioAsync() | sealed |
DoScenarioAsync() | sealed |
DoSignificantDigitRoundingScenarios(Windows::Globalization::NumberFormatting::RoundingAlgorithm roundingAlgorithm) | sealed | [private]
DoSomething(Windows::Foundation::Diagnostics::ILoggingTarget^logger) | sealed | [private]
DoubleSpace_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
DoubleSpaceHalfLeading_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
DoWin10Mode(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DoWin81Mode(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
download | sealed | [private]
DownloadAsync(DownloadOperationItem^item) | sealed | [private]
DownloadContactDataAsync(Windows::ApplicationModel::Contacts::Contact^contact) | sealed | [private]
DownloadOperationItem(Windows::Networking::BackgroundTransfer::DownloadOperation^download) | sealed |
DownloadProgress(Windows::Foundation::IAsyncOperationWithProgress< Windows::Networking::BackgroundTransfer::DownloadOperation^, Windows::Networking::BackgroundTransfer::DownloadOperation^>^operation, Windows::Networking::BackgroundTransfer::DownloadOperation^) | sealed | [private]
DownloadProgress(DownloadOperationItem^item) | sealed | [private]
DPI96 | sealed | [private, static]
DPOnPageName | sealed | [private]
DragCompleted(Windows::Foundation::IAsyncOperation< Windows::ApplicationModel::DataTransfer::DataPackageOperation >^asyncInfo, Windows::Foundation::AsyncStatus asyncStatus) | sealed | [private]
DrainBackBufferAsync() | sealed | [private]
DrawBoundingRect() | sealed | [private]
drawer | sealed | [private]
drawer_AlarmExpired(Windows::Devices::PointOfService::CashDrawerCloseAlarm^alarm, Platform::Object^sender) | sealed | [private]
drawer_StatusUpdated(Windows::Devices::PointOfService::CashDrawer^sender, Windows::Devices::PointOfService::CashDrawerStatusUpdatedEventArgs^e) | sealed | [private]
DropBorder_DragEnter(Platform::Object^sender, Windows::UI::Xaml::DragEventArgs^e) | sealed | [private]
DropBorder_Drop(Platform::Object^sender, Windows::UI::Xaml::DragEventArgs^e) | sealed | [private]
durationOfRecordedSession | sealed | [private]
DXFLOptionCombo_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
element | sealed | [private]
element | sealed | [private]
ElementNotFound | sealed | [private, static]
Email | sealed |
EmailButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
emailConstraint | sealed | [private]
Employees | sealed |
EnableAsync() | sealed | [private]
EnableButtons(bool isEnabled) | sealed | [private]
EnableButtons() | sealed | [private]
EnableButtons() | sealed | [private]
EnableButtons() | sealed | [private]
EnableControls_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
EnableControlsInTitleBar(bool enable) | sealed |
enabled | sealed |
EnableDisableLogging(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
EnableDisableLogging(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
EnableIndependentInputEventHandlers() | sealed | [private]
EnableInkingEventHandlers() | sealed | [private]
EnableLoggingIndependentInputEventHandlers(bool enable) | sealed | [private]
EnableLoggingStrokeEventHandlers(bool enable) | sealed | [private]
EnableLoggingUnprocessedInputEventHandlers(bool enable) | sealed | [private]
EnableNonSquarePARProfiles() | sealed | [private]
EnableNonSquarePARProfiles() | sealed | [private]
EnablePasteItemOnly(bool IsEnabled, Windows::Foundation::Point pos) | sealed |
EnableUI(bool newState) | sealed | [private]
EnableUnprocessedInputEventHandlers() | sealed | [private]
end enum value | sealed | [private]
EndCall() | sealed | [private]
EndCallButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
EndExtendedExecution() | sealed | [protected]
EndExtendedExecution() | sealed | [protected]
EndExtendedExecution() | sealed | [protected]
EndRound(bool hasWon) | sealed | [private]
EndScenario_Click(Platform::Object^sender, RoutedEventArgs e) | sealed | [private]
endTimeOfRecordedSession | sealed | [private]
EnvironmentComboBox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
EnvironmentComboBox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
EnvironmentComboBox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
eraseAllClickedToken | sealed | [private]
Erasing enum value | sealed | [private]
ErasingMode enum value | sealed | [private]
ErasingModeCheckBox_Checked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ErasingModeCheckBox_Unchecked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
EventHandlerForDevice(void) | sealed | [private]
eventHandlerForDevice | sealed | [private, static]
eventRegistrationToken | sealed | [private]
EventTests() | sealed |
eventToken | sealed | [private]
Execute_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Execute_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Execute_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ExecuteJobAndReportResultAsync(Windows::Devices::PointOfService::ReceiptPrintJob^job) | sealed | [private]
expectedRpcCallbackRate | sealed | [private]
ExtendedExecutionSessionRevoked(Platform::Object^sender, Windows::ApplicationModel::ExtendedExecution::ExtendedExecutionRevokedEventArgs^args) | sealed | [private]
ExtendView_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
externalCamera | sealed | [private]
ExtractButton_Tapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | sealed | [private]
ExtractButton_Tapped(Platform::Object^sender, TappedRoutedEventArgs^e) | sealed | [private]
falToken | sealed | [private]
FeatureReports() | sealed |
file | sealed | [private]
FileLoggingSessionScenario() | sealed | [private]
FillComboBox() | sealed | [private]
FillTextBox(Windows::Media::Core::SpeechCue^cue) | sealed | [private]
FillTextBoxes(Windows::Media::Core::SpeechCue^cue, Windows::Media::Core::TimedMetadataTrack^timedMetadataTrack) | sealed | [private]
Find_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Find_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Find_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
FindAndCancelExistingBackgroundTask() | sealed | [private]
findAtCenterButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
FindButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel desiredPanel) | sealed | [private]
FindCertificateFromStoreAsync() | sealed | [private]
FindClaimEnable_Click(Platform::Object^sender, RoutedEventArgs^e) | sealed | [private]
FindDevice(Platform::String^deviceId) | sealed | [private]
FindPrinter_Click() | sealed | [protected]
FindReceiptPrinter() | sealed | [private]
FindScrollViewer(DependencyObject^depObject) | sealed | [private]
FindScrollViewer(DependencyObject^depObject) | sealed | [private]
FirmwareAccess() | sealed |
FirstPage | PrintHelper | [protected]
firstVideoFile | sealed | [private]
Fix_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
followCircle | sealed | [private]
FollowCircleTest(Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateEventArgs^args) | sealed | [private]
FontDownloadListener_DownloadCompleted() | sealed | [private]
Footer_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Footer_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
forceManipulationsToEnd | sealed | [private]
Format | sealed |
FormatComboBox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
FormatDownloadedRanges(Windows::Foundation::Collections::IIterable< Windows::Networking::BackgroundTransfer::BackgroundTransferFileRange >^ranges) | sealed | [private, static]
FPS | sealed | [private, static]
FrameFormatModel(Windows::Media::Capture::Frames::MediaFrameFormat^format) | sealed |
FrameRate() | sealed |
FrameReader_FrameArrived(Windows::Media::Capture::Frames::MediaFrameReader^sender, Windows::Media::Capture::Frames::MediaFrameArrivedEventArgs^args) | sealed | [private]
FrameReader_FrameArrived(Windows::Media::Capture::Frames::MediaFrameReader^sender, Windows::Media::Capture::Frames::MediaFrameArrivedEventArgs^args) | sealed | [private]
FrameRenderer(Windows::UI::Xaml::Controls::Image^image) | sealed |
FrameSourceGroupModel(Windows::Media::Capture::Frames::MediaFrameSourceGroup^sourceGroup) | sealed |
FrameSourceInfoModel(Windows::Media::Capture::Frames::MediaFrameSourceInfo^sourceInfo) | sealed |
FulfillConsumableButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
FulfillConsumableButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Functions() | sealed |
GenerateDefaultSettings() | sealed | [private]
GeneratePageAsync(int photoNumber, PageDescription pageDescription) | sealed | [private]
generator | sealed | [private]
generator | sealed | [private]
generator | sealed | [private]
geolocator | sealed | [private]
GetAccounts() | sealed | [private]
GetActivitySensorAsync() | sealed | [private]
GetAddress(int i) | sealed | [private]
getAllHistory | sealed | [private]
GetAppLanguagesAsFormattedString() | sealed | [private]
GetAppLocalSettingsValueAsBool(Platform::String^key) | sealed | [inline, private, static]
GetAppLocalSettingsValueAsBool(Platform::String^key) | sealed | [inline, private, static]
GetAppLocalSettingsValueAsObject(Platform::String^key) | sealed | [inline, private, static]
GetAppLocalSettingsValueAsObject(Platform::String^key) | sealed | [inline, private, static]
GetAppLocalSettingsValueAsString(Platform::String^key) | sealed | [inline, private, static]
GetAppLocalSettingsValueAsString(Platform::String^key) | sealed | [inline, private, static]
GetAssociatedProductsButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetBooleanInputReport_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^eventArgs) | sealed | [private]
GetBooleanInputReportAsync(uint8 buttonNumber) | sealed | [private]
GetButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetClientCertificateAsync() | sealed | [private]
GetClustersForZoomLevel(int zoomLevel) | sealed | [private]
GetCO2Level(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
getColor(Platform::String^colorString) | sealed | [private]
getColor(Platform::String^colorString) | sealed | [private]
GetConsumableBalanceButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetConsumableBalanceButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetCurrentButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetCurrentMessage() | sealed |
GetCurrentStrokesView(Windows::Foundation::DateTime time) | sealed | [private]
GetCustomerCollectionsId(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [protected]
GetCustomerFooter() | sealed | [private]
GetCustomerFooter() | sealed | [private]
GetCustomerPurchaseId(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [protected]
GetCustomProfile() | sealed | [private]
GetData(Platform::Object^sender, Platform::Object^e) | sealed | [private]
GetDataModelForCurrentListViewFlyout() | sealed | [private]
GetDataModelForCurrentListViewFlyout() | sealed | [private]
GetDefaultAsyncBtn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetDefaultProvidersAndAccounts() | sealed | [private]
GetDependencies_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetDeviceSpecificProperties(Windows::UI::Input::PointerPoint^currentPoint) | sealed | [private]
GetExecutionDeferral() | sealed | [private]
GetFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetFileFromFutureAccessListButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetFilesAndFoldersButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetFilesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [protected]
GetFilesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [protected]
GetFriendlyName(bool showFrameRate=true) | sealed |
GetGeotagButton_Click() | sealed | [protected]
GetGyrometerSample(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetHistory_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetHitTestState(Windows::Foundation::Point position) | sealed | [private]
GetInkingSubstate(Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
GetInstalledLocation_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetItemIndex(Windows::UI::Input::RadialControllerMenuItem^item) | sealed | [private]
GetLedBlinkPattern_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetLedBlinkPatternAsync(void) | sealed | [private]
GetLicenseState() | sealed | [private]
GetLogoBackgroundColor() | sealed | [private]
GetManagedConsumablesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetManufacturerName_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetMerchantFooter() | sealed | [private]
GetMerchantFooter() | sealed | [private]
GetMouseProperties(Windows::UI::Input::PointerPoint^currentPoint) | sealed | [private]
GetNumericInputReport_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^eventArgs) | sealed | [private]
GetNumericInputReportAsync(void) | sealed | [private]
GetPackage_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetParent_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetPartialStroke(Windows::UI::Input::Inking::InkStroke^stroke, Windows::Foundation::DateTime time) | sealed | [private]
GetPassportAuthenticationMessageAsync(Windows::Storage::Streams::IBuffer^message, Platform::String^accountId) | sealed | [private]
GetPasswordCredentialFromUserAsync() | sealed | [private]
GetPenProperties(Windows::UI::Input::PointerPoint^currentPoint) | sealed | [private]
GetPicturesLibrary() | sealed | [private]
GetPinFromUserAsync() | sealed | [private]
GetPinValue_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
GetPointerProperties(Windows::UI::Input::PointerPoint^currentPoint) | sealed | [private]
GetPresetProfile(Windows::UI::Xaml::Controls::ComboBox^comboBox) | sealed | [private]
GetPresetProfile(Windows::UI::Xaml::Controls::ComboBox^comboBox) | sealed | [private]
GetPrintPreviewPage(Object^sender, GetPreviewPageEventArgs^e) override | sealed | [protected, virtual]
GetPropertyDisplayValue(Platform::Object^property) | sealed | [protected]
GetPropertyForDisplay(Platform::String^key) | sealed | [inline]
GetProviders() | sealed | [private]
GetProvidersAndAccounts() | sealed | [private]
GetProvidersAndAccounts() | sealed | [private]
GetProvidersAndAccounts() | sealed | [private]
GetProvidersAndAccounts() | sealed | [private]
GetRadialControllerMenuItemFromSender(Platform::Object^sender) | sealed | [private]
GetSampleData() | sealed | [inline, static]
GetSampleData() | sealed | [private]
GetSelectedCeremonies() | sealed | [private]
GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^request) override | sealed | [protected, virtual]
GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^request) override | sealed | [protected, virtual]
GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^request) override | sealed | [protected, virtual]
GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^request) override | sealed | [protected, virtual]
GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^request) override | sealed | [protected, virtual]
GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^request) override | sealed | [protected, virtual]
GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^request) override | sealed | [protected, virtual]
GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^request) override | sealed | [protected, virtual]
GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^request) override | sealed | [protected, virtual]
GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^request) override | sealed | [protected, virtual]
GetSubtypeForFrameReader(Windows::Media::Capture::Frames::MediaFrameSourceKind kind, Windows::Media::Capture::Frames::MediaFrameFormat^format) | sealed | [static]
GetThumbnailButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetThumbnailButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetThumbnailButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetThumbnailButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetThumbnailButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetTime() | sealed |
GetTokenFromAzureOAuthAsync() | sealed | [private]
GetTouchProperties(Windows::UI::Input::PointerPoint^currentPoint) | sealed | [private]
GetUnmanagedConsumablesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetUserCollectionButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GetUserConfirmationAsync(Platform::String^pin) | sealed | [private]
GetVideoProfileSupportedDeviceIdAsync(Windows::Devices::Enumeration::Panel panel) | sealed | [private]
GetVideoProfileSupportedDeviceIdAsync(Windows::Devices::Enumeration::Panel panel) | sealed | [private]
GetVideoProfileSupportedDeviceIdAsync(Windows::Devices::Enumeration::Panel panel) | sealed | [private]
glyphBuffer | sealed | [private]
GreenButton_Click(_In_ Platform::Object^sender, _In_ Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
group | sealed | [private]
GroupByHelper(Windows::Storage::Search::QueryOptions^queryOptions) | sealed | [private]
GroupByMonthButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GroupByRatingButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GroupByTagButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
GroupComboBox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
GroupedBackgroundTask() | sealed |
GroupedBackgroundTask() | sealed |
GroupNameLocalizedResource_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
gyrometer | sealed | [private]
gyrometerWindows | sealed | [private]
gyrometerWP | sealed | [private]
HandleCardAdded(Windows::Devices::SmartCards::SmartCardReader^evtReader, Windows::Devices::SmartCards::CardAddedEventArgs^args) | sealed | [private]
HandleCardRemoved(Windows::Devices::SmartCards::SmartCardReader^evtReader, Windows::Devices::SmartCards::CardRemovedEventArgs^args) | sealed | [private]
HandleDownloadAsync(Windows::Networking::BackgroundTransfer::DownloadOperation^download, boolean start) | sealed | [private]
HandleDownloadAsync() | sealed | [private]
HandleError(Platform::Exception^error, Platform::String^msg, Platform::String^prefix) | sealed | [private]
HandleFollowCircleInput(Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateEventArgs^args) | sealed | [private]
HandleRecognitionResult(Windows::Media::SpeechRecognition::SpeechRecognitionResult^recoResult) | sealed | [private]
HandleRecognitionResult(Windows::Media::SpeechRecognition::SpeechRecognitionResult^recoResult) | sealed | [private]
HandleRegularInput(Windows::UI::Input::Inking::Core::CoreWetStrokeUpdateEventArgs^args) | sealed | [private]
HandleUploadAsync(Windows::Networking::BackgroundTransfer::UploadOperation^upload, bool start) | sealed | [private]
HasSameFormat(Windows::Media::Capture::Frames::MediaFrameFormat^otherFormat) | sealed | [inline]
Height() | sealed |
HeightSlider_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
HexDump(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Hide() | sealed |
Hide() | sealed |
Hide() | sealed |
HideGuidance() | sealed | [private]
HideGuidance() | sealed | [private]
HideGuidance() | sealed | [private]
HideGuidanceButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
HideGuidanceButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
HideGuidanceButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
HidePairingPanel() | sealed | [private]
HidePropertyPopUp(Windows::UI::Input::PointerPoint^currentPoint) | sealed | [private]
highLatency enum value | sealed | [private]
HighlightWordOnScreen(int startPositionInInput, int endPositionInInput) | sealed | [private]
historyRecords | sealed | [private]
horizontalScrollableWindow | sealed | [private]
Hover enum value | sealed | [private]
HResultPrivacyStatementDeclined | sealed | [private, static]
HResultRecognizerNotFound | sealed | [private, static]
HttpMapTileDataSourceUriRequested(Windows::UI::Xaml::Controls::Maps::HttpMapTileDataSource^sender, Windows::UI::Xaml::Controls::Maps::MapTileUriRequestedEventArgs^e) | sealed | [private]
httpTileSource | sealed | [private]
htu21dSensor | sealed | [private]
hypothesisGeneratedToken | sealed | [private]
id | sealed |
Id | sealed |
IMAGE_ENCODING_STRING | sealed | [private]
imageFile | sealed | [private]
ImageSourceUri | sealed |
InCircleEdgeZone(double distanceFromCenter) | sealed | [private]
inclinometer | sealed | [private]
inCollection | sealed |
IncomingConnectionEvent | sealed | [private]
IndependentEvent_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
IndependentInputOnPointerEntering(Windows::UI::Input::Inking::Core::CoreInkIndependentInputSource^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
IndependentInputOnPointerExiting(Windows::UI::Input::Inking::Core::CoreInkIndependentInputSource^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
IndependentInputOnPointerHovering(Windows::UI::Input::Inking::Core::CoreInkIndependentInputSource^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
IndependentInputOnPointerLost(Windows::UI::Input::Inking::Core::CoreInkIndependentInputSource^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
IndependentInputOnPointerMoving(Windows::UI::Input::Inking::Core::CoreInkIndependentInputSource^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
IndependentInputOnPointerPressing(Windows::UI::Input::Inking::Core::CoreInkIndependentInputSource^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
IndependentInputOnPointerReleasing(Windows::UI::Input::Inking::Core::CoreInkIndependentInputSource^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
InertiaSwitch_Toggled(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InertiaSwitch_Toggled(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InitalizeAccountsControlDialog() | sealed | [private]
InitalizeAccountsControlDialog() | sealed | [private]
InitalizeAccountsControlDialog() | sealed | [private]
InitalizeAccountsControlDialog() | sealed | [private]
InitalizeAccountsControlDialog() | sealed | [private]
InitCustomProfileBtn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InitDrawerButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InitDrawerButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Initialize(Platform::String^displayName, Windows::Devices::Enumeration::DeviceClass deviceClassSelector, Platform::String^selector, Windows::Devices::Enumeration::DeviceInformationKind kind) | sealed | [inline, private]
Initialize() | sealed | [private]
Initialize() | sealed | [private]
InitializeAsync() | sealed | [private]
InitializeAsync() | sealed | [private]
InitializeAsync() | sealed | [private]
InitializeAsync() | sealed | [private]
InitializeAsync() | sealed | [private]
InitializeAsync() | sealed | [private]
InitializeAsync() | sealed | [private]
InitializeCameraAsync() | sealed | [private]
InitializeCameraAsync() | sealed | [private]
InitializeCameraAsync() | sealed | [private]
InitializeCameraAsync() | sealed | [private]
InitializeCameraButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InitializeCameraButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InitializeCameraButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InitializeController() | sealed | [private]
initialized | sealed | [private]
InitializeDeviceWatchers(void) | sealed | [private]
InitializeLampAsync() | sealed | [private]
InitializeListboxVoiceChooser() | sealed | [private]
InitializeListboxVoiceChooser() | sealed | [private]
InitializeListboxVoiceChooser() | sealed | [private]
InitializeOsrFx2DeviceWatcher(void) | sealed | [private]
InitializeRecognizer(Windows::Globalization::Language^recognizerLanguage) | sealed | [private]
InitializeRecognizer(Windows::Globalization::Language^recognizerLanguage) | sealed | [private]
InitializeRecognizer(Windows::Globalization::Language^recognizerLanguage) | sealed | [private]
InitializeRecognizer(Windows::Globalization::Language^recognizerLanguage) | sealed | [private]
InitializeRecognizer() | sealed | [private]
InitializeRecognizer(Windows::Globalization::Language^recognizerLanguage) | sealed | [private]
InitializeRecognizer(Windows::Globalization::Language^recognizerLanguage) | sealed | [private]
InitializeRecognizer(Windows::Globalization::Language^recognizerLanguage) | sealed | [private]
InitializeSuperMuttDeviceWatcher(void) | sealed | [private]
InitializeTransforms() | sealed | [private]
InitializeTransforms() | sealed |
InitializeUIControls() | sealed | [private]
InitializeValues() | sealed | [private]
InitializeValues() | sealed | [private]
InitializeValues() | sealed | [private]
InitializeValues() | sealed | [private]
initializing enum value | sealed | [private]
initializing_previewSetupCompleted() | sealed | [private]
InitLampBtn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InitManipulationTransforms() | sealed | [private]
InitOptions() | sealed | [private]
InitOptions() | sealed | [private]
InitRecordProfileBtn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
inkDrawingAttributesChangedToken | sealed | [private]
InkingAreaSubStates enum name | sealed | [private]
InkingEvent_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InkingMode enum value | sealed | [private]
InkingModeSelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
InkPresenter_StrokesCollected(Windows::UI::Input::Inking::InkPresenter^sender, Windows::UI::Input::Inking::InkStrokesCollectedEventArgs^args) | sealed | [private]
InkPresenter_StrokesCollected(Windows::UI::Input::Inking::InkPresenter^sender, Windows::UI::Input::Inking::InkStrokesCollectedEventArgs^e) | sealed | [private]
InkPresenter_StrokesErased(Windows::UI::Input::Inking::InkStrokeInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
InkPresenter_StrokesErased(Windows::UI::Input::Inking::InkPresenter^sender, Windows::UI::Input::Inking::InkStrokesErasedEventArgs^args) | sealed | [private]
inkRecognizerContainer | sealed | [private]
inkReplayTimer | sealed | [private]
InkReplayTimer_Tick(Platform::Object^sender, Platform::Object^e) | sealed | [private]
InkStackPanel_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs e) | sealed | [private]
InkToolbar_ActiveToolChanged(Windows::UI::Xaml::Controls::InkToolbar^sender, Platform::Object^args) | sealed | [private]
InkToolbar_EraseAllClicked(Windows::UI::Xaml::Controls::InkToolbar^sender, Platform::Object^args) | sealed | [private]
inkToolbar_InkDrawingAttributesChanged(Windows::UI::Xaml::Controls::InkToolbar^sender, Platform::Object^args) | sealed | [private]
InkToolbar_InkDrawingAttributesChanged(Windows::UI::Xaml::Controls::InkToolbar^sender, Platform::Object^args) | sealed | [private]
InkToolbar_IsStencilButtonCheckedChanged(Windows::UI::Xaml::Controls::InkToolbar^sender, Windows::UI::Xaml::Controls::InkToolbarIsStencilButtonCheckedChangedEventArgs^args) | sealed | [private]
InkToolbar_IsStencilButtonCheckedChanged(Windows::UI::Xaml::Controls::InkToolbar^sender, Windows::UI::Xaml::Controls::InkToolbarIsStencilButtonCheckedChangedEventArgs^args) | sealed | [private]
inkToolbar_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InkToolbar_SelectedStencilChanged(Windows::UI::Xaml::DependencyObject^sender, Windows::UI::Xaml::DependencyProperty^dp) | sealed | [private]
InkToolbarMode enum value | sealed | [private]
inputLoopWorker | sealed | [private]
InputModes enum name | sealed | [private]
InputOutputReports() | sealed |
InputPauseButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InputPauseButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InputPauseButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InputPlayButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InputPlayButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InputPlayButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InputReportEvents() | sealed |
inputReportEventToken | sealed | [private]
InputStopButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InputStopButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InputStopButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
InsideInkingArea enum value | sealed | [private]
InsideSelectionRect enum value | sealed | [private]
InstallClientCertificateAsync() | sealed | [private]
Instance1 enum value | sealed | [private]
Instance2 enum value | sealed | [private]
interactionMode | sealed | [private]
InterruptMessageWorker(Windows::Devices::Custom::CustomDevice^fx2Device, Windows::Storage::Streams::IBuffer^switchMessageBuffer) | sealed | [private]
InvalidateLayout() | sealed | [private]
InvalidateLayout() | sealed | [private]
InvalidateLayout() | sealed | [private]
isAllDevicesEnumerated | sealed | [private]
isAngleDetected | sealed | [private]
IsAnImportantTransaction | sealed | [private]
IsAppLocalSettingsValue(Platform::String^key) | sealed | [inline, private, static]
IsAppLocalSettingsValue(Platform::String^key) | sealed | [inline, private, static]
isBoundRect | sealed | [private]
isBusy | sealed | [private]
IsChecked(Windows::UI::Xaml::Controls::Primitives::ToggleButton^button) | sealed | [private]
isEnabledAutoReconnect | sealed | [private]
IsFixNeededAsync(Windows::ApplicationModel::UserDataAccounts::UserDataAccount^account) | sealed | [private]
IsFx2CustomTriggerTaskRegistered() | sealed | [private]
IsImportantTransaction_Click() | sealed | [protected]
isInitialized | sealed | [private]
IsItemInMenu(Windows::UI::Input::RadialControllerMenuItem^item) | sealed | [private]
isLastKnownFullScreen | sealed | [private]
isLaunched | sealed | [private]
IsNew | sealed |
IsNonNull(Platform::Object^item) | sealed | [inline, static]
IsNonNull(Platform::Object^item) | sealed | [inline, static]
IsNonNull(Platform::Object^o) | sealed | [static]
isPopulatingLanguages | sealed | [private]
isPreviewing | sealed | [private]
IsPrinterClaimed() | sealed | [private]
isPropertyChangedObserved | sealed | [private]
isRegisteredForInputReportEvents | sealed | [private]
IsTargetBorder(Platform::Object^sender) | sealed | [private]
IsWatcherRunning() | sealed |
IsWatcherStarted(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher) | sealed | [private, static]
IsWebException(Platform::String^title, Platform::Exception^ex) | sealed | [private]
IsWebException(Platform::String^title, Platform::Exception^ex) | sealed | [private]
ItemDetails(Windows::Services::Store::StoreProduct^product) | sealed | [inline]
itemsSeen | sealed | [private]
keyDownToken | sealed | [private]
Kind | sealed |
Lamp_AvailabilityChanged(Windows::Devices::Lights::Lamp^sender, Windows::Devices::Lights::LampAvailabilityChangedEventArgs^args) | sealed | [private]
lampToggle_Toggled(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
LanguageList_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
LanguageList_SelectionChanged(Platform::Object^sender, SelectionChangedEventArgs^e) | sealed | [private]
languageMap | sealed | [private]
LanguageTagToRecognizerName(Platform::String^bcp47tag) | sealed | [static]
lasso | sealed | [private]
LassoSelect | sealed |
lastSelectedIndex | sealed | [private]
lastUpdateTime | sealed | [private]
LatencyModes enum name | sealed | [private]
LatencyModeToggled(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Launch_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Launch_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Launch_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Launch_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Launch_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
LaunchAtSize_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
LaunchContextMenu(Windows::Foundation::Point contextMenuPosition) | sealed | [private]
LaunchInFullScreenModeCheckBox_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
LED_PIN | sealed | [private]
lineDisplay | sealed | [private]
LineTo(Platform::Array< WindowsPreview::Media::Capture::Frames::TrackedPose >^poses, WindowsPreview::Media::Capture::Frames::BodyPart fromBodyPart, WindowsPreview::Media::Capture::Frames::BodyPart toBodyPart, CoordinateTransformationMethod^positionTransformation) | sealed | [private, static]
ListboxVoiceChooser_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
ListboxVoiceChooser_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
ListboxVoiceChooser_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
LISTEN_PIN | sealed | [private]
listenPin | sealed | [private]
ListFoldersButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
listOfDevices | sealed | [private]
ListsAndTemplates() | sealed |
ListSmartCards_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ListView_ContextCanceled(Windows::UI::Xaml::UIElement^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ListView_ContextRequested(Windows::UI::Xaml::UIElement^sender, Windows::UI::Xaml::Input::ContextRequestedEventArgs^e) | sealed | [private]
LoadAccount() | sealed | [private]
LoadAccount() | sealed | [private]
LoadAccounts() | sealed | [private]
LoadBitmapAsync(Windows::Foundation::Uri^source, bool landscape) | sealed | [private]
LoadButton_Tapped(Platform::Object^sender, TappedRoutedEventArgs^e) | sealed | [private]
LoadDocument() | sealed |
LoadImage(Windows::Storage::StorageFile^file) | sealed | [private]
LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | sealed |
LoadLogoBitmapAsync() | sealed | [private]
LoadPlaceInfoAsync() | sealed | [private]
LoadSampleImage() | sealed | [private]
LocalClientButtonClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Location | sealed |
LocationTrackingReason() | sealed |
LockScenarioChange() | sealed | [private]
LockScenarioChange() | sealed | [private]
LockToXAxis() | sealed |
LockToYAxis() | sealed |
Log(Platform::String^message) | sealed | [private]
Log(Platform::String^message) | sealed | [private]
Log(Platform::String^message) | sealed | [private]
Log(Platform::String^message) | sealed | [inline]
Log(Platform::String^message) | sealed | [inline]
Log(LogEventAction action) | sealed | [private]
LogContactInfo(Windows::UI::Input::RadialControllerScreenContact^contact) | sealed | [private]
LogException(Platform::String^title, Platform::Exception^ex) | sealed | [private]
LogException(Platform::String^title, Platform::Exception^ex) | sealed | [private]
LogException(Platform::String^title, Platform::Exception^ex, Windows::Networking::BackgroundTransfer::DownloadOperation^download=nullptr) | sealed | [private]
LoggingScenarioEventArgs(LoggingScenarioEventType type, const std::wstring &logFileFullPath) | sealed | [inline, private]
LoggingScenarioEventArgs(bool enabled) | sealed | [inline, private]
LoggingSessionScenario() | sealed | [private]
LogMessage(Platform::String^message) | sealed | [private]
LogoffAndRemoveAccount() | sealed | [private]
LogoffAndRemoveAccount() | sealed | [private]
LogoffAndRemoveAccount() | sealed | [private]
LogoffAndRemoveAccount() | sealed | [private]
LogoffAndRemoveAccount(Windows::Security::Credentials::WebAccount^account) | sealed | [private]
LogoffAndRemoveAccount() | sealed | [private]
LogoffAndRemoveAllAccounts() | sealed | [private]
LogStatus(Platform::String^message, SDKTemplate::NotifyType type) | sealed | [private]
LogStatus(Platform::String^message, SDKTemplate::NotifyType type) | sealed | [private]
LogStatus(Platform::String^message, SDKTemplate::NotifyType type) | sealed | [private]
LogStatusAsync(Platform::String^message, NotifyType type) | sealed | [private]
LogStatusAsync(Platform::String^message, NotifyType type) | sealed | [private]
LogStatusAsync(Platform::String^message, NotifyType type) | sealed | [private]
LogStatusAsync(Platform::String^message, NotifyType type) | sealed | [private]
LogStatusAsync(Platform::String^message, NotifyType type) | sealed | [private]
LogStatusAsync(Platform::String^message, NotifyType type) | sealed | [private]
LogStatusToOutputBoxAsync(Platform::String^message) | sealed | [private]
LogStatusToOutputBoxAsync(Platform::String^message) | sealed | [private]
LogStatusToOutputBoxAsync(Platform::String^message) | sealed | [private]
LogStatusToOutputBoxAsync(Platform::String^message) | sealed | [private]
LogStatusToOutputBoxAsync(Platform::String^message) | sealed | [private]
LogStatusToOutputBoxAsync(Platform::String^message) | sealed | [private]
LogToggleSwitch_Toggled(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
LogWithWin10Constructor() | sealed |
LogWithWin81Constructor() | sealed |
lowLatency enum value | sealed | [private]
m_account | sealed | [private]
m_account | sealed | [private]
m_accountCommandsRequestedRegistrationToken | sealed | [private]
m_accountListView | sealed | [static]
m_accounts | sealed | [private]
m_activeAccount | sealed | [private]
m_activitySensor | sealed | [private]
m_addingAccount | sealed | [private]
m_afterWriteFile | sealed | [private]
m_backBuffer | sealed | [private]
m_beforeReadFile | sealed | [private]
m_brushes | sealed | [private]
m_correlatedFrameRenderer | sealed | [private]
m_CritsecCustomSensor | sealed | [private]
m_csPrintSync | sealed | [private]
m_currentPageDescription | sealed | [private]
m_currentTask | sealed | [private]
m_CustomSensor | sealed | [private]
m_DesiredReportInterval | sealed | [private]
m_Device | sealed |
m_DeviceAccessInfo | sealed | [private]
m_deviceAccessInfo | sealed | [private]
m_deviceResources | sealed | [private]
m_directXPage | sealed | [private]
m_Dispatcher | sealed | [private]
m_dispatcher | sealed | [private]
m_displayInformation | sealed | [private]
m_documentPresenter | sealed | [private]
m_downloadableFontName | sealed | [private]
m_downloadCompletedEventToken | sealed | [private]
m_dpi | sealed | [private]
m_dpiChangedEventToken | sealed | [private]
m_faToken | sealed | [private]
m_fontDownloadListener | sealed | [private]
m_frameArrivedToken | sealed | [private]
m_frameLock | sealed | [private]
m_frameRenderer | sealed | [private]
m_frameRenderers | sealed | [private]
m_frameSources | sealed | [private]
m_groupCollection | sealed | [private]
m_imageElement | sealed | [private]
m_imagePath | sealed | [private]
m_imagePath(imagePath) | sealed | [inline]
m_imageTarget | sealed | [private]
m_imageText | sealed | [private]
m_isWindowVisible | sealed | [private]
m_languages | sealed | [private]
m_layoutUpdateInProgress | sealed | [private]
m_logger | sealed | [private]
m_logger | sealed | [private]
m_mediaCapture | sealed | [private]
m_mediaCapture | sealed | [private]
m_messageCount | sealed | [private]
m_moderateMarginsIconAsyncOperation | sealed | [private]
m_Name | sealed | [private]
m_narrowMarginsIconAsyncOperation | sealed | [private]
m_pageCollection | sealed | [private]
m_passportAvailable | sealed | [private]
m_photoScale | sealed | [private]
m_photoSize | sealed | [private]
m_printPages | sealed | [private]
m_provider | sealed | [private]
m_providers | sealed | [private]
m_reader | sealed | [private]
m_readers | sealed | [private]
m_ReadingToken | sealed | [private]
m_readingToken | sealed | [private]
m_renderer | sealed | [private]
m_requestCount | sealed | [private]
m_rootPage | sealed | [private]
m_RootPage | sealed | [private]
m_selectedAccountAction | sealed | [private]
m_selectedSourceGroupIndex | sealed | [private]
m_selectedSourceGroupIndex | sealed | [private]
m_showHeader | sealed | [private]
m_source | sealed | [private]
m_sourceCollection | sealed | [private]
m_streaming | sealed | [private]
m_taskRunning | sealed | [private]
m_textBackgroundColor | sealed | [private]
m_textBlock | sealed | [private]
m_textColor | sealed | [private]
m_textLayout | sealed | [private]
m_textLayoutImageSource | sealed |
m_textLayoutImageSource | sealed | [private]
m_textLayoutLineMetrics | sealed |
m_title | sealed | [private]
m_visibilityChangedEventToken | sealed | [private]
m_visibilityEventRegistrationToken | sealed | [private]
m_VisibilityToken | sealed | [private]
m_watcher | sealed | [private]
m_Watcher | sealed | [private]
m_watcherDeviceAddedToken | sealed | [private]
m_watcherDeviceRemovedToken | sealed | [private]
m_watcherDeviceUpdatedToken | sealed | [private]
m_wideMarginsIconAsyncOperation | sealed | [private]
main | sealed | [private]
MainPage() | sealed |
MainPage() | sealed |
MakeColor(double red, double green, double blue) | sealed |
MakeCurrent_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs e) | sealed | [private]
Manage_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ManageAccount enum value | sealed | [private]
ManipulateMe_ManipulationCompleted(Platform::Object^sender, Windows::UI::Xaml::Input::ManipulationCompletedRoutedEventArgs^e) | sealed | [private]
ManipulateMe_ManipulationDelta(Platform::Object^sender, Windows::UI::Xaml::Input::ManipulationDeltaRoutedEventArgs^e) | sealed | [private]
ManipulateMe_ManipulationInertiaStarting(Platform::Object^sender, Windows::UI::Xaml::Input::ManipulationInertiaStartingRoutedEventArgs^e) | sealed | [private]
ManipulateMe_ManipulationStarted(Platform::Object^sender, Windows::UI::Xaml::Input::ManipulationStartedRoutedEventArgs^e) | sealed | [private]
ManipulationInputProcessor(Windows::UI::Input::GestureRecognizer^gestureRecognizer, Windows::UI::Xaml::UIElement^target, Windows::UI::Xaml::UIElement^referenceFrame) | sealed |
manipulationProcessor | sealed | [private]
manipulationProcessor | sealed | [private]
ManipulationProcessor(Windows::UI::Input::GestureRecognizer^gestureRecognizer, Windows::UI::Xaml::Controls::Border^target, Windows::UI::Xaml::UIElement^referenceFrame) | sealed |
mapBillboardAddButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
mapBillboardStreamReference | sealed | [private]
mapClearButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
mapElement3DAddButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
mapElementsLayer1Button_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
mapElementsLayer2Button_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
mapIconAddButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MapIconState enum name | sealed | [private]
MapIconStateToStyleEntryState typedef | sealed | [private]
mapIconStreamReference | sealed | [private]
mapItemButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MapLayers | sealed | [private]
mapModelStreamReference | sealed | [private]
mapPolygonAddButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
mapPolylineAddButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MarkIn(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MarkOut(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MarshalLog(Platform::String^value) | sealed | [private]
MarshalLog(Platform::String^value) | sealed | [private]
MarshalNotifyUser(Platform::String^message, SDKTemplate::NotifyType type) | sealed | [private]
MatchPreviewAspectRatio() | sealed | [private]
maxUploadFileSize | sealed | [private, static]
maxWindows | sealed | [private]
MeasureOverride(Size desiredSize) override | sealed | [protected, virtual]
media_MediaEnded(Windows::Media::Playback::MediaPlayer^timedMetadataTrack, Platform::Object^e) | sealed | [private]
media_MediaEnded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
media_MediaEnded(Windows::Media::Playback::MediaPlayer^sender, Platform::Object^e) | sealed | [private]
mediaCapture | sealed | [private]
MediaCapture_Failed(Windows::Media::Capture::MediaCapture^sender, Windows::Media::Capture::MediaCaptureFailedEventArgs^e) | sealed | [private]
MediaCapture_Failed(Windows::Media::Capture::MediaCapture^sender, Windows::Media::Capture::MediaCaptureFailedEventArgs^e) | sealed | [private]
MediaCapture_Failed(Windows::Media::Capture::MediaCapture^sender, Windows::Media::Capture::MediaCaptureFailedEventArgs^e) | sealed | [private]
MediaCapture_Failed(MediaCapture^sender, MediaCaptureFailedEventArgs^errorEventArgs) | sealed | [private]
mediaCaptureFailedEventToken | sealed | [private]
mediaStreamSource | sealed | [private]
menuItems | sealed | [private]
messageNumber | sealed | [private]
MessageReceived(Windows::Networking::Sockets::MessageWebSocket^sender, Windows::Networking::Sockets::MessageWebSocketMessageReceivedEventArgs^args) | sealed | [private]
MessageReceived(Windows::Networking::Sockets::MessageWebSocket^sender, Windows::Networking::Sockets::MessageWebSocketMessageReceivedEventArgs^args) | sealed | [private]
MessageTextBox_KeyUp(Platform::Object^sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs^e) | sealed | [protected]
messageWebSocket | sealed | [private]
messageWriter | sealed | [private]
metadata_MarkCueEntered(Windows::Media::Core::TimedMetadataTrack^timedMetadataTrack, Windows::Media::Core::MediaCueEventArgs^args) | sealed | [private]
metadata_SpeechCueEntered(Windows::Media::Core::TimedMetadataTrack^timedMetadataTrack, Windows::Media::Core::MediaCueEventArgs^args) | sealed | [private]
MeteringData() | sealed |
meteringOn | sealed | [private]
meteringOnWhileSuspension | sealed | [private]
Methods_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
Methods_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
MICROSOFT_PROVIDER_ID | sealed | [private]
minPenSize | sealed | [private, static]
mirroringPreview | sealed | [private]
Model | sealed |
movementAxis_Changed(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
movementAxis_Changed(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
MoveOnXAndYAxes() | sealed |
mruToken | sealed | [private]
MSA_CLIENT_ID | sealed | [private]
MSA_SCOPE_REQUESTED | sealed | [private]
MultipleTasks() | sealed |
myGridView_ContainerContentChanging(Windows::UI::Xaml::Controls::ListViewBase^sender, Windows::UI::Xaml::Controls::ContainerContentChangingEventArgs^args) | sealed | [private]
MyInt | sealed |
myLayer1 | sealed | [private]
myLayer2 | sealed | [private]
MyMap_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MyMap_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MyMap_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MyMap_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MyMap_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MyMap_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
myMap_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
myMap_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
myMap_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
myMap_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MyMap_MapTapped(Windows::UI::Xaml::Controls::Maps::MapControl^sender, Windows::UI::Xaml::Controls::Maps::MapInputEventArgs^args) | sealed | [private]
myMap_ZoomLevelChanged(Windows::UI::Xaml::Controls::Maps::MapControl^sender, Platform::Object^args) | sealed | [private]
MyMapLoaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
MyUserControl1() | sealed |
navigatedAway | sealed | [private]
nearestMegabyte(unsigned long long bytes) | sealed | [private, static]
newButtonText | sealed | [private]
NewWindowButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
NextButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
NextButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
nextWindowId | sealed | [private]
noButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
NoCaptureDevicesHResult | sealed | [private, static]
nodeNamespace | sealed |
nodeValue | sealed |
None enum value | sealed | [private]
NormalizedAnchorPoint | sealed |
Not(bool value) | sealed | [inline, static]
notificationsGroup | sealed | [private]
NotifyIfAnyError(__int64 errCode) | sealed | [private]
NotifyPropertyChanged(Platform::String^prop) | sealed | [private]
NotifyUser(Platform::String^strMessage, NotifyType type) | sealed | [private]
NotifyUser(Platform::String^strMessage, NotifyType type) | sealed | [private]
NullStringProperty | sealed |
numberIconReferences | sealed | [private]
NumberOfPhotos | sealed | [private, static]
NumDownloads | sealed | [private]
numInputReportEventsReceived | sealed | [private]
OcrCapturedImage() | sealed |
OcrFileImage() | sealed |
ocrLanguage | sealed | [private]
OfflineLicensesChanged(Windows::Services::Store::StoreContext^sender, Platform::Object^args) | sealed | [private]
okButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnAamvaCardDataReceived(Windows::Devices::PointOfService::ClaimedMagneticStripeReader^sender, Windows::Devices::PointOfService::MagneticStripeReaderAamvaCardDataReceivedEventArgs^args) | sealed | [private]
OnAccessChanged(Windows::Devices::Enumeration::DeviceAccessInformation^sender, Windows::Devices::Enumeration::DeviceAccessChangedEventArgs^args) | sealed | [private]
OnAccessChanged(Windows::Devices::Enumeration::DeviceAccessInformation^sender, Windows::Devices::Enumeration::DeviceAccessChangedEventArgs^args) | sealed | [private]
OnAccessChanged(Windows::Devices::Enumeration::DeviceAccessInformation^sender, Windows::Devices::Enumeration::DeviceAccessChangedEventArgs^args) | sealed | [private]
OnAccountCommandsRequested(Windows::UI::ApplicationSettings::AccountsSettingsPane^sender, Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
OnAccountCommandsRequested(Windows::UI::ApplicationSettings::AccountsSettingsPane^sender, Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
OnAccountCommandsRequested(Windows::UI::ApplicationSettings::AccountsSettingsPane^sender, Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
OnAccountCommandsRequested(Windows::UI::ApplicationSettings::AccountsSettingsPane^sender, Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
OnAccountCommandsRequested(Windows::UI::ApplicationSettings::AccountsSettingsPane^sender, Windows::UI::ApplicationSettings::AccountsSettingsPaneCommandsRequestedEventArgs^e) | sealed | [private]
OnApplyTemplate() override | sealed | [protected]
OnApplyTemplate() override | sealed | [protected, virtual]
OnAppResume(Platform::Object^sender, Platform::Object^args) | sealed | [private]
OnAppResume(Platform::Object^sender, Platform::Object^args) | sealed | [private]
OnAppResuming(Platform::Object^sender, Platform::Object^args) | sealed | [private]
OnAppResuming(Platform::Object^sender, Platform::Object^args) | sealed | [private]
OnApproximateAccuracy(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnApproximateAccuracy(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnApproximateAccuracy() | sealed | [protected]
OnAppSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^e) | sealed | [private]
OnAppSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^e) | sealed | [private]
OnAppSuspension(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [private]
OnAppSuspension(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [private]
OnAutoDismissTimerExpired(Platform::Object^sender, Platform::Object^e) | sealed | [private]
OnAutoDismissTimerExpired(Platform::Object^sender, Platform::Object^e) | sealed | [private]
OnAutoDismissTimerExpired(Platform::Object^sender, Platform::Object^e) | sealed | [private]
OnBackgroundTaskCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^sender, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^e) | sealed | [private]
OnBankCardDataReceived(Windows::Devices::PointOfService::ClaimedMagneticStripeReader^sender, Windows::Devices::PointOfService::MagneticStripeReaderBankCardDataReceivedEventArgs^args) | sealed | [private]
OnBringIntoView(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnButtonClicked(Windows::UI::Input::RadialController^sender, Windows::UI::Input::RadialControllerButtonClickedEventArgs^args) | sealed | [private]
OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason) | sealed |
OnCaptureFailed(Windows::Media::Capture::MediaCapture^sender, Windows::Media::Capture::MediaCaptureFailedEventArgs^errorEventArgs) | sealed | [inline, private]
OnChannelLoggingEnabled(Windows::Foundation::Diagnostics::ILoggingChannel^sender, Platform::Object^args) | sealed | [private]
OnChannelLoggingEnabled(Windows::Foundation::Diagnostics::ILoggingChannel^sender, Platform::Object^args) | sealed | [private]
OnChatViewContainerContentChanging(Windows::UI::Xaml::Controls::ListViewBase^sender, Windows::UI::Xaml::Controls::ContainerContentChangingEventArgs^args) | sealed | [private]
OnClear(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnClear(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnClear(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnClosed(Windows::Networking::Sockets::IWebSocket^sender, Windows::Networking::Sockets::WebSocketClosedEventArgs^args) | sealed | [private]
OnClosed(Windows::Networking::Sockets::IWebSocket^sender, Windows::Networking::Sockets::WebSocketClosedEventArgs^args) | sealed | [private]
OnClosed(Windows::Networking::Sockets::IWebSocket^sender, Windows::Networking::Sockets::WebSocketClosedEventArgs^args) | sealed | [private]
OnClosed(Windows::Networking::Sockets::IWebSocket^sender, Windows::Networking::Sockets::WebSocketClosedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^args) | sealed | [private]
OnCompositionScaleChanged(_In_ Windows::UI::Xaml::Controls::SwapChainPanel^sender, _In_ Object^args) | sealed | [private]
OnCompositionScaleChanged(Windows::UI::Xaml::Controls::SwapChainPanel^sender, Object^args) | sealed | [private]
OnConnect() | sealed | [protected]
OnConnect() | sealed | [protected]
OnConnect() | sealed | [protected]
OnConnectionRequested(Windows::Devices::WiFiDirect::WiFiDirectConnectionListener^sender, Windows::Devices::WiFiDirect::WiFiDirectConnectionRequestedEventArgs^connectionEventArgs) | sealed | [private]
OnConnectionStatusChanged(Windows::Devices::WiFiDirect::WiFiDirectDevice^sender, Object^arg) | sealed | [private]
OnControlAcquired(Windows::UI::Input::RadialController^sender, Windows::UI::Input::RadialControllerControlAcquiredEventArgs^args) | sealed | [private]
OnControlLost(Windows::UI::Input::RadialController^sender, Platform::Object^args) | sealed | [private]
OnCopy(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnCustomSensorAdded(Windows::Devices::Enumeration::DeviceWatcher^watcher, Windows::Devices::Enumeration::DeviceInformation^firstDevice) | sealed | [private]
OnCustomSensorAdded(Windows::Devices::Enumeration::DeviceWatcher^watcher, Windows::Devices::Enumeration::DeviceInformation^firstDevice) | sealed | [private]
OnCut(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnDeferredImageRequestedHandler(Windows::ApplicationModel::DataTransfer::DataProviderRequest^request) | sealed | [private]
OnDeviceAccessChanged(Windows::Devices::Enumeration::DeviceAccessInformation^sender, Windows::Devices::Enumeration::DeviceAccessChangedEventArgs^eventArgs) | sealed | [private]
OnDeviceAdded(Windows::Devices::Enumeration::DeviceWatcher^sender, Windows::Devices::Enumeration::DeviceInformation^deviceInfo) | sealed | [private]
OnDeviceAdded(Windows::Devices::Enumeration::DeviceWatcher^sender, Windows::Devices::Enumeration::DeviceInformation^deviceInformation, Platform::String^deviceSelector) | sealed | [private]
OnDeviceAdded(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher, Windows::Devices::Enumeration::DeviceInformation^deviceInfo) | sealed | [private]
OnDeviceClosing(EventHandlerForDevice^sender, Windows::Devices::Enumeration::DeviceInformation^deviceInformation) | sealed | [private]
OnDeviceClosing(EventHandlerForDevice^sender, Windows::Devices::Enumeration::DeviceInformation^deviceInformation) | sealed | [private]
OnDeviceConnected(EventHandlerForDevice^sender, OnDeviceConnectedEventArgs^onDeviceConnectedEventArgs) | sealed | [private]
OnDeviceConnectedEventArgs(bool isDeviceSuccessfullyConnected, Windows::Devices::Enumeration::DeviceInformation^deviceInformation) | sealed | [inline]
OnDeviceEnumerationComplete(Windows::Devices::Enumeration::DeviceWatcher^sender, Platform::Object^args) | sealed | [private]
OnDeviceListChanged(Windows::Devices::Enumeration::DeviceWatcher^sender, Platform::String^id) | sealed | [private]
OnDeviceListChanged(Windows::Devices::Enumeration::DeviceWatcher^sender, Platform::String^id) | sealed | [private]
OnDeviceListChanged(Windows::Devices::Enumeration::DeviceWatcher^sender, Platform::String^id) | sealed | [private]
OnDeviceRemoved(Windows::Devices::Enumeration::DeviceWatcher^sender, Windows::Devices::Enumeration::DeviceInformationUpdate^deviceInformationUpdate) | sealed | [private]
OnDeviceRemoved(Windows::Devices::Enumeration::DeviceWatcher^sender, Windows::Devices::Enumeration::DeviceInformationUpdate^deviceInformationUpdate) | sealed | [private]
OnDeviceRemoved(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher, Windows::Devices::Enumeration::DeviceInformationUpdate^deviceInfoUpdate) | sealed | [private]
OnDeviceUpdated(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher, Windows::Devices::Enumeration::DeviceInformationUpdate^deviceInfoUpdate) | sealed | [private]
OnDisconnect() | sealed | [protected]
OnDisconnect() | sealed | [protected]
OnDisconnect() | sealed | [protected]
OnDisplayContentsInvalidated(_In_ Windows::Graphics::Display::DisplayInformation^sender, _In_ Platform::Object^args) | sealed | [private]
OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [private]
OnDownloadProgress(Windows::Foundation::IAsyncOperationWithProgress< Windows::Networking::BackgroundTransfer::DownloadOperation^, Windows::Networking::BackgroundTransfer::DownloadOperation^>^sender, Windows::Networking::BackgroundTransfer::DownloadOperation^progress) | sealed | [private]
OnDownloadProgress(Windows::Foundation::IAsyncOperationWithProgress< Windows::Networking::BackgroundTransfer::DownloadOperation^, Windows::Networking::BackgroundTransfer::DownloadOperation^>^sender, Windows::Networking::BackgroundTransfer::DownloadOperation^progress) | sealed | [private]
OnDpiChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^) | sealed | [private]
OnDpiChanged(_In_ Windows::Graphics::Display::DisplayInformation^sender, _In_ Platform::Object^args) | sealed | [private]
OnDpiChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [private]
OnDrawingAttributesChanged(Windows::UI::Xaml::Controls::InkToolbar^sender, Platform::Object^args) | sealed | [private]
OneAndHalfSpace_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
OnEnumerationCompleted(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher, Object^o) | sealed | [private]
OnHighAccuracy(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnHighAccuracy(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnHighAccuracy() | sealed | [protected]
OnHolding(Windows::UI::Input::GestureRecognizer^sender, Windows::UI::Input::HoldingEventArgs^args) | sealed | [private]
OnIncomingConnection(Microsoft::Samples::SimpleCommunication::StspMediaSinkProxy^sender, Microsoft::Samples::SimpleCommunication::IncomingConnectionEventArgs^args) | sealed | [private]
OnIncomingConnection(Microsoft::Samples::SimpleCommunication::StspMediaSinkProxy^sender, Microsoft::Samples::SimpleCommunication::IncomingConnectionEventArgs^args) | sealed | [private]
OnIncomingConnection(Object^sender, Object^args) | sealed | [inline, private]
OnInitializeCompleted(Windows::Foundation::HResult hr) | sealed | [private]
OnInitializeCompletedDispatchedHandler() | sealed | [private]
OnInputReportEvent(Windows::Devices::HumanInterfaceDevice::HidDevice^sender, Windows::Devices::HumanInterfaceDevice::HidInputReportReceivedEventArgs^eventArgs) | sealed | [private]
OnInsertShape(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnIsVisibleChanged(Windows::ApplicationModel::Core::CoreApplicationViewTitleBar^sender, Platform::Object^args) | sealed | [private]
OnItemInvoked(unsigned int selectedItemIndex) | sealed |
OnKeyDown(Platform::Object^sender, Windows::UI::Xaml::Input::KeyRoutedEventArgs^e) | sealed | [private]
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^e) override | sealed | [protected, virtual]
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^e) override | sealed | [virtual]
OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^e) override | sealed | [protected, virtual]
OnLayerMapElementClicked(Windows::UI::Xaml::Controls::Maps::MapElementsLayer^sender, Windows::UI::Xaml::Controls::Maps::MapElementsLayerClickEventArgs^args) | sealed | [private]
OnLayoutMetricsChanged(Windows::ApplicationModel::Core::CoreApplicationViewTitleBar^sender, Platform::Object^args) | sealed | [private]
OnLoadAsync(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnLoaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnLoadedActions(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnLogFileGenerated(Windows::Foundation::Diagnostics::IFileLoggingSession^sender, Windows::Foundation::Diagnostics::LogFileGeneratedEventArgs^args) | sealed | [private]
OnLoggingEnabled(Windows::Foundation::Diagnostics::ILoggingChannel^sender, Platform::Object^args) | sealed | [private]
OnLogSizeChanged(Platform::Object^sender, Platform::Object^args) | sealed | [private]
OnManipulationCompleted(Windows::UI::Input::GestureRecognizer^, Windows::UI::Input::ManipulationCompletedEventArgs^e) | sealed | [private]
OnManipulationCompleted(Windows::UI::Input::GestureRecognizer^sender, Windows::UI::Input::ManipulationCompletedEventArgs^args) | sealed | [private]
OnManipulationCompleted(Windows::UI::Input::GestureRecognizer^sender, Windows::UI::Input::ManipulationCompletedEventArgs^args) | sealed | [private]
OnManipulationInertiaStarting(Windows::UI::Input::GestureRecognizer^r, Windows::UI::Input::ManipulationInertiaStartingEventArgs^e) | sealed | [private]
OnManipulationInertiaStarting(Windows::UI::Input::GestureRecognizer^sender, Windows::UI::Input::ManipulationInertiaStartingEventArgs^args) | sealed | [private]
OnManipulationInertiaStarting(Windows::UI::Input::GestureRecognizer^sender, Windows::UI::Input::ManipulationInertiaStartingEventArgs^args) | sealed | [private]
OnManipulationStarted(Windows::UI::Input::GestureRecognizer^, Windows::UI::Input::ManipulationStartedEventArgs^e) | sealed | [private]
OnManipulationStarted(Windows::UI::Input::GestureRecognizer^sender, Windows::UI::Input::ManipulationStartedEventArgs^args) | sealed | [private]
OnManipulationStarted(Windows::UI::Input::GestureRecognizer^sender, Windows::UI::Input::ManipulationStartedEventArgs^args) | sealed | [private]
OnManipulationUpdated(Windows::UI::Input::GestureRecognizer^, Windows::UI::Input::ManipulationUpdatedEventArgs^e) | sealed | [private]
OnManipulationUpdated(Windows::UI::Input::GestureRecognizer^sender, Windows::UI::Input::ManipulationUpdatedEventArgs^args) | sealed | [private]
OnManipulationUpdated(Windows::UI::Input::GestureRecognizer^sender, Windows::UI::Input::ManipulationUpdatedEventArgs^args) | sealed | [private]
OnMediaCaptureFailed(CaptureDevice^sender, CaptureFailedEventArgs^errorEventArgs) | sealed | [private]
OnMediaCaptureFailed(CaptureDevice^sender, CaptureFailedEventArgs^errorEventArgs) | sealed | [private]
OnMediaFailed(Platform::Object^sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^e) | sealed | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | sealed | [protected]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | sealed | [protected]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | sealed | [protected]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | sealed | [protected]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | sealed | [protected]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | sealed | [protected, virtual]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | sealed | [protected]
OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^e) override | sealed | [protected, virtual]
OnNavigationFailed(Platform::Object^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs^e) | sealed | [private]
OnNavigationFailed(Platform::Object^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs^e) | sealed | [private]
OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [private]
OnOrientationChanged(_In_ Windows::Graphics::Display::DisplayInformation^sender, _In_ Platform::Object^args) | sealed | [private]
OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^e) | sealed | [private]
OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [private]
OnPaste(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnPenColorChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnPenThicknessChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnPenTypeChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnPointerCanceled(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | sealed | [private]
OnPointerCanceled(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | sealed | [private]
OnPointerExited(Platform::Object^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
OnPointerMoved(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | sealed | [private]
OnPointerMoved(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | sealed | [private]
OnPointerMoved(Platform::Object^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
OnPointerPressed(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | sealed | [private]
OnPointerPressed(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | sealed | [private]
OnPointerPressed(Platform::Object^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
OnPointerReleased(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | sealed | [private]
OnPointerReleased(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^args) | sealed | [private]
OnPointerReleased(Platform::Object^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
OnPreviewPagesCreated(Windows::Graphics::Printing::PrintTaskOptions^printTaskOptions) override | sealed | [protected, virtual]
OnPrintButtonClick(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnPrintButtonClick(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnPrintButtonClick(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnPrintButtonClick(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnPrintButtonClick(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnPrintButtonClick(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^args) | sealed | [private]
OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^args) | sealed | [private]
OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^args) | sealed | [private]
OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^args) | sealed | [private]
OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^args) | sealed | [private]
OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^args) | sealed | [private]
OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^args) | sealed | [private]
OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^args) | sealed | [private]
OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^args) | sealed | [private]
OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^args) | sealed | [private]
OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^args) | sealed | [private]
OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^args) | sealed | [private]
OnPropertyChanged(Platform::String^propertyName) | sealed | [private]
OnPropertyChanged(Platform::String^name) | sealed | [protected]
OnPropertyChanged(Platform::String^propertyName) | sealed | [protected]
OnProximitySensorAdded(Windows::Devices::Enumeration::DeviceWatcher^sender, Windows::Devices::Enumeration::DeviceInformation^device) | sealed | [private]
OnProximitySensorAdded(Windows::Devices::Enumeration::DeviceWatcher^sender, Windows::Devices::Enumeration::DeviceInformation^device) | sealed | [private]
OnProximitySensorAdded(Windows::Devices::Enumeration::DeviceWatcher^sender, Windows::Devices::Enumeration::DeviceInformation^device) | sealed | [private]
OnProximitySensorAdded(Windows::Devices::Enumeration::DeviceWatcher^sender, Windows::Devices::Enumeration::DeviceInformation^device) | sealed | [private]
OnRangesDownloaded(Windows::Networking::BackgroundTransfer::DownloadOperation^sender, Windows::Networking::BackgroundTransfer::BackgroundTransferRangesDownloadedEventArgs^args) | sealed | [private]
OnReadingChanged(Windows::Devices::Sensors::Custom::CustomSensor^sender, Windows::Devices::Sensors::Custom::CustomSensorReadingChangedEventArgs^e) | sealed | [private]
OnReadingChanged(Windows::Devices::Sensors::Pedometer^sender, Windows::Devices::Sensors::PedometerReadingChangedEventArgs^args) | sealed | [private]
OnRecognizeAsync(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnRecognizerChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnReleaseDeviceRequested(Platform::Object^sender, Windows::Devices::PointOfService::ClaimedMagneticStripeReader^args) | sealed | [private]
OnReleaseDeviceRequested(Platform::Object^sender, Windows::Devices::PointOfService::ClaimedMagneticStripeReader^args) | sealed | [private]
OnRendering(_In_ Platform::Object^sender, _In_ Platform::Object^args) | sealed | [private]
OnRendering(Platform::Object^sender, Platform::Object^args) | sealed | [private]
OnReplay(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnReset(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnResuming(Platform::Object^sender, Platform::Object^args) | sealed | [private]
OnRightTapped(Windows::UI::Input::GestureRecognizer^sender, Windows::UI::Input::RightTappedEventArgs^args) | sealed | [private]
OnRotationChanged(Windows::UI::Input::RadialController^sender, Windows::UI::Input::RadialControllerRotationChangedEventArgs^args) | sealed | [private]
OnSaveAsync(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnScreenContactContinued(Windows::UI::Input::RadialController^sender, Windows::UI::Input::RadialControllerScreenContactContinuedEventArgs^args) | sealed | [private]
OnScreenContactEnded(Windows::UI::Input::RadialController^sender, Platform::Object^args) | sealed | [private]
OnScreenContactStarted(Windows::UI::Input::RadialController^sender, Windows::UI::Input::RadialControllerScreenContactStartedEventArgs^args) | sealed | [private]
OnSend() | sealed | [protected]
OnSend() | sealed | [protected]
OnServerCustomValidationRequested(Windows::Networking::Sockets::MessageWebSocket^sender, Windows::Networking::Sockets::WebSocketServerCustomValidationRequestedEventArgs^args) | sealed | [private]
OnServerCustomValidationRequested(Windows::Networking::Sockets::StreamWebSocket^sender, Windows::Networking::Sockets::WebSocketServerCustomValidationRequestedEventArgs^args) | sealed | [private]
OnServerCustomValidationRequested(Windows::Networking::Sockets::MessageWebSocket^sender, Windows::Networking::Sockets::WebSocketServerCustomValidationRequestedEventArgs^args) | sealed | [private]
OnShareProvidersRequested(Windows::ApplicationModel::DataTransfer::DataTransferManager^sender, Windows::ApplicationModel::DataTransfer::ShareProvidersRequestedEventArgs^e) | sealed | [private]
OnShareToContosoChat(Windows::ApplicationModel::DataTransfer::ShareProviderOperation^operation) | sealed | [private]
OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
OnSizeChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::WindowSizeChangedEventArgs^args) | sealed | [private]
OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs e) | sealed | [private]
OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs e) | sealed | [private]
OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
OnSocketConnectionReceived(Windows::Networking::Sockets::StreamSocketListener^sender, Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs^connectionReceivedEventArgs) | sealed | [private]
OnStart(Windows::ApplicationModel::Background::BackgroundTaskRegistrationGroup^sender, Windows::ApplicationModel::Activation::BackgroundActivatedEventArgs^args) | sealed | [static]
OnStart() | sealed | [protected]
OnStatusChanged(Platform::Object^sender, LoggingScenarioEventArgs^args) | sealed | [private]
OnStatusChanged(Platform::Object^sender, LoggingScenarioEventArgs^args) | sealed | [private]
OnStatusChanged(Windows::Devices::WiFiDirect::WiFiDirectAdvertisementPublisher^sender, Windows::Devices::WiFiDirect::WiFiDirectAdvertisementPublisherStatusChangedEventArgs^statusEventArgs) | sealed | [private]
OnStop() | sealed | [protected]
OnStopped(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher, Object^o) | sealed | [private]
OnStrokeCanceled(Windows::UI::Input::Inking::InkStrokeInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
OnStrokeContinued(Windows::UI::Input::Inking::InkStrokeInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
OnStrokeEnded(Windows::UI::Input::Inking::InkStrokeInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
OnStrokesCollected(Windows::UI::Input::Inking::InkPresenter^sender, Windows::UI::Input::Inking::InkStrokesCollectedEventArgs^args) | sealed | [private]
OnStrokeStarted(Windows::UI::Input::Inking::InkStrokeInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^e) | sealed | [private]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^e) | sealed | [private]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^e) | sealed | [private]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [private]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^e) | sealed | [private]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^e) | sealed | [private]
OnSwapChainPanelSizeChanged(_In_ Platform::Object^sender, _In_ Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
OnSwapChainPanelSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^args) | sealed | [private]
OnTargetFormatChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
OnTargetFormatChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
OnTargetFormatChanged(Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
OnTaskCompleted() | sealed | [private]
OnTick(Platform::Object^sender, Platform::Object^args) | sealed | [private]
OnTimer(Windows::System::Threading::ThreadPoolTimer^timer) | sealed | [private]
OnTimer(Windows::System::Threading::ThreadPoolTimer^timer) | sealed | [private]
OnTimerTick(Object^sender, Object^e) | sealed | [private]
OnTimerTick(Object^sender, Object^e) | sealed | [private]
OnTimerTick(Object^sender, Object^e) | sealed | [private]
OnUnreliableAccuracy(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnUnreliableAccuracy(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OnUnreliableAccuracy() | sealed | [protected]
OnViewChanged(Platform::Object^, Windows::UI::Xaml::Controls::ScrollViewerViewChangedEventArgs^e) | sealed | [private]
OnVisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^args) | sealed | [private]
OnVisibilityChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::VisibilityChangedEventArgs^args) | sealed | [private]
OnWindowResize(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | sealed | [private]
OnWindowResize(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | sealed | [private]
OnWindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | sealed | [private]
OnWindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | sealed | [private]
OnWindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | sealed | [private]
OnWindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^e) | sealed | [private]
OnWindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^args) | sealed | [private]
OnWindowSizeChanged(Platform::Object^sender, Windows::UI::Core::WindowSizeChangedEventArgs^args) | sealed | [private]
OpenDrawerButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OpenFromListButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OpenFx2DeviceAsync(Platform::String^Id) | sealed | [private]
OpenMenuItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OpenMenuItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OpenMenuItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
openPrivacySettings_Click(Windows::UI::Xaml::Documents::Hyperlink^sender, Windows::UI::Xaml::Documents::HyperlinkClickEventArgs^args) | sealed | [private]
openPrivacySettings_Click(Windows::UI::Xaml::Documents::Hyperlink^sender, Windows::UI::Xaml::Documents::HyperlinkClickEventArgs^args) | sealed | [private]
openPrivacySettings_Click(Windows::UI::Xaml::Documents::Hyperlink^sender, Windows::UI::Xaml::Documents::HyperlinkClickEventArgs^args) | sealed | [private]
optedIn | sealed | [private, static]
OrderSlider_ValudChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
ORGANIZATION_AUTHORITY | sealed | [private]
OrientationChanged(Windows::Devices::Sensors::SimpleOrientationSensor^sender, Windows::Devices::Sensors::SimpleOrientationSensorOrientationChangedEventArgs^e) | sealed | [private]
orientationChangedEventToken | sealed | [private]
orientationChangedToken | sealed | [private]
OrientationsToString(Windows::Graphics::Display::DisplayOrientations orientations) | sealed | [private, static]
orientationToken | sealed | [private]
OtherBindings() | sealed |
OtherLinkInvoked(Windows::UI::Popups::IUICommand^command) | sealed | [private]
OtherLinkInvoked(Windows::UI::Popups::IUICommand^command) | sealed | [private]
OtherLinkInvoked(Windows::UI::Popups::IUICommand^command) | sealed | [private]
OtherLinkInvoked(Windows::UI::Popups::IUICommand^command) | sealed | [private]
OtherLinkInvoked(Windows::UI::Popups::IUICommand^command) | sealed | [private]
OutputPauseButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OutputPauseButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OutputPauseButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OutputPlayButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OutputPlayButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OutputPlayButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OutputSettings(double rawPixelsPerViewPixel, Windows::UI::Xaml::FrameworkElement^rectangle, Windows::UI::Xaml::Controls::TextBlock^relativePxText, Windows::UI::Xaml::Controls::TextBlock^physicalPxText, Windows::UI::Xaml::Controls::TextBlock^fontTextBlock) | sealed | [private]
OutputStopButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OutputStopButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OutputStopButton_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
OutputTokenResult(Windows::Security::Authentication::Web::Core::WebTokenRequestResult^result) | sealed | [private]
OutputTokenResult(Windows::Security::Authentication::Web::Core::WebTokenRequestResult^result) | sealed | [private]
OutputTokenResult(Windows::Security::Authentication::Web::Core::WebTokenRequestResult^result) | sealed | [private]
OutputTokenResult(Windows::Security::Authentication::Web::Core::WebTokenRequestResult^result) | sealed | [private]
OutputTokenResult(Windows::Security::Authentication::Web::Core::WebTokenRequestResult^result) | sealed | [private]
OutputTokenResult(Windows::Security::Authentication::Web::Core::WebTokenRequestResult^result) | sealed | [private]
overflow | sealed |
overlayVideoFile | sealed | [private]
Page_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Page_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Page_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Page_Loaded(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
pageContent | sealed | [private]
PageRangePrintHelper(Page^scenarioPage) | sealed |
PageToPrint() | sealed |
PairButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PairButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PairingRequestedHandler(Windows::Devices::Enumeration::DeviceInformationCustomPairing^sender, Windows::Devices::Enumeration::DevicePairingRequestedEventArgs^args) | sealed | [private]
ParsePinPolicy() | sealed | [private]
passive enum value | sealed | [private]
PassportAvailableCheckAsync() | sealed | [private]
PassportDelete() | sealed | [private]
PasteFlyoutItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PauseAll_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PauseAnimationTapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | sealed | [private]
PauseDownload_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [protected]
pdfDocument | sealed | [private]
pedometer | sealed | [private]
penSize | sealed | [private]
penSize | sealed | [private, static]
penSizeIncrement | sealed | [private, static]
periodicTimer | sealed | [private]
PeriodicTimer | sealed | [private]
pfnLink_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PhasedTemplate_Checked(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PhasingTests() | sealed |
PhoneButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
phoneConstraint | sealed | [private]
PhotoButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PhotoSettings_Changed(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PhotosPrintHelper(Page^scenarioPage) | sealed | [inline]
PickAFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickAFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickAndSetButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickAudioButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickAudioButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickContactEmail() | sealed |
PickContactPhone() | sealed |
PickContactsEmail() | sealed |
PickContactsPhone() | sealed |
pickedFile | sealed | [private]
PickFile(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickFile(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickFile(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickFilesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickFolderButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickNextMediaSourceAsync() | sealed | [private]
PickNextMediaSourceAsync() | sealed | [private]
PickNextMediaSourceWorkerAsync() | sealed | [private]
PickNextMediaSourceWorkerAsync() | sealed | [private]
PickOutput(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickOutput(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickOutput(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickPlaylistButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickPlaylistButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickPlaylistButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickPlaylistButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PickSingleDeviceButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
picturesLibrary | sealed | [private]
pin | sealed | [private]
Pin_ValueChanged(Windows::Devices::Gpio::GpioPin^sender, Windows::Devices::Gpio::GpioPinValueChangedEventArgs^e) | sealed | [private]
pinPolicyAllowedIndex | sealed | [private, static]
pinPolicyDisallowedIndex | sealed | [private, static]
pinPolicyRequireOneIndex | sealed | [private, static]
PitchSlider_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
places | sealed | [private]
PlayAnimationTapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | sealed | [private]
PlayButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PlayButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PlayButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PlayFile(Windows::Storage::StorageFile^MediaFile) | sealed | [private]
PlayFile(Windows::Storage::StorageFile^MediaFile) | sealed | [private]
PlayFile(Windows::Storage::StorageFile^MediaFile) | sealed | [private]
playlist | sealed | [private]
Pointer_Entered(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | sealed | [private]
Pointer_Moved(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | sealed | [private]
Pointer_Pressed(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | sealed | [private]
Pointer_Released(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | sealed | [private]
Pointer_Wheel_Changed(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | sealed | [private]
PointerHitTestStates enum name | sealed | [private]
pointerMovedToken | sealed | [private]
pointerPressedToken | sealed | [private]
pointerReleasedToken | sealed | [private]
PopulateColorsClick(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
PopulateComboBox() | sealed | [private]
PopulateComboBox(Windows::Media::Capture::MediaStreamType streamType, Windows::UI::Xaml::Controls::ComboBox^comboBox, bool showFrameRate=true) | sealed | [private]
PopulateComboBoxes() | sealed | [private]
PopulateLanguageDropdown() | sealed | [private]
PopulateLanguageDropdown() | sealed | [private]
PopulateLanguageDropdown() | sealed | [private]
PopulateLanguageDropdown() | sealed | [private]
PopulateLanguageDropdown() | sealed | [private]
PopulateLanguageDropdown() | sealed | [private]
PopulateLanguageDropdown() | sealed | [private]
PopulateSettingsComboBox() | sealed | [private]
popups | sealed | [private]
PreparePrintContent(Page^page) | PrintHelper |
PrepareSampleFiles_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PrepareToSuspend() | sealed |
PrepareToSuspendAsync() | sealed |
PresentTextLayout() | sealed | [private]
PreviewButtonClicked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PreviewImage_SizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
PreviewImage_SizeChanged(Platform::Object^sender, SizeChangedEventArgs^e) | sealed | [private]
previewing enum value | sealed | [private]
previewing_localClientButtonClicked() | sealed | [private]
previewing_previewButtonClicked() | sealed | [private]
previewing_recordingStarted() | sealed | [private]
PreviewOptionsPrintHelper(Page^scenarioPage) | sealed | [inline]
PreviewOptionsPrintHelper::AddOnePrintPage(RichTextBlockOverflow^lastRTBOAdded, Windows::Graphics::Printing::PrintPageDescription printPageDescription) | sealed | [protected]
PreviewSettings_Changed(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PreviewSettings_Changed(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PreviewUnavailable() | sealed |
PreviewUnavailable(Windows::Foundation::Size paperSize, Windows::Foundation::Size printableSize) | sealed |
previousInputLanguage | sealed | [private]
previousSwitchValues | sealed | [private]
previousTransform | sealed | [private]
previousZoomLevel | sealed | [private]
price | sealed |
PrintBarcode_Click() | sealed | [protected]
PrintBitmap_Click() | sealed | [protected]
printDetailedOptions_OptionChanged(Windows::Graphics::Printing::OptionDetails::PrintTaskOptionDetails^sender, Windows::Graphics::Printing::OptionDetails::PrintTaskOptionChangedEventArgs^args) | sealed | [private]
PrintDetailedOptionsOptionChanged(Windows::Graphics::Printing::OptionDetails::PrintTaskOptionDetails^sender, Windows::Graphics::Printing::OptionDetails::PrintTaskOptionChangedEventArgs^args) | sealed | [protected]
printer | sealed | [private]
PrintFrame | sealed |
printHelper | sealed | [private]
PrintLine_Click(Platform::Object^sender, RoutedEventArgs e) | sealed | [private]
PrintLine_Click() | sealed | [protected]
PrintLineFeedAndCutPaper(ReceiptPrintJob^job, Platform::String^receipt) | sealed | [private]
PrintLineFeedAndCutPaper(Windows::Devices::PointOfService::ReceiptPrintJob^job, Platform::String^receipt) | sealed | [private]
PrintMenuItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PrintMenuItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PrintMenuItem_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PrintProfileInformation(Windows::Media::Capture::MediaCaptureVideoProfile^profile, Windows::Media::Capture::MediaCaptureVideoProfileMediaDescription^description) | sealed | [private]
PrintReceipt() | sealed | [private]
PrintReceipt_Click(Platform::Object^sender, RoutedEventArgs e) | sealed | [private]
PrintReceipt_Click() | sealed | [protected]
PrintRow(Platform::Array< byte >^bytes, int i) | sealed | [private]
PrintSelectedItem(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | sealed | [private]
PrintSelectedItem() | sealed | [private]
PrintTaskRequested(Windows::Graphics::Printing::PrintManager^sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^e) override | sealed | [protected, virtual]
PrintTaskRequested(Windows::Graphics::Printing::PrintManager^sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^e) override | sealed | [protected, virtual]
PrintTaskRequested(Windows::Graphics::Printing::PrintManager^sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^e) override | sealed | [protected, virtual]
PrintTaskRequested(Windows::Graphics::Printing::PrintManager^sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^e) override | sealed | [protected, virtual]
PrintTaskRequested(Windows::Graphics::Printing::PrintManager^sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^e) override | sealed | [protected, virtual]
PrivacyPolicyInvoked(Windows::UI::Popups::IUICommand^command) | sealed | [private]
PrivacyPolicyInvoked(Windows::UI::Popups::IUICommand^command) | sealed | [private]
PrivacyPolicyInvoked(Windows::UI::Popups::IUICommand^command) | sealed | [private]
PrivacyPolicyInvoked(Windows::UI::Popups::IUICommand^command) | sealed | [private]
PrivacyPolicyInvoked(Windows::UI::Popups::IUICommand^command) | sealed | [private]
privatePropertyChanged | sealed | [private]
ProcessColor(String^value) | sealed |
ProcessDataVirtualizationScrollOffsetsAsync(double actualHeight) | sealed | [private]
ProcessFrame(Windows::Media::Capture::Frames::MediaFrameReference^frame) | sealed |
processingScrollOffsets | sealed | [private]
processingScrollOffsetsDeferred | sealed | [private]
productKind | sealed |
Progress | sealed | [private]
projectionCombobox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
PropertyChanged | sealed |
ProtectionLevel | sealed |
ProtectionLevelSelectorInfo(Platform::String^displayName, Windows::Devices::Enumeration::DevicePairingProtectionLevel protectionLevel) | sealed | [inline]
Protocol_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
providePasswordCredentialSrc | sealed | [private]
providePinTaskSrc | sealed | [private]
PROVIDER_ID_SUBCONTAINER | sealed | [private]
PtFromPx(double pixel) | sealed | [private]
PurchaseAddOnButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PurchaseAddOnButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PurchaseAddOnButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PurchaseFullLicense() | sealed |
PurpleButton_Click(_In_ Platform::Object^sender, _In_ Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
PxFromPt(double pt) | sealed | [private]
radius | sealed | [private, static]
RadiusSlider_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
RaiseDeviceChanged(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher, Platform::String^id) | sealed | [private]
RaiseToastAfterDelay(int id, int seconds) | sealed | [private]
randomAccessStream | sealed | [private]
ReadBlock_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ReadBytes() | sealed |
ReadBytesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
readCancellationTokenSource | sealed | [private]
readCounter | sealed | [private]
reader | sealed | [private]
Reader_FrameArrived(Windows::Media::Capture::Frames::MediaFrameReader^reader, Windows::Media::Capture::Frames::MediaFrameArrivedEventArgs^args) | sealed | [private]
ReadFromStreamButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::Accelerometer^sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^e) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::Accelerometer^sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^e) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::ActivitySensor^sender, Windows::Devices::Sensors::ActivitySensorReadingChangedEventArgs^e) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::Altimeter^sender, Windows::Devices::Sensors::AltimeterReadingChangedEventArgs^e) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::Barometer^sender, Windows::Devices::Sensors::BarometerReadingChangedEventArgs^e) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::Compass^sender, Windows::Devices::Sensors::CompassReadingChangedEventArgs^e) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::Gyrometer^sender, Windows::Devices::Sensors::GyrometerReadingChangedEventArgs^e) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::Inclinometer^sender, Windows::Devices::Sensors::InclinometerReadingChangedEventArgs^e) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::LightSensor^sender, Windows::Devices::Sensors::LightSensorReadingChangedEventArgs^e) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::OrientationSensor^sender, Windows::Devices::Sensors::OrientationSensorReadingChangedEventArgs^e) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::ProximitySensor^sender, Windows::Devices::Sensors::ProximitySensorReadingChangedEventArgs^e) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::Inclinometer^sender, Windows::Devices::Sensors::InclinometerReadingChangedEventArgs^e) | sealed | [private]
ReadingChangedOriginal(Windows::Devices::Sensors::Accelerometer^sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^e) | sealed | [private]
ReadingChangedReadingTransform(Windows::Devices::Sensors::Accelerometer^sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^e) | sealed | [private]
readingToken | sealed | [private]
readingTokenOriginal | sealed | [private]
readingTokenReadingTransform | sealed | [private]
ReadLoop(Windows::Storage::Streams::DataReader^dataReader) | sealed | [private]
ReadMessage() | sealed |
ReadOnlyTextBox_ContextMenuOpening(Platform::Object^sender, Windows::UI::Xaml::Controls::ContextMenuEventArgs^e) | sealed | [private]
readOperation | sealed | [private]
ReadStreamAsync(Concurrency::task< Windows::Networking::BackgroundTransfer::DownloadOperation^> downloadTask, Windows::Storage::Streams::Buffer^readBuffer) | sealed | [private]
ReadTextButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ReceiveDataLoop(Windows::Networking::Sockets::StreamWebSocket^activeSocket, Windows::Storage::Streams::IBuffer^readBuffer, UINT32 bytesReceivedSoFar) | sealed | [private]
Recognize_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
recognizer | sealed | [private]
RecognizeWithoutUI_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RecognizeWithoutUIDictationGrammar_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RecognizeWithoutUIListConstraint_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RecognizeWithoutUIWebSearchGrammar_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RecognizeWithUI_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RecognizeWithUIDictationGrammar_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RecognizeWithUIListConstraint_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RecognizeWithUIWebSearchGrammar_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
recordCollection | sealed | [private]
recoView | sealed | [private]
reference | sealed | [private]
RefreshButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
refreshMapIcons() | sealed | [private]
RefreshPreview() | sealed | [private]
RefreshPreview() | sealed | [private]
RefreshPreview() | sealed | [protected]
RefreshTimer_Tick(Platform::Object^sender, Platform::Object^e) | sealed | [private]
RefreshWindowButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterBackgroundTask() | sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterBackgroundTask(Windows::ApplicationModel::Background::DeviceWatcherTrigger^deviceWatcherTrigger) | sealed | [private]
RegisterBackgroundTask() | sealed | [private]
RegisterBackgroundTask() | sealed | [private]
RegisterBtn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterCustomTrigger_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
registered | sealed | [private]
registeredDevice | sealed | [private]
registeredForEvents | sealed | [private]
RegisterForAppEvents(void) | sealed | [private]
RegisterForBoundaryEvents(Windows::Media::Playback::MediaPlaybackItem^mediaPlaybackItem) | sealed | [private]
RegisterForDeviceAccessStatusChange() | sealed | [private]
RegisterForDeviceWatcherEvents(void) | sealed | [private]
RegisterForInputReportEvents() | sealed | [private]
RegisterForInputReportEvents_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^eventArgs) | sealed | [private]
RegisterForMarkEvents(Windows::Media::Playback::MediaPlaybackItem^mediaPlaybackItem) | sealed | [private]
RegisterGroupedBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterGroupedBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RegisterMetadataHandlerForMarks(Windows::Media::Playback::MediaPlaybackItem^mediaPlaybackItem, int index) | sealed | [private]
RegisterMetadataHandlerForSentences(Windows::Media::Playback::MediaPlaybackItem^mediaPlaybackItem, int index) | sealed | [private]
RegisterMetadataHandlerForWords(Windows::Media::Playback::MediaPlaybackItem^mediaPlaybackItem, int index) | sealed | [private]
ReleaseAll_Click() | sealed | [protected]
ReleaseButton1_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ReleaseButton2_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ReleaseClaim_Click() | sealed | [protected]
releaseDeviceRequestedToken | sealed | [private]
releaseRequestedToken1 | sealed | [private]
releaseRequestedToken2 | sealed | [private]
RemoveCredentials_Click(Platform::Object^, Platform::Object^) | sealed |
RemoveCustomProviders() | sealed | [private]
RemoveDeviceAsync(Platform::String^id) | sealed | [private]
RemoveDeviceFromList(Platform::String^deviceId) | sealed | [private]
RemoveFeedButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RemoveFolderButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RemoveItem(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | sealed | [private]
RemoveJumpList_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Render(WindowsPreview::Media::Capture::Frames::PoseTrackingFrame^frame, CoordinateTransformationMethod^transformation) | sealed |
RenderPropertyPopUp(Platform::String^pointerProperties, Platform::String^deviceSpecificProperties, Windows::UI::Input::PointerPoint^currentPoint) | sealed | [private]
reorderGroup | sealed | [private]
ReportCalendarData(Windows::Globalization::Calendar^calendar, Platform::String^calendarLabel) | sealed | [private]
ReportCalendarData(Windows::Globalization::Calendar^calendar, Platform::String^calendarLabel) | sealed | [private]
ReportCalendarData(Windows::Globalization::Calendar^calendar, Platform::String^calendarLabel) | sealed | [private]
ReportCalendarData(Windows::Globalization::Calendar^calendar) | sealed | [private]
ReportColors() | sealed | [private]
ReportContactResult(Windows::ApplicationModel::Contacts::Contact^contact) | sealed | [private]
ReportContactResults(Windows::Foundation::Collections::IVector< Windows::ApplicationModel::Contacts::Contact^>^contacts) | sealed | [private]
ReportLanguageData(Windows::Globalization::Language^lang) | sealed | [private]
ReportRegionData(Windows::Globalization::GeographicRegion^region) | sealed | [private]
RequestCalibration(Windows::Devices::Sensors::MagnetometerAccuracy accuracy) | sealed |
RequestCalibration(Windows::Devices::Sensors::MagnetometerAccuracy accuracy) | sealed |
RequestCalibration(Windows::Devices::Sensors::MagnetometerAccuracy accuracy) | sealed |
RequestConsent_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RequestMicrophonePermissionAsync() | sealed | [static]
RequestTextLayoutUpdate() | sealed | [private]
Reset() | sealed |
Reset() | sealed |
Reset() | sealed | [private]
Reset_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Reset_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ResetButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ResetButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ResetButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
resetButton_Pressed(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
resetButton_Pressed(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ResetButton_Pressed(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ResetOutput() | sealed | [private]
ResetOutput() | sealed | [private]
ResetPin_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ResetRect() | sealed |
ResetScenarioState() | sealed | [private]
ResetScenarioState() | sealed | [private]
ResetScenarioState() | sealed | [private]
ResetTheScenarioState() | sealed | [private]
ResetTheScenarioState() | sealed | [private]
ResetTheScenarioState() | sealed | [private]
ResetValuesClick(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ResetValuesClick(Object^, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ResetValuesClick(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ResetValuesClick(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ResizeView_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RestartWatcher() | sealed | [private]
RestoreScrollPosition() | sealed | [protected]
resultCollection | sealed | [private]
ResultsListView_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
ResultsListView_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
ResumeAll_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ResumeDownload_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [protected]
ResumeLoggingIfApplicable() | sealed |
ResumeLoggingIfApplicable() | sealed |
RetrieveAllItems_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RetrieveAllItems_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RetrieveMatchedItems_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RetrieveMatchingItems_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
RevealPasswords_Click(Platform::Object^, Platform::Object^) | sealed |
Role enum name | sealed | [private]
RollSlider_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
rootPage | sealed | [private]
rootPage | sealed | [private]
rotationDegrees | sealed | [private]
RotationSpeedSlider_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
rpcclient | sealed | [private]
rpcDataCountOld | sealed | [private]
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance) | sealed |
RunDownload(Windows::Networking::BackgroundTransfer::DownloadOperation^download) | sealed | [private]
RunDownloads(Windows::Networking::BackgroundTransfer::BackgroundDownloader^downloader, ScenarioType type) | sealed | [private]
RunDownloadsAsync() | sealed | [private]
runId | sealed | [private, static]
running | sealed | [private]
runningStepCount | sealed | [private]
S1_AddWithAPI() | sealed |
S2_UpdateAndDeleteWithAPI() | sealed |
S3_RetrieveWithAPI() | sealed |
S4_CheckIndexRevision() | sealed |
S5_AddWithAppContent() | sealed |
S6_DeleteWithAppContent() | sealed |
S7_RetrieveWithAppContent() | sealed |
sampleArray | sealed | [private]
SampleBackgroundTask() | sealed |
SampleBackgroundTask() | sealed |
SampleBackgroundTaskWithCondition() | sealed |
SampleBackgroundTaskWithCondition() | sealed |
SampleButton_Tapped(Platform::Object^sender, TappedRoutedEventArgs^e) | sealed | [private]
sampleMessage | sealed | [private]
samplePeriod | sealed | [private]
sampleRefreshCount | sealed | [private]
Save_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SaveAccount(Windows::Security::Credentials::WebAccount^account) | sealed | [private]
SaveAccount(Windows::Security::Credentials::WebAccount^account) | sealed | [private]
SaveAccount(Windows::Security::Credentials::WebAccount^account) | sealed | [private]
SaveAccount(Windows::Security::Credentials::WebAccountProvider^provider, Windows::Security::Credentials::WebAccount^account) | sealed | [private]
SaveAccount(Windows::Security::Credentials::WebAccount^account) | sealed | [private]
SaveAccount(Windows::Security::Credentials::WebAccount^account) | sealed | [private]
savedScrollPosition | sealed | [private]
SaveFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | sealed |
SaveLogInMemoryToFileAsync() | sealed | [private]
SaveScrollPosition() | sealed | [protected]
SaveToFutureAccessListButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SavingDataReason() | sealed |
ScalingSlider_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
Scenario(Platform::String^title, Platform::String^description, Platform::String^className) | sealed |
Scenario0_Choose() | sealed |
Scenario0_Choose() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario1() | sealed |
Scenario10() | sealed |
Scenario10() | sealed |
Scenario10() | sealed |
Scenario10() | sealed |
Scenario10_SearchMultipleResourceIds(Windows::ApplicationModel::Resources::Core::ResourceContext^context, Platform::Collections::Vector< Platform::String^>^resourceIds) | sealed | [private]
Scenario10_ShowCandidates(Platform::String^resourceId, Windows::Foundation::Collections::IVectorView< Windows::ApplicationModel::Resources::Core::ResourceCandidate^>^resourceCandidates) | sealed | [private]
Scenario10Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Scenario11() | sealed |
Scenario11() | sealed |
Scenario11() | sealed |
Scenario11() | sealed |
Scenario11Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Scenario12() | sealed |
Scenario12() | sealed |
Scenario12() | sealed |
Scenario12Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Scenario13() | sealed |
Scenario1::GetElementRect(Windows::UI::Xaml::FrameworkElement^element) | sealed | [private]
Scenario1_AddAccount() | sealed |
Scenario1_Advertiser() | sealed |
Scenario1_Analyze() | sealed |
Scenario1_AppBarButtons() | sealed |
Scenario1_BankCards() | sealed |
Scenario1_Basic() | sealed |
Scenario1_Basic() | sealed |
Scenario1_Basic() | sealed |
Scenario1_Basic() | sealed |
Scenario1_Basic() | sealed |
Scenario1_CheckConsentAvailability() | sealed |
Scenario1_Colors() | sealed |
Scenario1_Configuration() | sealed |
Scenario1_Conversion() | sealed |
Scenario1_CorrelateStreams() | sealed |
Scenario1_Create() | sealed |
Scenario1_CreateTPMVSC() | sealed |
Scenario1_CurrentActivity() | sealed |
Scenario1_CustomDry() | sealed |
Scenario1_Data() | sealed |
Scenario1_DataEvents() | sealed |
Scenario1_DataEvents() | sealed |
Scenario1_DataEvents() | sealed |
Scenario1_DataEvents() | sealed |
Scenario1_DataEvents() | sealed |
Scenario1_DataEvents() | sealed |
Scenario1_DataEvents() | sealed |
Scenario1_DataEvents() | sealed |
Scenario1_DataEvents() | sealed |
Scenario1_DataEvents() | sealed |
Scenario1_DataEvents() | sealed |
Scenario1_DataEvents() | sealed |
Scenario1_Default() | sealed |
Scenario1_DefaultAccount() | sealed |
Scenario1_DefaultSpacing() | sealed |
Scenario1_DevicePicker() | sealed |
Scenario1_DeviceUse() | sealed |
Scenario1_DisplayDepthColorIR() | sealed |
Scenario1_Download() | sealed |
Scenario1_Enable() | sealed |
Scenario1_EventAndMenuHookup() | sealed |
Scenario1_Events() | sealed |
Scenario1_ExtractTextSegments() | sealed |
Scenario1_FindClaimEnable() | sealed |
Scenario1_Geotag() | sealed |
Scenario1_GetAndSetPin() | sealed |
Scenario1_GetDeviceInformation() | sealed |
Scenario1_GetLamp() | sealed |
Scenario1_Launched() | sealed |
Scenario1_ListView() | sealed |
Scenario1_LongAndShortFormats() | sealed |
Scenario1_LowLatency() | sealed |
Scenario1_LowLatencyInput() | sealed |
Scenario1_Message() | sealed |
Scenario1_Metrics() | sealed |
Scenario1_Mini() | sealed |
Scenario1_OmnidirectionalSound() | sealed |
Scenario1_OpenDrawer() | sealed |
Scenario1_Orientation() | sealed |
Scenario1_PercentPermilleFormatting() | sealed |
Scenario1_Prefs() | sealed |
Scenario1_PreviewSettings() | sealed |
Scenario1_ReadData() | sealed |
Scenario1_ReadData() | sealed |
Scenario1_ReceiptPrinter() | sealed |
Scenario1_Render() | sealed |
Scenario1_Save() | sealed |
Scenario1_SelectDisplay() | sealed |
Scenario1_SetRecordProfile() | sealed |
Scenario1_Single() | sealed |
Scenario1_SingleFile() | sealed |
Scenario1_SpellingTextSuggestions() | sealed |
Scenario1_TrialMode() | sealed |
Scenario1_TrimAndSaveClip() | sealed |
Scenario1Basic() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2() | sealed |
Scenario2::GetTextboxSelectionRect(Windows::UI::Xaml::Controls::TextBox^textbox) | sealed | [private]
Scenario2_AamvaCards() | sealed |
Scenario2_AppendClips() | sealed |
Scenario2_CardioidSound() | sealed |
Scenario2_ChangePin() | sealed |
Scenario2_CloseDrawer() | sealed |
Scenario2_ConcurrentProfile() | sealed |
Scenario2_Connector() | sealed |
Scenario2_Custom() | sealed |
Scenario2_DecimalFormatting() | sealed |
Scenario2_DelayMini() | sealed |
Scenario2_DeviceWatcher() | sealed |
Scenario2_Disable() | sealed |
Scenario2_Display() | sealed |
Scenario2_DisplayText() | sealed |
Scenario2_DragUICustomization() | sealed |
Scenario2_EnableSettings() | sealed |
Scenario2_Extend() | sealed |
Scenario2_FindAvailableSourceGroups() | sealed |
Scenario2_GetCurrentTextSegmentFromIndex() | sealed |
Scenario2_History() | sealed |
Scenario2_History() | sealed |
Scenario2_Icons() | sealed |
Scenario2_InAppPurchase() | sealed |
Scenario2_Lang() | sealed |
Scenario2_Launch() | sealed |
Scenario2_Launch() | sealed |
Scenario2_Listen() | sealed |
Scenario2_Load() | sealed |
Scenario2_Manage() | sealed |
Scenario2_ManageAccount() | sealed |
Scenario2_MessageCaption() | sealed |
Scenario2_Msa() | sealed |
Scenario2_MultiFile() | sealed |
Scenario2_Multiple() | sealed |
Scenario2_oAuthFacebook() | sealed |
Scenario2_PhotoSettings() | sealed |
Scenario2_Polling() | sealed |
Scenario2_Polling() | sealed |
Scenario2_Polling() | sealed |
Scenario2_Polling() | sealed |
Scenario2_Polling() | sealed |
Scenario2_Polling() | sealed |
Scenario2_Polling() | sealed |
Scenario2_Polling() | sealed |
Scenario2_Polling() | sealed |
Scenario2_Polling() | sealed |
Scenario2_Polling() | sealed |
Scenario2_Prediction() | sealed |
Scenario2_PrintReceipt() | sealed |
Scenario2_Remove() | sealed |
Scenario2_RequestConsent() | sealed |
Scenario2_ScopedViews() | sealed |
Scenario2_ShakeEvents() | sealed |
Scenario2_Stats() | sealed |
Scenario2_StringTemplate() | sealed |
Scenario2_UniformSpacing() | sealed |
Scenario2_Upload() | sealed |
Scenario2_VideoChat() | sealed |
Scenario2StandardOptions() | sealed |
Scenario3() | sealed |
Scenario3() | sealed |
Scenario3() | sealed |
Scenario3() | sealed |
Scenario3() | sealed |
Scenario3() | sealed |
Scenario3() | sealed |
Scenario3() | sealed |
Scenario3() | sealed |
Scenario3() | sealed |
Scenario3() | sealed |
Scenario3() | sealed |
Scenario3() | sealed |
Scenario3_Aad() | sealed |
Scenario3_Add() | sealed |
Scenario3_AddAudioTracks() | sealed |
Scenario3_AspectRatio() | sealed |
Scenario3_AvailabilityChanged() | sealed |
Scenario3_BackgroundDeviceWatcher() | sealed |
Scenario3_Calibration() | sealed |
Scenario3_Calibration() | sealed |
Scenario3_Calibration() | sealed |
Scenario3_ChangeEvents() | sealed |
Scenario3_CredentialPickerOptions() | sealed |
Scenario3_CurrencyFormatting() | sealed |
Scenario3_CurrentStepCount() | sealed |
Scenario3_CustomDecay() | sealed |
Scenario3_CustomItems() | sealed |
Scenario3_DisplayOnOff() | sealed |
Scenario3_EnableHdrProfile() | sealed |
Scenario3_Enum() | sealed |
Scenario3_Events() | sealed |
Scenario3_FixAccount() | sealed |
Scenario3_Full() | sealed |
Scenario3_MultipleClaims() | sealed |
Scenario3_MultipleDrawers() | sealed |
Scenario3_Notifications() | sealed |
Scenario3_ParameterizedTemplate() | sealed |
Scenario3_Polling() | sealed |
Scenario3_Porting() | sealed |
Scenario3_ProportionalSpacing() | sealed |
Scenario3_Region() | sealed |
Scenario3_ResetPin() | sealed |
Scenario3_ReverseConversion() | sealed |
Scenario3_SingleFolder() | sealed |
Scenario3_StartDragAsync() | sealed |
Scenario3_Trim() | sealed |
Scenario3_UnmanagedConsumable() | sealed |
Scenario3_UsingWindows() | sealed |
Scenario3Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Scenario3CustomOptions() | sealed |
Scenario4() | sealed |
Scenario4() | sealed |
Scenario4() | sealed |
Scenario4() | sealed |
Scenario4() | sealed |
Scenario4() | sealed |
Scenario4() | sealed |
Scenario4() | sealed |
Scenario4::RecoButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Scenario4_AddOverlays() | sealed |
Scenario4_AddOverlays() | sealed |
Scenario4_BackgroundActivity() | sealed |
Scenario4_BackgroundProximitySensor() | sealed |
Scenario4_BackgroundTask() | sealed |
Scenario4_ChangeAdminKey() | sealed |
Scenario4_ChangeSystemGroup() | sealed |
Scenario4_CompletionGroups() | sealed |
Scenario4_ConsumableProduct() | sealed |
Scenario4_Control() | sealed |
Scenario4_Input() | sealed |
Scenario4_ManyProviders() | sealed |
Scenario4_NumberParsing() | sealed |
Scenario4_OrientationChanged() | sealed |
Scenario4_Override() | sealed |
Scenario4_Remove() | sealed |
Scenario4_SaveFile() | sealed |
Scenario4_Snapshot() | sealed |
Scenario4_UnicodeExtensions() | sealed |
Scenario4_UpdatingLineDisplayAttributes() | sealed |
Scenario4PageRange() | sealed |
Scenario5() | sealed |
Scenario5() | sealed |
Scenario5() | sealed |
Scenario5() | sealed |
Scenario5() | sealed |
Scenario5() | sealed |
Scenario5::nearbyStreetside(Windows::Devices::Geolocation::Geopoint^spaceNeedlePoint) | sealed | [private]
Scenario5::OnSizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
Scenario5_Clear() | sealed |
Scenario5_DataEventsBatching() | sealed |
Scenario5_DefiningCustomGlyphs() | sealed |
Scenario5_GetSingleDevice() | sealed |
Scenario5_IsSupported() | sealed |
Scenario5_ManyProvidersManyAccounts() | sealed |
Scenario5_Multiple() | sealed |
Scenario5_RandomAccess() | sealed |
Scenario5_RoundingAndPadding() | sealed |
Scenario5_TimeZone() | sealed |
Scenario5_TriggerCFU() | sealed |
Scenario5_UnicodeExtensions() | sealed |
Scenario5_UserCollection() | sealed |
Scenario5_VerifyResponse() | sealed |
Scenario5Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Scenario5Photos() | sealed |
Scenario6() | sealed |
Scenario6() | sealed |
Scenario6() | sealed |
Scenario6() | sealed |
Scenario6_AppListingURI() | sealed |
Scenario6_CustomFilterAddedProps() | sealed |
Scenario6_CustomProvider() | sealed |
Scenario6_DeleteTPMVSC() | sealed |
Scenario6_ManipulatingCursorAttributes() | sealed |
Scenario6_NumeralSystemTranslation() | sealed |
Scenario6_RecoverableErrors() | sealed |
Scenario6_Styling() | sealed |
Scenario6_TimeZone() | sealed |
Scenario6DisablePreview() | sealed |
Scenario7() | sealed |
Scenario7() | sealed |
Scenario7() | sealed |
Scenario7() | sealed |
Scenario7_B2B() | sealed |
Scenario7_CustomContent() | sealed |
Scenario7_DeviceInformationKind() | sealed |
Scenario7_DownloadReordering() | sealed |
Scenario7_DownloadReordering::IsWebException(Platform::String^title, Platform::Exception^ex, Windows::Networking::BackgroundTransfer::DownloadOperation^download=nullptr) | sealed | [private]
Scenario7_ListSmartCards() | sealed |
Scenario7_ScrollingContentUsingMarquee() | sealed |
Scenario7_UsingUnicodeExtensions() | sealed |
Scenario7Button_Show_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Scenario8() | sealed |
Scenario8() | sealed |
Scenario8() | sealed |
Scenario8() | sealed |
Scenario8::LanguageOverrideCombo_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
Scenario8_PairDevice() | sealed |
Scenario8_Reflow() | sealed |
Scenario8_Transmit() | sealed |
Scenario9() | sealed |
Scenario9() | sealed |
Scenario9() | sealed |
Scenario9_CustomPairDevice() | sealed |
Scenario_CloudFontOverview() | sealed |
Scenario_CloudFontOverview() | sealed |
Scenario_ContinuousDictation() | sealed |
Scenario_ContinuousRecognitionListGrammar() | sealed |
Scenario_ContinuousRecognitionSRGSGrammar() | sealed |
Scenario_Document1() | sealed |
Scenario_Document1() | sealed |
Scenario_Document2() | sealed |
Scenario_Document2() | sealed |
Scenario_Document3() | sealed |
Scenario_Document3() | sealed |
Scenario_ListConstraint() | sealed |
Scenario_PauseAsync() | sealed |
Scenario_PredefinedDictationGrammar() | sealed |
Scenario_PredefinedWebSearchGrammar() | sealed |
Scenario_SampleOverview() | sealed |
Scenario_SampleOverview() | sealed |
Scenario_SRGSConstraint() | sealed |
Scenario_SynthesizeSSML() | sealed |
Scenario_SynthesizeText() | sealed |
Scenario_SynthesizeTextBoundaries() | sealed |
ScenarioControl_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
ScenarioControl_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
ScenarioDisable() | sealed | [protected]
ScenarioDisable() | sealed | [protected]
ScenarioDisable() | sealed | [protected]
ScenarioDisable() | sealed | [protected]
ScenarioDisable() | sealed | [protected]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable() | sealed | [protected]
ScenarioDisable() | sealed | [protected]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioDisableReadingChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable() | sealed | [protected]
ScenarioEnable() | sealed | [protected]
ScenarioEnable() | sealed | [protected]
ScenarioEnable() | sealed | [protected]
ScenarioEnable() | sealed | [protected]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable() | sealed | [protected]
ScenarioEnable() | sealed | [protected]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnable(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEnableReadingChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEndReadButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioEndReadButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioGet(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioGetActivityHistory(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioGetCurrentActivity(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioGetData(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioGetData(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioGetData(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioOneStates enum name | sealed | [private]
ScenarioRegisterTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioRegisterTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioRegisterTask_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioStartReadButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioStartReadButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioType enum name | sealed | [private]
ScenarioUnregisterTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioUnregisterTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScenarioUnregisterTask_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ScrollViewer_ViewChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::ScrollViewerViewChangedEventArgs^args) | sealed | [private]
SDKTemplate::Scenario1_Advertiser::OnConnectionStatusChanged(Windows::Devices::WiFiDirect::WiFiDirectDevice^sender, Platform::Object^arg) | sealed | [private]
SearchButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SecondaryPage() | sealed |
secondVideoFile | sealed | [private]
SecureBootState_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SeekDownload_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [protected]
SelectButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SelectDeviceInList(Platform::String^deviceIdToSelect) | sealed | [private]
Selected enum value | sealed | [private]
selectedLayer | sealed | [private]
selectedStencilChangedToken | sealed | [private]
SelectFilesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SelectImageButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SelectImageButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SelectImageButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Selecting enum value | sealed | [private]
SelectingMode enum value | sealed | [private]
SelectingOrPasting enum value | sealed | [private]
SelectionSegmentButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SelectionSegmentsButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SelectItem(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | sealed | [private]
SelectLayer(Windows::UI::Xaml::Controls::Maps::MapElementsLayer^layer) | sealed | [private]
Selector | sealed |
SelectPreferredCameraStreamSettingAsync(Windows::Media::Capture::MediaStreamType mediaStreamType, VideoSettingsFilter^settingsFilterFunc) | sealed | [private]
SelectPreviouslySelectedItem(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | sealed | [private]
SendAsync() | sealed | [private]
SendAsync() | sealed | [private]
SendBooleanOutputReport_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^eventArgs) | sealed | [private]
SendBooleanOutputReportAsync(bool bitValue, uint8 buttonNumber) | sealed | [private]
SendDataLoop(Windows::Networking::Sockets::StreamWebSocket^activeSocket, Windows::Storage::Streams::IBuffer^sendBuffer, UINT32 bytesSentSoFar) | sealed | [private]
SendNumericOutputReport_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^eventArgs) | sealed | [private]
SendNumericOutputReportAsync(uint8 valueToWrite) | sealed | [private]
SendTextMessage() | sealed | [protected]
sensor | sealed | [private]
sensor | sealed | [private]
sensor | sealed | [private]
sensor | sealed | [private]
sensor | sealed | [private]
sensor | sealed | [private]
separatorQueue | sealed |
separatorQueueWidth | sealed |
ServiceViewModel() | sealed | [private]
ServiceViewModel::ResumeMeteringService(Object^, Object^) | sealed | [private]
ServiceViewModel::SuspendMeteringService(Object^, Windows::ApplicationModel::SuspendingEventArgs^) | sealed | [private]
ServicingCompleteTask() | sealed |
ServicingCompleteTask() | sealed |
session | sealed | [private]
SessionRevoked(Platform::Object^sender, Windows::ApplicationModel::ExtendedExecution::ExtendedExecutionRevokedEventArgs^args) | sealed | [private]
SessionRevoked(Platform::Object^sender, Windows::ApplicationModel::ExtendedExecution::ExtendedExecutionRevokedEventArgs^args) | sealed | [private]
SessionRevoked(Platform::Object^sender, Windows::ApplicationModel::ExtendedExecution::ExtendedExecutionRevokedEventArgs^args) | sealed | [private]
sessionRevokedToken | sealed | [private]
SET_PIN | sealed | [private]
SetAppLocalSettingsValue(Platform::String^key, Platform::Object^value) | sealed | [inline, private, static]
SetAppLocalSettingsValue(Platform::String^key, Platform::Object^value) | sealed | [inline, private, static]
SetBusy(bool value) | sealed | [private]
SetBusy(bool value) | sealed | [private]
SetBusy(bool value) | sealed | [private]
SetBusy(bool value) | sealed | [private]
SetCancelButton(bool isEnabled) | sealed | [private]
SetCancelButton(bool isEnabled) | sealed | [private]
SetCancelButton(bool isEnabled) | sealed | [private]
SetCanvasSize() | sealed | [private]
SetClaimedUI(CashDrawerInstance instance) | sealed | [private]
SetDefaultButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SetDefaultRecognizerByCurrentInputMethodLanguageTag() | sealed | [private]
SetDefaultStyleCombobox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
SetError(Platform::String^errorText) | sealed | [private]
SetErrorMessage() | sealed |
SetGeotagButton_Click() | sealed | [protected]
SetGeotagFromGeolocatorButton_Click() | sealed | [protected]
SetItemInvokedCallback(Windows::UI::Input::RadialControllerMenuItem^menuItem, unsigned int index) | sealed | [private]
SetLayoutWidth(float width) | sealed |
SetLedBlinkPattern_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SetLedBlinkPatternAsync(uint8 pattern) | sealed | [private]
SetLockScreenImage() | sealed |
SetMapProjection() | sealed | [private]
SetMapStyle() | sealed | [private]
SetMapStyleSheet() | sealed | [private]
SetMargins(Platform::String^marginsValue) | sealed | [private]
SetMinimumSize_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SetOutputFileButton(bool isEnabled) | sealed | [private]
SetOutputFileButton(bool isEnabled) | sealed | [private]
SetPasswordExplainVisibility(bool isShown) | sealed | [private]
SetPickFileButton(bool isEnabled) | sealed | [private]
SetPickFileButton(bool isEnabled) | sealed | [private]
SetPickFileButton(bool isEnabled) | sealed | [private]
setPin | sealed | [private]
SetPinHigh_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
SetPinLow_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
SetPreviewRotationAsync() | sealed | [private]
SetRecognizerByName(Platform::String^recognizerName) | sealed | [private]
SetReleasedUI(CashDrawerInstance instance) | sealed | [private]
SetResult(Windows::Security::Credentials::UI::CredentialPickerResults^res) | sealed | [private]
SetResult(Windows::Security::Credentials::UI::CredentialPickerResults^res) | sealed | [private]
SetResult(Windows::Security::Credentials::UI::CredentialPickerResults^res) | sealed | [private]
SetSamplePeriod(int rate) | sealed |
SetStyleSheetStateCombobox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SetTranscodeButton(bool isEnabled) | sealed | [private]
SetTranscodeButton(bool isEnabled) | sealed | [private]
SetTranscodeButton(bool isEnabled) | sealed | [private]
SetUpAccounts() | sealed | [private]
SetValuesFromLineDisplay() | sealed | [private]
shakeCounter | sealed | [private]
Shaken(Windows::Devices::Sensors::Accelerometer^sender, Windows::Devices::Sensors::AccelerometerShakenEventArgs^e) | sealed | [private]
shakenToken | sealed | [private]
ShareApplicationLink() | sealed |
ShareCustomData() | sealed |
ShareCustomProvider() | sealed |
ShareDelayRenderedFiles() | sealed |
sharedFlyout | sealed | [private]
ShareFiles() | sealed |
ShareHtml() | sealed |
ShareImage() | sealed |
ShareText() | sealed |
ShareWebLink() | sealed |
ShareWebView_NavigationCompleted(Platform::Object^sender, Windows::UI::Xaml::Controls::WebViewNavigationCompletedEventArgs^e) | sealed | [private]
ShowContactCard_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowContactCard_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowContactCard_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowContactCardWithOptions_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowContactCardWithPlacement_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowDevicePicker(bool pickSingle) | sealed | [private]
ShowDevicePickerButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowGuidance() | sealed | [private]
ShowGuidance() | sealed | [private]
ShowGuidance() | sealed | [private]
ShowGuidanceButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowGuidanceButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowGuidanceButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowListButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowPairingPanel(Platform::String^text, Windows::Devices::Enumeration::DevicePairingKinds pairingKind) | sealed | [private]
ShowPlaceholder(unsigned int count) | sealed |
ShowPrintUIAsync() | PrintHelper |
ShowPropertiesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowResults_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
ShowResults_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
ShowResults_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
ShowResults_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
ShowResults_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
ShowResults_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
ShowResults_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
ShowResults_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
ShowResults_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
showSpaceNeedleButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowStandardSystemOverlaysButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
showStreetSideNearSpaceneedle_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ShowText() | sealed |
ShowTrialPeriodInformation() | sealed |
SignalBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SignalBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SignIn() | sealed |
SignInPassportAsync(bool passportIsPrimaryLogin) | sealed | [private]
SignInPasswordAsync(bool calledFromPassport) | sealed | [private]
SimpleLogger(Windows::UI::Xaml::Controls::TextBlock^textBlock) | sealed | [inline]
SimpleLogger(Windows::UI::Xaml::Controls::TextBlock^textBlock) | sealed | [inline]
SingleSpace_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
SkeletalFrameRenderer() | sealed |
Sleep(int time) | sealed | [private]
Slider_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
slider_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
sliderEnabled | sealed | [private]
sliders | sealed | [private]
sliderValue | sealed | [private]
SlowPhasing_Checked(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SlowPhasing_UnChecked(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
smartCardItems | sealed | [private]
SocketReaderWriter(Windows::Networking::Sockets::StreamSocket^socket, SDKTemplate::MainPage^mainPage) | sealed | [inline]
socketRW | sealed | [private]
SourceComboBox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
SourceGrid_DragStarting(Windows::UI::Xaml::UIElement^sender, Windows::UI::Xaml::DragStartingEventArgs^args) | sealed | [private]
SourceGroup | sealed |
SourceGroupCollection(Windows::UI::Core::CoreDispatcher^uiDispatcher) | sealed |
SourceInfo | sealed |
SourceInfos | sealed |
SourceListView_DragItemsStarting(Platform::Object^sender, Windows::UI::Xaml::Controls::DragItemsStartingEventArgs^e) | sealed | [private]
SourcePositionX_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
SourcePositionX_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
SourcePositionY_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
SourcePositionY_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
SourcePositionZ_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
SourcePositionZ_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
sourceRotation | sealed | [private]
SourceTextBlock_DragStarting(Windows::UI::Xaml::UIElement^sender, Windows::UI::Xaml::DragStartingEventArgs^args) | sealed | [private]
SourceTextBlock_PointerMoved(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | sealed | [private]
Speak_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Speak_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
Speak_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SpecificHistory_Checked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
speechContext | sealed | [private]
speechRecognizer | sealed | [private]
SpeechRecognizer_HypothesisGenerated(Windows::Media::SpeechRecognition::SpeechRecognizer^sender, Windows::Media::SpeechRecognition::SpeechRecognitionHypothesisGeneratedEventArgs^args) | sealed | [private]
SpeechRecognizer_StateChanged(Windows::Media::SpeechRecognition::SpeechRecognizer^sender, Windows::Media::SpeechRecognition::SpeechRecognizerStateChangedEventArgs^args) | sealed | [private]
SpeechRecognizer_StateChanged(Windows::Media::SpeechRecognition::SpeechRecognizer^sender, Windows::Media::SpeechRecognition::SpeechRecognizerStateChangedEventArgs^args) | sealed | [private]
SpeechRecognizer_StateChanged(Windows::Media::SpeechRecognition::SpeechRecognizer^sender, Windows::Media::SpeechRecognition::SpeechRecognizerStateChangedEventArgs^args) | sealed | [private]
SpeechRecognizer_StateChanged(Windows::Media::SpeechRecognition::SpeechRecognizer^sender, Windows::Media::SpeechRecognition::SpeechRecognizerStateChangedEventArgs^args) | sealed | [private]
SpeechRecognizer_StateChanged(Windows::Media::SpeechRecognition::SpeechRecognizer^sender, Windows::Media::SpeechRecognition::SpeechRecognizerStateChangedEventArgs^args) | sealed | [private]
SpeechRecognizer_StateChanged(Windows::Media::SpeechRecognition::SpeechRecognizer^sender, Windows::Media::SpeechRecognition::SpeechRecognizerStateChangedEventArgs^args) | sealed | [private]
SpeechRecognizer_StateChanged(Windows::Media::SpeechRecognition::SpeechRecognizer^sender, Windows::Media::SpeechRecognition::SpeechRecognizerStateChangedEventArgs^args) | sealed | [private]
SpeechRecognizer_StateChanged(Windows::Media::SpeechRecognition::SpeechRecognizer^sender, Windows::Media::SpeechRecognition::SpeechRecognizerStateChangedEventArgs^args) | sealed | [private]
speechResourceMap | sealed | [private]
srwSingletonCreationLock | sealed | [private, static]
StandardOptionsPrintHelper(Page^scenarioPage) | sealed | [inline]
Start(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance) | sealed | [static]
StartAsync() | sealed | [private]
StartButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
startButtonEnabled | sealed | [private]
StartCameraAsync() | sealed | [private]
StartDeviceWatcher(void) | sealed | [private]
StartDeviceWatchers(void) | sealed | [private]
StartDownload(Windows::Networking::BackgroundTransfer::BackgroundTransferPriority priority) | sealed | [private]
StartDownload(Windows::Storage::StorageFile^destinationFile, Windows::Networking::BackgroundTransfer::BackgroundDownloader^downloader, Windows::Foundation::Uri^source) | sealed | [private]
StartDownload_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartDownload_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [protected]
StartDownload_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [protected]
StartDownload_Click(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartDownloadAndReadContentsAsync() | sealed | [private]
StartDownloadsButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartHandlingAppEvents(void) | sealed | [private]
StartHighPriorityDownload_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartInterruptMessageWorker(Windows::Devices::Custom::CustomDevice^fx2Device) | sealed | [private]
StartLocationTrackingAsync() | sealed | [private]
StartLogging() | sealed |
StartLogging() | sealed |
StartMetering(int sampleRate) | sealed |
StartMultipartUpload_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartPreviewAsync() | sealed | [private]
StartProcessingDataVirtualizationScrollOffsets(double actualHeight) | sealed | [private]
StartReaderAsync() | sealed | [private]
StartReceiveData(Windows::Networking::Sockets::StreamWebSocket^activeSocket) | sealed | [private]
StartRecordingAsync(Windows::Media::MediaProperties::MediaEncodingProfile^mediaEncodingProfile) | sealed | [private]
StartRecordingToCustomSink() | sealed | [private]
StartRecordingToCustomSinkAsync() | sealed | [private]
StartScenario() | sealed | [private]
StartScenario() | sealed | [private]
StartScenarioAsync() | sealed | [private]
StartScenarioAsync() | sealed | [private]
StartScrollingButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartSendData(Windows::Networking::Sockets::StreamWebSocket^activeSocket) | sealed | [private]
StartSensorBackgroundTaskAsync(Platform::String^deviceId) | sealed | [private]
StartStopScenario_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
StartStopScenario_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
StartStopScenario_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
StartStopScenario_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed |
StartStrokeSelection(Windows::Foundation::Point position) | sealed | [private]
StartSuperMuttInputReports(void) | sealed | [private]
startTime | sealed | [private]
StartUpload_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartWatcher() | sealed | [private]
StartWatcher() | sealed | [private]
StartWatcher(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher) | sealed |
StartWatcher() | sealed | [private]
StartWatcher() | sealed | [private]
StartWatcher() | sealed | [private]
StartWatcher() | sealed | [private]
StartWatcher() | sealed | [private]
StartWatcherButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartWatcherButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartWatcherButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartWatcherButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartWatcherButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartWatcherButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StartWatchers() | sealed | [private]
stateChangedToken | sealed | [private]
statusUpdatedToken | sealed | [private]
stencilButtonCheckedChangedToken | sealed | [private]
stepCount | sealed | [private]
stepCountGoalOffset | sealed | [private, static]
stepGoal | sealed | [private]
stepKind | sealed |
stepsCount | sealed |
stepsDuration | sealed |
StopAllScrollingAsync() | sealed | [private]
StopAnimationTapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | sealed | [private]
StopAsync() | sealed | [private]
StopButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StopButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StopButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StopButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
stopButtonEnabled | sealed | [private]
StopDeviceWatcher(void) | sealed | [private]
StopDeviceWatchers(void) | sealed | [private]
StopHandlingAppEvents(void) | sealed | [private]
StopMetering() | sealed |
stopMeteringRequested | sealed | [private]
StopPlayers() | sealed | [private]
StopPlayers() | sealed | [private]
StopPlayers() | sealed | [private]
StopPreviewAsync() | sealed | [private]
StopReaderAsync() | sealed | [private]
StopRecordingAsync() | sealed | [private]
StopReplay() | sealed | [private]
StopScenario() | sealed | [private]
StopScenario() | sealed | [private]
StopScenario() | sealed | [private]
StopScenario() | sealed | [private]
StopScrollingButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StopSuperMuttInputReports(void) | sealed | [private]
StopWatcher() | sealed |
StopWatcher() | sealed | [private]
StopWatcher() | sealed | [private]
StopWatcher() | sealed | [private]
StopWatcher() | sealed | [private]
StopWatcher() | sealed | [private]
StopWatcher() | sealed | [private]
StopWatcherButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StopWatcherButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StopWatcherButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StopWatcherButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StopWatcherButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StopWatcherButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StopWatchers(bool reset=false) | sealed | [private]
storageItemAccessList | sealed | [private]
storageItems | sealed | [private]
storeContext | sealed | [private]
STORED_ACCOUNT_AUTHORITY | sealed | [private]
STORED_ACCOUNT_ID_KEY | sealed | [private]
STORED_AUTHORITY_ID_KEY | sealed | [private]
STORED_PROVIDER_ID_KEY | sealed | [private]
storeId | sealed |
streaming enum value | sealed | [private]
streaming_latencyModeToggled() | sealed | [private]
streaming_previewButtonClicked() | sealed | [private]
streaming_recordingStarted() | sealed | [private]
StreamResolutionHelper(Windows::Media::MediaProperties::IMediaEncodingProperties^encodingProperties) | sealed |
streamWebSocket | sealed | [private]
StringFromDouble(double) | sealed | [private]
strokeBuilder | sealed | [private]
StrokeEvent_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
StrokeInput_StrokeStarted(Windows::UI::Input::Inking::InkStrokeInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
strokesToReplay | sealed | [private]
styleCombobox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^e) | sealed | [private]
SuccessfulSignIn(Account^account) | sealed | [private]
supportedCursorTypes | sealed | [private]
SUPPRESS_DURATION_APPROXIMATE_TICKS | sealed | [private, static]
SUPPRESS_DURATION_UNRELIABLE_TICKS | sealed | [private, static]
suspendDeferral | sealed | [private]
suspendingToken | sealed | [private]
Swap(T &v1, T &v2) | sealed | [private, static]
switchChangedEventsHandler | sealed | [private]
SymbologyListEntry(UINT symbologyId) | sealed | [inline]
SymbologyListEntry(UINT symbologyId, bool symbologyEnabled) | sealed | [inline]
synthesisStream | sealed | [private]
synthesizer | sealed | [private]
SynthesizeSSMLStream() | sealed | [private]
SynthesizeTextStream() | sealed | [private]
SystemGroup_Frequent_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SystemGroup_None_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
SystemGroup_Recent_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
target_DoubleTapped(Platform::Object^sender, Windows::UI::Xaml::Input::DoubleTappedRoutedEventArgs^e) | sealed | [private]
target_Holding(Platform::Object^sender, Windows::UI::Xaml::Input::HoldingRoutedEventArgs^e) | sealed | [private]
target_PointerEntered(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | sealed | [private]
target_PointerExited(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | sealed | [private]
target_PointerPressed(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | sealed | [private]
target_PointerReleased(Platform::Object^sender, Windows::UI::Xaml::Input::PointerRoutedEventArgs^e) | sealed | [private]
target_RightTapped(Platform::Object^sender, Windows::UI::Xaml::Input::RightTappedRoutedEventArgs^e) | sealed | [private]
target_Tapped(Platform::Object^sender, Windows::UI::Xaml::Input::TappedRoutedEventArgs^e) | sealed | [private]
TargetListView_DragItemsCompleted(Windows::UI::Xaml::Controls::ListViewBase^sender, Windows::UI::Xaml::Controls::DragItemsCompletedEventArgs^args) | sealed | [private]
TargetListView_DragItemsStarting(Platform::Object^sender, Windows::UI::Xaml::Controls::DragItemsStartingEventArgs^e) | sealed | [private]
TargetListView_DragOver(Platform::Object^sender, Windows::UI::Xaml::DragEventArgs^e) | sealed | [private]
TargetListView_Drop(Platform::Object^sender, Windows::UI::Xaml::DragEventArgs^e) | sealed | [private]
TargetTextBlock_DragEnter(Platform::Object^sender, Windows::UI::Xaml::DragEventArgs^e) | sealed | [private]
TargetTextBlock_Drop(Platform::Object^sender, Windows::UI::Xaml::DragEventArgs^e) | sealed | [private]
TargetTextBox_DragEnter(Platform::Object^sender, Windows::UI::Xaml::DragEventArgs^e) | sealed | [private]
TargetTextBox_DragLeave(Platform::Object^sender, Windows::UI::Xaml::DragEventArgs^e) | sealed | [private]
TargetTextBox_Drop(Platform::Object^sender, Windows::UI::Xaml::DragEventArgs^e) | sealed | [private]
taskCount | sealed | [private]
TaskDeferral | sealed | [private]
TaskInstance | sealed | [private]
taskRegistration | sealed | [private]
Templates() | sealed |
tenMinutesIn100NanoSecondUnits | sealed | [private, static]
TextColor(Windows::UI::Color c) | sealed | [static]
TextContentBlock | sealed |
TextLayoutFrame_SizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
TextLayoutFrame_SizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
TextLayoutFrame_SizeChanged(Platform::Object^sender, Windows::UI::Xaml::SizeChangedEventArgs^e) | sealed | [private]
textServiceManager | sealed | [private]
TextServiceManager_InputLanguageChanged(Windows::UI::Text::Core::CoreTextServicesManager^sender, Platform::Object^args) | sealed | [private]
Tile enum value | sealed | [private]
TileNotificationButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
timedMetadataTrackChangedHandler(Windows::Media::Playback::MediaPlaybackItem^mediaPlaybackItem, Windows::Foundation::Collections::IVectorChangedEventArgs^args) | sealed | [private]
timer | sealed | [private]
Timer_Tick(Platform::Object^sender, Platform::Object^e) | sealed | [private]
Timer_Tick(Platform::Object^sender, Platform::Object^e) | sealed | [private]
Timer_Tick(Platform::Object^sender, Platform::Object^e) | sealed | [private]
timerToken | sealed | [private]
TimeTriggeredTask() | sealed |
TimeTriggeredTask() | sealed |
Title | sealed |
titleBar | sealed | [private]
Toast enum value | sealed | [private]
ToastNotificationButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ToCustomStyleEntryState(MapIconState state) | sealed | [private, static]
ToDefaultStyleEntryState(MapIconState state) | sealed | [private, static]
Toggle_Custom(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ToggleDepth_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ToggleFullScreenModeButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ToggleFullScreenModeButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ToggleLogs(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ToggleMenuSuppression(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^args) | sealed | [private]
toggles | sealed | [private]
ToggleSkeletons_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ToHex(byte value) | sealed | [private]
token | sealed | [private]
TongueButton_Click(_In_ Platform::Object^sender, _In_ Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ToolButton_Lasso(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
totalCumulativeSteps | sealed | [private]
totalNumberBytesReceived | sealed | [private]
TouchInking_Checked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TouchInking_Unchecked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TouchInkingCheckBox_Checked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TouchInkingCheckBox_Unchecked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TouchWriting | sealed |
TrafficFlowVisible_Checked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
trafficFlowVisibleCheckBox_Unchecked(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TranscodeCancel(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TranscodeCancel(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TranscodeCancel(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TranscodeCustom(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TranscodeError(Platform::String^error) | sealed | [private]
TranscodeError(Platform::String^error) | sealed | [private]
TranscodeError(Platform::String^error) | sealed | [private]
TranscodeFailure(Windows::Media::Transcoding::TranscodeFailureReason reason) | sealed | [private]
TranscodeFailure(Windows::Media::Transcoding::TranscodeFailureReason reason) | sealed | [private]
TranscodeFailure(Windows::Media::Transcoding::TranscodeFailureReason reason) | sealed | [private]
TranscodePreset(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TranscodeProgress(Windows::Foundation::IAsyncActionWithProgress< double >^asyncInfo, double percent) | sealed | [private]
TranscodeProgress(Windows::Foundation::IAsyncActionWithProgress< double >^asyncInfo, double percent) | sealed | [private]
TranscodeProgress(Windows::Foundation::IAsyncActionWithProgress< double >^asyncInfo, double percent) | sealed | [private]
TranscodeTrim(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TransferData(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TransformBitmap(Windows::Graphics::Imaging::SoftwareBitmap^inputBitmap, TransformScanline pixelTransformation) | sealed | [private, static]
transforms | sealed | [private]
Transmit_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
trigger | sealed | [private]
TrimClip_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
TryCreateDownloadAsync(Windows::Networking::BackgroundTransfer::BackgroundDownloader^downloader, UINT8 delaySeconds, Platform::String^fileNameSuffix, ScenarioType type, Platform::Collections::Vector< Windows::Networking::BackgroundTransfer::DownloadOperation^>^downloadOperations, Concurrency::task< void > &resultTask) | sealed | [private]
TryInitializeCaptureAsync() | sealed | [private]
TryInitializeMediaCaptureAsync(Windows::Media::Capture::Frames::MediaFrameSourceGroup^group) | sealed | [private]
TryInitializeMediaCaptureAsync(Windows::Media::Capture::Frames::MediaFrameSourceGroup^group) | sealed | [private]
UndeferElementClick(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
uninitialized enum value | sealed | [private]
unknownStepCount | sealed | [private]
UnlockScenarioChange() | sealed | [private]
UnlockScenarioChange() | sealed | [private]
UnpairButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnpairButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnprocessedEvent_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnprocessedInput_PointerEntered(Windows::UI::Input::Inking::InkUnprocessedInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
UnprocessedInput_PointerEntered1(Windows::UI::Input::Inking::InkUnprocessedInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
UnprocessedInput_PointerMoved(Windows::UI::Input::Inking::InkUnprocessedInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
UnprocessedInput_PointerPressed(Windows::UI::Input::Inking::InkUnprocessedInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
UnprocessedInput_PointerReleased(Windows::UI::Input::Inking::InkUnprocessedInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
UnprocessedInputOnPointerEntered(Windows::UI::Input::Inking::InkUnprocessedInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
UnprocessedInputOnPointerExited(Windows::UI::Input::Inking::InkUnprocessedInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
UnprocessedInputOnPointerHovered(Windows::UI::Input::Inking::InkUnprocessedInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
UnprocessedInputOnPointerLost(Windows::UI::Input::Inking::InkUnprocessedInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
UnprocessedInputOnPointerMoved(Windows::UI::Input::Inking::InkUnprocessedInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
UnprocessedInputOnPointerPressed(Windows::UI::Input::Inking::InkUnprocessedInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
UnprocessedInputOnPointerReleased(Windows::UI::Input::Inking::InkUnprocessedInput^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterBackgroundTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterBackgroundTask(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^taskReg) | sealed | [private]
UnRegisterBtn_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterCustomTrigger_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterForPrinting() | PrintHelper |
UnregisterFromAppEvents(void) | sealed | [private]
UnregisterFromDeviceAccessStatusChange() | sealed | [private]
UnregisterFromDeviceWatcherEvents(void) | sealed | [private]
UnregisterFromInputReportEvent(void) | sealed | [private]
UnregisterFromInputReportEvents_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^eventArgs) | sealed | [private]
UnregisterGroupedTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterGroupedTask(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterTask() | sealed | [private]
UnregisterUngroupedTasks(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnregisterUngroupedTasks(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UnspecifiedReason() | sealed |
UpdateAvailableLanguages() | sealed | [private]
UpdateButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UpdateButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UpdateButtons() | sealed | [private]
UpdateButtons() | sealed | [private]
UpdateButtonStateAsync() | sealed | [private]
UpdateColors() | sealed | [private]
UpdateConnectDisconnectButtonsAndList(bool enableConnectButton) | sealed | [private]
UpdateContent() | sealed | [private]
UpdateContent() | sealed | [private]
UpdateContent() | sealed | [private]
UpdateContent() | sealed | [private]
UpdateControls() | sealed | [private]
UpdateControls() | sealed | [private]
UpdateControls() | sealed | [private]
UpdateCurrentAppLanguageMessage() | sealed | [private]
UpdateEventRegistration(bool registerForEvents) | sealed | [private]
UpdateFrameSource() | sealed | [private]
UpdateFullScreenModeStatus() | sealed | [private]
UpdateGlyphBitmapImage() | sealed | [private]
UpdateHeaderText() | sealed | [private]
UpdateLayoutMetrics() | sealed | [private]
UpdateLocalClientWindow() | sealed | [private]
UpdateMapElementOnClick(Windows::UI::Xaml::Controls::Maps::MapElement^mapElement, MapIconStateToStyleEntryState toStyleEntryState) | sealed | [private, static]
UpdateMapElementOnPointerEntered(Windows::UI::Xaml::Controls::Maps::MapElement^mapElement, MapIconStateToStyleEntryState toStyleEntryState) | sealed | [private, static]
UpdateMapElementOnPointerExited(Windows::UI::Xaml::Controls::Maps::MapElement^mapElement, MapIconStateToStyleEntryState toStyleEntryState) | sealed | [private, static]
UpdateMessageLog(LogEventAction action) | sealed | [private]
UpdateName_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UpdatePairingButtons() | sealed | [private]
UpdatePairingButtons() | sealed | [private]
UpdatePositionAndVisibility() | sealed | [private]
UpdatePropertyHelper(Platform::String^itemKey, Platform::String^propertyKey, Platform::String^propertyName, Platform::Object^newValue) | sealed | [private]
UpdateProps(Rect boundingBox) | sealed | [private]
UpdateRegisterButton() | sealed | [private]
UpdateRegisterEventButtons(void) | sealed | [private]
UpdateRunningAverageContainerHeight(Windows::UI::Xaml::Controls::ListViewBase^sender, Windows::UI::Xaml::Controls::ContainerContentChangingEventArgs^args) | sealed | [private]
UpdateRunningAverageContainerHeightHandler | sealed | [private]
UpdateScalingAndOrder() | sealed | [private]
UpdateSSMLText() | sealed | [private]
UpdateStartStopButtons(void) | sealed | [private]
UpdateStatus | sealed |
UpdateStatus() | sealed | [private]
UpdateStatusOutput(Windows::Devices::PointOfService::CashDrawerStatusKind status) | sealed | [private]
UpdateSwitchStateTable(Platform::Array< bool >^SwitchStateArray) | sealed | [private]
UpdateTextLayout() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUI() | sealed | [private]
UpdateUIAsync(Platform::String^status) | sealed | [private]
UpdateUIAsync(Platform::String^status) | sealed | [private]
UpdateUIAsync(Platform::String^status) | sealed | [private]
UpdateValuesClick(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UpdateValuesClick(Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UpdateValuesClick(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UpdateValuesClick(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UpdateVisualState() | sealed | [private]
UpdateVisualState() | sealed | [private]
UpdateVisualState() | sealed | [private]
UpdateVisualState() | sealed | [private]
UpdateWordBoxTransform() | sealed | [private]
UpdateWordBoxTransform() | sealed | [private]
UploadMultipleFilesAsync(Windows::Foundation::Uri^uri, Windows::Foundation::Collections::IVectorView< Windows::Storage::StorageFile^>^files) | sealed | [private]
UploadProgress(Windows::Foundation::IAsyncOperationWithProgress< Windows::Networking::BackgroundTransfer::UploadOperation^, Windows::Networking::BackgroundTransfer::UploadOperation^>^operation, Windows::Networking::BackgroundTransfer::UploadOperation^) | sealed | [private]
UploadSingleFileAsync(Windows::Foundation::Uri^uri, Windows::Storage::IStorageFile^file) | sealed | [private]
urls | sealed | [private]
UseCustomColors_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs e) | sealed | [inline, private]
UseInertia(bool inertia) | sealed |
UseMinimalOverlaysCheckBox_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
UserDataAccountViewModel(Windows::ApplicationModel::UserDataAccounts::UserDataAccount^account) | sealed | [inline]
UserLanguageToggle_Toggled(Platform::Object^sender, RoutedEventArgs^e) | sealed | [private]
UserSelect() | sealed |
UsesPassport | sealed |
ValidateAndGetUri(Platform::String^uriString) | sealed | [private]
ValidatePageRangeOption(Windows::Graphics::Printing::OptionDetails::PrintPageRangeOptionDetails^pageRangeOption) | sealed | [protected]
verifyButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
VerifyResponse_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
VersionString(Windows::ApplicationModel::PackageVersion version) | sealed | [private]
verticalScrollableWindow | sealed | [private]
VIDEO_ENCODING_STRING | sealed | [private]
VideoButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
VideoPlaybackErrorHandler(Platform::Object^sender, Windows::UI::Xaml::ExceptionRoutedEventArgs^e) | sealed | [private]
VideoSettings_Changed(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
ViewModel | sealed |
ViewPage() | sealed |
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
VisibilityChanged(Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [protected]
VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
visibilityToken | sealed | [private]
WaitForDrawerCloseButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
waiting enum value | sealed | [private]
waiting_previewButtonClicked() | sealed | [private]
walkingStepCount | sealed | [private]
watcher | sealed | [private]
Watcher_Added(Windows::Devices::Enumeration::DeviceWatcher^watcher, Windows::Devices::Enumeration::DeviceInformation^deviceInformation) | sealed | [private]
Watcher_DeviceAdded(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher, Windows::Devices::Enumeration::DeviceInformation^deviceInfo) | sealed | [private]
Watcher_DeviceRemoved(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher, Windows::Devices::Enumeration::DeviceInformationUpdate^deviceInfoUpdate) | sealed | [private]
Watcher_DeviceUpdated(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher, Windows::Devices::Enumeration::DeviceInformationUpdate^deviceInfoUpdate) | sealed | [private]
Watcher_EnumerationCompleted(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher, Platform::Object^e) | sealed | [private]
Watcher_EnumerationCompleted(Windows::Devices::Enumeration::DeviceWatcher^watcher, Platform::Object^e) | sealed | [private]
Watcher_Stopped(Windows::Devices::Enumeration::DeviceWatcher^deviceWatcher, Platform::Object^e) | sealed | [private]
watchersStarted | sealed | [private]
watchersSuspended | sealed | [private]
watcherStarted | sealed | [private]
watcherSuspended | sealed | [private]
WebAccountCommandInvoked(Windows::UI::ApplicationSettings::WebAccountCommand^command, Windows::UI::ApplicationSettings::WebAccountInvokedArgs^args) | sealed | [private]
WebAccountCommandInvoked(Windows::UI::ApplicationSettings::WebAccountCommand^command, Windows::UI::ApplicationSettings::WebAccountInvokedArgs^args) | sealed | [private]
WebAccountCommandInvoked(Windows::UI::ApplicationSettings::WebAccountCommand^command, Windows::UI::ApplicationSettings::WebAccountInvokedArgs^args) | sealed | [private]
WebAccountCommandInvoked(Windows::UI::ApplicationSettings::WebAccountCommand^command, Windows::UI::ApplicationSettings::WebAccountInvokedArgs^args) | sealed | [private]
WebAccountCommandInvoked(Windows::UI::ApplicationSettings::WebAccountCommand^command, Windows::UI::ApplicationSettings::WebAccountInvokedArgs^args) | sealed | [private]
WebAccountProviderCommandInvoked(Windows::UI::ApplicationSettings::WebAccountProviderCommand^command) | sealed | [private]
WebAccountProviderCommandInvoked(Windows::UI::ApplicationSettings::WebAccountProviderCommand^command) | sealed | [private]
WebAccountProviderCommandInvoked(Windows::UI::ApplicationSettings::WebAccountProviderCommand^command) | sealed | [private]
WebAccountProviderCommandInvoked(Windows::UI::ApplicationSettings::WebAccountProviderCommand^command) | sealed | [private]
WebAccountProviderCommandInvoked(Windows::UI::ApplicationSettings::WebAccountProviderCommand^command) | sealed | [private]
wfdDevice | sealed | [private]
Width() | sealed |
Window_VisibilityChanged(Platform::Object^sender, Windows::UI::Core::VisibilityChangedEventArgs^e) | sealed | [private]
windowList | sealed | [private]
windowResizeToken | sealed | [private]
windowSizeChangedToken | sealed | [private]
windowVisible | sealed | [private]
word | sealed | [private]
wordBoxes | sealed | [private]
wordHeight | sealed | [private]
WordOverlay(OcrWord^ocrWord) | sealed |
wordPosition | sealed | [private]
WordSegmentButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
WordSegmentsButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
wordWidth | sealed | [private]
WriteBlock_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
WriteBytesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
writeCounter | sealed | [private]
WriteMessage(Platform::String^message) | sealed |
WriteReadStream() | sealed |
WriteTextButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
WriteToFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
WriteToFileWithExplicitCFUButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
WriteToStreamButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
xamlGestureRecognizer | sealed | [private]
YawSlider_ValueChanged(Platform::Object^sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^e) | sealed | [private]
YellowButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
yesButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
~Conversation() | sealed | [inline, virtual]
~DirectXPage() | sealed | [virtual]
~DocumentPresenter() | sealed | [virtual]
~EventHandlerForDevice() | sealed | [private]
~FileLoggingSessionScenario() | sealed | [private]
~LoggingSessionScenario() | sealed | [private]
~Scenario1_DeviceUse() | sealed | [virtual]
~Scenario1_Download() | sealed | [private]
~Scenario1_LowLatencyInput() | sealed | [virtual]
~Scenario1_OmnidirectionalSound() | sealed | [virtual]
~Scenario1_PreviewSettings() | sealed | [virtual]
~Scenario2_CardioidSound() | sealed | [virtual]
~Scenario2_PhotoSettings() | sealed | [virtual]
~Scenario2_Upload() | sealed | [private]
~Scenario3_AspectRatio() | sealed | [virtual]
~Scenario3_CustomDecay() | sealed | [virtual]
~Scenario3_Notifications() | sealed | [private]
~SourceGroupCollection() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:24:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VertexPositionTex Member List

This is the complete list of members for VertexPositionTex, including all inherited members.
pos | VertexPositionTex
tex | VertexPositionTex
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContextMenu/cpp/pch.h Source File

  • ContextMenu
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Audio/AudioFileReader.cpp Source File

  • HolographicVoiceInput
  • cpp
  • Audio

AudioFileReader.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012
00013 #include "AudioFileReader.h"
00014
00015 using namespace Concurrency;
00016 using namespace Microsoft::WRL;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Media::SpeechSynthesis;
00019 using namespace Windows::Storage::Streams;
00020
00021 _Use_decl_annotations_
00022 HRESULT AudioFileReader::Initialize(LPCWSTR filename)
00023 {
00024     BOOL mfStarted = FALSE;
00025     auto hr = MFStartup(MF_VERSION);
00026     mfStarted = SUCCEEDED(hr);
00027
00028     ComPtr<IMFSourceReader> reader;
00029     if (SUCCEEDED(hr))
00030     {
00031         hr = MFCreateSourceReaderFromURL(filename, nullptr, &reader);
00032     }
00033
00034     // Select the first audio stream, and deselect all other streams.
00035     if (SUCCEEDED(hr))
00036     {
00037         hr = reader->SetStreamSelection(static_cast<DWORD>(MF_SOURCE_READER_ALL_STREAMS), FALSE);
00038     }
00039
00040     if (SUCCEEDED(hr))
00041     {
00042         hr = reader->SetStreamSelection(static_cast<DWORD>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), TRUE);
00043     }
00044
00045     // Create a partial media type that specifies uncompressed PCM audio.
00046     ComPtr<IMFMediaType> partialType;
00047     if (SUCCEEDED(hr))
00048     {
00049         hr = MFCreateMediaType(&partialType);
00050     }
00051
00052     if (SUCCEEDED(hr))
00053     {
00054         hr = partialType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio);
00055     }
00056
00057     if (SUCCEEDED(hr))
00058     {
00059         hr = partialType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM);
00060     }
00061
00062     // Set this type on the source reader. The source reader will load the necessary decoder.
00063     if (SUCCEEDED(hr))
00064     {
00065         hr = reader->SetCurrentMediaType(static_cast<DWORD>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), nullptr, partialType.Get());
00066     }
00067
00068     // Get the complete uncompressed format
00069     ComPtr<IMFMediaType> uncompressedAudioType;
00070     if (SUCCEEDED(hr))
00071     {
00072         hr = reader->GetCurrentMediaType(static_cast<DWORD>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), &uncompressedAudioType);
00073     }
00074
00075     // Ensure the stream is selected.
00076     if (SUCCEEDED(hr))
00077     {
00078         hr = reader->SetStreamSelection(static_cast<DWORD>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), TRUE);
00079     }
00080
00081     // Get the audio block size and number of bytes/second from the audio format.
00082     if (SUCCEEDED(hr))
00083     {
00084         WAVEFORMATEX* format = nullptr;
00085         UINT32 size = 0;
00086         hr = MFCreateWaveFormatExFromMFMediaType(uncompressedAudioType.Get(), &format, &size);
00087
00088         // Only mono PCM files are supported for HRTF processing
00089         if (SUCCEEDED(hr) && format->wFormatTag != WAVE_FORMAT_PCM && format->nChannels != 1)
00090         {
00091             hr = E_INVALIDARG;
00092         }
00093
00094         if (SUCCEEDED(hr))
00095         {
00096             CopyMemory(&_format, format, sizeof WAVEFORMATEX);
00097         }
00098
00099         if (format)
00100         {
00101             CoTaskMemFree(format);
00102         }
00103     }
00104
00105     // Get audio samples from the source reader.
00106     _audioData.resize(0);
00107     while (SUCCEEDED(hr))
00108     {
00109         DWORD dwFlags = 0;
00110
00111         // Read the next sample.
00112         ComPtr<IMFSample> sample;
00113         hr = reader->ReadSample(static_cast<DWORD>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), 0, nullptr, &dwFlags, nullptr, &sample);
00114
00115         if (SUCCEEDED(hr) && (dwFlags & MF_SOURCE_READERF_ENDOFSTREAM) != 0)
00116         {
00117             // End of stream
00118             break;
00119         }
00120
00121         if (SUCCEEDED(hr) && sample == nullptr)
00122         {
00123             // No sample, keep going
00124             continue;
00125         }
00126
00127         // Get a pointer to the audio data in the sample.
00128         ComPtr<IMFMediaBuffer> buffer;
00129         if (SUCCEEDED(hr))
00130         {
00131             hr = sample->ConvertToContiguousBuffer(&buffer);
00132         }
00133
00134         DWORD bufferSize = 0;
00135         if (SUCCEEDED(hr))
00136         {
00137             BYTE* data;
00138             hr = buffer->Lock(&data, nullptr, &bufferSize);
00139
00140             auto currentDataSize = _audioData.size();
00141             if (SUCCEEDED(hr))
00142             {
00143                 _audioData.resize(currentDataSize + bufferSize);
00144             }
00145
00146             if (SUCCEEDED(hr))
00147             {
00148                 CopyMemory(_audioData.data() + currentDataSize, data, bufferSize);
00149                 // Unlock the buffer
00150                 hr = buffer->Unlock();
00151             }
00152         }
00153     }
00154
00155     if (mfStarted)
00156     {
00157         MFShutdown();
00158     }
00159
00160     return hr;
00161 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Altimeter/cs/Scenario1_DataEvents.xaml.cs Source File

  • Altimeter
  • cs

Scenario1_DataEvents.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Devices.Sensors;
00015 using Windows.Foundation;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario1_DataEvents : Page
00024     {
00025         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00026         // as NotifyUser()
00027         MainPage rootPage = MainPage.Current;
00028
00029         private Altimeter sensor;
00030         private uint desiredReportIntervalMs;
00031
00032         public Scenario1_DataEvents()
00033         {
00034             this.InitializeComponent();
00035
00036             sensor = Altimeter.GetDefault();
00037             if (null != sensor)
00038             {
00039                 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00040                 // This value will be used later to activate the sensor.
00041                 uint minReportIntervalMs = sensor.MinimumReportInterval;
00042                 desiredReportIntervalMs = minReportIntervalMs > 1000 ? minReportIntervalMs : 1000;
00043             }
00044             else
00045             {
00046                 rootPage.NotifyUser("No altimeter found", NotifyType.ErrorMessage);
00047             }
00048         }
00049
00050         /// <summary>
00051         /// Invoked when this page is about to be displayed in a Frame.
00052         /// </summary>
00053         /// <param name="e">Event data that describes how this page was reached. The Parameter
00054         /// property is typically used to configure the page.</param>
00055         protected override void OnNavigatedTo(NavigationEventArgs e)
00056         {
00057             ScenarioEnableButton.IsEnabled = true;
00058             ScenarioDisableButton.IsEnabled = false;
00059         }
00060
00061         /// <summary>
00062         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00063         /// </summary>
00064         /// <param name="e">
00065         /// Event data that can be examined by overriding code. The event data is representative
00066         /// of the navigation that will unload the current Page unless canceled. The
00067         /// navigation can potentially be canceled by setting Cancel.
00068         /// </param>
00069         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00070         {
00071             if (ScenarioDisableButton.IsEnabled)
00072             {
00073                 Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00074                 sensor.ReadingChanged -= new TypedEventHandler<Altimeter, AltimeterReadingChangedEventArgs>(ReadingChanged);
00075
00076                 // Restore the default report interval to release resources while the sensor is not in use
00077                 sensor.ReportInterval = 0;
00078             }
00079
00080             base.OnNavigatingFrom(e);
00081         }
00082
00083         /// <summary>
00084         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00085         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00086         /// </summary>
00087         /// <param name="sender"></param>
00088         /// <param name="e">
00089         /// Event data that can be examined for the current visibility state.
00090         /// </param>
00091         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00092         {
00093             if (ScenarioDisableButton.IsEnabled)
00094             {
00095                 if (e.Visible)
00096                 {
00097                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00098                     sensor.ReadingChanged += new TypedEventHandler<Altimeter, AltimeterReadingChangedEventArgs>(ReadingChanged);
00099                 }
00100                 else
00101                 {
00102                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00103                     sensor.ReadingChanged -= new TypedEventHandler<Altimeter, AltimeterReadingChangedEventArgs>(ReadingChanged);
00104                 }
00105             }
00106         }
00107
00108         /// <summary>
00109         /// This is the event handler for ReadingChanged events.
00110         /// </summary>
00111         /// <param name="sender"></param>
00112         /// <param name="e"></param>
00113         async private void ReadingChanged(object sender, AltimeterReadingChangedEventArgs e)
00114         {
00115             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00116             {
00117                 AltimeterReading reading = e.Reading;
00118                 ScenarioOutput_M.Text = String.Format("{0,5:0.00}", reading.AltitudeChangeInMeters);
00119             });
00120         }
00121
00122         /// <summary>
00123         /// This is the click handler for the 'Enable' button.
00124         /// </summary>
00125         /// <param name="sender"></param>
00126         /// <param name="e"></param>
00127         private void ScenarioEnable(object sender, RoutedEventArgs e)
00128         {
00129             if (null != sensor)
00130             {
00131                 // Establish the report interval
00132                 sensor.ReportInterval = desiredReportIntervalMs;
00133
00134                 Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged);
00135                 sensor.ReadingChanged += new TypedEventHandler<Altimeter, AltimeterReadingChangedEventArgs>(ReadingChanged);
00136
00137                 ScenarioEnableButton.IsEnabled = false;
00138                 ScenarioDisableButton.IsEnabled = true;
00139             }
00140             else
00141             {
00142                 rootPage.NotifyUser("No altimeter found", NotifyType.ErrorMessage);
00143             }
00144         }
00145
00146         /// <summary>
00147         /// This is the click handler for the 'Disable' button.
00148         /// </summary>
00149         /// <param name="sender"></param>
00150         /// <param name="e"></param>
00151         private void ScenarioDisable(object sender, RoutedEventArgs e)
00152         {
00153             Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00154             sensor.ReadingChanged -= new TypedEventHandler<Altimeter, AltimeterReadingChangedEventArgs>(ReadingChanged);
00155
00156             // Restore the default report interval to release resources while the sensor is not in use
00157             sensor.ReportInterval = 0;
00158
00159             ScenarioEnableButton.IsEnabled = true;
00160             ScenarioDisableButton.IsEnabled = false;
00161         }
00162     }
00163 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks.Shared/Trip.cpp Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks.Shared

Trip.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Trip.h"
00013
00014 using namespace AdventureWorks_Shared;
00015
00016 using namespace Platform;
00017 using namespace Windows::ApplicationModel::Core;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Globalization;
00020 using namespace Windows::UI::Xaml::Data;
00021 using namespace Windows::UI::Core;
00022
00023 Trip::Trip()
00024 {
00025 }
00026
00027 String^ Trip::Destination::get()
00028 {
00029     return this->destination;
00030 }
00031
00032 void Trip::Destination::set(String^ value)
00033 {
00034     this->destination = value;
00035     NotifyPropertyChanged("Destination");
00036 }
00037
00038 String^ Trip::Description::get()
00039 {
00040     return this->description;
00041 }
00042
00043 void Trip::Description::set(String^ value)
00044 {
00045     this->description = value;
00046     NotifyPropertyChanged("Description");
00047 }
00048
00049 String^ Trip::Notes::get()
00050 {
00051     return this->notes;
00052 }
00053
00054 void Trip::Notes::set(String^ value)
00055 {
00056     this->notes = value;
00057     NotifyPropertyChanged("Notes");
00058 }
00059
00060
00061 Calendar^ Trip::StartDate::get()
00062 {
00063     return this->startDate;
00064 }
00065
00066 void Trip::StartDate::set(Calendar^ value)
00067 {
00068     this->startDate = value;
00069     NotifyPropertyChanged("StartDate");
00070 }
00071
00072 Calendar^ Trip::EndDate::get()
00073 {
00074     return this->endDate;
00075 }
00076
00077 void Trip::EndDate::set(Calendar^ value)
00078 {
00079     this->endDate = value;
00080     NotifyPropertyChanged("EndDate");
00081 }
00082
00083 /// <summary> Fire property changed events if a subscriber is listening. </summary>
00084 /// <param name="propertyName">The name of the property modified.</param>
00085 void Trip::NotifyPropertyChanged(String^ propertyName)
00086 {
00087     try
00088     {
00089         if (subscribers > 0)
00090         {
00091             CoreApplicationView^ view = CoreApplication::MainView;
00092             view->CoreWindow->Dispatcher->RunAsync(
00093                 CoreDispatcherPriority::Normal,
00094                 ref new DispatchedHandler([this, propertyName]()
00095             {
00096                 PropertyChanged(this, ref new PropertyChangedEventArgs(propertyName));
00097             }));
00098         }
00099     }
00100     catch (Platform::Exception^)
00101     {
00102         // swallow exceptions here, we might be running on the background thread.
00103     }
00104 }
Generated on Fri Nov 15 2024 22:18:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LanguageFont/cppwinrt/Scenario1_UIFonts.h Source File

  • LanguageFont
  • cppwinrt

Scenario1_UIFonts.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_UIFonts.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1_UIFonts : Scenario1_UIFontsT<Scenario1_UIFonts>
00020     {
00021         Scenario1_UIFonts();
00022
00023         void ApplyFonts_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024     };
00025 }
00026
00027 namespace winrt::SDKTemplate::factory_implementation
00028 {
00029     struct Scenario1_UIFonts : Scenario1_UIFontsT<Scenario1_UIFonts, implementation::Scenario1_UIFonts>
00030     {
00031     };
00032 }
Generated on Fri Nov 15 2024 22:20:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_MultipleScanners Member List

This is the complete list of members for Scenario2_MultipleScanners, including all inherited members.
BarcodeScannerInstance enum name | Scenario2_MultipleScanners | [private]
barcodeScannerInstance1 | Scenario2_MultipleScanners | [private]
barcodeScannerInstance2 | Scenario2_MultipleScanners | [private]
ButtonEndScanningInstance1_Click(object sender, RoutedEventArgs e) | Scenario2_MultipleScanners | [inline, private]
ButtonEndScanningInstance2_Click(object sender, RoutedEventArgs e) | Scenario2_MultipleScanners | [inline, private]
ButtonStartScanningInstance1_Click(object sender, RoutedEventArgs e) | Scenario2_MultipleScanners | [inline, private]
ButtonStartScanningInstance2_Click(object sender, RoutedEventArgs e) | Scenario2_MultipleScanners | [inline, private]
ClaimBarcodeScannerAsync(BarcodeScannerInstance instance) | Scenario2_MultipleScanners | [inline, private]
claimedBarcodeScannerInstance1 | Scenario2_MultipleScanners | [private]
claimedBarcodeScannerInstance1_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args) | Scenario2_MultipleScanners | [inline, private]
claimedBarcodeScannerInstance1_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e) | Scenario2_MultipleScanners | [inline, private]
claimedBarcodeScannerInstance2 | Scenario2_MultipleScanners | [private]
claimedBarcodeScannerInstance2_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args) | Scenario2_MultipleScanners | [inline, private]
claimedBarcodeScannerInstance2_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e) | Scenario2_MultipleScanners | [inline, private]
CreateDefaultScannerObjectAsync(BarcodeScannerInstance instance) | Scenario2_MultipleScanners | [inline, private]
EnableBarcodeScannerAsync(BarcodeScannerInstance instance) | Scenario2_MultipleScanners | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_MultipleScanners | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_MultipleScanners | [inline, protected]
ResetTheScenarioState() | Scenario2_MultipleScanners | [inline, private]
ResetUI() | Scenario2_MultipleScanners | [inline, private]
rootPage | Scenario2_MultipleScanners | [private]
Scenario2_MultipleScanners() | Scenario2_MultipleScanners | [inline]
SetUI(BarcodeScannerInstance instance) | Scenario2_MultipleScanners | [inline, private]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/pch.cpp Source File

  • XamlBind
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Trip Member List

This is the complete list of members for Trip, including all inherited members.
description | Trip | [private]
Description | Trip |
destination | Trip | [private]
Destination | Trip |
endDate | Trip | [private]
EndDate | Trip |
Notes | Trip |
notes | Trip | [private]
NotifyPropertyChanged(string propertyName) | Trip | [inline, private]
PropertyChanged | Trip |
StartDate | Trip |
startDate | Trip | [private]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3 Member List

This is the complete list of members for Scenario3, including all inherited members.
Discover_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3 | [inline, private]
DoConnect_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3 | [inline, private]
GetProvisioningInfo_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3 | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario3 | [inline, protected]
provisioningInfo | Scenario3 | [private]
rootPage | Scenario3 | [private]
Scenario3() | Scenario3 | [inline]
SessionConnected() | Scenario3 | [inline]
thisLock | Scenario3 | [private]
UpdateDiscoveryList(IList< DiscoveredDeviceWrapper > devices) | Scenario3 | [inline]
Generated on Fri Nov 15 2024 22:24:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePickerContracts/cs/MainPage.xaml.cs Source File

  • FilePickerContracts
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Data;
00017 using Windows.UI.Xaml.Media;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class MainPage : Page
00028     {
00029         public static MainPage Current;
00030
00031         public MainPage()
00032         {
00033             this.InitializeComponent();
00034
00035             // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00036             // in order to call methods that are in this class.
00037             Current = this;
00038             SampleTitle.Text = FEATURE_NAME;
00039         }
00040
00041         protected override void OnNavigatedTo(NavigationEventArgs e)
00042         {
00043             // Populate the scenario list from the SampleConfiguration.cs file
00044             ScenarioControl.ItemsSource = scenarios;
00045             if (Window.Current.Bounds.Width < 640)
00046             {
00047                 ScenarioControl.SelectedIndex = -1;
00048             }
00049             else
00050             {
00051                 ScenarioControl.SelectedIndex = 0;
00052             }
00053         }
00054
00055         /// <summary>
00056         /// Called whenever the user changes selection in the scenarios list.  This method will navigate to the respective
00057         /// sample scenario page.
00058         /// </summary>
00059         /// <param name="sender"></param>
00060         /// <param name="e"></param>
00061         private void ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
00062         {
00063             // Clear the status block when navigating scenarios.
00064             NotifyUser(String.Empty, NotifyType.StatusMessage);
00065
00066             ListBox scenarioListBox = sender as ListBox;
00067             Scenario s = scenarioListBox.SelectedItem as Scenario;
00068             if (s != null)
00069             {
00070                 ScenarioFrame.Navigate(s.ClassType);
00071                 if (Window.Current.Bounds.Width < 640)
00072                 {
00073                     Splitter.IsPaneOpen = false;
00074                     StatusBorder.Visibility = Visibility.Collapsed;
00075                 }
00076             }
00077         }
00078
00079         public List<Scenario> Scenarios
00080         {
00081             get { return this.scenarios; }
00082         }
00083
00084         /// <summary>
00085         /// Used to display messages to the user
00086         /// </summary>
00087         /// <param name="strMessage"></param>
00088         /// <param name="type"></param>
00089         public void NotifyUser(string strMessage, NotifyType type)
00090         {
00091             switch (type)
00092             {
00093                 case NotifyType.StatusMessage:
00094                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green);
00095                     break;
00096                 case NotifyType.ErrorMessage:
00097                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red);
00098                     break;
00099             }
00100             StatusBlock.Text = strMessage;
00101
00102             // Collapse the StatusBlock if it has no text to conserve real estate.
00103             StatusBorder.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed;
00104         }
00105
00106         async void Footer_Click(object sender, RoutedEventArgs e)
00107         {
00108             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00109         }
00110
00111         private void Button_Click(object sender, RoutedEventArgs e)
00112         {
00113             //Splitter.DisplayMode = (Splitter.DisplayMode == SplitViewDisplayMode.Inline) ? SplitViewDisplayMode.CompactInline : SplitViewDisplayMode.Inline;
00114             Splitter.IsPaneOpen = (Splitter.IsPaneOpen == true) ? false : true;
00115             StatusBorder.Visibility = Visibility.Collapsed;
00116         }
00117     }
00118     public enum NotifyType
00119     {
00120         StatusMessage,
00121         ErrorMessage
00122     };
00123
00124     public class ScenarioBindingConverter : IValueConverter
00125     {
00126         public object Convert(object value, Type targetType, object parameter, string language)
00127         {
00128             Scenario s = value as Scenario;
00129             return (MainPage.Current.Scenarios.IndexOf(s) + 1) + ") " + s.Title;
00130         }
00131
00132         public object ConvertBack(object value, Type targetType, object parameter, string language)
00133         {
00134             return true;
00135         }
00136     }
00137 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cpp/Scenario2_Connector.xaml.h Source File

  • WiFiDirect
  • cpp

Scenario2_Connector.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Connector.g.h"
00015 #include "MainPage.xaml.h"
00016 #include "SocketReaderWriter.h"
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class Scenario2_Connector sealed
00025     {
00026     public:
00027         Scenario2_Connector();
00028
00029         property Windows::Foundation::Collections::IObservableVector<DiscoveredDevice^>^ _discoveredDevices;
00030         property Windows::Foundation::Collections::IObservableVector<ConnectedDevice^>^ _connectedDevices;
00031
00032     private:
00033         void btnWatcher_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void btnIe_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         void btnFromId_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         void btnClose_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         void btnSendMessage_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038
00039         MainPage^ rootPage;
00040         Windows::Devices::Enumeration::DeviceWatcher^ _deviceWatcher;
00041         std::mutex _discoveryMutex;
00042         bool _fWatcherStarted;
00043
00044         void OnDeviceAdded(Windows::Devices::Enumeration::DeviceWatcher^ deviceWatcher, Windows::Devices::Enumeration::DeviceInformation^ deviceInfo);
00045         void OnDeviceRemoved(Windows::Devices::Enumeration::DeviceWatcher^ deviceWatcher, Windows::Devices::Enumeration::DeviceInformationUpdate^ deviceInfoUpdate);
00046         void OnDeviceUpdated(Windows::Devices::Enumeration::DeviceWatcher^ deviceWatcher, Windows::Devices::Enumeration::DeviceInformationUpdate^ deviceInfoUpdate);
00047         void OnEnumerationCompleted(Windows::Devices::Enumeration::DeviceWatcher^ deviceWatcher, Object^ o);
00048         void OnStopped(Windows::Devices::Enumeration::DeviceWatcher^ deviceWatcher, Object^ o);
00049
00050         void OnConnectionStatusChanged(Windows::Devices::WiFiDirect::WiFiDirectDevice^ sender, Object^ arg);
00051
00052         Windows::Foundation::EventRegistrationToken _deviceAddedToken;
00053         Windows::Foundation::EventRegistrationToken _deviceRemovedToken;
00054         Windows::Foundation::EventRegistrationToken _deviceUpdatedToken;
00055         Windows::Foundation::EventRegistrationToken _deviceWatcherEnumerationCompletedToken;
00056         Windows::Foundation::EventRegistrationToken _deviceWatcherStoppedToken;
00057     };
00058 }
Generated on Fri Nov 15 2024 22:22:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3 Member List

This is the complete list of members for Scenario3, including all inherited members.
Scenario3() Scenario3 [inline]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/pch.h Source File

  • HolographicTagAlong
  • cpp

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <agile.h>
00015 #include <array>
00016 #include <concrt.h>
00017 #include <d2d1_2.h>
00018 #include <d3d11_4.h>
00019 #include <DirectXColors.h>
00020 #include <dwrite_2.h>
00021 #include <map>
00022 #include <mutex>
00023 #include <string>
00024 #include <wincodec.h>
00025 #include <WindowsNumerics.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cpp/Common/MeshGeometry.cpp Source File

  • 360VideoPlayback
  • cpp
  • Common

MeshGeometry.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "MeshGeometry.h"
00003 #include "..\360VideoPlaybackMain.h"
00004 #include "DeviceResources.h"
00005 #include "DirectXHelper.h"
00006 #include "..\Content\ShaderStructures.h"
00007
00008 using namespace _360VideoPlayback;
00009 using namespace DirectX;
00010 using namespace DX;
00011 using namespace Microsoft::WRL;
00012 using namespace std;
00013 using namespace Windows::Foundation::Numerics;
00014
00015 shared_ptr<MeshGeometry> MeshGeometry::MakeTexturedCube()
00016 {
00017     _360VideoPlayback::VertexPositionTexture cubeVertices[] =
00018     {
00019         { XMFLOAT3(-0.5f, 0.5f, -0.5f), XMFLOAT2(-1.0f, -1.0f) }, // +Y (top face)
00020         { XMFLOAT3(0.5f, 0.5f, -0.5f), XMFLOAT2(-1.0f, -1.0f) },
00021         { XMFLOAT3(0.5f, 0.5f,  0.5f), XMFLOAT2(-1.0f, -1.0f) },
00022         { XMFLOAT3(-0.5f, 0.5f,  0.5f), XMFLOAT2(-1.0f, -1.0f) },
00023
00024         { XMFLOAT3(-0.5f, -0.5f,  0.5f), XMFLOAT2(-1.0f, -1.0f) }, // -Y (bottom face)
00025         { XMFLOAT3(0.5f, -0.5f,  0.5f), XMFLOAT2(-1.0f, -1.0f) },
00026         { XMFLOAT3(0.5f, -0.5f, -0.5f), XMFLOAT2(-1.0f, -1.0f) },
00027         { XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT2(-1.0f, -1.0f) },
00028
00029         { XMFLOAT3(0.5f,  0.5f,  0.5f), XMFLOAT2(-1.0f, -1.0f) }, // +X (right face)
00030         { XMFLOAT3(0.5f,  0.5f, -0.5f), XMFLOAT2(-1.0f, -1.0f) },
00031         { XMFLOAT3(0.5f, -0.5f, -0.5f), XMFLOAT2(-1.0f, -1.0f) },
00032         { XMFLOAT3(0.5f, -0.5f,  0.5f), XMFLOAT2(-1.0f, -1.0f) },
00033
00034         { XMFLOAT3(-0.5f,  0.5f, -0.5f), XMFLOAT2(-1.0f, -1.0f) }, // -X (left face)
00035         { XMFLOAT3(-0.5f,  0.5f,  0.5f), XMFLOAT2(-1.0f, -1.0f) },
00036         { XMFLOAT3(-0.5f, -0.5f,  0.5f), XMFLOAT2(-1.0f, -1.0f) },
00037         { XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT2(-1.0f, -1.0f) },
00038
00039         { XMFLOAT3(-0.5f,  0.5f, 0.5f), XMFLOAT2(0.0f, 0.0f) }, // +Z (front face)
00040         { XMFLOAT3(0.5f,  0.5f, 0.5f), XMFLOAT2(1.0f, 0.0f) }, // WARNING: This Front face is tied directly to the DEFAULT_CUBE_BOUNDING_PLANE. If you modify this, update both
00041         { XMFLOAT3(0.5f, -0.5f, 0.5f), XMFLOAT2(1.0f, 1.0f) },
00042         { XMFLOAT3(-0.5f, -0.5f, 0.5f), XMFLOAT2(0.0f, 1.0f) },
00043
00044         { XMFLOAT3(0.5f,  0.5f, -0.5f), XMFLOAT2(-1.0f, -1.0f) }, // -Z (back face)
00045         { XMFLOAT3(-0.5f,  0.5f, -0.5f), XMFLOAT2(-1.0f, -1.0f) },
00046         { XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT2(-1.0f, -1.0f) },
00047         { XMFLOAT3(0.5f, -0.5f, -0.5f), XMFLOAT2(-1.0f, -1.0f) },
00048     };
00049
00050     unsigned short cubeIndices[] =
00051     {
00052         0, 1, 2,
00053         0, 2, 3,
00054
00055         4, 5, 6,
00056         4, 6, 7,
00057
00058         8, 9, 10,
00059         8, 10, 11,
00060
00061         12, 13, 14,
00062         12, 14, 15,
00063
00064         16, 17, 18,
00065         16, 18, 19,
00066
00067         20, 21, 22,
00068         20, 22, 23
00069     };
00070
00071     ComPtr<ID3D11Buffer> vertexBuffer = CreateVertexBuffer(ARRAYSIZE(cubeVertices), cubeVertices);
00072     ComPtr<ID3D11Buffer> indexBuffer = CreateIndexBuffer(ARRAYSIZE(cubeIndices), cubeIndices);
00073
00074     return make_shared<MeshGeometry>(
00075         D3D11_PRIMITIVE_TOPOLOGY::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
00076         vertexBuffer,
00077         indexBuffer,
00078         static_cast<uint32>(sizeof(_360VideoPlayback::VertexPositionTexture)),
00079         static_cast<uint32>(ARRAYSIZE(cubeIndices))
00080         );
00081 }
00082
00083 shared_ptr<MeshGeometry> MeshGeometry::MakeTexturedCylinder(unsigned short tessellation)
00084 {
00085     const float frontFaceZ = 0.5f;
00086     const float backFaceZ = -0.5f;
00087     vector<VertexPositionTexture> vertices = {
00088         {{ 0.0f, 0.0f, frontFaceZ }, { 0.5f, 0.5f }}, // Front face center vertex
00089         {{ 0.0f, 0.0f, backFaceZ },  { 0.0f, 0.0f }}  // Back face center vertex
00090     };
00091
00092     const unsigned short frontFaceCenterVertexIndex = 0;
00093     const unsigned short backFaceCenterVertexIndex = 1;
00094
00095     unsigned short frontFaceVerticesStartIndex = static_cast<unsigned short>(vertices.size());
00096     auto frontFaceVertices = MeshGeometry::MakeCylinderFaceVertices(
00097         tessellation,
00098         frontFaceZ,
00099         [](float x, float y) -> XMFLOAT2
00100     {
00101         const float u = x + 0.5f;
00102         const float v = -y + 0.5f;
00103
00104         return { u, v };
00105     }
00106     );
00107     copy(begin(frontFaceVertices), end(frontFaceVertices), back_inserter(vertices));
00108
00109     // While the vertex positions of the front face and the "front" side vertices are the same,
00110     // we want the UV coordinates to be different.
00111     // So duplicate the vertices and set the UV coordinates to [0,0]
00112     unsigned short frontFaceSideVerticesStartIndex = static_cast<unsigned short>(vertices.size());
00113     auto frontFaceSideVertices = MeshGeometry::MakeCylinderFaceVertices(
00114         tessellation,
00115         frontFaceZ,
00116         [](float /*x*/, float /*y*/) -> XMFLOAT2
00117     {
00118         return { 0.0f, 0.0f };
00119     }
00120     );
00121     copy(begin(frontFaceSideVertices), end(frontFaceSideVertices), back_inserter(vertices));
00122
00123     // Shared by the back face and "back" side vertices.
00124     unsigned short backFaceVerticesStartIndex = static_cast<unsigned short>(vertices.size());
00125     auto backFaceVertices = MeshGeometry::MakeCylinderFaceVertices(
00126         tessellation,
00127         backFaceZ,
00128         [](float /*x*/, float /*y*/) -> XMFLOAT2
00129     {
00130         return { 0.0f, 0.0f };
00131     }
00132     );
00133     copy(begin(backFaceVertices), end(backFaceVertices), back_inserter(vertices));
00134
00135     // Front face indices
00136     vector<unsigned short> indices = MeshGeometry::MakeCylinderFaceIndices(
00137         tessellation,
00138         /*vertexIndexOffset*/ frontFaceVerticesStartIndex,
00139         /*centerVertexIndex*/ frontFaceCenterVertexIndex,
00140         /*isFrontFace*/ true);
00141
00142     // Back face indices.
00143     // This may be shown brifly during intro/outro animations so we need to show it.
00144     vector<unsigned short> backFaceIndices = MeshGeometry::MakeCylinderFaceIndices(
00145         tessellation,
00146         /*vertexIndexOffset*/ backFaceVerticesStartIndex,
00147         /*centerVertexIndex*/ backFaceCenterVertexIndex,
00148         /*isFrontFace*/ false);
00149     copy(begin(backFaceIndices), end(backFaceIndices), back_inserter(indices));
00150
00151     // Side indices
00152     vector<unsigned short> sideIndices = MeshGeometry::MakeCylinderSideIndices(
00153         tessellation,
00154         /*vertexIndexOffset*/ frontFaceSideVerticesStartIndex,
00155         /*cylinderFaceVertexStride*/ static_cast<unsigned short>(frontFaceSideVertices.size()));
00156     copy(begin(sideIndices), end(sideIndices), back_inserter(indices));
00157
00158     ComPtr<ID3D11Buffer> vertexBuffer = CreateVertexBuffer(
00159         static_cast<unsigned int>(vertices.size()),
00160         vertices.data()
00161     );
00162
00163     ComPtr<ID3D11Buffer> indexBuffer = CreateIndexBuffer(
00164         static_cast<unsigned int>(indices.size()),
00165         indices.data());
00166
00167     return make_shared<MeshGeometry>(
00168         D3D11_PRIMITIVE_TOPOLOGY::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
00169         vertexBuffer,
00170         indexBuffer,
00171         static_cast<uint32>(sizeof(VertexPositionTexture)),
00172         static_cast<uint32>(indices.size())
00173         );
00174 }
00175
00176 vector<VertexPositionTexture> MeshGeometry::MakeCylinderFaceVertices(unsigned short tessellation, float z, function<XMFLOAT2(float x, float y)> uvGenerator)
00177 {
00178     // Create a fan of triangles from the center of the circle.
00179     // Reserve space for all vertices along the outer edges and the center vertex.
00180     vector<VertexPositionTexture> vertices;
00181     vertices.resize(tessellation + 1);
00182     for (int i = 0; i < tessellation; i++)
00183     {
00184         const float angle = XM_2PI * (static_cast<float>(i) / tessellation);
00185
00186         const float x = 0.5f * cos(angle);
00187         const float y = 0.5f * sin(angle);
00188
00189         const XMFLOAT3 pos{ x, y, z };
00190         const XMFLOAT2 uv = uvGenerator(x, y);
00191
00192         vertices[i] = { pos, uv };
00193     }
00194
00195     return vertices;
00196 }
00197
00198 vector<unsigned short> MeshGeometry::MakeCylinderFaceIndices(unsigned short tessellation, unsigned short vertexIndexOffset, unsigned short centerVertexIndex, bool isFrontFace)
00199 {
00200     vector<unsigned short> indices;
00201     indices.resize(tessellation * 3);
00202
00203     for (unsigned short i = 0; i < tessellation; i++)
00204     {
00205         // The next 3 vertices are for the i-th triangle
00206         const int baseTriangleIndex = (i * 3);
00207
00208         unsigned short currentVertexIndex = vertexIndexOffset + i;
00209         unsigned short nextVertexIndex = vertexIndexOffset + ((i + 1) % tessellation);
00210
00211         if (isFrontFace)
00212         {
00213             // Clockwise ordering
00214             indices[baseTriangleIndex] = currentVertexIndex;
00215             indices[baseTriangleIndex + 1] = centerVertexIndex;
00216             indices[baseTriangleIndex + 2] = nextVertexIndex;
00217         }
00218         else
00219         {
00220             // Counter-clockwise ordering
00221             indices[baseTriangleIndex] = nextVertexIndex;
00222             indices[baseTriangleIndex + 1] = centerVertexIndex;
00223             indices[baseTriangleIndex + 2] = currentVertexIndex;
00224         }
00225     }
00226
00227     return indices;
00228 }
00229
00230 vector<unsigned short> MeshGeometry::MakeCylinderSideIndices(unsigned short tessellation, unsigned short vertexIndexOffset, unsigned short cylinderFaceVertexStride)
00231 {
00232     vector<unsigned short> indices;
00233     indices.resize(tessellation * 6);
00234
00235     for (unsigned short i = 0; i < tessellation; i++)
00236     {
00237         // The next 6 vertices are for the i-th quad making up the i-th side of the cylinder
00238         const int baseTriangleIndex = (i * 6);
00239
00240         unsigned short currentVertexIndexFrontFace = vertexIndexOffset + i;
00241         unsigned short currentVertexIndexBackFace = vertexIndexOffset + i + cylinderFaceVertexStride;
00242         unsigned short nextVertexIndexFrontFace = vertexIndexOffset + ((i + 1) % tessellation);
00243         unsigned short nextVertexIndexBackFace = vertexIndexOffset + ((i + 1) % tessellation) + cylinderFaceVertexStride;
00244
00245         indices[baseTriangleIndex] = currentVertexIndexFrontFace;
00246         indices[baseTriangleIndex + 1] = nextVertexIndexFrontFace;
00247         indices[baseTriangleIndex + 2] = currentVertexIndexBackFace;
00248
00249         indices[baseTriangleIndex + 3] = nextVertexIndexFrontFace;
00250         indices[baseTriangleIndex + 4] = nextVertexIndexBackFace;
00251         indices[baseTriangleIndex + 5] = currentVertexIndexBackFace;
00252     }
00253
00254     return indices;
00255 }
00256
00257 ComPtr<ID3D11Buffer> MeshGeometry::CreateVertexBuffer(unsigned int numVertices, const VertexPositionTexture* vertexData)
00258 {
00259     ComPtr<ID3D11Buffer> vertexBufferInternal;
00260     D3D11_BUFFER_DESC VertexBufferDesc;
00261     VertexBufferDesc.ByteWidth = sizeof(_360VideoPlayback::VertexPositionTexture) * numVertices;
00262     VertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00263     VertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00264     VertexBufferDesc.CPUAccessFlags = 0;
00265     VertexBufferDesc.MiscFlags = 0;
00266     VertexBufferDesc.StructureByteStride = 0;
00267
00268     D3D11_SUBRESOURCE_DATA VertexBufferData;
00269     VertexBufferData.pSysMem = vertexData;
00270     VertexBufferData.SysMemPitch = 0;
00271     VertexBufferData.SysMemSlicePitch = 0;
00272
00273     DX::ThrowIfFailed(
00274         _360VideoPlaybackMain::GetDeviceResources()->GetD3DDevice()->CreateBuffer(
00275             &VertexBufferDesc,
00276             &VertexBufferData,
00277             &vertexBufferInternal));
00278
00279     return vertexBufferInternal;
00280 }
00281
00282 ComPtr<ID3D11Buffer> MeshGeometry::CreateIndexBuffer(unsigned int numIndices, const unsigned short* indexData)
00283 {
00284     ComPtr<ID3D11Buffer> indexBufferInternal;
00285
00286     D3D11_BUFFER_DESC IndexBufferDesc;
00287     IndexBufferDesc.ByteWidth = sizeof(unsigned short) * numIndices;
00288     IndexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
00289     IndexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
00290     IndexBufferDesc.CPUAccessFlags = 0;
00291     IndexBufferDesc.MiscFlags = 0;
00292     IndexBufferDesc.StructureByteStride = 0;
00293
00294     D3D11_SUBRESOURCE_DATA IndexBufferData;
00295     IndexBufferData.pSysMem = indexData;
00296     IndexBufferData.SysMemPitch = 0;
00297     IndexBufferData.SysMemSlicePitch = 0;
00298
00299     DX::ThrowIfFailed(
00300         _360VideoPlaybackMain::GetDeviceResources()->GetD3DDevice()->CreateBuffer(
00301             &IndexBufferDesc,
00302             &IndexBufferData,
00303             &indexBufferInternal));
00304
00305     return indexBufferInternal;
00306 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cs/BackgroundActivity.cs Source File

  • BackgroundActivation
  • cs

BackgroundActivity.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Diagnostics;
00013 using System.Threading;
00014 using Windows.ApplicationModel.Activation;
00015 using Windows.ApplicationModel.Background;
00016 using Windows.Foundation;
00017 using Windows.Storage;
00018 using Windows.System.Threading;
00019
00020 namespace SDKTemplate
00021 {
00022     public class BackgroundActivity
00023     {
00024         BackgroundTaskCancellationReason _cancelReason = BackgroundTaskCancellationReason.Abort;
00025         volatile bool _cancelRequested = false;
00026         BackgroundTaskDeferral _deferral = null;
00027         ThreadPoolTimer _periodicTimer = null;
00028         uint _progress = 0;
00029         IBackgroundTaskInstance _taskInstance = null;
00030
00031         //
00032         // The Run method is the entry point of a background task.
00033         //
00034         public void Run(IBackgroundTaskInstance taskInstance)
00035         {
00036             Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");
00037
00038             //
00039             // Query BackgroundWorkCost
00040             // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
00041             // of work in the background task and return immediately.
00042             //
00043             var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
00044
00045             //
00046             // Associate a cancellation handler with the background task.
00047             //
00048             taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
00049
00050             //
00051             // Get the deferral object from the task instance, and take a reference to the taskInstance;
00052             //
00053             _deferral = taskInstance.GetDeferral();
00054             _taskInstance = taskInstance;
00055
00056             _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));
00057         }
00058
00059         //
00060         // Handles background task cancellation.
00061         //
00062         private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
00063         {
00064             //
00065             // Indicate that the background task is canceled.
00066             //
00067             _cancelRequested = true;
00068             _cancelReason = reason;
00069
00070             Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested...");
00071         }
00072
00073         //
00074         // Simulate the background task activity.
00075         //
00076         private void PeriodicTimerCallback(ThreadPoolTimer timer)
00077         {
00078             if ((_cancelRequested == false) && (_progress < 100))
00079             {
00080                 _progress += 10;
00081                 _taskInstance.Progress = _progress;
00082             }
00083             else
00084             {
00085                 _periodicTimer.Cancel();
00086
00087                 var key = _taskInstance.Task.Name;
00088
00089                 //
00090                 // Record that this background task ran.
00091                 //
00092                 String taskStatus = (_progress < 100) ? "Canceled with reason: " + _cancelReason.ToString() : "Completed";
00093                 BackgroundTaskSample.TaskStatuses[key] = taskStatus;
00094                 Debug.WriteLine("Background " + _taskInstance.Task.Name + taskStatus);
00095
00096                 //
00097                 // Indicate that the background task has completed.
00098                 //
00099                 _deferral.Complete();
00100             }
00101         }
00102
00103         public static void Start(BackgroundTaskRegistrationGroup sender, BackgroundActivatedEventArgs args)
00104         {
00105             Start(args.TaskInstance);
00106         }
00107
00108         public static void Start(IBackgroundTaskInstance taskInstance)
00109         {
00110             // Use the taskInstance.Name and/or taskInstance.InstanceId to determine
00111             // what background activity to perform. In this sample, all of our
00112             // background activities are the same, so there is nothing to check.
00113             var activity = new BackgroundActivity();
00114             activity.Run(taskInstance);
00115         }
00116     }
00117 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_UnicodeExtensions Member List

This is the complete list of members for Scenario5_UnicodeExtensions, including all inherited members.
Display() | Scenario5_UnicodeExtensions | [inline, private]
Scenario5_UnicodeExtensions() | Scenario5_UnicodeExtensions | [inline]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/PixelShader/BasicTimer.h Source File

  • D2DCustomEffects
  • cpp
  • PixelShader

BasicTimer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // A simple timer class used to drive the render loop of the actively-animated
00015 // DirectX SDK samples. Uses the QueryPerformanceCounter function to retrieve
00016 // high-resolution timing information.
00017 ref class BasicTimer
00018 {
00019 private:
00020     LARGE_INTEGER m_frequency;
00021     LARGE_INTEGER m_currentTime;
00022     LARGE_INTEGER m_startTime;
00023     LARGE_INTEGER m_lastTime;
00024     float m_total;
00025     float m_delta;
00026
00027 internal:
00028     BasicTimer();
00029     void Reset();
00030     void Update();
00031     property float Total
00032     {
00033         float get();
00034     }
00035     property float Delta
00036     {
00037         float get();
00038     }
00039 };
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/Scenario6.xaml.cpp Source File

  • SimpleInk
  • cpp

Scenario6.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario6.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Core;
00020 using namespace Windows::UI::Input::Inking;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Media;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 Scenario6::Scenario6() : rootPage(MainPage::Current)
00030 {
00031     InitializeComponent();
00032
00033     // Initialize the InkCanvas controls
00034     inkCanvas->InkPresenter->InputDeviceTypes = CoreInputDeviceTypes::Mouse | CoreInputDeviceTypes::Pen;
00035     inkCanvas2->InkPresenter->InputDeviceTypes = CoreInputDeviceTypes::Mouse | CoreInputDeviceTypes::Pen;
00036
00037     inkCanvas->InkPresenter->UnprocessedInput->PointerEntered += ref new TypedEventHandler<InkUnprocessedInput^, PointerEventArgs^>(this, &Scenario6::UnprocessedInput_PointerEntered);
00038     inkCanvas2->InkPresenter->UnprocessedInput->PointerEntered += ref new TypedEventHandler<InkUnprocessedInput^, PointerEventArgs^>(this, &Scenario6::UnprocessedInput_PointerEntered1);
00039 }
00040
00041 void Scenario6::UnprocessedInput_PointerEntered(InkUnprocessedInput^ sender, PointerEventArgs^ args)
00042 {
00043     border1->BorderBrush = ref new SolidColorBrush(Windows::UI::Colors::Blue);
00044     border2->BorderBrush = ref new SolidColorBrush(Windows::UI::Colors::Gray);
00045     inkToolbar->TargetInkCanvas = inkCanvas;
00046 }
00047
00048 void Scenario6::UnprocessedInput_PointerEntered1(InkUnprocessedInput^ sender, PointerEventArgs^ args)
00049 {
00050     border1->BorderBrush = ref new SolidColorBrush(Windows::UI::Colors::Gray);
00051     border2->BorderBrush = ref new SolidColorBrush(Windows::UI::Colors::Blue);
00052     inkToolbar->TargetInkCanvas = inkCanvas2;
00053 }
00054
00055 void Scenario6::OnSizeChanged(Platform::Object^ sender, SizeChangedEventArgs^ e)
00056 {
00057     SetCanvasSize();
00058 }
00059
00060
00061 void Scenario6::SetCanvasSize()
00062 {
00063     outputGrid->Width = RootGrid->ActualWidth / 2;
00064     outputGrid->Height = RootGrid->ActualHeight / 2;
00065     inkCanvas->Width = RootGrid->ActualWidth / 2;
00066     inkCanvas->Height = RootGrid->ActualHeight / 2;
00067     outputGrid2->Width = RootGrid->ActualWidth / 2;
00068     outputGrid2->Height = RootGrid->ActualHeight / 2;
00069     inkCanvas2->Width = RootGrid->ActualWidth / 2;
00070     inkCanvas2->Height = RootGrid->ActualHeight / 2;
00071 }
00072
00073 void Scenario6::ToggleLogs(Platform::Object^ sender, RoutedEventArgs^ e)
00074 {
00075     auto stencilButton = safe_cast<InkToolbarStencilButton^>(inkToolbar->GetMenuButton(InkToolbarMenuKind::Stencil));
00076
00077     if (toggleLog->IsOn)
00078     {
00079         LogBorder->Visibility = Windows::UI::Xaml::Visibility::Visible;
00080         activeToolChangedToken = inkToolbar->ActiveToolChanged += ref new TypedEventHandler<InkToolbar^, Platform::Object^>(this, &Scenario6::InkToolbar_ActiveToolChanged);
00081         inkDrawingAttributesChangedToken = inkToolbar->InkDrawingAttributesChanged += ref new TypedEventHandler<InkToolbar^, Platform::Object^>(this, &Scenario6::InkToolbar_InkDrawingAttributesChanged);
00082         eraseAllClickedToken = inkToolbar->EraseAllClicked += ref new TypedEventHandler<InkToolbar^, Platform::Object^>(this, &Scenario6::InkToolbar_EraseAllClicked);
00083         stencilButtonCheckedChangedToken = inkToolbar->IsStencilButtonCheckedChanged += ref new TypedEventHandler<InkToolbar^, InkToolbarIsStencilButtonCheckedChangedEventArgs^>(this, &Scenario6::InkToolbar_IsStencilButtonCheckedChanged);
00084         selectedStencilChangedToken = stencilButton->RegisterPropertyChangedCallback(InkToolbarStencilButton::SelectedStencilProperty, ref new DependencyPropertyChangedCallback(this, &Scenario6::InkToolbar_SelectedStencilChanged));
00085     }
00086     else
00087     {
00088         LogBorder->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00089         textLogs->Text = "";
00090         inkToolbar->ActiveToolChanged -= activeToolChangedToken;
00091         inkToolbar->InkDrawingAttributesChanged -= inkDrawingAttributesChangedToken;
00092         inkToolbar->EraseAllClicked -= eraseAllClickedToken;
00093         inkToolbar->IsStencilButtonCheckedChanged -= stencilButtonCheckedChangedToken;
00094         stencilButton->UnregisterPropertyChangedCallback(InkToolbarStencilButton::SelectedStencilProperty, selectedStencilChangedToken);
00095     }
00096 }
00097
00098 void Scenario6::InkToolbar_IsStencilButtonCheckedChanged(InkToolbar^ sender, InkToolbarIsStencilButtonCheckedChangedEventArgs^ args)
00099 {
00100     textLogs->Text = "IsStencilButtonCheckedChanged(Kind = " + args->StencilKind.ToString() +
00101         ", IsChecked = " + args->StencilButton->IsChecked->Value.ToString() + ")\n" + textLogs->Text;
00102 }
00103
00104 void Scenario6::InkToolbar_SelectedStencilChanged(DependencyObject^ sender, DependencyProperty^ dp)
00105 {
00106     auto stencilButton = safe_cast<InkToolbarStencilButton^>(sender);
00107     textLogs->Text = "SelectedStencil changed to " + stencilButton->SelectedStencil.ToString() + "\n" + textLogs->Text;
00108 }
00109
00110 void Scenario6::InkToolbar_EraseAllClicked(InkToolbar^ sender, Platform::Object^ args)
00111 {
00112     textLogs->Text = "EraseAllClicked\n" + textLogs->Text;
00113 }
00114
00115 void Scenario6::InkToolbar_InkDrawingAttributesChanged(InkToolbar^ sender, Platform::Object^ args)
00116 {
00117     textLogs->Text = "InkDrawingAttributesChanged\n" + textLogs->Text;
00118 }
00119
00120 void Scenario6::InkToolbar_ActiveToolChanged(InkToolbar^ sender, Platform::Object^ args)
00121 {
00122     textLogs->Text = "ActiveToolChanged\n" + textLogs->Text;
00123 }
Generated on Fri Nov 15 2024 22:19:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDragAndDrop/cpp/Scenario2_DragUICustomization.xaml.h Source File

  • XamlDragAndDrop
  • cpp

Scenario2_DragUICustomization.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_DragUICustomization.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario2_DragUICustomization sealed
00024     {
00025     public:
00026         Scenario2_DragUICustomization();
00027     private:
00028         MainPage^ rootPage;
00029         Platform::String^ _insideName;
00030         Platform::String^ _outsideName;
00031         Platform::String^ _dropHere;
00032         bool IsChecked(Windows::UI::Xaml::Controls::Primitives::ToggleButton^ button);
00033
00034         void SourceGrid_DragStarting(Windows::UI::Xaml::UIElement^ sender, Windows::UI::Xaml::DragStartingEventArgs^ args);
00035         void TargetTextBox_Drop(Platform::Object^ sender, Windows::UI::Xaml::DragEventArgs^ e);
00036         void TargetTextBox_DragEnter(Platform::Object^ sender, Windows::UI::Xaml::DragEventArgs^ e);
00037         void TargetTextBox_DragLeave(Platform::Object^ sender, Windows::UI::Xaml::DragEventArgs^ e);
00038
00039     };
00040 }
Generated on Fri Nov 15 2024 22:22:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceConfiguration Member List

This is the complete list of members for DeviceConfiguration, including all inherited members.
BaudRate | DeviceConfiguration
BreakSignalState_false | DeviceConfiguration
BreakSignalState_true | DeviceConfiguration
DataBits | DeviceConfiguration
Handshake | DeviceConfiguration
IsDataTerminalReady_false | DeviceConfiguration
IsDataTerminalReady_true | DeviceConfiguration
IsRequestToSendEnabled_false | DeviceConfiguration
IsRequestToSendEnabled_true | DeviceConfiguration
Parity | DeviceConfiguration
StopBits | DeviceConfiguration
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_MoveCertificate Member List

This is the complete list of members for Scenario1_MoveCertificate, including all inherited members.
appStore | Scenario1_MoveCertificate | [private]
MoveAppCertificateToUserCertificateStore(object sender, RoutedEventArgs e) | Scenario1_MoveCertificate | [inline, private]
MoveItemBetweenListViews(ListViewItem item, ListView source, ListView destination) | Scenario1_MoveCertificate | [inline, private, static]
MoveUserCertificateToAppCertificateStore(object sender, RoutedEventArgs e) | Scenario1_MoveCertificate | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_MoveCertificate | [inline, protected]
Scenario1_MoveCertificate() | Scenario1_MoveCertificate | [inline]
userStore | Scenario1_MoveCertificate | [private]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraResolution/cpp/StreamResolutionHelper.cpp Source File

  • CameraResolution
  • cpp

StreamResolutionHelper.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "StreamResolutionHelper.h"
00014 #include <sstream>
00015 #include <math.h>
00016 #include <iomanip>
00017
00018 using namespace Platform;
00019 using namespace SDKTemplate;
00020 using namespace Windows::Media::MediaProperties;
00021
00022 StreamResolutionHelper::StreamResolutionHelper(IMediaEncodingProperties^ encodingProperties)
00023     : _encodingProperties(encodingProperties)
00024     , _type(encodingProperties->GetType()->FullName)
00025     , IMAGE_ENCODING_STRING(ref new String(L"Windows.Media.MediaProperties.ImageEncodingProperties"))
00026     , VIDEO_ENCODING_STRING(ref new String(L"Windows.Media.MediaProperties.VideoEncodingProperties"))
00027 {
00028 }
00029
00030 /// <summary>
00031 /// Output properties to a readable format for UI purposes
00032 /// eg. 1920x1080 [1.78] 30fps MPEG
00033 /// </summary>
00034 /// <param name="showFrameRate"></param>
00035 /// <returns>Readable string</returns>
00036 Platform::String^ StreamResolutionHelper::GetFriendlyName(bool showFrameRate)
00037 {
00038     std::wstringstream ss;
00039
00040     if (_type == IMAGE_ENCODING_STRING || !showFrameRate)
00041     {
00042         ss << Width() << "x" << Height() << " [" << std::setprecision(3) << AspectRatio() << "] "
00043             << _encodingProperties->Subtype->ToString()->Data();
00044     }
00045     else if (_type == VIDEO_ENCODING_STRING)
00046     {
00047         ss << Width() << "x" << Height() << " [" << std::setprecision(3) << AspectRatio() << "] "
00048             << FrameRate() << "FPS " << _encodingProperties->Subtype->ToString()->Data();
00049     }
00050
00051     return ref new String(ss.str().c_str());
00052 }
00053
00054 unsigned int StreamResolutionHelper::Width()
00055 {
00056     if (_type == IMAGE_ENCODING_STRING)
00057     {
00058         return static_cast<ImageEncodingProperties^>(_encodingProperties)->Width;
00059     }
00060     else if (_type == VIDEO_ENCODING_STRING)
00061     {
00062         return static_cast<VideoEncodingProperties^>(_encodingProperties)->Width;
00063     }
00064
00065     return 0;
00066 }
00067
00068 unsigned int StreamResolutionHelper::Height()
00069 {
00070     if (_type == IMAGE_ENCODING_STRING)
00071     {
00072         return static_cast<ImageEncodingProperties^>(_encodingProperties)->Height;
00073     }
00074     else if (_type == VIDEO_ENCODING_STRING)
00075     {
00076         return static_cast<VideoEncodingProperties^>(_encodingProperties)->Height;
00077     }
00078
00079     return 0;
00080 }
00081
00082 unsigned int StreamResolutionHelper::FrameRate()
00083 {
00084     if (_type == VIDEO_ENCODING_STRING)
00085     {
00086         VideoEncodingProperties^ videoEncodingProperties = static_cast<VideoEncodingProperties^>(_encodingProperties);
00087         if (videoEncodingProperties->FrameRate->Denominator != 0)
00088         {
00089             return videoEncodingProperties->FrameRate->Numerator / videoEncodingProperties->FrameRate->Denominator;
00090         }
00091     }
00092
00093     return 0;
00094 }
00095
00096 double StreamResolutionHelper::AspectRatio()
00097 {
00098     double width = static_cast<double>(Width());
00099     double height = static_cast<double>(Height());
00100     return round(width != 0) ? width / height : NAN;
00101 }
Generated on Fri Nov 15 2024 22:18:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/Scenario2_ChangePIN.cpp Source File

  • SmartCard
  • cppwinrt

Scenario2_ChangePIN.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_ChangePIN.h"
00014 #include "Scenario2_ChangePIN.g.cpp"
00015
00016 namespace winrt
00017 {
00018     using namespace Windows::Foundation;
00019     using namespace Windows::UI::Xaml;
00020     using namespace Windows::UI::Xaml::Controls;
00021     using namespace Windows::Devices::SmartCards;
00022 }
00023
00024 namespace winrt::SDKTemplate::implementation
00025 {
00026     Scenario2_ChangePIN::Scenario2_ChangePIN()
00027     {
00028         InitializeComponent();
00029     }
00030
00031     /// <summary>
00032     /// Click handler for the 'ChangePin' button.
00033     /// </summary>
00034     /// <param name="sender"></param>
00035     fire_and_forget Scenario2_ChangePIN::ChangePin_Click(IInspectable const& sender, RoutedEventArgs const&)
00036     {
00037         auto lifetime = get_strong();
00038
00039         if (!ValidateTPMSmartCard())
00040         {
00041             m_rootPage.NotifyUser(L"Use Scenario One to create a TPM virtual smart card.", NotifyType::ErrorMessage);
00042             co_return;
00043         }
00044
00045         auto b = sender.as<Button>();
00046         b.IsEnabled(false);
00047
00048         try
00049         {
00050             SmartCard card = co_await GetSmartCardAsync();
00051             SmartCardProvisioning provisioning = co_await Windows::Devices::SmartCards::SmartCardProvisioning::FromSmartCardAsync(card);
00052
00053             m_rootPage.NotifyUser(L"Changing smart card PIN...", NotifyType::StatusMessage);
00054
00055             bool result = co_await provisioning.RequestPinChangeAsync();
00056
00057             if (result)
00058             {
00059                 m_rootPage.NotifyUser(L"Smart card change PIN operation completed.", NotifyType::StatusMessage);
00060             }
00061             else
00062             {
00063                 m_rootPage.NotifyUser(L"Smart card change PIN operation was canceled by the user.", NotifyType::StatusMessage);
00064             }
00065         }
00066         catch (hresult_error const& ex)
00067         {
00068             m_rootPage.NotifyUser(L"Changing smart card PIN failed with exception: " + ex.message(), NotifyType::ErrorMessage);
00069         }
00070
00071         b.IsEnabled(true);
00072     }
00073 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cpp/Scenario4_Control.xaml.cpp Source File

  • XamlCommanding
  • cpp

Scenario4_Control.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario4_Control.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Primitives;
00023 using namespace Windows::UI::Xaml::Data;
00024 using namespace Windows::UI::Xaml::Input;
00025 using namespace Windows::UI::Xaml::Media;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00029
00030 Scenario4_Control::Scenario4_Control()
00031 {
00032     InitializeComponent();
00033 }
Generated on Fri Nov 15 2024 22:22:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario8_UpdateAsync Member List

This is the complete list of members for Scenario8_UpdateAsync, including all inherited members.
Scenario8_UpdateAsync() | Scenario8_UpdateAsync
UpdateDefaultLogo_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario8_UpdateAsync
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/StereoProjection.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

StereoProjection.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 typedef struct STEREO_PARAMETERS
00015 {
00016     float viewerDistanceInches;
00017     float displaySizeInches;
00018     float pixelResolutionWidth;
00019     float pixelResolutionHeight;
00020     float stereoSeparationFactor;
00021     float stereoExaggerationFactor;
00022 } STEREO_PARAMETERS;
00023
00024 // Enumeration for stereo channels (left and right).
00025 typedef enum class STEREO_CHANNEL
00026 {
00027     LEFT = 0,
00028     RIGHT
00029 } STEREO_CHANNEL;
00030
00031 // Enumeration for stereo mode (normal or inverted).
00032 typedef enum class STEREO_MODE
00033 {
00034     NORMAL = 0,
00035     INVERTED,
00036 } STEREO_MODE;
00037
00038 void StereoCreateDefaultParameters(_Out_ STEREO_PARAMETERS* pStereoParameters);
00039
00040 DirectX::XMMATRIX MatrixStereoProjectionFovLH(
00041     _In_opt_ const STEREO_PARAMETERS* stereoParameters,
00042     STEREO_CHANNEL channel,
00043     float fovAngleY,
00044     float aspectHByW,
00045     float nearZ,
00046     float farZ,
00047     STEREO_MODE stereoMode
00048     );
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Matrix4x4< T > Member List

This is the complete list of members for Matrix4x4< T >, including all inherited members.
_11 | Matrix4x4< T > |
_12 | Matrix4x4< T > |
_13 | Matrix4x4< T > |
_14 | Matrix4x4< T > |
_21 | Matrix4x4< T > |
_22 | Matrix4x4< T > |
_23 | Matrix4x4< T > |
_24 | Matrix4x4< T > |
_31 | Matrix4x4< T > |
_32 | Matrix4x4< T > |
_33 | Matrix4x4< T > |
_34 | Matrix4x4< T > |
_41 | Matrix4x4< T > |
_42 | Matrix4x4< T > |
_43 | Matrix4x4< T > |
_44 | Matrix4x4< T > |
_m00 | Matrix4x4< T > |
_m01 | Matrix4x4< T > |
_m02 | Matrix4x4< T > |
_m03 | Matrix4x4< T > |
_m10 | Matrix4x4< T > |
_m11 | Matrix4x4< T > |
_m12 | Matrix4x4< T > |
_m13 | Matrix4x4< T > |
_m20 | Matrix4x4< T > |
_m21 | Matrix4x4< T > |
_m22 | Matrix4x4< T > |
_m23 | Matrix4x4< T > |
_m30 | Matrix4x4< T > |
_m31 | Matrix4x4< T > |
_m32 | Matrix4x4< T > |
_m33 | Matrix4x4< T > |
Matrix4x4(T value=0) | Matrix4x4< T > | [inline]
Matrix4x4(T i11, T i12, T i13, T i14, T i21, T i22, T i23, T i24, T i31, T i32, T i33, T i34, T i41, T i42, T i43, T i44) | Matrix4x4< T > | [inline]
Matrix4x4(T value=0) | Matrix4x4< T > | [inline]
Matrix4x4(T i11, T i12, T i13, T i14, T i21, T i22, T i23, T i24, T i31, T i32, T i33, T i34, T i41, T i42, T i43, T i44) | Matrix4x4< T > | [inline]
Matrix4x4(T value=0) | Matrix4x4< T > | [inline]
Matrix4x4(T i11, T i12, T i13, T i14, T i21, T i22, T i23, T i24, T i31, T i32, T i33, T i34, T i41, T i42, T i43, T i44) | Matrix4x4< T > | [inline]
onebased | Matrix4x4< T > |
operator[](unsigned int index) | Matrix4x4< T > | [inline]
operator[](unsigned int index) | Matrix4x4< T > | [inline]
operator[](unsigned int index) | Matrix4x4< T > | [inline]
zerobased | Matrix4x4< T > |
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cpp/BackgroundTransfer/pch.h Source File

  • BackgroundTransfer
  • cpp
  • BackgroundTransfer

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020
00021 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_InteractionFeedback Member List

This is the complete list of members for Scenario4_InteractionFeedback, including all inherited members.
currentFeedback | Scenario4_InteractionFeedback | [private]
GetSelectedFeedbackOrFallback(out string message) | Scenario4_InteractionFeedback | [inline, private]
hapticsController | Scenario4_InteractionFeedback | [private]
MainGrid_Entered(object sender, PointerRoutedEventArgs e) | Scenario4_InteractionFeedback | [inline, private]
MainGrid_Exited(object sender, PointerRoutedEventArgs e) | Scenario4_InteractionFeedback | [inline, private]
penDevice | Scenario4_InteractionFeedback | [private]
Scenario4_InteractionFeedback() | Scenario4_InteractionFeedback | [inline]
SendFeedback_Clicked(object sender, RoutedEventArgs e) | Scenario4_InteractionFeedback | [inline, private]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6_TimeZone Member List

This is the complete list of members for Scenario6_TimeZone, including all inherited members.
Display_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario6_TimeZone
Scenario6_TimeZone() | Scenario6_TimeZone
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_UIFonts Member List

This is the complete list of members for Scenario1_UIFonts, including all inherited members.
ApplyFonts_Click(object sender, RoutedEventArgs e) | Scenario1_UIFonts | [inline, private]
Scenario1_UIFonts() | Scenario1_UIFonts | [inline]
Generated on Fri Nov 15 2024 22:23:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cs/Scenario4_InteractionFeedback.xaml.cs Source File

  • PenHaptics
  • cs

Scenario4_InteractionFeedback.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.Devices.Haptics;
00013 using Windows.Devices.Input;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Input;
00017
00018 // This sample shows how to play Interaction feedback tactile signals, how to
00019 // adjust the intensity of the tactile signal, and how to fall back to a default
00020 // waveform if the desired waveform is not supported by the current PenDevice
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario4_InteractionFeedback : Page
00024     {
00025         SimpleHapticsController hapticsController;
00026         PenDevice penDevice;
00027         SimpleHapticsControllerFeedback currentFeedback;
00028
00029         public Scenario4_InteractionFeedback()
00030         {
00031             InitializeComponent();
00032         }
00033
00034         // The PointerEnter event will get fired as soon as Pointer input is received.
00035         // This event handler implementation will query the device providing input to see if it's a pen and
00036         // then check to see the pen supports tactile feedback
00037         private void MainGrid_Entered(object sender, PointerRoutedEventArgs e)
00038         {
00039             // If the current Pointer device is not a pen, exit
00040             if (e.Pointer.PointerDeviceType != PointerDeviceType.Pen)
00041             {
00042                 return;
00043             }
00044
00045             // Attempt to retrieve the PenDevice from the current PointerId
00046             penDevice = PenDevice.GetFromPointerId(e.Pointer.PointerId);
00047
00048             // If a PenDevice cannot be retrieved based on the PointerId, it does not support
00049             // advanced pen features, such as tactile feedback
00050             if (penDevice == null)
00051             {
00052                 statusText.Text = "Advanced pen features not supported";
00053                 return;
00054             }
00055
00056             // Check to see if the current PenDevice supports tactile feedback by seeing if it
00057             // has a SimpleHapticsController
00058             hapticsController = penDevice.SimpleHapticsController;
00059             if (hapticsController == null)
00060             {
00061                 statusText.Text = "This pen does not provide tactile feedback";
00062                 return;
00063             }
00064         }
00065
00066         // Stop sending the tactile feedback and clear the current penDevice and hapticsController on PointerExit.
00067         // Stopping the feedback is important as it clears the tactile signal from the PenDevice's
00068         // SimpleHapticsController, ensuring that it has a clean state once it next enters range.
00069         private void MainGrid_Exited(object sender, PointerRoutedEventArgs e)
00070         {
00071             penDevice = null;
00072             statusText.Text = "";
00073             if (hapticsController != null)
00074             {
00075                 hapticsController.StopFeedback();
00076                 hapticsController = null;
00077                 currentFeedback = null;
00078             }
00079         }
00080
00081         // Send haptic feedback that matches the selected waveform upon the button being clicked
00082         private void SendFeedback_Clicked(object sender, RoutedEventArgs e)
00083         {
00084             if (hapticsController == null)
00085             {
00086                 return;
00087             }
00088
00089             // Get feedback based on the user's selected waveform
00090             currentFeedback = GetSelectedFeedbackOrFallback(out string message);
00091
00092             // Send the current feedback to the PenDevice's SimpleHapticsController.
00093             // Once sent, unlike inking feedback, this feedback will be played immediately.
00094             // Also, check to see if the current PenDevice's SimpleHapticsController supports
00095             // setting the intensity value of the tactile feedback.  If so, set it based
00096             // on the slider.  If not, send the feedback without custom intensity.
00097             if (hapticsController.IsIntensitySupported)
00098             {
00099                 hapticsController.SendHapticFeedback(currentFeedback, intensitySlider.Value / 100);
00100                 message += "\nIntensity set to " + intensitySlider.Value + "%";
00101             }
00102             else
00103             {
00104                 hapticsController.SendHapticFeedback(currentFeedback);
00105                 message += "\nSetting intensity is not supported by this pen";
00106             }
00107             statusText.Text = message;
00108         }
00109
00110         // Get feedback which matches the currently selected waveform in the dropdown.
00111         // To get the feedback, the SimpleHapticsController's SupportedFeedback list must be traversed
00112         // to see if a matching feedback is present.
00113         // This is important because Click is the only Interaction waveform required to be
00114         // supported by every pen with haptics.
00115         // If no matching feedback is found in the SupportedFeedback list, this method returns
00116         // Click as a guaranteed fallback.
00117         private SimpleHapticsControllerFeedback GetSelectedFeedbackOrFallback(out string message)
00118         {
00119             // Look up the waveform the user selected.
00120             string name = (string)waveformComboBox.SelectionBoxItem;
00121             ushort waveform = MainPage.WaveformNamesMap[name];
00122
00123             // See if the haptics controller supports the selected waveform.
00124             SimpleHapticsControllerFeedback feedback = MainPage.FindSupportedFeedback(hapticsController, waveform);
00125             if (feedback != null)
00126             {
00127                 message = "Waveform set to " + name;
00128                 return feedback;
00129             }
00130
00131             // It does not. Use Click as a fallback.
00132             message = name + " is not supported by this pen, so falling back to Click";
00133             return MainPage.FindSupportedFeedback(hapticsController, KnownSimpleHapticsControllerWaveforms.Click);
00134         }
00135     }
00136 }
Generated on Fri Nov 15 2024 22:20:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_InteractionFeedback Member List

This is the complete list of members for Scenario4_InteractionFeedback, including all inherited members.
GetSelectedFeedbackOrFallback(std::wstring &message) | Scenario4_InteractionFeedback | [private]
MainGrid_Entered(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::Input::PointerRoutedEventArgs const &e) | Scenario4_InteractionFeedback |
MainGrid_Exited(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::Input::PointerRoutedEventArgs const &e) | Scenario4_InteractionFeedback |
Scenario4_InteractionFeedback() | Scenario4_InteractionFeedback |
SendFeedback_Clicked(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario4_InteractionFeedback |
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundSensors/cpp/Scenario1_DeviceUse.xaml.h Source File

  • BackgroundSensors
  • cpp

Scenario1_DeviceUse.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario1_DeviceUse.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario1_DeviceUse sealed
00012     {
00013     public:
00014         Scenario1_DeviceUse();
00015         virtual ~Scenario1_DeviceUse();
00016
00017     private:
00018         void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00019
00020         void ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021
00022         void ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00023
00024         Concurrency::task<bool> StartSensorBackgroundTaskAsync(Platform::String^ deviceId);
00025
00026         void FindAndCancelExistingBackgroundTask();
00027
00028         void RefreshTimer_Tick(Platform::Object^ sender, Platform::Object^ e);
00029
00030         void OnBackgroundTaskCompleted(
00031             Windows::ApplicationModel::Background::BackgroundTaskRegistration^ sender,
00032             Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ e);
00033
00034     private:
00035         MainPage^ rootPage;
00036
00037         // Used for requesting a DeviceUse trigger task to receive accelerometer data.
00038         Windows::Devices::Sensors::Accelerometer^ _accelerometer;
00039
00040         // Used to trigger the DeviceUse background task that consumes the accelerometer.
00041         Windows::ApplicationModel::Background::DeviceUseTrigger^ _deviceUseTrigger;
00042
00043         // Used to register the device use background task.
00044         Windows::ApplicationModel::Background::BackgroundTaskRegistration^ _deviceUseBackgroundTaskRegistration;
00045
00046         // Used for refreshing the number of samples received when the app is visible.
00047         Windows::UI::Xaml::DispatcherTimer^ _refreshTimer;
00048
00049         // Used for unregistering from the VisibilityChanged event.
00050         Windows::Foundation::EventRegistrationToken _visibilityToken;
00051
00052         // Used for unregistering from the background task completion event.
00053         Windows::Foundation::EventRegistrationToken _taskCompletionToken;
00054     };
00055 }
Generated on Fri Nov 15 2024 22:18:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/Common/BasicLoader.cpp Source File

  • Simple3DGameXaml
  • cpp
  • Common

BasicLoader.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "BasicLoader.h"
00010 #include "BasicShapes.h"
00011 #include "DDSTextureLoader.h"
00012 #include "DirectXSample.h"
00013 #include <memory>
00014
00015 using namespace Microsoft::WRL;
00016 using namespace Windows::Storage;
00017 using namespace Windows::Storage::Streams;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::ApplicationModel;
00020 using namespace std;
00021 using namespace concurrency;
00022
00023 BasicLoader::BasicLoader(
00024     _In_ ID3D11Device* d3dDevice,
00025     _In_opt_ IWICImagingFactory2* wicFactory
00026     ) :
00027     m_d3dDevice(d3dDevice),
00028     m_wicFactory(wicFactory)
00029 {
00030     // Create a new BasicReaderWriter to do raw file I/O.
00031     m_basicReaderWriter = ref new BasicReaderWriter();
00032 }
00033
00034 template <class DeviceChildType>
00035 inline void BasicLoader::SetDebugName(
00036     _In_ DeviceChildType* object,
00037     _In_ Platform::String^ name
00038     )
00039 {
00040 #if defined(_DEBUG)
00041     // Only assign debug names in debug builds.
00042
00043     char nameString[1024];
00044     int nameStringLength = WideCharToMultiByte(
00045         CP_ACP,
00046         0,
00047         name->Data(),
00048         -1,
00049         nameString,
00050         1024,
00051         nullptr,
00052         nullptr
00053         );
00054
00055     if (nameStringLength == 0)
00056     {
00057         char defaultNameString[] = "BasicLoaderObject";
00058         DX::ThrowIfFailed(
00059             object->SetPrivateData(
00060                 WKPDID_D3DDebugObjectName,
00061                 sizeof(defaultNameString) - 1,
00062                 defaultNameString
00063                 )
00064             );
00065     }
00066     else
00067     {
00068         DX::ThrowIfFailed(
00069             object->SetPrivateData(
00070                 WKPDID_D3DDebugObjectName,
00071                 nameStringLength - 1,
00072                 nameString
00073                 )
00074             );
00075     }
00076 #endif
00077 }
00078
00079 Platform::String^ BasicLoader::GetExtension(
00080     _In_ Platform::String^ filename
00081     )
00082 {
00083     int lastDotIndex = -1;
00084     for (int i = filename->Length() - 1; i >= 0 && lastDotIndex == -1; i--)
00085     {
00086         if (*(filename->Data() + i) == '.')
00087         {
00088             lastDotIndex = i;
00089         }
00090     }
00091     if (lastDotIndex != -1)
00092     {
00093         std::unique_ptr<wchar_t[]> extension(new wchar_t[filename->Length() - lastDotIndex]);
00094         for (unsigned int i = 0; i < filename->Length() - lastDotIndex; i++)
00095         {
00096             extension[i] = tolower(*(filename->Data() + lastDotIndex + 1 + i));
00097         }
00098         return ref new Platform::String(extension.get());
00099     }
00100     return "";
00101 }
00102
00103 void BasicLoader::CreateTexture(
00104     _In_ bool decodeAsDDS,
00105     _In_reads_bytes_(dataSize) byte* data,
00106     _In_ uint32 dataSize,
00107     _Out_opt_ ID3D11Texture2D** texture,
00108     _Out_opt_ ID3D11ShaderResourceView** textureView,
00109     _In_opt_ Platform::String^ debugName
00110     )
00111 {
00112     ComPtr<ID3D11ShaderResourceView> shaderResourceView;
00113     ComPtr<ID3D11Texture2D> texture2D;
00114
00115     if (decodeAsDDS)
00116     {
00117         ComPtr<ID3D11Resource> resource;
00118
00119         if (textureView == nullptr)
00120         {
00121             CreateDDSTextureFromMemory(
00122                 m_d3dDevice.Get(),
00123                 data,
00124                 dataSize,
00125                 &resource,
00126                 nullptr
00127                 );
00128         }
00129         else
00130         {
00131             CreateDDSTextureFromMemory(
00132                 m_d3dDevice.Get(),
00133                 data,
00134                 dataSize,
00135                 &resource,
00136                 &shaderResourceView
00137                 );
00138         }
00139
00140         DX::ThrowIfFailed(
00141             resource.As(&texture2D)
00142             );
00143     }
00144     else
00145     {
00146         if (m_wicFactory.Get() == nullptr)
00147         {
00148             // A WIC factory object is required in order to load texture
00149             // assets stored in non-DDS formats.  If BasicLoader was not
00150             // initialized with one, create one as needed.
00151             DX::ThrowIfFailed(
00152                 CoCreateInstance(
00153                     CLSID_WICImagingFactory,
00154                     nullptr,
00155                     CLSCTX_INPROC_SERVER,
00156                     IID_PPV_ARGS(&m_wicFactory)
00157                     )
00158                 );
00159         }
00160
00161         ComPtr<IWICStream> stream;
00162         DX::ThrowIfFailed(
00163             m_wicFactory->CreateStream(&stream)
00164             );
00165
00166         DX::ThrowIfFailed(
00167             stream->InitializeFromMemory(
00168                 data,
00169                 dataSize
00170                 )
00171             );
00172
00173         ComPtr<IWICBitmapDecoder> bitmapDecoder;
00174         DX::ThrowIfFailed(
00175             m_wicFactory->CreateDecoderFromStream(
00176                 stream.Get(),
00177                 nullptr,
00178                 WICDecodeMetadataCacheOnDemand,
00179                 &bitmapDecoder
00180                 )
00181             );
00182
00183         ComPtr<IWICBitmapFrameDecode> bitmapFrame;
00184         DX::ThrowIfFailed(
00185             bitmapDecoder->GetFrame(0, &bitmapFrame)
00186             );
00187
00188         ComPtr<IWICFormatConverter> formatConverter;
00189         DX::ThrowIfFailed(
00190             m_wicFactory->CreateFormatConverter(&formatConverter)
00191             );
00192
00193         DX::ThrowIfFailed(
00194             formatConverter->Initialize(
00195                 bitmapFrame.Get(),
00196                 GUID_WICPixelFormat32bppPBGRA,
00197                 WICBitmapDitherTypeNone,
00198                 nullptr,
00199                 0.0,
00200                 WICBitmapPaletteTypeCustom
00201                 )
00202             );
00203
00204         uint32 width;
00205         uint32 height;
00206         DX::ThrowIfFailed(
00207             bitmapFrame->GetSize(&width, &height)
00208             );
00209
00210         std::unique_ptr<byte[]> bitmapPixels(new byte[width * height * 4]);
00211         DX::ThrowIfFailed(
00212             formatConverter->CopyPixels(
00213                 nullptr,
00214                 width * 4,
00215                 width * height * 4,
00216                 bitmapPixels.get()
00217                 )
00218             );
00219
00220         D3D11_SUBRESOURCE_DATA initialData;
00221         ZeroMemory(&initialData, sizeof(initialData));
00222         initialData.pSysMem = bitmapPixels.get();
00223         initialData.SysMemPitch = width * 4;
00224         initialData.SysMemSlicePitch = 0;
00225
00226         CD3D11_TEXTURE2D_DESC textureDesc(
00227             DXGI_FORMAT_B8G8R8A8_UNORM,
00228             width,
00229             height,
00230             1,
00231             1
00232             );
00233
00234         DX::ThrowIfFailed(
00235             m_d3dDevice->CreateTexture2D(
00236                 &textureDesc,
00237                 &initialData,
00238                 &texture2D
00239                 )
00240             );
00241
00242         if (textureView != nullptr)
00243         {
00244             CD3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc(
00245                 texture2D.Get(),
00246                 D3D11_SRV_DIMENSION_TEXTURE2D
00247                 );
00248
00249             DX::ThrowIfFailed(
00250                 m_d3dDevice->CreateShaderResourceView(
00251                     texture2D.Get(),
00252                     &shaderResourceViewDesc,
00253                     &shaderResourceView
00254                     )
00255                 );
00256         }
00257     }
00258
00259     SetDebugName(texture2D.Get(), debugName);
00260
00261     if (texture != nullptr)
00262     {
00263         *texture = texture2D.Detach();
00264     }
00265     if (textureView != nullptr)
00266     {
00267         *textureView = shaderResourceView.Detach();
00268     }
00269 }
00270
00271 void BasicLoader::CreateInputLayout(
00272     _In_reads_bytes_(bytecodeSize) byte* bytecode,
00273     _In_ uint32 bytecodeSize,
00274     _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC* layoutDesc,
00275     _In_ uint32 layoutDescNumElements,
00276     _Out_ ID3D11InputLayout** layout
00277     )
00278 {
00279     if (layoutDesc == nullptr)
00280     {
00281         // If no input layout is specified, use the BasicVertex layout.
00282         const D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] =
00283         {
00284             { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,  D3D11_INPUT_PER_VERTEX_DATA, 0 },
00285             { "NORMAL",   0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00286             { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,    0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00287         };
00288
00289         DX::ThrowIfFailed(
00290             m_d3dDevice->CreateInputLayout(
00291                 basicVertexLayoutDesc,
00292                 ARRAYSIZE(basicVertexLayoutDesc),
00293                 bytecode,
00294                 bytecodeSize,
00295                 layout
00296                 )
00297             );
00298     }
00299     else
00300     {
00301         DX::ThrowIfFailed(
00302             m_d3dDevice->CreateInputLayout(
00303                 layoutDesc,
00304                 layoutDescNumElements,
00305                 bytecode,
00306                 bytecodeSize,
00307                 layout
00308                 )
00309             );
00310     }
00311 }
00312
00313 void BasicLoader::CreateMesh(
00314     _In_ byte* meshData,
00315     _Out_ ID3D11Buffer** vertexBuffer,
00316     _Out_ ID3D11Buffer** indexBuffer,
00317     _Out_opt_ uint32* vertexCount,
00318     _Out_opt_ uint32* indexCount,
00319     _In_opt_ Platform::String^ debugName
00320     )
00321 {
00322     // The first 4 bytes of the BasicMesh format define the number of vertices in the mesh.
00323     uint32 numVertices = *reinterpret_cast<uint32*>(meshData);
00324
00325     // The following 4 bytes define the number of indices in the mesh.
00326     uint32 numIndices = *reinterpret_cast<uint32*>(meshData + sizeof(uint32));
00327
00328     // The next segment of the BasicMesh format contains the vertices of the mesh.
00329     BasicVertex* vertices = reinterpret_cast<BasicVertex*>(meshData + sizeof(uint32) * 2);
00330
00331     // The last segment of the BasicMesh format contains the indices of the mesh.
00332     uint16* indices = reinterpret_cast<uint16*>(meshData + sizeof(uint32) * 2 + sizeof(BasicVertex) * numVertices);
00333
00334     // Create the vertex and index buffers with the mesh data.
00335
00336     D3D11_SUBRESOURCE_DATA vertexBufferData = {0};
00337     vertexBufferData.pSysMem = vertices;
00338     vertexBufferData.SysMemPitch = 0;
00339     vertexBufferData.SysMemSlicePitch = 0;
00340     CD3D11_BUFFER_DESC vertexBufferDesc(numVertices * sizeof(BasicVertex), D3D11_BIND_VERTEX_BUFFER);
00341     DX::ThrowIfFailed(
00342         m_d3dDevice->CreateBuffer(
00343             &vertexBufferDesc,
00344             &vertexBufferData,
00345             vertexBuffer
00346             )
00347         );
00348
00349     D3D11_SUBRESOURCE_DATA indexBufferData = {0};
00350     indexBufferData.pSysMem = indices;
00351     indexBufferData.SysMemPitch = 0;
00352     indexBufferData.SysMemSlicePitch = 0;
00353     CD3D11_BUFFER_DESC indexBufferDesc(numIndices * sizeof(uint16), D3D11_BIND_INDEX_BUFFER);
00354     DX::ThrowIfFailed(
00355         m_d3dDevice->CreateBuffer(
00356             &indexBufferDesc,
00357             &indexBufferData,
00358             indexBuffer
00359             )
00360         );
00361
00362     SetDebugName(*vertexBuffer, Platform::String::Concat(debugName, "_VertexBuffer"));
00363     SetDebugName(*indexBuffer, Platform::String::Concat(debugName, "_IndexBuffer"));
00364
00365     if (vertexCount != nullptr)
00366     {
00367         *vertexCount = numVertices;
00368     }
00369     if (indexCount != nullptr)
00370     {
00371         *indexCount = numIndices;
00372     }
00373 }
00374
00375 void BasicLoader::LoadTexture(
00376     _In_ Platform::String^ filename,
00377     _Out_opt_ ID3D11Texture2D** texture,
00378     _Out_opt_ ID3D11ShaderResourceView** textureView
00379     )
00380 {
00381     Platform::Array<byte>^ textureData = m_basicReaderWriter->ReadData(filename);
00382
00383     CreateTexture(
00384         GetExtension(filename) == "dds",
00385         textureData->Data,
00386         textureData->Length,
00387         texture,
00388         textureView,
00389         filename
00390         );
00391 }
00392
00393 task<void> BasicLoader::LoadTextureAsync(
00394     _In_ Platform::String^ filename,
00395     _Out_opt_ ID3D11Texture2D** texture,
00396     _Out_opt_ ID3D11ShaderResourceView** textureView
00397     )
00398 {
00399     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ textureData)
00400     {
00401         CreateTexture(
00402             GetExtension(filename) == "dds",
00403             textureData->Data,
00404             textureData->Length,
00405             texture,
00406             textureView,
00407             filename
00408             );
00409     });
00410 }
00411
00412 void BasicLoader::LoadShader(
00413     _In_ Platform::String^ filename,
00414     _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[],
00415     _In_ uint32 layoutDescNumElements,
00416     _Out_ ID3D11VertexShader** shader,
00417     _Out_opt_ ID3D11InputLayout** layout
00418     )
00419 {
00420     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00421
00422     DX::ThrowIfFailed(
00423         m_d3dDevice->CreateVertexShader(
00424             bytecode->Data,
00425             bytecode->Length,
00426             nullptr,
00427             shader
00428             )
00429         );
00430
00431     SetDebugName(*shader, filename);
00432
00433     if (layout != nullptr)
00434     {
00435         CreateInputLayout(
00436             bytecode->Data,
00437             bytecode->Length,
00438             layoutDesc,
00439             layoutDescNumElements,
00440             layout
00441             );
00442
00443         SetDebugName(*layout, filename);
00444     }
00445 }
00446
00447 task<void> BasicLoader::LoadShaderAsync(
00448     _In_ Platform::String^ filename,
00449     _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[],
00450     _In_ uint32 layoutDescNumElements,
00451     _Out_ ID3D11VertexShader** shader,
00452     _Out_opt_ ID3D11InputLayout** layout
00453     )
00454 {
00455     // This method assumes that the lifetime of input arguments may be shorter
00456     // than the duration of this task.  In order to ensure accurate results, a
00457     // copy of all arguments passed by pointer must be made.  The method then
00458     // ensures that the lifetime of the copied data exceeds that of the task.
00459
00460     // Create copies of the layoutDesc array as well as the SemanticName strings,
00461     // both of which are pointers to data whose lifetimes may be shorter than that
00462     // of this method's task.
00463     shared_ptr<vector<D3D11_INPUT_ELEMENT_DESC>> layoutDescCopy;
00464     shared_ptr<vector<string>> layoutDescSemanticNamesCopy;
00465     if (layoutDesc != nullptr)
00466     {
00467         layoutDescCopy.reset(
00468             new vector<D3D11_INPUT_ELEMENT_DESC>(
00469                 layoutDesc,
00470                 layoutDesc + layoutDescNumElements
00471                 )
00472             );
00473
00474         layoutDescSemanticNamesCopy.reset(
00475             new vector<string>(layoutDescNumElements)
00476             );
00477
00478         for (uint32 i = 0; i < layoutDescNumElements; i++)
00479         {
00480             layoutDescSemanticNamesCopy->at(i).assign(layoutDesc[i].SemanticName);
00481         }
00482     }
00483
00484     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00485     {
00486         DX::ThrowIfFailed(
00487             m_d3dDevice->CreateVertexShader(
00488                 bytecode->Data,
00489                 bytecode->Length,
00490                 nullptr,
00491                 shader
00492                 )
00493             );
00494
00495         SetDebugName(*shader, filename);
00496
00497         if (layout != nullptr)
00498         {
00499             if (layoutDesc != nullptr)
00500             {
00501                 // Reassign the SemanticName elements of the layoutDesc array copy to point
00502                 // to the corresponding copied strings. Performing the assignment inside the
00503                 // lambda body ensures that the lambda will take a reference to the shared_ptr
00504                 // that holds the data.  This will guarantee that the data is still valid when
00505                 // CreateInputLayout is called.
00506                 for (uint32 i = 0; i < layoutDescNumElements; i++)
00507                 {
00508                     layoutDescCopy->at(i).SemanticName = layoutDescSemanticNamesCopy->at(i).c_str();
00509                 }
00510             }
00511
00512             CreateInputLayout(
00513                 bytecode->Data,
00514                 bytecode->Length,
00515                 layoutDesc == nullptr ? nullptr : layoutDescCopy->data(),
00516                 layoutDescNumElements,
00517                 layout
00518                 );
00519
00520             SetDebugName(*layout, filename);
00521         }
00522     });
00523 }
00524
00525 void BasicLoader::LoadShader(
00526     _In_ Platform::String^ filename,
00527     _Out_ ID3D11PixelShader** shader
00528     )
00529 {
00530     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00531
00532     DX::ThrowIfFailed(
00533         m_d3dDevice->CreatePixelShader(
00534             bytecode->Data,
00535             bytecode->Length,
00536             nullptr,
00537             shader
00538             )
00539         );
00540
00541     SetDebugName(*shader, filename);
00542 }
00543
00544 task<void> BasicLoader::LoadShaderAsync(
00545     _In_ Platform::String^ filename,
00546     _Out_ ID3D11PixelShader** shader
00547     )
00548 {
00549     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00550     {
00551         DX::ThrowIfFailed(
00552             m_d3dDevice->CreatePixelShader(
00553                 bytecode->Data,
00554                 bytecode->Length,
00555                 nullptr,
00556                 shader
00557                 )
00558             );
00559
00560         SetDebugName(*shader, filename);
00561     });
00562 }
00563
00564 void BasicLoader::LoadShader(
00565     _In_ Platform::String^ filename,
00566     _Out_ ID3D11ComputeShader** shader
00567     )
00568 {
00569     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00570
00571     DX::ThrowIfFailed(
00572         m_d3dDevice->CreateComputeShader(
00573             bytecode->Data,
00574             bytecode->Length,
00575             nullptr,
00576             shader
00577             )
00578         );
00579
00580     SetDebugName(*shader, filename);
00581 }
00582
00583 task<void> BasicLoader::LoadShaderAsync(
00584     _In_ Platform::String^ filename,
00585     _Out_ ID3D11ComputeShader** shader
00586     )
00587 {
00588     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00589     {
00590         DX::ThrowIfFailed(
00591             m_d3dDevice->CreateComputeShader(
00592                 bytecode->Data,
00593                 bytecode->Length,
00594                 nullptr,
00595                 shader
00596                 )
00597             );
00598
00599         SetDebugName(*shader, filename);
00600     });
00601 }
00602
00603 void BasicLoader::LoadShader(
00604     _In_ Platform::String^ filename,
00605     _Out_ ID3D11GeometryShader** shader
00606     )
00607 {
00608     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00609
00610     DX::ThrowIfFailed(
00611         m_d3dDevice->CreateGeometryShader(
00612             bytecode->Data,
00613             bytecode->Length,
00614             nullptr,
00615             shader
00616             )
00617         );
00618
00619     SetDebugName(*shader, filename);
00620 }
00621
00622 task<void> BasicLoader::LoadShaderAsync(
00623     _In_ Platform::String^ filename,
00624     _Out_ ID3D11GeometryShader** shader
00625     )
00626 {
00627     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00628     {
00629         DX::ThrowIfFailed(
00630             m_d3dDevice->CreateGeometryShader(
00631                 bytecode->Data,
00632                 bytecode->Length,
00633                 nullptr,
00634                 shader
00635                 )
00636             );
00637
00638         SetDebugName(*shader, filename);
00639     });
00640 }
00641
00642 void BasicLoader::LoadShader(
00643     _In_ Platform::String^ filename,
00644     _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration,
00645     _In_ uint32 numEntries,
00646     _In_reads_opt_(numStrides) const uint32* bufferStrides,
00647     _In_ uint32 numStrides,
00648     _In_ uint32 rasterizedStream,
00649     _Out_ ID3D11GeometryShader** shader
00650     )
00651 {
00652     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00653
00654     DX::ThrowIfFailed(
00655         m_d3dDevice->CreateGeometryShaderWithStreamOutput(
00656             bytecode->Data,
00657             bytecode->Length,
00658             streamOutDeclaration,
00659             numEntries,
00660             bufferStrides,
00661             numStrides,
00662             rasterizedStream,
00663             nullptr,
00664             shader
00665             )
00666         );
00667
00668     SetDebugName(*shader, filename);
00669 }
00670
00671 task<void> BasicLoader::LoadShaderAsync(
00672     _In_ Platform::String^ filename,
00673     _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration,
00674     _In_ uint32 numEntries,
00675     _In_reads_opt_(numStrides) const uint32* bufferStrides,
00676     _In_ uint32 numStrides,
00677     _In_ uint32 rasterizedStream,
00678     _Out_ ID3D11GeometryShader** shader
00679     )
00680 {
00681     // This method assumes that the lifetime of input arguments may be shorter
00682     // than the duration of this task.  In order to ensure accurate results, a
00683     // copy of all arguments passed by pointer must be made.  The method then
00684     // ensures that the lifetime of the copied data exceeds that of the task.
00685
00686     // Create copies of the streamOutDeclaration array as well as the SemanticName
00687     // strings, both of which are pointers to data whose lifetimes may be shorter
00688     // than that of this method's task.
00689     shared_ptr<vector<D3D11_SO_DECLARATION_ENTRY>> streamOutDeclarationCopy;
00690     shared_ptr<vector<string>> streamOutDeclarationSemanticNamesCopy;
00691     if (streamOutDeclaration != nullptr)
00692     {
00693         streamOutDeclarationCopy.reset(
00694             new vector<D3D11_SO_DECLARATION_ENTRY>(
00695                 streamOutDeclaration,
00696                 streamOutDeclaration + numEntries
00697                 )
00698             );
00699
00700         streamOutDeclarationSemanticNamesCopy.reset(
00701             new vector<string>(numEntries)
00702             );
00703
00704         for (uint32 i = 0; i < numEntries; i++)
00705         {
00706             streamOutDeclarationSemanticNamesCopy->at(i).assign(streamOutDeclaration[i].SemanticName);
00707         }
00708     }
00709
00710     // Create a copy of the bufferStrides array, which is a pointer to data
00711     // whose lifetime may be shorter than that of this method's task.
00712     shared_ptr<vector<uint32>> bufferStridesCopy;
00713     if (bufferStrides != nullptr)
00714     {
00715         bufferStridesCopy.reset(
00716             new vector<uint32>(
00717                 bufferStrides,
00718                 bufferStrides + numStrides
00719                 )
00720             );
00721     }
00722
00723     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00724     {
00725         if (streamOutDeclaration != nullptr)
00726         {
00727             // Reassign the SemanticName elements of the streamOutDeclaration array copy to
00728             // point to the corresponding copied strings. Performing the assignment inside the
00729             // lambda body ensures that the lambda will take a reference to the shared_ptr
00730             // that holds the data.  This will guarantee that the data is still valid when
00731             // CreateGeometryShaderWithStreamOutput is called.
00732             for (uint32 i = 0; i < numEntries; i++)
00733             {
00734                 streamOutDeclarationCopy->at(i).SemanticName = streamOutDeclarationSemanticNamesCopy->at(i).c_str();
00735             }
00736         }
00737
00738         DX::ThrowIfFailed(
00739             m_d3dDevice->CreateGeometryShaderWithStreamOutput(
00740                 bytecode->Data,
00741                 bytecode->Length,
00742                 streamOutDeclaration == nullptr ? nullptr : streamOutDeclarationCopy->data(),
00743                 numEntries,
00744                 bufferStrides == nullptr ? nullptr : bufferStridesCopy->data(),
00745                 numStrides,
00746                 rasterizedStream,
00747                 nullptr,
00748                 shader
00749                 )
00750             );
00751
00752         SetDebugName(*shader, filename);
00753     });
00754 }
00755
00756 void BasicLoader::LoadShader(
00757     _In_ Platform::String^ filename,
00758     _Out_ ID3D11HullShader** shader
00759     )
00760 {
00761     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00762
00763     DX::ThrowIfFailed(
00764         m_d3dDevice->CreateHullShader(
00765             bytecode->Data,
00766             bytecode->Length,
00767             nullptr,
00768             shader
00769             )
00770         );
00771
00772     SetDebugName(*shader, filename);
00773 }
00774
00775 task<void> BasicLoader::LoadShaderAsync(
00776     _In_ Platform::String^ filename,
00777     _Out_ ID3D11HullShader** shader
00778     )
00779 {
00780     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00781     {
00782         DX::ThrowIfFailed(
00783             m_d3dDevice->CreateHullShader(
00784                 bytecode->Data,
00785                 bytecode->Length,
00786                 nullptr,
00787                 shader
00788                 )
00789             );
00790
00791         SetDebugName(*shader, filename);
00792     });
00793 }
00794
00795 void BasicLoader::LoadShader(
00796     _In_ Platform::String^ filename,
00797     _Out_ ID3D11DomainShader** shader
00798     )
00799 {
00800     Platform::Array<byte>^ bytecode = m_basicReaderWriter->ReadData(filename);
00801
00802     DX::ThrowIfFailed(
00803         m_d3dDevice->CreateDomainShader(
00804             bytecode->Data,
00805             bytecode->Length,
00806             nullptr,
00807             shader
00808             )
00809         );
00810
00811     SetDebugName(*shader, filename);
00812 }
00813
00814 task<void> BasicLoader::LoadShaderAsync(
00815     _In_ Platform::String^ filename,
00816     _Out_ ID3D11DomainShader** shader
00817     )
00818 {
00819     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ bytecode)
00820     {
00821         DX::ThrowIfFailed(
00822             m_d3dDevice->CreateDomainShader(
00823                 bytecode->Data,
00824                 bytecode->Length,
00825                 nullptr,
00826                 shader
00827                 )
00828             );
00829
00830         SetDebugName(*shader, filename);
00831     });
00832 }
00833
00834 void BasicLoader::LoadMesh(
00835     _In_ Platform::String^ filename,
00836     _Out_ ID3D11Buffer** vertexBuffer,
00837     _Out_ ID3D11Buffer** indexBuffer,
00838     _Out_opt_ uint32* vertexCount,
00839     _Out_opt_ uint32* indexCount
00840     )
00841 {
00842     Platform::Array<byte>^ meshData = m_basicReaderWriter->ReadData(filename);
00843
00844     CreateMesh(
00845         meshData->Data,
00846         vertexBuffer,
00847         indexBuffer,
00848         vertexCount,
00849         indexCount,
00850         filename
00851         );
00852 }
00853
00854 task<void> BasicLoader::LoadMeshAsync(
00855     _In_ Platform::String^ filename,
00856     _Out_ ID3D11Buffer** vertexBuffer,
00857     _Out_ ID3D11Buffer** indexBuffer,
00858     _Out_opt_ uint32* vertexCount,
00859     _Out_opt_ uint32* indexCount
00860     )
00861 {
00862     return m_basicReaderWriter->ReadDataAsync(filename).then([=](const Platform::Array<byte>^ meshData)
00863     {
00864         CreateMesh(
00865             meshData->Data,
00866             vertexBuffer,
00867             indexBuffer,
00868             vertexCount,
00869             indexCount,
00870             filename
00871             );
00872     });
00873 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VisualProperties Member List

This is the complete list of members for VisualProperties, including all inherited members.
_compositionTarget | VisualProperties | [private]
_compositor | VisualProperties | [private]
_currentVisual | VisualProperties | [private]
_dragging | VisualProperties | [private]
_offsetBias | VisualProperties | [private]
_random | VisualProperties | [private]
_root | VisualProperties | [private]
_view | VisualProperties | [private]
_window | VisualProperties | [private]
CreateChildElement() | VisualProperties | [inline, private]
Initialize(CoreApplicationView view) | VisualProperties | [inline, private]
InitNewComposition() | VisualProperties | [inline, private]
Load(string unused) | VisualProperties | [inline, private]
OnPointerMoved(CoreWindow window, PointerEventArgs args) | VisualProperties | [inline, private]
OnPointerPressed(CoreWindow window, PointerEventArgs args) | VisualProperties | [inline, private]
OnPointerReleased(CoreWindow window, PointerEventArgs args) | VisualProperties | [inline, private]
Run() | VisualProperties | [inline, private]
SetWindow(CoreWindow window) | VisualProperties | [inline, private]
Uninitialize() | VisualProperties | [inline, private]
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Scenario2_DeviceWatcher.h Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

Scenario2_DeviceWatcher.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_DeviceWatcher.g.h"
00015 #include "MainPage.h"
00016 #include "DeviceWatcherHelper.h"
00017
00018 namespace winrt::SDKTemplate::implementation
00019 {
00020     struct Scenario2_DeviceWatcher : Scenario2_DeviceWatcherT<Scenario2_DeviceWatcher>
00021     {
00022         Scenario2_DeviceWatcher();
00023
00024         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00026
00027         void StartWatcherButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void StopWatcherButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029
00030     private:
00031         SDKTemplate::MainPage rootPage{ SDKTemplate::implementation::MainPage::Current() };
00032         Windows::Foundation::Collections::IObservableVector<SDKTemplate::DeviceInformationDisplay> resultCollection = winrt::single_threaded_observable_vector<SDKTemplate::DeviceInformationDisplay>();
00033         com_ptr<DeviceWatcherHelper> deviceWatcherHelper = make_self<DeviceWatcherHelper>(resultCollection, Dispatcher());
00034
00035         void StartWatcher();
00036         void StopWatcher();
00037     };
00038 }
00039
00040 namespace winrt::SDKTemplate::factory_implementation
00041 {
00042     struct Scenario2_DeviceWatcher : Scenario2_DeviceWatcherT<Scenario2_DeviceWatcher, implementation::Scenario2_DeviceWatcher>
00043     {
00044     };
00045 }
Generated on Fri Nov 15 2024 22:19:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MainPage Member List

This is the complete list of members for MainPage, including all inherited members.
__pad0__ | MainPage |
_deviceEventArgs | MainPage | [private]
_importOperation | MainPage | [private]
_placeholder | MainPage | [private]
_placeholder | MainPage | [private]
accelerometerReadingType | MainPage |
AccelerometerReadingType | MainPage |
AddCustomTitleBar() | MainPage | [inline]
AddItem() | MainPage | [inline, private]
ADMIN_KEY_LENGTH_IN_BYTES | MainPage |
adminkey | MainPage | [private]
AdminKey | MainPage |
APP_TITLE | MainPage |
appbarTileId | MainPage |
ApplyLanguageFont(TextBlock textBlock, LanguageFont languageFont) | MainPage | [inline, static]
ApplyScale(FrameworkElement box, double widthScale, double heightScale) | MainPage | [inline, private, static]
AreCertificateAndCertChainValidAsync(Windows::Security::Cryptography::Certificates::Certificate^serverCert, Windows::Foundation::Collections::IVectorView< Windows::Security::Cryptography::Certificates::Certificate^>^certChain) | MainPage | [static]
AreCertificateAndCertChainValidAsync(Certificate serverCert, IReadOnlyList< Certificate > certChain) | MainPage | [inline, static]
areControlsInTitleBar | MainPage |
AreControlsInTitleBar | MainPage |
audioExtensions | MainPage | [static]
audioExtensionsInner | MainPage | [private, static]
BuildClipboardFormatsOutputString() | MainPage | [inline]
BuildWebSocketError(Platform::Exception^ex) | MainPage | [static]
BuildWebSocketError(Exception ex) | MainPage | [inline, static]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
CaptionedMediaUri | MainPage |
CheckBackgroundAndRequestLocationAccess() | MainPage | [inline, static]
ClaimedPrinter | MainPage |
ClaimedPrinter | MainPage | [private]
ClaimedPrinter_ReleaseDeviceRequested(Windows::Devices::PointOfService::ClaimedPosPrinter^sender, Windows::Devices::PointOfService::PosPrinterReleaseDeviceRequestedEventArgs^args) | MainPage | [private]
ClaimedPrinter_ReleaseDeviceRequested(ClaimedPosPrinter sender, PosPrinterReleaseDeviceRequestedEventArgs args) | MainPage | [inline, private]
ClaimScenarioLineDisplayAsync() | MainPage |
ClaimScenarioLineDisplayAsync() | MainPage | [inline]
CleanUpMediaPlayerSource(Windows.Media.Playback.MediaPlayer mp) | MainPage | [inline, static]
commonMediaPlayer | MainPage |
ContentManagementSystemStub | MainPage | [static]
CreateCityBuildingsCollection() | MainPage | [static]
CreateCityBuildingsCollection() | MainPage | [inline, static]
CreateCityParksCollection() | MainPage | [static]
CreateCityParksCollection() | MainPage | [inline, static]
CreateContactFromUserInput(TextBox EmailAddress, TextBox PhoneNumber) | MainPage | [inline]
CreateFilePicker(string[] extensions) | MainPage | [inline, static]
Current | MainPage | [static]
customTitleBar | MainPage |
defaultViewModel | MainPage | [private]
DefaultViewModel | MainPage |
DeviceEvent | MainPage |
deviceId | MainPage | [private]
deviceInfo | MainPage |
deviceInfo | MainPage | [private]
Dismissed | MainPage | [private]
DisplayChangedFormats() | MainPage | [inline, private]
DisplayResult(Windows::UI::Xaml::Controls::Image^image, Windows::UI::Xaml::Controls::TextBlock^textBlock, Platform::String^thumbnailModeName, size_t size, Windows::Storage::IStorageItem^item, Windows::Storage::FileProperties::StorageItemThumbnail^thumbnail, bool isGroup) | MainPage | [static]
DisplayResult(Image image, TextBlock textBlock, string thumbnailModeName, uint size, IStorageItem item, StorageItemThumbnail thumbnail, bool isGroup) | MainPage | [inline, static]
DisplayToast(string message) | MainPage | [inline, static]
DisplayToast(string content) | MainPage | [inline, static]
dynamicTileId | MainPage |
E_NO_UNICODE_TRANSLATION | MainPage |
EnableClipboardContentChangedNotifications(bool enable) | MainPage | [inline]
EnsureMediaExtensionManager() | MainPage | [inline]
falToken | MainPage |
FEATURE_NAME | MainPage |
filename | MainPage |
FillItemsFromSavedJson(ItemsControl control, string key) | MainPage | [inline, static]
FindContentById(int id) | MainPage | [inline, static]
FindSupportedFeedback(SimpleHapticsController hapticsController, ushort waveform) | MainPage | [inline, static]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
GetBufferFromString(Platform::String^string) | MainPage | [static]
GetBufferFromString(string str) | MainPage | [inline, private, static]
GetContactResult(Contact contact) | MainPage | [inline, static]
GetElementLocation(object e) | MainPage | [inline, static]
GetElementRect(Windows.UI.Xaml.FrameworkElement element) | MainPage | [inline, static]
GetElementRect(Windows::UI::Xaml::FrameworkElement^element) | MainPage | [static]
GetElementRect(FrameworkElement element) | MainPage | [inline, static]
GetElementRect(object e) | MainPage | [inline, static]
GetPlaceHolderImage() | MainPage | [private]
GetScenarioIdForLaunch(string launchParam, ref int index) | MainPage | [private]
GetSmartCard() | MainPage | [inline]
GetStringFromBuffer(Windows::Storage::Streams::IBuffer^buffer) | MainPage | [static]
GetStringFromBuffer(IBuffer buffer) | MainPage | [inline, private, static]
GetUserViewModelsAsync() | MainPage | [inline, static]
GoToScenario(int index) | MainPage | [inline]
HandleClipboardChanged() | MainPage | [inline, private]
HandleIoException(Platform::COMException^e, Platform::String^description) | MainPage |
HideStatus() | MainPage | [inline]
HighlightFaces(WriteableBitmap displaySource, IList< DetectedFace > foundFaces, Canvas canvas, DataTemplate template) | MainPage | [inline, static]
HighlightRanges(TextBlock tb, String TextContent, IReadOnlyList< TextSegment > ranges) | MainPage | [inline]
ImportOperation | MainPage |
index | MainPage |
initialize | MainPage |
InitializePasswordVaultInTheBackground() | MainPage | [static]
InitializePasswordVaultInTheBackground() | MainPage | [inline, private, static]
IsAnImportantTransaction | MainPage |
IsAnImportantTransaction | MainPage | [private]
isApplicationWindowActive | MainPage | [private]
IsCertificateValidAsync(Windows::Security::Cryptography::Certificates::Certificate^serverCert) | MainPage | [private, static]
IsCertificateValidAsync(Certificate serverCert) | MainPage | [inline, private, static]
IsClipboardContentChangedEnabled | MainPage |
LaunchArgs | MainPage |
launchParam | MainPage |
launchParam | MainPage | [private]
LaunchParam | MainPage |
LineDisplayId | MainPage |
ListView_ItemClick(object sender, ItemClickEventArgs e) | MainPage | [inline, private]
LoadDataAccountsAsync(ComboBox comboBox) | MainPage | [inline]
LoadScenarioForProtocolActivation(ProtocolActivatedEventArgs protocolArgs) | MainPage | [inline]
LoadStringFromPackageFileAsync(string name) | MainPage | [inline, static]
logoSecondaryTileId | MainPage |
LookupBackgroundTask(string name) | MainPage | [inline, static]
LookupSavedString(string key, string defaultValue="") | MainPage | [inline, static]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
MainPage() | MainPage | [inline]
mediaExtensionManager | MainPage | [static]
mediaExtensionMgr | MainPage | [private, static]
MissingTitleError | MainPage |
mruToken | MainPage |
MultiTrackVideoMediaUri | MainPage |
NavigateToAutoPlay() | MainPage | [inline]
NavigateToPageWithParameter(int pageIndex, object parameter) | MainPage | [inline]
NavigateToPageWithParameter(int pageIndex, object parameter) | MainPage | [inline]
NavigateToReconnect() | MainPage | [inline]
NavigateToScenario(Type type) | MainPage | [inline]
NavigateToScenario(Type scenario, object param=null) | MainPage | [inline, private]
NavigateToScenarioWithParameter(Scenario scenario, object parameter) | MainPage | [inline]
navigationHelper | MainPage | [private]
NavigationHelper | MainPage |
NavigationHelper_Load(object sender, LoadStateEventArgs e) | MainPage | [inline, private]
NavigationHelper_Save(object sender, SaveStateEventArgs e) | MainPage | [inline, private]
needToPrintClipboardFormat | MainPage | [private]
NotifyUser(string strMessage, NotifyType type) | MainPage | [inline]
NotifyUser(string strMessage, NotifyType type) | MainPage | [inline]
NotifyUser(string strMessage, NotifyType type) | MainPage | [inline]
NotifyUser(string strMessage, NotifyType type) | MainPage | [inline]
NotifyUser(string strMessage, NotifyType type, bool clearPrevious=false) | MainPage | [inline]
NotifyUser(string strMessage, NotifyType type) | MainPage | [inline]
NotifyUser(string strMessage, NotifyType type) | MainPage | [inline]
NotifyUser(string strMessage, NotifyType type) | MainPage | [inline]
NotifyUser(string strMessage, NotifyType type) | MainPage | [inline]
NotifyUser(string strMessage, NotifyType type) | MainPage | [inline]
NotifyUser(string strMessage, NotifyType type) | MainPage | [inline]
NotifyUserFileNotExist() | MainPage |
NotifyUserFileNotExist() | MainPage | [inline, private]
NotifyUserFromBackground(string strMessage, NotifyType type) | MainPage | [inline]
OnClipboardChanged(Object sender, Object e) | MainPage | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnSignInInfoChanged() | MainPage | [inline, private]
OnWindowActivated(object sender, WindowActivatedEventArgs e) | MainPage | [inline, private]
PickPlaylistAsync() | MainPage |
PickPlaylistAsync() | MainPage | [inline]
PlaceHolderImage | MainPage | [private]
playlistExtensions | MainPage | [static]
playlistExtensionsInner | MainPage | [private, static]
Printer | MainPage | [private]
ProjectionViewPageControl | MainPage |
publicKeyHint | MainPage | [private]
ReleaseAllPrinters() | MainPage |
ReleaseAllPrinters() | MainPage | [inline]
ReleaseClaimedPrinter() | MainPage |
ReleaseClaimedPrinter() | MainPage | [inline]
releaseDeviceRequestedToken | MainPage | [private]
RemoveCustomTitleBar() | MainPage |
RemoveCustomTitleBar() | MainPage | [inline]
ReportSavedStatus() | MainPage | [inline, static]
RepositionFaces(WriteableBitmap displaySource, Canvas canvas) | MainPage | [inline, static]
ResetItems() | MainPage | [inline, private]
ResetOutput(Image image, TextBlock output, TextBlock outputDetails=null) | MainPage | [inline]
SAMPLE_NAME | MainPage |
sampleFile | MainPage | [private]
sampleFile | MainPage |
SampleMovieURL | MainPage | [static]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
Scenarios | MainPage |
scenarios | MainPage | [private]
scenariosInner | MainPage | [private, static]
SeattleGeopoint | MainPage | [static]
SelectedBleDeviceId | MainPage |
SelectedBleDeviceName | MainPage |
SensorDescription | MainPage |
sensorOptimizationGoal | MainPage |
SensorOptimizationGoal | MainPage |
SensorReadingType | MainPage |
sensorReadingType | MainPage |
SetExtendedSplashInfo(Rect splashRect, bool dismissStat) | MainPage | [inline]
SetReadingText(TextBlock textBlock, AccelerometerReading reading) | MainPage | [inline, static]
SetReadingText(TextBlock textBlock, OrientationSensorReading reading) | MainPage | [inline, static]
SignInWithHello() | MainPage | [inline, private]
SignInWithHelloAsync() | MainPage | [inline, private]
SignInWithPassword() | MainPage | [inline, private]
SintelMediaUri | MainPage |
SmartCardReaderDeviceId | MainPage |
SplashImageRect | MainPage | [private]
StateChanged | MainPage |
StateChanged | MainPage | [private]
SubscribeToReleaseDeviceRequested() | MainPage |
SubscribeToReleaseDeviceRequested() | MainPage | [inline]
systemList | MainPage |
systemMap | MainPage |
TryGetUri(string uriString) | MainPage | [inline]
TrySavePlaylistAsync(Windows::Media::Playlists::Playlist^playlist) | MainPage |
TrySavePlaylistAsync(Playlist playlist) | MainPage | [inline]
UncaptionedMediaUri | MainPage |
Unregister() | MainPage | [inline, private]
UpdateUI() | MainPage | [inline, private]
userId | MainPage | [private]
ValidateFile() | MainPage | [inline, private]
ValidateSystemDiscovery() | MainPage | [inline, private]
ValidateTPMSmartCard() | MainPage | [inline]
ViewSizePreferences | MainPage | [static]
WaveformNamesMap | MainPage | [static]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MainPage Member List

This is the complete list of members for MainPage, including all inherited members.
_viewModel | MainPage | [private]
MainPage() | MainPage | [inline]
MainPage_Loaded(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/ActivationTypes/BackgroundWithAppClosed/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • ActivationTypes
  • BackgroundWithAppClosed

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Linq;
00003 using System.Threading.Tasks;
00004 using Windows.ApplicationModel.Background;
00005 using Windows.UI.Notifications;
00006 using Windows.UI.Popups;
00007 using Windows.UI.Xaml.Controls;
00008
00009 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00010
00011 namespace Notifications.ScenarioPages.Toasts.ActivationTypes.BackgroundWithAppClosed
00012 {
00013     /// <summary>
00014     /// An empty page that can be used on its own or navigated to within a Frame.
00015     /// </summary>
00016     public sealed partial class ScenarioElement : UserControl
00017     {
00018         private static readonly string BACKGROUND_ENTRY_POINT = typeof(BackgroundTasks.ToastActivationTypeBackgroundClosedTask).FullName;
00019
00020         public ScenarioElement()
00021         {
00022             this.InitializeComponent();
00023
00024             Initialize();
00025         }
00026
00027         private async void Initialize()
00028         {
00029             // Clear all existing notifications
00030             ToastNotificationManager.History.Clear();
00031
00032             // Register background task
00033             if (!await RegisterBackgroundTask())
00034             {
00035                 await new MessageDialog("ERROR: Couldn't register background task.").ShowAsync();
00036                 return;
00037             }
00038
00039             // Pop notifications
00040             popToastControl.Payload =
00041                 $@"
00042                 <toast activationType='background' launch='args'>
00043                     <visual>
00044                         <binding template='ToastGeneric'>
00045                             <text>Background with App Closed</text>
00046                             <text>Ensure the app is closed. Make sure ""Windows 10"" is in the first text box. Press ""submit"".</text>
00047                         </binding>
00048                     </visual>
00049                     <actions>
00050
00051                         <input
00052                             id = 'message'
00053                             type = 'text'
00054                             title = 'Message'
00055                             placeHolderContent = 'Enter ""Windows 10""'
00056                             defaultInput = 'Windows 10' />
00057
00058                         <action activationType = 'background'
00059                                 arguments = 'quickReply'
00060                                 content = 'submit' />
00061
00062                         <action activationType = 'background'
00063                                 arguments = 'cancel'
00064                                 content = 'cancel' />
00065
00066                     </actions>
00067                 </toast>";
00068         }
00069
00070         private async Task<bool> RegisterBackgroundTask()
00071         {
00072             // Unregister any previous exising background task
00073             UnregisterBackgroundTask();
00074
00075             // Request access
00076             BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
00077
00078             // If denied
00079             if (status != BackgroundAccessStatus.AlwaysAllowed && status != BackgroundAccessStatus.AllowedSubjectToSystemPolicy)
00080                 return false;
00081
00082             // Construct the background task
00083             BackgroundTaskBuilder builder = new BackgroundTaskBuilder()
00084             {
00085                 Name = BACKGROUND_ENTRY_POINT,
00086                 TaskEntryPoint = BACKGROUND_ENTRY_POINT
00087             };
00088
00089             // Set trigger for Toast History Changed
00090             builder.SetTrigger(new ToastNotificationActionTrigger());
00091
00092             // And register the background task
00093             BackgroundTaskRegistration registration = builder.Register();
00094
00095             return true;
00096         }
00097
00098         private static void UnregisterBackgroundTask()
00099         {
00100             var task = BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault(i => i.Name.Equals(BACKGROUND_ENTRY_POINT));
00101
00102             if (task != null)
00103                 task.Unregister(true);
00104         }
00105     }
00106 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Scenario3_BackgroundTask.h Source File

  • Geolocation
  • cppwinrt

Scenario3_BackgroundTask.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_BackgroundTask.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario3_BackgroundTask : Scenario3_BackgroundTaskT<Scenario3_BackgroundTask>
00019     {
00020         Scenario3_BackgroundTask();
00021
00022         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00023         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00024         void RegisterBackgroundTask(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00025         void UnregisterBackgroundTask(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00026
00027     private:
00028         SDKTemplate::MainPage m_rootPage{ MainPage::Current() };
00029         Windows::ApplicationModel::Background::IBackgroundTaskRegistration m_geolocTask;
00030         event_token m_taskCompletedToken{};
00031
00032         static constexpr wchar_t BackgroundTaskName[] = L"SampleLocationBackgroundTask";
00033         static constexpr std::wstring_view BackgroundTaskEntryPoint = name_of<BackgroundTask::LocationBackgroundTask>();
00034
00035         fire_and_forget OnCompleted(Windows::ApplicationModel::Background::IBackgroundTaskRegistration sender, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs e);
00036         void UpdateButtonStates();
00037     };
00038 }
00039
00040 namespace winrt::SDKTemplate::factory_implementation
00041 {
00042     struct Scenario3_BackgroundTask : Scenario3_BackgroundTaskT<Scenario3_BackgroundTask, implementation::Scenario3_BackgroundTask>
00043     {
00044     };
00045 }
Generated on Fri Nov 15 2024 22:19:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_Capabilities Member List

This is the complete list of members for Scenario5_Capabilities, including all inherited members.
Capabilities_Click(object sender, RoutedEventArgs e) | Scenario5_Capabilities | [inline, private]
m_rootPage | Scenario5_Capabilities | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario5_Capabilities | [inline, protected]
ReportCapabilityAsync(RemoteSystem selectedSystem, string capability, TextBlock resultBlock) | Scenario5_Capabilities | [inline, private]
Scenario5_Capabilities() | Scenario5_Capabilities | [inline]
SystemList | Scenario5_Capabilities |
UpdateStatus(string status, NotifyType statusType) | Scenario5_Capabilities | [inline, private]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MessageDialog/cpp/pch.cpp Source File

  • MessageDialog
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/Common/InkEventLogger.cpp Source File

  • ComplexInk
  • cpp
  • Common

InkEventLogger.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "InkEventLogger.h"
00005
00006
00007 InkEventLogger::InkEventLogger()
00008 {
00009     _currentConfig = LogEventTypes::EventNone;
00010     _countOfCoalescedIndependentInput = 0;
00011     _countOfCoalescedStrokeMessages = 0;
00012     _countOfCoalescedUnprocessedInput = 0;
00013 }
00014
00015 void InkEventLogger::SetConfiguration(LogEventTypes config)
00016 {
00017     _currentConfig = config;
00018 }
00019
00020 void InkEventLogger::EnableLoggingConfiguration(LogEventTypes type, bool addConfig)
00021 {
00022     if (addConfig)
00023     {
00024         _currentConfig = (LogEventTypes)(_currentConfig | type);
00025     }
00026     else
00027     {
00028         _currentConfig = (LogEventTypes)(_currentConfig & ~(type));
00029     }
00030 }
00031
00032 void InkEventLogger::Log(LogEventAction eventAction)
00033 {
00034     std::wstring newLogEntry;
00035     std::wstring messageCount;
00036
00037     // Filter events
00038     if ((eventAction >= StrokeCollected && eventAction <= StrokeErased))
00039     {
00040         if ((_currentConfig & LogEventTypes::InkingEventType) != LogEventTypes::InkingEventType)
00041         {
00042             return;
00043         }
00044     }
00045     else if ((eventAction >= IndependentInputEntered && eventAction <= IndependentInputExited))
00046     {
00047         if ((_currentConfig & LogEventTypes::IndependentInputEventType) != LogEventTypes::IndependentInputEventType)
00048         {
00049             return;
00050         }
00051     }
00052     else if ((eventAction >= UnprocessedInputEntered && eventAction <= UnprocessedInputExited))
00053     {
00054         if ((_currentConfig & LogEventTypes::UnprocessedInputEventType) != LogEventTypes::UnprocessedInputEventType)
00055         {
00056             return;
00057         }
00058     }
00059     else if ((eventAction >= StrokeStarted && eventAction <= StrokeCanceled))
00060     {
00061         if ((_currentConfig & LogEventTypes::StrokeEventType) != LogEventTypes::StrokeEventType)
00062         {
00063             return;
00064         }
00065     }
00066     else
00067     {
00068         return;
00069     }
00070
00071
00072     switch (eventAction)
00073     {
00074     case LogEventAction::IndependentInputEntered:
00075         newLogEntry = L"Independent Input - Entered";
00076         _countOfCoalescedIndependentInput = 0;
00077         break;
00078     case LogEventAction::IndependentInputExited:
00079         newLogEntry = L"Independent Input - Exited";
00080         if (_countOfCoalescedIndependentInput > 0)
00081         {
00082             // Coalescing hover and mouse events to avoid excessive logging
00083             // For hover, count the number of hover messages and display them
00084             // only when the stylus exits or the sytlus is in contact with the
00085             // screen.
00086             messageCount = _countOfCoalescedIndependentInput.ToString()->Data();
00087             newLogEntry += L"\nIndependent Input - Hover (" + messageCount + L")";
00088             _countOfCoalescedIndependentInput = 0;
00089         }
00090         break;
00091     case LogEventAction::IndependentInputHover:
00092         _countOfCoalescedIndependentInput++;
00093         break;
00094     case LogEventAction::IndependentInputLost:
00095         newLogEntry = L"Independent Input - Lost";
00096         _countOfCoalescedIndependentInput = 0;
00097         break;
00098     case LogEventAction::IndependentInputMoved:
00099         _countOfCoalescedIndependentInput++;
00100         break;
00101     case LogEventAction::IndependentInputPressed:
00102         newLogEntry = L"Independent Input - Pressed";
00103         if (_countOfCoalescedIndependentInput > 0)
00104         {
00105             // This means pen came in range and now it
00106             // starts inking
00107             messageCount = _countOfCoalescedIndependentInput.ToString()->Data();
00108             newLogEntry += L"\nIndependent Input - Hover (" + messageCount + L")";
00109             _countOfCoalescedUnprocessedInput = 0;
00110         }
00111         break;
00112     case LogEventAction::IndependentInputReleased:
00113         newLogEntry = L"Independent Input - Released";
00114         if (_countOfCoalescedIndependentInput > 0)
00115         {
00116             messageCount = _countOfCoalescedIndependentInput.ToString()->Data();
00117             newLogEntry += L"\nIndependent Input - Moved (" + messageCount + L")";
00118             _countOfCoalescedIndependentInput = 0;
00119         }
00120         break;
00121     case LogEventAction::UnprocessedInputEntered:
00122         newLogEntry = L"Unprocessed Input - Entered";
00123         _countOfCoalescedUnprocessedInput = 0;
00124         break;
00125     case LogEventAction::UnprocessedInputExited:
00126         newLogEntry = L"Unprocessed Input - Exited";
00127         if (_countOfCoalescedUnprocessedInput > 0)
00128         {
00129             messageCount = _countOfCoalescedUnprocessedInput.ToString()->Data();
00130             newLogEntry += L"\nUnprocessed Input - Hover (" + messageCount + L")";
00131             _countOfCoalescedUnprocessedInput = 0;
00132         }
00133         break;
00134     case LogEventAction::UnprocessedInputHover:
00135         _countOfCoalescedUnprocessedInput++;
00136         break;
00137     case LogEventAction::UnprocessedInputLost:
00138         newLogEntry = L"Unprocessed Input - Lost";
00139         _countOfCoalescedUnprocessedInput = 0;
00140         break;
00141     case LogEventAction::UnprocessedInputMoved:
00142         _countOfCoalescedUnprocessedInput++;
00143         break;
00144     case LogEventAction::UnprocessedInputPressed:
00145         newLogEntry = L"Unprocessed Input - Pressed";
00146         newLogEntry = L"Unprocessed Input - Exited";
00147         if (_countOfCoalescedUnprocessedInput > 0)
00148         {
00149             messageCount = _countOfCoalescedUnprocessedInput.ToString()->Data();
00150             newLogEntry += L"\nUnprocessed Input - Hover (" + messageCount + L")";
00151             _countOfCoalescedUnprocessedInput = 0;
00152         }
00153         break;
00154     case LogEventAction::UnprocessedInputReleased:
00155         newLogEntry = L"Unprocessed Input - Released";
00156         if (_countOfCoalescedUnprocessedInput > 0)
00157         {
00158             messageCount = _countOfCoalescedUnprocessedInput.ToString()->Data();
00159             newLogEntry += L"\nUnprocessed Input - Moved (" + messageCount + L")";
00160             _countOfCoalescedUnprocessedInput = 0;
00161         }
00162         break;
00163     case LogEventAction::StrokeCanceled:
00164         newLogEntry = L"Stroke Canceled";
00165         _countOfCoalescedStrokeMessages = 0;
00166         break;
00167     case LogEventAction::StrokeCollected:
00168         newLogEntry = L"Stroke Collected";
00169         break;
00170     case LogEventAction::StrokeContinued:
00171         _countOfCoalescedStrokeMessages++;
00172         break;
00173     case LogEventAction::StrokeEnded:
00174         newLogEntry = L"Stroke Ended";
00175         if (_countOfCoalescedStrokeMessages > 0)
00176         {
00177             messageCount = _countOfCoalescedStrokeMessages.ToString()->Data();
00178             newLogEntry += L"\nStroke Continued (" + messageCount + L")";
00179             _countOfCoalescedStrokeMessages = 0;
00180         }
00181         break;
00182     case LogEventAction::StrokeErased:
00183         newLogEntry = L"Stroke Erased";
00184         break;
00185     case LogEventAction::StrokeStarted:
00186         newLogEntry = L"Stroke Started";
00187         _countOfCoalescedStrokeMessages = 0;
00188         break;
00189     default:
00190         newLogEntry = L"";
00191         break;
00192     }
00193
00194     if (newLogEntry != L"")
00195     {
00196         _log = newLogEntry + L"\n" + _log;
00197     }
00198 }
Generated on Fri Nov 15 2024 22:18:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cpp/Scenario5.xaml.h Source File

  • FileThumbnails
  • cpp

Scenario5.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario5.xaml.h
00014 // Declaration of the Scenario5 class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario5.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     [Windows::Foundation::Metadata::WebHostHidden]
00026     public ref class Scenario5 sealed
00027     {
00028     public:
00029         Scenario5();
00030
00031     protected:
00032         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00033
00034     private:
00035         MainPage^ rootPage;
00036
00037         void GetThumbnailButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Fri Nov 15 2024 22:18:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppWindow/cppwinrt/Scenario2_DisplayRegion.h Source File

  • AppWindow
  • cppwinrt

Scenario2_DisplayRegion.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_DisplayRegion.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_DisplayRegion : Scenario2_DisplayRegionT<Scenario2_DisplayRegion>
00019     {
00020         Scenario2_DisplayRegion();
00021
00022         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00023         fire_and_forget OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00024
00025         fire_and_forget Button_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00026
00027     private:
00028         Windows::UI::WindowManagement::AppWindow appWindow{ nullptr };
00029         Windows::UI::Xaml::Controls::Frame appWindowFrame{};
00030
00031         int NumberOfAvailableDisplayRegions();
00032         Windows::UI::WindowManagement::DisplayRegion GetOtherDisplayRegion(Windows::UI::WindowManagement::DisplayRegion currentAppDisplayRegion);
00033         void OnWindowClosed(Windows::UI::WindowManagement::AppWindow const& sender, IInspectable const&);
00034     };
00035 }
00036
00037 namespace winrt::SDKTemplate::factory_implementation
00038 {
00039     struct Scenario2_DisplayRegion : Scenario2_DisplayRegionT<Scenario2_DisplayRegion, implementation::Scenario2_DisplayRegion>
00040     {
00041     };
00042 }
Generated on Fri Nov 15 2024 22:18:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cs/Scenario10_SetCookie.xaml.cs Source File

  • HttpClient
  • cs

Scenario10_SetCookie.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using Windows.Web.Http;
00017 using Windows.Web.Http.Filters;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario10_SetCookie : Page
00022     {
00023         MainPage rootPage = MainPage.Current;
00024
00025         public Scenario10_SetCookie()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         private void SetCookie_Click(object sender, RoutedEventArgs e)
00031         {
00032             if (String.IsNullOrEmpty(NameField.Text) || String.IsNullOrEmpty(DomainField.Text) || String.IsNullOrEmpty(PathField.Text))
00033             {
00034                 rootPage.NotifyUser("Invalid name, domain, or path value.", NotifyType.ErrorMessage);
00035                 return;
00036             }
00037
00038             try
00039             {
00040                 HttpCookie cookie = new HttpCookie(NameField.Text, DomainField.Text, PathField.Text);
00041                 cookie.Value = ValueField.Text;
00042
00043                 if (NullCheckBox.IsChecked.Value)
00044                 {
00045                     cookie.Expires = null;
00046                 }
00047                 else
00048                 {
00049                     cookie.Expires = ExpiresDatePicker.Date + ExpiresTimePicker.Time;
00050                 }
00051
00052                 cookie.Secure = SecureToggle.IsOn;
00053                 cookie.HttpOnly = HttpOnlyToggle.IsOn;
00054
00055                 HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
00056                 bool replaced = filter.CookieManager.SetCookie(cookie, false);
00057
00058                 if (replaced)
00059                 {
00060                     rootPage.NotifyUser("Cookie replaced.", NotifyType.StatusMessage);
00061                 }
00062                 else
00063                 {
00064                     rootPage.NotifyUser("Cookie set.", NotifyType.StatusMessage);
00065                 }
00066             }
00067             catch (ArgumentException ex)
00068             {
00069                 rootPage.NotifyUser(ex.Message, NotifyType.StatusMessage);
00070             }
00071             catch (Exception ex)
00072             {
00073                 rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage);
00074             }
00075         }
00076     }
00077 }
Generated on Fri Nov 15 2024 22:20:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cpp/Scenario4_UpdatingLineDisplayAttributes.xaml.h Source File

  • LineDisplay
  • cpp

Scenario4_UpdatingLineDisplayAttributes.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_UpdatingLineDisplayAttributes.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     [Windows::UI::Xaml::Data::Bindable]
00021     public ref class Scenario4_UpdatingLineDisplayAttributes sealed
00022     {
00023     public:
00024         Scenario4_UpdatingLineDisplayAttributes();
00025
00026     protected:
00027         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00028         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029
00030     private:
00031         MainPage^ rootPage = MainPage::Current;
00032         Windows::Devices::PointOfService::ClaimedLineDisplay^ lineDisplay;
00033
00034         Concurrency::task<void> InitializeAsync();
00035         void SetValuesFromLineDisplay();
00036
00037         void UpdateButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Fri Nov 15 2024 22:20:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaImport/cs/MainPage.xaml.cs Source File

  • MediaImport
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Data;
00017 using Windows.UI.Xaml.Media;
00018 using Windows.UI.Xaml.Navigation;
00019 using Windows.ApplicationModel.Activation;
00020 using Windows.Media.Import;
00021
00022 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00023
00024 namespace SDKTemplate
00025 {
00026     /// <summary>
00027     /// An empty page that can be used on its own or navigated to within a Frame.
00028     /// </summary>
00029     public sealed partial class MainPage : Page
00030     {
00031         public static MainPage Current;
00032
00033         private DeviceActivatedEventArgs _deviceEventArgs = null;
00034         public DeviceActivatedEventArgs DeviceEvent
00035         {
00036             get { return _deviceEventArgs; }
00037             set { _deviceEventArgs = value; }
00038         }
00039
00040         private PhotoImportOperation _importOperation = null;
00041         public PhotoImportOperation ImportOperation
00042         {
00043             get { return _importOperation; }
00044             set { _importOperation = value; }
00045         }
00046
00047         public void NavigateToAutoPlay()
00048         {
00049             ScenarioFrame.Navigate(this.Scenarios[0].ClassType,this.DeviceEvent);
00050         }
00051
00052         public void NavigateToReconnect()
00053         {
00054             ScenarioFrame.Navigate(this.Scenarios[0].ClassType,this.ImportOperation);
00055         }
00056
00057         public MainPage()
00058         {
00059             this.InitializeComponent();
00060
00061             // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00062             // in order to call methods that are in this class.
00063             Current = this;
00064             SampleTitle.Text = FEATURE_NAME;
00065         }
00066
00067         protected override void OnNavigatedTo(NavigationEventArgs e)
00068         {
00069             // Populate the scenario list from the SampleConfiguration.cs file
00070             ScenarioControl.ItemsSource = scenarios;
00071             if (Window.Current.Bounds.Width < 640)
00072             {
00073                 ScenarioControl.SelectedIndex = -1;
00074             }
00075             else
00076             {
00077                 ScenarioControl.SelectedIndex = 0;
00078             }
00079         }
00080
00081         /// <summary>
00082         /// Called whenever the user changes selection in the scenarios list.  This method will navigate to the respective
00083         /// sample scenario page.
00084         /// </summary>
00085         /// <param name="sender"></param>
00086         /// <param name="e"></param>
00087         private void ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
00088         {
00089             // Clear the status block when navigating scenarios.
00090             NotifyUser(String.Empty, NotifyType.StatusMessage);
00091
00092             ListBox scenarioListBox = sender as ListBox;
00093             Scenario s = scenarioListBox.SelectedItem as Scenario;
00094             if (s != null)
00095             {
00096                 ScenarioFrame.Navigate(s.ClassType);
00097                 if (Window.Current.Bounds.Width < 640)
00098                 {
00099                     Splitter.IsPaneOpen = false;
00100                     StatusBorder.Visibility = Visibility.Collapsed;
00101                 }
00102             }
00103         }
00104
00105         public List<Scenario> Scenarios
00106         {
00107             get { return this.scenarios; }
00108         }
00109
00110         /// <summary>
00111         /// Used to display messages to the user
00112         /// </summary>
00113         /// <param name="strMessage"></param>
00114         /// <param name="type"></param>
00115         public void NotifyUser(string strMessage, NotifyType type)
00116         {
00117             switch (type)
00118             {
00119                 case NotifyType.StatusMessage:
00120                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green);
00121                     break;
00122                 case NotifyType.ErrorMessage:
00123                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red);
00124                     break;
00125             }
00126             StatusBlock.Text = strMessage;
00127
00128             // Collapse the StatusBlock if it has no text to conserve real estate.
00129             StatusBorder.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed;
00130         }
00131
00132         async void Footer_Click(object sender, RoutedEventArgs e)
00133         {
00134             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00135         }
00136
00137         private void Button_Click(object sender, RoutedEventArgs e)
00138         {
00139             Splitter.IsPaneOpen = (Splitter.IsPaneOpen == true) ? false : true;
00140             StatusBorder.Visibility = Visibility.Collapsed;
00141         }
00142     }
00143     public enum NotifyType
00144     {
00145         StatusMessage,
00146         ErrorMessage
00147     };
00148
00149     public class ScenarioBindingConverter : IValueConverter
00150     {
00151         public object Convert(object value, Type targetType, object parameter, string language)
00152         {
00153             Scenario s = value as Scenario;
00154             return (MainPage.Current.Scenarios.IndexOf(s) + 1) + ") " + s.Title;
00155         }
00156
00157         public object ConvertBack(object value, Type targetType, object parameter, string language)
00158         {
00159             return true;
00160         }
00161     }
00162 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cs/Scenario5_DeviceReadWrite.xaml.cs Source File

  • CustomCapability
  • cs

Scenario5_DeviceReadWrite.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Storage.Streams;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Documents;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class DeviceReadWrite
00021     {
00022         MainPage rootPage = MainPage.Current;
00023
00024         public DeviceReadWrite()
00025         {
00026             this.InitializeComponent();
00027         }
00028
00029         private int writeCounter = 0;
00030         private int readCounter = 0;
00031
00032         private async void ReadBlock_Click(object sender, RoutedEventArgs e)
00033         {
00034             var fx2Device = DeviceList.Current.GetSelectedDevice();
00035
00036             if (fx2Device == null)
00037             {
00038                 rootPage.NotifyUser("Fx2 device not connected or accessible", NotifyType.ErrorMessage);
00039                 return;
00040             }
00041
00042             var button = (Button)sender;
00043             button.IsEnabled = false;
00044
00045             var dataReader = new DataReader(fx2Device.InputStream);
00046
00047             int counter = readCounter++;
00048             LogMessage($"Read {counter} begin");
00049
00050             // load the data reader from the stream.  For purposes of this
00051             // sample, assume all messages read are < 64 bytes
00052
00053             await dataReader.LoadAsync(64);
00054
00055             // Get the message string out of the buffer
00056             var message = dataReader.ReadString(dataReader.UnconsumedBufferLength);
00057
00058             LogMessage($"Read {counter} end: {message}");
00059
00060             button.IsEnabled = true;
00061         }
00062
00063         private async void WriteBlock_Click(object sender, RoutedEventArgs e)
00064         {
00065             var fx2Device = DeviceList.Current.GetSelectedDevice();
00066
00067             if (fx2Device == null)
00068             {
00069                 rootPage.NotifyUser("Fx2 device not connected or accessible", NotifyType.ErrorMessage);
00070                 return;
00071             }
00072
00073             var button = (Button)sender;
00074             button.IsEnabled = false;
00075
00076             // Generate a string to write to the device
00077             var counter = writeCounter++;
00078
00079             // Use a data writer to convert the string into a buffer
00080             var dataWriter = new DataWriter();
00081             var msg = "This is message " + counter;
00082             dataWriter.WriteString(msg);
00083
00084             LogMessage($"Write {counter} begin: {msg}");
00085             var bytesRead = await fx2Device.OutputStream.WriteAsync(dataWriter.DetachBuffer());
00086             LogMessage($"Write {counter} end: {bytesRead} bytes written");
00087
00088             button.IsEnabled = true;
00089         }
00090
00091         private void LogMessage(string message)
00092         {
00093             var span = new Span();
00094             var run = new Run();
00095             run.Text = message;
00096
00097             span.Inlines.Add(run);
00098             span.Inlines.Add(new LineBreak());
00099
00100             OutputText.Inlines.Insert(0, span);
00101         }
00102     }
00103 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cppwinrt/SocketReaderWriter.cpp Source File

  • WiFiDirect
  • cppwinrt

SocketReaderWriter.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014 #include "SocketReaderWriter.h"
00015 #include "ConnectedDevice.g.cpp"
00016 #include "Utils.g.cpp"
00017
00018 using namespace winrt;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Networking::Sockets;
00022 using namespace Windows::Storage::Streams;
00023
00024 namespace winrt::SDKTemplate
00025 {
00026     SocketReaderWriter::SocketReaderWriter(StreamSocket socket, MainPage mainPage) :
00027         streamSocket(socket), rootPage(mainPage),
00028         dataReader(socket.InputStream()), dataWriter(socket.OutputStream())
00029     {
00030         dataReader.UnicodeEncoding(UnicodeEncoding::Utf8);
00031         dataReader.ByteOrder(ByteOrder::LittleEndian);
00032
00033         dataWriter.UnicodeEncoding(UnicodeEncoding::Utf8);
00034         dataWriter.ByteOrder(ByteOrder::LittleEndian);
00035     }
00036
00037     void SocketReaderWriter::Close()
00038     {
00039         dataReader.Close();
00040         dataWriter.Close();
00041         streamSocket.Close();
00042     }
00043
00044     IAsyncAction SocketReaderWriter::WriteMessageAsync(hstring const& message)
00045     {
00046         auto lifetime = get_strong();
00047
00048         try
00049         {
00050             dataWriter.WriteUInt32(dataWriter.MeasureString(message));
00051             dataWriter.WriteString(message);
00052             co_await dataWriter.StoreAsync();
00053             rootPage.NotifyUser(L"Sent message: " + message, NotifyType::StatusMessage);
00054         }
00055         catch (hresult_error const& ex)
00056         {
00057             rootPage.NotifyUser(L"WriteMessage raised exception: " + ex.message(), NotifyType::ErrorMessage);
00058         }
00059     }
00060
00061     IAsyncOperation<IReference<hstring>> SocketReaderWriter::ReadMessageAsync()
00062     {
00063         auto lifetime = get_strong();
00064
00065         try
00066         {
00067             uint32_t bytesRead = co_await dataReader.LoadAsync(sizeof(uint32_t));
00068             if (bytesRead > 0)
00069             {
00070                 // Determine how long the string is.
00071                 uint32_t messageLength = dataReader.ReadUInt32();
00072                 bytesRead = co_await dataReader.LoadAsync(messageLength);
00073                 if (bytesRead > 0)
00074                 {
00075                     // Decode the string.
00076                     hstring message = dataReader.ReadString(messageLength);
00077                     rootPage.NotifyUser(L"Got message: " + message, NotifyType::StatusMessage);
00078                     co_return message;
00079                 }
00080             }
00081         }
00082         catch (hresult_error const&)
00083         {
00084             rootPage.NotifyUser(L"Socket was closed!", NotifyType::StatusMessage);
00085         }
00086         co_return nullptr;
00087     }
00088 }
Generated on Fri Nov 15 2024 22:22:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Common/CameraResources.h Source File

  • HolographicVoiceInput
  • cpp
  • Common

CameraResources.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 namespace DX
00014 {
00015     class DeviceResources;
00016
00017     // Constant buffer used to send the view-projection matrices to the shader pipeline.
00018     struct ViewProjectionConstantBuffer
00019     {
00020         DirectX::XMFLOAT4X4 viewProjection[2];
00021     };
00022
00023     // Assert that the constant buffer remains 16-byte aligned (best practice).
00024     static_assert((sizeof(ViewProjectionConstantBuffer) % (sizeof(float) * 4)) == 0, "ViewProjection constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00025
00026     // Manages DirectX device resources that are specific to a holographic camera, such as the
00027     // back buffer, ViewProjection constant buffer, and viewport.
00028     class CameraResources
00029     {
00030     public:
00031         CameraResources(Windows::Graphics::Holographic::HolographicCamera^ holographicCamera);
00032
00033         void CreateResourcesForBackBuffer(
00034             DX::DeviceResources* pDeviceResources,
00035             Windows::Graphics::Holographic::HolographicCameraRenderingParameters^ cameraParameters
00036             );
00037         void ReleaseResourcesForBackBuffer(
00038             DX::DeviceResources* pDeviceResources
00039             );
00040
00041         void UpdateViewProjectionBuffer(
00042             std::shared_ptr<DX::DeviceResources> deviceResources,
00043             Windows::Graphics::Holographic::HolographicCameraPose^ cameraPose,
00044             Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem);
00045
00046         bool AttachViewProjectionBuffer(
00047             std::shared_ptr<DX::DeviceResources> deviceResources);
00048
00049         // Direct3D device resources.
00050         ID3D11RenderTargetView* GetBackBufferRenderTargetView()     const { return m_d3dRenderTargetView.Get();     }
00051         ID3D11DepthStencilView* GetDepthStencilView()               const { return m_d3dDepthStencilView.Get();     }
00052         ID3D11Texture2D*        GetBackBufferTexture2D()            const { return m_d3dBackBuffer.Get();           }
00053         D3D11_VIEWPORT          GetViewport()                       const { return m_d3dViewport;                   }
00054         DXGI_FORMAT             GetBackBufferDXGIFormat()           const { return m_dxgiFormat;                    }
00055
00056         // Render target properties.
00057         Windows::Foundation::Size GetRenderTargetSize()             const { return m_d3dRenderTargetSize;           }
00058         bool                    IsRenderingStereoscopic()           const { return m_isStereo;                      }
00059
00060         // The holographic camera these resources are for.
00061         Windows::Graphics::Holographic::HolographicCamera^ GetHolographicCamera() const { return m_holographicCamera; }
00062
00063     private:
00064         // Direct3D rendering objects. Required for 3D.
00065         Microsoft::WRL::ComPtr<ID3D11RenderTargetView>      m_d3dRenderTargetView;
00066         Microsoft::WRL::ComPtr<ID3D11DepthStencilView>      m_d3dDepthStencilView;
00067         Microsoft::WRL::ComPtr<ID3D11Texture2D>             m_d3dBackBuffer;
00068
00069         // Device resource to store view and projection matrices.
00070         Microsoft::WRL::ComPtr<ID3D11Buffer>                m_viewProjectionConstantBuffer;
00071
00072         // Direct3D rendering properties.
00073         DXGI_FORMAT                                         m_dxgiFormat;
00074         Windows::Foundation::Size                           m_d3dRenderTargetSize;
00075         D3D11_VIEWPORT                                      m_d3dViewport;
00076
00077         // Indicates whether the camera supports stereoscopic rendering.
00078         bool                                                m_isStereo = false;
00079
00080         // Indicates whether this camera has a pending frame.
00081         bool                                                m_framePending = false;
00082
00083         // Pointer to the holographic camera these resources are for.
00084         Windows::Graphics::Holographic::HolographicCamera^  m_holographicCamera = nullptr;
00085     };
00086 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DGradientMesh/cpp/SampleOverlay.cpp Source File

  • D2DGradientMesh
  • cpp

SampleOverlay.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "SampleOverlay.h"
00010
00011 using namespace D2DGradientMesh;
00012
00013 using namespace Windows::UI::Core;
00014 using namespace Windows::Foundation;
00015 using namespace Microsoft::WRL;
00016 using namespace Windows::UI::ViewManagement;
00017 using namespace Windows::Graphics::Display;
00018 using namespace D2D1;
00019
00020 SampleOverlay::SampleOverlay(const std::shared_ptr<DX::DeviceResources>& deviceResources, const std::wstring& caption) :
00021     m_deviceResources(deviceResources),
00022     m_caption(caption),
00023     m_drawOverlay(true)
00024 {
00025     m_padding = 8.0f;
00026     m_textVerticalOffset = 7.0f;
00027     m_logoSize = D2D1::SizeF(0.0f, 0.0f);
00028     m_overlayWidth = 0.0f;
00029
00030     CreateDeviceDependentResources();
00031     CreateWindowSizeDependentResources();
00032 }
00033
00034 void SampleOverlay::CreateDeviceDependentResources()
00035 {
00036     DX::ThrowIfFailed(
00037         m_deviceResources->GetD2DDeviceContext()->CreateSolidColorBrush(ColorF(ColorF::White), &m_whiteBrush)
00038         );
00039
00040     ComPtr<IWICBitmapDecoder> wicBitmapDecoder;
00041     DX::ThrowIfFailed(
00042         m_deviceResources->GetWicImagingFactory()->CreateDecoderFromFilename(
00043             L"Assets\\storelogo-sdk.png",
00044             nullptr,
00045             GENERIC_READ,
00046             WICDecodeMetadataCacheOnDemand,
00047             &wicBitmapDecoder
00048             )
00049         );
00050
00051     ComPtr<IWICBitmapFrameDecode> wicBitmapFrame;
00052     DX::ThrowIfFailed(
00053         wicBitmapDecoder->GetFrame(0, &wicBitmapFrame)
00054         );
00055
00056     ComPtr<IWICFormatConverter> wicFormatConverter;
00057     DX::ThrowIfFailed(
00058         m_deviceResources->GetWicImagingFactory()->CreateFormatConverter(&wicFormatConverter)
00059         );
00060
00061     DX::ThrowIfFailed(
00062         wicFormatConverter->Initialize(
00063             wicBitmapFrame.Get(),
00064             GUID_WICPixelFormat32bppPBGRA,
00065             WICBitmapDitherTypeNone,
00066             nullptr,
00067             0.0,
00068             WICBitmapPaletteTypeCustom  // the BGRA format has no palette so this value is ignored
00069             )
00070         );
00071
00072     double dpiX = 96.0;
00073     double dpiY = 96.0;
00074     DX::ThrowIfFailed(
00075         wicFormatConverter->GetResolution(&dpiX, &dpiY)
00076         );
00077
00078     DX::ThrowIfFailed(
00079         m_deviceResources->GetD2DDeviceContext()->CreateBitmapFromWicBitmap(
00080             wicFormatConverter.Get(),
00081             BitmapProperties(
00082                 PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00083                 static_cast<float>(dpiX),
00084                 static_cast<float>(dpiY)
00085                 ),
00086             &m_logoBitmap
00087             )
00088         );
00089
00090     m_logoSize = m_logoBitmap->GetSize();
00091
00092     ComPtr<IDWriteTextFormat> nameTextFormat;
00093     DX::ThrowIfFailed(
00094         m_deviceResources->GetDWriteFactory()->CreateTextFormat(
00095             L"Segoe UI",
00096             nullptr,
00097             DWRITE_FONT_WEIGHT_LIGHT,
00098             DWRITE_FONT_STYLE_NORMAL,
00099             DWRITE_FONT_STRETCH_NORMAL,
00100             36.0f,
00101             L"en-US",
00102             &nameTextFormat
00103             )
00104         );
00105
00106     DX::ThrowIfFailed(
00107         nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
00108         );
00109
00110     DX::ThrowIfFailed(
00111         nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
00112         );
00113
00114     DX::ThrowIfFailed(
00115         m_deviceResources->GetDWriteFactory()->CreateTextLayout(
00116             m_caption.c_str(),
00117             static_cast<UINT32>(m_caption.size()),
00118             nameTextFormat.Get(),
00119             4096.0f,
00120             4096.0f,
00121             &m_textLayout
00122             )
00123         );
00124
00125     DWRITE_TEXT_METRICS metrics = {0};
00126     DX::ThrowIfFailed(
00127         m_textLayout->GetMetrics(&metrics)
00128         );
00129
00130     m_overlayWidth = m_padding * 3.0f + m_logoSize.width + metrics.width;
00131
00132     DX::ThrowIfFailed(
00133         m_deviceResources->GetD2DFactory()->CreateDrawingStateBlock(&m_stateBlock)
00134         );
00135 }
00136
00137 void SampleOverlay::CreateWindowSizeDependentResources()
00138 {
00139     if (CoreWindow::GetForCurrentThread()->Bounds.Width < m_overlayWidth)
00140     {
00141         m_drawOverlay = false;
00142     }
00143     else
00144     {
00145         m_drawOverlay = true;
00146     }
00147 }
00148
00149 // Release all references to resources that depend on the graphics device.
00150 // This method is invoked when the device is lost and resources are no longer usable.
00151 void SampleOverlay::ReleaseDeviceDependentResources()
00152 {
00153     m_whiteBrush.Reset();
00154     m_logoBitmap.Reset();
00155 }
00156
00157 void SampleOverlay::Render()
00158 {
00159     if (m_drawOverlay)
00160     {
00161         m_deviceResources->GetD2DDeviceContext()->SaveDrawingState(m_stateBlock.Get());
00162
00163         m_deviceResources->GetD2DDeviceContext()->BeginDraw();
00164         m_deviceResources->GetD2DDeviceContext()->SetTransform(m_deviceResources->GetOrientationTransform2D());
00165         m_deviceResources->GetD2DDeviceContext()->DrawBitmap(
00166             m_logoBitmap.Get(),
00167             D2D1::RectF(m_padding, m_padding, m_logoSize.width + m_padding, m_logoSize.height + m_padding)
00168             );
00169
00170         m_deviceResources->GetD2DDeviceContext()->DrawTextLayout(
00171             Point2F(m_logoSize.width + 2.0f * m_padding, m_textVerticalOffset),
00172             m_textLayout.Get(),
00173             m_whiteBrush.Get()
00174             );
00175
00176         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00177         // is lost. It will be handled during the next call to Present.
00178         HRESULT hr = m_deviceResources->GetD2DDeviceContext()->EndDraw();
00179         if (hr != D2DERR_RECREATE_TARGET)
00180         {
00181             DX::ThrowIfFailed(hr);
00182         }
00183
00184         m_deviceResources->GetD2DDeviceContext()->RestoreDrawingState(m_stateBlock.Get());
00185     }
00186 }
00187
00188 float SampleOverlay::GetTitleHeightInDips()
00189 {
00190     return m_logoSize.height + m_padding;
00191 }
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cppwinrt/Scenario2_UnpinTile.cpp Source File

  • SecondaryTiles
  • cppwinrt

Scenario2_UnpinTile.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_UnpinTile.h"
00014 #include "Scenario2_UnpinTile.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::UI::StartScreen;
00020 using namespace Windows::UI::Xaml;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     Scenario2_UnpinTile::Scenario2_UnpinTile()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     fire_and_forget Scenario2_UnpinTile::UnpinSecondaryTile_Click(IInspectable sender, RoutedEventArgs const&)
00030     {
00031         auto lifetime = get_strong();
00032
00033         if (SecondaryTile::Exists(SampleHelpers::LogoSecondaryTileId))
00034         {
00035             // First prepare the tile to be unpinned
00036             SecondaryTile secondaryTile(SampleHelpers::LogoSecondaryTileId);
00037             // Now make the delete request.
00038             bool isUnpinned = co_await secondaryTile.RequestDeleteForSelectionAsync(SampleHelpers::GetElementRect(sender), Windows::UI::Popups::Placement::Below);
00039             if (isUnpinned)
00040             {
00041                 rootPage.NotifyUser(L"Secondary tile successfully unpinned.", NotifyType::StatusMessage);
00042             }
00043             else
00044             {
00045                 rootPage.NotifyUser(L"Secondary tile not unpinned.", NotifyType::ErrorMessage);
00046             }
00047         }
00048         else
00049         {
00050             rootPage.NotifyUser(hstring(SampleHelpers::LogoSecondaryTileId) + L" is not currently pinned.", NotifyType::ErrorMessage);
00051         }
00052     }
00053 }
Generated on Fri Nov 15 2024 22:21:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SplashScreen/cs/Scenario2_ExtendedSplash.xaml.cs Source File

  • SplashScreen
  • cs

Scenario2_ExtendedSplash.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using SDKTemplate;
00012
00013 using System;
00014 using Windows.Foundation;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SplashScreenSample
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class Scenario2 : Page
00025     {
00026         public Scenario2()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         protected override void OnNavigatedTo(NavigationEventArgs e)
00032         {
00033             Rect rect = MainPage.Current.SplashImageRect;
00034             XValue.Text = " " + rect.X.ToString() + ", ";
00035             YValue.Text = " " + rect.Y.ToString() + " with ";
00036             WidthValue.Text = " " + rect.Width.ToString() + ", ";
00037             HeightValue.Text = " " + rect.Height.ToString() + ".";
00038         }
00039     }
00040 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: StreamSocket/cs/Scenario2_Connect.xaml.cs Source File

  • StreamSocket
  • cs

Scenario2_Connect.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using Windows.ApplicationModel.Core;
00015 using Windows.Networking;
00016 using Windows.Networking.Connectivity;
00017 using Windows.Networking.Sockets;
00018 using Windows.Storage.Streams;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace StreamSocketSample
00024 {
00025     /// <summary>
00026     /// A page for second scenario.
00027     /// </summary>
00028     public sealed partial class Scenario2 : Page
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         MainPage rootPage = MainPage.Current;
00033
00034         // Limit traffic to the same adapter that the listener is using to demonstrate client adapter-binding.
00035         NetworkAdapter adapter = null;
00036
00037         public Scenario2()
00038         {
00039             this.InitializeComponent();
00040         }
00041
00042         /// <summary>
00043         /// Invoked when this page is about to be displayed in a Frame.
00044         /// </summary>
00045         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00046         /// property is typically used to configure the page.</param>
00047         protected override void OnNavigatedTo(NavigationEventArgs e)
00048         {
00049             // Make sure we're using the correct server address if an adapter was selected in scenario 1.
00050             object serverAddress;
00051             if (CoreApplication.Properties.TryGetValue("serverAddress", out serverAddress))
00052             {
00053                 if (serverAddress is string)
00054                 {
00055                     HostNameForConnect.Text = serverAddress as string;
00056                 }
00057             }
00058
00059             adapter = null;
00060             object networkAdapter;
00061             if (CoreApplication.Properties.TryGetValue("adapter", out networkAdapter))
00062             {
00063                 adapter = (NetworkAdapter)networkAdapter;
00064             }
00065         }
00066
00067         /// <summary>
00068         /// This is the click handler for the 'ConnectSocket' button.
00069         /// </summary>
00070         /// <param name="sender">Object for which the event was generated.</param>
00071         /// <param name="e">Event's parameters.</param>
00072         private async void ConnectSocket_Click(object sender, RoutedEventArgs e)
00073         {
00074             if (CoreApplication.Properties.ContainsKey("clientSocket"))
00075             {
00076                 rootPage.NotifyUser(
00077                     "This step has already been executed. Please move to the next one.",
00078                     NotifyType.ErrorMessage);
00079                 return;
00080             }
00081
00082             if (String.IsNullOrEmpty(ServiceNameForConnect.Text))
00083             {
00084                 rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage);
00085                 return;
00086             }
00087
00088             // By default 'HostNameForConnect' is disabled and host name validation is not required. When enabling the
00089             // text box validating the host name is required since it was received from an untrusted source
00090             // (user input). The host name is validated by catching ArgumentExceptions thrown by the HostName
00091             // constructor for invalid input.
00092             HostName hostName;
00093             try
00094             {
00095                 hostName = new HostName(HostNameForConnect.Text);
00096             }
00097             catch (ArgumentException)
00098             {
00099                 rootPage.NotifyUser("Error: Invalid host name.", NotifyType.ErrorMessage);
00100                 return;
00101             }
00102
00103             StreamSocket socket = new StreamSocket();
00104
00105             // If necessary, tweak the socket's control options before carrying out the connect operation.
00106             // Refer to the StreamSocketControl class' MSDN documentation for the full list of control options.
00107             socket.Control.KeepAlive = false;
00108
00109             // Save the socket, so subsequent steps can use it.
00110             CoreApplication.Properties.Add("clientSocket", socket);
00111             try
00112             {
00113                 if (adapter == null)
00114                 {
00115                     rootPage.NotifyUser("Connecting to: " + HostNameForConnect.Text, NotifyType.StatusMessage);
00116
00117                     // Connect to the server (by default, the listener we created in the previous step).
00118                     await socket.ConnectAsync(hostName, ServiceNameForConnect.Text);
00119
00120                     rootPage.NotifyUser("Connected", NotifyType.StatusMessage);
00121                 }
00122                 else
00123                 {
00124                     rootPage.NotifyUser(
00125                         "Connecting to: " + HostNameForConnect.Text +
00126                         " using network adapter " + adapter.NetworkAdapterId,
00127                         NotifyType.StatusMessage);
00128
00129                     // Connect to the server (by default, the listener we created in the previous step)
00130                     // limiting traffic to the same adapter that the user specified in the previous step.
00131                     // This option will be overridden by interfaces with weak-host or forwarding modes enabled.
00132                     await socket.ConnectAsync(
00133                         hostName,
00134                         ServiceNameForConnect.Text,
00135                         SocketProtectionLevel.PlainSocket,
00136                         adapter);
00137
00138                     rootPage.NotifyUser(
00139                         "Connected using network adapter " + adapter.NetworkAdapterId,
00140                         NotifyType.StatusMessage);
00141                 }
00142
00143                 // Mark the socket as connected. Set the value to null, as we care only about the fact that the
00144                 // property is set.
00145                 CoreApplication.Properties.Add("connected", null);
00146             }
00147             catch (Exception exception)
00148             {
00149                 // If this is an unknown status it means that the error is fatal and retry will likely fail.
00150                 if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
00151                 {
00152                     throw;
00153                 }
00154
00155                 rootPage.NotifyUser("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage);
00156             }
00157         }
00158     }
00159 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cpp/Scenario5_Clear.xaml.h Source File

  • Playlists
  • cpp

Scenario5_Clear.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario5_Clear.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     /// <summary>
00011     /// Display animation metrics.
00012     /// </summary>
00013     [Windows::Foundation::Metadata::WebHostHidden]
00014     public ref class Scenario5_Clear sealed
00015     {
00016     public:
00017         Scenario5_Clear();
00018     private:
00019         MainPage^ rootPage;
00020         void PickPlaylistButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021     };
00022 }
Generated on Fri Nov 15 2024 22:20:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Personalization/cpp/SetLockScreenImage.xaml.cpp Source File

  • Personalization
  • cpp

SetLockScreenImage.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario1.xaml.cpp
00013 // Implementation of the Scenario1 class
00014 //
00015
00016 #include "pch.h"
00017 #include "SetLockScreenImage.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace Concurrency;
00022 using namespace Platform;
00023 using namespace Windows::ApplicationModel;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Navigation;
00028 using namespace Windows::UI::Xaml::Media::Imaging;
00029 using namespace Windows::Storage;
00030 using namespace Windows::Storage::Streams;
00031 using namespace Windows::Storage::Pickers;
00032 using namespace Windows::System::UserProfile;
00033
00034 SetLockScreenImage::SetLockScreenImage()
00035 {
00036     InitializeComponent();
00037 }
00038
00039 /// <summary>
00040 /// Invoked when this page is about to be displayed in a Frame.
00041 /// </summary>
00042 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00043 /// property is typically used to configure the page.</param>
00044 void SetLockScreenImage::OnNavigatedTo(NavigationEventArgs^ e)
00045 {
00046     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00047     // as NotifyUser()
00048     rootPage = MainPage::Current;
00049 }
00050
00051 /// <summary>
00052 /// This loads the File Picker so that the user may pick an image. Upon valid image selection, the image is then set as the lock screen image.
00053 /// </summary>
00054 /// <param name="sender"></param>
00055 /// <param name="e"></param>
00056 void SetLockScreenImage::PickAndSetButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00057 {
00058     rootPage->NotifyUser(" ", NotifyType::StatusMessage);
00059     FileOpenPicker^ imagePicker = ref new FileOpenPicker();
00060     imagePicker->ViewMode = PickerViewMode::Thumbnail;
00061     imagePicker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00062     imagePicker->FileTypeFilter->Append(".jpg");
00063     imagePicker->FileTypeFilter->Append(".jpeg");
00064     imagePicker->FileTypeFilter->Append(".png");
00065     imagePicker->FileTypeFilter->Append(".bmp");
00066
00067     create_task(imagePicker->PickSingleFileAsync()).then([this](StorageFile^ imageFile)
00068     {
00069         if (imageFile != nullptr)
00070         {
00071             rootPage->NotifyUser("Selected image: " + imageFile->Name, NotifyType::StatusMessage);
00072
00073             // Application now has access to the picked file, setting image to lockscreen.
00074             create_task(Windows::System::UserProfile::LockScreen::SetImageFileAsync(imageFile)).then([this](task<void> result)
00075             {
00076                 try
00077                 {
00078                     // Use result.get() to trigger exception if invalid image is chosen
00079                     result.get();
00080                     // Retrieve the lock screen image that was set
00081                     auto imageStream = Windows::System::UserProfile::LockScreen::GetImageStream();
00082                     if (imageStream != nullptr)
00083                     {
00084                         auto bitmapImage = ref new BitmapImage();
00085                         bitmapImage->SetSource(imageStream);
00086                         LockScreenImage->Source = bitmapImage;
00087                         LockScreenImage->Visibility = Windows::UI::Xaml::Visibility::Visible;
00088                     }
00089                     else
00090                     {
00091                         LockScreenImage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00092                         rootPage->NotifyUser("Setting the lock screen image failed.", NotifyType::ErrorMessage);
00093                     }
00094                 }
00095                 catch (Exception ^ex)
00096                 {
00097                     LockScreenImage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00098                     rootPage->NotifyUser("Invalid image selected or error opening stream.", NotifyType::ErrorMessage);
00099                 }
00100             });
00101         }
00102         else
00103         {
00104             LockScreenImage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00105             rootPage->NotifyUser("No image was selected", NotifyType::StatusMessage);
00106         }
00107     });
00108 }
Generated on Fri Nov 15 2024 22:20:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Model Member List

This is the complete list of members for Model, including all inherited members.
Description | Model
IsColorEnabled | Model
Name | Model
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/Scenario2.xaml.cpp Source File

  • SimpleInk
  • cpp

Scenario2.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2.xaml.h"
00014 #include <WindowsNumerics.h>
00015
00016 #define _USE_MATH_DEFINES
00017 #include <math.h>
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace Platform;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Numerics;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::UI::Core;
00026 using namespace Windows::UI::Input::Inking;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Media;
00030 using namespace Windows::UI::Xaml::Shapes;
00031
00032 InkDrawingAttributes^ CalligraphicPen::CreateInkDrawingAttributesCore(Brush^ brush, double strokeWidth)
00033 {
00034     InkDrawingAttributes^ inkDrawingAttributes = ref new InkDrawingAttributes();
00035     inkDrawingAttributes->PenTip = PenTipShape::Circle;
00036     inkDrawingAttributes->IgnorePressure = false;
00037     SolidColorBrush^ solidColorBrush = safe_cast<SolidColorBrush^>(brush);
00038
00039     if (solidColorBrush != nullptr)
00040     {
00041         inkDrawingAttributes->Color = solidColorBrush->Color;
00042     }
00043
00044     inkDrawingAttributes->Size = Size((float)strokeWidth, 2.0f * (float)strokeWidth);
00045     inkDrawingAttributes->PenTipTransform = make_float3x2_rotation((float)((M_PI * 45.0) / 180.0));
00046
00047     return inkDrawingAttributes;
00048 }
00049
00050 Scenario2::Scenario2()
00051 {
00052     InitializeComponent();
00053     LassoSelect = (Symbol)0xEF20;
00054     TouchWriting = (Symbol)0xED5F;
00055
00056     // Initialize the InkCanvas
00057     inkCanvas->InkPresenter->InputDeviceTypes = CoreInputDeviceTypes::Mouse | CoreInputDeviceTypes::Pen;
00058
00059     // Handlers to clear the selection when inking or erasing is detected
00060     inkCanvas->InkPresenter->StrokeInput->StrokeStarted += ref new TypedEventHandler<InkStrokeInput^, PointerEventArgs^>(this, &Scenario2::StrokeInput_StrokeStarted);
00061     inkCanvas->InkPresenter->StrokeInput->StrokeEnded += ref new TypedEventHandler<InkStrokeInput^, PointerEventArgs^>(this, &Scenario2::InkPresenter_StrokesErased);
00062 }
00063
00064 void Scenario2::StrokeInput_StrokeStarted(InkStrokeInput^ sender, PointerEventArgs^ args)
00065 {
00066     ClearSelection();
00067     inkCanvas->InkPresenter->UnprocessedInput->PointerPressed -= pointerPressedToken;
00068     inkCanvas->InkPresenter->UnprocessedInput->PointerMoved -= pointerMovedToken;
00069     inkCanvas->InkPresenter->UnprocessedInput->PointerReleased -= pointerReleasedToken;
00070 }
00071
00072 void Scenario2::InkPresenter_StrokesErased(InkStrokeInput^ sender, PointerEventArgs^ args)
00073 {
00074     ClearSelection();
00075     inkCanvas->InkPresenter->UnprocessedInput->PointerPressed -= pointerPressedToken;
00076     inkCanvas->InkPresenter->UnprocessedInput->PointerMoved -= pointerMovedToken;
00077     inkCanvas->InkPresenter->UnprocessedInput->PointerReleased -= pointerReleasedToken;
00078 }
00079
00080 void Scenario2::OnSizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00081 {
00082     HelperFunctions::UpdateCanvasSize(RootGrid, outputGrid, inkCanvas);
00083 }
00084
00085 void Scenario2::Toggle_Custom(Object^ sender, RoutedEventArgs^ e)
00086 {
00087     if (toggleButton->IsChecked)
00088     {
00089         auto types = inkCanvas->InkPresenter->InputDeviceTypes;
00090         inkCanvas->InkPresenter->InputDeviceTypes = types | CoreInputDeviceTypes::Touch;
00091     }
00092     else
00093     {
00094         auto types = inkCanvas->InkPresenter->InputDeviceTypes;
00095         inkCanvas->InkPresenter->InputDeviceTypes = types & ~CoreInputDeviceTypes::Touch;
00096     }
00097 }
00098
00099 void Scenario2::UnprocessedInput_PointerPressed(InkUnprocessedInput^ sender, PointerEventArgs^  args)
00100 {
00101     lasso = ref new Polyline();
00102     lasso->Stroke = ref new SolidColorBrush(Windows::UI::Colors::Blue);
00103     lasso->StrokeThickness = 1;
00104     lasso->StrokeDashArray = ref new DoubleCollection();
00105     lasso->StrokeDashArray->Append(5.0);
00106     lasso->StrokeDashArray->Append(2.0);
00107     lasso->Points->Append(args->CurrentPoint->RawPosition);
00108     selectionCanvas->Children->Append(lasso);
00109     isBoundRect = true;
00110 }
00111
00112 void Scenario2::UnprocessedInput_PointerMoved(InkUnprocessedInput^ sender, PointerEventArgs^  args)
00113 {
00114     if (isBoundRect)
00115     {
00116         lasso->Points->Append(args->CurrentPoint->RawPosition);
00117     }
00118 }
00119
00120 void Scenario2::UnprocessedInput_PointerReleased(InkUnprocessedInput^ sender, PointerEventArgs^ args)
00121 {
00122     lasso->Points->Append(args->CurrentPoint->RawPosition);
00123
00124     boundingRect = inkCanvas->InkPresenter->StrokeContainer->SelectWithPolyLine(lasso->Points);
00125     isBoundRect = false;
00126     DrawBoundingRect();
00127 }
00128
00129 void Scenario2::DrawBoundingRect()
00130 {
00131     selectionCanvas->Children->Clear();
00132
00133     if (boundingRect.Width <= 0 || boundingRect.Height <= 0)
00134     {
00135         return;
00136     }
00137
00138     auto rectangle = ref new Rectangle();
00139     rectangle->Stroke = ref new SolidColorBrush(Windows::UI::Colors::Blue);
00140     rectangle->StrokeThickness = 1;
00141     rectangle->StrokeDashArray = ref new DoubleCollection();
00142     rectangle->StrokeDashArray->Append(5.0);
00143     rectangle->StrokeDashArray->Append(2.0);
00144     rectangle->Width = boundingRect.Width;
00145     rectangle->Height = boundingRect.Height;
00146
00147     selectionCanvas->SetLeft(rectangle, boundingRect.X);
00148     selectionCanvas->SetTop(rectangle, boundingRect.Y);
00149     selectionCanvas->Children->Append(rectangle);
00150 }
00151
00152
00153 void Scenario2::ToolButton_Lasso(Object^ sender, RoutedEventArgs^ e)
00154 {
00155     // By default, pen barrel button or right mouse button is processed for inking
00156     // Set the configuration to instead allow processing these input on the UI thread
00157     inkCanvas->InkPresenter->InputProcessingConfiguration->RightDragAction = InkInputRightDragAction::LeaveUnprocessed;
00158
00159     pointerPressedToken = inkCanvas->InkPresenter->UnprocessedInput->PointerPressed += ref new TypedEventHandler<InkUnprocessedInput^, PointerEventArgs^>(this, &Scenario2::UnprocessedInput_PointerPressed);
00160     pointerMovedToken = inkCanvas->InkPresenter->UnprocessedInput->PointerMoved += ref new TypedEventHandler<InkUnprocessedInput^, PointerEventArgs^>(this, &Scenario2::UnprocessedInput_PointerMoved);
00161     pointerReleasedToken = inkCanvas->InkPresenter->UnprocessedInput->PointerReleased += ref new TypedEventHandler<InkUnprocessedInput^, PointerEventArgs^>(this, &Scenario2::UnprocessedInput_PointerReleased);
00162 }
00163
00164 void Scenario2::ClearDrawnBoundingRect()
00165 {
00166     if (selectionCanvas->Children->Size > 0)
00167     {
00168         selectionCanvas->Children->Clear();
00169         boundingRect = Rect::Empty;
00170     }
00171 }
00172
00173 void Scenario2::OnCopy(Object^ sender, RoutedEventArgs^ e)
00174 {
00175     inkCanvas->InkPresenter->StrokeContainer->CopySelectedToClipboard();
00176 }
00177
00178 void Scenario2::OnCut(Object^ sender, RoutedEventArgs^ e)
00179 {
00180     inkCanvas->InkPresenter->StrokeContainer->CopySelectedToClipboard();
00181     inkCanvas->InkPresenter->StrokeContainer->DeleteSelected();
00182     ClearDrawnBoundingRect();
00183 }
00184
00185 void Scenario2::OnPaste(Object^ sender, RoutedEventArgs^ e)
00186 {
00187     if (inkCanvas->InkPresenter->StrokeContainer->CanPasteFromClipboard())
00188     {
00189         inkCanvas->InkPresenter->StrokeContainer->PasteFromClipboard(Point((float)(scrollViewer->HorizontalOffset + 10) / scrollViewer->ZoomFactor, (float)(scrollViewer->VerticalOffset + 10) / scrollViewer->ZoomFactor));
00190     }
00191     else
00192     {
00193         rootPage->NotifyUser("Cannot paste from clipboard.", NotifyType::ErrorMessage);
00194     }
00195 }
00196
00197 void Scenario2::ClearSelection()
00198 {
00199     auto strokes = inkCanvas->InkPresenter->StrokeContainer->GetStrokes();
00200     for (auto stroke : strokes)
00201     {
00202         stroke->Selected = false;
00203     }
00204     ClearDrawnBoundingRect();
00205 }
00206
00207 void Scenario2::CurrentToolChanged(InkToolbar^ sender, Object^ args)
00208 {
00209     bool enabled = sender->ActiveTool->Equals(toolButtonLasso);
00210
00211     ButtonCut->IsEnabled = enabled;
00212     ButtonCopy->IsEnabled = enabled;
00213     ButtonPaste->IsEnabled = enabled;
00214 }
Generated on Fri Nov 15 2024 22:17:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cs/Scenario5_TimeZone.xaml.cs Source File

  • Calendar
  • cs

Scenario5_TimeZone.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.Text;
00013 using Windows.Foundation;
00014 using Windows.Globalization;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class Scenario5_TimeZone : Page
00021     {
00022         public Scenario5_TimeZone()
00023         {
00024             this.InitializeComponent();
00025         }
00026
00027         private string ReportCalendarData(Calendar calendar)
00028         {
00029             // Display individual date/time elements.
00030             return string.Format("In {0} time zone:   {1}   {2} {3}, {4}   {5}:{6}:{7} {8}  {9}",
00031                                  calendar.GetTimeZone(),
00032                                  calendar.DayOfWeekAsSoloString(),
00033                                  calendar.MonthAsSoloString(),
00034                                  calendar.DayAsPaddedString(2),
00035                                  calendar.YearAsString(),
00036                                  calendar.HourAsPaddedString(2),
00037                                  calendar.MinuteAsPaddedString(2),
00038                                  calendar.SecondAsPaddedString(2),
00039                                  calendar.PeriodAsString(),
00040                                  calendar.TimeZoneAsString(3));
00041         }
00042
00043         private void ShowResults_Click(object sender, RoutedEventArgs e)
00044         {
00045             // This scenario illustrates time zone support in Windows.Globalization.Calendar class
00046
00047             // Displayed time zones in addition to the local time zone.
00048             string[] timeZones = new[] { "UTC", "America/New_York", "Asia/Kolkata" };
00049
00050             // Store results here.
00051             StringBuilder results = new StringBuilder();
00052
00053             // Create default Calendar object
00054             Calendar calendar = new Calendar();
00055             string localTimeZone = calendar.GetTimeZone();
00056
00057             // Show current time in local time zone
00058             results.AppendLine("Current date and time:");
00059             results.AppendLine(ReportCalendarData(calendar));
00060
00061             // Show current time in additional time zones
00062             foreach (string timeZone in timeZones)
00063             {
00064                 calendar.ChangeTimeZone(timeZone);
00065                 results.AppendLine(ReportCalendarData(calendar));
00066             }
00067             results.AppendLine();
00068
00069             // Change back to local time zone
00070             calendar.ChangeTimeZone(localTimeZone);
00071
00072             // Show a time on 14th day of second month of next year.
00073             // Note the effect of daylight saving time on the results.
00074             results.AppendLine("Same time on 14th day of second month of next year:");
00075             calendar.AddYears(1); calendar.Month = 2; calendar.Day = 14;
00076             results.AppendLine(ReportCalendarData(calendar));
00077             foreach (string timeZone in timeZones)
00078             {
00079                 calendar.ChangeTimeZone(timeZone);
00080                 results.AppendLine(ReportCalendarData(calendar));
00081             }
00082             results.AppendLine();
00083
00084             // Change back to local time zone
00085             calendar.ChangeTimeZone(localTimeZone);
00086
00087             // Show a time on 14th day of tenth month of next year.
00088             // Note the effect of daylight saving time on the results.
00089             results.AppendLine("Same time on 14th day of tenth month of next year:");
00090             calendar.AddMonths(8);
00091             results.AppendLine(ReportCalendarData(calendar));
00092             foreach (string timeZone in timeZones)
00093             {
00094                 calendar.ChangeTimeZone(timeZone);
00095                 results.AppendLine(ReportCalendarData(calendar));
00096             }
00097             results.AppendLine();
00098
00099             // Display the results
00100             OutputTextBlock.Text = results.ToString();
00101         }
00102     }
00103 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cs/Scenario8_Copy.xaml.cs Source File

  • FileAccess
  • cs

Scenario8_Copy.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.IO;
00014 using Windows.Storage;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// Copying a file.
00023     /// </summary>
00024     public sealed partial class Scenario8 : Page
00025     {
00026         MainPage rootPage = MainPage.Current;
00027
00028         public Scenario8()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         protected override void OnNavigatedTo(NavigationEventArgs e)
00034         {
00035             rootPage.ValidateFile();
00036         }
00037
00038         private async void CopyFileButton_Click(object sender, RoutedEventArgs e)
00039         {
00040             StorageFile file = rootPage.sampleFile;
00041             if (file != null)
00042             {
00043                 try
00044                 {
00045                     StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
00046                     StorageFile fileCopy = await file.CopyAsync(picturesLibrary, "sample - Copy.dat", NameCollisionOption.ReplaceExisting);
00047                     rootPage.NotifyUser($"The file '{file.Name}' was copied and the new file was named '{fileCopy.Name}'.", NotifyType.StatusMessage);
00048                 }
00049                 catch (FileNotFoundException)
00050                 {
00051                     rootPage.NotifyUserFileNotExist();
00052                 }
00053                 catch (Exception ex)
00054                 {
00055                     // I/O errors are reported as exceptions.
00056                     rootPage.NotifyUser($"Error copying file '{file.Name}': {ex.Message}", NotifyType.ErrorMessage);
00057                 }
00058             }
00059             else
00060             {
00061                 rootPage.NotifyUserFileNotExist();
00062             }
00063         }
00064     }
00065 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cppwinrt/Scenario1.h Source File

  • Logging
  • cppwinrt

Scenario1.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1 : Scenario1T<Scenario1>
00019     {
00020         Scenario1();
00021
00022         void
00023         DoWin81Mode(
00024             Windows::Foundation::IInspectable const& sender,
00025             Windows::UI::Xaml::RoutedEventArgs const& args);
00026
00027         void
00028         DoWin10Mode(
00029             Windows::Foundation::IInspectable const& sender,
00030             Windows::UI::Xaml::RoutedEventArgs const& args);
00031     };
00032 }
00033
00034 namespace winrt::SDKTemplate::factory_implementation
00035 {
00036     struct Scenario1 : Scenario1T<Scenario1, implementation::Scenario1>
00037     {
00038     };
00039 }
Generated on Fri Nov 15 2024 22:19:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSuggestion/cpp/pch.cpp Source File

  • TextSuggestion
  • cpp

pch.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/Scenario6_CustomFilterAddedProps.xaml.cpp Source File

  • DeviceEnumerationAndPairing
  • cpp

Scenario6_CustomFilterAddedProps.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario6_CustomFilterAddedProps.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Platform::Collections;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::UI::Core;
00013 using namespace Windows::UI::Xaml;
00014 using namespace Windows::UI::Xaml::Controls;
00015 using namespace Windows::UI::Xaml::Controls::Primitives;
00016 using namespace Windows::UI::Xaml::Data;
00017 using namespace Windows::UI::Xaml::Input;
00018 using namespace Windows::UI::Xaml::Media;
00019 using namespace Windows::UI::Xaml::Navigation;
00020 using namespace Windows::Devices::Enumeration;
00021
00022 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00023
00024 Scenario6_CustomFilterAddedProps::Scenario6_CustomFilterAddedProps()
00025 {
00026     InitializeComponent();
00027     deviceWatcherHelper = ref new DeviceWatcherHelper(resultCollection, Dispatcher);
00028 }
00029
00030 void Scenario6_CustomFilterAddedProps::OnNavigatedTo(NavigationEventArgs^ e)
00031 {
00032     resultsListView->ItemsSource = resultCollection;
00033 }
00034
00035 void Scenario6_CustomFilterAddedProps::OnNavigatedFrom(NavigationEventArgs^ e)
00036 {
00037     deviceWatcherHelper->Reset();
00038 }
00039
00040 void Scenario6_CustomFilterAddedProps::StartWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00041 {
00042     StartWatcher();
00043 }
00044
00045 void Scenario6_CustomFilterAddedProps::StopWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     StopWatcher();
00048 }
00049
00050 void Scenario6_CustomFilterAddedProps::StartWatcher()
00051 {
00052     aqsFilterTextBox->IsEnabled = false;
00053     startWatcherButton->IsEnabled = false;
00054     resultCollection->Clear();
00055
00056     // Request some additional properties.  In this saample, these extra properties are just used in the ResultsListViewTemplate.
00057     // Take a look there in the XAML. Also look at the coverter used by the XAML GeneralPropertyValueConverter.  In general you just use
00058     // DeviceInformation.Properties["<property name>"] to get a property. e.g. DeviceInformation.Properties["System.Devices.InterfaceClassGuid"].
00059     Vector<String^>^ requestedProperties = ref new Vector<String^>();
00060     requestedProperties->Append("System.Devices.InterfaceClassGuid");
00061     requestedProperties->Append("System.ItemNameDisplay");
00062
00063     // Use AQS string filter from the text box
00064     DeviceWatcher^ deviceWatcher = DeviceInformation::CreateWatcher(
00065         aqsFilterTextBox->Text,
00066         requestedProperties);
00067
00068     rootPage->NotifyUser("Starting Watcher...", NotifyType::StatusMessage);
00069     deviceWatcherHelper->StartWatcher(deviceWatcher);
00070     stopWatcherButton->IsEnabled = true;
00071     stopWatcherButton->Focus(::FocusState::Keyboard);
00072     aqsFilterTextBox->IsEnabled = true;
00073 }
00074
00075 void Scenario6_CustomFilterAddedProps::StopWatcher()
00076 {
00077     aqsFilterTextBox->IsEnabled = false;
00078     stopWatcherButton->IsEnabled = false;
00079
00080     deviceWatcherHelper->StopWatcher();
00081
00082     startWatcherButton->IsEnabled = true;
00083     startWatcherButton->Focus(::FocusState::Keyboard);
00084     aqsFilterTextBox->IsEnabled = true;
00085 }
00086
Generated on Fri Nov 15 2024 22:19:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Scan Member List

This is the complete list of members for Scenario2_Scan, including all inherited members.
Button_Click(object sender, RoutedEventArgs e) | Scenario2_Scan | [inline, private]
DisplayNetworkReport(WiFiNetworkReport report) | Scenario2_Scan | [inline, private]
firstAdapter | Scenario2_Scan | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_Scan | [inline, protected]
ResultCollection | Scenario2_Scan |
rootPage | Scenario2_Scan | [private]
Scenario2_Scan() | Scenario2_Scan | [inline]
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserActivity/cs/Scenario2_AdvancedUserActivity.xaml.cs Source File

  • UserActivity
  • cs

Scenario2_AdvancedUserActivity.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.ApplicationModel.UserActivities;
00015 using Windows.UI;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class Scenario2_AdvancedUserActivity : Page
00025     {
00026         private UserActivitySession _currentSession;
00027
00028         public Scenario2_AdvancedUserActivity()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         protected override async void OnNavigatedTo(NavigationEventArgs e)
00034         {
00035             // If we were activated from a URI, say so.
00036             // A real app would use the information in the URI to restore state.
00037             var message = e.Parameter as string;
00038             if (!String.IsNullOrEmpty(message))
00039             {
00040                 MainPage.Current.NotifyUser(message, NotifyType.StatusMessage);
00041             }
00042
00043             await CreateUserActivityAsync();
00044         }
00045
00046         private async Task CreateUserActivityAsync()
00047         {
00048             // Get channel and create activity.
00049             UserActivityChannel channel = UserActivityChannel.GetDefault();
00050             UserActivity activity = await channel.GetOrCreateUserActivityAsync("Scenario2_AdvancedUserActivity");
00051
00052             // Set deep-link and properties.
00053             activity.ActivationUri = new Uri("sdkUserActivitySample:page?Scenario2_AdvancedUserActivity");
00054             activity.VisualElements.DisplayText = "README.md";
00055
00056             // Add advanced properties.
00057             activity.ContentUri = new Uri("https://raw.githubusercontent.com/Microsoft/Windows-universal-samples/master/README.md");
00058             activity.FallbackUri = new Uri("http://go.microsoft.com/fwlink/p/?LinkId=873257");
00059
00060             activity.VisualElements.Attribution = new UserActivityAttribution()
00061             {
00062
00063                 IconUri = new Uri("https://raw.githubusercontent.com/Microsoft/Windows-universal-samples/master/SharedContent/media/storelogo-sdk.png"),
00064                 AlternateText = "Windows SDK Samples",
00065                 AddImageQuery = false
00066             };
00067
00068             activity.VisualElements.BackgroundColor = Color.FromArgb(0xFF, 0x00, 0xb2, 0xf0);
00069             activity.VisualElements.Description = "https://raw.githubusercontent.com/Microsoft/Windows-universal-samples/master/README.md";
00070
00071             // Save to activity feed.
00072             await activity.SaveAsync();
00073
00074             // Create a session, which indicates that the user is engaged
00075             // in the activity.
00076             _currentSession = activity.CreateSession();
00077         }
00078
00079         protected override void OnNavigatedFrom(NavigationEventArgs e)
00080         {
00081             // Dispose the session, which indicates that the user is no longer
00082             // engaged in the activity.
00083             _currentSession?.Dispose();
00084         }
00085     }
00086 }
Generated on Fri Nov 15 2024 22:21:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraResolution/cpp/Scenario1_PreviewSettings.xaml.h Source File

  • CameraResolution
  • cpp

Scenario1_PreviewSettings.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_PreviewSettings.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario1_PreviewSettings sealed
00021     {
00022     public:
00023         Scenario1_PreviewSettings();
00024         virtual ~Scenario1_PreviewSettings();
00025
00026     protected:
00027         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00028
00029     private:
00030         MainPage^ _rootPage;
00031         Platform::Agile<Windows::Media::Capture::MediaCapture^> _mediaCapture;
00032         Windows::Foundation::EventRegistrationToken _mediaCaptureFailedEventToken;
00033
00034         bool _isPreviewing;
00035
00036         Concurrency::task<void> InitializeCameraAsync();
00037         Concurrency::task<void> CleanupCameraAsync();
00038
00039         void InitializeCameraButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void ComboBoxSettings_Changed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041
00042         void PopulateSettingsComboBox();
00043
00044         void MediaCapture_Failed(Windows::Media::Capture::MediaCapture^ sender, Windows::Media::Capture::MediaCaptureFailedEventArgs^ e);
00045     };
00046 }
Generated on Fri Nov 15 2024 22:18:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Nfc/PcscSdk/Pcsc.cs Source File

  • Nfc
  • PcscSdk

Pcsc.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.Runtime.InteropServices.WindowsRuntime;
00013 using Windows.Storage.Streams;
00014
00015 namespace Pcsc
00016 {
00017     /// <summary>
00018     /// PCSC GetData command
00019     /// </summary>
00020     public class GetData : Iso7816.ApduCommand
00021     {
00022         public enum GetDataDataType : byte
00023         {
00024             Uid = 0x00,
00025             HistoricalBytes = 0x01 // Returned data excludes CRC
00026         }
00027         public GetDataDataType Type
00028         {
00029             set { base.P1 = (byte)value; }
00030             get { return (GetDataDataType)base.P1; }
00031         }
00032         public GetData(GetDataDataType type)
00033             : base((byte)Iso7816.Cla.ReservedForPts, (byte)Pcsc.Ins.GetData, (byte)type, 0, null, 0)
00034         {
00035         }
00036     }
00037     /// <summary>
00038     /// PCSC LoadKeys command
00039     /// </summary>
00040     public class LoadKeys : Iso7816.ApduCommand
00041     {
00042         public enum LoadKeysKeyType : byte
00043         {
00044             CardKey = 0x00,
00045             ReaderKey = 0x80,
00046
00047             Mask = 0x80,
00048         }
00049         public enum LoadKeysTransmissionType : byte
00050         {
00051             Plain = 0x00,
00052             Secured = 0x40,
00053
00054             Mask = 0x40,
00055         }
00056         public enum LoadKeysStorageType : byte
00057         {
00058             Volatile = 0x00,
00059             NonVolatile = 0x20,
00060
00061             Mask = 0x20,
00062         }
00063         public LoadKeysKeyType KeyType
00064         {
00065             set { base.P1 = (byte)((base.P1 & ~(byte)LoadKeysKeyType.Mask) | (byte)(value & LoadKeysKeyType.Mask)); }
00066             get { return (LoadKeysKeyType)(base.P1 & (byte)LoadKeysKeyType.Mask); }
00067         }
00068         public LoadKeysTransmissionType TransmissionType
00069         {
00070             set { base.P1 = (byte)((base.P1 & ~(byte)LoadKeysTransmissionType.Mask) | (byte)(value & LoadKeysTransmissionType.Mask)); }
00071             get { return (LoadKeysTransmissionType)(base.P1 & (byte)LoadKeysTransmissionType.Mask); }
00072         }
00073         public LoadKeysStorageType StorageType
00074         {
00075             set { base.P1 = (byte)((base.P1 & ~(byte)LoadKeysStorageType.Mask) | (byte)(value & LoadKeysStorageType.Mask)); }
00076             get { return (LoadKeysStorageType)(base.P1 & (byte)LoadKeysStorageType.Mask); }
00077         }
00078         public byte ReaderKeyNumber
00079         {
00080             set { base.P1 = (byte)((base.P1 & 0xF0) | (byte)(value & 0x0F)); }
00081             get { return (byte)(base.P1 & 0x0F); }
00082         }
00083         public byte KeyNumber
00084         {
00085             set { base.P2 = value; }
00086             get { return base.P2; }
00087         }
00088         public byte[] KeyData
00089         {
00090             set { base.CommandData = value; }
00091             get { return base.CommandData; }
00092         }
00093         public LoadKeys(LoadKeysKeyType keyType, byte? readerKeyNumber, LoadKeysTransmissionType transmissionType, LoadKeysStorageType storageType, byte keyNumber, byte[] keyData)
00094             : base((byte)Iso7816.Cla.ReservedForPts, (byte)Pcsc.Ins.LoadKeys, (byte)((byte)keyType | (byte)transmissionType | (byte)storageType | (readerKeyNumber ?? 0)), keyNumber, keyData, null)
00095         {
00096         }
00097     }
00098     /// <summary>
00099     /// PCSC GeneralAuthenticate command
00100     /// </summary>
00101     public class GeneralAuthenticate : Iso7816.ApduCommand
00102     {
00103         public enum GeneralAuthenticateKeyType : byte
00104         {
00105             MifareKeyA = 0x60,
00106             PicoTagPassKeyB = 0x61
00107         }
00108         public enum GeneralAuthenticateVersionNumber : byte
00109         {
00110             VersionOne = 0x01
00111         }
00112         public GeneralAuthenticateVersionNumber VersionNumber
00113         {
00114             set { base.CommandData[0] = (byte)value; }
00115             get { return (GeneralAuthenticateVersionNumber)base.CommandData[0]; }
00116         }
00117         public ushort Address
00118         {
00119             set
00120             {
00121                 base.CommandData[1] = (byte)(value >> 8);
00122                 base.CommandData[2] = (byte)(value & 0x00FF);
00123             }
00124             get { return (ushort)((base.CommandData[1] << 8) | base.CommandData[2]); }
00125         }
00126         public byte KeyType
00127         {
00128             set { base.CommandData[3] = value; }
00129             get { return base.CommandData[3]; }
00130         }
00131         public byte KeyNumber
00132         {
00133             set { base.CommandData[4] = value; }
00134             get { return base.CommandData[4]; }
00135         }
00136         public GeneralAuthenticate(GeneralAuthenticateVersionNumber version, ushort address, GeneralAuthenticateKeyType keyType, byte keyNo)
00137             : base((byte)Iso7816.Cla.ReservedForPts, (byte)Pcsc.Ins.GeneralAuthenticate, 0, 0, new byte[5] { (byte)version, (byte)(address >> 8), (byte)(address & 0x00FF), (byte)keyType, keyNo }, null)
00138         {
00139         }
00140     }
00141     /// <summary>
00142     /// PCSC ReadBinary command
00143     /// </summary>
00144     public class ReadBinary : Iso7816.ApduCommand
00145     {
00146         public ReadBinary(ushort address, byte? expectedReturnBytes)
00147             : base((byte)Iso7816.Cla.ReservedForPts, (byte)Pcsc.Ins.ReadBinary, 0, 0, null, expectedReturnBytes)
00148         {
00149             this.Address = address;
00150         }
00151
00152         public ushort Address
00153         {
00154             set
00155             {
00156                 base.P1 = (byte)(value >> 8);
00157                 base.P2 = (byte)(value & 0x00FF);
00158             }
00159             get { return (ushort)((base.P1 << 8) | base.P2); }
00160         }
00161     }
00162     /// <summary>
00163     /// PCSC Updatebinary Command
00164     /// </summary>
00165     public class UpdateBinary : Iso7816.ApduCommand
00166     {
00167         public UpdateBinary(ushort address, byte[] dataToWrite)
00168             : base((byte)Iso7816.Cla.ReservedForPts, (byte)Pcsc.Ins.UpdateBinary, 0, 0, dataToWrite, null)
00169         {
00170             this.Address = address;
00171         }
00172
00173         public ushort Address
00174         {
00175             set
00176             {
00177                 base.P1 = (byte)(value >> 8);
00178                 base.P2 = (byte)(value & 0x00FF);
00179             }
00180             get { return (ushort)((base.P1 << 8) | base.P2); }
00181         }
00182     }
00183     /// <summary>
00184     /// PCSC GetUid command
00185     /// </summary>
00186     public class GetUid : GetData
00187     {
00188         public GetUid()
00189             : base(GetData.GetDataDataType.Uid)
00190         {
00191         }
00192     }
00193     /// <summary>
00194     /// PCSC GetHistoricalBytes command
00195     /// </summary>
00196     public class GetHistoricalBytes : GetData
00197     {
00198         public GetHistoricalBytes()
00199             : base(GetData.GetDataDataType.HistoricalBytes)
00200         {
00201         }
00202     }
00203     /// <summary>
00204     /// PCSC ManageSession command
00205     /// </summary>
00206     public class ManageSession : Iso7816.ApduCommand
00207     {
00208         public enum DataObjectType
00209         {
00210             Version = 0x80,
00211             StartTransparentSession = 0x81,
00212             EndTransparentSession = 0x82,
00213             Timer = 0x5F46,
00214         }
00215         public ManageSession(byte[] dataObjects)
00216             : base((byte)Iso7816.Cla.ReservedForPts, (byte)Iso7816.Ins.Envelope, 0x00, 0x00, dataObjects, null)
00217         {
00218             ApduResponseType = typeof(ManageSessionResponse);
00219         }
00220     }
00221     /// <summary>
00222     /// PCSC TransparentExchange command
00223     /// </summary>
00224     public class TransparentExchange : Iso7816.ApduCommand
00225     {
00226         public enum DataObjectType
00227         {
00228             Transceive = 0x95,
00229             Timer = 0x5F46,
00230         }
00231         public TransparentExchange(byte[] dataObjects)
00232             : base((byte)Iso7816.Cla.ReservedForPts, (byte)Iso7816.Ins.Envelope, 0x00, 0x01, dataObjects, null)
00233         {
00234             ApduResponseType = typeof(TransparentExchangeResponse);
00235         }
00236     }
00237     /// <summary>
00238     /// PCSC IncrementDecrement command
00239     /// </summary>
00240     public class IncrementDecrement : Iso7816.ApduCommand
00241     {
00242         public enum DataObjectType
00243         {
00244             Increment = 0xA0,
00245             Decrement = 0xA1
00246         }
00247         public IncrementDecrement(byte[] dataObjects)
00248             : base((byte)Iso7816.Cla.ReservedForPts, (byte)Iso7816.Ins.Envelope, 0x00, 0x03, dataObjects, null)
00249         {
00250         }
00251     }
00252     /// <summary>
00253     /// PCSC Apdu response
00254     /// </summary>
00255     public class ApduResponse : Iso7816.ApduResponse
00256     {
00257         public ApduResponse()
00258             : base()
00259         {
00260         }
00261     }
00262     /// <summary>
00263     /// PCSC ManageSession response
00264     /// </summary>
00265     public class ManageSessionResponse : Iso7816.ApduResponse
00266     {
00267         public enum DataObjectType
00268         {
00269             GenericErrorStatus = 0xC0,
00270             Version = 0x80,
00271         }
00272         public ManageSessionResponse()
00273             : base()
00274         {
00275         }
00276         public override bool Succeeded
00277         {
00278             get
00279             {
00280                 if (base.Succeeded)
00281                 {
00282                     byte[] value = ExtractTlvDataObject(new byte[1] { (byte)DataObjectType.GenericErrorStatus });
00283
00284                     if (value.Length != 3)
00285                         throw new System.InvalidOperationException("Invalid value size for TLV response");
00286
00287                     return (value[0] == 0x00 && value[1] == 0x90 && value[2] == 0x00); // XX SW1 SW2 XX=Number of bad data object in the APDU
00288                 }
00289
00290                 return false;
00291             }
00292         }
00293         public char Version
00294         {
00295             get
00296             {
00297                 byte[] value = ExtractTlvDataObject(new byte[1] { (byte)DataObjectType.Version });
00298
00299                 if (value.Length != 1)
00300                     throw new System.InvalidOperationException("Invalid value size for TLV response");
00301
00302                 return System.BitConverter.ToChar(value, 0);
00303             }
00304         }
00305     }
00306     /// <summary>
00307     /// PCSC TransparentExchange response
00308     /// </summary>
00309     public class TransparentExchangeResponse : Iso7816.ApduResponse
00310     {
00311         public enum DataObjectType
00312         {
00313             GenericErrorStatus = 0xC0,
00314             ResponseStatus = 0x96,
00315             IccResponse = 0x97,
00316         }
00317         public TransparentExchangeResponse()
00318             : base()
00319         {
00320         }
00321         public override bool Succeeded
00322         {
00323             get
00324             {
00325                 if (base.Succeeded)
00326                 {
00327                     byte[] value = ExtractTlvDataObject(new byte[1] { (byte)DataObjectType.GenericErrorStatus });
00328
00329                     if (value.Length != 3)
00330                         throw new System.InvalidOperationException("Invalid value size for TLV response");
00331
00332                     return (value[0] == 0x00 && value[1] == 0x90 && value[2] == 0x00); // XX SW1 SW2 XX=Number of bad data object in the APDU
00333                 }
00334
00335                 return false;
00336             }
00337         }
00338         public ushort ResponseStatus
00339         {
00340             get
00341             {
00342                 byte[] value = ExtractTlvDataObject(new byte[1] { (byte)DataObjectType.ResponseStatus });
00343
00344                 if (value.Length != 2)
00345                     throw new System.InvalidOperationException("Invalid value size for TLV response");
00346
00347                 return System.BitConverter.ToUInt16(value, 0);
00348             }
00349
00350         }
00351         public byte[] IccResponse
00352         {
00353             get
00354             {
00355                 return ExtractTlvDataObject(new byte[1] { (byte)DataObjectType.IccResponse });
00356             }
00357         }
00358     }
00359 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/Util/ApiInformation.cs Source File

  • AdvancedCasting
  • cs
  • Util

ApiInformation.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017
00018 namespace ScreenCasting.Util
00019 {
00020     class ApiInformation
00021     {
00022         public static bool IsTypePresent(string typeName)
00023         {
00024             try
00025             {
00026                 Windows.Media.Casting.CastingDevicePicker picker = new Windows.Media.Casting.CastingDevicePicker();
00027
00028                 return true;
00029             }
00030             catch {
00031                 return false;
00032             }
00033         }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cpp/cpp/Scenario4_CustomExceptionWRL.xaml.h Source File

  • ProxyStubsForWinRTComponents
  • cpp
  • cpp

Scenario4_CustomExceptionWRL.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008 #include "Scenario4_CustomExceptionWRL.g.h"
00009
00010 namespace SDKSample
00011 {
00012     namespace ProxyStubsForWinRTComponents
00013     {
00014         public ref class CustomExceptionWRL sealed
00015         {
00016         public:
00017             CustomExceptionWRL();
00018
00019         private:
00020             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021         };
00022     }
00023 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAccountManagement/cs/DefaultAccountScenario.xaml.cs Source File

  • WebAccountManagement
  • cs

DefaultAccountScenario.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.ApplicationSettings;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using SDKTemplate;
00017 using Windows.Security.Credentials;
00018 using Windows.Security.Authentication.Web.Core;
00019 using System;
00020 using Windows.Storage;
00021 using System.Threading.Tasks;
00022 using System.Collections.Generic;
00023 using Windows.UI.Popups;
00024 using Windows.UI.Xaml.Media;
00025
00026 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00027
00028 namespace Accounts
00029 {
00030     // Important Note for running this sample:
00031     // The sample as-is will not be able to get tokens without having it's app manifest being
00032     // modified to use the App Identity of a registered Microsoft Store/registered AAD app.
00033     //
00034     // See 'Related Topics' in the README.md for instructions on how to register an app.
00035
00036     /// <summary>
00037     /// This scenario covers getting the default account.
00038     ///
00039     /// First you must get the default account provider by passing the id "https://login.windows.local"
00040     /// into WebAuthenticationCoreManager::FindAccountProviderAsync.
00041     ///
00042     /// It's important to note whether this account is MSA or AAD depending on the authority that the
00043     /// provider has.
00044     ///    MSA: authority == "consumers"
00045     ///    AAD: authority == "organizations"
00046     /// These will determine what strings you pass into the token request.
00047     ///
00048     /// Then you can call WebAuthenticationCoreManager::RequestTokenSilentlyAsync or
00049     /// WebAuthenticationCoreManager::RequestTokenAsync to get a token for the user.
00050     ///
00051     /// The main difference between these APIs is that if the user needs to enter login
00052     /// credentials before a token can be returned, RequestTokenAsync will result in
00053     /// a UI popping up while RequestTokenSilentlyAsync will just return a result of
00054     /// UserInteractionRequired.
00055     ///
00056     /// If you hit UserInteractionRequired, then you will need to call the regular
00057     /// RequestTokenAsync.
00058     /// </summary>
00059
00060     public sealed partial class DefaultAccountScenario : Page
00061     {
00062         private MainPage rootPage;
00063
00064         const string DefaultProviderId = "https://login.windows.local";
00065         const string MicrosoftProviderId = "https://login.microsoft.com";
00066         const string MicrosoftAccountAuthority = "consumers";
00067         const string AzureActiveDirectoryAuthority = "organizations";
00068
00069         const string MicrosoftAccountClientId = "none";
00070         const string MicrosoftAccountScopeRequested = "wl.basic";
00071
00072         // To obtain azureAD tokens, you must register this app on the AzureAD portal, and obtain the client ID
00073         const string AzureActiveDirectoryClientId = "";
00074         const string AzureActiveDirectoryScopeRequested = "";
00075
00076         WebAccountProvider defaultProvider;
00077         WebAccount defaultAccount;
00078
00079         public DefaultAccountScenario()
00080         {
00081             this.InitializeComponent();
00082         }
00083
00084         protected override void OnNavigatedTo(NavigationEventArgs e)
00085         {
00086             rootPage = MainPage.Current;
00087
00088             IdentityChecker.SampleIdentityConfigurationCorrect(NotRegisteredWarning, AzureActiveDirectoryClientId);
00089         }
00090
00091         protected override void OnNavigatedFrom(NavigationEventArgs e)
00092         {
00093
00094         }
00095
00096         private async void Button_DefaultSignIn_Click(object sender, RoutedEventArgs e)
00097         {
00098             defaultProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(DefaultProviderId);
00099
00100             if(defaultProvider == null)
00101             {
00102                 rootPage.NotifyUser("This user does not have a primary account", NotifyType.StatusMessage);
00103             }
00104             else
00105             {
00106                 // Set the clientID and scope based on the authority. The authority tells us if the account is a Microsoft account or an Azure AD.
00107                 String scope = defaultProvider.Authority == MicrosoftAccountAuthority ? MicrosoftAccountScopeRequested : AzureActiveDirectoryScopeRequested;
00108                 String clientID = defaultProvider.Authority == MicrosoftAccountAuthority ? MicrosoftAccountClientId : AzureActiveDirectoryClientId;
00109
00110                 AuthenticateWithRequestToken(defaultProvider, scope, clientID);
00111             }
00112         }
00113
00114         private async void Button_GetTokenSilently_Click(object sender, RoutedEventArgs e)
00115         {
00116             if(defaultAccount == null || defaultProvider == null)
00117             {
00118                 rootPage.NotifyUser("No account known to get account silently", NotifyType.ErrorMessage);
00119             }
00120             else
00121             {
00122                 await GetTokenSilent(defaultProvider, defaultAccount);
00123             }
00124         }
00125
00126         private void Button_Reset_Click(object sender, RoutedEventArgs e)
00127         {
00128             defaultAccount = null;
00129             defaultProvider = null;
00130             button_GetTokenSilently.IsEnabled = false;
00131             textblock_SignedInStatus.Text = "Not signed in";
00132             textblock_SignedInStatus.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
00133             listview_SignedInAccounts.Items.Clear();
00134
00135         }
00136
00137         public async void AuthenticateWithRequestToken(WebAccountProvider Provider, String Scope, String ClientID)
00138         {
00139             try
00140             {
00141                 WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID);
00142
00143                 // Azure Active Directory requires a resource to return a token
00144                 if(Provider.Id == "https://login.microsoft.com" && Provider.Authority == "organizations")
00145                 {
00146                     webTokenRequest.Properties.Add("resource", "https://graph.windows.net");
00147                 }
00148
00149                 // If the user selected a specific account, RequestTokenAsync will return a token for that account.
00150                 // The user may be prompted for credentials or to authorize using that account with your app
00151                 // If the user selected a provider, the user will be prompted for credentials to login to a new account
00152                 WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
00153
00154                 if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
00155                 {
00156                     defaultAccount = webTokenRequestResult.ResponseData[0].WebAccount;
00157
00158                     button_GetTokenSilently.IsEnabled = true;
00159                     textblock_SignedInStatus.Text = "Signed in with:";
00160                     textblock_SignedInStatus.Foreground = new SolidColorBrush(Windows.UI.Colors.Green);
00161                     listview_SignedInAccounts.Items.Clear();
00162                     listview_SignedInAccounts.Items.Add(defaultAccount.Id);
00163                 }
00164
00165                 OutputTokenResult(webTokenRequestResult);
00166             }
00167             catch (Exception ex)
00168             {
00169                 rootPage.NotifyUser("Web Token request failed: " + ex, NotifyType.ErrorMessage);
00170             }
00171         }
00172
00173         private async Task GetTokenSilent(WebAccountProvider Provider, WebAccount Account)
00174         {
00175             // Set the clientID and scope based on the authority. The authority tells us if the account is a Microsoft account or an Azure AD.
00176             String scope = defaultProvider.Authority == MicrosoftAccountAuthority ? MicrosoftAccountScopeRequested : AzureActiveDirectoryScopeRequested;
00177             String clientID = defaultProvider.Authority == MicrosoftAccountAuthority ? MicrosoftAccountClientId : AzureActiveDirectoryClientId;
00178
00179             WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, scope, clientID);
00180
00181             // Azure Active Directory requires a resource to return a token
00182             if (Provider.Authority == "organizations")
00183             {
00184                 webTokenRequest.Properties.Add("resource", "https://graph.windows.net");
00185             }
00186
00187             WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, Account);
00188
00189             if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
00190             {
00191                 rootPage.NotifyUser("Silent request successful for user:" + webTokenRequestResult.ResponseData[0].WebAccount.UserName, NotifyType.StatusMessage);
00192             }
00193             else if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
00194             {
00195                 rootPage.NotifyUser("Cannot retrieve token silently because user interaction is required to complete this request.", NotifyType.ErrorMessage);
00196             }
00197             else
00198             {
00199                 rootPage.NotifyUser("Web Token request error: " + webTokenRequestResult.ResponseStatus + " Code: " + webTokenRequestResult.ResponseError.ErrorMessage, NotifyType.StatusMessage);
00200             }
00201         }
00202
00203         public void OutputTokenResult(WebTokenRequestResult result)
00204         {
00205             if (result.ResponseStatus == WebTokenRequestStatus.Success)
00206             {
00207                 rootPage.NotifyUser("Web Token request successful for user:" + result.ResponseData[0].WebAccount.UserName, NotifyType.StatusMessage);
00208             }
00209             else
00210             {
00211                 rootPage.NotifyUser("Web Token request error: " + result.ResponseStatus + " Code: " + result.ResponseError.ErrorMessage, NotifyType.StatusMessage);
00212             }
00213         }
00214
00215     }
00216 }
Generated on Fri Nov 15 2024 22:21:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario_SRGSConstraint Member List

This is the complete list of members for Scenario_SRGSConstraint, including all inherited members.
cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario_SRGSConstraint | [inline, private]
colorLookup | Scenario_SRGSConstraint | [private]
getColor(string colorString) | Scenario_SRGSConstraint | [inline, private]
HandleRecognitionResult(SpeechRecognitionResult recoResult) | Scenario_SRGSConstraint | [inline, private]
HResultPrivacyStatementDeclined | Scenario_SRGSConstraint | [private, static]
HResultRecognizerNotFound | Scenario_SRGSConstraint | [private, static]
InitializeRecognizer(Language recognizerLanguage) | Scenario_SRGSConstraint | [inline, private]
isPopulatingLanguages | Scenario_SRGSConstraint | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario_SRGSConstraint | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario_SRGSConstraint | [inline, protected]
PopulateLanguageDropdown() | Scenario_SRGSConstraint | [inline, private]
recognitionOperation | Scenario_SRGSConstraint | [private]
RecognizeWithoutUI_Click(object sender, RoutedEventArgs e) | Scenario_SRGSConstraint | [inline, private]
RecognizeWithUI_Click(object sender, RoutedEventArgs e) | Scenario_SRGSConstraint | [inline, private]
Scenario_SRGSConstraint() | Scenario_SRGSConstraint | [inline]
speechContext | Scenario_SRGSConstraint | [private]
speechRecognizer | Scenario_SRGSConstraint | [private]
SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args) | Scenario_SRGSConstraint | [inline, private]
speechResourceMap | Scenario_SRGSConstraint | [private]
Generated on Fri Nov 15 2024 22:24:01 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Common/CameraResources.cpp Source File

  • HolographicFaceTracking
  • cpp
  • Common

CameraResources.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013
00014 #include "CameraResources.h"
00015 #include "Common\DirectXHelper.h"
00016 #include "DeviceResources.h"
00017 #include <windows.graphics.directx.direct3d11.interop.h>
00018
00019 using namespace DirectX;
00020 using namespace Microsoft::WRL;
00021 using namespace Windows::Graphics::DirectX::Direct3D11;
00022 using namespace Windows::Graphics::Holographic;
00023 using namespace Windows::Perception::Spatial;
00024
00025 DX::CameraResources::CameraResources(HolographicCamera^ camera) :
00026     m_holographicCamera(camera),
00027     m_isStereo(camera->IsStereo),
00028     m_d3dRenderTargetSize(camera->RenderTargetSize)
00029 {
00030     m_d3dViewport = CD3D11_VIEWPORT(
00031         0.f, 0.f,
00032         m_d3dRenderTargetSize.Width,
00033         m_d3dRenderTargetSize.Height
00034         );
00035 };
00036
00037 // Updates resources associated with a holographic camera's swap chain.
00038 // The app does not access the swap chain directly, but it does create
00039 // resource views for the back buffer.
00040 void DX::CameraResources::CreateResourcesForBackBuffer(
00041     DX::DeviceResources* pDeviceResources,
00042     HolographicCameraRenderingParameters^ cameraParameters
00043     )
00044 {
00045     const auto device = pDeviceResources->GetD3DDevice();
00046
00047     // Get the WinRT object representing the holographic camera's back buffer.
00048     IDirect3DSurface^ surface = cameraParameters->Direct3D11BackBuffer;
00049
00050     // Get a DXGI interface for the holographic camera's back buffer.
00051     // Holographic cameras do not provide the DXGI swap chain, which is owned
00052     // by the system. The Direct3D back buffer resource is provided using WinRT
00053     // interop APIs.
00054     ComPtr<ID3D11Resource> resource;
00055     ThrowIfFailed(
00056         GetDXGIInterfaceFromObject(surface, IID_PPV_ARGS(&resource))
00057         );
00058
00059     // Get a Direct3D interface for the holographic camera's back buffer.
00060     ComPtr<ID3D11Texture2D> cameraBackBuffer;
00061     ThrowIfFailed(
00062         resource.As(&cameraBackBuffer)
00063         );
00064
00065     // Determine if the back buffer has changed. If so, ensure that the render target view
00066     // is for the current back buffer.
00067     if (m_d3dBackBuffer.Get() != cameraBackBuffer.Get())
00068     {
00069         // This can change every frame as the system moves to the next buffer in the
00070         // swap chain. This mode of operation will occur when certain rendering modes
00071         // are activated.
00072         m_d3dBackBuffer = cameraBackBuffer;
00073
00074         // Create a render target view of the back buffer.
00075         // Creating this resource is inexpensive, and is better than keeping track of
00076         // the back buffers in order to pre-allocate render target views for each one.
00077         DX::ThrowIfFailed(
00078             device->CreateRenderTargetView(
00079                 m_d3dBackBuffer.Get(),
00080                 nullptr,
00081                 &m_d3dRenderTargetView
00082                 )
00083             );
00084
00085         // Get the DXGI format for the back buffer.
00086         // This information can be accessed by the app using CameraResources::GetBackBufferDXGIFormat().
00087         D3D11_TEXTURE2D_DESC backBufferDesc;
00088         m_d3dBackBuffer->GetDesc(&backBufferDesc);
00089         m_dxgiFormat = backBufferDesc.Format;
00090
00091         // Check for render target size changes.
00092         Windows::Foundation::Size currentSize = m_holographicCamera->RenderTargetSize;
00093         if (m_d3dRenderTargetSize != currentSize)
00094         {
00095             // Set render target size.
00096             m_d3dRenderTargetSize = currentSize;
00097
00098             // A new depth stencil view is also needed.
00099             m_d3dDepthStencilView.Reset();
00100         }
00101     }
00102
00103     // Refresh depth stencil resources, if needed.
00104     if (m_d3dDepthStencilView == nullptr)
00105     {
00106         // Create a depth stencil view for use with 3D rendering if needed.
00107         CD3D11_TEXTURE2D_DESC depthStencilDesc(
00108             DXGI_FORMAT_D16_UNORM,
00109             static_cast<UINT>(m_d3dRenderTargetSize.Width),
00110             static_cast<UINT>(m_d3dRenderTargetSize.Height),
00111             m_isStereo ? 2 : 1, // Create two textures when rendering in stereo.
00112             1, // Use a single mipmap level.
00113             D3D11_BIND_DEPTH_STENCIL
00114             );
00115
00116         ComPtr<ID3D11Texture2D> depthStencil;
00117         DX::ThrowIfFailed(
00118             device->CreateTexture2D(
00119                 &depthStencilDesc,
00120                 nullptr,
00121                 &depthStencil
00122                 )
00123             );
00124
00125         CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(
00126             m_isStereo ? D3D11_DSV_DIMENSION_TEXTURE2DARRAY : D3D11_DSV_DIMENSION_TEXTURE2D
00127             );
00128         DX::ThrowIfFailed(
00129             device->CreateDepthStencilView(
00130                 depthStencil.Get(),
00131                 &depthStencilViewDesc,
00132                 &m_d3dDepthStencilView
00133                 )
00134             );
00135     }
00136
00137     // Create the constant buffer, if needed.
00138     if (m_viewProjectionConstantBuffer == nullptr)
00139     {
00140         // Create a constant buffer to store view and projection matrices for the camera.
00141         CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00142         DX::ThrowIfFailed(
00143             device->CreateBuffer(
00144                 &constantBufferDesc,
00145                 nullptr,
00146                 &m_viewProjectionConstantBuffer
00147                 )
00148             );
00149     }
00150 }
00151
00152 // Releases resources associated with a back buffer.
00153 void DX::CameraResources::ReleaseResourcesForBackBuffer(DX::DeviceResources* pDeviceResources)
00154 {
00155     const auto context = pDeviceResources->GetD3DDeviceContext();
00156
00157     // Release camera-specific resources.
00158     m_d3dBackBuffer.Reset();
00159     m_d3dRenderTargetView.Reset();
00160     m_d3dDepthStencilView.Reset();
00161     m_viewProjectionConstantBuffer.Reset();
00162
00163     // Ensure system references to the back buffer are released by clearing the render
00164     // target from the graphics pipeline state, and then flushing the Direct3D context.
00165     ID3D11RenderTargetView* nullViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { nullptr };
00166     context->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00167     context->Flush();
00168 }
00169
00170 // Updates the view/projection constant buffer for a holographic camera.
00171 void DX::CameraResources::UpdateViewProjectionBuffer(
00172     std::shared_ptr<DX::DeviceResources> deviceResources,
00173     HolographicCameraPose^ cameraPose,
00174     SpatialCoordinateSystem^ coordinateSystem
00175     )
00176 {
00177     // The system changes the viewport on a per-frame basis for system optimizations.
00178     m_d3dViewport = CD3D11_VIEWPORT(
00179         cameraPose->Viewport.Left,
00180         cameraPose->Viewport.Top,
00181         cameraPose->Viewport.Width,
00182         cameraPose->Viewport.Height
00183         );
00184
00185     // The projection transform for each frame is provided by the HolographicCameraPose.
00186     HolographicStereoTransform cameraProjectionTransform = cameraPose->ProjectionTransform;
00187
00188     // Get a container object with the view and projection matrices for the given
00189     // pose in the given coordinate system.
00190     Platform::IBox<HolographicStereoTransform>^ viewTransformContainer = cameraPose->TryGetViewTransform(coordinateSystem);
00191
00192     // If TryGetViewTransform returns a null pointer, that means the pose and coordinate
00193     // system cannot be understood relative to one another; content cannot be rendered
00194     // in this coordinate system for the duration of the current frame.
00195     // This usually means that positional tracking is not active for the current frame, in
00196     // which case it is possible to use a SpatialLocatorAttachedFrameOfReference to render
00197     // content that is not world-locked instead.
00198     DX::ViewProjectionConstantBuffer viewProjectionConstantBufferData;
00199     bool viewTransformAcquired = viewTransformContainer != nullptr;
00200     if (viewTransformAcquired)
00201     {
00202         // Otherwise, the set of view transforms can be retrieved.
00203         HolographicStereoTransform viewCoordinateSystemTransform = viewTransformContainer->Value;
00204
00205         // Update the view matrices. Holographic cameras (such as Microsoft HoloLens) are
00206         // constantly moving relative to the world. The view matrices need to be updated
00207         // every frame.
00208         viewProjectionConstantBufferData.viewProjection[0] = viewCoordinateSystemTransform.Left * cameraProjectionTransform.Left;
00209         viewProjectionConstantBufferData.viewProjection[1] = viewCoordinateSystemTransform.Right * cameraProjectionTransform.Right;
00210     }
00211
00212     // Use the D3D device context to update Direct3D device-based resources.
00213     const auto context = deviceResources->GetD3DDeviceContext();
00214
00215     // Loading is asynchronous. Resources must be created before they can be updated.
00216     if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || !viewTransformAcquired)
00217     {
00218         m_framePending = false;
00219     }
00220     else
00221     {
00222         // Update the view and projection matrices.
00223         context->UpdateSubresource(
00224             m_viewProjectionConstantBuffer.Get(),
00225             0,
00226             nullptr,
00227             &viewProjectionConstantBufferData,
00228             0,
00229             0
00230             );
00231
00232         m_framePending = true;
00233     }
00234 }
00235
00236 // Gets the view-projection constant buffer for the HolographicCamera and attaches it
00237 // to the shader pipeline.
00238 bool DX::CameraResources::AttachViewProjectionBuffer(
00239     std::shared_ptr<DX::DeviceResources> deviceResources
00240     )
00241 {
00242     // This method uses Direct3D device-based resources.
00243     const auto context = deviceResources->GetD3DDeviceContext();
00244
00245     // Loading is asynchronous. Resources must be created before they can be updated.
00246     // Cameras can also be added asynchronously, in which case they must be initialized
00247     // before they can be used.
00248     if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || m_framePending == false)
00249     {
00250         return false;
00251     }
00252
00253     // Set the viewport for this camera.
00254     context->RSSetViewports(1, &m_d3dViewport);
00255
00256     // Send the constant buffer to the vertex shader.
00257     context->VSSetConstantBuffers(
00258         1,
00259         1,
00260         m_viewProjectionConstantBuffer.GetAddressOf()
00261         );
00262
00263     // The template includes a pass-through geometry shader that is used by
00264     // default on systems that don't support the D3D11_FEATURE_D3D11_OPTIONS3::
00265     // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer extension. The shader
00266     // will be enabled at run-time on systems that require it.
00267     // If your app will also use the geometry shader for other tasks and those
00268     // tasks require the view/projection matrix, uncomment the following line
00269     // of code to send the constant buffer to the geometry shader as well.
00270     /*context->GSSetConstantBuffers(
00271         1,
00272         1,
00273         m_viewProjectionConstantBuffer.GetAddressOf()
00274         );*/
00275
00276     m_framePending = false;
00277
00278     return true;
00279 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraResolution/cpp/pch.cpp Source File

  • CameraResolution
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/Tasks/SampleBackgroundTask.cpp Source File

  • BackgroundTask
  • cpp
  • Tasks

SampleBackgroundTask.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 // SampleBackgroundTask.cpp
00012 #include "pch.h"
00013 #include "SampleBackgroundTask.h"
00014
00015 using namespace Tasks;
00016 using namespace Windows::ApplicationModel::Background;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Storage;
00019 using namespace Windows::System::Threading;
00020
00021 void SampleBackgroundTask::Run(IBackgroundTaskInstance^ taskInstance)
00022 {
00023     //
00024     // Query BackgroundWorkCost
00025     // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
00026     // of work in the background task and return immediately.
00027     //
00028     auto cost = BackgroundWorkCost::CurrentBackgroundWorkCost;
00029     auto settings = ApplicationData::Current->LocalSettings;
00030     settings->Values->Insert("BackgroundWorkCost", cost.ToString());
00031
00032     //
00033     // Associate a cancellation handler with the background task.
00034     //
00035     taskInstance->Canceled += ref new BackgroundTaskCanceledEventHandler(this, &SampleBackgroundTask::OnCanceled);
00036
00037     //
00038     // Get the deferral object from the task instance, and take a reference to the taskInstance.
00039     //
00040     TaskDeferral = taskInstance->GetDeferral();
00041     TaskInstance = taskInstance;
00042
00043     auto timerDelegate = [this](ThreadPoolTimer^ timer)
00044     {
00045         if ((CancelRequested == false) &&
00046             (Progress < 100))
00047         {
00048             Progress += 10;
00049             TaskInstance->Progress = Progress;
00050         }
00051         else
00052         {
00053             PeriodicTimer->Cancel();
00054
00055             //
00056             // Record that this background task ran.
00057             //
00058             auto taskStatus = (Progress < 100) ? "Canceled with reason: " + CancelReason.ToString() : "Completed";
00059             auto key = TaskInstance->Task->Name;
00060             auto settings = ApplicationData::Current->LocalSettings;
00061             settings->Values->Insert(key, taskStatus);
00062
00063             //
00064             // Indicate that the background task has completed.
00065             //
00066             TaskDeferral->Complete();
00067         }
00068     };
00069
00070     TimeSpan period;
00071     period.Duration = 1000 * 10000; // 1 second
00072     PeriodicTimer = ThreadPoolTimer::CreatePeriodicTimer(ref new TimerElapsedHandler(timerDelegate), period);
00073 }
00074
00075 //
00076 // Handles background task cancellation.
00077 //
00078 void SampleBackgroundTask::OnCanceled(IBackgroundTaskInstance^ taskInstance, BackgroundTaskCancellationReason reason)
00079 {
00080     //
00081     // Indicate that the background task is canceled.
00082     //
00083     CancelRequested = true;
00084     CancelReason = reason;
00085 }
Generated on Fri Nov 15 2024 22:18:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cpp/Common/SeekBarElement.cpp Source File

  • 360VideoPlayback
  • cpp
  • Common

SeekBarElement.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "SeekBarElement.h"
00003 #include "DeviceResources.h"
00004 #include "DirectXHelper.h"
00005 #include "..\360VideoPlaybackMain.h"
00006 #include "..\AppView.h"
00007
00008 using namespace _360VideoPlayback;
00009 using namespace DX;
00010 using namespace Microsoft::WRL;
00011 using namespace Platform;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::Foundation::Numerics;
00015 using namespace Windows::Globalization::NumberFormatting;
00016 using namespace Windows::Media::Core;
00017 using namespace Windows::Media::Playback;
00018 using namespace Windows::UI::Input::Spatial;
00019
00020 const long long s_hnsPerMillisecond = 10000;
00021 const int64 ticksPerSecond = 10000000LL;
00022 const UINT millisecondsPerSecond = 1000;
00023 const unsigned int END_OF_PLAYBACK_BUFFER_MS = 200;
00024
00025 SeekBarElement::SeekBarElement(float elementWidth, float elementHeight, float leftRightPadding, float topBottomPadding) :
00026     m_leftRightPadding(leftRightPadding),
00027     m_topBottomPadding(topBottomPadding),
00028     m_currentPlayPosition(0),
00029     m_currentVideoDuration(0),
00030     m_secondsElapsedSinceTimeUpdate(0.0)
00031 {
00032     m_isFocusIntersectionCalculated = true;
00033     m_elementSize = float2(elementWidth, elementHeight);
00034     m_sliderPosition = 0.0f;
00035     m_sliderWidth = max((m_elementSize.x - (m_leftRightPadding * 2.0f)), 0.0f);
00036     m_sliderHeight = max((m_elementSize.y - (m_topBottomPadding * 2.0f)), 0.0f);
00037
00038     m_sliderFrontSegment = std::make_shared<Line>(m_sliderHeight);
00039     AddChildElement(m_sliderFrontSegment);
00040
00041     m_sliderRemainingSegment = std::make_shared<Line>(m_sliderHeight);
00042     AddChildElement(m_sliderRemainingSegment);
00043
00044     float seekBarYCoordinate = m_topBottomPadding + (m_sliderHeight * 0.5f);
00045     m_sliderFrontSegmentStart = D2D1::Point2F(m_leftRightPadding, 0.0f);
00046     m_sliderFrontSegment->SetStartPoint(m_sliderFrontSegmentStart);
00047     m_sliderFrontSegment->SetTranslation({ 0.0f, seekBarYCoordinate });
00048
00049     m_sliderRemainingSegmentEnd = D2D1::Point2F(m_elementSize.x - m_leftRightPadding, 0.0f);
00050     m_sliderRemainingSegment->SetEndPoint(m_sliderRemainingSegmentEnd);
00051     m_sliderRemainingSegment->SetTranslation({ 0.0f, seekBarYCoordinate });
00052     m_textSize = FONT_SIZE * 1.25f;
00053     m_elapsedTimeText = std::make_shared<Text>(L"", m_textSize, DWRITE_FONT_WEIGHT_NORMAL);
00054     AddChildElement(m_elapsedTimeText);
00055
00056     m_remainingTimeText = std::make_shared<Text>(L"", m_textSize, DWRITE_FONT_WEIGHT_NORMAL);
00057     AddChildElement(m_remainingTimeText);
00058 }
00059
00060 void SeekBarElement::Initialize()
00061 {
00062     auto d2dcontext = m_deviceResources->GetD2DDeviceContext();
00063     __super::Initialize();
00064
00065     DX::ThrowIfFailed(
00066         d2dcontext->CreateSolidColorBrush(
00067             D2D1::ColorF(D2D1::ColorF::White),
00068             &m_frontSegmentBrush));
00069
00070     DX::ThrowIfFailed(
00071         d2dcontext->CreateSolidColorBrush(
00072             D2D1::ColorF(D2D1::ColorF::Gray),
00073             &m_endSegmentBrush));
00074
00075     DX::ThrowIfFailed(
00076         d2dcontext->CreateSolidColorBrush(
00077             D2D1::ColorF(D2D1::ColorF::White),
00078             &m_brush));
00079
00080     m_sliderFrontSegment->SetBrush(m_frontSegmentBrush.Get());
00081     m_sliderFrontSegment->Initialize();
00082
00083     m_sliderRemainingSegment->SetBrush(m_endSegmentBrush.Get());
00084     m_sliderRemainingSegment->Initialize();
00085
00086
00087     m_elapsedTimeText->SetBrush(m_brush.Get());
00088     m_elapsedTimeText->Initialize();
00089     m_remainingTimeText->SetBrush(m_brush.Get());
00090     m_remainingTimeText->Initialize();
00091     // Text goes below the seekbar
00092     float startYCoordinateOfText = m_elementSize.y - m_topBottomPadding + 4.0f;
00093     m_elapsedTimeText->SetTranslation({ m_leftRightPadding, startYCoordinateOfText });
00094     m_remainingTimeText->SetTranslation({ (m_elementSize.x - m_leftRightPadding - (FONT_SIZE * 3.0f)), startYCoordinateOfText });
00095
00096     UpdateLayoutFromCurrentTime();
00097 }
00098
00099 void SeekBarElement::UpdateSliderPosition(float value)
00100 {
00101     m_sliderPosition = value;
00102     // Clamp [0,1]
00103     if (m_sliderPosition < 0.0f)
00104     {
00105         m_sliderPosition = 0.0f;
00106     }
00107     else if (m_sliderPosition > 1.0f)
00108     {
00109         m_sliderPosition = 1.0f;
00110     }
00111
00112     float sliderUIPosition = m_sliderPosition > 0.0f ? (m_sliderWidth * m_sliderPosition) + m_leftRightPadding : m_leftRightPadding;
00113     m_sliderFrontSegmentEnd = D2D1::Point2F(sliderUIPosition, 0.0f);
00114     m_sliderFrontSegment->SetEndPoint(m_sliderFrontSegmentEnd);
00115     m_sliderRemainingSegmentStart = D2D1::Point2F(sliderUIPosition, 0.0f);
00116     m_sliderRemainingSegment->SetStartPoint(m_sliderRemainingSegmentStart);
00117 }
00118
00119 void SeekBarElement::Update(const DX::StepTimer& timer, SpatialPointerPose^ cameraPose)
00120 {
00121     __super::Update(timer, cameraPose);
00122     m_secondsElapsedSinceTimeUpdate += timer.GetElapsedSeconds();
00123
00124     // Update the current seek bar time no more than once every second.
00125     if (m_secondsElapsedSinceTimeUpdate > 1.0)
00126     {
00127         UpdateLayoutFromCurrentTime();
00128         m_secondsElapsedSinceTimeUpdate = 0.0;
00129     }
00130 }
00131
00132 void SeekBarElement::UpdateLayoutFromCurrentTime()
00133 {
00134     m_currentVideoDuration = AppView::GetMediaPlayer()->PlaybackSession->NaturalDuration.Duration / s_hnsPerMillisecond;
00135     if (m_currentVideoDuration != 0)
00136     {
00137         m_currentPlayPosition = AppView::GetMediaPlayer()->PlaybackSession->Position.Duration / s_hnsPerMillisecond;
00138         if (m_currentPlayPosition > m_currentVideoDuration)
00139         {
00140             m_currentVideoDuration = m_currentPlayPosition;
00141         }
00142     }
00143     // Update current and remaining time indicators
00144     m_elapsedTimeString = FormatTimeString(m_currentPlayPosition)->Data();
00145     m_remainingTimeString = FormatTimeString(m_currentVideoDuration - m_currentPlayPosition)->Data();
00146     m_elapsedTimeText->SetText(m_elapsedTimeString);
00147     m_remainingTimeText->SetText(m_remainingTimeString);
00148
00149     float currentTimeSliderPosition = static_cast<float>(m_currentVideoDuration) > 0.0f ? static_cast<float>(m_currentPlayPosition) / static_cast<float>(m_currentVideoDuration) : 0.0f;
00150     UpdateSliderPosition(currentTimeSliderPosition);
00151 }
00152
00153 void SeekBarElement::PerformAction()
00154 {
00155     // Update the Slider's position
00156     float xIntersectionPoint = m_elementCoordIntersectionPoint.x;
00157     // Clamp before and after the slider
00158     // Otherwise compute slider based on relative position
00159     if (xIntersectionPoint < m_leftRightPadding)
00160     {
00161         UpdateSliderPosition(0.0f);
00162     }
00163     else if (xIntersectionPoint > (m_leftRightPadding + m_sliderWidth))
00164     {
00165         UpdateSliderPosition(1.0f);
00166     }
00167     else
00168     {
00169         UpdateSliderPosition((xIntersectionPoint - m_leftRightPadding) / m_sliderWidth);
00170     }
00171
00172     unsigned int seekTime = static_cast<unsigned int>(m_currentVideoDuration * m_sliderPosition);
00173
00174     if (seekTime >= (static_cast<unsigned int>(AppView::GetMediaPlayer()->PlaybackSession->NaturalDuration.Duration / s_hnsPerMillisecond)) - END_OF_PLAYBACK_BUFFER_MS)
00175     {
00176         seekTime = (static_cast<unsigned int>(AppView::GetMediaPlayer()->PlaybackSession->NaturalDuration.Duration / s_hnsPerMillisecond)) - END_OF_PLAYBACK_BUFFER_MS;
00177     }
00178     auto seekTimeSpan = TimeSpan();
00179     seekTimeSpan.Duration = static_cast<int64>(seekTime) * s_hnsPerMillisecond;
00180     AppView::GetMediaPlayer()->PlaybackSession->Position = seekTimeSpan;
00181 }
00182
00183 String^ SeekBarElement::FormatTimeString(int64 intervalValue)
00184 {
00185     String^ formattedTimeSpan;
00186     std::chrono::milliseconds duration{ intervalValue };
00187     auto seconds = static_cast<unsigned int>(std::chrono::duration_cast<std::chrono::seconds>(duration).count());
00188     auto minutes = static_cast<unsigned int>(std::chrono::duration_cast<std::chrono::minutes>(duration).count());
00189     seconds -= minutes * 60;
00190     auto hours = static_cast<unsigned int>(std::chrono::duration_cast<std::chrono::hours>(duration).count());
00191     minutes -= hours * 60;
00192
00193     DecimalFormatter^ twoDigitNumberFormatter = ref new DecimalFormatter(
00194         Windows::System::UserProfile::GlobalizationPreferences::Languages,
00195         Windows::System::UserProfile::GlobalizationPreferences::HomeGeographicRegion);
00196     twoDigitNumberFormatter->FractionDigits = 0;
00197     twoDigitNumberFormatter->IsGrouped = false;
00198     twoDigitNumberFormatter->IntegerDigits = 2;
00199
00200     if (hours > 0)
00201     {
00202         // Display Hours naturally, but display minutes and seconds using 2 digits
00203         formattedTimeSpan = ref new String(
00204             (twoDigitNumberFormatter->FormatUInt(hours) + L":" +
00205                 twoDigitNumberFormatter->FormatUInt(minutes) + L":" +
00206                 twoDigitNumberFormatter->FormatUInt(seconds))->Data());
00207     }
00208     else
00209     {
00210         // If the hour count is 0, then only display minutes and seconds
00211         formattedTimeSpan = ref new String(
00212             (twoDigitNumberFormatter->FormatUInt(minutes) + L":" +
00213                 twoDigitNumberFormatter->FormatUInt(seconds))->Data());
00214     }
00215     return formattedTimeSpan;
00216 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cpp/Scenario4_Override.xaml.cpp Source File

  • DateTimeFormatting
  • cpp

Scenario4_Override.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario4_Override.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Platform::Collections;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Globalization;
00022 using namespace Windows::Globalization::DateTimeFormatting;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 Scenario4_Override::Scenario4_Override()
00028 {
00029     InitializeComponent();
00030 }
00031
00032 void Scenario4_Override::Display()
00033 {
00034     // This scenario uses the Windows.Globalization.DateTimeFormatting.DateTimeFormatter class
00035     // to format a date/time by using a formatter that provides specific languages,
00036     // geographic region, calendar and clock
00037
00038     //Get the current default application context language
00039     String^ currentLanguage = ApplicationLanguages::Languages->GetAt(0);
00040
00041     // Array languages used by the test
00042     auto ja = ref new Vector<String^>({ "ja-JP" });
00043     auto fr = ref new Vector<String^>({ "fr-FR" });
00044     auto de = ref new Vector<String^>({ "de-DE" });
00045
00046     // Formatters for dates and times
00047     Array<DateTimeFormatter^> ^dateFormatters = {
00048         ref new DateTimeFormatter("longdate", ja, "JP", CalendarIdentifiers::Japanese, ClockIdentifiers::TwelveHour),
00049
00050         ref new DateTimeFormatter("month day", fr, "FR", CalendarIdentifiers::Gregorian, ClockIdentifiers::TwentyFourHour),
00051
00052         ref new DateTimeFormatter(
00053             YearFormat::Abbreviated,
00054             MonthFormat::Abbreviated,
00055             DayFormat::Default,
00056             DayOfWeekFormat::None,
00057             HourFormat::None,
00058             MinuteFormat::None,
00059             SecondFormat::None,
00060             de, "DE", CalendarIdentifiers::Gregorian, ClockIdentifiers::TwelveHour),
00061
00062         ref new DateTimeFormatter("longtime", ja, "JP", CalendarIdentifiers::Japanese, ClockIdentifiers::TwelveHour),
00063
00064         ref new DateTimeFormatter("hour minute", fr, "FR", CalendarIdentifiers::Gregorian, ClockIdentifiers::TwentyFourHour),
00065
00066         ref new DateTimeFormatter(
00067             YearFormat::None,
00068             MonthFormat::None,
00069             DayFormat::None,
00070             DayOfWeekFormat::None,
00071             HourFormat::Default,
00072             MinuteFormat::Default,
00073             SecondFormat::None,
00074             de, "DE", CalendarIdentifiers::Gregorian, ClockIdentifiers::TwelveHour)
00075     };
00076
00077     // Obtain the date that will be formatted.
00078     Windows::Globalization::Calendar^ cal = ref new Windows::Globalization::Calendar();
00079     Windows::Foundation::DateTime dateToFormat = cal->GetDateTime();
00080
00081     // Keep the results here
00082     String^ results = "";
00083     results = results + "Current default application context language: " + currentLanguage + "\n\n";
00084
00085     // Generate the results.
00086     for (auto formatter : dateFormatters)
00087     {
00088         // Perform the actual formatting.
00089         results = results + formatter->Template + ": (" + formatter->ResolvedLanguage + ") " + formatter->Format(dateToFormat) + "\n";
00090     }
00091
00092     // Display the results.
00093     OutputTextBlock->Text = results;
00094 }
Generated on Fri Nov 15 2024 22:19:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cs/SampleConfiguration.cs Source File

  • IoT-GPIO
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "GPIO C# Sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Get and set GPIO pin value", ClassType=typeof(Scenario1_GetAndSetPin)},
00025             new Scenario() { Title="Listen for changes in GPIO pin value", ClassType=typeof(Scenario2_Listen)},
00026         };
00027
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

App Member List

This is the complete list of members for App, including all inherited members.
App() | App | [inline]
Current_UnhandledException(object sender, UnhandledExceptionEventArgs e) | App | [inline, private]
OnActivated(IActivatedEventArgs args) | App | [inline, protected]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnSuspending(object sender, SuspendingEventArgs e) | App | [inline, private]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JapanesePhoneticAnalysis/cs/SampleConfiguration.cs Source File

  • JapanesePhoneticAnalysis
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Japanese phonetic analysis";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Analyze Japanese text", ClassType=typeof(Scenario1_Analyze)},
00025         };
00026     }
00027
00028     public class Scenario
00029     {
00030         public string Title { get; set; }
00031         public Type ClassType { get; set; }
00032     }
00033 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCloudFontIntegration/cpp/Scenario_Document2.xaml.cpp Source File

  • XamlCloudFontIntegration
  • cpp

Scenario_Document2.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario_Document2.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Primitives;
00023 using namespace Windows::UI::Xaml::Data;
00024 using namespace Windows::UI::Xaml::Input;
00025 using namespace Windows::UI::Xaml::Media;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028
00029 Scenario_Document2::Scenario_Document2()
00030 {
00031     InitializeComponent();
00032 }
00033
00034
00035 void Scenario_Document2::Page_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00036 {
00037     // Font formatting is being applied on page load rather than in XAML markup
00038     // so that the on-demand cloud font behavior can be experienced when the
00039     // app runs rather than when the XAML file is viewed in Visual Studio.
00040
00041     // Formatting will be applied to all content elements in the page that don't
00042     // already have FontFamily set.
00043     this->FontFamily = ref new Windows::UI::Xaml::Media::FontFamily("FangSong");
00044 }
Generated on Fri Nov 15 2024 22:19:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: GlobalizationPreferences/cppwinrt/Project.idl Source File

  • GlobalizationPreferences
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_Prefs : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_Prefs();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_Lang : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_Lang();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3_Region : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3_Region();
00030     }
00031
00032     [default_interface]
00033     runtimeclass Scenario4_Input : Windows.UI.Xaml.Controls.Page
00034     {
00035         Scenario4_Input();
00036     }
00037 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/Controls/UpdateFourTilesControl.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • Controls

UpdateFourTilesControl.xaml.cs

Go to the documentation of this file.
00001 ﻿using Notifications.Helpers;
00002 using Windows.UI.Xaml;
00003 using Windows.UI.Xaml.Controls;
00004
00005 // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
00006
00007 namespace Notifications.Controls
00008 {
00009     public sealed partial class UpdateFourTilesControl : UserControl
00010     {
00011         public UpdateFourTilesControl()
00012         {
00013             this.InitializeComponent();
00014         }
00015
00016         private async void ButtonPin_Click(object sender, RoutedEventArgs e)
00017         {
00018             ButtonPin.IsEnabled = false;
00019
00020             await TilesHelper.UpdateTiles(TextBoxPayload.Text);
00021
00022             ButtonPin.IsEnabled = true;
00023         }
00024
00025         public void SetTilePayload(string xml)
00026         {
00027             TextBoxPayload.Text = xml;
00028         }
00029
00030         private void ButtonToggleShowPayload_Click(object sender, RoutedEventArgs e)
00031         {
00032             if (TextBoxPayload.Visibility == Visibility.Visible)
00033             {
00034                 TextBoxPayload.Visibility = Visibility.Collapsed;
00035                 ButtonToggleShowPayload.Content = "Show Payload";
00036             }
00037
00038             else
00039             {
00040                 TextBoxPayload.Visibility = Visibility.Visible;
00041                 ButtonToggleShowPayload.Content = "Hide Payload";
00042             }
00043         }
00044     }
00045 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

List< T >::POSITION Member List

This is the complete list of members for List< T >::POSITION, including all inherited members.
List< T > class | List< T >::POSITION | [friend]
operator!=(const POSITION &p) const | List< T >::POSITION | [inline]
operator==(const POSITION &p) const | List< T >::POSITION | [inline]
pNode | List< T >::POSITION | [private]
POSITION() | List< T >::POSITION | [inline]
POSITION(Node *p) | List< T >::POSITION | [inline, private]
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

WorldCeilingMesh Member List

This is the complete list of members for WorldCeilingMesh, including all inherited members.
m_indexBuffer | MeshObject | [protected]
m_indexCount | MeshObject | [protected]
m_vertexBuffer | MeshObject | [protected]
m_vertexCount | MeshObject | [protected]
MeshObject() | MeshObject |
Render(_In_ ID3D11DeviceContext *context) | MeshObject | [virtual]
WorldCeilingMesh(_In_ winrt::com_ptr< ID3D11Device3 > const &device) | WorldCeilingMesh |
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Account Member List

This is the complete list of members for Account, including all inherited members.
AccountName | Account
IconUri | Account
Generated on Fri Nov 15 2024 22:24:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cpp/SampleConfiguration.cpp Source File

  • NumberFormatting
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Percent and Permille Formatting", "SDKTemplate.Scenario1_PercentPermilleFormatting" },
00012     { "Decimal Formatting", "SDKTemplate.Scenario2_DecimalFormatting" },
00013     { "Currency Formatting", "SDKTemplate.Scenario3_CurrencyFormatting" },
00014     { "Number Parsing", "SDKTemplate.Scenario4_NumberParsing" },
00015     { "Rounding and Padding", "SDKTemplate.Scenario5_RoundingAndPadding" },
00016     { "Numeral System Translation", "SDKTemplate.Scenario6_NumeralSystemTranslation" },
00017     { "Formatting/Translation using Unicode Extensions", "SDKTemplate.Scenario7_UsingUnicodeExtensions" }
00018 };
Generated on Fri Nov 15 2024 22:17:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cpp/Scenario3_SingleFolder.xaml.cpp Source File

  • FilePicker
  • cpp

Scenario3_SingleFolder.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_SingleFolder.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Storage;
00020 using namespace Windows::Storage::Pickers;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario3_SingleFolder::Scenario3_SingleFolder()
00026 {
00027     InitializeComponent();
00028     rootPage = MainPage::Current;
00029 }
00030
00031 void Scenario3_SingleFolder::PickFolderButton_Click(Object^ sender, RoutedEventArgs^ e)
00032 {
00033     // Clear previous returned folder name, if it exists, between iterations of this scenario
00034     OutputTextBlock->Text = "";
00035
00036     FolderPicker^ folderPicker = ref new FolderPicker();
00037     folderPicker->SuggestedStartLocation = PickerLocationId::Desktop;
00038
00039     // Users expect to have a filtered view of their folders depending on the scenario.
00040     // For example, when choosing a documents folder, restrict the filetypes to documents for your application.
00041     folderPicker->FileTypeFilter->Append(".docx");
00042     folderPicker->FileTypeFilter->Append(".xlsx");
00043     folderPicker->FileTypeFilter->Append(".pptx");
00044
00045     create_task(folderPicker->PickSingleFolderAsync()).then([this](StorageFolder^ folder)
00046     {
00047         if (folder)
00048         {
00049             OutputTextBlock->Text = "Picked folder: " + folder->Name;
00050         }
00051         else
00052         {
00053             OutputTextBlock->Text = "Operation cancelled.";
00054         }
00055     });
00056 }
Generated on Fri Nov 15 2024 22:19:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Fx2Driver Member List

This is the complete list of members for Fx2Driver, including all inherited members.
__pad0__ | Fx2Driver |
DeviceInterfaceGuid | Fx2Driver | [static]
DeviceInterfaceGuid | Fx2Driver | [static]
DeviceType | Fx2Driver |
DigitToSevenSegment(byte value) | Fx2Driver | [static]
DigitToSevenSegment(byte value) | Fx2Driver | [inline, static]
FunctionBase | Fx2Driver | [static]
FunctionBase | Fx2Driver |
GetInterruptMessage | Fx2Driver | [static]
GetInterruptMessage | Fx2Driver | [static]
GetSevenSegmentDisplay | Fx2Driver | [static]
GetSevenSegmentDisplay | Fx2Driver | [static]
ReadSwitches | Fx2Driver | [static]
ReadSwitches | Fx2Driver | [static]
SetSevenSegmentDisplay | Fx2Driver | [static]
SetSevenSegmentDisplay | Fx2Driver | [static]
SevenSegmentToDigit(byte value) | Fx2Driver | [static]
SevenSegmentToDigit(byte value) | Fx2Driver | [inline, static]
SevenSegmentValues | Fx2Driver | [private, static]
SevenSegmentValues | Fx2Driver | [private, static]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_LaunchFile Member List

This is the complete list of members for Scenario1_LaunchFile, including all inherited members.
fileToLaunch | Scenario1_LaunchFile | [private]
GetFileToLaunch() | Scenario1_LaunchFile | [inline, private]
GetOpenWithPosition(FrameworkElement element) | Scenario1_LaunchFile | [inline, private]
LaunchFileDefault() | Scenario1_LaunchFile | [inline, private]
LaunchFileOpenWith(object sender, RoutedEventArgs e) | Scenario1_LaunchFile | [inline, private]
LaunchFileSplitScreen() | Scenario1_LaunchFile | [inline, private]
LaunchFileWithWarning() | Scenario1_LaunchFile | [inline, private]
PickAndLaunchFile() | Scenario1_LaunchFile | [inline, private]
rootPage | Scenario1_LaunchFile | [private]
Scenario1_LaunchFile() | Scenario1_LaunchFile | [inline]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Mini Member List

This is the complete list of members for Scenario1_Mini, including all inherited members.
OnNavigatedTo(NavigationEventArgs e) | Scenario1_Mini | [inline, protected]
rootPage | Scenario1_Mini | [private]
Scenario1_Mini() | Scenario1_Mini | [inline]
ShowContactCard_Click(object sender, RoutedEventArgs e) | Scenario1_Mini | [inline, private]
ShowContactCardWithOptions_Click(object sender, RoutedEventArgs e) | Scenario1_Mini | [inline, private]
ShowContactCardWithPlacement_Click(object sender, RoutedEventArgs e) | Scenario1_Mini | [inline, private]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NetworkConnectivity/cppwinrt/Scenario1_NetworkConnectivity.h Source File

  • NetworkConnectivity
  • cppwinrt

Scenario1_NetworkConnectivity.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012 #include "Scenario1_NetworkConnectivity.g.h"
00013
00014 namespace winrt::SDKTemplate::implementation
00015 {
00016     struct Scenario1_NetworkConnectivity : Scenario1_NetworkConnectivityT<Scenario1_NetworkConnectivity>
00017     {
00018         Scenario1_NetworkConnectivity();
00019         fire_and_forget QueryCurrentNetworkConnectivityButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00020     };
00021 }
00022
00023 namespace winrt::SDKTemplate::factory_implementation
00024 {
00025     struct Scenario1_NetworkConnectivity : Scenario1_NetworkConnectivityT<Scenario1_NetworkConnectivity, implementation::Scenario1_NetworkConnectivity>
00026     {
00027     };
00028 }
Generated on Fri Nov 15 2024 22:20:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PlayReady/cs/Shared/PlayReadyHelpers.cs Source File

  • PlayReady
  • cs
  • Shared

PlayReadyHelpers.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate.ViewModels;
00013 using System;
00014 using Windows.ApplicationModel.Core;
00015 using Windows.Media.Protection;
00016 using Windows.Media.Protection.PlayReady;
00017 using Windows.UI.Core;
00018
00019 namespace SDKTemplate.Shared
00020 {
00021     // This class provides helper methods for common PlayReady operations.
00022     // Both Reactive and Proactive service call helpers are defined.
00023     // Proactive helpers will configure a request and use the Reative method for the call.
00024     class PlayReadyHelpers
00025     {
00026         // This property shows if the application has been individualized.
00027         // The PlayReadyCertificateSecurityLevel will be 0 if it has not.
00028         static public bool IsIndividualized
00029         {
00030             get { return PlayReadyStatics.PlayReadyCertificateSecurityLevel != 0; }
00031         }
00032
00033         static public MediaProtectionManager InitializeProtectionManager(ServiceRequestedEventHandler serviceRequestHandler)
00034         {
00035
00036             var protectionManager = new MediaProtectionManager();
00037
00038             //A setting to tell MF that we are using PlayReady.
00039             var props = new Windows.Foundation.Collections.PropertySet();
00040             props.Add("{F4637010-03C3-42CD-B932-B48ADF3A6A54}", "Windows.Media.Protection.PlayReady.PlayReadyWinRTTrustedInput");
00041             protectionManager.Properties.Add("Windows.Media.Protection.MediaProtectionSystemIdMapping", props);
00042             protectionManager.Properties.Add("Windows.Media.Protection.MediaProtectionSystemId", "{F4637010-03C3-42CD-B932-B48ADF3A6A54}");
00043             //Maps the conatiner guid from the manifest or media segment
00044             protectionManager.Properties.Add("Windows.Media.Protection.MediaProtectionContainerGuid", "{9A04F079-9840-4286-AB92-E65BE0885F95}");
00045
00046             protectionManager.ServiceRequested += new ServiceRequestedEventHandler(serviceRequestHandler);
00047             protectionManager.ComponentLoadFailed += new ComponentLoadFailedEventHandler(ComponentLoadFailed);
00048
00049             // Windows 10 provides built in support for Dash and does not require additional configuration.
00050             // This would be be good place to configure a MediaExtensionManager to support another stream source
00051             // such as the Smooth Streaming SDK
00052
00053             return protectionManager;
00054
00055         }
00056
00057         static public PlayReadyLicenseSession createLicenseSession()
00058         {
00059             //A setting to tell MF that we are using PlayReady.
00060             var propSetMF = new Windows.Foundation.Collections.PropertySet();
00061             propSetMF["Windows.Media.Protection.MediaProtectionSystemId"] = "{F4637010-03C3-42CD-B932-B48ADF3A6A54}";
00062             var cpsystems = new Windows.Foundation.Collections.PropertySet();
00063             cpsystems["{F4637010-03C3-42CD-B932-B48ADF3A6A54}"] = "Windows.Media.Protection.PlayReady.PlayReadyWinRTTrustedInput"; //Playready TrustedInput Class Name
00064             propSetMF["Windows.Media.Protection.MediaProtectionSystemIdMapping"] = cpsystems;
00065
00066             //Create the MF media session that the license will be tied to
00067             var pmpServer = new Windows.Media.Protection.MediaProtectionPMPServer(propSetMF);
00068
00069             var propSetPMPServer = new Windows.Foundation.Collections.PropertySet();
00070             //Set the property for the LicenseSession. This tells PlayReady to tie the license to that particular media session
00071             propSetPMPServer["Windows.Media.Protection.MediaProtectionPMPServer"] = pmpServer;
00072
00073             var licenseSession = new Windows.Media.Protection.PlayReady.PlayReadyLicenseSession(propSetPMPServer);
00074             return licenseSession;
00075         }
00076
00077
00078         /// <summary>
00079         /// A ComponentLoadFailed event will occur when binary data fails to load.
00080         /// This an infrequent event that may be triggered by a pending OS update in which DRM compoments
00081         /// are being renewed and may require a restart.
00082         /// </summary>
00083         static void ComponentLoadFailed(MediaProtectionManager sender, ComponentLoadFailedEventArgs e)
00084         {
00085
00086             for (int i = 0; i < e.Information.Items.Count; i++)
00087             {
00088                 ViewModelBase.Log(e.Information.Items[i].Name + "\nReasons=0x" + e.Information.Items[i].Reasons + "\n"
00089                                                     + "Renewal Id=" + e.Information.Items[i].RenewalId);
00090             }
00091             e.Completion.Complete(false);
00092         }
00093
00094         /// <summary>
00095         /// Reactive individualization is triggered by PlayReady when the DRM is first utilized in a new app.
00096         /// If individualization was triggered as part a license request then that request will be queued until
00097         /// the indiv process completes. The serviceCompletionNotifier is utilized to notify the ProtectionManager
00098         /// that the next service request can begin.
00099         /// </summary>
00100         static public async void ReactiveIndividualization(PlayReadyIndividualizationServiceRequest indivRequest,
00101                                                                 MediaProtectionServiceCompletion serviceCompletionNotifier,
00102                                                                 Action callback = null)
00103         {
00104             Exception exception = null;
00105             try
00106             {
00107                 // The actual service call.
00108                 // The Indiv ServiceRequest call cannot be customized like most other ServiceRequests.
00109                 await indivRequest.BeginServiceRequest();
00110             }
00111             catch (Exception ex)
00112             {
00113                 exception = ex;
00114             }
00115             finally
00116             {
00117                 if (serviceCompletionNotifier != null)
00118                 {
00119                     // The Complete call will notify listeners that the service call is complete
00120                     // and queued service requests can begin.
00121                     serviceCompletionNotifier.Complete(exception == null);
00122                 }
00123                 ViewModelBase.Log("ReactiveIndividualization::Complete");
00124             }
00125
00126             // The callback is only used in the sample to show PlayReadyStatics within the UI on the
00127             // completion of the ServiceRequest.
00128             if (callback != null)
00129             {
00130                 var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
00131                 await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00132                 {
00133                     callback.Invoke();
00134                 });
00135             }
00136         }
00137
00138         /// <summary>
00139         /// Reactive license acquisition is triggered by PlayReady when the DRM does not have a license for the
00140         /// content(KeyID) as part of an active playback attempt.
00141         /// Service requests can be queued which is useful in scenarios such as root/leaf license and PlayReady Domains
00142         /// where one license depends on another. The serviceCompletionNotifier is utilized to notify the ProtectionManager
00143         /// that the next service request can begin.
00144         /// </summary>
00145         static async public void ReactiveLicenseAcquisition(IPlayReadyLicenseAcquisitionServiceRequest licenseRequest,
00146                                                                    MediaProtectionServiceCompletion serviceCompletionNotifier,
00147                                                                    Action callback = null)
00148         {
00149
00150             Exception exception = null;
00151             bool success = false;
00152             try
00153             {
00154                 await licenseRequest.BeginServiceRequest();
00155                 success = true;
00156             }
00157             catch (Exception ex)
00158             {
00159                 exception = ex;
00160             }
00161             finally
00162             {
00163                 if (serviceCompletionNotifier != null)
00164                 {
00165                     // The Complete call will notify listeners that the service call is complete
00166                     // and queued service requests can begin.
00167                     serviceCompletionNotifier.Complete(success);
00168                     serviceCompletionNotifier = null;
00169                 }
00170                 ViewModelBase.Log("ReactiveLicenseAcquisition::Complete");
00171             }
00172
00173             // optional call back to update UI.
00174             if (callback != null)
00175             {
00176                 var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
00177                 await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00178                 {
00179                     callback.Invoke();
00180                 });
00181
00182             }
00183         }
00184
00185         /// <summary>
00186         /// The individual process can kick off proactively and not need to wait for a reactionary service
00187         /// request from PlayReady. This enables the app to manage when activation occures.
00188         /// </summary>
00189         static public void ProactiveIndividualization(Action callback)
00190         {
00191             //Creating a new Indiv request and using the previous reactive method to complete the request
00192             var indivRequest = new PlayReadyIndividualizationServiceRequest();
00193             ReactiveIndividualization(indivRequest, null, callback);
00194         }
00195
00196         /// <summary>
00197         /// The application can proativly request a license by creating a license request and
00198         /// assigning a header which provides the specifics such as the KeyId of the license needed.
00199         /// </summary>
00200         static public void ProactiveLicenseAcquisition(PlayReadyContentHeader contentHeader, Action callback = null)
00201         {
00202             var laRequest = new PlayReadyLicenseAcquisitionServiceRequest();
00203             laRequest.ContentHeader = contentHeader;
00204             ReactiveLicenseAcquisition(laRequest, null, callback);
00205         }
00206
00207
00208
00209
00210     }
00211 }
00212
Generated on Fri Nov 15 2024 22:20:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/xBindSampleModel/IEmployee.cs Source File

  • XamlBind
  • cs
  • xBindSampleModel

IEmployee.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using Windows.UI.Xaml.Data;
00005 using System.ComponentModel;
00006 using System.Runtime.CompilerServices;
00007 using System.Collections.ObjectModel;
00008
00009 using Windows.Foundation.Collections;
00010 using System.Collections;
00011 using System.Collections.Specialized;
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Popups;
00014
00015 namespace xBindSampleModel
00016 {
00017     public interface IEmployee
00018     {
00019         string FirstName { get; set; }
00020         string LastName { get; set; }
00021         Manager DirectManager { get; set; }
00022         bool IsManager { get; }
00023         string Title { get; }
00024         string Name { get; }
00025         bool Visibility { get; set; }
00026         string NullStringProperty { get; set; }
00027         Windows.UI.Xaml.Media.ImageSource NullImageSource { get; set; }
00028         void Poke(object sender, RoutedEventArgs e);
00029         string FullName();
00030     }
00031 }
00032
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AuthTypeToStringConverter Member List

This is the complete list of members for AuthTypeToStringConverter, including all inherited members.
Convert(object value, Type targetType, object parameter, string language) | AuthTypeToStringConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | AuthTypeToStringConverter | [inline]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cpp/SampleConfiguration.cpp Source File

  • WebSocket
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Networking::Sockets;
00022 using namespace Windows::Security::Cryptography::Certificates;
00023 using namespace Windows::Web;
00024
00025 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00026 {
00027     { "UTF-8 text messages", "SDKTemplate.Scenario1" },
00028     { "Binary data stream", "SDKTemplate.Scenario2" },
00029     { "Client authentication", "SDKTemplate.Scenario3" },
00030     { "Partial and Complete Messages", "SDKTemplate.Scenario4" },
00031 };
00032
00033 Uri^ MainPage::TryGetUri(String^ uriString)
00034 {
00035     Windows::Foundation::Uri^ webSocketUri;
00036
00037     // Create a Uri instance and catch exceptions related to invalid input. This method returns 'true'
00038     // if the Uri instance was successfully created and 'false' otherwise.
00039     try
00040     {
00041         webSocketUri = ref new Uri(uriString);
00042     }
00043     catch (NullReferenceException^)
00044     {
00045         NotifyUser("Error: URI must not be null or empty.", NotifyType::ErrorMessage);
00046         return nullptr;
00047     }
00048     catch (InvalidArgumentException^)
00049     {
00050         NotifyUser("Error: Invalid URI", NotifyType::ErrorMessage);
00051         return nullptr;
00052     }
00053
00054     if (webSocketUri->Fragment != "")
00055     {
00056         NotifyUser("Error: URI fragments not supported in WebSocket URIs.", NotifyType::ErrorMessage);
00057         return nullptr;
00058     }
00059
00060     // Uri->SchemeName returns the canonicalized scheme name so we can use case-sensitive, ordinal string
00061     // comparison.
00062     if (webSocketUri->SchemeName != "ws" && webSocketUri->SchemeName != "wss")
00063     {
00064         NotifyUser("Error: WebSockets only support ws:// and wss:// schemes.", NotifyType::ErrorMessage);
00065         return nullptr;
00066     }
00067
00068     return webSocketUri;
00069 }
00070
00071 String^ MainPage::BuildWebSocketError(Exception^ ex)
00072 {
00073     // Normally we'd use the HResult and status to test for specific conditions we want to handle.
00074     // In this sample, we'll just output them for demonstration purposes.
00075
00076     WebErrorStatus status = WebSocketError::GetStatus(ex->HResult);
00077
00078     switch (status)
00079     {
00080     case WebErrorStatus::CannotConnect:
00081     case WebErrorStatus::NotFound:
00082     case WebErrorStatus::RequestTimeout:
00083         return "Cannot connect to the server. Please make sure " +
00084             "to run the server setup script before running the sample.";
00085
00086     case WebErrorStatus::Unknown:
00087         return "COM error: " + ex->HResult.ToString();
00088
00089     default:
00090         return "Error: " + status.ToString();
00091     }
00092 }
00093
00094 // All the certificates in the certificate chain as well as the final certificate itself
00095 // must be valid.
00096 task<bool> MainPage::AreCertificateAndCertChainValidAsync(
00097     Certificate^ serverCert,
00098     IVectorView<Windows::Security::Cryptography::Certificates::Certificate^>^ certChain)
00099 {
00100     std::vector<task<bool>> tasks(certChain->Size + 1);
00101     // Check validity of all the certificates in the certificate chain.
00102     std::transform(begin(certChain), end(certChain), begin(tasks), IsCertificateValidAsync);
00103     // Check validity of the final certificate.
00104     tasks[certChain->Size] = IsCertificateValidAsync(serverCert);
00105
00106     return when_all(begin(tasks), end(tasks)).then([](std::vector<bool> results)
00107     {
00108         // Return true if every result is true.
00109         return std::find(begin(results), end(results), false) == end(results);
00110     });
00111 }
00112
00113 // This is a placeholder call to simulate long-running async calls. Note that this code runs synchronously as part
00114 // of the SSL/TLS handshake. Avoid performing lengthy operations here - else, the remote server may terminate the
00115 // connection abruptly.
00116 task<bool> MainPage::IsCertificateValidAsync(Certificate^ serverCert)
00117 {
00118     // In this sample, we check the issuer of the certificate - this is purely for illustration
00119     // purposes and should not be considered as a recommendation for certificate validation.
00120     return task_from_result(serverCert->Issuer == "www.fabrikam.com");
00121 }
Generated on Fri Nov 15 2024 22:17:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DpiScaling/cpp/Scenario1.xaml.cpp Source File

  • DpiScaling
  • cpp

Scenario1.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario1.xaml.cpp
00013 // Implementation of the Scenario1 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario1.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace Platform;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::Graphics::Display;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Media::Imaging;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 Scenario1::Scenario1()
00031 {
00032     InitializeComponent();
00033     DisplayInformation^ displayInformation = DisplayInformation::GetForCurrentView();
00034     token = (displayInformation->DpiChanged += ref new TypedEventHandler<DisplayInformation^, Platform::Object^>(this, &Scenario1::DisplayProperties_DpiChanged));
00035 }
00036
00037 void Scenario1::ResetOutput()
00038 {
00039     DisplayInformation^ displayInformation = DisplayInformation::GetForCurrentView();
00040     String^ scaleValue = static_cast<int>(displayInformation->RawPixelsPerViewPixel * 100.0f + 0.5f).ToString();
00041     ManualLoadURL->Text = "http://www.contoso.com/imageScale" + scaleValue + ".png";
00042     ScalingText->Text = scaleValue + "%";
00043     LogicalDPIText->Text = displayInformation->LogicalDpi.ToString() + " DPI";
00044 }
00045
00046 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00047 {
00048     ResetOutput();
00049 }
00050
00051 void Scenario1::OnNavigatedFrom(NavigationEventArgs^ e)
00052 {
00053     DisplayInformation^ displayInformation = DisplayInformation::GetForCurrentView();
00054     displayInformation->DpiChanged -= token;
00055 }
00056
00057 void Scenario1::DisplayProperties_DpiChanged(DisplayInformation^ sender, Platform::Object^ args)
00058 {
00059     ResetOutput();
00060 }
Generated on Fri Nov 15 2024 22:17:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Client/RpcClientApi.h Source File

  • CustomCapability
  • Service
  • Client

RpcClientApi.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012
00013 //
00014 // Exported API's for RPC client that can be used in
00015 // Win32/UWP app. This can be also consumed in managed
00016 // code using PInvoke
00017 //
00018 extern "C" {
00019 typedef void * RPC_CLIENT_HANDLE;
00020
00021 // Opens metering RPC endpoint
00022 __declspec(dllexport)
00023 __int64 RpcClientInitialize(RPC_CLIENT_HANDLE* RpcClientHandle);
00024
00025 // Starts metering service and blocks till metering is stopped
00026 __declspec(dllexport)
00027 __int64 StartMeteringAndWaitForStop(RPC_CLIENT_HANDLE RpcClientHandle, __int64 samplePeriod);
00028
00029 // Sends stop metering to RPC Service
00030 __declspec(dllexport)
00031 __int64 StopMeteringData(RPC_CLIENT_HANDLE RpcClientHandle);
00032
00033 // Updates sample rate of metering RPC Service
00034 __declspec(dllexport)
00035 __int64 SetSampleRate(RPC_CLIENT_HANDLE RpcClientHandle, int rate);
00036
00037 // Get the most recent metering data received from the metering RPC service
00038 __declspec(dllexport)
00039 __int64 GetMeteringData(RPC_CLIENT_HANDLE RpcClientHandle, __int64* MeteringData);
00040
00041 // Retrieve the metering callback count for the current metering session
00042 __declspec(dllexport)
00043 __int64 GetCallbackCount(RPC_CLIENT_HANDLE RpcClientHandle, __int64* MeteringData);
00044
00045 // Closes metering RPC endpoint
00046 __declspec(dllexport)
00047 __int64 RpcClientClose(RPC_CLIENT_HANDLE RpcClientHandle);
00048 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ModelNormalConstantBuffer Member List

This is the complete list of members for ModelNormalConstantBuffer, including all inherited members.
colorFadeFactor | ModelNormalConstantBuffer
modelToWorld | ModelNormalConstantBuffer
normalToWorld | ModelNormalConstantBuffer
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ExtendedExecution/cs/Scenario2_SavingDataReason.xaml.cs Source File

  • ExtendedExecution
  • cs

Scenario2_SavingDataReason.xaml.cs

Go to the documentation of this file.
00001 ﻿
00002 //*********************************************************
00003 //
00004 // Copyright (c) Microsoft. All rights reserved.
00005 // This code is licensed under the MIT License (MIT).
00006 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00007 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00008 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00009 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00010 //
00011 //*********************************************************
00012
00013 using System;
00014 using System.Threading;
00015 using System.Threading.Tasks;
00016 using Windows.ApplicationModel;
00017 using Windows.ApplicationModel.ExtendedExecution;
00018 using Windows.UI.Core;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// Page containing the Extended Execution SavingData Reason scenario functions.
00027     /// </summary>
00028     public sealed partial class SavingDataReason : Page
00029     {
00030         private MainPage rootPage = MainPage.Current;
00031
00032         private CancellationTokenSource cancellationTokenSource;
00033         private SuspendingDeferral suspendDeferral;
00034
00035         public SavingDataReason()
00036         {
00037             this.InitializeComponent();
00038         }
00039
00040         protected override void OnNavigatedTo(NavigationEventArgs e)
00041         {
00042             // Add a suspension handler in order to request a SavingData Extended Execution.
00043             App.Current.Suspending += OnSuspending;
00044         }
00045
00046         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00047         {
00048             App.Current.Suspending -= OnSuspending;
00049         }
00050
00051         private async void OnSuspending(object sender, SuspendingEventArgs args)
00052         {
00053             suspendDeferral = args.SuspendingOperation.GetDeferral();
00054
00055             rootPage.NotifyUser("", NotifyType.StatusMessage);
00056
00057             using (var session = new ExtendedExecutionSession())
00058             {
00059                 session.Reason = ExtendedExecutionReason.SavingData;
00060                 session.Description = "Pretending to save data to slow storage.";
00061                 session.Revoked += ExtendedExecutionSessionRevoked;
00062
00063                 ExtendedExecutionResult result = await session.RequestExtensionAsync();
00064                 switch (result)
00065                 {
00066                     case ExtendedExecutionResult.Allowed:
00067                         // We can perform a longer save operation (e.g., upload to the cloud).
00068                         try
00069                         {
00070                             MainPage.DisplayToast("Performing a long save operation.");
00071                             cancellationTokenSource = new CancellationTokenSource();
00072                             await Task.Delay(TimeSpan.FromSeconds(10), cancellationTokenSource.Token);
00073                             MainPage.DisplayToast("Still saving.");
00074                             await Task.Delay(TimeSpan.FromSeconds(10), cancellationTokenSource.Token);
00075                             MainPage.DisplayToast("Long save complete.");
00076                         }
00077                         catch (TaskCanceledException) { }
00078                         break;
00079                     default:
00080                     case ExtendedExecutionResult.Denied:
00081                         // We must perform a fast save operation.
00082                         MainPage.DisplayToast("Performing a fast save operation.");
00083                         await Task.Delay(TimeSpan.FromSeconds(1));
00084                         MainPage.DisplayToast("Fast save complete.");
00085                         break;
00086                 }
00087
00088                 session.Revoked -= ExtendedExecutionSessionRevoked;
00089             }
00090
00091             suspendDeferral?.Complete();
00092             suspendDeferral = null;
00093         }
00094
00095         private async void ExtendedExecutionSessionRevoked(object sender, ExtendedExecutionRevokedEventArgs args)
00096         {
00097             //If session is revoked, make the OnSuspending event handler stop or the application will be terminated
00098             if (cancellationTokenSource != null){ cancellationTokenSource.Cancel(); }
00099
00100             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00101             {
00102                 switch (args.Reason)
00103                 {
00104                     case ExtendedExecutionRevokedReason.Resumed:
00105                         // A resumed app has returned to the foreground
00106                         rootPage.NotifyUser("Extended execution revoked due to returning to foreground.", NotifyType.StatusMessage);
00107                         break;
00108
00109                     case ExtendedExecutionRevokedReason.SystemPolicy:
00110                         //An app can be in the foreground or background when a revocation due to system policy occurs
00111                         MainPage.DisplayToast("Extended execution revoked due to system policy.");
00112                         rootPage.NotifyUser("Extended execution revoked due to system policy.", NotifyType.StatusMessage);
00113                         break;
00114                 }
00115
00116                 suspendDeferral?.Complete();
00117                 suspendDeferral = null;
00118             });
00119         }
00120     }
00121 }
Generated on Fri Nov 15 2024 22:19:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cpp/SampleConfiguration.cpp Source File

  • ActivitySensor
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Current activity", "SDKTemplate.Scenario1_CurrentActivity" },
00021     { "Activity history", "SDKTemplate.Scenario2_History" },
00022     { "Events", "SDKTemplate.Scenario3_ChangeEvents" },
00023     { "Background activity", "SDKTemplate.Scenario4_BackgroundActivity" }
00024 };
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: VideoPlayback/cs/Scenario1_PlayingVideos.xaml.cs Source File

  • VideoPlayback
  • cs

Scenario1_PlayingVideos.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Media.Core;
00014 using Windows.Storage;
00015 using Windows.Storage.Pickers;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// Demonstrates basic video playback using MediaElement.
00024     /// </summary>
00025     public sealed partial class Scenario1 : Page
00026     {
00027         private MainPage rootPage = MainPage.Current;
00028
00029         public Scenario1()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override void OnNavigatedFrom(NavigationEventArgs e)
00035         {
00036             MediaPlayerHelper.CleanUpMediaPlayerSource(mediaPlayerElement.MediaPlayer);
00037         }
00038
00039         /// <summary>
00040         /// Handles the pick file button click event to load a video.
00041         /// </summary>
00042         private async void pickFileButton_Click(object sender, RoutedEventArgs e)
00043         {
00044             // Clear previous returned file name, if it exists, between iterations of this scenario
00045             rootPage.NotifyUser("", NotifyType.StatusMessage);
00046
00047             // Create and open the file picker
00048             FileOpenPicker openPicker = new FileOpenPicker();
00049             openPicker.ViewMode = PickerViewMode.Thumbnail;
00050             openPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
00051             openPicker.FileTypeFilter.Add(".mp4");
00052             openPicker.FileTypeFilter.Add(".mkv");
00053             openPicker.FileTypeFilter.Add(".avi");
00054
00055             StorageFile file = await openPicker.PickSingleFileAsync();
00056             if (file != null)
00057             {
00058                 rootPage.NotifyUser("Picked video: " + file.Name, NotifyType.StatusMessage);
00059                 this.mediaPlayerElement.MediaPlayer.Source = MediaSource.CreateFromStorageFile(file);
00060                 this.mediaPlayerElement.MediaPlayer.Play();
00061             }
00062             else
00063             {
00064                 rootPage.NotifyUser("Operation cancelled.", NotifyType.ErrorMessage);
00065             }
00066         }
00067     }
00068 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlStateTriggers/cs/ItemTemplateControl.xaml.cs Source File

  • XamlStateTriggers
  • cs

ItemTemplateControl.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.IO;
00004 using System.Linq;
00005 using System.Runtime.InteropServices.WindowsRuntime;
00006 using Windows.Foundation;
00007 using Windows.Foundation.Collections;
00008 using Windows.UI.Xaml;
00009 using Windows.UI.Xaml.Controls;
00010 using Windows.UI.Xaml.Controls.Primitives;
00011 using Windows.UI.Xaml.Data;
00012 using Windows.UI.Xaml.Input;
00013 using Windows.UI.Xaml.Media;
00014 using Windows.UI.Xaml.Navigation;
00015
00016 // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
00017
00018 namespace StateTriggersSample
00019 {
00020     public sealed partial class ItemTemplateControl : UserControl
00021     {
00022         public ItemTemplateControl()
00023         {
00024             this.InitializeComponent();
00025         }
00026     }
00027 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/UnhandledExceptionPage.xaml.cs Source File

  • AdvancedCasting
  • cs

UnhandledExceptionPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.IO;
00015 using System.Linq;
00016 using System.Runtime.InteropServices.WindowsRuntime;
00017 using Windows.Foundation;
00018 using Windows.Foundation.Collections;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Controls.Primitives;
00022 using Windows.UI.Xaml.Data;
00023 using Windows.UI.Xaml.Input;
00024 using Windows.UI.Xaml.Media;
00025 using Windows.UI.Xaml.Navigation;
00026
00027 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00028
00029 namespace ScreenCasting
00030 {
00031
00032
00033
00034     /// <summary>
00035     /// An empty page that can be used on its own or navigated to within a Frame.
00036     /// </summary>
00037     public sealed partial class UnhandledExceptionPage : Page
00038     {
00039         public static void ShowUnhandledException(Exception ex)
00040         {
00041             Frame rootFrame = Window.Current.Content as Frame;
00042             if (rootFrame == null)
00043             {
00044                 rootFrame = new Frame();
00045                 Window.Current.Content = rootFrame;
00046                 Window.Current.Activate();
00047             }
00048
00049             rootFrame.Navigate(typeof(UnhandledExceptionPage), ex.ToString());
00050         }
00051
00052         protected override void OnNavigatedTo(NavigationEventArgs e)
00053         {
00054             base.OnNavigatedTo(e);
00055
00056             if(e.Parameter is string)
00057             {
00058                 this.StatusMessage = (string)e.Parameter;
00059             }
00060         }
00061         public UnhandledExceptionPage()
00062         {
00063             InitializeComponent();
00064         }
00065
00066         public string StatusMessage
00067             {
00068             get { return this.Status.Text; }
00069             set { this.Status.Text = value; }
00070             }
00071     }
00072 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: StreamSocket/cpp/Scenario2.xaml.h Source File

  • StreamSocket
  • cpp

Scenario2.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2.xaml.h
00014 // Declaration of the Scenario2 class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario2.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     namespace StreamSocketSample
00026     {
00027         /// <summary>
00028         /// An empty page that can be used on its own or navigated to within a Frame.
00029         /// </summary>
00030         [Windows::Foundation::Metadata::WebHostHidden]
00031         public ref class Scenario2 sealed
00032         {
00033         public:
00034             Scenario2();
00035
00036         protected:
00037             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038         private:
00039             MainPage^ rootPage;
00040             Windows::Networking::Connectivity::NetworkAdapter^ adapter;
00041             void ConnectSocket_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         };
00043     }
00044 }
Generated on Fri Nov 15 2024 22:18:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DSvgImage/cpp/DirectXPage.xaml.h Source File

  • D2DSvgImage
  • cpp

DirectXPage.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "DirectXPage.g.h"
00015
00016 #include "Common\DeviceResources.h"
00017 #include "D2DSvgImageRenderer.h"
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// A page that hosts the Direct2D app in a SwapChainPanel, and app UI in XAML.
00023     /// </summary>
00024     [Windows::UI::Xaml::Data::Bindable]
00025     public ref class DirectXPage sealed : Windows::UI::Xaml::Data::INotifyPropertyChanged
00026     {
00027     public:
00028         DirectXPage();
00029         virtual ~DirectXPage();
00030
00031         void SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00032         void LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00033
00034         // INotifyPropertyChanged.
00035         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
00036
00037     private:
00038         // UI element event handlers.
00039         void YellowButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void GreenButton_Click(_In_ Platform::Object^ sender, _In_ Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void PurpleButton_Click(_In_ Platform::Object^ sender, _In_ Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void TongueButton_Click(_In_ Platform::Object^ sender, _In_ Windows::UI::Xaml::RoutedEventArgs^ e);
00043         void Slider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00044
00045         // XAML low-level rendering event handler.
00046         void OnRendering(_In_ Platform::Object^ sender, _In_ Platform::Object^ args);
00047
00048         // Window event handlers.
00049         void OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^ sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args);
00050
00051         // DisplayInformation event handlers.
00052         void OnDpiChanged(_In_ Windows::Graphics::Display::DisplayInformation^ sender, _In_ Platform::Object^ args);
00053         void OnOrientationChanged(_In_ Windows::Graphics::Display::DisplayInformation^ sender, _In_ Platform::Object^ args);
00054         void OnDisplayContentsInvalidated(_In_ Windows::Graphics::Display::DisplayInformation^ sender, _In_ Platform::Object^ args);
00055
00056         // Other event handlers.
00057         void OnCompositionScaleChanged(_In_ Windows::UI::Xaml::Controls::SwapChainPanel^ sender, _In_ Object^ args);
00058         void OnSwapChainPanelSizeChanged(_In_ Platform::Object^ sender, _In_ Windows::UI::Xaml::SizeChangedEventArgs^ e);
00059
00060         // Resources used to draw the DirectX content in the XAML page.
00061         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00062         std::unique_ptr<D2DSvgImageRenderer> m_renderer;
00063         bool m_isWindowVisible;
00064
00065         // INotifyPropertyChanged.
00066         void OnPropertyChanged(Platform::String^ propertyName);
00067     };
00068 }
00069
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HotspotAuthentication/cs/HotspotAuthenticationTask/BackgroundTask.cs Source File

  • HotspotAuthentication
  • cs
  • HotspotAuthenticationTask

BackgroundTask.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Diagnostics;
00014 using System.Threading.Tasks;
00015 using Windows.ApplicationModel.Background;
00016 using Windows.Data.Xml.Dom;
00017 using Windows.Networking.NetworkOperators;
00018 using Windows.UI.Notifications;
00019
00020 // The namespace for the background tasks.
00021 namespace HotspotAuthenticationTask
00022 {
00023     // A background task always implements the IBackgroundTask interface.
00024     public sealed class AuthenticationTask : IBackgroundTask
00025     {
00026         private const string _foregroundAppId = "HotspotAuthenticationApp.App";
00027         private volatile bool _cancelRequested = false;
00028
00029         private HotspotAuthenticationEventDetails _details;
00030         private HotspotAuthenticationContext _context;
00031
00032         // The Run method is the entry point of a background task.
00033         public async void Run(IBackgroundTaskInstance taskInstance)
00034         {
00035             Debug.WriteLine("Background " + taskInstance.Task.Name + " starting...");
00036
00037             // Convert the trigger details to a HotspotAuthenticationEventDetails.
00038             _details = taskInstance.TriggerDetails as HotspotAuthenticationEventDetails;
00039
00040             // Associate a cancelation handler with the background task for handlers
00041             // that may take a considerable time to complete.
00042             taskInstance.Canceled += OnCanceled;
00043
00044             // Take a deferral so that we can call asynchronous APIs.
00045             BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
00046
00047             // The real work happens in RunAsync.
00048             await RunAsync();
00049
00050             Debug.WriteLine("Background " + taskInstance.Task.Name + " completed");
00051
00052             deferral.Complete();
00053         }
00054
00055         private async Task RunAsync()
00056         {
00057             // Do the background task activity. First, get the authentication context.
00058             Debug.WriteLine("Getting event details");
00059
00060             if (!HotspotAuthenticationContext.TryGetAuthenticationContext(_details.EventToken, out _context))
00061             {
00062                 // The event is not targetting this application. There is no further processing to do.
00063                 Debug.WriteLine("Failed to get event context");
00064                 return;
00065             }
00066
00067             byte[] ssid = _context.WirelessNetworkId;
00068             Debug.WriteLine("SSID: " + System.Text.UTF8Encoding.UTF8.GetString(ssid, 0, ssid.Length));
00069
00070             if (ConfigStore.UseNativeWISPr)
00071             {
00072                 // Following code can be used if using native WISPr implementation. Please note that
00073                 // following HotspotAuthenticationContext properties only work on windows and not on windows phone.
00074                 // On Windows Phone they return un-useful strings
00075                 // Developers are expected to implement their own WISPr implementation on Phone
00076
00077                 Debug.WriteLine("AuthenticationUrl: " + _context.AuthenticationUrl.OriginalString);
00078                 Debug.WriteLine("RedirectMessageUrl: " + _context.RedirectMessageUrl.OriginalString);
00079                 Debug.WriteLine("RedirectMessageXml: " + _context.RedirectMessageXml.GetXml());
00080
00081                 // In this sample, the AuthenticationUrl is always checked in the background task handler
00082                 // to avoid launching the foreground app in case the authentication host is not trusted.
00083                 if (ConfigStore.AuthenticationHost != _context.AuthenticationUrl.Host)
00084                 {
00085                     // Hotspot is not using the trusted authentication server.
00086                     // Abort authentication and disconnect.
00087                     Debug.WriteLine("Authentication server is untrusted");
00088                     _context.AbortAuthentication(ConfigStore.MarkAsManualConnect);
00089                     return;
00090                 }
00091             }
00092
00093             // Run the appropriate scenario selected by the foreground app.
00094             if (ConfigStore.AuthenticateThroughBackgroundTask)
00095             {
00096                 await AuthenticateInBackgroundAsync();
00097             }
00098             else
00099             {
00100                 ContinueAuthenticationInForeground();
00101             }
00102             return;
00103         }
00104
00105         private async Task AuthenticateInBackgroundAsync()
00106         {
00107             // In case this handler performs more complex tasks, it may get canceled at runtime.
00108             // Check if task was canceled by now.
00109             if (_cancelRequested)
00110             {
00111                 // In case the task handler takes too long to generate credentials and gets canceled,
00112                 // the handler should terminate the authentication by aborting it
00113                 Debug.WriteLine("Aborting authentication");
00114                 _context.AbortAuthentication(ConfigStore.MarkAsManualConnect);
00115                 return;
00116             }
00117
00118             if (ConfigStore.UseNativeWISPr)
00119             {
00120                 // The most common way of handling an authentication attempt is by providing WISPr credentials
00121                 // through the IssueCredentialsAsync API.
00122                 // If the task doesn't take any actions for authentication failures, it can use the
00123                 // IssueCredentials API to just provide credenstials.
00124                 // Alternatively, an application could run its own business logic to authentication with the
00125                 // hotspot. In this case it should call the SkipAuthentication API. Note that it should call
00126                 // SkipAuthentication after it has authenticated to allow Windows to refresh the network connectivity
00127                 // state instantly.
00128                 Debug.WriteLine("Issuing credentials");
00129                 HotspotCredentialsAuthenticationResult result = await _context.IssueCredentialsAsync(
00130                     ConfigStore.UserName, ConfigStore.Password, ConfigStore.ExtraParameters, ConfigStore.MarkAsManualConnect);
00131                 if (result.ResponseCode == HotspotAuthenticationResponseCode.LoginSucceeded)
00132                 {
00133                     Debug.WriteLine("Issuing credentials succeeded");
00134                     Uri logoffUrl = result.LogoffUrl;
00135                     if (logoffUrl != null)
00136                     {
00137                         Debug.WriteLine("The logoff URL is: " + logoffUrl.OriginalString);
00138                     }
00139                 }
00140                 else
00141                 {
00142                     Debug.WriteLine("Issuing credentials failed");
00143                 }
00144             }
00145             else
00146             {
00147                 //TODO: Please perform any authentication that is required by your particular scenario.
00148                 // Check _cancelRequested periodically in case the task is canceled.
00149
00150                 // Finally call SkipAuthentication to indicate that we are not doing native WISPr authentication
00151                 // This call also serves the purpose of indicating a successful authentication.
00152                 _context.SkipAuthentication();
00153             }
00154         }
00155
00156         private void ContinueAuthenticationInForeground()
00157         {
00158             Debug.WriteLine("Triggering foreground application");
00159             // Pass event token to application
00160             ConfigStore.AuthenticationToken = _details.EventToken;
00161
00162             // Trigger notification
00163             // Since TriggerAttentionRequired function throws NotImplementedException on phone we will be using
00164             // regular Toast Notification to notify user about the authentication, Tapping on the notification will
00165             // launch the application where user can complete the authentication
00166             if (ConfigStore.UseNativeWISPr)
00167             {
00168                 // The second parameter is used as the activation command line.
00169                 _context.TriggerAttentionRequired(_foregroundAppId, "");
00170             }
00171             else
00172             {
00173                 var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
00174                 toastXml.GetElementsByTagName("text")[0].AppendChild(toastXml.CreateTextNode("Auth by foreground"));
00175                 IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
00176                 ((XmlElement)toastNode).SetAttribute("launch", "AuthByForeground");
00177
00178                 var toast = new ToastNotification(toastXml);
00179                 toast.Tag = "AuthByForeground";
00180                 toast.Group = "HotspotAuthAPI";
00181
00182                 var notification = ToastNotificationManager.CreateToastNotifier();
00183                 notification.Show(toast);
00184             }
00185         }
00186
00187         // Handles background task cancellation.
00188         private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
00189         {
00190             // Indicate that the background task is canceled.
00191             _cancelRequested = true;
00192
00193             Debug.WriteLine("Background " + sender.Task.Name + " cancel requested...");
00194         }
00195     }
00196 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RadioManager/cppwinrt/Scenario1_Toggle.h Source File

  • RadioManager
  • cppwinrt

Scenario1_Toggle.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Toggle.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1_Toggle : Scenario1_ToggleT<Scenario1_Toggle>
00020     {
00021         Scenario1_Toggle();
00022
00023         fire_and_forget OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00024
00025     private:
00026         SDKTemplate::MainPage rootPage{ SDKTemplate::implementation::MainPage::Current() };
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario1_Toggle : Scenario1_ToggleT<Scenario1_Toggle, implementation::Scenario1_Toggle>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:21:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario05 Member List

This is the complete list of members for Scenario05, including all inherited members.
activeDevice | Scenario05 | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario05 | [inline, protected]
picker | Scenario05 | [private]
Picker_DevicePickerDismissed(DevicePicker sender, object args) | Scenario05 | [inline, private]
Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args) | Scenario05 | [inline, private]
Picker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args) | Scenario05 | [inline, private]
Player_CurrentStateChanged(object sender, RoutedEventArgs e) | Scenario05 | [inline, private]
Player_MediaFailed(object sender, ExceptionRoutedEventArgs e) | Scenario05 | [inline, private]
Player_MediaOpened(object sender, RoutedEventArgs e) | Scenario05 | [inline, private]
pvb | Scenario05 | [private]
Pvb_ProjectionStopping(object sender, EventArgs e) | Scenario05 | [inline, private]
rootPage | Scenario05 | [private]
Scenario05() | Scenario05 | [inline]
thisViewId | Scenario05 | [private]
TransportControls_CastButtonClicked(object sender, EventArgs e) | Scenario05 | [inline, private]
video | Scenario05 | [private]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCorrelation/cpp/FrameRenderer.h Source File

  • CameraStreamCorrelation
  • cpp

FrameRenderer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace SDKTemplate
00015 {
00016     // Function type used to map scanline of pixels to an alternate format.
00017     typedef std::function<void(int, byte*, byte*)> TransformScanline;
00018
00019     class FrameRenderer
00020     {
00021     public:
00022         FrameRenderer(Windows::UI::Xaml::Controls::Image^ image);
00023
00024         /// <summary>
00025         /// Buffer and render color frame.
00026         /// </summary>
00027         void ProcessColorFrame(Windows::Media::Capture::Frames::MediaFrameReference^ colorFrame);
00028
00029         /// <summary>
00030         /// Buffer and render correlated color and depth frames.
00031         /// </summary>
00032         void ProcessDepthAndColorFrames(
00033             Windows::Media::Capture::Frames::MediaFrameReference^ colorFrame,
00034             Windows::Media::Capture::Frames::MediaFrameReference^ depthFrame);
00035
00036     private: // private methods
00037         /// <summary>
00038         /// Perform mapping of depth pixels to color pixels.
00039         /// </summary>
00040         Windows::Graphics::Imaging::SoftwareBitmap^ MapDepthToColor(
00041             Windows::Media::Capture::Frames::VideoMediaFrame^ colorFrame,
00042             Windows::Media::Capture::Frames::VideoMediaFrame^ depthFrame,
00043             Windows::Media::Devices::Core::CameraIntrinsics^ colorCameraIntrinsics,
00044             Windows::Perception::Spatial::SpatialCoordinateSystem^ colorCoordinateSystem,
00045             Windows::Media::Devices::Core::DepthCorrelatedCoordinateMapper^ coordinateMapper);
00046
00047         /// <summary>
00048         /// Buffer processed bitmap and render on UI.
00049         /// </summary>
00050         void BufferBitmapForRendering(Windows::Graphics::Imaging::SoftwareBitmap^ softwareBitmap);
00051
00052         /// <summary>
00053         /// Keep presenting the m_backBuffer until there are no more.
00054         /// </summary>
00055         concurrency::task<void> FrameRenderer::DrainBackBufferAsync();
00056
00057     private: // private data
00058         Windows::UI::Xaml::Controls::Image^ m_imageElement;
00059         Windows::Graphics::Imaging::SoftwareBitmap^ m_backBuffer;
00060
00061         Platform::Array<Windows::Foundation::Point>^ m_colorSpacePoints;
00062         Platform::Array<Windows::Foundation::Numerics::float3>^ m_depthSpacePoints;
00063
00064         UINT32 m_previousBufferWidth = 0;
00065         UINT32 m_previousBufferHeight = 0;
00066
00067         bool m_taskRunning = false;
00068
00069     private: // private synchronization
00070         std::mutex m_pointBufferMutex;
00071
00072     };
00073 } // CameraStreamCorrelation
Generated on Fri Nov 15 2024 22:18:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cpp/Server/BreadTypes.h Source File

  • ProxyStubsForWinRTComponents
  • cpp
  • Server

BreadTypes.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008
00009 namespace Microsoft { namespace SDKSamples { namespace Kitchen {
00010     public enum class OvenTemperature
00011     {
00012         Low,
00013         Medium,
00014         High
00015     };
00016
00017     public value struct Dimensions
00018     {
00019         double Depth;
00020         double Height;
00021         double Width;
00022     };
00023 } /* Kitchen */ } /* SDKSamples */ } /* Microsoft */
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SerialArduino/cs/DeviceListEntry.cs Source File

  • SerialArduino
  • cs

DeviceListEntry.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017
00018 using Windows.Devices.Enumeration;
00019
00020 namespace SerialArduino
00021 {
00022     /// <summary>
00023     /// The class will only expose properties from DeviceInformation that are going to be used
00024     /// in this sample. Each instance of this class provides information about a single device.
00025     ///
00026     /// This class is used by the UI to display device specific information so that
00027     /// the user can identify which device to use.
00028     /// </summary>
00029     public class DeviceListEntry
00030     {
00031         private DeviceInformation device;
00032         private String deviceSelector;
00033
00034         public String InstanceId
00035         {
00036             get
00037             {
00038                 return device.Properties[DeviceProperties.DeviceInstanceId] as String;
00039             }
00040         }
00041
00042         public DeviceInformation DeviceInformation
00043         {
00044             get
00045             {
00046                 return device;
00047             }
00048         }
00049
00050         public String DeviceSelector
00051         {
00052             get
00053             {
00054                 return deviceSelector;
00055             }
00056         }
00057
00058         /// <summary>
00059         /// The class is mainly used as a DeviceInformation wrapper so that the UI can bind to a list of these.
00060         /// </summary>
00061         /// <param name="deviceInformation"></param>
00062         /// <param name="deviceSelector">The AQS used to find this device</param>
00063         public DeviceListEntry(Windows.Devices.Enumeration.DeviceInformation deviceInformation, String deviceSelector)
00064         {
00065             device = deviceInformation;
00066             this.deviceSelector = deviceSelector;
00067         }
00068
00069     }
00070 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/Actions/InputText/PlaceholderContent/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • Actions
  • InputText
  • PlaceholderContent

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Notifications;
00003 using Windows.UI.Popups;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00008
00009 namespace Notifications.ScenarioPages.Toasts.Actions.InputText.PlaceholderContent
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     public sealed partial class ScenarioElement : UserControl
00015     {
00016         public ScenarioElement()
00017         {
00018             this.InitializeComponent();
00019         }
00020
00021         private void UserControl_Loaded(object sender, RoutedEventArgs e)
00022         {
00023             Initialize();
00024         }
00025
00026         private void Initialize()
00027         {
00028             // Clear all existing notifications
00029             ToastNotificationManager.History.Clear();
00030
00031             // Pop notifications
00032             popToastControl.Payload =
00033                 $@"
00034                 <toast activationType='foreground' launch='args'>
00035                     <visual>
00036                         <binding template='ToastGeneric'>
00037                             <text>Input Text - Placeholder</text>
00038                             <text>Make sure ""My placeholder content"" is displayed as the placeholder content of the text box in this toast.</text>
00039                         </binding>
00040                     </visual>
00041                     <actions>
00042
00043                         <input
00044                             id = 'message'
00045                             type = 'text'
00046                             placeHolderContent = 'My placeholder content' />
00047
00048                     </actions>
00049                 </toast>";
00050         }
00051
00052         private async void Error(string message)
00053         {
00054             await new MessageDialog(message, "ERROR").ShowAsync();
00055         }
00056     }
00057 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AzureDataProvider Member List

This is the complete list of members for AzureDataProvider, including all inherited members.
GetAll(int max_results) | AzureDataProvider | [inline, virtual]
GetFromID(string id) | AzureDataProvider | [inline, virtual]
GetRandomVideo() | AzureDataProvider | [inline, virtual]
MAX_RESULTS | AzureDataProvider | [private]
s_metaDataList | AzureDataProvider | [private, static]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/AsyncCB.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

AsyncCB.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 //////////////////////////////////////////////////////////////////////////
00004 //  AsyncCallback [template]
00005 //
00006 //  Description:
00007 //  Helper class that routes IMFAsyncCallback::Invoke calls to a class
00008 //  method on the parent class.
00009 //
00010 //  Usage:
00011 //  Add this class as a member variable. In the parent class constructor,
00012 //  initialize the AsyncCallback class like this:
00013 //      m_cb(this, &CYourClass::OnInvoke)
00014 //  where
00015 //      m_cb       = AsyncCallback object
00016 //      CYourClass = parent class
00017 //      OnInvoke   = Method in the parent class to receive Invoke calls.
00018 //
00019 //  The parent's OnInvoke method (you can name it anything you like) must
00020 //  have a signature that matches the InvokeFn typedef below.
00021 //////////////////////////////////////////////////////////////////////////
00022
00023 // T: Type of the parent object
00024 template<class T>
00025 class AsyncCallback : public IMFAsyncCallback
00026 {
00027 public:
00028     typedef HRESULT (T::*InvokeFn)(IMFAsyncResult *pAsyncResult);
00029
00030     AsyncCallback(T *pParent, InvokeFn fn) : m_pParent(pParent), m_pInvokeFn(fn)
00031     {
00032     }
00033
00034     // IUnknown
00035     STDMETHODIMP_(ULONG) AddRef() {
00036         // Delegate to parent class.
00037         return m_pParent->AddRef();
00038     }
00039     STDMETHODIMP_(ULONG) Release() {
00040         // Delegate to parent class.
00041         return m_pParent->Release();
00042     }
00043     STDMETHODIMP QueryInterface(REFIID iid, void** ppv)
00044     {
00045         if (!ppv)
00046         {
00047             return E_POINTER;
00048         }
00049         if (iid == __uuidof(IUnknown))
00050         {
00051             *ppv = static_cast<IUnknown*>(static_cast<IMFAsyncCallback*>(this));
00052         }
00053         else if (iid == __uuidof(IMFAsyncCallback))
00054         {
00055             *ppv = static_cast<IMFAsyncCallback*>(this);
00056         }
00057         else
00058         {
00059             *ppv = NULL;
00060             return E_NOINTERFACE;
00061         }
00062         AddRef();
00063         return S_OK;
00064     }
00065
00066
00067     // IMFAsyncCallback methods
00068     STDMETHODIMP GetParameters(DWORD*, DWORD*)
00069     {
00070         // Implementation of this method is optional.
00071         return E_NOTIMPL;
00072     }
00073
00074     STDMETHODIMP Invoke(IMFAsyncResult* pAsyncResult)
00075     {
00076         return (m_pParent->*m_pInvokeFn)(pAsyncResult);
00077     }
00078
00079     T *m_pParent;
00080     InvokeFn m_pInvokeFn;
00081 };
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DAdvancedColorImages/cpp/D2DAdvancedColorImages/App.xaml.cpp Source File

  • D2DAdvancedColorImages
  • cpp
  • D2DAdvancedColorImages

App.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "App.xaml.h"
00014
00015 using namespace D2DAdvancedColorImages;
00016
00017 using namespace Platform;
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::ApplicationModel::Activation;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Storage;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Controls::Primitives;
00026 using namespace Windows::UI::Xaml::Data;
00027 using namespace Windows::UI::Xaml::Input;
00028 using namespace Windows::UI::Xaml::Interop;
00029 using namespace Windows::UI::Xaml::Media;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 /// <summary>
00033 /// Initializes the singleton application object.  This is the first line of authored code
00034 /// executed, and as such is the logical equivalent of main() or WinMain().
00035 /// </summary>
00036 App::App()
00037 {
00038     InitializeComponent();
00039     Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
00040     Resuming += ref new EventHandler<Object^>(this, &App::OnResuming);
00041 }
00042
00043 /// <summary>
00044 /// Invoked when the application is launched normally by the end user.  Other entry points
00045 /// will be used when the application is launched to open a specific file, to display
00046 /// search results, and so forth.
00047 /// </summary>
00048 /// <param name="e">Details about the launch request and process.</param>
00049 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
00050 {
00051     if (m_directXPage == nullptr)
00052     {
00053         m_directXPage = ref new DirectXPage();
00054     }
00055
00056     if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
00057     {
00058         m_directXPage->LoadInternalState(ApplicationData::Current->LocalSettings->Values);
00059     }
00060
00061     m_directXPage->LoadDefaultImage();
00062
00063     // Place the page in the current window and ensure that it is active.
00064     Window::Current->Content = m_directXPage;
00065     Window::Current->Activate();
00066 }
00067
00068 // Invoked when the app is launched via the file type association for which the app has registered.
00069 void App::OnFileActivated(Windows::ApplicationModel::Activation::FileActivatedEventArgs ^ e)
00070 {
00071     if (m_directXPage == nullptr)
00072     {
00073         m_directXPage = ref new DirectXPage();
00074     }
00075
00076     if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
00077     {
00078         m_directXPage->LoadInternalState(ApplicationData::Current->LocalSettings->Values);
00079     }
00080
00081     int numFiles = e->Files->Size;
00082
00083     if (numFiles == 1)
00084     {
00085         IStorageItem^ storageItem = e->Files->GetAt(0);
00086         StorageFile^ storageFile = (StorageFile^)storageItem;
00087
00088         m_directXPage->LoadImage(storageFile);
00089     }
00090     else
00091     {
00092         throw ref new Platform::FailureException(L"Activated with incorrect number of files.");
00093     }
00094
00095     // Place the page in the current window and ensure that it is active.
00096     Window::Current->Content = m_directXPage;
00097     Window::Current->Activate();
00098 }
00099
00100 /// <summary>
00101 /// Invoked when application execution is being suspended.  Application state is saved
00102 /// without knowing whether the application will be terminated or resumed with the contents
00103 /// of memory still intact.
00104 /// </summary>
00105 /// <param name="sender">The source of the suspend request.</param>
00106 /// <param name="e">Details about the suspend request.</param>
00107 void App::OnSuspending(Object^, SuspendingEventArgs^)
00108 {
00109     m_directXPage->SaveInternalState(ApplicationData::Current->LocalSettings->Values);
00110 }
00111
00112 /// <summary>
00113 /// Invoked when application execution is being resumed.
00114 /// </summary>
00115 /// <param name="sender">The source of the resume request.</param>
00116 /// <param name="args">Details about the resume request.</param>
00117 void App::OnResuming(Object^, Object^)
00118 {
00119     m_directXPage->LoadInternalState(ApplicationData::Current->LocalSettings->Values);
00120 }
Generated on Fri Nov 15 2024 22:16:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ItemTemplateControl Member List

This is the complete list of members for ItemTemplateControl, including all inherited members.
ItemTemplateControl() ItemTemplateControl [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaTranscoding/cs/Scenario1_Default.xaml.cs Source File

  • MediaTranscoding
  • cs

Scenario1_Default.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading;
00014 using System.Threading.Tasks;
00015 using Windows.Media.MediaProperties;
00016 using Windows.Media.Transcoding;
00017 using Windows.Storage;
00018 using Windows.Storage.Pickers;
00019 using Windows.Storage.Streams;
00020 using Windows.UI.Core;
00021 using Windows.UI.Xaml;
00022 using Windows.UI.Xaml.Controls;
00023 using Windows.UI.Xaml.Media;
00024 using Windows.UI.Xaml.Navigation;
00025
00026 namespace SDKTemplate
00027 {
00028     public sealed partial class Scenario1_Default : Page
00029     {
00030         MainPage rootPage = MainPage.Current;
00031
00032         CoreDispatcher _dispatcher = Window.Current.Dispatcher;
00033         CancellationTokenSource _cts;
00034         string _OutputFileName = "TranscodeSampleOutput";
00035         MediaEncodingProfile _Profile;
00036         StorageFile _InputFile = null;
00037         StorageFile _OutputFile = null;
00038         MediaTranscoder _Transcoder = new MediaTranscoder();
00039         string _OutputType = "MP4";
00040         string _OutputFileExtension = ".mp4";
00041
00042         public Scenario1_Default()
00043         {
00044             this.InitializeComponent();
00045             _cts = new CancellationTokenSource();
00046
00047             // Hook up UI
00048             PickFileButton.Click += new RoutedEventHandler(PickFile);
00049             SetOutputButton.Click += new RoutedEventHandler(PickOutput);
00050             TargetFormat.SelectionChanged += new SelectionChangedEventHandler(OnTargetFormatChanged);
00051             Transcode.Click += new RoutedEventHandler(TranscodePreset);
00052             Cancel.Click += new RoutedEventHandler(TranscodeCancel);
00053
00054             // Media Controls
00055             InputPlayButton.Click += new RoutedEventHandler(InputPlayButton_Click);
00056             InputPauseButton.Click += new RoutedEventHandler(InputPauseButton_Click);
00057             InputStopButton.Click += new RoutedEventHandler(InputStopButton_Click);
00058             OutputPlayButton.Click += new RoutedEventHandler(OutputPlayButton_Click);
00059             OutputPauseButton.Click += new RoutedEventHandler(OutputPauseButton_Click);
00060             OutputStopButton.Click += new RoutedEventHandler(OutputStopButton_Click);
00061
00062             // File is not selected, disable all buttons but PickFileButton
00063             DisableButtons();
00064             SetPickFileButton(true);
00065             SetOutputFileButton(true);
00066             SetCancelButton(false);
00067         }
00068
00069         public void Dispose()
00070         {
00071             _cts.Dispose();
00072         }
00073
00074         /// <summary>
00075         /// Invoked when this page is about to be displayed in a Frame.
00076         /// </summary>
00077         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00078         /// property is typically used to configure the page.</param>
00079         protected override void OnNavigatedTo(NavigationEventArgs e)
00080         {
00081         }
00082
00083         async void TranscodePreset(Object sender, RoutedEventArgs e)
00084         {
00085             StopPlayers();
00086             DisableButtons();
00087             GetPresetProfile(ProfileSelect);
00088
00089             // Clear messages
00090             StatusMessage.Text = "";
00091
00092             try
00093             {
00094                 if ((_InputFile != null) && (_OutputFile != null))
00095                 {
00096                     var preparedTranscodeResult = await _Transcoder.PrepareFileTranscodeAsync(_InputFile, _OutputFile, _Profile);
00097
00098                     if (EnableMrfCrf444.IsChecked.HasValue && (bool)EnableMrfCrf444.IsChecked)
00099                     {
00100                         _Transcoder.VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.MrfCrf444;
00101                     }
00102                     else
00103                     {
00104                         _Transcoder.VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.Default;
00105                     }
00106
00107                     if (preparedTranscodeResult.CanTranscode)
00108                     {
00109                         SetCancelButton(true);
00110                         var progress = new Progress<double>(TranscodeProgress);
00111                         await preparedTranscodeResult.TranscodeAsync().AsTask(_cts.Token, progress);
00112                         TranscodeComplete();
00113                     }
00114                     else
00115                     {
00116                         TranscodeFailure(preparedTranscodeResult.FailureReason);
00117                     }
00118                 }
00119             }
00120             catch (TaskCanceledException)
00121             {
00122                 OutputText("");
00123                 TranscodeError("Transcode Canceled");
00124             }
00125             catch (Exception exception)
00126             {
00127                 TranscodeError(exception.Message);
00128             }
00129         }
00130
00131         void GetPresetProfile(ComboBox combobox)
00132         {
00133             _Profile = null;
00134             VideoEncodingQuality videoEncodingProfile = VideoEncodingQuality.Wvga;
00135             switch (combobox.SelectedIndex)
00136             {
00137                 case 0:
00138                     videoEncodingProfile = VideoEncodingQuality.HD1080p;
00139                     break;
00140                 case 1:
00141                     videoEncodingProfile = VideoEncodingQuality.HD720p;
00142                     break;
00143                 case 2:
00144                     videoEncodingProfile = VideoEncodingQuality.Wvga;
00145                     break;
00146                 case 3:
00147                     videoEncodingProfile = VideoEncodingQuality.Ntsc;
00148                     break;
00149                 case 4:
00150                     videoEncodingProfile = VideoEncodingQuality.Pal;
00151                     break;
00152                 case 5:
00153                     videoEncodingProfile = VideoEncodingQuality.Vga;
00154                     break;
00155                 case 6:
00156                     videoEncodingProfile = VideoEncodingQuality.Qvga;
00157                     break;
00158             }
00159
00160             switch (_OutputType)
00161             {
00162                 case "AVI":
00163                     _Profile = MediaEncodingProfile.CreateAvi(videoEncodingProfile);
00164                     break;
00165                 case "WMV":
00166                     _Profile = MediaEncodingProfile.CreateWmv(videoEncodingProfile);
00167                     break;
00168                 default:
00169                     _Profile = MediaEncodingProfile.CreateMp4(videoEncodingProfile);
00170                     break;
00171             }
00172
00173             /*
00174             For transcoding to audio profiles, create the encoding profile using one of these APIs:
00175                 MediaEncodingProfile.CreateMp3(audioEncodingProfile)
00176                 MediaEncodingProfile.CreateM4a(audioEncodingProfile)
00177                 MediaEncodingProfile.CreateWma(audioEncodingProfile)
00178                 MediaEncodingProfile.CreateWav(audioEncodingProfile)
00179
00180             where audioEncodingProfile is one of these presets:
00181                 AudioEncodingQuality.High
00182                 AudioEncodingQuality.Medium
00183                 AudioEncodingQuality.Low
00184             */
00185         }
00186
00187         void TranscodeProgress(double percent)
00188         {
00189             OutputText("Progress:  " + percent.ToString().Split('.')[0] + "%");
00190         }
00191
00192         async void TranscodeComplete()
00193         {
00194             OutputText("Transcode completed.");
00195             OutputPathText("Output (" + _OutputFile.Path + ")");
00196             IRandomAccessStream stream = await _OutputFile.OpenAsync(FileAccessMode.Read);
00197             await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00198             {
00199                 OutputVideo.SetSource(stream, _OutputFile.ContentType);
00200             });
00201
00202             EnableButtons();
00203             SetCancelButton(false);
00204         }
00205
00206         async void TranscodeCancel(object sender, RoutedEventArgs e)
00207         {
00208             try
00209             {
00210                 _cts.Cancel();
00211                 _cts.Dispose();
00212                 _cts = new CancellationTokenSource();
00213
00214                 if (_OutputFile != null)
00215                 {
00216                     await _OutputFile.DeleteAsync();
00217                 }
00218             }
00219             catch (Exception exception)
00220             {
00221                 TranscodeError(exception.Message);
00222             }
00223         }
00224
00225         async void TranscodeFailure(TranscodeFailureReason reason)
00226         {
00227             try
00228             {
00229                 if (_OutputFile != null)
00230                 {
00231                     await _OutputFile.DeleteAsync();
00232                 }
00233             }
00234             catch (Exception exception)
00235             {
00236                 TranscodeError(exception.Message);
00237             }
00238
00239             switch (reason)
00240             {
00241                 case TranscodeFailureReason.CodecNotFound:
00242                     TranscodeError("Codec not found.");
00243                     break;
00244                 case TranscodeFailureReason.InvalidProfile:
00245                     TranscodeError("Invalid profile.");
00246                     break;
00247                 default:
00248                     TranscodeError("Unknown failure.");
00249                     break;
00250             }
00251         }
00252
00253         async void PickFile(object sender, RoutedEventArgs e)
00254         {
00255             FileOpenPicker picker = new FileOpenPicker();
00256             picker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
00257             picker.FileTypeFilter.Add(".wmv");
00258             picker.FileTypeFilter.Add(".mp4");
00259
00260             StorageFile file = await picker.PickSingleFileAsync();
00261             if (file != null)
00262             {
00263                 IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
00264
00265                 _InputFile = file;
00266                 InputVideo.SetSource(stream, file.ContentType);
00267                 InputVideo.Play();
00268
00269                 // Enable buttons
00270                 EnableButtons();
00271             }
00272         }
00273
00274         async void PickOutput(object sender, RoutedEventArgs e)
00275         {
00276             FileSavePicker picker = new FileSavePicker();
00277             picker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
00278             picker.SuggestedFileName = _OutputFileName;
00279             picker.FileTypeChoices.Add(_OutputType, new System.Collections.Generic.List<string>() { _OutputFileExtension });
00280
00281             _OutputFile = await picker.PickSaveFileAsync();
00282
00283             if (_OutputFile != null)
00284             {
00285                 SetTranscodeButton(true);
00286             }
00287         }
00288
00289         void OnTargetFormatChanged(object sender, SelectionChangedEventArgs e)
00290         {
00291             switch (TargetFormat.SelectedIndex)
00292             {
00293                 case 1:
00294                     _OutputType = "WMV";
00295                     _OutputFileExtension = ".wmv";
00296                     EnableNonSquarePARProfiles();
00297                     break;
00298                 case 2:
00299                     _OutputType = "AVI";
00300                     _OutputFileExtension = ".avi";
00301
00302                     // Disable NTSC and PAL profiles as non-square pixel aspect ratios are not supported by AVI
00303                     DisableNonSquarePARProfiles();
00304                     break;
00305                 default:
00306                     _OutputType = "MP4";
00307                     _OutputFileExtension = ".mp4";
00308                     EnableNonSquarePARProfiles();
00309                     break;
00310             }
00311         }
00312
00313         void InputPlayButton_Click(Object sender, RoutedEventArgs e)
00314         {
00315             if (InputVideo.DefaultPlaybackRate == 0)
00316             {
00317                 InputVideo.DefaultPlaybackRate = 1.0;
00318                 InputVideo.PlaybackRate = 1.0;
00319             }
00320
00321             InputVideo.Play();
00322         }
00323
00324         void InputStopButton_Click(Object sender, RoutedEventArgs e)
00325         {
00326             InputVideo.Stop();
00327         }
00328
00329         void InputPauseButton_Click(Object sender, RoutedEventArgs e)
00330         {
00331             InputVideo.Pause();
00332         }
00333
00334         void OutputPlayButton_Click(Object sender, RoutedEventArgs e)
00335         {
00336             if (OutputVideo.DefaultPlaybackRate == 0)
00337             {
00338                 OutputVideo.DefaultPlaybackRate = 1.0;
00339                 OutputVideo.PlaybackRate = 1.0;
00340             }
00341
00342             OutputVideo.Play();
00343         }
00344
00345         void OutputStopButton_Click(Object sender, RoutedEventArgs e)
00346         {
00347             OutputVideo.Stop();
00348         }
00349
00350         void OutputPauseButton_Click(Object sender, RoutedEventArgs e)
00351         {
00352             OutputVideo.Pause();
00353         }
00354
00355         async void SetPickFileButton(bool isEnabled)
00356         {
00357             await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00358             {
00359                 PickFileButton.IsEnabled = isEnabled;
00360             });
00361         }
00362
00363         async void SetOutputFileButton(bool isEnabled)
00364         {
00365             await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00366             {
00367                 SetOutputButton.IsEnabled = isEnabled;
00368             });
00369         }
00370
00371         async void SetTranscodeButton(bool isEnabled)
00372         {
00373             await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00374             {
00375                 Transcode.IsEnabled = isEnabled;
00376             });
00377         }
00378
00379         async void SetCancelButton(bool isEnabled)
00380         {
00381             await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00382             {
00383                 Cancel.IsEnabled = isEnabled;
00384             });
00385         }
00386
00387         async void EnableButtons()
00388         {
00389             await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00390             {
00391                 PickFileButton.IsEnabled = true;
00392                 SetOutputButton.IsEnabled = true;
00393                 TargetFormat.IsEnabled = true;
00394                 ProfileSelect.IsEnabled = true;
00395                 EnableMrfCrf444.IsEnabled = true;
00396
00397                 // The transcode button's initial state should be disabled until an output
00398                 // file has been set.
00399                 Transcode.IsEnabled = false;
00400             });
00401         }
00402
00403         async void DisableButtons()
00404         {
00405             await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00406             {
00407                 ProfileSelect.IsEnabled = false;
00408                 Transcode.IsEnabled = false;
00409                 PickFileButton.IsEnabled = false;
00410                 SetOutputButton.IsEnabled = false;
00411                 TargetFormat.IsEnabled = false;
00412                 EnableMrfCrf444.IsEnabled = false;
00413             });
00414         }
00415
00416         void EnableNonSquarePARProfiles()
00417         {
00418             ComboBoxItem_NTSC.IsEnabled = true;
00419             ComboBoxItem_PAL.IsEnabled = true;
00420         }
00421
00422         void DisableNonSquarePARProfiles()
00423         {
00424             ComboBoxItem_NTSC.IsEnabled = false;
00425             ComboBoxItem_PAL.IsEnabled = false;
00426
00427             // Ensure a valid profile is set
00428             if ((ProfileSelect.SelectedIndex == 3) || (ProfileSelect.SelectedIndex == 4))
00429             {
00430                 ProfileSelect.SelectedIndex = 2;
00431             }
00432         }
00433
00434         async void StopPlayers()
00435         {
00436             await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00437             {
00438                 if (InputVideo.CurrentState != MediaElementState.Paused)
00439                 {
00440                     InputVideo.Pause();
00441                 }
00442                 if (OutputVideo.CurrentState != MediaElementState.Paused)
00443                 {
00444                     OutputVideo.Pause();
00445                 }
00446             });
00447         }
00448
00449         async void PlayFile(StorageFile MediaFile)
00450         {
00451             await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
00452             {
00453                 try
00454                 {
00455                     IRandomAccessStream stream = await MediaFile.OpenAsync(FileAccessMode.Read);
00456                     OutputVideo.SetSource(stream, MediaFile.ContentType);
00457                     OutputVideo.Play();
00458                 }
00459                 catch (Exception exception)
00460                 {
00461                     TranscodeError(exception.Message);
00462                 }
00463             });
00464         }
00465
00466         async void TranscodeError(string error)
00467         {
00468             await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00469             {
00470                 StatusMessage.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
00471                 StatusMessage.Text = error;
00472             });
00473
00474             EnableButtons();
00475             SetCancelButton(false);
00476         }
00477
00478         async void OutputText(string text)
00479         {
00480             await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00481             {
00482                 OutputMsg.Foreground = new SolidColorBrush(Windows.UI.Colors.Green);
00483                 OutputMsg.Text = text;
00484             });
00485         }
00486
00487         async void OutputPathText(string text)
00488         {
00489             await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00490             {
00491                 OutputPath.Text = text;
00492             });
00493         }
00494     }
00495 }
Generated on Fri Nov 15 2024 22:20:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/LiveTiles/AdaptiveTemplates/Images/Source/FromAppData/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • LiveTiles
  • AdaptiveTemplates
  • Images
  • Source
  • FromAppData

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Notifications.Helpers;
00002 using System;
00003 using Windows.Data.Xml.Dom;
00004 using Windows.Storage;
00005 using Windows.Storage.Pickers;
00006 using Windows.UI.Notifications;
00007 using Windows.UI.StartScreen;
00008 using Windows.UI.Xaml;
00009 using Windows.UI.Xaml.Controls;
00010 using Windows.UI.Xaml.Media.Imaging;
00011
00012 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00013
00014 namespace Notifications.ScenarioPages.LiveTiles.AdaptiveTemplates.Images.Source.FromAppData
00015 {
00016     /// <summary>
00017     /// An empty page that can be used on its own or navigated to within a Frame.
00018     /// </summary>
00019     public sealed partial class ScenarioElement : UserControl
00020     {
00021         public ScenarioElement()
00022         {
00023             this.InitializeComponent();
00024         }
00025
00026         private Uri _imagePath;
00027
00028         private async void ButtonPickImage_Click(object sender, RoutedEventArgs e)
00029         {
00030             FileOpenPicker picker = new FileOpenPicker();
00031             picker.ViewMode = PickerViewMode.Thumbnail;
00032             picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
00033             picker.CommitButtonText = "Open Image";
00034             picker.FileTypeFilter.Add(".jpg");
00035             picker.FileTypeFilter.Add(".jpeg");
00036             picker.FileTypeFilter.Add(".png");
00037
00038             StorageFile file = await picker.PickSingleFileAsync();
00039             if (file != null)
00040             {
00041                 StorageFolder logosFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("TileNotifications", CreationCollisionOption.OpenIfExists);
00042
00043                 // Copy the file to local app data
00044                 StorageFile localFile = await file.CopyAsync(logosFolder, file.Name, NameCollisionOption.GenerateUniqueName);
00045
00046                 _imagePath = new Uri("ms-appdata:///Local/TileNotifications/" + localFile.Name);
00047
00048                 ButtonPinTile.IsEnabled = true;
00049                 ImageLogoPreview.Source = new BitmapImage(_imagePath);
00050             }
00051         }
00052
00053         private async void ButtonPinTile_Click(object sender, RoutedEventArgs e)
00054         {
00055             base.IsEnabled = false;
00056
00057             string ImageUrl = _imagePath.ToString();
00058
00059             SecondaryTile tile = TilesHelper.GenerateSecondaryTile("App Package Image");
00060             await tile.RequestCreateAsync();
00061
00062             string tileXmlString =
00063                 "<tile>"
00064                 + "<visual>"
00065                 + "<binding template='TileSmall'>"
00066                 + "<image src='" + ImageUrl + "' alt='image'/>"
00067                 + "</binding>"
00068                 + "<binding template='TileMedium'>"
00069                 + "<image src='" + ImageUrl + "' alt='image'/>"
00070                 + "</binding>"
00071                 + "<binding template='TileWide'>"
00072                 + "<image src='" + ImageUrl + "' alt='image'/>"
00073                 + "</binding>"
00074                 + "<binding template='TileLarge'>"
00075                 + "<image src='" + ImageUrl + "' alt='image'/>"
00076                 + "</binding>"
00077                 + "</visual>"
00078                 + "</tile>";
00079
00080             XmlDocument xmlDoc = new XmlDocument();
00081             xmlDoc.LoadXml(tileXmlString);
00082             TileNotification notifyTile = new TileNotification(xmlDoc);
00083             TileUpdateManager.CreateTileUpdaterForSecondaryTile(tile.TileId).Update(notifyTile);
00084
00085             base.IsEnabled = true;
00086         }
00087     }
00088 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

unique_cotaskmem_ptr< T > Member List

This is the complete list of members for unique_cotaskmem_ptr< T >, including all inherited members.
get() | unique_cotaskmem_ptr< T > | [inline]
m_p | unique_cotaskmem_ptr< T > |
operator->() | unique_cotaskmem_ptr< T > | [inline]
operator=(unique_cotaskmem_ptr const &other) | unique_cotaskmem_ptr< T > | [inline]
put() | unique_cotaskmem_ptr< T > | [inline]
unique_cotaskmem_ptr(T *p=nullptr) | unique_cotaskmem_ptr< T > | [inline]
unique_cotaskmem_ptr(unique_cotaskmem_ptr const &) | unique_cotaskmem_ptr< T > |
unique_cotaskmem_ptr(unique_cotaskmem_ptr &&other) | unique_cotaskmem_ptr< T > | [inline]
~unique_cotaskmem_ptr() | unique_cotaskmem_ptr< T > | [inline]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cpp/Scenario7_CustomContent.xaml.cpp Source File

  • XamlCommanding
  • cpp

Scenario7_CustomContent.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // Scenario7_CustomContent.xaml.cpp
00003 // Implementation of the Scenario7_CustomContent class
00004 //
00005
00006 #include "pch.h"
00007 #include "Scenario7_CustomContent.xaml.h"
00008
00009 using namespace SDKTemplate;
00010
00011 using namespace Platform;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::UI::Xaml;
00015 using namespace Windows::UI::Xaml::Controls;
00016 using namespace Windows::UI::Xaml::Controls::Primitives;
00017 using namespace Windows::UI::Xaml::Data;
00018 using namespace Windows::UI::Xaml::Input;
00019 using namespace Windows::UI::Xaml::Media;
00020 using namespace Windows::UI::Xaml::Navigation;
00021
00022 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00023
00024 Scenario7_CustomContent::Scenario7_CustomContent()
00025 {
00026     InitializeComponent();
00027 }
00028
00029
00030 void Scenario7_CustomContent::CommandBar_Opening(Platform::Object^ sender, Platform::Object^ e)
00031 {
00032     appbarbutton->IsCompact = !appbarbutton->IsCompact;
00033 }
00034
00035
00036 void Scenario7_CustomContent::CommandBar_Closed(Platform::Object^ sender, Platform::Object^ e)
00037 {
00038     appbarbutton->IsCompact = !appbarbutton->IsCompact;
00039 }
Generated on Fri Nov 15 2024 22:22:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/SampleConfiguration.h Source File

  • FileAccess
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     struct SampleState
00018     {
00019         static hstring const& FileName() { return fileName; }
00020
00021         static Windows::Storage::StorageFile const& SampleFile() { return sampleFile; }
00022         static void SampleFile(Windows::Storage::StorageFile value) { sampleFile = std::move(value); }
00023
00024         static fire_and_forget ValidateFile();
00025         static void NotifyUserFileNotExist();
00026         static Windows::Storage::Streams::IBuffer GetBufferFromString(hstring const& string);
00027         static hstring GetStringFromBuffer(Windows::Storage::Streams::IBuffer const& buffer);
00028
00029         static hstring const& MruToken() { return mruToken; }
00030         static void MruToken(hstring value) { mruToken = std::move(value); }
00031
00032         static hstring const& FalToken() { return falToken; }
00033         static void FalToken(hstring value) { falToken = std::move(value); }
00034
00035     private:
00036         static hstring fileName;
00037         static Windows::Storage::StorageFile sampleFile;
00038         static hstring mruToken;
00039         static hstring falToken;
00040     };
00041 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cs/Scenario7_PinFromAppbar.xaml.cs Source File

  • SecondaryTiles
  • cs

Scenario7_PinFromAppbar.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using Windows.UI.Core;
00013 using Windows.UI.StartScreen;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class Scenario7_PinFromAppbar : Page
00021     {
00022         // Don't use NotifyUser on this page because it conflicts with the AppBar.
00023
00024         public Scenario7_PinFromAppbar()
00025         {
00026             this.InitializeComponent();
00027         }
00028
00029         protected override void OnNavigatedTo(NavigationEventArgs e)
00030         {
00031             // The appbar is open by default.
00032             Message.Text = "Tap or click the Pin button to pin a tile.";
00033             UpdateAppBarButton();
00034
00035             Window.Current.Activated += Window_Activated;
00036         }
00037
00038         protected override void OnNavigatedFrom(NavigationEventArgs e)
00039         {
00040             Window.Current.Activated -= Window_Activated;
00041         }
00042
00043         void Window_Activated(object sender, WindowActivatedEventArgs e)
00044         {
00045             // When the window regains activation, refresh the pin/unpin button.
00046             UpdateAppBarButton();
00047         }
00048
00049         // This updates the Pin/Unpin button in the app bar based on whether the
00050         // secondary tile is already pinned.
00051         private void UpdateAppBarButton()
00052         {
00053             if (SecondaryTile.Exists(MainPage.appbarTileId))
00054             {
00055                 this.PinUnPinCommandButton.Label = "Unpin";
00056                 this.PinUnPinCommandButton.Icon = new SymbolIcon(Symbol.UnPin);
00057             }
00058             else
00059             {
00060                 this.PinUnPinCommandButton.Label = "Pin";
00061                 this.PinUnPinCommandButton.Icon = new SymbolIcon(Symbol.Pin);
00062             }
00063
00064             this.PinUnPinCommandButton.UpdateLayout();
00065         }
00066
00067         async void PinToAppBar_Click(object sender, RoutedEventArgs e)
00068         {
00069             this.SecondaryTileCommandBar.IsSticky = true;
00070
00071             // Let us first verify if we need to pin or unpin
00072             if (SecondaryTile.Exists(MainPage.appbarTileId))
00073             {
00074                 // First prepare the tile to be unpinned
00075                 SecondaryTile secondaryTile = new SecondaryTile(MainPage.appbarTileId);
00076
00077                 // Now make the delete request.
00078                 bool isUnpinned = await secondaryTile.RequestDeleteForSelectionAsync(MainPage.GetElementRect((FrameworkElement)sender), Windows.UI.Popups.Placement.Above);
00079                 if (isUnpinned)
00080                 {
00081                     Message.Text = MainPage.appbarTileId + " was unpinned.";
00082                 }
00083                 else
00084                 {
00085                     Message.Text = MainPage.appbarTileId + " was not unpinned.";
00086                 }
00087
00088                 UpdateAppBarButton();
00089             }
00090             else
00091             {
00092                 // Prepare package images for the medium tile size in our tile to be pinned
00093                 Uri square150x150Logo = new Uri("ms-appx:///Assets/square150x150Tile-sdk.png");
00094
00095                 // During creation of secondary tile, an application may set additional arguments on the tile that will be passed in during activation,
00096                 // so that the app knows which tile the user is launching. In this sample, we'll pass in the date and time the secondary tile was pinned.
00097                 string tileActivationArguments = MainPage.appbarTileId + " WasPinnedAt=" + DateTime.Now.ToLocalTime().ToString();
00098
00099                 // Create a Secondary tile with all the required arguments.
00100                 // Note the last argument specifies what size the Secondary tile should show up as by default in the Pin to start fly out.
00101                 // It can be set to TileSize.Square150x150, TileSize.Wide310x150, or TileSize.Default.
00102                 // If set to TileSize.Wide310x150, then the asset for the wide size must be supplied as well.
00103                 // TileSize.Default will default to the wide size if a wide size is provided, and to the medium size otherwise.
00104                 SecondaryTile secondaryTile = new SecondaryTile(MainPage.appbarTileId,
00105                                                                 "Secondary tile pinned via AppBar",
00106                                                                 tileActivationArguments,
00107                                                                 square150x150Logo,
00108                                                                 TileSize.Square150x150);
00109
00110                 // Whether or not the app name should be displayed on the tile can be controlled for each tile size.  The default is false.
00111                 secondaryTile.VisualElements.ShowNameOnSquare150x150Logo = true;
00112
00113                 // Specify a foreground text value.
00114                 // The tile background color is inherited from the parent unless a separate value is specified.
00115                 secondaryTile.VisualElements.ForegroundText = ForegroundText.Dark;
00116
00117                 // OK, the tile is created and we can now attempt to pin the tile.
00118                 // Note that the status message is updated when the async operation to pin the tile completes.
00119                 bool isPinned = await secondaryTile.RequestCreateForSelectionAsync(MainPage.GetElementRect(sender), Windows.UI.Popups.Placement.Above);
00120                 if (isPinned)
00121                 {
00122                     Message.Text = MainPage.appbarTileId + " was successfully pinned.";
00123                 }
00124                 else
00125                 {
00126                     Message.Text = MainPage.appbarTileId + " was not pinned.";
00127                 }
00128
00129                 UpdateAppBarButton();
00130             }
00131
00132             this.BottomAppBar.IsSticky = false;
00133         }
00134
00135         void BottomAppBar_Opened(object sender, object e)
00136         {
00137             UpdateAppBarButton();
00138         }
00139     }
00140 }
Generated on Fri Nov 15 2024 22:21:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/Tasks/pch.cpp Source File

  • BackgroundTask
  • cpp
  • Tasks

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/AppView.h Source File

  • HolographicTagAlong
  • cpp

AppView.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015 #include "HolographicTagAlongSampleMain.h"
00016
00017 namespace HolographicTagAlongSample
00018 {
00019     // IFrameworkView class. Connects the app with the Windows shell and handles application lifecycle events.
00020     ref class AppView sealed : public Windows::ApplicationModel::Core::IFrameworkView
00021     {
00022     public:
00023         AppView();
00024
00025         // IFrameworkView methods.
00026         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00027         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00028         virtual void Load(Platform::String^ entryPoint);
00029         virtual void Run();
00030         virtual void Uninitialize();
00031
00032     protected:
00033         // Application lifecycle event handlers.
00034         void OnViewActivated(Windows::ApplicationModel::Core::CoreApplicationView^ sender, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00035         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00036         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00037
00038         // Window event handlers.
00039         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00040         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00041
00042         // CoreWindow input event handlers.
00043         void OnKeyPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args);
00044
00045     private:
00046         std::unique_ptr<HolographicTagAlongSampleMain> m_main;
00047
00048         std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00049         bool                                                m_windowClosed  = false;
00050         bool                                                m_windowVisible = true;
00051
00052         // The holographic space the app will use for rendering.
00053         Windows::Graphics::Holographic::HolographicSpace^   m_holographicSpace = nullptr;
00054     };
00055
00056     // The entry point for the app.
00057     ref class AppViewSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00058     {
00059     public:
00060         virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00061     };
00062 }
00063
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ArticlePage Member List

This is the complete list of members for ArticlePage, including all inherited members.
_loadTimer | ArticlePage | [private]
_uiSettings | ArticlePage | [private]
Article | ArticlePage |
ArticlePage() | ArticlePage | [inline]
ArticlePage_BackRequested(object sender, BackRequestedEventArgs e) | ArticlePage | [inline, private]
ArticleProperty | ArticlePage | [static]
BackButton_Click(object sender, RoutedEventArgs e) | ArticlePage | [inline, private]
LoadTimer_Tick(object sender, object e) | ArticlePage | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | ArticlePage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | ArticlePage | [inline, protected]
s_articleProperty | ArticlePage | [private, static]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/GroupInfoList.cpp Source File

  • XamlListView
  • cppwinrt

GroupInfoList.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "GroupInfoList.h"
00014 #include "GroupInfoList.g.cpp"
Generated on Fri Nov 15 2024 22:22:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SmartCardReaderUtils Member List

This is the complete list of members for SmartCardReaderUtils, including all inherited members.
GetFirstSmartCardReaderInfo(SmartCardReaderKind readerKind=SmartCardReaderKind.Any) SmartCardReaderUtils [inline, static]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ConnectedDevice Member List

This is the complete list of members for ConnectedDevice, including all inherited members.
ConnectedDevice(string displayName, WiFiDirectDevice wfdDevice, SocketReaderWriter socketRW) | ConnectedDevice | [inline]
DisplayName | ConnectedDevice |
Dispose() | ConnectedDevice | [inline]
SocketRW | ConnectedDevice |
ToString() | ConnectedDevice |
WfdDevice | ConnectedDevice |
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialSound/cpp/AudioFileReader.h Source File

  • SpatialSound
  • cpp

AudioFileReader.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012
00013
00014 //
00015 // Helper class uses MediaFoundation to read audio files
00016 //
00017 class AudioFileReader
00018 {
00019 public:
00020     virtual ~AudioFileReader() {}
00021     HRESULT Initialize(_In_ LPCWSTR filename);
00022
00023     const WAVEFORMATEX* GetFormat() const
00024     {
00025         return &_format;
00026     }
00027
00028     size_t GetSize() const
00029     {
00030         return _audioData.size();
00031     }
00032
00033     const BYTE* GetData() const
00034     {
00035         return _audioData.data();
00036     }
00037
00038 private:
00039     WAVEFORMATEX        _format;
00040     std::vector<BYTE>   _audioData;
00041 };
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cppwinrt/CopyImage.cpp Source File

  • Clipboard
  • cppwinrt

CopyImage.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SampleConfiguration.h"
00014 #include "CopyImage.h"
00015 #include "CopyImage.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::ApplicationModel::DataTransfer;
00020 using namespace Windows::Graphics::Imaging;
00021 using namespace Windows::Storage;
00022 using namespace Windows::Storage::Pickers;
00023 using namespace Windows::Storage::Streams;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Media::Imaging;
00028
00029 namespace winrt::SDKTemplate::implementation
00030 {
00031     CopyImage::CopyImage()
00032     {
00033         InitializeComponent();
00034     }
00035
00036     void CopyImage::CopyButton_Click(IInspectable const&, RoutedEventArgs const&)
00037     {
00038         CopyBitmap(false);
00039     }
00040
00041     void CopyImage::CopyWithDelayedRenderingButton_Click(IInspectable const&, RoutedEventArgs const&)
00042     {
00043         CopyBitmap(true);
00044     }
00045
00046     fire_and_forget CopyImage::CopyBitmap(bool isDelayRendered)
00047     {
00048         auto lifetime = get_strong();
00049
00050         auto imagePicker = FileOpenPicker();
00051         imagePicker.ViewMode(PickerViewMode::Thumbnail);
00052         imagePicker.SuggestedStartLocation(PickerLocationId::PicturesLibrary);
00053         imagePicker.FileTypeFilter().ReplaceAll({ L".jpg", L".png", L".bmp", L".gif", L".tif" });
00054
00055         auto imageFile = co_await imagePicker.PickSingleFileAsync();
00056         if (imageFile)
00057         {
00058             auto dataPackage = DataPackage();
00059             hstring message;
00060
00061             // Use one click handler for two operations: regular copy and copy using delayed rendering
00062             // Differentiate the case by the button name
00063             if (isDelayRendered)
00064             {
00065                 dataPackage.SetDataProvider(StandardDataFormats::Bitmap(),
00066                     [imageFile](auto&& request)
00067                     {
00068                         OnDeferredImageRequestedHandler(request, imageFile);
00069                     });
00070                 message = L"Image has been copied using delayed rendering";
00071             }
00072             else
00073             {
00074                 dataPackage.SetBitmap(RandomAccessStreamReference::CreateFromFile(imageFile));
00075                 message = L"Image has been copied";
00076             }
00077
00078             if (Clipboard::SetContentWithOptions(dataPackage, nullptr))
00079             {
00080                 rootPage.NotifyUser(message, NotifyType::StatusMessage);
00081             }
00082             else
00083             {
00084                 // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
00085                 rootPage.NotifyUser(L"Error copying content to clipboard.", NotifyType::ErrorMessage);
00086             }
00087         }
00088     }
00089
00090     fire_and_forget CopyImage::PasteButton_Click(IInspectable const&, RoutedEventArgs const&)
00091     {
00092         auto lifetime = get_strong();
00093
00094         rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00095
00096         // Get the bitmap and display it.
00097         auto dataPackageView = Clipboard::GetContent();
00098         if (dataPackageView.Contains(StandardDataFormats::Bitmap()))
00099         {
00100             IRandomAccessStreamReference imageReceived = nullptr;
00101             try
00102             {
00103                 imageReceived = co_await dataPackageView.GetBitmapAsync();
00104             }
00105             catch (hresult_error const& ex)
00106             {
00107                 rootPage.NotifyUser(L"Error retrieving image from Clipboard: " + ex.message(), NotifyType::ErrorMessage);
00108             }
00109
00110             if (imageReceived)
00111             {
00112                 auto imageStream = co_await imageReceived.OpenReadAsync();
00113                 auto bitmapImage = BitmapImage();
00114                 bitmapImage.SetSource(imageStream);
00115                 OutputImage().Source(bitmapImage);
00116                 OutputImage().Visibility(Visibility::Visible);
00117                 OutputText().Text(L"Image is retrieved from the clipboard and pasted successfully.");
00118                 imageStream.Close();
00119             }
00120         }
00121         else
00122         {
00123             OutputText().Text(L"Bitmap format is not available in clipboard");
00124             OutputImage().Visibility(Visibility::Collapsed);
00125         }
00126     }
00127
00128     fire_and_forget CopyImage::OnDeferredImageRequestedHandler(DataProviderRequest request, StorageFile imageFile)
00129     {
00130         // Since this method is calling async methods prior to setting the data in DataPackage,
00131         // deferral object must be used
00132         auto deferral = request.GetDeferral();
00133
00134         try
00135         {
00136             auto imageStream = co_await imageFile.OpenAsync(FileAccessMode::Read);
00137
00138             // Decode the image
00139             auto imageDecoder = co_await BitmapDecoder::CreateAsync(imageStream);
00140
00141             // Re-encode the image at 50% width and height
00142             auto inMemoryStream = InMemoryRandomAccessStream();
00143             auto imageEncoder = co_await BitmapEncoder::CreateForTranscodingAsync(inMemoryStream, imageDecoder);
00144             imageEncoder.BitmapTransform().ScaledWidth(static_cast<uint32_t>(imageDecoder.OrientedPixelWidth() * 0.5));
00145             imageEncoder.BitmapTransform().ScaledHeight(static_cast<uint32_t>(imageDecoder.OrientedPixelHeight() * 0.5));
00146             co_await imageEncoder.FlushAsync();
00147
00148             request.SetData(RandomAccessStreamReference::CreateFromStream(inMemoryStream));
00149
00150             SampleState::DisplayToast(L"Image has been set via deferral");
00151         }
00152         catch (hresult_error const& ex)
00153         {
00154             SampleState::DisplayToast(L"Failed delayed rendering - " + ex.message());
00155         }
00156         deferral.Complete();
00157     }
00158 }
Generated on Fri Nov 15 2024 22:18:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ExtendedExecution/cs/Scenario3_LocationTrackingReason.xaml.cs Source File

  • ExtendedExecution
  • cs

Scenario3_LocationTrackingReason.xaml.cs

Go to the documentation of this file.
00001 ﻿
00002 //*********************************************************
00003 //
00004 // Copyright (c) Microsoft. All rights reserved.
00005 // This code is licensed under the MIT License (MIT).
00006 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00007 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00008 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00009 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00010 //
00011 //*********************************************************
00012
00013 using System;
00014 using System.Threading;
00015 using System.Threading.Tasks;
00016 using Windows.ApplicationModel.ExtendedExecution;
00017 using Windows.Devices.Geolocation;
00018 using Windows.UI.Core;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// Page containing the Extended Execution LocationTracking Reason scenario functions.
00026     /// </summary>
00027     public sealed partial class LocationTrackingReason : Page
00028     {
00029         private MainPage rootPage = MainPage.Current;
00030
00031         ExtendedExecutionSession session = null;
00032         private Timer periodicTimer = null;
00033
00034         public LocationTrackingReason()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00040         {
00041             // End the Extended Execution Session.
00042             // Only one extended execution session can be held by an application at one time.
00043             ClearExtendedExecution();
00044         }
00045
00046         void ClearExtendedExecution()
00047         {
00048             if (session != null)
00049             {
00050                 session.Revoked -= SessionRevoked;
00051                 session.Dispose();
00052                 session = null;
00053             }
00054
00055             if (periodicTimer != null)
00056             {
00057                 periodicTimer.Dispose();
00058                 periodicTimer = null;
00059             }
00060         }
00061
00062         private void UpdateUI()
00063         {
00064             if (session == null)
00065             {
00066                 Status.Text = "Not requested";
00067                 RequestButton.IsEnabled = true;
00068                 CloseButton.IsEnabled = false;
00069             }
00070             else
00071             {
00072                 Status.Text = "Requested";
00073                 RequestButton.IsEnabled = false;
00074                 CloseButton.IsEnabled = true;
00075             }
00076         }
00077
00078         private async Task<Geolocator> StartLocationTrackingAsync()
00079         {
00080             Geolocator geolocator = null;
00081
00082             // Request permission to access location
00083             var accessStatus = await Geolocator.RequestAccessAsync();
00084
00085             switch (accessStatus)
00086             {
00087                 case GeolocationAccessStatus.Allowed:
00088                     // See the Geolocation sample for more information on using the Geolocator class.
00089                     geolocator = new Geolocator { ReportInterval = 2000 };
00090                     break;
00091
00092                 case GeolocationAccessStatus.Denied:
00093                     rootPage.NotifyUser("Access to location is denied.", NotifyType.ErrorMessage);
00094                     break;
00095
00096                 default:
00097                 case GeolocationAccessStatus.Unspecified:
00098                     rootPage.NotifyUser("Couldn't access the geolocator.", NotifyType.ErrorMessage);
00099                     break;
00100             }
00101
00102             return geolocator;
00103         }
00104
00105         private async void BeginExtendedExecution()
00106         {
00107             // The previous Extended Execution must be closed before a new one can be requested.
00108             // This code is redundant here because the sample doesn't allow a new extended
00109             // execution to begin until the previous one ends, but we leave it here for illustration.
00110             ClearExtendedExecution();
00111
00112             var newSession = new ExtendedExecutionSession();
00113             newSession.Reason = ExtendedExecutionReason.LocationTracking;
00114             newSession.Description = "Tracking your location";
00115             newSession.Revoked += SessionRevoked;
00116             ExtendedExecutionResult result = await newSession.RequestExtensionAsync();
00117
00118             switch (result)
00119             {
00120                 case ExtendedExecutionResult.Allowed:
00121                     rootPage.NotifyUser("Extended execution allowed.", NotifyType.StatusMessage);
00122                     session = newSession;
00123                     Geolocator geolocator = await StartLocationTrackingAsync();
00124                     periodicTimer = new Timer(OnTimer, geolocator, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10));
00125                     break;
00126
00127                 default:
00128                 case ExtendedExecutionResult.Denied:
00129                     rootPage.NotifyUser("Extended execution denied.", NotifyType.ErrorMessage);
00130                     newSession.Dispose();
00131                     break;
00132             }
00133             UpdateUI();
00134         }
00135
00136         private async void OnTimer(object state)
00137         {
00138             var geolocator = (Geolocator)state;
00139             string message;
00140             if (geolocator == null)
00141             {
00142                 message = "No geolocator";
00143             }
00144             else
00145             {
00146                 Geoposition geoposition = await geolocator.GetGeopositionAsync();
00147                 if (geoposition == null)
00148                 {
00149                     message = "Cannot get current location";
00150                 }
00151                 else
00152                 {
00153                     BasicGeoposition basicPosition = geoposition.Coordinate.Point.Position;
00154                     message = $"Longitude = {basicPosition.Longitude}, Latitude = {basicPosition.Latitude}";
00155                 }
00156             }
00157             MainPage.DisplayToast(message);
00158         }
00159
00160         private void EndExtendedExecution()
00161         {
00162             ClearExtendedExecution();
00163             UpdateUI();
00164         }
00165
00166         private async void SessionRevoked(object sender, ExtendedExecutionRevokedEventArgs args)
00167         {
00168             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00169             {
00170                 switch (args.Reason)
00171                 {
00172                     case ExtendedExecutionRevokedReason.Resumed:
00173                         rootPage.NotifyUser("Extended execution revoked due to returning to foreground.", NotifyType.StatusMessage);
00174                         break;
00175
00176                     case ExtendedExecutionRevokedReason.SystemPolicy:
00177                         rootPage.NotifyUser("Extended execution revoked due to system policy.", NotifyType.StatusMessage);
00178                         break;
00179                 }
00180
00181                 EndExtendedExecution();
00182             });
00183         }
00184     }
00185 }
Generated on Fri Nov 15 2024 22:19:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cppwinrt/Content/ShaderStructures.h Source File

  • BasicHologram
  • cppwinrt
  • Content

ShaderStructures.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 namespace BasicHologram
00004 {
00005     // Constant buffer used to send hologram position transform to the shader pipeline.
00006     struct ModelConstantBuffer
00007     {
00008         DirectX::XMFLOAT4X4 model;
00009     };
00010
00011     // Assert that the constant buffer remains 16-byte aligned (best practice).
00012     static_assert((sizeof(ModelConstantBuffer) % (sizeof(float) * 4)) == 0, "Model constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00013
00014
00015     // Used to send per-vertex data to the vertex shader.
00016     struct VertexPositionColor
00017     {
00018         DirectX::XMFLOAT3 pos;
00019         DirectX::XMFLOAT3 color;
00020     };
00021 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario1.xaml.cpp Source File

  • MapControl
  • cpp

Scenario1.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Devices::Geolocation;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Maps;
00023
00024 Scenario1::Scenario1()
00025 {
00026     InitializeComponent();
00027 }
00028
00029 void Scenario1::MyMap_Loaded(Object^ sender, RoutedEventArgs^ e)
00030 {
00031     myMap->Center = MainPage::SeattleGeopoint;
00032     myMap->ZoomLevel = 12;
00033     SetMapStyle();
00034     SetMapProjection();
00035 }
00036
00037 void Scenario1::MyMap_MapTapped(MapControl^ sender, MapInputEventArgs^ args)
00038 {
00039     BasicGeoposition tappedGeoPosition = args->Location->Position;
00040     String^ status = "MapTapped at Latitude:" + tappedGeoPosition.Latitude + ", Longitude: " + tappedGeoPosition.Longitude;
00041     rootPage->NotifyUser(status, NotifyType::StatusMessage);
00042 }
00043
00044 void Scenario1::TrafficFlowVisible_Checked(Object^ sender, RoutedEventArgs^ e)
00045 {
00046     myMap->TrafficFlowVisible = true;
00047 }
00048
00049 void Scenario1::trafficFlowVisibleCheckBox_Unchecked(Object^ sender, RoutedEventArgs^ e)
00050 {
00051     myMap->TrafficFlowVisible = false;
00052 }
00053
00054 void Scenario1::styleCombobox_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00055 {
00056     // Protect against events that are raised before we are fully initialized.
00057     if (myMap != nullptr)
00058     {
00059         SetMapStyle();
00060     }
00061 }
00062
00063 void Scenario1::SetMapStyle()
00064 {
00065     switch (styleCombobox->SelectedIndex)
00066     {
00067     case 0:
00068         myMap->Style = MapStyle::None;
00069         break;
00070     case 1:
00071         myMap->Style = MapStyle::Road;
00072         break;
00073     case 2:
00074         myMap->Style = MapStyle::Aerial;
00075         break;
00076     case 3:
00077         myMap->Style = MapStyle::AerialWithRoads;
00078         break;
00079     case 4:
00080         myMap->Style = MapStyle::Terrain;
00081         break;
00082     }
00083 }
00084
00085 void Scenario1::projectionCombobox_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00086 {
00087     // Protect against events that are raised before we are fully initialized.
00088     if (myMap != nullptr)
00089     {
00090         SetMapProjection();
00091     }
00092 }
00093
00094 void Scenario1::SetMapProjection()
00095 {
00096     switch (projectionCombobox->SelectedIndex)
00097     {
00098     case 0:
00099         myMap->MapProjection = MapProjection::WebMercator;
00100         break;
00101     case 1:
00102         myMap->MapProjection = MapProjection::Globe;
00103         break;
00104    }
00105 }
Generated on Fri Nov 15 2024 22:17:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ClientDeviceInformation/cpp/SampleConfiguration.cpp Source File

  • ClientDeviceInformation
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Get Device Information", "SDKTemplate.Scenario1_GetDeviceInformation" },
00012 };
Generated on Fri Nov 15 2024 22:17:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlMasterDetail/cppwinrt/ItemViewModel.cpp Source File

  • XamlMasterDetail
  • cppwinrt

ItemViewModel.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "ViewModels.ItemViewModel.g.h"
00014
00015 namespace winrt::MasterDetailApp::ViewModels::implementation
00016 {
00017     struct ItemViewModel : ItemViewModelT<ItemViewModel>
00018     {
00019         ItemViewModel(MasterDetailApp::Data::Item const& item) :
00020             m_id{ item.ItemId() }, m_title{ item.Title() },
00021             m_text{ item.Text() }, m_dateCreated{ item.DateCreated() }
00022         {
00023         }
00024
00025         static MasterDetailApp::ViewModels::ItemViewModel FromItem(MasterDetailApp::Data::Item const& item)
00026         {
00027             return make<ItemViewModel>(item);
00028         }
00029
00030         int ItemId() { return m_id; }
00031         hstring Title() { return m_title; }
00032         hstring Text() { return m_text; }
00033         Windows::Foundation::DateTime DateCreated() { return m_dateCreated; }
00034
00035         hstring DateCreatedHourMinute()
00036         {
00037             auto formatter = Windows::Globalization::DateTimeFormatting::DateTimeFormatter(L"hour minute");
00038             return formatter.Format(m_dateCreated);
00039         }
00040
00041     private:
00042         int const m_id;
00043         hstring const m_title;
00044         hstring m_text;
00045         Windows::Foundation::DateTime const m_dateCreated;
00046     };
00047 }
00048
00049 namespace winrt::MasterDetailApp::ViewModels::factory_implementation
00050 {
00051     struct ItemViewModel : ItemViewModelT<ItemViewModel, implementation::ItemViewModel>
00052     {
00053     };
00054 }
00055
00056 #include "ViewModels.ItemViewModel.g.cpp"
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cs/Scenario5_DataEventsBatching.xaml.cs Source File

  • Accelerometer
  • cs

Scenario5_DataEventsBatching.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Devices.Sensors;
00014 using Windows.UI.Core;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario5_DataEventsBatching : Page
00022     {
00023         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00024         // as NotifyUser()
00025         MainPage rootPage = MainPage.Current;
00026
00027         private Accelerometer accelerometer;
00028         private uint desiredReportInterval;
00029         private uint desiredReportLatency;
00030
00031
00032         public Scenario5_DataEventsBatching()
00033         {
00034             this.InitializeComponent();
00035         }
00036
00037         protected override void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039             accelerometer = Accelerometer.GetDefault(rootPage.AccelerometerReadingType);
00040             if (accelerometer != null)
00041             {
00042                 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00043                 // This value will be used later to activate the sensor.
00044                 desiredReportInterval = Math.Max(accelerometer.MinimumReportInterval, 16);
00045
00046                 // MaxBatchSize will be 0 if the accelerometer does not support batching.
00047                 uint maxLatency = accelerometer.MaxBatchSize * desiredReportInterval;
00048                 desiredReportLatency = Math.Min(maxLatency, 10000);
00049
00050                 rootPage.NotifyUser(rootPage.AccelerometerReadingType + " accelerometer ready", NotifyType.StatusMessage);
00051                 ScenarioEnableButton.IsEnabled = true;
00052             }
00053             else
00054             {
00055                 rootPage.NotifyUser(rootPage.AccelerometerReadingType + " accelerometer not found", NotifyType.ErrorMessage);
00056             }
00057         }
00058
00059         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00060         {
00061             if (ScenarioDisableButton.IsEnabled)
00062             {
00063                 ScenarioDisable();
00064             }
00065         }
00066
00067         /// <summary>
00068         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00069         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00070         /// </summary>
00071         /// <param name="sender"></param>
00072         /// <param name="e">
00073         /// Event data that can be examined for the current visibility state.
00074         /// </param>
00075         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00076         {
00077             if (ScenarioDisableButton.IsEnabled)
00078             {
00079                 if (e.Visible)
00080                 {
00081                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00082                     accelerometer.ReadingChanged += ReadingChanged;
00083                 }
00084                 else
00085                 {
00086                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00087                     accelerometer.ReadingChanged -= ReadingChanged;
00088                 }
00089             }
00090         }
00091
00092         /// <summary>
00093         /// This is the event handler for ReadingChanged events.
00094         /// </summary>
00095         /// <param name="sender"></param>
00096         /// <param name="e"></param>
00097         async private void ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e)
00098         {
00099             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00100             {
00101                 MainPage.SetReadingText(ScenarioOutput, e.Reading);
00102             });
00103         }
00104
00105         /// <summary>
00106         /// This is the click handler for the 'Enable' button.
00107         /// </summary>
00108         private void ScenarioEnable()
00109         {
00110             // Establish the report interval
00111             accelerometer.ReportInterval = desiredReportInterval;
00112
00113             // Establish the report latency. This is a no-op if the accelerometer does not support batching
00114             accelerometer.ReportLatency = desiredReportLatency;
00115             Window.Current.VisibilityChanged += VisibilityChanged;
00116             accelerometer.ReadingChanged += ReadingChanged;
00117
00118             ScenarioEnableButton.IsEnabled = false;
00119             ScenarioDisableButton.IsEnabled = true;
00120         }
00121
00122         /// <summary>
00123         /// This is the click handler for the 'Disable' button.
00124         /// </summary>
00125         private void ScenarioDisable()
00126         {
00127             Window.Current.VisibilityChanged -= VisibilityChanged;
00128             accelerometer.ReadingChanged -= ReadingChanged;
00129
00130             // Restore the default report interval to release resources while the sensor is not in use
00131             accelerometer.ReportInterval = 0;
00132
00133             ScenarioEnableButton.IsEnabled = true;
00134             ScenarioDisableButton.IsEnabled = false;
00135         }
00136     }
00137 }
Generated on Fri Nov 15 2024 22:17:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cs/Scenario4_Override.xaml.cs Source File

  • DateTimeFormatting
  • cs

Scenario4_Override.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Text;
00014 using Windows.Foundation;
00015 using Windows.Foundation.Collections;
00016 using Windows.Globalization;
00017 using Windows.Globalization.DateTimeFormatting;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario4_Override : Page
00025     {
00026         public Scenario4_Override()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         /// <summary>
00032         /// This is the click handler for the 'Display' button.
00033         /// </summary>
00034         private void Display()
00035         {
00036             // This scenario uses the Windows.Globalization.DateTimeFormatting.DateTimeFormatter class
00037             // to format a date/time by using a formatter that provides specific languages,
00038             // geographic region, calendar and clock
00039
00040             // We keep results in this variable
00041             StringBuilder results = new StringBuilder();
00042             results.AppendLine("Current default application context language: " + ApplicationLanguages.Languages[0]);
00043             results.AppendLine();
00044
00045             // Create formatters with individual format specifiers for date/time elements.
00046             DateTimeFormatter[] templateFormatters = new[]
00047             {
00048                 // Example formatters for dates using string templates.
00049                 new DateTimeFormatter("longdate", new[] { "ja-JP", "en-US" }, "JP", CalendarIdentifiers.Japanese, ClockIdentifiers.TwelveHour),
00050                 new DateTimeFormatter("month day", new[] { "fr-FR", "en-US" }, "FR", CalendarIdentifiers.Gregorian, ClockIdentifiers.TwentyFourHour),
00051
00052                 // Example formatters using paranetrized date templates.
00053                 new DateTimeFormatter(YearFormat.Abbreviated,
00054                     MonthFormat.Abbreviated,
00055                     DayFormat.Default,
00056                     DayOfWeekFormat.None,
00057                     HourFormat.None,
00058                     MinuteFormat.None,
00059                     SecondFormat.None,
00060                     new[] { "de-DE", "en-US" },
00061                     "DE",
00062                     CalendarIdentifiers.Gregorian,
00063                     ClockIdentifiers.TwelveHour),
00064
00065                 // Example formatters for times.
00066                 new DateTimeFormatter("longtime", new[] { "ja-JP", "en-US" }, "JP", CalendarIdentifiers.Japanese, ClockIdentifiers.TwelveHour),
00067                 new DateTimeFormatter("hour minute", new[] { "fr-FR", "en-US" }, "FR", CalendarIdentifiers.Gregorian, ClockIdentifiers.TwentyFourHour),
00068
00069                 // Example formatters using paranetrized time templates.
00070                 new DateTimeFormatter(YearFormat.None,
00071                     MonthFormat.None,
00072                     DayFormat.None,
00073                     DayOfWeekFormat.None,
00074                     HourFormat.Default,
00075                     MinuteFormat.Default,
00076                     SecondFormat.None,
00077                     new[] { "de-DE" },
00078                     "DE",
00079                     CalendarIdentifiers.Gregorian,
00080                     ClockIdentifiers.TwelveHour),
00081              };
00082
00083             // Create date/time to format and display.
00084             DateTime dateTime = DateTime.Now;
00085
00086             // Format and display date/time. Calendar always supports Now. Otherwise you may need to verify dateTime is in supported range.
00087             foreach (DateTimeFormatter formatter in templateFormatters)
00088             {
00089                 // Format and display date/time.
00090                 results.AppendLine(formatter.Template + ": (" + formatter.ResolvedLanguage + ") " + formatter.Format(dateTime));
00091             }
00092
00093             // Display the results
00094             OutputTextBlock.Text = results.ToString();
00095         }
00096     }
00097 }
Generated on Fri Nov 15 2024 22:19:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/Scenario1_ProvisionTPM.h Source File

  • SmartCard
  • cppwinrt

Scenario1_ProvisionTPM.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <string>
00015 #include "Scenario1_ProvisionTPM.g.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1_ProvisionTPM : Scenario1_ProvisionTPMT<Scenario1_ProvisionTPM>
00020     {
00021         Scenario1_ProvisionTPM();
00022
00023         fire_and_forget Create_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const&);
00024
00025     private:
00026         SDKTemplate::MainPage m_rootPage{ SDKTemplate::MainPage::Current() };
00027
00028         Windows::Devices::SmartCards::SmartCardReader m_reader{ nullptr };
00029         Windows::Devices::SmartCards::SmartCardReader::CardAdded_revoker m_cardAddedToken;
00030
00031         void HandleCardAdded(Windows::Devices::SmartCards::SmartCardReader const&, Windows::Devices::SmartCards::CardAddedEventArgs const&);
00032
00033         Windows::Devices::SmartCards::SmartCardPinPolicy ParsePinPolicy();
00034     };
00035 }
00036
00037 namespace winrt::SDKTemplate::factory_implementation
00038 {
00039     struct Scenario1_ProvisionTPM : Scenario1_ProvisionTPMT<Scenario1_ProvisionTPM, implementation::Scenario1_ProvisionTPM>
00040     {
00041     };
00042 };
Generated on Fri Nov 15 2024 22:21:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboardTextInput/cpp/Scenario2_ScopedViews.xaml.cpp Source File

  • TouchKeyboardTextInput
  • cpp

Scenario2_ScopedViews.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_ScopedViews.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Primitives;
00023 using namespace Windows::UI::Xaml::Data;
00024 using namespace Windows::UI::Xaml::Input;
00025 using namespace Windows::UI::Xaml::Media;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00029
00030 Scenario2_ScopedViews::Scenario2_ScopedViews()
00031 {
00032     InitializeComponent();
00033 }
Generated on Fri Nov 15 2024 22:21:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Line Member List

This is the complete list of members for Line, including all inherited members.
AddChildElement(const std::shared_ptr< BaseElement > &childElement) | BaseElement |
ArrangeElements() | BaseElement | [virtual]
BaseElement() | BaseElement |
GetElementMargin() | BaseElement | [inline]
GetElementSize() | BaseElement | [inline]
GetIgnoreLayout() | BaseElement | [inline]
GetIsRenderPassNeeded() | BaseElement | [inline]
GetIsVisible() | BaseElement | [inline]
Initialize() | BaseElement | [virtual]
Line(FLOAT strokeThickness) | Line |
m_deviceResources | BaseElement | [protected]
m_elementMargin | BaseElement | [protected]
m_elementSize | BaseElement | [protected]
m_ignoreLayout | BaseElement | [protected]
m_isInitialized | BaseElement | [protected]
m_isLayoutHorizontal | BaseElement | [protected]
m_isRenderPassNeeded | BaseElement | [protected]
m_isVisible | BaseElement | [protected]
m_lineEnd | Line | [private]
m_lineStart | Line | [private]
m_parentTranslation | BaseElement | [protected]
m_strokeThickness | Line | [private]
m_transformedTranslation | BaseElement | [protected]
m_transformMatrix | BaseElement | [protected]
m_transformRecalculationNeeded | BaseElement | [protected]
m_translation | BaseElement | [protected]
Render() override | Line | [protected, virtual]
SetBrush(ID2D1SolidColorBrush *brush) | BaseElement |
SetElementMargin(ElementMargin margin) | BaseElement | [inline]
SetElementSize(Windows::Foundation::Numerics::float2 size) | BaseElement | [inline]
SetEndPoint(D2D1_POINT_2F &point) | Line |
SetIgnoreLayout(bool ignoreLayout) | BaseElement | [inline]
SetIsVisible(bool visible) | BaseElement |
SetLayoutHorizontal(bool isLayoutHorizontal) | BaseElement | [inline]
SetParentTransform(Windows::Foundation::Numerics::float2 translation) | BaseElement |
SetStartPoint(D2D1_POINT_2F &point) | Line |
SetTranslation(Windows::Foundation::Numerics::float2 translation) | BaseElement | [virtual]
TryRender() | BaseElement |
Update(const DX::StepTimer &timer, Windows::UI::Input::Spatial::SpatialPointerPose^cameraPose) | BaseElement | [virtual]
~BaseElement() | BaseElement | [virtual]
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cpp/Scenario5_DeviceReadWrite.xaml.h Source File

  • CustomCapability
  • cpp

Scenario5_DeviceReadWrite.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "Scenario5_DeviceReadWrite.g.h"
00014
00015 namespace SDKTemplate
00016 {
00017     /// <summary>
00018     /// An empty page that can be used on its own or navigated to within a Frame.
00019     /// </summary>
00020     [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class DeviceReadWrite sealed
00022     {
00023     public:
00024         DeviceReadWrite();
00025
00026     private:
00027         MainPage^ rootPage = MainPage::Current;
00028
00029         unsigned int writeCounter = 0;
00030         unsigned int readCounter = 0;
00031
00032         void ReadBlock_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033         void WriteBlock_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034
00035         void LogMessage(Platform::String^ message);
00036     };
00037 }
00038
Generated on Fri Nov 15 2024 22:19:03 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cpp/Scenario3_ClientAuthentication.xaml.h Source File

  • WebSocket
  • cpp

Scenario3_ClientAuthentication.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1.xaml.h
00014 // Declaration of the Scenario1 class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario3_ClientAuthentication.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario3 sealed
00030     {
00031     public:
00032         Scenario3();
00033
00034     protected:
00035         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036
00037         void OnConnect();
00038         void OnDisconnect();
00039
00040     private:
00041         MainPage^ rootPage = MainPage::Current;
00042         Windows::Networking::Sockets::StreamWebSocket^ streamWebSocket;
00043         bool busy = false;
00044
00045         void UpdateVisualState();
00046         void SetBusy(bool value);
00047         Concurrency::task<Windows::Security::Cryptography::Certificates::Certificate^> FindCertificateFromStoreAsync();
00048         Concurrency::task<Windows::Security::Cryptography::Certificates::Certificate^> InstallClientCertificateAsync();
00049         Concurrency::task<Windows::Security::Cryptography::Certificates::Certificate^> GetClientCertificateAsync();
00050         Concurrency::task<void> ConnectWebSocketAsync();
00051         void OnClosed(Windows::Networking::Sockets::IWebSocket^ sender, Windows::Networking::Sockets::WebSocketClosedEventArgs^ args);
00052         void CloseSocket();
00053         void AppendOutputLine(Platform::String^ value);
00054     };
00055 }
Generated on Fri Nov 15 2024 22:22:01 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario03 Member List

This is the complete list of members for Scenario03, including all inherited members.
activeDeviceInformation | Scenario03 | [private]
activeDialDevice | Scenario03 | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario03 | [inline, protected]
picker | Scenario03 | [private]
Picker_DevicePickerDismissed(DialDevicePicker sender, object args) | Scenario03 | [inline, private]
Picker_DeviceSelected(DialDevicePicker sender, DialDeviceSelectedEventArgs args) | Scenario03 | [inline, private]
Picker_DisconnectButtonClicked(DialDevicePicker sender, DialDisconnectButtonClickedEventArgs args) | Scenario03 | [inline, private]
Player_CurrentStateChanged(object sender, RoutedEventArgs e) | Scenario03 | [inline, private]
Player_MediaFailed(object sender, ExceptionRoutedEventArgs e) | Scenario03 | [inline, private]
Player_MediaOpened(object sender, RoutedEventArgs e) | Scenario03 | [inline, private]
rootPage | Scenario03 | [private]
Scenario03() | Scenario03 | [inline]
TransportControls_CastButtonClicked(object sender, EventArgs e) | Scenario03 | [inline, private]
video | Scenario03 | [private]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cs/Scenario2_Listen.xaml.cs Source File

  • IoT-GPIO
  • cs

Scenario2_Listen.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Devices.Gpio;
00014 using Windows.UI.Core;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// Scenario describing how to listen for changes to a GPIO pin value
00023     /// </summary>
00024     public sealed partial class Scenario2_Listen : Page
00025     {
00026         // Use GPIO pin 5 to set values
00027         private const int SET_PIN = 5;
00028         private GpioPin setPin;
00029
00030         // Use GPIO pin 6 to listen for value changes
00031         private const int LISTEN_PIN = 6;
00032         private GpioPin listenPin;
00033
00034         private GpioPinValue currentValue = GpioPinValue.High;
00035         private DispatcherTimer timer;
00036
00037         public Scenario2_Listen()
00038         {
00039             this.InitializeComponent();
00040         }
00041
00042         protected override void OnNavigatedFrom(NavigationEventArgs e)
00043         {
00044             StopScenario();
00045         }
00046
00047         void StartScenario()
00048         {
00049             // Initialize the GPIO objects.
00050             var gpio = GpioController.GetDefault();
00051
00052             // Set up our GPIO pin for setting values.
00053             // If this next line crashes with a NullReferenceException,
00054             // then the problem is that there is no GPIO controller on the device.
00055             setPin = gpio.OpenPin(SET_PIN);
00056
00057             // Establish initial value and configure pin for output.
00058             setPin.Write(currentValue);
00059             setPin.SetDriveMode(GpioPinDriveMode.Output);
00060
00061             // Set up our GPIO pin for listening for value changes.
00062             listenPin = gpio.OpenPin(LISTEN_PIN);
00063
00064             // Configure pin for input and add ValueChanged listener.
00065             listenPin.SetDriveMode(GpioPinDriveMode.Input);
00066             listenPin.ValueChanged += Pin_ValueChanged;
00067
00068             // Start toggling the pin value every 500ms.
00069             timer = new DispatcherTimer();
00070             timer.Interval = TimeSpan.FromMilliseconds(500);
00071             timer.Tick += Timer_Tick;
00072             timer.Start();
00073         }
00074
00075         void StopScenario()
00076         {
00077             // Stop the timer.
00078             if (timer != null)
00079             {
00080                 timer.Stop();
00081                 timer = null;
00082             }
00083
00084             // Release the GPIO pins.
00085             if (setPin != null)
00086             {
00087                 setPin.Dispose();
00088                 setPin = null;
00089             }
00090             if (listenPin != null)
00091             {
00092                 listenPin.ValueChanged -= Pin_ValueChanged;
00093                 listenPin.Dispose();
00094                 listenPin = null;
00095             }
00096         }
00097
00098         void StartStopScenario_Click(object sender, RoutedEventArgs e)
00099         {
00100             if (timer != null)
00101             {
00102                 StopScenario();
00103                 StartStopButton.Content = "Start";
00104                 ScenarioControls.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00105             }
00106             else
00107             {
00108                 StartScenario();
00109                 StartStopButton.Content = "Stop";
00110                 ScenarioControls.Visibility = Windows.UI.Xaml.Visibility.Visible;
00111             }
00112         }
00113         private void Pin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
00114         {
00115             // Report the change in pin value.
00116             var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00117             {
00118                 CurrentPinValue.Text = listenPin.Read().ToString();
00119             });
00120         }
00121
00122         private void Timer_Tick(object sender, object e)
00123         {
00124             // Toggle the existing pin value.
00125             currentValue = (currentValue == GpioPinValue.High) ? GpioPinValue.Low : GpioPinValue.High;
00126             setPin.Write(currentValue);
00127         }
00128     }
00129 }
Generated on Fri Nov 15 2024 22:20:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BindingHelpers Member List

This is the complete list of members for BindingHelpers, including all inherited members.
CollapsedIf(bool value) | BindingHelpers | [inline, static]
Not(bool value) | BindingHelpers | [inline, static]
Generated on Fri Nov 15 2024 22:24:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LockScreenApps/cppwinrt/SampleConfiguration.h Source File

  • LockScreenApps
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialSound/cpp/Scenario2_CardioidSound.xaml.cpp Source File

  • SpatialSound
  • cpp

Scenario2_CardioidSound.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012
00013 #include "pch.h"
00014 #include "Scenario2_CardioidSound.xaml.h"
00015
00016 using namespace SDKTemplate;
00017
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Media;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029
00030 Scenario2_CardioidSound::Scenario2_CardioidSound() : _rootPage(MainPage::Current)
00031 {
00032     InitializeComponent();
00033     auto hr = _cardioidSound.Initialize(L"assets//MonoSound.wav");
00034     if (SUCCEEDED(hr))
00035     {
00036         _timer = ref new DispatcherTimer();
00037         _timerEventToken = _timer->Tick += ref new EventHandler<Platform::Object^>(this, &Scenario2_CardioidSound::OnTimerTick);
00038         TimeSpan timespan;
00039         timespan.Duration = 10000 / 30;
00040         _timer->Interval = timespan;
00041         EnvironmentComboBox->SelectedIndex = static_cast<int>(_cardioidSound.GetEnvironment());
00042         _rootPage->NotifyUser("Stopped", NotifyType::StatusMessage);
00043     }
00044     else
00045     {
00046         if (hr == E_NOTIMPL)
00047         {
00048             _rootPage->NotifyUser("HRTF API is not supported on this platform. Use X3DAudio API instead - https://code.msdn.microsoft.com/XAudio2-Win32-Samples-024b3933", NotifyType::ErrorMessage);
00049         }
00050         else
00051         {
00052             throw ref new COMException(hr);
00053         }
00054     }
00055
00056     _initialized = SUCCEEDED(hr);
00057 }
00058
00059 Scenario2_CardioidSound::~Scenario2_CardioidSound()
00060 {
00061     if (_timerEventToken.Value != 0)
00062     {
00063         _timer->Tick -= _timerEventToken;
00064     }
00065 }
00066
00067 void SDKTemplate::Scenario2_CardioidSound::EnvironmentComboBox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
00068 {
00069     if (_initialized)
00070     {
00071         _cardioidSound.SetEnvironment(static_cast<HrtfEnvironment>(EnvironmentComboBox->SelectedIndex));
00072     }
00073 }
00074
00075 void SDKTemplate::Scenario2_CardioidSound::ScalingSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00076 {
00077     UpdateScalingAndOrder();
00078 }
00079
00080 void SDKTemplate::Scenario2_CardioidSound::OrderSlider_ValudChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00081 {
00082     UpdateScalingAndOrder();
00083 }
00084
00085 void SDKTemplate::Scenario2_CardioidSound::YawSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00086 {
00087     _yaw = static_cast<float>(e->NewValue);
00088 }
00089
00090 void SDKTemplate::Scenario2_CardioidSound::PitchSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00091 {
00092     _pitch = static_cast<float>(e->NewValue);
00093 }
00094
00095
00096 void SDKTemplate::Scenario2_CardioidSound::RollSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00097 {
00098     _roll = static_cast<float>(e->NewValue);
00099 }
00100
00101 void SDKTemplate::Scenario2_CardioidSound::PlayButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00102 {
00103     if (_initialized)
00104     {
00105         _cardioidSound.Start();
00106         _state = PlayState::Playing;
00107         _rootPage->NotifyUser("Playing", NotifyType::StatusMessage);
00108     }
00109 }
00110
00111 void SDKTemplate::Scenario2_CardioidSound::StopButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00112 {
00113     if (_initialized)
00114     {
00115         _cardioidSound.Stop();
00116         _state = PlayState::Stopped;
00117         _rootPage->NotifyUser("Stopped", NotifyType::StatusMessage);
00118     }
00119 }
00120
00121 void SDKTemplate::Scenario2_CardioidSound::OnTimerTick(Object^ sender, Object^ e)
00122 {
00123     // Update the sound position and orientation on every dispatcher timer tick.
00124     _cardioidSound.OnUpdate(_x, _y, _z, _pitch, _yaw, _roll);
00125 }
00126
00127 void SDKTemplate::Scenario2_CardioidSound::UpdateScalingAndOrder()
00128 {
00129     if (_initialized)
00130     {
00131         _timer->Stop();
00132         _cardioidSound.ConfigureApo(static_cast<float>(ScalingSlider->Value), static_cast<float>(OrderSlider->Value));
00133         _timer->Start();
00134
00135         if (_state == PlayState::Playing)
00136         {
00137             _cardioidSound.Start();
00138         }
00139     }
00140 }
00141
00142 void SDKTemplate::Scenario2_CardioidSound::SourcePositionX_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00143 {
00144     _x = static_cast<float>(e->NewValue);
00145 }
00146
00147 void SDKTemplate::Scenario2_CardioidSound::SourcePositionY_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00148 {
00149     _y = static_cast<float>(e->NewValue);
00150 }
00151
00152 void SDKTemplate::Scenario2_CardioidSound::SourcePositionZ_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00153 {
00154     _z = static_cast<float>(e->NewValue);
00155 }
Generated on Fri Nov 15 2024 22:21:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cppwinrt/pch.h Source File

  • PenHaptics
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.Foundation.Numerics.h"
00007 #include "winrt/Windows.ApplicationModel.Activation.h"
00008 #include "winrt/Windows.Devices.Haptics.h"
00009 #include "winrt/Windows.Devices.Input.h"
00010 #include "winrt/Windows.System.h"
00011 #include "winrt/Windows.UI.h"
00012 #include "winrt/Windows.UI.Core.h"
00013 #include "winrt/Windows.UI.Xaml.h"
00014 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00015 #include "winrt/Windows.UI.Xaml.Controls.h"
00016 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00017 #include "winrt/Windows.UI.Xaml.Documents.h"
00018 #include "winrt/Windows.UI.Xaml.Input.h"
00019 #include "winrt/Windows.UI.Xaml.Interop.h"
00020 #include "winrt/Windows.UI.Xaml.Markup.h"
00021 #include "winrt/Windows.UI.Xaml.Media.h"
00022 #include "winrt/Windows.UI.Xaml.Navigation.h"
00023 #include "winrt/Windows.UI.Xaml.Shapes.h"
00024 #include <math.h>
00025 #include <map>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MessageDialog/cpp/CancelCommand.xaml.h Source File

  • MessageDialog
  • cpp

CancelCommand.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // CancelCommand.xaml.h
00013 // Declaration of the CancelCommand class
00014 //
00015
00016 #pragma once
00017
00018 #include "CancelCommand.g.h"
00019 #include "MainPage.xaml.h"
00020
00021 namespace SDKTemplate
00022 {
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class CancelCommand sealed
00025     {
00026     public:
00027         CancelCommand();
00028
00029     protected:
00030         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00031     private:
00032         MainPage^ rootPage;
00033         void CancelCommandButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void CommandInvokedHandler(Windows::UI::Popups::IUICommand^ command);
00035     };
00036 }
Generated on Fri Nov 15 2024 22:20:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaImport/cs/App.xaml.cs Source File

  • MediaImport
  • cs

App.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel;
00014 using Windows.ApplicationModel.Activation;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018 using Windows.Media.Import;
00019 using System.Collections.Generic;
00020 using System.Diagnostics;
00021
00022 // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
00023
00024 namespace SDKTemplate
00025 {
00026     /// <summary>
00027     /// Provides application-specific behavior to supplement the default Application class.
00028     /// </summary>
00029     sealed partial class App : Application
00030     {
00031         /// <summary>
00032         /// Initializes the singleton application object.  This is the first line of authored code
00033         /// executed, and as such is the logical equivalent of main() or WinMain().
00034         /// </summary>
00035         public App()
00036         {
00037             this.InitializeComponent();
00038             this.Suspending += OnSuspending;
00039         }
00040
00041         /// <summary>
00042         /// Invoked when the application is launched normally by the end user.  Other entry points
00043         /// will be used such as when the application is launched to open a specific file.
00044         /// </summary>
00045         /// <param name="e">Details about the launch request and process.</param>
00046         protected override async void OnLaunched(LaunchActivatedEventArgs e)
00047         {
00048
00049 #if DEBUG
00050             if (System.Diagnostics.Debugger.IsAttached)
00051             {
00052                 this.DebugSettings.EnableFrameRateCounter = false;
00053             }
00054 #endif
00055
00056             Frame rootFrame = Window.Current.Content as Frame;
00057
00058             // Do not repeat app initialization when the Window already has content,
00059             // just ensure that the window is active
00060
00061             if (rootFrame == null)
00062             {
00063                 // Create a Frame to act as the navigation context and navigate to the first page
00064                 rootFrame = new Frame();
00065                 // Set the default language
00066                 rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
00067
00068                 rootFrame.NavigationFailed += OnNavigationFailed;
00069                 rootFrame.Navigate(typeof(MainPage));
00070
00071                 // if our app was previous terminated or wasn't running, check if there were pending progress
00072                 if (e.PreviousExecutionState == ApplicationExecutionState.Terminated || e.PreviousExecutionState == ApplicationExecutionState.NotRunning)
00073                 {
00074                     try
00075                     {
00076                         bool isImportSupported = await PhotoImportManager.IsSupportedAsync();
00077                         if (isImportSupported)
00078                         {
00079                             // Determine if there was an in progress session
00080                             IReadOnlyList<PhotoImportOperation> ops = PhotoImportManager.GetPendingOperations();
00081
00082                             // If there is at least one session and state isn't idle, restore session state
00083
00084                             if (ops != null && ops.Count != 0)
00085                             {
00086                                 var p = rootFrame.Content as MainPage;
00087
00088                                 if (ops.Count > 1)
00089                                 {
00090                                     // If there is more than one operation, since this app handles single
00091                                     // download sessions only, the previous session(s) were not properly
00092                                     // disposed of, do this now.
00093
00094                                     for (int x = 0; x < ops.Count - 1; x++)
00095                                     {
00096                                         ops[x].Session.Dispose();
00097                                     }
00098                                 }
00099
00100                                 // Take the last operation from the list, and if some task was started, navigate to reconnect to the proper stage.
00101
00102                                 p.ImportOperation = ops[ops.Count - 1];
00103
00104                                 if (p.ImportOperation.Stage != PhotoImportStage.NotStarted)
00105                                 {
00106                                     p.NavigateToReconnect();
00107                                 }
00108                                 else
00109                                 {
00110                                     p.ImportOperation.Session.Dispose();
00111                                 }
00112                             }
00113                         }
00114                     }
00115                     catch (Exception ex)
00116                     {
00117                         Debug.WriteLine("Exception: " + ex.Message);
00118                     }
00119                 }
00120
00121                 // Place the frame in the current Window
00122
00123                 Window.Current.Content = rootFrame;
00124             }
00125
00126             if (rootFrame.Content == null)
00127             {
00128                 // When the navigation stack isn't restored navigate to the first page,
00129                 // configuring the new page by passing required information as a navigation
00130                 // parameter
00131                 rootFrame.Navigate(typeof(MainPage), e.Arguments);
00132             }
00133             // Ensure the current window is active
00134             Window.Current.Activate();
00135         }
00136
00137         /// <summary>
00138         /// Invoked when Navigation to a certain page fails
00139         /// </summary>
00140         /// <param name="sender">The Frame which failed navigation</param>
00141         /// <param name="e">Details about the navigation failure</param>
00142         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00143         {
00144             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00145         }
00146
00147         /// <summary>
00148         /// Invoked when application is being suspended.  Application state is saved
00149         /// without knowing whether the application will be terminated or resumed with the contents
00150         /// of memory still intact.
00151         /// </summary>
00152         /// <param name="sender">The source of the suspend request.</param>
00153         /// <param name="e">Details about the suspend request.</param>
00154         private void OnSuspending(object sender, SuspendingEventArgs e)
00155         {
00156             var deferral = e.SuspendingOperation.GetDeferral();
00157             //TODO: Save application state and stop any background activity
00158             deferral.Complete();
00159         }
00160
00161         protected override void OnActivated(IActivatedEventArgs args)
00162         {
00163             // AutoPlay scenario: This app is registered for as a hanlder for WPD\ImageSourceAutoPlay event in the Package.appxmanifest
00164             if (args.Kind == ActivationKind.Device)
00165             {
00166                 Frame rootFrame = null;
00167                 // Ensure that the current page exists and is activated
00168                 if (Window.Current.Content == null)
00169                 {
00170                     rootFrame = new Frame();
00171                     rootFrame.Navigate(typeof(MainPage));
00172                     Window.Current.Content = rootFrame;
00173                 }
00174                 else
00175                 {
00176                     rootFrame = Window.Current.Content as Frame;
00177                 }
00178
00179                 // Reference the current page as type MainPage
00180                  var page = rootFrame.Content as MainPage;
00181
00182                 // Cast the activated event args as DeviceActivatedEventArgs and navigate to scenario1 to preselect the device
00183                 var deviceArgs = args as DeviceActivatedEventArgs;
00184                 page.DeviceEvent = deviceArgs;
00185                 page.NavigateToAutoPlay();
00186
00187                 Window.Current.Activate();
00188             }
00189
00190             base.OnActivated(args);
00191         }
00192     }
00193 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cpp/Scenario6_AppListingURI.xaml.cpp Source File

  • Store
  • cpp

Scenario6_AppListingURI.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario6_AppListingURI.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::Services::Store;
00021 using namespace Windows::UI::Xaml;
00022
00023 Scenario6_AppListingURI::Scenario6_AppListingURI()
00024 {
00025     InitializeComponent();
00026
00027     storeContext = StoreContext::GetDefault();
00028 }
00029
00030 void Scenario6_AppListingURI::DisplayLink(Object^ sender, RoutedEventArgs^ e)
00031 {
00032     create_task(storeContext->GetStoreProductForCurrentAppAsync()).then([this](StoreProductResult^ result)
00033     {
00034         if (result->ExtendedError.Value != S_OK)
00035         {
00036             Utils::ReportExtendedError(result->ExtendedError);
00037             return;
00038         }
00039
00040         Windows::System::Launcher::LaunchUriAsync(result->Product->LinkUri);
00041     });
00042 }
Generated on Fri Nov 15 2024 22:21:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ModemDeviceServices Member List

This is the complete list of members for ModemDeviceServices, including all inherited members.
btnDeviceService_Click(object sender, RoutedEventArgs e) | ModemDeviceServices | [inline, private]
ModemDeviceServices() | ModemDeviceServices | [inline]
rootPage | ModemDeviceServices | [private]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IOnboardingSignals Member List

This is the complete list of members for IOnboardingSignals, including all inherited members.
ConnectionResultReceived IOnboardingSignals
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PasswordVault/cpp/pch.cpp Source File

  • PasswordVault
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Compression/cpp/Scenario3.xaml.cpp Source File

  • Compression
  • cpp

Scenario3.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario3.xaml.cpp
00013 // Implementation of the Scenario3 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario3.xaml.h"
00018 #include "CompressionUtils.h"
00019
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Navigation;
00023 using namespace Windows::UI::ViewManagement;
00024 using namespace Windows::Storage;
00025 using namespace Windows::Storage::Pickers;
00026 using namespace Windows::Storage::Streams;
00027 using namespace Windows::Storage::Compression;
00028
00029 using namespace SDKTemplate::Compression;
00030
00031 using namespace concurrency;
00032
00033 Scenario3::Scenario3()
00034 {
00035     InitializeComponent();
00036 }
00037
00038 /// <summary>
00039 /// Invoked when this page is about to be displayed in a Frame.
00040 /// </summary>
00041 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00042 /// property is typically used to configure the page.</param>
00043 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00044 {
00045     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00046     // as NotifyUser()
00047     rootPage = MainPage::Current;
00048 }
00049
00050 void ::SDKTemplate::Compression::Scenario3::DoScenario(Windows::Storage::Compression::CompressAlgorithm Algorithm)
00051 {
00052     Progress->Text = "";
00053     rootPage->NotifyUser("Working...", NotifyType::StatusMessage);
00054
00055     auto context = std::make_shared<ScenarioContext>();
00056     context->raStream = ref new InMemoryRandomAccessStream();
00057
00058     auto picker = ref new Pickers::FileOpenPicker();
00059     picker->FileTypeFilter->Append("*");
00060
00061     // First pick a test file and open it for reading
00062     create_task(picker->PickSingleFileAsync()).then([=](StorageFile^ OriginalFile)
00063     {
00064         if (!OriginalFile)
00065         {
00066             throw std::runtime_error("No file has been selected");
00067         }
00068
00069         Progress->Text += "File \"" + OriginalFile->Name + "\" has been picked\n";
00070
00071         return OriginalFile->OpenAsync(FileAccessMode::Read);
00072     })
00073
00074     // Then read the whole file into memory buffer
00075     .then([=](IRandomAccessStream^ OriginalStream)
00076     {
00077         return ReadStreamTask(OriginalStream, context->originalData).RunTask();
00078     })
00079
00080     // Then compress data using "classic" Compression API
00081     .then([=](size_t BytesRead)
00082     {
00083         Progress->Text += BytesRead + " bytes have been read from disk\n";
00084
00085         // IMPORTANT:
00086         // Tasks, that are created over IAsyncOperation (and the likes) or descended from them
00087         // have their continuations scheduled to the same ASTA apartment effectively blocking
00088         // the GUI for the length of processing continuation. Create an independent task here
00089         // instead of adding continuation on the upper level task (which descends from
00090         // "apartment-aware" task) so we will not block the GUI (ASTA) thread while compressing.
00091         return task<size_t>([=]
00092         {
00093             // We are by convention the only thread to touch context->compressedData and
00094             // context->decompressedData at this point - no synchronization necessary
00095
00096             COMPRESSOR_HANDLE compressorHandle = nullptr;
00097
00098             try
00099             {
00100                 // Enumaration values of Windows::Storage::Compression::CompressAlgorithm are
00101                 // guaranteed to match values from compressapi.h
00102                 ULONG compressAlgorithm = static_cast<ULONG>(Algorithm);
00103                 SIZE_T compressedDataSize = 0;
00104                 std::vector<byte> compressedData;
00105
00106                 // Compress algorithm should always be explicit for "classic" Compression API
00107                 if (compressAlgorithm == COMPRESS_ALGORITHM_INVALID)
00108                 {
00109                     compressAlgorithm = COMPRESS_ALGORITHM_XPRESS;
00110                 }
00111
00112                 if (!CreateCompressor(compressAlgorithm, nullptr, &compressorHandle))
00113                 {
00114                     throw std::runtime_error("Cannot create compressor");
00115                 }
00116
00117                 if (!Compress(compressorHandle, context->originalData.data(), context->originalData.size(), nullptr, 0, &compressedDataSize) &&
00118                     (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
00119                 {
00120                     throw std::runtime_error("Cannot get decompressed data size");
00121                 }
00122
00123                 compressedData.resize(compressedDataSize);
00124
00125                 if (!Compress(compressorHandle,
00126                                 context->originalData.data(),
00127                                 context->originalData.size(),
00128                                 compressedData.data(),
00129                                 compressedData.size(),
00130                                 &compressedDataSize))
00131                 {
00132                     throw std::runtime_error("Cannot decompress data");
00133                 }
00134                 compressedData.resize(compressedDataSize);
00135
00136                 CloseCompressor(compressorHandle);
00137
00138                 context->compressedData = std::move(compressedData);
00139                 return context->compressedData.size();
00140             }
00141             catch (...)
00142             {
00143                 if (compressorHandle != nullptr)
00144                 {
00145                     CloseDecompressor(compressorHandle);
00146                 }
00147
00148                 throw;
00149             }
00150         });
00151     })
00152
00153     // Then write compressed data into in-memory stream
00154     .then([=](size_t CompressedSize)
00155     {
00156         Progress->Text += "Compressed into " + CompressedSize + " bytes\n";
00157
00158         auto dataWriter = ref new DataWriter(context->raStream);
00159         context->writer = dataWriter;
00160         auto data = ref new Platform::Array<byte>(context->compressedData.data(), (unsigned int)context->compressedData.size());
00161         dataWriter->WriteBytes(data);
00162
00163         return dataWriter->StoreAsync();
00164     })
00165
00166     // Then decompress in-memory stream into vector
00167     .then([=](size_t CompressedSize)
00168     {
00169         auto decompressor = ref new Decompressor(context->raStream->GetInputStreamAt(0));
00170
00171         Progress->Text += "Decompressor object has been created\n";
00172
00173         return ReadStreamTask(decompressor, context->decompressedData).RunTask();
00174     })
00175
00176     // Then verify if any data has been lost in action
00177     .then([=](size_t BytesRead)
00178     {
00179         Progress->Text += BytesRead + " bytes have been decompressed\n";
00180
00181         if (context->decompressedData.size() != BytesRead)
00182         {
00183             throw std::runtime_error("Decompressed data size doesn't match number of bytes read from in-memory stream");
00184         }
00185
00186         if (context->originalData.size() != context->decompressedData.size())
00187         {
00188             throw std::runtime_error("Decompressed data size doesn't match original one");
00189         }
00190
00191         if (!std::equal(context->originalData.begin(), context->originalData.end(), context->decompressedData.begin()))
00192         {
00193             throw std::runtime_error("Decompressed data doesn't match original one");
00194         }
00195
00196         Progress->Text += "Decompressed data matches original\n";
00197     })
00198
00199     // Final task based continuation is used to handle exceptions in the chain above
00200     .then([=](task<void> FinalContinuation)
00201     {
00202         try
00203         {
00204             // Transport all exceptions to this thread. This task is guaranteed to be completed by now.
00205             FinalContinuation.get();
00206
00207             Progress->Text += "All done\n";
00208             rootPage->NotifyUser("Finished", NotifyType::StatusMessage);
00209         }
00210         catch (Platform::Exception ^e)
00211         {
00212             rootPage->NotifyUser(e->Message, NotifyType::ErrorMessage);
00213         }
00214         catch (const std::exception &e)
00215         {
00216             std::wstringstream wss;
00217             wss << e.what();
00218             rootPage->NotifyUser(ref new Platform::String(wss.str().c_str()), NotifyType::ErrorMessage);
00219         }
00220     });
00221 }
00222
00223 void ::SDKTemplate::Compression::Scenario3::CompressFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00224 {
00225     ComboBoxItem^ item = safe_cast<ComboBoxItem^>(CompressAlgorithmComboBox->SelectedItem);
00226
00227     if (item == nullptr)
00228     {
00229         return;
00230     }
00231
00232     CompressAlgorithm Algorithm = (CompressAlgorithm) CompressAlgorithmFromComboBoxItem(item);
00233
00234     if (Algorithm == CompressAlgorithm::InvalidAlgorithm)
00235     {
00236         return;
00237     }
00238
00239     DoScenario(Algorithm);
00240 }
00241
00242 void ::SDKTemplate::Compression::Scenario3::CompressAlgorithmComboBox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00243 {
00244     SelectionChangedEventArgs^ args = safe_cast<SelectionChangedEventArgs^>(e);
00245
00246     if (args == nullptr)
00247     {
00248         return;
00249     }
00250     if (CompressAlgorithmComboBox == nullptr)
00251     {
00252         return;
00253     }
00254
00255     if (args->AddedItems->Size != 0 && args->RemovedItems->Size == 0)
00256     {
00257         ComboBoxItem^ addedItem = safe_cast<ComboBoxItem^>(args->AddedItems->GetAt(0));
00258         if (addedItem->Content->Equals("Default"))
00259         {
00260                 UpdateDescriptionVisibility(addedItem, Windows::UI::Xaml::Visibility::Visible);
00261         }
00262         return;
00263     }
00264     else
00265     {
00266         ComboBoxItem^ addedItem = safe_cast<ComboBoxItem^>(args->AddedItems->GetAt(0));
00267         ComboBoxItem^ removedItem = safe_cast<ComboBoxItem^>(args->RemovedItems->GetAt(0));
00268
00269         UpdateDescriptionVisibility(addedItem, Windows::UI::Xaml::Visibility::Visible);
00270         UpdateDescriptionVisibility(removedItem, Windows::UI::Xaml::Visibility::Collapsed);
00271     }
00272 }
00273
00274 void ::SDKTemplate::Compression::Scenario3::UpdateDescriptionVisibility(ComboBoxItem^ item, Windows::UI::Xaml::Visibility visibility)
00275 {
00276     TextBlock^ textBlock = nullptr;
00277
00278     CompressAlgorithm algorithm = (CompressAlgorithm) CompressAlgorithmFromComboBoxItem(item);
00279     switch (algorithm)
00280     {
00281     case CompressAlgorithm::NullAlgorithm:
00282         textBlock = DefaultTextBlock;
00283         break;
00284     case CompressAlgorithm::Xpress:
00285         textBlock = XpressTextBlock;
00286         break;
00287     case CompressAlgorithm::XpressHuff:
00288         textBlock = XpressHuffTextBlock;
00289         break;
00290     case CompressAlgorithm::Mszip:
00291         textBlock = MszipTextBlock;
00292         break;
00293     case CompressAlgorithm::Lzms:
00294         textBlock = LzmsTextBlock;
00295         break;
00296     default:
00297         return;
00298     }
00299
00300     textBlock->Visibility = visibility;
00301 }
00302
00303 int ::SDKTemplate::Compression::Scenario3::CompressAlgorithmFromComboBoxItem(ComboBoxItem^ item)
00304 {
00305     CompressAlgorithm Algorithm = CompressAlgorithm::NullAlgorithm;
00306
00307     if (item == DefaultComboBoxItem)
00308     {
00309         Algorithm = CompressAlgorithm::NullAlgorithm;
00310     }
00311     else if (item == XpressComboBoxItem)
00312     {
00313         Algorithm = CompressAlgorithm::Xpress;
00314     }
00315     else if (item == XpressHuffComboBoxItem)
00316     {
00317         Algorithm = CompressAlgorithm::XpressHuff;
00318     }
00319     else if (item == MszipComboBoxItem)
00320     {
00321         Algorithm = CompressAlgorithm::Mszip;
00322     }
00323     else if (item == LzmsComboBoxItem)
00324     {
00325         Algorithm = CompressAlgorithm::Lzms;
00326     }
00327     else
00328     {
00329         Algorithm = CompressAlgorithm::InvalidAlgorithm;
00330     }
00331
00332     return (int) Algorithm;
00333 }
Generated on Fri Nov 15 2024 22:18:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInteractionMode/cppwinrt/pch.h Source File

  • UserInteractionMode
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.System.h"
00008 #include "winrt/Windows.UI.Core.h"
00009 #include "winrt/Windows.UI.ViewManagement.h"
00010 #include "winrt/Windows.UI.Xaml.h"
00011 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00012 #include "winrt/Windows.UI.Xaml.Controls.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00014 #include "winrt/Windows.UI.Xaml.Documents.h"
00015 #include "winrt/Windows.UI.Xaml.Interop.h"
00016 #include "winrt/Windows.UI.Xaml.Markup.h"
00017 #include "winrt/Windows.UI.Xaml.Media.h"
00018 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteLineSpacingModes/cpp/DWriteTextLayoutImplementation/TextLayoutImageSource.cpp Source File

  • DWriteLineSpacingModes
  • cpp
  • DWriteTextLayoutImplementation

TextLayoutImageSource.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "TextLayoutImageSource.h"
00014 #include "DirectXHelper.h"
00015
00016 using namespace DWriteTextLayoutImplementation;
00017 using namespace Platform;
00018 using namespace Microsoft::WRL;
00019 using namespace Windows::ApplicationModel;
00020 using namespace Windows::UI::Xaml;
00021
00022
00023 // constructors
00024
00025 TextLayoutImageSource::TextLayoutImageSource(TextLayout^ textLayout) :
00026     TextLayoutImageSource(textLayout, textLayout->Width, textLayout->Height) {}
00027
00028
00029 TextLayoutImageSource::TextLayoutImageSource(TextLayout^ textLayout, uint32 pixelWidth, uint32 pixelHeight) :
00030     SurfaceImageSource(static_cast<int>(pixelWidth), static_cast<int>(pixelHeight)),
00031     m_textLayout(textLayout),
00032     m_pixelWidth(pixelWidth),
00033     m_pixelHeight(pixelHeight)
00034 {
00035     CreateDeviceResources();
00036     m_suspendEventHandlerRegistrationToken = (Application::Current->Suspending += ref new SuspendingEventHandler(this, &TextLayoutImageSource::OnSuspending));
00037 }
00038
00039
00040 TextLayoutImageSource::~TextLayoutImageSource()
00041 {
00042     Application::Current->Suspending -= m_suspendEventHandlerRegistrationToken;
00043 }
00044
00045
00046 // private methods:
00047
00048 void TextLayoutImageSource::CreateDeviceResources()
00049 {
00050     // This flag adds support for surfaces with a different color channel ordering
00051     // than the API default. It is required for compatibility with Direct2D.
00052     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00053
00054 #if defined(_DEBUG)
00055     if (DX::SdkLayersAvailable())
00056     {
00057         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00058         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00059     }
00060 #endif
00061
00062     // This array defines the set of DirectX hardware feature levels this app will support.
00063     // Note the ordering should be preserved.
00064     // Don't forget to declare your application's minimum required feature level in its
00065     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00066     D3D_FEATURE_LEVEL featureLevels[] =
00067     {
00068         D3D_FEATURE_LEVEL_11_1,
00069         D3D_FEATURE_LEVEL_11_0,
00070         D3D_FEATURE_LEVEL_10_1,
00071         D3D_FEATURE_LEVEL_10_0,
00072         D3D_FEATURE_LEVEL_9_3,
00073         D3D_FEATURE_LEVEL_9_2,
00074         D3D_FEATURE_LEVEL_9_1
00075     };
00076
00077     // Create the Direct3D 11 API device object.
00078     D3D_FEATURE_LEVEL supportedFeatureLevel; // We will need this to determine size limits for our SurfaceImageSource.
00079     HRESULT hr = D3D11CreateDevice(
00080         nullptr,                    // Specify nullptr to use the default adapter.
00081         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00082         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00083         creationFlags,              // Set debug and Direct2D compatibility flags.
00084         featureLevels,              // List of feature levels this app can support.
00085         ARRAYSIZE(featureLevels),
00086         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00087         &m_d3dDevice,               // Returns the Direct3D device created.
00088         &supportedFeatureLevel,
00089         nullptr
00090         );
00091
00092     if (FAILED(hr))
00093     {
00094         // If the initialization fails, fall back to the WARP device.
00095         // For more information on WARP, see:
00096         // http://go.microsoft.com/fwlink/?LinkId=286690
00097         DX::ThrowIfFailed(
00098             D3D11CreateDevice(
00099                 nullptr,
00100                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00101                 0,
00102                 creationFlags,
00103                 featureLevels,
00104                 ARRAYSIZE(featureLevels),
00105                 D3D11_SDK_VERSION,
00106                 &m_d3dDevice,
00107                 &supportedFeatureLevel,
00108                 nullptr
00109                 )
00110             );
00111     }
00112
00113     // Get the Direct3D 11.1 API device.
00114     ComPtr<IDXGIDevice> dxgiDevice;
00115     DX::ThrowIfFailed(
00116         m_d3dDevice.As(&dxgiDevice)
00117         );
00118
00119     // Create the Direct2D device object and a corresponding context.
00120     DX::ThrowIfFailed(
00121         D2D1CreateDevice(
00122             dxgiDevice.Get(),
00123             nullptr,
00124             &m_d2dDevice
00125             )
00126         );
00127
00128     DX::ThrowIfFailed(
00129         m_d2dDevice->CreateDeviceContext(
00130             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00131             &m_d2dContext
00132             )
00133         );
00134
00135     // Query for ISurfaceImageSourceNative interface.
00136     ComPtr<ISurfaceImageSourceNative> sisNative;
00137     DX::ThrowIfFailed(
00138         reinterpret_cast<IUnknown*>(this)->QueryInterface(IID_PPV_ARGS(&sisNative))
00139         );
00140
00141     // Associate the DXGI device with the SurfaceImageSource.
00142     DX::ThrowIfFailed(
00143         sisNative->SetDevice(dxgiDevice.Get())
00144         );
00145
00146     // Create D2D brushes.
00147     DX::ThrowIfFailed(
00148         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &m_textBrush)
00149         );
00150
00151     DX::ThrowIfFailed(
00152         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightYellow), &m_textBackgroundBrush)
00153         );
00154
00155     DX::ThrowIfFailed(
00156         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightBlue), &m_textAscentBrush)
00157         );
00158
00159     DX::ThrowIfFailed(
00160         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightPink), &m_textDescentBrush)
00161         );
00162
00163     DX::ThrowIfFailed(
00164         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightGreen), &m_textLineGapBrush)
00165         );
00166
00167     DX::ThrowIfFailed(
00168         m_d2dContext->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &m_boundsBrush)
00169         );
00170
00171     // Create D2D stroke style
00172     ComPtr<ID2D1Factory> d2dFactory;
00173     m_d2dDevice->GetFactory(&d2dFactory);
00174
00175     float const dashes[] = { 2.0f, 2.0f };
00176
00177     auto strokeProperties = D2D1::StrokeStyleProperties(
00178         D2D1_CAP_STYLE_FLAT,
00179         D2D1_CAP_STYLE_FLAT,
00180         D2D1_CAP_STYLE_FLAT,
00181         D2D1_LINE_JOIN_MITER,
00182         1.0f,
00183         D2D1_DASH_STYLE_CUSTOM,
00184         0.0f
00185         );
00186
00187     DX::ThrowIfFailed(
00188         d2dFactory->CreateStrokeStyle(strokeProperties, dashes, ARRAYSIZE(dashes), &m_boundsStrokeStyle)
00189         );
00190 }
00191
00192
00193 void TextLayoutImageSource::Draw()
00194 {
00195     // If the device was lost in one of the steps, an exception will bubble up.
00196     // We'll test for the relevant errors and attempt to recreate the device.
00197     try
00198     {
00199         BeginDraw();
00200         Clear();
00201         DrawLineMetricsDecorations();
00202         DrawText();
00203         EndDraw();
00204     }
00205     catch (Platform::Exception^ e)
00206     {
00207         HRESULT hr = e->HResult;
00208         if (hr == D2DERR_RECREATE_TARGET || hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00209         {
00210             // If the device has been removed or reset, attempt to recreate it and continue drawing.
00211             CreateDeviceResources();
00212             Draw();
00213         }
00214         else
00215         {
00216             // Notify the caller by throwing an exception if any other error was encountered.
00217             // If hit after a recursively re-entering, we won't be making another recursive
00218             // call -- this will bubble back up the call stack.
00219             DX::ThrowIfFailed(hr);
00220         }
00221     }
00222 }
00223
00224
00225 void TextLayoutImageSource::BeginDraw()
00226 {
00227     BeginDraw(Windows::Foundation::Rect(0.0f, 0.0f, static_cast<float>(m_pixelWidth), static_cast<float>(m_pixelHeight)));
00228 }
00229
00230
00231 void TextLayoutImageSource::BeginDraw(Windows::Foundation::Rect updateRect)
00232 {
00233     // Assumed: the caller knows not to use SurfaceImageSource to draw content
00234     // that might exceed the available maximum texture dimensions of the device.
00235     // If that is a possibility, then VirutalSurfaceImageSource should be used
00236     // instead. For more information on maxiumum texture dimensions, see:
00237     // https://msdn.microsoft.com/en-us/library/windows/desktop/ff476876
00238     //
00239     // For information on VirtualSurfaceImageSource versus SurfaceImageSource, see
00240     // https://msdn.microsoft.com/en-us/library/windows/apps/hh825871
00241
00242     POINT offset;
00243     ComPtr<IDXGISurface> surface;
00244
00245     // Express target area as a native RECT type.
00246     RECT updateRectNative;
00247     updateRectNative.left = static_cast<LONG>(updateRect.Left);
00248     updateRectNative.top = static_cast<LONG>(updateRect.Top);
00249     updateRectNative.right = static_cast<LONG>(updateRect.Right);
00250     updateRectNative.bottom = static_cast<LONG>(updateRect.Bottom);
00251
00252     // Query for ISurfaceImageSourceNative interface.
00253     ComPtr<ISurfaceImageSourceNative> sisNative;
00254     DX::ThrowIfFailed(
00255         reinterpret_cast<IUnknown*>(this)->QueryInterface(IID_PPV_ARGS(&sisNative))
00256         );
00257
00258     // Begin drawing - returns a target surface and an offset to use as the top left origin when drawing.
00259     DX::ThrowIfFailed(
00260         sisNative->BeginDraw(updateRectNative, &surface, &offset)
00261         );
00262
00263     // Create render target.
00264     ComPtr<ID2D1Bitmap1> bitmap;
00265     DX::ThrowIfFailed(
00266         m_d2dContext->CreateBitmapFromDxgiSurface(
00267             surface.Get(),
00268             nullptr,
00269             &bitmap
00270             )
00271         );
00272
00273     // Set context's render target.
00274     m_d2dContext->SetTarget(bitmap.Get());
00275
00276     // Begin drawing using D2D context.
00277     m_d2dContext->BeginDraw();
00278
00279     // Apply a clip and transform to constrain updates to the target update area.
00280     // This is required to ensure coordinates within the target surface remain
00281     // consistent by taking into account the offset returned by BeginDraw, and
00282     // can also improve performance by optimizing the area that is drawn by D2D.
00283     // Apps should always account for the offset output parameter returned by
00284     // BeginDraw, since it may not match the passed updateRect input parameter's location.
00285     m_d2dContext->PushAxisAlignedClip(
00286         D2D1::RectF(
00287             static_cast<float>(offset.x),
00288             static_cast<float>(offset.y),
00289             static_cast<float>(offset.x + updateRect.Width),
00290             static_cast<float>(offset.y + updateRect.Height)
00291             ),
00292         D2D1_ANTIALIAS_MODE_ALIASED
00293         );
00294
00295     m_d2dContext->SetTransform(
00296         D2D1::Matrix3x2F::Translation(
00297             static_cast<float>(offset.x),
00298             static_cast<float>(offset.y)
00299             )
00300         );
00301 }
00302
00303
00304 void TextLayoutImageSource::EndDraw()
00305 {
00306     // Remove the transform and clip applied in BeginDraw since
00307     // the target area can change on every update.
00308     m_d2dContext->SetTransform(D2D1::IdentityMatrix());
00309     m_d2dContext->PopAxisAlignedClip();
00310
00311     // Remove the render target and end drawing.
00312     m_d2dContext->SetTarget(nullptr);
00313     DX::ThrowIfFailed(
00314         m_d2dContext->EndDraw()
00315         );
00316
00317     // Query for ISurfaceImageSourceNative interface.
00318     Microsoft::WRL::ComPtr<ISurfaceImageSourceNative> sisNative;
00319     DX::ThrowIfFailed(
00320         reinterpret_cast<IUnknown*>(this)->QueryInterface(IID_PPV_ARGS(&sisNative))
00321         );
00322
00323     DX::ThrowIfFailed(
00324         sisNative->EndDraw()
00325         );
00326 }
00327
00328
00329 void TextLayoutImageSource::Clear()
00330 {
00331     m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::White));
00332 }
00333
00334
00335 void TextLayoutImageSource::DrawText()
00336 {
00337     // The underlying IDWriteTextLayout from the TextLayout object will be needed
00338     // to interact with D2D.
00339     Microsoft::WRL::ComPtr<IDWriteTextLayout> dwriteTextLayout = m_textLayout->GetDWriteTextLayout();
00340
00341     m_d2dContext->DrawTextLayout(D2D1::Point2F(), dwriteTextLayout.Get(), m_textBrush.Get());
00342 }
00343
00344
00345 void TextLayoutImageSource::DrawLineMetricsDecorations()
00346 {
00347     // Decorations will be drawn to indicate the metrics of each line in the text layout.
00348
00349     // Start by filling a background color.
00350     float right = static_cast<float>(m_textLayout->Width);
00351     DWRITE_TEXT_METRICS textMetrics = m_textLayout->GetTextMetrics();
00352
00353     m_d2dContext->FillRectangle(
00354         D2D1::RectF(0.0f, 0.0f, right, textMetrics.height),
00355         m_textBackgroundBrush.Get()
00356         );
00357
00358     // Get the line metrics.
00359     std::vector<DWRITE_LINE_METRICS1> lineMetrics = m_textLayout->GetLineMetrics();
00360     uint32 lineCount = static_cast<uint32>(lineMetrics.size());
00361
00362     float y = 0;
00363
00364     for (uint32 i = 0; i < lineCount; ++i)
00365     {
00366         // Get the line metrics structure for the current line.
00367         auto& line = lineMetrics[i];
00368
00369         // Calculate distances relative to the top of the text layout.
00370         float topOfLine = y + line.leadingBefore;
00371         float baseline = y + line.baseline;
00372         float bottomOfLine = y + line.height - line.leadingAfter;
00373
00374         // Draw different colored backgrounds to indicate the ascent
00375         // and descent distances.
00376         if (baseline < bottomOfLine)
00377         {
00378             m_d2dContext->FillRectangle(D2D1::RectF(0, topOfLine, right, baseline), m_textAscentBrush.Get());
00379             m_d2dContext->FillRectangle(D2D1::RectF(0, baseline, right, bottomOfLine), m_textDescentBrush.Get());
00380         }
00381         else
00382         {
00383             // The baseline distance is greater than the line height. This
00384             // means that a portion of the line will be drawn outside the
00385             // nominal extent of the line. When uniform spacing is used,
00386             // this will occur if the baseline that was specified is
00387             // greater than the specified height. When proportional spacing
00388             // is used, this will occur if the baseline that was specified
00389             // is greater than 1.0.
00390             m_d2dContext->FillRectangle(D2D1::RectF(0, topOfLine, right, bottomOfLine), m_textAscentBrush.Get());
00391         }
00392
00393         // Draw a bounding line above the current text line.
00394         m_d2dContext->DrawLine(D2D1::Point2F(0, y), D2D1::Point2F(right, y), m_boundsBrush.Get(), 1.0f, m_boundsStrokeStyle.Get());
00395
00396         y += line.height;
00397     }
00398
00399     // Draw a bounding line after the last text line.
00400     m_d2dContext->DrawLine(D2D1::Point2F(0, y), D2D1::Point2F(right, y), m_boundsBrush.Get(), 1.0f, m_boundsStrokeStyle.Get());
00401
00402 }
00403
00404
00405 // event handlers
00406
00407 void TextLayoutImageSource::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00408 {
00409     // Hint to the display driver that the app is entering an idle state and that its
00410     // memory can be used temporarily for other apps.
00411
00412     ComPtr<IDXGIDevice3> dxgiDevice;
00413     m_d3dDevice.As(&dxgiDevice);
00414     dxgiDevice->Trim();
00415 }
Generated on Fri Nov 15 2024 22:19:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/DeviceState.h Source File

  • WindowsAudioSession
  • cppwinrt

DeviceState.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012 #include "DeviceStateChangedEventArgs.g.h"
00013
00014 namespace winrt::SDKTemplate::implementation
00015 {
00016     struct DeviceStateChangedEventArgs : DeviceStateChangedEventArgsT<DeviceStateChangedEventArgs>
00017     {
00018         DeviceStateChangedEventArgs(enum DeviceState deviceState, hresult error) : m_deviceState(deviceState), m_error(error) {}
00019
00020         enum DeviceState DeviceState() { return m_deviceState; }
00021         hresult ExtendedError() { return m_error; }
00022
00023     private:
00024         enum DeviceState const m_deviceState;
00025         hresult const m_error;
00026     };
00027
00028     template<typename D>
00029     struct DeviceStateSourceT
00030     {
00031         DeviceState DeviceState() { return m_deviceState; }
00032
00033         event_token DeviceStateChanged(Windows::Foundation::TypedEventHandler<IDeviceStateSource, SDKTemplate::DeviceStateChangedEventArgs> const& handler)
00034         {
00035             return m_deviceStateChanged.add(handler);
00036         }
00037         void DeviceStateChanged(event_token token)
00038         {
00039             return m_deviceStateChanged.remove(token);
00040         }
00041
00042     protected:
00043         enum DeviceState m_deviceState = DeviceState::Uninitialized;
00044         event<Windows::Foundation::TypedEventHandler<IDeviceStateSource, SDKTemplate::DeviceStateChangedEventArgs>> m_deviceStateChanged;
00045
00046         void SetState(enum DeviceState state, HRESULT error = S_OK)
00047         {
00048             if (m_deviceState != state)
00049             {
00050                 m_deviceState = state;
00051                 m_deviceStateChanged(*static_cast<D*>(this), make<implementation::DeviceStateChangedEventArgs>(state, error));
00052             }
00053         }
00054
00055         void SetStateNoNotify(enum DeviceState state)
00056         {
00057             m_deviceState = state;
00058         }
00059     };
00060 }
00061
Generated on Fri Nov 15 2024 22:22:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cpp/SampleConfiguration.h Source File

  • Store
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <collection.h>
00015
00016 namespace SDKTemplate
00017 {
00018     partial ref class ItemDetails;
00019
00020     public value struct Scenario
00021     {
00022         Platform::String^ Title;
00023         Platform::String^ ClassName;
00024     };
00025
00026     partial ref class MainPage
00027     {
00028     public:
00029         static property Platform::String^ FEATURE_NAME
00030         {
00031             Platform::String^ get()
00032             {
00033                 return "Store C++ Sample";
00034             }
00035         }
00036
00037         static property Platform::Array<Scenario>^ scenarios
00038         {
00039             Platform::Array<Scenario>^ get()
00040             {
00041                 return scenariosInner;
00042             }
00043         }
00044
00045     private:
00046         static Platform::Array<Scenario>^ scenariosInner;
00047     };
00048
00049     namespace Utils
00050     {
00051         int64_t DaysUntil(Windows::Foundation::DateTime endDate);
00052
00053         Platform::Collections::Vector<ItemDetails^>^
00054             CreateProductListFromQueryResult(Windows::Services::Store::StoreProductQueryResult^ addOns, Platform::String^ description);
00055
00056         void ReportExtendedError(Windows::Foundation::HResult extendedError);
00057     };
00058
00059     // Helper functions for binding.
00060     public ref class BindingUtils sealed
00061     {
00062     public:
00063         static bool IsNonNull(Platform::Object^ o);
00064     };
00065 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LineSegment Member List

This is the complete list of members for LineSegment, including all inherited members.
length | LineSegment
position | LineSegment
uLength | LineSegment
uStart | LineSegment
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CalibrationBar Member List

This is the complete list of members for CalibrationBar, including all inherited members.
_barDismissed | CalibrationBar | [private]
_calibrationTimer | CalibrationBar | [private]
_lastCalibrationTime | CalibrationBar | [private]
CALIBRATION_POPUP_AUTO_DIMSMISS_TIME | CalibrationBar | [private]
CalibrationBar() | CalibrationBar | [inline]
CalibrationBar() | CalibrationBar | [inline]
CanShowCalibrationBar(MagnetometerAccuracy accuracy) | CalibrationBar | [inline, private]
CanShowCalibrationBar(MagnetometerAccuracy accuracy) | CalibrationBar | [inline, private]
DismissPopup_Click(object sender, RoutedEventArgs e) | CalibrationBar | [inline, private]
DismissPopup_Click(object sender, RoutedEventArgs e) | CalibrationBar | [inline, private]
Hide() | CalibrationBar | [inline]
Hide() | CalibrationBar | [inline]
HideGuidance() | CalibrationBar | [inline, private]
HideGuidance() | CalibrationBar | [inline, private]
HideGuidanceButton_Click(object sender, RoutedEventArgs e) | CalibrationBar | [inline, private]
HideGuidanceButton_Click(object sender, RoutedEventArgs e) | CalibrationBar | [inline, private]
InvalidateLayout() | CalibrationBar | [inline, private]
InvalidateLayout() | CalibrationBar | [inline, private]
LAYOUT_WIDTH_768 | CalibrationBar | [private]
OnAutoDismissTimerExpired(object sender, object e) | CalibrationBar | [inline, private]
OnAutoDismissTimerExpired(object sender, object e) | CalibrationBar | [inline, private]
OnWindowSizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e) | CalibrationBar | [inline, private]
OnWindowSizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e) | CalibrationBar | [inline, private]
RequestCalibration(MagnetometerAccuracy accuracy) | CalibrationBar | [inline]
RequestCalibration(MagnetometerAccuracy accuracy) | CalibrationBar | [inline]
ShowGuidance() | CalibrationBar | [inline, private]
ShowGuidance() | CalibrationBar | [inline, private]
ShowGuidanceButton_Click(object sender, RoutedEventArgs e) | CalibrationBar | [inline, private]
ShowGuidanceButton_Click(object sender, RoutedEventArgs e) | CalibrationBar | [inline, private]
SUPPRESS_DURATION_APPROXIMATE_MIN | CalibrationBar | [private]
SUPPRESS_DURATION_UNRELIABLE_MIN | CalibrationBar | [private]
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ManageCardScenario Member List

This is the complete list of members for ManageCardScenario, including all inherited members.
btnDebugLog_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | ManageCardScenario | [inline, private]
btnDisableCard_Click(object sender, RoutedEventArgs e) | ManageCardScenario | [inline, private]
btnEnableCard_Click(object sender, RoutedEventArgs e) | ManageCardScenario | [inline, private]
btnForegroundOverrideCard_Click(object sender, RoutedEventArgs e) | ManageCardScenario | [inline, private]
btnRegisterBgTask_Click(object sender, RoutedEventArgs e) | ManageCardScenario | [inline, private]
btnRegisterSamplePaymentCard_Click(object sender, RoutedEventArgs e) | ManageCardScenario | [inline, private]
btnUnregisterCard_Click(object sender, RoutedEventArgs e) | ManageCardScenario | [inline, private]
chkDenyIfPhoneLocked_Checked(object sender, RoutedEventArgs e) | ManageCardScenario | [inline, private]
chkDenyIfPhoneLocked_Unchecked(object sender, RoutedEventArgs e) | ManageCardScenario | [inline, private]
chkLaunchAboveLock_Checked(object sender, RoutedEventArgs e) | ManageCardScenario | [inline, private]
chkLaunchAboveLock_Unchecked(object sender, RoutedEventArgs e) | ManageCardScenario | [inline, private]
isHceSupported | ManageCardScenario | [private]
lstCards_SelectionChanged(object sender, SelectionChangedEventArgs e) | ManageCardScenario | [inline, private]
ManageCardScenario() | ManageCardScenario | [inline]
OnNavigatedTo(NavigationEventArgs e) | ManageCardScenario | [inline, protected]
rootPage | ManageCardScenario | [private]
ShowDialog(string msg) | ManageCardScenario | [inline, private]
Window_VisibilityChanged(object sender, VisibilityChangedEventArgs e) | ManageCardScenario | [inline, private]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/pch.cpp Source File

  • ShareSource
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario8.xaml.cpp Source File

  • MapControl
  • cpp

Scenario8.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario8.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Concurrency;
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Services::Maps::OfflineMaps;
00020 using namespace Windows::UI::Core;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Maps;
00024
00025 Scenario8::Scenario8()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 void Scenario8::myMap_Loaded(Object^ sender, RoutedEventArgs^ e)
00031 {
00032     myMap->Center = MainPage::SeattleGeopoint;
00033     myMap->ZoomLevel = 12;
00034 }
00035
00036 void Scenario8::findAtCenterButton_Click(Object^ sender, RoutedEventArgs^ e)
00037 {
00038     resultsGrid->Children->Clear();
00039     resultsGrid->RowDefinitions->Clear();
00040     resultStatusTextBlock->Text = "";
00041
00042     // finds all available Offline Map packages at the map center geopoint
00043     create_task(OfflineMapPackage::FindPackagesAsync(myMap->Center))
00044         .then([this](OfflineMapPackageQueryResult^ result)
00045     {
00046         if (result->Status != OfflineMapPackageQueryStatus::Success)
00047         {
00048             resultStatusTextBlock->Text = "Error: " + result->Status.ToString();
00049         }
00050         else if (result->Packages->Size == 0)
00051         {
00052             resultStatusTextBlock->Text = "No maps found";
00053         }
00054         else
00055         {
00056             for (OfflineMapPackage^ package : result->Packages)
00057             {
00058                 addToResultGrid(package);
00059             }
00060         }
00061     });
00062 }
00063
00064 void Scenario8::addToResultGrid(OfflineMapPackage^ package)
00065 {
00066     // a descriptive name for the package
00067     // ex: "Washington, USA (160 MB)"
00068     String^ descriptiveName =
00069         package->DisplayName + ", " +
00070         package->EnclosingRegionName +
00071         " (" + nearestMegabyte(package->EstimatedSizeInBytes) + " MB)";
00072
00073     // current download status (Downloaded, NotDownloaded, Downloading, etc)
00074     String^ downloadStatus = package->Status.ToString();
00075
00076     TextBlock^ packageNameTextBlock = ref new TextBlock();
00077     packageNameTextBlock->Text = descriptiveName;
00078     packageNameTextBlock->Margin = Thickness(5);
00079     packageNameTextBlock->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Center;
00080
00081     TextBlock^ packageStatusTextBlock = ref new TextBlock();
00082     packageStatusTextBlock->Text = downloadStatus;
00083     packageStatusTextBlock->Margin = Thickness(5);
00084     packageStatusTextBlock->VerticalAlignment = Windows::UI::Xaml::VerticalAlignment::Center;
00085
00086     Button^ packageDownloadButton = ref new Button();
00087     packageDownloadButton->Content = "Download";
00088     packageDownloadButton->IsEnabled = canDownload(package);
00089
00090     // click event handler for Download button
00091     packageDownloadButton->Click += ref new RoutedEventHandler(
00092         [package, packageStatusTextBlock](Object^ sender, RoutedEventArgs^ args)
00093     {
00094         // queue up the package for download
00095         // requires offlineMapsManagement capability (see Package.appxmanifest)
00096         create_task(package->RequestStartDownloadAsync())
00097             .then([packageStatusTextBlock](OfflineMapPackageStartDownloadResult^ result)
00098         {
00099             // show any error
00100             if (result->Status != OfflineMapPackageStartDownloadStatus::Success)
00101             {
00102                 packageStatusTextBlock->Text = result->Status.ToString();
00103             }
00104         });
00105     });
00106
00107     // listen for package status changes
00108     package->StatusChanged += ref new TypedEventHandler<OfflineMapPackage ^, Platform::Object ^>(
00109         [package, packageStatusTextBlock, packageDownloadButton](OfflineMapPackage^ sender, Platform::Object^ args)
00110     {
00111         // event might not be on the UI thread, so marshal if we need to update UI
00112         packageStatusTextBlock->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler(
00113             [package, packageStatusTextBlock, packageDownloadButton]()
00114         {
00115             // update the UI (download status, download button enable/disable)
00116             packageStatusTextBlock->Text = package->Status.ToString();
00117             packageDownloadButton->IsEnabled = canDownload(package);
00118         }));
00119     });
00120
00121     Grid::SetRow(packageNameTextBlock, resultsGrid->RowDefinitions->Size);
00122     Grid::SetColumn(packageNameTextBlock, 0);
00123
00124     Grid::SetRow(packageStatusTextBlock, resultsGrid->RowDefinitions->Size);
00125     Grid::SetColumn(packageStatusTextBlock, 1);
00126
00127     Grid::SetRow(packageDownloadButton, resultsGrid->RowDefinitions->Size);
00128     Grid::SetColumn(packageDownloadButton, 2);
00129
00130     RowDefinition^ rowDef = ref new RowDefinition();
00131     rowDef->Height = GridLength::Auto;
00132     resultsGrid->RowDefinitions->Append(rowDef);
00133
00134     resultsGrid->Children->Append(packageNameTextBlock);
00135     resultsGrid->Children->Append(packageStatusTextBlock);
00136     resultsGrid->Children->Append(packageDownloadButton);
00137 }
00138
00139 unsigned long long Scenario8::nearestMegabyte(unsigned long long bytes)
00140 {
00141     return (unsigned long long)round(bytes / (1024.0 * 1024.0));
00142 }
00143
00144 bool Scenario8::canDownload(OfflineMapPackage^ package)
00145 {
00146     // we can start a download if the package isn't downloaded or it's currently being deleted
00147     return package->Status == OfflineMapPackageStatus::NotDownloaded || package->Status == OfflineMapPackageStatus::Deleting;
00148 }
Generated on Fri Nov 15 2024 22:18:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SpinningCubeRenderer Member List

This is the complete list of members for SpinningCubeRenderer, including all inherited members.
c_lerpRate | SpinningCubeRenderer | [private]
CreateDeviceDependentResourcesAsync() override | SpinningCubeRenderer | [virtual]
GetPosition() const | SpinningCubeRenderer | [inline]
GetVelocity() const | SpinningCubeRenderer | [inline]
m_degreesPerSecond | SpinningCubeRenderer | [private]
m_deviceResources | Resource | [protected]
m_geometryShader | SpinningCubeRenderer | [private]
m_indexBuffer | SpinningCubeRenderer | [private]
m_indexCount | SpinningCubeRenderer | [private]
m_inputLayout | SpinningCubeRenderer | [private]
m_modelConstantBuffer | SpinningCubeRenderer | [private]
m_modelConstantBufferData | SpinningCubeRenderer | [private]
m_pixelShader | SpinningCubeRenderer | [private]
m_position | SpinningCubeRenderer | [private]
m_targetPosition | SpinningCubeRenderer | [private]
m_usingVprtShaders | SpinningCubeRenderer | [private]
m_velocity | SpinningCubeRenderer | [private]
m_vertexBuffer | SpinningCubeRenderer | [private]
m_vertexShader | SpinningCubeRenderer | [private]
ReleaseDeviceDependentResources() override | SpinningCubeRenderer | [virtual]
Render() | SpinningCubeRenderer |
Resource(std::shared_ptr< DeviceResources > deviceResources) | Resource | [inline]
SetTargetPosition(Windows::Foundation::Numerics::float3 pos) | SpinningCubeRenderer | [inline]
SpinningCubeRenderer(std::shared_ptr< DX::DeviceResources > deviceResources) | SpinningCubeRenderer |
Update(const DX::StepTimer &timer) | SpinningCubeRenderer |
~Resource() | Resource | [virtual]
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cpp/pch.cpp Source File

  • Playlists
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_UsingWindows Member List

This is the complete list of members for Scenario3_UsingWindows, including all inherited members.
CanCreateNewWindow(ObservableCollection< WindowInfo > windowsList) | Scenario3_UsingWindows |
CanDestroyWindow(object item) | Scenario3_UsingWindows |
DestroyWindowButton_Click(object sender, RoutedEventArgs e) | Scenario3_UsingWindows | [inline, private]
DisplayTextButton_Click(object sender, RoutedEventArgs e) | Scenario3_UsingWindows | [inline, private]
InitializeAsync() | Scenario3_UsingWindows | [inline, private]
IsNonNull(object item) | Scenario3_UsingWindows |
lineDisplay | Scenario3_UsingWindows | [private]
maxWindows | Scenario3_UsingWindows | [private]
NewWindowButton_Click(object sender, RoutedEventArgs e) | Scenario3_UsingWindows | [inline, private]
nextWindowId | Scenario3_UsingWindows | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario3_UsingWindows | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_UsingWindows | [inline, protected]
RefreshWindowButton_Click(object sender, RoutedEventArgs e) | Scenario3_UsingWindows | [inline, private]
rootPage | Scenario3_UsingWindows | [private]
Scenario3_UsingWindows() | Scenario3_UsingWindows | [inline]
WindowList | Scenario3_UsingWindows |
Generated on Fri Nov 15 2024 22:23:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LowLatency Member List

This is the complete list of members for LowLatency, including all inherited members.
CleanupAsync() | LowLatency | [inline, private]
currentState | LowLatency | [private]
defaultMode | LowLatency | [private]
device | LowLatency | [private]
Device_CaptureFailed(object sender, MediaCaptureFailedEventArgs e) | LowLatency | [inline, private]
Device_IncomingConnectionArrived(object sender, IncomingConnectionEventArgs e) | LowLatency | [inline, private]
HiddenVideo | LowLatency | [private]
InitializeAsync() | LowLatency | [inline, private]
LatencyMode enum name | LowLatency | [private]
LatencyModeToggle_Toggled(object sender, RoutedEventArgs e) | LowLatency | [inline, private]
LocalhostVideo | LowLatency | [private]
LoopbackClientButton_Click(object sender, RoutedEventArgs e) | LowLatency | [inline, private]
LowLatency() | LowLatency | [inline]
mode | LowLatency | [private]
OnNavigatedTo(NavigationEventArgs e) | LowLatency | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | LowLatency | [inline, protected]
PreviewButton_Click(object sender, RoutedEventArgs e) | LowLatency | [inline, private]
previewEncodingProperties | LowLatency | [private]
Previewing_PreviewButtonClicked() | LowLatency | [inline, private]
PreviewSetupCompleted() | LowLatency | [inline, private]
previousState | LowLatency | [private]
rootPage | LowLatency | [private]
StartRecordingToCustomSink() | LowLatency | [inline, private]
State enum name | LowLatency | [private]
Streaming_PreviewButtonClicked() | LowLatency | [inline, private]
Waiting_PreviewButtonClicked() | LowLatency | [inline, private]
Window_VisibilityChanged(object sender, Windows.UI.Core.VisibilityChangedEventArgs e) | LowLatency | [inline, private]
Generated on Fri Nov 15 2024 22:24:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/Scenario4.h Source File

  • FileAccess
  • cppwinrt

Scenario4.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     /// <summary>
00020     /// Writing and reading bytes in a file.
00021     /// </summary>
00022     struct Scenario4 : Scenario4T<Scenario4>
00023     {
00024         Scenario4();
00025
00026         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00027         fire_and_forget WriteBytesButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00028         fire_and_forget ReadBytesButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00029
00030     private:
00031         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00032     };
00033 }
00034
00035 namespace winrt::SDKTemplate::factory_implementation
00036 {
00037     struct Scenario4 : Scenario4T<Scenario4, implementation::Scenario4>
00038     {
00039     };
00040 }
Generated on Fri Nov 15 2024 22:19:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProximitySensor/cs/Tasks/ProximitySensorBackgroundTask.cs Source File

  • ProximitySensor
  • cs
  • Tasks

ProximitySensorBackgroundTask.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Diagnostics;
00014 using Windows.ApplicationModel.Background;
00015 using Windows.Devices.Sensors;
00016 using Windows.Storage;
00017
00018 namespace Tasks
00019 {
00020     public sealed class ProximitySensorBackgroundTask : IBackgroundTask
00021     {
00022         /// <summary>
00023         /// The entry point of a background task.
00024         /// </summary>
00025         /// <param name="taskInstance">The current background task instance.</param>
00026         public void Run(IBackgroundTaskInstance taskInstance)
00027         {
00028             Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");
00029
00030             // Associate a cancellation handler with the background task.
00031             // Even though this task isn't performing much work, it can still be canceled.
00032             taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
00033
00034             // Read the sensor readings from the trigger reports
00035             SensorDataThresholdTriggerDetails triggerDetails = taskInstance.TriggerDetails as SensorDataThresholdTriggerDetails;
00036             // Ensure the type of trigger we are dealing with is of type 'ProximitySensor'
00037             if (SensorType.ProximitySensor == triggerDetails.SensorType)
00038             {
00039                 var reports = ProximitySensor.GetReadingsFromTriggerDetails(triggerDetails);
00040                 var settings = ApplicationData.Current.LocalSettings;
00041                 var lastReading = reports[reports.Count - 1];
00042
00043                 // cache appropriate details from this trigger in application data
00044                 settings.Values["ReportCount"] = reports.Count.ToString();
00045                 settings.Values["LastTimestamp"] = lastReading.Timestamp.ToString("u");
00046                 settings.Values["Detected"] = lastReading.IsDetected.ToString();
00047                 settings.Values["TaskStatus"] = "Completed at " + DateTime.Now.ToString("u");
00048             }
00049
00050             // No deferral is held on taskInstance because we are returning immediately.
00051         }
00052
00053         /// <summary>
00054         /// Handles background task cancellation.
00055         /// </summary>
00056         /// <param name="sender">The background task instance being cancelled.</param>
00057         /// <param name="reason">The cancellation reason.</param>
00058         private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
00059         {
00060             var settings = ApplicationData.Current.LocalSettings;
00061             Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested...");
00062             settings.Values["TaskStatus"] = reason.ToString() + " at " + DateTime.Now.ToString("u");
00063         }
00064     }
00065 }
Generated on Fri Nov 15 2024 22:21:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/Common/PersistentState.h Source File

  • Simple3DGameXaml
  • cpp
  • Common

PersistentState.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 // A simple helper class that provides support for saving and loading various
00011 // data types to an IPropertySet. Used by DirectX SDK samples to implement
00012 // process lifetime management (PLM).
00013 ref class PersistentState
00014 {
00015 internal:
00016     void Initialize(
00017         _In_ Windows::Foundation::Collections::IPropertySet^ settingsValues,
00018         _In_ Platform::String^ key
00019         );
00020
00021     void SaveBool(Platform::String^ key, bool value);
00022     void SaveInt32(Platform::String^ key, int value);
00023     void SaveSingle(Platform::String^ key, float value);
00024     void SaveXMFLOAT3(Platform::String^ key, DirectX::XMFLOAT3 value);
00025     void SaveString(Platform::String^ key, Platform::String^ string);
00026
00027     bool LoadBool(Platform::String^ key, bool defaultValue);
00028     int  LoadInt32(Platform::String^ key, int defaultValue);
00029     float LoadSingle(Platform::String^ key, float defaultValue);
00030     DirectX::XMFLOAT3 LoadXMFLOAT3(Platform::String^ key, DirectX::XMFLOAT3 defaultValue);
00031     Platform::String^ LoadString(Platform::String^ key, Platform::String^ defaultValue);
00032
00033 private:
00034     Platform::String^ m_keyName;
00035     Windows::Foundation::Collections::IPropertySet^ m_settingsValues;
00036 };
Generated on Fri Nov 15 2024 22:21:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
App() | sealed |
Initialize(Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
Load(Platform::String^entryPoint) | sealed | [virtual]
m_deviceResources | sealed | [private]
m_main | sealed | [private]
m_windowClosed | sealed | [private]
m_windowVisible | sealed | [private]
OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | sealed | [protected]
OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnDpiChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnPointerPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::PointerEventArgs^args) | sealed | [protected]
OnResuming(Platform::Object^sender, Platform::Object^args) | sealed | [protected]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [protected]
OnVisibilityChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::VisibilityChangedEventArgs^args) | sealed | [protected]
OnWindowClosed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::CoreWindowEventArgs^args) | sealed | [protected]
OnWindowSizeChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::WindowSizeChangedEventArgs^args) | sealed | [protected]
Run() | sealed | [virtual]
SetWindow(Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
Uninitialize() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/Scenario2.xaml.cpp Source File

  • WindowsAudioSession
  • cpp

Scenario2.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario2.xaml.cpp
00013 // Implementation of the Scenario2 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario2.xaml.h"
00018 #include <ppl.h>
00019 using namespace concurrency;
00020
00021 using namespace SDKSample;
00022 using namespace SDKSample::WASAPIAudio;
00023
00024 using namespace Platform;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Media;
00027 using namespace Windows::Storage;
00028 using namespace Windows::UI::Core;
00029 using namespace Windows::UI::Xaml;
00030 using namespace Windows::UI::Xaml::Controls;
00031 using namespace Windows::UI::Xaml::Navigation;
00032
00033
00034 Scenario2::Scenario2() :
00035  m_IsMFLoaded(false),
00036  m_ContentStream(nullptr),
00037  m_StateChangedEvent(nullptr),
00038  m_spRenderer(nullptr),
00039  m_ContentType(ContentType::ContentTypeTone)
00040 {
00041  InitializeComponent();
00042
00043  // Initialize MF
00044  HRESULT hr = MFStartup(MF_VERSION, MFSTARTUP_LITE);
00045  if (SUCCEEDED(hr))
00046  {
00047   m_IsMFLoaded = true;
00048  }
00049  else
00050  {
00051   ThrowIfFailed(hr);
00052  }
00053
00054  m_CoreDispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
00055
00056  // Register for Media Transport controls.  This is required to support background
00057  // audio scenarios.
00058  m_SystemMediaControls = SystemMediaTransportControls::GetForCurrentView();
00059  m_SystemMediaControlsButtonToken = m_SystemMediaControls->ButtonPressed += ref new TypedEventHandler<SystemMediaTransportControls^, SystemMediaTransportControlsButtonPressedEventArgs^>(this, &Scenario2::MediaButtonPressed);
00060  m_SystemMediaControls->IsPlayEnabled = true;
00061  m_SystemMediaControls->IsPauseEnabled = true;
00062  m_SystemMediaControls->IsStopEnabled = true;
00063
00064  // Get a string representing the Default Audio Render Device
00065  String^ deviceId = Windows::Media::Devices::MediaDevice::GetDefaultAudioRenderId(Windows::Media::Devices::AudioDeviceRole::Default);
00066
00067  // The string is empty if there is no such device.
00068  if (deviceId->IsEmpty())
00069  {
00070   ShowStatusMessage(L"No audio devices available", NotifyType::StatusMessage);
00071   return;
00072  }
00073
00074  auto PropertiesToRetrieve = ref new Platform::Collections::Vector<String^>();
00075  PropertiesToRetrieve->Append("System.Devices.AudioDevice.RawProcessingSupported");
00076  // read property store to see if the device supports a RAW processing mode
00077  create_task(Windows::Devices::Enumeration::DeviceInformation::CreateFromIdAsync(deviceId, PropertiesToRetrieve)).then([this] (Windows::Devices::Enumeration::DeviceInformation^ deviceInformation)
00078  {
00079   auto obj = deviceInformation->Properties->Lookup("System.Devices.AudioDevice.RawProcessingSupported");
00080   this->m_deviceSupportsRawMode = false;
00081   if (obj)
00082   {
00083    this->m_deviceSupportsRawMode = obj->Equals(true);
00084   }
00085
00086   if (this->m_deviceSupportsRawMode)
00087   {
00088    this->toggleRawAudio->IsEnabled = true;
00089    ShowStatusMessage("Raw Supported", NotifyType::StatusMessage);
00090   }
00091   else
00092   {
00093    this->toggleRawAudio->IsEnabled = false;
00094    ShowStatusMessage("Raw Not Supported", NotifyType::StatusMessage);
00095   }
00096  });
00097 }
00098
00099 Scenario2::~Scenario2()
00100 {
00101  if (m_deviceStateChangeToken.Value != 0)
00102  {
00103   m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00104   m_StateChangedEvent = nullptr;
00105   m_deviceStateChangeToken.Value = 0;
00106  }
00107
00108  if (m_SystemMediaControls)
00109  {
00110   m_SystemMediaControls->ButtonPressed -= m_SystemMediaControlsButtonToken;
00111   m_SystemMediaControls->IsPlayEnabled = false;
00112   m_SystemMediaControls->IsPauseEnabled = false;
00113   m_SystemMediaControls->IsStopEnabled = false;
00114   m_SystemMediaControls->PlaybackStatus = MediaPlaybackStatus::Closed;
00115  }
00116
00117  // Uninitialize MF
00118  if (m_IsMFLoaded)
00119  {
00120   MFShutdown();
00121   m_IsMFLoaded = false;
00122  }
00123 }
00124
00125 /// <summary>
00126 /// Invoked when this page is about to be displayed in a Frame.
00127 /// </summary>
00128 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00129 /// property is typically used to configure the page.</param>
00130 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00131 {
00132  // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00133  // as NotifyUser()
00134  rootPage = MainPage::Current;
00135  UpdateContentUI(false);
00136 }
00137
00138 /// <summary>
00139 /// Invoked when about to leave this page.
00140 /// </summary>
00141 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00142 /// property is typically used to configure the page.</param>
00143 void Scenario2::OnNavigatedFrom(NavigationEventArgs^ e)
00144 {
00145  if (nullptr != m_StateChangedEvent)
00146  {
00147   DeviceState deviceState = m_StateChangedEvent->GetState();
00148
00149   if (deviceState == DeviceState::DeviceStatePlaying)
00150   {
00151    StopDevice();
00152   }
00153  }
00154 }
00155
00156 #pragma region UI Related Code
00157 void Scenario2::ShowStatusMessage(Platform::String^ str, NotifyType messageType)
00158 {
00159  m_CoreDispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00160   [this, str, messageType]()
00161  {
00162   rootPage->NotifyUser(str, messageType);
00163  }));
00164 }
00165
00166 // Updates content controls based on selected option
00167 void Scenario2::UpdateContentUI(Platform::Boolean disableAll)
00168 {
00169  if ((nullptr != btnFilePicker) &&
00170   (nullptr != sliderFrequency))
00171  {
00172   if (disableAll)
00173   {
00174    btnFilePicker->IsEnabled = false;
00175    sliderFrequency->IsEnabled = false;
00176    radioFile->IsEnabled = false;
00177    radioTone->IsEnabled = false;
00178   }
00179   else
00180   {
00181    radioFile->IsEnabled = true;
00182    radioTone->IsEnabled = true;
00183
00184    switch (m_ContentType)
00185    {
00186    case ContentType::ContentTypeTone:
00187     btnFilePicker->IsEnabled = false;
00188     sliderFrequency->IsEnabled = true;
00189     UpdateContentProps(sliderFrequency->Value.ToString() + " Hz");
00190     break;
00191
00192    case ContentType::ContentTypeFile:
00193     btnFilePicker->IsEnabled = true;
00194     sliderFrequency->IsEnabled = false;
00195     break;
00196
00197    default:
00198     break;
00199    }
00200   }
00201  }
00202 }
00203
00204 // Updates transport controls based on current playstate
00205 void Scenario2::UpdateMediaControlUI(DeviceState deviceState)
00206 {
00207  switch (deviceState)
00208  {
00209  case DeviceState::DeviceStatePlaying:
00210   btnPlay->IsEnabled = false;
00211   btnStop->IsEnabled = true;
00212   btnPlayPause->IsEnabled = true;
00213   btnPause->IsEnabled = true;
00214   break;
00215
00216  case DeviceState::DeviceStateStopped:
00217  case DeviceState::DeviceStateInError:
00218   btnPlay->IsEnabled = true;
00219   btnStop->IsEnabled = false;
00220   btnPlayPause->IsEnabled = true;
00221   btnPause->IsEnabled = false;
00222
00223   UpdateContentUI(false);
00224   break;
00225
00226  case DeviceState::DeviceStatePaused:
00227   btnPlay->IsEnabled = true;
00228   btnStop->IsEnabled = true;
00229   btnPlayPause->IsEnabled = true;
00230   btnPause->IsEnabled = false;
00231   break;
00232
00233  case DeviceState::DeviceStateStarting:
00234  case DeviceState::DeviceStateStopping:
00235   btnPlay->IsEnabled = false;
00236   btnStop->IsEnabled = false;
00237   btnPlayPause->IsEnabled = false;
00238   btnPause->IsEnabled = false;
00239
00240   UpdateContentUI(true);
00241   break;
00242  }
00243 }
00244
00245 // Updates textbox on UI thread
00246 void Scenario2::UpdateContentProps(String^ str)
00247 {
00248  String^ text = str;
00249
00250  if (nullptr != txtContentProps)
00251  {
00252   // The event handler may be invoked on a background thread, so use the Dispatcher to invoke the UI-related code on the UI thread.
00253   txtContentProps->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00254    [this, text]()
00255   {
00256    Windows::UI::Xaml::Media::SolidColorBrush ^brush;
00257    txtContentProps->Text = text;
00258
00259    if (("" == text) && (m_ContentType == ContentType::ContentTypeFile))
00260    {
00261     brush = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::ColorHelper::FromArgb(0xCC, 0xFF, 0x00, 0x00));
00262    }
00263    else
00264    {
00265     brush = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::ColorHelper::FromArgb(0xFF, 0xFF, 0xFF, 0xFF));
00266    }
00267
00268    txtContentProps->Background = brush;
00269   }));
00270  }
00271 }
00272
00273 #pragma endregion
00274
00275 #pragma region UI Event Handlers
00276 void Scenario2::sliderFrequency_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00277 {
00278  Slider^ s = safe_cast<Slider^>(sender) ;
00279  if (s != nullptr)
00280  {
00281   UpdateContentProps(s->Value.ToString() + " Hz");
00282  }
00283 }
00284
00285 void Scenario2::sliderVolume_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
00286 {
00287  Slider^ s = safe_cast<Slider^>(sender) ;
00288  if (s != nullptr)
00289  {
00290   OnSetVolume(static_cast<UINT32>(s->Value));
00291  }
00292 }
00293
00294 void Scenario2::radioTone_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00295 {
00296  m_ContentType = ContentType::ContentTypeTone;
00297  UpdateContentProps("");
00298  m_ContentStream = nullptr;
00299  UpdateContentUI(false);
00300 }
00301
00302 void Scenario2::radioFile_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00303 {
00304  m_ContentType = ContentType::ContentTypeFile;
00305  UpdateContentProps("");
00306  m_ContentStream = nullptr;
00307  UpdateContentUI(false);
00308 }
00309
00310 void Scenario2::btnPlay_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00311 {
00312  StartDevice();
00313 }
00314
00315 void Scenario2::btnPause_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00316 {
00317  PauseDevice();
00318 }
00319
00320 void Scenario2::btnPlayPause_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00321 {
00322  PlayPauseToggleDevice();
00323 }
00324
00325 void Scenario2::btnStop_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00326 {
00327  StopDevice();
00328 }
00329
00330 void Scenario2::btnFilePicker_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00331 {
00332  OnPickFileAsync();
00333 }
00334
00335 #pragma endregion
00336
00337 // Event callback from WASAPI renderer for changes in device state
00338 void Scenario2::OnDeviceStateChange(Object^ sender, DeviceStateChangedEventArgs^ e)
00339 {
00340  // Update Control Buttons
00341  m_CoreDispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00342   [this, e]()
00343  {
00344   UpdateMediaControlUI(e->State);
00345  }));
00346
00347  // Handle state specific messages
00348  switch (e->State)
00349  {
00350  case DeviceState::DeviceStateInitialized:
00351   StartDevice();
00352   m_SystemMediaControls->PlaybackStatus = MediaPlaybackStatus::Closed;
00353   break;
00354
00355  case DeviceState::DeviceStatePlaying:
00356   ShowStatusMessage("Playback Started", NotifyType::StatusMessage);
00357   m_SystemMediaControls->PlaybackStatus = MediaPlaybackStatus::Playing;
00358   break;
00359
00360  case DeviceState::DeviceStatePaused:
00361   ShowStatusMessage("Playback Paused", NotifyType::StatusMessage);
00362   m_SystemMediaControls->PlaybackStatus = MediaPlaybackStatus::Paused;
00363   break;
00364
00365  case DeviceState::DeviceStateStopped:
00366   m_spRenderer = nullptr;
00367
00368   if (m_deviceStateChangeToken.Value != 0)
00369   {
00370    m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00371    m_StateChangedEvent = nullptr;
00372    m_deviceStateChangeToken.Value = 0;
00373   }
00374
00375   ShowStatusMessage("Playback Stopped", NotifyType::StatusMessage);
00376   m_SystemMediaControls->PlaybackStatus = MediaPlaybackStatus::Stopped;
00377   break;
00378
00379  case DeviceState::DeviceStateInError:
00380   HRESULT hr = e->hr;
00381
00382   if (m_deviceStateChangeToken.Value != 0)
00383   {
00384    m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00385    m_StateChangedEvent = nullptr;
00386    m_deviceStateChangeToken.Value = 0;
00387   }
00388
00389   m_spRenderer = nullptr;
00390
00391   m_SystemMediaControls->PlaybackStatus = MediaPlaybackStatus::Closed;
00392
00393   wchar_t hrVal[11];
00394   swprintf_s(hrVal, 11, L"0x%08x\0", hr);
00395   String^ strHRVal = ref new String(hrVal);
00396
00397   String^ strMessage = "";
00398
00399   // Specifically handle a couple of known errors
00400   switch (hr)
00401   {
00402   case AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE:
00403    strMessage = "ERROR: Endpoint Does Not Support HW Offload (" + strHRVal + ")";
00404    ShowStatusMessage(strMessage, NotifyType::ErrorMessage);
00405    break;
00406
00407   case AUDCLNT_E_RESOURCES_INVALIDATED:
00408    strMessage = "ERROR: Endpoint Lost Access To Resources (" + strHRVal + ")";
00409    ShowStatusMessage(strMessage, NotifyType::ErrorMessage);
00410    break;
00411
00412   default:
00413    strMessage = "ERROR: " + strHRVal + " has occurred.";
00414    ShowStatusMessage(strMessage, NotifyType::ErrorMessage);
00415   }
00416  }
00417 }
00418
00419 //
00420 //  OnPickFileAsync()
00421 //
00422 //  File chooser for MF Source playback.  Retrieves a pointer to IRandomAccessStream
00423 //
00424 void Scenario2::OnPickFileAsync()
00425 {
00426  Pickers::FileOpenPicker^ filePicker = ref new Pickers::FileOpenPicker();
00427  filePicker->ViewMode = Pickers::PickerViewMode::List;
00428  filePicker->SuggestedStartLocation = Pickers::PickerLocationId::MusicLibrary;
00429  filePicker->FileTypeFilter->Append(".wav");
00430  filePicker->FileTypeFilter->Append(".mp3");
00431  filePicker->FileTypeFilter->Append(".wma");
00432
00433  concurrency::create_task(filePicker->PickSingleFileAsync()).then(
00434   [this](Windows::Storage::StorageFile^ file)
00435  {
00436   if (nullptr != file)
00437   {
00438    // Open the stream
00439    concurrency::create_task(file->OpenAsync(FileAccessMode::Read)).then(
00440     [this, file](IRandomAccessStream^ stream)
00441    {
00442     if (stream != nullptr)
00443     {
00444      m_ContentStream = stream;
00445      UpdateContentProps(file->Path);
00446     }
00447    });
00448   }
00449  });
00450 }
00451
00452 //
00453 //  OnSetVolume()
00454 //
00455 //  Updates the session volume
00456 //
00457 void Scenario2::OnSetVolume(UINT32 volume)
00458 {
00459  if (m_spRenderer)
00460  {
00461   // Updates the Session volume on the AudioClient
00462   m_spRenderer->SetVolumeOnSession(volume);
00463  }
00464 }
00465
00466 //
00467 //  InitializeDevice()
00468 //
00469 //  Sets up a new instance of the WASAPI renderer
00470 //
00471 void Scenario2::InitializeDevice()
00472 {
00473  HRESULT hr = S_OK;
00474
00475  if (!m_spRenderer)
00476  {
00477   // Create a new WASAPI instance
00478   m_spRenderer = Make<WASAPIRenderer>();
00479
00480   if (nullptr == m_spRenderer)
00481   {
00482    OnDeviceStateChange(this, ref new DeviceStateChangedEventArgs(DeviceState::DeviceStateInError, E_OUTOFMEMORY));
00483    return;
00484   }
00485
00486   // Get a pointer to the device event interface
00487   m_StateChangedEvent = m_spRenderer->GetDeviceStateEvent();
00488
00489   if (nullptr == m_StateChangedEvent)
00490   {
00491    OnDeviceStateChange(this, ref new DeviceStateChangedEventArgs(DeviceState::DeviceStateInError, E_FAIL));
00492    return;
00493   }
00494
00495   // Register for events
00496   m_deviceStateChangeToken = m_StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler(this, &Scenario2::OnDeviceStateChange);
00497
00498   // Configure user based properties
00499   DEVICEPROPS props;
00500   int BufferSize = 0;
00501   swscanf_s(txtHWBuffer->Text->Data(), L"%d", &BufferSize);
00502
00503   switch (m_ContentType)
00504   {
00505   case ContentType::ContentTypeTone:
00506    props.IsTonePlayback = true;
00507    props.Frequency = static_cast<DWORD>(sliderFrequency->Value);
00508    break;
00509
00510   case ContentType::ContentTypeFile:
00511    props.IsTonePlayback = false;
00512    props.ContentStream = m_ContentStream;
00513    break;
00514   }
00515
00516   props.IsLowLatency = false;
00517   props.IsHWOffload = static_cast<Platform::Boolean>(toggleHWOffload->IsOn);
00518   props.IsBackground = static_cast<Platform::Boolean>(toggleBackgroundAudio->IsOn);
00519   props.IsRawChosen = static_cast<Platform::Boolean>(toggleRawAudio->IsOn);
00520   props.IsRawSupported = m_deviceSupportsRawMode;
00521   props.hnsBufferDuration = static_cast<REFERENCE_TIME>(BufferSize) ;
00522
00523   m_spRenderer->SetProperties(props);
00524
00525   // Selects the Default Audio Device
00526   m_spRenderer->InitializeAudioDeviceAsync();
00527
00528   // Set the initial volume.
00529   OnSetVolume(static_cast<UINT32>(sliderVolume->Value));
00530  }
00531 }
00532
00533 //
00534 //  StartDevice()
00535 //
00536 void Scenario2::StartDevice()
00537 {
00538  if (nullptr == m_spRenderer)
00539  {
00540   // Call from main UI thread
00541   InitializeDevice();
00542  }
00543  else
00544  {
00545   // Starts a work item to begin playback, likely in the paused state
00546   m_spRenderer->StartPlaybackAsync();
00547  }
00548 }
00549
00550 //
00551 //  StopDevice()
00552 //
00553 void Scenario2::StopDevice()
00554 {
00555  if (m_spRenderer)
00556  {
00557   // Set the event to stop playback
00558   m_spRenderer->StopPlaybackAsync();
00559  }
00560 }
00561
00562 //
00563 //  PauseDevice()
00564 //
00565 void Scenario2::PauseDevice()
00566 {
00567  if (m_spRenderer)
00568  {
00569   DeviceState deviceState = m_StateChangedEvent->GetState();
00570
00571   if (deviceState == DeviceState::DeviceStatePlaying)
00572   {
00573    // Starts a work item to pause playback
00574    m_spRenderer->PausePlaybackAsync();
00575   }
00576  }
00577 }
00578
00579 //
00580 //  PlayPauseToggleDevice()
00581 //
00582 void Scenario2::PlayPauseToggleDevice()
00583 {
00584  if (m_spRenderer)
00585  {
00586   DeviceState deviceState = m_StateChangedEvent->GetState();
00587
00588   if (deviceState == DeviceState::DeviceStatePlaying)
00589   {
00590    // Starts a work item to pause playback
00591    m_spRenderer->PausePlaybackAsync();
00592   }
00593   else if (deviceState == DeviceState::DeviceStatePaused)
00594   {
00595    // Starts a work item to pause playback
00596    m_spRenderer->StartPlaybackAsync();
00597   }
00598  }
00599  else
00600  {
00601   StartDevice();
00602  }
00603 }
00604
00605 //
00606 //   MediaButtonPressed
00607 //
00608 void Scenario2::MediaButtonPressed(SystemMediaTransportControls^ sender, SystemMediaTransportControlsButtonPressedEventArgs^ e)
00609 {
00610  m_CoreDispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00611   [this, e]()
00612  {
00613   switch (e->Button)
00614   {
00615   case SystemMediaTransportControlsButton::Play:
00616    StartDevice();
00617    break;
00618
00619   case SystemMediaTransportControlsButton::Pause:
00620    PauseDevice();
00621    break;
00622
00623   case SystemMediaTransportControlsButton::Stop:
00624    StopDevice();
00625    break;
00626
00627   default:
00628    break;
00629   }
00630  }));
00631 }
Generated on Fri Nov 15 2024 22:18:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/Scenario1.cpp Source File

  • WindowsAudioSession
  • cppwinrt

Scenario1.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
00012 #include "Scenario1.h"
00013 #include "Scenario1.g.cpp"
00014
00015 using namespace winrt;
00016 using namespace winrt::Windows::Foundation;
00017 using namespace winrt::Windows::Devices::Enumeration;
00018 using namespace winrt::Windows::Media::Devices;
00019 using namespace winrt::Windows::UI::Core;
00020 using namespace winrt::Windows::UI::Xaml;
00021 using namespace winrt::Windows::UI::Xaml::Controls;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario1::Scenario1()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     fire_and_forget Scenario1::Enumerate_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00031     {
00032         auto lifetime = get_strong();
00033
00034         DevicesList().Items().Clear();
00035
00036         // Get the string identifier of the audio renderer
00037         hstring AudioSelector = MediaDevice::GetAudioRenderSelector();
00038
00039         // Custom properties defined in mmdeviceapi.h in the format "{GUID} PID"
00040         constexpr wchar_t PKEY_AudioEndpoint_Supports_EventDriven_Mode[] = L"{1da5d803-d492-4edd-8c23-e0c0ffee7f0e} 7";
00041
00042         // Add custom properties to the query
00043         DeviceInformationCollection deviceInfoCollection = co_await DeviceInformation::FindAllAsync(AudioSelector, { PKEY_AudioEndpoint_Supports_EventDriven_Mode });
00044         try
00045         {
00046             // Enumerate through the devices and the custom properties
00047             for (DeviceInformation&& deviceInfo : deviceInfoCollection)
00048             {
00049                 hstring deviceInfoString = deviceInfo.Name();
00050
00051                 // Pull out the custom property
00052                 std::optional<uint32_t> supportsEventDriven = deviceInfo.Properties().TryLookup(PKEY_AudioEndpoint_Supports_EventDriven_Mode).try_as<uint32_t>();
00053                 if (supportsEventDriven)
00054                 {
00055                     deviceInfoString = deviceInfoString + L" --> EventDriven(" + to_hstring(supportsEventDriven.value()) + L")";
00056                 }
00057
00058                 DevicesList().Items().Append(box_value(deviceInfoString));
00059             }
00060             rootPage.NotifyUser(L"Enumerated " + to_hstring(deviceInfoCollection.Size()) + L" device(s).", NotifyType::StatusMessage);
00061         }
00062         catch (...)
00063         {
00064             rootPage.NotifyUser(to_message(), NotifyType::ErrorMessage);
00065         }
00066     }
00067 }
Generated on Fri Nov 15 2024 22:19:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7 Member List

This is the complete list of members for Scenario7, including all inherited members.
Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario7 | [inline, private]
Scenario7() | Scenario7 | [inline]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AudioCategory/cs/AudioCategory/Scenario3.xaml.cs Source File

  • AudioCategory
  • cs
  • AudioCategory

Scenario3.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016 using Windows.UI.Xaml.Media;
00017
00018 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00019
00020 namespace PlaybackManager
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class Scenario3 : Page
00026     {
00027         public Scenario3()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         private void Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00033         {
00034             Playback.SetAudioCategory(AudioCategory.GameChat);
00035             Playback.SelectFile();
00036         }
00037     }
00038 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraManualControls/cs/MainPage.IsoSpeed.xaml.cs Source File

  • CameraManualControls
  • cs

MainPage.IsoSpeed.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019
00020 namespace CameraManualControls
00021 {
00022     public sealed partial class MainPage : Page
00023     {
00024
00025         private void UpdateIsoControlCapabilities()
00026         {
00027             var isoSpeedControl = _mediaCapture.VideoDeviceController.IsoSpeedControl;
00028
00029             if (isoSpeedControl.Supported)
00030             {
00031                 IsoButton.Tag = Visibility.Visible;
00032
00033                 IsoAutoCheckBox.IsChecked = isoSpeedControl.Auto;
00034
00035                 // Unhook the event handler, so that changing properties on the slider won't trigger an API call
00036                 IsoSlider.ValueChanged -= IsoSlider_ValueChanged;
00037
00038                 var value = isoSpeedControl.Value;
00039                 IsoSlider.Minimum = isoSpeedControl.Min;
00040                 IsoSlider.Maximum = isoSpeedControl.Max;
00041                 IsoSlider.StepFrequency = isoSpeedControl.Step;
00042                 IsoSlider.Value = value;
00043
00044                 IsoSlider.ValueChanged += IsoSlider_ValueChanged;
00045             }
00046             else
00047             {
00048                 IsoButton.Visibility = Visibility.Collapsed;
00049                 IsoButton.Tag = Visibility.Collapsed;
00050             }
00051         }
00052
00053         private async void IsoSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e)
00054         {
00055             if (_settingUpUi) return;
00056
00057             var value = (sender as Slider).Value;
00058
00059             await _mediaCapture.VideoDeviceController.IsoSpeedControl.SetValueAsync((uint)value);
00060         }
00061
00062         private async void IsoAutoCheckBox_CheckedChanged(object sender, RoutedEventArgs e)
00063         {
00064             var autoIso = (sender as CheckBox).IsChecked == true;
00065
00066             if (autoIso)
00067             {
00068                 await _mediaCapture.VideoDeviceController.IsoSpeedControl.SetAutoAsync();
00069             }
00070             else
00071             {
00072                 await _mediaCapture.VideoDeviceController.IsoSpeedControl.SetValueAsync((uint)IsoSlider.Value);
00073             }
00074         }
00075
00076     }
00077 }
Generated on Fri Nov 15 2024 22:18:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSerialDeviceAccess/cs/Scenario1_ConnectDisconnect.xaml.cs Source File

  • CustomSerialDeviceAccess
  • cs

Scenario1_ConnectDisconnect.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016
00017 using System;
00018 using System.IO;
00019 using System.Collections.Generic;
00020 using System.Collections.ObjectModel;
00021
00022 using Windows.ApplicationModel;
00023 using Windows.Foundation;
00024
00025 using Windows.UI.Core;
00026
00027 using Windows.Devices.Enumeration;
00028 using Windows.Devices.SerialCommunication;
00029 using CustomSerialDeviceAccess;
00030
00031 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00032
00033 namespace CustomSerialDeviceAccess
00034 {
00035     /// <summary>
00036     /// Demonstrates how to connect to a Serial Device and respond to device disconnects, app suspending and resuming events.
00037     ///
00038     /// To use this sample with your device:
00039     /// 1) Include the device in the Package.appxmanifest. For instructions, see Package.appxmanifest documentation.
00040     /// 2) Create a DeviceWatcher object for your device. See the InitializeDeviceWatcher method in this sample.
00041     /// </summary>
00042     public sealed partial class Scenario1_ConnectDisconnect : Page
00043     {
00044         private const String ButtonNameDisconnectFromDevice = "Disconnect from device";
00045         private const String ButtonNameDisableReconnectToDevice = "Do not automatically reconnect to device that was just closed";
00046
00047         // Pointer back to the main page
00048         private MainPage rootPage = MainPage.Current;
00049
00050         private SuspendingEventHandler appSuspendEventHandler;
00051         private EventHandler<Object> appResumeEventHandler;
00052
00053         private ObservableCollection<DeviceListEntry> listOfDevices;
00054
00055         private Dictionary<DeviceWatcher, String> mapDeviceWatchersToDeviceSelector;
00056         private Boolean watchersSuspended;
00057         private Boolean watchersStarted;
00058
00059         // Has all the devices enumerated by the device watcher?
00060         private Boolean isAllDevicesEnumerated;
00061
00062         public Scenario1_ConnectDisconnect()
00063         {
00064             this.InitializeComponent();
00065
00066             listOfDevices = new ObservableCollection<DeviceListEntry>();
00067
00068             mapDeviceWatchersToDeviceSelector = new Dictionary<DeviceWatcher, String>();
00069             watchersStarted = false;
00070             watchersSuspended = false;
00071
00072             isAllDevicesEnumerated = false;
00073         }
00074
00075         /// <summary>
00076         /// Invoked when this page is about to be displayed in a Frame.
00077         ///
00078         /// Create the DeviceWatcher objects when the user navigates to this page so the UI list of devices is populated.
00079         /// </summary>
00080         /// <param name="eventArgs">Event data that describes how this page was reached.  The Parameter
00081         /// property is typically used to configure the page.</param>
00082         protected override void OnNavigatedTo(NavigationEventArgs eventArgs)
00083         {
00084             // If we are connected to the device or planning to reconnect, we should disable the list of devices
00085             // to prevent the user from opening a device without explicitly closing or disabling the auto reconnect
00086             if (EventHandlerForDevice.Current.IsDeviceConnected
00087                 || (EventHandlerForDevice.Current.IsEnabledAutoReconnect
00088                 && EventHandlerForDevice.Current.DeviceInformation != null))
00089             {
00090                 UpdateConnectDisconnectButtonsAndList(false);
00091
00092                 // These notifications will occur if we are waiting to reconnect to device when we start the page
00093                 EventHandlerForDevice.Current.OnDeviceConnected = this.OnDeviceConnected;
00094                 EventHandlerForDevice.Current.OnDeviceClose = this.OnDeviceClosing;
00095             }
00096             else
00097             {
00098                 UpdateConnectDisconnectButtonsAndList(true);
00099             }
00100
00101             // Begin watching out for events
00102             StartHandlingAppEvents();
00103
00104             // Initialize the desired device watchers so that we can watch for when devices are connected/removed
00105             InitializeDeviceWatchers();
00106             StartDeviceWatchers();
00107
00108             DeviceListSource.Source = listOfDevices;
00109         }
00110
00111         /// <summary>
00112         /// Unregister from App events and DeviceWatcher events because this page will be unloaded.
00113         /// </summary>
00114         /// <param name="eventArgs"></param>
00115         protected override void OnNavigatedFrom(NavigationEventArgs eventArgs)
00116         {
00117             StopDeviceWatchers();
00118             StopHandlingAppEvents();
00119
00120             // We no longer care about the device being connected
00121             EventHandlerForDevice.Current.OnDeviceConnected = null;
00122             EventHandlerForDevice.Current.OnDeviceClose = null;
00123         }
00124
00125         private async void ConnectToDevice_Click(Object sender, RoutedEventArgs eventArgs)
00126         {
00127             var selection = ConnectDevices.SelectedItems;
00128             DeviceListEntry entry = null;
00129
00130             if (selection.Count > 0)
00131             {
00132                 var obj = selection[0];
00133                 entry = (DeviceListEntry)obj;
00134
00135                 if (entry != null)
00136                 {
00137                     // Create an EventHandlerForDevice to watch for the device we are connecting to
00138                     EventHandlerForDevice.CreateNewEventHandlerForDevice();
00139
00140                     // Get notified when the device was successfully connected to or about to be closed
00141                     EventHandlerForDevice.Current.OnDeviceConnected = this.OnDeviceConnected;
00142                     EventHandlerForDevice.Current.OnDeviceClose = this.OnDeviceClosing;
00143
00144                     // It is important that the FromIdAsync call is made on the UI thread because the consent prompt, when present,
00145                     // can only be displayed on the UI thread. Since this method is invoked by the UI, we are already in the UI thread.
00146                     Boolean openSuccess = await EventHandlerForDevice.Current.OpenDeviceAsync(entry.DeviceInformation, entry.DeviceSelector);
00147
00148                     // Disable connect button if we connected to the device
00149                     UpdateConnectDisconnectButtonsAndList(!openSuccess);
00150                 }
00151             }
00152         }
00153
00154         private void DisconnectFromDevice_Click(Object sender, RoutedEventArgs eventArgs)
00155         {
00156             var selection = ConnectDevices.SelectedItems;
00157             DeviceListEntry entry = null;
00158
00159             // Prevent auto reconnect because we are voluntarily closing it
00160             // Re-enable the ConnectDevice list and ConnectToDevice button if the connected/opened device was removed.
00161             EventHandlerForDevice.Current.IsEnabledAutoReconnect = false;
00162
00163             if (selection.Count > 0)
00164             {
00165                 var obj = selection[0];
00166                 entry = (DeviceListEntry)obj;
00167
00168                 if (entry != null)
00169                 {
00170                     EventHandlerForDevice.Current.CloseDevice();
00171                 }
00172             }
00173
00174             UpdateConnectDisconnectButtonsAndList(true);
00175         }
00176
00177         /// <summary>
00178         /// Initialize device watchers to watch for the Serial Devices.
00179         ///
00180         /// GetDeviceSelector return an AQS string that can be passed directly into DeviceWatcher.createWatcher() or  DeviceInformation.createFromIdAsync().
00181         ///
00182         /// In this sample, a DeviceWatcher will be used to watch for devices because we can detect surprise device removals.
00183         /// </summary>
00184         private void InitializeDeviceWatchers()
00185         {
00186
00187             // Target all Serial Devices present on the system
00188             var deviceSelector = SerialDevice.GetDeviceSelector();
00189
00190             // Other variations of GetDeviceSelector() usage are commented for reference
00191             //
00192             // Target a specific USB Serial Device using its VID and PID (here Arduino VID/PID is used)
00193             // var deviceSelector = SerialDevice.GetDeviceSelectorFromUsbVidPid(0x2341, 0x0043);
00194             //
00195             // Target a specific Serial Device by its COM PORT Name - "COM3"
00196             // var deviceSelector = SerialDevice.GetDeviceSelector("COM3");
00197             //
00198             // Target a specific UART based Serial Device by its COM PORT Name (usually defined in ACPI) - "UART1"
00199             // var deviceSelector = SerialDevice.GetDeviceSelector("UART1");
00200             //
00201
00202             // Create a device watcher to look for instances of the Serial Device that match the device selector
00203             // used earlier.
00204
00205             var deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector);
00206
00207             // Allow the EventHandlerForDevice to handle device watcher events that relates or effects our device (i.e. device removal, addition, app suspension/resume)
00208             AddDeviceWatcher(deviceWatcher, deviceSelector);
00209         }
00210
00211         private void StartHandlingAppEvents()
00212         {
00213             appSuspendEventHandler = new SuspendingEventHandler(this.OnAppSuspension);
00214             appResumeEventHandler = new EventHandler<Object>(this.OnAppResume);
00215
00216             // This event is raised when the app is exited and when the app is suspended
00217             App.Current.Suspending += appSuspendEventHandler;
00218
00219             App.Current.Resuming += appResumeEventHandler;
00220         }
00221
00222         private void StopHandlingAppEvents()
00223         {
00224             // This event is raised when the app is exited and when the app is suspended
00225             App.Current.Suspending -= appSuspendEventHandler;
00226
00227             App.Current.Resuming -= appResumeEventHandler;
00228         }
00229
00230         /// <summary>
00231         /// Registers for Added, Removed, and Enumerated events on the provided deviceWatcher before adding it to an internal list.
00232         /// </summary>
00233         /// <param name="deviceWatcher"></param>
00234         /// <param name="deviceSelector">The AQS used to create the device watcher</param>
00235         private void AddDeviceWatcher(DeviceWatcher deviceWatcher, String deviceSelector)
00236         {
00237             deviceWatcher.Added += new TypedEventHandler<DeviceWatcher, DeviceInformation>(this.OnDeviceAdded);
00238             deviceWatcher.Removed += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(this.OnDeviceRemoved);
00239             deviceWatcher.EnumerationCompleted += new TypedEventHandler<DeviceWatcher, Object>(this.OnDeviceEnumerationComplete);
00240
00241             mapDeviceWatchersToDeviceSelector.Add(deviceWatcher, deviceSelector);
00242         }
00243
00244         /// <summary>
00245         /// Starts all device watchers including ones that have been individually stopped.
00246         /// </summary>
00247         private void StartDeviceWatchers()
00248         {
00249             // Start all device watchers
00250             watchersStarted = true;
00251             isAllDevicesEnumerated = false;
00252
00253             foreach (DeviceWatcher deviceWatcher in mapDeviceWatchersToDeviceSelector.Keys)
00254             {
00255                 if ((deviceWatcher.Status != DeviceWatcherStatus.Started)
00256                     && (deviceWatcher.Status != DeviceWatcherStatus.EnumerationCompleted))
00257                 {
00258                     deviceWatcher.Start();
00259                 }
00260             }
00261         }
00262
00263         /// <summary>
00264         /// Stops all device watchers.
00265         /// </summary>
00266         private void StopDeviceWatchers()
00267         {
00268             // Stop all device watchers
00269             foreach (DeviceWatcher deviceWatcher in mapDeviceWatchersToDeviceSelector.Keys)
00270             {
00271                 if ((deviceWatcher.Status == DeviceWatcherStatus.Started)
00272                     || (deviceWatcher.Status == DeviceWatcherStatus.EnumerationCompleted))
00273                 {
00274                     deviceWatcher.Stop();
00275                 }
00276             }
00277
00278             // Clear the list of devices so we don't have potentially disconnected devices around
00279             ClearDeviceEntries();
00280
00281             watchersStarted = false;
00282         }
00283
00284         /// <summary>
00285         /// Creates a DeviceListEntry for a device and adds it to the list of devices in the UI
00286         /// </summary>
00287         /// <param name="deviceInformation">DeviceInformation on the device to be added to the list</param>
00288         /// <param name="deviceSelector">The AQS used to find this device</param>
00289         private void AddDeviceToList(DeviceInformation deviceInformation, String deviceSelector)
00290         {
00291             // search the device list for a device with a matching interface ID
00292             var match = FindDevice(deviceInformation.Id);
00293
00294             // Add the device if it's new
00295             if (match == null)
00296             {
00297                 // Create a new element for this device interface, and queue up the query of its
00298                 // device information
00299                 match = new DeviceListEntry(deviceInformation, deviceSelector);
00300
00301                 // Add the new element to the end of the list of devices
00302                 listOfDevices.Add(match);
00303             }
00304         }
00305
00306         private void RemoveDeviceFromList(String deviceId)
00307         {
00308             // Removes the device entry from the interal list; therefore the UI
00309             var deviceEntry = FindDevice(deviceId);
00310
00311             listOfDevices.Remove(deviceEntry);
00312         }
00313
00314         private void ClearDeviceEntries()
00315         {
00316             listOfDevices.Clear();
00317         }
00318
00319         /// <summary>
00320         /// Searches through the existing list of devices for the first DeviceListEntry that has
00321         /// the specified device Id.
00322         /// </summary>
00323         /// <param name="deviceId">Id of the device that is being searched for</param>
00324         /// <returns>DeviceListEntry that has the provided Id; else a nullptr</returns>
00325         private DeviceListEntry FindDevice(String deviceId)
00326         {
00327             if (deviceId != null)
00328             {
00329                 foreach (DeviceListEntry entry in listOfDevices)
00330                 {
00331                     if (entry.DeviceInformation.Id == deviceId)
00332                     {
00333                         return entry;
00334                     }
00335                 }
00336             }
00337
00338             return null;
00339         }
00340
00341         /// <summary>
00342         /// We must stop the DeviceWatchers because device watchers will continue to raise events even if
00343         /// the app is in suspension, which is not desired (drains battery). We resume the device watcher once the app resumes again.
00344         /// </summary>
00345         /// <param name="sender"></param>
00346         /// <param name="eventArgs"></param>
00347         private void OnAppSuspension(Object sender, SuspendingEventArgs args)
00348         {
00349             if (watchersStarted)
00350             {
00351                 watchersSuspended = true;
00352                 StopDeviceWatchers();
00353             }
00354             else
00355             {
00356                 watchersSuspended = false;
00357             }
00358         }
00359
00360         /// <summary>
00361         /// See OnAppSuspension for why we are starting the device watchers again
00362         /// </summary>
00363         /// <param name="sender"></param>
00364         /// <param name="args"></param>
00365         private void OnAppResume(Object sender, Object args)
00366         {
00367             if (watchersSuspended)
00368             {
00369                 watchersSuspended = false;
00370                 StartDeviceWatchers();
00371             }
00372         }
00373
00374         /// <summary>
00375         /// We will remove the device from the UI
00376         /// </summary>
00377         /// <param name="sender"></param>
00378         /// <param name="deviceInformationUpdate"></param>
00379         private async void OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceInformationUpdate)
00380         {
00381             await rootPage.Dispatcher.RunAsync(
00382                 CoreDispatcherPriority.Normal,
00383                 new DispatchedHandler(() =>
00384                 {
00385                     rootPage.NotifyUser("Device removed - " + deviceInformationUpdate.Id, NotifyType.StatusMessage);
00386
00387                     RemoveDeviceFromList(deviceInformationUpdate.Id);
00388                 }));
00389         }
00390
00391         /// <summary>
00392         /// This function will add the device to the listOfDevices so that it shows up in the UI
00393         /// </summary>
00394         /// <param name="sender"></param>
00395         /// <param name="deviceInformation"></param>
00396         private async void OnDeviceAdded(DeviceWatcher sender, DeviceInformation deviceInformation)
00397         {
00398             await rootPage.Dispatcher.RunAsync(
00399                 CoreDispatcherPriority.Normal,
00400                 new DispatchedHandler(() =>
00401                 {
00402                     rootPage.NotifyUser("Device added - " + deviceInformation.Id, NotifyType.StatusMessage);
00403
00404                     AddDeviceToList(deviceInformation, mapDeviceWatchersToDeviceSelector[sender]);
00405                 }));
00406         }
00407
00408         /// <summary>
00409         /// Notify the UI whether or not we are connected to a device
00410         /// </summary>
00411         /// <param name="sender"></param>
00412         /// <param name="args"></param>
00413         private async void OnDeviceEnumerationComplete(DeviceWatcher sender, Object args)
00414         {
00415             await rootPage.Dispatcher.RunAsync(
00416                 CoreDispatcherPriority.Normal,
00417                 new DispatchedHandler(() =>
00418                 {
00419                     isAllDevicesEnumerated = true;
00420
00421                     // If we finished enumerating devices and the device has not been connected yet, the OnDeviceConnected method
00422                     // is responsible for selecting the device in the device list (UI); otherwise, this method does that.
00423                     if (EventHandlerForDevice.Current.IsDeviceConnected)
00424                     {
00425                         SelectDeviceInList(EventHandlerForDevice.Current.DeviceInformation.Id);
00426
00427                         ButtonDisconnectFromDevice.Content = ButtonNameDisconnectFromDevice;
00428
00429                         if (EventHandlerForDevice.Current.Device.PortName != "")
00430                         {
00431                             rootPage.NotifyUser("Connected to - " +
00432                                                 EventHandlerForDevice.Current.Device.PortName +
00433                                                 " - " +
00434                                                 EventHandlerForDevice.Current.DeviceInformation.Id, NotifyType.StatusMessage);
00435                         } else
00436                         {
00437                             rootPage.NotifyUser("Connected to - " +
00438                                                 EventHandlerForDevice.Current.DeviceInformation.Id, NotifyType.StatusMessage);
00439                         }
00440                     }
00441                     else if (EventHandlerForDevice.Current.IsEnabledAutoReconnect && EventHandlerForDevice.Current.DeviceInformation != null)
00442                     {
00443                         // We will be reconnecting to a device
00444                         ButtonDisconnectFromDevice.Content = ButtonNameDisableReconnectToDevice;
00445
00446                         rootPage.NotifyUser("Waiting to reconnect to device -  " + EventHandlerForDevice.Current.DeviceInformation.Id, NotifyType.StatusMessage);
00447                     }
00448                     else
00449                     {
00450                         rootPage.NotifyUser("No device is currently connected", NotifyType.StatusMessage);
00451                     }
00452                 }));
00453         }
00454
00455         /// <summary>
00456         /// If all the devices have been enumerated, select the device in the list we connected to. Otherwise let the EnumerationComplete event
00457         /// from the device watcher handle the device selection
00458         /// </summary>
00459         /// <param name="sender"></param>
00460         /// <param name="deviceInformation"></param>
00461         private void OnDeviceConnected(EventHandlerForDevice sender, DeviceInformation deviceInformation)
00462         {
00463             // Find and select our connected device
00464             if (isAllDevicesEnumerated)
00465             {
00466                 SelectDeviceInList(EventHandlerForDevice.Current.DeviceInformation.Id);
00467
00468                 ButtonDisconnectFromDevice.Content = ButtonNameDisconnectFromDevice;
00469             }
00470
00471             if (EventHandlerForDevice.Current.Device.PortName != "")
00472             {
00473                 rootPage.NotifyUser("Connected to - " +
00474                                     EventHandlerForDevice.Current.Device.PortName +
00475                                     " - " +
00476                                     EventHandlerForDevice.Current.DeviceInformation.Id, NotifyType.StatusMessage);
00477             } else
00478             {
00479                 rootPage.NotifyUser("Connected to - " +
00480                                     EventHandlerForDevice.Current.DeviceInformation.Id, NotifyType.StatusMessage);
00481             }
00482         }
00483
00484         /// <summary>
00485         /// The device was closed. If we will autoreconnect to the device, reflect that in the UI
00486         /// </summary>
00487         /// <param name="sender"></param>
00488         /// <param name="deviceInformation"></param>
00489         private async void OnDeviceClosing(EventHandlerForDevice sender, DeviceInformation deviceInformation)
00490         {
00491             await rootPage.Dispatcher.RunAsync(
00492                 CoreDispatcherPriority.Normal,
00493                 new DispatchedHandler(() =>
00494                 {
00495                     // We were connected to the device that was unplugged, so change the "Disconnect from device" button
00496                     // to "Do not reconnect to device"
00497                     if (ButtonDisconnectFromDevice.IsEnabled && EventHandlerForDevice.Current.IsEnabledAutoReconnect)
00498                     {
00499                         ButtonDisconnectFromDevice.Content = ButtonNameDisableReconnectToDevice;
00500                     }
00501                 }));
00502         }
00503
00504         /// <summary>
00505         /// Selects the item in the UI's listbox that corresponds to the provided device id. If there are no
00506         /// matches, we will deselect anything that is selected.
00507         /// </summary>
00508         /// <param name="deviceIdToSelect">The device id of the device to select on the list box</param>
00509         private void SelectDeviceInList(String deviceIdToSelect)
00510         {
00511             // Don't select anything by default.
00512             ConnectDevices.SelectedIndex = -1;
00513
00514             for (int deviceListIndex = 0; deviceListIndex < listOfDevices.Count; deviceListIndex++)
00515             {
00516                 if (listOfDevices[deviceListIndex].DeviceInformation.Id == deviceIdToSelect)
00517                 {
00518                     ConnectDevices.SelectedIndex = deviceListIndex;
00519
00520                     break;
00521                 }
00522             }
00523         }
00524
00525         /// <summary>
00526         /// When ButtonConnectToDevice is disabled, ConnectDevices list will also be disabled.
00527         /// </summary>
00528         /// <param name="enableConnectButton">The state of ButtonConnectToDevice</param>
00529         private void UpdateConnectDisconnectButtonsAndList(Boolean enableConnectButton)
00530         {
00531             ButtonConnectToDevice.IsEnabled = enableConnectButton;
00532             ButtonDisconnectFromDevice.IsEnabled = !ButtonConnectToDevice.IsEnabled;
00533
00534             ConnectDevices.IsEnabled = ButtonConnectToDevice.IsEnabled;
00535         }
00536     }
00537 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

TypeConversionHelpers Member List

This is the complete list of members for TypeConversionHelpers, including all inherited members.
__pad0__ | TypeConversionHelpers |
GetAllJoynMessageArg(alljoyn_msgarg argument, PCSTR signature, _Out_ T *value) | TypeConversionHelpers | [inline, static]
GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Platform::String^*value) | TypeConversionHelpers | [inline, static]
GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IVector< T >^*value) | TypeConversionHelpers | [inline, static]
GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IVectorView< T >^*value) | TypeConversionHelpers | [inline, static]
GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IVector< Platform::String^>^*value) | TypeConversionHelpers | [inline, static]
GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IVectorView< Platform::String^>^*value) | TypeConversionHelpers | [inline, static]
GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IMap< T, U >^*value) | TypeConversionHelpers | [inline, static]
GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IMap< T, Platform::Object^>^*value) | TypeConversionHelpers | [inline, static]
GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IMapView< T, U >^*value) | TypeConversionHelpers | [inline, static]
GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Platform::Object^*value) | TypeConversionHelpers | [inline, static]
GetDictionaryTypeSignatures(_In_ PCSTR signature, _Inout_ std::vector< char > *keySignature, _Inout_ std::vector< char > *valueSignature) | TypeConversionHelpers | [static]
GetMapFromVariant(_In_ alljoyn_msgarg argument, _In_ char mapSignature, _Outptr_result_maybenull_ Platform::Object^*value) | TypeConversionHelpers | [inline, static]
GetValueFromVariant(_In_ alljoyn_msgarg argument, _Outptr_result_maybenull_ Platform::Object^*value) | TypeConversionHelpers | [inline, static]
GetVariantArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Platform::Object^*value) | TypeConversionHelpers | [inline, static]
GetVariantStructureArg(_In_ alljoyn_msgarg argument, _Outptr_result_maybenull_ Platform::Object^*value) | TypeConversionHelpers | [inline, static]
SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ T value) | TypeConversionHelpers | [inline, static]
SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Platform::String^value) | TypeConversionHelpers | [inline, static]
SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Windows::Foundation::Collections::IVectorView< T >^value) | TypeConversionHelpers | [inline, static]
SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Windows::Foundation::Collections::IVector< T >^value) | TypeConversionHelpers | [inline, static]
SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Windows::Foundation::Collections::IVectorView< Platform::String^>^value) | TypeConversionHelpers | [inline, static]
SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Windows::Foundation::Collections::IVector< Platform::String^>^value) | TypeConversionHelpers | [inline, static]
SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, Windows::Foundation::Collections::IMapView< T, U >^value) | TypeConversionHelpers | [inline, static]
SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Windows::Foundation::Collections::IMap< T, U >^value) | TypeConversionHelpers | [inline, static]
SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Platform::Object^value) | TypeConversionHelpers | [inline, static]
SetVariantArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ T value) | TypeConversionHelpers | [inline, static]
SetVariantStructureArg(_In_ alljoyn_msgarg argument, _In_ PROJECT_NAMESPACE::AllJoynMessageArgStructure^value) | TypeConversionHelpers | [inline, static]
signature | TypeConversionHelpers |
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cs/Scenario11_TryGet.xaml.cs Source File

  • FileAccess
  • cs

Scenario11_TryGet.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Storage;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Attempting to get a file with no error on failure.
00022     /// </summary>
00023     public sealed partial class Scenario11 : Page
00024     {
00025         MainPage rootPage = MainPage.Current;
00026
00027         public Scenario11()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         private async void GetFileButton_Click(object sender, RoutedEventArgs e)
00033         {
00034             StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
00035             StorageFile file = await storageFolder.TryGetItemAsync("sample.dat") as StorageFile;
00036             if (file != null)
00037             {
00038                 rootPage.NotifyUser($"Operation result: {file.Name}", NotifyType.StatusMessage);
00039             }
00040             else
00041             {
00042                 rootPage.NotifyUser("Operation result: null", NotifyType.StatusMessage);
00043             }
00044         }
00045     }
00046 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiScan/cpp/Scenario3_RegisterForUpdates.xaml.h Source File

  • WiFiScan
  • cpp

Scenario3_RegisterForUpdates.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_RegisterForUpdates.g.h"
00015 #include "MainPage.xaml.h"
00016 #include "DisplayHelpers.h"
00017
00018 namespace SDKTemplate
00019 {
00020     namespace WiFiScan
00021     {
00022         /// <summary>
00023         /// An empty page that can be used on its own or navigated to within a Frame.
00024         /// </summary>
00025         [Windows::Foundation::Metadata::WebHostHidden]
00026         [Windows::UI::Xaml::Data::Bindable]
00027         public ref class Scenario3_RegisterForUpdates sealed
00028         {
00029         public:
00030             Scenario3_RegisterForUpdates();
00031
00032             property Windows::Foundation::Collections::IObservableVector<WiFiNetworkDisplay^>^ ResultCollection;
00033
00034         protected:
00035             void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036
00037         private:
00038             void Button_Click_Register(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039             void Button_Click_Unregister(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040             void DisplayNetworkReport(Windows::Devices::WiFi::WiFiNetworkReport^ report, Windows::Devices::WiFi::WiFiAdapter^ adapter);
00041             void OnAvailableNetworksChanged(Windows::Devices::WiFi::WiFiAdapter ^sender, Platform::Object ^args);
00042
00043             MainPage^ _rootPage;
00044             Windows::Devices::WiFi::WiFiAdapter^ _firstAdapter;
00045             Windows::Foundation::EventRegistrationToken _registrationToken;
00046         };
00047     }
00048 }
Generated on Fri Nov 15 2024 22:22:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PoseTrackingFrameHeader Member List

This is the complete list of members for PoseTrackingFrameHeader, including all inherited members.
CustomDataTypeGuid | PoseTrackingFrameHeader
EntitiesCount | PoseTrackingFrameHeader
EntityOffsets | PoseTrackingFrameHeader
Generated on Fri Nov 15 2024 22:23:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BackButtonPage Member List

This is the complete list of members for BackButtonPage, including all inherited members.
BackButtonPage_BackRequested(object sender, BackRequestedEventArgs e) | BackButtonPage | [inline, private]
BackButtonVisibility | BackButtonPage |
OnBackRequested(object sender, BackRequestedEventArgs e) | BackButtonPage | [inline, protected, virtual]
OnNavigatedFrom(NavigationEventArgs e) | BackButtonPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | BackButtonPage | [inline, protected]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_MoveCertificate Member List

This is the complete list of members for Scenario1_MoveCertificate, including all inherited members.
appStore | Scenario1_MoveCertificate | [private]
MoveAppCertificateToUserCertificateStore(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_MoveCertificate |
MoveUserCertificateToAppCertificateStore(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_MoveCertificate |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_MoveCertificate |
Scenario1_MoveCertificate() | Scenario1_MoveCertificate |
userStore | Scenario1_MoveCertificate | [private]
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OnDemandHotspot/cppwinrt/SampleConfiguration.cpp Source File

  • OnDemandHotspot
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"OnDemandHotspot C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Manage Hotspot", xaml_typename<SDKTemplate::Scenario1_ManageHotspot>() },
00029 });
Generated on Fri Nov 15 2024 22:17:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/CritSec.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

CritSec.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 //////////////////////////////////////////////////////////////////////////
00004 //  CritSec
00005 //  Description: Wraps a critical section.
00006 //////////////////////////////////////////////////////////////////////////
00007
00008 class CritSec
00009 {
00010 public:
00011     CRITICAL_SECTION m_criticalSection;
00012 public:
00013     CritSec()
00014     {
00015         InitializeCriticalSectionEx(&m_criticalSection, 100, 0);
00016     }
00017
00018     ~CritSec()
00019     {
00020         DeleteCriticalSection(&m_criticalSection);
00021     }
00022
00023     _Acquires_lock_(m_criticalSection)
00024     void Lock()
00025     {
00026         EnterCriticalSection(&m_criticalSection);
00027     }
00028
00029     _Releases_lock_(m_criticalSection)
00030     void Unlock()
00031     {
00032         LeaveCriticalSection(&m_criticalSection);
00033     }
00034 };
00035
00036
00037 //////////////////////////////////////////////////////////////////////////
00038 //  AutoLock
00039 //  Description: Provides automatic locking and unlocking of a
00040 //               of a critical section.
00041 //
00042 //  Note: The AutoLock object must go out of scope before the CritSec.
00043 //////////////////////////////////////////////////////////////////////////
00044
00045 class AutoLock
00046 {
00047 private:
00048     CritSec *m_pCriticalSection;
00049 public:
00050     _Acquires_lock_(m_pCriticalSection)
00051     AutoLock(CritSec& crit)
00052     {
00053         m_pCriticalSection = &crit;
00054         m_pCriticalSection->Lock();
00055     }
00056
00057     _Releases_lock_(m_pCriticalSection)
00058     ~AutoLock()
00059     {
00060         m_pCriticalSection->Unlock();
00061     }
00062 };
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
_accelerometer | sealed | [private]
_deferral | sealed | [private]
_readingToken | sealed | [private]
_sampleCount | sealed | [private]
OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^sender, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason) | sealed | [private]
ReadingChanged(Windows::Devices::Sensors::Accelerometer^sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^e) | sealed | [private]
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance) | sealed | [virtual]
Scenario1_BackgroundTask() | sealed |
~Scenario1_BackgroundTask() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MediaCapturePreviewer Member List

This is the complete list of members for MediaCapturePreviewer, including all inherited members.
_dispatcher | MediaCapturePreviewer | [private]
_previewControl | MediaCapturePreviewer | [private]
CleanupCameraAsync() | MediaCapturePreviewer | [inline]
InitializeCameraAsync() | MediaCapturePreviewer | [inline]
IsPreviewing | MediaCapturePreviewer |
IsRecording | MediaCapturePreviewer |
MediaCapture | MediaCapturePreviewer |
MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs e) | MediaCapturePreviewer | [inline, private]
MediaCapturePreviewer(CaptureElement previewControl, CoreDispatcher dispatcher) | MediaCapturePreviewer | [inline]
SetMediaStreamPropertiesAsync(MediaStreamType streamType, IMediaEncodingProperties encodingProperties) | MediaCapturePreviewer | [inline]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CopyFiles Member List

This is the complete list of members for CopyFiles, including all inherited members.
CopyButton_Click(object sender, RoutedEventArgs e) | CopyFiles | [inline, private]
CopyFiles() | CopyFiles | [inline]
PasteButton_Click(object sender, RoutedEventArgs e) | CopyFiles | [inline, private]
rootPage | CopyFiles | [private]
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationData/cs/Scenario4_CompositeSettings.xaml.cs Source File

  • ApplicationData
  • cs

Scenario4_CompositeSettings.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using System;
00015 using Windows.Storage;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario4_CompositeSettings : Page
00020     {
00021         ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
00022
00023         const string settingName = "exampleCompositeSetting";
00024         const string settingName1 = "one";
00025         const string settingName2 = "hello";
00026
00027         public Scenario4_CompositeSettings()
00028         {
00029             InitializeComponent();
00030         }
00031
00032         void WriteCompositeSetting_Click(Object sender, RoutedEventArgs e)
00033         {
00034             // Composite settings are used to group multiple settings.
00035             // Note that Composite settings may not be nested.
00036             ApplicationDataCompositeValue composite = new ApplicationDataCompositeValue();
00037             composite[settingName1] = 1; // example value
00038             composite[settingName2] = "world"; // example value
00039
00040             localSettings.Values[settingName] = composite;
00041
00042             DisplayOutput();
00043         }
00044
00045         void DeleteCompositeSetting_Click(Object sender, RoutedEventArgs e)
00046         {
00047             localSettings.Values.Remove(settingName);
00048
00049             DisplayOutput();
00050         }
00051
00052         void DisplayOutput()
00053         {
00054             ApplicationDataCompositeValue composite = (ApplicationDataCompositeValue)localSettings.Values[settingName];
00055
00056             String output;
00057             if (composite == null)
00058             {
00059                 output = "Composite Setting: <empty>";
00060             }
00061             else
00062             {
00063                 output = String.Format("Composite Setting: {{{0} = {1}, {2} = \"{3}\"}}", settingName1, composite[settingName1], settingName2, composite[settingName2]);
00064             }
00065
00066             OutputTextBlock.Text = output;
00067         }
00068
00069         protected override void OnNavigatedTo(NavigationEventArgs e)
00070         {
00071             DisplayOutput();
00072         }
00073     }
00074 }
Generated on Fri Nov 15 2024 22:17:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LiveDash/cs/LiveDash/Models/Period.cs Source File

  • LiveDash
  • cs
  • LiveDash
  • Models

Period.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006
00007 namespace LiveDash.Models
00008 {
00009     /// <summary>
00010     /// Represents a period within a media presentation description
00011     /// </summary>
00012     public class Period
00013     {
00014         private List<MediaStream> m_streams;
00015
00016         private string id;
00017         private bool isSelected;
00018         private TimeSpan duration;
00019         private TimeSpan start;
00020
00021         internal Period()
00022         {
00023             m_streams = new List<MediaStream>();
00024         }
00025
00026         #region properties
00027         internal string Id
00028         {
00029             get
00030             {
00031                 return id;
00032             }
00033             set
00034             {
00035                 id = value;
00036             }
00037         }
00038
00039         internal bool IsSelected
00040         {
00041             get
00042             {
00043                 return isSelected;
00044             }
00045             set
00046             {
00047                 isSelected = value;
00048             }
00049         }
00050
00051         internal TimeSpan Duration
00052         {
00053             get
00054             {
00055                 return duration;
00056             }
00057
00058             set
00059             {
00060                 duration = value;
00061             }
00062         }
00063
00064         internal TimeSpan Start
00065         {
00066             get
00067             {
00068                 return start;
00069             }
00070
00071             set
00072             {
00073                 start = value;
00074             }
00075         }
00076         #endregion
00077
00078         internal void AddStream(MediaStream stream)
00079         {
00080             m_streams.Add(stream);
00081         }
00082
00083         /// <summary>
00084         /// Gets the stream with the video/mp4 mime type and will
00085         /// return null otherwise
00086         /// </summary>
00087         internal MediaStream GetVideoStream()
00088         {
00089             foreach (var stream in m_streams)
00090             {
00091                 if (stream.MimeType.Equals(Manifest.VideoMimeType))
00092                 {
00093                     return stream;
00094                 }
00095             }
00096             return null;
00097         }
00098
00099         /// <summary>
00100         /// Gets the stream with the audio/mp4 mime type and will
00101         /// return null otherwise
00102         /// </summary>
00103         internal MediaStream GetAudioStream()
00104         {
00105             foreach (var stream in m_streams)
00106             {
00107                 if (stream.MimeType.Equals(Manifest.AudioMimeType))
00108                 {
00109                     return stream;
00110                 }
00111             }
00112             return null;
00113         }
00114     }
00115 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MultipleViews/cppwinrt/SecondaryViewPage.cpp Source File

  • MultipleViews
  • cppwinrt

SecondaryViewPage.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SecondaryViewPage.h"
00014 #include "SecondaryViewPage.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::System;
00019 using namespace Windows::UI::Core::AnimationMetrics;
00020 using namespace Windows::UI::ViewManagement;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Media;
00023 using namespace Windows::UI::Xaml::Media::Animation;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 namespace
00027 {
00028     const int ANIMATION_TRANSLATION_START = 100;
00029     const int ANIMATION_TRANSLATION_END = 0;
00030     const int ANIMATION_OPACITY_START = 0;
00031     const int ANIMATION_OPACITY_END = 1;
00032     hstring EMPTY_TITLE = L"<title cleared>";
00033 }
00034
00035 namespace winrt::SDKTemplate::implementation
00036 {
00037     SecondaryViewPage::SecondaryViewPage()
00038     {
00039         InitializeComponent();
00040         m_enterAnimation = CreateEnterAnimation();
00041     }
00042
00043     void SecondaryViewPage::OnNavigatedTo(NavigationEventArgs const& e)
00044     {
00045         m_thisViewControl = e.Parameter().as<SDKTemplate::ViewLifetimeControl>();
00046
00047         // When this view is finally released, clean up state
00048         m_releasedToken = m_thisViewControl.Released({ get_weak(), &SecondaryViewPage::View_Released });
00049     }
00050
00051     fire_and_forget SecondaryViewPage::SwitchAndAnimate(int32_t fromViewId)
00052     {
00053         auto lifetime = get_strong();
00054
00055         // This continues the flow from Scenario 3
00056         m_thisViewControl.StartViewInUse();
00057
00058         // Before switching, make this view match the outgoing window
00059         // (go to a blank background)
00060         m_enterAnimation.Begin();
00061         m_enterAnimation.Pause();
00062         m_enterAnimation.Seek(TimeSpan::zero());
00063
00064         // Bring this view onto screen. Since the two view are drawing
00065         // the same visual, the user will not be able to perceive the switch
00066         co_await ApplicationViewSwitcher::SwitchAsync(
00067             ApplicationView::GetForCurrentView().Id(),
00068             fromViewId,
00069             ApplicationViewSwitchingOptions::SkipAnimation);
00070
00071         // Now that this window is on screen, animate in its contents
00072         m_enterAnimation.Begin();
00073         m_thisViewControl.StopViewInUse();
00074     }
00075
00076     void SecondaryViewPage::SetTitle_Click(IInspectable const&, RoutedEventArgs const&)
00077     {
00078         // Set a title for the window. This title is visible
00079          // in system switchers
00080         SetTitle(TitleBox().Text());
00081     }
00082
00083     void SecondaryViewPage::ClearTitle_Click(IInspectable const&, RoutedEventArgs const&)
00084     {
00085         // Clear the title by setting it to blank
00086         SetTitle(L"");
00087         TitleBox().Text(L"");
00088     }
00089
00090     fire_and_forget SecondaryViewPage::SetTitle(hstring newTitle)
00091     {
00092         auto lifetime = get_strong();
00093
00094         auto thisViewId = ApplicationView::GetForCurrentView().Id();
00095         ApplicationView::GetForCurrentView().Title(newTitle);
00096         m_thisViewControl.StartViewInUse();
00097
00098         // The title contained in the ViewLifetimeControl object is bound to
00099         // UI elements on the main thread. So, updating the title
00100         // in this object must be done on the main thread
00101         co_await resume_foreground(SampleState::MainDispatcher);
00102
00103         // We are now in the main window.
00104
00105         // Setting the title on ApplicationView to blank will clear the title in
00106         // the system switcher. It would be good to still have a title in the app's UI.
00107         if (newTitle.empty())
00108         {
00109             newTitle = EMPTY_TITLE;
00110         }
00111
00112         SampleState::UpdateTitle(newTitle, thisViewId);
00113         m_thisViewControl.StopViewInUse();
00114     }
00115
00116     fire_and_forget SecondaryViewPage::View_Released(SDKTemplate::ViewLifetimeControl const& sender, IInspectable const&)
00117     {
00118         auto lifetime = get_strong();
00119
00120         sender.Released(m_releasedToken);
00121
00122         auto thisDispatcher = Window::Current().Dispatcher();
00123
00124         // The ViewLifetimeControl object is bound to U.I elements on the main thread
00125         // So, the object must be removed from that thread
00126         co_await resume_foreground(SampleState::MainDispatcher);
00127
00128         // We are now in the main window.
00129
00130         for (unsigned int i = 0; i < SampleState::SecondaryViews.Size(); i++)
00131         {
00132             auto viewData = SampleState::SecondaryViews.GetAt(i).as<ViewLifetimeControl>();
00133             if (m_thisViewControl.Id() == viewData.Id())
00134             {
00135                 SampleState::SecondaryViews.RemoveAt(i);
00136
00137                 co_await resume_foreground(thisDispatcher);
00138
00139                 // We are now in the secondary window.
00140
00141                 // It's important to make sure no work is scheduled on this thread
00142                 // after it starts to close (no data binding changes, no changes to
00143                 // XAML, creating new objects in destructors, etc.) since
00144                 // that will throw exceptions
00145                 Window::Current().Close();
00146                 co_return;
00147             }
00148         }
00149
00150         throw hresult_error(HRESULT_FROM_WIN32(ERROR_NOT_FOUND), L"ViewID not found in collection");
00151     }
00152
00153     void SecondaryViewPage::HandleProtocolLaunch(Uri const& uri)
00154     {
00155         // This code should only get executed if DisableSystemActivationPolicy
00156         // has not been called.
00157         ProtocolText().Visibility(Visibility::Visible);
00158         ProtocolText().Text(uri.AbsoluteUri());
00159     }
00160
00161     fire_and_forget SecondaryViewPage::ProtocolLaunch_Click(IInspectable const&, RoutedEventArgs const&)
00162     {
00163         auto lifetime = get_strong();
00164
00165         // Used with Scenario 2
00166         m_thisViewControl.StartViewInUse();
00167         co_await Launcher::LaunchUriAsync(Uri(L"multiple-view-sample://basiclaunch/"));
00168         m_thisViewControl.StopViewInUse();
00169     }
00170
00171     fire_and_forget SecondaryViewPage::GoToMain_Click(IInspectable const&, RoutedEventArgs const&)
00172     {
00173         auto lifetime = get_strong();
00174
00175         // Switch to the main view without explicitly requesting
00176         // that this view be hidden
00177         m_thisViewControl.StartViewInUse();
00178         co_await ApplicationViewSwitcher::SwitchAsync(SampleState::MainViewId);
00179         m_thisViewControl.StopViewInUse();
00180     }
00181
00182     fire_and_forget SecondaryViewPage::HideView_Click(IInspectable const&, RoutedEventArgs const&)
00183     {
00184         auto lifetime = get_strong();
00185
00186         m_thisViewControl.StartViewInUse();
00187         co_await ApplicationViewSwitcher::SwitchAsync(
00188             SampleState::MainViewId,
00189             ApplicationView::GetForCurrentView().Id(),
00190             ApplicationViewSwitchingOptions::ConsolidateViews);
00191
00192         m_thisViewControl.StopViewInUse();
00193     }
00194
00195
00196     Storyboard SecondaryViewPage::CreateEnterAnimation()
00197     {
00198         Storyboard enterAnimation;
00199
00200         // Use the AnimationDescription object if available. Otherwise, return an empty storyboard (no animation).
00201         if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent(L"Windows.UI.Core.AnimationMetrics.AnimationDescription"))
00202         {
00203             Storyboard::SetTarget(enterAnimation, LayoutRoot());
00204
00205             AnimationDescription ad(AnimationEffect::EnterPage, AnimationEffectTarget::Primary);
00206             for (unsigned int i = 0; i < LayoutRoot().Children().Size(); i++)
00207             {
00208                 // Add a render transform to the existing one just for animations
00209                 auto element = LayoutRoot().Children().GetAt(i);
00210                 TransformGroup tg;
00211                 tg.Children().Append(TranslateTransform());
00212                 tg.Children().Append(element.RenderTransform());
00213                 element.RenderTransform(tg);
00214
00215                 // Calculate the stagger for each animation. Note that this has a max
00216                 TimeSpan delay = std::min(std::chrono::duration_cast<TimeSpan>(ad.StaggerDelay() * i * ad.StaggerDelayFactor()), ad.DelayLimit());
00217
00218                 for (auto description : ad.Animations())
00219                 {
00220                     DoubleAnimationUsingKeyFrames animation;
00221
00222                     // Start the animation at the right offset
00223                     SplineDoubleKeyFrame startSpline;
00224                     startSpline.KeyTime(KeyTimeHelper::FromTimeSpan(TimeSpan::zero()));
00225                     Storyboard::SetTarget(animation, element);
00226
00227                     // Hold at that offset until the stagger delay is hit
00228                     SplineDoubleKeyFrame middleSpline;
00229                     middleSpline.KeyTime(KeyTimeHelper::FromTimeSpan(delay));
00230
00231                     // Animation from delayed time to last time
00232                     SplineDoubleKeyFrame endSpline;
00233                     KeySpline endSplineKey;
00234                     endSplineKey.ControlPoint1(description.Control1());
00235                     endSplineKey.ControlPoint2(description.Control2());
00236                     endSpline.KeySpline(endSplineKey);
00237                     TimeSpan endKeyTime = description.Duration() + delay;
00238                     endSpline.KeyTime(KeyTimeHelper::FromTimeSpan(endKeyTime));
00239
00240                     // Do the translation
00241                     if (description.Type() == PropertyAnimationType::Translation)
00242                     {
00243                         startSpline.Value(ANIMATION_TRANSLATION_START);
00244                         middleSpline.Value(ANIMATION_TRANSLATION_START);
00245                         endSpline.Value(ANIMATION_TRANSLATION_END);
00246
00247                         Storyboard::SetTargetProperty(animation, L"(UIElement.RenderTransform).(TransformGroup.Children)[0].X");
00248                     }
00249                     // Opacity
00250                     else if (description.Type() == PropertyAnimationType::Opacity)
00251                     {
00252                         startSpline.Value(ANIMATION_OPACITY_START);
00253                         middleSpline.Value(ANIMATION_OPACITY_START);
00254                         endSpline.Value(ANIMATION_OPACITY_END);
00255
00256                         Storyboard::SetTargetProperty(animation, L"Opacity");
00257                     }
00258                     else
00259                     {
00260                         throw hresult_invalid_argument(L"Encountered an unexpected animation type.");
00261                     }
00262
00263                     // Put the final animation together
00264                     animation.KeyFrames().Append(startSpline);
00265                     animation.KeyFrames().Append(middleSpline);
00266                     animation.KeyFrames().Append(endSpline);
00267                     enterAnimation.Children().Append(animation);
00268                 }
00269             }
00270         }
00271
00272         return enterAnimation;
00273     }
00274 }
Generated on Fri Nov 15 2024 22:20:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MIDI/cs/Scenario1_MIDIDeviceEnumeration.xaml.cs Source File

  • MIDI
  • cs

Scenario1_MIDIDeviceEnumeration.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Threading.Tasks;
00016 using Windows.Devices.Enumeration;
00017 using Windows.Devices.Midi;
00018 using Windows.UI.Core;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace MIDI
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class Scenario1_MIDIDeviceEnumeration : Page
00029     {
00030         /// <summary>
00031         /// Main Page
00032         /// </summary>
00033         private MainPage rootPage;
00034
00035         /// <summary>
00036         /// Device watchers for MIDI in and out ports
00037         /// </summary>
00038         MidiDeviceWatcher midiInDeviceWatcher;
00039         MidiDeviceWatcher midiOutDeviceWatcher;
00040
00041         /// <summary>
00042         /// Set the rootpage context when entering the scenario
00043         /// </summary>
00044         /// <param name="e">Event arguments</param>
00045         protected override void OnNavigatedTo(NavigationEventArgs e)
00046         {
00047             this.rootPage = MainPage.Current;
00048         }
00049
00050         /// <summary>
00051         /// Stop the device watchers when leaving the scenario
00052         /// </summary>
00053         /// <param name="e">Event arguments</param>
00054         protected override void OnNavigatedFrom(NavigationEventArgs e)
00055         {
00056             base.OnNavigatedFrom(e);
00057
00058             // Stop the input and output device watchers
00059             this.midiInDeviceWatcher.Stop();
00060             this.midiOutDeviceWatcher.Stop();
00061         }
00062
00063         /// <summary>
00064         /// Constructor: Empty device lists, start the device watchers and
00065         /// set initial states for buttons
00066         /// </summary>
00067         public Scenario1_MIDIDeviceEnumeration()
00068         {
00069             this.InitializeComponent();
00070
00071             // Start with a clean slate
00072             ClearAllDeviceValues();
00073
00074             // Ensure Auto-detect devices toggle is on
00075             this.deviceAutoDetectToggle.IsOn = true;
00076
00077             // Set up the MIDI input and output device watchers
00078             this.midiInDeviceWatcher = new MidiDeviceWatcher(MidiInPort.GetDeviceSelector(), Dispatcher, this.inputDevices);
00079             this.midiOutDeviceWatcher = new MidiDeviceWatcher(MidiOutPort.GetDeviceSelector(), Dispatcher, this.outputDevices);
00080
00081             // Start watching for devices
00082             this.midiInDeviceWatcher.Start();
00083             this.midiOutDeviceWatcher.Start();
00084
00085             // Disable manual enumeration buttons
00086             this.listInputDevicesButton.IsEnabled = false;
00087             this.listOutputDevicesButton.IsEnabled = false;
00088         }
00089
00090         /// <summary>
00091         /// Clear all input and output MIDI device lists and properties
00092         /// </summary>
00093         private void ClearAllDeviceValues()
00094         {
00095             // Clear input devices
00096             this.inputDevices.Items.Clear();
00097             this.inputDevices.Items.Add("Click button to list input MIDI devices");
00098             this.inputDevices.IsEnabled = false;
00099
00100             // Clear output devices
00101             this.outputDevices.Items.Clear();
00102             this.outputDevices.Items.Add("Click button to list output MIDI devices");
00103             this.outputDevices.IsEnabled = false;
00104
00105             // Clear input device properties
00106             this.inputDeviceProperties.Items.Clear();
00107             this.inputDeviceProperties.Items.Add("Select a MIDI input device to view its properties");
00108             this.inputDeviceProperties.IsEnabled = false;
00109
00110             // Clear output device properties
00111             this.outputDeviceProperties.Items.Clear();
00112             this.outputDeviceProperties.Items.Add("Select a MIDI output device to view its properties");
00113             this.outputDeviceProperties.IsEnabled = false;
00114         }
00115
00116         /// <summary>
00117         /// Input button click handler
00118         /// </summary>
00119         /// <param name="sender">Element that fired the event</param>
00120         /// <param name="e">Event arguments</param>
00121         private async void listInputDevicesButton_Click(object sender, RoutedEventArgs e)
00122         {
00123             // Enumerate input devices
00124             await EnumerateMidiInputDevices();
00125         }
00126
00127         /// <summary>
00128         /// Query DeviceInformation class for Midi Input devices
00129         /// </summary>
00130         private async Task EnumerateMidiInputDevices()
00131         {
00132             // Clear input devices
00133             this.inputDevices.Items.Clear();
00134             this.inputDeviceProperties.Items.Clear();
00135             this.inputDeviceProperties.IsEnabled = false;
00136
00137             // Find all input MIDI devices
00138             string midiInputQueryString = MidiInPort.GetDeviceSelector();
00139             DeviceInformationCollection midiInputDevices = await DeviceInformation.FindAllAsync(midiInputQueryString);
00140
00141             // Return if no external devices are connected
00142             if (midiInputDevices.Count == 0)
00143             {
00144                 this.inputDevices.Items.Add("No MIDI input devices found!");
00145                 this.inputDevices.IsEnabled = false;
00146
00147                 this.rootPage.NotifyUser("Please connect at least one external MIDI device for this demo to work correctly", NotifyType.ErrorMessage);
00148                 return;
00149             }
00150
00151             // Else, add each connected input device to the list
00152             foreach (DeviceInformation deviceInfo in midiInputDevices)
00153             {
00154                 this.inputDevices.Items.Add(deviceInfo.Name);
00155                 this.inputDevices.IsEnabled = true;
00156             }
00157
00158             this.rootPage.NotifyUser("MIDI Input devices found!", NotifyType.StatusMessage);
00159         }
00160
00161         /// <summary>
00162         /// Output button click handler
00163         /// </summary>
00164         /// <param name="sender">Element that fired the event</param>
00165         /// <param name="e">Event arguments</param>
00166         private async void listOutputDevicesButton_Click(object sender, RoutedEventArgs e)
00167         {
00168             // Enumerate output devices
00169             await EnumerateMidiOutputDevices();
00170         }
00171
00172         /// <summary>
00173         /// Query DeviceInformation class for Midi Output devices
00174         /// </summary>
00175         private async Task EnumerateMidiOutputDevices()
00176         {
00177             // Clear output devices
00178             this.outputDevices.Items.Clear();
00179             this.outputDeviceProperties.Items.Clear();
00180             this.outputDeviceProperties.IsEnabled = false;
00181
00182             // Find all output MIDI devices
00183             string midiOutputQueryString = MidiOutPort.GetDeviceSelector();
00184             DeviceInformationCollection midiOutputDevices = await DeviceInformation.FindAllAsync(midiOutputQueryString);
00185
00186             // Return if no external devices are connected, and GS synth is not detected
00187             if (midiOutputDevices.Count == 0)
00188             {
00189                 this.outputDevices.Items.Add("No MIDI output devices found!");
00190                 this.outputDevices.IsEnabled = false;
00191
00192                 this.rootPage.NotifyUser("Please connect at least one external MIDI device for this demo to work correctly", NotifyType.ErrorMessage);
00193                 return;
00194             }
00195
00196             // List specific device information for each output device
00197             foreach (DeviceInformation deviceInfo in midiOutputDevices)
00198             {
00199                 this.outputDevices.Items.Add(deviceInfo.Name);
00200                 this.outputDevices.IsEnabled = true;
00201             }
00202
00203             this.rootPage.NotifyUser("MIDI Output devices found!", NotifyType.StatusMessage);
00204         }
00205
00206         /// <summary>
00207         /// Detect the toggle state of the Devicewatcher button.
00208         /// If auto-detect is on, disable manual enumeration buttons and start device watchers
00209         /// If auto-detect is off, enable manual enumeration buttons and stop device watchers
00210         /// </summary>
00211         /// <param name="sender">Element that fired the event</param>
00212         /// <param name="e">Event arguments</param>
00213         private void DeviceAutoDetectToggle_Toggled(object sender, RoutedEventArgs e)
00214         {
00215             if (this.deviceAutoDetectToggle.IsOn)
00216             {
00217                 this.listInputDevicesButton.IsEnabled = false;
00218                 this.listOutputDevicesButton.IsEnabled = false;
00219
00220                 if (this.midiInDeviceWatcher != null)
00221                 {
00222                     this.midiInDeviceWatcher.Start();
00223                 }
00224                 if (this.midiOutDeviceWatcher != null)
00225                 {
00226                     this.midiOutDeviceWatcher.Start();
00227                 }
00228             }
00229             else
00230             {
00231                 this.listInputDevicesButton.IsEnabled = true;
00232                 this.listOutputDevicesButton.IsEnabled = true;
00233
00234                 if (this.midiInDeviceWatcher != null)
00235                 {
00236                     this.midiInDeviceWatcher.Stop();
00237                 }
00238                 if (this.midiOutDeviceWatcher != null)
00239                 {
00240                     this.midiOutDeviceWatcher.Stop();
00241                 }
00242             }
00243         }
00244
00245         /// <summary>
00246         /// Change the active input MIDI device
00247         /// </summary>
00248         /// <param name="sender">Element that fired the event</param>
00249         /// <param name="e">Event arguments</param>
00250         private void inputDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
00251         {
00252             // Get the selected input MIDI device
00253             int selectedInputDeviceIndex = this.inputDevices.SelectedIndex;
00254
00255             // Try to display the appropriate device properties
00256             if (selectedInputDeviceIndex < 0)
00257             {
00258                 // Clear input device properties
00259                 this.inputDeviceProperties.Items.Clear();
00260                 this.inputDeviceProperties.Items.Add("Select a MIDI input device to view its properties");
00261                 this.inputDeviceProperties.IsEnabled = false;
00262                 this.rootPage.NotifyUser("Select a MIDI input device to view its properties", NotifyType.StatusMessage);
00263                 return;
00264             }
00265
00266             DeviceInformationCollection devInfoCollection = this.midiInDeviceWatcher.GetDeviceInformationCollection();
00267             if (devInfoCollection == null)
00268             {
00269                 this.inputDeviceProperties.Items.Clear();
00270                 this.inputDeviceProperties.Items.Add("Device not found!");
00271                 this.inputDeviceProperties.IsEnabled = false;
00272                 this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage);
00273                 return;
00274             }
00275
00276             DeviceInformation devInfo = devInfoCollection[selectedInputDeviceIndex];
00277             if (devInfo == null)
00278             {
00279                 this.inputDeviceProperties.Items.Clear();
00280                 this.inputDeviceProperties.Items.Add("Device not found!");
00281                 this.inputDeviceProperties.IsEnabled = false;
00282                 this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage);
00283                 return;
00284             }
00285
00286             // Display the found properties
00287             DisplayDeviceProperties(devInfo, this.inputDeviceProperties);
00288             this.rootPage.NotifyUser("Device information found!", NotifyType.StatusMessage);
00289         }
00290
00291         /// <summary>
00292         /// Change the active output MIDI device
00293         /// </summary>
00294         /// <param name="sender">Element that fired the event</param>
00295         /// <param name="e">Event arguments</param>
00296         private void outputDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
00297         {
00298             // Get the selected output MIDI device
00299             int selectedOutputDeviceIndex = this.outputDevices.SelectedIndex;
00300
00301             // Try to display the appropriate device properties
00302             if (selectedOutputDeviceIndex < 0)
00303             {
00304                 // Clear output device properties
00305                 this.outputDeviceProperties.Items.Clear();
00306                 this.outputDeviceProperties.Items.Add("Select a MIDI output device to view its properties");
00307                 this.outputDeviceProperties.IsEnabled = false;
00308                 this.rootPage.NotifyUser("Select a MIDI output device to view its properties", NotifyType.StatusMessage);
00309                 return;
00310             }
00311
00312             DeviceInformationCollection devInfoCollection = this.midiOutDeviceWatcher.GetDeviceInformationCollection();
00313             if (devInfoCollection == null)
00314             {
00315                 this.outputDeviceProperties.Items.Clear();
00316                 this.outputDeviceProperties.Items.Add("Device not found!");
00317                 this.outputDeviceProperties.IsEnabled = false;
00318                 this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage);
00319                 return;
00320             }
00321
00322             DeviceInformation devInfo = devInfoCollection[selectedOutputDeviceIndex];
00323             if (devInfo == null)
00324             {
00325                 this.outputDeviceProperties.Items.Clear();
00326                 this.outputDeviceProperties.Items.Add("Device not found!");
00327                 this.outputDeviceProperties.IsEnabled = false;
00328                 this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage);
00329                 return;
00330             }
00331
00332             // Display the found properties
00333             DisplayDeviceProperties(devInfo, this.outputDeviceProperties);
00334             this.rootPage.NotifyUser("Device information found!", NotifyType.StatusMessage);
00335         }
00336
00337         /// <summary>
00338         /// Display the properties of the MIDI device to the user
00339         /// </summary>
00340         /// <param name="devInfo"></param>
00341         /// <param name="propertiesList"></param>
00342         private void DisplayDeviceProperties(DeviceInformation devInfo, ListBox propertiesList)
00343         {
00344             propertiesList.Items.Clear();
00345             propertiesList.Items.Add("Id: " + devInfo.Id);
00346             propertiesList.Items.Add("Name: " + devInfo.Name);
00347             propertiesList.Items.Add("IsDefault: " + devInfo.IsDefault);
00348             propertiesList.Items.Add("IsEnabled: " + devInfo.IsEnabled);
00349             propertiesList.Items.Add("EnclosureLocation: " + devInfo.EnclosureLocation);
00350
00351             // Add device interface information
00352             propertiesList.Items.Add("----Device Interface----");
00353             foreach (var deviceProperty in devInfo.Properties)
00354             {
00355                 propertiesList.Items.Add(deviceProperty.Key + ": " + deviceProperty.Value);
00356             }
00357
00358             propertiesList.IsEnabled = true;
00359         }
00360     }
00361 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MultipleViews/cs/SecondaryViewPage.xaml.cs Source File

  • MultipleViews
  • cs

SecondaryViewPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using SDKTemplate;
00008 using SecondaryViewsHelpers;
00009 using System;
00010 using Windows.System;
00011 using Windows.UI.Core;
00012 using Windows.UI.Core.AnimationMetrics;
00013 using Windows.UI.ViewManagement;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Media;
00017 using Windows.UI.Xaml.Media.Animation;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     // This page is shown in secondary views created by this app.
00023     // See Scenario 1 for details on how to create a secondary view
00024     public sealed partial class SecondaryViewPage : Page
00025     {
00026         const int ANIMATION_TRANSLATION_START = 100;
00027         const int ANIMATION_TRANSLATION_END = 0;
00028         const int ANIMATION_OPACITY_START = 0;
00029         const int ANIMATION_OPACITY_END = 1;
00030
00031         const string EMPTY_TITLE = "<title cleared>";
00032
00033         ViewLifetimeControl thisViewControl;
00034         int mainViewId;
00035         CoreDispatcher mainDispatcher;
00036
00037         public SecondaryViewPage()
00038         {
00039             this.InitializeComponent();
00040         }
00041
00042         protected override void OnNavigatedTo(NavigationEventArgs e)
00043         {
00044             thisViewControl = (ViewLifetimeControl) e.Parameter;
00045             mainViewId = ((App)App.Current).MainViewId;
00046             mainDispatcher = ((App)App.Current).MainDispatcher;
00047
00048             // When this view is finally release, clean up state
00049             thisViewControl.Released += ViewLifetimeControl_Released;
00050         }
00051
00052         private async void GoToMain_Click(object sender, RoutedEventArgs e)
00053         {
00054             // Switch to the main view without explicitly requesting
00055             // that this view be hidden
00056             thisViewControl.StartViewInUse();
00057             await ApplicationViewSwitcher.SwitchAsync(mainViewId);
00058             thisViewControl.StopViewInUse();
00059         }
00060
00061         private async void HideView_Click(object sender, RoutedEventArgs e)
00062         {
00063             // Switch to main and hide this view entirely from the user
00064             thisViewControl.StartViewInUse();
00065             await ApplicationViewSwitcher.SwitchAsync(mainViewId,
00066                 ApplicationView.GetForCurrentView().Id,
00067                 ApplicationViewSwitchingOptions.ConsolidateViews);
00068             thisViewControl.StopViewInUse();
00069         }
00070
00071         private void SetTitle_Click(object sender, RoutedEventArgs e)
00072         {
00073             // Set a title for the window. This title is visible
00074             // in system switchers
00075             SetTitle(TitleBox.Text);
00076         }
00077
00078         private void ClearTitle_Click(object sender, RoutedEventArgs e)
00079         {
00080             // Clear the title by setting it to blank
00081             SetTitle("");
00082             TitleBox.Text = "";
00083         }
00084
00085         private async void SetTitle(string newTitle)
00086         {
00087             var thisViewId = ApplicationView.GetForCurrentView().Id;
00088             ApplicationView.GetForCurrentView().Title = newTitle;
00089             thisViewControl.StartViewInUse();
00090
00091             // The title contained in the ViewLifetimeControl object is bound to
00092             // UI elements on the main thread. So, updating the title
00093             // in this object must be done on the main thread
00094             await mainDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00095             {
00096                 // Setting the title on ApplicationView to blank will clear the title in
00097                 // the system switcher. It would be good to still have a title in the app's UI.
00098                 if (newTitle == "")
00099                 {
00100                     newTitle = EMPTY_TITLE;
00101                 }
00102
00103                 ((App)App.Current).UpdateTitle(newTitle, thisViewId);
00104             });
00105             thisViewControl.StopViewInUse();
00106         }
00107
00108         private async void ViewLifetimeControl_Released(Object sender, EventArgs e)
00109         {
00110             ((ViewLifetimeControl)sender).Released -= ViewLifetimeControl_Released;
00111             // The ViewLifetimeControl object is bound to UI elements on the main thread
00112             // So, the object must be removed from that thread
00113             await mainDispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00114             {
00115                 ((App)App.Current).SecondaryViews.Remove(thisViewControl);
00116             });
00117
00118             // The released event is fired on the thread of the window
00119             // it pertains to.
00120             //
00121             // It's important to make sure no work is scheduled on this thread
00122             // after it starts to close (no data binding changes, no changes to
00123             // XAML, creating new objects in destructors, etc.) since
00124             // that will throw exceptions
00125             Window.Current.Close();
00126         }
00127
00128         public void HandleProtocolLaunch(Uri uri)
00129         {
00130             // This code should only get executed if DisableSystemActivationPolicy
00131             // has not been called.
00132             ProtocolText.Visibility = Visibility.Visible;
00133             ProtocolText.Text = uri.AbsoluteUri;
00134         }
00135
00136         private async void ProtocolLaunch_Click(object sender, RoutedEventArgs e)
00137         {
00138             // The activation will always end up on the same page unless you
00139             // create an external protocol activation.
00140             thisViewControl.StartViewInUse();
00141             await Launcher.LaunchUriAsync(new Uri("multiple-view-sample://basiclaunch/"));
00142             thisViewControl.StopViewInUse();
00143         }
00144
00145         public async void SwitchAndAnimate(int fromViewId)
00146         {
00147             // This continues the flow from Scenario 3
00148             thisViewControl.StartViewInUse();
00149
00150             // Calculate the entrance animation. Recalculate this every time,
00151             // because the animation description can vary (for example,
00152             // if the user changes accessibility settings).
00153             Storyboard enterAnimation = CreateEnterAnimation(LayoutRoot);
00154
00155             // Before switching, make this view match the outgoing window
00156             // (go to a blank background)
00157             enterAnimation.Begin();
00158             enterAnimation.Pause();
00159             enterAnimation.Seek(TimeSpan.FromMilliseconds(0));
00160
00161             // Bring this view onto screen. Since the two view are drawing
00162             // the same visual, the user will not be able to perceive the switch
00163             await ApplicationViewSwitcher.SwitchAsync(ApplicationView.GetForCurrentView().Id,
00164                 fromViewId,
00165                 ApplicationViewSwitchingOptions.SkipAnimation);
00166
00167             // Now that this window is on screen, animate in its contents
00168             enterAnimation.Begin();
00169             thisViewControl.StopViewInUse();
00170         }
00171
00172         private Storyboard CreateEnterAnimation(Panel layoutRoot)
00173         {
00174             var enterAnimation = new Storyboard();
00175
00176             // Use the AnimationDescription object if available. Otherwise, return an empty storyboard (no animation).
00177             if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.Core.AnimationMetrics.AnimationDescription"))
00178             {
00179                 Storyboard.SetTarget(enterAnimation, layoutRoot);
00180
00181                 var ad = new AnimationDescription(AnimationEffect.EnterPage, AnimationEffectTarget.Primary);
00182                 for (int i = 0; i < layoutRoot.Children.Count; i++)
00183                 {
00184                     // Add a render transform to the existing one just for animations
00185                     var element = layoutRoot.Children[i];
00186                     var tg = new TransformGroup();
00187                     tg.Children.Add(new TranslateTransform());
00188                     tg.Children.Add(element.RenderTransform);
00189                     element.RenderTransform = tg;
00190
00191                     // Calculate the stagger for each animation. Note that this has a max
00192                     var delayMs = Math.Min(ad.StaggerDelay.TotalMilliseconds * i * ad.StaggerDelayFactor, ad.DelayLimit.Milliseconds);
00193                     var delay = TimeSpan.FromMilliseconds(delayMs);
00194
00195                     foreach (var description in ad.Animations)
00196                     {
00197                         var animation = new DoubleAnimationUsingKeyFrames();
00198
00199                         // Start the animation at the right offset
00200                         var startSpline = new SplineDoubleKeyFrame();
00201                         startSpline.KeyTime = TimeSpan.FromMilliseconds(0);
00202                         Storyboard.SetTarget(animation, element);
00203
00204                         // Hold at that offset until the stagger delay is hit
00205                         var middleSpline = new SplineDoubleKeyFrame();
00206                         middleSpline.KeyTime = delay;
00207
00208                         // Animation from delayed time to last time
00209                         var endSpline = new SplineDoubleKeyFrame();
00210                         endSpline.KeySpline = new KeySpline() { ControlPoint1 = description.Control1, ControlPoint2 = description.Control2 };
00211                         endSpline.KeyTime = description.Duration + delay;
00212
00213                         // Do the translation
00214                         if (description.Type == PropertyAnimationType.Translation)
00215                         {
00216                             startSpline.Value = ANIMATION_TRANSLATION_START;
00217                             middleSpline.Value = ANIMATION_TRANSLATION_START;
00218                             endSpline.Value = ANIMATION_TRANSLATION_END;
00219
00220                             Storyboard.SetTargetProperty(animation, "(UIElement.RenderTransform).(TransformGroup.Children)[0].X");
00221                         }
00222                         // Opacity
00223                         else if (description.Type == PropertyAnimationType.Opacity)
00224                         {
00225                             startSpline.Value = ANIMATION_OPACITY_START;
00226                             middleSpline.Value = ANIMATION_OPACITY_START;
00227                             endSpline.Value = ANIMATION_OPACITY_END;
00228
00229                             Storyboard.SetTargetProperty(animation, "Opacity");
00230                         }
00231                         else
00232                         {
00233                             throw new Exception("Encountered an unexpected animation type.");
00234                         }
00235
00236                         // Put the final animation together
00237                         animation.KeyFrames.Add(startSpline);
00238                         animation.KeyFrames.Add(middleSpline);
00239                         animation.KeyFrames.Add(endSpline);
00240                         enterAnimation.Children.Add(animation);
00241                     }
00242                 }
00243             }
00244             return enterAnimation;
00245         }
00246     }
00247 }
Generated on Fri Nov 15 2024 22:20:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cs/Scenario2_DecimalFormatting.xaml.cs Source File

  • NumberFormatting
  • cs

Scenario2_DecimalFormatting.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Text;
00013 using Windows.Globalization.NumberFormatting;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario2_DecimalFormatting : Page
00020     {
00021         public Scenario2_DecimalFormatting()
00022         {
00023             this.InitializeComponent();
00024         }
00025
00026         /// <summary>
00027         /// This is the click handler for the 'Display' button.
00028         /// </summary>
00029         /// <param name="sender"></param>
00030         /// <param name="e"></param>
00031         private void Display_Click(object sender, RoutedEventArgs e)
00032         {
00033             // This scenario uses the Windows.Globalization.NumberFormatting.DecimalFormatter class
00034             // to format a number.
00035
00036             // Keep results of the scenario in a StringBuilder
00037             StringBuilder results = new StringBuilder();
00038
00039             // Create formatter initialized using the current user's preference settings.
00040             DecimalFormatter decimalFormat = new Windows.Globalization.NumberFormatting.DecimalFormatter();
00041
00042             // Make a random number.
00043             double randomNumber = (new Random().NextDouble() * 100000);
00044
00045             // Format with the user's default preferences.
00046             String decimalCurrent = decimalFormat.Format(randomNumber);
00047
00048             // Format with grouping.
00049             DecimalFormatter decimalFormat1 = new Windows.Globalization.NumberFormatting.DecimalFormatter();
00050             decimalFormat1.IsGrouped = true;
00051             String decimal1 = decimalFormat1.Format(randomNumber);
00052
00053             // Format with grouping using French.
00054             DecimalFormatter decimalFormatFR = new Windows.Globalization.NumberFormatting.DecimalFormatter(new string[] { "fr-FR" }, "ZZ");
00055             decimalFormatFR.IsGrouped = true;
00056             String decimalFR = decimalFormatFR.Format(randomNumber);
00057
00058             // Illustrate how automatic digit substitution works
00059             DecimalFormatter decimalFormatAR = new Windows.Globalization.NumberFormatting.DecimalFormatter(new string[] { "ar" }, "ZZ");
00060             decimalFormatAR.IsGrouped = true;
00061             String decimalAR = decimalFormatAR.Format(randomNumber);
00062
00063             // Get a fixed number.
00064             ulong fixedNumber = 500;
00065
00066             // Format with the user's default preferences.
00067             String decimal2 = decimalFormat.Format(fixedNumber);
00068
00069             // Format always with a decimal point.
00070             DecimalFormatter decimalFormat3 = new Windows.Globalization.NumberFormatting.DecimalFormatter();
00071             decimalFormat3.IsDecimalPointAlwaysDisplayed = true;
00072             decimalFormat3.FractionDigits = 0;
00073             String decimal3 = decimalFormat3.Format(fixedNumber);
00074
00075             // Format with no fractional digits or decimal point.
00076             DecimalFormatter decimalFormat4 = new Windows.Globalization.NumberFormatting.DecimalFormatter();
00077             decimalFormat4.FractionDigits = 0;
00078             String decimal4 = decimalFormat4.Format(fixedNumber);
00079
00080             // Display the results.
00081             results.AppendLine("Random number (" + randomNumber + ")");
00082             results.AppendLine("With current user preferences: " + decimalCurrent);
00083             results.AppendLine("With grouping separators: " + decimal1);
00084             results.AppendLine("With grouping separators (fr-FR): " + decimalFR);
00085             results.AppendLine("With digit substitution (ar): " + decimalAR);
00086             results.AppendLine();
00087             results.AppendLine("Fixed number (" + fixedNumber + ")");
00088             results.AppendLine("With current user preferences: " + decimal2);
00089             results.AppendLine("Always with a decimal point: " + decimal3);
00090             results.AppendLine("With no fraction digits or decimal points: " + decimal4);
00091
00092             // Display the results
00093             OutputTextBlock.Text = results.ToString();
00094         }
00095     }
00096 }
Generated on Fri Nov 15 2024 22:20:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLInProcessWinRTComponent/cpp/cpp/Scenario4_CustomExceptionWRL.xaml.h Source File

  • WRLInProcessWinRTComponent
  • cpp
  • cpp

Scenario4_CustomExceptionWRL.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008 #include "Scenario4_CustomExceptionWRL.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     namespace WRLInProcessWinRTComponent
00013     {
00014         public ref class CustomExceptionWRL sealed
00015         {
00016         public:
00017             CustomExceptionWRL();
00018
00019         private:
00020             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021         };
00022     }
00023 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_LaunchAppServices Member List

This is the complete list of members for Scenario3_LaunchAppServices, including all inherited members.
ConnectToRemoteAppServiceAsync() | Scenario3_LaunchAppServices | [inline, private]
GenerateRandomNumber_Clicked(object sender, RoutedEventArgs e) | Scenario3_LaunchAppServices | [inline, private]
m_maximumValue | Scenario3_LaunchAppServices | [private]
m_minimumValue | Scenario3_LaunchAppServices | [private]
m_rootPage | Scenario3_LaunchAppServices | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_LaunchAppServices | [inline, protected]
Scenario3_LaunchAppServices() | Scenario3_LaunchAppServices | [inline]
SendMessageToRemoteAppServiceAsync(AppServiceConnection connection) | Scenario3_LaunchAppServices | [inline, private]
SystemList | Scenario3_LaunchAppServices |
UpdateStatus(string status, NotifyType statusType) | Scenario3_LaunchAppServices | [inline, private]
ValidateInput() | Scenario3_LaunchAppServices | [inline, private]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario_SynthesizeText Member List

This is the complete list of members for Scenario_SynthesizeText, including all inherited members.
InitializeListboxVoiceChooser() | Scenario_SynthesizeText | [inline, private]
ListboxVoiceChooser_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario_SynthesizeText | [inline, private]
media_MediaEnded(object sender, RoutedEventArgs e) | Scenario_SynthesizeText | [inline, private]
Scenario_SynthesizeText() | Scenario_SynthesizeText | [inline]
Speak_Click(object sender, RoutedEventArgs e) | Scenario_SynthesizeText | [inline, private]
speechContext | Scenario_SynthesizeText | [private]
speechResourceMap | Scenario_SynthesizeText | [private]
synthesizer | Scenario_SynthesizeText | [private]
Generated on Fri Nov 15 2024 22:24:01 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackButton/cs/App.xaml.cs Source File

  • BackButton
  • cs

App.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel;
00014 using Windows.ApplicationModel.Activation;
00015 using Windows.UI.Core;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// Provides application-specific behavior to supplement the default Application class.
00026     /// </summary>
00027     sealed partial class App : Application
00028     {
00029         /// <summary>
00030         /// Initializes the singleton application object.  This is the first line of authored code
00031         /// executed, and as such is the logical equivalent of main() or WinMain().
00032         /// </summary>
00033         public App()
00034         {
00035             this.InitializeComponent();
00036             this.Construct();
00037         }
00038
00039         /// <summary>
00040         /// Invoked when the application is launched normally by the end user.  Other entry points
00041         /// will be used such as when the application is launched to open a specific file.
00042         /// </summary>
00043         /// <param name="e">Details about the launch request and process.</param>
00044         protected override void OnLaunched(LaunchActivatedEventArgs e)
00045         {
00046
00047 #if DEBUG
00048             if (System.Diagnostics.Debugger.IsAttached)
00049             {
00050                 this.DebugSettings.EnableFrameRateCounter = false;
00051             }
00052 #endif
00053
00054             Frame rootFrame = Window.Current.Content as Frame;
00055
00056             // Do not repeat app initialization when the Window already has content,
00057             // just ensure that the window is active
00058             if (rootFrame == null)
00059             {
00060                 // Create a Frame to act as the navigation context and navigate to the first page
00061                 rootFrame = new Frame();
00062                 // Set the default language
00063                 rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
00064
00065                 rootFrame.NavigationFailed += OnNavigationFailed;
00066
00067                 if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
00068                 {
00069                     //TODO: Load state from previously suspended application
00070                 }
00071
00072                 // Place the frame in the current Window
00073                 Window.Current.Content = rootFrame;
00074             }
00075
00076             if (rootFrame.Content == null)
00077             {
00078                 // When the navigation stack isn't restored navigate to the first page,
00079                 // configuring the new page by passing required information as a navigation
00080                 // parameter
00081                 rootFrame.Navigate(typeof(MainPage), e.Arguments);
00082             }
00083
00084             // Register a global back event handler. This can be registered on a per-page-bases if you only have a subset of your pages
00085             // that needs to handle back or if you want to do page-specific logic before deciding to navigate back on those pages.
00086             SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;
00087
00088             // Ensure the current window is active
00089             Window.Current.Activate();
00090         }
00091
00092         /// <summary>
00093         /// Invoked when a user issues a global back on the device.
00094         /// If the app has no in-app back stack left for the current view/frame the user may be navigated away
00095         /// back to the previous app in the system's app back stack or to the start screen.
00096         /// In windowed mode on desktop there is no system app back stack and the user will stay in the app even when the in-app back stack is depleted.
00097         /// </summary>
00098         /// <param name="sender"></param>
00099         /// <param name="e"></param>
00100         private void App_BackRequested(object sender, BackRequestedEventArgs e)
00101         {
00102             Frame rootFrame = Window.Current.Content as Frame;
00103             if (rootFrame == null)
00104                 return;
00105
00106             // If we can go back and the event has not already been handled, do so.
00107             if (rootFrame.CanGoBack && e.Handled == false)
00108             {
00109                 e.Handled = true;
00110                 rootFrame.GoBack();
00111             }
00112         }
00113
00114         /// <summary>
00115         /// Invoked when Navigation to a certain page fails
00116         /// </summary>
00117         /// <param name="sender">The Frame which failed navigation</param>
00118         /// <param name="e">Details about the navigation failure</param>
00119         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00120         {
00121             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00122         }
00123
00124         // Add any application contructor code in here.
00125         partial void Construct();
00126     }
00127 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Json/cppwinrt/User.cpp Source File

  • Json
  • cppwinrt

User.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "User.h"
00014 #include "User.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace winrt::Windows::Data::Json;
00018
00019 namespace winrt::SDKTemplate::implementation
00020 {
00021     User::User(hstring const& jsonString)
00022     {
00023         JsonObject jsonObject = JsonObject::Parse(jsonString);
00024         m_id = jsonObject.GetNamedString(idKey, L"");
00025
00026         IJsonValue phoneJsonValue = jsonObject.GetNamedValue(phoneKey);
00027         if (phoneJsonValue.ValueType() == JsonValueType::Null)
00028         {
00029             m_phone = {};
00030         }
00031         else
00032         {
00033             m_phone = phoneJsonValue.GetString();
00034         }
00035
00036         m_name = jsonObject.GetNamedString(nameKey, L"");
00037         m_timezone = jsonObject.GetNamedNumber(timezoneKey, 0.0);
00038         m_verified = jsonObject.GetNamedBoolean(verifiedKey, false);
00039
00040         for (IJsonValue jsonValue : jsonObject.GetNamedArray(educationKey, {}))
00041         {
00042             m_education.Append(SDKTemplate::School(jsonValue.GetObject()));
00043         }
00044     }
00045
00046     hstring User::Stringify()
00047     {
00048         JsonObject jsonObject;
00049
00050         jsonObject.SetNamedValue(idKey, JsonValue::CreateStringValue(m_id));
00051
00052         // Treating a blank string as null
00053         if (m_phone.empty())
00054         {
00055             jsonObject.SetNamedValue(phoneKey, JsonValue::CreateNullValue());
00056         }
00057         else
00058         {
00059             jsonObject.SetNamedValue(phoneKey, JsonValue::CreateStringValue(m_phone));
00060         }
00061
00062         jsonObject.SetNamedValue(nameKey, JsonValue::CreateStringValue(m_name));
00063         jsonObject.SetNamedValue(timezoneKey, JsonValue::CreateNumberValue(m_timezone));
00064         jsonObject.SetNamedValue(verifiedKey, JsonValue::CreateBooleanValue(m_verified));
00065
00066         JsonArray jsonArray;
00067         for (SDKTemplate::School school : m_education)
00068         {
00069             jsonArray.Append(school.ToJsonObject());
00070         }
00071
00072         // JsonObject can also be treated as an IMap.
00073         jsonObject.Insert(educationKey, jsonArray);
00074
00075         return jsonObject.Stringify();
00076     }
00077 }
Generated on Fri Nov 15 2024 22:20:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MainPage_SaveFile Member List

This is the complete list of members for MainPage_SaveFile, including all inherited members.
MainPage_SaveFile() | MainPage_SaveFile | [inline]
SaveFileButton_Click(object sender, RoutedEventArgs e) | MainPage_SaveFile | [inline, private]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
Initialize() | ScenarioElement | [inline, private]
Replace_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
UserControl_Loaded(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
Generated on Fri Nov 15 2024 22:23:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInteractionMode/cppwinrt/Scenario1_Basic.cpp Source File

  • UserInteractionMode
  • cppwinrt

Scenario1_Basic.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_Basic.h"
00014 #include "Scenario1_Basic.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::UI::Core;
00019 using namespace Windows::UI::ViewManagement;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Data;
00022 using namespace Windows::UI::Xaml::Navigation;
00023
00024 namespace winrt::SDKTemplate::implementation
00025 {
00026     Scenario1_Basic::Scenario1_Basic()
00027     {
00028         InitializeComponent();
00029     }
00030
00031     void Scenario1_Basic::OnNavigatedTo(NavigationEventArgs const&)
00032     {
00033         rootPage = MainPage::Current();
00034
00035         // The SizeChanged event is raised when the user interaction mode changes.
00036         windowResizeToken = Window::Current().SizeChanged({ get_weak(), &Scenario1_Basic::OnWindowResize });
00037         UpdateContent();
00038     }
00039
00040     void Scenario1_Basic::OnNavigatedFrom(NavigationEventArgs const&)
00041     {
00042         Window::Current().SizeChanged(windowResizeToken);
00043     }
00044
00045     void Scenario1_Basic::OnWindowResize(IInspectable const&, WindowSizeChangedEventArgs const&)
00046     {
00047         UpdateContent();
00048     }
00049
00050     void Scenario1_Basic::UpdateContent()
00051     {
00052         m_interactionMode = UIViewSettings::GetForCurrentView().UserInteractionMode();
00053
00054         // Update styles
00055         m_checkBoxStyle = InteractionMode() == UserInteractionMode::Mouse ? MouseCheckBoxStyle() : TouchCheckBoxStyle();
00056
00057         m_propertyChanged(*this, PropertyChangedEventArgs(L"InteractionMode"));
00058         m_propertyChanged(*this, PropertyChangedEventArgs(L"CheckBoxStyle"));
00059     }
00060
00061     event_token Scenario1_Basic::PropertyChanged(PropertyChangedEventHandler const& handler)
00062     {
00063         return m_propertyChanged.add(handler);
00064     }
00065
00066     void Scenario1_Basic::PropertyChanged(event_token const& token) noexcept
00067     {
00068         m_propertyChanged.remove(token);
00069     }
00070 }
Generated on Fri Nov 15 2024 22:19:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicSuspension/cs/Common/SuspensionManager.cs Source File

  • BasicSuspension
  • cs
  • Common

SuspensionManager.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.IO;
00015 using System.Linq;
00016 using System.Runtime.Serialization;
00017 using System.Text;
00018 using System.Threading.Tasks;
00019 using Windows.ApplicationModel;
00020 using Windows.Storage;
00021 using Windows.Storage.Streams;
00022 using Windows.UI.Xaml;
00023 using Windows.UI.Xaml.Controls;
00024
00025 namespace SDKTemplate.Common
00026 {
00027     /// <summary>
00028     /// SuspensionManager captures global session state to simplify process lifetime management
00029     /// for an application.  Note that session state will be automatically cleared under a variety
00030     /// of conditions and should only be used to store information that would be convenient to
00031     /// carry across sessions, but that should be discarded when an application crashes or is
00032     /// upgraded.
00033     /// </summary>
00034     internal sealed class SuspensionManager
00035     {
00036         private static Dictionary<string, object> _sessionState = new Dictionary<string, object>();
00037         private static List<Type> _knownTypes = new List<Type>();
00038         private const string sessionStateFilename = "_sessionState.xml";
00039
00040         /// <summary>
00041         /// Provides access to global session state for the current session.  This state is
00042         /// serialized by <see cref="SaveAsync"/> and restored by
00043         /// <see cref="RestoreAsync"/>, so values must be serializable by
00044         /// <see cref="DataContractSerializer"/> and should be as compact as possible.  Strings
00045         /// and other self-contained data types are strongly recommended.
00046         /// </summary>
00047         public static Dictionary<string, object> SessionState
00048         {
00049             get { return _sessionState; }
00050         }
00051
00052         /// <summary>
00053         /// List of custom types provided to the <see cref="DataContractSerializer"/> when
00054         /// reading and writing session state.  Initially empty, additional types may be
00055         /// added to customize the serialization process.
00056         /// </summary>
00057         public static List<Type> KnownTypes
00058         {
00059             get { return _knownTypes; }
00060         }
00061
00062         /// <summary>
00063         /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00064         /// registered with <see cref="RegisterFrame"/> will also preserve their current
00065         /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00066         /// to save its state.
00067         /// </summary>
00068         /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00069         public static async Task SaveAsync()
00070         {
00071             try
00072             {
00073                 // Save the navigation state for all registered frames
00074                 foreach (var weakFrameReference in _registeredFrames)
00075                 {
00076                     Frame frame;
00077                     if (weakFrameReference.TryGetTarget(out frame))
00078                     {
00079                         SaveFrameNavigationState(frame);
00080                     }
00081                 }
00082
00083                 // Serialize the session state synchronously to avoid asynchronous access to shared
00084                 // state
00085                 MemoryStream sessionData = new MemoryStream();
00086                 DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
00087                 serializer.WriteObject(sessionData, _sessionState);
00088
00089                 // Get an output stream for the SessionState file and write the state asynchronously
00090                 StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
00091                 using (Stream fileStream = await file.OpenStreamForWriteAsync())
00092                 {
00093                     sessionData.Seek(0, SeekOrigin.Begin);
00094                     await sessionData.CopyToAsync(fileStream);
00095                 }
00096             }
00097             catch (Exception e)
00098             {
00099                 throw new SuspensionManagerException(e);
00100             }
00101         }
00102
00103         /// <summary>
00104         /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00105         /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00106         /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00107         /// state.
00108         /// </summary>
00109         /// <param name="sessionBaseKey">An optional key that identifies the type of session.
00110         /// This can be used to distinguish between multiple application launch scenarios.</param>
00111         /// <returns>An asynchronous task that reflects when session state has been read.  The
00112         /// content of <see cref="SessionState"/> should not be relied upon until this task
00113         /// completes.</returns>
00114         public static async Task RestoreAsync(String sessionBaseKey = null)
00115         {
00116             _sessionState = new Dictionary<String, Object>();
00117
00118             try
00119             {
00120                 // Get the input stream for the SessionState file
00121                 StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename);
00122                 using (IInputStream inStream = await file.OpenSequentialReadAsync())
00123                 {
00124                     // Deserialize the Session State
00125                     DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
00126                     _sessionState = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
00127                 }
00128
00129                 // Restore any registered frames to their saved state
00130                 foreach (var weakFrameReference in _registeredFrames)
00131                 {
00132                     Frame frame;
00133                     if (weakFrameReference.TryGetTarget(out frame) && (string)frame.GetValue(FrameSessionBaseKeyProperty) == sessionBaseKey)
00134                     {
00135                         frame.ClearValue(FrameSessionStateProperty);
00136                         RestoreFrameNavigationState(frame);
00137                     }
00138                 }
00139             }
00140             catch (Exception e)
00141             {
00142                 throw new SuspensionManagerException(e);
00143             }
00144         }
00145
00146         private static DependencyProperty FrameSessionStateKeyProperty =
00147             DependencyProperty.RegisterAttached("_FrameSessionStateKey", typeof(String), typeof(SuspensionManager), null);
00148         private static DependencyProperty FrameSessionBaseKeyProperty =
00149             DependencyProperty.RegisterAttached("_FrameSessionBaseKeyParams", typeof(String), typeof(SuspensionManager), null);
00150         private static DependencyProperty FrameSessionStateProperty =
00151             DependencyProperty.RegisterAttached("_FrameSessionState", typeof(Dictionary<String, Object>), typeof(SuspensionManager), null);
00152         private static List<WeakReference<Frame>> _registeredFrames = new List<WeakReference<Frame>>();
00153
00154         /// <summary>
00155         /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00156         /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00157         /// immediately after creation if they will participate in session state management.  Upon
00158         /// registration if state has already been restored for the specified key
00159         /// the navigation history will immediately be restored.  Subsequent invocations of
00160         /// <see cref="RestoreAsync"/> will also restore navigation history.
00161         /// </summary>
00162         /// <param name="frame">An instance whose navigation history should be managed by
00163         /// <see cref="SuspensionManager"/></param>
00164         /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00165         /// store navigation-related information.</param>
00166         /// <param name="sessionBaseKey">An optional key that identifies the type of session.
00167         /// This can be used to distinguish between multiple application launch scenarios.</param>
00168         public static void RegisterFrame(Frame frame, String sessionStateKey, String sessionBaseKey = null)
00169         {
00170             if (frame.GetValue(FrameSessionStateKeyProperty) != null)
00171             {
00172                 throw new InvalidOperationException("Frames can only be registered to one session state key");
00173             }
00174
00175             if (frame.GetValue(FrameSessionStateProperty) != null)
00176             {
00177                 throw new InvalidOperationException("Frames must be either be registered before accessing frame session state, or not registered at all");
00178             }
00179
00180             if (!string.IsNullOrEmpty(sessionBaseKey))
00181             {
00182                 frame.SetValue(FrameSessionBaseKeyProperty, sessionBaseKey);
00183                 sessionStateKey = sessionBaseKey + "_" + sessionStateKey;
00184             }
00185
00186             // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00187             // navigation state should be managed
00188             frame.SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00189             _registeredFrames.Add(new WeakReference<Frame>(frame));
00190
00191             // Check to see if navigation state can be restored
00192             RestoreFrameNavigationState(frame);
00193         }
00194
00195         /// <summary>
00196         /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00197         /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00198         /// removed.
00199         /// </summary>
00200         /// <param name="frame">An instance whose navigation history should no longer be
00201         /// managed.</param>
00202         public static void UnregisterFrame(Frame frame)
00203         {
00204             // Remove session state and remove the frame from the list of frames whose navigation
00205             // state will be saved (along with any weak references that are no longer reachable)
00206             SessionState.Remove((String)frame.GetValue(FrameSessionStateKeyProperty));
00207             _registeredFrames.RemoveAll((weakFrameReference) =>
00208             {
00209                 Frame testFrame;
00210                 return !weakFrameReference.TryGetTarget(out testFrame) || testFrame == frame;
00211             });
00212         }
00213
00214         /// <summary>
00215         /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00216         /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00217         /// their session state saved and restored automatically as a part of the global
00218         /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00219         /// that can still be useful when restoring pages that have been discarded from the
00220         /// navigation cache.
00221         /// </summary>
00222         /// <remarks>Apps may choose to rely on <see cref="NavigationHelper"/> to manage
00223         /// page-specific state instead of working with frame session state directly.</remarks>
00224         /// <param name="frame">The instance for which session state is desired.</param>
00225         /// <returns>A collection of state subject to the same serialization mechanism as
00226         /// <see cref="SessionState"/>.</returns>
00227         public static Dictionary<String, Object> SessionStateForFrame(Frame frame)
00228         {
00229             var frameState = (Dictionary<String, Object>)frame.GetValue(FrameSessionStateProperty);
00230
00231             if (frameState == null)
00232             {
00233                 var frameSessionKey = (String)frame.GetValue(FrameSessionStateKeyProperty);
00234                 if (frameSessionKey != null)
00235                 {
00236                     // Registered frames reflect the corresponding session state
00237                     if (!_sessionState.ContainsKey(frameSessionKey))
00238                     {
00239                         _sessionState[frameSessionKey] = new Dictionary<String, Object>();
00240                     }
00241                     frameState = (Dictionary<String, Object>)_sessionState[frameSessionKey];
00242                 }
00243                 else
00244                 {
00245                     // Frames that aren't registered have transient state
00246                     frameState = new Dictionary<String, Object>();
00247                 }
00248                 frame.SetValue(FrameSessionStateProperty, frameState);
00249             }
00250             return frameState;
00251         }
00252
00253         private static void RestoreFrameNavigationState(Frame frame)
00254         {
00255             var frameState = SessionStateForFrame(frame);
00256             if (frameState.ContainsKey("Navigation"))
00257             {
00258                 frame.SetNavigationState((String)frameState["Navigation"]);
00259             }
00260         }
00261
00262         private static void SaveFrameNavigationState(Frame frame)
00263         {
00264             var frameState = SessionStateForFrame(frame);
00265             frameState["Navigation"] = frame.GetNavigationState();
00266         }
00267     }
00268     public class SuspensionManagerException : Exception
00269     {
00270         public SuspensionManagerException()
00271         {
00272         }
00273
00274         public SuspensionManagerException(Exception e)
00275             : base("SuspensionManager failed", e)
00276         {
00277
00278         }
00279     }
00280 }
Generated on Fri Nov 15 2024 22:18:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PedometerBackgroundTask Member List

This is the complete list of members for PedometerBackgroundTask, including all inherited members.
OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) | PedometerBackgroundTask | [inline, private]
Run(IBackgroundTaskInstance taskInstance) | PedometerBackgroundTask | [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraAdvancedCapture/cpp/pch.cpp Source File

  • CameraAdvancedCapture
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSensors/cpp/pch.cpp Source File

  • CustomSensors
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Files Member List

This is the complete list of members for Scenario1_Files, including all inherited members.
ChooseFile_Click(object sender, RoutedEventArgs e) | Scenario1_Files | [inline, private]
ChooseFolder_Click(object sender, RoutedEventArgs e) | Scenario1_Files | [inline, private]
DisplayOutput() | Scenario1_Files | [inline, private]
filename | Scenario1_Files | [private]
Increment_Local_Click(Object sender, RoutedEventArgs e) | Scenario1_Files | [inline, private]
Increment_LocalCache_Click(Object sender, RoutedEventArgs e) | Scenario1_Files | [inline, private]
Increment_Temporary_Click(Object sender, RoutedEventArgs e) | Scenario1_Files | [inline, private]
localCacheCounter | Scenario1_Files | [private]
localCacheFolder | Scenario1_Files | [private]
localCounter | Scenario1_Files | [private]
localFolder | Scenario1_Files | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_Files | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_Files | [inline, protected]
ProtectL1_Click(object sender, RoutedEventArgs e) | Scenario1_Files | [inline, private]
ProtectL2_Click(object sender, RoutedEventArgs e) | Scenario1_Files | [inline, private]
Read_Local_Counter() | Scenario1_Files | [inline, private]
Read_LocalCache_Counter() | Scenario1_Files | [inline, private]
Read_Temporary_Counter() | Scenario1_Files | [inline, private]
ReportStatus(string operation, UserDataStorageItemProtectionStatus status) | Scenario1_Files | [inline, private]
rootPage | Scenario1_Files | [private]
Scenario1_Files() | Scenario1_Files | [inline]
Scenario1_Files() | Scenario1_Files | [inline]
selectedItem | Scenario1_Files | [private]
temporaryCounter | Scenario1_Files | [private]
temporaryFolder | Scenario1_Files | [private]
Unprotect_Click(object sender, RoutedEventArgs e) | Scenario1_Files | [inline, private]
UpdateItem(IStorageItem item) | Scenario1_Files | [inline, private]
userDataProtectionManager | Scenario1_Files | [private]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraAdvancedCapture/cpp/MainPage.xaml.cpp Source File

  • CameraAdvancedCapture
  • cpp

MainPage.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include <sstream>
00015 #include <math.h>
00016 #include <ctime>
00017
00018 using namespace CameraAdvancedCapture;
00019 using namespace Concurrency;
00020 using namespace Platform;
00021 using namespace Windows::Devices::Sensors;
00022 using namespace Windows::Devices::Enumeration;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::Graphics::Imaging;
00026 using namespace Windows::Graphics::Display;
00027 using namespace Windows::Media;
00028 using namespace Windows::Media::Core;
00029 using namespace Windows::Phone::UI::Input;
00030 using namespace Windows::UI::Xaml;
00031 using namespace Windows::UI::Xaml::Controls;
00032 using namespace Windows::UI::Xaml::Controls::Primitives;
00033 using namespace Windows::UI::Xaml::Data;
00034 using namespace Windows::UI::Xaml::Media;
00035 using namespace Windows::UI::Xaml::Navigation;
00036 using namespace Windows::Storage;
00037
00038 MainPage::MainPage()
00039     : _mediaCapture(nullptr)
00040     , _isInitialized(false)
00041     , _isPreviewing(false)
00042     , _externalCamera(false)
00043     , _mirroringPreview(false)
00044     , _advancedCaptureMode(-1)
00045     , CERTAINTY_CAP(0.7)
00046     , _advancedCapture(nullptr)
00047     , _sceneAnalysisEffect(nullptr)
00048     , _deviceOrientation(SimpleOrientation::NotRotated)
00049     , _displayOrientation(DisplayOrientations::Portrait)
00050     , _displayRequest(ref new Windows::System::Display::DisplayRequest())
00051     , RotationKey({ 0xC380465D, 0x2271, 0x428C,{ 0x9B, 0x83, 0xEC, 0xEA, 0x3B, 0x4A, 0x85, 0xC1 } })
00052     , _captureFolder(nullptr)
00053 {
00054     this->InitializeComponent();
00055
00056     _orientationSensor = SimpleOrientationSensor::GetDefault();
00057     _displayInformation = DisplayInformation::GetForCurrentView();
00058     _systemMediaControls = SystemMediaTransportControls::GetForCurrentView();
00059
00060     // Do not cache the state of the UI when suspending/navigating
00061     Page::NavigationCacheMode = Navigation::NavigationCacheMode::Disabled;
00062
00063     // Useful to know when to initialize/clean up the camera
00064     _applicationSuspendingEventToken =
00065         Application::Current->Suspending += ref new SuspendingEventHandler(this, &MainPage::Application_Suspending);
00066     _applicationResumingEventToken =
00067         Application::Current->Resuming += ref new EventHandler<Object^>(this, &MainPage::Application_Resuming);
00068
00069     // Set the maximum on the progress bar
00070     HdrImpactBar->Maximum = CERTAINTY_CAP;
00071 }
00072
00073 MainPage::~MainPage()
00074 {
00075     Application::Current->Suspending -= _applicationSuspendingEventToken;
00076     Application::Current->Resuming -= _applicationResumingEventToken;
00077 }
00078
00079 /// <summary>
00080 /// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI
00081 /// </summary>
00082 /// <returns></returns>
00083 task<void> MainPage::InitializeCameraAsync()
00084 {
00085     WriteLine("InitializeCameraAsync");
00086
00087     // Get available devices for capturing pictures
00088     return FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel::Back)
00089         .then([this](DeviceInformation^ camera)
00090     {
00091         if (camera == nullptr)
00092         {
00093             WriteLine("No camera device found!");
00094             return;
00095         }
00096         // Figure out where the camera is located to account for mirroring and later adjust rotation accordingly
00097         if (camera->EnclosureLocation == nullptr || camera->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Unknown)
00098         {
00099             // No information on the location of the camera, assume it's an external camera, not integrated on the device
00100             _externalCamera = true;
00101         }
00102         else
00103         {
00104             // Camera is fixed on the device
00105             _externalCamera = false;
00106
00107             // Only mirror the preview if the camera is on the front panel
00108             _mirroringPreview = (camera->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Front);
00109         }
00110
00111         _mediaCapture = ref new Capture::MediaCapture();
00112
00113         // Register for a notification when something goes wrong
00114         _mediaCaptureFailedEventToken =
00115             _mediaCapture->Failed += ref new Capture::MediaCaptureFailedEventHandler(this, &MainPage::MediaCapture_Failed);
00116
00117         auto settings = ref new Capture::MediaCaptureInitializationSettings();
00118         settings->VideoDeviceId = camera->Id;
00119         settings->StreamingCaptureMode = Capture::StreamingCaptureMode::AudioAndVideo;
00120
00121         // Initialize media capture, start the preview, kick off scene analysis, enable Advanced Capture
00122         create_task(_mediaCapture->InitializeAsync(settings))
00123             .then([this]()
00124         {
00125             _isInitialized = true;
00126
00127             return StartPreviewAsync();
00128         }).then([this]()
00129         {
00130             return CreateSceneAnalysisEffectAsync();
00131         }).then([this]()
00132         {
00133             return EnableAdvancedCaptureAsync();
00134         // Different return types, must do the error checking here since we cannot return and send
00135         // execeptions back up the chain.
00136         }).then([this](task<void> previousTask)
00137         {
00138             try
00139             {
00140                 previousTask.get();
00141             }
00142             catch (AccessDeniedException^)
00143             {
00144                 WriteLine("The app was denied access to the camera");
00145             }
00146
00147             // Update the controls to reflect the current state of the app
00148             UpdateUi();
00149         });
00150
00151     });
00152 }
00153
00154 /// <summary>
00155 /// Cleans up the camera resources (after stopping any video recording and/or preview if necessary) and unregisters from MediaCapture events
00156 /// </summary>
00157 /// <returns></returns>
00158 Concurrency::task<void> MainPage::CleanupCameraAsync()
00159 {
00160     WriteLine("CleanupCameraAsync");
00161
00162     std::vector<task<void>> taskList;
00163
00164     if (_isInitialized)
00165     {
00166         if (_isPreviewing)
00167         {
00168             auto stopPreviewTask = create_task(StopPreviewAsync());
00169             taskList.push_back(stopPreviewTask);
00170         }
00171
00172         if (_advancedCapture)
00173         {
00174             auto disableAdvancedCaptureTask = create_task(DisableAdvancedCaptureAsync());
00175             taskList.push_back(disableAdvancedCaptureTask);
00176         }
00177
00178         if (_sceneAnalysisEffect)
00179         {
00180             auto cleanSceneAnalysisTask = create_task(CleanSceneAnalysisEffectAsync());
00181             taskList.push_back(cleanSceneAnalysisTask);
00182         }
00183
00184         _isInitialized = false;
00185     }
00186
00187     // When all our tasks complete, clean up MediaCapture
00188     return when_all(taskList.begin(), taskList.end())
00189         .then([this]()
00190     {
00191         if (_mediaCapture != nullptr)
00192         {
00193             _mediaCapture->Failed -= _mediaCaptureFailedEventToken;
00194             _mediaCapture = nullptr;
00195         }
00196     });
00197 }
00198
00199 /// <summary>
00200 /// Starts the preview and adjusts it for for rotation and mirroring after making a request to keep the screen on
00201 /// </summary>
00202 /// <returns></returns>
00203 task<void> MainPage::StartPreviewAsync()
00204 {
00205     // Prevent the device from sleeping while the preview is running
00206     _displayRequest->RequestActive();
00207
00208     // Set the preview source in the UI and mirror it if necessary
00209     PreviewControl->Source = _mediaCapture.Get();
00210     PreviewControl->FlowDirection = _mirroringPreview ? Windows::UI::Xaml::FlowDirection::RightToLeft : Windows::UI::Xaml::FlowDirection::LeftToRight;
00211
00212     // Start the preview
00213     return create_task(_mediaCapture->StartPreviewAsync())
00214         .then([this](task<void> previousTask)
00215     {
00216         _isPreviewing = true;
00217
00218         // Only need to update the orientation if the camera is mounted on the device
00219         if (!_externalCamera)
00220         {
00221             return SetPreviewRotationAsync();
00222         }
00223
00224         // Not external, just return the previous task
00225         return previousTask;
00226     });
00227 }
00228
00229 /// <summary>
00230 /// Gets the current orientation of the UI in relation to the device (when AutoRotationPreferences cannot be honored) and applies a corrective rotation to the preview
00231 /// </summary>
00232 /// <returns></returns>
00233 task<void> MainPage::SetPreviewRotationAsync()
00234 {
00235     // Calculate which way and how far to rotate the preview
00236     int rotationDegrees = ConvertDisplayOrientationToDegrees(_displayOrientation);
00237
00238     // The rotation direction needs to be inverted if the preview is being mirrored
00239     if (_mirroringPreview)
00240     {
00241         rotationDegrees = (360 - rotationDegrees) % 360;
00242     }
00243
00244     // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames
00245     auto props = _mediaCapture->VideoDeviceController->GetMediaStreamProperties(Capture::MediaStreamType::VideoPreview);
00246     props->Properties->Insert(RotationKey, rotationDegrees);
00247     return create_task(_mediaCapture->SetEncodingPropertiesAsync(Capture::MediaStreamType::VideoPreview, props, nullptr));
00248 }
00249
00250 /// <summary>
00251 /// Stops the preview and deactivates a display request, to allow the screen to go into power saving modes
00252 /// </summary>
00253 /// <returns></returns>
00254 task<void> MainPage::StopPreviewAsync()
00255 {
00256     _isPreviewing = false;
00257
00258     return create_task(_mediaCapture->StopPreviewAsync())
00259         .then([this]()
00260     {
00261         // Use the dispatcher because this method is sometimes called from non-UI threads
00262         return Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00263         {
00264             // Cleanup the UI
00265             PreviewControl->Source = nullptr;
00266             // Allow the device screen to sleep now that the preview is stopped
00267             _displayRequest->RequestRelease();
00268         }));
00269     });
00270 }
00271
00272 /// <summary>
00273 /// Adds scene analysis to the video preview stream, registers for its event, enables it, and gets the effect instance
00274 /// </summary>
00275 /// <returns></returns>
00276 task<void> MainPage::CreateSceneAnalysisEffectAsync()
00277 {
00278     // Create the definition, which will contain some initialization settings
00279     auto definition = ref new SceneAnalysisEffectDefinition();
00280
00281     // Add the effect to the video preview stream
00282     return create_task(_mediaCapture->AddVideoEffectAsync(definition, Capture::MediaStreamType::VideoPreview))
00283         .then([this](IMediaExtension^ effect)
00284     {
00285         _sceneAnalysisEffect = safe_cast<SceneAnalysisEffect^>(effect);
00286
00287         WriteLine("SA effect added to pipeline");
00288
00289         // Subscribe to notifications about scene information
00290         _sceneAnalyzedEventToken =
00291             _sceneAnalysisEffect->SceneAnalyzed += ref new TypedEventHandler<SceneAnalysisEffect^, SceneAnalyzedEventArgs^>(this, &MainPage::SceneAnalysisEffect_SceneAnalyzed);
00292
00293         // Enable HDR analysis
00294         _sceneAnalysisEffect->HighDynamicRangeAnalyzer->Enabled = true;
00295     });
00296 }
00297
00298 /// <summary>
00299 /// Disables and removes the scene analysis effect, and unregisters the event handler for the SceneAnalyzed event of the effect
00300 /// </summary>
00301 /// <returns></returns>
00302 task<void> MainPage::CleanSceneAnalysisEffectAsync()
00303 {
00304     // Disable detection
00305     _sceneAnalysisEffect->HighDynamicRangeAnalyzer->Enabled = false;
00306
00307     _sceneAnalysisEffect->SceneAnalyzed -= _sceneAnalyzedEventToken;
00308
00309     // Remove the effect from the pipeline (see ClearEffectsAsync method to remove all effects from a given stream)
00310     return create_task(_mediaCapture->RemoveEffectAsync(_sceneAnalysisEffect))
00311         .then([this]()
00312     {
00313         WriteLine("SceneAnalysis effect removed from pipeline");
00314
00315         // Clear the member variable that held the effect instance
00316         _sceneAnalysisEffect = nullptr;
00317     });
00318 }
00319
00320 /// <summary>
00321 /// Creates an instance of the AdvancedPhotoCapture and registers for its events
00322 /// </summary>
00323 /// <returns></returns>
00324 Concurrency::task<void> MainPage::EnableAdvancedCaptureAsync()
00325 {
00326     // No work to be done if there already is an AdvancedCapture
00327     if (_advancedCapture != nullptr)
00328     {
00329         return EmptyTask();
00330     }
00331
00332     // Configure one of the modes in the control
00333     CycleAdvancedCaptureMode();
00334
00335     // Prepare for an Advanced Capture
00336     return create_task(_mediaCapture->PrepareAdvancedPhotoCaptureAsync(Windows::Media::MediaProperties::ImageEncodingProperties::CreateJpeg()))
00337         .then([this](Capture::AdvancedPhotoCapture^ advancedCapture)
00338     {
00339         WriteLine("Enabled Advanced Capture");
00340
00341         _advancedCapture = advancedCapture;
00342
00343         // Register for events published by the AdvancedCapture
00344         _allPhotosCapturedEventToken =
00345             _advancedCapture->AllPhotosCaptured += ref new TypedEventHandler<Capture::AdvancedPhotoCapture^, Object^>(this, &MainPage::AdvancedCapture_AllPhotosCaptured);
00346         _optionalRefPhotoCapturedEventToken =
00347             _advancedCapture->OptionalReferencePhotoCaptured += ref new TypedEventHandler<Capture::AdvancedPhotoCapture^, Capture::OptionalReferencePhotoCapturedEventArgs^>(this, &MainPage::AdvancedCapture_OptionalReferencePhotoCaptured);
00348     });
00349 }
00350
00351 /// <summary>
00352 /// Configures the AdvancedPhotoControl to the next supported mode
00353 /// </summary>
00354 /// <remarks>
00355 /// Note that this method can be safely called regardless of whether the AdvancedPhotoCapture is in the "prepared
00356 /// state" or not. Internal changes to the mode will be applied  when calling Prepare, or when calling Capture if
00357 /// the mode has been changed since the call to Prepare. This allows for fast changing of desired capture modes,
00358 /// that can more quickly adapt to rapidly changing shooting conditions.
00359 /// </remarks>
00360 void MainPage::CycleAdvancedCaptureMode()
00361 {
00362     // Calculate the index for the next supported mode
00363     _advancedCaptureMode = (_advancedCaptureMode + 1) % _mediaCapture->VideoDeviceController->AdvancedPhotoControl->SupportedModes->Size;
00364
00365     // Configure the settings object to the mode at the calculated index
00366     auto settings = ref new Devices::AdvancedPhotoCaptureSettings();
00367     settings->Mode = _mediaCapture->VideoDeviceController->AdvancedPhotoControl->SupportedModes->GetAt(_advancedCaptureMode);
00368
00369     // Configure the mode on the control
00370     _mediaCapture->VideoDeviceController->AdvancedPhotoControl->Configure(settings);
00371
00372     // Update the button text to reflect the current mode
00373     ModeTextBlock->Text = _mediaCapture->VideoDeviceController->AdvancedPhotoControl->Mode.ToString();
00374 }
00375
00376 /// <summary>
00377 /// Cleans up the instance of the AdvancedCapture
00378 /// </summary>
00379 /// <returns></returns>
00380 Concurrency::task<void> MainPage::DisableAdvancedCaptureAsync()
00381 {
00382     // No work to be done if there is no AdvancedCapture
00383     if (_advancedCapture == nullptr)
00384     {
00385         return EmptyTask();
00386     }
00387
00388     return create_task(_advancedCapture->FinishAsync())
00389         .then([this]()
00390     {
00391         _advancedCapture = nullptr;
00392
00393         // Reset the Advanced Capture Mode index
00394         _advancedCaptureMode = -1;
00395
00396         WriteLine("Disabled Advanced Capture");
00397     });
00398 }
00399
00400 /// <summary>
00401 /// Takes an Advanced Capture photo to a StorageFile and adds rotation metadata to it
00402 /// </summary>
00403 /// <returns></returns>
00404 task<void> MainPage::TakeAdvancedCapturePhotoAsync()
00405 {
00406     // Lock the UI as a simple way to prevent reentrancy
00407     PhotoButton->IsEnabled = false;
00408     CycleModeButton->IsEnabled = false;
00409
00410     // Take the picture
00411     WriteLine("Taking Advanced Capture photo...");
00412
00413     // Create a context object, to identify the capture in the OptionalReferencePhotoCaptured event
00414     auto context = ref new AdvancedCaptureContext();
00415
00416     // Create file based off the current time
00417     context->CaptureFileName = L"AdvancedCapturePhoto_" + GetTimeStr() + L".jpg";
00418     context->CaptureOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
00419
00420     return create_task(_advancedCapture->CaptureAsync(context))
00421         .then([this, context](Capture::AdvancedCapturedPhoto^ photo)
00422     {
00423         context->Photo = photo;
00424         return create_task(_captureFolder->CreateFileAsync(context->CaptureFileName, CreationCollisionOption::GenerateUniqueName));
00425     }).then([this, context](StorageFile^ file)
00426     {
00427         WriteLine("Advanced Capture photo taken! Saving to " + file->Path);
00428         return ReencodeAndSavePhotoAsync(context->Photo->Frame, file, context->CaptureOrientation);
00429     }).then([this](task<void> previousTask)
00430     {
00431         try
00432         {
00433             previousTask.get();
00434         }
00435         catch (Exception^ ex)
00436         {
00437             // File I/O errors are reported as exceptions
00438             WriteException(ex);
00439         }
00440
00441         // Re-enable the buttons to reflect the current state of the app
00442         UpdateUi();
00443     });
00444 }
00445
00446 /// <summary>
00447 /// Attempts to find and return a device mounted on the panel specified, and on failure to find one it will return the first device listed
00448 /// </summary>
00449 /// <param name="panel">The desired panel on which the returned device should be mounted, if available</param>
00450 /// <returns></returns>
00451 task<DeviceInformation^> MainPage::FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel panel)
00452 {
00453     // Get available devices for capturing pictures
00454     auto allVideoDevices = DeviceInformation::FindAllAsync(DeviceClass::VideoCapture);
00455
00456     auto deviceEnumTask = create_task(allVideoDevices);
00457     return deviceEnumTask.then([panel](DeviceInformationCollection^ devices)
00458     {
00459         for (auto cameraDeviceInfo : devices)
00460         {
00461             if (cameraDeviceInfo->EnclosureLocation != nullptr && cameraDeviceInfo->EnclosureLocation->Panel == panel)
00462             {
00463                 return cameraDeviceInfo;
00464             }
00465         }
00466
00467         // Nothing matched, just return the first
00468         if (devices->Size > 0)
00469         {
00470             return devices->GetAt(0);
00471         }
00472
00473         // We didn't find any devices, so return a null instance
00474         DeviceInformation^ camera = nullptr;
00475         return camera;
00476     });
00477 }
00478
00479 /// <summary>
00480 /// Applies the given orientation to a photo stream and saves it as a StorageFile
00481 /// </summary>
00482 /// <param name="stream">The photo stream</param>
00483 /// <param name="photoOrientation">The orientation metadata to apply to the photo</param>
00484 /// <returns></returns>
00485 task<void> MainPage::ReencodeAndSavePhotoAsync(Streams::IRandomAccessStream^ stream, StorageFile^ file, FileProperties::PhotoOrientation photoOrientation)
00486 {
00487     // Using this state variable to pass multiple values through our task chain
00488     ReencodeState^ state = ref new ReencodeState();
00489     state->File = file;
00490     state->Orientation = photoOrientation;
00491
00492     return create_task(BitmapDecoder::CreateAsync(stream))
00493         .then([state](BitmapDecoder^ decoder)
00494     {
00495         state->Decoder = decoder;
00496         return create_task(state->File->OpenAsync(FileAccessMode::ReadWrite));
00497     }).then([state](Streams::IRandomAccessStream^ outputStream)
00498     {
00499         return create_task(BitmapEncoder::CreateForTranscodingAsync(outputStream, state->Decoder));
00500     }).then([state](BitmapEncoder^ encoder)
00501     {
00502         state->Encoder = encoder;
00503         auto properties = ref new Windows::Graphics::Imaging::BitmapPropertySet();
00504         properties->Insert("System.Photo.Orientation", ref new BitmapTypedValue((unsigned short)state->Orientation, Windows::Foundation::PropertyType::UInt16));
00505
00506         return create_task(state->Encoder->BitmapProperties->SetPropertiesAsync(properties));
00507     }).then([state]()
00508     {
00509         return state->Encoder->FlushAsync();
00510     });
00511 }
00512
00513 /// <summary>
00514 /// This method will enable/disable the buttons depending on the current state of the app
00515 /// </summary>
00516 void MainPage::UpdateUi()
00517 {
00518     // The buttons should only be enabled if the preview started sucessfully
00519     PhotoButton->IsEnabled = _isPreviewing;
00520     CycleModeButton->IsEnabled = _isPreviewing;
00521 }
00522
00523 /// <summary>
00524 /// Attempts to lock the page orientation, hide the StatusBar (on Phone) and registers event handlers for hardware buttons and orientation sensors
00525 /// </summary>
00526 /// <returns></returns>
00527 task<void> MainPage::SetupUiAsync()
00528 {
00529     // Attempt to lock page to landscape orientation to prevent the CaptureElement from rotating, as this gives a better experience
00530     DisplayInformation::AutoRotationPreferences = DisplayOrientations::Landscape;
00531
00532     RegisterEventHandlers();
00533
00534      // Populate orientation variables with the current state
00535     _displayOrientation = _displayInformation->CurrentOrientation;
00536     if (_orientationSensor != nullptr)
00537     {
00538         _deviceOrientation = _orientationSensor->GetCurrentOrientation();
00539     }
00540
00541     create_task(StorageLibrary::GetLibraryAsync(KnownLibraryId::Pictures))
00542         .then([this](StorageLibrary^ picturesLibrary)
00543     {
00544         _captureFolder = picturesLibrary->SaveFolder;
00545         if (_captureFolder == nullptr)
00546         {
00547             // In this case fall back to the local app storage since the Pictures Library is not available
00548             _captureFolder = ApplicationData::Current->LocalFolder;
00549         }
00550     });
00551
00552     // Hide the status bar
00553     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00554     {
00555         return create_task(Windows::UI::ViewManagement::StatusBar::GetForCurrentView()->HideAsync());
00556     }
00557     else
00558     {
00559         return EmptyTask();
00560     }
00561 }
00562
00563 /// <summary>
00564 /// Unregisters event handlers for hardware buttons and orientation sensors, allows the StatusBar (on Phone) to show, and removes the page orientation lock
00565 /// </summary>
00566 /// <returns></returns>
00567 task<void> MainPage::CleanupUiAsync()
00568 {
00569     UnregisterEventHandlers();
00570
00571     // Revert orientation preferences
00572     DisplayInformation::AutoRotationPreferences = DisplayOrientations::None;
00573
00574     // Show the status bar
00575     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00576     {
00577         return create_task(Windows::UI::ViewManagement::StatusBar::GetForCurrentView()->ShowAsync());
00578     }
00579     else
00580     {
00581         return EmptyTask();
00582     }
00583 }
00584
00585 /// <summary>
00586 /// Registers event handlers for hardware buttons and orientation sensors, and performs an initial update of the UI rotation
00587 /// </summary>
00588 void MainPage::RegisterEventHandlers()
00589 {
00590     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00591     {
00592         _hardwareCameraButtonEventToken =
00593             HardwareButtons::CameraPressed += ref new Windows::Foundation::EventHandler<CameraEventArgs^>(this, &MainPage::HardwareButtons_CameraPress);
00594     }
00595
00596     // If there is an orientation sensor present on the device, register for notifications
00597     if (_orientationSensor != nullptr)
00598     {
00599         _orientationChangedEventToken =
00600             _orientationSensor->OrientationChanged += ref new TypedEventHandler<SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^>(this, &MainPage::OrientationSensor_OrientationChanged);
00601
00602         // Update orientation of buttons with the current orientation
00603         UpdateControlOrientation();
00604     }
00605
00606     CycleModeButton->Click += ref new RoutedEventHandler(this, &MainPage::CycleModeButton_Click);
00607
00608     _displayInformationEventToken =
00609         _displayInformation->OrientationChanged += ref new TypedEventHandler<DisplayInformation^, Object^>(this, &MainPage::DisplayInformation_OrientationChanged);
00610
00611     _mediaControlPropChangedEventToken =
00612         _systemMediaControls->PropertyChanged += ref new TypedEventHandler<SystemMediaTransportControls^, SystemMediaTransportControlsPropertyChangedEventArgs^>(this, &MainPage::SystemMediaControls_PropertyChanged);
00613 }
00614
00615 /// <summary>
00616 /// Unregisters event handlers for hardware buttons and orientation sensors
00617 /// </summary>
00618 void MainPage::UnregisterEventHandlers()
00619 {
00620     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00621     {
00622         HardwareButtons::CameraPressed -= _hardwareCameraButtonEventToken;
00623     }
00624
00625     if (_orientationSensor != nullptr)
00626     {
00627         _orientationSensor->OrientationChanged -= _orientationChangedEventToken;
00628     }
00629
00630     _displayInformation->OrientationChanged -= _displayInformationEventToken;
00631     _systemMediaControls->PropertyChanged -= _mediaControlPropChangedEventToken;
00632 }
00633
00634 /// <summary>
00635 /// Writes a given string to the output window
00636 /// </summary>
00637 /// <param name="str">String to be written</param>
00638 void MainPage::WriteLine(String^ str)
00639 {
00640     std::wstringstream wStringstream;
00641     wStringstream << str->Data() << "\n";
00642     OutputDebugString(wStringstream.str().c_str());
00643 }
00644
00645 /// <summary>
00646 /// Writes a given exception message and hresult to the output window
00647 /// </summary>
00648 /// <param name="ex">Exception to be written</param>
00649 void MainPage::WriteException(Exception^ ex)
00650 {
00651     std::wstringstream wStringstream;
00652     wStringstream << "0x" << ex->HResult << ": " << ex->Message->Data();
00653     OutputDebugString(wStringstream.str().c_str());
00654 }
00655
00656 /// <summary>
00657 /// Sometimes we need to conditionally return a task. If certain parameters are not met we cannot
00658 /// return null, but we can return a task that does nothing.
00659 /// </summary>
00660 /// <returns></returns>
00661 task<void> MainPage::EmptyTask()
00662 {
00663     return create_task([] {});
00664 }
00665
00666 /// <summary>
00667 /// Helper that gets the current time in HH-MM-SS format
00668 /// </summary>
00669 /// <returns>String with the current time</returns>
00670 String^ MainPage::GetTimeStr()
00671 {
00672     wchar_t temp[10];
00673     __time32_t rawtime;
00674     struct tm timeinfo;
00675
00676     _time32(&rawtime);
00677     _localtime32_s(&timeinfo, &rawtime);
00678
00679     wcsftime(temp, 10, L"%I-%M-%S", &timeinfo);
00680     return ref new String(temp);
00681 }
00682
00683 /// <summary>
00684 /// Helper function to remove characters from a string
00685 /// </summary>
00686 /// <param name="string">String we are removing characters from</param>
00687 /// <param name="removalStr">String to be removed</param>
00688 /// <param name="replacementStr">String to be added</param>
00689 /// <returns>True as long as the start is not -1</returns> todo
00690 bool MainPage::StringReplace(std::wstring& string, const std::wstring& removalStr, const std::wstring& replacementStr)
00691 {
00692     // Find the start of the string to replace
00693     size_t startPos = string.find(removalStr);
00694
00695     // If we can't find the string, return false
00696     if (startPos == std::string::npos)
00697     {
00698         return false;
00699     }
00700
00701     // Replace the string we found with the new value
00702     string.replace(startPos, removalStr.length(), replacementStr);
00703     return true;
00704 }
00705
00706 /// <summary>
00707 /// Calculates the current camera orientation from the device orientation by taking into account whether the camera is external or facing the user
00708 /// </summary>
00709 /// <returns>The camera orientation in space, with an inverted rotation in the case the camera is mounted on the device and is facing the user</returns>
00710 SimpleOrientation MainPage::GetCameraOrientation()
00711 {
00712     if (_externalCamera)
00713     {
00714         // Cameras that are not attached to the device do not rotate along with it, so apply no rotation
00715         return SimpleOrientation::NotRotated;
00716     }
00717
00718     auto result = _deviceOrientation;
00719
00720     // Account for the fact that, on portrait-first devices, the camera sensor is mounted at a 90 degree offset to the native orientation
00721     if (_displayInformation->NativeOrientation == DisplayOrientations::Portrait) {
00722         switch (result) {
00723         case SimpleOrientation::Rotated90DegreesCounterclockwise:
00724             result = SimpleOrientation::NotRotated;
00725             break;
00726         case SimpleOrientation::Rotated180DegreesCounterclockwise:
00727             result = SimpleOrientation::Rotated90DegreesCounterclockwise;
00728             break;
00729         case SimpleOrientation::Rotated270DegreesCounterclockwise:
00730             result = SimpleOrientation::Rotated180DegreesCounterclockwise;
00731             break;
00732         case SimpleOrientation::NotRotated:
00733         default:
00734             result = SimpleOrientation::Rotated270DegreesCounterclockwise;
00735             break;
00736         }
00737     }
00738
00739     // If the preview is being mirrored for a front-facing camera, then the rotation should be inverted
00740     if (_mirroringPreview)
00741     {
00742         // This only affects the 90 and 270 degree cases, because rotating 0 and 180 degrees is the same clockwise and counter-clockwise
00743         switch (_deviceOrientation)
00744         {
00745         case SimpleOrientation::Rotated90DegreesCounterclockwise:
00746             return SimpleOrientation::Rotated270DegreesCounterclockwise;
00747         case SimpleOrientation::Rotated270DegreesCounterclockwise:
00748             return SimpleOrientation::Rotated90DegreesCounterclockwise;
00749         }
00750     }
00751
00752     return result;
00753 }
00754
00755 /// <summary>
00756 /// Converts the given orientation of the device in space to the metadata that can be added to captured photos
00757 /// </summary>
00758 /// <param name="orientation">The orientation of the device in space</param>
00759 /// <returns></returns>
00760 FileProperties::PhotoOrientation MainPage::ConvertOrientationToPhotoOrientation(SimpleOrientation orientation)
00761 {
00762     switch (orientation)
00763     {
00764     case SimpleOrientation::Rotated90DegreesCounterclockwise:
00765         return FileProperties::PhotoOrientation::Rotate90;
00766     case SimpleOrientation::Rotated180DegreesCounterclockwise:
00767         return FileProperties::PhotoOrientation::Rotate180;
00768     case SimpleOrientation::Rotated270DegreesCounterclockwise:
00769         return FileProperties::PhotoOrientation::Rotate270;
00770     case SimpleOrientation::NotRotated:
00771     default:
00772         return FileProperties::PhotoOrientation::Normal;
00773     }
00774 }
00775
00776 /// <summary>
00777 /// Converts the given orientation of the device in space to the corresponding rotation in degrees
00778 /// </summary>
00779 /// <param name="orientation">The orientation of the device in space</param>
00780 /// <returns>An orientation in degrees</returns>
00781 int MainPage::ConvertDeviceOrientationToDegrees(SimpleOrientation orientation)
00782 {
00783     switch (orientation)
00784     {
00785     case SimpleOrientation::Rotated90DegreesCounterclockwise:
00786         return 90;
00787     case SimpleOrientation::Rotated180DegreesCounterclockwise:
00788         return 180;
00789     case SimpleOrientation::Rotated270DegreesCounterclockwise:
00790         return 270;
00791     case SimpleOrientation::NotRotated:
00792     default:
00793         return 0;
00794     }
00795 }
00796
00797 /// <summary>
00798 /// Converts the given orientation of the app on the screen to the corresponding rotation in degrees
00799 /// </summary>
00800 /// <param name="orientation">The orientation of the app on the screen</param>
00801 /// <returns>An orientation in degrees</returns>
00802 int MainPage::ConvertDisplayOrientationToDegrees(DisplayOrientations orientation)
00803 {
00804     switch (orientation)
00805     {
00806     case DisplayOrientations::Portrait:
00807         return 90;
00808     case DisplayOrientations::LandscapeFlipped:
00809         return 180;
00810     case DisplayOrientations::PortraitFlipped:
00811         return 270;
00812     case DisplayOrientations::Landscape:
00813     default:
00814         return 0;
00815     }
00816 }
00817
00818 /// <summary>
00819 /// Uses the current device orientation in space and page orientation on the screen to calculate the rotation
00820 /// transformation to apply to the controls
00821 /// </summary>
00822 void MainPage::UpdateControlOrientation()
00823 {
00824     int currDeviceOrientation = ConvertDeviceOrientationToDegrees(_deviceOrientation);
00825     int currDisplayOrientation = ConvertDisplayOrientationToDegrees(_displayOrientation);
00826
00827     if (_displayInformation->NativeOrientation == DisplayOrientations::Portrait)
00828     {
00829         currDeviceOrientation -= 90;
00830     }
00831
00832     // Combine both rotations and make sure that 0 <= result < 360
00833     auto angle = (360 + currDisplayOrientation + currDeviceOrientation) % 360;
00834
00835     // Rotate the buttons in the UI to match the rotation of the device
00836     auto transform = ref new RotateTransform();
00837     transform->Angle = angle;
00838
00839     // The RenderTransform is safe to use (i.e. it won't cause layout issues) in this case, because these buttons have a 1:1 aspect ratio
00840     PhotoButton->RenderTransform = transform;
00841     CycleModeButton->RenderTransform = transform;
00842
00843     // Adjust which way the progress bar fills so it's always from the user's left->right or bottom->top
00844     HdrImpactBar->FlowDirection = (angle == 180 || angle == 270) ? Windows::UI::Xaml::FlowDirection::RightToLeft : Windows::UI::Xaml::FlowDirection::LeftToRight;
00845 }
00846
00847 void MainPage::Application_Suspending(Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e)
00848 {
00849     // Handle global application events only if this page is active
00850     if (Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name)
00851     {
00852         auto deferral = e->SuspendingOperation->GetDeferral();
00853         CleanupUiAsync()
00854             .then([this, deferral]()
00855         {
00856             CleanupCameraAsync();
00857         }).then([this, deferral]()
00858         {
00859             deferral->Complete();
00860         });
00861     }
00862 }
00863
00864 void MainPage::Application_Resuming(Platform::Object^ sender, Platform::Object^ args)
00865 {
00866     // Handle global application events only if this page is active
00867     if (Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name)
00868     {
00869         SetupUiAsync();
00870         InitializeCameraAsync();
00871     }
00872 }
00873
00874 void MainPage::DisplayInformation_OrientationChanged(DisplayInformation^ sender, Object^ args)
00875 {
00876     // This event will fire when the page is rotated, when the DisplayInformation.AutoRotationPreferences
00877     // value set in the SetupUiAsync() method cannot be not honored
00878     if (_isPreviewing)
00879     {
00880         SetPreviewRotationAsync();
00881     }
00882
00883     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00884     {
00885         UpdateControlOrientation();
00886     }));
00887 }
00888
00889 /// <summary>
00890 /// This event will be raised every time the effect processes a preview frame, to deliver information about the current scene in the camera preview.
00891 /// </summary>
00892 /// <param name="sender">The effect raising the event.</param>
00893 /// <param name="args">The event data.</param>
00894 void MainPage::SceneAnalysisEffect_SceneAnalyzed(SceneAnalysisEffect^ sender, SceneAnalyzedEventArgs^ args)
00895 {
00896     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, args]()
00897     {
00898         // Update the graphical representation of how much detail could be recovered through an HDR capture, ranging
00899         // from 0 ("everything is within the dynamic range of the camera") to CERTAINTY_CAP ("at this point the app
00900         // strongly recommends an HDR capture"), where CERTAINTY_CAP can be any number between 0 and 1 that the app chooses.
00901         HdrImpactBar->Value = min(CERTAINTY_CAP, args->ResultFrame->HighDynamicRange->Certainty);
00902
00903         SceneTypeTextBlock->Text = "Scene: " + args->ResultFrame->AnalysisRecommendation.ToString();
00904     }));
00905 }
00906
00907 void MainPage::CycleModeButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00908 {
00909     CycleAdvancedCaptureMode();
00910 }
00911
00912 void MainPage::PhotoButton_Click(Object^, Windows::UI::Xaml::RoutedEventArgs^)
00913 {
00914     TakeAdvancedCapturePhotoAsync();
00915 }
00916
00917 /// <summary>
00918 /// In the event of the app being minimized this method handles media property change events. If the app receives a mute
00919 /// notification, it is no longer in the foregroud.
00920 /// </summary>
00921 /// <param name="sender"></param>
00922 /// <param name="args"></param>
00923 void MainPage::SystemMediaControls_PropertyChanged(SystemMediaTransportControls^ sender, SystemMediaTransportControlsPropertyChangedEventArgs^ args)
00924 {
00925     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, sender, args]()
00926     {
00927         // Only handle this event if this page is currently being displayed
00928         if (args->Property == SystemMediaTransportControlsProperty::SoundLevel && Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name)
00929         {
00930             // Check to see if the app is being muted. If so, it is being minimized.
00931             // Otherwise if it is not initialized, it is being brought into focus.
00932             if (sender->SoundLevel == SoundLevel::Muted)
00933             {
00934                 CleanupCameraAsync();
00935             }
00936             else if (!_isInitialized)
00937             {
00938                 InitializeCameraAsync();
00939             }
00940         }
00941     }));
00942 }
00943
00944 /// <summary>
00945 /// Occurs each time the simple orientation sensor reports a new sensor reading.
00946 /// </summary>
00947 /// <param name="args">The event data.</param>
00948 void MainPage::OrientationSensor_OrientationChanged(SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^ args)
00949 {
00950     // If the device is parallel to the ground, keep the last orientation used. This allows users to take pictures of documents (FaceUp)
00951     // or the ceiling (FaceDown) in any orientation, by first holding the device in the desired orientation, and then pointing the camera
00952     // at the desired subject.
00953     if (args->Orientation != SimpleOrientation::Faceup && args->Orientation != SimpleOrientation::Facedown)
00954     {
00955         _deviceOrientation = args->Orientation;
00956
00957         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00958         {
00959             UpdateControlOrientation();
00960         }));
00961     }
00962 }
00963
00964 void MainPage::HardwareButtons_CameraPress(Platform::Object^, Windows::Phone::UI::Input::CameraEventArgs^)
00965 {
00966     TakeAdvancedCapturePhotoAsync();
00967 }
00968
00969 /// <summary>
00970 /// This event will be raised only on devices that support returning a reference photo, which is a normal exposure of the scene
00971 /// without processing, also referred to as "EV0".
00972 /// </summary>
00973 /// <param name="sender">The object raising this event.</param>
00974 /// <param name="args">The event data.</param>
00975 void MainPage::AdvancedCapture_OptionalReferencePhotoCaptured(Capture::AdvancedPhotoCapture^ sender, Capture::OptionalReferencePhotoCapturedEventArgs^ args)
00976 {
00977     // Retrieve the context (i.e. the information about the capture this event belongs to)
00978     auto context = static_cast<AdvancedCaptureContext^>(args->Context);
00979
00980     // Hold a reference to the frame and filename before the async file creation operation so they're not cleaned up before ReencodeAndSavePhotoAsync
00981     auto frame = args->Frame;
00982
00983     // Add "_Reference" at the end of the filename to create when saving the reference photo
00984     std::wstringstream fileName;
00985     fileName << context->CaptureFileName->Data();
00986     auto strName = fileName.str();
00987     StringReplace(strName, std::wstring(L".jpg"), std::wstring(L"_Reference.jpg"));
00988
00989     create_task(_captureFolder->CreateFileAsync(ref new String(strName.c_str()), CreationCollisionOption::GenerateUniqueName))
00990         .then([this, frame, context](StorageFile^ file)
00991     {
00992         WriteLine("AdvancedCapture_OptionalReferencePhotoCaptured for " + context->CaptureFileName + ". Saving to " + file->Path);
00993         ReencodeAndSavePhotoAsync(frame, file, context->CaptureOrientation);
00994     });
00995 }
00996
00997 /// <summary>
00998 /// This event will be raised when all the necessary captures are completed, and at this point the camera is technically ready
00999 /// to capture again while the processing takes place.
01000 /// </summary>
01001 /// <param name="sender">The object raising this event.</param>
01002 /// <param name="args">The event data.</param>
01003 void MainPage::AdvancedCapture_AllPhotosCaptured(Capture::AdvancedPhotoCapture^ sender, Object^ args)
01004 {
01005     WriteLine("AdvancedCapture_AllPhotosCaptured");
01006 }
01007
01008 void MainPage::MediaCapture_Failed(Capture::MediaCapture ^currentCaptureObject, Capture::MediaCaptureFailedEventArgs^ errorEventArgs)
01009 {
01010     std::wstringstream ss;
01011     ss << "MediaCapture_Failed: 0x" << errorEventArgs->Code << ": " << errorEventArgs->Message->Data();
01012     WriteLine(ref new String(ss.str().c_str()));
01013
01014     CleanupCameraAsync()
01015         .then([this]()
01016     {
01017         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
01018         {
01019             UpdateUi();
01020         }));
01021     });
01022 }
01023
01024 void MainPage::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
01025 {
01026     SetupUiAsync();
01027     InitializeCameraAsync();
01028 }
01029
01030 void MainPage::OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e)
01031 {
01032     // Handling of this event is included for completeness, as it will only fire when navigating between pages and this sample only includes one page
01033     CleanupCameraAsync();
01034     CleanupUiAsync();
01035 }
Generated on Fri Nov 15 2024 22:16:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cpp/SampleConfiguration.cpp Source File

  • Pedometer
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Events", "SDKTemplate.Scenario1_Events" },
00021     { "History", "SDKTemplate.Scenario2_History" },
00022     { "Current step count", "SDKTemplate.Scenario3_CurrentStepCount" },
00023     { "Background Pedometer", "SDKTemplate.Scenario4_BackgroundTask" }
00024 };
Generated on Fri Nov 15 2024 22:17:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/ShareApplicationLink.xaml.cpp Source File

  • ShareSource
  • cpp

ShareApplicationLink.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ShareApplicationLink.xaml.cpp
00014 // Implementation of the ShareApplicationLink class
00015 //
00016
00017 #include "pch.h"
00018 #include "ShareApplicationLink.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::ApplicationModel::DataTransfer;
00025 using namespace Windows::UI;
00026 using namespace Windows::Storage::Streams;
00027
00028 ShareApplicationLink::ShareApplicationLink()
00029 {
00030     InitializeComponent();
00031
00032     // Populate the ApplicationLinkComboBox with the application links for all of the scenarios
00033     auto scenarioList = ref new Platform::Collections::Vector<Object^>();
00034     Uri^ itemToSelect = nullptr;
00035     for (unsigned int i = 0; i < SDKTemplate::MainPage::scenarios->Length; ++i)
00036     {
00037         Scenario s = MainPage::scenarios[i];
00038         Uri^ applicationLink = SharePage::GetApplicationLink(s.ClassName);
00039         scenarioList->Append(applicationLink);
00040         if (s.ClassName->Equals(GetType()->FullName))
00041         {
00042             itemToSelect = applicationLink;
00043         }
00044     }
00045     ApplicationLinkComboBox->ItemsSource = scenarioList;
00046     ApplicationLinkComboBox->SelectedItem = itemToSelect; // Default selection to the application link for this scenario
00047 }
00048
00049 bool ShareApplicationLink::GetShareContent(DataRequest^ request)
00050 {
00051     bool succeeded = false;
00052
00053     Uri^ selectedApplicationLink = dynamic_cast<Uri^>(ApplicationLinkComboBox->SelectedItem);
00054     if (selectedApplicationLink != nullptr)
00055     {
00056         request->Data->Properties->Title = TitleInputBox->Text;
00057         request->Data->Properties->Description = DescriptionInputBox->Text;
00058         request->Data->Properties->ContentSourceApplicationLink = ApplicationLink;
00059         request->Data->SetApplicationLink(selectedApplicationLink);
00060
00061         // Place the selected logo and the background color in the data package properties
00062         if (MicrosoftLogo->IsChecked->Value)
00063         {
00064             request->Data->Properties->Square30x30Logo = RandomAccessStreamReference::CreateFromUri(ref new Uri("ms-appx:///assets/microsoftLogo.png"));
00065             request->Data->Properties->LogoBackgroundColor = GetLogoBackgroundColor();
00066         }
00067         else if (VisualStudioLogo->IsChecked->Value)
00068         {
00069             request->Data->Properties->Square30x30Logo = RandomAccessStreamReference::CreateFromUri(ref new Uri("ms-appx:///assets/visualStudioLogo.png"));
00070             request->Data->Properties->LogoBackgroundColor = GetLogoBackgroundColor();
00071         }
00072
00073         succeeded = true;
00074     }
00075     else
00076     {
00077         request->FailWithDisplayText(L"Select the application link you would like to share and try again.");
00078     }
00079
00080     return succeeded;
00081 }
00082
00083 Color ShareApplicationLink::GetLogoBackgroundColor()
00084 {
00085     Color backgroundColor;
00086     backgroundColor.R = (unsigned char)RedSlider->Value;
00087     backgroundColor.G = (unsigned char)GreenSlider->Value;
00088     backgroundColor.B = (unsigned char)BlueSlider->Value;
00089     backgroundColor.A = (unsigned char)AlphaSlider->Value;
00090
00091     return backgroundColor;
00092 }
Generated on Fri Nov 15 2024 22:21:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/Contact.cpp Source File

  • XamlListView
  • cppwinrt

Contact.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Contact.h"
00013 #include "Contact.g.cpp"
00014 #include <random>
00015
00016 using namespace winrt;
00017 using namespace winrt::Windows::Foundation::Collections;
00018 namespace
00019 {
00020   auto& random_generator()
00021   {
00022     static std::mt19937 generator{ std::random_device{}() };
00023     return generator;
00024   }
00025
00026   template<typename T>
00027   T random_in_range(T minValue, T maxValue)
00028   {
00029     return std::uniform_int_distribution<T>(minValue, maxValue)(random_generator());
00030   }
00031
00032   template<typename T>
00033   T random_below(T limit)
00034   {
00035     return random_in_range(T{}, limit - 1);
00036   }
00037
00038   template<typename T>
00039   T const& random_select(std::vector<T> const& source)
00040   {
00041     return source[random_below(source.size())];
00042   }
00043 }
00044
00045 namespace winrt::SDKTemplate::implementation
00046 {
00047   IObservableVector<SDKTemplate::Contact> Contact::GetContacts(int count)
00048   {
00049     std::vector<SDKTemplate::Contact> contacts;
00050     std::generate_n(std::back_inserter(contacts), count, &Contact::GetNewContact);
00051     return single_threaded_observable_vector(std::move(contacts));
00052   }
00053
00054   IObservableVector<SDKTemplate::GroupInfoList> Contact::GetContactsGrouped(int count)
00055   {
00056     std::map<int, std::vector<SDKTemplate::Contact>> groupMap;
00057
00058     // Generate the contacts and put each one in a group
00059     // based on the first letter of the last name.
00060     for (int i = 0; i < count; i++)
00061     {
00062       SDKTemplate::Contact contact = GetNewContact();
00063       auto upper = toupper(contact.LastName()[0]);
00064       groupMap[upper].push_back(contact);
00065     }
00066
00067     // Generate the list of GroupInfoList object, each representing one group.
00068     std::vector<SDKTemplate::GroupInfoList> groups;
00069     for (auto&& [upper, values] : groupMap)
00070     {
00071       SDKTemplate::GroupInfoList group;
00072       group.Key(to_hstring(static_cast<char16_t>(upper)));
00073       group.ReplaceAll(std::move(values));
00074       groups.push_back(group);
00075     }
00076     return single_threaded_observable_vector(std::move(groups));
00077   }
00078
00079   hstring Contact::GeneratePosition()
00080   {
00081     static std::vector<hstring> const positions({ L"Program Manager", L"Developer", L"Product Manager", L"Evangelist" });
00082     return random_select(positions);
00083   }
00084
00085   hstring Contact::GenerateBiography()
00086   {
00087     static std::vector<hstring> const biographies({
00088       L"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer id facilisis lectus. Cras nec convallis ante, quis pulvinar tellus. Integer dictum accumsan pulvinar. Pellentesque eget enim sodales sapien vestibulum consequat.",
00089       L"Maecenas eu sapien ac urna aliquam dictum.",
00090       L"Nullam eget mattis metus. Donec pharetra, tellus in mattis tincidunt, magna ipsum gravida nibh, vitae lobortis ante odio vel quam.",
00091       L"Quisque accumsan pretium ligula in faucibus. Mauris sollicitudin augue vitae lorem cursus condimentum quis ac mauris. Pellentesque quis turpis non nunc pretium sagittis. Nulla facilisi. Maecenas eu lectus ante. Proin eleifend vel lectus non tincidunt. Fusce condimentum luctus nisi, in elementum ante tincidunt nec.",
00092       L"Aenean in nisl at elit venenatis blandit ut vitae lectus. Praesent in sollicitudin nunc. Pellentesque justo augue, pretium at sem lacinia, scelerisque semper erat. Ut cursus tortor at metus lacinia dapibus.",
00093       L"Ut consequat magna luctus justo egestas vehicula. Integer pharetra risus libero, et posuere justo mattis et.",
00094       L"Proin malesuada, libero vitae aliquam venenatis, diam est faucibus felis, vitae efficitur erat nunc non mauris. Suspendisse at sodales erat.",
00095       L"Aenean vulputate, turpis non tincidunt ornare, metus est sagittis erat, id lobortis orci odio eget quam. Suspendisse ex purus, lobortis quis suscipit a, volutpat vitae turpis.",
00096       L"Duis facilisis, quam ut laoreet commodo, elit ex aliquet massa, non varius tellus lectus et nunc. Donec vitae risus ut ante pretium semper. Phasellus consectetur volutpat orci, eu dapibus turpis. Fusce varius sapien eu mattis pharetra.",
00097       L"Nam vulputate eu erat ornare blandit. Proin eget lacinia erat. Praesent nisl lectus, pretium eget leo et, dapibus dapibus velit. Integer at bibendum mi, et fringilla sem."
00098       });
00099     return random_select(biographies);
00100   }
00101
00102   hstring Contact::GeneratePhoneNumber()
00103   {
00104     return L"(" + to_hstring(random_in_range(100, 999)) + L") " + to_hstring(random_in_range(100, 999)) + L"-" + to_hstring(random_in_range(100, 9999));
00105   }
00106
00107   hstring Contact::GenerateFirstName()
00108   {
00109     static std::vector<hstring> const names({
00110       L"Lilly", L"Mukhtar", L"Sophie", L"Femke", L"Abdul-Rafi'", L"Chirag-ud-D...", L"Mariana", L"Aarif", L"Sara",
00111       L"Ibadah", L"Fakhr", L"Ilene", L"Sardar", L"Hanna", L"Julie", L"Iain", L"Natalia", L"Henrik", L"Rasa", L"Quentin",
00112       L"Gadi", L"Pernille", L"Ishtar", L"Jimme", L"Justina", L"Lale", L"Elize", L"Rand", L"Roshanara", L"Rajab", L"Bijou",
00113       L"Marcus", L"Marcus", L"Alima", L"Francisco", L"Thaqib", L"Andreas", L"Mariana", L"Amalie", L"Rodney", L"Dena", L"Fadl",
00114       L"Ammar", L"Anna", L"Nasreen", L"Reem", L"Tomas", L"Filipa", L"Frank", L"Bari'ah", L"Parvaiz", L"Jibran", L"Tomas",
00115       L"Elli", L"Carlos", L"Diego", L"Henrik", L"Aruna", L"Vahid", L"Eliana", L"Roxane", L"Amanda", L"Ingrid", L"Wander",
00116       L"Malika", L"Basim", L"Eisa", L"Alina", L"Andreas", L"Deeba", L"Diya", L"Parveen", L"Bakr", L"Celine", L"Bakr",
00117       L"Marcus", L"Daniel", L"Mathea", L"Edmee", L"Hedda", L"Maria", L"Maja", L"Alhasan", L"Alina", L"Hedda", L"Victor",
00118       L"Aaftab", L"Guilherme", L"Maria", L"Kai", L"Sabien", L"Abdel", L"Fadl", L"Bahaar", L"Vasco", L"Jibran", L"Parsa",
00119       L"Catalina", L"Fouad", L"Colette"
00120       });
00121     return random_select(names);
00122   }
00123
00124   hstring Contact::GenerateLastName()
00125   {
00126     static std::vector<hstring> const names({
00127       L"Carlson", L"Attia", L"Quint", L"Hollenberg", L"Khoury", L"Araujo", L"Hakimi", L"Seegers", L"Abadi", L"al",
00128       L"Krommenhoek", L"Siavashi", L"Kvistad", L"Sjo", L"Vanderslik", L"Fernandes", L"Dehli", L"Sheibani",
00129       L"Laamers", L"Batlouni", L"Lyngvær", L"Oveisi", L"Veenhuizen", L"Gardenier", L"Siavashi", L"Mutlu", L"Karzai",
00130       L"Mousavi", L"Natsheh", L"Seegers", L"Nevland", L"Lægreid", L"Bishara", L"Cunha", L"Hotaki", L"Kyvik",
00131       L"Cardoso", L"Pilskog", L"Pennekamp", L"Nuijten", L"Bettar", L"Borsboom", L"Skistad", L"Asef", L"Sayegh",
00132       L"Sousa", L"Medeiros", L"Kregel", L"Shamoun", L"Behzadi", L"Kuzbari", L"Ferreira", L"Van", L"Barros",
00133       L"Fernandes", L"Formo", L"Nolet", L"Shahrestaani", L"Correla", L"Amiri", L"Sousa", L"Fretheim", L"Van",
00134       L"Hamade", L"Baba", L"Mustafa", L"Bishara", L"Formo", L"Hemmati", L"Nader", L"Hatami", L"Natsheh", L"Langen",
00135       L"Maloof", L"Berger", L"Ostrem", L"Bardsen", L"Kramer", L"Bekken", L"Salcedo", L"Holter", L"Nader", L"Bettar",
00136       L"Georgsen", L"Cunha", L"Zardooz", L"Araujo", L"Batalha", L"Antunes", L"Vanderhoorn", L"Nader", L"Abadi",
00137       L"Siavashi", L"Montes", L"Sherzai", L"Vanderschans", L"Neves", L"Sarraf", L"Kuiters"
00138       });
00139     return random_select(names);
00140   }
00141
00142 }
Generated on Fri Nov 15 2024 22:22:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cpp/Scenario4_BackgroundActivity.xaml.cpp Source File

  • ActivitySensor
  • cpp

Scenario4_BackgroundActivity.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario4_BackgroundActivity.xaml.cpp
00014 // Implementation of the Scenario4_BackgroundActivity class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario4_BackgroundActivity.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Concurrency;
00023 using namespace Platform;
00024 using namespace Windows::ApplicationModel::Background;
00025 using namespace Windows::Devices::Enumeration;
00026 using namespace Windows::Devices::Sensors;
00027 using namespace Windows::Storage;
00028 using namespace Windows::UI::Core;
00029 using namespace Windows::UI::Xaml;
00030 using namespace Windows::UI::Xaml::Controls;
00031 using namespace Windows::UI::Xaml::Navigation;
00032
00033 Scenario4_BackgroundActivity::Scenario4_BackgroundActivity() : rootPage(MainPage::Current)
00034 {
00035     InitializeComponent();
00036 }
00037
00038 /// <summary>
00039 /// Invoked when this page is about to be displayed in a Frame.
00040 /// </summary>
00041 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00042 /// property is typically used to configure the page.</param>
00043 void Scenario4_BackgroundActivity::OnNavigatedTo(NavigationEventArgs^ e)
00044 {
00045     for (const auto& cur : BackgroundTaskRegistration::AllTasks)
00046     {
00047         auto registration = dynamic_cast<BackgroundTaskRegistration^>(cur->Value);
00048         if (SampleBackgroundTaskName == registration->Name)
00049         {
00050             registered = true;
00051             break;
00052         }
00053     }
00054
00055     UpdateUIAsync(registered ? "Registered" : "Unregistered");
00056 }
00057
00058 /// <summary>
00059 /// This is the click handler for the 'Register Task' button.
00060 /// </summary>
00061 /// <param name="sender"></param>
00062 /// <param name="e"></param>
00063 void Scenario4_BackgroundActivity::ScenarioRegisterTask(Object^ sender, RoutedEventArgs^ e)
00064 {
00065     // Determine if we can access activity sensors
00066     auto deviceAccessInfo = DeviceAccessInformation::CreateFromDeviceClassId(GUID_ActivitySensor_ClassId);
00067     if (deviceAccessInfo->CurrentStatus == DeviceAccessStatus::Allowed)
00068     {
00069         // Determine if an activity sensor is present
00070         // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
00071         create_task(ActivitySensor::GetDefaultAsync).then([this](ActivitySensor^ sensor)
00072         {
00073             if (nullptr != sensor)
00074             {
00075                 create_task(BackgroundExecutionManager::RequestAccessAsync()).then([this](BackgroundAccessStatus status)
00076                 {
00077                     if ((BackgroundAccessStatus::AlwaysAllowed == status) ||
00078                         (BackgroundAccessStatus::AllowedSubjectToSystemPolicy == status))
00079                     {
00080                         RegisterBackgroundTask();
00081                     }
00082                     else
00083                     {
00084                         rootPage->NotifyUser("Background tasks may be disabled for this app", NotifyType::ErrorMessage);
00085                     }
00086                 });
00087             }
00088             else
00089             {
00090                 rootPage->NotifyUser("No activity sensors found", NotifyType::ErrorMessage);
00091             }
00092         });
00093     }
00094     else
00095     {
00096         rootPage->NotifyUser("Access denied to activity sensors", NotifyType::ErrorMessage);
00097     }
00098 }
00099
00100 /// <summary>
00101 /// This is the click handler for the 'Unregister Task' button.
00102 /// </summary>
00103 /// <param name="sender"></param>
00104 /// <param name="e"></param>
00105 void Scenario4_BackgroundActivity::ScenarioUnregisterTask(Object^ sender, RoutedEventArgs^ e)
00106 {
00107     // Loop through all background tasks and unregister any with SampleBackgroundTaskName
00108     for (const auto& cur : BackgroundTaskRegistration::AllTasks)
00109     {
00110         auto registration = dynamic_cast<BackgroundTaskRegistration^>(cur->Value);
00111         if (SampleBackgroundTaskName == registration->Name)
00112         {
00113             registration->Unregister(true /*cancelTask*/);
00114             registered = false;
00115         }
00116     }
00117
00118     if (!registered)
00119     {
00120         UpdateUIAsync("Unregistered");
00121     }
00122 }
00123
00124 /// <summary>
00125 /// This is the event handler for background task completion.
00126 /// </summary>
00127 /// <param name="task">The task that is reporting completion.</param>
00128 /// <param name="args">The completion report arguments.</param>
00129 void Scenario4_BackgroundActivity::OnCompleted(BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
00130 {
00131     String^ status = "Completed";
00132     try
00133     {
00134         args->CheckResult();
00135     }
00136     catch (Exception^ e)
00137     {
00138         status = e->Message;
00139     }
00140     UpdateUIAsync(status);
00141 }
00142
00143 /// <summary>
00144 /// Registers the background task.
00145 /// </summary>
00146 void Scenario4_BackgroundActivity::RegisterBackgroundTask()
00147 {
00148     auto builder = ref new BackgroundTaskBuilder();
00149     builder->Name = SampleBackgroundTaskName;
00150     builder->TaskEntryPoint = SampleBackgroundTaskEntryPoint;
00151
00152     const unsigned int reportIntervalMs = 3000; // 3 seconds
00153     auto trigger = ref new ActivitySensorTrigger(reportIntervalMs);
00154
00155     trigger->SubscribedActivities->Append(ActivityType::Walking);
00156     trigger->SubscribedActivities->Append(ActivityType::Running);
00157     trigger->SubscribedActivities->Append(ActivityType::Biking);
00158
00159     builder->SetTrigger(trigger);
00160
00161     auto task = builder->Register();
00162     task->Completed += ref new BackgroundTaskCompletedEventHandler(this, &Scenario4_BackgroundActivity::OnCompleted);
00163
00164     registered = true;
00165     UpdateUIAsync("Registered");
00166 }
00167
00168 /// <summary>
00169 /// Updates the scenario UI.
00170 /// </summary>
00171 /// <param name="status">The status string to display.</param>
00172 void Scenario4_BackgroundActivity::UpdateUIAsync(String^ status)
00173 {
00174     // Update the buttons in the UI thread
00175     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, status]()
00176     {
00177         ScenarioRegisterTaskButton->IsEnabled = !registered;
00178         ScenarioUnregisterTaskButton->IsEnabled = registered;
00179         ScenarioOutput_TaskRegistration->Text = status;
00180
00181         auto settings = ApplicationData::Current->LocalSettings;
00182
00183         if (settings->Values->HasKey("ReportCount"))
00184         {
00185             ScenarioOutput_ReportCount->Text = safe_cast<String^>(settings->Values->Lookup("ReportCount")); // stored as a string
00186         }
00187         if (settings->Values->HasKey("TaskStatus"))
00188         {
00189             ScenarioOutput_TaskStatus->Text = safe_cast<String^>(settings->Values->Lookup("TaskStatus")); // stored as a string
00190         }
00191         if (settings->Values->HasKey("LastActivity"))
00192         {
00193             ScenarioOutput_LastActivity->Text = safe_cast<String^>(settings->Values->Lookup("LastActivity")); // stored as a string
00194         }
00195         if (settings->Values->HasKey("LastConfidence"))
00196         {
00197             ScenarioOutput_LastConfidence->Text = safe_cast<String^>(settings->Values->Lookup("LastConfidence")); // stored as a string
00198         }
00199         if (settings->Values->HasKey("LastTimestamp"))
00200         {
00201             ScenarioOutput_LastTimestamp->Text = safe_cast<String^>(settings->Values->Lookup("LastTimestamp")); // stored as a string
00202         }
00203     }));
00204 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario02_GetStream Member List

This is the complete list of members for Scenario02_GetStream, including all inherited members.
Cancel_Click(object sender, RoutedEventArgs e) | Scenario02_GetStream | [inline, private]
cts | Scenario02_GetStream | [private]
httpClient | Scenario02_GetStream | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario02_GetStream | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario02_GetStream | [inline, protected]
rootPage | Scenario02_GetStream | [private]
Scenario02_GetStream() | Scenario02_GetStream | [inline]
Start_Click(object sender, RoutedEventArgs e) | Scenario02_GetStream | [inline, private]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContextMenu/cs/Scenario2.xaml.cs Source File

  • ContextMenu
  • cs

Scenario2.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.DataTransfer;
00014 using Windows.Foundation;
00015 using Windows.System;
00016 using Windows.UI.Popups;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020 using Windows.UI.Xaml.Media;
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class Scenario2 : Page
00028     {
00029         public Scenario2()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         // returns a rect for selected text
00035         // if no text is selected, returns caret location
00036         // textbox should not be empty
00037         private Rect GetTextboxSelectionRect(TextBox textbox)
00038         {
00039             Rect rectFirst, rectLast;
00040             if (textbox.SelectionStart == textbox.Text.Length)
00041             {
00042                 rectFirst = textbox.GetRectFromCharacterIndex(textbox.SelectionStart - 1, true);
00043             }
00044             else
00045             {
00046                 rectFirst = textbox.GetRectFromCharacterIndex(textbox.SelectionStart, false);
00047             }
00048
00049             int lastIndex = textbox.SelectionStart + textbox.SelectionLength;
00050             if (lastIndex == textbox.Text.Length)
00051             {
00052                 rectLast = textbox.GetRectFromCharacterIndex(lastIndex - 1, true);
00053             }
00054             else
00055             {
00056                 rectLast = textbox.GetRectFromCharacterIndex(lastIndex, false);
00057             }
00058
00059             rectFirst.Union(rectLast);
00060
00061             GeneralTransform transform = textbox.TransformToVisual(null);
00062             return transform.TransformBounds(rectFirst);
00063         }
00064
00065         private async void ReadOnlyTextBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)
00066         {
00067             e.Handled = true;
00068             TextBox textbox = (TextBox)sender;
00069             if (textbox.SelectionLength > 0)
00070             {
00071                 // Create a menu and add commands specifying an id value for each instead of a delegate.
00072                 var menu = new PopupMenu();
00073                 menu.Commands.Add(new UICommand("Copy", null, 1));
00074                 menu.Commands.Add(new UICommandSeparator());
00075                 menu.Commands.Add(new UICommand("Highlight", null, 2));
00076                 menu.Commands.Add(new UICommand("Look up", null, 3));
00077
00078                 // We don't want to obscure content, so pass in a rectangle representing the selection area.
00079                 // NOTE: this code only handles textboxes with a single line. If a textbox has multiple lines,
00080                 //       then the context menu should be placed at cursor/pointer location by convention.
00081                 OutputTextBlock.Text = "Context menu shown";
00082                 Rect rect = GetTextboxSelectionRect(textbox);
00083                 var chosenCommand = await menu.ShowForSelectionAsync(rect);
00084                 if (chosenCommand != null)
00085                 {
00086                     switch ((int)chosenCommand.Id)
00087                     {
00088                         case 1:
00089                             String selectedText = ((TextBox)sender).SelectedText;
00090                             var dataPackage = new DataPackage();
00091                             dataPackage.SetText(selectedText);
00092                             Clipboard.SetContent(dataPackage);
00093                             OutputTextBlock.Text = "'" + chosenCommand.Label + "'(" + chosenCommand.Id.ToString() + ") selected; '" + selectedText + "' copied to clipboard";
00094                             break;
00095
00096                         case 2:
00097                             OutputTextBlock.Text = "'" + chosenCommand.Label + "'(" + chosenCommand.Id.ToString() + ") selected";
00098                             break;
00099
00100                         case 3:
00101                             OutputTextBlock.Text = "'" + chosenCommand.Label + "'(" + chosenCommand.Id.ToString() + ") selected";
00102                             break;
00103                     }
00104                 }
00105                 else
00106                 {
00107                     OutputTextBlock.Text = "Context menu dismissed";
00108                 }
00109             }
00110             else
00111             {
00112                 OutputTextBlock.Text = "Context menu not shown because there is no text selected";
00113             }
00114         }
00115     }
00116 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cppwinrt/Scenario1_SingleFile.cpp Source File

  • FilePicker
  • cppwinrt

Scenario1_SingleFile.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_SingleFile.h"
00014 #include "Scenario1_SingleFile.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Storage;
00019 using namespace Windows::Storage::Pickers;
00020 using namespace Windows::UI::Xaml;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     Scenario1_SingleFile::Scenario1_SingleFile()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     fire_and_forget Scenario1_SingleFile::PickAFileButton_Click(IInspectable const&, RoutedEventArgs const&)
00030     {
00031         auto lifetime = get_strong();
00032
00033         // Clear previous returned file name, if it exists, between iterations of this scenario
00034         OutputTextBlock().Text(L"");
00035
00036         FileOpenPicker openPicker;
00037         openPicker.ViewMode(PickerViewMode::Thumbnail);
00038         openPicker.SuggestedStartLocation(PickerLocationId::PicturesLibrary);
00039         openPicker.FileTypeFilter().ReplaceAll({ L".jpg", L".jpeg", L".png" });
00040         StorageFile file = co_await openPicker.PickSingleFileAsync();
00041         if (file != nullptr)
00042         {
00043             // The StorageFile has read/write access to the picked file.
00044             // See the FileAccess sample for code that uses a StorageFile to read and write.
00045             OutputTextBlock().Text(L"Picked photo: " + file.Name());
00046         }
00047         else
00048         {
00049             OutputTextBlock().Text(L"Operation cancelled.");
00050         }
00051     }
00052 }
Generated on Fri Nov 15 2024 22:19:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MainPage Member List

This is the complete list of members for MainPage, including all inherited members.
_captureFolder | MainPage | [private]
_deviceOrientation | MainPage | [private]
_displayInformation | MainPage | [private]
_displayOrientation | MainPage | [private]
_displayRequest | MainPage | [private]
_externalCamera | MainPage | [private]
_isFocused | MainPage | [private]
_isInitialized | MainPage | [private]
_isPreviewing | MainPage | [private]
_isRecording | MainPage | [private]
_mediaCapture | MainPage | [private]
_mirroringPreview | MainPage | [private]
_orientationSensor | MainPage | [private]
_settingUpUi | MainPage | [private]
_singleControlMode | MainPage | [private]
_systemMediaControls | MainPage | [private]
_systemNavigationManager | MainPage | [private]
Application_Resuming(object sender, object o) | MainPage | [inline, private]
Application_Suspending(object sender, SuspendingEventArgs e) | MainPage | [inline, private]
CafFocusRadioButton_Checked(object sender, RoutedEventArgs e) | MainPage | [inline, private]
CleanupCameraAsync() | MainPage | [inline, private]
CleanupUiAsync() | MainPage | [inline, private]
ConvertDeviceOrientationToDegrees(SimpleOrientation orientation) | MainPage | [inline, private, static]
ConvertDisplayOrientationToDegrees(DisplayOrientations orientation) | MainPage | [inline, private, static]
ConvertOrientationToPhotoOrientation(SimpleOrientation orientation) | MainPage | [inline, private, static]
ConvertUiTapToPreviewRect(Point tap, Size size, Rect previewRect) | MainPage | [inline, private]
DisplayInformation_OrientationChanged(DisplayInformation sender, object args) | MainPage | [inline, private]
EvSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e) | MainPage | [inline, private]
EvStepCountToString(int steps, float stepSize) | MainPage | [inline, private, static]
FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel) | MainPage | [inline, private, static]
FlashAutoRadioButton_Checked(object sender, RoutedEventArgs e) | MainPage | [inline, private]
FlashOffRadioButton_Checked(object sender, RoutedEventArgs e) | MainPage | [inline, private]
FlashOnRadioButton_Checked(object sender, RoutedEventArgs e) | MainPage | [inline, private]
FocusCamera(RegionOfInterest region) | MainPage | [inline, private]
FocusLightCheckBox_CheckedChanged(object sender, RoutedEventArgs e) | MainPage | [inline, private]
FocusSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e) | MainPage | [inline, private]
GetCameraOrientation() | MainPage | [inline, private]
GetPreviewStreamRectInControl(VideoEncodingProperties previewResolution, CaptureElement previewControl, DisplayOrientations displayOrientation) | MainPage | [inline, static]
HardwareButtons_CameraPressed(object sender, CameraEventArgs e) | MainPage | [inline, private]
InitializeCameraAsync() | MainPage | [inline, private]
IsoAutoCheckBox_CheckedChanged(object sender, RoutedEventArgs e) | MainPage | [inline, private]
IsoSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e) | MainPage | [inline, private]
MainPage() | MainPage | [inline]
ManualControlButton_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
ManualFocusRadioButton_Checked(object sender, RoutedEventArgs e) | MainPage | [inline, private]
MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) | MainPage | [inline, private]
MediaCapture_RecordLimitationExceeded(MediaCapture sender) | MainPage | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | MainPage | [inline, protected]
OrientationSensor_OrientationChanged(SimpleOrientationSensor sender, SimpleOrientationSensorOrientationChangedEventArgs args) | MainPage | [inline, private]
PhotoButton_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
PreviewControl_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e) | MainPage | [inline, private]
PreviewControl_Tapped(object sender, TappedRoutedEventArgs e) | MainPage | [inline, private]
RedEyeFlashCheckBox_CheckedChanged(object sender, RoutedEventArgs e) | MainPage | [inline, private]
ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation) | MainPage | [inline, private, static]
RegisterEventHandlers() | MainPage | [inline, private]
RotationKey | MainPage | [private, static]
SetPreviewRotationAsync() | MainPage | [inline, private]
SetSingleControl(object activeButton) | MainPage | [inline, private]
SetupUiAsync() | MainPage | [inline, private]
SetZoomLevel(float level) | MainPage | [inline, private]
ShutterCheckBox_CheckedChanged(object sender, RoutedEventArgs e) | MainPage | [inline, private]
ShutterSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e) | MainPage | [inline, private]
StartPreviewAsync() | MainPage | [inline, private]
StartRecordingAsync() | MainPage | [inline, private]
StopPreviewAsync() | MainPage | [inline, private]
StopRecordingAsync() | MainPage | [inline, private]
SystemMediaControls_PropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs args) | MainPage | [inline, private]
SystemNavigationManager_BackRequested(object sender, BackRequestedEventArgs e) | MainPage | [inline, private]
TakePhotoAsync() | MainPage | [inline, private]
TapFocusRadioButton_Checked(object sender, RoutedEventArgs e) | MainPage | [inline, private]
TapToFocus(Point position, Size size) | MainPage | [inline]
TapUnfocus() | MainPage | [inline, private]
TorchCheckBox_CheckedChanged(object sender, RoutedEventArgs e) | MainPage | [inline, private]
UnregisterEventHandlers() | MainPage | [inline, private]
UpdateButtonOrientation() | MainPage | [inline, private]
UpdateCaptureControls() | MainPage | [inline, private]
UpdateEvControlCapabilities() | MainPage | [inline, private]
UpdateExposureControlCapabilities() | MainPage | [inline, private]
UpdateFlashControlCapabilities() | MainPage | [inline, private]
UpdateFocusControlCapabilities() | MainPage | [inline, private]
UpdateIsoControlCapabilities() | MainPage | [inline, private]
UpdateManualControlCapabilities() | MainPage | [inline, private]
UpdateWbControlCapabilities() | MainPage | [inline, private]
UpdateZoomControlCapabilities() | MainPage | [inline, private]
VideoButton_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
WbComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
WbSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e) | MainPage | [inline, private]
ZoomSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e) | MainPage | [inline, private]
Generated on Fri Nov 15 2024 22:23:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LoggingScenarioEventArgs Member List

This is the complete list of members for LoggingScenarioEventArgs, including all inherited members.
Enabled | LoggingScenarioEventArgs |
LogFilePath | LoggingScenarioEventArgs |
LoggingScenarioEventArgs(LoggingScenarioEventType type) | LoggingScenarioEventArgs | [inline]
LoggingScenarioEventArgs(LoggingScenarioEventType type, string logFilePath) | LoggingScenarioEventArgs | [inline]
LoggingScenarioEventArgs(bool enabled) | LoggingScenarioEventArgs | [inline]
Type | LoggingScenarioEventArgs |
Generated on Fri Nov 15 2024 22:23:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/02_Casting_API_CastButton.xaml.cs Source File

  • AdvancedCasting
  • cs

02_Casting_API_CastButton.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using ScreenCasting.Controls;
00013 using ScreenCasting.Data.Azure;
00014 using ScreenCasting.Data.Common;
00015 using System;
00016 using Windows.Devices.Enumeration;
00017 using Windows.Foundation;
00018 using Windows.Media.Casting;
00019 using Windows.UI;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Media;
00023 using Windows.UI.Xaml.Media.Imaging;
00024 using Windows.UI.Xaml.Navigation;
00025
00026 namespace ScreenCasting
00027 {
00028     public sealed partial class Scenario02 : Page
00029     {
00030         private MainPage rootPage;
00031         private CastingDevicePicker picker = null;
00032         private VideoMetaData video = null;
00033         private CastingConnection connection;
00034         public Scenario02()
00035         {
00036             this.InitializeComponent();
00037
00038             rootPage = MainPage.Current;
00039
00040             //Subscribe to player events
00041             player.MediaOpened += Player_MediaOpened;
00042             player.MediaFailed += Player_MediaFailed;
00043             player.CurrentStateChanged += Player_CurrentStateChanged;
00044
00045             // Get an Azure hosted video
00046             AzureDataProvider dataProvider = new AzureDataProvider();
00047             video = dataProvider.GetRandomVideo();
00048
00049             //Set the source on the player
00050             rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage);
00051             player.Source = video.VideoLink;
00052             this.LicenseText.Text = "License: " + video.License;
00053
00054             //Subscribe for the clicked event on the custom cast button
00055             ((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked;
00056
00057             // Instantiate the Device Picker
00058             picker = new CastingDevicePicker();
00059
00060             // Generate the filter based on the content in the MediaElement
00061             picker.Filter.SupportedCastingSources.Add(player.GetAsCastingSource());
00062
00063             //Hook up device selected event
00064             picker.CastingDeviceSelected += Picker_CastingDeviceSelected;
00065
00066             //Hook up device disconnected event
00067             picker.CastingDevicePickerDismissed += Picker_CastingDevicePickerDismissed;
00068
00069             //Set the Appearence of the picker
00070             picker.Appearance.BackgroundColor = Colors.Black;
00071             picker.Appearance.ForegroundColor = Colors.White;
00072             picker.Appearance.AccentColor = Colors.Gray;
00073
00074             picker.Appearance.SelectedAccentColor = Colors.Gray;
00075
00076             picker.Appearance.SelectedForegroundColor = Colors.White;
00077             picker.Appearance.SelectedBackgroundColor = Colors.Black;
00078         }
00079
00080         private void TransportControls_CastButtonClicked(object sender, EventArgs e)
00081         {
00082             rootPage.NotifyUser("Custom Cast Button Clicked", NotifyType.StatusMessage);
00083
00084             //Pause Current Playback
00085             player.Pause();
00086
00087             //Get the custom transport controls
00088             MediaTransportControlsWithCustomCastButton mtc = (MediaTransportControlsWithCustomCastButton)this.player.TransportControls;
00089
00090             //Retrieve the location of the casting button
00091             GeneralTransform transform = mtc.CastButton.TransformToVisual(Window.Current.Content as UIElement);
00092             Point pt = transform.TransformPoint(new Point(0, 0));
00093
00094             //Show the picker above our custom cast button
00095             picker.Show(new Rect(pt.X, pt.Y, mtc.CastButton.ActualWidth, mtc.CastButton.ActualHeight), Windows.UI.Popups.Placement.Above);
00096         }
00097
00098         private async void Picker_CastingDevicePickerDismissed(CastingDevicePicker sender, object args)
00099         {
00100             // This dispatches the casting calls to the UI thread.
00101             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00102             {
00103                 player.Play();
00104             });
00105         }
00106         private async void Picker_CastingDeviceSelected(CastingDevicePicker sender, CastingDeviceSelectedEventArgs args)
00107         {
00108             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
00109             {
00110                 try
00111                 {
00112                     rootPage.NotifyUser(string.Format("Picker DeviceSelected event fired for device '{0}'", args.SelectedCastingDevice.FriendlyName), NotifyType.StatusMessage);
00113
00114                     //DateTime t1 = DateTime.Now;
00115                     //DeviceInformation mydevice = await DeviceInformation.CreateFromIdAsync(args.SelectedCastingDevice.Id);
00116                     //DateTime t2 = DateTime.Now;
00117
00118                     //TimeSpan ts = new TimeSpan(t2.Ticks - t1.Ticks);
00119
00120                     //System.Diagnostics.Debug.WriteLine(string.Format("DeviceInformation.CreateFromIdAsync took '{0} seconds'", ts.TotalSeconds));
00121
00122                     //Create a casting conneciton from our selected casting device
00123                     rootPage.NotifyUser(string.Format("Creating connection for '{0}'", args.SelectedCastingDevice.FriendlyName), NotifyType.StatusMessage);
00124                     connection = args.SelectedCastingDevice.CreateCastingConnection();
00125
00126                     //Hook up the casting events
00127                     connection.ErrorOccurred += Connection_ErrorOccurred;
00128                     connection.StateChanged += Connection_StateChanged;
00129
00130                     // Get the casting source from the MediaElement
00131                     CastingSource source = null;
00132
00133                     try
00134                     {
00135                         // Get the casting source from the Media Element
00136                         source = player.GetAsCastingSource();
00137
00138                         // Start Casting
00139                         rootPage.NotifyUser(string.Format("Starting casting to '{0}'", args.SelectedCastingDevice.FriendlyName), NotifyType.StatusMessage);
00140                         CastingConnectionErrorStatus status = await connection.RequestStartCastingAsync(source);
00141
00142                         if (status == CastingConnectionErrorStatus.Succeeded)
00143                         {
00144                             player.Play();
00145                             rootPage.NotifyUser(string.Format("Starting casting to '{0}'", args.SelectedCastingDevice.FriendlyName), NotifyType.StatusMessage);
00146                         }
00147
00148                     }
00149                     catch
00150                     {
00151                         rootPage.NotifyUser(string.Format("Failed to get casting source for video '{0}'", video.Title), NotifyType.ErrorMessage);
00152                     }
00153                 }
00154                 catch (Exception ex)
00155                 {
00156                     UnhandledExceptionPage.ShowUnhandledException(ex);
00157                 }
00158             });
00159         }
00160
00161         #region Casting Connection Status Methods
00162         private async void Connection_StateChanged(CastingConnection sender, object args)
00163         {
00164             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00165             {
00166                 rootPage.NotifyUser("Casting Connection State Changed: " + sender.State, NotifyType.StatusMessage);
00167             });
00168         }
00169         private async void Connection_ErrorOccurred(CastingConnection sender, CastingConnectionErrorOccurredEventArgs args)
00170         {
00171             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00172             {
00173                 rootPage.NotifyUser("Connection Error Occured: " + args.Message, NotifyType.ErrorMessage);
00174             });
00175         }
00176
00177         #endregion
00178
00179
00180         #region Media Element Status Methods
00181         private void Player_CurrentStateChanged(object sender, RoutedEventArgs e)
00182         {
00183             rootPage.NotifyUser(string.Format("{0} '{1}'", this.player.CurrentState, video.Title), NotifyType.StatusMessage);
00184         }
00185         private void Player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
00186         {
00187             rootPage.NotifyUser(string.Format("Failed to load '{0}'", video.Title), NotifyType.ErrorMessage);
00188         }
00189         private void Player_MediaOpened(object sender, RoutedEventArgs e)
00190         {
00191             rootPage.NotifyUser(string.Format("Openend '{0}'", video.Title), NotifyType.StatusMessage);
00192         }
00193
00194
00195         #endregion
00196         protected override void OnNavigatedTo(NavigationEventArgs e)
00197         {
00198             rootPage = MainPage.Current;
00199         }
00200     }
00201 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cpp/Scenario2_SampleBackgroundTaskWithCondition.xaml.cpp Source File

  • BackgroundActivation
  • cpp

Scenario2_SampleBackgroundTaskWithCondition.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario2_SampleBackgroundTaskWithCondition.xaml.cpp
00013 // Implementation of the SampleBackgroundTaskWithCondition class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario2_SampleBackgroundTaskWithCondition.xaml.h"
00018 #include "SampleConfiguration.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::ApplicationModel::Background;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 SampleBackgroundTaskWithCondition::SampleBackgroundTaskWithCondition()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Invoked when this page is about to be displayed in a Frame.
00035 /// </summary>
00036 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037 /// property is typically used to configure the page.</param>
00038 void SampleBackgroundTaskWithCondition::OnNavigatedTo(NavigationEventArgs^ e)
00039 {
00040     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00041     // as NotifyUser()
00042     rootPage = MainPage::Current;
00043
00044     //
00045     // Attach progress and completed handlers to any existing tasks.
00046     //
00047     for (auto pair : BackgroundTaskRegistration::AllTasks)
00048     {
00049         auto task = pair->Value;
00050         if (task->Name == SampleBackgroundTaskWithConditionName)
00051         {
00052             BackgroundTaskSample::UpdateBackgroundTaskRegistrationStatus(task->Name, true);
00053             AttachProgressAndCompletedHandlers(task);
00054             break;
00055         }
00056     }
00057
00058     UpdateUI();
00059 }
00060
00061 /// <summary>
00062 /// Attach progress and completed handers to a background task.
00063 /// </summary>
00064 /// <param name="task">The task to attach progress and completed handlers to.</param>
00065 void SampleBackgroundTaskWithCondition::AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration^ task)
00066 {
00067     task->Progress += ref new BackgroundTaskProgressEventHandler(this, &SampleBackgroundTaskWithCondition::OnProgress);
00068     task->Completed += ref new BackgroundTaskCompletedEventHandler(this, &SampleBackgroundTaskWithCondition::OnCompleted);
00069 }
00070
00071 /// <summary>
00072 /// Register a SampleBackgroundTaskWithCondition.
00073 /// </summary>
00074 /// <param name="sender"></param>
00075 /// <param name="e"></param>
00076 void SampleBackgroundTaskWithCondition::RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00077 {
00078     auto task = BackgroundTaskSample::RegisterBackgroundTask(nullptr,
00079                                                              SampleBackgroundTaskWithConditionName,
00080                                                              ref new SystemTrigger(SystemTriggerType::TimeZoneChange, false),
00081                                                              ref new SystemCondition(SystemConditionType::InternetAvailable));
00082     AttachProgressAndCompletedHandlers(task);
00083     UpdateUI();
00084 }
00085
00086 /// <summary>
00087 /// Unregister a SampleBackgroundTaskWithCondition.
00088 /// </summary>
00089 /// <param name="sender"></param>
00090 /// <param name="e"></param>
00091 void SampleBackgroundTaskWithCondition::UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00092 {
00093     BackgroundTaskSample::UnregisterBackgroundTasks(SampleBackgroundTaskWithConditionName);
00094     UpdateUI();
00095 }
00096
00097 /// <summary>
00098 /// Handle background task progress.
00099 /// </summary>
00100 /// <param name="task">The task that is reporting progress.</param>
00101 /// <param name="args">Arguments of the progress report.</param>
00102 void SampleBackgroundTaskWithCondition::OnProgress(BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
00103 {
00104     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00105     {
00106         auto progress = "Progress: " + args->Progress + "%";
00107         BackgroundTaskSample::SampleBackgroundTaskWithConditionProgress = progress;
00108         UpdateUI();
00109     }));
00110 }
00111
00112 /// <summary>
00113 /// Handle background task completion.
00114 /// </summary>
00115 /// <param name="task">The task that is reporting completion.</param>
00116 /// <param name="args">Arguments of the completion report.</param>
00117 void SampleBackgroundTaskWithCondition::OnCompleted(BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
00118 {
00119     UpdateUI();
00120 }
00121
00122 /// <summary>
00123 /// Update the scenario UI.
00124 /// </summary>
00125 void SampleBackgroundTaskWithCondition::UpdateUI()
00126 {
00127     auto uiDelegate = [this]()
00128     {
00129         RegisterButton->IsEnabled = !BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered;
00130         UnregisterButton->IsEnabled = BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered;
00131         Progress->Text = BackgroundTaskSample::SampleBackgroundTaskWithConditionProgress;
00132         Status->Text = BackgroundTaskSample::GetBackgroundTaskStatus(SampleBackgroundTaskWithConditionName);
00133     };
00134     auto handler = ref new Windows::UI::Core::DispatchedHandler(uiDelegate, Platform::CallbackContext::Any);
00135
00136     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, handler);
00137 }
Generated on Fri Nov 15 2024 22:18:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks.Shared/Trip.h Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks.Shared

Trip.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012 namespace AdventureWorks_Shared
00013 {
00014     [Windows::UI::Xaml::Data::Bindable]
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class Trip sealed : Windows::UI::Xaml::Data::INotifyPropertyChanged
00017     {
00018     public:
00019         Trip();
00020
00021         // Inherited via INotifyPropertyChanged
00022         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler ^ PropertyChanged
00023         {
00024             Windows::Foundation::EventRegistrationToken add(Windows::UI::Xaml::Data::PropertyChangedEventHandler^ handler)
00025             {
00026                 subscribers++;
00027                 return _PropertyChanged += handler;
00028             }
00029
00030             void remove(Windows::Foundation::EventRegistrationToken token)
00031             {
00032                 subscribers--;
00033                 return _PropertyChanged -= token;
00034             }
00035
00036         internal:
00037             void raise(Object^ sender, Windows::UI::Xaml::Data::PropertyChangedEventArgs^ args)
00038             {
00039                 if (subscribers > 0)
00040                 {
00041                     return _PropertyChanged(sender, args);
00042                 }
00043                 return;
00044             }
00045         };
00046
00047         property Platform::String^ Destination
00048         {
00049             Platform::String^ get();
00050             void set(Platform::String^ value);
00051         }
00052
00053         property Platform::String^ Description
00054         {
00055             Platform::String^ get();
00056             void set(Platform::String^ value);
00057         }
00058
00059         property Windows::Globalization::Calendar^ StartDate
00060         {
00061             Windows::Globalization::Calendar^ get();
00062             void set(Windows::Globalization::Calendar^ value);
00063         }
00064
00065         property Windows::Globalization::Calendar^ EndDate
00066         {
00067             Windows::Globalization::Calendar^ get();
00068             void set(Windows::Globalization::Calendar^ value);
00069         }
00070
00071         property Platform::String^ Notes
00072         {
00073             Platform::String^ get();
00074             void set(Platform::String^ value);
00075         }
00076
00077     private:
00078         int subscribers;
00079         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler ^ _PropertyChanged;
00080         Platform::String^ destination;
00081         Platform::String^ description;
00082         Windows::Globalization::Calendar^ startDate;
00083         Windows::Globalization::Calendar^ endDate;
00084         Platform::String^ notes;
00085
00086         void NotifyPropertyChanged(Platform::String^ propertyName);
00087     };
00088
00089 }
Generated on Fri Nov 15 2024 22:18:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/HttpJsonContent.cpp Source File

  • HttpClient
  • cppwinrt

HttpJsonContent.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "HttpJsonContent.h"
00014 #include "HttpJsonContent.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace winrt::Windows::Data::Json;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::Security::Cryptography;
00020 using namespace winrt::Windows::Storage::Streams;
00021 using namespace winrt::Windows::Web::Http;
00022 using namespace winrt::Windows::Web::Http::Headers;
00023
00024 namespace winrt::SDKTemplate::implementation
00025 {
00026     HttpJsonContent::HttpJsonContent(IJsonValue const& jsonValue) : m_jsonValue(jsonValue)
00027     {
00028         if (jsonValue == nullptr)
00029         {
00030             throw hresult_invalid_argument(L"jsonValue");
00031         }
00032
00033         HttpMediaTypeHeaderValue headerValue(L"application/json");
00034         headerValue.CharSet(L"UTF-8");
00035         m_headers.ContentType(headerValue);
00036     }
00037
00038     IAsyncOperationWithProgress<uint64_t, uint64_t> HttpJsonContent::BufferAllAsync()
00039     {
00040         auto progress = co_await get_progress_token();
00041         uint64_t length = GetLength();
00042
00043         // Report progress.
00044         progress(length);
00045
00046         // Just return the size in bytes.
00047         co_return length;
00048     }
00049
00050     IAsyncOperationWithProgress<IBuffer, uint64_t> HttpJsonContent::ReadAsBufferAsync()
00051     {
00052         co_return ToBuffer();
00053     }
00054
00055     IAsyncOperationWithProgress<IInputStream, uint64_t> HttpJsonContent::ReadAsInputStreamAsync()
00056     {
00057         auto lifetime = get_strong();
00058         auto progress = co_await get_progress_token();
00059
00060         InMemoryRandomAccessStream randomAccessStream;
00061         co_await randomAccessStream.WriteAsync(ToBuffer());
00062
00063         // Report progress.
00064         progress(randomAccessStream.Size());
00065
00066         co_return randomAccessStream.GetInputStreamAt(0);
00067     }
00068
00069     IAsyncOperationWithProgress<hstring, uint64_t> HttpJsonContent::ReadAsStringAsync()
00070     {
00071         auto lifetime = get_strong();
00072         auto progress = co_await get_progress_token();
00073
00074         hstring jsonString = m_jsonValue.Stringify();
00075
00076         // Report progress (length of string)
00077         progress(jsonString.size());
00078
00079         co_return jsonString;
00080     }
00081
00082     bool HttpJsonContent::TryComputeLength(uint64_t& length)
00083     {
00084         length = GetLength();
00085         return true;
00086     }
00087
00088     IAsyncOperationWithProgress<uint64_t, uint64_t> HttpJsonContent::WriteToStreamAsync(IOutputStream outputStream)
00089     {
00090         auto lifetime = get_strong();
00091         auto progress = co_await get_progress_token();
00092
00093         auto bytesStored = co_await outputStream.WriteAsync(ToBuffer());
00094
00095         // Report progress.
00096         progress(bytesStored);
00097
00098         co_return bytesStored;
00099     }
00100
00101     uint64_t HttpJsonContent::GetLength()
00102     {
00103         return ToBuffer().Length();
00104     }
00105
00106     IBuffer HttpJsonContent::ToBuffer()
00107     {
00108         return CryptographicBuffer::ConvertStringToBinary(m_jsonValue.Stringify(), BinaryStringEncoding::Utf8);
00109     }
00110 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario09_GetCookie Member List

This is the complete list of members for Scenario09_GetCookie, including all inherited members.
Cancel_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario09_GetCookie |
CancelableRequestAsync(Windows::Foundation::Uri resourceUri) | Scenario09_GetCookie | [private]
GetCookies_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario09_GetCookie |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario09_GetCookie |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario09_GetCookie |
Scenario09_GetCookie() | Scenario09_GetCookie |
SendHttpGetButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario09_GetCookie |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/shared/TypeConversionHelpers.h Source File

  • AllJoyn
  • shared

TypeConversionHelpers.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #pragma once
00022
00023 ref class TypeConversionHelpers
00024 {
00025 internal:
00026     // Get the array of primitive values stored in the given alljoyn_msgarg.  The values in the array will be returned as
00027     // a Windows::Foundation::Collections::IVector.
00028     template<class T>
00029     static _Check_return_ int32 GetPrimitiveArrayMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IVector<T>^* value)
00030     {
00031         *value = nullptr;
00032         size_t elementCount = 0;
00033         T* arrayContents = nullptr;
00034         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_get(argument, signature, &elementCount, &arrayContents));
00035
00036         if (arrayContents == nullptr)
00037         {
00038             *value = ref new Platform::Collections::Vector<T>();
00039         }
00040         else
00041         {
00042             *value = ref new Platform::Collections::Vector<T>(ref new Platform::Array<T>(arrayContents, static_cast<unsigned int>(elementCount)));
00043         }
00044
00045         return ER_OK;
00046     }
00047
00048     // Get the array of primitive values stored in the given alljoyn_msgarg.  The values in the array will be returned as
00049     // a Windows::Foundation::Collections::IVectorView.
00050     template<class T>
00051     static _Check_return_ int32 GetPrimitiveArrayMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IVectorView<T>^* value)
00052     {
00053         Windows::Foundation::Collections::IVector<T>^ result;
00054         int32 status = GetPrimitiveArrayMessageArg(argument, signature, &result);
00055         *value = result->GetView();
00056         return status;
00057     }
00058
00059     // Check whether the value passed in is an AllJoyn type signature for an array of primitive values,
00060     // such as an array of int32s or an array of booleans.
00061     static _Check_return_ bool IsArrayOfPrimitives(_In_ PCSTR signature)
00062     {
00063         return (strlen(signature) == 2) && (signature[1] != 's') && (signature[1] != 'v');
00064     }
00065
00066     // Find the next complete type in the given AllJoyn type signature and append it to typeSignature.
00067     //
00068     // Examples:
00069     //   If signature is "ii", it will append "i", because that string describes the integer type
00070     //   If signature is "a(is)si" it will append "a(is)", because that string fully describes an array of structures.
00071     static _Check_return_ int32 AppendNextCompleteType(_In_ PCSTR signature, _Inout_ std::vector<char>* typeSignature);
00072
00073     // Get the key and value types from the type AllJoyn type signature for a dictionary.
00074     static _Check_return_ int32 GetDictionaryTypeSignatures(_In_ PCSTR signature, _Inout_ std::vector<char>* keySignature, _Inout_ std::vector<char>* valueSignature);
00075
00076     // Get the value of an alljoyn_msgarg whose value matches WinRT type T.
00077     //
00078     // The default implementation of this function passes the value directly to alljoyn_msgarg_get, which
00079     // will work for any primitive types (int32, byte, etc.)  More complex types that require additional
00080     // work to convert between the WinRT type and the AllJoyn type must have a specialization of this template
00081     // function to perform the conversion.
00082     template<class T>
00083     static _Check_return_ int32 GetAllJoynMessageArg(alljoyn_msgarg argument, PCSTR signature, _Out_ T* value)
00084     {
00085         return alljoyn_msgarg_get(argument, signature, value);
00086     }
00087
00088     // Set the value of an alljoyn_msgarg to the value of WinRT type T.
00089     //
00090     // The default implementation of this function passes the value directly to alljoyn_msgarg_set, which
00091     // will work for any primitive types (int32, byte, etc.)  More complex types that require additional
00092     // work to convert between the WinRT type and the AllJoyn type must have a specialization of this template
00093     // function to perform the conversion.
00094     template<class T>
00095     static _Check_return_ int32 SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ T value)
00096     {
00097         return alljoyn_msgarg_set(argument, signature, value);
00098     }
00099
00100     static _Check_return_ int32 GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Platform::String^* value)
00101     {
00102         *value = nullptr;
00103         PSTR allJoynValue = nullptr;
00104         QStatus status = alljoyn_msgarg_get(argument, signature, &allJoynValue);
00105         if ((ER_OK == status) && (nullptr != allJoynValue))
00106         {
00107             *value = AllJoynHelpers::MultibyteToPlatformString(allJoynValue);
00108         }
00109         return static_cast<int32>(status);
00110     }
00111
00112     static _Check_return_ int32 SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Platform::String^ value)
00113     {
00114         std::vector<char> inputArg = AllJoynHelpers::PlatformToMultibyteString(value);
00115         return alljoyn_msgarg_set_and_stabilize(argument, signature, inputArg.data());
00116     }
00117
00118     template<class T>
00119     static _Check_return_ int32 GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IVector<T>^* value)
00120     {
00121         *value = ref new Platform::Collections::Vector<T>();
00122         if (signature[0] != 'a')
00123         {
00124             return ER_BUS_SIGNATURE_MISMATCH;
00125         }
00126
00127         if (IsArrayOfPrimitives(signature))
00128         {
00129             return GetPrimitiveArrayMessageArg(argument, signature, value);
00130         }
00131
00132         // Remove the 'a' to get the signature of an array element.
00133         PCSTR elementSignature = signature + 1;
00134         size_t elementCount = 0;
00135         alljoyn_msgarg arrayContents = nullptr;
00136         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_get(argument, signature, &elementCount, &arrayContents));
00137
00138         if (arrayContents != nullptr)
00139         {
00140             for (size_t i = 0; i < elementCount; i++)
00141             {
00142                 T elementValue;
00143                 RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(alljoyn_msgarg_array_element(arrayContents, i), elementSignature, &elementValue));
00144                 (*value)->Append(elementValue);
00145             }
00146         }
00147
00148         return ER_OK;
00149     }
00150
00151     template<class T>
00152     static _Check_return_ int32 SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Windows::Foundation::Collections::IVectorView<T>^ value)
00153     {
00154         if (signature[0] != 'a')
00155         {
00156             return ER_BUS_SIGNATURE_MISMATCH;
00157         }
00158
00159         // An empty or null vector will cause errors in AllJoyn.
00160         if (value == nullptr || value->Size < 1)
00161         {
00162             return ER_INVALID_DATA;
00163         }
00164
00165         // Remove the 'a' to get the signature of an array element.
00166         PCSTR elementSignature = signature + 1;
00167         alljoyn_msgarg arrayArgument = alljoyn_msgarg_array_create(value->Size);
00168
00169         for (size_t i = 0; i < value->Size; i++)
00170         {
00171             RETURN_IF_QSTATUS_ERROR(SetAllJoynMessageArg(alljoyn_msgarg_array_element(arrayArgument, i), elementSignature, value->GetAt(static_cast<unsigned int>(i))));
00172         }
00173
00174         QStatus status = alljoyn_msgarg_set_and_stabilize(argument, "a*", (size_t)value->Size, arrayArgument);
00175         alljoyn_msgarg_destroy(arrayArgument);
00176         return static_cast<int32>(status);
00177     }
00178
00179     template<class T>
00180     static _Check_return_ int32 GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IVectorView<T>^* value)
00181     {
00182         Windows::Foundation::Collections::IVector<T>^ result;
00183         int32 status = GetAllJoynMessageArg(argument, signature, &result);
00184         *value = result->GetView();
00185         return status;
00186     }
00187
00188     template<class T>
00189     static _Check_return_ int32 SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Windows::Foundation::Collections::IVector<T>^ value)
00190     {
00191         return SetAllJoynMessageArg(argument, signature, value->GetView());
00192     }
00193
00194     static _Check_return_ int32 SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Windows::Foundation::Collections::IVectorView<Platform::String^>^ value)
00195     {
00196         // An empty or null vector will cause errors in AllJoyn.
00197         if (value == nullptr || value->Size < 1)
00198         {
00199             return ER_INVALID_DATA;
00200         }
00201
00202         std::vector<std::vector<char>> strings;
00203         for (unsigned int i = 0; i < value->Size; i++)
00204         {
00205             strings.push_back(AllJoynHelpers::PlatformToMultibyteString(value->GetAt(i)));
00206         }
00207
00208         // alljoyn_msgarg_set expects the strings to be in the form of an array of char*.
00209         std::vector<char*> allJoynArgument;
00210         for (unsigned int i = 0; i < value->Size; i++)
00211         {
00212             allJoynArgument.push_back(strings.at(i).data());
00213         }
00214
00215         return alljoyn_msgarg_set_and_stabilize(argument, signature, value->Size, allJoynArgument.data());
00216     }
00217
00218     static _Check_return_ int32 GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IVector<Platform::String^>^* value)
00219     {
00220         *value = ref new Platform::Collections::Vector<Platform::String^>();
00221         size_t elementCount = 0;
00222         alljoyn_msgarg arrayContents = nullptr;
00223         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_get(argument, signature, &elementCount, &arrayContents));
00224
00225         if (arrayContents != nullptr)
00226         {
00227             for (size_t i = 0; i < elementCount; i++)
00228             {
00229                 Platform::String^ elementValue;
00230                 RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(alljoyn_msgarg_array_element(arrayContents, i), "s", &elementValue));
00231                 (*value)->Append(elementValue);
00232             }
00233         }
00234
00235         return S_OK;
00236     }
00237
00238     static _Check_return_ int32 GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IVectorView<Platform::String^>^* value)
00239     {
00240         Windows::Foundation::Collections::IVector<Platform::String^>^ result;
00241         int32 status = GetAllJoynMessageArg(argument, signature, &result);
00242         *value = result->GetView();
00243         return status;
00244     }
00245
00246     static _Check_return_ int32 SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Windows::Foundation::Collections::IVector<Platform::String^>^ value)
00247     {
00248         return SetAllJoynMessageArg(argument, signature, value->GetView());
00249     }
00250
00251     template<class T, class U>
00252     static _Check_return_ int32 GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IMap<T, U>^* value)
00253     {
00254         *value = ref new Platform::Collections::Map<T, U>();
00255
00256         std::vector<char> keyType;
00257         std::vector<char> valueType;
00258         RETURN_IF_QSTATUS_ERROR(GetDictionaryTypeSignatures(signature, &keyType, &valueType));
00259
00260         size_t elementCount = 0;
00261         alljoyn_msgarg dictionaryContents = nullptr;
00262         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_get(argument, signature, &elementCount, &dictionaryContents));
00263
00264         if (dictionaryContents != nullptr)
00265         {
00266             for (size_t i = 0; i < elementCount; i++)
00267             {
00268                 alljoyn_msgarg keyArg, valueArg;
00269                 RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_get(alljoyn_msgarg_array_element(dictionaryContents, i), "{**}", &keyArg, &valueArg));
00270                 T dictionaryKey;
00271                 RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(keyArg, keyType.data(), &dictionaryKey));
00272                 U dictionaryValue;
00273                 RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(valueArg, valueType.data(), &dictionaryValue));
00274
00275                 (*value)->Insert(dictionaryKey, dictionaryValue);
00276             }
00277         }
00278
00279         return ER_OK;
00280     }
00281
00282     template<class T>
00283     static _Check_return_ int32 GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IMap<T, Platform::Object^>^* value)
00284     {
00285         *value = ref new Platform::Collections::Map<T, Platform::Object^>();
00286
00287         std::vector<char> keyType;
00288         std::vector<char> valueType;
00289         RETURN_IF_QSTATUS_ERROR(GetDictionaryTypeSignatures(signature, &keyType, &valueType));
00290
00291         size_t elementCount = 0;
00292         alljoyn_msgarg dictionaryContents = nullptr;
00293         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_get(argument, signature, &elementCount, &dictionaryContents));
00294
00295         if (dictionaryContents != nullptr)
00296         {
00297             for (size_t i = 0; i < elementCount; i++)
00298             {
00299                 alljoyn_msgarg keyArg, valueArg;
00300                 RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_get(alljoyn_msgarg_array_element(dictionaryContents, i), "{*v}", &keyArg, &valueArg));
00301                 T dictionaryKey;
00302                 RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(keyArg, keyType.data(), &dictionaryKey));
00303                 Platform::Object^ dictionaryValue;
00304                 RETURN_IF_QSTATUS_ERROR(GetValueFromVariant(valueArg, &dictionaryValue));
00305
00306                 (*value)->Insert(dictionaryKey, dictionaryValue);
00307             }
00308         }
00309
00310         return ER_OK;
00311     }
00312
00313     template<class T, class U>
00314     static _Check_return_ int32 SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, Windows::Foundation::Collections::IMapView<T, U>^ value)
00315     {
00316         std::vector<char> keyType;
00317         std::vector<char> valueType;
00318         RETURN_IF_QSTATUS_ERROR(GetDictionaryTypeSignatures(signature, &keyType, &valueType));
00319
00320         // An empty or null vector will cause errors in AllJoyn.
00321         if (value == nullptr || value->Size < 1)
00322         {
00323             return ER_INVALID_DATA;
00324         }
00325
00326         alljoyn_msgarg dictionaryArg = alljoyn_msgarg_array_create(value->Size);
00327
00328         int i = 0;
00329         for (auto dictionaryElement : value)
00330         {
00331             alljoyn_msgarg keyArg = alljoyn_msgarg_create();
00332             alljoyn_msgarg valueArg = alljoyn_msgarg_create();
00333             RETURN_IF_QSTATUS_ERROR(SetAllJoynMessageArg(keyArg, keyType.data(), dictionaryElement->Key));
00334             RETURN_IF_QSTATUS_ERROR(SetAllJoynMessageArg(valueArg, valueType.data(), dictionaryElement->Value));
00335
00336             RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_set_and_stabilize(alljoyn_msgarg_array_element(dictionaryArg, i++), "{**}", keyArg, valueArg));
00337             alljoyn_msgarg_destroy(keyArg);
00338             alljoyn_msgarg_destroy(valueArg);
00339         }
00340
00341         QStatus status = alljoyn_msgarg_set_and_stabilize(argument, signature, (size_t)value->Size, dictionaryArg);
00342         alljoyn_msgarg_destroy(dictionaryArg);
00343         return static_cast<int32>(status);
00344     }
00345
00346     template<class T, class U>
00347     static _Check_return_ int32 GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Windows::Foundation::Collections::IMapView<T, U>^* value)
00348     {
00349         Windows::Foundation::Collections::IMap<T, U>^ result;
00350         int32 status = GetAllJoynMessageArg(argument, signature, &result);
00351         *value = result->GetView();
00352         return status;
00353     }
00354
00355     template<class T, class U>
00356     static _Check_return_ int32 SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Windows::Foundation::Collections::IMap<T, U>^ value)
00357     {
00358         return SetAllJoynMessageArg(argument, signature, value->GetView());
00359     }
00360
00361     static _Check_return_ int32 SetVariantStructureArg(_In_ alljoyn_msgarg argument, _In_ PROJECT_NAMESPACE::AllJoynMessageArgStructure^ value)
00362     {
00363         alljoyn_msgarg variantArg = alljoyn_msgarg_create();
00364         alljoyn_msgarg fields = alljoyn_msgarg_array_create(value->Size);
00365         for (unsigned int i = 0; i < value->Size; i++)
00366         {
00367             RETURN_IF_QSTATUS_ERROR(SetAllJoynMessageArg(alljoyn_msgarg_array_element(fields, i), "v", value->GetAt(i)));
00368         }
00369
00370         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_setstruct(variantArg, fields, value->Size));
00371         alljoyn_msgarg_destroy(fields);
00372
00373         QStatus status = alljoyn_msgarg_set_and_stabilize(argument, "v", variantArg);
00374         alljoyn_msgarg_destroy(variantArg);
00375
00376         return static_cast<int32>(status);
00377     }
00378
00379     static _Check_return_ int32 GetVariantStructureArg(_In_ alljoyn_msgarg argument, _Outptr_result_maybenull_ Platform::Object^* value)
00380     {
00381         *value = nullptr;
00382         size_t memberCount = alljoyn_msgarg_getnummembers(argument);
00383         auto result = ref new PROJECT_NAMESPACE::AllJoynMessageArgStructure();
00384
00385         for (size_t i = 0; i < memberCount; i++)
00386         {
00387             Platform::Object^ variantValue;
00388             RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(alljoyn_msgarg_getmember(argument, i), "v", &variantValue));
00389             result->Append(variantValue);
00390         }
00391
00392         *value = result;
00393         return ER_OK;
00394     }
00395
00396     template<class T>
00397     static _Check_return_ int32 SetVariantArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ T value)
00398     {
00399         alljoyn_msgarg variantArg = alljoyn_msgarg_create();
00400         RETURN_IF_QSTATUS_ERROR(SetAllJoynMessageArg(variantArg, signature, value));
00401         QStatus status = alljoyn_msgarg_set_and_stabilize(argument, "v", variantArg);
00402         alljoyn_msgarg_destroy(variantArg);
00403         return status;
00404     }
00405
00406     template<class T>
00407     static _Check_return_ int32 GetVariantArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Platform::Object^* value)
00408     {
00409         *value = nullptr;
00410
00411         T innerValue;
00412         RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(argument, signature, &innerValue));
00413         *value = innerValue;
00414         return ER_OK;
00415     }
00416
00417     static _Check_return_ int32 SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ Platform::Object^ value)
00418     {
00419         UNREFERENCED_PARAMETER(signature);
00420
00421         auto byteValue = dynamic_cast<Platform::IBox<byte>^>(value);
00422         if (byteValue != nullptr)
00423         {
00424             return SetVariantArg(argument, "y", byteValue->Value);
00425         }
00426         auto boolValue = dynamic_cast<Platform::IBox<bool>^>(value);
00427         if (boolValue != nullptr)
00428         {
00429             return SetVariantArg(argument, "b", boolValue->Value);
00430         }
00431         auto int16Value = dynamic_cast<Platform::IBox<int16>^>(value);
00432         if (int16Value != nullptr)
00433         {
00434             return SetVariantArg(argument, "n", int16Value->Value);
00435         }
00436         auto uint16Value = dynamic_cast<Platform::IBox<uint16>^>(value);
00437         if (uint16Value != nullptr)
00438         {
00439             return SetVariantArg(argument, "q", uint16Value->Value);
00440         }
00441         auto int32Value = dynamic_cast<Platform::IBox<int32>^>(value);
00442         if (int32Value != nullptr)
00443         {
00444             return SetVariantArg(argument, "i", int32Value->Value);
00445         }
00446         auto uint32Value = dynamic_cast<Platform::IBox<uint32>^>(value);
00447         if (uint32Value != nullptr)
00448         {
00449             return SetVariantArg(argument, "u", uint32Value->Value);
00450         }
00451         auto int64Value = dynamic_cast<Platform::IBox<int64>^>(value);
00452         if (int64Value != nullptr)
00453         {
00454             return SetVariantArg(argument, "x", int64Value->Value);
00455         }
00456         auto uint64Value = dynamic_cast<Platform::IBox<uint64>^>(value);
00457         if (uint64Value != nullptr)
00458         {
00459             return SetVariantArg(argument, "t", uint64Value->Value);
00460         }
00461         auto doubleValue = dynamic_cast<Platform::IBox<double>^>(value);
00462         if (doubleValue != nullptr)
00463         {
00464             return SetVariantArg(argument, "d", doubleValue->Value);
00465         }
00466         auto stringValue = dynamic_cast<Platform::String^>(value);
00467         if (stringValue != nullptr)
00468         {
00469             return SetVariantArg(argument, "s", stringValue);
00470         }
00471         auto structValue = dynamic_cast<PROJECT_NAMESPACE::AllJoynMessageArgStructure^>(value);
00472         if (structValue != nullptr)
00473         {
00474             return SetVariantStructureArg(argument, structValue);
00475         }
00476         auto vectorValue = dynamic_cast<Windows::Foundation::Collections::IVector<Platform::Object^>^>(value);
00477         if (vectorValue != nullptr)
00478         {
00479             return SetVariantArg(argument, "av", vectorValue);
00480         }
00481         auto byteMapValue = dynamic_cast<Windows::Foundation::Collections::IMap<byte, Platform::Object^>^>(value);
00482         if (byteMapValue != nullptr)
00483         {
00484             return SetVariantArg(argument, "a{yv}", byteMapValue);
00485         }
00486         auto boolMapValue = dynamic_cast<Windows::Foundation::Collections::IMap<bool, Platform::Object^>^>(value);
00487         if (boolMapValue != nullptr)
00488         {
00489             return SetVariantArg(argument, "a{bv}", boolMapValue);
00490         }
00491         auto int16MapValue = dynamic_cast<Windows::Foundation::Collections::IMap<int16, Platform::Object^>^>(value);
00492         if (int16MapValue != nullptr)
00493         {
00494             return SetVariantArg(argument, "a{nv}", int16MapValue);
00495         }
00496         auto uint16MapValue = dynamic_cast<Windows::Foundation::Collections::IMap<uint16, Platform::Object^>^>(value);
00497         if (uint16MapValue != nullptr)
00498         {
00499             return SetVariantArg(argument, "a{qv}", int16MapValue);
00500         }
00501         auto int32MapValue = dynamic_cast<Windows::Foundation::Collections::IMap<int32, Platform::Object^>^>(value);
00502         if (int32MapValue != nullptr)
00503         {
00504             return SetVariantArg(argument, "a{iv}", int32MapValue);
00505         }
00506         auto uint32MapValue = dynamic_cast<Windows::Foundation::Collections::IMap<uint32, Platform::Object^>^>(value);
00507         if (uint32MapValue != nullptr)
00508         {
00509             return SetVariantArg(argument, "a{uv}", uint32MapValue);
00510         }
00511         auto int64MapValue = dynamic_cast<Windows::Foundation::Collections::IMap<int64, Platform::Object^>^>(value);
00512         if (int64MapValue != nullptr)
00513         {
00514             return SetVariantArg(argument, "a{xv}", int64MapValue);
00515         }
00516         auto uint64MapValue = dynamic_cast<Windows::Foundation::Collections::IMap<uint64, Platform::Object^>^>(value);
00517         if (uint64MapValue != nullptr)
00518         {
00519             return SetVariantArg(argument, "a{tv}", uint64MapValue);
00520         }
00521         auto doubleMapValue = dynamic_cast<Windows::Foundation::Collections::IMap<double, Platform::Object^>^>(value);
00522         if (doubleMapValue != nullptr)
00523         {
00524             return SetVariantArg(argument, "a{dv}", doubleMapValue);
00525         }
00526         auto stringMapValue = dynamic_cast<Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^>(value);
00527         if (stringMapValue != nullptr)
00528         {
00529             return SetVariantArg(argument, "a{sv}", stringMapValue);
00530         }
00531
00532         return ER_BUS_BAD_VALUE_TYPE;
00533     }
00534
00535     static _Check_return_ int32 GetMapFromVariant(_In_ alljoyn_msgarg argument, _In_ char mapSignature, _Outptr_result_maybenull_ Platform::Object^* value)
00536     {
00537         *value = nullptr;
00538
00539         switch (mapSignature)
00540         {
00541         case 'y':
00542         {
00543             return GetVariantArg<Windows::Foundation::Collections::IMap<byte, Platform::Object^>^>(argument, "a{yv}", value);
00544         }
00545         case 'b':
00546         {
00547             return GetVariantArg<Windows::Foundation::Collections::IMap<bool, Platform::Object^>^>(argument, "a{bv}", value);
00548         }
00549         case 'n':
00550         {
00551             return GetVariantArg<Windows::Foundation::Collections::IMap<int16, Platform::Object^>^>(argument, "a{nv}", value);
00552         }
00553         case 'q':
00554         {
00555             return GetVariantArg<Windows::Foundation::Collections::IMap<uint16, Platform::Object^>^>(argument, "a{qv}", value);
00556         }
00557         case 'i':
00558         {
00559             return GetVariantArg<Windows::Foundation::Collections::IMap<int32, Platform::Object^>^>(argument, "a{iv}", value);
00560         }
00561         case 'u':
00562         {
00563             return GetVariantArg<Windows::Foundation::Collections::IMap<uint32, Platform::Object^>^>(argument, "a{uv}", value);
00564         }
00565         case 'x':
00566         {
00567             return GetVariantArg<Windows::Foundation::Collections::IMap<int64, Platform::Object^>^>(argument, "a{xv}", value);
00568         }
00569         case 't':
00570         {
00571             return GetVariantArg<Windows::Foundation::Collections::IMap<uint64, Platform::Object^>^>(argument, "a{tv}", value);
00572         }
00573         case 'd':
00574         {
00575             return GetVariantArg<Windows::Foundation::Collections::IMap<double, Platform::Object^>^>(argument, "a{dv}", value);
00576         }
00577         case 's':
00578         {
00579             return GetVariantArg<Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^>(argument, "a{sv}", value);
00580         }
00581         default:
00582             return ER_BUS_BAD_SIGNATURE;
00583         }
00584     }
00585
00586     static _Check_return_ int32 GetValueFromVariant(_In_ alljoyn_msgarg argument, _Outptr_result_maybenull_ Platform::Object^* value)
00587     {
00588         *value = nullptr;
00589         char variantSignature[c_MaximumSignatureLength];
00590         alljoyn_msgarg_signature(argument, variantSignature, c_MaximumSignatureLength);
00591
00592         switch (variantSignature[0])
00593         {
00594         case 'y':
00595             return GetVariantArg<byte>(argument, "y", value);
00596         case 'b':
00597             return GetVariantArg<bool>(argument, "b", value);
00598         case 'n':
00599             return GetVariantArg<int16>(argument, "n", value);
00600         case 'q':
00601             return GetVariantArg<uint16>(argument, "q", value);
00602         case 'i':
00603             return GetVariantArg<int32>(argument, "i", value);
00604         case 'u':
00605             return GetVariantArg<uint32>(argument, "u", value);
00606         case 'x':
00607             return GetVariantArg<int64>(argument, "x", value);
00608         case 't':
00609             return GetVariantArg<uint64>(argument, "t", value);
00610         case 'd':
00611             return GetVariantArg<double>(argument, "d", value);
00612         case 's':
00613             return GetVariantArg<Platform::String^>(argument, "s", value);
00614         case '(':
00615             return GetVariantStructureArg(argument, value);
00616         case 'a':
00617             if (strlen(variantSignature) < 2)
00618             {
00619                 return ER_BUS_BAD_SIGNATURE;
00620             }
00621             if (variantSignature[1] == '{')
00622             {
00623                 if (strlen(variantSignature) < 3)
00624                 {
00625                     return ER_BUS_BAD_SIGNATURE;
00626                 }
00627
00628                 return GetMapFromVariant(argument, variantSignature[2], value);
00629             }
00630             else
00631             {
00632                 return GetVariantArg<Windows::Foundation::Collections::IVector<Platform::Object^>^>(argument, "av", value);
00633             }
00634         }
00635
00636         return ER_BUS_BAD_SIGNATURE;
00637     }
00638
00639     static _Check_return_ int32 GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Outptr_result_maybenull_ Platform::Object^* value)
00640     {
00641         UNREFERENCED_PARAMETER(signature);
00642
00643         *value = nullptr;
00644         alljoyn_msgarg variantArg;
00645         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_get(argument, "v", &variantArg));
00646         return GetValueFromVariant(variantArg, value);
00647     }
00648 };
Generated on Fri Nov 15 2024 22:17:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInteractionMode/cppwinrt/SampleConfiguration.cpp Source File

  • UserInteractionMode
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::ViewManagement;
00020 using namespace SDKTemplate;
00021
00022 hstring implementation::MainPage::FEATURE_NAME()
00023 {
00024     return L"User interaction mode";
00025 }
00026
00027 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00028 {
00029     Scenario{ L"Responding to mode", xaml_typename<SDKTemplate::Scenario1_Basic>() },
00030 });
00031
00032 hstring winrt::to_hstring(UserInteractionMode value)
00033 {
00034     switch (value)
00035     {
00036     case UserInteractionMode::Mouse:
00037         return L"Mouse";
00038         break;
00039
00040     case UserInteractionMode::Touch:
00041         return L"Touch";
00042
00043     default:
00044         return to_hstring(get_abi(value));
00045     }
00046 }
Generated on Fri Nov 15 2024 22:17:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PdfDocument/cpp/SampleConfiguration.cpp Source File

  • PdfDocument
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Render document", "SDKTemplate.Scenario1_Render" },
00021 };
Generated on Fri Nov 15 2024 22:17:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Twitter Member List

This is the complete list of members for Scenario2_Twitter, including all inherited members.
GetNonce() | Scenario2_Twitter | [inline, private]
GetSignature(string sigBaseString, string consumerSecretKey) | Scenario2_Twitter | [inline, private]
GetTimeStamp() | Scenario2_Twitter | [inline, private]
GetTwitterRequestTokenAsync(string twitterCallbackUrl, string consumerKey) | Scenario2_Twitter | [inline, private]
GetTwitterUserNameAsync(string webAuthResultResponseData) | Scenario2_Twitter | [inline, private]
Launch_Click(object sender, RoutedEventArgs e) | Scenario2_Twitter | [inline, private]
OutputToken(String TokenUri) | Scenario2_Twitter | [inline, private]
rootPage | Scenario2_Twitter | [private]
Scenario2_Twitter() | Scenario2_Twitter | [inline]
SendDataAsync(String Url) | Scenario2_Twitter | [inline, private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_DataEvents Member List

This is the complete list of members for Scenario1_DataEvents, including all inherited members.
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_DataEvents |
ReadingChanged(Windows::Devices::Sensors::HumanPresenceSensor const &, Windows::Devices::Sensors::HumanPresenceSensorReadingChangedEventArgs e) | Scenario1_DataEvents | [private]
Scenario1_DataEvents() | Scenario1_DataEvents |
ScenarioGetSensor_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_DataEvents |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LightSensor/cs/Scenario1_DataEvents.xaml.cs Source File

  • LightSensor
  • cs

Scenario1_DataEvents.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using System;
00017 using Windows.Devices.Sensors;
00018 using Windows.Foundation;
00019 using System.Threading.Tasks;
00020 using Windows.UI.Core;
00021
00022 namespace LightSensorCS
00023 {
00024     public sealed partial class Scenario1_DataEvents : Page
00025     {
00026         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00027         // as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         private LightSensor _sensor;
00031         private uint _desiredReportInterval;
00032
00033         public Scenario1_DataEvents()
00034         {
00035             this.InitializeComponent();
00036
00037             _sensor = LightSensor.GetDefault();
00038             if (_sensor != null)
00039             {
00040                 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00041                 // This value will be used later to activate the sensor.
00042                 uint minReportInterval = _sensor.MinimumReportInterval;
00043                 _desiredReportInterval = minReportInterval > 100 ? minReportInterval : 100;
00044             }
00045             else
00046             {
00047                 rootPage.NotifyUser("No light sensor found", NotifyType.ErrorMessage);
00048             }
00049         }
00050
00051         /// <summary>
00052         /// Invoked when this page is about to be displayed in a Frame.
00053         /// </summary>
00054         /// <param name="e">Event data that describes how this page was reached. The Parameter
00055         /// property is typically used to configure the page.</param>
00056         protected override void OnNavigatedTo(NavigationEventArgs e)
00057         {
00058             ScenarioEnableButton.IsEnabled = true;
00059             ScenarioDisableButton.IsEnabled = false;
00060         }
00061
00062         /// <summary>
00063         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00064         /// </summary>
00065         /// <param name="e">
00066         /// Event data that can be examined by overriding code. The event data is representative
00067         /// of the navigation that will unload the current Page unless canceled. The
00068         /// navigation can potentially be canceled by setting Cancel.
00069         /// </param>
00070         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00071         {
00072             if (ScenarioDisableButton.IsEnabled)
00073             {
00074                 Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00075                 _sensor.ReadingChanged -= new TypedEventHandler<LightSensor, LightSensorReadingChangedEventArgs>(ReadingChanged);
00076
00077                 // Restore the default report interval to release resources while the sensor is not in use
00078                 _sensor.ReportInterval = 0;
00079             }
00080
00081             base.OnNavigatingFrom(e);
00082         }
00083
00084         /// <summary>
00085         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00086         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00087         /// </summary>
00088         /// <param name="sender"></param>
00089         /// <param name="e">
00090         /// Event data that can be examined for the current visibility state.
00091         /// </param>
00092         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00093         {
00094             if (ScenarioDisableButton.IsEnabled)
00095             {
00096                 if (e.Visible)
00097                 {
00098                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00099                     _sensor.ReadingChanged += new TypedEventHandler<LightSensor, LightSensorReadingChangedEventArgs>(ReadingChanged);
00100                 }
00101                 else
00102                 {
00103                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00104                     _sensor.ReadingChanged -= new TypedEventHandler<LightSensor, LightSensorReadingChangedEventArgs>(ReadingChanged);
00105                 }
00106             }
00107         }
00108
00109         /// <summary>
00110         /// This is the event handler for ReadingChanged events.
00111         /// </summary>
00112         /// <param name="sender"></param>
00113         /// <param name="e"></param>
00114         async private void ReadingChanged(object sender, LightSensorReadingChangedEventArgs e)
00115         {
00116             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00117             {
00118                 LightSensorReading reading = e.Reading;
00119                 ScenarioOutput_LUX.Text = String.Format("{0,5:0.00}", reading.IlluminanceInLux);
00120             });
00121         }
00122
00123         /// <summary>
00124         /// This is the click handler for the 'Enable' button.
00125         /// </summary>
00126         /// <param name="sender"></param>
00127         /// <param name="e"></param>
00128         private void ScenarioEnable(object sender, RoutedEventArgs e)
00129         {
00130             if (_sensor != null)
00131             {
00132                 // Establish the report interval
00133                 _sensor.ReportInterval = _desiredReportInterval;
00134
00135                 Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged);
00136                 _sensor.ReadingChanged += new TypedEventHandler<LightSensor, LightSensorReadingChangedEventArgs>(ReadingChanged);
00137
00138                 ScenarioEnableButton.IsEnabled = false;
00139                 ScenarioDisableButton.IsEnabled = true;
00140             }
00141             else
00142             {
00143                 rootPage.NotifyUser("No light sensor found", NotifyType.ErrorMessage);
00144             }
00145         }
00146
00147         /// <summary>
00148         /// This is the click handler for the 'Disable' button.
00149         /// </summary>
00150         /// <param name="sender"></param>
00151         /// <param name="e"></param>
00152         private void ScenarioDisable(object sender, RoutedEventArgs e)
00153         {
00154             Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00155             _sensor.ReadingChanged -= new TypedEventHandler<LightSensor, LightSensorReadingChangedEventArgs>(ReadingChanged);
00156
00157             // Restore the default report interval to release resources while the sensor is not in use
00158             _sensor.ReportInterval = 0;
00159
00160             ScenarioEnableButton.IsEnabled = true;
00161             ScenarioDisableButton.IsEnabled = false;
00162         }
00163     }
00164 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomUsbDeviceAccess/cs/Utilities.cs Source File

  • CustomUsbDeviceAccess
  • cs

Utilities.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017
00018 using Windows.Devices.Usb;
00019 using Windows.UI.Xaml;
00020 using SDKTemplate;
00021
00022 namespace CustomUsbDeviceAccess
00023 {
00024     class Utilities
00025     {
00026         /// <summary>
00027         /// Displays the compatible scenarios and hides the non-compatible ones.
00028         /// If there are no supported devices, the scenarioContainer will be hidden and an error message
00029         /// will be displayed.
00030         /// </summary>
00031         /// <param name="scenarios">The key is the device type that the value, scenario, supports.</param>
00032         /// <param name="scenarioContainer">The container that encompasses all the scenarios that are specific to devices</param>
00033         public static void SetUpDeviceScenarios(Dictionary<DeviceType, UIElement> scenarios, UIElement scenarioContainer)
00034         {
00035             UIElement supportedScenario = null;
00036
00037             if (EventHandlerForDevice.Current.IsDeviceConnected)
00038             {
00039                 foreach (KeyValuePair<DeviceType, UIElement> deviceScenario in scenarios)
00040                 {
00041                     // Enable the scenario if it's generic or the device type matches
00042                     if ((deviceScenario.Key == DeviceType.All)
00043                         || (deviceScenario.Key == Utilities.GetDeviceType(EventHandlerForDevice.Current.Device)))
00044                     {
00045                         // Make the scenario visible in case other devices use the same scenario and collapsed it.
00046                         deviceScenario.Value.Visibility = Visibility.Visible;
00047
00048                         supportedScenario = deviceScenario.Value;
00049                     }
00050                     else if (deviceScenario.Value != supportedScenario)
00051                     {
00052                         // Don't hide the scenario if it is supported by the current device and is shared by other devices
00053
00054                         deviceScenario.Value.Visibility = Visibility.Collapsed;
00055                     }
00056                 }
00057             }
00058
00059             if (supportedScenario == null)
00060             {
00061                 // Hide the container so that common elements shared across scenarios are also hidden
00062                 scenarioContainer.Visibility = Visibility.Collapsed;
00063
00064                 NotifyDeviceNotConnected();
00065             }
00066         }
00067
00068         /// <summary>
00069         /// Device type of the device provided device.
00070         /// </summary>
00071         /// <param name="device"></param>
00072         /// <returns>The DeviceType of the device or DeviceType.None if there are no devices connected or is not recognized</returns>
00073         public static DeviceType GetDeviceType(UsbDevice device)
00074         {
00075             if (device != null)
00076             {
00077                 if (device.DeviceDescriptor.VendorId == OsrFx2.DeviceVid
00078                     && device.DeviceDescriptor.ProductId == OsrFx2.DevicePid)
00079                 {
00080                     return DeviceType.OsrFx2;
00081                 }
00082                 else if (device.DeviceDescriptor.VendorId == SuperMutt.DeviceVid
00083                     && device.DeviceDescriptor.ProductId == SuperMutt.DevicePid)
00084                 {
00085                     return DeviceType.SuperMutt;
00086                 }
00087             }
00088
00089             return DeviceType.None;
00090         }
00091
00092         public static Boolean IsSuperMuttDevice(UsbDevice device)
00093         {
00094             return (GetDeviceType(device) == DeviceType.SuperMutt);
00095         }
00096
00097         /// <summary>
00098         /// Prints an error message stating that device is not connected
00099         /// </summary>
00100         public static void NotifyDeviceNotConnected()
00101         {
00102             MainPage.Current.NotifyUser("Device is not connected, please select a plugged in device to try the scenario again", NotifyType.ErrorMessage);
00103         }
00104     }
00105 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AppViewSource Member List

This is the complete list of members for AppViewSource, including all inherited members.
CreateView() AppViewSource [inline]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LightSensor/cs/SampleConfiguration.cs Source File

  • LightSensor
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using LightSensorCS;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Light Sensor";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title = "Data Events", ClassType = typeof(LightSensorCS.Scenario1_DataEvents) },
00026             new Scenario() { Title = "Polling", ClassType = typeof(LightSensorCS.Scenario2_Polling) }
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cppwinrt/pch.cpp Source File

  • WebSocket
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/Common/BasicMath.h Source File

  • Simple3DGameDX
  • cppwinrt
  • Common

BasicMath.h

Go to the documentation of this file.
00001 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 // PARTICULAR PURPOSE.
00005 //
00006 // Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #define _USE_MATH_DEFINES
00011 #include <math.h>
00012
00013 // This header defines math and matrix helper functions and structures used
00014 // by DirectX SDK samples.
00015
00016 // Common Constants
00017
00018 #define PI_F 3.1415927f
00019
00020 // Template Vector & Matrix Classes
00021
00022 template <class T> struct Vector2
00023 {
00024     union
00025     {
00026         struct
00027         {
00028             T x;
00029             T y;
00030         } coord;
00031         struct
00032         {
00033             T r;
00034             T g;
00035         } color;
00036         struct
00037         {
00038             T u;
00039             T v;
00040         } textcoord;
00041     };
00042
00043     T& operator[](unsigned int index)
00044     {
00045         return static_cast<T*>(this)[index];
00046     }
00047
00048     Vector2(T _x = 0, T _y = 0) : x(_x), y(_y) { }
00049 };
00050
00051 template <class T> struct Vector3
00052 {
00053     union
00054     {
00055         struct
00056         {
00057             T x;
00058             T y;
00059             T z;
00060         } coord;
00061         struct
00062         {
00063             T r;
00064             T g;
00065             T b;
00066         } color;
00067         struct
00068         {
00069             T u;
00070             T v;
00071             T w;
00072         } texcoord;
00073     };
00074
00075     T& operator[](unsigned int index)
00076     {
00077         return static_cast<T*>(this)[index];
00078     }
00079
00080     Vector3(T _x = 0, T _y = 0, T _z = 0) : coord{ _x, _y, _z } { }
00081 };
00082
00083 template <class T> struct Vector4
00084 {
00085     union
00086     {
00087         struct
00088         {
00089             T x;
00090             T y;
00091             T z;
00092             T w;
00093         } coord;
00094         struct
00095         {
00096             T r;
00097             T g;
00098             T b;
00099             T a;
00100         } color;
00101     };
00102
00103     T& operator[](unsigned int index)
00104     {
00105         return static_cast<T*>(this)[index];
00106     }
00107
00108     Vector4(T _x = 0, T _y = 0, T _z = 0, T _w = 0) : x(_x), y(_y), z(_z), w(_w) { }
00109 };
00110
00111 template <class T> struct Matrix4x4
00112 {
00113     union
00114     {
00115         struct
00116         {
00117             T _11; T _12; T _13; T _14;
00118             T _21; T _22; T _23; T _24;
00119             T _31; T _32; T _33; T _34;
00120             T _41; T _42; T _43; T _44;
00121         } onebased;
00122         struct
00123         {
00124             T _m00; T _m01; T _m02; T _m03;
00125             T _m10; T _m11; T _m12; T _m13;
00126             T _m20; T _m21; T _m22; T _m23;
00127             T _m30; T _m31; T _m32; T _m33;
00128         } zerobased;
00129     };
00130
00131     Matrix4x4(T value = 0)
00132     {
00133         onebased._11 = onebased._12 = onebased._13 = onebased._14 = value;
00134         onebased._21 = onebased._22 = onebased._23 = onebased._24 = value;
00135         onebased._31 = onebased._32 = onebased._33 = onebased._34 = value;
00136         onebased._41 = onebased._42 = onebased._43 = onebased._44 = value;
00137     }
00138
00139     Matrix4x4(
00140         T i11, T i12, T i13, T i14,
00141         T i21, T i22, T i23, T i24,
00142         T i31, T i32, T i33, T i34,
00143         T i41, T i42, T i43, T i44
00144         )
00145     {
00146         _11 = i11; _12 = i12; _13 = i13; _14 = i14;
00147         _21 = i21; _22 = i22; _23 = i23; _24 = i24;
00148         _31 = i31; _32 = i32; _33 = i33; _34 = i34;
00149         _41 = i41; _42 = i42; _43 = i43; _44 = i44;
00150     }
00151
00152     T* operator[](unsigned int index)
00153     {
00154         return &(reinterpret_cast<T*>(this)[index * 4]);
00155     }
00156 };
00157
00158 // Template Vector Operations
00159
00160 template <class T>
00161 T dot(Vector2<T> a, Vector2<T> b)
00162 {
00163     return a.x * b.x + a.y * b.y;
00164 }
00165
00166 template <class T>
00167 T dot(Vector3<T> a, Vector3<T> b)
00168 {
00169     return a.x * b.x + a.y * b.y + a.z * b.z;
00170 }
00171
00172 template <class T>
00173 T dot(Vector4<T> a, Vector4<T> b)
00174 {
00175     return a.x * b.x + a.y * b.y + a.z * b.z + a.w + b.w;
00176 }
00177
00178 template <class T>
00179 T length(Vector2<T> a)
00180 {
00181     return sqrt(a.x * a.x + a.y * a.y);
00182 }
00183
00184 template <class T>
00185 T length(Vector3<T> a)
00186 {
00187     return sqrt(a.coord.x * a.coord.x + a.coord.y * a.coord.y + a.coord.z * a.coord.z);
00188 }
00189
00190 template <class T>
00191 T length(Vector4<T> a)
00192 {
00193     return sqrt(a.coord.x * a.coord.x + a.coord.y * a.coord.y + a.coord.z * a.coord.z + a.coord.w * a.coord.w);
00194 }
00195
00196 template <class T>
00197 Vector3<T> cross(Vector3<T> a, Vector3<T> b)
00198 {
00199     return Vector3<T>((a.y * b.z) - (a.z * b.y), (a.z * b.x) - (a.x * b.z), (a.x * b.y) - (a.y * b.x));
00200 }
00201
00202 template <class T>
00203 Vector2<T> normalize(Vector2<T> a)
00204 {
00205     T len = length(a);
00206     return Vector2<T>(a.x / len, a.y / len);
00207 }
00208
00209 template <class T>
00210 Vector3<T> normalize(Vector3<T> a)
00211 {
00212     T len = length(a);
00213     return Vector3<T>(a.coord.x / len, a.coord.y / len, a.coord.z / len);
00214 }
00215
00216 template <class T>
00217 Vector4<T> normalize(Vector4<T> a)
00218 {
00219     T len = length(a);
00220     return Vector4<T>(a.coord.x / len, a.coord.y / len, a.coord.z / len, a.coord.w / len);
00221 }
00222
00223 // Template Vector Operators
00224
00225 template <class T>
00226 Vector2<T> operator-(Vector2<T> a, Vector2<T> b)
00227 {
00228     return Vector2<T>(a.x - b.x, a.y - b.y);
00229 }
00230
00231 template <class T>
00232 Vector2<T> operator-(Vector2<T> a)
00233 {
00234     return Vector2<T>(-a.x, -a.y);
00235 }
00236
00237 template <class T>
00238 Vector3<T> operator-(Vector3<T> a, Vector3<T> b)
00239 {
00240     return Vector3<T>(a.x - b.x, a.y - b.y, a.z - b.z);
00241 }
00242
00243 template <class T>
00244 Vector3<T> operator-(Vector3<T> a)
00245 {
00246     return Vector3<T>(-a.x, -a.y, -a.z);
00247 }
00248
00249 template <class T>
00250 Vector4<T> operator-(Vector4<T> a, Vector4<T> b)
00251 {
00252     return Vector4<T>(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
00253 }
00254
00255 template <class T>
00256 Vector4<T> operator-(Vector4<T> a)
00257 {
00258     return Vector4<T>(-a.x, -a.y, -a.z, -a.w);
00259 }
00260
00261 template <class T>
00262 Vector2<T> operator+(Vector2<T> a, Vector2<T> b)
00263 {
00264     return Vector2<T>(a.x + b.x, a.y + b.y);
00265 }
00266
00267 template <class T>
00268 Vector3<T> operator+(Vector3<T> a, Vector3<T> b)
00269 {
00270     return Vector3<T>(a.x + b.x, a.y + b.y, a.z + b.z);
00271 }
00272
00273 template <class T>
00274 Vector4<T> operator+(Vector4<T> a, Vector4<T> b)
00275 {
00276     return Vector4<T>(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
00277 }
00278
00279 template <class T>
00280 Vector2<T> operator*(Vector2<T> a, T s)
00281 {
00282     return Vector2<T>(a.x * s, a.y * s);
00283 }
00284
00285 template <class T>
00286 Vector2<T> operator*(T s, Vector2<T> a)
00287 {
00288     return a * s;
00289 }
00290
00291 template <class T>
00292 Vector2<T> operator*(Vector2<T> a, Vector2<T> b)
00293 {
00294     return Vector2<T>(a.x * b.x, a.y * b.y);
00295 }
00296
00297 template <class T>
00298 Vector2<T> operator/(Vector2<T> a, T s)
00299 {
00300     return Vector2<T>(a.x / s, a.y / s);
00301 }
00302
00303 template <class T>
00304 Vector3<T> operator*(Vector3<T> a, T s)
00305 {
00306     return Vector3<T>(a.x * s, a.y * s, a.z * s);
00307 }
00308
00309 template <class T>
00310 Vector3<T> operator*(T s, Vector3<T> a)
00311 {
00312     return a * s;
00313 }
00314
00315 template <class T>
00316 Vector3<T> operator*(Vector3<T> a, Vector3<T> b)
00317 {
00318     return Vector3<T>(a.x * b.x, a.y * b.y, a.z * b.z);
00319 }
00320
00321 template <class T>
00322 Vector3<T> operator/(Vector3<T> a, T s)
00323 {
00324     return Vector3<T>(a.x / s, a.y / s, a.z / s);
00325 }
00326
00327 template <class T>
00328 Vector4<T> operator*(Vector4<T> a, T s)
00329 {
00330     return Vector4<T>(a.x * s, a.y * s, a.z * s, a.w * s);
00331 }
00332
00333 template <class T>
00334 Vector4<T> operator*(T s, Vector4<T> a)
00335 {
00336     return a * s;
00337 }
00338
00339 template <class T>
00340 Vector4<T> operator*(Vector4<T> a, Vector4<T> b)
00341 {
00342     return Vector4<T>(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w);
00343 }
00344
00345 template <class T>
00346 Vector4<T> operator/(Vector4<T> a, T s)
00347 {
00348     return Vector4<T>(a.x / s, a.y / s, a.z / s, a.w / s);
00349 }
00350
00351
00352
00353 // Template Matrix Operations
00354
00355 template <class T>
00356 Matrix4x4<T> transpose(Matrix4x4<T> m)
00357 {
00358     return Matrix4x4<T>(
00359         m._11, m._21, m._31, m._41,
00360         m_.12, m._22, m._32, m._42,
00361         m._13, m._23, m._33, m._43,
00362         m._14, m._24, m._34, m._44
00363         );
00364 }
00365
00366 template <class T>
00367 Matrix4x4<T> mul(Matrix4x4<T> m1, Matrix4x4<T> m2)
00368 {
00369     Matrix4x4<T> mOut;
00370
00371     for (int i = 0; i < 4; i++)
00372     {
00373         for (int j = 0; j < 4; j++)
00374         {
00375             for (int k = 0; k < 4; k++)
00376             {
00377                 mOut[i][j] += m1[i][k] * m2[k][j];
00378             }
00379         }
00380     }
00381
00382     return mOut;
00383 }
00384
00385 // Common HLSL-compatible vector typedefs
00386
00387 typedef unsigned int uint;
00388
00389 typedef Vector2<float> float2;
00390 typedef Vector3<float> float3;
00391 typedef Vector4<float> float4;
00392
00393 typedef Matrix4x4<float> float4x4;
00394
00395 // Standard Matrix Intializers
00396
00397 inline float4x4 identity()
00398 {
00399     float4x4 mOut;
00400
00401     mOut.onebased._11 = 1.0f; mOut.onebased._12 = 0.0f; mOut.onebased._13 = 0.0f; mOut.onebased._14 = 0.0f;
00402     mOut.onebased._21 = 0.0f; mOut.onebased._22 = 1.0f; mOut.onebased._23 = 0.0f; mOut.onebased._24 = 0.0f;
00403     mOut.onebased._31 = 0.0f; mOut.onebased._32 = 0.0f; mOut.onebased._33 = 1.0f; mOut.onebased._34 = 0.0f;
00404     mOut.onebased._41 = 0.0f; mOut.onebased._42 = 0.0f; mOut.onebased._43 = 0.0f; mOut.onebased._44 = 1.0f;
00405
00406     return mOut;
00407 }
00408
00409 inline float4x4 translation(float x, float y, float z)
00410 {
00411     float4x4 mOut;
00412
00413     mOut.onebased._11 = 1.0f; mOut.onebased._12 = 0.0f; mOut.onebased._13 = 0.0f; mOut.onebased._14 = x;
00414     mOut.onebased._21 = 0.0f; mOut.onebased._22 = 1.0f; mOut.onebased._23 = 0.0f; mOut.onebased._24 = y;
00415     mOut.onebased._31 = 0.0f; mOut.onebased._32 = 0.0f; mOut.onebased._33 = 1.0f; mOut.onebased._34 = z;
00416     mOut.onebased._41 = 0.0f; mOut.onebased._42 = 0.0f; mOut.onebased._43 = 0.0f; mOut.onebased._44 = 1.0f;
00417
00418     return mOut;
00419 }
00420
00421 inline float4x4 scale(float x, float y, float z)
00422 {
00423     float4x4 mOut;
00424
00425     mOut.onebased._11 = x;    mOut.onebased._12 = 0.0f; mOut.onebased._13 = 0.0f; mOut.onebased._14 = 0.0f;
00426     mOut.onebased._21 = 0.0f; mOut.onebased._22 = y;    mOut.onebased._23 = 0.0f; mOut.onebased._24 = 0.0f;
00427     mOut.onebased._31 = 0.0f; mOut.onebased._32 = 0.0f; mOut.onebased._33 = z;    mOut.onebased._34 = 0.0f;
00428     mOut.onebased._41 = 0.0f; mOut.onebased._42 = 0.0f; mOut.onebased._43 = 0.0f; mOut.onebased._44 = 1.0f;
00429
00430     return mOut;
00431 }
00432
00433 inline float4x4 rotationX(float degreeX)
00434 {
00435     float angleInRadians = degreeX * (PI_F / 180.0f);
00436
00437     float sinAngle = sinf(angleInRadians);
00438     float cosAngle = cosf(angleInRadians);
00439
00440     float4x4 mOut;
00441
00442     mOut.onebased._11 = 1.0f; mOut.onebased._12 = 0.0f;     mOut.onebased._13 = 0.0f;      mOut.onebased._14 = 0.0f;
00443     mOut.onebased._21 = 0.0f; mOut.onebased._22 = cosAngle; mOut.onebased._23 = -sinAngle; mOut.onebased._24 = 0.0f;
00444     mOut.onebased._31 = 0.0f; mOut.onebased._32 = sinAngle; mOut.onebased._33 = cosAngle;  mOut.onebased._34 = 0.0f;
00445     mOut.onebased._41 = 0.0f; mOut.onebased._42 = 0.0f;     mOut.onebased._43 = 0.0f;      mOut.onebased._44 = 1.0f;
00446
00447     return mOut;
00448 }
00449
00450 inline float4x4 rotationY(float degreeY)
00451 {
00452     float angleInRadians = degreeY * (PI_F / 180.0f);
00453
00454     float sinAngle = sinf(angleInRadians);
00455     float cosAngle = cosf(angleInRadians);
00456
00457     float4x4 mOut;
00458
00459     mOut.onebased._11 = cosAngle;  mOut.onebased._12 = 0.0f; mOut.onebased._13 = sinAngle; mOut.onebased._14 = 0.0f;
00460     mOut.onebased._21 = 0.0f;      mOut.onebased._22 = 1.0f; mOut.onebased._23 = 0.0f;     mOut.onebased._24 = 0.0f;
00461     mOut.onebased._31 = -sinAngle; mOut.onebased._32 = 0.0f; mOut.onebased._33 = cosAngle; mOut.onebased._34 = 0.0f;
00462     mOut.onebased._41 = 0.0f;      mOut.onebased._42 = 0.0f; mOut.onebased._43 = 0.0f;     mOut.onebased._44 = 1.0f;
00463
00464     return mOut;
00465 }
00466
00467 inline float4x4 rotationZ(float degreeZ)
00468 {
00469     float angleInRadians = degreeZ * (PI_F / 180.0f);
00470
00471     float sinAngle = sinf(angleInRadians);
00472     float cosAngle = cosf(angleInRadians);
00473
00474     float4x4 mOut;
00475
00476     mOut.onebased._11 = cosAngle; mOut.onebased._12 = -sinAngle; mOut.onebased._13 = 0.0f; mOut.onebased._14 = 0.0f;
00477     mOut.onebased._21 = sinAngle; mOut.onebased._22 = cosAngle;  mOut.onebased._23 = 0.0f; mOut.onebased._24 = 0.0f;
00478     mOut.onebased._31 = 0.0f;     mOut.onebased._32 = 0.0f;      mOut.onebased._33 = 1.0f; mOut.onebased._34 = 0.0f;
00479     mOut.onebased._41 = 0.0f;     mOut.onebased._42 = 0.0f;      mOut.onebased._43 = 0.0f; mOut.onebased._44 = 1.0f;
00480
00481     return mOut;
00482 }
00483
00484 // 3D Rotation matrix for an arbitrary axis specified by x, y and z
00485 inline float4x4 rotationArbitrary(float3 axis, float degree)
00486 {
00487     axis = normalize(axis);
00488
00489     float angleInRadians = degree * (PI_F / 180.0f);
00490
00491     float sinAngle = sinf(angleInRadians);
00492     float cosAngle = cosf(angleInRadians);
00493     float oneMinusCosAngle = 1 - cosAngle;
00494
00495     float4x4 mOut;
00496
00497     mOut.onebased._11 = 1.0f + oneMinusCosAngle * (axis.coord.x * axis.coord.x - 1.0f);
00498     mOut.onebased._12 = axis.coord.z * sinAngle + oneMinusCosAngle * axis.coord.x * axis.coord.y;
00499     mOut.onebased._13 = -axis.coord.y * sinAngle + oneMinusCosAngle * axis.coord.x * axis.coord.z;
00500     mOut.onebased._41 = 0.0f;
00501
00502     mOut.onebased._21 = -axis.coord.z * sinAngle + oneMinusCosAngle * axis.coord.y * axis.coord.x;
00503     mOut.onebased._22 = 1.0f + oneMinusCosAngle * (axis.coord.y * axis.coord.y - 1.0f);
00504     mOut.onebased._23 = axis.coord.x * sinAngle + oneMinusCosAngle * axis.coord.y * axis.coord.z;
00505     mOut.onebased._24 = 0.0f;
00506
00507     mOut.onebased._31 = axis.coord.y * sinAngle + oneMinusCosAngle * axis.coord.z * axis.coord.x;
00508     mOut.onebased._32 = -axis.coord.x * sinAngle + oneMinusCosAngle * axis.coord.z * axis.coord.y;
00509     mOut.onebased._33 = 1.0f + oneMinusCosAngle * (axis.coord.z * axis.coord.z - 1.0f);
00510     mOut.onebased._34 = 0.0f;
00511
00512     mOut.onebased._41 = 0.0f;
00513     mOut.onebased._42 = 0.0f;
00514     mOut.onebased._43 = 0.0f;
00515     mOut.onebased._44 = 1.0f;
00516
00517     return mOut;
00518 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/BasicHologramMain.h Source File

  • BasicHologram
  • cpp

BasicHologramMain.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 //
00004 // Comment out this preprocessor definition to disable all of the
00005 // sample content.
00006 //
00007 // To remove the content after disabling it:
00008 //     * Remove the unused code from your app's Main class.
00009 //     * Delete the Content folder provided with this template.
00010 //
00011 #define DRAW_SAMPLE_CONTENT
00012
00013 #include "Common\DeviceResources.h"
00014 #include "Common\StepTimer.h"
00015
00016 #ifdef DRAW_SAMPLE_CONTENT
00017 #include "Content\SpinningCubeRenderer.h"
00018 #include "Content\SpatialInputHandler.h"
00019 #endif
00020
00021 // Updates, renders, and presents holographic content using Direct3D.
00022 namespace BasicHologram
00023 {
00024     class BasicHologramMain : public DX::IDeviceNotify
00025     {
00026     public:
00027         BasicHologramMain(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00028         ~BasicHologramMain();
00029
00030         // Sets the holographic space. This is our closest analogue to setting a new window
00031         // for the app.
00032         void SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^ holographicSpace);
00033
00034         // Starts the holographic frame and updates the content.
00035         Windows::Graphics::Holographic::HolographicFrame^ Update();
00036
00037         // Renders holograms, including world-locked content.
00038         bool Render(Windows::Graphics::Holographic::HolographicFrame^ holographicFrame);
00039
00040         // Handle saving and loading of app state owned by AppMain.
00041         void SaveAppState();
00042         void LoadAppState();
00043
00044         // Handle mouse input.
00045         void OnPointerPressed();
00046
00047         // IDeviceNotify
00048         virtual void OnDeviceLost();
00049         virtual void OnDeviceRestored();
00050
00051     private:
00052         // Asynchronously creates resources for new holographic cameras.
00053         void OnCameraAdded(
00054             Windows::Graphics::Holographic::HolographicSpace^ sender,
00055             Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs^ args);
00056
00057         // Synchronously releases resources for holographic cameras that are no longer
00058         // attached to the system.
00059         void OnCameraRemoved(
00060             Windows::Graphics::Holographic::HolographicSpace^ sender,
00061             Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs^ args);
00062
00063         // Used to notify the app when the positional tracking state changes.
00064         void OnLocatabilityChanged(
00065             Windows::Perception::Spatial::SpatialLocator^ sender,
00066             Platform::Object^ args);
00067
00068         // Used to be aware of gamepads that are plugged in after the app starts.
00069         void OnGamepadAdded(Platform::Object^, Windows::Gaming::Input::Gamepad^ args);
00070
00071         // Used to stop updating gamepads that are removed while the app is running.
00072         void OnGamepadRemoved(Platform::Object^, Windows::Gaming::Input::Gamepad^ args);
00073
00074         // Used to respond to changes to the default spatial locator.
00075         void OnHolographicDisplayIsAvailableChanged(Platform::Object^, Platform::Object^);
00076
00077         // Clears event registration state. Used when changing to a new HolographicSpace
00078         // and when tearing down AppMain.
00079         void UnregisterHolographicEventHandlers();
00080
00081 #ifdef DRAW_SAMPLE_CONTENT
00082         // Renders a colorful holographic cube that's 20 centimeters wide. This sample content
00083         // is used to demonstrate world-locked rendering.
00084         std::unique_ptr<SpinningCubeRenderer>                           m_spinningCubeRenderer;
00085
00086         // Listens for the Pressed spatial input event.
00087         std::shared_ptr<SpatialInputHandler>                            m_spatialInputHandler;
00088 #endif
00089
00090         // Cached pointer to device resources.
00091         std::shared_ptr<DX::DeviceResources>                            m_deviceResources;
00092
00093         // Render loop timer.
00094         DX::StepTimer                                                   m_timer;
00095
00096         // Represents the holographic space around the user.
00097         Windows::Graphics::Holographic::HolographicSpace^               m_holographicSpace;
00098
00099         // SpatialLocator that is attached to the default HolographicDisplay.
00100         Windows::Perception::Spatial::SpatialLocator^                   m_spatialLocator;
00101
00102         // A stationary reference frame based on m_spatialLocator.
00103         Windows::Perception::Spatial::SpatialStationaryFrameOfReference^ m_stationaryReferenceFrame;
00104
00105         // Event registration tokens.
00106         Windows::Foundation::EventRegistrationToken                     m_cameraAddedToken;
00107         Windows::Foundation::EventRegistrationToken                     m_cameraRemovedToken;
00108         Windows::Foundation::EventRegistrationToken                     m_locatabilityChangedToken;
00109         Windows::Foundation::EventRegistrationToken                     m_gamepadAddedEventToken;
00110         Windows::Foundation::EventRegistrationToken                     m_gamepadRemovedEventToken;
00111         Windows::Foundation::EventRegistrationToken                     m_holographicDisplayIsAvailableChangedEventToken;
00112
00113         // Keep track of gamepads.
00114         struct GamepadWithButtonState
00115         {
00116             GamepadWithButtonState(
00117                 Windows::Gaming::Input::Gamepad^ gamepad,
00118                 bool buttonAWasPressedLastFrame)
00119             {
00120                 this->gamepad = gamepad;
00121                 this->buttonAWasPressedLastFrame = buttonAWasPressedLastFrame;
00122             }
00123             Windows::Gaming::Input::Gamepad^ gamepad;
00124             bool buttonAWasPressedLastFrame = false;
00125         };
00126         std::vector<GamepadWithButtonState>                             m_gamepads;
00127
00128         // Keep track of mouse input.
00129         bool                                                            m_pointerPressed = false;
00130
00131         // Cache whether or not the HolographicCamera.Display property can be accessed.
00132         bool                                                            m_canGetHolographicDisplayForCamera = false;
00133
00134         // Cache whether or not the HolographicDisplay.GetDefault() method can be called.
00135         bool                                                            m_canGetDefaultHolographicDisplay = false;
00136
00137         // Cache whether or not the HolographicCameraRenderingParameters.CommitDirect3D11DepthBuffer() method can be called.
00138         bool                                                            m_canCommitDirect3D11DepthBuffer = false;
00139     };
00140 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cs/Scenario1.xaml.cs Source File

  • MapControl
  • cs

Scenario1.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using Windows.Devices.Geolocation;
00015 using Windows.Foundation;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Controls.Maps;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario1 : Page
00024     {
00025         private MainPage rootPage;
00026
00027         public Scenario1()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         private void MyMap_Loaded(object sender, RoutedEventArgs e)
00033         {
00034             myMap.Center = MainPage.SeattleGeopoint;
00035             myMap.ZoomLevel = 12;
00036             SetMapStyle();
00037             SetMapProjection();
00038         }
00039
00040         private void MyMap_MapTapped(Windows.UI.Xaml.Controls.Maps.MapControl sender, Windows.UI.Xaml.Controls.Maps.MapInputEventArgs args)
00041         {
00042             var tappedGeoPosition = args.Location.Position;
00043             string status = "MapTapped at \nLatitude:" + tappedGeoPosition.Latitude + "\nLongitude: " + tappedGeoPosition.Longitude;
00044             rootPage.NotifyUser( status, NotifyType.StatusMessage);
00045         }
00046
00047         protected override void OnNavigatedTo(NavigationEventArgs e)
00048         {
00049             rootPage = MainPage.Current;
00050         }
00051
00052         private void TrafficFlowVisible_Checked(object sender, RoutedEventArgs e)
00053         {
00054             myMap.TrafficFlowVisible = true;
00055         }
00056
00057         private void trafficFlowVisibleCheckBox_Unchecked(object sender, RoutedEventArgs e)
00058         {
00059             myMap.TrafficFlowVisible = false;
00060         }
00061
00062         private void styleCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
00063         {
00064             // Protect against events that are raised before we are fully initialized.
00065             if (myMap != null)
00066             {
00067                 SetMapStyle();
00068             }
00069         }
00070
00071         private void SetMapStyle()
00072         {
00073             switch(styleCombobox.SelectedIndex)
00074             {
00075                 case 0:
00076                     myMap.Style = MapStyle.None;
00077                     break;
00078                 case 1:
00079                     myMap.Style = MapStyle.Road;
00080                     break;
00081                 case 2:
00082                     myMap.Style = MapStyle.Aerial;
00083                     break;
00084                 case 3:
00085                     myMap.Style = MapStyle.AerialWithRoads;
00086                     break;
00087                 case 4:
00088                     myMap.Style = MapStyle.Terrain;
00089                     break;
00090             }
00091         }
00092
00093         private void projectionCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
00094         {
00095             // Protect against events that are raised before we are fully initialized.
00096             if (myMap != null)
00097             {
00098                 SetMapProjection();
00099             }
00100         }
00101
00102         private void SetMapProjection()
00103         {
00104             switch (projectionCombobox.SelectedIndex)
00105             {
00106                 case 0:
00107                     myMap.MapProjection = MapProjection.WebMercator;
00108                     break;
00109                 case 1:
00110                     myMap.MapProjection = MapProjection.Globe;
00111                     break;
00112             }
00113         }
00114     }
00115 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/DPadHelper.h Source File

  • SpatialInteractionSource
  • cpp

DPadHelper.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 namespace HolographicPaint
00004 {
00005
00006     enum class DPadAction { None, Left, Right, Top, Bottom };
00007
00008     // This class and the class derived from it allows the application to receive the same commands
00009     // for controllers with a Touchpad or a Thumbstick.
00010     class IDPadHelper
00011     {
00012     public:
00013
00014         virtual DPadAction Update(Windows::UI::Input::Spatial::SpatialInteractionControllerProperties^ controllerState)
00015         {
00016             return DPadAction::None;
00017         }
00018
00019         virtual DPadAction SourcePressed(Windows::UI::Input::Spatial::SpatialInteractionPressKind pressKind, Windows::UI::Input::Spatial::SpatialInteractionControllerProperties^ controllerState)
00020         {
00021             return DPadAction::None;
00022         }
00023     };
00024
00025     class ThumbstickDPadHelper : public IDPadHelper
00026     {
00027     public:
00028
00029         ThumbstickDPadHelper(double threshold = .5);
00030
00031         virtual DPadAction Update(Windows::UI::Input::Spatial::SpatialInteractionControllerProperties^ controllerState) override;
00032
00033     private:
00034         bool m_waitForCenter;
00035         double m_threshold;
00036     };
00037
00038     class TouchpadDPadHelper : public IDPadHelper
00039     {
00040     public:
00041
00042         TouchpadDPadHelper(double threshold = .3);
00043
00044         virtual DPadAction SourcePressed(
00045             Windows::UI::Input::Spatial::SpatialInteractionPressKind pressKind,
00046             Windows::UI::Input::Spatial::SpatialInteractionControllerProperties^ controllerState) override;
00047
00048     private:
00049         double m_threshold;
00050     };
00051 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/DeviceResources.h Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

DeviceResources.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace DX
00015 {
00016     // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created.
00017     interface IDeviceNotify
00018     {
00019         virtual void OnDeviceLost() = 0;
00020         virtual void OnDeviceRestored() = 0;
00021     };
00022
00023     // Controls all the DirectX device resources.
00024     class DeviceResources
00025     {
00026     public:
00027         DeviceResources();
00028         void SetWindow(Windows::UI::Core::CoreWindow^ window);
00029         void SetLogicalSize(Windows::Foundation::Size logicalSize);
00030         void SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation);
00031         void SetDpi(float dpi);
00032         void ValidateDevice();
00033         void HandleDeviceLost();
00034         void RegisterDeviceNotify(IDeviceNotify* deviceNotify);
00035         void Trim();
00036         void Present();
00037
00038         // Device Accessors.
00039         Windows::Foundation::Size GetOutputSize() const                 { return m_outputSize; }
00040         Windows::Foundation::Size GetLogicalSize() const                { return m_logicalSize; }
00041
00042         // D3D Accessors.
00043         ID3D11Device2*          GetD3DDevice() const                    { return m_d3dDevice.Get(); }
00044         ID3D11DeviceContext3*   GetD3DDeviceContext() const             { return m_d3dContext.Get(); }
00045         IDXGISwapChain1*        GetSwapChain() const                    { return m_swapChain.Get(); }
00046         D3D_FEATURE_LEVEL       GetDeviceFeatureLevel() const           { return m_d3dFeatureLevel; }
00047         ID3D11RenderTargetView* GetBackBufferRenderTargetView() const   { return m_d3dRenderTargetView.Get(); }
00048         ID3D11DepthStencilView* GetDepthStencilView() const             { return m_d3dDepthStencilView.Get(); }
00049         D3D11_VIEWPORT          GetScreenViewport() const               { return m_screenViewport; }
00050         DirectX::XMFLOAT4X4     GetOrientationTransform3D() const       { return m_orientationTransform3D; }
00051
00052         // D2D Accessors.
00053         ID2D1Factory3*          GetD2DFactory() const                   { return m_d2dFactory.Get(); }
00054         ID2D1Device2*           GetD2DDevice() const                    { return m_d2dDevice.Get(); }
00055         ID2D1DeviceContext2*    GetD2DDeviceContext() const             { return m_d2dContext.Get(); }
00056         ID2D1Bitmap1*           GetD2DTargetBitmap() const              { return m_d2dTargetBitmap.Get(); }
00057         IDWriteFactory2*        GetDWriteFactory() const                { return m_dwriteFactory.Get();  }
00058         IWICImagingFactory2*    GetWicImagingFactory() const            { return m_wicFactory.Get(); }
00059         D2D1::Matrix3x2F        GetOrientationTransform2D() const       { return m_orientationTransform2D; }
00060
00061     private:
00062         void CreateDeviceIndependentResources();
00063         void CreateDeviceResources();
00064         void CreateWindowSizeDependentResources();
00065         DXGI_MODE_ROTATION ComputeDisplayRotation();
00066
00067         // Direct3D objects.
00068         Microsoft::WRL::ComPtr<ID3D11Device2>           m_d3dDevice;
00069         Microsoft::WRL::ComPtr<ID3D11DeviceContext3>    m_d3dContext;
00070         Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00071
00072         // Direct3D rendering objects. Required for 3D.
00073         Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00074         Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00075         D3D11_VIEWPORT                                  m_screenViewport;
00076
00077         // Direct2D drawing components.
00078         Microsoft::WRL::ComPtr<ID2D1Factory3>       m_d2dFactory;
00079         Microsoft::WRL::ComPtr<ID2D1Device2>        m_d2dDevice;
00080         Microsoft::WRL::ComPtr<ID2D1DeviceContext2> m_d2dContext;
00081         Microsoft::WRL::ComPtr<ID2D1Bitmap1>        m_d2dTargetBitmap;
00082
00083         // DirectWrite drawing components.
00084         Microsoft::WRL::ComPtr<IDWriteFactory2>     m_dwriteFactory;
00085         Microsoft::WRL::ComPtr<IWICImagingFactory2> m_wicFactory;
00086
00087         // Cached reference to the Window.
00088         Platform::Agile<Windows::UI::Core::CoreWindow> m_window;
00089
00090         // Cached device properties.
00091         D3D_FEATURE_LEVEL                               m_d3dFeatureLevel;
00092         Windows::Foundation::Size                       m_d3dRenderTargetSize;
00093         Windows::Foundation::Size                       m_outputSize;
00094         Windows::Foundation::Size                       m_logicalSize;
00095         Windows::Graphics::Display::DisplayOrientations m_nativeOrientation;
00096         Windows::Graphics::Display::DisplayOrientations m_currentOrientation;
00097         float                                           m_dpi;
00098
00099         // Transforms used for display orientation.
00100         D2D1::Matrix3x2F    m_orientationTransform2D;
00101         DirectX::XMFLOAT4X4 m_orientationTransform3D;
00102
00103         // The IDeviceNotify can be held directly as it owns the DeviceResources.
00104         IDeviceNotify* m_deviceNotify;
00105     };
00106 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cs/SampleConfiguration.cs Source File

  • Geolocation
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.ApplicationModel.Background;
00015 using Windows.Data.Json;
00016 using Windows.Devices.Geolocation;
00017 using Windows.UI.Xaml.Controls;
00018
00019 namespace SDKTemplate
00020 {
00021     public partial class MainPage : Page
00022     {
00023         public const string FEATURE_NAME = "Geolocation";
00024
00025         List<Scenario> scenarios = new List<Scenario>
00026         {
00027             new Scenario() { Title = "Track position", ClassType = typeof(Scenario1_TrackPosition) },
00028             new Scenario() { Title = "Get position", ClassType = typeof(Scenario2_GetPosition) },
00029             new Scenario() { Title = "Background position", ClassType = typeof(Scenario3_BackgroundTask) },
00030             new Scenario() { Title = "Foreground geofencing", ClassType = typeof(Scenario4_ForegroundGeofence) },
00031             new Scenario() { Title = "Background geofencing", ClassType = typeof(Scenario5_GeofenceBackgroundTask) },
00032             new Scenario() { Title = "Get last visit", ClassType= typeof(Scenario6_GetLastVisit)},
00033             new Scenario() { Title = "Foreground visit monitoring", ClassType= typeof(Scenario7_ForegroundVisits)},
00034             new Scenario() { Title = "Background visit monitoring", ClassType=typeof(Scenario8_VisitsBackgroundTask)},
00035         };
00036
00037         /// <summary>
00038         /// Look up a background task by name.
00039         /// If found, then also report whether the user has granted background execution access.
00040         /// </summary>
00041         public static IBackgroundTaskRegistration LookupBackgroundTask(string name)
00042         {
00043             IBackgroundTaskRegistration found = null;
00044
00045             // Loop through all background tasks to find one with the matching name
00046             foreach (var entry in BackgroundTaskRegistration.AllTasks)
00047             {
00048                 var task = entry.Value;
00049                 if (task.Name == name)
00050                 {
00051                     found = task;
00052                     break;
00053                 }
00054             }
00055
00056             if (found != null)
00057             {
00058                 // Check whether the user has already granted background execution access.
00059                 BackgroundAccessStatus backgroundAccessStatus = BackgroundExecutionManager.GetAccessStatus();
00060
00061                 MainPage rootPage = MainPage.Current;
00062                 switch (backgroundAccessStatus)
00063                 {
00064                     case BackgroundAccessStatus.AlwaysAllowed:
00065                     case BackgroundAccessStatus.AllowedSubjectToSystemPolicy:
00066                         rootPage.NotifyUser("Background task is already registered. Waiting for next update...", NotifyType.StatusMessage);
00067                         break;
00068
00069                     default:
00070                         rootPage.NotifyUser("Background tasks may be disabled for this app", NotifyType.ErrorMessage);
00071                         break;
00072                 }
00073             }
00074
00075             return found;
00076
00077         }
00078
00079         /// <summary>
00080         /// Check and report whether the user has granted background execution access.
00081         /// If so, then also request location access so that the background task can do its work.
00082         /// </summary>
00083         public static async void CheckBackgroundAndRequestLocationAccess()
00084         {
00085             // Get permission for a background task from the user. If the user has already answered once,
00086             // this does nothing and the user must manually update their preference via Settings.
00087             BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
00088
00089             MainPage rootPage = MainPage.Current;
00090
00091             switch (backgroundAccessStatus)
00092             {
00093                 case BackgroundAccessStatus.AlwaysAllowed:
00094                 case BackgroundAccessStatus.AllowedSubjectToSystemPolicy:
00095                     // BackgroundTask is allowed
00096                     rootPage.NotifyUser("Background task registered.", NotifyType.StatusMessage);
00097
00098                     // Need to request access to location.
00099                     // This must be done when we create the background task registration
00100                     // because the background task cannot display UI.
00101                     // If the user has already answered once,
00102                     // this does nothing and the user must manually update their preference via Settings.
00103                     switch (await Geolocator.RequestAccessAsync())
00104                     {
00105                         case GeolocationAccessStatus.Allowed:
00106                             break;
00107
00108                         case GeolocationAccessStatus.Denied:
00109                             rootPage.NotifyUser("Access to location is denied.", NotifyType.ErrorMessage);
00110                             break;
00111
00112                         case GeolocationAccessStatus.Unspecified:
00113                             rootPage.NotifyUser("Unspecified error!", NotifyType.ErrorMessage);
00114                             break;
00115                     }
00116                     break;
00117
00118                 default:
00119                     rootPage.NotifyUser("Background tasks may be disabled for this app", NotifyType.ErrorMessage);
00120                     break;
00121             }
00122         }
00123
00124         /// <summary>
00125         /// Look up a string in the saved LocalSettings, or a default value if no string is found.
00126         /// </summary>
00127         /// <param name="key">The key to look up</param>
00128         /// <param name="defaultValue">The fallback value to use if the key is not found or the value is not a string</param>
00129         /// <returns></returns>
00130         public static string LookupSavedString(string key, string defaultValue = "")
00131         {
00132             var values = Windows.Storage.ApplicationData.Current.LocalSettings.Values;
00133             object o;
00134             values.TryGetValue(key, out o);
00135             string s = o as string;
00136             return (s == null) ? defaultValue : s;
00137         }
00138
00139         /// <summary>
00140         /// Look up a JSON string in the saved LocalSettings and fill the ItemsControl with the strings in it.
00141         /// </summary>
00142         /// <param name="control"></param>
00143         /// <param name="key"></param>
00144         public static void FillItemsFromSavedJson(ItemsControl control, string key)
00145         {
00146             string json = LookupSavedString(key);
00147             if (!string.IsNullOrEmpty(json))
00148             {
00149                 // remove all entries and repopulate
00150                 var items = control.Items;
00151                 items.Clear();
00152
00153                 foreach (IJsonValue element in JsonValue.Parse(json).GetArray())
00154                 {
00155                     items.Add(element.GetString());
00156                 }
00157             }
00158         }
00159
00160         /// <summary>
00161         /// Look up the "Status" in the saved LocalSettings and display it if present.
00162         /// </summary>
00163         public static void ReportSavedStatus()
00164         {
00165             string status = LookupSavedString("Status");
00166             if (!string.IsNullOrEmpty(status))
00167             {
00168                 MainPage.Current.NotifyUser(status, NotifyType.StatusMessage);
00169             }
00170         }
00171     }
00172
00173     public class Scenario
00174     {
00175         public string Title { get; set; }
00176         public Type ClassType { get; set; }
00177     }
00178 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cs/Scenario2.xaml.cs Source File

  • Logging
  • cs

Scenario2.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// UI for the LoggingSession sample.
00022     /// </summary>
00023     public sealed partial class Scenario2
00024     {
00025         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00026         // as NotifyUser()
00027         MainPage rootPage = MainPage.Current;
00028
00029         internal LoggingSessionScenario LoggingSessionScenario { get { return LoggingSessionScenario.Instance; } }
00030
00031         public Scenario2()
00032         {
00033             // This sample UI is interested in events from
00034             // the LoggingSessionScenario class so the UI can be updated.
00035             LoggingSessionScenario.StatusChanged += LoggingSessionScenario_StatusChanged;
00036             this.InitializeComponent();
00037         }
00038
00039         async void LoggingSessionScenario_StatusChanged(object sender, LoggingScenarioEventArgs e)
00040         {
00041             if (e.Type == LoggingScenarioEventType.BusyStatusChanged)
00042             {
00043                 UpdateControls();
00044             }
00045             else if (e.Type == LoggingScenarioEventType.LogFileGenerated)
00046             {
00047                 await AddLogFileMessageDispatch("LogFileGenerated", e.LogFilePath);
00048             }
00049             else if (e.Type == LoggingScenarioEventType.LoggingEnabledDisabled)
00050             {
00051                 await AddMessageDispatch(string.Format("Logging has been {0}.", e.Enabled ? "enabled" : "disabled"));
00052             }
00053         }
00054
00055         ScrollViewer FindScrollViewer(DependencyObject depObject)
00056         {
00057             if (depObject == null)
00058             {
00059                 return null;
00060             }
00061
00062             int countThisLevel = Windows.UI.Xaml.Media.VisualTreeHelper.GetChildrenCount(depObject);
00063             if (countThisLevel <= 0)
00064             {
00065                 return null;
00066             }
00067
00068             for (int childIndex = 0; childIndex < countThisLevel; childIndex++)
00069             {
00070                 DependencyObject childDepObject = Windows.UI.Xaml.Media.VisualTreeHelper.GetChild(depObject, childIndex);
00071                 if (childDepObject is ScrollViewer)
00072                 {
00073                     return (ScrollViewer)childDepObject;
00074                 }
00075
00076                 ScrollViewer svFromChild = FindScrollViewer(childDepObject);
00077                 if (svFromChild != null)
00078                 {
00079                     return svFromChild;
00080                 }
00081             }
00082
00083             return null;
00084         }
00085
00086         /// <summary>
00087         /// Add a message to the UI control which displays status while the sample is running.
00088         /// </summary>
00089         /// <param name="message">The message to append to the UI log.</param>
00090         public void AddMessage(string message)
00091         {
00092             StatusMessageList.Text += message + "\r\n";
00093             StatusMessageList.Select(StatusMessageList.Text.Length, 0);
00094
00095             ScrollViewer svFind = FindScrollViewer(StatusMessageList);
00096             if (svFind != null)
00097             {
00098                 svFind.ChangeView(null, StatusMessageList.ActualHeight, null);
00099             }
00100         }
00101
00102         /// <summary>
00103         /// Dispatch to the UI thread and add a message to the UI control which displays status while the sample is running.
00104         /// </summary>
00105         /// <param name="message">The message to append to the UI log.</param>
00106         public async Task AddLogFileMessageDispatch(string message, string path)
00107         {
00108             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
00109             {
00110                 string finalMessage;
00111                 if (path != null && path.Length > 0)
00112                 {
00113                     var fileName = System.IO.Path.GetFileName(path);
00114                     var directoryName = System.IO.Path.GetDirectoryName(path);
00115                     finalMessage = message + ": " + fileName;
00116                     ViewLogInfo.Text =
00117                         $"Log folder: \"{directoryName}\"\r\n" +
00118                         $"- To view with tracerpt: tracerpt.exe \"{path}\" -of XML -o LogFile.xml\r\n" +
00119                         $"- To view with Windows Performance Toolkit (WPT):\r\n" +
00120                         $"   xperf -merge \"{path}\" merged.etl\r\n" +
00121                         $"   wpa.exe merged.etl";
00122                 }
00123                 else
00124                 {
00125                     finalMessage = string.Format("{0}: none, nothing logged since saving the last file.", message);
00126                 }
00127                 AddMessage(finalMessage);
00128             }).AsTask();
00129         }
00130
00131         /// <summary>
00132         /// Dispatch to the UI thread and add a message to the UI log.
00133         /// </summary>
00134         /// <param name="message">The message to appened to the UI log.</param>
00135         /// <returns>The task.</returns>
00136         public async Task AddMessageDispatch(string message)
00137         {
00138             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
00139             {
00140                 AddMessage(message);
00141             }).AsTask();
00142         }
00143
00144         /// <summary>
00145         /// Adjust UI controls based on what the sample is doing.
00146         /// </summary>
00147         private void UpdateControls()
00148         {
00149             if (LoggingSessionScenario.Instance.IsLoggingEnabled)
00150             {
00151                 InputTextBlock1.Text = "Logging is enabled. Click 'Disable Logging' to disable logging. With logging enabled, you can click 'Log Messages' to use the logging API to generate log files.";
00152                 EnableDisableLoggingButton.Content = "Disable Logging";
00153
00154                 if (LoggingSessionScenario.Instance.IsBusy)
00155                 {
00156                     DoScenarioButton.IsEnabled = false;
00157                     EnableDisableLoggingButton.IsEnabled = false;
00158                 }
00159                 else
00160                 {
00161                     DoScenarioButton.IsEnabled = true;
00162                     EnableDisableLoggingButton.IsEnabled = true;
00163                 }
00164             }
00165             else
00166             {
00167                 InputTextBlock1.Text = "Logging is disabled. Click 'Enable Logging' to enable logging. After you enable logging you can click 'Log Messages' to use the logging API to generate log files.";
00168                 EnableDisableLoggingButton.Content = "Enable Logging";
00169                 DoScenarioButton.IsEnabled = false;
00170                 if (LoggingSessionScenario.Instance.IsBusy)
00171                 {
00172                     EnableDisableLoggingButton.IsEnabled = false;
00173                 }
00174                 else
00175                 {
00176                     EnableDisableLoggingButton.IsEnabled = true;
00177                 }
00178             }
00179         }
00180
00181         /// <summary>
00182         /// Invoked when this page is about to be displayed in a Frame.
00183         /// </summary>
00184         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00185         /// property is typically used to configure the page.</param>
00186         protected override void OnNavigatedTo(NavigationEventArgs e)
00187         {
00188             UpdateControls();
00189         }
00190
00191         /// <summary>
00192         /// Enabled/disabled logging.
00193         /// </summary>
00194         /// <param name="sender">The sender.</param>
00195         /// <param name="e">The event arguments.</param>
00196         private void EnableDisableLogging(object sender, RoutedEventArgs e)
00197         {
00198             LoggingSessionScenario loggingSessionScenario = LoggingSessionScenario.Instance;
00199
00200             if (loggingSessionScenario.IsLoggingEnabled)
00201             {
00202                 rootPage.NotifyUser("Disabling logging...", NotifyType.StatusMessage);
00203             }
00204             else
00205             {
00206                 rootPage.NotifyUser("Enabling logging...", NotifyType.StatusMessage);
00207             }
00208
00209             LoggingSessionScenario.Instance.ToggleLoggingEnabledDisabled();
00210
00211             if (loggingSessionScenario.IsLoggingEnabled)
00212             {
00213                 rootPage.NotifyUser("Logging enabled.", NotifyType.StatusMessage);
00214             }
00215             else
00216             {
00217                 rootPage.NotifyUser("Logging disabled.", NotifyType.StatusMessage);
00218             }
00219
00220             UpdateControls();
00221         }
00222
00223         /// <summary>
00224         /// Run a sample scenario which logs lots of messages to produce several log files.
00225         /// </summary>
00226         /// <param name="sender">The sender.</param>
00227         /// <param name="e">The event args.</param>
00228         private async void DoScenario(object sender, RoutedEventArgs e)
00229         {
00230             DoScenarioButton.IsEnabled = false;
00231             rootPage.NotifyUser("Scenario running...", NotifyType.StatusMessage);
00232             await LoggingSessionScenario.DoScenarioAsync();
00233             rootPage.NotifyUser("Scenario finished.", NotifyType.StatusMessage);
00234             DoScenarioButton.IsEnabled = true;
00235         }
00236     }
00237 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TitleBar/cppwinrt/Scenario2_Extend.cpp Source File

  • TitleBar
  • cppwinrt

Scenario2_Extend.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Extend.h"
00014 #include "Scenario2_Extend.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::ApplicationModel::Core;
00020 using namespace Windows::UI::ViewManagement;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario2_Extend::Scenario2_Extend()
00028     {
00029         InitializeComponent();
00030
00031         bool isExtendedIntoTitleBar = CoreApplication::GetCurrentView().TitleBar().ExtendViewIntoTitleBar();
00032         ExtendView().IsChecked(isExtendedIntoTitleBar);
00033         EnableControls().Visibility(isExtendedIntoTitleBar ? Visibility::Visible : Visibility::Collapsed);
00034         EnableControls().IsChecked(SampleState::AreControlsInTitleBar());
00035     }
00036
00037     void Scenario2_Extend::OnNavigatedTo(NavigationEventArgs const&)
00038     {
00039         windowSizeChangedToken = Window::Current().SizeChanged([this](auto&&, auto&&)
00040         {
00041             UpdateFullScreenModeStatus();
00042         });
00043         UpdateFullScreenModeStatus();
00044     }
00045
00046     void Scenario2_Extend::OnNavigatedFrom(NavigationEventArgs const&)
00047     {
00048         Window::Current().SizeChanged(windowSizeChangedToken);
00049     }
00050
00051     void Scenario2_Extend::ExtendView_Click(IInspectable const&, RoutedEventArgs const&)
00052     {
00053         bool extend = ExtendView().IsChecked().Value();
00054         CoreApplication::GetCurrentView().TitleBar().ExtendViewIntoTitleBar(extend);
00055         EnableControls().Visibility(extend ? Visibility::Visible : Visibility::Collapsed);
00056         if (extend)
00057         {
00058             SampleState::AddCustomTitleBar();
00059         }
00060         else
00061         {
00062             SampleState::RemoveCustomTitleBar();
00063         }
00064     }
00065
00066     void Scenario2_Extend::ToggleFullScreenModeButton_Click(IInspectable const&, RoutedEventArgs const&)
00067     {
00068         ApplicationView view = ApplicationView::GetForCurrentView();
00069         if (view.IsFullScreenMode())
00070         {
00071             view.ExitFullScreenMode();
00072             rootPage.NotifyUser(L"Exited full screen mode", NotifyType::StatusMessage);
00073         }
00074         else
00075         {
00076             if (view.TryEnterFullScreenMode())
00077             {
00078                 rootPage.NotifyUser(L"Entered full screen mode", NotifyType::StatusMessage);
00079             }
00080             else
00081             {
00082                 rootPage.NotifyUser(L"Failed to enter full screen mode", NotifyType::ErrorMessage);
00083             }
00084         }
00085     }
00086
00087     void Scenario2_Extend::EnableControls_Click(IInspectable const&, RoutedEventArgs const&)
00088     {
00089         SampleState::AreControlsInTitleBar(EnableControls().IsChecked().Value());
00090     }
00091
00092     void Scenario2_Extend::UpdateFullScreenModeStatus()
00093     {
00094         bool isFullScreenMode = ApplicationView::GetForCurrentView().IsFullScreenMode();
00095         ToggleFullScreenModeSymbol().Symbol(isFullScreenMode ? Symbol::BackToWindow : Symbol::FullScreen);
00096         ReportFullScreenMode().Text(isFullScreenMode ? L"is in" : L"is not in");
00097     }
00098 }
Generated on Fri Nov 15 2024 22:21:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PlaylistView Member List

This is the complete list of members for PlaylistView, including all inherited members.
ItemClick | PlaylistView |
MediaList | PlaylistView |
mediaList | PlaylistView | [private]
PlaylistView() | PlaylistView | [inline]
PropertyChanged | PlaylistView |
RaisePropertyChanged(string propertyName) | PlaylistView | [inline, private]
SelectionChanged | PlaylistView |
Generated on Fri Nov 15 2024 22:23:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteColorGlyph/cpp/DirectXHelper.h Source File

  • DWriteColorGlyph
  • cpp

DirectXHelper.h

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include <ppltasks.h>
00011
00012 namespace DX
00013 {
00014     inline void ThrowIfFailed(HRESULT hr)
00015     {
00016         if (FAILED(hr))
00017         {
00018             // Set a breakpoint on this line to catch Win32 API errors.
00019             throw Platform::Exception::CreateException(hr);
00020         }
00021     }
00022
00023     // Function that reads from a binary file asynchronously.
00024     inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename)
00025     {
00026         using namespace Windows::Storage;
00027         using namespace Concurrency;
00028
00029         auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
00030
00031         return create_task(folder->GetFileAsync(Platform::StringReference(filename.c_str()))).then([] (StorageFile^ file)
00032         {
00033             return FileIO::ReadBufferAsync(file);
00034         }).then([] (Streams::IBuffer^ fileBuffer) -> std::vector<byte>
00035         {
00036             std::vector<byte> returnBuffer;
00037             returnBuffer.resize(fileBuffer->Length);
00038             Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), fileBuffer->Length));
00039             return returnBuffer;
00040         });
00041     }
00042
00043     // Converts a length in device-independent pixels (DIPs) to a length in physical pixels.
00044     inline float ConvertDipsToPixels(float dips, float dpi)
00045     {
00046         static const float dipsPerInch = 96.0f;
00047         return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00048     }
00049
00050     // Converts a length in physical pixels to a length in device-independent pixels (DIPs).
00051     inline float ConvertPixelsToDips(float pixels)
00052     {
00053         static const float dipsPerInch = 96.0f;
00054         return pixels * dipsPerInch / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->LogicalDpi; // Do not round.
00055     }
00056
00057     // Converts a length in physical pixels to a length in device-independent pixels (DIPs) using the provided DPI. This removes the need
00058     // to call this function from a thread associated with a CoreWindow, which is required by DisplayInformation::GetForCurrentView().
00059     inline float ConvertPixelsToDips(float pixels, float dpi)
00060     {
00061         static const float dipsPerInch = 96.0f;
00062         return pixels * dipsPerInch / dpi; // Do not round.
00063     }
00064
00065 #if defined(_DEBUG)
00066     // Check for SDK Layer support.
00067     inline bool SdkLayersAvailable()
00068     {
00069         HRESULT hr = D3D11CreateDevice(
00070             nullptr,
00071             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00072             0,
00073             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00074             nullptr,                    // Any feature level will do.
00075             0,
00076             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00077             nullptr,                    // No need to keep the D3D device reference.
00078             nullptr,                    // No need to know the feature level.
00079             nullptr                     // No need to keep the D3D device context reference.
00080             );
00081
00082         return SUCCEEDED(hr);
00083     }
00084 #endif
00085 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/Scenario_ListConstraint.xaml.cpp Source File

  • SpeechRecognitionAndSynthesis
  • cpp

Scenario_ListConstraint.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario_ListConstraint.xaml.h"
00014 #include "AudioCapturePermissions.h"
00015
00016 using namespace SDKTemplate;
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::ApplicationModel::Resources::Core;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Media::SpeechRecognition;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Controls::Primitives;
00028 using namespace Windows::UI::Xaml::Data;
00029 using namespace Windows::UI::Xaml::Input;
00030 using namespace Windows::UI::Xaml::Media;
00031 using namespace Windows::UI::Xaml::Navigation;
00032
00033 Scenario_ListConstraint::Scenario_ListConstraint() : rootPage(MainPage::Current)
00034 {
00035     InitializeComponent();
00036 }
00037
00038 /// <summary>
00039 /// When activating the scenario, ensure we have permission from the user to access their microphone, and
00040 /// provide an appropriate path for the user to enable access to the microphone if they haven't
00041 /// given explicit permission for it.
00042 /// </summary>
00043 /// <param name="e">The navigation event details</param>
00044 void Scenario_ListConstraint::OnNavigatedTo(NavigationEventArgs^ e)
00045 {
00046     Page::OnNavigatedTo(e);
00047
00048     // Save the UI thread dispatcher to allow speech status messages to be shown on the UI.
00049     dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
00050
00051     create_task(AudioCapturePermissions::RequestMicrophonePermissionAsync(), task_continuation_context::use_current())
00052         .then([this](bool permissionGained)
00053     {
00054         if (permissionGained)
00055         {
00056             // Enable the recognition buttons.
00057             this->btnRecognizeWithUI->IsEnabled = true;
00058             this->btnRecognizeWithoutUI->IsEnabled = true;
00059
00060       Windows::Globalization::Language^ speechLanguage = SpeechRecognizer::SystemSpeechLanguage;
00061       speechContext = ResourceContext::GetForCurrentView();
00062       speechContext->Languages = ref new VectorView<String^>(1, speechLanguage->LanguageTag);
00063
00064       speechResourceMap = ResourceManager::Current->MainResourceMap->GetSubtree(L"LocalizationSpeechResources");
00065
00066       PopulateLanguageDropdown();
00067       InitializeRecognizer(SpeechRecognizer::SystemSpeechLanguage);
00068         }
00069         else
00070         {
00071             this->resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00072             this->resultTextBlock->Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
00073       this->cbLanguageSelection->IsEnabled = false;
00074         }
00075   });
00076 }
00077
00078 /// <summary>
00079 /// Creates a SpeechRecognizer instance and initializes the grammar.
00080 /// </summary>
00081 void Scenario_ListConstraint::InitializeRecognizer(Windows::Globalization::Language^ recognizerLanguage)
00082 {
00083     // If reinitializing the recognizer (ie, changing the speech language), clean up the old recognizer first.
00084     // Avoid doing this while the recognizer is active by disabling the ability to change languages while listening.
00085     if (this->speechRecognizer != nullptr)
00086     {
00087         speechRecognizer->StateChanged -= stateChangedToken;
00088
00089         delete this->speechRecognizer;
00090         this->speechRecognizer = nullptr;
00091     }
00092
00093     try
00094     {
00095         // Create an instance of SpeechRecognizer.
00096         this->speechRecognizer = ref new SpeechRecognizer(recognizerLanguage);
00097
00098         // Provide feedback to the user about the state of the recognizer.
00099         stateChangedToken = speechRecognizer->StateChanged +=
00100             ref new Windows::Foundation::TypedEventHandler<
00101             SpeechRecognizer ^,
00102             SpeechRecognizerStateChangedEventArgs ^>(
00103                 this,
00104                 &Scenario_ListConstraint::SpeechRecognizer_StateChanged);
00105
00106         // Build a command-list grammar. Commands should ideally be drawn from a resource file for localization, and
00107         // be grouped into tags for alternate forms of the same command.
00108         speechRecognizer->Constraints->Append(
00109             ref new SpeechRecognitionListConstraint(
00110                 ref new Vector<String^>({
00111             speechResourceMap->GetValue(L"ListGrammarGoHome", speechContext)->ValueAsString
00112         }), "Home"));
00113         speechRecognizer->Constraints->Append(
00114             ref new SpeechRecognitionListConstraint(
00115                 ref new Vector<String^>({
00116             speechResourceMap->GetValue(L"ListGrammarGoToContosoStudio", speechContext)->ValueAsString
00117         }), "GoToContosoStudio"));
00118         speechRecognizer->Constraints->Append(
00119             ref new SpeechRecognitionListConstraint(
00120                 ref new Vector<String^>({
00121             speechResourceMap->GetValue(L"ListGrammarShowMessage", speechContext)->ValueAsString,
00122             speechResourceMap->GetValue(L"ListGrammarOpenMessage", speechContext)->ValueAsString
00123         }), "Message"));
00124         speechRecognizer->Constraints->Append(
00125             ref new SpeechRecognitionListConstraint(
00126                 ref new Vector<String^>({
00127             speechResourceMap->GetValue(L"ListGrammarSendEmail", speechContext)->ValueAsString,
00128             speechResourceMap->GetValue(L"ListGrammarCreateEmail", speechContext)->ValueAsString
00129         }), "Email"));
00130         speechRecognizer->Constraints->Append(
00131             ref new SpeechRecognitionListConstraint(
00132                 ref new Vector<String^>({
00133             speechResourceMap->GetValue(L"ListGrammarCallNitaFarley", speechContext)->ValueAsString,
00134             speechResourceMap->GetValue(L"ListGrammarCallNita", speechContext)->ValueAsString
00135         }), "CallNita"));
00136         speechRecognizer->Constraints->Append(
00137             ref new SpeechRecognitionListConstraint(
00138                 ref new Vector<String^>({
00139             speechResourceMap->GetValue(L"ListGrammarCallWayneSigmon", speechContext)->ValueAsString,
00140             speechResourceMap->GetValue(L"ListGrammarCallWayne", speechContext)->ValueAsString
00141         }), "CallWayne"));
00142
00143         // RecognizeWithUIAsync allows developers to customize the prompts.
00144         String^ uiOptionsText = ref new String(L"Try saying ") +
00145             speechResourceMap->GetValue("ListGrammarGoHome", speechContext)->ValueAsString + L"', '" +
00146             speechResourceMap->GetValue("ListGrammarGoToContosoStudio", speechContext)->ValueAsString + L"' or '" +
00147             speechResourceMap->GetValue("ListGrammarShowMessage", speechContext)->ValueAsString + L"'";
00148
00149         speechRecognizer->UIOptions->ExampleText = uiOptionsText;
00150         helpTextBlock->Text = speechResourceMap->GetValue("ListGrammarHelpText", speechContext)->ValueAsString + L"\n" +
00151             uiOptionsText;
00152
00153         // Compile the constraint.
00154         create_task(speechRecognizer->CompileConstraintsAsync(), task_continuation_context::use_current())
00155             .then([this](task<SpeechRecognitionCompilationResult^> previousTask)
00156         {
00157             SpeechRecognitionCompilationResult^ compilationResult = previousTask.get();
00158
00159             // Check to make sure that the constraints were in a proper format and the recognizer was able to compile it.
00160             if (compilationResult->Status != SpeechRecognitionResultStatus::Success)
00161             {
00162                 // Disable the recognition buttons.
00163                 btnRecognizeWithUI->IsEnabled = false;
00164                 btnRecognizeWithoutUI->IsEnabled = false;
00165
00166                 // Let the user know that the grammar didn't compile properly.
00167                 resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00168                 resultTextBlock->Text = "Unable to compile grammar.";
00169
00170             }
00171             else
00172             {
00173                 btnRecognizeWithUI->IsEnabled = true;
00174                 btnRecognizeWithoutUI->IsEnabled = true;
00175
00176                 resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00177             }
00178         }, task_continuation_context::use_current());
00179
00180 }
00181 catch (Platform::Exception^ ex)
00182 {
00183     if ((unsigned int)ex->HResult == HResultRecognizerNotFound)
00184     {
00185         btnRecognizeWithUI->IsEnabled = false;
00186         btnRecognizeWithoutUI->IsEnabled = false;
00187
00188         resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00189         resultTextBlock->Text = L"Speech Language pack for selected language not installed.";
00190     }
00191     else
00192     {
00193         auto messageDialog = ref new Windows::UI::Popups::MessageDialog(ex->Message, "Exception");
00194         create_task(messageDialog->ShowAsync());
00195     }
00196 }
00197
00198 }
00199
00200 /// <summary>
00201 /// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks,
00202 /// dipose the speech recognizer, and clean up to ensure the scenario is not still attempting to recognize
00203 /// speech while not in view.
00204 /// </summary>
00205 /// <param name="e">Details about the navigation event</param>
00206 void Scenario_ListConstraint::OnNavigatedFrom(NavigationEventArgs^ e)
00207 {
00208     Page::OnNavigatedFrom(e);
00209
00210     if (speechRecognizer != nullptr)
00211     {
00212         speechRecognizer->StateChanged -= stateChangedToken;
00213
00214         delete speechRecognizer;
00215         speechRecognizer = nullptr;
00216     }
00217 }
00218
00219 /// <summary>
00220 /// Uses the recognizer constructed earlier to listen for speech from the user before displaying
00221 /// it back on the screen. Uses the built-in speech recognition UI.
00222 /// </summary>
00223 /// <param name="sender">Button that triggered this event</param>
00224 /// <param name="e">State information about the routed event</param>
00225 void Scenario_ListConstraint::RecognizeWithUIListConstraint_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00226 {
00227     heardYouSayTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00228
00229     // Start recognition.
00230     create_task(speechRecognizer->RecognizeWithUIAsync(), task_continuation_context::use_current())
00231         .then([this](task<SpeechRecognitionResult^> recognitionTask)
00232     {
00233         try
00234         {
00235             SpeechRecognitionResult^ speechRecognitionResult = recognitionTask.get();
00236
00237             String^ tag = L"unknown";
00238             if (speechRecognitionResult->Constraint != nullptr)
00239             {
00240                 // Only attempt to retreive a constraint tag if the result has one. If
00241                 // the garbage rule is hit, this may be null.
00242                 tag = speechRecognitionResult->Constraint->Tag;
00243             }
00244
00245             // If successful, display the recognition result.
00246             if (speechRecognitionResult->Status == SpeechRecognitionResultStatus::Success)
00247             {
00248                 heardYouSayTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00249                 resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00250                 resultTextBlock->Text = L"Heard: '" + speechRecognitionResult->Text + L"', Tag( '" + tag + L"', Confidence: " + speechRecognitionResult->Confidence.ToString() + ")";
00251             }
00252             else
00253             {
00254                 heardYouSayTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00255                 resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00256                 resultTextBlock->Text = L"Speech Recognition Failure, Status: " + speechRecognitionResult->Status.ToString();
00257             }
00258         }
00259         catch (ObjectDisposedException^ exception)
00260         {
00261             // ObjectDisposedException will be thrown if you exit the scenario while the recogizer is actively
00262             // processing speech. Since this happens here when we navigate out of the scenario, don't try to
00263             // show a message dialog for this exception.
00264             OutputDebugString(L"ObjectDisposedException caught while recognition in progress (can be ignored):");
00265             OutputDebugString(exception->ToString()->Data());
00266         }
00267         catch (Exception^ exception)
00268         {
00269             // Handle the speech privacy policy error.
00270             if ((unsigned int)exception->HResult == Scenario_ListConstraint::HResultPrivacyStatementDeclined)
00271             {
00272                 resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00273                 resultTextBlock->Text = "The privacy statement was declined. Go to Settings -> Privacy -> Speech, inking and typing, and ensure you have viewed the privacy policy, and Cortana is set to 'Get To Know You'";
00274             }
00275             else
00276             {
00277                 auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00278                 create_task(messageDialog->ShowAsync());
00279             }
00280         }
00281     });
00282 }
00283
00284 /// <summary>
00285 /// Uses the recognizer constructed earlier to listen for speech from the user before displaying
00286 /// it back on the screen. Uses developer-provided UI for user feedback.
00287 /// </summary>
00288 /// <param name="sender">Button that triggered this event</param>
00289 /// <param name="e">State information about the routed event</param>
00290 void Scenario_ListConstraint::RecognizeWithoutUIListConstraint_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00291 {
00292     heardYouSayTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00293
00294     // Disable the UI while recognition is occurring, and provide feedback to the user about current state.
00295     btnRecognizeWithUI->IsEnabled = false;
00296     btnRecognizeWithoutUI->IsEnabled = false;
00297     cbLanguageSelection->IsEnabled = false;
00298     listenWithoutUIButtonText->Text = " listening for speech...";
00299
00300     // Start recognition.
00301     create_task(speechRecognizer->RecognizeAsync(), task_continuation_context::use_current())
00302         .then([this](task<SpeechRecognitionResult^> recognitionTask)
00303     {
00304         try
00305         {
00306             SpeechRecognitionResult^ speechRecognitionResult = recognitionTask.get();
00307
00308             String^ tag = L"unknown";
00309             if (speechRecognitionResult->Constraint != nullptr)
00310             {
00311                 // Only attempt to retreive a constraint tag if the result has one. If
00312                 // the garbage rule is hit, this may be null.
00313                 tag = speechRecognitionResult->Constraint->Tag;
00314             }
00315
00316             // If successful, display the recognition result.
00317             if (speechRecognitionResult->Status == SpeechRecognitionResultStatus::Success)
00318             {
00319                 heardYouSayTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00320                 resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00321                 resultTextBlock->Text = L"Heard: '" + speechRecognitionResult->Text + L"', Tag( '" + tag + L"', Confidence: " + speechRecognitionResult->Confidence.ToString() + ")";
00322             }
00323             else
00324             {
00325                 heardYouSayTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00326                 resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00327                 resultTextBlock->Text = L"Speech Recognition Failure, Status: " + speechRecognitionResult->Status.ToString();
00328             }
00329
00330             // Reset UI state.
00331             listenWithoutUIButtonText->Text = " without UI";
00332             btnRecognizeWithUI->IsEnabled = true;
00333             btnRecognizeWithoutUI->IsEnabled = true;
00334             cbLanguageSelection->IsEnabled = true;
00335         }
00336         catch (ObjectDisposedException^ exception)
00337         {
00338             // ObjectDisposedException will be thrown if you exit the scenario while the recogizer is actively
00339             // processing speech. Since this happens here when we navigate out of the scenario, don't try to
00340             // show a message dialog for this exception.
00341             OutputDebugString(L"ObjectDisposedException caught while recognition in progress (can be ignored):");
00342             OutputDebugString(exception->ToString()->Data());
00343         }
00344         catch (Exception^ exception)
00345         {
00346             // Handle the speech privacy policy error.
00347             if ((unsigned int)exception->HResult == Scenario_ListConstraint::HResultPrivacyStatementDeclined)
00348             {
00349                 resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00350                 resultTextBlock->Text = "The privacy statement was declined. Go to Settings -> Privacy -> Speech, inking and typing, and ensure you have viewed the privacy policy, and Cortana is set to 'Get To Know You'";
00351             }
00352             else
00353             {
00354                 auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00355                 create_task(messageDialog->ShowAsync());
00356             }
00357         }
00358     });
00359 }
00360
00361 /// <summary>
00362 /// Handle SpeechRecognizer state changed events by updating a UI component.
00363 /// </summary>
00364 /// <param name="sender">Speech recognizer that generated this status event</param>
00365 /// <param name="args">The recognizer's status</param>
00366 void Scenario_ListConstraint::SpeechRecognizer_StateChanged(SpeechRecognizer ^sender, SpeechRecognizerStateChangedEventArgs ^args)
00367 {
00368     dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00369     {
00370         rootPage->NotifyUser("Speech recognizer state: " + args->State.ToString(), NotifyType::StatusMessage);
00371     }));
00372
00373 }
00374
00375 /// <summary>
00376 /// Populate language dropdown with supported Dictation languages.
00377 /// </summary>
00378 void Scenario_ListConstraint::PopulateLanguageDropdown()
00379 {
00380     // disable callback temporarily.
00381     isPopulatingLanguages = true;
00382
00383     Windows::Globalization::Language^ defaultLanguage = SpeechRecognizer::SystemSpeechLanguage;
00384     auto supportedLanguages = SpeechRecognizer::SupportedGrammarLanguages;
00385     for (Windows::Globalization::Language^ lang : supportedLanguages)
00386     {
00387         ComboBoxItem^ item = ref new ComboBoxItem();
00388         item->Tag = lang;
00389         item->Content = lang->DisplayName;
00390
00391         cbLanguageSelection->Items->Append(item);
00392         if (lang->LanguageTag == defaultLanguage->LanguageTag)
00393         {
00394             item->IsSelected = true;
00395             cbLanguageSelection->SelectedItem = item;
00396         }
00397     }
00398
00399     isPopulatingLanguages = false;
00400 }
00401
00402
00403 /// <summary>
00404 /// Re-initialize the recognizer based on selections from the language combobox.
00405 /// </summary>
00406 void Scenario_ListConstraint::cbLanguageSelection_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00407 {
00408     if (isPopulatingLanguages)
00409     {
00410         return;
00411     }
00412
00413     ComboBoxItem^ item = (ComboBoxItem^)(cbLanguageSelection->SelectedItem);
00414     Windows::Globalization::Language^ newLanguage = (Windows::Globalization::Language^)item->Tag;
00415
00416     if (this->speechRecognizer != nullptr)
00417     {
00418         if (speechRecognizer->CurrentLanguage == newLanguage)
00419         {
00420             return;
00421         }
00422     }
00423
00424     try
00425     {
00426         speechContext->Languages = ref new VectorView<String^>(1, newLanguage->LanguageTag);
00427
00428         InitializeRecognizer(newLanguage);
00429     }
00430     catch (Exception^ exception)
00431     {
00432         auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00433         create_task(messageDialog->ShowAsync());
00434     }
00435
00436 }
Generated on Fri Nov 15 2024 22:21:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_AddOverlays Member List

This is the complete list of members for Scenario4_AddOverlays, including all inherited members.
baseVideoFile | Scenario4_AddOverlays | [private]
ChooseBaseVideo_Click(object sender, RoutedEventArgs e) | Scenario4_AddOverlays | [inline, private]
ChooseOverlayVideo_Click(object sender, RoutedEventArgs e) | Scenario4_AddOverlays | [inline, private]
composition | Scenario4_AddOverlays | [private]
CreateOverlays() | Scenario4_AddOverlays | [inline, private]
mediaStreamSource | Scenario4_AddOverlays | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario4_AddOverlays | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario4_AddOverlays | [inline, protected]
overlayVideoFile | Scenario4_AddOverlays | [private]
rootPage | Scenario4_AddOverlays | [private]
Scenario4_AddOverlays() | Scenario4_AddOverlays | [inline]
Generated on Fri Nov 15 2024 22:23:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialSound/cpp/Resource.h Source File

  • SpatialSound
  • cpp

Resource.h

Go to the documentation of this file.
00001 //{{NO_DEPENDENCIES}}
00002 // SpatialSound.rc
00003
00004 // Next default values for new objects
00005 //
00006 #ifdef APSTUDIO_INVOKED
00007 #ifndef APSTUDIO_READONLY_SYMBOLS
00008 #define _APS_NEXT_RESOURCE_VALUE        101
00009 #define _APS_NEXT_COMMAND_VALUE         40001
00010 #define _APS_NEXT_CONTROL_VALUE         1001
00011 #define _APS_NEXT_SYMED_VALUE           101
00012 #endif
00013 #endif
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: GlobalizationPreferences/cpp/pch.h Source File

  • GlobalizationPreferences
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/Scenario_SynthesizeTextBoundaries.xaml.cpp Source File

  • SpeechRecognitionAndSynthesis
  • cpp

Scenario_SynthesizeTextBoundaries.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario_SynthesizeTextBoundaries.xaml.h"
00014 #include <pplawait.h>
00015
00016 using namespace SDKTemplate;
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::ApplicationModel::Resources::Core;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Media::Core;
00024 using namespace Windows::Media::Playback;
00025 using namespace Windows::Media::SpeechSynthesis;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Controls::Primitives;
00029 using namespace Windows::UI::Xaml::Data;
00030 using namespace Windows::UI::Xaml::Input;
00031 using namespace Windows::UI::Xaml::Media;
00032 using namespace Windows::UI::Xaml::Navigation;
00033 using namespace Windows::UI::Core;
00034
00035 Scenario_SynthesizeTextBoundaries::Scenario_SynthesizeTextBoundaries() : rootPage(MainPage::Current)
00036 {
00037     InitializeComponent();
00038     synthesizer = ref new SpeechSynthesizer();
00039
00040     // initialize localization for text blob
00041     speechContext = ResourceContext::GetForCurrentView();
00042     speechContext->Languages = ref new VectorView<String^>(1, SpeechSynthesizer::DefaultVoice->Language);
00043
00044     speechResourceMap = ResourceManager::Current->MainResourceMap->GetSubtree(L"LocalizationTTSResources");
00045
00046     InitializeListboxVoiceChooser();
00047
00048     MediaPlayer^ player = ref new MediaPlayer();
00049     player->AutoPlay = false;
00050     player->MediaEnded += ref new  TypedEventHandler<MediaPlayer^, Object^>(this,&Scenario_SynthesizeTextBoundaries::media_MediaEnded);
00051
00052     media->SetMediaPlayer(player);
00053 }
00054
00055 /// <summary>
00056 /// This is invoked when the user clicks on the speak/stop button.
00057 /// </summary>
00058 /// <param name="sender">Button that triggered this event</param>
00059 /// <param name="e">State information about the routed event</param>
00060 void Scenario_SynthesizeTextBoundaries::Speak_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00061 {
00062     // If the media is playing, the user has pressed the button to stop the playback.
00063     if (media->MediaPlayer->PlaybackSession->PlaybackState == MediaPlaybackState::Playing)
00064     {
00065         media->MediaPlayer->Pause();
00066         btnSpeak->Content = "Speak";
00067     }
00068     else
00069     {
00070         String^ text = textToSynthesize->Text;
00071         if (!text->IsEmpty())
00072         {
00073             // Change the button label. You could also just disable the button if you don't want any user control.
00074             btnSpeak->Content = "Stop";
00075
00076             synthesizer->Options->IncludeWordBoundaryMetadata = true;
00077             synthesizer->Options->IncludeSentenceBoundaryMetadata = true;
00078
00079             //functionality wrapped in task function
00080             SynthesizeTextStream();
00081         }
00082     }
00083
00084 }
00085
00086 task<void> Scenario_SynthesizeTextBoundaries::SynthesizeTextStream()
00087 {
00088     String^ text = textToSynthesize->Text;
00089
00090     return create_task(synthesizer->SynthesizeTextToStreamAsync(text))
00091         .then([this](task<SpeechSynthesisStream^> previousTask)
00092     {
00093         try
00094         {
00095             synthesisStream = previousTask.get();
00096
00097             // Create a media source from the stream:
00098             MediaSource^ mediaSource = MediaSource::CreateFromStream(synthesisStream, synthesisStream->ContentType);
00099
00100             //Create a Media Playback Item
00101             MediaPlaybackItem^ mediaPlaybackItem = ref new MediaPlaybackItem(mediaSource);
00102
00103             // Ensure that the app is notified for cues.
00104             RegisterForBoundaryEvents(mediaPlaybackItem);
00105
00106             // Set the source of the MediaElement or MediaPlayerElement to the MediaPlaybackItem
00107             // and start playing the synthesized audio stream.
00108             media->Source = mediaPlaybackItem;
00109             media->MediaPlayer->Play();
00110         }
00111         catch (Exception^ ex)
00112         {
00113             if (ex->HResult == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND))
00114             {
00115                 btnSpeak->Content = L"Speak";
00116                 btnSpeak->IsEnabled = false;
00117                 listboxVoiceChooser->IsEnabled = false;
00118                 Windows::UI::Popups::MessageDialog^ dialog =
00119                     ref new Windows::UI::Popups::MessageDialog(ex->Message, "Media playback components unavailable.");
00120                 create_task(dialog->ShowAsync());
00121             }
00122             else
00123             {
00124                 // If the text is not able to be synthesized, throw an error message to the user.
00125                 btnSpeak->Content = L"Speak";
00126                 Windows::UI::Popups::MessageDialog^ dialog =
00127                     ref new Windows::UI::Popups::MessageDialog(ex->Message, "Unable to synthesize text");
00128                 create_task(dialog->ShowAsync());
00129             }
00130         }
00131     }, task_continuation_context::use_current());
00132 }
00133
00134 /// <summary>
00135 /// This is called when the user has selects a voice from the drop down.
00136 /// </summary>
00137 /// <param name="sender">unused object parameter</param>
00138 /// <param name="e">unused event parameter</param>
00139 void Scenario_SynthesizeTextBoundaries::ListboxVoiceChooser_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00140 {
00141     if (e->AddedItems->Size > 0)
00142     {
00143         ComboBoxItem^ first = safe_cast<ComboBoxItem^>(e->AddedItems->GetAt(0));
00144         VoiceInformation^ voice = safe_cast<VoiceInformation^>(first->Tag);
00145         synthesizer->Voice = voice;
00146
00147
00148         // update UI text to be an appropriate default translation.
00149         speechContext->Languages = ref new VectorView<String^>(1, { voice->Language });
00150         textToSynthesize->Text = speechResourceMap->GetValue("SynthesizeTextBoundariesDefaultText", speechContext)->ValueAsString;
00151
00152     }
00153 }
00154
00155 /// <summary>
00156 /// This is invoked when the stream is finished playing.
00157 /// </summary>
00158 /// <remarks>
00159 /// In this case, we're changing the button label based on the state.
00160 /// </remarks>
00161 /// <param name="sender">unused object parameter</param>
00162 /// <param name="e">unused event parameter</param>
00163 void Scenario_SynthesizeTextBoundaries::media_MediaEnded(Windows::Media::Playback::MediaPlayer^ sender, Platform::Object^ e)
00164 {
00165
00166     // Because this call is not awaited, execution of the current method continues before the call is completed
00167     Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
00168                                                                                                  ref new Windows::UI::Core::DispatchedHandler([this]()
00169     {
00170         btnSpeak->Content = "Speak";
00171     }));
00172 }
00173
00174 /// <summary>
00175 /// This creates items out of the system installed voices. The voices are then displayed in a listbox.
00176 /// This allows the user to change the voice of the synthesizer in your app based on their preference.
00177 /// </summary>
00178 void Scenario_SynthesizeTextBoundaries::InitializeListboxVoiceChooser()
00179 {
00180     // Get all of the installed voices.
00181     IVectorView<VoiceInformation^>^ voices = SpeechSynthesizer::AllVoices;
00182
00183     // Get the currently selected voice.
00184     VoiceInformation^ currentVoice = synthesizer->Voice;
00185
00186     // Copy the read-only voice information IVectorView into a mutable std::vector
00187     std::vector<VoiceInformation^> sortedVoices(voices->Size);
00188     std::copy(begin(voices), end(voices), sortedVoices.begin());
00189
00190     // Sort it based on the language tag (en-US, fr-FR, etc), to group them for readability.
00191     std::sort(begin(sortedVoices), end(sortedVoices), [](VoiceInformation^ a, VoiceInformation^ b)
00192     {
00193         return b->Language > a->Language;
00194     });
00195
00196     // Add them to the combo box in order.
00197     std::for_each(begin(sortedVoices), end(sortedVoices), [&](VoiceInformation^ voice)
00198     {
00199         ComboBoxItem^ item = ref new ComboBoxItem();
00200         item->Name = voice->DisplayName;
00201         item->Tag = voice;
00202         item->Content = voice->DisplayName + L" (" + voice->Language + L")";
00203         listboxVoiceChooser->Items->Append(item);
00204
00205         // Check to see if we're looking at the current voice and set it as selected in the listbox.
00206         if (currentVoice->Id == voice->Id)
00207         {
00208             item->IsSelected = true;
00209             listboxVoiceChooser->SelectedItem = item;
00210         }
00211     });
00212 }
00213
00214 /// <summary>
00215 /// Register for all boundary events and register a function to add any new events if they arise.
00216 /// </summary>
00217 /// <param name="mediaPlaybackItem">The Media Playback Item to register events for.</param>
00218 void Scenario_SynthesizeTextBoundaries::RegisterForBoundaryEvents(Windows::Media::Playback::MediaPlaybackItem^ mediaPlaybackItem)
00219 {
00220     // If tracks were available at source resolution time, itterate through and register:
00221     for (unsigned int index = 0; index < mediaPlaybackItem->TimedMetadataTracks->Size; index++)
00222     {
00223         RegisterMetadataHandlerForWords(mediaPlaybackItem, index);
00224         RegisterMetadataHandlerForSentences(mediaPlaybackItem, index);
00225     }
00226
00227     // Since the tracks are added later we will
00228     // monitor the tracks being added and subscribe to the ones of interest
00229     mediaPlaybackItem->TimedMetadataTracksChanged +=
00230         ref new TypedEventHandler<MediaPlaybackItem^, IVectorChangedEventArgs^>
00231         (this, &Scenario_SynthesizeTextBoundaries::timedMetadataTrackChangedHandler);
00232 }
00233
00234 /// <summary>
00235 /// Register for boundary events when they arise.
00236 /// </summary>
00237 /// <param name="mediaPlaybackItem">The Media PLayback Item add handlers to.</param>
00238 /// <param name="args">Arguments for the event.</param>
00239 void Scenario_SynthesizeTextBoundaries::timedMetadataTrackChangedHandler(Windows::Media::Playback::MediaPlaybackItem^ mediaPlaybackItem,
00240     Windows::Foundation::Collections::IVectorChangedEventArgs^ args)
00241 {
00242     if (args->CollectionChange == CollectionChange::ItemInserted)
00243     {
00244         RegisterMetadataHandlerForWords(mediaPlaybackItem, args->Index);
00245         RegisterMetadataHandlerForSentences(mediaPlaybackItem, args->Index);
00246     }
00247     else if (args->CollectionChange == CollectionChange::Reset)
00248     {
00249         for (unsigned int index = 0; index < mediaPlaybackItem->TimedMetadataTracks->Size; index++)
00250         {
00251             RegisterMetadataHandlerForWords(mediaPlaybackItem, index);
00252             RegisterMetadataHandlerForSentences(mediaPlaybackItem, index);
00253         }
00254     }
00255 }
00256
00257
00258 /// <summary>
00259 /// Register for just word boundary events.
00260 /// </summary>
00261 /// <param name="mediaPlaybackItem">The Media PLayback Item add handlers to.</param>
00262 /// <param name="index">Index of the timedMetadataTrack within the mediaPlaybackItem.</param>
00263 void Scenario_SynthesizeTextBoundaries::RegisterMetadataHandlerForWords(Windows::Media::Playback::MediaPlaybackItem^ mediaPlaybackItem, int index)
00264 {
00265     auto timedTrack = mediaPlaybackItem->TimedMetadataTracks->GetAt(index);
00266     //register for only word cues
00267     if (timedTrack->Id == "SpeechWord" && checkBoxWordBoundaries->IsChecked->Value == true)
00268     {
00269         timedTrack->CueEntered += ref new  TypedEventHandler<TimedMetadataTrack^, MediaCueEventArgs^>
00270             (this, &Scenario_SynthesizeTextBoundaries::metadata_SpeechCueEntered);
00271         mediaPlaybackItem->TimedMetadataTracks->SetPresentationMode(index, TimedMetadataTrackPresentationMode::ApplicationPresented);
00272     }
00273 }
00274
00275 /// <summary>
00276 /// Register for just sentence boundary events.
00277 /// </summary>
00278 /// <param name="mediaPlaybackItem">The Media Playback Item to register handlers for.</param>
00279 /// <param name="index">Index of the timedMetadataTrack within the mediaPlaybackItem.</param>
00280 void Scenario_SynthesizeTextBoundaries::RegisterMetadataHandlerForSentences(Windows::Media::Playback::MediaPlaybackItem^ mediaPlaybackItem, int index)
00281 {
00282     auto timedTrack = mediaPlaybackItem->TimedMetadataTracks->GetAt(index);
00283     //register for only sentence cues
00284     if (timedTrack->Id == "SpeechSentence" && (bool)checkBoxSentenceBoundaries->IsChecked->Value == true)
00285     {
00286         timedTrack->CueEntered += ref new  TypedEventHandler<TimedMetadataTrack^, MediaCueEventArgs^>
00287             (this, &Scenario_SynthesizeTextBoundaries::metadata_SpeechCueEntered);
00288         mediaPlaybackItem->TimedMetadataTracks->SetPresentationMode(index, TimedMetadataTrackPresentationMode::ApplicationPresented);
00289     }
00290 }
00291
00292 /// <summary>
00293 /// This function executes when a SpeechCue is hit and calls the functions to update the UI
00294 /// </summary>
00295 /// <param name="timedMetadataTrack">The timedMetadataTrack associated with the event.</param>
00296 /// <param name="args">the arguments associated with the event.</param>
00297 void Scenario_SynthesizeTextBoundaries::metadata_SpeechCueEntered(Windows::Media::Core::TimedMetadataTrack^ timedMetadataTrack,
00298                                                                   Windows::Media::Core::MediaCueEventArgs^ args)
00299 {
00300     // Check in case there are different tracks and the handler was used for more tracks
00301     if (timedMetadataTrack->TimedMetadataKind == TimedMetadataKind::Speech)
00302     {
00303         auto cue = (SpeechCue^)args->Cue;
00304         if (cue != nullptr)
00305         {
00306             printf("Hit Cue with start:%d and end: %d\r\n", cue->StartPositionInInput->Value,cue->EndPositionInInput->Value);
00307             wprintf(L"Cue text:[%s]\r\n", cue->Text->Data());
00308
00309             // Do something with the cue
00310             // Because this call is not awaited, execution of the current method continues before the call is completed
00311             Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
00312                 ref new Windows::UI::Core::DispatchedHandler([this, cue, timedMetadataTrack]()
00313             {
00314                 // Your UI update code goes here!
00315                 HighlightWordOnScreen(cue->StartPositionInInput->Value, cue->EndPositionInInput->Value);
00316                 FillTextBoxes(cue, timedMetadataTrack);
00317             }));
00318         }
00319     }
00320 }
00321
00322 /// <summary>
00323 /// This function selects the word associated with the start and end positions.
00324 /// </summary>
00325 /// <param name="startPositionInput"> the starting index of the word </param>
00326 /// <param name="endPositionInInput"> the ending index of the word </param>
00327 void Scenario_SynthesizeTextBoundaries::HighlightWordOnScreen(int startPositionInInput, int endPositionInInput)
00328 {
00329     //since we are using indecies we need to add 1 to the end position
00330     textToSynthesize->Select((int)startPositionInInput, (int)(endPositionInInput + 1) - (int)startPositionInInput);
00331 }
00332
00333 /// <summary>
00334 /// This function executes when a SpeechCue is hit and calls the functions to update the UI
00335 /// </summary>
00336 /// <param name="timedMetadataTrack">The timedMetadataTrack associated with the event.</param>
00337 /// <param name="cue">the SpeechCue object.</param>
00338 void Scenario_SynthesizeTextBoundaries::FillTextBoxes(Windows::Media::Core::SpeechCue ^ cue, Windows::Media::Core::TimedMetadataTrack ^ timedMetadataTrack)
00339 {
00340     //if it is a sentence cue, populate the sentence text box.
00341     if (timedMetadataTrack->Id == "SpeechSentence")
00342     {
00343         textBoxLastSpeechSentence->Text = cue->Text;
00344     }
00345     //if it is a word cue, populate the word text box
00346     if (timedMetadataTrack->Id == "SpeechWord")
00347     {
00348         textBoxLastSpeechWord->Text = cue->Text;
00349     }
00350 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/Common/BasicShapes.h Source File

  • Simple3DGameDX
  • cpp
  • Common

BasicShapes.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include "BasicMath.h"
00011
00012 // Defines the vertex format for the shapes generated in the functions below.
00013 struct BasicVertex
00014 {
00015     float3 pos;  // position
00016     float3 norm; // surface normal vector
00017     float2 tex;  // texture coordinate
00018 };
00019
00020 // Defines the vertex format for all shapes generated in the functions below.
00021 struct TangentVertex
00022 {
00023     float3 pos;  // position
00024     float2 tex;  // texture coordinate
00025     float3 uTan; // texture coordinate u-tangent vector
00026     float3 vTan; // texture coordinate v-tangent vector
00027 };
00028
00029 // A helper class that provides convenient functions for creating common
00030 // geometrical shapes used by DirectX SDK samples.
00031 ref class BasicShapes
00032 {
00033 internal:
00034     BasicShapes(ID3D11Device *d3dDevice);
00035     void CreateCube(
00036         _Out_ ID3D11Buffer **vertexBuffer,
00037         _Out_ ID3D11Buffer **indexBuffer,
00038         _Out_opt_ unsigned int *vertexCount,
00039         _Out_opt_ unsigned int *indexCount
00040         );
00041     void CreateBox(
00042         float3 radii,
00043         _Out_ ID3D11Buffer **vertexBuffer,
00044         _Out_ ID3D11Buffer **indexBuffer,
00045         _Out_opt_ unsigned int *vertexCount,
00046         _Out_opt_ unsigned int *indexCount
00047         );
00048     void CreateSphere(
00049         _Out_ ID3D11Buffer **vertexBuffer,
00050         _Out_ ID3D11Buffer **indexBuffer,
00051         _Out_opt_ unsigned int *vertexCount,
00052         _Out_opt_ unsigned int *indexCount
00053         );
00054     void CreateTangentSphere(
00055         _Out_ ID3D11Buffer **vertexBuffer,
00056         _Out_ ID3D11Buffer **indexBuffer,
00057         _Out_opt_ unsigned int *vertexCount,
00058         _Out_opt_ unsigned int *indexCount
00059         );
00060     void CreateReferenceAxis(
00061         _Out_ ID3D11Buffer **vertexBuffer,
00062         _Out_ ID3D11Buffer **indexBuffer,
00063         _Out_opt_ unsigned int *vertexCount,
00064         _Out_opt_ unsigned int *indexCount
00065         );
00066
00067 private:
00068     Microsoft::WRL::ComPtr<ID3D11Device> m_d3dDevice;
00069
00070     void CreateVertexBuffer(
00071         _In_ unsigned int numVertices,
00072         _In_ BasicVertex *vertexData,
00073         _Out_ ID3D11Buffer **vertexBuffer
00074         );
00075
00076     void CreateIndexBuffer(
00077         _In_ unsigned int numIndices,
00078         _In_ unsigned short *indexData,
00079         _Out_ ID3D11Buffer **indexBuffer
00080         );
00081
00082     void CreateTangentVertexBuffer(
00083         _In_ unsigned int numVertices,
00084         _In_ TangentVertex *vertexData,
00085         _Out_ ID3D11Buffer **vertexBuffer
00086         );
00087
00088 };
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SerialArduino/cs/Constants.cs Source File

  • SerialArduino
  • cs

Constants.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017
00018 using SerialArduino;
00019 using Windows.UI.Xaml.Controls;
00020
00021 namespace SerialArduino
00022 {
00023     public class DeviceProperties
00024     {
00025         public const String DeviceInstanceId = "System.Devices.DeviceInstanceId";
00026     }
00027
00028     public class ArduinoDevice
00029     {
00030         public const UInt16 Vid = 0x2341;
00031         public const UInt16 Pid = 0x0043;
00032     }
00033
00034 }
Generated on Fri Nov 15 2024 22:18:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/PrintHelper.h Source File

  • Printing
  • cpp

PrintHelper.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "MainPage.xaml.h"
00006
00007 using namespace Windows::UI::Xaml;
00008 using namespace Windows::UI::Xaml::Controls;
00009 using namespace Windows::UI::Xaml::Printing;
00010
00011 namespace SDKTemplate
00012 {
00013     [Windows::Foundation::Metadata::WebHostHidden]
00014     ref class PrintHelper
00015     {
00016     internal:
00017         /// <summary>
00018         /// Constructor
00019         /// </summary>
00020         /// <param name="scenarioPage">The scenario page constructing us</param>
00021         PrintHelper(Page^ scenarioPage);
00022
00023         /// <summary>
00024         /// A list of UIElements used to store the print preview pages.  This gives easy access
00025         /// to any desired preview page.
00026         /// </summary>
00027         property const std::vector<UIElement^>& PrintPreviewPages
00028         {
00029             const std::vector<UIElement^>& get()
00030             {
00031                 return m_printPreviewPages;
00032             }
00033         }
00034
00035     public:
00036         /// <summary>
00037         /// This function registers the app for printing with Windows and sets up the necessary event handlers for the print process.
00038         /// </summary>
00039         void RegisterForPrinting();
00040
00041         /// <summary>
00042         /// This function unregisters the app for printing with Windows.
00043         /// </summary>
00044         void UnregisterForPrinting();
00045
00046         void ShowPrintUIAsync();
00047
00048         void PreparePrintContent(Page^ page);
00049
00050     private:
00051         /// <summary>
00052         /// Print task requested event registration token
00053         /// </summary>
00054         Windows::Foundation::EventRegistrationToken m_printTaskRequestedEventToken;
00055
00056         /// <summary>
00057         /// A reference back to the scenario page used to access XAML elements on the scenario page.
00058         /// </summary>
00059         Page^ m_scenarioPage;
00060
00061         /// <summary>
00062         /// PrintDocument is used to prepare the pages for printing.
00063         /// Prepare the pages to print in the handlers for the Paginate, GetPreviewPage, and AddPages events.
00064         /// </summary>
00065         PrintDocument^ m_printDocument;
00066
00067         /// <summary>
00068         /// Marker interface for document source
00069         /// </summary>
00070         Windows::Graphics::Printing::IPrintDocumentSource^  m_printDocumentSource;
00071
00072         /// <summary>
00073         /// A list of UIElements used to store the print preview pages.  This gives easy access
00074         /// to any desired preview page.
00075         /// </summary>
00076         std::vector<UIElement^> m_printPreviewPages;
00077
00078         /// <summary>
00079         /// 7.5% margin on each side leaves 85% for content.
00080         /// </summary>
00081         float m_applicationContentMarginLeft = 0.075f;
00082
00083         /// <summary>
00084         /// 3% margin at top and bottom leaves 94% for content.
00085         /// </summary>
00086         float m_applicationContentMarginTop = 0.03f;
00087
00088     protected:
00089         /// <summary>
00090         /// The percent of app's margin width
00091         /// </summary>
00092         property float ApplicationContentMarginLeft
00093         {
00094             float get()
00095             {
00096                 return m_applicationContentMarginLeft;
00097             }
00098             void set(float value)
00099             {
00100                 m_applicationContentMarginLeft = value;
00101             }
00102         }
00103
00104         /// <summary>
00105         /// The percent of app's margin height
00106         /// </summary>
00107         property float ApplicationContentMarginTop
00108         {
00109             float get()
00110             {
00111                 return m_applicationContentMarginTop;
00112             }
00113             void set(float value)
00114             {
00115                 m_applicationContentMarginTop = value;
00116             }
00117         }
00118
00119         /// <summary>
00120         ///  A hidden canvas used to hold pages we wish to print
00121         /// </summary>
00122         property Canvas^ PrintCanvas
00123         {
00124             Canvas^ get()
00125             {
00126                 return safe_cast<Canvas^>(m_scenarioPage->FindName("PrintCanvas"));
00127             }
00128         }
00129
00130         property Page^ ScenarioPage
00131         {
00132             Page^ get()
00133             {
00134                 return m_scenarioPage;
00135             }
00136         }
00137
00138         /// <summary>
00139         /// A boolean which tracks whether the app has been registered for printing
00140         /// </summary>
00141         property bool RegisteredForPrinting;
00142
00143         /// <summary>
00144         /// First page in the printing-content series
00145         /// From this "virtual sized" paged content is split(text is flowing) to "printing pages"
00146         /// </summary>
00147         property FrameworkElement^ FirstPage;
00148
00149         property Windows::Graphics::Printing::IPrintDocumentSource^ PrintDocumentSource
00150         {
00151             Windows::Graphics::Printing::IPrintDocumentSource^ get()
00152             {
00153                 return m_printDocumentSource;
00154             }
00155         }
00156
00157         property PrintDocument^ CurrentPrintDocument
00158         {
00159             PrintDocument^ get()
00160             {
00161                 return m_printDocument;
00162             }
00163         }
00164
00165         property int PrintPreviewPageCount
00166         {
00167             int get()
00168             {
00169                 return static_cast<int>(m_printPreviewPages.size());
00170             }
00171         }
00172
00173         /// <summary>
00174         /// Method that will generate print content for the scenario
00175         /// For scenarios 1-4: it will create the first page from which content will flow
00176         /// Scenario 5 uses a different approach
00177         /// </summary>
00178         /// <param name="Page">The page to print</param>
00179         virtual void PreparePrintContentImpl(Page^ page);
00180
00181         /// <summary>
00182         /// This is the event handler for PrintManager.PrintTaskRequested.
00183         /// In order to ensure a good user experience, the system requires that the app handle the PrintTaskRequested event within the time specified by PrintTaskRequestedEventArgs->Request->Deadline.
00184         /// Therefore, we use this handler to only create the print task.
00185         /// The print settings customization can be done when the print document source is requested.
00186         /// </summary>
00187         /// <param name="sender">PrintManager</param>
00188         /// <param name="e">PrintTaskRequestedEventArgs</param>
00189         virtual void PrintTaskRequested(Windows::Graphics::Printing::PrintManager^ sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^ e);
00190
00191         /// <summary>
00192         /// This is the event handler for PrintDocument.Paginate. It creates print preview pages for the app.
00193         /// </summary>
00194         /// <param name="sender">PrintDocument</param>
00195         /// <param name="e">Paginate Event Arguments</param>
00196         virtual void CreatePrintPreviewPages(Object^ sender, PaginateEventArgs^ e);
00197
00198         /// <summary>
00199         /// This is called after the preview pages have been recreated.
00200         /// </summary>
00201         /// <param name="printTaskOptions"></param>
00202         virtual void OnPreviewPagesCreated(Windows::Graphics::Printing::PrintTaskOptions^ printTaskOptions) {};
00203
00204         /// <summary>
00205         /// This is the event handler for PrintDocument.GetPrintPreviewPage. It provides a specific print preview page,
00206         /// in the form of an UIElement, to an instance of PrintDocument. PrintDocument subsequently converts the UIElement
00207         /// into a page that the Windows print system can deal with.
00208         /// </summary>
00209         /// <param name="sender">The Print Document</param>
00210         /// <param name="e">Arguments containing the preview requested page</param>
00211         virtual void GetPrintPreviewPage(Object^ sender, GetPreviewPageEventArgs^ e);
00212
00213         /// <summary>
00214         /// This is the event handler for PrintDocument.AddPages. It provides all pages to be printed, in the form of
00215         /// UIElements, to an instance of PrintDocument. PrintDocument subsequently converts the UIElements
00216         /// into a pages that the Windows print system can deal with.
00217         /// </summary>
00218         /// <param name="sender"></param>
00219         /// <param name="e">Add page event arguments containing a print task options reference</param>
00220         virtual void AddPrintPages(Object^ sender, AddPagesEventArgs^ e);
00221
00222         /// <summary>
00223         /// This function creates and adds one print preview page to the internal cache of print preview
00224         /// pages stored in m_printPreviewPages.
00225         /// </summary>
00226         /// <param name="lastRTBOAdded">Last RichTextBlockOverflow element added in the current content</param>
00227         /// <param name="printPageDescription">Printer's page description</param>
00228         virtual RichTextBlockOverflow^ AddOnePrintPreviewPage(RichTextBlockOverflow^ lastRTBOAdded, Windows::Graphics::Printing::PrintPageDescription printPageDescription);
00229     };
00230 }
Generated on Fri Nov 15 2024 22:20:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Compression/cpp/SampleConfiguration.cpp Source File

  • Compression
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "WinRT to WinRT compression/decompression", "SDKTemplate.Compression.Scenario1" },
00012     { "WinRT to Classic compression/decompression", "SDKTemplate.Compression.Scenario2" },
00013     { "Classic to WinRT compression/decompression", "SDKTemplate.Compression.Scenario3" }
00014 };
Generated on Fri Nov 15 2024 22:17:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicFaceDetection/cppwinrt/Scenario2_DetectInWebcam.h Source File

  • BasicFaceDetection
  • cppwinrt

Scenario2_DetectInWebcam.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_DetectInWebcam.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario2_DetectInWebcam : Scenario2_DetectInWebcamT<Scenario2_DetectInWebcam>
00020     {
00021         Scenario2_DetectInWebcam();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025
00026         fire_and_forget CameraStreamingButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         fire_and_forget CameraSnapshotButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void SnapshotCanvas_SizeChanged(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::SizeChangedEventArgs const& e);
00029
00030     private:
00031         // Values for identifying and controlling scenario states.
00032         enum ScenarioState
00033         {
00034             // Display is blank - default state.
00035             Idle,
00036
00037             // Webcam is actively engaged and a live video stream is displayed.
00038             Streaming,
00039
00040             // Snapshot image has been captured and is being displayed along with detected faces; webcam is not active.
00041             Snapshot,
00042         };
00043
00044     private:
00045         // Reference back to the "root" page of the app.
00046         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00047
00048         // Holds the current scenario state value.
00049         ScenarioState currentState = ScenarioState::Idle;
00050
00051         // References a MediaCapture instance; is null when not in Streaming state.
00052         agile_ref<Windows::Media::Capture::MediaCapture> agileMediaCapture{ nullptr };
00053
00054         // Cache of properties from the current MediaCapture device which is used for capturing the preview frame.
00055         Windows::Media::MediaProperties::VideoEncodingProperties videoProperties{ nullptr };
00056
00057         // References a FaceDetector instance.
00058         Windows::Media::FaceAnalysis::FaceDetector faceDetector{ nullptr };
00059
00060         // Event registration tokens.
00061         event_token suspendingEventToken;
00062
00063     private:
00064         fire_and_forget OnSuspending(Windows::Foundation::IInspectable const& sender, Windows::ApplicationModel::SuspendingEventArgs const& e);
00065         Windows::Foundation::IAsyncOperation<bool> StartWebcamStreamingAsync();
00066         Windows::Foundation::IAsyncAction ShutdownWebcamAsync();
00067         Windows::Foundation::IAsyncOperation<bool> TakeSnapshotAndFindFacesAsync();
00068         void SetupVisualization(Windows::UI::Xaml::Media::Imaging::WriteableBitmap const& displaySource, Windows::Foundation::Collections::IVector<Windows::Media::FaceAnalysis::DetectedFace> const& foundFaces);
00069         Windows::Foundation::IAsyncAction ChangeScenarioStateAsync(ScenarioState newState);
00070         fire_and_forget AbandonStreaming();
00071         fire_and_forget MediaCapture_CameraStreamStateChanged(Windows::Media::Capture::MediaCapture const& sender, Windows::Foundation::IInspectable const& args);
00072
00073     };
00074 }
00075
00076 namespace winrt::SDKTemplate::factory_implementation
00077 {
00078     struct Scenario2_DetectInWebcam : Scenario2_DetectInWebcamT<Scenario2_DetectInWebcam, implementation::Scenario2_DetectInWebcam>
00079     {
00080     };
00081 }
Generated on Fri Nov 15 2024 22:18:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInfo/cppwinrt/UserViewModel.h Source File

  • UserInfo
  • cppwinrt

UserViewModel.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "UserViewModel.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct UserViewModel : UserViewModelT<UserViewModel>
00019     {
00020         UserViewModel(hstring userId, hstring displayName) :
00021             m_userId(std::move(userId)),
00022             m_displayName(std::move(displayName))
00023         {
00024         }
00025
00026         hstring UserId()
00027         {
00028             return m_userId;
00029         }
00030
00031         void UserId(hstring userId)
00032         {
00033             m_userId = std::move(userId);
00034             RaisePropertyChanged(L"UserId");
00035         }
00036
00037         hstring DisplayName()
00038         {
00039             return m_displayName;
00040         }
00041
00042         void DisplayName(hstring displayName)
00043         {
00044             m_displayName = std::move(displayName);
00045             RaisePropertyChanged(L"DisplayName");
00046         }
00047
00048         event_token PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler)
00049         {
00050             return m_propertyChanged.add(handler);
00051         }
00052
00053         void PropertyChanged(event_token token)
00054         {
00055             m_propertyChanged.remove(token);
00056         }
00057
00058     private:
00059         void RaisePropertyChanged(hstring propertyName)
00060         {
00061             m_propertyChanged(*this, Windows::UI::Xaml::Data::PropertyChangedEventArgs(propertyName));
00062         }
00063
00064     private:
00065         hstring m_userId;
00066         hstring m_displayName;
00067         event<Windows::UI::Xaml::Data::PropertyChangedEventHandler> m_propertyChanged;
00068     };
00069 }
00070
00071 #if 0
00072 namespace winrt::SDKTemplate::factory_implementation
00073 {
00074     struct UserViewModel : UserViewModelT<UserViewModel, implementation::UserViewModel>
00075     {
00076     };
00077 }
00078 #endif
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Print3D Member List

This is the complete list of members for Print3D, including all inherited members.
a | Print3D | [private, static]
b | Print3D | [private, static]
enableButton | Print3D | [private, static]
g | Print3D | [private, static]
groupId | Print3D | [private, static]
indicesCount | Print3D | [private, static]
indicesMaterialPrint | Print3D | [private, static]
indicesPrint | Print3D | [private, static]
labelText | Print3D | [private, static]
ObjectToPrint | Print3D |
OnGUI() | Print3D | [inline, private]
pngBytes | Print3D | [private, static]
r | Print3D | [private, static]
Start() | Print3D | [inline, private]
StartPrinting() | Print3D | [inline, private]
Step1 | Print3D | [private, static]
Step2 | Print3D | [private, static]
Step3 | Print3D | [private, static]
Update() | Print3D | [inline, private]
uvPrint | Print3D | [private, static]
verticesCount | Print3D | [private, static]
verticesMaterialCount | Print3D | [private, static]
verticesPrint | Print3D | [private, static]
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: KeyCredentialManager/cpp/App.xaml.cpp Source File

  • KeyCredentialManager
  • cpp

App.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::ApplicationModel::Activation;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Controls::Primitives;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::UI::Xaml::Input;
00027 using namespace Windows::UI::Xaml::Interop;
00028 using namespace Windows::UI::Xaml::Media;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
00032
00033 /// <summary>
00034 /// Initializes the singleton application object.  This is the first line of authored code
00035 /// executed, and as such is the logical equivalent of main() or WinMain().
00036 /// </summary>
00037 App::App()
00038 {
00039     InitializeComponent();
00040     Suspending += ref new Windows::UI::Xaml::SuspendingEventHandler(this, &SDKTemplate::App::OnSuspending);
00041 }
00042
00043 /// <summary>
00044 /// Invoked when the application is launched normally by the end user.  Other entry points
00045 /// will be used such as when the application is launched to open a specific file.
00046 /// </summary>
00047 /// <param name="e">Details about the launch request and process.</param>
00048 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
00049 {
00050 #if _DEBUG
00051     // Show graphics profiling information while debugging.
00052     if (IsDebuggerPresent())
00053     {
00054         // Display the current frame rate counters
00055         DebugSettings->EnableFrameRateCounter = false;
00056     }
00057 #endif
00058
00059     auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00060
00061     // Do not repeat app initialization when the Window already has content,
00062     // just ensure that the window is active
00063     if (rootFrame == nullptr)
00064     {
00065         // Create a Frame to act as the navigation context and associate it with
00066         // a SuspensionManager key
00067         rootFrame = ref new Frame();
00068
00069         // Set the default language
00070         rootFrame->Language = Windows::Globalization::ApplicationLanguages::Languages->GetAt(0);
00071
00072         rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed);
00073
00074         if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
00075         {
00076             // TODO: Restore the saved session state only when appropriate, scheduling the
00077             // final launch steps after the restore is complete
00078         }
00079
00080         if (rootFrame->Content == nullptr)
00081         {
00082             // When the navigation stack isn't restored navigate to the first page,
00083             // configuring the new page by passing required information as a navigation
00084             // parameter
00085             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00086         }
00087         // Place the frame in the current Window
00088         Window::Current->Content = rootFrame;
00089         // Ensure the current window is active
00090         Window::Current->Activate();
00091     }
00092     else
00093     {
00094         if (rootFrame->Content == nullptr)
00095         {
00096             // When the navigation stack isn't restored navigate to the first page,
00097             // configuring the new page by passing required information as a navigation
00098             // parameter
00099             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00100         }
00101         // Ensure the current window is active
00102         Window::Current->Activate();
00103     }
00104 }
00105
00106 /// <summary>
00107 /// Invoked when application execution is being suspended.  Application state is saved
00108 /// without knowing whether the application will be terminated or resumed with the contents
00109 /// of memory still intact.
00110 /// </summary>
00111 /// <param name="sender">The source of the suspend request.</param>
00112 /// <param name="e">Details about the suspend request.</param>
00113 void App::OnSuspending(Object^ /* sender */, SuspendingEventArgs^ /* e */)
00114 {
00115     //TODO: Save application state and stop any background activity
00116 }
00117
00118
00119 /// <summary>
00120 /// Invoked when Navigation to a certain page fails
00121 /// </summary>
00122 /// <param name="sender">The Frame which failed navigation</param>
00123 /// <param name="e">Details about the navigation failure</param>
00124 void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e)
00125 {
00126     throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name);
00127 }
Generated on Fri Nov 15 2024 22:16:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_ChangePIN Member List

This is the complete list of members for Scenario2_ChangePIN, including all inherited members.
ChangePin_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_ChangePIN
Scenario2_ChangePIN() | Scenario2_ChangePIN
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Contact Member List

This is the complete list of members for Contact, including all inherited members.
Biography | Contact |
Contact() | Contact | [inline]
FirstName | Contact |
GenerateBiography() | Contact | [inline, private, static]
GenerateFirstName() | Contact | [inline, private, static]
GenerateLastName() | Contact | [inline, private, static]
GeneratePhoneNumber() | Contact | [inline, private, static]
GeneratePosition() | Contact | [inline, private, static]
GetContacts(int numberOfContacts) | Contact | [inline, static]
GetContactsGrouped(int numberOfContacts) | Contact | [inline, static]
GetNewContact() | Contact | [inline, static]
Id | Contact |
InitialOf(string word) | Contact | [inline, private, static]
Initials | Contact |
LastName | Contact |
Name | Contact |
PhoneNumber | Contact |
Position | Contact |
random | Contact | [private, static]
ToString() | Contact | [inline]
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_ForegroundGeofence Member List

This is the complete list of members for Scenario4_ForegroundGeofence, including all inherited members.
_cts | Scenario4_ForegroundGeofence | [private]
_rootPage | Scenario4_ForegroundGeofence | [private]
AddEventDescription(string eventDescription) | Scenario4_ForegroundGeofence | [inline, private]
AddGeofenceToRegisteredGeofenceListBox(Geofence geofence) | Scenario4_ForegroundGeofence | [inline, private]
defaultDwellTime | Scenario4_ForegroundGeofence | [private]
GenerateGeofence() | Scenario4_ForegroundGeofence | [inline, private]
geofenceMonitor | Scenario4_ForegroundGeofence | [private]
OnCreateGeofence(object sender, RoutedEventArgs e) | Scenario4_ForegroundGeofence | [inline, private]
OnGeofenceStateChanged(GeofenceMonitor sender, object e) | Scenario4_ForegroundGeofence | [inline]
OnGeofenceStatusChanged(GeofenceMonitor sender, object e) | Scenario4_ForegroundGeofence | [inline]
OnNavigatedFrom(NavigationEventArgs e) | Scenario4_ForegroundGeofence | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario4_ForegroundGeofence | [inline, protected]
OnRegisteredGeofenceListBoxSelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario4_ForegroundGeofence | [inline, private]
OnRemoveGeofenceItem(object sender, RoutedEventArgs e) | Scenario4_ForegroundGeofence | [inline, private]
OnSetPositionToHere(object sender, RoutedEventArgs e) | Scenario4_ForegroundGeofence | [inline, private]
OnVisibilityChanged(object sender, VisibilityChangedEventArgs args) | Scenario4_ForegroundGeofence | [inline, private]
ParseDoubleFromTextBox(TextBox e, string name, double minValue, double maxValue, out double value) | Scenario4_ForegroundGeofence | [inline, private]
ParseTimeSpan(string field, TimeSpan defaultValue, out TimeSpan value) | Scenario4_ForegroundGeofence | [inline, private]
RefreshControlsFromGeofence(Geofence geofence) | Scenario4_ForegroundGeofence | [inline, private]
Scenario4_ForegroundGeofence() | Scenario4_ForegroundGeofence | [inline]
startImmediately | Scenario4_ForegroundGeofence | [private]
timeSpanFormat | Scenario4_ForegroundGeofence | [private, static]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DGradientMesh/cpp/D2DGradientMeshRenderer.h Source File

  • D2DGradientMesh
  • cpp

D2DGradientMeshRenderer.h

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include "DeviceResources.h"
00011
00012 namespace D2DGradientMesh
00013 {
00014     // This sample renderer instantiates a basic rendering pipeline.
00015     class D2DGradientMeshRenderer
00016     {
00017     public:
00018         D2DGradientMeshRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00019         void CreateDeviceDependentResources();
00020         void CreateWindowSizeDependentResources();
00021         void ReleaseDeviceDependentResources();
00022         void Render();
00023
00024     private:
00025         // Cached pointer to device resources.
00026         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00027
00028         // Sample-specific resources.
00029         Microsoft::WRL::ComPtr<ID2D1GradientMesh> m_gradientMesh;
00030     };
00031 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: EnterpriseDataProtection/cs/Scenario14_QueryCpPaste.xaml.cs Source File

  • EnterpriseDataProtection
  • cs

Scenario14_QueryCpPaste.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using System.Threading.Tasks;
00017 using SDKTemplate;
00018 using Windows.Security.EnterpriseData;
00019 using Windows.ApplicationModel.DataTransfer;
00020 using Windows.Foundation;
00021
00022
00023 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00024
00025 namespace EdpSample
00026 {
00027     /// <summary>
00028     /// An empty page that can be used on its own or navigated to within a Frame.
00029     /// </summary>
00030     public sealed partial class Scenario14_QueryCpPaste : Page
00031     {
00032         private MainPage rootPage;
00033
00034         public Scenario14_QueryCpPaste()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         protected override void OnNavigatedTo(NavigationEventArgs e)
00040         {
00041             rootPage = MainPage.Current;
00042         }
00043
00044         bool IsClipboardPeekAllowedAsync()
00045         {
00046             var result = ProtectionPolicyEvaluationResult.Blocked;
00047             var dataPackageView = Clipboard.GetContent();
00048             if (dataPackageView.Contains("text"))
00049             {
00050                 var protectionPolicyManager = ProtectionPolicyManager.GetForCurrentView();
00051                 result = ProtectionPolicyManager.CheckAccess(dataPackageView.Properties.EnterpriseId,
00052                     protectionPolicyManager.Identity);
00053             }
00054
00055             // Since this is a convenience feature to allow a peek of clipboard content,
00056             // if state is Blocked or ConsentRequired, do not show peek.
00057
00058             return result == ProtectionPolicyEvaluationResult.Allowed;
00059         }
00060
00061         private void QueryCp_Click(object sender, RoutedEventArgs e)
00062         {
00063             rootPage.NotifyUser("Check Access for Paste returned: " + IsClipboardPeekAllowedAsync(), NotifyType.StatusMessage);
00064         }
00065     }
00066 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cpp/Scenario6_NumeralSystemTranslation.xaml.cpp Source File

  • NumberFormatting
  • cpp

Scenario6_NumeralSystemTranslation.xaml.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario6_NumeralSystemTranslation.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Windows::UI::Xaml;
00010 using namespace Windows::UI::Xaml::Controls;
00011 using namespace Windows::UI::Xaml::Navigation;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::Globalization::NumberFormatting;
00015
00016 Scenario6_NumeralSystemTranslation::Scenario6_NumeralSystemTranslation()
00017 {
00018     InitializeComponent();
00019 }
00020
00021 void Scenario6_NumeralSystemTranslation::Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00022 {
00023     // Text for which translation of the numeral system will be performed.  Please note that translation only happens between
00024     // Latin and any other supported numeral system.  Translation between numeral systems is not a supported scenario.
00025     String^ stringToTranslate = "These are the 10 digits of a numeral system: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9";
00026
00027     // Variable where we keep the results of the scenario
00028     String^ results = "Original string: " + stringToTranslate + "\n\n";
00029
00030     // The numeral system translator is initialized based on the current application language.
00031     NumeralSystemTranslator^ numeralTranslator = ref new NumeralSystemTranslator();
00032
00033     // Do translation
00034     results = results + "Using application settings (" + numeralTranslator->NumeralSystem + "): ";
00035     results = results + numeralTranslator->TranslateNumerals(stringToTranslate) + "\n";
00036
00037     // Switch to a different numeral system
00038     numeralTranslator->NumeralSystem = "hanidec";
00039
00040     // Do translation
00041     results = results + "Using numeral system via property (" + numeralTranslator->NumeralSystem + " ): ";
00042     results = results + numeralTranslator->TranslateNumerals(stringToTranslate) + "\n";
00043
00044     // Create a converter using a language list to initialize the numeral system to an appropriate default
00045     auto languages = ref new Platform::Collections::Vector<String^>();
00046     languages->Append("ar-SA");
00047     languages->Append("en-US");
00048     numeralTranslator = ref new NumeralSystemTranslator(languages);
00049
00050     // Do translation
00051     results = results + "Using numeral system via language list (" + numeralTranslator->NumeralSystem + "): ";
00052     results = results + numeralTranslator->TranslateNumerals(stringToTranslate) + "\n";
00053
00054     // Display the results.
00055     OutputTextBlock->Text = results;
00056 }
Generated on Fri Nov 15 2024 22:20:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cs/Scenario_SRGSConstraint.xaml.cs Source File

  • SpeechRecognitionAndSynthesis
  • cs

Scenario_SRGSConstraint.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Threading.Tasks;
00016 using Windows.ApplicationModel;
00017 using Windows.ApplicationModel.Resources.Core;
00018 using Windows.Globalization;
00019 using Windows.Media.SpeechRecognition;
00020 using Windows.Storage;
00021 using Windows.UI;
00022 using Windows.UI.Core;
00023 using Windows.UI.Xaml;
00024 using Windows.UI.Xaml.Controls;
00025 using Windows.UI.Xaml.Media;
00026 using Windows.UI.Xaml.Navigation;
00027 using Windows.Foundation;
00028
00029 namespace SDKTemplate
00030 {
00031     public sealed partial class Scenario_SRGSConstraint : Page
00032     {
00033         /// <summary>
00034         /// This HResult represents the scenario where a user is prompted to allow in-app speech, but
00035         /// declines. This should only happen on a Phone device, where speech is enabled for the entire device,
00036         /// not per-app.
00037         /// </summary>
00038         private static uint HResultPrivacyStatementDeclined = 0x80045509;
00039
00040         /// <summary>
00041         /// the HResult 0x8004503a typically represents the case where a recognizer for a particular language cannot
00042         /// be found. This may occur if the language is installed, but the speech pack for that language is not.
00043         /// See Settings -> Time & Language -> Region & Language -> *Language* -> Options -> Speech Language Options.
00044         /// </summary>
00045         private static uint HResultRecognizerNotFound = 0x8004503a;
00046
00047         private SpeechRecognizer speechRecognizer;
00048         private IAsyncOperation<SpeechRecognitionResult> recognitionOperation;
00049         private ResourceContext speechContext;
00050         private ResourceMap speechResourceMap;
00051         private bool isPopulatingLanguages = false;
00052
00053         private Dictionary<string, Color> colorLookup = new Dictionary<string, Color>
00054         {
00055             { "COLOR_RED",   Colors.Red },   {"COLOR_BLUE",  Colors.Blue },  {"COLOR_BLACK",  Colors.Black},
00056             { "COLOR_BROWN", Colors.Brown},  {"COLOR_PURPLE",Colors.Purple}, {"COLOR_GREEN",  Colors.Green},
00057             { "COLOR_YELLOW",Colors.Yellow}, {"COLOR_CYAN",  Colors.Cyan},   {"COLOR_MAGENTA",Colors.Magenta},
00058             { "COLOR_ORANGE",Colors.Orange}, {"COLOR_GRAY",  Colors.Gray},   {"COLOR_WHITE",  Colors.White}
00059         };
00060
00061
00062         public Scenario_SRGSConstraint()
00063         {
00064             InitializeComponent();
00065         }
00066
00067         /// <summary>
00068         /// When activating the scenario, ensure we have permission from the user to access their microphone, and
00069         /// provide an appropriate path for the user to enable access to the microphone if they haven't
00070         /// given explicit permission for it.
00071         /// </summary>
00072         /// <param name="e">The navigation event details</param>
00073         protected async override void OnNavigatedTo(NavigationEventArgs e)
00074         {
00075             bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
00076             if (permissionGained)
00077             {
00078                 // Enable the recognition buttons.
00079                 btnRecognizeWithUI.IsEnabled = true;
00080                 btnRecognizeWithoutUI.IsEnabled = true;
00081
00082                 Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
00083                 string langTag = speechLanguage.LanguageTag;
00084                 speechContext = ResourceContext.GetForCurrentView();
00085                 speechContext.Languages = new string[] { langTag };
00086
00087                 speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");
00088
00089                 PopulateLanguageDropdown();
00090                 await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
00091             }
00092             else
00093             {
00094                 resultTextBlock.Visibility = Visibility.Visible;
00095                 resultTextBlock.Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
00096
00097                 btnRecognizeWithUI.IsEnabled = false;
00098                 btnRecognizeWithoutUI.IsEnabled = false;
00099                 cbLanguageSelection.IsEnabled = false;
00100             }
00101         }
00102
00103         /// <summary>
00104         /// Look up the supported languages for this speech recognition scenario,
00105         /// that are installed on this machine, and populate a dropdown with a list.
00106         /// </summary>
00107         private void PopulateLanguageDropdown()
00108         {
00109
00110             // disable the callback so we don't accidentally trigger initialization of the recognizer
00111             // while initialization is already in progress.
00112             isPopulatingLanguages = true;
00113
00114             Language defaultLanguage = SpeechRecognizer.SystemSpeechLanguage;
00115             IEnumerable<Language> supportedLanguages = SpeechRecognizer.SupportedGrammarLanguages;
00116             foreach (Language lang in supportedLanguages)
00117             {
00118                 ComboBoxItem item = new ComboBoxItem();
00119                 item.Tag = lang;
00120                 item.Content = lang.DisplayName;
00121
00122                 cbLanguageSelection.Items.Add(item);
00123                 if (lang.LanguageTag == defaultLanguage.LanguageTag)
00124                 {
00125                     item.IsSelected = true;
00126                     cbLanguageSelection.SelectedItem = item;
00127                 }
00128             }
00129
00130             isPopulatingLanguages = false;
00131         }
00132
00133         /// <summary>
00134         /// When a user changes the speech recognition language, trigger re-initialization of the
00135         /// speech engine with that language, and change any speech-specific UI assets.
00136         /// </summary>
00137         /// <param name="sender">Ignored</param>
00138         /// <param name="e">Ignored</param>
00139         private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
00140         {
00141             if (isPopulatingLanguages)
00142             {
00143                 return;
00144             }
00145
00146             ComboBoxItem item = (ComboBoxItem)(cbLanguageSelection.SelectedItem);
00147             Language newLanguage = (Language)item.Tag;
00148
00149             if (speechRecognizer != null)
00150             {
00151                 if (speechRecognizer.CurrentLanguage == newLanguage)
00152                 {
00153                     return;
00154                 }
00155             }
00156
00157             // trigger cleanup and re-initialization of speech.
00158             try
00159             {
00160                 speechContext.Languages = new string[] { newLanguage.LanguageTag };
00161
00162                 await InitializeRecognizer(newLanguage);
00163             }
00164             catch (Exception exception)
00165             {
00166                 var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
00167                 await messageDialog.ShowAsync();
00168             }
00169         }
00170
00171         /// <summary>
00172         /// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks.
00173         /// </summary>
00174         /// <param name="e">Details about the navigation event</param>
00175         protected override void OnNavigatedFrom(NavigationEventArgs e)
00176         {
00177             base.OnNavigatedFrom(e);
00178             if (speechRecognizer != null)
00179             {
00180                 if (speechRecognizer.State != SpeechRecognizerState.Idle)
00181                 {
00182                     if (recognitionOperation != null)
00183                     {
00184                         recognitionOperation.Cancel();
00185                         recognitionOperation = null;
00186                     }
00187                 }
00188
00189                 speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
00190
00191                 this.speechRecognizer.Dispose();
00192                 this.speechRecognizer = null;
00193             }
00194         }
00195
00196         /// <summary>
00197         /// Initialize Speech Recognizer and compile constraints.
00198         /// </summary>
00199         /// <param name="recognizerLanguage">Language to use for the speech recognizer</param>
00200         /// <returns>Awaitable task.</returns>
00201         private async Task InitializeRecognizer(Language recognizerLanguage)
00202         {
00203             if (speechRecognizer != null)
00204             {
00205                 // cleanup prior to re-initializing this scenario.
00206                 speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
00207
00208                 this.speechRecognizer.Dispose();
00209                 this.speechRecognizer = null;
00210             }
00211
00212             try
00213             {
00214                 // Initialize the SRGS-compliant XML file.
00215                 // For more information about grammars for Windows apps and how to
00216                 // define and use SRGS-compliant grammars in your app, see
00217                 // https://msdn.microsoft.com/en-us/library/dn596121.aspx
00218
00219                 // determine the language code being used.
00220                 string languageTag = recognizerLanguage.LanguageTag;
00221                 string fileName = String.Format("SRGS\\{0}\\SRGSColors.xml", languageTag);
00222                 StorageFile grammarContentFile = await Package.Current.InstalledLocation.GetFileAsync(fileName);
00223
00224                 // Initialize the SpeechRecognizer and add the grammar.
00225                 speechRecognizer = new SpeechRecognizer(recognizerLanguage);
00226
00227                 // Provide feedback to the user about the state of the recognizer.
00228                 speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
00229
00230                 // RecognizeWithUIAsync allows developers to customize the prompts.
00231                 speechRecognizer.UIOptions.ExampleText = speechResourceMap.GetValue("SRGSUIOptionsExampleText", speechContext).ValueAsString;
00232
00233                 SpeechRecognitionGrammarFileConstraint grammarConstraint = new SpeechRecognitionGrammarFileConstraint(grammarContentFile);
00234                 speechRecognizer.Constraints.Add(grammarConstraint);
00235                 SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync();
00236
00237                 // Check to make sure that the constraints were in a proper format and the recognizer was able to compile it.
00238                 if (compilationResult.Status != SpeechRecognitionResultStatus.Success)
00239                 {
00240                     // Disable the recognition buttons.
00241                     btnRecognizeWithUI.IsEnabled = false;
00242                     btnRecognizeWithoutUI.IsEnabled = false;
00243
00244                     // Let the user know that the grammar didn't compile properly.
00245                     resultTextBlock.Visibility = Visibility.Visible;
00246                     resultTextBlock.Text = "Unable to compile grammar.";
00247                 }
00248                 else
00249                 {
00250                     btnRecognizeWithUI.IsEnabled = true;
00251                     btnRecognizeWithoutUI.IsEnabled = true;
00252
00253                     resultTextBlock.Visibility = Visibility.Visible;
00254                     resultTextBlock.Text = speechResourceMap.GetValue("SRGSListeningPromptText", speechContext).ValueAsString;
00255
00256                     // Set EndSilenceTimeout to give users more time to complete speaking a phrase.
00257                     speechRecognizer.Timeouts.EndSilenceTimeout = TimeSpan.FromSeconds(1.2);
00258                 }
00259             }
00260             catch (Exception ex)
00261             {
00262                 if ((uint)ex.HResult == HResultRecognizerNotFound)
00263                 {
00264                     btnRecognizeWithUI.IsEnabled = false;
00265                     btnRecognizeWithoutUI.IsEnabled = false;
00266
00267                     resultTextBlock.Visibility = Visibility.Visible;
00268                     resultTextBlock.Text = "Speech Language pack for selected language not installed.";
00269                 }
00270                 else
00271                 {
00272                     var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
00273                     await messageDialog.ShowAsync();
00274                 }
00275             }
00276         }
00277
00278         /// <summary>
00279         /// Handle SpeechRecognizer state changed events by updating a UI component.
00280         /// </summary>
00281         /// <param name="sender">Speech recognizer that generated this status event</param>
00282         /// <param name="args">The recognizer's status</param>
00283         private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args)
00284         {
00285             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00286             {
00287                 MainPage.Current.NotifyUser("Speech recognizer state: " + args.State.ToString(), NotifyType.StatusMessage);
00288             });
00289         }
00290
00291         /// <summary>
00292         /// Uses the recognizer constructed earlier to listen for speech from the user before displaying
00293         /// it back on the screen. Uses the built-in speech recognition UI.
00294         /// </summary>
00295         /// <param name="sender">Button that triggered this event</param>
00296         /// <param name="e">State information about the routed event</param>
00297         private async void RecognizeWithUI_Click(object sender, RoutedEventArgs e)
00298         {
00299             // Reset the text to prompt the user.
00300             resultTextBlock.Text = speechResourceMap.GetValue("SRGSListeningPromptText", speechContext).ValueAsString;
00301
00302             // Start recognition.
00303             try
00304             {
00305                 recognitionOperation = speechRecognizer.RecognizeWithUIAsync();
00306                 SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
00307                 if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
00308                 {
00309                     HandleRecognitionResult(speechRecognitionResult);
00310                 }
00311                 else
00312                 {
00313                     resultTextBlock.Visibility = Visibility.Visible;
00314                     resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString());
00315                 }
00316             }
00317             catch (TaskCanceledException exception)
00318             {
00319                 // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
00320                 // processing speech. Since this happens here when we navigate out of the scenario, don't try to
00321                 // show a message dialog for this exception.
00322                 System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
00323                 System.Diagnostics.Debug.WriteLine(exception.ToString());
00324             }
00325             catch (Exception exception)
00326             {
00327                 // Handle the speech privacy policy error.
00328                 if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
00329                 {
00330                     resultTextBlock.Visibility = Visibility.Visible;
00331                     resultTextBlock.Text = "The privacy statement was declined.";
00332                 }
00333                 else
00334                 {
00335                     var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
00336                     await messageDialog.ShowAsync();
00337                 }
00338             }
00339         }
00340
00341         /// <summary>
00342         /// Uses the recognizer constructed earlier to listen for speech from the user before displaying
00343         /// it back on the screen. Uses developer-provided UI for user feedback.
00344         /// </summary>
00345         /// <param name="sender">Button that triggered this event</param>
00346         /// <param name="e">State information about the routed event</param>
00347         private async void RecognizeWithoutUI_Click(object sender, RoutedEventArgs e)
00348         {
00349             // Reset the text to prompt the user.
00350             resultTextBlock.Text = speechResourceMap.GetValue("SRGSListeningPromptText", speechContext).ValueAsString;
00351
00352             // Disable the UI while recognition is occurring, and provide feedback to the user about current state.
00353             btnRecognizeWithUI.IsEnabled = false;
00354             btnRecognizeWithoutUI.IsEnabled = false;
00355             cbLanguageSelection.IsEnabled = false;
00356             listenWithoutUIButtonText.Text = " listening for speech...";
00357
00358             // Start recognition.
00359             try
00360             {
00361                 recognitionOperation = speechRecognizer.RecognizeAsync();
00362                 SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
00363                 if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
00364                 {
00365                     HandleRecognitionResult(speechRecognitionResult);
00366                 }
00367                 else
00368                 {
00369                     resultTextBlock.Visibility = Visibility.Visible;
00370                     resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString());
00371                 }
00372             }
00373             catch (TaskCanceledException exception)
00374             {
00375                 // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
00376                 // processing speech. Since this happens here when we navigate out of the scenario, don't try to
00377                 // show a message dialog for this exception.
00378                 System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
00379                 System.Diagnostics.Debug.WriteLine(exception.ToString());
00380             }
00381             catch (Exception exception)
00382             {
00383                 // Handle the speech privacy policy error.
00384                 if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
00385                 {
00386                     resultTextBlock.Visibility = Visibility.Visible;
00387                     resultTextBlock.Text = "The privacy statement was declined.";
00388                 }
00389                 else
00390                 {
00391                     var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
00392                     await messageDialog.ShowAsync();
00393                 }
00394             }
00395
00396             // Reset UI state.
00397             listenWithoutUIButtonText.Text = " without UI";
00398             cbLanguageSelection.IsEnabled = true;
00399             btnRecognizeWithUI.IsEnabled = true;
00400             btnRecognizeWithoutUI.IsEnabled = true;
00401         }
00402
00403         /// <summary>
00404         /// Uses the result from the speech recognizer to change the colors of the shapes.
00405         /// </summary>
00406         /// <param name="recoResult">The result from the recognition event</param>
00407         private void HandleRecognitionResult(SpeechRecognitionResult recoResult)
00408         {
00409             // Check the confidence level of the recognition result.
00410             if (recoResult.Confidence == SpeechRecognitionConfidence.High ||
00411             recoResult.Confidence == SpeechRecognitionConfidence.Medium)
00412             {
00413                 // Declare a string that will contain messages when the color rule matches GARBAGE.
00414                 string garbagePrompt = "";
00415
00416                 // BACKGROUND: Check to see if the recognition result contains the semantic key for the background color,
00417                 // and not a match for the GARBAGE rule, and change the color.
00418                 if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BACKGROUND") && recoResult.SemanticInterpretation.Properties["KEY_BACKGROUND"][0].ToString() != "...")
00419                 {
00420                     string backgroundColor = recoResult.SemanticInterpretation.Properties["KEY_BACKGROUND"][0].ToString();
00421                     colorRectangle.Fill = new SolidColorBrush(getColor(backgroundColor));
00422                 }
00423
00424                 // If "background" was matched, but the color rule matched GARBAGE, prompt the user.
00425                 else if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BACKGROUND") && recoResult.SemanticInterpretation.Properties["KEY_BACKGROUND"][0].ToString() == "...")
00426                 {
00427
00428                     garbagePrompt += speechResourceMap.GetValue("SRGSBackgroundGarbagePromptText", speechContext).ValueAsString;
00429                     resultTextBlock.Text = garbagePrompt;
00430                 }
00431
00432                 // BORDER: Check to see if the recognition result contains the semantic key for the border color,
00433                 // and not a match for the GARBAGE rule, and change the color.
00434                 if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BORDER") && recoResult.SemanticInterpretation.Properties["KEY_BORDER"][0].ToString() != "...")
00435                 {
00436                     string borderColor = recoResult.SemanticInterpretation.Properties["KEY_BORDER"][0].ToString();
00437                     colorRectangle.Stroke = new SolidColorBrush(getColor(borderColor));
00438                 }
00439
00440                 // If "border" was matched, but the color rule matched GARBAGE, prompt the user.
00441                 else if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BORDER") && recoResult.SemanticInterpretation.Properties["KEY_BORDER"][0].ToString() == "...")
00442                 {
00443                     garbagePrompt += speechResourceMap.GetValue("SRGSBorderGarbagePromptText", speechContext).ValueAsString;
00444                     resultTextBlock.Text = garbagePrompt;
00445                 }
00446
00447                 // CIRCLE: Check to see if the recognition result contains the semantic key for the circle color,
00448                 // and not a match for the GARBAGE rule, and change the color.
00449                 if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_CIRCLE") && recoResult.SemanticInterpretation.Properties["KEY_CIRCLE"][0].ToString() != "...")
00450                 {
00451                     string circleColor = recoResult.SemanticInterpretation.Properties["KEY_CIRCLE"][0].ToString();
00452                     colorCircle.Fill = new SolidColorBrush(getColor(circleColor));
00453                 }
00454
00455                 // If "circle" was matched, but the color rule matched GARBAGE, prompt the user.
00456                 else if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_CIRCLE") && recoResult.SemanticInterpretation.Properties["KEY_CIRCLE"][0].ToString() == "...")
00457                 {
00458                     garbagePrompt += speechResourceMap.GetValue("SRGSCircleGarbagePromptText", speechContext).ValueAsString;
00459                     resultTextBlock.Text = garbagePrompt;
00460                 }
00461
00462                 // Initialize a string that will describe the user's color choices.
00463                 string textBoxColors = "You selected (Semantic Interpretation)-> \n";
00464
00465                 // Write the color choices contained in the semantics of the recognition result to the text box.
00466                 foreach (KeyValuePair<String, IReadOnlyList<string>> child in recoResult.SemanticInterpretation.Properties)
00467                 {
00468
00469                     // Check to see if any of the semantic values in recognition result contains a match for the GARBAGE rule.
00470                     if (!child.Value.Equals("..."))
00471                     {
00472
00473                         // Cycle through the semantic keys and values and write them to the text box.
00474                         textBoxColors += (string.Format(" {0} {1}\n",
00475                         child.Value[0], child.Key ?? "null"));
00476
00477                         resultTextBlock.Text = textBoxColors;
00478                     }
00479
00480                     // If there was no match to the colors rule or if it matched GARBAGE, prompt the user.
00481                     else
00482                     {
00483                         resultTextBlock.Text = garbagePrompt;
00484                     }
00485                 }
00486             }
00487
00488             // Prompt the user if recognition failed or recognition confidence is low.
00489             else if (recoResult.Confidence == SpeechRecognitionConfidence.Rejected ||
00490             recoResult.Confidence == SpeechRecognitionConfidence.Low)
00491             {
00492                 resultTextBlock.Text = speechResourceMap.GetValue("SRGSGarbagePromptText", speechContext).ValueAsString;
00493             }
00494         }
00495
00496         /// <summary>
00497         /// Creates a color object from the passed in string.
00498         /// </summary>
00499         /// <param name="colorString">The name of the color</param>
00500         private Color getColor(string colorString)
00501         {
00502             Color newColor = Colors.Transparent;
00503
00504             if (colorLookup.ContainsKey(colorString))
00505             {
00506                 newColor = colorLookup[colorString];
00507             }
00508
00509             return newColor;
00510         }
00511     }
00512 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cppwinrt/pch.cpp Source File

  • JumpList
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cpp/pch.cpp Source File

  • WiFiDirect
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cs/cpp/SampleConfiguration.cpp Source File

  • ProxyStubsForWinRTComponents
  • cs
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     // The format here is the following:
00012     { "Using Custom Components",                                     "SDKSample.ProxyStubsForWinRTComponents.OvenClient" },
00013     { "Using Custom Components (Implemented using WRL)",             "SDKSample.ProxyStubsForWinRTComponents.OvenClientWRL" },
00014     { "Handling Windows Runtime Exceptions",                         "SDKSample.ProxyStubsForWinRTComponents.CustomException" },
00015     { "Handling Windows Runtime Exceptions (Implemented using WRL)", "SDKSample.ProxyStubsForWinRTComponents.CustomExceptionWRL" }
00016 };
Generated on Fri Nov 15 2024 22:17:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_BackgroundDeviceWatcher Member List

This is the complete list of members for Scenario3_BackgroundDeviceWatcher, including all inherited members.
backgroundTaskName | Scenario3_BackgroundDeviceWatcher | [private]
backgroundTaskRegistration | Scenario3_BackgroundDeviceWatcher | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario3_BackgroundDeviceWatcher | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_BackgroundDeviceWatcher | [inline, protected]
OnTaskCompleted(BackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) | Scenario3_BackgroundDeviceWatcher | [inline, private]
RegisterBackgroundTask(DeviceWatcherTrigger deviceWatcherTrigger) | Scenario3_BackgroundDeviceWatcher | [inline, private]
rootPage | Scenario3_BackgroundDeviceWatcher | [private]
Scenario3_BackgroundDeviceWatcher() | Scenario3_BackgroundDeviceWatcher | [inline]
StartWatcher() | Scenario3_BackgroundDeviceWatcher | [inline, private]
StartWatcherButton_Click(object sender, RoutedEventArgs e) | Scenario3_BackgroundDeviceWatcher | [inline, private]
StopWatcher() | Scenario3_BackgroundDeviceWatcher | [inline, private]
StopWatcherButton_Click(object sender, RoutedEventArgs e) | Scenario3_BackgroundDeviceWatcher | [inline, private]
UnregisterBackgroundTask(IBackgroundTaskRegistration taskReg) | Scenario3_BackgroundDeviceWatcher | [inline, private]
Generated on Fri Nov 15 2024 22:23:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlAnimatedGif/cs/SampleConfiguration.cs Source File

  • XamlAnimatedGif
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "XAML Animated GIF Sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Animated GIFs", ClassType=typeof(Scenario1_Basic)},
00025         };
00026     }
00027
00028     public class Scenario
00029     {
00030         public string Title { get; set; }
00031         public Type ClassType { get; set; }
00032     }
00033 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlLite/cppwinrt/Scenario2_XmlWriter.cpp Source File

  • XmlLite
  • cppwinrt

Scenario2_XmlWriter.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_XmlWriter.h"
00014 #include "Scenario2_XmlWriter.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::ApplicationModel;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Storage;
00020 using namespace Windows::Storage::Streams;
00021 using namespace Windows::UI::Xaml;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario2_XmlWriter::Scenario2_XmlWriter()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     fire_and_forget Scenario2_XmlWriter::DoSomething_Click(IInspectable const&, RoutedEventArgs const&)
00031     {
00032         auto lifetime = get_strong();
00033
00034         hstring result;
00035         try
00036         {
00037             StorageFolder localFolder = ApplicationData::Current().LocalFolder();
00038             StorageFile file = co_await localFolder.CreateFileAsync(L"XmlWriterOutput.xml", CreationCollisionOption::OpenIfExists);
00039             IRandomAccessStream randomAccessWriteStream = co_await file.OpenAsync(FileAccessMode::ReadWrite);
00040             com_ptr<IStream> writeStream = capture<IStream>(::CreateStreamOverRandomAccessStream, winrt::get_unknown(randomAccessWriteStream));
00041             WriteXml(writeStream);
00042             result = L"File is written to " + file.Path() + L" successfully";
00043         }
00044         catch (hresult_error const& e)
00045         {
00046             result = L"Exception occured while writing the xml file: " + e.message() +
00047                 L"\nError code: " + to_hstring(e.code());
00048         }
00049         OutputTextBlock1().Text(result);
00050     }
00051
00052     void Scenario2_XmlWriter::WriteXml(com_ptr<IStream> const& writeStream)
00053     {
00054         com_ptr<IXmlWriter> writer;
00055         check_hresult(::CreateXmlWriter(IID_PPV_ARGS(&writer), nullptr));
00056         check_hresult(writer->SetOutput(writeStream.get()));
00057         check_hresult(writer->SetProperty(XmlWriterProperty_Indent, TRUE));
00058
00059         check_hresult(writer->WriteStartDocument(XmlStandalone_Omit));
00060         check_hresult(writer->WriteDocType(L"root", nullptr, nullptr, nullptr));
00061         check_hresult(writer->WriteProcessingInstruction(L"xml-stylesheet",
00062             L"href=\"mystyle.css\" title=\"Compact\" type=\"text/css\""));
00063         check_hresult(writer->WriteStartElement(nullptr, L"root", nullptr));
00064         check_hresult(writer->WriteStartElement(nullptr, L"sub", nullptr));
00065         check_hresult(writer->WriteAttributeString(nullptr, L"myAttr", nullptr, L"1234"));
00066         check_hresult(writer->WriteString(L"Markup is <escaped> for this string"));
00067         check_hresult(writer->WriteFullEndElement());
00068         check_hresult(writer->WriteStartElement(nullptr, L"anotherChild", nullptr));
00069         check_hresult(writer->WriteString(L"some text"));
00070         check_hresult(writer->WriteFullEndElement());
00071         check_hresult(writer->WriteWhitespace(L"\n"));
00072         check_hresult(writer->WriteCData(L"This is CDATA text."));
00073         check_hresult(writer->WriteWhitespace(L"\n"));
00074         check_hresult(writer->WriteStartElement(nullptr, L"containsCharacterEntity", nullptr));
00075         check_hresult(writer->WriteCharEntity(L'a'));
00076         check_hresult(writer->WriteFullEndElement());
00077         check_hresult(writer->WriteWhitespace(L"\n"));
00078         check_hresult(writer->WriteStartElement(nullptr, L"containsChars", nullptr));
00079         check_hresult(writer->WriteChars(L"abcdefghijklm", 5));
00080         check_hresult(writer->WriteFullEndElement());
00081         check_hresult(writer->WriteWhitespace(L"\n"));
00082         check_hresult(writer->WriteStartElement(nullptr, L"containsName", nullptr));
00083         check_hresult(writer->WriteName(L"myName"));
00084         check_hresult(writer->WriteEndElement());
00085         check_hresult(writer->WriteWhitespace(L"\n"));
00086         check_hresult(writer->WriteStartElement(nullptr, L"containsNmToken", nullptr));
00087         check_hresult(writer->WriteNmToken(L"myNmToken"));
00088         check_hresult(writer->WriteEndElement());
00089         check_hresult(writer->WriteWhitespace(L"\n"));
00090         check_hresult(writer->WriteComment(L"This is a comment"));
00091         check_hresult(writer->WriteWhitespace(L"\n"));
00092         check_hresult(writer->WriteRaw(L"<elementWrittenRaw/>"));
00093         check_hresult(writer->WriteWhitespace(L"\n"));
00094         check_hresult(writer->WriteRawChars(L"<rawCharacters/>", 16));
00095         check_hresult(writer->WriteWhitespace(L"\n"));
00096         check_hresult(writer->WriteElementString(nullptr, L"myElement", nullptr, L"myValue"));
00097         check_hresult(writer->WriteFullEndElement());
00098         check_hresult(writer->WriteWhitespace(L"\n"));
00099         check_hresult(writer->WriteEndDocument());
00100     }
00101 }
Generated on Fri Nov 15 2024 22:22:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-I2C/cpp/pch.cpp Source File

  • IoT-I2C
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Include the standard header and generate the precompiled header.
00014 //
00015
00016 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_GetPosition Member List

This is the complete list of members for Scenario2_GetPosition, including all inherited members.
CancelGetGeolocationButtonClicked(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_GetPosition |
GetGeolocationButtonClicked(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_GetPosition |
m_pendingOperation | Scenario2_GetPosition | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario2_GetPosition |
Scenario2_GetPosition() | Scenario2_GetPosition |
ShowSatelliteData(bool isVisible) | Scenario2_GetPosition | [private]
UpdateLocationData(Windows::Devices::Geolocation::Geoposition const &position) | Scenario2_GetPosition | [private]
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cs/Tasks/SampleBackgroundTask.cs Source File

  • BackgroundTask
  • cs
  • Tasks

SampleBackgroundTask.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Diagnostics;
00013 using System.Threading;
00014 using Windows.ApplicationModel.Background;
00015 using Windows.Foundation;
00016 using Windows.Storage;
00017 using Windows.System.Threading;
00018
00019 //
00020 // The namespace for the background tasks.
00021 //
00022 namespace Tasks
00023 {
00024     //
00025     // A background task always implements the IBackgroundTask interface.
00026     //
00027     public sealed class SampleBackgroundTask : IBackgroundTask
00028     {
00029         BackgroundTaskCancellationReason _cancelReason = BackgroundTaskCancellationReason.Abort;
00030         volatile bool _cancelRequested = false;
00031         BackgroundTaskDeferral _deferral = null;
00032         ThreadPoolTimer _periodicTimer = null;
00033         uint _progress = 0;
00034         IBackgroundTaskInstance _taskInstance = null;
00035
00036         //
00037         // The Run method is the entry point of a background task.
00038         //
00039         public void Run(IBackgroundTaskInstance taskInstance)
00040         {
00041             Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");
00042
00043             //
00044             // Query BackgroundWorkCost
00045             // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
00046             // of work in the background task and return immediately.
00047             //
00048             var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
00049             var settings = ApplicationData.Current.LocalSettings;
00050             settings.Values["BackgroundWorkCost"] = cost.ToString();
00051
00052             //
00053             // Associate a cancellation handler with the background task.
00054             //
00055             taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
00056
00057             //
00058             // Get the deferral object from the task instance, and take a reference to the taskInstance;
00059             //
00060             _deferral = taskInstance.GetDeferral();
00061             _taskInstance = taskInstance;
00062
00063             _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));
00064         }
00065
00066         //
00067         // Handles background task cancellation.
00068         //
00069         private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
00070         {
00071             //
00072             // Indicate that the background task is canceled.
00073             //
00074             _cancelRequested = true;
00075             _cancelReason = reason;
00076
00077             Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested...");
00078         }
00079
00080         //
00081         // Simulate the background task activity.
00082         //
00083         private void PeriodicTimerCallback(ThreadPoolTimer timer)
00084         {
00085             if ((_cancelRequested == false) && (_progress < 100))
00086             {
00087                 _progress += 10;
00088                 _taskInstance.Progress = _progress;
00089             }
00090             else
00091             {
00092                 _periodicTimer.Cancel();
00093
00094                 var key = _taskInstance.Task.Name;
00095
00096                 //
00097                 // Record that this background task ran.
00098                 //
00099                 String taskStatus = (_progress < 100) ? "Canceled with reason: " + _cancelReason.ToString() : "Completed";
00100                 var settings = ApplicationData.Current.LocalSettings;
00101                 settings.Values[key] = taskStatus;
00102                 Debug.WriteLine("Background " + _taskInstance.Task.Name + settings.Values[key]);
00103
00104                 //
00105                 // Indicate that the background task has completed.
00106                 //
00107                 _deferral.Complete();
00108             }
00109         }
00110     }
00111 }
Generated on Fri Nov 15 2024 22:18:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/Common/DDSTextureLoader.h Source File

  • Simple3DGameDX
  • cpp
  • Common

DDSTextureLoader.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.h
00003 //
00004 // Functions for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note these functions are useful as a light-weight runtime loader for DDS files. For
00007 // a full-featured DDS file reader, writer, and texture processing pipeline see
00008 // the 'Texconv' sample and the 'DirectXTex' library.
00009 //
00010 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00011 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00012 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00013 // PARTICULAR PURPOSE.
00014 //
00015 // Copyright (c) Microsoft Corporation. All rights reserved.
00016 //
00017 // http://go.microsoft.com/fwlink/?LinkId=248926
00018 // http://go.microsoft.com/fwlink/?LinkId=248929
00019 //--------------------------------------------------------------------------------------
00020
00021 #pragma once
00022
00023 void CreateDDSTextureFromMemory(
00024     _In_ ID3D11Device* d3dDevice,
00025     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
00026     _In_ size_t ddsDataSize,
00027     _Outptr_opt_ ID3D11Resource** texture,
00028     _Outptr_opt_ ID3D11ShaderResourceView** textureView,
00029     _In_ size_t maxsize = 0,
00030     _Out_opt_ D2D1_ALPHA_MODE* alphaMode = nullptr
00031     );
00032
00033 void CreateDDSTextureFromMemoryEx(
00034     _In_ ID3D11Device* d3dDevice,
00035     _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
00036     _In_ size_t ddsDataSize,
00037     _In_ size_t maxsize,
00038     _In_ D3D11_USAGE usage,
00039     _In_ unsigned int bindFlags,
00040     _In_ unsigned int cpuAccessFlags,
00041     _In_ unsigned int miscFlags,
00042     _In_ bool forceSRGB,
00043     _Outptr_opt_ ID3D11Resource** texture,
00044     _Outptr_opt_ ID3D11ShaderResourceView** textureView,
00045     _Out_opt_ D2D1_ALPHA_MODE* alphaMode = nullptr
00046     );
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ListViewEdgeTappedEventArgs Member List

This is the complete list of members for ListViewEdgeTappedEventArgs, including all inherited members.
item | ListViewEdgeTappedEventArgs | [private]
Item() | ListViewEdgeTappedEventArgs | [inline]
ListViewEdgeTappedEventArgs(Windows::UI::Xaml::Controls::ListViewItem const &item) | ListViewEdgeTappedEventArgs | [inline]
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlWebView/cs/Scenario10_UnviewableContent.xaml.cs Source File

  • XamlWebView
  • cs

Scenario10_UnviewableContent.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using System;
00017 using Windows.UI.ViewManagement;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class Scenario10_UnviewableContent : Page
00025     {
00026         private MainPage rootPage = MainPage.Current;
00027
00028         public Scenario10_UnviewableContent()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         protected override void OnNavigatedTo(NavigationEventArgs e)
00034         {
00035             WebViewControl.Navigate(new Uri("https://www.bing.com/search?q=site%3Amicrosoft.com+filetype%3Apdf"));
00036         }
00037
00038          private async void WebViewControl_UnviewableContentIdentified(WebView sender, WebViewUnviewableContentIdentifiedEventArgs args)
00039         {
00040             if (args.Uri.AbsolutePath.EndsWith(".pdf"))
00041             {
00042                 if (await Windows.System.Launcher.LaunchUriAsync(args.Uri))
00043                 {
00044                     rootPage.NotifyUser($"Launched {args.Uri} with system launcher", NotifyType.StatusMessage);
00045                 }
00046                 else
00047                 {
00048                     rootPage.NotifyUser($"Failed to launch {args.Uri}", NotifyType.ErrorMessage);
00049                 }
00050             } else
00051             {
00052                 rootPage.NotifyUser($"Blocked unknown file type of {args.Uri}", NotifyType.ErrorMessage);
00053             }
00054         }
00055     }
00056 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_Override Member List

This is the complete list of members for Scenario4_Override, including all inherited members.
Display_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario4_Override
Scenario4_Override() | Scenario4_Override
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleOrientationSensor/cpp/pch.cpp Source File

  • SimpleOrientationSensor
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cs/Scenario3.xaml.cs Source File

  • XamlCommanding
  • cs

Scenario3.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using Windows.UI.Xaml.Controls;
00014
00015 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00016
00017 namespace Commanding
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     public sealed partial class Scenario3 : Page
00023     {
00024         public Scenario3()
00025         {
00026             this.InitializeComponent();
00027             MainPage.Current.NotifyUser("CommandBar: Background Opacity at 50%", NotifyType.StatusMessage);
00028         }
00029
00030         private void CommandBar_Opening(object sender, object e)
00031         {
00032             this.translucentBackgroundBrush.Opacity = 1.0;
00033             MainPage.Current.NotifyUser("CommandBar: OPENING.  Setting Background Opacity to 100%", NotifyType.ErrorMessage);
00034         }
00035
00036         private void CommandBar_Closing(object sender, object e)
00037         {
00038             MainPage.Current.NotifyUser("CommandBar: CLOSING", NotifyType.ErrorMessage);
00039         }
00040
00041         private void CommandBar_Opened(object sender, object e)
00042         {
00043             MainPage.Current.NotifyUser("CommandBar: OPENED", NotifyType.StatusMessage);
00044         }
00045
00046         private void CommandBar_Closed(object sender, object e)
00047         {
00048             this.translucentBackgroundBrush.Opacity = 0.5;
00049             MainPage.Current.NotifyUser("CommandBar: CLOSED.  Setting Background Opacity to 50%", NotifyType.StatusMessage);
00050         }
00051     }
00052 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cppwinrt/BindingHelpers.h Source File

  • BarcodeScanner
  • cppwinrt

BindingHelpers.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "BindingHelpers.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct BindingHelpers
00019     {
00020         static bool Not(bool value)
00021         {
00022             return !value;
00023         }
00024
00025         static winrt::Windows::UI::Xaml::Visibility CollapsedIf(bool value)
00026         {
00027             return value ? winrt::Windows::UI::Xaml::Visibility::Collapsed : winrt::Windows::UI::Xaml::Visibility::Visible;
00028         }
00029     };
00030 }
00031
00032 namespace winrt::SDKTemplate::factory_implementation
00033 {
00034     struct BindingHelpers : BindingHelpersT<BindingHelpers, implementation::BindingHelpers>
00035     {
00036     };
00037 }
Generated on Fri Nov 15 2024 22:18:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/Scenario9_CustomPairDevice.xaml.h Source File

  • DeviceEnumerationAndPairing
  • cpp

Scenario9_CustomPairDevice.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario9_CustomPairDevice.g.h"
00006 #include "MainPage.xaml.h"
00007 #include "DisplayHelpers.h"
00008 #include "DeviceWatcherHelper.h"
00009
00010 namespace SDKTemplate
00011 {
00012     [Windows::Foundation::Metadata::WebHostHidden]
00013     public ref class Scenario9_CustomPairDevice sealed
00014     {
00015     public:
00016         Scenario9_CustomPairDevice();
00017
00018     protected:
00019         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00020         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00021
00022     private:
00023         void StartWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00024         void StopWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00025         void PairButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00026         void UnpairButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00027
00028         void StartWatcher();
00029         void StopWatcher();
00030
00031         void ResultsListView_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00032
00033         void PairingRequestedHandler(Windows::Devices::Enumeration::DeviceInformationCustomPairing^ sender, Windows::Devices::Enumeration::DevicePairingRequestedEventArgs^ args);
00034
00035         void ShowPairingPanel(Platform::String^ text, Windows::Devices::Enumeration::DevicePairingKinds pairingKind);
00036         void HidePairingPanel();
00037         concurrency::task<Platform::String^> GetPinFromUserAsync();
00038         void CompleteProvidePinTask(Platform::String^ pin = nullptr);
00039         concurrency::task<bool> GetUserConfirmationAsync(Platform::String^ pin);
00040         void CompleteConfirmPinTask(bool accept);
00041         void okButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void verifyButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         concurrency::task<Windows::Security::Credentials::PasswordCredential^> GetPasswordCredentialFromUserAsync();
00044         void CompletePasswordCredential(Platform::String^ username = nullptr, Platform::String^ password = nullptr);
00045         void yesButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046         void noButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047
00048         void OnDeviceListChanged(Windows::Devices::Enumeration::DeviceWatcher^ sender, Platform::String^ id);
00049         void UpdatePairingButtons();
00050         Windows::Devices::Enumeration::DevicePairingKinds GetSelectedCeremonies();
00051
00052         MainPage^ rootPage = MainPage::Current;
00053         Windows::Foundation::Collections::IObservableVector<DeviceInformationDisplay^>^ resultCollection = ref new Platform::Collections::Vector<DeviceInformationDisplay^>();
00054         DeviceWatcherHelper^ deviceWatcherHelper;
00055
00056         concurrency::task_completion_event<Platform::String^> providePinTaskSrc;
00057         concurrency::task_completion_event<bool> confirmPinTaskSrc;
00058         concurrency::task_completion_event<Windows::Security::Credentials::PasswordCredential^> providePasswordCredentialSrc;
00059     };
00060 }
Generated on Fri Nov 15 2024 22:19:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cs/Scenario4_ConsumableProduct.xaml.cs Source File

  • Store
  • cs

Scenario4_ConsumableProduct.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Services.Store;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// A page for fourth scenario.
00021     /// </summary>
00022     public sealed partial class Scenario4_ConsumableProduct : Page
00023     {
00024         MainPage rootPage = MainPage.Current;
00025         private StoreContext storeContext = StoreContext.GetDefault();
00026
00027         public Scenario4_ConsumableProduct()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         private async void GetManagedConsumablesButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00033         {
00034             // Create a filtered list of the product AddOns I care about
00035             string[] filterList = new string[] { "Consumable" };
00036
00037             // Get list of Add Ons this app can sell, filtering for the types we know about
00038             StoreProductQueryResult addOns = await storeContext.GetAssociatedStoreProductsAsync(filterList);
00039
00040             ProductsListView.ItemsSource = Utils.CreateProductListFromQueryResult(addOns, "Consumable Add-Ons");
00041         }
00042
00043         private async void PurchaseAddOnButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00044         {
00045             var item = (ItemDetails)ProductsListView.SelectedItem;
00046
00047             StorePurchaseResult result = await storeContext.RequestPurchaseAsync(item.StoreId);
00048             if (result.ExtendedError != null)
00049             {
00050                 Utils.ReportExtendedError(result.ExtendedError);
00051                 return;
00052             }
00053
00054             switch (result.Status)
00055             {
00056                 case StorePurchaseStatus.AlreadyPurchased: // should never get this for a managed consumable since they are stackable
00057                     rootPage.NotifyUser($"You already bought this consumable.", NotifyType.ErrorMessage);
00058                     break;
00059
00060                 case StorePurchaseStatus.Succeeded:
00061                     rootPage.NotifyUser($"You bought {item.Title}.", NotifyType.StatusMessage);
00062                     break;
00063
00064                 case StorePurchaseStatus.NotPurchased:
00065                     rootPage.NotifyUser("Product was not purchased, it may have been canceled.", NotifyType.ErrorMessage);
00066                     break;
00067
00068                 case StorePurchaseStatus.NetworkError:
00069                     rootPage.NotifyUser("Product was not purchased due to a network error.", NotifyType.ErrorMessage);
00070                     break;
00071
00072                 case StorePurchaseStatus.ServerError:
00073                     rootPage.NotifyUser("Product was not purchased due to a server error.", NotifyType.ErrorMessage);
00074                     break;
00075
00076                 default:
00077                     rootPage.NotifyUser("Product was not purchased due to an unknown error.", NotifyType.ErrorMessage);
00078                     break;
00079             }
00080         }
00081
00082         private async void GetConsumableBalanceButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00083         {
00084             var item = (ItemDetails)ProductsListView.SelectedItem;
00085
00086             StoreConsumableResult result = await storeContext.GetConsumableBalanceRemainingAsync(item.StoreId);
00087             if (result.ExtendedError != null)
00088             {
00089                 Utils.ReportExtendedError(result.ExtendedError);
00090                 return;
00091             }
00092
00093             switch (result.Status)
00094             {
00095                 case StoreConsumableStatus.InsufficentQuantity: // should never get this...
00096                     rootPage.NotifyUser($"Insufficient Quantity! Balance Remaining: {result.BalanceRemaining}", NotifyType.ErrorMessage);
00097                     break;
00098
00099                 case StoreConsumableStatus.Succeeded:
00100                     rootPage.NotifyUser($"Balance Remaining: {result.BalanceRemaining}", NotifyType.StatusMessage);
00101                     break;
00102
00103                 case StoreConsumableStatus.NetworkError:
00104                     rootPage.NotifyUser("Network error retrieving consumable balance.", NotifyType.ErrorMessage);
00105                     break;
00106
00107                 case StoreConsumableStatus.ServerError:
00108                     rootPage.NotifyUser("Server error retrieving consumable balance.", NotifyType.ErrorMessage);
00109                     break;
00110
00111                 default:
00112                     rootPage.NotifyUser("Unknown error retrieving consumable balance.", NotifyType.ErrorMessage);
00113                     break;
00114             }
00115         }
00116
00117         private async void FulfillConsumableButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00118         {
00119             var item = (ItemDetails)ProductsListView.SelectedItem;
00120
00121             UInt32 quantity = UInt32.Parse((string)QuantityComboBox.SelectedValue);
00122
00123             // This can be used to ensure this request is never double fulfilled. The server will
00124             // only accept one report for this specific GUID.
00125             Guid trackingId = Guid.NewGuid();
00126
00127             StoreConsumableResult result = await storeContext.ReportConsumableFulfillmentAsync(item.StoreId, quantity, trackingId);
00128             if (result.ExtendedError != null)
00129             {
00130                 Utils.ReportExtendedError(result.ExtendedError);
00131                 return;
00132             }
00133
00134             switch (result.Status)
00135             {
00136                 case StoreConsumableStatus.InsufficentQuantity:
00137                     rootPage.NotifyUser($"Insufficient Quantity! Balance Remaining: {result.BalanceRemaining}", NotifyType.ErrorMessage);
00138                     break;
00139
00140                 case StoreConsumableStatus.Succeeded:
00141                     rootPage.NotifyUser($"Successful fulfillment! Balance Remaining: {result.BalanceRemaining}", NotifyType.StatusMessage);
00142                     break;
00143
00144                 case StoreConsumableStatus.NetworkError:
00145                     rootPage.NotifyUser("Network error fulfilling consumable.", NotifyType.ErrorMessage);
00146                     break;
00147
00148                 case StoreConsumableStatus.ServerError:
00149                     rootPage.NotifyUser("Server error fulfilling consumable.", NotifyType.ErrorMessage);
00150                     break;
00151
00152                 default:
00153                     rootPage.NotifyUser("Unknown error fulfilling consumable.", NotifyType.ErrorMessage);
00154                     break;
00155             }
00156         }
00157     }
00158 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLOutOfProcessWinRTComponent/cpp/Server/Microsoft.SDKSamples.Kitchen.idl Source File

  • WRLOutOfProcessWinRTComponent
  • cpp
  • Server

Microsoft.SDKSamples.Kitchen.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include <sdkddkver.h>
00008 import "Windows.Foundation.idl";
00009
00010 namespace Microsoft.SDKSamples.Kitchen
00011 {
00012     [version(1.0)]
00013     typedef struct Dimensions
00014     {
00015         double Depth;
00016         double Height;
00017         double Width;
00018     } Dimensions;
00019
00020     [version(1.0)]
00021     typedef enum OvenTemperature
00022     {
00023         Low,
00024         Medium,
00025         High
00026     } OvenTemperature;
00027
00028     runtimeclass Bread;
00029     runtimeclass BreadBakedEventArgs;
00030     runtimeclass Oven;
00031
00032     [version(1.0), uuid(F13EA3D5-7B24-4CDE-9E5F-57AF30F0733C), exclusiveto(Bread)]
00033     interface IBread : IInspectable
00034     {
00035         [propget] HRESULT Flavor([out, retval] HSTRING* value);
00036     }
00037
00038     [version(1.0), uuid(332FD2F1-1C69-4C91-949E-4BB67A85BDC5)]
00039     interface IAppliance : IInspectable
00040     {
00041         [propget] HRESULT Volume([out, retval] double* value);
00042     }
00043
00044     [version(1.0), uuid(699B1394-3CEB-4A14-AE23-EFEC518B088B), exclusiveto(BreadBakedEventArgs)]
00045     interface IBreadBakedEventArgs : IInspectable
00046     {
00047         [propget] HRESULT Bread([out, retval] Bread** value);
00048     }
00049
00050     [version(1.0), uuid(6A112353-4F87-4460-A908-2944E92686F3), exclusiveto(Oven)]
00051     interface IOven : IInspectable requires IAppliance
00052     {
00053         HRESULT ConfigurePreheatTemperature([in] OvenTemperature temperature);
00054         HRESULT BakeBread([in] HSTRING flavor);
00055
00056         [eventadd] HRESULT BreadBaked([in] Windows.Foundation.TypedEventHandler<Oven*, BreadBakedEventArgs*>* handler, [out, retval] EventRegistrationToken* token);
00057         [eventremove] HRESULT BreadBaked([in] EventRegistrationToken token);
00058     }
00059
00060     [version(1.0), uuid(F36C2A21-F4E3-4C39-94CE-EB9190AFDAB3), exclusiveto(Oven)]
00061     interface IOvenFactory : IInspectable
00062     {
00063         HRESULT CreateOven([in] Dimensions dimensions, [out, retval] Oven** result);
00064     }
00065
00066     [version(1.0)]
00067     runtimeclass Bread
00068     {
00069         [default] interface IBread;
00070     }
00071
00072     [version(1.0)]
00073     runtimeclass BreadBakedEventArgs
00074     {
00075         [default] interface IBreadBakedEventArgs;
00076     }
00077
00078     [version(1.0), activatable(1.0), activatable(IOvenFactory, 1.0)]
00079     runtimeclass Oven
00080     {
00081         [default] interface IOven;
00082     }
00083 }
Generated on Fri Nov 15 2024 22:22:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cpp/Tasks/pch.h Source File

  • BackgroundTransfer
  • cpp
  • Tasks

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <collection.h>
00015 #include <ppltasks.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BufferHelper Member List

This is the complete list of members for BufferHelper, including all inherited members.
_buffer | BufferHelper | [private]
_bufferByteAccess | BufferHelper | [private]
_bytes | BufferHelper | [private]
_offset | BufferHelper | [private]
_size | BufferHelper | [private]
BufferHelper(Windows::Storage::Streams::IBuffer^buffer) | BufferHelper | [inline]
BufferHelper(BufferView^bufferView) | BufferHelper | [inline]
CheckBufferSize(const parentType *ptr, uint32_t effectiveCount) | BufferHelper | [inline]
GetPtrAt(uint32_t byteOffset) const | BufferHelper | [inline]
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteColorGlyph/cpp/DeviceResources.cpp Source File

  • DWriteColorGlyph
  • cpp

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "DeviceResources.h"
00010
00011 #include "DirectXHelper.h"
00012 #include <windows.ui.xaml.media.dxinterop.h>
00013
00014 using namespace D2D1;
00015 using namespace DirectX;
00016 using namespace Microsoft::WRL;
00017 using namespace Windows::Graphics::Display;
00018 using namespace Windows::UI::Core;
00019 using namespace Windows::UI::Xaml::Controls;
00020 using namespace Platform;
00021
00022 // Constants used to calculate screen rotations
00023 namespace ScreenRotation
00024 {
00025     // 0-degree Z-rotation
00026     static const XMFLOAT4X4 Rotation0(
00027         1.0f, 0.0f, 0.0f, 0.0f,
00028         0.0f, 1.0f, 0.0f, 0.0f,
00029         0.0f, 0.0f, 1.0f, 0.0f,
00030         0.0f, 0.0f, 0.0f, 1.0f
00031         );
00032
00033     // 90-degree Z-rotation
00034     static const XMFLOAT4X4 Rotation90(
00035         0.0f, 1.0f, 0.0f, 0.0f,
00036         -1.0f, 0.0f, 0.0f, 0.0f,
00037         0.0f, 0.0f, 1.0f, 0.0f,
00038         0.0f, 0.0f, 0.0f, 1.0f
00039         );
00040
00041     // 180-degree Z-rotation
00042     static const XMFLOAT4X4 Rotation180(
00043         -1.0f, 0.0f, 0.0f, 0.0f,
00044         0.0f, -1.0f, 0.0f, 0.0f,
00045         0.0f, 0.0f, 1.0f, 0.0f,
00046         0.0f, 0.0f, 0.0f, 1.0f
00047         );
00048
00049     // 270-degree Z-rotation
00050     static const XMFLOAT4X4 Rotation270(
00051         0.0f, -1.0f, 0.0f, 0.0f,
00052         1.0f, 0.0f, 0.0f, 0.0f,
00053         0.0f, 0.0f, 1.0f, 0.0f,
00054         0.0f, 0.0f, 0.0f, 1.0f
00055         );
00056 };
00057
00058 // Constructor for DeviceResources.
00059 DX::DeviceResources::DeviceResources() :
00060     m_d3dFeatureLevel(D3D_FEATURE_LEVEL_9_1),
00061     m_d3dRenderTargetSize(),
00062     m_outputSize(),
00063     m_logicalSize(),
00064     m_nativeOrientation(DisplayOrientations::None),
00065     m_currentOrientation(DisplayOrientations::None),
00066     m_dpi(-1.0f),
00067     m_deviceNotify(nullptr)
00068 {
00069     CreateDeviceIndependentResources();
00070     CreateDeviceResources();
00071 }
00072
00073 // Configures resources that don't depend on the Direct3D device.
00074 void DX::DeviceResources::CreateDeviceIndependentResources()
00075 {
00076     // Initialize Direct2D resources.
00077     D2D1_FACTORY_OPTIONS options;
00078     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00079
00080 #if defined(_DEBUG)
00081     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00082     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00083 #endif
00084
00085     // Initialize the Direct2D Factory.
00086     DX::ThrowIfFailed(
00087         D2D1CreateFactory(
00088             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00089             __uuidof(ID2D1Factory5),
00090             &options,
00091             &m_d2dFactory
00092             )
00093         );
00094
00095     // Initialize the DirectWrite Factory.
00096     DX::ThrowIfFailed(
00097         DWriteCreateFactory(
00098             DWRITE_FACTORY_TYPE_SHARED,
00099             __uuidof(IDWriteFactory4),
00100             &m_dwriteFactory
00101             )
00102         );
00103
00104     // Initialize the Windows Imaging Component (WIC) Factory.
00105     DX::ThrowIfFailed(
00106         CoCreateInstance(
00107             CLSID_WICImagingFactory2,
00108             nullptr,
00109             CLSCTX_INPROC_SERVER,
00110             IID_PPV_ARGS(&m_wicFactory)
00111             )
00112         );
00113 }
00114
00115 // Configures the Direct3D device, and stores handles to it and the device context.
00116 void DX::DeviceResources::CreateDeviceResources()
00117 {
00118     // This flag adds support for surfaces with a different color channel ordering
00119     // than the API default. It is required for compatibility with Direct2D.
00120     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00121
00122 #if defined(_DEBUG)
00123     if (DX::SdkLayersAvailable())
00124     {
00125         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00126         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00127     }
00128 #endif
00129
00130     // This array defines the set of DirectX hardware feature levels this app will support.
00131     // Note the ordering should be preserved.
00132     // Don't forget to declare your application's minimum required feature level in its
00133     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00134     D3D_FEATURE_LEVEL featureLevels[] =
00135     {
00136         D3D_FEATURE_LEVEL_11_1,
00137         D3D_FEATURE_LEVEL_11_0,
00138         D3D_FEATURE_LEVEL_10_1,
00139         D3D_FEATURE_LEVEL_10_0,
00140         D3D_FEATURE_LEVEL_9_3,
00141         D3D_FEATURE_LEVEL_9_2,
00142         D3D_FEATURE_LEVEL_9_1
00143     };
00144
00145     // Create the Direct3D 11 API device object and a corresponding context.
00146     ComPtr<ID3D11Device> device;
00147     ComPtr<ID3D11DeviceContext> context;
00148
00149     HRESULT hr = D3D11CreateDevice(
00150         nullptr,                    // Specify nullptr to use the default adapter.
00151         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00152         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00153         creationFlags,              // Set debug and Direct2D compatibility flags.
00154         featureLevels,              // List of feature levels this app can support.
00155         ARRAYSIZE(featureLevels),   // Size of the list above.
00156         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00157         &device,                    // Returns the Direct3D device created.
00158         &m_d3dFeatureLevel,         // Returns feature level of device created.
00159         &context                    // Returns the device immediate context.
00160         );
00161
00162     if (FAILED(hr))
00163     {
00164         // If the initialization fails, fall back to the WARP device.
00165         // For more information on WARP, see:
00166         // http://go.microsoft.com/fwlink/?LinkId=286690
00167         DX::ThrowIfFailed(
00168             D3D11CreateDevice(
00169                 nullptr,
00170                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00171                 0,
00172                 creationFlags,
00173                 featureLevels,
00174                 ARRAYSIZE(featureLevels),
00175                 D3D11_SDK_VERSION,
00176                 &device,
00177                 &m_d3dFeatureLevel,
00178                 &context
00179                 )
00180             );
00181     }
00182
00183     // Store pointers to the Direct3D 11.1 API device and immediate context.
00184     DX::ThrowIfFailed(
00185         device.As(&m_d3dDevice)
00186         );
00187
00188     DX::ThrowIfFailed(
00189         context.As(&m_d3dContext)
00190         );
00191
00192     // Create the Direct2D device object and a corresponding context.
00193     ComPtr<IDXGIDevice3> dxgiDevice;
00194     DX::ThrowIfFailed(
00195         m_d3dDevice.As(&dxgiDevice)
00196         );
00197
00198     DX::ThrowIfFailed(
00199         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00200         );
00201
00202     DX::ThrowIfFailed(
00203         m_d2dDevice->CreateDeviceContext(
00204             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00205             &m_d2dContext
00206             )
00207         );
00208 }
00209
00210 // These resources need to be recreated every time the window size is changed.
00211 void DX::DeviceResources::CreateWindowSizeDependentResources()
00212 {
00213     // Clear the previous window size specific context.
00214     ID3D11RenderTargetView* nullViews [] = { nullptr };
00215     m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00216     m_d2dContext->SetTarget(nullptr);
00217     m_d2dTargetBitmap = nullptr;
00218     m_d3dContext->Flush();
00219
00220     // Calculate the necessary render target size in pixels.
00221     m_outputSize.Width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_dpi);
00222     m_outputSize.Height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_dpi);
00223
00224     // Prevent zero size DirectX content from being created.
00225     m_outputSize.Width = max(m_outputSize.Width, 1);
00226     m_outputSize.Height = max(m_outputSize.Height, 1);
00227
00228     // The width and height of the swap chain must be based on the window's
00229     // natively-oriented width and height. If the window is not in the native
00230     // orientation, the dimensions must be reversed.
00231     DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation();
00232
00233     bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270;
00234     m_d3dRenderTargetSize.Width = swapDimensions ? m_outputSize.Height : m_outputSize.Width;
00235     m_d3dRenderTargetSize.Height = swapDimensions ? m_outputSize.Width : m_outputSize.Height;
00236
00237     if (m_swapChain != nullptr)
00238     {
00239         // If the swap chain already exists, resize it.
00240         HRESULT hr = m_swapChain->ResizeBuffers(
00241             2, // Double-buffered swap chain.
00242             static_cast<UINT>(m_d3dRenderTargetSize.Width),
00243             static_cast<UINT>(m_d3dRenderTargetSize.Height),
00244             DXGI_FORMAT_B8G8R8A8_UNORM,
00245             0
00246             );
00247
00248         if (hr == DXGI_ERROR_DEVICE_REMOVED)
00249         {
00250             // If the device was removed for any reason, a new device and swap chain will need to be created.
00251             HandleDeviceLost();
00252
00253             // Everything is set up now. Do not continue execution of this method. HandleDeviceLost will reenter this method
00254             // and correctly set up the new device.
00255             return;
00256         }
00257         else
00258         {
00259             DX::ThrowIfFailed(hr);
00260         }
00261     }
00262     else
00263     {
00264         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00265         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00266
00267         swapChainDesc.Width = static_cast<UINT>(m_d3dRenderTargetSize.Width); // Match the size of the window.
00268         swapChainDesc.Height = static_cast<UINT>(m_d3dRenderTargetSize.Height);
00269         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swap chain format.
00270         swapChainDesc.Stereo = false;
00271         swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling.
00272         swapChainDesc.SampleDesc.Quality = 0;
00273         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00274         swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency.
00275         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Runtime apps must use this SwapEffect.
00276         swapChainDesc.Flags = 0;
00277         swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE; // When using XAML interop, this value cannot be DXGI_ALPHA_MODE_PREMULTIPLIED.
00278         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00279
00280         // This sequence obtains the DXGI factory that was used to create the Direct3D device above.
00281         ComPtr<IDXGIDevice3> dxgiDevice;
00282         DX::ThrowIfFailed(
00283             m_d3dDevice.As(&dxgiDevice)
00284             );
00285
00286         ComPtr<IDXGIAdapter> dxgiAdapter;
00287         DX::ThrowIfFailed(
00288             dxgiDevice->GetAdapter(&dxgiAdapter)
00289             );
00290
00291         ComPtr<IDXGIFactory2> dxgiFactory;
00292         DX::ThrowIfFailed(
00293             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00294             );
00295
00296         DX::ThrowIfFailed(
00297             dxgiFactory->CreateSwapChainForCoreWindow(
00298                 m_d3dDevice.Get(),
00299                 reinterpret_cast<IUnknown*>(m_window.Get()),
00300                 &swapChainDesc,
00301                 nullptr,
00302                 &m_swapChain
00303                 )
00304             );
00305
00306         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00307         // ensures that the application will only render after each VSync, minimizing power consumption.
00308         DX::ThrowIfFailed(
00309             dxgiDevice->SetMaximumFrameLatency(1)
00310             );
00311     }
00312
00313     // Set the proper orientation for the swap chain, and generate 2D and
00314     // 3D matrix transformations for rendering to the rotated swap chain.
00315     // Note the rotation angle for the 2D and 3D transforms are different.
00316     // This is due to the difference in coordinate spaces.  Additionally,
00317     // the 3D matrix is specified explicitly to avoid rounding errors.
00318
00319     switch (displayRotation)
00320     {
00321     case DXGI_MODE_ROTATION_IDENTITY:
00322         m_orientationTransform2D = Matrix3x2F::Identity();
00323         m_orientationTransform3D = ScreenRotation::Rotation0;
00324         break;
00325
00326     case DXGI_MODE_ROTATION_ROTATE90:
00327         m_orientationTransform2D =
00328             Matrix3x2F::Rotation(90.0f) *
00329             Matrix3x2F::Translation(m_logicalSize.Height, 0.0f);
00330         m_orientationTransform3D = ScreenRotation::Rotation270;
00331         break;
00332
00333     case DXGI_MODE_ROTATION_ROTATE180:
00334         m_orientationTransform2D =
00335             Matrix3x2F::Rotation(180.0f) *
00336             Matrix3x2F::Translation(m_logicalSize.Width, m_logicalSize.Height);
00337         m_orientationTransform3D = ScreenRotation::Rotation180;
00338         break;
00339
00340     case DXGI_MODE_ROTATION_ROTATE270:
00341         m_orientationTransform2D =
00342             Matrix3x2F::Rotation(270.0f) *
00343             Matrix3x2F::Translation(0.0f, m_logicalSize.Width);
00344         m_orientationTransform3D = ScreenRotation::Rotation90;
00345         break;
00346
00347     default:
00348         throw ref new FailureException();
00349     }
00350
00351     DX::ThrowIfFailed(
00352         m_swapChain->SetRotation(displayRotation)
00353         );
00354
00355     // Create a Direct2D target bitmap associated with the
00356     // swap chain back buffer and set it as the current target.
00357     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00358         D2D1::BitmapProperties1(
00359             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00360             D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00361             m_dpi,
00362             m_dpi
00363             );
00364
00365     ComPtr<IDXGISurface2> dxgiBackBuffer;
00366     DX::ThrowIfFailed(
00367         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00368         );
00369
00370     DX::ThrowIfFailed(
00371         m_d2dContext->CreateBitmapFromDxgiSurface(
00372             dxgiBackBuffer.Get(),
00373             &bitmapProperties,
00374             &m_d2dTargetBitmap
00375             )
00376         );
00377
00378     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00379
00380     // Grayscale text anti-aliasing is recommended for all Windows Runtime apps.
00381     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00382 }
00383
00384 // This method is called when the CoreWindow is created (or re-created).
00385 void DX::DeviceResources::SetWindow(CoreWindow^ window)
00386 {
00387     m_window = window;
00388
00389     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00390
00391     m_logicalSize = Windows::Foundation::Size(window->Bounds.Width, window->Bounds.Height);
00392     m_nativeOrientation = currentDisplayInformation->NativeOrientation;
00393     m_currentOrientation = currentDisplayInformation->CurrentOrientation;
00394     m_dpi = currentDisplayInformation->LogicalDpi;
00395
00396     m_d2dContext->SetDpi(m_dpi, m_dpi);
00397     CreateWindowSizeDependentResources();
00398 }
00399
00400 // This method is called in the event handler for the SizeChanged event.
00401 void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize)
00402 {
00403     if (m_logicalSize != logicalSize)
00404     {
00405         m_logicalSize = logicalSize;
00406         CreateWindowSizeDependentResources();
00407     }
00408 }
00409
00410 // This method is called in the event handler for the DpiChanged event.
00411 void DX::DeviceResources::SetDpi(float dpi)
00412 {
00413     if (dpi != m_dpi)
00414     {
00415         m_dpi = dpi;
00416
00417         // When the display DPI changes, the logical size of the window (measured in Dips) also changes and needs to be updated.
00418         m_logicalSize = Windows::Foundation::Size(m_window->Bounds.Width, m_window->Bounds.Height);
00419
00420         m_d2dContext->SetDpi(m_dpi, m_dpi);
00421         CreateWindowSizeDependentResources();
00422     }
00423 }
00424
00425 // This method is called in the event handler for the OrientationChanged event.
00426 void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation)
00427 {
00428     if (m_currentOrientation != currentOrientation)
00429     {
00430         m_currentOrientation = currentOrientation;
00431         CreateWindowSizeDependentResources();
00432     }
00433 }
00434
00435 // This method is called in the event handler for the DisplayContentsInvalidated event.
00436 void DX::DeviceResources::ValidateDevice()
00437 {
00438     // The D3D Device is no longer valid if the default adapter changed since the device
00439     // was created or if the device has been removed.
00440
00441     // First, get the information for the default adapter from when the device was created.
00442
00443     ComPtr<IDXGIDevice3> dxgiDevice;
00444     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00445
00446     ComPtr<IDXGIAdapter> deviceAdapter;
00447     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00448
00449     ComPtr<IDXGIFactory2> deviceFactory;
00450     DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory)));
00451
00452     ComPtr<IDXGIAdapter1> previousDefaultAdapter;
00453     DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter));
00454
00455     DXGI_ADAPTER_DESC previousDesc;
00456     DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc));
00457
00458     // Next, get the information for the current default adapter.
00459
00460     ComPtr<IDXGIFactory2> currentFactory;
00461     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&currentFactory)));
00462
00463     ComPtr<IDXGIAdapter1> currentDefaultAdapter;
00464     DX::ThrowIfFailed(currentFactory->EnumAdapters1(0, &currentDefaultAdapter));
00465
00466     DXGI_ADAPTER_DESC currentDesc;
00467     DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(&currentDesc));
00468
00469     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00470     // a new D3D device must be created.
00471
00472     if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart ||
00473         previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart ||
00474         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00475     {
00476         // Release references to resources related to the old device.
00477         dxgiDevice = nullptr;
00478         deviceAdapter = nullptr;
00479         deviceFactory = nullptr;
00480         previousDefaultAdapter = nullptr;
00481
00482         // Create a new device and swap chain.
00483         HandleDeviceLost();
00484     }
00485 }
00486
00487 // Recreate all device resources and set them back to the current state.
00488 void DX::DeviceResources::HandleDeviceLost()
00489 {
00490     m_swapChain = nullptr;
00491
00492     if (m_deviceNotify != nullptr)
00493     {
00494         // Notify the renderers that device resources need to be released.
00495         // This ensures all references to the existing swap chain are released so that a new one can be created.
00496         m_deviceNotify->OnDeviceLost();
00497     }
00498
00499     // Create the new device and swap chain.
00500     CreateDeviceResources();
00501     m_d2dContext->SetDpi(m_dpi, m_dpi);
00502     CreateWindowSizeDependentResources();
00503
00504     if (m_deviceNotify != nullptr)
00505     {
00506         // Notify the renderers that resources can now be created again.
00507         m_deviceNotify->OnDeviceRestored();
00508     }
00509 }
00510
00511 // Register our DeviceNotify to be informed on device lost and creation.
00512 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify *deviceNotify)
00513 {
00514     m_deviceNotify = deviceNotify;
00515 }
00516
00517 // Call this method when the app suspends. It provides a hint to the driver that the app
00518 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00519 void DX::DeviceResources::Trim()
00520 {
00521     ComPtr<IDXGIDevice3> dxgiDevice;
00522     m_d3dDevice.As(&dxgiDevice);
00523
00524     dxgiDevice->Trim();
00525 }
00526
00527 // Present the contents of the swap chain to the screen.
00528 void DX::DeviceResources::Present()
00529 {
00530     // The first argument instructs DXGI to block until VSync, putting the application
00531     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00532     // frames that will never be displayed to the screen.
00533     HRESULT hr = m_swapChain->Present(1, 0);
00534
00535     // If the device was removed either by a disconnection or a driver upgrade, we
00536     // must recreate all device resources.
00537     if (hr == DXGI_ERROR_DEVICE_REMOVED)
00538     {
00539         HandleDeviceLost();
00540     }
00541     else
00542     {
00543         DX::ThrowIfFailed(hr);
00544     }
00545 }
00546
00547 // This method determines the rotation between the display device's native Orientation and the
00548 // current display orientation.
00549 DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation()
00550 {
00551     DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
00552
00553     // Note: NativeOrientation can only be Landscape or Portrait even though
00554     // the DisplayOrientations enum has other values.
00555     switch (m_nativeOrientation)
00556     {
00557     case DisplayOrientations::Landscape:
00558         switch (m_currentOrientation)
00559         {
00560         case DisplayOrientations::Landscape:
00561             rotation = DXGI_MODE_ROTATION_IDENTITY;
00562             break;
00563
00564         case DisplayOrientations::Portrait:
00565             rotation = DXGI_MODE_ROTATION_ROTATE270;
00566             break;
00567
00568         case DisplayOrientations::LandscapeFlipped:
00569             rotation = DXGI_MODE_ROTATION_ROTATE180;
00570             break;
00571
00572         case DisplayOrientations::PortraitFlipped:
00573             rotation = DXGI_MODE_ROTATION_ROTATE90;
00574             break;
00575         }
00576         break;
00577
00578     case DisplayOrientations::Portrait:
00579         switch (m_currentOrientation)
00580         {
00581         case DisplayOrientations::Landscape:
00582             rotation = DXGI_MODE_ROTATION_ROTATE90;
00583             break;
00584
00585         case DisplayOrientations::Portrait:
00586             rotation = DXGI_MODE_ROTATION_IDENTITY;
00587             break;
00588
00589         case DisplayOrientations::LandscapeFlipped:
00590             rotation = DXGI_MODE_ROTATION_ROTATE270;
00591             break;
00592
00593         case DisplayOrientations::PortraitFlipped:
00594             rotation = DXGI_MODE_ROTATION_ROTATE180;
00595             break;
00596         }
00597         break;
00598     }
00599     return rotation;
00600 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SemanticTextQuery/cpp/FindInProperty.xaml.cpp Source File

  • SemanticTextQuery
  • cpp

FindInProperty.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 //
00008 // Scenario2.xaml.cpp
00009 // Implementation of the Scenario2 class
00010 //
00011
00012 #include "pch.h"
00013 #include <ppltasks.h>
00014 #include "FindInProperty.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace SDKTemplate;
00018 using namespace concurrency;
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Storage;
00023 using namespace Windows::Storage::FileProperties;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Documents;
00027
00028 Scenario2::Scenario2()
00029 {
00030     InitializeComponent();
00031     FindQueryText->Text = "Title:Good OR Content:Tree";
00032     TitleText->Text = "These are Good Times";
00033     ContentText->Text = "There are many good times to be had. Go for a walk among the trees.";
00034 }
00035
00036 void Scenario2::Find_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00037 {
00038     ContentTextOutput->Text = "";
00039     TitleTextOutput->Text = "";
00040     auto mySemanticTextQuery = ref new Windows::Data::Text::SemanticTextQuery(FindQueryText->Text);
00041     IVectorView<Windows::Data::Text::TextSegment>^ ranges = mySemanticTextQuery->FindInProperty(ContentText->Text, "System.Search.Contents");
00042     HighlightRanges(ContentTextOutput, ContentText->Text, ranges);
00043     IVectorView<Windows::Data::Text::TextSegment>^ rangesTitle = mySemanticTextQuery->FindInProperty(TitleText->Text, "System.Title");
00044     HighlightRanges(TitleTextOutput, TitleText->Text, rangesTitle);
00045 }
Generated on Fri Nov 15 2024 22:21:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3 Member List

This is the complete list of members for Scenario3, including all inherited members.
OnNavigatedTo(NavigationEventArgs e) | Scenario3 | [inline, protected]
rootPage | Scenario3 | [private]
Scenario3() | Scenario3 | [inline]
SendHello_Click(object sender, RoutedEventArgs e) | Scenario3 | [inline, private]
Generated on Fri Nov 15 2024 22:23:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CopyText Member List

This is the complete list of members for CopyText, including all inherited members.
CopyButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | CopyText |
CopyText() | CopyText |
DisplayResourceMapAsync(Windows::ApplicationModel::DataTransfer::DataPackageView dataPackageView) | CopyText | [private]
htmlFragment | CopyText | [private]
imgSrc | CopyText | [private]
PasteButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | CopyText |
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cs/Content/ShaderStructures.cs Source File

  • BasicHologram
  • cs
  • Content

ShaderStructures.cs

Go to the documentation of this file.
00001 ﻿using System.Numerics;
00002
00003 namespace BasicHologram.Content
00004 {
00005     /// <summary>
00006     /// Constant buffer used to send hologram position transform to the shader pipeline.
00007     /// </summary>
00008     internal struct ModelConstantBuffer
00009     {
00010         public Matrix4x4 model;
00011     }
00012
00013     /// <summary>
00014     /// Used to send per-vertex data to the vertex shader.
00015     /// </summary>
00016     internal struct VertexPositionColor
00017     {
00018         public VertexPositionColor(Vector3 pos, Vector3 color)
00019         {
00020             this.pos   = pos;
00021             this.color = color;
00022         }
00023
00024         public Vector3 pos;
00025         public Vector3 color;
00026     };
00027 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/Controls/ContextMenuFlyout.xaml.cpp Source File

  • ComplexInk
  • cpp
  • Controls

ContextMenuFlyout.xaml.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003
00004 #include "pch.h"
00005 #include "ContextMenuFlyout.xaml.h"
00006
00007 using namespace SDKTemplate;
00008 using namespace Windows::UI::Xaml::Controls;
00009
00010 ContextMenuFlyout::ContextMenuFlyout(std::shared_ptr<SceneComposer> sceneComposer)
00011 {
00012     InitializeComponent();
00013     _sceneComposer = sceneComposer;
00014 }
00015
00016 void ContextMenuFlyout::EnablePasteItemOnly(bool IsEnabled, Windows::Foundation::Point pos)
00017 {
00018     // This method enables all items (cut/copy) when paste is disabled and then disables
00019     // them when paste is enabled. This is to provide a context menu that has certain functionality
00020     // enabled when a stylus is inside the selection rectangle and paste only when doing a gesture
00021     // outside of it.
00022     _pastePosition = pos;
00023     for (unsigned int index = 0; index < this->Items->Size; index++)
00024     {
00025         this->Items->GetAt(index)->IsEnabled = (PASTE_ITEM_INDEX == index) ? IsEnabled : !IsEnabled;
00026     }
00027 }
00028
00029 void SDKTemplate::ContextMenuFlyout::CopyFlyoutItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00030 {
00031     if (_sceneComposer != nullptr)
00032     {
00033         _sceneComposer->CopySelected();
00034     }
00035 }
00036
00037 void SDKTemplate::ContextMenuFlyout::CutFlyoutItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00038 {
00039     if (_sceneComposer != nullptr)
00040     {
00041         _sceneComposer->CutSelected();
00042     }
00043 }
00044
00045 void SDKTemplate::ContextMenuFlyout::PasteFlyoutItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     if (_sceneComposer != nullptr)
00048     {
00049         _sceneComposer->PasteSelected(_pastePosition);
00050     }
00051 }
Generated on Fri Nov 15 2024 22:18:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5 Member List

This is the complete list of members for Scenario5, including all inherited members.
Scenario5() Scenario5 [inline]
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

unique_shared_work_queue Member List

This is the complete list of members for unique_shared_work_queue, including all inherited members.
get() | unique_shared_work_queue | [inline]
m_queueId | unique_shared_work_queue | [private]
operator=(unique_shared_work_queue const &) | unique_shared_work_queue |
unique_shared_work_queue(PCWSTR className) | unique_shared_work_queue | [inline]
unique_shared_work_queue(unique_shared_work_queue const &) | unique_shared_work_queue |
~unique_shared_work_queue() | unique_shared_work_queue | [inline]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MediaCaptureManager Member List

This is the complete list of members for MediaCaptureManager, including all inherited members.
CanTakePhoto() | MediaCaptureManager |
CanToggleVideo() | MediaCaptureManager |
InitializeAsync(IMFDXGIDeviceManager *pDxgiDeviceManager=nullptr) | MediaCaptureManager |
Initialized enum value | MediaCaptureManager | [private]
IsHologramEnabled() | MediaCaptureManager | [inline]
IsSystemAudioEnabled() | MediaCaptureManager | [inline]
m_audioEffectAdded | MediaCaptureManager | [private]
m_currentState | MediaCaptureManager | [private]
m_hologramEnabled | MediaCaptureManager | [private]
m_lock | MediaCaptureManager | [private]
m_mediaCapture | MediaCaptureManager | [private]
m_photoEffectAdded | MediaCaptureManager | [private]
m_spMFDXGIDeviceManager | MediaCaptureManager | [private]
m_sysAudioEnabled | MediaCaptureManager | [private]
m_videoEffectAdded | MediaCaptureManager | [private]
MediaCaptureManager() | MediaCaptureManager |
Recording enum value | MediaCaptureManager | [private]
SetHologramEnabled(const bool enabled) | MediaCaptureManager | [inline]
SetSystemAudioEnabled(const bool enabled) | MediaCaptureManager | [inline]
StartingRecord enum value | MediaCaptureManager | [private]
StartRecordingAsync() | MediaCaptureManager |
State enum name | MediaCaptureManager | [private]
StoppingRecord enum value | MediaCaptureManager | [private]
StopRecordingAsync() | MediaCaptureManager |
TakePhotoAsync() | MediaCaptureManager |
TakingPhoto enum value | MediaCaptureManager | [private]
Unknown enum value | MediaCaptureManager | [private]
~MediaCaptureManager() | MediaCaptureManager | [virtual]
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialStage/cpp/AppView.cpp Source File

  • HolographicSpatialStage
  • cpp

AppView.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
00002 #include "AppView.h"
00003
00004 #include <ppltasks.h>
00005
00006 using namespace HolographicSpatialStage;
00007
00008 using namespace concurrency;
00009 using namespace Windows::ApplicationModel;
00010 using namespace Windows::ApplicationModel::Activation;
00011 using namespace Windows::ApplicationModel::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Graphics::Holographic;
00014 using namespace Windows::UI::Core;
00015
00016 // The main function is only used to initialize our IFrameworkView class.
00017 // Under most circumstances, you should not need to modify this function.
00018 [Platform::MTAThread]
00019 int main(Platform::Array<Platform::String^>^)
00020 {
00021     AppViewSource^ appViewSource = ref new ::AppViewSource();
00022     CoreApplication::Run(appViewSource);
00023     return 0;
00024 }
00025
00026 IFrameworkView^ AppViewSource::CreateView()
00027 {
00028     return ref new AppView();
00029 }
00030
00031 AppView::AppView()
00032 {
00033 }
00034
00035
00036 // IFrameworkView methods
00037
00038 // The first method called when the IFrameworkView is being created.
00039 // Use this method to subscribe for Windows shell events and to initialize your app.
00040 void AppView::Initialize(CoreApplicationView^ applicationView)
00041 {
00042     applicationView->Activated +=
00043         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &AppView::OnViewActivated);
00044
00045     // Register event handlers for app lifecycle.
00046     CoreApplication::Suspending +=
00047         ref new EventHandler<SuspendingEventArgs^>(this, &AppView::OnSuspending);
00048
00049     CoreApplication::Resuming +=
00050         ref new EventHandler<Platform::Object^>(this, &AppView::OnResuming);
00051
00052     // At this point we have access to the device and we can create device-dependent
00053     // resources.
00054     m_deviceResources = std::make_shared<DX::DeviceResources>();
00055
00056     m_main = std::make_unique<HolographicSpatialStageMain>(m_deviceResources);
00057 }
00058
00059 // Called when the CoreWindow object is created (or re-created).
00060 void AppView::SetWindow(CoreWindow^ window)
00061 {
00062     // Register for notification that the app window is being closed.
00063     window->Closed +=
00064         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &AppView::OnWindowClosed);
00065
00066     // Register for notifications that the app window is losing focus.
00067     window->VisibilityChanged +=
00068         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &AppView::OnVisibilityChanged);
00069
00070     // Create a holographic space for the core window for the current view.
00071     // Presenting holographic frames that are created by this holographic space will put
00072     // the app into exclusive mode.
00073     m_holographicSpace = HolographicSpace::CreateForCoreWindow(window);
00074
00075     // The DeviceResources class uses the preferred DXGI adapter ID from the holographic
00076     // space (when available) to create a Direct3D device. The HolographicSpace
00077     // uses this ID3D11Device to create and manage device-based resources such as
00078     // swap chains.
00079     m_deviceResources->SetHolographicSpace(m_holographicSpace);
00080
00081     // The main class uses the holographic space for updates and rendering.
00082     m_main->SetHolographicSpace(m_holographicSpace);
00083 }
00084
00085 // The Load method can be used to initialize scene resources or to load a
00086 // previously saved app state.
00087 void AppView::Load(Platform::String^ entryPoint)
00088 {
00089 }
00090
00091 // This method is called after the window becomes active. It oversees the
00092 // update, draw, and present loop, and it also oversees window message processing.
00093 void AppView::Run()
00094 {
00095     while (!m_windowClosed)
00096     {
00097         if (m_windowVisible && (m_holographicSpace != nullptr))
00098         {
00099             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00100
00101             HolographicFrame^ holographicFrame = m_main->Update();
00102
00103             if (m_main->Render(holographicFrame))
00104             {
00105                 // The holographic frame has an API that presents the swap chain for each
00106                 // holographic camera.
00107                 m_deviceResources->Present(holographicFrame);
00108             }
00109         }
00110         else
00111         {
00112             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00113         }
00114     }
00115 }
00116
00117 // Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
00118 // class is torn down while the app is in the foreground.
00119 // This method is not often used, but IFrameworkView requires it and it will be called for
00120 // holographic apps.
00121 void AppView::Uninitialize()
00122 {
00123
00124 }
00125
00126
00127 // Application lifecycle event handlers
00128
00129 // Called when the app is prelaunched. Use this method to load resources ahead of time
00130 // and enable faster launch times.
00131 void AppView::OnLaunched(LaunchActivatedEventArgs^ args)
00132 {
00133     if (args->PrelaunchActivated)
00134     {
00135         return;
00136     }
00137 }
00138
00139 // Called when the app view is activated. Activates the app's CoreWindow.
00140 void AppView::OnViewActivated(CoreApplicationView^ sender, IActivatedEventArgs^ args)
00141 {
00142     // Run() won't start until the CoreWindow is activated.
00143     sender->CoreWindow->Activate();
00144 }
00145
00146 void AppView::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
00147 {
00148     // Save app state asynchronously after requesting a deferral. Holding a deferral
00149     // indicates that the application is busy performing suspending operations. Be
00150     // aware that a deferral may not be held indefinitely; after about five seconds,
00151     // the app will be forced to exit.
00152     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
00153
00154     create_task([this, deferral] ()
00155     {
00156         m_deviceResources->Trim();
00157
00158         deferral->Complete();
00159     });
00160 }
00161
00162 void AppView::OnResuming(Platform::Object^ sender, Platform::Object^ args)
00163 {
00164     // Restore any data or state that was unloaded on suspend. By default, data
00165     // and state are persisted when resuming from suspend. Note that this event
00166     // does not occur if the app was previously terminated.
00167 }
00168
00169
00170 // Window event handlers
00171
00172 void AppView::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
00173 {
00174     m_windowVisible = args->Visible;
00175 }
00176
00177 void AppView::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
00178 {
00179     m_windowClosed = true;
00180 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

S5_AddWithAppContent Member List

This is the complete list of members for S5_AddWithAppContent, including all inherited members.
AddToIndex_Click(object sender, RoutedEventArgs e) | S5_AddWithAppContent | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | S5_AddWithAppContent | [inline, protected]
rootPage | S5_AddWithAppContent | [private]
S5_AddWithAppContent() | S5_AddWithAppContent | [inline]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaEditing/cpp/pch.h Source File

  • MediaEditing
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cppwinrt/LoggingScenarioHelpers.h Source File

  • Logging
  • cppwinrt

LoggingScenarioHelpers.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace winrt::SDKTemplate
00015 {
00016     // Create a time stamp to append to log file names so
00017     // each file has a unique name. The format is:
00018     //     YYMMDD-hhmmssMMM
00019     // where
00020     //     YY == year
00021     //     MM == month
00022     //     DD == day
00023     //     hh == hours
00024     //     mm == minutes
00025     //     ss == seconds
00026     //     MMM == milliseconds
00027     inline std::wstring
00028     GetTimeStamp()
00029     {
00030         std::wstring result;
00031         SYSTEMTIME timeNow;
00032         GetLocalTime(&timeNow);
00033         result.resize(16);
00034         swprintf_s(
00035             &result[0],
00036             result.size() + 1,
00037             L"%02u%02u%02u-%02u%02u%02u%03u",
00038             timeNow.wYear - 2000,
00039             timeNow.wMonth,
00040             timeNow.wDay,
00041             timeNow.wHour,
00042             timeNow.wMinute,
00043             timeNow.wSecond,
00044             timeNow.wMilliseconds);
00045         return result;
00046     }
00047
00048     inline Windows::UI::Xaml::Controls::ScrollViewer
00049     FindScrollViewer(Windows::UI::Xaml::DependencyObject const& control)
00050     {
00051         if (control == nullptr)
00052         {
00053             return nullptr;
00054         }
00055
00056         int childCount = Windows::UI::Xaml::Media::VisualTreeHelper::GetChildrenCount(control);
00057         if (childCount <= 0)
00058         {
00059             return nullptr;
00060         }
00061
00062         for (int childIndex = 0; childIndex < childCount; childIndex++)
00063         {
00064             Windows::UI::Xaml::DependencyObject childControl =
00065                 Windows::UI::Xaml::Media::VisualTreeHelper::GetChild(control, childIndex);
00066             Windows::UI::Xaml::Controls::ScrollViewer viewer =
00067                 childControl.try_as<Windows::UI::Xaml::Controls::ScrollViewer>();
00068             if (viewer != nullptr)
00069             {
00070                 return viewer;
00071             }
00072
00073             viewer = FindScrollViewer(childControl);
00074             if (viewer != nullptr)
00075             {
00076                 return viewer;
00077             }
00078         }
00079
00080         return nullptr;
00081     }
00082 }
Generated on Fri Nov 15 2024 22:20:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CameraResources Member List

This is the complete list of members for CameraResources, including all inherited members.
AttachViewProjectionBuffer(DeviceResources deviceResources) | CameraResources | [inline]
BackBufferDxgiFormat | CameraResources |
BackBufferRenderTargetView | CameraResources |
BackBufferTexture2D | CameraResources |
CameraResources(HolographicCamera holographicCamera) | CameraResources | [inline]
CreateResourcesForBackBuffer(DeviceResources deviceResources, ref HolographicCameraRenderingParameters cameraParameters) | CameraResources | [inline]
d3dBackBuffer | CameraResources | [private]
d3dDepthBuffer | CameraResources | [private]
d3dDepthStencilView | CameraResources | [private]
d3dRenderTargetSize | CameraResources | [private]
d3dRenderTargetView | CameraResources | [private]
d3dViewport | CameraResources | [private]
DepthBufferTexture2D | CameraResources |
DepthStencilView | CameraResources |
Dispose() | Disposer | [inline]
Dispose(bool disposeManagedResources) | Disposer | [inline, protected, virtual]
Disposer() | Disposer | [inline, protected]
dxgiFormat | CameraResources | [private]
framePending | CameraResources | [private]
HolographicCamera | CameraResources |
holographicCamera | CameraResources | [private]
IsDisposed | Disposer | [protected]
IsRenderingStereoscopic | CameraResources |
isStereo | CameraResources | [private]
ReleaseAllDeviceResources(DeviceResources deviceResources) | CameraResources | [inline]
ReleaseResourcesForBackBuffer(DeviceResources deviceResources) | CameraResources | [inline]
RemoveAndDispose< T >(ref T objectToDispose) | Disposer | [inline, protected]
RemoveToDispose< T >(T objectToRemove) | Disposer | [inline, protected]
RenderTargetSize | CameraResources |
ToDispose< T >(T objectToDispose) | Disposer | [inline, protected]
UpdateViewProjectionBuffer(DeviceResources deviceResources, HolographicCameraPose cameraPose, SpatialCoordinateSystem coordinateSystem) | CameraResources | [inline]
Viewport | CameraResources |
viewProjectionConstantBuffer | CameraResources | [private]
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSegmentation/cpp/Scenario1_ExtractTextSegments.xaml.cpp Source File

  • TextSegmentation
  • cpp

Scenario1_ExtractTextSegments.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario1_ExtractTextSegments.xaml.h"
00005 #include "MainPage.xaml.h"
00006
00007 using namespace Platform;
00008
00009 using namespace SDKTemplate;
00010
00011 using namespace Windows::UI::Xaml;
00012 using namespace Windows::UI::Xaml::Controls;
00013
00014
00015 Scenario1_ExtractTextSegments::Scenario1_ExtractTextSegments()
00016 {
00017     InitializeComponent();
00018 }
00019
00020 /// <summary>
00021 /// This is the click handler for the 'Word Segments' button.
00022 ///
00023 /// When this button is activated, the Text Segmentation API will calculate
00024 /// the word segments from the given input string and language tag, and then
00025 /// print out the word and alternate-form segments for that language.
00026 ///
00027 /// </summary>
00028 /// <param name="sender">The object that raised the event.</param>
00029 /// <param name="e">Event data that describes the click action on the button.</param>
00030 void Scenario1_ExtractTextSegments::WordSegmentsButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00031 {
00032     Button^ b = dynamic_cast<Button^>(sender);
00033     if (b != nullptr)
00034     {
00035         // Initialize and obtain input values
00036         String^ notifyText = ref new String();
00037
00038         // Obtain the input string value, check for non-emptiness
00039         String^ inputStringText = inputStringBox->Text;
00040         if (inputStringText->IsEmpty())
00041         {
00042             notifyText = "\nCannot compute word segments: input string is empty.";
00043             MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00044             return;
00045         }
00046
00047         // Obtain the language tag value, check for non-emptiness and that it is valid
00048         // Ex. Valid Values:
00049         //     "en-US" (English (United States))
00050         //     "fr-FR" (French (France))
00051         //     "de-DE" (German (Germany))
00052         //     "ja-JP" (Japanese (Japan))
00053         //     "ar-SA" (Arabic (Saudi Arabia))
00054         //     "zh-CN" (China (PRC))
00055         String^ languageTagText = languageTagBox->Text;
00056         if (languageTagText->IsEmpty())
00057         {
00058             notifyText += "\nLanguage tag input is empty ... using generic-language segmentation rules.";
00059             languageTagText = "und";    // This is used for non language-specific locales. 'und' is short for 'undetermined'.
00060         }
00061         else
00062         {
00063             if (!Windows::Globalization::Language::IsWellFormed(languageTagText))
00064             {
00065                 notifyText = "\nLanguage tag is not well formed: \"" + languageTagText + "\"";
00066                 MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00067                 return;
00068             }
00069         }
00070
00071         // Notify that we are going to calculate word segments
00072         notifyText += "\n\nCalculating word segments ...\n";
00073         notifyText += "\nInput: \"" + inputStringText + "\"";
00074         notifyText += "\nLanguage Tag: \"" + languageTagText + "\"";
00075
00076         // Call the TextSegmentation API to calculate the word boundaries, add them to a StringBuilder instance
00077         auto segmenter = ref new Windows::Data::Text::WordsSegmenter(languageTagText);
00078         auto wordSegments = segmenter->GetTokens(inputStringText);
00079
00080         // Iterate over the word segments, add words and alternates to notifyText
00081         for (unsigned int iWordSegment = 0; iWordSegment != wordSegments->Size; iWordSegment++)
00082         {
00083             auto wordSegment = wordSegments->GetAt(iWordSegment);
00084             notifyText += "\n\tWord---->\"" + wordSegment->Text + "\"";
00085
00086             auto alternateForms = wordSegment->AlternateForms;
00087             for (unsigned int iAlternateForm = 0; iAlternateForm != alternateForms->Size; iAlternateForm++)
00088             {
00089                 auto alternateForm = alternateForms->GetAt(iAlternateForm);
00090                 notifyText += "\n\t\tAlternate---->\"" + alternateForm->AlternateText + "\"";
00091             }
00092         }
00093
00094         // send notifyText to the output pane
00095         MainPage::Current->NotifyUser(notifyText, NotifyType::StatusMessage);
00096     }
00097 }
00098
00099 /// <summary>
00100 /// This is the click handler for the 'Selection Segments' button.
00101 ///
00102 /// When this button is activated, the Text Segmentation API will calculate
00103 /// the selection segments from the given input string and language tag, and then
00104 /// print out the word and alternate-form segments for that language.
00105 ///
00106 /// Selection segments differ from word segments in that they describe the bounds
00107 /// between active-selection snapping behavior.
00108 ///
00109 /// </summary>
00110 /// <param name="sender">The object that raised the event.</param>
00111 /// <param name="e">Event data that describes the click action on the button.</param>
00112 void Scenario1_ExtractTextSegments::SelectionSegmentsButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00113 {
00114     Button^ b = dynamic_cast<Button^>(sender);
00115     if (b != nullptr)
00116     {
00117         // Initialize and obtain input values
00118         String^ notifyText = ref new String();
00119
00120         // Obtain the input string value, check for non-emptiness
00121         String^ inputStringText = inputStringBox->Text;
00122         if (inputStringText->IsEmpty())
00123         {
00124             notifyText = "\nCannot compute selection segments: input string is empty.";
00125             MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00126             return;
00127         }
00128
00129         // Obtain the language tag value, check for non-emptiness and that it is valid
00130         // Ex. Valid Values:
00131         //     "en-US" (English (United States))
00132         //     "fr-FR" (French (France))
00133         //     "de-DE" (German (Germany))
00134         //     "ja-JP" (Japanese (Japan))
00135         //     "ar-SA" (Arabic (Saudi Arabia))
00136         //     "zh-CN" (China (PRC))
00137         String^ languageTagText = languageTagBox->Text;
00138         if (languageTagText->IsEmpty())
00139         {
00140             notifyText += "\nLanguage tag input is empty ... using generic-language segmentation rules.";
00141             languageTagText = "und";    // This is used for non language-specific locales. 'und' is short for 'undetermined'.
00142         }
00143         else
00144         {
00145             if (!Windows::Globalization::Language::IsWellFormed(languageTagText))
00146             {
00147                 notifyText = "\nLanguage tag is not well formed: \"" + languageTagText + "\"";
00148                 MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00149                 return;
00150             }
00151         }
00152
00153         // Notify that we are going to calculate selection segments
00154         notifyText += "\n\nCalculating selection segments ...\n";
00155         notifyText += "\nInput: \"" + inputStringText + "\"";
00156         notifyText += "\nLanguage Tag: \"" + languageTagText + "\"";
00157
00158         // Call the TextSegmentation API to calculate the word boundaries, add them to a StringBuilder instance
00159         auto segmenter = ref new Windows::Data::Text::SelectableWordsSegmenter(languageTagText);
00160         auto selectionSegments = segmenter->GetTokens(inputStringText);
00161
00162         // Iterate over the selection segments, add segments to notifyText
00163         for (unsigned int iSelectionSegment = 0; iSelectionSegment != selectionSegments->Size; iSelectionSegment++)
00164         {
00165             auto selectionSegment = selectionSegments->GetAt(iSelectionSegment);
00166             notifyText += "\n\tWord---->\"" + selectionSegment->Text + "\"";
00167         }
00168
00169         // send notifyText to the output pane
00170         MainPage::Current->NotifyUser(notifyText, NotifyType::StatusMessage);
00171     }
00172 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SceneComposer::InkObject Member List

This is the complete list of members for SceneComposer::InkObject, including all inherited members.
_highlighterStroke | SceneComposer::InkObject | [private]
_stroke | SceneComposer::InkObject | [private]
GetDefaultStrokeSize() | SceneComposer::InkObject | [inline, static]
GetInkStroke() | SceneComposer::InkObject | [inline]
GetSelectedStrokeSize() | SceneComposer::InkObject | [inline, static]
getStrokes() | SceneComposer::InkObject | [inline]
getType() | SceneComposer::InkObject | [inline, virtual]
InkObject(Windows::UI::Input::Inking::InkStroke^s) | SceneComposer::InkObject | [inline]
IsStrokeSelected() | SceneComposer::InkObject | [inline]
SelectStroke(Windows::UI::Input::Inking::InkStrokeContainer^strokeContainerForTemp) | SceneComposer::InkObject | [inline]
Generated on Fri Nov 15 2024 22:24:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ReactiveViewModel Member List

This is the complete list of members for ReactiveViewModel, including all inherited members.
CmdPlayMovie | ReactiveViewModel |
CmdStopMovie | ReactiveViewModel |
licenseURL | ReactiveViewModel | [private]
Log(string message) | ViewModelBase | [inline, static]
MinConfig(MediaElement mediaElement) | ReactiveViewModel | [inline]
moviePath | ReactiveViewModel | [private]
MoviePath | ReactiveViewModel |
OutputLog | ViewModelBase |
PlaybackEnabled | ViewModelBase |
PlayReadyInfo | ReactiveViewModel |
ProcessServiceRequest(IMediaProtectionServiceRequest serviceRequest) | ReactiveViewModel | [inline, private]
PropertyChanged | ViewModelBase |
ProtectionManager | ViewModelBase |
RaisePropertyChanged([CallerMemberName] string propertyName="") | ViewModelBase | [inline, protected]
ReactiveViewModel(MediaElement mediaElement) | ReactiveViewModel | [inline]
serviceCompletionNotifier | ReactiveViewModel | [private]
ServiceRequested(MediaProtectionManager sender, ServiceRequestedEventArgs srEvent) | ReactiveViewModel | [inline, private]
SetPlaybackEnabled(bool enabled) | ViewModelBase | [inline]
Generated on Fri Nov 15 2024 22:24:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/Content/Tool.h Source File

  • SpatialInteractionSource
  • cpp
  • Content

Tool.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "Common\DeviceResources.h"
00004 #include "ShaderStructures.h"
00005 #include "RenderingInterfaces.h"
00006
00007 namespace HolographicPaint
00008 {
00009
00010     // Base drawing object
00011     class Tool : public IBaseRenderedObject
00012     {
00013     public:
00014         Tool(Windows::UI::Color color, float diameter);
00015
00016         void SetPosition(Windows::Foundation::Numerics::float3 position);
00017         void SetOrientation(Windows::Foundation::Numerics::quaternion orientation);
00018
00019         Windows::UI::Color GetColor() const { return m_color; }
00020         float GetDiameter() const { return m_diameter; }
00021
00022         // IBaseRenderedObject
00023         virtual void Update(ID3D11DeviceContext* pDeviceContext) override;
00024         virtual void Render(ID3D11DeviceContext* pDeviceContext, IRenderer* pRenderingHelper) override;
00025
00026     protected:
00027         float m_diameter;
00028         Windows::UI::Color m_color;
00029         Windows::Foundation::Numerics::float3 m_position;
00030         Windows::Foundation::Numerics::quaternion m_orientation;
00031
00032         bool m_refreshModelConstantBufferData = true;
00033         ModelConstantBuffer m_modelConstantBufferData;
00034     };
00035
00036     // Known tool represented by a cross inside a square and allowing the user to clear the current drawing
00037     class ClearTool : public Tool
00038     {
00039     public:
00040         ClearTool(Windows::UI::Color color, float diameter);
00041
00042         // IBaseRenderedObject
00043         virtual void Update(ID3D11DeviceContext* pDeviceContext) override;
00044         virtual void Render(ID3D11DeviceContext* pDeviceContext, IRenderer* pRenderingHelper) override;
00045
00046     protected:
00047         Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexBuffer;
00048         Microsoft::WRL::ComPtr<ID3D11Buffer> m_indexBuffer;
00049         uint32 m_indexCount = 0;
00050         bool m_resetBuffers = true;
00051     };
00052 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_ChatClient Member List

This is the complete list of members for Scenario1_ChatClient, including all inherited members.
App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) | Scenario1_ChatClient | [inline, private]
bluetoothDevice | Scenario1_ChatClient | [private]
chatService | Scenario1_ChatClient | [private]
chatSocket | Scenario1_ChatClient | [private]
chatWriter | Scenario1_ChatClient | [private]
ConnectButton_Click(object sender, RoutedEventArgs e) | Scenario1_ChatClient | [inline, private]
deviceWatcher | Scenario1_ChatClient | [private]
Disconnect(string disconnectReason) | Scenario1_ChatClient | [inline, private]
DisconnectButton_Click(object sender, RoutedEventArgs e) | Scenario1_ChatClient | [inline, private]
KeyboardKey_Pressed(object sender, KeyRoutedEventArgs e) | Scenario1_ChatClient | [inline]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_ChatClient | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_ChatClient | [inline, protected]
ReceiveStringLoop(DataReader chatReader) | Scenario1_ChatClient | [inline, private]
RequestAccessButton_Click(object sender, RoutedEventArgs e) | Scenario1_ChatClient | [inline, private]
ResetMainUI() | Scenario1_ChatClient | [inline, private]
ResultCollection | Scenario1_ChatClient |
ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario1_ChatClient | [inline, private]
rootPage | Scenario1_ChatClient | [private]
RunButton_Click(object sender, RoutedEventArgs e) | Scenario1_ChatClient | [inline, private]
Scenario1_ChatClient() | Scenario1_ChatClient | [inline]
SendButton_Click(object sender, RoutedEventArgs e) | Scenario1_ChatClient | [inline, private]
SendMessage() | Scenario1_ChatClient | [inline, private]
SetChatUI(string serviceName, string deviceName) | Scenario1_ChatClient | [inline, private]
SetDeviceWatcherUI() | Scenario1_ChatClient | [inline, private]
StartUnpairedDeviceWatcher() | Scenario1_ChatClient | [inline, private]
StopWatcher() | Scenario1_ChatClient | [inline, private]
UpdatePairingButtons() | Scenario1_ChatClient | [inline, private]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PasswordVault/cpp/pch.h Source File

  • PasswordVault
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/Common/PersistentState.cpp Source File

  • Simple3DGameXaml
  • cpp
  • Common

PersistentState.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "PersistentState.h"
00010 #include "DirectXSample.h"
00011
00012 using namespace Microsoft::WRL;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::Foundation::Collections;
00015 using namespace Windows::Storage;
00016 using namespace DirectX;
00017
00018 void PersistentState::Initialize(
00019     _In_ IPropertySet^ settingsValues,
00020     _In_ Platform::String^ key
00021     )
00022 {
00023     m_settingsValues = settingsValues;
00024     m_keyName = key;
00025 }
00026
00027 void PersistentState::SaveBool(Platform::String^ key, bool value)
00028 {
00029     Platform::String^ fullKey = Platform::String::Concat(m_keyName, key);
00030     if (m_settingsValues->HasKey(fullKey))
00031     {
00032         m_settingsValues->Remove(fullKey);
00033     }
00034     m_settingsValues->Insert(fullKey, PropertyValue::CreateInt32(value ? 1 : 0));
00035 }
00036
00037 void PersistentState::SaveInt32(Platform::String^ key, int value)
00038 {
00039     Platform::String^ fullKey = Platform::String::Concat(m_keyName, key);
00040     if (m_settingsValues->HasKey(fullKey))
00041     {
00042         m_settingsValues->Remove(fullKey);
00043     }
00044     m_settingsValues->Insert(fullKey, PropertyValue::CreateInt32(value));
00045 }
00046
00047 void PersistentState::SaveSingle(Platform::String^ key, float value)
00048 {
00049     Platform::String^ fullKey = Platform::String::Concat(m_keyName, key);
00050     if (m_settingsValues->HasKey(fullKey))
00051     {
00052         m_settingsValues->Remove(fullKey);
00053     }
00054     m_settingsValues->Insert(fullKey, PropertyValue::CreateSingle(value));
00055 }
00056
00057 void PersistentState::SaveXMFLOAT3(Platform::String^ key, DirectX::XMFLOAT3 value)
00058 {
00059     Platform::String^ fullKey = Platform::String::Concat(m_keyName, key);
00060     if (m_settingsValues->HasKey(fullKey))
00061     {
00062         m_settingsValues->Remove(fullKey);
00063     }
00064     Platform::Array<float>^ array3 = ref new Platform::Array<float>(3);
00065     array3[0] = value.x;
00066     array3[1] = value.y;
00067     array3[2] = value.z;
00068     m_settingsValues->Insert(fullKey, PropertyValue::CreateSingleArray(array3));
00069 }
00070
00071 void PersistentState::SaveString(Platform::String^ key, Platform::String^ string)
00072 {
00073     Platform::String^ fullKey = Platform::String::Concat(m_keyName, key);
00074     if (m_settingsValues->HasKey(fullKey))
00075     {
00076         m_settingsValues->Remove(fullKey);
00077     }
00078     m_settingsValues->Insert(fullKey, PropertyValue::CreateString(string));
00079 }
00080
00081 bool PersistentState::LoadBool(Platform::String^ key, bool defaultValue)
00082 {
00083     Platform::String^ fullKey = Platform::String::Concat(m_keyName, key);
00084     if (m_settingsValues->HasKey(fullKey))
00085     {
00086         int state = safe_cast<IPropertyValue^>(m_settingsValues->Lookup(fullKey))->GetInt32();
00087         return state ? true : false;
00088     }
00089     return defaultValue;
00090 }
00091
00092 int PersistentState::LoadInt32(Platform::String^ key, int defaultValue)
00093 {
00094     Platform::String^ fullKey = Platform::String::Concat(m_keyName, key);
00095     if (m_settingsValues->HasKey(fullKey))
00096     {
00097         return safe_cast<IPropertyValue^>(m_settingsValues->Lookup(fullKey))->GetInt32();
00098     }
00099     return defaultValue;
00100 }
00101
00102 float PersistentState::LoadSingle(Platform::String^ key, float defaultValue)
00103 {
00104     Platform::String^ fullKey = Platform::String::Concat(m_keyName, key);
00105     if (m_settingsValues->HasKey(fullKey))
00106     {
00107         return safe_cast<IPropertyValue^>(m_settingsValues->Lookup(fullKey))->GetSingle();
00108     }
00109     return defaultValue;
00110 }
00111
00112 XMFLOAT3 PersistentState::LoadXMFLOAT3(Platform::String^ key, DirectX::XMFLOAT3 defaultValue)
00113 {
00114     XMFLOAT3 value;
00115     Platform::String^ fullKey = Platform::String::Concat(m_keyName, key);
00116     if (m_settingsValues->HasKey(fullKey))
00117     {
00118         Platform::Array<float>^ array3;
00119         safe_cast<IPropertyValue^>(m_settingsValues->Lookup(fullKey))->GetSingleArray(&array3);
00120         value.x = array3[0];
00121         value.y = array3[1];
00122         value.z = array3[2];
00123         return value;
00124     }
00125     return defaultValue;
00126 }
00127
00128 Platform::String^ PersistentState::LoadString(Platform::String^ key, Platform::String^ defaultValue)
00129 {
00130     Platform::String^ fullKey = Platform::String::Concat(m_keyName, key);
00131     if (m_settingsValues->HasKey(fullKey))
00132     {
00133         return safe_cast<IPropertyValue^>(m_settingsValues->Lookup(fullKey))->GetString();
00134     }
00135     return defaultValue;
00136 }
Generated on Fri Nov 15 2024 22:21:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PlaybackPage Member List

This is the complete list of members for PlaybackPage, including all inherited members.
activeGamePad | PlaybackPage | [private]
centerX | PlaybackPage | [private]
centerY | PlaybackPage | [private]
heading | PlaybackPage | [private]
IsMediaAlreadyOpened() | PlaybackPage | [inline, private]
isPointerPress | PlaybackPage | [private]
m_inputLoopWorker | PlaybackPage | [private]
mediaPlayer | PlaybackPage | [private]
MediaPlayer_MediaOpened(MediaPlayer sender, object args) | PlaybackPage | [inline, private]
mouseWheelData | PlaybackPage | [private]
mtcGrid | PlaybackPage | [private]
OnKeyDown(CoreWindow sender, KeyEventArgs args) | PlaybackPage | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | PlaybackPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | PlaybackPage | [inline, protected]
OnPointerMoved(object sender, PointerRoutedEventArgs e) | PlaybackPage | [inline, private]
OnPointerPressed(object sender, PointerRoutedEventArgs e) | PlaybackPage | [inline, private]
OnPointerReleased(object sender, PointerRoutedEventArgs e) | PlaybackPage | [inline, private]
OnPointerWheelChanged(object sender, PointerRoutedEventArgs e) | PlaybackPage | [inline, private]
pitch | PlaybackPage | [private]
PlaybackPage() | PlaybackPage | [inline]
PlaybackPage_LayoutUpdated(object sender, object e) | PlaybackPage | [inline, private]
PlaybackSession_PlaybackStateChanged(MediaPlaybackSession sender, object args) | PlaybackPage | [inline, private]
ResetState() | PlaybackPage | [inline, private]
rotationdelta | PlaybackPage | [private]
scrollStep | PlaybackPage | [private]
StartInputLoop() | PlaybackPage | [inline, private]
THUMBSTICK_DEADZONE | PlaybackPage | [private]
timer | PlaybackPage | [private]
videoProjection | PlaybackPage | [private]
workItemHandler | PlaybackPage | [private]
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/BasicReaderWriter.h Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

BasicReaderWriter.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <ppltasks.h>
00015
00016 // A simple reader/writer class that provides support for reading and writing
00017 // files on disk. Provides synchronous and asynchronous methods.
00018 ref class BasicReaderWriter
00019 {
00020 private:
00021     Windows::Storage::StorageFolder^ m_location;
00022
00023 internal:
00024     BasicReaderWriter();
00025     BasicReaderWriter(
00026         _In_ Windows::Storage::StorageFolder^ folder
00027         );
00028
00029     Platform::Array<byte>^ ReadData(
00030         _In_ Platform::String^ filename
00031         );
00032
00033     concurrency::task<Platform::Array<byte>^> ReadDataAsync(
00034         _In_ Platform::String^ filename
00035         );
00036
00037     uint32 WriteData(
00038         _In_ Platform::String^ filename,
00039         _In_ const Platform::Array<byte>^ fileData
00040         );
00041
00042     concurrency::task<void> WriteDataAsync(
00043         _In_ Platform::String^ filename,
00044         _In_ const Platform::Array<byte>^ fileData
00045         );
00046 };
Generated on Fri Nov 15 2024 22:19:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Content/NV12VideoTexture.cpp Source File

  • HolographicFaceTracking
  • cpp
  • Content

NV12VideoTexture.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "NV12VideoTexture.h"
00014 #include "Common\DirectXHelper.h"
00015
00016 #include <MemoryBuffer.h> // IMemoryBufferByteAccess
00017
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Graphics::Imaging;
00020
00021 using namespace Microsoft::WRL;
00022 using namespace Microsoft::WRL::Wrappers;
00023
00024 using namespace HolographicFaceTracker;
00025
00026 NV12VideoTexture::NV12VideoTexture(std::shared_ptr<DX::DeviceResources> deviceResources, uint32_t width, uint32_t height)
00027     : DX::Resource(std::move(deviceResources))
00028     , m_width(width)
00029     , m_height(height)
00030 {
00031 }
00032
00033 // Opens up the underlying buffer of a SoftwareBitmap and copies to our D3D11 Texture
00034 void NV12VideoTexture::CopyFromVideoMediaFrame(Windows::Media::Capture::Frames::VideoMediaFrame^ source)
00035 {
00036     SoftwareBitmap^ softwareBitmap = source->SoftwareBitmap;
00037
00038     if (softwareBitmap == nullptr)
00039     {
00040         OutputDebugString(L"SoftwareBitmap was null\r\n");
00041         return;
00042     }
00043
00044     if (softwareBitmap->BitmapPixelFormat != BitmapPixelFormat::Nv12)
00045     {
00046         OutputDebugString(L"BitmapPixelFormat was not NV12\r\n");
00047         return;
00048     }
00049
00050     BitmapBuffer^ bitmapBuffer = softwareBitmap->LockBuffer(BitmapBufferAccessMode::Read);
00051     IMemoryBufferReference^ bufferRef = bitmapBuffer->CreateReference();
00052
00053     ComPtr<IMemoryBufferByteAccess> memoryBufferByteAccess;
00054     if (SUCCEEDED(reinterpret_cast<IInspectable*>(bufferRef)->QueryInterface(IID_PPV_ARGS(&memoryBufferByteAccess))))
00055     {
00056         BYTE* pSourceBuffer = nullptr;
00057         UINT32 sourceCapacity = 0;
00058         if (SUCCEEDED(memoryBufferByteAccess->GetBuffer(&pSourceBuffer, &sourceCapacity)) && pSourceBuffer)
00059         {
00060             auto const context = m_deviceResources->GetD3DDeviceContext();
00061
00062             // Copy the new video frame over.
00063             D3D11_MAPPED_SUBRESOURCE subResource;
00064             if (SUCCEEDED(context->Map(m_texture.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &subResource)))
00065             {
00066                 std::memcpy(subResource.pData, pSourceBuffer, sourceCapacity);
00067                 context->Unmap(m_texture.Get(), 0);
00068             }
00069         }
00070     }
00071 }
00072
00073 concurrency::task<void> NV12VideoTexture::CreateDeviceDependentResourcesAsync()
00074 {
00075     return concurrency::create_task([this]
00076     {
00077         D3D11_TEXTURE2D_DESC const texDesc = CD3D11_TEXTURE2D_DESC(
00078             DXGI_FORMAT_NV12,           // HoloLens PV camera format, common for video sources
00079             m_width,                    // Width of the video frames
00080             m_height,                   // Height of the video frames
00081             1,                          // Number of textures in the array
00082             1,                          // Number of miplevels in each texture
00083             D3D11_BIND_SHADER_RESOURCE, // We read from this texture in the shader
00084             D3D11_USAGE_DYNAMIC,        // Because we'll be copying from CPU memory
00085             D3D11_CPU_ACCESS_WRITE      // We only need to write into the texture
00086         );
00087
00088         DX::ThrowIfFailed(
00089             m_deviceResources->GetD3DDevice()->CreateTexture2D(
00090                 &texDesc,
00091                 nullptr,
00092                 &m_texture
00093             )
00094         );
00095
00096         // https://msdn.microsoft.com/en-us/library/windows/desktop/bb173059(v=vs.85).aspx
00097         // To access DXGI_FORMAT_NV12 in the shader, we need to map the luminance channel and the chrominance channels
00098         // into a format that shaders can understand.
00099         // In the case of NV12, DirectX understands how the texture is laid out, so we can create these
00100         // shader resource views which represent the two channels of the NV12 texture.
00101         // Then inside the shader we convert YUV into RGB so we can render.
00102
00103         // DirectX specifies the view format to be DXGI_FORMAT_R8_UNORM for NV12 luminance channel.
00104         // Luminance is 8 bits per pixel. DirectX will handle converting 8-bit integers into normalized
00105         // floats for use in the shader.
00106         D3D11_SHADER_RESOURCE_VIEW_DESC const luminancePlaneDesc = CD3D11_SHADER_RESOURCE_VIEW_DESC(
00107             m_texture.Get(),
00108             D3D11_SRV_DIMENSION_TEXTURE2D,
00109             DXGI_FORMAT_R8_UNORM
00110         );
00111
00112         DX::ThrowIfFailed(
00113             m_deviceResources->GetD3DDevice()->CreateShaderResourceView(
00114                 m_texture.Get(),
00115                 &luminancePlaneDesc,
00116                 &m_luminanceView
00117             )
00118         );
00119
00120         // DirectX specifies the view format to be DXGI_FORMAT_R8G8_UNORM for NV12 chrominance channel.
00121         // Chrominance has 8 bits for U and 8 bits for V per sample (1 sample per 2x2 block of pixels).
00122         //  DirectX will handle converting 8-bit integers into normalized floats for use in the shader.
00123         D3D11_SHADER_RESOURCE_VIEW_DESC const chrominancePlaneDesc = CD3D11_SHADER_RESOURCE_VIEW_DESC(
00124             m_texture.Get(),
00125             D3D11_SRV_DIMENSION_TEXTURE2D,
00126             DXGI_FORMAT_R8G8_UNORM
00127         );
00128
00129         DX::ThrowIfFailed(
00130             m_deviceResources->GetD3DDevice()->CreateShaderResourceView(
00131                 m_texture.Get(),
00132                 &chrominancePlaneDesc,
00133                 &m_chrominanceView
00134             )
00135         );
00136     });
00137 }
00138
00139 void NV12VideoTexture::ReleaseDeviceDependentResources()
00140 {
00141     m_chrominanceView.Reset();
00142     m_luminanceView.Reset();
00143     m_texture.Reset();
00144 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cpp/Common/BaseElement.h Source File

  • 360VideoPlayback
  • cpp
  • Common

BaseElement.h

Go to the documentation of this file.
00001 #pragma once
00002 #include "StepTimer.h"
00003 #include "DeviceResources.h"
00004
00005 #define FONT_SIZE 10.667f
00006 #define BUTTON_SIZE 64
00007
00008 namespace DX
00009 {
00010     // Margin in terms of left, top, right, bottom.
00011     // "Pushes" the element away from its sibling elements and away from boundaries of its parent container.
00012     // Does not change the intristic size of the element; the parent element will take the margin of its child elements into consideration during arrangement.
00013     struct ElementMargin
00014     {
00015         ElementMargin() = default;
00016
00017         ElementMargin(float l, float t, float r, float b) :
00018             left(l),
00019             top(t),
00020             right(r),
00021             bottom(b)
00022         {
00023             _ASSERTE(left >= 0.0f);
00024             _ASSERTE(top >= 0.0f);
00025             _ASSERTE(right >= 0.0f);
00026             _ASSERTE(bottom >= 0.0f);
00027         }
00028
00029         float left = 0.0f;
00030         float top = 0.0f;
00031         float right = 0.0f;
00032         float bottom = 0.0f;
00033     };
00034
00035     class BaseElement
00036     {
00037     public:
00038         BaseElement();
00039         virtual ~BaseElement() = default;
00040         virtual void Initialize();
00041         virtual void Update(const DX::StepTimer& timer, Windows::UI::Input::Spatial::SpatialPointerPose^ cameraPose);
00042         void TryRender();
00043         void SetIsVisible(bool visible);
00044         bool GetIsVisible() { return m_isVisible; };
00045         void SetElementSize(Windows::Foundation::Numerics::float2 size) { m_elementSize = size; }
00046         bool GetIsRenderPassNeeded() { return m_isRenderPassNeeded; };
00047         Windows::Foundation::Numerics::float2 GetElementSize() { return m_elementSize; };
00048         // NOTE: This translation is the translation of the 2D BaseElement from the texture's origin
00049         virtual void SetTranslation(Windows::Foundation::Numerics::float2 translation);
00050         void SetParentTransform(Windows::Foundation::Numerics::float2 translation);
00051         void AddChildElement(const std::shared_ptr<BaseElement>& childElement);
00052         void SetElementMargin(ElementMargin margin) { m_elementMargin = margin; };
00053         void SetIgnoreLayout(bool ignoreLayout) { m_ignoreLayout = ignoreLayout; }
00054         ElementMargin& GetElementMargin() { return m_elementMargin; };
00055         bool GetIgnoreLayout() { return m_ignoreLayout; };
00056         void SetLayoutHorizontal(bool isLayoutHorizontal) { m_isLayoutHorizontal = isLayoutHorizontal; }
00057         void SetBrush(ID2D1SolidColorBrush* brush);
00058         // Applies layout properties down the element tree.
00059         // ArrangeElements must be manually called any time:
00060         // - The element's layout properties have changed (layout direction, content alignment, etc.)
00061         // - Any child's layout properties are updated.
00062         // - Children elements are added or removed.
00063         virtual void ArrangeElements();
00064
00065     protected:
00066         virtual void Render();
00067
00068         bool m_isInitialized;
00069         bool m_transformRecalculationNeeded;
00070         bool m_isRenderPassNeeded;
00071         bool m_isVisible;
00072         bool m_ignoreLayout;
00073
00074         Windows::Foundation::Numerics::float2 m_translation;
00075         Windows::Foundation::Numerics::float2 m_transformedTranslation;
00076         Windows::Foundation::Numerics::float2 m_parentTranslation;
00077         // Width and height dimensions
00078         Windows::Foundation::Numerics::float2 m_elementSize;
00079         D2D1::Matrix3x2F m_transformMatrix = D2D1::Matrix3x2F::Identity();
00080         bool m_isLayoutHorizontal = false;
00081         ElementMargin m_elementMargin;
00082
00083         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00084         std::vector<std::shared_ptr<BaseElement>> m_childElements;
00085         Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> m_brush;
00086         // Cached pointer to device resources.
00087     };
00088
00089     // Manage focus across multiple Elements
00090     class FocusableElement : public BaseElement
00091     {
00092     public:
00093         FocusableElement();
00094         virtual ~FocusableElement() = default;
00095         virtual void Update(const DX::StepTimer& timer, Windows::UI::Input::Spatial::SpatialPointerPose^ cameraPose) override;
00096         virtual bool IsFocused() { return m_isFocused; };
00097         virtual void PerformAction() {};
00098         virtual void SetParentControlInformation(bool focused, Windows::Foundation::Numerics::float2 focusedPosition, UINT parentTextureWidth, UINT parentTextureHeight);
00099         virtual void FocusUpdate() {};
00100     protected:
00101         bool m_isFocused;
00102         bool m_isParentFocused;
00103         // If an Element needs to know where the intersection occurs relative to its coordinates, set m_isSubElementIntersectionInfoNeeded true
00104         // For example, the parentTexture might be 100x100 and your Element might be 50x50 centered on the texture and lets say the Focus is also the center of the texture.
00105         // For most Elements, simply knowing that the coordinate 50,50 is inside the Element and thus its focused. But, some Elements such as Sliders need to know
00106         // Where in its Element Coordinate system did the intersection occur (so you can adjust the seekbar). In this case, by turning this parameter on, it will store the
00107         // Element Coordinate Intersection into the below field. So sticking with the above example, it would store 25,25 since the Element is centered in the Parent Texture
00108         bool m_isFocusIntersectionCalculated;
00109         Windows::Foundation::Numerics::float2 m_elementCoordIntersectionPoint;
00110         UINT m_parentTextureWidth;
00111         UINT m_parentTextureHeight;
00112         Windows::Foundation::Numerics::float2 m_parentFocusedPosition;
00113     };
00114
00115     class Text : public BaseElement
00116     {
00117     public:
00118         Text(std::wstring text,
00119             FLOAT fontSize,
00120             DWRITE_FONT_WEIGHT fontWeight = DWRITE_FONT_WEIGHT_ULTRA_BOLD);
00121         void SetText(std::wstring text);
00122
00123     protected:
00124         virtual void Render() override;
00125
00126     private:
00127         void CreateTextContext();
00128         std::wstring m_text;
00129         Microsoft::WRL::ComPtr<IDWriteTextFormat> m_textFormat;
00130         Microsoft::WRL::ComPtr<IDWriteTextLayout> m_textLayout;
00131         DWRITE_FONT_WEIGHT m_fontWeight;
00132         float m_transformedFontSize;
00133     };
00134
00135     class Line : public BaseElement
00136     {
00137     public:
00138         Line(FLOAT strokeThickness);
00139         void SetStartPoint(D2D1_POINT_2F& point);
00140         void SetEndPoint(D2D1_POINT_2F& point);
00141
00142     protected:
00143         virtual void Render() override;
00144
00145     private:
00146         FLOAT m_strokeThickness;
00147         D2D1_POINT_2F m_lineStart;
00148         D2D1_POINT_2F m_lineEnd;
00149     };
00150
00151     class Ellipse : public BaseElement
00152     {
00153     public:
00154         Ellipse(FLOAT radiusX, FLOAT radiusY, FLOAT strokeThickness, D2D1::ColorF brushColor);
00155         virtual void Initialize() override;
00156         void SetRadius(FLOAT x, FLOAT y);
00157
00158     protected:
00159         virtual void Render() override;
00160
00161     private:
00162         D2D1::ColorF m_brushColor;
00163         FLOAT m_strokeThickness;
00164         FLOAT m_radiusX;
00165         FLOAT m_radiusY;
00166         D2D1_ELLIPSE m_ellipse;
00167     };
00168
00169     class FilledEllipse : public BaseElement
00170     {
00171     public:
00172         FilledEllipse(FLOAT radiusX, FLOAT radiusY, D2D1::ColorF brushColor);
00173         virtual void Initialize() override;
00174         void SetRadius(FLOAT x, FLOAT y);
00175
00176     protected:
00177         virtual void Render() override;
00178
00179     private:
00180         D2D1::ColorF m_brushColor;
00181         FLOAT m_radiusX;
00182         FLOAT m_radiusY;
00183         D2D1_ELLIPSE m_ellipse;
00184     };
00185
00186     class Rectangle : public BaseElement
00187     {
00188     public:
00189         Rectangle(FLOAT width, FLOAT height, FLOAT strokeThickness, D2D1::ColorF brushColor);
00190         virtual void Initialize() override;
00191         void SetRect(const D2D1_RECT_F& rect) { m_rect = rect; }
00192         FLOAT GetStrokeThickness() { return m_strokeThickness; };
00193
00194     protected:
00195         virtual void Render() override;
00196
00197     private:
00198         D2D1_RECT_F m_rect;
00199         FLOAT m_strokeThickness;
00200         D2D1::ColorF m_brushColor;
00201     };
00202
00203     class FilledRectangle : public BaseElement
00204     {
00205     public:
00206         FilledRectangle(FLOAT width, FLOAT height, D2D1::ColorF brushColor);
00207         virtual void Initialize() override;
00208         void SetRect(const D2D1_RECT_F& rect) { m_rect = rect; }
00209
00210     protected:
00211         virtual void Render() override;
00212
00213     private:
00214         D2D1_RECT_F m_rect;
00215         D2D1::ColorF m_brushColor;
00216     };
00217 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SerialArduino/cs/Scenario1_ConnectDisconnect.xaml.cs Source File

  • SerialArduino
  • cs

Scenario1_ConnectDisconnect.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016
00017 using System;
00018 using System.IO;
00019 using System.Collections.Generic;
00020 using System.Collections.ObjectModel;
00021
00022 using Windows.ApplicationModel;
00023 using Windows.Foundation;
00024
00025 using Windows.UI.Core;
00026
00027 using Windows.Devices.Enumeration;
00028 using Windows.Devices.SerialCommunication;
00029 using SerialArduino;
00030
00031 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00032
00033 namespace SerialArduino
00034 {
00035     /// <summary>
00036     /// Demonstrates how to connect to a Serial Device and respond to device disconnects, app suspending and resuming events.
00037     ///
00038     /// To use this sample with your device:
00039     /// 1) Include the device in the Package.appxmanifest. For instructions, see Package.appxmanifest documentation.
00040     /// 2) Create a DeviceWatcher object for your device. See the InitializeDeviceWatcher method in this sample.
00041     /// </summary>
00042     public sealed partial class Scenario1_ConnectDisconnect : Page
00043     {
00044         private const String ButtonNameDisconnectFromDevice = "Disconnect from device";
00045         private const String ButtonNameDisableReconnectToDevice = "Do not automatically reconnect to device that was just closed";
00046
00047         // Pointer back to the main page
00048         private MainPage rootPage = MainPage.Current;
00049
00050         private SuspendingEventHandler appSuspendEventHandler;
00051         private EventHandler<Object> appResumeEventHandler;
00052
00053         private ObservableCollection<DeviceListEntry> listOfDevices;
00054
00055         private Dictionary<DeviceWatcher, String> mapDeviceWatchersToDeviceSelector;
00056         private Boolean watchersSuspended;
00057         private Boolean watchersStarted;
00058
00059         // Has all the devices enumerated by the device watcher?
00060         private Boolean isAllDevicesEnumerated;
00061
00062         public Scenario1_ConnectDisconnect()
00063         {
00064             this.InitializeComponent();
00065
00066             listOfDevices = new ObservableCollection<DeviceListEntry>();
00067
00068             mapDeviceWatchersToDeviceSelector = new Dictionary<DeviceWatcher, String>();
00069             watchersStarted = false;
00070             watchersSuspended = false;
00071
00072             isAllDevicesEnumerated = false;
00073         }
00074
00075         /// <summary>
00076         /// Invoked when this page is about to be displayed in a Frame.
00077         ///
00078         /// Create the DeviceWatcher objects when the user navigates to this page so the UI list of devices is populated.
00079         /// </summary>
00080         /// <param name="eventArgs">Event data that describes how this page was reached.  The Parameter
00081         /// property is typically used to configure the page.</param>
00082         protected override void OnNavigatedTo(NavigationEventArgs eventArgs)
00083         {
00084             // If we are connected to the device or planning to reconnect, we should disable the list of devices
00085             // to prevent the user from opening a device without explicitly closing or disabling the auto reconnect
00086             if (EventHandlerForDevice.Current.IsDeviceConnected
00087                 || (EventHandlerForDevice.Current.IsEnabledAutoReconnect
00088                 && EventHandlerForDevice.Current.DeviceInformation != null))
00089             {
00090                 UpdateConnectDisconnectButtonsAndList(false);
00091
00092                 // These notifications will occur if we are waiting to reconnect to device when we start the page
00093                 EventHandlerForDevice.Current.OnDeviceConnected = this.OnDeviceConnected;
00094                 EventHandlerForDevice.Current.OnDeviceClose = this.OnDeviceClosing;
00095             }
00096             else
00097             {
00098                 UpdateConnectDisconnectButtonsAndList(true);
00099             }
00100
00101             // Begin watching out for events
00102             StartHandlingAppEvents();
00103
00104             // Initialize the desired device watchers so that we can watch for when devices are connected/removed
00105             InitializeDeviceWatchers();
00106             StartDeviceWatchers();
00107
00108             DeviceListSource.Source = listOfDevices;
00109         }
00110
00111         /// <summary>
00112         /// Unregister from App events and DeviceWatcher events because this page will be unloaded.
00113         /// </summary>
00114         /// <param name="eventArgs"></param>
00115         protected override void OnNavigatedFrom(NavigationEventArgs eventArgs)
00116         {
00117             StopDeviceWatchers();
00118             StopHandlingAppEvents();
00119
00120             // We no longer care about the device being connected
00121             EventHandlerForDevice.Current.OnDeviceConnected = null;
00122             EventHandlerForDevice.Current.OnDeviceClose = null;
00123         }
00124
00125         private async void ConnectToDevice_Click(Object sender, RoutedEventArgs eventArgs)
00126         {
00127             var selection = ConnectDevices.SelectedItems;
00128             DeviceListEntry entry = null;
00129
00130             if (selection.Count > 0)
00131             {
00132                 var obj = selection[0];
00133                 entry = (DeviceListEntry)obj;
00134
00135                 if (entry != null)
00136                 {
00137                     // Create an EventHandlerForDevice to watch for the device we are connecting to
00138                     EventHandlerForDevice.CreateNewEventHandlerForDevice();
00139
00140                     // Get notified when the device was successfully connected to or about to be closed
00141                     EventHandlerForDevice.Current.OnDeviceConnected = this.OnDeviceConnected;
00142                     EventHandlerForDevice.Current.OnDeviceClose = this.OnDeviceClosing;
00143
00144                     // It is important that the FromIdAsync call is made on the UI thread because the consent prompt, when present,
00145                     // can only be displayed on the UI thread. Since this method is invoked by the UI, we are already in the UI thread.
00146                     Boolean openSuccess = await EventHandlerForDevice.Current.OpenDeviceAsync(entry.DeviceInformation, entry.DeviceSelector);
00147
00148                     // Disable connect button if we connected to the device
00149                     UpdateConnectDisconnectButtonsAndList(!openSuccess);
00150                 }
00151             }
00152         }
00153
00154         private void DisconnectFromDevice_Click(Object sender, RoutedEventArgs eventArgs)
00155         {
00156             var selection = ConnectDevices.SelectedItems;
00157             DeviceListEntry entry = null;
00158
00159             // Prevent auto reconnect because we are voluntarily closing it
00160             // Re-enable the ConnectDevice list and ConnectToDevice button if the connected/opened device was removed.
00161             EventHandlerForDevice.Current.IsEnabledAutoReconnect = false;
00162
00163             if (selection.Count > 0)
00164             {
00165                 var obj = selection[0];
00166                 entry = (DeviceListEntry)obj;
00167
00168                 if (entry != null)
00169                 {
00170                     EventHandlerForDevice.Current.CloseDevice();
00171                 }
00172             }
00173
00174             UpdateConnectDisconnectButtonsAndList(true);
00175         }
00176
00177         /// <summary>
00178         /// Initialize device watchers to look for the Serial Arduino device
00179         ///
00180         /// GetDeviceSelector return an AQS string that can be passed directly into DeviceWatcher.createWatcher() or  DeviceInformation.createFromIdAsync().
00181         ///
00182         /// In this sample, a DeviceWatcher will be used to watch for devices because we can detect surprise device removals.
00183         /// </summary>
00184         private void InitializeDeviceWatchers()
00185         {
00186             string deviceSelector = Windows.Devices.SerialCommunication.SerialDevice.GetDeviceSelectorFromUsbVidPid(
00187                                                                     ArduinoDevice.Vid, ArduinoDevice.Pid);
00188
00189             // Create a device watcher to look for instances of the Serial Device that match the device selector
00190             // used earlier.
00191
00192             var deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector);
00193
00194             // Allow the EventHandlerForDevice to handle device watcher events that relates or effects our device (i.e. device removal, addition, app suspension/resume)
00195             AddDeviceWatcher(deviceWatcher, deviceSelector);
00196         }
00197
00198         private void StartHandlingAppEvents()
00199         {
00200             appSuspendEventHandler = new SuspendingEventHandler(this.OnAppSuspension);
00201             appResumeEventHandler = new EventHandler<Object>(this.OnAppResume);
00202
00203             // This event is raised when the app is exited and when the app is suspended
00204             App.Current.Suspending += appSuspendEventHandler;
00205
00206             App.Current.Resuming += appResumeEventHandler;
00207         }
00208
00209         private void StopHandlingAppEvents()
00210         {
00211             // This event is raised when the app is exited and when the app is suspended
00212             App.Current.Suspending -= appSuspendEventHandler;
00213
00214             App.Current.Resuming -= appResumeEventHandler;
00215         }
00216
00217         /// <summary>
00218         /// Registers for Added, Removed, and Enumerated events on the provided deviceWatcher before adding it to an internal list.
00219         /// </summary>
00220         /// <param name="deviceWatcher"></param>
00221         /// <param name="deviceSelector">The AQS used to create the device watcher</param>
00222         private void AddDeviceWatcher(DeviceWatcher deviceWatcher, String deviceSelector)
00223         {
00224             deviceWatcher.Added += new TypedEventHandler<DeviceWatcher, DeviceInformation>(this.OnDeviceAdded);
00225             deviceWatcher.Removed += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(this.OnDeviceRemoved);
00226             deviceWatcher.EnumerationCompleted += new TypedEventHandler<DeviceWatcher, Object>(this.OnDeviceEnumerationComplete);
00227
00228             mapDeviceWatchersToDeviceSelector.Add(deviceWatcher, deviceSelector);
00229         }
00230
00231         /// <summary>
00232         /// Starts all device watchers including ones that have been individually stopped.
00233         /// </summary>
00234         private void StartDeviceWatchers()
00235         {
00236             // Start all device watchers
00237             watchersStarted = true;
00238             isAllDevicesEnumerated = false;
00239
00240             foreach (DeviceWatcher deviceWatcher in mapDeviceWatchersToDeviceSelector.Keys)
00241             {
00242                 if ((deviceWatcher.Status != DeviceWatcherStatus.Started)
00243                     && (deviceWatcher.Status != DeviceWatcherStatus.EnumerationCompleted))
00244                 {
00245                     deviceWatcher.Start();
00246                 }
00247             }
00248         }
00249
00250         /// <summary>
00251         /// Stops all device watchers.
00252         /// </summary>
00253         private void StopDeviceWatchers()
00254         {
00255             // Stop all device watchers
00256             foreach (DeviceWatcher deviceWatcher in mapDeviceWatchersToDeviceSelector.Keys)
00257             {
00258                 if ((deviceWatcher.Status == DeviceWatcherStatus.Started)
00259                     || (deviceWatcher.Status == DeviceWatcherStatus.EnumerationCompleted))
00260                 {
00261                     deviceWatcher.Stop();
00262                 }
00263             }
00264
00265             // Clear the list of devices so we don't have potentially disconnected devices around
00266             ClearDeviceEntries();
00267
00268             watchersStarted = false;
00269         }
00270
00271         /// <summary>
00272         /// Creates a DeviceListEntry for a device and adds it to the list of devices in the UI
00273         /// </summary>
00274         /// <param name="deviceInformation">DeviceInformation on the device to be added to the list</param>
00275         /// <param name="deviceSelector">The AQS used to find this device</param>
00276         private void AddDeviceToList(DeviceInformation deviceInformation, String deviceSelector)
00277         {
00278             // search the device list for a device with a matching interface ID
00279             var match = FindDevice(deviceInformation.Id);
00280
00281             // Add the device if it's new
00282             if (match == null)
00283             {
00284                 // Create a new element for this device interface, and queue up the query of its
00285                 // device information
00286                 match = new DeviceListEntry(deviceInformation, deviceSelector);
00287
00288                 // Add the new element to the end of the list of devices
00289                 listOfDevices.Add(match);
00290             }
00291         }
00292
00293         private void RemoveDeviceFromList(String deviceId)
00294         {
00295             // Removes the device entry from the interal list; therefore the UI
00296             var deviceEntry = FindDevice(deviceId);
00297
00298             listOfDevices.Remove(deviceEntry);
00299         }
00300
00301         private void ClearDeviceEntries()
00302         {
00303             listOfDevices.Clear();
00304         }
00305
00306         /// <summary>
00307         /// Searches through the existing list of devices for the first DeviceListEntry that has
00308         /// the specified device Id.
00309         /// </summary>
00310         /// <param name="deviceId">Id of the device that is being searched for</param>
00311         /// <returns>DeviceListEntry that has the provided Id; else a nullptr</returns>
00312         private DeviceListEntry FindDevice(String deviceId)
00313         {
00314             if (deviceId != null)
00315             {
00316                 foreach (DeviceListEntry entry in listOfDevices)
00317                 {
00318                     if (entry.DeviceInformation.Id == deviceId)
00319                     {
00320                         return entry;
00321                     }
00322                 }
00323             }
00324
00325             return null;
00326         }
00327
00328         /// <summary>
00329         /// We must stop the DeviceWatchers because device watchers will continue to raise events even if
00330         /// the app is in suspension, which is not desired (drains battery). We resume the device watcher once the app resumes again.
00331         /// </summary>
00332         /// <param name="sender"></param>
00333         /// <param name="eventArgs"></param>
00334         private void OnAppSuspension(Object sender, SuspendingEventArgs args)
00335         {
00336             if (watchersStarted)
00337             {
00338                 watchersSuspended = true;
00339                 StopDeviceWatchers();
00340             }
00341             else
00342             {
00343                 watchersSuspended = false;
00344             }
00345         }
00346
00347         /// <summary>
00348         /// See OnAppSuspension for why we are starting the device watchers again
00349         /// </summary>
00350         /// <param name="sender"></param>
00351         /// <param name="args"></param>
00352         private void OnAppResume(Object sender, Object args)
00353         {
00354             if (watchersSuspended)
00355             {
00356                 watchersSuspended = false;
00357                 StartDeviceWatchers();
00358             }
00359         }
00360
00361         /// <summary>
00362         /// We will remove the device from the UI
00363         /// </summary>
00364         /// <param name="sender"></param>
00365         /// <param name="deviceInformationUpdate"></param>
00366         private async void OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceInformationUpdate)
00367         {
00368             await rootPage.Dispatcher.RunAsync(
00369                 CoreDispatcherPriority.Normal,
00370                 new DispatchedHandler(() =>
00371                 {
00372                     rootPage.NotifyUser("Device removed - " + deviceInformationUpdate.Id, NotifyType.StatusMessage);
00373
00374                     RemoveDeviceFromList(deviceInformationUpdate.Id);
00375                 }));
00376         }
00377
00378         /// <summary>
00379         /// This function will add the device to the listOfDevices so that it shows up in the UI
00380         /// </summary>
00381         /// <param name="sender"></param>
00382         /// <param name="deviceInformation"></param>
00383         private async void OnDeviceAdded(DeviceWatcher sender, DeviceInformation deviceInformation)
00384         {
00385             await rootPage.Dispatcher.RunAsync(
00386                 CoreDispatcherPriority.Normal,
00387                 new DispatchedHandler(() =>
00388                 {
00389                     rootPage.NotifyUser("Device added - " + deviceInformation.Id, NotifyType.StatusMessage);
00390
00391                     AddDeviceToList(deviceInformation, mapDeviceWatchersToDeviceSelector[sender]);
00392                 }));
00393         }
00394
00395         /// <summary>
00396         /// Notify the UI whether or not we are connected to a device
00397         /// </summary>
00398         /// <param name="sender"></param>
00399         /// <param name="args"></param>
00400         private async void OnDeviceEnumerationComplete(DeviceWatcher sender, Object args)
00401         {
00402             await rootPage.Dispatcher.RunAsync(
00403                 CoreDispatcherPriority.Normal,
00404                 new DispatchedHandler(() =>
00405                 {
00406                     isAllDevicesEnumerated = true;
00407
00408                     // If we finished enumerating devices and the device has not been connected yet, the OnDeviceConnected method
00409                     // is responsible for selecting the device in the device list (UI); otherwise, this method does that.
00410                     if (EventHandlerForDevice.Current.IsDeviceConnected)
00411                     {
00412                         SelectDeviceInList(EventHandlerForDevice.Current.DeviceInformation.Id);
00413
00414                         ButtonDisconnectFromDevice.Content = ButtonNameDisconnectFromDevice;
00415
00416                         rootPage.NotifyUser("Connected to - " +
00417                                             EventHandlerForDevice.Current.DeviceInformation.Id, NotifyType.StatusMessage);
00418
00419                         EventHandlerForDevice.Current.ConfigureCurrentlyConnectedDevice();
00420                     }
00421                     else if (EventHandlerForDevice.Current.IsEnabledAutoReconnect && EventHandlerForDevice.Current.DeviceInformation != null)
00422                     {
00423                         // We will be reconnecting to a device
00424                         ButtonDisconnectFromDevice.Content = ButtonNameDisableReconnectToDevice;
00425
00426                         rootPage.NotifyUser("Waiting to reconnect to device -  " + EventHandlerForDevice.Current.DeviceInformation.Id, NotifyType.StatusMessage);
00427                     }
00428                     else
00429                     {
00430                         rootPage.NotifyUser("No device is currently connected", NotifyType.StatusMessage);
00431                     }
00432                 }));
00433         }
00434
00435         /// <summary>
00436         /// If all the devices have been enumerated, select the device in the list we connected to. Otherwise let the EnumerationComplete event
00437         /// from the device watcher handle the device selection
00438         /// </summary>
00439         /// <param name="sender"></param>
00440         /// <param name="deviceInformation"></param>
00441         private void OnDeviceConnected(EventHandlerForDevice sender, DeviceInformation deviceInformation)
00442         {
00443             // Find and select our connected device
00444             if (isAllDevicesEnumerated)
00445             {
00446                 SelectDeviceInList(EventHandlerForDevice.Current.DeviceInformation.Id);
00447
00448                 ButtonDisconnectFromDevice.Content = ButtonNameDisconnectFromDevice;
00449             }
00450
00451             rootPage.NotifyUser("Connected to - " +
00452                                 EventHandlerForDevice.Current.DeviceInformation.Id, NotifyType.StatusMessage);
00453         }
00454
00455         /// <summary>
00456         /// The device was closed. If we will autoreconnect to the device, reflect that in the UI
00457         /// </summary>
00458         /// <param name="sender"></param>
00459         /// <param name="deviceInformation"></param>
00460         private async void OnDeviceClosing(EventHandlerForDevice sender, DeviceInformation deviceInformation)
00461         {
00462             await rootPage.Dispatcher.RunAsync(
00463                 CoreDispatcherPriority.Normal,
00464                 new DispatchedHandler(() =>
00465                 {
00466                     // We were connected to the device that was unplugged, so change the "Disconnect from device" button
00467                     // to "Do not reconnect to device"
00468                     if (ButtonDisconnectFromDevice.IsEnabled && EventHandlerForDevice.Current.IsEnabledAutoReconnect)
00469                     {
00470                         ButtonDisconnectFromDevice.Content = ButtonNameDisableReconnectToDevice;
00471                     }
00472                 }));
00473         }
00474
00475         /// <summary>
00476         /// Selects the item in the UI's listbox that corresponds to the provided device id. If there are no
00477         /// matches, we will deselect anything that is selected.
00478         /// </summary>
00479         /// <param name="deviceIdToSelect">The device id of the device to select on the list box</param>
00480         private void SelectDeviceInList(String deviceIdToSelect)
00481         {
00482             // Don't select anything by default.
00483             ConnectDevices.SelectedIndex = -1;
00484
00485             for (int deviceListIndex = 0; deviceListIndex < listOfDevices.Count; deviceListIndex++)
00486             {
00487                 if (listOfDevices[deviceListIndex].DeviceInformation.Id == deviceIdToSelect)
00488                 {
00489                     ConnectDevices.SelectedIndex = deviceListIndex;
00490
00491                     break;
00492                 }
00493             }
00494         }
00495
00496         /// <summary>
00497         /// When ButtonConnectToDevice is disabled, ConnectDevices list will also be disabled.
00498         /// </summary>
00499         /// <param name="enableConnectButton">The state of ButtonConnectToDevice</param>
00500         private void UpdateConnectDisconnectButtonsAndList(Boolean enableConnectButton)
00501         {
00502             ButtonConnectToDevice.IsEnabled = enableConnectButton;
00503             ButtonDisconnectFromDevice.IsEnabled = !ButtonConnectToDevice.IsEnabled;
00504
00505             ConnectDevices.IsEnabled = ButtonConnectToDevice.IsEnabled;
00506         }
00507     }
00508 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IOvenFactory Member List

This is the complete list of members for IOvenFactory, including all inherited members.
CreateOven([in] Dimensions dimensions,[out, retval] Oven **result) | IOvenFactory
CreateOven([in] Dimensions dimensions,[out, retval] Oven **result) | IOvenFactory
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cs/FxCompile.cs Source File

  • BasicHologram
  • cs

FxCompile.cs

Go to the documentation of this file.
00001 //-----------------------------------------------------------------------
00002 // <copyright file="FxCompile.cs" company="Microsoft">
00003 // Copyright (C) Microsoft Corporation. All rights reserved.
00004 // </copyright>
00005 //-----------------------------------------------------------------------
00006
00007 using Microsoft.Build.Framework;
00008 using System;
00009 using System.Collections;
00010 using System.Collections.Generic;
00011 using System.Linq;
00012 using System.Text;
00013 using System.Threading.Tasks;
00014 using Microsoft.Build.Utilities;
00015
00016 namespace Microsoft.Build.Tasks
00017 {
00018     /// <summary>
00019     /// Task to support Fxc.exe
00020     /// </summary>
00021     public class FxCompile : ToolTask
00022     {
00023         /// <summary>
00024         /// Constructor
00025         /// </summary>
00026         public FxCompile()
00027         {
00028             // Because FxCop wants it this way.
00029         }
00030
00031         #region Inputs
00032
00033         /// <summary>
00034         /// Sources to be compiled.
00035         /// </summary>
00036         /// <remarks>Required for task to run.</remarks>
00037         [Required]
00038         public virtual ITaskItem[] Source
00039         {
00040             get { return (ITaskItem[])Bag["Sources"]; }
00041             set { Bag["Sources"] = value; }
00042         }
00043
00044         /// <summary>
00045         /// Gets the collection of parameters used by the derived task class.
00046         /// </summary>
00047         /// <value>Parameter bag.</value>
00048         protected internal Hashtable Bag
00049         {
00050             get
00051             {
00052                 return bag;
00053             }
00054         }
00055
00056         private Hashtable bag = new Hashtable();
00057
00058         /// <summary>
00059         /// ShaderType, requires ShaderModel
00060         /// Specifies the type of shader.  (/T [type]_[model])
00061         /// </summary>
00062         /// <remarks>Consider using one of these: "NotSet", "Effect", "Vertex", "Pixel", "Geometry", "Hull", "Domain", "Compute", or "Texture".</remarks>
00063         public virtual string ShaderType
00064         {
00065             get
00066             {
00067                 return (string)Bag["ShaderType"];
00068             }
00069
00070             set
00071             {
00072                 string result = String.Empty;
00073                 switch (value.ToLowerInvariant())
00074                 {
00075                     case "notset":
00076                         result = "";
00077                         break;
00078                     case "effect":
00079                         result = "/T fx";
00080                         break;
00081                     case "vertex":
00082                         result = "/T vs";
00083                         break;
00084                     case "pixel":
00085                         result = "/T ps";
00086                         break;
00087                     case "geometry":
00088                         result = "/T gs";
00089                         break;
00090                     case "hull":
00091                         result = "/T hs";
00092                         break;
00093                     case "domain":
00094                         result = "/T ds";
00095                         break;
00096                     case "compute":
00097                         result = "/T cs";
00098                         break;
00099                     case "texture":
00100                         result = "/T tx";
00101                         break;
00102                     default:
00103                         throw new ArgumentException("ShaderType of " + value + @" is an invalid.  Consider using one of these: ""NotSet"", ""Effect"", ""Vertex"", ""Pixel"", ""Geometry"", ""Hull"", ""Domain"", ""Compute"", or ""Texture"".");
00104                 }
00105
00106                 Bag["ShaderType"] = result;
00107             }
00108         }
00109
00110         /// <summary>
00111         /// ShaderModel, requires ShaderType
00112         /// Specifies the shader model. Some shader types can only be used with recent shader models (/T [type]_[model])
00113         /// </summary>
00114         public virtual string ShaderModel
00115         {
00116             get { return (string)Bag["ShaderModel"]; }
00117             set { Bag["ShaderModel"] = value; }
00118         }
00119
00120         /// <summary>
00121         /// AssemblerOutput, requires AssemblerOutputFile
00122         /// Specifies the contents of assembly language output file. (/Fc, /Fx)
00123         /// </summary>
00124         /// <remarks>Consider using one of these: "Assembly Code" or "Assembly Code and Hex".</remarks>
00125         public virtual string AssemblerOutput
00126         {
00127             get
00128             {
00129                 return (string)Bag["AssemblerOutput"];
00130             }
00131
00132             set
00133             {
00134                 string result = String.Empty;
00135                 switch (value.ToLowerInvariant())
00136                 {
00137                     case "Assembly Code":
00138                         result = "/Fc";
00139                         break;
00140                     case "Assembly Code and Hex":
00141                         result = "/Fx";
00142                         break;
00143                     default:
00144                         throw new ArgumentException("AssemblerOutput of " + value + @" is an invalid.  Consider using one of these: ""Assembly Code"" or ""Assembly Code and Hex"".");
00145                 }
00146
00147                 Bag["AssemblerOutput"] = value;
00148             }
00149         }
00150
00151         /// <summary>
00152         /// AssemblerOutputFile, requires AssemblerOutput
00153         /// Specifies file name for assembly code listing file
00154         /// </summary>
00155         public virtual string AssemblerOutputFile
00156         {
00157             get { return (string)Bag["AssemblerOutputFile"]; }
00158             set { Bag["AssemblerOutputFile"] = value; }
00159         }
00160
00161         /// <summary>
00162         /// Specifies a name for the variable name in the header file (/Vn [name])
00163         /// </summary>
00164         public virtual string VariableName
00165         {
00166             get { return (string)Bag["VariableName"]; }
00167             set { Bag["VariableName"] = value; }
00168         }
00169
00170         /// <summary>
00171         /// Specifies a name for header file containing object code. (/Fh [name])
00172         /// </summary>
00173         public virtual string HeaderFileOutput
00174         {
00175             get { return (string)Bag["HeaderFileOutput"]; }
00176             set { Bag["HeaderFileOutput"] = value; }
00177         }
00178
00179         /// <summary>
00180         /// Specifies a name for object file. (/Fo [name])
00181         /// </summary>
00182         public virtual string ObjectFileOutput
00183         {
00184             get { return (string)Bag["ObjectFileOutput"]; }
00185             set { Bag["ObjectFileOutput"] = value; }
00186         }
00187
00188         /// <summary>
00189         /// Defines preprocessing symbols for your source file.
00190         /// </summary>
00191         public virtual string[] PreprocessorDefinitions
00192         {
00193             get { return (string[])Bag["PreprocessorDefinitions"]; }
00194             set { Bag["PreprocessorDefinitions"] = value; }
00195         }
00196
00197         /// <summary>
00198         /// Specifies one or more directories to add to the include path; separate with semi-colons if more than one. (/I[path])
00199         /// </summary>
00200         public virtual string[] AdditionalIncludeDirectories
00201         {
00202             get { return (string[])Bag["AdditionalIncludeDirectories"]; }
00203             set { Bag["AdditionalIncludeDirectories"] = value; }
00204         }
00205
00206         /// <summary>
00207         /// Suppresses the display of the startup banner and information message. (/nologo)
00208         /// </summary>
00209         public virtual bool SuppressStartupBanner
00210         {
00211             get { return GetBoolParameterWithDefault("SuppressStartupBanner", false); }
00212             set { Bag["SuppressStartupBanner"] = value; }
00213         }
00214
00215         /// <summary>
00216         /// Specifies the name of the entry point for the shader (/E[name])
00217         /// </summary>
00218         public virtual string EntryPointName
00219         {
00220             get { return (string)Bag["EntryPointName"]; }
00221             set { Bag["EntryPointName"] = value; }
00222         }
00223
00224         /// <summary>
00225         /// Treats all compiler warnings as errors. For a new project, it may be best to use /WX in all compilations; resolving all warnings will ensure the fewest possible hard-to-find code defects.
00226         /// </summary>
00227         public virtual bool TreatWarningAsError
00228         {
00229             get { return GetBoolParameterWithDefault("TreatWarningAsError", false); }
00230             set { Bag["TreatWarningAsError"] = value; }
00231         }
00232
00233         /// <summary>
00234         /// Disable optimizations. /Od implies /Gfp though output may not be identical to /Od /Gfp.
00235         /// </summary>
00236         public virtual bool DisableOptimizations
00237         {
00238             get { return GetBoolParameterWithDefault("DisableOptimizations", false); }
00239             set { Bag["DisableOptimizations"] = value; }
00240         }
00241
00242         /// <summary>
00243         /// Enable debugging information.
00244         /// </summary>
00245         public virtual bool EnableDebuggingInformation
00246         {
00247             get { return GetBoolParameterWithDefault("EnableDebuggingInformation", false); }
00248             set { Bag["EnableDebuggingInformation"] = value; }
00249         }
00250
00251         /// <summary>
00252         /// Path to Windows SDK
00253         /// </summary>
00254         public string SdkToolsPath
00255         {
00256             get { return (string)Bag["SdkToolsPath"]; }
00257             set { Bag["SdkToolsPath"] = value; }
00258         }
00259
00260         /// <summary>
00261         /// Name to Fxc.exe
00262         /// </summary>
00263         protected override string ToolName
00264         {
00265             get { return "Fxc.exe"; }
00266         }
00267
00268         #endregion
00269
00270         /// <summary>
00271         /// Returns a string with those switches and other information that can't go into a response file and
00272         /// must go directly onto the command line.
00273         /// Called after ValidateParameters and SkipTaskExecution
00274         /// </summary>
00275         /// <returns></returns>
00276         override protected string GenerateCommandLineCommands()
00277         {
00278             CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
00279             AddCommandLineCommands(commandLineBuilder);
00280             return commandLineBuilder.ToString();
00281         }
00282
00283         /// <summary>
00284         /// Returns the command line switch used by the tool executable to specify the response file
00285         /// Will only be called if the task returned a non empty string from GetResponseFileCommands
00286         /// Called after ValidateParameters, SkipTaskExecution and GetResponseFileCommands
00287         /// </summary>
00288         /// <param name="responseFilePath">full path to the temporarily created response file</param>
00289         /// <returns></returns>
00290         override protected string GenerateResponseFileCommands()
00291         {
00292             CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
00293             AddResponseFileCommands(commandLineBuilder);
00294             return commandLineBuilder.ToString();
00295         }
00296
00297         /// <summary>
00298         /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
00299         /// </summary>
00300         /// <param name="commandLine"></param>
00301         protected internal virtual void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
00302         {
00303         }
00304
00305         /// <summary>
00306         /// Add Command Line Commands
00307         /// </summary>
00308         /// <param name="commandLine">CommandLineBuilderExtension</param>
00309         protected internal void AddCommandLineCommands(CommandLineBuilderExtension commandLine)
00310         {
00311             //// Order of these affect the order of the command line
00312
00313             commandLine.AppendSwitchIfNotNull("/I ", AdditionalIncludeDirectories, "");
00314             commandLine.AppendSwitch(SuppressStartupBanner ? "/nologo" : String.Empty);
00315             commandLine.AppendSwitchIfNotNull("/E", EntryPointName);
00316             commandLine.AppendSwitch(TreatWarningAsError ? "/WX" : String.Empty);
00317
00318             // Switch cannot be null
00319             if (ShaderType != null && ShaderModel != null)
00320             {
00321                 // shader Model and Type are one switch
00322                 commandLine.AppendSwitch(ShaderType + "_" + ShaderModel);
00323             }
00324
00325             commandLine.AppendSwitchIfNotNull("/D ", PreprocessorDefinitions, "");
00326             commandLine.AppendSwitchIfNotNull("/Fh ", HeaderFileOutput);
00327             commandLine.AppendSwitchIfNotNull("/Fo ", ObjectFileOutput);
00328
00329             // Switch cannot be null
00330             if (AssemblerOutput != null)
00331             {
00332                 commandLine.AppendSwitchIfNotNull(AssemblerOutput, AssemblerOutputFile);
00333             }
00334
00335             commandLine.AppendSwitchIfNotNull("/Vn ", VariableName);
00336             commandLine.AppendSwitch(DisableOptimizations ? "/Od" : String.Empty);
00337             commandLine.AppendSwitch(EnableDebuggingInformation ? "/Zi" : String.Empty);
00338
00339             commandLine.AppendSwitchIfNotNull("", Source, " ");
00340         }
00341
00342         /// <summary>
00343         /// Fullpath to the fxc.exe
00344         /// </summary>
00345         /// <returns>Fullpath to fxc.exe, if found.  Otherwise empty or null.</returns>
00346         protected override string GenerateFullPathToTool()
00347         {
00348             return System.IO.Path.Combine(SdkToolsPath, ToolName);
00349         }
00350
00351         /// <summary>
00352         /// Get a bool parameter and return a default if its not present
00353         /// in the hash table.
00354         /// </summary>
00355         /// <param name="parameters"></param>
00356         /// <param name="parameterName"></param>
00357         /// <param name="defaultValue"></param>
00358         /// <returns></returns>
00359         /// <owner>JomoF</owner>
00360         protected internal bool GetBoolParameterWithDefault(string parameterName, bool defaultValue)
00361         {
00362             object obj = bag[parameterName];
00363             return (obj == null) ? defaultValue : (bool) obj;
00364         }
00365     }
00366 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cppwinrt/BarcodeScannerInfo.cpp Source File

  • BarcodeScanner
  • cppwinrt

BarcodeScannerInfo.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "BarcodeScannerInfo.h"
00014 #include "BarcodeScannerInfo.g.cpp"
00015
Generated on Fri Nov 15 2024 22:18:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Configuration Member List

This is the complete list of members for Scenario1_Configuration, including all inherited members.
LanguageList_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario1_Configuration | [inline, private]
localSettings | Scenario1_Configuration | [private, static]
rootPage | Scenario1_Configuration | [private]
Scenario1_Configuration() | Scenario1_Configuration | [inline]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-I2C/cpp/SampleConfiguration.cpp Source File

  • IoT-I2C
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016
00017 Platform::Array<SDKTemplate::Scenario>^ SDKTemplate::MainPage::scenariosInner = ref new Platform::Array<SDKTemplate::Scenario>
00018 {
00019     { "Read data from I2C device", "SDKTemplate.Scenario1_ReadData" },
00020 };
00021
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/SampleConfiguration.h Source File

  • FileAccess
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return ref new Platform::String(L"File access C++ sample");
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029         static property Platform::String^ Filename
00030         {
00031             Platform::String^ get()
00032             {
00033                 return ref new Platform::String(L"sample.dat");
00034             }
00035         }
00036
00037         property Windows::Storage::StorageFile^ SampleFile
00038         {
00039             Windows::Storage::StorageFile^ get()
00040             {
00041                 return sampleFile;
00042             }
00043             void set(Windows::Storage::StorageFile^ value)
00044             {
00045                 sampleFile = value;
00046             }
00047         }
00048
00049     internal:
00050         void ValidateFile();
00051         void NotifyUserFileNotExist();
00052         void HandleIoException(Platform::COMException^ e, Platform::String^ description);
00053         static Windows::Storage::Streams::IBuffer^ GetBufferFromString(Platform::String^ string);
00054         static Platform::String^ GetStringFromBuffer(Windows::Storage::Streams::IBuffer^ buffer);
00055     private:
00056         static Platform::Array<Scenario>^ scenariosInner;
00057         Windows::Storage::StorageFile^ sampleFile;
00058     };
00059
00060     public value struct Scenario
00061     {
00062         Platform::String^ Title;
00063         Platform::String^ ClassName;
00064     };
00065 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cs/SampleConfiguration.cs Source File

  • Pedometer
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using PedometerCS;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Pedometer";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Events", ClassType=typeof(Scenario1_Events) },
00026             new Scenario() { Title="History", ClassType=typeof(Scenario2_History) },
00027             new Scenario() { Title="Current step count", ClassType=typeof(Scenario3_CurrentStepCount) },
00028             new Scenario() { Title="Background Pedometer", ClassType=typeof(Scenario4_BackgroundPedometer) }
00029         };
00030     }
00031     public class Scenario
00032     {
00033         public string Title { get; set; }
00034         public Type ClassType { get; set; }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/Common/DDSTextureLoader.h Source File

  • Simple3DGameDX
  • cppwinrt
  • Common

DDSTextureLoader.h

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.h
00003 //
00004 // Functions for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note these functions are useful as a light-weight runtime loader for DDS files. For
00007 // a full-featured DDS file reader, writer, and texture processing pipeline see
00008 // the 'Texconv' sample and the 'DirectXTex' library.
00009 //
00010 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00011 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00012 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00013 // PARTICULAR PURPOSE.
00014 //
00015 // Copyright (c) Microsoft Corporation. All rights reserved.
00016 //
00017 // http://go.microsoft.com/fwlink/?LinkId=248926
00018 // http://go.microsoft.com/fwlink/?LinkId=248929
00019 //--------------------------------------------------------------------------------------
00020
00021 #pragma once
00022
00023 void CreateDDSTextureFromMemory(
00024     _In_ ID3D11Device* d3dDevice,
00025     _In_reads_bytes_(ddsDataSize) const byte* ddsData,
00026     _In_ size_t ddsDataSize,
00027     _Outptr_opt_ ID3D11Resource** texture,
00028     _Outptr_opt_ ID3D11ShaderResourceView** textureView,
00029     _In_ size_t maxsize = 0,
00030     _Out_opt_ D2D1_ALPHA_MODE* alphaMode = nullptr
00031     );
00032
00033 void CreateDDSTextureFromMemoryEx(
00034     _In_ ID3D11Device* d3dDevice,
00035     _In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
00036     _In_ size_t ddsDataSize,
00037     _In_ size_t maxsize,
00038     _In_ D3D11_USAGE usage,
00039     _In_ unsigned int bindFlags,
00040     _In_ unsigned int cpuAccessFlags,
00041     _In_ unsigned int miscFlags,
00042     _In_ bool forceSRGB,
00043     _Outptr_opt_ ID3D11Resource** texture,
00044     _Outptr_opt_ ID3D11ShaderResourceView** textureView,
00045     _Out_opt_ D2D1_ALPHA_MODE* alphaMode = nullptr
00046     );
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioContext Member List

This is the complete list of members for ScenarioContext, including all inherited members.
compressedData | ScenarioContext
compressor | ScenarioContext
decompressedData | ScenarioContext
originalData | ScenarioContext
raStream | ScenarioContext
writer | ScenarioContext
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/Scenario3.xaml.h Source File

  • SimpleInk
  • cpp

Scenario3.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario3 sealed
00024     {
00025     public:
00026         Scenario3();
00027
00028     private:
00029         void OnSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs e);
00030         void InkPresenter_StrokesErased(Windows::UI::Input::Inking::InkPresenter^ sender, Windows::UI::Input::Inking::InkStrokesErasedEventArgs^ args);
00031         void InkPresenter_StrokesCollected(Windows::UI::Input::Inking::InkPresenter^ sender, Windows::UI::Input::Inking::InkStrokesCollectedEventArgs^ args);
00032         void OnPenColorChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033         void OnPenTypeChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void OnPenThicknessChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         void OnClear(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         void OnSaveAsync(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         void OnLoadAsync(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         void TouchInkingCheckBox_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         void TouchInkingCheckBox_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void ErasingModeCheckBox_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void ErasingModeCheckBox_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void OnSizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00043
00044
00045         MainPage^ rootPage;
00046         const static int minPenSize = 2;
00047         const static int penSizeIncrement = 2;
00048
00049         int penSize;
00050     };
00051 }
Generated on Fri Nov 15 2024 22:18:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmsSendAndReceive/cs/SmsBackgroundTask/SmsBackgroundTask.cs Source File

  • SmsSendAndReceive
  • cs
  • SmsBackgroundTask

SmsBackgroundTask.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Diagnostics;
00014 using System.Collections.Generic;
00015 using System.Linq;
00016 using System.Text;
00017 using System.Threading;
00018 using System.Threading.Tasks;
00019 using Windows.ApplicationModel.Background;
00020 using Windows.Storage;
00021 using Windows.Devices.Sms;
00022 using Windows.Data.Xml.Dom;
00023 using Windows.UI.Notifications;
00024
00025 namespace SmsBackgroundTask
00026 {
00027     public sealed class SampleSmsBackgroundTask : IBackgroundTask
00028     {
00029         //
00030         // The Run method is the entry point of a background task.
00031         //
00032         public void Run(IBackgroundTaskInstance taskInstance)
00033         {
00034             Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");
00035             //
00036             // Associate a cancellation handler with the background task.
00037             //
00038             taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
00039
00040             //
00041             // Do the background task activity.
00042             //
00043             DisplayToast(taskInstance);
00044
00045             //
00046             // Provide status to application via local settings storage
00047             //
00048             var settings = Windows.Storage.ApplicationData.Current.LocalSettings;
00049             settings.Values[taskInstance.Task.TaskId.ToString()] = "Completed";
00050
00051             Debug.WriteLine("Background " + taskInstance.Task.Name + ("process ran"));
00052         }
00053
00054         private void DisplayToast(IBackgroundTaskInstance taskInstance)
00055         {
00056             try
00057             {
00058                 SmsMessageReceivedTriggerDetails smsDetails = taskInstance.TriggerDetails as SmsMessageReceivedTriggerDetails;
00059
00060                 // Just registered for text messages
00061                 SmsTextMessage2 smsTextMessage;
00062                 if (smsDetails.MessageType == SmsMessageType.Text)
00063                 {
00064                     smsTextMessage = smsDetails.TextMessage;
00065
00066                     XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
00067
00068                     XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
00069
00070                     stringElements.Item(0).AppendChild(toastXml.CreateTextNode(smsTextMessage.From));
00071
00072                     stringElements.Item(1).AppendChild(toastXml.CreateTextNode(smsTextMessage.Body));
00073
00074                     ToastNotification notification = new ToastNotification(toastXml);
00075                     ToastNotificationManager.CreateToastNotifier().Show(notification);
00076                 }
00077                 else
00078                 {
00079                     Debug.WriteLine("Invalid message type: " + smsDetails.MessageType);
00080                 }
00081
00082                 // Ack the message
00083                 smsDetails.Accept();
00084             }
00085             catch (Exception ex)
00086             {
00087                 Debug.WriteLine("Error displaying toast: " + ex.Message);
00088             }
00089         }
00090
00091
00092         //
00093         // Handles background task cancellation.
00094         //
00095         private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
00096         {
00097             //
00098             // Indicate that the background task is canceled.
00099             //
00100             var settings = Windows.Storage.ApplicationData.Current.LocalSettings;
00101             settings.Values[sender.Task.TaskId.ToString()] = "Canceled";
00102
00103             Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested...");
00104         }
00105     }
00106 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cpp/Scenario2_StringTemplate.xaml.h Source File

  • DateTimeFormatting
  • cpp

Scenario2_StringTemplate.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario2_StringTemplate.g.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario2_StringTemplate sealed
00021     {
00022     public:
00023         Scenario2_StringTemplate();
00024         void Display();
00025     };
00026 }
Generated on Fri Nov 15 2024 22:19:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaEditing/cpp/Scenario4_AddOverlays.xaml.h Source File

  • MediaEditing
  • cpp

Scenario4_AddOverlays.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_AddOverlays.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario4_AddOverlays sealed
00021     {
00022     public:
00023         Scenario4_AddOverlays();
00024
00025     protected:
00026         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00027
00028     private:
00029         SDKTemplate::MainPage^ rootPage;
00030         Windows::Media::Editing::MediaComposition^ composition;
00031         Windows::Storage::StorageFile^ baseVideoFile;
00032         Windows::Storage::StorageFile^ overlayVideoFile;
00033         Windows::Media::Core::MediaStreamSource^ mediaStreamSource;
00034
00035         void ChooseVideo_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         void AddAudio_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037
00038         void ChooseBaseVideo_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         void ChooseOverlayVideo_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void CreateOverlays();
00041     };
00042 }
Generated on Fri Nov 15 2024 22:20:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario03_GetList Member List

This is the complete list of members for Scenario03_GetList, including all inherited members.
Cancel_Click(object sender, RoutedEventArgs e) | Scenario03_GetList | [inline, private]
cts | Scenario03_GetList | [private]
httpClient | Scenario03_GetList | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario03_GetList | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario03_GetList | [inline, protected]
rootPage | Scenario03_GetList | [private]
Scenario03_GetList() | Scenario03_GetList | [inline]
Start_Click(object sender, RoutedEventArgs e) | Scenario03_GetList | [inline, private]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/BackgroundTask/pch.cpp Source File

  • BackgroundTask
  • cpp
  • BackgroundTask

pch.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_DataEvents Member List

This is the complete list of members for Scenario1_DataEvents, including all inherited members.
_sensor | Scenario1_DataEvents | [private]
DisplayOrientation(TextBlock tb, SimpleOrientation orientation) | Scenario1_DataEvents | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_DataEvents | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario1_DataEvents | [inline, protected]
OrientationChanged(object sender, SimpleOrientationSensorOrientationChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
rootPage | Scenario1_DataEvents | [private]
Scenario1_DataEvents() | Scenario1_DataEvents | [inline]
ScenarioDisable(object sender, RoutedEventArgs e) | Scenario1_DataEvents | [inline, private]
ScenarioEnable(object sender, RoutedEventArgs e) | Scenario1_DataEvents | [inline, private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cs/AppResourceClassLibrary/Properties/AssemblyInfo.cs Source File

  • ApplicationResources
  • cs
  • AppResourceClassLibrary
  • Properties

AssemblyInfo.cs

Go to the documentation of this file.
00001 ﻿using System.Reflection;
00002 using System.Runtime.CompilerServices;
00003 using System.Runtime.InteropServices;
00004
00005 // General Information about an assembly is controlled through the following
00006 // set of attributes. Change these attribute values to modify the information
00007 // associated with an assembly.
00008 [assembly: AssemblyTitle("AppResourceClassLibrary")]
00009 [assembly: AssemblyDescription("")]
00010 [assembly: AssemblyConfiguration("")]
00011 [assembly: AssemblyCompany("")]
00012 [assembly: AssemblyProduct("AppResourceClassLibrary")]
00013 [assembly: AssemblyCopyright("Copyright ©  2015")]
00014 [assembly: AssemblyTrademark("")]
00015 [assembly: AssemblyCulture("")]
00016
00017 // Version information for an assembly consists of the following four values:
00018 //
00019 //      Major Version
00020 //      Minor Version
00021 //      Build Number
00022 //      Revision
00023 //
00024 // You can specify all the values or you can default the Build and Revision Numbers
00025 // by using the '*' as shown below:
00026 // [assembly: AssemblyVersion("1.0.*")]
00027 [assembly: AssemblyVersion("1.0.0.0")]
00028 [assembly: AssemblyFileVersion("1.0.0.0")]
00029 [assembly: ComVisible(false)]
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_Snapshot Member List

This is the complete list of members for Scenario4_Snapshot, including all inherited members.
FindButton_Click(object sender, RoutedEventArgs e) | Scenario4_Snapshot | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario4_Snapshot | [inline, protected]
resultCollection | Scenario4_Snapshot | [private]
rootPage | Scenario4_Snapshot | [private]
Scenario4_Snapshot() | Scenario4_Snapshot | [inline]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DpiScaling/cpp/pch.cpp Source File

  • DpiScaling
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario04_PostText.h Source File

  • HttpClient
  • cppwinrt

Scenario04_PostText.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario04_PostText.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario04_PostText : Scenario04_PostTextT<Scenario04_PostText>
00020     {
00021         Scenario04_PostText();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025
00026         fire_and_forget Start_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         void Cancel_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028
00029     private:
00030         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00031         Windows::Web::Http::HttpClient httpClient{ nullptr };
00032         Windows::Foundation::IAsyncAction pendingAction{ nullptr };
00033
00034         Windows::Foundation::IAsyncAction CancelableRequestAsync(Windows::Foundation::Uri resourceUri);
00035     };
00036 }
00037
00038 namespace winrt::SDKTemplate::factory_implementation
00039 {
00040     struct Scenario04_PostText : Scenario04_PostTextT<Scenario04_PostText, implementation::Scenario04_PostText>
00041     {
00042     };
00043 }
Generated on Fri Nov 15 2024 22:19:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cs/WiFiDirectServiceWrappers.cs Source File

  • WiFiDirectServices
  • cs

WiFiDirectServiceWrappers.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Networking.Sockets;
00015 using System.Threading.Tasks;
00016 using Windows.Devices.WiFiDirect.Services;
00017 using Windows.Devices.Enumeration;
00018 using Windows.Storage.Streams;
00019 using System.Globalization;
00020 using System.Threading;
00021
00022 namespace SDKTemplate
00023 {
00024     namespace WiFiDirectServices
00025     {
00026         /// <summary>
00027         /// Wraps WiFiDirectServiceAdvertiser and handles callbacks and related state
00028         /// </summary>
00029         public class AdvertisementWrapper : IDisposable
00030         {
00031             private Object thisLock = new Object();
00032
00033             private WiFiDirectServiceAdvertiser advertiser = null;
00034             // Used to update main state
00035             private WiFiDirectServiceManager manager = null;
00036
00037             // PIN to use for display config method (if selected)
00038             private string pin = "";
00039
00040             // Keep track of incoming service requests that need to be accepted or rejected
00041             private IList<WiFiDirectServiceSessionRequest> requestList = new List<WiFiDirectServiceSessionRequest>();
00042
00043
00044             // Keep internal identifier
00045             private int uniqueInternalId;
00046             private static int nextId = 1;
00047
00048             public AdvertisementWrapper(
00049                 WiFiDirectServiceAdvertiser advertiser,
00050                 WiFiDirectServiceManager manager,
00051                 string pin = ""
00052                 )
00053             {
00054                 this.advertiser = advertiser;
00055                 this.manager = manager;
00056                 // Store PIN for "display" config method
00057                 this.pin = pin;
00058
00059                 uniqueInternalId = nextId++;
00060
00061                 // This should fire when the service is created and advertisement has started
00062                 // It will also fire when the advertisement has stopped for any reason
00063                 this.advertiser.AdvertisementStatusChanged += OnAdvertisementStatusChanged;
00064                 // This will fire when an auto-accept session is connected. Advertiser should keep track of the new service session
00065                 this.advertiser.AutoAcceptSessionConnected += OnAutoAcceptSessionConnected;
00066                 // This will fire when a session is requested and it must be explicitly accepted or rejected.
00067                 // The advertiser may need to display a PIN or take user input for a PIN
00068                 this.advertiser.SessionRequested += OnSessionRequested;
00069             }
00070
00071             public WiFiDirectServiceAdvertiser Advertiser
00072             {
00073                 get { return advertiser; }
00074             }
00075
00076             public int InternalId
00077             {
00078                 get { return uniqueInternalId; }
00079             }
00080
00081             public string Pin
00082             {
00083                 get { return pin; }
00084             }
00085
00086             public string Name
00087             {
00088                 get { return advertiser.ServiceName; }
00089             }
00090
00091             public string Status
00092             {
00093                 get { return advertiser.AdvertisementStatus.ToString(); }
00094             }
00095
00096             public IList<WiFiDirectServiceSessionRequest> SessionRequestList
00097             {
00098                 get { return requestList; }
00099             }
00100
00101             // NOTE: this is mutually exclusive with OnAutoAcceptSessionConnected
00102             private void OnSessionRequested(WiFiDirectServiceAdvertiser sender, WiFiDirectServiceSessionRequestedEventArgs args)
00103             {
00104                 try
00105                 {
00106                     ThrowIfDisposed();
00107
00108                     manager.NotifyUser("Received session request", NotifyType.StatusMessage);
00109
00110                     string sessionInfo = "";
00111                     if (args.GetSessionRequest().SessionInfo != null && args.GetSessionRequest().SessionInfo.Length > 0)
00112                     {
00113                         using (DataReader sessionInfoDataReader = DataReader.FromBuffer(args.GetSessionRequest().SessionInfo))
00114                         {
00115                             sessionInfo = sessionInfoDataReader.ReadString(args.GetSessionRequest().SessionInfo.Length);
00116                             manager.NotifyUser("Received Session Info: " + sessionInfo, NotifyType.StatusMessage);
00117                         }
00118                     }
00119
00120                     lock (thisLock)
00121                     {
00122                         requestList.Add(args.GetSessionRequest());
00123                     }
00124
00125                     // Now we update the UI and wait for action to take (accept or decline)
00126                     manager.AddSessionRequest(args.GetSessionRequest(), this);
00127
00128                     if (args.GetSessionRequest().ProvisioningInfo.IsGroupFormationNeeded &&
00129                         args.GetSessionRequest().ProvisioningInfo.SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod.PinDisplay)
00130                     {
00131                         // This means the advertiser should display a PIN and the seeker will look at the display and enter the same PIN
00132                         // The PIN may be randomly generated now, but for this sample, we configure a PIN when starting the advertiser
00133                         manager.NotifyUser("Remote side should enter PIN: " + pin, NotifyType.StatusMessage);
00134                     }
00135                 }
00136                 catch (Exception ex)
00137                 {
00138                     manager.NotifyUser("OnSessionRequest Failed: " + ex.Message, NotifyType.ErrorMessage);
00139                 }
00140             }
00141
00142             public async void AcceptSessionRequest(string id, string pin = "")
00143             {
00144                 WiFiDirectServiceSessionRequest request = null;
00145                 bool found = false;
00146
00147                 lock (thisLock)
00148                 {
00149                     foreach (var r in requestList)
00150                     {
00151                         if (r.DeviceInformation.Id == id)
00152                         {
00153                             found = true;
00154                             request = r;
00155                         }
00156                     }
00157
00158                     if (!found)
00159                     {
00160                         throw new KeyNotFoundException("Attempted to accept session not found in list");
00161                     }
00162
00163                     requestList.Remove(request);
00164                 }
00165                 manager.RemoveSessionRequest(request, this);
00166
00167                 try
00168                 {
00169                     WiFiDirectServiceSession session = null;
00170                     string pinForConnect = pin;
00171
00172                     // Determine if a PIN is needed
00173                     if (request.ProvisioningInfo.IsGroupFormationNeeded &&
00174                         request.ProvisioningInfo.SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod.PinDisplay)
00175                     {
00176                         // This means the advertiser should display a PIN and the seeker will look at the display and enter the same PIN
00177                         // The PIN may be randomly generated now, but for this sample, we configure a PIN when starting the advertiser
00178                         pinForConnect = this.pin;
00179                     }
00180                     else if (request.ProvisioningInfo.IsGroupFormationNeeded &&
00181                         request.ProvisioningInfo.SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod.PinEntry)
00182                     {
00183                         // This means that the seeker should display a PIN and the advertiser will need to look at that display and enter the same PIN
00184                         if (pin.Length == 0)
00185                         {
00186                             throw new ArgumentException("Expected PIN for connection, not provided");
00187                         }
00188                         pinForConnect = pin;
00189                     }
00190                     else
00191                     {
00192                         // PIN not needed, do not pass into connect
00193                         pinForConnect = "";
00194                     }
00195
00196                     manager.NotifyUser("Accepting session request...", NotifyType.StatusMessage);
00197
00198                     if (pinForConnect.Length > 0)
00199                     {
00200                         // NOTE: This MUST be called from the UI thread
00201                         session = await advertiser.ConnectAsync(request.DeviceInformation, pinForConnect);
00202                     }
00203                     else
00204                     {
00205                         // NOTE: This MUST be called from the UI thread
00206                         session = await advertiser.ConnectAsync(request.DeviceInformation);
00207                     }
00208
00209                     manager.NotifyUser("Session request accepted", NotifyType.StatusMessage);
00210
00211                     SessionWrapper sessionWrapper = new SessionWrapper(session, manager);
00212                     manager.AddSession(sessionWrapper);
00213                 }
00214                 catch (Exception ex)
00215                 {
00216                     manager.NotifyUser("AcceptSessionRequest Failed: " + ex.Message, NotifyType.ErrorMessage);
00217                 }
00218             }
00219
00220             public void DeclineSessionRequest(string id)
00221             {
00222                 WiFiDirectServiceSessionRequest request = null;
00223
00224                 bool found = false;
00225
00226                 lock (thisLock)
00227                 {
00228                     foreach (var r in requestList)
00229                     {
00230                         if (r.DeviceInformation.Id == id)
00231                         {
00232                             found = true;
00233                             request = r;
00234                         }
00235                     }
00236
00237                     if (!found)
00238                     {
00239                         throw new KeyNotFoundException("Attempted to accept session not found in list");
00240                     }
00241
00242                     requestList.Remove(request);
00243                 }
00244                 manager.RemoveSessionRequest(request, this);
00245
00246                 // Decline incoming requests by disposing the request object
00247                 request.Dispose();
00248                 manager.NotifyUser("Declined Request", NotifyType.StatusMessage);
00249             }
00250
00251             // NOTE: this is mutually exclusive with OnSessionRequested
00252             private void OnAutoAcceptSessionConnected(WiFiDirectServiceAdvertiser sender, WiFiDirectServiceAutoAcceptSessionConnectedEventArgs args)
00253             {
00254                 try
00255                 {
00256                     ThrowIfDisposed();
00257
00258                     string sessionInfo = "";
00259                     if (args.SessionInfo != null && args.SessionInfo.Length > 0)
00260                     {
00261                         using (DataReader sessionInfoDataReader = DataReader.FromBuffer(args.SessionInfo))
00262                         {
00263                             sessionInfo = sessionInfoDataReader.ReadString(args.SessionInfo.Length);
00264                         }
00265                     }
00266
00267                     manager.NotifyUser("Auto-Accept Session Connected: sessionInfo=" + sessionInfo, NotifyType.StatusMessage);
00268
00269                     SessionWrapper sessionWrapper = new SessionWrapper(args.Session, manager);
00270                     manager.AddSession(sessionWrapper);
00271                 }
00272                 catch (Exception ex)
00273                 {
00274                     manager.NotifyUser("OnAutoAcceptSessionConnected Failed: " + ex.Message, NotifyType.ErrorMessage);
00275                 }
00276             }
00277
00278             private void OnAdvertisementStatusChanged(WiFiDirectServiceAdvertiser sender, object args)
00279             {
00280                 try
00281                 {
00282                     ThrowIfDisposed();
00283
00284                     WiFiDirectServiceAdvertisementStatus status = advertiser.AdvertisementStatus;
00285
00286                     manager.NotifyUser("Advertisement Status Changed to " + status.ToString(), NotifyType.StatusMessage);
00287
00288                     manager.AdvertiserStatusChanged(this);
00289                 }
00290                 catch (Exception ex)
00291                 {
00292                     manager.NotifyUser("OnAdvertisementStatusChanged Failed: " + ex.Message, NotifyType.ErrorMessage);
00293                 }
00294             }
00295
00296             #region Dispose
00297             bool disposed = false;
00298
00299             ~AdvertisementWrapper()
00300             {
00301                 Dispose(false);
00302             }
00303
00304             public void Dispose()
00305             {
00306                 Dispose(true);
00307                 GC.SuppressFinalize(this);
00308             }
00309
00310             protected virtual void Dispose(bool disposing)
00311             {
00312                 if (disposed)
00313                 {
00314                     return;
00315                 }
00316
00317                 if (disposing)
00318                 {
00319                     // Stop advertising
00320                     // If for some reason the advertiser is stopping between the time that we check
00321                     // the AdvertisementStatus and when we call Stop, this will throw
00322                     try
00323                     {
00324                         if (advertiser.AdvertisementStatus == WiFiDirectServiceAdvertisementStatus.Started)
00325                         {
00326                             advertiser.Stop();
00327                         }
00328                     }
00329                     catch (Exception)
00330                     {
00331                         // Stop can throw if it is already stopped or stopping, ignore
00332                     }
00333
00334                     // Remove event handlers
00335                     advertiser.AdvertisementStatusChanged -= OnAdvertisementStatusChanged;
00336                     advertiser.AutoAcceptSessionConnected -= OnAutoAcceptSessionConnected;
00337                     advertiser.SessionRequested -= OnSessionRequested;
00338
00339                     foreach (var request in requestList)
00340                     {
00341                         request.Dispose();
00342                     }
00343                     requestList.Clear();
00344                 }
00345
00346                 disposed = true;
00347             }
00348
00349             private void ThrowIfDisposed()
00350             {
00351                 if (disposed)
00352                 {
00353                     throw new ObjectDisposedException("AdvertisementWrapper");
00354                 }
00355             }
00356             #endregion
00357         }
00358
00359         public class DiscoveredDeviceWrapper : IDisposable
00360         {
00361             private DeviceInformation deviceInfo;
00362             // Used to update main state
00363             private WiFiDirectServiceManager manager = null;
00364
00365             // When we start opening/connecting to a session we store this (only used for a single connect)
00366             private WiFiDirectService service = null;
00367
00368             public DiscoveredDeviceWrapper(
00369                 DeviceInformation deviceInfo,
00370                 WiFiDirectServiceManager manager
00371                 )
00372             {
00373                 this.deviceInfo = deviceInfo;
00374                 this.manager = manager;
00375
00376                 ParseProperties();
00377             }
00378
00379             private void ParseProperties()
00380             {
00381                 object serviceName;
00382                 if (deviceInfo.Properties.TryGetValue("System.Devices.WiFiDirectServices.ServiceName", out serviceName))
00383                 {
00384                     ServiceName = serviceName.ToString();
00385                 }
00386                 else
00387                 {
00388                     ServiceName = "";
00389                 }
00390
00391                 object advertisementId;
00392                 if (deviceInfo.Properties.TryGetValue("System.Devices.WiFiDirectServices.AdvertisementId", out advertisementId))
00393                 {
00394                     AdvertisementId = Convert.ToUInt32(advertisementId, CultureInfo.InvariantCulture);
00395                 }
00396                 else
00397                 {
00398                     AdvertisementId = 0;
00399                 }
00400
00401                 object configMethods;
00402                 if (deviceInfo.Properties.TryGetValue("System.Devices.WiFiDirectServices.ServiceConfigMethods", out configMethods))
00403                 {
00404                     ConfigMethods = Convert.ToUInt32(configMethods, CultureInfo.InvariantCulture);
00405                 }
00406                 else
00407                 {
00408                     ConfigMethods = 0;
00409                 }
00410
00411                 object serviceAddress;
00412                 if (deviceInfo.Properties.TryGetValue("System.Devices.WiFiDirectServices.ServiceAddress", out serviceAddress))
00413                 {
00414                     byte[] macBuffer = (byte[])serviceAddress;
00415
00416                     ServiceAddress = "";
00417                     foreach (byte octet in macBuffer)
00418                     {
00419                         ServiceAddress += octet.ToString("X2", CultureInfo.InvariantCulture) + ":";
00420                     }
00421                     if (ServiceAddress.Length > 0)
00422                     {
00423                         ServiceAddress = ServiceAddress.Substring(0, ServiceAddress.Length - 1);
00424                     }
00425                 }
00426                 else
00427                 {
00428                     ServiceAddress = "XX:XX:XX:XX:XX:XX";
00429                 }
00430
00431                 ServiceInfo = "";
00432                 object serviceInfo;
00433                 if (deviceInfo.Properties.TryGetValue("System.Devices.WiFiDirectServices.ServiceInformation", out serviceInfo))
00434                 {
00435                     if (serviceInfo != null)
00436                     {
00437                         IBuffer serviceInfoBuffer;
00438                         using (var tempStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
00439                         {
00440                             using (var serviceInfoDataWriter = new DataWriter(tempStream))
00441                             {
00442                                 serviceInfoDataWriter.WriteBytes((Byte[])serviceInfo);
00443                                 serviceInfoBuffer = serviceInfoDataWriter.DetachBuffer();
00444                             }
00445                         }
00446
00447                         using (DataReader serviceInfoDataReader = DataReader.FromBuffer(serviceInfoBuffer))
00448                         {
00449                             ServiceInfo = serviceInfoDataReader.ReadString(serviceInfoBuffer.Length);
00450                         }
00451                     }
00452                 }
00453             }
00454
00455             // Expose properties from the discovered device
00456             public string ServiceName { get; private set; }
00457             public string ServiceAddress { get; private set; }
00458             public UInt32 AdvertisementId { get; private set; }
00459             public UInt32 ConfigMethods { get; private set; }
00460             public string ServiceInfo { get; private set; }
00461
00462             /// <summary>
00463             /// Calls WiFiDirectService.FromId to open the seeker session
00464             /// Caller can then use this.Service to modify settings before connecting
00465             /// </summary>
00466             public async Task OpenSessionAsync()
00467             {
00468                 ThrowIfDisposed();
00469
00470                 // This wrapper can only be used for FromIdAsync once
00471                 if (service != null)
00472                 {
00473                     throw new Exception("Attempted to connect to discovered service a second time!");
00474                 }
00475
00476                 manager.NotifyUser("Open session...", NotifyType.StatusMessage);
00477
00478                 try
00479                 {
00480                     // NOTE: This MUST be called from the UI thread
00481                     service = await WiFiDirectService.FromIdAsync(deviceInfo.Id);
00482                     service.SessionDeferred += OnSessionDeferred;
00483                 }
00484                 catch (Exception ex)
00485                 {
00486                     manager.NotifyUser("FromIdAsync Failed: " + ex.Message, NotifyType.ErrorMessage);
00487                 }
00488             }
00489
00490             /// <summary>
00491             /// Call this to set options before doing the actual connect
00492             /// </summary>
00493             /// <param name="preferGO">If true, this peer will prefer to be the group owner (GO) of the connection</param>
00494             /// <param name="sessionInfo">Optional 144 byte buffer to send with the request to the advertising peer</param>
00495             public async Task SetServiceOptionsAsync(bool preferGO, string sessionInfo)
00496             {
00497                 ThrowIfDisposed();
00498
00499                 // Must call FromIdAsync first
00500                 if (service == null)
00501                 {
00502                     await OpenSessionAsync();
00503                 }
00504
00505                 service.PreferGroupOwnerMode = preferGO;
00506
00507                 if (sessionInfo != "")
00508                 {
00509                     using (var sessionInfoDataWriter = new DataWriter(new InMemoryRandomAccessStream()))
00510                     {
00511                         sessionInfoDataWriter.WriteString(sessionInfo);
00512                         service.SessionInfo = sessionInfoDataWriter.DetachBuffer();
00513                     }
00514                 }
00515                 else
00516                 {
00517                     service.SessionInfo = null;
00518                 }
00519             }
00520
00521             /// <summary>
00522             /// Calls service.GetProvisioningInfoAsync to begin provision discovery and
00523             /// determine if a PIN will be needed to connect
00524             /// </summary>
00525             /// <param name="configMethod">Selected Config Method to use, based on supported config methods of discovered device</param>
00526             public async Task<WiFiDirectServiceProvisioningInfo> GetProvisioningInfoAsync(
00527                 WiFiDirectServiceConfigurationMethod configMethod
00528                 )
00529             {
00530                 WiFiDirectServiceProvisioningInfo provisioningInfo = null;
00531                 ThrowIfDisposed();
00532
00533                 // Must call FromIdAsync first
00534                 if (service == null)
00535                 {
00536                     await OpenSessionAsync();
00537                 }
00538
00539                 manager.NotifyUser("Get provisioning info...", NotifyType.StatusMessage);
00540
00541                 try
00542                 {
00543                     provisioningInfo = await service.GetProvisioningInfoAsync(configMethod);
00544
00545                     if (provisioningInfo.IsGroupFormationNeeded)
00546                     {
00547                         if (provisioningInfo.SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod.PinDisplay)
00548                         {
00549                             // UI should display the PIN and pass it into the call to Connect
00550                             manager.NotifyUser("Group Formation is needed, should DISPLAY PIN", NotifyType.StatusMessage);
00551                         }
00552                         else if (provisioningInfo.SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod.PinEntry)
00553                         {
00554                             // UI should take PIN as input and pass it into the call to Connect
00555                             manager.NotifyUser("Group Formation is needed, should ENTER PIN", NotifyType.StatusMessage);
00556                         }
00557                         else
00558                         {
00559                             manager.NotifyUser("Group Formation is needed, no PIN required", NotifyType.StatusMessage);
00560                         }
00561                     }
00562                     else
00563                     {
00564                         manager.NotifyUser("Group Formation is not needed", NotifyType.StatusMessage);
00565                     }
00566                 }
00567                 catch (Exception ex)
00568                 {
00569                     // This could fail due to driver or network issues
00570                     manager.NotifyUser("GetProvisioningInfoAsync Failed: " + ex.Message, NotifyType.ErrorMessage);
00571                 }
00572
00573                 return provisioningInfo;
00574             }
00575
00576             /// <summary>
00577             /// Calls service.ConnectAsync() to connect the session
00578             /// If the session is not already opened, it calls OpenSessionAsync
00579             /// </summary>
00580             /// <param name="pin">Optional PIN if needed</param>
00581             public async void ConnectAsync(string pin = "")
00582             {
00583                 ThrowIfDisposed();
00584
00585                 // Must call FromIdAsync first
00586                 if (service == null)
00587                 {
00588                     await OpenSessionAsync();
00589                 }
00590
00591                 WiFiDirectServiceSession session = null;
00592
00593                 manager.NotifyUser("Connecting...", NotifyType.StatusMessage);
00594
00595                 try
00596                 {
00597                     if (pin.Length > 0)
00598                     {
00599                         session = await service.ConnectAsync(pin);
00600                     }
00601                     else
00602                     {
00603                         session = await service.ConnectAsync();
00604                     }
00605
00606                     manager.NotifyUser("Done Connecting", NotifyType.StatusMessage);
00607
00608                     // Now we are done with this WiFiDirectService instance
00609                     // Clear state so a new connection can be started
00610                     service.SessionDeferred -= OnSessionDeferred;
00611                     service = null;
00612
00613                     SessionWrapper sessionWrapper = new SessionWrapper(session, manager);
00614                     manager.AddSession(sessionWrapper);
00615                 }
00616                 catch (Exception ex)
00617                 {
00618                     // This could fail due to driver or network issues
00619                     manager.NotifyUser("ConnectAsync Failed: " + ex.Message, NotifyType.ErrorMessage);
00620                 }
00621             }
00622
00623             private void OnSessionDeferred(WiFiDirectService sender, WiFiDirectServiceSessionDeferredEventArgs args)
00624             {
00625                 string deferredSessionInfo = "";
00626                 if (args.DeferredSessionInfo != null && args.DeferredSessionInfo.Length > 0)
00627                 {
00628                     using (DataReader sessionInfoDataReader = DataReader.FromBuffer(args.DeferredSessionInfo))
00629                     {
00630                         deferredSessionInfo = sessionInfoDataReader.ReadString(args.DeferredSessionInfo.Length);
00631                     }
00632                 }
00633
00634                 manager.NotifyUser("Session Connection was deferred... (" + deferredSessionInfo + ")", NotifyType.StatusMessage);
00635             }
00636
00637             #region Dispose
00638             bool disposed = false;
00639
00640             ~DiscoveredDeviceWrapper()
00641             {
00642                 Dispose(false);
00643             }
00644
00645             public void Dispose()
00646             {
00647                 Dispose(true);
00648                 GC.SuppressFinalize(this);
00649             }
00650
00651             protected virtual void Dispose(bool disposing)
00652             {
00653                 if (disposed)
00654                 {
00655                     return;
00656                 }
00657
00658                 if (disposing)
00659                 {
00660                     if (service != null)
00661                     {
00662                         service.SessionDeferred -= OnSessionDeferred;
00663                     }
00664                 }
00665
00666                 disposed = true;
00667             }
00668
00669             private void ThrowIfDisposed()
00670             {
00671                 if (disposed)
00672                 {
00673                     throw new ObjectDisposedException("DiscoveredDeviceWrapper");
00674                 }
00675             }
00676             #endregion
00677         }
00678
00679         public class SessionWrapper : IDisposable
00680         {
00681             private WiFiDirectServiceSession session;
00682             // Used to update main state
00683             private WiFiDirectServiceManager manager = null;
00684
00685             // Stream Socket Listeners are created when locally opening TCP ports
00686             private IList<StreamSocketListenerWrapper> streamSocketListeners = new List<StreamSocketListenerWrapper>();
00687
00688             // Keep a list of connected sockets
00689             private IList<SocketWrapper> socketList = new List<SocketWrapper>();
00690
00691             // Used to wait for the session to close before cleaning up the wrapper
00692             private AutoResetEvent sessionClosedEvent = new AutoResetEvent(false);
00693
00694             public SessionWrapper(
00695                 WiFiDirectServiceSession session,
00696                 WiFiDirectServiceManager manager)
00697             {
00698                 this.session = session;
00699                 this.manager = manager;
00700
00701                 this.session.SessionStatusChanged += OnSessionStatusChanged;
00702                 this.session.RemotePortAdded += OnRemotePortAdded;
00703             }
00704
00705             public WiFiDirectServiceSession Session
00706             {
00707                 get { return session; }
00708             }
00709
00710             public uint AdvertisementId
00711             {
00712                 get { return session.AdvertisementId; }
00713             }
00714             public uint SessionId
00715             {
00716                 get { return session.SessionId; }
00717             }
00718
00719             public string ServiceAddress
00720             {
00721                 get { return session.ServiceAddress; }
00722             }
00723
00724             public string SessionAddress
00725             {
00726                 get { return session.SessionAddress; }
00727             }
00728
00729             public IList<SocketWrapper> SocketList
00730             {
00731                 get { return socketList; }
00732             }
00733
00734             public void Close()
00735             {
00736                 ThrowIfDisposed();
00737
00738                 foreach (var socket in socketList)
00739                 {
00740                     socket.Dispose();
00741                 }
00742                 socketList.Clear();
00743
00744                 session.Dispose();
00745
00746                 // Wait for status change
00747                 // NOTE: this should complete in 5 seconds under normal circumstances
00748                 if (!sessionClosedEvent.WaitOne(60000))
00749                 {
00750                     throw new Exception("Timed out waiting for session to close");
00751                 }
00752             }
00753
00754             public async void AddStreamSocketListenerAsync(UInt16 port)
00755             {
00756                 ThrowIfDisposed();
00757
00758                 manager.NotifyUser("Adding stream socket listener for TCP port " + port, NotifyType.StatusMessage);
00759
00760                 var endpointPairCollection = session.GetConnectionEndpointPairs();
00761
00762                 // Create listener for socket connection (and add to list to cleanup later)
00763                 StreamSocketListener listenerSocket = new StreamSocketListener();
00764                 StreamSocketListenerWrapper listenerWrapper = new StreamSocketListenerWrapper(
00765                     manager,
00766                     listenerSocket,
00767                     this
00768                     );
00769
00770                 try
00771                 {
00772                     manager.NotifyUser("BindEndpointAsync...", NotifyType.StatusMessage);
00773                     await listenerSocket.BindEndpointAsync(endpointPairCollection[0].LocalHostName, Convert.ToString(port, CultureInfo.InvariantCulture));
00774                     manager.NotifyUser("BindEndpointAsync Done", NotifyType.StatusMessage);
00775
00776                     manager.NotifyUser("AddStreamSocketListenerAsync...", NotifyType.StatusMessage);
00777                     await session.AddStreamSocketListenerAsync(listenerSocket);
00778                     manager.NotifyUser("AddStreamSocketListenerAsync Done", NotifyType.StatusMessage);
00779                 }
00780                 catch (Exception ex)
00781                 {
00782                     manager.NotifyUser("AddStreamSocketListenerAsync Failed: " + ex.Message, NotifyType.ErrorMessage);
00783                 }
00784
00785                 streamSocketListeners.Add(listenerWrapper);
00786             }
00787
00788             public async void AddDatagramSocketAsync(UInt16 port)
00789             {
00790                 ThrowIfDisposed();
00791
00792                 manager.NotifyUser("Adding stream socket listener for UDP port " + port, NotifyType.StatusMessage);
00793
00794                 var endpointPairCollection = session.GetConnectionEndpointPairs();
00795
00796                 DatagramSocket socket = new DatagramSocket();
00797                 // Socket is "read-only", cannot send data but can receive data
00798                 // Expectation is that application starts a listening socket, then remote device sends data
00799                 SocketWrapper socketWrapper = new SocketWrapper(manager, null, socket, false);
00800
00801                 try
00802                 {
00803                     // Bind UDP socket for receiving messages (peer should call connect and send messages to this socket)
00804                     manager.NotifyUser("BindEndpointAsync...", NotifyType.StatusMessage);
00805                     await socket.BindEndpointAsync(endpointPairCollection[0].LocalHostName, Convert.ToString(port, CultureInfo.InvariantCulture));
00806                     manager.NotifyUser("BindEndpointAsync Done", NotifyType.StatusMessage);
00807
00808                     manager.NotifyUser("AddDatagramSocketAsync...", NotifyType.StatusMessage);
00809                     await session.AddDatagramSocketAsync(socket);
00810                     manager.NotifyUser("AddDatagramSocketAsync Done", NotifyType.StatusMessage);
00811
00812                     // Update manager so UI can add to list
00813                     manager.AddSocket(socketWrapper);
00814                 }
00815                 catch (Exception ex)
00816                 {
00817                     manager.NotifyUser("AddDatagramSocketAsync Failed: " + ex.Message, NotifyType.ErrorMessage);
00818                 }
00819
00820                 socketList.Add(socketWrapper);
00821             }
00822
00823             // This will fire when the connected peer attempts to open a port for this connection
00824             // The peer should start a stream socket listener (for TCP)
00825             private async void OnRemotePortAdded(WiFiDirectServiceSession sender, WiFiDirectServiceRemotePortAddedEventArgs args)
00826             {
00827                 try
00828                 {
00829                     ThrowIfDisposed();
00830
00831                     var endpointPairCollection = args.EndpointPairs;
00832                     var protocol = args.Protocol;
00833                     if (endpointPairCollection.Count == 0)
00834                     {
00835                         manager.NotifyUser("No endpoint pairs for remote port added event", NotifyType.ErrorMessage);
00836                         return;
00837                     }
00838
00839                     manager.NotifyUser(String.Format("{0} Port {1} Added by remote peer",
00840                         (protocol == WiFiDirectServiceIPProtocol.Tcp) ? "TCP" : ((protocol == WiFiDirectServiceIPProtocol.Udp) ? "UDP" : "???"),
00841                         endpointPairCollection[0].RemoteServiceName
00842                         ),
00843                         NotifyType.StatusMessage
00844                         );
00845
00846                     SocketWrapper socketWrapper = null;
00847
00848                     if (args.Protocol == WiFiDirectServiceIPProtocol.Tcp)
00849                     {
00850                         // Connect to the stream socket listener
00851                         StreamSocket streamSocket = new StreamSocket();
00852                         socketWrapper = new SocketWrapper(manager, streamSocket, null, true);
00853
00854                         manager.NotifyUser("Connecting to stream socket...", NotifyType.StatusMessage);
00855                         await streamSocket.ConnectAsync(endpointPairCollection[0]);
00856                         // Start receiving messages recursively
00857                         var rcv = socketWrapper.ReceiveMessageAsync();
00858                         manager.NotifyUser("Stream socket connected", NotifyType.StatusMessage);
00859                     }
00860                     else if (args.Protocol == WiFiDirectServiceIPProtocol.Udp)
00861                     {
00862                         // Connect a socket over UDP
00863                         DatagramSocket datagramSocket = new DatagramSocket();
00864                         socketWrapper = new SocketWrapper(manager, null, datagramSocket, true);
00865
00866                         manager.NotifyUser("Connecting to datagram socket...", NotifyType.StatusMessage);
00867                         await datagramSocket.ConnectAsync(endpointPairCollection[0]);
00868                         manager.NotifyUser("Datagram socket connected", NotifyType.StatusMessage);
00869                     }
00870                     else
00871                     {
00872                         manager.NotifyUser("Bad protocol for remote port added event", NotifyType.ErrorMessage);
00873                         return;
00874                     }
00875
00876                     socketList.Add(socketWrapper);
00877                     // Update manager so UI can add to list
00878                     manager.AddSocket(socketWrapper);
00879                 }
00880                 catch (Exception ex)
00881                 {
00882                     manager.NotifyUser("OnRemotePortAdded Failed: " + ex.Message, NotifyType.ErrorMessage);
00883                 }
00884             }
00885
00886             public void AddStreamSocketInternal(StreamSocket socket)
00887             {
00888                 SocketWrapper socketWrapper = new SocketWrapper(manager, socket, null, true);
00889
00890                 // Start receiving messages recursively
00891                 var rcv = socketWrapper.ReceiveMessageAsync();
00892
00893                 socketList.Add(socketWrapper);
00894                 // Update manager so UI can add to list
00895                 manager.AddSocket(socketWrapper);
00896             }
00897
00898             private void OnSessionStatusChanged(WiFiDirectServiceSession sender, object args)
00899             {
00900                 try
00901                 {
00902                     ThrowIfDisposed();
00903
00904                     manager.NotifyUser("Session Status Changed to " + session.Status.ToString(), NotifyType.StatusMessage);
00905
00906                     if (session.Status == WiFiDirectServiceSessionStatus.Closed)
00907                     {
00908                         sessionClosedEvent.Set();
00909                         // Cleanup
00910                         manager.RemoveSession(this);
00911                     }
00912                 }
00913                 catch (Exception ex)
00914                 {
00915                     manager.NotifyUser("OnSessionStatusChanged Failed: " + ex.Message, NotifyType.ErrorMessage);
00916                 }
00917             }
00918
00919             #region Dispose
00920             bool disposed = false;
00921
00922             ~SessionWrapper()
00923             {
00924                 Dispose(false);
00925             }
00926
00927             public void Dispose()
00928             {
00929                 Dispose(true);
00930                 GC.SuppressFinalize(this);
00931             }
00932
00933             protected virtual void Dispose(bool disposing)
00934             {
00935                 if (disposed)
00936                 {
00937                     return;
00938                 }
00939
00940                 if (disposing)
00941                 {
00942                     // This will close the session
00943                     session.Dispose();
00944
00945                     // Remove event handlers
00946                     session.SessionStatusChanged -= OnSessionStatusChanged;
00947                     session.RemotePortAdded -= OnRemotePortAdded;
00948
00949                     foreach (var listener in streamSocketListeners)
00950                     {
00951                         listener.Dispose();
00952                     }
00953                     streamSocketListeners.Clear();
00954
00955                     foreach (var socket in socketList)
00956                     {
00957                         socket.Dispose();
00958                     }
00959                     socketList.Clear();
00960
00961                     sessionClosedEvent.Dispose();
00962                 }
00963
00964                 disposed = true;
00965             }
00966
00967             private void ThrowIfDisposed()
00968             {
00969                 if (disposed)
00970                 {
00971                     throw new ObjectDisposedException("SessionWrapper");
00972                 }
00973             }
00974             #endregion
00975         }
00976
00977         public class StreamSocketListenerWrapper : IDisposable
00978         {
00979             private StreamSocketListener streamSocketListener;
00980             // Used to update main state
00981             private WiFiDirectServiceManager manager = null;
00982
00983             private SessionWrapper session = null;
00984
00985             public StreamSocketListenerWrapper(
00986                 WiFiDirectServiceManager manager,
00987                 StreamSocketListener streamSocketListener,
00988                 SessionWrapper session
00989                 )
00990             {
00991                 this.streamSocketListener = streamSocketListener;
00992                 this.session = session;
00993                 this.manager = manager;
00994
00995                 this.streamSocketListener.ConnectionReceived += OnConnectionReceived;
00996             }
00997
00998             private void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
00999             {
01000                 manager.NotifyUser("Connection received for TCP Port " + sender.Information.LocalPort, NotifyType.StatusMessage);
01001
01002                 session.AddStreamSocketInternal(args.Socket);
01003             }
01004
01005             #region Dispose
01006             bool disposed = false;
01007
01008             ~StreamSocketListenerWrapper()
01009             {
01010                 Dispose(false);
01011             }
01012
01013             public void Dispose()
01014             {
01015                 Dispose(true);
01016                 GC.SuppressFinalize(this);
01017             }
01018
01019             protected virtual void Dispose(bool disposing)
01020             {
01021                 if (disposed)
01022                 {
01023                     return;
01024                 }
01025
01026                 if (disposing)
01027                 {
01028                     try
01029                     {
01030                         streamSocketListener.ConnectionReceived -= OnConnectionReceived;
01031                     }
01032                     catch (Exception)
01033                     { }
01034
01035                     streamSocketListener.Dispose();
01036                 }
01037
01038                 disposed = true;
01039             }
01040
01041             private void ThrowIfDisposed()
01042             {
01043                 if (disposed)
01044                 {
01045                     throw new ObjectDisposedException("StreamSocketListenerWrapper");
01046                 }
01047             }
01048             #endregion
01049         }
01050
01051         // Generic wrapper for TCP (Stream) or UDP (Datagram) socket
01052         // For this sample, this just allows messages to be sent between connected peers,
01053         // real application would handle higher level logic over the connected socket(s)
01054         public class SocketWrapper : IDisposable
01055         {
01056             private StreamSocket streamSocket = null;
01057             private DatagramSocket datagramSocket = null;
01058             // Used to update main state
01059             private WiFiDirectServiceManager manager = null;
01060
01061             private DataReader reader = null;
01062             private DataWriter writer;
01063
01064             public SocketWrapper(
01065                 WiFiDirectServiceManager manager,
01066                 StreamSocket streamSocket = null,
01067                 DatagramSocket datagramSocket = null,
01068                 bool canSend = true)
01069             {
01070                 this.streamSocket = streamSocket;
01071                 this.datagramSocket = datagramSocket;
01072                 this.manager = manager;
01073
01074                 if (streamSocket == null && datagramSocket == null)
01075                 {
01076                     throw new Exception("Bad SocketWrapper parameters, must provide a TCP or UDP socket");
01077                 }
01078                 else if (streamSocket != null && datagramSocket != null)
01079                 {
01080                     throw new Exception("Bad SocketWrapper parameters, got both TCP and UDP socket, expected only one");
01081                 }
01082                 else if (streamSocket != null)
01083                 {
01084                     reader = new DataReader(streamSocket.InputStream);
01085                     if (canSend)
01086                     {
01087                         writer = new DataWriter(streamSocket.OutputStream);
01088                     }
01089                 }
01090                 else
01091                 {
01092                     datagramSocket.MessageReceived += OnUDPMessageReceived;
01093                     if (canSend)
01094                     {
01095                         writer = new DataWriter(datagramSocket.OutputStream);
01096                     }
01097                 }
01098
01099                 if (reader != null)
01100                 {
01101                     reader.UnicodeEncoding = UnicodeEncoding.Utf8;
01102                     reader.ByteOrder = ByteOrder.LittleEndian;
01103                 }
01104
01105                 if (writer != null)
01106                 {
01107                     writer.UnicodeEncoding = UnicodeEncoding.Utf8;
01108                     writer.ByteOrder = ByteOrder.LittleEndian;
01109                 }
01110             }
01111
01112             public string Protocol
01113             {
01114                 get
01115                 {
01116                     if (streamSocket != null)
01117                     {
01118                         return "TCP";
01119                     }
01120                     else if (datagramSocket != null)
01121                     {
01122                         return "UDP";
01123                     }
01124                     else
01125                     {
01126                         return "???";
01127                     }
01128                 }
01129             }
01130
01131             public string Port
01132             {
01133                 get
01134                 {
01135                     if (streamSocket != null)
01136                     {
01137                         return streamSocket.Information.LocalPort;
01138                     }
01139                     else if (datagramSocket != null)
01140                     {
01141                         return datagramSocket.Information.LocalPort;
01142                     }
01143                     else
01144                     {
01145                         return "???";
01146                     }
01147                 }
01148             }
01149
01150             /// <summary>
01151             /// Send a string over the socket (TCP or UDP)
01152             /// Will send as a uint32 size followed by the message
01153             /// </summary>
01154             /// <param name="message">Message to send</param>
01155             public async Task SendMessageAsync(string message)
01156             {
01157                 try
01158                 {
01159                     ThrowIfDisposed();
01160
01161                     if (writer == null)
01162                     {
01163                         manager.NotifyUser("Socket is unable to send messages (receive only socket).", NotifyType.ErrorMessage);
01164                     }
01165                     else
01166                     {
01167                         writer.WriteUInt32(writer.MeasureString(message));
01168                         writer.WriteString(message);
01169                         await writer.StoreAsync();
01170
01171                         uint bytesSent = writer.MeasureString(message);
01172
01173                         manager.NotifyUser(String.Format("Sent Message: \"{0}\", {1} bytes",
01174                                 (message.Length > 32) ? message.Substring(0, 32) + "..." : message,
01175                                 bytesSent
01176                                 ),
01177                             NotifyType.StatusMessage
01178                             );
01179                     }
01180                 }
01181                 catch (Exception ex)
01182                 {
01183                     manager.NotifyUser("SendMessageAsync Failed: " + ex.Message, NotifyType.ErrorMessage);
01184                 }
01185             }
01186
01187             /// <summary>
01188             /// Read strings sent over the TCP socket
01189             /// Reads the uint32 size then the actual string
01190             /// </summary>
01191             public async Task ReceiveMessageAsync()
01192             {
01193                 await HandleReceivedMessage(this.reader);
01194             }
01195
01196             /// <summary>
01197             /// Handle both TCP receive call and UDP event handler
01198             /// </summary>
01199             /// <param name="datareader"></param>
01200             /// <param name="load">Set to true when the datareader.LoadAsync needs to be called for TCP</param>
01201             /// <returns></returns>
01202             private async Task HandleReceivedMessage(DataReader datareader, bool load = true)
01203             {
01204                 try
01205                 {
01206                     ThrowIfDisposed();
01207                     uint bytesRead = 0;
01208
01209                     if (load)
01210                     {
01211                         bytesRead = await datareader.LoadAsync(sizeof(uint));
01212
01213                         if (bytesRead != sizeof(uint))
01214                         {
01215                             manager.NotifyUser("The underlying socket was closed before we were able to read the whole data.", NotifyType.ErrorMessage);
01216                             return;
01217                         }
01218                     }
01219
01220                     if (!load || bytesRead > 0)
01221                     {
01222                         // Determine how long the string is.
01223                         uint messageLength = (uint)datareader.ReadUInt32();
01224
01225                         if (load)
01226                         {
01227                             bytesRead = await datareader.LoadAsync(messageLength);
01228                             if (bytesRead != messageLength)
01229                             {
01230                                 manager.NotifyUser("The underlying socket was closed before we were able to read the whole data.", NotifyType.ErrorMessage);
01231                                 return;
01232                             }
01233                         }
01234
01235                         if ((!load && messageLength > 0) || bytesRead > 0)
01236                         {
01237                             // Decode the string.
01238                             string currentMessage = datareader.ReadString(messageLength);
01239                             uint bytesReceived = messageLength;
01240
01241                             // Just print a message for now
01242                             manager.NotifyUser(String.Format("Received Message: \"{0}\", {1} bytes",
01243                                     (currentMessage.Length > 32) ? currentMessage.Substring(0, 32) + "..." : currentMessage,
01244                                     bytesReceived
01245                                     ),
01246                                 NotifyType.StatusMessage
01247                                 );
01248
01249                             // TCP will need to call this again, UDP will get callbacks
01250                             if (load)
01251                             {
01252                                 await HandleReceivedMessage(datareader, load);
01253                             }
01254                         }
01255                         else
01256                         {
01257                             manager.NotifyUser("ReceiveMessage 0 bytes loaded for message content.", NotifyType.ErrorMessage);
01258                         }
01259                     }
01260                     else
01261                     {
01262                         manager.NotifyUser("ReceiveMessage 0 bytes loaded for message content.", NotifyType.ErrorMessage);
01263                     }
01264                 }
01265                 catch (Exception ex)
01266                 {
01267                     manager.NotifyUser("HandleReceivedMessage Failed: " + ex.Message, NotifyType.ErrorMessage);
01268                 }
01269             }
01270
01271             private async void OnUDPMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
01272             {
01273                 try
01274                 {
01275                     DataReader udpReader = args.GetDataReader();
01276                     udpReader.UnicodeEncoding = UnicodeEncoding.Utf8;
01277                     udpReader.ByteOrder = ByteOrder.LittleEndian;
01278
01279                     await HandleReceivedMessage(udpReader, false);
01280                 }
01281                 catch (Exception ex)
01282                 {
01283                     manager.NotifyUser("OnUDPMessageReceived Failed: " + ex.Message, NotifyType.ErrorMessage);
01284                 }
01285             }
01286
01287             #region Dispose
01288             bool disposed = false;
01289
01290             ~SocketWrapper()
01291             {
01292                 Dispose(false);
01293             }
01294
01295             public void Dispose()
01296             {
01297                 Dispose(true);
01298                 GC.SuppressFinalize(this);
01299             }
01300
01301             protected virtual void Dispose(bool disposing)
01302             {
01303                 if (disposed)
01304                 {
01305                     return;
01306                 }
01307
01308                 if (disposing)
01309                 {
01310                     if (streamSocket != null)
01311                     {
01312                         streamSocket.Dispose();
01313                     }
01314
01315                     if (datagramSocket != null)
01316                     {
01317                         datagramSocket.Dispose();
01318                         datagramSocket.MessageReceived -= OnUDPMessageReceived;
01319                     }
01320
01321                     if (writer != null)
01322                     {
01323                         writer.Dispose();
01324                     }
01325
01326                     if (reader != null)
01327                     {
01328                         reader.Dispose();
01329                     }
01330                 }
01331
01332                 disposed = true;
01333             }
01334
01335             private void ThrowIfDisposed()
01336             {
01337                 if (disposed)
01338                 {
01339                     throw new ObjectDisposedException("SocketWrapper");
01340                 }
01341             }
01342             #endregion
01343         }
01344     }
01345
01346 }
Generated on Fri Nov 15 2024 22:22:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cpp/Scenario5_Multiple.xaml.cpp Source File

  • XamlCommanding
  • cpp

Scenario5_Multiple.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // Scenario5_Multiple.xaml.cpp
00003 // Implementation of the Scenario5_Multiple class
00004 //
00005
00006 #include "pch.h"
00007 #include "Scenario5_Multiple.xaml.h"
00008
00009 using namespace SDKTemplate;
00010
00011 using namespace Platform;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::UI::Xaml;
00015 using namespace Windows::UI::Xaml::Controls;
00016 using namespace Windows::UI::Xaml::Controls::Primitives;
00017 using namespace Windows::UI::Xaml::Data;
00018 using namespace Windows::UI::Xaml::Input;
00019 using namespace Windows::UI::Xaml::Media;
00020 using namespace Windows::UI::Xaml::Navigation;
00021
00022 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00023
00024 Scenario5_Multiple::Scenario5_Multiple()
00025 {
00026     InitializeComponent();
00027 }
Generated on Fri Nov 15 2024 22:22:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCorrelation/cpp/SkeletalFrameRenderer.h Source File

  • CameraStreamCorrelation
  • cpp

SkeletalFrameRenderer.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace SDKTemplate
00015 {
00016     // Delegate used to map skeletal points from depth space to required display space.
00017     public delegate Windows::Foundation::Point CoordinateTransformationMethod(Windows::Foundation::Numerics::float3);
00018
00019     public ref class SkeletalFrameRenderer sealed : public Windows::UI::Xaml::Controls::Canvas
00020     {
00021     public:
00022         SkeletalFrameRenderer();
00023
00024         /// <summary>
00025         /// Clears all rendered shapes on this canvas.
00026         /// </summary>
00027         void Clear();
00028
00029         /// <summary>
00030         /// Renders a pose tracking frame to this canvas.
00031         /// </summary>
00032         void Render(WindowsPreview::Media::Capture::Frames::PoseTrackingFrame^ frame, CoordinateTransformationMethod^ transformation);
00033
00034     private:
00035         std::vector<Windows::UI::Xaml::Media::Brush^> m_brushes;
00036
00037         static Windows::UI::Xaml::Shapes::Line^ LineTo(
00038             Platform::Array<WindowsPreview::Media::Capture::Frames::TrackedPose>^ poses,
00039             WindowsPreview::Media::Capture::Frames::BodyPart fromBodyPart,
00040             WindowsPreview::Media::Capture::Frames::BodyPart toBodyPart,
00041             CoordinateTransformationMethod^ positionTransformation);
00042     };
00043 } // CameraStreamCorrelation
Generated on Fri Nov 15 2024 22:18:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCoordinateMapper/cpp/Content/ShaderStructures.h Source File

  • CameraStreamCoordinateMapper
  • cpp
  • Content

ShaderStructures.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace CameraStreamCoordinateMapper
00015 {
00016     // Constant buffer used to send MVP matrices to the vertex shader.
00017     struct alignas(16) ModelViewProjectionConstantBuffer
00018     {
00019         DirectX::XMFLOAT4X4 model;
00020         DirectX::XMFLOAT4X4 view;
00021         DirectX::XMFLOAT4X4 projection;
00022     };
00023
00024     struct VertexPositionTex
00025     {
00026         DirectX::XMFLOAT3 pos;
00027         DirectX::XMFLOAT2 tex;
00028     };
00029
00030     struct alignas(16) CameraIntrinsics_Shader
00031     {
00032         uint32_t imageWidth;
00033         uint32_t imageHeight;
00034     };
00035
00036     struct alignas(16) RasterizeDepthMeshConstants_Shader
00037     {
00038         CameraIntrinsics_Shader depthIntrinsics;
00039         CameraIntrinsics_Shader sourceIntrinsics;
00040         CameraIntrinsics_Shader targetIntrinsics;
00041         Windows::Foundation::Numerics::float4x4 depthToSource;
00042         Windows::Foundation::Numerics::float4x4 depthToTarget;
00043         Windows::Foundation::Numerics::float4x4 sourceProjectionMatrix;
00044         Windows::Foundation::Numerics::float4x4 targetProjectionMatrix;
00045         float depthMapUnitsToMeters;
00046         float depthRangeMinimumInMeters;
00047         float depthRangeMaximumInMeters;
00048         uint32_t depthMapImageWidthMinusOne;
00049     };
00050
00051     struct alignas(16) VisualizeDepthMeshConstants_Shader
00052     {
00053         Windows::Foundation::Numerics::float4x4 worldToProj;
00054     };
00055 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cs/Scenario2_DeviceWatcher.xaml.cs Source File

  • DeviceEnumerationAndPairing
  • cs

Scenario2_DeviceWatcher.xaml.cs

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 using System;
00004 using System.Collections.ObjectModel;
00005 using Windows.Devices.Enumeration;
00006 using Windows.Foundation;
00007 using Windows.UI.Core;
00008 using Windows.UI.Xaml;
00009 using Windows.UI.Xaml.Controls;
00010 using Windows.UI.Xaml.Navigation;
00011
00012 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00013
00014 namespace SDKTemplate
00015 {
00016     /// <summary>
00017     /// An empty page that can be used on its own or navigated to within a Frame.
00018     /// </summary>
00019     public sealed partial class Scenario2_DeviceWatcher : Page
00020     {
00021         private MainPage rootPage = MainPage.Current;
00022
00023         private DeviceWatcherHelper deviceWatcherHelper;
00024
00025         private ObservableCollection<DeviceInformationDisplay> resultCollection = new ObservableCollection<DeviceInformationDisplay>();
00026
00027         public Scenario2_DeviceWatcher()
00028         {
00029             this.InitializeComponent();
00030
00031             deviceWatcherHelper = new DeviceWatcherHelper(resultCollection, Dispatcher);
00032         }
00033
00034         protected override void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             resultsListView.ItemsSource = resultCollection;
00037             selectorComboBox.ItemsSource = DeviceSelectorChoices.DeviceWatcherSelectors;
00038             selectorComboBox.SelectedIndex = 0;
00039         }
00040
00041         protected override void OnNavigatedFrom(NavigationEventArgs e)
00042         {
00043             deviceWatcherHelper.Reset();
00044         }
00045
00046         private void StartWatcherButton_Click(object sender, RoutedEventArgs e)
00047         {
00048             StartWatcher();
00049         }
00050
00051         private void StopWatcherButton_Click(object sender, RoutedEventArgs e)
00052         {
00053             StopWatcher();
00054         }
00055
00056         private void StartWatcher()
00057         {
00058             startWatcherButton.IsEnabled = false;
00059             resultCollection.Clear();
00060
00061             // First get the device selector chosen by the UI.
00062             DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;
00063
00064             DeviceWatcher deviceWatcher;
00065             if (null == deviceSelectorInfo.Selector)
00066             {
00067                 // If the a pre-canned device class selector was chosen, call the DeviceClass overload
00068                 deviceWatcher = DeviceInformation.CreateWatcher(deviceSelectorInfo.DeviceClassSelector);
00069             }
00070             else if (deviceSelectorInfo.Kind == DeviceInformationKind.Unknown)
00071             {
00072                 // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
00073                 // Kind will be determined by the selector
00074                 deviceWatcher = DeviceInformation.CreateWatcher(
00075                     deviceSelectorInfo.Selector,
00076                     null // don't request additional properties for this sample
00077                     );
00078             }
00079             else
00080             {
00081                 // Kind is specified in the selector info
00082                 deviceWatcher = DeviceInformation.CreateWatcher(
00083                     deviceSelectorInfo.Selector,
00084                     null, // don't request additional properties for this sample
00085                     deviceSelectorInfo.Kind);
00086             }
00087
00088             rootPage.NotifyUser("Starting Watcher...", NotifyType.StatusMessage);
00089             deviceWatcherHelper.StartWatcher(deviceWatcher);
00090             stopWatcherButton.IsEnabled = true;
00091         }
00092
00093         private void StopWatcher()
00094         {
00095             stopWatcherButton.IsEnabled = false;
00096             deviceWatcherHelper.StopWatcher();
00097             startWatcherButton.IsEnabled = true;
00098         }
00099     }
00100 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cs/Scenario4_PartialReadWrite.xaml.cs Source File

  • WebSocket
  • cs

Scenario4_PartialReadWrite.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.IO;
00014 using System.Threading.Tasks;
00015 using Windows.Foundation;
00016 using Windows.Networking.Sockets;
00017 using Windows.Security.Cryptography.Certificates;
00018 using Windows.Storage.Streams;
00019 using Windows.UI.Core;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Navigation;
00023
00024 namespace SDKTemplate
00025 {
00026     /// <summary>
00027     /// An empty page that can be used on its own or navigated to within a Frame.
00028     /// </summary>
00029     public sealed partial class Scenario4_PartialReadWrite : Page
00030     {
00031         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00032         // as NotifyUser()
00033         MainPage rootPage = MainPage.Current;
00034
00035         private MessageWebSocket messageWebSocket;
00036         private bool busy;
00037
00038         public Scenario4_PartialReadWrite()
00039         {
00040             this.InitializeComponent();
00041             UpdateVisualState();
00042         }
00043
00044         protected override void OnNavigatedFrom(NavigationEventArgs e)
00045         {
00046             CloseSocket();
00047         }
00048
00049         private void UpdateVisualState()
00050         {
00051             if (busy)
00052             {
00053                 VisualStateManager.GoToState(this, "Busy", false);
00054             }
00055             else
00056             {
00057                 bool connected = (messageWebSocket != null);
00058                 VisualStateManager.GoToState(this, connected ? "Connected" : "Disconnected", false);
00059             }
00060         }
00061
00062         private void SetBusy(bool value)
00063         {
00064             busy = value;
00065             UpdateVisualState();
00066         }
00067
00068         private async void OnConnect(object sender, RoutedEventArgs e)
00069         {
00070             SetBusy(true);
00071             await ConnectAsync();
00072             SetBusy(false);
00073         }
00074
00075         private async Task ConnectAsync()
00076         {
00077             if (String.IsNullOrEmpty(ServerAddressField.Text))
00078             {
00079                 rootPage.NotifyUser("Please specify a URI to connect to", NotifyType.ErrorMessage);
00080                 return;
00081             }
00082
00083             // Validating the URI is required since it was received from an untrusted source (user input).
00084             // The URI is validated by calling TryGetUri() that will return null for strings that are not
00085             // valid WebSocket URIs.
00086             // Note that when enabling the text box users may provide URIs to machines on the intrAnet
00087             // or intErnet. In these cases the app requires the "Private Networks (Client and Server)" or
00088             // "Internet (Client)" capability respectively.
00089             Uri server = rootPage.TryGetUri(ServerAddressField.Text);
00090             if (server == null)
00091             {
00092                 return;
00093             }
00094
00095             messageWebSocket = new MessageWebSocket();
00096             messageWebSocket.Control.MessageType = SocketMessageType.Utf8;
00097
00098             // To support receiving event notifications for partial messages, you must set this receive mode.
00099             // If you do not set this mode, you will only receive notifications for complete messages; which is
00100             // the default behavior. Setting to Partial allows us to process partial data as soon as it arrives,
00101             // as opposed to waiting until the EndOfMessage to process the entire data.
00102             messageWebSocket.Control.ReceiveMode = MessageWebSocketReceiveMode.PartialMessage;
00103
00104             messageWebSocket.MessageReceived += MessageReceived;
00105             messageWebSocket.Closed += OnClosed;
00106
00107             if (server.Scheme == "wss")
00108             {
00109                 // WARNING: Only test applications should ignore SSL errors.
00110                 // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle
00111                 // attacks. (Although the connection is secure, the server is not authenticated.)
00112                 // Note that not all certificate validation errors can be ignored.
00113                 // In this case, we are ignoring these errors since the certificate assigned to the localhost
00114                 // URI is self-signed and has subject name = fabrikam.com
00115                 messageWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
00116                 messageWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
00117             }
00118
00119             AppendOutputLine($"Connecting to {server}...");
00120             try
00121             {
00122                 await messageWebSocket.ConnectAsync(server);
00123             }
00124             catch (Exception ex) // For debugging
00125             {
00126                 // Error happened during connect operation.
00127                 messageWebSocket.Dispose();
00128                 messageWebSocket = null;
00129
00130                 AppendOutputLine(MainPage.BuildWebSocketError(ex));
00131                 AppendOutputLine(ex.Message);
00132                 return;
00133             }
00134
00135             rootPage.NotifyUser("Connected", NotifyType.StatusMessage);
00136         }
00137
00138         async void OnSend(object sender, RoutedEventArgs e)
00139         {
00140             SetBusy(true);
00141             await SendAsync();
00142             SetBusy(false);
00143         }
00144
00145         async Task SendAsync()
00146         {
00147             string message = InputField.Text;
00148             if (String.IsNullOrEmpty(message))
00149             {
00150                 rootPage.NotifyUser("Please specify text to send", NotifyType.ErrorMessage);
00151                 return;
00152             }
00153
00154             try
00155             {
00156                 DataWriter messageWriter = new DataWriter();
00157                 messageWriter.WriteString(message);
00158                 IBuffer buffer = messageWriter.DetachBuffer();
00159
00160                 if (EndOfMessageCheckBox.IsChecked == true)
00161                 {
00162                     AppendOutputLine("Sending end of message: " + message);
00163                     await messageWebSocket.SendFinalFrameAsync(buffer);
00164                 }
00165                 else
00166                 {
00167                     AppendOutputLine("Sending partial message: " + message);
00168                     await messageWebSocket.SendNonfinalFrameAsync(buffer);
00169                 }
00170             }
00171             catch (Exception ex)
00172             {
00173                 AppendOutputLine(MainPage.BuildWebSocketError(ex));
00174                 AppendOutputLine(ex.Message);
00175                 return;
00176             }
00177
00178             rootPage.NotifyUser("Send Complete", NotifyType.StatusMessage);
00179         }
00180
00181         private void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
00182         {
00183             // Dispatch the event to the UI thread so we can update UI.
00184             var ignore = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00185             {
00186                 string partialOrCompleted = "Partial";
00187
00188                 if (args.IsMessageComplete)
00189                 {
00190                     partialOrCompleted = "Complete";
00191                 }
00192
00193                 AppendOutputLine(partialOrCompleted + " message received; Type: " + args.MessageType);
00194
00195                 using (DataReader reader = args.GetDataReader())
00196                 {
00197                     reader.UnicodeEncoding = UnicodeEncoding.Utf8;
00198
00199                     try
00200                     {
00201                         // Note that it may be possible for partial UTF8 messages to be split between a character if it
00202                         // extends multiple bytes. We avoid this by using only ASCII characters in this example.
00203                         // Should your application use multi-byte characters, you will need to do checks for broken characters.
00204                         string read = reader.ReadString(reader.UnconsumedBufferLength);
00205                         AppendOutputLine(read);
00206                     }
00207                     catch (Exception ex)
00208                     {
00209                         AppendOutputLine(MainPage.BuildWebSocketError(ex));
00210                         AppendOutputLine(ex.Message);
00211                     }
00212                 }
00213             });
00214         }
00215
00216         private void OnDisconnect(object sender, RoutedEventArgs e)
00217         {
00218             SetBusy(true);
00219             rootPage.NotifyUser("Closing", NotifyType.StatusMessage);
00220             CloseSocket();
00221             SetBusy(false);
00222             rootPage.NotifyUser("Closed", NotifyType.StatusMessage);
00223         }
00224
00225         // This may be triggered remotely by the server or locally by Close/Dispose()
00226         private async void OnClosed(IWebSocket sender, WebSocketClosedEventArgs args)
00227         {
00228             // Dispatch the event to the UI thread so we do not need to synchronize access to messageWebSocket.
00229             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00230             {
00231                 AppendOutputLine("Closed; Code: " + args.Code + ", Reason: " + args.Reason);
00232
00233                 if (messageWebSocket == sender)
00234                 {
00235                     CloseSocket();
00236                     UpdateVisualState();
00237                 }
00238             });
00239         }
00240
00241         private void CloseSocket()
00242         {
00243             if (messageWebSocket != null)
00244             {
00245                 try
00246                 {
00247                     messageWebSocket.Close(1000, "Closed due to user request.");
00248                 }
00249                 catch (Exception ex)
00250                 {
00251                     AppendOutputLine(MainPage.BuildWebSocketError(ex));
00252                     AppendOutputLine(ex.Message);
00253                 }
00254                 messageWebSocket = null;
00255             }
00256         }
00257
00258         private void AppendOutputLine(string value)
00259         {
00260             OutputField.Text += value + "\r\n";
00261         }
00262     }
00263 }
Generated on Fri Nov 15 2024 22:22:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario08_PostCustomContent.h Source File

  • HttpClient
  • cppwinrt

Scenario08_PostCustomContent.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario08_PostCustomContent.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario08_PostCustomContent : Scenario08_PostCustomContentT<Scenario08_PostCustomContent>
00020     {
00021         Scenario08_PostCustomContent();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025
00026         fire_and_forget Start_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         void Cancel_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028
00029     private:
00030         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00031         Windows::Web::Http::HttpClient httpClient{ nullptr };
00032         Windows::Foundation::IAsyncAction pendingAction{ nullptr };
00033
00034         Windows::Foundation::IAsyncAction CancelableRequestAsync(
00035             Windows::Foundation::Uri resourceUri,
00036             Windows::Web::Http::IHttpContent content);
00037     };
00038 }
00039
00040 namespace winrt::SDKTemplate::factory_implementation
00041 {
00042     struct Scenario08_PostCustomContent : Scenario08_PostCustomContentT<Scenario08_PostCustomContent, implementation::Scenario08_PostCustomContent>
00043     {
00044     };
00045 }
Generated on Fri Nov 15 2024 22:19:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameUIControl.h Source File

  • Simple3DGameDX
  • cppwinrt

GameUIControl.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012
00013 // The IGameUIControl interface provides an abstraction to the GameMain class
00014 // for controlling UI elements on the screen in response to game state. It helps to
00015 // provide separation between the game control and how the UI is displayed to the user.
00016 //    SetGameLoading - is called to have the UI indicate the game is currently loading
00017 //        resources for the game or a particular level. GameMain will call this
00018 //        method repeatedly to provide update progress. 'dots' is the number of
00019 //        dots to display to indicate progress.
00020 //    SetGameStats - is called to have the UI indicate the status of the last completed game.
00021 //    SetGameOver - is called to have the UI indicate this iteration of the game as finished.
00022 //    SetLevelStart - is called to have the UI indicate the level is ready to begin. This includes
00023 //        providing the objectives for the level and other current data.
00024 //    SetPause - is called to have the UI indicate the game is currently in the Paused state.
00025 //    ShowTooSmall - this method indicates the UI should display to the user that the current
00026 //        display configuration is too small for the game to be played.
00027 //    HideTooSmall - this method inticates the UI should stop displaying to the user that the
00028 //        current display configuration is too small for game play.
00029 //    SetAction - is called to have the UI indicate the next action the user should take.
00030 //    ShowGameInfoOverlay - is called to have the UI display to the user the current state
00031 //        as defined by the other interface calls above.
00032 //    HideGameInfoOverlay - is called to have the UI remove the display of the current state
00033 //        when the game transitions into active game play.
00034
00035 namespace Simple3DGameDX
00036 {
00037     enum class GameInfoOverlayCommand
00038     {
00039         None,
00040         TapToContinue,
00041         PleaseWait,
00042         PlayAgain,
00043     };
00044
00045     interface IGameUIControl
00046     {
00047         virtual void SetGameLoading(uint32_t dots) = 0;
00048         virtual void SetGameStats(int maxLevel, int hitCount, int shotCount) = 0;
00049         virtual void SetGameOver(bool win, int maxLevel, int hitCount, int shotCount, int highScore) = 0;
00050         virtual void SetLevelStart(int level, std::wstring const& objective, float timeLimit, float bonusTime) = 0;
00051         virtual void SetPause(int level, int hitCount, int shotCount, float timeRemaining) = 0;
00052         virtual void ShowTooSmall() = 0;
00053         virtual void HideTooSmall() = 0;
00054         virtual void SetAction(GameInfoOverlayCommand action) = 0;
00055         virtual void HideGameInfoOverlay() = 0;
00056         virtual void ShowGameInfoOverlay() = 0;
00057     };
00058 };
Generated on Fri Nov 15 2024 22:21:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_PercentPermilleFormatting Member List

This is the complete list of members for Scenario1_PercentPermilleFormatting, including all inherited members.
Display_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_PercentPermilleFormatting
Scenario1_PercentPermilleFormatting() | Scenario1_PercentPermilleFormatting
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

WiFiDirectServiceManager Member List

This is the complete list of members for WiFiDirectServiceManager, including all inherited members.
AddAdvertiser(AdvertisementWrapper advertiser) | WiFiDirectServiceManager | [inline, private]
AddSession(SessionWrapper session) | WiFiDirectServiceManager | [inline]
AddSessionRequest(WiFiDirectServiceSessionRequest request, AdvertisementWrapper advertiser) | WiFiDirectServiceManager | [inline]
AddSocket(SocketWrapper socket) | WiFiDirectServiceManager | [inline]
Advertisers | WiFiDirectServiceManager |
advertisers | WiFiDirectServiceManager | [private]
AdvertiserStatusChanged(AdvertisementWrapper advertiser) | WiFiDirectServiceManager | [inline]
CloseSession(int index) | WiFiDirectServiceManager | [inline]
ConnectedSessionList | WiFiDirectServiceManager |
connectedSessions | WiFiDirectServiceManager | [private]
CurrentSession | WiFiDirectServiceManager |
discoveredDevices | WiFiDirectServiceManager | [private]
DiscoveredDevices | WiFiDirectServiceManager |
DiscoverServicesAsync(string serviceName, string requestedServiceInfo) | WiFiDirectServiceManager | [inline]
Dispose() | WiFiDirectServiceManager | [inline]
Dispose(bool disposing) | WiFiDirectServiceManager | [inline, protected, virtual]
disposed | WiFiDirectServiceManager | [private]
instance | WiFiDirectServiceManager | [private, static]
Instance | WiFiDirectServiceManager | [static]
NotifyUser(string message, NotifyType type) | WiFiDirectServiceManager | [inline]
RemoveAdvertiser(int index) | WiFiDirectServiceManager | [inline, private]
RemoveAdvertiser(AdvertisementWrapper advertiser) | WiFiDirectServiceManager | [inline]
RemoveSession(int index) | WiFiDirectServiceManager | [inline]
RemoveSession(SessionWrapper session) | WiFiDirectServiceManager | [inline]
RemoveSessionRequest(WiFiDirectServiceSessionRequest request, AdvertisementWrapper advertiser) | WiFiDirectServiceManager | [inline]
rootPage | WiFiDirectServiceManager | [private]
RootPage | WiFiDirectServiceManager |
scenario1 | WiFiDirectServiceManager | [private]
Scenario1 | WiFiDirectServiceManager |
scenario2 | WiFiDirectServiceManager | [private]
Scenario2 | WiFiDirectServiceManager |
Scenario3 | WiFiDirectServiceManager |
scenario3 | WiFiDirectServiceManager | [private]
Scenario4 | WiFiDirectServiceManager |
scenario4 | WiFiDirectServiceManager | [private]
scenario5 | WiFiDirectServiceManager | [private]
Scenario5 | WiFiDirectServiceManager |
selectedSession | WiFiDirectServiceManager | [private]
SelectSession(int index) | WiFiDirectServiceManager | [inline]
StartAdvertisement(string serviceName, bool autoAccept, bool preferGO, string pin, IList< WiFiDirectServiceConfigurationMethod > configMethods, WiFiDirectServiceStatus status, uint customStatus, string serviceInfo, string deferredServiceInfo, IList< String > prefixList) | WiFiDirectServiceManager | [inline]
thisLock | WiFiDirectServiceManager | [private]
ThrowIfDisposed() | WiFiDirectServiceManager | [inline, private]
UnpublishService(int index) | WiFiDirectServiceManager | [inline]
WiFiDirectServiceManager() | WiFiDirectServiceManager | [inline, private]
~WiFiDirectServiceManager() | WiFiDirectServiceManager | [inline, private]
Generated on Fri Nov 15 2024 22:24:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CredentialPicker/cpp/pch.h Source File

  • CredentialPicker
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cppwinrt/Scenario2_Launch.cpp Source File

  • ResizeAppView
  • cppwinrt

Scenario2_Launch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Launch.h"
00014 #include "Scenario2_Launch.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::UI::ViewManagement;
00019 using namespace Windows::UI::Xaml;
00020
00021 namespace winrt::SDKTemplate::implementation
00022 {
00023     Scenario2_Launch::Scenario2_Launch()
00024     {
00025         InitializeComponent();
00026         LaunchAtSize().IsChecked(ApplicationView::PreferredLaunchWindowingMode() != ApplicationViewWindowingMode::Auto);
00027     }
00028
00029     // If you set the PreferredLaunchViewSize and PreferredLaunchWindowingMode
00030     // before calling Window.Current.Activate(), then it will take effect
00031     // on the current launch. Otherwise, it takes effect at the next launch.
00032     void Scenario2_Launch::LaunchAtSize_Click(IInspectable const&, RoutedEventArgs const&)
00033     {
00034         if (LaunchAtSize().IsChecked().Value())
00035         {
00036             // For best results, set the PreferredLaunchViewSize before setting
00037             // the PreferredLaunchWindowingMode.
00038             ApplicationView::PreferredLaunchViewSize({ 600, 500 });
00039             ApplicationView::PreferredLaunchWindowingMode(ApplicationViewWindowingMode::PreferredLaunchViewSize);
00040         }
00041         else
00042         {
00043             ApplicationView::PreferredLaunchWindowingMode(ApplicationViewWindowingMode::Auto);
00044         }
00045     }
00046 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Inclinometer/cs/Scenario1_DataEvents.xaml.cs Source File

  • Inclinometer
  • cs

Scenario1_DataEvents.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using System;
00017 using Windows.Devices.Sensors;
00018 using Windows.Foundation;
00019 using System.Threading.Tasks;
00020 using Windows.UI.Core;
00021
00022 namespace InclinometerCS
00023 {
00024     public sealed partial class Scenario1_DataEvents : Page
00025     {
00026         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00027         // as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         private Inclinometer _inclinometer;
00031         private uint _desiredReportInterval;
00032
00033         public Scenario1_DataEvents()
00034         {
00035             this.InitializeComponent();
00036
00037             _inclinometer = Inclinometer.GetDefault();
00038             if (_inclinometer != null)
00039             {
00040                 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00041                 // This value will be used later to activate the sensor.
00042                 uint minReportInterval = _inclinometer.MinimumReportInterval;
00043                 _desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00044             }
00045             else
00046             {
00047                 rootPage.NotifyUser("No inclinometer found", NotifyType.ErrorMessage);
00048             }
00049         }
00050
00051         /// <summary>
00052         /// Invoked when this page is about to be displayed in a Frame.
00053         /// </summary>
00054         /// <param name="e">Event data that describes how this page was reached. The Parameter
00055         /// property is typically used to configure the page.</param>
00056         protected override void OnNavigatedTo(NavigationEventArgs e)
00057         {
00058             ScenarioEnableButton.IsEnabled = true;
00059             ScenarioDisableButton.IsEnabled = false;
00060         }
00061
00062         /// <summary>
00063         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00064         /// </summary>
00065         /// <param name="e">
00066         /// Event data that can be examined by overriding code. The event data is representative
00067         /// of the navigation that will unload the current Page unless canceled. The
00068         /// navigation can potentially be canceled by setting Cancel.
00069         /// </param>
00070         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00071         {
00072             if (ScenarioDisableButton.IsEnabled)
00073             {
00074                 Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00075                 _inclinometer.ReadingChanged -= new TypedEventHandler<Inclinometer, InclinometerReadingChangedEventArgs>(ReadingChanged);
00076
00077                 // Restore the default report interval to release resources while the sensor is not in use
00078                 _inclinometer.ReportInterval = 0;
00079             }
00080
00081             base.OnNavigatingFrom(e);
00082         }
00083
00084         /// <summary>
00085         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00086         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00087         /// </summary>
00088         /// <param name="sender"></param>
00089         /// <param name="e">
00090         /// Event data that can be examined for the current visibility state.
00091         /// </param>
00092         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00093         {
00094             if (ScenarioDisableButton.IsEnabled)
00095             {
00096                 if (e.Visible)
00097                 {
00098                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00099                     _inclinometer.ReadingChanged += new TypedEventHandler<Inclinometer, InclinometerReadingChangedEventArgs>(ReadingChanged);
00100                 }
00101                 else
00102                 {
00103                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00104                     _inclinometer.ReadingChanged -= new TypedEventHandler<Inclinometer, InclinometerReadingChangedEventArgs>(ReadingChanged);
00105                 }
00106             }
00107         }
00108
00109         /// <summary>
00110         /// This is the event handler for ReadingChanged events.
00111         /// </summary>
00112         /// <param name="sender"></param>
00113         /// <param name="e"></param>
00114         async private void ReadingChanged(object sender, InclinometerReadingChangedEventArgs e)
00115         {
00116             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00117             {
00118                 InclinometerReading reading = e.Reading;
00119                 ScenarioOutput_X.Text = String.Format("{0,5:0.00}", reading.PitchDegrees);
00120                 ScenarioOutput_Y.Text = String.Format("{0,5:0.00}", reading.RollDegrees);
00121                 ScenarioOutput_Z.Text = String.Format("{0,5:0.00}", reading.YawDegrees);
00122                 switch (reading.YawAccuracy)
00123                 {
00124                     case MagnetometerAccuracy.Unknown:
00125                         ScenarioOutput_YawAccuracy.Text = "Unknown";
00126                         break;
00127                     case MagnetometerAccuracy.Unreliable:
00128                         ScenarioOutput_YawAccuracy.Text = "Unreliable";
00129                         break;
00130                     case MagnetometerAccuracy.Approximate:
00131                         ScenarioOutput_YawAccuracy.Text = "Approximate";
00132                         break;
00133                     case MagnetometerAccuracy.High:
00134                         ScenarioOutput_YawAccuracy.Text = "High";
00135                         break;
00136                     default:
00137                         ScenarioOutput_YawAccuracy.Text = "No data";
00138                         break;
00139                 }
00140             });
00141         }
00142
00143         /// <summary>
00144         /// This is the click handler for the 'Enable' button.
00145         /// </summary>
00146         /// <param name="sender"></param>
00147         /// <param name="e"></param>
00148         private void ScenarioEnable(object sender, RoutedEventArgs e)
00149         {
00150             if (_inclinometer != null)
00151             {
00152                 // Establish the report interval
00153                 _inclinometer.ReportInterval = _desiredReportInterval;
00154
00155                 Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged);
00156                 _inclinometer.ReadingChanged += new TypedEventHandler<Inclinometer, InclinometerReadingChangedEventArgs>(ReadingChanged);
00157
00158                 ScenarioEnableButton.IsEnabled = false;
00159                 ScenarioDisableButton.IsEnabled = true;
00160             }
00161             else
00162             {
00163                 rootPage.NotifyUser("No inclinometer found", NotifyType.ErrorMessage);
00164             }
00165         }
00166
00167         /// <summary>
00168         /// This is the click handler for the 'Disable' button.
00169         /// </summary>
00170         /// <param name="sender"></param>
00171         /// <param name="e"></param>
00172         private void ScenarioDisable(object sender, RoutedEventArgs e)
00173         {
00174             Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00175             _inclinometer.ReadingChanged -= new TypedEventHandler<Inclinometer, InclinometerReadingChangedEventArgs>(ReadingChanged);
00176
00177             // Restore the default report interval to release resources while the sensor is not in use
00178             _inclinometer.ReportInterval = 0;
00179
00180             ScenarioEnableButton.IsEnabled = true;
00181             ScenarioDisableButton.IsEnabled = false;
00182         }
00183     }
00184 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7_ListAllCards Member List

This is the complete list of members for Scenario7_ListAllCards, including all inherited members.
ListSmartCard_Click(object sender, RoutedEventArgs e) | Scenario7_ListAllCards | [inline, private]
rootPage | Scenario7_ListAllCards | [private]
Scenario7_ListAllCards() | Scenario7_ListAllCards | [inline]
Generated on Fri Nov 15 2024 22:23:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CompletedCallback Member List

This is the complete list of members for CompletedCallback, including all inherited members.
CompletedCallback() | CompletedCallback | [inline]
CompletedCallbackButton_Click(object sender, RoutedEventArgs e) | CompletedCallback | [inline, private]
rootPage | CompletedCallback | [private]
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cppwinrt/Common/DeviceResources.h Source File

  • BasicHologram
  • cppwinrt
  • Common

DeviceResources.h

Go to the documentation of this file.
00001 ﻿
00002 #pragma once
00003
00004 #include "CameraResources.h"
00005
00006 namespace DX
00007 {
00008     // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created.
00009     interface IDeviceNotify
00010     {
00011         virtual void OnDeviceLost() = 0;
00012         virtual void OnDeviceRestored() = 0;
00013     };
00014
00015     // Creates and manages a Direct3D device and immediate context, Direct2D device and context (for debug), and the holographic swap chain.
00016     class DeviceResources
00017     {
00018     public:
00019         DeviceResources();
00020
00021         // Public methods related to Direct3D devices.
00022         void HandleDeviceLost();
00023         void RegisterDeviceNotify(IDeviceNotify* deviceNotify);
00024         void Trim();
00025         void Present(winrt::Windows::Graphics::Holographic::HolographicFrame frame);
00026
00027         // Public methods related to holographic devices.
00028         void SetHolographicSpace(winrt::Windows::Graphics::Holographic::HolographicSpace space);
00029         void EnsureCameraResources(
00030             winrt::Windows::Graphics::Holographic::HolographicFrame frame,
00031             winrt::Windows::Graphics::Holographic::HolographicFramePrediction prediction);
00032
00033         void AddHolographicCamera(winrt::Windows::Graphics::Holographic::HolographicCamera camera);
00034         void RemoveHolographicCamera(winrt::Windows::Graphics::Holographic::HolographicCamera camera);
00035
00036         // Holographic accessors.
00037         template<typename RetType, typename LCallback>
00038         RetType                 UseHolographicCameraResources(LCallback const& callback);
00039
00040         winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice
00041                                 GetD3DInteropDevice()           const { return m_d3dInteropDevice;      }
00042
00043         // D3D accessors.
00044         ID3D11Device4*          GetD3DDevice()                  const { return m_d3dDevice.Get();       }
00045         ID3D11DeviceContext3*   GetD3DDeviceContext()           const { return m_d3dContext.Get();      }
00046         D3D_FEATURE_LEVEL       GetDeviceFeatureLevel()         const { return m_d3dFeatureLevel;       }
00047         bool                    GetDeviceSupportsVprt()         const { return m_supportsVprt;          }
00048
00049         // DXGI acessors.
00050         IDXGIAdapter3*          GetDXGIAdapter()                const { return m_dxgiAdapter.Get();     }
00051
00052         // D2D accessors.
00053         ID2D1Factory2*          GetD2DFactory()                 const { return m_d2dFactory.Get();      }
00054         IDWriteFactory2*        GetDWriteFactory()              const { return m_dwriteFactory.Get();   }
00055         IWICImagingFactory2*    GetWicImagingFactory()          const { return m_wicFactory.Get();      }
00056
00057     private:
00058         // Private methods related to the Direct3D device, and resources based on that device.
00059         void CreateDeviceIndependentResources();
00060         void InitializeUsingHolographicSpace();
00061         void CreateDeviceResources();
00062
00063         // Direct3D objects.
00064         Microsoft::WRL::ComPtr<ID3D11Device4>                   m_d3dDevice;
00065         Microsoft::WRL::ComPtr<ID3D11DeviceContext3>            m_d3dContext;
00066         Microsoft::WRL::ComPtr<IDXGIAdapter3>                   m_dxgiAdapter;
00067
00068         // Direct3D interop objects.
00069         winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice m_d3dInteropDevice;
00070
00071         // Direct2D factories.
00072         Microsoft::WRL::ComPtr<ID2D1Factory2>                   m_d2dFactory;
00073         Microsoft::WRL::ComPtr<IDWriteFactory2>                 m_dwriteFactory;
00074         Microsoft::WRL::ComPtr<IWICImagingFactory2>             m_wicFactory;
00075
00076         // The holographic space provides a preferred DXGI adapter ID.
00077         winrt::Windows::Graphics::Holographic::HolographicSpace m_holographicSpace = nullptr;
00078
00079         // Properties of the Direct3D device currently in use.
00080         D3D_FEATURE_LEVEL                                       m_d3dFeatureLevel = D3D_FEATURE_LEVEL_10_0;
00081
00082         // The IDeviceNotify can be held directly as it owns the DeviceResources.
00083         IDeviceNotify*                                          m_deviceNotify = nullptr;
00084
00085         // Whether or not the current Direct3D device supports the optional feature
00086         // for setting the render target array index from the vertex shader stage.
00087         bool                                                    m_supportsVprt = false;
00088
00089         // Back buffer resources, etc. for attached holographic cameras.
00090         std::map<UINT32, std::unique_ptr<CameraResources>>      m_cameraResources;
00091         std::mutex                                              m_cameraResourcesLock;
00092     };
00093 }
00094
00095 // Device-based resources for holographic cameras are stored in a std::map. Access this list by providing a
00096 // callback to this function, and the std::map will be guarded from add and remove
00097 // events until the callback returns. The callback is processed immediately and must
00098 // not contain any nested calls to UseHolographicCameraResources.
00099 // The callback takes a parameter of type std::map<UINT32, std::unique_ptr<DX::CameraResources>>&
00100 // through which the list of cameras will be accessed.
00101 template<typename RetType, typename LCallback>
00102 RetType DX::DeviceResources::UseHolographicCameraResources(LCallback const& callback)
00103 {
00104     std::lock_guard<std::mutex> guard(m_cameraResourcesLock);
00105     return callback(m_cameraResources);
00106 }
00107
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraFrames/cs/Scenario1_DisplayDepthColorIR.xaml.cs Source File

  • CameraFrames
  • cs

Scenario1_DisplayDepthColorIR.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Linq;
00014 using System.Collections.Generic;
00015 using System.Threading.Tasks;
00016 using Windows.Media.Capture;
00017 using Windows.Media.Capture.Frames;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario1_DisplayDepthColorIR : Page
00025     {
00026         private MediaCapture _mediaCapture;
00027
00028         private List<MediaFrameReader> _sourceReaders = new List<MediaFrameReader>();
00029         private IReadOnlyDictionary<MediaFrameSourceKind, FrameRenderer> _frameRenderers;
00030
00031         private int _groupSelectionIndex;
00032         private readonly SimpleLogger _logger;
00033
00034         public Scenario1_DisplayDepthColorIR()
00035         {
00036             InitializeComponent();
00037             _logger = new SimpleLogger(outputTextBlock);
00038
00039             // This sample reads three kinds of frames: Color, Depth, and Infrared.
00040             _frameRenderers = new Dictionary<MediaFrameSourceKind, FrameRenderer>()
00041             {
00042                 { MediaFrameSourceKind.Color, new FrameRenderer(colorPreviewImage) },
00043                 { MediaFrameSourceKind.Depth, new FrameRenderer(depthPreviewImage)},
00044                 { MediaFrameSourceKind.Infrared, new FrameRenderer(infraredPreviewImage)},
00045             };
00046         }
00047
00048         protected override async void OnNavigatedTo(NavigationEventArgs e)
00049         {
00050             await PickNextMediaSourceAsync();
00051         }
00052
00053         protected override async void OnNavigatedFrom(NavigationEventArgs e)
00054         {
00055             await CleanupMediaCaptureAsync();
00056         }
00057
00058         private async void NextButton_Click(object eventSender, RoutedEventArgs eventArgs)
00059         {
00060             await PickNextMediaSourceAsync();
00061         }
00062
00063         /// <summary>
00064         /// Disables the "Next Group" button while we switch to the next camera
00065         /// source and start reading frames.
00066         /// </summary>
00067         private async Task PickNextMediaSourceAsync()
00068         {
00069             try
00070             {
00071                 this.NextButton.IsEnabled = false;
00072                 await PickNextMediaSourceWorkerAsync();
00073             }
00074             finally
00075             {
00076                 this.NextButton.IsEnabled = true;
00077             }
00078         }
00079
00080         /// <summary>
00081         /// Switches to the next camera source and starts reading frames.
00082         /// </summary>
00083         private async Task PickNextMediaSourceWorkerAsync()
00084         {
00085             await CleanupMediaCaptureAsync();
00086
00087             var allGroups = await MediaFrameSourceGroup.FindAllAsync();
00088
00089             if (allGroups.Count == 0)
00090             {
00091                 _logger.Log("No source groups found.");
00092                 return;
00093             }
00094
00095             // Pick next group in the array after each time the Next button is clicked.
00096             _groupSelectionIndex = (_groupSelectionIndex + 1) % allGroups.Count;
00097             var selectedGroup = allGroups[_groupSelectionIndex];
00098
00099             _logger.Log($"Found {allGroups.Count} groups and selecting index [{_groupSelectionIndex}]: {selectedGroup.DisplayName}");
00100
00101             try
00102             {
00103                 // Initialize MediaCapture with selected group.
00104                 // This can raise an exception if the source no longer exists,
00105                 // or if the source could not be initialized.
00106                 await InitializeMediaCaptureAsync(selectedGroup);
00107             }
00108             catch (Exception exception)
00109             {
00110                 _logger.Log($"MediaCapture initialization error: {exception.Message}");
00111                 await CleanupMediaCaptureAsync();
00112                 return;
00113             }
00114
00115             // Set up frame readers, register event handlers and start streaming.
00116             var startedKinds = new HashSet<MediaFrameSourceKind>();
00117             foreach (MediaFrameSource source in _mediaCapture.FrameSources.Values)
00118             {
00119                 MediaFrameSourceKind kind = source.Info.SourceKind;
00120
00121                 // Ignore this source if we already have a source of this kind.
00122                 if (startedKinds.Contains(kind))
00123                 {
00124                     continue;
00125                 }
00126
00127                 // Look for a format which the FrameRenderer can render.
00128                 string requestedSubtype = null;
00129                 foreach (MediaFrameFormat format in source.SupportedFormats)
00130                 {
00131                     requestedSubtype = FrameRenderer.GetSubtypeForFrameReader(kind, format);
00132                     if (requestedSubtype != null)
00133                     {
00134                         // Tell the source to use the format we can render.
00135                         await source.SetFormatAsync(format);
00136                         break;
00137                     }
00138                 }
00139                 if (requestedSubtype == null)
00140                 {
00141                     // No acceptable format was found. Ignore this source.
00142                     continue;
00143                 }
00144
00145                 MediaFrameReader frameReader = await _mediaCapture.CreateFrameReaderAsync(source, requestedSubtype);
00146
00147                 frameReader.FrameArrived += FrameReader_FrameArrived;
00148                 _sourceReaders.Add(frameReader);
00149
00150                 MediaFrameReaderStartStatus status = await frameReader.StartAsync();
00151                 if (status == MediaFrameReaderStartStatus.Success)
00152                 {
00153                     _logger.Log($"Started {kind} reader.");
00154                     startedKinds.Add(kind);
00155                 }
00156                 else
00157                 {
00158                     _logger.Log($"Unable to start {kind} reader. Error: {status}");
00159                 }
00160             }
00161
00162             if (startedKinds.Count == 0)
00163             {
00164                 _logger.Log($"No eligible sources in {selectedGroup.DisplayName}.");
00165             }
00166         }
00167
00168         /// <summary>
00169         /// Initializes the MediaCapture object with the given source group.
00170         /// </summary>
00171         /// <param name="sourceGroup">SourceGroup with which to initialize.</param>
00172         private async Task InitializeMediaCaptureAsync(MediaFrameSourceGroup sourceGroup)
00173         {
00174             if (_mediaCapture != null)
00175             {
00176                 return;
00177             }
00178
00179             // Initialize mediacapture with the source group.
00180             _mediaCapture = new MediaCapture();
00181             var settings = new MediaCaptureInitializationSettings
00182             {
00183                 SourceGroup = sourceGroup,
00184
00185                 // This media capture can share streaming with other apps.
00186                 SharingMode = MediaCaptureSharingMode.SharedReadOnly,
00187
00188                 // Only stream video and don't initialize audio capture devices.
00189                 StreamingCaptureMode = StreamingCaptureMode.Video,
00190
00191                 // Set to CPU to ensure frames always contain CPU SoftwareBitmap images
00192                 // instead of preferring GPU D3DSurface images.
00193                 MemoryPreference = MediaCaptureMemoryPreference.Cpu
00194             };
00195
00196             await _mediaCapture.InitializeAsync(settings);
00197             _logger.Log("MediaCapture is successfully initialized in shared mode.");
00198         }
00199
00200         /// <summary>
00201         /// Unregisters FrameArrived event handlers, stops and disposes frame readers
00202         /// and disposes the MediaCapture object.
00203         /// </summary>
00204         private async Task CleanupMediaCaptureAsync()
00205         {
00206             if (_mediaCapture != null)
00207             {
00208                 using (var mediaCapture = _mediaCapture)
00209                 {
00210                     _mediaCapture = null;
00211
00212                     foreach (var reader in _sourceReaders)
00213                     {
00214                         if (reader != null)
00215                         {
00216                             reader.FrameArrived -= FrameReader_FrameArrived;
00217                             await reader.StopAsync();
00218                             reader.Dispose();
00219                         }
00220                     }
00221                     _sourceReaders.Clear();
00222                 }
00223             }
00224         }
00225
00226         /// <summary>
00227         /// Handles a frame arrived event and renders the frame to the screen.
00228         /// </summary>
00229         private void FrameReader_FrameArrived(MediaFrameReader sender, MediaFrameArrivedEventArgs args)
00230         {
00231             // TryAcquireLatestFrame will return the latest frame that has not yet been acquired.
00232             // This can return null if there is no such frame, or if the reader is not in the
00233             // "Started" state. The latter can occur if a FrameArrived event was in flight
00234             // when the reader was stopped.
00235             using (var frame = sender.TryAcquireLatestFrame())
00236             {
00237                 if (frame != null)
00238                 {
00239                     var renderer = _frameRenderers[frame.SourceKind];
00240                     renderer.ProcessFrame(frame);
00241                 }
00242             }
00243         }
00244     };
00245 }
Generated on Fri Nov 15 2024 22:18:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cppwinrt/pch.cpp Source File

  • FilePicker
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LockScreenApps/cs/SampleConfiguration.cs Source File

  • LockScreenApps
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Lock Screen Apps C# Sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Add app to lock screen", ClassType=typeof(Scenario1_Configure)},
00025             new Scenario() { Title="Badge and tile notifications", ClassType=typeof(Scenario2_Notifications)},
00026             new Scenario() { Title="Secondary tiles", ClassType=typeof(Scenario3_SecondaryTiles)},
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cppwinrt/Scenario4_NumberParsing.h Source File

  • NumberFormatting
  • cppwinrt

Scenario4_NumberParsing.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_NumberParsing.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario4_NumberParsing : Scenario4_NumberParsingT<Scenario4_NumberParsing>
00019     {
00020         Scenario4_NumberParsing();
00021
00022         void Display_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario4_NumberParsing : Scenario4_NumberParsingT<Scenario4_NumberParsing, implementation::Scenario4_NumberParsing>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:20:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario8_TransmitAPDU Member List

This is the complete list of members for Scenario8_TransmitAPDU, including all inherited members.
rootPage | Scenario8_TransmitAPDU | [private]
Scenario8_TransmitAPDU() | Scenario8_TransmitAPDU | [inline]
Transmit_Click(object sender, RoutedEventArgs e) | Scenario8_TransmitAPDU | [inline, private]
Generated on Fri Nov 15 2024 22:24:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/Common/StepTimer.cs Source File

  • 360VideoPlayback
  • cs
  • Common

StepTimer.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Diagnostics;
00003
00004 namespace _360VideoPlayback.Common
00005 {
00006     /// <summary>
00007     /// Helper class for animation and simulation timing.
00008     /// </summary>
00009     internal class StepTimer
00010     {
00011         // Integer format represents time using 10,000,000 ticks per second.
00012         private const long TicksPerSecond = 10000000;
00013
00014         // Source timing data uses QPC units.
00015         private long qpcFrequency;
00016         private long qpcLastTime;
00017         private long qpcMaxDelta;
00018
00019         // Derived timing data uses a canonical tick format.
00020         private long leftOverTicks = 0;
00021
00022         // Members for tracking the framerate.
00023         private int framesThisSecond = 0;
00024         private long qpcSecondCounter = 0;
00025
00026         public StepTimer()
00027         {
00028             qpcFrequency = Stopwatch.Frequency;
00029             qpcLastTime = Stopwatch.GetTimestamp();
00030
00031             // Initialize max delta to 1/10 of a second.
00032             qpcMaxDelta = qpcFrequency / 10;
00033         }
00034
00035         /// <summary>
00036         /// After an intentional timing discontinuity (for instance a blocking IO operation)
00037         /// call this to avoid having the fixed timestep logic attempt a set of catch-up
00038         /// Update calls.
00039         /// </summary>
00040         public void ResetElapsedTime()
00041         {
00042             qpcLastTime = Stopwatch.GetTimestamp();
00043
00044             leftOverTicks = 0;
00045             FramesPerSecond = 0;
00046             framesThisSecond = 0;
00047             qpcSecondCounter = 0;
00048         }
00049
00050         /// <summary>
00051         /// Get elapsed time since the previous Update call.
00052         /// </summary>
00053         public long ElapsedTicks { get; private set; } = 0;
00054
00055         /// <summary>
00056         /// Get elapsed time since the previous Update call.
00057         /// </summary>
00058         public double ElapsedSeconds => TicksToSeconds(ElapsedTicks);
00059
00060         /// <summary>
00061         /// Get total time since the start of the program.
00062         /// </summary>
00063         public long TotalTicks { get; private set; } = 0;
00064
00065         /// <summary>
00066         /// Get total time since the start of the program.
00067         /// </summary>
00068         public double TotalSeconds => TicksToSeconds(TotalTicks);
00069
00070         /// <summary>
00071         /// Get total number of updates since start of the program.
00072         /// </summary>
00073         public int FrameCount { get; private set; } = 0;
00074
00075         /// <summary>
00076         /// Get the current framerate.
00077         /// </summary>
00078         public int FramesPerSecond { get; private set; } = 0;
00079
00080         /// <summary>
00081         /// Get/Set whether to use fixed or variable timestep mode.
00082         /// </summary>
00083         public bool IsFixedTimeStep { get; set; } = false;
00084
00085         /// <summary>
00086         /// Get/Set how often to call Update when in fixed timestep mode.
00087         /// </summary>
00088         public long TargetElapsedTicks { get; set; } = TicksPerSecond / 60;
00089
00090         /// <summary>
00091         /// Get/Set how often to call Update when in fixed timestep mode.
00092         /// </summary>
00093         public double TargetElapsedSeconds
00094         {
00095             get { return TicksToSeconds(TargetElapsedTicks); }
00096             set { TargetElapsedTicks = SecondsToTicks(value); }
00097         }
00098
00099         /// <summary>
00100         /// // Update timer state, calling the specified Update function the appropriate number of times.
00101         /// </summary>
00102         public void Tick(Action update)
00103         {
00104             // Query the current time.
00105             long currentTime = Stopwatch.GetTimestamp();
00106
00107             long timeDelta = currentTime - qpcLastTime;
00108
00109             qpcLastTime = currentTime;
00110             qpcSecondCounter += timeDelta;
00111
00112             // Clamp excessively large time deltas (e.g. after paused in the debugger).
00113             if (timeDelta > qpcMaxDelta)
00114             {
00115                 timeDelta = qpcMaxDelta;
00116             }
00117
00118             // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp.
00119             timeDelta *= TicksPerSecond;
00120             timeDelta /= qpcFrequency;
00121
00122             long lastFrameCount = FrameCount;
00123
00124             if (IsFixedTimeStep)
00125             {
00126                 // Fixed timestep update logic
00127
00128                 // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp
00129                 // the clock to exactly match the target value. This prevents tiny and irrelevant errors
00130                 // from accumulating over time. Without this clamping, a game that requested a 60 fps
00131                 // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually
00132                 // accumulate enough tiny errors that it would drop a frame. It is better to just round
00133                 // small deviations down to zero to leave things running smoothly.
00134
00135                 if (Math.Abs(timeDelta - TargetElapsedTicks) < (TicksPerSecond / 4000))
00136                 {
00137                     timeDelta = TargetElapsedTicks;
00138                 }
00139
00140                 leftOverTicks += timeDelta;
00141
00142                 while (leftOverTicks >= TargetElapsedTicks)
00143                 {
00144                     ElapsedTicks = TargetElapsedTicks;
00145                     TotalTicks += TargetElapsedTicks;
00146                     leftOverTicks -= TargetElapsedTicks;
00147                     FrameCount++;
00148
00149                     update();
00150                 }
00151             }
00152             else
00153             {
00154                 // Variable timestep update logic.
00155                 ElapsedTicks = timeDelta;
00156                 TotalTicks += timeDelta;
00157                 leftOverTicks = 0;
00158                 FrameCount++;
00159
00160                 update();
00161             }
00162
00163             // Track the current framerate.
00164             if (FrameCount != lastFrameCount)
00165             {
00166                 framesThisSecond++;
00167             }
00168
00169             if (qpcSecondCounter >= qpcFrequency)
00170             {
00171                 FramesPerSecond = framesThisSecond;
00172                 framesThisSecond = 0;
00173                 qpcSecondCounter %= qpcFrequency;
00174             }
00175         }
00176
00177         private static double TicksToSeconds(long ticks)
00178         {
00179             return (double)ticks / TicksPerSecond;
00180         }
00181
00182         private static long SecondsToTicks(double seconds)
00183         {
00184             return (long)(seconds * TicksPerSecond);
00185         }
00186     }
00187 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cpp/BackgroundTransfer/Scenario4_CompletionGroups.xaml.h Source File

  • BackgroundTransfer
  • cpp
  • BackgroundTransfer

Scenario4_CompletionGroups.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario4_CompletionGroups.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class Scenario4_CompletionGroups sealed
00025     {
00026     public:
00027         Scenario4_CompletionGroups();
00028
00029     protected:
00030         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00031
00032     private:
00033         SDKTemplate::MainPage^ rootPage;
00034
00035         void AttachDownloads();
00036         void StartDownloadsButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         void StartDownload(
00038             Windows::Storage::StorageFile^ destinationFile,
00039             Windows::Networking::BackgroundTransfer::BackgroundDownloader^ downloader,
00040             Windows::Foundation::Uri^ source);
00041         void MarshalNotifyUser(Platform::String^ message, SDKTemplate::NotifyType type);
00042     };
00043 }
Generated on Fri Nov 15 2024 22:18:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_BackgroundActivity Member List

This is the complete list of members for Scenario4_BackgroundActivity, including all inherited members.
ActivitySensorClassId | Scenario4_BackgroundActivity | [private]
OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) | Scenario4_BackgroundActivity | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario4_BackgroundActivity | [inline, protected]
RegisterBackgroundTask() | Scenario4_BackgroundActivity | [inline, private]
registered | Scenario4_BackgroundActivity | [private]
rootPage | Scenario4_BackgroundActivity | [private]
SampleBackgroundTaskEntryPoint | Scenario4_BackgroundActivity |
SampleBackgroundTaskName | Scenario4_BackgroundActivity |
Scenario4_BackgroundActivity() | Scenario4_BackgroundActivity | [inline]
ScenarioRegisterTask(object sender, RoutedEventArgs e) | Scenario4_BackgroundActivity | [inline, private]
ScenarioUnregisterTask(object sender, RoutedEventArgs e) | Scenario4_BackgroundActivity | [inline, private]
UpdateUIAsync(string status) | Scenario4_BackgroundActivity | [inline, private]
Generated on Fri Nov 15 2024 22:23:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OCR/cppwinrt/WordOverlay.cpp Source File

  • OCR
  • cppwinrt

WordOverlay.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "WordOverlay.h"
00003 #include "WordOverlay.g.cpp"
00004
00005 using namespace winrt;
00006 using namespace winrt::Windows::Foundation;
00007 using namespace winrt::Windows::Media::Ocr;
00008 using namespace winrt::Windows::UI::Xaml;
00009 using namespace winrt::Windows::UI::Xaml::Controls;
00010 using namespace winrt::Windows::UI::Xaml::Data;
00011 using namespace winrt::Windows::UI::Xaml::Media;
00012
00013 namespace winrt::SDKTemplate::implementation
00014 {
00015     WordOverlay::WordOverlay(OcrWord const& ocrWord)
00016     {
00017         word = ocrWord;
00018
00019         UpdateProps(word.BoundingRect());
00020     }
00021
00022     event_token WordOverlay::PropertyChanged(PropertyChangedEventHandler const& handler)
00023     {
00024         return m_propertyChanged.add(handler);
00025     }
00026
00027     void WordOverlay::PropertyChanged(event_token const& token) noexcept
00028     {
00029         m_propertyChanged.remove(token);
00030     }
00031
00032     void WordOverlay::Transform(ScaleTransform const& scale)
00033     {
00034         // Scale word box bounding rect and update properties.
00035         UpdateProps(scale.TransformBounds(word.BoundingRect()));
00036     }
00037
00038     Border WordOverlay::CreateBorder(Style const& style, UIElement const& child)
00039     {
00040         Border overlay;
00041         overlay.Child(child);
00042         overlay.Style(style);
00043
00044         // Bind word boxes to UI.
00045         overlay.SetBinding(FrameworkElement::MarginProperty(), CreateBinding(L"WordPosition"));
00046         overlay.SetBinding(FrameworkElement::WidthProperty(), CreateBinding(L"WordWidth"));
00047         overlay.SetBinding(FrameworkElement::HeightProperty(), CreateBinding(L"WordHeight"));
00048
00049         return overlay;
00050     }
00051
00052     Binding WordOverlay::CreateBinding(hstring const& propertyName)
00053     {
00054         Binding positionBinding;
00055
00056         positionBinding.Path(PropertyPath{ propertyName });
00057         positionBinding.Source(*this);
00058
00059         return positionBinding;
00060     }
00061
00062     void WordOverlay::UpdateProps(Rect const& wordBoundingBox)
00063     {
00064         m_wordBoundingBox = wordBoundingBox;
00065
00066         OnPropertyChanged(L"WordPosition");
00067         OnPropertyChanged(L"WordWidth");
00068         OnPropertyChanged(L"WordHeight");
00069     }
00070
00071     void WordOverlay::OnPropertyChanged(hstring const& PropertyName)
00072     {
00073         m_propertyChanged(*this, PropertyChangedEventArgs(PropertyName));
00074     }
00075 }
Generated on Fri Nov 15 2024 22:20:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario Member List

This is the complete list of members for Scenario, including all inherited members.
ClassName | Scenario |
ClassName | Scenario |
ClassType | Scenario |
Description | Scenario |
LoadXmlFile(String folder, String file) | Scenario | [inline, static]
RichEditBoxSetError(RichEditBox richEditBox, String errorMsg) | Scenario | [inline, static]
RichEditBoxSetMsg(RichEditBox richEditBox, String msg, bool fReadOnly) | Scenario | [inline, static]
RichEditBoxSetText(RichEditBox richEditBox, String msg, Windows.UI.Color color, bool fReadOnly) | Scenario | [inline, static]
Title | Scenario |
Title | Scenario |
Title | Scenario |
ToString() | Scenario | [inline]
ToString() | Scenario | [inline]
ToString() | Scenario | [inline]
ToString() | Scenario | [inline]
ToString() | Scenario | [inline]
ToString() | Scenario | [inline]
ToString() | Scenario | [inline]
ToString() | Scenario | [inline]
ToString() | Scenario | [inline]
ToString() | Scenario | [inline]
ToString() | Scenario | [inline]
ToString() | Scenario | [inline]
ToString() | Scenario | [inline]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileSearch/cpp/Scenario1.xaml.cpp Source File

  • FileSearch
  • cpp

Scenario1.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1.xaml.cpp
00014 // Implementation of the Scenario1 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario1.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace concurrency;
00023 using namespace Platform;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::Storage;
00026 using namespace Windows::Storage::Search;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 Scenario1::Scenario1()
00032 {
00033     InitializeComponent();
00034 }
00035
00036 void Scenario1::SearchButton_Click(Object^ sender, RoutedEventArgs^ e)
00037 {
00038     auto fileTypeFilter = ref new Platform::Collections::Vector<Platform::String^>();
00039     fileTypeFilter->Append("*");
00040     auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderBySearchRank, fileTypeFilter);
00041     //use the user's input to make a query
00042     queryOptions->UserSearchFilter = InputTextBox->Text;
00043
00044     create_task(KnownFolders::GetFolderForUserAsync(nullptr /* current user */, KnownFolderId::MusicLibrary)).then([this, queryOptions](StorageFolder^ musicFolder)
00045     {
00046         auto queryResult = musicFolder->CreateFileQueryWithOptions(queryOptions);
00047         //find all files that match the query
00048         return queryResult->GetFilesAsync();
00049     }).then([this, queryOptions](IVectorView<StorageFile^>^ files)
00050     {
00051         String^ outputText = "";
00052
00053         //output how many files that match the query were found
00054         if (files->Size == 0)
00055         {
00056             outputText += "No files found for '" + queryOptions->UserSearchFilter + "'";
00057         }
00058         else if (files->Size == 1)
00059         {
00060             outputText += files->Size.ToString() + " file found:\n\n";
00061         }
00062         else
00063         {
00064             outputText += files->Size.ToString() + " files found:\n\n";
00065         }
00066
00067         //output the name of each file that matches the query
00068         for (unsigned int i = 0; i < files->Size; i++)
00069         {
00070             outputText += files->GetAt(i)->Name + "\n";
00071         }
00072
00073         OutputTextBlock->Text = outputText;
00074     });
00075 }
Generated on Fri Nov 15 2024 22:17:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: StreamSocket/cpp/Scenario2.xaml.cpp Source File

  • StreamSocket
  • cpp

Scenario2.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2.xaml.cpp
00014 // Implementation of the Scenario2 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario2.xaml.h"
00019
00020 using namespace SDKTemplate;
00021 using namespace SDKTemplate::StreamSocketSample;
00022
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Windows::ApplicationModel::Core;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Networking;
00028 using namespace Windows::Networking::Connectivity;
00029 using namespace Windows::Networking::Sockets;
00030 using namespace Windows::UI::Xaml;
00031 using namespace Windows::UI::Xaml::Controls;
00032 using namespace Windows::UI::Xaml::Navigation;
00033
00034 Scenario2::Scenario2() : adapter(nullptr)
00035 {
00036     InitializeComponent();
00037 }
00038
00039 /// <summary>
00040 /// Invoked when this page is about to be displayed in a Frame.
00041 /// </summary>
00042 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00043 /// property is typically used to configure the page.</param>
00044 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00045 {
00046     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00047     // as NotifyUser()
00048     rootPage = MainPage::Current;
00049
00050     if (CoreApplication::Properties->HasKey("serverAddress"))
00051     {
00052         Object^ serverAddressObject = CoreApplication::Properties->Lookup("serverAddress");
00053         String^ serverAddress = dynamic_cast<String^>(serverAddressObject);
00054         if (serverAddress)
00055         {
00056             HostNameForConnect->Text = serverAddress;
00057         }
00058     }
00059
00060     adapter = nullptr;
00061     if (CoreApplication::Properties->HasKey("adapter"))
00062     {
00063         Object^ networkAdapter = CoreApplication::Properties->Lookup("adapter");
00064         adapter = dynamic_cast<NetworkAdapter^>(networkAdapter);
00065     }
00066 }
00067
00068
00069 void Scenario2::ConnectSocket_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00070 {
00071     // Overriding the socket here is safe as it will be deleted once all references to it are gone. However, in many
00072     // cases this is a dangerous pattern to override data semi-randomly (each time user clicked the button) so we
00073     // block it here.
00074     if (CoreApplication::Properties->HasKey("clientSocket"))
00075     {
00076         rootPage->NotifyUser(
00077             "This step has already been executed. Please move to the next one.",
00078             NotifyType::ErrorMessage);
00079         return;
00080     }
00081
00082     if (ServiceNameForConnect->Text == nullptr)
00083     {
00084         rootPage->NotifyUser("Please provide a service name.", NotifyType::ErrorMessage);
00085         return;
00086     }
00087
00088     // By default 'HostNameForConnect' is disabled and host name validation is not required. When enabling the text
00089     // box validating the host name is required since it was received from an untrusted source (user input).
00090     // The host name is validated by catching InvalidArgumentExceptions thrown by the HostName constructor for invalid
00091     // input.
00092     HostName^ hostName;
00093     try
00094     {
00095         hostName = ref new HostName(HostNameForConnect->Text);
00096     }
00097     catch (InvalidArgumentException^ e)
00098     {
00099         rootPage->NotifyUser("Error: Invalid host name.", NotifyType::ErrorMessage);
00100         return;
00101     }
00102
00103     StreamSocket^ socket = ref new StreamSocket();
00104
00105     // If necessary, tweak the socket's control options before carrying out the connect operation.
00106     // Refer to the StreamSocketControl class' MSDN documentation for the full list of control options.
00107     socket->Control->KeepAlive = false;
00108
00109     // Save the socket, so subsequent steps can use it.
00110     CoreApplication::Properties->Insert("clientSocket", socket);
00111
00112     rootPage->NotifyUser("Connecting to: " + HostNameForConnect->Text, NotifyType::StatusMessage);
00113
00114     if (adapter == nullptr)
00115     {
00116         // Connect to the server (by default, the listener we created in the previous step).
00117         create_task(socket->ConnectAsync(
00118             hostName,
00119             ServiceNameForConnect->Text,
00120             SocketProtectionLevel::PlainSocket)).then([this] (task<void> previousTask)
00121         {
00122             try
00123             {
00124                 // Try getting all exceptions from the continuation chain above this point.
00125                 previousTask.get();
00126                 rootPage->NotifyUser("Connected", NotifyType::StatusMessage);
00127
00128                 // Mark the socket as connected. We do not really care about the value of the property; the mere
00129                 // existence of it means that we are connected.
00130                 CoreApplication::Properties->Insert("connected", nullptr);
00131             }
00132             catch (Exception^ exception)
00133             {
00134                 rootPage->NotifyUser("Connect failed with error: " + exception->Message, NotifyType::ErrorMessage);
00135             }
00136         });
00137     }
00138     else
00139     {
00140         // Connect to the server (by default, the listener we created in the previous step)
00141         // limiting traffic to the same adapter that the user specified in the previous step.
00142         // This option will be overridden by interfaces with weak-host or forwarding modes enabled.
00143         create_task(socket->ConnectAsync(
00144             hostName,
00145             ServiceNameForConnect->Text,
00146             SocketProtectionLevel::PlainSocket,
00147             adapter)).then([this] (task<void> previousTask)
00148         {
00149             try
00150             {
00151                 // Try getting all exceptions from the continuation chain above this point.
00152                 previousTask.get();
00153                 rootPage->NotifyUser(
00154                     "Connected using network adapter" + adapter->NetworkAdapterId,
00155                     NotifyType::StatusMessage);
00156
00157                 // Mark the socket as connected. We do not really care about the value of the property; the mere
00158                 // existence of it means that we are connected.
00159                 CoreApplication::Properties->Insert("connected", nullptr);
00160             }
00161             catch (Exception^ exception)
00162             {
00163                 rootPage->NotifyUser("Connect failed with error: " + exception->Message, NotifyType::ErrorMessage);
00164             }
00165         });
00166     }
00167 }
Generated on Fri Nov 15 2024 22:17:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario5_Stream.xaml.cpp Source File

  • FileAccess
  • cpp

Scenario5_Stream.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario5_Stream.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Storage;
00020 using namespace Windows::Storage::Streams;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario5::Scenario5()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 void Scenario5::OnNavigatedTo(NavigationEventArgs^ e)
00031 {
00032     rootPage->ValidateFile();
00033 }
00034
00035 void Scenario5::WriteToStreamButton_Click(Object^ sender, RoutedEventArgs^ e)
00036 {
00037     StorageFile^ file = rootPage->SampleFile;
00038     if (file != nullptr)
00039     {
00040         String^ userContent = InputTextBox->Text;
00041         create_task(file->OpenTransactedWriteAsync()).then([this, userContent](StorageStreamTransaction^ transaction)
00042         {
00043             IBuffer^ buffer = MainPage::GetBufferFromString(userContent);
00044             return create_task(transaction->Stream->WriteAsync(buffer)).then([transaction](unsigned int bytesWritten)
00045             {
00046                 transaction->Stream->Size = bytesWritten; // truncate file
00047                 return create_task(transaction->CommitAsync());
00048             }).then([transaction]()
00049             {
00050                 delete transaction; // As a best practice, explicitly close the transaction resource as soon as it is no longer needed.
00051             });
00052         }).then([this, file, userContent]()
00053         {
00054             rootPage->NotifyUser("The following text was written to '" + file->Name + "' using a stream:\n" + userContent, NotifyType::StatusMessage);
00055         }).then([this, file](task<void> previousTask)
00056         {
00057             try
00058             {
00059                 previousTask.get();
00060             }
00061             catch (COMException^ ex)
00062             {
00063                 rootPage->HandleIoException(ex, "Error writing to '" + file->Name + "'");
00064             }
00065         });
00066     }
00067     else
00068     {
00069         rootPage->NotifyUserFileNotExist();
00070     }
00071 }
00072
00073 void Scenario5::ReadFromStreamButton_Click(Object^ sender, RoutedEventArgs^ e)
00074 {
00075     StorageFile^ file = rootPage->SampleFile;
00076     if (file != nullptr)
00077     {
00078         create_task(file->OpenAsync(FileAccessMode::Read)).then([this, file](IRandomAccessStream^ readStream)
00079         {
00080             UINT64 size64 = readStream->Size;
00081             if (size64 <= MAXUINT32)
00082             {
00083                 UINT32 size32 = static_cast<UINT32>(size64);
00084                 IBuffer^ buffer = ref new Buffer(size32);
00085                 return create_task(readStream->ReadAsync(buffer, size32, InputStreamOptions::None)).then([this, file, readStream](IBuffer^ buffer)
00086                 {
00087                     delete readStream; // As a best practice, explicitly close the readStream resource as soon as it is no longer needed.
00088                     String^ fileContent = MainPage::GetStringFromBuffer(buffer);
00089                     rootPage->NotifyUser("The following text was read from '" + file->Name + "' using a stream:\n" + fileContent, NotifyType::StatusMessage);
00090                 });
00091             }
00092             else
00093             {
00094                 delete readStream; // As a best practice, explicitly close the readStream resource as soon as it is no longer needed.
00095                 rootPage->NotifyUser("File " + file->Name + " is too big for LoadAsync to load in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync.", NotifyType::ErrorMessage);
00096                 return task_from_result();
00097             }
00098         }).then([this, file](task<void> previousTask)
00099         {
00100             try
00101             {
00102                 previousTask.get();
00103             }
00104             catch (COMException^ ex)
00105             {
00106                 rootPage->HandleIoException(ex, "Error reading from '" + file->Name + "'");
00107             }
00108         });
00109     }
00110     else
00111     {
00112         rootPage->NotifyUserFileNotExist();
00113     }
00114 }
Generated on Fri Nov 15 2024 22:19:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Json/cs/Scenario1_ParseAndStringify.xaml.cs Source File

  • Json
  • cs

Scenario1_ParseAndStringify.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Data.Json;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario1_ParseAndStringify : Page
00020     {
00021         MainPage rootPage = MainPage.Current;
00022
00023         User CurrentUser
00024         {
00025             get => (User)DataContext;
00026             set => DataContext = value;
00027         }
00028
00029         public Scenario1_ParseAndStringify()
00030         {
00031             this.InitializeComponent();
00032             CurrentUser = new User(JsonInput.Text);
00033         }
00034
00035         private void Parse_Click(object sender, RoutedEventArgs e)
00036         {
00037             try
00038             {
00039                 CurrentUser = new User(JsonInput.Text);
00040                 rootPage.NotifyUser("JSON string parsed successfully.", NotifyType.StatusMessage);
00041             }
00042             catch (Exception ex) when (IsExceptionHandled(ex))
00043             {
00044             }
00045         }
00046
00047         private void Stringify_Click(object sender, RoutedEventArgs e)
00048         {
00049             JsonInput.Text = "";
00050
00051             JsonInput.Text = CurrentUser.Stringify();
00052             rootPage.NotifyUser("JSON object serialized to string successfully.", NotifyType.StatusMessage);
00053         }
00054
00055         private void Add_Click(object sender, RoutedEventArgs e)
00056         {
00057             CurrentUser.Education.Add(new School());
00058             rootPage.NotifyUser("New row added.", NotifyType.StatusMessage);
00059         }
00060
00061         private void DeleteSchool_Click(object sender, RoutedEventArgs e)
00062         {
00063             var school = (School)((FrameworkElement)sender).DataContext;
00064             CurrentUser.Education.Remove(school);
00065         }
00066
00067         private bool IsExceptionHandled(Exception ex)
00068         {
00069             if (ex.HResult == unchecked((int)0x8000000E)) // E_ILLEGAL_METHOD_CALL
00070             {
00071                 rootPage.NotifyUser("JSON did not match expected schema: " + ex.Message, NotifyType.ErrorMessage);
00072                 return true;
00073             }
00074
00075             JsonErrorStatus error = JsonError.GetJsonStatus(ex.HResult);
00076             if (error == JsonErrorStatus.Unknown)
00077             {
00078                 return false;
00079             }
00080
00081             rootPage.NotifyUser(error + ": " + ex.Message, NotifyType.ErrorMessage);
00082             return true;
00083         }
00084     }
00085 }
Generated on Fri Nov 15 2024 22:20:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
_compositionTarget | sealed |
_compositor | sealed |
_currentVisual | sealed |
_dragging | sealed |
_offsetBias | sealed |
_root | sealed |
_view | sealed |
_window | sealed |
CallbackCount | sealed |
cMovementMetersPerSecond | sealed | [private, static]
cPixelsToMeters | sealed | [private, static]
cPixelsToMetersPerSecond | sealed | [private, static]
cPixelsToRadians | sealed | [private, static]
cPixelsToRadiansPerSecond | sealed | [private, static]
CreateChildElement() | sealed |
CreateView() | sealed | [virtual]
CreateView() | sealed | [virtual]
CreateView() | sealed | [virtual]
CreateView() | sealed | [virtual]
CreateView() | sealed | [virtual]
CreateView() | sealed | [virtual]
cRotationRadiansPerSecond | sealed | [private, static]
FirstPersonCamera() | sealed |
GetCameraToWorld() | sealed |
GetWorldToCamera() | sealed |
hRpcBinding | sealed | [private]
Initialize(Windows::ApplicationModel::Core::CoreApplicationView^view) override | sealed |
Initialize() | sealed |
InitNewComposition() | sealed |
Load(Platform::String^unused) override | sealed |
m_pitchAngle | sealed | [private]
m_position | sealed | [private]
m_prevCursor | sealed | [private]
m_yawAngle | sealed | [private]
MeteringData | sealed |
MoveAlongX(float distance) | sealed | [private]
MoveAlongY(float distance) | sealed | [private]
MoveAlongZ(float distance) | sealed | [private]
OnPointerMoved(Windows::UI::Core::CoreWindow^window, Windows::UI::Core::PointerEventArgs^args) | sealed | [private]
OnPointerMoved(Windows::UI::Core::CoreWindow^window, Windows::UI::Core::PointerEventArgs^args) | sealed |
OnPointerPressed(Windows::UI::Core::CoreWindow^window, Windows::UI::Core::PointerEventArgs^args) | sealed |
OnPointerReleased(Windows::UI::Core::CoreWindow^window, Windows::UI::Core::PointerEventArgs^args) | sealed |
phContext | sealed | [private]
Reset() | sealed |
RotatePitch(float radians) | sealed | [private]
RotateYaw(float radians) | sealed | [private]
Run() override | sealed |
SetSampleRate(int rate) | sealed |
SetWindow(Windows::UI::Core::CoreWindow^window) override | sealed |
StartMeteringAndWaitForStop(__int64 samplePeriod) | sealed |
StopMetering() | sealed |
Uninitialize() override | sealed |
Update(float dt) | sealed |
VisualProperties() | sealed |
~RpcClient() | sealed |
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_CheckConsentAvailability Member List

This is the complete list of members for Scenario1_CheckConsentAvailability, including all inherited members.
CheckAvailability_Click(object sender, RoutedEventArgs e) | Scenario1_CheckConsentAvailability | [inline, private]
rootPage | Scenario1_CheckConsentAvailability | [private]
Scenario1_CheckConsentAvailability() | Scenario1_CheckConsentAvailability | [inline]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Item Member List

This is the complete list of members for Item, including all inherited members.
DateCreated | Item
Id | Item
Text | Item
Title | Item
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackButton/cpp/pch.h Source File

  • BackButton
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//
00002 // pch.h
00003 // Header for standard system include files.
00004 //
00005
00006 #pragma once
00007
00008 #include <collection.h>
00009 #include <ppltasks.h>
00010
00011 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DSvgImage/cpp/pch.h Source File

  • D2DSvgImage
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <agile.h>
00015 #include <concrt.h>
00016 #include <memory>
00017 #include <ppltasks.h>
00018 #include <wrl.h>
00019 #include <wrl/client.h>
00020 #include <shcore.h>
00021
00022 #include <d3d11_3.h>
00023 #include <d2d1_3.h>
00024 #include <dwrite_3.h>
00025 #include <wincodec.h>
00026 #include <DirectXMath.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlContextMenu/cs/Scenario3.xaml.cs Source File

  • XamlContextMenu
  • cs

Scenario3.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Linq;
00016 using Windows.Foundation;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Input;
00020 using Windows.UI.Xaml.Media;
00021
00022 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00023
00024 namespace SDKTemplate
00025 {
00026     public sealed partial class Scenario3 : Page
00027     {
00028         private MainPage rootPage = MainPage.Current;
00029         public List<SampleDataModel> AllItems = SampleDataModel.GetSampleData();
00030         private MenuFlyout sharedFlyout;
00031
00032         public Scenario3()
00033         {
00034             this.InitializeComponent();
00035             sharedFlyout = (MenuFlyout)Resources["SampleContextMenu"];
00036         }
00037
00038         private void ListView_ContextRequested(UIElement sender, ContextRequestedEventArgs e)
00039         {
00040             // Walk up the tree to find the ListViewItem.
00041             // There may not be one if the click wasn't on an item.
00042             var requestedElement = (FrameworkElement)e.OriginalSource;
00043             while ((requestedElement != sender) && !(requestedElement is ListViewItem))
00044             {
00045                 requestedElement = (FrameworkElement)VisualTreeHelper.GetParent(requestedElement);
00046             }
00047             if (requestedElement != sender)
00048             {
00049                 // The context menu request was indeed for a ListViewItem.
00050                 var model = (SampleDataModel)ItemListView.ItemFromContainer(requestedElement);
00051                 Point point;
00052                 if (e.TryGetPosition(requestedElement, out point))
00053                 {
00054                     rootPage.NotifyUser($"Showing flyout for {model.Title} at {point}", NotifyType.StatusMessage);
00055                     sharedFlyout.ShowAt(requestedElement, point);
00056                 }
00057                 else
00058                 {
00059                     // Not invoked via pointer, so let XAML choose a default location.
00060                     rootPage.NotifyUser($"Showing flyout for {model.Title} at default location", NotifyType.StatusMessage);
00061                     sharedFlyout.ShowAt(requestedElement);
00062                 }
00063
00064                 e.Handled = true;
00065             }
00066         }
00067
00068         private void ListView_ContextCanceled(UIElement sender, RoutedEventArgs args)
00069         {
00070             sharedFlyout.Hide();
00071         }
00072
00073         private SampleDataModel GetDataModelForCurrentListViewFlyout()
00074         {
00075             // Obtain the ListViewItem for which the user requested a context menu.
00076             var listViewItem = sharedFlyout.Target;
00077
00078             // Get the data model for the ListViewItem.
00079             return (SampleDataModel)ItemListView.ItemFromContainer(listViewItem);
00080         }
00081
00082         private void OpenMenuItem_Click(object sender, RoutedEventArgs e)
00083         {
00084             SampleDataModel model = GetDataModelForCurrentListViewFlyout();
00085             rootPage.NotifyUser($"Item: {model.Title}, Action: Open", NotifyType.StatusMessage);
00086         }
00087
00088         private void PrintMenuItem_Click(object sender, RoutedEventArgs e)
00089         {
00090             SampleDataModel model = GetDataModelForCurrentListViewFlyout();
00091             rootPage.NotifyUser($"Item: {model.Title}, Action: Print", NotifyType.StatusMessage);
00092         }
00093
00094         private void DeleteMenuItem_Click(object sender, RoutedEventArgs e)
00095         {
00096             SampleDataModel model = GetDataModelForCurrentListViewFlyout();
00097             rootPage.NotifyUser($"Item: {model.Title}, Action: Delete", NotifyType.StatusMessage);
00098         }
00099     }
00100 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/Common/BasicReaderWriter.h Source File

  • Simple3DGameDX
  • cppwinrt
  • Common

BasicReaderWriter.h

Go to the documentation of this file.
00001 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 // PARTICULAR PURPOSE.
00005 //
00006 // Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 // A simple reader/writer class that provides support for reading and writing
00011 // files on disk. Provides synchronous and asynchronous methods.
00012
00013 class BasicReaderWriter
00014 {
00015 public:
00016     BasicReaderWriter();
00017
00018     BasicReaderWriter(
00019         _In_ winrt::Windows::Storage::StorageFolder folder
00020         );
00021
00022     std::vector<byte> ReadData(
00023         _In_ winrt::hstring const& filename
00024         );
00025
00026     winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Storage::Streams::IBuffer> ReadDataAsync(
00027         _In_ winrt::hstring const& filename
00028         );
00029
00030     uint32_t WriteData(
00031         _In_ winrt::hstring const& filename,
00032         _In_ std::vector<byte> const& fileData
00033         );
00034
00035     winrt::Windows::Foundation::IAsyncAction WriteDataAsync(
00036         _In_ winrt::hstring const& filename,
00037         _In_ std::vector<byte> const& fileData
00038         );
00039
00040 private:
00041     winrt::Windows::Storage::StorageFolder m_location{ nullptr };
00042 };
Generated on Fri Nov 15 2024 22:19:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactPanel/cs/AppContactPanel.xaml.cs Source File

  • ContactPanel
  • cs

AppContactPanel.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.ApplicationModel.Activation;
00015 using Windows.ApplicationModel.Contacts;
00016 using Windows.System;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// A page that is hosted within the MyPeople flyout on the taskbar.
00025     /// </summary>
00026     public sealed partial class AppContactPanel : Page
00027     {
00028         string _appContactId = string.Empty;
00029         Contact lightContact = null;
00030         Contact fullContact = null;
00031
00032         public AppContactPanel()
00033         {
00034             this.InitializeComponent();
00035         }
00036
00037         public async void OnActivated(ContactPanelActivatedEventArgs args)
00038         {
00039             // Register the handler for a full app launch from the My People flyout
00040             args.ContactPanel.LaunchFullAppRequested += AppContactPanel_LaunchFullAppRequested;
00041
00042             // Apply some customization.
00043             args.ContactPanel.HeaderColor = Windows.UI.Colors.LightBlue;
00044
00045             // The Contact object that is passed in with ContactPanelActivatedEventArgs is not very usable,
00046             // we need to obtain a full contact from the ContactStore in order to do anything interesting.
00047             lightContact = args.Contact;
00048
00049             await InitializePageAsync();
00050         }
00051
00052         public async Task InitializePageAsync()
00053         {
00054             if (fullContact == null)
00055             {
00056                 ContactStore store = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AppContactsReadWrite);
00057                 try
00058                 {
00059                     fullContact = await store.GetContactAsync(lightContact.Id);
00060                 }
00061                 catch
00062                 {
00063                     // User denied access to the contact database.
00064                 }
00065             }
00066
00067             if (fullContact != null)
00068             {
00069                 // Now that we have a full Contact object, we can do richer operations such as querying the display name
00070                 this.contactName.Text = fullContact.DisplayName;
00071
00072                 // This is the remoteId that your app annotated the contact with on creation
00073                 this.remoteId.Text = _appContactId = await GetRemoteIdForContactAsync(fullContact);
00074
00075                 if (RequestContactAccessPanel.Visibility == Visibility.Visible)
00076                 {
00077                     Window.Current.Activated -= OnWindowActivated;
00078                     ContactHistoryPanel.Visibility = Visibility.Visible;
00079                     RequestContactAccessPanel.Visibility = Visibility.Collapsed;
00080                 }
00081             }
00082             else
00083             {
00084                 // Prompt the user to grant access to contacts.
00085                 if (RequestContactAccessPanel.Visibility == Visibility.Collapsed)
00086                 {
00087                     ContactHistoryPanel.Visibility = Visibility.Collapsed;
00088                     RequestContactAccessPanel.Visibility = Visibility.Visible;
00089
00090                     // Re-check each time we regain activation.
00091                     Window.Current.Activated += OnWindowActivated;
00092                 }
00093             }
00094         }
00095
00096         public async Task<string> GetRemoteIdForContactAsync(Contact fullContact)
00097         {
00098             var contactAnnotationStore = await ContactManager.RequestAnnotationStoreAsync(ContactAnnotationStoreAccessType.AppAnnotationsReadWrite);
00099
00100             var contactAnnotations = await contactAnnotationStore.FindAnnotationsForContactAsync(fullContact);
00101
00102             if (contactAnnotations.Count >= 0)
00103             {
00104                 return contactAnnotations[0].RemoteId;
00105             }
00106
00107             return string.Empty;
00108         }
00109
00110         private async void AppContactPanel_LaunchFullAppRequested(ContactPanel sender, ContactPanelLaunchFullAppRequestedEventArgs args)
00111         {
00112             // callback to relaunch the sample app as a protocol launch with the remoteID for the current
00113             // contact as a launcher argument.
00114             args.Handled = true;
00115             await this.Dispatcher.RunAsync(
00116                 CoreDispatcherPriority.Normal,
00117                 async () =>
00118                 {
00119                     LauncherOptions options = new LauncherOptions();
00120                     options.TargetApplicationPackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;
00121
00122                     await Launcher.LaunchUriAsync(new Uri($"{Constants.Protocol}:?ContactRemoteId={Uri.EscapeDataString(_appContactId)}"), options);
00123                     sender.ClosePanel();
00124                 });
00125         }
00126
00127         private async void AllowAccess_Click(object sender, RoutedEventArgs e)
00128         {
00129             await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-contacts"));
00130         }
00131
00132         private async void OnWindowActivated(object sender, WindowActivatedEventArgs e)
00133         {
00134             if (e.WindowActivationState != CoreWindowActivationState.Deactivated)
00135             {
00136                 await InitializePageAsync();
00137             }
00138         }
00139     }
00140 }
Generated on Fri Nov 15 2024 22:18:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Scenario6_GetLastVisit.h Source File

  • Geolocation
  • cppwinrt

Scenario6_GetLastVisit.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario6_GetLastVisit.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario6_GetLastVisit : Scenario6_GetLastVisitT<Scenario6_GetLastVisit>
00019     {
00020         Scenario6_GetLastVisit();
00021
00022         fire_and_forget GetLastVisitButtonClicked(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00023
00024     private:
00025         SDKTemplate::MainPage m_rootPage{ MainPage::Current() };
00026
00027         void UpdateLastVisit(Windows::Devices::Geolocation::Geovisit const& visit);
00028     };
00029 }
00030
00031 namespace winrt::SDKTemplate::factory_implementation
00032 {
00033     struct Scenario6_GetLastVisit : Scenario6_GetLastVisitT<Scenario6_GetLastVisit, implementation::Scenario6_GetLastVisit>
00034     {
00035     };
00036 }
Generated on Fri Nov 15 2024 22:19:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceSelectorChoices Member List

This is the complete list of members for DeviceSelectorChoices, including all inherited members.
BackgroundDeviceWatcherSelectors() | DeviceSelectorChoices | [static]
CommonDeviceSelectors() | DeviceSelectorChoices | [static]
DevicePickerSelectors() | DeviceSelectorChoices | [static]
DeviceWatcherSelectors() | DeviceSelectorChoices | [static]
FindAllAsyncSelectors() | DeviceSelectorChoices | [static]
PairingSelectors() | DeviceSelectorChoices | [static]
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_ManageHotspot Member List

This is the complete list of members for Scenario1_ManageHotspot, including all inherited members.
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario1_ManageHotspot |
RegisterTasks_Click(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_ManageHotspot |
SavePropertiesForBackgroundTask() | Scenario1_ManageHotspot | [private]
Scenario1_ManageHotspot() | Scenario1_ManageHotspot |
UnregisterTasks_Click(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_ManageHotspot |
UpdateNowButton_Click(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_ManageHotspot |
UpdateOnDemandButton_Click(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_ManageHotspot |
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario10_Delete.xaml.cpp Source File

  • FileAccess
  • cpp

Scenario10_Delete.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario10_Delete.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Storage;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Navigation;
00022
00023 Scenario10::Scenario10()
00024 {
00025     InitializeComponent();
00026 }
00027
00028 void Scenario10::OnNavigatedTo(NavigationEventArgs^ e)
00029 {
00030     rootPage->ValidateFile();
00031 }
00032
00033 void Scenario10::DeleteFileButton_Click(Object^ sender, RoutedEventArgs^ e)
00034 {
00035     StorageFile^ file = rootPage->SampleFile;
00036     if (file != nullptr)
00037     {
00038         String^ fileName = file->Name;
00039         // Deletes the file
00040         create_task(file->DeleteAsync()).then([this, fileName](task<void> task)
00041         {
00042             try
00043             {
00044                 task.get();
00045                 rootPage->SampleFile = nullptr;
00046                 rootPage->NotifyUser("The file '" + fileName + "' was deleted", NotifyType::StatusMessage);
00047             }
00048             catch (COMException^ ex)
00049             {
00050                 // I/O errors are reported as exceptions.
00051                 rootPage->HandleIoException(ex, "Error deleting file '" + fileName + "'");
00052             }
00053         });
00054     }
00055     else
00056     {
00057         rootPage->NotifyUserFileNotExist();
00058     }
00059 }
Generated on Fri Nov 15 2024 22:19:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FullScreenMode/cpp/Scenario2_Launch.xaml.h Source File

  • FullScreenMode
  • cpp

Scenario2_Launch.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Launch.g.h"
00015
00016 namespace SDKTemplate
00017 {
00018     [Windows::Foundation::Metadata::WebHostHidden]
00019     public ref class Scenario2_Launch sealed
00020     {
00021     public:
00022         Scenario2_Launch();
00023
00024     private:
00025         void LaunchInFullScreenModeCheckBox_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00026     };
00027 }
Generated on Fri Nov 15 2024 22:19:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cpp/Scenario1_Launched.xaml.h Source File

  • JumpList
  • cpp

Scenario1_Launched.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Launched.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario1_Launched sealed
00021     {
00022     public:
00023         Scenario1_Launched();
00024
00025     protected:
00026         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00027     };
00028 }
Generated on Fri Nov 15 2024 22:20:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MessageDialog/cs/CancelCommand.xaml.cs Source File

  • MessageDialog
  • cs

CancelCommand.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Popups;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using System;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class CancelCommand : Page
00021     {
00022         MainPage rootPage = MainPage.Current;
00023
00024         public CancelCommand()
00025         {
00026             this.InitializeComponent();
00027         }
00028
00029         /// <summary>
00030         /// Click handler for the 'CancelCommandButton' button.
00031         /// Demonstrates setting the command to be invoked when the 'escape' key is pressed.
00032         /// Also demonstrates retrieval of the label of the chosen command and setting a callback to a function.
00033         /// A message will be displayed indicating which command was invoked.
00034         /// In this scenario, 'Try again' is selected as the default choice, and the 'escape' key will invoke the command named 'Close'
00035         /// </summary>
00036         /// <param name="sender">The Object that caused this event to be fired.</param>
00037         /// <param name="e">State information and event data associated with the routed event.</param>
00038         private async void CancelCommandButton_Click(object sender, RoutedEventArgs e)
00039         {
00040             // Create the message dialog and set its content
00041             var messageDialog = new MessageDialog("No internet connection has been found.");
00042
00043             // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
00044             messageDialog.Commands.Add(new UICommand("Try again", new UICommandInvokedHandler(this.CommandInvokedHandler)));
00045             messageDialog.Commands.Add(new UICommand("Close", new UICommandInvokedHandler(this.CommandInvokedHandler)));
00046
00047             // Set the command that will be invoked by default
00048             messageDialog.DefaultCommandIndex = 0;
00049
00050             // Set the command to be invoked when escape is pressed
00051             messageDialog.CancelCommandIndex = 1;
00052
00053             // Show the message dialog
00054             await messageDialog.ShowAsync();
00055         }
00056
00057         #region Commands
00058         /// <summary>
00059         /// Callback function for the invocation of the dialog commands.
00060         /// </summary>
00061         /// <param name="command">The command that was invoked.</param>
00062         private void CommandInvokedHandler(IUICommand command)
00063         {
00064             // Display message showing the label of the command that was invoked
00065             rootPage.NotifyUser("The '" + command.Label + "' command has been selected.", NotifyType.StatusMessage);
00066         }
00067         #endregion
00068     }
00069 }
Generated on Fri Nov 15 2024 22:20:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SerialArduino/cs/Scenario2_LEDTemp.xaml.cs Source File

  • SerialArduino
  • cs

Scenario2_LEDTemp.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Diagnostics;
00014 using System.Threading;
00015
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 using Windows.Devices.SerialCommunication;
00022
00023 using System.Threading.Tasks;
00024 using Windows.Storage.Streams;
00025
00026 using SDKTemplate;
00027 using SerialArduino;
00028
00029 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00030
00031 namespace SerialArduino
00032 {
00033     /// <summary>
00034     /// An empty page that can be used on its own or navigated to within a Frame.
00035     /// </summary>
00036     public sealed partial class Scenario2_LEDTemp : Page, IDisposable
00037     {
00038
00039         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00040         // as NotifyUser()
00041         private MainPage rootPage = MainPage.Current;
00042
00043         // Track Read Operation
00044         private CancellationTokenSource ReadCancellationTokenSource;
00045         private Object ReadCancelLock = new Object();
00046
00047         DataReader DataReaderObject = null;
00048
00049         // Track Write Operation
00050         private CancellationTokenSource WriteCancellationTokenSource;
00051         private Object WriteCancelLock = new Object();
00052
00053         DataWriter DataWriterObject = null;
00054
00055         // Indicate if we navigate away from this page or not.
00056         private Boolean IsNavigatedAway;
00057
00058         public enum LedState
00059         {
00060             LedStateOn,
00061             LedStateOff
00062         };
00063
00064         public Scenario2_LEDTemp()
00065         {
00066             this.InitializeComponent();
00067         }
00068
00069         public void Dispose()
00070         {
00071             if (ReadCancellationTokenSource != null)
00072             {
00073                 ReadCancellationTokenSource.Dispose();
00074                 ReadCancellationTokenSource = null;
00075             }
00076
00077             if (WriteCancellationTokenSource != null)
00078             {
00079                 WriteCancellationTokenSource.Dispose();
00080                 WriteCancellationTokenSource = null;
00081             }
00082         }
00083
00084         /// <summary>
00085         /// Invoked when this page is about to be displayed in a Frame.
00086         ///
00087         /// We will enable/disable parts of the UI if the device doesn't support it.
00088         /// </summary>
00089         /// <param name="eventArgs">Event data that describes how this page was reached.  The Parameter
00090         /// property is typically used to configure the page.</param>
00091         protected override void OnNavigatedTo(NavigationEventArgs eventArgs)
00092         {
00093             if (EventHandlerForDevice.Current.Device == null)
00094             {
00095                 LEDTempScrollViewer.Visibility = Visibility.Collapsed;
00096                 MainPage.Current.NotifyUser("Device is not connected", NotifyType.ErrorMessage);
00097             }
00098             else
00099             {
00100                 MainPage.Current.NotifyUser("Connected to " + EventHandlerForDevice.Current.DeviceInformation.Id,
00101                                             NotifyType.StatusMessage);
00102
00103                 // So we can reset future tasks
00104                 ResetReadCancellationTokenSource();
00105                 ResetWriteCancellationTokenSource();
00106             }
00107         }
00108
00109         /// <summary>
00110         /// Cancel any on going tasks when navigating away from the page so the device is in a consistent state throughout
00111         /// all the scenarios
00112         /// </summary>
00113         /// <param name="eventArgs"></param>
00114         protected override void OnNavigatedFrom(NavigationEventArgs eventArgs)
00115         {
00116             IsNavigatedAway = true;
00117             CancelAllIoTasks();
00118         }
00119
00120         /// <summary>
00121         /// Invoked when the LED toggle switch is toggled
00122         /// </summary>
00123         private void LED3Switch_Toggled(object sender, RoutedEventArgs e)
00124         {
00125             if (LED3Switch.IsOn == true)
00126             {
00127                 WriteLedCommand("3", LedState.LedStateOn);
00128             }
00129             else
00130             {
00131                 WriteLedCommand("3", LedState.LedStateOff);
00132             }
00133         }
00134
00135         private void LED4Switch_Toggled(object sender, RoutedEventArgs e)
00136         {
00137             if (LED4Switch.IsOn == true)
00138             {
00139                 WriteLedCommand("4", LedState.LedStateOn);
00140             }
00141             else
00142             {
00143                 WriteLedCommand("4", LedState.LedStateOff);
00144             }
00145         }
00146
00147         private void LED5Switch_Toggled(object sender, RoutedEventArgs e)
00148         {
00149             if (LED5Switch.IsOn == true)
00150             {
00151                 WriteLedCommand("5", LedState.LedStateOn);
00152             }
00153             else
00154             {
00155                 WriteLedCommand("5", LedState.LedStateOff);
00156             }
00157         }
00158
00159         private void LED6Switch_Toggled(object sender, RoutedEventArgs e)
00160         {
00161             if (LED6Switch.IsOn == true)
00162             {
00163                 WriteLedCommand("6", LedState.LedStateOn);
00164             }
00165             else
00166             {
00167                 WriteLedCommand("6", LedState.LedStateOff);
00168             }
00169         }
00170
00171         /// <summary>
00172         /// Writes a custom command to the device to turn LEDs on/off
00173         /// using a DataWriter to the OutputStream
00174         /// </summary>
00175         /// <param name="ledNumber"></param>
00176         /// <param name="ledState"></param>
00177         private async void WriteLedCommand(String ledNumber, LedState ledState)
00178         {
00179             if (EventHandlerForDevice.Current.IsDeviceConnected)
00180             {
00181                 try
00182                 {
00183                     rootPage.NotifyUser("Writing...", NotifyType.StatusMessage);
00184
00185                     DataWriterObject = new DataWriter(EventHandlerForDevice.Current.Device.OutputStream);
00186
00187                     switch (ledState)
00188                     {
00189                         case LedState.LedStateOn:
00190                             DataWriterObject.WriteString("ledon " + ledNumber + "\r");
00191                             break;
00192
00193                         case LedState.LedStateOff:
00194                             DataWriterObject.WriteString("ledoff " + ledNumber + "\r");
00195                             break;
00196
00197                         default:
00198                             break;
00199                     }
00200
00201                     await WriteAsync(WriteCancellationTokenSource.Token);
00202                 }
00203                 catch (OperationCanceledException /*exception*/)
00204                 {
00205                     NotifyWriteTaskCanceled();
00206                 }
00207                 catch (Exception exception)
00208                 {
00209                     MainPage.Current.NotifyUser(exception.Message.ToString(), NotifyType.ErrorMessage);
00210                     Debug.WriteLine(exception.Message.ToString());
00211                 }
00212                 finally
00213                 {
00214                     DataWriterObject.DetachStream();
00215                     DataWriterObject = null;
00216                 }
00217             }
00218             else
00219             {
00220                 Utilities.NotifyDeviceNotConnected();
00221             }
00222         }
00223
00224         /// <summary>
00225         /// Invoked when the Temperature Button is clicked
00226         /// </summary>
00227         private async void TemperatureButton_Click(object sender, RoutedEventArgs e)
00228         {
00229             if (EventHandlerForDevice.Current.IsDeviceConnected)
00230             {
00231                 try
00232                 {
00233                     rootPage.NotifyUser("Getting temperature...", NotifyType.StatusMessage);
00234
00235                     DataWriterObject = new DataWriter(EventHandlerForDevice.Current.Device.OutputStream);
00236                     DataWriterObject.WriteString("temp\r");
00237
00238                     await WriteAsync(WriteCancellationTokenSource.Token);
00239                 }
00240                 catch (OperationCanceledException /*exception*/)
00241                 {
00242                     NotifyWriteTaskCanceled();
00243                 }
00244                 catch (Exception exception)
00245                 {
00246                     MainPage.Current.NotifyUser(exception.Message.ToString(), NotifyType.ErrorMessage);
00247                     Debug.WriteLine(exception.Message.ToString());
00248                 }
00249                 finally
00250                 {
00251                     DataWriterObject.DetachStream();
00252                     DataWriterObject = null;
00253                 }
00254
00255                 try
00256                 {
00257                     TemperatureValue.Text = String.Empty;
00258
00259                     DataReaderObject = new DataReader(EventHandlerForDevice.Current.Device.InputStream);
00260                     await ReadAsync(ReadCancellationTokenSource.Token);
00261                 }
00262                 catch (OperationCanceledException /*exception*/)
00263                 {
00264                     NotifyReadTaskCanceled();
00265                 }
00266                 catch (Exception exception)
00267                 {
00268                     MainPage.Current.NotifyUser(exception.Message.ToString(), NotifyType.ErrorMessage);
00269                     Debug.WriteLine(exception.Message.ToString());
00270                 }
00271                 finally
00272                 {
00273                     DataReaderObject.DetachStream();
00274                     DataReaderObject = null;
00275                 }
00276             }
00277             else
00278             {
00279                 Utilities.NotifyDeviceNotConnected();
00280             }
00281         }
00282
00283         /// <summary>
00284         /// Write to the output stream using a task
00285         /// </summary>
00286         /// <param name="cancellationToken"></param>
00287         private async Task WriteAsync(CancellationToken cancellationToken)
00288         {
00289             Task<UInt32> storeAsyncTask;
00290
00291             // Don't start any IO if we canceled the task
00292             lock (WriteCancelLock)
00293             {
00294                 cancellationToken.ThrowIfCancellationRequested();
00295
00296                 // Cancellation Token will be used so we can stop the task operation explicitly
00297                 // The completion function should still be called so that we can properly handle a canceled task
00298                 storeAsyncTask = DataWriterObject.StoreAsync().AsTask(cancellationToken);
00299             }
00300
00301             UInt32 bytesWritten = await storeAsyncTask;
00302             rootPage.NotifyUser("Write completed - " + bytesWritten.ToString() + " bytes written", NotifyType.StatusMessage);
00303         }
00304
00305         /// <summary>
00306         /// Read from the input output stream using a task
00307         /// </summary>
00308         /// <param name="cancellationToken"></param>
00309         private async Task ReadAsync(CancellationToken cancellationToken)
00310         {
00311             Task<UInt32> loadAsyncTask;
00312
00313             uint ReadBufferLength = 7;
00314
00315             // Don't start any IO if we canceled the task
00316             lock (ReadCancelLock)
00317             {
00318                 cancellationToken.ThrowIfCancellationRequested();
00319
00320                 // Cancellation Token will be used so we can stop the task operation explicitly
00321                 // The completion function should still be called so that we can properly handle a canceled task
00322                 DataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
00323                 loadAsyncTask = DataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken);
00324             }
00325
00326             UInt32 bytesRead = await loadAsyncTask;
00327
00328             if (bytesRead > 0)
00329             {
00330                 String temp = DataReaderObject.ReadString(bytesRead);
00331                 TemperatureValue.Text = temp.Trim() + "°C";
00332             }
00333
00334             rootPage.NotifyUser("Read completed - " + bytesRead.ToString() + " bytes were read", NotifyType.StatusMessage);
00335         }
00336
00337
00338         /// <summary>
00339         /// It is important to be able to cancel tasks that may take a while to complete. Cancelling tasks is the only way to stop any pending IO
00340         /// operations asynchronously. If the Serial Device is closed/deleted while there are pending IOs, the destructor will cancel all pending IO
00341         /// operations.
00342         /// </summary>
00343         ///
00344
00345         private void CancelReadTask()
00346         {
00347             lock (ReadCancelLock)
00348             {
00349                 if (ReadCancellationTokenSource != null)
00350                 {
00351                     if (!ReadCancellationTokenSource.IsCancellationRequested)
00352                     {
00353                         ReadCancellationTokenSource.Cancel();
00354
00355                         // Existing IO already has a local copy of the old cancellation token so this reset won't affect it
00356                         ResetReadCancellationTokenSource();
00357                     }
00358                 }
00359             }
00360         }
00361
00362         private void CancelWriteTask()
00363         {
00364             lock (WriteCancelLock)
00365             {
00366                 if (WriteCancellationTokenSource != null)
00367                 {
00368                     if (!WriteCancellationTokenSource.IsCancellationRequested)
00369                     {
00370                         WriteCancellationTokenSource.Cancel();
00371
00372                         // Existing IO already has a local copy of the old cancellation token so this reset won't affect it
00373                         ResetWriteCancellationTokenSource();
00374                     }
00375                 }
00376             }
00377         }
00378         private void CancelAllIoTasks()
00379         {
00380             CancelReadTask();
00381             CancelWriteTask();
00382         }
00383
00384         private void ResetReadCancellationTokenSource()
00385         {
00386             // Create a new cancellation token source so that can cancel all the tokens again
00387             ReadCancellationTokenSource = new CancellationTokenSource();
00388
00389             // Hook the cancellation callback (called whenever Task.cancel is called)
00390             ReadCancellationTokenSource.Token.Register(() => NotifyReadCancelingTask());
00391         }
00392
00393         private void ResetWriteCancellationTokenSource()
00394         {
00395             // Create a new cancellation token source so that can cancel all the tokens again
00396             WriteCancellationTokenSource = new CancellationTokenSource();
00397
00398             // Hook the cancellation callback (called whenever Task.cancel is called)
00399             WriteCancellationTokenSource.Token.Register(() => NotifyWriteCancelingTask());
00400         }
00401
00402         /// <summary>
00403         /// Print a status message saying we are canceling a task and disable all buttons to prevent multiple cancel requests.
00404         /// <summary>
00405         private async void NotifyReadCancelingTask()
00406         {
00407             // Setting the dispatcher priority to high allows the UI to handle disabling of all the buttons
00408             // before any of the IO completion callbacks get a chance to modify the UI; that way this method
00409             // will never get the opportunity to overwrite UI changes made by IO callbacks
00410             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.High,
00411                 new DispatchedHandler(() =>
00412                 {
00413                     if (!IsNavigatedAway)
00414                     {
00415                         rootPage.NotifyUser("Canceling Read... Please wait...", NotifyType.StatusMessage);
00416                     }
00417                 }));
00418         }
00419
00420         private async void NotifyWriteCancelingTask()
00421         {
00422             // Setting the dispatcher priority to high allows the UI to handle disabling of all the buttons
00423             // before any of the IO completion callbacks get a chance to modify the UI; that way this method
00424             // will never get the opportunity to overwrite UI changes made by IO callbacks
00425             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.High,
00426                 new DispatchedHandler(() =>
00427                 {
00428                     if (!IsNavigatedAway)
00429                     {
00430                         rootPage.NotifyUser("Canceling Write... Please wait...", NotifyType.StatusMessage);
00431                     }
00432                 }));
00433         }
00434
00435
00436         /// <summary>
00437         /// Notifies the UI that the operation has been cancelled
00438         /// </summary>
00439         private async void NotifyReadTaskCanceled()
00440         {
00441             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00442                 new DispatchedHandler(() =>
00443                 {
00444                     if (!IsNavigatedAway)
00445                     {
00446                         rootPage.NotifyUser("Read request has been cancelled", NotifyType.StatusMessage);
00447                     }
00448                 }));
00449         }
00450
00451         private async void NotifyWriteTaskCanceled()
00452         {
00453             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00454                 new DispatchedHandler(() =>
00455                 {
00456                     if (!IsNavigatedAway)
00457                     {
00458                         rootPage.NotifyUser("Write request has been cancelled", NotifyType.StatusMessage);
00459                     }
00460                 }));
00461         }
00462
00463     }
00464 }
Generated on Fri Nov 15 2024 22:21:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cppwinrt/pch.cpp Source File

  • FileThumbnails
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/pch.h Source File

  • Printing
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
ButtonPin_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ButtonUpdate_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
Update(string tileId, XmlDocument doc) | ScenarioElement | [inline, private]
Generated on Fri Nov 15 2024 22:23:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomUsbDeviceAccess/cs/BackgroundTask/IoSyncBackgroundTask.cs Source File

  • CustomUsbDeviceAccess
  • cs
  • BackgroundTask

IoSyncBackgroundTask.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using System;
00008 using System.Collections.Generic;
00009 using System.Linq;
00010 using System.Text;
00011 using System.Threading;
00012 using System.Threading.Tasks;
00013 using Windows.ApplicationModel.Background;
00014 using Windows.Devices.Background;
00015 using Windows.Devices.Enumeration;
00016 using Windows.Devices.Usb;
00017 using Windows.Storage;
00018 using Windows.Storage.Streams;
00019
00020 namespace BackgroundTask
00021 {
00022     public sealed class IoSyncBackgroundTask : IBackgroundTask, IDisposable
00023     {
00024         // Deferral must be used to prevent the background task from terminating
00025         // while an asynchronous operation is still active
00026         private BackgroundTaskDeferral deferral;
00027         private IBackgroundTaskInstance backgroundTaskInstance;
00028
00029         private DeviceUseDetails deviceSyncDetails;
00030
00031         private UsbDevice device;
00032
00033         private CancellationTokenSource cancellationTokenSource;
00034
00035         public async void Run(IBackgroundTaskInstance taskInstance)
00036         {
00037             backgroundTaskInstance = taskInstance;
00038
00039             // Trigger details contain device id and arguments that are provided by the caller in the main app
00040             // The taskInstance can always be casted to DeviceUseDetails if this background task was started using a DeviceUseTrigger
00041             deviceSyncDetails = (DeviceUseDetails)taskInstance.TriggerDetails;
00042
00043             deferral = taskInstance.GetDeferral();
00044
00045             try
00046             {
00047                 backgroundTaskInstance.Progress = 0;
00048
00049                 cancellationTokenSource = new CancellationTokenSource();
00050
00051                 taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
00052
00053                 // For simplicity, no error checking will be done after opening the device. Ideally, one should always
00054                 // check if the device was successfully opened and respond accordingly. For an example on how to do this,
00055                 // please see Scenario 1 of this sample.
00056                 //
00057                 // The user may also block the device via the settings charm while we are syncing (in background task). In order to deal with
00058                 // the user changing permissions, we have to listen for DeviceAccessInformation->AccessChanged events. See EventHandlerForDevice
00059                 // for how to handle DeviceAccessInformation.AccessChanged event.
00060                 OpenDevice();
00061
00062                 // The sample only demonstrates a bulk write for simplicity.
00063                 // IO operations can be done after opening the device.
00064                 // For more information on BackgroundTasks, please see the BackgroundTask sample on MSDN.
00065                 UInt32 bytesWritten = await Task.Run(() =>
00066                 {
00067                     return WriteToDeviceAsync();
00068                 },
00069                 cancellationTokenSource.Token);
00070
00071                 ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskResult] = bytesWritten;
00072                 ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskStatus] = BackgroundTaskInformation.TaskCompleted;
00073             }
00074             catch (OperationCanceledException /*ex*/)
00075             {
00076                 ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskResult] = 0;
00077                 ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskStatus] = BackgroundTaskInformation.TaskCanceled;
00078             }
00079             finally
00080             {
00081                 // Close the device because we are finished syncing and so that the app may reopen the device
00082                 device.Dispose();
00083
00084                 device = null;
00085             }
00086
00087             // Complete the background task (this raises the OnCompleted event on the corresponding BackgroundTaskRegistration)
00088             deferral.Complete();
00089         }
00090
00091         public void Dispose()
00092         {
00093             if (cancellationTokenSource != null)
00094             {
00095                 cancellationTokenSource.Dispose();
00096                 cancellationTokenSource = null;
00097             }
00098         }
00099
00100         private void OpenDevice()
00101         {
00102             var deviceTask = UsbDevice.FromIdAsync(deviceSyncDetails.DeviceId).AsTask(cancellationTokenSource.Token);
00103
00104             deviceTask.Wait();
00105
00106             device = deviceTask.Result;
00107
00108             // We opened the device, so notify the app that we've completed a bit of the background task
00109             backgroundTaskInstance.Progress = 10;
00110         }
00111
00112         /// <summary>
00113         /// Cancels opening device and the IO operation, whichever is still running
00114         /// </summary>
00115         /// <param name="sender"></param>
00116         /// <param name="reason"></param>
00117         private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
00118         {
00119             cancellationTokenSource.Cancel();
00120
00121             backgroundTaskInstance.Progress = 0;
00122         }
00123
00124         /// <summary>
00125         /// This method exists to demonstrate IO with the device since that is what is expected for a sync scenario. There already exists
00126         /// scenarios in this sample that demonstrate how to properly perform IO with the device, please see those for more information on
00127         /// performing various kinds of IO.
00128         ///
00129         /// Writes to device's first bulkOut endpoint of the default interface and updates progress per write.
00130         /// When this method finishes, the progress will be 100.
00131         /// </summary>
00132         /// <returns>Total number of bytes written to the device</returns>
00133         private async Task<UInt32> WriteToDeviceAsync()
00134         {
00135             UInt32 totalBytesWritten = 0;
00136
00137             var firstBulkOutEndpoint = device.DefaultInterface.BulkOutPipes[0];
00138
00139             // Distributes the remaining progress (out of 100) among each write
00140             double progressIncreasePerWrite = (100 - backgroundTaskInstance.Progress) / ((double)Sync.NumberOfTimesToWrite);
00141
00142             // This progress will be incremented by the more accurate progressIncreasePerWrite value and then rounded up before notifying the app
00143             double syncProgress = backgroundTaskInstance.Progress;
00144
00145             var dataWriter = new DataWriter(firstBulkOutEndpoint.OutputStream);
00146
00147             // Create an array, all default initialized to 0, and write it to the buffer
00148             // The data inside the buffer will be garbage
00149             var arrayBuffer = new Byte[Sync.BytesToWriteAtATime];
00150
00151             for (UInt32 timesWritten = 0; timesWritten < Sync.NumberOfTimesToWrite; timesWritten++)
00152             {
00153                 cancellationTokenSource.Token.ThrowIfCancellationRequested();
00154
00155                 dataWriter.WriteBytes(arrayBuffer);
00156
00157                 totalBytesWritten += await dataWriter.StoreAsync().AsTask(cancellationTokenSource.Token);
00158
00159                 syncProgress += progressIncreasePerWrite;
00160
00161                 // Rounding our value up because backgroundTaskInstance.progress is an unsigned int
00162                 backgroundTaskInstance.Progress = Convert.ToUInt32(Math.Ceiling(syncProgress));
00163             }
00164
00165             return totalBytesWritten;
00166         }
00167     }
00168 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/App.xaml.cpp Source File

  • Simple3DGameXaml
  • cpp

App.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "App.xaml.h"
00014
00015 using namespace Platform;
00016 using namespace Simple3DGameXaml;
00017 using namespace Windows::ApplicationModel;
00018 using namespace Windows::ApplicationModel::Activation;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::UI::Core;
00021 using namespace Windows::UI::Xaml;
00022
00023
00024 //----------------------------------------------------------------------
00025
00026 App::App()
00027 {
00028     InitializeComponent();
00029     Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
00030     Resuming += ref new EventHandler<Object^>(this, &App::OnResuming);
00031
00032 #if defined(_DEBUG)
00033     UnhandledException += ref new UnhandledExceptionEventHandler([](Object^ /* sender */, UnhandledExceptionEventArgs^ args)
00034     {
00035         String^ error = "Simple3DGameXaml::App::UnhandledException: " + args->Message + "\n";
00036         OutputDebugStringW(error->Data());
00037     });
00038 #endif
00039
00040     RequiresPointerMode = ApplicationRequiresPointerMode::WhenRequested;
00041 }
00042
00043 //----------------------------------------------------------------------
00044
00045 void App::OnLaunched(_In_ LaunchActivatedEventArgs^ /* args */)
00046 {
00047     m_mainPage = ref new DirectXPage();
00048
00049     Window::Current->Content = m_mainPage;
00050     Window::Current->Activate();
00051 }
00052
00053 //----------------------------------------------------------------------
00054
00055 void App::OnSuspending(
00056     _In_ Object^ /* sender */,
00057     _In_ SuspendingEventArgs^ args
00058     )
00059 {
00060     m_mainPage->OnSuspending();
00061 }
00062
00063 //----------------------------------------------------------------------
00064
00065 void App::OnResuming(
00066     _In_ Object^ /* sender */,
00067     _In_ Object^ /* args */
00068     )
00069 {
00070     m_mainPage->OnResuming();
00071 }
00072
00073 //----------------------------------------------------------------------
Generated on Fri Nov 15 2024 22:16:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Magnetometer/cs/Scenario1_DataEvents.xaml.cs Source File

  • Magnetometer
  • cs

Scenario1_DataEvents.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Devices.Sensors;
00014 using Windows.Foundation;
00015 using Windows.UI.Core;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario1_DataEvents : Page
00023     {
00024         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00025         // as NotifyUser()
00026         MainPage rootPage = MainPage.Current;
00027
00028         private Magnetometer _magnetometer;
00029         private uint _desiredReportInterval;
00030
00031         public Scenario1_DataEvents()
00032         {
00033             this.InitializeComponent();
00034
00035             _magnetometer = Magnetometer.GetDefault();
00036             if (_magnetometer != null)
00037             {
00038                 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00039                 // This value will be used later to activate the sensor.
00040                 uint minReportInterval = _magnetometer.MinimumReportInterval;
00041                 _desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;
00042             }
00043             else
00044             {
00045                 rootPage.NotifyUser("No magnetometer found", NotifyType.ErrorMessage);
00046             }
00047         }
00048
00049         /// <summary>
00050         /// Invoked when this page is about to be displayed in a Frame.
00051         /// </summary>
00052         /// <param name="e">Event data that describes how this page was reached. The Parameter
00053         /// property is typically used to configure the page.</param>
00054         protected override void OnNavigatedTo(NavigationEventArgs e)
00055         {
00056             ScenarioEnableButton.IsEnabled = true;
00057             ScenarioDisableButton.IsEnabled = false;
00058         }
00059
00060         /// <summary>
00061         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00062         /// </summary>
00063         /// <param name="e">
00064         /// Event data that can be examined by overriding code. The event data is representative
00065         /// of the navigation that will unload the current Page unless canceled. The
00066         /// navigation can potentially be canceled by setting Cancel.
00067         /// </param>
00068         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00069         {
00070             if (ScenarioDisableButton.IsEnabled)
00071             {
00072                 Window.Current.VisibilityChanged -= VisibilityChanged;
00073                 _magnetometer.ReadingChanged -= ReadingChanged;
00074
00075                 // Restore the default report interval to release resources while the sensor is not in use
00076                 _magnetometer.ReportInterval = 0;
00077             }
00078         }
00079
00080         /// <summary>
00081         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00082         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00083         /// </summary>
00084         /// <param name="sender"></param>
00085         /// <param name="e">
00086         /// Event data that can be examined for the current visibility state.
00087         /// </param>
00088         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00089         {
00090             if (ScenarioDisableButton.IsEnabled)
00091             {
00092                 if (e.Visible)
00093                 {
00094                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00095                     _magnetometer.ReadingChanged += ReadingChanged;
00096                 }
00097                 else
00098                 {
00099                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00100                     _magnetometer.ReadingChanged -= ReadingChanged;
00101                 }
00102             }
00103         }
00104
00105         /// <summary>
00106         /// This is the event handler for ReadingChanged events.
00107         /// </summary>
00108         /// <param name="sender"></param>
00109         /// <param name="e"></param>
00110         async private void ReadingChanged(object sender, MagnetometerReadingChangedEventArgs e)
00111         {
00112             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00113             {
00114                 MagnetometerReading reading = e.Reading;
00115                 ScenarioOutput_X.Text = String.Format("{0,5:0.00}", reading.MagneticFieldX);
00116                 ScenarioOutput_Y.Text = String.Format("{0,5:0.00}", reading.MagneticFieldY);
00117                 ScenarioOutput_Z.Text = String.Format("{0,5:0.00}", reading.MagneticFieldZ);
00118             });
00119         }
00120
00121         /// <summary>
00122         /// This is the click handler for the 'Enable' button.
00123         /// </summary>
00124         /// <param name="sender"></param>
00125         /// <param name="e"></param>
00126         private void ScenarioEnable(object sender, RoutedEventArgs e)
00127         {
00128             if (_magnetometer != null)
00129             {
00130                 // Establish the report interval
00131                 _magnetometer.ReportInterval = _desiredReportInterval;
00132
00133                 Window.Current.VisibilityChanged += VisibilityChanged;
00134                 _magnetometer.ReadingChanged += ReadingChanged;
00135
00136                 ScenarioEnableButton.IsEnabled = false;
00137                 ScenarioDisableButton.IsEnabled = true;
00138             }
00139             else
00140             {
00141                 rootPage.NotifyUser("No magnetometer found", NotifyType.ErrorMessage);
00142             }
00143         }
00144
00145         /// <summary>
00146         /// This is the click handler for the 'Disable' button.
00147         /// </summary>
00148         /// <param name="sender"></param>
00149         /// <param name="e"></param>
00150         private void ScenarioDisable(object sender, RoutedEventArgs e)
00151         {
00152             Window.Current.VisibilityChanged -= VisibilityChanged;
00153             _magnetometer.ReadingChanged -= ReadingChanged;
00154
00155             // Restore the default report interval to release resources while the sensor is not in use
00156             _magnetometer.ReportInterval = 0;
00157
00158             ScenarioEnableButton.IsEnabled = true;
00159             ScenarioDisableButton.IsEnabled = false;
00160         }
00161     }
00162 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

WASAPICapture Member List

This is the complete list of members for WASAPICapture, including all inherited members.
ActivateCompleted(IActivateAudioInterfaceAsyncOperation *operation) | WASAPICapture |
AsyncInitializeAudioDevice() noexcept | WASAPICapture |
AsyncStartCapture() | WASAPICapture |
AsyncStopCapture() | WASAPICapture |
AsyncStoreData() | WASAPICapture | [private]
CreateWAVFile() | WASAPICapture | [private]
DeviceState() | DeviceStateSourceT< WASAPICapture > | [inline, private]
DeviceStateChanged(Windows::Foundation::TypedEventHandler< IDeviceStateSource, SDKTemplate::DeviceStateChangedEventArgs > const &handler) | DeviceStateSourceT< WASAPICapture > | [inline, private]
DeviceStateChanged(event_token token) | DeviceStateSourceT< WASAPICapture > | [inline, private]
FixWAVHeader() | WASAPICapture | [private]
InitializeScopeData() | WASAPICapture | [private]
m_audioCaptureClient | WASAPICapture | [private]
m_audioClient | WASAPICapture | [private]
m_bufferFrames | WASAPICapture | [private]
m_bytesSinceLastFlush | WASAPICapture | [private]
m_contentStream | WASAPICapture | [private]
m_dataSize | WASAPICapture | [private]
m_defaultPeriodInFrames | WASAPICapture | [private]
m_deviceState | DeviceStateSourceT< WASAPICapture > | [private]
m_deviceStateChanged | DeviceStateSourceT< WASAPICapture > | [private]
m_fundamentalPeriodInFrames | WASAPICapture | [private]
m_headerSize | WASAPICapture | [private]
m_isLowLatency | WASAPICapture | [private]
m_lock | WASAPICapture | [private]
m_maxPeriodInFrames | WASAPICapture | [private]
m_minPeriodInFrames | WASAPICapture | [private]
m_mixFormat | WASAPICapture | [private]
m_outputStream | WASAPICapture | [private]
m_plotDataBuffer | WASAPICapture | [private]
m_plotDataMaxPoints | WASAPICapture | [private]
m_plotDataPointsFilled | WASAPICapture | [private]
m_plotDataReady | PlotDataSourceT< WASAPICapture > | [private]
m_sampleReadyAsyncResult | WASAPICapture | [private]
m_sampleReadyKey | WASAPICapture | [private]
m_writing | WASAPICapture | [private]
OnAudioSampleRequested() | WASAPICapture | [private]
OnFinishCapture(IMFAsyncResult *pResult) | WASAPICapture | [private]
OnSampleReady(IMFAsyncResult *pResult) | WASAPICapture | [private]
OnSendScopeData(IMFAsyncResult *pResult) | WASAPICapture | [private]
OnStartCapture(IMFAsyncResult *pResult) | WASAPICapture | [private]
OnStopCapture(IMFAsyncResult *pResult) | WASAPICapture | [private]
PlotDataReady(Windows::Foundation::TypedEventHandler< IPlotDataSource, SDKTemplate::PlotDataReadyEventArgs > const &handler) | PlotDataSourceT< WASAPICapture > | [inline, private]
PlotDataReady(event_token token) | PlotDataSourceT< WASAPICapture > | [inline, private]
ProcessScopeData(array_view< uint8_t > rawBytes) | WASAPICapture | [private]
ReportPlotDataReady(Windows::Storage::Streams::IBuffer const &buffer) | PlotDataSourceT< WASAPICapture > | [inline, private]
SetLowLatencyCapture(bool value) | WASAPICapture | [inline]
SetState(enum DeviceState state, HRESULT error=S_OK) | DeviceStateSourceT< WASAPICapture > | [inline, private]
SetStateNoNotify(enum DeviceState state) | DeviceStateSourceT< WASAPICapture > | [inline, private]
WASAPICapture() | WASAPICapture |
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario2WinRTComponent/OnboardingStructures.h Source File

  • AllJoyn
  • Common
  • Scenario2WinRTComponent

OnboardingStructures.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #pragma once
00022
00023 namespace org { namespace alljoyn { namespace Onboarding {
00024
00025 public ref class OnboardingScanListItem sealed
00026 {
00027 public:
00028     property Platform::String^ Value1
00029     {
00030         Platform::String^ get() { return m_value1; }
00031         void set(Platform::String^ value) { m_value1 = value; }
00032     }
00033
00034     property int16 Value2
00035     {
00036         int16 get() { return m_value2; }
00037         void set(int16 value) { m_value2 = value; }
00038     }
00039
00040 private:
00041     Platform::String^ m_value1;
00042     int16 m_value2;
00043 };
00044
00045 public ref class Onboarding sealed
00046 {
00047 public:
00048     property int16 Value1
00049     {
00050         int16 get() { return m_value1; }
00051         void set(int16 value) { m_value1 = value; }
00052     }
00053
00054     property Platform::String^ Value2
00055     {
00056         Platform::String^ get() { return m_value2; }
00057         void set(Platform::String^ value) { m_value2 = value; }
00058     }
00059
00060 private:
00061     int16 m_value1;
00062     Platform::String^ m_value2;
00063 };
00064
00065 public ref class OnboardingLastError sealed
00066 {
00067 public:
00068     property int16 Value1
00069     {
00070         int16 get() { return m_value1; }
00071         void set(int16 value) { m_value1 = value; }
00072     }
00073
00074     property Platform::String^ Value2
00075     {
00076         Platform::String^ get() { return m_value2; }
00077         void set(Platform::String^ value) { m_value2 = value; }
00078     }
00079
00080 private:
00081     int16 m_value1;
00082     Platform::String^ m_value2;
00083 };
00084
00085 public ref class AllJoynMessageArgStructure sealed : Windows::Foundation::Collections::IVector<Platform::Object^>
00086 {
00087 public:
00088     AllJoynMessageArgStructure()
00089     {
00090         m_vector = ref new Platform::Collections::Vector<Platform::Object^>();
00091     }
00092
00093     virtual Windows::Foundation::Collections::IIterator<Platform::Object^>^ First()
00094     {
00095         return m_vector->First();
00096     }
00097
00098     virtual Platform::Object^ GetAt(unsigned int index)
00099     {
00100         return m_vector->GetAt(index);
00101     }
00102
00103     virtual property unsigned int Size {
00104         virtual unsigned int get()
00105         {
00106             return m_vector->Size;
00107         }
00108     }
00109
00110     virtual bool IndexOf(Platform::Object^ value, unsigned int * index)
00111     {
00112         return m_vector->IndexOf(value, index);
00113     }
00114
00115     virtual unsigned int GetMany(unsigned int startIndex, Platform::WriteOnlyArray<Platform::Object^>^ items)
00116     {
00117         return m_vector->GetMany(startIndex, items);
00118     }
00119
00120     virtual Windows::Foundation::Collections::IVectorView<Platform::Object^>^ GetView()
00121     {
00122         return m_vector->GetView();
00123     }
00124
00125     virtual void SetAt(unsigned int index, Platform::Object^ value)
00126     {
00127         return m_vector->SetAt(index, value);
00128     }
00129
00130     virtual void InsertAt(unsigned int index, Platform::Object^ value)
00131     {
00132         return m_vector->InsertAt(index, value);
00133     }
00134
00135     virtual void Append(Platform::Object^ value)
00136     {
00137         return m_vector->Append(value);
00138     }
00139
00140     virtual void RemoveAt(unsigned int index)
00141     {
00142         return m_vector->RemoveAt(index);
00143     }
00144
00145     virtual void RemoveAtEnd()
00146     {
00147         return m_vector->RemoveAtEnd();
00148     }
00149
00150     virtual void Clear()
00151     {
00152         return m_vector->Clear();
00153     }
00154
00155     virtual void ReplaceAll(const Platform::Array<Platform::Object^>^ items)
00156     {
00157         return m_vector->ReplaceAll(items);
00158     }
00159
00160 private:
00161     Platform::Collections::Vector<Platform::Object^>^ m_vector;
00162 };
00163 } } }
00164
00165 partial ref class TypeConversionHelpers
00166 {
00167 internal:
00168     static _Check_return_ int32 GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Out_ org::alljoyn::Onboarding::OnboardingScanListItem^* value)
00169     {
00170         UNREFERENCED_PARAMETER(signature);
00171
00172         (*value) = ref new org::alljoyn::Onboarding::OnboardingScanListItem();
00173
00174         alljoyn_msgarg argument1;
00175         alljoyn_msgarg argument2;
00176         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_get(argument, "(**)", &argument1, &argument2));
00177
00178         Platform::String^ value1;
00179         RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(argument1, "s", &value1));
00180         (*value)->Value1 = value1;
00181         int16 value2;
00182         RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(argument2, "n", &value2));
00183         (*value)->Value2 = value2;
00184
00185         return ER_OK;
00186     }
00187
00188     static _Check_return_ int32 SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ org::alljoyn::Onboarding::OnboardingScanListItem^ value)
00189     {
00190         UNREFERENCED_PARAMETER(signature);
00191
00192         auto argument1 = alljoyn_msgarg_create();
00193         RETURN_IF_QSTATUS_ERROR(SetAllJoynMessageArg(argument1, "s", value->Value1));
00194         auto argument2 = alljoyn_msgarg_create();
00195         RETURN_IF_QSTATUS_ERROR(SetAllJoynMessageArg(argument2, "n", value->Value2));
00196
00197         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_set(argument, "(**)", argument1, argument2));
00198         alljoyn_msgarg_stabilize(argument);
00199         alljoyn_msgarg_destroy(argument1);
00200         alljoyn_msgarg_destroy(argument2);
00201
00202         return ER_OK;
00203     }
00204
00205     static _Check_return_ int32 GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Out_ org::alljoyn::Onboarding::Onboarding^* value)
00206     {
00207         UNREFERENCED_PARAMETER(signature);
00208
00209         (*value) = ref new org::alljoyn::Onboarding::Onboarding();
00210
00211         alljoyn_msgarg argument1;
00212         alljoyn_msgarg argument2;
00213         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_get(argument, "(**)", &argument1, &argument2));
00214
00215         int16 value1;
00216         RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(argument1, "n", &value1));
00217         (*value)->Value1 = value1;
00218         Platform::String^ value2;
00219         RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(argument2, "s", &value2));
00220         (*value)->Value2 = value2;
00221
00222         return ER_OK;
00223     }
00224
00225     static _Check_return_ int32 SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ org::alljoyn::Onboarding::Onboarding^ value)
00226     {
00227         UNREFERENCED_PARAMETER(signature);
00228
00229         auto argument1 = alljoyn_msgarg_create();
00230         RETURN_IF_QSTATUS_ERROR(SetAllJoynMessageArg(argument1, "n", value->Value1));
00231         auto argument2 = alljoyn_msgarg_create();
00232         RETURN_IF_QSTATUS_ERROR(SetAllJoynMessageArg(argument2, "s", value->Value2));
00233
00234         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_set(argument, "(**)", argument1, argument2));
00235         alljoyn_msgarg_stabilize(argument);
00236         alljoyn_msgarg_destroy(argument1);
00237         alljoyn_msgarg_destroy(argument2);
00238
00239         return ER_OK;
00240     }
00241
00242     static _Check_return_ int32 GetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _Out_ org::alljoyn::Onboarding::OnboardingLastError^* value)
00243     {
00244         UNREFERENCED_PARAMETER(signature);
00245
00246         (*value) = ref new org::alljoyn::Onboarding::OnboardingLastError();
00247
00248         alljoyn_msgarg argument1;
00249         alljoyn_msgarg argument2;
00250         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_get(argument, "(**)", &argument1, &argument2));
00251
00252         int16 value1;
00253         RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(argument1, "n", &value1));
00254         (*value)->Value1 = value1;
00255         Platform::String^ value2;
00256         RETURN_IF_QSTATUS_ERROR(GetAllJoynMessageArg(argument2, "s", &value2));
00257         (*value)->Value2 = value2;
00258
00259         return ER_OK;
00260     }
00261
00262     static _Check_return_ int32 SetAllJoynMessageArg(_In_ alljoyn_msgarg argument, _In_ PCSTR signature, _In_ org::alljoyn::Onboarding::OnboardingLastError^ value)
00263     {
00264         UNREFERENCED_PARAMETER(signature);
00265
00266         auto argument1 = alljoyn_msgarg_create();
00267         RETURN_IF_QSTATUS_ERROR(SetAllJoynMessageArg(argument1, "n", value->Value1));
00268         auto argument2 = alljoyn_msgarg_create();
00269         RETURN_IF_QSTATUS_ERROR(SetAllJoynMessageArg(argument2, "s", value->Value2));
00270
00271         RETURN_IF_QSTATUS_ERROR(alljoyn_msgarg_set(argument, "(**)", argument1, argument2));
00272         alljoyn_msgarg_stabilize(argument);
00273         alljoyn_msgarg_destroy(argument1);
00274         alljoyn_msgarg_destroy(argument2);
00275
00276         return ER_OK;
00277     }
00278
00279 };
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/CustomVertexShaderRenderer.h Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

CustomVertexShaderRenderer.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "DeviceResources.h"
00015 #include "BasicTimer.h"
00016 #include "WaveEffect.h"
00017
00018 namespace CustomVertexShader
00019 {
00020     // This sample renderer instantiates a basic rendering pipeline.
00021     class CustomVertexShaderRenderer
00022     {
00023     public:
00024         CustomVertexShaderRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00025         void CreateDeviceIndependentResources();
00026         void CreateDeviceDependentResources();
00027         void CreateWindowSizeDependentResources();
00028         void ReleaseDeviceDependentResources();
00029         void UpdateManipulationState(_In_ Windows::UI::Input::ManipulationUpdatedEventArgs^ args);
00030         void Update();
00031         void Render();
00032
00033         // Process lifetime management handlers.
00034         void SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00035         void LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00036
00037     private:
00038         void UpdateImageScale(float scale);
00039
00040     private:
00041         // Cached pointer to device resources.
00042         std::shared_ptr<DX::DeviceResources>                    m_deviceResources;
00043         Platform::Agile<Windows::UI::Input::GestureRecognizer>  m_gestureRecognizer;
00044         Microsoft::WRL::ComPtr<IWICFormatConverter>             m_formatConvert;
00045         Microsoft::WRL::ComPtr<ID2D1ImageSourceFromWic>         m_imageSource;
00046         Microsoft::WRL::ComPtr<ID2D1TransformedImageSource>     m_transformedImage;
00047         Microsoft::WRL::ComPtr<ID2D1Effect>                     m_waveEffect;
00048
00049         D2D1_SIZE_U                                             m_imageSize;
00050         // Stretch the image in the X and Y dimensions.
00051         float                                                   m_skewX;
00052         float                                                   m_skewY;
00053         bool                                                    m_isWindowClosed;
00054
00055         BasicTimer^                                             m_timer;
00056     };
00057 }
00058
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/GameInfoOverlay.h Source File

  • Simple3DGameDX
  • cpp

GameInfoOverlay.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // GameInfoOverlay:
00015 // This class maintains a D2D1 Bitmap surface to provide information to the player
00016 // on the state of the game when the game is not in active play.
00017 // This class has several different status modes:
00018 //     GameLoading - this displays a title and a series of dots to show progress.
00019 //     GameStats - this displays a title and the Max level achieved, the hit and shot counts.
00020 //     GameOver - this displays a title and the game status.
00021 //     Pause - this displays only a title - 'Paused'.
00022 // In addition to the status modes, there is a region at the bottom that displays what the
00023 // player is expected to do next.  This can be one of four things:
00024 //     None - the action is blank.  This is usually set when the game does not currently have focus.
00025 //     TapToContinue - the game is waiting for the player to provide input that they are ready to
00026 //         proceed.
00027 //     PleaseWait - the game is actively doing some background processing (like loading a level).
00028 //     PlayAgain - the game has completed and is waiting for the player to indicate they are ready
00029 //         to play another round of the game.
00030 #include "GameUIControl.h"
00031
00032 ref class GameInfoOverlay : public Simple3DGameDX::IGameUIControl
00033 {
00034 internal:
00035     GameInfoOverlay(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00036
00037     void CreateDeviceDependentResources();
00038     void CreateWindowSizeDependentResources(D2D_SIZE_F overlaySize);
00039     void ReleaseDeviceDependentResources();
00040
00041     bool Visible() { return m_visible; };
00042     ID2D1Bitmap1* Bitmap();
00043
00044 public:
00045     // IGameUIControl interface
00046     virtual void SetGameLoading(uint32 dots);
00047     virtual void SetGameStats(int maxLevel, int hitCount, int shotCount);
00048     virtual void SetGameOver(bool win, int maxLevel, int hitCount, int shotCount, int highScore);
00049     virtual void SetLevelStart(int level, Platform::String^ objective, float timeLimit, float bonusTime);
00050     virtual void SetPause(int level, int hitCount, int shotCount, float timeRemaining);
00051     virtual void SetAction(Simple3DGameDX::GameInfoOverlayCommand action);
00052     virtual void HideGameInfoOverlay() { m_visible = false; };
00053     virtual void ShowGameInfoOverlay() { m_visible = true; };
00054     virtual void ShowTooSmall();
00055     virtual void HideTooSmall();
00056
00057 private:
00058     // Cached pointer to device resources.
00059     std::shared_ptr<DX::DeviceResources>            m_deviceResources;
00060
00061     bool                                            m_visible;
00062     bool                                            m_tooSmallActive;
00063
00064     D2D1_RECT_F                                     m_titleRectangle;
00065     D2D1_RECT_F                                     m_bodyRectangle;
00066     D2D1_RECT_F                                     m_actionRectangle;
00067
00068     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_levelBitmap;
00069     Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_tooSmallBitmap;
00070     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_textFormatTitle;
00071     Microsoft::WRL::ComPtr<IDWriteTextFormat>       m_textFormatBody;
00072     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_textBrush;
00073     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_backgroundBrush;
00074     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_actionBrush;
00075     Platform::String^                               m_titleString;
00076     Platform::String^                               m_bodyString;
00077     Platform::String^                               m_actionString;
00078 };
Generated on Fri Nov 15 2024 22:21:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/BackgroundTask/Scenario6_GroupedTask.xaml.h Source File

  • BackgroundTask
  • cpp
  • BackgroundTask

Scenario6_GroupedTask.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario5_GroupedTask.xaml.h
00013 // Declaration of the GroupedBackgroundTask class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019 #include "pch.h"
00020 #include "Scenario6_GroupedTask.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class GroupedBackgroundTask sealed
00030     {
00031     public:
00032         GroupedBackgroundTask();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036     private:
00037         SDKTemplate::MainPage^ rootPage;
00038         BackgroundTaskRegistrationGroup^ group = nullptr;
00039
00040         void AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^ task);
00041         void RegisterGroupedBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void UnregisterGroupedTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         void UnregisterUngroupedTasks(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         void OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^ args);
00045         void OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ args);
00046         void UpdateUI();
00047     };
00048 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cs/Tasks/GeofenceBackgroundTask.cs Source File

  • Geolocation
  • cs
  • Tasks

GeofenceBackgroundTask.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Collections.Generic;
00013 using Windows.ApplicationModel.Background;
00014 using Windows.Data.Json;
00015 using Windows.Storage;
00016 using Windows.Devices.Geolocation;
00017 using Windows.Devices.Geolocation.Geofencing;
00018
00019 namespace BackgroundTask
00020 {
00021     public sealed class GeofenceBackgroundTask : IBackgroundTask
00022     {
00023         // Value determined by how many max length event descriptors (91 chars)
00024         // stored as a JSON string can fit in 8K (max allowed for local settings)
00025         private const int maxEventDescriptors = 42;
00026
00027         // LocalSettings persistent data.
00028         IDictionary<string, object> _values = ApplicationData.Current.LocalSettings.Values;
00029
00030         void IBackgroundTask.Run(IBackgroundTaskInstance taskInstance)
00031         {
00032             BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
00033
00034             try
00035             {
00036                 // Handle geofence state change reports
00037                 ProcessGeofenceStateChangedReports();
00038             }
00039             catch (UnauthorizedAccessException)
00040             {
00041                 _values["Status"] = "Location permissions are disabled. Enable access through the settings.";
00042                 _values.Remove("BackgroundGeofenceEventCollection");
00043             }
00044             finally
00045             {
00046                 deferral.Complete();
00047             }
00048         }
00049
00050         private void ProcessGeofenceStateChangedReports()
00051         {
00052             // Load the values saved from last time.
00053             JsonArray geofenceBackgroundEvents = Helpers.LoadSavedJson("BackgroundGeofenceEventCollection");
00054
00055             // Process the state changes that have occurred since the last time we ran.
00056             string description = null;
00057             GeofenceMonitor monitor = GeofenceMonitor.Current;
00058             IReadOnlyList<GeofenceStateChangeReport> reports = monitor.ReadReports();
00059
00060             foreach (GeofenceStateChangeReport report in reports)
00061             {
00062                 description = GenerateReportDescription(report);
00063
00064                 // Add to the collection, trimming old events if necessary.
00065                 if (geofenceBackgroundEvents.Count == maxEventDescriptors)
00066                 {
00067                     geofenceBackgroundEvents.RemoveAt(maxEventDescriptors - 1);
00068                 }
00069                 geofenceBackgroundEvents.Insert(0, JsonValue.CreateStringValue(description));
00070             }
00071
00072             int numReports = reports.Count;
00073             if (numReports > 0)
00074             {
00075                 // Save the modified results for next time.
00076                 _values["BackgroundGeofenceEventCollection"] = geofenceBackgroundEvents.Stringify();
00077
00078                 if (numReports > 1)
00079                 {
00080                     description = $"There are {numReports} new geofence events";
00081                 }
00082                 Helpers.DisplayToast(description);
00083             }
00084         }
00085
00086         private string GenerateReportDescription(GeofenceStateChangeReport report)
00087         {
00088             GeofenceState state = report.NewState;
00089             DateTimeOffset timestamp = report.Geoposition.Coordinate.Timestamp;
00090
00091             string result = $"{report.Geofence.Id} {timestamp:G}";
00092
00093             if (state == GeofenceState.Removed)
00094             {
00095                 GeofenceRemovalReason reason = report.RemovalReason;
00096                 if (reason == GeofenceRemovalReason.Expired)
00097                 {
00098                     result += " (Removed/Expired)";
00099                 }
00100                 else if (reason == GeofenceRemovalReason.Used)
00101                 {
00102                     result += " (Removed/Used)";
00103                 }
00104             }
00105             else if (state == GeofenceState.Entered)
00106             {
00107                 result += " (Entered)";
00108             }
00109             else if (state == GeofenceState.Exited)
00110             {
00111                 result += " (Exited)";
00112             }
00113             return result;
00114         }
00115     }
00116 }
Generated on Fri Nov 15 2024 22:19:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLInProcessWinRTComponent/cpp/cs/Scenario1_OvenClient.xaml.cs Source File

  • WRLInProcessWinRTComponent
  • cpp
  • cs

Scenario1_OvenClient.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using Microsoft.SDKSamples.Kitchen;
00008
00009 using Windows.Foundation;
00010 using Windows.UI.Xaml;
00011 using Windows.UI.Xaml.Controls;
00012 using Windows.UI.Xaml.Navigation;
00013 using SDKTemplate;
00014 using System;
00015
00016 namespace WRLInProcessWinRTComponent
00017 {
00018     /// <summary>
00019     /// An empty page that can be used on its own or navigated to within a Frame.
00020     /// </summary>
00021     public sealed partial class OvenClient : Page
00022     {
00023         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00024         // as NotifyUser()
00025         MainPage rootPage = MainPage.Current;
00026
00027         // Keep a ref to the oven since it is an event source.
00028         Oven _myOven = null;
00029
00030         public OvenClient()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         /// <summary>
00036         /// Invoked when this page is about to be displayed in a Frame.
00037         /// </summary>
00038         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00039         /// property is typically used to configure the page.</param>
00040         protected override void OnNavigatedTo(NavigationEventArgs e)
00041         {
00042         }
00043
00044         /// <summary>
00045         /// Use the custom Oven and BreadBakedEventArgs Windows Runtime components.
00046         /// </summary>
00047         /// <param name="sender">Contains information about the button that fired the event.</param>
00048         /// <param name="e">Contains state information and event data associated with a routed event.</param>
00049         private void Start_Click(object sender, RoutedEventArgs e)
00050         {
00051             // Component Creation
00052             if (_myOven == null)
00053             {
00054                 Dimensions dimensions;
00055                 dimensions.Width = 2;
00056                 dimensions.Height = 2;
00057                 dimensions.Depth = 2;
00058
00059                 _myOven = new Oven(dimensions);
00060             }
00061
00062             // Getters and setters are accessed using property syntax
00063             OvenClientOutput.Text += "Oven volume is: " + _myOven.Volume.ToString() + "\n";
00064
00065             // Register even listeners
00066             _myOven.BreadBaked += new TypedEventHandler<Oven, BreadBakedEventArgs>(BreadCompletedHandler1);
00067             _myOven.BreadBaked += new TypedEventHandler<Oven, BreadBakedEventArgs>(BreadCompletedHandler2);
00068             _myOven.BreadBaked += new TypedEventHandler<Oven, BreadBakedEventArgs>(BreadCompletedHandler3);
00069
00070             // Unregister from an event using the -= syntax and a delegate instance
00071             _myOven.BreadBaked -= new TypedEventHandler<Oven, BreadBakedEventArgs>(BreadCompletedHandler3);
00072
00073             // Bake a loaf of bread. This will trigger the BreadBaked event.
00074             _myOven.BakeBread("Sourdough");
00075
00076             // Trigger the event again with a different preheat time
00077             _myOven.ConfigurePreheatTemperature(OvenTemperature.High);
00078             _myOven.BakeBread("Wheat");
00079         }
00080
00081         async private void BreadCompletedHandler1(Oven oven, BreadBakedEventArgs args)
00082         {
00083             Action updateOutputText = () =>
00084                 {
00085                     OvenClientOutput.Text += "Event Handler 1: Invoked\n";
00086                     OvenClientOutput.Text += "Event Handler 1: Oven volume is: " + oven.Volume.ToString() + "\n";
00087                     OvenClientOutput.Text += "Event Handler 1: BreadBakedEventArgs flavor is: " + args.Bread.Flavor + "\n";
00088                 };
00089
00090             await OvenClientOutput.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(updateOutputText));
00091         }
00092
00093         async private void BreadCompletedHandler2(Oven oven, BreadBakedEventArgs bread)
00094         {
00095             Action updateOutputText = () =>
00096                 {
00097                     OvenClientOutput.Text += "Event Handler 2: Invoked\n";
00098                 };
00099             await OvenClientOutput.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(updateOutputText));
00100         }
00101
00102         async private void BreadCompletedHandler3(Oven oven, BreadBakedEventArgs bread)
00103         {
00104             // Event handler 3 was removed and will not be invoked
00105             Action updateOutputText = () =>
00106                 {
00107                     OvenClientOutput.Text += "Event Handler 3: Invoked\n";
00108                 };
00109
00110             await OvenClientOutput.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(updateOutputText));
00111         }
00112     }
00113 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_PinTile Member List

This is the complete list of members for Scenario1_PinTile, including all inherited members.
PinButton_Click(object sender, RoutedEventArgs e) | Scenario1_PinTile | [inline, private]
rootPage | Scenario1_PinTile | [private]
Scenario1_PinTile() | Scenario1_PinTile | [inline]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cs/ContinuationPage.xaml.cs Source File

  • Printing
  • cs

ContinuationPage.xaml.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Xaml.Controls;
00002
00003 namespace PrintSample
00004 {
00005     /// <summary>
00006     /// A paged used to flow text from a given text container
00007     /// Usage: Output scenarios 1-4 might not fit entirely on a given "printer page"
00008     /// In that case simply add new continuation pages of the given size until all the content can be displayed
00009     /// </summary>
00010     public sealed partial class ContinuationPage : Page
00011     {
00012         /// <summary>
00013         /// Creates a continuation page and links text-flow to a text flow container
00014         /// </summary>
00015         /// <param name="textLinkContainer">Text link container which will flow text into this page</param>
00016         public ContinuationPage(RichTextBlockOverflow textLinkContainer)
00017         {
00018             InitializeComponent();
00019             textLinkContainer.OverflowContentTarget = ContinuationPageLinkedContainer;
00020         }
00021     }
00022 }
Generated on Fri Nov 15 2024 22:21:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ILivePlayer Member List

This is the complete list of members for ILivePlayer, including all inherited members.
DesiredLiveOffset(TimeSpan offset) | ILivePlayer
GoToLive() | ILivePlayer
Initialize(Uri manifest, MediaElement mediaElement) | ILivePlayer
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cppwinrt/SampleConfiguration.h Source File

  • IoT-GPIO
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     inline hstring PinValueToString(Windows::Devices::Gpio::GpioPinValue value)
00018     {
00019         switch (value)
00020         {
00021         case Windows::Devices::Gpio::GpioPinValue::Low: return L"Low";
00022         case Windows::Devices::Gpio::GpioPinValue::High: return L"High";
00023         default: return to_hstring(static_cast<int32_t>(value));
00024         }
00025     }
00026 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/Scenario7.cpp Source File

  • FileAccess
  • cppwinrt

Scenario7.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario7.h"
00014 #include "Scenario7.g.cpp"
00015 #include "SampleConfiguration.h"
00016 #include <sstream>
00017
00018 using namespace winrt;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Storage;
00021 using namespace Windows::Storage::AccessCache;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario7::Scenario7()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     void Scenario7::OnNavigatedTo(NavigationEventArgs const&)
00033     {
00034         SampleState::ValidateFile();
00035     }
00036
00037     void Scenario7::AddToListButton_Click(IInspectable const&, RoutedEventArgs const&)
00038     {
00039         StorageFile file = SampleState::SampleFile();
00040         if (file != nullptr)
00041         {
00042             if (MRURadioButton().IsChecked().Value()) {
00043                 // Add the file to app MRU and possibly system MRU
00044                 RecentStorageItemVisibility visibility = SystemMRUCheckBox().IsChecked().Value() ? RecentStorageItemVisibility::AppAndSystem : RecentStorageItemVisibility::AppOnly;
00045                 SampleState::MruToken(StorageApplicationPermissions::MostRecentlyUsedList().Add(file, file.Name(), visibility));
00046                 rootPage.NotifyUser(L"The file '" + file.Name() + L"' was added to the MRU list and a token was stored.", NotifyType::StatusMessage);
00047             }
00048             else
00049             {
00050                 // Add the file to the FAL
00051                 try
00052                 {
00053                     SampleState::FalToken(StorageApplicationPermissions::FutureAccessList().Add(file, file.Name()));
00054                     rootPage.NotifyUser(L"The file '" + file.Name() + L"' was added to the FAL list and a token was stored.", NotifyType::StatusMessage);
00055                 }
00056                 catch (const hresult_error& ex)
00057                 {
00058                     if (ex.code() == FA_E_MAX_PERSISTED_ITEMS_REACHED)
00059                     {
00060                         // A real program would call Remove() to create room in the FAL.
00061                         rootPage.NotifyUser(L"The file '" + file.Name() + L"' was not added to the FAL list because the FAL list is full.", NotifyType::ErrorMessage);
00062                     }
00063                     else
00064                     {
00065                         throw;
00066                     }
00067                 }
00068             }
00069         }
00070         else
00071         {
00072             SampleState::NotifyUserFileNotExist();
00073         }
00074     }
00075
00076     void Scenario7::ShowListButton_Click(IInspectable const&, RoutedEventArgs const&)
00077     {
00078         AccessListEntryView entries{ nullptr };
00079         std::wstring listName;
00080         if (MRURadioButton().IsChecked().Value())
00081         {
00082             listName = L"MRU";
00083             entries = StorageApplicationPermissions::MostRecentlyUsedList().Entries();
00084         }
00085         else
00086         {
00087             listName = L"FAL";
00088             entries = StorageApplicationPermissions::FutureAccessList().Entries();
00089         }
00090
00091         std::wstringstream stream;
00092         if (entries.Size() > 0)
00093         {
00094             stream << L"The " << listName << L" list contains the following item(s):";
00095             for (AccessListEntry const& entry : entries)
00096             {
00097                 stream << std::endl;
00098                 // Application previously chose to store file.Name in this field
00099                 stream << std::wstring_view{ entry.Metadata };
00100             }
00101         }
00102         else
00103         {
00104             stream << L"The " << listName << L" list is empty.";
00105         }
00106         rootPage.NotifyUser(stream.str(), NotifyType::StatusMessage);
00107     }
00108
00109     fire_and_forget Scenario7::OpenFromListButton_Click(IInspectable const&, RoutedEventArgs const&)
00110     {
00111         auto lifetime = get_strong();
00112
00113         StorageFile file{ nullptr };
00114
00115         if (MRURadioButton().IsChecked().Value())
00116         {
00117             if (!SampleState::MruToken().empty())
00118             {
00119                 // When the MRU becomes full, older entries are automatically deleted, so check if the
00120                 // token is still valid before using it.
00121                 if (StorageApplicationPermissions::MostRecentlyUsedList().ContainsItem(SampleState::MruToken()))
00122                 {
00123                     // Open the file via the token that was stored when adding this file into the MRU list
00124                     file = co_await StorageApplicationPermissions::MostRecentlyUsedList().GetFileAsync(SampleState::MruToken());
00125                 }
00126                 else
00127                 {
00128                     rootPage.NotifyUser(L"The token is no longer valid.", NotifyType::ErrorMessage);
00129                 }
00130             }
00131             else
00132             {
00133                 rootPage.NotifyUser(L"This operation requires a token. Add file to the MRU list first.", NotifyType::ErrorMessage);
00134             }
00135         }
00136         else
00137         {
00138             if (!SampleState::FalToken().empty())
00139             {
00140                 // Open the file via the token that was stored when adding this file into the FAL list.
00141                 // The token remains valid until we explicitly remove it.
00142                 file = co_await StorageApplicationPermissions::FutureAccessList().GetFileAsync(SampleState::FalToken());
00143             }
00144             else
00145             {
00146                 rootPage.NotifyUser(L"This operation requires a token. Add file to the FAL list first.", NotifyType::ErrorMessage);
00147             }
00148         }
00149
00150         if (file != nullptr)
00151         {
00152             try
00153             {
00154                 // Read the file
00155                 hstring fileContent = co_await FileIO::ReadTextAsync(file);
00156                 rootPage.NotifyUser(L"The file '" + file.Name() + L"' was opened by a stored token. It contains the following text:\n" + fileContent, NotifyType::StatusMessage);
00157             }
00158             catch (hresult_error const& ex)
00159             {
00160                 // I/O errors are reported as exceptions.
00161                 rootPage.NotifyUser(L"Error reading file opened from list: " + ex.message(), NotifyType::ErrorMessage);
00162             }
00163         }
00164     }
00165 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LiveDash/cs/LiveDash/Models/MediaSegment.cs Source File

  • LiveDash
  • cs
  • LiveDash
  • Models

MediaSegment.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006
00007 namespace LiveDash.Models
00008 {
00009     /// <summary>
00010     /// Represents a media segment withing a media stream
00011     /// </summary>
00012     internal class MediaSegment
00013     {
00014         private UInt64 t;
00015         private UInt64 d;
00016         private UInt64 s;
00017         private string url;
00018
00019         internal MediaSegment()
00020         {
00021         }
00022
00023         #region properties
00024         internal UInt64 Timestamp
00025         {
00026             get { return t; }
00027
00028             set { t = value; }
00029         }
00030         internal UInt64 Duration
00031         {
00032             get { return d; }
00033
00034             set { d = value; }
00035         }
00036
00037         internal UInt64 Number
00038         {
00039             get { return s; }
00040
00041             set { s = value; }
00042         }
00043
00044         internal string SegmentUrl
00045         {
00046             get { return url; }
00047
00048             set { url = value; }
00049         }
00050         #endregion
00051     }
00052 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Player Member List

This is the complete list of members for Player, including all inherited members.
AddAudioAndVideoSourceBuffers(Period currentPeriod) | Player | [inline, private]
CheckForMediaPresentationDuration() | Player | [inline, private]
Close() | Player | [inline, private]
ConfigureMse() | Player | [inline, private]
GetAudioBuffer() | Player | [inline, private]
GetVideoBuffer() | Player | [inline, private]
GoToLiveEdge() | Player | [inline, private]
HasLiveOffsetValue | Player |
hasLiveOffsetValue | Player | [private]
Initialize() | Player | [inline, private]
isPaused | Player | [private]
liveOffset | Player | [private]
LiveOffset | Player |
M_mediaElement_CurrentStateChanged(object sender, RoutedEventArgs e) | Player | [inline, private]
M_mse_Closed(MseStreamSource sender, object args) | Player | [inline, private]
M_mse_Opened(MseStreamSource sender, object args) | Player | [inline, private]
manifest | Player | [private]
manifestReloadTimer | Player | [private]
mediaElement | Player | [private]
mse | Player | [private]
opened | Player | [private]
playbackTimer | Player | [private]
Player(MediaElement vid, MseStreamSource mse, Manifest manifest) | Player | [inline]
ReloadManifest() | Player | [inline, private]
SearchSegmentIfOutsideBuffer() | Player | [inline, private]
SetLiveOffsetValue() | Player | [inline, private]
sourceBuffers | Player | [private]
StartManifestReloadTimer() | Player | [inline, private]
UpdateData(TimeSpan now) | Player | [inline, private]
UpdateLiveSourceBuffers() | Player | [inline, private]
UpdateLiveSourceBuffersToLiveEdge() | Player | [inline, private]
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cpp/Scenario4_BackgroundActivity.xaml.h Source File

  • ActivitySensor
  • cpp

Scenario4_BackgroundActivity.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario4_BackgroundActivity.xaml.h
00014 // Declaration of the Scenario4_BackgroundActivity class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario4_BackgroundActivity.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     static Platform::String^ SampleBackgroundTaskName = "ActivitySensorBackgroundTask";
00026     static Platform::String^ SampleBackgroundTaskEntryPoint = "Tasks.ActivitySensorBackgroundTask";
00027
00028     /// <summary>
00029     /// An empty page that can be used on its own or navigated to within a Frame.
00030     /// </summary>
00031     [Windows::Foundation::Metadata::WebHostHidden]
00032     public ref class Scenario4_BackgroundActivity sealed
00033     {
00034     public:
00035         Scenario4_BackgroundActivity();
00036
00037     protected:
00038         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00039
00040     private:
00041         SDKTemplate::MainPage^ rootPage;
00042         bool registered;
00043
00044         void ScenarioRegisterTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045         void ScenarioUnregisterTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046         void OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ args);
00047         void RegisterBackgroundTask();
00048         void UpdateUIAsync(Platform::String^ status);
00049     };
00050 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BasicHologramMain Member List

This is the complete list of members for BasicHologramMain, including all inherited members.
BasicHologramMain(const std::shared_ptr< DX::DeviceResources > &deviceResources) | BasicHologramMain |
BasicHologramMain(std::shared_ptr< DX::DeviceResources > const &deviceResources) | BasicHologramMain |
LoadAppState() | BasicHologramMain |
LoadAppState() | BasicHologramMain |
m_cameraAddedToken | BasicHologramMain | [private]
m_cameraAddedToken | BasicHologramMain | [private]
m_cameraRemovedToken | BasicHologramMain | [private]
m_cameraRemovedToken | BasicHologramMain | [private]
m_canCommitDirect3D11DepthBuffer | BasicHologramMain | [private]
m_canGetDefaultHolographicDisplay | BasicHologramMain | [private]
m_canGetHolographicDisplayForCamera | BasicHologramMain | [private]
m_deviceResources | BasicHologramMain | [private]
m_gamepadAddedEventToken | BasicHologramMain | [private]
m_gamepadAddedEventToken | BasicHologramMain | [private]
m_gamepadRemovedEventToken | BasicHologramMain | [private]
m_gamepadRemovedEventToken | BasicHologramMain | [private]
m_gamepads | BasicHologramMain | [private]
m_holographicDisplayIsAvailableChangedEventToken | BasicHologramMain | [private]
m_holographicDisplayIsAvailableChangedEventToken | BasicHologramMain | [private]
m_holographicSpace | BasicHologramMain | [private]
m_holographicSpace | BasicHologramMain | [private]
m_locatabilityChangedToken | BasicHologramMain | [private]
m_locatabilityChangedToken | BasicHologramMain | [private]
m_pointerPressed | BasicHologramMain | [private]
m_spatialLocator | BasicHologramMain | [private]
m_spatialLocator | BasicHologramMain | [private]
m_stationaryReferenceFrame | BasicHologramMain | [private]
m_stationaryReferenceFrame | BasicHologramMain | [private]
m_timer | BasicHologramMain | [private]
OnCameraAdded(Windows::Graphics::Holographic::HolographicSpace^sender, Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs^args) | BasicHologramMain | [private]
OnCameraAdded(winrt::Windows::Graphics::Holographic::HolographicSpace const &sender, winrt::Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs const &args) | BasicHologramMain | [private]
OnCameraRemoved(Windows::Graphics::Holographic::HolographicSpace^sender, Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs^args) | BasicHologramMain | [private]
OnCameraRemoved(winrt::Windows::Graphics::Holographic::HolographicSpace const &sender, winrt::Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs const &args) | BasicHologramMain | [private]
OnDeviceLost() | BasicHologramMain | [virtual]
OnDeviceLost() override | BasicHologramMain |
OnDeviceRestored() | BasicHologramMain | [virtual]
OnDeviceRestored() override | BasicHologramMain |
OnGamepadAdded(Platform::Object^, Windows::Gaming::Input::Gamepad^args) | BasicHologramMain | [private]
OnGamepadAdded(winrt::Windows::Foundation::IInspectable, winrt::Windows::Gaming::Input::Gamepad const &args) | BasicHologramMain | [private]
OnGamepadRemoved(Platform::Object^, Windows::Gaming::Input::Gamepad^args) | BasicHologramMain | [private]
OnGamepadRemoved(winrt::Windows::Foundation::IInspectable, winrt::Windows::Gaming::Input::Gamepad const &args) | BasicHologramMain | [private]
OnHolographicDisplayIsAvailableChanged(Platform::Object^, Platform::Object^) | BasicHologramMain | [private]
OnHolographicDisplayIsAvailableChanged(winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable) | BasicHologramMain | [private]
OnLocatabilityChanged(Windows::Perception::Spatial::SpatialLocator^sender, Platform::Object^args) | BasicHologramMain | [private]
OnLocatabilityChanged(winrt::Windows::Perception::Spatial::SpatialLocator const &sender, winrt::Windows::Foundation::IInspectable const &args) | BasicHologramMain | [private]
OnPointerPressed() | BasicHologramMain |
OnPointerPressed() | BasicHologramMain |
Render(Windows::Graphics::Holographic::HolographicFrame^holographicFrame) | BasicHologramMain |
Render(winrt::Windows::Graphics::Holographic::HolographicFrame const &holographicFrame) | BasicHologramMain |
SaveAppState() | BasicHologramMain |
SaveAppState() | BasicHologramMain |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^holographicSpace) | BasicHologramMain |
SetHolographicSpace(winrt::Windows::Graphics::Holographic::HolographicSpace const &holographicSpace) | BasicHologramMain |
UnregisterHolographicEventHandlers() | BasicHologramMain | [private]
UnregisterHolographicEventHandlers() | BasicHologramMain | [private]
Update() | BasicHologramMain |
Update() | BasicHologramMain |
~BasicHologramMain() | BasicHologramMain |
~BasicHologramMain() | BasicHologramMain |
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4 Member List

This is the complete list of members for Scenario4, including all inherited members.
CloseSockets_Click(object sender, RoutedEventArgs e) | Scenario4 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario4 | [inline, protected]
rootPage | Scenario4 | [private]
Scenario4() | Scenario4 | [inline]
Generated on Fri Nov 15 2024 22:23:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cs/Scenario0_Choose.xaml.cs Source File

  • Accelerometer
  • cs

Scenario0_Choose.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Devices.Sensors;
00016 using Windows.Foundation;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario0_Choose : Page
00025     {
00026         MainPage rootPage = MainPage.Current;
00027
00028         public Scenario0_Choose()
00029         {
00030             this.InitializeComponent();
00031             var readingTypes = new List<AccelerometerReadingType>()
00032             {
00033                 AccelerometerReadingType.Standard,
00034                 AccelerometerReadingType.Linear,
00035                 AccelerometerReadingType.Gravity,
00036             };
00037             ReadingTypeComboBox.ItemsSource = readingTypes;
00038             ReadingTypeComboBox.SelectedIndex = readingTypes.IndexOf(rootPage.AccelerometerReadingType);
00039         }
00040
00041         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00042         {
00043             rootPage.AccelerometerReadingType = (AccelerometerReadingType)ReadingTypeComboBox.SelectedValue;
00044         }
00045     }
00046 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceInformationKindChoices Member List

This is the complete list of members for DeviceInformationKindChoices, including all inherited members.
Choices() DeviceInformationKindChoices [static]
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStarterKit/cpp/CameraRotationHelper.h Source File

  • CameraStarterKit
  • cpp

CameraRotationHelper.h

Go to the documentation of this file.
00001 #pragma once
00002 using namespace Windows::Foundation;
00003 using namespace Windows::Devices::Enumeration;
00004 using namespace Windows::Devices::Sensors;
00005 using namespace Windows::Graphics::Display;
00006 using namespace Windows::Media::Capture;
00007 using namespace Windows::Storage::FileProperties;
00008
00009
00010 namespace CameraStarterKit
00011 {
00012     ref class CameraRotationHelper sealed
00013     {
00014     public:
00015         event EventHandler<bool>^ OrientationChanged;
00016
00017         CameraRotationHelper(EnclosureLocation^ cameraEnclosureLocation);
00018
00019         static bool IsEnclosureLocationExternal(EnclosureLocation^ enclosureLocation);
00020         SimpleOrientation GetUIOrientation();
00021         SimpleOrientation GetCameraCaptureOrientation();
00022         SimpleOrientation GetCameraPreviewOrientation();
00023         static PhotoOrientation ConvertSimpleOrientationToPhotoOrientation(SimpleOrientation orientation);
00024         static int ConvertSimpleOrientationToClockwiseDegrees(SimpleOrientation orientation);
00025     private:
00026         EnclosureLocation^ _cameraEnclosureLocation;
00027         DisplayInformation^ _displayInformation;
00028         SimpleOrientationSensor^ _orientationSensor;
00029
00030         SimpleOrientation ConvertDisplayOrientationToSimpleOrientation(DisplayOrientations orientation);
00031         static SimpleOrientation MirrorOrientation(SimpleOrientation orientation);
00032         static SimpleOrientation AddOrientations(SimpleOrientation a, SimpleOrientation b);
00033         static SimpleOrientation SubtractOrientations(SimpleOrientation a, SimpleOrientation b);
00034         static VideoRotation ConvertSimpleOrientationToVideoRotation(SimpleOrientation orientation);
00035         static SimpleOrientation ConvertClockwiseDegreesToSimpleOrientation(int orientation);
00036         void SimpleOrientationSensor_OrientationChanged(SimpleOrientationSensor^ sender, SimpleOrientationSensorOrientationChangedEventArgs^ args);
00037         void DisplayInformation_OrientationChanged(DisplayInformation^ sender, Object^ ref);
00038         bool ShouldMirrorPreview();
00039         SimpleOrientation GetCameraOrientationRelativeToNativeOrientation();
00040     };
00041 }
Generated on Fri Nov 15 2024 22:18:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/Scenario11.h Source File

  • FileAccess
  • cppwinrt

Scenario11.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario11.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario11 : Scenario11T<Scenario11>
00020     {
00021         Scenario11();
00022
00023         fire_and_forget GetFileButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00024     private:
00025         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00026     };
00027 }
00028
00029 namespace winrt::SDKTemplate::factory_implementation
00030 {
00031     struct Scenario11 : Scenario11T<Scenario11, implementation::Scenario11>
00032     {
00033     };
00034 }
Generated on Fri Nov 15 2024 22:19:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLOutOfProcessWinRTComponent/cpp/cpp/SampleConfiguration.h Source File

  • WRLOutOfProcessWinRTComponent
  • cpp
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "WRL Out-of-process Runtime Component";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MultipleViews/cppwinrt/pch.h Source File

  • MultipleViews
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #define NOMINMAX
00004 #include <hstring.h>
00005 #include "winrt/Windows.Foundation.h"
00006 #include "winrt/Windows.Foundation.Collections.h"
00007 #include "winrt/Windows.Foundation.Metadata.h"
00008 #include "winrt/Windows.ApplicationModel.Activation.h"
00009 #include "winrt/Windows.ApplicationModel.Core.h"
00010 #include "winrt/Windows.System.h"
00011 #include "winrt/Windows.UI.Core.h"
00012 #include "winrt/Windows.UI.Core.AnimationMetrics.h"
00013 #include "winrt/Windows.UI.ViewManagement.h"
00014 #include "winrt/Windows.UI.Xaml.h"
00015 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00016 #include "winrt/Windows.UI.Xaml.Controls.h"
00017 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00018 #include "winrt/Windows.UI.Xaml.Documents.h"
00019 #include "winrt/Windows.UI.Xaml.Interop.h"
00020 #include "winrt/Windows.UI.Xaml.Markup.h"
00021 #include "winrt/Windows.UI.Xaml.Media.h"
00022 #include "winrt/Windows.UI.Xaml.Media.Animation.h"
00023 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TitleBar/cpp/pch.cpp Source File

  • TitleBar
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothLE/cs/Scenario2_Client.xaml.cs Source File

  • BluetoothLE
  • cs

Scenario2_Client.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Text;
00015 using System.Threading.Tasks;
00016 using Windows.Devices.Bluetooth;
00017 using Windows.Devices.Bluetooth.GenericAttributeProfile;
00018 using Windows.Devices.Enumeration;
00019 using Windows.Security.Cryptography;
00020 using Windows.Storage.Streams;
00021 using Windows.UI.Core;
00022 using Windows.UI.Xaml;
00023 using Windows.UI.Xaml.Controls;
00024 using Windows.UI.Xaml.Navigation;
00025
00026 namespace SDKTemplate
00027 {
00028     // This scenario connects to the device selected in the "Discover
00029     // GATT Servers" scenario and communicates with it.
00030     // Note that this scenario is rather artificial because it communicates
00031     // with an unknown service with unknown characteristics.
00032     // In practice, your app will be interested in a specific service with
00033     // a specific characteristic.
00034     public sealed partial class Scenario2_Client : Page
00035     {
00036         private MainPage rootPage = MainPage.Current;
00037
00038         private BluetoothLEDevice bluetoothLeDevice = null;
00039         private GattCharacteristic selectedCharacteristic;
00040
00041         // Only one registered characteristic at a time.
00042         private GattCharacteristic registeredCharacteristic;
00043         private GattPresentationFormat presentationFormat;
00044
00045         #region Error Codes
00046         readonly int E_BLUETOOTH_ATT_WRITE_NOT_PERMITTED = unchecked((int)0x80650003);
00047         readonly int E_BLUETOOTH_ATT_INVALID_PDU = unchecked((int)0x80650004);
00048         readonly int E_ACCESSDENIED = unchecked((int)0x80070005);
00049         readonly int E_DEVICE_NOT_AVAILABLE = unchecked((int)0x800710df); // HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE)
00050         #endregion
00051
00052         #region UI Code
00053         public Scenario2_Client()
00054         {
00055             InitializeComponent();
00056         }
00057
00058         protected override void OnNavigatedTo(NavigationEventArgs e)
00059         {
00060             SelectedDeviceRun.Text = rootPage.SelectedBleDeviceName;
00061             if (string.IsNullOrEmpty(rootPage.SelectedBleDeviceId))
00062             {
00063                 ConnectButton.IsEnabled = false;
00064             }
00065         }
00066
00067         protected override async void OnNavigatedFrom(NavigationEventArgs e)
00068         {
00069             var success = await ClearBluetoothLEDeviceAsync();
00070             if (!success)
00071             {
00072                 rootPage.NotifyUser("Error: Unable to reset app state", NotifyType.ErrorMessage);
00073             }
00074         }
00075         #endregion
00076
00077         #region Enumerating Services
00078         private async Task<bool> ClearBluetoothLEDeviceAsync()
00079         {
00080             if (subscribedForNotifications)
00081             {
00082                 // Need to clear the CCCD from the remote device so we stop receiving notifications
00083                 var result = await registeredCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None);
00084                 if (result != GattCommunicationStatus.Success)
00085                 {
00086                     return false;
00087                 }
00088                 else
00089                 {
00090                     selectedCharacteristic.ValueChanged -= Characteristic_ValueChanged;
00091                     subscribedForNotifications = false;
00092                 }
00093             }
00094             bluetoothLeDevice?.Dispose();
00095             bluetoothLeDevice = null;
00096             return true;
00097         }
00098
00099         private async void ConnectButton_Click()
00100         {
00101             ConnectButton.IsEnabled = false;
00102
00103             if (!await ClearBluetoothLEDeviceAsync())
00104             {
00105                 rootPage.NotifyUser("Error: Unable to reset state, try again.", NotifyType.ErrorMessage);
00106                 ConnectButton.IsEnabled = true;
00107                 return;
00108             }
00109
00110             try
00111             {
00112                 // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
00113                 bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(rootPage.SelectedBleDeviceId);
00114
00115                 if (bluetoothLeDevice == null)
00116                 {
00117                     rootPage.NotifyUser("Failed to connect to device.", NotifyType.ErrorMessage);
00118                 }
00119             }
00120             catch (Exception ex) when (ex.HResult == E_DEVICE_NOT_AVAILABLE)
00121             {
00122                 rootPage.NotifyUser("Bluetooth radio is not on.", NotifyType.ErrorMessage);
00123             }
00124
00125             if (bluetoothLeDevice != null)
00126             {
00127                 // Note: BluetoothLEDevice.GattServices property will return an empty list for unpaired devices. For all uses we recommend using the GetGattServicesAsync method.
00128                 // BT_Code: GetGattServicesAsync returns a list of all the supported services of the device (even if it's not paired to the system).
00129                 // If the services supported by the device are expected to change during BT usage, subscribe to the GattServicesChanged event.
00130                 GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached);
00131
00132                 if (result.Status == GattCommunicationStatus.Success)
00133                 {
00134                     var services = result.Services;
00135                     rootPage.NotifyUser(String.Format("Found {0} services", services.Count), NotifyType.StatusMessage);
00136                     foreach (var service in services)
00137                     {
00138                         ServiceList.Items.Add(new ComboBoxItem { Content = DisplayHelpers.GetServiceName(service), Tag = service });
00139                     }
00140                     ConnectButton.Visibility = Visibility.Collapsed;
00141                     ServiceList.Visibility = Visibility.Visible;
00142                 }
00143                 else
00144                 {
00145                     rootPage.NotifyUser("Device unreachable", NotifyType.ErrorMessage);
00146                 }
00147             }
00148             ConnectButton.IsEnabled = true;
00149         }
00150         #endregion
00151
00152         #region Enumerating Characteristics
00153         private async void ServiceList_SelectionChanged()
00154         {
00155             var service = (GattDeviceService)((ComboBoxItem)ServiceList.SelectedItem)?.Tag;
00156
00157             CharacteristicList.Items.Clear();
00158             RemoveValueChangedHandler();
00159
00160             IReadOnlyList<GattCharacteristic> characteristics = null;
00161             try
00162             {
00163                 // Ensure we have access to the device.
00164                 var accessStatus = await service.RequestAccessAsync();
00165                 if (accessStatus == DeviceAccessStatus.Allowed)
00166                 {
00167                     // BT_Code: Get all the child characteristics of a service. Use the cache mode to specify uncached characterstics only
00168                     // and the new Async functions to get the characteristics of unpaired devices as well.
00169                     var result = await service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached);
00170                     if (result.Status == GattCommunicationStatus.Success)
00171                     {
00172                         characteristics = result.Characteristics;
00173                     }
00174                     else
00175                     {
00176                         rootPage.NotifyUser("Error accessing service.", NotifyType.ErrorMessage);
00177
00178                         // On error, act as if there are no characteristics.
00179                         characteristics = new List<GattCharacteristic>();
00180                     }
00181                 }
00182                 else
00183                 {
00184                     // Not granted access
00185                     rootPage.NotifyUser("Error accessing service.", NotifyType.ErrorMessage);
00186
00187                     // On error, act as if there are no characteristics.
00188                     characteristics = new List<GattCharacteristic>();
00189
00190                 }
00191             }
00192             catch (Exception ex)
00193             {
00194                 rootPage.NotifyUser("Restricted service. Can't read characteristics: " + ex.Message,
00195                     NotifyType.ErrorMessage);
00196                 // On error, act as if there are no characteristics.
00197                 characteristics = new List<GattCharacteristic>();
00198             }
00199
00200             foreach (GattCharacteristic c in characteristics)
00201             {
00202                 CharacteristicList.Items.Add(new ComboBoxItem { Content = DisplayHelpers.GetCharacteristicName(c), Tag = c });
00203             }
00204             CharacteristicList.Visibility = Visibility.Visible;
00205         }
00206         #endregion
00207
00208         private void AddValueChangedHandler()
00209         {
00210             ValueChangedSubscribeToggle.Content = "Unsubscribe from value changes";
00211             if (!subscribedForNotifications)
00212             {
00213                 registeredCharacteristic = selectedCharacteristic;
00214                 registeredCharacteristic.ValueChanged += Characteristic_ValueChanged;
00215                 subscribedForNotifications = true;
00216             }
00217         }
00218
00219         private void RemoveValueChangedHandler()
00220         {
00221             ValueChangedSubscribeToggle.Content = "Subscribe to value changes";
00222             if (subscribedForNotifications)
00223             {
00224                 registeredCharacteristic.ValueChanged -= Characteristic_ValueChanged;
00225                 registeredCharacteristic = null;
00226                 subscribedForNotifications = false;
00227             }
00228         }
00229
00230         private async void CharacteristicList_SelectionChanged()
00231         {
00232             selectedCharacteristic = (GattCharacteristic)((ComboBoxItem)CharacteristicList.SelectedItem)?.Tag;
00233             if (selectedCharacteristic == null)
00234             {
00235                 EnableCharacteristicPanels(GattCharacteristicProperties.None);
00236                 rootPage.NotifyUser("No characteristic selected", NotifyType.ErrorMessage);
00237                 return;
00238             }
00239
00240             // Get all the child descriptors of a characteristics. Use the cache mode to specify uncached descriptors only
00241             // and the new Async functions to get the descriptors of unpaired devices as well.
00242             var result = await selectedCharacteristic.GetDescriptorsAsync(BluetoothCacheMode.Uncached);
00243             if (result.Status != GattCommunicationStatus.Success)
00244             {
00245                 rootPage.NotifyUser("Descriptor read failure: " + result.Status.ToString(), NotifyType.ErrorMessage);
00246             }
00247
00248             // BT_Code: There's no need to access presentation format unless there's at least one.
00249             presentationFormat = null;
00250             if (selectedCharacteristic.PresentationFormats.Count > 0)
00251             {
00252
00253                 if (selectedCharacteristic.PresentationFormats.Count.Equals(1))
00254                 {
00255                     // Get the presentation format since there's only one way of presenting it
00256                     presentationFormat = selectedCharacteristic.PresentationFormats[0];
00257                 }
00258                 else
00259                 {
00260                     // It's difficult to figure out how to split up a characteristic and encode its different parts properly.
00261                     // In this case, we'll just encode the whole thing to a string to make it easy to print out.
00262                 }
00263             }
00264
00265             // Enable/disable operations based on the GattCharacteristicProperties.
00266             EnableCharacteristicPanels(selectedCharacteristic.CharacteristicProperties);
00267         }
00268
00269         private void SetVisibility(UIElement element, bool visible)
00270         {
00271             element.Visibility = visible ? Visibility.Visible : Visibility.Collapsed;
00272         }
00273
00274         private void EnableCharacteristicPanels(GattCharacteristicProperties properties)
00275         {
00276             // BT_Code: Hide the controls which do not apply to this characteristic.
00277             SetVisibility(CharacteristicReadButton, properties.HasFlag(GattCharacteristicProperties.Read));
00278
00279             SetVisibility(CharacteristicWritePanel,
00280                 properties.HasFlag(GattCharacteristicProperties.Write) ||
00281                 properties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse));
00282             CharacteristicWriteValue.Text = "";
00283
00284             SetVisibility(ValueChangedSubscribeToggle, properties.HasFlag(GattCharacteristicProperties.Indicate) ||
00285                                                        properties.HasFlag(GattCharacteristicProperties.Notify));
00286
00287         }
00288
00289         private async void CharacteristicReadButton_Click()
00290         {
00291             // BT_Code: Read the actual value from the device by using Uncached.
00292             GattReadResult result = await selectedCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached);
00293             if (result.Status == GattCommunicationStatus.Success)
00294             {
00295                 string formattedResult = FormatValueByPresentation(result.Value, presentationFormat);
00296                 rootPage.NotifyUser($"Read result: {formattedResult}", NotifyType.StatusMessage);
00297             }
00298             else
00299             {
00300                 rootPage.NotifyUser($"Read failed: {result.Status}", NotifyType.ErrorMessage);
00301             }
00302         }
00303
00304         private async void CharacteristicWriteButton_Click()
00305         {
00306             if (!String.IsNullOrEmpty(CharacteristicWriteValue.Text))
00307             {
00308                 var writeBuffer = CryptographicBuffer.ConvertStringToBinary(CharacteristicWriteValue.Text,
00309                     BinaryStringEncoding.Utf8);
00310
00311                 var writeSuccessful = await WriteBufferToSelectedCharacteristicAsync(writeBuffer);
00312             }
00313             else
00314             {
00315                 rootPage.NotifyUser("No data to write to device", NotifyType.ErrorMessage);
00316             }
00317         }
00318
00319         private async void CharacteristicWriteButtonInt_Click()
00320         {
00321             if (!String.IsNullOrEmpty(CharacteristicWriteValue.Text))
00322             {
00323                 var isValidValue = Int32.TryParse(CharacteristicWriteValue.Text, out int readValue);
00324                 if (isValidValue)
00325                 {
00326                     var writer = new DataWriter();
00327                     writer.ByteOrder = ByteOrder.LittleEndian;
00328                     writer.WriteInt32(readValue);
00329
00330                     var writeSuccessful = await WriteBufferToSelectedCharacteristicAsync(writer.DetachBuffer());
00331                 }
00332                 else
00333                 {
00334                     rootPage.NotifyUser("Data to write has to be an int32", NotifyType.ErrorMessage);
00335                 }
00336             }
00337             else
00338             {
00339                 rootPage.NotifyUser("No data to write to device", NotifyType.ErrorMessage);
00340             }
00341         }
00342
00343         private async Task<bool> WriteBufferToSelectedCharacteristicAsync(IBuffer buffer)
00344         {
00345             try
00346             {
00347                 // BT_Code: Writes the value from the buffer to the characteristic.
00348                 var result = await selectedCharacteristic.WriteValueWithResultAsync(buffer);
00349
00350                 if (result.Status == GattCommunicationStatus.Success)
00351                 {
00352                     rootPage.NotifyUser("Successfully wrote value to device", NotifyType.StatusMessage);
00353                     return true;
00354                 }
00355                 else
00356                 {
00357                     rootPage.NotifyUser($"Write failed: {result.Status}", NotifyType.ErrorMessage);
00358                     return false;
00359                 }
00360             }
00361             catch (Exception ex) when (ex.HResult == E_BLUETOOTH_ATT_INVALID_PDU)
00362             {
00363                 rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
00364                 return false;
00365             }
00366             catch (Exception ex) when (ex.HResult == E_BLUETOOTH_ATT_WRITE_NOT_PERMITTED || ex.HResult == E_ACCESSDENIED)
00367             {
00368                 // This usually happens when a device reports that it support writing, but it actually doesn't.
00369                 rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
00370                 return false;
00371             }
00372         }
00373
00374         private bool subscribedForNotifications = false;
00375         private async void ValueChangedSubscribeToggle_Click()
00376         {
00377             if (!subscribedForNotifications)
00378             {
00379                 // initialize status
00380                 GattCommunicationStatus status = GattCommunicationStatus.Unreachable;
00381                 var cccdValue = GattClientCharacteristicConfigurationDescriptorValue.None;
00382                 if (selectedCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Indicate))
00383                 {
00384                     cccdValue = GattClientCharacteristicConfigurationDescriptorValue.Indicate;
00385                 }
00386
00387                 else if (selectedCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
00388                 {
00389                     cccdValue = GattClientCharacteristicConfigurationDescriptorValue.Notify;
00390                 }
00391
00392                 try
00393                 {
00394                     // BT_Code: Must write the CCCD in order for server to send indications.
00395                     // We receive them in the ValueChanged event handler.
00396                     status = await selectedCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(cccdValue);
00397
00398                     if (status == GattCommunicationStatus.Success)
00399                     {
00400                         AddValueChangedHandler();
00401                         rootPage.NotifyUser("Successfully subscribed for value changes", NotifyType.StatusMessage);
00402                     }
00403                     else
00404                     {
00405                         rootPage.NotifyUser($"Error registering for value changes: {status}", NotifyType.ErrorMessage);
00406                     }
00407                 }
00408                 catch (UnauthorizedAccessException ex)
00409                 {
00410                     // This usually happens when a device reports that it support indicate, but it actually doesn't.
00411                     rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
00412                 }
00413             }
00414             else
00415             {
00416                 try
00417                 {
00418                     // BT_Code: Must write the CCCD in order for server to send notifications.
00419                     // We receive them in the ValueChanged event handler.
00420                     // Note that this sample configures either Indicate or Notify, but not both.
00421                     var result = await
00422                             selectedCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
00423                                 GattClientCharacteristicConfigurationDescriptorValue.None);
00424                     if (result == GattCommunicationStatus.Success)
00425                     {
00426                         subscribedForNotifications = false;
00427                         RemoveValueChangedHandler();
00428                         rootPage.NotifyUser("Successfully un-registered for notifications", NotifyType.StatusMessage);
00429                     }
00430                     else
00431                     {
00432                         rootPage.NotifyUser($"Error un-registering for notifications: {result}", NotifyType.ErrorMessage);
00433                     }
00434                 }
00435                 catch (UnauthorizedAccessException ex)
00436                 {
00437                     // This usually happens when a device reports that it support notify, but it actually doesn't.
00438                     rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
00439                 }
00440             }
00441         }
00442
00443         private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
00444         {
00445             // BT_Code: An Indicate or Notify reported that the value has changed.
00446             // Display the new value with a timestamp.
00447             var newValue = FormatValueByPresentation(args.CharacteristicValue, presentationFormat);
00448             var message = $"Value at {DateTime.Now:hh:mm:ss.FFF}: {newValue}";
00449             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00450                 () => CharacteristicLatestValue.Text = message);
00451         }
00452
00453         private string FormatValueByPresentation(IBuffer buffer, GattPresentationFormat format)
00454         {
00455             // BT_Code: For the purpose of this sample, this function converts only UInt32 and
00456             // UTF-8 buffers to readable text. It can be extended to support other formats if your app needs them.
00457             byte[] data;
00458             CryptographicBuffer.CopyToByteArray(buffer, out data);
00459             if (format != null)
00460             {
00461                 if (format.FormatType == GattPresentationFormatTypes.UInt32 && data.Length >= 4)
00462                 {
00463                     return BitConverter.ToInt32(data, 0).ToString();
00464                 }
00465                 else if (format.FormatType == GattPresentationFormatTypes.Utf8)
00466                 {
00467                     try
00468                     {
00469                         return Encoding.UTF8.GetString(data);
00470                     }
00471                     catch (ArgumentException)
00472                     {
00473                         return "(error: Invalid UTF-8 string)";
00474                     }
00475                 }
00476                 else
00477                 {
00478                     // Add support for other format types as needed.
00479                     return "Unsupported format: " + CryptographicBuffer.EncodeToHexString(buffer);
00480                 }
00481             }
00482             else if (data != null)
00483             {
00484                 // We don't know what format to use. Let's try some well-known profiles, or default back to UTF-8.
00485                 if (selectedCharacteristic.Uuid.Equals(GattCharacteristicUuids.HeartRateMeasurement))
00486                 {
00487                     try
00488                     {
00489                         return "Heart Rate: " + ParseHeartRateValue(data).ToString();
00490                     }
00491                     catch (ArgumentException)
00492                     {
00493                         return "Heart Rate: (unable to parse)";
00494                     }
00495                 }
00496                 else if (selectedCharacteristic.Uuid.Equals(GattCharacteristicUuids.BatteryLevel))
00497                 {
00498                     try
00499                     {
00500                         // battery level is encoded as a percentage value in the first byte according to
00501                         // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.battery_level.xml
00502                         return "Battery Level: " + data[0].ToString() + "%";
00503                     }
00504                     catch (ArgumentException)
00505                     {
00506                         return "Battery Level: (unable to parse)";
00507                     }
00508                 }
00509                 // This is our custom calc service Result UUID. Format it like an Int
00510                 else if (selectedCharacteristic.Uuid.Equals(Constants.ResultCharacteristicUuid))
00511                 {
00512                     return BitConverter.ToInt32(data, 0).ToString();
00513                 }
00514                 // No guarantees on if a characteristic is registered for notifications.
00515                 else if (registeredCharacteristic != null)
00516                 {
00517                     // This is our custom calc service Result UUID. Format it like an Int
00518                     if (registeredCharacteristic.Uuid.Equals(Constants.ResultCharacteristicUuid))
00519                     {
00520                         return BitConverter.ToInt32(data, 0).ToString();
00521                     }
00522                 }
00523                 else
00524                 {
00525                     try
00526                     {
00527                         return "Unknown format: " + Encoding.UTF8.GetString(data);
00528                     }
00529                     catch (ArgumentException)
00530                     {
00531                         return "Unknown format";
00532                     }
00533                 }
00534             }
00535             else
00536             {
00537                 return "Empty data received";
00538             }
00539             return "Unknown format";
00540         }
00541
00542         /// <summary>
00543         /// Process the raw data received from the device into application usable data,
00544         /// according the the Bluetooth Heart Rate Profile.
00545         /// https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.heart_rate_measurement.xml&u=org.bluetooth.characteristic.heart_rate_measurement.xml
00546         /// This function throws an exception if the data cannot be parsed.
00547         /// </summary>
00548         /// <param name="data">Raw data received from the heart rate monitor.</param>
00549         /// <returns>The heart rate measurement value.</returns>
00550         private static ushort ParseHeartRateValue(byte[] data)
00551         {
00552             // Heart Rate profile defined flag values
00553             const byte heartRateValueFormat = 0x01;
00554
00555             byte flags = data[0];
00556             bool isHeartRateValueSizeLong = ((flags & heartRateValueFormat) != 0);
00557
00558             if (isHeartRateValueSizeLong)
00559             {
00560                 return BitConverter.ToUInt16(data, 1);
00561             }
00562             else
00563             {
00564                 return data[1];
00565             }
00566         }
00567     }
00568 }
Generated on Fri Nov 15 2024 22:18:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cs/Helpers/BufferConverter.cs Source File

  • WiFiDirectServices
  • cs
  • Helpers

BufferConverter.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml.Data;
00014 using Windows.Storage.Streams;
00015 using System.Globalization;
00016
00017 namespace SDKTemplate.Helpers
00018 {
00019     public class BufferConverter : IValueConverter
00020     {
00021         public object Convert(object value, Type targetType, object parameter, string language)
00022         {
00023             String metadata = String.Empty;
00024             IBuffer buffer = value as IBuffer;
00025             if (buffer != null)
00026             {
00027                 using (var metadataReader = DataReader.FromBuffer(buffer))
00028                 {
00029                     metadata = metadataReader.ReadString(buffer.Length);
00030                 }
00031                 metadata = String.Format(CultureInfo.InvariantCulture, "({0})", metadata);
00032             }
00033             return metadata;
00034         }
00035
00036         public object ConvertBack(object value, Type targetType, object parameter, string language)
00037         {
00038             throw new NotImplementedException();
00039         }
00040     }
00041 }
Generated on Fri Nov 15 2024 22:22:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: VersionAdaptiveCode/cs/MPEUserControl.xaml.cs Source File

  • VersionAdaptiveCode
  • cs

MPEUserControl.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Media.Core;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class MPEUserControl : UserControl
00022     {
00023         MediaPlayerElement MPE;
00024         public MPEUserControl()
00025         {
00026             this.InitializeComponent();
00027
00028             MPE = new MediaPlayerElement();
00029             MPE.AreTransportControlsEnabled = true;
00030             MPE.AutoPlay = true;
00031
00032             MPE.HorizontalAlignment = HorizontalAlignment.Stretch;
00033             MPE.VerticalAlignment = VerticalAlignment.Stretch;
00034             MPE.MediaPlayer.IsLoopingEnabled = true;
00035             RootGrid.Children.Add(MPE);
00036             MPE.SetValue(Grid.RowProperty, 1);
00037         }
00038
00039         private void Control_Loaded(object sender, RoutedEventArgs e)
00040         {
00041             Uri uri = new Uri("ms-appx:///Assets/ladybug.wmv");
00042             MPE.Source = MediaSource.CreateFromUri(uri);
00043         }
00044
00045         private void Control_Unloaded(object sender, RoutedEventArgs e)
00046         {
00047             MPE.Source = null;
00048         }
00049
00050         private void FrameStepForward_Click(object sender, RoutedEventArgs e)
00051         {
00052             MPE.MediaPlayer.StepForwardOneFrame();
00053         }
00054
00055         private void FrameStepBackward_Click(object sender, RoutedEventArgs e)
00056         {
00057             MPE.MediaPlayer.StepBackwardOneFrame();
00058         }
00059     }
00060 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RemotePeer Member List

This is the complete list of members for RemotePeer, including all inherited members.
hostName | RemotePeer | [private]
IsMatching(HostName hostName, String port) | RemotePeer | [inline]
outputStream | RemotePeer | [private]
OutputStream | RemotePeer |
port | RemotePeer | [private]
RemotePeer(IOutputStream outputStream, HostName hostName, String port) | RemotePeer | [inline]
ToString() | RemotePeer | [inline]
Generated on Fri Nov 15 2024 22:23:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampArray/cppwinrt/Scenario1_Basics.h Source File

  • LampArray
  • cppwinrt

Scenario1_Basics.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Basics.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_Basics : Scenario1_BasicsT<Scenario1_Basics>
00019     {
00020     public:
00021         Scenario1_Basics();
00022
00023         void OnNavigatedTo(winrt::Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00024         void OnNavigatedFrom(winrt::Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00025
00026         void Apply_Clicked(
00027             winrt::Windows::Foundation::IInspectable const& sender,
00028             winrt::Windows::UI::Xaml::RoutedEventArgs const& e);
00029
00030     private:
00031         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00032         winrt::Windows::Devices::Enumeration::DeviceWatcher m_deviceWatcher{ nullptr };
00033
00034         // Currently attached LampArrays
00035         std::vector<std::shared_ptr<LampArrayInfo>> m_attachedLampArrays;
00036
00037         winrt::Windows::Devices::Enumeration::DeviceWatcher::Added_revoker m_deviceAddedRevoker;
00038         winrt::Windows::Devices::Enumeration::DeviceWatcher::Removed_revoker m_deviceRemovedRevoker;
00039
00040         winrt::fire_and_forget Watcher_Added(
00041             winrt::Windows::Devices::Enumeration::DeviceWatcher const&,
00042             winrt::Windows::Devices::Enumeration::DeviceInformation const& deviceInformation);
00043
00044         winrt::fire_and_forget Watcher_Removed(
00045             winrt::Windows::Devices::Enumeration::DeviceWatcher const&,
00046             winrt::Windows::Devices::Enumeration::DeviceInformationUpdate deviceInformationUpdate);
00047
00048         winrt::fire_and_forget LampArray_AvailabilityChanged(
00049             winrt::Windows::Devices::Lights::LampArray const& sender,
00050             winrt::Windows::Foundation::IInspectable const&);
00051
00052         void UpdateLampArrayList();
00053
00054         void ApplySettingsToLampArray(winrt::Windows::Devices::Lights::LampArray const& lampArray);
00055         void SetGradientPatternToLampArray(winrt::Windows::Devices::Lights::LampArray const& lampArray);
00056         void SetWasdPatternToLampArray(winrt::Windows::Devices::Lights::LampArray const& lampArray);
00057     };
00058 }
00059
00060 namespace winrt::SDKTemplate::factory_implementation
00061 {
00062     struct Scenario1_Basics : Scenario1_BasicsT<Scenario1_Basics, implementation::Scenario1_Basics>
00063     {
00064     };
00065 }
Generated on Fri Nov 15 2024 22:20:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
_LaunchType enum name | sealed | [private]
ApduReceived(Windows::Devices::SmartCards::SmartCardEmulator^emulator, Windows::Devices::SmartCards::SmartCardEmulatorApduReceivedEventArgs^eventArgs) | sealed | [private]
BgTask() | sealed |
Complete enum value | sealed | [private]
DebugLog(const wchar_t *pwstrMessage) | sealed | [private]
DebugLogString(Platform::String^message) | sealed | [private]
Denied enum value | sealed | [private]
EndTask() | sealed | [private]
Failed enum value | sealed | [private]
FlushDebugLog() | sealed | [private]
HandleHceActivation() | sealed | [private]
LaunchForegroundApp(LaunchType type, LPWSTR wszMessage) | sealed | [private]
LaunchType typedef | sealed | [private]
m_csDebugLog | sealed | [private]
m_csLock | sealed | [private]
m_currentConnectionId | sealed | [private]
m_deferral | sealed | [private]
m_emulator | sealed | [private]
m_fDenyTransactions | sealed | [private]
m_fTaskEnded | sealed | [private]
m_fTransactionCompleted | sealed | [private]
m_paymentAidRegistration | sealed | [private]
m_pbCurrentAppletId | sealed | [private]
m_taskInstance | sealed | [private]
m_triggerDetails | sealed | [private]
m_wsDebugLog | sealed | [private]
ProcessCommandApdu(_In_ Windows::Storage::Streams::IBuffer^commandApdu, _Out_ bool *pfComplete) | sealed | [private]
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance) | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/BackgroundTask/Scenario5_ApplicationTriggerTask.xaml.h Source File

  • BackgroundTask
  • cpp
  • BackgroundTask

Scenario5_ApplicationTriggerTask.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario5_ApplicationTriggerTask.xaml.h
00013 // Declaration of the ApplicationTriggerTask class
00014 //
00015
00016 #pragma once
00017
00018 #include <ppltasks.h>
00019 #include "pch.h"
00020 #include "Scenario5_ApplicationTriggerTask.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class ApplicationTriggerTask sealed
00030     {
00031     public:
00032         ApplicationTriggerTask();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036     private:
00037         SDKTemplate::MainPage^ rootPage;
00038         ApplicationTrigger^ trigger = nullptr;
00039
00040         void AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^ task);
00041         void RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         void SignalBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         void OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^ args);
00045         void OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ args);
00046         void UpdateUI();
00047     };
00048 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackButton/cs/MainPage.xaml.cs Source File

  • BackButton
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Core;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Data;
00018 using Windows.UI.Xaml.Media;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class MainPage : Page
00029     {
00030         public static MainPage Current;
00031
00032         public MainPage()
00033         {
00034             this.InitializeComponent();
00035
00036             // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00037             // in order to call methods that are in this class.
00038             Current = this;
00039             SampleTitle.Text = FEATURE_NAME;
00040
00041             // Caching your main page is good practice, this makes it snappy for the user to return to "home" of your app.
00042             this.NavigationCacheMode = NavigationCacheMode.Required;
00043         }
00044
00045         protected override void OnNavigatedTo(NavigationEventArgs e)
00046         {
00047             // Populate the scenario list from the SampleConfiguration.cs file
00048             ScenarioControl.ItemsSource = scenarios;
00049             if (Window.Current.Bounds.Width < 640)
00050             {
00051                 ScenarioControl.SelectedIndex = -1;
00052             }
00053             else
00054             {
00055                 ScenarioControl.SelectedIndex = 0;
00056             }
00057
00058             // This page is always at the top of our in-app back stack.
00059             // Once it is reached there is no further back so we can always disable the title bar back UI when navigated here.
00060             // If you want to you can always to the Frame.CanGoBack check for all your pages and act accordingly.
00061             SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
00062         }
00063
00064         /// <summary>
00065         /// Called whenever the user changes selection in the scenarios list.  This method will navigate to the respective
00066         /// sample scenario page.
00067         /// </summary>
00068         /// <param name="sender"></param>
00069         /// <param name="e"></param>
00070         private void ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
00071         {
00072             // Clear the status block when navigating scenarios.
00073             NotifyUser(String.Empty, NotifyType.StatusMessage);
00074
00075             ListBox scenarioListBox = sender as ListBox;
00076             Scenario s = scenarioListBox.SelectedItem as Scenario;
00077             if (s != null)
00078             {
00079                 ScenarioFrame.Navigate(s.ClassType);
00080                 if (Window.Current.Bounds.Width < 640)
00081                 {
00082                     Splitter.IsPaneOpen = false;
00083                 }
00084             }
00085         }
00086
00087         public List<Scenario> Scenarios
00088         {
00089             get { return this.scenarios; }
00090         }
00091
00092         /// <summary>
00093         /// Used to display messages to the user
00094         /// </summary>
00095         /// <param name="strMessage"></param>
00096         /// <param name="type"></param>
00097         public void NotifyUser(string strMessage, NotifyType type)
00098         {
00099             switch (type)
00100             {
00101                 case NotifyType.StatusMessage:
00102                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green);
00103                     break;
00104                 case NotifyType.ErrorMessage:
00105                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red);
00106                     break;
00107             }
00108             StatusBlock.Text = strMessage;
00109
00110             // Collapse the StatusBlock if it has no text to conserve real estate.
00111             StatusBorder.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed;
00112             if (StatusBlock.Text != String.Empty)
00113             {
00114                 StatusBorder.Visibility = Visibility.Visible;
00115                 StatusPanel.Visibility = Visibility.Visible;
00116             }
00117             else
00118             {
00119                 StatusBorder.Visibility = Visibility.Collapsed;
00120                 StatusPanel.Visibility = Visibility.Collapsed;
00121             }
00122         }
00123
00124         async void Footer_Click(object sender, RoutedEventArgs e)
00125         {
00126             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00127         }
00128
00129         private void Button_Click(object sender, RoutedEventArgs e)
00130         {
00131             Splitter.IsPaneOpen = !Splitter.IsPaneOpen;
00132         }
00133     }
00134     public enum NotifyType
00135     {
00136         StatusMessage,
00137         ErrorMessage
00138     };
00139
00140     public class ScenarioBindingConverter : IValueConverter
00141     {
00142         public object Convert(object value, Type targetType, object parameter, string language)
00143         {
00144             Scenario s = value as Scenario;
00145             return (MainPage.Current.Scenarios.IndexOf(s) + 1) + ") " + s.Title;
00146         }
00147
00148         public object ConvertBack(object value, Type targetType, object parameter, string language)
00149         {
00150             return true;
00151         }
00152     }
00153 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/scenario7.xaml.h Source File

  • ApplicationResources
  • cpp

scenario7.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario7.xaml.h
00013 // Declaration of the Scenario7 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario7.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024
00025         /// <summary>
00026         /// An empty page that can be used on its own or navigated to within a Frame.
00027         /// </summary>
00028         [Windows::Foundation::Metadata::WebHostHidden]
00029         public ref class Scenario7 sealed
00030         {
00031         public:
00032             Scenario7();
00033
00034         protected:
00035             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036             virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         private:
00039             MainPage^ rootPage;
00040             Windows::ApplicationModel::Resources::Core::ResourceContext^ defaultContextForCurrentView;
00041             void Scenario7Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042             void ContextChanged(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::String^>^ sender, Windows::Foundation::Collections::IMapChangedEventArgs<Platform::String^>^ eventArg);
00043             Windows::Foundation::EventRegistrationToken eventToken;
00044         };
00045
00046 }
Generated on Fri Nov 15 2024 22:18:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GpuCoordinateMapper::RasterizedFrameBlob Member List

This is the complete list of members for GpuCoordinateMapper::RasterizedFrameBlob, including all inherited members.
depthImage | GpuCoordinateMapper::RasterizedFrameBlob
depthIntrinsics | GpuCoordinateMapper::RasterizedFrameBlob
depthRangeMaximumInMeters | GpuCoordinateMapper::RasterizedFrameBlob
depthRangeMinimumInMeters | GpuCoordinateMapper::RasterizedFrameBlob
depthScaleInMeters | GpuCoordinateMapper::RasterizedFrameBlob
depthToSource | GpuCoordinateMapper::RasterizedFrameBlob
depthToTarget | GpuCoordinateMapper::RasterizedFrameBlob
depthUnprojectionMap | GpuCoordinateMapper::RasterizedFrameBlob
sourceDistortionMap | GpuCoordinateMapper::RasterizedFrameBlob
sourceImage | GpuCoordinateMapper::RasterizedFrameBlob
sourceIntrinsics | GpuCoordinateMapper::RasterizedFrameBlob
sourceProjectionMatrix | GpuCoordinateMapper::RasterizedFrameBlob
targetDistortionMap | GpuCoordinateMapper::RasterizedFrameBlob
targetImage | GpuCoordinateMapper::RasterizedFrameBlob
targetIntrinsics | GpuCoordinateMapper::RasterizedFrameBlob
targetProjectionMatrix | GpuCoordinateMapper::RasterizedFrameBlob
targetRasterizedDepth | GpuCoordinateMapper::RasterizedFrameBlob
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/Scenario4.h Source File

  • WindowsAudioSession
  • cppwinrt

Scenario4.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012 #include "pch.h"
00013 #include "Scenario4.g.h"
00014 #include "WASAPICapture.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario4 : Scenario4T<Scenario4>, MediaFoundationInitializer
00019     {
00020         Scenario4();
00021
00022         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00023
00024         void btnStartCapture_Click(IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00025         void btnStopCapture_Click(IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026
00027     private:
00028         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00029         event_token m_deviceStateChangeToken;
00030         event_token m_plotDataReadyToken;
00031
00032         int m_discontinuityCount;
00033         bool m_isLowLatency;
00034         com_ptr<WASAPICapture> m_capture;
00035
00036         // UI Helpers
00037         void UpdateMediaControlUI(DeviceState deviceState);
00038
00039         // Handlers
00040         fire_and_forget OnDeviceStateChange(IDeviceStateSource const& sender, SDKTemplate::DeviceStateChangedEventArgs e);
00041         fire_and_forget OnPlotDataReady(IPlotDataSource const& sender, SDKTemplate::PlotDataReadyEventArgs e);
00042
00043         void InitializeCapture();
00044         void StopCapture();
00045         void ClearCapture();
00046     };
00047 }
00048
00049 namespace winrt::SDKTemplate::factory_implementation
00050 {
00051     struct Scenario4 : Scenario4T<Scenario4, implementation::Scenario4>
00052     {
00053     };
00054 }
Generated on Fri Nov 15 2024 22:19:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DpiScaling/cpp/pch.h Source File

  • DpiScaling
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlContextMenu/cs/Scenario1.xaml.cs Source File

  • XamlContextMenu
  • cs

Scenario1.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Linq;
00016 using Windows.Foundation;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Input;
00020 using Windows.UI.Xaml.Media;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario1 : Page
00025     {
00026         private MainPage rootPage = MainPage.Current;
00027
00028         public Scenario1()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         private void OpenMenuItem_Click(object sender, RoutedEventArgs e)
00034         {
00035             rootPage.NotifyUser("Action: Open", NotifyType.StatusMessage);
00036         }
00037
00038         private void PrintMenuItem_Click(object sender, RoutedEventArgs e)
00039         {
00040             rootPage.NotifyUser("Action: Print", NotifyType.StatusMessage);
00041         }
00042
00043         private void DeleteMenuItem_Click(object sender, RoutedEventArgs e)
00044         {
00045             rootPage.NotifyUser("Action: Delete", NotifyType.StatusMessage);
00046         }
00047     }
00048 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Gyrometer/cpp/Scenario2_Polling.xaml.h Source File

  • Gyrometer
  • cpp

Scenario2_Polling.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_Polling.xaml.h
00014 // Declaration of the Scenario2_Polling class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario2_Polling.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario2_Polling sealed
00030     {
00031     public:
00032         Scenario2_Polling();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038     private:
00039         SDKTemplate::MainPage^ rootPage;
00040         Windows::UI::Core::CoreDispatcher^ dispatcher;
00041         Windows::Devices::Sensors::Gyrometer^ gyrometer;
00042         Windows::Foundation::EventRegistrationToken visibilityToken;
00043         uint32 desiredReportInterval;
00044         Windows::UI::Xaml::DispatcherTimer^ dispatcherTimer;
00045
00046         void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00047         void DisplayCurrentReading(Platform::Object^ sender, Platform::Object^ e);
00048         void ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049         void ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050     };
00051 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cs/Scenario3.xaml.cs Source File

  • Logging
  • cs

Scenario3.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// UI for the FileLoggingSession sample.
00022     /// </summary>
00023     public sealed partial class Scenario3
00024     {
00025         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00026         // as NotifyUser()
00027         MainPage rootPage = MainPage.Current;
00028
00029         internal FileLoggingSessionScenario LoggingScenario { get { return FileLoggingSessionScenario.Instance; } }
00030
00031         public Scenario3()
00032         {
00033             // This sample UI is interested in events from
00034             // the LoggingScenario class so the UI can be updated.
00035             LoggingScenario.StatusChanged += LoggingScenario_StatusChanged;
00036             this.InitializeComponent();
00037         }
00038
00039         async void LoggingScenario_StatusChanged(object sender, LoggingScenarioEventArgs e)
00040         {
00041             if (e.Type == LoggingScenarioEventType.BusyStatusChanged)
00042             {
00043                 UpdateControls();
00044             }
00045             else if (e.Type == LoggingScenarioEventType.LogFileGenerated)
00046             {
00047                 await AddLogFileMessageDispatch("LogFileGenerated", e.LogFilePath);
00048             }
00049             else if (e.Type == LoggingScenarioEventType.LogFileGeneratedAtSuspend)
00050             {
00051                 await AddLogFileMessageDispatch("Log file at suspend", e.LogFilePath);
00052             }
00053             else if (e.Type == LoggingScenarioEventType.LogFileGeneratedAtDisable)
00054             {
00055                 await AddLogFileMessageDispatch("Log file at disable", e.LogFilePath);
00056             }
00057             else if (e.Type == LoggingScenarioEventType.LoggingEnabledDisabled)
00058             {
00059                 await AddMessageDispatch(string.Format("Logging has been {0}.", e.Enabled ? "enabled" : "disabled"));
00060             }
00061         }
00062
00063         ScrollViewer FindScrollViewer(DependencyObject depObject)
00064         {
00065             if (depObject == null)
00066             {
00067                 return null;
00068             }
00069
00070             int countThisLevel = Windows.UI.Xaml.Media.VisualTreeHelper.GetChildrenCount(depObject);
00071             if (countThisLevel <= 0)
00072             {
00073                 return null;
00074             }
00075
00076             for (int childIndex = 0; childIndex < countThisLevel; childIndex++)
00077             {
00078                 DependencyObject childDepObject = Windows.UI.Xaml.Media.VisualTreeHelper.GetChild(depObject, childIndex);
00079                 if (childDepObject is ScrollViewer)
00080                 {
00081                     return (ScrollViewer)childDepObject;
00082                 }
00083
00084                 ScrollViewer svFromChild = FindScrollViewer(childDepObject);
00085                 if (svFromChild != null)
00086                 {
00087                     return svFromChild;
00088                 }
00089             }
00090
00091             return null;
00092         }
00093
00094         /// <summary>
00095         /// Add a message to the UI control which displays status while the sample is running.
00096         /// </summary>
00097         /// <param name="message">The message to append to the UI log.</param>
00098         public void AddMessage(string message)
00099         {
00100             string messageToAdd = message + "\r\n";
00101             StatusMessageList.Text += messageToAdd;
00102             StatusMessageList.Select(StatusMessageList.Text.Length, 0);
00103
00104             ScrollViewer svFind = FindScrollViewer(StatusMessageList);
00105             if (svFind != null)
00106             {
00107                 svFind.ChangeView(null, StatusMessageList.ActualHeight, null);
00108             }
00109         }
00110
00111         /// <summary>
00112         /// Dispatch to the UI thread and add a message to the UI control which displays status while the sample is running.
00113         /// </summary>
00114         /// <param name="message">The message to append to the UI log.</param>
00115         public async Task AddLogFileMessageDispatch(string message, string path)
00116         {
00117             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
00118             {
00119                 string finalMessage;
00120                 if (path != null && path.Length > 0)
00121                 {
00122                     var directoryName = System.IO.Path.GetDirectoryName(path);
00123                     var fileName = System.IO.Path.GetFileName(path);
00124                     finalMessage = string.Format("{0}: {1}", message, fileName);
00125                     ViewLogInfo.Text =
00126                        $"Log folder: \"{directoryName}\"\r\n" +
00127                        $"- To view with tracerpt: tracerpt.exe \"{path}\" -of XML -o LogFile.xml\r\n" +
00128                        $"- To view with Windows Performance Toolkit (WPT):\r\n" +
00129                        $"   xperf -merge \"{path}\" merged.etl\r\n" +
00130                        $"   wpa.exe merged.etl";
00131                 }
00132                 else
00133                 {
00134                     finalMessage = string.Format("{0}: none, nothing logged since saving the last file.", message);
00135                 }
00136                 AddMessage(finalMessage);
00137             }).AsTask();
00138         }
00139
00140         /// <summary>
00141         /// Dispatch to the UI thread and add a message to the UI log.
00142         /// </summary>
00143         /// <param name="message">The message to appened to the UI log.</param>
00144         /// <returns>The task.</returns>
00145         public async Task AddMessageDispatch(string message)
00146         {
00147             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
00148             {
00149                 AddMessage(message);
00150             }).AsTask();
00151         }
00152
00153         /// <summary>
00154         /// Adjust UI controls based on what the sample is doing.
00155         /// </summary>
00156         private void UpdateControls()
00157         {
00158             if (FileLoggingSessionScenario.Instance.IsLoggingEnabled)
00159             {
00160                 InputTextBlock1.Text = "Logging is enabled. Click 'Disable Logging' to disable logging. With logging enabled, you can click 'Log Messages' to use the logging API to generate log files.";
00161                 EnableDisableLoggingButton.Content = "Disable Logging";
00162                 if (FileLoggingSessionScenario.Instance.IsBusy)
00163                 {
00164                     DoScenarioButton.IsEnabled = false;
00165                     EnableDisableLoggingButton.IsEnabled = false;
00166                 }
00167                 else
00168                 {
00169                     DoScenarioButton.IsEnabled = true;
00170                     EnableDisableLoggingButton.IsEnabled = true;
00171                 }
00172             }
00173             else
00174             {
00175                 InputTextBlock1.Text = "Logging is disabled. Click 'Enable Logging' to enable logging. After you enable logging you can click 'Log Messages' to use the logging API to generate log files.";
00176                 EnableDisableLoggingButton.Content = "Enable Logging";
00177                 DoScenarioButton.IsEnabled = false;
00178                 if (FileLoggingSessionScenario.Instance.IsBusy)
00179                 {
00180                     EnableDisableLoggingButton.IsEnabled = false;
00181                 }
00182                 else
00183                 {
00184                     EnableDisableLoggingButton.IsEnabled = true;
00185                 }
00186             }
00187         }
00188
00189         /// <summary>
00190         /// Invoked when this page is about to be displayed in a Frame.
00191         /// </summary>
00192         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00193         /// property is typically used to configure the page.</param>
00194         protected override void OnNavigatedTo(NavigationEventArgs e)
00195         {
00196             UpdateControls();
00197         }
00198
00199         /// <summary>
00200         /// Enabled/disabled logging.
00201         /// </summary>
00202         /// <param name="sender">The sender.</param>
00203         /// <param name="e">The event arguments.</param>
00204         private async void EnableDisableLogging(object sender, RoutedEventArgs e)
00205         {
00206             FileLoggingSessionScenario loggingScenario = FileLoggingSessionScenario.Instance;
00207
00208             if (loggingScenario.IsLoggingEnabled)
00209             {
00210                 rootPage.NotifyUser("Disabling logging...", NotifyType.StatusMessage);
00211             }
00212             else
00213             {
00214                 rootPage.NotifyUser("Enabling logging...", NotifyType.StatusMessage);
00215             }
00216
00217             await FileLoggingSessionScenario.Instance.ToggleLoggingEnabledDisabledAsync();
00218
00219             if (loggingScenario.IsLoggingEnabled)
00220             {
00221                 rootPage.NotifyUser("Logging enabled.", NotifyType.StatusMessage);
00222             }
00223             else
00224             {
00225                 rootPage.NotifyUser("Logging disabled.", NotifyType.StatusMessage);
00226             }
00227
00228             UpdateControls();
00229         }
00230
00231         /// <summary>
00232         /// Run a sample scenario which logs lots of messages to produce several log files.
00233         /// </summary>
00234         /// <param name="sender">The sender.</param>
00235         /// <param name="e">The event args.</param>
00236         private async void DoScenario(object sender, RoutedEventArgs e)
00237         {
00238             DoScenarioButton.IsEnabled = false;
00239             rootPage.NotifyUser("Scenario running...", NotifyType.StatusMessage);
00240             await LoggingScenario.DoScenarioAsync();
00241             rootPage.NotifyUser("Scenario finished.", NotifyType.StatusMessage);
00242             DoScenarioButton.IsEnabled = true;
00243         }
00244     }
00245 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContentIndexer/cpp/S7_RetrieveWithAppContent.xaml.cpp Source File

  • ContentIndexer
  • cpp

S7_RetrieveWithAppContent.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // S7_RetrieveWithAppContent.xaml.cpp
00014 // Implementation of the S7_RetrieveWithAppContent class
00015 //
00016
00017 #include "pch.h"
00018 #include "S7_RetrieveWithAppContent.xaml.h"
00019 #include "MainPage.xaml.h"
00020 #include "Helpers.h"
00021
00022 using namespace SDKTemplate;
00023
00024 using namespace concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::Foundation;
00030 using namespace Windows::Foundation::Collections;
00031
00032 S7_RetrieveWithAppContent::S7_RetrieveWithAppContent()
00033 {
00034     InitializeComponent();
00035     InitializeRevisionNumber();
00036 }
00037
00038 void S7_RetrieveWithAppContent::AddToIndex_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00039 {
00040     return AddAppContentFilesToIndexedFolder();
00041 }
00042
00043 void RetrieveAppContentHelper(std::function<Windows::Storage::Search::StorageFileQueryResult^(Windows::Storage::StorageFolder^)> getQueryFunction)
00044 {
00045     create_task(Windows::Storage::ApplicationData::Current->LocalFolder->CreateFolderAsync(L"Indexed", Windows::Storage::CreationCollisionOption::OpenIfExists)).then(
00046     [getQueryFunction](Windows::Storage::StorageFolder^ indexedFolder)
00047     {
00048         auto query = getQueryFunction(indexedFolder);
00049         return query->GetFilesAsync();
00050     }).then([](IVectorView<Windows::Storage::StorageFile^>^ files)
00051     {
00052         auto propertyKeys = ref new Vector<String^>();
00053         propertyKeys->Append(Windows::Storage::SystemProperties::ItemNameDisplay);
00054         propertyKeys->Append(Windows::Storage::SystemProperties::Keywords);
00055         propertyKeys->Append(Windows::Storage::SystemProperties::Comment);
00056         propertyKeys->Append(Windows::Storage::SystemProperties::Title);
00057         std::vector<task<IMap<String^, Object^>^>> retrieveTasks;
00058         for (const auto& file : files)
00059         {
00060             retrieveTasks.push_back(create_task(file->Properties->RetrievePropertiesAsync(propertyKeys)));
00061         }
00062         return when_all(retrieveTasks.begin(), retrieveTasks.end());
00063     }).then([](std::vector<IMap<String^, Object^>^> retrievedItems)
00064     {
00065         String^ outputString;
00066         for (const auto& item : retrievedItems)
00067         {
00068             outputString += L"Name: " + StringifyProperty(item->Lookup(Windows::Storage::SystemProperties::ItemNameDisplay)) + L"\n";
00069             outputString += L"Keywords: " + StringifyProperty(item->Lookup(Windows::Storage::SystemProperties::Keywords)) + L"\n";
00070             outputString += L"Comment: " + StringifyProperty(item->Lookup(Windows::Storage::SystemProperties::Comment)) + L"\n";
00071             outputString += L"Title: " + StringifyProperty(item->Lookup(Windows::Storage::SystemProperties::Title)) + L"\n\n";
00072         }
00073         MainPage::Current->NotifyUser(outputString, NotifyType::StatusMessage);
00074     });
00075 }
00076
00077 // This function retrieves all items added to the index through the app's appcontent-ms files
00078 void S7_RetrieveWithAppContent::RetrieveAllItems_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00079 {
00080     return RetrieveAppContentHelper([](Windows::Storage::StorageFolder^ indexedFolder)
00081         {
00082             // Query for all files in the "LocalState\Indexed" folder and sort the results by name
00083             return indexedFolder->CreateFileQuery(Windows::Storage::Search::CommonFileQuery::OrderByName);
00084         });
00085 }
00086
00087 // This function retrieves all items added to the index through the app's appcontent-ms files which
00088 // have an ItemNameDisplay property containing "Sample 1"
00089 void S7_RetrieveWithAppContent::RetrieveMatchedItems_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00090 {
00091     return RetrieveAppContentHelper([](Windows::Storage::StorageFolder^ indexedFolder)
00092         {
00093             auto queryOptions = ref new Windows::Storage::Search::QueryOptions();
00094             // Include only items returned via the index in the search results
00095             queryOptions->IndexerOption = Windows::Storage::Search::IndexerOption::OnlyUseIndexer;
00096             // Create an AQS (Advanced Query Syntax) query which will look for ItemNameDisplay properties which contain "Sample 1"
00097             queryOptions->ApplicationSearchFilter = Windows::Storage::SystemProperties::ItemNameDisplay + L":\"Sample 1\"";
00098             return indexedFolder->CreateFileQueryWithOptions(queryOptions);
00099         });
00100 }
Generated on Fri Nov 15 2024 22:18:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAccountManagement/cs/IdentityChecker.cs Source File

  • WebAccountManagement
  • cs

IdentityChecker.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using Windows.ApplicationModel;
00007 using Windows.UI.Xaml.Controls;
00008
00009 namespace Accounts
00010 {
00011     // helper function to check if sample is configured to get AzureAD and Microsoft account tokens
00012     class IdentityChecker
00013     {
00014         public static void SampleIdentityConfigurationCorrect(TextBlock outputLocation, String AzureClientId = "Not applicable")
00015         {
00016             string outputMessage = "";
00017             bool isCorrect = true;
00018
00019             if (AzureClientId == "")
00020             {
00021                 outputMessage += "Azure AD Client ID not set; cannot sign in with Azure AD\n";
00022                 isCorrect = false;
00023             }
00024
00025             if ( Package.Current.Id.Publisher == "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")
00026             {
00027                 outputMessage += "Application identity not set; cannot sign in with Microsoft account.\n";
00028                 isCorrect = false;
00029             }
00030
00031             if (!isCorrect)
00032             {
00033                 outputMessage += "See Readme.MD for details";
00034                 outputLocation.Text = outputMessage;
00035             }
00036
00037         }
00038     }
00039 }
Generated on Fri Nov 15 2024 22:21:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NetworkConnectivity/cs/SampleConfiguration.cs Source File

  • NetworkConnectivity
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "NetworkingConnectivity";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title = "Query network connectivity", ClassType = typeof(Scenario1_NetworkConnectivity) },
00025             new Scenario() { Title = "Get network cost information", ClassType = typeof(Scenario2_NetworkCost) },
00026             new Scenario() { Title = "Listen to connectivity changes", ClassType = typeof(Scenario3_NetworkConnectivityChanges) },
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleOrientationSensor/cs/Scenario1_DataEvents.xaml.cs Source File

  • SimpleOrientationSensor
  • cs

Scenario1_DataEvents.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using System;
00017 using Windows.Devices.Sensors;
00018 using Windows.Foundation;
00019 using System.Threading.Tasks;
00020 using Windows.UI.Core;
00021
00022 namespace SimpleOrientationCS
00023 {
00024     public sealed partial class Scenario1_DataEvents : Page
00025     {
00026         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00027         // as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         private SimpleOrientationSensor _sensor;
00031
00032         public Scenario1_DataEvents()
00033         {
00034             this.InitializeComponent();
00035
00036             _sensor = SimpleOrientationSensor.GetDefault();
00037             if (_sensor == null)
00038             {
00039                 rootPage.NotifyUser("No simple orientation sensor found", NotifyType.ErrorMessage);
00040             }
00041         }
00042
00043         /// <summary>
00044         /// Invoked when this page is about to be displayed in a Frame.
00045         /// </summary>
00046         /// <param name="e">Event data that describes how this page was reached. The Parameter
00047         /// property is typically used to configure the page.</param>
00048         protected override void OnNavigatedTo(NavigationEventArgs e)
00049         {
00050             ScenarioEnableButton.IsEnabled = true;
00051             ScenarioDisableButton.IsEnabled = false;
00052         }
00053
00054         /// <summary>
00055         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00056         /// </summary>
00057         /// <param name="e">
00058         /// Event data that can be examined by overriding code. The event data is representative
00059         /// of the navigation that will unload the current Page unless canceled. The
00060         /// navigation can potentially be canceled by setting Cancel.
00061         /// </param>
00062         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00063         {
00064             if (ScenarioDisableButton.IsEnabled)
00065             {
00066                 Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00067                 _sensor.OrientationChanged -= new TypedEventHandler<SimpleOrientationSensor, SimpleOrientationSensorOrientationChangedEventArgs>(OrientationChanged);
00068             }
00069
00070             base.OnNavigatingFrom(e);
00071         }
00072
00073         /// <summary>
00074         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00075         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00076         /// </summary>
00077         /// <param name="sender"></param>
00078         /// <param name="e">
00079         /// Event data that can be examined for the current visibility state.
00080         /// </param>
00081         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00082         {
00083             if (ScenarioDisableButton.IsEnabled)
00084             {
00085                 if (e.Visible)
00086                 {
00087                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00088                     _sensor.OrientationChanged += new TypedEventHandler<SimpleOrientationSensor, SimpleOrientationSensorOrientationChangedEventArgs>(OrientationChanged);
00089                 }
00090                 else
00091                 {
00092                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00093                     _sensor.OrientationChanged -= new TypedEventHandler<SimpleOrientationSensor, SimpleOrientationSensorOrientationChangedEventArgs>(OrientationChanged);
00094                 }
00095             }
00096         }
00097
00098         /// <summary>
00099         /// Helper method to display the device orientation in the specified text box.
00100         /// </summary>
00101         /// <param name="tb">
00102         /// The text box receiving the orientation value.
00103         /// </param>
00104         /// <param name="orientation">
00105         /// The orientation value.
00106         /// </param>
00107         private void DisplayOrientation(TextBlock tb, SimpleOrientation orientation)
00108         {
00109             switch (orientation)
00110             {
00111                 case SimpleOrientation.NotRotated:
00112                     tb.Text = "Not Rotated";
00113                     break;
00114                 case SimpleOrientation.Rotated90DegreesCounterclockwise:
00115                     tb.Text = "Rotated 90 Degrees Counterclockwise";
00116                     break;
00117                 case SimpleOrientation.Rotated180DegreesCounterclockwise:
00118                     tb.Text = "Rotated 180 Degrees Counterclockwise";
00119                     break;
00120                 case SimpleOrientation.Rotated270DegreesCounterclockwise:
00121                     tb.Text = "Rotated 270 Degrees Counterclockwise";
00122                     break;
00123                 case SimpleOrientation.Faceup:
00124                     tb.Text = "Faceup";
00125                     break;
00126                 case SimpleOrientation.Facedown:
00127                     tb.Text = "Facedown";
00128                     break;
00129                 default:
00130                     tb.Text = "Unknown orientation";
00131                     break;
00132             }
00133         }
00134
00135         /// <summary>
00136         /// This is the event handler for OrientationChanged events.
00137         /// </summary>
00138         /// <param name="sender"></param>
00139         /// <param name="e"></param>
00140         async private void OrientationChanged(object sender, SimpleOrientationSensorOrientationChangedEventArgs e)
00141         {
00142             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00143             {
00144                 DisplayOrientation(ScenarioOutput_Orientation, e.Orientation);
00145             });
00146         }
00147
00148         /// <summary>
00149         /// This is the click handler for the 'Enable' button.
00150         /// </summary>
00151         /// <param name="sender"></param>
00152         /// <param name="e"></param>
00153         private void ScenarioEnable(object sender, RoutedEventArgs e)
00154         {
00155             if (_sensor != null)
00156             {
00157                 Window.Current.VisibilityChanged += new WindowVisibilityChangedEventHandler(VisibilityChanged);
00158                 _sensor.OrientationChanged += new TypedEventHandler<SimpleOrientationSensor, SimpleOrientationSensorOrientationChangedEventArgs>(OrientationChanged);
00159
00160                 ScenarioEnableButton.IsEnabled = false;
00161                 ScenarioDisableButton.IsEnabled = true;
00162
00163                 // Display the current orientation once while waiting for the next orientation change
00164                 DisplayOrientation(ScenarioOutput_Orientation, _sensor.GetCurrentOrientation());
00165             }
00166             else
00167             {
00168                 rootPage.NotifyUser("No simple orientation sensor found", NotifyType.ErrorMessage);
00169             }
00170         }
00171
00172         /// <summary>
00173         /// This is the click handler for the 'Disable' button.
00174         /// </summary>
00175         /// <param name="sender"></param>
00176         /// <param name="e"></param>
00177         private void ScenarioDisable(object sender, RoutedEventArgs e)
00178         {
00179             Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);
00180             _sensor.OrientationChanged -= new TypedEventHandler<SimpleOrientationSensor, SimpleOrientationSensorOrientationChangedEventArgs>(OrientationChanged);
00181
00182             ScenarioEnableButton.IsEnabled = true;
00183             ScenarioDisableButton.IsEnabled = false;
00184         }
00185     }
00186 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RemoteSystems/cs/Scenario2_LaunchUri.xaml.cs Source File

  • RemoteSystems
  • cs

Scenario2_LaunchUri.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.ObjectModel;
00014 using Windows.System;
00015 using Windows.System.RemoteSystems;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario2_LaunchUri : Page
00023     {
00024         private MainPage m_rootPage;
00025
00026         public Scenario2_LaunchUri()
00027         {
00028             this.InitializeComponent();
00029             this.DataContext = this;
00030         }
00031
00032         protected override void OnNavigatedTo(NavigationEventArgs e)
00033         {
00034             m_rootPage = MainPage.Current;
00035             m_rootPage.ValidateSystemDiscovery();
00036         }
00037
00038         public ObservableCollection<RemoteSystem> SystemList => m_rootPage.systemList;
00039
00040         private async void Launch_Clicked(object sender, RoutedEventArgs e)
00041         {
00042             RemoteSystem selectedSystem = SystemListComboBox.SelectedItem as RemoteSystem;
00043             if (selectedSystem != null)
00044             {
00045                 Uri uri;
00046                 if (Uri.TryCreate(UriTextBox.Text, UriKind.Absolute, out uri))
00047                 {
00048                     UpdateStatus("LaunchUriAsync called. Waiting for response...", NotifyType.StatusMessage);
00049
00050                     // Launch URI on the remote system.
00051                     // Note: LaunchUriAsync needs to called from the UI thread.
00052                     RemoteLaunchUriStatus launchUriStatus = await RemoteLauncher.LaunchUriAsync(new RemoteSystemConnectionRequest(selectedSystem), uri);
00053
00054                     UpdateStatus("LaunchUriStatus = " + launchUriStatus.ToString(), launchUriStatus == RemoteLaunchUriStatus.Success ? NotifyType.StatusMessage : NotifyType.ErrorMessage);
00055                 }
00056                 else
00057                 {
00058                     UpdateStatus("Please enter a valid URI.", NotifyType.ErrorMessage);
00059                 }
00060             }
00061             else
00062             {
00063                 UpdateStatus("Please select a system.", NotifyType.ErrorMessage);
00064             }
00065         }
00066
00067         private void UpdateStatus(string status, NotifyType statusType)
00068         {
00069             m_rootPage.NotifyUser(status, statusType);
00070         }
00071     }
00072 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PresenceSensor/cppwinrt/Scenario1_DataEvents.h Source File

  • PresenceSensor
  • cppwinrt

Scenario1_DataEvents.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_DataEvents.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1_DataEvents : Scenario1_DataEventsT<Scenario1_DataEvents>
00020     {
00021         Scenario1_DataEvents();
00022
00023         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024
00025         // These methods are public so they can be called by binding.
00026         fire_and_forget ScenarioGetSensor_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027
00028     private:
00029         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00030         Windows::Devices::Sensors::HumanPresenceSensor sensor{ nullptr };
00031         event_token sensorReadingChangedToken{};
00032
00033         fire_and_forget ReadingChanged(Windows::Devices::Sensors::HumanPresenceSensor const&, Windows::Devices::Sensors::HumanPresenceSensorReadingChangedEventArgs e);
00034     };
00035 }
00036
00037 namespace winrt::SDKTemplate::factory_implementation
00038 {
00039     struct Scenario1_DataEvents : Scenario1_DataEventsT<Scenario1_DataEvents, implementation::Scenario1_DataEvents>
00040     {
00041     };
00042 }
Generated on Fri Nov 15 2024 22:20:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

App Member List

This is the complete list of members for App, including all inherited members.
App() | App | [inline]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnSuspending(object sender, SuspendingEventArgs e) | App | [inline, private]
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/App.xaml.cs Source File

  • AdvancedCasting
  • cs

App.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel;
00014 using Windows.ApplicationModel.Activation;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
00020
00021 namespace ScreenCasting
00022 {
00023     /// <summary>
00024     /// Provides application-specific behavior to supplement the default Application class.
00025     /// </summary>
00026     sealed partial class App : Application
00027     {
00028         /// <summary>
00029         /// Initializes the singleton application object.  This is the first line of authored code
00030         /// executed, and as such is the logical equivalent of main() or WinMain().
00031         /// </summary>
00032         public App()
00033         {
00034             this.InitializeComponent();
00035             this.Suspending += OnSuspending;
00036         }
00037
00038         /// <summary>
00039         /// Invoked when the application is launched normally by the end user.  Other entry points
00040         /// will be used such as when the application is launched to open a specific file.
00041         /// </summary>
00042         /// <param name="e">Details about the launch request and process.</param>
00043         protected override void OnLaunched(LaunchActivatedEventArgs e)
00044         {
00045 #if DEBUG
00046             if (System.Diagnostics.Debugger.IsAttached)
00047             {
00048                 this.DebugSettings.EnableFrameRateCounter = false;
00049
00050             }
00051
00052 #endif
00053             Application.Current.UnhandledException += Current_UnhandledException;
00054
00055             Window.Current.Activate();
00056
00057             Frame rootFrame = Window.Current.Content as Frame;
00058
00059             // Do not repeat app initialization when the Window already has content,
00060             // just ensure that the window is active
00061             if (rootFrame == null)
00062             {
00063                 // Create a Frame to act as the navigation context and navigate to the first page
00064                 rootFrame = new Frame();
00065                 // Set the default language
00066                 rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
00067
00068                 rootFrame.NavigationFailed += OnNavigationFailed;
00069
00070                 if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
00071                 {
00072                     //TODO: Load state from previously suspended application
00073                 }
00074
00075                 // Place the frame in the current Window
00076                 Window.Current.Content = rootFrame;
00077                 Window.Current.Activate();
00078             }
00079
00080             if (rootFrame.Content == null)
00081             {
00082                 // When the navigation stack isn't restored navigate to the first page,
00083                 // configuring the new page by passing required information as a navigation
00084                 // parameter
00085                 try
00086                 {
00087                     rootFrame.Navigate(typeof(MainPage), e);
00088                 }
00089                 catch (Exception ex)
00090                 {
00091                     Window.Current.Content = new Frame();
00092                     Window.Current.Activate();
00093                     rootFrame.Navigate(typeof(UnhandledExceptionPage), e.Arguments);
00094                     ((UnhandledExceptionPage)rootFrame.Content).StatusMessage = ex.Message + ex.StackTrace;
00095                 }
00096
00097             }
00098
00099
00100             // Ensure the current window is active
00101             Window.Current.Activate();
00102         }
00103
00104         private void Current_UnhandledException(object sender, UnhandledExceptionEventArgs e)
00105         {
00106             Window.Current.Content = new Frame();
00107             Frame rootFrame = Window.Current.Content as Frame;
00108             Window.Current.Activate();
00109             rootFrame.Navigate(typeof(UnhandledExceptionPage));
00110             ((UnhandledExceptionPage)rootFrame.Content).StatusMessage = e.Exception.Message + e.Exception.StackTrace;
00111         }
00112
00113         protected override void OnActivated(IActivatedEventArgs args)
00114         {
00115             try
00116             {
00117                 Window.Current.Content = new Frame();
00118                 Frame rootFrame = Window.Current.Content as Frame;
00119                 Window.Current.Activate();
00120
00121
00122                 if (args.Kind == ActivationKind.DialReceiver)
00123                 {
00124                     rootFrame.Navigate(typeof(MainPage), args);
00125                 }
00126                 else
00127                 {
00128                     rootFrame.Navigate(typeof(MainPage));
00129                 }
00130                 base.OnActivated(args);
00131             }
00132             catch (Exception ex)
00133             {
00134                 Window.Current.Content = new Frame();
00135                 Frame rootFrame = Window.Current.Content as Frame;
00136                 Window.Current.Activate();
00137                 rootFrame.Navigate(typeof(UnhandledExceptionPage));
00138                 ((UnhandledExceptionPage)rootFrame.Content).StatusMessage = ex.Message + ex.StackTrace;
00139             }
00140         }
00141
00142         /// <summary>
00143         /// Invoked when Navigation to a certain page fails
00144         /// </summary>
00145         /// <param name="sender">The Frame which failed navigation</param>
00146         /// <param name="e">Details about the navigation failure</param>
00147         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00148         {
00149             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00150         }
00151
00152         /// <summary>
00153         /// Invoked when application execution is being suspended.  Application state is saved
00154         /// without knowing whether the application will be terminated or resumed with the contents
00155         /// of memory still intact.
00156         /// </summary>
00157         /// <param name="sender">The source of the suspend request.</param>
00158         /// <param name="e">Details about the suspend request.</param>
00159         private void OnSuspending(object sender, SuspendingEventArgs e)
00160         {
00161             var deferral = e.SuspendingOperation.GetDeferral();
00162             //TODO: Save application state and stop any background activity
00163             deferral.Complete();
00164         }
00165     }
00166 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomHidDeviceAccess/cpp/SampleConfiguration.cpp Source File

  • CustomHidDeviceAccess
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Connecting To Device", "SDKTemplate.DeviceConnect" },
00012     { "Feature Reports", "SDKTemplate.FeatureReports" },
00013     { "Input Report Events", "SDKTemplate.InputReportEvents" },
00014     { "Input and Output Reports", "SDKTemplate.InputOutputReports" }
00015 };
Generated on Fri Nov 15 2024 22:17:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cpp/BackgroundTransfer/Scenario4_CompletionGroups.xaml.cpp Source File

  • BackgroundTransfer
  • cpp
  • BackgroundTransfer

Scenario4_CompletionGroups.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario4_CompletionGroups.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace SDKTemplate;
00020 using namespace std;
00021 using namespace Tasks;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::Networking::BackgroundTransfer;
00025 using namespace Windows::Storage;
00026 using namespace Windows::UI::Core;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Controls::Primitives;
00030 using namespace Windows::UI::Xaml::Data;
00031 using namespace Windows::UI::Xaml::Input;
00032 using namespace Windows::UI::Xaml::Media;
00033 using namespace Windows::UI::Xaml::Navigation;
00034
00035 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00036
00037 Scenario4_CompletionGroups::Scenario4_CompletionGroups()
00038 {
00039     InitializeComponent();
00040 }
00041
00042 void Scenario4_CompletionGroups::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00045     // as NotifyUser()
00046     rootPage = MainPage::Current;
00047
00048     AttachDownloads();
00049 }
00050
00051 void Scenario4_CompletionGroups::AttachDownloads()
00052 {
00053     // You may (but are not required to) use transfer groups along with completion groups.
00054     // Note that we only enumerate transfers that belong to this sample scenario.
00055     BackgroundTransferGroup^ transferGroup = CompletionGroupTask::CreateTransferGroup();
00056     create_task(BackgroundDownloader::GetCurrentDownloadsForTransferGroupAsync(transferGroup))
00057         .then([this](IVectorView<DownloadOperation^>^ downloads)
00058     {
00059         if (downloads->Size > 0)
00060         {
00061             for (unsigned int i = 0; i < downloads->Size; i++)
00062             {
00063                 create_task(downloads->GetAt(i)->AttachAsync()).then([this](task<DownloadOperation^> previousTask)
00064                 {
00065                     try
00066                     {
00067                         previousTask.get();
00068                     }
00069                     catch (Exception^ ex)
00070                     {
00071                         // Ignore errors: We're just interested in canceling all downloads from previous instances.
00072                     }
00073                 });
00074             }
00075
00076             MarshalNotifyUser(downloads->Size.ToString() + " downloads attached.", NotifyType::StatusMessage);
00077         }
00078     }).then([this](task<void> previousTask)
00079     {
00080         try
00081         {
00082             previousTask.get();
00083         }
00084         catch (Exception^ ex)
00085         {
00086             MarshalNotifyUser("Error discovering downloads: " + ex->Message, NotifyType::ErrorMessage);
00087         }
00088     });
00089 }
00090
00091 void Scenario4_CompletionGroups::StartDownloadsButton_Click(Object^ sender, RoutedEventArgs^ e)
00092 {
00093     // Clear the status block.
00094     rootPage->NotifyUser("", NotifyType::StatusMessage);
00095
00096     BackgroundDownloader^ downloader = CompletionGroupTask::CreateBackgroundDownloader();
00097
00098     vector<task<void>> postCreateFileTasks;
00099
00100     for (int i = 0; i < 10; i++)
00101     {
00102         String^ sourceString = serverAddressField->Text + "?id=" + i.ToString();
00103
00104         Uri^ source;
00105         if (!rootPage->TryGetUri(sourceString, &source))
00106         {
00107             rootPage->NotifyUser("Unable to create the source URI.", NotifyType::ErrorMessage);
00108             return;
00109         }
00110
00111         task<StorageFile^> createFileTask = create_task(KnownFolders::GetFolderForUserAsync(nullptr /* current user */, KnownFolderId::PicturesLibrary))
00112             .then([](StorageFolder^ picturesLibrary)
00113         {
00114             return picturesLibrary->CreateFileAsync("picture.png", CreationCollisionOption::GenerateUniqueName);
00115         });
00116
00117         task<void> postCreateFileTask = createFileTask.then([this, downloader, source](task<StorageFile^> createFileTask)
00118         {
00119             StorageFile^ destinationFile = nullptr;
00120             try
00121             {
00122                 destinationFile = createFileTask.get();
00123             }
00124             catch (Exception^ ex)
00125             {
00126                 MarshalNotifyUser("Error creating file: " + ex->Message, NotifyType::ErrorMessage);
00127             }
00128
00129             if (destinationFile != nullptr)
00130             {
00131                 StartDownload(destinationFile, downloader, source);
00132             }
00133         });
00134
00135         postCreateFileTasks.push_back(postCreateFileTask);
00136     }
00137
00138
00139     when_all(postCreateFileTasks.begin(), postCreateFileTasks.end()).then([this, downloader]()
00140     {
00141         // The completion group must be enabled after all the downloads in the completion group are created.
00142         // Otherwise, if a download was allowed to be created within the completion group after the
00143         // completion group was enabled, it could happen that all downloads created before already completed
00144         // and completion group task was already triggered. It does not matter whether a completion group is
00145         // enabled before or after the calls to StartAsync().
00146         downloader->CompletionGroup->Enable();
00147
00148         MarshalNotifyUser("Completion group enabled.", NotifyType::StatusMessage);
00149     });
00150 }
00151
00152 void Scenario4_CompletionGroups::StartDownload(StorageFile^ destinationFile, BackgroundDownloader^ downloader, Uri^ source)
00153 {
00154     DownloadOperation^ download = downloader->CreateDownload(source, destinationFile);
00155
00156     create_task(download->StartAsync()).then([](task<DownloadOperation^> previousTask)
00157     {
00158         try
00159         {
00160             // Completion group tasks happen in addition to, not instead of, a
00161             // DownloadOperation's normal StartAsync and AttachAsync continuations. Even if you
00162             // are using a completion group, you should still use task.then() to attach a
00163             // completion handler to each transfer you create in your main application process.
00164             //
00165             // Even if a completion group is associated with multiple DownloadOperations, each
00166             // operation's StartAsync and AttachAsync continuations will be invoked individually.
00167             // The individual continuations execute independently of the completion group's
00168             // background task.They may occur before, after, or concurrently with each other.
00169
00170             // Check if there is any error.
00171             previousTask.get();
00172         }
00173         catch (Exception^ ex)
00174         {
00175             // It is required to handle exceptions. Otherwise exceptions bubble up
00176             // and the application may crash.
00177         }
00178     });
00179 }
00180
00181 // When operations happen on a background thread we have to marshal UI updates back to the UI thread.
00182 void Scenario4_CompletionGroups::MarshalNotifyUser(String^ message, NotifyType type)
00183 {
00184     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, message, type]()
00185     {
00186         rootPage->NotifyUser(message, type);
00187     }));
00188 }
Generated on Fri Nov 15 2024 22:18:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/WASAPICapture.cpp Source File

  • WindowsAudioSession
  • cpp

WASAPICapture.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // WASAPICapture.h
00013 //
00014
00015 #include "pch.h"
00016 #include "WASAPICapture.h"
00017
00018 using namespace Windows::Storage;
00019 using namespace Windows::System::Threading;
00020 using namespace SDKSample::WASAPIAudio;
00021
00022 #define BITS_PER_BYTE 8
00023
00024 //
00025 //  WASAPICapture()
00026 //
00027 WASAPICapture::WASAPICapture() :
00028     m_BufferFrames( 0 ),
00029     m_cbDataSize( 0 ),
00030     m_cbHeaderSize( 0 ),
00031     m_cbFlushCounter( 0 ),
00032     m_dwQueueID( 0 ),
00033     m_DeviceStateChanged( nullptr ),
00034     m_AudioClient( nullptr ),
00035     m_AudioCaptureClient( nullptr ),
00036     m_SampleReadyAsyncResult( nullptr ),
00037     m_ContentStream( nullptr ),
00038     m_OutputStream( nullptr ),
00039     m_WAVDataWriter( nullptr ),
00040     m_PlotData( nullptr ),
00041     m_fWriting( false )
00042 {
00043     // Create events for sample ready or user stop
00044     m_SampleReadyEvent = CreateEventEx( nullptr, nullptr, 0, EVENT_ALL_ACCESS );
00045     if (nullptr == m_SampleReadyEvent)
00046     {
00047         ThrowIfFailed( HRESULT_FROM_WIN32( GetLastError() ) );
00048     }
00049
00050     if (!InitializeCriticalSectionEx( &m_CritSec, 0, 0 ))
00051     {
00052         ThrowIfFailed( HRESULT_FROM_WIN32( GetLastError() ) );
00053     }
00054
00055     m_DeviceStateChanged = ref new DeviceStateChangedEvent();
00056
00057     // Register MMCSS work queue
00058     HRESULT hr = S_OK;
00059     DWORD dwTaskID = 0;
00060
00061     hr = MFLockSharedWorkQueue( L"Capture", 0, &dwTaskID, &m_dwQueueID );
00062     if (FAILED( hr ))
00063     {
00064         ThrowIfFailed( hr );
00065     }
00066
00067     // Set the capture event work queue to use the MMCSS queue
00068     m_xSampleReady.SetQueueID( m_dwQueueID );
00069 }
00070
00071 //
00072 //  ~WASAPICapture()
00073 //
00074 WASAPICapture::~WASAPICapture()
00075 {
00076     SAFE_RELEASE( m_AudioClient );
00077     SAFE_RELEASE( m_AudioCaptureClient );
00078     SAFE_RELEASE( m_SampleReadyAsyncResult );
00079
00080     if (INVALID_HANDLE_VALUE != m_SampleReadyEvent)
00081     {
00082         CloseHandle( m_SampleReadyEvent );
00083         m_SampleReadyEvent = INVALID_HANDLE_VALUE;
00084     }
00085
00086     MFUnlockWorkQueue( m_dwQueueID );
00087     CoTaskMemFree( m_MixFormat );
00088
00089     m_DeviceStateChanged = nullptr;
00090     m_ContentStream = nullptr;
00091     m_OutputStream = nullptr;
00092     m_WAVDataWriter = nullptr;
00093
00094     m_PlotData = nullptr;
00095
00096     DeleteCriticalSection( &m_CritSec );
00097 }
00098
00099 //
00100 //  InitializeAudioDeviceAsync()
00101 //
00102 //  Activates the default audio capture on a asynchronous callback thread.  This needs
00103 //  to be called from the main UI thread.
00104 //
00105 HRESULT WASAPICapture::InitializeAudioDeviceAsync()
00106 {
00107     ComPtr<IActivateAudioInterfaceAsyncOperation> asyncOp;
00108     HRESULT hr = S_OK;
00109
00110     // Get a string representing the Default Audio Capture Device
00111     m_DeviceIdString = MediaDevice::GetDefaultAudioCaptureId( Windows::Media::Devices::AudioDeviceRole::Default );
00112
00113     // This call must be made on the main UI thread.  Async operation will call back to
00114     // IActivateAudioInterfaceCompletionHandler::ActivateCompleted, which must be an agile interface implementation
00115     hr = ActivateAudioInterfaceAsync( m_DeviceIdString->Data(), __uuidof(IAudioClient3), nullptr, this, &asyncOp );
00116     if (FAILED( hr ))
00117     {
00118         m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
00119     }
00120
00121     return hr;
00122 }
00123
00124 //
00125 //  ActivateCompleted()
00126 //
00127 //  Callback implementation of ActivateAudioInterfaceAsync function.  This will be called on MTA thread
00128 //  when results of the activation are available.
00129 //
00130 HRESULT WASAPICapture::ActivateCompleted( IActivateAudioInterfaceAsyncOperation *operation )
00131 {
00132     HRESULT hr = S_OK;
00133     HRESULT hrActivateResult = S_OK;
00134     ComPtr<IUnknown> punkAudioInterface;
00135
00136     // Check for a successful activation result
00137     hr = operation->GetActivateResult( &hrActivateResult, &punkAudioInterface );
00138     if (FAILED( hr ))
00139     {
00140         goto exit;
00141     }
00142
00143     hr = hrActivateResult;
00144     if (FAILED( hr ))
00145     {
00146         goto exit;
00147     }
00148
00149     // Get the pointer for the Audio Client
00150     punkAudioInterface.CopyTo( &m_AudioClient );
00151     if (nullptr == m_AudioClient)
00152     {
00153         hr = E_NOINTERFACE;
00154         goto exit;
00155     }
00156
00157     hr = m_AudioClient->GetMixFormat( &m_MixFormat );
00158     if (FAILED( hr ))
00159     {
00160         goto exit;
00161     }
00162
00163     // convert from Float to 16-bit PCM
00164     switch ( m_MixFormat->wFormatTag )
00165     {
00166     case WAVE_FORMAT_PCM:
00167         // nothing to do
00168         break;
00169
00170     case WAVE_FORMAT_IEEE_FLOAT:
00171         m_MixFormat->wFormatTag = WAVE_FORMAT_PCM;
00172         m_MixFormat->wBitsPerSample = 16;
00173         m_MixFormat->nBlockAlign = m_MixFormat->nChannels * m_MixFormat->wBitsPerSample / BITS_PER_BYTE;
00174         m_MixFormat->nAvgBytesPerSec = m_MixFormat->nSamplesPerSec * m_MixFormat->nBlockAlign;
00175         break;
00176
00177     case WAVE_FORMAT_EXTENSIBLE:
00178         {
00179             WAVEFORMATEXTENSIBLE *pWaveFormatExtensible = reinterpret_cast<WAVEFORMATEXTENSIBLE *>(m_MixFormat);
00180             if ( pWaveFormatExtensible->SubFormat == KSDATAFORMAT_SUBTYPE_PCM )
00181             {
00182                 // nothing to do
00183             }
00184             else if ( pWaveFormatExtensible->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT )
00185             {
00186                 pWaveFormatExtensible->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
00187                 pWaveFormatExtensible->Format.wBitsPerSample = 16;
00188                 pWaveFormatExtensible->Format.nBlockAlign =
00189                     pWaveFormatExtensible->Format.nChannels *
00190                     pWaveFormatExtensible->Format.wBitsPerSample /
00191                     BITS_PER_BYTE;
00192                 pWaveFormatExtensible->Format.nAvgBytesPerSec =
00193                     pWaveFormatExtensible->Format.nSamplesPerSec *
00194                     pWaveFormatExtensible->Format.nBlockAlign;
00195                 pWaveFormatExtensible->Samples.wValidBitsPerSample =
00196                     pWaveFormatExtensible->Format.wBitsPerSample;
00197
00198                 // leave the channel mask as-is
00199             }
00200             else
00201             {
00202                 // we can only handle float or PCM
00203                 hr = HRESULT_FROM_WIN32( ERROR_NOT_FOUND );
00204             }
00205             break;
00206         }
00207
00208     default:
00209         // we can only handle float or PCM
00210         hr = HRESULT_FROM_WIN32( ERROR_NOT_FOUND );
00211         break;
00212     }
00213
00214     if (FAILED( hr ))
00215     {
00216         goto exit;
00217     }
00218
00219     // The wfx parameter below is optional (Its needed only for MATCH_FORMAT clients). Otherwise, wfx will be assumed
00220     // to be the current engine format based on the processing mode for this stream
00221     hr = m_AudioClient->GetSharedModeEnginePeriod(m_MixFormat, &m_DefaultPeriodInFrames, &m_FundamentalPeriodInFrames, &m_MinPeriodInFrames, &m_MaxPeriodInFrames);
00222     if (FAILED(hr))
00223     {
00224         goto exit;
00225     }
00226
00227     // Initialize the AudioClient in Shared Mode with the user specified buffer
00228     if (m_DeviceProps.IsLowLatency == false)
00229     {
00230         hr = m_AudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED,
00231             AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
00232             200000,
00233             0,
00234             m_MixFormat,
00235             nullptr);
00236     }
00237     else
00238     {
00239         hr = m_AudioClient->InitializeSharedAudioStream(
00240             AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
00241             m_MinPeriodInFrames,
00242             m_MixFormat,
00243             nullptr);
00244     }
00245
00246
00247     if (FAILED( hr ))
00248     {
00249         goto exit;
00250     }
00251
00252     // Get the maximum size of the AudioClient Buffer
00253     hr = m_AudioClient->GetBufferSize( &m_BufferFrames );
00254     if (FAILED( hr ))
00255     {
00256         goto exit;
00257     }
00258
00259     // Get the capture client
00260     hr = m_AudioClient->GetService( __uuidof(IAudioCaptureClient), (void**) &m_AudioCaptureClient );
00261     if (FAILED( hr ))
00262     {
00263         goto exit;
00264     }
00265
00266     // Create Async callback for sample events
00267     hr = MFCreateAsyncResult( nullptr, &m_xSampleReady, nullptr, &m_SampleReadyAsyncResult );
00268     if (FAILED( hr ))
00269     {
00270         goto exit;
00271     }
00272
00273     // Sets the event handle that the system signals when an audio buffer is ready to be processed by the client
00274     hr = m_AudioClient->SetEventHandle( m_SampleReadyEvent );
00275     if (FAILED( hr ))
00276     {
00277         goto exit;
00278     }
00279
00280     // Create the visualization array
00281     hr = InitializeScopeData();
00282     if (FAILED( hr ))
00283     {
00284         goto exit;
00285     }
00286
00287     // Creates the WAV file.  If successful, will set the Initialized event
00288     hr = CreateWAVFile();
00289     if (FAILED( hr ))
00290     {
00291         goto exit;
00292     }
00293
00294 exit:
00295     if (FAILED( hr ))
00296     {
00297         m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
00298         SAFE_RELEASE( m_AudioClient );
00299         SAFE_RELEASE( m_AudioCaptureClient );
00300         SAFE_RELEASE( m_SampleReadyAsyncResult );
00301     }
00302
00303     // Need to return S_OK
00304     return S_OK;
00305 }
00306
00307 //
00308 //  CreateWAVFile()
00309 //
00310 //  Creates a WAV file in KnownFolders::MusicLibrary
00311 //
00312 HRESULT WASAPICapture::CreateWAVFile()
00313 {
00314     // Create the WAV file, appending a number if file already exists
00315     concurrency::task<StorageFile^>( KnownFolders::MusicLibrary->CreateFileAsync( AUDIO_FILE_NAME, CreationCollisionOption::GenerateUniqueName )).then(
00316         [this]( StorageFile^ file )
00317     {
00318         return file->OpenAsync( FileAccessMode::ReadWrite );
00319     })
00320
00321     // Then create a RandomAccessStream
00322     .then([this]( IRandomAccessStream^ stream )
00323     {
00324         // Get the OutputStream for the file
00325         m_ContentStream = stream;
00326         m_OutputStream = m_ContentStream->GetOutputStreamAt(0);
00327
00328         // Create the DataWriter
00329         m_WAVDataWriter = ref new DataWriter( m_OutputStream );
00330
00331         // Create the WAV header
00332         DWORD header[] = {
00333             FCC('RIFF'),        // RIFF header
00334             0,                  // Total size of WAV (will be filled in later)
00335             FCC('WAVE'),        // WAVE FourCC
00336             FCC('fmt '),        // Start of 'fmt ' chunk
00337             sizeof(WAVEFORMATEX) + m_MixFormat->cbSize      // Size of fmt chunk
00338         };
00339
00340         DWORD data[] = { FCC('data'), 0 };  // Start of 'data' chunk
00341
00342         auto headerBytes = ref new Platform::Array<BYTE>( reinterpret_cast<BYTE*>(header), sizeof(header) );
00343         auto formatBytes = ref new Platform::Array<BYTE>( reinterpret_cast<BYTE*>(m_MixFormat), sizeof(WAVEFORMATEX) + m_MixFormat->cbSize );
00344         auto dataBytes = ref new Platform::Array<BYTE>( reinterpret_cast<BYTE*>(data), sizeof(data) );
00345
00346         if ( (nullptr == headerBytes) || (nullptr == formatBytes) || (nullptr == dataBytes) )
00347         {
00348             ThrowIfFailed( E_OUTOFMEMORY );
00349         }
00350
00351         // Write the header
00352         m_WAVDataWriter->WriteBytes( headerBytes );
00353         m_WAVDataWriter->WriteBytes( formatBytes );
00354         m_WAVDataWriter->WriteBytes( dataBytes );
00355
00356         return m_WAVDataWriter->StoreAsync();
00357     })
00358
00359     // Wait for file data to be written to file
00360     .then([this]( unsigned int BytesWritten )
00361     {
00362         m_cbHeaderSize = BytesWritten;
00363         return m_WAVDataWriter->FlushAsync();
00364     })
00365
00366     // Our file is ready to go, so we can now signal that initialization is finished
00367     .then([this]( concurrency::task<bool> previousTask )
00368     {
00369         try
00370         {
00371             previousTask.get();
00372             m_DeviceStateChanged->SetState( DeviceState::DeviceStateInitialized, S_OK, true );
00373         }
00374         catch (Platform::Exception ^e)
00375         {
00376             m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, e->HResult, true );
00377         }
00378     });
00379
00380     return S_OK;
00381 }
00382
00383 //
00384 //  FixWAVHeader()
00385 //
00386 //  The size values were not known when we originally wrote the header, so now go through and fix the values
00387 //
00388 HRESULT WASAPICapture::FixWAVHeader()
00389 {
00390     auto DataSizeByte = ref new Platform::Array<BYTE>( reinterpret_cast<BYTE*>( &m_cbDataSize ), sizeof(DWORD) );
00391
00392     // Write the size of the 'data' chunk first
00393     IOutputStream^ OutputStream = m_ContentStream->GetOutputStreamAt( m_cbHeaderSize - sizeof(DWORD) );
00394     m_WAVDataWriter = ref new DataWriter( OutputStream );
00395     m_WAVDataWriter->WriteBytes( DataSizeByte );
00396
00397     concurrency::task<unsigned int>( m_WAVDataWriter->StoreAsync()).then(
00398         [this]( unsigned int BytesWritten )
00399     {
00400         DWORD cbTotalSize = m_cbDataSize + m_cbHeaderSize - 8;
00401         auto TotalSizeByte = ref new Platform::Array<BYTE>( reinterpret_cast<BYTE*>( &cbTotalSize ), sizeof(DWORD) );
00402
00403         // Write the total file size, minus RIFF chunk and size
00404         IOutputStream^ OutputStream = m_ContentStream->GetOutputStreamAt( sizeof(DWORD) );  // sizeof(DWORD) == sizeof(FOURCC)
00405         m_WAVDataWriter = ref new DataWriter( OutputStream );
00406         m_WAVDataWriter->WriteBytes( TotalSizeByte );
00407
00408         concurrency::task<unsigned int>( m_WAVDataWriter->StoreAsync()).then(
00409             [this]( unsigned int BytesWritten )
00410         {
00411             return m_WAVDataWriter->FlushAsync();
00412         })
00413
00414         .then(
00415             [this]( bool f )
00416         {
00417             m_DeviceStateChanged->SetState( DeviceState::DeviceStateStopped, S_OK, true );
00418         });
00419     });
00420
00421     return S_OK;
00422 }
00423
00424 //
00425 //  InitializeScopeData()
00426 //
00427 //  Setup data structures for sample visualizations
00428 //
00429 HRESULT WASAPICapture::InitializeScopeData()
00430 {
00431     HRESULT hr = S_OK;
00432
00433     m_cPlotDataFilled = 0;
00434     m_cPlotDataMax = (MILLISECONDS_TO_VISUALIZE * m_MixFormat->nSamplesPerSec) / 1000;
00435
00436     m_PlotData = ref new Platform::Array<int, 1>( m_cPlotDataMax + 1 );
00437     if (nullptr == m_PlotData)
00438     {
00439         return E_OUTOFMEMORY;
00440     }
00441
00442     // Only Support 16 bit Audio for now
00443     if (m_MixFormat->wBitsPerSample == 16)
00444     {
00445         m_PlotData[ m_cPlotDataMax ] = -32768;  // INT16_MAX
00446     }
00447     else
00448     {
00449         m_PlotData = nullptr;
00450         hr = S_FALSE;
00451     }
00452
00453     return hr;
00454 }
00455
00456 //
00457 //  StartCaptureAsync()
00458 //
00459 //  Starts asynchronous capture on a separate thread via MF Work Item
00460 //
00461 HRESULT WASAPICapture::StartCaptureAsync()
00462 {
00463     HRESULT hr = S_OK;
00464
00465     // We should be in the initialzied state if this is the first time through getting ready to capture.
00466     if (m_DeviceStateChanged->GetState() == DeviceState::DeviceStateInitialized)
00467     {
00468         m_DeviceStateChanged->SetState( DeviceState::DeviceStateStarting, S_OK, true );
00469         return MFPutWorkItem2( MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_xStartCapture, nullptr );
00470     }
00471
00472     // We are in the wrong state
00473     return E_NOT_VALID_STATE;
00474 }
00475
00476 //
00477 //  OnStartCapture()
00478 //
00479 //  Callback method to start capture
00480 //
00481 HRESULT WASAPICapture::OnStartCapture( IMFAsyncResult* pResult )
00482 {
00483     HRESULT hr = S_OK;
00484
00485     // Start the capture
00486     hr = m_AudioClient->Start();
00487     if (SUCCEEDED( hr ))
00488     {
00489         hr = MFPutWaitingWorkItem( m_SampleReadyEvent, 0, m_SampleReadyAsyncResult, &m_SampleReadyKey );
00490     }
00491
00492     if (SUCCEEDED( hr ))
00493     {
00494         m_DeviceStateChanged->SetState( DeviceState::DeviceStateCapturing, S_OK, true );
00495     }
00496     else
00497     {
00498         m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
00499     }
00500
00501     return S_OK;
00502 }
00503
00504 //
00505 //  StopCaptureAsync()
00506 //
00507 //  Stop capture asynchronously via MF Work Item
00508 //
00509 HRESULT WASAPICapture::StopCaptureAsync()
00510 {
00511     if ( (m_DeviceStateChanged->GetState() != DeviceState::DeviceStateCapturing) &&
00512          (m_DeviceStateChanged->GetState() != DeviceState::DeviceStateInError) )
00513     {
00514         return E_NOT_VALID_STATE;
00515     }
00516
00517     m_DeviceStateChanged->SetState( DeviceState::DeviceStateStopping, S_OK, true );
00518
00519     return MFPutWorkItem2( MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_xStopCapture, nullptr );
00520 }
00521
00522 //
00523 //  OnStopCapture()
00524 //
00525 //  Callback method to stop capture
00526 //
00527 HRESULT WASAPICapture::OnStopCapture( IMFAsyncResult* pResult )
00528 {
00529     // Stop capture by cancelling Work Item
00530     // Cancel the queued work item (if any)
00531     if (0 != m_SampleReadyKey)
00532     {
00533         MFCancelWorkItem( m_SampleReadyKey );
00534         m_SampleReadyKey = 0;
00535     }
00536
00537     m_AudioClient->Stop();
00538     SAFE_RELEASE( m_SampleReadyAsyncResult );
00539
00540     // If this is set, it means we writing from the memory buffer to the actual file asynchronously
00541     // Since a second call to StoreAsync() can cause an exception, don't queue this now, but rather
00542     // let the async operation completion handle the call.
00543     if (!m_fWriting)
00544     {
00545         m_DeviceStateChanged->SetState( DeviceState::DeviceStateFlushing, S_OK, true );
00546
00547         concurrency::task<unsigned int>( m_WAVDataWriter->StoreAsync()).then(
00548             [this]( unsigned int BytesWritten )
00549         {
00550             FinishCaptureAsync();
00551         });
00552     }
00553
00554     return S_OK;
00555 }
00556
00557 //
00558 //  FinishCaptureAsync()
00559 //
00560 //  Finalizes WAV file on a separate thread via MF Work Item
00561 //
00562 HRESULT WASAPICapture::FinishCaptureAsync()
00563 {
00564     // We should be flushing when this is called
00565     if (m_DeviceStateChanged->GetState() == DeviceState::DeviceStateFlushing)
00566     {
00567         return MFPutWorkItem2( MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_xFinishCapture, nullptr );
00568     }
00569
00570     // We are in the wrong state
00571     return E_NOT_VALID_STATE;
00572 }
00573
00574 //
00575 //  OnFinishCapture()
00576 //
00577 //  Because of the asynchronous nature of the MF Work Queues and the DataWriter, there could still be
00578 //  a sample processing.  So this will get called to finalize the WAV header.
00579 //
00580 HRESULT WASAPICapture::OnFinishCapture( IMFAsyncResult* pResult )
00581 {
00582     // FixWAVHeader will set the DeviceStateStopped when all async tasks are complete
00583     return FixWAVHeader();
00584 }
00585
00586 //
00587 //  OnSampleReady()
00588 //
00589 //  Callback method when ready to fill sample buffer
00590 //
00591 HRESULT WASAPICapture::OnSampleReady( IMFAsyncResult* pResult )
00592 {
00593     HRESULT hr = S_OK;
00594
00595     hr = OnAudioSampleRequested( false );
00596
00597     if (SUCCEEDED( hr ))
00598     {
00599         // Re-queue work item for next sample
00600         if (m_DeviceStateChanged->GetState() ==  DeviceState::DeviceStateCapturing)
00601         {
00602             hr = MFPutWaitingWorkItem( m_SampleReadyEvent, 0, m_SampleReadyAsyncResult, &m_SampleReadyKey );
00603         }
00604     }
00605     else
00606     {
00607         m_DeviceStateChanged->SetState( DeviceState::DeviceStateInError, hr, true );
00608     }
00609
00610     return hr;
00611 }
00612
00613 //
00614 //  OnAudioSampleRequested()
00615 //
00616 //  Called when audio device fires m_SampleReadyEvent
00617 //
00618 HRESULT WASAPICapture::OnAudioSampleRequested( Platform::Boolean IsSilence )
00619 {
00620     HRESULT hr = S_OK;
00621     UINT32 FramesAvailable = 0;
00622     BYTE *Data = nullptr;
00623     DWORD dwCaptureFlags;
00624     UINT64 u64DevicePosition = 0;
00625     UINT64 u64QPCPosition = 0;
00626     DWORD cbBytesToCapture = 0;
00627
00628     EnterCriticalSection( &m_CritSec );
00629
00630     // If this flag is set, we have already queued up the async call to finialize the WAV header
00631     // So we don't want to grab or write any more data that would possibly give us an invalid size
00632     if ( (m_DeviceStateChanged->GetState() == DeviceState::DeviceStateStopping) ||
00633          (m_DeviceStateChanged->GetState() == DeviceState::DeviceStateFlushing) )
00634     {
00635         goto exit;
00636     }
00637
00638     // A word on why we have a loop here;
00639     // Suppose it has been 10 milliseconds or so since the last time
00640     // this routine was invoked, and that we're capturing 48000 samples per second.
00641     //
00642     // The audio engine can be reasonably expected to have accumulated about that much
00643     // audio data - that is, about 480 samples.
00644     //
00645     // However, the audio engine is free to accumulate this in various ways:
00646     // a. as a single packet of 480 samples, OR
00647     // b. as a packet of 80 samples plus a packet of 400 samples, OR
00648     // c. as 48 packets of 10 samples each.
00649     //
00650     // In particular, there is no guarantee that this routine will be
00651     // run once for each packet.
00652     //
00653     // So every time this routine runs, we need to read ALL the packets
00654     // that are now available;
00655     //
00656     // We do this by calling IAudioCaptureClient::GetNextPacketSize
00657     // over and over again until it indicates there are no more packets remaining.
00658     for
00659     (
00660         hr = m_AudioCaptureClient->GetNextPacketSize(&FramesAvailable);
00661         SUCCEEDED(hr) && FramesAvailable > 0;
00662         hr = m_AudioCaptureClient->GetNextPacketSize(&FramesAvailable)
00663     )
00664     {
00665         cbBytesToCapture = FramesAvailable * m_MixFormat->nBlockAlign;
00666
00667         // WAV files have a 4GB (0xFFFFFFFF) size limit, so likely we have hit that limit when we
00668         // overflow here.  Time to stop the capture
00669         if ( (m_cbDataSize + cbBytesToCapture) < m_cbDataSize )
00670         {
00671             StopCaptureAsync();
00672             goto exit;
00673         }
00674
00675         // Get sample buffer
00676         hr = m_AudioCaptureClient->GetBuffer( &Data, &FramesAvailable, &dwCaptureFlags, &u64DevicePosition, &u64QPCPosition );
00677         if (FAILED( hr ))
00678         {
00679             goto exit;
00680         }
00681
00682         if (dwCaptureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY)
00683         {
00684             // Pass down a discontinuity flag in case the app is interested and reset back to capturing
00685             m_DeviceStateChanged->SetState( DeviceState::DeviceStateDiscontinuity, S_OK, true );
00686             m_DeviceStateChanged->SetState( DeviceState::DeviceStateCapturing, S_OK, false );
00687         }
00688
00689         // Zero out sample if silence
00690         if ( (dwCaptureFlags & AUDCLNT_BUFFERFLAGS_SILENT) || IsSilence )
00691         {
00692             memset( Data, 0, FramesAvailable * m_MixFormat->nBlockAlign );
00693         }
00694
00695         // Store data in array
00696         auto dataByte = ref new Platform::Array<BYTE, 1>( Data, cbBytesToCapture );
00697
00698         // Release buffer back
00699         m_AudioCaptureClient->ReleaseBuffer( FramesAvailable );
00700
00701         // Update plotter data
00702         ProcessScopeData( dataByte->Data, dataByte->Length );
00703
00704         // Write File and async store
00705         m_WAVDataWriter->WriteBytes( dataByte );
00706
00707         // Increase the size of our 'data' chunk and flush counter.  m_cbDataSize needs to be accurate
00708         // Its OK if m_cbFlushCounter is an approximation
00709         m_cbDataSize += cbBytesToCapture;
00710         m_cbFlushCounter += cbBytesToCapture;
00711
00712         if ( (m_cbFlushCounter > ( m_MixFormat->nAvgBytesPerSec * FLUSH_INTERVAL_SEC )) && !m_fWriting )
00713         {
00714             // Set this flag when about to commit the async storage operation.  We don't want to
00715             // accidently call stop and finalize the WAV header or run into a scenario where the
00716             // store operation takes longer than FLUSH_INTERVAL_SEC as multiple concurrent calls
00717             // to StoreAsync() can cause an exception
00718             m_fWriting = true;
00719
00720             // Reset the counter now since we can process more samples during the async callback
00721             m_cbFlushCounter = 0;
00722
00723             concurrency::task<unsigned int>( m_WAVDataWriter->StoreAsync()).then(
00724                 [this]( unsigned int BytesWritten )
00725             {
00726                 m_fWriting = false;
00727
00728                 // We need to check for StopCapture while we are flusing the file.  If it has come through, then we
00729                 // can go ahead and call FinisheCaptureAsync() to write the WAV header
00730                 if (m_DeviceStateChanged->GetState() == DeviceState::DeviceStateStopping)
00731                 {
00732                     m_DeviceStateChanged->SetState( DeviceState::DeviceStateFlushing, S_OK, true );
00733                     FinishCaptureAsync();
00734                 }
00735             });
00736         }
00737     }
00738
00739 exit:
00740     LeaveCriticalSection( &m_CritSec );
00741
00742     return hr;
00743 }
00744
00745 //
00746 //  ProcessScopeData()
00747 //
00748 //  Copies sample data to the buffer array and fires the event
00749 //
00750 HRESULT WASAPICapture::ProcessScopeData( BYTE* pData, DWORD cbBytes )
00751 {
00752     HRESULT hr = S_OK;
00753
00754     // We don't have a valid pointer array, so return.  This could be the case if we aren't
00755     // dealing with 16-bit audio
00756     if (m_PlotData == nullptr)
00757     {
00758         return S_FALSE;
00759     }
00760
00761     DWORD dwNumPoints = cbBytes / m_MixFormat->nChannels / (m_MixFormat->wBitsPerSample / 8);
00762
00763     // Read the 16-bit samples from channel 0
00764     INT16 *pi16 = (INT16*)pData;
00765
00766     for ( DWORD i = 0; m_cPlotDataFilled < m_cPlotDataMax && i < dwNumPoints; i++ )
00767     {
00768         m_PlotData[ m_cPlotDataFilled ] = *pi16;
00769         pi16 += m_MixFormat->nChannels;
00770
00771         m_cPlotDataFilled++;
00772     }
00773
00774     // Send off the event and get ready for the next set of samples
00775     if (m_cPlotDataFilled == m_cPlotDataMax)
00776     {
00777         ComPtr<IUnknown> spUnknown;
00778         ComPtr<CAsyncState> spState = Make<CAsyncState>( m_PlotData, m_cPlotDataMax + 1 );
00779
00780         hr = spState.As( &spUnknown );
00781         if (SUCCEEDED( hr ))
00782         {
00783             MFPutWorkItem2( MFASYNC_CALLBACK_QUEUE_MULTITHREADED, 0, &m_xSendScopeData, spUnknown.Get() );
00784         }
00785
00786         m_cPlotDataFilled = 0;
00787     }
00788
00789     return hr;
00790 }
00791
00792 //
00793 //  OnSendScopeData()
00794 //
00795 //  Callback method to stop capture
00796 //
00797 HRESULT WASAPICapture::OnSendScopeData( IMFAsyncResult* pResult )
00798 {
00799     HRESULT hr = S_OK;
00800     CAsyncState *pState = nullptr;
00801
00802     hr = pResult->GetState( reinterpret_cast<IUnknown**>(&pState) );
00803     if (SUCCEEDED( hr ))
00804     {
00805         PlotDataReadyEvent::SendEvent( reinterpret_cast<Platform::Object^>(this), pState->m_Data , pState->m_Size );
00806     }
00807
00808     SAFE_RELEASE( pState );
00809
00810     return S_OK;
00811 }
00812
00813 //
00814 //  SetProperties()
00815 //
00816 //  Sets various properties that the user defines in the scenario
00817 //
00818 HRESULT WASAPICapture::SetProperties(CAPTUREDEVICEPROPS props)
00819 {
00820     m_DeviceProps = props;
00821     return S_OK;
00822 }
Generated on Fri Nov 15 2024 22:22:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_SelectDisplay Member List

This is the complete list of members for Scenario1_SelectDisplay, including all inherited members.
IsNonNull(object item) | Scenario1_SelectDisplay |
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_SelectDisplay | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_SelectDisplay | [inline, protected]
RefreshButton_Click(object sender, RoutedEventArgs e) | Scenario1_SelectDisplay | [inline, private]
RestartWatcher() | Scenario1_SelectDisplay | [inline, private]
rootPage | Scenario1_SelectDisplay | [private]
Scenario1_SelectDisplay() | Scenario1_SelectDisplay | [inline]
SelectButton_Click(object sender, RoutedEventArgs e) | Scenario1_SelectDisplay | [inline, private]
StopWatcher() | Scenario1_SelectDisplay | [inline, private]
watcher | Scenario1_SelectDisplay | [private]
Watcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo) | Scenario1_SelectDisplay | [inline, private]
Watcher_EnumerationCompleted(DeviceWatcher sender, object e) | Scenario1_SelectDisplay | [inline, private]
Generated on Fri Nov 15 2024 22:23:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInfo/cppwinrt/Project.idl Source File

  • UserInfo
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_FindUsers : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_FindUsers();
00018
00019         void ShowProperties();
00020     }
00021
00022     [default_interface]
00023     runtimeclass Scenario2_WatchUsers : Windows.UI.Xaml.Controls.Page
00024     {
00025         Scenario2_WatchUsers();
00026
00027         Windows.Foundation.Collections.IObservableVector<UserViewModel> Users{ get; };
00028         void StartWatching();
00029         void StopWatching();
00030     }
00031
00032   [default_interface]
00033   runtimeclass Scenario3_CheckUserConsentGroup : Windows.UI.Xaml.Controls.Page
00034   {
00035     Scenario3_CheckUserConsentGroup();
00036   }
00037
00038     [Windows.UI.Xaml.Data.Bindable]
00039     runtimeclass UserViewModel : Windows.UI.Xaml.Data.INotifyPropertyChanged
00040     {
00041         String UserId { get; };
00042         String DisplayName { get; };
00043     }
00044 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/BackgroundTask/Scenario3_ServicingCompleteTask.xaml.h Source File

  • BackgroundTask
  • cpp
  • BackgroundTask

Scenario3_ServicingCompleteTask.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario3_ServicingCompleteTask.xaml.h
00013 // Declaration of the ServicingCompleteTask class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario3_ServicingCompleteTask.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     [Windows::Foundation::Metadata::WebHostHidden]
00028     public ref class ServicingCompleteTask sealed
00029     {
00030     public:
00031         ServicingCompleteTask();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035     private:
00036         SDKTemplate::MainPage^ rootPage;
00037
00038         void AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^ task);
00039         void RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^ args);
00042         void OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ args);
00043         void UpdateUI();
00044     };
00045 }
Generated on Fri Nov 15 2024 22:18:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/Scenario2.cpp Source File

  • WindowsAudioSession
  • cppwinrt

Scenario2.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
00012 #include "Scenario2.h"
00013 #include "Scenario2.g.cpp"
00014
00015 using namespace winrt;
00016 using namespace winrt::Windows::Devices::Enumeration;
00017 using namespace winrt::Windows::Media;
00018 using namespace winrt::Windows::Media::Devices;
00019 using namespace winrt::Windows::Storage;
00020 using namespace winrt::Windows::Storage::Pickers;
00021 using namespace winrt::Windows::Storage::Streams;
00022 using namespace winrt::Windows::UI;
00023 using namespace winrt::Windows::UI::Xaml::Controls::Primitives;
00024 using namespace winrt::Windows::UI::Xaml::Media;
00025 using namespace winrt::Windows::UI::Xaml::Navigation;
00026
00027 namespace winrt::SDKTemplate::implementation
00028 {
00029     Scenario2::Scenario2()
00030     {
00031         InitializeComponent();
00032     }
00033
00034     fire_and_forget Scenario2::OnNavigatedTo(NavigationEventArgs const&)
00035     {
00036         auto lifetime = get_strong();
00037
00038         // Register for Media Transport controls.  This is required to support background
00039         // audio scenarios.
00040         m_systemMediaControls = SystemMediaTransportControls::GetForCurrentView();
00041         m_systemMediaControlsButtonToken = m_systemMediaControls.ButtonPressed({ get_weak(), &Scenario2::MediaButtonPressed });
00042         m_systemMediaControls.IsPlayEnabled(true);
00043         m_systemMediaControls.IsPauseEnabled(true);
00044         m_systemMediaControls.IsStopEnabled(true);
00045
00046         UpdateContentUI();
00047
00048         // Get a string representing the Default Audio Render Device
00049         hstring deviceId = MediaDevice::GetDefaultAudioRenderId(AudioDeviceRole::Default);
00050
00051         // The string is empty if there is no such device.
00052         if (deviceId.empty())
00053         {
00054             rootPage.NotifyUser(L"No audio devices available", NotifyType::StatusMessage);
00055             co_return;
00056         }
00057
00058         // read property store to see if the device supports a RAW processing mode
00059         static constexpr wchar_t PKEY_AudioDevice_RawProcessingSupported[] = L"System.Devices.AudioDevice.RawProcessingSupported";
00060         DeviceInformation deviceInformation = co_await DeviceInformation::CreateFromIdAsync(deviceId, { PKEY_AudioDevice_RawProcessingSupported });
00061
00062         std::optional<bool> obj = deviceInformation.Properties().TryLookup(PKEY_AudioDevice_RawProcessingSupported).try_as<bool>();
00063         m_deviceSupportsRawMode = (obj == true);
00064         toggleRawAudio().IsEnabled(m_deviceSupportsRawMode);
00065
00066         if (m_deviceSupportsRawMode)
00067         {
00068             rootPage.NotifyUser(L"Raw Supported", NotifyType::StatusMessage);
00069         }
00070         else
00071         {
00072             rootPage.NotifyUser(L"Raw Not Supported", NotifyType::StatusMessage);
00073         }
00074     }
00075
00076     void Scenario2::OnNavigatedFrom(NavigationEventArgs const&)
00077     {
00078         StopDevice();
00079
00080         if (m_deviceStateChangeToken)
00081         {
00082             m_renderer->DeviceStateChanged(std::exchange(m_deviceStateChangeToken, {}));
00083         }
00084
00085         if (m_systemMediaControlsButtonToken)
00086         {
00087             m_systemMediaControls.ButtonPressed(m_systemMediaControlsButtonToken);
00088             m_systemMediaControls.IsPlayEnabled(false);
00089             m_systemMediaControls.IsPauseEnabled(false);
00090             m_systemMediaControls.IsStopEnabled(false);
00091             m_systemMediaControls.PlaybackStatus(MediaPlaybackStatus::Closed);
00092         }
00093     }
00094
00095 #pragma region UI Related Code
00096
00097     void Scenario2::DisableContentUI()
00098     {
00099         btnFilePicker().IsEnabled(false);
00100         sliderFrequency().IsEnabled(false);
00101         radioFile().IsEnabled(false);
00102         radioTone().IsEnabled(false);
00103     }
00104
00105     // Updates content controls based on selected option
00106     void Scenario2::UpdateContentUI()
00107     {
00108         // Ignore calls triggered by binding before construction is complete.
00109         if (radioFile() == nullptr)
00110         {
00111             return;
00112         }
00113
00114         radioFile().IsEnabled(true);
00115         radioTone().IsEnabled(true);
00116
00117         switch (m_contentType)
00118         {
00119         case ContentType::Tone:
00120             btnFilePicker().IsEnabled(false);
00121             sliderFrequency().IsEnabled(true);
00122             UpdateContentProps(to_hstring(sliderFrequency().Value()) + L" Hz");
00123             break;
00124
00125         case ContentType::File:
00126             btnFilePicker().IsEnabled(true);
00127             sliderFrequency().IsEnabled(false);
00128             break;
00129
00130         default:
00131             break;
00132         }
00133     }
00134
00135     // Updates transport controls based on current playstate
00136     void Scenario2::UpdateMediaControlUI(DeviceState deviceState)
00137     {
00138         switch (deviceState)
00139         {
00140         case DeviceState::Playing:
00141             btnPlay().IsEnabled(false);
00142             btnStop().IsEnabled(true);
00143             btnPlayPause().IsEnabled(true);
00144             btnPause().IsEnabled(true);
00145             break;
00146
00147         case DeviceState::Stopped:
00148         case DeviceState::Error:
00149             btnPlay().IsEnabled(true);
00150             btnStop().IsEnabled(false);
00151             btnPlayPause().IsEnabled(true);
00152             btnPause().IsEnabled(false);
00153
00154             UpdateContentUI();
00155             break;
00156
00157         case DeviceState::Paused:
00158             btnPlay().IsEnabled(true);
00159             btnStop().IsEnabled(true);
00160             btnPlayPause().IsEnabled(true);
00161             btnPause().IsEnabled(false);
00162             break;
00163
00164         case DeviceState::Starting:
00165         case DeviceState::Stopping:
00166             btnPlay().IsEnabled(false);
00167             btnStop().IsEnabled(false);
00168             btnPlayPause().IsEnabled(false);
00169             btnPause().IsEnabled(false);
00170
00171             DisableContentUI();
00172             break;
00173         }
00174     }
00175
00176     // Updates textbox
00177     void Scenario2::UpdateContentProps(hstring const& text)
00178     {
00179         // Ignore calls triggered by binding before construction is complete.
00180         if (txtContentProps() == nullptr)
00181         {
00182             return;
00183         }
00184
00185         txtContentProps().Text(text);
00186
00187         if (text.empty() && (m_contentType == ContentType::File))
00188         {
00189             txtContentProps().Background(SolidColorBrush({ 0xCC, 0xFF, 0x00, 0x00 }));
00190         }
00191         else
00192         {
00193             txtContentProps().Background(nullptr);
00194         }
00195     }
00196
00197 #pragma endregion
00198
00199 #pragma region UI Event Handlers
00200
00201     void Scenario2::sliderFrequency_ValueChanged(IInspectable const&, RangeBaseValueChangedEventArgs const& e)
00202     {
00203         UpdateContentProps(to_hstring(e.NewValue()) + L" Hz");
00204     }
00205
00206     void Scenario2::sliderVolume_ValueChanged(IInspectable const&, RangeBaseValueChangedEventArgs const& e)
00207     {
00208         OnSetVolume(e.NewValue());
00209     }
00210
00211     void Scenario2::radioTone_Checked(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00212     {
00213         m_contentType = ContentType::Tone;
00214         UpdateContentProps(L"");
00215         m_contentStream = nullptr;
00216         UpdateContentUI();
00217     }
00218
00219     void Scenario2::radioFile_Checked(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00220     {
00221         m_contentType = ContentType::File;
00222         UpdateContentProps(L"");
00223         m_contentStream = nullptr;
00224         UpdateContentUI();
00225     }
00226
00227     void Scenario2::btnPlay_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00228     {
00229         StartDevice();
00230     }
00231
00232     void Scenario2::btnPause_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00233     {
00234         PauseDevice();
00235     }
00236
00237     void Scenario2::btnPlayPause_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00238     {
00239         PlayPauseToggleDevice();
00240     }
00241
00242     void Scenario2::btnStop_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00243     {
00244         StopDevice();
00245     }
00246
00247     void Scenario2::btnFilePicker_Click(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00248     {
00249         OnPickFileAsync();
00250     }
00251
00252 #pragma endregion
00253
00254     // Event callback from WASAPI renderer for changes in device state
00255     fire_and_forget Scenario2::OnDeviceStateChange(IDeviceStateSource const&, SDKTemplate::DeviceStateChangedEventArgs e)
00256     {
00257         auto lifetime = get_strong();
00258
00259         // Handle state specific messages
00260         switch (e.DeviceState())
00261         {
00262         case DeviceState::Initialized:
00263             StartDevice();
00264             m_systemMediaControls.PlaybackStatus(MediaPlaybackStatus::Closed);
00265             break;
00266
00267         case DeviceState::Playing:
00268             rootPage.NotifyUser(L"Playback Started", NotifyType::StatusMessage);
00269             m_systemMediaControls.PlaybackStatus(MediaPlaybackStatus::Playing);
00270             break;
00271
00272         case DeviceState::Paused:
00273             rootPage.NotifyUser(L"Playback Paused", NotifyType::StatusMessage);
00274             m_systemMediaControls.PlaybackStatus(MediaPlaybackStatus::Paused);
00275             break;
00276
00277         case DeviceState::Stopped:
00278             if (m_deviceStateChangeToken)
00279             {
00280                 m_renderer->DeviceStateChanged(std::exchange(m_deviceStateChangeToken, {}));
00281             }
00282             m_renderer = nullptr;
00283
00284             rootPage.NotifyUser(L"Playback Stopped", NotifyType::StatusMessage);
00285             m_systemMediaControls.PlaybackStatus(MediaPlaybackStatus::Stopped);
00286             break;
00287
00288         case DeviceState::Error:
00289             if (m_deviceStateChangeToken)
00290             {
00291                 m_renderer->DeviceStateChanged(std::exchange(m_deviceStateChangeToken, {}));
00292             }
00293             m_renderer = nullptr;
00294
00295             m_systemMediaControls.PlaybackStatus(MediaPlaybackStatus::Closed);
00296
00297             // Specifically handle a couple of known errors
00298             auto error = e.ExtendedError();
00299             switch (error)
00300             {
00301             case AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE:
00302                 rootPage.NotifyUser(L"ERROR: Endpoint Does Not Support HW Offload", NotifyType::ErrorMessage);
00303                 break;
00304
00305             case AUDCLNT_E_RESOURCES_INVALIDATED:
00306                 rootPage.NotifyUser(L"ERROR: Endpoint Lost Access To Resources", NotifyType::ErrorMessage);
00307                 break;
00308
00309             default:
00310                 rootPage.NotifyUser(L"ERROR: " + hresult_error(error).message(), NotifyType::ErrorMessage);
00311                 break;
00312             }
00313         }
00314
00315         // Update Control Buttons
00316         co_await resume_foreground(Dispatcher());
00317         UpdateMediaControlUI(e.DeviceState());
00318     }
00319
00320     //
00321     //  OnPickFileAsync()
00322     //
00323     //  File chooser for MF Source playback.  Retrieves a pointer to IRandomAccessStream
00324     //
00325     fire_and_forget Scenario2::OnPickFileAsync()
00326     {
00327         auto lifetime = get_strong();
00328         FileOpenPicker filePicker;
00329         filePicker.ViewMode(PickerViewMode::List);
00330         filePicker.SuggestedStartLocation(PickerLocationId::MusicLibrary);
00331         filePicker.FileTypeFilter().ReplaceAll({ L".wav", L".mp3", L".wma" });
00332
00333         StorageFile file = co_await filePicker.PickSingleFileAsync();
00334         if (file != nullptr)
00335         {
00336             // Open the stream
00337             IRandomAccessStream stream = co_await file.OpenAsync(FileAccessMode::Read);
00338             if (stream != nullptr)
00339             {
00340                 m_contentStream = stream;
00341                 UpdateContentProps(file.Path());
00342             }
00343         }
00344     }
00345
00346     //
00347     //  OnSetVolume()
00348     //
00349     //  Updates the session volume
00350     //
00351     void Scenario2::OnSetVolume(double volume)
00352     {
00353         if (m_renderer)
00354         {
00355             // Updates the Session volume on the AudioClient
00356             m_renderer->SetVolumeOnSession(volume);
00357         }
00358     }
00359
00360     //
00361     //  InitializeDevice()
00362     //
00363     //  Sets up a new instance of the WASAPI renderer
00364     //
00365     void Scenario2::InitializeDevice()
00366     {
00367         if (m_renderer)
00368         {
00369             // Already initialized.
00370             return;
00371         }
00372
00373         // Create a new WASAPI instance
00374         m_renderer = make_self<WASAPIRenderer>();
00375
00376         // Register for events
00377         m_deviceStateChangeToken = m_renderer->DeviceStateChanged({ get_weak(), &Scenario2::OnDeviceStateChange });
00378
00379         // Configure user based properties
00380
00381         m_renderer->SetContentType(m_contentType);
00382         m_renderer->SetFrequency(sliderFrequency().Value());
00383         m_renderer->SetContentStream(m_contentStream);
00384         m_renderer->SetHWOffload(toggleHWOffload().IsOn());
00385         m_renderer->SetBackgroundAudio(toggleBackgroundAudio().IsOn());
00386         m_renderer->SetRawAudio(m_deviceSupportsRawMode && toggleRawAudio().IsOn());
00387
00388         int BufferSize = 0;
00389         swscanf_s(txtHWBuffer().Text().c_str(), L"%d", &BufferSize);
00390         m_renderer->SetBufferDuration(static_cast<REFERENCE_TIME>(BufferSize));
00391
00392         // Selects the Default Audio Device
00393         m_renderer->AsyncInitializeAudioDevice();
00394
00395         // Set the initial volume.
00396         OnSetVolume(sliderVolume().Value());
00397     }
00398
00399     void Scenario2::StartDevice()
00400     {
00401         if (m_renderer == nullptr)
00402         {
00403             // Call from main UI thread
00404             InitializeDevice();
00405         }
00406         else
00407         {
00408             // Starts a work item to begin playback, likely in the paused state
00409             m_renderer->StartPlayback();
00410         }
00411     }
00412
00413     void Scenario2::StopDevice()
00414     {
00415         if (m_renderer)
00416         {
00417             // Set the event to stop playback
00418             m_renderer->StopPlaybackAsync();
00419         }
00420     }
00421
00422     void Scenario2::PauseDevice()
00423     {
00424         if (m_renderer)
00425         {
00426             if (m_renderer->DeviceState() == DeviceState::Playing)
00427             {
00428                 // Starts a work item to pause playback
00429                 m_renderer->PausePlaybackAsync();
00430             }
00431         }
00432     }
00433
00434     void Scenario2::PlayPauseToggleDevice()
00435     {
00436         if (m_renderer)
00437         {
00438             DeviceState deviceState = m_renderer->DeviceState();
00439
00440             if (deviceState == DeviceState::Playing)
00441             {
00442                 // Starts a work item to pause playback
00443                 m_renderer->PausePlaybackAsync();
00444             }
00445             else if (deviceState == DeviceState::Paused)
00446             {
00447                 // Starts a work item to pause playback
00448                 m_renderer->StartPlayback();
00449             }
00450         }
00451         else
00452         {
00453             StartDevice();
00454         }
00455     }
00456
00457     fire_and_forget Scenario2::MediaButtonPressed(SystemMediaTransportControls const&, SystemMediaTransportControlsButtonPressedEventArgs e)
00458     {
00459         auto lifetime = get_strong();
00460         co_await resume_foreground(Dispatcher());
00461
00462         switch (e.Button())
00463         {
00464         case SystemMediaTransportControlsButton::Play:
00465             StartDevice();
00466             break;
00467
00468         case SystemMediaTransportControlsButton::Pause:
00469             PauseDevice();
00470             break;
00471
00472         case SystemMediaTransportControlsButton::Stop:
00473             StopDevice();
00474             break;
00475
00476         default:
00477             break;
00478         }
00479     }
00480 }
Generated on Fri Nov 15 2024 22:19:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cs/Scenario1_AdvertiserCreate.xaml.cs Source File

  • WiFiDirectServices
  • cs

Scenario1_AdvertiserCreate.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Globalization;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018 using Windows.Devices.WiFiDirect.Services;
00019
00020 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00021
00022 namespace SDKTemplate
00023 {
00024     namespace WiFiDirectServices
00025     {
00026         /// <summary>
00027         /// UI that exposes properties to begin advertising a Wi-Fi Direct Service.
00028         /// A normal application would hide this implementation and just provide a way to begin advertising a service
00029         ///
00030         /// Most of the actual logic for Wi-Fi Direct Services is in WiFiDirectServicesManager.cs and WiFiDirectServicesWrappers.cs
00031         /// </summary>
00032         public sealed partial class Scenario1 : Page
00033         {
00034             private MainPage rootPage;
00035
00036             public Scenario1()
00037             {
00038                 this.InitializeComponent();
00039             }
00040
00041             protected override void OnNavigatedTo(NavigationEventArgs e)
00042             {
00043                 rootPage = MainPage.Current;
00044
00045                 ResetFields();
00046                 WiFiDirectServiceManager.Instance.Scenario1 = this;
00047             }
00048
00049             protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00050             {
00051                 WiFiDirectServiceManager.Instance.Scenario1 = null;
00052             }
00053
00054             private void ResetFields()
00055             {
00056                 ServiceName.Text = "";
00057                 AutoAccept.IsChecked = true;
00058                 PreferGO.IsChecked = true;
00059                 Status.SelectedIndex = 0;
00060                 CustomStatus.Text = "";
00061                 ConfigMethodDefault.IsChecked = true;
00062                 ConfigMethodDispaly.IsChecked = true;
00063                 ConfigMethodDisplayPin.Text = "";
00064                 ConfigMethodKeypad.IsChecked = false;
00065                 DeferredSessionInfo.Text = "";
00066                 ServiceInformation.Text = "";
00067                 ServicePrefixList.Items.Clear();
00068             }
00069
00070             private void CreateAdvertiser_Click(object sender, RoutedEventArgs e)
00071             {
00072                 rootPage.NotifyUser("Creating Advertisement", NotifyType.StatusMessage);
00073
00074                 try
00075                 {
00076                     List<WiFiDirectServiceConfigurationMethod> configMethods = new List<WiFiDirectServiceConfigurationMethod>();
00077
00078                     if (ConfigMethodDispaly.IsChecked ?? false)
00079                     {
00080                         configMethods.Add(WiFiDirectServiceConfigurationMethod.PinDisplay);
00081                     }
00082                     if (ConfigMethodKeypad.IsChecked ?? false)
00083                     {
00084                         configMethods.Add(WiFiDirectServiceConfigurationMethod.PinEntry);
00085                     }
00086                     if (ConfigMethodDefault.IsChecked ?? false)
00087                     {
00088                         configMethods.Add(WiFiDirectServiceConfigurationMethod.Default);
00089                     }
00090
00091                     WiFiDirectServiceStatus status = WiFiDirectServiceStatus.Available;
00092                     if (Status.SelectedItem.ToString() == "Busy")
00093                     {
00094                         status = WiFiDirectServiceStatus.Busy;
00095                     }
00096                     else if (Status.SelectedItem.ToString() == "Custom")
00097                     {
00098                         status = WiFiDirectServiceStatus.Custom;
00099                     }
00100
00101                     uint customStatus = 0;
00102                     if (CustomStatus.Text.Length > 0)
00103                     {
00104                         uint temp = 0;
00105                         if (uint.TryParse(CustomStatus.Text, out temp))
00106                         {
00107                             customStatus = temp;
00108                         }
00109                     }
00110
00111                     // NOTE: Each prefix published will be handled by the driver so there are limitations
00112                     // to how many prefixes can be supported. In general, apps should only publish prefixes
00113                     // of the service name that are required for discovery
00114                     // Typically, this would be something like "com.example.games" for a service called "com.example.games.foobar"
00115                     IList<String> prefixList = new List<String>();
00116                     foreach (var prefix in ServicePrefixList.Items)
00117                     {
00118                         // NOTE: these must be actual prefixes of the service name
00119                         // Publication will fail if they are not
00120                         prefixList.Add((string)prefix);
00121                     }
00122
00123                     WiFiDirectServiceManager.Instance.StartAdvertisement(
00124                         ServiceName.Text,
00125                         AutoAccept.IsChecked ?? false,
00126                         PreferGO.IsChecked ?? false,
00127                         ConfigMethodDisplayPin.Text,
00128                         configMethods,
00129                         status,
00130                         customStatus,
00131                         ServiceInformation.Text,
00132                         DeferredSessionInfo.Text,
00133                         prefixList
00134                         );
00135
00136                     ResetFields();
00137
00138                     // Force navigation to the next page for smoother experience
00139                     rootPage.GoToScenario(1);
00140                 }
00141                 catch (Exception ex)
00142                 {
00143                     rootPage.NotifyUser(String.Format(CultureInfo.InvariantCulture, "Failed to start service: {0}", ex.Message), NotifyType.ErrorMessage);
00144                 }
00145             }
00146
00147             private void RemovePrefix_Click(object sender, RoutedEventArgs e)
00148             {
00149                 foreach (var prefix in ServicePrefixList.SelectedItems)
00150                 {
00151                     ServicePrefixList.Items.Remove(prefix);
00152                 }
00153             }
00154
00155             private void AddPrefix_Click(object sender, RoutedEventArgs e)
00156             {
00157                 if (NewPrefix.Text != "")
00158                 {
00159                     ServicePrefixList.Items.Add(NewPrefix.Text);
00160                     NewPrefix.Text = "";
00161                 }
00162             }
00163         }
00164     }
00165 }
Generated on Fri Nov 15 2024 22:22:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_XmlReader Member List

This is the complete list of members for Scenario1_XmlReader, including all inherited members.
ReadAttributes(std::wostream &result, com_ptr< IXmlReader > const &reader) | Scenario1_XmlReader | [private, static]
ReadXml(std::wostream &result, com_ptr< IStream > const &readStream) | Scenario1_XmlReader | [private, static]
ReadXmlClick(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1_XmlReader |
Scenario1_XmlReader() | Scenario1_XmlReader |
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/AudioCapturePermissions.cpp Source File

  • SpeechRecognitionAndSynthesis
  • cpp

AudioCapturePermissions.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "AudioCapturePermissions.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Concurrency;
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Media::Capture;
00020
00021 /// <summary>
00022 /// On desktop/tablet systems, users are prompted to give permission to use capture devices on a
00023 /// per-app basis. Along with declaring the microphone DeviceCapability in the package manifest,
00024 /// this method tests the privacy setting for microphone access for this application.
00025 /// Note that this only checks the Settings->Privacy->Microphone setting, it does not handle
00026 /// the Cortana/Dictation privacy check, however (Under Settings->Privacy->Speech, Inking and Typing).
00027 ///
00028 /// Developers should ideally perform a check like this every time their app gains focus, in order to
00029 /// check if the user has changed the setting while the app was suspended or not in focus.
00030 /// </summary>
00031 /// <returns>true if the microphone can be accessed without any permissions problems.</returns>
00032 IAsyncOperation<bool>^  AudioCapturePermissions::RequestMicrophonePermissionAsync()
00033 {
00034     return create_async([]()
00035     {
00036     try
00037     {
00038       // Request access to the microphone only, to limit the number of capabilities we need
00039       // to request in the package manifest.
00040       MediaCaptureInitializationSettings^ settings = ref new MediaCaptureInitializationSettings();
00041       settings->StreamingCaptureMode = StreamingCaptureMode::Audio;
00042       settings->MediaCategory = MediaCategory::Speech;
00043       MediaCapture^ capture = ref new MediaCapture();
00044
00045       return create_task(capture->InitializeAsync(settings))
00046         .then([](task<void> previousTask) -> bool
00047       {
00048         try
00049         {
00050           previousTask.get();
00051         }
00052         catch (AccessDeniedException^)
00053         {
00054           // The user has turned off access to the microphone. If this occurs, we should show an error, or disable
00055           // functionality within the app to ensure that further exceptions aren't generated when
00056           // recognition is attempted.
00057           return false;
00058         }
00059         catch (Exception^ exception)
00060         {
00061           // This can be replicated by using remote desktop to a system, but not redirecting the microphone input.
00062           // Can also occur if using the virtual machine console tool to access a VM instead of using remote desktop.
00063           if (exception->HResult == AudioCapturePermissions::NoCaptureDevicesHResult)
00064           {
00065             auto messageDialog = ref new Windows::UI::Popups::MessageDialog("No Audio Capture devices are present on this system.");
00066             create_task(messageDialog->ShowAsync());
00067             return false;
00068           }
00069
00070           throw;
00071         }
00072         return true;
00073       });
00074     }
00075     catch (Platform::ClassNotRegisteredException^ ex)
00076     {
00077       // If media player components are unavailable (eg, on an N SKU of windows), we may
00078       // get ClassNotRegisteredException when trying to check if we have permission to use
00079       // the microphone.
00080       auto messageDialog = ref new Windows::UI::Popups::MessageDialog("Media Player Components unavailable.");
00081       create_task(messageDialog->ShowAsync());
00082       return create_task([] {return false; });
00083     }
00084     });
00085
00086 }
Generated on Fri Nov 15 2024 22:21:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cs/SampleConfiguration.cs Source File

  • ResizeAppView
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Resize app view";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Resizing the view", ClassType=typeof(Scenario1_Basic)},
00025             new Scenario() { Title="Launching at a custom size", ClassType=typeof(Scenario2_Launch)},
00026         };
00027     }
00028
00029     public class Scenario
00030     {
00031         public string Title { get; set; }
00032         public Type ClassType { get; set; }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: InkAnalysis/cs/Scenario2.xaml.cs Source File

  • InkAnalysis
  • cs

Scenario2.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using System;
00012 using System.Collections.Generic;
00013 using Windows.Foundation;
00014 using Windows.UI.Core;
00015 using Windows.UI.Input.Inking;
00016 using Windows.UI.Input.Inking.Analysis;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Input;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021 using Windows.UI.Xaml.Shapes;
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// This scenario demostrates text recognition with InkAnalyzer.
00027     /// </summary>
00028     public sealed partial class Scenario2 : Page
00029     {
00030         private MainPage rootPage = MainPage.Current;
00031         InkPresenter inkPresenter;
00032         InkAnalyzer inkAnalyzer;
00033         InkAnalysisParagraph paragraphSelected;
00034         DispatcherTimer dispatcherTimer;
00035
00036         public Scenario2()
00037         {
00038             this.InitializeComponent();
00039
00040             inkPresenter = inkCanvas.InkPresenter;
00041             inkPresenter.StrokesCollected += InkPresenter_StrokesCollected;
00042             inkPresenter.StrokesErased += InkPresenter_StrokesErased;
00043             inkPresenter.StrokeInput.StrokeStarted += StrokeInput_StrokeStarted;
00044
00045             // We exclude CoreInputDeviceTypes.Touch because we use touch to select paragraphs.
00046             inkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Pen | CoreInputDeviceTypes.Mouse;
00047
00048             inkCanvas.Tapped += InkCanvas_Tapped;
00049             inkCanvas.DoubleTapped += InkCanvas_DoubleTapped;
00050
00051             inkAnalyzer = new InkAnalyzer();
00052             paragraphSelected = null;
00053
00054             dispatcherTimer = new DispatcherTimer();
00055             dispatcherTimer.Tick += DispatcherTimer_Tick;
00056
00057             // We perform analysis when there has been a change to the
00058             // ink presenter and the user has been idle for 1 second.
00059             dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
00060         }
00061
00062         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00063         {
00064             dispatcherTimer.Stop();
00065         }
00066
00067         private void InkPresenter_StrokesErased(InkPresenter sender, InkStrokesErasedEventArgs args)
00068         {
00069             dispatcherTimer.Stop();
00070             foreach (var stroke in args.Strokes)
00071             {
00072                 inkAnalyzer.RemoveDataForStroke(stroke.Id);
00073             }
00074             dispatcherTimer.Start();
00075         }
00076
00077         private void StrokeInput_StrokeStarted(InkStrokeInput sender, Windows.UI.Core.PointerEventArgs args)
00078         {
00079             // Don't perform analysis while a stroke is in progress.
00080             dispatcherTimer.Stop();
00081         }
00082
00083         private void InkPresenter_StrokesCollected(InkPresenter sender, InkStrokesCollectedEventArgs args)
00084         {
00085             dispatcherTimer.Stop();
00086             inkAnalyzer.AddDataForStrokes(args.Strokes);
00087             dispatcherTimer.Start();
00088         }
00089
00090         private async void DispatcherTimer_Tick(object sender, object e)
00091         {
00092             dispatcherTimer.Stop();
00093             if (!inkAnalyzer.IsAnalyzing)
00094             {
00095                 var result = await inkAnalyzer.AnalyzeAsync();
00096             }
00097             else
00098             {
00099                 // Ink analyzer is busy. Wait a while and try again.
00100                 dispatcherTimer.Start();
00101             }
00102         }
00103
00104         private void ClearButton_Click(object sender, RoutedEventArgs e)
00105         {
00106             // Don't run analysis when there is nothing to analyze.
00107             dispatcherTimer.Stop();
00108
00109             inkPresenter.StrokeContainer.Clear();
00110             inkAnalyzer.ClearDataForAllStrokes();
00111             canvas.Children.Clear();
00112             canvas.Children.Add(SelectionRect);
00113             SelectionRect.Visibility = Visibility.Collapsed;
00114         }
00115
00116         private void InkCanvas_Tapped(object sender, TappedRoutedEventArgs e)
00117         {
00118             var position = e.GetPosition(inkCanvas);
00119
00120             var paragraph = FindHitParagraph(position);
00121             if (paragraph == null)
00122             {
00123                 // Did not tap on a paragraph.
00124                 SelectionRect.Visibility = Visibility.Collapsed;
00125             }
00126             else
00127             {
00128                 // Show the selection rect at the paragraph's bounding rect.
00129                 Rect rect = paragraph.BoundingRect;
00130                 SelectionRect.Width = rect.Width;
00131                 SelectionRect.Height = rect.Height;
00132                 Canvas.SetLeft(SelectionRect, rect.Left);
00133                 Canvas.SetTop(SelectionRect, rect.Top);
00134
00135                 SelectionRect.Visibility = Visibility.Visible;
00136             }
00137             paragraphSelected = paragraph;
00138         }
00139
00140         private void InkCanvas_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
00141         {
00142             // Convert the selected paragraph or list item
00143             if (paragraphSelected != null)
00144             {
00145                 Rect rect = paragraphSelected.BoundingRect;
00146                 var text = ExtractTextFromParagraph(paragraphSelected);
00147
00148                 if ((rect.X > 0) && (rect.Y > 0) && (text != string.Empty))
00149                 {
00150                     // Create text box with recognized text
00151                     var textBlock = new TextBlock();
00152                     textBlock.Text = text;
00153                     textBlock.MaxWidth = rect.Width;
00154                     textBlock.MaxHeight = rect.Height;
00155                     Canvas.SetLeft(textBlock, rect.X);
00156                     Canvas.SetTop(textBlock, rect.Y);
00157
00158                     // Remove strokes from InkPresenter
00159                     IReadOnlyList<uint> strokeIds = paragraphSelected.GetStrokeIds();
00160                     foreach (var strokeId in strokeIds)
00161                     {
00162                         var stroke = inkPresenter.StrokeContainer.GetStrokeById(strokeId);
00163                         stroke.Selected = true;
00164                     }
00165                     inkPresenter.StrokeContainer.DeleteSelected();
00166
00167                     // Remove strokes from InkAnalyzer
00168                     inkAnalyzer.RemoveDataForStrokes(strokeIds);
00169
00170                     // Hide the SelectionRect
00171                     SelectionRect.Visibility = Visibility.Collapsed;
00172
00173                     canvas.Children.Add(textBlock);
00174                     paragraphSelected = null;
00175                 }
00176             }
00177         }
00178
00179         private string ExtractTextFromParagraph(InkAnalysisParagraph paragraph)
00180         {
00181             // The paragraph.RecognizedText property also returns the text,
00182             // but manually walking through the lines allows us to preserve
00183             // line breaks.
00184             var lines = new List<string>();
00185             foreach (var child in paragraph.Children)
00186             {
00187                 if (child.Kind == InkAnalysisNodeKind.Line)
00188                 {
00189                     var line = (InkAnalysisLine)child;
00190                     lines.Add(line.RecognizedText);
00191                 }
00192                 else if (child.Kind == InkAnalysisNodeKind.ListItem)
00193                 {
00194                     var listItem = (InkAnalysisListItem)child;
00195                     lines.Add(listItem.RecognizedText);
00196                 }
00197             }
00198             return String.Join("\n", lines);
00199         }
00200
00201         private InkAnalysisParagraph FindHitParagraph(Point pt)
00202         {
00203             var paragraphs = inkAnalyzer.AnalysisRoot.FindNodes(InkAnalysisNodeKind.Paragraph);
00204             foreach (var paragraph in paragraphs)
00205             {
00206                 // To support ink written with angle, RotatedBoundingRect should be used in hit testing.
00207                 if (RectHelper.Contains(paragraph.BoundingRect, pt))
00208                 {
00209                     return (InkAnalysisParagraph)paragraph;
00210                 }
00211             }
00212             return null;
00213         }
00214    }
00215 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSuggestion/cpp/Scenario1_Conversion.xaml.cpp Source File

  • TextSuggestion
  • cpp

Scenario1_Conversion.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario1_Conversion.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Platform::Collections;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::UI::Xaml;
00013 using namespace Windows::UI::Xaml::Controls;
00014 using namespace Windows::UI::Xaml::Controls::Primitives;
00015 using namespace Windows::UI::Xaml::Data;
00016 using namespace Windows::UI::Xaml::Input;
00017 using namespace Windows::UI::Xaml::Media;
00018 using namespace Windows::UI::Xaml::Navigation;
00019
00020 Scenario1_Conversion::Scenario1_Conversion() : rootPage(MainPage::Current)
00021 {
00022     InitializeComponent();
00023 }
00024
00025 /// <summary>
00026 /// This is the click handler for the 'Create Generator' button.
00027 /// When this button is activated, this method will create a text conversion
00028 /// generator with the language tag provided by the user. The generator will
00029 /// try to resolve the language tag and check if the language is supported
00030 /// and installed.
00031 /// </summary>
00032 /// <param name="sender">The object that raised the event.</param>
00033 /// <param name="e">Event data that describes the click action on the button.</param>
00034 void Scenario1_Conversion::CreateGeneratorButton_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00035 {
00036     String^ notifyText = ref new String();
00037
00038     // Try to parse the language and create generator accordingly.
00039     generator = ref new Windows::Data::Text::TextConversionGenerator(langTag->Text);
00040
00041     // Only allow generator operation when the language is available and installed.
00042     if (generator == nullptr)
00043     {
00044         if (generatorOperationArea != nullptr)
00045         {
00046             generatorOperationArea->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00047         }
00048
00049         notifyText = "Successfully instantiated a generator.";
00050         MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00051     }
00052     else if (generator->ResolvedLanguage == "und")
00053     {
00054         if (generatorOperationArea != nullptr)
00055         {
00056             generatorOperationArea->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00057         }
00058
00059         notifyText = "Unsupported language.";
00060         MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00061     }
00062     else if (generator->LanguageAvailableButNotInstalled)
00063     {
00064         if (generatorOperationArea != nullptr)
00065         {
00066             generatorOperationArea->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00067         }
00068
00069         notifyText = "Language available but not installed.";
00070         MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00071     }
00072     else
00073     {
00074         if (generatorOperationArea != nullptr)
00075         {
00076             generatorOperationArea->Visibility = Windows::UI::Xaml::Visibility::Visible;
00077         }
00078
00079         notifyText = "Successfully instantiated a generator.";
00080         MainPage::Current->NotifyUser(notifyText, NotifyType::StatusMessage);
00081     }
00082 }
00083
00084 /// <summary>
00085 /// Selecting the generator method to use.
00086 /// User can either specify the max candidate number to get, or use the default value.
00087 /// </summary>
00088 /// <param name="sender">The object that raised the event.</param>
00089 /// <param name="e">Event data that describes the click action on the button.</param>
00090 void Scenario1_Conversion::Methods_SelectionChanged(Platform::Object^ sender, SelectionChangedEventArgs^ e)
00091 {
00092     ComboBoxItem^ selectedItem = dynamic_cast<ComboBoxItem^>(methods->SelectedItem);
00093
00094     if (maxCandidatesArea != nullptr)
00095     {
00096         // Only show the candidate number input control when user chooses to specify the number.
00097         if ((selectedItem->Tag != nullptr) && selectedItem->Tag->ToString()->Equals("needMaxCount"))
00098         {
00099             maxCandidatesArea->Visibility = Windows::UI::Xaml::Visibility::Visible;
00100         }
00101         else
00102         {
00103             maxCandidatesArea->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00104         }
00105     }
00106 }
00107
00108 /// <summary>
00109 /// This is the click handler for the 'Execute' button.
00110 /// When this button is activated, the text conversion generator will get
00111 /// the conversion candidates for given input string and language tag, then
00112 /// print them in result column.
00113 /// Using 'concurrency::create_task' to create an asynchronous task and
00114 /// handle the result when it completes.
00115 /// </summary>
00116 /// <param name="sender">The object that raised the event.</param>
00117 /// <param name="e">Event data that describes the click action on the button.</param>
00118 void Scenario1_Conversion::Execute_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00119 {
00120     // Clean up result column.
00121     resultView->ItemsSource = nullptr;
00122
00123     // Clean notification area.
00124     String^ notifyText = ref new String();
00125     MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00126
00127     auto input = Input->Text;
00128
00129     ComboBoxItem^ selectedItem = dynamic_cast<ComboBoxItem^>(methods->SelectedItem);
00130
00131     if ((generator != nullptr) && (selectedItem != nullptr) && !input->IsEmpty())
00132     {
00133         // Specify the candidate number to get.
00134         if ((selectedItem->Tag != nullptr) && selectedItem->Tag->ToString()->Equals("needMaxCount"))
00135         {
00136             int maxCandidateCount = _wtoi(maxCandidates->Text->Data());
00137
00138             if (maxCandidateCount > 0)
00139             {
00140                 // Call the API with max candidate number we expect, and list the result when there are any candidates.
00141                 concurrency::create_task(generator->GetCandidatesAsync(input, static_cast<UINT>(maxCandidateCount))).then([this](IVectorView<String^>^ candidates)
00142                 {
00143                     DisplayMultipleCandidates(candidates);
00144                 });
00145             }
00146             else
00147             {
00148                 MainPage::Current->NotifyUser("Not a valid candidate number. Expecting positive integer.", NotifyType::ErrorMessage);
00149             }
00150         }
00151         else
00152         {
00153             // Call the API with default candidate number, and list the result when there are any candidates.
00154             concurrency::create_task(generator->GetCandidatesAsync(input)).then([this](IVectorView<String^>^ candidates)
00155             {
00156                 DisplayMultipleCandidates(candidates);
00157             });
00158         }
00159     }
00160 }
00161
00162 /// <summary>
00163 /// Helper method for displaying conversion candidates.
00164 /// </summary>
00165 /// <param name="result">The converison candidates we got from text conversion generator.</param>
00166 void Scenario1_Conversion::DisplayMultipleCandidates(IVectorView<String^>^ candidates)
00167 {
00168     Vector<String^>^ itemsSource = ref new Vector<String^>();
00169     for (unsigned int i = 0; i < candidates->Size; i++)
00170     {
00171         itemsSource->Append(candidates->GetAt(i));
00172     }
00173
00174     resultView->ItemsSource = itemsSource;
00175
00176     if (resultView->Items->Size == 0)
00177     {
00178         MainPage::Current->NotifyUser("No candidates.", NotifyType::StatusMessage);
00179     }
00180 }
00181
Generated on Fri Nov 15 2024 22:21:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/ShareDelayRenderedFiles.xaml.cpp Source File

  • ShareSource
  • cpp

ShareDelayRenderedFiles.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ShareDelayRenderedFiles.xaml.cpp
00014 // Implementation of the ShareDelayRenderedFiles class
00015 //
00016
00017 #include "pch.h"
00018 #include "ShareDelayRenderedFiles.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace concurrency;
00023 using namespace Platform;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Graphics::Imaging;
00026 using namespace Windows::Storage;
00027 using namespace Windows::Storage::Streams;
00028 using namespace Windows::Storage::Pickers;
00029 using namespace Windows::UI::Xaml;
00030 using namespace Windows::UI::Xaml::Media::Imaging;
00031 using namespace Windows::ApplicationModel::DataTransfer;
00032
00033 ShareDelayRenderedFiles::ShareDelayRenderedFiles()
00034 {
00035     InitializeComponent();
00036 }
00037
00038 bool ShareDelayRenderedFiles::GetShareContent(DataRequest^ request)
00039 {
00040     bool succeeded = false;
00041
00042     if (imageFile != nullptr)
00043     {
00044         auto requestData = request->Data;
00045         requestData->Properties->Title = "Delay rendered image";
00046         requestData->Properties->Description = "Resized image from the Share Source sample";
00047         requestData->Properties->ContentSourceApplicationLink = ApplicationLink;
00048         requestData->Properties->Thumbnail = RandomAccessStreamReference::CreateFromFile(imageFile);
00049         requestData->SetDataProvider(StandardDataFormats::Bitmap, ref new DataProviderHandler(this, &ShareDelayRenderedFiles::OnDeferredImageRequestedHandler));
00050         succeeded = true;
00051     }
00052     else
00053     {
00054         request->FailWithDisplayText("Select an image you would like to share and try again.");
00055     }
00056     return succeeded;
00057 }
00058
00059 void ShareDelayRenderedFiles::OnDeferredImageRequestedHandler(DataProviderRequest^ request)
00060 {
00061     // In this delegate we provide updated Bitmap data using delayed rendering.
00062
00063     if (imageFile != nullptr)
00064     {
00065         // If the delegate is calling any asynchronous operations it needs to acquire the deferral first. This lets the
00066         // system know that you are performing some operations that might take a little longer and that the call to
00067         // SetData could happen after the delegate returns. Once you acquired the deferral object you must call Complete
00068         // on it after your final call to SetData.
00069         auto deferral = request->GetDeferral();
00070         auto inMemoryStream = ref new InMemoryRandomAccessStream();
00071
00072         // Use a reference-counted pointer to store the requested dimensions across function calls.
00073         std::shared_ptr<Size> newSize(new Size);
00074
00075         create_task(imageFile->OpenAsync(FileAccessMode::Read)).then(
00076             [this](IRandomAccessStream^ stream) -> IAsyncOperation<BitmapDecoder^>^
00077         {
00078             return BitmapDecoder::CreateAsync(stream);
00079         }).then([this, inMemoryStream, newSize](BitmapDecoder^ imageDecoder) -> IAsyncOperation<BitmapEncoder^>^
00080         {
00081             newSize.get()->Height = imageDecoder->OrientedPixelHeight * 0.5f;
00082             newSize.get()->Width = imageDecoder->OrientedPixelWidth * 0.5f;
00083             return BitmapEncoder::CreateForTranscodingAsync(inMemoryStream, imageDecoder);
00084         }).then([this, newSize](BitmapEncoder^ imageEncoder) -> IAsyncAction^
00085         {
00086             imageEncoder->BitmapTransform->ScaledWidth = safe_cast<unsigned int>(newSize.get()->Width);
00087             imageEncoder->BitmapTransform->ScaledHeight = safe_cast<unsigned int>(newSize.get()->Height);
00088             return imageEncoder->FlushAsync();
00089         }).then([this, deferral, request, inMemoryStream](task<void> newTask)
00090         {
00091             // Forces any exceptions from previous operations to get thrown here.
00092             // That way, we can ensure that the deferral completed method always gets called.
00093             try
00094             {
00095                 newTask.get();
00096                 request->SetData(RandomAccessStreamReference::CreateFromStream(inMemoryStream));
00097             }
00098             catch (Exception^)
00099             {
00100                 deferral->Complete();
00101                 throw;
00102             }
00103
00104             // If the operation completed successfully, end the deferral.
00105             deferral->Complete();
00106         });
00107     }
00108 }
00109
00110 void ShareDelayRenderedFiles::SelectImageButton_Click(Object^ sender, RoutedEventArgs^ e)
00111 {
00112     auto imagePicker = ref new FileOpenPicker();
00113     imagePicker->ViewMode = PickerViewMode::Thumbnail;
00114     imagePicker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00115     imagePicker->FileTypeFilter->Append(".jpg");
00116     imagePicker->FileTypeFilter->Append(".png");
00117     imagePicker->FileTypeFilter->Append(".bmp");
00118     imagePicker->FileTypeFilter->Append(".gif");
00119     imagePicker->FileTypeFilter->Append(".tif");
00120
00121     create_task(imagePicker->PickSingleFileAsync()).then([this](StorageFile^ pickedFile)
00122     {
00123         if (pickedFile != nullptr)
00124         {
00125             imageFile = pickedFile;
00126
00127             // Display the image in the UI.
00128             create_task(pickedFile->OpenAsync(FileAccessMode::Read)).then([this](IRandomAccessStream^ displayStream)
00129             {
00130                 auto bitmapImage = ref new BitmapImage();
00131                 bitmapImage->SetSource(displayStream);
00132                 ImageHolder->Source = bitmapImage;
00133             });
00134             MainPage::Current->NotifyUser("Selected " + imageFile->Name +".", NotifyType::StatusMessage);
00135
00136             ShareStep->Visibility = Windows::UI::Xaml::Visibility::Visible;
00137         }
00138     });
00139 }
Generated on Fri Nov 15 2024 22:21:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/Scenario4_ChangeAdminKey.cpp Source File

  • SmartCard
  • cppwinrt

Scenario4_ChangeAdminKey.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario4_ChangeAdminKey.h"
00014 #include "Scenario4_ChangeAdminKey.g.cpp"
00015
00016 namespace winrt
00017 {
00018     using namespace Windows::Foundation;
00019     using namespace Windows::Storage::Streams;
00020     using namespace Windows::Devices::SmartCards;
00021     using namespace Windows::Security::Cryptography;
00022     using namespace Windows::UI::Xaml;
00023     using namespace Windows::UI::Xaml::Controls;
00024 }
00025
00026 namespace winrt::SDKTemplate::implementation
00027 {
00028     Scenario4_ChangeAdminKey::Scenario4_ChangeAdminKey()
00029     {
00030         InitializeComponent();
00031     }
00032
00033     /// <summary>
00034     /// Click handler for the 'ChangeAdminKey' button.
00035     /// </summary>
00036     /// <param name="sender"></param>
00037     fire_and_forget Scenario4_ChangeAdminKey::ChangeAdminKey_Click(IInspectable const& sender, RoutedEventArgs const&)
00038     {
00039         auto lifetime = get_strong();
00040
00041         if (!ValidateTPMSmartCard())
00042         {
00043             m_rootPage.NotifyUser(L"Use Scenario One to create a TPM virtual smart card.", NotifyType::ErrorMessage);
00044             co_return;
00045         }
00046
00047         auto b = sender.as<Windows::UI::Xaml::Controls::Button>();
00048         b.IsEnabled(false);
00049
00050         try
00051         {
00052             IBuffer newadminkey = CryptographicBuffer::GenerateRandom(ADMIN_KEY_LENGTH_IN_BYTES);
00053
00054             SmartCard card = co_await GetSmartCardAsync();
00055             SmartCardProvisioning provisioning = co_await SmartCardProvisioning::FromSmartCardAsync(card);
00056
00057             m_rootPage.NotifyUser(L"Changing smart card admin key...", NotifyType::StatusMessage);
00058
00059             // We rely on this object's destructor to clean up the context.
00060             SmartCardChallengeContext context = co_await provisioning.GetChallengeContextAsync();
00061
00062             IBuffer response = CalculateChallengeResponse(context.Challenge(), GetAdminKey());
00063             co_await context.ChangeAdministrativeKeyAsync(response, newadminkey);
00064             SetAdminKey(newadminkey);
00065
00066             m_rootPage.NotifyUser(L"Smart card change admin key operation completed.", NotifyType::StatusMessage);
00067             // context destructed here
00068         }
00069         catch (hresult_error const& ex)
00070         {
00071             m_rootPage.NotifyUser(L"Changing smart card admin key operation failed with exception: " + ex.message(), NotifyType::ErrorMessage);
00072         }
00073
00074         b.IsEnabled(false);
00075     }
00076
00077 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSegmentation/cpp/SampleConfiguration.cpp Source File

  • TextSegmentation
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Extract Text Segments", "SDKTemplate.Scenario1_ExtractTextSegments" },
00012     { "Get Current Text Segment From Index", "SDKTemplate.Scenario2_GetCurrentTextSegmentFromIndex" }
00013 };
Generated on Fri Nov 15 2024 22:17:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cs/AdventureWorks/Common/DateTimeOffsetConverter.cs Source File

  • CortanaVoiceCommand
  • cs
  • AdventureWorks
  • Common

DateTimeOffsetConverter.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017 using Windows.UI.Xaml.Data;
00018
00019 namespace AdventureWorks.Common
00020 {
00021     /// <summary>
00022     /// Convert a DateTime to a DateTimeOffset for use by a DatePicker, and back
00023     /// to allow for two-day data-binding.
00024     /// </summary>
00025     public class DateTimeOffsetConverter : IValueConverter
00026     {
00027         /// <summary>
00028         /// Convert a DateTime to a DateTimeOffset.
00029         /// </summary>
00030         /// <param name="value">The DateTime to convert</param>
00031         /// <param name="targetType">Ignored.</param>
00032         /// <param name="parameter">Ignored.</param>
00033         /// <param name="language">Ignored.</param>
00034         /// <returns></returns>
00035         public object Convert(object value, Type targetType, object parameter, string language)
00036         {
00037             try
00038             {
00039                 if(value == null)
00040                 {
00041                     return "";
00042                 }
00043
00044                 DateTime date = (DateTime)value;
00045                 return string.Format(
00046                     "{0:dddd MMMM dd yyyy}",
00047                     date);
00048             }
00049             catch (Exception)
00050             {
00051                 return "";
00052             }
00053         }
00054
00055         /// <summary>
00056         /// Convert a DateTimeOffset to a DateTime.
00057         /// </summary>
00058         /// <param name="value">DateTimeOffset to convert.</param>
00059         /// <param name="targetType">Ignored.</param>
00060         /// <param name="parameter">Ignored.</param>
00061         /// <param name="language">Ignored.</param>
00062         /// <returns></returns>
00063         public object ConvertBack(object value, Type targetType, object parameter, string language)
00064         {
00065             try
00066             {
00067                 string dateText = (string)value;
00068                 DateTime date;
00069                 if (DateTime.TryParse(dateText, out date))
00070                 {
00071                     return date;
00072                 }
00073
00074                 return null;
00075             }
00076             catch (Exception)
00077             {
00078                 return null;
00079             }
00080
00081         }
00082     }
00083 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCustomMediaTransportControls/cs/CustomMediaTransportControls.cs Source File

  • XamlCustomMediaTransportControls
  • cs

CustomMediaTransportControls.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using Windows.UI.Xaml;
00007 using Windows.UI.Xaml.Controls;
00008 using Windows.UI.Xaml.Controls.Primitives;
00009 using Windows.UI.Xaml.Data;
00010 using Windows.UI.Xaml.Documents;
00011 using Windows.UI.Xaml.Input;
00012 using Windows.UI.Xaml.Media;
00013
00014 namespace CustomMediaTransportControls
00015 {
00016     public sealed class CustomMediaTransportControls : MediaTransportControls
00017     {
00018         public event EventHandler<EventArgs> Liked;
00019
00020         public CustomMediaTransportControls()
00021         {
00022             this.DefaultStyleKey = typeof(CustomMediaTransportControls);
00023         }
00024
00025         protected override void OnApplyTemplate()
00026         {
00027             // This is where you would get your custom button and create an event handler for its click method.
00028             Button likeButton = GetTemplateChild("LikeButton") as Button;
00029             likeButton.Click += LikeButton_Click;
00030
00031             base.OnApplyTemplate();
00032         }
00033
00034         private void LikeButton_Click(object sender, RoutedEventArgs e)
00035         {
00036             // Raise an event on the custom control when 'like' is clicked
00037             Liked?.Invoke(this, EventArgs.Empty);
00038         }
00039     }
00040 }
Generated on Fri Nov 15 2024 22:22:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cpp/BackgroundActivity.h Source File

  • BackgroundActivation
  • cpp

BackgroundActivity.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 namespace SDKTemplate
00014 {
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class BackgroundActivity sealed
00017     {
00018     public:
00019         void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance);
00020         void OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason);
00021
00022         static void OnStart(Windows::ApplicationModel::Background::BackgroundTaskRegistrationGroup^ sender, Windows::ApplicationModel::Activation::BackgroundActivatedEventArgs^ args);
00023         static void Start(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance);
00024     private:
00025         Windows::ApplicationModel::Background::BackgroundTaskCancellationReason CancelReason = Windows::ApplicationModel::Background::BackgroundTaskCancellationReason::Abort;
00026         volatile bool CancelRequested = false;
00027         Platform::Agile<Windows::ApplicationModel::Background::BackgroundTaskDeferral> TaskDeferral = nullptr;
00028         Windows::System::Threading::ThreadPoolTimer^ PeriodicTimer = nullptr;
00029         unsigned int Progress = 0;
00030         Windows::ApplicationModel::Background::IBackgroundTaskInstance^ TaskInstance = nullptr;
00031     };
00032 }
Generated on Fri Nov 15 2024 22:18:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLInProcessWinRTComponent/cpp/Server/Microsoft.SDKSamples.Kitchen.idl Source File

  • WRLInProcessWinRTComponent
  • cpp
  • Server

Microsoft.SDKSamples.Kitchen.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include <sdkddkver.h>
00008 import "Windows.Foundation.idl";
00009
00010 namespace Microsoft.SDKSamples.Kitchen
00011 {
00012     [version(1.0)]
00013     typedef struct Dimensions
00014     {
00015         double Depth;
00016         double Height;
00017         double Width;
00018     } Dimensions;
00019
00020     [version(1.0)]
00021     typedef enum OvenTemperature
00022     {
00023         Low,
00024         Medium,
00025         High
00026     } OvenTemperature;
00027
00028     runtimeclass Bread;
00029     runtimeclass BreadBakedEventArgs;
00030     runtimeclass Oven;
00031
00032     [version(1.0), uuid(F13EA3D5-7B24-4CDE-9E5F-57AF30F0733C), exclusiveto(Bread)]
00033     interface IBread : IInspectable
00034     {
00035         [propget] HRESULT Flavor([out, retval] HSTRING* value);
00036     }
00037
00038     [version(1.0), uuid(332FD2F1-1C69-4C91-949E-4BB67A85BDC5)]
00039     interface IAppliance : IInspectable
00040     {
00041         [propget] HRESULT Volume([out, retval] double* value);
00042     }
00043
00044     [version(1.0), uuid(699B1394-3CEB-4A14-AE23-EFEC518B088B), exclusiveto(BreadBakedEventArgs)]
00045     interface IBreadBakedEventArgs : IInspectable
00046     {
00047         [propget] HRESULT Bread([out, retval] Bread** value);
00048     }
00049
00050     [version(1.0), uuid(6A112353-4F87-4460-A908-2944E92686F3), exclusiveto(Oven)]
00051     interface IOven : IInspectable requires IAppliance
00052     {
00053         HRESULT ConfigurePreheatTemperature([in] OvenTemperature temperature);
00054         HRESULT BakeBread([in] HSTRING flavor);
00055
00056         [eventadd] HRESULT BreadBaked([in] Windows.Foundation.TypedEventHandler<Oven*, BreadBakedEventArgs*>* handler, [out, retval] EventRegistrationToken* token);
00057         [eventremove] HRESULT BreadBaked([in] EventRegistrationToken token);
00058     }
00059
00060     [version(1.0), uuid(F36C2A21-F4E3-4C39-94CE-EB9190AFDAB3), exclusiveto(Oven)]
00061     interface IOvenFactory : IInspectable
00062     {
00063         HRESULT CreateOven([in] Dimensions dimensions, [out, retval] Oven** result);
00064     }
00065
00066     [version(1.0)]
00067     runtimeclass Bread
00068     {
00069         [default] interface IBread;
00070     }
00071
00072     [version(1.0)]
00073     runtimeclass BreadBakedEventArgs
00074     {
00075         [default] interface IBreadBakedEventArgs;
00076     }
00077
00078     [version(1.0), activatable(1.0), activatable(IOvenFactory, 1.0)]
00079     runtimeclass Oven
00080     {
00081         [default] interface IOven;
00082     }
00083 }
Generated on Fri Nov 15 2024 22:22:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/Common/DirectXHelper.cpp Source File

  • HolographicMixedRealityCapture
  • cpp
  • Common

DirectXHelper.cpp

Go to the documentation of this file.
00001 ﻿//--------------------------------------------------------------------------------------
00002 // This file is adapted from the file WICTextureLoader.cpp in the DirectXTex project.
00003 //
00004 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00006 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00007 // PARTICULAR PURPOSE.
00008 //
00009 // Copyright (c) Microsoft Corporation. All rights reserved.
00010 //
00011 // http://go.microsoft.com/fwlink/?LinkId=248926
00012 // http://go.microsoft.com/fwlink/?LinkId=248929
00013 //--------------------------------------------------------------------------------------
00014 #include <pch.h>
00015 #include "DirectXHelper.h"
00016 #include <wincodec.h>
00017
00018 using namespace Microsoft::WRL;
00019
00020 //-------------------------------------------------------------------------------------
00021 // WIC Pixel Format Translation Data
00022 //-------------------------------------------------------------------------------------
00023 struct WICTranslate
00024 {
00025     GUID                wic;
00026     DXGI_FORMAT         format;
00027 };
00028
00029 static WICTranslate g_WICFormats[] =
00030 {
00031     { GUID_WICPixelFormat128bppRGBAFloat,       DXGI_FORMAT_R32G32B32A32_FLOAT },
00032
00033     { GUID_WICPixelFormat64bppRGBAHalf,         DXGI_FORMAT_R16G16B16A16_FLOAT },
00034     { GUID_WICPixelFormat64bppRGBA,             DXGI_FORMAT_R16G16B16A16_UNORM },
00035
00036     { GUID_WICPixelFormat32bppRGBA,             DXGI_FORMAT_R8G8B8A8_UNORM },
00037     { GUID_WICPixelFormat32bppBGRA,             DXGI_FORMAT_B8G8R8A8_UNORM }, // DXGI 1.1
00038     { GUID_WICPixelFormat32bppBGR,              DXGI_FORMAT_B8G8R8X8_UNORM }, // DXGI 1.1
00039
00040     { GUID_WICPixelFormat32bppRGBA1010102XR,    DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM }, // DXGI 1.1
00041     { GUID_WICPixelFormat32bppRGBA1010102,      DXGI_FORMAT_R10G10B10A2_UNORM },
00042
00043     { GUID_WICPixelFormat16bppBGRA5551,         DXGI_FORMAT_B5G5R5A1_UNORM },
00044     { GUID_WICPixelFormat16bppBGR565,           DXGI_FORMAT_B5G6R5_UNORM },
00045
00046     { GUID_WICPixelFormat32bppGrayFloat,        DXGI_FORMAT_R32_FLOAT },
00047     { GUID_WICPixelFormat16bppGrayHalf,         DXGI_FORMAT_R16_FLOAT },
00048     { GUID_WICPixelFormat16bppGray,             DXGI_FORMAT_R16_UNORM },
00049     { GUID_WICPixelFormat8bppGray,              DXGI_FORMAT_R8_UNORM },
00050
00051     { GUID_WICPixelFormat8bppAlpha,             DXGI_FORMAT_A8_UNORM },
00052
00053     { GUID_WICPixelFormat96bppRGBFloat,         DXGI_FORMAT_R32G32B32_FLOAT },
00054 };
00055
00056 //-------------------------------------------------------------------------------------
00057 // WIC Pixel Format nearest conversion table
00058 //-------------------------------------------------------------------------------------
00059
00060 struct WICConvert
00061 {
00062     GUID        source;
00063     GUID        target;
00064 };
00065
00066 static WICConvert g_WICConvert[] =
00067 {
00068     // Note target GUID in this conversion table must be one of those directly supported formats (above).
00069
00070     { GUID_WICPixelFormatBlackWhite,            GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM
00071
00072     { GUID_WICPixelFormat1bppIndexed,           GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00073     { GUID_WICPixelFormat2bppIndexed,           GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00074     { GUID_WICPixelFormat4bppIndexed,           GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00075     { GUID_WICPixelFormat8bppIndexed,           GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00076
00077     { GUID_WICPixelFormat2bppGray,              GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM
00078     { GUID_WICPixelFormat4bppGray,              GUID_WICPixelFormat8bppGray }, // DXGI_FORMAT_R8_UNORM
00079
00080     { GUID_WICPixelFormat16bppGrayFixedPoint,   GUID_WICPixelFormat16bppGrayHalf }, // DXGI_FORMAT_R16_FLOAT
00081     { GUID_WICPixelFormat32bppGrayFixedPoint,   GUID_WICPixelFormat32bppGrayFloat }, // DXGI_FORMAT_R32_FLOAT
00082
00083     { GUID_WICPixelFormat16bppBGR555,           GUID_WICPixelFormat16bppBGRA5551 }, // DXGI_FORMAT_B5G5R5A1_UNORM
00084
00085     { GUID_WICPixelFormat32bppBGR101010,        GUID_WICPixelFormat32bppRGBA1010102 }, // DXGI_FORMAT_R10G10B10A2_UNORM
00086
00087     { GUID_WICPixelFormat24bppBGR,              GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00088     { GUID_WICPixelFormat24bppRGB,              GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00089     { GUID_WICPixelFormat32bppPBGRA,            GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00090     { GUID_WICPixelFormat32bppPRGBA,            GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00091
00092     { GUID_WICPixelFormat48bppRGB,              GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00093     { GUID_WICPixelFormat48bppBGR,              GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00094     { GUID_WICPixelFormat64bppBGRA,             GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00095     { GUID_WICPixelFormat64bppPRGBA,            GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00096     { GUID_WICPixelFormat64bppPBGRA,            GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00097
00098     { GUID_WICPixelFormat48bppRGBFixedPoint,    GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00099     { GUID_WICPixelFormat48bppBGRFixedPoint,    GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00100     { GUID_WICPixelFormat64bppRGBAFixedPoint,   GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00101     { GUID_WICPixelFormat64bppBGRAFixedPoint,   GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00102     { GUID_WICPixelFormat64bppRGBFixedPoint,    GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00103     { GUID_WICPixelFormat64bppRGBHalf,          GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00104     { GUID_WICPixelFormat48bppRGBHalf,          GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00105
00106     { GUID_WICPixelFormat128bppPRGBAFloat,      GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT
00107     { GUID_WICPixelFormat128bppRGBFloat,        GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT
00108     { GUID_WICPixelFormat128bppRGBAFixedPoint,  GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT
00109     { GUID_WICPixelFormat128bppRGBFixedPoint,   GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT
00110     { GUID_WICPixelFormat32bppRGBE,             GUID_WICPixelFormat128bppRGBAFloat }, // DXGI_FORMAT_R32G32B32A32_FLOAT
00111
00112     { GUID_WICPixelFormat32bppCMYK,             GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00113     { GUID_WICPixelFormat64bppCMYK,             GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00114     { GUID_WICPixelFormat40bppCMYKAlpha,        GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00115     { GUID_WICPixelFormat80bppCMYKAlpha,        GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00116
00117     { GUID_WICPixelFormat32bppRGB,              GUID_WICPixelFormat32bppRGBA }, // DXGI_FORMAT_R8G8B8A8_UNORM
00118     { GUID_WICPixelFormat64bppRGB,              GUID_WICPixelFormat64bppRGBA }, // DXGI_FORMAT_R16G16B16A16_UNORM
00119     { GUID_WICPixelFormat64bppPRGBAHalf,        GUID_WICPixelFormat64bppRGBAHalf }, // DXGI_FORMAT_R16G16B16A16_FLOAT
00120
00121     { GUID_WICPixelFormat96bppRGBFixedPoint, GUID_WICPixelFormat96bppRGBFloat }, // DXGI_FORMAT_R32G32B32_FLOAT
00122
00123                                                                                 // We don't support n-channel formats
00124 };
00125
00126 static IWICImagingFactory* _GetWIC()
00127 {
00128     static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT;
00129
00130     void* result = nullptr;
00131     InitOnceExecuteOnce(
00132         &s_initOnce,
00133         [](_In_ PINIT_ONCE, void*, void** context) -> BOOL
00134         {
00135             HRESULT hr = CoCreateInstance(
00136                 CLSID_WICImagingFactory2,
00137                 nullptr,
00138                 CLSCTX_INPROC_SERVER,
00139                 __uuidof(IWICImagingFactory2),
00140                 context);
00141             return SUCCEEDED(hr);
00142         },
00143         nullptr,
00144         &result);
00145
00146     return reinterpret_cast<IWICImagingFactory*>(result);
00147 }
00148
00149 //---------------------------------------------------------------------------------
00150 static DXGI_FORMAT _WICToDXGI(const GUID& guid)
00151 {
00152     for (size_t i = 0; i < _countof(g_WICFormats); ++i)
00153     {
00154         if (memcmp(&g_WICFormats[i].wic, &guid, sizeof(GUID)) == 0)
00155             return g_WICFormats[i].format;
00156     }
00157
00158     return DXGI_FORMAT_UNKNOWN;
00159 }
00160
00161 //---------------------------------------------------------------------------------
00162 static size_t _WICBitsPerPixel(REFGUID targetGuid)
00163 {
00164     IWICImagingFactory* pWIC = _GetWIC();
00165     if (!pWIC)
00166         return 0;
00167
00168     ComPtr<IWICComponentInfo> cinfo;
00169     if (FAILED(pWIC->CreateComponentInfo(targetGuid, cinfo.GetAddressOf())))
00170         return 0;
00171
00172     WICComponentType type;
00173     if (FAILED(cinfo->GetComponentType(&type)))
00174         return 0;
00175
00176     if (type != WICPixelFormat)
00177         return 0;
00178
00179     ComPtr<IWICPixelFormatInfo> pfinfo;
00180     if (FAILED(cinfo.As(&pfinfo)))
00181         return 0;
00182
00183     UINT bpp;
00184     if (FAILED(pfinfo->GetBitsPerPixel(&bpp)))
00185         return 0;
00186
00187     return bpp;
00188 }
00189
00190
00191 //--------------------------------------------------------------------------------------
00192 static DXGI_FORMAT MakeSRGB(_In_ DXGI_FORMAT format)
00193 {
00194     switch (format)
00195     {
00196     case DXGI_FORMAT_R8G8B8A8_UNORM:
00197         return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
00198
00199     case DXGI_FORMAT_BC1_UNORM:
00200         return DXGI_FORMAT_BC1_UNORM_SRGB;
00201
00202     case DXGI_FORMAT_BC2_UNORM:
00203         return DXGI_FORMAT_BC2_UNORM_SRGB;
00204
00205     case DXGI_FORMAT_BC3_UNORM:
00206         return DXGI_FORMAT_BC3_UNORM_SRGB;
00207
00208     case DXGI_FORMAT_B8G8R8A8_UNORM:
00209         return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
00210
00211     case DXGI_FORMAT_B8G8R8X8_UNORM:
00212         return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
00213
00214     case DXGI_FORMAT_BC7_UNORM:
00215         return DXGI_FORMAT_BC7_UNORM_SRGB;
00216
00217     default:
00218         return format;
00219     }
00220 }
00221
00222 static HRESULT CreateTextureFromWIC(_In_ ID3D11Device* d3dDevice,
00223     _In_opt_ ID3D11DeviceContext* d3dContext,
00224     _In_ IWICBitmapFrameDecode *frame,
00225     _In_ size_t maxsize,
00226     _In_ D3D11_USAGE usage,
00227     _In_ unsigned int bindFlags,
00228     _In_ unsigned int cpuAccessFlags,
00229     _In_ unsigned int miscFlags,
00230     _In_ bool forceSRGB,
00231     _Out_opt_ ID3D11Resource** texture,
00232     _Out_opt_ ID3D11ShaderResourceView** textureView)
00233 {
00234     UINT width, height;
00235     HRESULT hr = frame->GetSize(&width, &height);
00236     if (FAILED(hr))
00237         return hr;
00238
00239     assert(width > 0 && height > 0);
00240
00241     if (!maxsize)
00242     {
00243         // This is a bit conservative because the hardware could support larger textures than
00244         // the Feature Level defined minimums, but doing it this way is much easier and more
00245         // performant for WIC than the 'fail and retry' model used by DDSTextureLoader
00246
00247         switch (d3dDevice->GetFeatureLevel())
00248         {
00249         case D3D_FEATURE_LEVEL_9_1:
00250         case D3D_FEATURE_LEVEL_9_2:
00251             maxsize = 2048 /*D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
00252             break;
00253
00254         case D3D_FEATURE_LEVEL_9_3:
00255             maxsize = 4096 /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
00256             break;
00257
00258         case D3D_FEATURE_LEVEL_10_0:
00259         case D3D_FEATURE_LEVEL_10_1:
00260             maxsize = 8192 /*D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
00261             break;
00262
00263         default:
00264             maxsize = D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION;
00265             break;
00266         }
00267     }
00268
00269     assert(maxsize > 0);
00270
00271     UINT twidth, theight;
00272     if (width > maxsize || height > maxsize)
00273     {
00274         float ar = static_cast<float>(height) / static_cast<float>(width);
00275         if (width > height)
00276         {
00277             twidth = static_cast<UINT>(maxsize);
00278             theight = static_cast<UINT>(static_cast<float>(maxsize) * ar);
00279         }
00280         else
00281         {
00282             theight = static_cast<UINT>(maxsize);
00283             twidth = static_cast<UINT>(static_cast<float>(maxsize) / ar);
00284         }
00285         assert(twidth <= maxsize && theight <= maxsize);
00286     }
00287     else
00288     {
00289         twidth = width;
00290         theight = height;
00291     }
00292
00293     // Determine format
00294     WICPixelFormatGUID pixelFormat;
00295     hr = frame->GetPixelFormat(&pixelFormat);
00296     if (FAILED(hr))
00297         return hr;
00298
00299     WICPixelFormatGUID convertGUID;
00300     memcpy(&convertGUID, &pixelFormat, sizeof(WICPixelFormatGUID));
00301
00302     size_t bpp = 0;
00303
00304     DXGI_FORMAT format = _WICToDXGI(pixelFormat);
00305     if (format == DXGI_FORMAT_UNKNOWN)
00306     {
00307         for (size_t i = 0; i < _countof(g_WICConvert); ++i)
00308         {
00309             if (memcmp(&g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0)
00310             {
00311                 memcpy(&convertGUID, &g_WICConvert[i].target, sizeof(WICPixelFormatGUID));
00312
00313                 format = _WICToDXGI(g_WICConvert[i].target);
00314                 assert(format != DXGI_FORMAT_UNKNOWN);
00315                 bpp = _WICBitsPerPixel(convertGUID);
00316                 break;
00317             }
00318         }
00319
00320         if (format == DXGI_FORMAT_UNKNOWN)
00321             return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
00322     }
00323     else
00324     {
00325         bpp = _WICBitsPerPixel(pixelFormat);
00326     }
00327
00328     if ((format == DXGI_FORMAT_R32G32B32_FLOAT) && d3dContext != 0 && textureView != 0)
00329     {
00330         // Special case test for optional device support for autogen mipchains for R32G32B32_FLOAT
00331         UINT fmtSupport = 0;
00332         hr = d3dDevice->CheckFormatSupport(DXGI_FORMAT_R32G32B32_FLOAT, &fmtSupport);
00333         if (FAILED(hr) || !(fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN))
00334         {
00335             // Use R32G32B32A32_FLOAT instead which is required for Feature Level 10.0 and up
00336             memcpy(&convertGUID, &GUID_WICPixelFormat128bppRGBAFloat, sizeof(WICPixelFormatGUID));
00337             format = DXGI_FORMAT_R32G32B32A32_FLOAT;
00338             bpp = 128;
00339         }
00340     }
00341
00342     if (!bpp)
00343         return E_FAIL;
00344
00345     // Handle sRGB formats
00346     if (forceSRGB)
00347     {
00348         format = MakeSRGB(format);
00349     }
00350     else
00351     {
00352         ComPtr<IWICMetadataQueryReader> metareader;
00353         if (SUCCEEDED(frame->GetMetadataQueryReader(metareader.GetAddressOf())))
00354         {
00355             GUID containerFormat;
00356             if (SUCCEEDED(metareader->GetContainerFormat(&containerFormat)))
00357             {
00358                 // Check for sRGB colorspace metadata
00359                 bool sRGB = false;
00360
00361                 PROPVARIANT value;
00362                 PropVariantInit(&value);
00363
00364                 if (memcmp(&containerFormat, &GUID_ContainerFormatPng, sizeof(GUID)) == 0)
00365                 {
00366                     // Check for sRGB chunk
00367                     if (SUCCEEDED(metareader->GetMetadataByName(L"/sRGB/RenderingIntent", &value)) && value.vt == VT_UI1)
00368                     {
00369                         sRGB = true;
00370                     }
00371                 }
00372                 else if (SUCCEEDED(metareader->GetMetadataByName(L"System.Image.ColorSpace", &value)) && value.vt == VT_UI2 && value.uiVal == 1)
00373                 {
00374                     sRGB = true;
00375                 }
00376
00377                 PropVariantClear(&value);
00378
00379                 if (sRGB)
00380                     format = MakeSRGB(format);
00381             }
00382         }
00383     }
00384
00385     // Verify our target format is supported by the current device
00386     // (handles WDDM 1.0 or WDDM 1.1 device driver cases as well as DirectX 11.0 Runtime without 16bpp format support)
00387     UINT support = 0;
00388     hr = d3dDevice->CheckFormatSupport(format, &support);
00389     if (FAILED(hr) || !(support & D3D11_FORMAT_SUPPORT_TEXTURE2D))
00390     {
00391         // Fallback to RGBA 32-bit format which is supported by all devices
00392         memcpy(&convertGUID, &GUID_WICPixelFormat32bppRGBA, sizeof(WICPixelFormatGUID));
00393         format = DXGI_FORMAT_R8G8B8A8_UNORM;
00394         bpp = 32;
00395     }
00396
00397     // Allocate temporary memory for image
00398     size_t rowPitch = (twidth * bpp + 7) / 8;
00399     size_t imageSize = rowPitch * theight;
00400
00401     std::unique_ptr<uint8_t[]> temp(new (std::nothrow) uint8_t[imageSize]);
00402     if (!temp)
00403         return E_OUTOFMEMORY;
00404
00405     // Load image data
00406     if (memcmp(&convertGUID, &pixelFormat, sizeof(GUID)) == 0
00407         && twidth == width
00408         && theight == height)
00409     {
00410         // No format conversion or resize needed
00411         hr = frame->CopyPixels(0, static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize), temp.get());
00412         if (FAILED(hr))
00413             return hr;
00414     }
00415     else if (twidth != width || theight != height)
00416     {
00417         // Resize
00418         IWICImagingFactory* pWIC = _GetWIC();
00419         if (!pWIC)
00420             return E_NOINTERFACE;
00421
00422         ComPtr<IWICBitmapScaler> scaler;
00423         hr = pWIC->CreateBitmapScaler(scaler.GetAddressOf());
00424         if (FAILED(hr))
00425             return hr;
00426
00427         hr = scaler->Initialize(frame, twidth, theight, WICBitmapInterpolationModeFant);
00428         if (FAILED(hr))
00429             return hr;
00430
00431         WICPixelFormatGUID pfScaler;
00432         hr = scaler->GetPixelFormat(&pfScaler);
00433         if (FAILED(hr))
00434             return hr;
00435
00436         if (memcmp(&convertGUID, &pfScaler, sizeof(GUID)) == 0)
00437         {
00438             // No format conversion needed
00439             hr = scaler->CopyPixels(0, static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize), temp.get());
00440             if (FAILED(hr))
00441                 return hr;
00442         }
00443         else
00444         {
00445             ComPtr<IWICFormatConverter> FC;
00446             hr = pWIC->CreateFormatConverter(FC.GetAddressOf());
00447             if (FAILED(hr))
00448                 return hr;
00449
00450             BOOL canConvert = FALSE;
00451             hr = FC->CanConvert(pfScaler, convertGUID, &canConvert);
00452             if (FAILED(hr) || !canConvert)
00453             {
00454                 return E_UNEXPECTED;
00455             }
00456
00457             hr = FC->Initialize(scaler.Get(), convertGUID, WICBitmapDitherTypeErrorDiffusion, 0, 0, WICBitmapPaletteTypeCustom);
00458             if (FAILED(hr))
00459                 return hr;
00460
00461             hr = FC->CopyPixels(0, static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize), temp.get());
00462             if (FAILED(hr))
00463                 return hr;
00464         }
00465     }
00466     else
00467     {
00468         // Format conversion but no resize
00469         IWICImagingFactory* pWIC = _GetWIC();
00470         if (!pWIC)
00471             return E_NOINTERFACE;
00472
00473         ComPtr<IWICFormatConverter> FC;
00474         hr = pWIC->CreateFormatConverter(FC.GetAddressOf());
00475         if (FAILED(hr))
00476             return hr;
00477
00478         BOOL canConvert = FALSE;
00479         hr = FC->CanConvert(pixelFormat, convertGUID, &canConvert);
00480         if (FAILED(hr) || !canConvert)
00481         {
00482             return E_UNEXPECTED;
00483         }
00484
00485         hr = FC->Initialize(frame, convertGUID, WICBitmapDitherTypeErrorDiffusion, 0, 0, WICBitmapPaletteTypeCustom);
00486         if (FAILED(hr))
00487             return hr;
00488
00489         hr = FC->CopyPixels(0, static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize), temp.get());
00490         if (FAILED(hr))
00491             return hr;
00492     }
00493
00494     // See if format is supported for auto-gen mipmaps (varies by feature level)
00495     bool autogen = false;
00496     if (d3dContext != 0 && textureView != 0) // Must have context and shader-view to auto generate mipmaps
00497     {
00498         UINT fmtSupport = 0;
00499         hr = d3dDevice->CheckFormatSupport(format, &fmtSupport);
00500         if (SUCCEEDED(hr) && (fmtSupport & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN))
00501         {
00502             autogen = true;
00503         }
00504     }
00505
00506     // Create texture
00507     D3D11_TEXTURE2D_DESC desc;
00508     desc.Width = twidth;
00509     desc.Height = theight;
00510     desc.MipLevels = (autogen) ? 0 : 1;
00511     desc.ArraySize = 1;
00512     desc.Format = format;
00513     desc.SampleDesc.Count = 1;
00514     desc.SampleDesc.Quality = 0;
00515     desc.Usage = usage;
00516     desc.CPUAccessFlags = cpuAccessFlags;
00517
00518     if (autogen)
00519     {
00520         desc.BindFlags = bindFlags | D3D11_BIND_RENDER_TARGET;
00521         desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_GENERATE_MIPS;
00522     }
00523     else
00524     {
00525         desc.BindFlags = bindFlags;
00526         desc.MiscFlags = miscFlags;
00527     }
00528
00529     D3D11_SUBRESOURCE_DATA initData;
00530     initData.pSysMem = temp.get();
00531     initData.SysMemPitch = static_cast<UINT>(rowPitch);
00532     initData.SysMemSlicePitch = static_cast<UINT>(imageSize);
00533
00534     ID3D11Texture2D* tex = nullptr;
00535     hr = d3dDevice->CreateTexture2D(&desc, (autogen) ? nullptr : &initData, &tex);
00536     if (SUCCEEDED(hr) && tex != 0)
00537     {
00538         if (textureView != 0)
00539         {
00540             D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00541             memset(&SRVDesc, 0, sizeof(SRVDesc));
00542             SRVDesc.Format = desc.Format;
00543
00544             SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
00545             SRVDesc.Texture2D.MipLevels = (autogen) ? -1 : 1;
00546
00547             hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00548             if (FAILED(hr))
00549             {
00550                 tex->Release();
00551                 return hr;
00552             }
00553
00554             if (autogen)
00555             {
00556                 assert(d3dContext != 0);
00557                 d3dContext->UpdateSubresource(tex, 0, nullptr, temp.get(), static_cast<UINT>(rowPitch), static_cast<UINT>(imageSize));
00558                 d3dContext->GenerateMips(*textureView);
00559             }
00560         }
00561
00562         if (texture != 0)
00563         {
00564             *texture = tex;
00565         }
00566         else
00567         {
00568             tex->Release();
00569         }
00570     }
00571
00572     return hr;
00573 }
00574
00575 HRESULT DX::CreateWICTextureFromMemoryEx(ID3D11Device* d3dDevice,
00576                                          const uint8_t* wicData,
00577                                          size_t wicDataSize,
00578                                          size_t maxsize,
00579                                          D3D11_USAGE usage,
00580                                          unsigned int bindFlags,
00581                                          unsigned int cpuAccessFlags,
00582                                          unsigned int miscFlags,
00583                                          bool forceSRGB,
00584                                          ID3D11Resource** texture,
00585                                          ID3D11ShaderResourceView** textureView)
00586 {
00587     if (texture)
00588     {
00589         *texture = nullptr;
00590     }
00591     if (textureView)
00592     {
00593         *textureView = nullptr;
00594     }
00595
00596     if (!d3dDevice || !wicData || (!texture && !textureView))
00597         return E_INVALIDARG;
00598
00599     if (!wicDataSize)
00600         return E_FAIL;
00601
00602 #ifdef _WIN64
00603     if (wicDataSize > 0xFFFFFFFF)
00604         return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE);
00605 #endif
00606
00607     IWICImagingFactory* pWIC = _GetWIC();
00608     if (!pWIC)
00609         return E_NOINTERFACE;
00610
00611     // Create input stream for memory
00612     ComPtr<IWICStream> stream;
00613     HRESULT hr = pWIC->CreateStream(stream.GetAddressOf());
00614     if (FAILED(hr))
00615         return hr;
00616
00617     hr = stream->InitializeFromMemory(const_cast<uint8_t*>(wicData), static_cast<DWORD>(wicDataSize));
00618     if (FAILED(hr))
00619         return hr;
00620
00621     // Initialize WIC
00622     ComPtr<IWICBitmapDecoder> decoder;
00623     hr = pWIC->CreateDecoderFromStream(stream.Get(), 0, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf());
00624     if (FAILED(hr))
00625         return hr;
00626
00627     ComPtr<IWICBitmapFrameDecode> frame;
00628     hr = decoder->GetFrame(0, frame.GetAddressOf());
00629     if (FAILED(hr))
00630         return hr;
00631
00632     hr = CreateTextureFromWIC(d3dDevice, nullptr,
00633                               frame.Get(), maxsize,
00634                               usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB,
00635                               texture, textureView);
00636
00637     return hr;
00638 }
00639
00640
00641 HRESULT DX::CreateWICTextureFromMemory(ID3D11Device* d3dDevice,
00642                                        const uint8_t* wicData,
00643                                        size_t wicDataSize,
00644                                        ID3D11Resource** texture,
00645                                        ID3D11ShaderResourceView** textureView,
00646                                        size_t maxsize)
00647 {
00648     return CreateWICTextureFromMemoryEx(d3dDevice, wicData, wicDataSize, maxsize,
00649                                         D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false,
00650                                         texture, textureView);
00651 }
00652
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Audio/AudioStreamReader.h Source File

  • HolographicVoiceInput
  • cpp
  • Audio

AudioStreamReader.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012
00013 #include <vector>
00014
00015 //
00016 // Helper class uses MediaFoundation to read audio files
00017 //
00018 class AudioStreamReader
00019 {
00020 public:
00021     virtual ~AudioStreamReader() {}
00022     HRESULT Initialize(_In_ Windows::Media::SpeechSynthesis::SpeechSynthesisStream^ speechSynthesisStream);
00023
00024     const WAVEFORMATEX* GetFormat() const
00025     {
00026         return &_format;
00027     }
00028
00029     size_t GetSize() const
00030     {
00031         return _audioData.size();
00032     }
00033
00034     const BYTE* GetData() const
00035     {
00036         return _audioData.data();
00037     }
00038
00039 private:
00040     WAVEFORMATEX        _format;
00041     std::vector<BYTE>   _audioData;
00042 };
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Package/cpp/scenario1_identity.xaml.h Source File

  • Package
  • cpp

scenario1_identity.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario1.xaml.h
00013 // Declaration of the Scenario1 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario1_Identity.g.h"
00020 #include "MainPage.xaml.h"
00021
00022
00023     namespace SDKTemplate
00024     {
00025         /// <summary>
00026         /// An empty page that can be used on its own or navigated to within a Frame.
00027         /// </summary>
00028         [Windows::Foundation::Metadata::WebHostHidden]
00029         public ref class Scenario1 sealed
00030         {
00031         public:
00032             Scenario1();
00033
00034         protected:
00035             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         private:
00037             MainPage^ rootPage;
00038
00039             Platform::String^ VersionString(Windows::ApplicationModel::PackageVersion version);
00040             Platform::String^ ArchitectureString(Windows::System::ProcessorArchitecture architecture);
00041
00042             void GetPackage_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043         };
00044
00045 }
Generated on Fri Nov 15 2024 22:20:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisplayOrientation/cppwinrt/Scenario1_Orientation.h Source File

  • DisplayOrientation
  • cppwinrt

Scenario1_Orientation.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Orientation.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_Orientation : Scenario1_OrientationT<Scenario1_Orientation>
00019     {
00020         Scenario1_Orientation();
00021
00022         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00023         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024
00025         void ApplyRotationLock_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026
00027     private:
00028         Windows::Graphics::Display::DisplayInformation displayInfo{ nullptr };
00029         event_token orientationChangedToken{};
00030
00031         void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation const&, Windows::Foundation::IInspectable const&);
00032         hstring OrientationsToString(Windows::Graphics::Display::DisplayOrientations orientations);
00033         void UpdateContent();
00034     };
00035 }
00036
00037 namespace winrt::SDKTemplate::factory_implementation
00038 {
00039     struct Scenario1_Orientation : Scenario1_OrientationT<Scenario1_Orientation, implementation::Scenario1_Orientation>
00040     {
00041     };
00042 }
Generated on Fri Nov 15 2024 22:19:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_InAppPurchase Member List

This is the complete list of members for Scenario2_InAppPurchase, including all inherited members.
GetAssociatedProductsButton_Click(object sender, RoutedEventArgs e) | Scenario2_InAppPurchase | [inline, private]
PurchaseAddOnButton_Click(object sender, RoutedEventArgs e) | Scenario2_InAppPurchase | [inline, private]
rootPage | Scenario2_InAppPurchase | [private]
Scenario2_InAppPurchase() | Scenario2_InAppPurchase | [inline]
storeContext | Scenario2_InAppPurchase | [private]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/App.xaml.cs Source File

  • 360VideoPlayback
  • cs

App.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.ApplicationModel;
00003 using Windows.ApplicationModel.Activation;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006 using Windows.UI.Xaml.Navigation;
00007
00008 namespace _360VideoPlayback
00009 {
00010     /// <summary>
00011     /// Provides application-specific behavior to supplement the default Application class.
00012     /// </summary>
00013     sealed partial class App : Application
00014     {
00015         /// <summary>
00016         /// Initializes the singleton application object.  This is the first line of authored code
00017         /// executed, and as such is the logical equivalent of main() or WinMain().
00018         /// </summary>
00019         public App()
00020         {
00021             this.InitializeComponent();
00022             this.Suspending += OnSuspending;
00023             Application.Current.RequiresPointerMode = ApplicationRequiresPointerMode.WhenRequested;
00024         }
00025
00026         /// <summary>
00027         /// Invoked when the application is launched normally by the end user.  Other entry points
00028         /// will be used such as when the application is launched to open a specific file.
00029         /// </summary>
00030         /// <param name="e">Details about the launch request and process.</param>
00031         protected override void OnLaunched(LaunchActivatedEventArgs e)
00032         {
00033 #if DEBUG
00034             if (System.Diagnostics.Debugger.IsAttached)
00035             {
00036                 this.DebugSettings.EnableFrameRateCounter = false;
00037             }
00038 #endif
00039
00040             Frame rootFrame = Window.Current.Content as Frame;
00041
00042             // Do not repeat app initialization when the Window already has content,
00043             // just ensure that the window is active
00044             if (rootFrame == null)
00045             {
00046                 // Create a Frame to act as the navigation context and navigate to the first page
00047                 rootFrame = new Frame();
00048
00049                 rootFrame.NavigationFailed += OnNavigationFailed;
00050
00051                 if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
00052                 {
00053                     //TODO: Load state from previously suspended application
00054                 }
00055
00056                 // Place the frame in the current Window
00057                 Window.Current.Content = rootFrame;
00058             }
00059
00060             if (e.PrelaunchActivated == false)
00061             {
00062                 if (rootFrame.Content == null)
00063                 {
00064                     // When the navigation stack isn't restored navigate to the first page,
00065                     // configuring the new page by passing required information as a navigation
00066                     // parameter
00067                     rootFrame.Navigate(typeof(MainPage), e.Arguments);
00068                 }
00069                 // Ensure the current window is active
00070                 Window.Current.Activate();
00071             }
00072         }
00073
00074         /// <summary>
00075         /// Invoked when Navigation to a certain page fails
00076         /// </summary>
00077         /// <param name="sender">The Frame which failed navigation</param>
00078         /// <param name="e">Details about the navigation failure</param>
00079         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00080         {
00081             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00082         }
00083
00084         /// <summary>
00085         /// Invoked when application execution is being suspended.  Application state is saved
00086         /// without knowing whether the application will be terminated or resumed with the contents
00087         /// of memory still intact.
00088         /// </summary>
00089         /// <param name="sender">The source of the suspend request.</param>
00090         /// <param name="e">Details about the suspend request.</param>
00091         private void OnSuspending(object sender, SuspendingEventArgs e)
00092         {
00093             var deferral = e.SuspendingOperation.GetDeferral();
00094             //TODO: Save application state and stop any background activity
00095             deferral.Complete();
00096         }
00097     }
00098 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cpp/Scenario5_RoundingAndPadding.xaml.cpp Source File

  • NumberFormatting
  • cpp

Scenario5_RoundingAndPadding.xaml.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario5_RoundingAndPadding.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Windows::UI::Xaml;
00010 using namespace Windows::UI::Xaml::Controls;
00011 using namespace Windows::UI::Xaml::Navigation;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::Globalization::NumberFormatting;
00015
00016 Scenario5_RoundingAndPadding::Scenario5_RoundingAndPadding()
00017 {
00018     InitializeComponent();
00019 }
00020
00021 /// <summary>
00022 /// Used to display the rounding algorithm in a string format.  Used by the different scenarios when
00023 /// displaying results for the scenario
00024 /// </summary>
00025 /// <param name="roundingAlgorithm"></param>
00026 String^ Scenario5_RoundingAndPadding::DisplayRoundingAlgorithmAsString(RoundingAlgorithm roundingAlgorithm)
00027 {
00028     String^ roundingAsString = "";
00029
00030     // Convert the enumeration value into a string representation
00031     switch (roundingAlgorithm) {
00032         case RoundingAlgorithm::None:
00033             roundingAsString = "no";
00034             break;
00035         case RoundingAlgorithm::RoundAwayFromZero:
00036             roundingAsString = "away from zero";
00037             break;
00038         case RoundingAlgorithm::RoundDown:
00039             roundingAsString = "down";
00040             break;
00041         case RoundingAlgorithm::RoundHalfAwayFromZero:
00042             roundingAsString = "half away from zero";
00043             break;
00044         case RoundingAlgorithm::RoundHalfDown:
00045             roundingAsString = "half down";
00046             break;
00047         case RoundingAlgorithm::RoundHalfToEven:
00048             roundingAsString = "half to even";
00049             break;
00050         case RoundingAlgorithm::RoundHalfToOdd:
00051             roundingAsString = "half to odd";
00052             break;
00053         case RoundingAlgorithm::RoundHalfTowardsZero:
00054             roundingAsString = "half towards zero";
00055             break;
00056         case RoundingAlgorithm::RoundHalfUp:
00057             roundingAsString = "half up";
00058             break;
00059         case RoundingAlgorithm::RoundTowardsZero:
00060             roundingAsString = "toward zero";
00061             break;
00062         case RoundingAlgorithm::RoundUp:
00063             roundingAsString = "up";
00064             break;
00065         default:
00066             roundingAsString = "unknown";
00067             break;
00068     }
00069
00070     return roundingAsString;
00071 }
00072
00073 /// <summary>
00074 /// Executes the padding scenarios.
00075 /// </summary>
00076 /// <param name="formatter">
00077 /// The formatter parameter can be either a DecimalFormatter, PercentFormatter
00078 /// PerMilleFormatter or CurrencyFormatter
00079 /// </param>
00080 String^ Scenario5_RoundingAndPadding::DoPaddingScenarios(INumberFormatter^ formatter)
00081 {
00082     // Display the properties of the scenario
00083     String^ results = "Padding with ";
00084     results = results + ((ISignificantDigitsOption^)formatter)->SignificantDigits + " significant digits, ";
00085     results = results + ((INumberFormatterOptions^)formatter)->IntegerDigits + " integer digits, ";
00086     results = results + ((INumberFormatterOptions^)formatter)->FractionDigits + " fractional digits\n\n";
00087
00088     // Iterate through the numbers to pad, format them and add them to the results
00089     double numbersToPad[] = { 0.12, 1.2, 10.2, 102 };
00090     for (int index = 0; index < sizeof(numbersToPad)/sizeof(double); index++)
00091     {
00092         double numberToPad = numbersToPad[index];
00093         String^ paddedNumber = formatter->Format(numberToPad);
00094         results = results + "Value: " + numberToPad + " Padded: " + paddedNumber + "\n";
00095     }
00096
00097     // Add a carriage return at the end of the scenario for readability
00098     return results + "\n";
00099 }
00100
00101 /// <summary>
00102 /// Demonstrates how to perform padding and rounding by using the DecimalFormatter class (can be any of the
00103 /// formatter classes in the Windows.Globalization.Numberformatting namespace) and the IncrementNumberRounder
00104 /// to do so.  The SignificantDigitsNumberRounder can also be used instead of the latter.
00105 /// </summary>
00106 /// <param name="roundingAlgorithm"></param>
00107 /// <param name="significantDigits"></param>
00108 /// <param name="integerDigits"></param>
00109 /// <param name="fractionalDigits"></param>
00110 String^ Scenario5_RoundingAndPadding::DoPaddingAndRoundingScenarios(RoundingAlgorithm roundingAlgorithm, unsigned int significantDigits, int integerDigits, int fractionalDigits)
00111 {
00112     // Create the rounder and set the rounding algorithm provided as a parameter
00113     IncrementNumberRounder^ rounder = ref new Windows::Globalization::NumberFormatting::IncrementNumberRounder();
00114     rounder->RoundingAlgorithm = roundingAlgorithm;
00115
00116     // Create the formatter, set the padding properties provided as parameters and associate the rounder
00117     // we have just created
00118     DecimalFormatter^ formatter = ref new Windows::Globalization::NumberFormatting::DecimalFormatter();
00119     formatter->SignificantDigits = significantDigits;
00120     formatter->IntegerDigits = integerDigits;
00121     formatter->FractionDigits = fractionalDigits;
00122     formatter->NumberRounder = rounder;
00123
00124     // Stores the results
00125     String^ results = "";
00126
00127     // Iterate through the increments we have defined in the scenario
00128     double incrementsToRound[] = { 0.001, 0.01, 0.1, 1.0 };
00129     for (int incrementIndex=0; incrementIndex < sizeof(incrementsToRound)/sizeof(double); incrementIndex++)
00130     {
00131         // Set the increment to round to
00132         rounder->Increment = incrementsToRound[incrementIndex];
00133
00134         // Display the properties of the scenario
00135         results = results + "Padding and rounding with ";
00136         results = results + formatter->SignificantDigits + " significant digits, ";
00137         results = results + formatter->IntegerDigits + " integer digits, ";
00138         results = results + formatter->FractionDigits + " fractional digits, ";
00139         results = results + rounder->Increment + " increment and ";
00140         results = results + DisplayRoundingAlgorithmAsString(rounder->RoundingAlgorithm) + " rounding algorithm\n\n";
00141
00142         // Iterate through the numbers to round and pad, format them and add them to the results
00143         double numbersToFormat[] = { 0.1458, 1.458, 14.58, 145.8 };
00144         for (int numberIndex = 0; numberIndex < sizeof(numbersToFormat)/sizeof(double); numberIndex++)
00145         {
00146             double numberToFormat = numbersToFormat[numberIndex];
00147             String^ formattedNumber = formatter->Format(numberToFormat);
00148             results = results + "Value: " + numberToFormat + " Formatted: " + formattedNumber + "\n";
00149         }
00150
00151         // Add a carriage return at the end of the scenario for readability
00152         results = results + "\n";
00153     }
00154
00155     return results;
00156 }
00157
00158 /// <summary>
00159 /// This scenario illustrates how to provide a rounding algorithm to a CurrencyFormatter class by means of the
00160 /// applyRoundingForCurrency method.  This will associate an IncrementNumberRounder using the same increment as the
00161 /// fractionDigits appropriate for the currency and language.  You can always choose to provide a different rounding
00162 /// algorithm by setting the numberRounder property, as depicted in the doPaddingAndRoundingScenarios function.
00163 /// The mechanism provided here is better suited for currencies.
00164 /// </summary>
00165 /// <param name="currencyCode"></param>
00166 /// <param name="roundingAlgorithm"></param>
00167 String^ Scenario5_RoundingAndPadding::DoCurrencyRoundingScenarios(String^ currencyCode, RoundingAlgorithm roundingAlgorithm)
00168 {
00169     // Create the currency formatter and set the rounding algorithm provided as a parameter
00170     CurrencyFormatter^ currencyFormatter = ref new Windows::Globalization::NumberFormatting::CurrencyFormatter(currencyCode);
00171     currencyFormatter->ApplyRoundingForCurrency(roundingAlgorithm);
00172
00173     // Display the properties of the scenario
00174     String^ results = "Currency formatting for ";
00175     results = results + currencyFormatter->Currency + " currency and using the ";
00176     results = results + DisplayRoundingAlgorithmAsString(roundingAlgorithm) + " rounding algorithm\n\n";
00177
00178     // Iterate through the numbers to round and add them to the results
00179     double numbersToFormat[] = { 14.55, 3.345, 16.2, 175.8 };
00180     for (int numberIndex = 0; numberIndex < sizeof(numbersToFormat)/sizeof(double); numberIndex++)
00181     {
00182         double numberToFormat = numbersToFormat[numberIndex];
00183         String^ formattedNumber = currencyFormatter->Format(numberToFormat);
00184         results = results + "Value: " + numberToFormat + " Formatted: " + formattedNumber + "\n";
00185     }
00186
00187     // Add a carriage return at the end of the scenario for readability
00188     return results + "\n";
00189 }
00190
00191 /// <summary>
00192 /// Shows how to do number rounding using the IncrementNumberRounding class.
00193 ///</summary>
00194 ///<param name="roundingAlgorithm"></param>
00195 String^ Scenario5_RoundingAndPadding::DoIncrementRoundingScenarios(RoundingAlgorithm roundingAlgorithm)
00196 {
00197     // Create the rounder and set the rounding algorithm provided as a parameter
00198     IncrementNumberRounder^ rounder = ref new Windows::Globalization::NumberFormatting::IncrementNumberRounder();
00199     rounder->RoundingAlgorithm = roundingAlgorithm;
00200
00201     // Formatter to display the rounded value.  It is recommended to use the increment number
00202     // rounder within a formatter object to avoid precision issues when displaying.
00203     DecimalFormatter^ formatter = ref new Windows::Globalization::NumberFormatting::DecimalFormatter();
00204     formatter->NumberRounder = rounder;
00205
00206     // Stores the results
00207     String^ results = "";
00208
00209     // Iterate through the increments we have defined in the scenario
00210     double incrementsToRound[] = { 0.001, 0.01, 0.1, 1.0 };
00211     for (int incrementIndex = 0; incrementIndex < sizeof(incrementsToRound)/sizeof(double); incrementIndex++)
00212     {
00213         // Set the significant digits to round to
00214         rounder->Increment = incrementsToRound[incrementIndex];
00215
00216         // Display the properties of the scenario
00217         results = results + "Rounding with ";
00218         results = results + rounder->Increment + " increment and ";
00219         results = results + DisplayRoundingAlgorithmAsString(rounder->RoundingAlgorithm) + " rounding algorithm\n\n";
00220
00221         // Iterate through the numbers to round and add them to the results
00222         double numbersToRound[] = { 0.1458, 1.458, 14.58, 145.8 };
00223         for (int numberIndex = 0; numberIndex < sizeof(numbersToRound)/sizeof(double); numberIndex++)
00224         {
00225             double numberToRound = numbersToRound[numberIndex];
00226             results = results + "Value: " + numberToRound + " Rounded: " + formatter->Format(numberToRound) + "\n";
00227         }
00228
00229         // Add a carriage return at the end of the scenario for readability
00230         results = results + "\n";
00231     }
00232
00233     return results;
00234 }
00235
00236 /// <summary>
00237 /// Shows how to do number rounding using the SignificantDigitsNumberRounder class.
00238 /// </summary>
00239 /// <param name="roundingAlgorithm"></param>
00240 String^ Scenario5_RoundingAndPadding::DoSignificantDigitRoundingScenarios(RoundingAlgorithm roundingAlgorithm)
00241 {
00242     // Create the rounder and set the rounding algorithm provided as a parameter.
00243     SignificantDigitsNumberRounder^ rounder = ref new Windows::Globalization::NumberFormatting::SignificantDigitsNumberRounder();
00244     rounder->RoundingAlgorithm = roundingAlgorithm;
00245
00246     // Stores the results
00247     String^ results = "";
00248
00249     // Iterate through the significant digits we have defined in the scenario
00250     unsigned int digitsToRound[] = { 3, 2, 1 };
00251     for (int digitIndex = 0; digitIndex < sizeof(digitsToRound)/sizeof(unsigned int); digitIndex++)
00252     {
00253         // Set the significant digits to round to
00254         rounder->SignificantDigits = digitsToRound[digitIndex];
00255
00256         // Display the properties of the scenario
00257         results = results + "Rounding with ";
00258         results = results + rounder->SignificantDigits + " significant digits and ";
00259         results = results + DisplayRoundingAlgorithmAsString(rounder->RoundingAlgorithm) + " rounding algorithm\n\n";
00260
00261         // Iterate through the numbers to round and add them to the results
00262         double numbersToRound[] = { 0.1458, 1.458, 14.58, 145.8 };
00263         for (int numberIndex = 0; numberIndex < sizeof(numbersToRound)/sizeof(double); numberIndex++)
00264         {
00265             double numberToRound = numbersToRound[numberIndex];
00266             double roundedValue = rounder->RoundDouble(numberToRound);
00267             results = results + "Value: " + numberToRound + " Rounded: " + roundedValue + "\n";
00268         }
00269
00270         // Add a carriage return at the end of the scenario for readability
00271         results = results + "\n";
00272     }
00273
00274     return results;
00275 }
00276
00277 /// <summary>
00278 /// This is the click handler for the 'Display' button.
00279 /// </summary>
00280 /// <param name="sender"></param>
00281 /// <param name="e"></param>
00282 void Scenario5_RoundingAndPadding::Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00283 {
00284     // Variable where we keep results to display
00285     String^ results = "";
00286
00287     // Create a decimal formatter used to do padding with only 4 significant digits.  We zero the
00288     // integerDigits and fractionDigits to only show the behavior of the significantDigits property
00289     // when formatting.
00290     DecimalFormatter^ decimalFormatter = ref new DecimalFormatter();
00291     decimalFormatter->SignificantDigits = 4;
00292     decimalFormatter->IntegerDigits = 0;
00293     decimalFormatter->FractionDigits = 0;
00294
00295     // Run through the scenarios with padding
00296     results = results + DoPaddingScenarios(decimalFormatter);
00297
00298     // Create a percent formatter used to do padding with 4 significant digits, 2 minimum integer
00299     // digits, 2 minimum factional digits.  This will show how the behavior of the significantDigits
00300     // property in conjunction with the integerDigits and fractionDigits properties.
00301     PercentFormatter^ percentFormatter = ref new PercentFormatter();
00302     percentFormatter->SignificantDigits = 4;
00303     percentFormatter->IntegerDigits = 2;
00304     percentFormatter->FractionDigits = 2;
00305
00306     // Run through the scenarios
00307     results = results + DoPaddingScenarios(percentFormatter);
00308
00309     // Do the significant rounding scenarios with round up algorithm
00310     results = results + DoSignificantDigitRoundingScenarios(RoundingAlgorithm::RoundUp);
00311
00312     // Do the significant rounding scenarios with round down algorithm
00313     results = results + DoSignificantDigitRoundingScenarios(RoundingAlgorithm::RoundDown);
00314
00315     // Do the increment rounding scenarios with round half up algorithm
00316     results = results + DoIncrementRoundingScenarios(RoundingAlgorithm::RoundHalfUp);
00317
00318     // Do the increment rounding scenarios with round half down algorithm
00319     results = results + DoIncrementRoundingScenarios(RoundingAlgorithm::RoundHalfDown);
00320
00321     // Do currency formatting with rounding for Japanese Yen with round half to odd algorithm
00322     results = results + DoCurrencyRoundingScenarios("JPY", RoundingAlgorithm::RoundHalfToOdd);
00323
00324     // Do currency formatting with rounding for Euro with round half to even algorithm
00325     results = results + DoCurrencyRoundingScenarios("EUR", RoundingAlgorithm::RoundHalfToEven);
00326
00327     // Do padding and rounding scenarios using round half up algorithm
00328     results = results + DoPaddingAndRoundingScenarios(RoundingAlgorithm::RoundHalfUp, 4, 3, 2);
00329
00330     // Do padding and rounding scenarios using round half down algorithm
00331     results = results + DoPaddingAndRoundingScenarios(RoundingAlgorithm::RoundHalfDown, 4, 3, 2);
00332
00333     OutputTextBlock->Text = results;
00334 }
Generated on Fri Nov 15 2024 22:20:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cpp/Common/StepTimer.h Source File

  • 360VideoPlayback
  • cpp
  • Common

StepTimer.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 namespace DX
00004 {
00005     // Helper class for animation and simulation timing.
00006     class StepTimer
00007     {
00008     public:
00009         StepTimer() :
00010             m_elapsedTicks(0),
00011             m_totalTicks(0),
00012             m_leftOverTicks(0),
00013             m_frameCount(0),
00014             m_framesPerSecond(0),
00015             m_framesThisSecond(0),
00016             m_qpcSecondCounter(0),
00017             m_isFixedTimeStep(false),
00018             m_targetElapsedTicks(TicksPerSecond / 60)
00019         {
00020             m_qpcFrequency = GetPerformanceFrequency();
00021
00022             // Initialize max delta to 1/10 of a second.
00023             m_qpcMaxDelta = m_qpcFrequency / 10;
00024         }
00025
00026         // Get elapsed time since the previous Update call.
00027         uint64 GetElapsedTicks() const                        { return m_elapsedTicks;                  }
00028         double GetElapsedSeconds() const                      { return TicksToSeconds(m_elapsedTicks);  }
00029
00030         // Get total time since the start of the program.
00031         uint64 GetTotalTicks() const                          { return m_totalTicks;                    }
00032         double GetTotalSeconds() const                        { return TicksToSeconds(m_totalTicks);    }
00033
00034         // Get total number of updates since start of the program.
00035         uint32 GetFrameCount() const                          { return m_frameCount;                    }
00036
00037         // Get the current framerate.
00038         uint32 GetFramesPerSecond() const                     { return m_framesPerSecond;               }
00039
00040         // Set whether to use fixed or variable timestep mode.
00041         void SetFixedTimeStep(bool isFixedTimestep)           { m_isFixedTimeStep = isFixedTimestep;    }
00042
00043         // Set how often to call Update when in fixed timestep mode.
00044         void SetTargetElapsedTicks(uint64 targetElapsed)      { m_targetElapsedTicks = targetElapsed;   }
00045         void SetTargetElapsedSeconds(double targetElapsed)    { m_targetElapsedTicks = SecondsToTicks(targetElapsed);   }
00046
00047         // Integer format represents time using 10,000,000 ticks per second.
00048         static const uint64 TicksPerSecond = 10'000'000;
00049
00050         static double TicksToSeconds(uint64 ticks)            { return static_cast<double>(ticks) / TicksPerSecond;     }
00051         static uint64 SecondsToTicks(double seconds)          { return static_cast<uint64>(seconds * TicksPerSecond);   }
00052
00053         // Convenient wrapper for QueryPerformanceFrequency. Throws an exception if
00054         // the call to QueryPerformanceFrequency fails.
00055         static inline uint64 GetPerformanceFrequency()
00056         {
00057             LARGE_INTEGER freq;
00058             if (!QueryPerformanceFrequency(&freq))
00059             {
00060                 throw ref new Platform::FailureException();
00061             }
00062             return freq.QuadPart;
00063         }
00064
00065         // Gets the current number of ticks from QueryPerformanceCounter. Throws an
00066         // exception if the call to QueryPerformanceCounter fails.
00067         static inline int64 GetTicks()
00068         {
00069             LARGE_INTEGER ticks;
00070             if (!QueryPerformanceCounter(&ticks))
00071             {
00072                 throw ref new Platform::FailureException();
00073             }
00074             return ticks.QuadPart;
00075         }
00076
00077         // After an intentional timing discontinuity (for instance a blocking IO operation)
00078         // call this to avoid having the fixed timestep logic attempt a set of catch-up
00079         // Update calls.
00080
00081         void ResetElapsedTime()
00082         {
00083             m_qpcLastTime = GetTicks();
00084
00085             m_leftOverTicks    = 0;
00086             m_framesPerSecond  = 0;
00087             m_framesThisSecond = 0;
00088             m_qpcSecondCounter = 0;
00089         }
00090
00091         // Update timer state, calling the specified Update function the appropriate number of times.
00092         template<typename TUpdate>
00093         void Tick(const TUpdate& update)
00094         {
00095             // Query the current time.
00096             uint64 currentTime = GetTicks();
00097             uint64 timeDelta   = currentTime - m_qpcLastTime;
00098
00099             m_qpcLastTime      = currentTime;
00100             m_qpcSecondCounter += timeDelta;
00101
00102             // Clamp excessively large time deltas (e.g. after paused in the debugger).
00103             if (timeDelta > m_qpcMaxDelta)
00104             {
00105                 timeDelta = m_qpcMaxDelta;
00106             }
00107
00108             // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp.
00109             timeDelta *= TicksPerSecond;
00110             timeDelta /= m_qpcFrequency;
00111
00112             uint32 lastFrameCount = m_frameCount;
00113
00114             if (m_isFixedTimeStep)
00115             {
00116                 // Fixed timestep update logic
00117
00118                 // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp
00119                 // the clock to exactly match the target value. This prevents tiny and irrelevant errors
00120                 // from accumulating over time. Without this clamping, a game that requested a 60 fps
00121                 // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually
00122                 // accumulate enough tiny errors that it would drop a frame. It is better to just round
00123                 // small deviations down to zero to leave things running smoothly.
00124
00125                 if (abs(static_cast<int64>(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000)
00126                 {
00127                     timeDelta = m_targetElapsedTicks;
00128                 }
00129
00130                 m_leftOverTicks += timeDelta;
00131
00132                 while (m_leftOverTicks >= m_targetElapsedTicks)
00133                 {
00134                     m_elapsedTicks   = m_targetElapsedTicks;
00135                     m_totalTicks    += m_targetElapsedTicks;
00136                     m_leftOverTicks -= m_targetElapsedTicks;
00137                     m_frameCount++;
00138
00139                     update();
00140                 }
00141             }
00142             else
00143             {
00144                 // Variable timestep update logic.
00145                 m_elapsedTicks  = timeDelta;
00146                 m_totalTicks   += timeDelta;
00147                 m_leftOverTicks = 0;
00148                 m_frameCount++;
00149
00150                 update();
00151             }
00152
00153             // Track the current framerate.
00154             if (m_frameCount != lastFrameCount)
00155             {
00156                 m_framesThisSecond++;
00157             }
00158
00159             if (m_qpcSecondCounter >= static_cast<uint64>(m_qpcFrequency))
00160             {
00161                 m_framesPerSecond   = m_framesThisSecond;
00162                 m_framesThisSecond  = 0;
00163                 m_qpcSecondCounter %= m_qpcFrequency;
00164             }
00165         }
00166
00167     private:
00168
00169         // Source timing data uses QPC units.
00170         uint64 m_qpcFrequency;
00171         uint64 m_qpcLastTime;
00172         uint64 m_qpcMaxDelta;
00173
00174         // Derived timing data uses a canonical tick format.
00175         uint64 m_elapsedTicks;
00176         uint64 m_totalTicks;
00177         uint64 m_leftOverTicks;
00178
00179         // Members for tracking the framerate.
00180         uint32 m_frameCount;
00181         uint32 m_framesPerSecond;
00182         uint32 m_framesThisSecond;
00183         uint64 m_qpcSecondCounter;
00184
00185         // Members for configuring fixed timestep mode.
00186         bool   m_isFixedTimeStep;
00187         uint64 m_targetElapsedTicks;
00188     };
00189 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Inclinometer/cpp/Scenario3_Calibration.xaml.cpp Source File

  • Inclinometer
  • cpp

Scenario3_Calibration.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario3_Calibration.xaml.cpp
00014 // Implementation of the Scenario3_Calibration class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario3_Calibration.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::Devices::Sensors;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::UI::Core;
00028 using namespace Platform;
00029
00030 Scenario3_Calibration::Scenario3_Calibration() : rootPage(MainPage::Current)
00031 {
00032     InitializeComponent();
00033     calibrationBar = ref new CalibrationBar();
00034 }
00035
00036 /// <summary>
00037 /// Invoked when this page is about to be displayed in a Frame.
00038 /// </summary>
00039 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00040 /// property is typically used to configure the page.</param>
00041 void Scenario3_Calibration::OnNavigatedTo(NavigationEventArgs^ e)
00042 {
00043 }
00044
00045 /// <summary>
00046 /// Invoked when this page is no longer displayed.
00047 /// </summary>
00048 /// <param name="e"></param>
00049 void Scenario3_Calibration::OnNavigatedFrom(NavigationEventArgs^ e)
00050 {
00051     // If the navigation is external to the app do not clean up.
00052     // This can occur on Phone when suspending the app.
00053     if (e->NavigationMode == NavigationMode::Forward && e->Uri == nullptr)
00054     {
00055         return;
00056     }
00057
00058     calibrationBar->Hide();
00059 }
00060
00061 /// <summary>
00062 /// This is the click handler for high accuracy. Acceptable accuracy met, so
00063 /// hide the calibration bar.
00064 /// </summary>
00065 /// <param name="sender"></param>
00066 /// <param name="e"></param>
00067 void Scenario3_Calibration::OnHighAccuracy(Object^ sender, RoutedEventArgs^ e)
00068 {
00069     calibrationBar->Hide();
00070 }
00071
00072 /// <summary>
00073 /// This is the click handler for approximate accuracy. Acceptable accuracy met, so
00074 /// hide the calibration bar.
00075 /// </summary>
00076 /// <param name="sender"></param>
00077 /// <param name="e"></param>
00078 void Scenario3_Calibration::OnApproximateAccuracy(Object^ sender, RoutedEventArgs^ e)
00079 {
00080     calibrationBar->Hide();
00081 }
00082
00083 /// <summary>
00084 /// This is the click handler for unreliable accuracy. Sensor does not meet accuracy
00085 /// requirements. Request to show the calibration bar per the calibration guidance.
00086 /// </summary>
00087 /// <param name="sender"></param>
00088 /// <param name="e"></param>
00089 void Scenario3_Calibration::OnUnreliableAccuracy(Object^ sender, RoutedEventArgs^ e)
00090 {
00091     calibrationBar->RequestCalibration(MagnetometerAccuracy::Unreliable);
00092 }
Generated on Fri Nov 15 2024 22:18:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ViewLifetimeControl Member List

This is the complete list of members for ViewLifetimeControl, including all inherited members.
consolidated | ViewLifetimeControl | [private]
Consolidated | ViewLifetimeControl |
CreateForCurrentView() | ViewLifetimeControl | [inline, static]
CreateForCurrentView() | ViewLifetimeControl | [inline, static]
Dispatcher | ViewLifetimeControl |
dispatcher | ViewLifetimeControl | [private]
FinalizeRelease() | ViewLifetimeControl | [inline, private]
FinalizeRelease() | ViewLifetimeControl | [inline, private]
Id | ViewLifetimeControl |
InternalReleased | ViewLifetimeControl | [private]
madeVisible | ViewLifetimeControl | [private]
PropertyChanged | ViewLifetimeControl |
refCount | ViewLifetimeControl | [private]
RegisterForEvents() | ViewLifetimeControl | [inline, private]
RegisterForEvents() | ViewLifetimeControl | [inline, private]
Released | ViewLifetimeControl |
released | ViewLifetimeControl | [private]
StartViewInUse() | ViewLifetimeControl | [inline]
StartViewInUse() | ViewLifetimeControl | [inline]
StopViewInUse() | ViewLifetimeControl | [inline]
StopViewInUse() | ViewLifetimeControl | [inline]
Title | ViewLifetimeControl |
title | ViewLifetimeControl | [private]
UnregisterForEvents() | ViewLifetimeControl | [inline, private]
UnregisterForEvents() | ViewLifetimeControl | [inline, private]
ViewConsolidated(ApplicationView sender, ApplicationViewConsolidatedEventArgs e) | ViewLifetimeControl | [inline, private]
ViewConsolidated(ApplicationView sender, ApplicationViewConsolidatedEventArgs e) | ViewLifetimeControl | [inline, private]
viewId | ViewLifetimeControl | [private]
ViewLifetimeControl(CoreWindow newWindow) | ViewLifetimeControl | [inline, private]
ViewLifetimeControl(CoreWindow newWindow) | ViewLifetimeControl | [inline, private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | ViewLifetimeControl | [inline, private]
window | ViewLifetimeControl | [private]
Generated on Fri Nov 15 2024 22:24:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cppwinrt/pch.h Source File

  • ResizeAppView
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.System.h"
00008 #include "winrt/Windows.UI.Core.h"
00009 #include "winrt/Windows.UI.ViewManagement.h"
00010 #include "winrt/Windows.UI.Xaml.h"
00011 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00012 #include "winrt/Windows.UI.Xaml.Controls.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00014 #include "winrt/Windows.UI.Xaml.Documents.h"
00015 #include "winrt/Windows.UI.Xaml.Interop.h"
00016 #include "winrt/Windows.UI.Xaml.Markup.h"
00017 #include "winrt/Windows.UI.Xaml.Media.h"
00018 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cpp/AppView.h Source File

  • 360VideoPlayback
  • cpp

AppView.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "Common\DeviceResources.h"
00004 #include "360VideoPlaybackMain.h"
00005
00006 namespace _360VideoPlayback
00007 {
00008     // IFrameworkView class. Connects the app with the Windows shell and handles application lifecycle events.
00009     ref class AppView sealed : public Windows::ApplicationModel::Core::IFrameworkView
00010     {
00011     public:
00012         AppView(Windows::Foundation::Uri^ sourceUri);
00013
00014         // IFrameworkView methods.
00015         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00016         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00017         virtual void Load(Platform::String^ entryPoint);
00018         virtual void Run();
00019         virtual void Uninitialize();
00020         static Windows::Media::Playback::MediaPlayer^ GetMediaPlayer();
00021
00022     protected:
00023         // Application lifecycle event handlers.
00024         void OnViewActivated(Windows::ApplicationModel::Core::CoreApplicationView^ sender, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00025         void OnMainViewActivated(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowActivatedEventArgs^ args);
00026         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00027         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00028
00029         // Window event handlers.
00030         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00031         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00032
00033         // CoreWindow input event handlers.
00034         void OnKeyPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args);
00035
00036     private:
00037         std::unique_ptr<_360VideoPlaybackMain> m_main;
00038         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00039         bool m_windowClosed = false;
00040         bool m_windowVisible = true;
00041         bool m_ShadersNeed = false;
00042         bool m_ShadersCreated = false;
00043         bool m_appViewConsolidated = false;
00044         bool m_mainWindowReactivated = false;
00045         // The holographic space the app will use for rendering.
00046         Windows::Graphics::Holographic::HolographicSpace^ m_holographicSpace = nullptr;
00047         static Windows::Media::Playback::MediaPlayer^ m_mediaPlayer;
00048         void OnConsolidated(Windows::UI::ViewManagement::ApplicationView^ sender, Windows::UI::ViewManagement::ApplicationViewConsolidatedEventArgs^ args);
00049         void OnMediaOpened(Windows::Media::Playback::MediaPlayer^ sender, Platform::Object^ args);
00050         void TryCloseWindow();
00051         Windows::Foundation::Uri^ m_sourceUri;
00052     };
00053
00054     // The entry point for the app.
00055     ref class AppViewSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00056     {
00057     public:
00058         AppViewSource(Windows::Foundation::Uri^ sourceUri);
00059         virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00060     private:
00061         Windows::Foundation::Uri^ m_sourceUri;
00062     };
00063 }
00064
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackButton/cs/SampleConfiguration.cs Source File

  • BackButton
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "SystemBack";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Subscribe to the BackRequested event", ClassType=typeof(Scenario1)},
00025         };
00026     }
00027
00028     public class Scenario
00029     {
00030         public string Title { get; set; }
00031         public Type ClassType { get; set; }
00032     }
00033 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ISecureInterfaceProducer Member List

This is the complete list of members for ISecureInterfaceProducer, including all inherited members.
SessionLost | ISecureInterfaceProducer
SessionMemberAdded | ISecureInterfaceProducer
SessionMemberRemoved | ISecureInterfaceProducer
Stopped | ISecureInterfaceProducer
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FullScreenMode/cs/Scenario1_Basic.xaml.cs Source File

  • FullScreenMode
  • cs

Scenario1_Basic.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Core;
00013 using Windows.UI.ViewManagement;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Input;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario1_Basic : Page
00022     {
00023         private MainPage rootPage;
00024
00025         // What is the program's last known full-screen state?
00026         // We use this to detect when the system forced us out of full-screen mode.
00027         private bool isLastKnownFullScreen = ApplicationView.GetForCurrentView().IsFullScreenMode;
00028
00029         public Scenario1_Basic()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             rootPage = MainPage.Current;
00037
00038             Window.Current.SizeChanged += OnWindowResize;
00039             rootPage.KeyDown += OnKeyDown;
00040             UpdateContent();
00041         }
00042
00043         protected override void OnNavigatedFrom(NavigationEventArgs e)
00044         {
00045             Window.Current.SizeChanged -= OnWindowResize;
00046             rootPage.KeyDown -= OnKeyDown;
00047         }
00048
00049         private void ToggleFullScreenModeButton_Click(object sender, RoutedEventArgs e)
00050         {
00051             var view = ApplicationView.GetForCurrentView();
00052             if (view.IsFullScreenMode)
00053             {
00054                 view.ExitFullScreenMode();
00055                 rootPage.NotifyUser("Exiting full screen mode", NotifyType.StatusMessage);
00056                 isLastKnownFullScreen = false;
00057                 // The SizeChanged event will be raised when the exit from full screen mode is complete.
00058             }
00059             else
00060             {
00061                 if (view.TryEnterFullScreenMode())
00062                 {
00063                     rootPage.NotifyUser("Entering full screen mode", NotifyType.StatusMessage);
00064                     isLastKnownFullScreen = true;
00065                     // The SizeChanged event will be raised when the entry to full screen mode is complete.
00066                 }
00067                 else
00068                 {
00069                     rootPage.NotifyUser("Failed to enter full screen mode", NotifyType.ErrorMessage);
00070                 }
00071             }
00072         }
00073
00074         private void ShowStandardSystemOverlaysButton_Click(object sender, RoutedEventArgs e)
00075         {
00076             var view = ApplicationView.GetForCurrentView();
00077             view.ShowStandardSystemOverlays();
00078         }
00079
00080         private void UseMinimalOverlaysCheckBox_Click(object sender, RoutedEventArgs e)
00081         {
00082             var view = ApplicationView.GetForCurrentView();
00083             view.FullScreenSystemOverlayMode = UseMinimalOverlaysCheckBox.IsChecked.Value ? FullScreenSystemOverlayMode.Minimal : FullScreenSystemOverlayMode.Standard;
00084         }
00085
00086         void OnWindowResize(object sender, WindowSizeChangedEventArgs e)
00087         {
00088             UpdateContent();
00089         }
00090
00091         void UpdateContent()
00092         {
00093             var view = ApplicationView.GetForCurrentView();
00094             var isFullScreenMode = view.IsFullScreenMode;
00095             ToggleFullScreenModeSymbol.Symbol = isFullScreenMode ? Symbol.BackToWindow : Symbol.FullScreen;
00096             ReportFullScreenMode.Text = isFullScreenMode ? "is in" : "is not in";
00097             FullScreenOptionsPanel.Visibility = isFullScreenMode ? Visibility.Visible : Visibility.Collapsed;
00098
00099             // Did the system force a change in full screen mode?
00100             if (isLastKnownFullScreen != isFullScreenMode)
00101             {
00102                 isLastKnownFullScreen = isFullScreenMode;
00103                 // Clear any stray messages that talked about the mode we are no longer in.
00104                 rootPage.NotifyUser("", NotifyType.StatusMessage);
00105             }
00106         }
00107
00108         void OnKeyDown(object sender, KeyRoutedEventArgs e)
00109         {
00110             if (e.Key == Windows.System.VirtualKey.Escape)
00111             {
00112                 var view = ApplicationView.GetForCurrentView();
00113                 if (view.IsFullScreenMode)
00114                 {
00115                     view.ExitFullScreenMode();
00116                     rootPage.NotifyUser("Exited full screen mode due to keypress", NotifyType.StatusMessage);
00117                     isLastKnownFullScreen = false;
00118                 }
00119             }
00120         }
00121     }
00122 }
Generated on Fri Nov 15 2024 22:19:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MessageDialog/cpp/DefaultCloseCommand.xaml.h Source File

  • MessageDialog
  • cpp

DefaultCloseCommand.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // CustomCommand.xaml.h
00013 // Declaration of the CustomCommand class
00014 //
00015
00016 #pragma once
00017
00018 #include "DefaultCloseCommand.g.h"
00019 #include "MainPage.xaml.h"
00020
00021 namespace SDKTemplate
00022 {
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class DefaultCloseCommand sealed
00025     {
00026     public:
00027         DefaultCloseCommand();
00028
00029     protected:
00030         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00031     private:
00032         MainPage^ rootPage;
00033         void DefaultCloseCommandButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034     };
00035 }
Generated on Fri Nov 15 2024 22:20:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraGetPreviewFrame/cs/App.xaml.cs Source File

  • CameraGetPreviewFrame
  • cs

App.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.Activation;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 namespace CameraGetPreviewFrame
00019 {
00020     /// <summary>
00021     /// Provides application-specific behavior to supplement the default Application class.
00022     /// </summary>
00023     sealed partial class App : Application
00024     {
00025         /// <summary>
00026         /// Initializes the singleton application object.  This is the first line of authored code
00027         /// executed, and as such is the logical equivalent of main() or WinMain().
00028         /// </summary>
00029         public App()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         /// <summary>
00035         /// Invoked when the application is launched normally by the end user.  Other entry points
00036         /// will be used such as when the application is launched to open a specific file.
00037         /// </summary>
00038         /// <param name="e">Details about the launch request and process.</param>
00039         protected override void OnLaunched(LaunchActivatedEventArgs e)
00040         {
00041
00042 #if DEBUG
00043             if (System.Diagnostics.Debugger.IsAttached)
00044             {
00045                 this.DebugSettings.EnableFrameRateCounter = true;
00046             }
00047 #endif
00048
00049             Frame rootFrame = Window.Current.Content as Frame;
00050
00051             // Do not repeat app initialization when the Window already has content,
00052             // just ensure that the window is active
00053             if (rootFrame == null)
00054             {
00055                 // Create a Frame to act as the navigation context and navigate to the first page
00056                 rootFrame = new Frame();
00057                 // Set the default language
00058                 rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
00059
00060                 rootFrame.NavigationFailed += OnNavigationFailed;
00061
00062                 // Place the frame in the current Window
00063                 Window.Current.Content = rootFrame;
00064             }
00065
00066             if (rootFrame.Content == null)
00067             {
00068                 // When the navigation stack isn't restored navigate to the first page,
00069                 // configuring the new page by passing required information as a navigation
00070                 // parameter
00071                 rootFrame.Navigate(typeof(MainPage), e.Arguments);
00072             }
00073             // Ensure the current window is active
00074             Window.Current.Activate();
00075         }
00076
00077         /// <summary>
00078         /// Invoked when Navigation to a certain page fails
00079         /// </summary>
00080         /// <param name="sender">The Frame which failed navigation</param>
00081         /// <param name="e">Details about the navigation failure</param>
00082         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00083         {
00084             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00085         }
00086     }
00087 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6_ManipulatingCursorAttributes Member List

This is the complete list of members for Scenario6_ManipulatingCursorAttributes, including all inherited members.
DisplayTextButton_Click(object sender, RoutedEventArgs e) | Scenario6_ManipulatingCursorAttributes | [inline, private]
InitializeAsync() | Scenario6_ManipulatingCursorAttributes | [inline, private]
lineDisplay | Scenario6_ManipulatingCursorAttributes | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario6_ManipulatingCursorAttributes | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario6_ManipulatingCursorAttributes | [inline, protected]
ResetButton_Click(object sender, RoutedEventArgs e) | Scenario6_ManipulatingCursorAttributes | [inline, private]
rootPage | Scenario6_ManipulatingCursorAttributes | [private]
Scenario6_ManipulatingCursorAttributes() | Scenario6_ManipulatingCursorAttributes | [inline]
UpdateButton_Click(object sender, RoutedEventArgs e) | Scenario6_ManipulatingCursorAttributes | [inline, private]
Generated on Fri Nov 15 2024 22:23:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DPhotoAdjustment/cpp/App.xaml.cpp Source File

  • D2DPhotoAdjustment
  • cpp

App.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "App.xaml.h"
00014
00015 using namespace D2DPhotoAdjustment;
00016
00017 using namespace Platform;
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::ApplicationModel::Activation;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Storage;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Controls::Primitives;
00026 using namespace Windows::UI::Xaml::Data;
00027 using namespace Windows::UI::Xaml::Input;
00028 using namespace Windows::UI::Xaml::Interop;
00029 using namespace Windows::UI::Xaml::Media;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 /// <summary>
00033 /// Initializes the singleton application object.  This is the first line of authored code
00034 /// executed, and as such is the logical equivalent of main() or WinMain().
00035 /// </summary>
00036 App::App()
00037 {
00038     InitializeComponent();
00039     Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
00040     Resuming += ref new EventHandler<Object^>(this, &App::OnResuming);
00041 }
00042
00043 /// <summary>
00044 /// Invoked when the application is launched normally by the end user.  Other entry points
00045 /// will be used when the application is launched to open a specific file, to display
00046 /// search results, and so forth.
00047 /// </summary>
00048 /// <param name="e">Details about the launch request and process.</param>
00049 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
00050 {
00051 #if _DEBUG
00052     if (IsDebuggerPresent())
00053     {
00054         DebugSettings->EnableFrameRateCounter = true;
00055     }
00056 #endif
00057
00058     if (m_directXPage == nullptr)
00059     {
00060         m_directXPage = ref new DirectXPage();
00061     }
00062
00063     if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
00064     {
00065         m_directXPage->LoadInternalState(ApplicationData::Current->LocalSettings->Values);
00066     }
00067
00068     // Place the page in the current window and ensure that it is active.
00069     Window::Current->Content = m_directXPage;
00070     Window::Current->Activate();
00071 }
00072
00073 /// <summary>
00074 /// Invoked when application execution is being suspended.  Application state is saved
00075 /// without knowing whether the application will be terminated or resumed with the contents
00076 /// of memory still intact.
00077 /// </summary>
00078 /// <param name="sender">The source of the suspend request.</param>
00079 /// <param name="e">Details about the suspend request.</param>
00080 void App::OnSuspending(Object^, SuspendingEventArgs^)
00081 {
00082     m_directXPage->SaveInternalState(ApplicationData::Current->LocalSettings->Values);
00083 }
00084
00085 /// <summary>
00086 /// Invoked when application execution is being resumed.
00087 /// </summary>
00088 /// <param name="sender">The source of the resume request.</param>
00089 /// <param name="args">Details about the resume request.</param>
00090 void App::OnResuming(Object^, Object^)
00091 {
00092     m_directXPage->LoadInternalState(ApplicationData::Current->LocalSettings->Values);
00093 }
Generated on Fri Nov 15 2024 22:16:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JapanesePhoneticAnalysis/cpp/Scenario1_Analyze.xaml.h Source File

  • JapanesePhoneticAnalysis
  • cpp

Scenario1_Analyze.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Analyze.g.h"
00015
00016 namespace SDKTemplate
00017 {
00018     [Windows::Foundation::Metadata::WebHostHidden]
00019     public ref class Scenario1_Analyze sealed
00020     {
00021     public:
00022         Scenario1_Analyze();
00023     private:
00024         void AnalyzeButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00025     };
00026 }
Generated on Fri Nov 15 2024 22:20:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_BackgroundTask Member List

This is the complete list of members for Scenario3_BackgroundTask, including all inherited members.
_geolocTask | Scenario3_BackgroundTask | [private]
_rootPage | Scenario3_BackgroundTask | [private]
BackgroundTaskEntryPoint | Scenario3_BackgroundTask | [private]
BackgroundTaskName | Scenario3_BackgroundTask | [private]
OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e) | Scenario3_BackgroundTask | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario3_BackgroundTask | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_BackgroundTask | [inline, protected]
RegisterBackgroundTask(object sender, RoutedEventArgs e) | Scenario3_BackgroundTask | [inline, private]
Scenario3_BackgroundTask() | Scenario3_BackgroundTask | [inline]
UnregisterBackgroundTask(object sender, RoutedEventArgs e) | Scenario3_BackgroundTask | [inline, private]
UpdateButtonStates() | Scenario3_BackgroundTask | [inline, private]
Generated on Fri Nov 15 2024 22:23:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PresenceSensor/cppwinrt/pch.h Source File

  • PresenceSensor
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Devices.Enumeration.h"
00008 #include "winrt/Windows.Devices.Sensors.h"
00009 #include "winrt/Windows.Globalization.DateTimeFormatting.h"
00010 #include "winrt/Windows.System.h"
00011 #include "winrt/Windows.UI.Core.h"
00012 #include "winrt/Windows.UI.Xaml.h"
00013 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00014 #include "winrt/Windows.UI.Xaml.Controls.h"
00015 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00016 #include "winrt/Windows.UI.Xaml.Documents.h"
00017 #include "winrt/Windows.UI.Xaml.Interop.h"
00018 #include "winrt/Windows.UI.Xaml.Markup.h"
00019 #include "winrt/Windows.UI.Xaml.Media.h"
00020 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/Common.h Source File

  • WindowsAudioSession
  • cppwinrt

Common.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 namespace winrt::SDKTemplate
00014 {
00015     // RAII helper class to ensure something happens even in case of exception.
00016     template<typename Lambda>
00017     struct scope_exit
00018     {
00019         scope_exit(Lambda&& lambda) : m_lambda(std::move(lambda)) {}
00020         ~scope_exit() { m_lambda(); }
00021
00022         scope_exit(const scope_exit&) = delete;
00023         void operator=(const scope_exit&) = delete;
00024
00025         Lambda m_lambda;
00026     };
00027
00028     // RAII class to initialize Media Foundation.
00029     struct MediaFoundationInitializer
00030     {
00031         MediaFoundationInitializer()
00032         {
00033             // Initialize MF
00034             check_hresult(MFStartup(MF_VERSION, MFSTARTUP_LITE));
00035         }
00036
00037         ~MediaFoundationInitializer()
00038         {
00039             MFShutdown();
00040         }
00041     };
00042
00043     // RAII class to lock/unlock a shared work queue.
00044     struct unique_shared_work_queue
00045     {
00046         unique_shared_work_queue(PCWSTR className)
00047         {
00048             DWORD taskId = 0; // 0 means "create a new task group"
00049             check_hresult(MFLockSharedWorkQueue(className, 0, &taskId, &m_queueId));
00050         }
00051
00052         ~unique_shared_work_queue()
00053         {
00054             MFUnlockWorkQueue(m_queueId);
00055         }
00056
00057         unique_shared_work_queue(unique_shared_work_queue const&) = delete;
00058         void operator=(unique_shared_work_queue const&) = delete;
00059
00060         DWORD get() { return m_queueId; }
00061     private:
00062         DWORD m_queueId = 0;
00063     };
00064
00065     // RAII class analogous to std::unique_ptr, but calls CoTaskMemFree instead of delete.
00066     template<typename T>
00067     struct unique_cotaskmem_ptr
00068     {
00069         unique_cotaskmem_ptr(T* p = nullptr) : m_p(p) {}
00070         ~unique_cotaskmem_ptr() { CoTaskMemFree(m_p); }
00071
00072         unique_cotaskmem_ptr(unique_cotaskmem_ptr const&) = delete;
00073         unique_cotaskmem_ptr(unique_cotaskmem_ptr&& other) : m_p(std::exchange(other.m_p, nullptr)) {}
00074         unique_cotaskmem_ptr& operator=(unique_cotaskmem_ptr const& other)
00075         {
00076             CoTaskMemFree(std::exchange(m_p, std::exchange(other.m_p, nullptr)));
00077             return *this;
00078         }
00079
00080         T* operator->() { return m_p; }
00081         T* get() { return m_p; }
00082         T** put() { return &m_p; }
00083         T* m_p;
00084     };
00085
00086     // Helper class for allowing a class to implement multiple versions of
00087     // IMFAsyncCallback.
00088     template<auto Callback>
00089     struct EmbeddedMFAsyncCallback : ::IMFAsyncCallback
00090     {
00091         template<typename Parent> static Parent* parent_finder(HRESULT(Parent::*)(IMFAsyncResult*)) { return nullptr; }
00092         using ParentPtr = decltype(parent_finder(Callback));
00093
00094         ParentPtr m_parent;
00095         DWORD m_queueId = 0;
00096
00097         EmbeddedMFAsyncCallback(ParentPtr parent) : m_parent(parent) {}
00098
00099         STDMETHOD(QueryInterface)(REFIID riid, void** ppvObject) final
00100         {
00101             if (is_guid_of<::IMFAsyncCallback, ::IUnknown>(riid))
00102             {
00103                 (*ppvObject) = this;
00104                 AddRef();
00105                 return S_OK;
00106             }
00107             *ppvObject = nullptr;
00108             return E_NOINTERFACE;
00109         }
00110
00111         STDMETHOD_(ULONG, AddRef)() final { return m_parent->AddRef(); }
00112         STDMETHOD_(ULONG, Release)() final { return m_parent->Release(); }
00113
00114         STDMETHOD(GetParameters)(DWORD* flags, DWORD* queueId) final
00115         {
00116             *flags = 0;
00117             *queueId = m_queueId;
00118             return S_OK;
00119         }
00120
00121         STDMETHOD(Invoke)(IMFAsyncResult* result) final
00122         {
00123             return (m_parent->*Callback)(result);
00124         }
00125
00126         void SetQueueID(DWORD queueId) { m_queueId = queueId; }
00127     };
00128
00129     struct RenderBuffer
00130     {
00131         uint32_t BufferSize;
00132         uint32_t BytesFilled;
00133         std::unique_ptr<BYTE[]> Buffer;
00134
00135         RenderBuffer(uint32_t size) :
00136             BufferSize(size),
00137             BytesFilled(size),
00138             Buffer(new BYTE[size])
00139         {
00140         }
00141     };
00142
00143     enum class RenderSampleType
00144     {
00145         Unknown,
00146         Float,
00147         Pcm16Bit,
00148         Pcm24In32Bit,
00149     };
00150
00151     //
00152     //  GetRenderSampleType()
00153     //
00154     //  Determine the sample format based on media type
00155     //
00156     inline RenderSampleType GetRenderSampleType(WAVEFORMATEX const* wfx)
00157     {
00158         WAVEFORMATEXTENSIBLE const* wfext = reinterpret_cast<WAVEFORMATEXTENSIBLE const*>(wfx);
00159
00160         if ((wfx->wFormatTag == WAVE_FORMAT_PCM) ||
00161             ((wfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
00162                 (wfext->SubFormat == KSDATAFORMAT_SUBTYPE_PCM)))
00163         {
00164             if (wfx->wBitsPerSample == 16)
00165             {
00166                 return RenderSampleType::Pcm16Bit;
00167             }
00168             else if (wfx->wBitsPerSample == 32)
00169             {
00170                 if ((wfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
00171                     (wfext->Samples.wValidBitsPerSample == 24))
00172                 {
00173                     return RenderSampleType::Pcm24In32Bit;
00174                 }
00175             }
00176         }
00177         else if ((wfx->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) ||
00178             ((wfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) &&
00179                 (wfext->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)))
00180         {
00181             return RenderSampleType::Float;
00182         }
00183
00184         return RenderSampleType::Unknown;
00185     }
00186 }
Generated on Fri Nov 15 2024 22:22:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario03_GetList.h Source File

  • HttpClient
  • cppwinrt

Scenario03_GetList.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario03_GetList.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario03_GetList : Scenario03_GetListT<Scenario03_GetList>
00020     {
00021         Scenario03_GetList();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025
00026         fire_and_forget Start_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         void Cancel_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028
00029     private:
00030         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00031         Windows::Web::Http::HttpClient httpClient{ nullptr };
00032         Windows::Foundation::IAsyncAction pendingAction{ nullptr };
00033
00034         Windows::Foundation::IAsyncAction CancelableRequestAsync(Windows::Foundation::Uri resourceUri);
00035     };
00036 }
00037
00038 namespace winrt::SDKTemplate::factory_implementation
00039 {
00040     struct Scenario03_GetList : Scenario03_GetListT<Scenario03_GetList, implementation::Scenario03_GetList>
00041     {
00042     };
00043 }
Generated on Fri Nov 15 2024 22:19:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserConsentVerifier/cpp/pch.cpp Source File

  • UserConsentVerifier
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteLineSpacingModes/cpp/DWriteTextLayoutImplementation/TextLayout.h Source File

  • DWriteLineSpacingModes
  • cpp
  • DWriteTextLayoutImplementation

TextLayout.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace DWriteTextLayoutImplementation
00015 {
00016     // Wrapper for DWRITE_LINE_SPACING_METHOD enumeration.
00017     // The DWRITE_LINE_SPACING_METHOD enumeration is defined in dwrite.h.
00018     public enum class LineSpacingMethod
00019     {
00020         // Default line spacing depends solely on the content, growing
00021         // to accommodate the size of fonts and inline objects.
00022         Default = DWRITE_LINE_SPACING_METHOD_DEFAULT,
00023
00024         // Uniform line spacing: the spacing of all lines is determined by
00025         // values provided by the app in a DWRITE_LINE_SPACING structure.
00026         // One use of uniform spacing is to avoid the uneven appearance
00027         // that can occur from font fallback.
00028         Uniform = DWRITE_LINE_SPACING_METHOD_UNIFORM,
00029
00030         // Proportional line spacing: the spacing and baseline distances
00031         // are based on the computed values based on the content, as with
00032         // default spacing, but adjusted proportionally by scaling factors
00033         // you provide in a DWRITE_LINE_SPACING structure.
00034         Proportional = DWRITE_LINE_SPACING_METHOD_PROPORTIONAL
00035     };
00036
00037     // Wrapper for DWRITE_FONT_LINE_GAP_USAGE enumeration. The
00038     // DWRITE_FONT_LINE_GAP_USAGE enumeration is defined in dwrite_3.h.
00039     public enum class FontLineGapUsage
00040     {
00041         // Use default behavior for line gap usage. (This is different
00042         // for GDI-compatible text layout than for normal text layout.)
00043         Default = DWRITE_FONT_LINE_GAP_USAGE_DEFAULT,
00044
00045         // The font line gap is excluded from line spacing.
00046         Disabled = DWRITE_FONT_LINE_GAP_USAGE_DISABLED,
00047
00048         // The font line gap is included in line spacing.
00049         Enabled = DWRITE_FONT_LINE_GAP_USAGE_ENABLED
00050     };
00051
00052
00053     // Wrapper for DWRITE_LINE_METRICS1 structure.
00054     public ref class LineMetrics sealed
00055     {
00056     public:
00057         property uint32 length                   { uint32 get() { return m_lineMetrics.length; } }
00058         property uint32 trailingWhitespaceLength { uint32 get() { return m_lineMetrics.trailingWhitespaceLength; } }
00059         property uint32 newlineLength            { uint32 get() { return m_lineMetrics.newlineLength; } }
00060         property bool   isTrimmed                { bool   get() { return !!m_lineMetrics.isTrimmed; } }
00061         property float  height                   { float  get() { return m_lineMetrics.height; } }
00062         property float  baseline                 { float  get() { return m_lineMetrics.baseline; } }
00063         property float  leadingBefore            { float  get() { return m_lineMetrics.leadingBefore; } }
00064         property float  leadingAfter             { float  get() { return m_lineMetrics.leadingAfter; } }
00065
00066     internal:
00067         void SetLineMetrics(DWRITE_LINE_METRICS1 lineMetrics) { m_lineMetrics = lineMetrics; }
00068
00069     private:
00070         DWRITE_LINE_METRICS1 m_lineMetrics;
00071     };
00072
00073
00074
00075     public ref class TextLayout sealed
00076     {
00077     public:
00078         TextLayout(
00079             Platform::String^ text,
00080             Platform::String^ languageTag,
00081             Platform::String^ fontFamily,
00082             float fontSize,
00083             uint32 pixelWidth,
00084             DWriteTextLayoutImplementation::LineSpacingMethod lineSpacingMethod
00085             );
00086
00087         Platform::Array<LineMetrics^>^ GetTextLayoutLineMetrics();
00088
00089         property uint32 Width
00090         {
00091             uint32 get() { return m_pixelWidth; }
00092         }
00093
00094         property uint32 Height
00095         {
00096             uint32 get() { return m_pixelHeight; }
00097         }
00098
00099         property DWriteTextLayoutImplementation::LineSpacingMethod LineSpacingMethod
00100         {
00101             DWriteTextLayoutImplementation::LineSpacingMethod get()
00102             {
00103                 return static_cast<DWriteTextLayoutImplementation::LineSpacingMethod>(m_lineSpacing.method);
00104             }
00105
00106             void set(DWriteTextLayoutImplementation::LineSpacingMethod value);
00107         }
00108
00109         property float LineSpacingHeight
00110         {
00111             float get() { return m_lineSpacing.height; }
00112             void set(float value);
00113         }
00114
00115         property float LineSpacingBaseline
00116         {
00117             float get() { return m_lineSpacing.baseline; }
00118             void set(float value);
00119         }
00120
00121         property float LineSpacingLeadingBefore
00122         {
00123             float get() { return m_lineSpacing.leadingBefore; }
00124             void set(float value);
00125         }
00126
00127         property FontLineGapUsage FontLineGapUsage
00128         {
00129             DWriteTextLayoutImplementation::FontLineGapUsage get()
00130             {
00131                 return static_cast<DWriteTextLayoutImplementation::FontLineGapUsage>(m_lineSpacing.fontLineGapUsage);
00132             }
00133
00134             void set(DWriteTextLayoutImplementation::FontLineGapUsage value);
00135         }
00136
00137
00138     internal:
00139         Microsoft::WRL::ComPtr<IDWriteTextLayout> GetDWriteTextLayout() { return m_textLayout.Get(); }
00140         DWRITE_TEXT_METRICS GetTextMetrics();
00141         std::vector<DWRITE_LINE_METRICS1> GetLineMetrics();
00142
00143     private:
00144         void SetLineSpacingDefaults();
00145         void SetLineSpacing();
00146         void InvalidateLayout();
00147         void UpdateCachedMetrics();
00148         void EnsureCachedLineMetrics();
00149
00150         std::wstring                                        m_text;
00151         std::wstring                                        m_languageTag;
00152         std::wstring                                        m_fontFamily;
00153         float                                               m_fontSize;
00154         uint32                                              m_pixelWidth; // set in constructor
00155         uint32                                              m_pixelHeight; // derived from layout
00156
00157         // DirectWrite objects
00158         Microsoft::WRL::ComPtr<IDWriteFactory3>             m_dwriteFactory;
00159         Microsoft::WRL::ComPtr<IDWriteTextLayout3>          m_textLayout;
00160
00161         // The DWRITE_LINE_SPACING structure is defined in dwrite_3.h and has
00162         // these members which are used to control the line spacing behavior:
00163         //     DWRITE_LINE_SPACING_METHOD method
00164         //     float height
00165         //     float baseline
00166         //     float leadingBefore
00167         //     DWRITE_FONT_LINE_GAP_USAGE fontLineGapUsage
00168         // The method selected will determine different interpretation and
00169         // effect for the other members. See dwrite_3.h for details.
00170         DWRITE_LINE_SPACING                                 m_lineSpacing;
00171
00172         // The DWRITE_LINE_METRICS1 structure is defined in dwrite_3.h and
00173         // is used to report computed metrics for a given line of a text
00174         // layout after the layout has been performed. It includes these
00175         // members:
00176         //     float height
00177         //     float baseline
00178         //     float leadingBefore
00179         //     float leadingAfter
00180         std::vector<DWRITE_LINE_METRICS1>                   m_lineMetrics;
00181     };
00182 }
Generated on Fri Nov 15 2024 22:19:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/Common/DeviceResources.h Source File

  • SpatialInteractionSource
  • cpp
  • Common

DeviceResources.h

Go to the documentation of this file.
00001 ﻿
00002 #pragma once
00003
00004 #include "CameraResources.h"
00005
00006 namespace DX
00007 {
00008     // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created.
00009     interface IDeviceNotify
00010     {
00011         virtual void OnDeviceLost()     = 0;
00012         virtual void OnDeviceRestored() = 0;
00013     };
00014
00015     // Creates and manages a Direct3D device and immediate context, Direct2D device and context (for debug), and the holographic swap chain.
00016     class DeviceResources
00017     {
00018     public:
00019         DeviceResources();
00020
00021         // Public methods related to Direct3D devices.
00022         void HandleDeviceLost();
00023         void RegisterDeviceNotify(IDeviceNotify* deviceNotify);
00024         void Trim();
00025         void Present(Windows::Graphics::Holographic::HolographicFrame^ frame);
00026
00027         // Public methods related to holographic devices.
00028         void SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^ space);
00029         void EnsureCameraResources(
00030             Windows::Graphics::Holographic::HolographicFrame^ frame,
00031             Windows::Graphics::Holographic::HolographicFramePrediction^ prediction);
00032
00033         void AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^ camera);
00034         void RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^ camera);
00035
00036         // Holographic accessors.
00037         template<typename RetType, typename LCallback>
00038         RetType                 UseHolographicCameraResources(const LCallback& callback);
00039
00040         Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^
00041                                 GetD3DInteropDevice() const             { return m_d3dInteropDevice;    }
00042
00043         // D3D accessors.
00044         ID3D11Device4*          GetD3DDevice() const                    { return m_d3dDevice.Get();     }
00045         ID3D11DeviceContext3*   GetD3DDeviceContext() const             { return m_d3dContext.Get();    }
00046         D3D_FEATURE_LEVEL       GetDeviceFeatureLevel() const           { return m_d3dFeatureLevel;     }
00047         bool                    GetDeviceSupportsVprt() const           { return m_supportsVprt;        }
00048
00049         // DXGI acessors.
00050         IDXGIAdapter3*          GetDXGIAdapter() const                  { return m_dxgiAdapter.Get();   }
00051
00052         // D2D accessors.
00053         ID2D1Factory2*          GetD2DFactory() const                   { return m_d2dFactory.Get();    }
00054         IDWriteFactory2*        GetDWriteFactory() const                { return m_dwriteFactory.Get(); }
00055         IWICImagingFactory2*    GetWicImagingFactory() const            { return m_wicFactory.Get();    }
00056
00057     private:
00058         // Private methods related to the Direct3D device, and resources based on that device.
00059         void CreateDeviceIndependentResources();
00060         void InitializeUsingHolographicSpace();
00061         void CreateDeviceResources();
00062
00063         // Direct3D objects.
00064         Microsoft::WRL::ComPtr<ID3D11Device4>                   m_d3dDevice;
00065         Microsoft::WRL::ComPtr<ID3D11DeviceContext3>            m_d3dContext;
00066         Microsoft::WRL::ComPtr<IDXGIAdapter3>                   m_dxgiAdapter;
00067
00068         // Direct3D interop objects.
00069         Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^ m_d3dInteropDevice;
00070
00071         // Direct2D factories.
00072         Microsoft::WRL::ComPtr<ID2D1Factory2>                   m_d2dFactory;
00073         Microsoft::WRL::ComPtr<IDWriteFactory2>                 m_dwriteFactory;
00074         Microsoft::WRL::ComPtr<IWICImagingFactory2>             m_wicFactory;
00075
00076         // The holographic space provides a preferred DXGI adapter ID.
00077         Windows::Graphics::Holographic::HolographicSpace^       m_holographicSpace = nullptr;
00078
00079         // Properties of the Direct3D device currently in use.
00080         D3D_FEATURE_LEVEL                                       m_d3dFeatureLevel = D3D_FEATURE_LEVEL_10_0;
00081
00082         // The IDeviceNotify can be held directly as it owns the DeviceResources.
00083         IDeviceNotify*                                          m_deviceNotify = nullptr;
00084
00085         // Whether or not the current Direct3D device supports the optional feature
00086         // for setting the render target array index from the vertex shader stage.
00087         bool                                                    m_supportsVprt = false;
00088
00089         // Back buffer resources, etc. for attached holographic cameras.
00090         std::map<UINT32, std::unique_ptr<CameraResources>>      m_cameraResources;
00091         std::mutex                                              m_cameraResourcesLock;
00092     };
00093 }
00094
00095 // Device-based resources for holographic cameras are stored in a std::map. Access this list by providing a
00096 // callback to this function, and the std::map will be guarded from add and remove
00097 // events until the callback returns. The callback is processed immediately and must
00098 // not contain any nested calls to UseHolographicCameraResources.
00099 // The callback takes a parameter of type std::map<UINT32, std::unique_ptr<DX::CameraResources>>&
00100 // through which the list of cameras will be accessed.
00101 template<typename RetType, typename LCallback>
00102 RetType DX::DeviceResources::UseHolographicCameraResources(const LCallback& callback)
00103 {
00104     std::lock_guard<std::mutex> guard(m_cameraResourcesLock);
00105     return callback(m_cameraResources);
00106 }
00107
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/ComputeShader/DeviceResources.h Source File

  • D2DCustomEffects
  • cpp
  • ComputeShader

DeviceResources.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace DX
00015 {
00016     // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created.
00017     interface IDeviceNotify
00018     {
00019         virtual void OnDeviceLost() = 0;
00020         virtual void OnDeviceRestored() = 0;
00021     };
00022
00023     // Controls all the DirectX device resources.
00024     class DeviceResources
00025     {
00026     public:
00027         DeviceResources();
00028         DeviceResources(_In_ bool forceWarpDevice);
00029         void SetWindow(Windows::UI::Core::CoreWindow^ window);
00030         void SetLogicalSize(Windows::Foundation::Size logicalSize);
00031         void SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation);
00032         void SetDpi(float dpi);
00033         void ValidateDevice();
00034         void HandleDeviceLost();
00035         void RegisterDeviceNotify(IDeviceNotify* deviceNotify);
00036         void Trim();
00037         void Present();
00038
00039         // Device Accessors.
00040         Windows::Foundation::Size GetOutputSize() const                 { return m_outputSize; }
00041         Windows::Foundation::Size GetLogicalSize() const                { return m_logicalSize; }
00042
00043         // D3D Accessors.
00044         ID3D11Device2*          GetD3DDevice() const                    { return m_d3dDevice.Get(); }
00045         ID3D11DeviceContext3*   GetD3DDeviceContext() const             { return m_d3dContext.Get(); }
00046         IDXGISwapChain1*        GetSwapChain() const                    { return m_swapChain.Get(); }
00047         D3D_FEATURE_LEVEL       GetDeviceFeatureLevel() const           { return m_d3dFeatureLevel; }
00048         ID3D11RenderTargetView* GetBackBufferRenderTargetView() const   { return m_d3dRenderTargetView.Get(); }
00049         ID3D11DepthStencilView* GetDepthStencilView() const             { return m_d3dDepthStencilView.Get(); }
00050         D3D11_VIEWPORT          GetScreenViewport() const               { return m_screenViewport; }
00051         DirectX::XMFLOAT4X4     GetOrientationTransform3D() const       { return m_orientationTransform3D; }
00052
00053         // D2D Accessors.
00054         ID2D1Factory3*          GetD2DFactory() const                   { return m_d2dFactory.Get(); }
00055         ID2D1Device2*           GetD2DDevice() const                    { return m_d2dDevice.Get(); }
00056         ID2D1DeviceContext2*    GetD2DDeviceContext() const             { return m_d2dContext.Get(); }
00057         ID2D1Bitmap1*           GetD2DTargetBitmap() const              { return m_d2dTargetBitmap.Get(); }
00058         IDWriteFactory2*        GetDWriteFactory() const                { return m_dwriteFactory.Get();  }
00059         IWICImagingFactory2*    GetWicImagingFactory() const            { return m_wicFactory.Get(); }
00060         D2D1::Matrix3x2F        GetOrientationTransform2D() const       { return m_orientationTransform2D; }
00061
00062     private:
00063         void CreateDeviceIndependentResources();
00064         void CreateDeviceResources();
00065         void CreateWindowSizeDependentResources();
00066         DXGI_MODE_ROTATION ComputeDisplayRotation();
00067
00068         // Direct3D objects.
00069         Microsoft::WRL::ComPtr<ID3D11Device2>           m_d3dDevice;
00070         Microsoft::WRL::ComPtr<ID3D11DeviceContext3>    m_d3dContext;
00071         Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00072
00073         // Direct3D rendering objects. Required for 3D.
00074         Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00075         Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00076         D3D11_VIEWPORT                                  m_screenViewport;
00077
00078         // Direct2D drawing components.
00079         Microsoft::WRL::ComPtr<ID2D1Factory3>       m_d2dFactory;
00080         Microsoft::WRL::ComPtr<ID2D1Device2>        m_d2dDevice;
00081         Microsoft::WRL::ComPtr<ID2D1DeviceContext2> m_d2dContext;
00082         Microsoft::WRL::ComPtr<ID2D1Bitmap1>        m_d2dTargetBitmap;
00083
00084         // DirectWrite drawing components.
00085         Microsoft::WRL::ComPtr<IDWriteFactory2>     m_dwriteFactory;
00086         Microsoft::WRL::ComPtr<IWICImagingFactory2> m_wicFactory;
00087
00088         // Cached reference to the Window.
00089         Platform::Agile<Windows::UI::Core::CoreWindow> m_window;
00090
00091         // Cached device properties.
00092         D3D_FEATURE_LEVEL                               m_d3dFeatureLevel;
00093         Windows::Foundation::Size                       m_d3dRenderTargetSize;
00094         Windows::Foundation::Size                       m_outputSize;
00095         Windows::Foundation::Size                       m_logicalSize;
00096         Windows::Graphics::Display::DisplayOrientations m_nativeOrientation;
00097         Windows::Graphics::Display::DisplayOrientations m_currentOrientation;
00098         float                                           m_dpi;
00099         bool                                            m_forceWarpDevice;
00100
00101         // Transforms used for display orientation.
00102         D2D1::Matrix3x2F    m_orientationTransform2D;
00103         DirectX::XMFLOAT4X4 m_orientationTransform3D;
00104
00105         // The IDeviceNotify can be held directly as it owns the DeviceResources.
00106         IDeviceNotify* m_deviceNotify;
00107     };
00108 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Personalization/cpp/pch.cpp Source File

  • Personalization
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cs/Scenario3_Text.xaml.cs Source File

  • FileAccess
  • cs

Scenario3_Text.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.IO;
00014 using Windows.Storage;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// Writing and reading text in a file.
00023     /// </summary>
00024     public sealed partial class Scenario3 : Page
00025     {
00026         MainPage rootPage = MainPage.Current;
00027
00028         public Scenario3()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         protected override void OnNavigatedTo(NavigationEventArgs e)
00034         {
00035             rootPage.ValidateFile();
00036         }
00037
00038         private async void WriteTextButton_Click(object sender, RoutedEventArgs e)
00039         {
00040             StorageFile file = rootPage.sampleFile;
00041             if (file != null)
00042             {
00043                 try
00044                 {
00045                     string userContent = InputTextBox.Text;
00046                     await FileIO.WriteTextAsync(file, userContent);
00047                     rootPage.NotifyUser($"The following text was written to '{file.Name}':\n{userContent}", NotifyType.StatusMessage);
00048                 }
00049                 catch (FileNotFoundException)
00050                 {
00051                     rootPage.NotifyUserFileNotExist();
00052                 }
00053                 catch (Exception ex)
00054                 {
00055                     // I/O errors are reported as exceptions.
00056                     rootPage.NotifyUser($"Error writing to '{file.Name}': {ex.Message}", NotifyType.ErrorMessage);
00057                 }
00058             }
00059             else
00060             {
00061                 rootPage.NotifyUserFileNotExist();
00062             }
00063         }
00064
00065         private async void ReadTextButton_Click(object sender, RoutedEventArgs e)
00066         {
00067             StorageFile file = rootPage.sampleFile;
00068             if (file != null)
00069             {
00070                 try
00071                 {
00072                     string fileContent = await FileIO.ReadTextAsync(file);
00073                     rootPage.NotifyUser($"The following text was read from '{file.Name}':\n{fileContent}", NotifyType.StatusMessage);
00074                 }
00075                 catch (FileNotFoundException)
00076                 {
00077                     rootPage.NotifyUserFileNotExist();
00078                 }
00079                 catch (Exception ex) when (ex.HResult == MainPage.E_NO_UNICODE_TRANSLATION)
00080                 {
00081                     rootPage.NotifyUser("Could not decode file to Unicode.", NotifyType.ErrorMessage);
00082                 }
00083                 catch (Exception ex)
00084                 {
00085                     // I/O errors are reported as exceptions.
00086                     rootPage.NotifyUser($"Error reading from '{file.Name}': {ex.Message}", NotifyType.ErrorMessage);
00087                 }
00088             }
00089             else
00090             {
00091                 rootPage.NotifyUserFileNotExist();
00092             }
00093         }
00094     }
00095 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_DataEvents Member List

This is the complete list of members for Scenario1_DataEvents, including all inherited members.
_desiredReportInterval | Scenario1_DataEvents | [private]
_inclinometer | Scenario1_DataEvents | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_DataEvents | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario1_DataEvents | [inline, protected]
ReadingChanged(object sender, InclinometerReadingChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
rootPage | Scenario1_DataEvents | [private]
Scenario1_DataEvents() | Scenario1_DataEvents | [inline]
ScenarioDisable(object sender, RoutedEventArgs e) | Scenario1_DataEvents | [inline, private]
ScenarioEnable(object sender, RoutedEventArgs e) | Scenario1_DataEvents | [inline, private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MarkHotProducts Member List

This is the complete list of members for MarkHotProducts, including all inherited members.
MarkHotProducts() | MarkHotProducts | [inline]
OnNavigatedTo(NavigationEventArgs e) | MarkHotProducts | [inline, protected]
rootPage | MarkHotProducts | [private]
Scenario2BtnDefault_Click(object sender, RoutedEventArgs e) | MarkHotProducts | [inline, private]
Scenario2BtnSave_Click(object sender, RoutedEventArgs e) | MarkHotProducts | [inline, private]
Scenario2Init() | MarkHotProducts | [inline, private]
Generated on Fri Nov 15 2024 22:24:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationData/cppwinrt/Scenario3_SettingContainer.h Source File

  • ApplicationData
  • cppwinrt

Scenario3_SettingContainer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_SettingContainer.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario3_SettingContainer : Scenario3_SettingContainerT<Scenario3_SettingContainer>
00020     {
00021         Scenario3_SettingContainer();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00024         void CreateContainer_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00025         void DeleteContainer_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00026         void WriteSetting_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00027         void DeleteSetting_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00028
00029     private:
00030
00031         void DisplayOutput();
00032
00033         Windows::Storage::ApplicationDataContainer localSettings = Windows::Storage::ApplicationData::Current().LocalSettings();
00034
00035         inline static const auto containerName = L"exampleContainer";
00036         inline static const auto settingName = L"exampleSetting";
00037     };
00038 }
00039
00040 namespace winrt::SDKTemplate::factory_implementation
00041 {
00042     struct Scenario3_SettingContainer : Scenario3_SettingContainerT<Scenario3_SettingContainer, implementation::Scenario3_SettingContainer>
00043     {
00044     };
00045 }
00046
Generated on Fri Nov 15 2024 22:17:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cs/Scenario1_SimpleListView.xaml.cs Source File

  • XamlListView
  • cs

Scenario1_SimpleListView.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014
00015 namespace SDKTemplate
00016 {
00017     public sealed partial class Scenario1_SimpleListView : Page
00018     {
00019         public Scenario1_SimpleListView()
00020         {
00021             InitializeComponent();
00022             ContactsCVS.Source = Contact.GetContactsGrouped(250);
00023         }
00024     }
00025 }
Generated on Fri Nov 15 2024 22:22:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OCR/cppwinrt/pch.cpp Source File

  • OCR
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/SampleConfiguration.h Source File

  • Geolocation
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     bool TryParseUInt(const wchar_t* str, uint32_t& result);
00018     wchar_t* TryParseUIntPrefix(const wchar_t* str, uint32_t& result);
00019     bool TryParseDouble(const wchar_t* str, double& result);
00020
00021     hstring FormatDateTime(Windows::Foundation::DateTime value, hstring const& format);
00022
00023     Windows::ApplicationModel::Background::IBackgroundTaskRegistration LookupBackgroundTask(hstring const& name);
00024     fire_and_forget CheckBackgroundAndRequestLocationAccess();
00025
00026     void FillItemsFromSavedJson(Windows::UI::Xaml::Controls::ItemsControl const& itemsControl, hstring const& key);
00027     void ReportSavedStatus();
00028
00029     hstring to_message();
00030 }
00031
00032 namespace winrt
00033 {
00034     hstring to_hstring(Windows::Foundation::IReference<double> const& value);
00035     hstring to_hstring(Windows::Foundation::TimeSpan value);
00036     hstring to_hstring(Windows::Devices::Geolocation::PositionSource value);
00037     hstring to_hstring(Windows::Devices::Geolocation::VisitStateChange value);
00038     hstring to_hstring(Windows::Devices::Geolocation::Geofencing::GeofenceState value);
00039     hstring to_hstring(Windows::Devices::Geolocation::Geofencing::GeofenceMonitorStatus value);
00040     hstring to_hstring(Windows::Devices::Geolocation::Geofencing::GeofenceRemovalReason value);
00041 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario10_SetCookie.cpp Source File

  • HttpClient
  • cppwinrt

Scenario10_SetCookie.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario10_SetCookie.h"
00014 #include "Scenario10_SetCookie.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace winrt::Windows::Foundation;
00018 using namespace winrt::Windows::UI::Xaml;
00019 using namespace winrt::Windows::Web::Http;
00020 using namespace winrt::Windows::Web::Http::Filters;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     Scenario10_SetCookie::Scenario10_SetCookie()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     void Scenario10_SetCookie::SetCookie_Click(IInspectable const&, RoutedEventArgs const&)
00030     {
00031         hstring name = NameField().Text();
00032         hstring domain = DomainField().Text();
00033         hstring path = PathField().Text();
00034
00035         if (name.empty() || domain.empty() || path.empty())
00036         {
00037             rootPage.NotifyUser(L"Invalid name, domain, or path value.", NotifyType::ErrorMessage);
00038             return;
00039         }
00040
00041         try
00042         {
00043             HttpCookie cookie(name, domain, path);
00044             cookie.Value(ValueField().Text());
00045
00046             if (NullCheckBox().IsChecked().Value())
00047             {
00048                 cookie.Expires(nullptr);
00049             }
00050             else
00051             {
00052                 cookie.Expires(ExpiresDatePicker().Date() + ExpiresTimePicker().Time());
00053             }
00054
00055             cookie.Secure(SecureToggle().IsOn());
00056             cookie.HttpOnly(HttpOnlyToggle().IsOn());
00057
00058             HttpBaseProtocolFilter filter;
00059             bool replaced = filter.CookieManager().SetCookie(cookie, false);
00060
00061             if (replaced)
00062             {
00063                 rootPage.NotifyUser(L"Cookie replaced.", NotifyType::StatusMessage);
00064             }
00065             else
00066             {
00067                 rootPage.NotifyUser(L"Cookie set.", NotifyType::StatusMessage);
00068             }
00069         }
00070         catch (hresult_invalid_argument const& ex)
00071         {
00072             rootPage.NotifyUser(ex.message(), NotifyType::StatusMessage);
00073         }
00074         catch (hresult_error const& ex)
00075         {
00076             rootPage.NotifyUser(L"Error: " + ex.message(), NotifyType::ErrorMessage);
00077         }
00078     }
00079 }
Generated on Fri Nov 15 2024 22:19:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_TimeZone Member List

This is the complete list of members for Scenario5_TimeZone, including all inherited members.
ReportCalendarData(Calendar calendar) | Scenario5_TimeZone | [inline, private]
Scenario5_TimeZone() | Scenario5_TimeZone | [inline]
ShowResults_Click(object sender, RoutedEventArgs e) | Scenario5_TimeZone | [inline, private]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-SPI/cpp/SampleConfiguration.cpp Source File

  • IoT-SPI
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016
00017 Platform::Array<SDKTemplate::Scenario>^ SDKTemplate::MainPage::scenariosInner = ref new Platform::Array<SDKTemplate::Scenario>
00018 {
00019     { "Read data from SPI device", "SDKTemplate.Scenario1_ReadData" },
00020 };
00021
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInfo/cppwinrt/Scenario2_WatchUsers.cpp Source File

  • UserInfo
  • cppwinrt

Scenario2_WatchUsers.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_WatchUsers.h"
00014 #include "UserViewModel.h"
00015 #include "Scenario2_WatchUsers.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::System;
00020 using namespace winrt::Windows::UI::Xaml;
00021 using namespace winrt::Windows::UI::Xaml::Navigation;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario2_WatchUsers::Scenario2_WatchUsers()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     void Scenario2_WatchUsers::OnNavigatedFrom(NavigationEventArgs const&)
00031     {
00032         StopWatching();
00033     }
00034
00035     void Scenario2_WatchUsers::StartWatching()
00036     {
00037         rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00038
00039         userNumber = 1;
00040         users.Clear();
00041         userWatcher = User::CreateWatcher();
00042
00043         userAddedToken = userWatcher.Added({ get_weak(), &Scenario2_WatchUsers::OnUserAdded });
00044         userUpdatedToken = userWatcher.Updated({ get_weak(), &Scenario2_WatchUsers::OnUserUpdated });
00045         userRemovedToken = userWatcher.Removed({ get_weak(), &Scenario2_WatchUsers::OnUserRemoved });
00046         enumerationCompletedToken = userWatcher.EnumerationCompleted({ get_weak(), &Scenario2_WatchUsers::OnEnumerationCompleted });
00047         watcherStoppedToken = userWatcher.Stopped({ get_weak(), &Scenario2_WatchUsers::OnWatcherStopped });
00048         userWatcher.Start();
00049         StartButton().IsEnabled(false);
00050         StopButton().IsEnabled(true);
00051     }
00052
00053     void Scenario2_WatchUsers::StopWatching()
00054     {
00055         if (userWatcher != nullptr)
00056         {
00057             // Unregister all event handlers in case events are in flight.
00058             userWatcher.Added(userAddedToken);
00059             userWatcher.Updated(userUpdatedToken);
00060             userWatcher.Removed(userRemovedToken);
00061             userWatcher.EnumerationCompleted(enumerationCompletedToken);
00062             userWatcher.Stopped(watcherStoppedToken);
00063             userWatcher.Stop();
00064             userWatcher = nullptr;
00065             users.Clear();
00066             StartButton().IsEnabled(true);
00067             StopButton().IsEnabled(false);
00068         }
00069     }
00070
00071     SDKTemplate::UserViewModel Scenario2_WatchUsers::FindModelByUserId(hstring const& userId)
00072     {
00073         for (SDKTemplate::UserViewModel&& model : users)
00074         {
00075             if (model.UserId() == userId)
00076             {
00077                 return model;
00078             }
00079         }
00080         return nullptr;
00081     }
00082
00083     IAsyncOperation<hstring> Scenario2_WatchUsers::GetDisplayNameOrGenericNameAsync(User user)
00084     {
00085         auto lifetime = get_strong();
00086
00087         // Try to get the display name.
00088         hstring displayName = (co_await user.GetPropertyAsync(KnownUserProperties::DisplayName())).as<hstring>();
00089
00090         // Choose a generic name if we do not have access to the actual name.
00091         if (displayName.empty())
00092         {
00093             displayName = L"User #" + to_hstring(userNumber);
00094             userNumber++;
00095         }
00096         co_return displayName;
00097     }
00098
00099     fire_and_forget Scenario2_WatchUsers::OnUserAdded(UserWatcher const&, UserChangedEventArgs const& e)
00100     {
00101         auto lifetime = get_strong();
00102
00103         User user = e.User();
00104
00105         // UI work must happen on the UI thread.
00106         co_await resume_foreground(Dispatcher());
00107
00108         // Create the user with "..." as the temporary display name.
00109         // Add it right away, because it might get removed while the
00110         // "co_await GetDisplayNameOrGenericNameAsync()" is running.
00111         com_ptr<UserViewModel> model = make_self<UserViewModel>(user.NonRoamableId(), L"\u2026");
00112         users.Append(*model);
00113
00114         // Try to get the display name.
00115         model->DisplayName(co_await GetDisplayNameOrGenericNameAsync(user));
00116     }
00117
00118     fire_and_forget Scenario2_WatchUsers::OnUserUpdated(UserWatcher const&, UserChangedEventArgs const& e)
00119     {
00120         auto lifetime = get_strong();
00121
00122         User user = e.User();
00123
00124         // UI work must happen on the UI thread.
00125         co_await resume_foreground(Dispatcher());
00126
00127         // Look for the user in our collection and update the display name.
00128         SDKTemplate::UserViewModel model = FindModelByUserId(user.NonRoamableId());
00129         if (model != nullptr)
00130         {
00131             get_self<UserViewModel>(model)->DisplayName(co_await GetDisplayNameOrGenericNameAsync(user));
00132         }
00133     }
00134
00135     fire_and_forget Scenario2_WatchUsers::OnUserRemoved(UserWatcher const&, UserChangedEventArgs const& e)
00136     {
00137         auto lifetime = get_strong();
00138
00139         User user = e.User();
00140
00141         // UI work must happen on the UI thread.
00142         co_await resume_foreground(Dispatcher());
00143
00144         // Look for the user in our collection and remove it.
00145         SDKTemplate::UserViewModel model = FindModelByUserId(user.NonRoamableId());
00146         if (model != nullptr)
00147         {
00148             uint32_t index;
00149             if (users.IndexOf(model, index))
00150             {
00151                 users.RemoveAt(index);
00152             }
00153         }
00154     }
00155
00156     fire_and_forget Scenario2_WatchUsers::OnEnumerationCompleted(UserWatcher const&, IInspectable const&)
00157     {
00158         auto lifetime = get_strong();
00159
00160         // UI work must happen on the UI thread.
00161         co_await resume_foreground(Dispatcher());
00162
00163         rootPage.NotifyUser(L"Enumeration complete. Watching for changes...", NotifyType::StatusMessage);
00164     }
00165
00166     fire_and_forget Scenario2_WatchUsers::OnWatcherStopped(UserWatcher const&, IInspectable const&)
00167     {
00168         auto lifetime = get_strong();
00169
00170         // UI work must happen on the UI thread.
00171         co_await resume_foreground(Dispatcher());
00172
00173         StopWatching();
00174     }
00175
00176
00177
00178 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geotag/cpp/SampleConfiguration.h Source File

  • Geotag
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Geotag API";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PasswordVault/cpp/SampleConfiguration.h Source File

  • PasswordVault
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Password vault C++ sample";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031
00032         // Value is not important. This is just a trick to run code at construction.
00033         bool initialize = InitializePasswordVaultInTheBackground();
00034
00035         static bool InitializePasswordVaultInTheBackground();
00036     };
00037
00038     public value struct Scenario
00039     {
00040         Platform::String^ Title;
00041         Platform::String^ ClassName;
00042     };
00043 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppWindow/cppwinrt/Scenario4_CompactOverlay.cpp Source File

  • AppWindow
  • cppwinrt

Scenario4_CompactOverlay.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario4_CompactOverlay.h"
00014 #include "Scenario4_CompactOverlay.g.cpp"
00015 #include "MainPage.h"
00016 #include "SampleConfiguration.h"
00017
00018 using namespace winrt;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::UI::ViewManagement;
00021 using namespace Windows::UI::WindowManagement;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Hosting;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 namespace winrt::SDKTemplate::implementation
00027 {
00028     Scenario4_CompactOverlay::Scenario4_CompactOverlay()
00029     {
00030         InitializeComponent();
00031     }
00032
00033     fire_and_forget Scenario4_CompactOverlay::OnNavigatedFrom(NavigationEventArgs const&)
00034     {
00035         if (appWindow != nullptr)
00036         {
00037             co_await appWindow.CloseAsync();
00038         }
00039     }
00040
00041     fire_and_forget Scenario4_CompactOverlay::ShowWindowBtn_Click(IInspectable const&, RoutedEventArgs const&)
00042     {
00043         auto lifetime = get_strong();
00044
00045         // Is CompactOverlay supported for our main window?
00046         // If so, it will be supported for a new window as well.
00047         // If it isn't, it will not be supported for new windows either so we cannot proceed.
00048         if (!ApplicationView::GetForCurrentView().IsViewModeSupported(ApplicationViewMode::CompactOverlay))
00049         {
00050             return;
00051         }
00052
00053         unique_disabled_control re_enabled{ showWindowBtn() };
00054
00055         // Only ever create one window. If the AppWindow already exists call TryShow on it to bring it to foreground.
00056         if (appWindow == nullptr)
00057         {
00058             // Create a new window
00059             appWindow = co_await AppWindow::TryCreateAsync();
00060             // Clean up when the window is closced
00061             appWindow.Closed({ get_weak(), &Scenario4_CompactOverlay::OnWindowClosed });
00062
00063             // Is CompactOverlay supported for this AppWindow? If not, then stop.
00064             if (appWindow.Presenter().IsPresentationSupported(AppWindowPresentationKind::CompactOverlay))
00065             {
00066                 // Create a new frame for the window
00067                 // Navigate the frame to the CompactOverlay page inside it.
00068                 appWindowFrame.Navigate(xaml_typename<SDKTemplate::SecondaryAppWindowPage>());
00069                 // Attach the frame to the window
00070                 ElementCompositionPreview::SetAppWindowContent(appWindow, appWindowFrame);
00071                 // Let's set the title so that we can tell the windows apart
00072                 appWindow.Title(L"CompactOverlay Window");
00073                 // Request the Presentation of the window to CompactOverlay
00074                 bool switched = appWindow.Presenter().RequestPresentation(AppWindowPresentationKind::CompactOverlay);
00075                 if (switched)
00076                 {
00077                     // If the request was satisfied, show the window
00078                     co_await appWindow.TryShowAsync();
00079                 }
00080             }
00081         }
00082         else
00083         {
00084             co_await appWindow.TryShowAsync();
00085         }
00086     }
00087
00088     void Scenario4_CompactOverlay::OnWindowClosed(AppWindow const&, IInspectable const&)
00089     {
00090         // Make sure we release the reference to this window, and release XAML resources.
00091         appWindow = nullptr;
00092         appWindowFrame.Content(nullptr);
00093     }
00094 }
Generated on Fri Nov 15 2024 22:18:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/Scenario3CustomOptions.xaml.cpp Source File

  • Printing
  • cpp

Scenario3CustomOptions.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario3CustomOptions.xaml.h"
00005 #include "PageToPrint.xaml.h"
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace Concurrency;
00010 using namespace Platform;
00011 using namespace Windows::Foundation;
00012 using namespace Windows::Foundation::Collections;
00013 using namespace Windows::Graphics::Display;
00014 using namespace Windows::Graphics::Printing;
00015 using namespace Windows::Graphics::Printing::OptionDetails;
00016 using namespace Windows::UI;
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Controls::Primitives;
00020 using namespace Windows::UI::Xaml::Data;
00021 using namespace Windows::UI::Xaml::Input;
00022 using namespace Windows::UI::Xaml::Media;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Windows::Storage::Streams;
00025
00026 CustomOptionsPrintHelper::CustomOptionsPrintHelper(Page^ scenarioPage) :
00027     PrintHelper(scenarioPage)
00028 {
00029     // Start these operations early because we know we're going to need the
00030     // streams in PrintTaskRequested.
00031     RandomAccessStreamReference^ wideMarginsIconReference = RandomAccessStreamReference::CreateFromUri(ref new Uri("ms-appx:///Assets/wideMargins.svg"));
00032     m_wideMarginsIconAsyncOperation = wideMarginsIconReference->OpenReadAsync();
00033
00034     RandomAccessStreamReference^ moderateMarginsIconReference = RandomAccessStreamReference::CreateFromUri(ref new Uri("ms-appx:///Assets/moderateMargins.svg"));
00035     m_moderateMarginsIconAsyncOperation = moderateMarginsIconReference->OpenReadAsync();
00036
00037     RandomAccessStreamReference^ narrowMarginsIconReference = RandomAccessStreamReference::CreateFromUri(ref new Uri("ms-appx:///Assets/narrowMargins.svg"));
00038     m_narrowMarginsIconAsyncOperation = narrowMarginsIconReference->OpenReadAsync();
00039 }
00040
00041 DisplayContent GetDisplayContent(int option)
00042 {
00043     DisplayContent displayContent;
00044     switch (option)
00045     {
00046     case 1:
00047         displayContent = DisplayContent::Text;
00048         break;
00049     case 2:
00050         displayContent = DisplayContent::Images;
00051         break;
00052     default:
00053         displayContent = DisplayContent::TextAndImages;
00054         break;
00055     }
00056
00057     return displayContent;
00058 }
00059
00060 /// <summary>
00061 /// This is the event handler for PrintManager.PrintTaskRequested.
00062 /// In order to ensure a good user experience, the system requires that the app handle the PrintTaskRequested event within the time specified by PrintTaskRequestedEventArgs->Request->Deadline.
00063 /// Therefore, we use this handler to only create the print task.
00064 /// The print settings customization can be done when the print document source is requested.
00065 /// </summary>
00066 /// <param name="sender">PrintManager</param>
00067 /// <param name="e">PrintTaskRequestedEventArgs</param>
00068 void CustomOptionsPrintHelper::PrintTaskRequested(PrintManager^ sender, PrintTaskRequestedEventArgs^ e)
00069 {
00070     auto deferral = e->Request->GetDeferral();
00071
00072     PrintTask^ printTask = e->Request->CreatePrintTask("C++ Printing SDK Sample", ref new PrintTaskSourceRequestedHandler([=](PrintTaskSourceRequestedArgs^ args)
00073     {
00074         args->SetSource(PrintDocumentSource);
00075     }));
00076
00077     // Clear the print options that are displayed beacuse adding the same one multiple times will throw an exception
00078     IVector<String^>^ displayedOptions = printTask->Options->DisplayedOptions;
00079     displayedOptions->Clear();
00080
00081     // Choose the printer options to be shown.
00082     // The order in which the options are appended determines the order in which they appear in the UI
00083     PrintTaskOptionDetails^ printDetailedOptions = PrintTaskOptionDetails::GetFromPrintTaskOptions(printTask->Options);
00084     displayedOptions->Clear();
00085
00086     displayedOptions->Append(StandardPrintTaskOptions::Copies);
00087     displayedOptions->Append(StandardPrintTaskOptions::Orientation);
00088     displayedOptions->Append(StandardPrintTaskOptions::ColorMode);
00089
00090     // Create a new list option
00091     PrintCustomItemListOptionDetails^ pageFormat = printDetailedOptions->CreateItemListOption(L"PageContent", L"Pictures");
00092     pageFormat->AddItem(L"PicturesText", L"Pictures and text");
00093     pageFormat->AddItem(L"PicturesOnly", L"Pictures only");
00094     pageFormat->AddItem(L"TextOnly", L"Text only");
00095
00096     // Add the custom option to the option list
00097     displayedOptions->Append(L"PageContent");
00098
00099     // Create a new toggle option "Show header".
00100     PrintCustomToggleOptionDetails^ header = printDetailedOptions->CreateToggleOption("Header", "Show header");
00101
00102     // App tells the user some more information about what the feature means.
00103     header->Description = "Display a header on the first page";
00104
00105     // Set the default value
00106     header->TrySetValue(m_showHeader);
00107
00108     // Add the custom option to the option list
00109     displayedOptions->Append("Header");
00110
00111     // Create a new list option
00112     PrintCustomItemListOptionDetails^ margins = printDetailedOptions->CreateItemListOption("Margins", "Margins");
00113     create_task(m_wideMarginsIconAsyncOperation).then([this, margins](IRandomAccessStreamWithContentType^ stream)
00114     {
00115         margins->AddItem("WideMargins", "Wide", "Each margin is 20% of the paper size", stream);
00116         return create_task(m_moderateMarginsIconAsyncOperation);
00117     }).then([this, margins](IRandomAccessStreamWithContentType^ stream)
00118     {
00119         margins->AddItem("ModerateMargins", "Moderate", "Each margin is 10% of the paper size", stream);
00120         return create_task(m_narrowMarginsIconAsyncOperation);
00121     }).then([this, margins](IRandomAccessStreamWithContentType^ stream)
00122     {
00123         margins->AddItem("NarrowMargins", "Narrow", "Each margin is 5% of the paper size", stream);
00124     }).then([this, margins, displayedOptions, printDetailedOptions, printTask]()
00125     {
00126         // The default is ModerateMargins
00127         SetMargins("ModerateMargins");
00128         margins->TrySetValue("ModerateMargins");
00129
00130         // App tells the user some more information about what the feature means
00131         margins->Description = "The space between the content of your document and the edge of the paper";
00132
00133         // Add the custom option to the option list
00134         displayedOptions->Append("Margins");
00135
00136         printDetailedOptions->OptionChanged += ref new TypedEventHandler<PrintTaskOptionDetails^, PrintTaskOptionChangedEventArgs^>(this, &CustomOptionsPrintHelper::printDetailedOptions_OptionChanged);
00137
00138         // Print Task event handler is invoked when the print job is completed.
00139         printTask->Completed += ref new TypedEventHandler<PrintTask^, PrintTaskCompletedEventArgs^>([=](PrintTask^ sender, PrintTaskCompletedEventArgs^ e)
00140         {
00141             // Notify the user when the print operation fails.
00142             if (e->Completion == Windows::Graphics::Printing::PrintTaskCompletion::Failed)
00143             {
00144                 MainPage::Current->NotifyUser(ref new String(L"Failed to print."), NotifyType::ErrorMessage);
00145             }
00146         });
00147     }).then([deferral](task<void> previousTask)
00148     {
00149         deferral->Complete();
00150         previousTask.get();
00151     });
00152 }
00153
00154 /// <summary>
00155 /// Option change event handler
00156 /// </summary>
00157 /// <param name="sender">PrintTaskOptionsDetails object</param>
00158 /// <param name="args">the event arguments containing the changed option id</param>
00159 void CustomOptionsPrintHelper::printDetailedOptions_OptionChanged(PrintTaskOptionDetails^ sender, PrintTaskOptionChangedEventArgs^ args)
00160 {
00161     bool invalidatePreview = false;
00162
00163     String^ optionId = safe_cast<String^>(args->OptionId);
00164
00165     if (optionId == "PageContent")
00166     {
00167         invalidatePreview = true;
00168     }
00169     else if (optionId == "Margins")
00170     {
00171         PrintCustomItemListOptionDetails^ marginsOption = (PrintCustomItemListOptionDetails^)sender->Options->Lookup("Margins");
00172         String^ marginsValue = marginsOption->Value->ToString();
00173
00174         SetMargins(marginsValue);
00175
00176         marginsOption->WarningText = "";
00177         if (marginsValue == "NarrowMargins")
00178         {
00179             marginsOption->WarningText = "Narrow margins may not be supported by some printers";
00180         }
00181
00182         invalidatePreview = true;
00183     }
00184     else if (optionId == "Header")
00185     {
00186         PrintCustomToggleOptionDetails^ headerOption = (PrintCustomToggleOptionDetails^)sender->Options->Lookup("Header");
00187         m_showHeader = (bool)headerOption->Value;
00188         invalidatePreview = true;
00189     }
00190
00191     if (invalidatePreview)
00192     {
00193         RefreshPreview();
00194     }
00195 }
00196
00197 /// <summary>
00198 /// Helper function used to set the top and left margins based on used selection
00199 /// </summary>
00200 /// <param name="marginsValue">The Id of the option selected by the user</param>
00201 void CustomOptionsPrintHelper::SetMargins(String^ marginsValue)
00202 {
00203     if (marginsValue == "WideMargins")
00204     {
00205         ApplicationContentMarginTop = 0.2f;
00206         ApplicationContentMarginLeft = 0.2f;
00207     }
00208     else if (marginsValue == "ModerateMargins")
00209     {
00210         ApplicationContentMarginTop = 0.1f;
00211         ApplicationContentMarginLeft = 0.1f;
00212     }
00213     else if (marginsValue == "NarrowMargins")
00214     {
00215         ApplicationContentMarginTop = 0.05f;
00216         ApplicationContentMarginLeft = 0.05f;
00217     }
00218 }
00219
00220 /// <summary>
00221 /// Helper function used to triger a preview refresh
00222 /// </summary>
00223 void CustomOptionsPrintHelper::RefreshPreview()
00224 {
00225     auto callback = ref new Windows::UI::Core::DispatchedHandler([this]()
00226     {
00227         CurrentPrintDocument->InvalidatePreview();
00228     });
00229
00230
00231     ScenarioPage->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
00232 }
00233
00234 /// <summary>
00235 /// This is the event handler for PrintDocument.Paginate. It creates print preview pages for the app.
00236 /// </summary>
00237 /// <param name="sender"></param>
00238 /// <param name="e">Paginate Event Arguments</param>
00239 void CustomOptionsPrintHelper::CreatePrintPreviewPages(Object^ sender, PaginateEventArgs^ e)
00240 {
00241     // Get PageContent property
00242     PrintTaskOptionDetails^ printDetailedOptions = PrintTaskOptionDetails::GetFromPrintTaskOptions(e->PrintTaskOptions);
00243     IPrintOptionDetails^ printOptionDetails = printDetailedOptions->Options->Lookup(ref new String(L"PageContent"));
00244     String^ pageContent = safe_cast<String^>(printOptionDetails->Value);
00245
00246     // Set the text & image display flag
00247     int result = (wcsstr(pageContent->Data(), L"Pictures") != nullptr) << 1 | (wcsstr(pageContent->Data(), L"Text") != nullptr);
00248     m_imageText = GetDisplayContent(result);
00249
00250     PrintHelper::CreatePrintPreviewPages(sender, e);
00251 }
00252
00253 /// <summary>
00254 /// This function creates and adds one print preview page to the internal cache of print preview
00255 /// pages stored in m_printPreviewPages.
00256 /// </summary>
00257 /// <param name="lastRTBOAdded">Last RichTextBlockOverflow element added in the current content</param>
00258 /// <param name="printPageDescription">Printer's page description</param>
00259 RichTextBlockOverflow^ CustomOptionsPrintHelper::AddOnePrintPreviewPage(RichTextBlockOverflow^ lastRTBOAdded, PrintPageDescription printPageDescription)
00260 {
00261     // Check if we need to hide/show text & images for this scenario
00262     // Since all is rulled by the first page (page flow), here is where we must start
00263     if (lastRTBOAdded == nullptr)
00264     {
00265         // Get a refference to page objects
00266         Grid^ pageContent = safe_cast<Grid^>(FirstPage->FindName("PrintableArea"));
00267         Image^ scenarioImage = safe_cast<Image^>(FirstPage->FindName("ScenarioImage"));
00268         RichTextBlock^ mainText = safe_cast<RichTextBlock^>(FirstPage->FindName("TextContent"));
00269         RichTextBlockOverflow^ firstLink = safe_cast<RichTextBlockOverflow^>(FirstPage->FindName("FirstLinkedContainer"));
00270         RichTextBlockOverflow^ continuationLink = safe_cast<RichTextBlockOverflow^>(FirstPage->FindName("ContinuationPageLinkedContainer"));
00271
00272         // Hide(collapse) and move elements in different grid cells depending by the viewable content(only text, only pictures)
00273
00274         scenarioImage->Visibility = ShowImage ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00275         firstLink->SetValue(Grid::ColumnSpanProperty, ShowImage ? 1 : 2);
00276
00277         scenarioImage->SetValue(Grid::RowProperty, ShowText ? 2 : 1);
00278         scenarioImage->SetValue(Grid::ColumnProperty, ShowText ? 1 : 0);
00279
00280         pageContent->ColumnDefinitions->GetAt(0)->Width = Windows::UI::Xaml::GridLengthHelper::FromValueAndType(ShowText ? 6 : 4, GridUnitType::Star);
00281         pageContent->ColumnDefinitions->GetAt(1)->Width = Windows::UI::Xaml::GridLengthHelper::FromValueAndType(ShowText ? 4 : 6, GridUnitType::Star);
00282
00283         // Break the text flow if the app is not printing text in order not to spawn pages with blank content
00284         mainText->Visibility = ShowText ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00285         continuationLink->Visibility = ShowText ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00286
00287         // Hide header if appropriate
00288         StackPanel^ header = safe_cast<StackPanel^>(FirstPage->FindName("Header"));
00289         header->Visibility = m_showHeader ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00290     }
00291
00292     //Continue with the rest of the base printing layout processing (paper size, printable page size)
00293     return PrintHelper::AddOnePrintPreviewPage(lastRTBOAdded, printPageDescription);
00294 }
00295
00296 Scenario3CustomOptions::Scenario3CustomOptions()
00297 {
00298     InitializeComponent();
00299 }
00300
00301 void Scenario3CustomOptions::OnPrintButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00302 {
00303     printHelper->ShowPrintUIAsync();
00304 }
00305
00306 void Scenario3CustomOptions::OnNavigatedTo(NavigationEventArgs^ e)
00307 {
00308     if (PrintManager::IsSupported())
00309     {
00310         // Tell the user how to print
00311         MainPage::Current->NotifyUser("Print contract registered with customization, use the Print button to print.", NotifyType::StatusMessage);
00312     }
00313     else
00314     {
00315         // Remove the print button
00316         InvokePrintingButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00317
00318         // Inform user that Printing is not supported
00319         MainPage::Current->NotifyUser("Printing is not supported.", NotifyType::ErrorMessage);
00320
00321         // Printing-related event handlers will never be called if printing
00322         // is not supported, but it's okay to register for them anyway.
00323     }
00324
00325     // Initalize common helper class and register for printing
00326     printHelper = ref new CustomOptionsPrintHelper(this);
00327     printHelper->RegisterForPrinting();
00328
00329     // Initialize print content for this scenario
00330     printHelper->PreparePrintContent(ref new PageToPrint());
00331 }
00332
00333 void Scenario3CustomOptions::OnNavigatedFrom(NavigationEventArgs^ e)
00334 {
00335     if (printHelper)
00336     {
00337         printHelper->UnregisterForPrinting();
00338     }
00339 }
Generated on Fri Nov 15 2024 22:21:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_RoundingAndPadding Member List

This is the complete list of members for Scenario5_RoundingAndPadding, including all inherited members.
Display_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario5_RoundingAndPadding
Scenario5_RoundingAndPadding() | Scenario5_RoundingAndPadding
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OrientationSensor/cs/Scenario3_Calibration.xaml.cs Source File

  • OrientationSensor
  • cs

Scenario3_Calibration.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.Devices.Sensors;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario3_Calibration : Page
00020     {
00021         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00022         // as NotifyUser()
00023         MainPage rootPage = MainPage.Current;
00024         CalibrationBar calibrationBar = new CalibrationBar();
00025
00026         public Scenario3_Calibration()
00027         {
00028             this.InitializeComponent();
00029
00030             if (rootPage.SensorReadingType == SensorReadingType.Relative)
00031             {
00032                 EnabledContent.Visibility = Visibility.Collapsed;
00033                 DisabledContent.Visibility = Visibility.Visible;
00034             }
00035         }
00036
00037         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00038         {
00039             calibrationBar.Hide();
00040         }
00041
00042         /// <summary>
00043         /// This is the click handler for high accuracy. Acceptable accuracy met, so
00044         /// hide the calibration bar.
00045         /// </summary>
00046         private void OnHighAccuracy()
00047         {
00048             calibrationBar.Hide();
00049         }
00050
00051         /// <summary>
00052         /// This is the click handler for approximate accuracy. Acceptable accuracy met, so
00053         /// hide the calibration bar.
00054         /// </summary>
00055         private void OnApproximateAccuracy()
00056         {
00057             calibrationBar.Hide();
00058         }
00059
00060         /// <summary>
00061         /// This is the click handler for unreliable accuracy. Sensor does not meet accuracy
00062         /// requirements. Request to show the calibration bar per the calibration guidance.
00063         /// </summary>
00064         private void OnUnreliableAccuracy()
00065         {
00066             calibrationBar.RequestCalibration(MagnetometerAccuracy.Unreliable);
00067         }
00068     }
00069 }
Generated on Fri Nov 15 2024 22:18:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/AppView.cpp Source File

  • HolographicVoiceInput
  • cpp

AppView.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
00012 #include "AppView.h"
00013
00014 #include <ppltasks.h>
00015
00016 using namespace HolographicVoiceInput;
00017
00018 using namespace concurrency;
00019 using namespace Windows::ApplicationModel;
00020 using namespace Windows::ApplicationModel::Activation;
00021 using namespace Windows::ApplicationModel::Core;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Graphics::Holographic;
00024 using namespace Windows::UI::Core;
00025
00026 // The main function is only used to initialize our IFrameworkView class.
00027 // Under most circumstances, you should not need to modify this function.
00028 [Platform::MTAThread]
00029 int main(Platform::Array<Platform::String^>^)
00030 {
00031     AppViewSource^ appViewSource = ref new ::AppViewSource();
00032     CoreApplication::Run(appViewSource);
00033     return 0;
00034 }
00035
00036 IFrameworkView^ AppViewSource::CreateView()
00037 {
00038     return ref new AppView();
00039 }
00040
00041 AppView::AppView()
00042 {
00043 }
00044
00045
00046 // IFrameworkView methods
00047
00048 // The first method called when the IFrameworkView is being created.
00049 // Use this method to subscribe for Windows shell events and to initialize your app.
00050 void AppView::Initialize(CoreApplicationView^ applicationView)
00051 {
00052     applicationView->Activated +=
00053         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &AppView::OnViewActivated);
00054
00055     // Register event handlers for app lifecycle.
00056     CoreApplication::Suspending +=
00057         ref new EventHandler<SuspendingEventArgs^>(this, &AppView::OnSuspending);
00058
00059     CoreApplication::Resuming +=
00060         ref new EventHandler<Platform::Object^>(this, &AppView::OnResuming);
00061
00062     // At this point we have access to the device and we can create device-dependent
00063     // resources.
00064     m_deviceResources = std::make_shared<DX::DeviceResources>();
00065
00066     m_main = std::make_unique<HolographicVoiceInputMain>(m_deviceResources);
00067 }
00068
00069 // Called when the CoreWindow object is created (or re-created).
00070 void AppView::SetWindow(CoreWindow^ window)
00071 {
00072     // Register for keypress notifications.
00073     window->KeyDown +=
00074         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &AppView::OnKeyPressed);
00075
00076     // Register for notification that the app window is being closed.
00077     window->Closed +=
00078         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &AppView::OnWindowClosed);
00079
00080     // Register for notifications that the app window is losing focus.
00081     window->VisibilityChanged +=
00082         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &AppView::OnVisibilityChanged);
00083
00084     // Create a holographic space for the core window for the current view.
00085     // Presenting holographic frames that are created by this holographic space will put
00086     // the app into exclusive mode.
00087     m_holographicSpace = HolographicSpace::CreateForCoreWindow(window);
00088
00089     // The DeviceResources class uses the preferred DXGI adapter ID from the holographic
00090     // space (when available) to create a Direct3D device. The HolographicSpace
00091     // uses this ID3D11Device to create and manage device-based resources such as
00092     // swap chains.
00093     m_deviceResources->SetHolographicSpace(m_holographicSpace);
00094
00095     // The main class uses the holographic space for updates and rendering.
00096     m_main->SetHolographicSpace(m_holographicSpace);
00097 }
00098
00099 // The Load method can be used to initialize scene resources or to load a
00100 // previously saved app state.
00101 void AppView::Load(Platform::String^ entryPoint)
00102 {
00103 }
00104
00105 // This method is called after the window becomes active. It oversees the
00106 // update, draw, and present loop, and it also oversees window message processing.
00107 void AppView::Run()
00108 {
00109     while (!m_windowClosed)
00110     {
00111         if (m_windowVisible && (m_holographicSpace != nullptr))
00112         {
00113             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00114
00115             HolographicFrame^ holographicFrame = m_main->Update();
00116
00117             if (m_main->Render(holographicFrame))
00118             {
00119                 // The holographic frame has an API that presents the swap chain for each
00120                 // holographic camera.
00121                 m_deviceResources->Present(holographicFrame);
00122             }
00123         }
00124         else
00125         {
00126             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00127         }
00128     }
00129 }
00130
00131 // Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
00132 // class is torn down while the app is in the foreground.
00133 // This method is not often used, but IFrameworkView requires it and it will be called for
00134 // holographic apps.
00135 void AppView::Uninitialize()
00136 {
00137
00138 }
00139
00140
00141 // Application lifecycle event handlers
00142
00143 // Called when the app view is activated. Activates the app's CoreWindow.
00144 void AppView::OnViewActivated(CoreApplicationView^ sender, IActivatedEventArgs^ args)
00145 {
00146     // Run() won't start until the CoreWindow is activated.
00147     sender->CoreWindow->Activate();
00148 }
00149
00150 void AppView::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
00151 {
00152     // Save app state asynchronously after requesting a deferral. Holding a deferral
00153     // indicates that the application is busy performing suspending operations. Be
00154     // aware that a deferral may not be held indefinitely; after about five seconds,
00155     // the app will be forced to exit.
00156     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
00157
00158     create_task([this, deferral] ()
00159     {
00160         m_deviceResources->Trim();
00161
00162         if (m_main != nullptr)
00163         {
00164             m_main->SaveAppState();
00165         }
00166
00167         //
00168         // TODO: Insert code here to save your app state.
00169         //
00170
00171         deferral->Complete();
00172     });
00173 }
00174
00175 void AppView::OnResuming(Platform::Object^ sender, Platform::Object^ args)
00176 {
00177     // Restore any data or state that was unloaded on suspend. By default, data
00178     // and state are persisted when resuming from suspend. Note that this event
00179     // does not occur if the app was previously terminated.
00180
00181     if (m_main != nullptr)
00182     {
00183         m_main->LoadAppState();
00184     }
00185
00186     //
00187     // TODO: Insert code here to load your app state.
00188     //
00189 }
00190
00191
00192 // Window event handlers
00193
00194 void AppView::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
00195 {
00196     m_windowVisible = args->Visible;
00197 }
00198
00199 void AppView::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
00200 {
00201     m_windowClosed = true;
00202 }
00203
00204
00205 // Input event handlers
00206
00207 void AppView::OnKeyPressed(CoreWindow^ sender, KeyEventArgs^ args)
00208 {
00209     //
00210     // TODO: Bluetooth keyboards are supported by HoloLens. You can use this method for
00211     //       keyboard input if you want to support it as an optional input method for
00212     //       your holographic app.
00213     //
00214 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PosPrinter/cpp/Scenario3_MultipleClaims.xaml.cpp Source File

  • PosPrinter
  • cpp

Scenario3_MultipleClaims.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_MultipleClaims.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Devices::PointOfService;
00020 using namespace Windows::Foundation;
00021
00022 Scenario3_MultipleClaims::Scenario3_MultipleClaims()
00023 {
00024     InitializeComponent();
00025 }
00026
00027 void Scenario3_MultipleClaims::ClaimSamePrinter_Click()
00028 {
00029     ClaimResultText->Text = "";
00030     rootPage->NotifyUser("", NotifyType::StatusMessage);
00031
00032
00033     if (rootPage->Printer == nullptr)
00034     {
00035         rootPage->NotifyUser("Use scenario 1 to find a printer first.", NotifyType::ErrorMessage);
00036         return;
00037     }
00038
00039     create_task(PosPrinter::FromIdAsync(rootPage->Printer->DeviceId)).then([this](PosPrinter^ printer)
00040     {
00041         if (printer == nullptr)
00042         {
00043             rootPage->NotifyUser("Cannot create same printer as scenario 1.", NotifyType::ErrorMessage);
00044         }
00045         else
00046         {
00047             create_task(printer->ClaimPrinterAsync()).then([this, printer](ClaimedPosPrinter^ claimedPrinter)
00048             {
00049                 if (claimedPrinter != nullptr)
00050                 {
00051                     ClaimResultText->Text = "Claimed the printer.";
00052
00053                     // This scenario doesn't do anything with the printer aside from claim it.
00054                     // Release our claim by closing the claimed printer.
00055                     delete claimedPrinter;
00056                 }
00057                 else
00058                 {
00059                     ClaimResultText->Text = "Did not claim the printer.";
00060                 }
00061                 // Close the duplicate printer.
00062                 delete printer;
00063             });
00064         }
00065     });
00066 }
Generated on Fri Nov 15 2024 22:20:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DWriteColorTextRendererMain Member List

This is the complete list of members for DWriteColorTextRendererMain, including all inherited members.
DWriteColorTextRendererMain(const std::shared_ptr< DX::DeviceResources > &deviceResources) | DWriteColorTextRendererMain |
m_deviceResources | DWriteColorTextRendererMain | [private]
m_sampleOverlay | DWriteColorTextRendererMain | [private]
m_sceneRenderer | DWriteColorTextRendererMain | [private]
OnDeviceLost() | DWriteColorTextRendererMain | [virtual]
OnDeviceRestored() | DWriteColorTextRendererMain | [virtual]
Render() | DWriteColorTextRendererMain |
UpdateForWindowSizeChange() | DWriteColorTextRendererMain |
~DWriteColorTextRendererMain() | DWriteColorTextRendererMain |
Generated on Fri Nov 15 2024 22:23:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CompletionGroupTask Member List

This is the complete list of members for CompletionGroupTask, including all inherited members.
CreateBackgroundDownloader() | CompletionGroupTask | [inline, static]
InvokeSimpleToast(int succeeded, int failed) | CompletionGroupTask | [inline]
IsFailed(DownloadOperation download) | CompletionGroupTask | [inline, private]
RetryDownloadsAsync(IEnumerable< DownloadOperation > downloadsToRetry) | CompletionGroupTask | [inline, private]
Run(IBackgroundTaskInstance taskInstance) | CompletionGroupTask | [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_TrackInWebcam Member List

This is the complete list of members for Scenario1_TrackInWebcam, including all inherited members.
AbandonStreaming() | Scenario1_TrackInWebcam | [private]
CameraStreamingButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_TrackInWebcam |
ChangeScenarioStateAsync(ScenarioState newState) | Scenario1_TrackInWebcam | [private]
currentState | Scenario1_TrackInWebcam | [private]
Idle enum value | Scenario1_TrackInWebcam | [private]
MediaCapture_CameraStreamFailed(Windows::Media::Capture::MediaCapture const &sender, Windows::Foundation::IInspectable const &args) | Scenario1_TrackInWebcam | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_TrackInWebcam |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_TrackInWebcam |
OnSuspending(Windows::Foundation::IInspectable const &sender, Windows::ApplicationModel::SuspendingEventArgs const &e) | Scenario1_TrackInWebcam | [private]
ProcessCurrentVideoFrame(Windows::System::Threading::ThreadPoolTimer const &timer) | Scenario1_TrackInWebcam | [private]
ProcessCurrentVideoFrameAsync() | Scenario1_TrackInWebcam | [private]
Scenario1_TrackInWebcam() | Scenario1_TrackInWebcam |
ScenarioState enum name | Scenario1_TrackInWebcam | [private]
SetupVisualization(Windows::Foundation::Size framePixelSize, Windows::Foundation::Collections::IVector< Windows::Media::FaceAnalysis::DetectedFace > const &foundFaces) | Scenario1_TrackInWebcam | [private]
ShutdownWebcamAsync() | Scenario1_TrackInWebcam | [private]
StartWebcamStreamingAsync() | Scenario1_TrackInWebcam | [private]
Streaming enum value | Scenario1_TrackInWebcam | [private]
suspendingEventToken | Scenario1_TrackInWebcam | [private]
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Scenario3_BackgroundDeviceWatcher.cpp Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

Scenario3_BackgroundDeviceWatcher.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_BackgroundDeviceWatcher.h"
00014 #include "SampleConfiguration.h"
00015 #include "DeviceHelpers.h"
00016 #include "DeviceWatcherHelper.h"
00017 #include "Scenario3_BackgroundDeviceWatcher.g.cpp"
00018
00019 using namespace winrt;
00020 using namespace winrt::Windows::ApplicationModel::Background;
00021 using namespace winrt::Windows::Devices::Enumeration;
00022 using namespace winrt::Windows::Foundation;
00023 using namespace winrt::Windows::Storage;
00024 using namespace winrt::Windows::UI::Xaml;
00025 using namespace winrt::Windows::UI::Xaml::Navigation;
00026
00027 winrt::hstring backgroundTaskName = L"DeviceEnumeration_BackgroundTaskName";
00028
00029 namespace winrt::SDKTemplate::implementation
00030 {
00031     Scenario3_BackgroundDeviceWatcher::Scenario3_BackgroundDeviceWatcher()
00032     {
00033         InitializeComponent();
00034     }
00035
00036     void Scenario3_BackgroundDeviceWatcher::OnNavigatedTo(NavigationEventArgs const&)
00037     {
00038         selectorComboBox().ItemsSource(DeviceSelectorChoices::BackgroundDeviceWatcherSelectors());
00039         selectorComboBox().SelectedIndex(0);
00040
00041         // Determine if the background task is already active
00042         for (auto&& task : BackgroundTaskRegistration::AllTasks())
00043         {
00044             if (backgroundTaskName == task.Value().Name())
00045             {
00046                 backgroundTaskRegistration = task.Value();
00047                 startWatcherButton().IsEnabled(false);
00048                 stopWatcherButton().IsEnabled(true);
00049                 break;
00050             }
00051         }
00052     }
00053
00054     void Scenario3_BackgroundDeviceWatcher::OnNavigatedFrom(NavigationEventArgs const&)
00055     {
00056         if (backgroundTaskRegistration != nullptr)
00057         {
00058             backgroundTaskRegistration.Completed(taskCompletedToken);
00059             backgroundTaskRegistration = nullptr;
00060         }
00061     }
00062
00063     void Scenario3_BackgroundDeviceWatcher::StartWatcherButton_Click(IInspectable const&, RoutedEventArgs const&)
00064     {
00065         StartWatcher();
00066     }
00067
00068     void Scenario3_BackgroundDeviceWatcher::StopWatcherButton_Click(IInspectable const&, RoutedEventArgs const&)
00069     {
00070         StopWatcher();
00071     }
00072
00073     void Scenario3_BackgroundDeviceWatcher::StartWatcher()
00074     {
00075         std::vector<DeviceWatcherEventKind> triggerEventKinds = { DeviceWatcherEventKind::Add, DeviceWatcherEventKind::Remove, DeviceWatcherEventKind::Update };
00076
00077         startWatcherButton().IsEnabled(false);
00078
00079         // First get the device selector chosen by the UI.
00080         IInspectable item = selectorComboBox().SelectedItem();
00081         DeviceSelectorInfo* deviceSelectorInfo = FromInspectable<DeviceSelectorInfo>(item);
00082
00083         DeviceWatcher deviceWatcher{ nullptr };
00084         if (deviceSelectorInfo->Selector().empty())
00085         {
00086             // If a pre-canned device class selector was chosen, call the DeviceClass overload
00087             deviceWatcher = DeviceInformation::CreateWatcher(deviceSelectorInfo->DeviceClassSelector());
00088         }
00089         else if (deviceSelectorInfo->Kind() == DeviceInformationKind::Unknown)
00090         {
00091             // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
00092             // Kind will be determined by the selector
00093             deviceWatcher = DeviceInformation::CreateWatcher(
00094                 deviceSelectorInfo->Selector(),
00095                 nullptr // don't request additional properties for this sample
00096             );
00097         }
00098         else
00099         {
00100             // Kind is specified in the selector info
00101             deviceWatcher = DeviceInformation::CreateWatcher(
00102                 deviceSelectorInfo->Selector(),
00103                 nullptr, // don't request additional properties for this sample
00104                 deviceSelectorInfo->Kind());
00105         }
00106
00107         //
00108         // Get the background trigger for this watcher
00109         DeviceWatcherTrigger deviceWatcherTrigger = deviceWatcher.GetBackgroundTrigger(triggerEventKinds);
00110
00111         rootPage.NotifyUser(L"Starting Watcher...", NotifyType::StatusMessage);
00112
00113         // Register this trigger for our background task
00114         RegisterBackgroundTask(deviceWatcherTrigger);
00115
00116         stopWatcherButton().IsEnabled(true);
00117     }
00118
00119     void Scenario3_BackgroundDeviceWatcher::RegisterBackgroundTask(DeviceWatcherTrigger const& deviceWatcherTrigger)
00120     {
00121         // First see if we already have this background task registered. If so, unregister
00122         // it before we register it with the new trigger.
00123
00124         for (auto&& task : BackgroundTaskRegistration::AllTasks())
00125         {
00126             if (backgroundTaskName == task.Value().Name())
00127             {
00128                 UnregisterBackgroundTask(task.Value());
00129             }
00130         }
00131
00132         BackgroundTaskBuilder taskBuilder;
00133         taskBuilder.Name(backgroundTaskName);
00134         taskBuilder.TaskEntryPoint(L"BackgroundDeviceWatcherTask.BackgroundDeviceWatcher");
00135         taskBuilder.SetTrigger(deviceWatcherTrigger);
00136
00137         backgroundTaskRegistration = taskBuilder.Register();
00138         taskCompletedToken = backgroundTaskRegistration.Completed({ get_weak(), &Scenario3_BackgroundDeviceWatcher::OnTaskCompleted });
00139     }
00140
00141     fire_and_forget Scenario3_BackgroundDeviceWatcher::OnTaskCompleted(BackgroundTaskRegistration const&, BackgroundTaskCompletedEventArgs const&)
00142     {
00143         auto lifetime = get_strong();
00144
00145         co_await resume_foreground(Dispatcher());
00146
00147         rootPage.NotifyUser(L"Background task completed", NotifyType::StatusMessage);
00148     }
00149
00150     void Scenario3_BackgroundDeviceWatcher::StopWatcher()
00151     {
00152         stopWatcherButton().IsEnabled(false);
00153         if (backgroundTaskRegistration != nullptr)
00154         {
00155             UnregisterBackgroundTask(backgroundTaskRegistration);
00156         }
00157         startWatcherButton().IsEnabled(true);
00158     }
00159
00160     void Scenario3_BackgroundDeviceWatcher::UnregisterBackgroundTask(IBackgroundTaskRegistration const& taskReg)
00161     {
00162         taskReg.Unregister(true);
00163         ApplicationDataContainer settings = ApplicationData::Current().LocalSettings();
00164         settings.Values().Insert(L"eventCount", box_value(0U));
00165     }
00166 }
Generated on Fri Nov 15 2024 22:19:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cppwinrt/Project.idl Source File

  • Logging
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1 : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2 : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3 : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3();
00030     }
00031
00032     // LoggingScenario tells the UI what's happening by
00033     // using the following enums.
00034     enum LoggingScenarioEventType
00035     {
00036         BusyStatusChanged,
00037         LogFileGenerated,
00038         LogFileGeneratedAtDisable,
00039         LogFileGeneratedAtSuspend,
00040         LoggingEnabledDisabled,
00041     };
00042
00043     runtimeclass LoggingScenarioEventArgs
00044     {
00045         LoggingScenarioEventType Type{ get; };
00046         Boolean Enabled{ get; };
00047         String LogFileFullPath{ get; };
00048     }
00049
00050     delegate void StatusChangedHandler(LoggingScenarioEventArgs e);
00051
00052 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

XmlDocumentToStringConverter Member List

This is the complete list of members for XmlDocumentToStringConverter, including all inherited members.
Convert(object value, Type targetType, object parameter, string language) | XmlDocumentToStringConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | XmlDocumentToStringConverter | [inline]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_LongAndShortFormats Member List

This is the complete list of members for Scenario1_LongAndShortFormats, including all inherited members.
Display() | Scenario1_LongAndShortFormats | [inline, private]
Scenario1_LongAndShortFormats() | Scenario1_LongAndShortFormats | [inline]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2 Member List

This is the complete list of members for Scenario2, including all inherited members.
_instance | Scenario2 | [private]
_statusChangedToken | Scenario2 | [private]
AddMessage(_In_ LPCWSTR message) | Scenario2 | [private]
btnFilePicker_Click(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2 |
btnPause_Click(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2 |
btnPlay_Click(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2 |
btnPlayPause_Click(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2 |
btnStop_Click(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2 |
DisableContentUI() | Scenario2 |
DoScenario(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &args) | Scenario2 |
EnableDisableLogging(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &args) | Scenario2 |
GetParent_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2 |
GetThumbnailButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2 |
GroupByHelperAsync(Windows::Storage::Search::QueryOptions queryOptions) | Scenario2 | [private]
GroupByMonthButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2 |
GroupByRatingButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2 |
GroupByTagButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2 |
InitializeDevice() | Scenario2 |
m_contentType | Scenario2 | [private]
m_deviceStateChangeToken | Scenario2 | [private]
m_deviceSupportsRawMode | Scenario2 | [private]
m_renderer | Scenario2 | [private]
m_systemMediaControlsButtonToken | Scenario2 | [private]
MediaButtonPressed(Windows::Media::SystemMediaTransportControls const &sender, Windows::Media::SystemMediaTransportControlsButtonPressedEventArgs e) | Scenario2 |
MediaFoundationInitializer() | MediaFoundationInitializer | [inline, private]
OnDeviceStateChange(IDeviceStateSource const &sender, SDKTemplate::DeviceStateChangedEventArgs e) | Scenario2 |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &args) | Scenario2 |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario2 |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario2 |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario2 |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &args) | Scenario2 |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario2 |
OnPickFileAsync() | Scenario2 |
OnSetVolume(double volume) | Scenario2 |
OnStatusChanged(SDKTemplate::LoggingScenarioEventArgs args) | Scenario2 | [private]
PauseDevice() | Scenario2 |
PlayPauseToggleDevice() | Scenario2 |
radioFile_Checked(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2 |
radioTone_Checked(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2 |
Scenario2() | Scenario2 |
Scenario2() | Scenario2 |
Scenario2() | Scenario2 |
Scenario2() | Scenario2 |
Scenario2() | Scenario2 |
sliderFrequency_ValueChanged(IInspectable const &sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs const &e) | Scenario2 |
sliderVolume_ValueChanged(IInspectable const &sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs const &e) | Scenario2 |
StartDevice() | Scenario2 |
StopDevice() | Scenario2 |
UpdateContentProps(hstring const &text) | Scenario2 |
UpdateContentUI() | Scenario2 |
UpdateControls() | Scenario2 | [private]
UpdateMediaControlUI(DeviceState deviceState) | Scenario2 |
~MediaFoundationInitializer() | MediaFoundationInitializer | [inline, private]
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/SampleConfiguration.h Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt
00016 {
00017     hstring to_hstring(Windows::Devices::Enumeration::DevicePairingResultStatus status);
00018     hstring to_hstring(Windows::Devices::Enumeration::DeviceUnpairingResultStatus status);
00019     hstring to_hstring(Windows::Devices::Enumeration::DeviceInformationKind kind);
00020 }
00021
00022 namespace winrt::SDKTemplate
00023 {
00024     template<typename T>
00025     T* FromInspectable(Windows::Foundation::IInspectable const& insp)
00026     {
00027         // Note that this a reference to the T inside the IInspectable,
00028         // so the caller is responsible for keeping the IInspectable alive.
00029         return insp ? get_self<T>(insp.as<typename T::class_type>()) : nullptr;
00030     }
00031
00032     template<typename T>
00033     struct SimpleTaskCompletionSource : SimpleTaskCompletionSource<void>
00034     {
00035         void SetResult(T value)
00036         {
00037             if (!result)
00038             {
00039                 result = std::move(value);
00040                 SimpleTaskCompletionSource<void>::SetResult();
00041             }
00042         }
00043
00044         Windows::Foundation::IAsyncOperation<T> Task()
00045         {
00046             co_await SimpleTaskCompletionSource<void>::Task();
00047             co_return result.value();
00048         }
00049     private:
00050         std::optional<T> result{};
00051     };
00052
00053     template<>
00054     struct SimpleTaskCompletionSource<void>
00055     {
00056         SimpleTaskCompletionSource()
00057         {
00058             check_bool(static_cast<bool>(completeEvent));
00059         }
00060
00061         void SetResult()
00062         {
00063             SetEvent(completeEvent.get());
00064         }
00065
00066         Windows::Foundation::IAsyncAction Task()
00067         {
00068             handle localEvent;
00069             check_bool(DuplicateHandle(GetCurrentProcess(), completeEvent.get(), GetCurrentProcess(), localEvent.put(), 0, FALSE, DUPLICATE_SAME_ACCESS));
00070             co_await resume_on_signal(localEvent.get());
00071         }
00072     private:
00073         handle completeEvent{ CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_MODIFY_STATE | SYNCHRONIZE) };
00074     };
00075 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraResolution/cs/SampleConfiguration.cs Source File

  • CameraResolution
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using System;
00012 using System.Threading.Tasks;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.Media.Capture;
00016 using Windows.UI.Core;
00017 using Windows.Media.MediaProperties;
00018
00019 namespace SDKTemplate
00020 {
00021     public partial class MainPage : Page
00022     {
00023         public const string FEATURE_NAME = "Camera resolution C# sample";
00024
00025         List<Scenario> scenarios = new List<Scenario>
00026         {
00027             new Scenario() { Title="Change camera preview settings", ClassType=typeof(Scenario1_PreviewSettings)},
00028             new Scenario() { Title="Change preview and photo settings", ClassType=typeof(Scenario2_PhotoSettings)},
00029             new Scenario() { Title="Match aspect ratios", ClassType=typeof(Scenario3_AspectRatio)}
00030         };
00031     }
00032
00033     public class Scenario
00034     {
00035         public string Title { get; set; }
00036         public Type ClassType { get; set; }
00037     }
00038
00039     public class MediaCapturePreviewer
00040     {
00041         CoreDispatcher _dispatcher;
00042         CaptureElement _previewControl;
00043
00044         public MediaCapturePreviewer(CaptureElement previewControl, CoreDispatcher dispatcher)
00045         {
00046             _previewControl = previewControl;
00047             _dispatcher = dispatcher;
00048         }
00049
00050         public bool IsPreviewing { get; private set; }
00051         public bool IsRecording { get; set; }
00052         public MediaCapture MediaCapture { get; private set; }
00053
00054         /// <summary>
00055         /// Sets encoding properties on a camera stream. Ensures CaptureElement and preview stream are stopped before setting properties.
00056         /// </summary>
00057         public async Task SetMediaStreamPropertiesAsync(MediaStreamType streamType, IMediaEncodingProperties encodingProperties)
00058         {
00059             // Stop preview and unlink the CaptureElement from the MediaCapture object
00060             await MediaCapture.StopPreviewAsync();
00061             _previewControl.Source = null;
00062
00063             // Apply desired stream properties
00064             await MediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, encodingProperties);
00065
00066             // Recreate the CaptureElement pipeline and restart the preview
00067             _previewControl.Source = MediaCapture;
00068             await MediaCapture.StartPreviewAsync();
00069         }
00070
00071         /// <summary>
00072         /// Initializes the MediaCapture, starts preview.
00073         /// </summary>
00074         public async Task InitializeCameraAsync()
00075         {
00076             MediaCapture = new MediaCapture();
00077             MediaCapture.Failed += MediaCapture_Failed;
00078
00079             try
00080             {
00081                 await MediaCapture.InitializeAsync();
00082                 _previewControl.Source = MediaCapture;
00083                 await MediaCapture.StartPreviewAsync();
00084                 IsPreviewing = true;
00085             }
00086             catch (UnauthorizedAccessException)
00087             {
00088                 // This can happen if access to the camera has been revoked.
00089                 MainPage.Current.NotifyUser("The app was denied access to the camera", NotifyType.ErrorMessage);
00090                 await CleanupCameraAsync();
00091             }
00092         }
00093
00094         public async Task CleanupCameraAsync()
00095         {
00096             if (IsRecording)
00097             {
00098                 await MediaCapture.StopRecordAsync();
00099                 IsRecording = false;
00100             }
00101
00102             if (IsPreviewing)
00103             {
00104                 await MediaCapture.StopPreviewAsync();
00105                 IsPreviewing = false;
00106             }
00107
00108             _previewControl.Source = null;
00109
00110             if (MediaCapture != null)
00111             {
00112                 MediaCapture.Dispose();
00113                 MediaCapture = null;
00114             }
00115         }
00116
00117         private void MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs e)
00118         {
00119             var task = _dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
00120             {
00121                 MainPage.Current.NotifyUser("Preview stopped: " + e.Message, NotifyType.ErrorMessage);
00122                 IsRecording = false;
00123                 IsPreviewing = false;
00124                 await CleanupCameraAsync();
00125             });
00126         }
00127     }
00128 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteColorGlyph/cpp/App.h Source File

  • DWriteColorGlyph
  • cpp

App.h

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include "pch.h"
00011 #include "DeviceResources.h"
00012 #include "DWriteColorTextRendererMain.h"
00013
00014 namespace DWriteColorTextRenderer
00015 {
00016     // Main entry point for our app. Connects the app with the Windows shell and handles application lifecycle events.
00017     ref class App sealed : public Windows::ApplicationModel::Core::IFrameworkView
00018     {
00019     public:
00020         App();
00021
00022         // IFrameworkView Methods.
00023         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00024         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00025         virtual void Load(Platform::String^ entryPoint);
00026         virtual void Run();
00027         virtual void Uninitialize();
00028
00029     protected:
00030         // Application lifecycle event handlers.
00031         void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00032         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00033         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00034
00035         // Window event handlers.
00036         void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args);
00037         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00038         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00039
00040         // DisplayInformation event handlers.
00041         void OnDpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00042         void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00043         void OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00044
00045     private:
00046         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00047         std::unique_ptr<DWriteColorTextRendererMain> m_main;
00048         bool m_windowClosed;
00049         bool m_windowVisible;
00050     };
00051 }
00052
00053 ref class DirectXApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00054 {
00055 public:
00056     virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00057 };
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Calibration Member List

This is the complete list of members for Scenario3_Calibration, including all inherited members.
calibrationBar | Scenario3_Calibration | [private]
OnApproximateAccuracy(object sender, RoutedEventArgs e) | Scenario3_Calibration | [inline, private]
OnApproximateAccuracy() | Scenario3_Calibration | [inline, private]
OnHighAccuracy(object sender, RoutedEventArgs e) | Scenario3_Calibration | [inline, private]
OnHighAccuracy() | Scenario3_Calibration | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_Calibration | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario3_Calibration | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario3_Calibration | [inline, protected]
OnUnreliableAccuracy(object sender, RoutedEventArgs e) | Scenario3_Calibration | [inline, private]
OnUnreliableAccuracy() | Scenario3_Calibration | [inline, private]
rootPage | Scenario3_Calibration | [private]
Scenario3_Calibration() | Scenario3_Calibration | [inline]
Scenario3_Calibration() | Scenario3_Calibration | [inline]
Generated on Fri Nov 15 2024 22:23:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlPivot/cs/SampleConfiguration.cs Source File

  • XamlPivot
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using PivotCS;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Pivot";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Scenario 1 - Basic", ClassType=typeof(Scenario1)},
00026             new Scenario() { Title="Scenario 2 - Headers", ClassType=typeof(Scenario2)},
00027             new Scenario() { Title="Scenario 3 - Tabs", ClassType=typeof(Scenario3)}
00028         };
00029     }
00030
00031     public class Scenario
00032     {
00033         public string Title { get; set; }
00034         public Type ClassType { get; set; }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScannerProvider/cpp/BarcodeDecoder/BarcodeDecoder.cpp Source File

  • BarcodeScannerProvider
  • cpp
  • BarcodeDecoder

BarcodeDecoder.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "BarcodeDecoder.h"
00013 #include "Provider.h"
00014
00015 using namespace Platform;
00016 using namespace Windows::ApplicationModel::Background;
00017 using namespace Windows::Devices::PointOfService::Provider;
00018
00019 namespace BarcodeDecoder
00020 {
00021     Provider^ provider = nullptr;
00022
00023     void BarcodeDecodeTask::Run(IBackgroundTaskInstance^ taskInstance)
00024     {
00025         provider = ref new Provider(taskInstance);
00026     }
00027 }
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCoordinateMapper/cpp/pch.h Source File

  • CameraStreamCoordinateMapper
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #define NOMINMAX
00015
00016 #include <wrl.h>
00017 #include <wrl\client.h>
00018 #include <dxgi1_4.h>
00019 #include <d3d11_3.h>
00020 #include <d2d1_3.h>
00021 #include <d2d1effects_2.h>
00022 #include <dwrite_3.h>
00023 #include <wincodec.h>
00024 #include <DirectXColors.h>
00025 #include <DirectXMath.h>
00026 #include <WindowsNumerics.h>
00027 #include <collection.h>
00028 #include <agile.h>
00029 #include <concrt.h>
00030
00031 #include <memory>
00032 #include <shared_mutex>
00033 #include <future>
00034 #include <algorithm>
00035 #include <numeric>
00036 #include <optional>
00037 #include <string>
00038 #include <cmath>
00039
00040 #include <experimental\resumable>
00041 #include <ppltasks.h>
00042 #include <pplawait.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

QuadModelConstantBuffer Member List

This is the complete list of members for QuadModelConstantBuffer, including all inherited members.
model | QuadModelConstantBuffer
texCoordOffset | QuadModelConstantBuffer
texCoordScale | QuadModelConstantBuffer
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cpp/Scenario1_SingleFile.xaml.cpp Source File

  • FilePicker
  • cpp

Scenario1_SingleFile.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_SingleFile.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Storage;
00020 using namespace Windows::Storage::Pickers;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario1_SingleFile::Scenario1_SingleFile()
00026 {
00027     InitializeComponent();
00028     rootPage = MainPage::Current;
00029 }
00030
00031 void Scenario1_SingleFile::PickAFileButton_Click(Object^ sender, RoutedEventArgs^ e)
00032 {
00033     // Clear previous returned file name, if it exists, between iterations of this scenario
00034     OutputTextBlock->Text = "";
00035
00036     FileOpenPicker^ openPicker = ref new FileOpenPicker();
00037     openPicker->ViewMode = PickerViewMode::Thumbnail;
00038     openPicker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00039     openPicker->FileTypeFilter->Append(".jpg");
00040     openPicker->FileTypeFilter->Append(".jpeg");
00041     openPicker->FileTypeFilter->Append(".png");
00042
00043     create_task(openPicker->PickSingleFileAsync()).then([this](StorageFile^ file)
00044     {
00045         if (file)
00046         {
00047             OutputTextBlock->Text = "Picked photo: " + file->Name;
00048         }
00049         else
00050         {
00051             OutputTextBlock->Text = "Operation cancelled.";
00052         }
00053     });
00054 }
Generated on Fri Nov 15 2024 22:19:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_Tuning Member List

This is the complete list of members for Scenario4_Tuning, including all inherited members.
adaptiveMediaSource | Scenario4_Tuning | [private]
adaptiveMediaSourceLogger | Scenario4_Tuning | [private]
bitrateHelper | Scenario4_Tuning | [private]
ctsForInboundBitsPerSecondUiRefresh | Scenario4_Tuning | [private]
DesiredMaxBitrateList_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario4_Tuning | [inline, private]
DesiredMinBitrateList_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario4_Tuning | [inline, private]
DownloadBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadBitrateChangedEventArgs args) | Scenario4_Tuning | [inline, private]
HideDescriptionOnSmallScreen() | Scenario4_Tuning | [inline, private]
InitialBitrateList_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario4_Tuning | [inline, private]
InitializeBitrateLists(AdaptiveMediaSource aMS) | Scenario4_Tuning | [inline, private]
IsValidBitrateCombination(uint?desiredMinBitrate, uint?desiredMaxBitrate, uint initialBitrate) | Scenario4_Tuning | [inline, private]
LoadSourceFromUriAsync(Uri uri, HttpClient httpClient=null) | Scenario4_Tuning | [inline, private]
Log(string message) | Scenario4_Tuning | [inline, private]
mediaPlaybackItemLogger | Scenario4_Tuning | [private]
mediaPlayerLogger | Scenario4_Tuning | [private]
mediaSourceLogger | Scenario4_Tuning | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario4_Tuning | [inline, protected]
Page_OnLoaded(object sender, RoutedEventArgs e) | Scenario4_Tuning | [inline, private]
PlaybackBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourcePlaybackBitrateChangedEventArgs args) | Scenario4_Tuning | [inline, private]
PollForInboundBitsPerSecond(CancellationTokenSource cts) | Scenario4_Tuning | [inline, private]
RegisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource adaptiveMediaSource) | Scenario4_Tuning | [inline, private]
Scenario4_Tuning() | Scenario4_Tuning | [inline]
SetBitrateDowngradeTriggerRatio_Click() | Scenario4_Tuning | [inline, private]
SetDesiredBitrateHeadroomRatio_Click() | Scenario4_Tuning | [inline, private]
UnregisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource adaptiveMediaSource) | Scenario4_Tuning | [inline, private]
UnregisterHandlers(MediaPlayer mediaPlayer) | Scenario4_Tuning | [inline, private]
UpdateDownloadBitrateAsync(uint downloadBitrate) | Scenario4_Tuning | [inline, private]
UpdatePlaybackBitrateAsync(uint playbackBitrate) | Scenario4_Tuning | [inline, private]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DpiScaling/cpp/Scenario1.xaml.h Source File

  • DpiScaling
  • cpp

Scenario1.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario1.xaml.h
00013 // Declaration of the Scenario1 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario1.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024     [Windows::Foundation::Metadata::WebHostHidden]
00025     public ref class Scenario1 sealed
00026     {
00027     public:
00028         Scenario1();
00029
00030     protected:
00031         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00032         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00033
00034     private:
00035         Windows::Foundation::EventRegistrationToken token;
00036
00037         void ResetOutput();
00038         void DisplayProperties_DpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args);
00039     };
00040 }
Generated on Fri Nov 15 2024 22:17:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/BasicTests.xaml.cpp Source File

  • XamlBind
  • cpp

BasicTests.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // BasicTests.xaml.cpp
00003 // Implementation of the BasicTests class
00004 //
00005
00006 #include "pch.h"
00007 #include "BasicTests.xaml.h"
00008
00009 using namespace SDKTemplate;
00010
00011 using namespace Platform;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::UI::Xaml;
00015 using namespace Windows::UI::Xaml::Controls;
00016 using namespace Windows::UI::Xaml::Controls::Primitives;
00017 using namespace Windows::UI::Xaml::Data;
00018 using namespace Windows::UI::Xaml::Input;
00019 using namespace Windows::UI::Xaml::Media;
00020 using namespace Windows::UI::Xaml::Navigation;
00021 using namespace Windows::UI::Xaml::Interop;
00022
00023 using namespace xBindSampleModel;
00024
00025 DependencyProperty^ BasicTests::_DPOnPage = DependencyProperty::Register("DPOnPage", TypeName(::Platform::String::typeid), TypeName(BasicTests::typeid), nullptr);
00026
00027 BasicTests::BasicTests()
00028 {
00029     Model = ref new DataModel();
00030     InitializeComponent();
00031     InitializeValues();
00032 }
00033
00034 void BasicTests::InitializeValues()
00035 {
00036     this->DPOnPage = "DP on page";
00037 }
00038
00039 void BasicTests::UpdateValuesClick(Object^ sender, ::Windows::UI::Xaml::RoutedEventArgs^ e)
00040 {
00041     this->Model->UpdateValues();
00042     this->DPOnPage += "-";
00043 }
00044
00045 void BasicTests::ResetValuesClick(Object^ sender, ::Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     this->Model->InitializeValues();
00048     this->InitializeValues();
00049
00050 }
Generated on Fri Nov 15 2024 22:22:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/pch.h Source File

  • ApplicationResources
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario06_PostMultipart.cpp Source File

  • HttpClient
  • cppwinrt

Scenario06_PostMultipart.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario06_PostMultipart.h"
00014 #include "Scenario06_PostMultipart.g.cpp"
00015 #include "Helpers.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::UI::Xaml;
00020 using namespace winrt::Windows::UI::Xaml::Navigation;
00021 using namespace winrt::Windows::Web::Http;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario06_PostMultipart::Scenario06_PostMultipart()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     void Scenario06_PostMultipart::OnNavigatedTo(NavigationEventArgs const&)
00031     {
00032         httpClient = Helpers::CreateHttpClientWithCustomHeaders();
00033     }
00034
00035     void Scenario06_PostMultipart::OnNavigatedFrom(NavigationEventArgs const&)
00036     {
00037         httpClient.Close();
00038     }
00039
00040     fire_and_forget Scenario06_PostMultipart::Start_Click(IInspectable const&, RoutedEventArgs const&)
00041     {
00042         auto lifetime = get_strong();
00043
00044         // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00045         // valid, absolute URI, we'll notify the user about the incorrect input.
00046         Uri resourceUri = Helpers::TryParseHttpUri(AddressField().Text());
00047         if (!resourceUri)
00048         {
00049             rootPage.NotifyUser(L"Invalid URI.", NotifyType::ErrorMessage);
00050             return;
00051         }
00052
00053         Helpers::ScenarioStarted(StartButton(), CancelButton(), OutputField());
00054         rootPage.NotifyUser(L"In progress", NotifyType::StatusMessage);
00055
00056         HttpMultipartFormDataContent form;
00057         form.Add(HttpStringContent(RequestBodyField().Text()), L"data");
00058
00059         // This sample uses a "try" in order to support cancellation.
00060         // If you don't need to support cancellation, then the "try" is not needed.
00061         try
00062         {
00063             pendingAction = CancelableRequestAsync(resourceUri, form);
00064             co_await pendingAction;
00065         }
00066         catch (hresult_canceled const&)
00067         {
00068             rootPage.NotifyUser(L"Request canceled.", NotifyType::ErrorMessage);
00069         }
00070
00071         Helpers::ScenarioCompleted(StartButton(), CancelButton());
00072     }
00073
00074     IAsyncAction Scenario06_PostMultipart::CancelableRequestAsync(Uri resourceUri, HttpMultipartFormDataContent form)
00075     {
00076         auto lifetime = get_strong();
00077         auto cancellation = co_await get_cancellation_token();
00078         cancellation.enable_propagation();
00079
00080         HttpRequestResult result = co_await httpClient.TryPostAsync(resourceUri, form);
00081
00082         if (result.Succeeded())
00083         {
00084             co_await Helpers::DisplayTextResultAsync(result.ResponseMessage(), OutputField());
00085
00086             rootPage.NotifyUser(L"Completed", NotifyType::StatusMessage);
00087         }
00088         else
00089         {
00090             Helpers::DisplayWebError(rootPage, result.ExtendedError());
00091         }
00092     }
00093
00094     void Scenario06_PostMultipart::Cancel_Click(IInspectable const&, RoutedEventArgs const&)
00095     {
00096         if (pendingAction)
00097         {
00098             pendingAction.Cancel();
00099         }
00100     }
00101 }
Generated on Fri Nov 15 2024 22:19:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IDPadHelper Member List

This is the complete list of members for IDPadHelper, including all inherited members.
SourcePressed(Windows::UI::Input::Spatial::SpatialInteractionPressKind pressKind, Windows::UI::Input::Spatial::SpatialInteractionControllerProperties^controllerState) | IDPadHelper | [inline, virtual]
Update(Windows::UI::Input::Spatial::SpatialInteractionControllerProperties^controllerState) | IDPadHelper | [inline, virtual]
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ConnectionSettingsPanel Member List

This is the complete list of members for ConnectionSettingsPanel, including all inherited members.
btnAddConfigMethods_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | ConnectionSettingsPanel |
ConnectionSettingsPanel() | ConnectionSettingsPanel |
OnPairingRequested(Windows::Devices::Enumeration::DeviceInformationCustomPairing const &, Windows::Devices::Enumeration::DevicePairingRequestedEventArgs const &e) | ConnectionSettingsPanel | [private]
RequestPairDeviceAsync(Windows::Devices::Enumeration::DeviceInformationPairing pairing) | ConnectionSettingsPanel |
Reset() | ConnectionSettingsPanel |
supportedConfigMethods | ConnectionSettingsPanel | [private]
Generated on Fri Nov 15 2024 22:24:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cppwinrt/CopyText.h Source File

  • Clipboard
  • cppwinrt

CopyText.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "CopyText.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct CopyText : CopyTextT<CopyText>
00020     {
00021         CopyText();
00022
00023         void CopyButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024         fire_and_forget PasteButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00025
00026     private:
00027         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00028         hstring imgSrc = L"ms-appx-web:///assets/windows-sdk.png";
00029         hstring htmlFragment = L"Use clipboard to copy and paste text in different formats, including plain text, and formatted text (HTML). <br />"
00030             L" To <b>copy</b>, add text formats to a <i>DataPackage</i>, and then place <i>DataPackage</i> to Clipboard.<br /> "
00031             L"To <b>paste</b>, get <i>DataPackageView</i> from clipboard, and retrieve the content of the desired text format from it.<br />"
00032             L"To handle local image files in the formatted text (such as the one below), use ResourceMap collection."
00033             L"<br /><img id=\"scenario1LocalImage\" src=\"" +
00034             imgSrc +
00035             L"\" /><br />"
00036             L"<i>DataPackage</i> class is also used to share or send content between applications. <br />"
00037             L"See the Share SDK sample for more information.";
00038
00039         fire_and_forget DisplayResourceMapAsync(Windows::ApplicationModel::DataTransfer::DataPackageView dataPackageView);
00040     };
00041 }
00042
00043 namespace winrt::SDKTemplate::factory_implementation
00044 {
00045     struct CopyText : CopyTextT<CopyText, implementation::CopyText>
00046     {
00047     };
00048 }
Generated on Fri Nov 15 2024 22:18:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FullScreenMode/cpp/pch.cpp Source File

  • FullScreenMode
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario05_PostStream.h Source File

  • HttpClient
  • cppwinrt

Scenario05_PostStream.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario05_PostStream.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario05_PostStream : Scenario05_PostStreamT<Scenario05_PostStream>
00020     {
00021         Scenario05_PostStream();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025
00026         fire_and_forget Start_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         void Cancel_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028
00029     private:
00030         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00031         Windows::Web::Http::HttpClient httpClient{ nullptr };
00032         Windows::Foundation::IAsyncAction pendingAction{ nullptr };
00033
00034         Windows::Foundation::IAsyncAction CancelableRequestAsync(Windows::Web::Http::HttpRequestMessage request);
00035     };
00036 }
00037
00038 namespace winrt::SDKTemplate::factory_implementation
00039 {
00040     struct Scenario05_PostStream : Scenario05_PostStreamT<Scenario05_PostStream, implementation::Scenario05_PostStream>
00041     {
00042     };
00043 }
Generated on Fri Nov 15 2024 22:19:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cppwinrt/Scenario1_UTF8.cpp Source File

  • WebSocket
  • cppwinrt

Scenario1_UTF8.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_UTF8.h"
00014 #include "Scenario1_UTF8.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::Networking::Sockets;
00020 using namespace winrt::Windows::Security::Cryptography::Certificates;
00021 using namespace winrt::Windows::Storage::Streams;
00022 using namespace winrt::Windows::UI::Xaml;
00023 using namespace winrt::Windows::UI::Xaml::Navigation;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario1_UTF8::Scenario1_UTF8()
00028     {
00029         InitializeComponent();
00030         UpdateVisualState();
00031     }
00032
00033     void Scenario1_UTF8::OnNavigatedFrom(NavigationEventArgs const&)
00034     {
00035         CloseSocket();
00036     }
00037
00038     void Scenario1_UTF8::UpdateVisualState()
00039     {
00040         if (m_busy)
00041         {
00042             VisualStateManager::GoToState(*this, L"Busy", false);
00043         }
00044         else if (m_messageWebSocket != nullptr)
00045         {
00046             VisualStateManager::GoToState(*this, L"Connected", false);
00047         }
00048         else
00049         {
00050             VisualStateManager::GoToState(*this, L"Disconnected", false);
00051         }
00052     }
00053
00054     void Scenario1_UTF8::SetBusy(bool value)
00055     {
00056         m_busy = value;
00057         UpdateVisualState();
00058     }
00059
00060     fire_and_forget Scenario1_UTF8::OnConnect(IInspectable const&, RoutedEventArgs const&)
00061     {
00062         auto lifetime = get_strong();
00063
00064         SetBusy(true);
00065         co_await ConnectAsync();
00066         SetBusy(false);
00067     }
00068
00069     IAsyncAction Scenario1_UTF8::ConnectAsync()
00070     {
00071         auto lifetime = get_strong();
00072
00073         if (InputField().Text().empty())
00074         {
00075             m_rootPage.NotifyUser(L"Please specify text to send", NotifyType::ErrorMessage);
00076             co_return;
00077         }
00078
00079         // Validating the URI is required since it was received from an untrusted source (user input).
00080         // The URI is validated by calling TryGetUri() that will return null for strings that are not
00081         // valid WebSocket URIs.
00082         // Note that when enabling the text box users may provide URIs to machines on the intrAnet
00083         // or intErnet. In these cases the app requires the "Private Networks (Client and Server)" or
00084         // "Internet (Client)" capability respectively.
00085         Uri server = TryGetUri(m_rootPage, ServerAddressField().Text());
00086         if (server == nullptr)
00087         {
00088             co_return;
00089         }
00090
00091         m_messageWebSocket = MessageWebSocket();
00092         m_messageWebSocket.Control().MessageType(SocketMessageType::Utf8);
00093         m_messageWebSocket.MessageReceived({ get_weak(), &Scenario1_UTF8::MessageReceived });
00094         m_messageWebSocket.Closed({ get_weak(), &Scenario1_UTF8::OnClosed });
00095
00096         // If we are connecting to wss:// endpoint, by default, the OS performs validation of
00097         // the server certificate based on well-known trusted CAs. We can perform additional custom
00098         // validation if needed.
00099         if (SecureWebSocketCheckBox().IsChecked().Value())
00100         {
00101             // WARNING: Only test applications should ignore SSL errors.
00102             // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle
00103             // attacks. (Although the connection is secure, the server is not authenticated.)
00104             // Note that not all certificate validation errors can be ignored.
00105             // In this case, we are ignoring these errors since the certificate assigned to the localhost
00106             // URI is self-signed and has subject name = fabrikam.com
00107             m_messageWebSocket.Control().IgnorableServerCertificateErrors().Append(ChainValidationResult::Untrusted);
00108             m_messageWebSocket.Control().IgnorableServerCertificateErrors().Append(ChainValidationResult::InvalidName);
00109
00110             // Add event handler to listen to the ServerCustomValidationRequested event. This enables performing
00111             // custom validation of the server certificate. The event handler must implement the desired
00112             // custom certificate validation logic.
00113             m_messageWebSocket.ServerCustomValidationRequested({ get_weak(), &Scenario1_UTF8::OnServerCustomValidationRequested });
00114
00115             // Certificate validation occurs only for secure connections.
00116             if (server.SchemeName() != L"wss")
00117             {
00118                 AppendOutputLine(L"Note: Certificate validation is performed only for the wss: scheme.");
00119             }
00120         }
00121
00122         AppendOutputLine(L"Connecting to " + server.AbsoluteCanonicalUri() + L"...");
00123         try
00124         {
00125             co_await m_messageWebSocket.ConnectAsync(server);
00126         }
00127         catch (winrt::hresult_error const& ex) // For debugging
00128         {
00129             // Error happened during connect operation.
00130             m_messageWebSocket.Close();
00131             m_messageWebSocket = nullptr;
00132
00133             AppendOutputLine(BuildWebSocketError(ex));
00134             AppendOutputLine(ex.message());
00135             co_return;
00136         }
00137
00138         // The default DataWriter encoding is Utf8.
00139         m_messageWriter = DataWriter(m_messageWebSocket.OutputStream());
00140         m_rootPage.NotifyUser(L"Connected", NotifyType::StatusMessage);
00141     }
00142
00143     fire_and_forget Scenario1_UTF8::OnServerCustomValidationRequested(MessageWebSocket const&, WebSocketServerCustomValidationRequestedEventArgs e)
00144     {
00145         auto lifetime = get_strong();
00146
00147         // In order to call async APIs in this handler, you must first take a deferral and then
00148         // complete it once you are done with the operation. The Deferral destructor
00149         // ensures that the deferral completes when control leaves the function.
00150         Deferral deferral = e.GetDeferral();
00151
00152         // Get the server certificate and certificate chain from the args parameter.
00153         const bool isValid = co_await AreCertificateAndCertChainValidAsync(e.ServerCertificate(), e.ServerIntermediateCertificates());
00154
00155         if (!isValid)
00156         {
00157             e.Reject();
00158         }
00159
00160         // Continue on the UI thread so we can update UI.
00161         co_await resume_foreground(Dispatcher());
00162
00163         if (isValid)
00164         {
00165             AppendOutputLine(L"Custom validation of server certificate passed.");
00166         }
00167         else
00168         {
00169             AppendOutputLine(L"Custom validation of server certificate failed.");
00170         }
00171     }
00172
00173     fire_and_forget Scenario1_UTF8::OnSend(IInspectable const&, RoutedEventArgs const&)
00174     {
00175         auto lifetime = get_strong();
00176
00177         SetBusy(true);
00178         co_await SendAsync();
00179         SetBusy(false);
00180     }
00181
00182     IAsyncAction Scenario1_UTF8::SendAsync()
00183     {
00184         auto lifetime = get_strong();
00185
00186         hstring message = InputField().Text();
00187         if (message.empty())
00188         {
00189             m_rootPage.NotifyUser(L"Please specify text to send", NotifyType::ErrorMessage);
00190             co_return;
00191         }
00192
00193         AppendOutputLine(L"Sending Message: " + message);
00194
00195         // Buffer any data we want to send.
00196         m_messageWriter.WriteString(message);
00197
00198         try
00199         {
00200             // Send the data as one complete message.
00201             co_await m_messageWriter.StoreAsync();
00202         }
00203         catch (winrt::hresult_error const& ex)
00204         {
00205             AppendOutputLine(BuildWebSocketError(ex));
00206             AppendOutputLine(ex.message());
00207             co_return;
00208         }
00209
00210         m_rootPage.NotifyUser(L"Send Complete", NotifyType::StatusMessage);
00211     }
00212
00213     fire_and_forget Scenario1_UTF8::MessageReceived(MessageWebSocket const&, MessageWebSocketMessageReceivedEventArgs e)
00214     {
00215         auto lifetime = get_strong();
00216
00217         // Continue on the UI thread so we can update UI.
00218         co_await resume_foreground(Dispatcher());
00219
00220         AppendOutputLine(L"Message Received; Type: " + to_hstring(e.MessageType()));
00221         DataReader reader = e.GetDataReader();
00222
00223         reader.UnicodeEncoding(UnicodeEncoding::Utf8);
00224
00225         try
00226         {
00227             hstring read = reader.ReadString(reader.UnconsumedBufferLength());
00228             AppendOutputLine(read);
00229         }
00230         catch (winrt::hresult_error const& ex)
00231         {
00232             AppendOutputLine(BuildWebSocketError(ex));
00233             AppendOutputLine(ex.message());
00234         }
00235         reader.Close();
00236     }
00237
00238     void Scenario1_UTF8::OnDisconnect(IInspectable const&, RoutedEventArgs const&)
00239     {
00240         SetBusy(true);
00241         m_rootPage.NotifyUser(L"Closing", NotifyType::StatusMessage);
00242         CloseSocket();
00243         SetBusy(false);
00244         m_rootPage.NotifyUser(L"Closed", NotifyType::StatusMessage);
00245     }
00246
00247     // This may be triggered remotely by the server or locally by Close()
00248     fire_and_forget Scenario1_UTF8::OnClosed(IWebSocket sender, WebSocketClosedEventArgs e)
00249     {
00250         auto lifetime = get_strong();
00251
00252         // Continue on the UI thread so we do not need to synchronize access to messageWebSocket.
00253         co_await resume_foreground(Dispatcher());
00254
00255         AppendOutputLine(L"Closed; Code: " + to_hstring(e.Code()) + L", Reason: " + e.Reason());
00256
00257         if (m_messageWebSocket == sender)
00258         {
00259             CloseSocket();
00260             UpdateVisualState();
00261         }
00262     }
00263
00264     void Scenario1_UTF8::CloseSocket()
00265     {
00266         if (m_messageWriter)
00267         {
00268             // In order to reuse the socket with another DataWriter, the socket's output stream needs to be detached.
00269             // Otherwise, the DataWriter's destructor will automatically close the stream and all subsequent I/O operations
00270             // invoked on the socket's output stream will fail with ObjectDisposedException.
00271             //
00272             // This is only added for completeness, as this sample closes the socket in the very next code block.
00273             m_messageWriter.DetachStream();
00274             m_messageWriter.Close();
00275             m_messageWriter = nullptr;
00276         }
00277
00278         if (m_messageWebSocket)
00279         {
00280             try
00281             {
00282                 m_messageWebSocket.Close(1000, L"Closed due to user request.");
00283             }
00284             catch (winrt::hresult_error const& ex)
00285             {
00286                 AppendOutputLine(BuildWebSocketError(ex));
00287                 AppendOutputLine(ex.message());
00288             }
00289             m_messageWebSocket = nullptr;
00290         }
00291     }
00292
00293     void Scenario1_UTF8::AppendOutputLine(hstring const& value)
00294     {
00295         OutputField().Text(OutputField().Text() + value + L"\r\n");
00296     }
00297 }
Generated on Fri Nov 15 2024 22:22:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LoggingScenarioEventArgs Member List

This is the complete list of members for LoggingScenarioEventArgs, including all inherited members.
_enabled | LoggingScenarioEventArgs | [private]
_logFileFullPath | LoggingScenarioEventArgs | [private]
_type | LoggingScenarioEventArgs | [private]
Enabled() const noexcept | LoggingScenarioEventArgs | [inline]
LogFileFullPath() const noexcept | LoggingScenarioEventArgs | [inline]
LoggingScenarioEventArgs(LoggingScenarioEventType type) | LoggingScenarioEventArgs | [inline]
LoggingScenarioEventArgs(LoggingScenarioEventType type, hstring const &logFileFullPath) | LoggingScenarioEventArgs | [inline]
LoggingScenarioEventArgs(LoggingScenarioEventType type, bool enabled) | LoggingScenarioEventArgs | [inline]
Type() const noexcept | LoggingScenarioEventArgs | [inline]
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cs/cpp/Scenario3_CustomException.xaml.h Source File

  • ProxyStubsForWinRTComponents
  • cs
  • cpp

Scenario3_CustomException.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008 #include "Scenario3_CustomException.g.h"
00009
00010 namespace SDKSample
00011 {
00012     namespace ProxyStubsForWinRTComponents
00013     {
00014         public ref class CustomException sealed
00015         {
00016         public:
00017             CustomException();
00018
00019         private:
00020             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021         };
00022     }
00023 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationData/cppwinrt/pch.h Source File

  • ApplicationData
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.System.h"
00008 #include "winrt/Windows.UI.Core.h"
00009 #include "winrt/Windows.UI.Xaml.h"
00010 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00011 #include "winrt/Windows.UI.Xaml.Controls.h"
00012 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00013 #include "winrt/Windows.UI.Xaml.Documents.h"
00014 #include "winrt/Windows.UI.Xaml.Interop.h"
00015 #include "winrt/Windows.UI.Xaml.Markup.h"
00016 #include "winrt/Windows.UI.Xaml.Media.h"
00017 #include "winrt/Windows.UI.Xaml.Media.Imaging.h"
00018 #include "winrt/Windows.UI.Xaml.Navigation.h"
00019 #include "winrt/Windows.Storage.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialMapping/cpp/Common/StepTimer.h Source File

  • HolographicSpatialMapping
  • cpp
  • Common

StepTimer.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace DX
00015 {
00016     // Helper class for animation and simulation timing.
00017     class StepTimer
00018     {
00019     public:
00020         StepTimer() :
00021             m_elapsedTicks(0),
00022             m_totalTicks(0),
00023             m_leftOverTicks(0),
00024             m_frameCount(0),
00025             m_framesPerSecond(0),
00026             m_framesThisSecond(0),
00027             m_qpcSecondCounter(0),
00028             m_isFixedTimeStep(false),
00029             m_targetElapsedTicks(TicksPerSecond / 60)
00030         {
00031             m_qpcFrequency = GetPerformanceFrequency();
00032
00033             // Initialize max delta to 1/10 of a second.
00034             m_qpcMaxDelta = m_qpcFrequency / 10;
00035         }
00036
00037         // Get elapsed time since the previous Update call.
00038         uint64 GetElapsedTicks() const                        { return m_elapsedTicks;                  }
00039         double GetElapsedSeconds() const                      { return TicksToSeconds(m_elapsedTicks);  }
00040
00041         // Get total time since the start of the program.
00042         uint64 GetTotalTicks() const                          { return m_totalTicks;                    }
00043         double GetTotalSeconds() const                        { return TicksToSeconds(m_totalTicks);    }
00044
00045         // Get total number of updates since start of the program.
00046         uint32 GetFrameCount() const                          { return m_frameCount;                    }
00047
00048         // Get the current framerate.
00049         uint32 GetFramesPerSecond() const                     { return m_framesPerSecond;               }
00050
00051         // Set whether to use fixed or variable timestep mode.
00052         void SetFixedTimeStep(bool isFixedTimestep)           { m_isFixedTimeStep = isFixedTimestep;    }
00053
00054         // Set how often to call Update when in fixed timestep mode.
00055         void SetTargetElapsedTicks(uint64 targetElapsed)      { m_targetElapsedTicks = targetElapsed;   }
00056         void SetTargetElapsedSeconds(double targetElapsed)    { m_targetElapsedTicks = SecondsToTicks(targetElapsed);   }
00057
00058         // Integer format represents time using 10,000,000 ticks per second.
00059         static const uint64 TicksPerSecond = 10'000'000;
00060
00061         static double TicksToSeconds(uint64 ticks)            { return static_cast<double>(ticks) / TicksPerSecond;     }
00062         static uint64 SecondsToTicks(double seconds)          { return static_cast<uint64>(seconds * TicksPerSecond);   }
00063
00064         // Convenient wrapper for QueryPerformanceFrequency. Throws an exception if
00065         // the call to QueryPerformanceFrequency fails.
00066         static inline uint64 GetPerformanceFrequency()
00067         {
00068             LARGE_INTEGER freq;
00069             if (!QueryPerformanceFrequency(&freq))
00070             {
00071                 throw ref new Platform::FailureException();
00072             }
00073             return freq.QuadPart;
00074         }
00075
00076         // Gets the current number of ticks from QueryPerformanceCounter. Throws an
00077         // exception if the call to QueryPerformanceCounter fails.
00078         static inline int64 GetTicks()
00079         {
00080             LARGE_INTEGER ticks;
00081             if (!QueryPerformanceCounter(&ticks))
00082             {
00083                 throw ref new Platform::FailureException();
00084             }
00085             return ticks.QuadPart;
00086         }
00087
00088         // After an intentional timing discontinuity (for instance a blocking IO operation)
00089         // call this to avoid having the fixed timestep logic attempt a set of catch-up
00090         // Update calls.
00091
00092         void ResetElapsedTime()
00093         {
00094             m_qpcLastTime = GetTicks();
00095
00096             m_leftOverTicks    = 0;
00097             m_framesPerSecond  = 0;
00098             m_framesThisSecond = 0;
00099             m_qpcSecondCounter = 0;
00100         }
00101
00102         // Update timer state, calling the specified Update function the appropriate number of times.
00103         template<typename TUpdate>
00104         void Tick(const TUpdate& update)
00105         {
00106             // Query the current time.
00107             uint64 currentTime = GetTicks();
00108             uint64 timeDelta   = currentTime - m_qpcLastTime;
00109
00110             m_qpcLastTime      = currentTime;
00111             m_qpcSecondCounter += timeDelta;
00112
00113             // Clamp excessively large time deltas (e.g. after paused in the debugger).
00114             if (timeDelta > m_qpcMaxDelta)
00115             {
00116                 timeDelta = m_qpcMaxDelta;
00117             }
00118
00119             // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp.
00120             timeDelta *= TicksPerSecond;
00121             timeDelta /= m_qpcFrequency;
00122
00123             uint32 lastFrameCount = m_frameCount;
00124
00125             if (m_isFixedTimeStep)
00126             {
00127                 // Fixed timestep update logic
00128
00129                 // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp
00130                 // the clock to exactly match the target value. This prevents tiny and irrelevant errors
00131                 // from accumulating over time. Without this clamping, a game that requested a 60 fps
00132                 // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually
00133                 // accumulate enough tiny errors that it would drop a frame. It is better to just round
00134                 // small deviations down to zero to leave things running smoothly.
00135
00136                 if (abs(static_cast<int64>(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000)
00137                 {
00138                     timeDelta = m_targetElapsedTicks;
00139                 }
00140
00141                 m_leftOverTicks += timeDelta;
00142
00143                 while (m_leftOverTicks >= m_targetElapsedTicks)
00144                 {
00145                     m_elapsedTicks   = m_targetElapsedTicks;
00146                     m_totalTicks    += m_targetElapsedTicks;
00147                     m_leftOverTicks -= m_targetElapsedTicks;
00148                     m_frameCount++;
00149
00150                     update();
00151                 }
00152             }
00153             else
00154             {
00155                 // Variable timestep update logic.
00156                 m_elapsedTicks  = timeDelta;
00157                 m_totalTicks   += timeDelta;
00158                 m_leftOverTicks = 0;
00159                 m_frameCount++;
00160
00161                 update();
00162             }
00163
00164             // Track the current framerate.
00165             if (m_frameCount != lastFrameCount)
00166             {
00167                 m_framesThisSecond++;
00168             }
00169
00170             if (m_qpcSecondCounter >= static_cast<uint64>(m_qpcFrequency))
00171             {
00172                 m_framesPerSecond   = m_framesThisSecond;
00173                 m_framesThisSecond  = 0;
00174                 m_qpcSecondCounter %= m_qpcFrequency;
00175             }
00176         }
00177
00178     private:
00179
00180         // Source timing data uses QPC units.
00181         uint64 m_qpcFrequency;
00182         uint64 m_qpcLastTime;
00183         uint64 m_qpcMaxDelta;
00184
00185         // Derived timing data uses a canonical tick format.
00186         uint64 m_elapsedTicks;
00187         uint64 m_totalTicks;
00188         uint64 m_leftOverTicks;
00189
00190         // Members for tracking the framerate.
00191         uint32 m_frameCount;
00192         uint32 m_framesPerSecond;
00193         uint32 m_framesThisSecond;
00194         uint64 m_qpcSecondCounter;
00195
00196         // Members for configuring fixed timestep mode.
00197         bool   m_isFixedTimeStep;
00198         uint64 m_targetElapsedTicks;
00199     };
00200 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Enable Member List

This is the complete list of members for Scenario1_Enable, including all inherited members.
Scenario1_Enable() Scenario1_Enable
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CameraStreamProcessor::FrameData Member List

This is the complete list of members for CameraStreamProcessor::FrameData, including all inherited members.
frame | CameraStreamProcessor::FrameData
index | CameraStreamProcessor::FrameData
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario2WinRTComponent/OnboardingProducer.h Source File

  • AllJoyn
  • Common
  • Scenario2WinRTComponent

OnboardingProducer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #pragma once
00022
00023 namespace org { namespace alljoyn { namespace Onboarding {
00024
00025 extern PCSTR c_OnboardingIntrospectionXml;
00026
00027 ref class OnboardingProducer;
00028
00029 public interface class IOnboardingProducer
00030 {
00031     event Windows::Foundation::TypedEventHandler<OnboardingProducer^, Windows::Devices::AllJoyn::AllJoynProducerStoppedEventArgs^>^ Stopped;
00032     event Windows::Foundation::TypedEventHandler<OnboardingProducer^, Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^>^ SessionLost;
00033     event Windows::Foundation::TypedEventHandler<OnboardingProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^>^ SessionMemberAdded;
00034     event Windows::Foundation::TypedEventHandler<OnboardingProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^>^ SessionMemberRemoved;
00035 };
00036
00037 public ref class OnboardingProducer sealed : [Windows::Foundation::Metadata::Default] IOnboardingProducer
00038 {
00039 public:
00040     OnboardingProducer(Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment);
00041     virtual ~OnboardingProducer();
00042
00043     // The implementation of IOnboardingService that will handle method calls and property requests.
00044     property IOnboardingService^ Service
00045     {
00046         IOnboardingService^ get() { return m_serviceInterface; }
00047         void set(IOnboardingService^ value) { m_serviceInterface = value; }
00048     }
00049
00050     // Used to send signals or register functions to handle received signals.
00051     property OnboardingLegacySignals^ Signals
00052     {
00053         OnboardingLegacySignals^ get() { return m_signals; }
00054     }
00055
00056     // This event will fire whenever this producer is stopped.
00057     virtual event Windows::Foundation::TypedEventHandler<OnboardingProducer^, Windows::Devices::AllJoyn::AllJoynProducerStoppedEventArgs^>^ Stopped
00058     {
00059         Windows::Foundation::EventRegistrationToken add(Windows::Foundation::TypedEventHandler<OnboardingProducer^, Windows::Devices::AllJoyn::AllJoynProducerStoppedEventArgs^>^ handler)
00060         {
00061             return _Stopped += ref new Windows::Foundation::EventHandler<Platform::Object^>
00062             ([handler](Platform::Object^ sender, Platform::Object^ args)
00063             {
00064                 handler->Invoke(safe_cast<OnboardingProducer^>(sender), safe_cast<Windows::Devices::AllJoyn::AllJoynProducerStoppedEventArgs^>(args));
00065             }, Platform::CallbackContext::Same);
00066         }
00067         void remove(Windows::Foundation::EventRegistrationToken token)
00068         {
00069             _Stopped -= token;
00070         }
00071     internal:
00072         void raise(OnboardingProducer^ sender, Windows::Devices::AllJoyn::AllJoynProducerStoppedEventArgs^ args)
00073         {
00074             _Stopped(sender, args);
00075         }
00076     }
00077
00078     // This event will fire whenever the producer loses the session that it created.
00079     virtual event Windows::Foundation::TypedEventHandler<OnboardingProducer^, Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^>^ SessionLost
00080     {
00081         Windows::Foundation::EventRegistrationToken add(Windows::Foundation::TypedEventHandler<OnboardingProducer^, Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^>^ handler)
00082         {
00083             return _SessionLost += ref new Windows::Foundation::EventHandler<Platform::Object^>
00084             ([handler](Platform::Object^ sender, Platform::Object^ args)
00085             {
00086                 handler->Invoke(safe_cast<OnboardingProducer^>(sender), safe_cast<Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^>(args));
00087             }, Platform::CallbackContext::Same);
00088         }
00089         void remove(Windows::Foundation::EventRegistrationToken token)
00090         {
00091             _SessionLost -= token;
00092         }
00093     internal:
00094         void raise(OnboardingProducer^ sender, Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^ args)
00095         {
00096             _SessionLost(sender, args);
00097         }
00098     }
00099
00100     // This event will fire whenever a member joins the session.
00101     virtual event Windows::Foundation::TypedEventHandler<OnboardingProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^>^ SessionMemberAdded
00102     {
00103         Windows::Foundation::EventRegistrationToken add(Windows::Foundation::TypedEventHandler<OnboardingProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^>^ handler)
00104         {
00105             return _SessionMemberAdded += ref new Windows::Foundation::EventHandler<Platform::Object^>
00106             ([handler](Platform::Object^ sender, Platform::Object^ args)
00107             {
00108                 handler->Invoke(safe_cast<OnboardingProducer^>(sender), safe_cast<Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^>(args));
00109             }, Platform::CallbackContext::Same);
00110         }
00111         void remove(Windows::Foundation::EventRegistrationToken token)
00112         {
00113             _SessionMemberAdded -= token;
00114         }
00115     internal:
00116         void raise(OnboardingProducer^ sender, Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^ args)
00117         {
00118             _SessionMemberAdded(sender, args);
00119         }
00120     }
00121
00122     // This event will fire whenever a member leaves the session.
00123     virtual event Windows::Foundation::TypedEventHandler<OnboardingProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^>^ SessionMemberRemoved
00124     {
00125         Windows::Foundation::EventRegistrationToken add(Windows::Foundation::TypedEventHandler<OnboardingProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^>^ handler)
00126         {
00127             return _SessionMemberRemoved += ref new Windows::Foundation::EventHandler<Platform::Object^>
00128             ([handler](Platform::Object^ sender, Platform::Object^ args)
00129             {
00130                 handler->Invoke(safe_cast<OnboardingProducer^>(sender), safe_cast<Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^>(args));
00131             }, Platform::CallbackContext::Same);
00132         }
00133         void remove(Windows::Foundation::EventRegistrationToken token)
00134         {
00135             _SessionMemberRemoved -= token;
00136         }
00137     internal:
00138         void raise(OnboardingProducer^ sender, Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^ args)
00139         {
00140             _SessionMemberRemoved(sender, args);
00141         }
00142     }
00143
00144     // Start advertising the service.
00145     void Start();
00146
00147     // Stop advertising the service.
00148     void Stop();
00149
00150     // Remove a member that has joined this session.
00151     int32 RemoveMemberFromSession(_In_ Platform::String^ uniqueName);
00152
00153 internal:
00154     bool OnAcceptSessionJoiner(_In_ alljoyn_sessionport sessionPort, _In_ PCSTR joiner, _In_ const alljoyn_sessionopts opts);
00155     void OnSessionJoined(_In_ alljoyn_sessionport sessionPort, _In_ alljoyn_sessionid id, _In_ PCSTR joiner);
00156     QStatus OnPropertyGet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _Inout_ alljoyn_msgarg val);
00157     QStatus OnPropertySet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg val);
00158     void OnSessionLost(_In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason);
00159     void OnSessionMemberAdded(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName);
00160     void OnSessionMemberRemoved(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName);
00161
00162     property Platform::String^ ServiceObjectPath
00163     {
00164         Platform::String^ get() { return m_ServiceObjectPath; }
00165         void set(Platform::String^ value) { m_ServiceObjectPath = value; }
00166     }
00167
00168     property alljoyn_busobject BusObject
00169     {
00170         alljoyn_busobject get() { return m_busObject; }
00171         void set(alljoyn_busobject value) { m_busObject = value; }
00172     }
00173
00174     property alljoyn_sessionportlistener SessionPortListener
00175     {
00176         alljoyn_sessionportlistener get() { return m_sessionPortListener; }
00177         void set(alljoyn_sessionportlistener value) { m_sessionPortListener = value; }
00178     }
00179
00180     property alljoyn_sessionlistener SessionListener
00181     {
00182         alljoyn_sessionlistener get() { return m_sessionListener; }
00183         void set(alljoyn_sessionlistener value) { m_sessionListener = value; }
00184     }
00185
00186     property alljoyn_sessionport SessionPort
00187     {
00188         alljoyn_sessionport get() { return m_sessionPort; }
00189     internal:
00190         void set(alljoyn_sessionport value) { m_sessionPort = value; }
00191     }
00192
00193     property alljoyn_sessionid SessionId
00194     {
00195         alljoyn_sessionid get() { return m_sessionId; }
00196     }
00197
00198     // Stop advertising the service and pass status to anyone listening for the Stopped event.
00199     void StopInternal(int32 status);
00200
00201     void BusAttachmentStateChanged(_In_ Windows::Devices::AllJoyn::AllJoynBusAttachment^ sender, _In_ Windows::Devices::AllJoyn::AllJoynBusAttachmentStateChangedEventArgs^ args);
00202
00203 private:
00204     virtual event Windows::Foundation::EventHandler<Platform::Object^>^ _Stopped;
00205     virtual event Windows::Foundation::EventHandler<Platform::Object^>^ _SessionLost;
00206     virtual event Windows::Foundation::EventHandler<Platform::Object^>^ _SessionMemberAdded;
00207     virtual event Windows::Foundation::EventHandler<Platform::Object^>^ _SessionMemberRemoved;
00208
00209     // "Sends the personal AP information to the onboardee"
00210     static void CallConfigureWiFiHandler(_Inout_ alljoyn_busobject busObject, _In_ alljoyn_message message);
00211     // "Tells the onboardee to connect to the personal AP"
00212     static void CallConnectHandler(_Inout_ alljoyn_busobject busObject, _In_ alljoyn_message message);
00213     // "Tells the onboardee to disconnect from the personal AP"
00214     static void CallOffboardHandler(_Inout_ alljoyn_busobject busObject, _In_ alljoyn_message message);
00215     // "Scans all the Wi-Fi access points in the onboardee's proximity"
00216     static void CallGetScanInfoHandler(_Inout_ alljoyn_busobject busObject, _In_ alljoyn_message message);
00217     // "This signal is emitted when the connection attempt against the personal AP is completed"
00218     static void CallConnectionResultSignalHandler(_In_ const alljoyn_interfacedescription_member* member, _In_ alljoyn_message message);
00219
00220     // Register a callback function to handle methods.
00221     QStatus AddMethodHandler(_In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_methodhandler_ptr handler);
00222     // Register a callback function to handle incoming signals.
00223     QStatus AddSignalHandler(_In_ alljoyn_busattachment busAttachment, _In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_signalhandler_ptr handler);
00224
00225     void UnregisterFromBus();
00226
00227     Windows::Devices::AllJoyn::AllJoynBusAttachment^ m_busAttachment;
00228     Windows::Foundation::EventRegistrationToken m_busAttachmentStateChangedToken;
00229     OnboardingLegacySignals^ m_signals;
00230     IOnboardingService^ m_serviceInterface;
00231     Platform::String^ m_ServiceObjectPath;
00232
00233     alljoyn_busobject m_busObject;
00234     alljoyn_sessionportlistener m_sessionPortListener;
00235     alljoyn_sessionlistener m_sessionListener;
00236     alljoyn_sessionport m_sessionPort;
00237     alljoyn_sessionid m_sessionId;
00238
00239     // Used to pass a pointer to this class to callbacks
00240     Platform::WeakReference* m_weak;
00241
00242     // These maps are required because we need a way to pass the producer to the method
00243     // and signal handlers, but the current AllJoyn C API does not allow passing a context to these
00244     // callbacks.
00245     static std::map<alljoyn_busobject, Platform::WeakReference*> SourceObjects;
00246     static std::map<alljoyn_interfacedescription, Platform::WeakReference*> SourceInterfaces;
00247 };
00248
00249 } } }
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cppwinrt/CopyText.cpp Source File

  • Clipboard
  • cppwinrt

CopyText.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "CopyText.h"
00014 #include "CopyText.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::ApplicationModel::DataTransfer;
00018 using namespace Windows::Data::Html;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Storage::Streams;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     CopyText::CopyText()
00028     {
00029         InitializeComponent();
00030         Description().NavigateToString(htmlFragment);
00031     }
00032
00033     void CopyText::CopyButton_Click(IInspectable const&, RoutedEventArgs const&)
00034     {
00035         OutputText().Text(L"");
00036         OutputResourceMapKeys().Text(L"");
00037         OutputHtml().NavigateToString(L"<HTML></HTML>");
00038
00039         // Set the content to DataPackage as html format
00040         hstring htmlFormat = HtmlFormatHelper::CreateHtmlFormat(this->htmlFragment);
00041         auto dataPackage = DataPackage();
00042         dataPackage.SetHtmlFormat(htmlFormat);
00043
00044         // Set the content to DataPackage as (plain) text format
00045         hstring plainText = HtmlUtilities::ConvertToText(this->htmlFragment);
00046         dataPackage.SetText(plainText);
00047
00048         // Populate resourceMap with StreamReference objects corresponding to local image files embedded in HTML
00049         auto imgUri = Uri(imgSrc);
00050         auto imgRef = RandomAccessStreamReference::CreateFromUri(imgUri);
00051         dataPackage.ResourceMap().Insert(imgSrc, imgRef);
00052
00053         // Set the DataPackage to clipboard.
00054         if (Clipboard::SetContentWithOptions(dataPackage, nullptr))
00055         {
00056             rootPage.NotifyUser(L"Text and HTML formats have been copied to clipboard.", NotifyType::StatusMessage);
00057         }
00058         else
00059         {
00060             // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
00061             rootPage.NotifyUser(L"Error copying content to clipboard.", NotifyType::ErrorMessage);
00062         }
00063     }
00064
00065     fire_and_forget CopyText::PasteButton_Click(IInspectable const&, RoutedEventArgs const&)
00066     {
00067         auto lifetime = get_strong();
00068
00069         rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00070         OutputText().Text(L"");
00071         OutputResourceMapKeys().Text(L"");
00072         OutputHtml().NavigateToString(L"<HTML></HTML>");
00073
00074         auto dataPackageView = Clipboard::GetContent();
00075         if (dataPackageView.Contains(StandardDataFormats::Text()))
00076         {
00077             try
00078             {
00079                 auto text = co_await dataPackageView.GetTextAsync();
00080                 OutputText().Text(L"Text: \n" + text);
00081             }
00082             catch (hresult_error const& ex)
00083             {
00084                 rootPage.NotifyUser(L"Error retrieving Text format from Clipboard: " + ex.message(), NotifyType::ErrorMessage);
00085             }
00086         }
00087         else
00088         {
00089             OutputText().Text(L"Text: \nText format is not available in clipboard");
00090         }
00091
00092         if (dataPackageView.Contains(StandardDataFormats::Html()))
00093         {
00094             DisplayResourceMapAsync(dataPackageView);
00095
00096             hstring htmlFormat = L"";
00097             try
00098             {
00099                 htmlFormat = co_await dataPackageView.GetHtmlFormatAsync();
00100             }
00101             catch (hresult_error const& ex)
00102             {
00103                 rootPage.NotifyUser(L"Error retrieving HTML format from Clipboard: " + ex.message(), NotifyType::ErrorMessage);
00104             }
00105
00106             if (!htmlFormat.empty())
00107             {
00108                 hstring fragment = HtmlFormatHelper::GetStaticFragment(htmlFormat);
00109                 OutputHtml().NavigateToString(L"HTML:<br/ > " + fragment);
00110             }
00111         }
00112         else
00113         {
00114             OutputHtml().NavigateToString(L"HTML:<br/ > HTML format is not available in clipboard");
00115         }
00116     }
00117
00118     // Note: this sample is not trying to resolve and render the HTML using resource map.
00119     // Please refer to the Clipboard JavaScript sample for an example of how to use resource map
00120     // for local images display within an HTML format. This sample will only demonstrate how to
00121     // get a resource map object and extract its key values
00122     fire_and_forget CopyText::DisplayResourceMapAsync(DataPackageView dataPackageView)
00123     {
00124         auto lifetime = get_strong();
00125
00126         std::wostringstream output;
00127         output << std::endl << L"Resource map: ";
00128
00129         IMapView<hstring, RandomAccessStreamReference> resMap = nullptr;
00130         try
00131         {
00132             resMap = co_await dataPackageView.GetResourceMapAsync();
00133         }
00134         catch (hresult_error const& ex)
00135         {
00136             rootPage.NotifyUser(L"Error retrieving Resource map from Clipboard: " + ex.message(), NotifyType::ErrorMessage);
00137         }
00138
00139         if (resMap)
00140         {
00141             if (resMap.Size() > 0)
00142             {
00143                 for (auto&& item : resMap)
00144                 {
00145                     output << std::endl << L"Key: " << std::wstring_view(item.Key());
00146                 }
00147             }
00148             else
00149             {
00150                 output << std::endl << L"Resource map is empty";
00151             }
00152         }
00153         OutputResourceMapKeys().Text(output.str());
00154     }
00155 }
00156
Generated on Fri Nov 15 2024 22:18:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/AdaptiveTemplates/Image/Src/FromAppPackage/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • AdaptiveTemplates
  • Image
  • Src
  • FromAppPackage

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Notifications;
00003 using Windows.UI.Popups;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00008
00009 namespace Notifications.ScenarioPages.Toasts.AdaptiveTemplates.Image.Src.FromAppPackage
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     public sealed partial class ScenarioElement : UserControl
00015     {
00016         public ScenarioElement()
00017         {
00018             this.InitializeComponent();
00019         }
00020
00021         private void UserControl_Loaded(object sender, RoutedEventArgs e)
00022         {
00023             Initialize();
00024         }
00025
00026         private void Initialize()
00027         {
00028             // Clear all existing notifications
00029             ToastNotificationManager.History.Clear();
00030
00031             // Pop notifications
00032             popToastControl.Payload =
00033                 $@"
00034                 <toast scenario='reminder'>
00035                     <visual>
00036                         <binding template='ToastGeneric'>
00037                             <text>Image Src - From App Package</text>
00038                             <text>Make sure an image is displayed below this text.</text>
00039                             <image src='ms-appx:///ScenarioPages/Toasts/AdaptiveTemplates/Image/Src/FromAppPackage/Image.jpg'/>
00040                         </binding>
00041                     </visual>
00042                 </toast>";
00043         }
00044
00045         private async void Error(string message)
00046         {
00047             await new MessageDialog(message, "ERROR").ShowAsync();
00048         }
00049     }
00050 }
Generated on Fri Nov 15 2024 22:20:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cs/Scenario3_Polling.xaml.cs Source File

  • Accelerometer
  • cs

Scenario3_Polling.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Devices.Sensors;
00014 using Windows.UI.Core;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario3_Polling : Page
00022     {
00023         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00024         // as NotifyUser()
00025         MainPage rootPage = MainPage.Current;
00026
00027         private Accelerometer _accelerometer;
00028         private uint _desiredReportInterval;
00029         private DispatcherTimer _dispatcherTimer;
00030
00031         public Scenario3_Polling()
00032         {
00033             this.InitializeComponent();
00034         }
00035
00036         protected override void OnNavigatedTo(NavigationEventArgs e)
00037         {
00038             _accelerometer = Accelerometer.GetDefault(rootPage.AccelerometerReadingType);
00039             if (_accelerometer != null)
00040             {
00041                 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00042                 // This value will be used later to activate the sensor.
00043                 _desiredReportInterval = Math.Max(_accelerometer.MinimumReportInterval, 16);
00044
00045                 // Set up a DispatchTimer
00046                 _dispatcherTimer = new DispatcherTimer();
00047                 _dispatcherTimer.Tick += DisplayCurrentReading;
00048                 _dispatcherTimer.Interval = TimeSpan.FromMilliseconds(_desiredReportInterval);
00049
00050                 rootPage.NotifyUser(rootPage.AccelerometerReadingType + " accelerometer ready", NotifyType.StatusMessage);
00051                 ScenarioEnableButton.IsEnabled = true;
00052             }
00053             else
00054             {
00055                 rootPage.NotifyUser(rootPage.AccelerometerReadingType + " accelerometer not found", NotifyType.ErrorMessage);
00056             }
00057         }
00058
00059         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00060         {
00061             if (ScenarioDisableButton.IsEnabled)
00062             {
00063                 ScenarioDisable();
00064             }
00065         }
00066
00067         /// <summary>
00068         /// This is the event handler for VisibilityChanged events. You would register for these notifications
00069         /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00070         /// </summary>
00071         /// <param name="sender"></param>
00072         /// <param name="e">
00073         /// Event data that can be examined for the current visibility state.
00074         /// </param>
00075         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00076         {
00077             if (ScenarioDisableButton.IsEnabled)
00078             {
00079                 if (e.Visible)
00080                 {
00081                     // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00082                     _dispatcherTimer.Start();
00083                 }
00084                 else
00085                 {
00086                     // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00087                     _dispatcherTimer.Stop();
00088                 }
00089             }
00090         }
00091
00092         /// <summary>
00093         /// This is the dispatcher callback.
00094         /// </summary>
00095         /// <param name="sender"></param>
00096         /// <param name="args"></param>
00097         private void DisplayCurrentReading(object sender, object args)
00098         {
00099             AccelerometerReading reading = _accelerometer.GetCurrentReading();
00100             if (reading != null)
00101             {
00102                 MainPage.SetReadingText(ScenarioOutput, reading);
00103             }
00104         }
00105
00106         /// <summary>
00107         /// This is the click handler for the 'Enable' button.
00108         /// </summary>
00109         private void ScenarioEnable()
00110         {
00111             // Set the report interval to enable the sensor for polling
00112             _accelerometer.ReportInterval = _desiredReportInterval;
00113
00114             Window.Current.VisibilityChanged += VisibilityChanged;
00115             _dispatcherTimer.Start();
00116
00117             ScenarioEnableButton.IsEnabled = false;
00118             ScenarioDisableButton.IsEnabled = true;
00119         }
00120
00121         /// <summary>
00122         /// This is the click handler for the 'Disable' button.
00123         /// </summary>
00124         private void ScenarioDisable()
00125         {
00126             Window.Current.VisibilityChanged -= VisibilityChanged;
00127
00128             // Stop the dispatcher
00129             _dispatcherTimer.Stop();
00130
00131             // Restore the default report interval to release resources while the sensor is not in use
00132             _accelerometer.ReportInterval = 0;
00133
00134             ScenarioEnableButton.IsEnabled = true;
00135             ScenarioDisableButton.IsEnabled = false;
00136         }
00137     }
00138 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cppwinrt/Scenario3_ActiveSymbologies.cpp Source File

  • BarcodeScanner
  • cppwinrt

Scenario3_ActiveSymbologies.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
00002 #include "Scenario3_ActiveSymbologies.h"
00003 #include "Scenario3_ActiveSymbologies.g.cpp"
00004
00005 namespace winrt
00006 {
00007     using namespace Windows::Foundation;
00008     using namespace Windows::Foundation::Collections;
00009     using namespace Windows::Devices::PointOfService;
00010     using namespace Windows::UI::Core;
00011     using namespace Windows::UI::Xaml;
00012     using namespace Windows::UI::Xaml::Data;
00013     using namespace Windows::UI::Xaml::Controls;
00014     using namespace Windows::UI::Xaml::Navigation;
00015 }
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     Scenario3_ActiveSymbologies::Scenario3_ActiveSymbologies()
00020     {
00021         InitializeComponent();
00022
00023         m_listOfSymbologies = single_threaded_observable_vector<SDKTemplate::SymbologyListEntry>();
00024         SymbologyListSource().Source(m_listOfSymbologies);
00025     }
00026
00027     /// <summary>
00028     /// Invoked when this page is about to be displayed in a Frame.
00029     /// </summary>
00030     void Scenario3_ActiveSymbologies::OnNavigatedTo(NavigationEventArgs const&)
00031     {
00032         ResetTheScenarioState();
00033     }
00034
00035     /// <summary>
00036     /// Invoked when this page is no longer displayed.
00037     /// </summary>
00038     void Scenario3_ActiveSymbologies::OnNavigatedFrom(NavigationEventArgs const&)
00039     {
00040         ResetTheScenarioState();
00041     }
00042
00043     /// <summary>
00044     /// Event Handler for Start Scan Button Click.
00045     /// Sets up the barcode scanner to be ready to receive the data events from the scan.
00046     /// </summary>
00047     fire_and_forget Scenario3_ActiveSymbologies::ScenarioStartScanButton_Click(IInspectable const&, RoutedEventArgs const&)
00048     {
00049         auto lifetime = get_strong();
00050
00051         ScenarioStartScanButton().IsEnabled(false);
00052
00053         m_rootPage.NotifyUser(L"Acquiring barcode scanner object.", NotifyType::StatusMessage);
00054
00055         // create the barcode scanner.
00056         m_scanner = co_await BarcodeScanner::GetDefaultAsync();
00057
00058         if (m_scanner)
00059         {
00060             // Claim the scanner for exclusive use and enable it so raises DataReceived events.
00061             m_claimedScanner = co_await m_scanner.ClaimScannerAsync();
00062             if (m_claimedScanner)
00063             {
00064                 // It is always a good idea to have a release device requested event handler.
00065                 // If this event is not handled, then another app can claim ownership of the barcode scanner.
00066                 m_scannerReleaseRequestedToken = m_claimedScanner.ReleaseDeviceRequested({ get_weak(), &Scenario3_ActiveSymbologies::claimedScanner_ReleaseDeviceRequested });
00067
00068                 // after successfully claiming, attach the datareceived event handler.
00069                 m_scannerDataReceivedToken = m_claimedScanner.DataReceived({ get_weak(), &Scenario3_ActiveSymbologies::claimedScanner_DataReceived });
00070
00071                 // Ask the platform to decode the data by default. When this is set, the platform
00072                 // will decode the raw data from the barcode scanner and include in the
00073                 // BarcodeScannerReport.ScanDataLabel and ScanDataType in the DataReceived event.
00074                 m_claimedScanner.IsDecodeDataEnabled(true);
00075
00076                 // Enable the scanner so it raises DataReceived events.
00077                 // Do this after adding the DataReceived event handler.
00078                 co_await m_claimedScanner.EnableAsync();
00079
00080                 // after successful claim, list supported symbologies
00081                 auto supportedSymbologies = co_await m_scanner.GetSupportedSymbologiesAsync();
00082                 for (uint32_t symbology : supportedSymbologies)
00083                 {
00084                     m_listOfSymbologies.Append(SymbologyListEntry{ symbology });
00085                 }
00086
00087                 // reset the button state
00088                 ScenarioEndScanButton().IsEnabled(true);
00089                 SetActiveSymbologiesButton().IsEnabled(true);
00090
00091                 m_rootPage.NotifyUser(L"Ready to scan. Device ID: " + m_claimedScanner.DeviceId(), NotifyType::StatusMessage);
00092             }
00093             else
00094             {
00095                 m_scanner.Close();
00096                 m_scanner = nullptr;
00097                 ScenarioStartScanButton().IsEnabled(true);
00098                 m_rootPage.NotifyUser(L"Claim barcode scanner failed.", NotifyType::ErrorMessage);
00099             }
00100         }
00101         else
00102         {
00103             ScenarioStartScanButton().IsEnabled(true);
00104             m_rootPage.NotifyUser(L"Barcode scanner not found. Please connect a barcode scanner.", NotifyType::ErrorMessage);
00105         }
00106     }
00107
00108     /// <summary>
00109     /// Event handler for the Release Device Requested event fired when barcode scanner receives Claim request from another application
00110     /// </summary>
00111     /// <param name="e"> Contains the ClamiedBarcodeScanner that is sending this request</param>
00112     void Scenario3_ActiveSymbologies::claimedScanner_ReleaseDeviceRequested(IInspectable const&, ClaimedBarcodeScanner const& e)
00113     {
00114         // always retain the device
00115         e.RetainDevice();
00116         m_rootPage.NotifyUser(L"Event ReleaseDeviceRequested received. Retaining the barcode scanner.", NotifyType::StatusMessage);
00117     }
00118
00119
00120     /// <summary>
00121     /// Event handler for the DataReceived event fired when a barcode is scanned by the barcode scanner
00122     /// </summary>
00123     /// <param name="args"> Contains the BarcodeScannerDataReceivedEventArgs which contains the data obtained in the scan</param>
00124     fire_and_forget Scenario3_ActiveSymbologies::claimedScanner_DataReceived(ClaimedBarcodeScanner const&, BarcodeScannerDataReceivedEventArgs args)
00125     {
00126         auto lifetime = get_strong();
00127
00128         // need to update the UI data on the dispatcher thread.
00129         // update the UI with the data received from the scan.
00130         co_await resume_foreground(Dispatcher());
00131
00132         // read the data from the buffer and convert to string.
00133         ScenarioOutputScanDataLabel().Text(GetDataLabelString(args.Report().ScanDataLabel(), args.Report().ScanDataType()));
00134         ScenarioOutputScanData().Text(GetDataString(args.Report().ScanData()));
00135         ScenarioOutputScanDataType().Text(BarcodeSymbologies::GetName(args.Report().ScanDataType()));
00136     }
00137
00138     /// <summary>
00139     /// Reset the Scenario state
00140     /// </summary>
00141     void Scenario3_ActiveSymbologies::ResetTheScenarioState()
00142     {
00143         if (m_claimedScanner)
00144         {
00145             // Detach the event handlers
00146             m_claimedScanner.DataReceived(m_scannerDataReceivedToken);
00147             m_claimedScanner.ReleaseDeviceRequested(m_scannerReleaseRequestedToken);
00148
00149             // Release the Barcode Scanner and set to nullptr
00150             m_claimedScanner.Close();
00151             m_claimedScanner = nullptr;
00152         }
00153
00154         if (m_scanner)
00155         {
00156             m_scanner.Close();
00157             m_scanner = nullptr;
00158         }
00159
00160         // Reset the UI if we are still the current page.
00161         if (Frame().Content() == *this)
00162         {
00163             m_rootPage.NotifyUser(L"Click the start scanning button to begin.", NotifyType::StatusMessage);
00164             ScenarioOutputScanData().Text(L"No data");
00165             ScenarioOutputScanDataLabel().Text(L"No data");
00166             ScenarioOutputScanDataType().Text(L"No data");
00167
00168             // reset the button state
00169             SetActiveSymbologiesButton().IsEnabled(false);
00170             ScenarioEndScanButton().IsEnabled(false);
00171             ScenarioStartScanButton().IsEnabled(true);
00172
00173             // reset symbology list
00174             m_listOfSymbologies.Clear();
00175         }
00176     }
00177
00178     /// <summary>
00179     /// Event handler for End Scan Button Click.
00180     /// Releases the Barcode Scanner and resets the text in the UI
00181     /// </summary>
00182     void Scenario3_ActiveSymbologies::ScenarioEndScanButton_Click(IInspectable const&, RoutedEventArgs const&)
00183     {
00184         ResetTheScenarioState();
00185     }
00186
00187     fire_and_forget Scenario3_ActiveSymbologies::SetActiveSymbologies_Click(IInspectable const&, RoutedEventArgs const&)
00188     {
00189         auto lifetime = get_strong();
00190
00191         if (m_claimedScanner)
00192         {
00193             std::vector<uint32_t> symbologyList;
00194             for (auto&& symbologyListEntry : m_listOfSymbologies)
00195             {
00196                 if (symbologyListEntry.IsEnabled())
00197                 {
00198                     symbologyList.push_back(symbologyListEntry.Id());
00199                 }
00200             }
00201
00202             co_await m_claimedScanner.SetActiveSymbologiesAsync(std::move(symbologyList));
00203         }
00204     }
00205 }
Generated on Fri Nov 15 2024 22:18:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CachedFileUpdaterPage Member List

This is the complete list of members for CachedFileUpdaterPage, including all inherited members.
Activate(CachedFileUpdaterActivatedEventArgs args) | CachedFileUpdaterPage | [inline]
CachedFileUpdaterPage() | CachedFileUpdaterPage | [inline]
CachedFileUpdaterPage_SizeChanged(object sender, SizeChangedEventArgs e) | CachedFileUpdaterPage | [inline, private]
CachedFileUpdaterPageResized | CachedFileUpdaterPage |
cachedFileUpdaterUI | CachedFileUpdaterPage | [private]
CachedFileUpdaterUI_FileUpdateRequested(CachedFileUpdaterUI sender, FileUpdateRequestedEventArgs args) | CachedFileUpdaterPage | [inline, private]
CachedFileUpdaterUI_UIRequested(CachedFileUpdaterUI sender, object args) | CachedFileUpdaterPage | [inline, private]
Current | CachedFileUpdaterPage | [static]
dispatcher | CachedFileUpdaterPage | [private]
FEATURE_NAME | CachedFileUpdaterPage |
fileUpdateRequest | CachedFileUpdaterPage | [private]
fileUpdateRequestDeferral | CachedFileUpdaterPage | [private]
Footer_Click(object sender, RoutedEventArgs e) | CachedFileUpdaterPage | [inline, private]
HiddenFrame | CachedFileUpdaterPage | [private]
InvalidateLayout() | CachedFileUpdaterPage | [inline, private]
InvalidateSize() | CachedFileUpdaterPage | [inline, private]
LaunchArgs | CachedFileUpdaterPage |
LoadScenario(Type scenarioClass) | CachedFileUpdaterPage | [inline]
NotifyUser(string strMessage, NotifyType type) | CachedFileUpdaterPage | [inline]
OnNavigatedTo(NavigationEventArgs e) | CachedFileUpdaterPage | [inline, protected]
PopulateScenarios() | CachedFileUpdaterPage | [inline, private]
ScenarioLoaded | CachedFileUpdaterPage |
scenarios | CachedFileUpdaterPage | [private]
Scenarios_SelectionChanged(object sender, SelectionChangedEventArgs e) | CachedFileUpdaterPage | [inline, private]
SetFeatureName(string str) | CachedFileUpdaterPage | [inline, private]
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cs/ShareImage.xaml.cs Source File

  • ShareSource
  • cs

ShareImage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.ApplicationModel.DataTransfer;
00015 using Windows.Storage;
00016 using Windows.Storage.Pickers;
00017 using Windows.Storage.Streams;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Media.Imaging;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class ShareImage
00024     {
00025         private StorageFile imageFile;
00026
00027         public ShareImage()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         protected override bool GetShareContent(DataRequest request)
00033         {
00034             bool succeeded = false;
00035
00036             if (this.imageFile != null)
00037             {
00038                 DataPackage requestData = request.Data;
00039                 requestData.Properties.Title = TitleInputBox.Text;
00040                 requestData.Properties.Description = DescriptionInputBox.Text; // The description is optional.
00041                 requestData.Properties.ContentSourceApplicationLink = ApplicationLink;
00042
00043                 // It's recommended to use both SetBitmap and SetStorageItems for sharing a single image
00044                 // since the target app may only support one or the other.
00045
00046                 List<IStorageItem> imageItems = new List<IStorageItem>();
00047                 imageItems.Add(this.imageFile);
00048                 requestData.SetStorageItems(imageItems);
00049
00050                 RandomAccessStreamReference imageStreamRef = RandomAccessStreamReference.CreateFromFile(this.imageFile);
00051                 requestData.Properties.Thumbnail = imageStreamRef;
00052                 requestData.SetBitmap(imageStreamRef);
00053                 succeeded = true;
00054             }
00055             else
00056             {
00057                 request.FailWithDisplayText("Select an image you would like to share and try again.");
00058             }
00059             return succeeded;
00060         }
00061
00062         private async void SelectImageButton_Click(object sender, RoutedEventArgs e)
00063         {
00064             FileOpenPicker imagePicker = new FileOpenPicker
00065             {
00066                 ViewMode = PickerViewMode.Thumbnail,
00067                 SuggestedStartLocation = PickerLocationId.PicturesLibrary,
00068                 FileTypeFilter = { ".jpg", ".png", ".bmp", ".gif", ".tif" }
00069             };
00070
00071             StorageFile pickedImage = await imagePicker.PickSingleFileAsync();
00072
00073             if (pickedImage != null)
00074             {
00075                 this.imageFile = pickedImage;
00076
00077                 // Display the image in the UI.
00078                 IRandomAccessStream displayStream = await pickedImage.OpenAsync(FileAccessMode.Read);
00079                 BitmapImage bitmapImage = new BitmapImage();
00080                 bitmapImage.SetSource(displayStream);
00081                 ImageHolder.Source = bitmapImage;
00082                 this.rootPage.NotifyUser("Selected " + pickedImage.Name + ".", NotifyType.StatusMessage);
00083
00084                 ShareStep.Visibility = Visibility.Visible;
00085             }
00086         }
00087     }
00088 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/ProducerExperiences/cs/Scenario1ViewModel.cs Source File

  • AllJoyn
  • ProducerExperiences
  • cs

Scenario1ViewModel.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using com.microsoft.Samples.SecureInterface;
00013 using SDKTemplate;
00014 using System;
00015 using System.ComponentModel;
00016 using System.Runtime.CompilerServices;
00017 using System.Windows.Input;
00018 using Windows.Devices.AllJoyn;
00019 using Windows.UI.Core;
00020 using Windows.UI.Xaml;
00021
00022 namespace AllJoynProducerExperiences
00023 {
00024     class Scenario1ViewModel : INotifyPropertyChanged
00025     {
00026         private MainPage rootPage;
00027         private CoreDispatcher m_dispatcher;
00028         private string m_key = "";
00029         private bool m_isBusAttachmentConnected = false;
00030         private AllJoynBusAttachment m_busAttachment = null;
00031         private SecureInterfaceProducer m_producer = null;
00032         private Visibility m_producerOptionsVisibility = Visibility.Collapsed;
00033
00034         public Scenario1ViewModel()
00035         {
00036             m_dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
00037             rootPage = MainPage.Current;
00038         }
00039
00040         public event PropertyChangedEventHandler PropertyChanged;
00041
00042         public string Key
00043         {
00044             get
00045             {
00046                 return m_key;
00047             }
00048             private set
00049             {
00050                 m_key = value;
00051                 RaisePropertyChangedEventAsync();
00052             }
00053         }
00054
00055         public bool IsUpperCaseEnabled
00056         {
00057             get
00058             {
00059                 return AppData.IsUpperCaseEnabled;
00060             }
00061             set
00062             {
00063                 AppData.IsUpperCaseEnabled = value;
00064                 if (m_producer != null)
00065                 {
00066                     m_producer.EmitIsUpperCaseEnabledChanged();
00067                 }
00068             }
00069         }
00070
00071         public string SignalText { get; set; }
00072
00073         public Visibility ProducerOptionsVisibility
00074         {
00075             get
00076             {
00077                 return m_producerOptionsVisibility;
00078             }
00079             private set
00080             {
00081                 m_producerOptionsVisibility = value;
00082                 RaisePropertyChangedEventAsync();
00083             }
00084         }
00085
00086         public ICommand LaunchProducer
00087         {
00088             get
00089             {
00090                 return new RelayCommand((object args) =>
00091                 {
00092                     Start();
00093                 });
00094             }
00095         }
00096
00097         public ICommand SendSignal
00098         {
00099             get
00100             {
00101                 return new RelayCommand((object args) =>
00102                 {
00103                     SendTextSignal();
00104                 });
00105             }
00106         }
00107
00108         public void ScenarioCleanup()
00109         {
00110             if (m_producer != null)
00111             {
00112                 m_producer.Stop();
00113                 m_producer.Dispose();
00114             }
00115
00116             if (m_busAttachment != null)
00117             {
00118                 m_busAttachment.CredentialsRequested -= AlljoynBusAttachment_CredentialsRequested;
00119                 m_busAttachment.AuthenticationComplete -= AlljoynBusAttachment_AuthenticationComplete;
00120                 m_busAttachment.StateChanged -= AlljoynBusAttachment_StateChanged;
00121                 m_busAttachment.Disconnect();
00122             }
00123         }
00124
00125         protected async void RaisePropertyChangedEventAsync([CallerMemberName] string name = "")
00126         {
00127             await m_dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00128             {
00129                 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
00130             });
00131         }
00132
00133         private void Start()
00134         {
00135             // Prevent launching the producer again if it is already launched.
00136             if (m_isBusAttachmentConnected)
00137             {
00138                 UpdateStatusAsync("Already launched.", NotifyType.StatusMessage);
00139             }
00140             else
00141             {
00142                 UpdateStatusAsync("Launching...", NotifyType.StatusMessage);
00143
00144                 m_busAttachment = new AllJoynBusAttachment();
00145                 m_busAttachment.StateChanged += AlljoynBusAttachment_StateChanged;
00146                 m_busAttachment.AuthenticationMechanisms.Clear();
00147                 m_busAttachment.AuthenticationMechanisms.Add(AllJoynAuthenticationMechanism.EcdheSpeke);
00148                 m_busAttachment.AuthenticationComplete += AlljoynBusAttachment_AuthenticationComplete;
00149                 m_busAttachment.CredentialsRequested += AlljoynBusAttachment_CredentialsRequested;
00150
00151                 // Optional - Populate About data for the producer.
00152                 m_busAttachment.AboutData.DefaultManufacturer = "Contoso";
00153                 m_busAttachment.AboutData.SupportUrl = new Uri("http://www.contoso.com/support");
00154                 m_busAttachment.AboutData.ModelNumber = "ContosoTestModel";
00155                 m_busAttachment.AboutData.DefaultDescription = "A secure AllJoyn sample";
00156
00157                 // Generate the one-time 6-digit numeric pre-shared key.
00158                 Random rnd = new Random();
00159                 Key = rnd.Next(100000, 1000000).ToString();
00160
00161                 // Initialize the producer object generated by the AllJoynCodeGenerator tool.
00162                 m_producer = new SecureInterfaceProducer(m_busAttachment);
00163
00164                 // Instantiate SecureInterfaceService which will handle the concatenation method calls.
00165                 m_producer.Service = new SecureInterfaceService();
00166
00167                 // Start advertising the service.
00168                 m_producer.Start();
00169             }
00170         }
00171
00172         private void SendTextSignal()
00173         {
00174             if (m_producer != null)
00175             {
00176                 if (!string.IsNullOrWhiteSpace(SignalText))
00177                 {
00178                     m_producer.Signals.TextSent(SignalText);
00179                     UpdateStatusAsync("Signal sent.", NotifyType.StatusMessage);
00180                 }
00181                 else
00182                 {
00183                     UpdateStatusAsync("No text entered.", NotifyType.ErrorMessage);
00184                 }
00185             }
00186         }
00187
00188         private void AlljoynBusAttachment_StateChanged(AllJoynBusAttachment sender, AllJoynBusAttachmentStateChangedEventArgs args)
00189         {
00190             switch (args.State)
00191             {
00192                 case AllJoynBusAttachmentState.Disconnected:
00193                     UpdateStatusAsync(string.Format("Disconnected from the AllJoyn bus attachment with AllJoyn status: 0x{0:X}.", args.Status), NotifyType.StatusMessage);
00194                     m_isBusAttachmentConnected = false;
00195                     ProducerOptionsVisibility = Visibility.Collapsed;
00196                     AppData.IsUpperCaseEnabledPropertyDataChanged -= AppData_IsUpperCaseEnabledPropertyDataChanged;
00197                     break;
00198                 case AllJoynBusAttachmentState.Connected:
00199                     UpdateStatusAsync("Launched.", NotifyType.StatusMessage);
00200                     m_isBusAttachmentConnected = true;
00201                     ProducerOptionsVisibility = Visibility.Visible;
00202                     AppData.IsUpperCaseEnabledPropertyDataChanged += AppData_IsUpperCaseEnabledPropertyDataChanged;
00203                     break;
00204                 default:
00205                     break;
00206             }
00207         }
00208
00209         private void AlljoynBusAttachment_AuthenticationComplete(AllJoynBusAttachment sender, AllJoynAuthenticationCompleteEventArgs args)
00210         {
00211             if (args.Succeeded)
00212             {
00213                 UpdateStatusAsync("Authentication was successful.", NotifyType.StatusMessage);
00214             }
00215             else
00216             {
00217                 UpdateStatusAsync("Authentication failed.", NotifyType.ErrorMessage);
00218             }
00219         }
00220
00221         private void AlljoynBusAttachment_CredentialsRequested(AllJoynBusAttachment sender, AllJoynCredentialsRequestedEventArgs args)
00222         {
00223             if (args.Credentials.AuthenticationMechanism == AllJoynAuthenticationMechanism.EcdheSpeke)
00224             {
00225                 args.Credentials.PasswordCredential.Password = m_key;
00226             }
00227             else
00228             {
00229                 UpdateStatusAsync("Unexpected authentication mechanism.", NotifyType.ErrorMessage);
00230             }
00231         }
00232
00233         private void AppData_IsUpperCaseEnabledPropertyDataChanged(object sender, EventArgs e)
00234         {
00235             RaisePropertyChangedEventAsync("IsUpperCaseEnabled");
00236         }
00237
00238         private async void UpdateStatusAsync(string status, NotifyType statusType)
00239         {
00240             await m_dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00241             {
00242                 rootPage.NotifyUser(status, statusType);
00243             });
00244         }
00245     }
00246 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePickerContracts/cs/FileOpenPickerPage.xaml.cs Source File

  • FilePickerContracts
  • cs

FileOpenPickerPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Collections.Generic;
00013 using Windows.ApplicationModel.Activation;
00014 using Windows.Storage.Pickers.Provider;
00015 using Windows.UI.ViewManagement;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Markup;
00019 using Windows.UI.Xaml.Navigation;
00020
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class FileOpenPickerPage : Page
00028     {
00029         public const string FEATURE_NAME = "File Open Picker Page";
00030
00031         public Windows.ApplicationModel.Activation.LaunchActivatedEventArgs LaunchArgs;
00032
00033         public static FileOpenPickerPage Current;
00034
00035         private Frame HiddenFrame = null;
00036
00037         internal FileOpenPickerUI fileOpenPickerUI = null;
00038
00039         List<Scenario> scenarios = new List<Scenario>
00040         {
00041             new Scenario() { Title = "1) Pick a file from the application package", ClassType = typeof(FilePickerContracts.FileOpenPicker_PickAppFile) },
00042             new Scenario() { Title = "2) Pick a file from a URI",           ClassType = typeof(FilePickerContracts.FileOpenPicker_PickURLFile) },
00043             new Scenario() { Title = "3) Pick cached file",                 ClassType = typeof(FilePickerContracts.FileOpenPicker_PickCachedFile) },
00044         };
00045
00046         public void Activate(FileOpenPickerActivatedEventArgs args)
00047         {
00048             // cache FileOpenPickerUI
00049             fileOpenPickerUI = args.FileOpenPickerUI;
00050             Window.Current.Content = this;
00051             this.OnNavigatedTo(null);
00052             Window.Current.Activate();
00053         }
00054
00055         public FileOpenPickerPage()
00056         {
00057             this.InitializeComponent();
00058
00059             // This is a static public property that will allow downstream pages to get
00060             // a handle to the FileOpenPickerPage instance in order to call methods that are in this class.
00061             Current = this;
00062
00063             // This frame is hidden, meaning it is never shown.  It is simply used to load
00064             // each scenario page and then pluck out the input and output sections and
00065             // place them into the UserControls on the main page.
00066             HiddenFrame = new Windows.UI.Xaml.Controls.Frame();
00067             HiddenFrame.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00068             LayoutRoot.Children.Add(HiddenFrame);
00069
00070             // Populate the sample title from the constant in this file.
00071             SetFeatureName(FEATURE_NAME);
00072         }
00073
00074         void FileOpenPickerPage_SizeChanged(object sender, SizeChangedEventArgs e)
00075         {
00076             InvalidateSize();
00077         }
00078
00079         /// <summary>
00080         /// Invoked when this page is about to be displayed in a Frame.
00081         /// </summary>
00082         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00083         /// property is typically used to configure the page.</param>
00084         protected override void OnNavigatedTo(NavigationEventArgs e)
00085         {
00086             PopulateScenarios();
00087             InvalidateLayout();
00088         }
00089
00090         private void InvalidateSize()
00091         {
00092             // Get the window width
00093             double windowWidth = this.ActualWidth;
00094
00095             if (windowWidth != 0.0)
00096             {
00097                 // Get the width of the ListBox.
00098                 double listBoxWidth = Scenarios.ActualWidth;
00099
00100                 // Is the ListBox using any margins that we need to consider?
00101                 double listBoxMarginLeft = Scenarios.Margin.Left;
00102                 double listBoxMarginRight = Scenarios.Margin.Right;
00103
00104                 // Figure out how much room is left after considering the list box width
00105                 double availableWidth = windowWidth - listBoxWidth;
00106
00107                 // Is the top most child using margins?
00108                 double layoutRootMarginLeft = ContentRoot.Margin.Left;
00109                 double layoutRootMarginRight = ContentRoot.Margin.Right;
00110
00111                 // We have different widths to use depending on the view state
00112                 if (this.ActualWidth >= 768)
00113                 {
00114                     // Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
00115                     // and the LayoutRoot's margins
00116                     InputSection.Width = ((availableWidth) - (layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight));
00117                 }
00118                 else
00119                 {
00120                     // Make us as big as the left over space, factoring in just the LayoutRoot's margins.
00121                         InputSection.Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight));
00122
00123                 }
00124             }
00125             InvalidateLayout();
00126         }
00127
00128         private void InvalidateLayout()
00129         {
00130
00131             if (this.ActualWidth < 768)
00132             {
00133                 Grid.SetRow(DescriptionText, 3);
00134                 Grid.SetColumn(DescriptionText, 0);
00135
00136                 Grid.SetRow(InputSection, 4);
00137                 Grid.SetColumn(InputSection, 0);
00138
00139                 Grid.SetRow(FooterPanel, 2);
00140                 Grid.SetColumn(FooterPanel, 0);
00141             }
00142             else
00143             {
00144                 Grid.SetRow(DescriptionText, 1);
00145                 Grid.SetColumn(DescriptionText, 1);
00146
00147                 Grid.SetRow(InputSection, 2);
00148                 Grid.SetColumn(InputSection, 1);
00149
00150                 Grid.SetRow(FooterPanel, 1);
00151                 Grid.SetColumn(FooterPanel, 1);
00152             }
00153         }
00154
00155         private void PopulateScenarios()
00156         {
00157             Scenarios.ItemsSource = scenarios;
00158             Scenarios.SelectedIndex = 0;
00159         }
00160
00161         /// <summary>
00162         /// This method is responsible for loading the individual input and output sections for each scenario.  This
00163         /// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
00164         /// and output sections into the respective UserControl on the main page.
00165         /// </summary>
00166         /// <param name="scenarioName"></param>
00167         public void LoadScenario(Type scenarioClass)
00168         {
00169
00170             // Load the ScenarioX.xaml file into the Frame.
00171             HiddenFrame.Navigate(scenarioClass, this);
00172
00173             // Get the top element, the Page, so we can look up the elements
00174             // that represent the input and output sections of the ScenarioX file.
00175             Page hiddenPage = HiddenFrame.Content as Page;
00176
00177             // Get each element.
00178             UIElement input = hiddenPage.FindName("Input") as UIElement;
00179             UIElement output = hiddenPage.FindName("Output") as UIElement;
00180
00181             if (input == null)
00182             {
00183                 // Malformed input section.
00184                 NotifyUser(String.Format(
00185                     "Cannot load scenario input section for {0}.  Make sure root of input section markup has x:Name of 'Input'",
00186                     scenarioClass.Name), NotifyType.ErrorMessage);
00187                 return;
00188             }
00189
00190             if (output == null)
00191             {
00192                 // Malformed output section.
00193                 NotifyUser(String.Format(
00194                     "Cannot load scenario output section for {0}.  Make sure root of output section markup has x:Name of 'Output'",
00195                     scenarioClass.Name), NotifyType.ErrorMessage);
00196                 return;
00197             }
00198
00199             // Find the LayoutRoot which parents the input and output sections in the main page.
00200             Panel panel = hiddenPage.FindName("LayoutRoot") as Panel;
00201
00202             if (panel != null)
00203             {
00204                 // Get rid of the content that is currently in the intput and output sections.
00205                 panel.Children.Remove(input);
00206                 panel.Children.Remove(output);
00207
00208                 // Populate the input and output sections with the newly loaded content.
00209                 InputSection.Content = input;
00210                 OutputSection.Content = output;
00211             }
00212             else
00213             {
00214                 // Malformed Scenario file.
00215                 NotifyUser(String.Format(
00216                     "Cannot load scenario: '{0}'.  Make sure root tag in the '{0}' file has an x:Name of 'LayoutRoot'",
00217                     scenarioClass.Name), NotifyType.ErrorMessage);
00218             }
00219
00220         }
00221
00222         void OnScenarioSelectionChanged()
00223         {
00224             if (Scenarios.SelectedItem != null)
00225             {
00226                 NotifyUser("", NotifyType.StatusMessage);
00227
00228                 Scenario scenario = Scenarios.SelectedItem as Scenario;
00229                 LoadScenario(scenario.ClassType);
00230                 InvalidateSize();
00231             }
00232         }
00233
00234         public void NotifyUser(string strMessage, NotifyType type)
00235         {
00236             switch (type)
00237             {
00238                 // Use the status message style.
00239                 case NotifyType.StatusMessage:
00240                     StatusBlock.Style = Resources["StatusStyle"] as Style;
00241                     break;
00242                 // Use the error message style.
00243                 case NotifyType.ErrorMessage:
00244                     StatusBlock.Style = Resources["ErrorStyle"] as Style;
00245                     break;
00246             }
00247             StatusBlock.Text = strMessage;
00248
00249             // Collapse the StatusBlock if it has no text to conserve real estate.
00250             if (StatusBlock.Text != String.Empty)
00251             {
00252                 StatusBlock.Visibility = Windows.UI.Xaml.Visibility.Visible;
00253             }
00254             else
00255             {
00256                 StatusBlock.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00257             }
00258         }
00259
00260         async void Footer_Click(object sender, RoutedEventArgs e)
00261         {
00262             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00263         }
00264
00265         private void SetFeatureName(string str)
00266         {
00267             FeatureName.Text = str;
00268         }
00269     }
00270 }
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserActivity/cs/Scenario3_AdaptiveCard.xaml.cs Source File

  • UserActivity
  • cs

Scenario3_AdaptiveCard.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.ApplicationModel.UserActivities;
00015 using Windows.Storage;
00016 using Windows.UI.Shell;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class Scenario3_AdaptiveCard : Page
00026     {
00027         private UserActivitySession _currentSession;
00028
00029         public Scenario3_AdaptiveCard()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override async void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             // If we were activated from a URI, say so.
00037             // A real app would use the information in the URI to restore state.
00038             var message = e.Parameter as string;
00039             if (!String.IsNullOrEmpty(message))
00040             {
00041                 MainPage.Current.NotifyUser(message, NotifyType.StatusMessage);
00042             }
00043
00044             await CreateUserActivityAsync();
00045         }
00046
00047         private async Task CreateUserActivityAsync()
00048         {
00049             // Get channel and create activity.
00050             UserActivityChannel channel = UserActivityChannel.GetDefault();
00051             UserActivity activity = await channel.GetOrCreateUserActivityAsync("Scenario3_AdaptiveCard");
00052
00053             // Set deep-link and properties.
00054             activity.ActivationUri = new Uri("sdkUserActivitySample:page?Scenario3_AdaptiveCard");
00055             activity.VisualElements.DisplayText = "User Activity with Adaptive Card";
00056
00057             // Sreate and set Adaptive Card.
00058             StorageFile cardFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/UserActivityCard.json"));
00059             string cardText = await FileIO.ReadTextAsync(cardFile);
00060             activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(cardText);
00061
00062             // Save to activity feed.
00063             await activity.SaveAsync();
00064
00065             // Create a session, which indicates that the user is engaged
00066             // in the activity.
00067             _currentSession = activity.CreateSession();
00068         }
00069
00070         protected override void OnNavigatedFrom(NavigationEventArgs e)
00071         {
00072             // Dispose the session, which indicates that the user is no longer
00073             // engaged in the activity.
00074             _currentSession?.Dispose();
00075         }
00076     }
00077 }
Generated on Fri Nov 15 2024 22:21:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomDecaySound Member List

This is the complete list of members for CustomDecaySound, including all inherited members.
_audioFile | CustomDecaySound | [private]
_environment | CustomDecaySound | [private]
_hrtfParams | CustomDecaySound | [private]
_sourceVoice | CustomDecaySound | [private]
_xaudio2 | CustomDecaySound | [private]
GetEnvironment() | CustomDecaySound | [inline]
Initialize(_In_ LPCWSTR filename) | CustomDecaySound |
OnUpdate(_In_ float x, _In_ float, _In_ float z) | CustomDecaySound |
SetEnvironment(_In_ HrtfEnvironment environment) | CustomDecaySound |
Start() | CustomDecaySound |
Stop() | CustomDecaySound |
~CustomDecaySound() | CustomDecaySound | [virtual]
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/Actions/SystemCommands/SnoozeAndDismiss/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • Actions
  • SystemCommands
  • SnoozeAndDismiss

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Notifications;
00003 using Windows.UI.Popups;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00008
00009 namespace Notifications.ScenarioPages.Toasts.Actions.SystemCommands.SnoozeAndDismiss
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     public sealed partial class ScenarioElement : UserControl
00015     {
00016         public ScenarioElement()
00017         {
00018             this.InitializeComponent();
00019         }
00020
00021         private void UserControl_Loaded(object sender, RoutedEventArgs e)
00022         {
00023             Initialize();
00024         }
00025
00026         private void Initialize()
00027         {
00028             // Clear all existing notifications
00029             ToastNotificationManager.History.Clear();
00030
00031             // Pop notifications
00032             popToastControl.Payload =
00033                 $@"
00034                 <toast activationType='foreground' launch='args' scenario='reminder'>
00035                     <visual>
00036                         <binding template='ToastGeneric'>
00037                             <text>SystemCommands SnoozeAndDismiss</text>
00038                             <text>Make sure there's a dropbox for selecting snooze interval, a snooze button, and a dismiss button. Actions should be handled by system.</text>
00039                         </binding>
00040                     </visual>
00041                     <actions hint-systemCommands = 'SnoozeAndDismiss' />
00042                 </toast>";
00043         }
00044
00045         private async void Error(string message)
00046         {
00047             await new MessageDialog(message, "ERROR").ShowAsync();
00048         }
00049     }
00050 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
context | sealed | [private]
DisambiguateTrips(std::vector< AdventureWorks_Shared::Trip^> trips, Platform::String^disambiguationMessage, Platform::String^secondDisambiguationMessage) | sealed | [private]
GetResourceString(Platform::String^resourceName) | sealed | [private]
GetResourceStringAndFormat(Platform::String^resourceName, Platform::String^param) | sealed | [private]
LaunchAppInForeground() | sealed | [private]
OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^sender, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason) | sealed | [private]
OnVoiceCommandCompleted(Windows::ApplicationModel::VoiceCommands::VoiceCommandServiceConnection^sender, Windows::ApplicationModel::VoiceCommands::VoiceCommandCompletedEventArgs^args) | sealed | [private]
resourceMap | sealed | [private]
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance) | sealed | [virtual]
SendCompletionMessageForCancellation(Platform::String^destination) | sealed | [private]
SendCompletionMessageForDestination(Platform::String^destination) | sealed | [private]
serviceDeferral | sealed | [private]
ShowProgressScreen(Platform::String^progressMessage) | sealed | [private]
taskCancelledToken | sealed | [private]
voiceServiceConnection | sealed | [private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Altimeter/cpp/SampleConfiguration.h Source File

  • Altimeter
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Altimeter";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cs/Scenario4.xaml.cs Source File

  • MapControl
  • cs

Scenario4.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.IO;
00016 using System.Linq;
00017 using System.Runtime.InteropServices.WindowsRuntime;
00018 using Windows.Devices.Geolocation;
00019 using Windows.Foundation;
00020 using Windows.Foundation.Collections;
00021 using Windows.UI.Xaml;
00022 using Windows.UI.Xaml.Controls;
00023 using Windows.UI.Xaml.Controls.Maps;
00024 using Windows.UI.Xaml.Data;
00025 using Windows.UI.Xaml.Input;
00026 using Windows.UI.Xaml.Media;
00027
00028 namespace SDKTemplate
00029 {
00030     public sealed partial class Scenario4 : Page
00031     {
00032         private MainPage rootPage = MainPage.Current;
00033
00034         public Scenario4()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         private async void showSpaceNeedleButton_Click(object sender, RoutedEventArgs e)
00040         {
00041             if (myMap.Is3DSupported)
00042             {
00043                 myMap.Style = MapStyle.Aerial3DWithRoads;
00044
00045                 Geopoint spaceNeedlePoint = new Geopoint(new BasicGeoposition() { Latitude = 47.6204, Longitude = -122.3491 });
00046
00047                 MapScene spaceNeedleScene = MapScene.CreateFromLocationAndRadius(spaceNeedlePoint,
00048                                                                                     400, /* show this many meters around */
00049                                                                                     135, /* looking at it to the south east*/
00050                                                                                     60 /* degrees pitch */);
00051
00052                 await myMap.TrySetSceneAsync(spaceNeedleScene);
00053             }
00054             else
00055             {
00056                 string status = "3D views are not supported on this device.";
00057                 rootPage.NotifyUser(status, NotifyType.ErrorMessage);
00058             }
00059
00060
00061         }
00062
00063         private void myMap_Loaded(object sender, RoutedEventArgs e)
00064         {
00065             myMap.Center = MainPage.SeattleGeopoint;
00066             myMap.ZoomLevel = 12;
00067         }
00068     }
00069 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackButton/cs/SecondaryPage.xaml.cs Source File

  • BackButton
  • cs

SecondaryPage.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.IO;
00004 using System.Linq;
00005 using System.Runtime.InteropServices.WindowsRuntime;
00006 using Windows.Foundation;
00007 using Windows.Foundation.Collections;
00008 using Windows.UI.Core;
00009 using Windows.UI.Xaml;
00010 using Windows.UI.Xaml.Controls;
00011 using Windows.UI.Xaml.Controls.Primitives;
00012 using Windows.UI.Xaml.Data;
00013 using Windows.UI.Xaml.Input;
00014 using Windows.UI.Xaml.Media;
00015 using Windows.UI.Xaml.Navigation;
00016
00017 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class SecondaryPage : Page
00025     {
00026         public SecondaryPage()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         protected override void OnNavigatedTo(NavigationEventArgs e)
00032         {
00033             bool optedIn = false;
00034
00035             if ((bool)e.Parameter)
00036             {
00037                 optedIn = true;
00038
00039             }
00040
00041             Frame rootFrame = Window.Current.Content as Frame;
00042
00043             if (rootFrame.CanGoBack && optedIn)
00044             {
00045                 // If we have pages in our in-app backstack and have opted in to showing back, do so
00046                 SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
00047             }
00048             else
00049             {
00050                 // Remove the UI from the title bar if there are no pages in our in-app back stack
00051                 SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
00052             }
00053         }
00054     }
00055 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DAdvancedColorImages/cpp/D2DAdvancedColorImages/BasicReaderWriter.cpp Source File

  • D2DAdvancedColorImages
  • cpp
  • D2DAdvancedColorImages

BasicReaderWriter.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "BasicReaderWriter.h"
00014
00015 using namespace Microsoft::WRL;
00016 using namespace Windows::Storage;
00017 using namespace Windows::Storage::FileProperties;
00018 using namespace Windows::Storage::Streams;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::ApplicationModel;
00021 using namespace concurrency;
00022
00023 BasicReaderWriter::BasicReaderWriter()
00024 {
00025     m_location = Package::Current->InstalledLocation;
00026 }
00027
00028 BasicReaderWriter::BasicReaderWriter(
00029     _In_ Windows::Storage::StorageFolder^ folder
00030     )
00031 {
00032     m_location = folder;
00033     Platform::String^ path = m_location->Path;
00034     if (path->Length() == 0)
00035     {
00036         // Applications are not permitted to access certain
00037         // folders, such as the Documents folder, using this
00038         // code path.  In such cases, the Path property for
00039         // the folder will be an empty string.
00040         throw ref new Platform::FailureException();
00041     }
00042 }
00043
00044 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00045     _In_ Platform::String^ filename
00046     )
00047 {
00048     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00049     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00050     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00051     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00052     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00053     extendedParams.lpSecurityAttributes = nullptr;
00054     extendedParams.hTemplateFile = nullptr;
00055
00056     Wrappers::FileHandle file(
00057         CreateFile2(
00058             filename->Data(),
00059             GENERIC_READ,
00060             FILE_SHARE_READ,
00061             OPEN_EXISTING,
00062             &extendedParams
00063             )
00064         );
00065     if (file.Get() == INVALID_HANDLE_VALUE)
00066     {
00067         throw ref new Platform::FailureException();
00068     }
00069
00070     FILE_STANDARD_INFO fileInfo = {0};
00071     if (!GetFileInformationByHandleEx(
00072         file.Get(),
00073         FileStandardInfo,
00074         &fileInfo,
00075         sizeof(fileInfo)
00076         ))
00077     {
00078         throw ref new Platform::FailureException();
00079     }
00080
00081     if (fileInfo.EndOfFile.HighPart != 0)
00082     {
00083         throw ref new Platform::OutOfMemoryException();
00084     }
00085
00086     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00087
00088     if (!ReadFile(
00089         file.Get(),
00090         fileData->Data,
00091         fileData->Length,
00092         nullptr,
00093         nullptr
00094         ))
00095     {
00096         throw ref new Platform::FailureException();
00097     }
00098
00099     return fileData;
00100 }
00101
00102 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00103     _In_ Platform::String^ filename
00104     )
00105 {
00106     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00107     {
00108         return FileIO::ReadBufferAsync(file);
00109     }).then([=](IBuffer^ buffer)
00110     {
00111         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00112         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00113         return fileData;
00114     });
00115 }
00116
00117 uint32 BasicReaderWriter::WriteData(
00118     _In_ Platform::String^ filename,
00119     _In_ const Platform::Array<byte>^ fileData
00120     )
00121 {
00122     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00123     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00124     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00125     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00126     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00127     extendedParams.lpSecurityAttributes = nullptr;
00128     extendedParams.hTemplateFile = nullptr;
00129
00130     Wrappers::FileHandle file(
00131         CreateFile2(
00132             filename->Data(),
00133             GENERIC_WRITE,
00134             0,
00135             CREATE_ALWAYS,
00136             &extendedParams
00137             )
00138         );
00139     if (file.Get() == INVALID_HANDLE_VALUE)
00140     {
00141         throw ref new Platform::FailureException();
00142     }
00143
00144     DWORD numBytesWritten;
00145     if (
00146         !WriteFile(
00147             file.Get(),
00148             fileData->Data,
00149             fileData->Length,
00150             &numBytesWritten,
00151             nullptr
00152             ) ||
00153         numBytesWritten != fileData->Length
00154         )
00155     {
00156         throw ref new Platform::FailureException();
00157     }
00158
00159     return numBytesWritten;
00160 }
00161
00162 task<void> BasicReaderWriter::WriteDataAsync(
00163     _In_ Platform::String^ filename,
00164     _In_ const Platform::Array<byte>^ fileData
00165     )
00166 {
00167     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00168     {
00169         FileIO::WriteBytesAsync(file, fileData);
00170     });
00171 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cpp/Scenario2_Launch.xaml.cpp Source File

  • ResizeAppView
  • cpp

Scenario2_Launch.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Launch.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::ViewManagement;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023
00024 Scenario2_Launch::Scenario2_Launch()
00025 {
00026     InitializeComponent();
00027     LaunchAtSize->IsChecked = ApplicationView::PreferredLaunchWindowingMode != ApplicationViewWindowingMode::Auto;
00028 }
00029
00030 // If you set the PreferredLaunchViewSize and PreferredLaunchWindowingMode
00031 // before calling Window::Current->Activate(), then it will take effect
00032 // on the current launch. Otherwise, it takes effect at the next launch.
00033 void Scenario2_Launch::LaunchAtSize_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00034 {
00035     if (LaunchAtSize->IsChecked->Value)
00036     {
00037         // For best results, set the PreferredLaunchViewSize before setting
00038         // the PreferredLaunchWindowingMode.
00039         ApplicationView::PreferredLaunchViewSize = Size(600, 500);
00040         ApplicationView::PreferredLaunchWindowingMode = ApplicationViewWindowingMode::PreferredLaunchViewSize;
00041     }
00042     else
00043     {
00044         ApplicationView::PreferredLaunchWindowingMode = ApplicationViewWindowingMode::Auto;
00045     }
00046 }
Generated on Fri Nov 15 2024 22:19:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLInProcessWinRTComponent/cpp/cpp/Scenario3_CustomException.xaml.h Source File

  • WRLInProcessWinRTComponent
  • cpp
  • cpp

Scenario3_CustomException.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008 #include "Scenario3_CustomException.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     namespace WRLInProcessWinRTComponent
00013     {
00014         public ref class CustomException sealed
00015         {
00016         public:
00017             CustomException();
00018
00019         private:
00020             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021         };
00022     }
00023 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundSensors/cpp/BackgroundTask/pch.h Source File

  • BackgroundSensors
  • cpp
  • BackgroundTask

pch.h

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include <collection.h>
00006 #include <ppltasks.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cpp/SampleConfiguration.cpp Source File

  • Playlists
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace concurrency;
00008 using namespace Platform;
00009 using namespace SDKTemplate;
00010 using namespace Windows::Media::Playlists;
00011 using namespace Windows::Storage;
00012 using namespace Windows::Storage::Pickers;
00013
00014 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00015 {
00016     { "Create a playlist", "SDKTemplate.Scenario1_Create" },
00017     { "Display a playlist", "SDKTemplate.Scenario2_Display" },
00018     { "Add items to a playlist", "SDKTemplate.Scenario3_Add" },
00019     { "Remove an item from a playlist", "SDKTemplate.Scenario4_Remove" },
00020     { "Clear a playlist", "SDKTemplate.Scenario5_Clear" },
00021 };
00022
00023 Array<String^>^ MainPage::audioExtensionsInner = ref new Array<String^>
00024 {
00025     L".wma",  L".mp3",  L".mp2",  L".aac", L".adt", L".adts", L".m4a"
00026 };
00027
00028 Array<String^>^ MainPage::playlistExtensionsInner = ref new Array<String^>
00029 {
00030     L".m3u", L".wpl", L".zpl"
00031 };
00032
00033 FileOpenPicker^ MainPage::CreateFilePicker(Array<String^>^ extensions)
00034 {
00035     FileOpenPicker^ picker = ref new FileOpenPicker();
00036     picker->SuggestedStartLocation = PickerLocationId::MusicLibrary;
00037
00038     // Load the picker with the desired extensions.
00039     for (unsigned int i = 0; i < extensions->Length; i++)
00040     {
00041         picker->FileTypeFilter->Append(extensions[i]);
00042     }
00043
00044     return picker;
00045 }
00046
00047 // Returns the playlist the user picked.
00048 // If the user did not pick a playlist, or the playlist could not be loaded,
00049 // then returns nullptr and reports the error to the user.
00050 task<Playlist^> MainPage::PickPlaylistAsync()
00051 {
00052     // Pick a file, then load it as a playlist.
00053     FileOpenPicker^ picker = MainPage::CreateFilePicker(MainPage::playlistExtensions);
00054     return create_task(picker->PickSingleFileAsync()).then([this](StorageFile^ file)
00055     {
00056         if (file != nullptr)
00057         {
00058             return create_task(Playlist::LoadAsync(file)).then([this](task<Playlist^> playlistTask)
00059             {
00060                 try
00061                 {
00062                     return playlistTask.get();
00063                 }
00064                 catch (Exception^ ex)
00065                 {
00066                     NotifyUser(ex->Message, NotifyType::ErrorMessage);
00067                     return (Playlist^)nullptr;
00068                 }
00069             });
00070         }
00071         else
00072         {
00073             NotifyUser("No playlist picked.", NotifyType::ErrorMessage);
00074             return create_task([]() -> Playlist^ { return nullptr; });
00075         }
00076     });
00077 }
00078
00079 // Returns true if the playlist was saved successfully.
00080 // On failure, returns false and reports the error to the user.
00081 task<bool> MainPage::TrySavePlaylistAsync(Playlist^ playlist)
00082 {
00083     return create_task(playlist->SaveAsync()).then([this](task<void> saveTask)
00084     {
00085         try
00086         {
00087             saveTask.get();
00088             return true;
00089         }
00090         catch (Exception^ ex)
00091         {
00092             NotifyUser(ex->Message, NotifyType::ErrorMessage);
00093             return false;
00094         }
00095     });
00096 }
Generated on Fri Nov 15 2024 22:17:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraVideoStabilization/cpp/MainPage.xaml.cpp Source File

  • CameraVideoStabilization
  • cpp

MainPage.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include <sstream>
00015
00016 using namespace CameraVideoStabilization;
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Devices::Enumeration;
00020 using namespace Windows::Devices::Sensors;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::Graphics::Imaging;
00025 using namespace Windows::Media;
00026 using namespace Windows::Media::Core;
00027 using namespace Windows::Phone::UI::Input;
00028 using namespace Windows::Storage;
00029 using namespace Windows::UI::Xaml;
00030 using namespace Windows::UI::Xaml::Controls;
00031 using namespace Windows::UI::Xaml::Controls::Primitives;
00032 using namespace Windows::UI::Xaml::Data;
00033 using namespace Windows::UI::Xaml::Input;
00034 using namespace Windows::UI::Xaml::Media;
00035 using namespace Windows::UI::Xaml::Navigation;
00036
00037 MainPage::MainPage()
00038     : _mediaCapture(nullptr)
00039     , _isInitialized(false)
00040     , _isPreviewing(false)
00041     , _isRecording(false)
00042     , _encodingProfile(nullptr)
00043     , _externalCamera(false)
00044     , _mirroringPreview(false)
00045     , _deviceOrientation(SimpleOrientation::NotRotated)
00046     , _displayOrientation(DisplayOrientations::Portrait)
00047     , _displayRequest(ref new Windows::System::Display::DisplayRequest())
00048     , RotationKey({ 0xC380465D, 0x2271, 0x428C,{ 0x9B, 0x83, 0xEC, 0xEA, 0x3B, 0x4A, 0x85, 0xC1 } })
00049     , _videoStabilizationEffect(nullptr)
00050     , _inputPropertiesBackup(nullptr)
00051     , _outputPropertiesBackup(nullptr)
00052     , _captureFolder(nullptr)
00053 {
00054     InitializeComponent();
00055
00056     _orientationSensor = SimpleOrientationSensor::GetDefault();
00057     _displayInformation = DisplayInformation::GetForCurrentView();
00058     _systemMediaControls = SystemMediaTransportControls::GetForCurrentView();
00059
00060     // Do not cache the state of the UI when suspending/navigating
00061     Page::NavigationCacheMode = Navigation::NavigationCacheMode::Disabled;
00062
00063     // Useful to know when to initialize/clean up the camera
00064     _applicationSuspendingEventToken =
00065         Application::Current->Suspending += ref new SuspendingEventHandler(this, &MainPage::Application_Suspending);
00066     _applicationResumingEventToken =
00067         Application::Current->Resuming += ref new EventHandler<Object^>(this, &MainPage::Application_Resuming);
00068 }
00069
00070 MainPage::~MainPage()
00071 {
00072     Application::Current->Suspending -= _applicationSuspendingEventToken;
00073     Application::Current->Resuming -= _applicationResumingEventToken;
00074 }
00075
00076 /// <summary>
00077 /// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI
00078 /// </summary>
00079 /// <returns></returns>
00080 task<void> MainPage::InitializeCameraAsync()
00081 {
00082     WriteLine("InitializeCameraAsync");
00083
00084     // Get available devices for capturing pictures
00085     return FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel::Back)
00086         .then([this](DeviceInformation^ camera)
00087     {
00088         if (camera == nullptr)
00089         {
00090             WriteLine("No camera device found!");
00091             return;
00092         }
00093         // Figure out where the camera is located
00094         if (camera->EnclosureLocation == nullptr || camera->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Unknown)
00095         {
00096             // No information on the location of the camera, assume it's an external camera, not integrated on the device
00097             _externalCamera = true;
00098         }
00099         else
00100         {
00101             // Camera is fixed on the device
00102             _externalCamera = false;
00103
00104             // Only mirror the preview if the camera is on the front panel
00105             _mirroringPreview = (camera->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Front);
00106         }
00107
00108         _mediaCapture = ref new Capture::MediaCapture();
00109
00110         // Register for a notification when video recording has reached the maximum time and when something goes wrong
00111         _recordLimitationExceededEventToken =
00112             _mediaCapture->RecordLimitationExceeded += ref new Capture::RecordLimitationExceededEventHandler(this, &MainPage::MediaCapture_RecordLimitationExceeded);
00113         _mediaCaptureFailedEventToken =
00114             _mediaCapture->Failed += ref new Capture::MediaCaptureFailedEventHandler(this, &MainPage::MediaCapture_Failed);
00115
00116         auto settings = ref new Capture::MediaCaptureInitializationSettings();
00117         settings->VideoDeviceId = camera->Id;
00118         settings->StreamingCaptureMode = Capture::StreamingCaptureMode::AudioAndVideo;
00119
00120         // Initialize media capture and start the preview
00121         create_task(_mediaCapture->InitializeAsync(settings))
00122             .then([this]()
00123         {
00124             // Set up the encoding profile for video recording
00125             _encodingProfile = MediaProperties::MediaEncodingProfile::CreateMp4(MediaProperties::VideoEncodingQuality::Auto);
00126             _isInitialized = true;
00127
00128             return StartPreviewAsync()
00129                 .then([this]()
00130             {
00131                 UpdateCaptureControls();
00132             });
00133         }).then([this](task<void> previousTask)
00134         {
00135             try
00136             {
00137                 previousTask.get();
00138             }
00139             catch (AccessDeniedException^)
00140             {
00141                 WriteLine("The app was denied access to the camera");
00142             }
00143         });
00144     });
00145 }
00146
00147 /// <summary>
00148 /// Cleans up the camera resources (after stopping any video recording and/or preview if necessary) and unregisters from MediaCapture events
00149 /// </summary>
00150 /// <returns></returns>
00151 Concurrency::task<void> MainPage::CleanupCameraAsync()
00152 {
00153     WriteLine("CleanupCameraAsync");
00154
00155     std::vector<task<void>> taskList;
00156
00157     if (_isInitialized)
00158     {
00159         // If a recording is in progress during cleanup, stop it to save the recording
00160         if (_isRecording)
00161         {
00162             auto stopRecordTask = create_task(StopRecordingAsync());
00163             taskList.push_back(stopRecordTask);
00164         }
00165
00166         // Clear the effect if one exists
00167         if (_videoStabilizationEffect != nullptr)
00168         {
00169             auto cleanStabilizationTask = CleanUpVideoStabilizationEffectAsync();
00170             taskList.push_back(cleanStabilizationTask);
00171         }
00172
00173         if (_isPreviewing)
00174         {
00175             auto stopPreviewTask = create_task(StopPreviewAsync());
00176             taskList.push_back(stopPreviewTask);
00177         }
00178
00179         _isInitialized = false;
00180     }
00181
00182     // When all our tasks complete, clean up MediaCapture
00183     return when_all(taskList.begin(), taskList.end())
00184         .then([this]()
00185     {
00186         if (_mediaCapture != nullptr)
00187         {
00188             _mediaCapture->RecordLimitationExceeded -= _recordLimitationExceededEventToken;
00189             _mediaCapture->Failed -= _mediaCaptureFailedEventToken;
00190             _mediaCapture = nullptr;
00191         }
00192     });
00193 }
00194
00195 /// <summary>
00196 /// Starts the preview and adjusts it for for rotation and mirroring after making a request to keep the screen on
00197 /// </summary>
00198 /// <returns></returns>
00199 task<void> MainPage::StartPreviewAsync()
00200 {
00201     // Prevent the device from sleeping while the preview is running
00202     _displayRequest->RequestActive();
00203
00204     // Set the preview source in the UI and mirror it if necessary
00205     PreviewControl->Source = _mediaCapture.Get();
00206     PreviewControl->FlowDirection = _mirroringPreview ? Windows::UI::Xaml::FlowDirection::RightToLeft : Windows::UI::Xaml::FlowDirection::LeftToRight;
00207
00208     // Start the preview
00209     return create_task(_mediaCapture->StartPreviewAsync())
00210         .then([this](task<void> previousTask)
00211     {
00212         _isPreviewing = true;
00213
00214         // Only need to update the orientation if the camera is mounted on the device
00215         if (!_externalCamera)
00216         {
00217             return SetPreviewRotationAsync();
00218         }
00219
00220         // Not external, just return the previous task
00221         return previousTask;
00222     });
00223 }
00224
00225 /// <summary>
00226 /// Gets the current orientation of the UI in relation to the device (when AutoRotationPreferences cannot be honored) and applies a corrective rotation to the preview
00227 /// </summary>
00228 /// <returns></returns>
00229 task<void> MainPage::SetPreviewRotationAsync()
00230 {
00231     // Calculate which way and how far to rotate the preview
00232     int rotationDegrees = ConvertDisplayOrientationToDegrees(_displayOrientation);
00233
00234     // The rotation direction needs to be inverted if the preview is being mirrored
00235     if (_mirroringPreview)
00236     {
00237         rotationDegrees = (360 - rotationDegrees) % 360;
00238     }
00239
00240     // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames
00241     auto props = _mediaCapture->VideoDeviceController->GetMediaStreamProperties(Capture::MediaStreamType::VideoPreview);
00242     props->Properties->Insert(RotationKey, rotationDegrees);
00243     return create_task(_mediaCapture->SetEncodingPropertiesAsync(Capture::MediaStreamType::VideoPreview, props, nullptr));
00244 }
00245
00246 /// <summary>
00247 /// Stops the preview and deactivates a display request, to allow the screen to go into power saving modes
00248 /// </summary>
00249 /// <returns></returns>
00250 task<void> MainPage::StopPreviewAsync()
00251 {
00252     _isPreviewing = false;
00253
00254     return create_task(_mediaCapture->StopPreviewAsync())
00255         .then([this]()
00256     {
00257         // Use the dispatcher because this method is sometimes called from non-UI threads
00258         return Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00259         {
00260             // Cleanup the UI
00261             PreviewControl->Source = nullptr;
00262             // Allow the device screen to sleep now that the preview is stopped
00263             _displayRequest->RequestRelease();
00264         }));
00265     });
00266 }
00267
00268 /// <summary>
00269 /// Adds video stabilization to the video record stream, registers for its event, enables it, and gets the effect instance
00270 /// </summary>
00271 /// <returns></returns>
00272 task<void> MainPage::CreateVideoStabilizationEffectAsync()
00273 {
00274     // No work to be done if there already is an effect
00275     if (_videoStabilizationEffect != nullptr)
00276     {
00277         return EmptyTask();
00278     }
00279
00280     // Create the definition, which will contain some initialization settings
00281     auto definition = ref new VideoStabilizationEffectDefinition();
00282
00283     // Add the effect to the video record stream
00284     return create_task(_mediaCapture->AddVideoEffectAsync(definition, Capture::MediaStreamType::VideoRecord))
00285         .then([this](IMediaExtension^ mediaExtension)
00286     {
00287         WriteLine("VS effect added to pipeline");
00288
00289         _videoStabilizationEffect = static_cast<VideoStabilizationEffect^>(mediaExtension);
00290
00291         // Subscribe to notifications for changes in the enabled state for the effect
00292         _videoStabilizationEnabledToken =
00293             _videoStabilizationEffect->EnabledChanged += ref new TypedEventHandler<VideoStabilizationEffect^, VideoStabilizationEffectEnabledChangedEventArgs^>(this, &MainPage::VideoStabilizationEffect_EnabledChanged);
00294
00295         // Enable the effect
00296         _videoStabilizationEffect->Enabled = true;
00297
00298 #if (USE_VS_RECOMMENDATION)
00299         // Configure the pipeline to use the optimal settings for VS
00300         return SetUpVideoStabilizationRecommendationAsync();
00301
00302         // At this point, one of two things has happened:
00303         //
00304         // a) If a more suitable capture resolution was available:
00305         //    1. Such resolution will have been set up for video capture ("input")
00306         //    2. The MediaEncodingProfile ("output") will have been changed to specify dimensions reflecting the amount of cropping
00307         //       done on said capture resolution (possibly even none if the new resolution offers enough padding)
00308         // b) If no better suited capture resolution was available:
00309         //    1. The video capture resolution will not have changed
00310         //    2. The MediaEncodingProfile will have been changed to specify smaller dimensions than the capture resolution
00311         //       so that the video isn't scaled back up to the capture resolution after cropping, which could cause a loss in quality
00312 #else
00313         WriteLine("Not setting up VS recommendation");
00314         return EmptyTask();
00315         // Not setting up VS recommendation means that the video will be captured at the desired resolution,
00316         // then cropped by the VS effect as part of the stabilization process, and then scaled back up to the
00317         // original capture resolution
00318 #endif
00319     });
00320 }
00321
00322 /// <summary>
00323 /// Configures the pipeline to use the optimal resolutions for VS based on the settings currently in use
00324 /// </summary>
00325 /// <returns></returns>
00326 task<void> MainPage::SetUpVideoStabilizationRecommendationAsync()
00327 {
00328     WriteLine("Setting up VS recommendation...");
00329
00330     // Get the recommendation from the effect based on our current input and output configuration
00331     auto recommendation = _videoStabilizationEffect->GetRecommendedStreamConfiguration(_mediaCapture->VideoDeviceController, _encodingProfile->Video);
00332
00333     // Handle the recommendations for the output from the effect
00334     if (recommendation->OutputProperties != nullptr)
00335     {
00336         // Back up the current output properties from before VS was activated
00337         _outputPropertiesBackup = _encodingProfile->Video;
00338
00339         // Apply the recommended encoding profile for the output, which will result in a video with the same dimensions as configured
00340         // before VideoStabilization was added if an appropriate padded capture resolution was available. Otherwise, it will be slightly
00341         // smaller (due to cropping). This prevents upscaling back to the original size, which can result in a loss of quality
00342         _encodingProfile->Video = recommendation->OutputProperties;
00343         WriteLine("VS recommendation for the MediaEncodingProfile (output) has been applied");
00344     }
00345
00346     // Handle the recommendation for the input into the effect, which can contain a larger resolution than currently configured, so cropping is minimized
00347     if (recommendation->InputProperties != nullptr)
00348     {
00349         // Back up the current input properties from before VS was activated
00350         _inputPropertiesBackup = static_cast<MediaProperties::VideoEncodingProperties^>(_mediaCapture->VideoDeviceController->GetMediaStreamProperties(Capture::MediaStreamType::VideoRecord));
00351
00352         // Set the recommendation from the effect (a resolution higher than the current one to allow for cropping) on the input
00353         return create_task(_mediaCapture->VideoDeviceController->SetMediaStreamPropertiesAsync(Capture::MediaStreamType::VideoRecord, recommendation->InputProperties))
00354             .then([this]()
00355         {
00356             WriteLine("VS recommendation for the MediaStreamProperties (input) has been applied");
00357         });
00358     }
00359     else
00360     {
00361         return EmptyTask();
00362     }
00363 }
00364
00365 /// <summary>
00366 ///  Disables and removes the video stabilization effect, and unregisters the event handler for the EnabledChanged event of the effect
00367 /// </summary>
00368 /// <returns></returns>
00369 task<void> MainPage::CleanUpVideoStabilizationEffectAsync()
00370 {
00371     // No work to be done if there is no effect
00372     if (_videoStabilizationEffect == nullptr)
00373     {
00374         return EmptyTask();
00375     }
00376
00377     // Disable the effect
00378     _videoStabilizationEffect->Enabled = false;
00379
00380     _videoStabilizationEffect->EnabledChanged -= _videoStabilizationEnabledToken;
00381
00382     // Remove the effect (see ClearEffectsAsync method to remove all effects from a stream)
00383     return create_task(_mediaCapture->RemoveEffectAsync(_videoStabilizationEffect))
00384         .then([this]()
00385     {
00386         WriteLine("VS effect removed from pipeline");
00387
00388         // If backed up settings (stream properties and encoding profile) exist, restore them and clear the backups
00389         if (_outputPropertiesBackup != nullptr)
00390         {
00391             _encodingProfile->Video = _outputPropertiesBackup;
00392             _outputPropertiesBackup = nullptr;
00393         }
00394
00395         task<void> taskToExecute;
00396         if (_inputPropertiesBackup != nullptr)
00397         {
00398             taskToExecute = create_task(_mediaCapture->VideoDeviceController->SetMediaStreamPropertiesAsync(Capture::MediaStreamType::VideoRecord, _inputPropertiesBackup));
00399             _inputPropertiesBackup = nullptr;
00400         }
00401         else
00402         {
00403             taskToExecute = EmptyTask();
00404         }
00405
00406         return taskToExecute;
00407     }).then([this]()
00408     {
00409         // Clear the member variable that held the effect instance
00410         _videoStabilizationEffect = nullptr;
00411     });
00412 }
00413
00414 /// <summary>
00415 /// Records an MP4 video to a StorageFile and adds rotation metadata to it
00416 /// </summary>
00417 /// <returns></returns>
00418 task<void> MainPage::StartRecordingAsync()
00419 {
00420     // Create storage file for the capture
00421     return create_task(_captureFolder->CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption::GenerateUniqueName))
00422         .then([this](StorageFile^ file)
00423     {
00424         // Calculate rotation angle, taking mirroring into account if necessary
00425         auto rotationAngle = 360 - ConvertDeviceOrientationToDegrees(GetCameraOrientation());
00426
00427         // Add it to the encoding profile, or edit the value if the GUID was already a part of the properties
00428         _encodingProfile->Video->Properties->Insert(RotationKey, rotationAngle);
00429
00430         return create_task(_mediaCapture->StartRecordToStorageFileAsync(_encodingProfile, file))
00431             .then([this, file]()
00432         {
00433             _isRecording = true;
00434             WriteLine("Started recording to: " + file->Path);
00435         });
00436     }).then([this](task<void> previousTask)
00437     {
00438         try
00439         {
00440             previousTask.get();
00441         }
00442         catch (Exception^ ex)
00443         {
00444             // File I/O errors are reported as exceptions
00445             WriteException(ex);
00446         }
00447     });
00448 }
00449
00450 /// <summary>
00451 /// Stops recording a video
00452 /// </summary>
00453 /// <returns></returns>
00454 task<void> MainPage::StopRecordingAsync()
00455 {
00456     _isRecording = false;
00457
00458     WriteLine("Stopping recording...");
00459     return create_task(_mediaCapture->StopRecordAsync())
00460         .then([this]()
00461     {
00462         WriteLine("Stopped recording!");
00463
00464         // If VS disabled itself during recording, clean up the effect
00465         if (_videoStabilizationEffect != nullptr && !_videoStabilizationEffect->Enabled)
00466         {
00467             // Cleaning up the effect here is an implementation choice in this sample, so that, at the end of the recording, it's clearer
00468             // to the user that the effect turned itself off. Alternatively, one could try to re-enable the effect (e.g. if the reason
00469             // it disabled itself was RunningSlowly, there's a chance it will work next time), and/or prompt the user to choose a lower capture
00470             // resolution / framerate instead.
00471             return CleanUpVideoStabilizationEffectAsync();
00472         }
00473         else
00474         {
00475             return EmptyTask();
00476         }
00477     });
00478 }
00479
00480 /// <summary>
00481 /// Attempts to find and return a device mounted on the panel specified, and on failure to find one it will return the first device listed
00482 /// </summary>
00483 /// <param name="panel">The desired panel on which the returned device should be mounted, if available</param>
00484 /// <returns></returns>
00485 task<DeviceInformation^> MainPage::FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel panel)
00486 {
00487     // Get available devices for capturing pictures
00488     auto allVideoDevices = DeviceInformation::FindAllAsync(DeviceClass::VideoCapture);
00489
00490     auto deviceEnumTask = create_task(allVideoDevices);
00491     return deviceEnumTask.then([panel](DeviceInformationCollection^ devices)
00492     {
00493         for (auto cameraDeviceInfo : devices)
00494         {
00495             if (cameraDeviceInfo->EnclosureLocation != nullptr && cameraDeviceInfo->EnclosureLocation->Panel == panel)
00496             {
00497                 return cameraDeviceInfo;
00498             }
00499         }
00500
00501         // Nothing matched, just return the first
00502         if (devices->Size > 0)
00503         {
00504             return devices->GetAt(0);
00505         }
00506
00507         // We didn't find any devices, so return a null instance
00508         DeviceInformation^ camera = nullptr;
00509         return camera;
00510     });
00511 }
00512
00513 /// <summary>
00514 /// This method will update the icons, enable/disable and show/hide the photo/video buttons depending on the current state of the app and the capabilities of the device
00515 /// </summary>
00516 void MainPage::UpdateCaptureControls()
00517 {
00518     // The button should only be enabled if the preview started sucessfully
00519     VideoButton->IsEnabled = _isPreviewing;
00520
00521     // Allow toggling VS only while not recording or when the effect exists but it has been disabled
00522     VsToggleButton->IsEnabled = (_isPreviewing && !_isRecording) ||
00523         (_videoStabilizationEffect != nullptr && !_videoStabilizationEffect->Enabled);
00524
00525     // Update recording button to show "Stop" icon instead of red "Record" icon
00526     StartRecordingIcon->Visibility = _isRecording ? Windows::UI::Xaml::Visibility::Collapsed : Windows::UI::Xaml::Visibility::Visible;
00527     StopRecordingIcon->Visibility = _isRecording ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00528
00529     // Show "VS On" icon when effect exists and is enabled, otherwise show "VS Off icon"
00530     if (_videoStabilizationEffect != nullptr && _videoStabilizationEffect->Enabled)
00531     {
00532         VsOnIcon->Visibility = Windows::UI::Xaml::Visibility::Visible;
00533         VsOffIcon->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00534     }
00535     else
00536     {
00537         VsOnIcon->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00538         VsOffIcon->Visibility = Windows::UI::Xaml::Visibility::Visible;
00539     }
00540 }
00541
00542 /// <summary>
00543 /// Attempts to lock the page orientation, hide the StatusBar (on Phone) and registers event handlers for orientation sensors
00544 /// </summary>
00545 /// <returns></returns>
00546 task<void> MainPage::SetupUiAsync()
00547 {
00548     // Attempt to lock page to landscape orientation to prevent the CaptureElement from rotating, as this gives a better experience
00549     DisplayInformation::AutoRotationPreferences = DisplayOrientations::Landscape;
00550
00551     RegisterEventHandlers();
00552
00553      // Populate orientation variables with the current state
00554     _displayOrientation = _displayInformation->CurrentOrientation;
00555     if (_orientationSensor != nullptr)
00556     {
00557         _deviceOrientation = _orientationSensor->GetCurrentOrientation();
00558     }
00559
00560     create_task(StorageLibrary::GetLibraryAsync(KnownLibraryId::Pictures))
00561         .then([this](StorageLibrary^ picturesLibrary)
00562     {
00563         _captureFolder = picturesLibrary->SaveFolder;
00564         if (_captureFolder == nullptr)
00565         {
00566             // In this case fall back to the local app storage since the Pictures Library is not available
00567             _captureFolder = ApplicationData::Current->LocalFolder;
00568         }
00569     });
00570
00571     // Hide the status bar
00572     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00573     {
00574         return create_task(Windows::UI::ViewManagement::StatusBar::GetForCurrentView()->HideAsync());
00575     }
00576     else
00577     {
00578         return EmptyTask();
00579     }
00580 }
00581
00582 /// <summary>
00583 /// Unregisters event handlers for orientation sensors, allows the StatusBar (on Phone) to show, and removes the page orientation lock
00584 /// </summary>
00585 /// <returns></returns>
00586 task<void> MainPage::CleanupUiAsync()
00587 {
00588     UnregisterEventHandlers();
00589
00590     // Revert orientation preferences
00591     DisplayInformation::AutoRotationPreferences = DisplayOrientations::None;
00592
00593     // Show the status bar
00594     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00595     {
00596         return create_task(Windows::UI::ViewManagement::StatusBar::GetForCurrentView()->ShowAsync());
00597     }
00598     else
00599     {
00600         return EmptyTask();
00601     }
00602 }
00603
00604 /// <summary>
00605 /// Registers event handlers for hardware buttons and orientation sensors, and performs an initial update of the UI rotation
00606 /// </summary>
00607 void MainPage::RegisterEventHandlers()
00608 {
00609     // If there is an orientation sensor present on the device, register for notifications
00610     if (_orientationSensor != nullptr)
00611     {
00612         _orientationChangedEventToken =
00613             _orientationSensor->OrientationChanged += ref new TypedEventHandler<SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^>(this, &MainPage::OrientationSensor_OrientationChanged);
00614
00615         // Update orientation of buttons with the current orientation
00616         UpdateButtonOrientation();
00617     }
00618
00619     _displayInformationEventToken =
00620         _displayInformation->OrientationChanged += ref new TypedEventHandler<DisplayInformation^, Object^>(this, &MainPage::DisplayInformation_OrientationChanged);
00621
00622     _mediaControlPropChangedEventToken =
00623         _systemMediaControls->PropertyChanged += ref new TypedEventHandler<SystemMediaTransportControls^, SystemMediaTransportControlsPropertyChangedEventArgs^>(this, &MainPage::SystemMediaControls_PropertyChanged);
00624 }
00625
00626 /// <summary>
00627 /// Unregisters event handlers for hardware buttons and orientation sensors
00628 /// </summary>
00629 void MainPage::UnregisterEventHandlers()
00630 {
00631     if (_orientationSensor != nullptr)
00632     {
00633         _orientationSensor->OrientationChanged -= _orientationChangedEventToken;
00634     }
00635
00636     _displayInformation->OrientationChanged -= _displayInformationEventToken;
00637     _systemMediaControls->PropertyChanged -= _mediaControlPropChangedEventToken;
00638 }
00639
00640 /// <summary>
00641 /// Writes a given string to the output window
00642 /// </summary>
00643 /// <param name="str">String to be written</param>
00644 void MainPage::WriteLine(String^ str)
00645 {
00646     std::wstringstream wStringstream;
00647     wStringstream << str->Data() << "\n";
00648     OutputDebugString(wStringstream.str().c_str());
00649 }
00650
00651 /// <summary>
00652 /// Writes a given exception message and hresult to the output window
00653 /// </summary>
00654 /// <param name="ex">Exception to be written</param>
00655 void MainPage::WriteException(Exception^ ex)
00656 {
00657     std::wstringstream wStringstream;
00658     wStringstream << "0x" << ex->HResult << ": " << ex->Message->Data();
00659     OutputDebugString(wStringstream.str().c_str());
00660 }
00661
00662 /// <summary>
00663 /// Sometimes we need to conditionally return a task. If certain parameters are not met we cannot
00664 /// return null, but we can return a task that does nothing.
00665 /// </summary>
00666 /// <returns></returns>
00667 task<void> MainPage::EmptyTask()
00668 {
00669     return create_task([] {});
00670 }
00671
00672 /// <summary>
00673 /// Calculates the current camera orientation from the device orientation by taking into account whether the camera is external or facing the user
00674 /// </summary>
00675 /// <returns>The camera orientation in space, with an inverted rotation in the case the camera is mounted on the device and is facing the user</returns>
00676 SimpleOrientation MainPage::GetCameraOrientation()
00677 {
00678     if (_externalCamera)
00679     {
00680         // Cameras that are not attached to the device do not rotate along with it, so apply no rotation
00681         return SimpleOrientation::NotRotated;
00682     }
00683
00684     auto result = _deviceOrientation;
00685
00686     // Account for the fact that, on portrait-first devices, the camera sensor is mounted at a 90 degree offset to the native orientation
00687     if (_displayInformation->NativeOrientation == DisplayOrientations::Portrait)
00688     {
00689         switch (result)
00690         {
00691         case SimpleOrientation::Rotated90DegreesCounterclockwise:
00692             result = SimpleOrientation::NotRotated;
00693             break;
00694         case SimpleOrientation::Rotated180DegreesCounterclockwise:
00695             result = SimpleOrientation::Rotated90DegreesCounterclockwise;
00696             break;
00697         case SimpleOrientation::Rotated270DegreesCounterclockwise:
00698             result = SimpleOrientation::Rotated180DegreesCounterclockwise;
00699             break;
00700         case SimpleOrientation::NotRotated:
00701             result = SimpleOrientation::Rotated270DegreesCounterclockwise;
00702             break;
00703         }
00704     }
00705
00706     // If the preview is being mirrored for a front-facing camera, then the rotation should be inverted
00707     if (_mirroringPreview)
00708     {
00709         // This only affects the 90 and 270 degree cases, because rotating 0 and 180 degrees is the same clockwise and counter-clockwise
00710         switch (_deviceOrientation)
00711         {
00712         case SimpleOrientation::Rotated90DegreesCounterclockwise:
00713             return SimpleOrientation::Rotated270DegreesCounterclockwise;
00714         case SimpleOrientation::Rotated270DegreesCounterclockwise:
00715             return SimpleOrientation::Rotated90DegreesCounterclockwise;
00716         }
00717     }
00718
00719     return result;
00720 }
00721
00722 /// <summary>
00723 /// Converts the given orientation of the device in space to the metadata that can be added to captured photos
00724 /// </summary>
00725 /// <param name="orientation">The orientation of the device in space</param>
00726 /// <returns></returns>
00727 FileProperties::PhotoOrientation MainPage::ConvertOrientationToPhotoOrientation(SimpleOrientation orientation)
00728 {
00729     switch (orientation)
00730     {
00731     case SimpleOrientation::Rotated90DegreesCounterclockwise:
00732         return FileProperties::PhotoOrientation::Rotate90;
00733     case SimpleOrientation::Rotated180DegreesCounterclockwise:
00734         return FileProperties::PhotoOrientation::Rotate180;
00735     case SimpleOrientation::Rotated270DegreesCounterclockwise:
00736         return FileProperties::PhotoOrientation::Rotate270;
00737     case SimpleOrientation::NotRotated:
00738     default:
00739         return FileProperties::PhotoOrientation::Normal;
00740     }
00741 }
00742
00743 /// <summary>
00744 /// Converts the given orientation of the device in space to the corresponding rotation in degrees
00745 /// </summary>
00746 /// <param name="orientation">The orientation of the device in space</param>
00747 /// <returns>An orientation in degrees</returns>
00748 int MainPage::ConvertDeviceOrientationToDegrees(SimpleOrientation orientation)
00749 {
00750     switch (orientation)
00751     {
00752     case SimpleOrientation::Rotated90DegreesCounterclockwise:
00753         return 90;
00754     case SimpleOrientation::Rotated180DegreesCounterclockwise:
00755         return 180;
00756     case SimpleOrientation::Rotated270DegreesCounterclockwise:
00757         return 270;
00758     case SimpleOrientation::NotRotated:
00759     default:
00760         return 0;
00761     }
00762 }
00763
00764 /// <summary>
00765 /// Converts the given orientation of the app on the screen to the corresponding rotation in degrees
00766 /// </summary>
00767 /// <param name="orientation">The orientation of the app on the screen</param>
00768 /// <returns>An orientation in degrees</returns>
00769 int MainPage::ConvertDisplayOrientationToDegrees(DisplayOrientations orientation)
00770 {
00771     switch (orientation)
00772     {
00773     case DisplayOrientations::Portrait:
00774         return 90;
00775     case DisplayOrientations::LandscapeFlipped:
00776         return 180;
00777     case DisplayOrientations::PortraitFlipped:
00778         return 270;
00779     case DisplayOrientations::Landscape:
00780     default:
00781         return 0;
00782     }
00783 }
00784
00785 /// <summary>
00786 /// Uses the current device orientation in space and page orientation on the screen to calculate the rotation
00787 /// transformation to apply to the controls
00788 /// </summary>
00789 void MainPage::UpdateButtonOrientation()
00790 {
00791     int device = ConvertDeviceOrientationToDegrees(_deviceOrientation);
00792     int display = ConvertDisplayOrientationToDegrees(_displayOrientation);
00793
00794     if (_displayInformation->NativeOrientation == DisplayOrientations::Portrait)
00795     {
00796         device -= 90;
00797     }
00798
00799     // Combine both rotations and make sure that 0 <= result < 360
00800     auto angle = (display + device) % 360;
00801
00802     // Rotate the buttons in the UI to match the rotation of the device
00803     auto transform = ref new RotateTransform();
00804     transform->Angle = angle;
00805
00806     // The RenderTransform is safe to use (i.e. it won't cause layout issues) in this case, because these buttons have a 1:1 aspect ratio
00807     VsToggleButton->RenderTransform = transform;
00808     VideoButton->RenderTransform = transform;
00809 }
00810
00811 void MainPage::Application_Suspending(Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e)
00812 {
00813     // Handle global application events only if this page is active
00814     if (Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name)
00815     {
00816         auto deferral = e->SuspendingOperation->GetDeferral();
00817         CleanupUiAsync()
00818             .then([this, deferral]()
00819         {
00820             CleanupCameraAsync();
00821         }).then([this, deferral]()
00822         {
00823             deferral->Complete();
00824         });
00825     }
00826 }
00827
00828 void MainPage::Application_Resuming(Platform::Object^ sender, Platform::Object^ args)
00829 {
00830     // Handle global application events only if this page is active
00831     if (Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name)
00832     {
00833         SetupUiAsync();
00834         InitializeCameraAsync();
00835     }
00836 }
00837
00838 /// <summary>
00839 /// This event will fire when the page is rotated, when the DisplayInformation.AutoRotationPreferences value set in the SetupUiAsync() method cannot be not honored.
00840 /// </summary>
00841 /// <param name="sender">The event source.</param>
00842 /// <param name="args">The event data.</param>
00843 void MainPage::DisplayInformation_OrientationChanged(DisplayInformation^ sender, Object^ args)
00844 {
00845     // This event will fire when the page is rotated, when the DisplayInformation.AutoRotationPreferences
00846     // value set in the SetupUiAsync() method cannot be not honored
00847     _displayOrientation = sender->CurrentOrientation;
00848
00849     if (_isPreviewing)
00850     {
00851         SetPreviewRotationAsync();
00852     }
00853
00854     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00855     {
00856         UpdateButtonOrientation();
00857     }));
00858 }
00859
00860 void MainPage::VsToggleButton_Click(Object^, Windows::UI::Xaml::RoutedEventArgs^)
00861 {
00862     // Note that for the most part, this button is disabled during recording, except when VS is turned off automatically
00863     task<void> taskToExecute;
00864
00865     if (!_isRecording)
00866     {
00867         // While *not* recording, either the effect doesn't exist (and should be created) or it exists and is enabled.
00868         // This sample doesn't allow the user to disable the effect while recording. For the case that the effect disables
00869         // itself while recording, StopRecordingAsync() will clean up the effect after the recording session ends.
00870
00871         if (_videoStabilizationEffect == nullptr)
00872         {
00873             // VS didn't exist, so create and enable the effect
00874             taskToExecute = CreateVideoStabilizationEffectAsync();
00875         }
00876         else if (_videoStabilizationEffect->Enabled)
00877         {
00878             // VS was enabled, so clean it up and restore any capture settings (MediaStreamType and EncodingProfile)
00879             taskToExecute = CleanUpVideoStabilizationEffectAsync();
00880         }
00881     }
00882     else if (!_videoStabilizationEffect->Enabled)
00883     {
00884         // While recording this button is diabled. The situation the user is allowed to tap it while recording, is when
00885         // VS turns itself off (see VideoStabilizationEffect_EnabledChanged), so proceed to re-enable the effect
00886         _videoStabilizationEffect->Enabled = true;
00887         taskToExecute = EmptyTask();
00888     }
00889
00890     taskToExecute.then([this](task<void> previousTask)
00891     {
00892         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00893         {
00894             UpdateCaptureControls();
00895         }));
00896     });
00897 }
00898
00899 void MainPage::VideoButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00900 {
00901     task<void> taskToExecute;
00902     if (!_isRecording)
00903     {
00904         taskToExecute = StartRecordingAsync();
00905     }
00906     else
00907     {
00908         taskToExecute = StopRecordingAsync();
00909     }
00910
00911     taskToExecute.then([this](task<void> previousTask)
00912     {
00913         // After starting or stopping video recording, update the UI to reflect the MediaCapture state
00914         UpdateCaptureControls();
00915     });
00916 }
00917
00918 /// <summary>
00919 /// In the event of the app being minimized this method handles media property change events. If the app receives a mute
00920 /// notification, it is no longer in the foregroud.
00921 /// </summary>
00922 /// <param name="sender"></param>
00923 /// <param name="args"></param>
00924 void MainPage::SystemMediaControls_PropertyChanged(SystemMediaTransportControls^ sender, SystemMediaTransportControlsPropertyChangedEventArgs^ args)
00925 {
00926     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, sender, args]()
00927     {
00928         // Only handle this event if this page is currently being displayed
00929         if (args->Property == SystemMediaTransportControlsProperty::SoundLevel && Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name)
00930         {
00931             // Check to see if the app is being muted. If so, it is being minimized.
00932             // Otherwise if it is not initialized, it is being brought into focus.
00933             if (sender->SoundLevel == SoundLevel::Muted)
00934             {
00935                 CleanupCameraAsync();
00936             }
00937             else if (!_isInitialized)
00938             {
00939                 InitializeCameraAsync();
00940             }
00941         }
00942     }));
00943 }
00944
00945 /// <summary>
00946 /// Triggers when the Enabled property of the VideoStabilizationEffect changes.
00947 /// </summary>
00948 /// <param name="sender">The instance of the effect firing the event.</param>
00949 /// <param name="args">Information about the event.</param>
00950 void MainPage::VideoStabilizationEffect_EnabledChanged(Windows::Media::Core::VideoStabilizationEffect^ sender, Windows::Media::Core::VideoStabilizationEffectEnabledChangedEventArgs^ args)
00951 {
00952     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([sender, args, this]()
00953     {
00954         WriteLine("VS Enabled: " + sender->Enabled.ToString() + ". Reason: " + args->Reason.ToString());
00955         UpdateCaptureControls();
00956     }));
00957 }
00958
00959 /// <summary>
00960 /// Occurs each time the simple orientation sensor reports a new sensor reading.
00961 /// </summary>
00962 /// <param name="args">The event data.</param>
00963 void MainPage::OrientationSensor_OrientationChanged(SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^ args)
00964 {
00965     // If the device is parallel to the ground, keep the last orientation used. This allows users to take pictures of documents (FaceUp)
00966     // or the ceiling (FaceDown) in any orientation, by first holding the device in the desired orientation, and then pointing the camera
00967     // at the desired subject.
00968     if (args->Orientation != SimpleOrientation::Faceup && args->Orientation != SimpleOrientation::Facedown)
00969     {
00970         _deviceOrientation = args->Orientation;
00971
00972         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00973         {
00974             UpdateButtonOrientation();
00975         }));
00976     }
00977 }
00978
00979 /// <summary>
00980 /// This is a notification that recording has to stop, and the app is expected to finalize the recording
00981 /// </summary>
00982 /// <param name="args">The event data.</param>
00983 void MainPage::MediaCapture_RecordLimitationExceeded(Capture::MediaCapture^)
00984 {
00985     StopRecordingAsync()
00986         .then([this]()
00987     {
00988         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00989         {
00990             UpdateCaptureControls();
00991         }));
00992     });
00993 }
00994
00995 void MainPage::MediaCapture_Failed(Capture::MediaCapture ^currentCaptureObject, Capture::MediaCaptureFailedEventArgs^ errorEventArgs)
00996 {
00997     std::wstringstream ss;
00998     ss << "MediaCapture_Failed: 0x" << errorEventArgs->Code << ": " << errorEventArgs->Message->Data();
00999     WriteLine(ref new String(ss.str().c_str()));
01000
01001     CleanupCameraAsync()
01002         .then([this]()
01003     {
01004         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
01005         {
01006             UpdateCaptureControls();
01007         }));
01008     });
01009 }
01010
01011 void MainPage::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
01012 {
01013     SetupUiAsync();
01014     InitializeCameraAsync();
01015 }
01016
01017 void MainPage::OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e)
01018 {
01019     // Handling of this event is included for completeness, as it will only fire when navigating between pages and this sample only includes one page
01020     CleanupCameraAsync();
01021     CleanupUiAsync();
01022 }
Generated on Fri Nov 15 2024 22:17:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisplayOrientation/cppwinrt/Scenario1_Orientation.cpp Source File

  • DisplayOrientation
  • cppwinrt

Scenario1_Orientation.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_Orientation.h"
00014 #include "Scenario1_Orientation.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace winrt::Windows::Foundation;
00018 using namespace winrt::Windows::Graphics::Display;
00019 using namespace winrt::Windows::UI::Xaml;
00020
00021 namespace winrt::SDKTemplate::implementation
00022 {
00023     Scenario1_Orientation::Scenario1_Orientation()
00024     {
00025         InitializeComponent();
00026     }
00027
00028     void Scenario1_Orientation::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&)
00029     {
00030         displayInfo = DisplayInformation::GetForCurrentView();
00031         orientationChangedToken = displayInfo.OrientationChanged({ get_weak(), &Scenario1_Orientation::OnOrientationChanged });
00032         UpdateContent();
00033     }
00034
00035     void Scenario1_Orientation::OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&)
00036     {
00037         displayInfo.OrientationChanged(orientationChangedToken);
00038     }
00039
00040     void Scenario1_Orientation::OnOrientationChanged(DisplayInformation const&, IInspectable const&)
00041     {
00042         UpdateContent();
00043     }
00044
00045     hstring Scenario1_Orientation::OrientationsToString(DisplayOrientations orientations)
00046     {
00047         std::wstring result = L"None";
00048
00049         if ((orientations & DisplayOrientations::Landscape) == DisplayOrientations::Landscape)
00050         {
00051             result += L", Landscape";
00052         }
00053         if ((orientations & DisplayOrientations::Portrait) == DisplayOrientations::Portrait)
00054         {
00055             result += L", Portrait";
00056         }
00057         if ((orientations & DisplayOrientations::LandscapeFlipped) == DisplayOrientations::LandscapeFlipped)
00058         {
00059             result += L", LandscapeFlipped";
00060         }
00061         if ((orientations & DisplayOrientations::PortraitFlipped) == DisplayOrientations::PortraitFlipped)
00062         {
00063             result += L", PortraitFlipped";
00064         }
00065         if (result != L"None")
00066         {
00067             result = result.substr(6);
00068         }
00069         return hstring{ result };
00070     }
00071
00072     void Scenario1_Orientation::UpdateContent()
00073     {
00074         NativeOrientationTextBlock().Text(OrientationsToString(displayInfo.NativeOrientation()));
00075         CurrentOrientationTextBlock().Text(OrientationsToString(displayInfo.CurrentOrientation()));
00076         AutoRotationPreferencesTextBlock().Text(OrientationsToString(DisplayInformation::AutoRotationPreferences()));
00077     }
00078
00079     void Scenario1_Orientation::ApplyRotationLock_Click(IInspectable const&, RoutedEventArgs const&)
00080     {
00081         DisplayOrientations orientations = DisplayOrientations::None;
00082
00083         if (PreferLandscape().IsChecked().Value())
00084         {
00085             orientations = orientations | DisplayOrientations::Landscape;
00086         }
00087         if (PreferPortrait().IsChecked().Value())
00088         {
00089             orientations = orientations | DisplayOrientations::Portrait;
00090         }
00091         if (PreferLandscapeFlipped().IsChecked().Value())
00092         {
00093             orientations = orientations | DisplayOrientations::LandscapeFlipped;
00094         }
00095         if (PreferPortraitFlipped().IsChecked().Value())
00096         {
00097             orientations = orientations | DisplayOrientations::PortraitFlipped;
00098         }
00099         DisplayInformation::AutoRotationPreferences(orientations);
00100         UpdateContent();
00101     }
00102 }
Generated on Fri Nov 15 2024 22:19:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cs/Scenario5_RestoreScrollPosition.xaml.cs Source File

  • XamlListView
  • cs

Scenario5_RestoreScrollPosition.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.ObjectModel;
00014 using System.Linq;
00015 using System.Threading.Tasks;
00016 using Windows.Foundation;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario5_RestoreScrollPosition : Page
00024     {
00025         // Global variables for page. Static persisted variables are used by ListViewPersistenceHelper
00026         // We need to save the item container height if the items have variable heights. If all items have a constant fixed height, you can manually
00027         // set the height to the fixed value in ItemsListView_ContainerContentChanging
00028         private ObservableCollection<Item> _items = Item.GetItems(300);
00029         private static double _persistedItemContainerHeight = -1;
00030         private static string _persistedItemKey = "";
00031         private static string _persistedPosition = "";
00032
00033         public Scenario5_RestoreScrollPosition()
00034         {
00035             InitializeComponent();
00036         }
00037
00038         private async void Page_Loaded(object sender, RoutedEventArgs e)
00039         {
00040             if (!string.IsNullOrEmpty(_persistedPosition))
00041             {
00042                 // Here we kick off the async function to use the saved string _persistedPosition and the function GetItem to restore the scroll posistion
00043                 await ListViewPersistenceHelper.SetRelativeScrollPositionAsync(this.ItemsListView, _persistedPosition, this.GetItem);
00044             }
00045         }
00046
00047         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00048         {
00049             // Before we navigate away from the page, we want to generate a new _persistedPosition string. This string contains the key of the item at the top of the
00050             // viewing window (generated by the function GetKey) and the offset of that item.
00051             _persistedPosition = ListViewPersistenceHelper.GetRelativeScrollPosition(this.ItemsListView, this.GetKey);
00052         }
00053
00054         private IAsyncOperation<object> GetItem(string key)
00055         {
00056             // This function takes a key that ListViewPersistenceHelper parsed out of the _persistedPosition string
00057             // It returns an item that corresponds to the given key
00058             // The implementation of this function is dependent on the data model you are using. Every item in your list should have
00059             // a unique key this function returns
00060             return Task.Run(() =>
00061             {
00062                 if (_items.Count <= 0)
00063                 {
00064                     return null;
00065                 }
00066                 else
00067                 {
00068                     return (object)_items.FirstOrDefault(i => i.Id == key);
00069                 }
00070             }).AsAsyncOperation();
00071         }
00072
00073         private string GetKey(object item)
00074         {
00075             // This function takes in the item at the top of the viewport at the moment of navigating away from the page, and returns
00076             // a key corresponding to that item. the implementation of this function is dependent on the data model you are using. In this
00077             // function we also save the fully rendered _persistedItemContainerHeight. You do not need to do this if all of your items have
00078             // the same fixed height. Finally, we save the key into a variable so it can be used outside of ListViewPersistenceHelper functions
00079             var singleItem = item as Item;
00080             if (singleItem != null)
00081             {
00082                 _persistedItemContainerHeight = (ItemsListView.ContainerFromItem(item) as ListViewItem).ActualHeight;
00083                 _persistedItemKey = singleItem.Id;
00084                 return _persistedItemKey;
00085             }
00086             else
00087             {
00088                 return string.Empty;
00089             }
00090         }
00091
00092         private void ItemsListView_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
00093         {
00094             // This function manually sets the height of the item ListViewPersistenceHelper is attempting to scroll to. We need to set the height
00095             // because if the item is not fully rendered at the time of scrolling, it can return an incorrect height and cause ListViewPersistenceHelper
00096             // to overscroll.
00097             var singleItem = args.Item as Item;
00098
00099             if (singleItem != null && singleItem.Id == _persistedItemKey)
00100             {
00101                 if (!args.InRecycleQueue)
00102                 {
00103                     // Here we set the container's height equal to the fully rendered container height we had saved before navigating away. If all the items in
00104                     // your list have the same fixed height, you can replace this variable with a hardcoded height value.
00105                     args.ItemContainer.Height = _persistedItemContainerHeight;
00106                 }
00107                 else
00108                 {
00109                     // Containers in a list are recycled when they are scrolled out of view. However, if those containers have their Height property set and the content
00110                     // changes, that set Height is still applied. This creates an incorect UI if the items in your list are supposed to be of variable height.
00111                     // If all the items in your list have the same fixed height, you do not have to do this.
00112                     args.ItemContainer.ClearValue(HeightProperty);
00113                 }
00114             }
00115         }
00116
00117         private void ItemsListView_ItemClick(object sender, RoutedEventArgs e)
00118         {
00119             this.Frame.Navigate(typeof(ImagePage));
00120         }
00121     }
00122 }
Generated on Fri Nov 15 2024 22:22:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cpp/pch.cpp Source File

  • JumpList
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MobileHotspot/cppwinrt/pch.cpp Source File

  • MobileHotspot
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/Content/IControl.h Source File

  • HolographicMixedRealityCapture
  • cpp
  • Content

IControl.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <memory>
00004 #include "..\Common\DeviceResources.h"
00005 #include "..\Common\StepTimer.h"
00006 #include <DirectXCollision.h>
00007
00008 namespace HolographicMRCSample
00009 {
00010     typedef enum
00011     {
00012         Control_Unknown = 0,
00013         Control_Panel,
00014         Control_Button,
00015         Control_CameraPreview
00016     } ControlType;
00017
00018     class IControl
00019     {
00020     public:
00021         virtual void Initialize(const std::shared_ptr<DX::DeviceResources>& deviceResources) = 0;
00022         virtual void CreateDeviceDependentResources() = 0;
00023         virtual void ReleaseDeviceDependentResources() = 0;
00024
00025         virtual void Update(
00026             const DX::StepTimer& timer,
00027             Windows::Graphics::Holographic::HolographicFrame^ holographicFrame,
00028             Windows::Perception::Spatial::SpatialCoordinateSystem^ currentCoordinateSystem,
00029             Windows::UI::Input::Spatial::SpatialInteractionSourceState^ interactionSource) = 0;
00030         virtual void Update(
00031             const DX::StepTimer& timer,
00032             Windows::Graphics::Holographic::HolographicFrame^ holographicFrame,
00033             Windows::Perception::Spatial::SpatialCoordinateSystem^ currentCoordinateSystem,
00034             Windows::UI::Input::Spatial::SpatialInteractionSourceState^ interactionSource,
00035             const DirectX::XMMATRIX &parentTransform) = 0;
00036         virtual void Render() = 0;
00037
00038         virtual void AddChild(const std::shared_ptr<IControl>& object) = 0;
00039
00040         virtual void SetPosition(Windows::Foundation::Numerics::float3 pos) = 0;
00041         virtual void SetRotation(Windows::Foundation::Numerics::float3 rot) = 0;
00042         virtual void SetScale(Windows::Foundation::Numerics::float3 scale) = 0;
00043
00044         virtual Windows::Foundation::Numerics::float3 GetPosition() = 0;
00045         virtual Windows::Foundation::Numerics::float3 GetRotation() = 0;
00046         virtual Windows::Foundation::Numerics::float3 GetScale() = 0;
00047
00048         virtual ControlType Type() = 0;
00049         virtual bool IsFocused() = 0;
00050         virtual bool IsEnabled() = 0;
00051
00052         virtual void SetEnabled(const bool enabled) = 0;
00053
00054         virtual void GetBoundingBox(DirectX::BoundingOrientedBox &boundingBox) = 0;
00055
00056         virtual void SetOnAirTapCallback(std::function<void()> callback) = 0;
00057     };
00058 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/Common/DeviceResources.cpp Source File

  • Simple3DGameDX
  • cpp
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DeviceResources.h"
00014 #include "DirectXSample.h"
00015
00016 using namespace D2D1;
00017 using namespace DirectX;
00018 using namespace Microsoft::WRL;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Graphics::Display;
00021 using namespace Windows::UI::Core;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Platform;
00024
00025 // Constants used to calculate screen rotations.
00026 namespace ScreenRotation
00027 {
00028     // 0-degree Z-rotation
00029     static const XMFLOAT4X4 Rotation0(
00030         1.0f, 0.0f, 0.0f, 0.0f,
00031         0.0f, 1.0f, 0.0f, 0.0f,
00032         0.0f, 0.0f, 1.0f, 0.0f,
00033         0.0f, 0.0f, 0.0f, 1.0f
00034         );
00035
00036     // 90-degree Z-rotation
00037     static const XMFLOAT4X4 Rotation90(
00038         0.0f, 1.0f, 0.0f, 0.0f,
00039         -1.0f, 0.0f, 0.0f, 0.0f,
00040         0.0f, 0.0f, 1.0f, 0.0f,
00041         0.0f, 0.0f, 0.0f, 1.0f
00042         );
00043
00044     // 180-degree Z-rotation
00045     static const XMFLOAT4X4 Rotation180(
00046         -1.0f, 0.0f, 0.0f, 0.0f,
00047         0.0f, -1.0f, 0.0f, 0.0f,
00048         0.0f, 0.0f, 1.0f, 0.0f,
00049         0.0f, 0.0f, 0.0f, 1.0f
00050         );
00051
00052     // 270-degree Z-rotation
00053     static const XMFLOAT4X4 Rotation270(
00054         0.0f, -1.0f, 0.0f, 0.0f,
00055         1.0f, 0.0f, 0.0f, 0.0f,
00056         0.0f, 0.0f, 1.0f, 0.0f,
00057         0.0f, 0.0f, 0.0f, 1.0f
00058         );
00059 };
00060
00061 // Constructor for DeviceResources.
00062 DX::DeviceResources::DeviceResources() :
00063     m_screenViewport(),
00064     m_d3dFeatureLevel(D3D_FEATURE_LEVEL_9_1),
00065     m_d3dRenderTargetSize(),
00066     m_outputSize(),
00067     m_logicalSize(),
00068     m_nativeOrientation(DisplayOrientations::None),
00069     m_currentOrientation(DisplayOrientations::None),
00070     m_dpi(-1.0f),
00071     m_deviceNotify(nullptr)
00072 {
00073     CreateDeviceIndependentResources();
00074     CreateDeviceResources();
00075 }
00076
00077 // Configures resources that don't depend on the Direct3D device.
00078 void DX::DeviceResources::CreateDeviceIndependentResources()
00079 {
00080     // Initialize Direct2D resources.
00081     D2D1_FACTORY_OPTIONS options;
00082     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00083
00084 #if defined(_DEBUG)
00085     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00086     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00087 #endif
00088
00089     // Initialize the Direct2D Factory.
00090     DX::ThrowIfFailed(
00091         D2D1CreateFactory(
00092             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00093             __uuidof(ID2D1Factory2),
00094             &options,
00095             &m_d2dFactory
00096             )
00097         );
00098
00099     // Initialize the DirectWrite Factory.
00100     DX::ThrowIfFailed(
00101         DWriteCreateFactory(
00102             DWRITE_FACTORY_TYPE_SHARED,
00103             __uuidof(IDWriteFactory2),
00104             &m_dwriteFactory
00105             )
00106         );
00107
00108     // Initialize the Windows Imaging Component (WIC) Factory.
00109     DX::ThrowIfFailed(
00110         CoCreateInstance(
00111             CLSID_WICImagingFactory2,
00112             nullptr,
00113             CLSCTX_INPROC_SERVER,
00114             IID_PPV_ARGS(&m_wicFactory)
00115             )
00116         );
00117 }
00118
00119 // Configures the Direct3D device, and stores handles to it and the device context.
00120 void DX::DeviceResources::CreateDeviceResources()
00121 {
00122     // This flag adds support for surfaces with a different color channel ordering
00123     // than the API default. It is required for compatibility with Direct2D.
00124     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00125
00126 #if defined(_DEBUG)
00127     if (DX::SdkLayersAvailable())
00128     {
00129         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00130         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00131     }
00132 #endif
00133
00134     // This array defines the set of DirectX hardware feature levels this app will support.
00135     // Note the ordering should be preserved.
00136     // Don't forget to declare your application's minimum required feature level in its
00137     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00138     D3D_FEATURE_LEVEL featureLevels [] =
00139     {
00140         D3D_FEATURE_LEVEL_11_1,
00141         D3D_FEATURE_LEVEL_11_0,
00142         D3D_FEATURE_LEVEL_10_1,
00143         D3D_FEATURE_LEVEL_10_0,
00144         D3D_FEATURE_LEVEL_9_3,
00145         D3D_FEATURE_LEVEL_9_2,
00146         D3D_FEATURE_LEVEL_9_1
00147     };
00148
00149     // Create the Direct3D 11 API device object and a corresponding context.
00150     ComPtr<ID3D11Device> device;
00151     ComPtr<ID3D11DeviceContext> context;
00152
00153     HRESULT hr = D3D11CreateDevice(
00154         nullptr,                    // Specify nullptr to use the default adapter.
00155         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00156         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00157         creationFlags,              // Set debug and Direct2D compatibility flags.
00158         featureLevels,              // List of feature levels this app can support.
00159         ARRAYSIZE(featureLevels),   // Size of the list above.
00160         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00161         &device,                    // Returns the Direct3D device created.
00162         &m_d3dFeatureLevel,         // Returns feature level of device created.
00163         &context                    // Returns the device immediate context.
00164         );
00165
00166     if (FAILED(hr))
00167     {
00168         // If the initialization fails, fall back to the WARP device.
00169         // For more information on WARP, see:
00170         // http://go.microsoft.com/fwlink/?LinkId=286690
00171         DX::ThrowIfFailed(
00172             D3D11CreateDevice(
00173                 nullptr,
00174                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00175                 0,
00176                 creationFlags,
00177                 featureLevels,
00178                 ARRAYSIZE(featureLevels),
00179                 D3D11_SDK_VERSION,
00180                 &device,
00181                 &m_d3dFeatureLevel,
00182                 &context
00183                 )
00184             );
00185     }
00186
00187     // Store pointers to the Direct3D 11.1 API device and immediate context.
00188     DX::ThrowIfFailed(
00189         device.As(&m_d3dDevice)
00190         );
00191
00192     DX::ThrowIfFailed(
00193         context.As(&m_d3dContext)
00194         );
00195
00196     // Create the Direct2D device object and a corresponding context.
00197     ComPtr<IDXGIDevice3> dxgiDevice;
00198     DX::ThrowIfFailed(
00199         m_d3dDevice.As(&dxgiDevice)
00200         );
00201
00202     DX::ThrowIfFailed(
00203         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00204         );
00205
00206     DX::ThrowIfFailed(
00207         m_d2dDevice->CreateDeviceContext(
00208             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00209             &m_d2dContext
00210             )
00211         );
00212 }
00213
00214 // These resources need to be recreated every time the window size is changed.
00215 void DX::DeviceResources::CreateWindowSizeDependentResources()
00216 {
00217     // Clear the previous window size specific context.
00218     ID3D11RenderTargetView* nullViews [] = { nullptr };
00219     m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00220     m_d3dRenderTargetView = nullptr;
00221     m_d3dRenderTargetViewRight = nullptr;
00222     m_d2dContext->SetTarget(nullptr);
00223     m_d2dTargetBitmap = nullptr;
00224     m_d2dTargetBitmapRight = nullptr;
00225     m_d3dDepthStencilView = nullptr;
00226     m_d3dContext->Flush();
00227
00228     // Calculate the necessary swap chain and render target size in pixels.
00229     m_outputSize.Width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_dpi);
00230     m_outputSize.Height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_dpi);
00231
00232     // Prevent zero size DirectX content from being created.
00233     m_outputSize.Width = max(m_outputSize.Width, 1);
00234     m_outputSize.Height = max(m_outputSize.Height, 1);
00235
00236     // The width and height of the swap chain must be based on the window's
00237     // natively-oriented width and height. If the window is not in the native
00238     // orientation, the dimensions must be reversed.
00239     DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation();
00240
00241     bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270;
00242     m_d3dRenderTargetSize.Width = swapDimensions ? m_outputSize.Height : m_outputSize.Width;
00243     m_d3dRenderTargetSize.Height = swapDimensions ? m_outputSize.Width : m_outputSize.Height;
00244
00245     if (m_swapChain != nullptr)
00246     {
00247         // If the swap chain already exists, resize it.
00248         HRESULT hr = m_swapChain->ResizeBuffers(
00249             2, // Double-buffered swap chain.
00250             static_cast<UINT>(m_d3dRenderTargetSize.Width),
00251             static_cast<UINT>(m_d3dRenderTargetSize.Height),
00252             DXGI_FORMAT_B8G8R8A8_UNORM,
00253             0
00254             );
00255
00256         if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00257         {
00258             // If the device was removed for any reason, a new device and swap chain will need to be created.
00259             HandleDeviceLost();
00260
00261             // Everything is set up now. Do not continue execution of this method. HandleDeviceLost will reenter this method
00262             // and correctly set up the new device.
00263             return;
00264         }
00265         else
00266         {
00267             DX::ThrowIfFailed(hr);
00268         }
00269     }
00270     else
00271     {
00272         CheckStereoEnabledStatus();
00273
00274         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00275         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = { 0 };
00276
00277         swapChainDesc.Width = static_cast<UINT>(m_d3dRenderTargetSize.Width); // Match the size of the window.
00278         swapChainDesc.Height = static_cast<UINT>(m_d3dRenderTargetSize.Height);
00279         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swap chain format.
00280         swapChainDesc.Stereo = m_stereoEnabled;
00281         swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling.
00282         swapChainDesc.SampleDesc.Quality = 0;
00283         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00284         swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency.
00285         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Store apps must use this SwapEffect.
00286         swapChainDesc.Flags = 0;
00287         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00288         swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
00289
00290         // This sequence obtains the DXGI factory that was used to create the Direct3D device above.
00291         ComPtr<IDXGIDevice3> dxgiDevice;
00292         DX::ThrowIfFailed(
00293             m_d3dDevice.As(&dxgiDevice)
00294             );
00295
00296         ComPtr<IDXGIAdapter> dxgiAdapter;
00297         DX::ThrowIfFailed(
00298             dxgiDevice->GetAdapter(&dxgiAdapter)
00299             );
00300
00301         ComPtr<IDXGIFactory3> dxgiFactory;
00302         DX::ThrowIfFailed(
00303             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00304             );
00305
00306         DX::ThrowIfFailed(
00307             dxgiFactory->CreateSwapChainForCoreWindow(
00308                 m_d3dDevice.Get(),
00309                 reinterpret_cast<IUnknown*>(m_window.Get()),
00310                 &swapChainDesc,
00311                 nullptr,
00312                 &m_swapChain
00313                 )
00314             );
00315
00316         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00317         // ensures that the application will only render after each VSync, minimizing power consumption.
00318         DX::ThrowIfFailed(
00319             dxgiDevice->SetMaximumFrameLatency(1)
00320             );
00321     }
00322
00323     // Set the proper orientation for the swap chain, and generate 2D and
00324     // 3D matrix transformations for rendering to the rotated swap chain.
00325     // Note the rotation angle for the 2D and 3D transforms are different.
00326     // This is due to the difference in coordinate spaces.  Additionally,
00327     // the 3D matrix is specified explicitly to avoid rounding errors.
00328
00329     switch (displayRotation)
00330     {
00331     case DXGI_MODE_ROTATION_IDENTITY:
00332         m_orientationTransform2D = Matrix3x2F::Identity();
00333         m_orientationTransform3D = ScreenRotation::Rotation0;
00334         break;
00335
00336     case DXGI_MODE_ROTATION_ROTATE90:
00337         m_orientationTransform2D =
00338             Matrix3x2F::Rotation(90.0f) *
00339             Matrix3x2F::Translation(m_logicalSize.Height, 0.0f);
00340         m_orientationTransform3D = ScreenRotation::Rotation270;
00341         break;
00342
00343     case DXGI_MODE_ROTATION_ROTATE180:
00344         m_orientationTransform2D =
00345             Matrix3x2F::Rotation(180.0f) *
00346             Matrix3x2F::Translation(m_logicalSize.Width, m_logicalSize.Height);
00347         m_orientationTransform3D = ScreenRotation::Rotation180;
00348         break;
00349
00350     case DXGI_MODE_ROTATION_ROTATE270:
00351         m_orientationTransform2D =
00352             Matrix3x2F::Rotation(270.0f) *
00353             Matrix3x2F::Translation(0.0f, m_logicalSize.Width);
00354         m_orientationTransform3D = ScreenRotation::Rotation90;
00355         break;
00356
00357     default:
00358         throw ref new FailureException();
00359     }
00360
00361     DX::ThrowIfFailed(
00362         m_swapChain->SetRotation(displayRotation)
00363         );
00364
00365     // Create a render target view of the swap chain back buffer.
00366     ComPtr<ID3D11Texture2D> backBuffer;
00367     DX::ThrowIfFailed(
00368         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00369         );
00370
00371     DX::ThrowIfFailed(
00372         m_d3dDevice->CreateRenderTargetView(
00373             backBuffer.Get(),
00374             nullptr,
00375             &m_d3dRenderTargetView
00376             )
00377         );
00378
00379     // Stereo swapchains have an arrayed resource, so create a second Render Target
00380     // for the right eye buffer.
00381     if (m_stereoEnabled)
00382     {
00383         CD3D11_RENDER_TARGET_VIEW_DESC renderTargetViewRightDesc(
00384             D3D11_RTV_DIMENSION_TEXTURE2DARRAY,
00385             DXGI_FORMAT_B8G8R8A8_UNORM,
00386             0,
00387             1,
00388             1
00389             );
00390
00391         DX::ThrowIfFailed(
00392             m_d3dDevice->CreateRenderTargetView(
00393                 backBuffer.Get(),
00394                 &renderTargetViewRightDesc,
00395                 &m_d3dRenderTargetViewRight
00396                 )
00397             );
00398     }
00399
00400     // Create a depth stencil view for use with 3D rendering if needed.
00401     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00402         DXGI_FORMAT_D24_UNORM_S8_UINT,
00403         static_cast<UINT>(m_d3dRenderTargetSize.Width),
00404         static_cast<UINT>(m_d3dRenderTargetSize.Height),
00405         1, // This depth stencil view has only one texture.
00406         1, // Use a single mipmap level.
00407         D3D11_BIND_DEPTH_STENCIL
00408         );
00409
00410     ComPtr<ID3D11Texture2D> depthStencil;
00411     DX::ThrowIfFailed(
00412         m_d3dDevice->CreateTexture2D(
00413             &depthStencilDesc,
00414             nullptr,
00415             &depthStencil
00416             )
00417         );
00418
00419     CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
00420     DX::ThrowIfFailed(
00421         m_d3dDevice->CreateDepthStencilView(
00422             depthStencil.Get(),
00423             &depthStencilViewDesc,
00424             &m_d3dDepthStencilView
00425             )
00426         );
00427
00428     // Set the 3D rendering viewport to target the entire window.
00429     m_screenViewport = CD3D11_VIEWPORT(
00430         0.0f,
00431         0.0f,
00432         m_d3dRenderTargetSize.Width,
00433         m_d3dRenderTargetSize.Height
00434         );
00435
00436     m_d3dContext->RSSetViewports(1, &m_screenViewport);
00437
00438     // Create a Direct2D target bitmap associated with the
00439     // swap chain back buffer and set it as the current target.
00440     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00441         D2D1::BitmapProperties1(
00442             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00443             D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED
00444             ),
00445         m_dpi,
00446         m_dpi
00447         );
00448
00449     ComPtr<IDXGIResource1> dxgiBackBuffer;
00450     DX::ThrowIfFailed(
00451         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00452         );
00453
00454     ComPtr<IDXGISurface2> dxgiSurface;
00455     DX::ThrowIfFailed(
00456         dxgiBackBuffer->CreateSubresourceSurface(0, &dxgiSurface)
00457         );
00458
00459     DX::ThrowIfFailed(
00460         m_d2dContext->CreateBitmapFromDxgiSurface(
00461             dxgiSurface.Get(),
00462             &bitmapProperties,
00463             &m_d2dTargetBitmap
00464             )
00465         );
00466
00467     // Stereo swapchains have an arrayed resource, so create a second Target Bitmap
00468     // for the right eye buffer.
00469     if (m_stereoEnabled)
00470     {
00471         DX::ThrowIfFailed(
00472             dxgiBackBuffer->CreateSubresourceSurface(1, &dxgiSurface)
00473             );
00474         DX::ThrowIfFailed(
00475             m_d2dContext->CreateBitmapFromDxgiSurface(
00476                 dxgiSurface.Get(),
00477                 &bitmapProperties,
00478                 &m_d2dTargetBitmapRight
00479                 )
00480             );
00481     }
00482
00483     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00484
00485     // Grayscale text anti-aliasing is recommended for all Windows Store apps.
00486     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00487 }
00488
00489 // This method is called when the CoreWindow is created (or re-created).
00490 void DX::DeviceResources::SetWindow(CoreWindow^ window)
00491 {
00492     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00493
00494     m_window = window;
00495     m_logicalSize = Windows::Foundation::Size(window->Bounds.Width, window->Bounds.Height);
00496     m_nativeOrientation = currentDisplayInformation->NativeOrientation;
00497     m_currentOrientation = currentDisplayInformation->CurrentOrientation;
00498     m_dpi = currentDisplayInformation->LogicalDpi;
00499     m_d2dContext->SetDpi(m_dpi, m_dpi);
00500
00501     CreateWindowSizeDependentResources();
00502 }
00503
00504 // This method is called in the event handler for the SizeChanged event.
00505 void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize)
00506 {
00507     if (m_logicalSize != logicalSize)
00508     {
00509         m_logicalSize = logicalSize;
00510         CreateWindowSizeDependentResources();
00511     }
00512 }
00513
00514 // This method is called in the event handler for the DpiChanged event.
00515 void DX::DeviceResources::SetDpi(float dpi)
00516 {
00517     if (dpi != m_dpi)
00518     {
00519         m_dpi = dpi;
00520
00521         // When the display DPI changes, the logical size of the window (measured in Dips) also changes and needs to be updated.
00522         m_logicalSize = Windows::Foundation::Size(m_window->Bounds.Width, m_window->Bounds.Height);
00523
00524         m_d2dContext->SetDpi(m_dpi, m_dpi);
00525         CreateWindowSizeDependentResources();
00526     }
00527 }
00528
00529 // This method is called in the event handler for the OrientationChanged event.
00530 void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation)
00531 {
00532     if (m_currentOrientation != currentOrientation)
00533     {
00534         m_currentOrientation = currentOrientation;
00535         CreateWindowSizeDependentResources();
00536     }
00537 }
00538
00539 // This method is called in the event handler for the DisplayContentsInvalidated event.
00540 void DX::DeviceResources::ValidateDevice()
00541 {
00542     // The D3D Device is no longer valid if the default adapter changed since the device
00543     // was created or if the device has been removed.
00544
00545     // First, get the information for the default adapter from when the device was created.
00546
00547     ComPtr<IDXGIDevice3> dxgiDevice;
00548     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00549
00550     ComPtr<IDXGIAdapter> deviceAdapter;
00551     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00552
00553     ComPtr<IDXGIFactory2> deviceFactory;
00554     DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory)));
00555
00556     ComPtr<IDXGIAdapter1> previousDefaultAdapter;
00557     DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter));
00558
00559     DXGI_ADAPTER_DESC previousDesc;
00560     DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc));
00561
00562     // Next, get the information for the current default adapter.
00563
00564     ComPtr<IDXGIFactory2> currentFactory;
00565     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&currentFactory)));
00566
00567     ComPtr<IDXGIAdapter1> currentDefaultAdapter;
00568     DX::ThrowIfFailed(currentFactory->EnumAdapters1(0, &currentDefaultAdapter));
00569
00570     DXGI_ADAPTER_DESC currentDesc;
00571     DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(&currentDesc));
00572
00573     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00574     // a new D3D device must be created.
00575
00576     if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart ||
00577         previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart ||
00578         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00579     {
00580         // Release references to resources related to the old device.
00581         dxgiDevice = nullptr;
00582         deviceAdapter = nullptr;
00583         deviceFactory = nullptr;
00584         previousDefaultAdapter = nullptr;
00585
00586         // Create a new device and swap chain.
00587         HandleDeviceLost();
00588     }
00589 }
00590
00591 // Recreate all device resources and set them back to the current state.
00592 void DX::DeviceResources::HandleDeviceLost()
00593 {
00594     m_swapChain = nullptr;
00595
00596     if (m_deviceNotify != nullptr)
00597     {
00598         m_deviceNotify->OnDeviceLost();
00599     }
00600
00601     // Make sure the rendering state has been released.
00602     m_d3dContext->OMSetRenderTargets(0, nullptr, nullptr);
00603     m_d3dDepthStencilView = nullptr;
00604     m_d3dRenderTargetView = nullptr;
00605     m_d3dRenderTargetViewRight = nullptr;
00606
00607     m_d2dContext->SetTarget(nullptr);
00608     m_d2dTargetBitmap = nullptr;
00609     m_d2dTargetBitmapRight = nullptr;
00610     m_d2dContext = nullptr;
00611     m_d2dDevice = nullptr;
00612
00613     m_d3dContext->Flush();
00614
00615     CreateDeviceResources();
00616     m_d2dContext->SetDpi(m_dpi, m_dpi);
00617     CreateWindowSizeDependentResources();
00618
00619     if (m_deviceNotify != nullptr)
00620     {
00621         m_deviceNotify->OnDeviceRestored();
00622     }
00623 }
00624
00625 // Register our DeviceNotify to be informed on device lost and creation.
00626 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00627 {
00628     m_deviceNotify = deviceNotify;
00629 }
00630
00631 // Call this method when the app suspends. It provides a hint to the driver that the app
00632 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00633 void DX::DeviceResources::Trim()
00634 {
00635     ComPtr<IDXGIDevice3> dxgiDevice;
00636     m_d3dDevice.As(&dxgiDevice);
00637
00638     dxgiDevice->Trim();
00639 }
00640
00641 // Present the contents of the swap chain to the screen.
00642 void DX::DeviceResources::Present()
00643 {
00644     // The first argument instructs DXGI to block until VSync, putting the application
00645     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00646     // frames that will never be displayed to the screen.
00647     HRESULT hr = m_swapChain->Present(1, 0);
00648
00649     // Discard the contents of the render target.
00650     // This is a valid operation only when the existing contents will be entirely
00651     // overwritten. If dirty or scroll rects are used, this call should be removed.
00652     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00653
00654     // Discard the contents of the depth stencil.
00655     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00656
00657     // If the device was removed either by a disconnection or a driver upgrade, we
00658     // must recreate all device resources.
00659     if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00660     {
00661         HandleDeviceLost();
00662     }
00663     else
00664     {
00665         DX::ThrowIfFailed(hr);
00666     }
00667 }
00668
00669 // This method determines the rotation between the display device's native Orientation and the
00670 // current display orientation.
00671 DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation()
00672 {
00673     DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
00674
00675     // Note: NativeOrientation can only be Landscape or Portrait even though
00676     // the DisplayOrientations enum has other values.
00677     switch (m_nativeOrientation)
00678     {
00679     case DisplayOrientations::Landscape:
00680         switch (m_currentOrientation)
00681         {
00682         case DisplayOrientations::Landscape:
00683             rotation = DXGI_MODE_ROTATION_IDENTITY;
00684             break;
00685
00686         case DisplayOrientations::Portrait:
00687             rotation = DXGI_MODE_ROTATION_ROTATE270;
00688             break;
00689
00690         case DisplayOrientations::LandscapeFlipped:
00691             rotation = DXGI_MODE_ROTATION_ROTATE180;
00692             break;
00693
00694         case DisplayOrientations::PortraitFlipped:
00695             rotation = DXGI_MODE_ROTATION_ROTATE90;
00696             break;
00697         }
00698         break;
00699
00700     case DisplayOrientations::Portrait:
00701         switch (m_currentOrientation)
00702         {
00703         case DisplayOrientations::Landscape:
00704             rotation = DXGI_MODE_ROTATION_ROTATE90;
00705             break;
00706
00707         case DisplayOrientations::Portrait:
00708             rotation = DXGI_MODE_ROTATION_IDENTITY;
00709             break;
00710
00711         case DisplayOrientations::LandscapeFlipped:
00712             rotation = DXGI_MODE_ROTATION_ROTATE270;
00713             break;
00714
00715         case DisplayOrientations::PortraitFlipped:
00716             rotation = DXGI_MODE_ROTATION_ROTATE180;
00717             break;
00718         }
00719         break;
00720     }
00721     return rotation;
00722 }
00723
00724 void DX::DeviceResources::UpdateStereoState()
00725 {
00726     bool previousStereoState = m_stereoEnabled;
00727     CheckStereoEnabledStatus();
00728     if (previousStereoState != m_stereoEnabled)
00729     {
00730         // Swap chain needs to be recreated so release the existing one.
00731         // The rest of the dependent resources with be released in CreateWindowSizeDependentResources.
00732         m_swapChain = nullptr;
00733         CreateWindowSizeDependentResources();
00734     }
00735
00736 }
00737
00738 void DX::DeviceResources::CheckStereoEnabledStatus()
00739 {
00740     // first, retrieve the underlying DXGI Device from the D3D Device
00741     ComPtr<IDXGIDevice1> dxgiDevice;
00742     DX::ThrowIfFailed(
00743         m_d3dDevice.As(&dxgiDevice)
00744         );
00745
00746     // next, get the associated adapter from the DXGI Device
00747     ComPtr<IDXGIAdapter> dxgiAdapter;
00748     DX::ThrowIfFailed(
00749         dxgiDevice->GetAdapter(&dxgiAdapter)
00750         );
00751
00752     // next, get the parent factory from the DXGI adapter
00753     ComPtr<IDXGIFactory2> dxgiFactory;
00754     DX::ThrowIfFailed(
00755         dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00756         );
00757
00758     m_stereoEnabled = dxgiFactory->IsWindowedStereoEnabled() ? true : false;
00759 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cpp/SampleConfiguration.h Source File

  • ResizeAppView
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Resize app view";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Level6.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Level6.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Level6:
00015 // This class defines the sixth and final level of the game. It derives from the
00016 // fifth level. In this level the targets do not disappear when they are hit.
00017 // The target will stay highlighted for two seconds. As this is the last level
00018 // the only criteria for completion is time expiring.
00019
00020 #include "Level5.h"
00021
00022 class Level6 : public Level5
00023 {
00024 public:
00025     Level6();
00026     virtual bool Update(
00027         float time,
00028         float elapsedTime,
00029         float timeRemaining,
00030         std::vector<std::shared_ptr<GameObject>> const& objects
00031         ) override;
00032 };
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cppwinrt/Scenario5_DisplayingBarcodePreview.h Source File

  • BarcodeScanner
  • cppwinrt

Scenario5_DisplayingBarcodePreview.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario5_DisplayingBarcodePreview.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario5_DisplayingBarcodePreview : Scenario5_DisplayingBarcodePreviewT<Scenario5_DisplayingBarcodePreview>
00019     {
00020         Scenario5_DisplayingBarcodePreview();
00021
00022         bool IsScannerClaimed()
00023         {
00024             return m_isScannerClaimed;
00025         }
00026         void IsScannerClaimed(bool claimed)
00027         {
00028             m_isScannerClaimed = claimed;
00029         }
00030
00031         bool IsPreviewing()
00032         {
00033             return m_isPreviewing;
00034         }
00035         void IsPreviewing(bool isPreviewing)
00036         {
00037             m_isPreviewing = isPreviewing;
00038         }
00039
00040         bool ScannerSupportsPreview()
00041         {
00042             return m_scannerSupportsPreview;
00043         }
00044         void ScannerSupportsPreview(bool supportsPreview)
00045         {
00046             m_scannerSupportsPreview = supportsPreview;
00047         }
00048
00049         bool SoftwareTriggerStarted()
00050         {
00051             return m_softwareTriggerStarted;
00052         }
00053         void SoftwareTriggerStarted(bool started)
00054         {
00055             m_softwareTriggerStarted = started;
00056         }
00057
00058         event_token PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const& handler)
00059         {
00060             return m_propertyChanged.add(handler);
00061         }
00062
00063         void PropertyChanged(event_token const& token) noexcept
00064         {
00065             return m_propertyChanged.remove(token);
00066         }
00067
00068         fire_and_forget Watcher_Added(Windows::Devices::Enumeration::DeviceWatcher const& sender, Windows::Devices::Enumeration::DeviceInformation args);
00069         fire_and_forget Watcher_Updated(Windows::Devices::Enumeration::DeviceWatcher const& sender, Windows::Devices::Enumeration::DeviceInformationUpdate const& args);
00070         fire_and_forget Watcher_Removed(Windows::Devices::Enumeration::DeviceWatcher const& sender, Windows::Devices::Enumeration::DeviceInformationUpdate const& args);
00071
00072         fire_and_forget OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& args);
00073         fire_and_forget ScannerSelection_Changed(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs const& args);
00074         void FlipPreview_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00075         fire_and_forget ShowPreviewButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00076         fire_and_forget StartSoftwareTriggerButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00077         fire_and_forget StopSoftwareTriggerButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00078         void HidePreviewButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00079
00080     private:
00081         Windows::Foundation::IAsyncAction StartMediaCaptureAsync(hstring videoDeviceId);
00082         Windows::Foundation::IAsyncAction CloseScannerResourcesAsync();
00083         Windows::Foundation::IAsyncAction SetPreviewRotationAsync(Windows::Graphics::Display::DisplayOrientations displayOrientation);
00084         void MediaCapture_Failed(Windows::Media::Capture::MediaCapture const& sender, Windows::Media::Capture::MediaCaptureFailedEventArgs const& errorEventArgs);
00085         Windows::Foundation::IAsyncAction SelectScannerAsync(hstring scannerDeviceId);
00086         void ClaimedScanner_Closed(Windows::Devices::PointOfService::ClaimedBarcodeScanner const& sender, Windows::Devices::PointOfService::ClaimedBarcodeScannerClosedEventArgs const& args);
00087
00088         fire_and_forget ClaimedScanner_DataReceived(Windows::Devices::PointOfService::ClaimedBarcodeScanner const&, Windows::Devices::PointOfService::BarcodeScannerDataReceivedEventArgs args);
00089
00090         void RaisePropertyChanged(hstring propertyName);
00091
00092         bool m_isScannerClaimed = false;
00093         bool m_isPreviewing = false;
00094         bool m_scannerSupportsPreview = false;
00095         bool m_softwareTriggerStarted = false;
00096
00097         SDKTemplate::MainPage m_rootPage{ MainPage::Current() };
00098         Windows::Foundation::Collections::IObservableVector<SDKTemplate::BarcodeScannerInfo> m_barcodeScanners{ single_threaded_observable_vector<SDKTemplate::BarcodeScannerInfo>() };
00099         Windows::Devices::PointOfService::BarcodeScanner m_selectedScanner{ nullptr };
00100         Windows::Devices::PointOfService::ClaimedBarcodeScanner m_claimedScanner{ nullptr };
00101         Windows::Devices::Enumeration::DeviceWatcher m_watcher{ nullptr };
00102
00103         Windows::System::Display::DisplayRequest m_displayRequest;
00104         Windows::Media::Capture::MediaCapture m_mediaCapture{ nullptr };
00105
00106         bool m_isSelectionChanging = false;
00107         hstring m_pendingSelectionDeviceId;
00108         bool isStopPending = false;
00109
00110         event<Windows::UI::Xaml::Data::PropertyChangedEventHandler> m_propertyChanged;
00111     };
00112 }
00113
00114 namespace winrt::SDKTemplate::factory_implementation
00115 {
00116     struct Scenario5_DisplayingBarcodePreview : Scenario5_DisplayingBarcodePreviewT<Scenario5_DisplayingBarcodePreview, implementation::Scenario5_DisplayingBarcodePreview>
00117     {
00118     };
00119 }
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cpp/Scenario5.xaml.cpp Source File

  • FileThumbnails
  • cpp

Scenario5.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario5.xaml.cpp
00014 // Implementation of the Scenario5 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario5.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace concurrency;
00023 using namespace Platform;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::Storage;
00026 using namespace Windows::Storage::FileProperties;
00027 using namespace Windows::Storage::Pickers;
00028 using namespace Windows::Storage::Search;
00029 using namespace Windows::UI::Xaml;
00030 using namespace Windows::UI::Xaml::Controls;
00031 using namespace Windows::UI::Xaml::Navigation;
00032
00033 Scenario5::Scenario5()
00034 {
00035     InitializeComponent();
00036     rootPage = MainPage::Current;
00037 }
00038
00039 void Scenario5::OnNavigatedTo(NavigationEventArgs^ e)
00040 {
00041     rootPage->ResetOutput(ThumbnailImage, OutputTextBlock, nullptr);
00042 }
00043
00044 void Scenario5::GetThumbnailButton_Click(Object^ sender, RoutedEventArgs^ e)
00045 {
00046     rootPage->ResetOutput(ThumbnailImage, OutputTextBlock, nullptr);
00047
00048     // Pick a folder
00049     FolderPicker^ folderPicker = ref new FolderPicker();
00050     Array<String^>^ extensions = FileExtensions::Image;
00051     for (unsigned int i = 0; i < extensions->Length; i++)
00052     {
00053         folderPicker->FileTypeFilter->Append(extensions[i]);
00054     }
00055
00056     create_task(folderPicker->PickSingleFolderAsync()).then([this](StorageFolder^ folder)
00057     {
00058         if (folder != nullptr)
00059         {
00060             const CommonFolderQuery monthShape = CommonFolderQuery::GroupByMonth;
00061             // Verify queries are supported because they are not supported in all picked locations.
00062             if (folder->IsCommonFolderQuerySupported(monthShape))
00063             {
00064                 create_task(folder->CreateFolderQuery(monthShape)->GetFoldersAsync()).then([this, folder](IVectorView<StorageFolder^>^ months)
00065                 {
00066                     if (months != nullptr && months->Size > 0)
00067                     {
00068                         StorageFolder^ firstMonth = months->GetAt(0);
00069                         const ThumbnailMode thumbnailMode = ThumbnailMode::PicturesView;
00070                         const size_t size = 200;
00071                         create_task(firstMonth->GetThumbnailAsync(thumbnailMode, size)).then([this, folder, firstMonth, size](StorageItemThumbnail^ thumbnail)
00072                         {
00073                             if (thumbnail != nullptr)
00074                             {
00075                                 MainPage::DisplayResult(ThumbnailImage, OutputTextBlock, "PicturesView", size, folder, thumbnail, true);
00076
00077                                 // Also display the list of files in the file group
00078                                 create_task(firstMonth->GetFilesAsync()).then([this](IVectorView<StorageFile^>^ files)
00079                                 {
00080                                     String^ output = "\nList of files in the group:\n\n";
00081                                     for (StorageFile^ file : files)
00082                                     {
00083                                         output += file->Name + "\n";
00084                                     }
00085                                     OutputDetails->Text = output;
00086                                 });
00087                             }
00088                             else
00089                             {
00090                                 rootPage->NotifyUser(Errors::NoImages, NotifyType::StatusMessage);
00091                             }
00092                         });
00093                     }
00094                     else
00095                     {
00096                         rootPage->NotifyUser(Errors::FileGroupEmpty, NotifyType::StatusMessage);
00097                     }
00098                 });
00099             }
00100             else
00101             {
00102                 rootPage->NotifyUser(Errors::FileGroupLocation, NotifyType::StatusMessage);
00103             }
00104         }
00105         else
00106         {
00107             rootPage->NotifyUser(Errors::Cancel, NotifyType::StatusMessage);
00108         }
00109     });
00110 }
Generated on Fri Nov 15 2024 22:18:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Level2.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Level2.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Level2.h"
00014 #include "Face.h"
00015
00016 Level2::Level2()
00017 {
00018     m_timeLimit = 30.0f;
00019     m_objective = L"Hit each of the targets in ORDER before time runs out.";
00020 }
00021
00022 //----------------------------------------------------------------------
00023
00024 void Level2::Initialize(std::vector<std::shared_ptr<GameObject>> const& objects)
00025 {
00026     Level1::Initialize(objects);
00027
00028     int targetCount = 0;
00029     for (auto&& object : objects)
00030     {
00031         if (auto target = dynamic_cast<Face*>(object.get()))
00032         {
00033             if (targetCount < 9)
00034             {
00035                 target->Target(targetCount == 0 ? true : false);
00036                 targetCount++;
00037             }
00038         }
00039     }
00040     m_nextId = 1;
00041 }
00042
00043 bool Level2::Update(
00044     float /* time */,
00045     float /* elapsedTime */,
00046     float /* timeRemaining */,
00047     std::vector<std::shared_ptr<GameObject>> const& objects
00048     )
00049 {
00050     int left = 0;
00051     for (auto&& object : objects)
00052     {
00053         if (object->Active() && (object->TargetId() > 0))
00054         {
00055             if (object->Hit() && (object->TargetId() == m_nextId))
00056             {
00057                 object->Active(false);
00058                 m_nextId++;
00059             }
00060             else
00061             {
00062                 left++;
00063             }
00064         }
00065         if (object->Active() && (object->TargetId() == m_nextId))
00066         {
00067             object->Target(true);
00068         }
00069     }
00070     return (left == 0);
00071 }
00072
00073 void Level2::SaveState(PersistentState& state)
00074 {
00075     state.SaveInt32(L":NextTarget", m_nextId);
00076 }
00077
00078 void Level2::LoadState(PersistentState& state)
00079 {
00080     m_nextId = state.LoadInt32(L":NextTarget", 1);
00081 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_InkingFeedback Member List

This is the complete list of members for Scenario3_InkingFeedback, including all inherited members.
currentFeedback | Scenario3_InkingFeedback | [private]
GetSelectedFeedbackOrFallback(out string message) | Scenario3_InkingFeedback | [inline, private]
HapticCanvas_Entered(object sender, PointerRoutedEventArgs e) | Scenario3_InkingFeedback | [inline, private]
HapticCanvas_Exited(object sender, PointerRoutedEventArgs e) | Scenario3_InkingFeedback | [inline, private]
hapticsController | Scenario3_InkingFeedback | [private]
penDevice | Scenario3_InkingFeedback | [private]
Scenario3_InkingFeedback() | Scenario3_InkingFeedback | [inline]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cppwinrt/SampleConfiguration.cpp Source File

  • IoT-GPIO
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"GPIO C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Get and set GPIO pin value", xaml_typename<SDKTemplate::Scenario1_GetAndSetPin>() },
00029     Scenario{ L"Listen for changes in GPIO pin value", xaml_typename < SDKTemplate::Scenario2_Listen>() },
00030 });
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CredentialPicker/cpp/Scenario3_CredentialPickerOptions.xaml.cpp Source File

  • CredentialPicker
  • cpp

Scenario3_CredentialPickerOptions.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario3_CredentialPickerOptions.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace concurrency;
00009 using namespace Platform;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::Security::Credentials::UI;
00013 using namespace Windows::UI::Xaml;
00014 using namespace Windows::UI::Xaml::Controls;
00015 using namespace Windows::UI::Xaml::Controls::Primitives;
00016 using namespace Windows::UI::Xaml::Data;
00017 using namespace Windows::UI::Xaml::Input;
00018 using namespace Windows::UI::Xaml::Media;
00019 using namespace Windows::UI::Xaml::Navigation;
00020
00021 Scenario3_CredentialPickerOptions::Scenario3_CredentialPickerOptions()
00022 {
00023     InitializeComponent();
00024 }
00025
00026 void Scenario3_CredentialPickerOptions::SetResult(CredentialPickerResults^ result)
00027 {
00028     auto domainName = result->CredentialDomainName;
00029     auto userName = result->CredentialUserName;
00030     auto password = result->CredentialPassword;
00031     auto savedByApi = result->CredentialSaved;
00032     auto saveOption = result->CredentialSaveOption;
00033
00034     Status->Text = "OK";
00035     Domain->Text = domainName;
00036     Username->Text = userName;
00037     Password->Text = password;
00038     CredentialSaved->Text = (savedByApi ? "true" : "false");
00039     switch (result->CredentialSaveOption)
00040     {
00041     case Windows::Security::Credentials::UI::CredentialSaveOption::Hidden:
00042         CheckboxState->Text = "Hidden";
00043         break;
00044     case Windows::Security::Credentials::UI::CredentialSaveOption::Selected:
00045         CheckboxState->Text = "Selected";
00046         break;
00047     case Windows::Security::Credentials::UI::CredentialSaveOption::Unselected:
00048         CheckboxState->Text = "Unselected";
00049         break;
00050     }
00051
00052 }
00053
00054 void Scenario3_CredentialPickerOptions::SetPasswordExplainVisibility(bool isShown)
00055 {
00056     if (isShown)
00057     {
00058         PasswordExplain1->Visibility = Windows::UI::Xaml::Visibility::Visible;
00059         PasswordExplain2->Visibility = Windows::UI::Xaml::Visibility::Visible;
00060     }
00061     else
00062     {
00063         PasswordExplain1->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00064         PasswordExplain2->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00065     }
00066 }
00067
00068 void Scenario3_CredentialPickerOptions::Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00069 {
00070     if ((Message->Text == nullptr) || (Caption->Text == nullptr) || (Target->Text == nullptr))
00071     {
00072         return;
00073     }
00074
00075     CredentialPickerOptions^ credPickerOptions = ref new CredentialPickerOptions();
00076     credPickerOptions->AlwaysDisplayDialog = AlwaysShowDialog->IsChecked->Value;
00077     credPickerOptions->Message = Message->Text;
00078     credPickerOptions->Caption = Caption->Text;
00079     credPickerOptions->TargetName = Target->Text;
00080     if (ProtocolSelection->SelectedItem == nullptr)
00081     {
00082         credPickerOptions->AuthenticationProtocol = Windows::Security::Credentials::UI::AuthenticationProtocol::Negotiate;
00083     }
00084     else
00085     {
00086         String^ protocolName = ((ComboBoxItem^)ProtocolSelection->SelectedItem)->Content->ToString();
00087         if (protocolName->Equals("Negotiate"))
00088         {
00089             credPickerOptions->AuthenticationProtocol = Windows::Security::Credentials::UI::AuthenticationProtocol::Negotiate;
00090         }
00091         else if (protocolName->Equals("NTLM"))
00092         {
00093             credPickerOptions->AuthenticationProtocol = Windows::Security::Credentials::UI::AuthenticationProtocol::Ntlm;
00094         }
00095         else if (protocolName->Equals("Kerberos"))
00096         {
00097             credPickerOptions->AuthenticationProtocol = Windows::Security::Credentials::UI::AuthenticationProtocol::Kerberos;
00098         }
00099         else if (protocolName->Equals("CredSsp"))
00100         {
00101             credPickerOptions->AuthenticationProtocol = Windows::Security::Credentials::UI::AuthenticationProtocol::CredSsp;
00102         }
00103         else if (protocolName->Equals("Basic"))
00104         {
00105             credPickerOptions->AuthenticationProtocol = Windows::Security::Credentials::UI::AuthenticationProtocol::Basic;
00106         }
00107         else if (protocolName->Equals("Digest"))
00108         {
00109             credPickerOptions->AuthenticationProtocol = Windows::Security::Credentials::UI::AuthenticationProtocol::Digest;
00110         }
00111         else if (protocolName->Equals("Custom"))
00112         {
00113             credPickerOptions->AuthenticationProtocol = Windows::Security::Credentials::UI::AuthenticationProtocol::Custom;
00114             credPickerOptions->CustomAuthenticationProtocol = CustomProtocol->Text;
00115         }
00116         else
00117         {
00118             MainPage::Current->NotifyUser("Unknown Protocol", NotifyType::ErrorMessage);
00119         }
00120     }
00121     if (SaveCheckboxSelection->SelectedItem != nullptr)
00122     {
00123         String^ checkboxState = ((ComboBoxItem^)SaveCheckboxSelection->SelectedItem)->Content->ToString();
00124         if (checkboxState->Equals("Hidden"))
00125         {
00126             credPickerOptions->CredentialSaveOption = Windows::Security::Credentials::UI::CredentialSaveOption::Hidden;
00127         }
00128         else if (checkboxState->Equals("Selected"))
00129         {
00130             credPickerOptions->CredentialSaveOption = Windows::Security::Credentials::UI::CredentialSaveOption::Selected;
00131         }
00132         else if (checkboxState->Equals("Unselected"))
00133         {
00134             credPickerOptions->CredentialSaveOption = Windows::Security::Credentials::UI::CredentialSaveOption::Unselected;
00135         }
00136         else
00137         {
00138             MainPage::Current->NotifyUser("Unknown Checkbox state", NotifyType::ErrorMessage);
00139         }
00140     }
00141     create_task(Windows::Security::Credentials::UI::CredentialPicker::PickAsync(credPickerOptions))
00142         .then([this](CredentialPickerResults^ credPickerResult)
00143     {
00144         SetResult(credPickerResult);
00145     });
00146
00147
00148 }
00149
00150 void Scenario3_CredentialPickerOptions::Protocol_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
00151 {
00152     ComboBox^ box = (ComboBox^)sender;
00153     if (ProtocolSelection == nullptr || ProtocolSelection->SelectedItem == nullptr || CustomProtocol == nullptr)
00154     {
00155         //return if this was triggered before all components are initialized
00156         return;
00157     }
00158
00159     String^ selectedProtocol = ProtocolSelection->SelectedItem->ToString();
00160
00161     if (selectedProtocol->Equals("Custom"))
00162     {
00163         CustomProtcolStackPanel->Visibility = Windows::UI::Xaml::Visibility::Visible;
00164     }
00165     else
00166     {
00167         CustomProtcolStackPanel->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00168         //Basic and Digest return plaintext passwords
00169         if (selectedProtocol->Equals("Basic"))
00170         {
00171             SetPasswordExplainVisibility(false);
00172         }
00173         else if (selectedProtocol->Equals("Digest"))
00174         {
00175             SetPasswordExplainVisibility(false);
00176         }
00177         else
00178         {
00179             SetPasswordExplainVisibility(true);
00180         }
00181     }
00182 }
Generated on Fri Nov 15 2024 22:19:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cppwinrt/Scenario3_SingleFolder.cpp Source File

  • FilePicker
  • cppwinrt

Scenario3_SingleFolder.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_SingleFolder.h"
00014 #include "Scenario3_SingleFolder.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Storage;
00019 using namespace Windows::Storage::AccessCache;
00020 using namespace Windows::Storage::Pickers;
00021 using namespace Windows::UI::Xaml;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario3_SingleFolder::Scenario3_SingleFolder()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     fire_and_forget Scenario3_SingleFolder::PickFolderButton_Click(IInspectable const&, RoutedEventArgs const&)
00031     {
00032         auto lifetime = get_strong();
00033
00034         // Clear previous returned folder name, if it exists, between iterations of this scenario
00035         OutputTextBlock().Text(L"");
00036
00037         FolderPicker folderPicker;
00038         folderPicker.SuggestedStartLocation(PickerLocationId::Desktop);
00039         folderPicker.FileTypeFilter().ReplaceAll({ L".docx",  L".xlsx", L".pptx" });
00040         StorageFolder folder = co_await folderPicker.PickSingleFolderAsync();
00041         if (folder != nullptr)
00042         {
00043             // The StorageFolder has read/write access to all contents in the picked folder (including other sub-folder contents).
00044             // See the FileAccess sample for code that obtains a StorageFile from a StorageFolder to read and write.
00045             StorageApplicationPermissions::FutureAccessList().AddOrReplace(L"PickedFolderToken", folder);
00046             OutputTextBlock().Text(L"Picked folder: " + folder.Name());
00047         }
00048         else
00049         {
00050             OutputTextBlock().Text(L"Operation cancelled.");
00051         }
00052     }
00053
00054 }
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HolographicTemplateAppMain::GamepadWithButtonState Member List

This is the complete list of members for HolographicTemplateAppMain::GamepadWithButtonState, including all inherited members.
buttonAWasPressedLastFrame | HolographicTemplateAppMain::GamepadWithButtonState |
gamepad | HolographicTemplateAppMain::GamepadWithButtonState |
GamepadWithButtonState(Windows.Gaming.Input.Gamepad gamepad, bool buttonAWasPressedLastFrame) | HolographicTemplateAppMain::GamepadWithButtonState | [inline]
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Conversation Member List

This is the complete list of members for Conversation, including all inherited members.
Conversation() | Conversation | [inline]
CreateMessages(uint count) | Conversation | [inline, private]
CreateRandomMessage() | Conversation | [inline, static]
fillerText | Conversation | [private, static]
HasMoreItems | Conversation |
LoadMoreItemsAsync(uint count) | Conversation | [inline]
messageCount | Conversation | [private]
rand | Conversation | [private, static]
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: KeyCredentialManager/cpp/pch.h Source File

  • KeyCredentialManager
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cppwinrt/SampleConfiguration.h Source File

  • PenHaptics
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017   std::map<hstring, uint16_t> const& WaveformNamesMap();
00018   Windows::Devices::Haptics::SimpleHapticsControllerFeedback FindSupportedFeedback(Windows::Devices::Haptics::SimpleHapticsController const& hapticsController, uint16_t waveform);
00019 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PipeEvents Member List

This is the complete list of members for PipeEvents, including all inherited members.
on_read | PipeEvents
on_write | PipeEvents
read_bytes | PipeEvents
total_pipe_bytes | PipeEvents
unread_buffer | PipeEvents
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Altimeter/cpp/SampleConfiguration.cpp Source File

  • Altimeter
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Data Events", "SDKTemplate.Scenario1_DataEvents" },
00021     { "Polling", "SDKTemplate.Scenario2_Polling" }
00022 };
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAuthenticationBroker/cs/Scenario2_Twitter.xaml.cs Source File

  • WebAuthenticationBroker
  • cs

Scenario2_Twitter.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Threading.Tasks;
00015 using Windows.Security.Authentication.Web;
00016 using Windows.Security.Cryptography;
00017 using Windows.Security.Cryptography.Core;
00018 using Windows.Storage.Streams;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.Web.Http;
00022 using Windows.Web.Http.Headers;
00023
00024 namespace WebAuthentication
00025 {
00026     public sealed partial class Scenario2_Twitter : Page
00027     {
00028         MainPage rootPage = MainPage.Current;
00029
00030         public Scenario2_Twitter()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         private async Task<String> SendDataAsync(String Url)
00036         {
00037             HttpClient httpClient = new HttpClient();
00038             HttpGetStringResult result = await httpClient.TryGetStringAsync(new Uri(Url));
00039             if (result.Succeeded)
00040             {
00041                 return result.Value;
00042             }
00043             else
00044             {
00045                 rootPage.NotifyUser("Error getting data from server." + result.ExtendedError.Message, NotifyType.StatusMessage);
00046                 return null;
00047             }
00048         }
00049
00050         private void OutputToken(String TokenUri)
00051         {
00052             TwitterReturnedToken.Text = TokenUri;
00053         }
00054
00055         private async void Launch_Click(object sender, RoutedEventArgs e)
00056         {
00057             if (TwitterClientID.Text == "")
00058             {
00059                 rootPage.NotifyUser("Please enter an Client ID.", NotifyType.StatusMessage);
00060             }
00061             else if (TwitterCallbackUrl.Text == "")
00062             {
00063                 rootPage.NotifyUser("Please enter an Callback URL.", NotifyType.StatusMessage);
00064             }
00065             else if (TwitterClientSecret.Text == "")
00066             {
00067                 rootPage.NotifyUser("Please enter an Client Secret.", NotifyType.StatusMessage);
00068             }
00069
00070             string oauth_token = await GetTwitterRequestTokenAsync(TwitterCallbackUrl.Text, TwitterClientID.Text);
00071             if (String.IsNullOrEmpty(oauth_token))
00072             {
00073                 rootPage.NotifyUser("Unable to obtain oauth token.", NotifyType.StatusMessage);
00074                 return;
00075             }
00076
00077             string TwitterUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth_token;
00078             System.Uri StartUri = new Uri(TwitterUrl);
00079             System.Uri EndUri = new Uri(TwitterCallbackUrl.Text);
00080
00081             WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, StartUri, EndUri);
00082             if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
00083             {
00084                 OutputToken(WebAuthenticationResult.ResponseData.ToString());
00085                 await GetTwitterUserNameAsync(WebAuthenticationResult.ResponseData.ToString());
00086             }
00087             else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
00088             {
00089                 OutputToken("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
00090             }
00091             else
00092             {
00093                 OutputToken("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
00094             }
00095         }
00096
00097         private async Task GetTwitterUserNameAsync(string webAuthResultResponseData)
00098         {
00099             // Acquiring a access_token first
00100             string responseData = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("oauth_token"));
00101             string request_token = null;
00102             string oauth_verifier = null;
00103             String[] keyValPairs = responseData.Split('&');
00104
00105             for (int i = 0; i < keyValPairs.Length; i++)
00106             {
00107                 String[] splits = keyValPairs[i].Split('=');
00108                 switch (splits[0])
00109                 {
00110                     case "oauth_token":
00111                         request_token = splits[1];
00112                         break;
00113                     case "oauth_verifier":
00114                         oauth_verifier = splits[1];
00115                         break;
00116                 }
00117             }
00118
00119             String TwitterUrl = "https://api.twitter.com/oauth/access_token";
00120
00121             string timeStamp = GetTimeStamp();
00122             string nonce = GetNonce();
00123
00124             String SigBaseStringParams = "oauth_consumer_key=" + TwitterClientID.Text;
00125             SigBaseStringParams += "&" + "oauth_nonce=" + nonce;
00126             SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
00127             SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp;
00128             SigBaseStringParams += "&" + "oauth_token=" + request_token;
00129             SigBaseStringParams += "&" + "oauth_version=1.0";
00130             String SigBaseString = "POST&";
00131             SigBaseString += Uri.EscapeDataString(TwitterUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);
00132
00133             String Signature = GetSignature(SigBaseString, TwitterClientSecret.Text);
00134
00135             HttpStringContent httpContent = new HttpStringContent("oauth_verifier=" + oauth_verifier, Windows.Storage.Streams.UnicodeEncoding.Utf8);
00136             httpContent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
00137             string authorizationHeaderParams = "oauth_consumer_key=\"" + TwitterClientID.Text + "\", oauth_nonce=\"" + nonce + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"" + Uri.EscapeDataString(Signature) + "\", oauth_timestamp=\"" + timeStamp + "\", oauth_token=\"" + Uri.EscapeDataString(request_token) + "\", oauth_version=\"1.0\"";
00138
00139             HttpClient httpClient = new HttpClient();
00140
00141             httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("OAuth", authorizationHeaderParams);
00142             HttpRequestResult result = await httpClient.TryPostAsync(new Uri(TwitterUrl), httpContent);
00143             if (result.Succeeded)
00144             {
00145                 string response = await result.ResponseMessage.Content.ReadAsStringAsync();
00146
00147                 String[] Tokens = response.Split('&');
00148                 string oauth_token_secret = null;
00149                 string access_token = null;
00150                 string screen_name = null;
00151
00152                 for (int i = 0; i < Tokens.Length; i++)
00153                 {
00154                     String[] splits = Tokens[i].Split('=');
00155                     switch (splits[0])
00156                     {
00157                         case "screen_name":
00158                             screen_name = splits[1];
00159                             break;
00160                         case "oauth_token":
00161                             access_token = splits[1];
00162                             break;
00163                         case "oauth_token_secret":
00164                             oauth_token_secret = splits[1];
00165                             break;
00166                     }
00167                 }
00168
00169                 if (access_token != null)
00170                 {
00171                     // Store access_token for futher use (e.g., account management).
00172                 }
00173
00174                 if (oauth_token_secret != null)
00175                 {
00176                     // Store oauth_token_secret for further use (e.g., account management).
00177                 }
00178                 if (screen_name != null)
00179                 {
00180                     rootPage.NotifyUser(screen_name + " is connected!", NotifyType.StatusMessage);
00181                 }
00182             }
00183         }
00184
00185         private async Task<string> GetTwitterRequestTokenAsync(string twitterCallbackUrl, string consumerKey)
00186         {
00187             // Acquiring a request token
00188             string TwitterUrl = "https://api.twitter.com/oauth/request_token";
00189
00190             string nonce = GetNonce();
00191             string timeStamp = GetTimeStamp();
00192             string SigBaseStringParams = "oauth_callback=" + Uri.EscapeDataString(twitterCallbackUrl);
00193             SigBaseStringParams += "&" + "oauth_consumer_key=" + consumerKey;
00194             SigBaseStringParams += "&" + "oauth_nonce=" + nonce;
00195             SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
00196             SigBaseStringParams += "&" + "oauth_timestamp=" + timeStamp;
00197             SigBaseStringParams += "&" + "oauth_version=1.0";
00198             string SigBaseString = "GET&";
00199             SigBaseString += Uri.EscapeDataString(TwitterUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);
00200             string Signature = GetSignature(SigBaseString, TwitterClientSecret.Text);
00201
00202             TwitterUrl += "?" + SigBaseStringParams + "&oauth_signature=" + Uri.EscapeDataString(Signature);
00203             HttpClient httpClient = new HttpClient();
00204             string request_token = null;
00205
00206             HttpGetStringResult result = await httpClient.TryGetStringAsync(new Uri(TwitterUrl));
00207             if (result.Succeeded)
00208             {
00209                 string oauth_token_secret = null;
00210                 string[] keyValPairs = result.Value.Split('&');
00211
00212                 for (int i = 0; i < keyValPairs.Length; i++)
00213                 {
00214                     string[] splits = keyValPairs[i].Split('=');
00215                     switch (splits[0])
00216                     {
00217                         case "oauth_token":
00218                             request_token = splits[1];
00219                             break;
00220                         case "oauth_token_secret":
00221                             oauth_token_secret = splits[1];
00222                             break;
00223                     }
00224                 }
00225             }
00226             return request_token;
00227         }
00228
00229         string GetNonce()
00230         {
00231             Random rand = new Random();
00232             int nonce = rand.Next(1000000000);
00233             return nonce.ToString();
00234         }
00235
00236         string GetTimeStamp()
00237         {
00238             TimeSpan SinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
00239             return Math.Round(SinceEpoch.TotalSeconds).ToString();
00240         }
00241
00242         string GetSignature(string sigBaseString, string consumerSecretKey)
00243         {
00244             IBuffer KeyMaterial = CryptographicBuffer.ConvertStringToBinary(consumerSecretKey + "&", BinaryStringEncoding.Utf8);
00245             MacAlgorithmProvider HmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
00246             CryptographicKey MacKey = HmacSha1Provider.CreateKey(KeyMaterial);
00247             IBuffer DataToBeSigned = CryptographicBuffer.ConvertStringToBinary(sigBaseString, BinaryStringEncoding.Utf8);
00248             IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned);
00249             string Signature = CryptographicBuffer.EncodeToBase64String(SignatureBuffer);
00250
00251             return Signature;
00252         }
00253     }
00254 }
Generated on Fri Nov 15 2024 22:21:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDeferLoadStrategy/cs/Scenarios/BasicDeferral.xaml.cs Source File

  • XamlDeferLoadStrategy
  • cs
  • Scenarios

BasicDeferral.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.IO;
00004 using System.Linq;
00005 using System.Runtime.InteropServices.WindowsRuntime;
00006 using Windows.Foundation;
00007 using Windows.Foundation.Collections;
00008 using Windows.UI.Xaml;
00009 using Windows.UI.Xaml.Controls;
00010 using Windows.UI.Xaml.Controls.Primitives;
00011 using Windows.UI.Xaml.Data;
00012 using Windows.UI.Xaml.Input;
00013 using Windows.UI.Xaml.Media;
00014 using Windows.UI.Xaml.Navigation;
00015 using Windows.UI.ViewManagement;
00016
00017 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00018
00019 namespace xDeferLoadStrategy
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class BasicDeferral : Page
00025     {
00026         public BasicDeferral()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         private void RealizeElements_Click(object sender, RoutedEventArgs e)
00032         {
00033             this.FindName("DeferredGrid"); //This will realize the deferred grid
00034         }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:22:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CSourceOperation Member List

This is the complete list of members for CSourceOperation, including all inherited members.
_cRef | CSourceOperation | [private]
_data | CSourceOperation | [private]
_opType | CSourceOperation | [private]
CSourceOperation(Type opType) | CSourceOperation |
GetData() const | CSourceOperation | [inline]
GetOperationType() const | CSourceOperation | [inline]
IFACEMETHOD_(ULONG, AddRef)() | CSourceOperation |
IFACEMETHOD_(ULONG, Release)() | CSourceOperation |
Operation_SetRate enum value | CSourceOperation |
Operation_Start enum value | CSourceOperation |
Operation_Stop enum value | CSourceOperation |
QueryInterface(REFIID riid, void **ppv) | CSourceOperation |
SetData(const PROPVARIANT &varData) | CSourceOperation |
Type enum name | CSourceOperation |
~CSourceOperation() | CSourceOperation | [virtual]
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DetailsPage Member List

This is the complete list of members for DetailsPage, including all inherited members.
DeleteItem(object sender, RoutedEventArgs e) | DetailsPage | [inline, private]
DetailsPage() | DetailsPage | [inline]
NavigateBackForWideState(bool useTransition) | DetailsPage | [inline, private]
OnBackRequested(object sender, BackRequestedEventArgs e) | DetailsPage | [inline, private]
OnLoaded(object sender, RoutedEventArgs e) | DetailsPage | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | DetailsPage | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | DetailsPage | [inline, protected]
OnUnloaded(object sender, RoutedEventArgs e) | DetailsPage | [inline, private]
OnWindowSizeChanged(object sender, WindowSizeChangedEventArgs e) | DetailsPage | [inline, private]
SelectedContact | DetailsPage | [private]
ShouldGoToWideState() | DetailsPage | [inline, private]
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ExtendedExecution/cpp/SampleConfiguration.cpp Source File

  • ExtendedExecution
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace Concurrency;
00017 using namespace Platform;
00018 using namespace SDKTemplate;
00019 using namespace Windows::Data::Xml::Dom;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::System::Threading;
00022 using namespace Windows::UI::Notifications;
00023
00024 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00025 {
00026     { "Unspecified Reason", "SDKTemplate.UnspecifiedReason" },
00027     { "Saving Data Reason", "SDKTemplate.SavingDataReason" },
00028     { "Location Tracking Reason", "SDKTemplate.LocationTrackingReason" },
00029     { "Using Multiple Tasks", "SDKTemplate.MultipleTasks" },
00030 };
00031
00032 ToastNotification^ MainPage::DisplayToast(String^ content)
00033 {
00034     String^ xml = "<toast activationType='foreground'>"
00035         "<visual>"
00036             "<binding template='ToastGeneric'>"
00037                 "<text>Extended Execution</text>"
00038             "</binding>"
00039         "</visual>"
00040     "</toast>";
00041
00042     XmlDocument^ doc = ref new XmlDocument();
00043     doc->LoadXml(xml);
00044
00045     auto binding = doc->SelectSingleNode("//binding");
00046
00047     auto el = doc->CreateElement("text");
00048     el->InnerText = content;
00049     binding->AppendChild(el); // Add content to notification
00050
00051     auto toast = ref new ToastNotification(doc);
00052
00053     ToastNotificationManager::CreateToastNotifier()->Show(toast); // Show the toast
00054
00055     return toast;
00056 }
00057
00058 TimeSpan Helpers::TimeSpanFromSeconds(int seconds)
00059 {
00060     TimeSpan timeSpan;
00061     timeSpan.Duration = seconds * 1000LL * 10000LL; // convert seconds to TimeSpan units
00062     return timeSpan;
00063 }
00064
00065 task<void> Helpers::DelayAsync(TimeSpan duration, Concurrency::cancellation_token cancel)
00066 {
00067     task_completion_event<void> tce;
00068     ThreadPoolTimer^ timer = ThreadPoolTimer::CreateTimer(ref new TimerElapsedHandler([tce](ThreadPoolTimer^)
00069     {
00070         tce.set();
00071     }), duration);
00072     return task<void>(tce, cancel);
00073 }
Generated on Fri Nov 15 2024 22:17:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cs/Scenario3_Add.xaml.cs Source File

  • Playlists
  • cs

Scenario3_Add.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Media.Playlists;
00015 using Windows.Storage;
00016 using Windows.Storage.Pickers;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario3_Add : Page
00024     {
00025         private MainPage rootPage = MainPage.Current;
00026         private Playlist playlist = null;
00027
00028         public Scenario3_Add()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         /// <summary>
00034         /// Loads a playlist picked by the user in the FilePicker
00035         /// </summary>
00036         /// <param name="sender"></param>
00037         /// <param name="e"></param>
00038         async private void PickPlaylistButton_Click(object sender, RoutedEventArgs e)
00039         {
00040             PickAudioButton.IsEnabled = false;
00041
00042             this.playlist = await rootPage.PickPlaylistAsync();
00043
00044             if (this.playlist != null)
00045             {
00046                 rootPage.NotifyUser("Playlist loaded.", NotifyType.StatusMessage);
00047             }
00048
00049             PickAudioButton.IsEnabled = (this.playlist != null);
00050
00051         }
00052
00053         /// <summary>
00054         /// Adds a file to the end of the playlist loaded in PickPlaylistButton_Click
00055         /// </summary>
00056         /// <param name="sender"></param>
00057         /// <param name="e"></param>
00058         async private void PickAudioButton_Click(object sender, RoutedEventArgs e)
00059         {
00060             FileOpenPicker picker = MainPage.CreateFilePicker(MainPage.audioExtensions);
00061             IReadOnlyList<StorageFile> files = await picker.PickMultipleFilesAsync();
00062
00063             if (files.Count > 0)
00064             {
00065                 foreach (StorageFile file in files)
00066                 {
00067                     this.playlist.Files.Add(file);
00068                 }
00069
00070                 if (await rootPage.TrySavePlaylistAsync(playlist))
00071                 {
00072                     rootPage.NotifyUser(files.Count + " files added to playlist.", NotifyType.StatusMessage);
00073                 }
00074             }
00075             else
00076             {
00077                 rootPage.NotifyUser("No files picked.", NotifyType.ErrorMessage);
00078             }
00079         }
00080     }
00081 }
Generated on Fri Nov 15 2024 22:20:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLOutOfProcessWinRTComponent/cpp/cpp/Scenario3_CustomException.xaml.h Source File

  • WRLOutOfProcessWinRTComponent
  • cpp
  • cpp

Scenario3_CustomException.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008 #include "Scenario3_CustomException.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     namespace WRLOutOfProcessWinRTComponent
00013     {
00014         public ref class CustomException sealed
00015         {
00016         public:
00017             CustomException();
00018
00019         private:
00020             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021         };
00022     }
00023 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlDocument/cs/Scenario2_MarkHotProducts.xaml.cs Source File

  • XmlDocument
  • cs

Scenario2_MarkHotProducts.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00019
00020 namespace Xml
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class MarkHotProducts : Page
00026     {
00027         private MainPage rootPage;
00028
00029         public MarkHotProducts()
00030         {
00031             this.InitializeComponent();
00032
00033             Scenario2Init();
00034         }
00035
00036         /// <summary>
00037         /// Invoked when this page is about to be displayed in a Frame.
00038         /// </summary>
00039         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00040         /// property is typically used to configure the page.</param>
00041         protected override void OnNavigatedTo(NavigationEventArgs e)
00042         {
00043             rootPage = MainPage.Current;
00044         }
00045
00046         /// <summary>
00047         /// This is the click handler for the 'Scenario2BtnDefault' button.
00048         /// This function will look up products and mark hot products.
00049         /// </summary>
00050         /// <param name="sender"></param>
00051         /// <param name="e"></param>
00052         private void Scenario2BtnDefault_Click(object sender, RoutedEventArgs e)
00053         {
00054             String xml;
00055             scenario2OriginalData.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xml);
00056
00057             var doc = new Windows.Data.Xml.Dom.XmlDocument();
00058             doc.LoadXml(xml);
00059
00060             // Mark 'hot' attribute to '1' if 'sell10days' is greater than 'InStore'
00061             var xpath = "/products/product[Sell10day>InStore]/@hot";
00062             var hotAttributes = doc.SelectNodes(xpath);
00063             for (uint index = 0; index < hotAttributes.Length; index++)
00064             {
00065                 hotAttributes.Item(index).NodeValue = "1";
00066             }
00067
00068             Scenario.RichEditBoxSetMsg(scenario2Result, doc.GetXml(), true);
00069             scenario2BtnSave.IsEnabled = true;  // enable Save button
00070         }
00071
00072         /// <summary>
00073         /// This is the click handler for the 'Scenario2BtnSave' button.
00074         /// This function is to save the new xml in which hot products are marked to a file.
00075         /// </summary>
00076         /// <param name="sender"></param>
00077         /// <param name="e"></param>
00078         private async void Scenario2BtnSave_Click(object sender, RoutedEventArgs e)
00079         {
00080             String xml;
00081             scenario2Result.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xml);
00082
00083             var doc = new Windows.Data.Xml.Dom.XmlDocument();
00084             doc.LoadXml(xml);
00085
00086             // save xml to a file
00087             var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("HotProducts.xml", Windows.Storage.CreationCollisionOption.GenerateUniqueName);
00088             await doc.SaveToFileAsync(file);
00089
00090             Scenario.RichEditBoxSetMsg(scenario2Result, "Save to \"" + file.Path + "\" successfully.", true);
00091
00092             scenario2BtnSave.IsEnabled = false;
00093         }
00094
00095         private async void Scenario2Init()
00096         {
00097             try
00098             {
00099                 Windows.Data.Xml.Dom.XmlDocument doc = await Scenario.LoadXmlFile("markHotProducts", "products.xml");
00100                 Scenario.RichEditBoxSetMsg(scenario2OriginalData, doc.GetXml(), true);
00101             }
00102             catch (Exception exp)
00103             {
00104                 Scenario.RichEditBoxSetError(scenario2Result, exp.Message);
00105                 rootPage.NotifyUser("Exception occured while loading xml file!", NotifyType.ErrorMessage);
00106             }
00107         }
00108     }
00109 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactCards/cs/Scenario3_Full.xaml.cs Source File

  • ContactCards
  • cs

Scenario3_Full.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.ApplicationModel.Contacts;
00013 using Windows.Foundation;
00014 using Windows.UI.ViewManagement;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario3_Full : Page
00022     {
00023         private MainPage rootPage = MainPage.Current;
00024
00025         public Scenario3_Full()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         private void ShowContactCard_Click(object sender, RoutedEventArgs e)
00031         {
00032             Contact contact = rootPage.CreateContactFromUserInput(EmailAddress, PhoneNumber);
00033             if (contact != null)
00034             {
00035                 // Try to share the screen half/half with the full contact card.
00036                 FullContactCardOptions options = new FullContactCardOptions();
00037                 options.DesiredRemainingView = ViewSizePreference.UseHalf;
00038
00039                 // Show the full contact card.
00040                 ContactManager.ShowFullContactCard(contact, options);
00041             }
00042         }
00043     }
00044 }
Generated on Fri Nov 15 2024 22:18:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Scenario1_TrackPosition.cpp Source File

  • Geolocation
  • cppwinrt

Scenario1_TrackPosition.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_TrackPosition.h"
00014 #include "Scenario1_TrackPosition.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Devices::Geolocation;
00019 using namespace winrt::Windows::Foundation;
00020 using namespace winrt::Windows::UI::Xaml;
00021 using namespace winrt::Windows::UI::Xaml::Navigation;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario1_TrackPosition::Scenario1_TrackPosition()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     void Scenario1_TrackPosition::OnNavigatedFrom(NavigationEventArgs const&)
00031     {
00032         if (m_geolocator != nullptr)
00033         {
00034             m_geolocator.PositionChanged(m_positionChangedToken);
00035             m_geolocator.StatusChanged(m_statusChangedToken);
00036             m_geolocator = nullptr;
00037         }
00038     }
00039
00040     fire_and_forget Scenario1_TrackPosition::StartTracking(IInspectable const&, RoutedEventArgs const&)
00041     {
00042         auto lifetime = get_strong();
00043
00044         // Request permission to access location
00045         auto accessStatus = co_await Geolocator::RequestAccessAsync();
00046
00047         switch (accessStatus)
00048         {
00049         case GeolocationAccessStatus::Allowed:
00050             // You should set MovementThreshold for distance-based tracking
00051             // or ReportInterval for periodic-based tracking before adding event
00052             // handlers. If none is set, a ReportInterval of 1 second is used
00053             // as a default and a position will be returned every 1 second.
00054             //
00055             // Value of 2000 milliseconds (2 seconds)
00056             // isn't a requirement, it is just an example.
00057             m_geolocator = Geolocator();
00058             m_geolocator.ReportInterval(2000);
00059
00060             // Subscribe to PositionChanged event to get updated tracking positions
00061             m_positionChangedToken = m_geolocator.PositionChanged({ get_weak(), &Scenario1_TrackPosition::OnPositionChanged });
00062
00063             // Subscribe to StatusChanged event to get updates of location status changes
00064             m_statusChangedToken = m_geolocator.StatusChanged({ get_weak(), &Scenario1_TrackPosition::OnStatusChanged });
00065
00066             m_rootPage.NotifyUser(L"Waiting for update...", NotifyType::StatusMessage);
00067             LocationDisabledMessage().Visibility(Visibility::Collapsed);
00068             StartTrackingButton().IsEnabled(false);
00069             StopTrackingButton().IsEnabled(true);
00070             break;
00071
00072         case GeolocationAccessStatus::Denied:
00073             m_rootPage.NotifyUser(L"Access to location is denied.", NotifyType::ErrorMessage);
00074             LocationDisabledMessage().Visibility(Visibility::Visible);
00075             break;
00076
00077         case GeolocationAccessStatus::Unspecified:
00078             m_rootPage.NotifyUser(L"Unspecificed error!", NotifyType::ErrorMessage);
00079             LocationDisabledMessage().Visibility(Visibility::Collapsed);
00080             break;
00081         }
00082     }
00083
00084     void Scenario1_TrackPosition::StopTracking(IInspectable const&, RoutedEventArgs const&)
00085     {
00086         m_geolocator.PositionChanged(m_positionChangedToken);
00087         m_geolocator.StatusChanged(m_statusChangedToken);
00088         m_geolocator = nullptr;
00089
00090         StartTrackingButton().IsEnabled(true);
00091         StopTrackingButton().IsEnabled(false);
00092
00093         // Clear status
00094         m_rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00095     }
00096
00097     // Event handler for PositionChanged events. It is raised when
00098     // a location is available for the tracking session specified.
00099     fire_and_forget Scenario1_TrackPosition::OnPositionChanged(Geolocator const&, PositionChangedEventArgs e)
00100     {
00101         auto lifetime = get_strong();
00102         co_await resume_foreground(Dispatcher());
00103         m_rootPage.NotifyUser(L"Location updated.", NotifyType::StatusMessage);
00104         UpdateLocationData(e.Position());
00105     }
00106
00107     // Event handler for StatusChanged events. It is raised when the
00108     // location status in the system changes.
00109     fire_and_forget Scenario1_TrackPosition::OnStatusChanged(Geolocator const&, StatusChangedEventArgs e)
00110     {
00111         auto lifetime = get_strong();
00112         co_await resume_foreground(Dispatcher());
00113
00114         // Show the location setting message only if status is disabled.
00115         LocationDisabledMessage().Visibility(Visibility::Collapsed);
00116
00117         switch (e.Status())
00118         {
00119         case PositionStatus::Ready:
00120             // Location platform is providing valid data.
00121             ScenarioOutput_Status().Text(L"Ready");
00122             m_rootPage.NotifyUser(L"Location platform is ready.", NotifyType::StatusMessage);
00123             break;
00124
00125         case PositionStatus::Initializing:
00126             // Location platform is attempting to acquire a fix.
00127             ScenarioOutput_Status().Text(L"Initializing");
00128             m_rootPage.NotifyUser(L"Location platform is attempting to obtain a position.", NotifyType::StatusMessage);
00129             break;
00130
00131         case PositionStatus::NoData:
00132             // Location platform could not obtain location data.
00133             ScenarioOutput_Status().Text(L"No data");
00134             m_rootPage.NotifyUser(L"Not able to determine the location.", NotifyType::ErrorMessage);
00135             break;
00136
00137         case PositionStatus::Disabled:
00138             // The permission to access location data is denied by the user or other policies.
00139             ScenarioOutput_Status().Text(L"Disabled");
00140             m_rootPage.NotifyUser(L"Access to location is denied.", NotifyType::ErrorMessage);
00141
00142             // Show message to the user to go to location settings
00143             LocationDisabledMessage().Visibility(Visibility::Visible);
00144
00145             // Clear cached location data if any
00146             UpdateLocationData(nullptr);
00147             break;
00148
00149         case PositionStatus::NotInitialized:
00150             // The location platform is not initialized. This indicates that the application
00151             // has not made a request for location data.
00152             ScenarioOutput_Status().Text(L"Not initialized");
00153             m_rootPage.NotifyUser(L"No request for location is made yet.", NotifyType::StatusMessage);
00154             break;
00155
00156         case PositionStatus::NotAvailable:
00157             // The location platform is not available on this version of the OS.
00158             ScenarioOutput_Status().Text(L"Not available");
00159             m_rootPage.NotifyUser(L"Location is not available on this version of the OS.", NotifyType::ErrorMessage);
00160             break;
00161
00162         default:
00163             ScenarioOutput_Status().Text(L"Unknown");
00164             m_rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00165             break;
00166         }
00167     }
00168
00169     // Updates the user interface with the Geoposition data provided
00170     void Scenario1_TrackPosition::UpdateLocationData(Geoposition const& position)
00171     {
00172         if (position == nullptr)
00173         {
00174             ScenarioOutput_Latitude().Text(L"No data");
00175             ScenarioOutput_Longitude().Text(L"No data");
00176             ScenarioOutput_Accuracy().Text(L"No data");
00177             ScenarioOutput_Source().Text(L"No data");
00178             ScenarioOutput_IsRemoteSource().Text(L"No data");
00179         }
00180         else
00181         {
00182             ScenarioOutput_Latitude().Text(to_hstring(position.Coordinate().Point().Position().Latitude));
00183             ScenarioOutput_Longitude().Text(to_hstring(position.Coordinate().Point().Position().Longitude));
00184             ScenarioOutput_Accuracy().Text(to_hstring(position.Coordinate().Accuracy()));
00185             ScenarioOutput_Source().Text(to_hstring(position.Coordinate().PositionSource()));
00186             ScenarioOutput_IsRemoteSource().Text(to_hstring(position.Coordinate().IsRemoteSource()));
00187         }
00188     }
00189 }
Generated on Fri Nov 15 2024 22:19:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/HttpFilters/HttpMeteredConnectionFilter.cpp Source File

  • HttpClient
  • HttpFilters

HttpMeteredConnectionFilter.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "HttpMeteredConnectionFilter.h"
00014 #include "HttpMeteredConnectionFilter.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace winrt::Windows::Foundation;
00018 using namespace winrt::Windows::Foundation::Collections;
00019 using namespace winrt::Windows::Networking::Connectivity;
00020 using namespace winrt::Windows::Web::Http;
00021 using namespace winrt::Windows::Web::Http::Filters;
00022
00023 namespace winrt::HttpFilters::implementation
00024 {
00025     HttpMeteredConnectionFilter::HttpMeteredConnectionFilter(IHttpFilter const& innerFilter) : m_innerFilter(innerFilter)
00026     {
00027         if (!m_innerFilter)
00028         {
00029             throw hresult_invalid_argument(L"innerFilter cannot be null.");
00030         }
00031     }
00032
00033     IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> HttpMeteredConnectionFilter::SendRequestAsync(HttpRequestMessage request)
00034     {
00035         auto lifetime = get_strong();
00036
00037         MeteredConnectionPriority priority = MeteredConnectionPriority::Low;
00038         auto value = request.Properties().TryLookup(MeteredConnectionPriorityPropertyNameLiteral).try_as<IPropertyValue>();
00039         if (value)
00040         {
00041             if (value.Type() == PropertyType::Double)
00042             {
00043                 // Numeric values in JavaScript are represented as doubles.
00044                 priority = static_cast<MeteredConnectionPriority>(value.GetDouble());
00045             }
00046             else
00047             {
00048                 priority = unbox_value_or(value, MeteredConnectionPriority::Low);
00049             }
00050         }
00051
00052         CheckPriority(priority);
00053
00054         return m_innerFilter.SendRequestAsync(request);
00055     }
00056
00057     void HttpMeteredConnectionFilter::CheckPriority(MeteredConnectionPriority priority)
00058     {
00059         MeteredConnectionBehavior behavior = GetBehavior();
00060
00061         switch (behavior)
00062         {
00063         case MeteredConnectionBehavior::Normal:
00064             // Under normal behavior all requests are allowed.
00065             return;
00066
00067         case MeteredConnectionBehavior::Conservative:
00068             // Under conservative behavior all requests except low priority requests are allowed.
00069             if (priority != MeteredConnectionPriority::Low)
00070             {
00071                 return;
00072             }
00073             break;
00074
00075         case MeteredConnectionBehavior::OptIn:
00076             // Under opt-in only high priority requests are allowed and only if user opted in.
00077             if (priority == MeteredConnectionPriority::High && OptIn())
00078             {
00079                 return;
00080             }
00081             break;
00082         }
00083
00084         // Everything else is not allowed.
00085         throw hresult_access_denied(L"The request priority is not allowed under the current connection behavior.");
00086     }
00087
00088     HttpMeteredConnectionFilter::MeteredConnectionBehavior HttpMeteredConnectionFilter::GetBehavior()
00089     {
00090         ConnectionProfile connectionProfile = NetworkInformation::GetInternetConnectionProfile();
00091
00092         if (connectionProfile == nullptr)
00093         {
00094             return MeteredConnectionBehavior::None;
00095         }
00096
00097         ConnectionCost connectionCost = connectionProfile.GetConnectionCost();
00098
00099         if (connectionCost.Roaming())
00100         {
00101             return MeteredConnectionBehavior::OptIn;
00102         }
00103
00104         NetworkCostType type = connectionCost.NetworkCostType();
00105         if (type == NetworkCostType::Unrestricted || type == NetworkCostType::Unknown)
00106         {
00107             return MeteredConnectionBehavior::Normal;
00108         }
00109
00110         else if (!connectionCost.OverDataLimit() && (type == NetworkCostType::Fixed || type == NetworkCostType::Variable))
00111         {
00112             return MeteredConnectionBehavior::Conservative;
00113         }
00114
00115         return MeteredConnectionBehavior::OptIn;
00116     }
00117
00118 }
Generated on Fri Nov 15 2024 22:20:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SecureStopViewModel Member List

This is the complete list of members for SecureStopViewModel, including all inherited members.
activePlayReadyHeader | SecureStopViewModel |
CmdGetPublisherCert | SecureStopViewModel |
CmdPlayMovie | SecureStopViewModel |
CmdRenewLicense | SecureStopViewModel |
CmdStopMovie | SecureStopViewModel |
GetPublisherCert(string publisherID, Action< byte[]> callback) | SecureStopViewModel | [inline, private]
licenseSession | SecureStopViewModel |
licenseUrl | SecureStopViewModel | [private]
Log(string message) | ViewModelBase | [inline, static]
MoviePath | SecureStopViewModel |
moviePath | SecureStopViewModel | [private]
OutputLog | ViewModelBase |
PlaybackEnabled | ViewModelBase |
PlayReadyInfo | SecureStopViewModel |
ProcessServiceRequest(IMediaProtectionServiceRequest serviceRequest) | SecureStopViewModel | [inline, private]
PropertyChanged | ViewModelBase |
ProtectionManager | ViewModelBase |
publisherCert | SecureStopViewModel | [private]
publisherID | SecureStopViewModel | [private]
RaisePropertyChanged([CallerMemberName] string propertyName="") | ViewModelBase | [inline, protected]
RenewActiveLicense() | SecureStopViewModel | [inline, private]
secureStopServiceUrl | SecureStopViewModel | [private]
SecureStopViewModel(MediaElement mediaElement) | SecureStopViewModel | [inline]
SendSecureStopRecords() | SecureStopViewModel | [inline, private]
serviceCompletionNotifier | SecureStopViewModel | [private]
ServiceRequested(MediaProtectionManager sender, ServiceRequestedEventArgs srEvent) | SecureStopViewModel | [inline, private]
SetPlaybackEnabled(bool enabled) | ViewModelBase | [inline]
Generated on Fri Nov 15 2024 22:24:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/SampleConfiguration.cpp Source File

  • SimpleInk
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019
00020 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00021 {
00022     { "Scenario 1", "SDKTemplate.Scenario1" },
00023     { "Scenario 2", "SDKTemplate.Scenario2" },
00024     { "Scenario 3", "SDKTemplate.Scenario3" },
00025     { "Scenario 4", "SDKTemplate.Scenario4" },
00026     { "Scenario 5", "SDKTemplate.Scenario5" },
00027     { "Scenario 6", "SDKTemplate.Scenario6" },
00028     { "Scenario 7", "SDKTemplate.Scenario7" },
00029     { "Scenario 8", "SDKTemplate.Scenario8" },
00030     { "Scenario 9", "SDKTemplate.Scenario9" },
00031     { "Scenario 10", "SDKTemplate.Scenario10" },
00032     { "Scenario 11", "SDKTemplate.Scenario11" },
00033     { "Scenario 12", "SDKTemplate.Scenario12" },
00034 };
00035
00036 void HelperFunctions::UpdateCanvasSize(FrameworkElement^ root, FrameworkElement^ output, FrameworkElement^ inkCanvas)
00037 {
00038     output->Width = root->ActualWidth;
00039     output->Height = root->ActualHeight / 2;
00040     inkCanvas->Width = root->ActualWidth;
00041     inkCanvas->Height = root->ActualHeight / 2;
00042 }
00043
00044
00045
Generated on Fri Nov 15 2024 22:17:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/BaseAttributes.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

BaseAttributes.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 namespace Microsoft { namespace Samples { namespace Common {
00011
00012     template <class TBase=IMFAttributes>
00013     class CBaseAttributes : public TBase
00014     {
00015     protected:
00016         // This version of the constructor does not initialize the
00017         // attribute store. The derived class must call Initialize() in
00018         // its own constructor.
00019         CBaseAttributes()
00020         {
00021         }
00022
00023         // This version of the constructor initializes the attribute
00024         // store, but the derived class must pass an HRESULT parameter
00025         // to the constructor.
00026
00027         CBaseAttributes(HRESULT &hr, UINT32 cInitialSize = 0)
00028         {
00029             hr = Initialize(cInitialSize);
00030         }
00031
00032         // The next version of the constructor uses a caller-provided
00033         // implementation of IMFAttributes.
00034
00035         // (Sometimes you want to delegate IMFAttributes calls to some
00036         // other object that implements IMFAttributes, rather than using
00037         // MFCreateAttributes.)
00038
00039         CBaseAttributes(HRESULT &hr, IUnknown *pUnk)
00040         {
00041             hr = Initialize(pUnk);
00042         }
00043
00044         virtual ~CBaseAttributes()
00045         {
00046         }
00047
00048         // Initializes the object by creating the standard Media Foundation attribute store.
00049         HRESULT Initialize(UINT32 cInitialSize = 0)
00050         {
00051             if (_spAttributes.Get() == nullptr)
00052             {
00053                 return MFCreateAttributes(&_spAttributes, cInitialSize);
00054             }
00055             else
00056             {
00057                 return S_OK;
00058             }
00059         }
00060
00061         // Initializes this object from a caller-provided attribute store.
00062         // pUnk: Pointer to an object that exposes IMFAttributes.
00063         HRESULT Initialize(IUnknown *pUnk)
00064         {
00065             if (_spAttributes)
00066             {
00067                 _spAttributes->Release();
00068                 _spAttributes = NULL;
00069             }
00070
00071
00072             return pUnk->QueryInterface(IID_PPV_ARGS(&_spAttributes));
00073         }
00074
00075     public:
00076
00077         // IMFAttributes methods
00078
00079         STDMETHODIMP GetItem(REFGUID guidKey, PROPVARIANT *pValue)
00080         {
00081             assert(_spAttributes);
00082             return _spAttributes->GetItem(guidKey, pValue);
00083         }
00084
00085         STDMETHODIMP GetItemType(REFGUID guidKey, MF_ATTRIBUTE_TYPE *pType)
00086         {
00087             assert(_spAttributes);
00088             return _spAttributes->GetItemType(guidKey, pType);
00089         }
00090
00091         STDMETHODIMP CompareItem(REFGUID guidKey, REFPROPVARIANT Value, BOOL *pbResult)
00092         {
00093             assert(_spAttributes);
00094             return _spAttributes->CompareItem(guidKey, Value, pbResult);
00095         }
00096
00097         STDMETHODIMP Compare(
00098             IMFAttributes *pTheirs,
00099             MF_ATTRIBUTES_MATCH_TYPE MatchType,
00100             BOOL *pbResult
00101             )
00102         {
00103             assert(_spAttributes);
00104             return _spAttributes->Compare(pTheirs, MatchType, pbResult);
00105         }
00106
00107         STDMETHODIMP GetUINT32(REFGUID guidKey, UINT32 *punValue)
00108         {
00109             assert(_spAttributes);
00110             return _spAttributes->GetUINT32(guidKey, punValue);
00111         }
00112
00113         STDMETHODIMP GetUINT64(REFGUID guidKey, UINT64 *punValue)
00114         {
00115             assert(_spAttributes);
00116             return _spAttributes->GetUINT64(guidKey, punValue);
00117         }
00118
00119         STDMETHODIMP GetDouble(REFGUID guidKey, double *pfValue)
00120         {
00121             assert(_spAttributes);
00122             return _spAttributes->GetDouble(guidKey, pfValue);
00123         }
00124
00125         STDMETHODIMP GetGUID(REFGUID guidKey, GUID *pguidValue)
00126         {
00127             assert(_spAttributes);
00128             return _spAttributes->GetGUID(guidKey, pguidValue);
00129         }
00130
00131         STDMETHODIMP GetStringLength(REFGUID guidKey, UINT32 *pcchLength)
00132         {
00133             assert(_spAttributes);
00134             return _spAttributes->GetStringLength(guidKey, pcchLength);
00135         }
00136
00137         STDMETHODIMP GetString(REFGUID guidKey, LPWSTR pwszValue, UINT32 cchBufSize, UINT32 *pcchLength)
00138         {
00139             assert(_spAttributes);
00140             return _spAttributes->GetString(guidKey, pwszValue, cchBufSize, pcchLength);
00141         }
00142
00143         STDMETHODIMP GetAllocatedString(REFGUID guidKey, LPWSTR *ppwszValue, UINT32 *pcchLength)
00144         {
00145             assert(_spAttributes);
00146             return _spAttributes->GetAllocatedString(guidKey, ppwszValue, pcchLength);
00147         }
00148
00149         STDMETHODIMP GetBlobSize(REFGUID guidKey, UINT32 *pcbBlobSize)
00150         {
00151             assert(_spAttributes);
00152             return _spAttributes->GetBlobSize(guidKey, pcbBlobSize);
00153         }
00154
00155         STDMETHODIMP GetBlob(REFGUID guidKey, UINT8 *pBuf, UINT32 cbBufSize, UINT32 *pcbBlobSize)
00156         {
00157             assert(_spAttributes);
00158             return _spAttributes->GetBlob(guidKey, pBuf, cbBufSize, pcbBlobSize);
00159         }
00160
00161         STDMETHODIMP GetAllocatedBlob(REFGUID guidKey, UINT8 **ppBuf, UINT32 *pcbSize)
00162         {
00163             assert(_spAttributes);
00164             return _spAttributes->GetAllocatedBlob(guidKey, ppBuf, pcbSize);
00165         }
00166
00167         STDMETHODIMP GetUnknown(REFGUID guidKey, REFIID riid, LPVOID *ppv)
00168         {
00169             assert(_spAttributes);
00170             return _spAttributes->GetUnknown(guidKey, riid, ppv);
00171         }
00172
00173         STDMETHODIMP SetItem(REFGUID guidKey, REFPROPVARIANT Value)
00174         {
00175             assert(_spAttributes);
00176             return _spAttributes->SetItem(guidKey, Value);
00177         }
00178
00179         STDMETHODIMP DeleteItem(REFGUID guidKey)
00180         {
00181             assert(_spAttributes);
00182             return _spAttributes->DeleteItem(guidKey);
00183         }
00184
00185         STDMETHODIMP DeleteAllItems()
00186         {
00187             assert(_spAttributes);
00188             return _spAttributes->DeleteAllItems();
00189         }
00190
00191         STDMETHODIMP SetUINT32(REFGUID guidKey, UINT32 unValue)
00192         {
00193             assert(_spAttributes);
00194             return _spAttributes->SetUINT32(guidKey, unValue);
00195         }
00196
00197         STDMETHODIMP SetUINT64(REFGUID guidKey,UINT64 unValue)
00198         {
00199             assert(_spAttributes);
00200             return _spAttributes->SetUINT64(guidKey, unValue);
00201         }
00202
00203         STDMETHODIMP SetDouble(REFGUID guidKey, double fValue)
00204         {
00205             assert(_spAttributes);
00206             return _spAttributes->SetDouble(guidKey, fValue);
00207         }
00208
00209         STDMETHODIMP SetGUID(REFGUID guidKey, REFGUID guidValue)
00210         {
00211             assert(_spAttributes);
00212             return _spAttributes->SetGUID(guidKey, guidValue);
00213         }
00214
00215         STDMETHODIMP SetString(REFGUID guidKey, LPCWSTR wszValue)
00216         {
00217             assert(_spAttributes);
00218             return _spAttributes->SetString(guidKey, wszValue);
00219         }
00220
00221         STDMETHODIMP SetBlob(REFGUID guidKey, const UINT8 *pBuf, UINT32 cbBufSize)
00222         {
00223             assert(_spAttributes);
00224             return _spAttributes->SetBlob(guidKey, pBuf, cbBufSize);
00225         }
00226
00227         STDMETHODIMP SetUnknown(REFGUID guidKey, IUnknown *pUnknown)
00228         {
00229             assert(_spAttributes);
00230             return _spAttributes->SetUnknown(guidKey, pUnknown);
00231         }
00232
00233         STDMETHODIMP LockStore()
00234         {
00235             assert(_spAttributes);
00236             return _spAttributes->LockStore();
00237         }
00238
00239         STDMETHODIMP UnlockStore()
00240         {
00241             assert(_spAttributes);
00242             return _spAttributes->UnlockStore();
00243         }
00244
00245         STDMETHODIMP GetCount(UINT32 *pcItems)
00246         {
00247             assert(_spAttributes);
00248             return _spAttributes->GetCount(pcItems);
00249         }
00250
00251         STDMETHODIMP GetItemByIndex(UINT32 unIndex, GUID *pguidKey, PROPVARIANT *pValue)
00252         {
00253             assert(_spAttributes);
00254             return _spAttributes->GetItemByIndex(unIndex, pguidKey, pValue);
00255         }
00256
00257         STDMETHODIMP CopyAllItems(IMFAttributes *pDest)
00258         {
00259             assert(_spAttributes);
00260             return _spAttributes->CopyAllItems(pDest);
00261         }
00262
00263         // Helper functions
00264
00265         HRESULT SerializeToStream(DWORD dwOptions, IStream *pStm)
00266             // dwOptions: Flags from MF_ATTRIBUTE_SERIALIZE_OPTIONS
00267         {
00268             assert(_spAttributes);
00269             return MFSerializeAttributesToStream(_spAttributes.Get(), dwOptions, pStm);
00270         }
00271
00272         HRESULT DeserializeFromStream(DWORD dwOptions, IStream *pStm)
00273         {
00274             assert(_spAttributes);
00275             return MFDeserializeAttributesFromStream(_spAttributes.Get(), dwOptions, pStm);
00276         }
00277
00278         // SerializeToBlob: Stores the attributes in a byte array.
00279         //
00280         // ppBuf: Receives a pointer to the byte array.
00281         // pcbSize: Receives the size of the byte array.
00282         //
00283         // The caller must free the array using CoTaskMemFree.
00284         HRESULT SerializeToBlob(UINT8 **ppBuffer, UINT *pcbSize)
00285         {
00286             assert(_spAttributes);
00287
00288             if (ppBuffer == NULL)
00289             {
00290                 return E_POINTER;
00291             }
00292             if (pcbSize == NULL)
00293             {
00294                 return E_POINTER;
00295             }
00296
00297             HRESULT hr = S_OK;
00298             UINT32 cbSize = 0;
00299             BYTE *pBuffer = NULL;
00300
00301             CHECK_HR(hr = MFGetAttributesAsBlobSize(_spAttributes.Get(), &cbSize));
00302
00303             pBuffer = (BYTE*)CoTaskMemAlloc(cbSize);
00304             if (pBuffer == NULL)
00305             {
00306                 CHECK_HR(hr = E_OUTOFMEMORY);
00307             }
00308
00309             CHECK_HR(hr = MFGetAttributesAsBlob(_spAttributes.Get(), pBuffer, cbSize));
00310
00311             *ppBuffer = pBuffer;
00312             *pcbSize = cbSize;
00313
00314     done:
00315             if (FAILED(hr))
00316             {
00317                 *ppBuffer = NULL;
00318                 *pcbSize = 0;
00319                 CoTaskMemFree(pBuffer);
00320             }
00321             return hr;
00322         }
00323
00324         HRESULT DeserializeFromBlob(const UINT8 *pBuffer, UINT cbSize)
00325         {
00326             assert(_spAttributes);
00327             return MFInitAttributesFromBlob(_spAttributes.Get(), pBuffer, cbSize);
00328         }
00329
00330         HRESULT GetRatio(REFGUID guidKey, UINT32 *pnNumerator, UINT32 *punDenominator)
00331         {
00332             assert(_spAttributes);
00333             return MFGetAttributeRatio(_spAttributes.Get(), guidKey, pnNumerator, punDenominator);
00334         }
00335
00336         HRESULT SetRatio(REFGUID guidKey, UINT32 unNumerator, UINT32 unDenominator)
00337         {
00338             assert(_spAttributes);
00339             return MFSetAttributeRatio(_spAttributes.Get(), guidKey, unNumerator, unDenominator);
00340         }
00341
00342         // Gets an attribute whose value represents the size of something (eg a video frame).
00343         HRESULT GetSize(REFGUID guidKey, UINT32 *punWidth, UINT32 *punHeight)
00344         {
00345             assert(_spAttributes);
00346             return MFGetAttributeSize(_spAttributes.Get(), guidKey, punWidth, punHeight);
00347         }
00348
00349         // Sets an attribute whose value represents the size of something (eg a video frame).
00350         HRESULT SetSize(REFGUID guidKey, UINT32 unWidth, UINT32 unHeight)
00351         {
00352             assert(_spAttributes);
00353             return MFSetAttributeSize (_spAttributes.Get(), guidKey, unWidth, unHeight);
00354         }
00355
00356     protected:
00357         ComPtr<IMFAttributes> _spAttributes;
00358     };
00359
00360 }}}
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FullScreenMode/cppwinrt/SampleConfiguration.h Source File

  • FullScreenMode
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDragAndDrop/cs/Scenario3_StartDragAsync.xaml.cs Source File

  • XamlDragAndDrop
  • cs

Scenario3_StartDragAsync.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.Collections.ObjectModel;
00013 using Windows.UI.Xaml.Controls;
00014 using System;
00015 using Windows.Storage;
00016 using Windows.UI.Xaml;
00017 using Windows.ApplicationModel.DataTransfer;
00018 using Windows.Foundation;
00019
00020 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00021
00022 namespace DragAndDropSampleManaged
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class Scenario3_StartDragAsync : Page
00028     {
00029         Random _rnd = new Random();
00030         // Collection of symbols to display and drag
00031         ObservableCollection<string> _symbols;
00032         // Is a round running
00033         bool _isActive;
00034         // Symbol to drag
00035         string _symbol;
00036         // Timer limiting the time allowed to drag the symbol to the right target
00037         DispatcherTimer _timer;
00038         // Keeping the Drag operation will allow to cancel it after it has started
00039         IAsyncOperation<DataPackageOperation> _dragOperation;
00040
00041         public Scenario3_StartDragAsync()
00042         {
00043             this.InitializeComponent();
00044             this.Loaded += Scenario3_StartDragAsync_Loaded;
00045         }
00046
00047         private async void Scenario3_StartDragAsync_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00048         {
00049             // Initialize the symbols from the Text file
00050             var uri = new Uri("ms-appx:///Assets/Symbols.txt", UriKind.RelativeOrAbsolute);
00051             var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
00052             var lines = await FileIO.ReadLinesAsync(file);
00053             _symbols = new ObservableCollection<string>(lines);
00054             DropGridView.ItemsSource = _symbols;
00055         }
00056
00057         /// <summary>
00058         /// Start button clicked: select a symbol, update the display
00059         /// and start the timer according to the difficulty level
00060         /// </summary>
00061         /// <param name="sender"></param>
00062         /// <param name="e"></param>
00063         private void StartButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00064         {
00065             if (!_isActive)
00066             {
00067                 int index = _rnd.Next(_symbols.Count);
00068                 _symbol = _symbols[index];
00069                 SourceTextBlock.Text = _symbol;
00070                 ResultTextBlock.Text = string.Empty;
00071                 _isActive = true;
00072
00073                 if (_timer == null)
00074                 {
00075                     _timer = new DispatcherTimer();
00076                     _timer.Tick += OnTick;
00077                 }
00078                 bool easy = (EasyRB.IsChecked != null) && EasyRB.IsChecked.Value;
00079                 _timer.Interval = TimeSpan.FromSeconds(easy ? 5.0 : 1.5);
00080                 _timer.Start();
00081                 StartButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00082                 SourceTextBlock.Visibility = Windows.UI.Xaml.Visibility.Visible;
00083             }
00084         }
00085
00086         /// <summary>
00087         ///  End of the timer: player lost and we might have to cancel the drag operation
00088         /// </summary>
00089         /// <param name="sender"></param>
00090         /// <param name="args"></param>
00091         private void OnTick(object sender, object args)
00092         {
00093             _timer.Stop();
00094             if (_dragOperation != null)
00095             {
00096                 // Cancel the drag operation: this is equivalent of the user pressing Escape
00097                 // or releasing the pointer on a non-target
00098                 // DropCompleted event would return DataPackageOperation.None as the result
00099                 _dragOperation.Cancel();
00100             }
00101             else
00102             {
00103                 // We test _isActive just in case the timer expired when we were handling the drop
00104                 if (_isActive)
00105                 {
00106                     EndRound(false);
00107                 }
00108             }
00109         }
00110
00111         /// <summary>
00112         /// If the pointer is moved and we are not yet dragging, start a drag operation
00113         /// using StartDragAsync, which will allow a later cancellation
00114         /// </summary>
00115         /// <param name="sender"></param>
00116         /// <param name="e"></param>
00117         private void SourceTextBlock_PointerMoved(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
00118         {
00119             if (_isActive && e.Pointer.IsInContact && (_dragOperation == null))
00120             {
00121                 _dragOperation = SourceTextBlock.StartDragAsync(e.GetCurrentPoint(SourceTextBlock));
00122                 _dragOperation.Completed = DragCompleted;
00123             }
00124         }
00125
00126         /// <summary>
00127         /// Update the user interface when the round is finished
00128         /// </summary>
00129         /// <param name="hasWon"></param>
00130         private void EndRound(bool hasWon)
00131         {
00132             _isActive = false;
00133             ResultTextBlock.Text = (hasWon ? "You win :-) !!" : "You lose :-( !!");
00134             StartButton.Visibility = Windows.UI.Xaml.Visibility.Visible;
00135             SourceTextBlock.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00136         }
00137
00138         /// <summary>
00139         /// Completion callback for the asynchronous call:
00140         /// it is called whether the drop succeeded, or the user released the pointer on a non-target
00141         /// or else we cancelled the operation from the timer's callback
00142         /// </summary>
00143         /// <param name="asyncInfo"></param>
00144         /// <param name="asyncStatus"></param>
00145         private void DragCompleted(IAsyncOperation<DataPackageOperation> asyncInfo, AsyncStatus asyncStatus)
00146         {
00147             _dragOperation = null;
00148             if (_timer != null) _timer.Stop();
00149             EndRound((asyncStatus == AsyncStatus.Completed) && (asyncInfo.GetResults() == DataPackageOperation.Copy));
00150         }
00151
00152         /// <summary>
00153         /// DragStarting is called even if we are starting the Drag Operation ourselved with StartDragAsync
00154         /// In this sample, we don't really need to handle it
00155         /// </summary>
00156         /// <param name="sender"></param>
00157         /// <param name="e"></param>
00158         private void SourceTextBlock_DragStarting(Windows.UI.Xaml.UIElement sender, Windows.UI.Xaml.DragStartingEventArgs e)
00159         {
00160             e.Data.RequestedOperation = DataPackageOperation.Copy;
00161             e.Data.SetText(_symbol);
00162         }
00163
00164         /// <summary>
00165         /// Check if the sender is a border AND has the dragged symbol
00166         /// </summary>
00167         /// <param name="sender"></param>
00168         /// <returns></returns>
00169         private bool IsSymbolTargetBorder(object sender)
00170         {
00171             var border = sender as Border;
00172             return (border != null) && (border.DataContext as string == _symbol);
00173         }
00174
00175         /// <summary>
00176         /// Entering a target: check if this will result in a win
00177         /// </summary>
00178         /// <param name="sender"></param>
00179         /// <param name="e"></param>
00180         private void DropBorder_DragEnter(object sender, Windows.UI.Xaml.DragEventArgs e)
00181         {
00182             bool win = (_dragOperation != null) && e.DataView.Contains(StandardDataFormats.Text) && IsSymbolTargetBorder(sender);
00183             e.AcceptedOperation = win ? DataPackageOperation.Copy : DataPackageOperation.None;
00184             e.DragUIOverride.IsCaptionVisible = false;
00185         }
00186
00187         /// <summary>
00188         /// Drop: check if this results in a win
00189         /// </summary>
00190         /// <param name="sender"></param>
00191         /// <param name="e"></param>
00192         private void DropBorder_Drop(object sender, Windows.UI.Xaml.DragEventArgs e)
00193         {
00194             bool win = (_dragOperation != null) && e.DataView.Contains(StandardDataFormats.Text) && IsSymbolTargetBorder(sender);
00195             e.AcceptedOperation = win ? DataPackageOperation.Copy : DataPackageOperation.None;
00196         }
00197     }
00198 }
Generated on Fri Nov 15 2024 22:22:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cs/Scenario5.xaml.cs Source File

  • SimpleInk
  • cs

Scenario5.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.Foundation;
00013 using Windows.UI.Core;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// This page shows the code to configure the intial state of the InkToolbar.
00021     /// </summary>
00022     public sealed partial class Scenario5 : Page
00023     {
00024         public Scenario5()
00025         {
00026             this.InitializeComponent();
00027
00028             // Initialize the InkCanvas
00029             inkCanvas.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Pen | CoreInputDeviceTypes.Touch;
00030         }
00031
00032         private void OnSizeChanged(object sender, SizeChangedEventArgs e)
00033         {
00034             HelperFunctions.UpdateCanvasSize(RootGrid, outputGrid, inkCanvas);
00035         }
00036    }
00037 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cpp/Scenario2_DeviceConnect.xaml.h Source File

  • CustomCapability
  • cpp

Scenario2_DeviceConnect.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "Scenario2_DeviceConnect.g.h"
00014
00015 namespace SDKTemplate
00016 {
00017     [Windows::Foundation::Metadata::WebHostHidden]
00018     public ref class DeviceConnect sealed
00019     {
00020     public:
00021         DeviceConnect();
00022
00023     protected:
00024         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00025
00026     private:
00027         MainPage^ rootPage = MainPage::Current;
00028
00029         void deviceConnectStart_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00030         void deviceConnectStop_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00031         void deviceConnectDevices_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00032
00033         void UpdateStartStopButtons(void);
00034
00035         Concurrency::task<void> OpenFx2DeviceAsync(Platform::String^ Id);
00036         void CloseFx2Device(void);
00037     };
00038 }
Generated on Fri Nov 15 2024 22:19:03 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmsSendAndReceive/cs/SmsSendAndReceive/SendTextMessage.xaml.cs Source File

  • SmsSendAndReceive
  • cs
  • SmsSendAndReceive

SendTextMessage.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using System;
00017 using System.Collections.Generic;
00018 using Windows.Devices.Sms;
00019
00020 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00021
00022 namespace SmsSendAndReceive
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class SendTextMessage : Page
00028     {
00029         private MainPage rootPage;
00030         private SmsDevice2 device;
00031
00032         public SendTextMessage()
00033         {
00034             this.InitializeComponent();
00035         }
00036
00037         protected override void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039             rootPage = MainPage.Current;
00040         }
00041
00042         private async void Send_Click(object sender, RoutedEventArgs e)
00043         {
00044             if (SendToText.Text == "")
00045             {
00046                 rootPage.NotifyUser("Please enter sender number", NotifyType.ErrorMessage);
00047                 return;
00048             }
00049
00050             if (SendMessageText.Text == "")
00051             {
00052                 rootPage.NotifyUser("Please enter message", NotifyType.ErrorMessage);
00053                 return;
00054             }
00055
00056             // If this is the first request, get the default SMS device. If this
00057             // is the first SMS device access, the user will be prompted to grant
00058             // access permission for this application.
00059             if (device == null)
00060             {
00061                 try
00062                 {
00063                     rootPage.NotifyUser("Getting default SMS device ...", NotifyType.StatusMessage);
00064                     device = SmsDevice2.GetDefault();
00065                 }
00066                 catch (Exception ex)
00067                 {
00068                     rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
00069                     return;
00070                 }
00071
00072             }
00073
00074             string msgStr = "";
00075             if (device != null)
00076             {
00077                 try
00078                 {
00079                     // Create a text message - set the entered destination number and message text.
00080                     SmsTextMessage2 msg = new SmsTextMessage2();
00081                     msg.To = SendToText.Text;
00082                     msg.Body = SendMessageText.Text;
00083
00084                     // Send the message asynchronously
00085                     rootPage.NotifyUser("Sending message ...", NotifyType.StatusMessage);
00086                     SmsSendMessageResult result = await device.SendMessageAndGetResultAsync(msg);
00087
00088                     if (result.IsSuccessful)
00089                     {
00090                         msgStr = "";
00091                         msgStr += "Text message sent, cellularClass: " + result.CellularClass.ToString();
00092                         IReadOnlyList<Int32> messageReferenceNumbers = result.MessageReferenceNumbers;
00093
00094                         for (int i = 0; i < messageReferenceNumbers.Count; i++)
00095                         {
00096                             msgStr += "\n\t\tMessageReferenceNumber[" + i.ToString() + "]: " + messageReferenceNumbers[i].ToString();
00097                         }
00098                         rootPage.NotifyUser(msgStr, NotifyType.StatusMessage);
00099                     }
00100                     else
00101                     {
00102                         msgStr = "";
00103                         msgStr += "ModemErrorCode: " + result.ModemErrorCode.ToString();
00104                         msgStr += "\nIsErrorTransient: " + result.IsErrorTransient.ToString();
00105                         if (result.ModemErrorCode == SmsModemErrorCode.MessagingNetworkError)
00106                         {
00107                             msgStr += "\n\tNetworkCauseCode: " + result.NetworkCauseCode.ToString();
00108
00109                             if (result.CellularClass == CellularClass.Cdma)
00110                             {
00111                                 msgStr += "\n\tTransportFailureCause: " + result.TransportFailureCause.ToString();
00112                             }
00113                             rootPage.NotifyUser(msgStr, NotifyType.ErrorMessage);
00114                         }
00115                     }
00116                 }
00117                 catch (Exception ex)
00118                 {
00119                     rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
00120                 }
00121             }
00122             else
00123             {
00124                 rootPage.NotifyUser("Failed to find SMS device", NotifyType.ErrorMessage);
00125             }
00126         }
00127     }
00128 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackButton/cs/Scenario1.xaml.cs Source File

  • BackButton
  • cs

Scenario1.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Core;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016
00017 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class Scenario1 : Page
00025     {
00026         private MainPage rootPage;
00027
00028         private static bool optedIn = false;
00029
00030         public Scenario1()
00031         {
00032             this.InitializeComponent();
00033
00034             // I want this page to be always cached so that we don't have to add logic to save/restore state for the checkbox.
00035             this.NavigationCacheMode = NavigationCacheMode.Required;
00036         }
00037
00038         protected override void OnNavigatedTo(NavigationEventArgs e)
00039         {
00040             rootPage = MainPage.Current;
00041         }
00042
00043         private void Button_Click(object sender, RoutedEventArgs e)
00044         {
00045             Frame rootFrame = Window.Current.Content as Frame;
00046
00047             // Navigate to the next page, with info in the parameters whether to enable the title bar UI or not.
00048             rootFrame.Navigate(typeof(SecondaryPage), optedIn);
00049         }
00050
00051         private void CheckBox_Toggle(object sender, RoutedEventArgs e)
00052         {
00053             optedIn = !optedIn;
00054         }
00055     }
00056 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IBread Member List

This is the complete list of members for IBread, including all inherited members.
Flavor | IBread
Flavor([out, retval] HSTRING *value) | IBread
Flavor([out, retval] HSTRING *value) | IBread
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cpp/Scenario4_OrientationChanged.xaml.cpp Source File

  • Accelerometer
  • cpp

Scenario4_OrientationChanged.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario4_OrientationChanged.xaml.cpp
00014 // Implementation of the Scenario4_OrientationChanged class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario4_OrientationChanged.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Graphics::Display;
00025 using namespace Windows::UI::Core;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::Devices::Sensors;
00030
00031 Scenario4_OrientationChanged::Scenario4_OrientationChanged()
00032 {
00033     InitializeComponent();
00034 }
00035
00036 void Scenario4_OrientationChanged::OnNavigatedTo(NavigationEventArgs^ e)
00037 {
00038     // Get two instances of the accelerometer:
00039     // One that returns the raw accelerometer data
00040     accelerometerOriginal = Accelerometer::GetDefault(rootPage->AccelerometerReadingType);
00041     // Other on which the 'ReadingTransform' is updated so that data returned aligns with the request transformation.
00042     accelerometerReadingTransform = Accelerometer::GetDefault(rootPage->AccelerometerReadingType);
00043
00044     if (accelerometerOriginal != nullptr && accelerometerReadingTransform != nullptr)
00045     {
00046         rootPage->NotifyUser(rootPage->AccelerometerReadingType.ToString() + " accelerometers ready", NotifyType::StatusMessage);
00047         ScenarioEnableButton->IsEnabled = true;
00048     }
00049     else
00050     {
00051         rootPage->NotifyUser(rootPage->AccelerometerReadingType.ToString() + " accelerometers not found", NotifyType::ErrorMessage);
00052     }
00053
00054     // Register for orientation change
00055     displayInformation = DisplayInformation::GetForCurrentView();
00056     orientationChangedToken = displayInformation->OrientationChanged += ref new Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation ^, Platform::Object ^>(this, &Scenario4_OrientationChanged::OnOrientationChanged);
00057 }
00058
00059 void Scenario4_OrientationChanged::OnNavigatedFrom(NavigationEventArgs^ e)
00060 {
00061     if (ScenarioDisableButton->IsEnabled)
00062     {
00063         ScenarioDisable();
00064     }
00065
00066     displayInformation->OrientationChanged -= orientationChangedToken;
00067 }
00068
00069
00070 /// <summary>
00071 /// Invoked on pressing 'Enable' button'.
00072 /// </summary>
00073 void Scenario4_OrientationChanged::ScenarioEnable()
00074 {
00075     // Establish the report interval
00076     accelerometerOriginal->ReportInterval = accelerometerReadingTransform->MinimumReportInterval;
00077     accelerometerReadingTransform->ReportInterval = accelerometerReadingTransform->MinimumReportInterval;
00078
00079     // Establish the ReadingTransform to align with the current display orientation, so
00080     // that the accelerometer data from 'accelerometerReadingTransform' will align with the
00081     // current display orientation
00082     accelerometerReadingTransform->ReadingTransform = displayInformation->CurrentOrientation;
00083
00084     visibilityToken = Window::Current->VisibilityChanged += ref new WindowVisibilityChangedEventHandler(this, &Scenario4_OrientationChanged::VisibilityChanged);
00085
00086     // Register for ReadingChanged event
00087     readingTokenOriginal = accelerometerOriginal->ReadingChanged += ref new TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^>(this, &Scenario4_OrientationChanged::ReadingChangedOriginal);
00088     readingTokenReadingTransform = accelerometerReadingTransform->ReadingChanged += ref new TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^>(this, &Scenario4_OrientationChanged::ReadingChangedReadingTransform);
00089
00090     ScenarioEnableButton->IsEnabled = false;
00091     ScenarioDisableButton->IsEnabled = true;
00092 }
00093
00094 /// <summary>
00095 /// Invoked on pressing 'Disable' button'.
00096 /// </summary>
00097 void Scenario4_OrientationChanged::ScenarioDisable()
00098 {
00099     Window::Current->VisibilityChanged -= visibilityToken;
00100     accelerometerOriginal->ReadingChanged -= readingTokenOriginal;
00101     accelerometerReadingTransform->ReadingChanged -= readingTokenReadingTransform;
00102
00103     // Restore the default report interval to release resources while the sensor is not in use
00104     accelerometerOriginal->ReportInterval = 0;
00105     accelerometerReadingTransform->ReportInterval = 0;
00106
00107     ScenarioEnableButton->IsEnabled = true;
00108     ScenarioDisableButton->IsEnabled = false;
00109 }
00110
00111 /// <summary>
00112 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00113 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00114 /// </summary>
00115 /// <param name="sender"></param>
00116 /// <param name="e">
00117 /// Event data that can be examined for the current visibility state.
00118 /// </param>
00119 void Scenario4_OrientationChanged::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00120 {
00121     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00122     if (ScenarioDisableButton->IsEnabled)
00123     {
00124         if (e->Visible)
00125         {
00126             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00127             readingTokenOriginal = accelerometerOriginal->ReadingChanged += ref new TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^>(this, &Scenario4_OrientationChanged::ReadingChangedOriginal);
00128             readingTokenReadingTransform = accelerometerReadingTransform->ReadingChanged += ref new TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^>(this, &Scenario4_OrientationChanged::ReadingChangedReadingTransform);
00129         }
00130         else
00131         {
00132             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00133             accelerometerOriginal->ReadingChanged -= readingTokenOriginal;
00134             accelerometerReadingTransform->ReadingChanged -= readingTokenReadingTransform;
00135         }
00136     }
00137 }
00138
00139
00140 /// <summary>
00141 /// This is the event handler for ReadingChanged event of the 'accelerometerOriginal' and should
00142 /// notify of the accelerometer reading changes.
00143 /// </summary>
00144 /// <param name="sender"></param>
00145 /// <param name="e">
00146 /// Event data represents the accelerometer reading in its original reference frame.
00147 /// </param>
00148 void Scenario4_OrientationChanged::ReadingChangedOriginal(Accelerometer^ sender, AccelerometerReadingChangedEventArgs^ e)
00149 {
00150     // We need to dispatch to the UI thread to display the output
00151     Dispatcher->RunAsync(
00152         CoreDispatcherPriority::Normal,
00153         ref new DispatchedHandler(
00154         [this, e]()
00155         {
00156             MainPage::SetReadingText(ScenarioOutputOriginal, e->Reading);
00157         },
00158         CallbackContext::Any
00159         )
00160         );
00161 }
00162
00163
00164 /// <summary>
00165 /// This is the event handler for ReadingChanged event of the 'accelerometerReadingTransform' and should
00166 /// notify of the accelerometer reading changes.
00167 /// </summary>
00168 /// <param name="sender"></param>
00169 /// <param name="e">
00170 /// Event data represents the accelerometer reading in the reference frame of the current
00171 // display orientation (as set to 'ReadingTransform' property of the sensor).
00172 /// </param>
00173 void Scenario4_OrientationChanged::ReadingChangedReadingTransform(Accelerometer^ sender, AccelerometerReadingChangedEventArgs^ e)
00174 {
00175     // We need to dispatch to the UI thread to display the output
00176     Dispatcher->RunAsync(
00177         CoreDispatcherPriority::Normal,
00178         ref new DispatchedHandler(
00179         [this, e]()
00180         {
00181             MainPage::SetReadingText(ScenarioOutputReadingTransform, e->Reading);
00182         },
00183         CallbackContext::Any
00184         )
00185         );
00186 }
00187
00188
00189 /// <summary>
00190 /// This is the event handler for OrientationChanged events. You would register for these notifications
00191 /// if sensor data needs to be transformed to align with the current display orientation.
00192 /// </summary>
00193 /// <param name="sender">
00194 /// DisplayInformation object from which the new Orientation can be determined
00195 /// </param>
00196 /// <param name="args"> </param>
00197 void Scenario4_OrientationChanged::OnOrientationChanged(Windows::Graphics::Display::DisplayInformation ^sender, Platform::Object ^args)
00198 {
00199     if (nullptr != accelerometerReadingTransform)
00200     {
00201         accelerometerReadingTransform->ReadingTransform = sender->CurrentOrientation;
00202     }
00203 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cpp/5-GestureRecognizer.xaml.cpp Source File

  • BasicInput
  • cpp

5-GestureRecognizer.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "5-GestureRecognizer.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::Devices::Input;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Input;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Controls::Primitives;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::UI::Xaml::Input;
00027 using namespace Windows::UI::Xaml::Media;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 Scenario5::Scenario5() : rootPage(SDKTemplate::MainPage::Current)
00031 {
00032     InitializeComponent();
00033
00034     InitOptions();
00035
00036     // Create a GestureRecognizer which will be used to process the manipulations
00037     // done on the rectangle
00038     recognizer = ref new GestureRecognizer();
00039
00040     // Create a ManipulationInputProcessor which will listen for events on the
00041     // rectangle, process them, and update the rectangle's position, size, and rotation
00042     manipulationProcessor = ref new ManipulationInputProcessor(recognizer, manipulateMe, mainCanvas);
00043 }
00044
00045 void Scenario5::InitOptions()
00046 {
00047     movementAxis->SelectedIndex = 0;
00048     InertiaSwitch->IsOn = true;
00049 }
00050
00051 void Scenario5::movementAxis_Changed(Platform::Object^ sender, SelectionChangedEventArgs^ e)
00052 {
00053     if (manipulationProcessor == nullptr)
00054     {
00055         return;
00056     }
00057
00058     ComboBox^ cb = dynamic_cast<ComboBox^>(sender);
00059     ComboBoxItem^ selectedItem = dynamic_cast<ComboBoxItem^>((cb)->SelectedItem);
00060
00061     auto selection = selectedItem->Content->ToString();
00062
00063     if (selection == L"X only")
00064     {
00065         manipulationProcessor->LockToXAxis();
00066     }
00067     else if (selection == L"Y only")
00068     {
00069         manipulationProcessor->LockToXAxis();
00070     }
00071     else
00072     {
00073         manipulationProcessor->MoveOnXAndYAxes();
00074     }
00075 }
00076
00077 void Scenario5::InertiaSwitch_Toggled(Platform::Object^ sender, RoutedEventArgs^ e)
00078 {
00079     if (manipulationProcessor == nullptr)
00080     {
00081         return;
00082     }
00083
00084     manipulationProcessor->UseInertia(InertiaSwitch->IsOn);
00085 }
00086
00087 void Scenario5::resetButton_Pressed(Platform::Object^ sender, RoutedEventArgs^ e)
00088 {
00089     InitOptions();
00090     manipulationProcessor->Reset();
00091 }
00092
00093 ManipulationInputProcessor::ManipulationInputProcessor(GestureRecognizer^ gestureRecognizer, UIElement^ target, UIElement^ referenceFrame)
00094     : recognizer(gestureRecognizer)
00095     , element(target)
00096     , reference(referenceFrame)
00097 {
00098     // Initialize the transforms that will be used to manipulate the shape
00099     InitializeTransforms();
00100
00101     InitializeTransforms();
00102
00103     // The GestureSettings property dictates what manipulation events the
00104     // Gesture Recognizer will listen to.  This will set it to a limited
00105     // subset of these events.
00106     recognizer->GestureSettings = GenerateDefaultSettings();
00107
00108     // Set up pointer event handlers. These receive input events that are used by the gesture recognizer->
00109     element->PointerPressed += ref new PointerEventHandler(this, &ManipulationInputProcessor::OnPointerPressed);
00110     element->PointerMoved += ref new PointerEventHandler(this, &ManipulationInputProcessor::OnPointerMoved);
00111     element->PointerReleased += ref new PointerEventHandler(this, &ManipulationInputProcessor::OnPointerReleased);
00112     element->PointerCanceled += ref new PointerEventHandler(this, &ManipulationInputProcessor::OnPointerCanceled);
00113
00114     // Set up event handlers to respond to gesture recognizer output
00115     recognizer->ManipulationStarted += ref new TypedEventHandler<GestureRecognizer^, ManipulationStartedEventArgs^>(this, &ManipulationInputProcessor::OnManipulationStarted);
00116     recognizer->ManipulationUpdated += ref new TypedEventHandler<GestureRecognizer^, ManipulationUpdatedEventArgs^>(this, &ManipulationInputProcessor::OnManipulationUpdated);
00117     recognizer->ManipulationCompleted += ref new TypedEventHandler<GestureRecognizer^, ManipulationCompletedEventArgs^>(this, &ManipulationInputProcessor::OnManipulationCompleted);
00118     recognizer->ManipulationInertiaStarting += ref new TypedEventHandler<GestureRecognizer^, ManipulationInertiaStartingEventArgs^>(this, &ManipulationInputProcessor::OnManipulationInertiaStarting);
00119 }
00120
00121 void ManipulationInputProcessor::InitializeTransforms()
00122 {
00123     cumulativeTransform = ref new TransformGroup();
00124     deltaTransform = ref new CompositeTransform();
00125     previousTransform = ref new MatrixTransform();
00126     previousTransform->Matrix = Matrix::Identity;
00127
00128     cumulativeTransform->Children->Append(previousTransform);
00129     cumulativeTransform->Children->Append(deltaTransform);
00130
00131     element->RenderTransform = cumulativeTransform;
00132 }
00133
00134 // Return the default GestureSettings for this sample
00135 GestureSettings ManipulationInputProcessor::GenerateDefaultSettings()
00136 {
00137     return GestureSettings::ManipulationTranslateX |
00138         GestureSettings::ManipulationTranslateY |
00139         GestureSettings::ManipulationRotate |
00140         GestureSettings::ManipulationTranslateInertia |
00141         GestureSettings::ManipulationRotateInertia;
00142 }
00143
00144 // Route the pointer pressed event to the gesture recognizer->
00145 // The points are in the reference frame of the canvas that contains the rectangle element->
00146 void ManipulationInputProcessor::OnPointerPressed(Platform::Object^ sender, PointerRoutedEventArgs^ args)
00147 {
00148     // Set the pointer capture to the element being interacted with so that only it
00149     // will fire pointer-related events
00150     element->CapturePointer(args->Pointer);
00151
00152     // Feed the current point into the gesture recognizer as a down event
00153     recognizer->ProcessDownEvent(args->GetCurrentPoint(reference));
00154 }
00155
00156 // Route the pointer moved event to the gesture recognizer->
00157 // The points are in the reference frame of the canvas that contains the rectangle element->
00158 void ManipulationInputProcessor::OnPointerMoved(Platform::Object^ sender, PointerRoutedEventArgs^ args)
00159 {
00160     // Feed the set of points into the gesture recognizer as a move event
00161     recognizer->ProcessMoveEvents(args->GetIntermediatePoints(reference));
00162 }
00163
00164 // Route the pointer released event to the gesture recognizer->
00165 // The points are in the reference frame of the canvas that contains the rectangle element->
00166 void ManipulationInputProcessor::OnPointerReleased(Platform::Object^ sender, PointerRoutedEventArgs^ args)
00167 {
00168     // Feed the current point into the gesture recognizer as an up event
00169     recognizer->ProcessUpEvent(args->GetCurrentPoint(reference));
00170
00171     // Release the pointer
00172     element->ReleasePointerCapture(args->Pointer);
00173 }
00174
00175 // Route the pointer canceled event to the gesture recognizer->
00176 // The points are in the reference frame of the canvas that contains the rectangle element->
00177 void ManipulationInputProcessor::OnPointerCanceled(Platform::Object^ sender, PointerRoutedEventArgs^ args)
00178 {
00179     recognizer->CompleteGesture();
00180     element->ReleasePointerCapture(args->Pointer);
00181 }
00182
00183 // When a manipulation begins, change the color of the Platform::Object^ to reflect
00184 // that a manipulation is in progress
00185 void ManipulationInputProcessor::OnManipulationStarted(GestureRecognizer^ sender, ManipulationStartedEventArgs^ e)
00186 {
00187     Border^ b = dynamic_cast<Border^>(element);
00188     b->Background = ref new SolidColorBrush(Windows::UI::Colors::DeepSkyBlue);
00189 }
00190
00191 // Process the change resulting from a manipulation
00192 void ManipulationInputProcessor::OnManipulationUpdated(GestureRecognizer^ sender, ManipulationUpdatedEventArgs^ e)
00193 {
00194     previousTransform->Matrix = cumulativeTransform->Value;
00195
00196     // Get the center point of the manipulation for rotation
00197     Point center = Point(e->Position.X, e->Position.Y);
00198     deltaTransform->CenterX = center.X;
00199     deltaTransform->CenterY = center.Y;
00200
00201     // Look at the Delta property of the ManipulationDeltaRoutedEventArgs to retrieve
00202     // the rotation, X, and Y changes
00203     deltaTransform->Rotation = e->Delta.Rotation;
00204     deltaTransform->TranslateX = e->Delta.Translation.X;
00205     deltaTransform->TranslateY = e->Delta.Translation.Y;
00206 }
00207
00208 // When a manipulation that's a result of inertia begins, change the color of the
00209 // the Platform::Object^ to reflect that inertia has taken over
00210 void ManipulationInputProcessor::OnManipulationInertiaStarting(GestureRecognizer^ sender, ManipulationInertiaStartingEventArgs^ e)
00211 {
00212     Border^ b = dynamic_cast<Border^>(element);
00213     b->Background = ref new SolidColorBrush(Windows::UI::Colors::RoyalBlue);
00214 }
00215
00216 // When a manipulation has finished, reset the color of the Platform::Object^
00217 void ManipulationInputProcessor::OnManipulationCompleted(GestureRecognizer^ sender, ManipulationCompletedEventArgs^ e)
00218 {
00219     Border^ b = dynamic_cast<Border^>(element);
00220     b->Background = ref new SolidColorBrush(Windows::UI::Colors::LightGray);
00221 }
00222
00223 // Modify the GestureSettings property to only allow movement on the X axis
00224 void ManipulationInputProcessor::LockToXAxis()
00225 {
00226     recognizer->CompleteGesture();
00227     auto mode = recognizer->GestureSettings;
00228     auto update = GestureSettings::ManipulationTranslateY | GestureSettings::ManipulationTranslateX;
00229     recognizer->GestureSettings = mode | update;
00230     mode = recognizer->GestureSettings;
00231     update = GestureSettings::ManipulationTranslateY;
00232     recognizer->GestureSettings = mode ^ update;
00233 }
00234
00235 // Modify the GestureSettings property to only allow movement on the Y axis
00236 void ManipulationInputProcessor::LockToYAxis()
00237 {
00238     recognizer->CompleteGesture();
00239     auto mode = recognizer->GestureSettings;
00240     auto update = GestureSettings::ManipulationTranslateY | GestureSettings::ManipulationTranslateX;
00241     recognizer->GestureSettings = mode | update;
00242     mode = recognizer->GestureSettings;
00243     update = GestureSettings::ManipulationTranslateX;
00244     recognizer->GestureSettings = mode ^ update;
00245 }
00246
00247 // Modify the GestureSettings property to allow movement on both the the X and Y axes
00248 void ManipulationInputProcessor::MoveOnXAndYAxes()
00249 {
00250     recognizer->CompleteGesture();
00251     auto mode = recognizer->GestureSettings;
00252     auto update = GestureSettings::ManipulationTranslateX | GestureSettings::ManipulationTranslateY;
00253     recognizer->GestureSettings = mode | update;
00254 }
00255
00256 // Modify the GestureSettings property to enable or disable inertia based on the passed-in value
00257 void ManipulationInputProcessor::UseInertia(bool inertia)
00258 {
00259     if (!inertia)
00260     {
00261         recognizer->CompleteGesture();
00262         auto mode = recognizer->GestureSettings;
00263         auto update = GestureSettings::ManipulationTranslateInertia | GestureSettings::ManipulationRotateInertia;
00264         recognizer->GestureSettings = mode ^ update;
00265     }
00266     else
00267     {
00268         recognizer->CompleteGesture();
00269         auto mode = recognizer->GestureSettings;
00270         auto update = GestureSettings::ManipulationTranslateInertia | GestureSettings::ManipulationRotateInertia;
00271         recognizer->GestureSettings = mode | update;
00272     }
00273 }
00274
00275 void ManipulationInputProcessor::Reset()
00276 {
00277     element->RenderTransform = nullptr;
00278     recognizer->CompleteGesture();
00279     InitializeTransforms();
00280     recognizer->GestureSettings = GenerateDefaultSettings();
00281 }
Generated on Fri Nov 15 2024 22:18:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cppwinrt/Scenario1_InkCanvasTactileFeedback.h Source File

  • PenHaptics
  • cppwinrt

Scenario1_InkCanvasTactileFeedback.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_InkCanvasTactileFeedback.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1_InkCanvasTactileFeedback : Scenario1_InkCanvasTactileFeedbackT<Scenario1_InkCanvasTactileFeedback>
00020     {
00021         Scenario1_InkCanvasTactileFeedback();
00022
00023         void OnSizeChanged(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::SizeChangedEventArgs const& e);
00024     };
00025 }
00026
00027 namespace winrt::SDKTemplate::factory_implementation
00028 {
00029     struct Scenario1_InkCanvasTactileFeedback : Scenario1_InkCanvasTactileFeedbackT<Scenario1_InkCanvasTactileFeedback, implementation::Scenario1_InkCanvasTactileFeedback>
00030     {
00031     };
00032 }
Generated on Fri Nov 15 2024 22:20:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cs/Scenario_ListConstraint.xaml.cs Source File

  • SpeechRecognitionAndSynthesis
  • cs

Scenario_ListConstraint.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Linq;
00016 using System.Threading;
00017 using System.Threading.Tasks;
00018 using Windows.ApplicationModel.Resources;
00019 using Windows.ApplicationModel.Resources.Core;
00020 using Windows.Foundation;
00021 using Windows.Globalization;
00022 using Windows.Media.SpeechRecognition;
00023 using Windows.UI.Core;
00024 using Windows.UI.Xaml;
00025 using Windows.UI.Xaml.Controls;
00026 using Windows.UI.Xaml.Navigation;
00027
00028 namespace SDKTemplate
00029 {
00030     public sealed partial class Scenario_ListConstraint : Page
00031     {
00032         /// <summary>
00033         /// This HResult represents the scenario where a user is prompted to allow in-app speech, but
00034         /// declines. This should only happen on a Phone device, where speech is enabled for the entire device,
00035         /// not per-app.
00036         /// </summary>
00037         private static uint HResultPrivacyStatementDeclined = 0x80045509;
00038
00039         /// <summary>
00040         /// the HResult 0x8004503a typically represents the case where a recognizer for a particular language cannot
00041         /// be found. This may occur if the language is installed, but the speech pack for that language is not.
00042         /// See Settings -> Time & Language -> Region & Language -> *Language* -> Options -> Speech Language Options.
00043         /// </summary>
00044         private static uint HResultRecognizerNotFound = 0x8004503a;
00045
00046         private SpeechRecognizer speechRecognizer;
00047         private ResourceContext speechContext;
00048         private ResourceMap speechResourceMap;
00049         private bool isPopulatingLanguages = false;
00050         private IAsyncOperation<SpeechRecognitionResult> recognitionOperation;
00051
00052         public Scenario_ListConstraint()
00053         {
00054             InitializeComponent();
00055         }
00056
00057         /// <summary>
00058         /// When activating the scenario, ensure we have permission from the user to access their microphone, and
00059         /// provide an appropriate path for the user to enable access to the microphone if they haven't
00060         /// given explicit permission for it.
00061         /// </summary>
00062         /// <param name="e">The navigation event details</param>
00063         protected async override void OnNavigatedTo(NavigationEventArgs e)
00064         {
00065             bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
00066             if (permissionGained)
00067             {
00068                 // Enable the recognition buttons.
00069                 btnRecognizeWithUI.IsEnabled = true;
00070                 btnRecognizeWithoutUI.IsEnabled = true;
00071
00072                 Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
00073                 string langTag = speechLanguage.LanguageTag;
00074                 speechContext = ResourceContext.GetForCurrentView();
00075                 speechContext.Languages = new string[] { langTag };
00076
00077                 speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");
00078
00079                 PopulateLanguageDropdown();
00080                 await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
00081             }
00082             else
00083             {
00084                 resultTextBlock.Visibility = Visibility.Visible;
00085                 resultTextBlock.Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
00086                 btnRecognizeWithUI.IsEnabled = false;
00087                 btnRecognizeWithoutUI.IsEnabled = false;
00088                 cbLanguageSelection.IsEnabled = false;
00089             }
00090         }
00091
00092         /// <summary>
00093         /// Look up the supported languages for this speech recognition scenario,
00094         /// that are installed on this machine, and populate a dropdown with a list.
00095         /// </summary>
00096         private void PopulateLanguageDropdown()
00097         {
00098             // disable the callback so we don't accidentally trigger initialization of the recognizer
00099             // while initialization is already in progress.
00100             isPopulatingLanguages = true;
00101
00102             Language defaultLanguage = SpeechRecognizer.SystemSpeechLanguage;
00103             IEnumerable<Language> supportedLanguages = SpeechRecognizer.SupportedGrammarLanguages;
00104             foreach(Language lang in supportedLanguages)
00105             {
00106                 ComboBoxItem item = new ComboBoxItem();
00107                 item.Tag = lang;
00108                 item.Content = lang.DisplayName;
00109
00110                 cbLanguageSelection.Items.Add(item);
00111                 if(lang.LanguageTag == defaultLanguage.LanguageTag)
00112                 {
00113                     item.IsSelected = true;
00114                     cbLanguageSelection.SelectedItem = item;
00115                 }
00116             }
00117             isPopulatingLanguages = false;
00118         }
00119
00120         /// <summary>
00121         /// When a user changes the speech recognition language, trigger re-initialization of the
00122         /// speech engine with that language, and change any speech-specific UI assets.
00123         /// </summary>
00124         /// <param name="sender">Ignored</param>
00125         /// <param name="e">Ignored</param>
00126         private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
00127         {
00128             if (isPopulatingLanguages)
00129             {
00130                 return;
00131             }
00132
00133             ComboBoxItem item = (ComboBoxItem)(cbLanguageSelection.SelectedItem);
00134             Language newLanguage = (Language)item.Tag;
00135             if (speechRecognizer != null)
00136             {
00137                 if (speechRecognizer.CurrentLanguage == newLanguage)
00138                 {
00139                     return;
00140                 }
00141             }
00142
00143             // trigger cleanup and re-initialization of speech.
00144             try
00145             {
00146                 // update the context for resource lookup
00147                 speechContext.Languages = new string[] { newLanguage.LanguageTag };
00148
00149                 await InitializeRecognizer(newLanguage);
00150             }
00151             catch (Exception exception)
00152             {
00153                 var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
00154                 await messageDialog.ShowAsync();
00155             }
00156         }
00157
00158         /// <summary>
00159         /// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks,
00160         /// dipose the speech recognizer, and clean up to ensure the scenario is not still attempting to recognize
00161         /// speech while not in view.
00162         /// </summary>
00163         /// <param name="e">Details about the navigation event</param>
00164         protected override void OnNavigatedFrom(NavigationEventArgs e)
00165         {
00166             base.OnNavigatedFrom(e);
00167             if (speechRecognizer != null)
00168             {
00169                 if (speechRecognizer.State != SpeechRecognizerState.Idle)
00170                 {
00171                     if (recognitionOperation != null)
00172                     {
00173                         recognitionOperation.Cancel();
00174                         recognitionOperation = null;
00175                     }
00176                 }
00177
00178                 speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
00179
00180                 this.speechRecognizer.Dispose();
00181                 this.speechRecognizer = null;
00182             }
00183         }
00184
00185         /// <summary>
00186         /// Initialize Speech Recognizer and compile constraints.
00187         /// </summary>
00188         /// <param name="recognizerLanguage">Language to use for the speech recognizer</param>
00189         /// <returns>Awaitable task.</returns>
00190         private async Task InitializeRecognizer(Language recognizerLanguage)
00191         {
00192             if(speechRecognizer != null)
00193             {
00194                 // cleanup prior to re-initializing this scenario.
00195                 speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
00196
00197                 this.speechRecognizer.Dispose();
00198                 this.speechRecognizer = null;
00199             }
00200             try
00201             {
00202                 // Create an instance of SpeechRecognizer.
00203                 speechRecognizer = new SpeechRecognizer(recognizerLanguage);
00204
00205                 // Provide feedback to the user about the state of the recognizer.
00206                 speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
00207
00208                 // Add a list constraint to the recognizer.
00209                 speechRecognizer.Constraints.Add(
00210                     new SpeechRecognitionListConstraint(
00211                         new List<string>()
00212                         {
00213                         speechResourceMap.GetValue("ListGrammarGoHome", speechContext).ValueAsString
00214                         }, "Home"));
00215                 speechRecognizer.Constraints.Add(
00216                     new SpeechRecognitionListConstraint(
00217                         new List<string>()
00218                         {
00219                         speechResourceMap.GetValue("ListGrammarGoToContosoStudio", speechContext).ValueAsString
00220                         }, "GoToContosoStudio"));
00221                 speechRecognizer.Constraints.Add(
00222                     new SpeechRecognitionListConstraint(
00223                         new List<string>()
00224                         {
00225                         speechResourceMap.GetValue("ListGrammarShowMessage", speechContext).ValueAsString,
00226                         speechResourceMap.GetValue("ListGrammarOpenMessage", speechContext).ValueAsString
00227                         }, "Message"));
00228                 speechRecognizer.Constraints.Add(
00229                     new SpeechRecognitionListConstraint(
00230                         new List<string>()
00231                         {
00232                         speechResourceMap.GetValue("ListGrammarSendEmail", speechContext).ValueAsString,
00233                         speechResourceMap.GetValue("ListGrammarCreateEmail", speechContext).ValueAsString
00234                         }, "Email"));
00235                 speechRecognizer.Constraints.Add(
00236                     new SpeechRecognitionListConstraint(
00237                         new List<string>()
00238                         {
00239                         speechResourceMap.GetValue("ListGrammarCallNitaFarley", speechContext).ValueAsString,
00240                         speechResourceMap.GetValue("ListGrammarCallNita", speechContext).ValueAsString
00241                         }, "CallNita"));
00242                 speechRecognizer.Constraints.Add(
00243                     new SpeechRecognitionListConstraint(
00244                         new List<string>()
00245                         {
00246                         speechResourceMap.GetValue("ListGrammarCallWayneSigmon", speechContext).ValueAsString,
00247                         speechResourceMap.GetValue("ListGrammarCallWayne", speechContext).ValueAsString
00248                         }, "CallWayne"));
00249
00250                 // RecognizeWithUIAsync allows developers to customize the prompts.
00251                 string uiOptionsText = string.Format("Try saying '{0}', '{1}' or '{2}'",
00252                     speechResourceMap.GetValue("ListGrammarGoHome", speechContext).ValueAsString,
00253                     speechResourceMap.GetValue("ListGrammarGoToContosoStudio", speechContext).ValueAsString,
00254                     speechResourceMap.GetValue("ListGrammarShowMessage", speechContext).ValueAsString);
00255                 speechRecognizer.UIOptions.ExampleText = uiOptionsText;
00256                 helpTextBlock.Text = string.Format("{0}\n{1}",
00257                     speechResourceMap.GetValue("ListGrammarHelpText", speechContext).ValueAsString,
00258                     uiOptionsText);
00259
00260                 // Compile the constraint.
00261                 SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync();
00262
00263                 // Check to make sure that the constraints were in a proper format and the recognizer was able to compile it.
00264                 if (compilationResult.Status != SpeechRecognitionResultStatus.Success)
00265                 {
00266                     // Disable the recognition buttons.
00267                     btnRecognizeWithUI.IsEnabled = false;
00268                     btnRecognizeWithoutUI.IsEnabled = false;
00269
00270                     // Let the user know that the grammar didn't compile properly.
00271                     resultTextBlock.Visibility = Visibility.Visible;
00272                     resultTextBlock.Text = "Unable to compile grammar.";
00273                 }
00274                 else
00275                 {
00276                     btnRecognizeWithUI.IsEnabled = true;
00277                     btnRecognizeWithoutUI.IsEnabled = true;
00278
00279                     resultTextBlock.Visibility = Visibility.Collapsed;
00280                 }
00281             }
00282             catch(Exception ex)
00283             {
00284                 if((uint)ex.HResult == HResultRecognizerNotFound)
00285                 {
00286                     btnRecognizeWithUI.IsEnabled = false;
00287                     btnRecognizeWithoutUI.IsEnabled = false;
00288
00289                     resultTextBlock.Visibility = Visibility.Visible;
00290                     resultTextBlock.Text = "Speech Language pack for selected language not installed.";
00291                 }
00292                 else
00293                 {
00294                     var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
00295                     await messageDialog.ShowAsync();
00296                 }
00297             }
00298         }
00299
00300         /// <summary>
00301         /// Handle SpeechRecognizer state changed events by updating a UI component.
00302         /// </summary>
00303         /// <param name="sender">Speech recognizer that generated this status event</param>
00304         /// <param name="args">The recognizer's status</param>
00305         private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args)
00306         {
00307             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00308             {
00309                 MainPage.Current.NotifyUser("Speech recognizer state: " + args.State.ToString(), NotifyType.StatusMessage);
00310             });
00311         }
00312
00313         /// <summary>
00314         /// Uses the recognizer constructed earlier to listen for speech from the user before displaying
00315         /// it back on the screen. Uses the built-in speech recognition UI.
00316         /// </summary>
00317         /// <param name="sender">Button that triggered this event</param>
00318         /// <param name="e">State information about the routed event</param>
00319         private async void RecognizeWithUIListConstraint_Click(object sender, RoutedEventArgs e)
00320         {
00321             heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;
00322
00323             // Start recognition.
00324             try
00325             {
00326                 recognitionOperation = speechRecognizer.RecognizeWithUIAsync();
00327
00328                 SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
00329                 // If successful, display the recognition result.
00330                 if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
00331                 {
00332                     string tag = "unknown";
00333                     if(speechRecognitionResult.Constraint != null)
00334                     {
00335                         // Only attempt to retreive the tag if we didn't hit the garbage rule.
00336                         tag = speechRecognitionResult.Constraint.Tag;
00337                     }
00338
00339                     heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible;
00340                     resultTextBlock.Text = string.Format("Heard: '{0}', (Tag: '{1}', Confidence: {2})", speechRecognitionResult.Text, tag, speechRecognitionResult.Confidence.ToString());
00341                 }
00342                 else
00343                 {
00344                     resultTextBlock.Visibility = Visibility.Visible;
00345                     resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString() );
00346                 }
00347             }
00348             catch (TaskCanceledException exception)
00349             {
00350                 // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
00351                 // processing speech. Since this happens here when we navigate out of the scenario, don't try to
00352                 // show a message dialog for this exception.
00353                 System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
00354                 System.Diagnostics.Debug.WriteLine(exception.ToString());
00355             }
00356             catch (Exception exception)
00357             {
00358                 // Handle the speech privacy policy error.
00359                 if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
00360                 {
00361                     resultTextBlock.Visibility = Visibility.Visible;
00362                     resultTextBlock.Text = "The privacy statement was declined.";
00363                 }
00364                 else
00365                 {
00366                     var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
00367                     await messageDialog.ShowAsync();
00368                 }
00369             }
00370         }
00371
00372         /// <summary>
00373         /// Uses the recognizer constructed earlier to listen for speech from the user before displaying
00374         /// it back on the screen. Uses developer-provided UI for user feedback.
00375         /// </summary>
00376         /// <param name="sender">Button that triggered this event</param>
00377         /// <param name="e">State information about the routed event</param>
00378         private async void RecognizeWithoutUIListConstraint_Click(object sender, RoutedEventArgs e)
00379         {
00380             heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed;
00381
00382             // Disable the UI while recognition is occurring, and provide feedback to the user about current state.
00383             btnRecognizeWithUI.IsEnabled = false;
00384             btnRecognizeWithoutUI.IsEnabled = false;
00385             cbLanguageSelection.IsEnabled = false;
00386             listenWithoutUIButtonText.Text = " listening for speech...";
00387
00388             // Start recognition.
00389             try
00390             {
00391                 // Save the recognition operation so we can cancel it (as it does not provide a blocking
00392                 // UI, unlike RecognizeWithAsync()
00393                 recognitionOperation = speechRecognizer.RecognizeAsync();
00394
00395                 SpeechRecognitionResult speechRecognitionResult = await recognitionOperation;
00396
00397                 // If successful, display the recognition result. A cancelled task should do nothing.
00398                 if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success)
00399                 {
00400                     string tag = "unknown";
00401                     if (speechRecognitionResult.Constraint != null)
00402                     {
00403                         // Only attempt to retreive the tag if we didn't hit the garbage rule.
00404                         tag = speechRecognitionResult.Constraint.Tag;
00405                     }
00406
00407                     heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible;
00408                     resultTextBlock.Text = string.Format("Heard: '{0}', (Tag: '{1}', Confidence: {2})", speechRecognitionResult.Text, tag, speechRecognitionResult.Confidence.ToString());
00409                 }
00410                 else
00411                 {
00412                     resultTextBlock.Visibility = Visibility.Visible;
00413                     resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString());
00414                 }
00415             }
00416             catch (TaskCanceledException exception)
00417             {
00418                 // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively
00419                 // processing speech. Since this happens here when we navigate out of the scenario, don't try to
00420                 // show a message dialog for this exception.
00421                 System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):");
00422                 System.Diagnostics.Debug.WriteLine(exception.ToString());
00423             }
00424             catch (Exception exception)
00425             {
00426                 // Handle the speech privacy policy error.
00427                 if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
00428                 {
00429                     resultTextBlock.Visibility = Visibility.Visible;
00430                     resultTextBlock.Text = "The privacy statement was declined.";
00431                 }
00432                 else
00433                 {
00434                     var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
00435                     await messageDialog.ShowAsync();
00436                 }
00437             }
00438
00439             // Reset UI state.
00440             listenWithoutUIButtonText.Text = " without UI";
00441             cbLanguageSelection.IsEnabled = true;
00442             btnRecognizeWithUI.IsEnabled = true;
00443             btnRecognizeWithoutUI.IsEnabled = true;
00444         }
00445     }
00446 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Polling Member List

This is the complete list of members for Scenario2_Polling, including all inherited members.
_desiredReportInterval | Scenario2_Polling | [private]
_dispatcherTimer | Scenario2_Polling | [private]
_sensor | Scenario2_Polling | [private]
DisplayCurrentReading(object sender, object args) | Scenario2_Polling | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_Polling | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario2_Polling | [inline, protected]
rootPage | Scenario2_Polling | [private]
Scenario2_Polling() | Scenario2_Polling | [inline]
ScenarioDisable(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
ScenarioEnable(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario2_Polling | [inline, private]
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cpp/FileLoggingSessionScenario.cpp Source File

  • Logging
  • cpp

FileLoggingSessionScenario.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include "pch.h"
00008 #include "FileLoggingSessionScenario.h"
00009 #include "LoggingScenarioHelpers.h"
00010
00011 #define SCENARIO_PREFIX                     L"FileLoggingSessionScenario_"
00012 #define DEFAULT_SESSION_NAME                SCENARIO_PREFIX L"Session"
00013 #define DEFAULT_CHANNEL_NAME                SCENARIO_PREFIX L"Channel"
00014 #define OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME SCENARIO_PREFIX L"LogFiles"
00015 #define LOGGING_ENABLED_SETTING_KEY_NAME    SCENARIO_PREFIX L"LoggingEnabled"
00016 #define LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME SCENARIO_PREFIX L"LogFileGeneratedBeforeSuspend"
00017
00018 using namespace concurrency;
00019 using namespace Windows::Foundation::Diagnostics;
00020 using namespace Windows::Storage;
00021 using namespace SDKTemplate;
00022
00023 FileLoggingSessionScenario^ FileLoggingSessionScenario::_instance;
00024
00025 FileLoggingSessionScenario::FileLoggingSessionScenario()
00026 {
00027     _logFileGeneratedCount = 0;
00028     _isPreparingForSuspend = false;
00029     _isBusy = false;
00030
00031     // Create the logging channel.
00032     // When an app logs messages to a channel, the messges will go
00033     // to any sessions which are consuming messages from the channel.
00034 #pragma warning(push)
00035 #pragma warning(disable : 4973)
00036     _channel = ref new Windows::Foundation::Diagnostics::LoggingChannel(DEFAULT_CHANNEL_NAME);
00037 #pragma warning(pop)
00038
00039     // This sample listens to the channel's events so it can track
00040     // information about the channel's enablement status.
00041     _channel->LoggingEnabled += ref new Windows::Foundation::TypedEventHandler<Windows::Foundation::Diagnostics::ILoggingChannel ^, Platform::Object ^>(this, &FileLoggingSessionScenario::OnChannelLoggingEnabled);
00042
00043     App::Current->Suspending += ref new Windows::UI::Xaml::SuspendingEventHandler(this, &FileLoggingSessionScenario::OnAppSuspending);
00044     App::Current->Resuming += ref new Windows::Foundation::EventHandler<Platform::Object ^>(this, &FileLoggingSessionScenario::OnAppResuming);
00045
00046     // If the app is being launched (not resumed), the
00047     // following call will activate logging if it had been
00048     // active at the time of the last suspend.
00049     ResumeLoggingIfApplicable();
00050 }
00051
00052 FileLoggingSessionScenario::~FileLoggingSessionScenario()
00053 {
00054 }
00055
00056 void FileLoggingSessionScenario::OnAppSuspending(Platform::Object ^sender, Windows::ApplicationModel::SuspendingEventArgs ^e)
00057 {
00058     (void) sender;    // Unused parameter
00059
00060     // Get a deferral before performing any async operations
00061     // to avoid suspension prior to LoggingScenario completing
00062     // PrepareToSuspendAsync().
00063     auto deferral = e->SuspendingOperation->GetDeferral();
00064     PrepareToSuspendAsync().then([=](task<void> previousTask)
00065     {
00066         // From LoggingScenario's perspective, it's now okay to
00067         // suspend, so release the deferral.
00068         deferral->Complete();
00069     });
00070 }
00071
00072 void FileLoggingSessionScenario::OnAppResuming(Platform::Object ^sender, Platform::Object ^args)
00073 {
00074     // If logging was active at the last suspend,
00075     // ResumeLoggingIfApplicable will re-activate
00076     // logging.
00077     ResumeLoggingIfApplicable();
00078 }
00079
00080 void FileLoggingSessionScenario::OnChannelLoggingEnabled(ILoggingChannel^ sender, Platform::Object^ args)
00081 {
00082     // This method is called when the channel is informing us of channel-related state changes.
00083     // Save new channel state. These values can be used for advanced logging scenarios where,
00084     // for example, it's desired to skip blocks of logging code if the channel is not being
00085     // consumed by any sessions.
00086     _isChannelEnabled = sender->Enabled;
00087     _channelLoggingLevel = sender->Level;
00088 }
00089
00090 // When the log file gets large, the system closes it and starts a new one.
00091 // The LogFileGenerated event is raised to give the app a chance to move
00092 // the recently-generated log file to a safe place. When the handler returns,
00093 // the FileLoggingSession may reuse the file name for a new log file.
00094 // This function moves the log file to an app-defined location.
00095 void FileLoggingSessionScenario::OnLogFileGenerated(IFileLoggingSession^ sender, LogFileGeneratedEventArgs^ args)
00096 {
00097     InterlockedIncrement(&_logFileGeneratedCount);
00098
00099     // ContinuationData allows information to be
00100     // shared across the below async operations.
00101     struct ContinuationData
00102     {
00103         StorageFolder^ ourSampleAppLogFolder;
00104         StorageFile^ generatedLogFile;
00105         Platform::String^ logFileName;
00106     };
00107     auto data = std::make_shared<ContinuationData>();
00108     data->generatedLogFile = args->File;
00109     // Create the app-defined folder under the app's local folder.
00110     // An app defines where/how it wants to store log files.
00111     // This sample uses OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME under
00112     // the app's local folder.
00113     create_task(ApplicationData::Current->LocalFolder->CreateFolderAsync(OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME, CreationCollisionOption::OpenIfExists))
00114         .then([this, data](StorageFolder^ ourSampleAppLogFolder)
00115         {
00116             // After creating/opening our sample app's log folder,
00117             // save it for use in a continuation further below.
00118             data->ourSampleAppLogFolder = ourSampleAppLogFolder;
00119             // Create a new log file name, and save it for use
00120             // in a continuation further below.
00121             data->logFileName = "Log-" + ref new Platform::String(GetTimeStamp().c_str()) + ".etl";
00122             // Move the log file to our sample app's log folder.
00123             return data->generatedLogFile->MoveAsync(ourSampleAppLogFolder, data->logFileName, Windows::Storage::NameCollisionOption::FailIfExists);
00124         })
00125         .then([this, data](task<void> previousTask)
00126         {
00127             // Update the UI to show the new log file.
00128             if (_isPreparingForSuspend == false)
00129             {
00130                 StatusChanged(this, ref new LoggingScenarioEventArgs(LoggingScenarioEventType::LogFileGenerated, std::wstring((data->ourSampleAppLogFolder->Path + "\\" + data->logFileName)->Data())));
00131             }
00132         });
00133 }
00134
00135 task<StorageFile^> FileLoggingSessionScenario::CloseSessionSaveFinalLogFile()
00136 {
00137
00138     // ContinuationData allows information to be
00139     // shared across the below async operations.
00140     struct ContinuationData
00141     {
00142         StorageFolder^ ourSampleAppLogFolder;
00143         Platform::String^ logFileName;
00144     };
00145     auto data = std::make_shared<ContinuationData>();
00146
00147     // Tell the session to save its final log file.
00148     return create_task(_session->CloseAndSaveToFileAsync())
00149         .then([this, data](StorageFile^ finalFileBeforeSuspend)
00150         {
00151             if (finalFileBeforeSuspend != nullptr)
00152             {
00153                 // A final log file was created.
00154                 // Move it to the sample-defined log folder.
00155                 // First, get create/open our sample-defined log folder.
00156                 return create_task(ApplicationData::Current->LocalFolder->CreateFolderAsync(OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME, CreationCollisionOption::OpenIfExists))
00157                     .then([this, finalFileBeforeSuspend, data](StorageFolder^ ourSampleAppLogFolder)
00158                     {
00159                         // Next, move the log file to the sample-defined log folder.
00160                         data->ourSampleAppLogFolder = ourSampleAppLogFolder;
00161                         data->logFileName = "Log-" + ref new Platform::String(GetTimeStamp().c_str()) + ".etl";
00162                         return finalFileBeforeSuspend->MoveAsync(ourSampleAppLogFolder, data->logFileName, Windows::Storage::NameCollisionOption::FailIfExists);
00163                     })
00164                     .then([this, data](task<void> previousTask)
00165                     {
00166                         // Return a StorageFile representing the log file.
00167                         return StorageFile::GetFileFromPathAsync(data->ourSampleAppLogFolder->Path + "\\" + data->logFileName);
00168                     });
00169             }
00170
00171             // Async operation need to return consistent types.
00172             // If the session did not produce any log file,
00173             // return a task which produces a null StorageFile.
00174             return task<StorageFile^>([]() -> StorageFile^
00175             {
00176                 return nullptr;
00177             });
00178         });
00179 }
00180
00181 // Handle a request to toggle logging enable/disable status.
00182 task<bool> FileLoggingSessionScenario::ToggleLoggingEnabledDisabledAsync()
00183 {
00184     IsBusy = true;
00185     try
00186     {
00187         if (_session != nullptr)
00188         {
00189             // Save any final log file.
00190             return create_task(CloseSessionSaveFinalLogFile()).then([this](StorageFile^ finalLogFilePath)
00191             {
00192                 // Cleanup the session and let the sample UI know of the new status.
00193                 delete _session;
00194                 _session = nullptr;
00195                 StatusChanged(this, ref new LoggingScenarioEventArgs(LoggingScenarioEventType::LogFileGeneratedAtDisable, finalLogFilePath == nullptr ? L"" : finalLogFilePath->Path->Data()));
00196                 SetAppLocalSettingsValue(LOGGING_ENABLED_SETTING_KEY_NAME, false);
00197                 StatusChanged(this, ref new LoggingScenarioEventArgs(false));
00198                 IsBusy = false;
00199                 return false;
00200             });
00201         }
00202         else
00203         {
00204             // Enable logging and let the UI know of the new status.
00205             StartLogging();
00206             SetAppLocalSettingsValue(LOGGING_ENABLED_SETTING_KEY_NAME, true);
00207             StatusChanged(this, ref new LoggingScenarioEventArgs(true));
00208             IsBusy = false;
00209             return task<bool>([]() -> bool
00210             {
00211                 return true;
00212             });
00213         }
00214     }
00215     catch (...)
00216     {
00217         IsBusy = false;
00218         throw;
00219     }
00220 }
00221
00222 void FileLoggingSessionScenario::StartLogging()
00223 {
00224     // If no session exists, create one.
00225     // NOTE: There are use cases where an application
00226     // may want to create only a channel for sessions outside
00227     // of the application itself. See MSDN for details. This
00228     // sample is the common scenario of an app logging events
00229     // which it wants to place in its own log file, so it creates
00230     // a session and channel as a pair. The channel is created
00231     // during construction of this LoggingScenario class so
00232     // it already exsits by the time this function is called.
00233     if (_session == nullptr)
00234     {
00235         _session = ref new Windows::Foundation::Diagnostics::FileLoggingSession(DEFAULT_SESSION_NAME);
00236         _session->LogFileGenerated += ref new Windows::Foundation::TypedEventHandler<IFileLoggingSession ^, LogFileGeneratedEventArgs ^>(this, &FileLoggingSessionScenario::OnLogFileGenerated);
00237     }
00238
00239     // This sample adds the channel at level "warning" to
00240     // demonstrated how messages logged at more verbose levels
00241     // are ignored by the session.
00242     _session->AddLoggingChannel(_channel, LoggingLevel::Warning);
00243 }
00244
00245 // Prepare this scenario for suspend.
00246 task<void> FileLoggingSessionScenario::PrepareToSuspendAsync()
00247 {
00248     if (_session != nullptr)
00249     {
00250         _isPreparingForSuspend = true;
00251         // Before suspend, save any final log file.
00252         return create_task(CloseSessionSaveFinalLogFile()).then([this](StorageFile^ finalLogFile)
00253         {
00254             // Cleanup the session.
00255             delete _session;
00256             _session = nullptr;
00257             // Save values used when the app is resumed or started later.
00258             // Logging is enabled.
00259             SetAppLocalSettingsValue(LOGGING_ENABLED_SETTING_KEY_NAME, true);
00260             // If there's a final log file...
00261             if (finalLogFile != nullptr)
00262             {
00263                 // Save the log file name saved at suspend so the sample UI can be
00264                 // updated on resume with that information.
00265                 SetAppLocalSettingsValue(LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME, finalLogFile->Path);
00266             }
00267             else
00268             {
00269                 SetAppLocalSettingsValue(LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME, nullptr);
00270             }
00271             _isPreparingForSuspend = false;
00272             return task<void>([]() -> void {});
00273         });
00274     }
00275     else
00276     {
00277         // Save values used when the app is resumed or started later.
00278         // Logging is not enabled and no log file was saved.
00279         SetAppLocalSettingsValue(LOGGING_ENABLED_SETTING_KEY_NAME, false);
00280         SetAppLocalSettingsValue(LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME, nullptr);
00281         return task<void>([]() -> void {});
00282     }
00283 }
00284
00285 // This is called when the app is either resuming or starting.
00286 // It will enable logging if the app has never been started before
00287 // or if logging had been enabled the last time the app was running.
00288 void FileLoggingSessionScenario::ResumeLoggingIfApplicable()
00289 {
00290     bool loggingEnabled;
00291     if (IsAppLocalSettingsValue(LOGGING_ENABLED_SETTING_KEY_NAME))
00292     {
00293         loggingEnabled = GetAppLocalSettingsValueAsBool(LOGGING_ENABLED_SETTING_KEY_NAME);
00294     }
00295     else
00296     {
00297         SetAppLocalSettingsValue(LOGGING_ENABLED_SETTING_KEY_NAME, true);
00298         loggingEnabled = true;
00299     }
00300
00301     if (loggingEnabled)
00302     {
00303         StartLogging();
00304     }
00305
00306     // When the sample suspends, it retains state as to whether or not it had
00307     // generated a new log file at the last suspension. This allows any
00308     // UI to be updated on resume to reflect that fact.
00309     if (IsAppLocalSettingsValue(LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME))
00310     {
00311         Platform::String^ pathOfLogFileGeneratedBeforeSuspend = GetAppLocalSettingsValueAsString(LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME);
00312         if (pathOfLogFileGeneratedBeforeSuspend != nullptr)
00313         {
00314             StatusChanged(this, ref new LoggingScenarioEventArgs(LoggingScenarioEventType::LogFileGeneratedAtSuspend, pathOfLogFileGeneratedBeforeSuspend->Data()));
00315             SetAppLocalSettingsValue(LOGFILEGEN_BEFORE_SUSPEND_SETTING_KEY_NAME, nullptr);
00316         }
00317     }
00318 }
00319
00320 // DoScenarioAsync creates a worker thread to simulate application activity.
00321 // In actual use, logging functions would be called from various parts of a
00322 // larger application. The purpose of the below concise function is to show
00323 // how logging works over periods of time when lots of messages are logged.
00324 // Primarily, it shows how log files are generated when each log file reaches
00325 // its maximum capacity. This function logs information in a loop
00326 // that exits after 3 log files have been generated. After each log file is
00327 // generated, the sample's UI is updated with the log file's name.
00328 task<void> FileLoggingSessionScenario::DoScenarioAsync()
00329 {
00330     // Tell the UI the scenario is busy working.
00331     IsBusy = true;
00332     try
00333     {
00334         // ContinuationData allows information to be
00335         // shared across the below async operations.
00336         struct ContinuationData
00337         {
00338             int messageIndex;
00339             int startFileCount;
00340             std::function<concurrency::task<void>(const std::shared_ptr<ContinuationData>&)> func;
00341         };
00342
00343         // Create an instance of ContinuationData to share
00344         // across the below async tasks.
00345         auto data = std::make_shared<ContinuationData>();
00346
00347         // A message index counter which increments for each
00348         // logging call.
00349         data->messageIndex = 0;
00350
00351         // Get the count of log files created so far.
00352         // The code below will execute until 3 more
00353         // log files are created.
00354         data->startFileCount = LogFileGeneratedCount;
00355
00356         // This is the main worker function. It is
00357         // called asynchronously until 3 new log files
00358         // have been created.
00359         data->func = [this](const std::shared_ptr<ContinuationData>& data)
00360         {
00361             const int NUMBER_OF_LOG_FILES_TO_GENERATE = 3;
00362
00363             // To demo logging, loop and log messages until 3 log files have been produced.
00364             // Each time a new log is created, the FileLoggingSession will notify this sample
00365             // via the FileLoggingSession::LogFileGenerated event.
00366             // While not 3 files yet, execute the following code...
00367             while (LogFileGeneratedCount - data->startFileCount < NUMBER_OF_LOG_FILES_TO_GENERATE)
00368             {
00369                 // Since the channel is added to the session at level Warning, the following
00370                 // message is logged because it is logged at level LoggingLevel.Critical.
00371                 Platform::String^ messageToLog =
00372                     "Message=" +
00373                     (++data->messageIndex).ToString() +
00374                     ": Lorem ipsum dolor sit amet, consectetur adipiscing elit.In ligula nisi, vehicula nec eleifend vel, rutrum non dolor.Vestibulum ante ipsum " +
00375                     "primis in faucibus orci luctus et ultrices posuere cubilia Curae; Curabitur elementum scelerisque accumsan. In hac habitasse platea dictumst.";
00376                 _channel->LogMessage(messageToLog, LoggingLevel::Critical);
00377
00378                 // Since the channel is added to the session at level Warning, the following
00379                 // message is *not* logged because it is logged at LoggingLevel.Information.
00380                 messageToLog =
00381                     "Message=" +
00382                     (++data->messageIndex).ToString() +
00383                     ": Lorem ipsum dolor sit amet, consectetur adipiscing elit.In ligula nisi, vehicula nec eleifend vel, rutrum non dolor.Vestibulum ante ipsum " +
00384                     "primis in faucibus orci luctus et ultrices posuere cubilia Curae; Curabitur elementum scelerisque accumsan. In hac habitasse platea dictumst.";
00385                 this->_channel->LogMessage(messageToLog, LoggingLevel::Information);
00386
00387                 int value = 1000000; // one million, 7 digits, 4-bytes as an int, 14 bytes as a wide character string.
00388                 _channel->LogMessage("Value #" + (++data->messageIndex).ToString() + "  " + value.ToString(), LoggingLevel::Critical); // value is logged as 14 byte wide character string.
00389                 _channel->LogValuePair("Value #" + (++data->messageIndex).ToString(), value, LoggingLevel::Critical); // value is logged as a 4-byte integer.
00390
00391                 //
00392                 // Pause every once in a while to simulate application activity outside of logging.
00393                 //
00394
00395                 if (data->messageIndex % 50 == 0)
00396                 {
00397                     // Create a task which calls this function again in 5 msecs.
00398                     // When this function is called again, it will continue its work.
00399                     return create_delayed_task(std::chrono::milliseconds(5), [=] { return data->func(data); });
00400                 }
00401             }
00402
00403             // 3 log files created, nothing more to do, stop.
00404             return task<void>([]() -> void {});
00405         };
00406
00407         // Create the first task of several which will create 3 log files,
00408         // and then execute the following continuation code when finished...
00409         return data->func(data).then([=](task<void> previousTask)
00410         {
00411             // This executes after 3 new log files have been created or
00412             // in the event of an unhandled exception in the above code.
00413             try
00414             {
00415                 // Tell the sample UI that the scenario is not busy any longer.
00416                 IsBusy = false;
00417
00418                 // The following 'get' will re-throw any exceptions which
00419                 // occurred during the above code (data->func above).
00420                 previousTask.get();
00421             }
00422             catch (...)
00423             {
00424                 OutputDebugString(L"Exception during DoScenario.");
00425                 throw;
00426             }
00427         });
00428     }
00429     catch (...)
00430     {
00431         IsBusy = false;
00432         throw;
00433     }
00434 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialSound/cpp/Scenario2_CardioidSound.xaml.h Source File

  • SpatialSound
  • cpp

Scenario2_CardioidSound.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012
00013 #pragma once
00014
00015 #include "Scenario2_CardioidSound.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 enum class PlayState { Stopped = 0, Playing };
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     [Windows::Foundation::Metadata::WebHostHidden]
00026     public ref class Scenario2_CardioidSound sealed
00027     {
00028     public:
00029         Scenario2_CardioidSound();
00030         virtual ~Scenario2_CardioidSound();
00031     private:
00032         void EnvironmentComboBox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00033         void PlayButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void StopButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         void ScalingSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00036         void OrderSlider_ValudChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00037
00038         // Source position sliders
00039         void SourcePositionX_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00040         void SourcePositionY_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00041         void SourcePositionZ_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00042
00043         // Source orientation sliders
00044         void YawSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00045         void PitchSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00046         void RollSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00047
00048         void OnTimerTick(Object^ sender, Object^ e);
00049         void UpdateScalingAndOrder();
00050
00051     private:
00052         MainPage^               _rootPage;
00053         bool                    _initialized = false;
00054         CardioidSound           _cardioidSound;
00055         DispatcherTimer^        _timer;
00056         EventRegistrationToken  _timerEventToken;
00057         float                   _x = 0;            // Source is centered
00058         float                   _y = 0;            // Source is at eye level with the listener
00059         float                   _z = -2;           // Source is 2 meters in front of the listener
00060         float                   _yaw = 0;
00061         float                   _pitch = 0;
00062         float                   _roll = 0;
00063         PlayState               _state = PlayState::Stopped;
00064     };
00065 }
Generated on Fri Nov 15 2024 22:21:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MediaTransportControls Member List

This is the complete list of members for MediaTransportControls, including all inherited members.
AddExitButton() | MediaTransportControls | [private]
AddPlayPauseButton() | MediaTransportControls | [private]
AddSeekbar() | MediaTransportControls | [private]
ApplyShaders() | MediaTransportControls |
ComputeLookAtQuaternion(Windows::Foundation::Numerics::float3 objectPosition, Windows::Foundation::Numerics::float3 targetPosition, Windows::Foundation::Numerics::float3 upVector) | MediaTransportControls | [inline, private]
Hide() | MediaTransportControls |
Initialize() | MediaTransportControls |
IsFocused() | MediaTransportControls |
IsVisible() | MediaTransportControls | [inline]
m_baseControls | MediaTransportControls | [private]
m_exitButtonControl | MediaTransportControls | [private]
m_inactiveSecondsCounter | MediaTransportControls | [private]
m_isVisible | MediaTransportControls | [private]
m_playPauseButtonControl | MediaTransportControls | [private]
m_position | MediaTransportControls | [private]
m_rotation | MediaTransportControls | [private]
m_seekbarControl | MediaTransportControls | [private]
m_shadersLoaded | MediaTransportControls | [private]
m_transform | MediaTransportControls | [private]
MediaTransportControls() | MediaTransportControls |
PerformPressedAction() | MediaTransportControls |
Render() | MediaTransportControls |
Show(Windows::UI::Input::Spatial::SpatialPointerPose^cameraPose, float distance) | MediaTransportControls |
Update(const DX::StepTimer &timer, Windows::UI::Input::Spatial::SpatialPointerPose^cameraPose) | MediaTransportControls |
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_DisplayOnOff Member List

This is the complete list of members for Scenario3_DisplayOnOff, including all inherited members.
displayController | Scenario3_DisplayOnOff | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_DisplayOnOff | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario3_DisplayOnOff | [inline, protected]
OnProximitySensorAdded(DeviceWatcher sender, DeviceInformation device) | Scenario3_DisplayOnOff | [inline, private]
rootPage | Scenario3_DisplayOnOff | [private]
Scenario3_DisplayOnOff() | Scenario3_DisplayOnOff | [inline]
ScenarioDisable(object sender, RoutedEventArgs e) | Scenario3_DisplayOnOff | [inline, private]
ScenarioEnable(object sender, RoutedEventArgs e) | Scenario3_DisplayOnOff | [inline, private]
sensor | Scenario3_DisplayOnOff | [private]
watcher | Scenario3_DisplayOnOff | [private]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2 Member List

This is the complete list of members for Scenario2, including all inherited members.
adapter | Scenario2 | [private]
ConnectSocket_Click(object sender, RoutedEventArgs e) | Scenario2 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2 | [inline, protected]
rootPage | Scenario2 | [private]
Scenario2() | Scenario2 | [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DpiScaling/cs/Scenario2.xaml.cs Source File

  • DpiScaling
  • cs

Scenario2.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using Windows.Graphics.Display;
00013 using Windows.UI.Text;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Media;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario2 : Page
00022     {
00023         public Scenario2()
00024         {
00025             InitializeComponent();
00026             DisplayInformation displayInformation = DisplayInformation.GetForCurrentView();
00027             displayInformation.DpiChanged += DisplayProperties_DpiChanged;
00028             DefaultLayoutText.FontSize = PxFromPt(20);  // xaml fontsize is in pixels.
00029         }
00030
00031         // Helpers to convert between points and pixels.
00032         double PtFromPx(double pixel)
00033         {
00034             return pixel * 72 / 96;
00035         }
00036
00037         double PxFromPt(double pt)
00038         {
00039             return pt * 96 / 72;
00040         }
00041
00042         void OutputSettings(double rawPixelsPerViewPixel, FrameworkElement rectangle, TextBlock viewPxText, TextBlock rawPxText, TextBlock fontTextBlock)
00043         {
00044             // Get the size of the rectangle in view pixels and calulate the size in raw pixels.
00045             double sizeInViewPx = rectangle.Width;
00046             double sizeInRawPx = sizeInViewPx * rawPixelsPerViewPixel;
00047
00048             viewPxText.Text = sizeInViewPx.ToString("F1") + " view px";
00049             rawPxText.Text = sizeInRawPx.ToString("F0") + " raw px";
00050
00051             double fontSize = PtFromPx(fontTextBlock.FontSize);
00052             fontTextBlock.Text = fontSize.ToString("F0") + "pt";
00053         }
00054
00055         void ResetOutput()
00056         {
00057             ResolutionTextBlock.Text = Window.Current.Bounds.Width.ToString("F1") + "x" + Window.Current.Bounds.Height.ToString("F1");
00058
00059             DisplayInformation displayInformation = DisplayInformation.GetForCurrentView();
00060             double rawPixelsPerViewPixel = displayInformation.RawPixelsPerViewPixel;
00061
00062             // Set the override rectangle size and override text font size by taking our desired
00063             // size in raw pixels and converting it to view pixels.
00064             const double rectSizeInRawPx = 100;
00065             double rectSizeInViewPx = rectSizeInRawPx / rawPixelsPerViewPixel;
00066             OverrideLayoutRect.Width = rectSizeInViewPx;
00067             OverrideLayoutRect.Height = rectSizeInViewPx;
00068
00069             double fontSizeInRawPx = PxFromPt(20);
00070             double fontSizeInViewPx = fontSizeInRawPx / rawPixelsPerViewPixel;
00071             OverrideLayoutText.FontSize = fontSizeInViewPx;
00072
00073             // Output settings for controls with default scaling behavior.
00074             OutputSettings(rawPixelsPerViewPixel, DefaultLayoutRect, DefaultRelativePx, DefaultPhysicalPx, DefaultLayoutText);
00075             // Output settings for override controls.
00076             OutputSettings(rawPixelsPerViewPixel, OverrideLayoutRect, OverrideRelativePx, OverridePhysicalPx, OverrideLayoutText);
00077         }
00078
00079         protected override void OnNavigatedTo(NavigationEventArgs e)
00080         {
00081             ResetOutput();
00082         }
00083
00084         void DisplayProperties_DpiChanged(DisplayInformation sender, object args)
00085         {
00086             ResetOutput();
00087         }
00088     }
00089 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Altimeter/cpp/pch.cpp Source File

  • Altimeter
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBottomUpList/cpp/pch.h Source File

  • XamlBottomUpList
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cpp/Scenario6_DeleteTPMVSC.xaml.cpp Source File

  • SmartCard
  • cpp

Scenario6_DeleteTPMVSC.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario6_DeleteTPMVSC.xaml.h"
00005 #include "ChallengeResponseAlgorithm.h"
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace concurrency;
00010 using namespace Platform;
00011 using namespace Windows::Devices::SmartCards;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::Storage::Streams;
00015 using namespace Windows::Security::Cryptography;
00016 using namespace Windows::Security::Cryptography::Core;
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Controls::Primitives;
00020 using namespace Windows::UI::Xaml::Data;
00021 using namespace Windows::UI::Xaml::Input;
00022 using namespace Windows::UI::Xaml::Media;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario6_DeleteTPMVSC::Scenario6_DeleteTPMVSC()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 void Scenario6_DeleteTPMVSC::Delete_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00031 {
00032     if (MainPage::Current->SmartCardReaderDeviceId == nullptr)
00033     {
00034         MainPage::Current->NotifyUser("Use Scenario One to create a TPM virtual smart card.", NotifyType::ErrorMessage);
00035         return;
00036     }
00037
00038     Button^ b = dynamic_cast<Button^>(sender);
00039     b->IsEnabled = false;
00040
00041     MainPage::Current->NotifyUser("Deleting TPM virtual smart card...", NotifyType::StatusMessage);
00042
00043     create_task(MainPage::Current->GetSmartCard()).then(
00044         [=](task<Windows::Devices::SmartCards::SmartCard^> getSmartCardTask)
00045     {
00046         Windows::Devices::SmartCards::SmartCard^ card = getSmartCardTask.get();
00047
00048         // The following block is not directly related to TPM virtual smart
00049         // card deletion, but rather demonstrates how to handle CardRemoved
00050         // events by registering an event handler with a SmartCardReader
00051         // object.  Since we are using a TPM virtual smart card in this
00052         // case, the card cannot actually be added to or removed from
00053         // the reader, but a CardRemoved event will fire when the reader
00054         // is deleted.
00055         {
00056             // Event handlers will only fire during the lifetime of the
00057             // particular SmartCardReader instance they are attached to;
00058             // thus, we must maintain a handle to the reader as an instance
00059             // member.
00060             this->reader = card->Reader;
00061
00062             // Here we use the += operator to add our event handler to the
00063             // collection of CardRemoved handlers for the reader.  Note that
00064             // if you want to do any UI operations in the handler, or in
00065             // general use any non-agile objects, you must specify a
00066             // callback context of CallbackContext::Same in the
00067             // TypedEventHandler's constructor, as below.  Otherwise you
00068             // may receive exceptions due to RPC_E_WRONG_THREAD.
00069             this->reader->CardRemoved += ref new TypedEventHandler<SmartCardReader ^, CardRemovedEventArgs ^>(this, &Scenario6_DeleteTPMVSC::HandleCardRemoved, CallbackContext::Same);
00070         }
00071
00072         return SmartCardProvisioning::RequestVirtualSmartCardDeletionAsync(card);
00073     }).then(
00074         [=](task<bool> deleteSmartCardTask)
00075     {
00076         try
00077         {
00078             bool result = deleteSmartCardTask.get();
00079             if (result)
00080             {
00081                 MainPage::Current->NotifyUser("TPM virtual smart card deletion completed.", NotifyType::StatusMessage);
00082                 MainPage::Current->SmartCardReaderDeviceId = nullptr;
00083             }
00084             else
00085             {
00086                 MainPage::Current->NotifyUser("TPM virtual smart card deletion was canceled by user.", NotifyType::StatusMessage);
00087             }
00088         }
00089         catch (Exception^ ex)
00090         {
00091             MainPage::Current->NotifyUser("TPM virtual smart card deletion failed with exception: " + ex->ToString(), NotifyType::ErrorMessage);
00092         }
00093
00094         b->IsEnabled = true;
00095     });
00096 }
00097
00098 void Scenario6_DeleteTPMVSC::HandleCardRemoved(SmartCardReader ^evtReader, CardRemovedEventArgs^ args)
00099 {
00100     MainPage::Current->NotifyUser("Card removed from reader " + evtReader->Name + ".", NotifyType::StatusMessage);
00101 }
Generated on Fri Nov 15 2024 22:21:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/xBindSampleModel/FileSystemDataSource.cs Source File

  • XamlBind
  • cpp
  • xBindSampleModel

FileSystemDataSource.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections;
00003 using System.Collections.Generic;
00004 using System.Collections.Specialized;
00005 using System.ComponentModel;
00006 using System.Diagnostics;
00007 using System.Threading.Tasks;
00008 using Windows.Foundation;
00009 using Windows.Foundation.Collections;
00010 using Windows.Storage;
00011 using Windows.Storage.FileProperties;
00012 using Windows.Storage.Search;
00013 using Windows.UI.Core;
00014 using Windows.UI.Xaml.Interop;
00015 using Windows.UI.Xaml.Media.Imaging;
00016
00017 namespace xBindSampleModel
00018 {
00019
00020     public sealed class FileItem
00021     {
00022         public string DisplayName { get; set; }
00023         public string Path { get; set; }
00024         public int FileSize { get; set; }
00025         public DateTimeOffset Date { get; set; }
00026         public int ImageWidth { get; private set; }
00027         public int ImageHeight { get; private set; }
00028
00029         private BitmapImage _imageData;
00030         public BitmapImage ImageData { get { return _imageData; } }
00031
00032         private async Task FetchImageAsync()
00033         {
00034             _imageData = new BitmapImage();
00035             StorageFile f = await StorageFile.GetFileFromPathAsync(Path);
00036             await _imageData.SetSourceAsync(await f.GetThumbnailAsync(ThumbnailMode.SingleItem));
00037         }
00038         public string Key { get; private set; }
00039
00040         internal async static Task<FileItem> fromStorageFile(StorageFile f)
00041         {
00042             FileItem item = new FileItem();
00043             item.Path = f.Path;
00044             item.DisplayName = f.DisplayName;
00045             BasicProperties bp = await f.GetBasicPropertiesAsync();
00046             item.FileSize = (int)bp.Size;
00047             item.Date = bp.DateModified;
00048             item.Key = f.FolderRelativeId;
00049             ImageProperties ip = await f.Properties.GetImagePropertiesAsync();
00050             item.ImageWidth = (int)ip.Width;
00051             item.ImageHeight = (int)ip.Height;
00052             var t = item.FetchImageAsync();
00053             return item;
00054         }
00055
00056         public string prettyDate
00057         {
00058             get
00059             {
00060                 DateTime now = DateTime.Now;
00061                 if (Date.Date == now.Date)
00062                 {
00063                     return Date.ToLocalTime().ToString("T");
00064                 }
00065                 else if (Date.Date == now.Date.AddDays(-1))
00066                 {
00067                     return "Yesterday";
00068                 }
00069                 else return Date.ToLocalTime().ToString("d MMM yyyy");
00070             }
00071         }
00072
00073         public string prettyFileSize
00074         {
00075             get { return FileSize.ToString("N0") + " bytes"; }
00076         }
00077
00078         public string prettyImageSize
00079         {
00080             get { return ImageWidth + " x " + ImageHeight + " px"; }
00081         }
00082     }
00083
00084
00085     public sealed class FileDataSource : INotifyCollectionChanged, System.Collections.IList, IObservableVector<FileItem>
00086     {
00087         private StorageFileQueryResult _queryResult;
00088         private CoreDispatcher dispatcher;
00089         private int _count = 0;
00090         private List<FileItem> _cache;
00091
00092         public event NotifyCollectionChangedEventHandler CollectionChanged;
00093         public event VectorChangedEventHandler<FileItem> VectorChanged;
00094
00095         public FileDataSource()
00096         {
00097             dispatcher = Windows.UI.Xaml.Window.Current.Dispatcher;
00098             _cache = new List<FileItem>();
00099         }
00100
00101         //WinRT wrapper
00102         public IAsyncAction SetupDataSource(StorageFolder folder)
00103         {
00104             return this.SetupDataSourceImpl(folder).AsAsyncAction();
00105         }
00106
00107         private async Task SetupDataSourceImpl(StorageFolder folder)
00108         {
00109             this.Folder = folder;
00110             QueryOptions options = new QueryOptions();
00111             options.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
00112             _queryResult = this.Folder.CreateFileQueryWithOptions(options);
00113             _queryResult.ContentsChanged += QueryResult_ContentsChanged;
00114             await FetchData();
00115         }
00116
00117         public IAsyncAction SetupDataSourceUsingPicturesFolder()
00118         {
00119             return SetupDataSourceUsingPicturesFolderImpl().AsAsyncAction();
00120         }
00121         private async Task SetupDataSourceUsingPicturesFolderImpl()
00122         {
00123             StorageLibrary pictures = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures);
00124             await SetupDataSourceImpl(pictures.SaveFolder);
00125         }
00126         public StorageFolder Folder { get; set; }
00127
00128         private void QueryResult_ContentsChanged(IStorageQueryResultBase sender, object args)
00129         {
00130             if (!dispatcher.HasThreadAccess)
00131             {
00132                 var t = dispatcher.RunAsync(CoreDispatcherPriority.Normal, ResetCollection);
00133             }
00134         }
00135
00136         public void ResetCollection()
00137         {
00138             if (CollectionChanged != null)
00139             {
00140                 CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
00141             }
00142             if (VectorChanged != null)
00143             {
00144                 VectorChanged(this, new VectorChangedEventArgs() { CollectionChange = CollectionChange.Reset });
00145             }
00146         }
00147
00148         private const int BATCHSIZE = 50;
00149
00150         async Task FetchData()
00151         {
00152             _count = (int)await _queryResult.GetItemCountAsync();
00153             this._cache.Clear();
00154             this._cache.AddRange(new FileItem[_count]);
00155             for (int i = 0; i < _count; i += BATCHSIZE)
00156             {
00157                 await fetchBatch(i);
00158             }
00159
00160             if (VectorChanged != null)
00161             {
00162                 VectorChanged(this, new VectorChangedEventArgs() { CollectionChange = CollectionChange.Reset });
00163             }
00164             if (CollectionChanged != null)
00165             {
00166                 CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
00167             }
00168         }
00169
00170         async Task fetchBatch(int index)
00171         {
00172             IReadOnlyList<StorageFile> results = await _queryResult.GetFilesAsync((uint)index, (uint)BATCHSIZE);
00173             List<Task> tasks = new List<Task>(BATCHSIZE);
00174             for (int i = 0; i < results.Count; i++)
00175             {
00176                 tasks.Add(
00177                     FileItem.fromStorageFile(results[i]).ContinueWith((f, j) =>
00178                     {
00179                         int cacheIndex = index + (int)j;
00180                         _cache[cacheIndex] = f.Result;
00181                     }, i));
00182             }
00183             await Task.WhenAll(tasks.ToArray());
00184         }
00185
00186         bool IList.Contains(object item)
00187         {
00188             return ((IList)this).IndexOf(item) != -1;
00189         }
00190
00191         object this[int index]
00192         {
00193             get
00194             {
00195                 object result = null;
00196                 if (index < _cache.Count) result = _cache[index];
00197                 return result;
00198             }
00199             set
00200             {
00201                 FileItem f = value as FileItem;
00202                 if (f != null)
00203                     _cache[index] = f;
00204                 else
00205                     throw new ArgumentException("The value is expected to be a fileitem");
00206             }
00207         }
00208         public int Count
00209         {
00210             get { return _count; }
00211         }
00212
00213         bool IList.IsFixedSize { get { return false; } }
00214
00215         bool IList.IsReadOnly { get { return true; } }
00216
00217
00218         int ICollection.Count { get { return _count; } }
00219
00220         bool ICollection.IsSynchronized { get { throw new NotImplementedException(); } }
00221
00222         object ICollection.SyncRoot { get { throw new NotImplementedException(); } }
00223
00224         object IList.this[int index]
00225         {
00226             get
00227             {
00228                 return this[index];
00229             }
00230             set
00231             {
00232                 throw new NotImplementedException();
00233             }
00234         }
00235
00236         int IList.Add(object item)
00237         {
00238             throw new NotImplementedException();
00239         }
00240
00241         void IList.Clear()
00242         {
00243             throw new NotImplementedException();
00244         }
00245
00246         int IList.IndexOf(object item)
00247         {
00248             return _cache.IndexOf((FileItem)item);
00249         }
00250
00251         void IList.Insert(int index, object value)
00252         {
00253             throw new NotImplementedException();
00254         }
00255
00256         void IList.Remove(object value)
00257         {
00258             throw new NotImplementedException();
00259         }
00260
00261         void IList.RemoveAt(int index)
00262         {
00263             throw new NotImplementedException();
00264         }
00265
00266         void ICollection.CopyTo(Array array, int index)
00267         {
00268             throw new NotImplementedException();
00269         }
00270
00271         IEnumerator IEnumerable.GetEnumerator()
00272         {
00273             throw new NotImplementedException();
00274         }
00275
00276         #region IObservableVector Implementation
00277         FileItem IList<FileItem>.this[int index]
00278         {
00279             get
00280             {
00281                 FileItem result = null;
00282                 if (index < _cache.Count) result = _cache[index];
00283                 return result;
00284             }
00285
00286             set
00287             {
00288                 _cache[index] = value;
00289             }
00290         }
00291
00292         int ICollection<FileItem>.Count
00293         {
00294             get
00295             {
00296                 return _count;
00297             }
00298         }
00299
00300         bool ICollection<FileItem>.IsReadOnly
00301         {
00302             get
00303             {
00304                 return true;
00305             }
00306         }
00307
00308         void ICollection<FileItem>.Add(FileItem item)
00309         {
00310             throw new NotImplementedException();
00311         }
00312
00313         void ICollection<FileItem>.Clear()
00314         {
00315             throw new NotImplementedException();
00316         }
00317
00318         bool ICollection<FileItem>.Contains(FileItem item)
00319         {
00320             throw new NotImplementedException();
00321         }
00322
00323         void ICollection<FileItem>.CopyTo(FileItem[] array, int arrayIndex)
00324         {
00325             throw new NotImplementedException();
00326         }
00327
00328         IEnumerator<FileItem> IEnumerable<FileItem>.GetEnumerator()
00329         {
00330             throw new NotImplementedException();
00331         }
00332
00333         int IList<FileItem>.IndexOf(FileItem item)
00334         {
00335             throw new NotImplementedException();
00336         }
00337
00338         void IList<FileItem>.Insert(int index, FileItem item)
00339         {
00340             throw new NotImplementedException();
00341         }
00342
00343         bool ICollection<FileItem>.Remove(FileItem item)
00344         {
00345             throw new NotImplementedException();
00346         }
00347
00348         void IList<FileItem>.RemoveAt(int index)
00349         {
00350             throw new NotImplementedException();
00351         }
00352         #endregion
00353     }
00354
00355 }
00356
00357
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SampleBackgroundTaskWithCondition Member List

This is the complete list of members for SampleBackgroundTaskWithCondition, including all inherited members.
AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task) | SampleBackgroundTaskWithCondition | [inline, private]
AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task) | SampleBackgroundTaskWithCondition | [inline, private]
OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) | SampleBackgroundTaskWithCondition | [inline, private]
OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) | SampleBackgroundTaskWithCondition | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | SampleBackgroundTaskWithCondition | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | SampleBackgroundTaskWithCondition | [inline, protected]
OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args) | SampleBackgroundTaskWithCondition | [inline, private]
OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args) | SampleBackgroundTaskWithCondition | [inline, private]
RegisterBackgroundTask(object sender, RoutedEventArgs e) | SampleBackgroundTaskWithCondition | [inline, private]
RegisterBackgroundTask(object sender, RoutedEventArgs e) | SampleBackgroundTaskWithCondition | [inline, private]
rootPage | SampleBackgroundTaskWithCondition | [private]
SampleBackgroundTaskWithCondition() | SampleBackgroundTaskWithCondition | [inline]
SampleBackgroundTaskWithCondition() | SampleBackgroundTaskWithCondition | [inline]
UnregisterBackgroundTask(object sender, RoutedEventArgs e) | SampleBackgroundTaskWithCondition | [inline, private]
UnregisterBackgroundTask(object sender, RoutedEventArgs e) | SampleBackgroundTaskWithCondition | [inline, private]
UpdateUI() | SampleBackgroundTaskWithCondition | [inline, private]
UpdateUI() | SampleBackgroundTaskWithCondition | [inline, private]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/BackgroundTask/Scenario4_TimeTriggeredTask.xaml.h Source File

  • BackgroundTask
  • cpp
  • BackgroundTask

Scenario4_TimeTriggeredTask.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario4_TimeTriggeredTask.xaml.h
00013 // Declaration of the TimeTriggeredTask class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario4_TimeTriggeredTask.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     [Windows::Foundation::Metadata::WebHostHidden]
00028     public ref class TimeTriggeredTask sealed
00029     {
00030     public:
00031         TimeTriggeredTask();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035     private:
00036         SDKTemplate::MainPage^ rootPage;
00037
00038         void AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^ task);
00039         void RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^ args);
00042         void OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ args);
00043         void UpdateUI();
00044     };
00045 }
Generated on Fri Nov 15 2024 22:18:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-I2C/cppwinrt/pch.h Source File

  • IoT-I2C
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Devices.Enumeration.h"
00008 #include "winrt/Windows.Devices.I2c.h"
00009 #include "winrt/Windows.System.h"
00010 #include "winrt/Windows.UI.Core.h"
00011 #include "winrt/Windows.UI.Xaml.h"
00012 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.h"
00014 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00015 #include "winrt/Windows.UI.Xaml.Documents.h"
00016 #include "winrt/Windows.UI.Xaml.Interop.h"
00017 #include "winrt/Windows.UI.Xaml.Markup.h"
00018 #include "winrt/Windows.UI.Xaml.Media.h"
00019 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Package/cs/scenario1_identity.xaml.cs Source File

  • Package
  • cs

scenario1_identity.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using SDKTemplate;
00015 using System;
00016 using Windows.ApplicationModel;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     public sealed partial class Scenario1 : Page
00024     {
00025         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00026         // as NotifyUser()
00027         MainPage rootPage = MainPage.Current;
00028
00029         public Scenario1()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         String versionString(PackageVersion version)
00035         {
00036             return String.Format("{0}.{1}.{2}.{3}",
00037                                  version.Major, version.Minor, version.Build, version.Revision);
00038         }
00039
00040         String architectureString(Windows.System.ProcessorArchitecture architecture)
00041         {
00042             switch (architecture)
00043             {
00044                 case Windows.System.ProcessorArchitecture.X86:
00045                     return "x86";
00046                 case Windows.System.ProcessorArchitecture.Arm:
00047                     return "arm";
00048                 case Windows.System.ProcessorArchitecture.X64:
00049                     return "x64";
00050                 case Windows.System.ProcessorArchitecture.Neutral:
00051                     return "neutral";
00052                 case Windows.System.ProcessorArchitecture.Unknown:
00053                     return "unknown";
00054                 default:
00055                     return "???";
00056             }
00057         }
00058
00059         void GetPackage_Click(Object sender, RoutedEventArgs e)
00060         {
00061             Package package = Package.Current;
00062             PackageId packageId = package.Id;
00063
00064             String output = String.Format("Name: \"{0}\"\n" +
00065                                           "Version: {1}\n" +
00066                                           "Architecture: {2}\n" +
00067                                           "ResourceId: \"{3}\"\n" +
00068                                           "Publisher: \"{4}\"\n" +
00069                                           "PublisherId: \"{5}\"\n" +
00070                                           "FullName: \"{6}\"\n" +
00071                                           "FamilyName: \"{7}\"\n" +
00072                                           "IsFramework: {8}\n",
00073                                           packageId.Name,
00074                                           versionString(packageId.Version),
00075                                           architectureString(packageId.Architecture),
00076                                           packageId.ResourceId,
00077                                           packageId.Publisher,
00078                                           packageId.PublisherId,
00079                                           packageId.FullName,
00080                                           packageId.FamilyName,
00081                                           package.IsFramework);
00082 #if WINDOWS_APP
00083             output += String.Format("IsResourcePackage: {0}\n" +
00084                                     "IsBundle: {1}\n" +
00085                                     "IsDevelopmentMode: {2}\n" +
00086                                     "DisplayName: \"{3}\"\n" +
00087                                     "PublisherDisplayName: \"{4}\"\n" +
00088                                     "Description: \"{5}\"\n" +
00089                                     "Logo: \"{6}\"\n",
00090                                     package.IsResourcePackage,
00091                                     package.IsBundle,
00092                                     package.IsDevelopmentMode,
00093                                     package.DisplayName,
00094                                     package.PublisherDisplayName,
00095                                     package.Description,
00096                                     package.Logo.AbsoluteUri);
00097 #endif
00098             OutputTextBlock.Text = output;
00099         }
00100
00101         /// <summary>
00102         /// Invoked when this page is about to be displayed in a Frame.
00103         /// </summary>
00104         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00105         /// property is typically used to configure the page.</param>
00106         protected override void OnNavigatedTo(NavigationEventArgs e)
00107         {
00108         }
00109     }
00110 }
Generated on Fri Nov 15 2024 22:20:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/CSharpModel.cs Source File

  • XamlBind
  • cs

CSharpModel.cs

Go to the documentation of this file.
00001 ﻿using System;
00002
00003 namespace xBindSampleCS
00004 {
00005     public class CSharpModel
00006     {
00007         public int IntField;
00008         public string StringField;
00009
00010         public CSharpModel()
00011         {
00012             InitializeValues();
00013         }
00014
00015         internal void InitializeValues()
00016         {
00017             StringField = "Simple string field";
00018             IntField = 2;
00019         }
00020
00021         internal void UpdateValues()
00022         {
00023             this.IntField = IntField + 1 % 10;
00024
00025             string ms = " " + DateTime.Now.Millisecond.ToString();
00026             this.StringField += ms;
00027         }
00028
00029     }
00030 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PreviewUnavailable Member List

This is the complete list of members for PreviewUnavailable, including all inherited members.
PreviewUnavailable() | PreviewUnavailable | [inline]
PreviewUnavailable(Size paperSize, Size printableSize) | PreviewUnavailable | [inline]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/AppView.cpp Source File

  • HolographicFaceTracking
  • cpp

AppView.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "AppView.h"
00014
00015 using namespace HolographicFaceTracker;
00016
00017 using namespace concurrency;
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::ApplicationModel::Activation;
00020 using namespace Windows::ApplicationModel::Core;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Graphics::Holographic;
00023 using namespace Windows::UI::Core;
00024
00025 // The main function is only used to initialize our IFrameworkView class.
00026 // Under most circumstances, you should not need to modify this function.
00027 [Platform::MTAThread]
00028 int main(Platform::Array<Platform::String^>^)
00029 {
00030     AppViewSource^ appViewSource = ref new ::AppViewSource();
00031     CoreApplication::Run(appViewSource);
00032     return 0;
00033 }
00034
00035 IFrameworkView^ AppViewSource::CreateView()
00036 {
00037     return ref new AppView();
00038 }
00039
00040 AppView::AppView()
00041 {
00042 }
00043
00044
00045 // IFrameworkView methods
00046
00047 // The first method called when the IFrameworkView is being created.
00048 // Use this method to subscribe for Windows shell events and to initialize your app.
00049 void AppView::Initialize(CoreApplicationView^ applicationView)
00050 {
00051     applicationView->Activated +=
00052         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &AppView::OnViewActivated);
00053
00054     // Register event handlers for app lifecycle.
00055     CoreApplication::Suspending +=
00056         ref new EventHandler<SuspendingEventArgs^>(this, &AppView::OnSuspending);
00057
00058     CoreApplication::Resuming +=
00059         ref new EventHandler<Platform::Object^>(this, &AppView::OnResuming);
00060
00061     // At this point we have access to the device and we can create device-dependent
00062     // resources.
00063     m_deviceResources = std::make_shared<DX::DeviceResources>();
00064
00065     m_main = std::make_unique<HolographicFaceTrackerMain>(m_deviceResources);
00066 }
00067
00068 // Called when the CoreWindow object is created (or re-created).
00069 void AppView::SetWindow(CoreWindow^ window)
00070 {
00071     // Register for keypress notifications.
00072     window->KeyDown +=
00073         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &AppView::OnKeyPressed);
00074
00075     // Register for notification that the app window is being closed.
00076     window->Closed +=
00077         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &AppView::OnWindowClosed);
00078
00079     // Register for notifications that the app window is losing focus.
00080     window->VisibilityChanged +=
00081         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &AppView::OnVisibilityChanged);
00082
00083     // Create a holographic space for the core window for the current view.
00084     // Presenting holographic frames that are created by this holographic space will put
00085     // the app into exclusive mode.
00086     m_holographicSpace = HolographicSpace::CreateForCoreWindow(window);
00087
00088     // The DeviceResources class uses the preferred DXGI adapter ID from the holographic
00089     // space (when available) to create a Direct3D device. The HolographicSpace
00090     // uses this ID3D11Device to create and manage device-based resources such as
00091     // swap chains.
00092     m_deviceResources->SetHolographicSpace(m_holographicSpace);
00093
00094     // The main class uses the holographic space for updates and rendering.
00095     m_main->SetHolographicSpace(m_holographicSpace);
00096 }
00097
00098 // The Load method can be used to initialize scene resources or to load a
00099 // previously saved app state.
00100 void AppView::Load(Platform::String^ entryPoint)
00101 {
00102 }
00103
00104 // This method is called after the window becomes active. It oversees the
00105 // update, draw, and present loop, and it also oversees window message processing.
00106 void AppView::Run()
00107 {
00108     while (!m_windowClosed)
00109     {
00110         if (m_windowVisible)
00111         {
00112             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00113
00114             HolographicFrame^ holographicFrame = m_main->Update();
00115
00116             if (m_main->Render(holographicFrame))
00117             {
00118                 m_deviceResources->Present(holographicFrame);
00119             }
00120         }
00121         else
00122         {
00123             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00124         }
00125     }
00126 }
00127
00128 // Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
00129 // class is torn down while the app is in the foreground.
00130 // This method is not often used, but IFrameworkView requires it and it will be called for
00131 // holographic apps.
00132 void AppView::Uninitialize()
00133 {
00134
00135 }
00136
00137
00138 // Application lifecycle event handlers
00139
00140 // Called when the app view is activated. Activates the app's CoreWindow.
00141 void AppView::OnViewActivated(CoreApplicationView^ sender, IActivatedEventArgs^ args)
00142 {
00143     // Run() won't start until the CoreWindow is activated.
00144     sender->CoreWindow->Activate();
00145 }
00146
00147 void AppView::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
00148 {
00149     // Save app state asynchronously after requesting a deferral. Holding a deferral
00150     // indicates that the application is busy performing suspending operations. Be
00151     // aware that a deferral may not be held indefinitely; after about five seconds,
00152     // the app will be forced to exit.
00153     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
00154
00155     create_task([this, deferral] ()
00156     {
00157         m_deviceResources->Trim();
00158
00159         if (m_main != nullptr)
00160         {
00161             m_main->SaveAppState();
00162         }
00163
00164         deferral->Complete();
00165     });
00166 }
00167
00168 void AppView::OnResuming(Platform::Object^ sender, Platform::Object^ args)
00169 {
00170     // Restore any data or state that was unloaded on suspend. By default, data
00171     // and state are persisted when resuming from suspend. Note that this event
00172     // does not occur if the app was previously terminated.
00173
00174     if (m_main != nullptr)
00175     {
00176         m_main->LoadAppState();
00177     }
00178 }
00179
00180
00181 // Window event handlers
00182
00183 void AppView::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
00184 {
00185     m_windowVisible = args->Visible;
00186 }
00187
00188 void AppView::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
00189 {
00190     m_windowClosed = true;
00191 }
00192
00193
00194 // Input event handlers
00195
00196 void AppView::OnKeyPressed(CoreWindow^ sender, KeyEventArgs^ args)
00197 {
00198     // This code sample does not use keyboard input.
00199 }
Generated on Fri Nov 15 2024 22:16:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/cpp/SampleConfiguration.cpp Source File

  • SimpleCommunication
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Low Latency", "SDKTemplate.Scenario1_LowLatency" },
00021     { "Video Chat", "SDKTemplate.Scenario2_VideoChat" }
00022 };
00023
00024 Windows::Media::MediaExtensionManager^ MainPage::mediaExtensionManager;
Generated on Fri Nov 15 2024 22:17:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/xBindSampleModel/EmployeeCollection.cs Source File

  • XamlBind
  • cpp
  • xBindSampleModel

EmployeeCollection.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections;
00003 using System.Collections.Generic;
00004 using System.Collections.ObjectModel;
00005 using System.Collections.Specialized;
00006 using System.Linq;
00007 using Windows.Foundation.Collections;
00008
00009 namespace xBindSampleModel
00010 {
00011     public sealed class VectorChangedEventArgs : IVectorChangedEventArgs
00012     {
00013         public CollectionChange CollectionChange { get; set; }
00014         public uint Index { get; set; }
00015     }
00016
00017
00018     //Implements both IObservableVector and INotifyCollectionChanged and as its used from both C++ and C# apps
00019     public sealed class EmployeeCollection : Windows.Foundation.Collections.IObservableVector<IEmployee>, IList<IEmployee>, INotifyCollectionChanged, IList
00020     {
00021         private ObservableCollection<IEmployee> data;
00022         public event VectorChangedEventHandler<IEmployee> VectorChanged;
00023         public event NotifyCollectionChangedEventHandler CollectionChanged;
00024
00025         public EmployeeCollection()
00026         {
00027             data = new ObservableCollection<IEmployee>();
00028             data.CollectionChanged += Data_CollectionChanged;
00029         }
00030
00031         private void Data_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
00032         {
00033             if (VectorChanged != null)
00034             {
00035                 VectorChangedEventArgs args = new VectorChangedEventArgs();
00036                 args.CollectionChange = CollectionChange.Reset;
00037                 VectorChanged(this, args);
00038             }
00039
00040             if (CollectionChanged != null)
00041             {
00042                 CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
00043                 CollectionChanged(this, e);
00044             }
00045         }
00046
00047         #region IObservableVector
00048         //IObservableVector derives from IList<T> so most of the interface members are strongly typed
00049
00050         public IEmployee this[int index]
00051         {
00052             get { return data[index]; }
00053             set { data[index] = value; }
00054         }
00055
00056         public int Count { get { return data.Count; } }
00057         public bool IsReadOnly { get { return false; } }
00058
00059         public void Add(IEmployee item)
00060         {
00061             data.Add(item);
00062         }
00063
00064         public void Clear()
00065         {
00066             data.Clear();
00067         }
00068         public bool Contains(IEmployee item)
00069         {
00070             return data.Contains(item);
00071         }
00072
00073         public void CopyTo(IEmployee[] array, int arrayIndex)
00074         {
00075             data.CopyTo(array, arrayIndex);
00076         }
00077         public IEnumerator<IEmployee> GetEnumerator() { return data.GetEnumerator(); }
00078
00079         public int IndexOf(IEmployee item) { return data.IndexOf(item); }
00080
00081         public void Insert(int index, IEmployee item)
00082         {
00083             data.Insert(index, item);
00084         }
00085
00086         public bool Remove(IEmployee item)
00087         {
00088             return data.Remove(item);
00089         }
00090
00091         public void RemoveAt(int index)
00092         {
00093             data.RemoveAt(index);
00094         }
00095
00096         IEnumerator IEnumerable.GetEnumerator()
00097         {
00098             return data.GetEnumerator();
00099         }
00100         #endregion
00101
00102         #region INotifyCollectionChanged
00103         //INotifyCollection changed inherits from IList (non generic) so most of its members are not strongly typed
00104
00105         object IList.this[int index]
00106         {
00107             get { return data[index]; }
00108             set { data[index] = (Employee)value; }
00109         }
00110
00111         int ICollection.Count { get { return data.Count; } }
00112         bool IList.IsFixedSize { get { return false; } }
00113         bool ICollection.IsSynchronized { get { return false; } }
00114         object ICollection.SyncRoot { get { throw new NotImplementedException(); } }
00115
00116         int IList.Add(object item)
00117         {
00118             data.Add((IEmployee)item);
00119             return data.Count;
00120         }
00121
00122         bool IList.IsReadOnly { get { return false; } }
00123
00124         bool IList.Contains(object item) { return data.Contains(item); }
00125
00126         int IList.IndexOf(object item) { return data.IndexOf((IEmployee)item); }
00127
00128         void IList.Insert(int index, object item)
00129         {
00130             data.Insert(index, (IEmployee)item);
00131         }
00132
00133         void IList.Remove(object item)
00134         {
00135             data.Remove((IEmployee)item);
00136         }
00137
00138         void IList.Clear()
00139         {
00140             data.Clear();
00141         }
00142
00143         void IList.RemoveAt(int index)
00144         {
00145             data.RemoveAt(index);
00146         }
00147
00148         void ICollection.CopyTo(Array array, int index)
00149         {
00150             throw new NotImplementedException();
00151         }
00152         #endregion
00153     }
00154
00155     internal class MapChangedEventArgs<K> : IMapChangedEventArgs<K>
00156     {
00157         public CollectionChange CollectionChange { get; set; }
00158         public K Key { get; set; }
00159     }
00160
00161     public sealed class EmployeeDictionary : IObservableMap<string, IEmployee>
00162     {
00163         private Dictionary<string, IEmployee> data = new Dictionary<string, IEmployee>();
00164         #region IObservable MAP
00165         public event MapChangedEventHandler<string, IEmployee> MapChanged;
00166
00167         private void FireMapChanged(CollectionChange change, string key)
00168         {
00169             if (MapChanged != null)
00170             {
00171                 MapChanged(this, new MapChangedEventArgs<string>() { CollectionChange = change, Key = key });
00172             }
00173         }
00174
00175         #endregion
00176
00177         #region Generic Dictionary
00178         public IEmployee this[string key]
00179         {
00180             get
00181             {
00182                 return data[key];
00183             }
00184             set
00185             {
00186                 data[key] = value;
00187                 FireMapChanged(CollectionChange.ItemChanged, key);
00188             }
00189         }
00190
00191         public int Count { get { return data.Count; } }
00192
00193         public bool IsReadOnly { get { return false; } }
00194
00195         public ICollection<string> Keys { get { return data.Keys; } }
00196
00197         public ICollection<IEmployee> Values { get { return data.Values; } }
00198
00199         public void Add(KeyValuePair<string, IEmployee> item)
00200         {
00201             data.Add(item.Key, item.Value);
00202             FireMapChanged(CollectionChange.ItemInserted, item.Key);
00203         }
00204
00205         public void Add(string key, IEmployee value)
00206         {
00207             data.Add(key, value);
00208             FireMapChanged(CollectionChange.ItemInserted, key);
00209         }
00210
00211         public void Clear()
00212         {
00213             data.Clear();
00214             FireMapChanged(CollectionChange.Reset, default(string));
00215         }
00216
00217         public bool Contains(KeyValuePair<string, IEmployee> item) { return data.Contains(item); }
00218
00219         public bool ContainsKey(string key) { return data.ContainsKey(key); }
00220
00221         public void CopyTo(KeyValuePair<string, IEmployee>[] array, int arrayIndex)
00222         {
00223             var keys = data.Keys.GetEnumerator();
00224             var values = data.Values.GetEnumerator();
00225             for (int i = 0; i < data.Count; i++)
00226             {
00227                 KeyValuePair<string, IEmployee> pair = new KeyValuePair<string, IEmployee>(keys.Current, values.Current);
00228                 array[arrayIndex + i] = pair;
00229                 keys.MoveNext();
00230                 values.MoveNext();
00231             }
00232         }
00233
00234         public IEnumerator<KeyValuePair<string, IEmployee>> GetEnumerator() { return data.GetEnumerator(); }
00235
00236         public bool Remove(KeyValuePair<string, IEmployee> item) { return Remove(item.Key); }
00237
00238         public bool Remove(string key)
00239         {
00240             bool removed = data.Remove(key);
00241             if (removed) { FireMapChanged(CollectionChange.ItemRemoved, key); }
00242             return removed;
00243         }
00244
00245         public bool TryGetValue(string key, out IEmployee value)
00246         {
00247             return data.TryGetValue(key, out value);
00248         }
00249
00250         IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)data).GetEnumerator(); }
00251         #endregion
00252
00253     }
00254
00255 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks/ViewModel/TripViewModel.h Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks
  • ViewModel

TripViewModel.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012 #include "ViewModel\ViewModelBase.h"
00013
00014 namespace AdventureWorks
00015 {
00016     [Windows::UI::Xaml::Data::Bindable]
00017     [Windows::Foundation::Metadata::WebHostHidden]
00018     public ref class TripViewModel sealed : public ViewModelBase
00019     {
00020     public:
00021         TripViewModel(AdventureWorks_Shared::TripStore^ store);
00022
00023         property AdventureWorks_Shared::Trip^ Trip
00024         {
00025             AdventureWorks_Shared::Trip^ get();
00026             void set(AdventureWorks_Shared::Trip^ value);
00027         }
00028
00029         property Platform::String^ DestinationValidationError
00030         {
00031             Platform::String^ get();
00032         }
00033
00034         property bool ShowDestinationValidation
00035         {
00036             bool get();
00037         }
00038
00039         property bool ShowDelete
00040         {
00041             bool get();
00042         }
00043
00044         property Windows::UI::Xaml::Input::ICommand^ SaveTripCommand
00045         {
00046             Windows::UI::Xaml::Input::ICommand^ get();
00047         }
00048
00049         property Windows::UI::Xaml::Input::ICommand^ DeleteTripCommand
00050         {
00051             Windows::UI::Xaml::Input::ICommand^ get();
00052         }
00053
00054         void LoadTripFromStore(Platform::String^ destination);
00055         void ShowTrip(AdventureWorks_Shared::Trip^ trip);
00056         void NewTrip();
00057         void UpdateDestinationPhraseList();
00058
00059     private:
00060         AdventureWorks_Shared::Trip^ trip;
00061         AdventureWorks_Shared::TripStore^ store;
00062
00063         Windows::UI::Xaml::Input::ICommand^ saveTripCommand;
00064         Windows::UI::Xaml::Input::ICommand^ deleteTripCommand;
00065
00066         bool showDestinationValidation = true;
00067         Platform::String^ destinationValidationError;
00068
00069         bool showDelete = false;
00070
00071         void setDestinationValidation(Platform::String^ value);
00072         void setShowDestinationValidation(bool value);
00073         void setShowDelete(bool value);
00074
00075         void DeleteTrip();
00076         void SaveTrip();
00077
00078     };
00079 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/Scenario1.h Source File

  • FileAccess
  • cppwinrt

Scenario1.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     /// <summary>
00020     /// Creating a file.
00021     /// </summary>
00022     struct Scenario1 : Scenario1T<Scenario1>
00023     {
00024         Scenario1();
00025         fire_and_forget CreateFileButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00026
00027     private:
00028         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00029     };
00030 }
00031
00032 namespace winrt::SDKTemplate::factory_implementation
00033 {
00034     struct Scenario1 : Scenario1T<Scenario1, implementation::Scenario1>
00035     {
00036     };
00037 }
Generated on Fri Nov 15 2024 22:19:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/Common/Disposer.cs Source File

  • 360VideoPlayback
  • cs
  • Common

Disposer.cs

Go to the documentation of this file.
00001 using System;
00002
00003 namespace _360VideoPlayback.Common
00004 {
00005     // A base class that tracks resources allocated by native code. This class is
00006     // used to release COM references to DirectX resources.
00007     public abstract class Disposer : IDisposable
00008     {
00009         #region Public methods
00010
00011         // Releases resources allocated by native code (unmanaged resources).
00012         // All disposable objects that were added to the collection will be disposed of
00013         // when this method is called.
00014         public void Dispose()
00015         {
00016             if (!IsDisposed)
00017             {
00018                 Dispose(true);
00019                 IsDisposed = true;
00020             }
00021         }
00022
00023         #endregion
00024
00025         #region Protected methods and properties
00026
00027         protected internal Disposer()
00028         {
00029         }
00030
00031         // Indicates whether this instance is already disposed.
00032         protected internal bool IsDisposed { get; private set; }
00033
00034         // Disposes all IDisposable object resources in the collection of disposable
00035         // objects.
00036         //
00037         // NOTE: Since this class exists to dispose of unmanaged resources, the
00038         //       disposeManagedResources parameter is ignored.
00039         protected virtual void Dispose(bool disposeManagedResources)
00040         {
00041             // If the DisposeCollector exists, have it dispose of all COM objects.
00042             if (!IsDisposed && DisposeCollector != null)
00043             {
00044                 DisposeCollector.Dispose();
00045             }
00046
00047             // The DisposeCollector is done, and can be discarded.
00048             DisposeCollector = null;
00049         }
00050
00051         // Adds an IDisposable object to the collection of disposable objects.
00052         protected internal T ToDispose<T>(T objectToDispose)
00053         {
00054             // If objectToDispose is not null, add it to the collection.
00055             if (!ReferenceEquals(objectToDispose, null))
00056             {
00057                 // Create DisposeCollector if it doesn't already exist.
00058                 if (DisposeCollector == null)
00059                 {
00060                     DisposeCollector = new SharpDX.DisposeCollector();
00061                     IsDisposed = false;
00062                 }
00063
00064                 return DisposeCollector.Collect(objectToDispose);
00065             }
00066
00067             // Otherwise, return a default instance of type T.
00068             return default(T);
00069         }
00070
00071         // Disposes of an IDisposable object immediately and also removes the object from the
00072         // collection of disposable objects.
00073         protected internal void RemoveAndDispose<T>(ref T objectToDispose)
00074         {
00075             // If objectToDispose is not null, and if the DisposeCollector is available, have
00076             // the DisposeCollector get rid of objectToDispose.
00077             if (!ReferenceEquals(objectToDispose, null) && (DisposeCollector != null))
00078             {
00079                 DisposeCollector.RemoveAndDispose(ref objectToDispose);
00080             }
00081         }
00082
00083         // Removes an IDisposable object from the collection of disposable objects. Does not
00084         // dispose of the object before removing it.
00085         protected internal void RemoveToDispose<T>(T objectToRemove)
00086         {
00087             // If objectToRemove is not null, have the DisposeCollector forget about it.
00088             if (!ReferenceEquals(objectToRemove, null) && (DisposeCollector != null))
00089             {
00090                 DisposeCollector.Remove(objectToRemove);
00091             }
00092         }
00093
00094         #endregion
00095
00096         #region Private properties
00097
00098         // The collection of disposable objects.
00099         private SharpDX.DisposeCollector DisposeCollector { get; set; }
00100
00101         #endregion
00102     }
00103 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlMasterDetail/cppwinrt/pch.cpp Source File

  • XamlMasterDetail
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cpp/Scenario1_Advertiser.xaml.h Source File

  • WiFiDirect
  • cpp

Scenario1_Advertiser.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Advertiser.g.h"
00015 #include "MainPage.xaml.h"
00016 #include "SocketReaderWriter.h"
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class Scenario1_Advertiser sealed
00025     {
00026     public:
00027         Scenario1_Advertiser();
00028
00029         property Windows::Foundation::Collections::IObservableVector<ConnectedDevice^>^ _connectedDevices;
00030
00031     private:
00032         void Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033         void Button_Click_1(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void Button_Click_2(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         void Button_Click_3(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00036         void btnStartAdvertisement_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         void btnStopAdvertisement_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         void btnAddIe_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         void btnClose_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void btnSendMessage_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041
00042         void OnConnectionRequested(Windows::Devices::WiFiDirect::WiFiDirectConnectionListener^ sender, Windows::Devices::WiFiDirect::WiFiDirectConnectionRequestedEventArgs^ connectionEventArgs);
00043         void OnStatusChanged(Windows::Devices::WiFiDirect::WiFiDirectAdvertisementPublisher^ sender, Windows::Devices::WiFiDirect::WiFiDirectAdvertisementPublisherStatusChangedEventArgs^ statusEventArgs);
00044         void OnSocketConnectionReceived(Windows::Networking::Sockets::StreamSocketListener^ sender, Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs^ connectionReceivedEventArgs);
00045         void SDKTemplate::Scenario1_Advertiser::OnConnectionStatusChanged(Windows::Devices::WiFiDirect::WiFiDirectDevice^ sender, Platform::Object^ arg);
00046
00047         MainPage^ rootPage;
00048
00049         Windows::Devices::WiFiDirect::WiFiDirectAdvertisementPublisher^ _publisher;
00050         Windows::Devices::WiFiDirect::WiFiDirectConnectionListener^ _listener;
00051         Windows::Networking::Sockets::StreamSocketListener^ _listenerSocket;
00052
00053         Windows::Foundation::EventRegistrationToken _connectionRequestedToken;
00054         Windows::Foundation::EventRegistrationToken _statusChangedToken;
00055     };
00056 }
Generated on Fri Nov 15 2024 22:22:03 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cs/Scenario2_Stats.xaml.cs Source File

  • Calendar
  • cs

Scenario2_Stats.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.Foundation;
00013 using Windows.Globalization;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario2_Stats : Page
00020     {
00021         public Scenario2_Stats()
00022         {
00023             this.InitializeComponent();
00024         }
00025
00026         private string ReportCalendarData(Calendar calendar, string calendarLabel)
00027         {
00028             string results = calendarLabel + ": " + calendar.GetCalendarSystem() + "\n";
00029             results += "Months in this Year: " + calendar.NumberOfMonthsInThisYear + "\n";
00030             results += "Days in this Month: " + calendar.NumberOfDaysInThisMonth + "\n";
00031             results += "Hours in this Period: " + calendar.NumberOfHoursInThisPeriod + "\n";
00032             results += "Era: " + calendar.EraAsString() + "\n";
00033             results += "\n";
00034             return results;
00035         }
00036
00037         private void ShowResults_Click(object sender, RoutedEventArgs e)
00038         {
00039             // This scenario uses the Windows.Globalization.Calendar class to display the calendar
00040             // system statistics.
00041
00042             // Create Calendar objects using different constructors.
00043             Calendar calendar = new Calendar();
00044             Calendar japaneseCalendar = new Calendar(new[] { "ja-JP" }, CalendarIdentifiers.Japanese, ClockIdentifiers.TwelveHour);
00045             Calendar hebrewCalendar = new Calendar(new[] { "he-IL" }, CalendarIdentifiers.Hebrew, ClockIdentifiers.TwentyFourHour);
00046
00047             // Display results
00048             OutputTextBlock.Text =
00049                 ReportCalendarData(calendar, "User's default calendar system") +
00050                 ReportCalendarData(japaneseCalendar, "Calendar system") +
00051                 ReportCalendarData(hebrewCalendar, "Calendar system");
00052         }
00053     }
00054 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cpp/SampleConfiguration.h Source File

  • CustomCapability
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Custom Capability C++ sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/Common/BasicReaderWriter.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • Common

BasicReaderWriter.cpp

Go to the documentation of this file.
00001 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 // PARTICULAR PURPOSE.
00005 //
00006 // Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "BasicReaderWriter.h"
00010
00011 using namespace winrt::Windows::Storage;
00012 using namespace winrt::Windows::Storage::Streams;
00013 using namespace winrt::Windows::ApplicationModel;
00014
00015 BasicReaderWriter::BasicReaderWriter()
00016 {
00017     m_location = Package::Current().InstalledLocation();
00018 }
00019
00020 BasicReaderWriter::BasicReaderWriter(
00021     _In_ winrt::Windows::Storage::StorageFolder folder
00022     )
00023     : m_location(std::move(folder))
00024 {
00025     winrt::hstring path = m_location.Path();
00026     if (path.size() == 0)
00027     {
00028         // Applications are not permitted to access certain
00029         // folders, such as the Documents folder, using this
00030         // code path. In such cases, the Path property for
00031         // the folder will be an empty string.
00032         winrt::throw_hresult(E_FAIL);
00033     }
00034 }
00035
00036 std::vector<byte> BasicReaderWriter::ReadData(
00037     _In_ winrt::hstring const& filename
00038     )
00039 {
00040     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = { 0 };
00041     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00042     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00043     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00044     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00045     extendedParams.lpSecurityAttributes = nullptr;
00046     extendedParams.hTemplateFile = nullptr;
00047
00048     winrt::file_handle file{
00049         CreateFile2(
00050             filename.c_str(),
00051             GENERIC_READ,
00052             FILE_SHARE_READ,
00053             OPEN_EXISTING,
00054             &extendedParams
00055             )
00056     };
00057     winrt::check_bool(bool{ file });
00058     if (file.get() == INVALID_HANDLE_VALUE)
00059     {
00060         winrt::throw_hresult(E_FAIL);
00061     }
00062
00063     FILE_STANDARD_INFO fileInfo = { 0 };
00064     if (!GetFileInformationByHandleEx(
00065         file.get(),
00066         FileStandardInfo,
00067         &fileInfo,
00068         sizeof(fileInfo)
00069         ))
00070     {
00071         winrt::throw_hresult(E_FAIL);
00072     }
00073
00074     if (fileInfo.EndOfFile.HighPart != 0)
00075     {
00076         winrt::throw_hresult(E_OUTOFMEMORY);
00077     }
00078
00079     std::vector<byte> fileData(fileInfo.EndOfFile.LowPart);
00080
00081     if (!ReadFile(
00082         file.get(),
00083         fileData.data(),
00084         (DWORD)fileData.size(),
00085         nullptr,
00086         nullptr
00087         ))
00088     {
00089         winrt::throw_hresult(E_FAIL);
00090     }
00091
00092     return fileData;
00093 }
00094
00095 winrt::Windows::Foundation::IAsyncOperation<winrt::Windows::Storage::Streams::IBuffer> BasicReaderWriter::ReadDataAsync(
00096     _In_ winrt::hstring const& filename
00097     )
00098 {
00099     StorageFile file{ co_await m_location.GetFileAsync(filename) };
00100     co_return co_await FileIO::ReadBufferAsync(file);
00101 }
00102
00103 uint32_t BasicReaderWriter::WriteData(
00104     _In_ winrt::hstring const& filename,
00105     _In_ std::vector<byte> const& fileData
00106     )
00107 {
00108     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = { 0 };
00109     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00110     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00111     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00112     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00113     extendedParams.lpSecurityAttributes = nullptr;
00114     extendedParams.hTemplateFile = nullptr;
00115
00116     winrt::file_handle file{
00117         CreateFile2(
00118             filename.c_str(),
00119             GENERIC_WRITE,
00120             0,
00121             CREATE_ALWAYS,
00122             &extendedParams
00123             )
00124     };
00125     winrt::check_bool(bool{ file });
00126     if (file.get() == INVALID_HANDLE_VALUE)
00127     {
00128         winrt::throw_hresult(E_FAIL);
00129     }
00130
00131     DWORD numBytesWritten{ 0 };
00132     if (
00133         !WriteFile(
00134             file.get(),
00135             fileData.data(),
00136             (DWORD)fileData.size(),
00137             &numBytesWritten,
00138             nullptr
00139             ) ||
00140         numBytesWritten != fileData.size()
00141         )
00142     {
00143         winrt::throw_hresult(E_FAIL);
00144     }
00145
00146     return numBytesWritten;
00147 }
00148
00149 winrt::Windows::Foundation::IAsyncAction BasicReaderWriter::WriteDataAsync(
00150     _In_ winrt::hstring const& filename,
00151     _In_ std::vector<byte> const& fileData
00152     )
00153 {
00154     StorageFile file{ co_await m_location.CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting) };
00155     co_await FileIO::WriteBytesAsync(file, fileData);
00156 }
Generated on Fri Nov 15 2024 22:19:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ModelConstantBuffer Member List

This is the complete list of members for ModelConstantBuffer, including all inherited members.
modelToWorld ModelConstantBuffer
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/Project.idl Source File

  • FileAccess
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1 : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2 : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3 : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3();
00030     }
00031
00032     [default_interface]
00033     runtimeclass Scenario4 : Windows.UI.Xaml.Controls.Page
00034     {
00035         Scenario4();
00036     }
00037
00038     [default_interface]
00039     runtimeclass Scenario5 : Windows.UI.Xaml.Controls.Page
00040     {
00041         Scenario5();
00042     }
00043
00044     [default_interface]
00045     runtimeclass Scenario6 : Windows.UI.Xaml.Controls.Page
00046     {
00047         Scenario6();
00048     }
00049
00050     [default_interface]
00051     runtimeclass Scenario7 : Windows.UI.Xaml.Controls.Page
00052     {
00053         Scenario7();
00054     }
00055
00056     [default_interface]
00057     runtimeclass Scenario8 : Windows.UI.Xaml.Controls.Page
00058     {
00059         Scenario8();
00060     }
00061
00062     [default_interface]
00063     runtimeclass Scenario9 : Windows.UI.Xaml.Controls.Page
00064     {
00065         Scenario9();
00066     }
00067
00068     [default_interface]
00069     runtimeclass Scenario10 : Windows.UI.Xaml.Controls.Page
00070     {
00071         Scenario10();
00072     }
00073
00074     [default_interface]
00075     runtimeclass Scenario11 : Windows.UI.Xaml.Controls.Page
00076     {
00077         Scenario11();
00078     }
00079 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Badges/Local/PrimaryTile/SetBadgeGlyph/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Badges
  • Local
  • PrimaryTile
  • SetBadgeGlyph

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Windows.Data.Xml.Dom;
00002 using Windows.UI.Notifications;
00003 using Windows.UI.Xaml;
00004 using Windows.UI.Xaml.Controls;
00005
00006 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00007
00008 namespace Notifications.ScenarioPages.Badges.Local.PrimaryTile.SetBadgeGlyph
00009 {
00010     /// <summary>
00011     /// An empty page that can be used on its own or navigated to within a Frame.
00012     /// </summary>
00013     public sealed partial class ScenarioElement : UserControl
00014     {
00015         public ScenarioElement()
00016         {
00017             this.InitializeComponent();
00018         }
00019
00020         private void ButtonUpdateBadgeGlyph_Click(object sender, RoutedEventArgs e)
00021         {
00022             string badgeGlyphValue = ComboBoxBadgeGlyph.SelectedItem as string;
00023
00024             // Get the blank badge XML payload for a badge glyph
00025             XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeGlyph);
00026
00027             // Set the value of the badge in the XML to our glyph value
00028             XmlElement badgeElement = badgeXml.SelectSingleNode("/badge") as XmlElement;
00029             badgeElement.SetAttribute("value", badgeGlyphValue);
00030
00031             // Create the badge notification
00032             BadgeNotification badge = new BadgeNotification(badgeXml);
00033
00034             // Create the badge updater for the application
00035             BadgeUpdater badgeUpdater = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
00036
00037             // And update the badge
00038             badgeUpdater.Update(badge);
00039         }
00040     }
00041 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/App.xaml.h Source File

  • WindowsAudioSession
  • cpp

App.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "App.g.h"
00015
00016 namespace SDKSample
00017 {
00018     /// <summary>
00019     /// Provides application-specific behavior to supplement the default Application class.
00020     /// </summary>
00021     ref class App sealed
00022     {
00023     protected:
00024         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override;
00025
00026     internal:
00027         App();
00028
00029     private:
00030         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
00031         void OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e);
00032     };
00033 }
Generated on Fri Nov 15 2024 22:16:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DSvgImage/cpp/pch.cpp Source File

  • D2DSvgImage
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CashDrawer/cpp/Scenario2_CloseDrawer.xaml.cpp Source File

  • CashDrawer
  • cpp

Scenario2_CloseDrawer.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_CloseDrawer.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Media;
00027 using namespace Windows::UI::Xaml::Navigation;
00028 using namespace Windows::Devices::PointOfService;
00029 using namespace Windows::UI::Core;
00030
00031 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00032
00033 Scenario2_CloseDrawer::Scenario2_CloseDrawer() : rootPage(MainPage::Current)
00034 {
00035     InitializeComponent();
00036 }
00037
00038
00039 /// <summary>
00040 /// Invoked when this page is about to be displayed in a Frame.
00041 /// </summary>
00042 /// <param name="e">Event data that describes how this page was reached.</param>
00043 void Scenario2_CloseDrawer::OnNavigatedTo(NavigationEventArgs^ e)
00044 {
00045     ResetScenarioState();
00046 }
00047
00048
00049 /// <summary>
00050 /// Invoked before the page is unloaded and is no longer the current source of a Frame.
00051 /// </summary>
00052 /// <param name="e">Event data describing the navigation that was requested.</param>
00053 void Scenario2_CloseDrawer::OnNavigatedFrom(NavigationEventArgs^ e)
00054 {
00055     ResetScenarioState();
00056 }
00057
00058
00059 /// <summary>
00060 /// Event handler for Initialize Drawer button.
00061 /// Claims and enables the default cash drawer.
00062 /// </summary>
00063 /// <param name="sender">Button that was clicked.</param>
00064 /// <param name="e">Event data associated with click event.</param>
00065 void Scenario2_CloseDrawer::InitDrawerButton_Click(Object^ sender, RoutedEventArgs^ e)
00066 {
00067     create_task(CreateDefaultCashDrawerObject()).then([this](bool success)
00068     {
00069         if (!success)
00070         {
00071             rootPage->NotifyUser("Cash drawer not found. Please connect a cash drawer.", NotifyType::ErrorMessage);
00072             return;
00073         }
00074
00075         create_task(ClaimCashDrawer()).then([this](bool success)
00076         {
00077             if (!success)
00078             {
00079                 rootPage->NotifyUser("Failed to claim cash drawer.", NotifyType::ErrorMessage);
00080                 return;
00081             }
00082
00083             create_task(claimedDrawer->EnableAsync()).then([this](bool success)
00084             {
00085                 if (!success)
00086                 {
00087                     rootPage->NotifyUser("Failed to enable cash drawer.", NotifyType::ErrorMessage);
00088                     return;
00089                 }
00090
00091                 statusUpdatedToken = drawer->StatusUpdated::add(ref new TypedEventHandler<CashDrawer^, CashDrawerStatusUpdatedEventArgs^>
00092                     (this, &Scenario2_CloseDrawer::drawer_StatusUpdated));
00093
00094                 UpdateStatusOutput(drawer->Status->StatusKind);
00095                 rootPage->NotifyUser("Successfully enabled cash drawer. Device ID: " + claimedDrawer->DeviceId, NotifyType::StatusMessage);
00096
00097                 InitDrawerButton->IsEnabled = false;
00098                 DrawerWaitButton->IsEnabled = true;
00099             });
00100         });
00101     });
00102 }
00103
00104
00105 /// <summary>
00106 /// Set up an alarm and wait for the drawer to close.
00107 /// </summary>
00108 /// <param name="sender">Button that was clicked.</param>
00109 /// <param name="e">Event data associated with click event.</param>
00110 void Scenario2_CloseDrawer::WaitForDrawerCloseButton_Click(Object^ sender, RoutedEventArgs^ e)
00111 {
00112     if (claimedDrawer == nullptr)
00113     {
00114         rootPage->NotifyUser("Drawer must be initialized.", NotifyType::ErrorMessage);
00115         return;
00116     }
00117
00118
00119     CashDrawerCloseAlarm^ alarm = claimedDrawer->CloseAlarm;
00120     if (alarm == nullptr)
00121     {
00122         rootPage->NotifyUser("Failed to create drawer alarm.", NotifyType::ErrorMessage);
00123         return;
00124     }
00125
00126     if (!claimedDrawer->IsDrawerOpen)
00127     {
00128         rootPage->NotifyUser("Drawer is already closed.", NotifyType::StatusMessage);
00129     }
00130     else
00131     {
00132         TimeSpan alarmTimeSpan;
00133         alarmTimeSpan.Duration = 300000000L;    // 30 second alarm timeout
00134         alarm->AlarmTimeout = alarmTimeSpan;
00135
00136         alarmTimeSpan.Duration = 30000000L;     // 3 second delay
00137         alarm->BeepDelay = alarmTimeSpan;
00138
00139         alarmTimeSpan.Duration = 10000000L;     // 1 second duration
00140         alarm->BeepDuration = alarmTimeSpan;
00141
00142         alarm->BeepFrequency = 700;
00143         alarm->AlarmTimeoutExpired += ref new TypedEventHandler<CashDrawerCloseAlarm^, Platform::Object^>(this, &Scenario2_CloseDrawer::drawer_AlarmExpired);
00144
00145         rootPage->NotifyUser("Waiting for drawer to close.", NotifyType::StatusMessage);
00146
00147         create_task(alarm->StartAsync()).then([this](bool success)
00148         {
00149             if (success)
00150                 rootPage->NotifyUser("Successfully waited for drawer close.", NotifyType::StatusMessage);
00151             else
00152                 rootPage->NotifyUser("Failed to wait for drawer close.", NotifyType::ErrorMessage);
00153         });
00154     }
00155 }
00156
00157
00158 /// <summary>
00159 /// Creates the default cash drawer.
00160 /// </summary>
00161 /// <returns>True if the cash drawer was created, false otherwise.</returns>
00162 task<bool> Scenario2_CloseDrawer::CreateDefaultCashDrawerObject()
00163 {
00164     rootPage->NotifyUser("Creating cash drawer object.", NotifyType::StatusMessage);
00165
00166     return DeviceHelpers::GetFirstCashDrawerAsync().then([this](CashDrawer^ defaultDrawer)
00167     {
00168         if (defaultDrawer == nullptr)
00169             return false;
00170
00171         drawer = defaultDrawer;
00172         return true;
00173     });
00174 }
00175
00176
00177 /// <summary>
00178 /// Attempt to claim the connected cash drawer.
00179 /// </summary>
00180 /// <returns>True if the operation succeeds, false otherwise.</returns>
00181 task<bool> Scenario2_CloseDrawer::ClaimCashDrawer()
00182 {
00183     return create_task(drawer->ClaimDrawerAsync()).then([this](ClaimedCashDrawer^ claimed)
00184     {
00185         if (claimed == nullptr)
00186             return false;
00187
00188         claimedDrawer = claimed;
00189         return true;
00190     });
00191 }
00192
00193
00194 /// <summary>
00195 /// Event callback for device status updates.
00196 /// </summary>
00197 /// <param name="drawer">CashDrawer object sending the status update event.</param>
00198 /// <param name="e">Event data associated with the status update.</param>
00199 void Scenario2_CloseDrawer::drawer_StatusUpdated(CashDrawer^ sender, CashDrawerStatusUpdatedEventArgs^ e)
00200 {
00201     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, e]()
00202     {
00203         UpdateStatusOutput(e->Status->StatusKind);
00204         rootPage->NotifyUser("Status updated event: " + e->Status->StatusKind.ToString(), NotifyType::StatusMessage);
00205     }));
00206 }
00207
00208
00209 /// <summary>
00210 /// Event callback for the alarm expiring.
00211 /// </summary>
00212 /// <param name="alarm">CashDrawerCloseAlarm that has expired.</param>
00213 /// <param name="sender">Unused by AlarmTimeoutExpired events.</param>
00214 void Scenario2_CloseDrawer::drawer_AlarmExpired(CashDrawerCloseAlarm^ alarm, Object^ e)
00215 {
00216     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00217     {
00218         rootPage->NotifyUser("Alarm expired.  Still waiting for drawer to be closed.", NotifyType::StatusMessage);
00219     }));
00220 }
00221
00222
00223 /// <summary>
00224 /// Reset the scenario to its initial state.
00225 /// </summary>
00226 void Scenario2_CloseDrawer::ResetScenarioState()
00227 {
00228     if (drawer != nullptr)
00229     {
00230         drawer->StatusUpdated::remove(statusUpdatedToken);
00231
00232         delete drawer;
00233         drawer = nullptr;
00234     }
00235
00236     if (claimedDrawer != nullptr)
00237     {
00238         delete claimedDrawer;
00239         claimedDrawer = nullptr;
00240     }
00241
00242     InitDrawerButton->IsEnabled = true;
00243     DrawerWaitButton->IsEnabled = false;
00244
00245     rootPage->NotifyUser("Click the init drawer button to begin.", NotifyType::StatusMessage);
00246 }
00247
00248
00249 /// <summary>
00250 /// Update the cash drawer text block.
00251 /// </summary>
00252 /// <param name="status">Cash drawer status to be displayed.</param>
00253 void Scenario2_CloseDrawer::UpdateStatusOutput(CashDrawerStatusKind status)
00254 {
00255     DrawerStatusBlock->Text = status.ToString();
00256 }
00257
Generated on Fri Nov 15 2024 22:18:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AdvancedCaptureContext Member List

This is the complete list of members for AdvancedCaptureContext, including all inherited members.
__pad0__ | AdvancedCaptureContext
CaptureOrientation | AdvancedCaptureContext
Photo | AdvancedCaptureContext
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDeferLoadStrategy/cs/MainPage.xaml.cs Source File

  • XamlDeferLoadStrategy
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Data;
00017 using Windows.UI.Xaml.Media;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class MainPage : Page
00028     {
00029         public static MainPage Current;
00030
00031         public MainPage()
00032         {
00033             this.InitializeComponent();
00034
00035             // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00036             // in order to call methods that are in this class.
00037             Current = this;
00038             SampleTitle.Text = FEATURE_NAME;
00039         }
00040
00041         protected override void OnNavigatedTo(NavigationEventArgs e)
00042         {
00043             // Populate the scenario list from the SampleConfiguration.cs file
00044             ScenarioControl.ItemsSource = scenarios;
00045             if (Window.Current.Bounds.Width < 640)
00046             {
00047                 ScenarioControl.SelectedIndex = -1;
00048             }
00049             else
00050             {
00051                 ScenarioControl.SelectedIndex = 0;
00052             }
00053         }
00054
00055         /// <summary>
00056         /// Called whenever the user changes selection in the scenarios list.  This method will navigate to the respective
00057         /// sample scenario page.
00058         /// </summary>
00059         /// <param name="sender"></param>
00060         /// <param name="e"></param>
00061         private void ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
00062         {
00063             ListBox scenarioListBox = sender as ListBox;
00064             Scenario s = scenarioListBox.SelectedItem as Scenario;
00065             if (s != null)
00066             {
00067                 ScenarioFrame.Navigate(s.ClassType);
00068                 if (Window.Current.Bounds.Width < 640)
00069                 {
00070                     Splitter.IsPaneOpen = false;
00071                 }
00072             }
00073         }
00074
00075         public List<Scenario> Scenarios
00076         {
00077             get { return this.scenarios; }
00078         }
00079
00080         async void Footer_Click(object sender, RoutedEventArgs e)
00081         {
00082             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00083         }
00084
00085         private void Button_Click(object sender, RoutedEventArgs e)
00086         {
00087             Splitter.IsPaneOpen = (Splitter.IsPaneOpen == true) ? false : true;
00088         }
00089     }
00090     public enum NotifyType
00091     {
00092         StatusMessage,
00093         ErrorMessage
00094     };
00095
00096     public class ScenarioBindingConverter : IValueConverter
00097     {
00098         public object Convert(object value, Type targetType, object parameter, string language)
00099         {
00100             Scenario s = value as Scenario;
00101             return (MainPage.Current.Scenarios.IndexOf(s) + 1) + ") " + s.Title;
00102         }
00103
00104         public object ConvertBack(object value, Type targetType, object parameter, string language)
00105         {
00106             return true;
00107         }
00108     }
00109 }
00110
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisablingScreenCapture/cppwinrt/Scenario3_AppCapture.cpp Source File

  • DisablingScreenCapture
  • cppwinrt

Scenario3_AppCapture.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_AppCapture.h"
00014 #include "Scenario3_AppCapture.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace winrt::Windows::Foundation;
00018 using namespace winrt::Windows::Media::Capture;
00019 using namespace winrt::Windows::UI::Xaml;
00020 using namespace winrt::Windows::UI::Xaml::Controls;
00021 using namespace winrt::Windows::UI::Xaml::Navigation;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario3_AppCapture::Scenario3_AppCapture()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     void Scenario3_AppCapture::OnNavigatedTo(NavigationEventArgs const&)
00031     {
00032         appCapture = AppCapture::GetForCurrentView();
00033         capturingChangedToken = appCapture.CapturingChanged({ get_weak(), &Scenario3_AppCapture::AppCapture_CapturingChanged });
00034         UpdateCaptureStatus();
00035     }
00036
00037     void Scenario3_AppCapture::OnNavigatedFrom(NavigationEventArgs const&)
00038     {
00039         appCapture.CapturingChanged(capturingChangedToken);
00040
00041         // Re-enable app capture when navigating away.
00042         AppCapture::SetAllowedAsync(true);
00043     }
00044
00045     fire_and_forget Scenario3_AppCapture::AllowAppCaptureCheckBox_Toggled(IInspectable const& sender, RoutedEventArgs const&)
00046     {
00047         auto lifetime = get_strong();
00048         ToggleSwitch toggleSwitch = sender.as<ToggleSwitch>();
00049         co_await AppCapture::SetAllowedAsync(toggleSwitch.IsOn());
00050     }
00051
00052     void Scenario3_AppCapture::AppCapture_CapturingChanged(AppCapture const&, IInspectable const&)
00053     {
00054         UpdateCaptureStatus();
00055     }
00056
00057     void Scenario3_AppCapture::UpdateCaptureStatus()
00058     {
00059         hstring audioStatus = appCapture.IsCapturingAudio() ? L"Audio is being captured." : L"Audio is not being captured.";
00060         hstring videoStatus = appCapture.IsCapturingVideo() ? L"Video is being captured." : L"Video is not being captured.";
00061         rootPage.NotifyUser(audioStatus + L"\n" + videoStatus, NotifyType::StatusMessage);
00062     }
00063 }
Generated on Fri Nov 15 2024 22:19:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cs/SampleConfiguration.cs Source File

  • BackgroundActivation
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Foundation.Collections;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.ApplicationModel.Activation;
00018 using Windows.ApplicationModel.Background;
00019 using Windows.Storage;
00020 using Windows.UI.Xaml;
00021
00022 namespace SDKTemplate
00023 {
00024     public partial class MainPage : Page
00025     {
00026         public const string FEATURE_NAME = "Background Activation";
00027
00028         List<Scenario> scenarios = new List<Scenario>
00029         {
00030             new Scenario() { Title="Background Task", ClassType=typeof(SampleBackgroundTask)},
00031             new Scenario() { Title="Background Task with Condition", ClassType=typeof(SampleBackgroundTaskWithCondition)},
00032             new Scenario() { Title="Servicing Complete Task", ClassType=typeof(ServicingCompleteTask)},
00033             new Scenario() { Title="Background Task with Time Trigger", ClassType=typeof(TimeTriggeredTask) },
00034             new Scenario() { Title="Background Task with Application Trigger", ClassType=typeof(ApplicationTriggerTask) },
00035             new Scenario() { Title="Grouped Background Task", ClassType=typeof(GroupedBackgroundTask) },
00036         };
00037     }
00038
00039     public class Scenario
00040     {
00041         public string Title { get; set; }
00042         public Type ClassType { get; set; }
00043     }
00044 }
00045
00046 namespace SDKTemplate
00047 {
00048     class BackgroundTaskSample
00049     {
00050         public const string SampleBackgroundTaskName = "SampleBackgroundTask";
00051         public static string SampleBackgroundTaskProgress = "";
00052         public static bool SampleBackgroundTaskRegistered = false;
00053
00054         public const string SampleBackgroundTaskWithConditionName = "SampleBackgroundTaskWithCondition";
00055         public static string SampleBackgroundTaskWithConditionProgress = "";
00056         public static bool SampleBackgroundTaskWithConditionRegistered = false;
00057
00058         public const string ServicingCompleteTaskName = "ServicingCompleteTask";
00059         public static string ServicingCompleteTaskProgress = "";
00060         public static bool ServicingCompleteTaskRegistered = false;
00061
00062         public const string TimeTriggeredTaskName = "TimeTriggeredTask";
00063         public static string TimeTriggeredTaskProgress = "";
00064         public static bool TimeTriggeredTaskRegistered = false;
00065
00066         public const string ApplicationTriggerTaskName = "ApplicationTriggerTask";
00067         public static string ApplicationTriggerTaskProgress = "";
00068         public static string ApplicationTriggerTaskResult = "";
00069         public static bool ApplicationTriggerTaskRegistered = false;
00070
00071         public const string GroupedBackgroundTaskName = "GroupedBackgroundTask";
00072         public const string BackgroundTaskGroupId = "3F2504E0-5F89-41D3-9A0C-0405E82C3333";
00073         public const string BackgroundTaskGroupFriendlyName = "Background Task Group";
00074         public static string GroupedBackgroundTaskProgress = "";
00075         public static bool GroupedBackgroundTaskRegistered = false;
00076
00077         // These strings are manipulated by multiple threads, so we must
00078         // use a thread-safe container.
00079         public static PropertySet TaskStatuses = new PropertySet();
00080
00081         /// <summary>
00082         /// Register a background task with the specified taskEntryPoint, name, trigger,
00083         /// and condition (optional).
00084         /// </summary>
00085         /// <param name="taskEntryPoint">Task entry point for the background task.</param>
00086         /// <param name="name">A name for the background task.</param>
00087         /// <param name="trigger">The trigger for the background task.</param>
00088         /// <param name="condition">An optional conditional event that must be true for the task to fire.</param>
00089         public static BackgroundTaskRegistration RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition, BackgroundTaskRegistrationGroup group = null)
00090         {
00091             if (TaskRequiresBackgroundAccess(name))
00092             {
00093                 // If the user denies access, the task will not run.
00094                 var requestTask = BackgroundExecutionManager.RequestAccessAsync();
00095             }
00096
00097             var builder = new BackgroundTaskBuilder();
00098
00099             builder.Name = name;
00100
00101             if (taskEntryPoint != null)
00102             {
00103                 // If you leave the TaskEntryPoint at its default value, then the task runs
00104                 // inside the main process from OnBackgroundActivated rather than as a separate process.
00105                 builder.TaskEntryPoint = taskEntryPoint;
00106             }
00107
00108             builder.SetTrigger(trigger);
00109
00110             if (condition != null)
00111             {
00112                 builder.AddCondition(condition);
00113
00114                 //
00115                 // If the condition changes while the background task is executing then it will
00116                 // be canceled.
00117                 //
00118                 builder.CancelOnConditionLoss = true;
00119             }
00120
00121             if (group != null)
00122             {
00123                 builder.TaskGroup = group;
00124             }
00125
00126             BackgroundTaskRegistration task = builder.Register();
00127
00128             UpdateBackgroundTaskRegistrationStatus(name, true);
00129
00130             //
00131             // Remove previous completion status.
00132             //
00133             TaskStatuses.Remove(name);
00134
00135             return task;
00136         }
00137
00138         /// <summary>
00139         /// Unregister background tasks with specified name.
00140         /// </summary>
00141         /// <param name="name">Name of the background task to unregister.</param>
00142         public static void UnregisterBackgroundTasks(String name, BackgroundTaskRegistrationGroup group = null)
00143         {
00144             //
00145             // If the given task group is registered then loop through all background tasks associated with it
00146             // and unregister any with the given name.
00147             //
00148             if (group != null)
00149             {
00150                 foreach (var cur in group.AllTasks)
00151                 {
00152                     if (cur.Value.Name == name)
00153                     {
00154                         cur.Value.Unregister(true);
00155                     }
00156                 }
00157             }
00158             else
00159             {
00160                 //
00161                 // Loop through all ungrouped background tasks and unregister any with the given name.
00162                 //
00163                 foreach (var cur in BackgroundTaskRegistration.AllTasks)
00164                 {
00165                     if (cur.Value.Name == name)
00166                     {
00167                         cur.Value.Unregister(true);
00168                     }
00169                 }
00170             }
00171
00172             UpdateBackgroundTaskRegistrationStatus(name, false);
00173         }
00174
00175         /// <summary>
00176         /// Retrieve a registered background task group. If no group is registered with the given id,
00177         /// then create a new one and return it.
00178         /// </summary>
00179         /// <returns>The task group associated with the given id</returns>
00180         public static BackgroundTaskRegistrationGroup GetTaskGroup(string id, string groupName)
00181         {
00182             var group = BackgroundTaskRegistration.GetTaskGroup(id);
00183
00184             if (group == null)
00185             {
00186                 group = new BackgroundTaskRegistrationGroup(id, groupName);
00187             }
00188
00189             return group;
00190         }
00191
00192         /// <summary>
00193         /// Store the registration status of a background task with a given name.
00194         /// </summary>
00195         /// <param name="name">Name of background task to store registration status for.</param>
00196         /// <param name="registered">TRUE if registered, FALSE if unregistered.</param>
00197         public static void UpdateBackgroundTaskRegistrationStatus(String name, bool registered)
00198         {
00199             switch (name)
00200             {
00201                 case SampleBackgroundTaskName:
00202                     SampleBackgroundTaskRegistered = registered;
00203                     break;
00204                 case SampleBackgroundTaskWithConditionName:
00205                     SampleBackgroundTaskWithConditionRegistered = registered;
00206                     break;
00207                 case ServicingCompleteTaskName:
00208                     ServicingCompleteTaskRegistered = registered;
00209                     break;
00210                 case TimeTriggeredTaskName:
00211                     TimeTriggeredTaskRegistered = registered;
00212                     break;
00213                 case ApplicationTriggerTaskName:
00214                     ApplicationTriggerTaskRegistered = registered;
00215                     break;
00216                 case GroupedBackgroundTaskName:
00217                     GroupedBackgroundTaskRegistered = registered;
00218                     break;
00219             }
00220         }
00221
00222         /// <summary>
00223         /// Get the registration / completion status of the background task with
00224         /// given name.
00225         /// </summary>
00226         /// <param name="name">Name of background task to retreive registration status.</param>
00227         public static String GetBackgroundTaskStatus(String name)
00228         {
00229             var registered = false;
00230             switch (name)
00231             {
00232                 case SampleBackgroundTaskName:
00233                     registered = SampleBackgroundTaskRegistered;
00234                     break;
00235                 case SampleBackgroundTaskWithConditionName:
00236                     registered = SampleBackgroundTaskWithConditionRegistered;
00237                     break;
00238                 case ServicingCompleteTaskName:
00239                     registered = ServicingCompleteTaskRegistered;
00240                     break;
00241                 case TimeTriggeredTaskName:
00242                     registered = TimeTriggeredTaskRegistered;
00243                     break;
00244                 case ApplicationTriggerTaskName:
00245                     registered = ApplicationTriggerTaskRegistered;
00246                     break;
00247                 case GroupedBackgroundTaskName:
00248                     registered = GroupedBackgroundTaskRegistered;
00249                     break;
00250             }
00251
00252             var status = registered ? "Registered" : "Unregistered";
00253
00254             object taskStatus;
00255             if (TaskStatuses.TryGetValue(name, out taskStatus))
00256             {
00257                 status += " - " + taskStatus.ToString();
00258             }
00259
00260             return status;
00261         }
00262
00263         /// <summary>
00264         /// Determine if task with given name requires background access.
00265         /// </summary>
00266         /// <param name="name">Name of background task to query background access requirement.</param>
00267         public static bool TaskRequiresBackgroundAccess(String name)
00268         {
00269             if ((name == TimeTriggeredTaskName) ||
00270                 (name == ApplicationTriggerTaskName))
00271             {
00272                 return true;
00273             }
00274             else
00275             {
00276                 return false;
00277             }
00278         }
00279     }
00280 }
00281
00282
00283 namespace SDKTemplate
00284 {
00285     sealed partial class App : Application
00286     {
00287         /// <summary>
00288         /// Override the Application.OnBackgroundActivated method to handle background activation in
00289         /// the main process. This entry point is used when BackgroundTaskBuilder.TaskEntryPoint is
00290         /// not set during background task registration.
00291         /// </summary>
00292         /// <param name="args"></param>
00293         protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
00294         {
00295             BackgroundActivity.Start(args.TaskInstance);
00296         }
00297
00298         /// <summary>
00299         /// Register for grouped background task events in the Application constructor.
00300         /// </summary>
00301         partial void Construct()
00302         {
00303             var group = BackgroundTaskSample.GetTaskGroup(BackgroundTaskSample.BackgroundTaskGroupId, BackgroundTaskSample.BackgroundTaskGroupFriendlyName);
00304             group.BackgroundActivated += BackgroundActivity.Start;
00305         }
00306     }
00307 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cpp/Scenario1_Data.xaml.cpp Source File

  • Calendar
  • cpp

Scenario1_Data.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_Data.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Platform::Collections;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::Globalization;
00021
00022 Scenario1_Data::Scenario1_Data()
00023 {
00024     InitializeComponent();
00025 }
00026
00027 String^ Scenario1_Data::ReportCalendarData(Calendar^ calendar, String^ calendarLabel)
00028 {
00029     String^ results = calendarLabel + ": " + calendar->GetCalendarSystem() + "\n";
00030     results += "Name of Month: " + calendar->MonthAsSoloString() + "\n";
00031     results += "Day of Month: " + calendar->DayAsPaddedString(2) + "\n";
00032     results += "Day of Week: " + calendar->DayOfWeekAsSoloString() + "\n";
00033     results += "Year: " + calendar->YearAsString() + "\n";
00034     results += "\n";
00035     return results;
00036 }
00037
00038
00039 void Scenario1_Data::ShowResults_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00040 {
00041     // This scenario uses the Windows.Globalization.Calendar class to display the parts of a date.
00042
00043     // Create Calendar objects using different constructors.
00044     Calendar^ calendar = ref new Calendar();
00045     Calendar^ japaneseCalendar = ref new Calendar(ref new Vector<String^>({ "ja-JP" }), CalendarIdentifiers::Japanese, ClockIdentifiers::TwelveHour);
00046     Calendar^ hebrewCalendar = ref new Calendar(ref new Vector<String^>({ "he-IL" }), CalendarIdentifiers::Hebrew, ClockIdentifiers::TwentyFourHour);
00047
00048     // Display the results
00049     OutputTextBlock->Text =
00050         ReportCalendarData(calendar, "User's default calendar system") +
00051         ReportCalendarData(japaneseCalendar, "Calendar system") +
00052         ReportCalendarData(hebrewCalendar, "Calendar system");
00053 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cpp/Scenario5_SendData.xaml.cpp Source File

  • WiFiDirectServices
  • cpp

Scenario5_SendData.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario5_SendData.xaml.h"
00014
00015 using namespace SDKTemplate::WiFiDirectServices;
00016
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Core;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Media;
00027 using namespace Windows::UI::Xaml::Navigation;
00028 using namespace std;
00029
00030 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00031
00032 Scenario5::Scenario5() : _rootPage(MainPage::Current)
00033 {
00034     InitializeComponent();
00035 }
00036
00037 void Scenario5::AddSocket(SocketWrapper^ socket)
00038 {
00039     Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
00040         ref new DispatchedHandler([this, socket]()
00041         {
00042             lock_guard<mutex> lock(_mutex);
00043
00044             ConnectedSockets->Items->Append(socket);
00045         }));
00046 }
00047
00048 void Scenario5::RemoveSocket(unsigned int index)
00049 {
00050     Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
00051         ref new DispatchedHandler([this, index]()
00052         {
00053             lock_guard<mutex> lock(_mutex);
00054
00055             if (index > ConnectedSockets->Items->Size - 1)
00056             {
00057                 throw ref new OutOfBoundsException("Attempted to remove socket no longer in list");
00058             }
00059
00060             ConnectedSockets->Items->RemoveAt(index);
00061         }));
00062 }
00063
00064 void Scenario5::OnNavigatedTo(NavigationEventArgs^ e)
00065 {
00066     lock_guard<mutex> lock(_mutex);
00067
00068     MainUI->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00069     PlaceholderUI->Visibility = Windows::UI::Xaml::Visibility::Visible;
00070
00071     _session = WiFiDirectServiceManager::Instance->CurrentSession;
00072
00073     if (_session != nullptr)
00074     {
00075         AdvertisementId->Text = _session->AdvertisementId.ToString();
00076         ServiceAddress->Text = _session->ServiceAddress;
00077         SessionId->Text = _session->SessionId.ToString();
00078         SessionAddress->Text = _session->SessionAddress;
00079         SessionStatus->Text = _session->Session->Status.ToString();
00080
00081         ConnectedSockets->Items->Clear();
00082         for (auto&& socket : _session->SocketList)
00083         {
00084             ConnectedSockets->Items->Append(socket);
00085         }
00086
00087         MainUI->Visibility = Windows::UI::Xaml::Visibility::Visible;
00088         PlaceholderUI->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00089     }
00090     else
00091     {
00092         AdvertisementId->Text = "##";
00093         ServiceAddress->Text = "XX:XX:XX:XX:XX:XX";
00094         SessionId->Text = "##";
00095         SessionAddress->Text = "XX:XX:XX:XX:XX:XX";
00096         SessionStatus->Text = "???";
00097
00098         ConnectedSockets->Items->Clear();
00099     }
00100
00101     WiFiDirectServiceManager::Instance->CurrentScenario5 = this;
00102 }
00103
00104 void Scenario5::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
00105 {
00106     WiFiDirectServiceManager::Instance->CurrentScenario5 = nullptr;
00107 }
00108
00109 void Scenario5::AddPort_Click(Object^ sender, RoutedEventArgs^ e)
00110 {
00111     if (_session != nullptr)
00112     {
00113         unsigned short port = 0;
00114         if (Port->Text->Length() > 0)
00115         {
00116             wistringstream ss(Port->Text->Data());
00117             ss >> port;
00118
00119             // Create socket asynchronously, will get callback when it is complete to add the socket to the list
00120             Concurrency::task<void> addPortTask;
00121             if ((dynamic_cast<ComboBoxItem^>(Protocol->SelectedItem))->Content->ToString() == "TCP")
00122             {
00123                 addPortTask = _session->AddStreamSocketListenerAsync(port);
00124             }
00125             else
00126             {
00127                 addPortTask = _session->AddDatagramSocketAsync(port);
00128             }
00129
00130             addPortTask.then([this](Concurrency::task<void> previousTask)
00131             {
00132                 try
00133                 {
00134                     // Try getting all exceptions from the continuation chain above this point.
00135                     previousTask.get();
00136                 }
00137                 catch (Exception^ ex)
00138                 {
00139                     _rootPage->NotifyUser("Add Socket Failed: " + ex->Message, NotifyType::ErrorMessage);
00140                 }
00141             });
00142         }
00143     }
00144 }
00145
00146 void Scenario5::DoSend_Click(Object^ sender, RoutedEventArgs^ e)
00147 {
00148     if (ConnectedSockets->Items->Size > 0 && _session != nullptr)
00149     {
00150         int index = ConnectedSockets->SelectedIndex;
00151         if (index >= 0)
00152         {
00153             String^ message = SendData->Text;
00154             SendData->Text = "";
00155
00156             _session->SocketList->GetAt(index)->SendMessageAsync(message)
00157             .then([this](Concurrency::task<void> previousTask)
00158             {
00159                 try
00160                 {
00161                     // Try getting all exceptions from the continuation chain above this point.
00162                     previousTask.get();
00163                 }
00164                 catch (Exception^ ex)
00165                 {
00166                     _rootPage->NotifyUser("SendMessageAsync Failed: " + ex->Message, NotifyType::ErrorMessage);
00167                 }
00168             });
00169         }
00170     }
00171 }
Generated on Fri Nov 15 2024 22:22:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlMasterDetail/cppwinrt/App.cpp Source File

  • XamlMasterDetail
  • cppwinrt

App.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "App.h"
00014 #include "MasterDetailPage.h"
00015 #include "DetailPage.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::ApplicationModel::Activation;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021 using namespace Windows::UI::Xaml::Navigation;
00022 using namespace MasterDetailApp;
00023 using namespace MasterDetailApp::implementation;
00024
00025 /// <summary>
00026 /// Initializes the singleton application object.  This is the first line of authored code
00027 /// executed, and as such is the logical equivalent of main() or WinMain().
00028 /// </summary>
00029 App::App()
00030 {
00031     InitializeComponent();
00032
00033 #if defined _DEBUG && !defined DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
00034     UnhandledException([this](IInspectable const&, UnhandledExceptionEventArgs const& e)
00035         {
00036             if (IsDebuggerPresent())
00037             {
00038                 auto errorMessage = e.Message();
00039                 __debugbreak();
00040             }
00041         });
00042 #endif
00043
00044     DetailPage::RegisterDependencyProperties();
00045 }
00046
00047 /// <summary>
00048 /// Invoked when the application is launched normally by the end user.  Other entry points
00049 /// will be used such as when the application is launched to open a specific file.
00050 /// </summary>
00051 /// <param name="e">Details about the launch request and process.</param>
00052 void App::OnLaunched(LaunchActivatedEventArgs const&)
00053 {
00054     Frame rootFrame = CreateRootFrame();
00055     if (rootFrame.Content() == nullptr)
00056     {
00057         rootFrame.Navigate(xaml_typename<MasterDetailApp::MasterDetailPage>());
00058     }
00059
00060     // Ensure the current window is active
00061     Window::Current().Activate();
00062 }
00063
00064 Frame App::CreateRootFrame()
00065 {
00066     Frame rootFrame{ nullptr };
00067     auto content = Window::Current().Content();
00068     if (content)
00069     {
00070         rootFrame = content.try_as<Frame>();
00071     }
00072
00073     // Do not repeat app initialization when the Window already has content,
00074     // just ensure that the window is active
00075     if (rootFrame == nullptr)
00076     {
00077         // Create a Frame to act as the navigation context
00078         rootFrame = Frame();
00079
00080         rootFrame.NavigationFailed({ this, &App::OnNavigationFailed });
00081
00082         // Place the frame in the current Window
00083         Window::Current().Content(rootFrame);
00084     }
00085
00086     return rootFrame;
00087 }
00088
00089 /// <summary>
00090 /// Invoked when Navigation to a certain page fails
00091 /// </summary>
00092 /// <param name="sender">The Frame which failed navigation</param>
00093 /// <param name="e">Details about the navigation failure</param>
00094 void App::OnNavigationFailed(IInspectable const&, NavigationFailedEventArgs const& e)
00095 {
00096     throw hresult_error(E_FAIL, hstring(L"Failed to load Page ") + e.SourcePageType().Name);
00097 }
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FolderEnumeration/cppwinrt/Scenario1.cpp Source File

  • FolderEnumeration
  • cppwinrt

Scenario1.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1.h"
00014 #include "Scenario1.g.cpp"
00015 #include <sstream>
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::Storage;
00021 using namespace Windows::UI::Xaml;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario1::Scenario1()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     fire_and_forget Scenario1::GetFilesAndFoldersButton_Click(IInspectable const&, RoutedEventArgs const&)
00031     {
00032         auto lifetime = get_strong();
00033
00034         StorageFolder picturesFolder = co_await KnownFolders::GetFolderForUserAsync(nullptr /* current user */, KnownFolderId::PicturesLibrary);
00035         IVectorView<StorageFile> fileList = co_await picturesFolder.GetFilesAsync();
00036         IVectorView<StorageFolder> folderList = co_await picturesFolder.GetFoldersAsync();
00037
00038         uint32_t count = fileList.Size() + folderList.Size();
00039
00040         std::wstringstream output;
00041         output << std::wstring_view{ picturesFolder.Name() } << L" (" << count << L")\n\n";
00042
00043         for (StorageFolder const& folder : folderList)
00044         {
00045             output << L"    " << std::wstring_view{ folder.DisplayName() } << L"\\" << std::endl;
00046         }
00047
00048         for (StorageFile const& file : fileList)
00049         {
00050             output << L"    " << std::wstring{ file.Name() } << std::endl;
00051         }
00052
00053         OutputTextBlock().Text(output.str());
00054     }
00055 }
Generated on Fri Nov 15 2024 22:19:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/AppView.h Source File

  • SpatialInteractionSource
  • cpp

AppView.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "Common\DeviceResources.h"
00004 #include "HolographicPaintMain.h"
00005
00006 namespace HolographicPaint
00007 {
00008     // IFrameworkView class. Connects the app with the Windows shell and handles application lifecycle events.
00009     ref class AppView sealed : public Windows::ApplicationModel::Core::IFrameworkView
00010     {
00011     public:
00012         AppView();
00013
00014         // IFrameworkView methods.
00015         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00016         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00017         virtual void Load(Platform::String^ entryPoint);
00018         virtual void Run();
00019         virtual void Uninitialize();
00020
00021     protected:
00022         // Application lifecycle event handlers.
00023         void OnViewActivated(Windows::ApplicationModel::Core::CoreApplicationView^ sender, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00024         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00025         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00026
00027         // Window event handlers.
00028         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00029         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00030
00031         // CoreWindow input event handlers.
00032         void OnKeyPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args);
00033
00034     private:
00035         std::unique_ptr<HolographicPaintMain> m_main;
00036
00037         std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00038         bool                                                m_windowClosed  = false;
00039         bool                                                m_windowVisible = true;
00040
00041         // The holographic space the app will use for rendering.
00042         Windows::Graphics::Holographic::HolographicSpace^   m_holographicSpace = nullptr;
00043     };
00044
00045     // The entry point for the app.
00046     ref class AppViewSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00047     {
00048     public:
00049         virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00050     };
00051 }
00052
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/MainPage.xaml.cs Source File

  • 360VideoPlayback
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Core;
00002 using Windows.UI.Xaml.Controls;
00003
00004 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00005
00006 namespace _360VideoPlayback
00007 {
00008     /// <summary>
00009     /// An empty page that can be used on its own or navigated to within a Frame.
00010     /// </summary>
00011     public sealed partial class MainPage : Page
00012     {
00013         public MainPage()
00014         {
00015             this.InitializeComponent();
00016             SystemNavigationManager.GetForCurrentView().BackRequested += MainPage_BackRequested;
00017             this.contentFrame.Navigate(typeof(VideoGallery));
00018         }
00019
00020         private void MainPage_BackRequested(object sender, BackRequestedEventArgs e)
00021         {
00022             goBack(null, e);
00023         }
00024
00025         private void goBack(object sender, BackRequestedEventArgs e)
00026         {
00027             if (this.contentFrame.CanGoBack)
00028             {
00029                 this.contentFrame.GoBack();
00030                 e.Handled = true;
00031             }
00032         }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundSensors/cs/BackgroundTask/Properties/AssemblyInfo.cs Source File

  • BackgroundSensors
  • cs
  • BackgroundTask
  • Properties

AssemblyInfo.cs

Go to the documentation of this file.
00001 ﻿using System.Reflection;
00002 using System.Runtime.CompilerServices;
00003 using System.Runtime.InteropServices;
00004
00005 // General Information about an assembly is controlled through the following
00006 // set of attributes. Change these attribute values to modify the information
00007 // associated with an assembly.
00008 [assembly: AssemblyTitle("Background Tasks for the BackgroundSensors C# Windows Phone sample")]
00009 [assembly: AssemblyDescription("")]
00010 [assembly: AssemblyConfiguration("")]
00011 [assembly: AssemblyCompany("Microsoft Corporation")]
00012 [assembly: AssemblyProduct("")]
00013 [assembly: AssemblyCopyright("")]
00014 [assembly: AssemblyTrademark("")]
00015 [assembly: AssemblyCulture("")]
00016
00017 // Version information for an assembly consists of the following four values:
00018 //
00019 //      Major Version
00020 //      Minor Version
00021 //      Build Number
00022 //      Revision
00023 //
00024 // You can specify all the values or you can default the Build and Revision Numbers
00025 // by using the '*' as shown below:
00026 // [assembly: AssemblyVersion("1.0.*")]
00027 [assembly: AssemblyVersion("1.0.0.0")]
00028 [assembly: AssemblyFileVersion("1.0.0.0")]
00029 [assembly: ComVisible(false)]
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cpp/Scenario3_SingleFolder.xaml.h Source File

  • FilePicker
  • cpp

Scenario3_SingleFolder.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario3_SingleFolder.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     public ref class Scenario3_SingleFolder sealed
00021     {
00022     public:
00023         Scenario3_SingleFolder();
00024
00025     private:
00026         MainPage^ rootPage;
00027
00028         void PickFolderButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029     };
00030 }
Generated on Fri Nov 15 2024 22:19:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cpp/Scenario2_Remove.xaml.cpp Source File

  • JumpList
  • cpp

Scenario2_Remove.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario2_Remove.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace concurrency;
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::StartScreen;
00023
00024 Scenario2_Remove::Scenario2_Remove()
00025 {
00026     InitializeComponent();
00027 }
00028
00029 void Scenario2_Remove::RemoveJumpList_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00030 {
00031   create_task(JumpList::LoadCurrentAsync()).then([this](JumpList^ jumpList) -> IAsyncAction^
00032   {
00033     jumpList->SystemGroupKind = JumpListSystemGroupKind::None;
00034     jumpList->Items->Clear();
00035     return jumpList->SaveAsync();
00036   }, task_continuation_context::use_arbitrary());
00037 }
Generated on Fri Nov 15 2024 22:20:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlMasterDetail/cs/Data/Item.cs Source File

  • XamlMasterDetail
  • cs
  • Data

Item.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006
00007 namespace MasterDetailApp.Data
00008 {
00009     public class Item
00010     {
00011         public int Id { get; set; }
00012         public DateTime DateCreated { get; set; }
00013         public string Title { get; set; }
00014         public string Text { get; set; }
00015     }
00016 }
Generated on Fri Nov 15 2024 22:22:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Cylinder.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Cylinder.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Cylinder.h"
00014
00015 using namespace DirectX;
00016
00017 Cylinder::Cylinder()
00018 {
00019     Initialize(XMFLOAT3(0.0f, 0.0f, 0.0f), 1.0f, XMFLOAT3(0.0f, 0.0f, 1.0f));
00020 }
00021
00022 Cylinder::Cylinder(
00023     XMFLOAT3 position,
00024     float radius,
00025     XMFLOAT3 direction
00026     )
00027 {
00028     Initialize(position, radius, direction);
00029 }
00030
00031 void Cylinder::Initialize(
00032     XMFLOAT3 position,
00033     float radius,
00034     XMFLOAT3 direction
00035     )
00036 {
00037     m_position = position;
00038     m_radius = radius;
00039     m_length = XMVectorGetX(XMVector3Length(XMLoadFloat3(&direction)));
00040     XMStoreFloat3(&m_axis, XMVector3Normalize(XMLoadFloat3(&direction)));
00041
00042     XMVECTOR up = XMVectorSet(0.0f, 0.0f, 1.0f, 1.0f);
00043     float angle1 = XMVectorGetX(
00044         XMVector3AngleBetweenVectors(up, XMLoadFloat3(&m_axis))
00045         );
00046
00047     XMMATRIX mat1 = XMMatrixIdentity();
00048
00049     if ((angle1 * angle1) > 0.025)
00050     {
00051         XMVECTOR axis1 = XMVector3Cross(up, XMLoadFloat3(&m_axis));
00052
00053         mat1 = XMMatrixRotationAxis(axis1, angle1);
00054     }
00055     XMStoreFloat4x4(&m_rotationMatrix, mat1);
00056
00057     XMStoreFloat4x4(
00058         &m_modelMatrix,
00059         XMMatrixScaling(m_radius, m_radius, m_length) *
00060         mat1 *
00061         XMMatrixTranslation(m_position.x, m_position.y, m_position.z)
00062         );
00063 }
00064
00065 void Cylinder::UpdatePosition()
00066 {
00067     XMStoreFloat4x4(
00068         &m_modelMatrix,
00069         XMMatrixScaling(m_radius, m_radius, m_length) *
00070         XMLoadFloat4x4(&m_rotationMatrix) *
00071         XMMatrixTranslation(m_position.x, m_position.y, m_position.z)
00072         );
00073 }
00074
00075 bool Cylinder::IsTouching(
00076     XMFLOAT3 point,
00077     float radius,
00078     _Out_ XMFLOAT3* contact,
00079     _Out_ XMFLOAT3* normal
00080     )
00081 {
00082     XMVECTOR p0;
00083     XMVECTOR axis;
00084     XMVECTOR p1;
00085     XMVECTOR px;
00086
00087     // Determine if a point is within radius distance of the cylinder and
00088     // return the point of contact (projection of the point onto the cylinder).
00089
00090     p0 = XMLoadFloat3(&m_position);
00091     axis = XMLoadFloat3(&m_axis);
00092     p1 = p0 + axis * m_length;
00093     px = XMLoadFloat3(&point);
00094
00095     float dist = XMVectorGetX(
00096         XMVector3LinePointDistance(p0, p1, px)
00097         );
00098
00099     // Projection of the point onto the Vector.
00100     float dist2 = XMVectorGetX(
00101         XMVector3Dot(px - p0, axis)
00102         );
00103
00104     XMVECTOR ptOnVector = p0 + dist2 * axis;
00105
00106     XMVECTOR normalVector = XMVector3Normalize(px - ptOnVector);
00107
00108     XMStoreFloat3(normal, normalVector);
00109     XMStoreFloat3(contact, ptOnVector + normalVector * m_radius);
00110
00111     if (dist < 0.0f)
00112     {
00113         dist *= -1.0f;
00114     }
00115
00116     if (dist < (radius + m_radius))
00117     {
00118         if (dist2 >= 0.0f && dist2 <= m_length)
00119         {
00120             return true;
00121         }
00122         else
00123         {
00124             return false;
00125         }
00126     }
00127     return false;
00128 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cpp/Scenario1_Data.xaml.h Source File

  • Calendar
  • cpp

Scenario1_Data.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Data.g.h"
00015
00016 namespace SDKTemplate
00017 {
00018     [Windows::Foundation::Metadata::WebHostHidden]
00019     public ref class Scenario1_Data sealed
00020     {
00021     public:
00022         Scenario1_Data();
00023         void ShowResults_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00024
00025     private:
00026         Platform::String^ ReportCalendarData(Windows::Globalization::Calendar^ calendar, Platform::String^ calendarLabel);
00027     };
00028 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: GlobalizationPreferences/cppwinrt/Scenario3_Region.cpp Source File

  • GlobalizationPreferences
  • cppwinrt

Scenario3_Region.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_Region.h"
00014 #include "Scenario3_Region.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Globalization;
00020 using namespace Windows::UI::Xaml;
00021
00022 namespace
00023 {
00024     hstring ReportRegionData(GeographicRegion const& region)
00025     {
00026         return L"Display Name: " + region.DisplayName() + L"\n" +
00027             L"Native Name: " + region.NativeName() + L"\n" +
00028             L"Currencies in use: " + SDKTemplate::StringJoin(L", ", region.CurrenciesInUse()) + L"\n" +
00029             L"Codes: " + region.CodeTwoLetter() + L", " + region.CodeThreeLetter() + L", " + region.CodeThreeDigit() + L"\n\n";
00030     }
00031
00032 }
00033 namespace winrt::SDKTemplate::implementation
00034 {
00035     Scenario3_Region::Scenario3_Region()
00036     {
00037         InitializeComponent();
00038     }
00039
00040     void Scenario3_Region::ShowResults_Click(IInspectable const&, RoutedEventArgs const&)
00041     {
00042         // This scenario uses the Windows.Globalization.GeographicRegion class to
00043         // obtain the geographic region characteristics.
00044         GeographicRegion userGeoRegion;
00045
00046         // This obtains the geographic region characteristics by providing a country or region code.
00047         GeographicRegion exampleGeoRegion(L"JP");
00048
00049         // Display the results
00050         OutputTextBlock().Text(L"User's Preferred Geographic Region\n" + ReportRegionData(userGeoRegion) +
00051             L"Example Geographic Region by region/country code (JP)\n" + ReportRegionData(exampleGeoRegion));
00052     }
00053 }
Generated on Fri Nov 15 2024 22:19:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

OcrFileImage Member List

This is the complete list of members for OcrFileImage, including all inherited members.
bitmap | OcrFileImage | [private]
ClearResults() | OcrFileImage | [inline, private]
ExtractButton_Click(object sender, RoutedEventArgs e) | OcrFileImage | [inline, private]
LanguageList_SelectionChanged(object sender, SelectionChangedEventArgs e) | OcrFileImage | [inline, private]
LoadButton_Click(object sender, RoutedEventArgs e) | OcrFileImage | [inline, private]
LoadImageAsync(StorageFile file) | OcrFileImage | [inline, private]
LoadSampleImageAsync() | OcrFileImage | [inline, private]
OcrFileImage() | OcrFileImage | [inline]
OnNavigatedTo(NavigationEventArgs e) | OcrFileImage | [inline, protected]
PreviewImage_SizeChanged(object sender, SizeChangedEventArgs e) | OcrFileImage | [inline, private]
rootPage | OcrFileImage | [private]
SampleButton_Click(object sender, RoutedEventArgs e) | OcrFileImage | [inline, private]
UpdateAvailableLanguages() | OcrFileImage | [inline, private]
UpdateWordBoxTransform() | OcrFileImage | [inline, private]
UserLanguageToggle_Toggled(object sender, Windows.UI.Xaml.RoutedEventArgs e) | OcrFileImage | [inline, private]
wordBoxes | OcrFileImage | [private]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/MainPage.xaml.cpp Source File

  • WindowsAudioSession
  • cpp

MainPage.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014
00015 using namespace SDKSample;
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021 using namespace Windows::UI::Xaml::Controls::Primitives;
00022 using namespace Windows::UI::Xaml::Data;
00023 using namespace Windows::UI::Xaml::Input;
00024 using namespace Windows::UI::Xaml::Media;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::UI::Xaml::Interop;
00027
00028 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00029
00030 MainPage^ MainPage::Current = nullptr;
00031
00032 MainPage::MainPage()
00033 {
00034     InitializeComponent();
00035     SampleTitle->Text = FEATURE_NAME;
00036
00037     // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00038     // in order to call methods that are in this class.
00039     MainPage::Current = this;
00040 }
00041
00042 void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // Populate the ListBox with the scenarios as defined in SampleConfiguration.cpp.
00045     auto itemCollection = ref new Platform::Collections::Vector<Object^>();
00046     int i = 1;
00047     for (auto const& s : MainPage::Current->scenarios)
00048     {
00049         // Create a textBlock to hold the content and apply the ListItemTextStyle from Styles.xaml
00050         TextBlock^ textBlock = ref new TextBlock();
00051         ListBoxItem^ item = ref new ListBoxItem();
00052         auto style = App::Current->Resources->Lookup("ListItemTextStyle");
00053
00054         textBlock->Text = (i++).ToString() + ") " + s.Title;
00055         textBlock->Style = safe_cast<Windows::UI::Xaml::Style ^>(style);
00056
00057         item->Name = s.ClassName;
00058         item->Content = textBlock;
00059         itemCollection->Append(item);
00060     }
00061
00062     // Set the newly created itemCollection as the ListBox ItemSource.
00063     ScenarioControl->ItemsSource = itemCollection;
00064     int startingScenarioIndex;
00065
00066     if (Window::Current->Bounds.Width < 640)
00067     {
00068         startingScenarioIndex = -1;
00069     }
00070     else
00071     {
00072         startingScenarioIndex = 0;
00073     }
00074
00075     ScenarioControl->SelectedIndex = startingScenarioIndex;
00076     ScenarioControl->ScrollIntoView(ScenarioControl->SelectedItem);
00077 }
00078
00079
00080 void MainPage::ScenarioControl_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00081 {
00082     ListBox^ scenarioListBox = safe_cast<ListBox^>(sender); //as ListBox;
00083     ListBoxItem^ item = dynamic_cast<ListBoxItem^>(scenarioListBox->SelectedItem);
00084     if (item != nullptr)
00085     {
00086         // Clear the status block when changing scenarios
00087         NotifyUser("", NotifyType::StatusMessage);
00088
00089         // Navigate to the selected scenario.
00090         TypeName scenarioType = { item->Name, TypeKind::Custom };
00091         ScenarioFrame->Navigate(scenarioType, this);
00092
00093         if (Window::Current->Bounds.Width < 640)
00094         {
00095             Splitter->IsPaneOpen = false;
00096             StatusBorder->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00097         }
00098     }
00099 }
00100
00101 void MainPage::NotifyUser(String^ strMessage, NotifyType type)
00102 {
00103     switch (type)
00104     {
00105     case NotifyType::StatusMessage:
00106         StatusBorder->Background = ref new SolidColorBrush(Windows::UI::Colors::Green);
00107         break;
00108     case NotifyType::ErrorMessage:
00109         StatusBorder->Background = ref new SolidColorBrush(Windows::UI::Colors::Red);
00110         break;
00111     default:
00112         break;
00113     }
00114     StatusBlock->Text = strMessage;
00115
00116     // Collapse the StatusBlock if it has no text to conserve real estate.
00117     if (StatusBlock->Text != "")
00118     {
00119         StatusBorder->Visibility = Windows::UI::Xaml::Visibility::Visible;
00120         StatusPanel->Visibility = Windows::UI::Xaml::Visibility::Visible;
00121     }
00122     else
00123     {
00124         StatusBorder->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00125         StatusPanel->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00126     }
00127 }
00128
00129 void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e)
00130 {
00131     auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag);
00132     Windows::System::Launcher::LaunchUriAsync(uri);
00133 }
00134
00135 void MainPage::Button_Click(Object^ sender, RoutedEventArgs^ e)
00136 {
00137     Splitter->IsPaneOpen = !Splitter->IsPaneOpen;
00138 }
Generated on Fri Nov 15 2024 22:17:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cs/3-DeviceCapabilities.xaml.cs Source File

  • BasicInput
  • cs

3-DeviceCapabilities.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014
00015 namespace SDKTemplate
00016 {
00017     public sealed partial class Scenario3 : Page
00018     {
00019         public Scenario3()
00020         {
00021             this.InitializeComponent();
00022
00023             // Retrieve information about whether or not a keyboard is present
00024             Windows.Devices.Input.KeyboardCapabilities kbdCapabilities = new Windows.Devices.Input.KeyboardCapabilities();
00025             keyboardText.Text = "Keyboard present = " + kbdCapabilities.KeyboardPresent.ToString();
00026
00027             // Retrieve information about the capabilities of the device's mouse.  This includes:
00028             // - Whether or not a mouse is present
00029             // - The number of buttons on the mouse
00030             // - Whether or not the mouse has a vertical scroll wheel
00031             // - Whether or not the mouse has a horizontal scroll wheel
00032             // - Whether or not the user has elected to swap the mouse buttons, causing
00033             //   the right mouse button to be the primary button
00034             Windows.Devices.Input.MouseCapabilities mouseCapabilities = new Windows.Devices.Input.MouseCapabilities();
00035             System.Text.StringBuilder sb = new System.Text.StringBuilder();
00036             sb.Append("Mouse present = " + mouseCapabilities.MousePresent.ToString() + "\n");
00037             sb.Append("Number of buttons = " + mouseCapabilities.NumberOfButtons.ToString() + "\n");
00038             sb.Append("Vertical wheel present = " + mouseCapabilities.VerticalWheelPresent.ToString() + "\n");
00039             sb.Append("Horizontal wheel present = " + mouseCapabilities.HorizontalWheelPresent.ToString() + "\n");
00040             sb.Append("Buttons swapped = " + mouseCapabilities.SwapButtons.ToString());
00041             mouseText.Text = sb.ToString();
00042
00043             // Retrieve information about the capabilities of the device's mouse.  This includes:
00044             // - Whether or not the device supports touch
00045             // - The supported number of simultaneous touch contacts
00046             Windows.Devices.Input.TouchCapabilities touchCapabilities = new Windows.Devices.Input.TouchCapabilities();
00047             sb = new System.Text.StringBuilder();
00048             sb.Append("Touch present = " + touchCapabilities.TouchPresent.ToString() + "\n");
00049             sb.Append("Touch contacts supported = " + touchCapabilities.Contacts.ToString());
00050             touchText.Text = sb.ToString();
00051         }
00052     }
00053 }
Generated on Fri Nov 15 2024 22:18:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TitleBar/cs/Scenario2_Extend.xaml.cs Source File

  • TitleBar
  • cs

Scenario2_Extend.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.ApplicationModel.Core;
00013 using Windows.UI.Core;
00014 using Windows.UI.ViewManagement;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario2_Extend : Page
00022     {
00023         private MainPage rootPage = MainPage.Current;
00024
00025         public Scenario2_Extend()
00026         {
00027             this.InitializeComponent();
00028             ExtendView.IsChecked = CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar;
00029             EnableControls.Visibility = ExtendView.IsChecked.Value ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed;
00030             EnableControls.IsChecked = rootPage.AreControlsInTitleBar;
00031
00032         }
00033
00034         protected override void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             rootPage = MainPage.Current;
00037
00038             // The SizeChanged event is raised when full screen mode changes.
00039             Window.Current.SizeChanged += OnWindowSizeChanged;
00040             UpdateFullScreenModeStatus();
00041         }
00042
00043         protected override void OnNavigatedFrom(NavigationEventArgs e)
00044         {
00045             Window.Current.SizeChanged -= OnWindowSizeChanged;
00046         }
00047
00048         private void ExtendView_Click(object sender, RoutedEventArgs e)
00049         {
00050             bool extend = ExtendView.IsChecked.Value;
00051             CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = extend;
00052             EnableControls.Visibility = extend ? Visibility.Visible : Visibility.Collapsed;
00053             if (extend)
00054             {
00055                 rootPage.AddCustomTitleBar();
00056             }
00057             else
00058             {
00059                 rootPage.RemoveCustomTitleBar();
00060             }
00061         }
00062
00063         private void EnableControls_Click(object sender, RoutedEventArgs e)
00064         {
00065             rootPage.AreControlsInTitleBar = EnableControls.IsChecked.Value;
00066         }
00067
00068         private void ToggleFullScreenModeButton_Click(object sender, RoutedEventArgs e)
00069         {
00070             var view = ApplicationView.GetForCurrentView();
00071             if (view.IsFullScreenMode)
00072             {
00073                 view.ExitFullScreenMode();
00074                 rootPage.NotifyUser("Exited full screen mode", NotifyType.StatusMessage);
00075             }
00076             else
00077             {
00078                 if (view.TryEnterFullScreenMode())
00079                 {
00080                     rootPage.NotifyUser("Entered full screen mode", NotifyType.StatusMessage);
00081                 }
00082                 else
00083                 {
00084                     rootPage.NotifyUser("Failed to enter full screen mode", NotifyType.ErrorMessage);
00085                 }
00086             }
00087         }
00088
00089         void OnWindowSizeChanged(object sender, WindowSizeChangedEventArgs e)
00090         {
00091             UpdateFullScreenModeStatus();
00092         }
00093
00094         void UpdateFullScreenModeStatus()
00095         {
00096             bool isFullScreenMode = ApplicationView.GetForCurrentView().IsFullScreenMode;
00097             ToggleFullScreenModeSymbol.Symbol = isFullScreenMode ? Symbol.BackToWindow : Symbol.FullScreen;
00098             ReportFullScreenMode.Text = isFullScreenMode ? "is in" : "is not in";
00099         }
00100     }
00101 }
Generated on Fri Nov 15 2024 22:21:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_PartialReadWrite Member List

This is the complete list of members for Scenario4_PartialReadWrite, including all inherited members.
AppendOutputLine(string value) | Scenario4_PartialReadWrite | [inline, private]
busy | Scenario4_PartialReadWrite | [private]
CloseSocket() | Scenario4_PartialReadWrite | [inline, private]
ConnectAsync() | Scenario4_PartialReadWrite | [inline, private]
MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) | Scenario4_PartialReadWrite | [inline, private]
messageWebSocket | Scenario4_PartialReadWrite | [private]
OnClosed(IWebSocket sender, WebSocketClosedEventArgs args) | Scenario4_PartialReadWrite | [inline, private]
OnConnect(object sender, RoutedEventArgs e) | Scenario4_PartialReadWrite | [inline, private]
OnDisconnect(object sender, RoutedEventArgs e) | Scenario4_PartialReadWrite | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario4_PartialReadWrite | [inline, protected]
OnSend(object sender, RoutedEventArgs e) | Scenario4_PartialReadWrite | [inline, private]
rootPage | Scenario4_PartialReadWrite | [private]
Scenario4_PartialReadWrite() | Scenario4_PartialReadWrite | [inline]
SendAsync() | Scenario4_PartialReadWrite | [inline, private]
SetBusy(bool value) | Scenario4_PartialReadWrite | [inline, private]
UpdateVisualState() | Scenario4_PartialReadWrite | [inline, private]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario06 Member List

This is the complete list of members for Scenario06, including all inherited members.
activeCastConnectionHandler | Scenario06 | [private]
activeDevice | Scenario06 | [private]
Connection_ErrorOccurred(CastingConnection sender, CastingConnectionErrorOccurredEventArgs args) | Scenario06 | [inline, private]
Connection_StateChanged(CastingConnection sender, object args) | Scenario06 | [inline, private]
MAX_RESULTS | Scenario06 | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario06 | [inline, protected]
picker | Scenario06 | [private]
Picker_DevicePickerDismissed(DevicePicker sender, object args) | Scenario06 | [inline, private]
Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args) | Scenario06 | [inline, private]
Picker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args) | Scenario06 | [inline, private]
Player_CurrentStateChanged(object sender, RoutedEventArgs e) | Scenario06 | [inline, private]
Player_MediaFailed(object sender, ExceptionRoutedEventArgs e) | Scenario06 | [inline, private]
Player_MediaOpened(object sender, RoutedEventArgs e) | Scenario06 | [inline, private]
pvb | Scenario06 | [private]
Pvb_ProjectionStopping(object sender, EventArgs e) | Scenario06 | [inline, private]
rootPage | Scenario06 | [private]
Scenario06() | Scenario06 | [inline]
thisViewId | Scenario06 | [private]
TransportControls_CastButtonClicked(object sender, EventArgs e) | Scenario06 | [inline, private]
TryCastMediaElementAsync(DeviceInformation device) | Scenario06 | [inline, private]
TryDisconnectCastingSessionAsync(CastingConnection connection) | Scenario06 | [inline, private]
TryLaunchDialAppAsync(DeviceInformation device) | Scenario06 | [inline, private]
TryProjectionManagerCastAsync(DeviceInformation device) | Scenario06 | [inline, private]
TryStopDialAppAsync(DialApp app) | Scenario06 | [inline, private]
TryStopProjectionManagerAsync(ProjectionViewBroker broker) | Scenario06 | [inline, private]
video | Scenario06 | [private]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Colors Member List

This is the complete list of members for Scenario1_Colors, including all inherited members.
PropertyChanged | Scenario1_Colors |
Scenario1_Colors() | Scenario1_Colors | [inline]
titleBar | Scenario1_Colors | [private]
TitleBar | Scenario1_Colors |
UpdateColors() | Scenario1_Colors | [inline, private]
UseCustomColors_Click(object sender, RoutedEventArgs e) | Scenario1_Colors | [inline, private]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cpp/Scenario5_IsSupported.xaml.cpp Source File

  • JumpList
  • cpp

Scenario5_IsSupported.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario5_IsSupported.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Xaml::Controls;
00020 using namespace Windows::UI::Xaml::Navigation;
00021 using namespace Windows::UI::StartScreen;
00022
00023 Scenario5_IsSupported::Scenario5_IsSupported()
00024 {
00025     InitializeComponent();
00026 }
00027
00028 void Scenario5_IsSupported::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00029 {
00030     Supported->Text = JumpList::IsSupported() ? "supports" : "does not support";
00031 }
Generated on Fri Nov 15 2024 22:20:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cpp/pch.h Source File

  • 360VideoPlayback
  • cpp

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <agile.h>
00004 #include <array>
00005 #include <d2d1_2.h>
00006 #include <d3d11_4.h>
00007 #include <DirectXColors.h>
00008 #include <dwrite_2.h>
00009 #include <map>
00010 #include <mutex>
00011 #include <wincodec.h>
00012 #include <WindowsNumerics.h>
00013 #include <collection.h>
00014 #include <ppltasks.h>
00015
00016 #include "App.xaml.h"
00017 #include <list>
00018
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cpp/Scenario5_TimeZone.xaml.h Source File

  • Calendar
  • cpp

Scenario5_TimeZone.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario5_TimeZone.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario5_TimeZone sealed
00021     {
00022     public:
00023         Scenario5_TimeZone();
00024         void ShowResults_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00025
00026     private:
00027         Platform::String^ ReportCalendarData(Windows::Globalization::Calendar^ calendar);
00028     };
00029 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/Common/StepTimer.h Source File

  • HolographicTagAlong
  • cpp
  • Common

StepTimer.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace DX
00015 {
00016     // Helper class for animation and simulation timing.
00017     class StepTimer
00018     {
00019     public:
00020         StepTimer() :
00021             m_elapsedTicks(0),
00022             m_totalTicks(0),
00023             m_leftOverTicks(0),
00024             m_frameCount(0),
00025             m_framesPerSecond(0),
00026             m_framesThisSecond(0),
00027             m_qpcSecondCounter(0),
00028             m_isFixedTimeStep(false),
00029             m_targetElapsedTicks(TicksPerSecond / 60)
00030         {
00031             m_qpcFrequency = GetPerformanceFrequency();
00032
00033             // Initialize max delta to 1/10 of a second.
00034             m_qpcMaxDelta = m_qpcFrequency / 10;
00035         }
00036
00037         // Get elapsed time since the previous Update call.
00038         uint64 GetElapsedTicks() const                        { return m_elapsedTicks;                  }
00039         double GetElapsedSeconds() const                      { return TicksToSeconds(m_elapsedTicks);  }
00040
00041         // Get total time since the start of the program.
00042         uint64 GetTotalTicks() const                          { return m_totalTicks;                    }
00043         double GetTotalSeconds() const                        { return TicksToSeconds(m_totalTicks);    }
00044
00045         // Get total number of updates since start of the program.
00046         uint32 GetFrameCount() const                          { return m_frameCount;                    }
00047
00048         // Get the current framerate.
00049         uint32 GetFramesPerSecond() const                     { return m_framesPerSecond;               }
00050
00051         // Set whether to use fixed or variable timestep mode.
00052         void SetFixedTimeStep(bool isFixedTimestep)           { m_isFixedTimeStep = isFixedTimestep;    }
00053
00054         // Set how often to call Update when in fixed timestep mode.
00055         void SetTargetElapsedTicks(uint64 targetElapsed)      { m_targetElapsedTicks = targetElapsed;   }
00056         void SetTargetElapsedSeconds(double targetElapsed)    { m_targetElapsedTicks = SecondsToTicks(targetElapsed);   }
00057
00058         // Integer format represents time using 10,000,000 ticks per second.
00059         static const uint64 TicksPerSecond = 10'000'000;
00060
00061         static double TicksToSeconds(uint64 ticks)            { return static_cast<double>(ticks) / TicksPerSecond;     }
00062         static uint64 SecondsToTicks(double seconds)          { return static_cast<uint64>(seconds * TicksPerSecond);   }
00063
00064         // Convenient wrapper for QueryPerformanceFrequency. Throws an exception if
00065         // the call to QueryPerformanceFrequency fails.
00066         static inline uint64 GetPerformanceFrequency()
00067         {
00068             LARGE_INTEGER freq;
00069             if (!QueryPerformanceFrequency(&freq))
00070             {
00071                 throw ref new Platform::FailureException();
00072             }
00073             return freq.QuadPart;
00074         }
00075
00076         // Gets the current number of ticks from QueryPerformanceCounter. Throws an
00077         // exception if the call to QueryPerformanceCounter fails.
00078         static inline int64 GetTicks()
00079         {
00080             LARGE_INTEGER ticks;
00081             if (!QueryPerformanceCounter(&ticks))
00082             {
00083                 throw ref new Platform::FailureException();
00084             }
00085             return ticks.QuadPart;
00086         }
00087
00088         // After an intentional timing discontinuity (for instance a blocking IO operation)
00089         // call this to avoid having the fixed timestep logic attempt a set of catch-up
00090         // Update calls.
00091
00092         void ResetElapsedTime()
00093         {
00094             m_qpcLastTime = GetTicks();
00095
00096             m_leftOverTicks    = 0;
00097             m_framesPerSecond  = 0;
00098             m_framesThisSecond = 0;
00099             m_qpcSecondCounter = 0;
00100         }
00101
00102         // Update timer state, calling the specified Update function the appropriate number of times.
00103         template<typename TUpdate>
00104         void Tick(const TUpdate& update)
00105         {
00106             // Query the current time.
00107             uint64 currentTime = GetTicks();
00108             uint64 timeDelta   = currentTime - m_qpcLastTime;
00109
00110             m_qpcLastTime      = currentTime;
00111             m_qpcSecondCounter += timeDelta;
00112
00113             // Clamp excessively large time deltas (e.g. after paused in the debugger).
00114             if (timeDelta > m_qpcMaxDelta)
00115             {
00116                 timeDelta = m_qpcMaxDelta;
00117             }
00118
00119             // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp.
00120             timeDelta *= TicksPerSecond;
00121             timeDelta /= m_qpcFrequency;
00122
00123             uint32 lastFrameCount = m_frameCount;
00124
00125             if (m_isFixedTimeStep)
00126             {
00127                 // Fixed timestep update logic
00128
00129                 // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp
00130                 // the clock to exactly match the target value. This prevents tiny and irrelevant errors
00131                 // from accumulating over time. Without this clamping, a game that requested a 60 fps
00132                 // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually
00133                 // accumulate enough tiny errors that it would drop a frame. It is better to just round
00134                 // small deviations down to zero to leave things running smoothly.
00135
00136                 if (abs(static_cast<int64>(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000)
00137                 {
00138                     timeDelta = m_targetElapsedTicks;
00139                 }
00140
00141                 m_leftOverTicks += timeDelta;
00142
00143                 while (m_leftOverTicks >= m_targetElapsedTicks)
00144                 {
00145                     m_elapsedTicks   = m_targetElapsedTicks;
00146                     m_totalTicks    += m_targetElapsedTicks;
00147                     m_leftOverTicks -= m_targetElapsedTicks;
00148                     m_frameCount++;
00149
00150                     update();
00151                 }
00152             }
00153             else
00154             {
00155                 // Variable timestep update logic.
00156                 m_elapsedTicks  = timeDelta;
00157                 m_totalTicks   += timeDelta;
00158                 m_leftOverTicks = 0;
00159                 m_frameCount++;
00160
00161                 update();
00162             }
00163
00164             // Track the current framerate.
00165             if (m_frameCount != lastFrameCount)
00166             {
00167                 m_framesThisSecond++;
00168             }
00169
00170             if (m_qpcSecondCounter >= static_cast<uint64>(m_qpcFrequency))
00171             {
00172                 m_framesPerSecond   = m_framesThisSecond;
00173                 m_framesThisSecond  = 0;
00174                 m_qpcSecondCounter %= m_qpcFrequency;
00175             }
00176         }
00177
00178     private:
00179
00180         // Source timing data uses QPC units.
00181         uint64 m_qpcFrequency;
00182         uint64 m_qpcLastTime;
00183         uint64 m_qpcMaxDelta;
00184
00185         // Derived timing data uses a canonical tick format.
00186         uint64 m_elapsedTicks;
00187         uint64 m_totalTicks;
00188         uint64 m_leftOverTicks;
00189
00190         // Members for tracking the framerate.
00191         uint32 m_frameCount;
00192         uint32 m_framesPerSecond;
00193         uint32 m_framesThisSecond;
00194         uint64 m_qpcSecondCounter;
00195
00196         // Members for configuring fixed timestep mode.
00197         bool   m_isFixedTimeStep;
00198         uint64 m_targetElapsedTicks;
00199     };
00200 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FileSavePicker_SaveToCachedFile Member List

This is the complete list of members for FileSavePicker_SaveToCachedFile, including all inherited members.
FileSavePicker_SaveToCachedFile() | FileSavePicker_SaveToCachedFile | [inline]
fileSavePickerUI | FileSavePicker_SaveToCachedFile | [private]
OnNavigatedFrom(NavigationEventArgs e) | FileSavePicker_SaveToCachedFile | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | FileSavePicker_SaveToCachedFile | [inline, protected]
OnTargetFileRequested(FileSavePickerUI sender, TargetFileRequestedEventArgs e) | FileSavePicker_SaveToCachedFile | [inline, private]
RegisterBackgroundTaskAsync() | FileSavePicker_SaveToCachedFile | [inline, private]
Simulate_Update_Collision_Click(object sender, RoutedEventArgs e) | FileSavePicker_SaveToCachedFile | [inline, private]
simulateUpdateConflict | FileSavePicker_SaveToCachedFile | [private]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cs/Scenario4_DeviceEvents.xaml.cs Source File

  • CustomCapability
  • cs

Scenario4_DeviceEvents.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Runtime.InteropServices.WindowsRuntime;
00014 using System.Threading;
00015 using System.Threading.Tasks;
00016 using Windows.Devices.Custom;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class DeviceEvents
00024     {
00025         MainPage rootPage = MainPage.Current;
00026
00027         // saved copy of the switch state, used to highlight which entries have changed
00028         bool[] previousSwitchValues = null;
00029
00030         public DeviceEvents()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         protected override void OnNavigatedTo(NavigationEventArgs e)
00036         {
00037             ClearSwitchStateTable();
00038             UpdateRegisterButton();
00039         }
00040
00041         protected override void OnNavigatedFrom(NavigationEventArgs e)
00042         {
00043             if (cancelSource != null)
00044             {
00045                 cancelSource.Cancel();
00046                 cancelSource = null;
00047             }
00048         }
00049
00050         private async void deviceEventsGet_Click(object sender, RoutedEventArgs e)
00051         {
00052             CustomDevice fx2Device = DeviceList.Current.GetSelectedDevice();
00053
00054             bool[] switchStateArray = new bool[8];
00055
00056             if (fx2Device == null)
00057             {
00058                 rootPage.NotifyUser("Fx2 device not connected or accessible", NotifyType.ErrorMessage);
00059                 return;
00060             }
00061
00062             var button = (Button)sender;
00063             button.IsEnabled = false;
00064
00065             var output = new byte[1];
00066
00067             try
00068             {
00069                 uint bytesRead = await fx2Device.SendIOControlAsync(Fx2Driver.ReadSwitches, null, output.AsBuffer());
00070                 if (bytesRead == 0)
00071                 {
00072                     rootPage.NotifyUser("Fx2 device returned 0 byte interrupt message.  Stopping", NotifyType.ErrorMessage);
00073                 }
00074                 else
00075                 {
00076                     switchStateArray = CreateSwitchStateArray(output);
00077                     UpdateSwitchStateTable(switchStateArray);
00078                 }
00079             }
00080             catch (Exception exception)
00081             {
00082                 rootPage.NotifyUser(exception.ToString(), NotifyType.ErrorMessage);
00083             }
00084             button.IsEnabled = true;
00085         }
00086
00087         private static bool[] CreateSwitchStateArray(byte[] output)
00088         {
00089             var switchStateArray = new bool[8];
00090
00091             for (int i = 0; i < 8; i += 1)
00092             {
00093                 switchStateArray[i] = (output[0] & (1 << i)) != 0;
00094             }
00095
00096             return switchStateArray;
00097         }
00098
00099         CancellationTokenSource cancelSource;
00100         byte[] switchMessageBuffer = new byte[1];
00101
00102         private void deviceEventsBegin_Click(object sender, RoutedEventArgs e)
00103         {
00104             var fx2Device = DeviceList.Current.GetSelectedDevice();
00105
00106             if (fx2Device == null)
00107             {
00108                 rootPage.NotifyUser("Fx2 device not connected or accessible", NotifyType.ErrorMessage);
00109                 return;
00110             }
00111
00112             if (cancelSource == null)
00113             {
00114                 ReadInterruptMessagesAsync();
00115             }
00116
00117             UpdateRegisterButton();
00118         }
00119
00120         private void deviceEventsCancel_Click(object sender, RoutedEventArgs e)
00121         {
00122             if (cancelSource != null)
00123             {
00124                 cancelSource.Cancel();
00125             }
00126             UpdateRegisterButton();
00127         }
00128
00129         private async void ReadInterruptMessagesAsync()
00130         {
00131             var fx2Device = DeviceList.Current.GetSelectedDevice();
00132             var switchMessageBuffer = new byte[1] { 0 };
00133
00134             cancelSource = new CancellationTokenSource();
00135
00136             bool failure = false;
00137
00138             while (!cancelSource.IsCancellationRequested)
00139             {
00140                 uint bytesRead;
00141
00142                 try
00143                 {
00144                     bytesRead = await fx2Device.SendIOControlAsync(
00145                                                     Fx2Driver.GetInterruptMessage,
00146                                                     null,
00147                                                     switchMessageBuffer.AsBuffer()
00148                                                     ).AsTask(cancelSource.Token);
00149                 }
00150                 catch (TaskCanceledException)
00151                 {
00152                     rootPage.NotifyUser("Pending GetInterruptMessage IO Control cancelled", NotifyType.StatusMessage);
00153                     failure = false;
00154                     break;
00155                 }
00156                 catch (Exception e)
00157                 {
00158                     rootPage.NotifyUser("Error accessing Fx2 device:\n" + e.Message, NotifyType.ErrorMessage);
00159                     failure = true;
00160                     break;
00161                 }
00162
00163                 if (bytesRead == 0)
00164                 {
00165                     rootPage.NotifyUser("Fx2 device returned 0 byte interrupt message.  Stopping\n", NotifyType.ErrorMessage);
00166                     failure = true;
00167                     break;
00168                 }
00169
00170                 var switchState = CreateSwitchStateArray(switchMessageBuffer);
00171                 UpdateSwitchStateTable(switchState);
00172
00173             }
00174
00175             if (failure)
00176             {
00177                 ClearSwitchStateTable();
00178             }
00179
00180             cancelSource = null;
00181             UpdateRegisterButton();
00182         }
00183
00184         private void UpdateRegisterButton()
00185         {
00186             deviceEventsBegin.IsEnabled = (cancelSource == null);
00187             deviceEventsCancel.IsEnabled = (cancelSource != null);
00188         }
00189
00190         private void ClearSwitchStateTable()
00191         {
00192             deviceEventsSwitches.Inlines.Clear();
00193             previousSwitchValues = null;
00194         }
00195
00196         private void UpdateSwitchStateTable(bool[] switchStateArray)
00197         {
00198             var output = deviceEventsSwitches;
00199
00200             DeviceList.CreateBooleanTable(
00201                 output.Inlines,
00202                 switchStateArray,
00203                 previousSwitchValues,
00204                 "Switch Number",
00205                 "Switch State",
00206                 "off",
00207                 "on"
00208                 );
00209             previousSwitchValues = switchStateArray;
00210         }
00211     }
00212 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/GroupInfoList.h Source File

  • XamlListView
  • cppwinrt

GroupInfoList.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "GroupInfoList.g.h"
00014
00015 namespace winrt::SDKTemplate::implementation
00016 {
00017     struct GroupInfoList : GroupInfoListT<GroupInfoList>
00018     {
00019         GroupInfoList() = default;
00020
00021         hstring Key() { return key; }
00022         void Key(hstring const& value) { key = value; }
00023         auto First() { return vector.First(); }
00024         auto GetAt(uint32_t index) { return vector.GetAt(index); }
00025         auto Size() { return vector.Size(); }
00026         auto GetView() { return vector.GetView(); }
00027         auto IndexOf(Windows::Foundation::IInspectable const& value, uint32_t& index) { return vector.IndexOf(value, index); }
00028         auto SetAt(uint32_t index, Windows::Foundation::IInspectable const& value) { return vector.SetAt(index, value); }
00029         auto InsertAt(uint32_t index, Windows::Foundation::IInspectable const& value) { return vector.InsertAt(index, value); }
00030         auto RemoveAt(uint32_t index) { return vector.RemoveAt(index); }
00031         auto Append(Windows::Foundation::IInspectable const& value) { return vector.Append(value); }
00032         auto RemoveAtEnd() { return vector.RemoveAtEnd(); }
00033         auto Clear() { return vector.Clear(); }
00034         auto GetMany(uint32_t startIndex, array_view<Windows::Foundation::IInspectable> items) { return vector.GetMany(startIndex, items); }
00035         auto ReplaceAll(array_view<Windows::Foundation::IInspectable const> items) { return vector.ReplaceAll(items); }
00036
00037     private:
00038         hstring key;
00039         Windows::Foundation::Collections::IVector<Windows::Foundation::IInspectable> vector = single_threaded_vector<Windows::Foundation::IInspectable>();
00040     };
00041 }
00042 namespace winrt::SDKTemplate::factory_implementation
00043 {
00044     struct GroupInfoList : GroupInfoListT<GroupInfoList, implementation::GroupInfoList>
00045     {
00046     };
00047 }
Generated on Fri Nov 15 2024 22:22:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_Override Member List

This is the complete list of members for Scenario4_Override, including all inherited members.
Display() | Scenario4_Override | [inline, private]
Scenario4_Override() | Scenario4_Override | [inline]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PlayReady/cs/SampleConfiguration.cs Source File

  • PlayReady
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "PlayReady C# Sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Reactive License Request", ClassType=typeof(Scenario1_ReactiveRequest)},
00025             new Scenario() { Title="Proactive License Request", ClassType=typeof(Scenario2_ProactiveRequest)},
00026             new Scenario() { Title="Manage HW/SW DRM", ClassType=typeof(Scenario3_HardwareDRM)},
00027             new Scenario() { Title="Secure Stop", ClassType=typeof(Scenario4_SecureStop)}
00028         };
00029
00030         public static string SampleMovieURL = "http://profficialsite.origin.mediaservices.windows.net/c51358ea-9a5e-4322-8951-897d640fdfd7/tearsofsteel_4k.ism/manifest(format=mpd-time-csf)";
00031     }
00032
00033     public class Scenario
00034     {
00035         public string Title { get; set; }
00036         public Type ClassType { get; set; }
00037     }
00038 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSuggestion/cs/SampleConfiguration.cs Source File

  • TextSuggestion
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 // Copyright (c) Microsoft Corporation. All rights reserved
00002
00003 using System;
00004 using System.Collections.Generic;
00005 using Windows.UI.Xaml.Controls;
00006 using TextSuggestion;
00007
00008 namespace SDKTemplate
00009 {
00010     public partial class MainPage : Page
00011     {
00012         public const string FEATURE_NAME = "TextSuggestion";
00013
00014         List<Scenario> scenarios = new List<Scenario>
00015         {
00016             new Scenario() { Title="Conversion", ClassType=typeof(Scenario1_Conversion)},
00017             new Scenario() { Title="Prediction", ClassType=typeof(Scenario2_Prediction)},
00018             new Scenario() { Title="ReverseConversion", ClassType=typeof(Scenario3_ReverseConversion)}
00019         };
00020     }
00021
00022     public class Scenario
00023     {
00024         public string Title { get; set; }
00025         public Type ClassType { get; set; }
00026     }
00027 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDragAndDrop/cpp/Scenario2_DragUICustomization.xaml.cpp Source File

  • XamlDragAndDrop
  • cpp

Scenario2_DragUICustomization.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_DragUICustomization.xaml.h"
00014
00015 using namespace SDKTemplate;
00016 using namespace concurrency;
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Primitives;
00023 using namespace Windows::UI::Xaml::Data;
00024 using namespace Windows::UI::Xaml::Input;
00025 using namespace Windows::UI::Xaml::Media;
00026 using namespace Windows::UI::Xaml::Media::Imaging;
00027 using namespace Windows::UI::Xaml::Navigation;
00028 using namespace Windows::Graphics::Imaging;
00029 using namespace Windows::Storage::Streams;
00030 using namespace Windows::ApplicationModel::DataTransfer;
00031
00032
00033 Scenario2_DragUICustomization::Scenario2_DragUICustomization()
00034     : rootPage(MainPage::Current),
00035     _insideName(ref new String(L"Inside")),
00036     _outsideName(ref new String(L"Outside")),
00037     _dropHere(ref new String(L"Drop here to insert text"))
00038 {
00039     InitializeComponent();
00040 }
00041
00042
00043 bool Scenario2_DragUICustomization::IsChecked(Windows::UI::Xaml::Controls::Primitives::ToggleButton^ button)
00044 {
00045     return (button->IsChecked != nullptr) && button->IsChecked->Value;
00046 }
00047
00048 /// <summary>
00049 /// Start of the Drag and Drop operation: we set some content and change the DragUI
00050 /// depending on the selected options
00051 /// </summary>
00052 /// <param name="sender"></param>
00053 /// <param name="args"></param>
00054 void Scenario2_DragUICustomization::SourceGrid_DragStarting(Windows::UI::Xaml::UIElement^ sender, Windows::UI::Xaml::DragStartingEventArgs^ args)
00055 {
00056     args->Data->SetText(SourceTextBox->Text);
00057     if (IsChecked(DataPackageRB))
00058     {
00059         // Standard icon will be used as the DragUIContent
00060         args->DragUI->SetContentFromDataPackage();
00061     }
00062     else if (IsChecked(CustomContentRB))
00063     {
00064         // Generate a bitmap with only the TextBox
00065         // We need to take the deferral as the rendering won't be completed synchronously
00066         auto deferral = args->GetDeferral();
00067         auto rtb = ref new RenderTargetBitmap();
00068         create_task(rtb->RenderAsync(SourceTextBox)).then([rtb]()
00069         {
00070             return rtb->GetPixelsAsync();
00071         }).then([rtb, deferral, args](IBuffer^ buffer)
00072         {
00073             auto bitmap = SoftwareBitmap::CreateCopyFromBuffer(buffer,
00074                 BitmapPixelFormat::Bgra8,
00075                 rtb->PixelWidth,
00076                 rtb->PixelHeight,
00077                 BitmapAlphaMode::Premultiplied);
00078             args->DragUI->SetContentFromSoftwareBitmap(bitmap);
00079             deferral->Complete();
00080         });
00081     }
00082     // else just show the dragged UIElement
00083 }
00084
00085 /// <summary>
00086 /// Entering the Target, we'll change its background and optionally change the DragUI as well
00087 /// </summary>
00088 /// <param name="sender"></param>
00089 /// <param name="e"></param>
00090 void Scenario2_DragUICustomization::TargetTextBox_DragEnter(Platform::Object^ sender, Windows::UI::Xaml::DragEventArgs^ e)
00091 {
00092     /// Change the background of the target
00093     VisualStateManager::GoToState(this, _insideName, true);
00094     bool hasText = e->DataView->Contains(StandardDataFormats::Text);
00095     e->AcceptedOperation = hasText ? DataPackageOperation::Copy : DataPackageOperation::None;
00096     if (hasText)
00097     {
00098         e->DragUIOverride->Caption = _dropHere;
00099         // Now customize the content
00100         if (IsChecked(HideRB))
00101         {
00102             e->DragUIOverride->IsGlyphVisible = false;
00103             e->DragUIOverride->IsContentVisible = false;
00104         }
00105         else if (IsChecked(CustomRB))
00106         {
00107             auto bitmap = ref new BitmapImage(ref new Uri(ref new String(L"ms-appx:///Assets/dropcursor.png")));
00108             // Anchor will define how to position the image relative to the pointer
00109             Point anchor{ 0,52 }; // lower left corner of the image
00110             e->DragUIOverride->SetContentFromBitmapImage(bitmap, anchor);
00111             e->DragUIOverride->IsGlyphVisible = false;
00112             e->DragUIOverride->IsCaptionVisible = false;
00113         }
00114         // else keep the DragUI Content set by the source
00115     }
00116 }
00117
00118 /// <summary>
00119 /// DragLeave: Restore previous background
00120 /// </summary>
00121 /// <param name="sender"></param>
00122 /// <param name="e"></param>
00123 void Scenario2_DragUICustomization::TargetTextBox_DragLeave(Platform::Object^ sender, Windows::UI::Xaml::DragEventArgs^ e)
00124 {
00125     VisualStateManager::GoToState(this, _outsideName, true);
00126 }
00127
00128 /// <summary>
00129 /// Drop: restore the background and append the dragged text
00130 /// </summary>
00131 /// <param name="sender"></param>
00132 /// <param name="e"></param>
00133 void Scenario2_DragUICustomization::TargetTextBox_Drop(Platform::Object^ sender, Windows::UI::Xaml::DragEventArgs^ e)
00134 {
00135     VisualStateManager::GoToState(this, _outsideName, true);
00136     bool hasText = e->DataView->Contains(StandardDataFormats::Text);
00137     e->AcceptedOperation = hasText ? DataPackageOperation::Copy : DataPackageOperation::None;
00138     if (hasText)
00139     {
00140         // if the result of the drop is not too important (and a text copy should have no impact on source)
00141         // we don't need to take the deferral and this will complete the operation faster
00142         create_task(e->DataView->GetTextAsync()).then([this](String^ text)
00143         {
00144             TargetTextBox->Text += text;
00145         });
00146     }
00147 }
Generated on Fri Nov 15 2024 22:22:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisablingScreenCapture/cpp/pch.cpp Source File

  • DisablingScreenCapture
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/Project.idl Source File

  • WindowsAudioSession
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1 : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2 : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3 : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3();
00030     }
00031
00032     [default_interface]
00033     runtimeclass Scenario4 : Windows.UI.Xaml.Controls.Page
00034     {
00035         Scenario4();
00036     }
00037
00038     // NB: All states >= Initialized will allow some methods
00039     // to be called successfully on the Audio Client
00040     enum DeviceState
00041     {
00042         Uninitialized,
00043         Error,
00044         Discontinuity,
00045         Flushing,
00046         Activated,
00047
00048         Initialized,
00049         Starting,
00050         Playing,
00051         Capturing,
00052         Pausing,
00053         Paused,
00054         Stopping,
00055         Stopped,
00056     };
00057
00058     runtimeclass DeviceStateChangedEventArgs
00059     {
00060         DeviceState DeviceState { get; };
00061         HRESULT ExtendedError{ get; };
00062     }
00063
00064     interface IDeviceStateSource
00065     {
00066         DeviceState DeviceState { get; };
00067         event Windows.Foundation.TypedEventHandler<IDeviceStateSource, DeviceStateChangedEventArgs> DeviceStateChanged;
00068     }
00069
00070     runtimeclass PlotDataReadyEventArgs
00071     {
00072         // Buffer of int16_t data values.
00073         Windows.Storage.Streams.IBuffer Points {get; };
00074     }
00075
00076     interface IPlotDataSource
00077     {
00078         event Windows.Foundation.TypedEventHandler<IPlotDataSource, PlotDataReadyEventArgs> PlotDataReady;
00079     };
00080 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/Scenario3.xaml.h Source File

  • WindowsAudioSession
  • cpp

Scenario3.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario3.xaml.h
00013 // Declaration of the Scenario3 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario3.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "WASAPIRenderer.h"
00022
00023 namespace SDKSample
00024 {
00025  namespace WASAPIAudio
00026  {
00027   [Windows::Foundation::Metadata::WebHostHidden]
00028   public ref class Scenario3 sealed
00029   {
00030
00031   public:
00032    Scenario3();
00033
00034   protected:
00035    // Template Support
00036    virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037    virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038
00039   private:
00040    ~Scenario3();
00041
00042    // UI Events
00043    void btnPlay_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044    void btnPause_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045    void btnPlayPause_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00046    void btnStop_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047    void btnFilePicker_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048    void radioTone_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049    void radioFile_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050    void sliderFrequency_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00051    void sliderVolume_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00052
00053    // UI Helpers
00054    void ShowStatusMessage(Platform::String^ str, NotifyType messageType);
00055    void UpdateContentProps(Platform::String^ str);
00056    void UpdateContentUI(Platform::Boolean disableAll);
00057    void UpdateMediaControlUI(DeviceState deviceState);
00058
00059    // Handlers
00060    void OnDeviceStateChange(Object^ sender, DeviceStateChangedEventArgs^ e);
00061    void OnPickFileAsync();
00062    void OnSetVolume(UINT32 volume);
00063
00064    void InitializeDevice();
00065    void StartDevice();
00066    void StopDevice();
00067    void PauseDevice();
00068    void PlayPauseToggleDevice();
00069
00070    void MediaButtonPressed(Windows::Media::SystemMediaTransportControls^ sender, Windows::Media::SystemMediaTransportControlsButtonPressedEventArgs^ e);
00071
00072   private:
00073    MainPage^            rootPage;
00074    Windows::UI::Core::CoreDispatcher^     m_CoreDispatcher;
00075    Windows::Media::SystemMediaTransportControls^   m_SystemMediaControls;
00076    Windows::Foundation::EventRegistrationToken  m_deviceStateChangeToken;
00077    Windows::Foundation::EventRegistrationToken  m_SystemMediaControlsButtonToken;
00078
00079    Platform::Boolean    m_IsMFLoaded;
00080    IRandomAccessStream^    m_ContentStream;
00081    ContentType    m_ContentType;
00082    DeviceStateChangedEvent^   m_StateChangedEvent;
00083    ComPtr<WASAPIRenderer>  m_spRenderer;
00084    Platform::Boolean    m_deviceSupportsRawMode;
00085    Platform::Boolean    m_IsMinimumLatency;
00086   };
00087  }
00088 }
Generated on Fri Nov 15 2024 22:18:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RemoteSystems/cs/Scenario3_LaunchAppServices.xaml.cs Source File

  • RemoteSystems
  • cs

Scenario3_LaunchAppServices.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.ObjectModel;
00014 using System.Threading.Tasks;
00015 using Windows.ApplicationModel.AppService;
00016 using Windows.Foundation.Collections;
00017 using Windows.System.RemoteSystems;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario3_LaunchAppServices : Page
00025     {
00026         private MainPage m_rootPage;
00027         private int m_minimumValue;
00028         private int m_maximumValue;
00029
00030         public Scenario3_LaunchAppServices()
00031         {
00032             this.InitializeComponent();
00033             this.DataContext = this;
00034         }
00035
00036         protected override void OnNavigatedTo(NavigationEventArgs e)
00037         {
00038             m_rootPage = MainPage.Current;
00039             m_rootPage.ValidateSystemDiscovery();
00040         }
00041
00042         public ObservableCollection<RemoteSystem> SystemList => m_rootPage.systemList;
00043
00044         private async void GenerateRandomNumber_Clicked(object sender, RoutedEventArgs e)
00045         {
00046             // Validate minimum and maximum input values.
00047             if (ValidateInput())
00048             {
00049                 // Connect to app service running on the selected system.
00050                 await ConnectToRemoteAppServiceAsync();
00051             }
00052         }
00053
00054         private bool ValidateInput()
00055         {
00056             if (!int.TryParse(MinValue.Text, out m_minimumValue))
00057             {
00058                 UpdateStatus("The Minimum Value should be a valid integer.", NotifyType.ErrorMessage);
00059                 return false;
00060             }
00061
00062             if (!int.TryParse(MaxValue.Text, out m_maximumValue))
00063             {
00064                 UpdateStatus("The Maximum Value should be a valid integer.", NotifyType.ErrorMessage);
00065                 return false;
00066             }
00067
00068             if (m_maximumValue <= m_minimumValue)
00069             {
00070                 UpdateStatus("Maximum Value must be larger than Minimum Value", NotifyType.ErrorMessage);
00071                 return false;
00072             }
00073
00074             return true;
00075         }
00076
00077         private async Task ConnectToRemoteAppServiceAsync()
00078         {
00079             RemoteSystem selectedSystem = SystemListComboBox.SelectedItem as RemoteSystem;
00080             if (selectedSystem != null)
00081             {
00082                 // Create a remote system connection request.
00083                 RemoteSystemConnectionRequest connectionRequest = new RemoteSystemConnectionRequest(selectedSystem);
00084
00085                 // Set up a new app service connection. The following app service name and package family name
00086                 // are used in this sample to work with AppServices provider SDK sample on a remote system.
00087                 using (AppServiceConnection connection = new AppServiceConnection
00088                 {
00089                     AppServiceName = "com.microsoft.randomnumbergenerator",
00090                     PackageFamilyName = "Microsoft.SDKSamples.AppServicesProvider.CS_8wekyb3d8bbwe"
00091                 })
00092                 {
00093                     UpdateStatus("Opening connection to remote app service...", NotifyType.StatusMessage);
00094                     AppServiceConnectionStatus status = await connection.OpenRemoteAsync(connectionRequest);
00095
00096                     if (status == AppServiceConnectionStatus.Success)
00097                     {
00098                         UpdateStatus("Successfully connected to remote app service.", NotifyType.StatusMessage);
00099                         await SendMessageToRemoteAppServiceAsync(connection);
00100                     }
00101                     else
00102                     {
00103                         UpdateStatus("Attempt to open a remote app service connection failed with error - " + status.ToString(), NotifyType.ErrorMessage);
00104                     }
00105                 }
00106             }
00107             else
00108             {
00109                 UpdateStatus("Select a system for remote connection.", NotifyType.ErrorMessage);
00110             }
00111         }
00112
00113         private async Task SendMessageToRemoteAppServiceAsync(AppServiceConnection connection)
00114         {
00115             // Send message if connection to the remote app service is open.
00116             if (connection != null)
00117             {
00118                 //Set up the inputs and send a message to the service.
00119                 ValueSet inputs = new ValueSet();
00120                 inputs.Add("minvalue", m_minimumValue);
00121                 inputs.Add("maxvalue", m_maximumValue);
00122                 UpdateStatus("Sent message to remote app service. Waiting for a response...", NotifyType.StatusMessage);
00123                 AppServiceResponse response = await connection.SendMessageAsync(inputs);
00124
00125                 if (response.Status == AppServiceResponseStatus.Success)
00126                 {
00127                     if (response.Message.ContainsKey("result"))
00128                     {
00129                         string resultText = response.Message["result"].ToString();
00130                         if (string.IsNullOrEmpty(resultText))
00131                         {
00132                             UpdateStatus("Remote app service did not respond with a result.", NotifyType.ErrorMessage);
00133                         }
00134                         else
00135                         {
00136                             UpdateStatus("Result = " + resultText, NotifyType.StatusMessage);
00137                         }
00138                     }
00139                     else
00140                     {
00141                         UpdateStatus("Response from remote app service does not contain a result.", NotifyType.ErrorMessage);
00142                     }
00143                 }
00144                 else
00145                 {
00146                     UpdateStatus("Sending message to remote app service failed with error - " + response.Status.ToString(), NotifyType.ErrorMessage);
00147                 }
00148             }
00149             else
00150             {
00151                 UpdateStatus("Not connected to any app service. Select a system to open a connection.", NotifyType.ErrorMessage);
00152             }
00153         }
00154
00155         private void UpdateStatus(string status, NotifyType statusType)
00156         {
00157             m_rootPage.NotifyUser(status, statusType);
00158         }
00159     }
00160 }
Generated on Fri Nov 15 2024 22:21:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AdaptivePage Member List

This is the complete list of members for AdaptivePage, including all inherited members.
Accounts | AdaptivePage |
AccountsList_Loading(FrameworkElement sender, object args) | AdaptivePage | [inline, private]
AdaptivePage() | AdaptivePage | [inline]
AdaptivePage_VisibleBoundsChanged(ApplicationView sender, object args) | AdaptivePage | [inline, private]
Emails | AdaptivePage |
Generated on Fri Nov 15 2024 22:24:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2 Member List

This is the complete list of members for Scenario2, including all inherited members.
dispatcher | Scenario2 | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2 | [inline, protected]
ProjectionManager_ProjectionDisplayAvailableChanged(object sender, object e) | Scenario2 | [inline, private]
RequestAndStartProjecting_Click(object sender, RoutedEventArgs e) | Scenario2 | [inline, private]
rootPage | Scenario2 | [private]
Scenario2() | Scenario2 | [inline]
StartProjecting_Click(object sender, RoutedEventArgs e) | Scenario2 | [inline, private]
thisViewId | Scenario2 | [private]
UpdateTextBlock(bool screenAvailable) | Scenario2 | [inline, private]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/PixelShader/DirectXHelper.h Source File

  • D2DCustomEffects
  • cpp
  • PixelShader

DirectXHelper.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <ppltasks.h>
00015
00016 namespace DX
00017 {
00018     inline void ThrowIfFailed(HRESULT hr)
00019     {
00020         if (FAILED(hr))
00021         {
00022             // Set a breakpoint on this line to catch Win32 API errors.
00023             throw Platform::Exception::CreateException(hr);
00024         }
00025     }
00026
00027     // Function that reads from a binary file asynchronously.
00028     inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename)
00029     {
00030         using namespace Windows::Storage;
00031         using namespace Concurrency;
00032
00033         auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
00034
00035         return create_task(folder->GetFileAsync(Platform::StringReference(filename.c_str()))).then([] (StorageFile^ file)
00036         {
00037             return FileIO::ReadBufferAsync(file);
00038         }).then([] (Streams::IBuffer^ fileBuffer) -> std::vector<byte>
00039         {
00040             std::vector<byte> returnBuffer;
00041             returnBuffer.resize(fileBuffer->Length);
00042             Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), fileBuffer->Length));
00043             return returnBuffer;
00044         });
00045     }
00046
00047     // Converts a length in device-independent pixels (DIPs) to a length in physical pixels.
00048     inline float ConvertDipsToPixels(float dips, float dpi)
00049     {
00050         static const float dipsPerInch = 96.0f;
00051         return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00052     }
00053
00054     // Converts a length in physical pixels to a length in device-independent pixels (DIPs).
00055     inline float ConvertPixelsToDips(float pixels)
00056     {
00057         static const float dipsPerInch = 96.0f;
00058         return pixels * dipsPerInch / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->LogicalDpi; // Do not round.
00059     }
00060
00061     // Converts a length in physical pixels to a length in device-independent pixels (DIPs) using the provided DPI. This removes the need
00062     // to call this function from a thread associated with a CoreWindow, which is required by DisplayInformation::GetForCurrentView().
00063     inline float ConvertPixelsToDips(float pixels, float dpi)
00064     {
00065         static const float dipsPerInch = 96.0f;
00066         return pixels * dipsPerInch / dpi; // Do not round.
00067     }
00068
00069 #if defined(_DEBUG)
00070     // Check for SDK Layer support.
00071     inline bool SdkLayersAvailable()
00072     {
00073         HRESULT hr = D3D11CreateDevice(
00074             nullptr,
00075             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00076             0,
00077             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00078             nullptr,                    // Any feature level will do.
00079             0,
00080             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00081             nullptr,                    // No need to keep the D3D device reference.
00082             nullptr,                    // No need to know the feature level.
00083             nullptr                     // No need to keep the D3D device context reference.
00084             );
00085
00086         return SUCCEEDED(hr);
00087     }
00088 #endif
00089 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cpp/Scenario2_Display.xaml.cpp Source File

  • Playlists
  • cpp

Scenario2_Display.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario2_Display.xaml.h"
00005 #include <sstream>
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace concurrency;
00010 using namespace Platform;
00011 using namespace Windows::Foundation;
00012 using namespace Windows::Foundation::Collections;
00013 using namespace Windows::Media::Playlists;
00014 using namespace Windows::Storage;
00015 using namespace Windows::Storage::FileProperties;
00016 using namespace Windows::Storage::Pickers;
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Controls::Primitives;
00020 using namespace Windows::UI::Xaml::Data;
00021 using namespace Windows::UI::Xaml::Input;
00022 using namespace Windows::UI::Xaml::Media;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 Scenario2_Display::Scenario2_Display() : rootPage(MainPage::Current)
00026 {
00027     InitializeComponent();
00028 }
00029
00030 void Scenario2_Display::PickPlaylistButton_Click(Object^ sender, RoutedEventArgs^ e)
00031 {
00032     this->rootPage->PickPlaylistAsync().then([this](Playlist^ playlist)
00033     {
00034         if (playlist != nullptr)
00035         {
00036             // create a vector to store the async operations
00037             std::vector<task<MusicProperties^>> results(playlist->Files->Size);
00038             for (unsigned int i = 0; i < playlist->Files->Size; i++)
00039             {
00040                 StorageFile^ file = playlist->Files->GetAt(i);
00041                 results[i] = create_task(file->Properties->GetMusicPropertiesAsync());
00042             }
00043
00044             // wait for all of the async operations to complete and then output the results
00045             when_all(results.begin(), results.end()).then([this, playlist](std::vector<MusicProperties^> results)
00046             {
00047                 String^ result = "Songs in playlist: " + playlist->Files->Size.ToString() + "\n";
00048                 for (unsigned int i = 0; i < results.size(); i++)
00049                 {
00050                     MusicProperties^ properties = results[i];
00051                     result += "\n";
00052                     result += "Path: " + playlist->Files->GetAt(i)->Path + "\n";
00053                     result += "Title: " + properties->Title + "\n";
00054                     result += "Album: " + properties->Album + "\n";
00055                     result += "Artist: " + properties->Artist + "\n";
00056                 }
00057                 this->OutputStatus->Text = result;
00058             });
00059         }
00060     });
00061 }
Generated on Fri Nov 15 2024 22:20:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/DPadHelper.cpp Source File

  • SpatialInteractionSource
  • cpp

DPadHelper.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "DPadHelper.h"
00003
00004 using namespace HolographicPaint;
00005 using namespace Windows::UI::Input::Spatial;
00006
00007 static DPadAction Select(double x, double y, double centerMin, double centerMax)
00008 {
00009     int dx = (x < centerMin) ? 0 : ((x < centerMax) ? 1 : 2);
00010     int dy = (y < centerMin) ? 0 : ((y < centerMax) ? 1 : 2);
00011     switch (dx)
00012     {
00013     case 0: // Left
00014         switch (dy)
00015         {
00016         case 0: // Lower left
00017             return (fabs(x) > fabs(y)) ? DPadAction::Left : DPadAction::Bottom;
00018         case 1: // Middle Left
00019         default:
00020             return DPadAction::Left;
00021         case 2: // Top Left
00022             return (fabs(x) > fabs(y)) ? DPadAction::Left : DPadAction::Bottom;
00023         }
00024     case 1: // Middle
00025     default:
00026         switch (dy)
00027         {
00028         case 0: // Bottom Middle
00029             return DPadAction::Bottom;
00030         case 1: // Middle
00031         default:
00032             return DPadAction::None;
00033         case 2: // Top Middle
00034             return DPadAction::Top;
00035         }
00036     case 2: // Right
00037         switch (dy)
00038         {
00039         case 0: // Bottom Right
00040             return (fabs(x) > fabs(y)) ? DPadAction::Right : DPadAction::Top;
00041         case 1: // Middle Right
00042         default:
00043             return DPadAction::Right;
00044         case 2: // Top right
00045             return (fabs(x) > fabs(y)) ? DPadAction::Right : DPadAction::Top;
00046         }
00047     }
00048 }
00049
00050 ThumbstickDPadHelper::ThumbstickDPadHelper(double threshold)
00051     : m_threshold(threshold), m_waitForCenter(false)
00052 {
00053 }
00054
00055 DPadAction ThumbstickDPadHelper::Update(SpatialInteractionControllerProperties^ controllerState)
00056 {
00057     double x = controllerState->ThumbstickX;
00058     double y = controllerState->ThumbstickY;
00059     DPadAction ret = DPadAction::None;
00060     if (m_waitForCenter)
00061     {
00062         m_waitForCenter = (x < -m_threshold) || (x > m_threshold) || (y < -m_threshold) || (y > m_threshold);
00063     }
00064     else
00065     {
00066         ret = Select(x, y, -m_threshold, m_threshold);
00067         m_waitForCenter = (ret != DPadAction::None);
00068     }
00069     return ret;
00070 }
00071
00072 TouchpadDPadHelper::TouchpadDPadHelper(double threshold)
00073     : m_threshold(threshold)
00074 {
00075 }
00076
00077 DPadAction TouchpadDPadHelper::SourcePressed(
00078     SpatialInteractionPressKind pressKind,
00079     SpatialInteractionControllerProperties^ controllerState)
00080 {
00081     double x = controllerState->TouchpadX;
00082     double y = controllerState->TouchpadY;
00083     return Select(x, y, -m_threshold, m_threshold);
00084 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_EnumerateTiles Member List

This is the complete list of members for Scenario3_EnumerateTiles, including all inherited members.
EnumerateSecondaryTiles_Click(object sender, RoutedEventArgs e) | Scenario3_EnumerateTiles | [inline, private]
rootPage | Scenario3_EnumerateTiles | [private]
Scenario3_EnumerateTiles() | Scenario3_EnumerateTiles | [inline]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cpp/Scenario3_UsingWindows.xaml.h Source File

  • LineDisplay
  • cpp

Scenario3_UsingWindows.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_UsingWindows.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::UI::Xaml::Data::Bindable]
00020     public ref class WindowInfo sealed
00021     {
00022     public:
00023         property Windows::Devices::PointOfService::LineDisplayWindow^ Window
00024         {
00025             Windows::Devices::PointOfService::LineDisplayWindow^ get()
00026             {
00027                 return window;
00028             }
00029
00030             void set(Windows::Devices::PointOfService::LineDisplayWindow^ value)
00031             {
00032                 window = value;
00033             }
00034         }
00035
00036         property int Id
00037         {
00038             int get()
00039             {
00040                 return id;
00041             }
00042
00043             void set(int value)
00044             {
00045                 id = value;
00046             }
00047         }
00048
00049         property Platform::String^ Name
00050         {
00051             Platform::String^ get()
00052             {
00053                 return (Id == 0) ? "(Default)" : "";
00054             }
00055         }
00056
00057         WindowInfo(Windows::Devices::PointOfService::LineDisplayWindow^ window, int id)
00058         {
00059             this->window = window;
00060             this->id = id;
00061         }
00062     private:
00063         Windows::Devices::PointOfService::LineDisplayWindow^ window;
00064         int id;
00065     };
00066
00067     [Windows::Foundation::Metadata::WebHostHidden]
00068     [Windows::UI::Xaml::Data::Bindable]
00069     public ref class Scenario3_UsingWindows sealed
00070     {
00071     public:
00072         Scenario3_UsingWindows();
00073
00074         property Windows::Foundation::Collections::IObservableVector<WindowInfo^>^ WindowList
00075         {
00076             Windows::Foundation::Collections::IObservableVector<WindowInfo^>^ get()
00077             {
00078                 return windowList;
00079             }
00080         }
00081
00082         // Public for binding purposes.
00083         bool IsNonNull(Platform::Object^ item)
00084         {
00085             return item != nullptr;
00086         }
00087
00088         // The default window cannot be destroyed.
00089         bool CanDestroyWindow(Platform::Object^ item)
00090         {
00091             return (item != nullptr) && (safe_cast<WindowInfo^>(item)->Id != 0);
00092         }
00093
00094         // Can create a new window if we haven't reached the maximum.
00095         bool CanCreateNewWindow(Windows::Foundation::Collections::IObservableVector<WindowInfo^>^ windowList)
00096         {
00097             return windowList->Size < maxWindows;
00098         }
00099
00100     protected:
00101         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00102         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00103
00104     private:
00105         MainPage^ rootPage = MainPage::Current;
00106         Windows::Devices::PointOfService::ClaimedLineDisplay^ lineDisplay;
00107
00108         Windows::Foundation::Collections::IObservableVector<WindowInfo^>^ windowList = ref new Platform::Collections::Vector<WindowInfo^>();
00109
00110         int nextWindowId = 0;
00111         unsigned int maxWindows = 0;
00112
00113         Concurrency::task<void> InitializeAsync();
00114
00115         void NewWindowButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00116         void RefreshWindowButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00117         void DestroyWindowButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00118         void DisplayTextButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00119     };
00120 }
Generated on Fri Nov 15 2024 22:20:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DataHelpers Member List

This is the complete list of members for DataHelpers, including all inherited members.
GetDataLabelString(IBuffer data, uint scanDataType) | DataHelpers | [inline, static]
GetDataString(IBuffer data) | DataHelpers | [inline, static]
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CopyImage Member List

This is the complete list of members for CopyImage, including all inherited members.
CopyBitmap(bool isDelayRendered) | CopyImage | [private]
CopyButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | CopyImage |
CopyImage() | CopyImage |
CopyWithDelayedRenderingButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | CopyImage |
OnDeferredImageRequestedHandler(Windows::ApplicationModel::DataTransfer::DataProviderRequest request, Windows::Storage::StorageFile imageFile) | CopyImage | [private, static]
PasteButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | CopyImage |
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cs/Tasks/VisitBackgroundTask.cs Source File

  • Geolocation
  • cs
  • Tasks

VisitBackgroundTask.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Collections.Generic;
00013 using Windows.ApplicationModel.Background;
00014 using Windows.Data.Json;
00015 using Windows.Devices.Geolocation;
00016 using Windows.Globalization;
00017 using Windows.Globalization.DateTimeFormatting;
00018 using Windows.Storage;
00019
00020 namespace BackgroundTask
00021 {
00022     public sealed class VisitBackgroundTask : IBackgroundTask
00023     {
00024         // Value determined by how many max length event descriptors (91 chars)
00025         // stored as a JSON string can fit in 8K (max allowed for local settings)
00026         private const int maxEventDescriptors = 42;
00027
00028         // LocalSettings persistent data.
00029         IDictionary<string, object> _values = ApplicationData.Current.LocalSettings.Values;
00030
00031         void IBackgroundTask.Run(IBackgroundTaskInstance taskInstance)
00032         {
00033             BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
00034             GeovisitTriggerDetails triggerDetails = (GeovisitTriggerDetails)taskInstance.TriggerDetails;
00035
00036             // Handle Visit reports
00037             ProcessVisitReports(triggerDetails);
00038             deferral.Complete();
00039         }
00040
00041         private void ProcessVisitReports(GeovisitTriggerDetails triggerDetails)
00042         {
00043             // Load the values saved from last time.
00044             JsonArray visitBackgroundEvents = Helpers.LoadSavedJson("BackgroundVisitEventCollection");
00045
00046             // Read reports from the triggerDetails.
00047             IReadOnlyList<Geovisit> reports = triggerDetails.ReadReports();
00048
00049             string description = null;
00050
00051             foreach (Geovisit report in reports)
00052             {
00053                 description = GenerateVisitDescription(report);
00054
00055                 // Add to the collection, trimming old events if necessary.
00056                 if (visitBackgroundEvents.Count == maxEventDescriptors)
00057                 {
00058                     visitBackgroundEvents.RemoveAt(maxEventDescriptors - 1);
00059                 }
00060                 visitBackgroundEvents.Insert(0, JsonValue.CreateStringValue(description));
00061             }
00062
00063             int numReports = reports.Count;
00064             if (numReports > 0)
00065             {
00066                 // Save the modified results for next time.
00067                 _values["BackgroundVisitEventCollection"] = visitBackgroundEvents.Stringify();
00068
00069                 if (numReports > 1)
00070                 {
00071                     description = $"There are {numReports} new geofence events";
00072                 }
00073                 Helpers.DisplayToast(description);
00074             }
00075         }
00076
00077         private string GenerateVisitDescription(Geovisit visit)
00078         {
00079             string result = $"{visit.Timestamp:G} {visit.StateChange}";
00080
00081             // Check if the report has a valid position.
00082             if (visit.Position != null)
00083             {
00084                 result += $" ({visit.Position.Coordinate.Point.Position.Latitude}, {visit.Position.Coordinate.Point.Position.Longitude})";
00085             }
00086
00087             return result;
00088         }
00089     }
00090 }
Generated on Fri Nov 15 2024 22:19:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario1WinRTComponent/SecureInterfaceEventArgs.h Source File

  • AllJoyn
  • Common
  • Scenario1WinRTComponent

SecureInterfaceEventArgs.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #pragma once
00022
00023 namespace com { namespace microsoft { namespace Samples { namespace SecureInterface {
00024
00025 // Signals
00026 // "This signal is emitted when producer sends a text message to consumer"
00027 public ref class SecureInterfaceTextSentReceivedEventArgs sealed
00028 {
00029 public:
00030     property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo
00031     {
00032         Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; }
00033         void set(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ value) { m_messageInfo = value; }
00034     }
00035
00036     property Platform::String^ Message
00037     {
00038         Platform::String^ get() { return m_interfaceMemberMessage; }
00039     internal:
00040         void set(_In_ Platform::String^ value) { m_interfaceMemberMessage = value; }
00041     }
00042
00043 private:
00044     Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo;
00045
00046     Platform::String^ m_interfaceMemberMessage;
00047 };
00048
00049
00050 } } } }
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackButton/cpp/Scenario1.xaml.h Source File

  • BackButton
  • cpp

Scenario1.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario1 sealed
00024     {
00025     public:
00026         Scenario1();
00027
00028     protected:
00029         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         void Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033         void CheckBox_Toggle(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs e);
00034
00035         MainPage^ rootPage;
00036        static bool optedIn;
00037
00038     };
00039 }
Generated on Fri Nov 15 2024 22:17:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OnDemandHotspot/cppwinrt/Project.idl Source File

  • OnDemandHotspot
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_ManageHotspot : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_ManageHotspot();
00018
00019         Windows.UI.Xaml.Controls.ToggleSwitch CellularBarsToggle{ get; };
00020         Windows.UI.Xaml.Controls.ToggleSwitch BatteryPercentageToggle{ get; };
00021     }
00022
00023     [Windows.UI.Xaml.Data.Bindable]
00024     runtimeclass ODHModel : Windows.UI.Xaml.Data.INotifyPropertyChanged
00025     {
00026         String Id { get; };
00027         String DisplayName;
00028         Boolean IsAvailable;
00029         Boolean BarsVisible;
00030         Int32 Bars;
00031         Boolean BatteryVisible;
00032         Int32 BatteryPercent;
00033         String Ssid;
00034         String Password;
00035
00036         Boolean SaveButtonEnabled { get; };
00037         void Button_Click_Save();
00038         void Button_Click_ApplyNow();
00039     }
00040 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/DisplayHelpers.h Source File

  • DeviceEnumerationAndPairing
  • cpp

DisplayHelpers.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 namespace SDKTemplate
00006 {
00007     [Windows::UI::Xaml::Data::Bindable]
00008     public ref class DeviceSelectorInfo sealed
00009     {
00010     public:
00011         DeviceSelectorInfo(
00012             Platform::String^ displayName,
00013             Windows::Devices::Enumeration::DeviceClass deviceClassSelector,
00014             Platform::String^ selector)
00015         {
00016             Initialize(
00017                 displayName,
00018                 deviceClassSelector,
00019                 selector,
00020                 Windows::Devices::Enumeration::DeviceInformationKind::Unknown);
00021         }
00022
00023         DeviceSelectorInfo(
00024             Platform::String^ displayName,
00025             Windows::Devices::Enumeration::DeviceClass deviceClassSelector,
00026             Platform::String^ selector,
00027             Windows::Devices::Enumeration::DeviceInformationKind kind)
00028         {
00029             Initialize(
00030                 displayName,
00031                 deviceClassSelector,
00032                 selector,
00033                 kind);
00034         }
00035
00036         property Platform::String^ DisplayName;
00037         property Windows::Devices::Enumeration::DeviceClass DeviceClassSelector;
00038         property Windows::Devices::Enumeration::DeviceInformationKind Kind;
00039         property Platform::String^ Selector;
00040
00041     private:
00042
00043         void Initialize(
00044             Platform::String^ displayName,
00045             Windows::Devices::Enumeration::DeviceClass deviceClassSelector,
00046             Platform::String^ selector,
00047             Windows::Devices::Enumeration::DeviceInformationKind kind)
00048         {
00049             DisplayName = displayName;
00050             DeviceClassSelector = deviceClassSelector;
00051             Kind = kind;
00052             Selector = selector;
00053         }
00054     };
00055
00056
00057     [Windows::UI::Xaml::Data::Bindable]
00058     public ref struct DeviceSelectorChoices sealed
00059     {
00060     public:
00061
00062         static property Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ CommonDeviceSelectors
00063         {
00064             Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ get();
00065         }
00066
00067         static property DeviceSelectorInfo^ Bluetooth
00068         {
00069             DeviceSelectorInfo^ get();
00070         }
00071
00072         static property DeviceSelectorInfo^ BluetoothUnpairedOnly
00073         {
00074             DeviceSelectorInfo^ get();
00075         }
00076
00077         static property DeviceSelectorInfo^ BluetoothPairedOnly
00078         {
00079             DeviceSelectorInfo^ get();
00080         }
00081
00082         static property DeviceSelectorInfo^ BluetoothLE
00083         {
00084             DeviceSelectorInfo^ get();
00085         }
00086
00087         static property DeviceSelectorInfo^ BluetoothLEUnpairedOnly
00088         {
00089             DeviceSelectorInfo^ get();
00090         }
00091
00092         static property DeviceSelectorInfo^ BluetoothLEPairedOnly
00093         {
00094             DeviceSelectorInfo^ get();
00095         }
00096
00097         static property DeviceSelectorInfo^ WiFiDirect
00098         {
00099             DeviceSelectorInfo^ get();
00100         }
00101
00102         static property DeviceSelectorInfo^ WiFiDirectPairedOnly
00103         {
00104             DeviceSelectorInfo^ get();
00105         }
00106
00107         static property DeviceSelectorInfo^ PointOfServicePrinter
00108         {
00109             DeviceSelectorInfo^ get();
00110         }
00111
00112         static property DeviceSelectorInfo^ VideoCasting
00113         {
00114             DeviceSelectorInfo^ get();
00115         }
00116
00117         static property DeviceSelectorInfo^ DialAllApps
00118         {
00119             DeviceSelectorInfo^ get();
00120         }
00121
00122         static property DeviceSelectorInfo^ Wsd
00123         {
00124             DeviceSelectorInfo^ get();
00125         }
00126
00127         static property DeviceSelectorInfo^ Upnp
00128         {
00129             DeviceSelectorInfo^ get();
00130         }
00131
00132         static property DeviceSelectorInfo^ NetworkCamera
00133         {
00134             DeviceSelectorInfo^ get();
00135         }
00136
00137         static property Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ DevicePickerSelectors
00138         {
00139             Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ get();
00140         }
00141
00142         static property Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ FindAllAsyncSelectors
00143         {
00144             Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ get();
00145         }
00146
00147         static property Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ DeviceWatcherSelectors
00148         {
00149             Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ get();
00150         }
00151
00152         static property Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ BackgroundDeviceWatcherSelectors
00153         {
00154             Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ get();
00155         }
00156
00157         static property Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ PairingSelectors
00158         {
00159             Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ get();
00160         }
00161     };
00162
00163
00164     [Windows::UI::Xaml::Data::Bindable]
00165     public ref struct DeviceInformationKindChoice sealed
00166     {
00167     public:
00168         DeviceInformationKindChoice(
00169             Platform::String^ displayName,
00170             Windows::Foundation::Collections::IVectorView<Windows::Devices::Enumeration::DeviceInformationKind>^ deviceInformationKinds)
00171         {
00172             DisplayName = displayName;
00173             DeviceInformationKinds = deviceInformationKinds;
00174         }
00175         property Platform::String^ DisplayName;
00176         property Windows::Foundation::Collections::IVectorView<Windows::Devices::Enumeration::DeviceInformationKind>^ DeviceInformationKinds;
00177     };
00178
00179
00180     [Windows::UI::Xaml::Data::Bindable]
00181     public ref struct DeviceInformationKindChoices sealed
00182     {
00183     public:
00184
00185         static property Windows::Foundation::Collections::IVectorView<DeviceInformationKindChoice^>^ Choices
00186         {
00187             Windows::Foundation::Collections::IVectorView<DeviceInformationKindChoice^>^ get();
00188         }
00189     };
00190
00191     [Windows::UI::Xaml::Data::Bindable]
00192     public ref struct ProtectionLevelSelectorInfo sealed
00193     {
00194     public:
00195         ProtectionLevelSelectorInfo(
00196             Platform::String^ displayName,
00197             Windows::Devices::Enumeration::DevicePairingProtectionLevel protectionLevel)
00198         {
00199             DisplayName = displayName;
00200             ProtectionLevel = protectionLevel;
00201         }
00202         property Platform::String^ DisplayName;
00203         property Windows::Devices::Enumeration::DevicePairingProtectionLevel ProtectionLevel;
00204     };
00205
00206     [Windows::UI::Xaml::Data::Bindable]
00207     public ref struct ProtectionSelectorChoices sealed
00208     {
00209     public:
00210
00211         static property Windows::Foundation::Collections::IVectorView<ProtectionLevelSelectorInfo^>^ Selectors
00212         {
00213             Windows::Foundation::Collections::IVectorView<ProtectionLevelSelectorInfo^>^ get();
00214         }
00215     };
00216
00217     [Windows::UI::Xaml::Data::Bindable]
00218     public ref class DeviceInformationDisplay sealed : Windows::UI::Xaml::Data::INotifyPropertyChanged
00219     {
00220     public:
00221
00222         DeviceInformationDisplay(Windows::Devices::Enumeration::DeviceInformation^ deviceInfoIn);
00223
00224         property Windows::Devices::Enumeration::DeviceInformationKind Kind
00225         {
00226             Windows::Devices::Enumeration::DeviceInformationKind get() { return deviceInfo->Kind; }
00227         }
00228
00229         property Platform::String^ KindString
00230         {
00231             Platform::String^ get();
00232         }
00233
00234         property Platform::String^ Id
00235         {
00236             Platform::String^ get() { return deviceInfo->Id; }
00237         }
00238
00239         property Platform::String^ Name
00240         {
00241             Platform::String^ get() { return deviceInfo->Name; }
00242         }
00243
00244         property Windows::UI::Xaml::Media::Imaging::BitmapImage^ GlyphBitmapImage;
00245
00246         property Windows::Foundation::Collections::IMapView<Platform::String^, Platform::Object^>^ Properties
00247         {
00248             Windows::Foundation::Collections::IMapView<Platform::String^, Platform::Object^>^ get()
00249             {
00250                 return deviceInfo->Properties;
00251             }
00252         }
00253
00254         property Platform::String^ CanPair
00255         {
00256             Platform::String^ get()
00257             {
00258                 return deviceInfo->Pairing->CanPair ? "True" : "False";
00259             }
00260         }
00261
00262         property Platform::String^ IsPaired
00263         {
00264             Platform::String^ get()
00265             {
00266                 return deviceInfo->Pairing->IsPaired ? "True" : "False";
00267             }
00268         }
00269
00270         property Windows::Devices::Enumeration::DeviceInformation^ DeviceInfo
00271         {
00272             Windows::Devices::Enumeration::DeviceInformation^ get() { return deviceInfo; }
00273         }
00274
00275         void Update(Windows::Devices::Enumeration::DeviceInformationUpdate^ deviceInfoUpdateIn);
00276
00277         Platform::String^ GetPropertyForDisplay(Platform::String^ key)
00278         {
00279             return Properties->HasKey(key) ? Properties->Lookup(key)->ToString() : nullptr;
00280         }
00281
00282         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
00283
00284     protected:
00285
00286         void OnPropertyChanged(Platform::String^ name);
00287
00288     private:
00289
00290         void UpdateGlyphBitmapImage();
00291
00292         Windows::Devices::Enumeration::DeviceInformation^ deviceInfo;
00293     };
00294
00295     public ref class GeneralPropertyValueConverter sealed : Windows::UI::Xaml::Data::IValueConverter
00296     {
00297     public:
00298
00299         virtual Platform::Object^ Convert(
00300             Platform::Object^ value,
00301             Windows::UI::Xaml::Interop::TypeName targetType,
00302             Platform::Object^ parameter,
00303             Platform::String^ language);
00304
00305         virtual Platform::Object^ ConvertBack(
00306             Platform::Object^ value,
00307             Windows::UI::Xaml::Interop::TypeName targetType,
00308             Platform::Object^ parameter,
00309             Platform::String^ language)
00310         {
00311             throw ref new Platform::NotImplementedException();
00312         }
00313     };
00314 }
Generated on Fri Nov 15 2024 22:19:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario15_ServerCertificateValidation.cpp Source File

  • HttpClient
  • cppwinrt

Scenario15_ServerCertificateValidation.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario15_ServerCertificateValidation.h"
00014 #include "Scenario15_ServerCertificateValidation.g.cpp"
00015 #include "Helpers.h"
00016
00017 using namespace std::literals::chrono_literals;
00018 using namespace winrt;
00019 using namespace winrt::Windows::Foundation;
00020 using namespace winrt::Windows::Foundation::Collections;
00021 using namespace winrt::Windows::Security::Cryptography::Certificates;
00022 using namespace winrt::Windows::UI::Xaml;
00023 using namespace winrt::Windows::UI::Xaml::Navigation;
00024 using namespace winrt::Windows::Web::Http;
00025 using namespace winrt::Windows::Web::Http::Filters;
00026
00027
00028 namespace winrt::SDKTemplate::implementation
00029 {
00030     Scenario15_ServerCertificateValidation::Scenario15_ServerCertificateValidation()
00031     {
00032         InitializeComponent();
00033     }
00034
00035     void Scenario15_ServerCertificateValidation::OnNavigatedTo(NavigationEventArgs const&)
00036     {
00037         filter = HttpBaseProtocolFilter();
00038         httpClient = HttpClient(filter);
00039     }
00040
00041     void Scenario15_ServerCertificateValidation::OnNavigatedFrom(NavigationEventArgs const&)
00042     {
00043         httpClient.Close();
00044         filter.Close();
00045     }
00046
00047     fire_and_forget Scenario15_ServerCertificateValidation::Start_Click(IInspectable const&, RoutedEventArgs const&)
00048     {
00049         auto lifetime = get_strong();
00050
00051         // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00052         // valid, absolute URI, we'll notify the user about the incorrect input.
00053         Uri resourceUri = Helpers::TryParseHttpUri(AddressField().Text());
00054         if (!resourceUri)
00055         {
00056             rootPage.NotifyUser(L"Invalid URI.", NotifyType::ErrorMessage);
00057             return;
00058         }
00059
00060         Helpers::ScenarioStarted(StartButton(), CancelButton(), nullptr);
00061         rootPage.NotifyUser(L"In progress", NotifyType::StatusMessage);
00062
00063         event_token customValidationToken{};
00064         if (DefaultOSValidation().IsChecked().Value())
00065         {
00066             // Do nothing
00067         }
00068         else if (DefaultAndCustomValidation().IsChecked().Value())
00069         {
00070             // Add event handler to listen to the ServerCustomValidationRequested event. By default, OS validation
00071             // will be performed before the event is raised.
00072             customValidationToken = filter.ServerCustomValidationRequested({ get_weak(), &Scenario15_ServerCertificateValidation::MyCustomServerCertificateValidator });
00073         }
00074         else if (IgnoreErrorsAndCustomValidation().IsChecked().Value())
00075         {
00076             // ---------------------------------------------------------------------------
00077             // WARNING: Only test applications should ignore SSL errors.
00078             // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle
00079             // attacks (while the connection is secure, the server is not authenticated).
00080             // Note that not all certificate validation errors can be ignored.
00081             // ---------------------------------------------------------------------------
00082             filter.IgnorableServerCertificateErrors().ReplaceAll({ ChainValidationResult::Untrusted, ChainValidationResult::InvalidName });
00083
00084             // Add event handler to listen to the ServerCustomValidationRequested event.
00085             // This event handler must implement the desired custom certificate validation logic.
00086             customValidationToken = filter.ServerCustomValidationRequested({ get_weak(), &Scenario15_ServerCertificateValidation::MyCustomServerCertificateValidator });
00087         }
00088
00089         // Here, we turn off writing to and reading from the cache to ensure that each request actually
00090         // hits the network and tries to establish an SSL/TLS connection with the server.
00091         filter.CacheControl().WriteBehavior(HttpCacheWriteBehavior::NoCache);
00092         filter.CacheControl().ReadBehavior(HttpCacheReadBehavior::NoCache);
00093
00094         HttpRequestMessage request(HttpMethod::Get(), resourceUri);
00095
00096         // This sample uses a "try" in order to support cancellation.
00097         // If you don't need to support cancellation, then the "try" is not needed.
00098         try
00099         {
00100             pendingAction = CancelableRequestAsync(request);
00101             co_await pendingAction;
00102         }
00103         catch (hresult_canceled const&)
00104         {
00105             rootPage.NotifyUser(L"Request canceled.", NotifyType::ErrorMessage);
00106         }
00107
00108         if (customValidationToken)
00109         {
00110             // Unregister the event handler after we are done validating.
00111             filter.ServerCustomValidationRequested(customValidationToken);
00112         }
00113
00114         Helpers::ScenarioCompleted(StartButton(), CancelButton());
00115     }
00116
00117     IAsyncAction Scenario15_ServerCertificateValidation::CancelableRequestAsync(HttpRequestMessage request)
00118     {
00119         auto lifetime = get_strong();
00120         auto cancellation = co_await get_cancellation_token();
00121         cancellation.enable_propagation();
00122
00123         HttpRequestResult result = co_await httpClient.TrySendRequestAsync(request, HttpCompletionOption::ResponseHeadersRead);
00124
00125         if (result.Succeeded())
00126         {
00127             rootPage.NotifyUser(L"Success - response received from server. Server certificate was valid.", NotifyType::StatusMessage);
00128         }
00129         else
00130         {
00131             Helpers::DisplayWebError(rootPage, result.ExtendedError());
00132         }
00133     }
00134
00135     void Scenario15_ServerCertificateValidation::Cancel_Click(IInspectable const&, RoutedEventArgs const&)
00136     {
00137         if (pendingAction)
00138         {
00139             pendingAction.Cancel();
00140         }
00141     }
00142
00143     // This event handler for server certificate validation executes synchronously as part of the SSL/TLS handshake.
00144     // An app should not perform lengthy operations inside this handler. Otherwise, the remote server may terminate the connection abruptly.
00145     fire_and_forget Scenario15_ServerCertificateValidation::MyCustomServerCertificateValidator(
00146         HttpBaseProtocolFilter const&, HttpServerCustomValidationRequestedEventArgs args)
00147     {
00148         auto lifetime = get_strong();
00149
00150         // Get the server certificate and certificate chain from the args parameter.
00151         Certificate serverCert = args.ServerCertificate();
00152         IVectorView<Certificate> serverCertChain = args.ServerIntermediateCertificates();
00153
00154         // To illustrate the use of async APIs, we use the IsCertificateValidAsync method.
00155         // In order to call async APIs in this handler, you must first take a deferral and then
00156         // release it once you are done with the operation. In C++/WinRT, the deferral
00157         // is released upon destruction, or you can hasten its release by calling the
00158         // Complete() method prior to destruction.
00159         Deferral deferral = args.GetDeferral();
00160
00161         try
00162         {
00163             bool isCertificateValid = co_await IsCertificateValidAsync(serverCert);
00164             if (!isCertificateValid)
00165             {
00166                 args.Reject();
00167             }
00168         }
00169         catch (hresult_error const&)
00170         {
00171             // If we get an exception from IsCertificateValidAsync, we reject the certificate
00172             // (secure by default).
00173             args.Reject();
00174         }
00175     }
00176
00177     IAsyncOperation<bool> Scenario15_ServerCertificateValidation::IsCertificateValidAsync(Certificate serverCert)
00178     {
00179         auto lifetime = get_strong();
00180
00181         // This is a placeholder call to simulate long-running async calls. Note that this code runs synchronously as part of the SSL/TLS handshake.
00182         // Avoid performing lengthy operations here - else, the remote server may terminate the connection abruptly.
00183         co_await resume_after(100ms);
00184
00185         // In this sample, we compare the hash code of the certificate to a specific hash - this is purely
00186         // for illustration purposes and should not be considered as a recommendation for certificate validation.
00187         static constexpr std::array<uint8_t, 20> trustedHash{
00188             0x28, 0xb8, 0x85, 0x04, 0xf6, 0x09, 0xf6, 0x85, 0xf1, 0x68,
00189             0xb9, 0xa4, 0x9c, 0x8f, 0x0e, 0xc4, 0x9e, 0xad, 0x8b, 0xc2
00190         };
00191         if (serverCert.GetHashValue() == array_view(trustedHash))
00192         {
00193             // If certificate satisfies the criteria, return true.
00194             co_return true;
00195         }
00196         else
00197         {
00198             // If certificate does not meet the required criteria, return false.
00199             co_return false;
00200         }
00201     }
00202
00203     void Scenario15_ServerCertificateValidation::DefaultOSValidation_Checked(IInspectable const&, RoutedEventArgs const&)
00204     {
00205         AddressField().Text(L"https://www.microsoft.com");
00206     }
00207
00208     void Scenario15_ServerCertificateValidation::DefaultAndCustomValidation_Checked(IInspectable const&, RoutedEventArgs const&)
00209     {
00210         AddressField().Text(L"https://www.microsoft.com");
00211     }
00212
00213     void Scenario15_ServerCertificateValidation::IgnoreErrorsAndCustomValidation_Checked(IInspectable const&, RoutedEventArgs const&)
00214     {
00215         AddressField().Text(L"https://localhost/HttpClientSample/default.aspx");
00216     }
00217 }
Generated on Fri Nov 15 2024 22:19:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/Common/CameraResources.cpp Source File

  • SpatialInteractionSource
  • cpp
  • Common

CameraResources.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002
00003 #include "CameraResources.h"
00004 #include "Common\DirectXHelper.h"
00005 #include "DeviceResources.h"
00006 #include <windows.graphics.directx.direct3d11.interop.h>
00007
00008 using namespace DirectX;
00009 using namespace Microsoft::WRL;
00010 using namespace Windows::Graphics::DirectX::Direct3D11;
00011 using namespace Windows::Graphics::Holographic;
00012 using namespace Windows::Perception::Spatial;
00013
00014 DX::CameraResources::CameraResources(HolographicCamera^ camera) :
00015     m_holographicCamera(camera),
00016     m_isStereo(camera->IsStereo),
00017     m_d3dRenderTargetSize(camera->RenderTargetSize)
00018 {
00019     m_d3dViewport = CD3D11_VIEWPORT(
00020         0.f, 0.f,
00021         m_d3dRenderTargetSize.Width,
00022         m_d3dRenderTargetSize.Height
00023         );
00024 };
00025
00026 // Updates resources associated with a holographic camera's swap chain.
00027 // The app does not access the swap chain directly, but it does create
00028 // resource views for the back buffer.
00029 void DX::CameraResources::CreateResourcesForBackBuffer(
00030     DX::DeviceResources* pDeviceResources,
00031     HolographicCameraRenderingParameters^ cameraParameters
00032     )
00033 {
00034     const auto device = pDeviceResources->GetD3DDevice();
00035
00036     // Get the WinRT object representing the holographic camera's back buffer.
00037     IDirect3DSurface^ surface = cameraParameters->Direct3D11BackBuffer;
00038
00039     // Get a DXGI interface for the holographic camera's back buffer.
00040     // Holographic cameras do not provide the DXGI swap chain, which is owned
00041     // by the system. The Direct3D back buffer resource is provided using WinRT
00042     // interop APIs.
00043     ComPtr<ID3D11Resource> resource;
00044     ThrowIfFailed(
00045         GetDXGIInterfaceFromObject(surface, IID_PPV_ARGS(&resource))
00046         );
00047
00048     // Get a Direct3D interface for the holographic camera's back buffer.
00049     ComPtr<ID3D11Texture2D> cameraBackBuffer;
00050     ThrowIfFailed(
00051         resource.As(&cameraBackBuffer)
00052         );
00053
00054     // Determine if the back buffer has changed. If so, ensure that the render target view
00055     // is for the current back buffer.
00056     if (m_d3dBackBuffer.Get() != cameraBackBuffer.Get())
00057     {
00058         // This can change every frame as the system moves to the next buffer in the
00059         // swap chain. This mode of operation will occur when certain rendering modes
00060         // are activated.
00061         m_d3dBackBuffer = cameraBackBuffer;
00062
00063         // Create a render target view of the back buffer.
00064         // Creating this resource is inexpensive, and is better than keeping track of
00065         // the back buffers in order to pre-allocate render target views for each one.
00066         DX::ThrowIfFailed(
00067             device->CreateRenderTargetView(
00068                 m_d3dBackBuffer.Get(),
00069                 nullptr,
00070                 &m_d3dRenderTargetView
00071                 )
00072             );
00073
00074         // Get the DXGI format for the back buffer.
00075         // This information can be accessed by the app using CameraResources::GetBackBufferDXGIFormat().
00076         D3D11_TEXTURE2D_DESC backBufferDesc;
00077         m_d3dBackBuffer->GetDesc(&backBufferDesc);
00078         m_dxgiFormat = backBufferDesc.Format;
00079
00080         // Check for render target size changes.
00081         Windows::Foundation::Size currentSize = m_holographicCamera->RenderTargetSize;
00082         if (m_d3dRenderTargetSize != currentSize)
00083         {
00084             // Set render target size.
00085             m_d3dRenderTargetSize = currentSize;
00086
00087             // A new depth stencil view is also needed.
00088             m_d3dDepthStencilView.Reset();
00089         }
00090     }
00091
00092     // Refresh depth stencil resources, if needed.
00093     if (m_d3dDepthStencilView == nullptr)
00094     {
00095         // Create a depth stencil view for use with 3D rendering if needed.
00096         CD3D11_TEXTURE2D_DESC depthStencilDesc(
00097             DXGI_FORMAT_D16_UNORM,
00098             static_cast<UINT>(m_d3dRenderTargetSize.Width),
00099             static_cast<UINT>(m_d3dRenderTargetSize.Height),
00100             m_isStereo ? 2 : 1, // Create two textures when rendering in stereo.
00101             1, // Use a single mipmap level.
00102             D3D11_BIND_DEPTH_STENCIL
00103             );
00104
00105         ComPtr<ID3D11Texture2D> depthStencil;
00106         DX::ThrowIfFailed(
00107             device->CreateTexture2D(
00108                 &depthStencilDesc,
00109                 nullptr,
00110                 &depthStencil
00111                 )
00112             );
00113
00114         CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(
00115             m_isStereo ? D3D11_DSV_DIMENSION_TEXTURE2DARRAY : D3D11_DSV_DIMENSION_TEXTURE2D
00116             );
00117         DX::ThrowIfFailed(
00118             device->CreateDepthStencilView(
00119                 depthStencil.Get(),
00120                 &depthStencilViewDesc,
00121                 &m_d3dDepthStencilView
00122                 )
00123             );
00124     }
00125
00126     // Create the constant buffer, if needed.
00127     if (m_viewProjectionConstantBuffer == nullptr)
00128     {
00129         // Create a constant buffer to store view and projection matrices for the camera.
00130         CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00131         DX::ThrowIfFailed(
00132             device->CreateBuffer(
00133                 &constantBufferDesc,
00134                 nullptr,
00135                 &m_viewProjectionConstantBuffer
00136                 )
00137             );
00138     }
00139
00140     // Prepare blend state to allow stroke transparency
00141     if (m_blendState == nullptr)
00142     {
00143         D3D11_BLEND_DESC blendStateDesc;
00144         ZeroMemory(&blendStateDesc, sizeof(D3D11_BLEND_DESC));
00145         blendStateDesc.AlphaToCoverageEnable = FALSE;
00146         blendStateDesc.IndependentBlendEnable = FALSE;
00147         blendStateDesc.RenderTarget[0].BlendEnable = TRUE;
00148         blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
00149         blendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
00150         blendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
00151         blendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
00152         blendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_DEST_ALPHA;
00153         blendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
00154         blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
00155
00156         DX::ThrowIfFailed(
00157             device->CreateBlendState(&blendStateDesc, m_blendState.ReleaseAndGetAddressOf())
00158         );
00159     }
00160 }
00161
00162 // Releases resources associated with a back buffer.
00163 void DX::CameraResources::ReleaseResourcesForBackBuffer(DX::DeviceResources* pDeviceResources)
00164 {
00165     const auto context = pDeviceResources->GetD3DDeviceContext();
00166
00167     // Release camera-specific resources.
00168     m_d3dBackBuffer.Reset();
00169     m_d3dRenderTargetView.Reset();
00170     m_d3dDepthStencilView.Reset();
00171     m_viewProjectionConstantBuffer.Reset();
00172
00173     // Ensure system references to the back buffer are released by clearing the render
00174     // target from the graphics pipeline state, and then flushing the Direct3D context.
00175     ID3D11RenderTargetView* nullViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { nullptr };
00176     context->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00177     context->Flush();
00178 }
00179
00180 // Updates the view/projection constant buffer for a holographic camera.
00181 void DX::CameraResources::UpdateViewProjectionBuffer(
00182     std::shared_ptr<DX::DeviceResources> deviceResources,
00183     HolographicCameraPose^ cameraPose,
00184     SpatialCoordinateSystem^ coordinateSystem
00185     )
00186 {
00187     // The system changes the viewport on a per-frame basis for system optimizations.
00188     m_d3dViewport = CD3D11_VIEWPORT(
00189         cameraPose->Viewport.Left,
00190         cameraPose->Viewport.Top,
00191         cameraPose->Viewport.Width,
00192         cameraPose->Viewport.Height
00193         );
00194
00195     // The projection transform for each frame is provided by the HolographicCameraPose.
00196     HolographicStereoTransform cameraProjectionTransform = cameraPose->ProjectionTransform;
00197
00198     // Get a container object with the view and projection matrices for the given
00199     // pose in the given coordinate system.
00200     Platform::IBox<HolographicStereoTransform>^ viewTransformContainer = cameraPose->TryGetViewTransform(coordinateSystem);
00201
00202     // If TryGetViewTransform returns a null pointer, that means the pose and coordinate
00203     // system cannot be understood relative to one another; content cannot be rendered
00204     // in this coordinate system for the duration of the current frame.
00205     // This usually means that positional tracking is not active for the current frame, in
00206     // which case it is possible to use a SpatialLocatorAttachedFrameOfReference to render
00207     // content that is not world-locked instead.
00208     DX::ViewProjectionConstantBuffer viewProjectionConstantBufferData;
00209     bool viewTransformAcquired = viewTransformContainer != nullptr;
00210     if (viewTransformAcquired)
00211     {
00212         // Otherwise, the set of view transforms can be retrieved.
00213         HolographicStereoTransform viewCoordinateSystemTransform = viewTransformContainer->Value;
00214
00215         // Update the view matrices. Holographic cameras (such as Microsoft HoloLens) are
00216         // constantly moving relative to the world. The view matrices need to be updated
00217         // every frame.
00218         XMStoreFloat4x4(
00219             &viewProjectionConstantBufferData.viewProjection[0],
00220             XMMatrixTranspose(XMLoadFloat4x4(&viewCoordinateSystemTransform.Left) * XMLoadFloat4x4(&cameraProjectionTransform.Left))
00221             );
00222         XMStoreFloat4x4(
00223             &viewProjectionConstantBufferData.viewProjection[1],
00224             XMMatrixTranspose(XMLoadFloat4x4(&viewCoordinateSystemTransform.Right) * XMLoadFloat4x4(&cameraProjectionTransform.Right))
00225             );
00226     }
00227
00228     // Use the D3D device context to update Direct3D device-based resources.
00229     const auto context = deviceResources->GetD3DDeviceContext();
00230
00231     // Loading is asynchronous. Resources must be created before they can be updated.
00232     if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || !viewTransformAcquired)
00233     {
00234         m_framePending = false;
00235     }
00236     else
00237     {
00238         // Update the view and projection matrices.
00239         context->UpdateSubresource(
00240             m_viewProjectionConstantBuffer.Get(),
00241             0,
00242             nullptr,
00243             &viewProjectionConstantBufferData,
00244             0,
00245             0
00246             );
00247
00248         m_framePending = true;
00249     }
00250 }
00251
00252 // Gets the view-projection constant buffer for the HolographicCamera and attaches it
00253 // to the shader pipeline.
00254 bool DX::CameraResources::AttachViewProjectionBuffer(
00255     std::shared_ptr<DX::DeviceResources> deviceResources
00256     )
00257 {
00258     // This method uses Direct3D device-based resources.
00259     const auto context = deviceResources->GetD3DDeviceContext();
00260
00261     // Loading is asynchronous. Resources must be created before they can be updated.
00262     // Cameras can also be added asynchronously, in which case they must be initialized
00263     // before they can be used.
00264     if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || m_framePending == false)
00265     {
00266         return false;
00267     }
00268
00269     // Set the viewport for this camera.
00270     context->RSSetViewports(1, &m_d3dViewport);
00271
00272     // Send the constant buffer to the vertex shader.
00273     context->VSSetConstantBuffers(
00274         1,
00275         1,
00276         m_viewProjectionConstantBuffer.GetAddressOf()
00277         );
00278
00279     // The template includes a pass-through geometry shader that is used by
00280     // default on systems that don't support the D3D11_FEATURE_D3D11_OPTIONS3::
00281     // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer extension. The shader
00282     // will be enabled at run-time on systems that require it.
00283     // If your app will also use the geometry shader for other tasks and those
00284     // tasks require the view/projection matrix, uncomment the following line
00285     // of code to send the constant buffer to the geometry shader as well.
00286     /*context->GSSetConstantBuffers(
00287         1,
00288         1,
00289         m_viewProjectionConstantBuffer.GetAddressOf()
00290         );*/
00291
00292     m_framePending = false;
00293
00294     return true;
00295 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStarterKit/cpp/pch.cpp Source File

  • CameraStarterKit
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AnimationMetrics/cs/Scenario1_Metrics.xaml.cs Source File

  • AnimationMetrics
  • cs

Scenario1_Metrics.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using Windows.UI.Core.AnimationMetrics;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario1_Metrics : Page
00020     {
00021         private MainPage rootPage;
00022
00023         public Scenario1_Metrics()
00024         {
00025             this.InitializeComponent();
00026         }
00027
00028         protected override void OnNavigatedTo(NavigationEventArgs e)
00029         {
00030             rootPage = MainPage.Current;
00031         }
00032
00033         /// <summary>
00034         /// Retrieves the specified metrics and displays them in textual form.
00035         /// </summary>
00036         /// <param name="effect">The AnimationEffect whose metrics are to be displayed.</param>
00037         /// <param name="target">The AnimationEffecTarget whose metrics are to be displayed.</param>
00038         private void DisplayMetrics(AnimationEffect effect, AnimationEffectTarget target)
00039         {
00040             var s = new System.Text.StringBuilder();
00041             AnimationDescription animationDescription = new AnimationDescription(effect, target);
00042             s.AppendFormat("Stagger delay = {0}ms", animationDescription.StaggerDelay.TotalMilliseconds);
00043             s.AppendLine();
00044             s.AppendFormat("Stagger delay factor = {0}", animationDescription.StaggerDelayFactor);
00045             s.AppendLine();
00046             s.AppendFormat("Delay limit = {0}ms", animationDescription.DelayLimit.TotalMilliseconds);
00047             s.AppendLine();
00048             s.AppendFormat("ZOrder = {0}", animationDescription.ZOrder);
00049             s.AppendLine();
00050             s.AppendLine();
00051
00052             int animationIndex = 0;
00053             foreach (var animation in animationDescription.Animations)
00054             {
00055                 s.AppendFormat("Animation #{0}:", ++animationIndex);
00056                 s.AppendLine();
00057
00058                 switch (animation.Type)
00059                 {
00060                     case PropertyAnimationType.Scale:
00061                         {
00062                             ScaleAnimation scale = animation as ScaleAnimation;
00063                             s.AppendLine("Type = Scale");
00064                             if (scale.InitialScaleX.HasValue)
00065                             {
00066                                 s.AppendFormat("InitialScaleX = {0}", scale.InitialScaleX.Value);
00067                                 s.AppendLine();
00068                             }
00069                             if (scale.InitialScaleY.HasValue)
00070                             {
00071                                 s.AppendFormat("InitialScaleY = {0}", scale.InitialScaleY.Value);
00072                                 s.AppendLine();
00073                             }
00074                             s.AppendFormat("FinalScaleX = {0}", scale.FinalScaleX);
00075                             s.AppendLine();
00076                             s.AppendFormat("FinalScaleY = {0}", scale.FinalScaleY);
00077                             s.AppendLine();
00078                             s.AppendFormat("Origin = {0}, {1}", scale.NormalizedOrigin.X, scale.NormalizedOrigin.Y);
00079                             s.AppendLine();
00080                         }
00081                         break;
00082                     case PropertyAnimationType.Translation:
00083                         s.AppendLine("Type = Translation");
00084                         break;
00085                     case PropertyAnimationType.Opacity:
00086                         {
00087                             OpacityAnimation opacity = animation as OpacityAnimation;
00088                             s.AppendLine("Type = Opacity");
00089                             if (opacity.InitialOpacity.HasValue)
00090                             {
00091                                 s.AppendFormat("InitialOpacity = {0}", opacity.InitialOpacity.Value);
00092                                 s.AppendLine();
00093                             }
00094                             s.AppendFormat("FinalOpacity = {0}", opacity.FinalOpacity);
00095                             s.AppendLine();
00096                         }
00097                         break;
00098                 }
00099
00100                 s.AppendFormat("Delay = {0}ms", animation.Delay.TotalMilliseconds);
00101                 s.AppendLine();
00102                 s.AppendFormat("Duration = {0}ms", animation.Duration.TotalMilliseconds);
00103                 s.AppendLine();
00104                 s.AppendFormat("Cubic Bezier control points");
00105                 s.AppendLine();
00106                 s.AppendFormat("    X1 = {0}, Y1 = {1}", animation.Control1.X, animation.Control1.Y);
00107                 s.AppendLine();
00108                 s.AppendFormat("    X2 = {0}, Y2 = {1}", animation.Control2.X, animation.Control2.Y);
00109                 s.AppendLine();
00110                 s.AppendLine();
00111             }
00112
00113             Metrics.Text = s.ToString();
00114         }
00115
00116         /// <summary>
00117         /// When the selection changes, update the output window.
00118         /// </summary>
00119         /// <param name="sender"></param>
00120         /// <param name="e"></param>
00121         private void Animations_SelectionChanged(object sender, SelectionChangedEventArgs e)
00122         {
00123             ListBox lb = sender as ListBox;
00124             if (lb != null)
00125             {
00126                 object selectedListBoxItem = lb.SelectedItem;
00127                 if (selectedListBoxItem == AddToListAdded)
00128                 {
00129                     DisplayMetrics(AnimationEffect.AddToList, AnimationEffectTarget.Added);
00130                 }
00131                 else if (selectedListBoxItem == AddToListAffected)
00132                 {
00133                     DisplayMetrics(AnimationEffect.AddToList, AnimationEffectTarget.Affected);
00134                 }
00135                 else if (selectedListBoxItem == EnterPage)
00136                 {
00137                     DisplayMetrics(AnimationEffect.EnterPage, AnimationEffectTarget.Primary);
00138                 }
00139             }
00140         }
00141     }
00142 }
Generated on Fri Nov 15 2024 22:17:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

OcrFileImage Member List

This is the complete list of members for OcrFileImage, including all inherited members.
ClearResults() | OcrFileImage | [private]
ExtractButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | OcrFileImage |
LanguageList_SelectionChanged(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | OcrFileImage |
LoadButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | OcrFileImage |
LoadImageAsync(Windows::Storage::StorageFile const &file) | OcrFileImage | [private]
LoadSampleImageAsync() | OcrFileImage | [private]
OcrFileImage() | OcrFileImage |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | OcrFileImage |
PreviewImage_SizeChanged(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | OcrFileImage |
SampleButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | OcrFileImage |
UpdateAvailableLanguages() | OcrFileImage | [private]
UpdateWordBoxTransform() | OcrFileImage | [private]
UserLanguageToggle_Toggled(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | OcrFileImage |
wordBoxes | OcrFileImage | [private]
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cpp/pch.h Source File

  • BasicInput
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/Helpers/BindableBase.cs Source File

  • Notifications
  • cs
  • Notifications
  • Helpers

BindableBase.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.ComponentModel;
00003 using System.Runtime.CompilerServices;
00004
00005 namespace Notifications.Helpers
00006 {
00007     /// <summary>
00008     /// From http://danrigby.com/2012/04/01/inotifypropertychanged-the-net-4-5-way-revisited/
00009     /// </summary>
00010     public abstract class BindableBase : INotifyPropertyChanged
00011     {
00012         public event PropertyChangedEventHandler PropertyChanged;
00013
00014         protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
00015         {
00016             if (Equals(storage, value))
00017             {
00018                 return false;
00019             }
00020
00021             storage = value;
00022             this.OnPropertyChanged(propertyName);
00023             return true;
00024         }
00025
00026         protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
00027         {
00028             PropertyChangedEventHandler eventHandler = this.PropertyChanged;
00029             if (eventHandler != null)
00030             {
00031                 eventHandler(this, new PropertyChangedEventArgs(propertyName));
00032             }
00033         }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Colors Member List

This is the complete list of members for Scenario1_Colors, including all inherited members.
m_propertyChanged | Scenario1_Colors | [private]
PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const &handler) | Scenario1_Colors |
PropertyChanged(event_token const &token) noexcept | Scenario1_Colors |
Scenario1_Colors() | Scenario1_Colors |
TitleBar() | Scenario1_Colors | [inline]
UpdateColors() | Scenario1_Colors | [private]
UseCustomColors_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Colors |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LibraryManagement/cs/S3_RemoveFolder.xaml.cs Source File

  • LibraryManagement
  • cs

S3_RemoveFolder.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Foundation.Collections;
00014 using Windows.Storage;
00015 using Windows.UI.Core;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class Scenario3 : Page
00026     {
00027         StorageLibrary picturesLibrary;
00028
00029         public Scenario3()
00030         {
00031             this.InitializeComponent();
00032             this.GetPicturesLibrary();
00033         }
00034
00035         /// <summary>
00036         /// Invoked when this page is about to be displayed in a Frame.
00037         /// </summary>
00038         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00039         /// property is typically used to configure the page.</param>
00040         protected override void OnNavigatedTo(NavigationEventArgs e)
00041         {
00042         }
00043
00044         /// <summary>
00045         /// Requests the user's permission to remove the selected location from the Pictures library.
00046         /// </summary>
00047         /// <param name="sender"></param>
00048         /// <param name="e"></param>
00049         private async void RemoveFolderButton_Click(object sender, RoutedEventArgs e)
00050         {
00051             var folderToRemove = (StorageFolder)FoldersComboBox.SelectedItem;
00052             if (await picturesLibrary.RequestRemoveFolderAsync(folderToRemove))
00053             {
00054                 OutputTextBlock.Text = folderToRemove.DisplayName + " was removed from the Pictures library.";
00055             }
00056             else
00057             {
00058                 OutputTextBlock.Text = "Operation canceled.";
00059             }
00060         }
00061
00062         /// <summary>
00063         /// Gets the Pictures library and sets up the FoldersComboBox to list its folders.
00064         /// </summary>
00065         private async void GetPicturesLibrary()
00066         {
00067             picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
00068
00069             // Bind the ComboBox to the list of folders currently in the library
00070             FoldersComboBox.ItemsSource = picturesLibrary.Folders;
00071
00072             // Update the states of our controls when the list of folders changes
00073             picturesLibrary.DefinitionChanged += async (StorageLibrary sender, object e) =>
00074                 {
00075                     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00076                     {
00077                         UpdateControls();
00078                     });
00079                 };
00080
00081             UpdateControls();
00082         }
00083
00084         /// <summary>
00085         // Fills the ComboBox control with the folders that make up the Pictures library.
00086         /// </summary>
00087         private void FillComboBox()
00088         {
00089             FoldersComboBox.ItemsSource = null;
00090             FoldersComboBox.ItemsSource = picturesLibrary.Folders;
00091         }
00092
00093         /// <summary>
00094         /// Updates the Visibility and IsEnabled properties of UI controls that depend upon the Pictures library
00095         /// having at least one folder in its Folders list.
00096         /// </summary>
00097         private void UpdateControls()
00098         {
00099             FillComboBox();
00100             bool libraryHasFolders = (picturesLibrary.Folders.Count > 0);
00101             FoldersComboBox.SelectedIndex = libraryHasFolders ? 0 : -1;
00102             FoldersComboBox.Visibility = libraryHasFolders ? Visibility.Visible : Visibility.Collapsed;
00103             LibraryEmptyTextBlock.Visibility = libraryHasFolders ? Visibility.Collapsed : Visibility.Visible;
00104             RemoveFolderButton.IsEnabled = libraryHasFolders;
00105         }
00106     }
00107 }
Generated on Fri Nov 15 2024 22:20:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cppwinrt/Scenario1_PinTile.cpp Source File

  • SecondaryTiles
  • cppwinrt

Scenario1_PinTile.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_PinTile.h"
00014 #include "Scenario1_PinTile.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::UI::StartScreen;
00020 using namespace Windows::UI::Xaml;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     Scenario1_PinTile::Scenario1_PinTile()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     fire_and_forget Scenario1_PinTile::PinButton_Click(IInspectable const& sender, RoutedEventArgs const&)
00030     {
00031         auto lifetime = get_strong();
00032
00033         // Prepare package images for the tile sizes in our tile to be pinned as well as for the square30x30 logo used in the Apps view.
00034         Uri square150x150Logo(L"ms-appx:///Assets/square150x150Tile-sdk.png");
00035         Uri wide310x150Logo(L"ms-appx:///Assets/wide310x150Tile-sdk.png");
00036         Uri square310x310Logo(L"ms-appx:///Assets/square310x310Tile-sdk.png");
00037
00038         // During creation of secondary tile, an application may set additional arguments on the tile that will be passed in during activation,
00039         // so that the app knows which tile the user is launching. In this sample, we'll pass in the date and time the secondary tile was pinned.
00040         hstring tileActivationArguments = hstring(SampleHelpers::LogoSecondaryTileId) + L" WasPinnedAt=" + SampleHelpers::CurrentTimeAsString();
00041
00042         // Create a Secondary tile with all the required arguments.
00043         // Note the last argument specifies what size the Secondary tile should show up as by default in the Pin to start fly out.
00044         // It can be set to TileSize.Square150x150, TileSize.Wide310x150, or TileSize.Default.
00045         // If set to TileSize.Wide310x150, then the asset for the wide size must be supplied as well.
00046         // TileSize.Default will default to the wide size if a wide size is provided, and to the medium size otherwise.
00047         SecondaryTile secondaryTile(SampleHelpers::LogoSecondaryTileId,
00048             L"Title text shown on the tile",
00049             tileActivationArguments,
00050             square150x150Logo,
00051             TileSize::Square150x150);
00052
00053         secondaryTile.VisualElements().Wide310x150Logo(wide310x150Logo);
00054         secondaryTile.VisualElements().Square310x310Logo(square310x310Logo);
00055
00056         // The display of the secondary tile name can be controlled for each tile size.
00057         // The default is false.
00058         secondaryTile.VisualElements().ShowNameOnSquare150x150Logo(true);
00059         secondaryTile.VisualElements().ShowNameOnWide310x150Logo(true);
00060         secondaryTile.VisualElements().ShowNameOnSquare310x310Logo(true);
00061
00062         // Specify a foreground text value.
00063         // The tile background color is inherited from the parent unless a separate value is specified.
00064         secondaryTile.VisualElements().ForegroundText(ForegroundText::Dark);
00065
00066         // Set this to false if roaming doesn't make sense for the secondary tile.
00067         // The default is true.
00068         secondaryTile.RoamingEnabled(false);
00069
00070         // The tile is created and we can now attempt to pin the tile.
00071         // Note that the status message is updated when the async operation to pin the tile completes.
00072         bool isPinned = co_await secondaryTile.RequestCreateForSelectionAsync(SampleHelpers::GetElementRect(sender), Windows::UI::Popups::Placement::Below);
00073
00074         if (isPinned)
00075         {
00076             rootPage.NotifyUser(L"Secondary tile successfully pinned.", NotifyType::StatusMessage);
00077         }
00078         else
00079         {
00080             rootPage.NotifyUser(L"Secondary tile not pinned.", NotifyType::ErrorMessage);
00081         }
00082     }
00083 }
Generated on Fri Nov 15 2024 22:21:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GameMain Member List

This is the complete list of members for GameMain, including all inherited members.
Close() | GameMain | [inline]
Close() | GameMain | [inline]
ConstructInBackground() | GameMain | [private]
CreateWindowSizeDependentResources() | GameMain |
CreateWindowSizeDependentResources() | GameMain |
CreateWindowSizeDependentResources() | GameMain |
CycleBackground() | GameMain |
GameMain(const std::shared_ptr< DX::DeviceResources > &deviceResources) | GameMain |
GameMain(std::shared_ptr< DX::DeviceResources > const &deviceResources) | GameMain |
GameMain(const std::shared_ptr< DX::DeviceResources > &deviceResources, Simple3DGameXaml::IGameUIControl^UIControl) | GameMain |
GetCriticalSection() | GameMain | [inline]
HandleDeviceRestored() | GameMain | [private]
InitializeGameState() | GameMain | [private]
InitializeGameState() | GameMain | [private]
InitializeGameState() | GameMain | [private]
InitializeLicense() | GameMain | [private]
InitializeLicenseCore() | GameMain | [private]
LicenseChanged(Windows::ApplicationModel::Store::ListingInformation^listing, Windows::ApplicationModel::Store::LicenseInformation^license) | GameMain |
LoadAndFinalizeLevelInBackground(bool renderNeeded=false) | GameMain | [private]
m_controller | GameMain | [private]
m_controller | GameMain | [private]
m_criticalSection | GameMain | [private]
m_deviceResources | GameMain | [private]
m_game | GameMain | [private]
m_game | GameMain | [private]
m_gameInfoOverlayCommand | GameMain | [private]
m_gameInfoOverlayState | GameMain | [private]
m_haveFocus | GameMain | [private]
m_licenseInformation | GameMain | [private]
m_listingInformation | GameMain | [private]
m_loadingCount | GameMain | [private]
m_loadingCount | GameMain | [private]
m_pauseRequested | GameMain | [private]
m_pressComplete | GameMain | [private]
m_pressResult | GameMain | [private]
m_renderer | GameMain | [private]
m_renderer | GameMain | [private]
m_renderLoopWorker | GameMain | [private]
m_renderNeeded | GameMain | [private]
m_uiControl | GameMain | [private]
m_uiControl | GameMain | [private]
m_uiControl | GameMain | [private]
m_updateState | GameMain | [private]
m_updateStateNext | GameMain | [private]
m_visible | GameMain | [private]
m_windowClosed | GameMain | [private]
OnDeviceLost() | GameMain | [virtual]
OnDeviceLost() | GameMain | [virtual]
OnDeviceLost() | GameMain | [virtual]
OnDeviceRestored() | GameMain | [virtual]
OnDeviceRestored() | GameMain | [virtual]
OnDeviceRestored() | GameMain | [virtual]
OnLicenseChanged() | GameMain | [private]
PauseRequested() | GameMain | [inline]
PauseRequested() | GameMain | [inline]
PauseRequested() | GameMain | [inline]
PressComplete() | GameMain | [inline]
PressComplete() | GameMain | [inline]
PressComplete() | GameMain | [inline]
ResetGame() | GameMain |
ResetGame() | GameMain |
ResetGame() | GameMain |
Resume() | GameMain |
Resume() | GameMain |
Resume() | GameMain |
Run() | GameMain |
Run() | GameMain |
SetBackground(unsigned int background) | GameMain |
SetGameInfoOverlay(GameControl::GameInfoOverlayState state) | GameMain | [private]
SetGameInfoOverlay(GameControl::GameInfoOverlayState state) | GameMain | [private]
SetGameInfoOverlay(GameControl::GameInfoOverlayState state) | GameMain | [private]
StartRenderLoop() | GameMain |
StopRenderLoop() | GameMain |
Suspend() | GameMain |
Suspend() | GameMain |
Suspend() | GameMain |
Update() | GameMain | [private]
Update() | GameMain | [private]
Update() | GameMain | [private]
UpdateLayoutState() | GameMain | [private]
UpdateLayoutState() | GameMain | [private]
UpdateLayoutState() | GameMain | [private]
Visibility(bool visible) | GameMain |
Visibility(bool visible) | GameMain |
WaitingForResourceLoading() | GameMain | [private]
WaitingForResourceLoading() | GameMain | [private]
WindowActivationChanged(Windows::UI::Core::CoreWindowActivationState activationState) | GameMain |
WindowActivationChanged(winrt::Windows::UI::Core::CoreWindowActivationState activationState) | GameMain |
WindowActivationChanged(Windows::UI::Core::CoreWindowActivationState activationState) | GameMain |
~GameMain() | GameMain |
~GameMain() | GameMain |
~GameMain() | GameMain |
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PersonalDataEncryption/cppwinrt/Scenario2_Memory.h Source File

  • PersonalDataEncryption
  • cppwinrt

Scenario2_Memory.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Memory.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario2_Memory : Scenario2_MemoryT<Scenario2_Memory>
00020     {
00021         Scenario2_Memory();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024
00025         fire_and_forget ProtectL1_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026         fire_and_forget ProtectL2_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         fire_and_forget Unprotect_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028
00029     private:
00030         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00031         winrt::Windows::Security::DataProtection::UserDataProtectionManager userDataProtectionManager{ nullptr };
00032         winrt::Windows::Storage::Streams::IBuffer protectedBuffer{ nullptr };
00033
00034         void ReportProtectedBuffer(Windows::Storage::Streams::IBuffer const& buffer);
00035     };
00036 }
00037
00038 namespace winrt::SDKTemplate::factory_implementation
00039 {
00040     struct Scenario2_Memory : Scenario2_MemoryT<Scenario2_Memory, implementation::Scenario2_Memory>
00041     {
00042     };
00043 }
Generated on Fri Nov 15 2024 22:20:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_Msappdata Member List

This is the complete list of members for Scenario5_Msappdata, including all inherited members.
OnNavigatedTo(NavigationEventArgs e) | Scenario5_Msappdata | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario5_Msappdata | [inline, protected]
Scenario5_Msappdata() | Scenario5_Msappdata | [inline]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DftTransform Member List

This is the complete list of members for DftTransform, including all inherited members.
CalculateThreadgroups(_In_ const D2D1_RECT_L *pOutputRect, _Out_ UINT32 *pDimensionX, _Out_ UINT32 *pDimensionY, _Out_ UINT32 *pDimensionZ) | DftTransform |
DftTransform(_In_ ID2D1EffectContext *context, TransformType dftType) | DftTransform |
IFACEMETHODIMP_(UINT32) GetInputCount() const | DftTransform | [inline]
IFACEMETHODIMP_(ULONG) AddRef() | DftTransform |
IFACEMETHODIMP_(ULONG) Release() | DftTransform |
m_constantBuffer | DftTransform | [private]
m_cRef | DftTransform | [private]
m_dftType | DftTransform | [private]
m_inputRect | DftTransform | [private]
m_maxLevelSupported | DftTransform | [private]
magnitudeScale | DftTransform |
MapInputRectsToOutputRect(_In_reads_(inputRectCount) const D2D1_RECT_L *pInputRects, _In_reads_(inputRectCount) const D2D1_RECT_L *pInputOpaqueSubRects, UINT32 inputRectCount, _Out_ D2D1_RECT_L *pOutputRect, _Out_ D2D1_RECT_L *pOutputOpaqueSubRect) | DftTransform |
MapInvalidRect(UINT32 inputIndex, D2D1_RECT_L invalidInputRect, _Out_ D2D1_RECT_L *pInvalidOutputRect) const | DftTransform |
MapOutputRectToInputRects(_In_ const D2D1_RECT_L *pOutputRect, _Out_writes_(inputRectCount) D2D1_RECT_L *pInputRects, UINT32 inputRectCount) const | DftTransform |
QueryInterface(REFIID riid, _Outptr_ void **ppOutput) | DftTransform |
SetComputeInfo(_In_ ID2D1ComputeInfo *pComputeInfo) | DftTransform |
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Polling Member List

This is the complete list of members for Scenario2_Polling, including all inherited members.
_desiredReportInterval | Scenario2_Polling | [private]
_dispatcherTimer | Scenario2_Polling | [private]
_inclinometer | Scenario2_Polling | [private]
DisplayCurrentReading(object sender, object args) | Scenario2_Polling | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_Polling | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario2_Polling | [inline, protected]
rootPage | Scenario2_Polling | [private]
Scenario2_Polling() | Scenario2_Polling | [inline]
ScenarioDisable(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
ScenarioEnable(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario2_Polling | [inline, private]
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactPicker/cpp/Scenario2_Multiple.xaml.h Source File

  • ContactPicker
  • cpp

Scenario2_Multiple.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Multiple.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario2_Multiple sealed
00021     {
00022     public:
00023         Scenario2_Multiple();
00024         void PickContactsEmail();
00025         void PickContactsPhone();
00026
00027     private:
00028         MainPage^ rootPage = MainPage::Current;
00029
00030         void ClearOutputs();
00031         void ReportContactResults(Windows::Foundation::Collections::IVector<Windows::ApplicationModel::Contacts::Contact^>^ contacts);
00032     };
00033 }
Generated on Fri Nov 15 2024 22:18:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Common/DirectXHelper.h Source File

  • HolographicFaceTracking
  • cpp
  • Common

DirectXHelper.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace DX
00015 {
00016     inline void ThrowIfFailed(HRESULT hr)
00017     {
00018         if (FAILED(hr))
00019         {
00020             // Set a breakpoint on this line to catch Win32 API errors.
00021             throw Platform::Exception::CreateException(hr);
00022         }
00023     }
00024
00025     // Function that reads from a binary file asynchronously.
00026     inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename)
00027     {
00028         using namespace Windows::Storage;
00029         using namespace Concurrency;
00030
00031         return create_task(PathIO::ReadBufferAsync(Platform::StringReference(filename.c_str()))).then(
00032             [] (Streams::IBuffer^ fileBuffer) -> std::vector<byte>
00033             {
00034                 std::vector<byte> returnBuffer;
00035                 returnBuffer.resize(fileBuffer->Length);
00036                 Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), returnBuffer.size()));
00037                 return returnBuffer;
00038             });
00039     }
00040
00041     // Converts a length in device-independent pixels (DIPs) to a length in physical pixels.
00042     inline float ConvertDipsToPixels(float dips, float dpi)
00043     {
00044         static const float dipsPerInch = 96.0f;
00045         return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00046     }
00047
00048 #if defined(_DEBUG)
00049     // Check for SDK Layer support.
00050     inline bool SdkLayersAvailable()
00051     {
00052         HRESULT hr = D3D11CreateDevice(
00053             nullptr,
00054             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00055             0,
00056             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00057             nullptr,                    // Any feature level will do.
00058             0,
00059             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00060             nullptr,                    // No need to keep the D3D device reference.
00061             nullptr,                    // No need to know the feature level.
00062             nullptr                     // No need to keep the D3D device context reference.
00063             );
00064
00065         return SUCCEEDED(hr);
00066     }
00067 #endif
00068 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCorrelation/cpp/PoseTrackingPreview/MFPoseTrackingFrame.h Source File

  • CameraStreamCorrelation
  • cpp
  • PoseTrackingPreview

MFPoseTrackingFrame.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Namespace and types to parse MediaFoundation perception buffer payload.
00015 namespace MFPoseTrackingPreview
00016 {
00017
00018     enum class TrackingStatus : int32_t {
00019         NotTracked = 0,
00020         Inferred = 1,
00021         Tracked = 2,
00022     };
00023
00024     // When PoseSet field of PoseTrackingEntity is set to PoseSet_BodyTracking, the
00025     // Poses of the PoseTrackingEntity follow the order defined by this enum
00026     enum class BodyPart : int32_t {
00027         SpineBase = 0,
00028         SpineMid = 1,
00029         Neck = 2,
00030         Head = 3,
00031         ShoulderLeft = 4,
00032         ElbowLeft = 5,
00033         WristLeft = 6,
00034         HandLeft = 7,
00035         ShoulderRight = 8,
00036         ElbowRight = 9,
00037         WristRight = 10,
00038         HandRight = 11,
00039         HipLeft = 12,
00040         KneeLeft = 13,
00041         AnkleLeft = 14,
00042         FootLeft = 15,
00043         HipRight = 16,
00044         KneeRight = 17,
00045         AnkleRight = 18,
00046         FootRight = 19,
00047         SpineShoulder = 20,
00048         HandTipLeft = 21,
00049         ThumbLeft = 22,
00050         HandTipRight = 23,
00051         ThumbRight = 24,
00052     };
00053
00054     struct TrackedPose {
00055         TrackingStatus PositionStatus;
00056         Windows::Foundation::Numerics::float3 Position;
00057         TrackingStatus OrientationStatus;
00058         Windows::Foundation::Numerics::quaternion Orientation;
00059     };
00060
00061     // The layout of a pose frame buffer is:
00062     //   1. PoseTrackingFrameHeader: Common structure for all providers.
00063     //      1. CustomDataTypeGuid: Guid corresponding to specific provider (16 bytes).
00064     //      2. EntitiesCount: How many entities are in this frame (4 bytes).
00065     //      3. EntityOffsets: Offsets of entity data from buffer start (4 * EntitiesCount bytes).
00066     //
00067     //   2. Provider-specific, per-frame data.
00068     //
00069     //   3. PoseTrackingEntityData #0: First entity data. Common structure for all providers.
00070     //      1. DataSizeInBytes: Size of entire entity (PoseTrackingEntityData + custom data) in bytes (4 bytes).
00071     //      2. EntityId: Allows correlation between frames (16 bytes).
00072     //      3. PoseSet: Guids for Body (such as Kinect), Handtracking, etc.: defines the meaning of each Pose (16 bytes).
00073     //      4. PosesCount: Count of poses in this entity data (4 bytes).
00074     //      5. IsTracked: Whether or not this entity is being tracked (1 byte).
00075     //      6. Poses: Array of common structure TrackedPose (sizeof(TrackedPose) * PosesCount bytes).
00076     //      7. Customer specific data for this entity (DataSizeInBytes - sizeof(PoseTrackedEntityData) - sizeof(TrackedPose) * (PosesCount -1) bytes)
00077     //
00078     //   4. Provider-specific data for entity #0 in this frame.
00079     //
00080     //   5. PoseTrackingEntityData #1: Second entity data. Common structure for all providers.
00081     //
00082     //   6. Provider-specific data for entity #1 in this frame.
00083
00084     struct PoseTrackingFrameHeader
00085     {
00086         // This Guid allows the consumer of the buffer to verify that
00087         // it has been written by the expected provider
00088         GUID CustomDataTypeGuid;
00089         uint32_t EntitiesCount;
00090         uint32_t EntityOffsets[1]; // actual length is EntitiesCount
00091     };
00092
00093     struct PoseTrackingEntityData
00094     {
00095         uint32_t DataSizeInBytes;
00096         GUID EntityId;
00097         GUID PoseSet;
00098         uint32_t PosesCount;
00099         bool IsTracked;
00100         TrackedPose Poses[1]; // actual length is PosesCount
00101     };
00102
00103     // Subtype for PoseTracking
00104     // {69232056-2ED9-4D0E-89CC-5D2734A56808}
00105     DEFINE_GUID(MFPerceptionFormat_PoseTracking, 0x69232056, 0x2ed9, 0x4d0e, 0x89, 0xcc, 0x5d, 0x27, 0x34, 0xa5, 0x68, 0x8);
00106
00107     // These two constants (used in the PoseSet attribute of PoseTrackingEntityData) define which
00108     // body part each TrackedPose corresponds to.
00109     // i.e. for body tracking: indexes in Poses correspond to values of the BodyPart enumerated type.
00110     //      for hand tracking: enumerated type is not yet defined.
00111     // {84520B1F-AB61-46DA-AB1D-E01340EF884E}
00112     DEFINE_GUID(PoseSet_BodyTracking, 0x84520b1f, 0xab61, 0x46da, 0xab, 0x1d, 0xe0, 0x13, 0x40, 0xef, 0x88, 0x4e);
00113     // {F142C82C-3A57-4E7D-8159-98BDBD6CCFE2}
00114     DEFINE_GUID(PoseSet_HandTracking, 0xf142c82c, 0x3a57, 0x4e7d, 0x81, 0x59, 0x98, 0xbd, 0xbd, 0x6c, 0xcf, 0xe2);
00115
00116 }
Generated on Fri Nov 15 2024 22:18:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cppwinrt/Scenario6_TimeZone.cpp Source File

  • DateTimeFormatting
  • cppwinrt

Scenario6_TimeZone.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario6_TimeZone.h"
00014 #include "Scenario6_TimeZone.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Globalization;
00019 using namespace Windows::Globalization::DateTimeFormatting;
00020 using namespace Windows::UI::Xaml;
00021
00022 namespace
00023 {
00024     void GenerateResult(std::wostream& results, DateTimeFormatter const& formatter, PCWSTR timeZone, DateTime dateToFormat)
00025     {
00026         // Perform the actual formatting.
00027         results << L"In " << timeZone << L" time zone: " <<
00028             std::wstring_view(formatter.Format(dateToFormat, timeZone)) << std::endl;
00029     }
00030 }
00031
00032 namespace winrt::SDKTemplate::implementation
00033 {
00034     Scenario6_TimeZone::Scenario6_TimeZone()
00035     {
00036         InitializeComponent();
00037     }
00038
00039     void Scenario6_TimeZone::Display_Click(IInspectable const&, RoutedEventArgs const&)
00040     {
00041         // This scenario illustrates time zone support in DateTimeFormatter class
00042
00043         // Displayed time zones (other than local time zone)
00044         std::array timeZones{ L"UTC", L"America/New_York", L"Asia/Kolkata" };
00045
00046         // Keep the results here
00047         std::wostringstream results;
00048
00049         // Create formatter object using longdate and longtime template
00050         DateTimeFormatter dateFormatter(L"longdate longtime");
00051
00052         // Create date/time to format and display.
00053         Calendar calendar;
00054         DateTime dateToFormat = calendar.GetDateTime();
00055
00056         // Show current time.
00057         results << L"Current date and time" << std::endl <<
00058             L"In Local time zone: " << std::wstring_view(dateFormatter.Format(dateToFormat)) << std::endl;
00059         for (auto&& timeZone : timeZones)
00060         {
00061             GenerateResult(results, dateFormatter, timeZone, dateToFormat);
00062         }
00063         results << std::endl;
00064
00065         // Show a time on 14th day of second month of next year.
00066         // Note the effect of daylight saving on the results.
00067         calendar.AddYears(1); calendar.Month(2); calendar.Day(14);
00068         dateToFormat = calendar.GetDateTime();
00069         results << L"Same time on 14th day of second month of next year" << std::endl <<
00070             L"In Local time zone: " << std::wstring_view(dateFormatter.Format(dateToFormat)) << std::endl;
00071         for (auto timeZone : timeZones)
00072         {
00073             GenerateResult(results, dateFormatter, timeZone, dateToFormat);
00074         }
00075         results << std::endl;
00076
00077         // Show a time on 14th day of tenth month of next year.
00078         // Note the effect of daylight saving on the results.
00079         calendar.AddMonths(8);
00080         dateToFormat = calendar.GetDateTime();
00081         results << L"Same time on 14th day of tenth month of next year" << std::endl <<
00082             L"In Local time zone: " << std::wstring_view(dateFormatter.Format(dateToFormat)) << std::endl;
00083         for (auto timeZone : timeZones)
00084         {
00085             GenerateResult(results, dateFormatter, timeZone, dateToFormat);
00086         }
00087         results << std::endl;
00088
00089         // Display the results.
00090         OutputTextBlock().Text(results.str());
00091     }
00092 }
Generated on Fri Nov 15 2024 22:19:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario1WinRTComponent/SecureInterfaceLegacySignals.cpp Source File

  • AllJoyn
  • Common
  • Scenario1WinRTComponent

SecureInterfaceLegacySignals.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #include "pch.h"
00022
00023 using namespace Microsoft::WRL;
00024 using namespace Platform;
00025 using namespace Windows::Devices::AllJoyn;
00026 using namespace Windows::Foundation;
00027 using namespace com::microsoft::Samples::SecureInterface;
00028
00029 void SecureInterfaceLegacySignals::Initialize(_In_ alljoyn_busobject busObject, _In_ alljoyn_sessionid sessionId)
00030 {
00031     m_busObject = busObject;
00032     m_sessionId = sessionId;
00033
00034     auto interfaceDefinition = alljoyn_busattachment_getinterface(alljoyn_busobject_getbusattachment(busObject), "com.microsoft.Samples.SecureInterface");
00035     alljoyn_interfacedescription_getmember(interfaceDefinition, "TextSent", &m_memberTextSent);
00036 }
00037
00038 void SecureInterfaceLegacySignals::TextSent(_In_ Platform::String^ interfaceMemberMessage)
00039 {
00040     if (nullptr == m_busObject)
00041     {
00042         return;
00043     }
00044
00045     size_t argCount = 1;
00046     alljoyn_msgarg arguments = alljoyn_msgarg_array_create(argCount);
00047     (void)TypeConversionHelpers::SetAllJoynMessageArg(alljoyn_msgarg_array_element(arguments, 0), "s", interfaceMemberMessage);
00048
00049     alljoyn_busobject_signal(
00050         m_busObject,
00051         NULL,  // Generated code only supports broadcast signals.
00052         m_sessionId,
00053         m_memberTextSent,
00054         arguments,
00055         argCount,
00056         0, // A signal with a TTL of 0 will be sent to every member of the session, regardless of how long it takes to deliver the message
00057         ALLJOYN_MESSAGE_FLAG_GLOBAL_BROADCAST, // Broadcast to everyone in the session.
00058         NULL); // The generated code does not need the generated signal message
00059
00060     alljoyn_msgarg_destroy(arguments);
00061 }
00062
00063 void SecureInterfaceLegacySignals::CallTextSentReceived(_In_ SecureInterfaceLegacySignals^ sender, _In_ SecureInterfaceTextSentReceivedEventArgs^ args)
00064 {
00065     TextSentReceived(sender, args);
00066 }
00067
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/Content/TextRenderer.h Source File

  • HolographicTagAlong
  • cpp
  • Content

TextRenderer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "common\DeviceResources.h"
00015
00016 namespace HolographicTagAlongSample
00017 {
00018     class TextRenderer
00019     {
00020     public:
00021         TextRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources, unsigned int const& textureWidth, unsigned int const& textureHeight);
00022
00023         void RenderTextOffscreen(const std::wstring& str);
00024
00025         void CreateDeviceDependentResources();
00026         void ReleaseDeviceDependentResources();
00027
00028         ID3D11ShaderResourceView* GetTexture() const { return m_shaderResourceView.Get();   };
00029         ID3D11SamplerState*       GetSampler() const { return m_pointSampler.Get();         };
00030
00031     private:
00032         // Cached pointer to device resources.
00033         const std::shared_ptr<DX::DeviceResources> m_deviceResources;
00034
00035         // Direct3D resources for rendering text to an off-screen render target.
00036         Microsoft::WRL::ComPtr<ID3D11Texture2D>             m_texture;
00037         Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>    m_shaderResourceView;
00038         Microsoft::WRL::ComPtr<ID3D11SamplerState>          m_pointSampler;
00039         Microsoft::WRL::ComPtr<ID3D11RenderTargetView>      m_renderTargetView;
00040         Microsoft::WRL::ComPtr<ID2D1RenderTarget>           m_d2dRenderTarget;
00041         Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>        m_whiteBrush;
00042         Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormat;
00043
00044         // CPU-based variables for configuring the offscreen render target.
00045         const unsigned int m_textureWidth;
00046         const unsigned int m_textureHeight;
00047     };
00048 }
Generated on Fri Nov 15 2024 22:18:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceListEntry Member List

This is the complete list of members for DeviceListEntry, including all inherited members.
device | DeviceListEntry | [private]
DeviceInformation | DeviceListEntry |
DeviceListEntry(Windows.Devices.Enumeration.DeviceInformation deviceInformation, String deviceSelector) | DeviceListEntry | [inline]
deviceSelector | DeviceListEntry | [private]
DeviceSelector | DeviceListEntry |
InstanceId | DeviceListEntry |
Generated on Fri Nov 15 2024 22:24:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cpp/Scenario1_GetAndSetPin.xaml.h Source File

  • IoT-GPIO
  • cpp

Scenario1_GetAndSetPin.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_GetAndSetPin.xaml.h
00014 //
00015
00016 #pragma once
00017
00018 #include "Scenario1_GetAndSetPin.g.h"
00019
00020 namespace SDKTemplate
00021 {
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario1_GetAndSetPin sealed
00024     {
00025     public:
00026         Scenario1_GetAndSetPin();
00027         void StartStopScenario_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00028         void SetPinHigh_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029         void SetPinLow_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00030         void GetPinValue_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00031
00032     protected:
00033         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs ^e) override;
00034
00035     private:
00036         void StartScenario();
00037         void StopScenario();
00038
00039     private:
00040         const int LED_PIN = 5;
00041         Windows::Devices::Gpio::GpioPin ^pin;
00042     };
00043 }
Generated on Fri Nov 15 2024 22:20:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cs/PrintHelper.cs Source File

  • Printing
  • cs

PrintHelper.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Threading.Tasks;
00004 using SDKTemplate;
00005 using Windows.Graphics.Printing;
00006 using Windows.UI.Xaml;
00007 using Windows.UI.Xaml.Controls;
00008 using Windows.UI.Xaml.Printing;
00009
00010 namespace PrintSample
00011 {
00012     public class PrintHelper
00013     {
00014         /// <summary>
00015         /// The percent of app's margin width, content is set at 85% (0.85) of the area's width
00016         /// </summary>
00017         protected double ApplicationContentMarginLeft = 0.075;
00018
00019         /// <summary>
00020         /// The percent of app's margin height, content is set at 94% (0.94) of tha area's height
00021         /// </summary>
00022         protected double ApplicationContentMarginTop = 0.03;
00023
00024         /// <summary>
00025         /// PrintDocument is used to prepare the pages for printing.
00026         /// Prepare the pages to print in the handlers for the Paginate, GetPreviewPage, and AddPages events.
00027         /// </summary>
00028         protected PrintDocument printDocument;
00029
00030         /// <summary>
00031         /// Marker interface for document source
00032         /// </summary>
00033         protected IPrintDocumentSource printDocumentSource;
00034
00035         /// <summary>
00036         /// A list of UIElements used to store the print preview pages.  This gives easy access
00037         /// to any desired preview page.
00038         /// </summary>
00039         internal List<UIElement> printPreviewPages;
00040
00041         // Event callback which is called after print preview pages are generated.  Photos scenario uses this to do filtering of preview pages
00042         protected event EventHandler PreviewPagesCreated;
00043
00044         /// <summary>
00045         /// First page in the printing-content series
00046         /// From this "virtual sized" paged content is split(text is flowing) to "printing pages"
00047         /// </summary>
00048         protected FrameworkElement firstPage;
00049
00050         /// <summary>
00051         ///  A reference back to the scenario page used to access XAML elements on the scenario page
00052         /// </summary>
00053         protected Page scenarioPage;
00054
00055         /// <summary>
00056         ///  A hidden canvas used to hold pages we wish to print
00057         /// </summary>
00058         protected Canvas PrintCanvas
00059         {
00060             get
00061             {
00062                 return scenarioPage.FindName("PrintCanvas") as Canvas;
00063             }
00064         }
00065
00066         /// <summary>
00067         /// Constructor
00068         /// </summary>
00069         /// <param name="scenarioPage">The scenario page constructing us</param>
00070         public PrintHelper(Page scenarioPage)
00071         {
00072             this.scenarioPage = scenarioPage;
00073             printPreviewPages = new List<UIElement>();
00074         }
00075
00076         /// <summary>
00077         /// This function registers the app for printing with Windows and sets up the necessary event handlers for the print process.
00078         /// </summary>
00079         public virtual void RegisterForPrinting()
00080         {
00081             printDocument = new PrintDocument();
00082             printDocumentSource = printDocument.DocumentSource;
00083             printDocument.Paginate += CreatePrintPreviewPages;
00084             printDocument.GetPreviewPage += GetPrintPreviewPage;
00085             printDocument.AddPages += AddPrintPages;
00086
00087             PrintManager printMan = PrintManager.GetForCurrentView();
00088             printMan.PrintTaskRequested += PrintTaskRequested;
00089         }
00090
00091         /// <summary>
00092         /// This function unregisters the app for printing with Windows.
00093         /// </summary>
00094         public virtual void UnregisterForPrinting()
00095         {
00096             if (printDocument == null)
00097             {
00098                 return;
00099             }
00100
00101             printDocument.Paginate -= CreatePrintPreviewPages;
00102             printDocument.GetPreviewPage -= GetPrintPreviewPage;
00103             printDocument.AddPages -= AddPrintPages;
00104             printDocument = null;
00105
00106             // Remove the handler for printing initialization.
00107             PrintManager printMan = PrintManager.GetForCurrentView();
00108             printMan.PrintTaskRequested -= PrintTaskRequested;
00109
00110             PrintCanvas.Children.Clear();
00111         }
00112
00113         public async Task ShowPrintUIAsync()
00114         {
00115             // Catch and print out any errors reported
00116             try
00117             {
00118                 await PrintManager.ShowPrintUIAsync();
00119             }
00120             catch (Exception e)
00121             {
00122                 MainPage.Current.NotifyUser("Error printing: " + e.Message + ", hr=" + e.HResult, NotifyType.ErrorMessage);
00123             }
00124         }
00125
00126         /// <summary>
00127         /// Method that will generate print content for the scenario
00128         /// For scenarios 1-4: it will create the first page from which content will flow
00129         /// Scenario 5 uses a different approach
00130         /// </summary>
00131         /// <param name="page">The page to print</param>
00132         public virtual void PreparePrintContent(Page page)
00133         {
00134             if (firstPage == null)
00135             {
00136                 firstPage = page;
00137                 StackPanel header = (StackPanel)firstPage.FindName("Header");
00138                 header.Visibility = Windows.UI.Xaml.Visibility.Visible;
00139             }
00140
00141             // Add the (newly created) page to the print canvas which is part of the visual tree and force it to go
00142             // through layout so that the linked containers correctly distribute the content inside them.
00143             PrintCanvas.Children.Add(firstPage);
00144             PrintCanvas.InvalidateMeasure();
00145             PrintCanvas.UpdateLayout();
00146         }
00147
00148         /// <summary>
00149         /// This is the event handler for PrintManager.PrintTaskRequested.
00150         /// </summary>
00151         /// <param name="sender">PrintManager</param>
00152         /// <param name="e">PrintTaskRequestedEventArgs </param>
00153         protected virtual void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e)
00154         {
00155             PrintTask printTask = null;
00156             printTask = e.Request.CreatePrintTask("C# Printing SDK Sample", sourceRequested =>
00157             {
00158                 // Print Task event handler is invoked when the print job is completed.
00159                 printTask.Completed += async (s, args) =>
00160                 {
00161                     // Notify the user when the print operation fails.
00162                     if (args.Completion == PrintTaskCompletion.Failed)
00163                     {
00164                         await scenarioPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00165                         {
00166                             MainPage.Current.NotifyUser("Failed to print.", NotifyType.ErrorMessage);
00167                         });
00168                     }
00169                 };
00170
00171                 sourceRequested.SetSource(printDocumentSource);
00172             });
00173         }
00174
00175         /// <summary>
00176         /// This is the event handler for PrintDocument.Paginate. It creates print preview pages for the app.
00177         /// </summary>
00178         /// <param name="sender">PrintDocument</param>
00179         /// <param name="e">Paginate Event Arguments</param>
00180         protected virtual void CreatePrintPreviewPages(object sender, PaginateEventArgs e)
00181         {
00182             lock (printPreviewPages)
00183             {
00184                 // Clear the cache of preview pages
00185                 printPreviewPages.Clear();
00186
00187                 // Clear the print canvas of preview pages
00188                 PrintCanvas.Children.Clear();
00189
00190                 // This variable keeps track of the last RichTextBlockOverflow element that was added to a page which will be printed
00191                 RichTextBlockOverflow lastRTBOOnPage;
00192
00193                 // Get the PrintTaskOptions
00194                 PrintTaskOptions printingOptions = ((PrintTaskOptions)e.PrintTaskOptions);
00195
00196                 // Get the page description to deterimine how big the page is
00197                 PrintPageDescription pageDescription = printingOptions.GetPageDescription(0);
00198
00199                 // We know there is at least one page to be printed. passing null as the first parameter to
00200                 // AddOnePrintPreviewPage tells the function to add the first page.
00201                 lastRTBOOnPage = AddOnePrintPreviewPage(null, pageDescription);
00202
00203                 // We know there are more pages to be added as long as the last RichTextBoxOverflow added to a print preview
00204                 // page has extra content
00205                 while (lastRTBOOnPage.HasOverflowContent && lastRTBOOnPage.Visibility == Windows.UI.Xaml.Visibility.Visible)
00206                 {
00207                     lastRTBOOnPage = AddOnePrintPreviewPage(lastRTBOOnPage, pageDescription);
00208                 }
00209
00210                 if (PreviewPagesCreated != null)
00211                 {
00212                     PreviewPagesCreated.Invoke(printPreviewPages, null);
00213                 }
00214
00215                 PrintDocument printDoc = (PrintDocument)sender;
00216
00217                 // Report the number of preview pages created
00218                 printDoc.SetPreviewPageCount(printPreviewPages.Count, PreviewPageCountType.Intermediate);
00219             }
00220         }
00221
00222         /// <summary>
00223         /// This is the event handler for PrintDocument.GetPrintPreviewPage. It provides a specific print preview page,
00224         /// in the form of an UIElement, to an instance of PrintDocument. PrintDocument subsequently converts the UIElement
00225         /// into a page that the Windows print system can deal with.
00226         /// </summary>
00227         /// <param name="sender">PrintDocument</param>
00228         /// <param name="e">Arguments containing the preview requested page</param>
00229         protected virtual void GetPrintPreviewPage(object sender, GetPreviewPageEventArgs e)
00230         {
00231             PrintDocument printDoc = (PrintDocument)sender;
00232             printDoc.SetPreviewPage(e.PageNumber, printPreviewPages[e.PageNumber - 1]);
00233         }
00234
00235         /// <summary>
00236         /// This is the event handler for PrintDocument.AddPages. It provides all pages to be printed, in the form of
00237         /// UIElements, to an instance of PrintDocument. PrintDocument subsequently converts the UIElements
00238         /// into a pages that the Windows print system can deal with.
00239         /// </summary>
00240         /// <param name="sender">PrintDocument</param>
00241         /// <param name="e">Add page event arguments containing a print task options reference</param>
00242         protected virtual void AddPrintPages(object sender, AddPagesEventArgs e)
00243         {
00244             // Loop over all of the preview pages and add each one to  add each page to be printied
00245             for (int i = 0; i < printPreviewPages.Count; i++)
00246             {
00247                 // We should have all pages ready at this point...
00248                 printDocument.AddPage(printPreviewPages[i]);
00249             }
00250
00251             PrintDocument printDoc = (PrintDocument)sender;
00252
00253             // Indicate that all of the print pages have been provided
00254             printDoc.AddPagesComplete();
00255         }
00256
00257         /// <summary>
00258         /// This function creates and adds one print preview page to the internal cache of print preview
00259         /// pages stored in printPreviewPages.
00260         /// </summary>
00261         /// <param name="lastRTBOAdded">Last RichTextBlockOverflow element added in the current content</param>
00262         /// <param name="printPageDescription">Printer's page description</param>
00263         protected virtual RichTextBlockOverflow AddOnePrintPreviewPage(RichTextBlockOverflow lastRTBOAdded, PrintPageDescription printPageDescription)
00264         {
00265             // XAML element that is used to represent to "printing page"
00266             FrameworkElement page;
00267
00268             // The link container for text overflowing in this page
00269             RichTextBlockOverflow textLink;
00270
00271             // Check if this is the first page ( no previous RichTextBlockOverflow)
00272             if (lastRTBOAdded == null)
00273             {
00274                 // If this is the first page add the specific scenario content
00275                 page = firstPage;
00276
00277                 // Hide footer since we don't know yet if it will be displayed (this might not be the last page) - wait for layout
00278                 StackPanel footer = (StackPanel)page.FindName("Footer");
00279                 footer.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00280             }
00281             else
00282             {
00283                 // Flow content (text) from previous pages
00284                 page = new ContinuationPage(lastRTBOAdded);
00285             }
00286
00287             // Set "paper" width
00288             page.Width = printPageDescription.PageSize.Width;
00289             page.Height = printPageDescription.PageSize.Height;
00290
00291             Grid printableArea = (Grid)page.FindName("PrintableArea");
00292
00293             // Get the margins size
00294             // If the ImageableRect is smaller than the app provided margins use the ImageableRect
00295             double marginWidth = Math.Max(printPageDescription.PageSize.Width - printPageDescription.ImageableRect.Width, printPageDescription.PageSize.Width * ApplicationContentMarginLeft * 2);
00296             double marginHeight = Math.Max(printPageDescription.PageSize.Height - printPageDescription.ImageableRect.Height, printPageDescription.PageSize.Height * ApplicationContentMarginTop * 2);
00297
00298             // Set-up "printable area" on the "paper"
00299             printableArea.Width = firstPage.Width - marginWidth;
00300             printableArea.Height = firstPage.Height - marginHeight;
00301
00302             // Add the (newley created) page to the print canvas which is part of the visual tree and force it to go
00303             // through layout so that the linked containers correctly distribute the content inside them.
00304             PrintCanvas.Children.Add(page);
00305             PrintCanvas.InvalidateMeasure();
00306             PrintCanvas.UpdateLayout();
00307
00308             // Find the last text container and see if the content is overflowing
00309             textLink = (RichTextBlockOverflow)page.FindName("ContinuationPageLinkedContainer");
00310
00311             // Check if this is the last page
00312             if (!textLink.HasOverflowContent && textLink.Visibility == Windows.UI.Xaml.Visibility.Visible)
00313             {
00314                 StackPanel footer = (StackPanel)page.FindName("Footer");
00315                 footer.Visibility = Windows.UI.Xaml.Visibility.Visible;
00316                 PrintCanvas.UpdateLayout();
00317             }
00318
00319             // Add the page to the page preview collection
00320             printPreviewPages.Add(page);
00321
00322             return textLink;
00323         }
00324     }
00325 }
Generated on Fri Nov 15 2024 22:21:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AtrInfo Member List

This is the complete list of members for AtrInfo, including all inherited members.
AtrInfo() | AtrInfo | [inline]
HistoricalBytes | AtrInfo |
MAXIMUM_ATR_CODES | AtrInfo |
ProtocolInterfaceA | AtrInfo |
ProtocolInterfaceB | AtrInfo |
ProtocolInterfaceC | AtrInfo |
ProtocolInterfaceD | AtrInfo |
TckValid | AtrInfo |
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cppwinrt/Scenario2_DecimalFormatting.h Source File

  • NumberFormatting
  • cppwinrt

Scenario2_DecimalFormatting.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_DecimalFormatting.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_DecimalFormatting : Scenario2_DecimalFormattingT<Scenario2_DecimalFormatting>
00019     {
00020         Scenario2_DecimalFormatting();
00021
00022         void Display_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario2_DecimalFormatting : Scenario2_DecimalFormattingT<Scenario2_DecimalFormatting, implementation::Scenario2_DecimalFormatting>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:20:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks/App.xaml.cpp Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks

App.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "View\TripListView.xaml.h"
00014 #include "View\TripDetails.xaml.h"
00015 #include "ViewModel\TripVoiceCommand.h"
00016
00017 using namespace AdventureWorks;
00018
00019 using namespace Concurrency;
00020 using namespace Platform;
00021 using namespace Windows::ApplicationModel;
00022 using namespace Windows::ApplicationModel::Activation;
00023 using namespace Windows::ApplicationModel::VoiceCommands;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Windows::Media::SpeechRecognition;
00027 using namespace Windows::Storage;
00028 using namespace Windows::UI::Core;
00029 using namespace Windows::UI::Xaml;
00030 using namespace Windows::UI::Xaml::Controls;
00031 using namespace Windows::UI::Xaml::Controls::Primitives;
00032 using namespace Windows::UI::Xaml::Data;
00033 using namespace Windows::UI::Xaml::Input;
00034 using namespace Windows::UI::Xaml::Interop;
00035 using namespace Windows::UI::Xaml::Media;
00036 using namespace Windows::UI::Xaml::Navigation;
00037
00038 // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
00039
00040 /// <summary>
00041 /// Initializes the singleton application object.  This is the first line of authored code
00042 /// executed, and as such is the logical equivalent of main() or WinMain().
00043 /// </summary>
00044 App::App()
00045 {
00046     InitializeComponent();
00047 }
00048
00049 /// <summary>
00050 /// Invoked when the application is launched normally by the end user.  Other entry points
00051 /// will be used such as when the application is launched by Cortana
00052 /// </summary>
00053 /// <param name="e">Details about the launch request and process.</param>
00054 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
00055 {
00056     auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00057
00058     // Do not repeat app initialization when the Window already has content,
00059     // just ensure that the window is active
00060     if (rootFrame == nullptr)
00061     {
00062         // Create a Frame to act as the navigation context and associate it with
00063         // a SuspensionManager key
00064         rootFrame = ref new Frame();
00065
00066         // Set the default language
00067         rootFrame->Language = Windows::Globalization::ApplicationLanguages::Languages->GetAt(0);
00068
00069         rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed);
00070
00071         // Register for Back button events.
00072         SystemNavigationManager::GetForCurrentView()->BackRequested += ref new Windows::Foundation::EventHandler<BackRequestedEventArgs^>(this, &App::OnBackRequested);
00073
00074         // Register for navigation events so we can update the Back button.
00075         rootFrame->Navigated += ref new NavigatedEventHandler(this, &App::OnNavigated);
00076
00077         if (rootFrame->Content == nullptr)
00078         {
00079             // When the navigation stack isn't restored navigate to the first page,
00080             // configuring the new page by passing required information as a navigation
00081             // parameter
00082             rootFrame->Navigate(TypeName(TripListView::typeid), e->Arguments);
00083         }
00084         // Place the frame in the current Window
00085         Window::Current->Content = rootFrame;
00086         // Ensure the current window is active
00087         Window::Current->Activate();
00088     }
00089     else
00090     {
00091         if (rootFrame->Content == nullptr)
00092         {
00093             // When the navigation stack isn't restored navigate to the first page,
00094             // configuring the new page by passing required information as a navigation
00095             // parameter
00096             rootFrame->Navigate(TypeName(TripListView::typeid), e->Arguments);
00097         }
00098         // Ensure the current window is active
00099         Window::Current->Activate();
00100     }
00101
00102     // Install VCD file, and update phrase list.
00103     create_task(Package::Current->InstalledLocation->GetFileAsync(L"AdventureWorksCommands.xml"))
00104         .then([this](StorageFile^ vcdStorageFile)
00105     {
00106         return VoiceCommandDefinitionManager::InstallCommandDefinitionsFromStorageFileAsync(vcdStorageFile);
00107
00108     }).then([this](task<void> t)
00109     {
00110         try
00111         {
00112             t.get();
00113
00114             ViewModelLocator^ locator = dynamic_cast<ViewModelLocator^>(App::Current->Resources->Lookup("ViewModelLocator"));
00115             if (locator != nullptr)
00116             {
00117                 locator->TripViewModel->UpdateDestinationPhraseList();
00118             }
00119         }
00120         catch (Platform::Exception^ ex)
00121         {
00122             OutputDebugStringW(L"Failed to install VCD or update phrase list:");
00123             OutputDebugStringW(ex->ToString()->Data());
00124         }
00125
00126     });
00127 }
00128
00129 /// <summary> Extract the semantic interpretation from the voice command. </summary>
00130 /// <param name="tag">The tag to look up</param>
00131 /// <param name="result">The speech reco result provided when the app is activated </summary>
00132 String^ App::SemanticInterpretation(String^ tag, SpeechRecognitionResult^ result)
00133 {
00134     auto semanticPropertySet = result->SemanticInterpretation->Properties->Lookup(tag);
00135     if (semanticPropertySet->Size > 0)
00136     {
00137         return semanticPropertySet->GetAt(0);
00138     }
00139     return nullptr;
00140 }
00141
00142 /// <summary> Handle activation launches. This may occur due to Cortana triggering a VoiceCommand
00143 /// activation, or a protocol activation, depending on the scenario. Foreground activations will use
00144 /// VoiceCommand activation. Background task activations will use protocol activation.
00145 /// <param name="e">The activation details (voice command or protocol activation details)</param>
00146 void App::OnActivated(IActivatedEventArgs^ e)
00147 {
00148     TypeName navigationToPageType;
00149     TripVoiceCommand^ navigationCommand;
00150
00151     // Handle foreground activation (the "Show trip to <destination>" Cortana command. Background activation
00152     // will be handled by the VoiceCommandService runtime component, and may result in protocol activation.
00153     if (e->Kind == ActivationKind::VoiceCommand)
00154     {
00155         VoiceCommandActivatedEventArgs^ commandArgs = dynamic_cast<VoiceCommandActivatedEventArgs^>(e);
00156         if (commandArgs != nullptr)
00157         {
00158             SpeechRecognitionResult^ speechRecoResult = commandArgs->Result;
00159
00160             String^ voiceCommandName = speechRecoResult->RulePath->GetAt(0);
00161             String^ textSpoken = speechRecoResult->Text;
00162
00163             String^ commandMode = this->SemanticInterpretation("commandMode", speechRecoResult);
00164             if (voiceCommandName->Equals(L"showTripToDestination"))
00165             {
00166                 String^ destination = this->SemanticInterpretation("destination", speechRecoResult);
00167
00168                 navigationCommand = ref new TripVoiceCommand(
00169                     voiceCommandName,
00170                     commandMode,
00171                     textSpoken,
00172                     destination);
00173
00174                 navigationToPageType = TypeName(TripDetails::typeid);
00175             }
00176             else
00177             {
00178                 navigationToPageType = TypeName(TripListView::typeid);
00179             }
00180         }
00181     }
00182     else if (e->Kind == ActivationKind::Protocol)
00183     {
00184         // Any links back to your app within Cortana will launch it via Protocol Activation.
00185         ProtocolActivatedEventArgs^ commandArgs = dynamic_cast<ProtocolActivatedEventArgs^>(e);
00186         if (commandArgs != nullptr)
00187         {
00188             WwwFormUrlDecoder^ decoder = ref new WwwFormUrlDecoder(commandArgs->Uri->Query);
00189             String^ destination = nullptr;
00190             try
00191             {
00192                 destination = decoder->GetFirstValueByName("LaunchContext");
00193
00194                 navigationCommand = ref new TripVoiceCommand(
00195                     "protocolLaunch",
00196                     "text",
00197                     "destination",
00198                     destination);
00199
00200                 navigationToPageType = TypeName(TripDetails::typeid);
00201             }
00202             catch (InvalidArgumentException^)
00203             {
00204                 // Invalid Argument is thrown if we're not launched with the LaunchContext set,
00205                 // so go to the main list of trips instead.
00206                 navigationToPageType = TypeName(TripListView::typeid);
00207             }
00208         }
00209     }
00210
00211     auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00212
00213     if (rootFrame == nullptr)
00214     {
00215         // Create a Frame to act as the navigation context and associate it with
00216         // a SuspensionManager key
00217         rootFrame = ref new Frame();
00218
00219         // Set the default language
00220         rootFrame->Language = Windows::Globalization::ApplicationLanguages::Languages->GetAt(0);
00221
00222         rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed);
00223     }
00224
00225     // When the navigation stack isn't restored navigate to the first page,
00226     // configuring the new page by passing required information as a navigation
00227     // parameter
00228     rootFrame->Navigate(navigationToPageType, navigationCommand);
00229
00230     // Place the frame in the current Window
00231     Window::Current->Content = rootFrame;
00232     // Ensure the current window is active
00233     Window::Current->Activate();
00234 }
00235
00236 /// <summary>
00237 /// Invoked when Navigation to a certain page fails
00238 /// </summary>
00239 /// <param name="sender">The Frame which failed navigation</param>
00240 /// <param name="e">Details about the navigation failure</param>
00241 void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e)
00242 {
00243     throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name);
00244 }
00245
00246 void App::OnNavigated(Object^ sender, NavigationEventArgs^ args)
00247 {
00248     bool canGoBack = false;
00249     auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00250     if (rootFrame != nullptr)
00251     {
00252         // If we returned to the root page, then empty the backstack.
00253         if (rootFrame->BackStack->Size > 0 &&
00254             args->SourcePageType.Name == rootFrame->BackStack->GetAt(0)->SourcePageType.Name)
00255         {
00256             rootFrame->BackStack->Clear();
00257         }
00258
00259         canGoBack = rootFrame->CanGoBack;
00260     }
00261
00262     // Set the Back button state appropriately.
00263     SystemNavigationManager::GetForCurrentView()->AppViewBackButtonVisibility =
00264         canGoBack ? AppViewBackButtonVisibility::Visible : AppViewBackButtonVisibility::Collapsed;
00265 }
00266
00267 void App::OnBackRequested(Object^ sender, BackRequestedEventArgs^ e)
00268 {
00269     if (!e->Handled)
00270     {
00271         auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00272         if (rootFrame != nullptr && rootFrame->CanGoBack)
00273         {
00274             e->Handled = true;
00275             rootFrame->GoBack();
00276         }
00277     }
00278 }
Generated on Fri Nov 15 2024 22:16:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraFaceDetection/cs/MainPage.xaml.cs Source File

  • CameraFaceDetection
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Diagnostics;
00014 using System.Linq;
00015 using System.Threading.Tasks;
00016 using Windows.ApplicationModel;
00017 using Windows.Devices.Enumeration;
00018 using Windows.Devices.Sensors;
00019 using Windows.Foundation;
00020 using Windows.Foundation.Metadata;
00021 using Windows.Graphics.Display;
00022 using Windows.Graphics.Imaging;
00023 using Windows.Media;
00024 using Windows.Media.Core;
00025 using Windows.Media.Capture;
00026 using Windows.Media.MediaProperties;
00027 using Windows.Phone.UI.Input;
00028 using Windows.Storage;
00029 using Windows.Storage.FileProperties;
00030 using Windows.Storage.Streams;
00031 using Windows.System.Display;
00032 using Windows.UI.Core;
00033 using Windows.UI.Xaml;
00034 using Windows.UI.Xaml.Controls;
00035 using Windows.UI.Xaml.Input;
00036 using Windows.UI.Xaml.Media;
00037 using Windows.UI.Xaml.Navigation;
00038 using Windows.UI.Xaml.Shapes;
00039 using Windows.Media.FaceAnalysis;
00040 using Windows.UI;
00041 using System.Collections.Generic;
00042
00043 namespace FaceDetection
00044 {
00045
00046     public sealed partial class MainPage : Page
00047     {
00048         // Receive notifications about rotation of the device and UI and apply any necessary rotation to the preview stream and UI controls
00049         private readonly DisplayInformation _displayInformation = DisplayInformation.GetForCurrentView();
00050         private readonly SimpleOrientationSensor _orientationSensor = SimpleOrientationSensor.GetDefault();
00051         private SimpleOrientation _deviceOrientation = SimpleOrientation.NotRotated;
00052         private DisplayOrientations _displayOrientation = DisplayOrientations.Portrait;
00053
00054         // Rotation metadata to apply to the preview stream and recorded videos (MF_MT_VIDEO_ROTATION)
00055         // Reference: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868174.aspx
00056         private static readonly Guid RotationKey = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1");
00057
00058         // Folder in which the captures will be stored (initialized in SetupUiAsync)
00059         private StorageFolder _captureFolder = null;
00060
00061         // Prevent the screen from sleeping while the camera is running
00062         private readonly DisplayRequest _displayRequest = new DisplayRequest();
00063
00064         // For listening to media property changes
00065         private readonly SystemMediaTransportControls _systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
00066
00067         // MediaCapture and its state variables
00068         private MediaCapture _mediaCapture;
00069         private IMediaEncodingProperties _previewProperties;
00070         private bool _isInitialized;
00071         private bool _isRecording;
00072
00073         // Information about the camera device
00074         private bool _mirroringPreview;
00075         private bool _externalCamera;
00076
00077         private FaceDetectionEffect _faceDetectionEffect;
00078
00079         #region Constructor, lifecycle and navigation
00080
00081         public MainPage()
00082         {
00083             this.InitializeComponent();
00084
00085             // Do not cache the state of the UI when suspending/navigating
00086             NavigationCacheMode = NavigationCacheMode.Disabled;
00087
00088             // Useful to know when to initialize/clean up the camera
00089             Application.Current.Suspending += Application_Suspending;
00090             Application.Current.Resuming += Application_Resuming;
00091         }
00092
00093         private async void Application_Suspending(object sender, SuspendingEventArgs e)
00094         {
00095             // Handle global application events only if this page is active
00096             if (Frame.CurrentSourcePageType == typeof(MainPage))
00097             {
00098                 var deferral = e.SuspendingOperation.GetDeferral();
00099
00100                 await CleanupCameraAsync();
00101
00102                 await CleanupUiAsync();
00103
00104                 deferral.Complete();
00105             }
00106         }
00107
00108         private async void Application_Resuming(object sender, object o)
00109         {
00110             // Handle global application events only if this page is active
00111             if (Frame.CurrentSourcePageType == typeof(MainPage))
00112             {
00113                 await SetupUiAsync();
00114
00115                 await InitializeCameraAsync();
00116             }
00117         }
00118
00119         protected override async void OnNavigatedTo(NavigationEventArgs e)
00120         {
00121             await SetupUiAsync();
00122
00123             await InitializeCameraAsync();
00124         }
00125
00126         protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
00127         {
00128             // Handling of this event is included for completenes, as it will only fire when navigating between pages and this sample only includes one page
00129
00130             await CleanupCameraAsync();
00131
00132             await CleanupUiAsync();
00133         }
00134
00135         #endregion Constructor, lifecycle and navigation
00136
00137
00138         #region Event handlers
00139
00140         /// <summary>
00141         /// In the event of the app being minimized this method handles media property change events. If the app receives a mute
00142         /// notification, it is no longer in the foregroud.
00143         /// </summary>
00144         /// <param name="sender"></param>
00145         /// <param name="args"></param>
00146         private async void SystemMediaControls_PropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs args)
00147         {
00148             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
00149             {
00150                 // Only handle this event if this page is currently being displayed
00151                 if (args.Property == SystemMediaTransportControlsProperty.SoundLevel && Frame.CurrentSourcePageType == typeof(MainPage))
00152                 {
00153                     // Check to see if the app is being muted. If so, it is being minimized.
00154                     // Otherwise if it is not initialized, it is being brought into focus.
00155                     if (sender.SoundLevel == SoundLevel.Muted)
00156                     {
00157                         await CleanupCameraAsync();
00158                     }
00159                     else if (!_isInitialized)
00160                     {
00161                         await InitializeCameraAsync();
00162                     }
00163                 }
00164             });
00165         }
00166
00167         /// <summary>
00168         /// Occurs each time the simple orientation sensor reports a new sensor reading.
00169         /// </summary>
00170         /// <param name="sender">The event source.</param>
00171         /// <param name="args">The event data.</param>
00172         private async void OrientationSensor_OrientationChanged(SimpleOrientationSensor sender, SimpleOrientationSensorOrientationChangedEventArgs args)
00173         {
00174             if (args.Orientation != SimpleOrientation.Faceup && args.Orientation != SimpleOrientation.Facedown)
00175             {
00176                 // Only update the current orientation if the device is not parallel to the ground. This allows users to take pictures of documents (FaceUp)
00177                 // or the ceiling (FaceDown) in portrait or landscape, by first holding the device in the desired orientation, and then pointing the camera
00178                 // either up or down, at the desired subject.
00179                 //Note: This assumes that the camera is either facing the same way as the screen, or the opposite way. For devices with cameras mounted
00180                 //      on other panels, this logic should be adjusted.
00181                 _deviceOrientation = args.Orientation;
00182
00183                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateButtonOrientation());
00184             }
00185         }
00186
00187         /// <summary>
00188         /// This event will fire when the page is rotated, when the DisplayInformation.AutoRotationPreferences value set in the SetupUiAsync() method cannot be not honored.
00189         /// </summary>
00190         /// <param name="sender">The event source.</param>
00191         /// <param name="args">The event data.</param>
00192         private async void DisplayInformation_OrientationChanged(DisplayInformation sender, object args)
00193         {
00194             _displayOrientation = sender.CurrentOrientation;
00195
00196             if (_previewProperties != null)
00197             {
00198                 await SetPreviewRotationAsync();
00199             }
00200
00201             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateButtonOrientation());
00202         }
00203
00204         private async void PhotoButton_Click(object sender, RoutedEventArgs e)
00205         {
00206             await TakePhotoAsync();
00207         }
00208
00209         private async void VideoButton_Click(object sender, RoutedEventArgs e)
00210         {
00211             if (!_isRecording)
00212             {
00213                 await StartRecordingAsync();
00214             }
00215             else
00216             {
00217                 await StopRecordingAsync();
00218             }
00219
00220             // After starting or stopping video recording, update the UI to reflect the MediaCapture state
00221             UpdateCaptureControls();
00222         }
00223
00224         private async void FaceDetectionButton_Click(object sender, RoutedEventArgs e)
00225         {
00226             if (_faceDetectionEffect == null || !_faceDetectionEffect.Enabled)
00227             {
00228                 // Clear any rectangles that may have been left over from a previous instance of the effect
00229                 FacesCanvas.Children.Clear();
00230
00231                 await CreateFaceDetectionEffectAsync();
00232             }
00233             else
00234             {
00235                 await CleanUpFaceDetectionEffectAsync();
00236             }
00237
00238             UpdateCaptureControls();
00239         }
00240
00241         private async void HardwareButtons_CameraPressed(object sender, CameraEventArgs e)
00242         {
00243             await TakePhotoAsync();
00244         }
00245
00246         private async void MediaCapture_RecordLimitationExceeded(MediaCapture sender)
00247         {
00248             // This is a notification that recording has to stop, and the app is expected to finalize the recording
00249
00250             await StopRecordingAsync();
00251
00252             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateCaptureControls());
00253         }
00254
00255         private async void MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs)
00256         {
00257             Debug.WriteLine("MediaCapture_Failed: (0x{0:X}) {1}", errorEventArgs.Code, errorEventArgs.Message);
00258
00259             await CleanupCameraAsync();
00260
00261             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UpdateCaptureControls());
00262         }
00263
00264         private async void FaceDetectionEffect_FaceDetected(FaceDetectionEffect sender, FaceDetectedEventArgs args)
00265         {
00266             // Ask the UI thread to render the face bounding boxes
00267             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => HighlightDetectedFaces(args.ResultFrame.DetectedFaces));
00268         }
00269
00270         #endregion Event handlers
00271
00272
00273         #region MediaCapture methods
00274
00275         /// <summary>
00276         /// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI
00277         /// </summary>
00278         /// <returns></returns>
00279         private async Task InitializeCameraAsync()
00280         {
00281             Debug.WriteLine("InitializeCameraAsync");
00282
00283             if (_mediaCapture == null)
00284             {
00285                 // Attempt to get the front camera if one is available, but use any camera device if not
00286                 var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Front);
00287
00288                 if (cameraDevice == null)
00289                 {
00290                     Debug.WriteLine("No camera device found!");
00291                     return;
00292                 }
00293
00294                 // Create MediaCapture and its settings
00295                 _mediaCapture = new MediaCapture();
00296
00297                 // Register for a notification when video recording has reached the maximum time and when something goes wrong
00298                 _mediaCapture.RecordLimitationExceeded += MediaCapture_RecordLimitationExceeded;
00299                 _mediaCapture.Failed += MediaCapture_Failed;
00300
00301                 var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
00302
00303                 // Initialize MediaCapture
00304                 try
00305                 {
00306                     await _mediaCapture.InitializeAsync(settings);
00307                     _isInitialized = true;
00308                 }
00309                 catch (UnauthorizedAccessException)
00310                 {
00311                     Debug.WriteLine("The app was denied access to the camera");
00312                 }
00313
00314                 // If initialization succeeded, start the preview
00315                 if (_isInitialized)
00316                 {
00317                     // Figure out where the camera is located
00318                     if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
00319                     {
00320                         // No information on the location of the camera, assume it's an external camera, not integrated on the device
00321                         _externalCamera = true;
00322                     }
00323                     else
00324                     {
00325                         // Camera is fixed on the device
00326                         _externalCamera = false;
00327
00328                         // Only mirror the preview if the camera is on the front panel
00329                         _mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
00330                     }
00331
00332                     await StartPreviewAsync();
00333
00334                     UpdateCaptureControls();
00335                 }
00336             }
00337         }
00338
00339         /// <summary>
00340         /// Starts the preview and adjusts it for for rotation and mirroring after making a request to keep the screen on
00341         /// </summary>
00342         /// <returns></returns>
00343         private async Task StartPreviewAsync()
00344         {
00345             // Prevent the device from sleeping while the preview is running
00346             _displayRequest.RequestActive();
00347
00348             // Set the preview source in the UI and mirror it if necessary
00349             PreviewControl.Source = _mediaCapture;
00350             PreviewControl.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
00351
00352             // Start the preview
00353             await _mediaCapture.StartPreviewAsync();
00354             _previewProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
00355
00356             // Initialize the preview to the current orientation
00357             if (_previewProperties != null)
00358             {
00359                 _displayOrientation = _displayInformation.CurrentOrientation;
00360
00361                 await SetPreviewRotationAsync();
00362             }
00363         }
00364
00365         /// <summary>
00366         /// Gets the current orientation of the UI in relation to the device (when AutoRotationPreferences cannot be honored) and applies a corrective rotation to the preview
00367         /// </summary>
00368         private async Task SetPreviewRotationAsync()
00369         {
00370             // Only need to update the orientation if the camera is mounted on the device
00371             if (_externalCamera) return;
00372
00373             // Calculate which way and how far to rotate the preview
00374             int rotationDegrees = ConvertDisplayOrientationToDegrees(_displayOrientation);
00375
00376             // The rotation direction needs to be inverted if the preview is being mirrored
00377             if (_mirroringPreview)
00378             {
00379                 rotationDegrees = (360 - rotationDegrees) % 360;
00380             }
00381
00382             // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames
00383             var props = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
00384             props.Properties.Add(RotationKey, rotationDegrees);
00385             await _mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, null);
00386         }
00387
00388         /// <summary>
00389         /// Stops the preview and deactivates a display request, to allow the screen to go into power saving modes
00390         /// </summary>
00391         /// <returns></returns>
00392         private async Task StopPreviewAsync()
00393         {
00394             // Stop the preview
00395             _previewProperties = null;
00396             await _mediaCapture.StopPreviewAsync();
00397
00398             // Use the dispatcher because this method is sometimes called from non-UI threads
00399             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00400             {
00401                 // Cleanup the UI
00402                 PreviewControl.Source = null;
00403
00404                 // Allow the device screen to sleep now that the preview is stopped
00405                 _displayRequest.RequestRelease();
00406             });
00407         }
00408
00409         /// <summary>
00410         /// Adds face detection to the preview stream, registers for its events, enables it, and gets the FaceDetectionEffect instance
00411         /// </summary>
00412         /// <returns></returns>
00413         private async Task CreateFaceDetectionEffectAsync()
00414         {
00415             // Create the definition, which will contain some initialization settings
00416             var definition = new FaceDetectionEffectDefinition();
00417
00418             // To ensure preview smoothness, do not delay incoming samples
00419             definition.SynchronousDetectionEnabled = false;
00420
00421             // In this scenario, choose detection speed over accuracy
00422             definition.DetectionMode = FaceDetectionMode.HighPerformance;
00423
00424             // Add the effect to the preview stream
00425             _faceDetectionEffect = (FaceDetectionEffect)await _mediaCapture.AddVideoEffectAsync(definition, MediaStreamType.VideoPreview);
00426
00427             // Register for face detection events
00428             _faceDetectionEffect.FaceDetected += FaceDetectionEffect_FaceDetected;
00429
00430             // Choose the shortest interval between detection events
00431             _faceDetectionEffect.DesiredDetectionInterval = TimeSpan.FromMilliseconds(33);
00432
00433             // Start detecting faces
00434             _faceDetectionEffect.Enabled = true;
00435         }
00436
00437         /// <summary>
00438         ///  Disables and removes the face detection effect, and unregisters the event handler for face detection
00439         /// </summary>
00440         /// <returns></returns>
00441         private async Task CleanUpFaceDetectionEffectAsync()
00442         {
00443             // Disable detection
00444             _faceDetectionEffect.Enabled = false;
00445
00446             // Unregister the event handler
00447             _faceDetectionEffect.FaceDetected -= FaceDetectionEffect_FaceDetected;
00448
00449             // Remove the effect (see ClearEffectsAsync method to remove all effects from a stream)
00450             await _mediaCapture.RemoveEffectAsync(_faceDetectionEffect);
00451
00452             // Clear the member variable that held the effect instance
00453             _faceDetectionEffect = null;
00454         }
00455
00456         /// <summary>
00457         /// Takes a photo to a StorageFile and adds rotation metadata to it
00458         /// </summary>
00459         /// <returns></returns>
00460         private async Task TakePhotoAsync()
00461         {
00462             // While taking a photo, keep the video button enabled only if the camera supports simultaneously taking pictures and recording video
00463             VideoButton.IsEnabled = _mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported;
00464
00465             // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
00466             VideoButton.Opacity = VideoButton.IsEnabled ? 1 : 0;
00467
00468             var stream = new InMemoryRandomAccessStream();
00469
00470             Debug.WriteLine("Taking photo...");
00471             await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
00472
00473             try
00474             {
00475                 var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName);
00476
00477                 Debug.WriteLine("Photo taken! Saving to " + file.Path);
00478
00479                 var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
00480
00481                 await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
00482
00483                 Debug.WriteLine("Photo saved!");
00484             }
00485             catch (Exception ex)
00486             {
00487                 // File I/O errors are reported as exceptions
00488                 Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
00489             }
00490
00491             // Done taking a photo, so re-enable the button
00492             VideoButton.IsEnabled = true;
00493             VideoButton.Opacity = 1;
00494         }
00495
00496         /// <summary>
00497         /// Records an MP4 video to a StorageFile and adds rotation metadata to it
00498         /// </summary>
00499         /// <returns></returns>
00500         private async Task StartRecordingAsync()
00501         {
00502             try
00503             {
00504                 // Create storage file for the capture
00505                 var videoFile = await _captureFolder.CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption.GenerateUniqueName);
00506
00507                 var encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
00508
00509                 // Calculate rotation angle, taking mirroring into account if necessary
00510                 var rotationAngle = 360 - ConvertDeviceOrientationToDegrees(GetCameraOrientation());
00511                 encodingProfile.Video.Properties.Add(RotationKey, PropertyValue.CreateInt32(rotationAngle));
00512
00513                 Debug.WriteLine("Starting recording to " + videoFile.Path);
00514
00515                 await _mediaCapture.StartRecordToStorageFileAsync(encodingProfile, videoFile);
00516                 _isRecording = true;
00517
00518                 Debug.WriteLine("Started recording!");
00519             }
00520             catch (Exception ex)
00521             {
00522                 // File I/O errors are reported as exceptions
00523                 Debug.WriteLine("Exception when starting video recording: " + ex.ToString());
00524             }
00525         }
00526
00527         /// <summary>
00528         /// Stops recording a video
00529         /// </summary>
00530         /// <returns></returns>
00531         private async Task StopRecordingAsync()
00532         {
00533             Debug.WriteLine("Stopping recording...");
00534
00535             _isRecording = false;
00536             await _mediaCapture.StopRecordAsync();
00537
00538             Debug.WriteLine("Stopped recording!");
00539         }
00540
00541         /// <summary>
00542         /// Cleans up the camera resources (after stopping any video recording and/or preview if necessary) and unregisters from MediaCapture events
00543         /// </summary>
00544         /// <returns></returns>
00545         private async Task CleanupCameraAsync()
00546         {
00547             Debug.WriteLine("CleanupCameraAsync");
00548
00549             if (_isInitialized)
00550             {
00551                 // If a recording is in progress during cleanup, stop it to save the recording
00552                 if (_isRecording)
00553                 {
00554                     await StopRecordingAsync();
00555                 }
00556
00557                 if (_faceDetectionEffect != null)
00558                 {
00559                     await CleanUpFaceDetectionEffectAsync();
00560                 }
00561
00562                 if (_previewProperties != null)
00563                 {
00564                     // The call to stop the preview is included here for completeness, but can be
00565                     // safely removed if a call to MediaCapture.Dispose() is being made later,
00566                     // as the preview will be automatically stopped at that point
00567                     await StopPreviewAsync();
00568                 }
00569
00570                 _isInitialized = false;
00571             }
00572
00573             if (_mediaCapture != null)
00574             {
00575                 _mediaCapture.RecordLimitationExceeded -= MediaCapture_RecordLimitationExceeded;
00576                 _mediaCapture.Failed -= MediaCapture_Failed;
00577                 _mediaCapture.Dispose();
00578                 _mediaCapture = null;
00579             }
00580         }
00581
00582         #endregion MediaCapture methods
00583
00584
00585         #region Helper functions
00586
00587         /// <summary>
00588         /// Attempts to lock the page orientation, hide the StatusBar (on Phone) and registers event handlers for hardware buttons and orientation sensors
00589         /// </summary>
00590         /// <returns></returns>
00591         private async Task SetupUiAsync()
00592         {
00593             // Attempt to lock page to landscape orientation to prevent the CaptureElement from rotating, as this gives a better experience
00594             DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
00595
00596             // Hide the status bar
00597             if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00598             {
00599                 await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();
00600             }
00601
00602             // Populate orientation variables with the current state
00603             _displayOrientation = _displayInformation.CurrentOrientation;
00604             if (_orientationSensor != null)
00605             {
00606                 _deviceOrientation = _orientationSensor.GetCurrentOrientation();
00607             }
00608
00609             RegisterEventHandlers();
00610
00611             var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
00612             // Fall back to the local app storage if the Pictures Library is not available
00613             _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
00614         }
00615
00616         /// <summary>
00617         /// Unregisters event handlers for hardware buttons and orientation sensors, allows the StatusBar (on Phone) to show, and removes the page orientation lock
00618         /// </summary>
00619         /// <returns></returns>
00620         private async Task CleanupUiAsync()
00621         {
00622             UnregisterEventHandlers();
00623
00624             // Show the status bar
00625             if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00626             {
00627                 await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync();
00628             }
00629
00630             // Revert orientation preferences
00631             DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;
00632         }
00633
00634         /// <summary>
00635         /// This method will update the icons, enable/disable and show/hide the photo/video buttons depending on the current state of the app and the capabilities of the device
00636         /// </summary>
00637         private void UpdateCaptureControls()
00638         {
00639             // The buttons should only be enabled if the preview started sucessfully
00640             PhotoButton.IsEnabled = _previewProperties != null;
00641             VideoButton.IsEnabled = _previewProperties != null;
00642             FaceDetectionButton.IsEnabled = _previewProperties != null;
00643
00644             // Update the face detection icon depending on whether the effect exists or not
00645             FaceDetectionDisabledIcon.Visibility = (_faceDetectionEffect == null || !_faceDetectionEffect.Enabled) ? Visibility.Visible : Visibility.Collapsed;
00646             FaceDetectionEnabledIcon.Visibility = (_faceDetectionEffect != null && _faceDetectionEffect.Enabled) ? Visibility.Visible : Visibility.Collapsed;
00647
00648             // Hide the face detection canvas and clear it
00649             FacesCanvas.Visibility = (_faceDetectionEffect != null && _faceDetectionEffect.Enabled) ? Visibility.Visible : Visibility.Collapsed;
00650
00651             // Update recording button to show "Stop" icon instead of red "Record" icon when recording
00652             StartRecordingIcon.Visibility = _isRecording ? Visibility.Collapsed : Visibility.Visible;
00653             StopRecordingIcon.Visibility = _isRecording ? Visibility.Visible : Visibility.Collapsed;
00654
00655             // If the camera doesn't support simultaneosly taking pictures and recording video, disable the photo button on record
00656             if (_isInitialized && !_mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported)
00657             {
00658                 PhotoButton.IsEnabled = !_isRecording;
00659
00660                 // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
00661                 PhotoButton.Opacity = PhotoButton.IsEnabled ? 1 : 0;
00662             }
00663         }
00664
00665         /// <summary>
00666         /// Registers event handlers for hardware buttons and orientation sensors, and performs an initial update of the UI rotation
00667         /// </summary>
00668         private void RegisterEventHandlers()
00669         {
00670             if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00671             {
00672                 HardwareButtons.CameraPressed += HardwareButtons_CameraPressed;
00673             }
00674
00675             // If there is an orientation sensor present on the device, register for notifications
00676             if (_orientationSensor != null)
00677             {
00678                 _orientationSensor.OrientationChanged += OrientationSensor_OrientationChanged;
00679
00680                 // Update orientation of buttons with the current orientation
00681                 UpdateButtonOrientation();
00682             }
00683
00684             _displayInformation.OrientationChanged += DisplayInformation_OrientationChanged;
00685             _systemMediaControls.PropertyChanged += SystemMediaControls_PropertyChanged;
00686         }
00687
00688         /// <summary>
00689         /// Unregisters event handlers for hardware buttons and orientation sensors
00690         /// </summary>
00691         private void UnregisterEventHandlers()
00692         {
00693             if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00694             {
00695                 HardwareButtons.CameraPressed -= HardwareButtons_CameraPressed;
00696             }
00697
00698             if (_orientationSensor != null)
00699             {
00700                 _orientationSensor.OrientationChanged -= OrientationSensor_OrientationChanged;
00701             }
00702
00703             _displayInformation.OrientationChanged -= DisplayInformation_OrientationChanged;
00704             _systemMediaControls.PropertyChanged -= SystemMediaControls_PropertyChanged;
00705         }
00706
00707         /// <summary>
00708         /// Attempts to find and return a device mounted on the panel specified, and on failure to find one it will return the first device listed
00709         /// </summary>
00710         /// <param name="desiredPanel">The desired panel on which the returned device should be mounted, if available</param>
00711         /// <returns></returns>
00712         private static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel)
00713         {
00714             // Get available devices for capturing pictures
00715             var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
00716
00717             // Get the desired camera by panel
00718             DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);
00719
00720             // If there is no device mounted on the desired panel, return the first device found
00721             return desiredDevice ?? allVideoDevices.FirstOrDefault();
00722         }
00723
00724         /// <summary>
00725         /// Applies the given orientation to a photo stream and saves it as a StorageFile
00726         /// </summary>
00727         /// <param name="stream">The photo stream</param>
00728         /// <param name="file">The StorageFile in which the photo stream will be saved</param>
00729         /// <param name="photoOrientation">The orientation metadata to apply to the photo</param>
00730         /// <returns></returns>
00731         private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation)
00732         {
00733             using (var inputStream = stream)
00734             {
00735                 var decoder = await BitmapDecoder.CreateAsync(inputStream);
00736
00737                 using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
00738                 {
00739                     var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
00740
00741                     var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };
00742
00743                     await encoder.BitmapProperties.SetPropertiesAsync(properties);
00744                     await encoder.FlushAsync();
00745                 }
00746             }
00747         }
00748
00749         #endregion Helper functions
00750
00751
00752         #region Rotation helpers
00753
00754         /// <summary>
00755         /// Calculates the current camera orientation from the device orientation by taking into account whether the camera is external or facing the user
00756         /// </summary>
00757         /// <returns>The camera orientation in space, with an inverted rotation in the case the camera is mounted on the device and is facing the user</returns>
00758         private SimpleOrientation GetCameraOrientation()
00759         {
00760             if (_externalCamera)
00761             {
00762                 // Cameras that are not attached to the device do not rotate along with it, so apply no rotation
00763                 return SimpleOrientation.NotRotated;
00764             }
00765
00766             var result = _deviceOrientation;
00767
00768             // Account for the fact that, on portrait-first devices, the camera sensor is mounted at a 90 degree offset to the native orientation
00769             if (_displayInformation.NativeOrientation == DisplayOrientations.Portrait)
00770             {
00771                 switch (result)
00772                 {
00773                     case SimpleOrientation.Rotated90DegreesCounterclockwise:
00774                         result = SimpleOrientation.NotRotated;
00775                         break;
00776                     case SimpleOrientation.Rotated180DegreesCounterclockwise:
00777                         result = SimpleOrientation.Rotated90DegreesCounterclockwise;
00778                         break;
00779                     case SimpleOrientation.Rotated270DegreesCounterclockwise:
00780                         result = SimpleOrientation.Rotated180DegreesCounterclockwise;
00781                         break;
00782                     case SimpleOrientation.NotRotated:
00783                         result = SimpleOrientation.Rotated270DegreesCounterclockwise;
00784                         break;
00785                 }
00786             }
00787
00788             // If the preview is being mirrored for a front-facing camera, then the rotation should be inverted
00789             if (_mirroringPreview)
00790             {
00791                 // This only affects the 90 and 270 degree cases, because rotating 0 and 180 degrees is the same clockwise and counter-clockwise
00792                 switch (result)
00793                 {
00794                     case SimpleOrientation.Rotated90DegreesCounterclockwise:
00795                         return SimpleOrientation.Rotated270DegreesCounterclockwise;
00796                     case SimpleOrientation.Rotated270DegreesCounterclockwise:
00797                         return SimpleOrientation.Rotated90DegreesCounterclockwise;
00798                 }
00799             }
00800
00801             return result;
00802         }
00803
00804         /// <summary>
00805         /// Converts the given orientation of the device in space to the corresponding rotation in degrees
00806         /// </summary>
00807         /// <param name="orientation">The orientation of the device in space</param>
00808         /// <returns>An orientation in degrees</returns>
00809         private static int ConvertDeviceOrientationToDegrees(SimpleOrientation orientation)
00810         {
00811             switch (orientation)
00812             {
00813                 case SimpleOrientation.Rotated90DegreesCounterclockwise:
00814                     return 90;
00815                 case SimpleOrientation.Rotated180DegreesCounterclockwise:
00816                     return 180;
00817                 case SimpleOrientation.Rotated270DegreesCounterclockwise:
00818                     return 270;
00819                 case SimpleOrientation.NotRotated:
00820                 default:
00821                     return 0;
00822             }
00823         }
00824
00825         /// <summary>
00826         /// Converts the given orientation of the app on the screen to the corresponding rotation in degrees
00827         /// </summary>
00828         /// <param name="orientation">The orientation of the app on the screen</param>
00829         /// <returns>An orientation in degrees</returns>
00830         private static int ConvertDisplayOrientationToDegrees(DisplayOrientations orientation)
00831         {
00832             switch (orientation)
00833             {
00834                 case DisplayOrientations.Portrait:
00835                     return 90;
00836                 case DisplayOrientations.LandscapeFlipped:
00837                     return 180;
00838                 case DisplayOrientations.PortraitFlipped:
00839                     return 270;
00840                 case DisplayOrientations.Landscape:
00841                 default:
00842                     return 0;
00843             }
00844         }
00845
00846         /// <summary>
00847         /// Converts the given orientation of the device in space to the metadata that can be added to captured photos
00848         /// </summary>
00849         /// <param name="orientation">The orientation of the device in space</param>
00850         /// <returns></returns>
00851         private static PhotoOrientation ConvertOrientationToPhotoOrientation(SimpleOrientation orientation)
00852         {
00853             switch (orientation)
00854             {
00855                 case SimpleOrientation.Rotated90DegreesCounterclockwise:
00856                     return PhotoOrientation.Rotate90;
00857                 case SimpleOrientation.Rotated180DegreesCounterclockwise:
00858                     return PhotoOrientation.Rotate180;
00859                 case SimpleOrientation.Rotated270DegreesCounterclockwise:
00860                     return PhotoOrientation.Rotate270;
00861                 case SimpleOrientation.NotRotated:
00862                 default:
00863                     return PhotoOrientation.Normal;
00864             }
00865         }
00866
00867         /// <summary>
00868         /// Uses the current device orientation in space and page orientation on the screen to calculate the rotation
00869         /// transformation to apply to the controls
00870         /// </summary>
00871         /// <returns>An angle in degrees to rotate the controls so they remain upright to the user regardless of device and page
00872         /// orientation</returns>
00873         private void UpdateButtonOrientation()
00874         {
00875             int device = ConvertDeviceOrientationToDegrees(_deviceOrientation);
00876             int display = ConvertDisplayOrientationToDegrees(_displayOrientation);
00877
00878             if (_displayInformation.NativeOrientation == DisplayOrientations.Portrait)
00879             {
00880                 device -= 90;
00881             }
00882
00883             // Combine both rotations and make sure that 0 <= result < 360
00884             var angle = (360 + display + device) % 360;
00885
00886             // Rotate the buttons in the UI to match the rotation of the device
00887             var transform = new RotateTransform { Angle = angle };
00888
00889             // The RenderTransform is safe to use (i.e. it won't cause layout issues) in this case, because these buttons have a 1:1 aspect ratio
00890             PhotoButton.RenderTransform = transform;
00891             VideoButton.RenderTransform = transform;
00892             FaceDetectionButton.RenderTransform = transform;
00893         }
00894
00895         /// <summary>
00896         /// Uses the current display orientation to calculate the rotation transformation to apply to the face detection bounding box canvas
00897         /// and mirrors it if the preview is being mirrored
00898         /// </summary>
00899         private void SetFacesCanvasRotation()
00900         {
00901             // Calculate how much to rotate the canvas
00902             int rotationDegrees = ConvertDisplayOrientationToDegrees(_displayOrientation);
00903
00904             // The rotation direction needs to be inverted if the preview is being mirrored, just like in SetPreviewRotationAsync
00905             if (_mirroringPreview)
00906             {
00907                 rotationDegrees = (360 - rotationDegrees) % 360;
00908             }
00909
00910             // Apply the rotation
00911             var transform = new RotateTransform { Angle = rotationDegrees };
00912             FacesCanvas.RenderTransform = transform;
00913
00914             var previewArea = GetPreviewStreamRectInControl(_previewProperties as VideoEncodingProperties, PreviewControl);
00915
00916             // For portrait mode orientations, swap the width and height of the canvas after the rotation, so the control continues to overlap the preview
00917             if (_displayOrientation == DisplayOrientations.Portrait || _displayOrientation == DisplayOrientations.PortraitFlipped)
00918             {
00919                 FacesCanvas.Width = previewArea.Height;
00920                 FacesCanvas.Height = previewArea.Width;
00921
00922                 // The position of the canvas also needs to be adjusted, as the size adjustment affects the centering of the control
00923                 Canvas.SetLeft(FacesCanvas, previewArea.X - (previewArea.Height - previewArea.Width) / 2);
00924                 Canvas.SetTop(FacesCanvas, previewArea.Y - (previewArea.Width - previewArea.Height) / 2);
00925             }
00926             else
00927             {
00928                 FacesCanvas.Width = previewArea.Width;
00929                 FacesCanvas.Height = previewArea.Height;
00930
00931                 Canvas.SetLeft(FacesCanvas, previewArea.X);
00932                 Canvas.SetTop(FacesCanvas, previewArea.Y);
00933             }
00934
00935             // Also mirror the canvas if the preview is being mirrored
00936             FacesCanvas.FlowDirection = _mirroringPreview ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
00937         }
00938
00939         #endregion Rotation helpers
00940
00941
00942         #region Face detection helpers
00943
00944         /// <summary>
00945         /// Iterates over all detected faces, creating and adding Rectangles to the FacesCanvas as face bounding boxes
00946         /// </summary>
00947         /// <param name="faces">The list of detected faces from the FaceDetected event of the effect</param>
00948         private void HighlightDetectedFaces(IReadOnlyList<DetectedFace> faces)
00949         {
00950             // Remove any existing rectangles from previous events
00951             FacesCanvas.Children.Clear();
00952
00953             // For each detected face
00954             for (int i = 0; i < faces.Count; i++)
00955             {
00956                 // Face coordinate units are preview resolution pixels, which can be a different scale from our display resolution, so a conversion may be necessary
00957                 Rectangle faceBoundingBox = ConvertPreviewToUiRectangle(faces[i].FaceBox);
00958
00959                 // Set bounding box stroke properties
00960                 faceBoundingBox.StrokeThickness = 2;
00961
00962                 // Highlight the first face in the set
00963                 faceBoundingBox.Stroke = (i == 0 ? new SolidColorBrush(Colors.Blue) : new SolidColorBrush(Colors.DeepSkyBlue));
00964
00965                 // Add grid to canvas containing all face UI objects
00966                 FacesCanvas.Children.Add(faceBoundingBox);
00967             }
00968
00969             // Update the face detection bounding box canvas orientation
00970             SetFacesCanvasRotation();
00971         }
00972
00973         /// <summary>
00974         /// Takes face information defined in preview coordinates and returns one in UI coordinates, taking
00975         /// into account the position and size of the preview control.
00976         /// </summary>
00977         /// <param name="faceBoxInPreviewCoordinates">Face coordinates as retried from the FaceBox property of a DetectedFace, in preview coordinates.</param>
00978         /// <returns>Rectangle in UI (CaptureElement) coordinates, to be used in a Canvas control.</returns>
00979         private Rectangle ConvertPreviewToUiRectangle(BitmapBounds faceBoxInPreviewCoordinates)
00980         {
00981             var result = new Rectangle();
00982             var previewStream = _previewProperties as VideoEncodingProperties;
00983
00984             // If there is no available information about the preview, return an empty rectangle, as re-scaling to the screen coordinates will be impossible
00985             if (previewStream == null) return result;
00986
00987             // Similarly, if any of the dimensions is zero (which would only happen in an error case) return an empty rectangle
00988             if (previewStream.Width == 0 || previewStream.Height == 0) return result;
00989
00990             double streamWidth = previewStream.Width;
00991             double streamHeight = previewStream.Height;
00992
00993             // For portrait orientations, the width and height need to be swapped
00994             if (_displayOrientation == DisplayOrientations.Portrait || _displayOrientation == DisplayOrientations.PortraitFlipped)
00995             {
00996                 streamHeight = previewStream.Width;
00997                 streamWidth = previewStream.Height;
00998             }
00999
01000             // Get the rectangle that is occupied by the actual video feed
01001             var previewInUI = GetPreviewStreamRectInControl(previewStream, PreviewControl);
01002
01003             // Scale the width and height from preview stream coordinates to window coordinates
01004             result.Width = (faceBoxInPreviewCoordinates.Width / streamWidth) * previewInUI.Width;
01005             result.Height = (faceBoxInPreviewCoordinates.Height / streamHeight) * previewInUI.Height;
01006
01007             // Scale the X and Y coordinates from preview stream coordinates to window coordinates
01008             var x = (faceBoxInPreviewCoordinates.X / streamWidth) * previewInUI.Width;
01009             var y = (faceBoxInPreviewCoordinates.Y / streamHeight) * previewInUI.Height;
01010             Canvas.SetLeft(result, x);
01011             Canvas.SetTop(result, y);
01012
01013             return result;
01014         }
01015
01016         /// <summary>
01017         /// Calculates the size and location of the rectangle that contains the preview stream within the preview control, when the scaling mode is Uniform
01018         /// </summary>
01019         /// <param name="previewResolution">The resolution at which the preview is running</param>
01020         /// <param name="previewControl">The control that is displaying the preview using Uniform as the scaling mode</param>
01021         /// <returns></returns>
01022         public Rect GetPreviewStreamRectInControl(VideoEncodingProperties previewResolution, CaptureElement previewControl)
01023         {
01024             var result = new Rect();
01025
01026             // In case this function is called before everything is initialized correctly, return an empty result
01027             if (previewControl == null || previewControl.ActualHeight < 1 || previewControl.ActualWidth < 1 ||
01028                 previewResolution == null || previewResolution.Height == 0 || previewResolution.Width == 0)
01029             {
01030                 return result;
01031             }
01032
01033             var streamWidth = previewResolution.Width;
01034             var streamHeight = previewResolution.Height;
01035
01036             // For portrait orientations, the width and height need to be swapped
01037             if (_displayOrientation == DisplayOrientations.Portrait || _displayOrientation == DisplayOrientations.PortraitFlipped)
01038             {
01039                 streamWidth = previewResolution.Height;
01040                 streamHeight = previewResolution.Width;
01041             }
01042
01043             // Start by assuming the preview display area in the control spans the entire width and height both (this is corrected in the next if for the necessary dimension)
01044             result.Width = previewControl.ActualWidth;
01045             result.Height = previewControl.ActualHeight;
01046
01047             // If UI is "wider" than preview, letterboxing will be on the sides
01048             if ((previewControl.ActualWidth / previewControl.ActualHeight > streamWidth / (double)streamHeight))
01049             {
01050                 var scale = previewControl.ActualHeight / streamHeight;
01051                 var scaledWidth = streamWidth * scale;
01052
01053                 result.X = (previewControl.ActualWidth - scaledWidth) / 2.0;
01054                 result.Width = scaledWidth;
01055             }
01056             else // Preview stream is "wider" than UI, so letterboxing will be on the top+bottom
01057             {
01058                 var scale = previewControl.ActualWidth / streamWidth;
01059                 var scaledHeight = streamHeight * scale;
01060
01061                 result.Y = (previewControl.ActualHeight - scaledHeight) / 2.0;
01062                 result.Height = scaledHeight;
01063             }
01064
01065             return result;
01066         }
01067
01068         #endregion
01069
01070     }
01071 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cs/Scenario7.xaml.cs Source File

  • XamlCommanding
  • cs

Scenario7.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013
00014 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00015
00016 namespace Commanding
00017 {
00018     /// <summary>
00019     /// An empty page that can be used on its own or navigated to within a Frame.
00020     /// </summary>
00021     public sealed partial class Scenario7 : Page
00022     {
00023         public Scenario7()
00024         {
00025             this.InitializeComponent();
00026         }
00027
00028         private void CommandBar_Opening(object sender, object e)
00029         {
00030             this.appbarbutton.IsCompact = !this.appbarbutton.IsCompact;
00031         }
00032
00033         private void CommandBar_Closed(object sender, object e)
00034         {
00035             this.appbarbutton.IsCompact = !this.appbarbutton.IsCompact;
00036         }
00037     }
00038 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CashDrawer/cpp/Scenario1_OpenDrawer.xaml.cpp Source File

  • CashDrawer
  • cpp

Scenario1_OpenDrawer.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_OpenDrawer.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Media;
00027 using namespace Windows::UI::Xaml::Navigation;
00028 using namespace Windows::Devices::PointOfService;
00029
00030 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00031
00032 Scenario1_OpenDrawer::Scenario1_OpenDrawer() : rootPage(MainPage::Current)
00033 {
00034     InitializeComponent();
00035 }
00036
00037
00038 /// <summary>
00039 /// Invoked when this page is about to be displayed in a Frame.
00040 /// </summary>
00041 /// <param name="e">Event data that describes how this page was reached.</param>
00042 void Scenario1_OpenDrawer::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     ResetScenarioState();
00045 }
00046
00047
00048 /// <summary>
00049 /// Invoked before the page is unloaded and is no longer the current source of a Frame.
00050 /// </summary>
00051 /// <param name="e">Event data describing the navigation that was requested.</param>
00052 void Scenario1_OpenDrawer::OnNavigatedFrom(NavigationEventArgs^ e)
00053 {
00054     ResetScenarioState();
00055 }
00056
00057
00058 /// <summary>
00059 /// Event handler for Initialize Drawer button.
00060 /// Claims and enables the default cash drawer.
00061 /// </summary>
00062 /// <param name="sender">Button that was clicked.</param>
00063 /// <param name="e">Event data associated with click event.</param>
00064 void Scenario1_OpenDrawer::InitDrawerButton_Click(Object^ sender, RoutedEventArgs^ e)
00065 {
00066     create_task(CreateDefaultCashDrawerObject()).then([this](bool success)
00067     {
00068         if (!success)
00069         {
00070             rootPage->NotifyUser("Cash drawer not found. Please connect a cash drawer.", NotifyType::ErrorMessage);
00071             return;
00072         }
00073
00074         create_task(ClaimCashDrawer()).then([this](bool success)
00075         {
00076             if (!success)
00077             {
00078                 rootPage->NotifyUser("Failed to claim cash drawer.", NotifyType::ErrorMessage);
00079                 return;
00080             }
00081
00082             create_task(claimedDrawer->EnableAsync()).then([this](bool success)
00083             {
00084                 if (!success)
00085                 {
00086                     rootPage->NotifyUser("Failed to enable cash drawer.", NotifyType::ErrorMessage);
00087                     return;
00088                 }
00089
00090                 rootPage->NotifyUser("Successfully enabled cash drawer. Device ID: " + claimedDrawer->DeviceId, NotifyType::StatusMessage);
00091
00092                 InitDrawerButton->IsEnabled = false;
00093                 OpenDrawerButton->IsEnabled = true;
00094             });
00095         });
00096     });
00097 }
00098
00099
00100 /// <summary>
00101 /// Open the cash drawer.
00102 /// </summary>
00103 /// <param name="sender">Button that was clicked.</param>
00104 /// <param name="e">Event data associated with click event.</param>
00105 void Scenario1_OpenDrawer::OpenDrawerButton_Click(Object^ sender, RoutedEventArgs^ e)
00106 {
00107     create_task(claimedDrawer->OpenDrawerAsync()).then([this](bool success)
00108     {
00109         if (success)
00110             rootPage->NotifyUser("Cash drawer open succeeded.", NotifyType::StatusMessage);
00111         else
00112             rootPage->NotifyUser("Cash drawer open failed.", NotifyType::ErrorMessage);
00113     });
00114
00115 }
00116
00117
00118 /// <summary>
00119 /// Creates the default cash drawer.
00120 /// </summary>
00121 /// <returns>True if the cash drawer was created, false otherwise.</returns>
00122 task<bool> Scenario1_OpenDrawer::CreateDefaultCashDrawerObject()
00123 {
00124     rootPage->NotifyUser("Creating cash drawer object.", NotifyType::StatusMessage);
00125
00126     return DeviceHelpers::GetFirstCashDrawerAsync().then([this](CashDrawer^ defaultDrawer)
00127     {
00128         if (defaultDrawer == nullptr)
00129             return false;
00130
00131         drawer = defaultDrawer;
00132         return true;
00133     });
00134 }
00135
00136
00137 /// <summary>
00138 /// Attempt to claim the connected cash drawer.
00139 /// </summary>
00140 /// <returns>True if the operation succeeds, false otherwise.</returns>
00141 task<bool> Scenario1_OpenDrawer::ClaimCashDrawer()
00142 {
00143     return create_task(drawer->ClaimDrawerAsync()).then([this](ClaimedCashDrawer^ claimed)
00144     {
00145         if (claimed == nullptr)
00146             return false;
00147
00148         claimedDrawer = claimed;
00149         return true;
00150     });
00151 }
00152
00153
00154 /// <summary>
00155 /// Reset the scenario to its initial state.
00156 /// </summary>
00157 void Scenario1_OpenDrawer::ResetScenarioState()
00158 {
00159     if (drawer != nullptr)
00160     {
00161         delete drawer;
00162         drawer = nullptr;
00163     }
00164
00165     if (claimedDrawer != nullptr)
00166     {
00167         delete claimedDrawer;
00168         claimedDrawer = nullptr;
00169     }
00170
00171     InitDrawerButton->IsEnabled = true;
00172     OpenDrawerButton->IsEnabled = false;
00173
00174     rootPage->NotifyUser("Click the init drawer button to begin.", NotifyType::StatusMessage);
00175 }
00176
Generated on Fri Nov 15 2024 22:18:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: GlobalizationPreferences/cppwinrt/SampleConfiguration.cpp Source File

  • GlobalizationPreferences
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::Globalization;
00020 using namespace SDKTemplate;
00021
00022 hstring implementation::MainPage::FEATURE_NAME()
00023 {
00024     return L"Globalization preferences C++/WinRT sample";
00025 }
00026
00027 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00028 {
00029     Scenario{ L"User preferences", xaml_typename<SDKTemplate::Scenario1_Prefs>() },
00030     Scenario{ L"Language characteristics", xaml_typename<SDKTemplate::Scenario2_Lang>() },
00031     Scenario{ L"Region characteristics", xaml_typename<SDKTemplate::Scenario3_Region>() },
00032     Scenario{ L"Current input language", xaml_typename<SDKTemplate::Scenario4_Input>() },
00033 });
00034
00035 hstring SDKTemplate::StringJoin(hstring const& delimiter, IVectorView<hstring> const& vector)
00036 {
00037     hstring result;
00038
00039     bool first = true;
00040     for (hstring value : vector)
00041     {
00042         if (!first)
00043         {
00044             result = result + delimiter;
00045         }
00046         result = result + value;
00047     }
00048     return result;
00049 }
00050
00051 hstring winrt::to_hstring(DayOfWeek value)
00052 {
00053     switch (value)
00054     {
00055     case DayOfWeek::Sunday: return L"Sunday";
00056     case DayOfWeek::Monday: return L"Monday";
00057     case DayOfWeek::Tuesday: return L"Tuesday";
00058     case DayOfWeek::Wednesday: return L"Wednesday";
00059     case DayOfWeek::Thursday: return L"Thursday";
00060     case DayOfWeek::Friday: return L"Friday";
00061     case DayOfWeek::Saturday: return L"Saturday";
00062     }
00063     return to_hstring(static_cast<int32_t>(value));
00064 }
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LocalHostItem Member List

This is the complete list of members for LocalHostItem, including all inherited members.
DisplayString | LocalHostItem |
LocalHost | LocalHostItem |
LocalHostItem(HostName localHostName) | LocalHostItem | [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/xBindSampleModel/Converters.cs Source File

  • XamlBind
  • cpp
  • xBindSampleModel

Converters.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI;
00003 using Windows.UI.Xaml;
00004 using Windows.UI.Xaml.Data;
00005
00006
00007 namespace BindTestbedModel
00008 {
00009     public sealed class ColorToStringConverter : IValueConverter
00010     {
00011         static string[] colorNames = { "AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenrod", "DarkGray", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "DarkOrange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DodgerBlue", "Firebrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "Goldenrod", "Gray", "Green", "GreenYellow", "Honeydew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenrodYellow", "LightGray", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquamarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenrod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Transparent", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen" };
00012         static Color[] colorValues = { Colors.AliceBlue, Colors.AntiqueWhite, Colors.Aqua, Colors.Aquamarine, Colors.Azure, Colors.Beige, Colors.Bisque, Colors.Black, Colors.BlanchedAlmond, Colors.Blue, Colors.BlueViolet, Colors.Brown, Colors.BurlyWood, Colors.CadetBlue, Colors.Chartreuse, Colors.Chocolate, Colors.Coral, Colors.CornflowerBlue, Colors.Cornsilk, Colors.Crimson, Colors.Cyan, Colors.DarkBlue, Colors.DarkCyan, Colors.DarkGoldenrod, Colors.DarkGray, Colors.DarkGreen, Colors.DarkKhaki, Colors.DarkMagenta, Colors.DarkOliveGreen, Colors.DarkOrange, Colors.DarkOrchid, Colors.DarkRed, Colors.DarkSalmon, Colors.DarkSeaGreen, Colors.DarkSlateBlue, Colors.DarkSlateGray, Colors.DarkTurquoise, Colors.DarkViolet, Colors.DeepPink, Colors.DeepSkyBlue, Colors.DimGray, Colors.DodgerBlue, Colors.Firebrick, Colors.FloralWhite, Colors.ForestGreen, Colors.Fuchsia, Colors.Gainsboro, Colors.GhostWhite, Colors.Gold, Colors.Goldenrod, Colors.Gray, Colors.Green, Colors.GreenYellow, Colors.Honeydew, Colors.HotPink, Colors.IndianRed, Colors.Indigo, Colors.Ivory, Colors.Khaki, Colors.Lavender, Colors.LavenderBlush, Colors.LawnGreen, Colors.LemonChiffon, Colors.LightBlue, Colors.LightCoral, Colors.LightCyan, Colors.LightGoldenrodYellow, Colors.LightGray, Colors.LightGreen, Colors.LightPink, Colors.LightSalmon, Colors.LightSeaGreen, Colors.LightSkyBlue, Colors.LightSlateGray, Colors.LightSteelBlue, Colors.LightYellow, Colors.Lime, Colors.LimeGreen, Colors.Linen, Colors.Magenta, Colors.Maroon, Colors.MediumAquamarine, Colors.MediumBlue, Colors.MediumOrchid, Colors.MediumPurple, Colors.MediumSeaGreen, Colors.MediumSlateBlue, Colors.MediumSpringGreen, Colors.MediumTurquoise, Colors.MediumVioletRed, Colors.MidnightBlue, Colors.MintCream, Colors.MistyRose, Colors.Moccasin, Colors.NavajoWhite, Colors.Navy, Colors.OldLace, Colors.Olive, Colors.OliveDrab, Colors.Orange, Colors.OrangeRed, Colors.Orchid, Colors.PaleGoldenrod, Colors.PaleGreen, Colors.PaleTurquoise, Colors.PaleVioletRed, Colors.PapayaWhip, Colors.PeachPuff, Colors.Peru, Colors.Pink, Colors.Plum, Colors.PowderBlue, Colors.Purple, Colors.Red, Colors.RosyBrown, Colors.RoyalBlue, Colors.SaddleBrown, Colors.Salmon, Colors.SandyBrown, Colors.SeaGreen, Colors.SeaShell, Colors.Sienna, Colors.Silver, Colors.SkyBlue, Colors.SlateBlue, Colors.SlateGray, Colors.Snow, Colors.SpringGreen, Colors.SteelBlue, Colors.Tan, Colors.Teal, Colors.Thistle, Colors.Tomato, Colors.Transparent, Colors.Turquoise, Colors.Violet, Colors.Wheat, Colors.White, Colors.WhiteSmoke, Colors.Yellow, Colors.YellowGreen };
00013
00014         public object Convert(object value, Type targetType, object parameter, string language)
00015         {
00016             Color src = (Color)value;
00017             for (int i = 0; i < colorValues.Length; i++)
00018             {
00019                 if (src == colorValues[i])
00020                 {
00021                     return colorNames[i];
00022                 }
00023             }
00024             return string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", src.A, src.R, src.G, src.B);
00025         }
00026
00027         public object ConvertBack(object value, Type targetType, object parameter, string language)
00028         {
00029             string src = (string)value;
00030             for (int i = 0; i < colorValues.Length; i++)
00031             {
00032                 if (src == colorNames[i])
00033                 {
00034                     return colorValues[i];
00035                 }
00036             }
00037             if (src.StartsWith("#"))
00038             {
00039                 return Color.FromArgb(Byte.Parse(src.Substring(1, 2), System.Globalization.NumberStyles.HexNumber),
00040                     Byte.Parse(src.Substring(3, 2), System.Globalization.NumberStyles.HexNumber),
00041                     Byte.Parse(src.Substring(5, 2), System.Globalization.NumberStyles.HexNumber),
00042                     Byte.Parse(src.Substring(7, 2), System.Globalization.NumberStyles.HexNumber));
00043             }
00044             throw new ArgumentException("Cannot parse the color");
00045         }
00046     }
00047 }
00048
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cs/Scenario2_MultiFile.xaml.cs Source File

  • FilePicker
  • cs

Scenario2_MultiFile.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Text;
00014 using System.Collections.Generic;
00015 using Windows.Storage;
00016 using Windows.Storage.Pickers;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026     public sealed partial class Scenario2_MultiFile : Page
00027     {
00028         MainPage rootPage = MainPage.Current;
00029
00030         public Scenario2_MultiFile()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         private async void PickFilesButton_Click(object sender, RoutedEventArgs e)
00036         {
00037             // Clear any previously returned files between iterations of this scenario
00038             OutputTextBlock.Text = "";
00039
00040             FileOpenPicker openPicker = new FileOpenPicker();
00041             openPicker.ViewMode = PickerViewMode.List;
00042             openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
00043             openPicker.FileTypeFilter.Add("*");
00044             IReadOnlyList<StorageFile> files = await openPicker.PickMultipleFilesAsync();
00045             if (files.Count > 0)
00046             {
00047                 StringBuilder output = new StringBuilder("Picked files:\n");
00048                 // The StorageFiles have read/write access to the picked files.
00049                 // See the FileAccess sample for code that uses a StorageFile to read and write.
00050                 foreach (StorageFile file in files)
00051                 {
00052                     output.Append(file.Name + "\n");
00053                 }
00054                 OutputTextBlock.Text = output.ToString();
00055             }
00056             else
00057             {
00058                 OutputTextBlock.Text = "Operation cancelled.";
00059             }
00060         }
00061     }
00062 }
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/Content/ShaderStructures.cs Source File

  • 360VideoPlayback
  • cs
  • Content

ShaderStructures.cs

Go to the documentation of this file.
00001 ﻿using System.Numerics;
00002
00003 namespace _360VideoPlayback.Content
00004 {
00005     /// <summary>
00006     /// Constant buffer used to send hologram position transform to the shader pipeline.
00007     /// </summary>
00008     internal struct ModelConstantBuffer
00009     {
00010         public Matrix4x4 model;
00011     }
00012
00013     /// <summary>
00014     /// Used to send per-vertex data to the vertex shader.
00015     /// </summary>
00016     internal struct VertexPositionColor
00017     {
00018         public VertexPositionColor(Vector3 pos, Vector3 color)
00019         {
00020             this.pos   = pos;
00021             this.color = color;
00022         }
00023
00024         public Vector3 pos;
00025         public Vector3 color;
00026     };
00027
00028     internal struct VertexPositionTexture
00029     {
00030         public VertexPositionTexture(Vector3 pos, Vector2 texture)
00031         {
00032             this.pos = pos;
00033             this.texture = texture;
00034         }
00035
00036         public Vector3 pos;
00037         public Vector2 texture;
00038     };
00039 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cs/Scenario4_Remove.xaml.cs Source File

  • Playlists
  • cs

Scenario4_Remove.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Media.Playlists;
00015 using Windows.Storage;
00016 using Windows.Storage.Pickers;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario4_Remove : Page
00024     {
00025         private MainPage rootPage = MainPage.Current;
00026
00027         public Scenario4_Remove()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         /// <summary>
00033         /// Removes the last file in the playlist picked by the user in the FilePicker
00034         /// </summary>
00035         /// <param name="sender"></param>
00036         /// <param name="e"></param>
00037         async private void PickPlaylistButton_Click(object sender, RoutedEventArgs e)
00038         {
00039             Playlist playlist = await rootPage.PickPlaylistAsync();
00040
00041             if (playlist != null)
00042             {
00043                 if (playlist.Files.Count > 0)
00044                 {
00045                     playlist.Files.RemoveAt(playlist.Files.Count - 1);
00046
00047                     if (await rootPage.TrySavePlaylistAsync(playlist))
00048                     {
00049                         rootPage.NotifyUser("The last item in the playlist was removed.", NotifyType.StatusMessage);
00050                     }
00051                 }
00052                 else
00053                 {
00054                     rootPage.NotifyUser("No items in playlist.", NotifyType.ErrorMessage);
00055                 }
00056             }
00057         }
00058     }
00059 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cs/Scenario1Basic.xaml.cs Source File

  • Printing
  • cs

Scenario1Basic.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using Windows.Graphics.Printing;
00017 using SDKTemplate;
00018
00019 namespace PrintSample
00020 {
00021     /// <summary>
00022     /// Scenario that demonstrates how to invoke the Print UI
00023     /// </summary>
00024     public sealed partial class Scenario1Basic : Page
00025     {
00026         private PrintHelper printHelper;
00027
00028         public Scenario1Basic()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         /// <summary>
00034         /// This is the click handler for the 'Print' button.
00035         /// </summary>
00036         /// <param name="sender"></param>
00037         /// <param name="e"></param>
00038         private async void OnPrintButtonClick(object sender, RoutedEventArgs e)
00039         {
00040             await printHelper.ShowPrintUIAsync();
00041         }
00042
00043         protected override void OnNavigatedTo(NavigationEventArgs e)
00044         {
00045             if (PrintManager.IsSupported())
00046             {
00047                 // Tell the user how to print
00048                 MainPage.Current.NotifyUser("Print contract registered with customization, use the Print button to print.", NotifyType.StatusMessage);
00049             }
00050             else
00051             {
00052                 // Remove the print button
00053                 InvokePrintingButton.Visibility = Visibility.Collapsed;
00054
00055                 // Inform user that Printing is not supported
00056                 MainPage.Current.NotifyUser("Printing is not supported.", NotifyType.ErrorMessage);
00057
00058                 // Printing-related event handlers will never be called if printing
00059                 // is not supported, but it's okay to register for them anyway.
00060             }
00061
00062             // Initalize common helper class and register for printing
00063             printHelper = new PrintHelper(this);
00064             printHelper.RegisterForPrinting();
00065
00066             // Initialize print content for this scenario
00067             printHelper.PreparePrintContent(new PageToPrint());
00068         }
00069
00070         protected override void OnNavigatedFrom(NavigationEventArgs e)
00071         {
00072             if (printHelper != null)
00073             {
00074                 printHelper.UnregisterForPrinting();
00075             }
00076         }
00077     }
00078 }
Generated on Fri Nov 15 2024 22:21:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_VerifyResponse Member List

This is the complete list of members for Scenario5_VerifyResponse, including all inherited members.
rootPage | Scenario5_VerifyResponse | [private]
Scenario5_VerifyResponse() | Scenario5_VerifyResponse | [inline]
VerifyResponse_Click(object sender, RoutedEventArgs e) | Scenario5_VerifyResponse | [inline, private]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePickerContracts/cs/MainPage_PickFile.xaml.cs Source File

  • FilePickerContracts
  • cs

MainPage_PickFile.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using SDKTemplate;
00012
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Text;
00016 using Windows.Storage;
00017 using Windows.Storage.Pickers;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace FilePickerContracts
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class MainPage_PickFile : Page
00028     {
00029         public MainPage_PickFile()
00030         {
00031             this.InitializeComponent();
00032             ThisAppTitle.Text = MainPage.APP_TITLE;
00033             PickFileButton.Click += new RoutedEventHandler(PickFileButton_Click);
00034         }
00035
00036         private async void PickFileButton_Click(object sender, RoutedEventArgs e)
00037         {
00038             MainPage page = MainPage.Current;
00039
00040             //$$page.ResetScenarioOutput(OutputTextBlock);
00041             // Set up and launch the Open Picker
00042             FileOpenPicker fileOpenPicker = new FileOpenPicker();
00043             fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
00044             fileOpenPicker.FileTypeFilter.Add(".png");
00045             fileOpenPicker.FileTypeFilter.Add(".txt");
00046
00047             IReadOnlyList<StorageFile> files = await fileOpenPicker.PickMultipleFilesAsync();
00048             StringBuilder fileNames = new StringBuilder();
00049             foreach (StorageFile file in files)
00050             {
00051                 // At this point, the app can begin reading from the provided file
00052                 fileNames.AppendLine(file.Name);
00053             }
00054
00055             OutputTextBlock.Text = fileNames.ToString();
00056         }
00057     }
00058 }
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cs/SocketReaderWriter.cs Source File

  • WiFiDirect
  • cs

SocketReaderWriter.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Networking.Sockets;
00014 using Windows.Storage.Streams;
00015 using Windows.Devices.Enumeration;
00016 using System.ComponentModel;
00017 using Windows.Devices.WiFiDirect;
00018 using System.Threading.Tasks;
00019 using Windows.UI.Popups;
00020 using Windows.UI.Core;
00021 using Windows.Foundation;
00022
00023 namespace SDKTemplate
00024 {
00025     public class SocketReaderWriter : IDisposable
00026     {
00027         DataReader _dataReader;
00028         DataWriter _dataWriter;
00029         StreamSocket _streamSocket;
00030         private MainPage _rootPage;
00031
00032         public SocketReaderWriter(StreamSocket socket, MainPage mainPage)
00033         {
00034             _dataReader = new DataReader(socket.InputStream);
00035             _dataReader.UnicodeEncoding = UnicodeEncoding.Utf8;
00036             _dataReader.ByteOrder = ByteOrder.LittleEndian;
00037
00038             _dataWriter = new DataWriter(socket.OutputStream);
00039             _dataWriter.UnicodeEncoding = UnicodeEncoding.Utf8;
00040             _dataWriter.ByteOrder = ByteOrder.LittleEndian;
00041
00042             _streamSocket = socket;
00043             _rootPage = mainPage;
00044         }
00045
00046         public void Dispose()
00047         {
00048             _dataReader.Dispose();
00049             _dataWriter.Dispose();
00050             _streamSocket.Dispose();
00051         }
00052
00053         public async Task WriteMessageAsync(string message)
00054         {
00055             try
00056             {
00057                 _dataWriter.WriteUInt32(_dataWriter.MeasureString(message));
00058                 _dataWriter.WriteString(message);
00059                 await _dataWriter.StoreAsync();
00060                 _rootPage.NotifyUserFromBackground("Sent message: " + message, NotifyType.StatusMessage);
00061             }
00062             catch (Exception ex)
00063             {
00064                 _rootPage.NotifyUserFromBackground("WriteMessage threw exception: " + ex.Message, NotifyType.StatusMessage);
00065             }
00066         }
00067
00068         public async Task<string> ReadMessageAsync()
00069         {
00070             try
00071             {
00072                 UInt32 bytesRead = await _dataReader.LoadAsync(sizeof(UInt32));
00073                 if (bytesRead > 0)
00074                 {
00075                     // Determine how long the string is.
00076                     UInt32 messageLength = _dataReader.ReadUInt32();
00077                     bytesRead = await _dataReader.LoadAsync(messageLength);
00078                     if (bytesRead > 0)
00079                     {
00080                         // Decode the string.
00081                         string message = _dataReader.ReadString(messageLength);
00082                         _rootPage.NotifyUserFromBackground("Got message: " + message, NotifyType.StatusMessage);
00083                         return message;
00084                     }
00085                 }
00086             }
00087             catch (Exception)
00088             {
00089                 _rootPage.NotifyUserFromBackground("Socket was closed!", NotifyType.StatusMessage);
00090             }
00091             return null;
00092         }
00093     }
00094
00095     public class DiscoveredDevice : INotifyPropertyChanged
00096     {
00097         public DeviceInformation DeviceInfo { get; private set; }
00098
00099         public DiscoveredDevice(DeviceInformation deviceInfo)
00100         {
00101             DeviceInfo = deviceInfo;
00102         }
00103
00104         public string DisplayName => DeviceInfo.Name + " - " + (DeviceInfo.Pairing.IsPaired ? "Paired" : "Unpaired");
00105         public override string ToString() => DisplayName;
00106
00107         public void UpdateDeviceInfo(DeviceInformationUpdate update)
00108         {
00109             DeviceInfo.Update(update);
00110             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("DisplayName"));
00111         }
00112
00113         public event PropertyChangedEventHandler PropertyChanged;
00114     }
00115
00116     public class ConnectedDevice : IDisposable
00117     {
00118         public SocketReaderWriter SocketRW { get; }
00119         public WiFiDirectDevice WfdDevice { get; }
00120         public string DisplayName { get; }
00121
00122         public ConnectedDevice(string displayName, WiFiDirectDevice wfdDevice, SocketReaderWriter socketRW)
00123         {
00124             DisplayName = displayName;
00125             WfdDevice = wfdDevice;
00126             SocketRW = socketRW;
00127         }
00128
00129         public override string ToString() => DisplayName;
00130
00131         public void Dispose()
00132         {
00133             // Close socket
00134             SocketRW.Dispose();
00135
00136             // Close WiFiDirectDevice object
00137             WfdDevice.Dispose();
00138         }
00139     }
00140 }
Generated on Fri Nov 15 2024 22:22:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_BasicFunctionality Member List

This is the complete list of members for Scenario1_BasicFunctionality, including all inherited members.
claimedScanner_DataReceived(Windows::Devices::PointOfService::ClaimedBarcodeScanner const &sender, Windows::Devices::PointOfService::BarcodeScannerDataReceivedEventArgs args) | Scenario1_BasicFunctionality |
claimedScanner_ReleaseDeviceRequested(Windows::Foundation::IInspectable const &, Windows::Devices::PointOfService::ClaimedBarcodeScanner const &e) | Scenario1_BasicFunctionality |
m_claimedScannerDataReceivedToken | Scenario1_BasicFunctionality | [private]
m_claimedScannerReleaseDeviceRequestedToken | Scenario1_BasicFunctionality | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_BasicFunctionality |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_BasicFunctionality |
ResetTheScenarioState() | Scenario1_BasicFunctionality | [private]
Scenario1_BasicFunctionality() | Scenario1_BasicFunctionality |
ScenarioEndScanButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_BasicFunctionality |
ScenarioStartScanButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_BasicFunctionality |
ScenarioStartTriggerButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_BasicFunctionality |
ScenarioStopTriggerButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_BasicFunctionality |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OnDemandHotspot/cppwinrt/BackgroundTask/Tasks.cpp Source File

  • OnDemandHotspot
  • cppwinrt
  • BackgroundTask

Tasks.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Tasks.h"
00014 #include "UpdateMetadataTask.g.cpp"
00015 #include "ConnectTask.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::ApplicationModel::Background;
00019 using namespace winrt::Windows::Data::Xml::Dom;
00020 using namespace winrt::Windows::Devices::WiFi;
00021 using namespace winrt::Windows::Foundation;
00022 using namespace winrt::Windows::Foundation::Collections;
00023 using namespace winrt::Windows::Security::Credentials;
00024 using namespace winrt::Windows::Storage;
00025 using namespace winrt::Windows::UI::Notifications;
00026
00027 namespace winrt::BackgroundTask::implementation
00028 {
00029     // This task is triggered when the system wants us to refresh our hotspot metadata.
00030     // This typically happens when the system is about to show a list of available Wi-Fi networks.
00031     void UpdateMetadataTask::Run(IBackgroundTaskInstance const&)
00032     {
00033         // A real on-demand hotspot task would contact each hotspot device to
00034         // obtain this information. This sample doesn't have a real hotspot device,
00035         // so it just repeats the information set by the UI portion of the app.
00036
00037         IPropertySet values{ ApplicationData::Current().LocalSettings().Values() };
00038         std::optional<winrt::guid> hotspotGuid = values.TryLookup(L"hotspotGuid").try_as<winrt::guid>();
00039         if (!hotspotGuid.has_value())
00040         {
00041             // Nothing configured.
00042             return;
00043         }
00044
00045         WiFiOnDemandHotspotNetwork network = WiFiOnDemandHotspotNetwork::GetOrCreateById(hotspotGuid.value());
00046         WiFiOnDemandHotspotNetworkProperties properties = network.GetProperties();
00047
00048         properties.Availability(values.Lookup(L"availability").as<bool>() ? WiFiOnDemandHotspotAvailability::Available : WiFiOnDemandHotspotAvailability::Unavailable);
00049         properties.DisplayName(values.Lookup(L"displayName").as<hstring>());
00050         std::optional<int> bars = values.TryLookup(L"bars").try_as<int>();
00051         properties.CellularBars(bars.has_value() ? std::optional(static_cast<WiFiOnDemandHotspotCellularBars>(bars.value())) : std::nullopt);
00052         properties.RemainingBatteryPercent(values.TryLookup(L"bars").try_as<uint32_t>());
00053         properties.Ssid(values.TryLookup(L"ssid").as<hstring>());
00054
00055         PasswordCredential credential;
00056         credential.Password(values.TryLookup(L"password").as<hstring>());
00057         properties.Password(credential);
00058
00059         network.UpdateProperties(properties);
00060     }
00061
00062     // This task is triggered when the user selects our hotspot in the list of available Wi-Fi networks.
00063     // The task should turn on the Wi-Fi hotspot so that the system can connect to it.
00064
00065     void ConnectTask::Run(IBackgroundTaskInstance const& taskInstance)
00066     {
00067         WiFiOnDemandHotspotConnectTriggerDetails triggerDetails = taskInstance.TriggerDetails().as<WiFiOnDemandHotspotConnectTriggerDetails>();
00068
00069         // A real on-demand hotspot task would contact the hotspot device and tell it
00070         // to start advertising the SSID.
00071         //
00072         // This sample doesn't have a real hotspot device, so it will simulate the action
00073         // by displaying a toast to instruct the user to turn on the mobile hotspot manually.
00074
00075         WiFiOnDemandHotspotNetwork network = triggerDetails.RequestedNetwork();
00076
00077         // Is this the network we know how to turn on?
00078         IPropertySet values = ApplicationData::Current().LocalSettings().Values();
00079         if (values.TryLookup(L"hotspotGuid").try_as<winrt::guid>().value_or(winrt::guid{}) != network.Id())
00080         {
00081             triggerDetails.ReportError(WiFiOnDemandHotspotConnectStatus::UnspecifiedFailure);
00082             return;
00083         }
00084
00085         // To demonstrate how to report errors turning on the hotspot, we will report an error
00086         // if the hotspot is configured with an SSID named "error".
00087         WiFiOnDemandHotspotNetworkProperties properties = network.GetProperties();
00088         hstring ssid = properties.Ssid();
00089         if (ssid == L"error")
00090         {
00091             // Simulate an error turning on the hotspot. You can report any error code from the
00092             // WiFiOnDemandHotspotConnectStatus enumeration.
00093             triggerDetails.ReportError(WiFiOnDemandHotspotConnectStatus::NetworkNotAvailable);
00094         }
00095         else
00096         {
00097             DisplayToast(ssid);
00098             Sleep(5000);
00099
00100             WiFiOnDemandHotspotConnectionResult result = triggerDetails.Connect();
00101             values.Insert(L"connectResult", box_value(static_cast<int>(result.Status())));
00102         }
00103     }
00104
00105     void ConnectTask::DisplayToast(const winrt::hstring& ssid)
00106     {
00107         ToastNotifier ToastNotifier = ToastNotificationManager::CreateToastNotifier();
00108
00109         // Create a two line toast and add audio reminder
00110
00111         // Here the xml that will be passed to the
00112         // ToastNotification for the toast is retrieved
00113         XmlDocument toastXml = ToastNotificationManager::GetTemplateContent(ToastTemplateType::ToastText02);
00114
00115         winrt::hstring message(L"SSID: '" + ssid + L"'. Connecting in five seconds.");
00116
00117         // Set both lines of text
00118         XmlNodeList toastNodeList = toastXml.GetElementsByTagName(L"text");
00119         toastNodeList.Item(0).AppendChild(toastXml.CreateTextNode(L"Please turn on your hotspot now!"));
00120         toastNodeList.Item(1).AppendChild(toastXml.CreateTextNode(message));
00121
00122         // now create a xml node for the audio source
00123         IXmlNode toastNode = toastXml.SelectSingleNode(L"/toast");
00124         XmlElement audio = toastXml.CreateElement(L"audio");
00125         audio.SetAttribute(L"src", L"ms-winsoundevent:Notification.SMS");
00126
00127         ToastNotification toast(toastXml);
00128         ToastNotifier.Show(toast);
00129     }
00130 }
Generated on Fri Nov 15 2024 22:20:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ProximitySensorBackgroundTask Member List

This is the complete list of members for ProximitySensorBackgroundTask, including all inherited members.
OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) | ProximitySensorBackgroundTask | [inline, private]
Run(IBackgroundTaskInstance taskInstance) | ProximitySensorBackgroundTask | [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OCR/cpp/pch.h Source File

  • OCR
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Transliteration Member List

This is the complete list of members for Scenario3_Transliteration, including all inherited members.
Go_Click(object sender, RoutedEventArgs e) | Scenario3_Transliteration | [inline]
rootPage | Scenario3_Transliteration | [private]
Scenario3_Transliteration() | Scenario3_Transliteration | [inline]
Generated on Fri Nov 15 2024 22:23:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AudioCategory/cs/AudioCategory/Scenario5.xaml.cs Source File

  • AudioCategory
  • cs
  • AudioCategory

Scenario5.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016 using Windows.UI.Xaml.Media;
00017
00018 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00019
00020 namespace PlaybackManager
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class Scenario5 : Page
00026     {
00027         public Scenario5()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         private void Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00033         {
00034             Playback.SetAudioCategory(AudioCategory.Communications);
00035             Playback.SelectFile();
00036         }
00037     }
00038 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/App.cpp Source File

  • Simple3DGameDX
  • cpp

App.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "App.h"
00014
00015 using namespace concurrency;
00016 using namespace DirectX;
00017 using namespace Windows::ApplicationModel;
00018 using namespace Windows::ApplicationModel::Activation;
00019 using namespace Windows::ApplicationModel::Core;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::UI::Core;
00023 using namespace Windows::UI::Input;
00024 using namespace Windows::UI::ViewManagement;
00025 using namespace Simple3DGameDX;
00026 using namespace GameControl;
00027
00028 //--------------------------------------------------------------------------------------
00029
00030 // The main function is only used to initialize our IFrameworkView class.
00031 [Platform::MTAThread]
00032 int main(Platform::Array<Platform::String^>^)
00033 {
00034     auto directXApplicationSource = ref new DirectXApplicationSource();
00035     CoreApplication::Run(directXApplicationSource);
00036     return 0;
00037 }
00038
00039 //--------------------------------------------------------------------------------------
00040
00041 IFrameworkView^ DirectXApplicationSource::CreateView()
00042 {
00043     return ref new App();
00044 }
00045
00046 //--------------------------------------------------------------------------------------
00047
00048 App::App()
00049 {
00050 }
00051
00052 //--------------------------------------------------------------------------------------
00053
00054 void App::Initialize(
00055     CoreApplicationView^ applicationView
00056     )
00057 {
00058     applicationView->Activated +=
00059         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated);
00060
00061     CoreApplication::Suspending +=
00062         ref new EventHandler<SuspendingEventArgs^>(this, &App::OnSuspending);
00063
00064     CoreApplication::Resuming +=
00065         ref new EventHandler<Platform::Object^>(this, &App::OnResuming);
00066
00067     // At this point we have access to the device.
00068     // We can create the device-dependent resources.
00069     m_deviceResources = std::make_shared<DX::DeviceResources>();
00070 }
00071
00072 //--------------------------------------------------------------------------------------
00073
00074 void App::SetWindow(
00075     CoreWindow^ window
00076     )
00077 {
00078     window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
00079
00080     PointerVisualizationSettings^ visualizationSettings = PointerVisualizationSettings::GetForCurrentView();
00081     visualizationSettings->IsContactFeedbackEnabled = false;
00082     visualizationSettings->IsBarrelButtonFeedbackEnabled = false;
00083
00084     m_deviceResources->SetWindow(window);
00085
00086     window->Activated +=
00087         ref new TypedEventHandler<CoreWindow^, WindowActivatedEventArgs^>(this, &App::OnWindowActivationChanged);
00088
00089     window->SizeChanged +=
00090         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &App::OnWindowSizeChanged);
00091
00092     window->Closed +=
00093         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::OnWindowClosed);
00094
00095     window->VisibilityChanged +=
00096         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &App::OnVisibilityChanged);
00097
00098     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00099
00100     currentDisplayInformation->DpiChanged +=
00101         ref new TypedEventHandler<DisplayInformation^, Platform::Object^>(this, &App::OnDpiChanged);
00102
00103     currentDisplayInformation->OrientationChanged +=
00104         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnOrientationChanged);
00105
00106     currentDisplayInformation->StereoEnabledChanged +=
00107         ref new TypedEventHandler<DisplayInformation^, Platform::Object^>(this, &App::OnStereoEnabledChanged);
00108
00109     DisplayInformation::DisplayContentsInvalidated +=
00110         ref new TypedEventHandler<DisplayInformation^, Platform::Object^>(this, &App::OnDisplayContentsInvalidated);
00111 }
00112
00113 //--------------------------------------------------------------------------------------
00114
00115 void App::Load(
00116     Platform::String^ /* entryPoint */
00117     )
00118 {
00119     if (!m_main)
00120     {
00121         m_main = std::unique_ptr<GameMain>(new GameMain(m_deviceResources));
00122     }
00123 }
00124
00125 //--------------------------------------------------------------------------------------
00126
00127 void App::Run()
00128 {
00129     m_main->Run();
00130 }
00131
00132 //--------------------------------------------------------------------------------------
00133
00134 void App::Uninitialize()
00135 {
00136 }
00137
00138 //----------------------------------------------------------------------
00139
00140 void App::OnStereoEnabledChanged(DisplayInformation^ /* sender */, Platform::Object^ /* args */)
00141 {
00142     m_deviceResources->UpdateStereoState();
00143     m_main->CreateWindowSizeDependentResources();
00144 }
00145
00146 //--------------------------------------------------------------------------------------
00147
00148 void App::OnWindowSizeChanged(
00149     CoreWindow^ window,
00150     WindowSizeChangedEventArgs^  args
00151     )
00152 {
00153     m_deviceResources->SetLogicalSize(args->Size);
00154     m_main->CreateWindowSizeDependentResources();
00155 }
00156
00157 //--------------------------------------------------------------------------------------
00158
00159 void App::OnWindowClosed(
00160     CoreWindow^ /* sender */,
00161     CoreWindowEventArgs^ /* args */
00162     )
00163 {
00164     m_main->Close();
00165 }
00166
00167 //--------------------------------------------------------------------------------------
00168
00169 void App::OnDpiChanged(DisplayInformation^ sender, Platform::Object^ /* args */)
00170 {
00171     m_deviceResources->SetDpi(sender->LogicalDpi);
00172     m_main->CreateWindowSizeDependentResources();
00173 }
00174
00175 //--------------------------------------------------------------------------------------
00176
00177 void App::OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args)
00178 {
00179     m_deviceResources->SetCurrentOrientation(sender->CurrentOrientation);
00180     m_main->CreateWindowSizeDependentResources();
00181 }
00182 //--------------------------------------------------------------------------------------
00183
00184 void App::OnDisplayContentsInvalidated(DisplayInformation^ /* sender */, Platform::Object^ /* args */)
00185 {
00186     m_deviceResources->ValidateDevice();
00187 }
00188
00189 //--------------------------------------------------------------------------------------
00190
00191 void App::OnActivated(
00192     CoreApplicationView^ /* applicationView */,
00193     IActivatedEventArgs^ /* args */
00194     )
00195 {
00196     CoreWindow::GetForCurrentThread()->Activate();
00197 }
00198
00199 //--------------------------------------------------------------------------------------
00200
00201 void App::OnVisibilityChanged(
00202     CoreWindow^ /* sender */,
00203     VisibilityChangedEventArgs^ args
00204     )
00205 {
00206     m_main->Visibility(args->Visible);
00207 }
00208
00209 //--------------------------------------------------------------------------------------
00210
00211 void App::OnWindowActivationChanged(
00212     Windows::UI::Core::CoreWindow^ /* sender */,
00213     Windows::UI::Core::WindowActivatedEventArgs^ args
00214     )
00215 {
00216     m_main->WindowActivationChanged(args->WindowActivationState);
00217 }
00218
00219 //--------------------------------------------------------------------------------------
00220
00221 void App::OnSuspending(
00222     Platform::Object^ /* sender */,
00223     SuspendingEventArgs^ args
00224     )
00225 {
00226     // Save app state asynchronously after requesting a deferral. Holding a deferral
00227     // indicates that the application is busy performing suspending operations. Be
00228     // aware that a deferral may not be held indefinitely. After about five seconds,
00229     // the app will be forced to exit.
00230     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
00231
00232     create_task([this, deferral]()
00233     {
00234         m_deviceResources->Trim();
00235
00236         m_main->Suspend();
00237
00238         deferral->Complete();
00239     });
00240 }
00241
00242 //--------------------------------------------------------------------------------------
00243
00244 void App::OnResuming(
00245     Platform::Object^ /* sender */,
00246     Platform::Object^ /* args */
00247     )
00248 {
00249     // Restore any data or state that was unloaded on suspend. By default, data
00250     // and state are persisted when resuming from suspend. Note that this event
00251     // does not occur if the app was previously terminated.
00252     m_main->Resume();
00253 }
00254
Generated on Fri Nov 15 2024 22:18:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MediaSegment Member List

This is the complete list of members for MediaSegment, including all inherited members.
d | MediaSegment | [private]
Duration | MediaSegment | [private]
MediaSegment() | MediaSegment | [inline, private]
Number | MediaSegment | [private]
s | MediaSegment | [private]
SegmentUrl | MediaSegment | [private]
t | MediaSegment | [private]
Timestamp | MediaSegment | [private]
url | MediaSegment | [private]
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothLE/cppwinrt/Project.idl Source File

  • BluetoothLE
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_Discovery : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_Discovery();
00018
00019         Windows.Foundation.Collections.IObservableVector<Object> KnownDevices{ get; };
00020
00021         Windows.UI.Xaml.Controls.ListView ResultsListView{ get; };
00022         void EnumerateButton_Click();
00023         void PairButton_Click();
00024         Boolean Not(Boolean value);
00025     }
00026
00027     [default_interface]
00028     runtimeclass Scenario2_Client : Windows.UI.Xaml.Controls.Page
00029     {
00030         Scenario2_Client();
00031
00032         void ConnectButton_Click();
00033         void ServiceList_SelectionChanged();
00034         void CharacteristicList_SelectionChanged();
00035         void CharacteristicReadButton_Click();
00036         void CharacteristicWriteButton_Click();
00037         void CharacteristicWriteButtonInt_Click();
00038         void ValueChangedSubscribeToggle_Click();
00039     }
00040
00041     [default_interface]
00042     runtimeclass Scenario3_ServerForeground : Windows.UI.Xaml.Controls.Page
00043     {
00044         Scenario3_ServerForeground();
00045
00046         void PublishButton_ClickAsync();
00047     }
00048
00049     /// <summary>
00050     ///     Display class used to represent a BluetoothLEDevice in the Device list
00051     /// </summary>
00052     runtimeclass BluetoothLEDeviceDisplay : Windows.UI.Xaml.Data.INotifyPropertyChanged
00053     {
00054         Windows.Devices.Enumeration.DeviceInformation DeviceInformation{ get; };
00055
00056         String Id{ get; };
00057         String Name{ get; };
00058         Boolean IsPaired{ get; };
00059         Boolean IsConnected{ get; };
00060         Boolean IsConnectable{ get; };
00061
00062         IMapView<String, Object> Properties{ get; };
00063
00064         Windows.UI.Xaml.Media.Imaging.BitmapImage GlyphBitmapImage{ get; };
00065
00066         void Update(Windows.Devices.Enumeration.DeviceInformationUpdate deviceInfoUpdate);
00067     };
00068 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProximitySensor/cpp/Scenario2_Polling.xaml.h Source File

  • ProximitySensor
  • cpp

Scenario2_Polling.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_Polling.xaml.h
00014 // Declaration of the Scenario2_Polling class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario2_Polling.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario2_Polling sealed
00030     {
00031     public:
00032         Scenario2_Polling();
00033
00034     private:
00035         SDKTemplate::MainPage^ rootPage;
00036         Windows::UI::Core::CoreDispatcher^ dispatcher;
00037         Windows::Devices::Enumeration::DeviceWatcher^ watcher;
00038         Windows::Devices::Sensors::ProximitySensor^ sensor;
00039
00040         void OnProximitySensorAdded(Windows::Devices::Enumeration::DeviceWatcher^ sender, Windows::Devices::Enumeration::DeviceInformation^ device);
00041         void ScenarioGetData(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042     };
00043 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cpp/Scenario4_ChangeAdminKey.xaml.h Source File

  • SmartCard
  • cpp

Scenario4_ChangeAdminKey.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario4_ChangeAdminKey.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario4_ChangeAdminKey sealed
00012     {
00013     public:
00014         Scenario4_ChangeAdminKey();
00015     private:
00016         void ChangeAdminKey_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00017     };
00018 }
Generated on Fri Nov 15 2024 22:21:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Json/cppwinrt/Project.idl Source File

  • Json
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_ParseAndStringify : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_ParseAndStringify();
00018     }
00019
00020     [Windows.UI.Xaml.Data.Bindable]
00021     runtimeclass School
00022     {
00023         School();
00024         School(Windows.Data.Json.JsonObject jsonObject);
00025
00026         Windows.Data.Json.JsonObject ToJsonObject();
00027
00028         String Id;
00029         String Name;
00030         String Type;
00031     }
00032
00033     [Windows.UI.Xaml.Data.Bindable]
00034     runtimeclass User
00035     {
00036         User();
00037         User(String jsonString);
00038
00039         String Id;
00040         String Phone;
00041         String Name;
00042         Windows.Foundation.Collections.IObservableVector<School> Education{ get; };
00043         Double Timezone;
00044         Boolean Verified;
00045
00046         String Stringify();
00047     }
00048 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RadioManager/cppwinrt/RadioModel.cpp Source File

  • RadioManager
  • cppwinrt

RadioModel.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "RadioModel.h"
00015 #include "RadioModel.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Devices::Radios;
00019 using namespace winrt::Windows::Foundation::Collections;
00020 using namespace winrt::Windows::UI::Core;
00021 using namespace winrt::Windows::UI::Xaml::Data;
00022 using namespace winrt::SDKTemplate;
00023
00024 namespace winrt::SDKTemplate::implementation
00025 {
00026     RadioModel::RadioModel(Radio const& radio, CoreDispatcher const& dispatcher) :
00027         radio(radio), dispatcher(dispatcher),
00028         // Controlling the mobile broadband radio requires the cellularDeviceControl restricted capability, which we do not have.
00029         isEnabled(radio.Kind() != RadioKind::MobileBroadband)
00030     {
00031         radio.StateChanged({ get_weak(), &RadioModel::Radio_StateChanged });
00032     }
00033
00034     fire_and_forget RadioModel::Radio_StateChanged(Radio const&, IInspectable const&)
00035     {
00036         // The Radio StateChanged event doesn't run from the UI thread, so we must use the dispatcher
00037         // to run NotifyPropertyChanged
00038         auto lifetime = get_strong();
00039         co_await resume_foreground(dispatcher);
00040         NotifyPropertyChanged(L"IsRadioOn");
00041     }
00042
00043     void RadioModel::NotifyPropertyChanged(hstring const& propertyName)
00044     {
00045         propertyChanged(*this, PropertyChangedEventArgs(propertyName));
00046     }
00047
00048     void RadioModel::SetEnabled(bool value)
00049     {
00050         isEnabled = value;
00051         NotifyPropertyChanged(L"IsEnabled");
00052     }
00053
00054     fire_and_forget RadioModel::SetRadioState(bool value)
00055     {
00056         if (value != IsRadioOn())
00057         {
00058             auto lifetime = get_strong();
00059             RadioState newState = value ? RadioState::On : RadioState::Off;
00060             SetEnabled(false);
00061             co_await radio.SetStateAsync(newState);
00062             SetEnabled(true);
00063             NotifyPropertyChanged(L"IsRadioOn");
00064         }
00065     }
00066
00067 }
Generated on Fri Nov 15 2024 22:21:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cpp/pch.cpp Source File

  • BasicInput
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlLite/cpp/pch.h Source File

  • XmlLite
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009 #include <shcore.h>
00010 #include <wrl.h>
00011 #include <xmllite.h>
00012
00013 #define ChkHr(stmt) do { hr = stmt; if (FAILED(hr)) return hr; } while(0)
00014
00015 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ApduResponse Member List

This is the complete list of members for ApduResponse, including all inherited members.
ApduResponse() | ApduResponse | [inline]
ExtractResponse(IBuffer response) | ApduResponse | [inline, virtual]
ExtractTlvDataObject(byte[] referenceTag) | ApduResponse | [inline]
ResponseData | ApduResponse |
Succeeded | ApduResponse |
SW | ApduResponse |
SW1 | ApduResponse |
SW2 | ApduResponse |
SWTranslation | ApduResponse |
TAG_COMPREHENSION_MASK | ApduResponse |
TAG_LENGTH_MULTI_BYTE_MASK | ApduResponse |
TAG_MULTI_BYTE_MASK | ApduResponse |
ToString() | ApduResponse | [inline]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-SPI/cppwinrt/SampleConfiguration.cpp Source File

  • IoT-SPI
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation::Collections;
00019 using namespace winrt::SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"SPI C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Read data from SPI device", xaml_typename<SDKTemplate::Scenario1_ReadData>() },
00029 });
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/Common/CameraResources.h Source File

  • HolographicTagAlong
  • cpp
  • Common

CameraResources.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace DX
00015 {
00016     class DeviceResources;
00017
00018     // Constant buffer used to send the view-projection matrices to the shader pipeline.
00019     struct ViewProjectionConstantBuffer
00020     {
00021         DirectX::XMFLOAT4X4 viewProjection[2];
00022     };
00023
00024     // Assert that the constant buffer remains 16-byte aligned (best practice).
00025     static_assert((sizeof(ViewProjectionConstantBuffer) % (sizeof(float) * 4)) == 0, "ViewProjection constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00026
00027     // Manages DirectX device resources that are specific to a holographic camera, such as the
00028     // back buffer, ViewProjection constant buffer, and viewport.
00029     class CameraResources
00030     {
00031     public:
00032         CameraResources(Windows::Graphics::Holographic::HolographicCamera^ holographicCamera);
00033
00034         void CreateResourcesForBackBuffer(
00035             DX::DeviceResources* pDeviceResources,
00036             Windows::Graphics::Holographic::HolographicCameraRenderingParameters^ cameraParameters
00037             );
00038         void ReleaseResourcesForBackBuffer(
00039             DX::DeviceResources* pDeviceResources
00040             );
00041
00042         void UpdateViewProjectionBuffer(
00043             std::shared_ptr<DX::DeviceResources> deviceResources,
00044             Windows::Graphics::Holographic::HolographicCameraPose^ cameraPose,
00045             Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem);
00046         bool AttachViewProjectionBuffer(
00047             std::shared_ptr<DX::DeviceResources> deviceResources);
00048
00049         // Direct3D device resources.
00050         ID3D11RenderTargetView* GetBackBufferRenderTargetView()     const { return m_d3dRenderTargetView.Get();     }
00051         ID3D11DepthStencilView* GetDepthStencilView()               const { return m_d3dDepthStencilView.Get();     }
00052         ID3D11Texture2D*        GetBackBufferTexture2D()            const { return m_d3dBackBuffer.Get();           }
00053         D3D11_VIEWPORT          GetViewport()                       const { return m_d3dViewport;                   }
00054         DXGI_FORMAT             GetBackBufferDXGIFormat()           const { return m_dxgiFormat;                    }
00055
00056         // Render target properties.
00057         Windows::Foundation::Size GetRenderTargetSize()             const { return m_d3dRenderTargetSize;           }
00058         bool                    IsRenderingStereoscopic()           const { return m_isStereo;                      }
00059
00060         // The holographic camera these resources are for.
00061         Windows::Graphics::Holographic::HolographicCamera^ GetHolographicCamera() const { return m_holographicCamera; }
00062
00063     private:
00064         // Direct3D rendering objects. Required for 3D.
00065         Microsoft::WRL::ComPtr<ID3D11RenderTargetView>      m_d3dRenderTargetView;
00066         Microsoft::WRL::ComPtr<ID3D11DepthStencilView>      m_d3dDepthStencilView;
00067         Microsoft::WRL::ComPtr<ID3D11Texture2D>             m_d3dBackBuffer;
00068
00069         // Device resource to store view and projection matrices.
00070         Microsoft::WRL::ComPtr<ID3D11Buffer>                m_viewProjectionConstantBuffer;
00071
00072         // Direct3D rendering properties.
00073         DXGI_FORMAT                                         m_dxgiFormat;
00074         Windows::Foundation::Size                           m_d3dRenderTargetSize;
00075         D3D11_VIEWPORT                                      m_d3dViewport;
00076
00077         // Indicates whether the camera supports stereoscopic rendering.
00078         bool                                                m_isStereo = false;
00079
00080         // Indicates whether this camera has a pending frame.
00081         bool                                                m_framePending = false;
00082
00083         // Pointer to the holographic camera these resources are for.
00084         Windows::Graphics::Holographic::HolographicCamera^  m_holographicCamera = nullptr;
00085     };
00086 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LightSensor/cpp/Scenario2_Polling.xaml.h Source File

  • LightSensor
  • cpp

Scenario2_Polling.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_Polling.xaml.h
00014 // Declaration of the Scenario2_Polling class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario2_Polling.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario2_Polling sealed
00030     {
00031     public:
00032         Scenario2_Polling();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038     private:
00039         SDKTemplate::MainPage^ rootPage;
00040         Windows::UI::Core::CoreDispatcher^ dispatcher;
00041         Windows::Devices::Sensors::LightSensor^ sensor;
00042         Windows::Foundation::EventRegistrationToken visibilityToken;
00043         uint32 desiredReportInterval;
00044         Windows::UI::Xaml::DispatcherTimer^ dispatcherTimer;
00045
00046         void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00047         void DisplayCurrentReading(Platform::Object^ sender, Platform::Object^ e);
00048         void ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049         void ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050     };
00051 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLInProcessWinRTComponent/cpp/cs/Scenario2_CustomException.xaml.cs Source File

  • WRLInProcessWinRTComponent
  • cpp
  • cs

Scenario2_CustomException.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using Microsoft.SDKSamples.Kitchen;
00008
00009 using Windows.UI.Xaml;
00010 using Windows.UI.Xaml.Controls;
00011 using Windows.UI.Xaml.Navigation;
00012 using SDKTemplate;
00013 using System;
00014
00015 namespace WRLInProcessWinRTComponent
00016 {
00017     public sealed partial class CustomException : Page
00018     {
00019         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00020         // as NotifyUser()
00021         MainPage rootPage = MainPage.Current;
00022
00023         public CustomException()
00024         {
00025             this.InitializeComponent();
00026         }
00027
00028         /// <summary>
00029         /// Invoked when this page is about to be displayed in a Frame.
00030         /// </summary>
00031         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00032         /// property is typically used to configure the page.</param>
00033         protected override void OnNavigatedTo(NavigationEventArgs e)
00034         {
00035         }
00036
00037         /// <summary>
00038         /// Handle a Windows Runtime error originated by the Oven Windows Runtime component.
00039         /// </summary>
00040         /// <param name="sender">Contains information about the button that fired the event.</param>
00041         /// <param name="e">Contains state information and event data associated with a routed event.</param>
00042         private void Start_Click(object sender, RoutedEventArgs e)
00043         {
00044             Oven myOven = new Oven();
00045
00046             try
00047             {
00048                 // Intentionally pass a bad parameter
00049                 myOven.ConfigurePreheatTemperature((OvenTemperature)5);
00050             }
00051             catch (System.ArgumentException)
00052             {
00053                 CustomExceptionOutput.Text += "Exception caught. Please attach a debugger and enable first chance native exceptions to view exception details.\n";
00054             }
00055         }
00056     }
00057 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cpp/ChallengeResponseAlgorithm.h Source File

  • SmartCard
  • cpp

ChallengeResponseAlgorithm.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // CallengeResponseAlgorithm.h
00013 // Declaration of the CallengeResponseAlgorithm class
00014 //
00015
00016 #pragma once
00017 using namespace Windows::Storage::Streams;
00018
00019 namespace SDKTemplate
00020 {
00021     ref class ChallengeResponseAlgorithm sealed
00022     {
00023     public:
00024         static IBuffer^ CalculateResponse(IBuffer^ challenge, IBuffer^ adminkey);
00025     };
00026 }
Generated on Fri Nov 15 2024 22:21:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SocketActivityStreamSocket/cs/SocketActivityBackgroundTask/SocketActivityTask.cs Source File

  • SocketActivityStreamSocket
  • cs
  • SocketActivityBackgroundTask

SocketActivityTask.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using System;
00012 using System.Collections.Generic;
00013 using System.Linq;
00014 using System.Text;
00015 using System.Threading.Tasks;
00016 using Windows.ApplicationModel.Background;
00017 using Windows.Foundation;
00018 using Windows.Networking;
00019 using Windows.Networking.Sockets;
00020 using Windows.Storage;
00021 using Windows.Storage.Streams;
00022 using Windows.UI.Notifications;
00023
00024 namespace SocketActivityBackgroundTask
00025 {
00026     public sealed class SocketActivityTask : Windows.ApplicationModel.Background.IBackgroundTask
00027     {
00028         private const string socketId = "SampleSocket";
00029
00030         public async void Run(IBackgroundTaskInstance taskInstance)
00031         {
00032             var deferral = taskInstance.GetDeferral();
00033             try
00034             {
00035                 var details = taskInstance.TriggerDetails as SocketActivityTriggerDetails;
00036                 var socketInformation = details.SocketInformation;
00037                 switch (details.Reason)
00038                 {
00039                     case SocketActivityTriggerReason.SocketActivity:
00040                         var socket = socketInformation.StreamSocket;
00041                         DataReader reader = new DataReader(socket.InputStream);
00042                         reader.InputStreamOptions = InputStreamOptions.Partial;
00043                         await reader.LoadAsync(250);
00044                         var dataString = reader.ReadString(reader.UnconsumedBufferLength);
00045                         ShowToast(dataString);
00046                         socket.TransferOwnership(socketInformation.Id);
00047                         break;
00048                     case SocketActivityTriggerReason.KeepAliveTimerExpired:
00049                         socket = socketInformation.StreamSocket;
00050                         DataWriter writer = new DataWriter(socket.OutputStream);
00051                         writer.WriteBytes(Encoding.UTF8.GetBytes("Keep alive"));
00052                         await writer.StoreAsync();
00053                         writer.DetachStream();
00054                         writer.Dispose();
00055                         socket.TransferOwnership(socketInformation.Id);
00056                         break;
00057                     case SocketActivityTriggerReason.SocketClosed:
00058                         socket = new StreamSocket();
00059                         socket.EnableTransferOwnership(taskInstance.Task.TaskId, SocketActivityConnectedStandbyAction.Wake);
00060                         if (ApplicationData.Current.LocalSettings.Values["hostname"] == null)
00061                         {
00062                             break;
00063                         }
00064                         var hostname = (String)ApplicationData.Current.LocalSettings.Values["hostname"];
00065                         var port = (String)ApplicationData.Current.LocalSettings.Values["port"];
00066                         await socket.ConnectAsync(new HostName(hostname), port);
00067                         socket.TransferOwnership(socketId);
00068                         break;
00069                     default:
00070                         break;
00071                 }
00072                 deferral.Complete();
00073             }
00074             catch (Exception exception)
00075             {
00076                 ShowToast(exception.Message);
00077                 deferral.Complete();
00078             }
00079         }
00080
00081         public void ShowToast(string text)
00082         {
00083             var toastNotifier = ToastNotificationManager.CreateToastNotifier();
00084             var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
00085             var textNodes = toastXml.GetElementsByTagName("text");
00086             textNodes.First().AppendChild(toastXml.CreateTextNode(text));
00087             var toastNotification = new ToastNotification(toastXml);
00088             toastNotifier.Show(new ToastNotification(toastXml));
00089         }
00090
00091     }
00092 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cs/EdgeTappedListView.cs Source File

  • XamlListView
  • cs

EdgeTappedListView.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using System;
00012 using Windows.UI.Input;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Input;
00016 using Windows.UI.Xaml.Media;
00017 using Windows.UI.Xaml.Shapes;
00018
00019 namespace SDKTemplate
00020 {
00021     public class ListViewEdgeTappedEventArgs : EventArgs
00022     {
00023         private ListViewItem listViewItem;
00024         public ListViewItem ListViewItem { get { return listViewItem; } }
00025         public ListViewEdgeTappedEventArgs(ListViewItem listViewItem)
00026         {
00027             this.listViewItem = listViewItem;
00028         }
00029     }
00030     public class EdgeTappedListView : ListView
00031     {
00032         private const double HIT_TARGET = 32;
00033         private const double VISUAL_INDICATOR_WIDTH = 12;
00034         private const string VISUAL_INDICATOR_NAME = "VisualIndicator";
00035         private ListViewItem listViewItemHighlighted = null;
00036         private Rectangle visualIndicator;
00037
00038         public delegate void ListViewEdgeTappedEventHandler(ListView sender, ListViewEdgeTappedEventArgs e);
00039         public event ListViewEdgeTappedEventHandler ItemLeftEdgeTapped;
00040         public Brush LeftEdgeBrush { get; set; }
00041         public bool IsItemLeftEdgeTapEnabled { get; set; }
00042
00043         public EdgeTappedListView()
00044         {
00045             this.ContainerContentChanging += OnContainerContentChanging;
00046             LeftEdgeBrush = Application.Current.Resources["SystemControlHighlightAltListAccentLowBrush"] as Brush;
00047         }
00048
00049         private void OnContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
00050         {
00051             if (args.InRecycleQueue)
00052             {
00053                 ListViewItem lvi = (args.ItemContainer as ListViewItem);
00054                 if (lvi != null)
00055                 {
00056                     UIElement element = VisualTreeHelper.GetChild(lvi, 0) as UIElement;
00057                     if (element != null)
00058                     {
00059                         element.PointerPressed -= OnPointerPressed;
00060                         element.PointerReleased -= OnPointerReleased;
00061                         element.PointerCaptureLost -= OnPointerCaptureLost;
00062                         element.PointerExited -= OnPointerExited;
00063                     }
00064                 }
00065             }
00066             else if (args.Phase == 0)
00067             {
00068                 ListViewItem lvi = (args.ItemContainer as ListViewItem);
00069                 if (null != lvi)
00070                 {
00071                     UIElement element = VisualTreeHelper.GetChild(lvi, 0) as UIElement;
00072                     if (null != element)
00073                     {
00074                         element.PointerPressed += OnPointerPressed;
00075                         element.PointerReleased += OnPointerReleased;
00076                         element.PointerCaptureLost += OnPointerCaptureLost;
00077                         element.PointerExited += OnPointerExited;
00078                     }
00079                 }
00080             }
00081         }
00082         void OnPointerPressed(object sender, PointerRoutedEventArgs e)
00083         {
00084             if (IsItemLeftEdgeTapEnabled)
00085             {
00086                 if (e.Pointer.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Touch)
00087                 {
00088                     UIElement element = (sender as UIElement);
00089                     if (null != element)
00090                     {
00091                         PointerPoint pointerPoint = e.GetCurrentPoint(element);
00092                         if (pointerPoint.Position.X <= HIT_TARGET)
00093                         {
00094                             listViewItemHighlighted = VisualTreeHelper.GetParent(element) as ListViewItem;
00095                             ShowVisual();
00096                         }
00097                     }
00098                 }
00099             }
00100         }
00101         void OnPointerReleased(object sender, PointerRoutedEventArgs e)
00102         {
00103             if (listViewItemHighlighted != null)
00104             {
00105                 ClearVisual();
00106             }
00107         }
00108         private void OnPointerCaptureLost(object sender, PointerRoutedEventArgs e)
00109         {
00110             ClearVisual();
00111         }
00112         void OnPointerExited(object sender, PointerRoutedEventArgs e)
00113         {
00114             ClearVisual();
00115         }
00116         private void ShowVisual()
00117         {
00118             if (listViewItemHighlighted != null)
00119             {
00120                 visualIndicator = listViewItemHighlighted.FindName(VISUAL_INDICATOR_NAME) as Rectangle;
00121                 if (visualIndicator == null)
00122                 {
00123                     visualIndicator = new Rectangle();
00124                     visualIndicator.Name = VISUAL_INDICATOR_NAME;
00125                     visualIndicator.Height = listViewItemHighlighted.ActualHeight;
00126                     visualIndicator.HorizontalAlignment = HorizontalAlignment.Left;
00127                     visualIndicator.Width = VISUAL_INDICATOR_WIDTH;
00128                     visualIndicator.Fill = LeftEdgeBrush;
00129                     visualIndicator.Margin = new Thickness(-(listViewItemHighlighted.Padding.Left), 0, 0, 0);
00130                     Panel panel = listViewItemHighlighted.ContentTemplateRoot as Panel;
00131                     if (panel != null)
00132                     {
00133                         var grid = panel as Grid;
00134                         if (grid != null)
00135                         {
00136                             visualIndicator.SetValue(Grid.RowSpanProperty, grid.RowDefinitions.Count);
00137                         }
00138                         panel.Children.Add(visualIndicator);
00139                     }
00140                 }
00141                 else
00142                 {
00143                     visualIndicator.Opacity = 1;
00144                 }
00145             }
00146         }
00147         private void ClearVisual()
00148         {
00149             if (listViewItemHighlighted != null)
00150             {
00151                 if (visualIndicator != null)
00152                 {
00153                     visualIndicator.Opacity = 0;
00154                     if (this.ItemLeftEdgeTapped != null)
00155                     {
00156                         ItemLeftEdgeTapped(this, new ListViewEdgeTappedEventArgs(listViewItemHighlighted));
00157                     }
00158                 }
00159                 listViewItemHighlighted = null;
00160             }
00161         }
00162     }
00163 }
Generated on Fri Nov 15 2024 22:22:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceListEntry Member List

This is the complete list of members for DeviceListEntry, including all inherited members.
device | DeviceListEntry | [private]
DeviceInformation | DeviceListEntry |
DeviceListEntry(Windows.Devices.Enumeration.DeviceInformation deviceInformation, String deviceSelector) | DeviceListEntry | [inline]
deviceSelector | DeviceListEntry | [private]
DeviceSelector | DeviceListEntry |
InstanceId | DeviceListEntry |
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ToneSampleGenerator Member List

This is the complete list of members for ToneSampleGenerator, including all inherited members.
FillSampleBuffer(array_view< uint8_t > buffer) | ToneSampleGenerator |
Flush() | ToneSampleGenerator | [inline]
GenerateSampleBuffer(double Frequency, UINT32 FramesPerPeriod, WAVEFORMATEX *wfx) | ToneSampleGenerator |
GetBufferLength() noexcept | ToneSampleGenerator | [inline]
IsEOF() noexcept | ToneSampleGenerator | [inline]
m_sampleQueue | ToneSampleGenerator | [private]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cs/BackgroundTransfer/Scenario5_RandomAccess.xaml.cs Source File

  • BackgroundTransfer
  • cs
  • BackgroundTransfer

Scenario5_RandomAccess.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading;
00015 using System.Threading.Tasks;
00016 using Windows.Foundation;
00017 using Windows.Networking.BackgroundTransfer;
00018 using Windows.Storage;
00019 using Windows.Storage.Streams;
00020 using Windows.UI.Core;
00021 using Windows.UI.Xaml;
00022 using Windows.UI.Xaml.Controls;
00023 using Windows.UI.Xaml.Navigation;
00024 using Windows.Web;
00025
00026 namespace SDKTemplate
00027 {
00028     public sealed partial class Scenario5_RandomAccess : Page
00029     {
00030         private MainPage rootPage = MainPage.Current;
00031
00032         // Constants.
00033         private const uint BytesPerMegaByte = 1000000;
00034
00035         // Scenario instance state.
00036         private DownloadOperation download = null;
00037         private IRandomAccessStreamWithContentType randomAccessStream = null;
00038         private Task<IBuffer> readOperation = null;
00039         private CancellationTokenSource readCancellationTokenSource = new CancellationTokenSource();
00040
00041         public Scenario5_RandomAccess()
00042         {
00043             InitializeComponent();
00044         }
00045
00046         protected async override void OnNavigatedTo(NavigationEventArgs e)
00047         {
00048             // An application must enumerate downloads when it gets started to prevent stale downloads/uploads.
00049             // Typically this can be done in the App class by overriding OnLaunched() and checking for
00050             // "args.Kind == ActivationKind.Launch" to detect an actual app launch.
00051             // We do it here in the sample to keep the sample code consolidated.
00052             // Note that for this specific scenario we are not interested in downloads from previous instances, so
00053             // we just enumerate all downloads from previous instances and cancel them immediately.
00054             await CancelActiveDownloadsAsync();
00055         }
00056
00057         protected override void OnNavigatedFrom(NavigationEventArgs e)
00058         {
00059             // Cancel any outstanding reads.
00060             readCancellationTokenSource.Cancel();
00061         }
00062
00063         private async Task CancelActiveDownloadsAsync()
00064         {
00065             IReadOnlyList<DownloadOperation> downloads;
00066             try
00067             {
00068                 downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
00069             }
00070             catch (Exception ex) when (IsWebException("Discovery error", ex))
00071             {
00072                 // Don't worry if the old downloads encountered web exceptions.
00073                 return;
00074             }
00075
00076             // If previous sample instances/scenarios started transfers that haven't completed yet, cancel them now
00077             // so that we can start this scenario cleanly.
00078             if (downloads.Count > 0)
00079             {
00080                 using (CancellationTokenSource canceledToken = new CancellationTokenSource())
00081                 {
00082                     canceledToken.Cancel();
00083
00084                     Task[] tasks = new Task[downloads.Count];
00085                     for (int i = 0; i < downloads.Count; i++)
00086                     {
00087                         tasks[i] = downloads[i].AttachAsync().AsTask(canceledToken.Token);
00088                     }
00089
00090                     try
00091                     {
00092                         await Task.WhenAll(tasks);
00093                     }
00094                     catch (TaskCanceledException)
00095                     {
00096                     }
00097                 }
00098                 rootPage.NotifyUser($"Canceled {downloads.Count} downloads.", NotifyType.StatusMessage);
00099             }
00100         }
00101
00102         private void PauseDownload_Click(object sender, RoutedEventArgs e)
00103         {
00104             if (download != null)
00105             {
00106                 download.Pause();
00107                 pauseDownloadButton.IsEnabled = false;
00108                 resumeDownloadButton.IsEnabled = true;
00109             }
00110         }
00111
00112         private void ResumeDownload_Click(object sender, RoutedEventArgs e)
00113         {
00114             if (download != null)
00115             {
00116                 download.Resume();
00117                 pauseDownloadButton.IsEnabled = true;
00118                 resumeDownloadButton.IsEnabled = false;
00119             }
00120         }
00121
00122         private void SeekDownload_Click(object sender, RoutedEventArgs e)
00123         {
00124             // Cancel the ongoing read operation (if any).
00125             if (readOperation != null)
00126             {
00127                 readCancellationTokenSource.Cancel();
00128
00129                 // Re-create the CancellationTokenSource for future reads.
00130                 readCancellationTokenSource = new CancellationTokenSource();
00131             }
00132
00133             if (randomAccessStream != null)
00134             {
00135                 // Update the stream's seek position to the user-selected one.
00136                 // The new seek position will take effect on the next ReadAsync operation.
00137                 var seekPositionInMegaBytes = (ulong)seekSlider.Value;
00138                 ulong seekPositionInBytes = seekPositionInMegaBytes * BytesPerMegaByte;
00139                 randomAccessStream.Seek(seekPositionInBytes);
00140             }
00141         }
00142
00143         private static string FormatDownloadedRanges(IEnumerable<BackgroundTransferFileRange> ranges)
00144         {
00145             string result = "";
00146             foreach (BackgroundTransferFileRange range in ranges)
00147             {
00148                 if (result != "")
00149                 {
00150                     result += ", ";
00151                 }
00152
00153                 result += $"{range.Offset}-{range.Offset + range.Length - 1}";
00154             }
00155
00156             if (result == "")
00157             {
00158                 result = "None";
00159             }
00160             return result;
00161         }
00162
00163         private async void OnDownloadProgress(IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> sender, DownloadOperation progress)
00164         {
00165             // We capture a snapshot of DownloadOperation.Progress because
00166             // it is is updated in real-time while the operation is ongoing.
00167             BackgroundDownloadProgress currentProgress = progress.Progress;
00168
00169             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00170             {
00171                 // Prepare the progress message to display in the UI.
00172                 ulong percent = 100;
00173                 if (currentProgress.TotalBytesToReceive > 0)
00174                 {
00175                     percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive;
00176                 }
00177
00178                 DownloadedStatusText.Text = $"{currentProgress.Status} - {percent}% downloaded.";
00179             });
00180         }
00181
00182         private async void OnRangesDownloaded(DownloadOperation sender, BackgroundTransferRangesDownloadedEventArgs args)
00183         {
00184             // BackgroundTransfer will wait for the app's RangesDownloaded event handlers to finish executing before
00185             // triggering the next RangesDownloaded event. Any download progress made while the app's handlers are
00186             // executing get coalesced into a single RangesDownloaded event.
00187             //
00188             // When calling async APIs inside this handler, we must first take a deferral and then complete it once we
00189             // are done processing the event. Otherwise, BackgroundTransfer will assume that the handler is done executing
00190             // as soon as the synchronous portion of the handler returns, even if there are still tasks running.
00191             using (args.GetDeferral())
00192             {
00193                 // AddedRanges tells you which ranges were downloaded since the last RangesDownloaded event.
00194                 // To get the full list of downloaded ranges, use the GetDownloadedRanges method.
00195                 string message = " Newly-downloaded ranges: " + FormatDownloadedRanges(args.AddedRanges);
00196
00197                 // A download may restart if the server contents changed while the download is in progress.
00198                 if (args.WasDownloadRestarted)
00199                 {
00200                     message += " (download was restarted)";
00201                 }
00202
00203                 // Wait for the UI update to happen before completing the deferral. That way, we can be certain that
00204                 // the next RangesDownloaded event will not get triggered midway through the UI update.
00205                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00206                 {
00207                     DownloadedRangesText.Text = FormatDownloadedRanges(sender.GetDownloadedRanges());
00208                     rootPage.NotifyUser(message, NotifyType.StatusMessage);
00209                 });
00210             }
00211         }
00212
00213         private async void StartDownload_Click(object sender, RoutedEventArgs e)
00214         {
00215             // Reset the output whenever a new download attempt begins.
00216             DownloadedInfoText.Text = "";
00217             DownloadedStatusText.Text = "";
00218             DownloadedRangesText.Text = "None";
00219             PreviousReadText.Text = "";
00220             CurrentReadText.Text = "";
00221
00222             Uri source;
00223             if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out source))
00224             {
00225                 rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
00226                 return;
00227             }
00228
00229             string destination = fileNameField.Text.Trim();
00230             if (string.IsNullOrWhiteSpace(destination))
00231             {
00232                 rootPage.NotifyUser("A local file name is required.", NotifyType.ErrorMessage);
00233                 return;
00234             }
00235
00236             StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
00237             StorageFile destinationFile;
00238             try
00239             {
00240                 destinationFile = await picturesLibrary.CreateFileAsync(destination, CreationCollisionOption.GenerateUniqueName);
00241             }
00242             catch (Exception ex)
00243             {
00244                 rootPage.NotifyUser("Error while creating file: " + ex.Message, NotifyType.ErrorMessage);
00245                 return;
00246             }
00247
00248             BackgroundDownloader downloader = new BackgroundDownloader();
00249             download = downloader.CreateDownload(source, destinationFile);
00250
00251             // Apps need to set the IsRandomAccessRequired boolean property to TRUE (default is FALSE) before they
00252             // call StartAsync() on a DownloadOperation object if they want to use the random access feature. After
00253             // opting into "random access" mode, GetResultRandomAccessStreamReference() can be called.
00254             //
00255             // Setting IsRandomAccessRequired to TRUE before starting the download is necessary because the
00256             // server-side requirements for Random Access functionality are stricter than for regular (sequential)
00257             // downloads, so BackgroundTransfer needs to know the app's intentions in advance. That way, it can fail
00258             // the transfer up front if the server does not satisfy those additional requirements (e.g., HTTP range
00259             // header support).
00260             download.IsRandomAccessRequired = true;
00261
00262             // Subscribe to RangesDownloaded notifications.
00263             download.RangesDownloaded += OnRangesDownloaded;
00264
00265             DownloadedInfoText.Text = $"Downloading to {destinationFile.Name}, {download.Guid}";
00266
00267             // Start the download and read partially-downloaded content while the transfer is still ongoing.
00268             await StartDownloadAndReadContentsAsync();
00269         }
00270
00271         private async Task StartDownloadAndReadContentsAsync()
00272         {
00273             try
00274             {
00275                 // Retrieve a random access stream from the download operation. Every OpenReadAsync() operation returns
00276                 // a new stream instance that is independent of previous ones (i.e., the seek position of one stream
00277                 // isn't affected by calls on another stream).
00278                 //
00279                 // This sample demonstrates the direct usage of a DownloadOperation's random access stream and its
00280                 // effects on the ongoing transfer. However, bear in mind that there are a variety of operations
00281                 // that can manage the stream on the app's behalf for specific scenarios. For instance, a
00282                 // DownloadOperation pointing to a video URL can be consumed by the MediaPlayer class in four easy
00283                 // steps:
00284                 //
00285                 // var randomAccessStreamReference = download.GetResultRandomAccessStreamReference();
00286                 // stream = await randomAccessStreamReference.OpenReadAsync();
00287                 // var mediaPlayer = new Windows.Media.Playback.MediaPlayer();
00288                 // mediaPlayer.Source = Windows.Media.Core.MediaSource.CreateFromStream(stream, stream.ContentType);
00289
00290                 var randomAccessStreamReference = download.GetResultRandomAccessStreamReference();
00291                 randomAccessStream = await randomAccessStreamReference.OpenReadAsync();
00292
00293                 // Start the download. If the server doesn't support random access, the download will fail
00294                 // with WebErrorStatus.InsufficientRangeSupport or WebErrorStatus.MissingContentLengthSupport.
00295                 IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> downloadOperation = download.StartAsync();
00296                 downloadOperation.Progress += OnDownloadProgress;
00297                 Task downloadTask = downloadOperation.AsTask();
00298
00299                 startDownloadButton.IsEnabled = false;
00300                 pauseDownloadButton.IsEnabled = true;
00301
00302                 // Read data while the download is still ongoing. Use a 1 MB read buffer for that purpose.
00303                 var readBuffer = new Windows.Storage.Streams.Buffer(BytesPerMegaByte);
00304                 while (!downloadTask.IsCompleted)
00305                 {
00306                     ulong readOffsetInBytes = randomAccessStream.Position;
00307
00308                     PreviousReadText.Text = CurrentReadText.Text;
00309                     CurrentReadText.Text = $"Reading from offset {readOffsetInBytes:n0}";
00310
00311                     readOperation = randomAccessStream.ReadAsync(
00312                         readBuffer,
00313                         readBuffer.Capacity,
00314                         InputStreamOptions.None).
00315                         AsTask(readCancellationTokenSource.Token);
00316
00317                     // Update the UI to show the current read's position.
00318                     currentPositionSlider.Value = readOffsetInBytes / BytesPerMegaByte;
00319
00320                     try
00321                     {
00322                         // Wait for the read to complete.
00323                         IBuffer bytesRead = await readOperation;
00324                         CurrentReadText.Text += $", completed with {bytesRead.Length:n0} bytes";
00325
00326                         // At this point, a real app would process the 'bytesRead' data to do something interesting
00327                         // with it (e.g., display video and/or play audio).
00328
00329                         if (randomAccessStream.Position >= randomAccessStream.Size)
00330                         {
00331                             // We have reached EOF. Wrap around to the beginning while we wait for the download to complete.
00332                             randomAccessStream.Seek(0);
00333                         }
00334                     }
00335                     catch (OperationCanceledException)
00336                     {
00337                         // The ongoing read was canceled by SeekDownload_Click(...) in order for a new download
00338                         // position to take effect immediately.
00339                         CurrentReadText.Text += ", cancelled.";
00340                     }
00341                 }
00342
00343                 // Wait for the download to complete.
00344                 await downloadTask;
00345
00346                 rootPage.NotifyUser("Download completed successfully", NotifyType.StatusMessage);
00347             }
00348             catch (Exception ex) when (IsWebException("Execution error", ex))
00349             {
00350                 // Abandon the operation if a web exception occurs.
00351             }
00352             finally
00353             {
00354                 download = null;
00355                 randomAccessStream = null;
00356                 readOperation = null;
00357
00358                 startDownloadButton.IsEnabled = true;
00359                 pauseDownloadButton.IsEnabled = false;
00360                 resumeDownloadButton.IsEnabled = false;
00361             }
00362         }
00363
00364         private bool IsWebException(string title, Exception ex)
00365         {
00366             WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
00367             bool result = (error != WebErrorStatus.Unknown);
00368             string message = result ? error.ToString() : ex.Message;
00369             if (download == null)
00370             {
00371                 rootPage.NotifyUser($"{title}: {message}", NotifyType.ErrorMessage);
00372             }
00373             else
00374             {
00375                 rootPage.NotifyUser($"{download.Guid} - {title}: {message}", NotifyType.ErrorMessage);
00376             }
00377
00378             return result;
00379         }
00380     }
00381 }
Generated on Fri Nov 15 2024 22:18:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ReadBytes Member List

This is the complete list of members for ReadBytes, including all inherited members.
bytesPerRow | ReadBytes | [private]
bytesPerSegment | ReadBytes | [private]
chunkSize | ReadBytes | [private]
HexDump(object sender, RoutedEventArgs e) | ReadBytes | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | ReadBytes | [inline, protected]
PrintRow(byte[] bytes, uint currByte) | ReadBytes | [inline, private]
ReadBytes() | ReadBytes | [inline]
rootPage | ReadBytes | [private]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cpp/Scenario3.xaml.cpp Source File

  • FileThumbnails
  • cpp

Scenario3.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario3.xaml.cpp
00014 // Implementation of the Scenario3 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario3.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace concurrency;
00023 using namespace Platform;
00024 using namespace Windows::Storage;
00025 using namespace Windows::Storage::FileProperties;
00026 using namespace Windows::Storage::Pickers;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 Scenario3::Scenario3()
00032 {
00033     InitializeComponent();
00034     rootPage = MainPage::Current;
00035 }
00036
00037 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00038 {
00039     rootPage->ResetOutput(ThumbnailImage, OutputTextBlock, nullptr);
00040 }
00041
00042 void Scenario3::GetThumbnailButton_Click(Object^ sender, RoutedEventArgs^ e)
00043 {
00044     rootPage->ResetOutput(ThumbnailImage, OutputTextBlock, nullptr);
00045
00046     // Pick a document
00047     FileOpenPicker^ openPicker = ref new FileOpenPicker();
00048     Array<String^>^ extensions = FileExtensions::Document;
00049     for (unsigned int i = 0; i < extensions->Length; i++)
00050     {
00051         openPicker->FileTypeFilter->Append(extensions[i]);
00052     }
00053
00054     create_task(openPicker->PickSingleFileAsync()).then([this](StorageFile^ file)
00055     {
00056         if (file != nullptr)
00057         {
00058             const ThumbnailMode thumbnailMode = ThumbnailMode::DocumentsView;
00059             const size_t size = 100;
00060             create_task(file->GetThumbnailAsync(thumbnailMode, size)).then([this, file, size](StorageItemThumbnail^ thumbnail)
00061             {
00062                 if (thumbnail != nullptr)
00063                 {
00064                     MainPage::DisplayResult(ThumbnailImage, OutputTextBlock, "DocumentsView", size, file, thumbnail, false);
00065                 }
00066                 else
00067                 {
00068                     rootPage->NotifyUser(Errors::NoIcon, NotifyType::StatusMessage);
00069                 }
00070             });
00071         }
00072         else
00073         {
00074             rootPage->NotifyUser(Errors::Cancel, NotifyType::StatusMessage);
00075         }
00076     });
00077 }
Generated on Fri Nov 15 2024 22:18:01 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_OrientationChanged Member List

This is the complete list of members for Scenario4_OrientationChanged, including all inherited members.
_accelerometerOriginal_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args) | Scenario4_OrientationChanged | [inline, private]
_accelerometerReadingTransform_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args) | Scenario4_OrientationChanged | [inline, private]
accelerometerOriginal | Scenario4_OrientationChanged | [private]
accelerometerReadingTransform | Scenario4_OrientationChanged | [private]
Current_VisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario4_OrientationChanged | [inline, private]
displayInformation | Scenario4_OrientationChanged | [private]
displayInformation_OrientationChanged(DisplayInformation sender, object args) | Scenario4_OrientationChanged | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario4_OrientationChanged | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario4_OrientationChanged | [inline, protected]
rootPage | Scenario4_OrientationChanged | [private]
Scenario4_OrientationChanged() | Scenario4_OrientationChanged | [inline]
ScenarioDisable() | Scenario4_OrientationChanged | [inline, private]
ScenarioEnable() | Scenario4_OrientationChanged | [inline, private]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SecondaryViewPage Member List

This is the complete list of members for SecondaryViewPage, including all inherited members.
ANIMATION_OPACITY_END | SecondaryViewPage | [private]
ANIMATION_OPACITY_START | SecondaryViewPage | [private]
ANIMATION_TRANSLATION_END | SecondaryViewPage | [private]
ANIMATION_TRANSLATION_START | SecondaryViewPage | [private]
ClearTitle_Click(object sender, RoutedEventArgs e) | SecondaryViewPage | [inline, private]
CreateEnterAnimation(Panel layoutRoot) | SecondaryViewPage | [inline, private]
EMPTY_TITLE | SecondaryViewPage | [private]
GoToMain_Click(object sender, RoutedEventArgs e) | SecondaryViewPage | [inline, private]
HandleProtocolLaunch(Uri uri) | SecondaryViewPage | [inline]
HideView_Click(object sender, RoutedEventArgs e) | SecondaryViewPage | [inline, private]
mainDispatcher | SecondaryViewPage | [private]
mainViewId | SecondaryViewPage | [private]
OnNavigatedTo(NavigationEventArgs e) | SecondaryViewPage | [inline, protected]
ProtocolLaunch_Click(object sender, RoutedEventArgs e) | SecondaryViewPage | [inline, private]
SecondaryViewPage() | SecondaryViewPage | [inline]
SetTitle(string newTitle) | SecondaryViewPage | [inline, private]
SetTitle_Click(object sender, RoutedEventArgs e) | SecondaryViewPage | [inline, private]
SwitchAndAnimate(int fromViewId) | SecondaryViewPage | [inline]
thisViewControl | SecondaryViewPage | [private]
ViewLifetimeControl_Released(Object sender, EventArgs e) | SecondaryViewPage | [inline, private]
Generated on Fri Nov 15 2024 22:24:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FolderEnumeration/cs/Scenario1.xaml.cs Source File

  • FolderEnumeration
  • cs

Scenario1.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Collections.Generic;
00013 using System.Text;
00014 using Windows.Storage;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario1 : Page
00022     {
00023         public Scenario1()
00024         {
00025             this.InitializeComponent();
00026         }
00027
00028         private async void GetFilesAndFoldersButton_Click(object sender, RoutedEventArgs e)
00029         {
00030             StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
00031
00032             IReadOnlyList<StorageFile> fileList = await picturesFolder.GetFilesAsync();
00033             IReadOnlyList<StorageFolder> folderList = await picturesFolder.GetFoldersAsync();
00034
00035             var count = fileList.Count + folderList.Count;
00036             StringBuilder outputText = new StringBuilder(picturesFolder.Name + " (" + count + ")\n\n");
00037
00038             foreach (StorageFolder folder in folderList)
00039             {
00040                 outputText.AppendLine("    " + folder.DisplayName + "\\");
00041             }
00042
00043             foreach (StorageFile file in fileList)
00044             {
00045                 outputText.AppendLine("    " + file.Name);
00046             }
00047
00048             OutputTextBlock.Text = outputText.ToString();
00049         }
00050     }
00051 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ComAutoRelease Member List

This is the complete list of members for ComAutoRelease, including all inherited members.
operator()(IUnknown *p) ComAutoRelease [inline]
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactPicker/cs/Scenario2_Multiple.xaml.cs Source File

  • ContactPicker
  • cs

Scenario2_Multiple.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.ApplicationModel.Contacts;
00015 using Windows.Foundation;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Input;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario2_Multiple : Page
00025     {
00026         private MainPage rootPage = MainPage.Current;
00027
00028         public Scenario2_Multiple()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         private void ClearOutputs()
00034         {
00035             // Reset the output fields.
00036             OutputText.Text = "";
00037             rootPage.NotifyUser("", NotifyType.StatusMessage);
00038         }
00039
00040         private void ReportContactResults(IList<Contact> contacts)
00041         {
00042             if (contacts != null && contacts.Count > 0)
00043             {
00044                 foreach (Contact contact in contacts)
00045                 {
00046                     OutputText.Text += MainPage.GetContactResult(contact) + "\n";
00047                 }
00048             }
00049             else
00050             {
00051                 rootPage.NotifyUser("No contacts were selected.", NotifyType.ErrorMessage);
00052             }
00053         }
00054
00055
00056         private async void PickContactsEmail()
00057         {
00058             ClearOutputs();
00059
00060             var contactPicker = new ContactPicker();
00061             // Ask the user to pick contact email addresses.
00062             contactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.Email);
00063             var contacts = await contactPicker.PickContactsAsync();
00064
00065             ReportContactResults(contacts);
00066         }
00067
00068         private async void PickContactsPhone()
00069         {
00070             ClearOutputs();
00071
00072             var contactPicker = new ContactPicker();
00073             // Ask the user to pick contact phone numbers.
00074             contactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber);
00075             var contacts = await contactPicker.PickContactsAsync();
00076
00077             ReportContactResults(contacts);
00078         }
00079
00080     }
00081 }
Generated on Fri Nov 15 2024 22:18:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ManageSessionResponse Member List

This is the complete list of members for ManageSessionResponse, including all inherited members.
ApduResponse() | ApduResponse | [inline]
DataObjectType enum name | ManageSessionResponse |
ExtractResponse(IBuffer response) | ApduResponse | [inline, virtual]
ExtractTlvDataObject(byte[] referenceTag) | ApduResponse | [inline]
ManageSessionResponse() | ManageSessionResponse | [inline]
ResponseData | ApduResponse |
Succeeded | ManageSessionResponse |
SW | ApduResponse |
SW1 | ApduResponse |
SW2 | ApduResponse |
SWTranslation | ApduResponse |
TAG_COMPREHENSION_MASK | ApduResponse |
TAG_LENGTH_MULTI_BYTE_MASK | ApduResponse |
TAG_MULTI_BYTE_MASK | ApduResponse |
ToString() | ApduResponse | [inline]
Version | ManageSessionResponse |
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PdfDocument/cppwinrt/Project.idl Source File

  • PdfDocument
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_Render : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_Render();
00018     }
00019 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Package/cs/SampleConfiguration.cs Source File

  • Package
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Package";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title = "Identity", ClassType = typeof(SDKTemplate.Scenario1) },
00025             new Scenario() { Title = "Installed Location", ClassType = typeof(SDKTemplate.Scenario2) },
00026             new Scenario() { Title = "Dependencies", ClassType = typeof(SDKTemplate.Scenario3) },
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cs/cpp/Scenario2_OvenClientWRL.xaml.h Source File

  • ProxyStubsForWinRTComponents
  • cs
  • cpp

Scenario2_OvenClientWRL.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008 #include "Scenario2_OvenClientWRL.g.h"
00009
00010 namespace SDKSample
00011 {
00012     namespace ProxyStubsForWinRTComponents
00013     {
00014         public ref class OvenClientWRL sealed
00015         {
00016         public:
00017             OvenClientWRL();
00018
00019         private:
00020             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021         };
00022     }
00023 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DownloadOperationItem Member List

This is the complete list of members for DownloadOperationItem, including all inherited members.
_download | DownloadOperationItem | [private]
_percentComplete | DownloadOperationItem | [private]
_stateText | DownloadOperationItem | [private]
download | DownloadOperationItem |
DownloadOperationItem(DownloadOperation download) | DownloadOperationItem | [inline]
percentComplete | DownloadOperationItem |
PropertyChanged | DownloadOperationItem |
stateText | DownloadOperationItem |
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraAdvancedCapture/cpp/pch.h Source File

  • CameraAdvancedCapture
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <collection.h>
00015 #include <ppltasks.h>
00016
00017 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CMediaSource Member List

This is the complete list of members for CMediaSource, including all inherited members.
_Acquires_lock_(_critSec) HRESULT Lock() | CMediaSource |
_cRef | CMediaSource | [private]
_critSec | CMediaSource | [private]
_CurrentReceivedOperationHeader | CMediaSource | [private]
_eSourceState | CMediaSource | [private]
_flRate | CMediaSource | [private]
_networkSender | CMediaSource | [private]
_openedEvent | CMediaSource | [private]
_Releases_lock_(_critSec) HRESULT Unlock() | CMediaSource |
_serverAddress | CMediaSource | [private]
_serverPort | CMediaSource | [private]
_spAttributes | CBaseAttributes<> | [protected]
_spCurrentReceiveBuffer | CMediaSource | [private]
_spCurrentReceivePacket | CMediaSource | [private]
_spEventQueue | CMediaSource | [private]
_spPresentationDescriptor | CMediaSource | [private]
_streams | CMediaSource | [private]
AddStream(StspStreamDescription *pStreamDesc) | CMediaSource | [private]
BeginGetEvent(IMFAsyncCallback *pCallback, IUnknown *punkState) | CMediaSource |
CBaseAttributes() | CBaseAttributes<> | [inline, protected]
CBaseAttributes(HRESULT &hr, UINT32 cInitialSize=0) | CBaseAttributes<> | [inline, protected]
CBaseAttributes(HRESULT &hr, IUnknown *pUnk) | CBaseAttributes<> | [inline, protected]
CheckShutdown() const | CMediaSource | [inline, private]
CMediaSource(void) | CMediaSource | [protected]
Compare(IMFAttributes *pTheirs, MF_ATTRIBUTES_MATCH_TYPE MatchType, BOOL *pbResult) | CBaseAttributes<> | [inline]
CompareItem(REFGUID guidKey, REFPROPVARIANT Value, BOOL *pbResult) | CBaseAttributes<> | [inline]
CompleteOpen(HRESULT hResult) | CMediaSource | [private]
CopyAllItems(IMFAttributes *pDest) | CBaseAttributes<> | [inline]
CreateInstance(CMediaSource **ppNetSource) | CMediaSource | [static]
CreatePresentationDescriptor(IMFPresentationDescriptor **ppPresentationDescriptor) | CMediaSource |
DeleteAllItems() | CBaseAttributes<> | [inline]
DeleteItem(REFGUID guidKey) | CBaseAttributes<> | [inline]
DeserializeFromBlob(const UINT8 *pBuffer, UINT cbSize) | CBaseAttributes<> | [inline]
DeserializeFromStream(DWORD dwOptions, IStream *pStm) | CBaseAttributes<> | [inline]
DispatchOperation(_In_ CSourceOperation *pOp) | CMediaSource |
OpQueue< CMediaSource, CSourceOperation >::DispatchOperation(CSourceOperation *pOp)=0 | OpQueue< CMediaSource, CSourceOperation > | [protected, pure virtual]
DoSetRate(CSetRateOperation *pOp) | CMediaSource | [private]
DoStart(CStartOperation *pOp) | CMediaSource | [private]
DoStop(CSourceOperation *pOp) | CMediaSource | [private]
EndGetEvent(IMFAsyncResult *pResult, IMFMediaEvent **ppEvent) | CMediaSource |
GetAllocatedBlob(REFGUID guidKey, UINT8 **ppBuf, UINT32 *pcbSize) | CBaseAttributes<> | [inline]
GetAllocatedString(REFGUID guidKey, LPWSTR *ppwszValue, UINT32 *pcchLength) | CBaseAttributes<> | [inline]
GetBlob(REFGUID guidKey, UINT8 *pBuf, UINT32 cbBufSize, UINT32 *pcbBlobSize) | CBaseAttributes<> | [inline]
GetBlobSize(REFGUID guidKey, UINT32 *pcbBlobSize) | CBaseAttributes<> | [inline]
GetCharacteristics(DWORD *pdwCharacteristics) | CMediaSource |
GetCount(UINT32 *pcItems) | CBaseAttributes<> | [inline]
GetDouble(REFGUID guidKey, double *pfValue) | CBaseAttributes<> | [inline]
GetEvent(DWORD dwFlags, IMFMediaEvent **ppEvent) | CMediaSource |
GetGUID(REFGUID guidKey, GUID *pguidValue) | CBaseAttributes<> | [inline]
GetItem(REFGUID guidKey, PROPVARIANT *pValue) | CBaseAttributes<> | [inline]
GetItemByIndex(UINT32 unIndex, GUID *pguidKey, PROPVARIANT *pValue) | CBaseAttributes<> | [inline]
GetItemType(REFGUID guidKey, MF_ATTRIBUTE_TYPE *pType) | CBaseAttributes<> | [inline]
GetRate(_Inout_opt_ BOOL *pfThin, _Inout_opt_ float *pflRate) | CMediaSource |
GetRatio(REFGUID guidKey, UINT32 *pnNumerator, UINT32 *punDenominator) | CBaseAttributes<> | [inline]
GetService(_In_ REFGUID guidService, _In_ REFIID riid, _Out_opt_ LPVOID *ppvObject) | CMediaSource |
GetSize(REFGUID guidKey, UINT32 *punWidth, UINT32 *punHeight) | CBaseAttributes<> | [inline]
GetStreamById(DWORD dwId, CMediaStream **ppStream) | CMediaSource | [private]
GetString(REFGUID guidKey, LPWSTR pwszValue, UINT32 cchBufSize, UINT32 *pcchLength) | CBaseAttributes<> | [inline]
GetStringLength(REFGUID guidKey, UINT32 *pcchLength) | CBaseAttributes<> | [inline]
GetUINT32(REFGUID guidKey, UINT32 *punValue) | CBaseAttributes<> | [inline]
GetUINT64(REFGUID guidKey, UINT64 *punValue) | CBaseAttributes<> | [inline]
GetUnknown(REFGUID guidKey, REFIID riid, LPVOID *ppv) | CBaseAttributes<> | [inline]
HandleError(HRESULT hResult) | CMediaSource | [private]
IFACEMETHOD_(ULONG, AddRef)() | CMediaSource |
IFACEMETHOD_(ULONG, Release)() | CMediaSource |
Initialize() | CMediaSource | [private]
CBaseAttributes<>::Initialize(UINT32 cInitialSize=0) | CBaseAttributes<> | [inline, protected]
CBaseAttributes<>::Initialize(IUnknown *pUnk) | CBaseAttributes<> | [inline, protected]
InitPresentationDescription() | CMediaSource | [private]
IsRateSupported(float flRate, float *pflAdjustedRate) | CMediaSource | [private]
LockStore() | CBaseAttributes<> | [inline]
m_critsec | OpQueue< CMediaSource, CSourceOperation > | [protected]
m_OnProcessQueue | OpQueue< CMediaSource, CSourceOperation > | [protected]
m_OpQueue | OpQueue< CMediaSource, CSourceOperation > | [protected]
OpenAsync(LPCWSTR pszUrl) | CMediaSource |
OpList typedef | OpQueue< CMediaSource, CSourceOperation > |
OpQueue(CRITICAL_SECTION &critsec) | OpQueue< CMediaSource, CSourceOperation > | [inline, protected]
ParseCurrentBuffer() | CMediaSource | [private]
ParseServerUrl(LPCWSTR pszUrl) | CMediaSource | [private]
Pause() | CMediaSource |
ProcessPacket(StspOperationHeader *pOpHeader, Network::IBufferPacket *pPacket) | CMediaSource | [private]
ProcessQueue() | OpQueue< CMediaSource, CSourceOperation > | [protected]
ProcessQueueAsync(IMFAsyncResult *pResult) | OpQueue< CMediaSource, CSourceOperation > | [protected]
ProcessServerDescription(Network::IBufferPacket *pPacket) | CMediaSource | [private]
ProcessServerFormatChange(Network::IBufferPacket *pPacket) | CMediaSource | [private]
ProcessServerSample(Network::IBufferPacket *pPacket) | CMediaSource | [private]
QueryInterface(REFIID riid, void **ppv) | CMediaSource |
QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT *pvValue) | CMediaSource |
QueueOperation(CSourceOperation *pOp) | OpQueue< CMediaSource, CSourceOperation > |
Receive() | CMediaSource | [private]
SelectStreams(IMFPresentationDescriptor *pPD) | CMediaSource | [private]
SendDescribeRequest() | CMediaSource | [private]
SendRequestAsync(StspOperation eOperation) | CMediaSource | [private]
SendStartRequest() | CMediaSource | [private]
SerializeToBlob(UINT8 **ppBuffer, UINT *pcbSize) | CBaseAttributes<> | [inline]
SerializeToStream(DWORD dwOptions, IStream *pStm) | CBaseAttributes<> | [inline]
SetBlob(REFGUID guidKey, const UINT8 *pBuf, UINT32 cbBufSize) | CBaseAttributes<> | [inline]
SetDouble(REFGUID guidKey, double fValue) | CBaseAttributes<> | [inline]
SetGUID(REFGUID guidKey, REFGUID guidValue) | CBaseAttributes<> | [inline]
SetItem(REFGUID guidKey, REFPROPVARIANT Value) | CBaseAttributes<> | [inline]
SetRate(BOOL fThin, float flRate) | CMediaSource |
SetRatio(REFGUID guidKey, UINT32 unNumerator, UINT32 unDenominator) | CBaseAttributes<> | [inline]
SetSize(REFGUID guidKey, UINT32 unWidth, UINT32 unHeight) | CBaseAttributes<> | [inline]
SetString(REFGUID guidKey, LPCWSTR wszValue) | CBaseAttributes<> | [inline]
SetUINT32(REFGUID guidKey, UINT32 unValue) | CBaseAttributes<> | [inline]
SetUINT64(REFGUID guidKey, UINT64 unValue) | CBaseAttributes<> | [inline]
SetUnknown(REFGUID guidKey, IUnknown *pUnknown) | CBaseAttributes<> | [inline]
Shutdown() | CMediaSource |
Start(IMFPresentationDescriptor *pPresentationDescriptor, const GUID *pguidTimeFormat, const PROPVARIANT *pvarStartPosition) | CMediaSource |
Stop() | CMediaSource |
StreamContainer typedef | CMediaSource | [private]
UnlockStore() | CBaseAttributes<> | [inline]
ValidateOperation(_In_ CSourceOperation *pOp) | CMediaSource |
OpQueue< CMediaSource, CSourceOperation >::ValidateOperation(CSourceOperation *pOp)=0 | OpQueue< CMediaSource, CSourceOperation > | [protected, pure virtual]
ValidatePresentationDescriptor(IMFPresentationDescriptor *pPD) | CMediaSource | [private]
~CBaseAttributes() | CBaseAttributes<> | [inline, protected, virtual]
~CMediaSource(void) | CMediaSource | [protected]
~OpQueue() | OpQueue< CMediaSource, CSourceOperation > | [inline, protected, virtual]
Generated on Fri Nov 15 2024 22:23:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/Scenario6_CustomFilterAddedProps.xaml.h Source File

  • DeviceEnumerationAndPairing
  • cpp

Scenario6_CustomFilterAddedProps.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario6_CustomFilterAddedProps.g.h"
00006 #include "MainPage.xaml.h"
00007 #include "DisplayHelpers.h"
00008 #include "DeviceWatcherHelper.h"
00009
00010 namespace SDKTemplate
00011 {
00012     [Windows::Foundation::Metadata::WebHostHidden]
00013     public ref class Scenario6_CustomFilterAddedProps sealed
00014     {
00015     public:
00016         Scenario6_CustomFilterAddedProps();
00017
00018     protected:
00019         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00020         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00021
00022     private:
00023         void StartWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00024         void StopWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00025
00026         void StartWatcher();
00027         void StopWatcher();
00028
00029         MainPage^ rootPage = MainPage::Current;
00030         Windows::Foundation::Collections::IObservableVector<DeviceInformationDisplay^>^ resultCollection = ref new Platform::Collections::Vector<DeviceInformationDisplay^>();
00031         DeviceWatcherHelper^ deviceWatcherHelper;
00032     };
00033 }
Generated on Fri Nov 15 2024 22:19:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_UnicodeExtensions Member List

This is the complete list of members for Scenario5_UnicodeExtensions, including all inherited members.
Display_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario5_UnicodeExtensions
Scenario5_UnicodeExtensions() | Scenario5_UnicodeExtensions
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AnimationMetrics/cpp/SampleConfiguration.h Source File

  • AnimationMetrics
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Animation metrics C++ sample";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactCards/cpp/Scenario2_DelayMini.xaml.cpp Source File

  • ContactCards
  • cpp

Scenario2_DelayMini.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_DelayMini.xaml.h"
00014
00015 using namespace Concurrency;
00016 using namespace SDKTemplate;
00017
00018 using namespace Platform;
00019 using namespace Windows::ApplicationModel::Contacts;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Core;
00023 using namespace Windows::UI::Popups;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026
00027 Scenario2_DelayMini::Scenario2_DelayMini()
00028 {
00029     InitializeComponent();
00030 }
00031
00032 void Scenario2_DelayMini::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00033 {
00034     if (!ContactManager::IsShowDelayLoadedContactCardSupported())
00035     {
00036         NotSupportedWarning->Visibility = Windows::UI::Xaml::Visibility::Visible;
00037     }
00038 }
00039
00040 Contact^ Scenario2_DelayMini::CreatePlaceholderContact()
00041 {
00042     // Create contact object with small set of initial data to display.
00043     Contact^ contact = ref new Contact();
00044     contact->FirstName = "Kim";
00045     contact->LastName = "Abercrombie";
00046
00047     ContactEmail^ email = ref new ContactEmail();
00048     email->Address = "kim@contoso.com";
00049     contact->Emails->Append(email);
00050
00051     return contact;
00052 }
00053
00054 task<Contact^> Scenario2_DelayMini::DownloadContactDataAsync(Contact^ contact)
00055 {
00056     bool downloadSucceeded = DownloadSucceeded->IsChecked->Value;
00057
00058     return create_task([this, contact, downloadSucceeded]()
00059     {
00060         // Simulate the download latency by delaying the execution by 2 seconds.
00061         Sleep(2000);
00062
00063         if (!downloadSucceeded)
00064         {
00065             return static_cast<Contact^>(nullptr);
00066         }
00067
00068         // Add more data to the contact object.
00069         ContactEmail^ workEmail = ref new ContactEmail();
00070         workEmail->Address = "kim@example.com";
00071         workEmail->Kind = ContactEmailKind::Work;
00072         contact->Emails->Append(workEmail);
00073
00074         ContactPhone^ homePhone = ref new ContactPhone();
00075         homePhone->Number = "(444) 555-0101";
00076         homePhone->Kind = ContactPhoneKind::Home;
00077         contact->Phones->Append(homePhone);
00078
00079         ContactPhone^ workPhone = ref new ContactPhone();
00080         workPhone->Number = "(245) 555-0123";
00081         workPhone->Kind = ContactPhoneKind::Work;
00082         contact->Phones->Append(workPhone);
00083
00084         ContactPhone^ mobilePhone = ref new ContactPhone();
00085         mobilePhone->Number = "(921) 555-0187";
00086         mobilePhone->Kind = ContactPhoneKind::Mobile;
00087         contact->Phones->Append(mobilePhone);
00088
00089         ContactAddress^ address = ref new ContactAddress();
00090         address->StreetAddress = "123 Main St";
00091         address->Locality = "Redmond";
00092         address->Region = "WA";
00093         address->Country = "USA";
00094         address->PostalCode = "00000";
00095         address->Kind = ContactAddressKind::Home;
00096         contact->Addresses->Append(address);
00097
00098         return contact;
00099     });
00100 }
00101
00102 void Scenario2_DelayMini::ShowContactCard_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00103 {
00104     Contact^ contact = CreatePlaceholderContact();
00105
00106     // Show the contact card next to the button.
00107     Rect rect = MainPage::GetElementRect(safe_cast<FrameworkElement^>(sender));
00108
00109     // The contact card placement can change when it is updated with more data. For improved user experience, specify placement
00110     // of the card so that it has space to grow and will not need to be repositioned. In this case, default placement first places
00111     // the card above the button because the card is small, but after the card is updated with more data, the operating system moves
00112     // the card below the button to fit the card's expanded size. Specifying that the contact card is placed below at the beginning
00113     // avoids this repositioning.
00114     Placement placement = Placement::Below;
00115
00116     // For demonstration purposes, we ask for the Enterprise contact card.
00117     ContactCardOptions^ options = ref new ContactCardOptions();
00118     options->HeaderKind = ContactCardHeaderKind::Enterprise;
00119
00120     ContactCardDelayedDataLoader^ dataLoader = ContactManager::ShowDelayLoadedContactCard(contact, rect, placement, options);
00121
00122     if (dataLoader != nullptr)
00123     {
00124         // Simulate downloading more data from the network for the contact.
00125         this->rootPage->NotifyUser("Simulating download...", NotifyType::StatusMessage);
00126
00127         DownloadContactDataAsync(contact).then([this, dataLoader](Contact^ fullContact)
00128         {
00129             String^ message;
00130             if (fullContact != nullptr)
00131             {
00132                 // Update the contact card with the full set of contact data.
00133                 dataLoader->SetData(fullContact);
00134                 message = "Contact has been updated with downloaded data.";
00135             }
00136             else
00137             {
00138                 message = "No further information available.";
00139             }
00140
00141             Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, message]()
00142             {
00143                 this->rootPage->NotifyUser(message, NotifyType::StatusMessage);
00144             }));
00145
00146             // Dispose the object to indicate that the delay-loading operation has completed.
00147             delete dataLoader;
00148         });
00149     }
00150     else
00151     {
00152         this->rootPage->NotifyUser("ShowDelayLoadedContactCard is not supported by this device.", NotifyType::ErrorMessage);
00153     }
00154 }
Generated on Fri Nov 15 2024 22:18:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Orientation Member List

This is the complete list of members for Scenario1_Orientation, including all inherited members.
ApplyRotationLock_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Orientation |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_Orientation |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_Orientation |
OnOrientationChanged(Windows::Graphics::Display::DisplayInformation const &, Windows::Foundation::IInspectable const &) | Scenario1_Orientation | [private]
OrientationsToString(Windows::Graphics::Display::DisplayOrientations orientations) | Scenario1_Orientation | [private]
Scenario1_Orientation() | Scenario1_Orientation |
UpdateContent() | Scenario1_Orientation | [private]
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFont/DocumentPresenter.cpp Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFont

DocumentPresenter.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DocumentPresenter.h"
00014 #include "MainPage.xaml.h"
00015
00016 using namespace SDKTemplate;
00017 using namespace DWriteTextLayoutCloudFontImplementation;
00018
00019 using Platform::String;
00020 using Windows::Foundation::TypedEventHandler;
00021 using Windows::Graphics::Display::DisplayInformation;
00022 using Windows::UI::Color;
00023 using Windows::UI::Xaml::Controls::Image;
00024 using Windows::UI::Xaml::Controls::ScrollViewer;
00025 using Windows::UI::Xaml::Window;
00026 using Windows::UI::Xaml::WindowVisibilityChangedEventHandler;
00027
00028
00029 // Text will be laid out using IDWriteTextLayout (implemented in the
00030 // TextLayout wrapper class) and then presented within XAML using a
00031 // SurfaceImageSource (implemented as the TextLayoutImageSource class).
00032 //
00033 // The width and height of the SurfaceImageSource need to  be determined before
00034 // it is created. This will be done by getting the current width of the XAML
00035 // frame in which the content will be presented, creating the text layout using
00036 // that width, and then getting the height determined for the layout.
00037 //
00038 // The content will be presented in the TextLayoutFrame element (a
00039 // ScrollViewer), and the actual width of that element won't be set until after
00040 // the page is loaded. We can initially create the text layout in the page
00041 // constructor with a default width (300) and then update it as the size of
00042 // TextLayoutFrame changes.
00043 //
00044 // To present Direct2D content within the XAML frame element, a SurfaceImageSource
00045 // implemented in the TextLayoutImageSource class) will be created and used as the
00046 // source for an image control contained within the TextLayoutFrame element. The
00047 // SurfaceImageSource implementation is not directly related to use of downloadable
00048 // fonts in DirectWrite, so not the primary focus of this sample.
00049 //
00050 // The layout will be drawn using a font that may not be installed on the
00051 // system. (For this page, the font used is contained in an optional Windows
00052 // feature that is not installed by default.) The text layout will initially
00053 // use fallback fonts. After it is created, the FontDownloadListener class will
00054 // be used to interact with the DirectWrite font download queue to request that
00055 // the specified font data be downloaded and then to get a notification when
00056 // the data is downloaded. When that event fires, the text layout will be
00057 // invalidated, forcing the text to be layed out again. This time, it will be
00058 // able to use the selected font data that has been downloaded.
00059
00060
00061 DocumentPresenter::DocumentPresenter(
00062     String^ text,
00063     String^ downloadableFontName,
00064     String^ languageTag,
00065     Color textColor,
00066     Color textBackgroundColor,
00067     Image^ imageTarget
00068 ) :
00069     m_downloadableFontName(downloadableFontName),
00070     m_textColor(textColor),
00071     m_textBackgroundColor(textBackgroundColor),
00072     m_imageTarget(imageTarget)
00073 {
00074     // Text content, fonts and colours are defined in each page. This class handles the
00075     // implementation:
00076     //
00077     // - Creating the text layout object.
00078     // - Creating the surface image source object.
00079     // - Interacting with the font download listener object.
00080     // - Handling events that require updating the text layout or surface image source.
00081
00082     // Create the TextLayout for our text content.
00083     m_textLayout = ref new TextLayout(text, languageTag, m_downloadableFontName, /* fontSize */ 20, /* default width */ 300);
00084
00085     // Update the app status bar to show what fonts have actually been used. This will
00086     // ask the text layout for info that will require it to draw, which in turn will
00087     // cause the layout to add remote fonts to the font download queue. The status bar
00088     // is an informational tool for the sample. In an actual app, the layout would get
00089     // used in other ways involving drawing or measuring that would cause it to add
00090     // remote fonts to the font download queue.
00091     UpdateStatus();
00092
00093     // Initialize FontDownloadListener, register a DownloadCompleted event handler, and
00094     // initiate a download.
00095     //
00096     // The FontDownloadListener is a singleton with static members. Calling Initialize
00097     // from any context will create the global singleton and set up its resources.
00098     //
00099     // The event handler must be unregistered before the page is destroyed. We'll do
00100     // that in the destructor. If we were to have XAML cache a page that has the
00101     // DocumentPresenter when the app navigates away from the page, then the handler
00102     // will still be hooked up, so the event won't be missed and the layout will be
00103     // updated.
00104     FontDownloadListener::Initialize();
00105     m_downloadCompletedEventToken = FontDownloadListener::DownloadCompleted += ref new FontDownloadCompletedHandler(this, &DocumentPresenter::FontDownloadListener_DownloadCompleted);
00106     FontDownloadListener::BeginDownload();
00107
00108     // Handle DpiChanged -- the SurfaceImageSource will need to be re-created.
00109     m_displayInformation = DisplayInformation::GetForCurrentView();
00110     m_dpi = m_displayInformation->LogicalDpi;
00111     m_dpiChangedEventToken = m_displayInformation->DpiChanged += ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DocumentPresenter::DisplayInformation_DpiChanged);
00112
00113     // Handle window VisibilityChanged -- the SurfaceImageSource will need to be re-created.
00114     m_visibilityChangedEventToken = Window::Current->VisibilityChanged += ref new WindowVisibilityChangedEventHandler(this, &DocumentPresenter::Window_VisibilityChanged);
00115
00116 } // DocumentPresenter()
00117
00118 DocumentPresenter::~DocumentPresenter()
00119 {
00120     FontDownloadListener::DownloadCompleted -= m_downloadCompletedEventToken;
00121     m_displayInformation->DpiChanged -= m_dpiChangedEventToken;
00122     Window::Current->VisibilityChanged -= m_visibilityChangedEventToken;
00123 }
00124
00125 void DocumentPresenter::SetLayoutWidth(float width)
00126 {
00127     if (width != m_textLayout->Width)
00128     {
00129         m_textLayout->Width = width;
00130         PresentTextLayout();
00131     }
00132 }
00133
00134 // Event handlers
00135
00136 void DocumentPresenter::DisplayInformation_DpiChanged(DisplayInformation^ displayInformation, Platform::Object^ e)
00137 {
00138     // Re-create the SurfaceImageSource if the DPI has changed.
00139     m_dpi = displayInformation->LogicalDpi;
00140     PresentTextLayout();
00141 }
00142
00143 void DocumentPresenter::FontDownloadListener_DownloadCompleted()
00144 {
00145     // DownloadCompleted is called from a worker thread, so schedule work
00146     // in the UI thread.
00147     MainPage::Current->Dispatcher->RunAsync(
00148         Windows::UI::Core::CoreDispatcherPriority::Normal,
00149         ref new Windows::UI::Core::DispatchedHandler([this]() { RequestTextLayoutUpdate(); })
00150     );
00151 }
00152
00153 void DocumentPresenter::Window_VisibilityChanged(Platform::Object ^sender, Windows::UI::Core::VisibilityChangedEventArgs ^e)
00154 {
00155     // Re-create the SurfaceImageSource if the window has just become visible.
00156     if (e->Visible)
00157     {
00158         PresentTextLayout();
00159     }
00160 }
00161
00162 // Private helper methods
00163
00164 void DocumentPresenter::PresentTextLayout()
00165 {
00166     // Create a new TextLayoutImageSource based on the text layout and
00167     // use it as the source for the XAML image element.
00168     m_textLayoutImageSource = ref new TextLayoutImageSource(m_textLayout, m_dpi, m_textColor, m_textBackgroundColor);
00169     m_imageTarget->Source = m_textLayoutImageSource;
00170 }
00171
00172 void DocumentPresenter::RequestTextLayoutUpdate()
00173 {
00174     // Don't initiate new work while there's work already in progress.
00175     if (!m_layoutUpdateInProgress)
00176     {
00177         m_layoutUpdateInProgress = true;
00178
00179         // Scheduling the update as a low-priority task so that work for multiple,
00180         // consecutive events that occur in rapid succession will get consolidated.
00181         MainPage::Current->Dispatcher->RunAsync(
00182             Windows::UI::Core::CoreDispatcherPriority::Low,
00183             ref new Windows::UI::Core::DispatchedHandler([this]() { UpdateTextLayout(); })
00184         );
00185     }
00186 }
00187
00188 void DocumentPresenter::UpdateTextLayout()
00189 {
00190     // We'll be completing the layout update, so we can clear the flag used
00191     // for consolidating multiple events occuring in rapid succession into
00192     // a single task.
00193     m_layoutUpdateInProgress = false;
00194
00195     // Refresh the TextLayout and present the updated layout. The refreshed
00196     // layout will be able to use fonts that have been downloaded.
00197     m_textLayout->InvalidateLayout();
00198     PresentTextLayout();
00199
00200     // Update the status bar to show what fonts have actually been used.
00201     UpdateStatus();
00202 }
00203
00204 void DocumentPresenter::UpdateStatus()
00205 {
00206     // Get the fonts that have actually been used in the text layout.
00207     String^ fontsUsed = m_textLayout->FontsUsed;
00208
00209     // The status will reflect whether the font used was the requested font
00210     // or a fallback font.
00211     NotifyType statusType = (fontsUsed == m_downloadableFontName) ? NotifyType::StatusMessage : NotifyType::ErrorMessage;
00212
00213     // Now update the status.
00214     MainPage::Current->NotifyUser("Fonts actually used: " + fontsUsed, statusType);
00215 }
Generated on Fri Nov 15 2024 22:19:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/EventTests.xaml.cpp Source File

  • XamlBind
  • cpp

EventTests.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // EventTests.xaml.cpp
00003 // Implementation of the EventTests class
00004 //
00005
00006 #include "pch.h"
00007 #include "EventTests.xaml.h"
00008
00009 using namespace SDKTemplate;
00010
00011 using namespace Platform;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Foundation::Collections;
00014 using namespace Windows::UI::Xaml;
00015 using namespace Windows::UI::Xaml::Controls;
00016 using namespace Windows::UI::Xaml::Controls::Primitives;
00017 using namespace Windows::UI::Xaml::Data;
00018 using namespace Windows::UI::Xaml::Input;
00019 using namespace Windows::UI::Xaml::Media;
00020 using namespace Windows::UI::Xaml::Navigation;
00021 using namespace Windows::UI::Popups;
00022
00023 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00024
00025 EventTests::EventTests()
00026 {
00027     InitializeComponent();
00028     this->Model = ref new xBindSampleModel::DataModel();
00029 }
00030
00031
00032 void EventTests::Click_RegularArgs(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00033 {
00034     MessageDialog^ dlg = ref new MessageDialog("Clicked - Regular Args");
00035     dlg->ShowAsync();
00036 }
00037
00038 void EventTests::Click_NoArgs()
00039 {
00040     MessageDialog^ dlg = ref new MessageDialog("Clicked - No Args");
00041     dlg->ShowAsync();
00042 }
00043
00044 void EventTests::Click_BaseArgs(Platform::Object^ sender, Platform::Object^ e)
00045 {
00046     MessageDialog^ dlg = ref new MessageDialog("Clicked - Base Args");
00047     dlg->ShowAsync();
00048 }
Generated on Fri Nov 15 2024 22:22:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cppwinrt/Project.idl Source File

  • SecondaryTiles
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_PinTile : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_PinTile();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_UnpinTile : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_UnpinTile();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3_EnumerateTiles : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3_EnumerateTiles();
00030     }
00031
00032     [default_interface]
00033     runtimeclass Scenario4_TilePinned : Windows.UI.Xaml.Controls.Page
00034     {
00035         Scenario4_TilePinned();
00036     }
00037
00038     [default_interface]
00039     runtimeclass Scenario5_LaunchedFromSecondaryTile : Windows.UI.Xaml.Controls.Page
00040     {
00041         Scenario5_LaunchedFromSecondaryTile();
00042     }
00043
00044     [default_interface]
00045     runtimeclass Scenario6_SecondaryTileNotification : Windows.UI.Xaml.Controls.Page
00046     {
00047         Scenario6_SecondaryTileNotification();
00048     }
00049
00050     [default_interface]
00051     runtimeclass Scenario7_PinFromAppbar : Windows.UI.Xaml.Controls.Page
00052     {
00053         Scenario7_PinFromAppbar();
00054     }
00055
00056     [default_interface]
00057     runtimeclass Scenario8_UpdateAsync : Windows.UI.Xaml.Controls.Page
00058     {
00059         Scenario8_UpdateAsync();
00060     }
00061 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LockScreenApps/cppwinrt/Scenario1_Configure.h Source File

  • LockScreenApps
  • cppwinrt

Scenario1_Configure.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Configure.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_Configure : Scenario1_ConfigureT<Scenario1_Configure>
00019     {
00020         Scenario1_Configure();
00021
00022         fire_and_forget OpenAppSettings(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023         fire_and_forget OpenLockscreenSettings(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024     };
00025 }
00026
00027 namespace winrt::SDKTemplate::factory_implementation
00028 {
00029     struct Scenario1_Configure : Scenario1_ConfigureT<Scenario1_Configure, implementation::Scenario1_Configure>
00030     {
00031     };
00032 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cppwinrt/Common/DeviceResources.cpp Source File

  • BasicHologram
  • cppwinrt
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿
00002 #include "pch.h"
00003 #include "DeviceResources.h"
00004 #include "DirectXHelper.h"
00005
00006 using namespace D2D1;
00007 using namespace Microsoft::WRL;
00008 using namespace winrt::Windows::Graphics::DirectX::Direct3D11;
00009 using namespace winrt::Windows::Graphics::Display;
00010 using namespace winrt::Windows::Graphics::Holographic;
00011
00012 // Constructor for DeviceResources.
00013 DX::DeviceResources::DeviceResources()
00014 {
00015     CreateDeviceIndependentResources();
00016 }
00017
00018 // Configures resources that don't depend on the Direct3D device.
00019 void DX::DeviceResources::CreateDeviceIndependentResources()
00020 {
00021     // Initialize Direct2D resources.
00022     D2D1_FACTORY_OPTIONS options{};
00023
00024 #if defined(_DEBUG)
00025     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00026     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00027 #endif
00028
00029     // Initialize the Direct2D Factory.
00030     winrt::check_hresult(
00031         D2D1CreateFactory(
00032             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00033             __uuidof(ID2D1Factory2),
00034             &options,
00035             &m_d2dFactory
00036         ));
00037
00038     // Initialize the DirectWrite Factory.
00039     winrt::check_hresult(
00040         DWriteCreateFactory(
00041             DWRITE_FACTORY_TYPE_SHARED,
00042             __uuidof(IDWriteFactory2),
00043             &m_dwriteFactory
00044         ));
00045
00046     // Initialize the Windows Imaging Component (WIC) Factory.
00047     winrt::check_hresult(
00048         CoCreateInstance(
00049             CLSID_WICImagingFactory2,
00050             nullptr,
00051             CLSCTX_INPROC_SERVER,
00052             IID_PPV_ARGS(&m_wicFactory)
00053         ));
00054 }
00055
00056 void DX::DeviceResources::SetHolographicSpace(HolographicSpace holographicSpace)
00057 {
00058     // Cache the holographic space. Used to re-initalize during device-lost scenarios.
00059     m_holographicSpace = holographicSpace;
00060
00061     InitializeUsingHolographicSpace();
00062 }
00063
00064 void DX::DeviceResources::InitializeUsingHolographicSpace()
00065 {
00066     // The holographic space might need to determine which adapter supports
00067     // holograms, in which case it will specify a non-zero PrimaryAdapterId.
00068     LUID id =
00069     {
00070         m_holographicSpace.PrimaryAdapterId().LowPart,
00071         m_holographicSpace.PrimaryAdapterId().HighPart
00072     };
00073
00074     // When a primary adapter ID is given to the app, the app should find
00075     // the corresponding DXGI adapter and use it to create Direct3D devices
00076     // and device contexts. Otherwise, there is no restriction on the DXGI
00077     // adapter the app can use.
00078     if ((id.HighPart != 0) || (id.LowPart != 0))
00079     {
00080         UINT createFlags = 0;
00081 #ifdef DEBUG
00082         if (DX::SdkLayersAvailable())
00083         {
00084             createFlags |= DXGI_CREATE_FACTORY_DEBUG;
00085         }
00086 #endif
00087         // Create the DXGI factory.
00088         ComPtr<IDXGIFactory1> dxgiFactory;
00089         winrt::check_hresult(
00090             CreateDXGIFactory2(
00091                 createFlags,
00092                 IID_PPV_ARGS(&dxgiFactory)
00093             ));
00094         ComPtr<IDXGIFactory4> dxgiFactory4;
00095         winrt::check_hresult(dxgiFactory.As(&dxgiFactory4));
00096
00097         // Retrieve the adapter specified by the holographic space.
00098         winrt::check_hresult(
00099             dxgiFactory4->EnumAdapterByLuid(
00100                 id,
00101                 IID_PPV_ARGS(&m_dxgiAdapter)
00102             ));
00103     }
00104     else
00105     {
00106         m_dxgiAdapter.Reset();
00107     }
00108
00109     CreateDeviceResources();
00110
00111     m_holographicSpace.SetDirect3D11Device(m_d3dInteropDevice);
00112 }
00113
00114 // Configures the Direct3D device, and stores handles to it and the device context.
00115 void DX::DeviceResources::CreateDeviceResources()
00116 {
00117     // This flag adds support for surfaces with a different color channel ordering
00118     // than the API default. It is required for compatibility with Direct2D.
00119     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00120
00121 #if defined(_DEBUG)
00122     if (DX::SdkLayersAvailable())
00123     {
00124         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00125         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00126     }
00127 #endif
00128
00129     // This array defines the set of DirectX hardware feature levels this app will support.
00130     // Note the ordering should be preserved.
00131     // Note that HoloLens supports feature level 11.1. The HoloLens emulator is also capable
00132     // of running on graphics cards starting with feature level 10.0.
00133     D3D_FEATURE_LEVEL featureLevels[] =
00134     {
00135         D3D_FEATURE_LEVEL_12_1,
00136         D3D_FEATURE_LEVEL_12_0,
00137         D3D_FEATURE_LEVEL_11_1,
00138         D3D_FEATURE_LEVEL_11_0,
00139         D3D_FEATURE_LEVEL_10_1,
00140         D3D_FEATURE_LEVEL_10_0
00141     };
00142
00143     // Create the Direct3D 11 API device object and a corresponding context.
00144     ComPtr<ID3D11Device> device;
00145     ComPtr<ID3D11DeviceContext> context;
00146
00147     const D3D_DRIVER_TYPE driverType = m_dxgiAdapter == nullptr ? D3D_DRIVER_TYPE_HARDWARE : D3D_DRIVER_TYPE_UNKNOWN;
00148     const HRESULT hr = D3D11CreateDevice(
00149         m_dxgiAdapter.Get(),        // Either nullptr, or the primary adapter determined by Windows Holographic.
00150         driverType,                 // Create a device using the hardware graphics driver.
00151         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00152         creationFlags,              // Set debug and Direct2D compatibility flags.
00153         featureLevels,              // List of feature levels this app can support.
00154         ARRAYSIZE(featureLevels),   // Size of the list above.
00155         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00156         &device,                    // Returns the Direct3D device created.
00157         &m_d3dFeatureLevel,         // Returns feature level of device created.
00158         &context                    // Returns the device immediate context.
00159     );
00160
00161     if (FAILED(hr))
00162     {
00163         // If the initialization fails, fall back to the WARP device.
00164         // For more information on WARP, see:
00165         // http://go.microsoft.com/fwlink/?LinkId=286690
00166         winrt::check_hresult(
00167             D3D11CreateDevice(
00168                 nullptr,              // Use the default DXGI adapter for WARP.
00169                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00170                 0,
00171                 creationFlags,
00172                 featureLevels,
00173                 ARRAYSIZE(featureLevels),
00174                 D3D11_SDK_VERSION,
00175                 &device,
00176                 &m_d3dFeatureLevel,
00177                 &context
00178             ));
00179     }
00180
00181     // Store pointers to the Direct3D device and immediate context.
00182     winrt::check_hresult(device.As(&m_d3dDevice));
00183     winrt::check_hresult(context.As(&m_d3dContext));
00184
00185     // Acquire the DXGI interface for the Direct3D device.
00186     ComPtr<IDXGIDevice3> dxgiDevice;
00187     winrt::check_hresult(m_d3dDevice.As(&dxgiDevice));
00188
00189     // Wrap the native device using a WinRT interop object.
00190     winrt::com_ptr<::IInspectable> object;
00191     winrt::check_hresult(CreateDirect3D11DeviceFromDXGIDevice(
00192         dxgiDevice.Get(),
00193         object.put()));
00194     m_d3dInteropDevice = object.as<IDirect3DDevice>();
00195
00196     // Cache the DXGI adapter.
00197     // This is for the case of no preferred DXGI adapter, or fallback to WARP.
00198     ComPtr<IDXGIAdapter> dxgiAdapter;
00199     winrt::check_hresult(dxgiDevice->GetAdapter(&dxgiAdapter));
00200     winrt::check_hresult(dxgiAdapter.As(&m_dxgiAdapter));
00201
00202     // Check for device support for the optional feature that allows setting the render target array index from the vertex shader stage.
00203     D3D11_FEATURE_DATA_D3D11_OPTIONS3 options;
00204     m_d3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS3, &options, sizeof(options));
00205     if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer)
00206     {
00207         m_supportsVprt = true;
00208     }
00209 }
00210
00211 // Validates the back buffer for each HolographicCamera and recreates
00212 // resources for back buffers that have changed.
00213 // Locks the set of holographic camera resources until the function exits.
00214 void DX::DeviceResources::EnsureCameraResources(
00215     HolographicFrame frame,
00216     HolographicFramePrediction prediction)
00217 {
00218     UseHolographicCameraResources<void>([this, frame, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00219     {
00220         for (HolographicCameraPose const& cameraPose : prediction.CameraPoses())
00221         {
00222             HolographicCameraRenderingParameters renderingParameters = frame.GetRenderingParameters(cameraPose);
00223             CameraResources* pCameraResources = cameraResourceMap[cameraPose.HolographicCamera().Id()].get();
00224
00225             pCameraResources->CreateResourcesForBackBuffer(this, renderingParameters);
00226         }
00227     });
00228 }
00229
00230 // Prepares to allocate resources and adds resource views for a camera.
00231 // Locks the set of holographic camera resources until the function exits.
00232 void DX::DeviceResources::AddHolographicCamera(HolographicCamera camera)
00233 {
00234     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00235     {
00236         cameraResourceMap[camera.Id()] = std::make_unique<CameraResources>(camera);
00237     });
00238 }
00239
00240 // Deallocates resources for a camera and removes the camera from the set.
00241 // Locks the set of holographic camera resources until the function exits.
00242 void DX::DeviceResources::RemoveHolographicCamera(HolographicCamera camera)
00243 {
00244     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00245     {
00246         CameraResources* pCameraResources = cameraResourceMap[camera.Id()].get();
00247
00248         if (pCameraResources != nullptr)
00249         {
00250             pCameraResources->ReleaseResourcesForBackBuffer(this);
00251             cameraResourceMap.erase(camera.Id());
00252         }
00253     });
00254 }
00255
00256 // Recreate all device resources and set them back to the current state.
00257 // Locks the set of holographic camera resources until the function exits.
00258 void DX::DeviceResources::HandleDeviceLost()
00259 {
00260     if (m_deviceNotify != nullptr)
00261     {
00262         m_deviceNotify->OnDeviceLost();
00263     }
00264
00265     UseHolographicCameraResources<void>([this](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00266     {
00267         for (auto& pair : cameraResourceMap)
00268         {
00269             CameraResources* pCameraResources = pair.second.get();
00270             pCameraResources->ReleaseResourcesForBackBuffer(this);
00271         }
00272     });
00273
00274     InitializeUsingHolographicSpace();
00275
00276     if (m_deviceNotify != nullptr)
00277     {
00278         m_deviceNotify->OnDeviceRestored();
00279     }
00280 }
00281
00282 // Register our DeviceNotify to be informed on device lost and creation.
00283 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00284 {
00285     m_deviceNotify = deviceNotify;
00286 }
00287
00288 // Call this method when the app suspends. It provides a hint to the driver that the app
00289 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00290 void DX::DeviceResources::Trim()
00291 {
00292     m_d3dContext->ClearState();
00293
00294     ComPtr<IDXGIDevice3> dxgiDevice;
00295     winrt::check_hresult(m_d3dDevice.As(&dxgiDevice));
00296     dxgiDevice->Trim();
00297 }
00298
00299 // Present the contents of the swap chain to the screen.
00300 // Locks the set of holographic camera resources until the function exits.
00301 void DX::DeviceResources::Present(HolographicFrame frame)
00302 {
00303     // By default, this API waits for the frame to finish before it returns.
00304     // Holographic apps should wait for the previous frame to finish before
00305     // starting work on a new frame. This allows for better results from
00306     // holographic frame predictions.
00307     HolographicFramePresentResult presentResult = frame.PresentUsingCurrentPrediction();
00308
00309     // The PresentUsingCurrentPrediction API will detect when the graphics device
00310     // changes or becomes invalid. When this happens, it is considered a Direct3D
00311     // device lost scenario.
00312     if (presentResult == HolographicFramePresentResult::DeviceRemoved)
00313     {
00314         // The Direct3D device, context, and resources should be recreated.
00315         HandleDeviceLost();
00316     }
00317 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampArray/cppwinrt/Scenario2_Effects.cpp Source File

  • LampArray
  • cppwinrt

Scenario2_Effects.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013
00014 #include "Scenario2_Effects.h"
00015 #include "Scenario2_Effects.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace winrt::Microsoft::Graphics::Canvas;
00019 using namespace winrt::Windows::Devices::Enumeration;
00020 using namespace winrt::Windows::Devices::Lights;
00021 using namespace winrt::Windows::Devices::Lights::Effects;
00022 using namespace winrt::Windows::Foundation;
00023 using namespace winrt::Windows::Graphics::Imaging;
00024 using namespace winrt::Windows::Storage;
00025 using namespace winrt::Windows::Storage::Streams;
00026 using namespace winrt::Windows::UI;
00027 using namespace winrt::Windows::UI::Xaml;
00028 using namespace winrt::Windows::UI::Xaml::Controls::Primitives;
00029 using namespace winrt::Windows::UI::Xaml::Media::Imaging;
00030 using namespace winrt::Windows::UI::Xaml::Navigation;
00031
00032 namespace
00033 {
00034     inline constexpr TimeSpan EffectUpdateInterval = std::chrono::milliseconds(33);
00035     inline constexpr TimeSpan ColorRampDuration = std::chrono::milliseconds(500);
00036     inline constexpr int CustomEffectFrameCount = 30;
00037     inline constexpr int GeneratedBitmapEffectFrameCount = 60;
00038 }
00039
00040 namespace winrt::SDKTemplate::implementation
00041 {
00042     Scenario2_Effects::Scenario2_Effects()
00043     {
00044         InitializeComponent();
00045     }
00046
00047     void Scenario2_Effects::OnNavigatedTo(NavigationEventArgs const&)
00048     {
00049         UpdateLampArrayList();
00050
00051         // Start watching for newly attached LampArrays.
00052         m_deviceWatcher = DeviceInformation::CreateWatcher(LampArray::GetDeviceSelector());
00053
00054         m_deviceAddedRevoker = m_deviceWatcher.Added(winrt::auto_revoke, { get_weak(), &Scenario2_Effects::Watcher_Added });
00055         m_deviceRemovedRevoker = m_deviceWatcher.Removed(winrt::auto_revoke, { get_weak(), &Scenario2_Effects::Watcher_Removed });
00056
00057         m_deviceWatcher.Start();
00058     }
00059
00060     void Scenario2_Effects::OnNavigatedFrom(NavigationEventArgs const&)
00061     {
00062         m_deviceWatcher.Stop();
00063
00064         // When changing scenarios, stop our effects to prevent them from interfering with the new scenario.
00065         CleanupPreviousEffect();
00066     }
00067
00068     winrt::fire_and_forget Scenario2_Effects::Watcher_Added(DeviceWatcher const&, DeviceInformation const& deviceInformation)
00069     {
00070         auto lifetime = get_strong();
00071
00072         auto info = std::make_unique<LampArrayInfo>(
00073             deviceInformation.Id(),
00074             deviceInformation.Name(),
00075             LampArray::FromIdAsync(deviceInformation.Id()).get());
00076
00077         // DeviceWatcher events are invoked on a background thread.
00078         // We need to switch to the foreground thread to update our app UI
00079         // and access member variables without race conditions.
00080
00081         co_await winrt::resume_foreground(Dispatcher());
00082
00083         if (info->lampArray == nullptr)
00084         {
00085             // A LampArray was found, but Windows couldn't initialize it.
00086             // This suggests a device error.
00087             rootPage.NotifyUser(L"Problem with LampArray " + info->displayName + L".", NotifyType::ErrorMessage);
00088             co_return;
00089         }
00090
00091         // Initial condition for the new LampArray is all lights off.
00092         info->lampArray.SetColor(Colors::Black());
00093
00094         // Set up the AvailabilityChanged event callback for being notified whether this process can control
00095         // RGB lighting for the newly attached LampArray.
00096         info->availabilityChangedRevoker = info->lampArray.AvailabilityChanged(winrt::auto_revoke, { this, &Scenario2_Effects::LampArray_AvailabilityChanged });
00097
00098         m_attachedLampArrays.push_back(std::move(info));
00099
00100         UpdateLampArrayList();
00101     }
00102
00103     winrt::fire_and_forget Scenario2_Effects::Watcher_Removed(DeviceWatcher const&, DeviceInformationUpdate deviceInformationUpdate)
00104     {
00105         auto lifetime = get_strong();
00106
00107         // DeviceWatcher events are invoked on a background thread.
00108         // We need to switch to the foreground thread to update our app UI
00109         // and access member variables without race conditions.
00110         co_await winrt::resume_foreground(Dispatcher());
00111
00112         m_attachedLampArrays.erase(
00113             std::remove_if(m_attachedLampArrays.begin(), m_attachedLampArrays.end(), [id = deviceInformationUpdate.Id()](auto&& info) { return info->id == id; }),
00114             m_attachedLampArrays.end());
00115
00116         UpdateLampArrayList();
00117     }
00118
00119     // The AvailabilityChanged event will fire when this calling process gains or loses control of RGB lighting
00120     // for the specified LampArray.
00121     winrt::fire_and_forget Scenario2_Effects::LampArray_AvailabilityChanged(const LampArray& sender, const IInspectable&)
00122     {
00123         co_await winrt::resume_foreground(Dispatcher());
00124
00125         UpdateLampArrayList();
00126     }
00127
00128     void Scenario2_Effects::UpdateLampArrayList()
00129     {
00130         std::wstring message = std::wstring(L"Attached LampArrays: ") + std::to_wstring(m_attachedLampArrays.size()) + L"\n";
00131
00132         for (auto&& info : m_attachedLampArrays)
00133         {
00134             message += L"\t" + info->displayName + L" ("
00135                 + std::to_wstring(info->lampArray.LampArrayKind()) + L", " + std::to_wstring(info->lampArray.LampCount()) + L" lamps, "
00136                 + std::wstring(info->lampArray.IsAvailable() ? L"Available" : L"Unavailable") + L")\n";
00137         }
00138
00139         LampArraysSummary().Text(message);
00140     }
00141
00142     // This method will be called when a new effect is selected. It will stop any running
00143     // LampArrayEffectPlaylists in progress and reset LampArray state in preparation for the new effect.
00144     void Scenario2_Effects::CleanupPreviousEffect()
00145     {
00146         // Clear the bitmap image in the app UI, as it is no longer current.
00147         ImageBitmap().Source(nullptr);
00148
00149         // Passing all the playlists to a single call to StopAll will stop them
00150         // simultaneously across all attached LampArrays.
00151         LampArrayEffectPlaylist::StopAll(m_readyPlaylists);
00152         m_readyPlaylists = m_emptyList;
00153     }
00154
00155 #pragma region Static bitmap effect
00156     winrt::fire_and_forget Scenario2_Effects::StaticBitmapButton_Click(IInspectable const&, RoutedEventArgs const&)
00157     {
00158         auto lifetime = get_strong();
00159
00160         CleanupPreviousEffect();
00161
00162         // This effect will display a specified bitmap image on all connected LampArrays.
00163         // The image will be stretched and scaled to fit the Lamp dimensions of each LampArray.
00164
00165         // First, open the desired bitmap file and convert it to a SoftwareBitmap
00166         auto bitmapUri = Uri(L"ms-appx:///Assets/grapes.jpg");
00167
00168         StorageFile file = co_await StorageFile::GetFileFromApplicationUriAsync(bitmapUri);
00169         IRandomAccessStream stream = co_await file.OpenAsync(FileAccessMode::Read);
00170         BitmapDecoder decoder = co_await BitmapDecoder::CreateAsync(stream);
00171         SoftwareBitmap bitmap = co_await decoder.GetSoftwareBitmapAsync();
00172         stream.Close();
00173
00174         // Show our bitmap image in the app UI
00175         ImageBitmap().Source(BitmapImage(bitmapUri));
00176
00177         // Gather the new LampArrayEffectPlaylists in this collection so we can start them simultaneously.
00178         std::vector<LampArrayEffectPlaylist> playlists;
00179
00180         // Create the effect playlist for each LampArray and add it to the collection.
00181         for (auto&& info : m_attachedLampArrays)
00182         {
00183             LampArrayBitmapEffect bitmapEffect(info->lampArray, GetLampArrayIndices(info->lampArray));
00184
00185             // We want to run this effect until is stopped. For the purposes of this sample,
00186             // set the effect Duration to run as long as possible.
00187             bitmapEffect.Duration(TimeSpan::max());
00188
00189             // The UpdateInterval specifies how frequently we want to receive our callback function.
00190             // Since this effect will display a static image, we only need to update once.
00191             // Set this interval to be the same as the effect duration.
00192             bitmapEffect.UpdateInterval(TimeSpan::max());
00193
00194             // Set the event handler for our effect. Use a helper function to
00195             // to specify a bitmap to display on the device.
00196             bitmapEffect.BitmapRequested([bitmap](auto&&, auto&& args)
00197             {
00198                 StaticBitmapEffect_BitmapRequested(bitmap, args);
00199             });
00200
00201             // Create a playlist consisting of our static bitmap effect.
00202             LampArrayEffectPlaylist playlist;
00203             playlist.Append(bitmapEffect);
00204
00205             // Add it to the list of playlists to start simultaneously.
00206             playlists.push_back(playlist);
00207         }
00208
00209         // Start the newly created effect playlists simultaneously.
00210         auto playlistsView = winrt::single_threaded_vector(std::move(playlists)).GetView();
00211         LampArrayEffectPlaylist::StartAll(playlistsView);
00212
00213         // Remember the playlists so we can stop them later.
00214         m_readyPlaylists = playlistsView;
00215     }
00216
00217     // Helper function for BitmapRequested event handler that
00218     // specifies the bitmap to display on the device.
00219     // The frequency of the effect callback is customizable.
00220     // The frequency of the event is customizable.
00221     // As configured above when setting up the static bitmap effect, this event will
00222     // be raised only once per effect iteration, since we set the update interval
00223     // equal to the effect duration.
00224     void Scenario2_Effects::StaticBitmapEffect_BitmapRequested(
00225         SoftwareBitmap const& bitmap,
00226         LampArrayBitmapRequestedEventArgs const& args)
00227     {
00228         // In a BitmapRequested handler, we can change the bitmap here to produce animations.
00229         // For the static bitmap effect, show the same image each time.
00230         args.UpdateBitmap(bitmap);
00231     }
00232 #pragma endregion
00233
00234 #pragma region Fade effect
00235     void Scenario2_Effects::FadeButton_Click(IInspectable const&, RoutedEventArgs const&)
00236     {
00237         CleanupPreviousEffect();
00238
00239         // This effect will set each Lamp to a random color and blink all Lamps simultaneously.
00240         // LampArrayBlinkEffect only supports a single color at a time. To create the desired effect with
00241         // different colors for each Lamp, we will create a separate LampArrayBlinkEffect for each Lamp,
00242         // specifying that we only want the effect to apply to a single Lamp index.
00243         // We will then add each Lamp effect to the playlist for its corresponding LampArray and configure the
00244         // playlist to run its effects simultaneously instead of sequentially.
00245
00246         // Gather the new LampArrayEffectPlaylists in this collection so we can start them simultaneously.
00247         std::vector<LampArrayEffectPlaylist> playlists;
00248
00249         auto uniform_byte = std::uniform_int_distribution(0, 255);
00250
00251         // Create the effect playlist for each LampArray and add it to the collection.
00252         for (auto&& info : m_attachedLampArrays)
00253         {
00254             LampArrayEffectPlaylist playlist;
00255
00256             // Configure the playlist to run the effects simultaneously.
00257             // This will result in all Lamps for this LampArray blinking in unison,
00258             // even though their colors will be different.
00259             playlist.EffectStartMode(LampArrayEffectStartMode::Simultaneous);
00260
00261             for (int i = 0; i < info->lampArray.LampCount(); i++)
00262             {
00263                 // Generate a color for each Lamp by choosing a random Red/Green/Blue combination.
00264                 auto color = ColorHelper::FromArgb(
00265                     std::numeric_limits<uint8_t>::max(), // Maximum alpha makes it opaque
00266                     (uint8_t)(uniform_byte(m_random)),
00267                     (uint8_t)(uniform_byte(m_random)),
00268                     (uint8_t)(uniform_byte(m_random)));
00269
00270                 // Create the effect and apply it to a single Lamp.
00271                 LampArrayBlinkEffect blinkEffect(info->lampArray, { i });
00272
00273                 blinkEffect.Color(color);
00274
00275                 // We can adjust the timing of the LampArrayBlinkEffect using these properties.
00276                 // Specify how long it should take for the full color to fade in from off/Black to peak intensity.
00277                 blinkEffect.AttackDuration(std::chrono::milliseconds(300));
00278
00279                 // Specify how long to display the color at peak intensity.
00280                 blinkEffect.SustainDuration(std::chrono::milliseconds(500));
00281
00282                 // Specify how long it should take for the full color to fade out from peak intensity to off/Black.
00283                 blinkEffect.DecayDuration(std::chrono::milliseconds(800));
00284
00285                 // Specify how long the Lamps should stay dark between blink repetitions.
00286                 blinkEffect.RepetitionDelay(std::chrono::milliseconds(100));
00287
00288                 // Repeat the blink sequence indefinitely until the effect playlist is stopped.
00289                 blinkEffect.RepetitionMode(LampArrayRepetitionMode::Forever);
00290
00291                 playlist.Append(blinkEffect);
00292
00293                 // Add it to the list of playlists to start simultaneously.
00294                 playlists.push_back(playlist);
00295             }
00296         }
00297
00298         // Start the newly created effect playlists simultaneously.
00299         auto playlistsView = winrt::single_threaded_vector(std::move(playlists)).GetView();
00300         LampArrayEffectPlaylist::StartAll(playlistsView);
00301
00302         // Remember the playlists so we can stop them later.
00303         m_readyPlaylists = playlistsView;
00304     }
00305 #pragma endregion
00306
00307 #pragma region Custom effect
00308     // Windows.Devices.Lights.Effects contains several built-in effect types. The LampArrayCustomEffect is provided for
00309     // greater customization of lighting beyond these simple effects. It enables the SetColor controls of LampArray to
00310     // be integrated and scheduled with other effects and effect playlists.
00311     // This sample will demonstrate using LampArrayCustomEffect to display a simple lighting animation.
00312     void Scenario2_Effects::CustomEffectButton_Click(IInspectable const&, RoutedEventArgs const&)
00313     {
00314         CleanupPreviousEffect();
00315
00316         // This effect will use LampArrayCustomEffect to create a wave-like animation.
00317         // Lamps will turn on from left to right across the LampArray, then turn off in a similar manner.
00318
00319         // Gather the new LampArrayEffectPlaylists in this collection so we can start them simultaneously.
00320         std::vector<LampArrayEffectPlaylist> playlists;
00321
00322         // Create the effect playlist for each LampArray and add it to the collection.
00323         for (auto&& info : m_attachedLampArrays)
00324         {
00325             LampArray const& lampArray = info->lampArray;
00326             std::vector<int> indices = GetLampArrayIndices(lampArray);
00327             float boundingBoxWidth = lampArray.BoundingBox().x;
00328             // Avoid division by zero when calculating normalized positions.
00329             if (boundingBoxWidth == 0.0f)
00330             {
00331                 boundingBoxWidth = 1.0f;
00332             }
00333             auto state = std::make_unique<CustomEffectState>(lampArray);
00334
00335             // Calculate the normalized position of each lamp.
00336             for (int i = 0; i < state->lampNormalizedX.size(); i++)
00337             {
00338                 auto lampInfo = lampArray.GetLampInfo(i);
00339                 state->lampNormalizedX[i] = lampInfo.Position().x / boundingBoxWidth;
00340             }
00341
00342             LampArrayCustomEffect customEffect = LampArrayCustomEffect(lampArray, indices);
00343
00344             // We want to run this effect until is stopped. For the purposes of this sample,
00345             // set the effect Duration to run as long as possible.
00346             customEffect.Duration(TimeSpan::max());
00347
00348             // The UpdateInterval specifies how frequently we want to receive our callback function.
00349             // For our animation, set this interval to 33 milliseconds, which equates to approximately 30 frames per second.
00350             customEffect.UpdateInterval(EffectUpdateInterval);
00351
00352             // This event handler will be called on every frame to update the animation.
00353             customEffect.UpdateRequested([state = std::move(state)](auto&&, auto&& args)
00354             {
00355                 CustomEffect_UpdateRequested(state.get(), args);
00356             });
00357
00358             // Create a playlist consisting of our wave effect.
00359             LampArrayEffectPlaylist playlist;
00360             playlist.Append(customEffect);
00361
00362             // Add it to the list of playlists to start simultaneously.
00363             playlists.push_back(playlist);
00364         }
00365
00366         // Start the newly created effect playlists.
00367         auto playlistsView = winrt::single_threaded_vector(std::move(playlists)).GetView();
00368         LampArrayEffectPlaylist::StartAll(playlistsView);
00369
00370         // Remember the playlists so we can stop them later.
00371         m_readyPlaylists = playlistsView;
00372     }
00373
00374     // Helper for the LampArrayCustomEffect.UpdateRequested event, called periodically at the requested UpdateInterval.
00375     // This enables more complex lighting patterns, such as animations. It also supports integration and scheduling with
00376     // other effects and effect playlists.
00377     // As configured above, this callback will be invoked every 33 milliseconds, or about 30 frames per second.
00378     void Scenario2_Effects::CustomEffect_UpdateRequested(
00379         CustomEffectState* state,
00380         winrt::Windows::Devices::Lights::Effects::LampArrayUpdateRequestedEventArgs const& args)
00381     {
00382         // Update the Lamp colors for the current frame. Start by calculating how far into the current iteration we are.
00383         // We will use this to mark how far across the LampArray bounding box the effect has reached.
00384         double effectProgress = ((state->frameNumber + 1) / static_cast<double>(CustomEffectFrameCount));
00385
00386         // If Lamps were being turned off in the previous iteration, turn them on now, and vice versa.
00387         Color color = state->isColorOn ? state->color : Colors::Black();
00388
00389         for (unsigned i = 0; i < state->lampNormalizedX.size(); i++)
00390         {
00391             // All Lamps that are to the left of our marker (normalized to the LampArray bounding box width)
00392             // should have their states updated.
00393             if (state->lampNormalizedX[i] <= effectProgress)
00394             {
00395                 state->lampColors[i] = color;
00396             }
00397         }
00398
00399         // Apply the Lamp states to the LampArray.
00400         args.SetColorsForIndices(state->lampColors, GetLampArrayIndices(state->lampArray));
00401
00402         // Increment our frame counter, with wraparound if we've reached the frame limit.
00403         // Also update whether the lamps should be turned on or off for the next iteration.
00404         if (++state->frameNumber == CustomEffectFrameCount)
00405         {
00406             state->frameNumber = 0;
00407             state->isColorOn = !state->isColorOn;
00408         }
00409     }
00410 #pragma endregion
00411
00412 #pragma region Generated bitmap effect
00413     // This effect will use Win2D to create a simple animation. On each frame, we will
00414     // generate a bitmap image and apply it to the entire LampArray.
00415     // The effect illustrates dynamically creating a bitmap image and using it in a lighting effect.
00416     // LampArrayBitmapEffect could be used for in-game lighting and/or integration with 2D graphics libraries.
00417     void Scenario2_Effects::GeneratedBitmapButton_Click(IInspectable const&, RoutedEventArgs const&)
00418     {
00419         CleanupPreviousEffect();
00420
00421         // Gather the new LampArrayEffectPlaylists in this collection so we can start them simultaneously.
00422         std::vector<LampArrayEffectPlaylist> playlists;
00423
00424         // Create the effect playlist for each LampArray and add it to the collection.
00425         for (auto&& info : m_attachedLampArrays)
00426         {
00427             auto state = std::make_unique<GeneratedBitmapState>();
00428
00429             auto generatedBitmapEffect = LampArrayBitmapEffect{ info->lampArray, GetLampArrayIndices(info->lampArray) };
00430
00431             // We want to run this effect until is stopped. For the purposes of this sample,
00432             // set the effect Duration to run as long as possible.
00433             generatedBitmapEffect.Duration(TimeSpan::max());
00434
00435             // The UpdateInterval specifies how frequently we want to receive our callback function.
00436             // For our animation, set this interval to 33 milliseconds, which equates to approximately 30 frames per second.
00437             generatedBitmapEffect.UpdateInterval(EffectUpdateInterval);
00438
00439             Size suggestedSize = generatedBitmapEffect.SuggestedBitmapSize();
00440             state->bitmapWidth = static_cast<uint32_t>(suggestedSize.Width);
00441             state->bitmapHeight = static_cast<uint32_t>(suggestedSize.Height);
00442
00443             // The size of the square is half the height or half the width, whichever is smaller.
00444             state->squareLength = std::min(suggestedSize.Height, suggestedSize.Width) / 2.0f;
00445
00446             // Vertically center the square.
00447             state->squareY = (suggestedSize.Height - state->squareLength) / 2.0f;
00448
00449             // Setup our Win2D helper objects.
00450             state->canvasDevice = CanvasDevice::GetSharedDevice();
00451
00452             state->offscreenCanvas = CanvasRenderTarget(state->canvasDevice, suggestedSize.Width, suggestedSize.Height, 96.0f);
00453
00454             state->offscreenDrawingSession = state->offscreenCanvas.CreateDrawingSession();
00455
00456             // The generated bitmap encompasses the entire LampArray
00457             state->squareBitmap = SoftwareBitmap(BitmapPixelFormat::Bgra8, state->bitmapWidth, state->bitmapHeight, BitmapAlphaMode::Premultiplied);
00458
00459             state->squareBuffer = Buffer(state->bitmapWidth * state->bitmapHeight * 4);
00460
00461             // This event handler will be called on every frame to update the bitmap to display on the device.
00462             generatedBitmapEffect.BitmapRequested([state = std::move(state)](auto&&, auto&& args)
00463             {
00464                 GeneratedBitmapEffect_UpdateRequested(state.get(), args);
00465             });
00466
00467             // Create a playlist consisting of our bitmap effect.
00468             LampArrayEffectPlaylist playlist;
00469             playlist.Append(generatedBitmapEffect);
00470
00471             // Add it to the list of playlists to start simultaneously.
00472             playlists.push_back(playlist);
00473         }
00474
00475         // Start the newly created effect playlists simultaneously.
00476         auto playlistsView = winrt::single_threaded_vector(std::move(playlists)).GetView();
00477         LampArrayEffectPlaylist::StartAll(playlistsView);
00478
00479         // Remember the playlists so we can stop them later.
00480         m_readyPlaylists = playlistsView;
00481     }
00482
00483     // Callback function that allows us to specify a bitmap to display on the device.
00484     // The frequency of the effect callback is customizable.
00485     // As configured above when setting up the generated bitmap effect, this will be invoked
00486     // every 33 milliseconds, or approximately 30 frames per second.
00487     // To demonstrate using a LampArrayBitmapEffect to perform lighting animations,
00488     // this callback will create an animation of a red rectangle moving left to right
00489     // across a blue background.
00490     void Scenario2_Effects::GeneratedBitmapEffect_UpdateRequested(
00491         GeneratedBitmapState* state,
00492         LampArrayBitmapRequestedEventArgs const& args)
00493     {
00494         // Draw a red rectangle on a blue background.
00495         state->offscreenDrawingSession.Clear(Colors::Blue());
00496
00497         // The rectangle starts out just beyond the left edge of the keyboard,
00498         // then moves to the right until it just leaves the keyboard,
00499         // and then repeats.
00500         float squareX = static_cast<float>(state->frameNumber * (state->bitmapWidth + state->squareLength) / GeneratedBitmapEffectFrameCount) - state->squareLength;
00501         state->offscreenDrawingSession.FillRectangle(
00502             squareX,
00503             state->squareY,
00504             state->squareLength,
00505             state->squareLength,
00506             Colors::Red());
00507
00508         state->offscreenDrawingSession.Flush();
00509
00510         // Apply the generated bitmap to the LampArray.
00511         state->offscreenCanvas.GetPixelBytes(state->squareBuffer);
00512         state->squareBitmap.CopyFromBuffer(state->squareBuffer);
00513
00514         args.UpdateBitmap(state->squareBitmap);
00515
00516         // Advance to the next frame for the next iteration.
00517         if (++state->frameNumber == GeneratedBitmapEffectFrameCount)
00518         {
00519             state->frameNumber = 0;
00520         }
00521     }
00522 #pragma endregion
00523
00524 #pragma region Color cycle effect
00525     void Scenario2_Effects::CycleButton_Click(IInspectable const&, RoutedEventArgs const&)
00526     {
00527         CleanupPreviousEffect();
00528
00529         // This effect will use LampArrayColorRampEffect to perform a rainbow cycle pattern on all Lamps.
00530         // We will do this for each LampArray by creating a LampArrayEffectPlaylist containing four LampArrayColorRampEffects.
00531         // Each effect will blend from the previously set color to a new color over a 500ms interval.
00532
00533         // Gather the new LampArrayEffectPlaylists in this collection so we can start them simultaneously.
00534         std::vector<LampArrayEffectPlaylist> playlists;
00535
00536         // Create the effect playlist for each LampArray and add it to the collection.
00537         for (auto&& info : m_attachedLampArrays)
00538         {
00539             // Create a playlist to hold our effects.
00540             LampArrayEffectPlaylist playlist;
00541             playlist.RepetitionMode(LampArrayRepetitionMode::Forever);
00542             playlist.EffectStartMode(LampArrayEffectStartMode::Sequential);
00543
00544             auto indices = GetLampArrayIndices(info->lampArray);
00545
00546             LampArrayColorRampEffect redRampEffect{ info->lampArray, indices };
00547             redRampEffect.Color(Colors::Red());
00548             redRampEffect.RampDuration(ColorRampDuration);
00549             redRampEffect.CompletionBehavior(LampArrayEffectCompletionBehavior::KeepState);
00550             playlist.Append(redRampEffect);
00551
00552             LampArrayColorRampEffect yellowRampEffect{ info->lampArray, indices };
00553             yellowRampEffect.Color(Colors::Yellow());
00554             yellowRampEffect.RampDuration(ColorRampDuration);
00555             yellowRampEffect.CompletionBehavior(LampArrayEffectCompletionBehavior::KeepState);
00556             playlist.Append(yellowRampEffect);
00557
00558             LampArrayColorRampEffect greenRampEffect{ info->lampArray, indices };
00559             greenRampEffect.Color(Colors::Green());
00560             greenRampEffect.RampDuration(ColorRampDuration);
00561             greenRampEffect.CompletionBehavior(LampArrayEffectCompletionBehavior::KeepState);
00562             playlist.Append(greenRampEffect);
00563
00564             LampArrayColorRampEffect blueRampEffect{ info->lampArray, indices };
00565             blueRampEffect.Color(Colors::Blue());
00566             blueRampEffect.RampDuration(ColorRampDuration);
00567             blueRampEffect.CompletionBehavior(LampArrayEffectCompletionBehavior::KeepState);
00568             playlist.Append(blueRampEffect);
00569
00570             // Add this multi-effect playlist to the list of playlists to start simultaneously.
00571             playlists.push_back(playlist);
00572         }
00573
00574         // Start the newly created effect playlists simultaneously.
00575         auto playlistsView = winrt::single_threaded_vector(std::move(playlists)).GetView();
00576         LampArrayEffectPlaylist::StartAll(playlistsView);
00577
00578         // Remember the playlists so we can stop them later.
00579         m_readyPlaylists = playlistsView;
00580     }
00581 #pragma endregion
00582
00583     void Scenario2_Effects::PauseButton_Click(IInspectable const&, RoutedEventArgs const&)
00584     {
00585         LampArrayEffectPlaylist::PauseAll(m_readyPlaylists);
00586     }
00587
00588     void Scenario2_Effects::PlayButton_Click(IInspectable const&, RoutedEventArgs const&)
00589     {
00590         LampArrayEffectPlaylist::StartAll(m_readyPlaylists);
00591     }
00592
00593     void Scenario2_Effects::StopButton_Click(IInspectable const&, RoutedEventArgs const&)
00594     {
00595         LampArrayEffectPlaylist::StopAll(m_readyPlaylists);
00596     }
00597
00598     // Helper function that returns all indices of a LampArray in order.
00599     // Used when we want to apply an effect to all Lamps on a LampArray.
00600     std::vector<int> Scenario2_Effects::GetLampArrayIndices(winrt::Windows::Devices::Lights::LampArray const& lampArray)
00601     {
00602         std::vector<int> indices(lampArray.LampCount());
00603         std::iota(indices.begin(), indices.end(), 0);
00604         return indices;
00605     }
00606 }
Generated on Fri Nov 15 2024 22:20:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_DetectInWebcam Member List

This is the complete list of members for Scenario2_DetectInWebcam, including all inherited members.
CameraSnapshotButton_Click(object sender, RoutedEventArgs e) | Scenario2_DetectInWebcam | [inline, private]
CameraStreamingButton_Click(object sender, RoutedEventArgs e) | Scenario2_DetectInWebcam | [inline, private]
ChangeScenarioStateAsync(ScenarioState newState) | Scenario2_DetectInWebcam | [inline, private]
currentState | Scenario2_DetectInWebcam | [private]
faceDetector | Scenario2_DetectInWebcam | [private]
mediaCapture | Scenario2_DetectInWebcam | [private]
MediaCapture_CameraStreamStateChanged(MediaCapture sender, object args) | Scenario2_DetectInWebcam | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_DetectInWebcam | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_DetectInWebcam | [inline, protected]
OnSuspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) | Scenario2_DetectInWebcam | [inline, private]
rootPage | Scenario2_DetectInWebcam | [private]
Scenario2_DetectInWebcam() | Scenario2_DetectInWebcam | [inline]
ScenarioState enum name | Scenario2_DetectInWebcam | [private]
SetupVisualization(WriteableBitmap displaySource, IList< DetectedFace > foundFaces) | Scenario2_DetectInWebcam | [inline, private]
ShutdownWebcamAsync() | Scenario2_DetectInWebcam | [inline, private]
SnapshotCanvas_SizeChanged(object sender, SizeChangedEventArgs e) | Scenario2_DetectInWebcam | [inline, private]
StartWebcamStreamingAsync() | Scenario2_DetectInWebcam | [inline, private]
TakeSnapshotAndFindFacesAsync() | Scenario2_DetectInWebcam | [inline, private]
videoProperties | Scenario2_DetectInWebcam | [private]
Generated on Fri Nov 15 2024 22:23:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_NetworkConnectivityChanges Member List

This is the complete list of members for Scenario3_NetworkConnectivityChanges, including all inherited members.
m_isNetworkStatusUpdatePending | Scenario3_NetworkConnectivityChanges | [private]
m_isUpdatingNetworkStatus | Scenario3_NetworkConnectivityChanges | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario3_NetworkConnectivityChanges |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario3_NetworkConnectivityChanges |
OnNetworkStatusChanged(Windows::Foundation::IInspectable const &) | Scenario3_NetworkConnectivityChanges | [private]
OptInOutComboBox_SelectionChanged(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::Controls::SelectionChangedEventArgs const &) | Scenario3_NetworkConnectivityChanges |
RegisterNetworkStatusChanged() | Scenario3_NetworkConnectivityChanges | [private]
RegisterUnregisterButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_NetworkConnectivityChanges |
Scenario3_NetworkConnectivityChanges() | Scenario3_NetworkConnectivityChanges |
UnregisterNetworkStatusChanged() | Scenario3_NetworkConnectivityChanges | [private]
UpdateButtonStates() | Scenario3_NetworkConnectivityChanges | [private]
UpdateNetworkStatus() | Scenario3_NetworkConnectivityChanges | [private]
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/pch.cpp Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Unicode/cppwinrt/SampleConfiguration.h Source File

  • Unicode
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/MrcEffectDefinitions/MrcAudioEffectDefinition.h Source File

  • HolographicMixedRealityCapture
  • cpp
  • MrcEffectDefinitions

MrcAudioEffectDefinition.h

Go to the documentation of this file.
00001 #pragma once
00002 // This class provides an IAudioEffectDefinition which can be used
00003 // to configure and create a MixedRealityCaptureAudioEffect
00004 // object. See https://developer.microsoft.com/en-us/windows/holographic/mixed_reality_capture_for_developers#creating_a_custom_mixed_reality_capture_.28mrc.29_recorder
00005 // for more information about the effect definition properties.
00006
00007 #define RUNTIMECLASS_MIXEDREALITYCAPTURE_AUDIO_EFFECT L"Windows.Media.MixedRealityCapture.MixedRealityCaptureAudioEffect"
00008
00009 //
00010 // MixerMode
00011 // Type: AudioMixerMode as UINT32
00012 //  0: Mic audio only
00013 //  1: System audio only
00014 //  2: Mixing mic and system audio (default)
00015 //
00016 #define PROPERTY_MIXERMODE  L"MixerMode"
00017
00018 //
00019 // LoopbackGain: Gain to apply to system audio volume.
00020 // Type : double (0.0 to 5.0)
00021 // Default: 1.0
00022 //
00023 #define PROPERTY_LOOPBACKGAIN  L"LoopbackGain"
00024
00025 //
00026 // MicrophoneGain: Gain to apply to mic volume.
00027 // Type : double (0.0 to 5.0)
00028 // Default: 1.0
00029 //
00030 #define PROPERTY_MICROPHONEGAIN  L"MicrophoneGain"
00031
00032 namespace MrcEffectDefinitions
00033 {
00034     public enum class AudioMixerMode
00035     {
00036         Mic = 0,
00037         Loopback = 1,
00038         MicAndLoopback = 2
00039     };
00040
00041     public ref class MrcAudioEffectDefinition sealed : public Windows::Media::Effects::IAudioEffectDefinition
00042     {
00043     public:
00044         MrcAudioEffectDefinition();
00045
00046         //
00047         // IAudioEffectDefinition
00048         //
00049         property Platform::String^ ActivatableClassId
00050         {
00051             virtual Platform::String^ get()
00052             {
00053                 return m_activatableClassId;
00054             }
00055         }
00056
00057         property Windows::Foundation::Collections::IPropertySet^ Properties
00058         {
00059             virtual Windows::Foundation::Collections::IPropertySet^ get()
00060             {
00061                 return m_propertySet;
00062             }
00063         }
00064
00065         //
00066         // Mixed Reality Capture effect properties
00067         //
00068         property AudioMixerMode MixerMode
00069         {
00070             AudioMixerMode get()
00071             {
00072                 return GetValueFromPropertySet<uint32_t>(m_propertySet, PROPERTY_MIXERMODE, DefaultAudioMixerMode);
00073             }
00074
00075             void set(AudioMixerMode newValue)
00076             {
00077                 m_propertySet->Insert(PROPERTY_MIXERMODE, static_cast<uint32_t>(newValue));
00078             }
00079         }
00080
00081         property double LoopbackGain
00082         {
00083             double get()
00084             {
00085                 return GetValueFromPropertySet<double>(m_propertySet, PROPERTY_LOOPBACKGAIN, DefaultLoopBackGain);
00086             }
00087
00088             void set(double newValue)
00089             {
00090                 m_propertySet->Insert(PROPERTY_LOOPBACKGAIN, static_cast<double>(newValue));
00091             }
00092         }
00093
00094         property double MicrophoneGain
00095         {
00096             double get()
00097             {
00098                 return GetValueFromPropertySet<double>(m_propertySet, PROPERTY_MICROPHONEGAIN, DefaultMicrophoneGain);
00099             }
00100
00101             void set(double newValue)
00102             {
00103                 m_propertySet->Insert(PROPERTY_MICROPHONEGAIN, static_cast<double>(newValue));
00104             }
00105         }
00106
00107     private:
00108         static constexpr AudioMixerMode DefaultAudioMixerMode = AudioMixerMode::MicAndLoopback;
00109         static constexpr double DefaultLoopBackGain = 1.0f;
00110         static constexpr double DefaultMicrophoneGain = 1.0f;
00111     private:
00112         Platform::String^ m_activatableClassId = ref new Platform::String(RUNTIMECLASS_MIXEDREALITYCAPTURE_AUDIO_EFFECT);
00113         Windows::Foundation::Collections::PropertySet^ m_propertySet = ref new Windows::Foundation::Collections::PropertySet();
00114     };
00115 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DDS_HEADER_DXT10 Member List

This is the complete list of members for DDS_HEADER_DXT10, including all inherited members.
arraySize | DDS_HEADER_DXT10
arraySize | DDS_HEADER_DXT10
dxgiFormat | DDS_HEADER_DXT10
miscFlag | DDS_HEADER_DXT10
miscFlag | DDS_HEADER_DXT10
miscFlags2 | DDS_HEADER_DXT10
miscFlags2 | DDS_HEADER_DXT10
resourceDimension | DDS_HEADER_DXT10
resourceDimension | DDS_HEADER_DXT10
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cppwinrt/SymbologyListEntry.cpp Source File

  • BarcodeScanner
  • cppwinrt

SymbologyListEntry.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SymbologyListEntry.h"
00014 #include "SymbologyListEntry.g.cpp"
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cpp/Scenario1_MeteringData.xaml.h Source File

  • CustomCapability
  • cpp

Scenario1_MeteringData.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_MeteringData.g.h"
00015 #include "ServiceViewModel.h"
00016 #include "DeviceList.h"
00017
00018 namespace SDKTemplate
00019 {
00020     [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class MeteringData sealed
00022     {
00023     public:
00024         MeteringData();
00025         property ServiceViewModel^ ViewModel;
00026
00027     private:
00028         void button_Click_StartMetering(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029         void button_Click_StopMetering(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00030         void slider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00031     };
00032 }
Generated on Fri Nov 15 2024 22:19:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cppwinrt/pch.cpp Source File

  • Calendar
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Package/cs/scenario3_dependencies.xaml.cs Source File

  • Package
  • cs

scenario3_dependencies.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using SDKTemplate;
00015 using System;
00016 using System.Collections.Generic;
00017 using Windows.ApplicationModel;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class Scenario3 : Page
00025     {
00026         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00027         // as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         public Scenario3()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         void GetDependencies_Click(Object sender, RoutedEventArgs e)
00036         {
00037             IReadOnlyList<Windows.ApplicationModel.Package> dependencies = Package.Current.Dependencies;
00038
00039             String output = String.Format("Count: {0}", dependencies.Count.ToString());
00040             for (int i = 0; i < dependencies.Count; i++)
00041             {
00042                 Package dependency = dependencies[i];
00043                 output += String.Format("\n[{0}]: {1}", i.ToString(), dependency.Id.FullName);
00044             }
00045
00046             OutputTextBlock.Text = output;
00047         }
00048
00049         /// <summary>
00050         /// Invoked when this page is about to be displayed in a Frame.
00051         /// </summary>
00052         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00053         /// property is typically used to configure the page.</param>
00054         protected override void OnNavigatedTo(NavigationEventArgs e)
00055         {
00056         }
00057     }
00058 }
Generated on Fri Nov 15 2024 22:20:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MobileHotspot/cs/SampleConfiguration.cs Source File

  • MobileHotspot
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Runtime.InteropServices;
00015 using System.Threading.Tasks;
00016 using Windows.Networking.Connectivity;
00017 using Windows.Networking.NetworkOperators;
00018 using Windows.UI.Xaml.Controls;
00019
00020 namespace SDKTemplate
00021 {
00022     public partial class MainPage : Page
00023     {
00024         public const string FEATURE_NAME = "MobileHotspot C# Sample";
00025
00026         List<Scenario> scenarios = new List<Scenario>
00027         {
00028             new Scenario() { Title="Configure Mobile Hotspot", ClassType=typeof(Scenario1_ConfigureMobileHotspot)},
00029             new Scenario() { Title="Toggle Mobile Hotspot", ClassType=typeof(Scenario2_ToggleMobileHotspot)},
00030         };
00031     }
00032
00033     public class Scenario
00034     {
00035         public string Title { get; set; }
00036         public Type ClassType { get; set; }
00037     }
00038
00039     public static class Helpers
00040     {
00041         public static NetworkOperatorTetheringManager TryGetCurrentNetworkOperatorTetheringManager()
00042         {
00043             // Get the connection profile associated with the internet connection currently used by the local machine.
00044             ConnectionProfile currentConnectionProfile = NetworkInformation.GetInternetConnectionProfile();
00045             if (currentConnectionProfile == null)
00046             {
00047                 MainPage.Current.NotifyUser("System is not connected to the Internet.", NotifyType.ErrorMessage);
00048                 return null;
00049             }
00050
00051             TetheringCapability tetheringCapability =
00052                 NetworkOperatorTetheringManager.GetTetheringCapabilityFromConnectionProfile(currentConnectionProfile);
00053
00054             if (tetheringCapability != TetheringCapability.Enabled)
00055             {
00056                 string message;
00057                 switch (tetheringCapability)
00058                 {
00059                     case TetheringCapability.DisabledByGroupPolicy:
00060                         message = "Tethering is disabled due to group policy.";
00061                         break;
00062                     case TetheringCapability.DisabledByHardwareLimitation:
00063                         message = "Tethering is not available due to hardware limitations.";
00064                         break;
00065                     case TetheringCapability.DisabledByOperator:
00066                         message = "Tethering operations are disabled for this account by the network operator.";
00067                         break;
00068                     case TetheringCapability.DisabledByRequiredAppNotInstalled:
00069                         message = "An application required for tethering operations is not available.";
00070                         break;
00071                     case TetheringCapability.DisabledBySku:
00072                         message = "Tethering is not supported by the current account services.";
00073                         break;
00074                     case TetheringCapability.DisabledBySystemCapability:
00075                         // This will occur if the "wiFiControl" capability is missing from the App.
00076                         message = "This app is not configured to access Wi-Fi devices on this machine.";
00077                         break;
00078                     default:
00079                         message = $"Tethering is disabled on this machine. (Code {(int)tetheringCapability}).";
00080                         break;
00081                 }
00082                 MainPage.Current.NotifyUser(message, NotifyType.ErrorMessage);
00083                 return null;
00084             }
00085
00086             const int E_NOT_FOUND = unchecked((int)0x80070490); // HRESULT_FROM_WIN32(ERROR_NOT_FOUND)
00087
00088             try
00089             {
00090                 return NetworkOperatorTetheringManager.CreateFromConnectionProfile(currentConnectionProfile);
00091             }
00092             catch (Exception ex) when (ex.HResult == E_NOT_FOUND)
00093             {
00094                 MainPage.Current.NotifyUser("System has no Wi-Fi adapters.", NotifyType.ErrorMessage);
00095                 return null;
00096             }
00097         }
00098
00099         public static string GetFriendlyName(TetheringWiFiBand value)
00100         {
00101             switch (value)
00102             {
00103                 case TetheringWiFiBand.Auto: return "Any available";
00104                 case TetheringWiFiBand.TwoPointFourGigahertz: return "2.4 GHz";
00105                 case TetheringWiFiBand.FiveGigahertz: return "5 Ghz";
00106                 case TetheringWiFiBand.SixGigahertz: return "6 GHz";
00107                 default: return $"Unknown ({(uint)value})";
00108             }
00109         }
00110
00111         public static string GetFriendlyName(TetheringWiFiAuthenticationKind value)
00112         {
00113             switch (value)
00114             {
00115                 case TetheringWiFiAuthenticationKind.Wpa2:
00116                     return "WPA2";
00117                 case TetheringWiFiAuthenticationKind.Wpa3TransitionMode:
00118                     return "WPA2/WPA3";
00119                 case TetheringWiFiAuthenticationKind.Wpa3:
00120                     return "WPA3";
00121                 default:
00122                     return $"Unknown ({(uint)value})";
00123             }
00124         }
00125
00126         const int E_INVALID_STATE = unchecked((int)0x8007139f); // HRESULT_FROM_WIN32(ERROR_INVALID_STATE)
00127
00128         // Calls NetworkOperatorTetheringAccessPointConfiguration.IsBandSupported but handles
00129         // certain boundary cases.
00130
00131         public static bool IsBandSupported(NetworkOperatorTetheringAccessPointConfiguration configuration, TetheringWiFiBand band)
00132         {
00133             // "Auto" mode is always supported even though it is technically not a frequency band.
00134             if (band == TetheringWiFiBand.Auto)
00135             {
00136                 return true;
00137             }
00138
00139             try
00140             {
00141                 return configuration.IsBandSupported(band);
00142             }
00143             catch (Exception ex) when (ex.HResult == E_INVALID_STATE)
00144             {
00145                 // The WiFi device has been disconnected. Report that we support nothing.
00146                 return false;
00147             }
00148         }
00149     }
00150 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks/ViewModel/TripVoiceCommand.cpp Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks
  • ViewModel

TripVoiceCommand.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "TripVoiceCommand.h"
00013
00014 using namespace AdventureWorks;
00015 using namespace Platform;
00016
00017 /// <summary> Utility class for passing voice command information around internally </summary>
00018 TripVoiceCommand::TripVoiceCommand(
00019     String^ voiceCommandName,
00020     String^ commandMode,
00021     String^ textSpoken,
00022     String^ destination)
00023 {
00024     this->voiceCommandName = voiceCommandName;
00025     this->commandMode = commandMode;
00026     this->textSpoken = textSpoken;
00027     this->destination = destination;
00028 }
00029
00030 Platform::String^ TripVoiceCommand::VoiceCommandName::get()
00031 {
00032     return this->voiceCommandName;
00033 }
00034
00035 Platform::String^ TripVoiceCommand::CommandMode::get()
00036 {
00037     return this->commandMode;
00038 }
00039
00040 Platform::String^ TripVoiceCommand::TextSpoken::get()
00041 {
00042     return this->textSpoken;
00043 }
00044
00045 Platform::String^ TripVoiceCommand::Destination::get()
00046 {
00047     return this->destination;
00048 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboard/cs/SampleConfiguration.cs Source File

  • TouchKeyboard
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "TouchKeyboard";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Display touch keyboard automatically", ClassType=typeof(Scenario1_Launch)},
00025             new Scenario() { Title="Listen for Show/Hide events", ClassType=typeof(Scenario2_ShowHideEvents)},
00026             new Scenario() { Title="Programmatically Show/Hide\nthe touch keyboard", ClassType=typeof(Scenario3_ShowHideMethods)},
00027             new Scenario() { Title="Showing the Emoji keyboard", ClassType=typeof(Scenario4_ShowView)}
00028         };
00029     }
00030
00031     public class Scenario
00032     {
00033         public string Title { get; set; }
00034         public Type ClassType { get; set; }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundMediaPlayback/cs/BackgroundApp.cs Source File

  • BackgroundMediaPlayback
  • cs

BackgroundApp.cs

Go to the documentation of this file.
00001 ﻿using BackgroundMediaPlayback.Services;
00002 using System;
00003 using System.Diagnostics;
00004 using Windows.ApplicationModel;
00005 using Windows.ApplicationModel.Activation;
00006 using Windows.System;
00007 using Windows.UI.Notifications;
00008 using Windows.UI.Xaml;
00009 using Windows.UI.Xaml.Media;
00010
00011 namespace SDKTemplate
00012 {
00013     sealed partial class App : Application
00014     {
00015         /// <summary>
00016         /// Flag to indicate whether the app is currently in
00017         /// foreground or background mode.
00018         /// </summary>
00019         /// <remarks>
00020         /// This is used later to determine when to load / unload UI.
00021         /// </remarks>
00022         bool isInBackgroundMode;
00023
00024         /// <summary>
00025         /// Called from App.xaml.cs when the application is constructed.
00026         /// </summary>
00027         partial void Construct()
00028         {
00029             // During the transition from foreground to background the
00030             // memory limit allowed for the application changes. The application
00031             // has a short time to respond by bringing its memory usage
00032             // under the new limit.
00033             MemoryManager.AppMemoryUsageLimitChanging += MemoryManager_AppMemoryUsageLimitChanging;
00034
00035             // After an application is backgrounded it is expected to stay
00036             // under a memory target to maintain priority to keep running.
00037             // Subscribe to the event that informs the app of this change.
00038             MemoryManager.AppMemoryUsageIncreased += MemoryManager_AppMemoryUsageIncreased;
00039
00040             // Subscribe to key lifecyle events to know when the app
00041             // transitions to and from foreground and background.
00042             // Leaving the background is an important transition
00043             // because the app may need to restore UI.
00044             EnteredBackground += App_EnteredBackground;
00045             LeavingBackground += App_LeavingBackground;
00046
00047             // Subscribe to regular lifecycle events to display a toast notification
00048             Suspending += App_Suspending;
00049             Resuming += App_Resuming;
00050         }
00051
00052         /// <summary>
00053         /// Invoked when application execution is being suspended.  Application state is saved
00054         /// without knowing whether the application will be terminated or resumed with the contents
00055         /// of memory still intact.
00056         /// </summary>
00057         /// <param name="sender">The source of the suspend request.</param>
00058         /// <param name="e">Details about the suspend request.</param>
00059         private void App_Suspending(object sender, SuspendingEventArgs e)
00060         {
00061             var deferral = e.SuspendingOperation.GetDeferral();
00062             // Optional: Save application state and stop any background activity
00063             ShowToast("Suspending");
00064             deferral.Complete();
00065         }
00066
00067         /// <summary>
00068         /// Invoked when application execution is resumed.
00069         /// </summary>
00070         /// <param name="sender"></param>
00071         /// <param name="e"></param>
00072         private void App_Resuming(object sender, object e)
00073         {
00074             ShowToast("Resuming");
00075         }
00076
00077         /// <summary>
00078         /// Raised when the memory limit for the app is changing, such as when the app
00079         /// enters the background.
00080         /// </summary>
00081         /// <remarks>
00082         /// If the app is using more than the new limit, it must reduce memory within 2 seconds
00083         /// on some platforms in order to avoid being suspended or terminated.
00084         ///
00085         /// While some platforms will allow the application
00086         /// to continue running over the limit, reducing usage in the time
00087         /// allotted will enable the best experience across the broadest range of devices.
00088         /// </remarks>
00089         /// <param name="sender"></param>
00090         /// <param name="e"></param>
00091         private void MemoryManager_AppMemoryUsageLimitChanging(object sender, AppMemoryUsageLimitChangingEventArgs e)
00092         {
00093             ShowToast("Memory usage limit changing from "
00094                 + (e.OldLimit / 1024) + "K to "
00095                 + (e.NewLimit / 1024) + "K");
00096
00097             // If app memory usage is over the limit about to be enforced,
00098             // then reduce usage within 2 seconds to avoid suspending.
00099             if (MemoryManager.AppMemoryUsage >= e.NewLimit)
00100             {
00101                 ReduceMemoryUsage(e.NewLimit);
00102             }
00103         }
00104
00105         /// <summary>
00106         /// Handle system notifications that the app has increased its
00107         /// memory usage level compared to its current target.
00108         /// </summary>
00109         /// <remarks>
00110         /// The app may have increased its usage or the app may have moved
00111         /// to the background and the system lowered the target the app
00112         /// is expected to reach. Either way, if the application wants
00113         /// to maintain its priority to avoid being suspended before
00114         /// other apps, it may need to reduce its memory usage.
00115         ///
00116         /// This is not a replacement for handling AppMemoryUsageLimitChanging
00117         /// which is critical to ensure the app immediately gets below the new
00118         /// limit. However, once the app is allowed to continue running and
00119         /// policy is applied, some apps may wish to continue monitoring
00120         /// usage to ensure they remain below the limit.
00121         /// </remarks>
00122         /// <param name="sender"></param>
00123         /// <param name="e"></param>
00124         private void MemoryManager_AppMemoryUsageIncreased(object sender, object e)
00125         {
00126             ShowToast("Memory usage increased");
00127
00128             // Obtain the current usage level
00129             var level = MemoryManager.AppMemoryUsageLevel;
00130
00131             // Check the usage level to determine whether reducing memory is necessary.
00132             // Memory usage may have been fine when initially entering the background but
00133             // a short time later the app might be using more memory and need to trim back.
00134             if (level == AppMemoryUsageLevel.OverLimit || level == AppMemoryUsageLevel.High)
00135             {
00136                 ReduceMemoryUsage(MemoryManager.AppMemoryUsageLimit);
00137             }
00138         }
00139
00140         /// <summary>
00141         /// The application entered the background.
00142         /// </summary>
00143         /// <param name="sender"></param>
00144         /// <param name="e"></param>
00145         private void App_EnteredBackground(object sender, EnteredBackgroundEventArgs e)
00146         {
00147             // Place the application into "background mode" and note the
00148             // transition with a flag.
00149             ShowToast("Entered background");
00150             isInBackgroundMode = true;
00151
00152             // An application may wish to release views and view data
00153             // at this point since the UI is no longer visible.
00154             //
00155             // As a performance optimization, here we note instead that
00156             // the app has entered background mode with a boolean and
00157             // defer unloading views until AppMemoryUsageLimitChanging or
00158             // AppMemoryUsageIncreased is raised with an indication that
00159             // the application is under memory pressure.
00160         }
00161
00162         /// <summary>
00163         /// The application is leaving the background.
00164         /// </summary>
00165         /// <param name="sender"></param>
00166         /// <param name="e"></param>
00167         private void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e)
00168         {
00169             // Mark the transition out of background mode.
00170             ShowToast("Leaving background");
00171             isInBackgroundMode = false;
00172
00173             // Reastore view content if it was previously unloaded.
00174             if (Window.Current.Content == null)
00175             {
00176                 ShowToast("Loading view");
00177                 CreateRootFrame(ApplicationExecutionState.Running, string.Empty);
00178             }
00179         }
00180
00181         /// <summary>
00182         /// Reduces application memory usage.
00183         /// </summary>
00184         /// <remarks>
00185         /// When the app enters the background, receives a memory limit changing
00186         /// event, or receives a memory usage increased
00187         /// event it can optionally unload cached data or even its view content in
00188         /// order to reduce memory usage and the chance of being suspended.
00189         ///
00190         /// This must be called from multiple event handlers because an application may already
00191         /// be in a high memory usage state when entering the background or it
00192         /// may be in a low memory usage state with no need to unload resources yet
00193         /// and only enter a higher state later.
00194         /// </remarks>
00195         public void ReduceMemoryUsage(ulong limit)
00196         {
00197             // If the app has caches or other memory it can free, now is the time.
00198             // << App can release memory here >>
00199
00200             // Additionally, if the application is currently
00201             // in background mode and still has a view with content
00202             // then the view can be released to save memory and
00203             // can be recreated again later when leaving the background.
00204             if (isInBackgroundMode && Window.Current.Content != null)
00205             {
00206                 ShowToast("Unloading view");
00207
00208                 // Clear the view content. Note that views should rely on
00209                 // events like Page.Unloaded to further release resources. Be careful
00210                 // to also release event handlers in views since references can
00211                 // prevent objects from being collected. C++ developers should take
00212                 // special care to use weak references for event handlers where appropriate.
00213                 Window.Current.Content = null;
00214
00215                 // Finally, clearing the content above and calling GC.Collect() below
00216                 // is what will trigger each Page.Unloaded handler to be called.
00217                 // In order for the resources each page has allocated to be released,
00218                 // it is necessary that each Page also call GC.Collect() from its
00219                 // Page.Unloaded handler.
00220             }
00221
00222             // Run the GC to collect released resources, including triggering
00223             // each Page.Unloaded handler to run.
00224             GC.Collect();
00225
00226             ShowToast("Finished reducing memory usage");
00227         }
00228
00229         /// <summary>
00230         /// Gets a string describing current memory usage
00231         /// </summary>
00232         /// <returns>String describing current memory usage</returns>
00233         private string GetMemoryUsageText()
00234         {
00235             return string.Format("[Memory: Level={0}, Usage={1}K, Target={2}K]",
00236                 MemoryManager.AppMemoryUsageLevel, MemoryManager.AppMemoryUsage / 1024, MemoryManager.AppMemoryUsageLimit / 1024);
00237         }
00238
00239         /// <summary>
00240         /// Sends a toast notification
00241         /// </summary>
00242         /// <param name="msg">Message to send</param>
00243         /// <param name="subMsg">Sub message</param>
00244         public void ShowToast(string msg, string subMsg = null)
00245         {
00246             if (subMsg == null)
00247                 subMsg = GetMemoryUsageText();
00248
00249             Debug.WriteLine(msg + "\n" + subMsg);
00250
00251             if (!SettingsService.Instance.ToastOnAppEvents)
00252                 return;
00253
00254             var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
00255
00256             var toastTextElements = toastXml.GetElementsByTagName("text");
00257             toastTextElements[0].AppendChild(toastXml.CreateTextNode(msg));
00258             toastTextElements[1].AppendChild(toastXml.CreateTextNode(subMsg));
00259
00260             var toast = new ToastNotification(toastXml);
00261             ToastNotificationManager.CreateToastNotifier().Show(toast);
00262         }
00263     }
00264 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/ComputeShader/DftTransform.cpp Source File

  • D2DCustomEffects
  • cpp
  • ComputeShader

DftTransform.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DftTransform.h"
00014 #include "BasicReaderWriter.h"
00015
00016 // These values should match those in the respective shaders.
00017 static const int CS4_numThreadsX = 24;
00018 static const int CS4_numThreadsY = 24;
00019 static const int CS5_numThreadsX = 32;
00020 static const int CS5_numThreadsY = 32;
00021
00022 DftTransform::DftTransform(_In_ ID2D1EffectContext* context, TransformType dftType) :
00023     m_cRef(0),
00024     m_dftType(dftType)
00025 {
00026     // Load the Shader Model 5 shader if the device supports it (DX 11_0), otherwise
00027     // fall back to Shader Model 4.
00028     D3D_FEATURE_LEVEL levels[] = { D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_11_0 };
00029     HRESULT hr = context->GetMaximumSupportedFeatureLevel(levels, ARRAYSIZE(levels), &m_maxLevelSupported);
00030
00031     if (SUCCEEDED(hr))
00032     {
00033         BasicReaderWriter^ reader = ref new BasicReaderWriter();
00034
00035         GUID shaderGUID;
00036         Platform::String^ shaderFile = "";
00037
00038         if (m_maxLevelSupported == D3D_FEATURE_LEVEL_11_0)
00039         {
00040             if (dftType == TransformType::Horizontal)
00041             {
00042                 shaderGUID = GUID_DFT_H_CS5;
00043                 shaderFile = "DFT_H_CS5.cso";
00044             }
00045             else
00046             {
00047                 shaderGUID = GUID_DFT_V_CS5;
00048                 shaderFile = "DFT_V_CS5.cso";
00049             }
00050         }
00051         else if (m_maxLevelSupported == D3D_FEATURE_LEVEL_10_0)
00052         {
00053             if (dftType == TransformType::Horizontal)
00054             {
00055                 shaderGUID = GUID_DFT_H_CS4;
00056                 shaderFile = "DFT_H_CS4.cso";
00057             }
00058             else
00059             {
00060                 shaderGUID = GUID_DFT_V_CS4;
00061                 shaderFile = "DFT_V_CS4.cso";
00062             }
00063         }
00064
00065         auto data = reader->ReadData(shaderFile);
00066         hr = context->LoadComputeShader(shaderGUID, data->Data, data->Length);
00067     }
00068
00069     if (FAILED(hr))
00070     {
00071         throw Platform::Exception::CreateException(hr);
00072     }
00073 }
00074
00075 IFACEMETHODIMP DftTransform::MapInvalidRect(
00076     UINT32 inputIndex,
00077     D2D1_RECT_L invalidInputRect,
00078     _Out_ D2D1_RECT_L* pInvalidOutputRect
00079     ) const
00080 {
00081     // Due to the nature of this effect, any change in the input file will affect the entire
00082     // output. To implement this, the effect sets the invalidOutputRect to the
00083     // entire input rect.
00084     *pInvalidOutputRect = m_inputRect;
00085     return S_OK;
00086 }
00087
00088 IFACEMETHODIMP DftTransform::MapOutputRectToInputRects(
00089     _In_ const D2D1_RECT_L* pOutputRect,
00090     _Out_writes_(inputRectCount) D2D1_RECT_L* pInputRects,
00091     UINT32 inputRectCount
00092     ) const
00093 {
00094     // Return an error if more than one input specified for transform.
00095     if (inputRectCount != 1)
00096     {
00097         return E_INVALIDARG;
00098     }
00099
00100     // Most effects will only need the region of the input that directly corresponds to the output,
00101     // and will want to set the inputRect accordingly. Due to the nature of this algorithm, the
00102     // effect needs to process the entire input, even if the output is not completely visible.
00103     // To do so, it sets the inputRect to be the previously reported input (in MapInputRectsToOutputRect),
00104     // instead of the requested output.
00105     pInputRects[0] = m_inputRect;
00106
00107     return S_OK;
00108 }
00109
00110 IFACEMETHODIMP DftTransform::MapInputRectsToOutputRect(
00111     _In_reads_(inputRectCount) const D2D1_RECT_L* pInputRects,
00112     _In_reads_(inputRectCount) const D2D1_RECT_L* pInputOpaqueSubRects,
00113     UINT32 inputRectCount,
00114     _Out_ D2D1_RECT_L* pOutputRect,
00115     _Out_ D2D1_RECT_L* pOutputOpaqueSubRect
00116     )
00117 {
00118     // Return an error if more than one input is specified for transform.
00119     if (inputRectCount != 1)
00120     {
00121         return E_INVALIDARG;
00122     }
00123
00124     // The output of the transform will be the same size as the input.
00125     *pOutputRect = pInputRects[0];
00126
00127     // Save the size of the input for use in MapOutputRectToInputRects
00128     // and MapInvalidRect. This represents the size of the entire input.
00129     m_inputRect = pInputRects[0];
00130
00131     // Because the effect output is merely a graph with a guaranteed alpha of '1',
00132     // the effect can mark the entire output as opaque. This does not affect the
00133     // output image itself, but allows Direct2D to use various optimizations, such
00134     // as using a more simple blend mode.
00135     *pOutputOpaqueSubRect = *pOutputRect;
00136
00137     return S_OK;
00138 }
00139
00140 IFACEMETHODIMP DftTransform::CalculateThreadgroups(
00141     _In_ const D2D1_RECT_L* pOutputRect,
00142     _Out_ UINT32* pDimensionX,
00143     _Out_ UINT32* pDimensionY,
00144     _Out_ UINT32* pDimensionZ
00145     )
00146 {
00147     // The dimensions specified here are what Direct2D uses to calculate how many instances of the shader to
00148     // call (said another way, which parameters are passed to the Direct3D Dispatch call). NumThreads specifies how many pixels
00149     // one instance of a shader operates on, while the Dimension parameter here specifies how many instances of the
00150     // shader to call. In this case we divide the width and height of the image by the corresponding NumThreads
00151     // to determine how many times we need to call the shader.
00152
00153     // If the image is not perfectly divisible by the numThreads values,
00154     // the app should round it up to the next whole number then manually
00155     // check in the shader when the current thread is outside the image's bounds.
00156     // If the value is not rounded up, the remainder pixels will not be processed.
00157
00158     *pDimensionX = 0;
00159     *pDimensionY = 0;
00160
00161     if (m_maxLevelSupported == D3D_FEATURE_LEVEL_11_0)
00162     {
00163         *pDimensionX = static_cast<UINT32>(ceil((m_inputRect.right - m_inputRect.left) / static_cast<float>(CS5_numThreadsX)));
00164         *pDimensionY = static_cast<UINT32>(ceil((m_inputRect.bottom - m_inputRect.top) / static_cast<float>(CS5_numThreadsY)));
00165     }
00166     else if (m_maxLevelSupported == D3D_FEATURE_LEVEL_10_0)
00167     {
00168         *pDimensionX = static_cast<UINT32>(ceil((m_inputRect.right - m_inputRect.left) / static_cast<float>(CS4_numThreadsX)));
00169         *pDimensionY = static_cast<UINT32>(ceil((m_inputRect.bottom - m_inputRect.top) / static_cast<float>(CS4_numThreadsY)));
00170     }
00171
00172     *pDimensionZ = 1;
00173
00174     return S_OK;
00175 }
00176
00177 IFACEMETHODIMP DftTransform::SetComputeInfo(_In_ ID2D1ComputeInfo* pComputeInfo)
00178 {
00179     HRESULT hr = S_OK;
00180
00181     UINT32 instructionCount = 0;
00182
00183     if (m_dftType == TransformType::Horizontal)
00184     {
00185         // The output of the horizontal shader is best represented as a float. This thus instructs
00186         // Direct2D to set the type of the output buffer to 32 bit floats.
00187         hr = pComputeInfo->SetOutputBuffer(D2D1_BUFFER_PRECISION_32BPC_FLOAT, D2D1_CHANNEL_DEPTH_4);
00188
00189         if (SUCCEEDED(hr))
00190         {
00191             if (m_maxLevelSupported == D3D_FEATURE_LEVEL_11_0)
00192             {
00193                 hr = pComputeInfo->SetComputeShader(GUID_DFT_H_CS5);
00194             }
00195             else
00196             {
00197                 hr = pComputeInfo->SetComputeShader(GUID_DFT_H_CS4);
00198             }
00199         }
00200     }
00201     else
00202     {
00203         // Update constant buffer b1 with the magnitude scale factor of our choosing. Constant
00204         // buffers can be updated as often as the transform wants, such as on property changes.
00205         m_constantBuffer.magnitudeScale = 500.0f;
00206         hr = pComputeInfo->SetComputeShaderConstantBuffer(reinterpret_cast<const BYTE*>(&m_constantBuffer), sizeof(m_constantBuffer));
00207
00208         if (SUCCEEDED(hr))
00209         {
00210             if (m_maxLevelSupported == D3D_FEATURE_LEVEL_11_0)
00211             {
00212                 hr = pComputeInfo->SetComputeShader(GUID_DFT_V_CS5);
00213             }
00214             else
00215             {
00216                 hr = pComputeInfo->SetComputeShader(GUID_DFT_V_CS4);
00217             }
00218         }
00219     }
00220
00221     if (SUCCEEDED(hr))
00222     {
00223         // Providing this hint allows D2D to optimize performance when processing large images.
00224         pComputeInfo->SetInstructionCountHint(instructionCount);
00225     }
00226
00227     return hr;
00228 }
00229
00230 IFACEMETHODIMP_(ULONG) DftTransform::AddRef()
00231 {
00232     // D2D ensures that that effects are only referenced from one thread at a time.
00233     // To improve performance, we simply increment/decrement our reference count
00234     // rather than use atomic InterlockedIncrement()/InterlockedDecrement() functions.
00235     m_cRef++;
00236
00237     return m_cRef;
00238 }
00239
00240 IFACEMETHODIMP_(ULONG) DftTransform::Release()
00241 {
00242     m_cRef--;
00243
00244     if (m_cRef == 0)
00245     {
00246         delete this;
00247         return 0;
00248     }
00249     else
00250     {
00251         return m_cRef;
00252     }
00253 }
00254
00255 IFACEMETHODIMP DftTransform::QueryInterface(
00256     REFIID riid,
00257     _Outptr_ void** ppOutput
00258     )
00259 {
00260     *ppOutput = nullptr;
00261     HRESULT hr = S_OK;
00262
00263     if (riid == __uuidof(ID2D1ComputeTransform))
00264     {
00265         *ppOutput = static_cast<ID2D1ComputeTransform*>(this);
00266     }
00267     else if (riid == __uuidof(ID2D1Transform))
00268     {
00269         *ppOutput = static_cast<ID2D1Transform*>(this);
00270     }
00271     else if (riid == __uuidof(ID2D1TransformNode))
00272     {
00273         *ppOutput = static_cast<ID2D1TransformNode*>(this);
00274     }
00275     else if (riid == __uuidof(IUnknown))
00276     {
00277         *ppOutput = this;
00278     }
00279     else
00280     {
00281         hr = E_NOINTERFACE;
00282     }
00283
00284     if (*ppOutput != nullptr)
00285     {
00286         AddRef();
00287     }
00288
00289     return hr;
00290 }
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/Content/ShaderStructures.h Source File

  • HolographicTagAlong
  • cpp
  • Content

ShaderStructures.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace HolographicTagAlongSample
00015 {
00016     // Constant buffer used to send per-hologram data to the shader pipeline.
00017     struct ModelConstantBuffer
00018     {
00019         DirectX::XMFLOAT4X4 model;
00020         DirectX::XMFLOAT4   hologramColorFadeMultiplier;
00021     };
00022
00023     // Assert that the constant buffer remains 16-byte aligned (best practice).
00024     // If shader structure members are not aligned to a 4-float boundary, data may
00025     // not show up where it is expected by the time it is read by the shader.
00026     static_assert((sizeof(ModelConstantBuffer) % (sizeof(float) * 4)) == 0, "Model constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00027
00028
00029     // Used to send per-vertex data to the vertex shader.
00030     struct VertexPositionColorTex
00031     {
00032         DirectX::XMFLOAT3 pos;
00033         DirectX::XMFLOAT3 color;
00034         DirectX::XMFLOAT2 texCoord;
00035     };
00036 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/SampleConfiguration.h Source File

  • ComplexInk
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Complex Ink Sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CashDrawer/cpp/Scenario3_MultipleDrawers.xaml.cpp Source File

  • CashDrawer
  • cpp

Scenario3_MultipleDrawers.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_MultipleDrawers.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Windows::Devices::PointOfService;
00018 using namespace concurrency;
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Controls::Primitives;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::UI::Xaml::Input;
00027 using namespace Windows::UI::Xaml::Media;
00028 using namespace Windows::UI::Xaml::Navigation;
00029 using namespace Windows::UI::Core;
00030
00031 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00032
00033 Scenario3_MultipleDrawers::Scenario3_MultipleDrawers() : rootPage(MainPage::Current)
00034 {
00035     InitializeComponent();
00036 }
00037
00038
00039 /// <summary>
00040 /// Invoked when this page is about to be displayed in a Frame.
00041 /// </summary>
00042 /// <param name="e">Event data that describes how this page was reached.</param>
00043 void Scenario3_MultipleDrawers::OnNavigatedTo(NavigationEventArgs^ e)
00044 {
00045     ResetScenarioState();
00046 }
00047
00048
00049 /// <summary>
00050 /// Invoked before the page is unloaded and is no longer the current source of a Frame.
00051 /// </summary>
00052 /// <param name="e">Event data describing the navigation that was requested.</param>
00053 void Scenario3_MultipleDrawers::OnNavigatedFrom(NavigationEventArgs^ e)
00054 {
00055     ResetScenarioState();
00056 }
00057
00058
00059 /// <summary>
00060 /// Creates the default cash drawer.
00061 /// </summary>
00062 /// <param name="instance">Specifies the cash drawer instance that should be used.</param>
00063 /// <returns>True if the cash drawer was created, false otherwise.</returns>
00064 task<bool> Scenario3_MultipleDrawers::CreateDefaultCashDrawerObject(CashDrawerInstance instance)
00065 {
00066     rootPage->NotifyUser("Creating cash drawer object.", NotifyType::StatusMessage);
00067
00068     return DeviceHelpers::GetFirstCashDrawerAsync().then([this, instance](CashDrawer^ defaultDrawer)
00069     {
00070         if (defaultDrawer == nullptr)
00071         {
00072             rootPage->NotifyUser("Cash drawer not found. Please connect a cash drawer.", NotifyType::ErrorMessage);
00073             return false;
00074         }
00075
00076         switch (instance)
00077         {
00078         case Instance1:
00079             cashDrawerInstance1 = defaultDrawer;
00080             break;
00081         case Instance2:
00082             cashDrawerInstance2 = defaultDrawer;
00083             break;
00084         default:
00085             break;
00086         }
00087
00088         return true;
00089     });
00090 }
00091
00092
00093 /// <summary>
00094 /// Attempt to claim the connected cash drawer.
00095 /// </summary>
00096 /// <param name="instance">Specifies the cash drawer instance that should be used.</param>
00097 /// <returns>True if the cash drawer was successfully claimed, false otherwise.</returns>
00098 task<bool> Scenario3_MultipleDrawers::ClaimCashDrawer(CashDrawerInstance instance)
00099 {
00100     CashDrawer^ drawer;
00101     if (instance == Instance1)
00102         drawer = cashDrawerInstance1;
00103     else
00104         drawer = cashDrawerInstance2;
00105
00106     return create_task(drawer->ClaimDrawerAsync()).then([this, instance](ClaimedCashDrawer^ claimed)
00107     {
00108         if (claimed == nullptr)
00109             return false;
00110
00111         if (instance == Instance1)
00112             claimedCashDrawerInstance1 = claimed;
00113         else
00114             claimedCashDrawerInstance2 = claimed;
00115
00116         return true;
00117     });
00118 }
00119
00120
00121 /// <summary>
00122 /// Event callback for claim instance 1 button.
00123 /// </summary>
00124 /// <param name="sender">Button that was clicked.</param>
00125 /// <param name="e">Event data associated with click event.</param>
00126 void Scenario3_MultipleDrawers::ClaimButton1_Click(Object^ sender, RoutedEventArgs^ e)
00127 {
00128     create_task(CreateDefaultCashDrawerObject(Instance1)).then([this](bool success)
00129     {
00130         if (success)
00131         {
00132             create_task(ClaimCashDrawer(Instance1)).then([this](bool success)
00133             {
00134                 if (!success)
00135                 {
00136                     rootPage->NotifyUser("Failed to claim instance 1.", NotifyType::ErrorMessage);
00137                     return;
00138                 }
00139
00140                 releaseRequestedToken1 = claimedCashDrawerInstance1->ReleaseDeviceRequested::add(
00141                     ref new TypedEventHandler<ClaimedCashDrawer^, Object^>(this, &Scenario3_MultipleDrawers::claimedCashDrawerInstance1_ReleaseDeviceRequested));
00142
00143                 rootPage->NotifyUser("Successfully claimed instance 1.", NotifyType::StatusMessage);
00144                 SetClaimedUI(Instance1);
00145             });
00146         }
00147     });
00148 }
00149
00150
00151 /// <summary>
00152 /// Event callback for claim instance 2 button.
00153 /// </summary>
00154 /// <param name="sender">Button that was clicked.</param>
00155 /// <param name="e">Event data associated with click event.</param>
00156 void Scenario3_MultipleDrawers::ClaimButton2_Click(Object^ sender, RoutedEventArgs^ e)
00157 {
00158     create_task(CreateDefaultCashDrawerObject(Instance2)).then([this](bool success)
00159     {
00160         if (success)
00161         {
00162             create_task(ClaimCashDrawer(Instance2)).then([this](bool success)
00163             {
00164                 if (!success)
00165                 {
00166                     rootPage->NotifyUser("Failed to claim instance 2.", NotifyType::ErrorMessage);
00167                     return;
00168                 }
00169
00170                 releaseRequestedToken2 = claimedCashDrawerInstance2->ReleaseDeviceRequested::add(
00171                     ref new TypedEventHandler<ClaimedCashDrawer^, Object^>(this, &Scenario3_MultipleDrawers::claimedCashDrawerInstance2_ReleaseDeviceRequested));
00172
00173                 rootPage->NotifyUser("Successfully claimed instance 2.", NotifyType::StatusMessage);
00174                 SetClaimedUI(Instance2);
00175             });
00176         }
00177     });
00178 }
00179
00180
00181 /// <summary>
00182 /// Event callback for release instance 1 button.
00183 /// </summary>
00184 /// <param name="sender">Button that was clicked.</param>
00185 /// <param name="e">Event data associated with click event.</param>
00186 void Scenario3_MultipleDrawers::ReleaseButton1_Click(Object^ sender, RoutedEventArgs^ e)
00187 {
00188     if (claimedCashDrawerInstance1 != nullptr)
00189     {
00190         claimedCashDrawerInstance1->ReleaseDeviceRequested::remove(releaseRequestedToken1);
00191         delete claimedCashDrawerInstance1;
00192         claimedCashDrawerInstance1 = nullptr;
00193
00194         SetReleasedUI(Instance1);
00195
00196         rootPage->NotifyUser("Claimed instance 1 was released.", NotifyType::StatusMessage);
00197     }
00198 }
00199
00200
00201 /// <summary>
00202 /// Event callback for release instance 2 button.
00203 /// </summary>
00204 /// <param name="sender">Button that was clicked.</param>
00205 /// <param name="e">Event data associated with click event.</param>
00206 void Scenario3_MultipleDrawers::ReleaseButton2_Click(Object^ sender, RoutedEventArgs^ e)
00207 {
00208     if (claimedCashDrawerInstance2 != nullptr)
00209     {
00210         claimedCashDrawerInstance2->ReleaseDeviceRequested::remove(releaseRequestedToken2);
00211         delete claimedCashDrawerInstance2;
00212         claimedCashDrawerInstance2 = nullptr;
00213
00214         SetReleasedUI(Instance2);
00215
00216         rootPage->NotifyUser("Claimed instance 2 was released.", NotifyType::StatusMessage);
00217     }
00218 }
00219
00220
00221 /// <summary>
00222 /// Event callback for a release device request for instance 1.
00223 /// </summary>
00224 /// <param name="sender">The drawer receiving the release device request.</param>
00225 /// <param name="e">Unused for ReleaseDeviceRequested events.</param>
00226 void Scenario3_MultipleDrawers::claimedCashDrawerInstance1_ReleaseDeviceRequested(ClaimedCashDrawer^ sender, Object^ e)
00227 {
00228     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00229     {
00230         rootPage->NotifyUser("Release instance 1 requested.", NotifyType::StatusMessage);
00231
00232         if (RetainCheckBox1->IsChecked->Value)
00233         {
00234             create_task(claimedCashDrawerInstance1->RetainDeviceAsync()).then([this](bool success)
00235             {
00236                 if (!success)
00237                     rootPage->NotifyUser("Cash drawer instance 1 retain failed.", NotifyType::ErrorMessage);
00238             });
00239         }
00240         else
00241         {
00242             claimedCashDrawerInstance1->ReleaseDeviceRequested::remove(releaseRequestedToken1);
00243             delete claimedCashDrawerInstance1;
00244             claimedCashDrawerInstance1 = nullptr;
00245
00246             SetReleasedUI(Instance1);
00247         }
00248     }));
00249 }
00250
00251
00252 /// <summary>
00253 /// Event callback for a release device request for instance 2.
00254 /// </summary>
00255 /// <param name="sender">The drawer receiving the release device request.</param>
00256 /// <param name="e">Unused for ReleaseDeviceRequested events.</param>
00257 void Scenario3_MultipleDrawers::claimedCashDrawerInstance2_ReleaseDeviceRequested(ClaimedCashDrawer^ sender, Object^ e)
00258 {
00259     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00260     {
00261         rootPage->NotifyUser("Release instance 2 requested.", NotifyType::StatusMessage);
00262
00263         if (RetainCheckBox2->IsChecked->Value)
00264         {
00265             create_task(claimedCashDrawerInstance2->RetainDeviceAsync()).then([this](bool success)
00266             {
00267                 if(!success)
00268                     rootPage->NotifyUser("Cash drawer instance 2 retain failed.", NotifyType::ErrorMessage);
00269             });
00270         }
00271         else
00272         {
00273             claimedCashDrawerInstance2->ReleaseDeviceRequested::remove(releaseRequestedToken2);
00274             delete claimedCashDrawerInstance2;
00275             claimedCashDrawerInstance2 = nullptr;
00276
00277             SetReleasedUI(Instance2);
00278         }
00279     }));
00280 }
00281
00282
00283 /// <summary>
00284 /// Reset the scenario to its initial state.
00285 /// </summary>
00286 void Scenario3_MultipleDrawers::ResetScenarioState()
00287 {
00288     if (cashDrawerInstance1 != nullptr)
00289     {
00290         delete cashDrawerInstance1;
00291         cashDrawerInstance1 = nullptr;
00292     }
00293
00294     if (cashDrawerInstance2 != nullptr)
00295     {
00296         delete cashDrawerInstance2;
00297         cashDrawerInstance2 = nullptr;
00298     }
00299
00300     if (claimedCashDrawerInstance1 != nullptr)
00301     {
00302         delete claimedCashDrawerInstance1;
00303         claimedCashDrawerInstance1 = nullptr;
00304     }
00305
00306     if (claimedCashDrawerInstance2 != nullptr)
00307     {
00308         delete claimedCashDrawerInstance2;
00309         claimedCashDrawerInstance2 = nullptr;
00310     }
00311
00312     ClaimButton1->IsEnabled = true;
00313     ClaimButton2->IsEnabled = true;
00314     ReleaseButton1->IsEnabled = false;
00315     ReleaseButton2->IsEnabled = false;
00316     RetainCheckBox1->IsChecked = true;
00317     RetainCheckBox2->IsChecked = true;
00318
00319     rootPage->NotifyUser("Click a claim button to begin.", NotifyType::StatusMessage);
00320 }
00321
00322
00323 /// <summary>
00324 /// Sets the UI elements to a state corresponding to the specified instace being claimed.
00325 /// </summary>
00326 /// <param name="instance">Corresponds to instance that has been claimed.</param>
00327 void Scenario3_MultipleDrawers::SetClaimedUI(CashDrawerInstance instance)
00328 {
00329     switch (instance)
00330     {
00331     case Instance1:
00332         ClaimButton1->IsEnabled = false;
00333         ClaimButton2->IsEnabled = true;
00334         ReleaseButton1->IsEnabled = true;
00335         ReleaseButton2->IsEnabled = false;
00336         break;
00337
00338     case Instance2:
00339         ClaimButton1->IsEnabled = true;
00340         ClaimButton2->IsEnabled = false;
00341         ReleaseButton1->IsEnabled = false;
00342         ReleaseButton2->IsEnabled = true;
00343         break;
00344
00345     default:
00346         break;
00347     }
00348 }
00349
00350
00351 /// <summary>
00352 /// Sets the UI elements to a state corresponding to the specified instace being released.
00353 /// </summary>
00354 /// <param name="instance">Corresponds to instance that has been released.</param>
00355 void Scenario3_MultipleDrawers::SetReleasedUI(CashDrawerInstance instance)
00356 {
00357     switch (instance)
00358     {
00359     case Instance1:
00360         ClaimButton1->IsEnabled = true;
00361         ReleaseButton1->IsEnabled = false;
00362         break;
00363
00364     case Instance2:
00365         ClaimButton2->IsEnabled = true;
00366         ReleaseButton2->IsEnabled = false;
00367         break;
00368
00369     default:
00370         break;
00371     }
00372 }
00373
Generated on Fri Nov 15 2024 22:18:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/Common/CameraResources.cpp Source File

  • BasicHologram
  • cpp
  • Common

CameraResources.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002
00003 #include "CameraResources.h"
00004 #include "Common\DirectXHelper.h"
00005 #include "DeviceResources.h"
00006 #include <windows.graphics.directx.direct3d11.interop.h>
00007
00008 using namespace DirectX;
00009 using namespace Microsoft::WRL;
00010 using namespace Windows::Graphics::DirectX::Direct3D11;
00011 using namespace Windows::Graphics::Holographic;
00012 using namespace Windows::Perception::Spatial;
00013
00014 DX::CameraResources::CameraResources(HolographicCamera^ camera) :
00015     m_holographicCamera(camera),
00016     m_isStereo(camera->IsStereo),
00017     m_d3dRenderTargetSize(camera->RenderTargetSize)
00018 {
00019     m_d3dViewport = CD3D11_VIEWPORT(
00020         0.f, 0.f,
00021         m_d3dRenderTargetSize.Width,
00022         m_d3dRenderTargetSize.Height
00023         );
00024 };
00025
00026 // Updates resources associated with a holographic camera's swap chain.
00027 // The app does not access the swap chain directly, but it does create
00028 // resource views for the back buffer.
00029 void DX::CameraResources::CreateResourcesForBackBuffer(
00030     DX::DeviceResources* pDeviceResources,
00031     HolographicCameraRenderingParameters^ cameraParameters
00032     )
00033 {
00034     const auto device = pDeviceResources->GetD3DDevice();
00035
00036     // Get the WinRT object representing the holographic camera's back buffer.
00037     IDirect3DSurface^ surface = cameraParameters->Direct3D11BackBuffer;
00038
00039     // Get a DXGI interface for the holographic camera's back buffer.
00040     // Holographic cameras do not provide the DXGI swap chain, which is owned
00041     // by the system. The Direct3D back buffer resource is provided using WinRT
00042     // interop APIs.
00043     ComPtr<ID3D11Resource> resource;
00044     ThrowIfFailed(
00045         GetDXGIInterfaceFromObject(surface, IID_PPV_ARGS(&resource))
00046         );
00047
00048     // Get a Direct3D interface for the holographic camera's back buffer.
00049     ComPtr<ID3D11Texture2D> cameraBackBuffer;
00050     ThrowIfFailed(
00051         resource.As(&cameraBackBuffer)
00052         );
00053
00054     // Determine if the back buffer has changed. If so, ensure that the render target view
00055     // is for the current back buffer.
00056     if (m_d3dBackBuffer.Get() != cameraBackBuffer.Get())
00057     {
00058         // This can change every frame as the system moves to the next buffer in the
00059         // swap chain. This mode of operation will occur when certain rendering modes
00060         // are activated.
00061         m_d3dBackBuffer = cameraBackBuffer;
00062
00063         // Create a render target view of the back buffer.
00064         // Creating this resource is inexpensive, and is better than keeping track of
00065         // the back buffers in order to pre-allocate render target views for each one.
00066         DX::ThrowIfFailed(
00067             device->CreateRenderTargetView(
00068                 m_d3dBackBuffer.Get(),
00069                 nullptr,
00070                 &m_d3dRenderTargetView
00071                 )
00072             );
00073
00074         // Get the DXGI format for the back buffer.
00075         // This information can be accessed by the app using CameraResources::GetBackBufferDXGIFormat().
00076         D3D11_TEXTURE2D_DESC backBufferDesc;
00077         m_d3dBackBuffer->GetDesc(&backBufferDesc);
00078         m_dxgiFormat = backBufferDesc.Format;
00079
00080         // Check for render target size changes.
00081         Windows::Foundation::Size currentSize = m_holographicCamera->RenderTargetSize;
00082         if (m_d3dRenderTargetSize != currentSize)
00083         {
00084             // Set render target size.
00085             m_d3dRenderTargetSize = currentSize;
00086
00087             // A new depth stencil view is also needed.
00088             m_d3dDepthStencilView.Reset();
00089         }
00090     }
00091
00092     // Refresh depth stencil resources, if needed.
00093     if (m_d3dDepthStencilView == nullptr)
00094     {
00095         // Create a depth stencil view for use with 3D rendering if needed.
00096         CD3D11_TEXTURE2D_DESC depthStencilDesc(
00097             DXGI_FORMAT_R16_TYPELESS,
00098             static_cast<UINT>(m_d3dRenderTargetSize.Width),
00099             static_cast<UINT>(m_d3dRenderTargetSize.Height),
00100             m_isStereo ? 2 : 1, // Create two textures when rendering in stereo.
00101             1, // Use a single mipmap level.
00102             D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE
00103             );
00104
00105         DX::ThrowIfFailed(
00106             device->CreateTexture2D(
00107                 &depthStencilDesc,
00108                 nullptr,
00109                 &m_d3dDepthStencil
00110                 )
00111             );
00112
00113         CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(
00114             m_isStereo ? D3D11_DSV_DIMENSION_TEXTURE2DARRAY : D3D11_DSV_DIMENSION_TEXTURE2D,
00115             DXGI_FORMAT_D16_UNORM
00116             );
00117         DX::ThrowIfFailed(
00118             device->CreateDepthStencilView(
00119                 m_d3dDepthStencil.Get(),
00120                 &depthStencilViewDesc,
00121                 &m_d3dDepthStencilView
00122                 )
00123             );
00124     }
00125
00126     // Create the constant buffer, if needed.
00127     if (m_viewProjectionConstantBuffer == nullptr)
00128     {
00129         // Create a constant buffer to store view and projection matrices for the camera.
00130         CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00131         DX::ThrowIfFailed(
00132             device->CreateBuffer(
00133                 &constantBufferDesc,
00134                 nullptr,
00135                 &m_viewProjectionConstantBuffer
00136                 )
00137             );
00138     }
00139 }
00140
00141 // Releases resources associated with a back buffer.
00142 void DX::CameraResources::ReleaseResourcesForBackBuffer(DX::DeviceResources* pDeviceResources)
00143 {
00144     const auto context = pDeviceResources->GetD3DDeviceContext();
00145
00146     // Release camera-specific resources.
00147     m_d3dBackBuffer.Reset();
00148     m_d3dDepthStencil.Reset();
00149     m_d3dRenderTargetView.Reset();
00150     m_d3dDepthStencilView.Reset();
00151     m_viewProjectionConstantBuffer.Reset();
00152
00153     // Ensure system references to the back buffer are released by clearing the render
00154     // target from the graphics pipeline state, and then flushing the Direct3D context.
00155     ID3D11RenderTargetView* nullViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { nullptr };
00156     context->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00157     context->Flush();
00158 }
00159
00160 // Updates the view/projection constant buffer for a holographic camera.
00161 void DX::CameraResources::UpdateViewProjectionBuffer(
00162     std::shared_ptr<DX::DeviceResources> deviceResources,
00163     HolographicCameraPose^ cameraPose,
00164     SpatialCoordinateSystem^ coordinateSystem
00165     )
00166 {
00167     // The system changes the viewport on a per-frame basis for system optimizations.
00168     m_d3dViewport = CD3D11_VIEWPORT(
00169         cameraPose->Viewport.Left,
00170         cameraPose->Viewport.Top,
00171         cameraPose->Viewport.Width,
00172         cameraPose->Viewport.Height
00173         );
00174
00175     // The projection transform for each frame is provided by the HolographicCameraPose.
00176     HolographicStereoTransform cameraProjectionTransform = cameraPose->ProjectionTransform;
00177
00178     // Get a container object with the view and projection matrices for the given
00179     // pose in the given coordinate system.
00180     Platform::IBox<HolographicStereoTransform>^ viewTransformContainer = cameraPose->TryGetViewTransform(coordinateSystem);
00181
00182     // If TryGetViewTransform returns a null pointer, that means the pose and coordinate
00183     // system cannot be understood relative to one another; content cannot be rendered
00184     // in this coordinate system for the duration of the current frame.
00185     // This usually means that positional tracking is not active for the current frame, in
00186     // which case it is possible to use a SpatialLocatorAttachedFrameOfReference to render
00187     // content that is not world-locked instead.
00188     DX::ViewProjectionConstantBuffer viewProjectionConstantBufferData;
00189     bool viewTransformAcquired = viewTransformContainer != nullptr;
00190     if (viewTransformAcquired)
00191     {
00192         // Otherwise, the set of view transforms can be retrieved.
00193         HolographicStereoTransform viewCoordinateSystemTransform = viewTransformContainer->Value;
00194
00195         // Update the view matrices. Holographic cameras (such as Microsoft HoloLens) are
00196         // constantly moving relative to the world. The view matrices need to be updated
00197         // every frame.
00198         XMStoreFloat4x4(
00199             &viewProjectionConstantBufferData.viewProjection[0],
00200             XMMatrixTranspose(XMLoadFloat4x4(&viewCoordinateSystemTransform.Left) * XMLoadFloat4x4(&cameraProjectionTransform.Left))
00201             );
00202         XMStoreFloat4x4(
00203             &viewProjectionConstantBufferData.viewProjection[1],
00204             XMMatrixTranspose(XMLoadFloat4x4(&viewCoordinateSystemTransform.Right) * XMLoadFloat4x4(&cameraProjectionTransform.Right))
00205             );
00206     }
00207
00208     // Use the D3D device context to update Direct3D device-based resources.
00209     const auto context = deviceResources->GetD3DDeviceContext();
00210
00211     // Loading is asynchronous. Resources must be created before they can be updated.
00212     if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || !viewTransformAcquired)
00213     {
00214         m_framePending = false;
00215     }
00216     else
00217     {
00218         // Update the view and projection matrices.
00219         context->UpdateSubresource(
00220             m_viewProjectionConstantBuffer.Get(),
00221             0,
00222             nullptr,
00223             &viewProjectionConstantBufferData,
00224             0,
00225             0
00226             );
00227
00228         m_framePending = true;
00229     }
00230 }
00231
00232 // Gets the view-projection constant buffer for the HolographicCamera and attaches it
00233 // to the shader pipeline.
00234 bool DX::CameraResources::AttachViewProjectionBuffer(
00235     std::shared_ptr<DX::DeviceResources> deviceResources
00236     )
00237 {
00238     // This method uses Direct3D device-based resources.
00239     const auto context = deviceResources->GetD3DDeviceContext();
00240
00241     // Loading is asynchronous. Resources must be created before they can be updated.
00242     // Cameras can also be added asynchronously, in which case they must be initialized
00243     // before they can be used.
00244     if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || m_framePending == false)
00245     {
00246         return false;
00247     }
00248
00249     // Set the viewport for this camera.
00250     context->RSSetViewports(1, &m_d3dViewport);
00251
00252     // Send the constant buffer to the vertex shader.
00253     context->VSSetConstantBuffers(
00254         1,
00255         1,
00256         m_viewProjectionConstantBuffer.GetAddressOf()
00257         );
00258
00259     // The template includes a pass-through geometry shader that is used by
00260     // default on systems that don't support the D3D11_FEATURE_D3D11_OPTIONS3::
00261     // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer extension. The shader
00262     // will be enabled at run-time on systems that require it.
00263     // If your app will also use the geometry shader for other tasks and those
00264     // tasks require the view/projection matrix, uncomment the following line
00265     // of code to send the constant buffer to the geometry shader as well.
00266     /*context->GSSetConstantBuffers(
00267         1,
00268         1,
00269         m_viewProjectionConstantBuffer.GetAddressOf()
00270         );*/
00271
00272     m_framePending = false;
00273
00274     return true;
00275 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInteractionMode/cppwinrt/Project.idl Source File

  • UserInteractionMode
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_Basic : Windows.UI.Xaml.Controls.Page, Windows.UI.Xaml.Data.INotifyPropertyChanged
00016     {
00017         Scenario1_Basic();
00018
00019         Windows.UI.Xaml.Style CheckBoxStyle{ get; };
00020         Windows.UI.ViewManagement.UserInteractionMode InteractionMode{ get; };
00021     }
00022 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cpp/SampleConfiguration.h Source File

  • Playlists
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Playlists";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029         static property Platform::Array<Platform::String^>^ audioExtensions
00030         {
00031             Platform::Array<Platform::String^>^ get()
00032             {
00033                 return audioExtensionsInner;
00034             }
00035         }
00036         static property Platform::Array<Platform::String^>^ playlistExtensions
00037         {
00038             Platform::Array<Platform::String^>^ get()
00039             {
00040                 return playlistExtensionsInner;
00041             }
00042         }
00043         static Windows::Storage::Pickers::FileOpenPicker^ CreateFilePicker(Platform::Array<Platform::String^>^ extensions);
00044         concurrency::task<Windows::Media::Playlists::Playlist^> PickPlaylistAsync();
00045         concurrency::task<bool> TrySavePlaylistAsync(Windows::Media::Playlists::Playlist^ playlist);
00046
00047     private:
00048         static Platform::Array<Scenario>^ scenariosInner;
00049         static Platform::Array<Platform::String^>^ audioExtensionsInner;
00050         static Platform::Array<Platform::String^>^ playlistExtensionsInner;
00051     };
00052
00053     public value struct Scenario
00054     {
00055         Platform::String^ Title;
00056         Platform::String^ ClassName;
00057     };
00058 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario05_PostStream Member List

This is the complete list of members for Scenario05_PostStream, including all inherited members.
Cancel_Click(object sender, RoutedEventArgs e) | Scenario05_PostStream | [inline, private]
cts | Scenario05_PostStream | [private]
GenerateSampleStream(int size) | Scenario05_PostStream | [inline, private, static]
httpClient | Scenario05_PostStream | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario05_PostStream | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario05_PostStream | [inline, protected]
rootPage | Scenario05_PostStream | [private]
Scenario05_PostStream() | Scenario05_PostStream | [inline]
Start_Click(object sender, RoutedEventArgs e) | Scenario05_PostStream | [inline, private]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlAnimatedGif/cpp/SampleConfiguration.cpp Source File

  • XamlAnimatedGif
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Animated GIFs", "SDKTemplate.Scenario1_Basic" },
00021 };
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/Scenario8_TransmitAPDU.cpp Source File

  • SmartCard
  • cppwinrt

Scenario8_TransmitAPDU.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario8_TransmitAPDU.h"
00014 #include "Scenario8_TransmitAPDU.g.cpp"
00015
00016 namespace winrt
00017 {
00018     using namespace Windows::Foundation;
00019     using namespace Windows::Security::Cryptography;
00020     using namespace Windows::Devices::SmartCards;
00021     using namespace Windows::Devices::Enumeration;
00022     using namespace Windows::UI::Xaml;
00023     using namespace Windows::UI::Xaml::Controls;
00024     using namespace Windows::Storage::Streams;
00025 }
00026
00027 namespace winrt::SDKTemplate::implementation
00028 {
00029     Scenario8_TransmitAPDU::Scenario8_TransmitAPDU()
00030     {
00031         InitializeComponent();
00032     }
00033
00034     /// <summary>
00035     /// Click handler for the 'TransmitAPDU' button.
00036     /// </summary>
00037     /// <param name="sender"></param>
00038     fire_and_forget Scenario8_TransmitAPDU::Transmit_Click(IInspectable const& sender, RoutedEventArgs const&)
00039     {
00040         auto lifetime = get_strong();
00041
00042         if (!ValidateTPMSmartCard())
00043         {
00044             m_rootPage.NotifyUser(L"Use Scenario One to create a TPM virtual smart card.", NotifyType::ErrorMessage);
00045             co_return;
00046         }
00047
00048         auto b = sender.as<Button>();
00049         b.IsEnabled(false);
00050
00051         try
00052         {
00053             SmartCard card = co_await GetSmartCardAsync();
00054
00055             // We rely on this object's destructor to clean up the connection.
00056             SmartCardConnection connection = co_await card.ConnectAsync();
00057
00058             // Read EF.ATR file
00059             // The command is meant specifically for GIDS cards
00060             // (such as TPM VSCs), and will fail on other types.
00061             static constexpr uint8_t readEfAtrBytes[] = { 0x00, 0xCB, 0x2F, 0x01, 0x02, 0x5C, 0x00, 0xFF };
00062             IBuffer readEfAtr = CryptographicBuffer::CreateFromByteArray(readEfAtrBytes);
00063             IBuffer result = co_await connection.TransmitAsync(readEfAtr);
00064
00065             m_rootPage.NotifyUser(L"Response: " + CryptographicBuffer::EncodeToHexString(result), NotifyType::StatusMessage);
00066             // connection destructed here
00067         }
00068         catch (hresult_error const& ex)
00069         {
00070             m_rootPage.NotifyUser(L"Transmitting APDU to card failed with exception: " + ex.message(), NotifyType::ErrorMessage);
00071         }
00072
00073         b.IsEnabled(true);
00074     }
00075 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
AppView() | sealed |
CreateView() | sealed | [virtual]
Initialize(Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
Load(Platform::String^entryPoint) | sealed | [virtual]
m_deviceResources | sealed | [private]
m_holographicSpace | sealed | [private]
m_main | sealed | [private]
m_windowClosed | sealed | [private]
m_windowVisible | sealed | [private]
OnKeyPressed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::KeyEventArgs^args) | sealed | [protected]
OnResuming(Platform::Object^sender, Platform::Object^args) | sealed | [protected]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [protected]
OnViewActivated(Windows::ApplicationModel::Core::CoreApplicationView^sender, Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | sealed | [protected]
OnVisibilityChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::VisibilityChangedEventArgs^args) | sealed | [protected]
OnWindowClosed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::CoreWindowEventArgs^args) | sealed | [protected]
Run() | sealed | [virtual]
SetWindow(Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
Uninitialize() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cppwinrt/Project.idl Source File

  • DateTimeFormatting
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_LongAndShortFormats : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_LongAndShortFormats();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_StringTemplate : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_StringTemplate();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3_ParameterizedTemplate : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3_ParameterizedTemplate();
00030     }
00031
00032     [default_interface]
00033     runtimeclass Scenario4_Override : Windows.UI.Xaml.Controls.Page
00034     {
00035         Scenario4_Override();
00036     }
00037
00038     [default_interface]
00039     runtimeclass Scenario5_UnicodeExtensions : Windows.UI.Xaml.Controls.Page
00040     {
00041         Scenario5_UnicodeExtensions();
00042     }
00043
00044     [default_interface]
00045     runtimeclass Scenario6_TimeZone : Windows.UI.Xaml.Controls.Page
00046     {
00047         Scenario6_TimeZone();
00048     }
00049 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/GameHud.h Source File

  • Simple3DGameDX
  • cpp

GameHud.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // GameHud:
00015 // This class maintains the resources necessary to draw the Heads Up Display, which is a
00016 // 2D overlay on top of the main 3D graphics generated for the game.
00017 // The GameHud Render method expects to be called within the context of a D2D BeginDraw
00018 // and makes D2D drawing calls to draw the text elements on the window.
00019
00020 #include "Simple3DGame.h"
00021 #include "DirectXSample.h"
00022
00023 ref class Simple3DGame;
00024
00025 ref class GameHud
00026 {
00027 internal:
00028     GameHud(
00029         _In_ const std::shared_ptr<DX::DeviceResources>& deviceResources,
00030         _In_ Platform::String^ titleHeader,
00031         _In_ Platform::String^ titleBody
00032         );
00033
00034     void CreateDeviceDependentResources();
00035     void CreateWindowSizeDependentResources();
00036     void ReleaseDeviceDependentResources();
00037     void Render(_In_ Simple3DGame^ game);
00038
00039 private:
00040     // Cached pointer to device resources.
00041     std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00042
00043     Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>        m_textBrush;
00044     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatBody;
00045     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatBodySymbol;
00046
00047     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatTitleHeader;
00048     Microsoft::WRL::ComPtr<IDWriteTextFormat>           m_textFormatTitleBody;
00049     Microsoft::WRL::ComPtr<ID2D1Bitmap>                 m_logoBitmap;
00050     Microsoft::WRL::ComPtr<IDWriteTextLayout>           m_titleHeaderLayout;
00051     Microsoft::WRL::ComPtr<IDWriteTextLayout>           m_titleBodyLayout;
00052
00053     bool                                                m_showTitle;
00054     Platform::String^                                   m_titleHeader;
00055     Platform::String^                                   m_titleBody;
00056
00057     float                                               m_titleBodyVerticalOffset;
00058     D2D1_SIZE_F                                         m_logoSize;
00059     D2D1_SIZE_F                                         m_maxTitleSize;
00060 };
Generated on Fri Nov 15 2024 22:21:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6 Member List

This is the complete list of members for Scenario6, including all inherited members.
dateAccessedProperty | Scenario6 | [private, static]
fileOwnerProperty | Scenario6 | [private, static]
InitializePlaybackList() | Scenario6 | [inline, private]
InkToolbar_ActiveToolChanged(InkToolbar sender, object args) | Scenario6 | [inline, private]
InkToolbar_EraseAllClicked(InkToolbar sender, object args) | Scenario6 | [inline, private]
InkToolbar_InkDrawingAttributesChanged(InkToolbar sender, object args) | Scenario6 | [inline, private]
InkToolbar_IsStencilButtonCheckedChanged(InkToolbar sender, InkToolbarIsStencilButtonCheckedChangedEventArgs args) | Scenario6 | [inline, private]
InkToolbar_SelectedStencilChanged(DependencyObject sender, DependencyProperty dp) | Scenario6 | [inline, private]
mp | Scenario6 | [private]
mpiLoggerList | Scenario6 | [private]
mplLogger | Scenario6 | [private]
mpLogger | Scenario6 | [private]
nextButton_Click(object sender, RoutedEventArgs e) | Scenario6 | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario6 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario6 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario6 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario6 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario6 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario6 | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario6 | [inline, protected]
OnSizeChanged(object sender, SizeChangedEventArgs e) | Scenario6 | [inline, private]
pfnLink_Click(object sender, RoutedEventArgs e) | Scenario6 | [inline, private]
playbackList | Scenario6 | [private]
PlaybackList_CurrentItemChanged(MediaPlaybackList sender, CurrentMediaPlaybackItemChangedEventArgs args) | Scenario6 | [inline, private]
PlaybackSession_PlaybackRateChanged(MediaPlaybackSession sender, object args) | Scenario6 | [inline, private]
PlaybackSession_PlaybackStateChanged(MediaPlaybackSession sender, object args) | Scenario6 | [inline, private]
playButton_Click(object sender, RoutedEventArgs e) | Scenario6 | [inline, private]
PlaylistView_ItemClick(object sender, ItemClickEventArgs e) | Scenario6 | [inline, private]
prevButton_Click(object sender, RoutedEventArgs e) | Scenario6 | [inline, private]
rootPage | Scenario6 | [private]
Scenario6() | Scenario6 | [inline]
Scenario6() | Scenario6 | [inline]
Scenario6() | Scenario6 | [inline]
Scenario6() | Scenario6 | [inline]
Scenario6() | Scenario6 | [inline]
Scenario6() | Scenario6 | [inline]
Scenario6Button_Show_Click(object sender, RoutedEventArgs e) | Scenario6 | [inline, private]
selectedStencilChangedToken | Scenario6 | [private]
SelectImageButton_Click(object sender, RoutedEventArgs e) | Scenario6 | [inline, private]
SetCanvasSize() | Scenario6 | [inline, private]
ShowPropertiesButton_Click(object sender, RoutedEventArgs e) | Scenario6 | [inline, private]
speedButton_Click(object sender, RoutedEventArgs e) | Scenario6 | [inline, private]
ToggleLogs(object sender, RoutedEventArgs e) | Scenario6 | [inline, private]
UnprocessedInput_PointerEntered(InkUnprocessedInput sender, PointerEventArgs args) | Scenario6 | [inline, private]
UnprocessedInput_PointerEntered1(InkUnprocessedInput sender, PointerEventArgs args) | Scenario6 | [inline, private]
UpdateTransportControls(MediaPlaybackState state) | Scenario6 | [inline, private]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampDevice/cs/SampleConfiguration.cs Source File

  • LampDevice
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     using System;
00015     using System.Collections.Generic;
00016     using Windows.UI.Xaml.Controls;
00017     using Lamp;
00018
00019     /// <summary>
00020     /// Main Page Class Object
00021     /// </summary>
00022     public partial class MainPage : Page
00023     {
00024         public const string FEATURE_NAME = "Lamp device C# sample";
00025
00026         List<Scenario> scenarios = new List<Scenario>
00027         {
00028             new Scenario() { Title="Get Lamp Instance", ClassType=typeof(Scenario1_GetLamp)},
00029             new Scenario() { Title="Enable Lamp and Settings Adjustment", ClassType=typeof(Scenario2_EnableSettings)},
00030             new Scenario() { Title="Lamp Device Change Events", ClassType=typeof(Scenario3_AvailabilityChanged)}
00031         };
00032     }
00033
00034     /// <summary>
00035     /// Scenario Class Object
00036     /// </summary>
00037     public class Scenario
00038     {
00039         public string Title { get; set; }
00040         public Type ClassType { get; set; }
00041     }
00042 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppWindow/cppwinrt/pch.cpp Source File

  • AppWindow
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cppwinrt/pch.h Source File

  • Calendar
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.Globalization.h"
00007 #include "winrt/Windows.Globalization.DateTimeFormatting.h"
00008 #include "winrt/Windows.ApplicationModel.Activation.h"
00009 #include "winrt/Windows.System.h"
00010 #include "winrt/Windows.UI.Core.h"
00011 #include "winrt/Windows.UI.Xaml.h"
00012 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.h"
00014 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00015 #include "winrt/Windows.UI.Xaml.Documents.h"
00016 #include "winrt/Windows.UI.Xaml.Interop.h"
00017 #include "winrt/Windows.UI.Xaml.Markup.h"
00018 #include "winrt/Windows.UI.Xaml.Media.h"
00019 #include "winrt/Windows.UI.Xaml.Navigation.h"
00020 #include <sstream>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialStage/cpp/Common/DeviceResources.h Source File

  • HolographicSpatialStage
  • cpp
  • Common

DeviceResources.h

Go to the documentation of this file.
00001 ﻿
00002 #pragma once
00003
00004 #include "CameraResources.h"
00005
00006 namespace DX
00007 {
00008     // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created.
00009     interface IDeviceNotify
00010     {
00011         virtual void OnDeviceLost()     = 0;
00012         virtual void OnDeviceRestored() = 0;
00013     };
00014
00015     // Creates and manages a Direct3D device and immediate context, Direct2D device and context (for debug), and the holographic swap chain.
00016     class DeviceResources
00017     {
00018     public:
00019         DeviceResources();
00020
00021         // Public methods related to Direct3D devices.
00022         void HandleDeviceLost();
00023         void RegisterDeviceNotify(IDeviceNotify* deviceNotify);
00024         void Trim();
00025         void Present(Windows::Graphics::Holographic::HolographicFrame^ frame);
00026
00027         // Public methods related to holographic devices.
00028         void SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^ space);
00029         void EnsureCameraResources(
00030             Windows::Graphics::Holographic::HolographicFrame^ frame,
00031             Windows::Graphics::Holographic::HolographicFramePrediction^ prediction);
00032
00033         void AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^ camera);
00034         void RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^ camera);
00035
00036         // Holographic accessors.
00037         template<typename RetType, typename LCallback>
00038         RetType                 UseHolographicCameraResources(const LCallback& callback);
00039
00040         Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^
00041                                 GetD3DInteropDevice() const             { return m_d3dInteropDevice;    }
00042
00043         // D3D accessors.
00044         ID3D11Device4*          GetD3DDevice() const                    { return m_d3dDevice.Get();     }
00045         ID3D11DeviceContext3*   GetD3DDeviceContext() const             { return m_d3dContext.Get();    }
00046         D3D_FEATURE_LEVEL       GetDeviceFeatureLevel() const           { return m_d3dFeatureLevel;     }
00047         bool                    GetDeviceSupportsVprt() const           { return m_supportsVprt;        }
00048
00049         // DXGI acessors.
00050         IDXGIAdapter3*          GetDXGIAdapter() const                  { return m_dxgiAdapter.Get();   }
00051
00052         // D2D accessors.
00053         ID2D1Factory2*          GetD2DFactory() const                   { return m_d2dFactory.Get();    }
00054         IDWriteFactory2*        GetDWriteFactory() const                { return m_dwriteFactory.Get(); }
00055         IWICImagingFactory2*    GetWicImagingFactory() const            { return m_wicFactory.Get();    }
00056
00057     private:
00058         // Private methods related to the Direct3D device, and resources based on that device.
00059         void CreateDeviceIndependentResources();
00060         void InitializeUsingHolographicSpace();
00061         void CreateDeviceResources();
00062
00063         // Direct3D objects.
00064         Microsoft::WRL::ComPtr<ID3D11Device4>                   m_d3dDevice;
00065         Microsoft::WRL::ComPtr<ID3D11DeviceContext3>            m_d3dContext;
00066         Microsoft::WRL::ComPtr<IDXGIAdapter3>                   m_dxgiAdapter;
00067
00068         // Direct3D interop objects.
00069         Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^ m_d3dInteropDevice;
00070
00071         // Direct2D factories.
00072         Microsoft::WRL::ComPtr<ID2D1Factory2>                   m_d2dFactory;
00073         Microsoft::WRL::ComPtr<IDWriteFactory2>                 m_dwriteFactory;
00074         Microsoft::WRL::ComPtr<IWICImagingFactory2>             m_wicFactory;
00075
00076         // The holographic space provides a preferred DXGI adapter ID.
00077         Windows::Graphics::Holographic::HolographicSpace^       m_holographicSpace = nullptr;
00078
00079         // Properties of the Direct3D device currently in use.
00080         D3D_FEATURE_LEVEL                                       m_d3dFeatureLevel = D3D_FEATURE_LEVEL_10_0;
00081
00082         // The IDeviceNotify can be held directly as it owns the DeviceResources.
00083         IDeviceNotify*                                          m_deviceNotify = nullptr;
00084
00085         // Whether or not the current Direct3D device supports the optional feature
00086         // for setting the render target array index from the vertex shader stage.
00087         bool                                                    m_supportsVprt = false;
00088
00089         // Back buffer resources, etc. for attached holographic cameras.
00090         std::map<UINT32, std::unique_ptr<CameraResources>>      m_cameraResources;
00091         std::mutex                                              m_cameraResourcesLock;
00092     };
00093 }
00094
00095 // Device-based resources for holographic cameras are stored in a std::map. Access this list by providing a
00096 // callback to this function, and the std::map will be guarded from add and remove
00097 // events until the callback returns. The callback is processed immediately and must
00098 // not contain any nested calls to UseHolographicCameraResources.
00099 // The callback takes a parameter of type std::map<UINT32, std::unique_ptr<DX::CameraResources>>&
00100 // through which the list of cameras will be accessed.
00101 template<typename RetType, typename LCallback>
00102 RetType DX::DeviceResources::UseHolographicCameraResources(const LCallback& callback)
00103 {
00104     std::lock_guard<std::mutex> guard(m_cameraResourcesLock);
00105     return callback(m_cameraResources);
00106 }
00107
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Extend Member List

This is the complete list of members for Scenario2_Extend, including all inherited members.
EnableControls_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Extend |
ExtendView_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Extend |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario2_Extend |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario2_Extend |
Scenario2_Extend() | Scenario2_Extend |
ToggleFullScreenModeButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Extend |
UpdateFullScreenModeStatus() | Scenario2_Extend | [private]
windowSizeChangedToken | Scenario2_Extend | [private]
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cs/Scenario2_History.xaml.cs Source File

  • Pedometer
  • cs

Scenario2_History.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013
00014 using System;
00015 using System.Collections.Generic;
00016 using System.Collections.ObjectModel;
00017 using Windows.Devices.Enumeration;
00018 using Windows.Devices.Sensors;
00019 using Windows.Globalization;
00020 using Windows.Globalization.DateTimeFormatting;
00021 using Windows.UI.Xaml;
00022 using Windows.UI.Xaml.Controls;
00023
00024 namespace PedometerCS
00025 {
00026     /// <summary>
00027     /// History Page that gets loaded when 'History' scenario is selected.
00028     /// </summary>
00029     public sealed partial class Scenario2_History : Page
00030     {
00031         MainPage rootPage = MainPage.Current;
00032
00033         // Common class ID for pedometers
00034         Guid PedometerClassId = new Guid("B19F89AF-E3EB-444B-8DEA-202575A71599");
00035
00036         public Scenario2_History()
00037         {
00038             this.InitializeComponent();
00039             historyRecords = new ObservableCollection<HistoryRecord>();
00040             historyRecordsList.DataContext = historyRecords;
00041         }
00042
00043         private void AllHistory_Checked(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00044         {
00045             // Collapse SpanPicker - SpanPicker will not be created yet the first time the page is loading
00046             if (SpanPicker != null)
00047             {
00048                 SpanPicker.Visibility = Visibility.Collapsed;
00049             }
00050             getAllHistory = true;
00051             rootPage.NotifyUser("This will retrieve all the step count history available on the system", NotifyType.StatusMessage);
00052         }
00053
00054         private void SpecificHistory_Checked(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00055         {
00056             SpanPicker.Visibility = Visibility.Visible;
00057             getAllHistory = false;
00058             rootPage.NotifyUser("This will retrieve all the step count history for the selected time span", NotifyType.StatusMessage);
00059         }
00060
00061         /// <summary>
00062         /// Invoked when 'Get History' button is clicked.
00063         /// Depending on the user selection, this handler uses one of the overloaded
00064         /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user
00065         /// </summary>
00066         /// <param name="sender">unused</param>
00067         /// <param name="e">unused</param>
00068         async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00069         {
00070             GetHistory.IsEnabled = false;
00071
00072             // Determine if we can access pedometers
00073             var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId);
00074             if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
00075             {
00076                 // Determine if a pedometer is present
00077                 // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
00078                 var sensor = await Pedometer.GetDefaultAsync();
00079                 if (sensor != null)
00080                 {
00081                     IReadOnlyList<PedometerReading> historyReadings = null;
00082                     var timestampFormatter = new DateTimeFormatter("shortdate longtime");
00083
00084                     // Disable subsequent history retrieval while the async operation is in progress
00085                     GetHistory.IsEnabled = false;
00086
00087                     // clear previous content being displayed
00088                     historyRecords.Clear();
00089
00090                     try
00091                     {
00092                         if (getAllHistory)
00093                         {
00094                             var dt = DateTime.FromFileTimeUtc(0);
00095                             var fromBeginning = new DateTimeOffset(dt);
00096                             rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage);
00097                             historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);
00098                         }
00099                         else
00100                         {
00101                             String notificationString = "Retrieving history from: ";
00102                             var calendar = new Calendar();
00103                             calendar.ChangeClock("24HourClock");
00104
00105                             // DateTime picker will also include hour, minute and seconds from the the system time.
00106                             // Decrement the same to be able to correctly add TimePicker values.
00107
00108                             calendar.SetDateTime(FromDate.Date);
00109                             calendar.AddNanoseconds(-calendar.Nanosecond);
00110                             calendar.AddSeconds(-calendar.Second);
00111                             calendar.AddMinutes(-calendar.Minute);
00112                             calendar.AddHours(-calendar.Hour);
00113                             calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds));
00114
00115                             DateTimeOffset fromTime = calendar.GetDateTime();
00116
00117                             calendar.SetDateTime(ToDate.Date);
00118                             calendar.AddNanoseconds(-calendar.Nanosecond);
00119                             calendar.AddSeconds(-calendar.Second);
00120                             calendar.AddMinutes(-calendar.Minute);
00121                             calendar.AddHours(-calendar.Hour);
00122                             calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds));
00123
00124                             DateTimeOffset toTime = calendar.GetDateTime();
00125
00126                             notificationString += timestampFormatter.Format(fromTime);
00127                             notificationString += " To ";
00128                             notificationString += timestampFormatter.Format(toTime);
00129
00130                             if (toTime.ToFileTime() < fromTime.ToFileTime())
00131                             {
00132                                 rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage);
00133
00134                                 // Enable subsequent history retrieval while the async operation is in progress
00135                                 GetHistory.IsEnabled = true;
00136                             }
00137                             else
00138                             {
00139                                 TimeSpan span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks);
00140                                 rootPage.NotifyUser(notificationString, NotifyType.StatusMessage);
00141                                 historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span);
00142                             }
00143                         }
00144
00145                         if (historyReadings != null)
00146                         {
00147                             foreach (PedometerReading reading in historyReadings)
00148                             {
00149                                 HistoryRecord record = new HistoryRecord(reading);
00150                                 historyRecords.Add(record);
00151
00152                                 // Get at most 100 records (number is arbitrary chosen for demonstration purposes)
00153                                 if (historyRecords.Count == 100)
00154                                 {
00155                                     break;
00156                                 }
00157                             }
00158
00159                             rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage);
00160                         }
00161                     }
00162                     catch (UnauthorizedAccessException)
00163                     {
00164                         rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
00165                     }
00166
00167                     // Finally, re-enable history retrieval
00168                     GetHistory.IsEnabled = true;
00169                 }
00170                 else
00171                 {
00172                     rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage);
00173                 }
00174             }
00175             else
00176             {
00177                 rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage);
00178             }
00179         }
00180
00181         private ObservableCollection<HistoryRecord> historyRecords;
00182         private bool getAllHistory = true;
00183     }
00184
00185     /// <summary>
00186     /// Represents a history record object that gets binded to the ListView
00187     /// controller in the XAML
00188     /// </summary>
00189     public sealed class HistoryRecord
00190     {
00191         public String TimeStamp
00192         {
00193             get
00194             {
00195                 DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");
00196                 return timestampFormatter.Format(recordTimestamp);
00197             }
00198         }
00199
00200         public String StepKind
00201         {
00202             get
00203             {
00204                 String stepString;
00205                 switch (stepKind)
00206                 {
00207                     case PedometerStepKind.Unknown:
00208                         stepString = "Unknown";
00209                         break;
00210                     case PedometerStepKind.Walking:
00211                         stepString = "Walking";
00212                         break;
00213                     case PedometerStepKind.Running:
00214                         stepString = "Running";
00215                         break;
00216                     default:
00217                         stepString = "Invalid Step Kind";
00218                         break;
00219                 }
00220                 return stepString;
00221             }
00222         }
00223
00224         public Int32 StepsCount
00225         {
00226             get
00227             {
00228                 return stepsCount;
00229             }
00230         }
00231         public double StepsDuration
00232         {
00233             get
00234             {
00235                 // return Duration in ms
00236                 return stepsDuration.TotalMilliseconds;
00237             }
00238         }
00239
00240         public HistoryRecord(PedometerReading reading)
00241         {
00242             stepKind = reading.StepKind;
00243             stepsCount = reading.CumulativeSteps;
00244             recordTimestamp = reading.Timestamp;
00245         }
00246
00247         private DateTimeOffset recordTimestamp;
00248         private PedometerStepKind stepKind;
00249         private Int32 stepsCount;
00250         private TimeSpan stepsDuration;
00251     }
00252 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Compression/cpp/Scenario3.xaml.h Source File

  • Compression
  • cpp

Scenario3.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario3.xaml.h
00013 // Declaration of the Scenario3 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario3.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024     namespace Compression
00025     {
00026         /// <summary>
00027         /// An empty page that can be used on its own or navigated to within a Frame.
00028         /// </summary>
00029         [Windows::Foundation::Metadata::WebHostHidden]
00030         public ref class Scenario3 sealed
00031         {
00032         public:
00033             Scenario3();
00034
00035         protected:
00036             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037         private:
00038             MainPage^ rootPage;
00039
00040             void DoScenario(Windows::Storage::Compression::CompressAlgorithm Algorithm);
00041
00042             void CompressAlgorithmComboBox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043             void CompressFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044             void UpdateDescriptionVisibility(Windows::UI::Xaml::Controls::ComboBoxItem^ item, Windows::UI::Xaml::Visibility visibility);
00045             int CompressAlgorithmFromComboBoxItem(Windows::UI::Xaml::Controls::ComboBoxItem^ item);
00046         };
00047     }
00048 }
Generated on Fri Nov 15 2024 22:18:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cppwinrt/Scenario4.cpp Source File

  • FileThumbnails
  • cppwinrt

Scenario4.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario4.h"
00014 #include "Scenario4.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Storage;
00020 using namespace Windows::Storage::FileProperties;
00021 using namespace Windows::Storage::Pickers;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario4::Scenario4()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     void Scenario4::OnNavigatedTo(NavigationEventArgs const&)
00033     {
00034         Helpers::ResetOutput(rootPage, ThumbnailImage(), OutputTextBlock());
00035     }
00036
00037     fire_and_forget Scenario4::GetThumbnailButton_Click(IInspectable const&, RoutedEventArgs const&)
00038     {
00039         auto lifetime = get_strong();
00040
00041         Helpers::ResetOutput(rootPage, ThumbnailImage(), OutputTextBlock());
00042
00043         // Pick a folder
00044         FolderPicker folderPicker;
00045         folderPicker.FileTypeFilter().ReplaceAll(FileExtensions::Image());
00046         StorageFolder folder = co_await folderPicker.PickSingleFolderAsync();
00047
00048         if (folder != nullptr)
00049         {
00050             const ThumbnailMode thumbnailMode = ThumbnailMode::PicturesView;
00051             const uint32_t size = 200;
00052             StorageItemThumbnail thumbnail = co_await folder.GetThumbnailAsync(thumbnailMode, size);
00053             if (thumbnail != nullptr)
00054             {
00055                 Helpers::DisplayResult(ThumbnailImage(), OutputTextBlock(), thumbnailMode, size, folder, thumbnail, false);
00056                 thumbnail.Close();
00057             }
00058             else
00059             {
00060                 rootPage.NotifyUser(Errors::NoIcon, NotifyType::StatusMessage);
00061             }
00062         }
00063         else
00064         {
00065             rootPage.NotifyUser(Errors::Cancel, NotifyType::StatusMessage);
00066         }
00067     }
00068 }
Generated on Fri Nov 15 2024 22:19:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cpp/Scenario1_CreateTPMVSC.xaml.h Source File

  • SmartCard
  • cpp

Scenario1_CreateTPMVSC.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario1_CreateTPMVSC.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario1_CreateTPMVSC sealed
00012     {
00013     public:
00014         Scenario1_CreateTPMVSC();
00015     private:
00016         static const int pinPolicyDisallowedIndex = 0;
00017         static const int pinPolicyAllowedIndex = 1;
00018         static const int pinPolicyRequireOneIndex = 2;
00019
00020         void Create_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021         void HandleCardAdded(Windows::Devices::SmartCards::SmartCardReader^ evtReader, Windows::Devices::SmartCards::CardAddedEventArgs^ args);
00022         Windows::Devices::SmartCards::SmartCardPinPolicy^ ParsePinPolicy();
00023         Windows::Devices::SmartCards::SmartCardReader^ reader;
00024     };
00025 }
Generated on Fri Nov 15 2024 22:21:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Package/cpp/SampleConfiguration.h Source File

  • Package
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Package";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContentIndexer/cpp/S2_UpdateAndDeleteWithAPI.xaml.cpp Source File

  • ContentIndexer
  • cpp

S2_UpdateAndDeleteWithAPI.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // S2_UpdateAndDeleteWithAPI.xaml.cpp
00014 // Implementation of the S2_UpdateAndDeleteWithAPI class
00015 //
00016
00017 #include "pch.h"
00018 #include "S2_UpdateAndDeleteWithAPI.xaml.h"
00019 #include "MainPage.xaml.h"
00020 #include "Helpers.h"
00021
00022 using namespace SDKTemplate;
00023
00024 using namespace concurrency;
00025 using namespace Platform;
00026 using namespace Platform::Collections;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::Foundation;
00030 using namespace Windows::Foundation::Collections;
00031
00032 S2_UpdateAndDeleteWithAPI::S2_UpdateAndDeleteWithAPI()
00033 {
00034     InitializeComponent();
00035     InitializeRevisionNumber();
00036 }
00037
00038 void S2_UpdateAndDeleteWithAPI::S2_UpdateAndDeleteWithAPI::AddToIndex_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00039 {
00040     auto indexer = Windows::Storage::Search::ContentIndexer::GetIndexer();
00041     AddItemsToIndex(indexer);
00042 }
00043
00044 void S2_UpdateAndDeleteWithAPI::S2_UpdateAndDeleteWithAPI::UpdatePropertyHelper(String^ itemKey, String^ propertyKey, String^ propertyName, Object^ newValue)
00045 {
00046     auto indexer = Windows::Storage::Search::ContentIndexer::GetIndexer();
00047     auto propertyKeys = ref new Vector<String^>();
00048     propertyKeys->Append(propertyKey);
00049     auto outputStrings = ref new Vector<String^>();
00050     create_task(indexer->RetrievePropertiesAsync(itemKey, propertyKeys)).then(
00051     [outputStrings, indexer, this, itemKey, propertyKey, newValue, propertyName](IMapView<String^, Object^>^ retrievedProperties) mutable
00052     {
00053         // Log the original value of the property
00054         outputStrings->Append(L"Original " + propertyName + L": " + StringifyProperty(retrievedProperties->Lookup(propertyKey)));
00055
00056         // Create an indexable content item to update the property
00057         auto content = ref new Windows::Storage::Search::IndexableContent();
00058         content->Id = itemKey;
00059         content->Properties->Insert(propertyKey, newValue);
00060
00061         // Update the indexer
00062         OnIndexerOperationBegin();
00063         return indexer->UpdateAsync(content);
00064     }).then([indexer, itemKey, propertyKeys]()
00065     {
00066         OnIndexerOperationComplete(indexer);
00067         return indexer->RetrievePropertiesAsync(itemKey, propertyKeys);
00068     }).then([outputStrings, propertyKey, propertyName](IMapView<String^, Object^>^ retrievedProperties) mutable
00069     {
00070         // Log the new value of the property
00071         outputStrings->Append(L"\nNew " + propertyName + L": " + StringifyProperty(retrievedProperties->Lookup(propertyKey)));
00072         auto outputString = ref new String(L"");
00073         for (const auto& str : outputStrings)
00074         {
00075             outputString += str;
00076         }
00077         return outputString;
00078     }).then([](task<String^> outputStringTask)
00079     {
00080         try
00081         {
00082             MainPage::Current->NotifyUser(outputStringTask.get(), NotifyType::StatusMessage);
00083         }
00084         catch (Platform::InvalidArgumentException^ e)
00085         {
00086             MainPage::Current->NotifyUser(L"Exception thrown! Did you try to retrieve or update a property on a non-existent item?" +
00087                                           L"\nMessage: " + e->Message +
00088                                           L"\nHRESULT: " + HResultToString(e->HResult),
00089                                           NotifyType::ErrorMessage);
00090         }
00091     });
00092 }
00093
00094 // This function updates the ItemNameDisplay property for the indexed item with the key "Sample 0." The
00095 // updated ItemNameDisplay property comes from the itemNameInput text box.
00096 void S2_UpdateAndDeleteWithAPI::S2_UpdateAndDeleteWithAPI::UpdateName_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00097 {
00098     UpdatePropertyHelper(L"SampleKey0", Windows::Storage::SystemProperties::ItemNameDisplay, L"item name", ItemNameInput->Text);
00099 }
00100
00101 // This function deletes the Keywords property for the indexed item with the key "Sample0."
00102 void S2_UpdateAndDeleteWithAPI::S2_UpdateAndDeleteWithAPI::DeleteKeywords_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00103 {
00104     UpdatePropertyHelper(L"SampleKey0", Windows::Storage::SystemProperties::Keywords, L"keywords", nullptr);
00105 }
00106
00107 void S2_UpdateAndDeleteWithAPI::S2_UpdateAndDeleteWithAPI::DeleteItemsHelper(std::function<IAsyncAction^(Windows::Storage::Search::ContentIndexer^)> deleteFunction)
00108 {
00109     auto indexer = Windows::Storage::Search::ContentIndexer::GetIndexer();
00110     auto propertiesToRetrieve = ref new Vector<String^>();
00111     propertiesToRetrieve->Append(Windows::Storage::SystemProperties::ItemNameDisplay);
00112     auto query = indexer->CreateQuery(L"*", propertiesToRetrieve);
00113     auto outputStrings = ref new Vector<String^>();
00114     create_task(query->GetCountAsync()).then([outputStrings, indexer, deleteFunction](unsigned int count)
00115     {
00116         outputStrings->Append(L"Original number of items: " + count);
00117         OnIndexerOperationBegin();
00118         return deleteFunction(indexer);
00119     }).then([propertiesToRetrieve, indexer]()
00120     {
00121         OnIndexerOperationComplete(indexer);
00122         auto query = indexer->CreateQuery(L"*", propertiesToRetrieve);
00123         return query->GetCountAsync();
00124     }).then([outputStrings](unsigned int count)
00125     {
00126         outputStrings->Append(L"\nNew number of items: " + count);
00127         auto outputString = ref new String(L"");
00128         for (const auto& str : outputStrings)
00129         {
00130             outputString += str;
00131         }
00132         MainPage::Current->NotifyUser(outputString, NotifyType::StatusMessage);
00133     });
00134 }
00135
00136 // This function deletes the indexed item with the key "SampleKey0" added to the index by this app via the ContentIndexer
00137 void S2_UpdateAndDeleteWithAPI::S2_UpdateAndDeleteWithAPI::DeleteSingleItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00138 {
00139     return DeleteItemsHelper(std::function<IAsyncAction^(Windows::Storage::Search::ContentIndexer^)>(
00140         [](Windows::Storage::Search::ContentIndexer^ indexer) -> IAsyncAction^
00141         {
00142             return indexer->DeleteAsync(L"SampleKey0");
00143         }));
00144 }
00145
00146 // This function deletes the indexed items with the keys "SampleKey1" and "SampleKey2" added to the index by this app via the ContentIndexer
00147 void S2_UpdateAndDeleteWithAPI::S2_UpdateAndDeleteWithAPI::DeleteMultipleItems_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00148 {
00149     return DeleteItemsHelper(std::function<IAsyncAction^(Windows::Storage::Search::ContentIndexer^)>(
00150         [](Windows::Storage::Search::ContentIndexer^ indexer) -> IAsyncAction^
00151         {
00152             auto documentKeys = ref new Vector<String^>();
00153             documentKeys->Append(L"SampleKey1");
00154             documentKeys->Append(L"SampleKey2");
00155             return indexer->DeleteMultipleAsync(documentKeys);
00156         }));
00157 }
00158
00159 // This function deletes all items added to the index by this app via the ContentIndexer
00160 void S2_UpdateAndDeleteWithAPI::S2_UpdateAndDeleteWithAPI::DeleteAllItems_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00161 {
00162     return DeleteItemsHelper(std::function<IAsyncAction^(Windows::Storage::Search::ContentIndexer^)>(
00163         [](Windows::Storage::Search::ContentIndexer^ indexer) -> IAsyncAction^
00164         {
00165             return indexer->DeleteAllAsync();
00166         }));
00167 }
Generated on Fri Nov 15 2024 22:18:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cppwinrt/Scenario3_CustomItems.cpp Source File

  • JumpList
  • cppwinrt

Scenario3_CustomItems.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_CustomItems.h"
00014 #include "Scenario3_CustomItems.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::UI::StartScreen;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Navigation;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     Scenario3_CustomItems::Scenario3_CustomItems()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     void Scenario3_CustomItems::DisplayNameLocalizedResource_Click(IInspectable const&, RoutedEventArgs const&)
00030     {
00031         DisplayName().IsEnabled(!DisplayNameLocalizedResource().IsChecked());
00032         DisplayName().Text (L"ms-resource:///Resources/CustomJumpListItemDisplayName");
00033
00034     }
00035
00036     void Scenario3_CustomItems::DescriptionLocalizedResource_Click(IInspectable const&, RoutedEventArgs const&)
00037     {
00038         Description().IsEnabled(!DescriptionLocalizedResource().IsChecked());
00039         Description().Text(L"ms-resource:///Resources/CustomJumpListItemDescription");
00040
00041     }
00042
00043     void Scenario3_CustomItems::GroupNameLocalizedResource_Click(IInspectable const&, RoutedEventArgs const&)
00044     {
00045         GroupName().IsEnabled(!GroupNameLocalizedResource().IsChecked());
00046         GroupName().Text(L"ms-resource:///Resources/CustomJumpListGroupName");
00047     }
00048
00049     fire_and_forget Scenario3_CustomItems::AddToJumpList_Click(IInspectable const&, RoutedEventArgs const&)
00050     {
00051         auto lifetime = get_strong();
00052
00053         JumpList jumpList = co_await JumpList::LoadCurrentAsync();
00054         jumpList.SystemGroupKind(JumpListSystemGroupKind::Recent);
00055
00056         auto item = JumpListItem::CreateWithArguments(Arguments().Text(), DisplayName().Text());
00057         item.Description(Description().Text());
00058         item.GroupName(GroupName().Text());
00059         item.Logo(Uri(L"ms-appx:///Assets/smalltile-sdk.png"));
00060
00061         jumpList.Items().Append(item);
00062
00063         co_await jumpList.SaveAsync();
00064     }
00065 }
Generated on Fri Nov 15 2024 22:20:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PresenceSensor/cppwinrt/Scenario2_Polling.cpp Source File

  • PresenceSensor
  • cppwinrt

Scenario2_Polling.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SampleConfiguration.h"
00014 #include "Scenario2_Polling.h"
00015 #include "Scenario2_Polling.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace Windows::Devices::Enumeration;
00019 using namespace Windows::Devices::Sensors;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Globalization::DateTimeFormatting;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 namespace winrt::SDKTemplate::implementation
00027 {
00028     Scenario2_Polling::Scenario2_Polling()
00029     {
00030         InitializeComponent();
00031     }
00032
00033     fire_and_forget Scenario2_Polling::ScenarioGetSensor_Click(IInspectable const&, RoutedEventArgs const&)
00034     {
00035         // This scenario uses DeviceInformation::FindAllAsync to find all
00036         // HumanPresenceSensor devices. This allows the app to choose a sensor
00037         // which best fits its requirements.
00038         //
00039         // Scenario 1 shows how to get the default HumanPresenceSensor device.
00040
00041         // Disable the button so the user can't click it again while we are already working.
00042         GetSensorButton().IsEnabled(false);
00043
00044         // Clear any previous message.
00045         rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00046
00047         hstring selector = HumanPresenceSensor::GetDeviceSelector();
00048         DeviceInformationCollection deviceInfos = co_await DeviceInformation::FindAllAsync(selector);
00049         for (DeviceInformation deviceInfo : deviceInfos)
00050         {
00051             HumanPresenceSensor foundSensor{ nullptr };
00052             try
00053             {
00054                 foundSensor = co_await HumanPresenceSensor::FromIdAsync(deviceInfo.Id());
00055             }
00056             catch (hresult_access_denied const&)
00057             {
00058                 // The user denied this app presence sensor access.
00059                 foundSensor = nullptr;
00060             }
00061
00062             if (foundSensor != nullptr)
00063             {
00064                 IReference<uint32_t> maxDetectableDistanceInMillimeters = foundSensor.MaxDetectableDistanceInMillimeters();
00065                 IReference<uint32_t> minDetectableDistanceInMillimeters = foundSensor.MinDetectableDistanceInMillimeters();
00066                 if (maxDetectableDistanceInMillimeters != nullptr)
00067                 {
00068                     // Check if this is the sensor that matches our ranges.
00069                     // TODO: Customize these values to your application's needs.
00070                     constexpr uint32_t distanceInMillimetersLValue = 200; // 0.2m
00071                     constexpr uint32_t distanceInMillimetersRValue = 1200; // 1.2m
00072                     if (minDetectableDistanceInMillimeters.Value() <= distanceInMillimetersLValue &&
00073                         maxDetectableDistanceInMillimeters.Value() >= distanceInMillimetersRValue)
00074                     {
00075                         rootPage.NotifyUser(L"Found a presence sensor that meets the detection range", NotifyType::StatusMessage);
00076                         sensor = foundSensor;
00077                     }
00078                     else
00079                     {
00080                         rootPage.NotifyUser(L"Presence sensor does not meet the detection range, using it anyway", NotifyType::StatusMessage);
00081                         // We'll use the sensor anyway, to demonstrate how events work.
00082                         // Your app may decide not to use this sensor and keep looking for another.
00083                         sensor = foundSensor;
00084                     }
00085                 }
00086                 else
00087                 {
00088                     rootPage.NotifyUser(L"Presence sensor does not report detection ranges, using it anyway", NotifyType::StatusMessage);
00089                     sensor = foundSensor;
00090                 }
00091             }
00092
00093             if (sensor != nullptr)
00094             {
00095                 // We found a sensor we like. We can stop looking now.
00096                 break;
00097             }
00098         }
00099
00100         GetSensorButton().IsEnabled(true);
00101
00102         if (sensor != nullptr)
00103         {
00104             VisualStateManager::GoToState(*this, L"Ready", true);
00105         }
00106         else
00107         {
00108             rootPage.NotifyUser(L"No presence sensor found", NotifyType::ErrorMessage);
00109         }
00110     }
00111
00112     void Scenario2_Polling::ScenarioGetData_Click(IInspectable const&, RoutedEventArgs const&)
00113     {
00114         HumanPresenceSensorReading reading{ nullptr };
00115         try
00116         {
00117             reading = sensor.GetCurrentReading();
00118         }
00119         catch (hresult_access_denied const&)
00120         {
00121             reading = nullptr;
00122         }
00123
00124         if (reading != nullptr)
00125         {
00126             if (sensor.IsEngagementSupported())
00127             {
00128                 EngagementStateTextBlock().Text(to_hstring(reading.Engagement()));
00129             }
00130             else
00131             {
00132                 EngagementStateTextBlock().Text(L"Not Supported");
00133             }
00134
00135             if (sensor.IsPresenceSupported())
00136             {
00137                 DetectionStateTextBlock().Text(to_hstring(reading.Presence()));
00138             }
00139             else
00140             {
00141                 DetectionStateTextBlock().Text(L"Not Supported");
00142             }
00143
00144             // Show the detection distance, if available
00145             IReference<uint32_t> distance = reading.DistanceInMillimeters();
00146             DetectionDistanceTextBlock().Text(distance == nullptr ? L"Unavailable" : to_hstring(distance.Value()));
00147
00148             TimestampTextBlock().Text(DateTimeFormatter(L"shortdate longtime").Format(reading.Timestamp()));
00149         }
00150     }
00151 }
Generated on Fri Nov 15 2024 22:20:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FolderEnumeration/cpp/SampleConfiguration.cpp Source File

  • FolderEnumeration
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Enumerate files and folders in the Pictures library",        "SDKTemplate.Scenario1" },
00012     { "Enumerate files in the Pictures library, by groups",         "SDKTemplate.Scenario2" },
00013     { "Enumerate files in the Pictures library with prefetch APIs", "SDKTemplate.Scenario3" },
00014     { "Enumerate files in a folder and display availability",       "SDKTemplate.Scenario4" },
00015 };
Generated on Fri Nov 15 2024 22:17:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Level5.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Level5.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Level5.h"
00014 #include "Cylinder.h"
00015 #include "Animate.h"
00016
00017 using namespace DirectX;
00018
00019 Level5::Level5()
00020 {
00021     m_timeLimit = 30.0f;
00022     m_objective = L"Hit each of the moving targets while avoiding the obstacles before time runs out.";
00023 }
00024
00025 void Level5::Initialize(std::vector<std::shared_ptr<GameObject>> const& objects)
00026 {
00027     Level3::Initialize(objects);
00028
00029     static constexpr XMFLOAT3 obstacleStartPosition[] =
00030     {
00031         XMFLOAT3(-4.5f, -3.0f, 0.0f),
00032         XMFLOAT3(4.5f, -3.0f, 0.0f),
00033         XMFLOAT3(0.0f, 3.01f, -2.0f),
00034         XMFLOAT3(-1.5f, -3.0f, -6.5f),
00035         XMFLOAT3(1.5f, -3.0f, -6.5f)
00036     };
00037     static constexpr XMFLOAT3 obstacleEndPosition[] =
00038     {
00039         XMFLOAT3(-2.0f, -3.0f, 0.0f),
00040         XMFLOAT3(2.0f, -3.0f, 0.0f),
00041         XMFLOAT3(0.0f, -3.0f, -2.0f),
00042         XMFLOAT3(-1.5f, -3.0f, -4.0f),
00043         XMFLOAT3(1.5f, -3.0f, -4.0f)
00044     };
00045     static constexpr float obstacleStartTime[] =
00046     {
00047         2.0f,
00048         5.0f,
00049         8.0f,
00050         11.0f,
00051         14.0f
00052     };
00053
00054     int obstacleCount = 0;
00055     for (auto&& object : objects)
00056     {
00057         if (auto obstacle = dynamic_cast<Cylinder*>(object.get()))
00058         {
00059             if (obstacleCount < 5)
00060             {
00061                 obstacle->Active(true);
00062                 obstacle->Position(obstacleStartPosition[obstacleCount]);
00063                 obstacle->AnimatePosition(
00064                     std::make_shared<AnimateLinePosition>(
00065                         obstacleStartPosition[obstacleCount],
00066                         obstacleEndPosition[obstacleCount],
00067                         (float)10.0,
00068                         false
00069                         )
00070                     );
00071                 obstacle->AnimatePosition()->Start(obstacleStartTime[obstacleCount]);
00072                 obstacleCount++;
00073             }
00074         }
00075     }
00076 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VideoItem Member List

This is the complete list of members for VideoItem, including all inherited members.
SourceUri | VideoItem |
Title | VideoItem |
VideoItem(string title, Uri sourceUri) | VideoItem | [inline]
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_DataEvents Member List

This is the complete list of members for Scenario1_DataEvents, including all inherited members.
_desiredReportInterval | Scenario1_DataEvents | [private]
_sensor | Scenario1_DataEvents | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_DataEvents | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario1_DataEvents | [inline, protected]
ReadingChanged(object sender, LightSensorReadingChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
rootPage | Scenario1_DataEvents | [private]
Scenario1_DataEvents() | Scenario1_DataEvents | [inline]
ScenarioDisable(object sender, RoutedEventArgs e) | Scenario1_DataEvents | [inline, private]
ScenarioEnable(object sender, RoutedEventArgs e) | Scenario1_DataEvents | [inline, private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PasswordVault/cppwinrt/Project.idl Source File

  • PasswordVault
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 namespace SDKTemplate
00002 {
00003     [default_interface]
00004     runtimeclass Scenario1_Save : Windows.UI.Xaml.Controls.Page
00005     {
00006         Scenario1_Save();
00007     }
00008
00009     [default_interface]
00010     runtimeclass Scenario2_Manage : Windows.UI.Xaml.Controls.Page
00011     {
00012         Scenario2_Manage();
00013     }
00014 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cpp/1-InputEvents.xaml.cpp Source File

  • BasicInput
  • cpp

1-InputEvents.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "1-InputEvents.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021 using namespace Windows::UI::Xaml::Controls::Primitives;
00022 using namespace Windows::UI::Xaml::Data;
00023 using namespace Windows::UI::Xaml::Input;
00024 using namespace Windows::UI::Xaml::Media;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 Scenario1::Scenario1()
00028 {
00029     InitializeComponent();
00030
00031     // pointer press/release handlers
00032     pressedTarget->PointerPressed += ref new PointerEventHandler(this, &Scenario1::target_PointerPressed);
00033     pressedTarget->PointerReleased += ref new PointerEventHandler(this, &Scenario1::target_PointerReleased);
00034
00035     // pointer enter/exit handlers
00036     enterExitTarget->PointerEntered += ref new PointerEventHandler(this, &Scenario1::target_PointerEntered);
00037     enterExitTarget->PointerExited += ref new PointerEventHandler(this, &Scenario1::target_PointerExited);
00038
00039     // gesture handlers
00040     tapTarget->Tapped += ref new TappedEventHandler(this, &Scenario1::target_Tapped);
00041     tapTarget->DoubleTapped += ref new DoubleTappedEventHandler(this, &Scenario1::target_DoubleTapped);
00042
00043     holdTarget->Holding += ref new HoldingEventHandler(this, &Scenario1::target_Holding);
00044     holdTarget->RightTapped += ref new RightTappedEventHandler(this, &Scenario1::target_RightTapped);
00045 }
00046
00047 // A PointerPressed event is sent whenever a mouse button, finger, or pen is pressed to make
00048 // contact with an object
00049 void Scenario1::target_PointerPressed(Object^ sender, PointerRoutedEventArgs^ e)
00050 {
00051     pressedTarget->Background = ref new SolidColorBrush(Windows::UI::Colors::RoyalBlue);
00052     pressedTargetText->Text = "Pointer Pressed";
00053 }
00054
00055 // A PointerReleased event is sent whenever a mouse button, finger, or pen is released to remove
00056 // contact from an object
00057 void Scenario1::target_PointerReleased(Object^ sender, PointerRoutedEventArgs^ e)
00058 {
00059     pressedTarget->Background = ref new SolidColorBrush(Windows::UI::Colors::LightGray);
00060     pressedTargetText->Text = "Pointer Released";
00061 }
00062
00063 // A PointerEntered event is sent whenever a mouse cursor is moved on top of an object
00064 // or when a pen or finger is dragged on top of an object
00065 void Scenario1::target_PointerEntered(Object^ sender, PointerRoutedEventArgs^ e)
00066 {
00067     enterExitTarget->Background = ref new SolidColorBrush(Windows::UI::Colors::RoyalBlue);
00068     enterExitTargetText->Text = "Pointer Entered";
00069 }
00070
00071 // A PointerExited event is sent whenever a mouse cursor is moved off of an object
00072 // or when a pen or finger is dragged off of an object
00073 void Scenario1::target_PointerExited(Object^ sender, PointerRoutedEventArgs^ e)
00074 {
00075     enterExitTarget->Background = ref new SolidColorBrush(Windows::UI::Colors::LightGray);
00076     enterExitTargetText->Text = "Pointer Exited";
00077 }
00078
00079 // A Tapped event is sent whenever a mouse is clicked or a finger or pen taps
00080 // the object
00081 void Scenario1::target_Tapped(Object^ sender, TappedRoutedEventArgs^ e)
00082 {
00083     tapTarget->Background = ref new SolidColorBrush(Windows::UI::Colors::DeepSkyBlue);
00084     tapTargetText->Text = "Tapped";
00085 }
00086
00087 // A DoubleTapped event is sent whenever a mouse is double-clicked or a finger or pen taps
00088 // the object twice in quick succession
00089 void Scenario1::target_DoubleTapped(Object^ sender, DoubleTappedRoutedEventArgs^ e)
00090 {
00091     tapTarget->Background = ref new SolidColorBrush(Windows::UI::Colors::RoyalBlue);
00092     tapTargetText->Text = "Double-Tapped";
00093 }
00094
00095 // A RightTapped event is sent whenever a mouse is right-clicked or a finger or pen
00096 // completes a Holding event.  This is intended to be used to handle secondary actions
00097 // on an object.
00098 void Scenario1::target_RightTapped(Object^ sender, RightTappedRoutedEventArgs^ e)
00099 {
00100     holdTarget->Background = ref new SolidColorBrush(Windows::UI::Colors::RoyalBlue);
00101     holdTargetText->Text = "Right Tapped";
00102 }
00103
00104 // A Holding event is sent whenever a finger or pen is pressed and held on top of
00105 // an object.
00106 // Once a small amount of time has elapsed, the event is sent with a HoldingState
00107 // of the type HoldingState.Started, indicating that the held threshold has just
00108 // been passed.
00109 // When a finger has been lifted after a successful hold, a Holding event is sent
00110 // with a HoldingState of Completed.
00111 // If the user cancels the hold after it has been started, but before it completes,
00112 // a Holding event is sent with a HoldingState of Canceled.
00113 void Scenario1::target_Holding(Object^ sender, HoldingRoutedEventArgs^ e)
00114 {
00115     if (e->HoldingState == Windows::UI::Input::HoldingState::Started)
00116     {
00117         holdTarget->Background = ref new SolidColorBrush(Windows::UI::Colors::DeepSkyBlue);
00118         holdTargetText->Text = "Holding";
00119     }
00120     else if (e->HoldingState == Windows::UI::Input::HoldingState::Completed)
00121     {
00122         holdTarget->Background = ref new SolidColorBrush(Windows::UI::Colors::LightGray);
00123         holdTargetText->Text = "Held";
00124     }
00125     else
00126     {
00127         holdTarget->Background = ref new SolidColorBrush(Windows::UI::Colors::LightGray);
00128         holdTargetText->Text = "Hold Canceled";
00129     }
00130 }
00131
Generated on Fri Nov 15 2024 22:18:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/Actions/Action/TextAndImage/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • Actions
  • Action
  • TextAndImage

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Notifications;
00003 using Windows.UI.Popups;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00008
00009 namespace Notifications.ScenarioPages.Toasts.Actions.Action.TextAndImage
00010 {
00011     /// <summary>
00012     /// An empty page that can be used on its own or navigated to within a Frame.
00013     /// </summary>
00014     public sealed partial class ScenarioElement : UserControl
00015     {
00016         public ScenarioElement()
00017         {
00018             this.InitializeComponent();
00019         }
00020
00021         private void UserControl_Loaded(object sender, RoutedEventArgs e)
00022         {
00023             Initialize();
00024         }
00025
00026         private void Initialize()
00027         {
00028             // Clear all existing notifications
00029             ToastNotificationManager.History.Clear();
00030
00031             // Pop notifications
00032             popToastControl.Payload =
00033                 $@"
00034                 <toast activationType='foreground' launch='args'>
00035                     <visual>
00036                         <binding template='ToastGeneric'>
00037                             <text>Action - text and image</text>
00038                             <text>Make sure the left button has a ""check"" icon with the text ""check"" below it, and the right button has a ""cancel"" icon with the text ""cancel"" below it.</text>
00039                         </binding>
00040                     </visual>
00041                     <actions>
00042
00043                         <action
00044                             content='check'
00045                             imageUri='Assets/check.png'
00046                             activationType='foreground'
00047                             arguments='check'/>
00048
00049                         <action
00050                             content='cancel'
00051                             imageUri='Assets/cancel.png'
00052                             activationType='foreground'
00053                             arguments='cancel'/>
00054
00055                     </actions>
00056                 </toast>";
00057         }
00058
00059         private async void Error(string message)
00060         {
00061             await new MessageDialog(message, "ERROR").ShowAsync();
00062         }
00063     }
00064 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboardTextInput/cs/Scenario1_SpellingTextSuggestions.xaml.cs Source File

  • TouchKeyboardTextInput
  • cs

Scenario1_SpellingTextSuggestions.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016
00017 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class Scenario1_SpellingTextSuggestions : Page
00025     {
00026         public Scenario1_SpellingTextSuggestions()
00027         {
00028             this.InitializeComponent();
00029         }
00030     }
00031 }
Generated on Fri Nov 15 2024 22:21:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cppwinrt/Project.idl Source File

  • IoT-GPIO
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_GetAndSetPin : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_GetAndSetPin();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_Listen : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_Listen();
00024     }
00025 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cpp/Scenario4.xaml.h Source File

  • FileThumbnails
  • cpp

Scenario4.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario4.xaml.h
00014 // Declaration of the Scenario4 class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario4.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     [Windows::Foundation::Metadata::WebHostHidden]
00026     public ref class Scenario4 sealed
00027     {
00028     public:
00029         Scenario4();
00030
00031     protected:
00032         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00033
00034     private:
00035         MainPage^ rootPage;
00036
00037         void GetThumbnailButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Fri Nov 15 2024 22:18:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OCR/cpp/WordOverlay.h Source File

  • OCR
  • cpp

WordOverlay.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 using namespace Windows::Foundation;
00015 using namespace Windows::Media::Ocr;
00016 using namespace Windows::UI::Xaml;
00017 using namespace Windows::UI::Xaml::Data;
00018 using namespace Windows::UI::Xaml::Media;
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// Wraps recognized word and provides word overlay position and size based on current scale.
00024     /// </summary>
00025     [Windows::UI::Xaml::Data::Bindable]
00026     public ref class WordOverlay sealed : INotifyPropertyChanged
00027     {
00028     public:
00029         WordOverlay(OcrWord^ ocrWord);
00030
00031         /// <summary>
00032         /// Left and Right properties of Thickess define word box position.
00033         /// </summary>
00034         property Thickness WordPosition
00035         {
00036             Thickness get()
00037             {
00038                 return wordPosition;
00039             }
00040         }
00041
00042         /// <summary>
00043         /// Scaled word box width.
00044         /// </summary>
00045         property double WordWidth
00046         {
00047             double get()
00048             {
00049                 return wordWidth;
00050             }
00051         }
00052
00053         /// <summary>
00054         /// Scaled word box height.
00055         /// </summary>
00056         property double WordHeight
00057         {
00058             double get()
00059             {
00060                 return wordHeight;
00061             }
00062         }
00063
00064         virtual event PropertyChangedEventHandler^ PropertyChanged
00065         {
00066             virtual EventRegistrationToken add(PropertyChangedEventHandler^ e)
00067             {
00068                 isPropertyChangedObserved = true;
00069                 return privatePropertyChanged += e;
00070             }
00071
00072             virtual void remove(EventRegistrationToken t)
00073             {
00074                 privatePropertyChanged -= t;
00075             }
00076
00077         protected:
00078             virtual void raise(Object^ sender, PropertyChangedEventArgs^ e)
00079             {
00080                 if (isPropertyChangedObserved)
00081                 {
00082                     privatePropertyChanged(sender, e);
00083                 }
00084             }
00085         }
00086
00087         void Transform(ScaleTransform^ transform);
00088         Binding^ CreateWordPositionBinding();
00089         Binding^ CreateWordWidthBinding();
00090         Binding^ CreateWordHeightBinding();
00091
00092     protected:
00093         void OnPropertyChanged(Platform::String^ propertyName);
00094
00095     private:
00096         OcrWord^ word;
00097
00098         Thickness wordPosition;
00099         double wordWidth;
00100         double wordHeight;
00101
00102         bool isPropertyChangedObserved;
00103         event PropertyChangedEventHandler^ privatePropertyChanged;
00104
00105         void UpdateProps(Rect boundingBox);
00106     };
00107 }
Generated on Fri Nov 15 2024 22:20:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4 Member List

This is the complete list of members for Scenario4, including all inherited members.
CloseSockets_Click(object sender, RoutedEventArgs e) | Scenario4 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario4 | [inline, protected]
rootPage | Scenario4 | [private]
Scenario4() | Scenario4 | [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaTranscoding/cpp/Scenario2_Custom.xaml.cpp Source File

  • MediaTranscoding
  • cpp

Scenario2_Custom.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Custom.xaml.h"
00014 #include <codecapi.h> // for eAVEncH264VLevel5_2
00015 #include <initguid.h>
00016 #include <mfapi.h> // for MF_MT_VIDEO_LEVEL
00017
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Media;
00021 using namespace Windows::Media::MediaProperties;
00022 using namespace Windows::Media::Transcoding;
00023 using namespace Windows::Storage;
00024 using namespace Windows::Storage::Pickers;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Navigation;
00028 using namespace Windows::Storage::Streams;
00029 using namespace concurrency;
00030 using namespace SDKTemplate;
00031
00032 Scenario2_Custom::Scenario2_Custom()
00033 {
00034     InitializeComponent();
00035
00036     // Hook up the UI
00037     PickFileButton->Click += ref new RoutedEventHandler(this, &Scenario2_Custom::PickFile);
00038     SetOutputButton->Click += ref new RoutedEventHandler(this, &Scenario2_Custom::PickOutput);
00039     TargetFormat->SelectionChanged += ref new SelectionChangedEventHandler(this, &Scenario2_Custom::OnTargetFormatChanged);
00040     Transcode->Click += ref new RoutedEventHandler(this, &Scenario2_Custom::TranscodeCustom);
00041     Cancel->Click += ref new RoutedEventHandler(this, &Scenario2_Custom::TranscodeCancel);
00042
00043     // Media Controls
00044     InputPlayButton->Click += ref new RoutedEventHandler(this, &Scenario2_Custom::InputPlayButton_Click);
00045     InputPauseButton->Click += ref new RoutedEventHandler(this, &Scenario2_Custom::InputPauseButton_Click);
00046     InputStopButton->Click += ref new RoutedEventHandler(this, &Scenario2_Custom::InputStopButton_Click);
00047     OutputPlayButton->Click += ref new RoutedEventHandler(this, &Scenario2_Custom::OutputPlayButton_Click);
00048     OutputPauseButton->Click += ref new RoutedEventHandler(this, &Scenario2_Custom::OutputPauseButton_Click);
00049     OutputStopButton->Click += ref new RoutedEventHandler(this, &Scenario2_Custom::OutputStopButton_Click);
00050
00051     // File is not selected, disable all buttons but PickFileButton
00052     DisableButtons();
00053     SetPickFileButton(true);
00054     SetCancelButton(false);
00055     SetOutputFileButton(false);
00056
00057     // Initialize Objects
00058     _Transcoder = ref new MediaTranscoder();
00059     _Profile = nullptr;
00060     _InputFile = nullptr;
00061     _OutputFile = nullptr;
00062     _OutputFileName = "TranscodeSampleOutput";
00063     _OutputFileExtension = ".mp4";
00064     _OutputType = "MP4";
00065     _CTS = cancellation_token_source();
00066
00067     // Initialize UI with default settings
00068     MediaEncodingProfile^ defaultProfile = MediaEncodingProfile::CreateMp4(VideoEncodingQuality::Wvga);
00069     VideoW->Text = defaultProfile->Video->Width.ToString();
00070     VideoH->Text = defaultProfile->Video->Height.ToString();
00071     VideoBR->Text = defaultProfile->Video->Bitrate.ToString();
00072     VideoFR->Text = defaultProfile->Video->FrameRate->Numerator.ToString();
00073     AudioBPS->Text = defaultProfile->Audio->BitsPerSample.ToString();
00074     AudioCC->Text = defaultProfile->Audio->ChannelCount.ToString();
00075     AudioBR->Text = defaultProfile->Audio->Bitrate.ToString();
00076     AudioSR->Text = defaultProfile->Audio->SampleRate.ToString();
00077
00078     _UseMp4 = true;
00079 }
00080
00081 /// <summary>
00082 /// Invoked when this page is about to be displayed in a Frame.
00083 /// </summary>
00084 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00085 /// property is typically used to configure the page.</param>
00086 void Scenario2_Custom::OnNavigatedTo(NavigationEventArgs^ e)
00087 {
00088     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00089     // as NotifyUser()
00090     rootPage = MainPage::Current;
00091 }
00092
00093 void Scenario2_Custom::GetCustomProfile()
00094 {
00095     if (_UseMp4)
00096     {
00097         _Profile = MediaEncodingProfile::CreateMp4(VideoEncodingQuality::Wvga);
00098     }
00099     else
00100     {
00101         _Profile = MediaEncodingProfile::CreateWmv(VideoEncodingQuality::Wvga);
00102     }
00103
00104     // TryParse() is not available. Using _wtoi() with #include <stdlib.h>
00105     try
00106     {
00107         _Profile->Video->Width = _wtoi(VideoW->Text->Data());
00108         _Profile->Video->Height = _wtoi(VideoH->Text->Data());
00109         _Profile->Video->Bitrate = _wtoi(VideoBR->Text->Data());
00110         _Profile->Video->FrameRate->Numerator = _wtoi(VideoFR->Text->Data());
00111         _Profile->Video->FrameRate->Denominator = 1;
00112         _Profile->Audio->BitsPerSample = _wtoi(AudioBPS->Text->Data());
00113         _Profile->Audio->ChannelCount = _wtoi(AudioCC->Text->Data());
00114         _Profile->Audio->Bitrate = _wtoi(AudioBR->Text->Data());
00115         _Profile->Audio->SampleRate = _wtoi(AudioSR->Text->Data());
00116
00117         // Video sources providing more than about 250 megapixels per second require the
00118         // H.264 encoder to be set to level 5.2. Information about H.264 encoding levels:
00119         // https://en.wikipedia.org/wiki/Advanced_Video_Coding#Levels
00120         // Windows doesn't always set the higher level automatically so it should be set
00121         // explicitly to avoid encoding failures. Constants needed to set the encoding level:
00122         // https://docs.microsoft.com/en-us/windows/win32/medfound/mf-mt-video-level
00123         // https://docs.microsoft.com/en-us/windows/win32/api/codecapi/ne-codecapi-eavench264vlevel
00124         if (_UseMp4)
00125         {
00126             static const int c_PixelsPerSecondRequiringLevel52 = 250000000;
00127             if (_Profile->Video->Width * _Profile->Video->Height *
00128                 _Profile->Video->FrameRate->Numerator / _Profile->Video->FrameRate->Denominator >
00129                 c_PixelsPerSecondRequiringLevel52)
00130             {
00131                 _Profile->Video->Properties->Insert(MF_MT_VIDEO_LEVEL, static_cast<UINT32>(eAVEncH264VLevel5_2));
00132             }
00133         }
00134     }
00135     catch (Exception^ exception)
00136     {
00137         TranscodeError(exception->Message);
00138     }
00139 }
00140
00141 void Scenario2_Custom::TranscodeCustom(Object^ sender, RoutedEventArgs^ e)
00142 {
00143     StopPlayers();
00144     DisableButtons();
00145     GetCustomProfile();
00146
00147     if ((EnableMrfCrf444->IsChecked != nullptr) && (EnableMrfCrf444->IsChecked->Value))
00148     {
00149         _Transcoder->VideoProcessingAlgorithm = Windows::Media::Transcoding::MediaVideoProcessingAlgorithm::MrfCrf444;
00150     }
00151     else
00152     {
00153         _Transcoder->VideoProcessingAlgorithm = Windows::Media::Transcoding::MediaVideoProcessingAlgorithm::Default;
00154     }
00155
00156     // Clear messages
00157     StatusMessage->Text = "";
00158
00159     try
00160     {
00161         if ((_InputFile != nullptr) && (_OutputFile != nullptr))
00162         {
00163             create_task(_Transcoder->PrepareFileTranscodeAsync(_InputFile, _OutputFile, _Profile)).then(
00164                 [this](PrepareTranscodeResult^ transcode)
00165             {
00166                 try
00167                 {
00168                     if (transcode->CanTranscode)
00169                     {
00170                         OutputMsg->Text = "";
00171                         SetCancelButton(true);
00172                         Windows::Foundation::IAsyncActionWithProgress<double>^ transcodeOp = transcode->TranscodeAsync();
00173
00174                         // Set Progress Callback
00175                         transcodeOp->Progress = ref new AsyncActionProgressHandler<double>(
00176                             [this](IAsyncActionWithProgress<double>^ asyncInfo, double percent) {
00177                             TranscodeProgress(asyncInfo, percent);
00178                         }, Platform::CallbackContext::Same);
00179
00180                         return transcodeOp;
00181                     }
00182                     else
00183                     {
00184                         TranscodeFailure(transcode->FailureReason);
00185                     }
00186                 }
00187                 catch (Platform::Exception^ exception)
00188                 {
00189                     TranscodeError(exception->Message);
00190                 }
00191
00192                 cancel_current_task();
00193             }).then(
00194                 [this](task<void> transcodeTask)
00195             {
00196                 try
00197                 {
00198                     transcodeTask.get();
00199                     OutputMsg->Text = "Transcode Completed.";
00200                     OutputPath->Text = "Output (" + _OutputFile->Path + ")";
00201                     PlayFile(_OutputFile);
00202                 }
00203                 catch (task_canceled&)
00204                 {
00205                     OutputMsg->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red);
00206                     OutputMsg->Text = "Transcode Cancelled.";
00207                 }
00208                 catch (Exception^ exception)
00209                 {
00210                     TranscodeError(exception->Message);
00211                 }
00212
00213                 EnableButtons();
00214                 SetCancelButton(false);
00215             });
00216         }
00217     }
00218     catch (Platform::Exception^ exception)
00219     {
00220         TranscodeError(exception->Message);
00221     }
00222 }
00223
00224 void Scenario2_Custom::TranscodeCancel(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00225 {
00226     try
00227     {
00228         _CTS.cancel();
00229         _CTS = cancellation_token_source();
00230
00231         if (_OutputFile != nullptr)
00232         {
00233             create_task(_OutputFile->DeleteAsync()).then(
00234                 [this](task<void> deleteTask)
00235             {
00236                 try
00237                 {
00238                     deleteTask.get();
00239                 }
00240                 catch (Platform::Exception^ exception)
00241                 {
00242                     TranscodeError(exception->Message);
00243                 }
00244             });
00245         }
00246     }
00247     catch (Platform::Exception^ exception)
00248     {
00249         TranscodeError(exception->Message);
00250     }
00251 }
00252
00253 void Scenario2_Custom::TranscodeProgress(IAsyncActionWithProgress<double>^ asyncInfo, double percent)
00254 {
00255     OutputMsg->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Green);
00256     OutputMsg->Text = "Progress:  " + ((int)percent).ToString() + "%";
00257 }
00258
00259 void Scenario2_Custom::TranscodeError(Platform::String^ error)
00260 {
00261     StatusMessage->Foreground = ref new Windows::UI::Xaml::Media::SolidColorBrush(Windows::UI::Colors::Red);
00262     StatusMessage->Text = error;
00263     EnableButtons();
00264     SetCancelButton(false);
00265 }
00266
00267 void Scenario2_Custom::TranscodeFailure(TranscodeFailureReason reason)
00268 {
00269     try
00270     {
00271         if (_OutputFile != nullptr)
00272         {
00273             create_task(_OutputFile->DeleteAsync()).then(
00274                 [this](task<void> deleteTask)
00275             {
00276                 try
00277                 {
00278                     deleteTask.get();
00279                 }
00280                 catch (Platform::Exception^ exception)
00281                 {
00282                     TranscodeError(exception->Message);
00283                 }
00284             });
00285         }
00286     }
00287     catch (Platform::Exception^ exception)
00288     {
00289         TranscodeError(exception->Message);
00290     }
00291
00292     switch (reason)
00293     {
00294     case TranscodeFailureReason::CodecNotFound:
00295         TranscodeError("Codec not found.");
00296         break;
00297     case TranscodeFailureReason::InvalidProfile:
00298         TranscodeError("Invalid profile.");
00299         break;
00300     default:
00301         TranscodeError("Unknown failure.");
00302     }
00303 }
00304
00305 void Scenario2_Custom::SetCancelButton(bool isEnabled)
00306 {
00307     Cancel->IsEnabled = isEnabled;
00308 }
00309
00310 void Scenario2_Custom::EnableButtons()
00311 {
00312     PickFileButton->IsEnabled = true;
00313     SetOutputButton->IsEnabled = true;
00314     TargetFormat->IsEnabled = true;
00315     EnableMrfCrf444->IsEnabled = true;
00316
00317     // The transcode button's initial state should be disabled until an output
00318     // file has been set.
00319     Transcode->IsEnabled = false;
00320 }
00321
00322 void Scenario2_Custom::DisableButtons()
00323 {
00324     PickFileButton->IsEnabled = false;
00325     SetOutputButton->IsEnabled = false;
00326     TargetFormat->IsEnabled = false;
00327     Transcode->IsEnabled = false;
00328     EnableMrfCrf444->IsEnabled = false;
00329 }
00330
00331 void Scenario2_Custom::PickFile(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00332 {
00333     try
00334     {
00335         FileOpenPicker^ picker = ref new FileOpenPicker();
00336         picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00337         picker->FileTypeFilter->Append(".wmv");
00338         picker->FileTypeFilter->Append(".mp4");
00339
00340         create_task(picker->PickSingleFileAsync()).then(
00341             [this](StorageFile^ inputFile)
00342         {
00343             try
00344             {
00345                 _InputFile = inputFile;
00346
00347                 if (_InputFile != nullptr)
00348                 {
00349                     return inputFile->OpenAsync(FileAccessMode::Read);
00350                 }
00351             }
00352             catch (Platform::Exception^ exception)
00353             {
00354                 TranscodeError(exception->Message);
00355             }
00356
00357             cancel_current_task();
00358         }).then(
00359             [this](IRandomAccessStream^ inputStream)
00360         {
00361             try
00362             {
00363                 InputVideo->SetSource(inputStream, _InputFile->ContentType);;
00364                 InputVideo->Play();
00365
00366                 //Enable buttons
00367                 EnableButtons();
00368             }
00369             catch (Platform::Exception^ exception)
00370             {
00371                 TranscodeError(exception->Message);
00372             }
00373         });
00374     }
00375     catch (Exception^ exception)
00376     {
00377         TranscodeError(exception->Message);
00378     }
00379 }
00380
00381 void Scenario2_Custom::PickOutput(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00382 {
00383     try
00384     {
00385         FileSavePicker^ picker = ref new FileSavePicker();
00386         picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00387         picker->SuggestedFileName = _OutputFileName;
00388
00389         auto extensions = ref new Platform::Collections::Vector<String^>();
00390         extensions->Append(_OutputFileExtension);
00391         picker->FileTypeChoices->Insert(_OutputType, extensions);
00392
00393         create_task(picker->PickSaveFileAsync()).then([this](StorageFile^ file) {
00394             if (file != nullptr)
00395             {
00396                 _OutputFile = file;
00397                 SetTranscodeButton(true);
00398             }
00399         });
00400     }
00401     catch (Exception^ exception)
00402     {
00403         TranscodeError(exception->Message);
00404     }
00405 }
00406
00407 void Scenario2_Custom::OnTargetFormatChanged(Object^ sender, SelectionChangedEventArgs^ e)
00408 {
00409     if (TargetFormat->SelectedIndex > 0)
00410     {
00411         _OutputFileExtension = ".wmv";
00412         _OutputType = "WMV";
00413         _UseMp4 = false;
00414     }
00415     else
00416     {
00417         _OutputFileExtension = ".mp4";
00418         _OutputType = "MP4";
00419         _UseMp4 = true;
00420     }
00421 }
00422
00423 void Scenario2_Custom::InputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00424 {
00425     if (InputVideo->DefaultPlaybackRate == 0)
00426     {
00427         InputVideo->DefaultPlaybackRate = 1.0;
00428         InputVideo->PlaybackRate = 1.0;
00429     }
00430
00431     InputVideo->Play();
00432 }
00433
00434 void Scenario2_Custom::InputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00435 {
00436     InputVideo->Stop();
00437 }
00438
00439 void Scenario2_Custom::InputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00440 {
00441     InputVideo->Pause();
00442 }
00443
00444 void Scenario2_Custom::OutputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00445 {
00446     if (OutputVideo->DefaultPlaybackRate == 0)
00447     {
00448         OutputVideo->DefaultPlaybackRate = 1.0;
00449         OutputVideo->PlaybackRate = 1.0;
00450     }
00451
00452     OutputVideo->Play();
00453 }
00454
00455 void Scenario2_Custom::OutputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00456 {
00457     OutputVideo->Stop();
00458 }
00459
00460 void Scenario2_Custom::OutputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00461 {
00462     OutputVideo->Pause();
00463 }
00464
00465 void Scenario2_Custom::SetPickFileButton(bool isEnabled)
00466 {
00467     PickFileButton->IsEnabled = isEnabled;
00468 }
00469
00470 void Scenario2_Custom::SetOutputFileButton(bool isEnabled)
00471 {
00472     SetOutputButton->IsEnabled = isEnabled;
00473 }
00474
00475 void Scenario2_Custom::SetTranscodeButton(bool isEnabled)
00476 {
00477     Transcode->IsEnabled = isEnabled;
00478 }
00479
00480
00481 void Scenario2_Custom::StopPlayers()
00482 {
00483     if (InputVideo->CurrentState != Media::MediaElementState::Paused)
00484     {
00485         InputVideo->Pause();
00486     }
00487     if (OutputVideo->CurrentState != Media::MediaElementState::Paused)
00488     {
00489         OutputVideo->Pause();
00490     }
00491 }
00492
00493 void Scenario2_Custom::PlayFile(Windows::Storage::StorageFile^ MediaFile)
00494 {
00495     try
00496     {
00497         create_task(MediaFile->OpenAsync(FileAccessMode::Read)).then(
00498             [&, this, MediaFile](IRandomAccessStream^ outputStream)
00499         {
00500             try
00501             {
00502                 OutputVideo->SetSource(outputStream, MediaFile->ContentType);
00503                 OutputVideo->Play();
00504             }
00505             catch (Platform::Exception^ exception)
00506             {
00507                 TranscodeError(exception->Message);
00508             }
00509         });
00510     }
00511     catch (Exception^ exception)
00512     {
00513         TranscodeError(exception->Message);
00514     }
00515 }
Generated on Fri Nov 15 2024 22:20:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: KeyCredentialManager/cpp/UserSelect.xaml.cpp Source File

  • KeyCredentialManager
  • cpp

UserSelect.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "UserSelect.xaml.h"
00005 #include "Account.h"
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace Platform;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::Storage;
00013 using namespace Windows::UI::Popups;
00014 using namespace Windows::UI::Xaml;
00015 using namespace Windows::UI::Xaml::Controls;
00016 using namespace Windows::UI::Xaml::Controls::Primitives;
00017 using namespace Windows::UI::Xaml::Data;
00018 using namespace Windows::UI::Xaml::Input;
00019 using namespace Windows::UI::Xaml::Media;
00020 using namespace Windows::UI::Xaml::Navigation;
00021 using namespace Windows::UI::Xaml::Interop;
00022
00023 UserSelect::UserSelect() : rootPage(MainPage::Current)
00024 {
00025     InitializeComponent();
00026     m_accountListView = listView_UserTileList;
00027     m_accountListView->SelectionChanged += ref new SelectionChangedEventHandler(this, &SDKTemplate::UserSelect::Button_SelectUser_Click);
00028     this->Loaded += ref new RoutedEventHandler(this, &SDKTemplate::UserSelect::OnLoadedActions);
00029 }
00030
00031 /// <summary>
00032 /// Function called when the current frame is loaded.
00033 ///
00034 /// Calls SetUpAccounts
00035 /// </summary>
00036 /// <param name="sender"></param>
00037 /// <param name="e"></param>
00038 void UserSelect::OnLoadedActions(Object^ sender, RoutedEventArgs^ e)
00039 {
00040     SetUpAccounts();
00041 }
00042
00043 /// <summary>
00044 ///
00045 /// Function called when an account is selected in the list of accounts
00046 ///
00047 /// Navigates to the sign in form and passes the chosen account
00048 /// The sign in form will check if Microsoft Passport should be used or not
00049 /// </summary>
00050 /// <param name="sender"></param>
00051 /// <param name="e"></param>
00052 void UserSelect::Button_SelectUser_Click(Object^ sender, SelectionChangedEventArgs^ e)
00053 {
00054     if (((ListView^)sender)->SelectedValue != nullptr)
00055     {
00056         Account^ account = ref new Account();
00057         Account^ selectedAccount = m_accountList->GetAt(((ListView^)sender)->SelectedIndex);
00058
00059         account->Name = selectedAccount->Name;
00060         account->Email = selectedAccount->Email;
00061         account->UsesPassport = selectedAccount->UsesPassport;
00062
00063         rootPage->NotifyUser("Account " + account->Name + " selected!", NotifyType::StatusMessage);
00064         TypeName signInType = { "SDKTemplate.SignIn", TypeKind::Custom };
00065         this->Frame->Navigate(signInType, account);
00066     }
00067 }
00068
00069 /// <summary>
00070 /// Function called when the "+" button is clicked for adding a new account
00071 ///
00072 /// Just navigates to the default sign in form with nothing filled out
00073 /// </summary>
00074 /// <param name="sender"></param>
00075 /// <param name="e"></param>
00076 void UserSelect::Button_AddUser_Click(Object^ sender, RoutedEventArgs^ e)
00077 {
00078     TypeName signInType = { "SDKTemplate.SignIn", TypeKind::Custom };
00079     this->Frame->Navigate(signInType);
00080 }
00081
00082 /// <summary>
00083 /// Checks to see if the user list has been created yet.
00084 /// If it hasn't then create it and then just go to the sign in form.
00085 /// Otherwise, load the list of users into the ListView.
00086 /// </summary>
00087 void UserSelect::SetUpAccounts()
00088 {
00089     if (m_accountList == nullptr)
00090     {
00091         m_accountList = ref new Platform::Collections::Vector<Account^>();
00092     }
00093     else
00094     {
00095         Platform::Collections::Vector<String^>^ usernames = ref new Platform::Collections::Vector<String^>();
00096
00097         for (unsigned int i = 0; i < m_accountList->Size; i++)
00098         {
00099             usernames->Append(m_accountList->GetAt(i)->Email);
00100         }
00101
00102         m_accountListView->ItemsSource = usernames;
00103     }
00104
00105     if (m_accountList->Size == 0)
00106     {
00107         TypeName signInType = { "SDKTemplate.SignIn", TypeKind::Custom };
00108         this->Frame->Navigate(signInType);
00109     }
00110 }
Generated on Fri Nov 15 2024 22:20:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario8_VisitsBackgroundTask Member List

This is the complete list of members for Scenario8_VisitsBackgroundTask, including all inherited members.
_rootPage | Scenario8_VisitsBackgroundTask | [private]
_visitTask | Scenario8_VisitsBackgroundTask | [private]
BackgroundTaskEntryPoint | Scenario8_VisitsBackgroundTask | [private]
BackgroundTaskName | Scenario8_VisitsBackgroundTask | [private]
FillEventListBoxWithExistingEvents() | Scenario8_VisitsBackgroundTask | [inline, private]
OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e) | Scenario8_VisitsBackgroundTask | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario8_VisitsBackgroundTask | [inline, protected]
RegisterBackgroundTask(object sender, RoutedEventArgs e) | Scenario8_VisitsBackgroundTask | [inline, private]
Scenario8_VisitsBackgroundTask() | Scenario8_VisitsBackgroundTask | [inline]
UnregisterBackgroundTask(object sender, RoutedEventArgs e) | Scenario8_VisitsBackgroundTask | [inline, private]
UpdateButtonStates() | Scenario8_VisitsBackgroundTask | [inline, private]
Generated on Fri Nov 15 2024 22:24:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCorrelation/cpp/SampleConfiguration.cpp Source File

  • CameraStreamCorrelation
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Correlate multiple streams", "SDKTemplate.Scenario1_CorrelateStreams" }
00021 };
Generated on Fri Nov 15 2024 22:17:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cpp/Scenario3_SeekerDiscover.xaml.h Source File

  • WiFiDirectServices
  • cpp

Scenario3_SeekerDiscover.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_SeekerDiscover.g.h"
00015
00016 namespace SDKTemplate
00017 {
00018     namespace WiFiDirectServices
00019     {
00020         /// <summary>
00021         /// UI that provides a way to discover any Wi-Fi Direct service by name
00022         /// A real application would likely hard-code the service name to a well-known service rather than expose this in the UI
00023         ///
00024         /// Most of the actual logic for Wi-Fi Direct Services is in WiFiDirectServicesManager.h/cpp and WiFiDirectServicesWrappers.h/cpp
00025         /// </summary>
00026         [Windows::Foundation::Metadata::WebHostHidden]
00027         public ref class Scenario3 sealed
00028         {
00029         public:
00030             Scenario3();
00031
00032             void SessionConnected();
00033
00034             void UpdateDiscoveryList(Windows::Foundation::Collections::IVector<DiscoveredDeviceWrapper^>^ devices);
00035
00036         protected:
00037             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00038
00039             virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00040
00041         private:
00042             SDKTemplate::MainPage^ _rootPage;
00043             std::mutex _mutex;
00044
00045             Windows::Devices::WiFiDirect::Services::WiFiDirectServiceProvisioningInfo^ _provisioningInfo;
00046
00047             void Discover_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048
00049             // An application has two ways to connect over Wi-Fi Direct services
00050             // 1) First call GetProvisioningInfoAsync to begin connecting,
00051             //        a) if a PIN is required (group formation is required and selected config method is PinEntry or PinDisplay) then call ConnectAsync with the PIN
00052             //        b) else if no PIN is required then call ConnectAsync with no PIN
00053             // 2) Call ConnectAsync to connect without a PIN and prefer the Wi-Fi Direct Default config method, if possible
00054
00055             void GetProvisioningInfo_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00056
00057             void DoConnect_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00058         };
00059     }
00060 }
Generated on Fri Nov 15 2024 22:22:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/BufferPacket.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

BufferPacket.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009 #include <list>
00010 #include <StspNetwork.h>
00011
00012 namespace Microsoft { namespace Samples { namespace SimpleCommunication { namespace Network {
00013
00014     class CBufferPacket : public IBufferPacket
00015     {
00016     public:
00017         typedef std::list<ComPtr<IMediaBufferWrapper> > Container;
00018         typedef std::list<ComPtr<IMediaBufferWrapper> >::iterator Iterator;
00019
00020         static HRESULT FromMFSample(IMFSample *pSample, IBufferPacket **ppBufferPackage);
00021         static HRESULT CreateInstance(IBufferPacket **ppBufferPackage);
00022
00023         // IUnknown
00024         IFACEMETHOD (QueryInterface) (REFIID riid, void **ppv);
00025         IFACEMETHOD_(ULONG, AddRef) ();
00026         IFACEMETHOD_(ULONG, Release) ();
00027
00028         // IBufferPacket
00029         IFACEMETHOD (AddBuffer) (IMediaBufferWrapper *pBuffer);
00030         IFACEMETHOD (InsertBuffer) (unsigned int nIndex, IMediaBufferWrapper *pBuffer);
00031         IFACEMETHOD (RemoveBuffer) (unsigned int nIndex, IMediaBufferWrapper **ppBuffer);
00032         IFACEMETHOD (Clear) ();
00033         IFACEMETHOD_(size_t, GetBufferCount) () const;
00034
00035         IFACEMETHOD (GetTotalLength) (_Out_ DWORD *pcbTotalLength);
00036         IFACEMETHOD (CopyTo) (DWORD nOffset, DWORD cbSize, _In_reads_bytes_(cbSize) void *pDest, _Out_ DWORD *pcbCopied);
00037         IFACEMETHOD (MoveLeft) (DWORD cbSize, _Out_writes_bytes_(cbSize) void *pDest);
00038         IFACEMETHOD (TrimLeft) (DWORD cbSize);
00039         IFACEMETHOD (ToMFSample) (IMFSample **ppSample);
00040
00041         IFACEMETHOD (GetEnumerator) (_Out_ IBufferEnumerator **ppEnumerator);
00042
00043     #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
00044         IFACEMETHOD (FillWSABUF) (WSABUF *pBuffers, size_t cBuffers);
00045         IFACEMETHOD (SaveToFile) (LPCWSTR pszFileName);
00046     #endif
00047     protected:
00048         CBufferPacket(void);
00049         ~CBufferPacket(void);
00050
00051     private:
00052         long                        _cRef;                      // reference count
00053         Container                   _buffers;                   // List of packets
00054     };
00055
00056     class CBufferEnumerator: public IBufferEnumerator
00057     {
00058     public:
00059         static HRESULT CreateInstance(CBufferPacket::Container &container, IUnknown *pParent, IBufferEnumerator **ppEnumerator);
00060
00061         // IUnknown
00062         IFACEMETHOD (QueryInterface) (REFIID riid, void **ppv);
00063         IFACEMETHOD_(ULONG, AddRef) ();
00064         IFACEMETHOD_(ULONG, Release) ();
00065
00066         // IBufferEnumerator
00067         IFACEMETHOD_ (bool, IsValid) ();
00068         IFACEMETHOD (GetCurrent) (_Out_ IMediaBufferWrapper **ppBuffer);
00069         IFACEMETHOD (MoveNext) ();
00070         IFACEMETHOD (Reset) ();
00071
00072     protected:
00073         CBufferEnumerator(CBufferPacket::Container &container, IUnknown *pParent);
00074         ~CBufferEnumerator();
00075
00076     private:
00077         long                        _cRef;                      // reference count
00078         CBufferPacket::Container    &_buffers;                  // List of packets
00079         CBufferPacket::Iterator     _currentIt;                 // Current position
00080         ComPtr<IUnknown>            _spParent;                  // Parent object, we hold reference to it to make sure the container is valid all the time.
00081     };
00082
00083 }}}}
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSensors/cpp/SampleConfiguration.h Source File

  • CustomSensors
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Custom sensors";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/SampleConfiguration.cs Source File

  • XamlBind
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using xBindSampleCS;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public string SAMPLE_NAME = "x:Bind Sample in C#";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario(){
00026                 Title = "Basic Bindings",
00027                 Description = "Demonstrates simple OneTime and OneWay bindings against a model. Buttons are provided to adjust the model which will cause the OneWay bindings against properties with notifications to update.",
00028                 ClassType=typeof(BasicTests)
00029             },
00030            new Scenario() {
00031                 Title = "Other Bindings",
00032                 Description = "Demonstrates a more complex set of bindings including TwoWay, Converters, TargetNullValue, FallbackValue and bindings used in a variety of places in markup.",
00033                 ClassType=typeof(OtherBindings)
00034             },
00035             new Scenario() {
00036                 Title = "List & Templates",
00037                 Description = "Demonstrates using bindings in data templates, consumed by a list and as the content template of a button. The templates are defined inline to the list, in the page's resources and in a seperate resource dictionary.",
00038                 ClassType=typeof(ListsAndTemplates)
00039             },
00040             new Scenario() {
00041                 Title = "List phasing using x:Phase",
00042                 Description = "Demonstrates using x:Phase to achieve incremenatal rendering of the list items.",
00043                 ClassType=typeof(PhasingTests)
00044             },
00045             new Scenario() {
00046                 Title = "Event Binding",
00047                 Description = "Demonstrates using x:Bind with Events",
00048                 ClassType=typeof(EventTests)
00049             },
00050             new Scenario() {
00051                 Title = "Function Binding",
00052                 Description = "Demonstrates using x:Bind to bind to functions which is an easier way to do value conversions than using IValueConverter",
00053                 ClassType=typeof(Functions)
00054     }
00055 };
00056     }
00057     public class Scenario
00058     {
00059         public string Title { get; set; }
00060         public string Description { get; set; }
00061         public Type ClassType { get; set; }
00062     }
00063 }
00064
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BuildNewRss Member List

This is the complete list of members for BuildNewRss, including all inherited members.
BuildNewRss() | BuildNewRss | [inline]
OnNavigatedTo(NavigationEventArgs e) | BuildNewRss | [inline, protected]
rootPage | BuildNewRss | [private]
Scenario1BtnDefault_Click(object sender, RoutedEventArgs e) | BuildNewRss | [inline, private]
Scenario1Init() | BuildNewRss | [inline, private]
Generated on Fri Nov 15 2024 22:24:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LightSensor/cpp/Scenario2_Polling.xaml.cpp Source File

  • LightSensor
  • cpp

Scenario2_Polling.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_Polling.xaml.cpp
00014 // Implementation of the Scenario2_Polling class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario2_Polling.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::Devices::Sensors;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::UI::Core;
00028 using namespace Platform;
00029
00030 Scenario2_Polling::Scenario2_Polling() : rootPage(MainPage::Current), desiredReportInterval(0)
00031 {
00032     InitializeComponent();
00033
00034     sensor = LightSensor::GetDefault();
00035     if (sensor != nullptr)
00036     {
00037         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00038         // This value will be used later to activate the sensor.
00039         uint32 minReportInterval = sensor->MinimumReportInterval;
00040         desiredReportInterval = minReportInterval > 100 ? minReportInterval : 100;
00041
00042         // Set up a DispatchTimer
00043         TimeSpan span;
00044         span.Duration = static_cast<int32>(desiredReportInterval) * 10000;   // convert to 100ns ticks
00045         dispatcherTimer = ref new DispatcherTimer();
00046         dispatcherTimer->Interval = span;
00047         dispatcherTimer->Tick += ref new Windows::Foundation::EventHandler<Object^>(this, &Scenario2_Polling::DisplayCurrentReading);
00048     }
00049     else
00050     {
00051         rootPage->NotifyUser("No light sensor found", NotifyType::ErrorMessage);
00052     }
00053 }
00054
00055 /// <summary>
00056 /// Invoked when this page is about to be displayed in a Frame.
00057 /// </summary>
00058 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00059 /// property is typically used to configure the page.</param>
00060 void Scenario2_Polling::OnNavigatedTo(NavigationEventArgs^ e)
00061 {
00062     ScenarioEnableButton->IsEnabled = true;
00063     ScenarioDisableButton->IsEnabled = false;
00064 }
00065
00066 /// <summary>
00067 /// Invoked when this page is no longer displayed.
00068 /// </summary>
00069 /// <param name="e"></param>
00070 void Scenario2_Polling::OnNavigatedFrom(NavigationEventArgs^ e)
00071 {
00072     // If the navigation is external to the app do not clean up.
00073     // This can occur on Phone when suspending the app.
00074     if (e->NavigationMode == NavigationMode::Forward && e->Uri == nullptr)
00075     {
00076         return;
00077     }
00078
00079     if (ScenarioDisableButton->IsEnabled)
00080     {
00081         Window::Current->VisibilityChanged::remove(visibilityToken);
00082         dispatcherTimer->Stop();
00083
00084         // Restore the default report interval to release resources while the sensor is not in use
00085         sensor->ReportInterval = 0;
00086     }
00087 }
00088
00089 /// <summary>
00090 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00091 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00092 /// </summary>
00093 /// <param name="sender"></param>
00094 /// <param name="e">
00095 /// Event data that can be examined for the current visibility state.
00096 /// </param>
00097 void Scenario2_Polling::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00098 {
00099     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00100     if (ScenarioDisableButton->IsEnabled)
00101     {
00102         if (e->Visible)
00103         {
00104             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00105             dispatcherTimer->Start();
00106         }
00107         else
00108         {
00109             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00110             dispatcherTimer->Stop();
00111         }
00112     }
00113 }
00114
00115 void Scenario2_Polling::DisplayCurrentReading(Object^ sender, Object^ e)
00116 {
00117     LightSensorReading^ reading = sensor->GetCurrentReading();
00118     if (reading != nullptr)
00119     {
00120         ScenarioOutput_LUX->Text = reading->IlluminanceInLux.ToString();
00121     }
00122 }
00123
00124 void Scenario2_Polling::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00125 {
00126     if (sensor != nullptr)
00127     {
00128         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario2_Polling::VisibilityChanged));
00129
00130         // Set the report interval to enable the sensor for polling
00131         sensor->ReportInterval = desiredReportInterval;
00132
00133         dispatcherTimer->Start();
00134
00135         ScenarioEnableButton->IsEnabled = false;
00136         ScenarioDisableButton->IsEnabled = true;
00137     }
00138     else
00139     {
00140         rootPage->NotifyUser("No light sensor found", NotifyType::ErrorMessage);
00141     }
00142 }
00143
00144 void Scenario2_Polling::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00145 {
00146     Window::Current->VisibilityChanged::remove(visibilityToken);
00147
00148     dispatcherTimer->Stop();
00149
00150     // Restore the default report interval to release resources while the sensor is not in use
00151     sensor->ReportInterval = 0;
00152
00153     ScenarioEnableButton->IsEnabled = true;
00154     ScenarioDisableButton->IsEnabled = false;
00155 }
Generated on Fri Nov 15 2024 22:17:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cpp/LoggingChannelScenario.h Source File

  • Logging
  • cpp

LoggingChannelScenario.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008
00009 namespace SDKTemplate
00010 {
00011     ref class LoggingChannelScenario sealed
00012     {
00013     public:
00014
00015         void LogWithWin81Constructor();
00016         void LogWithWin10Constructor();
00017
00018     private:
00019
00020         void DemonstrateLogging(Windows::Foundation::Diagnostics::LoggingChannel^ channel);
00021         Platform::String^ CollectExpensiveData();
00022         void DoSomething(Windows::Foundation::Diagnostics::ILoggingTarget^ logger);
00023         void OnLoggingEnabled(Windows::Foundation::Diagnostics::ILoggingChannel^ sender, Platform::Object^ args);
00024     };
00025 }
Generated on Fri Nov 15 2024 22:20:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario_SynthesizeTextBoundaries Member List

This is the complete list of members for Scenario_SynthesizeTextBoundaries, including all inherited members.
FillTextBoxes(SpeechCue cue, TimedMetadataTrack timedMetadataTrack) | Scenario_SynthesizeTextBoundaries | [inline, private]
HighlightTextOnScreen(int?startPositionInInput, int?endPositionInInput) | Scenario_SynthesizeTextBoundaries | [inline, private]
InitializeListboxVoiceChooser() | Scenario_SynthesizeTextBoundaries | [inline, private]
ListboxVoiceChooser_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario_SynthesizeTextBoundaries | [inline, private]
media_MediaEnded(MediaPlayer sender, object e) | Scenario_SynthesizeTextBoundaries | [inline, private]
metadata_SpeechCueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args) | Scenario_SynthesizeTextBoundaries | [inline, private]
RegisterForWordBoundaryEvents(MediaPlaybackItem mediaPlaybackItem) | Scenario_SynthesizeTextBoundaries | [inline, private]
RegisterMetadataHandlerForSentences(MediaPlaybackItem mediaPlaybackItem, int index) | Scenario_SynthesizeTextBoundaries | [inline, private]
RegisterMetadataHandlerForWords(MediaPlaybackItem mediaPlaybackItem, int index) | Scenario_SynthesizeTextBoundaries | [inline, private]
Scenario_SynthesizeTextBoundaries() | Scenario_SynthesizeTextBoundaries | [inline]
Speak_Click(object sender, RoutedEventArgs e) | Scenario_SynthesizeTextBoundaries | [inline, private]
speechContext | Scenario_SynthesizeTextBoundaries | [private]
speechResourceMap | Scenario_SynthesizeTextBoundaries | [private]
synthesizer | Scenario_SynthesizeTextBoundaries | [private]
Generated on Fri Nov 15 2024 22:24:01 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Prefs Member List

This is the complete list of members for Scenario1_Prefs, including all inherited members.
Scenario1_Prefs() | Scenario1_Prefs | [inline]
ShowResults_Click(object sender, RoutedEventArgs e) | Scenario1_Prefs | [inline, private]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cpp/Scenario1_SampleBackgroundTask.xaml.h Source File

  • BackgroundActivation
  • cpp

Scenario1_SampleBackgroundTask.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario1_SampleBackgroundTask.xaml.h
00013 // Declaration of the SampleBackgroundTask class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario1_SampleBackgroundTask.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     [Windows::Foundation::Metadata::WebHostHidden]
00028     public ref class SampleBackgroundTask sealed
00029     {
00030     public:
00031         SampleBackgroundTask();
00032
00033     protected:
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035     private:
00036         SDKTemplate::MainPage^ rootPage;
00037
00038         void AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^ task);
00039         void RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041         void OnProgress(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs^ args);
00042         void OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ args);
00043         void UpdateUI();
00044     };
00045 }
Generated on Fri Nov 15 2024 22:18:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Compass/cpp/CalibrationBar.xaml.cpp Source File

  • Compass
  • cpp

CalibrationBar.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // CalibrationBar.xaml.cpp
00014 // Implementation of the CalibrationBar class
00015 //
00016
00017 #include "pch.h"
00018 #include "CalibrationBar.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Media::Imaging;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::Devices::Sensors;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::UI::Core;
00029 using namespace Platform;
00030
00031 static const double LAYOUT_WIDTH_768 = 768.0;
00032
00033 CalibrationBar::CalibrationBar() : _barDismissed(false)
00034 {
00035     InitializeComponent();
00036
00037     _lastCalibrationTime.QuadPart = 0;
00038
00039     TimeSpan span;
00040     span.Duration = CALIBRATION_POPUP_AUTO_DISMISS_TIME_TICKS;
00041     _calibrationTimer = ref new DispatcherTimer();
00042     _calibrationTimer->Tick += ref new Windows::Foundation::EventHandler<Object^>(this, &CalibrationBar::OnAutoDismissTimerExpired);
00043     _calibrationTimer->Interval = span;
00044 }
00045
00046 /// <summary>
00047 /// Called when the application would like to show the calibration bar to the user
00048 /// to improve sensor accuracy.
00049 /// </summary>
00050 /// <param name="accuracy">Current accuracy of the sensor.</param>
00051 void CalibrationBar::RequestCalibration(MagnetometerAccuracy accuracy)
00052 {
00053     // Only show the calibration bar if it is hidden and sufficient
00054     // time has passed since it was last hidden.
00055     if (!CalibrationPopup->IsOpen && CanShowCalibrationBar(accuracy))
00056     {
00057         InvalidateLayout();
00058         _windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &CalibrationBar::OnWindowSizeChanged);
00059         HideGuidance(); // Calibration image hidden by default
00060         CalibrationPopup->IsOpen = true;
00061         _calibrationTimer->Start();
00062     }
00063 }
00064
00065 /// <summary>
00066 /// Called when sensor accuracy is sufficient and the application would like to
00067 /// hide the calibration bar.
00068 /// </summary>
00069 void CalibrationBar::Hide()
00070 {
00071     if (CalibrationPopup->IsOpen)
00072     {
00073         // Hide the calibration bar and save the current time.
00074         FILETIME filetime;
00075         GetSystemTimeAsFileTime(&filetime);
00076         _lastCalibrationTime.HighPart = filetime.dwHighDateTime;
00077         _lastCalibrationTime.LowPart = filetime.dwLowDateTime;
00078         HideGuidance();
00079         CalibrationPopup->IsOpen = false;
00080         Window::Current->SizeChanged -= _windowSizeEventToken;
00081         _calibrationTimer->Stop();
00082     }
00083 }
00084
00085 /// <summary>
00086 /// Invoked when the window size is updated.
00087 /// </summary>
00088 /// <param name="sender">Instance that triggered the event.</param>
00089 /// <param name="e">Event data describing the conditions that led to the event.</param>
00090 void CalibrationBar::OnWindowSizeChanged(Object^ sender, WindowSizeChangedEventArgs^ e)
00091 {
00092     InvalidateLayout();
00093 }
00094
00095 /// <summary>
00096 /// Updates the calibration bar layout based on the current window width.
00097 /// </summary>
00098 void CalibrationBar::InvalidateLayout()
00099 {
00100     CalibrationGrid->Width = Window::Current->Bounds.Width;
00101
00102     if (CalibrationGrid->Width < LAYOUT_WIDTH_768)
00103     {
00104         Grid::SetRow(DismissPopup, 1);
00105         Grid::SetColumn(DismissPopup, 1);
00106
00107         CalibrationGridTop->Margin = Thickness(0, 24, 20, 15);
00108         DismissPopup->Margin = Thickness(66, 15, 0, 0);
00109     }
00110     else
00111     {
00112         Grid::SetRow(DismissPopup, 0);
00113         Grid::SetColumn(DismissPopup, 2);
00114
00115         CalibrationGridTop->Margin = Thickness(0, 19, 66, 19);
00116         DismissPopup->Margin = Thickness(66, 0, 0, 0);
00117     }
00118 }
00119
00120 /// <summary>
00121 /// Called to determine if sufficient time has passed since the calibration bar
00122 /// was hidden to show the calibration bar again. This suppression time is
00123 /// dependent on the current sensor accuracy.
00124 /// </summary>
00125 /// <param name="accuracy">Current accuracy of the sensor.</param>
00126 bool CalibrationBar::CanShowCalibrationBar(MagnetometerAccuracy accuracy)
00127 {
00128     bool showBar = false;
00129     if (!_barDismissed)
00130     {
00131         FILETIME filetime;
00132         ULARGE_INTEGER now;
00133         GetSystemTimeAsFileTime(&filetime);
00134         now.HighPart = filetime.dwHighDateTime;
00135         now.LowPart = filetime.dwLowDateTime;
00136
00137         if ((accuracy == MagnetometerAccuracy::Approximate) &&
00138             (_lastCalibrationTime.QuadPart + SUPPRESS_DURATION_APPROXIMATE_TICKS <= now.QuadPart))
00139         {
00140             showBar = true;
00141         }
00142         else if ((accuracy == MagnetometerAccuracy::Unreliable) &&
00143             (_lastCalibrationTime.QuadPart + SUPPRESS_DURATION_UNRELIABLE_TICKS <= now.QuadPart))
00144         {
00145             showBar = true;
00146         }
00147     }
00148     return showBar;
00149 }
00150
00151 /// <summary>
00152 /// This is the click handler for the show guidance button.
00153 /// </summary>
00154 /// <param name="sender"></param>
00155 /// <param name="e"></param>
00156 void CalibrationBar::ShowGuidanceButton_Click(Object^ sender, RoutedEventArgs^ e)
00157 {
00158     if (Guidance->Visibility == Windows::UI::Xaml::Visibility::Collapsed)
00159     {
00160         ShowGuidance();
00161     }
00162 }
00163
00164 /// <summary>
00165 /// This is the click handler for the hide guidance button.
00166 /// </summary>
00167 /// <param name="sender"></param>
00168 /// <param name="e"></param>
00169 void CalibrationBar::HideGuidanceButton_Click(Object^ sender, RoutedEventArgs^ e)
00170 {
00171     if (Guidance->Visibility == Windows::UI::Xaml::Visibility::Visible)
00172     {
00173         HideGuidance();
00174     }
00175 }
00176
00177 /// <summary>
00178 /// This is the click handler for the dismiss popup button. It hides the
00179 /// calibration bar and prevents it from being shown again for the lifetime
00180 /// of the app.
00181 /// </summary>
00182 /// <param name="sender"></param>
00183 /// <param name="e"></param>
00184 void CalibrationBar::DismissPopup_Click(Object^ sender, RoutedEventArgs^ e)
00185 {
00186     // Don't show the calibration bar again.
00187     _barDismissed = true;
00188     Hide();
00189 }
00190
00191 /// <summary>
00192 /// Expands the calibration bar to show the calibration image to the user.
00193 /// </summary>
00194 /// <param name="sender"></param>
00195 /// <param name="e"></param>
00196 void CalibrationBar::ShowGuidance()
00197 {
00198     ShowGuidanceButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00199     HideGuidanceButton->Visibility = Windows::UI::Xaml::Visibility::Visible;
00200     Guidance->Visibility = Windows::UI::Xaml::Visibility::Visible;
00201 }
00202
00203 /// <summary>
00204 /// Collapses the calibration bar to hide the calibration image from the user.
00205 /// </summary>
00206 /// <param name="sender"></param>
00207 /// <param name="e"></param>
00208 void CalibrationBar::HideGuidance()
00209 {
00210     HideGuidanceButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00211     ShowGuidanceButton->Visibility = Windows::UI::Xaml::Visibility::Visible;
00212     Guidance->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00213 }
00214
00215 /// <summary>
00216 /// This is the handler for the auto dismiss timer. After the calibraiton bar
00217 /// has been shown for the maximum time, it is automatically hidden.
00218 /// </summary>
00219 /// <param name="sender"></param>
00220 /// <param name="e"></param>
00221 void CalibrationBar::OnAutoDismissTimerExpired(Object^ sender, Object^ e)
00222 {
00223     Hide();
00224 }
Generated on Fri Nov 15 2024 22:18:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cpp/Scenario1_AppBarButtons.xaml.h Source File

  • XamlCommanding
  • cpp

Scenario1_AppBarButtons.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_AppBarButtons.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario1_AppBarButtons sealed
00024     {
00025     public:
00026         Scenario1_AppBarButtons();
00027     };
00028 }
Generated on Fri Nov 15 2024 22:22:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaEditing/cs/Scenario4_AddOverlays.xaml.cs Source File

  • MediaEditing
  • cs

Scenario4_AddOverlays.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using Windows.Storage;
00017 using Windows.Foundation;
00018 using Windows.Media.Editing;
00019 using Windows.Media.Core;
00020 using SDKTemplate;
00021
00022 namespace MediaEditingSample
00023 {
00024     public sealed partial class Scenario4_AddOverlays : Page
00025     {
00026         private MainPage rootPage;
00027         private MediaComposition composition;
00028         private StorageFile baseVideoFile;
00029         private StorageFile overlayVideoFile;
00030         private MediaStreamSource mediaStreamSource;
00031
00032         public Scenario4_AddOverlays()
00033         {
00034             this.InitializeComponent();
00035         }
00036
00037         protected override void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039             rootPage = MainPage.Current;
00040         }
00041
00042         protected override void OnNavigatedFrom(NavigationEventArgs e)
00043         {
00044             mediaElement.Source = null;
00045             mediaStreamSource = null;
00046             base.OnNavigatedFrom(e);
00047         }
00048
00049         private async void ChooseBaseVideo_Click(object sender, RoutedEventArgs e)
00050         {
00051             var picker = new Windows.Storage.Pickers.FileOpenPicker();
00052             picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
00053             picker.FileTypeFilter.Add(".mp4");
00054             baseVideoFile = await picker.PickSingleFileAsync();
00055             if (baseVideoFile == null)
00056             {
00057                 rootPage.NotifyUser("File picking cancelled", NotifyType.ErrorMessage);
00058                 return;
00059             }
00060
00061             mediaElement.SetSource(await baseVideoFile.OpenReadAsync(), baseVideoFile.ContentType);
00062             chooseOverlayVideo.IsEnabled = true;
00063         }
00064
00065         private async void ChooseOverlayVideo_Click(object sender, RoutedEventArgs e)
00066         {
00067             var picker = new Windows.Storage.Pickers.FileOpenPicker();
00068             picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
00069             picker.FileTypeFilter.Add(".mp4");
00070             overlayVideoFile = await picker.PickSingleFileAsync();
00071             if (overlayVideoFile == null)
00072             {
00073                 rootPage.NotifyUser("File picking cancelled", NotifyType.ErrorMessage);
00074                 return;
00075             }
00076
00077             CreateOverlays();
00078             rootPage.NotifyUser("Overlay video chosen", NotifyType.StatusMessage);
00079         }
00080
00081         private async void CreateOverlays()
00082         {
00083             var baseVideoClip = await MediaClip.CreateFromFileAsync(baseVideoFile);
00084             composition = new MediaComposition();
00085             composition.Clips.Add(baseVideoClip);
00086
00087             var overlayVideoClip = await MediaClip.CreateFromFileAsync(overlayVideoFile);
00088
00089             // Overlay video in upper left corner, retain its native aspect ratio
00090             Rect videoOverlayPosition;
00091             var encodingProperties = overlayVideoClip.GetVideoEncodingProperties();
00092             videoOverlayPosition.Height = mediaElement.ActualHeight / 3;
00093             videoOverlayPosition.Width = (double)encodingProperties.Width / (double)encodingProperties.Height * videoOverlayPosition.Height;
00094             videoOverlayPosition.X = 0;
00095             videoOverlayPosition.Y = 0;
00096
00097             var videoOverlay = new MediaOverlay(overlayVideoClip);
00098             videoOverlay.Position = videoOverlayPosition;
00099             videoOverlay.Opacity = 0.75;
00100
00101             var overlayLayer = new MediaOverlayLayer();
00102             overlayLayer.Overlays.Add(videoOverlay);
00103             composition.OverlayLayers.Add(overlayLayer);
00104
00105             // Render to MediaElement
00106             mediaElement.Position = TimeSpan.Zero;
00107             mediaStreamSource = composition.GeneratePreviewMediaStreamSource((int)mediaElement.ActualWidth, (int)mediaElement.ActualHeight);
00108             mediaElement.SetMediaStreamSource(mediaStreamSource);
00109             rootPage.NotifyUser("Overlays created", NotifyType.StatusMessage);
00110         }
00111     }
00112 }
Generated on Fri Nov 15 2024 22:20:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlLite/cpp/SampleConfiguration.h Source File

  • XmlLite
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "XmlLite Sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraManualControls/cs/MainPage.ExposureValue.xaml.cs Source File

  • CameraManualControls
  • cs

MainPage.ExposureValue.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017 using Windows.Media.Devices;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml;
00020
00021 namespace CameraManualControls
00022 {
00023     public sealed partial class MainPage : Page
00024     {
00025
00026         private void UpdateEvControlCapabilities()
00027         {
00028             var exposureCompensationControl = _mediaCapture.VideoDeviceController.ExposureCompensationControl;
00029
00030             if (exposureCompensationControl.Supported)
00031             {
00032                 EvButton.Tag = Visibility.Visible;
00033
00034                 var value = exposureCompensationControl.Value;
00035
00036                 // The slider will track the number of steps
00037                 var stepSize = exposureCompensationControl.Step;
00038                 EvSlider.Minimum = exposureCompensationControl.Min / stepSize;
00039                 EvSlider.Maximum = exposureCompensationControl.Max / stepSize;
00040                 EvSlider.StepFrequency = 1;
00041                 EvSlider.Value = value / stepSize;
00042
00043                 EvTextBlock.Text = EvStepCountToString((int)Math.Round(value), stepSize);
00044             }
00045             else
00046             {
00047                 EvButton.Visibility = Visibility.Collapsed;
00048                 EvButton.Tag = Visibility.Collapsed;
00049             }
00050         }
00051
00052         private async void EvSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e)
00053         {
00054             if (_settingUpUi) return;
00055
00056             float stepSize = _mediaCapture.VideoDeviceController.ExposureCompensationControl.Step;
00057
00058             var value = (sender as Slider).Value;
00059             await _mediaCapture.VideoDeviceController.ExposureCompensationControl.SetValueAsync((float)value * stepSize);
00060
00061             EvTextBlock.Text = EvStepCountToString((int)Math.Round(value), stepSize);
00062         }
00063
00064         /// <summary>
00065         /// Converts the number of steps into a (mixed) fraction based on the step size, when the value used is steps * stepSize
00066         /// </summary>
00067         /// <param name="steps">Number of steps</param>
00068         /// <param name="stepSize">The size of one step</param>
00069         /// <returns></returns>
00070         private static string EvStepCountToString(int steps, float stepSize)
00071         {
00072             if (stepSize <= 0) throw new ArgumentOutOfRangeException(nameof(stepSize), "Parameter must be a positive value");
00073
00074             int stepsPerUnit = (int)Math.Round(1 / stepSize);
00075             if (steps == 0) return "0";
00076
00077             string sign = steps < 0 ? "-" : "+";
00078             int whole = (int)Math.Abs(steps * stepSize);
00079             int remainder = (stepsPerUnit >= 1) ? Math.Abs(steps) % stepsPerUnit : 0;
00080
00081             if (remainder == 0) return sign + whole.ToString();
00082
00083             string fraction = remainder.ToString() + "/" + stepsPerUnit.ToString();
00084
00085             if (whole == 0) return sign + fraction;
00086             return sign + whole.ToString() + " " + fraction;
00087         }
00088     }
00089 }
Generated on Fri Nov 15 2024 22:18:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JapanesePhoneticAnalysis/cppwinrt/Project.idl Source File

  • JapanesePhoneticAnalysis
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_Analyze : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_Analyze();
00018     }
00019 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppWindow/cs/Scenario3_Size.xaml.cs Source File

  • AppWindow
  • cs

Scenario3_Size.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Foundation;
00014 using Windows.UI.WindowManagement;
00015 using Windows.UI.WindowManagement.Preview;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Hosting;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario3_Size : Page
00024     {
00025         private AppWindow appWindow;
00026         private Frame appWindowFrame = new Frame();
00027
00028         public Scenario3_Size()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         protected override async void OnNavigatedFrom(NavigationEventArgs e)
00034         {
00035             if (appWindow != null)
00036             {
00037                 await appWindow.CloseAsync();
00038             }
00039         }
00040
00041         // Lower bounds on window size to keep things from being unresonably tiny.
00042         const double MinWindowWidth = 192;
00043         const double MinWindowHeight = 48;
00044
00045         private async void ShowWindowBtn_Click(object sender, RoutedEventArgs e)
00046         {
00047             // Clear any previous message.
00048             MainPage.Current.NotifyUser(string.Empty, NotifyType.StatusMessage);
00049
00050             Double.TryParse(windowWidthTxt.Text, out var windowWidth);
00051             Double.TryParse(windowHeightTxt.Text, out var windowHeight);
00052             if (windowWidth < MinWindowWidth || windowHeight < MinWindowHeight)
00053             {
00054                 MainPage.Current.NotifyUser($"Please specify a width of at least {MinWindowWidth} and a height of at least {MinWindowHeight}.", NotifyType.ErrorMessage);
00055                 return;
00056             }
00057
00058             showWindowBtn.IsEnabled = false;
00059
00060             // Only ever create and show one window. If the AppWindow exists use it
00061             if (appWindow == null)
00062             {
00063                 // Create a new window
00064                 appWindow = await AppWindow.TryCreateAsync();
00065                 // Make sure we release the reference to this window, and release XAML resources, when it's closed
00066                 appWindow.Closed += delegate { appWindow = null; appWindowFrame.Content = null; };
00067                 // Navigate the frame to the page we want to show in the new window
00068                 appWindowFrame.Navigate(typeof(SecondaryAppWindowPage));
00069             }
00070
00071             // If specified size is smaller than the default min size for a window we need to set a new preferred min size first.
00072             // Let's set it to the smallest allowed and leave it at that.
00073             if (windowWidth < 500 || windowHeight < 320)
00074             {
00075                 WindowManagementPreview.SetPreferredMinSize(appWindow, new Size(MinWindowWidth, MinWindowHeight));
00076             }
00077             // Request the size of our window
00078             appWindow.RequestSize(new Size(windowWidth, windowHeight));
00079             // Attach the XAML content to our window
00080             ElementCompositionPreview.SetAppWindowContent(appWindow, appWindowFrame);
00081
00082             // If the window is not visible, show it and/or bring it to foreground
00083             if (!appWindow.IsVisible)
00084             {
00085                 await appWindow.TryShowAsync();
00086             }
00087
00088             showWindowBtn.IsEnabled = true;
00089         }
00090     }
00091 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/StspMediaSinkProxy.cpp Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

StspMediaSinkProxy.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "StspMediaSinkProxy.h"
00010 #include "StspDefs.h"
00011 #include "StspMediaSink.h"
00012
00013 using namespace Microsoft::Samples::SimpleCommunication;
00014 using namespace Microsoft::Samples::SimpleCommunication::Network;
00015
00016 IncomingConnectionEventArgs::IncomingConnectionEventArgs(IStspSinkInternal *pSink, DWORD connectionId, String ^remoteUrl)
00017     : _spSink(pSink)
00018     , _connectionId(connectionId)
00019     , _remoteUrl(remoteUrl)
00020 {
00021 }
00022
00023 // User accepted connection
00024 void IncomingConnectionEventArgs::Accept()
00025 {
00026     _spSink->TriggerAcceptConnection(_connectionId);
00027 }
00028
00029 // User refused connection
00030 void IncomingConnectionEventArgs::Refuse()
00031 {
00032     _spSink->TriggerRefuseConnection(_connectionId);
00033 }
00034
00035 StspMediaSinkProxy::StspMediaSinkProxy()
00036 {
00037 }
00038
00039 StspMediaSinkProxy::~StspMediaSinkProxy()
00040 {
00041     AutoLock lock(_critSec);
00042
00043     if (_spMediaSink != nullptr)
00044     {
00045         _spMediaSink->Shutdown();
00046         _spMediaSink = nullptr;
00047     }
00048 }
00049
00050 Windows::Media::IMediaExtension ^StspMediaSinkProxy::GetMFExtensions()
00051 {
00052     AutoLock lock(_critSec);
00053
00054     if (_spMediaSink == nullptr)
00055     {
00056         Throw(MF_E_NOT_INITIALIZED);
00057     }
00058
00059     ComPtr<IInspectable> spInspectable;
00060     ThrowIfError(_spMediaSink.As(&spInspectable));
00061
00062     return safe_cast<IMediaExtension^>(reinterpret_cast<Object^>(spInspectable.Get()));
00063 }
00064
00065
00066 Windows::Foundation::IAsyncOperation<IMediaExtension^>^ StspMediaSinkProxy::InitializeAsync(
00067     Windows::Media::MediaProperties::IMediaEncodingProperties ^audioEncodingProperties,
00068     Windows::Media::MediaProperties::IMediaEncodingProperties ^videoEncodingProperties
00069     )
00070 {
00071     return concurrency::create_async([this, videoEncodingProperties, audioEncodingProperties]()
00072     {
00073         AutoLock lock(_critSec);
00074         CheckShutdown();
00075
00076         if (_spMediaSink != nullptr)
00077         {
00078             Throw(MF_E_ALREADY_INITIALIZED);
00079         }
00080
00081         // Prepare the MF extension
00082         ThrowIfError(MakeAndInitialize<CMediaSink>(&_spMediaSink, ref new StspSinkCallback(this), audioEncodingProperties, videoEncodingProperties));
00083
00084         ComPtr<IInspectable> spInspectable;
00085         ThrowIfError(_spMediaSink.As(&spInspectable));
00086
00087         return safe_cast<IMediaExtension^>(reinterpret_cast<Object^>(spInspectable.Get()));
00088     });
00089 }
00090
00091 void StspMediaSinkProxy::FireIncomingConnection(IncomingConnectionEventArgs ^args)
00092 {
00093     IncomingConnectionEvent(this, args);
00094 }
00095
00096 void StspMediaSinkProxy::OnShutdown()
00097 {
00098     AutoLock lock(_critSec);
00099     if (_fShutdown)
00100     {
00101         return;
00102     }
00103     _fShutdown = true;
00104     _spMediaSink = nullptr;
00105 }
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cpp/Scenario4_PartialReadWrite.xaml.cpp Source File

  • WebSocket
  • cpp

Scenario4_PartialReadWrite.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario4.xaml.cpp
00014 // Implementation of the Scenario4 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario4_PartialReadWrite.xaml.h"
00019
00020 using namespace concurrency;
00021 using namespace Platform;
00022 using namespace SDKTemplate;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::Networking::Sockets;
00026 using namespace Windows::Security::Cryptography::Certificates;
00027 using namespace Windows::Storage::Streams;
00028 using namespace Windows::UI::Core;
00029 using namespace Windows::UI::Xaml;
00030 using namespace Windows::UI::Xaml::Controls;
00031 using namespace Windows::UI::Xaml::Navigation;
00032 using namespace Windows::Web;
00033
00034 Scenario4::Scenario4()
00035 {
00036     InitializeComponent();
00037     UpdateVisualState();
00038 }
00039
00040 void Scenario4::OnNavigatedFrom(NavigationEventArgs^ e)
00041 {
00042     CloseSocket();
00043 }
00044
00045 void Scenario4::UpdateVisualState()
00046 {
00047     if (busy)
00048     {
00049         VisualStateManager::GoToState(this, "Busy", false);
00050     }
00051     else
00052     {
00053         bool connected = (messageWebSocket != nullptr);
00054         VisualStateManager::GoToState(this, connected ? "Connected" : "Disconnected", false);
00055     }
00056 }
00057
00058 void Scenario4::SetBusy(bool value)
00059 {
00060     busy = value;
00061     UpdateVisualState();
00062 }
00063
00064 void Scenario4::OnConnect()
00065 {
00066     SetBusy(true);
00067     ConnectAsync().then([this]()
00068     {
00069         SetBusy(false);
00070     });
00071 }
00072
00073 task<void> Scenario4::ConnectAsync()
00074 {
00075     if (ServerAddressField->Text->IsEmpty())
00076     {
00077         rootPage->NotifyUser("Please specify a URI to connect to", NotifyType::ErrorMessage);
00078         return task_from_result();
00079     }
00080
00081     // Validating the URI is required since it was received from an untrusted source (user input).
00082     // The URI is validated by calling TryGetUri() that will return 'nullptr' for strings that are not
00083     // valid WebSocket URIs.
00084     // Note that when enabling the text box users may provide URIs to machines on the intrAnet or intErnet. In
00085     // these cases the app requires the "Private Networks (Client and Server)" or "Internet (Client)" capability respectively.
00086     Uri^ server = rootPage->TryGetUri(ServerAddressField->Text);
00087     if (!server)
00088     {
00089         return task_from_result();
00090     }
00091
00092     messageWebSocket = ref new MessageWebSocket();
00093     messageWebSocket->Control->MessageType = SocketMessageType::Utf8;
00094
00095     // To support receiving event notifications for partial messages, you must set this receive mode.
00096     // If you do not set this mode, you will only receive notifications for complete messages; which is
00097     // the default behavior. Setting to Partial allows us to process partial data as soon as it arrives,
00098     // as opposed to waiting until the EndOfMessage to process the entire data.
00099     messageWebSocket->Control->ReceiveMode = MessageWebSocketReceiveMode::PartialMessage;
00100
00101     messageWebSocket->MessageReceived +=
00102         ref new TypedEventHandler<
00103         MessageWebSocket^,
00104         MessageWebSocketMessageReceivedEventArgs^>(this, &Scenario4::MessageReceived);
00105     messageWebSocket->Closed += ref new TypedEventHandler<IWebSocket^, WebSocketClosedEventArgs^>(this, &Scenario4::OnClosed);
00106
00107     if (server->SchemeName == "wss")
00108     {
00109         // WARNING: Only test applications should ignore SSL errors.
00110         // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle
00111         // attacks. (Although the connection is secure, the server is not authenticated.)
00112         // Note that not all certificate validation errors can be ignored.
00113         // In this case, we are ignoring these errors since the certificate assigned to the localhost
00114         // URI is self-signed and has subject name = fabrikam.com
00115         messageWebSocket->Control->IgnorableServerCertificateErrors->Append(ChainValidationResult::Untrusted);
00116         messageWebSocket->Control->IgnorableServerCertificateErrors->Append(ChainValidationResult::InvalidName);
00117     }
00118
00119     AppendOutputLine("Connecting to " + server->DisplayUri + "...");
00120
00121     return create_task(messageWebSocket->ConnectAsync(server))
00122         .then([this](task<void> previousTask)
00123     {
00124         try
00125         {
00126             // Reraise any exception that occurred in the task.
00127             previousTask.get();
00128         }
00129         catch (Exception^ ex)
00130         {
00131             // Error happened during connect operation.
00132             delete messageWebSocket;
00133             messageWebSocket = nullptr;
00134
00135             AppendOutputLine(MainPage::BuildWebSocketError(ex));
00136             AppendOutputLine(ex->Message);
00137             return;
00138         }
00139
00140         rootPage->NotifyUser("Connected", NotifyType::StatusMessage);
00141     });
00142 }
00143
00144 void Scenario4::OnSend()
00145 {
00146     SetBusy(true);
00147     SendAsync().then([this]()
00148     {
00149         SetBusy(false);
00150     });
00151 }
00152
00153 task<void> Scenario4::SendAsync()
00154 {
00155     String^ message = InputField->Text;
00156     if (message->IsEmpty())
00157     {
00158         rootPage->NotifyUser("Please specify text to send", NotifyType::ErrorMessage);
00159         return task_from_result();
00160     }
00161
00162     // Buffer any data we want to send.
00163
00164     Windows::Storage::Streams::DataWriter^ messageWriter = ref new DataWriter();
00165     messageWriter->WriteString(message);
00166     IBuffer^ buffer = messageWriter->DetachBuffer();
00167
00168     task<unsigned int> asyncTask;
00169
00170     if (EndOfMessageCheckBox->IsChecked->Value == true)
00171     {
00172         AppendOutputLine("Sending end of message: " + message);
00173         asyncTask = create_task(messageWebSocket->SendFinalFrameAsync(buffer));
00174     }
00175     else
00176     {
00177         AppendOutputLine("Sending partial message: " + message);
00178         asyncTask = create_task(messageWebSocket->SendNonfinalFrameAsync(buffer));
00179     }
00180
00181     return asyncTask.then([this](task<unsigned int> previousTask)
00182     {
00183         try
00184         {
00185             // Reraise any exception that occurred in the task.
00186             previousTask.get();
00187         }
00188         catch (Exception^ ex)
00189         {
00190             AppendOutputLine(MainPage::BuildWebSocketError(ex));
00191             AppendOutputLine(ex->Message);
00192             return;
00193         }
00194     });
00195 }
00196
00197 void Scenario4::MessageReceived(MessageWebSocket^ sender, MessageWebSocketMessageReceivedEventArgs^ args)
00198 {
00199     // Dispatch the event to the UI thread so we can update UI.
00200     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00201     {
00202         String^ partialOrCompleted = "Partial";
00203
00204         if (args->IsMessageComplete)
00205         {
00206             partialOrCompleted = "Complete";
00207         }
00208
00209         AppendOutputLine(partialOrCompleted + " message received; Type: " + args->MessageType.ToString());
00210
00211         DataReader^ reader = args->GetDataReader();
00212         reader->UnicodeEncoding = UnicodeEncoding::Utf8;
00213         try
00214         {
00215             // Note that it may be possible for partial UTF8 messages to be split between a character if it
00216             // extends multiple bytes. We avoid this by using only ASCII characters in this example.
00217             // Should your application use multi-byte characters, you will need to do checks for broken characters.
00218             String^ read = reader->ReadString(reader->UnconsumedBufferLength);
00219             AppendOutputLine(read);
00220         }
00221         catch (Exception^ ex)
00222         {
00223             AppendOutputLine(MainPage::BuildWebSocketError(ex));
00224             AppendOutputLine(ex->Message);
00225         }
00226         delete reader;
00227     }));
00228 }
00229
00230 void Scenario4::OnDisconnect()
00231 {
00232     SetBusy(true);
00233     rootPage->NotifyUser("Closing", NotifyType::StatusMessage);
00234     CloseSocket();
00235     SetBusy(false);
00236     rootPage->NotifyUser("Closed", NotifyType::StatusMessage);
00237 }
00238
00239 // The method may be triggered remotely by the server sending unsolicited close frame or locally by Close()/delete operator.
00240 void Scenario4::OnClosed(IWebSocket^ sender, WebSocketClosedEventArgs^ args)
00241 {
00242     // Dispatch the event to the UI thread so we do not need to synchronize access to messageWebSocket.
00243     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, sender, args] ()
00244     {
00245         AppendOutputLine("Closed; Code: " + args->Code.ToString() + ", Reason: " + args->Reason);
00246
00247         if (messageWebSocket == sender)
00248         {
00249             CloseSocket();
00250             UpdateVisualState();
00251         }
00252     }));
00253 }
00254
00255 void Scenario4::CloseSocket()
00256 {
00257     if (messageWebSocket != nullptr)
00258     {
00259         try
00260         {
00261             messageWebSocket->Close(1000, "Closed due to user request.");
00262         }
00263         catch (Exception^ ex)
00264         {
00265             AppendOutputLine(MainPage::BuildWebSocketError(ex));
00266             AppendOutputLine(ex->Message);
00267         }
00268         messageWebSocket = nullptr;
00269     }
00270 }
00271
00272 void Scenario4::AppendOutputLine(String^ value)
00273 {
00274     OutputField->Text += value + "\r\n";
00275 }
Generated on Fri Nov 15 2024 22:22:01 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

NegatingBoolConverter Member List

This is the complete list of members for NegatingBoolConverter, including all inherited members.
Convert(object value, Type targetType, object parameter, string language) | NegatingBoolConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | NegatingBoolConverter | [inline]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_DecimalFormatting Member List

This is the complete list of members for Scenario2_DecimalFormatting, including all inherited members.
Display_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_DecimalFormatting
Scenario2_DecimalFormatting() | Scenario2_DecimalFormatting
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationData/cs/Scenario3_SettingContainer.xaml.cs Source File

  • ApplicationData
  • cs

Scenario3_SettingContainer.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using System;
00015 using Windows.Storage;
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     public sealed partial class Scenario3_SettingContainer : Page
00023     {
00024         MainPage rootPage = MainPage.Current;
00025         ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
00026
00027         const string containerName = "exampleContainer";
00028         const string settingName = "exampleSetting";
00029
00030         public Scenario3_SettingContainer()
00031         {
00032             InitializeComponent();
00033         }
00034
00035         void CreateContainer_Click(Object sender, RoutedEventArgs e)
00036         {
00037             ApplicationDataContainer container = localSettings.CreateContainer(containerName, ApplicationDataCreateDisposition.Always);
00038
00039             DisplayOutput();
00040         }
00041
00042         void DeleteContainer_Click(Object sender, RoutedEventArgs e)
00043         {
00044             localSettings.DeleteContainer(containerName);
00045
00046             DisplayOutput();
00047         }
00048
00049         void WriteSetting_Click(Object sender, RoutedEventArgs e)
00050         {
00051             localSettings.Containers[containerName].Values[settingName] = "Hello World"; // example value
00052
00053             DisplayOutput();
00054         }
00055
00056         void DeleteSetting_Click(Object sender, RoutedEventArgs e)
00057         {
00058             localSettings.Containers[containerName].Values.Remove(settingName);
00059
00060             DisplayOutput();
00061         }
00062
00063         void DisplayOutput()
00064         {
00065             bool hasContainer = localSettings.Containers.TryGetValue(containerName, out ApplicationDataContainer container);
00066             bool hasSetting = hasContainer ? container.Values.ContainsKey(settingName) : false;
00067
00068             OutputTextBlock.Text = $"Container Exists: {hasContainer}\nSetting Exists: {hasSetting}";
00069
00070             WriteSetting.IsEnabled = hasContainer;
00071             DeleteSetting.IsEnabled = hasContainer;
00072         }
00073
00074         protected override void OnNavigatedTo(NavigationEventArgs e)
00075         {
00076             DisplayOutput();
00077         }
00078     }
00079 }
Generated on Fri Nov 15 2024 22:17:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cs/Scenario1_Create.xaml.cs Source File

  • FileAccess
  • cs

Scenario1_Create.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Storage;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Creating a file.
00022     /// </summary>
00023     public sealed partial class Scenario1 : Page
00024     {
00025         private MainPage rootPage = MainPage.Current;
00026
00027         public Scenario1()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         private async void CreateFileButton_Click(object sender, RoutedEventArgs e)
00033         {
00034             StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
00035             try
00036             {
00037                 rootPage.sampleFile = await storageFolder.CreateFileAsync(MainPage.filename, CreationCollisionOption.ReplaceExisting);
00038                 rootPage.NotifyUser($"The file '{rootPage.sampleFile.Name}' was created.", NotifyType.StatusMessage);
00039             }
00040             catch (Exception ex)
00041             {
00042                 // I/O errors are reported as exceptions.
00043                 rootPage.NotifyUser($"Error creating file '{MainPage.filename}': {ex.Message}", NotifyType.ErrorMessage);
00044             }
00045         }
00046     }
00047 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/Content/Panel.h Source File

  • HolographicMixedRealityCapture
  • cpp
  • Content

Panel.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "ControlBase.h"
00004
00005 namespace HolographicMRCSample
00006 {
00007     // This sample renderer instantiates a basic rendering pipeline.
00008     class Panel : public ControlBase
00009     {
00010     public:
00011         Panel(const float width, const float height, const float depth,
00012               const float red,   const float green,  const float blue, const float alpha);
00013
00014     protected:
00015         virtual void DoCreateDeviceDependentResources();
00016         virtual void DoReleaseDeviceDependentResources();
00017
00018         virtual void DoUpdate(
00019             const DX::StepTimer& timer,
00020             HolographicFrame^ holographicFrame,
00021             SpatialCoordinateSystem^ currentCoordinateSystem,
00022             SpatialInteractionSourceState^ interactionSource,
00023             const DirectX::XMMATRIX &parentTransform);
00024         virtual void DoRender();
00025
00026     private:
00027         // Direct3D resources for cube geometry.
00028         Microsoft::WRL::ComPtr<ID3D11InputLayout>       m_inputLayout;
00029         Microsoft::WRL::ComPtr<ID3D11Buffer>            m_vertexBuffer;
00030         Microsoft::WRL::ComPtr<ID3D11Buffer>            m_indexBuffer;
00031         Microsoft::WRL::ComPtr<ID3D11VertexShader>      m_vertexShader;
00032         Microsoft::WRL::ComPtr<ID3D11GeometryShader>    m_geometryShader;
00033         Microsoft::WRL::ComPtr<ID3D11PixelShader>       m_pixelShader;
00034         Microsoft::WRL::ComPtr<ID3D11Buffer>            m_modelConstantBuffer;
00035
00036         // System resources for cube geometry.
00037         ModelConstantBuffer                             m_modelConstantBufferData;
00038         uint32                                          m_indexCount = 0;
00039
00040         Windows::Foundation::Numerics::float3           m_size;
00041         Windows::Foundation::Numerics::float4           m_color;
00042
00043         // Variables used with the rendering loop.
00044         bool                                            m_loadingComplete = false;
00045
00046         // If the current D3D Device supports VPRT, we can avoid using a geometry
00047         // shader just to set the render target array index.
00048         bool                                            m_usingVprtShaders = false;
00049     };
00050 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialMapping/cpp/Content/RealtimeSurfaceMeshRenderer.h Source File

  • HolographicSpatialMapping
  • cpp
  • Content

RealtimeSurfaceMeshRenderer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015 #include "Common\StepTimer.h"
00016 #include "Content\SurfaceMesh.h"
00017 #include "Content\ShaderStructures.h"
00018
00019 #include <memory>
00020 #include <map>
00021 #include <ppltasks.h>
00022
00023 namespace WindowsHolographicCodeSamples
00024 {
00025     class RealtimeSurfaceMeshRenderer
00026     {
00027     public:
00028         RealtimeSurfaceMeshRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00029         void CreateDeviceDependentResources();
00030         void ReleaseDeviceDependentResources();
00031         void Update(
00032             DX::StepTimer const& timer,
00033             Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem
00034             );
00035         void Render(bool isStereo, bool useWireframe);
00036
00037         bool HasSurface(Platform::Guid id);
00038         void AddSurface(Platform::Guid id, Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ newSurface);
00039         void UpdateSurface(Platform::Guid id, Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ newSurface);
00040         void RemoveSurface(Platform::Guid id);
00041         void ClearSurfaces();
00042
00043         Windows::Foundation::DateTime GetLastUpdateTime(Platform::Guid id);
00044
00045         void HideInactiveMeshes(
00046             Windows::Foundation::Collections::IMapView<Platform::Guid,
00047             Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^>^ const& surfaceCollection);
00048
00049     private:
00050         Concurrency::task<void> AddOrUpdateSurfaceAsync(Platform::Guid id, Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^ newSurface);
00051
00052         // Cached pointer to device resources.
00053         std::shared_ptr<DX::DeviceResources>            m_deviceResources;
00054
00055         // Direct3D resources for SR mesh rendering pipeline.
00056         Microsoft::WRL::ComPtr<ID3D11InputLayout>       m_inputLayout;
00057         Microsoft::WRL::ComPtr<ID3D11VertexShader>      m_vertexShader;
00058         Microsoft::WRL::ComPtr<ID3D11GeometryShader>    m_geometryShader;
00059         Microsoft::WRL::ComPtr<ID3D11PixelShader>       m_lightingPixelShader;
00060         Microsoft::WRL::ComPtr<ID3D11PixelShader>       m_colorPixelShader;
00061
00062         // The set of surfaces in the collection.
00063         std::map<Platform::Guid, SurfaceMesh>           m_meshCollection;
00064
00065         // A way to lock map access.
00066         std::mutex                                      m_meshCollectionLock;
00067
00068         // Total number of surface meshes.
00069         unsigned int                                    m_surfaceMeshCount;
00070
00071         // Level of detail setting. The number of triangles that the system is allowed to provide per cubic meter.
00072         double                                          m_maxTrianglesPerCubicMeter = 1000.0;
00073
00074         // If the current D3D Device supports VPRT, we can avoid using a geometry
00075         // shader just to set the render target array index.
00076         bool                                            m_usingVprtShaders = false;
00077
00078         // Rasterizer states, for different rendering modes.
00079         Microsoft::WRL::ComPtr<ID3D11RasterizerState>   m_defaultRasterizerState;
00080         Microsoft::WRL::ComPtr<ID3D11RasterizerState>   m_wireframeRasterizerState;
00081
00082         // The duration of time, in seconds, a mesh is allowed to remain inactive before deletion.
00083         const float c_maxInactiveMeshTime = 120.f;
00084
00085         // The duration of time, in seconds, taken for a new surface mesh to fade in on-screen.
00086         const float c_surfaceMeshFadeInTime = 3.0f;
00087
00088         bool m_loadingComplete;
00089     };
00090 };
00091
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_SendMIDIMessages Member List

This is the complete list of members for Scenario3_SendMIDIMessages, including all inherited members.
currentMessageType | Scenario3_SendMIDIMessages | [private]
currentMidiOutputDevice | Scenario3_SendMIDIMessages | [private]
messageType_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario3_SendMIDIMessages | [inline, private]
messageTypes | Scenario3_SendMIDIMessages | [private]
midiOutDeviceWatcher | Scenario3_SendMIDIMessages | [private]
midiOutPorts | Scenario3_SendMIDIMessages | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario3_SendMIDIMessages | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_SendMIDIMessages | [inline, protected]
outputDevices_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario3_SendMIDIMessages | [inline, private]
Parameter1_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario3_SendMIDIMessages | [inline, private]
Parameter2_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario3_SendMIDIMessages | [inline, private]
Parameter3_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario3_SendMIDIMessages | [inline, private]
PopulateMessageTypes() | Scenario3_SendMIDIMessages | [inline, private]
PopulateParameterList(ComboBox list, int numberOfOptions, string listName) | Scenario3_SendMIDIMessages | [inline, private]
resetButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3_SendMIDIMessages | [inline, private]
ResetMessageTypeAndParameters(bool resetMessageType) | Scenario3_SendMIDIMessages | [inline, private]
rootPage | Scenario3_SendMIDIMessages | [private]
Scenario3_SendMIDIMessages() | Scenario3_SendMIDIMessages | [inline]
sendButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3_SendMIDIMessages | [inline, private]
UpdateParameterList1() | Scenario3_SendMIDIMessages | [inline, private]
UpdateParameterList2() | Scenario3_SendMIDIMessages | [inline, private]
UpdateParameterList3() | Scenario3_SendMIDIMessages | [inline, private]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/Scenario_PredefinedWebSearchGrammar.xaml.h Source File

  • SpeechRecognitionAndSynthesis
  • cpp

Scenario_PredefinedWebSearchGrammar.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario_PredefinedWebSearchGrammar.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario_PredefinedWebSearchGrammar sealed
00024     {
00025     public:
00026         Scenario_PredefinedWebSearchGrammar();
00027
00028     protected:
00029         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00031
00032     private:
00033         static const unsigned int HResultPrivacyStatementDeclined = 0x80045509;
00034
00035         SDKTemplate::MainPage^ rootPage;
00036         Windows::UI::Core::CoreDispatcher^ dispatcher;
00037         Windows::Media::SpeechRecognition::SpeechRecognizer^ speechRecognizer;
00038         Windows::ApplicationModel::Resources::Core::ResourceContext^ speechContext;
00039         Windows::ApplicationModel::Resources::Core::ResourceMap^ speechResourceMap;
00040
00041         void RecognizeWithUIWebSearchGrammar_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         void RecognizeWithoutUIWebSearchGrammar_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00043
00044         void InitializeRecognizer(Windows::Globalization::Language^ recognizerLanguage);
00045         void PopulateLanguageDropdown();
00046
00047         Windows::Foundation::EventRegistrationToken stateChangedToken;
00048         void SpeechRecognizer_StateChanged(Windows::Media::SpeechRecognition::SpeechRecognizer ^sender, Windows::Media::SpeechRecognition::SpeechRecognizerStateChangedEventArgs ^args);
00049         void cbLanguageSelection_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00050         void openPrivacySettings_Click(Windows::UI::Xaml::Documents::Hyperlink^ sender, Windows::UI::Xaml::Documents::HyperlinkClickEventArgs^ args);
00051     };
00052
00053 }
Generated on Fri Nov 15 2024 22:21:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cpp/pch.cpp Source File

  • SmartCard
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Package/cpp/scenario1_identity.xaml.cpp Source File

  • Package
  • cpp

scenario1_identity.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario1.xaml.cpp
00013 // Implementation of the Scenario1 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario1_Identity.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace Platform;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::ApplicationModel;
00027
00028 Scenario1::Scenario1()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Invoked when this page is about to be displayed in a Frame.
00035 /// </summary>
00036 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037 /// property is typically used to configure the page.</param>
00038 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00039 {
00040     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00041     // as NotifyUser()
00042     rootPage = MainPage::Current;
00043 }
00044
00045 Platform::String^ Scenario1::VersionString(PackageVersion version)
00046 {
00047     return version.Major.ToString() + "." + version.Minor.ToString() + "." +
00048            version.Build.ToString() + "." + version.Revision.ToString();
00049 }
00050
00051 Platform::String^ Scenario1::ArchitectureString(Windows::System::ProcessorArchitecture architecture)
00052 {
00053     switch (architecture)
00054     {
00055         case Windows::System::ProcessorArchitecture::X86:
00056             return "x86";
00057         case Windows::System::ProcessorArchitecture::Arm:
00058             return "arm";
00059         case Windows::System::ProcessorArchitecture::X64:
00060             return "x64";
00061         case Windows::System::ProcessorArchitecture::Neutral:
00062             return "neutral";
00063         case Windows::System::ProcessorArchitecture::Unknown:
00064             return "unknown";
00065         default:
00066             return "???";
00067     }
00068 }
00069
00070 void Scenario1::GetPackage_Click(Object^ sender, RoutedEventArgs^ e)
00071 {
00072     Package^ package = Package::Current;
00073     PackageId^ packageId = package->Id;
00074
00075     String^ output = "Name: \"" + packageId->Name + "\"\n" +
00076                      "Version: " + VersionString(packageId->Version) + "\n" +
00077                      "Architecture: " + ArchitectureString(packageId->Architecture) + "\n" +
00078                      "ResourceId: \"" + packageId->ResourceId + "\"\n" +
00079                      "Publisher: \"" + packageId->Publisher + "\"\n" +
00080                      "PublisherId: \"" + packageId->PublisherId + "\"\n" +
00081                      "FullName: \"" + packageId->FullName + "\"\n" +
00082                      "FamilyName: \"" + packageId->FamilyName + "\"\n" +
00083                      "IsFramework: " + package->IsFramework.ToString() + "\n";
00084 #if WINAPI_FAMILY == WINAPI_FAMILY_PC_APP
00085     output += "IsResourcePackage: " + package->IsResourcePackage.ToString() + "\n" +
00086               "IsBundle: " + package->IsBundle.ToString() + "\"\n" +
00087               "IsDevelopmentMode: " + package->IsDevelopmentMode.ToString() + "\n" +
00088               "DisplayName: \"" + package->DisplayName + "\"\n" +
00089               "PublisherDisplayName: \"" + package->PublisherDisplayName + "\"\n" +
00090               "Description: \"" + package->Description + "\"\n" +
00091               "Logo: \"" + package->Logo->AbsoluteUri + "\"\n";
00092 #endif
00093
00094     OutputTextBlock->Text = output;
00095 }
Generated on Fri Nov 15 2024 22:20:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraAdvancedCapture/cpp/App.xaml.cpp Source File

  • CameraAdvancedCapture
  • cpp

App.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014
00015 using namespace CameraAdvancedCapture;
00016 using namespace Platform;
00017 using namespace Windows::ApplicationModel;
00018 using namespace Windows::ApplicationModel::Activation;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Media;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 /// <summary>
00031 /// Initializes the singleton application object.  This is the first line of authored code
00032 /// executed, and as such is the logical equivalent of main() or WinMain().
00033 /// </summary>
00034 App::App()
00035 {
00036     InitializeComponent();
00037     Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
00038 }
00039
00040 /// <summary>
00041 /// Invoked when the application is launched normally by the end user.  Other entry points
00042 /// will be used such as when the application is launched to open a specific file.
00043 /// </summary>
00044 /// <param name="e">Details about the launch request and process.</param>
00045 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
00046 {
00047
00048 #if _DEBUG
00049         // Show graphics profiling information while debugging.
00050         if (IsDebuggerPresent())
00051         {
00052             // Display the current frame rate counters
00053              DebugSettings->EnableFrameRateCounter = true;
00054         }
00055 #endif
00056
00057     auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00058
00059     // Do not repeat app initialization when the Window already has content,
00060     // just ensure that the window is active
00061     if (rootFrame == nullptr)
00062     {
00063         // Create a Frame to act as the navigation context and associate it with
00064         // a SuspensionManager key
00065         rootFrame = ref new Frame();
00066
00067         // Set the default language
00068         rootFrame->Language = Windows::Globalization::ApplicationLanguages::Languages->GetAt(0);
00069
00070         rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed);
00071
00072         if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
00073         {
00074             // Restore the saved session state only when appropriate, scheduling the
00075             // final launch steps after the restore is complete
00076
00077         }
00078
00079         if (rootFrame->Content == nullptr)
00080         {
00081             // When the navigation stack isn't restored navigate to the first page,
00082             // configuring the new page by passing required information as a navigation
00083             // parameter
00084             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00085         }
00086         // Place the frame in the current Window
00087         Window::Current->Content = rootFrame;
00088         // Ensure the current window is active
00089         Window::Current->Activate();
00090     }
00091     else
00092     {
00093         if (rootFrame->Content == nullptr)
00094         {
00095             // When the navigation stack isn't restored navigate to the first page,
00096             // configuring the new page by passing required information as a navigation
00097             // parameter
00098             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00099         }
00100         // Ensure the current window is active
00101         Window::Current->Activate();
00102     }
00103 }
00104
00105 /// <summary>
00106 /// Invoked when application execution is being suspended.  Application state is saved
00107 /// without knowing whether the application will be terminated or resumed with the contents
00108 /// of memory still intact.
00109 /// </summary>
00110 /// <param name="sender">The source of the suspend request.</param>
00111 /// <param name="e">Details about the suspend request.</param>
00112 void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
00113 {
00114     (void) sender;  // Unused parameter
00115     (void) e;   // Unused parameter
00116
00117     // Save application state and stop any background activity
00118 }
00119
00120 /// <summary>
00121 /// Invoked when Navigation to a certain page fails
00122 /// </summary>
00123 /// <param name="sender">The Frame which failed navigation</param>
00124 /// <param name="e">Details about the navigation failure</param>
00125 void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e)
00126 {
00127     throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name);
00128 }
Generated on Fri Nov 15 2024 22:16:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/pch.h Source File

  • FileAccess
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #define NOMINMAX
00004 #include <hstring.h>
00005 #include "winrt/Windows.Foundation.h"
00006 #include "winrt/Windows.Foundation.Collections.h"
00007 #include "winrt/Windows.ApplicationModel.Activation.h"
00008 #include "winrt/Windows.Globalization.DateTimeFormatting.h"
00009 #include "winrt/Windows.Security.Cryptography.h"
00010 #include "winrt/Windows.Storage.h"
00011 #include "winrt/Windows.Storage.AccessCache.h"
00012 #include "winrt/Windows.Storage.FileProperties.h"
00013 #include "winrt/Windows.Storage.Pickers.h"
00014 #include "winrt/Windows.Storage.Streams.h"
00015 #include "winrt/Windows.System.h"
00016 #include "winrt/Windows.UI.Core.h"
00017 #include "winrt/Windows.UI.Xaml.h"
00018 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00019 #include "winrt/Windows.UI.Xaml.Controls.h"
00020 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00021 #include "winrt/Windows.UI.Xaml.Documents.h"
00022 #include "winrt/Windows.UI.Xaml.Interop.h"
00023 #include "winrt/Windows.UI.Xaml.Markup.h"
00024 #include "winrt/Windows.UI.Xaml.Media.h"
00025 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/StspMediaSource.cpp Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

StspMediaSource.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "StspMediaSource.h"
00010 #include "StspMediaStream.h"
00011 #include <IntSafe.h>
00012
00013 using namespace Microsoft::Samples::SimpleCommunication;
00014 using namespace Microsoft::Samples::SimpleCommunication::Network;
00015
00016 namespace
00017 {
00018     const DWORD c_cbReceiveBufferSize = 2 * 1024;
00019     const DWORD c_cbMaxPacketSize = 1024 * 1024;
00020 };
00021
00022 CSourceOperation::CSourceOperation(CSourceOperation::Type opType)
00023 : _cRef(1)
00024 , _opType(opType)
00025 {
00026     ZeroMemory(&_data, sizeof(_data));
00027 }
00028
00029 CSourceOperation::~CSourceOperation()
00030 {
00031     PropVariantClear(&_data);
00032 }
00033
00034 // IUnknown methods
00035 IFACEMETHODIMP CSourceOperation::QueryInterface(REFIID riid, void **ppv)
00036 {
00037     return E_NOINTERFACE;
00038 }
00039
00040 IFACEMETHODIMP_(ULONG) CSourceOperation::AddRef()
00041 {
00042     return InterlockedIncrement(&_cRef);
00043 }
00044
00045 IFACEMETHODIMP_(ULONG) CSourceOperation::Release()
00046 {
00047     long cRef = InterlockedDecrement(&_cRef);
00048     if (cRef == 0)
00049     {
00050         delete this;
00051     }
00052     return cRef;
00053 }
00054
00055 HRESULT CSourceOperation::SetData(const PROPVARIANT &varData)
00056 {
00057     return PropVariantCopy(&_data, &varData);
00058 }
00059
00060 CStartOperation::CStartOperation(IMFPresentationDescriptor *pPD)
00061 : CSourceOperation(CSourceOperation::Operation_Start)
00062 , _spPD(pPD)
00063 {
00064 }
00065
00066 CStartOperation::~CStartOperation()
00067 {
00068 }
00069
00070 CSetRateOperation::CSetRateOperation(BOOL fThin, float flRate)
00071 : CSourceOperation(CSourceOperation::Operation_SetRate)
00072 , _fThin(fThin)
00073 , _flRate(flRate)
00074 {
00075 }
00076
00077 CSetRateOperation::~CSetRateOperation()
00078 {
00079 }
00080
00081 CMediaSource::CMediaSource(void)
00082 : OpQueue<CMediaSource, CSourceOperation>(_critSec.m_criticalSection)
00083 , _cRef(1)
00084 , _eSourceState(SourceState_Invalid)
00085 , _serverPort(0)
00086 , _flRate(1.0f)
00087 {
00088     ZeroMemory(&_CurrentReceivedOperationHeader, sizeof(_CurrentReceivedOperationHeader));
00089 }
00090
00091 CMediaSource::~CMediaSource(void)
00092 {
00093 }
00094
00095 HRESULT CMediaSource::CreateInstance(CMediaSource **ppNetSource)
00096 {
00097     HRESULT hr = S_OK;
00098
00099     try
00100     {
00101         if (ppNetSource == nullptr)
00102         {
00103             Throw(E_INVALIDARG);
00104         }
00105
00106         ComPtr<CMediaSource> spSource;
00107         spSource.Attach(new (std::nothrow) CMediaSource());
00108         if (!spSource)
00109         {
00110             Throw(E_OUTOFMEMORY);
00111         }
00112
00113         spSource->Initialize();
00114
00115         *ppNetSource = spSource.Detach();
00116     }
00117     catch(Exception ^exc)
00118     {
00119         hr = exc->HResult;
00120     }
00121
00122     TRACEHR_RET(hr);
00123 }
00124
00125 // IUnknown methods
00126
00127 IFACEMETHODIMP CMediaSource::QueryInterface(REFIID riid, void **ppv)
00128 {
00129     if (ppv == nullptr)
00130     {
00131         return E_POINTER;
00132     }
00133     (*ppv) = nullptr;
00134
00135     HRESULT hr = S_OK;
00136     if (riid == IID_IUnknown ||
00137         riid == IID_IMFMediaSource ||
00138         riid == IID_IMFMediaEventGenerator)
00139     {
00140         (*ppv) = static_cast<IMFMediaSource*>(this);
00141         AddRef();
00142     }
00143     else if (riid == IID_IMFAttributes)
00144     {
00145         (*ppv) = static_cast<IMFAttributes*>(this);
00146         AddRef();
00147     }
00148     else if (riid == IID_IMFGetService)
00149     {
00150         (*ppv) = static_cast<IMFGetService*>(this);
00151         AddRef();
00152     }
00153     else if (riid == IID_IMFRateControl)
00154     {
00155         (*ppv) = static_cast<IMFRateControl*>(this);
00156         AddRef();
00157     }
00158     else
00159     {
00160         hr = E_NOINTERFACE;
00161     }
00162
00163     return hr;
00164 }
00165
00166 IFACEMETHODIMP_(ULONG) CMediaSource::AddRef()
00167 {
00168     return InterlockedIncrement(&_cRef);
00169 }
00170
00171 IFACEMETHODIMP_(ULONG) CMediaSource::Release()
00172 {
00173     long cRef = InterlockedDecrement(&_cRef);
00174     if (cRef == 0)
00175     {
00176         delete this;
00177     }
00178     return cRef;
00179 }
00180
00181 // IMFMediaEventGenerator methods.
00182 // Note: These methods call through to the event queue helper object.
00183 IFACEMETHODIMP CMediaSource::BeginGetEvent(IMFAsyncCallback *pCallback, IUnknown *punkState)
00184 {
00185     HRESULT hr = S_OK;
00186
00187     AutoLock lock(_critSec);
00188
00189     hr = CheckShutdown();
00190
00191     if (SUCCEEDED(hr))
00192     {
00193         hr = _spEventQueue->BeginGetEvent(pCallback, punkState);
00194     }
00195
00196     TRACEHR_RET(hr);
00197 }
00198
00199 IFACEMETHODIMP CMediaSource::EndGetEvent(IMFAsyncResult *pResult, IMFMediaEvent **ppEvent)
00200 {
00201     HRESULT hr = S_OK;
00202
00203     AutoLock lock(_critSec);
00204
00205     hr = CheckShutdown();
00206
00207     if (SUCCEEDED(hr))
00208     {
00209         hr = _spEventQueue->EndGetEvent(pResult, ppEvent);
00210     }
00211
00212     TRACEHR_RET(hr);
00213 }
00214
00215 IFACEMETHODIMP CMediaSource::GetEvent(DWORD dwFlags, IMFMediaEvent **ppEvent)
00216 {
00217     // NOTE:
00218     // GetEvent can block indefinitely, so we don't hold the lock.
00219     // This requires some juggling with the event queue pointer.
00220
00221     HRESULT hr = S_OK;
00222
00223     ComPtr<IMFMediaEventQueue> spQueue;
00224
00225     {
00226         AutoLock lock(_critSec);
00227
00228         // Check shutdown
00229         hr = CheckShutdown();
00230
00231         // Get the pointer to the event queue.
00232         if (SUCCEEDED(hr))
00233         {
00234             spQueue = _spEventQueue;
00235         }
00236     }
00237
00238     // Now get the event.
00239     if (SUCCEEDED(hr))
00240     {
00241         hr = spQueue->GetEvent(dwFlags, ppEvent);
00242     }
00243
00244
00245     TRACEHR_RET(hr);
00246 }
00247
00248 IFACEMETHODIMP CMediaSource::QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, PROPVARIANT const *pvValue)
00249 {
00250     HRESULT hr = S_OK;
00251
00252     AutoLock lock(_critSec);
00253
00254     hr = CheckShutdown();
00255
00256     if (SUCCEEDED(hr))
00257     {
00258         hr = _spEventQueue->QueueEventParamVar(met, guidExtendedType, hrStatus, pvValue);
00259     }
00260
00261     TRACEHR_RET(hr);
00262 }
00263
00264 // IMFMediaSource methods
00265 IFACEMETHODIMP CMediaSource::CreatePresentationDescriptor(
00266 IMFPresentationDescriptor **ppPresentationDescriptor
00267 )
00268 {
00269     if (ppPresentationDescriptor == NULL)
00270     {
00271         return E_POINTER;
00272     }
00273
00274     AutoLock lock(_critSec);
00275
00276     HRESULT hr = CheckShutdown();
00277
00278     if (SUCCEEDED(hr) &&
00279         (_eSourceState == SourceState_Opening || _eSourceState == SourceState_Invalid || !_spPresentationDescriptor))
00280     {
00281         hr = MF_E_NOT_INITIALIZED;
00282     }
00283
00284     if (SUCCEEDED(hr))
00285     {
00286         hr = _spPresentationDescriptor->Clone(ppPresentationDescriptor);
00287     }
00288
00289     return hr;
00290 }
00291
00292 IFACEMETHODIMP CMediaSource::GetCharacteristics(DWORD *pdwCharacteristics)
00293 {
00294     if (pdwCharacteristics == NULL)
00295     {
00296         return E_POINTER;
00297     }
00298
00299     AutoLock lock(_critSec);
00300
00301     HRESULT hr = CheckShutdown();
00302
00303     if (SUCCEEDED(hr))
00304     {
00305         *pdwCharacteristics = MFMEDIASOURCE_IS_LIVE;
00306     }
00307
00308     TRACEHR_RET(hr);
00309 }
00310
00311 IFACEMETHODIMP CMediaSource::Pause()
00312 {
00313     return MF_E_INVALID_STATE_TRANSITION;
00314 }
00315
00316 IFACEMETHODIMP CMediaSource::Shutdown()
00317 {
00318     AutoLock lock(_critSec);
00319
00320     HRESULT hr = CheckShutdown();
00321
00322     if (SUCCEEDED(hr))
00323     {
00324         if (_spEventQueue != nullptr)
00325         {
00326             _spEventQueue->Shutdown();
00327         }
00328         if (_networkSender != nullptr)
00329         {
00330             _networkSender->Close();
00331         }
00332
00333         StreamContainer::POSITION pos = _streams.FrontPosition();
00334         while (pos != _streams.EndPosition())
00335         {
00336             ComPtr<IMFMediaStream> spStream;
00337             hr = _streams.GetItemPos(pos, &spStream);
00338             pos = _streams.Next(pos);
00339             if (SUCCEEDED(hr))
00340             {
00341                 static_cast<CMediaStream*>(spStream.Get())->Shutdown();
00342             }
00343         }
00344
00345         _eSourceState = SourceState_Shutdown;
00346
00347         _streams.Clear();
00348
00349         _spEventQueue.Reset();
00350         _networkSender = nullptr;
00351     }
00352
00353     TRACEHR_RET(hr);
00354 }
00355
00356 IFACEMETHODIMP CMediaSource::Start(
00357                                    IMFPresentationDescriptor *pPresentationDescriptor,
00358                                    const GUID *pguidTimeFormat,
00359                                    const PROPVARIANT *pvarStartPos
00360                                    )
00361 {
00362     HRESULT hr = S_OK;
00363
00364     // Check parameters.
00365
00366     // Start position and presentation descriptor cannot be NULL.
00367     if (pvarStartPos == nullptr || pPresentationDescriptor == nullptr)
00368     {
00369         return E_INVALIDARG;
00370     }
00371
00372     // Check the time format.
00373     if ((pguidTimeFormat != nullptr) && (*pguidTimeFormat != GUID_NULL))
00374     {
00375         // Unrecognized time format GUID.
00376         return MF_E_UNSUPPORTED_TIME_FORMAT;
00377     }
00378
00379     // Check the data type of the start position.
00380     if (pvarStartPos->vt != VT_EMPTY && pvarStartPos->vt != VT_I8)
00381     {
00382         return MF_E_UNSUPPORTED_TIME_FORMAT;
00383     }
00384
00385     AutoLock lock(_critSec);
00386     ComPtr<CStartOperation> spStartOp;
00387
00388     if (_eSourceState != SourceState_Stopped &&
00389         _eSourceState != SourceState_Started)
00390     {
00391         hr = MF_E_INVALIDREQUEST;
00392     }
00393
00394     if (SUCCEEDED(hr))
00395     {
00396         // Check if the presentation description is valid.
00397         hr = ValidatePresentationDescriptor(pPresentationDescriptor);
00398     }
00399
00400     if (SUCCEEDED(hr))
00401     {
00402         // Prepare asynchronous operation attributes
00403         spStartOp.Attach(new (std::nothrow) CStartOperation(pPresentationDescriptor));
00404         if (!spStartOp)
00405         {
00406             hr = E_OUTOFMEMORY;
00407         }
00408
00409         if (SUCCEEDED(hr))
00410         {
00411             hr = spStartOp->SetData(*pvarStartPos);
00412         }
00413     }
00414
00415     if (SUCCEEDED(hr))
00416     {
00417         // Queue asynchronous operation
00418         hr = QueueOperation(spStartOp.Get());
00419     }
00420
00421     TRACEHR_RET(hr);
00422 }
00423
00424 IFACEMETHODIMP CMediaSource::Stop()
00425 {
00426     HRESULT hr = S_OK;
00427     ComPtr<CSourceOperation> spStopOp;
00428     spStopOp.Attach(new (std::nothrow) CSourceOperation(CSourceOperation::Operation_Stop));
00429     if (!spStopOp)
00430     {
00431         hr = E_OUTOFMEMORY;
00432     }
00433
00434     if (SUCCEEDED(hr))
00435     {
00436         // Queue asynchronous stop
00437         hr = QueueOperation(spStopOp.Get());
00438     }
00439
00440     TRACEHR_RET(hr);
00441 }
00442
00443 IFACEMETHODIMP CMediaSource::GetService( _In_ REFGUID guidService, _In_ REFIID riid, _Out_opt_ LPVOID *ppvObject)
00444 {
00445     HRESULT hr = MF_E_UNSUPPORTED_SERVICE;
00446
00447     if (ppvObject == nullptr)
00448     {
00449         return E_POINTER;
00450     }
00451
00452     if (guidService == MF_RATE_CONTROL_SERVICE)
00453     {
00454         hr = QueryInterface(riid, ppvObject);
00455     }
00456
00457     return hr;
00458 }
00459
00460 IFACEMETHODIMP CMediaSource::SetRate(BOOL fThin, float flRate)
00461 {
00462     if (fThin)
00463     {
00464         return MF_E_THINNING_UNSUPPORTED;
00465     }
00466     if (!IsRateSupported(flRate, &flRate))
00467     {
00468         return MF_E_UNSUPPORTED_RATE;
00469     }
00470
00471     AutoLock lock(_critSec);
00472     HRESULT hr = S_OK;
00473
00474     if (flRate == _flRate)
00475     {
00476         return S_OK;
00477     }
00478
00479     ComPtr<CSourceOperation> spSetRateOp;
00480     spSetRateOp.Attach(new (std::nothrow) CSetRateOperation(fThin, flRate));
00481     if (!spSetRateOp)
00482     {
00483         hr = E_OUTOFMEMORY;
00484     }
00485
00486     if (SUCCEEDED(hr))
00487     {
00488         // Queue asynchronous stop
00489         hr = QueueOperation(spSetRateOp.Get());
00490     }
00491
00492     TRACEHR_RET(hr);
00493 }
00494
00495 IFACEMETHODIMP CMediaSource::GetRate(_Inout_opt_ BOOL *pfThin, _Inout_opt_ float *pflRate)
00496 {
00497     AutoLock lock(_critSec);
00498     if (pfThin == nullptr || pflRate == nullptr)
00499     {
00500         return E_INVALIDARG;
00501     }
00502
00503     *pfThin = FALSE;
00504     *pflRate = _flRate;
00505
00506     return S_OK;
00507 }
00508
00509 __override HRESULT CMediaSource::DispatchOperation(_In_ CSourceOperation *pOp)
00510 {
00511     AutoLock lock(_critSec);
00512
00513     HRESULT hr = CheckShutdown();
00514
00515     if (SUCCEEDED(hr))
00516     {
00517         switch(pOp->GetOperationType())
00518         {
00519         case CSourceOperation::Operation_Start:
00520             DoStart(static_cast<CStartOperation *>(pOp));
00521             break;
00522         case CSourceOperation::Operation_Stop:
00523             DoStop(pOp);
00524             break;
00525         case CSourceOperation::Operation_SetRate:
00526             DoSetRate(static_cast<CSetRateOperation *>(pOp));
00527             break;
00528         default:
00529             hr = E_UNEXPECTED;
00530             break;
00531         }
00532     }
00533
00534     TRACEHR_RET(hr);
00535 }
00536
00537 __override HRESULT CMediaSource::ValidateOperation(_In_ CSourceOperation *pOp)
00538 {
00539     return S_OK;
00540 }
00541
00542 concurrency::task<void> CMediaSource::OpenAsync(LPCWSTR pszUrl)
00543 {
00544     AutoLock lock(_critSec);
00545
00546     if (_eSourceState != SourceState_Invalid)
00547     {
00548         Throw(MF_E_INVALIDREQUEST);
00549     }
00550
00551     if (pszUrl == nullptr)
00552     {
00553         Throw(E_INVALIDARG);
00554     }
00555
00556     // Get network client
00557     INetworkClient ^networkClient = safe_cast<INetworkClient^>(_networkSender);
00558
00559     // Parse url (to obtain host name and port)
00560     ParseServerUrl(pszUrl);
00561
00562     concurrency::create_task(networkClient->ConnectAsync(_serverAddress, _serverPort)).then([this](concurrency::task<void>& connectTask)
00563     {
00564         AutoLock lock(_critSec);
00565         try
00566         {
00567             connectTask.get();
00568             ThrowIfError(CheckShutdown());
00569             if (_eSourceState != SourceState_Opening)
00570             {
00571                 Throw(MF_E_UNEXPECTED);
00572             }
00573
00574             SendDescribeRequest();
00575         }
00576         catch(Exception ^exc)
00577         {
00578             HandleError(exc->HResult);
00579             Shutdown();
00580         }
00581     });
00582
00583     // If everything is ok now we are waiting for network client to connect.
00584     // Change state to opening.
00585     _eSourceState = SourceState_Opening;
00586
00587     return concurrency::task<void>(_openedEvent);
00588 }
00589
00590 _Acquires_lock_(_critSec)
00591 HRESULT CMediaSource::Lock()
00592 {
00593     _critSec.Lock();
00594     return S_OK;
00595 }
00596
00597 _Releases_lock_(_critSec)
00598 HRESULT CMediaSource::Unlock()
00599 {
00600     _critSec.Unlock();
00601     return S_OK;
00602 }
00603
00604 void CMediaSource::Initialize()
00605 {
00606     try
00607     {
00608         INetworkClient ^networkClient;
00609
00610         // Create the event queue helper.
00611         ThrowIfError(MFCreateEventQueue(&_spEventQueue));
00612
00613         ThrowIfError(CBaseAttributes<>::Initialize());
00614
00615         // Create network client
00616         networkClient = CreateNetworkClient();
00617
00618         _networkSender = safe_cast<INetworkChannel^>(networkClient);
00619     }
00620     catch(Exception^)
00621     {
00622         Shutdown();
00623         throw;
00624     }
00625 }
00626
00627 // Handle errors
00628 void CMediaSource::HandleError(HRESULT hResult)
00629 {
00630     if (_eSourceState == SourceState_Opening)
00631     {
00632         // If we have an error during opening operation complete it and pass the error to client.
00633         CompleteOpen(hResult);
00634     }
00635     else if (_eSourceState != SourceState_Shutdown)
00636     {
00637         // If we received an error at any other time (except shutdown) send MEError event.
00638         QueueEvent(MEError, GUID_NULL, hResult, nullptr);
00639     }
00640 }
00641
00642 // Returns stream object associated with given identifier
00643 HRESULT CMediaSource::GetStreamById(DWORD dwId, CMediaStream **ppStream)
00644 {
00645     assert(ppStream);
00646     HRESULT hr = MF_E_NOT_FOUND;
00647     StreamContainer::POSITION pos = _streams.FrontPosition();
00648     StreamContainer::POSITION posEnd = _streams.EndPosition();
00649
00650     for (; pos != posEnd; pos = _streams.Next(pos))
00651     {
00652         ComPtr<IMFMediaStream> spStream;
00653         HRESULT hErrorCode = _streams.GetItemPos(pos, &spStream);
00654         if (FAILED(hErrorCode))
00655         {
00656             hr = hErrorCode;
00657             break;
00658         }
00659         CMediaStream *pStream = static_cast<CMediaStream*>(spStream.Get());
00660         if (pStream->GetId() == dwId)
00661         {
00662             *ppStream = pStream;
00663             (*ppStream)->AddRef();
00664             hr = S_OK;
00665         }
00666     }
00667
00668     TRACEHR_RET(hr);
00669 }
00670
00671 void CMediaSource::ParseServerUrl(LPCWSTR pszUrl)
00672 {
00673     if (pszUrl == nullptr)
00674     {
00675         Throw(E_INVALIDARG);
00676     }
00677
00678     auto uri = ref new Windows::Foundation::Uri(ref new String(pszUrl));
00679
00680     String ^scheme = uri->SchemeName;
00681     // It is not a scheme we support
00682     if (wcscmp(scheme->Data(), c_szStspScheme) != 0)
00683     {
00684         Throw(MF_E_UNSUPPORTED_SCHEME);
00685     }
00686
00687     if (uri->Port == 0)
00688     {
00689         _serverPort = c_wStspDefaultPort;
00690     }
00691     else if (uri->Port < 0 || uri->Port > WORD_MAX)
00692     {
00693         Throw(E_UNEXPECTED);
00694     }
00695     else
00696     {
00697         _serverPort = (WORD)uri->Port;
00698     }
00699
00700     _serverAddress = uri->Host;
00701 }
00702
00703 void CMediaSource::CompleteOpen(HRESULT hResult)
00704 {
00705     assert(!_openedEvent._IsTriggered());
00706     if (FAILED(hResult))
00707     {
00708         _openedEvent.set_exception(ref new Exception(hResult));
00709     }
00710     else
00711     {
00712         _openedEvent.set();
00713     }
00714 }
00715
00716 concurrency::task<void> CMediaSource::SendRequestAsync(StspOperation eOperation)
00717 {
00718     ComPtr<IMediaBufferWrapper> spBuffer;
00719     ComPtr<IBufferPacket> spPacket;
00720     // We just send an operation header this operation contains no payload.
00721     ThrowIfError(CreateMediaBufferWrapper(sizeof(StspOperationHeader), &spBuffer));
00722
00723     ThrowIfError(CreateBufferPacket(&spPacket));
00724
00725     // Prepare operation header.
00726     StspOperationHeader *pOpHeader = reinterpret_cast<StspOperationHeader *>(spBuffer->GetBuffer());
00727     pOpHeader->cbDataSize = 0;
00728     pOpHeader->eOperation = eOperation;
00729     ThrowIfError(spBuffer->SetCurrentLength(sizeof(StspOperationHeader)));
00730
00731     ThrowIfError(spPacket->AddBuffer(spBuffer.Get()));
00732
00733     return concurrency::create_task(_networkSender->SendAsync(spPacket.Get()));
00734 }
00735
00736 // Sending request for media description to the server
00737 void CMediaSource::SendDescribeRequest()
00738 {
00739     _CurrentReceivedOperationHeader.eOperation = StspOperation_Unknown;
00740     ComPtr<CMediaSource> spThis = this;
00741     SendRequestAsync(StspOperation_ClientRequestDescription).then([this, spThis](concurrency::task<void>& task)
00742     {
00743         AutoLock lock(_critSec);
00744         try
00745         {
00746             task.get();
00747
00748             ThrowIfError(CheckShutdown());
00749             if (_eSourceState != SourceState_Opening)
00750             {
00751                 Throw(MF_E_UNEXPECTED);
00752             }
00753
00754             // Start receiving
00755             Receive();
00756         }
00757         catch(Exception ^exc)
00758         {
00759             HandleError(exc->HResult);
00760         }
00761     });
00762 }
00763
00764 void CMediaSource::SendStartRequest()
00765 {
00766     _CurrentReceivedOperationHeader.eOperation = StspOperation_Unknown;
00767     ComPtr<CMediaSource> spThis = this;
00768     SendRequestAsync(StspOperation_ClientRequestStart).then([this, spThis](concurrency::task<void>& task)
00769     {
00770         AutoLock lock(_critSec);
00771         try
00772         {
00773             task.get();
00774
00775             ThrowIfError(CheckShutdown());
00776             if (_eSourceState != SourceState_Starting && _eSourceState != SourceState_Started)
00777             {
00778                 Throw(MF_E_UNEXPECTED);
00779             }
00780         }
00781         catch(Exception ^exc)
00782         {
00783             HandleError(exc->HResult);
00784         }
00785     });
00786 }
00787
00788 // Trigger receiving operation
00789 void CMediaSource::Receive()
00790 {
00791     // We already during receive operation
00792     if (_spCurrentReceiveBuffer)
00793     {
00794         Throw(MF_E_INVALIDREQUEST);
00795     }
00796
00797     ComPtr<IMediaBufferWrapper> spBuffer;
00798     ThrowIfError(CreateMediaBufferWrapper(c_cbReceiveBufferSize, &spBuffer));
00799
00800     ComPtr<CMediaSource> spThis = this;
00801     concurrency::create_task(_networkSender->ReceiveAsync(spBuffer.Get())).then([this, spThis](concurrency::task<void>& task)
00802     {
00803         AutoLock lock(_critSec);
00804         try
00805         {
00806             task.get();
00807
00808             ThrowIfError(CheckShutdown());
00809
00810             ParseCurrentBuffer();
00811
00812             // Continue receiving
00813             Receive();
00814         }
00815         catch(Exception ^exc)
00816         {
00817             HandleError(exc->HResult);
00818         }
00819      });
00820
00821     _spCurrentReceiveBuffer = spBuffer;
00822 }
00823
00824 // Parse data stored in current receive buffer
00825 void CMediaSource::ParseCurrentBuffer()
00826 {
00827     bool fCompletePackage = false;
00828     DWORD cbTotalLength = 0;
00829     // Remember the buffer
00830     ComPtr<IMediaBufferWrapper> spLastBuffer = _spCurrentReceiveBuffer;
00831
00832     if (_spCurrentReceivePacket == nullptr)
00833     {
00834         // If packet object storing current operation data is not created yet - create it.
00835         ThrowIfError(CreateBufferPacket(&_spCurrentReceivePacket));
00836     }
00837
00838     // Add current receive buffer to the packet.
00839     ThrowIfError(_spCurrentReceivePacket->AddBuffer(_spCurrentReceiveBuffer.Get()));
00840     _spCurrentReceiveBuffer.Reset();
00841
00842     // Parsing new package, we have't read operation just yet
00843     if (_CurrentReceivedOperationHeader.eOperation == StspOperation_Unknown)
00844     {
00845         DWORD cbCurrentLength;
00846         ThrowIfError(_spCurrentReceivePacket->GetTotalLength(&cbCurrentLength));
00847
00848         // Check if we have enough data to retrieve operation header
00849         if(cbCurrentLength >= sizeof(StspOperationHeader))
00850         {
00851             ThrowIfError(_spCurrentReceivePacket->MoveLeft(sizeof(_CurrentReceivedOperationHeader), &_CurrentReceivedOperationHeader));
00852         }
00853         else
00854         {
00855             // We don't have enough data just yet so set data size to maximum packet size (then we will pass validation performed later on)
00856             _CurrentReceivedOperationHeader.cbDataSize = c_cbMaxPacketSize;
00857         }
00858     }
00859
00860     // Get length of the packet (without operation header which was removed from the packet).
00861     ThrowIfError(_spCurrentReceivePacket->GetTotalLength(&cbTotalLength));
00862
00863     if (// packet size is too large
00864         (c_cbMaxPacketSize < _CurrentReceivedOperationHeader.cbDataSize ||
00865         // Unrecognized operation
00866         _CurrentReceivedOperationHeader.eOperation >= StspOperation_Last))
00867     {
00868         Throw(MF_E_UNSUPPORTED_FORMAT);
00869     }
00870
00871     if (// Size of the package already exceeded value described in operation header
00872         cbTotalLength > _CurrentReceivedOperationHeader.cbDataSize)
00873     {
00874         // Trim the right edge of the packet and get buffer representing trimmed data
00875         ThrowIfError(spLastBuffer->TrimRight(cbTotalLength - _CurrentReceivedOperationHeader.cbDataSize, &_spCurrentReceiveBuffer));
00876         // Fix total length
00877         cbTotalLength = _CurrentReceivedOperationHeader.cbDataSize;
00878     }
00879
00880     // We've got a whole packet
00881     if (cbTotalLength == _CurrentReceivedOperationHeader.cbDataSize)
00882     {
00883         // Process packet payload
00884         ProcessPacket(&_CurrentReceivedOperationHeader, _spCurrentReceivePacket.Get());
00885         _spCurrentReceivePacket.Reset();
00886         _CurrentReceivedOperationHeader.eOperation =  StspOperation_Unknown;
00887     }
00888
00889     if (_spCurrentReceiveBuffer)
00890     {
00891         // We've got a buffer which was left from TrimRight operation above, we can keep parsing.
00892         ParseCurrentBuffer();
00893     }
00894 }
00895
00896 void CMediaSource::ProcessPacket(StspOperationHeader *pOpHeader, IBufferPacket *pPacket)
00897 {
00898     assert(pOpHeader);
00899     assert(pPacket);
00900
00901     switch(pOpHeader->eOperation)
00902     {
00903         // We received server description
00904     case StspOperation_ServerDescription:
00905         ProcessServerDescription(pPacket);
00906         break;
00907         // We received a media sample
00908     case StspOperation_ServerSample:
00909         ProcessServerSample(pPacket);
00910         break;
00911     case StspOperation_ServerFormatChange:
00912         ProcessServerFormatChange(pPacket);
00913         break;
00914         // No supported operation
00915     default:
00916         Throw(MF_E_UNSUPPORTED_FORMAT);
00917         break;
00918     }
00919 }
00920
00921 // Process server description packet
00922 void CMediaSource::ProcessServerDescription(IBufferPacket *pPacket)
00923 {
00924     DWORD cbTotalLen = 0;
00925     DWORD cbConstantSize = 0;
00926     StspDescription desc = {};
00927     StspDescription *pDescription = nullptr;
00928
00929     if (_eSourceState != SourceState_Opening)
00930     {
00931         // Server description should only be sent during opening state
00932         Throw(MF_E_UNEXPECTED);
00933     }
00934
00935     ThrowIfError(pPacket->GetTotalLength(&cbTotalLen));
00936
00937     // Minimum size of the operation payload is size of Description structure
00938     if (cbTotalLen < sizeof(StspDescription))
00939     {
00940         ThrowIfError(MF_E_UNSUPPORTED_FORMAT);
00941     }
00942
00943     // Copy description.
00944     ThrowIfError(pPacket->MoveLeft(sizeof(desc), &desc));
00945
00946
00947     // Size of the packet should match size described in the packet (size of Description structure
00948     // plus size of attribute blob)
00949     cbConstantSize = sizeof(desc) + (desc.cNumStreams - 1) * sizeof(StspStreamDescription);
00950     // Check if the input parameters are valid. We only support 2 streams.
00951     if (cbConstantSize < sizeof(desc) || desc.cNumStreams == 0 ||
00952         desc.cNumStreams > 2 || cbTotalLen < cbConstantSize)
00953     {
00954         ThrowIfError(MF_E_UNSUPPORTED_FORMAT);
00955     }
00956
00957     BYTE *pPtr = new (std::nothrow) BYTE[cbConstantSize];
00958     if (pPtr == nullptr)
00959     {
00960         Throw(E_OUTOFMEMORY);
00961     }
00962
00963     try
00964     {
00965         // Copy what we've already read
00966         CopyMemory(pPtr, &desc, sizeof(desc));
00967
00968         // Add more stream data if necessary at the end
00969         ThrowIfError(pPacket->MoveLeft(cbConstantSize - sizeof(desc), pPtr + sizeof(desc)));
00970
00971         // Data is ready
00972         pDescription = reinterpret_cast<StspDescription *>(pPtr);
00973
00974         DWORD cbAttributeSize = 0;
00975         for (DWORD nStream = 0; nStream < desc.cNumStreams; ++nStream)
00976         {
00977
00978             if (FAILED(DWordAdd(cbAttributeSize, pDescription->aStreams[nStream].cbAttributesSize, &cbAttributeSize)))
00979             {
00980                 Throw(MF_E_UNSUPPORTED_FORMAT);
00981             }
00982         }
00983
00984         // Validate the parameters. Limit the total size of attributes to 64kB.
00985         if ((cbTotalLen != (cbConstantSize + cbAttributeSize)) || (cbAttributeSize > 0x10000))
00986         {
00987             Throw(MF_E_UNSUPPORTED_FORMAT);
00988         }
00989
00990         // Create stream for every stream description sent by the server.
00991         for(DWORD nStream = 0; nStream < pDescription->cNumStreams; ++nStream)
00992         {
00993             ComPtr<CMediaStream> spStream;
00994
00995             ThrowIfError(CMediaStream::CreateInstance(&pDescription->aStreams[nStream], pPacket, this, &spStream));
00996
00997             ThrowIfError(_streams.InsertBack(spStream.Get()));
00998         }
00999
01000         InitPresentationDescription();
01001
01002         // Everything succeeded we are in stopped state now
01003         _eSourceState = SourceState_Stopped;
01004         CompleteOpen(S_OK);
01005
01006         delete[] pPtr;
01007     }
01008     catch(Exception ^exc)
01009     {
01010         delete[] pPtr;
01011         throw;
01012     }
01013 }
01014
01015 // Process a media sample reveived from the server.
01016 void CMediaSource::ProcessServerSample(IBufferPacket *pPacket)
01017 {
01018     if (_eSourceState == SourceState_Started)
01019     {
01020         // Only process samples when we are in started state
01021         StspSampleHeader sampleHead = {};
01022         DWORD cbTotalSize;
01023
01024         // Copy the header object
01025         ThrowIfError(pPacket->MoveLeft(sizeof(sampleHead), &sampleHead));
01026         ThrowIfError(pPacket->GetTotalLength(&cbTotalSize));
01027
01028         // Convert packet to MF sample
01029         ComPtr<IMFSample> spSample;
01030         ComPtr<CMediaStream> spStream;
01031
01032         ThrowIfError(GetStreamById(sampleHead.dwStreamId, &spStream));
01033
01034         if (spStream->IsActive())
01035         {
01036             ThrowIfError(pPacket->ToMFSample(&spSample));
01037             // Forward sample to a proper stream.
01038             spStream->ProcessSample(&sampleHead, spSample.Get());
01039         }
01040     }
01041     else
01042     {
01043         Throw(MF_E_UNEXPECTED);
01044     }
01045 }
01046
01047 void CMediaSource::ProcessServerFormatChange(IBufferPacket *pPacket)
01048 {
01049     BYTE *pAttributes = nullptr;
01050     Exception ^error;
01051
01052     try
01053     {
01054         if (_eSourceState == SourceState_Started)
01055         {
01056             DWORD cbTotalLen = 0;
01057             StspStreamDescription streamDesc;
01058             ThrowIfError(pPacket->GetTotalLength(&cbTotalLen));
01059
01060             // Minimum size of the operation payload is size of Description structure
01061             if (cbTotalLen < sizeof(StspStreamDescription))
01062             {
01063                 ThrowIfError(MF_E_UNSUPPORTED_FORMAT);
01064             }
01065
01066             ThrowIfError(pPacket->MoveLeft(sizeof(streamDesc), &streamDesc));
01067
01068             if (cbTotalLen != sizeof(StspStreamDescription) + streamDesc.cbAttributesSize || streamDesc.cbAttributesSize == 0)
01069             {
01070                 ThrowIfError(MF_E_UNSUPPORTED_FORMAT);
01071             }
01072
01073             // Prepare buffer where we will copy attributes to
01074             pAttributes = new(std::nothrow) BYTE[streamDesc.cbAttributesSize];
01075             if (pAttributes == nullptr)
01076             {
01077                 Throw(E_OUTOFMEMORY);
01078             }
01079
01080             ThrowIfError(pPacket->MoveLeft(streamDesc.cbAttributesSize, pAttributes));
01081
01082             ComPtr<IMFMediaType> spMediaType;
01083             // Create a media type object.
01084             ThrowIfError(MFCreateMediaType(&spMediaType));
01085             // Initialize media type's attributes
01086             ThrowIfError(MFInitAttributesFromBlob(spMediaType.Get(), pAttributes, streamDesc.cbAttributesSize));
01087
01088         }
01089         else
01090         {
01091             Throw(MF_E_UNEXPECTED);
01092         }
01093     }
01094     catch(Exception ^exc)
01095     {
01096         error = exc;
01097     }
01098
01099     delete[] pAttributes;
01100
01101     if (error != nullptr)
01102     {
01103         throw error;
01104     }
01105 }
01106
01107 void CMediaSource::InitPresentationDescription()
01108 {
01109     ComPtr<IMFPresentationDescriptor> spPresentationDescriptor;
01110     IMFStreamDescriptor **aStreams = nullptr;
01111
01112     aStreams = new (std::nothrow) IMFStreamDescriptor*[_streams.GetCount()];
01113     if (aStreams == nullptr)
01114     {
01115         Throw(E_OUTOFMEMORY);
01116     }
01117
01118     ZeroMemory(aStreams, sizeof(aStreams[0]) * _streams.GetCount());
01119
01120     StreamContainer::POSITION pos = _streams.FrontPosition();
01121     StreamContainer::POSITION posEnd = _streams.EndPosition();
01122
01123     for (DWORD nStream = 0; pos != posEnd; ++nStream, pos = pos = _streams.Next(pos))
01124     {
01125         ComPtr<IMFMediaStream> spStream;
01126         ThrowIfError(_streams.GetItemPos(pos, &spStream));
01127         ThrowIfError(spStream->GetStreamDescriptor(&aStreams[nStream]));
01128     }
01129
01130     ThrowIfError(MFCreatePresentationDescriptor(_streams.GetCount(), aStreams, &spPresentationDescriptor));
01131
01132     for (DWORD nStream = 0; nStream < _streams.GetCount(); ++nStream)
01133     {
01134         ThrowIfError(spPresentationDescriptor->SelectStream(nStream));
01135     }
01136
01137     _spPresentationDescriptor = spPresentationDescriptor;
01138
01139     if (aStreams != nullptr)
01140     {
01141         for (DWORD nStream = 0; nStream < _streams.GetCount(); ++nStream)
01142         {
01143             if (aStreams[nStream] != nullptr)
01144             {
01145                 aStreams[nStream]->Release();
01146             }
01147         }
01148
01149         delete[] aStreams;
01150     }
01151 }
01152
01153 HRESULT CMediaSource::ValidatePresentationDescriptor(IMFPresentationDescriptor *pPD)
01154 {
01155     HRESULT hr = S_OK;
01156     BOOL fSelected = FALSE;
01157     DWORD cStreams = 0;
01158
01159     if (_streams.GetCount() == 0)
01160     {
01161         return E_UNEXPECTED;
01162     }
01163
01164     // The caller's PD must have the same number of streams as ours.
01165     hr = pPD->GetStreamDescriptorCount(&cStreams);
01166
01167     if (SUCCEEDED(hr))
01168     {
01169         if (cStreams != _streams.GetCount())
01170         {
01171             hr = E_INVALIDARG;
01172         }
01173     }
01174
01175     // The caller must select at least one stream.
01176     if (SUCCEEDED(hr))
01177     {
01178         for (DWORD i = 0; i < cStreams; i++)
01179         {
01180             ComPtr<IMFStreamDescriptor> spSD;
01181             hr = pPD->GetStreamDescriptorByIndex(i, &fSelected, &spSD);
01182             if (FAILED(hr))
01183             {
01184                 break;
01185             }
01186         }
01187     }
01188
01189     TRACEHR_RET(hr);
01190 }
01191
01192 void CMediaSource::SelectStreams(IMFPresentationDescriptor *pPD)
01193 {
01194     for (DWORD nStream = 0; nStream < _streams.GetCount(); ++nStream)
01195     {
01196         ComPtr<IMFStreamDescriptor> spSD;
01197         ComPtr<CMediaStream> spStream;
01198         DWORD nStreamId;
01199         BOOL fSelected;
01200
01201         // Get next stream descriptor
01202         ThrowIfError(pPD->GetStreamDescriptorByIndex(nStream, &fSelected, &spSD));
01203
01204         // Get stream id
01205         ThrowIfError(spSD->GetStreamIdentifier(&nStreamId));
01206
01207         // Get simple net media stream
01208         ThrowIfError(GetStreamById(nStreamId, &spStream));
01209
01210         // Remember if stream was selected
01211         bool fWasSelected = spStream->IsActive();
01212         ThrowIfError(spStream->SetActive(!!fSelected));
01213
01214         if (fSelected)
01215         {
01216             // Choose event type to send
01217             MediaEventType met = (fWasSelected) ? MEUpdatedStream : MENewStream;
01218             ComPtr<IUnknown> spStreamUnk;
01219
01220             spStream.As(&spStreamUnk);
01221
01222             ThrowIfError(_spEventQueue->QueueEventParamUnk(met, GUID_NULL, S_OK, spStreamUnk.Get()));
01223
01224             // Start the stream. The stream will send the appropriate event.
01225             ThrowIfError(spStream->Start());
01226         }
01227     }
01228 }
01229
01230 void CMediaSource::DoStart(CStartOperation *pOp)
01231 {
01232     assert(pOp->GetOperationType() == CSourceOperation::Operation_Start);
01233     ComPtr<IMFPresentationDescriptor> spPD = pOp->GetPresentationDescriptor();
01234
01235     try
01236     {
01237         SelectStreams(spPD.Get());
01238
01239         _eSourceState = SourceState_Starting;
01240         SendStartRequest();
01241
01242         _eSourceState = SourceState_Started;
01243         ThrowIfError(_spEventQueue->QueueEventParamVar(MESourceStarted, GUID_NULL, S_OK, &pOp->GetData()));
01244     }
01245     catch(Exception ^exc)
01246     {
01247         _spEventQueue->QueueEventParamVar(MESourceStarted, GUID_NULL, exc->HResult, nullptr);
01248     }
01249 }
01250
01251 void CMediaSource::DoStop(CSourceOperation *pOp)
01252 {
01253     assert(pOp->GetOperationType() == CSourceOperation::Operation_Stop);
01254
01255     HRESULT hr = S_OK;
01256     try
01257     {
01258         StreamContainer::POSITION pos = _streams.FrontPosition();
01259         StreamContainer::POSITION posEnd = _streams.EndPosition();
01260
01261         for (; pos != posEnd; pos = _streams.Next(pos))
01262         {
01263             ComPtr<IMFMediaStream> spStream;
01264             ThrowIfError(_streams.GetItemPos(pos, &spStream));
01265             CMediaStream *pStream = static_cast<CMediaStream*>(spStream.Get());
01266             if (pStream->IsActive())
01267             {
01268                 ThrowIfError(pStream->Flush());
01269                 ThrowIfError(pStream->Stop());
01270             }
01271         }
01272     }
01273     catch(Exception ^exc)
01274     {
01275         hr = exc->HResult;
01276     }
01277     // Send the "stopped" event. This might include a failure code.
01278     (void)_spEventQueue->QueueEventParamVar(MESourceStopped, GUID_NULL, hr, nullptr);
01279 }
01280
01281 void CMediaSource::DoSetRate(CSetRateOperation *pOp)
01282 {
01283     assert(pOp->GetOperationType() == CSourceOperation::Operation_SetRate);
01284
01285     HRESULT hr = S_OK;
01286     try
01287     {
01288         StreamContainer::POSITION pos = _streams.FrontPosition();
01289         StreamContainer::POSITION posEnd = _streams.EndPosition();
01290
01291         for (; pos != posEnd; pos = _streams.Next(pos))
01292         {
01293             ComPtr<IMFMediaStream> spStream;
01294             ThrowIfError(_streams.GetItemPos(pos, &spStream));
01295
01296             CMediaStream *pStream = static_cast<CMediaStream*>(spStream.Get());
01297
01298             if (pStream->IsActive())
01299             {
01300                 ThrowIfError(pStream->Flush());
01301                 ThrowIfError(pStream->SetRate(pOp->GetRate()));
01302             }
01303         }
01304
01305         _flRate = pOp->GetRate();
01306     }
01307     catch(Exception ^exc)
01308     {
01309         hr = exc->HResult;
01310     }
01311     // Send the "rate changed" event. This might include a failure code.
01312     (void)_spEventQueue->QueueEventParamVar(MESourceRateChanged, GUID_NULL, hr, nullptr);
01313 }
01314
01315 bool CMediaSource::IsRateSupported(float flRate, float *pflAdjustedRate)
01316 {
01317     if (flRate < 0.00001f && flRate > -0.00001f)
01318     {
01319         *pflAdjustedRate = 0.0f;
01320         return true;
01321     }
01322     else if(flRate < 1.0001f && flRate > 0.9999f)
01323     {
01324         *pflAdjustedRate = 1.0f;
01325         return true;
01326     }
01327     return false;
01328 }
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLInProcessWinRTComponent/cpp/cpp/pch.h Source File

  • WRLInProcessWinRTComponent
  • cpp
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <wrl\event.h>
00008 #include <wrl\implements.h>
00009 #include <wrl\wrappers\corewrappers.h>
00010 #include <collection.h>
00011 #include <ppltasks.h>
00012
00013 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraManualControls/cs/MainPage.Zoom.xaml.cs Source File

  • CameraManualControls
  • cs

MainPage.Zoom.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017 using Windows.Media.Devices;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020
00021 namespace CameraManualControls
00022 {
00023     public sealed partial class MainPage : Page
00024     {
00025
00026         private void UpdateZoomControlCapabilities()
00027         {
00028             var zoomControl = _mediaCapture.VideoDeviceController.ZoomControl;
00029
00030             if (zoomControl.Supported)
00031             {
00032                 ZoomButton.Tag = Visibility.Visible;
00033
00034                 // Unhook the event handler, so that changing properties on the slider won't trigger an API call
00035                 ZoomSlider.ValueChanged -= ZoomSlider_ValueChanged;
00036
00037                 var value = zoomControl.Value;
00038                 ZoomSlider.Minimum = zoomControl.Min;
00039                 ZoomSlider.Maximum = zoomControl.Max;
00040                 ZoomSlider.StepFrequency = zoomControl.Step;
00041                 ZoomSlider.Value = value;
00042
00043                 ZoomSlider.ValueChanged += ZoomSlider_ValueChanged;
00044             }
00045             else
00046             {
00047                 ZoomButton.Visibility = Visibility.Collapsed;
00048                 ZoomButton.Tag = Visibility.Collapsed;
00049             }
00050         }
00051
00052         private void ZoomSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e)
00053         {
00054             if (_settingUpUi) return;
00055
00056             SetZoomLevel((float)ZoomSlider.Value);
00057         }
00058
00059         private void SetZoomLevel(float level)
00060         {
00061             var zoomControl = _mediaCapture.VideoDeviceController.ZoomControl;
00062
00063             // Make sure zoomFactor is within the valid range
00064             level = Math.Max(Math.Min(level, zoomControl.Max), zoomControl.Min);
00065
00066             // Make sure zoomFactor is a multiple of Step, snap to the next lower step
00067             level -= (level % zoomControl.Step);
00068
00069             var settings = new ZoomSettings { Value = level };
00070
00071             if (zoomControl.SupportedModes.Contains(ZoomTransitionMode.Smooth))
00072             {
00073                 // Favor smooth zoom for this sample
00074                 settings.Mode = ZoomTransitionMode.Smooth;
00075             }
00076             else
00077             {
00078                 settings.Mode = zoomControl.SupportedModes.First();
00079             }
00080
00081             zoomControl.Configure(settings);
00082         }
00083
00084     }
00085 }
Generated on Fri Nov 15 2024 22:18:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/ToneSampleGenerator.cpp Source File

  • WindowsAudioSession
  • cppwinrt

ToneSampleGenerator.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
00012 #include "ToneSampleGenerator.h"
00013
00014 namespace winrt::SDKTemplate
00015 {
00016     static constexpr int TONE_DURATION_SEC = 30;
00017     static constexpr double TONE_AMPLITUDE = 0.5;     // Scalar value, should be between 0.0 - 1.0
00018
00019     //
00020     //  GenerateSampleBuffer()
00021     //
00022     //  Create a linked list of sample buffers
00023     //
00024     void ToneSampleGenerator::GenerateSampleBuffer(double Frequency, UINT32 FramesPerPeriod, WAVEFORMATEX* wfx)
00025     {
00026         uint32_t renderBufferSizeInBytes = FramesPerPeriod * wfx->nBlockAlign;
00027         uint64_t renderDataLength = (wfx->nSamplesPerSec * TONE_DURATION_SEC * wfx->nBlockAlign) + (renderBufferSizeInBytes - 1);
00028         uint64_t renderBufferCount = renderDataLength / renderBufferSizeInBytes;
00029
00030         SineSampleInfo info;
00031         info.Frequency = Frequency;
00032         info.ChannelCount = wfx->nChannels;
00033         info.SamplesPerSecond = wfx->nSamplesPerSec;
00034         info.Amplitude = TONE_AMPLITUDE;
00035         info.Theta = 0; // Updated by GenerateSamples to remember where to resume
00036
00037         switch (GetRenderSampleType(wfx))
00038         {
00039         case RenderSampleType::Pcm16Bit:
00040             info.SampleSize = sizeof(int16_t);
00041             info.StoreSample = [](uint8_t* buffer, double value) { *reinterpret_cast<int16_t*>(buffer) = static_cast<int16_t>(value * (std::numeric_limits<int16_t>::max)()); };
00042             break;
00043
00044         case RenderSampleType::Pcm24In32Bit:
00045             info.SampleSize = sizeof(int32_t);
00046             // Scale to a 24-bit integer, stored in the upper 24 bits of the 32-bit sample.
00047             info.StoreSample = [](uint8_t* buffer, double value) { *reinterpret_cast<int32_t*>(buffer) = static_cast<int32_t>(value * ((1 << 23) - 1)) << 8; };
00048             break;
00049
00050         case RenderSampleType::Float:
00051             info.SampleSize = sizeof(float);
00052             info.StoreSample = [](uint8_t* buffer, double value) { *reinterpret_cast<float*>(buffer) = static_cast<float>(value); };
00053             break;
00054
00055         default:
00056             throw hresult_error(E_UNEXPECTED);
00057         }
00058
00059         std::forward_list<RenderBuffer>::iterator sampleQueueTail = m_sampleQueue.before_begin();
00060         for (uint64_t i = 0; i < renderBufferCount; i++)
00061         {
00062             sampleQueueTail = m_sampleQueue.emplace_after(sampleQueueTail, renderBufferSizeInBytes);
00063             RenderBuffer& sampleBuffer = *sampleQueueTail;
00064             info.GenerateSamples({ sampleBuffer.Buffer.get(), sampleBuffer.BufferSize });
00065         }
00066     }
00067
00068     //
00069     // GenerateSamples()
00070     //
00071     //  Generate samples which represent a sine wave that fits into the specified buffer.
00072     //  The wave begins at the Theta value stored in the SineSampleInfo, and on exit the
00073     //  value is updated to the first Theta value for the next buffer.
00074     //
00075     //  Buffer - Buffer to hold the samples
00076     //  BufferLength - Length of the buffer.
00077
00078     void ToneSampleGenerator::SineSampleInfo::GenerateSamples(array_view<uint8_t> buffer) noexcept
00079     {
00080         // Each sample represents (Frequency * 2 * M_PI / SamplesPerSecond) radians.
00081         // To avoid accumulated rounding errors, we track the cumulative Frequency.
00082         // To avoid loss of significance, we take the value mod SamplesPerSecond.
00083         size_t frames = buffer.size() / SampleSize / ChannelCount;
00084         uint8_t* next = buffer.data();
00085         for (size_t frame = 0; frame < frames; frame++)
00086         {
00087             double sinValue = Amplitude * sin(Theta * M_PI * 2 / SamplesPerSecond);
00088             for (size_t channel = 0; channel < ChannelCount; channel++)
00089             {
00090                 StoreSample(next, sinValue);
00091                 next += SampleSize;
00092             }
00093             Theta += Frequency;
00094             if (Theta > SamplesPerSecond)
00095             {
00096                 Theta = Theta - SamplesPerSecond;
00097             }
00098         }
00099     }
00100
00101     //
00102     //  FillSampleBuffer()
00103     //
00104     //  File the buffer of size bytesToRead with the first item in the queue.  Caller is responsible for allocating and freeing the buffer.
00105     //
00106     void ToneSampleGenerator::FillSampleBuffer(array_view<uint8_t> buffer)
00107     {
00108         RenderBuffer& sampleBuffer = m_sampleQueue.front();
00109
00110         if (buffer.size() > sampleBuffer.BufferSize)
00111         {
00112             throw hresult_invalid_argument();
00113         }
00114
00115         CopyMemory(buffer.data(), sampleBuffer.Buffer.get(), buffer.size());
00116
00117         m_sampleQueue.pop_front();
00118     }
00119 }
Generated on Fri Nov 15 2024 22:22:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AudioCategory/cs/AudioCategory/Scenario6.xaml.cs Source File

  • AudioCategory
  • cs
  • AudioCategory

Scenario6.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016 using Windows.UI.Xaml.Media;
00017
00018 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00019
00020 namespace PlaybackManager
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class Scenario6 : Page
00026     {
00027         public Scenario6()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         private void Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00033         {
00034             Playback.SetAudioCategory(AudioCategory.Alerts);
00035             Playback.SelectFile();
00036         }
00037     }
00038 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cs/Utils.cs Source File

  • WiFiDirect
  • cs

Utils.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Devices.Enumeration;
00015 using Windows.Foundation;
00016 using Windows.UI.Core;
00017 using Windows.UI.Popups;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020
00021 namespace SDKTemplate
00022 {
00023     public static class Globals
00024     {
00025         // WARNING! This custom OUI is for demonstration purposes only.
00026         // OUI values are assigned by the IEEE Registration Authority.
00027         // Replace this custom OUI with the value assigned to your organization.
00028         public static readonly byte[] CustomOui = { 0xAA, 0xBB, 0xCC };
00029         public static readonly byte CustomOuiType = 0xDD;
00030
00031         // OUI assigned to the Wi-Fi Alliance.
00032         public static readonly byte[] WfaOui = { 0x50, 0x6F, 0x9A };
00033
00034         // OUI assigned to Microsoft Corporation.
00035         public static readonly byte[] MsftOui = { 0x00, 0x50, 0xF2 };
00036
00037         public static readonly string strServerPort = "50001";
00038         public static readonly int iAdvertisementStartTimeout = 5000; // in ms
00039     }
00040
00041     public static class Utils
00042     {
00043         private static async Task ShowPinToUserAsync(CoreDispatcher dispatcher, string strPin)
00044         {
00045             await dispatcher.RunTaskAsync(async () =>
00046             {
00047                 var messageDialog = new MessageDialog($"Enter this PIN on the remote device: {strPin}");
00048
00049                 // Add commands
00050                 messageDialog.Commands.Add(new UICommand("OK", null, 0));
00051
00052                 // Set the command that will be invoked by default
00053                 messageDialog.DefaultCommandIndex = 0;
00054
00055                 // Set the command that will be invoked if the user cancels
00056                 messageDialog.CancelCommandIndex = 0;
00057
00058                 // Show the Pin
00059                 await messageDialog.ShowAsync();
00060             });
00061         }
00062
00063         private static async Task<string> GetPinFromUserAsync(CoreDispatcher dispatcher)
00064         {
00065             return await dispatcher.RunTaskAsync(async () =>
00066             {
00067                 var pinBox = new TextBox();
00068                 var dialog = new ContentDialog()
00069                 {
00070                     Title = "Enter Pin",
00071                     PrimaryButtonText = "OK",
00072                     Content = pinBox
00073                 };
00074                 await dialog.ShowAsync();
00075                 return pinBox.Text;
00076             });
00077         }
00078
00079         public static async void HandlePairing(CoreDispatcher dispatcher, DevicePairingRequestedEventArgs args)
00080         {
00081             using (Deferral deferral = args.GetDeferral())
00082             {
00083                 switch (args.PairingKind)
00084                 {
00085                     case DevicePairingKinds.DisplayPin:
00086                         await ShowPinToUserAsync(dispatcher, args.Pin);
00087                         args.Accept();
00088                         break;
00089
00090                     case DevicePairingKinds.ConfirmOnly:
00091                         args.Accept();
00092                         break;
00093
00094                     case DevicePairingKinds.ProvidePin:
00095                         {
00096                             string pin = await GetPinFromUserAsync(dispatcher);
00097                             if (!String.IsNullOrEmpty(pin))
00098                             {
00099                                 args.Accept(pin);
00100                             }
00101                         }
00102                         break;
00103                 }
00104             }
00105         }
00106
00107         // Helper function to take the selected item in a combo box
00108         // and return its tag, which is assumed to be of type T.
00109         static public T GetSelectedItemTag<T>(ComboBox comboBox)
00110         {
00111             var element = (FrameworkElement)comboBox.SelectedItem;
00112             return (T)element.Tag;
00113         }
00114
00115         // Function binding target for the "Send" button on a text box.
00116         static public bool CanSendMessage(string message, object connectedDevice)
00117         {
00118             return !String.IsNullOrEmpty(message) && connectedDevice != null;
00119         }
00120
00121         // General-purpose function binding targets.
00122         static public bool IsNonNull(object o)
00123         {
00124             return o != null;
00125         }
00126
00127         static public bool IsNonEmptyString(string value)
00128         {
00129             return !String.IsNullOrEmpty(value);
00130         }
00131     }
00132 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cpp/Scenario1_TrialMode.xaml.h Source File

  • Store
  • cpp

Scenario1_TrialMode.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario1_TrialMode.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class Scenario1_TrialMode sealed
00022     {
00023     public:
00024         Scenario1_TrialMode();
00025         void ShowTrialPeriodInformation();
00026         void PurchaseFullLicense();
00027
00028     protected:
00029         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030         virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00031     private:
00032         MainPage^ rootPage = MainPage::Current;
00033         Windows::Services::Store::StoreContext^ storeContext;
00034         Windows::Foundation::EventRegistrationToken eventRegistrationToken;
00035
00036         void OfflineLicensesChanged(Windows::Services::Store::StoreContext^ sender, Platform::Object^ args);
00037         void GetLicenseState();
00038     };
00039 }
00040
Generated on Fri Nov 15 2024 22:21:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_ShowHideMethods Member List

This is the complete list of members for Scenario3_ShowHideMethods, including all inherited members.
OnFadeOutCompleted(object sender, object e) | Scenario3_ShowHideMethods | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario3_ShowHideMethods | [inline, protected]
Scenario3_ShowHideMethods() | Scenario3_ShowHideMethods | [inline]
WordListBox_OnKeyUp(object sender, KeyRoutedEventArgs e) | Scenario3_ShowHideMethods | [inline, private]
Generated on Fri Nov 15 2024 22:23:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cpp/Scenario1_GetAndSetPin.xaml.cpp Source File

  • IoT-GPIO
  • cpp

Scenario1_GetAndSetPin.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_GetAndSetPin.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Windows::Devices::Gpio;
00018 using namespace Windows::UI::Xaml;
00019 using namespace Windows::UI::Xaml::Navigation;
00020
00021 Scenario1_GetAndSetPin::Scenario1_GetAndSetPin()
00022 {
00023     InitializeComponent();
00024 }
00025
00026 void Scenario1_GetAndSetPin::OnNavigatedFrom(NavigationEventArgs ^e)
00027 {
00028     StopScenario();
00029 }
00030
00031 void Scenario1_GetAndSetPin::StartScenario()
00032 {
00033     auto gpio = GpioController::GetDefault();
00034
00035     // Set up our GPIO pin for setting values.
00036     // If this next line crashes with an Access Violation reading 0x00000000,
00037     // then the problem is that there is no GPIO controller on the device.
00038     pin = gpio->OpenPin(LED_PIN);
00039
00040     // Configure pin for output.
00041     pin->SetDriveMode(GpioPinDriveMode::Output);
00042 }
00043
00044 void Scenario1_GetAndSetPin::StopScenario()
00045 {
00046     // Release the GPIO pin.
00047     delete pin;
00048     pin = nullptr;
00049 }
00050
00051 void Scenario1_GetAndSetPin::StartStopScenario_Click(Object^ sender, RoutedEventArgs^ e)
00052 {
00053     if (pin != nullptr)
00054     {
00055         StopScenario();
00056         StartStopButton->Content = "Start";
00057         ScenarioControls->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00058     }
00059     else
00060     {
00061         StartScenario();
00062         StartStopButton->Content = "Stop";
00063         ScenarioControls->Visibility = Windows::UI::Xaml::Visibility::Visible;
00064     }
00065 }
00066
00067 void Scenario1_GetAndSetPin::SetPinHigh_Click(Object^ sender, RoutedEventArgs^ e)
00068 {
00069     // Set the GPIO pin to High.
00070     pin->Write(GpioPinValue::High);
00071 }
00072
00073 void Scenario1_GetAndSetPin::SetPinLow_Click(Object^ sender, RoutedEventArgs^ e)
00074 {
00075     // Set the GPIO pin to Low.
00076     pin->Write(GpioPinValue::Low);
00077 }
00078
00079 void Scenario1_GetAndSetPin::GetPinValue_Click(Object^ sender, RoutedEventArgs^ e)
00080 {
00081     // Change the GUI to reflect the current pin value.
00082     CurrentPinValue->Text = pin->Read().ToString();
00083 }
00084
00085
Generated on Fri Nov 15 2024 22:20:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OCR/cs/WordOverlay.cs Source File

  • OCR
  • cs

WordOverlay.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.ComponentModel;
00013 using Windows.Foundation;
00014 using Windows.Media.Ocr;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Data;
00018 using Windows.UI.Xaml.Media;
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// Wraps recognized word and provides word overlay position and size based on current scale.
00024     /// </summary>
00025     class WordOverlay : INotifyPropertyChanged
00026     {
00027         private OcrWord word;
00028         private Rect wordBoundingRect;
00029
00030         /// <summary>
00031         /// Left and Right properties of Thickess define word box position.
00032         /// </summary>
00033         public Thickness WordPosition => new Thickness(wordBoundingRect.Left, wordBoundingRect.Top, 0, 0);
00034
00035         /// <summary>
00036         /// Scaled word box width.
00037         /// </summary>
00038         public double WordWidth => wordBoundingRect.Width;
00039
00040         /// <summary>
00041         /// Scaled word box height.
00042         /// </summary>
00043         public double WordHeight => wordBoundingRect.Height;
00044
00045         public event PropertyChangedEventHandler PropertyChanged;
00046
00047         public WordOverlay(OcrWord ocrWord)
00048         {
00049             word = ocrWord;
00050
00051             UpdateProps(word.BoundingRect);
00052         }
00053
00054         public void Transform(ScaleTransform scale)
00055         {
00056             // Scale word box bounding rect and update properties.
00057             UpdateProps(scale.TransformBounds(word.BoundingRect));
00058         }
00059
00060         public Border CreateBorder(Style style, UIElement child = null)
00061         {
00062             var overlay = new Border()
00063             {
00064                 Child = child,
00065                 Style = style
00066             };
00067
00068             // Bind word boxes to UI.
00069             overlay.SetBinding(FrameworkElement.MarginProperty, CreateBinding("WordPosition"));
00070             overlay.SetBinding(FrameworkElement.WidthProperty, CreateBinding("WordWidth"));
00071             overlay.SetBinding(FrameworkElement.HeightProperty, CreateBinding("WordHeight"));
00072
00073             return overlay;
00074         }
00075
00076         Binding CreateBinding(string propertyName) => new Binding() { Path = new PropertyPath(propertyName), Source = this };
00077
00078         private void UpdateProps(Rect wordBoundingBox)
00079         {
00080             wordBoundingRect = wordBoundingBox;
00081
00082             OnPropertyChanged("WordPosition");
00083             OnPropertyChanged("WordWidth");
00084             OnPropertyChanged("WordHeight");
00085         }
00086
00087         protected void OnPropertyChanged(string PropertyName)
00088         {
00089             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
00090         }
00091     }
00092 }
Generated on Fri Nov 15 2024 22:20:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

InputReportEvents Member List

This is the complete list of members for InputReportEvents, including all inherited members.
inputReportEventHandler | InputReportEvents | [private]
InputReportEvents() | InputReportEvents | [inline]
isRegisteredForInputReportEvents | InputReportEvents | [private]
navigatedAway | InputReportEvents | [private]
numInputReportEventsReceived | InputReportEvents | [private]
OnDeviceClosing(EventHandlerForDevice sender, DeviceInformation deviceInformation) | InputReportEvents | [inline, private]
OnInputReportEvent(HidDevice sender, HidInputReportReceivedEventArgs eventArgs) | InputReportEvents | [inline, private]
OnNavigatedFrom(NavigationEventArgs eventArgs) | InputReportEvents | [inline, protected]
OnNavigatedTo(NavigationEventArgs eventArgs) | InputReportEvents | [inline, protected]
registeredDevice | InputReportEvents | [private]
RegisterForInputReportEvents() | InputReportEvents | [inline, private]
RegisterForInputReportEvents_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs eventArgs) | InputReportEvents | [inline, private]
rootPage | InputReportEvents | [private]
StartSuperMuttInputReports() | InputReportEvents | [inline, private]
StopSuperMuttInputReports() | InputReportEvents | [inline, private]
totalNumberBytesReceived | InputReportEvents | [private]
UnregisterFromInputReportEvent() | InputReportEvents | [inline, private]
UnregisterFromInputReportEvents_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs eventArgs) | InputReportEvents | [inline, private]
UpdateRegisterEventButtons() | InputReportEvents | [inline, private]
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario1WinRTComponent/SecureInterfaceServiceEventArgs.cpp Source File

  • AllJoyn
  • Common
  • Scenario1WinRTComponent

SecureInterfaceServiceEventArgs.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #include "pch.h"
00022
00023 using namespace concurrency;
00024 using namespace Microsoft::WRL;
00025 using namespace Platform;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Foundation::Collections;
00028 using namespace Windows::Devices::AllJoyn;
00029 using namespace com::microsoft::Samples::SecureInterface;
00030 namespace com { namespace microsoft { namespace Samples { namespace SecureInterface {
00031
00032 // Methods
00033 SecureInterfaceConcatenateCalledEventArgs::SecureInterfaceConcatenateCalledEventArgs(
00034     _In_ AllJoynMessageInfo^ info,
00035     _In_ Platform::String^ interfaceMemberInStr1,
00036     _In_ Platform::String^ interfaceMemberInStr2)
00037     : m_raised(false),
00038     m_completionsRequired(0),
00039     m_messageInfo(info),
00040     m_interfaceMemberInStr1(interfaceMemberInStr1),
00041     m_interfaceMemberInStr2(interfaceMemberInStr2)
00042 {
00043     m_result = SecureInterfaceConcatenateResult::CreateFailureResult(ER_NOT_IMPLEMENTED);
00044 }
00045
00046 Deferral^ SecureInterfaceConcatenateCalledEventArgs::GetDeferral()
00047 {
00048     std::lock_guard<std::mutex> lockGuard(m_lock);
00049     if (m_raised)
00050     {
00051         // Cannot ask for a deferral after the event handler has returned.
00052         throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00053     }
00054
00055     m_completionsRequired++;
00056     auto handler = ref new DeferralCompletedHandler(this, &SecureInterfaceConcatenateCalledEventArgs::Complete);
00057     return ref new Deferral(handler);
00058 }
00059
00060 void SecureInterfaceConcatenateCalledEventArgs::InvokeAllFinished()
00061 {
00062     bool invokeNeeded;
00063
00064     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00065     {
00066         std::lock_guard<std::mutex> lockGuard(m_lock);
00067         m_raised = true;
00068         invokeNeeded = (m_completionsRequired == 0);
00069     }
00070
00071     if (invokeNeeded)
00072     {
00073         InvokeCompleteHandler();
00074     }
00075 }
00076
00077 void SecureInterfaceConcatenateCalledEventArgs::Complete()
00078 {
00079     bool invokeNeeded;
00080
00081     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00082     {
00083         std::lock_guard<std::mutex> lockGuard(m_lock);
00084         if (m_completionsRequired == 0)
00085         {
00086             // This should never happen since Complete() should only be called by Windows.Foundation.Deferral
00087             // which will only invoke our completion handler once.
00088             throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00089         }
00090         m_completionsRequired--;
00091         invokeNeeded = (m_raised && (m_completionsRequired == 0));
00092     }
00093
00094     if (invokeNeeded)
00095     {
00096         InvokeCompleteHandler();
00097     }
00098 }
00099
00100 void SecureInterfaceConcatenateCalledEventArgs::InvokeCompleteHandler()
00101 {
00102     if (m_result->Status == ER_NOT_IMPLEMENTED)
00103     {
00104         throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for ConcatenateCalled.");
00105     }
00106     else
00107     {
00108         m_tce.set(m_result);
00109     }
00110 }
00111
00112 // Readable Properties
00113 SecureInterfaceGetIsUpperCaseEnabledRequestedEventArgs::SecureInterfaceGetIsUpperCaseEnabledRequestedEventArgs(
00114     _In_ AllJoynMessageInfo^ info)
00115     : m_raised(false),
00116     m_completionsRequired(0),
00117     m_messageInfo(info)
00118 {
00119     m_result = SecureInterfaceGetIsUpperCaseEnabledResult::CreateFailureResult(ER_NOT_IMPLEMENTED);
00120 }
00121
00122 Deferral^ SecureInterfaceGetIsUpperCaseEnabledRequestedEventArgs::GetDeferral()
00123 {
00124     std::lock_guard<std::mutex> lockGuard(m_lock);
00125     if (m_raised)
00126     {
00127         // Cannot ask for a deferral after the event handler has returned.
00128         throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00129     }
00130
00131     m_completionsRequired++;
00132     auto handler = ref new DeferralCompletedHandler(this, &SecureInterfaceGetIsUpperCaseEnabledRequestedEventArgs::Complete);
00133     return ref new Deferral(handler);
00134 }
00135
00136 void SecureInterfaceGetIsUpperCaseEnabledRequestedEventArgs::InvokeAllFinished()
00137 {
00138     bool invokeNeeded;
00139
00140     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00141     {
00142         std::lock_guard<std::mutex> lockGuard(m_lock);
00143         m_raised = true;
00144         invokeNeeded = (m_completionsRequired == 0);
00145     }
00146
00147     if (invokeNeeded)
00148     {
00149         InvokeCompleteHandler();
00150     }
00151 }
00152
00153 void SecureInterfaceGetIsUpperCaseEnabledRequestedEventArgs::Complete()
00154 {
00155     bool invokeNeeded;
00156
00157     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00158     {
00159         std::lock_guard<std::mutex> lockGuard(m_lock);
00160         if (m_completionsRequired == 0)
00161         {
00162             // This should never happen since Complete() should only be called by Windows.Foundation.Deferral
00163             // which will only invoke our completion handler once.
00164             throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00165         }
00166         m_completionsRequired--;
00167         invokeNeeded = (m_raised && (m_completionsRequired == 0));
00168     }
00169
00170     if (invokeNeeded)
00171     {
00172         InvokeCompleteHandler();
00173     }
00174 }
00175
00176 void SecureInterfaceGetIsUpperCaseEnabledRequestedEventArgs::InvokeCompleteHandler()
00177 {
00178     if (m_result->Status == ER_NOT_IMPLEMENTED)
00179     {
00180         throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for GetIsUpperCaseEnabledRequested.");
00181     }
00182     else
00183     {
00184         m_tce.set(m_result);
00185     }
00186 }
00187
00188 // Writable Properties
00189 SecureInterfaceSetIsUpperCaseEnabledRequestedEventArgs::SecureInterfaceSetIsUpperCaseEnabledRequestedEventArgs(
00190     _In_ AllJoynMessageInfo^ info,
00191     _In_ bool value)
00192     : m_raised(false),
00193     m_completionsRequired(0),
00194     m_messageInfo(info),
00195     m_value(value)
00196 {
00197     m_result = SecureInterfaceSetIsUpperCaseEnabledResult::CreateFailureResult(ER_NOT_IMPLEMENTED);
00198 }
00199
00200 Deferral^ SecureInterfaceSetIsUpperCaseEnabledRequestedEventArgs::GetDeferral()
00201 {
00202     std::lock_guard<std::mutex> lockGuard(m_lock);
00203     if (m_raised)
00204     {
00205         // Cannot ask for a deferral after the event handler has returned.
00206         throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00207     }
00208
00209     m_completionsRequired++;
00210     auto handler = ref new DeferralCompletedHandler(this, &SecureInterfaceSetIsUpperCaseEnabledRequestedEventArgs::Complete);
00211     return ref new Deferral(handler);
00212 }
00213
00214 void SecureInterfaceSetIsUpperCaseEnabledRequestedEventArgs::InvokeAllFinished()
00215 {
00216     bool invokeNeeded;
00217
00218     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00219     {
00220         std::lock_guard<std::mutex> lockGuard(m_lock);
00221         m_raised = true;
00222         invokeNeeded = (m_completionsRequired == 0);
00223     }
00224
00225     if (invokeNeeded)
00226     {
00227         InvokeCompleteHandler();
00228     }
00229 }
00230
00231 void SecureInterfaceSetIsUpperCaseEnabledRequestedEventArgs::Complete()
00232 {
00233     bool invokeNeeded;
00234
00235     // We need to hold a lock while modifying private state, but release it before invoking a completion handler.
00236     {
00237         std::lock_guard<std::mutex> lockGuard(m_lock);
00238         if (m_completionsRequired == 0)
00239         {
00240             // This should never happen since Complete() should only be called by Windows.Foundation.Deferral
00241             // which will only invoke our completion handler once.
00242             throw Exception::CreateException(E_ILLEGAL_METHOD_CALL);
00243         }
00244         m_completionsRequired--;
00245         invokeNeeded = (m_raised && (m_completionsRequired == 0));
00246     }
00247
00248     if (invokeNeeded)
00249     {
00250         InvokeCompleteHandler();
00251     }
00252 }
00253
00254 void SecureInterfaceSetIsUpperCaseEnabledRequestedEventArgs::InvokeCompleteHandler()
00255 {
00256     if (m_result->Status == ER_NOT_IMPLEMENTED)
00257     {
00258         throw Exception::CreateException(E_NOTIMPL, "No handlers are registered for SetIsUpperCaseEnabledRequested.");
00259     }
00260     else
00261     {
00262         m_tce.set(m_result);
00263     }
00264 }
00265
00266 } } } }
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/Scenario4.xaml.h Source File

  • WindowsAudioSession
  • cpp

Scenario4.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario4.xaml.h
00013 // Declaration of the Scenario4 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario4.g.h"
00020 #include "MainPage.xaml.h"
00021 #include "WASAPICapture.h"
00022
00023 #define OSC_START_X  100
00024 #define OSC_START_Y  100
00025 #define OSC_X_LENGTH 700
00026 #define OSC_TOTAL_HEIGHT 200
00027
00028 namespace SDKSample
00029 {
00030     namespace WASAPIAudio
00031     {
00032         [Windows::Foundation::Metadata::WebHostHidden]
00033         public ref class Scenario4 sealed
00034         {
00035
00036         public:
00037             Scenario4();
00038
00039         protected:
00040             // Template Support
00041             virtual void OnNavigatedTo( Windows::UI::Xaml::Navigation::NavigationEventArgs^ e ) override;
00042             virtual void OnNavigatedFrom( Windows::UI::Xaml::Navigation::NavigationEventArgs^ e ) override;
00043
00044         private:
00045             ~Scenario4();
00046
00047             // UI Events
00048             void btnStartCapture_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049             void btnStopCapture_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050
00051             // UI Helpers
00052             void ShowStatusMessage( Platform::String^ str, NotifyType messageType );
00053             void UpdateMediaControlUI( DeviceState deviceState );
00054
00055             // Handlers
00056             void OnDeviceStateChange( Object^ sender, DeviceStateChangedEventArgs^ e );
00057             void OnPlotDataReady( Object^ sender, PlotDataReadyEventArgs^ e );
00058
00059             void InitializeCapture( Object^ sender, Object^ e );
00060             void StopCapture( Object^ sender, Object^ e );
00061
00062         private:
00063             MainPage^                                       rootPage;
00064             Windows::UI::Core::CoreDispatcher^              m_CoreDispatcher;
00065             Windows::UI::Xaml::Shapes::Polyline^            m_Oscilloscope;
00066
00067             Windows::Foundation::EventRegistrationToken     m_deviceStateChangeToken;
00068             Windows::Foundation::EventRegistrationToken     m_plotDataReadyToken;
00069
00070             int                         m_DiscontinuityCount;
00071             Platform::Boolean           m_IsMFLoaded;
00072             Platform::Boolean           m_IsLowLatency;
00073             DeviceStateChangedEvent^    m_StateChangedEvent;
00074             ComPtr<WASAPICapture>       m_spCapture;
00075         };
00076     }
00077 }
Generated on Fri Nov 15 2024 22:18:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cs/Scenario5_ApplicationTriggerTask.xaml.cs Source File

  • BackgroundActivation
  • cs

Scenario5_ApplicationTriggerTask.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using SDKTemplate;
00014 using Windows.ApplicationModel.Background;
00015 using Windows.Storage;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class ApplicationTriggerTask : Page
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         MainPage rootPage = MainPage.Current;
00033
00034         // A pointer to the ApplicationTrigger so we can signal it later
00035         ApplicationTrigger trigger = null;
00036
00037         public ApplicationTriggerTask()
00038         {
00039             this.InitializeComponent();
00040         }
00041
00042         /// <summary>
00043         /// Invoked when this page is about to be displayed in a Frame.
00044         /// </summary>
00045         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00046         /// property is typically used to configure the page.</param>
00047         protected override void OnNavigatedTo(NavigationEventArgs e)
00048         {
00049             foreach (var task in BackgroundTaskRegistration.AllTasks)
00050             {
00051                 if (task.Value.Name == BackgroundTaskSample.ApplicationTriggerTaskName)
00052                 {
00053                     AttachProgressAndCompletedHandlers(task.Value);
00054                     BackgroundTaskSample.UpdateBackgroundTaskRegistrationStatus(BackgroundTaskSample.ApplicationTriggerTaskName, true);
00055                     break;
00056                 }
00057             }
00058
00059             trigger = new ApplicationTrigger();
00060             UpdateUI();
00061         }
00062
00063         /// <summary>
00064         /// Register a ApplicationTriggerTask.
00065         /// </summary>
00066         /// <param name="sender"></param>
00067         /// <param name="e"></param>
00068         private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
00069         {
00070             var task = BackgroundTaskSample.RegisterBackgroundTask(null,
00071                                                                    BackgroundTaskSample.ApplicationTriggerTaskName,
00072                                                                    trigger,
00073                                                                    null);
00074             AttachProgressAndCompletedHandlers(task);
00075             UpdateUI();
00076         }
00077
00078         /// <summary>
00079         /// Unregister a ApplicationTriggerTask.
00080         /// </summary>
00081         /// <param name="sender"></param>
00082         /// <param name="e"></param>
00083         private void UnregisterBackgroundTask(object sender, RoutedEventArgs e)
00084         {
00085             BackgroundTaskSample.UnregisterBackgroundTasks(BackgroundTaskSample.ApplicationTriggerTaskName);
00086             BackgroundTaskSample.ApplicationTriggerTaskResult = "";
00087             UpdateUI();
00088         }
00089
00090         /// <summary>
00091         /// Signal a ApplicationTriggerTask.
00092         /// </summary>
00093         /// <param name="sender"></param>
00094         /// <param name="e"></param>
00095         private async void SignalBackgroundTask(object sender, RoutedEventArgs e)
00096         {
00097             // Reset the completion status
00098             BackgroundTaskSample.TaskStatuses.Remove(BackgroundTaskSample.ApplicationTriggerTaskName);
00099
00100             //Signal the ApplicationTrigger
00101             var result = await trigger.RequestAsync();
00102             BackgroundTaskSample.ApplicationTriggerTaskResult = "Signal result: " + result.ToString();
00103             UpdateUI();
00104         }
00105
00106         /// <summary>
00107         /// Attach progress and completed handers to a background task.
00108         /// </summary>
00109         /// <param name="task">The task to attach progress and completed handlers to.</param>
00110         private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
00111         {
00112             task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
00113             task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
00114         }
00115
00116         /// <summary>
00117         /// Handle background task progress.
00118         /// </summary>
00119         /// <param name="task">The task that is reporting progress.</param>
00120         /// <param name="e">Arguments of the progress report.</param>
00121         private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
00122         {
00123             var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00124             {
00125                 var progress = "Progress: " + args.Progress + "%";
00126                 BackgroundTaskSample.ApplicationTriggerTaskProgress = progress;
00127                 UpdateUI();
00128             });
00129         }
00130
00131         /// <summary>
00132         /// Handle background task completion.
00133         /// </summary>
00134         /// <param name="task">The task that is reporting completion.</param>
00135         /// <param name="e">Arguments of the completion report.</param>
00136         private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
00137         {
00138             UpdateUI();
00139         }
00140
00141         /// <summary>
00142         /// Update the scenario UI.
00143         /// </summary>
00144         private async void UpdateUI()
00145         {
00146             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00147             () =>
00148             {
00149                 RegisterButton.IsEnabled = !BackgroundTaskSample.ApplicationTriggerTaskRegistered;
00150                 UnregisterButton.IsEnabled = BackgroundTaskSample.ApplicationTriggerTaskRegistered;
00151                 SignalButton.IsEnabled = BackgroundTaskSample.ApplicationTriggerTaskRegistered & (trigger != null);
00152                 Progress.Text = BackgroundTaskSample.ApplicationTriggerTaskProgress;
00153                 Result.Text = BackgroundTaskSample.ApplicationTriggerTaskResult;
00154                 Status.Text = BackgroundTaskSample.GetBackgroundTaskStatus(BackgroundTaskSample.ApplicationTriggerTaskName);
00155             });
00156         }
00157
00158     }
00159 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserCertificateStore/cs/Scenario1_MoveCertificate.xaml.cs Source File

  • UserCertificateStore
  • cs

Scenario1_MoveCertificate.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018 using Windows.Security.Cryptography.Certificates;
00019 using Windows.Security.Cryptography;
00020
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario1_MoveCertificate : Page
00025     {
00026         CertificateStore appStore = CertificateStores.GetStoreByName(StandardCertificateStoreNames.Personal);
00027         UserCertificateStore userStore = CertificateStores.GetUserStoreByName(StandardCertificateStoreNames.Personal);
00028
00029         public Scenario1_MoveCertificate()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override async void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             IReadOnlyList<Certificate> certificates = await CertificateStores.FindAllAsync();
00037
00038             foreach (Certificate certificate in certificates)
00039             {
00040                 var item = new ListViewItem
00041                 {
00042                     Content = $"Subject: {certificate.Subject}, Serial Number: {CryptographicBuffer.EncodeToHexString(CryptographicBuffer.CreateFromByteArray(certificate.SerialNumber))}",
00043                     Tag = certificate
00044                 };
00045
00046                 if (certificate.IsPerUser)
00047                 {
00048                     UserCertificateListView.Items.Add(item);
00049                 }
00050                 else
00051                 {
00052                     AppCertificateListView.Items.Add(item);
00053                 }
00054             }
00055         }
00056
00057         static void MoveItemBetweenListViews(ListViewItem item, ListView source, ListView destination)
00058         {
00059             source.Items.Remove(item);
00060
00061             destination.Items.Add(item);
00062             destination.SelectedItem = item;
00063             destination.ScrollIntoView(item);
00064         }
00065
00066         private async void MoveUserCertificateToAppCertificateStore(object sender, RoutedEventArgs e)
00067         {
00068             var item = (ListViewItem)UserCertificateListView.SelectedItem;
00069             if (item != null)
00070             {
00071                 var certificate = (Certificate)item.Tag;
00072                 appStore.Add(certificate);
00073
00074                 if (await userStore.RequestDeleteAsync(certificate))
00075                 {
00076                     MoveItemBetweenListViews(item, UserCertificateListView, AppCertificateListView);
00077                 }
00078                 else
00079                 {
00080                     appStore.Delete(certificate);
00081                 }
00082             }
00083         }
00084
00085         private async void MoveAppCertificateToUserCertificateStore(object sender, RoutedEventArgs e)
00086         {
00087             var item = (ListViewItem)AppCertificateListView.SelectedItem;
00088             if (item != null)
00089             {
00090                 var certificate = (Certificate)item.Tag;
00091                 if (await userStore.RequestAddAsync(certificate))
00092                 {
00093                     appStore.Delete(certificate);
00094                     MoveItemBetweenListViews(item, AppCertificateListView, UserCertificateListView);
00095                 }
00096             }
00097         }
00098     }
00099 }
Generated on Fri Nov 15 2024 22:21:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/Util/CustomDevicePickerFilter.cs Source File

  • AdvancedCasting
  • cs
  • Util

CustomDevicePickerFilter.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017 using Windows.Devices.Enumeration;
00018
00019 namespace ScreenCasting.Util
00020 {
00021      public class CustomDevicePickerFilter
00022     {
00023         private IList<string> supportedDeviceSelectors = new List<string>();
00024
00025         public IList<string> SupportedDeviceSelectors
00026         {
00027             get { return supportedDeviceSelectors; }
00028         }
00029         public override string ToString()
00030         {
00031             string retval = string.Empty;
00032
00033             if (supportedDeviceSelectors.Count > 0)
00034                 retval = supportedDeviceSelectors[0];
00035
00036             if (supportedDeviceSelectors.Count > 1)
00037                 retval = "(" + retval + ")";
00038
00039             for (int idx = 1; idx < supportedDeviceSelectors.Count; idx++)
00040                 retval = retval + " OR (" + supportedDeviceSelectors[idx] + ")";
00041
00042             return retval;
00043         }
00044     }
00045 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SourceHandler::PositionInformation Member List

This is the complete list of members for SourceHandler::PositionInformation, including all inherited members.
CheckIfObsolete(long long now) | SourceHandler::PositionInformation
HasValue | SourceHandler::PositionInformation
IsCurrent | SourceHandler::PositionInformation
LastValueTime | SourceHandler::PositionInformation
Orientation | SourceHandler::PositionInformation
Position | SourceHandler::PositionInformation
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

StspStreamDescription Member List

This is the complete list of members for StspStreamDescription, including all inherited members.
cbAttributesSize | StspStreamDescription
dwStreamId | StspStreamDescription
guiMajorType | StspStreamDescription
guiSubType | StspStreamDescription
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cpp/Tasks/pch.cpp Source File

  • BackgroundTransfer
  • cpp
  • Tasks

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicFaceTracking/cppwinrt/SampleConfiguration.cpp Source File

  • BasicFaceTracking
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::Graphics::Imaging;
00020 using namespace SDKTemplate;
00021
00022 hstring implementation::MainPage::FEATURE_NAME()
00023 {
00024     return L"Basic face tracking C++/WinRT Sample";
00025 }
00026
00027 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00028 {
00029     Scenario{ L"Track Faces in Webcam", xaml_typename<SDKTemplate::Scenario1_TrackInWebcam>() },
00030 });
00031
00032 hstring winrt::to_hstring(BitmapPixelFormat format)
00033 {
00034     switch (format)
00035     {
00036     case BitmapPixelFormat::Unknown: return L"Unknown";
00037     case BitmapPixelFormat::Rgba16: return L"Rgba16";
00038     case BitmapPixelFormat::Rgba8: return L"Rgba8";
00039     case BitmapPixelFormat::Gray16: return L"Gray16";
00040     case BitmapPixelFormat::Gray8: return L"Gray8";
00041     case BitmapPixelFormat::Bgra8: return L"Bgra8";
00042     case BitmapPixelFormat::Nv12: return L"Nv12";
00043     case BitmapPixelFormat::P010: return L"P010";
00044     case BitmapPixelFormat::Yuy2: return L"Yuy2";
00045     }
00046     return to_hstring(static_cast<int32_t>(format));
00047 }
Generated on Fri Nov 15 2024 22:17:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/GameObject.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

GameObject.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // GameObject:
00015 // This is the class representing a generic object in the 3D world of the game. There are
00016 // specific sub-classes that have specific geometric shapes. This class contains all the
00017 // properties of objects that are common.
00018 //
00019 // During the game physics calculations the IsTouching method will be called to determine
00020 // the object's proximity to a point. It is expected the sub-classes will replace this method.
00021 // The Render method will be called during rendering to include the object in the generation of
00022 // the scene.
00023
00024 #include "MeshObject.h"
00025 #include "SoundEffect.h"
00026 #include "Animate.h"
00027 #include "Material.h"
00028
00029 class GameObject
00030 {
00031 public:
00032     GameObject();
00033
00034     // Expect the IsTouching method to be overloaded by subclasses.
00035     virtual bool IsTouching(
00036         DirectX::XMFLOAT3 /* point */,
00037         float /* radius */,
00038         _Out_ DirectX::XMFLOAT3* contact,
00039         _Out_ DirectX::XMFLOAT3* normal
00040         )
00041     {
00042         *contact = DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f);
00043         *normal = DirectX::XMFLOAT3(0.0f, 0.0f, 1.0f);
00044         return false;
00045     };
00046
00047     void Render(
00048         _In_ ID3D11DeviceContext* context,
00049         _In_ ID3D11Buffer* primitiveConstantBuffer
00050         );
00051
00052     void Active(bool active);
00053     bool Active();
00054     void Target(bool target);
00055     bool Target();
00056     void Hit(bool hit);
00057     bool Hit();
00058     void OnGround(bool ground);
00059     bool OnGround();
00060     void TargetId(int targetId);
00061     int  TargetId();
00062     void HitTime(float t);
00063     float HitTime();
00064
00065     void AnimatePosition(_In_ std::shared_ptr<Animate> const& animate);
00066     std::shared_ptr<Animate> AnimatePosition();
00067
00068     void HitSound(_In_ std::shared_ptr<SoundEffect> const& hitSound);
00069     std::shared_ptr<SoundEffect> HitSound();
00070
00071     void PlaySound(float impactSpeed, DirectX::XMFLOAT3 eyePoint);
00072
00073     void Mesh(_In_ std::shared_ptr<MeshObject> const& mesh);
00074
00075     void NormalMaterial(_In_ std::shared_ptr<Material> const& material);
00076     std::shared_ptr<Material> NormalMaterial();
00077     void HitMaterial(_In_ std::shared_ptr<Material> const& material);
00078     std::shared_ptr<Material> HitMaterial();
00079
00080     void Position(DirectX::XMFLOAT3 position);
00081     void Position(DirectX::XMVECTOR position);
00082     void Velocity(DirectX::XMFLOAT3 velocity);
00083     void Velocity(DirectX::XMVECTOR velocity);
00084     DirectX::XMMATRIX ModelMatrix();
00085     DirectX::XMFLOAT3 Position();
00086     DirectX::XMVECTOR VectorPosition();
00087     DirectX::XMVECTOR VectorVelocity();
00088     DirectX::XMFLOAT3 Velocity();
00089
00090 protected:
00091     DirectX::XMFLOAT4X4 m_modelMatrix;
00092     DirectX::XMFLOAT3   m_position;
00093
00094 private:
00095     virtual void UpdatePosition() {};
00096     // Object Data
00097     bool                         m_active;
00098     bool                         m_target;
00099     int                          m_targetId;
00100     bool                         m_hit;
00101     bool                         m_ground;
00102
00103     DirectX::XMFLOAT3            m_velocity;
00104
00105     std::shared_ptr<Material>    m_normalMaterial;
00106     std::shared_ptr<Material>    m_hitMaterial;
00107
00108     DirectX::XMFLOAT3            m_defaultXAxis;
00109     DirectX::XMFLOAT3            m_defaultYAxis;
00110     DirectX::XMFLOAT3            m_defaultZAxis;
00111
00112     float                        m_hitTime;
00113
00114     std::shared_ptr<Animate>     m_animatePosition;
00115     std::shared_ptr<MeshObject>  m_mesh;
00116
00117     std::shared_ptr<SoundEffect> m_hitSound;
00118 };
00119
00120 __forceinline void GameObject::Active(bool active)
00121 {
00122     m_active = active;
00123 }
00124
00125 __forceinline bool GameObject::Active()
00126 {
00127     return m_active;
00128 }
00129
00130 __forceinline void GameObject::Target(bool target)
00131 {
00132     m_target = target;
00133 }
00134
00135 __forceinline bool GameObject::Target()
00136 {
00137     return m_target;
00138 }
00139
00140 __forceinline void GameObject::Hit(bool hit)
00141 {
00142     m_hit = hit;
00143 }
00144
00145 __forceinline bool GameObject::Hit()
00146 {
00147     return m_hit;
00148 }
00149
00150 __forceinline void GameObject::OnGround(bool ground)
00151 {
00152     m_ground = ground;
00153 }
00154
00155 __forceinline bool GameObject::OnGround()
00156 {
00157     return m_ground;
00158 }
00159
00160 __forceinline void GameObject::TargetId(int targetId)
00161 {
00162     m_targetId = targetId;
00163 }
00164
00165 __forceinline int GameObject::TargetId()
00166 {
00167     return m_targetId;
00168 }
00169
00170 __forceinline void GameObject::HitTime(float t)
00171 {
00172     m_hitTime = t;
00173 }
00174
00175 __forceinline float GameObject::HitTime()
00176 {
00177     return m_hitTime;
00178 }
00179
00180 __forceinline void GameObject::Position(DirectX::XMFLOAT3 position)
00181 {
00182     m_position = position;
00183     // Update any internal states that are dependent on the position.
00184     // UpdatePosition is a virtual function that is specific to the derived class.
00185     UpdatePosition();
00186 }
00187
00188 __forceinline void GameObject::Position(DirectX::XMVECTOR position)
00189 {
00190     XMStoreFloat3(&m_position, position);
00191     // Update any internal states that are dependent on the position.
00192     // UpdatePosition is a virtual function that is specific to the derived class.
00193     UpdatePosition();
00194 }
00195
00196 __forceinline DirectX::XMFLOAT3 GameObject::Position()
00197 {
00198     return m_position;
00199 }
00200
00201 __forceinline DirectX::XMVECTOR GameObject::VectorPosition()
00202 {
00203     return DirectX::XMLoadFloat3(&m_position);
00204 }
00205
00206 __forceinline void GameObject::Velocity(DirectX::XMFLOAT3 velocity)
00207 {
00208     m_velocity = velocity;
00209 }
00210
00211 __forceinline void GameObject::Velocity(DirectX::XMVECTOR velocity)
00212 {
00213     XMStoreFloat3(&m_velocity, velocity);
00214 }
00215
00216 __forceinline DirectX::XMFLOAT3 GameObject::Velocity()
00217 {
00218     return m_velocity;
00219 }
00220
00221 __forceinline DirectX::XMVECTOR GameObject::VectorVelocity()
00222 {
00223     return DirectX::XMLoadFloat3(&m_velocity);
00224 }
00225
00226 __forceinline void GameObject::AnimatePosition(_In_ std::shared_ptr<Animate> const& animate)
00227 {
00228     m_animatePosition = animate;
00229 }
00230
00231 __forceinline std::shared_ptr<Animate> GameObject::AnimatePosition()
00232 {
00233     return m_animatePosition;
00234 }
00235
00236 __forceinline void GameObject::NormalMaterial(_In_ std::shared_ptr<Material> const& material)
00237 {
00238     m_normalMaterial = material;
00239 }
00240
00241 __forceinline std::shared_ptr<Material> GameObject::NormalMaterial()
00242 {
00243     return m_normalMaterial;
00244 }
00245
00246 __forceinline void GameObject::HitMaterial(_In_ std::shared_ptr<Material> const& material)
00247 {
00248     m_hitMaterial = material;
00249 }
00250
00251 __forceinline std::shared_ptr<Material> GameObject::HitMaterial()
00252 {
00253     return m_hitMaterial;
00254 }
00255
00256 __forceinline void GameObject::Mesh(_In_ std::shared_ptr<MeshObject> const& mesh)
00257 {
00258     m_mesh = mesh;
00259 }
00260
00261 __forceinline void GameObject::HitSound(_In_ std::shared_ptr<SoundEffect> const& hitSound)
00262 {
00263     m_hitSound = hitSound;
00264 }
00265
00266 __forceinline std::shared_ptr<SoundEffect> GameObject::HitSound()
00267 {
00268     return m_hitSound;
00269 }
00270
00271 __forceinline DirectX::XMMATRIX GameObject::ModelMatrix()
00272 {
00273     return DirectX::XMLoadFloat4x4(&m_modelMatrix);
00274 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/DeviceState.h Source File

  • WindowsAudioSession
  • cpp

DeviceState.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // devicestate.h
00013 //
00014
00015 #include "MainPage.xaml.h"
00016
00017 #pragma once
00018
00019 using namespace Windows::Storage::Streams;
00020
00021 namespace SDKSample
00022 {
00023     namespace WASAPIAudio
00024     {
00025         // NB: All states >= DeviceStateInitialized will allow some methods
00026         // to be called successfully on the Audio Client
00027         public enum class DeviceState
00028         {
00029             DeviceStateUnInitialized,
00030             DeviceStateInError,
00031             DeviceStateDiscontinuity,
00032             DeviceStateFlushing,
00033             DeviceStateActivated,
00034             DeviceStateInitialized,
00035             DeviceStateStarting,
00036             DeviceStatePlaying,
00037             DeviceStateCapturing,
00038             DeviceStatePausing,
00039             DeviceStatePaused,
00040             DeviceStateStopping,
00041             DeviceStateStopped
00042         };
00043
00044         // Class for DeviceStateChanged events
00045         public ref class DeviceStateChangedEventArgs sealed
00046         {
00047         internal:
00048             DeviceStateChangedEventArgs( DeviceState newState, HRESULT hr) :
00049                 m_DeviceState( newState ),
00050                 m_hr( hr )
00051             {};
00052
00053             property DeviceState State
00054             {
00055                 DeviceState get() { return m_DeviceState; }
00056             };
00057
00058             property int hr
00059             {
00060                 int get() { return m_hr; }
00061             }
00062
00063         private:
00064             DeviceState      m_DeviceState;
00065             HRESULT          m_hr;
00066         };
00067
00068         // DeviceStateChanged delegate
00069         public delegate void DeviceStateChangedHandler( Platform::Object^ sender, DeviceStateChangedEventArgs^ e );
00070
00071         // DeviceStateChanged Event
00072         public ref class DeviceStateChangedEvent sealed
00073         {
00074         public:
00075             DeviceStateChangedEvent() :
00076                 m_DeviceState( DeviceState::DeviceStateUnInitialized )
00077             {};
00078
00079             DeviceState GetState() { return m_DeviceState; };
00080
00081         internal:
00082             void SetState( DeviceState newState, HRESULT hr, Platform::Boolean FireEvent ) {
00083                 if (m_DeviceState != newState)
00084                 {
00085                     m_DeviceState = newState;
00086
00087                     if (FireEvent)
00088                     {
00089                         DeviceStateChangedEventArgs^ e = ref new DeviceStateChangedEventArgs( m_DeviceState, hr );
00090                         StateChangedEvent( this, e );
00091                     }
00092                 }
00093             };
00094
00095         public:
00096             static event DeviceStateChangedHandler^    StateChangedEvent;
00097
00098         private:
00099             DeviceState     m_DeviceState;
00100         };
00101     }
00102 }
Generated on Fri Nov 15 2024 22:22:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/Common/DirectXHelper.h Source File

  • HolographicTagAlong
  • cpp
  • Common

DirectXHelper.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <ppltasks.h>    // For create_task
00015
00016 namespace DX
00017 {
00018     inline void ThrowIfFailed(HRESULT hr)
00019     {
00020         if (FAILED(hr))
00021         {
00022             // Set a breakpoint on this line to catch Win32 API errors.
00023             throw Platform::Exception::CreateException(hr);
00024         }
00025     }
00026
00027     // Function that reads from a binary file asynchronously.
00028     inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename)
00029     {
00030         using namespace Windows::Storage;
00031         using namespace Concurrency;
00032
00033         return create_task(PathIO::ReadBufferAsync(Platform::StringReference(filename.c_str()))).then(
00034             [] (Streams::IBuffer^ fileBuffer) -> std::vector<byte>
00035             {
00036                 std::vector<byte> returnBuffer;
00037                 returnBuffer.resize(fileBuffer->Length);
00038                 Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), returnBuffer.size()));
00039                 return returnBuffer;
00040             });
00041     }
00042
00043     // Converts a length in device-independent pixels (DIPs) to a length in physical pixels.
00044     inline float ConvertDipsToPixels(float dips, float dpi)
00045     {
00046         constexpr float dipsPerInch = 96.0f;
00047         return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00048     }
00049
00050 #if defined(_DEBUG)
00051     // Check for SDK Layer support.
00052     inline bool SdkLayersAvailable()
00053     {
00054         HRESULT hr = D3D11CreateDevice(
00055             nullptr,
00056             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00057             0,
00058             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00059             nullptr,                    // Any feature level will do.
00060             0,
00061             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00062             nullptr,                    // No need to keep the D3D device reference.
00063             nullptr,                    // No need to know the feature level.
00064             nullptr                     // No need to keep the D3D device context reference.
00065             );
00066
00067         return SUCCEEDED(hr);
00068     }
00069 #endif
00070 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_SecondaryTiles Member List

This is the complete list of members for Scenario3_SecondaryTiles, including all inherited members.
BADGE_TILE_ID | Scenario3_SecondaryTiles | [private]
CreateBadgeAndTextTile_Click(object sender, RoutedEventArgs e) | Scenario3_SecondaryTiles | [inline, private]
CreateBadgeTile_Click(object sender, RoutedEventArgs e) | Scenario3_SecondaryTiles | [inline, private]
GetElementRect(FrameworkElement element) | Scenario3_SecondaryTiles | [inline, private]
rootPage | Scenario3_SecondaryTiles | [private]
Scenario3_SecondaryTiles() | Scenario3_SecondaryTiles | [inline]
TEXT_TILE_ID | Scenario3_SecondaryTiles | [private]
Generated on Fri Nov 15 2024 22:23:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

EventHandlerForDevice Member List

This is the complete list of members for EventHandlerForDevice, including all inherited members.
appResumeEventHandler | EventHandlerForDevice | [private]
appSuspendEventHandler | EventHandlerForDevice | [private]
CloseCurrentlyConnectedDevice() | EventHandlerForDevice | [inline, private]
CloseDevice() | EventHandlerForDevice | [inline]
CreateNewEventHandlerForDevice() | EventHandlerForDevice | [inline, static]
Current | EventHandlerForDevice | [static]
device | EventHandlerForDevice | [private]
Device | EventHandlerForDevice |
deviceAccessEventHandler | EventHandlerForDevice | [private]
DeviceAccessInformation | EventHandlerForDevice |
deviceAccessInformation | EventHandlerForDevice | [private]
deviceAddedEventHandler | EventHandlerForDevice | [private]
deviceCloseCallback | EventHandlerForDevice | [private]
deviceConnectedCallback | EventHandlerForDevice | [private]
DeviceInformation | EventHandlerForDevice |
deviceInformation | EventHandlerForDevice | [private]
deviceRemovedEventHandler | EventHandlerForDevice | [private]
deviceSelector | EventHandlerForDevice | [private]
DeviceSelector | EventHandlerForDevice |
deviceWatcher | EventHandlerForDevice | [private]
eventHandlerForDevice | EventHandlerForDevice | [private, static]
EventHandlerForDevice() | EventHandlerForDevice | [inline, private]
IsDeviceConnected | EventHandlerForDevice |
isEnabledAutoReconnect | EventHandlerForDevice | [private]
IsEnabledAutoReconnect | EventHandlerForDevice |
OnAppResume(Object sender, Object args) | EventHandlerForDevice | [inline, private]
OnAppSuspension(Object sender, SuspendingEventArgs args) | EventHandlerForDevice | [inline, private]
OnDeviceAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs eventArgs) | EventHandlerForDevice | [inline, private]
OnDeviceAdded(DeviceWatcher sender, DeviceInformation deviceInfo) | EventHandlerForDevice | [inline, private]
OnDeviceClose | EventHandlerForDevice |
OnDeviceConnected | EventHandlerForDevice |
OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceInformationUpdate) | EventHandlerForDevice | [inline, private]
OpenDeviceAsync(DeviceInformation deviceInfo, String deviceSelector) | EventHandlerForDevice | [inline]
RegisterForAppEvents() | EventHandlerForDevice | [inline, private]
RegisterForDeviceAccessStatusChange() | EventHandlerForDevice | [inline, private]
RegisterForDeviceWatcherEvents() | EventHandlerForDevice | [inline, private]
rootPage | EventHandlerForDevice | [private]
singletonCreationLock | EventHandlerForDevice | [private, static]
StartDeviceWatcher() | EventHandlerForDevice | [inline, private]
StopDeviceWatcher() | EventHandlerForDevice | [inline, private]
UnregisterFromAppEvents() | EventHandlerForDevice | [inline, private]
UnregisterFromDeviceAccessStatusChange() | EventHandlerForDevice | [inline, private]
UnregisterFromDeviceWatcherEvents() | EventHandlerForDevice | [inline, private]
watcherStarted | EventHandlerForDevice | [private]
watcherSuspended | EventHandlerForDevice | [private]
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ServicingComplete Member List

This is the complete list of members for ServicingComplete, including all inherited members.
_cancelRequested | ServicingComplete | [private]
OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) | ServicingComplete | [inline, private]
Run(IBackgroundTaskInstance taskInstance) | ServicingComplete | [inline]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraProfile/cpp/Scenario3_EnableHdrProfile.xaml.h Source File

  • CameraProfile
  • cpp

Scenario3_EnableHdrProfile.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_EnableHdrProfile.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario3_EnableHdrProfile sealed
00024     {
00025     public:
00026         Scenario3_EnableHdrProfile();
00027
00028         void CheckHdrSupportBtn_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029
00030     protected:
00031         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00032
00033     private:
00034         MainPage^ _rootPage;
00035         Concurrency::task<Platform::String^> GetVideoProfileSupportedDeviceIdAsync(Windows::Devices::Enumeration::Panel panel);
00036
00037         Concurrency::task<void> LogStatusToOutputBoxAsync(Platform::String^ message);
00038         Concurrency::task<void> LogStatusAsync(Platform::String^ message, NotifyType type);
00039     };
00040 }
Generated on Fri Nov 15 2024 22:18:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MIDI/cs/Scenario2_ReceiveMIDIMessages.xaml.cs Source File

  • MIDI
  • cs

Scenario2_ReceiveMIDIMessages.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Text;
00016 using Windows.Devices.Enumeration;
00017 using Windows.Devices.Midi;
00018 using Windows.Storage.Streams;
00019 using Windows.UI.Core;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00024
00025 namespace MIDI
00026 {
00027     /// <summary>
00028     /// An empty page that can be used on its own or navigated to within a Frame.
00029     /// </summary>
00030     public sealed partial class Scenario2_ReceiveMIDIMessages : Page
00031     {
00032         /// <summary>
00033         /// Main Page
00034         /// </summary>
00035         private MainPage rootPage;
00036
00037         /// <summary>
00038         /// Collection of active MidiInPorts
00039         /// </summary>
00040         private List<MidiInPort> midiInPorts;
00041
00042         /// <summary>
00043         /// Device watcher for MIDI in ports
00044         /// </summary>
00045         MidiDeviceWatcher midiInDeviceWatcher;
00046
00047         /// <summary>
00048         /// Set the rootpage context when entering the scenario
00049         /// </summary>
00050         /// <param name="e">Event arguments</param>
00051         protected override void OnNavigatedTo(NavigationEventArgs e)
00052         {
00053             this.rootPage = MainPage.Current;
00054         }
00055
00056         /// <summary>
00057         /// Stop the device watcher when leaving the scenario
00058         /// </summary>
00059         /// <param name="e">Event arguments</param>
00060         protected override void OnNavigatedFrom(NavigationEventArgs e)
00061         {
00062             base.OnNavigatedFrom(e);
00063
00064             // Stop the input device watcher
00065             this.midiInDeviceWatcher.Stop();
00066
00067             // Close all MidiInPorts
00068             foreach (MidiInPort inPort in this.midiInPorts)
00069             {
00070                 inPort.Dispose();
00071             }
00072             this.midiInPorts.Clear();
00073         }
00074
00075         /// <summary>
00076         /// Constructor: Start the device watcher
00077         /// </summary>
00078         public Scenario2_ReceiveMIDIMessages()
00079         {
00080             this.InitializeComponent();
00081
00082             // Initialize the list of active MIDI input devices
00083             this.midiInPorts = new List<MidiInPort>();
00084
00085             // Set up the MIDI input device watcher
00086             this.midiInDeviceWatcher = new MidiDeviceWatcher(MidiInPort.GetDeviceSelector(), Dispatcher, this.inputDevices);
00087
00088             // Start watching for devices
00089             this.midiInDeviceWatcher.Start();
00090         }
00091
00092         /// <summary>
00093         /// Change the input MIDI device from which to receive messages
00094         /// </summary>
00095         /// <param name="sender">Element that fired the event</param>
00096         /// <param name="e">Event arguments</param>
00097         private async void inputDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
00098         {
00099             // Get the selected input MIDI device
00100             int selectedInputDeviceIndex = (sender as ListBox).SelectedIndex;
00101
00102             // Try to create a MidiInPort
00103             if (selectedInputDeviceIndex < 0)
00104             {
00105                 // Clear input device messages
00106                 this.inputDeviceMessages.Items.Clear();
00107                 this.inputDeviceMessages.Items.Add("Select a MIDI input device to be able to see its messages");
00108                 this.inputDeviceMessages.IsEnabled = false;
00109                 this.rootPage.NotifyUser("Select a MIDI input device to be able to see its messages", NotifyType.StatusMessage);
00110                 return;
00111             }
00112
00113             DeviceInformationCollection devInfoCollection = this.midiInDeviceWatcher.GetDeviceInformationCollection();
00114             if (devInfoCollection == null)
00115             {
00116                 this.inputDeviceMessages.Items.Clear();
00117                 this.inputDeviceMessages.Items.Add("Device not found!");
00118                 this.inputDeviceMessages.IsEnabled = false;
00119                 this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage);
00120                 return;
00121             }
00122
00123             DeviceInformation devInfo = devInfoCollection[selectedInputDeviceIndex];
00124             if (devInfo == null)
00125             {
00126                 this.inputDeviceMessages.Items.Clear();
00127                 this.inputDeviceMessages.Items.Add("Device not found!");
00128                 this.inputDeviceMessages.IsEnabled = false;
00129                 this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage);
00130                 return;
00131             }
00132
00133             var currentMidiInputDevice = await MidiInPort.FromIdAsync(devInfo.Id);
00134             if (currentMidiInputDevice == null)
00135             {
00136                 this.rootPage.NotifyUser("Unable to create MidiInPort from input device", NotifyType.ErrorMessage);
00137                 return;
00138             }
00139
00140             // We have successfully created a MidiInPort; add the device to the list of active devices, and set up message receiving
00141             if (!this.midiInPorts.Contains(currentMidiInputDevice))
00142             {
00143                 this.midiInPorts.Add(currentMidiInputDevice);
00144                 currentMidiInputDevice.MessageReceived += MidiInputDevice_MessageReceived;
00145             }
00146
00147             // Clear any previous input messages
00148             this.inputDeviceMessages.Items.Clear();
00149             this.inputDeviceMessages.IsEnabled = true;
00150
00151             this.rootPage.NotifyUser("Input Device selected successfully! Waiting for messages...", NotifyType.StatusMessage);
00152         }
00153
00154         /// <summary>
00155         /// Display the received MIDI message in a readable format
00156         /// </summary>
00157         /// <param name="sender">Element that fired the event</param>
00158         /// <param name="args">The received message</param>
00159         private async void MidiInputDevice_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args)
00160         {
00161             IMidiMessage receivedMidiMessage = args.Message;
00162
00163             // Build the received MIDI message into a readable format
00164             StringBuilder outputMessage = new StringBuilder();
00165             outputMessage.Append(receivedMidiMessage.Timestamp.ToString()).Append(", Type: ").Append(receivedMidiMessage.Type);
00166
00167             // Add MIDI message parameters to the output, depending on the type of message
00168             switch (receivedMidiMessage.Type)
00169             {
00170                 case MidiMessageType.NoteOff:
00171                     var noteOffMessage = (MidiNoteOffMessage)receivedMidiMessage;
00172                     outputMessage.Append(", Channel: ").Append(noteOffMessage.Channel).Append(", Note: ").Append(noteOffMessage.Note).Append(", Velocity: ").Append(noteOffMessage.Velocity);
00173                     break;
00174                 case MidiMessageType.NoteOn:
00175                     var noteOnMessage = (MidiNoteOnMessage)receivedMidiMessage;
00176                     outputMessage.Append(", Channel: ").Append(noteOnMessage.Channel).Append(", Note: ").Append(noteOnMessage.Note).Append(", Velocity: ").Append(noteOnMessage.Velocity);
00177                     break;
00178                 case MidiMessageType.PolyphonicKeyPressure:
00179                     var polyphonicKeyPressureMessage = (MidiPolyphonicKeyPressureMessage)receivedMidiMessage;
00180                     outputMessage.Append(", Channel: ").Append(polyphonicKeyPressureMessage.Channel).Append(", Note: ").Append(polyphonicKeyPressureMessage.Note).Append(", Pressure: ").Append(polyphonicKeyPressureMessage.Pressure);
00181                     break;
00182                 case MidiMessageType.ControlChange:
00183                     var controlChangeMessage = (MidiControlChangeMessage)receivedMidiMessage;
00184                     outputMessage.Append(", Channel: ").Append(controlChangeMessage.Channel).Append(", Controller: ").Append(controlChangeMessage.Controller).Append(", Value: ").Append(controlChangeMessage.ControlValue);
00185                     break;
00186                 case MidiMessageType.ProgramChange:
00187                     var programChangeMessage = (MidiProgramChangeMessage)receivedMidiMessage;
00188                     outputMessage.Append(", Channel: ").Append(programChangeMessage.Channel).Append(", Program: ").Append(programChangeMessage.Program);
00189                     break;
00190                 case MidiMessageType.ChannelPressure:
00191                     var channelPressureMessage = (MidiChannelPressureMessage)receivedMidiMessage;
00192                     outputMessage.Append(", Channel: ").Append(channelPressureMessage.Channel).Append(", Pressure: ").Append(channelPressureMessage.Pressure);
00193                     break;
00194                 case MidiMessageType.PitchBendChange:
00195                     var pitchBendChangeMessage = (MidiPitchBendChangeMessage)receivedMidiMessage;
00196                     outputMessage.Append(", Channel: ").Append(pitchBendChangeMessage.Channel).Append(", Bend: ").Append(pitchBendChangeMessage.Bend);
00197                     break;
00198                 case MidiMessageType.SystemExclusive:
00199                     var systemExclusiveMessage = (MidiSystemExclusiveMessage)receivedMidiMessage;
00200                     outputMessage.Append(", ");
00201
00202                     // Read the SysEx bufffer
00203                     var sysExDataReader = DataReader.FromBuffer(systemExclusiveMessage.RawData);
00204                     while (sysExDataReader.UnconsumedBufferLength > 0)
00205                     {
00206                         byte byteRead = sysExDataReader.ReadByte();
00207                         // Pad with leading zero if necessary
00208                         outputMessage.Append(byteRead.ToString("X2")).Append(" ");
00209                     }
00210                     break;
00211                 case MidiMessageType.MidiTimeCode:
00212                     var timeCodeMessage = (MidiTimeCodeMessage)receivedMidiMessage;
00213                     outputMessage.Append(", FrameType: ").Append(timeCodeMessage.FrameType).Append(", Values: ").Append(timeCodeMessage.Values);
00214                     break;
00215                 case MidiMessageType.SongPositionPointer:
00216                     var songPositionPointerMessage = (MidiSongPositionPointerMessage)receivedMidiMessage;
00217                     outputMessage.Append(", Beats: ").Append(songPositionPointerMessage.Beats);
00218                     break;
00219                 case MidiMessageType.SongSelect:
00220                     var songSelectMessage = (MidiSongSelectMessage)receivedMidiMessage;
00221                     outputMessage.Append(", Song: ").Append(songSelectMessage.Song);
00222                     break;
00223                 case MidiMessageType.TuneRequest:
00224                     var tuneRequestMessage = (MidiTuneRequestMessage)receivedMidiMessage;
00225                     break;
00226                 case MidiMessageType.TimingClock:
00227                     var timingClockMessage = (MidiTimingClockMessage)receivedMidiMessage;
00228                     break;
00229                 case MidiMessageType.Start:
00230                     var startMessage = (MidiStartMessage)receivedMidiMessage;
00231                     break;
00232                 case MidiMessageType.Continue:
00233                     var continueMessage = (MidiContinueMessage)receivedMidiMessage;
00234                     break;
00235                 case MidiMessageType.Stop:
00236                     var stopMessage = (MidiStopMessage)receivedMidiMessage;
00237                     break;
00238                 case MidiMessageType.ActiveSensing:
00239                     var activeSensingMessage = (MidiActiveSensingMessage)receivedMidiMessage;
00240                     break;
00241                 case MidiMessageType.SystemReset:
00242                     var systemResetMessage = (MidiSystemResetMessage)receivedMidiMessage;
00243                     break;
00244                 case MidiMessageType.None:
00245                     throw new InvalidOperationException();
00246                 default:
00247                     break;
00248             }
00249
00250             // Use the Dispatcher to update the messages on the UI thread
00251             await Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
00252             {
00253                 // Skip TimingClock and ActiveSensing messages to avoid overcrowding the list. Commment this check out to see all messages
00254                 if ((receivedMidiMessage.Type != MidiMessageType.TimingClock) && (receivedMidiMessage.Type != MidiMessageType.ActiveSensing))
00255                 {
00256                     this.inputDeviceMessages.Items.Add(outputMessage + "\n");
00257                     this.inputDeviceMessages.ScrollIntoView(this.inputDeviceMessages.Items[this.inputDeviceMessages.Items.Count - 1]);
00258                     this.rootPage.NotifyUser("Message received successfully!", NotifyType.StatusMessage);
00259                 }
00260             });
00261         }
00262     }
00263 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RemoteSystems/cs/SampleConfiguration.cs Source File

  • RemoteSystems
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Collections.ObjectModel;
00015 using Windows.System.RemoteSystems;
00016 using Windows.UI.Xaml.Controls;
00017
00018 namespace SDKTemplate
00019 {
00020     public partial class MainPage : Page
00021     {
00022         public const string FEATURE_NAME = "RemoteSystems C# Sample";
00023
00024         List<Scenario> scenarios = new List<Scenario>
00025         {
00026             new Scenario() { Title="Discovery", ClassType=typeof(Scenario1_Discovery)},
00027             new Scenario() { Title="Launch URI", ClassType=typeof(Scenario2_LaunchUri)},
00028             new Scenario() { Title="Launch App Services", ClassType=typeof(Scenario3_LaunchAppServices)},
00029             new Scenario() { Title="Settings", ClassType=typeof(Scenario4_Settings)},
00030             new Scenario() { Title="Capabilities", ClassType=typeof(Scenario5_Capabilities)}
00031         };
00032
00033         public ObservableCollection<RemoteSystem> systemList = null;
00034         public Dictionary<string, RemoteSystem> systemMap = null;
00035
00036         /// <summary>
00037         /// Checks if the system discovery has been performed and systems have been found.
00038         /// </summary>
00039         internal bool ValidateSystemDiscovery()
00040         {
00041             if (systemList == null)
00042             {
00043                 NotifyUser("System discovery has not been performed. Use scenario one to discover systems.", NotifyType.ErrorMessage);
00044                 return false;
00045             }
00046             else if (systemList.Count == 0)
00047             {
00048                 NotifyUser("No systems have been found. Use scenario one to discover systems.", NotifyType.ErrorMessage);
00049                 return false;
00050             }
00051
00052             return true;
00053         }
00054     }
00055
00056     public class Scenario
00057     {
00058         public string Title { get; set; }
00059         public Type ClassType { get; set; }
00060     }
00061 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/xBindSampleModel/ColorToStringConverter.cs Source File

  • XamlBind
  • cs
  • xBindSampleModel

ColorToStringConverter.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI;
00003 using Windows.UI.Xaml;
00004 using Windows.UI.Xaml.Data;
00005
00006
00007 namespace xBindSampleModel
00008 {
00009     public sealed class ColorToStringConverter : IValueConverter
00010     {
00011         static string[] colorNames = { "AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenrod", "DarkGray", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "DarkOrange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DodgerBlue", "Firebrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "Goldenrod", "Gray", "Green", "GreenYellow", "Honeydew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenrodYellow", "LightGray", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquamarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenrod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Transparent", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen" };
00012         static Color[] colorValues = { Colors.AliceBlue, Colors.AntiqueWhite, Colors.Aqua, Colors.Aquamarine, Colors.Azure, Colors.Beige, Colors.Bisque, Colors.Black, Colors.BlanchedAlmond, Colors.Blue, Colors.BlueViolet, Colors.Brown, Colors.BurlyWood, Colors.CadetBlue, Colors.Chartreuse, Colors.Chocolate, Colors.Coral, Colors.CornflowerBlue, Colors.Cornsilk, Colors.Crimson, Colors.Cyan, Colors.DarkBlue, Colors.DarkCyan, Colors.DarkGoldenrod, Colors.DarkGray, Colors.DarkGreen, Colors.DarkKhaki, Colors.DarkMagenta, Colors.DarkOliveGreen, Colors.DarkOrange, Colors.DarkOrchid, Colors.DarkRed, Colors.DarkSalmon, Colors.DarkSeaGreen, Colors.DarkSlateBlue, Colors.DarkSlateGray, Colors.DarkTurquoise, Colors.DarkViolet, Colors.DeepPink, Colors.DeepSkyBlue, Colors.DimGray, Colors.DodgerBlue, Colors.Firebrick, Colors.FloralWhite, Colors.ForestGreen, Colors.Fuchsia, Colors.Gainsboro, Colors.GhostWhite, Colors.Gold, Colors.Goldenrod, Colors.Gray, Colors.Green, Colors.GreenYellow, Colors.Honeydew, Colors.HotPink, Colors.IndianRed, Colors.Indigo, Colors.Ivory, Colors.Khaki, Colors.Lavender, Colors.LavenderBlush, Colors.LawnGreen, Colors.LemonChiffon, Colors.LightBlue, Colors.LightCoral, Colors.LightCyan, Colors.LightGoldenrodYellow, Colors.LightGray, Colors.LightGreen, Colors.LightPink, Colors.LightSalmon, Colors.LightSeaGreen, Colors.LightSkyBlue, Colors.LightSlateGray, Colors.LightSteelBlue, Colors.LightYellow, Colors.Lime, Colors.LimeGreen, Colors.Linen, Colors.Magenta, Colors.Maroon, Colors.MediumAquamarine, Colors.MediumBlue, Colors.MediumOrchid, Colors.MediumPurple, Colors.MediumSeaGreen, Colors.MediumSlateBlue, Colors.MediumSpringGreen, Colors.MediumTurquoise, Colors.MediumVioletRed, Colors.MidnightBlue, Colors.MintCream, Colors.MistyRose, Colors.Moccasin, Colors.NavajoWhite, Colors.Navy, Colors.OldLace, Colors.Olive, Colors.OliveDrab, Colors.Orange, Colors.OrangeRed, Colors.Orchid, Colors.PaleGoldenrod, Colors.PaleGreen, Colors.PaleTurquoise, Colors.PaleVioletRed, Colors.PapayaWhip, Colors.PeachPuff, Colors.Peru, Colors.Pink, Colors.Plum, Colors.PowderBlue, Colors.Purple, Colors.Red, Colors.RosyBrown, Colors.RoyalBlue, Colors.SaddleBrown, Colors.Salmon, Colors.SandyBrown, Colors.SeaGreen, Colors.SeaShell, Colors.Sienna, Colors.Silver, Colors.SkyBlue, Colors.SlateBlue, Colors.SlateGray, Colors.Snow, Colors.SpringGreen, Colors.SteelBlue, Colors.Tan, Colors.Teal, Colors.Thistle, Colors.Tomato, Colors.Transparent, Colors.Turquoise, Colors.Violet, Colors.Wheat, Colors.White, Colors.WhiteSmoke, Colors.Yellow, Colors.YellowGreen };
00013
00014         public object Convert(object value, Type targetType, object parameter, string language)
00015         {
00016             Color src = (Color)value;
00017             for (int i = 0; i < colorValues.Length; i++)
00018             {
00019                 if (src == colorValues[i])
00020                 {
00021                     return colorNames[i];
00022                 }
00023             }
00024             return string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", src.A, src.R, src.G, src.B);
00025         }
00026
00027         public object ConvertBack(object value, Type targetType, object parameter, string language)
00028         {
00029             string src = (string)value;
00030             for (int i = 0; i < colorValues.Length; i++)
00031             {
00032                 if (src == colorNames[i])
00033                 {
00034                     return colorValues[i];
00035                 }
00036             }
00037             if (src.StartsWith("#"))
00038             {
00039                 return Color.FromArgb(Byte.Parse(src.Substring(1, 2), System.Globalization.NumberStyles.HexNumber),
00040                     Byte.Parse(src.Substring(3, 2), System.Globalization.NumberStyles.HexNumber),
00041                     Byte.Parse(src.Substring(5, 2), System.Globalization.NumberStyles.HexNumber),
00042                     Byte.Parse(src.Substring(7, 2), System.Globalization.NumberStyles.HexNumber));
00043             }
00044             throw new ArgumentException("Cannot parse the color");
00045         }
00046     }
00047 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GeofenceBackgroundTask Member List

This is the complete list of members for GeofenceBackgroundTask, including all inherited members.
_values | GeofenceBackgroundTask | [private]
GenerateReportDescription(GeofenceStateChangeReport report) | GeofenceBackgroundTask | [inline, private]
maxEventDescriptors | GeofenceBackgroundTask | [private]
ProcessGeofenceStateChangedReports() | GeofenceBackgroundTask | [inline, private]
Run(IBackgroundTaskInstance taskInstance) | GeofenceBackgroundTask | [inline, private]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5 Member List

This is the complete list of members for Scenario5, including all inherited members.
AddPort_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario5 | [inline, private]
AddSocket(SocketWrapper socket) | Scenario5 | [inline]
DoSend_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario5 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario5 | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario5 | [inline, protected]
RemoveSocket(int index) | Scenario5 | [inline]
rootPage | Scenario5 | [private]
Scenario5() | Scenario5 | [inline]
session | Scenario5 | [private]
thisLock | Scenario5 | [private]
Generated on Fri Nov 15 2024 22:24:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cpp/SampleConfiguration.cpp Source File

  • BasicInput
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Scenario 1", "SDKTemplate.Scenario1" },
00021     { "Scenario 2", "SDKTemplate.Scenario2" },
00022     { "Scenario 3", "SDKTemplate.Scenario3" },
00023     { "Scenario 4", "SDKTemplate.Scenario4" },
00024     { "Scenario 5", "SDKTemplate.Scenario5" }
00025 };
Generated on Fri Nov 15 2024 22:17:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LibraryManagement/cpp/S1_AddFolder.xaml.h Source File

  • LibraryManagement
  • cpp

S1_AddFolder.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1.xaml.h
00014 // Declaration of the Scenario1 class
00015 //
00016
00017 #pragma once
00018 #include "S1_AddFolder.g.h"
00019
00020 namespace SDKTemplate
00021 {
00022     public ref class Scenario1 sealed
00023     {
00024     public:
00025         Scenario1();
00026
00027     private:
00028         void AddFolderButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029     };
00030 }
Generated on Fri Nov 15 2024 22:20:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PosPrinter/cpp/Scenario1_ReceiptPrinter.xaml.h Source File

  • PosPrinter
  • cpp

Scenario1_ReceiptPrinter.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_ReceiptPrinter.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace Windows::Devices::PointOfService;
00018 using namespace Windows::UI::Xaml;
00019 using namespace Concurrency;
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026     [Windows::Foundation::Metadata::WebHostHidden]
00027     public ref class Scenario1_ReceiptPrinter sealed
00028     {
00029     public:
00030         Scenario1_ReceiptPrinter();
00031
00032     protected:
00033         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00034         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035
00036     private:
00037         MainPage^ rootPage;
00038         PosPrinter^ printer;
00039         ClaimedPosPrinter^ claimedPrinter;
00040         bool IsAnImportantTransaction = true;
00041         Windows::Foundation::EventRegistrationToken releaseDeviceRequestedToken;
00042
00043         task<void> FindReceiptPrinter();
00044         void ClaimedPrinter_ReleaseDeviceRequested(ClaimedPosPrinter ^claimedInstance, PosPrinterReleaseDeviceRequestedEventArgs ^args);
00045
00046         void FindClaimEnable_Click(Platform::Object^ sender, RoutedEventArgs^ e);
00047         void PrintLine_Click(Platform::Object^ sender, RoutedEventArgs e);
00048         void PrintReceipt_Click(Platform::Object^ sender, RoutedEventArgs e);
00049         void EndScenario_Click(Platform::Object^ sender, RoutedEventArgs e);
00050
00051         void ResetTheScenarioState();
00052         Platform::String^ GetMerchantFooter();
00053         Platform::String^ GetCustomerFooter();
00054         void PrintLineFeedAndCutPaper(ReceiptPrintJob^ job, Platform::String^ receipt);
00055
00056         task<void> ClaimPrinter();
00057         task<void> EnableAsync();
00058         void PrintReceipt();
00059
00060     };
00061 }
Generated on Fri Nov 15 2024 22:20:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AuthenticationTask Member List

This is the complete list of members for AuthenticationTask, including all inherited members.
_cancelRequested | AuthenticationTask | [private]
_context | AuthenticationTask | [private]
_details | AuthenticationTask | [private]
_foregroundAppId | AuthenticationTask | [private]
AuthenticateInBackgroundAsync() | AuthenticationTask | [inline, private]
ContinueAuthenticationInForeground() | AuthenticationTask | [inline, private]
OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) | AuthenticationTask | [inline, private]
Run(IBackgroundTaskInstance taskInstance) | AuthenticationTask | [inline]
RunAsync() | AuthenticationTask | [inline, private]
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_EdgeTappedListView Member List

This is the complete list of members for Scenario4_EdgeTappedListView, including all inherited members.
AddItem(object sender, RoutedEventArgs e) | Scenario4_EdgeTappedListView | [inline, private]
CancelSelection(object sender, RoutedEventArgs e) | Scenario4_EdgeTappedListView | [inline, private]
Contacts | Scenario4_EdgeTappedListView | [private]
OnBackRequested(object sender, BackRequestedEventArgs e) | Scenario4_EdgeTappedListView | [inline, private]
OnEdgeTapped(ListView sender, ListViewEdgeTappedEventArgs e) | Scenario4_EdgeTappedListView | [inline, private]
OnNavigatedFrom(Windows.UI.Xaml.Navigation.NavigationEventArgs e) | Scenario4_EdgeTappedListView | [inline, protected]
OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e) | Scenario4_EdgeTappedListView | [inline, protected]
OnSelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario4_EdgeTappedListView | [inline, private]
RemoveItem(object sender, RoutedEventArgs e) | Scenario4_EdgeTappedListView | [inline, private]
Scenario4_EdgeTappedListView() | Scenario4_EdgeTappedListView | [inline]
SelectItems(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario4_EdgeTappedListView | [inline, private]
SetCommandsVisibility(ListView listView) | Scenario4_EdgeTappedListView | [inline, private]
UpdateSelectionUI() | Scenario4_EdgeTappedListView | [inline, private]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/xBindSampleModel/DoubleToIntConverter.cs Source File

  • XamlBind
  • cs
  • xBindSampleModel

DoubleToIntConverter.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using Windows.UI.Xaml.Data;
00007
00008 namespace xBindSampleModel
00009 {
00010     public sealed class DoubleToIntConverter : IValueConverter
00011     {
00012         object IValueConverter.Convert(object value, Type targetType, object parameter, string language)
00013         {
00014             if (!value.GetType().Equals(typeof(double)))
00015             {
00016                 throw new ArgumentException("Only Double is supported");
00017             }
00018             if (targetType.Equals(typeof(Int32)))
00019             {
00020                 return (Int32)((double)value);
00021             }
00022             else if (targetType.Equals(typeof(UInt32)))
00023             {
00024                 return (UInt32)((double)value);
00025             }
00026             else
00027             {
00028                 throw new ArgumentException("Unsuported type {0}", targetType.FullName);
00029             }
00030         }
00031
00032         object IValueConverter.ConvertBack(object value, Type targetType, object parameter, string language)
00033         {
00034             return (double)((Int32)value);
00035         }
00036     }
00037
00038     public sealed class IntToDoubleConverter : IValueConverter
00039     {
00040         public object Convert(object value, Type targetType, object parameter, string language)
00041         {
00042             return (double)((Int32)value);
00043         }
00044
00045         public object ConvertBack(object value, Type targetType, object parameter, string language)
00046         {
00047             return (Int32)((double)value);
00048         }
00049     }
00050 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/MeshObject.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

MeshObject.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MeshObject.h"
00014 #include "ConstantBuffers.h"
00015
00016 MeshObject::MeshObject() :
00017     m_vertexCount(0),
00018     m_indexCount(0)
00019 {
00020 }
00021
00022 void MeshObject::Render(_In_ ID3D11DeviceContext* context)
00023 {
00024     uint32_t stride{ sizeof(PNTVertex) };
00025     uint32_t offset{ 0 };
00026
00027     ID3D11Buffer* vertexBuffer{ m_vertexBuffer.get() };
00028     context->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset);
00029     context->IASetIndexBuffer(m_indexBuffer.get(), DXGI_FORMAT_R16_UINT, 0);
00030     context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00031     context->DrawIndexed(m_indexCount, 0, 0);
00032 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundMediaPlayback/cs/ViewModels/MediaListViewModel.cs Source File

  • BackgroundMediaPlayback
  • cs
  • ViewModels

MediaListViewModel.cs

Go to the documentation of this file.
00001 ﻿using BackgroundMediaPlayback.DataModels;
00002 using System;
00003 using System.Collections.Generic;
00004 using System.Collections.ObjectModel;
00005 using System.Collections.Specialized;
00006 using System.ComponentModel;
00007 using System.Linq;
00008 using System.Text;
00009 using System.Threading.Tasks;
00010 using Windows.Media.Playback;
00011 using Windows.UI.Core;
00012
00013 namespace BackgroundMediaPlayback.ViewModels
00014 {
00015     /// <summary>
00016     /// View model for a list of media items.
00017     /// </summary>
00018     /// <remarks>
00019     /// The view model is backed by a data model (MediaList)
00020     /// and a playback model (MediaPlaybackList).
00021     ///
00022     /// This class currently supports TwoWay binding with the
00023     /// playback model so changes to the view model list also
00024     /// update the list of items scheduled for playback.
00025     ///
00026     /// Changes are not currently persisted back to or updated
00027     /// from the data model.
00028     ///
00029     /// This view model subscribes to events on the player
00030     /// and must unsubscribe before unloading the UI in
00031     /// background mode. Call Dispose() to initiate this.
00032     /// </remarks>
00033     public class MediaListViewModel : ObservableCollection<MediaItemViewModel>, IDisposable
00034     {
00035         CoreDispatcher dispatcher;
00036         int currentItemIndex = -1;
00037         bool disposed;
00038         bool initializing;
00039
00040         public MediaList MediaList { get; private set; }
00041
00042         public MediaItemViewModel CurrentItem
00043         {
00044             get { return currentItemIndex == -1 ? null : this[currentItemIndex]; }
00045             set
00046             {
00047                 if (value == null)
00048                 {
00049                     CurrentItemIndex = -1;
00050                     return;
00051                 }
00052
00053                 if (currentItemIndex == -1 || this[currentItemIndex] != value)
00054                 {
00055                     CurrentItemIndex = IndexOf(value);
00056                 }
00057             }
00058         }
00059
00060         public int CurrentItemIndex
00061         {
00062             get
00063             {
00064                 return currentItemIndex;
00065             }
00066             set
00067             {
00068                 if (currentItemIndex != value)
00069                 {
00070                     // Clamp invalid values
00071                     var min = -1;
00072                     var max = PlaybackList.Items.Count - 1;
00073                     currentItemIndex = (value < min) ? min : (value > max) ? max : value;
00074
00075                     try
00076                     {
00077                         // This succeeds if the playlist has been bound to a player
00078                         if (currentItemIndex >= 0 && currentItemIndex != PlaybackList.CurrentItemIndex)
00079                             PlaybackList.MoveTo((uint)currentItemIndex);
00080                     }
00081                     catch
00082                     {
00083                         // Most likely the playlist had not been bound to a player so set start index
00084                         PlaybackList.StartingItem = CurrentItem.PlaybackItem;
00085                     }
00086
00087                     OnPropertyChanged(new PropertyChangedEventArgs("CurrentItemIndex"));
00088                     OnPropertyChanged(new PropertyChangedEventArgs("CurrentItem"));
00089                 }
00090             }
00091         }
00092
00093         public MediaPlaybackList PlaybackList { get; private set; }
00094
00095         public MediaListViewModel(MediaList mediaList, MediaPlaybackList playbackList, CoreDispatcher dispatcher)
00096         {
00097             MediaList = mediaList;
00098             PlaybackList = playbackList;
00099             this.dispatcher = dispatcher;
00100
00101             // Verify consistency of the lists that were passed in
00102             var mediaListIds = mediaList.Select(i => i.ItemId);
00103             var playbackListIds = playbackList.Items.Select(
00104                 i => (string)i.Source.CustomProperties.SingleOrDefault(
00105                     p => p.Key == MediaItem.MediaItemIdKey).Value);
00106
00107             if (!mediaListIds.SequenceEqual(playbackListIds))
00108                 throw new ArgumentException("The passed in data model and playback model did not have the same sequence of items");
00109
00110             // Initialize the view model items
00111             initializing = true;
00112
00113             foreach (var mediaItem in mediaList)
00114                 Add(new MediaItemViewModel(this, mediaItem));
00115
00116             initializing = false;
00117
00118             // The view model supports TwoWay binding so update when the playback list item changes
00119             PlaybackList.CurrentItemChanged += PlaybackList_CurrentItemChanged;
00120
00121             // Start where the playback list is currently at
00122             CurrentItemIndex = (int)PlaybackList.CurrentItemIndex;
00123         }
00124
00125         protected override void InsertItem(int index, MediaItemViewModel item)
00126         {
00127             base.InsertItem(index, item);
00128
00129             // Don't add items during construction
00130             if (!initializing)
00131                 PlaybackList.Items.Add(item.PlaybackItem);
00132         }
00133
00134         protected override void ClearItems()
00135         {
00136             base.ClearItems();
00137
00138             PlaybackList.Items.Clear();
00139         }
00140
00141         protected override void RemoveItem(int index)
00142         {
00143             base.RemoveItem(index);
00144
00145             PlaybackList.Items.RemoveAt(index);
00146         }
00147
00148         protected override void SetItem(int index, MediaItemViewModel item)
00149         {
00150             base.SetItem(index, item);
00151
00152             PlaybackList.Items[index] = item.PlaybackItem;
00153         }
00154
00155         protected override void MoveItem(int oldIndex, int newIndex)
00156         {
00157             base.MoveItem(oldIndex, newIndex);
00158
00159             var item = PlaybackList.Items[oldIndex];
00160             PlaybackList.Items.RemoveAt(oldIndex);
00161             PlaybackList.Items.Insert(newIndex, item);
00162         }
00163
00164         /// <summary>
00165         /// This call comes in on a worker thread so requires a little extra care
00166         /// to avoid touching the UI if it has already been disposed.
00167         /// </summary>
00168         /// <param name="sender"></param>
00169         /// <param name="args"></param>
00170         private async void PlaybackList_CurrentItemChanged(MediaPlaybackList sender, CurrentMediaPlaybackItemChangedEventArgs args)
00171         {
00172             // If the event was unsubscribed before
00173             // this handler executed just return.
00174             if (disposed)
00175                 return;
00176
00177             await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00178             {
00179                 // If the event was unsubscribed before
00180                 // this handler executed just return.
00181                 if (disposed)
00182                     return;
00183
00184                 var playbackItem = args.NewItem;
00185
00186                 if (playbackItem == null)
00187                 {
00188                     CurrentItem = null;
00189                 }
00190                 else
00191                 {
00192                     // Find the single item in this list with a playback item
00193                     // matching the one we just received the event for.
00194                     CurrentItem = this.Single(mediaItemViewModel => mediaItemViewModel.PlaybackItem == playbackItem);
00195                 }
00196             });
00197         }
00198
00199         public void Dispose()
00200         {
00201             if (disposed)
00202                 return;
00203
00204             PlaybackList.CurrentItemChanged -= PlaybackList_CurrentItemChanged;
00205
00206             disposed = true;
00207         }
00208     }
00209 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboard/cs/Scenario3_ShowHideMethods.xaml.cs Source File

  • TouchKeyboard
  • cs

Scenario3_ShowHideMethods.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Input;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Sample page to call TryShow/TryHide methods.
00022     /// </summary>
00023     public sealed partial class Scenario3_ShowHideMethods : Page
00024     {
00025         public Scenario3_ShowHideMethods()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         protected override void OnNavigatedFrom(NavigationEventArgs e)
00031         {
00032             FadeOutResults.Stop();
00033         }
00034
00035         void WordListBox_OnKeyUp(object sender, KeyRoutedEventArgs e)
00036         {
00037             if (e.Key == Windows.System.VirtualKey.Enter)
00038             {
00039                 string text = WordListBox.Text;
00040                 if (text.Length > 0)
00041                 {
00042                     Windows.UI.ViewManagement.InputPane.GetForCurrentView().TryHide();
00043                     ResultsTextBlock.Text = text;
00044                     FadeOutResults.Begin();
00045                 }
00046             }
00047         }
00048
00049         void OnFadeOutCompleted(object sender, object e)
00050         {
00051             ResultsTextBlock.Text = "";
00052             Windows.UI.ViewManagement.InputPane.GetForCurrentView().TryShow();
00053         }
00054     }
00055 }
Generated on Fri Nov 15 2024 22:21:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialStage/cpp/Common/DirectXHelper.h Source File

  • HolographicSpatialStage
  • cpp
  • Common

DirectXHelper.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include <ppltasks.h>    // For create_task
00004
00005 namespace DX
00006 {
00007     inline void ThrowIfFailed(HRESULT hr)
00008     {
00009         if (FAILED(hr))
00010         {
00011             // Set a breakpoint on this line to catch Win32 API errors.
00012             throw Platform::Exception::CreateException(hr);
00013         }
00014     }
00015
00016     // Function that reads from a binary file asynchronously.
00017     inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename)
00018     {
00019         using namespace Windows::Storage;
00020         using namespace Concurrency;
00021
00022         return create_task(PathIO::ReadBufferAsync(Platform::StringReference(filename.c_str()))).then(
00023             [] (Streams::IBuffer^ fileBuffer) -> std::vector<byte>
00024             {
00025                 std::vector<byte> returnBuffer;
00026                 returnBuffer.resize(fileBuffer->Length);
00027                 Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), static_cast<unsigned int>(returnBuffer.size())));
00028                 return returnBuffer;
00029             });
00030     }
00031
00032     // Converts a length in device-independent pixels (DIPs) to a length in physical pixels.
00033     inline float ConvertDipsToPixels(float dips, float dpi)
00034     {
00035         constexpr float dipsPerInch = 96.0f;
00036         return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00037     }
00038
00039 #if defined(_DEBUG)
00040     // Check for SDK Layer support.
00041     inline bool SdkLayersAvailable()
00042     {
00043         HRESULT hr = D3D11CreateDevice(
00044             nullptr,
00045             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00046             0,
00047             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00048             nullptr,                    // Any feature level will do.
00049             0,
00050             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00051             nullptr,                    // No need to keep the D3D device reference.
00052             nullptr,                    // No need to know the feature level.
00053             nullptr                     // No need to keep the D3D device context reference.
00054             );
00055
00056         return SUCCEEDED(hr);
00057     }
00058 #endif
00059 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Level4.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Level4.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Level4:
00015 // This class defines the fourth level of the game. It derives from the
00016 // third level. The targets must be hit in numeric order.
00017
00018 #include "Level3.h"
00019
00020 class Level4 : public Level3
00021 {
00022 public:
00023     Level4();
00024     virtual void Initialize(std::vector<std::shared_ptr<GameObject>> const& objects) override;
00025
00026     virtual bool Update(
00027         float time,
00028         float elapsedTime,
00029         float timeRemaining,
00030         std::vector<std::shared_ptr<GameObject>> const& objects
00031         ) override;
00032
00033     virtual void SaveState(PersistentState& state) override;
00034     virtual void LoadState(PersistentState& state) override;
00035
00036 private:
00037     int m_nextId;
00038 };
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ShareHtml Member List

This is the complete list of members for ShareHtml, including all inherited members.
GetShareContent(DataRequest request) | ShareHtml | [inline, protected]
ShareHtml() | ShareHtml | [inline]
ShareWebView_NavigationCompleted(object sender, WebViewNavigationCompletedEventArgs e) | ShareHtml | [inline, private]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

UserViewModel Member List

This is the complete list of members for UserViewModel, including all inherited members.
DisplayName() | UserViewModel | [inline]
DisplayName(hstring displayName) | UserViewModel | [inline]
m_displayName | UserViewModel | [private]
m_propertyChanged | UserViewModel | [private]
m_userId | UserViewModel | [private]
PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const &handler) | UserViewModel | [inline]
PropertyChanged(event_token token) | UserViewModel | [inline]
RaisePropertyChanged(hstring propertyName) | UserViewModel | [inline, private]
UserId() | UserViewModel | [inline]
UserId(hstring userId) | UserViewModel | [inline]
UserViewModel(hstring userId, hstring displayName) | UserViewModel | [inline]
Generated on Fri Nov 15 2024 22:24:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/AppView.cpp Source File

  • SpatialInteractionSource
  • cpp

AppView.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
00002 #include "AppView.h"
00003
00004 #include <ppltasks.h>
00005
00006 using namespace HolographicPaint;
00007
00008 using namespace concurrency;
00009 using namespace Windows::ApplicationModel;
00010 using namespace Windows::ApplicationModel::Activation;
00011 using namespace Windows::ApplicationModel::Core;
00012 using namespace Windows::Foundation;
00013 using namespace Windows::Graphics::Holographic;
00014 using namespace Windows::UI::Core;
00015
00016 // The main function is only used to initialize our IFrameworkView class.
00017 // Under most circumstances, you should not need to modify this function.
00018 [Platform::MTAThread]
00019 int main(Platform::Array<Platform::String^>^)
00020 {
00021     AppViewSource^ appViewSource = ref new ::AppViewSource();
00022     CoreApplication::Run(appViewSource);
00023     return 0;
00024 }
00025
00026 IFrameworkView^ AppViewSource::CreateView()
00027 {
00028     return ref new AppView();
00029 }
00030
00031 AppView::AppView()
00032 {
00033 }
00034
00035
00036 // IFrameworkView methods
00037
00038 // The first method called when the IFrameworkView is being created.
00039 // Use this method to subscribe for Windows shell events and to initialize your app.
00040 void AppView::Initialize(CoreApplicationView^ applicationView)
00041 {
00042     applicationView->Activated +=
00043         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &AppView::OnViewActivated);
00044
00045     // Register event handlers for app lifecycle.
00046     CoreApplication::Suspending +=
00047         ref new EventHandler<SuspendingEventArgs^>(this, &AppView::OnSuspending);
00048
00049     CoreApplication::Resuming +=
00050         ref new EventHandler<Platform::Object^>(this, &AppView::OnResuming);
00051
00052     // At this point we have access to the device and we can create device-dependent
00053     // resources.
00054     m_deviceResources = std::make_shared<DX::DeviceResources>();
00055
00056     m_main = std::make_unique<HolographicPaintMain>(m_deviceResources);
00057 }
00058
00059 // Called when the CoreWindow object is created (or re-created).
00060 void AppView::SetWindow(CoreWindow^ window)
00061 {
00062     // Register for keypress notifications.
00063     window->KeyDown +=
00064         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &AppView::OnKeyPressed);
00065
00066     // Register for notification that the app window is being closed.
00067     window->Closed +=
00068         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &AppView::OnWindowClosed);
00069
00070     // Register for notifications that the app window is losing focus.
00071     window->VisibilityChanged +=
00072         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &AppView::OnVisibilityChanged);
00073
00074     // Create a holographic space for the core window for the current view.
00075     // Presenting holographic frames that are created by this holographic space will put
00076     // the app into exclusive mode.
00077     m_holographicSpace = HolographicSpace::CreateForCoreWindow(window);
00078
00079     // The DeviceResources class uses the preferred DXGI adapter ID from the holographic
00080     // space (when available) to create a Direct3D device. The HolographicSpace
00081     // uses this ID3D11Device to create and manage device-based resources such as
00082     // swap chains.
00083     m_deviceResources->SetHolographicSpace(m_holographicSpace);
00084
00085     // The main class uses the holographic space for updates and rendering.
00086     m_main->SetHolographicSpace(m_holographicSpace);
00087 }
00088
00089 // The Load method can be used to initialize scene resources or to load a
00090 // previously saved app state.
00091 void AppView::Load(Platform::String^ entryPoint)
00092 {
00093 }
00094
00095 // This method is called after the window becomes active. It oversees the
00096 // update, draw, and present loop, and it also oversees window message processing.
00097 void AppView::Run()
00098 {
00099     while (!m_windowClosed)
00100     {
00101         if (m_windowVisible && (m_holographicSpace != nullptr))
00102         {
00103             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00104
00105             HolographicFrame^ holographicFrame = m_main->Update();
00106
00107             if (m_main->Render(holographicFrame))
00108             {
00109                 // The holographic frame has an API that presents the swap chain for each
00110                 // holographic camera.
00111                 m_deviceResources->Present(holographicFrame);
00112             }
00113         }
00114         else
00115         {
00116             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00117         }
00118     }
00119 }
00120
00121 // Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
00122 // class is torn down while the app is in the foreground.
00123 // This method is not often used, but IFrameworkView requires it and it will be called for
00124 // holographic apps.
00125 void AppView::Uninitialize()
00126 {
00127 }
00128
00129
00130 // Application lifecycle event handlers
00131
00132 // Called when the app view is activated. Activates the app's CoreWindow.
00133 void AppView::OnViewActivated(CoreApplicationView^ sender, IActivatedEventArgs^ args)
00134 {
00135     // Run() won't start until the CoreWindow is activated.
00136     sender->CoreWindow->Activate();
00137 }
00138
00139 void AppView::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
00140 {
00141     // Save app state asynchronously after requesting a deferral. Holding a deferral
00142     // indicates that the application is busy performing suspending operations. Be
00143     // aware that a deferral may not be held indefinitely; after about five seconds,
00144     // the app will be forced to exit.
00145     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
00146
00147     create_task([this, deferral] ()
00148     {
00149         m_deviceResources->Trim();
00150
00151         deferral->Complete();
00152     });
00153 }
00154
00155 void AppView::OnResuming(Platform::Object^ sender, Platform::Object^ args)
00156 {
00157 }
00158
00159
00160 // Window event handlers
00161
00162 void AppView::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
00163 {
00164     m_windowVisible = args->Visible;
00165 }
00166
00167 void AppView::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
00168 {
00169     m_windowClosed = true;
00170 }
00171
00172
00173 // Input event handlers
00174
00175 void AppView::OnKeyPressed(CoreWindow^ sender, KeyEventArgs^ args)
00176 {
00177 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OrientationSensor/cs/SampleConfiguration.cs Source File

  • OrientationSensor
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Devices.Sensors;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Orientation Sensor C# Sample";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title = "Choose orientation sensor", ClassType = typeof(Scenario0_Choose) },
00026             new Scenario() { Title = "Data Events", ClassType = typeof(Scenario1_DataEvents) },
00027             new Scenario() { Title = "Polling", ClassType = typeof(Scenario2_Polling) },
00028             new Scenario() { Title = "Calibration", ClassType = typeof(Scenario3_Calibration) }
00029         };
00030
00031         public static void SetReadingText(TextBlock textBlock, OrientationSensorReading reading)
00032         {
00033             SensorQuaternion quaternion = reading.Quaternion;    // get a reference to the object to avoid re-creating it for each access
00034             string quaternionReport = string.Format("W: {0,5:0.00}, X: {1,5:0.00}, Y: {2,5:0.00}, Z: {3,5:0.00}",
00035                 quaternion.W, quaternion.X, quaternion.Y, quaternion.Z);
00036
00037             SensorRotationMatrix rotationMatrix = reading.RotationMatrix;
00038             string rotationMatrixReport = string.Format(
00039                 "M11: {0,5:0.00}, M12: {1,5:0.00}, M13: {2,5:0.00}\n" +
00040                 "M21: {3,5:0.00}, M22: {4,5:0.00}, M23: {5,5:0.00}\n" +
00041                 "M31: {6,5:0.00}, M32: {7,5:0.00}, M33: {8,5:0.00}",
00042                 rotationMatrix.M11, rotationMatrix.M12, rotationMatrix.M13,
00043                 rotationMatrix.M21, rotationMatrix.M22, rotationMatrix.M23,
00044                 rotationMatrix.M31, rotationMatrix.M32, rotationMatrix.M33);
00045
00046             string yawAccuracyReport;
00047             switch (reading.YawAccuracy)
00048             {
00049                 case MagnetometerAccuracy.Unknown:
00050                     yawAccuracyReport = "unknown";
00051                     break;
00052                 case MagnetometerAccuracy.Unreliable:
00053                     yawAccuracyReport = "unreliable";
00054                     break;
00055                 case MagnetometerAccuracy.Approximate:
00056                     yawAccuracyReport = "approximate";
00057                     break;
00058                 case MagnetometerAccuracy.High:
00059                     yawAccuracyReport = "high";
00060                     break;
00061                 default:
00062                     yawAccuracyReport = "other";
00063                     break;
00064             }
00065
00066             textBlock.Text = "Quaternion:\n" + quaternionReport + "\n\n" +
00067                 "Rotation Matrix:\n" + rotationMatrixReport + "\n\n" +
00068                 "Yaw Accuracy:\n" + yawAccuracyReport;
00069         }
00070
00071         public SensorReadingType SensorReadingType { get; set; } = SensorReadingType.Absolute;
00072
00073         public SensorOptimizationGoal SensorOptimizationGoal { get; set; } = SensorOptimizationGoal.Precision;
00074
00075         public string SensorDescription
00076         {
00077             get
00078             {
00079                 return SensorReadingType + " orientation sensor with " + SensorOptimizationGoal + " optimization goal";
00080             }
00081         }
00082     }
00083
00084     public class Scenario
00085     {
00086         public string Title { get; set; }
00087         public Type ClassType { get; set; }
00088     }
00089 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cs/Scenario3.xaml.cs Source File

  • FileThumbnails
  • cs

Scenario3.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Storage;
00014 using Windows.Storage.FileProperties;
00015 using Windows.Storage.Pickers;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario3 : Page
00023     {
00024         MainPage rootPage = MainPage.Current;
00025
00026         public Scenario3()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         protected override void OnNavigatedTo(NavigationEventArgs e)
00032         {
00033             rootPage.ResetOutput(ThumbnailImage, OutputTextBlock);
00034         }
00035
00036         private async void GetThumbnailButton_Click(object sender, RoutedEventArgs e)
00037         {
00038             rootPage.ResetOutput(ThumbnailImage, OutputTextBlock);
00039
00040             // Pick a document
00041             FileOpenPicker openPicker = new FileOpenPicker();
00042             foreach (string extension in FileExtensions.Document)
00043             {
00044                 openPicker.FileTypeFilter.Add(extension);
00045             }
00046
00047             StorageFile file = await openPicker.PickSingleFileAsync();
00048             if (file != null)
00049             {
00050                 const ThumbnailMode thumbnailMode = ThumbnailMode.DocumentsView;
00051                 const uint size = 100;
00052                 using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(thumbnailMode, size))
00053                 {
00054                     if (thumbnail != null)
00055                     {
00056                         MainPage.DisplayResult(ThumbnailImage, OutputTextBlock, thumbnailMode.ToString(), size, file, thumbnail, false);
00057                     }
00058                     else
00059                     {
00060                         rootPage.NotifyUser(Errors.NoIcon, NotifyType.StatusMessage);
00061                     }
00062                 }
00063             }
00064             else
00065             {
00066                 rootPage.NotifyUser(Errors.Cancel, NotifyType.StatusMessage);
00067             }
00068
00069         }
00070     }
00071 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cs/Scenario5_UserCollection.xaml.cs Source File

  • Store
  • cs

Scenario5_UserCollection.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Services.Store;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario5_UserCollection : Page
00020     {
00021         MainPage rootPage = MainPage.Current;
00022         private StoreContext storeContext = StoreContext.GetDefault();
00023
00024         public Scenario5_UserCollection()
00025         {
00026             this.InitializeComponent();
00027         }
00028
00029         private async void GetUserCollectionButton_Click(object sender, RoutedEventArgs e)
00030         {
00031             // Create a filtered list of the product AddOns I care about
00032             string[] filterList = new string[] { "Consumable", "Durable", "UnmanagedConsumable" };
00033
00034             // Get user collection for this product, filtering for the types we know about
00035             StoreProductQueryResult collection = await storeContext.GetUserCollectionAsync(filterList);
00036
00037             ProductsListView.ItemsSource = Utils.CreateProductListFromQueryResult(collection, "collection items");
00038         }
00039     }
00040 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RealtimeSurfaceMeshRenderer Member List

This is the complete list of members for RealtimeSurfaceMeshRenderer, including all inherited members.
AddOrUpdateSurfaceAsync(Platform::Guid id, Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^newSurface) | RealtimeSurfaceMeshRenderer | [private]
AddSurface(Platform::Guid id, Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^newSurface) | RealtimeSurfaceMeshRenderer |
c_maxInactiveMeshTime | RealtimeSurfaceMeshRenderer | [private]
c_surfaceMeshFadeInTime | RealtimeSurfaceMeshRenderer | [private]
ClearSurfaces() | RealtimeSurfaceMeshRenderer |
CreateDeviceDependentResources() | RealtimeSurfaceMeshRenderer |
GetLastUpdateTime(Platform::Guid id) | RealtimeSurfaceMeshRenderer |
HasSurface(Platform::Guid id) | RealtimeSurfaceMeshRenderer |
HideInactiveMeshes(Windows::Foundation::Collections::IMapView< Platform::Guid, Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^>^const &surfaceCollection) | RealtimeSurfaceMeshRenderer |
m_colorPixelShader | RealtimeSurfaceMeshRenderer | [private]
m_defaultRasterizerState | RealtimeSurfaceMeshRenderer | [private]
m_deviceResources | RealtimeSurfaceMeshRenderer | [private]
m_geometryShader | RealtimeSurfaceMeshRenderer | [private]
m_inputLayout | RealtimeSurfaceMeshRenderer | [private]
m_lightingPixelShader | RealtimeSurfaceMeshRenderer | [private]
m_loadingComplete | RealtimeSurfaceMeshRenderer | [private]
m_maxTrianglesPerCubicMeter | RealtimeSurfaceMeshRenderer | [private]
m_meshCollection | RealtimeSurfaceMeshRenderer | [private]
m_meshCollectionLock | RealtimeSurfaceMeshRenderer | [private]
m_surfaceMeshCount | RealtimeSurfaceMeshRenderer | [private]
m_usingVprtShaders | RealtimeSurfaceMeshRenderer | [private]
m_vertexShader | RealtimeSurfaceMeshRenderer | [private]
m_wireframeRasterizerState | RealtimeSurfaceMeshRenderer | [private]
RealtimeSurfaceMeshRenderer(const std::shared_ptr< DX::DeviceResources > &deviceResources) | RealtimeSurfaceMeshRenderer |
ReleaseDeviceDependentResources() | RealtimeSurfaceMeshRenderer |
RemoveSurface(Platform::Guid id) | RealtimeSurfaceMeshRenderer |
Render(bool isStereo, bool useWireframe) | RealtimeSurfaceMeshRenderer |
Update(DX::StepTimer const &timer, Windows::Perception::Spatial::SpatialCoordinateSystem^coordinateSystem) | RealtimeSurfaceMeshRenderer |
UpdateSurface(Platform::Guid id, Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo^newSurface) | RealtimeSurfaceMeshRenderer |
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cpp/WiFiDirectServicesWrappers.cpp Source File

  • WiFiDirectServices
  • cpp

WiFiDirectServicesWrappers.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "WiFiDirectServicesWrappers.h"
00014 #include <iomanip>
00015
00016 using namespace SDKTemplate::WiFiDirectServices;
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Devices::Enumeration;
00020 using namespace Windows::Devices::WiFiDirect::Services;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Networking::Sockets;
00023 using namespace Windows::Storage::Streams;
00024 using namespace Windows::Security::Cryptography;
00025 using namespace Windows::UI::Core;
00026 using namespace std;
00027
00028 int AdvertisementWrapper::_nextId = 1;
00029
00030 AdvertisementWrapper::AdvertisementWrapper(
00031     WiFiDirectServiceAdvertiser ^ advertiser,
00032     WiFiDirectServiceManager ^ manager,
00033     String ^ pin
00034     ) : _advertiser(advertiser),
00035         _manager(manager),
00036         _pin(pin),
00037         _uniqueInternalId(_nextId++)
00038 {
00039     _advertisementStatusChangedToken = _advertiser->AdvertisementStatusChanged += ref new TypedEventHandler<WiFiDirectServiceAdvertiser^, Object^>(
00040         this,
00041         &AdvertisementWrapper::OnAdvertisementStatusChanged
00042         );
00043     _autoAcceptSessionConnectedToken = _advertiser->AutoAcceptSessionConnected += ref new TypedEventHandler<WiFiDirectServiceAdvertiser^, WiFiDirectServiceAutoAcceptSessionConnectedEventArgs^>(
00044         this,
00045         &AdvertisementWrapper::OnAutoAcceptSessionConnected
00046         );
00047     _sessionRequestedToken = _advertiser->SessionRequested += ref new TypedEventHandler<WiFiDirectServiceAdvertiser^, WiFiDirectServiceSessionRequestedEventArgs^>(
00048         this,
00049         &AdvertisementWrapper::OnSessionRequested
00050         );
00051 }
00052
00053 AdvertisementWrapper::~AdvertisementWrapper()
00054 {
00055     // Stop advertising
00056     // If for some reason the advertiser is stopping between the time that we check
00057     // the AdvertisementStatus and when we call Stop, this will throw
00058     try
00059     {
00060         if (_advertiser->AdvertisementStatus == WiFiDirectServiceAdvertisementStatus::Started)
00061         {
00062             _advertiser->Stop();
00063         }
00064     }
00065     catch (Exception^)
00066     {
00067         // Stop can throw if it is already stopped or stopping, ignore
00068     }
00069
00070     // Remove event handlers
00071     _advertiser->AdvertisementStatusChanged -= _advertisementStatusChangedToken;
00072     _advertiser->AutoAcceptSessionConnected -= _autoAcceptSessionConnectedToken;
00073     _advertiser->SessionRequested -= _sessionRequestedToken;
00074
00075     _requestList->Clear();
00076 }
00077
00078 void AdvertisementWrapper::AcceptSessionRequest(Platform::String ^ id, Platform::String ^ pin)
00079 {
00080     WiFiDirectServiceSessionRequest^ request = nullptr;
00081     bool found = false;
00082     unsigned int index = 0;
00083
00084     {
00085         lock_guard<mutex> lock(_advertiserMutex);
00086         for (auto&& r : _requestList)
00087         {
00088             if (r->DeviceInformation->Id == id)
00089             {
00090                 found = true;
00091                 request = r;
00092                 break;
00093             }
00094             ++index;
00095         }
00096
00097         if (!found)
00098         {
00099             throw ref new OutOfBoundsException("Attempted to accept session not found in list");
00100         }
00101
00102         _requestList->RemoveAt(index);
00103     }
00104     _manager->RemoveSessionRequest(request, this);
00105
00106     task<WiFiDirectServiceSession^> sessionTask;
00107     String^ pinForConnect = pin;
00108
00109     // Determine if a PIN is needed
00110     if (request->ProvisioningInfo->IsGroupFormationNeeded &&
00111         request->ProvisioningInfo->SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod::PinDisplay)
00112     {
00113         // This means the advertiser should display a PIN and the seeker will look at the display and enter the same PIN
00114         // The PIN may be randomly generated now, but for this sample, we configure a PIN when starting the advertiser
00115         pinForConnect = _pin;
00116     }
00117     else if (request->ProvisioningInfo->IsGroupFormationNeeded &&
00118         request->ProvisioningInfo->SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod::PinEntry)
00119     {
00120         // This means that the seeker should display a PIN and the advertiser will need to look at that display and enter the same PIN
00121         if (pin->Length() == 0)
00122         {
00123             throw ref new InvalidArgumentException("Expected PIN for connection, not provided");
00124         }
00125         pinForConnect = pin;
00126     }
00127     else
00128     {
00129         // PIN not needed, do not pass into connect
00130         pinForConnect = "";
00131     }
00132
00133     _manager->NotifyUser("Accepting session request...", NotifyType::StatusMessage);
00134
00135     if (pinForConnect->Length() > 0)
00136     {
00137         // NOTE: ConnectAsync MUST be called from the UI thread
00138         sessionTask = create_task(_advertiser->ConnectAsync(request->DeviceInformation, pinForConnect), task_continuation_context::use_current());
00139     }
00140     else
00141     {
00142         // NOTE: ConnectAsync MUST be called from the UI thread
00143         sessionTask = create_task(_advertiser->ConnectAsync(request->DeviceInformation), task_continuation_context::use_current());
00144     }
00145
00146     sessionTask.then( [this](WiFiDirectServiceSession^ session)
00147     {
00148         _manager->NotifyUser("Session request accepted", NotifyType::StatusMessage);
00149
00150         SessionWrapper^ sessionWrapper = ref new SessionWrapper(session, _manager);
00151         _manager->AddSession(sessionWrapper);
00152     }, task_continuation_context::use_current()).then( [this](task<void> finalTask)
00153     {
00154         try
00155         {
00156             // Rethrow exceptions from async task in case ConnectAsync failed
00157             finalTask.get();
00158         }
00159         catch (Exception^ ex)
00160         {
00161             _manager->NotifyUser("ConnectAsync Failed: " + ex->Message, NotifyType::ErrorMessage);
00162         }
00163     });
00164 }
00165
00166 void AdvertisementWrapper::DeclineSessionRequest(Platform::String ^ id)
00167 {
00168     WiFiDirectServiceSessionRequest^ request = nullptr;
00169     bool found = false;
00170     unsigned int index = 0;
00171
00172     {
00173         lock_guard<mutex> lock(_advertiserMutex);
00174         for (auto&& r : _requestList)
00175         {
00176             if (r->DeviceInformation->Id == id)
00177             {
00178                 found = true;
00179                 request = r;
00180                 break;
00181             }
00182             ++index;
00183         }
00184
00185         if (!found)
00186         {
00187             throw ref new OutOfBoundsException("Attempted to accept session not found in list");
00188         }
00189
00190         _requestList->RemoveAt(index);
00191     }
00192     _manager->RemoveSessionRequest(request, this);
00193
00194     // Decline incoming requests by deleting the request
00195     delete request;
00196     _manager->NotifyUser("Declined Request", NotifyType::StatusMessage);
00197 }
00198
00199 void AdvertisementWrapper::OnSessionRequested(
00200     WiFiDirectServiceAdvertiser^ sender,
00201     WiFiDirectServiceSessionRequestedEventArgs^ args
00202     )
00203 {
00204     try
00205     {
00206         _manager->NotifyUser("Received session request", NotifyType::StatusMessage);
00207
00208         String^ sessionInfo = "";
00209         if (args->GetSessionRequest()->SessionInfo != nullptr && args->GetSessionRequest()->SessionInfo->Length > 0)
00210         {
00211             DataReader^ sessionInfoDataReader = DataReader::FromBuffer(args->GetSessionRequest()->SessionInfo);
00212             sessionInfo = sessionInfoDataReader->ReadString(args->GetSessionRequest()->SessionInfo->Length);
00213             _manager->NotifyUser("Received Session Info: " + sessionInfo, NotifyType::StatusMessage);
00214         }
00215
00216         {
00217             lock_guard<mutex> lock(_advertiserMutex);
00218             _requestList->Append(args->GetSessionRequest());
00219         }
00220
00221         // Now we update the UI and wait for action to take (accept or decline)
00222         _manager->AddSessionRequest(args->GetSessionRequest(), this);
00223
00224         if (args->GetSessionRequest()->ProvisioningInfo->IsGroupFormationNeeded &&
00225             args->GetSessionRequest()->ProvisioningInfo->SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod::PinDisplay)
00226         {
00227             // This means the advertiser should display a PIN and the seeker will look at the display and enter the same PIN
00228             // The PIN may be randomly generated now, but for this sample, we configure a PIN when starting the advertiser
00229             _manager->NotifyUser("Remote side should enter PIN: " + _pin, NotifyType::StatusMessage);
00230         }
00231     }
00232     catch (Exception^ ex)
00233     {
00234         _manager->NotifyUser("OnSessionRequest Failed: " + ex->Message, NotifyType::ErrorMessage);
00235     }
00236 }
00237
00238 void AdvertisementWrapper::OnAutoAcceptSessionConnected(
00239     WiFiDirectServiceAdvertiser^ sender,
00240     WiFiDirectServiceAutoAcceptSessionConnectedEventArgs^ args
00241     )
00242 {
00243     try
00244     {
00245         String^ sessionInfo = "";
00246         if (args->SessionInfo != nullptr && args->SessionInfo->Length > 0)
00247         {
00248             DataReader^ sessionInfoDataReader = DataReader::FromBuffer(args->SessionInfo);
00249             sessionInfo = sessionInfoDataReader->ReadString(args->SessionInfo->Length);
00250             _manager->NotifyUser("Received Session Info: " + sessionInfo, NotifyType::StatusMessage);
00251         }
00252
00253         _manager->NotifyUser("Auto-Accept Session Connected: sessionInfo=" + sessionInfo, NotifyType::StatusMessage);
00254
00255         SessionWrapper^ sessionWrapper = ref new SessionWrapper(args->Session, _manager);
00256         _manager->AddSession(sessionWrapper);
00257     }
00258     catch (Exception^ ex)
00259     {
00260         _manager->NotifyUser("OnAutoAcceptSessionConnected Failed: " + ex->Message, NotifyType::ErrorMessage);
00261     }
00262 }
00263
00264 void AdvertisementWrapper::OnAdvertisementStatusChanged(
00265     WiFiDirectServiceAdvertiser^ sender,
00266     Object^ args
00267     )
00268 {
00269     try
00270     {
00271         WiFiDirectServiceAdvertisementStatus status = _advertiser->AdvertisementStatus;
00272
00273         _manager->NotifyUser("Advertisement Status Changed to " + status.ToString(), NotifyType::StatusMessage);
00274
00275         _manager->AdvertiserStatusChanged(this);
00276     }
00277     catch (Exception^ ex)
00278     {
00279         _manager->NotifyUser("OnAdvertisementStatusChanged Failed: " + ex->Message, NotifyType::ErrorMessage);
00280     }
00281 }
00282
00283 DiscoveredDeviceWrapper::DiscoveredDeviceWrapper(
00284     DeviceInformation^ deviceInfo,
00285     WiFiDirectServiceManager^ manager
00286     ) : _deviceInfo(deviceInfo),
00287         _manager(manager)
00288 {
00289     // Read properties from the DeviceInfo
00290     ParseProperties();
00291 }
00292
00293 SDKTemplate::WiFiDirectServices::DiscoveredDeviceWrapper::~DiscoveredDeviceWrapper()
00294 {
00295     if (_service != nullptr)
00296     {
00297         _service->SessionDeferred -= _sessionDeferredToken;
00298     }
00299 }
00300
00301 task<void> DiscoveredDeviceWrapper::OpenSessionAsync()
00302 {
00303     // This wrapper can only be used for FromIdAsync once
00304     if (_service != nullptr)
00305     {
00306         throw ref new ChangedStateException("Attempted to connect to discovered service a second time!");
00307     }
00308
00309     _manager->NotifyUser("Open session...", NotifyType::StatusMessage);
00310
00311     // NOTE: FromIdAsync MUST be called from the UI thread
00312     return create_task(WiFiDirectService::FromIdAsync(_deviceInfo->Id)).then( [this](WiFiDirectService^ service)
00313     {
00314         _service = service;
00315         _sessionDeferredToken = _service->SessionDeferred += ref new TypedEventHandler<WiFiDirectService^, WiFiDirectServiceSessionDeferredEventArgs^>(
00316             this,
00317             &DiscoveredDeviceWrapper::OnSessionDeferred
00318             );
00319     });
00320 }
00321
00322 task<void> DiscoveredDeviceWrapper::SetServiceOptionsAsync(bool preferGO, Platform::String ^ sessionInfo)
00323 {
00324     // Must call FromIdAsync first
00325     auto task = create_task([]() { return; });
00326     if (_service == nullptr)
00327     {
00328         task = OpenSessionAsync();
00329     }
00330
00331     return task.then( [this, preferGO, sessionInfo]()
00332     {
00333         _service->PreferGroupOwnerMode = preferGO;
00334
00335         if (sessionInfo != "")
00336         {
00337             auto sessionInfoDataWriter = ref new DataWriter(ref new InMemoryRandomAccessStream());
00338             sessionInfoDataWriter->WriteString(sessionInfo);
00339             _service->SessionInfo = sessionInfoDataWriter->DetachBuffer();
00340         }
00341         else
00342         {
00343             _service->SessionInfo = nullptr;
00344         }
00345     });
00346 }
00347
00348 task<WiFiDirectServiceProvisioningInfo^> DiscoveredDeviceWrapper::GetProvisioningInfoAsync(WiFiDirectServiceConfigurationMethod configMethod)
00349 {
00350     // Must call FromIdAsync first
00351     auto task = create_task([]() { return; });
00352     if (_service == nullptr)
00353     {
00354         task = OpenSessionAsync();
00355     }
00356
00357     return task.then([this, configMethod]()
00358     {
00359         _manager->NotifyUser("Get provisioning info...", NotifyType::StatusMessage);
00360
00361         return _service->GetProvisioningInfoAsync(configMethod);
00362     }).then( [this](WiFiDirectServiceProvisioningInfo^ provisioningInfo)
00363     {
00364         // Take some action based on provisioning info, such as displaying the PIN
00365         if (provisioningInfo->IsGroupFormationNeeded)
00366         {
00367             if (provisioningInfo->SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod::PinDisplay)
00368             {
00369                 // UI should display the PIN and pass it into the call to Connect
00370                 _manager->NotifyUser("Group Formation is needed, should DISPLAY PIN", NotifyType::StatusMessage);
00371             }
00372             else if (provisioningInfo->SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod::PinEntry)
00373             {
00374                 // UI should take PIN as input and pass it into the call to Connect
00375                 _manager->NotifyUser("Group Formation is needed, should ENTER PIN", NotifyType::StatusMessage);
00376             }
00377             else
00378             {
00379                 _manager->NotifyUser("Group Formation is needed, no PIN required", NotifyType::StatusMessage);
00380             }
00381         }
00382         else
00383         {
00384             _manager->NotifyUser("Group Formation is not needed", NotifyType::StatusMessage);
00385         }
00386         return provisioningInfo;
00387     });
00388 }
00389
00390 task<void> SDKTemplate::WiFiDirectServices::DiscoveredDeviceWrapper::ConnectAsync(Platform::String ^ pin)
00391 {
00392     // Must call FromIdAsync first
00393     auto task = create_task([]() { return; });
00394     if (_service == nullptr)
00395     {
00396         task = OpenSessionAsync();
00397     }
00398
00399     return task.then([this, pin]()
00400     {
00401         _manager->NotifyUser("Connecting...", NotifyType::StatusMessage);
00402
00403         IAsyncOperation<WiFiDirectServiceSession^>^ connectOperation;
00404         if (pin->Length() > 0)
00405         {
00406             connectOperation = _service->ConnectAsync(pin);
00407         }
00408         else
00409         {
00410             connectOperation = _service->ConnectAsync();
00411         }
00412
00413         return create_task(connectOperation).then([this](WiFiDirectServiceSession^ session)
00414         {
00415             _manager->NotifyUser("Done Connecting", NotifyType::StatusMessage);
00416
00417             // Now we are done with this WiFiDirectService instance
00418             // Clear state so a new connection can be started
00419             _service->SessionDeferred -= _sessionDeferredToken;
00420             _service = nullptr;
00421
00422             SessionWrapper^ sessionWrapper = ref new SessionWrapper(session, _manager);
00423             _manager->AddSession(sessionWrapper);
00424         });
00425     });
00426 }
00427
00428 void DiscoveredDeviceWrapper::OnSessionDeferred(WiFiDirectService^ sender, WiFiDirectServiceSessionDeferredEventArgs^ args)
00429 {
00430     String^ deferredSessionInfo = "";
00431     if (args->DeferredSessionInfo != nullptr && args->DeferredSessionInfo->Length > 0)
00432     {
00433         DataReader^ sessionInfoDataReader = DataReader::FromBuffer(args->DeferredSessionInfo);
00434         deferredSessionInfo = sessionInfoDataReader->ReadString(args->DeferredSessionInfo->Length);
00435     }
00436
00437     _manager->NotifyUser("Session Connection was deferred... (" + deferredSessionInfo + ")", NotifyType::StatusMessage);
00438 }
00439
00440 void DiscoveredDeviceWrapper::ParseProperties()
00441 {
00442     if (_deviceInfo->Properties->HasKey("System.Devices.WiFiDirectServices.ServiceName"))
00443     {
00444         auto serviceName = _deviceInfo->Properties->Lookup("System.Devices.WiFiDirectServices.ServiceName");
00445         ServiceName = serviceName->ToString();
00446     }
00447     else
00448     {
00449         ServiceName = "";
00450     }
00451
00452     if (_deviceInfo->Properties->HasKey("System.Devices.WiFiDirectServices.AdvertisementId"))
00453     {
00454         auto advertisementId = _deviceInfo->Properties->Lookup("System.Devices.WiFiDirectServices.AdvertisementId");
00455         AdvertisementId = static_cast<unsigned int>(advertisementId);
00456     }
00457     else
00458     {
00459         AdvertisementId = 0;
00460     }
00461
00462     if (_deviceInfo->Properties->HasKey("System.Devices.WiFiDirectServices.ServiceConfigMethods"))
00463     {
00464         auto configMethods = _deviceInfo->Properties->Lookup("System.Devices.WiFiDirectServices.ServiceConfigMethods");
00465         ConfigMethods = static_cast<unsigned int>(configMethods);
00466     }
00467     else
00468     {
00469         ConfigMethods = 0;
00470     }
00471
00472     if (_deviceInfo->Properties->HasKey("System.Devices.WiFiDirectServices.ServiceAddress"))
00473     {
00474         auto serviceAddress = _deviceInfo->Properties->Lookup("System.Devices.WiFiDirectServices.ServiceAddress");
00475         auto serviceAddressProp = dynamic_cast<IPropertyValue^>(serviceAddress);
00476
00477         Array<unsigned char>^ macBuffer;
00478         serviceAddressProp->GetUInt8Array(&macBuffer);
00479
00480         // Convert from array to string of format xx:xx:xx:xx:xx:xx
00481         wostringstream stream;
00482         wstring strAddress;
00483         ServiceAddress = "";
00484         for (unsigned char b : macBuffer)
00485         {
00486             stream << hex << setfill(L'0') << setw(2) << b;
00487             stream << ":";
00488         }
00489         strAddress = stream.str().c_str();
00490         strAddress.pop_back();
00491         ServiceAddress = ref new String(strAddress.c_str());
00492     }
00493     else
00494     {
00495         ServiceAddress = "XX:XX:XX:XX:XX:XX";
00496     }
00497
00498     ServiceInfo = "";
00499     if (_deviceInfo->Properties->HasKey("System.Devices.WiFiDirectServices.ServiceInformation"))
00500     {
00501         auto serviceInfo = _deviceInfo->Properties->Lookup("System.Devices.WiFiDirectServices.ServiceInformation");
00502         auto serviceInfoProp = dynamic_cast<IPropertyValue^>(serviceInfo);
00503
00504         if (serviceInfoProp != nullptr)
00505         {
00506             Array<unsigned char>^ serviceInfoBuffer;
00507             serviceInfoProp->GetUInt8Array(&serviceInfoBuffer);
00508
00509             auto sessionInfoDataWriter = ref new DataWriter(ref new InMemoryRandomAccessStream());
00510             sessionInfoDataWriter->WriteBytes(serviceInfoBuffer);
00511
00512             DataReader^ serviceInfoDataReader = DataReader::FromBuffer(sessionInfoDataWriter->DetachBuffer());
00513             ServiceInfo = serviceInfoDataReader->ReadString(serviceInfoBuffer->Length);
00514         }
00515     }
00516 }
00517
00518 SessionWrapper::SessionWrapper(WiFiDirectServiceSession^ session, WiFiDirectServiceManager^ manager)
00519     : _session(session),
00520       _manager(manager)
00521 {
00522     _remotePortAddedToken = _session->RemotePortAdded += ref new TypedEventHandler<WiFiDirectServiceSession^, WiFiDirectServiceRemotePortAddedEventArgs^>(
00523         this,
00524         &SessionWrapper::OnRemotePortAdded
00525         );
00526     _sessionStatusChangedToken = _session->SessionStatusChanged += ref new TypedEventHandler<WiFiDirectServiceSession^, Object^>(
00527         this,
00528         &SessionWrapper::OnSessionStatusChanged
00529         );
00530 }
00531
00532 SessionWrapper::~SessionWrapper()
00533 {
00534     if (_session != nullptr)
00535     {
00536         _session->RemotePortAdded -= _remotePortAddedToken;
00537         _session->SessionStatusChanged -= _sessionStatusChangedToken;
00538     }
00539
00540     _streamSocketListeners->Clear();
00541     _socketList->Clear();
00542 }
00543
00544 void SDKTemplate::WiFiDirectServices::SessionWrapper::Close()
00545 {
00546     // When we assign to nullptr, that will close the session
00547     // However, we will get a notification of the session closed at this time
00548     // Make sure the _session variable is null before we start this
00549     Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession^ tempSession;
00550
00551     if (_session != nullptr)
00552     {
00553         lock_guard<mutex> lock(_sessionMutex);
00554         tempSession = _session;
00555         _session = nullptr;
00556     }
00557
00558     if (tempSession != nullptr)
00559     {
00560         tempSession = nullptr;
00561
00562         // Wait for status change
00563         // NOTE: this should complete in 5 seconds under normal circumstances
00564         if (0 != _sessionClosedEvent.wait(60000))
00565         {
00566             throw ref new FailureException("Timed out waiting for session to close");
00567         }
00568     }
00569 }
00570
00571 Concurrency::task<void> SessionWrapper::AddStreamSocketListenerAsync(uint16 port)
00572 {
00573     _manager->NotifyUser("Adding stream socket listener for TCP port " + port.ToString(), NotifyType::StatusMessage);
00574
00575     auto endpointPairCollection = _session->GetConnectionEndpointPairs();
00576
00577     // Create listener for socket connection (and add to list to cleanup later)
00578     StreamSocketListener^ listenerSocket = ref new StreamSocketListener();
00579     StreamSocketListenerWrapper^ listenerWrapper = ref new StreamSocketListenerWrapper(
00580         _manager,
00581         listenerSocket,
00582         this
00583         );
00584
00585     _manager->NotifyUser("BindEndpointAsync...", NotifyType::StatusMessage);
00586
00587     return create_task(listenerSocket->BindEndpointAsync(endpointPairCollection->GetAt(0)->LocalHostName, port.ToString()))
00588     .then([this, listenerSocket]()
00589     {
00590         _manager->NotifyUser("BindEndpointAsync Done", NotifyType::StatusMessage);
00591
00592         _manager->NotifyUser("AddStreamSocketListenerAsync...", NotifyType::StatusMessage);
00593         return create_task(_session->AddStreamSocketListenerAsync(listenerSocket))
00594         .then([this]()
00595         {
00596             _manager->NotifyUser("AddStreamSocketListenerAsync Done", NotifyType::StatusMessage);
00597         });
00598     })
00599     .then([this, listenerWrapper](task<void> finalTask)
00600     {
00601         try
00602         {
00603             // Rethrow exceptions from async task in case AddStreamSocketListenerAsync failed
00604             // This may happen if the same TCP port is used multiple times
00605             finalTask.get();
00606         }
00607         catch (Exception^ ex)
00608         {
00609             _manager->NotifyUser("AddStreamSocketListenerAsync Failed: " + ex->Message, NotifyType::ErrorMessage);
00610         }
00611
00612         _streamSocketListeners->Append(listenerWrapper);
00613     });
00614 }
00615
00616 Concurrency::task<void> SessionWrapper::AddDatagramSocketAsync(uint16 port)
00617 {
00618     _manager->NotifyUser("Adding stream socket listener for UDP port " + port.ToString(), NotifyType::StatusMessage);
00619
00620     auto endpointPairCollection = _session->GetConnectionEndpointPairs();
00621
00622     DatagramSocket^ socket = ref new DatagramSocket();
00623     // Socket is "read-only", cannot send data but can receive data
00624     // Expectation is that application starts a listening socket, then remote device sends data
00625     SocketWrapper^ socketWrapper = ref new SocketWrapper(_manager, nullptr, socket, false);
00626
00627     // Bind UDP socket for receiving messages (peer should call connect and send messages to this socket)
00628     _manager->NotifyUser("BindEndpointAsync...", NotifyType::StatusMessage);
00629
00630     return create_task(socket->BindEndpointAsync(endpointPairCollection->GetAt(0)->LocalHostName, port.ToString()))
00631     .then([this, socket, socketWrapper]()
00632     {
00633         _manager->NotifyUser("BindEndpointAsync Done", NotifyType::StatusMessage);
00634
00635         _manager->NotifyUser("AddDatagramSocketAsync...", NotifyType::StatusMessage);
00636         return create_task(_session->AddDatagramSocketAsync(socket))
00637             .then([this]()
00638             {
00639                 _manager->NotifyUser("AddDatagramSocketAsync Done", NotifyType::StatusMessage);
00640             }).then([this, socketWrapper]()
00641             {
00642                 // Update manager so UI can add to list
00643                 _manager->AddSocket(socketWrapper);
00644
00645                 _socketList->Append(socketWrapper);
00646             });
00647     })
00648     .then([this](task<void> finalTask)
00649     {
00650         try
00651         {
00652             // Rethrow exceptions from async task in case AddDatagramSocketAsync failed
00653             // This may happen if the same UDP port is used multiple times
00654             finalTask.get();
00655         }
00656         catch (Exception^ ex)
00657         {
00658             _manager->NotifyUser("AddDatagramSocketAsync Failed: " + ex->Message, NotifyType::ErrorMessage);
00659         }
00660     });
00661 }
00662
00663 void SessionWrapper::AddStreamSocketInternal(StreamSocket ^ socket)
00664 {
00665     SocketWrapper^ socketWrapper = ref new SocketWrapper(_manager, socket, nullptr, true);
00666
00667     // Start receiving messages recursively
00668     socketWrapper->StartReceiveLoop();
00669
00670     _socketList->Append(socketWrapper);
00671     // Update manager so UI can add to list
00672     _manager->AddSocket(socketWrapper);
00673 }
00674
00675 void SessionWrapper::OnRemotePortAdded(WiFiDirectServiceSession^ sender, WiFiDirectServiceRemotePortAddedEventArgs^ args)
00676 {
00677     auto endpointPairCollection = args->EndpointPairs;
00678     auto protocol = args->Protocol;
00679     if (endpointPairCollection->Size == 0)
00680     {
00681         _manager->NotifyUser("No endpoint pairs for remote port added event", NotifyType::ErrorMessage);
00682         return;
00683     }
00684
00685     _manager->NotifyUser(
00686         (protocol == WiFiDirectServiceIPProtocol::Tcp) ? "TCP" : ((protocol == WiFiDirectServiceIPProtocol::Udp) ? "UDP" : "???") +
00687         "Port " + endpointPairCollection->GetAt(0)->RemoteServiceName + "Added by remote peer",
00688         NotifyType::StatusMessage
00689         );
00690
00691     task<void> socketTask;
00692
00693     if (args->Protocol == WiFiDirectServiceIPProtocol::Tcp)
00694     {
00695         // Connect to the stream socket listener
00696         StreamSocket^ streamSocket = ref new StreamSocket();
00697         SocketWrapper^ socketWrapper = ref new SocketWrapper(_manager, streamSocket, nullptr, true);
00698
00699         _manager->NotifyUser("Connecting to stream socket...", NotifyType::StatusMessage);
00700
00701         socketTask = create_task(streamSocket->ConnectAsync(endpointPairCollection->GetAt(0)))
00702         .then([this, socketWrapper]()
00703         {
00704             // Start receiving messages recursively
00705             socketWrapper->StartReceiveLoop();
00706
00707             _manager->NotifyUser("Stream socket connected", NotifyType::StatusMessage);
00708
00709             _socketList->Append(socketWrapper);
00710             // Update manager so UI can add to list
00711             _manager->AddSocket(socketWrapper);
00712         });
00713     }
00714     else if (args->Protocol == WiFiDirectServiceIPProtocol::Udp)
00715     {
00716         // Connect a socket over UDP
00717         DatagramSocket^ datagramSocket = ref new DatagramSocket();
00718         SocketWrapper^ socketWrapper = ref new SocketWrapper(_manager, nullptr, datagramSocket, true);
00719
00720         _manager->NotifyUser("Connecting to datagram socket...", NotifyType::StatusMessage);
00721
00722         socketTask = create_task(datagramSocket->ConnectAsync(endpointPairCollection->GetAt(0)))
00723             .then([this, socketWrapper]()
00724             {
00725                 _manager->NotifyUser("Datagram socket connected", NotifyType::StatusMessage);
00726
00727                 _socketList->Append(socketWrapper);
00728                 // Update manager so UI can add to list
00729                 _manager->AddSocket(socketWrapper);
00730             });
00731     }
00732     else
00733     {
00734         _manager->NotifyUser("Bad protocol for remote port added event", NotifyType::ErrorMessage);
00735         return;
00736     }
00737
00738     socketTask.then([this](task<void> finalTask)
00739     {
00740         try
00741         {
00742             // Rethrow exceptions from async task in case ConnectAsync failed
00743             finalTask.get();
00744         }
00745         catch (Exception^ ex)
00746         {
00747             _manager->NotifyUser("Socket ConnectAsync Failed: " + ex->Message, NotifyType::ErrorMessage);
00748         }
00749     });
00750 }
00751
00752 void SessionWrapper::OnSessionStatusChanged(Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSession ^ sender, Platform::Object ^ args)
00753 {
00754     _manager->NotifyUser("Session Status Changed to " + sender->Status.ToString(), NotifyType::StatusMessage);
00755
00756     if (sender->Status == WiFiDirectServiceSessionStatus::Closed)
00757     {
00758         _sessionClosedEvent.set();
00759         // Cleanup
00760         _manager->RemoveSession(this);
00761     }
00762 }
00763
00764 StreamSocketListenerWrapper::StreamSocketListenerWrapper(
00765     WiFiDirectServiceManager^ manager,
00766     StreamSocketListener^ streamSocketListener,
00767     SessionWrapper^ session
00768     ) : _manager(manager),
00769         _streamSocketListener(streamSocketListener),
00770         _session(session)
00771 {
00772     _connectionReceivedToken = _streamSocketListener->ConnectionReceived += ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>(
00773         this,
00774         &StreamSocketListenerWrapper::OnConnectionReceived
00775         );
00776 }
00777
00778 StreamSocketListenerWrapper::~StreamSocketListenerWrapper()
00779 {
00780     _streamSocketListener->ConnectionReceived -= _connectionReceivedToken;
00781 }
00782
00783 void StreamSocketListenerWrapper::OnConnectionReceived(Windows::Networking::Sockets::StreamSocketListener ^ sender, Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs ^ args)
00784 {
00785     _manager->NotifyUser("Connection received for TCP Port " + sender->Information->LocalPort, NotifyType::StatusMessage);
00786
00787     _session->AddStreamSocketInternal(args->Socket);
00788 }
00789
00790 SocketWrapper::SocketWrapper(
00791     WiFiDirectServiceManager^ manager,
00792     StreamSocket^ streamSocket,
00793     DatagramSocket^ datagramSocket,
00794     bool canSend
00795     ) : _manager(manager),
00796         _streamSocket(streamSocket),
00797         _datagramSocket(datagramSocket)
00798 {
00799     if (streamSocket == nullptr && datagramSocket == nullptr)
00800     {
00801         throw ref new InvalidArgumentException("Bad SocketWrapper parameters, must provide a TCP or UDP socket");
00802     }
00803     else if (streamSocket != nullptr && datagramSocket != nullptr)
00804     {
00805         throw ref new InvalidArgumentException("Bad SocketWrapper parameters, got both TCP and UDP socket, expected only one");
00806     }
00807     else if (streamSocket != nullptr)
00808     {
00809         _reader = ref new DataReader(streamSocket->InputStream);
00810         if (canSend)
00811         {
00812             _writer = ref new DataWriter(streamSocket->OutputStream);
00813         }
00814     }
00815     else
00816     {
00817         _datagramMessageReceivedToken = datagramSocket->MessageReceived += ref new TypedEventHandler<DatagramSocket^, DatagramSocketMessageReceivedEventArgs^>(
00818             this,
00819             &SocketWrapper::OnUDPMessageReceived
00820             );
00821         if (canSend)
00822         {
00823             _writer = ref new DataWriter(datagramSocket->OutputStream);
00824         }
00825     }
00826
00827     if (_reader != nullptr)
00828     {
00829         _reader->UnicodeEncoding = UnicodeEncoding::Utf8;
00830         _reader->ByteOrder = ByteOrder::LittleEndian;
00831     }
00832
00833     if (_writer != nullptr)
00834     {
00835         _writer->UnicodeEncoding = UnicodeEncoding::Utf8;
00836         _writer->ByteOrder = ByteOrder::LittleEndian;
00837     }
00838 }
00839
00840 SocketWrapper::~SocketWrapper()
00841 {
00842     if (_datagramSocket != nullptr)
00843     {
00844         _datagramSocket->MessageReceived -= _datagramMessageReceivedToken;
00845     }
00846 }
00847
00848 String^ SocketWrapper::Protocol::get()
00849 {
00850     if (_streamSocket != nullptr)
00851     {
00852         return "TCP";
00853     }
00854     else if (_datagramSocket != nullptr)
00855     {
00856         return "UDP";
00857     }
00858     else
00859     {
00860         return "???";
00861     }
00862 }
00863
00864 String^ SocketWrapper::Port::get()
00865 {
00866     if (_streamSocket != nullptr)
00867     {
00868         return _streamSocket->Information->LocalPort;
00869     }
00870     else if (_datagramSocket != nullptr)
00871     {
00872         return _datagramSocket->Information->LocalPort;
00873     }
00874     else
00875     {
00876         return "???";
00877     }
00878 }
00879
00880 task<void> SocketWrapper::SendMessageAsync(String ^ message)
00881 {
00882     if (_writer == nullptr)
00883     {
00884         _manager->NotifyUser("Socket is unable to send messages (receive only socket).", NotifyType::ErrorMessage);
00885         return task_from_result();
00886     }
00887     else
00888     {
00889         _writer->WriteUInt32(_writer->MeasureString(message));
00890         _writer->WriteString(message);
00891
00892         return create_task(_writer->StoreAsync()).then([this, message](unsigned int bytesSent)
00893         {
00894             _manager->NotifyUser(
00895                 "Sent Message: \"" + message + "\", " + bytesSent + " bytes",
00896                 NotifyType::StatusMessage
00897             );
00898         }).then([this](task<void> previousTask)
00899         {
00900             try
00901             {
00902                 // Try getting all exceptions from the continuation chain above this point.
00903                 previousTask.get();
00904             }
00905             catch (Exception^ ex)
00906             {
00907                 _manager->NotifyUser("Send message Failed: " + ex->Message, NotifyType::ErrorMessage);
00908             }
00909         });
00910     }
00911 }
00912
00913 void SocketWrapper::StartReceiveLoop()
00914 {
00915     create_task(_reader->LoadAsync(sizeof(UINT32))).then( [this](unsigned int size)
00916     {
00917         if (size < sizeof(UINT32))
00918         {
00919             // The underlying socket was closed before we were able to read the whole data.
00920             cancel_current_task();
00921         }
00922
00923         unsigned int messageLength = _reader->ReadUInt32();
00924         return create_task(_reader->LoadAsync(messageLength)).then( [this, messageLength](unsigned int actualStringLength)
00925         {
00926             if (actualStringLength != messageLength)
00927             {
00928                 // The underlying socket was closed before we were able to read the whole data.
00929                 cancel_current_task();
00930             }
00931
00932             // Just print a message for now
00933             String^ message = _reader->ReadString(messageLength);
00934
00935             _manager->NotifyUser("Received Message: \"" +
00936                 message
00937                 + "\", " + messageLength + " bytes",
00938                 NotifyType::StatusMessage
00939                 );
00940         });
00941     }).then([this](task<void> previousTask)
00942     {
00943         try
00944         {
00945             // Try getting all exceptions from the continuation chain above this point.
00946             previousTask.get();
00947
00948             // Everything went ok, so try to receive another string. The receive will continue until the stream is
00949             // broken (i.e. peer closed the socket).
00950             StartReceiveLoop();
00951         }
00952         catch (Exception^ ex)
00953         {
00954             _manager->NotifyUser("Message Receive Loop Failed: " + ex->Message, NotifyType::ErrorMessage);
00955         }
00956         catch (task_canceled&)
00957         {
00958             _manager->NotifyUser("Message Receive loop canceled", NotifyType::ErrorMessage);
00959         }
00960     });
00961 }
00962
00963 void SocketWrapper::OnUDPMessageReceived(DatagramSocket^ sender, DatagramSocketMessageReceivedEventArgs^ args)
00964 {
00965     try
00966     {
00967         DataReader^ datareader = args->GetDataReader();
00968         datareader->UnicodeEncoding = UnicodeEncoding::Utf8;
00969         datareader->ByteOrder = ByteOrder::LittleEndian;
00970
00971         // Determine how long the string is.
00972         unsigned int messageLength = datareader->ReadUInt32();
00973
00974         if (messageLength > 0)
00975         {
00976             // Decode the string.
00977             String^ message = datareader->ReadString(messageLength);
00978
00979             // Just print a message for now
00980             _manager->NotifyUser(
00981                 "Received Message: \"" +
00982                 message
00983                 + "\", " + messageLength + " bytes",
00984                 NotifyType::StatusMessage
00985                 );
00986         }
00987         else
00988         {
00989             _manager->NotifyUser("ReceiveMessage 0 bytes loaded for message content.", NotifyType::ErrorMessage);
00990         }
00991     }
00992     catch (Exception^ ex)
00993     {
00994         _manager->NotifyUser("HandleReceivedMessage Failed: " + ex->Message, NotifyType::ErrorMessage);
00995     }
00996 }
Generated on Fri Nov 15 2024 22:22:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: StreamSocket/cpp/pch.cpp Source File

  • StreamSocket
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // pch.cpp
00014 // Include the standard header and generate the precompiled header.
00015 //
00016
00017 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraResolution/cpp/Scenario3_AspectRatio.xaml.h Source File

  • CameraResolution
  • cpp

Scenario3_AspectRatio.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_AspectRatio.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario3_AspectRatio sealed
00021     {
00022     public:
00023         Scenario3_AspectRatio();
00024         virtual ~Scenario3_AspectRatio();
00025
00026     protected:
00027         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00028
00029     private:
00030         MainPage^ _rootPage;
00031         Platform::Agile<Windows::Media::Capture::MediaCapture^> _mediaCapture;
00032         Windows::Foundation::EventRegistrationToken _mediaCaptureFailedEventToken;
00033
00034         bool _isPreviewing;
00035         bool _isRecording;
00036
00037         // Folder in which the captures will be stored
00038         Windows::Storage::StorageFolder^ _captureFolder;
00039
00040         Concurrency::task<void> InitializeCameraAsync();
00041         Concurrency::task<void> CleanupCameraAsync();
00042
00043         void InitializeCameraButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         void VideoButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045
00046         void PreviewSettings_Changed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047         void VideoSettings_Changed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048
00049         void CheckIfStreamsAreIdentical();
00050         void PopulateComboBoxes();
00051         void MatchPreviewAspectRatio();
00052
00053         void MediaCapture_Failed(Windows::Media::Capture::MediaCapture^ sender, Windows::Media::Capture::MediaCaptureFailedEventArgs^ e);
00054     };
00055 }
Generated on Fri Nov 15 2024 22:18:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cpp/Scenario5_TriggerCFU.xaml.h Source File

  • FilePicker
  • cpp

Scenario5_TriggerCFU.xaml.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include "pch.h"
00004 #include "Scenario5_TriggerCFU.g.h"
00005 #include "MainPage.xaml.h"
00006
00007 namespace SDKTemplate
00008 {
00009     public ref class Scenario5_TriggerCFU sealed
00010     {
00011     public:
00012         Scenario5_TriggerCFU();
00013
00014     private:
00015         MainPage^ rootPage = MainPage::Current;
00016         Windows::Storage::StorageFile^ m_afterWriteFile = nullptr;
00017         Windows::Storage::StorageFile^ m_beforeReadFile = nullptr;
00018         Platform::String^ m_faToken;
00019
00020         void UpdateButtons();
00021         void CreateFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00022         void WriteToFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00023         void WriteToFileWithExplicitCFUButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00024         void SaveToFutureAccessListButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00025         void GetFileFromFutureAccessListButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00026         void PickAFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00027     };
00028 }
Generated on Fri Nov 15 2024 22:19:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmsSendAndReceive/cs/SmsSendAndReceive/RegisterWithBackgroundTask.xaml.cs Source File

  • SmsSendAndReceive
  • cs
  • SmsSendAndReceive

RegisterWithBackgroundTask.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using System;
00017 using System.Collections.Generic;
00018 using Windows.UI.Core;
00019 using Windows.Storage;
00020 using Windows.ApplicationModel.Background;
00021 using Windows.Devices.Sms;
00022
00023 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00024
00025 namespace SmsSendAndReceive
00026 {
00027     /// <summary>
00028     /// An empty page that can be used on its own or navigated to within a Frame.
00029     /// </summary>
00030     public sealed partial class RegisterWithBackgroundTask : Page
00031     {
00032         private MainPage rootPage;
00033         private const string BackgroundTaskEntryPoint = "SmsBackgroundTask.SampleSmsBackgroundTask";
00034         private const string BackgroundTaskName = "SampleSmsBackgroundTask";
00035         private CoreDispatcher sampleDispatcher;
00036
00037         public RegisterWithBackgroundTask()
00038         {
00039             this.InitializeComponent();
00040
00041             // Get dispatcher for dispatching updates to the UI thread.
00042             sampleDispatcher = Window.Current.CoreWindow.Dispatcher;
00043
00044             RegisterButton.IsEnabled = true;
00045             UnregisterButton.IsEnabled = false;
00046
00047             try
00048             {
00049                 // Initialize state-based registration of currently registered background tasks.
00050                 InitializeRegisteredSmsBackgroundTasks();
00051             }
00052             catch (Exception ex)
00053             {
00054                 rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
00055             }
00056
00057         }
00058
00059         protected override void OnNavigatedTo(NavigationEventArgs e)
00060         {
00061             rootPage = MainPage.Current;
00062         }
00063
00064         // Update the registration status text and the button states based on the background task's
00065         // registration state.
00066         private void UpdateBackgroundTaskUIState(bool Registered)
00067         {
00068             if (Registered)
00069             {
00070                 BackgroundTaskStatus.Text = "Registered";
00071                 RegisterButton.IsEnabled = false;
00072                 UnregisterButton.IsEnabled = true;
00073             }
00074             else
00075             {
00076                 BackgroundTaskStatus.Text = "Unregistered";
00077                 RegisterButton.IsEnabled = true;
00078                 UnregisterButton.IsEnabled = false;
00079             }
00080         }
00081
00082         // Initialize state based on currently registered background tasks
00083         public void InitializeRegisteredSmsBackgroundTasks()
00084         {
00085             try
00086             {
00087                 //
00088                 // Initialize UI elements based on currently registered background tasks
00089                 // and associate background task completed event handler with each background task.
00090                 //
00091                 UpdateBackgroundTaskUIState(false);
00092
00093                 foreach (var item in BackgroundTaskRegistration.AllTasks)
00094                 {
00095                     IBackgroundTaskRegistration task = item.Value;
00096                     if (task.Name == BackgroundTaskName)
00097                     {
00098                         UpdateBackgroundTaskUIState(true);
00099                         task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
00100                     }
00101                 }
00102             }
00103             catch (Exception ex)
00104             {
00105                 rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
00106             }
00107         }
00108
00109
00110         private void Register_Click(object sender, RoutedEventArgs e)
00111         {
00112             // Check to see that a filter action type is set
00113             if (AcceptImmediatelyButton.IsChecked == false && DropButton.IsChecked == false && PeekButton.IsChecked == false && AcceptButton.IsChecked == false)
00114             {
00115                 rootPage.NotifyUser("Please set a filter action type", NotifyType.ErrorMessage);
00116                 return;
00117             }
00118
00119             // Check to see that a message type is set
00120             if (TextButton.IsChecked == false && AppButton.IsChecked == false && WapButton.IsChecked == false && BroadcastButton.IsChecked == false && VoicemailButton.IsChecked == false)
00121             {
00122                 rootPage.NotifyUser("Please set a message type", NotifyType.ErrorMessage);
00123                 return;
00124             }
00125
00126             try
00127             {
00128                 // Set filter action type
00129                 SmsMessageType messageType = SmsMessageType.Text; // set as Text as default
00130                 if (TextButton.IsChecked == true)
00131                 {
00132                     messageType = SmsMessageType.Text;
00133                 }
00134                 else if (AppButton.IsChecked == true)
00135                 {
00136                     messageType = SmsMessageType.App;
00137                 }
00138                 else if (WapButton.IsChecked == true)
00139                 {
00140                     messageType = SmsMessageType.Wap;
00141                 }
00142                 else if (BroadcastButton.IsChecked == true)
00143                 {
00144                     messageType = SmsMessageType.Broadcast;
00145                 }
00146                 else if (VoicemailButton.IsChecked == true)
00147                 {
00148                     messageType = SmsMessageType.Voicemail;
00149                 }
00150
00151                 // Create new filter rule (individual)
00152                 SmsFilterRule filter = new SmsFilterRule(messageType);
00153
00154                 // Set filter action type
00155                 SmsFilterActionType actionType = SmsFilterActionType.Accept; // set as Accept as default
00156                 if (AcceptImmediatelyButton.IsChecked == true)
00157                 {
00158                     actionType = SmsFilterActionType.AcceptImmediately;
00159                 }
00160                 else if (DropButton.IsChecked == true)
00161                 {
00162                     actionType = SmsFilterActionType.Drop;
00163                 }
00164                 else if (PeekButton.IsChecked == true)
00165                 {
00166                     actionType = SmsFilterActionType.Peek;
00167                 }
00168                 else if (AcceptButton.IsChecked == true)
00169                 {
00170                     actionType = SmsFilterActionType.Accept;
00171                 }
00172
00173                 // Created set of filters for this application
00174                 SmsFilterRules filterRules = new SmsFilterRules(actionType);
00175                 IList<SmsFilterRule> rules = filterRules.Rules;
00176                 rules.Add(filter);
00177
00178                 // Create a new background task builder.
00179                 BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
00180
00181                 // Create a new SmsMessageReceivedTrigger.
00182                 SmsMessageReceivedTrigger trigger = new SmsMessageReceivedTrigger(filterRules);
00183
00184                 // Associate the SmsReceived trigger with the background task builder.
00185                 taskBuilder.SetTrigger(trigger);
00186
00187                 // Specify the background task to run when the trigger fires.
00188                 taskBuilder.TaskEntryPoint = BackgroundTaskEntryPoint;
00189
00190                 // Name the background task.
00191                 taskBuilder.Name = BackgroundTaskName;
00192
00193                 // Register the background task.
00194                 BackgroundTaskRegistration taskRegistration = taskBuilder.Register();
00195
00196                 // Associate completed event handler with the new background task.
00197                 taskRegistration.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
00198
00199                 UpdateBackgroundTaskUIState(true);
00200                 rootPage.NotifyUser("Registered SMS background task", NotifyType.StatusMessage);
00201             }
00202             catch (Exception ex)
00203             {
00204                 rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
00205             }
00206         }
00207
00208         // Handle request to unregister the background task
00209         private void Unregister_Click(object sender, RoutedEventArgs e)
00210         {
00211             // Loop through all background tasks and unregister our background task
00212             foreach (var cur in BackgroundTaskRegistration.AllTasks)
00213             {
00214                 if (cur.Value.Name == BackgroundTaskName)
00215                 {
00216                     cur.Value.Unregister(true);
00217                 }
00218             }
00219
00220             UpdateBackgroundTaskUIState(false);
00221             rootPage.NotifyUser("Unregistered SMS background task.", NotifyType.StatusMessage);
00222
00223         }
00224
00225         // Handle background task completion event.
00226         private async void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
00227         {
00228             // Update the UI with the complrtion status reported by the background task.
00229             // Dispatch an anonymous task to the UI thread to do the update.
00230             await sampleDispatcher.RunAsync(CoreDispatcherPriority.Normal,
00231                 () =>
00232                 {
00233                     try
00234                     {
00235                         if ((sender != null) && (e != null))
00236                         {
00237                             // this method throws if the event is reporting an error
00238                             e.CheckResult();
00239
00240                             // Update the UI with the background task's completion status.
00241                             // The task stores status in the application data settings indexed by the task ID.
00242                             var key = sender.TaskId.ToString();
00243                             var settings = ApplicationData.Current.LocalSettings;
00244                             BackgroundTaskStatus.Text = settings.Values[key].ToString();
00245                         }
00246                     }
00247                     catch (Exception ex)
00248                     {
00249                         rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
00250                     }
00251                 });
00252         }
00253
00254
00255     }
00256 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

App Member List

This is the complete list of members for App, including all inherited members.
App() | App | [inline]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cppwinrt/Scenario4_UnicodeExtensions.h Source File

  • Calendar
  • cppwinrt

Scenario4_UnicodeExtensions.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_UnicodeExtensions.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario4_UnicodeExtensions : Scenario4_UnicodeExtensionsT<Scenario4_UnicodeExtensions>
00019     {
00020         Scenario4_UnicodeExtensions();
00021
00022         void ShowResults_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario4_UnicodeExtensions : Scenario4_UnicodeExtensionsT<Scenario4_UnicodeExtensions, implementation::Scenario4_UnicodeExtensions>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PresenceSensor/cs/SampleConfiguration.cs Source File

  • PresenceSensor
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Presence Sensor";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title = "Data Events", ClassType = typeof(Scenario1_DataEvents) },
00025             new Scenario() { Title = "Polling", ClassType = typeof(Scenario2_Polling) },
00026             new Scenario() { Title = "Choosing", ClassType = typeof(Scenario3_Choosing) },
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContentIndexer/cs/S1_AddWithAPI.xaml.cs Source File

  • ContentIndexer
  • cs

S1_AddWithAPI.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016 using System.Collections.Generic;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     public sealed partial class S1_AddWithAPI
00024     {
00025         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00026         // as NotifyUser()
00027         MainPage rootPage = MainPage.Current;
00028
00029         public S1_AddWithAPI()
00030         {
00031             this.InitializeComponent();
00032             Helpers.InitializeRevisionNumber();
00033         }
00034
00035         /// <summary>
00036         /// Invoked when this page is about to be displayed in a Frame.
00037         /// </summary>
00038         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00039         /// property is typically used to configure the page.</param>
00040         protected override void OnNavigatedTo(NavigationEventArgs e)
00041         {
00042         }
00043
00044         private async void AddToIndex_Click(object sender, RoutedEventArgs e)
00045         {
00046             if (ItemKeyInput.Text == "")
00047             {
00048                 rootPage.NotifyUser("You must add an item key to insert an item into the index.", NotifyType.ErrorMessage);
00049             }
00050             else
00051             {
00052                 // Write the content property to a stream
00053                 var contentStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
00054                 var contentWriter = new Windows.Storage.Streams.DataWriter(contentStream);
00055                 contentWriter.WriteString(ContentInput.Text);
00056                 await contentWriter.StoreAsync();
00057                 contentStream.Seek(0);
00058
00059                 // Get the name, keywords, and comment properties, and assign a language to them if provided
00060                 object itemNameValue = NameInput.Text;
00061                 object keywordsValue = KeywordsInput.Text;
00062                 object commentValue = CommentInput.Text;
00063                 if (LanguageInput.Text != "")
00064                 {
00065                     var itemNameValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage();
00066                     itemNameValueAndLanguage.Language = LanguageInput.Text;
00067                     itemNameValueAndLanguage.Value = itemNameValue;
00068                     itemNameValue = itemNameValueAndLanguage;
00069                     var keywordsValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage();
00070                     keywordsValueAndLanguage.Language = LanguageInput.Text;
00071                     keywordsValueAndLanguage.Value = keywordsValue;
00072                     keywordsValue = keywordsValueAndLanguage;
00073                     var commentValueAndLanguage = new Windows.Storage.Search.ValueAndLanguage();
00074                     commentValueAndLanguage.Language = LanguageInput.Text;
00075                     commentValueAndLanguage.Value = commentValue;
00076                     commentValue = commentValueAndLanguage;
00077                 }
00078
00079                 // Create the item to add to the indexer
00080                 var content = new Windows.Storage.Search.IndexableContent();
00081                 content.Id = ItemKeyInput.Text;
00082                 content.Properties.Add(Windows.Storage.SystemProperties.ItemNameDisplay, itemNameValue);
00083                 content.Properties.Add(Windows.Storage.SystemProperties.Keywords, keywordsValue);
00084                 content.Properties.Add(Windows.Storage.SystemProperties.Comment, commentValue);
00085                 content.Stream = contentStream;
00086                 content.StreamContentType = "text/plain";
00087
00088                 // Add the item to the indexer
00089                 Helpers.OnIndexerOperationBegin();
00090                 var indexer = Windows.Storage.Search.ContentIndexer.GetIndexer();
00091                 await indexer.AddAsync(content);
00092                 Helpers.OnIndexerOperationComplete(indexer);
00093
00094                 // Retrieve the item from the indexer and output its properties
00095                 var retrievedProperties = await indexer.RetrievePropertiesAsync(ItemKeyInput.Text, content.Properties.Keys);
00096                 rootPage.NotifyUser(Helpers.CreateItemString(ItemKeyInput.Text, content.Properties.Keys, retrievedProperties), NotifyType.StatusMessage);
00097             }
00098         }
00099     }
00100 }
Generated on Fri Nov 15 2024 22:18:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
App() | sealed |
Initialize(Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
Load(Platform::String^entryPoint) | sealed | [virtual]
m_deviceResources | sealed | [private]
m_main | sealed | [private]
m_windowClosed | sealed | [private]
m_windowVisible | sealed | [private]
OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | sealed | [protected]
OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnDpiChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnResuming(Platform::Object^sender, Platform::Object^args) | sealed | [protected]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [protected]
OnVisibilityChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::VisibilityChangedEventArgs^args) | sealed | [protected]
OnWindowClosed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::CoreWindowEventArgs^args) | sealed | [protected]
OnWindowSizeChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::WindowSizeChangedEventArgs^args) | sealed | [protected]
Run() | sealed | [virtual]
SetWindow(Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
Uninitialize() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_CurrencyFormatting Member List

This is the complete list of members for Scenario3_CurrencyFormatting, including all inherited members.
Display_Click(object sender, RoutedEventArgs e) | Scenario3_CurrencyFormatting | [inline, private]
Scenario3_CurrencyFormatting() | Scenario3_CurrencyFormatting | [inline]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/Common/DeviceResources.cs Source File

  • 360VideoPlayback
  • cs
  • Common

DeviceResources.cs

Go to the documentation of this file.
00001 ﻿using SharpDX.Direct3D;
00002 using SharpDX.Direct3D11;
00003 using System;
00004 using System.Collections.Generic;
00005 using System.Runtime.InteropServices;
00006 using Windows.Graphics.DirectX.Direct3D11;
00007 using Windows.Graphics.Holographic;
00008
00009 namespace _360VideoPlayback.Common
00010 {
00011     /// <summary>
00012     /// Controls all the DirectX device resources.
00013     /// </summary>
00014     internal class DeviceResources : Disposer
00015     {
00016         // Notifies the application that owns DeviceResources when the Direct3D device is lost.
00017         public event EventHandler DeviceLost;
00018
00019         // Notifies the application that owns DeviceResources when the Direct3D device is restored.
00020         public event EventHandler DeviceRestored;
00021
00022         // Direct3D objects.
00023         private Device3 d3dDevice;
00024         private DeviceContext3 d3dContext;
00025         private SharpDX.DXGI.Adapter3 dxgiAdapter;
00026
00027         // Direct3D interop objects.
00028         private IDirect3DDevice d3dInteropDevice;
00029
00030         // Direct2D factories.
00031         private SharpDX.Direct2D1.Factory2 d2dFactory;
00032         private SharpDX.DirectWrite.Factory1 dwriteFactory;
00033         private SharpDX.WIC.ImagingFactory2 wicFactory;
00034
00035         // The holographic space provides a preferred DXGI adapter ID.
00036         private HolographicSpace holographicSpace = null;
00037
00038         // Properties of the Direct3D device currently in use.
00039         private FeatureLevel d3dFeatureLevel = FeatureLevel.Level_10_0;
00040
00041         // Whether or not the current Direct3D device supports the optional feature
00042         // for setting the render target array index from the vertex shader stage.
00043         bool d3dDeviceSupportsVprt = false;
00044
00045         // Back buffer resources, etc. for attached holographic cameras.
00046         private Dictionary<uint, CameraResources> cameraResourcesDictionary = new Dictionary<uint, CameraResources>();
00047         private Object cameraResourcesLock = new Object();
00048
00049         /// <summary>
00050         /// Constructor for DeviceResources.
00051         /// </summary>
00052         public DeviceResources()
00053         {
00054             CreateDeviceIndependentResources();
00055         }
00056
00057         /// <summary>
00058         /// Configures resources that don't depend on the Direct3D device.
00059         /// </summary>
00060         private void CreateDeviceIndependentResources()
00061         {
00062             // Dispose previous references and set to null
00063             this.RemoveAndDispose(ref d2dFactory);
00064             this.RemoveAndDispose(ref dwriteFactory);
00065             this.RemoveAndDispose(ref wicFactory);
00066
00067             // Initialize Direct2D resources.
00068             var debugLevel = SharpDX.Direct2D1.DebugLevel.None;
00069             #if DEBUG
00070             if (DirectXHelper.SdkLayersAvailable())
00071             {
00072                 debugLevel = SharpDX.Direct2D1.DebugLevel.Information;
00073             }
00074             #endif
00075
00076             // Initialize the Direct2D Factory.
00077             d2dFactory = this.ToDispose(
00078                 new SharpDX.Direct2D1.Factory2(
00079                     SharpDX.Direct2D1.FactoryType.SingleThreaded,
00080                     debugLevel
00081                     )
00082                 );
00083
00084             // Initialize the DirectWrite Factory.
00085             dwriteFactory = this.ToDispose(
00086                 new SharpDX.DirectWrite.Factory1(SharpDX.DirectWrite.FactoryType.Shared)
00087                 );
00088
00089             // Initialize the Windows Imaging Component (WIC) Factory.
00090             wicFactory = this.ToDispose(
00091                 new SharpDX.WIC.ImagingFactory2()
00092                 );
00093         }
00094
00095         public void SetHolographicSpace(HolographicSpace holographicSpace)
00096         {
00097             // Cache the holographic space. Used to re-initalize during device-lost scenarios.
00098             this.holographicSpace = holographicSpace;
00099
00100             InitializeUsingHolographicSpace();
00101         }
00102
00103         public void InitializeUsingHolographicSpace()
00104         {
00105             // The holographic space might need to determine which adapter supports
00106             // holograms, in which case it will specify a non-zero PrimaryAdapterId.
00107             int shiftPos = sizeof(uint);
00108             ulong id = (ulong)holographicSpace.PrimaryAdapterId.LowPart | (((ulong)holographicSpace.PrimaryAdapterId.HighPart) << shiftPos);
00109
00110             // When a primary adapter ID is given to the app, the app should find
00111             // the corresponding DXGI adapter and use it to create Direct3D devices
00112             // and device contexts. Otherwise, there is no restriction on the DXGI
00113             // adapter the app can use.
00114             if (id != 0)
00115             {
00116                 // Create the DXGI factory.
00117                 using (var dxgiFactory4 = new SharpDX.DXGI.Factory4())
00118                 {
00119                     // Retrieve the adapter specified by the holographic space.
00120                     IntPtr adapterPtr;
00121                     dxgiFactory4.EnumAdapterByLuid((long)id, InteropStatics.IDXGIAdapter3, out adapterPtr);
00122
00123                     if (adapterPtr != IntPtr.Zero)
00124                     {
00125                         dxgiAdapter = new SharpDX.DXGI.Adapter3(adapterPtr);
00126                     }
00127                 }
00128             }
00129             else
00130             {
00131                 this.RemoveAndDispose(ref dxgiAdapter);
00132             }
00133
00134             CreateDeviceResources();
00135
00136             holographicSpace.SetDirect3D11Device(d3dInteropDevice);
00137         }
00138
00139
00140         /// <summary>
00141         /// Configures the Direct3D device, and stores handles to it and the device context.
00142         /// </summary>
00143         private void CreateDeviceResources()
00144         {
00145             DisposeDeviceAndContext();
00146
00147             // This flag adds support for surfaces with a different color channel ordering
00148             // than the API default. It is required for compatibility with Direct2D.
00149             DeviceCreationFlags creationFlags = DeviceCreationFlags.BgraSupport;
00150             creationFlags |= DeviceCreationFlags.VideoSupport;
00151
00152 #if DEBUG
00153             if (DirectXHelper.SdkLayersAvailable())
00154             {
00155                 // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00156                 creationFlags |= DeviceCreationFlags.Debug;
00157             }
00158 #endif
00159
00160             // This array defines the set of DirectX hardware feature levels this app will support.
00161             // Note the ordering should be preserved.
00162             // Note that HoloLens supports feature level 11.1. The HoloLens emulator is also capable
00163             // of running on graphics cards starting with feature level 10.0.
00164             FeatureLevel[] featureLevels =
00165             {
00166                 FeatureLevel.Level_12_1,
00167                 FeatureLevel.Level_12_0,
00168                 FeatureLevel.Level_11_1,
00169                 FeatureLevel.Level_11_0,
00170                 FeatureLevel.Level_10_1,
00171                 FeatureLevel.Level_10_0
00172             };
00173             RasterizerStateDescription rasterDesc = new RasterizerStateDescription()
00174             {
00175                 FillMode = FillMode.Solid,
00176                 CullMode = CullMode.Back,
00177                 IsFrontCounterClockwise = false,
00178                 DepthBias = 0,
00179                 SlopeScaledDepthBias = 0,
00180                 DepthBiasClamp = 0,
00181                 IsDepthClipEnabled = true,
00182                 IsScissorEnabled = false,
00183                 IsMultisampleEnabled = true,
00184                 IsAntialiasedLineEnabled = true
00185             };
00186
00187             // Create the Direct3D 11 API device object and a corresponding context.
00188             try
00189             {
00190                 if (null != dxgiAdapter)
00191                 {
00192                     using (var device = new Device(dxgiAdapter, creationFlags, featureLevels))
00193                     {
00194                         // Store pointers to the Direct3D 11.1 API device.
00195                         d3dDevice = this.ToDispose(device.QueryInterface<Device3>());
00196                     }
00197                 }
00198                 else
00199                 {
00200                     using (var device = new Device(DriverType.Hardware, creationFlags, featureLevels))
00201                     {
00202                         // Store a pointer to the Direct3D device.
00203                         d3dDevice = this.ToDispose(device.QueryInterface<Device3>());
00204                     }
00205                 }
00206             }
00207             catch
00208             {
00209                 // If the initialization fails, fall back to the WARP device.
00210                 // For more information on WARP, see:
00211                 // http://go.microsoft.com/fwlink/?LinkId=286690
00212                 using (var device = new Device(DriverType.Warp, creationFlags, featureLevels))
00213                 {
00214                     d3dDevice = this.ToDispose(device.QueryInterface<Device3>());
00215                 }
00216             }
00217
00218             // Cache the feature level of the device that was created.
00219             d3dFeatureLevel = d3dDevice.FeatureLevel;
00220
00221             // Store a pointer to the Direct3D immediate context.
00222             d3dContext = this.ToDispose(d3dDevice.ImmediateContext3);
00223
00224             // Acquire the DXGI interface for the Direct3D device.
00225             using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device3>())
00226             {
00227                 // Wrap the native device using a WinRT interop object.
00228                 IntPtr pUnknown;
00229                 UInt32 hr = InteropStatics.CreateDirect3D11DeviceFromDXGIDevice(dxgiDevice.NativePointer, out pUnknown);
00230                 if (hr == 0)
00231                 {
00232                     d3dInteropDevice = (IDirect3DDevice)Marshal.GetObjectForIUnknown(pUnknown);
00233                     Marshal.Release(pUnknown);
00234                 }
00235
00236                 // Store a pointer to the DXGI adapter.
00237                 // This is for the case of no preferred DXGI adapter, or fallback to WARP.
00238                 dxgiAdapter = this.ToDispose(dxgiDevice.Adapter.QueryInterface<SharpDX.DXGI.Adapter3>());
00239             }
00240
00241             // Check for device support for the optional feature that allows setting the render target array index from the vertex shader stage.
00242             var options = d3dDevice.CheckD3D113Features3();
00243             if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer)
00244             {
00245                 d3dDeviceSupportsVprt = true;
00246             }
00247
00248             RasterizerState rsState = new RasterizerState(d3dDevice, rasterDesc);
00249             d3dContext.Rasterizer.State = rsState;
00250             // Need to multithread for video Playback MF threads
00251             DeviceMultithread mt = d3dDevice.QueryInterface<SharpDX.Direct3D.DeviceMultithread>();
00252             mt.SetMultithreadProtected(true);
00253         }
00254
00255         /// <summary>
00256         /// Disposes of a device-based resources.
00257         /// </summary>
00258         private void DisposeDeviceAndContext()
00259         {
00260             // Dispose existing references to Direct3D 11 device and contxt, and set to null.
00261             this.RemoveAndDispose(ref d3dDevice);
00262             this.RemoveAndDispose(ref d3dContext);
00263             this.RemoveAndDispose(ref dxgiAdapter);
00264
00265             // Release the interop device.
00266             d3dInteropDevice = null;
00267         }
00268
00269         /// <summary>
00270         /// Validates the back buffer for each HolographicCamera and recreates
00271         /// resources for back buffers that have changed.
00272         /// Locks the set of holographic camera resources until the function exits.
00273         /// </summary>
00274         public void EnsureCameraResources(HolographicFrame frame, HolographicFramePrediction prediction)
00275         {
00276             UseHolographicCameraResources((Dictionary<uint, CameraResources> cameraResourcesDictionary) =>
00277             {
00278                 foreach (var pose in prediction.CameraPoses)
00279                 {
00280                     var renderingParameters = frame.GetRenderingParameters(pose);
00281                     var cameraResources = cameraResourcesDictionary[pose.HolographicCamera.Id];
00282
00283                     cameraResources.CreateResourcesForBackBuffer(this, renderingParameters);
00284                 }
00285             });
00286         }
00287
00288         /// <summary>
00289         /// Prepares to allocate resources and adds resource views for a camera.
00290         /// Locks the set of holographic camera resources until the function exits.
00291         /// </summary>
00292         public void AddHolographicCamera(HolographicCamera camera)
00293         {
00294             UseHolographicCameraResources((Dictionary<uint, CameraResources> cameraResourcesDictionary) =>
00295             {
00296                 cameraResourcesDictionary.Add(camera.Id, new CameraResources(camera));
00297             });
00298         }
00299
00300         // Deallocates resources for a camera and removes the camera from the set.
00301         // Locks the set of holographic camera resources until the function exits.
00302         public void RemoveHolographicCamera(HolographicCamera camera)
00303         {
00304             UseHolographicCameraResources((Dictionary<uint, CameraResources> cameraResourcesDictionary) =>
00305             {
00306                 CameraResources cameraResources = cameraResourcesDictionary[camera.Id];
00307
00308                 if (null != cameraResources)
00309                 {
00310                     cameraResources.ReleaseResourcesForBackBuffer(this);
00311                     cameraResourcesDictionary.Remove(camera.Id);
00312                 }
00313             });
00314         }
00315
00316         /// <summary>
00317         /// Recreate all device resources and set them back to the current state.
00318         /// Locks the set of holographic camera resources until the function exits.
00319         /// </summary>
00320         public void HandleDeviceLost()
00321         {
00322             DeviceLost.Invoke(this, null);
00323
00324             UseHolographicCameraResources((Dictionary<uint, CameraResources> cameraResourcesDictionary) =>
00325             {
00326                 foreach (var pair in cameraResourcesDictionary)
00327                 {
00328                     CameraResources cameraResources = pair.Value;
00329                     cameraResources.ReleaseAllDeviceResources(this);
00330                 }
00331             });
00332
00333             InitializeUsingHolographicSpace();
00334
00335             DeviceRestored.Invoke(this, null);
00336         }
00337
00338         /// <summary>
00339         /// Call this method when the app suspends. It provides a hint to the driver that the app
00340         /// is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00341         /// </summary>
00342         public void Trim()
00343         {
00344             d3dContext.ClearState();
00345
00346             using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device3>())
00347             {
00348                 dxgiDevice.Trim();
00349             }
00350         }
00351
00352         /// <summary>
00353         /// Present the contents of the swap chain to the screen.
00354         /// Locks the set of holographic camera resources until the function exits.
00355         /// </summary>
00356         public void Present(ref HolographicFrame frame)
00357         {
00358             // By default, this API waits for the frame to finish before it returns.
00359             // Holographic apps should wait for the previous frame to finish before
00360             // starting work on a new frame. This allows for better results from
00361             // holographic frame predictions.
00362             var presentResult = frame.PresentUsingCurrentPrediction(
00363                 HolographicFramePresentWaitBehavior.WaitForFrameToFinish
00364                 );
00365
00366             // The PresentUsingCurrentPrediction API will detect when the graphics device
00367             // changes or becomes invalid. When this happens, it is considered a Direct3D
00368             // device lost scenario.
00369             if (presentResult == HolographicFramePresentResult.DeviceRemoved)
00370             {
00371                 // The Direct3D device, context, and resources should be recreated.
00372                 HandleDeviceLost();
00373             }
00374         }
00375
00376         public delegate void SwapChainAction(Dictionary<uint, CameraResources> cameraResourcesDictionary);
00377         public delegate bool SwapChainActionWithResult(Dictionary<uint, CameraResources> cameraResourcesDictionary);
00378
00379         /// <summary>
00380         /// Device-based resources for holographic cameras are stored in a std::map. Access this list by providing a
00381         /// callback to this function, and the std::map will be guarded from add and remove
00382         /// events until the callback returns. The callback is processed immediately and must
00383         /// not contain any nested calls to UseHolographicCameraResources.
00384         /// The callback takes a parameter of type Dictionary<uint, CameraResources> cameraResourcesDictionary
00385         /// through which the list of cameras will be accessed.
00386         /// The callback also returns a boolean result.
00387         /// </summary>
00388         public bool UseHolographicCameraResources(SwapChainActionWithResult callback)
00389         {
00390             bool success = false;
00391             lock (cameraResourcesLock)
00392             {
00393                 success = callback(cameraResourcesDictionary);
00394             }
00395             return success;
00396         }
00397
00398         /// <summary>
00399         /// Device-based resources for holographic cameras are stored in a std::map. Access this list by providing a
00400         /// callback to this function, and the std::map will be guarded from add and remove
00401         /// events until the callback returns. The callback is processed immediately and must
00402         /// not contain any nested calls to UseHolographicCameraResources.
00403         /// The callback takes a parameter of type Dictionary<uint, CameraResources> cameraResourcesDictionary
00404         /// through which the list of cameras will be accessed.
00405         /// </summary>
00406         public void UseHolographicCameraResources(SwapChainAction callback)
00407         {
00408             lock (cameraResourcesLock)
00409             {
00410                 callback(cameraResourcesDictionary);
00411             }
00412         }
00413
00414         #region Property accessors
00415
00416         public Device3 D3DDevice => d3dDevice;
00417         public DeviceContext3 D3DDeviceContext => d3dContext;
00418         public SharpDX.DXGI.Adapter3 DxgiAdapter => dxgiAdapter;
00419         public IDirect3DDevice D3DInteropDevice => d3dInteropDevice;
00420         public SharpDX.Direct2D1.Factory2 D2DFactory => d2dFactory;
00421         public SharpDX.DirectWrite.Factory1 DWriteFactory => dwriteFactory;
00422         public SharpDX.WIC.ImagingFactory2 WicImagingFactory => wicFactory;
00423         public SharpDX.Direct3D.FeatureLevel D3DDeviceFeatureLevel => d3dFeatureLevel;
00424         public bool D3DDeviceSupportsVprt => d3dDeviceSupportsVprt;
00425
00426         #endregion
00427     }
00428 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BasicTests Member List

This is the complete list of members for BasicTests, including all inherited members.
_DPOnPage | BasicTests | [private, static]
BasicTests() | BasicTests | [inline]
CSharpModel | BasicTests |
DPOnPage | BasicTests |
DPOnPageName | BasicTests | [private]
DPOnPageProperty | BasicTests | [static]
InitializeValues() | BasicTests | [inline, private]
Model | BasicTests |
MyInt | BasicTests |
NullEmployee | BasicTests |
NullStringProperty | BasicTests |
ResetValuesClick(object sender, RoutedEventArgs e) | BasicTests | [inline, private]
UpdateValuesClick(object sender, RoutedEventArgs e) | BasicTests | [inline, private]
Generated on Fri Nov 15 2024 22:24:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlLite/cppwinrt/SampleConfiguration.h Source File

  • XmlLite
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     inline bool check_enumerator(hresult hr)
00018     {
00019         check_hresult(hr);
00020         return hr == S_OK;
00021     }
00022 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FocusPointConstantBuffer Member List

This is the complete list of members for FocusPointConstantBuffer, including all inherited members.
focusPointColor | FocusPointConstantBuffer
focusPointDirection | FocusPointConstantBuffer
focusPointIntensity | FocusPointConstantBuffer
focusPointOrigin | FocusPointConstantBuffer
focusPointRadius | FocusPointConstantBuffer
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RenderingHelper Member List

This is the complete list of members for RenderingHelper, including all inherited members.
CreateDeviceDependentResources() | RenderingHelper |
DrawCube() override | RenderingHelper | [virtual]
IsLoadingComplete() const | RenderingHelper | [inline]
m_deviceResources | RenderingHelper | [private]
m_geometryShader | RenderingHelper | [private]
m_indexBuffer | RenderingHelper | [private]
m_indexCount | RenderingHelper | [private]
m_inputLayout | RenderingHelper | [private]
m_loadingComplete | RenderingHelper | [private]
m_modelConstantBuffer | RenderingHelper | [private]
m_pixelShader | RenderingHelper | [private]
m_usingVprtShaders | RenderingHelper | [private]
m_vertexBuffer | RenderingHelper | [private]
m_vertexShader | RenderingHelper | [private]
PrepareRendering() | RenderingHelper |
ReleaseDeviceDependentResources() | RenderingHelper |
RenderingHelper(const std::shared_ptr< DX::DeviceResources > &deviceResources) | RenderingHelper |
SetConstantBuffer(ModelConstantBuffer *pModelConstantBuffer) override | RenderingHelper | [virtual]
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AudioCategory/cs/AudioCategory/Scenario2.xaml.cs Source File

  • AudioCategory
  • cs
  • AudioCategory

Scenario2.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016 using Windows.UI.Xaml.Media;
00017
00018 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00019
00020 namespace PlaybackManager
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class Scenario2 : Page
00026     {
00027         public Scenario2()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         private void Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00033         {
00034             Playback.SetAudioCategory(AudioCategory.Media);
00035             Playback.SelectFile();
00036         }
00037     }
00038 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AppViewSource Member List

This is the complete list of members for AppViewSource, including all inherited members.
AppViewSource(Uri sourceUri) | AppViewSource | [inline]
CreateView() | AppViewSource | [inline]
sourceUri | AppViewSource | [private]
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

App Member List

This is the complete list of members for App, including all inherited members.
App() | App | [inline]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnSuspending(object sender, SuspendingEventArgs e) | App | [inline, private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/Scenario6.cpp Source File

  • FileAccess
  • cppwinrt

Scenario6.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario6.h"
00014 #include "Scenario6.g.cpp"
00015 #include "SampleConfiguration.h"
00016 #include <sstream>
00017
00018 using namespace winrt;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Globalization::DateTimeFormatting;
00022 using namespace Windows::Storage;
00023 using namespace Windows::Storage::FileProperties;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 namespace winrt::SDKTemplate::implementation
00028 {
00029     Scenario6::Scenario6()
00030     {
00031         InitializeComponent();
00032     }
00033
00034     void Scenario6::OnNavigatedTo(NavigationEventArgs const&)
00035     {
00036         SampleState::ValidateFile();
00037     }
00038
00039     fire_and_forget Scenario6::ShowPropertiesButton_Click(IInspectable const&, RoutedEventArgs const&)
00040     {
00041         auto lifetime = get_strong();
00042
00043         DateTimeFormatter dateFormatter{ L"shortdate longtime" };
00044
00045         StorageFile file = SampleState::SampleFile();
00046         if (file != nullptr)
00047         {
00048             std::wstringstream stream;
00049
00050             try
00051             {
00052                 // Get top level file properties
00053                 stream << L"File name: " << std::wstring_view{ file.Name() } << std::endl;
00054                 stream << L"File type: " << std::wstring_view{ file.FileType() } << std::endl;
00055
00056                 // Get basic properties
00057                 BasicProperties basicProperties = co_await file.GetBasicPropertiesAsync();
00058                 stream << L"File size: " << basicProperties.Size() << std::endl;
00059                 stream << L"Date modified: " << std::wstring_view{ dateFormatter.Format(basicProperties.DateModified()) } << std::endl;
00060
00061                 // Get extra properties
00062                 hstring dateAccessProperty{ L"System.DateAccessed" };
00063                 hstring fileOwnerProperty{ L"System.FileOwner" };
00064                 IMap<hstring, IInspectable> extraProperties = co_await file.Properties().RetrievePropertiesAsync({ dateAccessProperty, fileOwnerProperty });
00065
00066                 auto accessDate = extraProperties.TryLookup(dateAccessProperty);
00067                 if (accessDate) {
00068                     stream << L"Date accessed: " << std::wstring_view{ dateFormatter.Format(unbox_value<DateTime>(accessDate)) } << std::endl;
00069                 }
00070
00071                 auto fileOwner = extraProperties.TryLookup(fileOwnerProperty);
00072                 if (fileOwner) {
00073                     stream << L"File owner: " << std::wstring_view{ unbox_value<hstring>(fileOwner) } << std::endl;
00074                 }
00075
00076                 rootPage.NotifyUser(stream.str(), NotifyType::StatusMessage);
00077             }
00078             catch (const hresult_error& ex)
00079             {
00080                 // I/O errors are reported as exceptions.
00081                 rootPage.NotifyUser(L"Error retrieving properties for '" + file.Name() + L"': " + ex.message(), NotifyType::ErrorMessage);
00082             }
00083         }
00084         else
00085         {
00086             SampleState::NotifyUserFileNotExist();
00087         }
00088     }
00089 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cpp/Scenario5_DefiningCustomGlyphs.xaml.cpp Source File

  • LineDisplay
  • cpp

Scenario5_DefiningCustomGlyphs.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario5_DefiningCustomGlyphs.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Devices::PointOfService;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Security::Cryptography;
00023 using namespace Windows::Storage::Streams;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Data;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 Scenario5_DefiningCustomGlyphs::Scenario5_DefiningCustomGlyphs()
00030 {
00031     InitializeComponent();
00032     DataContext = this;
00033 }
00034
00035 void Scenario5_DefiningCustomGlyphs::OnNavigatedTo(NavigationEventArgs^ e)
00036 {
00037     InitializeAsync();
00038 }
00039
00040 void Scenario5_DefiningCustomGlyphs::OnNavigatedFrom(NavigationEventArgs^ e)
00041 {
00042     delete lineDisplay;
00043     lineDisplay = nullptr;
00044 }
00045
00046 static String^ StringFromUtf32(unsigned int utf32)
00047 {
00048     wchar_t glyphString[3] = {};
00049     if (utf32 < 0x10000)
00050     {
00051         glyphString[0] = static_cast<wchar_t>(utf32);
00052     }
00053     else
00054     {
00055         Windows::Data::Text::UnicodeCharacters::GetSurrogatePairFromCodepoint(utf32, &glyphString[0], &glyphString[1]);
00056     }
00057     return ref new String(glyphString);
00058 }
00059
00060 task<void> Scenario5_DefiningCustomGlyphs::InitializeAsync()
00061 {
00062     ResetButton->IsEnabled = false;
00063     SupportedGlyphsComboBox->Items->Clear();
00064
00065     lineDisplay = co_await rootPage->ClaimScenarioLineDisplayAsync();
00066
00067     if ((lineDisplay != nullptr) && lineDisplay->Capabilities->CanDisplayCustomGlyphs)
00068     {
00069         std::wstring sampleText = L"ABC";
00070         for (unsigned int glyphCode : lineDisplay->CustomGlyphs->SupportedGlyphCodes)
00071         {
00072             String^ glyphString = StringFromUtf32(glyphCode);
00073             Helpers::AddItem(SupportedGlyphsComboBox, glyphCode, "Code " + glyphCode.ToString() + " (UTF-32 '" + glyphString + "')");
00074             if (sampleText.length() < 10)
00075             {
00076                 sampleText.append(glyphString->Data());
00077             }
00078         }
00079
00080         if (SupportedGlyphsComboBox->Items->Size > 0)
00081         {
00082             SupportedGlyphsComboBox->SelectedIndex = 0;
00083         }
00084
00085         Size glyphSize = lineDisplay->CustomGlyphs->SizeInPixels;
00086         glyphBuffer = CreateSolidGlyphBuffer(static_cast<int>(glyphSize.Width), static_cast<int>(glyphSize.Height));
00087
00088         co_await lineDisplay->DefaultWindow->TryDisplayTextAsync(ref new String(sampleText.c_str()));
00089     }
00090
00091     ResetButton->IsEnabled = true;
00092 }
00093
00094 void Scenario5_DefiningCustomGlyphs::DefineGlyphButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00095 {
00096     invoke_async_lambda([=]() -> task<void>
00097     {
00098         auto selectedGlyphCode = Helpers::GetSelectedItemTag<unsigned int>(SupportedGlyphsComboBox);
00099         if (co_await lineDisplay->CustomGlyphs->TryRedefineAsync(selectedGlyphCode, glyphBuffer) &&
00100             co_await lineDisplay->DefaultWindow->TryRefreshAsync())
00101         {
00102             rootPage->NotifyUser("Redefined glyph " + selectedGlyphCode.ToString() + ".", NotifyType::StatusMessage);
00103         }
00104         else
00105         {
00106             rootPage->NotifyUser("Failed to redefine glyph and refresh.", NotifyType::ErrorMessage);
00107         }
00108     });
00109 }
00110
00111 void Scenario5_DefiningCustomGlyphs::ResetButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00112 {
00113     invoke_async_lambda([=]() -> task<void>
00114     {
00115         delete lineDisplay;
00116         lineDisplay = nullptr;
00117         co_await InitializeAsync();
00118     });
00119 }
00120
00121 IBuffer^ Scenario5_DefiningCustomGlyphs::CreateSolidGlyphBuffer(int widthInPixels, int heightInPixels)
00122 {
00123     // Data is sent in one byte chunks, so find the minimum number of whole bytes
00124     // needed to define each row of the glyph.
00125     int bytesPerRow = (widthInPixels + 7) / 8;
00126
00127     auto newGlyphBuffer = ref new Array<byte>(bytesPerRow * heightInPixels);
00128     for (unsigned int i = 0; i < newGlyphBuffer->Length; i++)
00129     {
00130         // Set every bit so that we draw a solid rectangle.
00131         newGlyphBuffer[i] = 0xFF;
00132     }
00133
00134     return CryptographicBuffer::CreateFromByteArray(newGlyphBuffer);
00135 }
Generated on Fri Nov 15 2024 22:20:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_ResetPIN Member List

This is the complete list of members for Scenario3_ResetPIN, including all inherited members.
ResetPin_Click(object sender, RoutedEventArgs e) | Scenario3_ResetPIN | [inline, private]
rootPage | Scenario3_ResetPIN | [private]
Scenario3_ResetPIN() | Scenario3_ResetPIN | [inline]
Generated on Fri Nov 15 2024 22:23:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario5_Stream.xaml.h Source File

  • FileAccess
  • cpp

Scenario5_Stream.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario5_Stream.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Writing and reading using a stream.
00022     /// </summary>
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class Scenario5 sealed
00025     {
00026     public:
00027         Scenario5();
00028         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029
00030     private:
00031         MainPage^ rootPage = MainPage::Current;
00032
00033         void WriteToStreamButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void ReadFromStreamButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035     };
00036 }
Generated on Fri Nov 15 2024 22:19:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RelativeInclinometer/cpp/pch.h Source File

  • RelativeInclinometer
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicSuspension/cs/App.xaml.cs Source File

  • BasicSuspension
  • cs

App.xaml.cs

Go to the documentation of this file.
00001 ﻿using SDKTemplate.Common;
00002 using System;
00003 using System.Collections.Generic;
00004 using Windows.ApplicationModel;
00005 using Windows.ApplicationModel.Activation;
00006 using Windows.Storage;
00007 using Windows.UI.Xaml;
00008 using Windows.UI.Xaml.Controls;
00009 using Windows.UI.Xaml.Navigation;
00010
00011 namespace SDKTemplate
00012 {
00013     /// <summary>
00014     /// Provides application-specific behavior to supplement the default Application class.
00015     /// </summary>
00016     sealed partial class App : Application
00017     {
00018         private const string sessionStateFilename = "_sessionState.xml";
00019         private RootFrameNavigationHelper rootFrameNavigationHelper;
00020
00021         /// <summary>
00022         /// Initializes the singleton application object.  This is the first line of authored code
00023         /// executed, and as such is the logical equivalent of main() or WinMain().
00024         /// </summary>
00025         public App()
00026         {
00027             this.InitializeComponent();
00028             SuspensionManager.KnownTypes.AddRange(new[] { typeof(ItemList), typeof(Item) });
00029             this.Suspending += OnSuspending;
00030         }
00031
00032         /// <summary>
00033         /// Invoked when the application is launched normally by the end user.  Other entry points
00034         /// will be used such as when the application is launched to open a specific file.
00035         /// </summary>
00036         /// <param name="e">Details about the launch request and process.</param>
00037         protected override async void OnLaunched(LaunchActivatedEventArgs e)
00038         {
00039             Frame rootFrame = Window.Current.Content as Frame;
00040
00041             // Do not repeat app initialization when the Window already has content,
00042             // just ensure that the window is active
00043             if (rootFrame == null)
00044             {
00045                 // Create a Frame to act as the navigation context and navigate to the first page
00046                 rootFrame = new Frame();
00047                 SuspensionManager.RegisterFrame(rootFrame, "AppFrame");
00048
00049                 // Use the RootFrameNavigationHelper to respond to keyboard and mouse shortcuts.
00050                 this.rootFrameNavigationHelper = new RootFrameNavigationHelper(rootFrame);
00051
00052                 rootFrame.NavigationFailed += OnNavigationFailed;
00053
00054                 // If this is not the first time the app is run, then restore from the previous session.
00055                 StorageFile file;
00056                 try
00057                 {
00058                     file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename);
00059                 }
00060                 catch (Exception)
00061                 {
00062                     file = null;
00063                 }
00064
00065                 if (file != null)
00066                 {
00067                     //Load state from previously suspended application
00068                     await SuspensionManager.RestoreAsync();
00069                 }
00070
00071                 // Place the frame in the current Window
00072                 Window.Current.Content = rootFrame;
00073             }
00074
00075             if (rootFrame.Content == null)
00076             {
00077                 // When the navigation stack isn't restored navigate to the first page,
00078                 // configuring the new page by passing required information as a navigation
00079                 // parameter
00080                 rootFrame.Navigate(typeof(MainPage), e.Arguments);
00081             }
00082             // Ensure the current window is active
00083             Window.Current.Activate();
00084         }
00085
00086         /// <summary>
00087         /// Invoked when Navigation to a certain page fails
00088         /// </summary>
00089         /// <param name="sender">The Frame which failed navigation</param>
00090         /// <param name="e">Details about the navigation failure</param>
00091         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00092         {
00093             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00094         }
00095
00096         /// <summary>
00097         /// Invoked when application execution is being suspended.  Application state is saved
00098         /// without knowing whether the application will be terminated or resumed with the contents
00099         /// of memory still intact.
00100         /// </summary>
00101         /// <param name="sender">The source of the suspend request.</param>
00102         /// <param name="e">Details about the suspend request.</param>
00103         private async void OnSuspending(object sender, SuspendingEventArgs e)
00104         {
00105             var deferral = e.SuspendingOperation.GetDeferral();
00106
00107             // Save application state and stop any background activity.
00108             await SuspensionManager.SaveAsync();
00109             deferral.Complete();
00110         }
00111     }
00112 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlGamepadNavigation/cs/Scenario2_Engage.xaml.cs Source File

  • XamlGamepadNavigation
  • cs

Scenario2_Engage.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.Foundation;
00013 using Windows.UI.ViewManagement;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario2_Engage : Page
00020     {
00021         public Scenario2_Engage()
00022         {
00023             this.InitializeComponent();
00024         }
00025     }
00026 }
Generated on Fri Nov 15 2024 22:22:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/Common/DeviceResources.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DeviceResources.h"
00014 #include "DirectXSample.h"
00015
00016 using namespace D2D1;
00017 using namespace DirectX;
00018 using namespace winrt::Windows::Graphics::Display;
00019 using namespace winrt::Windows::UI::Core;
00020
00021 // Constants used to calculate screen rotations.
00022 namespace ScreenRotation
00023 {
00024     // 0-degree Z-rotation
00025     static const XMFLOAT4X4 Rotation0(
00026         1.0f, 0.0f, 0.0f, 0.0f,
00027         0.0f, 1.0f, 0.0f, 0.0f,
00028         0.0f, 0.0f, 1.0f, 0.0f,
00029         0.0f, 0.0f, 0.0f, 1.0f
00030         );
00031
00032     // 90-degree Z-rotation
00033     static const XMFLOAT4X4 Rotation90(
00034         0.0f, 1.0f, 0.0f, 0.0f,
00035         -1.0f, 0.0f, 0.0f, 0.0f,
00036         0.0f, 0.0f, 1.0f, 0.0f,
00037         0.0f, 0.0f, 0.0f, 1.0f
00038         );
00039
00040     // 180-degree Z-rotation
00041     static const XMFLOAT4X4 Rotation180(
00042         -1.0f, 0.0f, 0.0f, 0.0f,
00043         0.0f, -1.0f, 0.0f, 0.0f,
00044         0.0f, 0.0f, 1.0f, 0.0f,
00045         0.0f, 0.0f, 0.0f, 1.0f
00046         );
00047
00048     // 270-degree Z-rotation
00049     static const XMFLOAT4X4 Rotation270(
00050         0.0f, -1.0f, 0.0f, 0.0f,
00051         1.0f, 0.0f, 0.0f, 0.0f,
00052         0.0f, 0.0f, 1.0f, 0.0f,
00053         0.0f, 0.0f, 0.0f, 1.0f
00054         );
00055 };
00056
00057 // Constructor for DeviceResources.
00058 DX::DeviceResources::DeviceResources() :
00059     m_screenViewport(),
00060     m_d3dFeatureLevel(D3D_FEATURE_LEVEL_9_1),
00061     m_d3dRenderTargetSize(),
00062     m_outputSize(),
00063     m_logicalSize(),
00064     m_nativeOrientation(DisplayOrientations::None),
00065     m_currentOrientation(DisplayOrientations::None),
00066     m_dpi(-1.0f),
00067     m_deviceNotify(nullptr)
00068 {
00069     CreateDeviceIndependentResources();
00070     CreateDeviceResources();
00071 }
00072
00073 // Configures resources that don't depend on the Direct3D device.
00074 void DX::DeviceResources::CreateDeviceIndependentResources()
00075 {
00076     // Initialize Direct2D resources.
00077     D2D1_FACTORY_OPTIONS options;
00078     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00079
00080 #if defined(_DEBUG)
00081     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00082     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00083 #endif
00084
00085     // Initialize the Direct2D Factory.
00086     winrt::check_hresult(
00087         D2D1CreateFactory(
00088             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00089             __uuidof(m_d2dFactory),
00090             &options,
00091             m_d2dFactory.put_void()
00092             )
00093         );
00094
00095     // Initialize the DirectWrite Factory.
00096     winrt::check_hresult(
00097         DWriteCreateFactory(
00098             DWRITE_FACTORY_TYPE_SHARED,
00099             __uuidof(m_dwriteFactory),
00100             reinterpret_cast<IUnknown**>(m_dwriteFactory.put())
00101             )
00102         );
00103
00104     // Initialize the Windows Imaging Component (WIC) Factory.
00105     m_wicFactory = winrt::create_instance<IWICImagingFactory2>(CLSID_WICImagingFactory2);
00106 }
00107
00108 // Configures the Direct3D device, and stores handles to it and the device context.
00109 void DX::DeviceResources::CreateDeviceResources()
00110 {
00111     // This flag adds support for surfaces with a different color channel ordering
00112     // than the API default. It is required for compatibility with Direct2D.
00113     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00114
00115 #if defined(_DEBUG)
00116     if (DX::SdkLayersAvailable())
00117     {
00118         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00119         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00120     }
00121 #endif
00122
00123     // This array defines the set of DirectX hardware feature levels this app will support.
00124     // Note the ordering should be preserved.
00125     // Don't forget to declare your application's minimum required feature level in its
00126     // description. All applications are assumed to support 9.1 unless otherwise stated.
00127     D3D_FEATURE_LEVEL featureLevels[] =
00128     {
00129         D3D_FEATURE_LEVEL_11_1,
00130         D3D_FEATURE_LEVEL_11_0,
00131         D3D_FEATURE_LEVEL_10_1,
00132         D3D_FEATURE_LEVEL_10_0,
00133         D3D_FEATURE_LEVEL_9_3,
00134         D3D_FEATURE_LEVEL_9_2,
00135         D3D_FEATURE_LEVEL_9_1
00136     };
00137
00138     // Create the Direct3D 11 API device object and a corresponding context.
00139     winrt::com_ptr<ID3D11Device> device;
00140     winrt::com_ptr<ID3D11DeviceContext> context;
00141
00142     HRESULT hr = D3D11CreateDevice(
00143         nullptr,                    // Specify nullptr to use the default adapter.
00144         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00145         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00146         creationFlags,              // Set debug and Direct2D compatibility flags.
00147         featureLevels,              // List of feature levels this app can support.
00148         ARRAYSIZE(featureLevels),   // Size of the list above.
00149         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00150         device.put(),               // Returns the Direct3D device created.
00151         &m_d3dFeatureLevel,         // Returns feature level of device created.
00152         context.put()                    // Returns the device immediate context.
00153         );
00154
00155     if (FAILED(hr))
00156     {
00157         // If the initialization fails, fall back to the WARP device.
00158         // For more information on WARP, see:
00159         // http://go.microsoft.com/fwlink/?LinkId=286690
00160         winrt::check_hresult(
00161             D3D11CreateDevice(
00162                 nullptr,
00163                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00164                 0,
00165                 creationFlags,
00166                 featureLevels,
00167                 ARRAYSIZE(featureLevels),
00168                 D3D11_SDK_VERSION,
00169                 device.put(),
00170                 &m_d3dFeatureLevel,
00171                 context.put()
00172                 )
00173             );
00174     }
00175
00176     // Store pointers to the Direct3D 11.1 API device and immediate context.
00177     m_d3dDevice = device.as<ID3D11Device3>();
00178
00179     m_d3dContext = context.as<ID3D11DeviceContext3>();
00180
00181     // Create the Direct2D device object and a corresponding context.
00182     winrt::com_ptr<IDXGIDevice3> dxgiDevice;
00183     dxgiDevice = m_d3dDevice.as<IDXGIDevice3>();
00184
00185     winrt::check_hresult(
00186         m_d2dFactory->CreateDevice(dxgiDevice.get(), m_d2dDevice.put())
00187         );
00188
00189     winrt::check_hresult(
00190         m_d2dDevice->CreateDeviceContext(
00191             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00192             m_d2dContext.put()
00193             )
00194         );
00195 }
00196
00197 // These resources need to be recreated every time the window size is changed.
00198 void DX::DeviceResources::CreateWindowSizeDependentResources()
00199 {
00200     // Clear the previous window size specific context.
00201     ID3D11RenderTargetView* nullViews[] = { nullptr };
00202     m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00203     m_d3dRenderTargetView = nullptr;
00204     m_d3dRenderTargetViewRight = nullptr;
00205     m_d2dContext->SetTarget(nullptr);
00206     m_d2dTargetBitmap = nullptr;
00207     m_d2dTargetBitmapRight = nullptr;
00208     m_d3dDepthStencilView = nullptr;
00209     m_d3dContext->Flush();
00210
00211     // Calculate the necessary swap chain and render target size in pixels.
00212     m_outputSize.Width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_dpi);
00213     m_outputSize.Height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_dpi);
00214
00215     // Prevent zero size DirectX content from being created.
00216     m_outputSize.Width = max(m_outputSize.Width, 1);
00217     m_outputSize.Height = max(m_outputSize.Height, 1);
00218
00219     // The width and height of the swap chain must be based on the window's
00220     // natively-oriented width and height. If the window is not in the native
00221     // orientation, the dimensions must be reversed.
00222     DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation();
00223
00224     bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270;
00225     m_d3dRenderTargetSize.Width = swapDimensions ? m_outputSize.Height : m_outputSize.Width;
00226     m_d3dRenderTargetSize.Height = swapDimensions ? m_outputSize.Width : m_outputSize.Height;
00227
00228     if (m_swapChain != nullptr)
00229     {
00230         // If the swap chain already exists, resize it.
00231         HRESULT hr = m_swapChain->ResizeBuffers(
00232             2, // Double-buffered swap chain.
00233             static_cast<UINT>(m_d3dRenderTargetSize.Width),
00234             static_cast<UINT>(m_d3dRenderTargetSize.Height),
00235             DXGI_FORMAT_B8G8R8A8_UNORM,
00236             0
00237             );
00238
00239         if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00240         {
00241             // If the device was removed for any reason, a new device and swap chain will need to be created.
00242             HandleDeviceLost();
00243
00244             // Everything is set up now. Do not continue execution of this method. HandleDeviceLost will reenter this method
00245             // and correctly set up the new device.
00246             return;
00247         }
00248         else
00249         {
00250             winrt::check_hresult(hr);
00251         }
00252     }
00253     else
00254     {
00255         CheckStereoEnabledStatus();
00256
00257         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00258         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = { 0 };
00259
00260         swapChainDesc.Width = static_cast<UINT>(m_d3dRenderTargetSize.Width); // Match the size of the window.
00261         swapChainDesc.Height = static_cast<UINT>(m_d3dRenderTargetSize.Height);
00262         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swap chain format.
00263         swapChainDesc.Stereo = m_stereoEnabled;
00264         swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling.
00265         swapChainDesc.SampleDesc.Quality = 0;
00266         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00267         swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency.
00268         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Store apps must use this SwapEffect.
00269         swapChainDesc.Flags = 0;
00270         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00271         swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
00272
00273         // This sequence obtains the DXGI factory that was used to create the Direct3D device above.
00274         winrt::com_ptr<IDXGIDevice3> dxgiDevice;
00275         dxgiDevice = m_d3dDevice.as<IDXGIDevice3>();
00276
00277         winrt::com_ptr<IDXGIAdapter> dxgiAdapter;
00278         winrt::check_hresult(
00279             dxgiDevice->GetAdapter(dxgiAdapter.put())
00280             );
00281
00282         winrt::com_ptr<IDXGIFactory3> dxgiFactory;
00283         winrt::check_hresult(
00284             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00285             );
00286
00287         winrt::check_hresult(
00288             dxgiFactory->CreateSwapChainForCoreWindow(
00289                 m_d3dDevice.get(),
00290                 winrt::get_unknown(m_window.get()),
00291                 &swapChainDesc,
00292                 nullptr,
00293                 m_swapChain.put()
00294                 )
00295             );
00296
00297         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00298         // ensures that the application will only render after each VSync, minimizing power consumption.
00299         winrt::check_hresult(
00300             dxgiDevice->SetMaximumFrameLatency(1)
00301             );
00302     }
00303
00304     // Set the proper orientation for the swap chain, and generate 2D and
00305     // 3D matrix transformations for rendering to the rotated swap chain.
00306     // Note the rotation angle for the 2D and 3D transforms are different.
00307     // This is due to the difference in coordinate spaces. Additionally,
00308     // the 3D matrix is specified explicitly to avoid rounding errors.
00309
00310     switch (displayRotation)
00311     {
00312     case DXGI_MODE_ROTATION_IDENTITY:
00313         m_orientationTransform2D = Matrix3x2F::Identity();
00314         m_orientationTransform3D = ScreenRotation::Rotation0;
00315         break;
00316
00317     case DXGI_MODE_ROTATION_ROTATE90:
00318         m_orientationTransform2D =
00319             Matrix3x2F::Rotation(90.0f) *
00320             Matrix3x2F::Translation(m_logicalSize.Height, 0.0f);
00321         m_orientationTransform3D = ScreenRotation::Rotation270;
00322         break;
00323
00324     case DXGI_MODE_ROTATION_ROTATE180:
00325         m_orientationTransform2D =
00326             Matrix3x2F::Rotation(180.0f) *
00327             Matrix3x2F::Translation(m_logicalSize.Width, m_logicalSize.Height);
00328         m_orientationTransform3D = ScreenRotation::Rotation180;
00329         break;
00330
00331     case DXGI_MODE_ROTATION_ROTATE270:
00332         m_orientationTransform2D =
00333             Matrix3x2F::Rotation(270.0f) *
00334             Matrix3x2F::Translation(0.0f, m_logicalSize.Width);
00335         m_orientationTransform3D = ScreenRotation::Rotation90;
00336         break;
00337
00338     default:
00339         winrt::throw_hresult(E_FAIL);
00340     }
00341
00342     winrt::check_hresult(
00343         m_swapChain->SetRotation(displayRotation)
00344         );
00345
00346     // Create a render target view of the swap chain back buffer.
00347     winrt::com_ptr<ID3D11Texture2D> backBuffer = winrt::capture<ID3D11Texture2D>(m_swapChain, &IDXGISwapChain1::GetBuffer, 0);
00348
00349     winrt::check_hresult(
00350         m_d3dDevice->CreateRenderTargetView(
00351             backBuffer.get(),
00352             nullptr,
00353             m_d3dRenderTargetView.put()
00354             )
00355         );
00356
00357     // Stereo swapchains have an arrayed resource, so create a second Render Target
00358     // for the right eye buffer.
00359     if (m_stereoEnabled)
00360     {
00361         CD3D11_RENDER_TARGET_VIEW_DESC renderTargetViewRightDesc(
00362             D3D11_RTV_DIMENSION_TEXTURE2DARRAY,
00363             DXGI_FORMAT_B8G8R8A8_UNORM,
00364             0,
00365             1,
00366             1
00367             );
00368
00369         winrt::check_hresult(
00370             m_d3dDevice->CreateRenderTargetView(
00371                 backBuffer.get(),
00372                 &renderTargetViewRightDesc,
00373                 m_d3dRenderTargetViewRight.put()
00374                 )
00375             );
00376     }
00377
00378     // Create a depth stencil view for use with 3D rendering if needed.
00379     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00380         DXGI_FORMAT_D24_UNORM_S8_UINT,
00381         static_cast<UINT>(m_d3dRenderTargetSize.Width),
00382         static_cast<UINT>(m_d3dRenderTargetSize.Height),
00383         1, // This depth stencil view has only one texture.
00384         1, // Use a single mipmap level.
00385         D3D11_BIND_DEPTH_STENCIL
00386         );
00387
00388     winrt::com_ptr<ID3D11Texture2D> depthStencil;
00389     winrt::check_hresult(
00390         m_d3dDevice->CreateTexture2D(
00391             &depthStencilDesc,
00392             nullptr,
00393             depthStencil.put()
00394             )
00395         );
00396
00397     CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
00398     winrt::check_hresult(
00399         m_d3dDevice->CreateDepthStencilView(
00400             depthStencil.get(),
00401             &depthStencilViewDesc,
00402             m_d3dDepthStencilView.put()
00403             )
00404         );
00405
00406     // Set the 3D rendering viewport to target the entire window.
00407     m_screenViewport = CD3D11_VIEWPORT(
00408         0.0f,
00409         0.0f,
00410         m_d3dRenderTargetSize.Width,
00411         m_d3dRenderTargetSize.Height
00412         );
00413
00414     m_d3dContext->RSSetViewports(1, &m_screenViewport);
00415
00416     // Create a Direct2D target bitmap associated with the
00417     // swap chain back buffer and set it as the current target.
00418     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00419         D2D1::BitmapProperties1(
00420             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00421             D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED
00422                 ),
00423             m_dpi,
00424             m_dpi
00425             );
00426
00427     winrt::com_ptr<IDXGIResource1> dxgiBackBuffer = winrt::capture<IDXGIResource1>(m_swapChain, &IDXGISwapChain1::GetBuffer, 0);
00428
00429     winrt::com_ptr<IDXGISurface2> dxgiSurface;
00430     winrt::check_hresult(
00431         dxgiBackBuffer->CreateSubresourceSurface(0, dxgiSurface.put())
00432         );
00433
00434     winrt::check_hresult(
00435         m_d2dContext->CreateBitmapFromDxgiSurface(
00436             dxgiSurface.get(),
00437             &bitmapProperties,
00438             m_d2dTargetBitmap.put()
00439             )
00440         );
00441
00442     // Stereo swapchains have an arrayed resource, so create a second Target Bitmap
00443     // for the right eye buffer.
00444     if (m_stereoEnabled)
00445     {
00446         winrt::check_hresult(
00447             dxgiBackBuffer->CreateSubresourceSurface(1, dxgiSurface.put())
00448             );
00449         winrt::check_hresult(
00450             m_d2dContext->CreateBitmapFromDxgiSurface(
00451                 dxgiSurface.get(),
00452                 &bitmapProperties,
00453                 m_d2dTargetBitmapRight.put()
00454                 )
00455             );
00456     }
00457
00458     m_d2dContext->SetTarget(m_d2dTargetBitmap.get());
00459
00460     // Grayscale text anti-aliasing is recommended for all Windows Store apps.
00461     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00462 }
00463
00464 // This method is called when the CoreWindow is created (or re-created).
00465 void DX::DeviceResources::SetWindow(CoreWindow const& window)
00466 {
00467     DisplayInformation currentDisplayInformation = DisplayInformation::GetForCurrentView();
00468
00469     m_window = window;
00470     m_logicalSize = winrt::Windows::Foundation::Size(window.Bounds().Width, window.Bounds().Height);
00471     m_nativeOrientation = currentDisplayInformation.NativeOrientation();
00472     m_currentOrientation = currentDisplayInformation.CurrentOrientation();
00473     m_dpi = currentDisplayInformation.LogicalDpi();
00474     m_d2dContext->SetDpi(m_dpi, m_dpi);
00475
00476     CreateWindowSizeDependentResources();
00477 }
00478
00479 // This method is called in the event handler for the SizeChanged event.
00480 void DX::DeviceResources::SetLogicalSize(winrt::Windows::Foundation::Size logicalSize)
00481 {
00482     if (m_logicalSize != logicalSize)
00483     {
00484         m_logicalSize = logicalSize;
00485         CreateWindowSizeDependentResources();
00486     }
00487 }
00488
00489 // This method is called in the event handler for the DpiChanged event.
00490 void DX::DeviceResources::SetDpi(float dpi)
00491 {
00492     if (dpi != m_dpi)
00493     {
00494         m_dpi = dpi;
00495
00496         // When the display DPI changes, the logical size of the window (measured in Dips) also changes and needs to be updated.
00497         m_logicalSize = winrt::Windows::Foundation::Size(m_window.get().Bounds().Width, m_window.get().Bounds().Height);
00498
00499         m_d2dContext->SetDpi(m_dpi, m_dpi);
00500         CreateWindowSizeDependentResources();
00501     }
00502 }
00503
00504 // This method is called in the event handler for the OrientationChanged event.
00505 void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation)
00506 {
00507     if (m_currentOrientation != currentOrientation)
00508     {
00509         m_currentOrientation = currentOrientation;
00510         CreateWindowSizeDependentResources();
00511     }
00512 }
00513
00514 // This method is called in the event handler for the DisplayContentsInvalidated event.
00515 void DX::DeviceResources::ValidateDevice()
00516 {
00517     // The D3D Device is no longer valid if the default adapter changed since the device
00518     // was created or if the device has been removed.
00519
00520     // First, get the information for the default adapter from when the device was created.
00521
00522     winrt::com_ptr<IDXGIDevice3> dxgiDevice;
00523     dxgiDevice = m_d3dDevice.as<IDXGIDevice3>();
00524
00525     winrt::com_ptr<IDXGIAdapter> deviceAdapter;
00526     winrt::check_hresult(dxgiDevice->GetAdapter(deviceAdapter.put()));
00527
00528     winrt::com_ptr<IDXGIFactory2> deviceFactory;
00529     winrt::check_hresult(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory)));
00530
00531     winrt::com_ptr<IDXGIAdapter1> previousDefaultAdapter;
00532     winrt::check_hresult(deviceFactory->EnumAdapters1(0, previousDefaultAdapter.put()));
00533
00534     DXGI_ADAPTER_DESC previousDesc;
00535     winrt::check_hresult(previousDefaultAdapter->GetDesc(&previousDesc));
00536
00537     // Next, get the information for the current default adapter.
00538
00539     winrt::com_ptr<IDXGIFactory2> currentFactory;
00540     winrt::check_hresult(CreateDXGIFactory1(IID_PPV_ARGS(&currentFactory)));
00541
00542     winrt::com_ptr<IDXGIAdapter1> currentDefaultAdapter;
00543     winrt::check_hresult(currentFactory->EnumAdapters1(0, currentDefaultAdapter.put()));
00544
00545     DXGI_ADAPTER_DESC currentDesc;
00546     winrt::check_hresult(currentDefaultAdapter->GetDesc(&currentDesc));
00547
00548     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00549     // a new D3D device must be created.
00550
00551     if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart ||
00552         previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart ||
00553         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00554     {
00555         // Release references to resources related to the old device.
00556         dxgiDevice = nullptr;
00557         deviceAdapter = nullptr;
00558         deviceFactory = nullptr;
00559         previousDefaultAdapter = nullptr;
00560
00561         // Create a new device and swap chain.
00562         HandleDeviceLost();
00563     }
00564 }
00565
00566 // Recreate all device resources and set them back to the current state.
00567 void DX::DeviceResources::HandleDeviceLost()
00568 {
00569     m_swapChain = nullptr;
00570
00571     if (m_deviceNotify != nullptr)
00572     {
00573         m_deviceNotify->OnDeviceLost();
00574     }
00575
00576     // Make sure the rendering state has been released.
00577     m_d3dContext->OMSetRenderTargets(0, nullptr, nullptr);
00578     m_d3dDepthStencilView = nullptr;
00579     m_d3dRenderTargetView = nullptr;
00580     m_d3dRenderTargetViewRight = nullptr;
00581
00582     m_d2dContext->SetTarget(nullptr);
00583     m_d2dTargetBitmap = nullptr;
00584     m_d2dTargetBitmapRight = nullptr;
00585     m_d2dContext = nullptr;
00586     m_d2dDevice = nullptr;
00587
00588     m_d3dContext->Flush();
00589
00590     CreateDeviceResources();
00591     m_d2dContext->SetDpi(m_dpi, m_dpi);
00592     CreateWindowSizeDependentResources();
00593
00594     if (m_deviceNotify != nullptr)
00595     {
00596         m_deviceNotify->OnDeviceRestored();
00597     }
00598 }
00599
00600 // Register our DeviceNotify to be informed on device lost and creation.
00601 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00602 {
00603     m_deviceNotify = deviceNotify;
00604 }
00605
00606 // Call this method when the app suspends. It provides a hint to the driver that the app
00607 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00608 void DX::DeviceResources::Trim()
00609 {
00610     winrt::com_ptr<IDXGIDevice3> dxgiDevice;
00611     dxgiDevice = m_d3dDevice.as<IDXGIDevice3>();
00612
00613     dxgiDevice->Trim();
00614 }
00615
00616 // Present the contents of the swap chain to the screen.
00617 void DX::DeviceResources::Present()
00618 {
00619     // The first argument instructs DXGI to block until VSync, putting the application
00620     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00621     // frames that will never be displayed to the screen.
00622     HRESULT hr = m_swapChain->Present(1, 0);
00623
00624     // Discard the contents of the render target.
00625     // This is a valid operation only when the existing contents will be entirely
00626     // overwritten. If dirty or scroll rects are used, this call should be removed.
00627     m_d3dContext->DiscardView(m_d3dRenderTargetView.get());
00628
00629     // Discard the contents of the depth stencil.
00630     m_d3dContext->DiscardView(m_d3dDepthStencilView.get());
00631
00632     // If the device was removed either by a disconnection or a driver upgrade, we
00633     // must recreate all device resources.
00634     if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00635     {
00636         HandleDeviceLost();
00637     }
00638     else
00639     {
00640         winrt::check_hresult(hr);
00641     }
00642 }
00643
00644 // This method determines the rotation between the display device's native Orientation and the
00645 // current display orientation.
00646 DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation()
00647 {
00648     DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
00649
00650     // Note: NativeOrientation can only be Landscape or Portrait even though
00651     // the DisplayOrientations enum has other values.
00652     switch (m_nativeOrientation)
00653     {
00654     case DisplayOrientations::Landscape:
00655         switch (m_currentOrientation)
00656         {
00657         case DisplayOrientations::Landscape:
00658             rotation = DXGI_MODE_ROTATION_IDENTITY;
00659             break;
00660
00661         case DisplayOrientations::Portrait:
00662             rotation = DXGI_MODE_ROTATION_ROTATE270;
00663             break;
00664
00665         case DisplayOrientations::LandscapeFlipped:
00666             rotation = DXGI_MODE_ROTATION_ROTATE180;
00667             break;
00668
00669         case DisplayOrientations::PortraitFlipped:
00670             rotation = DXGI_MODE_ROTATION_ROTATE90;
00671             break;
00672         }
00673         break;
00674
00675     case DisplayOrientations::Portrait:
00676         switch (m_currentOrientation)
00677         {
00678         case DisplayOrientations::Landscape:
00679             rotation = DXGI_MODE_ROTATION_ROTATE90;
00680             break;
00681
00682         case DisplayOrientations::Portrait:
00683             rotation = DXGI_MODE_ROTATION_IDENTITY;
00684             break;
00685
00686         case DisplayOrientations::LandscapeFlipped:
00687             rotation = DXGI_MODE_ROTATION_ROTATE270;
00688             break;
00689
00690         case DisplayOrientations::PortraitFlipped:
00691             rotation = DXGI_MODE_ROTATION_ROTATE180;
00692             break;
00693         }
00694         break;
00695     }
00696     return rotation;
00697 }
00698
00699 void DX::DeviceResources::UpdateStereoState()
00700 {
00701     bool previousStereoState = m_stereoEnabled;
00702     CheckStereoEnabledStatus();
00703     if (previousStereoState != m_stereoEnabled)
00704     {
00705         // Swap chain needs to be recreated so release the existing one.
00706         // The rest of the dependent resources with be released in CreateWindowSizeDependentResources.
00707         m_swapChain = nullptr;
00708         CreateWindowSizeDependentResources();
00709     }
00710
00711 }
00712
00713 void DX::DeviceResources::CheckStereoEnabledStatus()
00714 {
00715     // first, retrieve the underlying DXGI Device from the D3D Device
00716     winrt::com_ptr<IDXGIDevice1> dxgiDevice;
00717     dxgiDevice = m_d3dDevice.as<IDXGIDevice1>();
00718
00719     // next, get the associated adapter from the DXGI Device
00720     winrt::com_ptr<IDXGIAdapter> dxgiAdapter;
00721     winrt::check_hresult(
00722         dxgiDevice->GetAdapter(dxgiAdapter.put())
00723         );
00724
00725     // next, get the parent factory from the DXGI adapter
00726     winrt::com_ptr<IDXGIFactory2> dxgiFactory;
00727     winrt::check_hresult(
00728         dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00729         );
00730
00731     m_stereoEnabled = dxgiFactory->IsWindowedStereoEnabled() ? true : false;
00732 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteLineSpacingModes/cpp/DWriteLineSpacingModes/SampleConfiguration.h Source File

  • DWriteLineSpacingModes
  • cpp
  • DWriteLineSpacingModes

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "DirectWrite Text Layout Line Spacing Modes";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: StreamSocket/cpp/Scenario4.xaml.cpp Source File

  • StreamSocket
  • cpp

Scenario4.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario4.xaml.cpp
00014 // Implementation of the Scenario4 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario4.xaml.h"
00019
00020 using namespace SDKTemplate;
00021 using namespace SDKTemplate::StreamSocketSample;
00022
00023 using namespace Concurrency;
00024 using namespace Windows::ApplicationModel::Core;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Networking::Sockets;
00027 using namespace Windows::Storage::Streams;
00028 using namespace Windows::UI::Xaml;
00029 using namespace Windows::UI::Xaml::Controls;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 Scenario4::Scenario4()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 /// <summary>
00038 /// Invoked when this page is about to be displayed in a Frame.
00039 /// </summary>
00040 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00041 /// property is typically used to configure the page.</param>
00042 void Scenario4::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00045     // as NotifyUser()
00046     rootPage = MainPage::Current;
00047 }
00048
00049 void Scenario4::CloseSockets_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00050 {
00051     if (CoreApplication::Properties->HasKey("clientDataWriter"))
00052     {
00053         // Remove the listener from the list of application properties as we are about to close it.
00054         DataWriter^ dataWriter = dynamic_cast<DataWriter^>(CoreApplication::Properties->Lookup("clientDataWriter"));
00055         CoreApplication::Properties->Remove("clientDataWriter");
00056
00057         // To reuse the socket with another data writer, the application must detach the stream from the
00058         // current writer before deleting it. This is added for completeness, as this sample closes the socket
00059         // in the very next block.
00060         dataWriter->DetachStream();
00061         delete dataWriter;
00062         dataWriter = nullptr;
00063     }
00064
00065     if (CoreApplication::Properties->HasKey("clientSocket"))
00066     {
00067         // Remove the socket from the list of application properties as we are about to close it.
00068         StreamSocket^ socket = dynamic_cast<StreamSocket^>(CoreApplication::Properties->Lookup("clientSocket"));
00069         CoreApplication::Properties->Remove("clientSocket");
00070
00071         // StreamSocket.Close() is exposed through the 'delete' keyword in C++/CX.
00072         // The line below explicitly closes the socket.
00073         delete socket;
00074         socket = nullptr;
00075     }
00076
00077     if (CoreApplication::Properties->HasKey("listener"))
00078     {
00079         // Remove the listener from the list of application properties as we are about to close it.
00080         StreamSocketListener^ listener = dynamic_cast<StreamSocketListener^>(CoreApplication::Properties->Lookup("listener"));
00081         CoreApplication::Properties->Remove("listener");
00082
00083         // StreamSocketListener.Close() is exposed through the 'delete' keyword in C++/CX.
00084         // The line below explicitly closes the listener.
00085         delete listener;
00086         listener = nullptr;
00087     }
00088
00089     if (CoreApplication::Properties->HasKey("connected"))
00090     {
00091         CoreApplication::Properties->Remove("connected");
00092     }
00093
00094     if (CoreApplication::Properties->HasKey("serverAddress"))
00095     {
00096         CoreApplication::Properties->Remove("serverAddress");
00097     }
00098
00099     if (CoreApplication::Properties->HasKey("adapter"))
00100     {
00101         CoreApplication::Properties->Remove("adapter");
00102     }
00103
00104     rootPage->NotifyUser("Socket and listener closed", NotifyType::StatusMessage);
00105 }
Generated on Fri Nov 15 2024 22:18:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cpp/Tasks/PedometerBackgroundTask.cpp Source File

  • Pedometer
  • cpp
  • Tasks

PedometerBackgroundTask.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // PedometerBackgroundTask.h
00014 // Declaration of the PedometerBackgroundTask class
00015 //
00016
00017 #include "pch.h"
00018 #include "PedometerBackgroundTask.h"
00019
00020 using namespace Windows::Devices::Sensors;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Globalization;
00023 using namespace Windows::Globalization::DateTimeFormatting;
00024 using namespace Windows::Storage;
00025 using namespace Windows::ApplicationModel::Background;
00026 using namespace Tasks;
00027
00028 /// <summary>
00029 /// The entry point of a background task.
00030 /// </summary>
00031 /// <param name="taskInstance">The current background task instance.</param>
00032 void PedometerBackgroundTask::Run(IBackgroundTaskInstance^ taskInstance)
00033 {
00034     // Associate a cancellation handler with the background task.
00035     // Even though this task isn't performing much work, it can still be canceled.
00036     taskInstance->Canceled += ref new BackgroundTaskCanceledEventHandler(this, &PedometerBackgroundTask::OnCanceled);
00037
00038     SensorDataThresholdTriggerDetails^ triggerDetails = safe_cast<SensorDataThresholdTriggerDetails^>(taskInstance->TriggerDetails);
00039     if (SensorType::Pedometer == triggerDetails->SensorType)
00040     {
00041         // read the pedometer readings from the trigger details
00042         auto reports = Pedometer::GetReadingsFromTriggerDetails(triggerDetails);
00043
00044         auto settings = ApplicationData::Current->LocalSettings;
00045         settings->Values->Insert("ReportCount", reports->Size.ToString());
00046
00047         auto timestampFormatter = ref new DateTimeFormatter("day month year hour minute second");
00048
00049         if (reports->Size > 0)
00050         {
00051             unsigned int nThFromLast = 1;
00052             // get the last value from the reports to display the step counts
00053             auto lastReading = reports->GetAt(reports->Size - nThFromLast);
00054             auto knownTimestamp = lastReading->Timestamp;
00055
00056             settings->Values->Insert("LastTimestamp", timestampFormatter->Format(lastReading->Timestamp));
00057
00058             // insert each 'step kind' specific count to the application cache to be used by the foreground app
00059             settings->Values->Insert(lastReading->StepKind.ToString(), lastReading->CumulativeSteps.ToString());
00060
00061             DateTime readingTimestamp(knownTimestamp);
00062
00063             // All reports that have the same timestamp correspond to step counts
00064             // of different step kinds supported by the sensor - Parse each one of
00065             // them and save in the application data
00066             while (nThFromLast < reports->Size)
00067             {
00068                 // get the next reading from the last
00069                 nThFromLast++;
00070                 lastReading = reports->GetAt(reports->Size - nThFromLast);
00071                 readingTimestamp = lastReading->Timestamp;
00072
00073                 // fetch and insert all reports that has the same time stamp
00074                 if (readingTimestamp.UniversalTime == knownTimestamp.UniversalTime)
00075                 {
00076                     // insert this 'step kind' count
00077                     settings->Values->Insert(lastReading->StepKind.ToString(), lastReading->CumulativeSteps.ToString());
00078                 }
00079                 else
00080                 {
00081                     break;
00082                 }
00083             }
00084         }
00085
00086         auto calendar = ref new Calendar();
00087         calendar->SetToNow();
00088         settings->Values->Insert("TaskStatus", "Completed at " + timestampFormatter->Format(calendar->GetDateTime()));
00089         // No deferral is held on taskInstance because we are returning immediately.
00090     }
00091 }
00092
00093 /// <summary>
00094 /// Handles background task cancellation.
00095 /// </summary>
00096 /// <param name="sender">The background task instance being canceled.</param>
00097 /// <param name="reason">The cancellation reason.</param>
00098 void PedometerBackgroundTask::OnCanceled(IBackgroundTaskInstance^ /*taskInstance*/, BackgroundTaskCancellationReason reason)
00099 {
00100     auto settings = ApplicationData::Current->LocalSettings;
00101     auto timestampFormatter = ref new DateTimeFormatter("day month year hour minute second");
00102
00103     auto calendar = ref new Calendar();
00104     calendar->SetToNow();
00105     settings->Values->Insert("TaskStatus", reason.ToString() + " at " + timestampFormatter->Format(calendar->GetDateTime()));
00106 }
Generated on Fri Nov 15 2024 22:20:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cppwinrt/Scenario3_ClientAuthentication.h Source File

  • WebSocket
  • cppwinrt

Scenario3_ClientAuthentication.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_ClientAuthentication.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario3_ClientAuthentication : Scenario3_ClientAuthenticationT<Scenario3_ClientAuthentication>
00019     {
00020         Scenario3_ClientAuthentication();
00021
00022         Windows::Foundation::IAsyncAction OnConnect(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00023         void OnDisconnect(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00025
00026     private:
00027         Windows::Foundation::IAsyncOperation<Windows::Security::Cryptography::Certificates::Certificate> FindCertificateFromStoreAsync();
00028         Windows::Foundation::IAsyncOperation<Windows::Security::Cryptography::Certificates::Certificate> InstallClientCertificateAsync();
00029         Windows::Foundation::IAsyncOperation<Windows::Security::Cryptography::Certificates::Certificate> GetClientCertificateAsync();
00030         Windows::Foundation::IAsyncAction ConnectWebSocketAsync();
00031         Windows::Foundation::IAsyncAction OnClosed(Windows::Networking::Sockets::IWebSocket sender, Windows::Networking::Sockets::WebSocketClosedEventArgs e);
00032         void CloseSocket();
00033         void AppendOutputLine(hstring const& value);
00034         void UpdateVisualState();
00035         void SetBusy(bool value);
00036
00037         SDKTemplate::MainPage m_rootPage{ MainPage::Current() };
00038         hstring m_ClientCertUriPath{ L"ms-appx:///Assets/clientCert.pfx" };
00039         hstring m_ClientCertPassword{ L"1234" };
00040         hstring m_ClientCertFriendlyName{ L"WebSocketSampleClientCert" };
00041         hstring m_ClientCertIssuerName{ L"www.contoso.com" };
00042         Windows::Networking::Sockets::StreamWebSocket m_streamWebSocket{ nullptr };
00043         bool m_busy{ false };
00044     };
00045 }
00046
00047 namespace winrt::SDKTemplate::factory_implementation
00048 {
00049     struct Scenario3_ClientAuthentication : Scenario3_ClientAuthenticationT<Scenario3_ClientAuthentication, implementation::Scenario3_ClientAuthentication>
00050     {
00051     };
00052 }
Generated on Fri Nov 15 2024 22:22:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicFaceDetection/cppwinrt/pch.h Source File

  • BasicFaceDetection
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.h"
00007 #include "winrt/Windows.ApplicationModel.Activation.h"
00008 #include "winrt/Windows.Graphics.Imaging.h"
00009 #include "winrt/Windows.Media.h"
00010 #include "winrt/Windows.Media.Capture.h"
00011 #include "winrt/Windows.Media.Devices.h"
00012 #include "winrt/Windows.Media.FaceAnalysis.h"
00013 #include "winrt/Windows.Media.MediaProperties.h"
00014 #include "winrt/Windows.Storage.h"
00015 #include "winrt/Windows.Storage.Pickers.h"
00016 #include "winrt/Windows.Storage.Streams.h"
00017 #include "winrt/Windows.System.h"
00018 #include "winrt/Windows.UI.Core.h"
00019 #include "winrt/Windows.UI.Xaml.h"
00020 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00021 #include "winrt/Windows.UI.Xaml.Controls.h"
00022 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00023 #include "winrt/Windows.UI.Xaml.Documents.h"
00024 #include "winrt/Windows.UI.Xaml.Interop.h"
00025 #include "winrt/Windows.UI.Xaml.Markup.h"
00026 #include "winrt/Windows.UI.Xaml.Media.h"
00027 #include "winrt/Windows.UI.Xaml.Media.Imaging.h"
00028 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FolderEnumeration/cs/Scenario3.xaml.cs Source File

  • FolderEnumeration
  • cs

Scenario3.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Collections.Generic;
00013 using System.Text;
00014 using Windows.Storage;
00015 using Windows.Storage.BulkAccess;
00016 using Windows.Storage.FileProperties;
00017 using Windows.Storage.Search;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario3 : Page
00025     {
00026         public Scenario3()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         const string CopyrightProperty = "System.Copyright";
00032         const string ColorSpaceProperty = "System.Image.ColorSpace";
00033
00034         private string GetPropertyDisplayValue(object property)
00035         {
00036             string value;
00037             if (property == null || string.IsNullOrEmpty(property.ToString()))
00038             {
00039                 value = "none";
00040             }
00041             else
00042             {
00043                 value = property.ToString();
00044             }
00045
00046             return value;
00047         }
00048
00049         private async void GetFilesButton_Click(object sender, RoutedEventArgs e)
00050         {
00051             // Reset output.
00052             OutputPanel.Children.Clear();
00053
00054             // Set up file type filter.
00055             List<string> fileTypeFilter = new List<string>();
00056             fileTypeFilter.Add(".jpg");
00057             fileTypeFilter.Add(".png");
00058             fileTypeFilter.Add(".bmp");
00059             fileTypeFilter.Add(".gif");
00060
00061             // Create query options.
00062             var queryOptions = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter);
00063
00064             // Set up property prefetch - use the PropertyPrefetchOptions for top-level properties
00065             // and a list for additional properties.
00066             List<string> propertyNames = new List<string>();
00067             propertyNames.Add(CopyrightProperty);
00068             propertyNames.Add(ColorSpaceProperty);
00069             queryOptions.SetPropertyPrefetch(PropertyPrefetchOptions.ImageProperties, propertyNames);
00070
00071             // Set up thumbnail prefetch if needed, e.g. when creating a picture gallery view.
00072             /*
00073             const uint requestedSize = 190;
00074             const ThumbnailMode thumbnailMode = ThumbnailMode.PicturesView;
00075             const ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale;
00076             queryOptions.SetThumbnailPrefetch(thumbnailMode, requestedSize, thumbnailOptions);
00077             */
00078
00079             // Set up the query and retrieve files.
00080             StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
00081             var query = picturesFolder.CreateFileQueryWithOptions(queryOptions);
00082             IReadOnlyList<StorageFile> fileList = await query.GetFilesAsync();
00083             foreach (StorageFile file in fileList)
00084             {
00085                 OutputPanel.Children.Add(CreateHeaderTextBlock(file.Name));
00086
00087                 // GetImagePropertiesAsync will return synchronously when prefetching has been able to
00088                 // retrieve the properties in advance.
00089                 var properties = await file.Properties.GetImagePropertiesAsync();
00090                 OutputPanel.Children.Add(CreateLineItemTextBlock("Dimensions: " + properties.Width + "x" + properties.Height));
00091
00092                 // Similarly, extra properties are retrieved asynchronously but may
00093                 // return immediately when prefetching has fulfilled its task.
00094                 IDictionary<string, object> extraProperties = await file.Properties.RetrievePropertiesAsync(propertyNames);
00095                 var propValue = extraProperties[CopyrightProperty];
00096                 OutputPanel.Children.Add(CreateLineItemTextBlock("Copyright: " + GetPropertyDisplayValue(propValue)));
00097                 propValue = extraProperties[ColorSpaceProperty];
00098                 OutputPanel.Children.Add(CreateLineItemTextBlock("Color space: " + GetPropertyDisplayValue(propValue)));
00099
00100                 // Thumbnails can also be retrieved and used.
00101                 // var thumbnail = await file.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions);
00102             }
00103         }
00104
00105         TextBlock CreateHeaderTextBlock(string contents)
00106         {
00107             TextBlock textBlock = new TextBlock();
00108             textBlock.Text = contents;
00109             textBlock.Style = (Style)Application.Current.Resources["SampleHeaderTextStyle"];
00110             textBlock.TextWrapping = TextWrapping.Wrap;
00111             return textBlock;
00112         }
00113
00114         TextBlock CreateLineItemTextBlock(string contents)
00115         {
00116             TextBlock textBlock = new TextBlock();
00117             textBlock.Text = contents;
00118             textBlock.Style = (Style)Application.Current.Resources["BasicTextStyle"];
00119             textBlock.TextWrapping = TextWrapping.Wrap;
00120             Thickness margin = textBlock.Margin;
00121             margin.Left = 20;
00122             textBlock.Margin = margin;
00123             return textBlock;
00124         }
00125     }
00126 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialMapping/cpp/Common/DirectXHelper.h Source File

  • HolographicSpatialMapping
  • cpp
  • Common

DirectXHelper.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <ppltasks.h>    // For create_task
00015
00016 namespace DX
00017 {
00018     inline void ThrowIfFailed(HRESULT hr)
00019     {
00020         if (FAILED(hr))
00021         {
00022             // Set a breakpoint on this line to catch Win32 API errors.
00023             throw Platform::Exception::CreateException(hr);
00024         }
00025     }
00026
00027     // Function that reads from a binary file asynchronously.
00028     inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename)
00029     {
00030         using namespace Windows::Storage;
00031         using namespace Concurrency;
00032
00033         return create_task(PathIO::ReadBufferAsync(Platform::StringReference(filename.c_str()))).then(
00034             [] (Streams::IBuffer^ fileBuffer) -> std::vector<byte>
00035             {
00036                 std::vector<byte> returnBuffer;
00037                 returnBuffer.resize(fileBuffer->Length);
00038                 Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), returnBuffer.size()));
00039                 return returnBuffer;
00040             });
00041     }
00042
00043     // Converts a length in device-independent pixels (DIPs) to a length in physical pixels.
00044     inline float ConvertDipsToPixels(float dips, float dpi)
00045     {
00046         static const float dipsPerInch = 96.0f;
00047         return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00048     }
00049
00050 #if defined(_DEBUG)
00051     // Check for SDK Layer support.
00052     inline bool SdkLayersAvailable()
00053     {
00054         HRESULT hr = D3D11CreateDevice(
00055             nullptr,
00056             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00057             0,
00058             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00059             nullptr,                    // Any feature level will do.
00060             0,
00061             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00062             nullptr,                    // No need to keep the D3D device reference.
00063             nullptr,                    // No need to know the feature level.
00064             nullptr                     // No need to keep the D3D device context reference.
00065             );
00066
00067         return SUCCEEDED(hr);
00068     }
00069 #endif
00070 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_RestoreScrollPosition Member List

This is the complete list of members for Scenario5_RestoreScrollPosition, including all inherited members.
_items | Scenario5_RestoreScrollPosition | [private]
_persistedItemContainerHeight | Scenario5_RestoreScrollPosition | [private, static]
_persistedItemKey | Scenario5_RestoreScrollPosition | [private, static]
_persistedPosition | Scenario5_RestoreScrollPosition | [private, static]
GetItem(string key) | Scenario5_RestoreScrollPosition | [inline, private]
GetKey(object item) | Scenario5_RestoreScrollPosition | [inline, private]
ItemsListView_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args) | Scenario5_RestoreScrollPosition | [inline, private]
ItemsListView_ItemClick(object sender, RoutedEventArgs e) | Scenario5_RestoreScrollPosition | [inline, private]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario5_RestoreScrollPosition | [inline, protected]
Page_Loaded(object sender, RoutedEventArgs e) | Scenario5_RestoreScrollPosition | [inline, private]
Scenario5_RestoreScrollPosition() | Scenario5_RestoreScrollPosition | [inline]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Content/TextRenderer.cpp Source File

  • HolographicFaceTracking
  • cpp
  • Content

TextRenderer.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013
00014 #include "Common\DirectXHelper.h"
00015 #include "TextRenderer.h"
00016
00017 using namespace HolographicFaceTracker;
00018
00019 TextRenderer::TextRenderer(std::shared_ptr<DX::DeviceResources> deviceResources, uint32_t textureWidth, uint32_t textureHeight)
00020     : DX::Resource(std::move(deviceResources)),
00021       m_textureWidth(textureWidth),
00022       m_textureHeight(textureHeight)
00023 {
00024 }
00025
00026 void TextRenderer::RenderTextOffscreen(const std::wstring& str)
00027 {
00028     // Clear the off-screen render target.
00029     m_deviceResources->GetD3DDeviceContext()->ClearRenderTargetView(m_renderTargetView.Get(), DirectX::Colors::Transparent);
00030
00031     // Begin drawing with D2D.
00032     m_d2dRenderTarget->BeginDraw();
00033
00034     // Create a text layout to match the screen.
00035     Microsoft::WRL::ComPtr<IDWriteTextLayout> textLayout;
00036     m_deviceResources->GetDWriteFactory()->CreateTextLayout(
00037         str.c_str(),
00038         static_cast<UINT32>(str.length()),
00039         m_textFormat.Get(),
00040         static_cast<float>(m_textureWidth),
00041         static_cast<float>(m_textureHeight),
00042         &textLayout
00043         );
00044
00045     // Get the text metrics from the text layout.
00046     DWRITE_TEXT_METRICS metrics;
00047     DX::ThrowIfFailed(textLayout->GetMetrics(&metrics));
00048
00049     // In this example, we position the text in the center of the off-screen render target.
00050     D2D1::Matrix3x2F screenTranslation = D2D1::Matrix3x2F::Translation(
00051         m_textureWidth * 0.5f,
00052         m_textureHeight * 0.5f + metrics.height * 0.5f
00053         );
00054     m_whiteBrush->SetTransform(screenTranslation);
00055
00056     // Render the text using DirectWrite.
00057     m_d2dRenderTarget->DrawTextLayout(
00058         D2D1::Point2F(0.0f, 0.0f),
00059         textLayout.Get(),
00060         m_whiteBrush.Get()
00061         );
00062
00063     // End drawing with D2D.
00064     HRESULT hr = m_d2dRenderTarget->EndDraw();
00065     if (hr != D2DERR_RECREATE_TARGET)
00066     {
00067         // Catch errors from D2D.
00068         DX::ThrowIfFailed(hr);
00069     }
00070 }
00071
00072 void TextRenderer::ReleaseDeviceDependentResources()
00073 {
00074     m_texture.Reset();
00075     m_shaderResourceView.Reset();
00076     m_pointSampler.Reset();
00077     m_renderTargetView.Reset();
00078     m_d2dRenderTarget.Reset();
00079     m_whiteBrush.Reset();
00080     m_textFormat.Reset();
00081 }
00082
00083 concurrency::task<void> TextRenderer::CreateDeviceDependentResourcesAsync()
00084 {
00085     return concurrency::create_task([this]
00086     {
00087         // Create a default sampler state, which will use point sampling.
00088         CD3D11_SAMPLER_DESC desc(D3D11_DEFAULT);
00089         m_deviceResources->GetD3DDevice()->CreateSamplerState(&desc, &m_pointSampler);
00090
00091         // Create the texture that will be used as the offscreen render target.
00092         CD3D11_TEXTURE2D_DESC textureDesc(
00093             DXGI_FORMAT_B8G8R8A8_UNORM,
00094             m_textureWidth,
00095             m_textureHeight,
00096             1,
00097             1,
00098             D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET
00099         );
00100         m_deviceResources->GetD3DDevice()->CreateTexture2D(&textureDesc, nullptr, &m_texture);
00101
00102         // Create read and write views for the offscreen render target.
00103         m_deviceResources->GetD3DDevice()->CreateShaderResourceView(m_texture.Get(), nullptr, &m_shaderResourceView);
00104         m_deviceResources->GetD3DDevice()->CreateRenderTargetView(m_texture.Get(), nullptr, &m_renderTargetView);
00105
00106         // In this example, we are using D2D and DirectWrite; so, we need to create a D2D render target as well.
00107         D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
00108             D2D1_RENDER_TARGET_TYPE_DEFAULT,
00109             D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED),
00110             96,
00111             96
00112         );
00113
00114         // The DXGI surface is used to create the render target.
00115         Microsoft::WRL::ComPtr<IDXGISurface> dxgiSurface;
00116         DX::ThrowIfFailed(m_texture.As(&dxgiSurface));
00117         DX::ThrowIfFailed(m_deviceResources->GetD2DFactory()->CreateDxgiSurfaceRenderTarget(dxgiSurface.Get(), &props, &m_d2dRenderTarget));
00118
00119         // Create a solid color brush that will be used to render the text.
00120         DX::ThrowIfFailed(m_d2dRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Cornsilk), &m_whiteBrush));
00121
00122         // This is where we format the text that will be written on the render target.
00123         DX::ThrowIfFailed(
00124             m_deviceResources->GetDWriteFactory()->CreateTextFormat(
00125                 L"Consolas",
00126                 NULL,
00127                 DWRITE_FONT_WEIGHT_NORMAL,
00128                 DWRITE_FONT_STYLE_NORMAL,
00129                 DWRITE_FONT_STRETCH_NORMAL,
00130                 64.0f,
00131                 L"",
00132                 &m_textFormat
00133             )
00134         );
00135         DX::ThrowIfFailed(m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER));
00136         DX::ThrowIfFailed(m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER));
00137     });
00138 }
00139
Generated on Fri Nov 15 2024 22:18:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Events Member List

This is the complete list of members for Scenario1_Events, including all inherited members.
AccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs e) | Scenario1_Events | [inline, private]
deviceAccessInformation | Scenario1_Events | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_Events | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_Events | [inline, protected]
pedometer | Scenario1_Events | [private]
Pedometer_ReadingChanged(Pedometer sender, PedometerReadingChangedEventArgs args) | Scenario1_Events | [inline, private]
PedometerClassId | Scenario1_Events | [private]
RegisterButton_Click(object sender, RoutedEventArgs e) | Scenario1_Events | [inline, private]
registeredForEvents | Scenario1_Events | [private]
rootPage | Scenario1_Events | [private]
runningStepCount | Scenario1_Events | [private]
Scenario1_Events() | Scenario1_Events | [inline]
totalCumulativeSteps | Scenario1_Events | [private]
unknownStepCount | Scenario1_Events | [private]
walkingStepCount | Scenario1_Events | [private]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SocketReaderWriter Member List

This is the complete list of members for SocketReaderWriter, including all inherited members.
Close() | SocketReaderWriter |
dataReader | SocketReaderWriter | [private]
dataWriter | SocketReaderWriter | [private]
ReadMessageAsync() | SocketReaderWriter |
rootPage | SocketReaderWriter | [private]
SocketReaderWriter(Windows::Networking::Sockets::StreamSocket socket, MainPage mainPage) | SocketReaderWriter |
streamSocket | SocketReaderWriter | [private]
WriteMessageAsync(hstring const &message) | SocketReaderWriter |
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ImagePage Member List

This is the complete list of members for ImagePage, including all inherited members.
ImagePage() | ImagePage |
OnBackRequested(Windows::Foundation::IInspectable const &, Windows::UI::Core::BackRequestedEventArgs const &e) | ImagePage | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | ImagePage |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | ImagePage |
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSegmentation/cppwinrt/SampleConfiguration.h Source File

  • TextSegmentation
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/Scenario_SynthesizeText.xaml.h Source File

  • SpeechRecognitionAndSynthesis
  • cpp

Scenario_SynthesizeText.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario_SynthesizeText.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario_SynthesizeText sealed
00021     {
00022     public:
00023         Scenario_SynthesizeText();
00024     private:
00025         SDKTemplate::MainPage^ rootPage;
00026
00027         Windows::Media::SpeechSynthesis::SpeechSynthesizer^ synthesizer;
00028         Windows::ApplicationModel::Resources::Core::ResourceContext^ speechContext;
00029         Windows::ApplicationModel::Resources::Core::ResourceMap^ speechResourceMap;
00030
00031         void Speak_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032         void ListboxVoiceChooser_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00033         void media_MediaEnded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034
00035         void InitializeListboxVoiceChooser();
00036     };
00037 }
Generated on Fri Nov 15 2024 22:21:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: EnterpriseDataProtection/cs/Scenario5_Revoke.xaml.cs Source File

  • EnterpriseDataProtection
  • cs

Scenario5_Revoke.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Storage;
00014 using Windows.Storage.Streams;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018 using Windows.Security.EnterpriseData;
00019 using SDKTemplate;
00020
00021
00022 namespace EdpSample
00023 {
00024
00025     public sealed partial class Scenario5 : Page
00026     {
00027         private MainPage rootPage;
00028         private string m_revokeScenarioTxt = "A user has several enterprise files on their personal device which are protected " +
00029                                            "to the enterprise identity. The user loses their device. When notified, the enterprise " +
00030                                            "has sent a request to wipe all Enterprise data from the user’s device to prevent it from " +
00031                                            "leaking. The remote management client on the device has received this request from the enterprise’s " +
00032                                            "remote management server. The remote management client calls RevokeContent to revoke keys required to access " +
00033                                            "content protected to the enterprise identity.";
00034         private string m_revokeEventScenarioText = "\n\nIn order to be notified when a revoke happens, the app registers with the ProtectedContentRevoked event. " +
00035                                                    "When it receives the event, it deletes any metadata associated with the enterprise mailbox which will no longer be required. ";
00036
00037         public Scenario5()
00038         {
00039             this.InitializeComponent();
00040         }
00041
00042         protected override void OnNavigatedTo(NavigationEventArgs e)
00043         {
00044             RevokeScenarioText.Text = m_revokeScenarioTxt + m_revokeEventScenarioText;
00045
00046             rootPage = MainPage.Current;
00047             ProtectionPolicyManager.ProtectedContentRevoked += ProtectedContentRevoked;
00048         }
00049
00050         private void Revoke_Click(object sender, RoutedEventArgs e)
00051         {
00052             ProtectionPolicyManager.RevokeContent(Scenario1.m_enterpriseId);
00053             rootPage.NotifyUser("RevokeContent executed", NotifyType.StatusMessage);
00054         }
00055
00056         void ProtectedContentRevoked(Object sender, ProtectedContentRevokedEventArgs args)
00057         {
00058             RevokeEventHdlr.Text = "Content is Revoked event has fired. Do some housekeeping";
00059         }
00060     }
00061 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/SlowInputStream.h Source File

  • HttpClient
  • cppwinrt

SlowInputStream.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012 #include "SlowInputStream.g.h"
00013
00014 namespace winrt::SDKTemplate::implementation
00015 {
00016     struct SlowInputStream : SlowInputStreamT<SlowInputStream>
00017     {
00018         SlowInputStream(uint32_t length) : m_length(length) { }
00019         Windows::Foundation::IAsyncOperationWithProgress<Windows::Storage::Streams::IBuffer, uint32_t>
00020             ReadAsync(Windows::Storage::Streams::IBuffer buffer, uint32_t count, Windows::Storage::Streams::InputStreamOptions options);
00021         void Close() { }
00022
00023     private:
00024         uint32_t const m_length;
00025         std::atomic<uint32_t> m_position = 0;
00026     };
00027 }
00028
00029 namespace winrt::SDKTemplate::factory_implementation
00030 {
00031     struct SlowInputStream : SlowInputStreamT<SlowInputStream, implementation::SlowInputStream>
00032     {
00033     };
00034 }
Generated on Fri Nov 15 2024 22:19:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JapanesePhoneticAnalysis/cppwinrt/Scenario1_Analyze.cpp Source File

  • JapanesePhoneticAnalysis
  • cppwinrt

Scenario1_Analyze.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_Analyze.h"
00014 #include "Scenario1_Analyze.g.cpp"
00015 #include "MainPage.h"
00016 #include <sstream>
00017
00018 using namespace winrt;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Globalization;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario1_Analyze::Scenario1_Analyze()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     void Scenario1_Analyze::AnalyzeButton_Click(IInspectable const&, RoutedEventArgs const&)
00033     {
00034         hstring input = InputTextBox().Text();
00035         std::wostringstream output;
00036
00037         // monoRuby = false means that each element in the result corresponds to a single Japanese word.
00038         // monoRuby = true means that each element in the result corresponds to one or more characters which are pronounced as a single unit.
00039         bool monoRuby = MonoRubyRadioButton().IsChecked().Value();
00040
00041         // Analyze the Japanese text according to the specified algorithm.
00042         // The maximum length of the input string is 100 characters.
00043         IVectorView<JapanesePhoneme> words = JapanesePhoneticAnalyzer::GetWords(input, monoRuby);
00044         for (JapanesePhoneme&& word : words)
00045         {
00046             // Put each phrase on its own line.
00047             if (output.tellp() != 0 && word.IsPhraseStart())
00048             {
00049                 output << std::endl;
00050             }
00051             // DisplayText is the display text of the word, which has same characters as the input of GetWords().
00052             // YomiText is the reading text of the word, as known as Yomi, which typically consists of Hiragana characters.
00053             // However, please note that the reading can contains some non-Hiragana characters for some display texts such as emoticons or symbols.
00054             output << std::wstring_view{ word.DisplayText() } << L"(" << std::wstring_view{ word.YomiText() } << ")";
00055         }
00056
00057         // Display the result.
00058         OutputTextBlock().Text(output.str());
00059         if (!input.empty() && words.Size() == 0)
00060         {
00061             // If the result from GetWords() is empty but the input is not empty,
00062             // it means the given input is too long to analyze.
00063             MainPage::Current().NotifyUser(L"Failed to get words from the input text.  The input text is too long to analyze.", NotifyType::ErrorMessage);
00064         }
00065         else
00066         {
00067             // Otherwise, the analysis has been done successfully.
00068             MainPage::Current().NotifyUser(L"Got words from the input text successfully.", NotifyType::StatusMessage);
00069         }
00070     }
00071 }
Generated on Fri Nov 15 2024 22:20:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cppwinrt/Scenario4_Override.cpp Source File

  • DateTimeFormatting
  • cppwinrt

Scenario4_Override.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario4_Override.h"
00014 #include "Scenario4_Override.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Globalization;
00019 using namespace Windows::Globalization::DateTimeFormatting;
00020 using namespace Windows::UI::Xaml;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     Scenario4_Override::Scenario4_Override()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     void Scenario4_Override::Display_Click(IInspectable const&, RoutedEventArgs const&)
00030     {
00031         // This scenario uses the Windows.Globalization.DateTimeFormatting.DateTimeFormatter class
00032         // to format a date/time by using a formatter that provides specific languages,
00033         // geographic region, calendar and clock
00034
00035         //Get the current default application context language
00036         hstring currentLanguage = ApplicationLanguages::Languages().GetAt(0);
00037
00038         // Formatters for dates and times
00039         std::array dateFormatters{
00040             DateTimeFormatter(L"longdate", { L"ja-JP" }, L"JP", CalendarIdentifiers::Japanese(), ClockIdentifiers::TwelveHour()),
00041
00042             DateTimeFormatter(L"month day", { L"fr-FR" }, L"FR", CalendarIdentifiers::Gregorian(), ClockIdentifiers::TwentyFourHour()),
00043
00044             DateTimeFormatter(
00045                 YearFormat::Abbreviated,
00046                 MonthFormat::Abbreviated,
00047                 DayFormat::Default,
00048                 DayOfWeekFormat::None,
00049                 HourFormat::None,
00050                 MinuteFormat::None,
00051                 SecondFormat::None,
00052                 { L"de-DE" }, L"DE", CalendarIdentifiers::Gregorian(), ClockIdentifiers::TwelveHour()),
00053
00054             DateTimeFormatter(L"longtime", { L"ja-JP" }, L"JP", CalendarIdentifiers::Japanese(), ClockIdentifiers::TwelveHour()),
00055
00056             DateTimeFormatter(L"hour minute", { L"fr-FR" }, L"FR", CalendarIdentifiers::Gregorian(), ClockIdentifiers::TwentyFourHour()),
00057
00058             DateTimeFormatter(
00059                 YearFormat::None,
00060                 MonthFormat::None,
00061                 DayFormat::None,
00062                 DayOfWeekFormat::None,
00063                 HourFormat::Default,
00064                 MinuteFormat::Default,
00065                 SecondFormat::None,
00066                 { L"de-DE" }, L"DE", CalendarIdentifiers::Gregorian(), ClockIdentifiers::TwelveHour()),
00067         };
00068
00069         // Obtain the date that will be formatted.
00070         DateTime dateToFormat = clock::now();
00071
00072         // Keep the results here
00073         std::wostringstream results;
00074         results << "Current default application context language: " << std::wstring_view(currentLanguage) << std::endl << std::endl;
00075
00076         // Generate the results.
00077         for (auto&& formatter : dateFormatters)
00078         {
00079             // Perform the actual formatting.
00080             results << std::wstring_view(formatter.Template()) << L": (" << std::wstring_view(formatter.ResolvedLanguage()) << L") " << std::wstring_view(formatter.Format(dateToFormat)) << std::endl;
00081         }
00082
00083         // Display the results.
00084         OutputTextBlock().Text(results.str());
00085     }
00086 }
Generated on Fri Nov 15 2024 22:19:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlLite/cppwinrt/Scenario1_XmlReader.h Source File

  • XmlLite
  • cppwinrt

Scenario1_XmlReader.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_XmlReader.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_XmlReader : Scenario1_XmlReaderT<Scenario1_XmlReader>
00019     {
00020         Scenario1_XmlReader();
00021
00022         fire_and_forget ReadXmlClick(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00023
00024     private:
00025         static void ReadXml(std::wostream& result, com_ptr<IStream> const& readStream);
00026         static void ReadAttributes(std::wostream& result, com_ptr<IXmlReader> const& reader);
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario1_XmlReader : Scenario1_XmlReaderT<Scenario1_XmlReader, implementation::Scenario1_XmlReader>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:22:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GeofenceBackgroundTask Member List

This is the complete list of members for GeofenceBackgroundTask, including all inherited members.
GenerateReportDescription(Windows::Devices::Geolocation::Geofencing::GeofenceStateChangeReport const &report) | GeofenceBackgroundTask | [private]
GeofenceBackgroundTask() | GeofenceBackgroundTask |
maxEventDescriptors | GeofenceBackgroundTask | [private, static]
ProcessGeofenceStateChangedReports() | GeofenceBackgroundTask | [private]
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance const &taskInstance) | GeofenceBackgroundTask |
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/Scenario3CustomOptions.xaml.h Source File

  • Printing
  • cpp

Scenario3CustomOptions.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario3CustomOptions.g.h"
00006 #include "PrintHelper.h"
00007
00008 namespace SDKTemplate
00009 {
00010     enum DisplayContent
00011     {
00012         /// <summary>
00013         /// Show only text
00014         /// </summary>
00015         Text = 1,
00016
00017         /// <summary>
00018         /// Show only images
00019         /// </summary>
00020         Images = 2,
00021
00022         /// <summary>
00023         /// Show a combination of images and text
00024         /// </summary>
00025         TextAndImages = 3
00026     };
00027
00028     ref class CustomOptionsPrintHelper sealed : public PrintHelper
00029     {
00030     public:
00031         CustomOptionsPrintHelper(Page^ scenarioPage);
00032
00033     protected:
00034         /// <summary>
00035         /// This is the event handler for PrintManager.PrintTaskRequested.
00036         /// In order to ensure a good user experience, the system requires that the app handle the PrintTaskRequested event within the time specified by PrintTaskRequestedEventArgs->Request->Deadline.
00037         /// Therefore, we use this handler to only create the print task.
00038         /// The print settings customization can be done when the print document source is requested.
00039         /// </summary>
00040         /// <param name="sender">PrintManager</param>
00041         /// <param name="e">PrintTaskRequestedEventArgs</param>
00042         virtual void PrintTaskRequested(Windows::Graphics::Printing::PrintManager^ sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^ e) override;
00043
00044         /// <summary>
00045         /// This is the event handler for PrintDocument.Paginate. It creates print preview pages for the app.
00046         /// </summary>
00047         /// <param name="sender"></param>
00048         /// <param name="e">Paginate Event Arguments</param>
00049         virtual void CreatePrintPreviewPages(Object^ sender, Windows::UI::Xaml::Printing::PaginateEventArgs^ e) override;
00050
00051         /// <summary>
00052         /// This function creates and adds one print preview page to the internal cache of print preview
00053         /// pages stored in m_printPreviewPages.
00054         /// </summary>
00055         /// <param name="lastRTBOAdded">Last RichTextBlockOverflow element added in the current content</param>
00056         /// <param name="printPageDescription">Printer's page description</param>
00057         virtual Windows::UI::Xaml::Controls::RichTextBlockOverflow^ AddOnePrintPreviewPage(
00058             Windows::UI::Xaml::Controls::RichTextBlockOverflow^ lastRTBOAdded,
00059             Windows::Graphics::Printing::PrintPageDescription printPageDescription) override;
00060
00061     private:
00062         /// <summary>
00063         /// A flag that determines if text & images are to be shown
00064         /// </summary>
00065         DisplayContent m_imageText;
00066
00067         /// <summary>
00068         /// Helper getter for image showing
00069         /// </summary>
00070         property bool ShowImage
00071         {
00072             bool get()
00073             {
00074                 return (m_imageText & DisplayContent::Images) == DisplayContent::Images;
00075             }
00076         }
00077
00078         /// <summary>
00079         /// Helper getter for text showing
00080         /// </summary>
00081         property bool ShowText
00082         {
00083             bool get()
00084             {
00085                 return (m_imageText & DisplayContent::Text) == DisplayContent::Text;
00086             }
00087         }
00088
00089         /// <summary>
00090         /// Option change event handler
00091         /// </summary>
00092         /// <param name="sender">PrintTaskOptionsDetails object</param>
00093         /// <param name="args">the event arguments containing the changed option id</param>
00094         void printDetailedOptions_OptionChanged(Windows::Graphics::Printing::OptionDetails::PrintTaskOptionDetails^ sender,
00095             Windows::Graphics::Printing::OptionDetails::PrintTaskOptionChangedEventArgs^ args);
00096
00097         /// <summary>
00098         /// Helper function used to triger a preview refresh
00099         /// </summary>
00100         void RefreshPreview();
00101
00102         /// <summary>
00103         /// Helper function used to set the top and left margins based on used selection
00104         /// </summary>
00105         /// <param name="marginsValue">The Id of the option selected by the user</param>
00106         void SetMargins(Platform::String^ marginsValue);
00107
00108         Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStreamWithContentType^>^ m_wideMarginsIconAsyncOperation;
00109         Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStreamWithContentType^>^ m_moderateMarginsIconAsyncOperation;
00110         Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStreamWithContentType^>^ m_narrowMarginsIconAsyncOperation;
00111
00112         bool m_showHeader;
00113     };
00114
00115     /// <summary>
00116     /// Scenario that demos how to add custom options (specific for the application)
00117     /// </summary>
00118     [Windows::Foundation::Metadata::WebHostHidden]
00119     public ref class Scenario3CustomOptions sealed
00120     {
00121     public:
00122         Scenario3CustomOptions();
00123
00124     protected:
00125         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00126         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00127
00128     private:
00129         PrintHelper^ printHelper;
00130         void OnPrintButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00131     };
00132 }
Generated on Fri Nov 15 2024 22:21:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Basics Member List

This is the complete list of members for Scenario1_Basics, including all inherited members.
Apply_Clicked(object sender, RoutedEventArgs e) | Scenario1_Basics | [inline, private]
ApplySettingsToLampArray(LampArray lampArray) | Scenario1_Basics | [inline, private]
CameraButtonPressCount | Scenario1_Basics | [private]
CheckBackgroundAccessStatus() | Scenario1_Basics | [inline, private]
GetOrientationReport() | Scenario1_Basics | [inline, private]
HardwareButtons_CameraPressed(object sender, CameraEventArgs e) | Scenario1_Basics | [inline, private]
hasAlwaysAllowedAccess | Scenario1_Basics | [private]
hasCameraButton | Scenario1_Basics | [private]
hasOrientationWithOptimizationGoal | Scenario1_Basics | [private]
LampArray_AvailabilityChanged(LampArray sender, object args) | Scenario1_Basics | [inline, private]
m_attachedLampArrays | Scenario1_Basics | [private]
m_deviceWatcher | Scenario1_Basics | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_Basics | [inline, protected]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_Basics | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_Basics | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_Basics | [inline, protected]
rootPage | Scenario1_Basics | [private]
Scenario1_Basics() | Scenario1_Basics | [inline]
Scenario1_Basics() | Scenario1_Basics | [inline]
SetGradientPatternToLampArray(LampArray lampArray) | Scenario1_Basics | [inline, private]
SetWasdPatternToLampArray(LampArray lampArray) | Scenario1_Basics | [inline, private]
UpdateLampArrayList() | Scenario1_Basics | [inline, private]
Watcher_Added(DeviceWatcher sender, DeviceInformation args) | Scenario1_Basics | [inline, private]
Watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args) | Scenario1_Basics | [inline, private]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/AppView.h Source File

  • HolographicVoiceInput
  • cpp

AppView.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 #include "Common\DeviceResources.h"
00014 #include "HolographicVoiceInputMain.h"
00015
00016 namespace HolographicVoiceInput
00017 {
00018     // IFrameworkView class. Connects the app with the Windows shell and handles application lifecycle events.
00019     ref class AppView sealed : public Windows::ApplicationModel::Core::IFrameworkView
00020     {
00021     public:
00022         AppView();
00023
00024         // IFrameworkView methods.
00025         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00026         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00027         virtual void Load(Platform::String^ entryPoint);
00028         virtual void Run();
00029         virtual void Uninitialize();
00030
00031     protected:
00032         // Application lifecycle event handlers.
00033         void OnViewActivated(Windows::ApplicationModel::Core::CoreApplicationView^ sender, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00034         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00035         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00036
00037         // Window event handlers.
00038         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00039         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00040
00041         // CoreWindow input event handlers.
00042         void OnKeyPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args);
00043
00044     private:
00045         std::unique_ptr<HolographicVoiceInputMain> m_main;
00046
00047         std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00048         bool                                                m_windowClosed  = false;
00049         bool                                                m_windowVisible = true;
00050
00051         // The holographic space the app will use for rendering.
00052         Windows::Graphics::Holographic::HolographicSpace^   m_holographicSpace = nullptr;
00053     };
00054
00055     // The entry point for the app.
00056     ref class AppViewSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00057     {
00058     public:
00059         virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00060     };
00061 }
00062
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cs/Scenario4_SaveFile.xaml.cs Source File

  • FilePicker
  • cs

Scenario4_SaveFile.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Storage;
00015 using Windows.Storage.Pickers;
00016 using Windows.Storage.Provider;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026     public sealed partial class Scenario4_SaveFile : Page
00027     {
00028         MainPage rootPage = MainPage.Current;
00029
00030         public Scenario4_SaveFile()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         private async void SaveFileButton_Click(object sender, RoutedEventArgs e)
00036         {
00037             // Clear previous returned file name, if it exists, between iterations of this scenario
00038             OutputTextBlock.Text = "";
00039
00040             FileSavePicker savePicker = new FileSavePicker();
00041             savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
00042             // Dropdown of file types the user can save the file as
00043             savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
00044             // Default file name if the user does not type one in or select a file to replace
00045             savePicker.SuggestedFileName = "New Document";
00046             StorageFile file = await savePicker.PickSaveFileAsync();
00047             if (file != null)
00048             {
00049                 // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
00050                 CachedFileManager.DeferUpdates(file);
00051                 // write to file
00052                 await FileIO.WriteTextAsync(file, "Example file contents.");
00053                 // Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
00054                 // Completing updates may require Windows to ask for user input.
00055                 FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
00056                 if (status == FileUpdateStatus.Complete)
00057                 {
00058                     OutputTextBlock.Text = "File " + file.Name + " was saved.";
00059                 }
00060                 else if (status == FileUpdateStatus.CompleteAndRenamed)
00061                 {
00062                     OutputTextBlock.Text = "File " + file.Name + " was renamed and saved.";
00063                 }
00064                 else
00065                 {
00066                     OutputTextBlock.Text = "File " + file.Name + " couldn't be saved.";
00067                 }
00068             }
00069             else
00070             {
00071                 OutputTextBlock.Text = "Operation cancelled.";
00072             }
00073         }
00074     }
00075 }
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OnDemandHotspot/cppwinrt/BackgroundTask/Tasks.h Source File

  • OnDemandHotspot
  • cppwinrt
  • BackgroundTask

Tasks.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014 #include "UpdateMetadataTask.g.h"
00015 #include "ConnectTask.g.h"
00016
00017 namespace winrt::BackgroundTask::implementation
00018 {
00019     struct UpdateMetadataTask : UpdateMetadataTaskT<UpdateMetadataTask>
00020     {
00021         void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance const& taskInstance);
00022     };
00023
00024     struct ConnectTask : ConnectTaskT<ConnectTask>
00025     {
00026         void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance const& taskInstance);
00027         void DisplayToast(const winrt::hstring& ssid);
00028     };
00029 }
00030
00031 namespace winrt::BackgroundTask::factory_implementation
00032 {
00033     struct UpdateMetadataTask : UpdateMetadataTaskT<UpdateMetadataTask, implementation::UpdateMetadataTask>
00034     {
00035     };
00036
00037     struct ConnectTask : ConnectTaskT<ConnectTask, implementation::ConnectTask>
00038     {
00039     };
00040 }
Generated on Fri Nov 15 2024 22:20:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_ActiveSymbologies Member List

This is the complete list of members for Scenario3_ActiveSymbologies, including all inherited members.
claimedScanner | Scenario3_ActiveSymbologies | [private]
claimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args) | Scenario3_ActiveSymbologies | [inline, private]
claimedScanner_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e) | Scenario3_ActiveSymbologies | [inline, private]
listOfSymbologies | Scenario3_ActiveSymbologies | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario3_ActiveSymbologies | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_ActiveSymbologies | [inline, protected]
ResetTheScenarioState() | Scenario3_ActiveSymbologies | [inline, private]
rootPage | Scenario3_ActiveSymbologies | [private]
scanner | Scenario3_ActiveSymbologies | [private]
Scenario3_ActiveSymbologies() | Scenario3_ActiveSymbologies | [inline]
ScenarioEndScanButton_Click(object sender, RoutedEventArgs e) | Scenario3_ActiveSymbologies | [inline, private]
ScenarioStartScanButton_Click(object sender, RoutedEventArgs e) | Scenario3_ActiveSymbologies | [inline, private]
SetActiveSymbologies_Click(object sender, RoutedEventArgs e) | Scenario3_ActiveSymbologies | [inline, private]
Generated on Fri Nov 15 2024 22:23:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomHidDeviceAccess/cs/DeviceListEntry.cs Source File

  • CustomHidDeviceAccess
  • cs

DeviceListEntry.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using System;
00008 using System.Collections.Generic;
00009 using System.Linq;
00010 using System.Text;
00011 using System.Threading.Tasks;
00012 using Windows.Devices.Enumeration;
00013
00014 namespace CustomHidDeviceAccess
00015 {
00016     /// <summary>
00017     /// The class will only expose properties from DeviceInformation that are going to be used
00018     /// in this sample. Each instance of this class provides information about a single device.
00019     ///
00020     /// This class is used by the UI to display device specific information so that
00021     /// the user can identify which device to use.
00022     /// </summary>
00023     public class DeviceListEntry
00024     {
00025         private DeviceInformation device;
00026         private String deviceSelector;
00027
00028         public String InstanceId
00029         {
00030             get
00031             {
00032                 return (String)device.Properties[DeviceProperties.DeviceInstanceId];
00033             }
00034         }
00035
00036         public DeviceInformation DeviceInformation
00037         {
00038             get
00039             {
00040                 return device;
00041             }
00042         }
00043
00044         public String DeviceSelector
00045         {
00046             get
00047             {
00048                 return deviceSelector;
00049             }
00050         }
00051
00052         /// <summary>
00053         /// The class is mainly used as a DeviceInformation wrapper so that the UI can bind to a list of these.
00054         /// </summary>
00055         /// <param name="deviceInformation"></param>
00056         /// <param name="deviceSelector">The AQS used to find this device</param>
00057         public DeviceListEntry(Windows.Devices.Enumeration.DeviceInformation deviceInformation, String deviceSelector)
00058         {
00059             device = deviceInformation;
00060             this.deviceSelector = deviceSelector;
00061         }
00062
00063     }
00064 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cs/Scenario3_BackgroundDeviceWatcher.xaml.cs Source File

  • DeviceEnumerationAndPairing
  • cs

Scenario3_BackgroundDeviceWatcher.xaml.cs

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 using System;
00004 using Windows.ApplicationModel.Background;
00005 using Windows.Devices.Enumeration;
00006 using Windows.Storage;
00007 using Windows.UI.Core;
00008 using Windows.UI.Xaml;
00009 using Windows.UI.Xaml.Controls;
00010 using Windows.UI.Xaml.Navigation;
00011
00012 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00013
00014 namespace SDKTemplate
00015 {
00016     /// <summary>
00017     /// An empty page that can be used on its own or navigated to within a Frame.
00018     /// </summary>
00019     public sealed partial class Scenario3_BackgroundDeviceWatcher : Page
00020     {
00021         private MainPage rootPage = MainPage.Current;
00022
00023         private string backgroundTaskName = "DeviceEnumerationCs_BackgroundTaskName";
00024         private IBackgroundTaskRegistration backgroundTaskRegistration = null;
00025
00026         public Scenario3_BackgroundDeviceWatcher()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         protected override void OnNavigatedTo(NavigationEventArgs e)
00032         {
00033             selectorComboBox.ItemsSource = DeviceSelectorChoices.BackgroundDeviceWatcherSelectors;
00034             selectorComboBox.SelectedIndex = 0;
00035
00036             // Determine if the background task is already active
00037             foreach (var task in BackgroundTaskRegistration.AllTasks)
00038             {
00039                 if (backgroundTaskName == task.Value.Name)
00040                 {
00041                     backgroundTaskRegistration = task.Value;
00042                     startWatcherButton.IsEnabled = false;
00043                     stopWatcherButton.IsEnabled = true;
00044                     break;
00045                 }
00046             }
00047         }
00048
00049         protected override void OnNavigatedFrom(NavigationEventArgs e)
00050         {
00051             if (backgroundTaskRegistration != null)
00052             {
00053                 backgroundTaskRegistration.Completed -= OnTaskCompleted;
00054                 backgroundTaskRegistration = null;
00055             }
00056         }
00057
00058         private void StartWatcherButton_Click(object sender, RoutedEventArgs e)
00059         {
00060             StartWatcher();
00061         }
00062
00063         private void StopWatcherButton_Click(object sender, RoutedEventArgs e)
00064         {
00065             StopWatcher();
00066         }
00067
00068         private void StartWatcher()
00069         {
00070             DeviceWatcherEventKind[] triggerEventKinds = { DeviceWatcherEventKind.Add, DeviceWatcherEventKind.Remove, DeviceWatcherEventKind.Update };
00071             DeviceWatcher deviceWatcher = null;
00072
00073             startWatcherButton.IsEnabled = false;
00074
00075             // First get the device selector chosen by the UI.
00076             DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;
00077
00078             if (null == deviceSelectorInfo.Selector)
00079             {
00080                 // If the a pre-canned device class selector was chosen, call the DeviceClass overload
00081                 deviceWatcher = DeviceInformation.CreateWatcher(deviceSelectorInfo.DeviceClassSelector);
00082             }
00083             else if (deviceSelectorInfo.Kind == DeviceInformationKind.Unknown)
00084             {
00085                 // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
00086                 // Kind will be determined by the selector
00087                 deviceWatcher = DeviceInformation.CreateWatcher(
00088                     deviceSelectorInfo.Selector,
00089                     null // don't request additional properties for this sample
00090                     );
00091             }
00092             else
00093             {
00094                 // Kind is specified in the selector info
00095                 deviceWatcher = DeviceInformation.CreateWatcher(
00096                     deviceSelectorInfo.Selector,
00097                     null, // don't request additional properties for this sample
00098                     deviceSelectorInfo.Kind);
00099             }
00100
00101             // Get the background trigger for this watcher
00102             DeviceWatcherTrigger deviceWatcherTrigger = deviceWatcher.GetBackgroundTrigger(triggerEventKinds);
00103
00104             rootPage.NotifyUser("Starting Watcher...", NotifyType.StatusMessage);
00105
00106             // Register this trigger for our background task
00107             RegisterBackgroundTask(deviceWatcherTrigger);
00108
00109             stopWatcherButton.IsEnabled = true;
00110             rootPage.NotifyUser("Watcher started...", NotifyType.StatusMessage);
00111         }
00112
00113         private void RegisterBackgroundTask(DeviceWatcherTrigger deviceWatcherTrigger)
00114         {
00115             BackgroundTaskBuilder taskBuilder;
00116
00117             // First see if we already have this background task registered. If so, unregister
00118             // it before we register it with the new trigger.
00119
00120             foreach (var task in BackgroundTaskRegistration.AllTasks)
00121             {
00122                 if (backgroundTaskName == task.Value.Name)
00123                 {
00124                     UnregisterBackgroundTask(task.Value);
00125                 }
00126             }
00127
00128             taskBuilder = new BackgroundTaskBuilder();
00129             taskBuilder.Name = backgroundTaskName;
00130             taskBuilder.TaskEntryPoint = "BackgroundDeviceWatcherTaskCs.BackgroundDeviceWatcher";
00131             taskBuilder.SetTrigger(deviceWatcherTrigger);
00132
00133             backgroundTaskRegistration = taskBuilder.Register();
00134             backgroundTaskRegistration.Completed += OnTaskCompleted;
00135         }
00136
00137         private async void OnTaskCompleted(BackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
00138         {
00139             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00140             {
00141                 rootPage.NotifyUser("Background task completed", NotifyType.StatusMessage);
00142             });
00143         }
00144
00145         private void StopWatcher()
00146         {
00147             stopWatcherButton.IsEnabled = false;
00148             if (null != backgroundTaskRegistration)
00149             {
00150                 UnregisterBackgroundTask(backgroundTaskRegistration);
00151             }
00152             startWatcherButton.IsEnabled = true;
00153         }
00154
00155         private void UnregisterBackgroundTask(IBackgroundTaskRegistration taskReg)
00156         {
00157             taskReg.Unregister(true);
00158             ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
00159             settings.Values["eventCount"] = (uint)0;
00160         }
00161     }
00162 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
__pad0__ | sealed |
_connectionId | sealed | [private]
_critSec | sealed | [private]
_fShutdown | sealed | [private]
_remoteUrl | sealed | [private]
_spMediaSink | sealed | [private]
_spSink | sealed | [private]
CheckShutdown() | sealed | [inline, private]
connectionId | sealed |
FireIncomingConnection(IncomingConnectionEventArgs^args) | sealed | [private]
GetMFExtensions() | sealed |
IncomingConnectionEvent | sealed |
InitializeAsync(Windows::Media::MediaProperties::IMediaEncodingProperties^audioEncodingProperties, Windows::Media::MediaProperties::IMediaEncodingProperties^videoEncodingProperties) | sealed |
mediaEncodingProperties | sealed |
OnShutdown() | sealed | [private]
Refuse() | sealed |
remoteUrl | sealed |
StspMediaSinkProxy() | sealed |
~StspMediaSinkProxy() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_SimpleListView Member List

This is the complete list of members for Scenario1_SimpleListView, including all inherited members.
Scenario1_SimpleListView() Scenario1_SimpleListView
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/pch.h Source File

  • XamlListView
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include <winrt/Windows.Foundation.h>
00005 #include <winrt/Windows.Foundation.Collections.h>
00006 #include <winrt/Windows.ApplicationModel.Activation.h>
00007 #include <winrt/Windows.Devices.Input.h>
00008 #include <winrt/Windows.System.h>
00009 #include <winrt/Windows.UI.Core.h>
00010 #include <winrt/Windows.UI.Input.h>
00011 #include <winrt/Windows.UI.Xaml.h>
00012 #include <winrt/Windows.UI.Xaml.Automation.Peers.h>
00013 #include <winrt/Windows.UI.Xaml.Controls.h>
00014 #include <winrt/Windows.UI.Xaml.Controls.Primitives.h>
00015 #include <winrt/Windows.UI.Xaml.Data.h>
00016 #include <winrt/Windows.UI.Xaml.Documents.h>
00017 #include <winrt/Windows.UI.Xaml.Input.h>
00018 #include <winrt/Windows.UI.Xaml.Interop.h>
00019 #include <winrt/Windows.UI.Xaml.Markup.h>
00020 #include <winrt/Windows.UI.Xaml.Media.h>
00021 #include <winrt/Windows.UI.Xaml.Media.Animation.h>
00022 #include <winrt/Windows.UI.Xaml.Media.Imaging.h>
00023 #include <winrt/Windows.UI.Xaml.Navigation.h>
00024 #include <winrt/Windows.UI.Xaml.Shapes.h>
00025 #include <winrt/SDKTemplate.h>
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cppwinrt/SampleConfiguration.cpp Source File

  • ResizeAppView
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"Resize app view";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Resizing the view", xaml_typename<SDKTemplate::Scenario1_Basic>() },
00029     Scenario{ L"Launching at a custom size", xaml_typename<SDKTemplate::Scenario2_Launch>() },
00030 });
Generated on Fri Nov 15 2024 22:17:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Scenario7_ForegroundVisits.h Source File

  • Geolocation
  • cppwinrt

Scenario7_ForegroundVisits.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario7_ForegroundVisits.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario7_ForegroundVisits : Scenario7_ForegroundVisitsT<Scenario7_ForegroundVisits>
00019     {
00020         Scenario7_ForegroundVisits();
00021
00022         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00023
00024         fire_and_forget StartMonitoring(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00025         void StopMonitoring(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00026
00027     private:
00028         SDKTemplate::MainPage m_rootPage{ MainPage::Current() };
00029
00030         // Provides access to visits
00031         Windows::Devices::Geolocation::GeovisitMonitor m_visitMonitor{ nullptr };
00032         event_token m_visitStateChangedToken{};
00033
00034         fire_and_forget OnVisitStateChanged(Windows::Devices::Geolocation::GeovisitMonitor const&, Windows::Devices::Geolocation::GeovisitStateChangedEventArgs args);
00035         void UpdateVisitData(Windows::Devices::Geolocation::Geovisit const& visit);
00036     };
00037 }
00038
00039 namespace winrt::SDKTemplate::factory_implementation
00040 {
00041     struct Scenario7_ForegroundVisits : Scenario7_ForegroundVisitsT<Scenario7_ForegroundVisits, implementation::Scenario7_ForegroundVisits>
00042     {
00043     };
00044 }
Generated on Fri Nov 15 2024 22:19:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/MediaBufferWrapper.cpp Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

MediaBufferWrapper.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "MediaBufferWrapper.h"
00010
00011 using namespace Microsoft::Samples::SimpleCommunication::Network;
00012
00013 HRESULT Microsoft::Samples::SimpleCommunication::Network::CreateMediaBufferWrapper(DWORD dwMaxLength, _Outptr_ IMediaBufferWrapper **ppMediaBufferWrapper)
00014 {
00015     return CMediaBufferWrapper::CreateInstance(dwMaxLength, ppMediaBufferWrapper);
00016 }
00017
00018 HRESULT Microsoft::Samples::SimpleCommunication::Network::CreateMediaBufferWrapper(_In_ IMFMediaBuffer *pMediaBuffer, _Outptr_ IMediaBufferWrapper **ppMediaBufferWrapper)
00019 {
00020     return CMediaBufferWrapper::CreateInstance(pMediaBuffer, ppMediaBufferWrapper);
00021 }
00022
00023 CMediaBufferWrapper::CMediaBufferWrapper(void)
00024     : _pBuffer(nullptr)
00025     , _nOffset(0)
00026 {
00027     TRACE(TRACE_LEVEL_LOW, L"Creating CMediaBufferWrapper %p\n", this);
00028 }
00029
00030 CMediaBufferWrapper::~CMediaBufferWrapper(void)
00031 {
00032     if (_spMediaBuffer)
00033     {
00034         if (_sp2DBuffer)
00035         {
00036             _sp2DBuffer->Unlock2D();
00037         }
00038         else
00039         {
00040             _spMediaBuffer->Unlock();
00041         }
00042     }
00043     TRACE(TRACE_LEVEL_LOW, L"Deleting CMediaBufferWrapper %p\n", this);
00044 }
00045
00046 HRESULT CMediaBufferWrapper::CreateInstance(DWORD cbMaxLength, _Outptr_ IMediaBufferWrapper **ppMediaBufferWrapper)
00047 {
00048     ComPtr<IMFMediaBuffer> spMediaBuffer;
00049     HRESULT hr = MFCreateMemoryBuffer(cbMaxLength, &spMediaBuffer);
00050
00051     if (SUCCEEDED(hr))
00052     {
00053         hr = CMediaBufferWrapper::CreateInstance(spMediaBuffer.Get(), ppMediaBufferWrapper);
00054     }
00055
00056     TRACEHR_RET(hr);
00057 }
00058
00059 HRESULT CMediaBufferWrapper::CreateInstance(_In_ IMFMediaBuffer *pMediaBuffer, _Outptr_ IMediaBufferWrapper **ppMediaBufferWrapper)
00060 {
00061     HRESULT hr = S_OK;
00062     ComPtr<CMediaBufferWrapper> spResult;
00063
00064     if (pMediaBuffer == nullptr || ppMediaBufferWrapper == nullptr)
00065     {
00066         return E_INVALIDARG;
00067     }
00068
00069     hr = MakeAndInitialize<CMediaBufferWrapper>(&spResult, pMediaBuffer);
00070
00071     if (!spResult)
00072     {
00073         hr = E_OUTOFMEMORY;
00074     }
00075
00076     if (SUCCEEDED(hr))
00077     {
00078         *ppMediaBufferWrapper = spResult.Detach();
00079     }
00080
00081     TRACEHR_RET(hr);
00082 }
00083
00084 HRESULT CMediaBufferWrapper::RuntimeClassInitialize(IMFMediaBuffer *pMediaBuffer)
00085 {
00086     assert(pMediaBuffer != nullptr);
00087
00088     DWORD cbMaxLength;
00089     DWORD cbCurrentLength;
00090     HRESULT hr = S_OK;
00091     if (SUCCEEDED(pMediaBuffer->QueryInterface(IID_PPV_ARGS(&_sp2DBuffer))))
00092     {
00093         LONG lPitch;
00094         hr = _sp2DBuffer->Lock2D(&_pBuffer, &lPitch);
00095         TRACE(TRACE_LEVEL_LOW, L"D3D CMediaBufferWrapper %p\n", this);
00096     }
00097     else
00098     {
00099         hr = pMediaBuffer->Lock(&_pBuffer, &cbMaxLength, &cbCurrentLength);
00100     }
00101
00102     if (SUCCEEDED(hr))
00103     {
00104         _spMediaBuffer = pMediaBuffer;
00105     }
00106     else
00107     {
00108         __debugbreak();
00109     }
00110
00111     TRACEHR_RET(hr);
00112 }
00113
00114 // IBuffer methods
00115 IFACEMETHODIMP CMediaBufferWrapper::get_Capacity(UINT *pcbCapacity)
00116 {
00117     DWORD cbCapacity = 0;
00118     HRESULT hr = _spMediaBuffer->GetMaxLength(&cbCapacity);
00119
00120     *pcbCapacity = cbCapacity;
00121
00122     return hr;
00123 }
00124
00125 IFACEMETHODIMP CMediaBufferWrapper::get_Length(UINT *pcbLength)
00126 {
00127     DWORD cbLength = 0;
00128     HRESULT hr = GetCurrentLength(&cbLength);
00129
00130     *pcbLength = cbLength;
00131
00132     return hr;
00133 }
00134
00135 IFACEMETHODIMP CMediaBufferWrapper::put_Length(UINT cbLength)
00136 {
00137     return SetCurrentLength(cbLength);
00138 }
00139
00140 // IBufferByteAccess methods
00141 IFACEMETHODIMP CMediaBufferWrapper::Buffer(_Out_ BYTE **ppBuffer)
00142 {
00143     *ppBuffer = GetBuffer();
00144     return S_OK;
00145 }
00146
00147 // IMarshal methods
00148 IFACEMETHODIMP CMediaBufferWrapper::GetUnmarshalClass(REFIID riid, _In_opt_ void *pv, DWORD dwDestContext,
00149                                                       _Reserved_ void *pvDestContext, DWORD mshlflags, _Out_ CLSID *pclsid)
00150 {
00151     HRESULT hr = CheckMarshal();
00152
00153     if (SUCCEEDED(hr))
00154     {
00155         hr = _spBufferMarshal->GetUnmarshalClass(riid, pv, dwDestContext, pvDestContext, mshlflags, pclsid);
00156     }
00157
00158     return hr;
00159 }
00160
00161 IFACEMETHODIMP CMediaBufferWrapper::GetMarshalSizeMax(REFIID riid, _In_opt_ void *pv, DWORD dwDestContext,
00162                                                       _Reserved_ void *pvDestContext, DWORD mshlflags, _Out_ DWORD *pcbSize)
00163 {
00164     HRESULT hr = CheckMarshal();
00165
00166     if (SUCCEEDED(hr))
00167     {
00168         hr = _spBufferMarshal->GetMarshalSizeMax(riid, pv, dwDestContext, pvDestContext, mshlflags, pcbSize);
00169     }
00170
00171     return hr;
00172 }
00173
00174 IFACEMETHODIMP CMediaBufferWrapper::MarshalInterface(_In_ IStream *pStm, REFIID riid, _In_opt_ void *pv, DWORD dwDestContext,
00175                                                      _Reserved_ void *pvDestContext, DWORD mshlflags)
00176 {
00177     HRESULT hr = CheckMarshal();
00178
00179     if (SUCCEEDED(hr))
00180     {
00181         hr = _spBufferMarshal->MarshalInterface(pStm,riid, pv, dwDestContext, pvDestContext, mshlflags);
00182     }
00183
00184     return hr;
00185 }
00186
00187 IFACEMETHODIMP CMediaBufferWrapper::UnmarshalInterface(_In_ IStream *, _In_ REFIID, _Outptr_ void **)
00188 {
00189     return E_NOTIMPL;
00190 }
00191
00192 IFACEMETHODIMP CMediaBufferWrapper::ReleaseMarshalData(_In_ IStream *)
00193 {
00194     return E_NOTIMPL;
00195 }
00196
00197 IFACEMETHODIMP CMediaBufferWrapper::DisconnectObject(DWORD)
00198 {
00199     return E_NOTIMPL;
00200 }
00201
00202 // IMediaBufferWrapper methods
00203 IFACEMETHODIMP CMediaBufferWrapper::SetOffset(DWORD nOffset)
00204 {
00205     DWORD cbCurrentLength;
00206
00207     HRESULT hr = _spMediaBuffer->GetCurrentLength(&cbCurrentLength);
00208
00209     if (SUCCEEDED(hr))
00210     {
00211         if (cbCurrentLength < nOffset)
00212         {
00213             hr = E_INVALIDARG;
00214         }
00215     }
00216
00217     TRACEHR_RET(hr);
00218 }
00219
00220 IFACEMETHODIMP CMediaBufferWrapper::GetCurrentLength(DWORD *pcbCurrentLength)
00221 {
00222     if (pcbCurrentLength == nullptr)
00223     {
00224         return E_INVALIDARG;
00225     }
00226     DWORD cbCurrentLength;
00227
00228     HRESULT hr = _spMediaBuffer->GetCurrentLength(&cbCurrentLength);
00229
00230     if (SUCCEEDED(hr))
00231     {
00232         if (cbCurrentLength <= _nOffset)
00233         {
00234             cbCurrentLength = 0;
00235         }
00236         else
00237         {
00238             cbCurrentLength -= _nOffset;
00239         }
00240
00241         *pcbCurrentLength = cbCurrentLength;
00242     }
00243
00244     TRACEHR_RET(hr);
00245 }
00246
00247 IFACEMETHODIMP CMediaBufferWrapper::SetCurrentLength(DWORD cbCurrentLength)
00248 {
00249     DWORD cbMaxLen = 0;
00250     HRESULT hr = _spMediaBuffer->GetMaxLength(&cbMaxLen);
00251
00252     if (SUCCEEDED(hr))
00253     {
00254         if (_nOffset > cbMaxLen)
00255         {
00256             _nOffset = cbMaxLen;
00257         }
00258
00259         if (cbCurrentLength > (cbMaxLen - _nOffset))
00260         {
00261             hr = E_INVALIDARG;
00262         }
00263         else
00264         {
00265             hr = _spMediaBuffer->SetCurrentLength(cbCurrentLength+_nOffset);
00266         }
00267     }
00268     TRACEHR_RET(hr);
00269 }
00270
00271 IFACEMETHODIMP CMediaBufferWrapper::TrimLeft(DWORD cbSize)
00272 {
00273     DWORD cbCurrentLen;
00274     HRESULT hr = GetCurrentLength(&cbCurrentLen);
00275
00276     if (SUCCEEDED(hr))
00277     {
00278         if (cbCurrentLen >= cbSize)
00279         {
00280             _nOffset += cbSize;
00281         }
00282         else
00283         {
00284             hr = E_INVALIDARG;
00285         }
00286     }
00287
00288     TRACEHR_RET(hr);
00289 }
00290
00291 // Trims cbSize bytes from the right end and returns them as a new buffer
00292 IFACEMETHODIMP CMediaBufferWrapper::TrimRight(DWORD cbSize, _Out_ IMediaBufferWrapper **pWrapper)
00293 {
00294     if (pWrapper == nullptr)
00295     {
00296         return E_INVALIDARG;
00297     }
00298
00299     ComPtr<IMediaBufferWrapper> spResult;
00300     DWORD cbCurrentLen;
00301     HRESULT hr = this->GetCurrentLength(&cbCurrentLen);
00302
00303     // Offset cannot be larger than current length.
00304     if (SUCCEEDED(hr) && cbCurrentLen <= cbSize)
00305     {
00306         return E_INVALIDARG;
00307     }
00308
00309     // Create result buffer representing at the end of the current one
00310     if (SUCCEEDED(hr))
00311     {
00312         ComPtr<IMFMediaBuffer> spMediaBuffer;
00313         hr = MFCreateMediaBufferWrapper(GetMediaBuffer(), GetOffset() + cbCurrentLen - cbSize, cbSize, &spMediaBuffer);
00314
00315         if (SUCCEEDED(hr))
00316         {
00317             hr = CMediaBufferWrapper::CreateInstance(spMediaBuffer.Get(), &spResult);
00318         }
00319     }
00320
00321     // Change the size of the length of the buffer
00322     if (SUCCEEDED(hr))
00323     {
00324         hr = SetCurrentLength(cbCurrentLen - cbSize);
00325     }
00326
00327     if (SUCCEEDED(hr))
00328     {
00329         *pWrapper = spResult.Detach();
00330     }
00331
00332     return hr;
00333 }
00334
00335 IFACEMETHODIMP CMediaBufferWrapper::Reset()
00336 {
00337     _nOffset = 0;
00338     return _spMediaBuffer->SetCurrentLength(0);
00339 }
00340
00341 HRESULT CMediaBufferWrapper::CheckMarshal()
00342 {
00343     HRESULT hr = S_OK;
00344     IMarshal **ppMarshal = _spBufferMarshal.GetAddressOf();
00345     if (*ppMarshal == nullptr)
00346     {
00347         IMarshal *pNewMarshal = nullptr;
00348         hr = RoGetBufferMarshaler(&pNewMarshal);
00349
00350         if (SUCCEEDED(hr) &&
00351             nullptr != InterlockedCompareExchangePointer(reinterpret_cast<PVOID*>(ppMarshal), pNewMarshal, nullptr))
00352         {
00353             pNewMarshal->Release();
00354         }
00355     }
00356
00357     return hr;
00358 }
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LanguageFont/cppwinrt/pch.cpp Source File

  • LanguageFont
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaTranscoding/cs/Scenario2_Custom.xaml.cs Source File

  • MediaTranscoding
  • cs

Scenario2_Custom.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading;
00014 using System.Threading.Tasks;
00015 using Windows.Media.MediaProperties;
00016 using Windows.Media.Transcoding;
00017 using Windows.Storage;
00018 using Windows.Storage.Pickers;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Media;
00022 using Windows.UI.Xaml.Navigation;
00023
00024 namespace SDKTemplate
00025 {
00026     public sealed partial class Scenario2_Custom : Page
00027     {
00028         MainPage rootPage = MainPage.Current;
00029
00030         Windows.UI.Core.CoreDispatcher _dispatcher = Window.Current.Dispatcher;
00031         CancellationTokenSource _cts;
00032         string _OutputFileName = "TranscodeSampleOutput";
00033         string _OutputFileExtension = ".mp4";
00034         string _OutputType = "MP4";
00035         Windows.Media.MediaProperties.MediaEncodingProfile _Profile;
00036         Windows.Storage.StorageFile _InputFile = null;
00037         Windows.Storage.StorageFile _OutputFile = null;
00038         Windows.Media.Transcoding.MediaTranscoder _Transcoder = new Windows.Media.Transcoding.MediaTranscoder();
00039         bool _UseMp4 = true;
00040
00041         public Scenario2_Custom()
00042         {
00043             this.InitializeComponent();
00044             _cts = new CancellationTokenSource();
00045
00046             // Hook up UI
00047             PickFileButton.Click += new RoutedEventHandler(PickFile);
00048             SetOutputButton.Click += new RoutedEventHandler(PickOutput);
00049             TargetFormat.SelectionChanged += new SelectionChangedEventHandler(OnTargetFormatChanged);
00050             Transcode.Click += new RoutedEventHandler(TranscodeCustom);
00051             Cancel.Click += new RoutedEventHandler(TranscodeCancel);
00052
00053             // Media Controls
00054             InputPlayButton.Click += new RoutedEventHandler(InputPlayButton_Click);
00055             InputPauseButton.Click += new RoutedEventHandler(InputPauseButton_Click);
00056             InputStopButton.Click += new RoutedEventHandler(InputStopButton_Click);
00057             OutputPlayButton.Click += new RoutedEventHandler(OutputPlayButton_Click);
00058             OutputPauseButton.Click += new RoutedEventHandler(OutputPauseButton_Click);
00059             OutputStopButton.Click += new RoutedEventHandler(OutputStopButton_Click);
00060
00061             // Initialize UI with default settings
00062             MediaEncodingProfile defaultProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Wvga);
00063             VideoW.Text = defaultProfile.Video.Width.ToString();
00064             VideoH.Text = defaultProfile.Video.Height.ToString();
00065             VideoBR.Text = defaultProfile.Video.Bitrate.ToString();
00066             VideoFR.Text = defaultProfile.Video.FrameRate.Numerator.ToString();
00067             AudioBPS.Text = defaultProfile.Audio.BitsPerSample.ToString();
00068             AudioCC.Text = defaultProfile.Audio.ChannelCount.ToString();
00069             AudioBR.Text = defaultProfile.Audio.Bitrate.ToString();
00070             AudioSR.Text = defaultProfile.Audio.SampleRate.ToString();
00071
00072             // File is not selected, disable all buttons but PickFileButton
00073             DisableButtons();
00074             SetPickFileButton(true);
00075             SetOutputFileButton(false);
00076             SetCancelButton(false);
00077         }
00078
00079         public void Dispose()
00080         {
00081             _cts.Dispose();
00082         }
00083
00084         /// <summary>
00085         /// Invoked when this page is about to be displayed in a Frame.
00086         /// </summary>
00087         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00088         /// property is typically used to configure the page.</param>
00089         protected override void OnNavigatedTo(NavigationEventArgs e)
00090         {
00091         }
00092
00093         async void TranscodeCustom(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00094         {
00095             StopPlayers();
00096             DisableButtons();
00097             GetCustomProfile();
00098
00099             // Clear messages
00100             StatusMessage.Text = "";
00101
00102             try
00103             {
00104                 if (_InputFile != null && _Profile != null && _OutputFile != null)
00105                 {
00106                     var preparedTranscodeResult = await _Transcoder.PrepareFileTranscodeAsync(_InputFile, _OutputFile, _Profile);
00107
00108                     if (EnableMrfCrf444.IsChecked.HasValue && (bool)EnableMrfCrf444.IsChecked)
00109                     {
00110                         _Transcoder.VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.MrfCrf444;
00111                     }
00112                     else
00113                     {
00114                         _Transcoder.VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.Default;
00115                     }
00116
00117                     if (preparedTranscodeResult.CanTranscode)
00118                     {
00119                         SetCancelButton(true);
00120                         var progress = new Progress<double>(TranscodeProgress);
00121                         await preparedTranscodeResult.TranscodeAsync().AsTask(_cts.Token, progress);
00122                         TranscodeComplete();
00123                     }
00124                     else
00125                     {
00126                         TranscodeFailure(preparedTranscodeResult.FailureReason);
00127                     }
00128                 }
00129             }
00130             catch (TaskCanceledException)
00131             {
00132                 OutputText("");
00133                 TranscodeError("Transcode Canceled");
00134             }
00135             catch (Exception exception)
00136             {
00137                 TranscodeError(exception.Message);
00138             }
00139         }
00140
00141         void GetCustomProfile()
00142         {
00143             if (_UseMp4)
00144             {
00145                 _Profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Wvga);
00146             }
00147             else
00148             {
00149                 _Profile = MediaEncodingProfile.CreateWmv(VideoEncodingQuality.Wvga);
00150             }
00151
00152             try
00153             {
00154                 _Profile.Video.Width = UInt32.Parse(VideoW.Text);
00155                 _Profile.Video.Height = UInt32.Parse(VideoH.Text);
00156                 _Profile.Video.Bitrate = UInt32.Parse(VideoBR.Text);
00157                 _Profile.Video.FrameRate.Numerator = UInt32.Parse(VideoFR.Text);
00158                 _Profile.Video.FrameRate.Denominator = 1;
00159                 _Profile.Audio.BitsPerSample = UInt32.Parse(AudioBPS.Text);
00160                 _Profile.Audio.ChannelCount = UInt32.Parse(AudioCC.Text);
00161                 _Profile.Audio.Bitrate = UInt32.Parse(AudioBR.Text);
00162                 _Profile.Audio.SampleRate = UInt32.Parse(AudioSR.Text);
00163
00164                 // Video sources providing more than about 250 megapixels per second require the
00165                 // H.264 encoder to be set to level 5.2. Information about H.264 encoding levels:
00166                 // https://en.wikipedia.org/wiki/Advanced_Video_Coding#Levels
00167                 // Windows doesn't always set the higher level automatically so it should be set
00168                 // explicitly to avoid encoding failures. Constants needed to set the encoding level:
00169                 // https://docs.microsoft.com/en-us/windows/win32/medfound/mf-mt-video-level
00170                 // https://docs.microsoft.com/en-us/windows/win32/api/codecapi/ne-codecapi-eavench264vlevel
00171                 if (_UseMp4)
00172                 {
00173                     const int c_PixelsPerSecondRequiringLevel52 = 250000000;
00174                     if (_Profile.Video.Width * _Profile.Video.Height *
00175                         _Profile.Video.FrameRate.Numerator / _Profile.Video.FrameRate.Denominator >
00176                         c_PixelsPerSecondRequiringLevel52)
00177                     {
00178                         _Profile.Video.Properties[MediaFoundationConstants.MF_MT_VIDEO_LEVEL] =
00179                             (UInt32)MediaFoundationConstants.eAVEncH264VLevel.eAVEncH264VLevel5_2;
00180                     }
00181                 }
00182
00183             }
00184             catch (Exception exception)
00185             {
00186                 TranscodeError(exception.Message);
00187                 _Profile = null;
00188             }
00189         }
00190
00191         void TranscodeProgress(double percent)
00192         {
00193             OutputText("Progress:  " + percent.ToString().Split('.')[0] + "%");
00194         }
00195
00196         async void TranscodeComplete()
00197         {
00198             OutputText("Transcode completed.");
00199             OutputPathText("Output (" + _OutputFile.Path + ")");
00200             Windows.Storage.Streams.IRandomAccessStream stream = await _OutputFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
00201             await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00202             {
00203                 OutputVideo.SetSource(stream, _OutputFile.ContentType);
00204             });
00205
00206             EnableButtons();
00207             SetCancelButton(false);
00208         }
00209
00210         async void TranscodeCancel(object sender, RoutedEventArgs e)
00211         {
00212             try
00213             {
00214                 _cts.Cancel();
00215                 _cts.Dispose();
00216                 _cts = new CancellationTokenSource();
00217
00218                 if (_OutputFile != null)
00219                 {
00220                     await _OutputFile.DeleteAsync();
00221                 }
00222             }
00223             catch (Exception exception)
00224             {
00225                 TranscodeError(exception.Message);
00226             }
00227         }
00228
00229         async void TranscodeFailure(TranscodeFailureReason reason)
00230         {
00231             try
00232             {
00233                 if (_OutputFile != null)
00234                 {
00235                     await _OutputFile.DeleteAsync();
00236                 }
00237             }
00238             catch (Exception exception)
00239             {
00240                 TranscodeError(exception.Message);
00241             }
00242
00243             switch (reason)
00244             {
00245                 case TranscodeFailureReason.CodecNotFound:
00246                     TranscodeError("Codec not found.");
00247                     break;
00248                 case TranscodeFailureReason.InvalidProfile:
00249                     TranscodeError("Invalid profile.");
00250                     break;
00251                 default:
00252                     TranscodeError("Unknown failure.");
00253                     break;
00254             }
00255         }
00256
00257         async void PickFile(object sender, RoutedEventArgs e)
00258         {
00259             Windows.Storage.Pickers.FileOpenPicker picker = new Windows.Storage.Pickers.FileOpenPicker();
00260             picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
00261             picker.FileTypeFilter.Add(".wmv");
00262             picker.FileTypeFilter.Add(".mp4");
00263
00264             Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
00265             if (file != null)
00266             {
00267                 Windows.Storage.Streams.IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
00268
00269                 _InputFile = file;
00270                 InputVideo.SetSource(stream, file.ContentType);
00271                 InputVideo.Play();
00272
00273                 // Enable buttons
00274                 EnableButtons();
00275             }
00276         }
00277
00278         async void PickOutput(object sender, RoutedEventArgs e)
00279         {
00280             FileSavePicker picker = new FileSavePicker();
00281             picker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
00282             picker.SuggestedFileName = _OutputFileName;
00283             picker.FileTypeChoices.Add(_OutputType, new System.Collections.Generic.List<string>() { _OutputFileExtension });
00284
00285             _OutputFile = await picker.PickSaveFileAsync();
00286
00287             if (_OutputFile != null)
00288             {
00289                 SetTranscodeButton(true);
00290             }
00291         }
00292         void OnTargetFormatChanged(object sender, SelectionChangedEventArgs e)
00293         {
00294             if (TargetFormat.SelectedIndex > 0)
00295             {
00296                 _OutputFileExtension = ".wmv";
00297                 _OutputType = "WMV";
00298                 _UseMp4 = false;
00299             }
00300             else
00301             {
00302                 _OutputFileExtension = ".mp4";
00303                 _OutputType = "MP4";
00304                 _UseMp4 = true;
00305             }
00306         }
00307
00308         void InputPlayButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00309         {
00310             if (InputVideo.DefaultPlaybackRate == 0)
00311             {
00312                 InputVideo.DefaultPlaybackRate = 1.0;
00313                 InputVideo.PlaybackRate = 1.0;
00314             }
00315
00316             InputVideo.Play();
00317         }
00318
00319         void InputStopButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00320         {
00321             InputVideo.Stop();
00322         }
00323
00324         void InputPauseButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00325         {
00326             InputVideo.Pause();
00327         }
00328
00329         void OutputPlayButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00330         {
00331             if (OutputVideo.DefaultPlaybackRate == 0)
00332             {
00333                 OutputVideo.DefaultPlaybackRate = 1.0;
00334                 OutputVideo.PlaybackRate = 1.0;
00335             }
00336
00337             OutputVideo.Play();
00338         }
00339
00340         void OutputStopButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00341         {
00342             OutputVideo.Stop();
00343         }
00344
00345         void OutputPauseButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00346         {
00347             OutputVideo.Pause();
00348         }
00349
00350         async void SetPickFileButton(bool isEnabled)
00351         {
00352             await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00353             {
00354                 PickFileButton.IsEnabled = isEnabled;
00355             });
00356         }
00357
00358         async void SetOutputFileButton(bool isEnabled)
00359         {
00360             await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00361             {
00362                 SetOutputButton.IsEnabled = isEnabled;
00363             });
00364         }
00365
00366         async void SetTranscodeButton(bool isEnabled)
00367         {
00368             await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00369             {
00370                 Transcode.IsEnabled = isEnabled;
00371             });
00372         }
00373
00374         async void SetCancelButton(bool isEnabled)
00375         {
00376             await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00377             {
00378                 Cancel.IsEnabled = isEnabled;
00379             });
00380         }
00381
00382         async void EnableButtons()
00383         {
00384             await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00385             {
00386                 PickFileButton.IsEnabled = true;
00387                 SetOutputButton.IsEnabled = true;
00388                 TargetFormat.IsEnabled = true;
00389                 EnableMrfCrf444.IsEnabled = true;
00390
00391                 // The transcode button's initial state should be disabled until an output
00392                 // file has been set.
00393                 Transcode.IsEnabled = false;
00394             });
00395         }
00396
00397         async void DisableButtons()
00398         {
00399             await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00400             {
00401                 Transcode.IsEnabled = false;
00402                 PickFileButton.IsEnabled = false;
00403                 SetOutputButton.IsEnabled = false;
00404                 TargetFormat.IsEnabled = false;
00405                 EnableMrfCrf444.IsEnabled = false;
00406             });
00407         }
00408
00409         async void StopPlayers()
00410         {
00411             await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00412             {
00413                 if (InputVideo.CurrentState != MediaElementState.Paused)
00414                 {
00415                     InputVideo.Pause();
00416                 }
00417                 if (OutputVideo.CurrentState != MediaElementState.Paused)
00418                 {
00419                     OutputVideo.Pause();
00420                 }
00421             });
00422         }
00423
00424         async void PlayFile(Windows.Storage.StorageFile MediaFile)
00425         {
00426             await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
00427             {
00428                 try
00429                 {
00430                     Windows.Storage.Streams.IRandomAccessStream stream = await MediaFile.OpenAsync(FileAccessMode.Read);
00431                     OutputVideo.SetSource(stream, MediaFile.ContentType);
00432                     OutputVideo.Play();
00433                 }
00434                 catch (Exception exception)
00435                 {
00436                     TranscodeError(exception.Message);
00437                 }
00438             });
00439         }
00440
00441         async void TranscodeError(string error)
00442         {
00443             await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00444             {
00445                 StatusMessage.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Red);
00446                 StatusMessage.Text = error;
00447             });
00448
00449             EnableButtons();
00450             SetCancelButton(false);
00451         }
00452
00453         async void OutputText(string text)
00454         {
00455             await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00456             {
00457                 OutputMsg.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Green);
00458                 OutputMsg.Text = text;
00459             });
00460         }
00461
00462         async void OutputPathText(string text)
00463         {
00464             await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00465             {
00466                 OutputPath.Text = text;
00467             });
00468         }
00469     }
00470 }
Generated on Fri Nov 15 2024 22:20:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Size Member List

This is the complete list of members for Scenario3_Size, including all inherited members.
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario3_Size |
OnWindowClosed(Windows::UI::WindowManagement::AppWindow const &sender, IInspectable const &) | Scenario3_Size | [private]
Scenario3_Size() | Scenario3_Size |
ShowWindowBtn_Click(IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_Size |
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario10_SetCookie.h Source File

  • HttpClient
  • cppwinrt

Scenario10_SetCookie.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario10_SetCookie.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario10_SetCookie : Scenario10_SetCookieT<Scenario10_SetCookie>
00020     {
00021         Scenario10_SetCookie();
00022
00023         void SetCookie_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024
00025     private:
00026         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario10_SetCookie : Scenario10_SetCookieT<Scenario10_SetCookie, implementation::Scenario10_SetCookie>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:19:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/Controls/InstructionControl.cs Source File

  • Notifications
  • cs
  • Notifications
  • Controls

InstructionControl.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Xaml;
00002 using Windows.UI.Xaml.Controls;
00003
00004 namespace Notifications.Controls
00005 {
00006     public class InstructionControl : ContentControl
00007     {
00008         public InstructionControl()
00009         {
00010             base.DefaultStyleKey = typeof(InstructionControl);
00011         }
00012
00013         public static readonly DependencyProperty InstructionProperty = DependencyProperty.Register("Instruction", typeof(string), typeof(InstructionControl), new PropertyMetadata(null));
00014
00015         public string Instruction
00016         {
00017             get { return GetValue(InstructionProperty) as string; }
00018             set { SetValue(InstructionProperty, value); }
00019         }
00020     }
00021 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed::StreamFilteringCriteria Member List

This is the complete list of members for sealed::StreamFilteringCriteria, including all inherited members.
aspectRatio | sealed::StreamFilteringCriteria
horizontalResolution | sealed::StreamFilteringCriteria
subType | sealed::StreamFilteringCriteria
Generated on Fri Nov 15 2024 22:24:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialMapping/cpp/Common/CameraResources.h Source File

  • HolographicSpatialMapping
  • cpp
  • Common

CameraResources.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Content\ShaderStructures.h"
00015
00016 namespace DX
00017 {
00018     class DeviceResources;
00019
00020     // Manages DirectX device resources that are specific to a holographic camera, such as the
00021     // back buffer, ViewProjection constant buffer, and viewport.
00022     class CameraResources
00023     {
00024     public:
00025         CameraResources(Windows::Graphics::Holographic::HolographicCamera^ holographicCamera);
00026
00027         void CreateResourcesForBackBuffer(
00028             DX::DeviceResources* pDeviceResources,
00029             Windows::Graphics::Holographic::HolographicCameraRenderingParameters^ cameraParameters
00030             );
00031         void ReleaseResourcesForBackBuffer(
00032             DX::DeviceResources* pDeviceResources
00033             );
00034
00035         void UpdateViewProjectionBuffer(
00036             std::shared_ptr<DX::DeviceResources> deviceResources,
00037             Windows::Graphics::Holographic::HolographicCameraPose^ cameraPose,
00038             Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem);
00039
00040         bool AttachViewProjectionBuffer(
00041             std::shared_ptr<DX::DeviceResources> deviceResources);
00042
00043         // Direct3D device resources.
00044         ID3D11RenderTargetView* GetBackBufferRenderTargetView()     const { return m_d3dRenderTargetView.Get();     }
00045         ID3D11DepthStencilView* GetDepthStencilView()               const { return m_d3dDepthStencilView.Get();     }
00046         ID3D11Texture2D*        GetBackBufferTexture2D()            const { return m_d3dBackBuffer.Get();           }
00047         ID3D11Texture2D*        GetDepthStencilTexture2D()          const { return m_d3dDepthStencil.Get();         }
00048         D3D11_VIEWPORT          GetViewport()                       const { return m_d3dViewport;                   }
00049         DXGI_FORMAT             GetBackBufferDXGIFormat()           const { return m_dxgiFormat;                    }
00050
00051         // Render target properties.
00052         Windows::Foundation::Size GetRenderTargetSize()             const { return m_d3dRenderTargetSize;           }
00053         bool                    IsRenderingStereoscopic()           const { return m_isStereo;                      }
00054
00055         // The holographic camera these resources are for.
00056         Windows::Graphics::Holographic::HolographicCamera^ GetHolographicCamera() const { return m_holographicCamera; }
00057
00058     private:
00059         // Direct3D rendering objects. Required for 3D.
00060         Microsoft::WRL::ComPtr<ID3D11RenderTargetView>      m_d3dRenderTargetView;
00061         Microsoft::WRL::ComPtr<ID3D11DepthStencilView>      m_d3dDepthStencilView;
00062         Microsoft::WRL::ComPtr<ID3D11Texture2D>             m_d3dBackBuffer;
00063         Microsoft::WRL::ComPtr<ID3D11Texture2D>             m_d3dDepthStencil;
00064
00065         // Device resource to store view and projection matrices.
00066         Microsoft::WRL::ComPtr<ID3D11Buffer>                m_viewProjectionConstantBuffer;
00067
00068         // Direct3D rendering properties.
00069         DXGI_FORMAT                                         m_dxgiFormat;
00070         Windows::Foundation::Size                           m_d3dRenderTargetSize;
00071         D3D11_VIEWPORT                                      m_d3dViewport;
00072
00073         // Indicates whether the camera supports stereoscopic rendering.
00074         bool                                                m_isStereo = false;
00075
00076         // Indicates whether this camera has a pending frame.
00077         bool                                                m_framePending = false;
00078
00079         // Pointer to the holographic camera these resources are for.
00080         Windows::Graphics::Holographic::HolographicCamera^  m_holographicCamera = nullptr;
00081     };
00082 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaTranscoding/cs/MediaFoundationConstants.cs Source File

  • MediaTranscoding
  • cs

MediaFoundationConstants.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using System;
00012
00013 namespace SDKTemplate
00014 {
00015     /// <summary>
00016     /// Assorted Media Foundation constants from the Windows SDK C headers
00017     /// </summary>
00018     class MediaFoundationConstants
00019     {
00020         // https://docs.microsoft.com/en-us/windows/win32/medfound/mf-mt-video-level
00021         // %ProgramFiles(x86)%\Windows Kits\10\Include\10.0.19041.0\um\mfapi.h
00022         public static readonly Guid MF_MT_VIDEO_LEVEL = new Guid("{96F66574-11C5-4015-8666-BFF516436DA7}");
00023
00024         // https://docs.microsoft.com/en-us/windows/win32/api/codecapi/ne-codecapi-eavench264vlevel
00025         // %ProgramFiles(x86)%\Windows Kits\10\Include\10.0.19041.0\um\codecapi.h
00026         public enum eAVEncH264VLevel : UInt32
00027         {
00028             eAVEncH264VLevel1 = 10,
00029             eAVEncH264VLevel1_b = 11,
00030             eAVEncH264VLevel1_1 = 11,
00031             eAVEncH264VLevel1_2 = 12,
00032             eAVEncH264VLevel1_3 = 13,
00033             eAVEncH264VLevel2 = 20,
00034             eAVEncH264VLevel2_1 = 21,
00035             eAVEncH264VLevel2_2 = 22,
00036             eAVEncH264VLevel3 = 30,
00037             eAVEncH264VLevel3_1 = 31,
00038             eAVEncH264VLevel3_2 = 32,
00039             eAVEncH264VLevel4 = 40,
00040             eAVEncH264VLevel4_1 = 41,
00041             eAVEncH264VLevel4_2 = 42,
00042             eAVEncH264VLevel5 = 50,
00043             eAVEncH264VLevel5_1 = 51,
00044             eAVEncH264VLevel5_2 = 52,
00045         };
00046     }
00047 }
Generated on Fri Nov 15 2024 22:20:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cs/SampleConfiguration.cs Source File

  • Store
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using System.Collections.Generic;
00015 using Windows.ApplicationModel;
00016 using Windows.ApplicationModel.Store;
00017 using Windows.Storage;
00018 using Windows.UI.Xaml.Controls;
00019 using System.Collections.ObjectModel;
00020 using Windows.Services.Store;
00021
00022 namespace SDKTemplate
00023 {
00024     public partial class MainPage : Page
00025     {
00026         // This is used on the main page as the title of the sample.
00027         public const string FEATURE_NAME = "Store C# Sample";
00028
00029         List<Scenario> scenarios = new List<Scenario>
00030         {
00031             new Scenario() { Title = "Trial-mode", ClassType = typeof(Scenario1_TrialMode) },
00032             new Scenario() { Title = "In-app purchase", ClassType = typeof(Scenario2_InAppPurchase) },
00033             new Scenario() { Title = "Unmanaged consumable product", ClassType = typeof(Scenario3_UnmanagedConsumable) },
00034             new Scenario() { Title = "Managed consumable product", ClassType = typeof(Scenario4_ConsumableProduct) },
00035             new Scenario() { Title = "User collection", ClassType = typeof(Scenario5_UserCollection) },
00036             new Scenario() { Title = "App listing URI", ClassType = typeof(Scenario6_AppListingURI) },
00037             new Scenario() { Title = "Business to Business", ClassType = typeof(Scenario7_B2B) }
00038         };
00039     }
00040
00041     public class Scenario
00042     {
00043         public string Title { get; set; }
00044
00045         public Type ClassType { get; set; }
00046
00047         public override string ToString()
00048         {
00049             return Title;
00050         }
00051     }
00052
00053     public static class Utils
00054     {
00055         public static ObservableCollection<ItemDetails>
00056             CreateProductListFromQueryResult(StoreProductQueryResult addOns, string description)
00057         {
00058             var productList = new ObservableCollection<ItemDetails>();
00059
00060             if (addOns.ExtendedError != null)
00061             {
00062                 ReportExtendedError(addOns.ExtendedError);
00063             }
00064             else if (addOns.Products.Count == 0)
00065             {
00066                 MainPage.Current.NotifyUser($"No configured {description} found for this Store Product.", NotifyType.ErrorMessage);
00067             }
00068             else
00069             {
00070                 foreach (StoreProduct product in addOns.Products.Values)
00071                 {
00072                     productList.Add(new ItemDetails(product));
00073                 }
00074             }
00075             return productList;
00076         }
00077
00078         static int IAP_E_UNEXPECTED = unchecked((int)0x803f6107);
00079
00080         public static void ReportExtendedError(Exception extendedError)
00081         {
00082             string message;
00083             if (extendedError.HResult == IAP_E_UNEXPECTED)
00084             {
00085                 message = "This sample has not been properly configured. See the README for instructions.";
00086             }
00087             else
00088             {
00089                 // The user may be offline or there might be some other server failure.
00090                 message = $"ExtendedError: {extendedError.Message}";
00091             }
00092             MainPage.Current.NotifyUser(message, NotifyType.ErrorMessage);
00093         }
00094     }
00095
00096     public static class BindingUtils
00097     {
00098         // Helper function for binding.
00099         public static bool IsNonNull(object o)
00100         {
00101             return o != null;
00102         }
00103     }
00104 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cppwinrt/pch.h Source File

  • Clipboard
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <sstream>
00004 #include <hstring.h>
00005 #include "winrt/Windows.Foundation.h"
00006 #include "winrt/Windows.Foundation.Collections.h"
00007 #include "winrt/Windows.ApplicationModel.Activation.h"
00008 #include "winrt/Windows.ApplicationModel.DataTransfer.h"
00009 #include "winrt/Windows.Data.Html.h"
00010 #include "winrt/Windows.Data.Xml.Dom.h"
00011 #include "winrt/Windows.Graphics.Imaging.h"
00012 #include "winrt/Windows.Storage.h"
00013 #include "winrt/Windows.Storage.Pickers.h"
00014 #include "winrt/Windows.Storage.Streams.h"
00015 #include "winrt/Windows.System.h"
00016 #include "winrt/Windows.UI.Core.h"
00017 #include "winrt/Windows.UI.Notifications.h"
00018 #include "winrt/Windows.UI.Xaml.h"
00019 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00020 #include "winrt/Windows.UI.Xaml.Controls.h"
00021 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00022 #include "winrt/Windows.UI.Xaml.Documents.h"
00023 #include "winrt/Windows.UI.Xaml.Interop.h"
00024 #include "winrt/Windows.UI.Xaml.Markup.h"
00025 #include "winrt/Windows.UI.Xaml.Media.h"
00026 #include "winrt/Windows.UI.Xaml.Media.Imaging.h"
00027 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cpp/pch.cpp Source File

  • Pedometer
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cpp/Scenario7_UsingUnicodeExtensions.xaml.h Source File

  • NumberFormatting
  • cpp

Scenario7_UsingUnicodeExtensions.xaml.h

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "pch.h"
00006 #include "Scenario7_UsingUnicodeExtensions.g.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario7_UsingUnicodeExtensions sealed
00012     {
00013     public:
00014         Scenario7_UsingUnicodeExtensions();
00015
00016     private:
00017         void Display_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00018     };
00019 }
Generated on Fri Nov 15 2024 22:20:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 3DPrinting/cs/Scenario2_Launch.xaml.cs Source File

  • 3DPrinting
  • cs

Scenario2_Launch.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using Windows.ApplicationModel;
00016 using Windows.Foundation;
00017 using Windows.Storage;
00018 using Windows.Storage.Pickers;
00019 using Windows.System;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022
00023 namespace SDKTemplate
00024 {
00025     public sealed partial class Scenario2_Launch : Page
00026     {
00027         private static string PackageFamilyName3DBuilder = "Microsoft.3DBuilder_8wekyb3d8bbwe";
00028
00029         private MainPage rootPage = MainPage.Current;
00030
00031         public Scenario2_Launch()
00032         {
00033             this.InitializeComponent();
00034         }
00035
00036         private async void CheckIf3DBuilderIsInstalled_Click(object sender, RoutedEventArgs e)
00037         {
00038             IReadOnlyList<AppInfo> handlers = await Launcher.FindFileHandlersAsync(".3mf");
00039             if (handlers.Any(info => info.PackageFamilyName == PackageFamilyName3DBuilder))
00040             {
00041                 rootPage.NotifyUser("3D Builder is installed", NotifyType.StatusMessage);
00042             }
00043             else
00044             {
00045                 rootPage.NotifyUser("3D Builder is not installed", NotifyType.ErrorMessage);
00046             }
00047         }
00048
00049         private async void LaunchFileIn3DBuilder_Click(object sender, RoutedEventArgs e)
00050         {
00051             FileOpenPicker openPicker = new FileOpenPicker();
00052             openPicker.ViewMode = PickerViewMode.Thumbnail;
00053             openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
00054             openPicker.FileTypeFilter.Add(".3mf");
00055             openPicker.FileTypeFilter.Add(".stl");
00056
00057             StorageFile file = await openPicker.PickSingleFileAsync();
00058             if (file == null)
00059             {
00060                 return;
00061             }
00062
00063             var options = new LauncherOptions();
00064
00065             // The target application is 3D Builder.
00066             options.TargetApplicationPackageFamilyName = PackageFamilyName3DBuilder;
00067
00068             // If 3D Builder is not installed, redirect the user to the Store to install it.
00069             options.FallbackUri = new Uri("ms-windows-store:PDP?PFN=" + PackageFamilyName3DBuilder);
00070
00071             await Launcher.LaunchFileAsync(file, options);
00072         }
00073     }
00074 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DatagramSocket/cs/SampleConfiguration.cs Source File

  • DatagramSocket
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.Collections.Generic;
00013 using Windows.UI.Xaml.Controls;using System;
00014
00015 namespace SDKTemplate
00016 {
00017     public partial class MainPage : Page
00018     {
00019         // This is used on the main page as the title of the sample.
00020         public const string FEATURE_NAME = "DatagramSocket";
00021
00022         // Change the array below to reflect the name of your scenarios.
00023         // This will be used to populate the list of scenarios on the main page with
00024         // which the user will choose the specific scenario that they are interested in.
00025         // These should be in the form: "Navigating to a web page".
00026         // The code in MainPage will take care of turning this into: "1) Navigating to a web page"
00027         List<Scenario> scenarios = new List<Scenario>
00028         {
00029             new Scenario() { Title = "Start Datagram Listener", ClassType = typeof(DatagramSocketSample.Scenario1) },
00030             new Scenario() { Title = "Connect to Listener", ClassType = typeof(DatagramSocketSample.Scenario2) },
00031             new Scenario() { Title = "Send Data", ClassType = typeof(DatagramSocketSample.Scenario3) },
00032             new Scenario() { Title = "Close Socket", ClassType = typeof(DatagramSocketSample.Scenario4) },
00033             new Scenario() { Title = "Multicast/Broadcast", ClassType = typeof(DatagramSocketSample.Scenario5) }
00034         };
00035     }
00036
00037     public class Scenario
00038     {
00039         public string Title { get; set; }
00040
00041         public Type ClassType { get; set; }
00042
00043         public override string ToString()
00044         {
00045             return Title;
00046         }
00047     }
00048 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserConsentVerifier/cppwinrt/Scenario1_CheckConsentAvailability.h Source File

  • UserConsentVerifier
  • cppwinrt

Scenario1_CheckConsentAvailability.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_CheckConsentAvailability.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_CheckConsentAvailability : Scenario1_CheckConsentAvailabilityT<Scenario1_CheckConsentAvailability>
00019     {
00020         Scenario1_CheckConsentAvailability();
00021
00022         fire_and_forget CheckAvailability_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023
00024     private:
00025         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00026     };
00027 }
00028
00029 namespace winrt::SDKTemplate::factory_implementation
00030 {
00031     struct Scenario1_CheckConsentAvailability : Scenario1_CheckConsentAvailabilityT<Scenario1_CheckConsentAvailability, implementation::Scenario1_CheckConsentAvailability>
00032     {
00033     };
00034 }
Generated on Fri Nov 15 2024 22:21:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario1WinRTComponent/SecureInterfaceProducer.cpp Source File

  • AllJoyn
  • Common
  • Scenario1WinRTComponent

SecureInterfaceProducer.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #include "pch.h"
00022
00023 using namespace concurrency;
00024 using namespace Microsoft::WRL;
00025 using namespace Platform;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Devices::AllJoyn;
00028 using namespace com::microsoft::Samples::SecureInterface;
00029
00030 std::map<alljoyn_busobject, WeakReference*> SecureInterfaceProducer::SourceObjects;
00031 std::map<alljoyn_interfacedescription, WeakReference*> SecureInterfaceProducer::SourceInterfaces;
00032
00033 SecureInterfaceProducer::SecureInterfaceProducer(AllJoynBusAttachment^ busAttachment)
00034     : m_busAttachment(busAttachment),
00035     m_sessionListener(nullptr),
00036     m_busObject(nullptr),
00037     m_sessionPort(0),
00038     m_sessionId(0)
00039 {
00040     m_weak = new WeakReference(this);
00041     ServiceObjectPath = ref new String(L"/Service");
00042     m_signals = ref new SecureInterfaceLegacySignals();
00043     m_busAttachmentStateChangedToken.Value = 0;
00044 }
00045
00046 SecureInterfaceProducer::~SecureInterfaceProducer()
00047 {
00048     UnregisterFromBus();
00049     delete m_weak;
00050 }
00051
00052 void SecureInterfaceProducer::UnregisterFromBus()
00053 {
00054     if ((nullptr != m_busAttachment) && (0 != m_busAttachmentStateChangedToken.Value))
00055     {
00056         m_busAttachment->StateChanged -= m_busAttachmentStateChangedToken;
00057         m_busAttachmentStateChangedToken.Value = 0;
00058     }
00059     if ((nullptr != m_busAttachment) && (nullptr != SessionPortListener))
00060     {
00061         alljoyn_busattachment_unbindsessionport(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), m_sessionPort);
00062         alljoyn_sessionportlistener_destroy(SessionPortListener);
00063         SessionPortListener = nullptr;
00064     }
00065     if ((nullptr != m_busAttachment) && (nullptr != BusObject))
00066     {
00067         alljoyn_busattachment_unregisterbusobject(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject);
00068         alljoyn_busobject_destroy(BusObject);
00069         BusObject = nullptr;
00070     }
00071     if ((nullptr != m_busAttachment) && (nullptr != SessionListener))
00072     {
00073         alljoyn_busattachment_leavesession(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), m_sessionId);
00074         alljoyn_busattachment_setsessionlistener(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), m_sessionId, nullptr);
00075         alljoyn_sessionlistener_destroy(SessionListener);
00076         SessionListener = nullptr;
00077     }
00078 }
00079
00080 bool SecureInterfaceProducer::OnAcceptSessionJoiner(_In_ alljoyn_sessionport sessionPort, _In_ PCSTR joiner, _In_ const alljoyn_sessionopts opts)
00081 {
00082     UNREFERENCED_PARAMETER(sessionPort); UNREFERENCED_PARAMETER(joiner); UNREFERENCED_PARAMETER(opts);
00083
00084     return true;
00085 }
00086
00087 void SecureInterfaceProducer::OnSessionJoined(_In_ alljoyn_sessionport sessionPort, _In_ alljoyn_sessionid id, _In_ PCSTR joiner)
00088 {
00089     UNREFERENCED_PARAMETER(joiner);
00090
00091     // We initialize the Signals object after the session has been joined, because it needs
00092     // the session id.
00093     m_signals->Initialize(BusObject, id);
00094     m_sessionPort = sessionPort;
00095     m_sessionId = id;
00096
00097     alljoyn_sessionlistener_callbacks callbacks =
00098     {
00099         AllJoynHelpers::SessionLostHandler<SecureInterfaceProducer>,
00100         AllJoynHelpers::SessionMemberAddedHandler<SecureInterfaceProducer>,
00101         AllJoynHelpers::SessionMemberRemovedHandler<SecureInterfaceProducer>
00102     };
00103
00104     SessionListener = alljoyn_sessionlistener_create(&callbacks, m_weak);
00105     alljoyn_busattachment_setsessionlistener(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), id, SessionListener);
00106 }
00107
00108 void SecureInterfaceProducer::OnSessionLost(_In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason)
00109 {
00110     if (sessionId == m_sessionId)
00111     {
00112         AllJoynSessionLostEventArgs^ args = ref new AllJoynSessionLostEventArgs(static_cast<AllJoynSessionLostReason>(reason));
00113         SessionLost(this, args);
00114     }
00115 }
00116
00117 void SecureInterfaceProducer::OnSessionMemberAdded(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
00118 {
00119     if (sessionId == m_sessionId)
00120     {
00121         auto args = ref new AllJoynSessionMemberAddedEventArgs(AllJoynHelpers::MultibyteToPlatformString(uniqueName));
00122         SessionMemberAdded(this, args);
00123     }
00124 }
00125
00126 void SecureInterfaceProducer::OnSessionMemberRemoved(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName)
00127 {
00128     if (sessionId == m_sessionId)
00129     {
00130         auto args = ref new AllJoynSessionMemberRemovedEventArgs(AllJoynHelpers::MultibyteToPlatformString(uniqueName));
00131         SessionMemberRemoved(this, args);
00132     }
00133 }
00134
00135 void SecureInterfaceProducer::BusAttachmentStateChanged(_In_ AllJoynBusAttachment^ sender, _In_ AllJoynBusAttachmentStateChangedEventArgs^ args)
00136 {
00137     if (args->State == AllJoynBusAttachmentState::Connected)
00138     {
00139         QStatus result = AllJoynHelpers::CreateProducerSession<SecureInterfaceProducer>(m_busAttachment, m_weak);
00140         if (ER_OK != result)
00141         {
00142             StopInternal(result);
00143             return;
00144         }
00145     }
00146     else if (args->State == AllJoynBusAttachmentState::Disconnected)
00147     {
00148         StopInternal(ER_BUS_STOPPING);
00149     }
00150 }
00151
00152 void SecureInterfaceProducer::CallConcatenateHandler(_Inout_ alljoyn_busobject busObject, _In_ alljoyn_message message)
00153 {
00154     auto source = SourceObjects.find(busObject);
00155     if (source == SourceObjects.end())
00156     {
00157         return;
00158     }
00159
00160     SecureInterfaceProducer^ producer = source->second->Resolve<SecureInterfaceProducer>();
00161     if (producer->Service != nullptr)
00162     {
00163         AllJoynMessageInfo^ callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
00164
00165         Platform::String^ inputArg0;
00166         (void)TypeConversionHelpers::GetAllJoynMessageArg(alljoyn_message_getarg(message, 0), "s", &inputArg0);
00167         Platform::String^ inputArg1;
00168         (void)TypeConversionHelpers::GetAllJoynMessageArg(alljoyn_message_getarg(message, 1), "s", &inputArg1);
00169
00170         SecureInterfaceConcatenateResult^ result = create_task(producer->Service->ConcatenateAsync(callInfo, inputArg0, inputArg1)).get();
00171         create_task([](){}).then([=]
00172         {
00173             int32 status;
00174
00175             if (nullptr == result)
00176             {
00177                 alljoyn_busobject_methodreply_status(busObject, message, ER_BUS_NO_LISTENER);
00178                 return;
00179             }
00180
00181             status = result->Status;
00182             if (AllJoynStatus::Ok != status)
00183             {
00184                 alljoyn_busobject_methodreply_status(busObject, message, static_cast<QStatus>(status));
00185                 return;
00186             }
00187
00188             size_t argCount = 1;
00189             alljoyn_msgarg outputs = alljoyn_msgarg_array_create(argCount);
00190
00191             status = TypeConversionHelpers::SetAllJoynMessageArg(alljoyn_msgarg_array_element(outputs, 0), "s", result->OutStr);
00192             if (AllJoynStatus::Ok != status)
00193             {
00194                 alljoyn_busobject_methodreply_status(busObject, message, static_cast<QStatus>(status));
00195                 alljoyn_msgarg_destroy(outputs);
00196                 return;
00197             }
00198
00199             alljoyn_busobject_methodreply_args(busObject, message, outputs, argCount);
00200             alljoyn_msgarg_destroy(outputs);
00201         }, result->m_creationContext).wait();
00202     }
00203 }
00204
00205 void SecureInterfaceProducer::CallTextSentSignalHandler(_In_ const alljoyn_interfacedescription_member* member, _In_ alljoyn_message message)
00206 {
00207     auto source = SourceInterfaces.find(member->iface);
00208     if (source == SourceInterfaces.end())
00209     {
00210         return;
00211     }
00212
00213     auto producer = source->second->Resolve<SecureInterfaceProducer>();
00214     if (producer->Signals != nullptr)
00215     {
00216         auto callInfo = ref new AllJoynMessageInfo(AllJoynHelpers::MultibyteToPlatformString(alljoyn_message_getsender(message)));
00217         auto eventArgs = ref new SecureInterfaceTextSentReceivedEventArgs();
00218         eventArgs->MessageInfo = callInfo;
00219
00220         Platform::String^ argument0;
00221         (void)TypeConversionHelpers::GetAllJoynMessageArg(alljoyn_message_getarg(message, 0), "s", &argument0);
00222         eventArgs->Message = argument0;
00223
00224         producer->Signals->CallTextSentReceived(producer->Signals, eventArgs);
00225     }
00226 }
00227
00228 QStatus SecureInterfaceProducer::AddMethodHandler(_In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_methodhandler_ptr handler)
00229 {
00230     alljoyn_interfacedescription_member member;
00231     if (!alljoyn_interfacedescription_getmember(interfaceDescription, methodName, &member))
00232     {
00233         return ER_BUS_INTERFACE_NO_SUCH_MEMBER;
00234     }
00235
00236     return alljoyn_busobject_addmethodhandler(
00237         m_busObject,
00238         member,
00239         handler,
00240         m_weak);
00241 }
00242
00243 QStatus SecureInterfaceProducer::AddSignalHandler(_In_ alljoyn_busattachment busAttachment, _In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_signalhandler_ptr handler)
00244 {
00245     alljoyn_interfacedescription_member member;
00246     if (!alljoyn_interfacedescription_getmember(interfaceDescription, methodName, &member))
00247     {
00248         return ER_BUS_INTERFACE_NO_SUCH_MEMBER;
00249     }
00250
00251     return alljoyn_busattachment_registersignalhandler(busAttachment, handler, member, NULL);
00252 }
00253
00254 QStatus SecureInterfaceProducer::OnPropertyGet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _Inout_ alljoyn_msgarg value)
00255 {
00256     UNREFERENCED_PARAMETER(interfaceName);
00257
00258     if (0 == strcmp(propertyName, "IsUpperCaseEnabled"))
00259     {
00260         auto task = create_task(Service->GetIsUpperCaseEnabledAsync(nullptr));
00261         auto result = task.get();
00262
00263         return create_task([](){}).then([=]() -> QStatus
00264         {
00265             if (AllJoynStatus::Ok != result->Status)
00266             {
00267                 return static_cast<QStatus>(result->Status);
00268             }
00269             return static_cast<QStatus>(TypeConversionHelpers::SetAllJoynMessageArg(value, "b", result->IsUpperCaseEnabled));
00270         }, result->m_creationContext).get();
00271     }
00272
00273     return ER_BUS_NO_SUCH_PROPERTY;
00274 }
00275
00276 QStatus SecureInterfaceProducer::OnPropertySet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg value)
00277 {
00278     UNREFERENCED_PARAMETER(interfaceName);
00279
00280     if (0 == strcmp(propertyName, "IsUpperCaseEnabled"))
00281     {
00282         bool argument;
00283         QStatus status = static_cast<QStatus>(TypeConversionHelpers::GetAllJoynMessageArg(value, "b", &argument));
00284         if (ER_OK == status)
00285         {
00286             auto task = create_task(Service->SetIsUpperCaseEnabledAsync(nullptr, argument));
00287             auto result = task.get();
00288             status = static_cast<QStatus>(result->Status);
00289         }
00290         return status;
00291     }
00292     return ER_BUS_NO_SUCH_PROPERTY;
00293 }
00294
00295 void SecureInterfaceProducer::EmitIsUpperCaseEnabledChanged()
00296 {
00297     create_task([&]
00298     {
00299         alljoyn_msgarg value = alljoyn_msgarg_create();
00300         OnPropertyGet("com.microsoft.Samples.SecureInterface", "IsUpperCaseEnabled", value);
00301
00302         alljoyn_busobject_emitpropertychanged(
00303             m_busObject,
00304             "com.microsoft.Samples.SecureInterface",
00305             "IsUpperCaseEnabled",
00306             value,
00307             m_sessionId);
00308
00309         alljoyn_msgarg_destroy(value);
00310     });
00311 }
00312
00313 void SecureInterfaceProducer::Start()
00314 {
00315     if (nullptr == m_busAttachment)
00316     {
00317         StopInternal(ER_FAIL);
00318         return;
00319     }
00320
00321     QStatus result = AllJoynHelpers::CreateInterfaces(m_busAttachment, c_SecureInterfaceIntrospectionXml);
00322     if (result != ER_OK)
00323     {
00324         StopInternal(result);
00325         return;
00326     }
00327
00328     result = AllJoynHelpers::CreateBusObject<SecureInterfaceProducer>(m_weak);
00329     if (result != ER_OK)
00330     {
00331         StopInternal(result);
00332         return;
00333     }
00334
00335     alljoyn_interfacedescription interfaceDescription = alljoyn_busattachment_getinterface(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), "com.microsoft.Samples.SecureInterface");
00336     if (interfaceDescription == nullptr)
00337     {
00338         StopInternal(ER_FAIL);
00339         return;
00340     }
00341     alljoyn_busobject_addinterface_announced(BusObject, interfaceDescription);
00342
00343     result = AddMethodHandler(
00344         interfaceDescription,
00345         "Concatenate",
00346         [](alljoyn_busobject busObject, const alljoyn_interfacedescription_member* member, alljoyn_message message) { UNREFERENCED_PARAMETER(member); CallConcatenateHandler(busObject, message); });
00347     if (result != ER_OK)
00348     {
00349         StopInternal(result);
00350         return;
00351     }
00352
00353     result = AddSignalHandler(
00354         AllJoynHelpers::GetInternalBusAttachment(m_busAttachment),
00355         interfaceDescription,
00356         "TextSent",
00357         [](const alljoyn_interfacedescription_member* member, PCSTR srcPath, alljoyn_message message) { UNREFERENCED_PARAMETER(srcPath); CallTextSentSignalHandler(member, message); });
00358     if (result != ER_OK)
00359     {
00360         StopInternal(result);
00361         return;
00362     }
00363
00364     SourceObjects[m_busObject] = m_weak;
00365     SourceInterfaces[interfaceDescription] = m_weak;
00366
00367     unsigned int noneMechanismIndex = 0;
00368     bool authenticationMechanismsContainsNone = m_busAttachment->AuthenticationMechanisms->IndexOf(AllJoynAuthenticationMechanism::None, &noneMechanismIndex);
00369     QCC_BOOL interfaceIsSecure = alljoyn_interfacedescription_issecure(interfaceDescription);
00370
00371     // If the current set of AuthenticationMechanisms supports authentication,
00372     // determine whether a secure BusObject is required.
00373     if (AllJoynHelpers::CanSecure(m_busAttachment->AuthenticationMechanisms))
00374     {
00375         // Register the BusObject as "secure" if the org.alljoyn.Bus.Secure XML annotation
00376         // is specified, or if None is not present in AuthenticationMechanisms.
00377         if (!authenticationMechanismsContainsNone || interfaceIsSecure)
00378         {
00379             result = alljoyn_busattachment_registerbusobject_secure(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject);
00380         }
00381         else
00382         {
00383             result = alljoyn_busattachment_registerbusobject(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject);
00384         }
00385     }
00386     else
00387     {
00388         // If the current set of AuthenticationMechanisms does not support authentication
00389         // but the interface requires security, report an error.
00390         if (interfaceIsSecure)
00391         {
00392             result = ER_BUS_NO_AUTHENTICATION_MECHANISM;
00393         }
00394         else
00395         {
00396             result = alljoyn_busattachment_registerbusobject(AllJoynHelpers::GetInternalBusAttachment(m_busAttachment), BusObject);
00397         }
00398     }
00399
00400     if (result != ER_OK)
00401     {
00402         StopInternal(result);
00403         return;
00404     }
00405
00406     m_busAttachmentStateChangedToken = m_busAttachment->StateChanged += ref new TypedEventHandler<AllJoynBusAttachment^,AllJoynBusAttachmentStateChangedEventArgs^>(this, &SecureInterfaceProducer::BusAttachmentStateChanged);
00407     m_busAttachment->Connect();
00408 }
00409
00410 void SecureInterfaceProducer::Stop()
00411 {
00412     StopInternal(AllJoynStatus::Ok);
00413 }
00414
00415 void SecureInterfaceProducer::StopInternal(int32 status)
00416 {
00417     UnregisterFromBus();
00418     Stopped(this, ref new AllJoynProducerStoppedEventArgs(status));
00419 }
00420
00421 int32 SecureInterfaceProducer::RemoveMemberFromSession(_In_ String^ uniqueName)
00422 {
00423     return alljoyn_busattachment_removesessionmember(
00424         AllJoynHelpers::GetInternalBusAttachment(m_busAttachment),
00425         m_sessionId,
00426         AllJoynHelpers::PlatformToMultibyteString(uniqueName).data());
00427 }
00428
00429 PCSTR com::microsoft::Samples::SecureInterface::c_SecureInterfaceIntrospectionXml = "<interface name=\"com.microsoft.Samples.SecureInterface\">"
00430 "  <description>A secure AllJoyn sample</description>"
00431 "  <annotation name=\"org.alljoyn.Bus.Secure\" value=\"true\" />"
00432 "  <method name=\"Concatenate\">"
00433 "    <description>Concatenate two input strings and returns the concatenated string as output</description>"
00434 "    <arg name=\"inStr1\" type=\"s\" direction=\"in\" />"
00435 "    <arg name=\"inStr2\" type=\"s\" direction=\"in\" />"
00436 "    <arg name=\"outStr\" type=\"s\" direction=\"out\" />"
00437 "  </method>"
00438 "  <property name=\"IsUpperCaseEnabled\" type=\"b\" access=\"readwrite\">"
00439 "    <description>Determine if the output of the Concatenate method is returned as upper case string or not</description>"
00440 "    <annotation name=\"org.freedesktop.DBus.Property.EmitsChangedSignal\" value=\"true\" />"
00441 "  </property>"
00442 "  <signal name=\"TextSent\">"
00443 "    <description>This signal is emitted when producer sends a text message to consumer</description>"
00444 "    <arg name=\"message\" type=\"s\" />"
00445 "  </signal>"
00446 "</interface>"
00447 ;
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cppwinrt/Project.idl Source File

  • FilePicker
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_SingleFile : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_SingleFile();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_MultiFile : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_MultiFile();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3_SingleFolder : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3_SingleFolder();
00030     }
00031
00032     [default_interface]
00033     runtimeclass Scenario4_SaveFile : Windows.UI.Xaml.Controls.Page
00034     {
00035         Scenario4_SaveFile();
00036     }
00037
00038     [default_interface]
00039     runtimeclass Scenario5_TriggerCFU : Windows.UI.Xaml.Controls.Page
00040     {
00041         Scenario5_TriggerCFU();
00042     }
00043 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cpp/Scenario2.xaml.cpp Source File

  • FileThumbnails
  • cpp

Scenario2.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2.xaml.cpp
00014 // Implementation of the Scenario2 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario2.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace concurrency;
00023 using namespace Platform;
00024 using namespace Windows::Storage;
00025 using namespace Windows::Storage::FileProperties;
00026 using namespace Windows::Storage::Pickers;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 Scenario2::Scenario2()
00032 {
00033     InitializeComponent();
00034     rootPage = MainPage::Current;
00035 }
00036
00037 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00038 {
00039     rootPage->ResetOutput(ThumbnailImage, OutputTextBlock, nullptr);
00040 }
00041
00042 void Scenario2::GetThumbnailButton_Click(Object^ sender, RoutedEventArgs^ e)
00043 {
00044     rootPage->ResetOutput(ThumbnailImage, OutputTextBlock, nullptr);
00045
00046     // Pick a music file
00047     FileOpenPicker^ openPicker = ref new FileOpenPicker();
00048     Array<String^>^ extensions = FileExtensions::Music;
00049     for (unsigned int i = 0; i < extensions->Length; i++)
00050     {
00051         openPicker->FileTypeFilter->Append(extensions[i]);
00052     }
00053
00054     create_task(openPicker->PickSingleFileAsync()).then([this](StorageFile^ file)
00055     {
00056         if (file != nullptr)
00057         {
00058             const ThumbnailMode thumbnailMode = ThumbnailMode::MusicView;
00059             const size_t size = 100;
00060             create_task(file->GetThumbnailAsync(thumbnailMode, size)).then([this, file, size](StorageItemThumbnail^ thumbnail)
00061             {
00062                 if (thumbnail != nullptr && thumbnail->Type == ThumbnailType::Image)
00063                 {
00064                     MainPage::DisplayResult(ThumbnailImage, OutputTextBlock, "MusicView", size, file, thumbnail, false);
00065                 }
00066                 else
00067                 {
00068                     rootPage->NotifyUser(Errors::NoAlbumArt, NotifyType::StatusMessage);
00069                 }
00070             });
00071         }
00072         else
00073         {
00074             rootPage->NotifyUser(Errors::Cancel, NotifyType::StatusMessage);
00075         }
00076     });
00077 }
Generated on Fri Nov 15 2024 22:17:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DatagramSocket/cs/Scenario4_Close.xaml.cs Source File

  • DatagramSocket
  • cs

Scenario4_Close.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Diagnostics;
00015 using Windows.ApplicationModel.Core;
00016 using Windows.Networking;
00017 using Windows.Networking.Sockets;
00018 using Windows.Storage.Streams;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace DatagramSocketSample
00024 {
00025     /// <summary>
00026     /// A page for fourth scenario.
00027     /// </summary>
00028     public sealed partial class Scenario4 : Page
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         MainPage rootPage = MainPage.Current;
00033
00034         public Scenario4()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         /// <summary>
00040         /// Invoked when this page is about to be displayed in a Frame.
00041         /// </summary>
00042         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00043         /// property is typically used to configure the page.</param>
00044         protected override void OnNavigatedTo(NavigationEventArgs e)
00045         {
00046         }
00047
00048         /// <summary>
00049         /// This is the click handler for the 'CloseSockets' button.
00050         /// </summary>
00051         /// <param name="sender">Object for which the event was generated.</param>
00052         /// <param name="e">Event's parameters.</param>
00053         private void CloseSockets_Click(object sender, RoutedEventArgs e)
00054         {
00055             object outValue;
00056             if (CoreApplication.Properties.TryGetValue("clientDataWriter", out outValue))
00057             {
00058                 // Remove the data writer from the list of application properties as we are about to close it.
00059                 CoreApplication.Properties.Remove("clientDataWriter");
00060                 DataWriter dataWriter = (DataWriter)outValue;
00061
00062                 // To reuse the socket with other data writer, application has to detach the stream from the writer
00063                 // before disposing it. This is added for completeness, as this sample closes the socket in
00064                 // very next block.
00065                 dataWriter.DetachStream();
00066                 dataWriter.Dispose();
00067             }
00068
00069             if (CoreApplication.Properties.TryGetValue("clientSocket", out outValue))
00070             {
00071                 // Remove the socket from the list of application properties as we are about to close it.
00072                 CoreApplication.Properties.Remove("clientSocket");
00073                 DatagramSocket socket = (DatagramSocket)outValue;
00074
00075                 // DatagramSocket.Close() is exposed through the Dispose() method in C#.
00076                 // The call below explicitly closes the socket.
00077                 socket.Dispose();
00078             }
00079
00080             if (CoreApplication.Properties.TryGetValue("listener", out outValue))
00081             {
00082                 // Remove the listener from the list of application properties as we are about to close it.
00083                 CoreApplication.Properties.Remove("listener");
00084                 DatagramSocket listener = (DatagramSocket)outValue;
00085
00086                 // DatagramSocket.Close() is exposed through the Dispose() method in C#.
00087                 // The call below explicitly closes the socket.
00088                 listener.Dispose();
00089             }
00090
00091             CoreApplication.Properties.Remove("remotePeer");
00092             CoreApplication.Properties.Remove("connected");
00093             CoreApplication.Properties.Remove("serverAddress");
00094
00095             rootPage.NotifyUser("Socket and listener closed", NotifyType.StatusMessage);
00096         }
00097
00098     }
00099 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/Content/ControlBase.cpp Source File

  • HolographicMixedRealityCapture
  • cpp
  • Content

ControlBase.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "ControlBase.h"
00003 #include "Common\DirectXHelper.h"
00004
00005 using namespace HolographicMRCSample;
00006 using namespace Concurrency;
00007 using namespace DirectX;
00008 using namespace Windows::Foundation::Numerics;
00009 using namespace Windows::UI::Input::Spatial;
00010
00011 // Loads vertex and pixel shaders from files and instantiates the cube geometry.
00012 ControlBase::ControlBase()
00013 {
00014 }
00015
00016 void ControlBase::Initialize(const std::shared_ptr<DX::DeviceResources>& deviceResources)
00017 {
00018     m_deviceResources = deviceResources;
00019
00020     CreateDeviceDependentResources();
00021 }
00022
00023 ControlBase::~ControlBase()
00024 {
00025     m_children.clear();
00026 }
00027
00028 void ControlBase::CreateDeviceDependentResources()
00029 {
00030     DoCreateDeviceDependentResources();
00031
00032     for (auto it = m_children.begin(); it != m_children.end(); it++)
00033     {
00034         it->get()->CreateDeviceDependentResources();
00035     }
00036 }
00037
00038 void ControlBase::ReleaseDeviceDependentResources()
00039 {
00040     DoReleaseDeviceDependentResources();
00041
00042     for (auto it = m_children.begin(); it != m_children.end(); it++)
00043     {
00044         it->get()->ReleaseDeviceDependentResources();
00045     }
00046 }
00047
00048 void ControlBase::Update(
00049     const DX::StepTimer& timer,
00050     HolographicFrame^ holographicFrame,
00051     SpatialCoordinateSystem^ currentCoordinateSystem,
00052     SpatialInteractionSourceState^ interactionSource)
00053 {
00054     Update(timer, holographicFrame, currentCoordinateSystem, interactionSource, DirectX::XMMatrixIdentity());
00055 }
00056
00057 void ControlBase::Update(
00058     const DX::StepTimer& timer,
00059     HolographicFrame^ holographicFrame,
00060     SpatialCoordinateSystem^ currentCoordinateSystem,
00061     SpatialInteractionSourceState^ interactionSource,
00062     const DirectX::XMMATRIX &parentTransform)
00063 {
00064     DoUpdate(timer, holographicFrame, currentCoordinateSystem, interactionSource, parentTransform);
00065
00066     for (auto it = m_children.begin(); it != m_children.end(); it++)
00067     {
00068         it->get()->Update(timer, holographicFrame, currentCoordinateSystem, interactionSource, DirectX::XMLoadFloat4x4(&m_transform));
00069     }
00070 }
00071
00072 void ControlBase::Render()
00073 {
00074     DoRender();
00075
00076     for (auto it = m_children.begin(); it != m_children.end(); it++)
00077     {
00078         it->get()->Render();
00079     }
00080 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CameraCoordinateMapper Member List

This is the complete list of members for CameraCoordinateMapper, including all inherited members.
AreCamerasStreaming() const | CameraCoordinateMapper |
CameraCoordinateMapper(std::shared_ptr< DX::DeviceResources > deviceResources, std::shared_ptr< CameraStreamProcessor > colorStreamProcessor, std::shared_ptr< CameraStreamProcessor > depthStreamProcessor) | CameraCoordinateMapper |
CreateAndStartAsync(std::shared_ptr< DX::DeviceResources > deviceResources) | CameraCoordinateMapper | [static]
CreateDeviceDependentResources() | CameraCoordinateMapper |
GetTargetAspectRatio() const | CameraCoordinateMapper |
GetTargetShaderResourceView() const | CameraCoordinateMapper |
m_colorCameraStreamProcessor | CameraCoordinateMapper | [private]
m_colorDistortionMapTexture | CameraCoordinateMapper | [private]
m_colorDistortionMapTextureSRV | CameraCoordinateMapper | [private]
m_colorFrameIndex | CameraCoordinateMapper | [private]
m_colorIntrinsics | CameraCoordinateMapper | [private]
m_colorTexture | CameraCoordinateMapper | [private]
m_colorTextureSRV | CameraCoordinateMapper | [private]
m_depthCameraStreamProcessor | CameraCoordinateMapper | [private]
m_depthFrameIndex | CameraCoordinateMapper | [private]
m_depthIntrinsics | CameraCoordinateMapper | [private]
m_depthTexture | CameraCoordinateMapper | [private]
m_depthTextureSRV | CameraCoordinateMapper | [private]
m_depthUnprojectionMapTexture | CameraCoordinateMapper | [private]
m_depthUnprojectionMapTextureSRV | CameraCoordinateMapper | [private]
m_deviceResources | CameraCoordinateMapper | [private]
m_gpuCoordinateMapper | CameraCoordinateMapper | [private]
m_rasterizeFrameBlob | CameraCoordinateMapper | [private]
m_targetRasterizedDepthTexture | CameraCoordinateMapper | [private]
m_targetRasterizedDepthTextureDSV | CameraCoordinateMapper | [private]
m_targetRasterizedDepthTextureSRV | CameraCoordinateMapper | [private]
m_targetTexture | CameraCoordinateMapper | [private]
m_targetTextureRTV | CameraCoordinateMapper | [private]
m_targetTextureSRV | CameraCoordinateMapper | [private]
m_visualizeFrameBlob | CameraCoordinateMapper | [private]
ReleaseDeviceDependentResources() | CameraCoordinateMapper |
RunCoordinateMapping() | CameraCoordinateMapper |
StartAsync() | CameraCoordinateMapper |
StopAsync() | CameraCoordinateMapper |
TryAcquireLatestFrameData() | CameraCoordinateMapper |
UpdateColorResources(Windows::Media::Capture::Frames::MediaFrameReference^colorFrame) | CameraCoordinateMapper | [private]
UpdateDepthResources(Windows::Media::Capture::Frames::MediaFrameReference^depthFrame) | CameraCoordinateMapper | [private]
VisualizeCoordinateMapping(ID3D11RenderTargetView *renderTarget, ID3D11DepthStencilView *depthBuffer, const D3D11_VIEWPORT &viewport, const Windows::Foundation::Numerics::float4x4 &worldToView) | CameraCoordinateMapper |
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScannerProvider/cs/BarcodeDecoder/Provider.cs Source File

  • BarcodeScannerProvider
  • cs
  • BarcodeDecoder

Provider.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.ApplicationModel.Background;
00015 using Windows.ApplicationModel.Resources;
00016 using Windows.Devices.PointOfService;
00017 using Windows.Devices.PointOfService.Provider;
00018 using Windows.Graphics.Imaging;
00019 using Windows.Security.Cryptography;
00020 using Windows.Storage.Streams;
00021
00022 namespace BarcodeDecoder
00023 {
00024     internal class Provider : IDisposable
00025     {
00026         private DecodeEngine decodeEngine = null;
00027         private DecodeResult previousDecodeResult = null;
00028         private IBackgroundTaskInstance backgroundTask = null;
00029         private bool scannerEnabled = false;
00030         private Dictionary<uint, BarcodeSymbologyAttributes> symbologyAttributes = new Dictionary<uint, BarcodeSymbologyAttributes>();
00031         private BackgroundTaskDeferral deferral = null;
00032         private BarcodeScannerFrameReader frameReader = null;
00033         private bool disposed = false;
00034         private BarcodeScannerProviderConnection connection = null;
00035
00036         readonly int E_BOUNDS = unchecked((int)0x8000000B);
00037
00038         public Provider(IBackgroundTaskInstance backgroundTask)
00039         {
00040             this.backgroundTask = backgroundTask;
00041
00042             var triggerDetails = (BarcodeScannerProviderTriggerDetails)backgroundTask.TriggerDetails;
00043             connection = triggerDetails.Connection;
00044
00045             Initialize();
00046         }
00047
00048         ~Provider()
00049         {
00050             Dispose(false);
00051         }
00052
00053         public void Dispose()
00054         {
00055             Dispose(true);
00056             GC.SuppressFinalize(this);
00057         }
00058
00059         protected virtual void Dispose(bool disposing)
00060         {
00061             if (disposed)
00062             {
00063                 return;
00064             }
00065
00066             if (disposing)
00067             {
00068                 frameReader?.Dispose();
00069                 frameReader = null;
00070
00071                 connection?.Dispose();
00072                 connection = null;
00073
00074                 deferral?.Complete();
00075                 deferral = null;
00076
00077                 disposed = true;
00078             }
00079         }
00080
00081         public static BarcodeScannerReport CreateBarcodeScannerReportFromString(string scanData, uint symbology)
00082         {
00083             IBuffer scanDataBuffer = CryptographicBuffer.ConvertStringToBinary(scanData, BinaryStringEncoding.Utf8);
00084             return new BarcodeScannerReport(symbology, scanDataBuffer, scanDataBuffer);
00085         }
00086
00087         private void Initialize()
00088         {
00089             deferral = backgroundTask.GetDeferral();
00090             RegisterEventHandlers();
00091
00092             // Set provider information. This information is localized, so read it from our resources.
00093             ResourceLoader resourceLoader = ResourceLoader.GetForViewIndependentUse();
00094             connection.CompanyName = resourceLoader.GetString("Company");
00095             connection.Name = resourceLoader.GetString("Product");
00096             connection.Version = resourceLoader.GetString("Version");
00097
00098             decodeEngine = new DecodeEngine();
00099
00100             // Our decode engine does not support any of these features.
00101             var attributesBuilder = new BarcodeSymbologyAttributesBuilder
00102             {
00103                 IsCheckDigitTransmissionSupported = false,
00104                 IsCheckDigitValidationSupported = false,
00105                 IsDecodeLengthSupported = false,
00106             };
00107
00108             // Tell the system which symbologies we support.
00109             foreach (uint symbology in decodeEngine.SupportedSymbologies)
00110             {
00111                 connection.SupportedSymbologies.Add(symbology);
00112
00113                 // Populate a dictionary for tracking symbology attributes for each supported symbology.
00114                 // (This step is unnecessary in the case of this sample because none of these properties
00115                 // is marked as supported in our BarcodeSymbologyAttributesBuilder, but we track them
00116                 // in this sample in order to show how it could be done.)
00117                 BarcodeSymbologyAttributes defaultAttributes = attributesBuilder.CreateAttributes();
00118                 if (attributesBuilder.IsDecodeLengthSupported)
00119                 {
00120                     // These are the default values, but we set them explicitly for demonstration purposes.
00121                     defaultAttributes.DecodeLength1 = 0;
00122                     defaultAttributes.DecodeLength2 = 0;
00123                     defaultAttributes.DecodeLengthKind = BarcodeSymbologyDecodeLengthKind.AnyLength;
00124                 }
00125                 if (attributesBuilder.IsCheckDigitTransmissionSupported)
00126                 {
00127                     // This is the default value, but we set it explicitly for demonstration purposes.
00128                     defaultAttributes.IsCheckDigitTransmissionEnabled = false;
00129                 }
00130                 if (attributesBuilder.IsCheckDigitValidationSupported)
00131                 {
00132                     // This is the default value, but we set it explicitly for demonstration purposes.
00133                     defaultAttributes.IsCheckDigitValidationEnabled = false;
00134                 }
00135                 symbologyAttributes.Add(symbology, defaultAttributes);
00136             }
00137
00138             // Start the connection after
00139             // 1. Provider information is set
00140             // 2. Supported symbologies are added
00141             // 3. All event handlers are registered
00142             connection.Start();
00143         }
00144
00145         private void RegisterEventHandlers()
00146         {
00147             backgroundTask.Canceled += BackgroundTask_Canceled;
00148             backgroundTask.Task.Completed += Task_Completed;
00149
00150             connection.EnableScannerRequested += BarcodeScannerProviderConnection_EnableScannerRequested;
00151             connection.DisableScannerRequested += BarcodeScannerProviderConnection_DisableScannerRequested;
00152
00153             connection.GetBarcodeSymbologyAttributesRequested += BarcodeScannerProviderConnection_GetBarcodeSymbologyAttributesRequested;
00154             connection.SetBarcodeSymbologyAttributesRequested += BarcodeScannerProviderConnection_SetBarcodeSymbologyAttributesRequested;
00155
00156             connection.StartSoftwareTriggerRequested += BarcodeScannerProviderConnection_StartSoftwareTriggerRequested;
00157             connection.StopSoftwareTriggerRequested += BarcodeScannerProviderConnection_StopSoftwareTriggerRequested;
00158
00159             connection.HideVideoPreviewRequested += BarcodeScannerProviderConnection_HideVideoPreviewRequested;
00160             connection.SetActiveSymbologiesRequested += BarcodeScannerProviderConnection_SetActiveSymbologiesRequested;
00161         }
00162
00163         private void Task_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
00164         {
00165             Dispose();
00166         }
00167
00168         private void BackgroundTask_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
00169         {
00170             Dispose();
00171         }
00172
00173         private async void BarcodeScannerProviderConnection_EnableScannerRequested(BarcodeScannerProviderConnection sender, BarcodeScannerEnableScannerRequestEventArgs args)
00174         {
00175             // For BarcodeScannerProviderConnection events,
00176             // a deferral is not required if the only async operation
00177             // is ReportCompletedAsync or ReportFailedAsync.
00178             scannerEnabled = true;
00179             await args.Request.ReportCompletedAsync();
00180         }
00181
00182         private async void BarcodeScannerProviderConnection_DisableScannerRequested(BarcodeScannerProviderConnection sender, BarcodeScannerDisableScannerRequestEventArgs args)
00183         {
00184             using (args.GetDeferral())
00185             {
00186                 scannerEnabled = false;
00187
00188                 // Stop frame reader when disabled
00189                 if (frameReader != null)
00190                 {
00191                     await frameReader.StopAsync();
00192                 }
00193                 await args.Request.ReportCompletedAsync();
00194             }
00195         }
00196
00197         private async void BarcodeScannerProviderConnection_GetBarcodeSymbologyAttributesRequested(BarcodeScannerProviderConnection sender, BarcodeScannerGetSymbologyAttributesRequestEventArgs args)
00198         {
00199             BarcodeSymbologyAttributes attributes;
00200             if (symbologyAttributes.TryGetValue(args.Request.Symbology, out attributes))
00201             {
00202                 await args.Request.ReportCompletedAsync(attributes);
00203             }
00204             else
00205             {
00206                 await args.Request.ReportFailedAsync(E_BOUNDS, "The requested symbology is not supported.");
00207             }
00208         }
00209
00210         private async void BarcodeScannerProviderConnection_SetBarcodeSymbologyAttributesRequested(BarcodeScannerProviderConnection sender, BarcodeScannerSetSymbologyAttributesRequestEventArgs args)
00211         {
00212             // Update the symbology attributes for the specified symbology.
00213             BarcodeSymbologyAttributes newAttributes = args.Request.Attributes;
00214             BarcodeSymbologyAttributes existingAttributes;
00215             if (symbologyAttributes.TryGetValue(args.Request.Symbology, out existingAttributes))
00216             {
00217                 // Our sample does not support these properties, but we update them for illustration purposes.
00218                 if (existingAttributes.IsDecodeLengthSupported)
00219                 {
00220                     existingAttributes.DecodeLength1 = newAttributes.DecodeLength1;
00221                     existingAttributes.DecodeLength2 = newAttributes.DecodeLength2;
00222                     existingAttributes.DecodeLengthKind = newAttributes.DecodeLengthKind;
00223                 }
00224                 if (existingAttributes.IsCheckDigitTransmissionSupported)
00225                 {
00226                     existingAttributes.IsCheckDigitTransmissionEnabled = newAttributes.IsCheckDigitTransmissionEnabled;
00227                 }
00228                 if (existingAttributes.IsCheckDigitValidationSupported)
00229                 {
00230                     existingAttributes.IsCheckDigitValidationEnabled = newAttributes.IsCheckDigitValidationEnabled;
00231                 }
00232                 // If we supported these properties, we would also have to update the parameters of the decoder
00233                 // at this point.
00234                 await args.Request.ReportCompletedAsync();
00235             }
00236             else
00237             {
00238                 await args.Request.ReportFailedAsync(E_BOUNDS, "The requested symbology is not supported.");
00239             }
00240         }
00241
00242         private async void FrameReader_FrameArrived(BarcodeScannerFrameReader sender, BarcodeScannerFrameReaderFrameArrivedEventArgs args)
00243         {
00244             if (!scannerEnabled)
00245             {
00246                 // Return immediately if decoder is not enabled
00247                 return;
00248             }
00249
00250             using (args.GetDeferral())
00251             {
00252                 SoftwareBitmap bitmap = null;
00253                 using (BarcodeScannerVideoFrame frame = await sender.TryAcquireLatestFrameAsync())
00254                 {
00255                     if (frame != null)
00256                     {
00257                         // Build software bitmap from pixel data
00258                         bitmap = SoftwareBitmap.CreateCopyFromBuffer(frame.PixelData, frame.Format, (int)frame.Width, (int)frame.Height);
00259                     }
00260                 }
00261
00262                 if (bitmap != null)
00263                 {
00264                     DecodeResult decodeResult = await decodeEngine.DecodeAsync(bitmap);
00265
00266                     bitmap.Dispose();
00267                     bitmap = null;
00268
00269                     // Report only if we have a result that is different from previous one.
00270                     if (decodeResult != null && !decodeResult.Equals(previousDecodeResult))
00271                     {
00272                         previousDecodeResult = decodeResult;
00273                         await connection.ReportScannedDataAsync(CreateBarcodeScannerReportFromString(decodeResult.Text, decodeResult.Symbology));
00274                     }
00275                 }
00276             }
00277         }
00278
00279         private async void BarcodeScannerProviderConnection_StartSoftwareTriggerRequested(BarcodeScannerProviderConnection sender, BarcodeScannerStartSoftwareTriggerRequestEventArgs args)
00280         {
00281             using (args.GetDeferral())
00282             {
00283                 bool readerStarted = false;
00284
00285                 if (scannerEnabled)
00286                 {
00287                     if (frameReader == null)
00288                     {
00289                         // Create frame reader to read video frames
00290                         frameReader = await connection.CreateFrameReaderAsync(BitmapPixelFormat.Nv12, new BitmapSize() { Width = 1280, Height = 720 });
00291                         frameReader.FrameArrived += FrameReader_FrameArrived;
00292                     }
00293
00294                     readerStarted = await frameReader.StartAsync();
00295                 }
00296
00297                 if (readerStarted)
00298                 {
00299                     await args.Request.ReportCompletedAsync();
00300                 }
00301                 else
00302                 {
00303                     await args.Request.ReportFailedAsync();
00304                 }
00305             }
00306         }
00307
00308         private async void BarcodeScannerProviderConnection_StopSoftwareTriggerRequested(BarcodeScannerProviderConnection sender, BarcodeScannerStopSoftwareTriggerRequestEventArgs args)
00309         {
00310             using (args.GetDeferral())
00311             {
00312                 if (frameReader != null)
00313                 {
00314                     await frameReader.StopAsync();
00315                 }
00316                 await args.Request.ReportCompletedAsync();
00317             }
00318         }
00319
00320         private async void BarcodeScannerProviderConnection_HideVideoPreviewRequested(BarcodeScannerProviderConnection sender, BarcodeScannerHideVideoPreviewRequestEventArgs args)
00321         {
00322             // There is no video preview running as background task. Simply report completed.
00323             await args.Request.ReportCompletedAsync();
00324         }
00325
00326         private async void BarcodeScannerProviderConnection_SetActiveSymbologiesRequested(BarcodeScannerProviderConnection sender, BarcodeScannerSetActiveSymbologiesRequestEventArgs args)
00327         {
00328             // Ensure all symbologies being set to active are supported.
00329             foreach (var symbology in args.Request.Symbologies)
00330             {
00331                 if (!decodeEngine.SupportedSymbologies.Contains(symbology))
00332                 {
00333                     // Found invalid symbology.
00334                     await args.Request.ReportFailedAsync();
00335                     return;
00336                 }
00337             }
00338             decodeEngine.ActiveSymbologies = new List<uint>(args.Request.Symbologies);
00339             await args.Request.ReportCompletedAsync();
00340         }
00341     }
00342 }
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cppwinrt/BasicHologramMain.h Source File

  • BasicHologram
  • cppwinrt

BasicHologramMain.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 //
00004 // Comment out this preprocessor definition to disable all of the
00005 // sample content.
00006 //
00007 // To remove the content after disabling it:
00008 //     * Remove the unused code from your app's Main class.
00009 //     * Delete the Content folder provided with this template.
00010 //
00011 #define DRAW_SAMPLE_CONTENT
00012
00013 #include "Common\DeviceResources.h"
00014 #include "Common\StepTimer.h"
00015
00016 #ifdef DRAW_SAMPLE_CONTENT
00017 #include "Content\SpinningCubeRenderer.h"
00018 #include "Content\SpatialInputHandler.h"
00019 #endif
00020
00021 // Updates, renders, and presents holographic content using Direct3D.
00022 namespace BasicHologram
00023 {
00024     class BasicHologramMain : public DX::IDeviceNotify
00025     {
00026     public:
00027         BasicHologramMain(std::shared_ptr<DX::DeviceResources> const& deviceResources);
00028         ~BasicHologramMain();
00029
00030         // Sets the holographic space. This is our closest analogue to setting a new window
00031         // for the app.
00032         void SetHolographicSpace(winrt::Windows::Graphics::Holographic::HolographicSpace const& holographicSpace);
00033
00034         // Starts the holographic frame and updates the content.
00035         winrt::Windows::Graphics::Holographic::HolographicFrame Update();
00036
00037         // Renders holograms, including world-locked content.
00038         bool Render(winrt::Windows::Graphics::Holographic::HolographicFrame const& holographicFrame);
00039
00040         // Handle saving and loading of app state owned by AppMain.
00041         void SaveAppState();
00042         void LoadAppState();
00043
00044         // Handle mouse input.
00045         void OnPointerPressed();
00046
00047         // IDeviceNotify
00048         void OnDeviceLost() override;
00049         void OnDeviceRestored() override;
00050
00051     private:
00052         // Asynchronously creates resources for new holographic cameras.
00053         void OnCameraAdded(
00054             winrt::Windows::Graphics::Holographic::HolographicSpace const& sender,
00055             winrt::Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs const& args);
00056
00057         // Synchronously releases resources for holographic cameras that are no longer
00058         // attached to the system.
00059         void OnCameraRemoved(
00060             winrt::Windows::Graphics::Holographic::HolographicSpace const& sender,
00061             winrt::Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs const& args);
00062
00063         // Used to notify the app when the positional tracking state changes.
00064         void OnLocatabilityChanged(
00065             winrt::Windows::Perception::Spatial::SpatialLocator const& sender,
00066             winrt::Windows::Foundation::IInspectable const& args);
00067
00068         // Used to be aware of gamepads that are plugged in after the app starts.
00069         void OnGamepadAdded(winrt::Windows::Foundation::IInspectable, winrt::Windows::Gaming::Input::Gamepad const& args);
00070
00071         // Used to stop looking for gamepads that are removed while the app is running.
00072         void OnGamepadRemoved(winrt::Windows::Foundation::IInspectable, winrt::Windows::Gaming::Input::Gamepad const& args);
00073
00074         // Used to respond to changes to the default spatial locator.
00075         void OnHolographicDisplayIsAvailableChanged(winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);
00076
00077         // Clears event registration state. Used when changing to a new HolographicSpace
00078         // and when tearing down AppMain.
00079         void UnregisterHolographicEventHandlers();
00080
00081 #ifdef DRAW_SAMPLE_CONTENT
00082         // Renders a colorful holographic cube that's 20 centimeters wide. This sample content
00083         // is used to demonstrate world-locked rendering.
00084         std::unique_ptr<SpinningCubeRenderer>                       m_spinningCubeRenderer;
00085
00086         // Listens for the Pressed spatial input event.
00087         std::shared_ptr<SpatialInputHandler>                        m_spatialInputHandler;
00088 #endif
00089
00090         // Cached pointer to device resources.
00091         std::shared_ptr<DX::DeviceResources>                        m_deviceResources;
00092
00093         // Render loop timer.
00094         DX::StepTimer                                               m_timer;
00095
00096         // Represents the holographic space around the user.
00097         winrt::Windows::Graphics::Holographic::HolographicSpace     m_holographicSpace = nullptr;
00098
00099         // SpatialLocator that is attached to the default HolographicDisplay.
00100         winrt::Windows::Perception::Spatial::SpatialLocator         m_spatialLocator = nullptr;
00101
00102         // A stationary reference frame based on m_spatialLocator.
00103         winrt::Windows::Perception::Spatial::SpatialStationaryFrameOfReference m_stationaryReferenceFrame = nullptr;
00104
00105         // Event registration tokens.
00106         winrt::event_token                                          m_cameraAddedToken;
00107         winrt::event_token                                          m_cameraRemovedToken;
00108         winrt::event_token                                          m_locatabilityChangedToken;
00109         winrt::event_token                                          m_gamepadAddedEventToken;
00110         winrt::event_token                                          m_gamepadRemovedEventToken;
00111         winrt::event_token                                          m_holographicDisplayIsAvailableChangedEventToken;
00112
00113         // Keep track of gamepads.
00114         struct GamepadWithButtonState
00115         {
00116             winrt::Windows::Gaming::Input::Gamepad gamepad;
00117             bool buttonAWasPressedLastFrame = false;
00118         };
00119         std::vector<GamepadWithButtonState>                         m_gamepads;
00120
00121         // Keep track of mouse input.
00122         bool                                                        m_pointerPressed = false;
00123
00124         // Cache whether or not the HolographicCamera.Display property can be accessed.
00125         bool                                                        m_canGetHolographicDisplayForCamera = false;
00126
00127         // Cache whether or not the HolographicDisplay.GetDefault() method can be called.
00128         bool                                                        m_canGetDefaultHolographicDisplay = false;
00129
00130         // Cache whether or not the HolographicCameraRenderingParameters.CommitDirect3D11DepthBuffer() method can be called.
00131         bool                                                        m_canCommitDirect3D11DepthBuffer = false;
00132     };
00133 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/PhasingTests.xaml.cpp Source File

  • XamlBind
  • cpp

PhasingTests.xaml.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // PhasingTests.xaml.cpp
00003 // Implementation of the PhasingTests class
00004 //
00005
00006 #include "pch.h"
00007 #include "PhasingTests.xaml.h"
00008
00009 using namespace SDKTemplate;
00010
00011 using namespace concurrency;
00012 using namespace Platform;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::Foundation::Collections;
00015 using namespace Windows::UI::Xaml;
00016 using namespace Windows::UI::Xaml::Controls;
00017 using namespace Windows::UI::Xaml::Controls::Primitives;
00018 using namespace Windows::UI::Xaml::Data;
00019 using namespace Windows::UI::Xaml::Input;
00020 using namespace Windows::UI::Xaml::Media;
00021 using namespace Windows::UI::Xaml::Navigation;
00022 using namespace Windows::Storage::Pickers;
00023 using namespace Windows::Storage;
00024
00025 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00026
00027 PhasingTests::PhasingTests()
00028 {
00029     InitializeComponent();
00030     CreateTestData();
00031     initialized = true;
00032 }
00033
00034 void PhasingTests::CreateTestData()
00035 {
00036     create_task(dataSource->SetupDataSourceUsingPicturesFolder()).then([this]()
00037     {
00038         this->LoadingPanel->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00039         this->myGridView->ItemsSource = dataSource;
00040     });
00041 }
00042
00043 void PhasingTests::Reset_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00044 {
00045     dataSource->ResetCollection();
00046 }
00047
00048
00049 void PhasingTests::ChangeFolderClick(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00050 {
00051     FolderPicker^ picker = ref new FolderPicker();
00052     picker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00053     picker->FileTypeFilter->Append(".jpg");
00054     picker->FileTypeFilter->Append(".png");
00055
00056     create_task(picker->PickSingleFolderAsync()).then([this](StorageFolder^ f)
00057     {
00058         dataSource = ref new xBindSampleModel::FileDataSource();
00059         this->myGridView->ItemsSource = dataSource;
00060         LoadingPanel->Visibility = Windows::UI::Xaml::Visibility::Visible;
00061         create_task(dataSource->SetupDataSource(f)).then([this]()
00062         {
00063             this->LoadingPanel->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00064         });
00065     });
00066 }
00067
00068 void PhasingTests::SlowPhasing_UnChecked(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00069 {
00070     SlowPhasing_Checked(sender, e);
00071 }
00072
00073 void PhasingTests::SlowPhasing_Checked(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00074 {
00075     if (initialized)
00076     {
00077         if (SlowPhasing->IsChecked->Value)
00078         {
00079             _CCCToken = myGridView->ContainerContentChanging += ref new TypedEventHandler<ListViewBase^, ContainerContentChangingEventArgs^>(this, &PhasingTests::myGridView_ContainerContentChanging);
00080         }
00081         else
00082         {
00083             myGridView->ContainerContentChanging -= _CCCToken;
00084         }
00085     }
00086 }
00087
00088 void PhasingTests::PhasedTemplate_Checked(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00089 {
00090     if (initialized)
00091     {
00092         if (RadioPhasedTempl->IsChecked->Value == true)
00093         {
00094             myGridView->ItemTemplate = dynamic_cast<DataTemplate^>(Resources->Lookup("PhasedFileTemplate"));
00095         }
00096         else if (RadioxBindTempl->IsChecked->Value)
00097         {
00098             myGridView->ItemTemplate = dynamic_cast<DataTemplate^>(Resources->Lookup("ClassicBindingFileTemplate"));
00099         }
00100         else if (RadioClassicTempl->IsChecked->Value)
00101         {
00102             myGridView->ItemTemplate = dynamic_cast<DataTemplate^>(Resources->Lookup("ClassicBindingFileTemplate"));
00103         }
00104     }
00105 }
00106
00107 void PhasingTests::myGridView_ContainerContentChanging(ListViewBase^ sender, ContainerContentChangingEventArgs^ args)
00108 {
00109     if (args->Phase < 10) args->RegisterUpdateCallback(ref new TypedEventHandler<ListViewBase^, ContainerContentChangingEventArgs^>(this, &PhasingTests::myGridView_ContainerContentChanging));
00110     Sleep(1);
00111 }
00112
00113 void PhasingTests::DataSource_VectorChanged(Windows::Foundation::Collections::IObservableVector<xBindSampleModel::FileItem^>^ sender, Windows::Foundation::Collections::IVectorChangedEventArgs^ e)
00114 {
00115     this->NoItemsPanel->Visibility = (dataSource->Count == 0) ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00116 }
00117
00118 void PhasingTests::Sleep(int timeout)
00119 {
00120     //This function should not be used in real apps, it blocks the UI thread for a timeout. It is used in this sample to illustrate the effects of phasing.
00121     auto eventHandle = ::CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, 0);
00122     ::WaitForSingleObjectEx(eventHandle, timeout, FALSE);
00123 }
Generated on Fri Nov 15 2024 22:22:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Provider Member List

This is the complete list of members for Provider, including all inherited members.
backgroundTask | Provider | [private]
BackgroundTask_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) | Provider | [inline, private]
BarcodeScannerProviderConnection_DisableScannerRequested(BarcodeScannerProviderConnection sender, BarcodeScannerDisableScannerRequestEventArgs args) | Provider | [inline, private]
BarcodeScannerProviderConnection_EnableScannerRequested(BarcodeScannerProviderConnection sender, BarcodeScannerEnableScannerRequestEventArgs args) | Provider | [inline, private]
BarcodeScannerProviderConnection_GetBarcodeSymbologyAttributesRequested(BarcodeScannerProviderConnection sender, BarcodeScannerGetSymbologyAttributesRequestEventArgs args) | Provider | [inline, private]
BarcodeScannerProviderConnection_HideVideoPreviewRequested(BarcodeScannerProviderConnection sender, BarcodeScannerHideVideoPreviewRequestEventArgs args) | Provider | [inline, private]
BarcodeScannerProviderConnection_SetActiveSymbologiesRequested(BarcodeScannerProviderConnection sender, BarcodeScannerSetActiveSymbologiesRequestEventArgs args) | Provider | [inline, private]
BarcodeScannerProviderConnection_SetBarcodeSymbologyAttributesRequested(BarcodeScannerProviderConnection sender, BarcodeScannerSetSymbologyAttributesRequestEventArgs args) | Provider | [inline, private]
BarcodeScannerProviderConnection_StartSoftwareTriggerRequested(BarcodeScannerProviderConnection sender, BarcodeScannerStartSoftwareTriggerRequestEventArgs args) | Provider | [inline, private]
BarcodeScannerProviderConnection_StopSoftwareTriggerRequested(BarcodeScannerProviderConnection sender, BarcodeScannerStopSoftwareTriggerRequestEventArgs args) | Provider | [inline, private]
connection | Provider | [private]
CreateBarcodeScannerReportFromString(string scanData, uint symbology) | Provider | [inline, static]
decodeEngine | Provider | [private]
deferral | Provider | [private]
Dispose() | Provider | [inline]
Dispose(bool disposing) | Provider | [inline, protected, virtual]
disposed | Provider | [private]
E_BOUNDS | Provider | [private]
frameReader | Provider | [private]
FrameReader_FrameArrived(BarcodeScannerFrameReader sender, BarcodeScannerFrameReaderFrameArrivedEventArgs args) | Provider | [inline, private]
Initialize() | Provider | [inline, private]
previousDecodeResult | Provider | [private]
Provider(IBackgroundTaskInstance backgroundTask) | Provider | [inline]
RegisterEventHandlers() | Provider | [inline, private]
scannerEnabled | Provider | [private]
symbologyAttributes | Provider | [private]
Task_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args) | Provider | [inline, private]
~Provider() | Provider | [inline, private]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SubjectPublicKeyInfo::SafeBCryptKeyHandle Member List

This is the complete list of members for SubjectPublicKeyInfo::SafeBCryptKeyHandle, including all inherited members.
ReleaseHandle() | SubjectPublicKeyInfo::SafeBCryptKeyHandle | [inline, protected]
SafeBCryptKeyHandle() | SubjectPublicKeyInfo::SafeBCryptKeyHandle | [inline, private]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LibraryManagement/cs/S1_AddFolder.xaml.cs Source File

  • LibraryManagement
  • cs

S1_AddFolder.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Storage;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     public sealed partial class Scenario1 : Page
00024     {
00025         public Scenario1()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         /// <summary>
00031         /// Invoked when this page is about to be displayed in a Frame.
00032         /// </summary>
00033         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00034         /// property is typically used to configure the page.</param>
00035         protected override void OnNavigatedTo(NavigationEventArgs e)
00036         {
00037         }
00038
00039         /// <summary>
00040         /// Displays the folder Picker to request that the user select a folder that will be added to the
00041         /// Pictures library.
00042         /// </summary>
00043         /// <param name="sender"></param>
00044         /// <param name="e"></param>
00045         private async void AddFolderButton_Click(object sender, RoutedEventArgs e)
00046         {
00047             StorageLibrary picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
00048             StorageFolder folderAdded = await picturesLibrary.RequestAddFolderAsync();
00049             if (folderAdded != null)
00050             {
00051                 OutputTextBlock.Text = folderAdded.DisplayName + " was added to the Pictures library.";
00052             }
00053             else
00054             {
00055                 OutputTextBlock.Text = "Operation canceled.";
00056             }
00057         }
00058     }
00059 }
Generated on Fri Nov 15 2024 22:20:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/Helpers/TilesHelper.cs Source File

  • Notifications
  • cs
  • Notifications
  • Helpers

TilesHelper.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Linq;
00003 using System.Threading.Tasks;
00004 using Windows.Data.Xml.Dom;
00005 using Windows.UI.Notifications;
00006 using Windows.UI.Popups;
00007 using Windows.UI.StartScreen;
00008
00009 namespace Notifications.Helpers
00010 {
00011     public class TilesHelper
00012     {
00013         public static async Task<SecondaryTile> PinNewSecondaryTile()
00014         {
00015             SecondaryTile tile = GenerateSecondaryTile("Secondary tile");
00016
00017             await tile.RequestCreateAsync();
00018
00019             return tile;
00020         }
00021
00022         public static SecondaryTile GenerateSecondaryTile(string tileId, string displayName)
00023         {
00024             SecondaryTile tile = new SecondaryTile(tileId, displayName, "args", new Uri("ms-appx:///Assets/Logo.png"), TileSize.Default);
00025             tile.VisualElements.Square71x71Logo = new Uri("ms-appx:///Assets/Small.png");
00026             tile.VisualElements.Wide310x150Logo = new Uri("ms-appx:///Assets/WideLogo.png");
00027             tile.VisualElements.Square310x310Logo = new Uri("ms-appx:///Assets/LargeLogo.png");
00028             tile.VisualElements.Square44x44Logo = new Uri("ms-appx:///Assets/SmallLogo.png"); // Branding logo
00029
00030             return tile;
00031         }
00032
00033         public static SecondaryTile GenerateSecondaryTile(string displayName)
00034         {
00035             return GenerateSecondaryTile(DateTime.Now.Ticks.ToString(), displayName);
00036         }
00037
00038         public static async Task<SecondaryTile> FindExisting(string tileId)
00039         {
00040             return (await SecondaryTile.FindAllAsync()).FirstOrDefault(i => i.TileId.Equals(tileId));
00041         }
00042
00043         public static async Task<SecondaryTile> PinNewSecondaryTile(string displayName, string xml)
00044         {
00045             SecondaryTile tile = GenerateSecondaryTile(displayName);
00046             await tile.RequestCreateAsync();
00047
00048             XmlDocument doc = new XmlDocument();
00049             doc.LoadXml(xml);
00050
00051             TileUpdateManager.CreateTileUpdaterForSecondaryTile(tile.TileId).Update(new TileNotification(doc));
00052
00053             return tile;
00054         }
00055
00056         public static async Task UpdateTiles(string xml)
00057         {
00058             XmlDocument doc;
00059
00060             try
00061             {
00062                 doc = new XmlDocument();
00063                 doc.LoadXml(xml);
00064             }
00065
00066             catch (Exception ex)
00067             {
00068                 await new MessageDialog(ex.ToString(), "ERROR: Invalid XML").ShowAsync();
00069                 return;
00070             }
00071
00072             await UpdateTiles(doc);
00073         }
00074
00075         public static async Task UpdateTiles(XmlDocument doc)
00076         {
00077             try
00078             {
00079                 TileUpdateManager.CreateTileUpdaterForApplication().Update(new TileNotification(doc));
00080
00081                 await UpdateTile("Small", doc);
00082                 await UpdateTile("Medium", doc);
00083                 await UpdateTile("Wide", doc);
00084                 await UpdateTile("Large", doc);
00085             }
00086
00087             catch (Exception ex)
00088             {
00089                 await new MessageDialog(ex.ToString(), "ERROR: Failed updating tiles").ShowAsync();
00090             }
00091         }
00092
00093         public static async Task UpdateTile(string tileId, XmlDocument doc)
00094         {
00095             if (!SecondaryTile.Exists(tileId))
00096             {
00097                 SecondaryTile tile = GenerateSecondaryTile(tileId, tileId);
00098                 tile.VisualElements.ShowNameOnSquare310x310Logo = true;
00099                 await tile.RequestCreateAsync();
00100             }
00101                 //await GenerateSecondaryTile(tileId, tileId).RequestCreateAsync();
00102
00103             TileUpdateManager.CreateTileUpdaterForSecondaryTile(tileId).Update(new TileNotification(doc));
00104         }
00105     }
00106 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ClientDeviceInformation/cpp/SampleConfiguration.h Source File

  • ClientDeviceInformation
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "EAS protocol";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCoordinateMapper/cpp/Content/GpuCoordinateMapper.cpp Source File

  • CameraStreamCoordinateMapper
  • cpp
  • Content

GpuCoordinateMapper.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "GpuCoordinateMapper.h"
00014 #include "Common\DirectXHelper.h"
00015
00016 #include "Shaders\RasterizeDepthMeshVS.h"
00017 #include "Shaders\RasterizeDepthMeshPS.h"
00018
00019 #include "Shaders\VisualizeDepthMeshVS.h"
00020 #include "Shaders\VisualizeDepthMeshPS.h"
00021
00022 using namespace CameraStreamCoordinateMapper;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::Foundation::Numerics;
00026
00027 namespace
00028 {
00029     CameraIntrinsics_Shader GetCameraIntrinsicsConstantsForShader(const GpuCoordinateMapper::CameraIntrinsics& intrinsics)
00030     {
00031         CameraIntrinsics_Shader constants;
00032
00033         constants.imageWidth = intrinsics.imageWidth;
00034         constants.imageHeight = intrinsics.imageHeight;
00035
00036         return constants;
00037     }
00038
00039     RasterizeDepthMeshConstants_Shader GetRasterizeDepthMeshConstantsForShader(const GpuCoordinateMapper::RasterizedFrameBlob& frameBlob)
00040     {
00041         RasterizeDepthMeshConstants_Shader constants;
00042
00043         constants.depthIntrinsics = GetCameraIntrinsicsConstantsForShader(frameBlob.depthIntrinsics);
00044         constants.targetIntrinsics = GetCameraIntrinsicsConstantsForShader(frameBlob.targetIntrinsics);
00045         constants.sourceIntrinsics = GetCameraIntrinsicsConstantsForShader(frameBlob.sourceIntrinsics);
00046         constants.depthToSource = frameBlob.depthToSource;
00047         constants.depthToTarget = frameBlob.depthToTarget;
00048         constants.sourceProjectionMatrix = frameBlob.sourceProjectionMatrix;
00049         constants.targetProjectionMatrix = frameBlob.targetProjectionMatrix;
00050
00051         // DepthMaps are currently D16 format: [0,65535], depthScaleInMeters is how large each unit is in meters.
00052         constants.depthMapUnitsToMeters = frameBlob.depthScaleInMeters * std::numeric_limits<UINT16>::max();
00053         constants.depthRangeMinimumInMeters = frameBlob.depthRangeMinimumInMeters;
00054         constants.depthRangeMaximumInMeters = frameBlob.depthRangeMaximumInMeters;
00055         constants.depthMapImageWidthMinusOne = frameBlob.depthIntrinsics.imageWidth - 1u;
00056
00057         return constants;
00058     }
00059
00060     VisualizeDepthMeshConstants_Shader GetVisualizeDepthMeshConstantsForShader(const GpuCoordinateMapper::VisualizeFrameBlob& frameBlob)
00061     {
00062         VisualizeDepthMeshConstants_Shader constants;
00063
00064         constants.worldToProj = frameBlob.worldToView * frameBlob.viewToProj;
00065
00066         return constants;
00067     }
00068 }
00069
00070 GpuCoordinateMapper::GpuCoordinateMapper(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00071     m_deviceResources(deviceResources)
00072 {
00073     CreateDeviceDependentResources();
00074 }
00075
00076 void CameraStreamCoordinateMapper::GpuCoordinateMapper::CreateDeviceDependentResources()
00077 {
00078     ID3D11Device* device = m_deviceResources->GetD3DDevice();
00079
00080     static const D3D11_INPUT_ELEMENT_DESC vertexDesc[] =
00081     {
00082         { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00083     };
00084
00085     m_rasterizeDepthMeshVertexShader = DX::CreateVertexShader(
00086         device,
00087         g_RasterizeDepthMeshVS,
00088         _countof(g_RasterizeDepthMeshVS));
00089
00090     m_rasterizeDepthMeshInputLayout = DX::CreateInputLayout(
00091         device,
00092         vertexDesc,
00093         _countof(vertexDesc),
00094         g_RasterizeDepthMeshVS,
00095         _countof(g_RasterizeDepthMeshVS));
00096
00097     m_rasterizeDepthMeshPixelShader = DX::CreatePixelShader(
00098         device,
00099         g_RasterizeDepthMeshPS,
00100         _countof(g_RasterizeDepthMeshPS));
00101
00102     m_visualizeDepthMeshVertexShader = DX::CreateVertexShader(
00103         device,
00104         g_VisualizeDepthMeshVS,
00105         _countof(g_VisualizeDepthMeshVS));
00106
00107     m_visualizeDepthMeshInputLayout = DX::CreateInputLayout(
00108         device,
00109         vertexDesc,
00110         _countof(vertexDesc),
00111         g_VisualizeDepthMeshVS,
00112         _countof(g_VisualizeDepthMeshVS));
00113
00114     m_visualizeDepthMeshPixelShader = DX::CreatePixelShader(
00115         device,
00116         g_VisualizeDepthMeshPS,
00117         _countof(g_VisualizeDepthMeshPS));
00118
00119     m_rasterizeDepthMeshConstants = DX::CreateBuffer(
00120         device,
00121         sizeof(RasterizeDepthMeshConstants_Shader),
00122         nullptr,
00123         D3D11_BIND_CONSTANT_BUFFER);
00124
00125     m_visualizeDepthMeshConstants = DX::CreateBuffer(
00126         device,
00127         sizeof(VisualizeDepthMeshConstants_Shader),
00128         nullptr,
00129         D3D11_BIND_CONSTANT_BUFFER);
00130
00131     m_samplerState = DX::CreateSamplerState(device);
00132
00133     static const float4 quadVertices[] = {
00134         float4(-1.0f, +1.0f, 0.0f, 1.0f), // top left
00135         float4(+1.0f, +1.0f, 0.0f, 1.0f), // top right
00136         float4(-1.0f, -1.0f, 0.0f, 1.0f), // bottom left
00137
00138         float4(+1.0f, +1.0f, 0.0f, 1.0f), // top right
00139         float4(+1.0f, -1.0f, 0.0f, 1.0f), // bottom right
00140         float4(-1.0f, -1.0f, 0.0f, 1.0f), // bottom left
00141     };
00142
00143     m_vertexCount = _countof(quadVertices);
00144
00145     m_vertexBuffer = DX::CreateBuffer(
00146         device,
00147         sizeof(quadVertices),
00148         quadVertices,
00149         D3D11_BIND_VERTEX_BUFFER);
00150 }
00151
00152 void CameraStreamCoordinateMapper::GpuCoordinateMapper::ReleaseDeviceDependentResources()
00153 {
00154     m_rasterizeDepthMeshVertexShader = nullptr;
00155     m_rasterizeDepthMeshInputLayout = nullptr;
00156     m_rasterizeDepthMeshPixelShader = nullptr;
00157
00158     m_visualizeDepthMeshVertexShader = nullptr;
00159     m_visualizeDepthMeshInputLayout = nullptr;
00160     m_visualizeDepthMeshPixelShader = nullptr;
00161
00162     m_rasterizeDepthMeshConstants = nullptr;
00163     m_visualizeDepthMeshConstants = nullptr;
00164     m_vertexBuffer = nullptr;
00165     m_samplerState = nullptr;
00166 }
00167
00168 ////////////////////////////////////////////////////////////////////////////////
00169 // RunCoordinateMapping - executes the correlation algorithm for this set of frame data
00170 //
00171 // The inputs come from the "depth*", "source*", and "target*" parameters, output is written to the "targetImage*" parameters
00172 //
00173 // The core algorithm:
00174 // 1.) Read each point from the depth image and undistort + unprojects it into 3D space (using depthUnprojectionMap)
00175 // 2.) Transforms that 3D point into "source" and "target" camera space (using depthToSource and depthToTarget matrices)
00176 // 3.) Projects + distorts it into source camera 2D space (using sourceProjectionMatrix and sourceDistortionMap)
00177 //     to determine which pixel to sample from
00178 // 4.) Projects + distorts it into target camera 2D space (using targetProjectionMatrix and targetDistortionMap)
00179 //     to determine where the final pixel is rendered on screen.
00180 //
00181 // The most common scenario has "source" and "target" as the same camera (Color), but
00182 // the algorithm is generic to allow other scenarios.
00183
00184 void CameraStreamCoordinateMapper::GpuCoordinateMapper::RunCoordinateMapping(
00185     const RasterizedFrameBlob& frameBlob)
00186 {
00187     ID3D11DeviceContext* context = m_deviceResources->GetD3DDeviceContext();
00188
00189     const RasterizeDepthMeshConstants_Shader constants = GetRasterizeDepthMeshConstantsForShader(frameBlob);
00190
00191     context->UpdateSubresource(m_rasterizeDepthMeshConstants.Get(), 0, nullptr, &constants, 0, 0);
00192
00193     context->ClearRenderTargetView(frameBlob.targetImage.Get(), DirectX::Colors::Black);
00194     context->ClearDepthStencilView(frameBlob.targetRasterizedDepth.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
00195
00196     ////////////////////////////////////////////////////////////////////////////////
00197     // Input Assembler + Rasterizer
00198     const UINT stride = sizeof(float4);
00199     const UINT offset = 0;
00200     context->IASetVertexBuffers(0, 1, m_vertexBuffer.GetAddressOf(), &stride, &offset);
00201     context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00202     context->IASetInputLayout(m_rasterizeDepthMeshInputLayout.Get());
00203
00204     const D3D11_VIEWPORT viewport = CD3D11_VIEWPORT(
00205         0.0f,
00206         0.0f,
00207         static_cast<float>(frameBlob.targetIntrinsics.imageWidth),
00208         static_cast<float>(frameBlob.targetIntrinsics.imageHeight)
00209     );
00210
00211     context->RSSetViewports(1, &viewport);
00212
00213     ////////////////////////////////////////////////////////////////////////////////
00214     // Vertex Shader
00215     context->VSSetShader(m_rasterizeDepthMeshVertexShader.Get(), nullptr, 0);
00216
00217     ID3D11Buffer* vertexConstantBuffers[] = {
00218         m_rasterizeDepthMeshConstants.Get()
00219     };
00220
00221     context->VSSetConstantBuffers(0, 1, m_rasterizeDepthMeshConstants.GetAddressOf());
00222
00223     ID3D11ShaderResourceView* vertexShaderResources[] = {
00224         frameBlob.depthImage.Get(),           // Depth Texture
00225         frameBlob.depthUnprojectionMap.Get(), // Depth Unprojection Map
00226         frameBlob.sourceDistortionMap.Get(),  // Source Distortion Map
00227         frameBlob.targetDistortionMap.Get()   // Target Distortion Map
00228     };
00229
00230     context->VSSetShaderResources(0, _countof(vertexShaderResources), vertexShaderResources);
00231     context->VSSetSamplers(0, 1, m_samplerState.GetAddressOf());
00232
00233     ////////////////////////////////////////////////////////////////////////////////
00234     // Pixel Shader
00235     context->PSSetShader(m_rasterizeDepthMeshPixelShader.Get(), nullptr, 0);
00236
00237     ID3D11ShaderResourceView* pixelShaderResources[] = {
00238         frameBlob.sourceImage.Get() // Source Texture
00239     };
00240
00241     context->PSSetShaderResources(0, _countof(pixelShaderResources), pixelShaderResources);
00242     context->PSSetSamplers(0, 1, m_samplerState.GetAddressOf());
00243
00244     ////////////////////////////////////////////////////////////////////////////////
00245     // Output Merger
00246     ID3D11RenderTargetView* outputRenderTargets[] = {
00247         frameBlob.targetImage.Get() // Target Texture
00248     };
00249
00250     context->OMSetRenderTargets(_countof(outputRenderTargets), outputRenderTargets, frameBlob.targetRasterizedDepth.Get());
00251
00252     ////////////////////////////////////////////////////////////////////////////////
00253     // Render
00254     const uint32_t instanceCount = (frameBlob.depthIntrinsics.imageWidth - 1) * (frameBlob.depthIntrinsics.imageHeight - 1);
00255
00256     context->DrawInstanced(m_vertexCount, instanceCount, 0, 0);
00257
00258     ////////////////////////////////////////////////////////////////////////////////
00259     // Cleanup: Unbind resources that might be used in later passes
00260     decltype(outputRenderTargets) null_outputRenderTargets = { nullptr };
00261     context->OMSetRenderTargets(_countof(null_outputRenderTargets), null_outputRenderTargets, nullptr);
00262
00263     decltype(pixelShaderResources) null_pixelShaderResources = { nullptr };
00264     context->PSSetShaderResources(0, _countof(null_pixelShaderResources), null_pixelShaderResources);
00265
00266     decltype(vertexShaderResources) null_vertexShaderResources = { nullptr };
00267     context->VSSetShaderResources(0, _countof(null_vertexShaderResources), null_vertexShaderResources);
00268 }
00269
00270 ////////////////////////////////////////////////////////////////////////////////
00271 // VisualizeCoordinateMapping - executes the correlation algorithm for this set of frame data
00272 //   except visualized from another perspective, using depth information from the previous pass
00273 //   in order to occlude pixels that weren't visible from the original target camera's perspective
00274 //
00275 // The inputs come from the "depth*" and "target*" parameters inside of the rasterizedFrameBlob.
00276 // The output is written to the visualizeFrameBlob "renderTarget*" parameters
00277 //
00278 // The core algorithm for visualizing from alternate perspectives:
00279 // 1.) Read each point from the depth image and undistort + unprojects it into 3D space (using depthUnprojectionMap)
00280 // 2.) Transforms that 3D point into "target" camera space (using depthToTarget matrices)
00281 // 3.) Projects + distorts it into target camera 2D space (using targetProjectionMatrix and targetDistortionMap)
00282 //     to determine where the final pixel was rendered on screen (so we can sample the depth buffer in the pixel shader)
00283 // 4.) Compute the depth of this point in "target" camera space and store it in the vertex
00284 // 5.) Compute the position of the 3D point given the app provided camera/projection
00285
00286 void GpuCoordinateMapper::VisualizeCoordinateMapping(
00287     const RasterizedFrameBlob& rasterizedFrameBlob,
00288     const VisualizeFrameBlob& visualizeFrameBlob)
00289 {
00290     ID3D11DeviceContext* context = m_deviceResources->GetD3DDeviceContext();
00291
00292     const RasterizeDepthMeshConstants_Shader rasterizeConstants = GetRasterizeDepthMeshConstantsForShader(rasterizedFrameBlob);
00293     context->UpdateSubresource(m_rasterizeDepthMeshConstants.Get(), 0, nullptr, &rasterizeConstants, 0, 0);
00294
00295     const VisualizeDepthMeshConstants_Shader visualizeConstants = GetVisualizeDepthMeshConstantsForShader(visualizeFrameBlob);
00296     context->UpdateSubresource(m_visualizeDepthMeshConstants.Get(), 0, nullptr, &visualizeConstants, 0, 0);
00297
00298     context->ClearRenderTargetView(visualizeFrameBlob.renderTarget.Get(), DirectX::Colors::Black);
00299     context->ClearDepthStencilView(visualizeFrameBlob.renderTargetDepthBuffer.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
00300
00301     ////////////////////////////////////////////////////////////////////////////////
00302     // Input Assembler + Rasterizer
00303     const UINT stride = sizeof(float4);
00304     const UINT offset = 0;
00305     context->IASetVertexBuffers(0, 1, m_vertexBuffer.GetAddressOf(), &stride, &offset);
00306     context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00307     context->IASetInputLayout(m_rasterizeDepthMeshInputLayout.Get());
00308
00309     context->RSSetViewports(1, &visualizeFrameBlob.viewport);
00310
00311     ////////////////////////////////////////////////////////////////////////////////
00312     // Vertex Shader
00313     context->VSSetShader(m_visualizeDepthMeshVertexShader.Get(), nullptr, 0);
00314
00315     ID3D11Buffer* const vertexConstantBuffers[] = {
00316         m_rasterizeDepthMeshConstants.Get(),
00317         m_visualizeDepthMeshConstants.Get()
00318     };
00319
00320     context->VSSetConstantBuffers(0, _countof(vertexConstantBuffers), vertexConstantBuffers);
00321
00322     ID3D11ShaderResourceView* const vertexShaderResources[] = {
00323         rasterizedFrameBlob.depthImage.Get(),           // Depth Texture
00324         rasterizedFrameBlob.depthUnprojectionMap.Get(), // Depth Unprojection Map
00325         rasterizedFrameBlob.targetDistortionMap.Get()   // Target Distortion Map
00326     };
00327
00328     context->VSSetShaderResources(0, _countof(vertexShaderResources), vertexShaderResources);
00329     context->VSSetSamplers(0, 1, m_samplerState.GetAddressOf());
00330
00331     ////////////////////////////////////////////////////////////////////////////////
00332     // Pixel Shader
00333     context->PSSetShader(m_visualizeDepthMeshPixelShader.Get(), nullptr, 0);
00334
00335     ID3D11Buffer* const pixelConstantBuffers[] = {
00336         m_rasterizeDepthMeshConstants.Get()
00337     };
00338
00339     context->PSSetConstantBuffers(0, _countof(pixelConstantBuffers), pixelConstantBuffers);
00340
00341     ID3D11ShaderResourceView* const pixelShaderResources[] = {
00342         visualizeFrameBlob.targetImage.Get(),           // Target Texture
00343         visualizeFrameBlob.targetImageDepthBuffer.Get() // Target Depth Buffer
00344     };
00345
00346     context->PSSetShaderResources(0, _countof(pixelShaderResources), pixelShaderResources);
00347     context->PSSetSamplers(0, 1, m_samplerState.GetAddressOf());
00348
00349     ////////////////////////////////////////////////////////////////////////////////
00350     // Output Merger
00351     ID3D11RenderTargetView* const outputRenderTargets[] = {
00352         visualizeFrameBlob.renderTarget.Get()
00353     };
00354
00355     context->OMSetRenderTargets(_countof(outputRenderTargets), outputRenderTargets, visualizeFrameBlob.renderTargetDepthBuffer.Get());
00356
00357     ////////////////////////////////////////////////////////////////////////////////
00358     // Render
00359     const uint32_t instanceCount = (rasterizedFrameBlob.depthIntrinsics.imageWidth - 1) * (rasterizedFrameBlob.depthIntrinsics.imageHeight - 1);
00360
00361     context->DrawInstanced(m_vertexCount, instanceCount, 0, 0);
00362
00363     ////////////////////////////////////////////////////////////////////////////////
00364     // Cleanup: Unbind resources that might be used in later passes
00365     decltype(outputRenderTargets) null_outputRenderTargets = { nullptr };
00366     context->OMSetRenderTargets(_countof(null_outputRenderTargets), null_outputRenderTargets, nullptr);
00367
00368     decltype(pixelShaderResources) null_pixelShaderResources = { nullptr };
00369     context->PSSetShaderResources(0, _countof(null_pixelShaderResources), null_pixelShaderResources);
00370
00371     decltype(vertexShaderResources) null_vertexShaderResources = { nullptr };
00372     context->VSSetShaderResources(0, _countof(null_vertexShaderResources), null_vertexShaderResources);
00373 }
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

_RPC_CLIENT Member List

This is the complete list of members for _RPC_CLIENT, including all inherited members.
RpcClient _RPC_CLIENT
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CBufferPacket Member List

This is the complete list of members for CBufferPacket, including all inherited members.
_buffers | CBufferPacket | [private]
_cRef | CBufferPacket | [private]
AddBuffer(IMediaBufferWrapper *pBuffer) | CBufferPacket |
CBufferPacket(void) | CBufferPacket | [protected]
Clear() | CBufferPacket |
Container typedef | CBufferPacket |
CopyTo(DWORD nOffset, DWORD cbSize, _In_reads_bytes_(cbSize) void *pDest, _Out_ DWORD *pcbCopied) | CBufferPacket |
CreateInstance(IBufferPacket **ppBufferPackage) | CBufferPacket | [static]
FromMFSample(IMFSample *pSample, IBufferPacket **ppBufferPackage) | CBufferPacket | [static]
GetEnumerator(_Out_ IBufferEnumerator **ppEnumerator) | CBufferPacket |
GetTotalLength(_Out_ DWORD *pcbTotalLength) | CBufferPacket |
IFACEMETHOD_(ULONG, AddRef)() | CBufferPacket |
IFACEMETHOD_(ULONG, Release)() | CBufferPacket |
IFACEMETHOD_(size_t, GetBufferCount)() const | CBufferPacket |
InsertBuffer(unsigned int nIndex, IMediaBufferWrapper *pBuffer) | CBufferPacket |
Iterator typedef | CBufferPacket |
MoveLeft(DWORD cbSize, _Out_writes_bytes_(cbSize) void *pDest) | CBufferPacket |
QueryInterface(REFIID riid, void **ppv) | CBufferPacket |
RemoveBuffer(unsigned int nIndex, IMediaBufferWrapper **ppBuffer) | CBufferPacket |
ToMFSample(IMFSample **ppSample) | CBufferPacket |
TrimLeft(DWORD cbSize) | CBufferPacket |
~CBufferPacket(void) | CBufferPacket | [protected]
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicFaceDetection/cppwinrt/SampleConfiguration.cpp Source File

  • BasicFaceDetection
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation::Collections;
00019 using namespace winrt::Windows::Graphics::Imaging;
00020 using namespace winrt::Windows::Media::FaceAnalysis;
00021 using namespace winrt::Windows::UI::Xaml;
00022 using namespace winrt::Windows::UI::Xaml::Controls;
00023 using namespace winrt::Windows::UI::Xaml::Media::Imaging;
00024 using namespace winrt::SDKTemplate;
00025
00026 hstring implementation::MainPage::FEATURE_NAME()
00027 {
00028     return L"Face detection C++/WinRT sample";
00029 }
00030
00031 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00032 {
00033     Scenario{ L"Detect Faces in Photos", xaml_typename<SDKTemplate::Scenario1_DetectInPhoto>() },
00034     Scenario{ L"Detect Faces in Webcam", xaml_typename<SDKTemplate::Scenario2_DetectInWebcam>() },
00035 });
00036
00037 // Rescale the size and position of the face highlight
00038 // to account for the difference between the size of the image and
00039 // the canvas.
00040 void ApplyScale(FrameworkElement const& box, double widthScale, double heightScale)
00041 {
00042     // We saved the original size of the face box in the element's Tag field.
00043     BitmapBounds faceBox = unbox_value<BitmapBounds>(box.Tag());
00044     box.Width(faceBox.Width * widthScale);
00045     box.Height(faceBox.Height * heightScale);
00046     box.Margin({ faceBox.X * widthScale, faceBox.Y * heightScale, 0, 0 });
00047 }
00048
00049 void SampleHelpers::HighlightFaces(
00050     WriteableBitmap const& displaySource,
00051     IVector<DetectedFace> const& foundFaces,
00052     Canvas const& canvas,
00053     DataTemplate const& dataTemplate)
00054 {
00055
00056     double widthScale = canvas.ActualWidth() / displaySource.PixelWidth();
00057     double heightScale = canvas.ActualHeight() / displaySource.PixelHeight();
00058
00059     for (DetectedFace face : foundFaces)
00060     {
00061         // Create an element for displaying the face box but since we're using a Canvas
00062         // we must scale the elements according to the image's actual size.
00063         // The original FaceBox values are saved in the element's Tag field so we can update the
00064         // boxes when the Canvas is resized.
00065         FrameworkElement box = dataTemplate.LoadContent().as<FrameworkElement>();
00066         box.Tag(box_value(face.FaceBox()));
00067         ApplyScale(box, widthScale, heightScale);
00068         canvas.Children().Append(box);
00069     }
00070
00071     hstring message;
00072     int32_t faceCount = foundFaces.Size();
00073     if (faceCount == 0)
00074     {
00075         message = L"Didn't find any human faces in the image";
00076     }
00077     else if (faceCount == 1)
00078     {
00079         message = L"Found a human face in the image";
00080     }
00081     else
00082     {
00083         message = L"Found " + to_hstring(faceCount) + L" human faces in the image";
00084     }
00085
00086     MainPage::Current().NotifyUser(message, NotifyType::StatusMessage);
00087
00088 }
00089
00090 void SampleHelpers::RepositionFaces(WriteableBitmap const& displaySource, Canvas const& canvas)
00091 {
00092     double widthScale = canvas.ActualWidth() / displaySource.PixelWidth();
00093     double heightScale = canvas.ActualHeight() / displaySource.PixelHeight();
00094
00095     for (UIElement element : canvas.Children())
00096     {
00097         ApplyScale(element.as<FrameworkElement>(), widthScale, heightScale);
00098     }
00099 }
Generated on Fri Nov 15 2024 22:17:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCorrelation/cpp/PoseTrackingPreview/PoseTrackingFrame.h Source File

  • CameraStreamCorrelation
  • cpp
  • PoseTrackingPreview

PoseTrackingFrame.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "MFPoseTrackingFrame.h"
00014
00015 namespace WindowsPreview {
00016     namespace Media {
00017         namespace Capture {
00018             namespace Frames {
00019
00020                 public enum class TrackingStatus : int32_t {
00021                     NotTracked = static_cast<int32_t>(MFPoseTrackingPreview::TrackingStatus::NotTracked),
00022                     Inferred = static_cast<int32_t>(MFPoseTrackingPreview::TrackingStatus::Inferred),
00023                     Tracked = static_cast<int32_t>(MFPoseTrackingPreview::TrackingStatus::Tracked)
00024                 };
00025
00026                 public value struct TrackedPose {
00027                     TrackingStatus PositionStatus;
00028                     Windows::Foundation::Numerics::float3 Position;
00029                     TrackingStatus OrientationStatus;
00030                     Windows::Foundation::Numerics::quaternion Orientation;
00031                 };
00032
00033                 // When PoseSet field of PoseTrackingEntity is set to PoseSet_BodyTracking, the
00034                 // Poses of the PoseTrackingEntity follow the order defined by this enum
00035                 public enum class BodyPart : int32_t {
00036                     SpineBase     = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::SpineBase),
00037                     SpineMid      = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::SpineMid),
00038                     Neck          = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::Neck),
00039                     Head          = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::Head),
00040                     ShoulderLeft  = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::ShoulderLeft),
00041                     ElbowLeft     = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::ElbowLeft),
00042                     WristLeft     = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::WristLeft),
00043                     HandLeft      = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::HandLeft),
00044                     ShoulderRight = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::ShoulderRight),
00045                     ElbowRight    = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::ElbowRight),
00046                     WristRight    = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::WristRight),
00047                     HandRight     = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::HandRight),
00048                     HipLeft       = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::HipLeft),
00049                     KneeLeft      = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::KneeLeft),
00050                     AnkleLeft     = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::AnkleLeft),
00051                     FootLeft      = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::FootLeft),
00052                     HipRight      = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::HipRight),
00053                     KneeRight     = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::KneeRight),
00054                     AnkleRight    = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::AnkleRight),
00055                     FootRight     = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::FootRight),
00056                     SpineShoulder = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::SpineShoulder),
00057                     HandTipLeft   = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::HandTipLeft),
00058                     ThumbLeft     = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::ThumbLeft),
00059                     HandTipRight  = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::HandTipRight),
00060                     ThumbRight    = static_cast<int32_t>(MFPoseTrackingPreview::BodyPart::ThumbRight)
00061                 };
00062
00063                 public ref class KnownPoseTrackingPointSets sealed
00064                 {
00065                 public:
00066                     static property Platform::Guid BodyTrackingPointSet
00067                     {
00068                         Platform::Guid get() { return MFPoseTrackingPreview::PoseSet_BodyTracking; }
00069                     }
00070
00071                     static property Platform::Guid HandTrackingPointSet
00072                     {
00073                         Platform::Guid get() { return MFPoseTrackingPreview::PoseSet_HandTracking; }
00074                     }
00075
00076                 };
00077
00078                 public ref class PoseTrackingEntity sealed
00079                 {
00080                 public:
00081                     property Platform::Guid EntityId
00082                     {
00083                         Platform::Guid get() { return _entityId; }
00084                     }
00085                     property Platform::Guid PoseSetId
00086                     {
00087                         Platform::Guid get() { return _poseSetId; }
00088                     }
00089                     property unsigned int PosesCount
00090                     {
00091                         unsigned int get() { return _posesCount; }
00092                     }
00093                     property bool IsTracked
00094                     {
00095                         bool get() { return _isTracked; }
00096                     }
00097
00098                     // Fills the poses array parameter with the Poses contained in the entity
00099                     // The array must be large enough, i.e. contain at least PosesCount elements
00100                     // Exactly PosesCount elements are written; the remaining of the array is unchanged
00101                     void GetPoses(_Out_ Platform::WriteOnlyArray<TrackedPose>^ poses);
00102
00103                     // Fills the poses array parameter with the Poses contained in the entity
00104                     // and at the positions indicated by the indices parameter
00105                     // poses array must be at least as large as indices array
00106                     // Exactly indices->Length elements are written; the rest of the array is unchanged
00107                     void GetPoses(_In_ const Platform::Array<unsigned int>^ indices, _Out_ Platform::WriteOnlyArray<TrackedPose>^ poses);
00108
00109                     // Retrieves the location of Provider specific entity data in the frame buffer
00110                     BufferView^ GetCustomData();
00111
00112                 internal:
00113                     PoseTrackingEntity(_In_ Windows::Storage::Streams::IBuffer^ frameBuffer, _In_ unsigned int entityIndex, _In_ const MFPoseTrackingPreview::PoseTrackingEntityData* entityHeader);
00114
00115                 private:
00116                     // Cached values for frequently access data
00117                     Platform::Guid _entityId;
00118                     Platform::Guid _poseSetId;
00119                     unsigned int _posesCount;
00120                     size_t _dataSize;
00121                     bool _isTracked;
00122
00123                     // Access to the full buffer
00124                     Windows::Storage::Streams::IBuffer^ _frameBuffer;
00125                     unsigned int _entityIndex;
00126                 };
00127
00128                 ref class PoseTrackingFrame;
00129
00130                 public enum class PoseTrackingFrameCreationStatus
00131                 {
00132                     Success, // The buffer could be correctly accessed and interpreted as a Pose Tracking Frame
00133                     NotAPerceptionMediaType, // The Media Type associated to the MediaFrameReference was not Perception
00134                     NotAPoseTrackingFrame,  // The Media Subtype associated to the MediaFrameReference was not Pose Tracking
00135                     FrameBufferReleased, // The Buffer associated to the MediaFrameReference has already been already released
00136                     InvalidFormat // There was a mistmatch between expected and real value of some internal fields of the buffer
00137                 };
00138
00139                 public ref class PoseTrackingFrameCreationResult sealed
00140                 {
00141                 public:
00142                     property PoseTrackingFrame^ Frame
00143                     {
00144                         PoseTrackingFrame^ get() { return _frame; }
00145                     }
00146                     property PoseTrackingFrameCreationStatus Status
00147                     {
00148                         PoseTrackingFrameCreationStatus get() { return _status; }
00149                     }
00150                 internal:
00151                     PoseTrackingFrameCreationResult(_In_opt_ PoseTrackingFrame^ frame, _In_ PoseTrackingFrameCreationStatus status)
00152                         : _frame(frame), _status(status)
00153                     {
00154                     }
00155                 private:
00156                     PoseTrackingFrame^ _frame;
00157                     PoseTrackingFrameCreationStatus _status;
00158                 };
00159
00160                 public ref class PoseTrackingFrame sealed
00161                 {
00162                 public:
00163                     static property Platform::Guid PoseTrackingSubtype
00164                     {
00165                         Platform::Guid get()
00166                         {
00167                             return MFPoseTrackingPreview::MFPerceptionFormat_PoseTracking;
00168                         }
00169                     }
00170
00171                     property Windows::Media::Capture::Frames::MediaFrameReference^ MediaFrameReference
00172                     {
00173                         Windows::Media::Capture::Frames::MediaFrameReference^ get() { return _mediaFrameReference; }
00174                     }
00175
00176                     property Windows::Foundation::Collections::IVectorView<PoseTrackingEntity^>^ Entities
00177                     {
00178                         Windows::Foundation::Collections::IVectorView<PoseTrackingEntity^>^ get() { return _entities; }
00179                     }
00180
00181                     property Platform::Guid CustomDataType
00182                     {
00183                         Platform::Guid get() { return _customDataType; }
00184                     }
00185
00186                     // Creates a PoseTrackingFrame from the MediaFrameReference
00187                     // If the MediaFrameReference does not contain Perception / PoseTracking data, the returned value is nullptr
00188                     static PoseTrackingFrameCreationResult^ Create(_In_ Windows::Media::Capture::Frames::MediaFrameReference^ mediaFrameReference);
00189
00190                     // Retrieves the location of Provider specific frame data in the frame buffer
00191                     BufferView^ GetCustomData();
00192
00193                 private:
00194                     Windows::Media::Capture::Frames::MediaFrameReference^ _mediaFrameReference;
00195                     Windows::Storage::Streams::IBuffer^ _frameBuffer;
00196                     Windows::Foundation::Collections::IVectorView<PoseTrackingEntity^>^ _entities;
00197                     Platform::Guid _customDataType;
00198
00199                     PoseTrackingFrame(Windows::Media::Capture::Frames::MediaFrameReference^ mediaFrameReference,
00200                         _In_ REFIID customDataType,
00201                         _In_ Windows::Storage::Streams::IBuffer^ frameBuffer,
00202                         _In_ Windows::Foundation::Collections::IVectorView<PoseTrackingEntity^>^ entities);
00203                 };
00204             }
00205         }
00206     }
00207 }
Generated on Fri Nov 15 2024 22:18:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/TargetTexture.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

TargetTexture.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // TargetTexture:
00015 // This is a helper class to procedurally generate textures for game
00016 // targets. There are two versions of the textures, one when it is
00017 // hit and the other is when it is not.
00018 // The class creates the necessary resources to draw the texture into
00019 // an off screen resource at initialization time.
00020
00021 class TargetTexture
00022 {
00023 public:
00024     TargetTexture(
00025         _In_ winrt::com_ptr<ID3D11Device3> d3dDevice,
00026         _In_ ID2D1Factory1* d2dFactory,
00027         _In_ IDWriteFactory1* dwriteFactory,
00028         _In_ ID2D1DeviceContext* d2dContext
00029         );
00030
00031     void CreateTextureResourceView(
00032         _In_ winrt::hstring const& name,
00033         _Out_ ID3D11ShaderResourceView** textureResourceView
00034         );
00035
00036     void CreateHitTextureResourceView(
00037         _In_ winrt::hstring const& name,
00038         _Out_ ID3D11ShaderResourceView** textureResourceView
00039         );
00040
00041 private:
00042     winrt::com_ptr<ID3D11Device1>           m_d3dDevice;
00043     winrt::com_ptr<ID2D1Factory1>           m_d2dFactory;
00044     winrt::com_ptr<ID2D1DeviceContext>      m_d2dContext;
00045     winrt::com_ptr<IDWriteFactory1>         m_dwriteFactory;
00046
00047     winrt::com_ptr<ID2D1SolidColorBrush>    m_redBrush;
00048     winrt::com_ptr<ID2D1SolidColorBrush>    m_blueBrush;
00049     winrt::com_ptr<ID2D1SolidColorBrush>    m_greenBrush;
00050     winrt::com_ptr<ID2D1SolidColorBrush>    m_whiteBrush;
00051     winrt::com_ptr<ID2D1SolidColorBrush>    m_blackBrush;
00052     winrt::com_ptr<ID2D1SolidColorBrush>    m_yellowBrush;
00053     winrt::com_ptr<ID2D1SolidColorBrush>    m_clearBrush;
00054
00055     winrt::com_ptr<ID2D1EllipseGeometry>    m_circleGeometry1;
00056     winrt::com_ptr<ID2D1EllipseGeometry>    m_circleGeometry2;
00057     winrt::com_ptr<ID2D1EllipseGeometry>    m_circleGeometry3;
00058     winrt::com_ptr<ID2D1EllipseGeometry>    m_circleGeometry4;
00059     winrt::com_ptr<ID2D1EllipseGeometry>    m_circleGeometry5;
00060
00061     winrt::com_ptr<IDWriteTextFormat>       m_textFormat;
00062 };
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OrientationSensor/cpp/Scenario0_Choose.xaml.cpp Source File

  • OrientationSensor
  • cpp

Scenario0_Choose.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario0_Choose.xaml.cpp
00014 // Implementation of the Scenario0_Choose class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario0_Choose.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Windows::Devices::Sensors;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 void Scenario0_Choose::AddReadingType(SensorReadingType readingType)
00029 {
00030     auto item = ref new ComboBoxItem();
00031     item->Content = readingType.ToString();
00032     item->Tag = readingType;
00033     ReadingTypeComboBox->Items->Append(item);
00034     if (readingType == rootPage->SensorReadingType)
00035     {
00036         ReadingTypeComboBox->SelectedItem = item;
00037     }
00038 }
00039
00040 void Scenario0_Choose::AddOptimizationGoal(SensorOptimizationGoal optimizationGoal)
00041 {
00042     auto item = ref new ComboBoxItem();
00043     item->Content = optimizationGoal.ToString();
00044     item->Tag = optimizationGoal;
00045     OptimizationGoalComboBox->Items->Append(item);
00046     if (optimizationGoal == rootPage->SensorOptimizationGoal)
00047     {
00048         OptimizationGoalComboBox->SelectedItem = item;
00049     }
00050 }
00051
00052 Scenario0_Choose::Scenario0_Choose()
00053 {
00054     InitializeComponent();
00055
00056     AddReadingType(SensorReadingType::Absolute);
00057     AddReadingType(SensorReadingType::Relative);
00058
00059     AddOptimizationGoal(SensorOptimizationGoal::Precision);
00060     AddOptimizationGoal(SensorOptimizationGoal::PowerEfficiency);
00061 }
00062
00063 void Scenario0_Choose::OnNavigatedFrom(NavigationEventArgs^ e)
00064 {
00065     auto item = safe_cast<ComboBoxItem^>(ReadingTypeComboBox->SelectedItem);
00066     rootPage->SensorReadingType = safe_cast<SensorReadingType>(item->Tag);
00067
00068     item = safe_cast<ComboBoxItem^>(OptimizationGoalComboBox->SelectedItem);
00069     rootPage->SensorOptimizationGoal = safe_cast<SensorOptimizationGoal>(item->Tag);
00070 }
Generated on Fri Nov 15 2024 22:17:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Package/cpp/pch.h Source File

  • Package
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cpp/4-XAMLManipulations.xaml.h Source File

  • BasicInput
  • cpp

4-XAMLManipulations.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "4-XAMLManipulations.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario4 sealed
00024     {
00025     public:
00026         Scenario4();
00027
00028     private:
00029
00030         void InitManipulationTransforms();
00031         void ManipulateMe_ManipulationStarted(Platform::Object^ sender, Windows::UI::Xaml::Input::ManipulationStartedRoutedEventArgs^ e);
00032         void ManipulateMe_ManipulationDelta(Platform::Object^ sender, Windows::UI::Xaml::Input::ManipulationDeltaRoutedEventArgs^ e);
00033         void ManipulateMe_ManipulationInertiaStarting(Platform::Object^ sender, Windows::UI::Xaml::Input::ManipulationInertiaStartingRoutedEventArgs^ e);
00034         void ManipulateMe_ManipulationCompleted(Platform::Object^ sender, Windows::UI::Xaml::Input::ManipulationCompletedRoutedEventArgs^ e);
00035         void movementAxis_Changed(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00036         void InertiaSwitch_Toggled(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         void InitOptions();
00038         void resetButton_Pressed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039
00040         MainPage^ rootPage = MainPage::Current;
00041         Windows::UI::Xaml::Media::TransformGroup^ transforms;
00042         Windows::UI::Xaml::Media::MatrixTransform^ previousTransform;
00043         Windows::UI::Xaml::Media::CompositeTransform^ deltaTransform;
00044         bool forceManipulationsToEnd;
00045     };
00046 }
Generated on Fri Nov 15 2024 22:18:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_DataEvents Member List

This is the complete list of members for Scenario1_DataEvents, including all inherited members.
_desiredReportInterval | Scenario1_DataEvents | [private]
_gyrometer | Scenario1_DataEvents | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_DataEvents | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario1_DataEvents | [inline, protected]
ReadingChanged(object sender, GyrometerReadingChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
rootPage | Scenario1_DataEvents | [private]
Scenario1_DataEvents() | Scenario1_DataEvents | [inline]
ScenarioDisable(object sender, RoutedEventArgs e) | Scenario1_DataEvents | [inline, private]
ScenarioEnable(object sender, RoutedEventArgs e) | Scenario1_DataEvents | [inline, private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks/Common/RelayCommand.cpp Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks
  • Common

RelayCommand.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "RelayCommand.h"
00013
00014 using namespace AdventureWorks;
00015
00016 using namespace Windows::Foundation;
00017
00018 /// <summary>
00019 /// Determines whether this <see cref="RelayCommand"/> can execute in its current state.
00020 /// </summary>
00021 /// <param name="parameter">
00022 /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
00023 /// </param>
00024 /// <returns>true if this command can be executed; otherwise, false.</returns>
00025 bool RelayCommand::CanExecute(Object^ parameter)
00026 {
00027     return (_canExecuteCallback)(parameter);
00028 }
00029
00030 /// <summary>
00031 /// Executes the <see cref="RelayCommand"/> on the current command target.
00032 /// </summary>
00033 /// <param name="parameter">
00034 /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
00035 /// </param>
00036 void RelayCommand::Execute(Object^ parameter)
00037 {
00038     (_executeCallback)(parameter);
00039 }
00040
00041 /// <summary>
00042 /// Method used to raise the <see cref="CanExecuteChanged"/> event
00043 /// to indicate that the return value of the <see cref="CanExecute"/>
00044 /// method has changed.
00045 /// </summary>
00046 void RelayCommand::RaiseCanExecuteChanged()
00047 {
00048     CanExecuteChanged(this, nullptr);
00049 }
00050
00051 /// <summary>
00052 /// RelayCommand Class Destructor.
00053 /// </summary>
00054 RelayCommand::~RelayCommand()
00055 {
00056     _canExecuteCallback = nullptr;
00057     _executeCallback = nullptr;
00058 };
00059
00060 /// <summary>
00061 /// Creates a new command that can always execute.
00062 /// </summary>
00063 /// <param name="canExecuteCallback">The execution status logic.</param>
00064 /// <param name="executeCallback">The execution logic.</param>
00065 RelayCommand::RelayCommand(std::function<bool(Platform::Object^)> canExecuteCallback,
00066     std::function<void(Platform::Object^)> executeCallback) :
00067     _canExecuteCallback(canExecuteCallback),
00068     _executeCallback(executeCallback)
00069 {
00070 }
Generated on Fri Nov 15 2024 22:18:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/SampleOverlay.h Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

SampleOverlay.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "DirectXHelper.h"
00015 #include "DeviceResources.h"
00016
00017 // This class is responsible for initializing and rendering the title overlay visible
00018 // at the top of the DirectX SDK samples.
00019 namespace CustomVertexShader
00020 {
00021     class SampleOverlay
00022     {
00023     public:
00024         SampleOverlay(const std::shared_ptr<DX::DeviceResources>& deviceResources, const std::wstring& caption);
00025         void CreateDeviceDependentResources();
00026         void CreateWindowSizeDependentResources();
00027         void ReleaseDeviceDependentResources();
00028         void Render();
00029         float GetTitleHeightInDips();
00030
00031     private:
00032         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00033
00034         Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>    m_whiteBrush;
00035         Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock>  m_stateBlock;
00036
00037         Microsoft::WRL::ComPtr<ID2D1Bitmap>             m_logoBitmap;
00038         Microsoft::WRL::ComPtr<IDWriteTextLayout>       m_textLayout;
00039
00040         UINT                                            m_idIncrement;
00041         bool                                            m_drawOverlay;
00042         std::wstring                                    m_caption;
00043         float                                           m_padding;
00044         float                                           m_textVerticalOffset;
00045         D2D1_SIZE_F                                     m_logoSize;
00046         float                                           m_overlayWidth;
00047     };
00048 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cs/Scenario_ContinuousRecognitionSRGSGrammar.xaml.cs Source File

  • SpeechRecognitionAndSynthesis
  • cs

Scenario_ContinuousRecognitionSRGSGrammar.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Threading.Tasks;
00016 using Windows.ApplicationModel;
00017 using Windows.ApplicationModel.Resources.Core;
00018 using Windows.Globalization;
00019 using Windows.Media.SpeechRecognition;
00020 using Windows.Storage;
00021 using Windows.UI;
00022 using Windows.UI.Core;
00023 using Windows.UI.Xaml;
00024 using Windows.UI.Xaml.Controls;
00025 using Windows.UI.Xaml.Media;
00026 using Windows.UI.Xaml.Navigation;
00027
00028 namespace SDKTemplate
00029 {
00030     public sealed partial class Scenario_ContinuousRecognitionSRGSGrammar : Page
00031     {
00032         // Reference to the main sample page in order to post status messages.
00033         private MainPage rootPage;
00034
00035         /// <summary>
00036         /// the HResult 0x8004503a typically represents the case where a recognizer for a particular language cannot
00037         /// be found. This may occur if the language is installed, but the speech pack for that language is not.
00038         /// See Settings -> Time & Language -> Region & Language -> *Language* -> Options -> Speech Language Options.
00039         /// </summary>
00040         private static uint HResultRecognizerNotFound = 0x8004503a;
00041
00042         // The speech recognizer used throughout this sample.
00043         private SpeechRecognizer speechRecognizer;
00044
00045         private ResourceContext speechContext;
00046         private ResourceMap speechResourceMap;
00047
00048         private bool isPopulatingLanguages = false;
00049
00050         private Dictionary<string, Color> colorLookup = new Dictionary<string, Color>
00051         {
00052             { "COLOR_RED",   Colors.Red },   {"COLOR_BLUE",  Colors.Blue },  {"COLOR_BLACK",  Colors.Black},
00053             { "COLOR_BROWN", Colors.Brown},  {"COLOR_PURPLE",Colors.Purple}, {"COLOR_GREEN",  Colors.Green},
00054             { "COLOR_YELLOW",Colors.Yellow}, {"COLOR_CYAN",  Colors.Cyan},   {"COLOR_MAGENTA",Colors.Magenta},
00055             { "COLOR_ORANGE",Colors.Orange}, {"COLOR_GRAY",  Colors.Gray},   {"COLOR_WHITE",  Colors.White}
00056         };
00057
00058         public Scenario_ContinuousRecognitionSRGSGrammar()
00059         {
00060             InitializeComponent();
00061         }
00062
00063         /// <summary>
00064         /// Upon entering the scenario, ensure that we have permissions to use the Microphone. This may entail popping up
00065         /// a dialog to the user on Desktop systems. Only enable functionality once we've gained that permission in order to
00066         /// prevent errors from occurring when using the SpeechRecognizer. If speech is not a primary input mechanism, developers
00067         /// should consider disabling appropriate parts of the UI if the user does not have a recording device, or does not allow
00068         /// audio input.
00069         /// </summary>
00070         /// <param name="e">Unused navigation parameters</param>
00071         protected async override void OnNavigatedTo(NavigationEventArgs e)
00072         {
00073             rootPage = MainPage.Current;
00074
00075             // Prompt the user for permission to access the microphone. This request will only happen
00076             // once, it will not re-prompt if the user rejects the permission.
00077             bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission();
00078             if (permissionGained)
00079             {
00080                 btnContinuousRecognize.IsEnabled = true;
00081
00082                 Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage;
00083                 string langTag = speechLanguage.LanguageTag;
00084                 speechContext = ResourceContext.GetForCurrentView();
00085                 speechContext.Languages = new string[] { langTag };
00086
00087                 speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources");
00088
00089                 PopulateLanguageDropdown();
00090
00091                 // Initialize the recognizer. Since the recognizer is disposed on scenario exit, we need to make sure we re-initialize it on scenario
00092                 // entrance, as the xaml page may not get destroyed between openings of the scenario.
00093                 await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage);
00094             }
00095             else
00096             {
00097                 resultTextBlock.Text = "Permission to access capture resources was not given by the user, reset the application setting in Settings->Privacy->Microphone.";
00098                 btnContinuousRecognize.IsEnabled = false;
00099                 cbLanguageSelection.IsEnabled = false;
00100             }
00101         }
00102
00103         /// <summary>
00104         /// Look up the supported languages for this speech recognition scenario,
00105         /// that are installed on this machine, and populate a dropdown with a list.
00106         /// </summary>
00107         private void PopulateLanguageDropdown()
00108         {
00109             // disable the callback so we don't accidentally trigger initialization of the recognizer
00110             // while initialization is already in progress.
00111             isPopulatingLanguages = true;
00112
00113             Language defaultLanguage = SpeechRecognizer.SystemSpeechLanguage;
00114             IEnumerable<Language> supportedLanguages = SpeechRecognizer.SupportedGrammarLanguages;
00115             foreach (Language lang in supportedLanguages)
00116             {
00117                 ComboBoxItem item = new ComboBoxItem();
00118                 item.Tag = lang;
00119                 item.Content = lang.DisplayName;
00120
00121                 cbLanguageSelection.Items.Add(item);
00122                 if (lang.LanguageTag == defaultLanguage.LanguageTag)
00123                 {
00124                     item.IsSelected = true;
00125                     cbLanguageSelection.SelectedItem = item;
00126                 }
00127             }
00128             isPopulatingLanguages = false;
00129         }
00130
00131         /// <summary>
00132         /// When a user changes the speech recognition language, trigger re-initialization of the
00133         /// speech engine with that language, and change any speech-specific UI assets.
00134         /// </summary>
00135         /// <param name="sender">Ignored</param>
00136         /// <param name="e">Ignored</param>
00137         private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
00138         {
00139             if (isPopulatingLanguages)
00140             {
00141                 return;
00142             }
00143
00144             btnContinuousRecognize.IsEnabled = false;
00145             ComboBoxItem item = (ComboBoxItem)(cbLanguageSelection.SelectedItem);
00146             Language newLanguage = (Language)item.Tag;
00147             if (speechRecognizer != null)
00148             {
00149                 if (speechRecognizer.CurrentLanguage == newLanguage)
00150                 {
00151                     return;
00152                 }
00153             }
00154
00155             // trigger cleanup and re-initialization of speech.
00156             try
00157             {
00158                 // update the context for resource lookup
00159                 speechContext.Languages = new string[] { newLanguage.LanguageTag };
00160
00161                 await InitializeRecognizer(newLanguage);
00162             }
00163             catch (Exception exception)
00164             {
00165                 var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception");
00166                 await messageDialog.ShowAsync();
00167             }
00168             btnContinuousRecognize.IsEnabled = true;
00169         }
00170
00171         /// <summary>
00172         /// Upon leaving, clean up the speech recognizer. Ensure we aren't still listening, and disable the event
00173         /// handlers to prevent leaks.
00174         /// </summary>
00175         /// <param name="e">Unused navigation parameters.</param>
00176         protected async override void OnNavigatedFrom(NavigationEventArgs e)
00177         {
00178             if (speechRecognizer != null)
00179             {
00180                 if (speechRecognizer.State != SpeechRecognizerState.Idle)
00181                 {
00182                     await speechRecognizer.ContinuousRecognitionSession.CancelAsync();
00183                 }
00184
00185                 speechRecognizer.ContinuousRecognitionSession.Completed -= ContinuousRecognitionSession_Completed;
00186                 speechRecognizer.ContinuousRecognitionSession.ResultGenerated -= ContinuousRecognitionSession_ResultGenerated;
00187                 speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
00188
00189                 this.speechRecognizer.Dispose();
00190                 this.speechRecognizer = null;
00191             }
00192         }
00193
00194         /// <summary>
00195         /// Initialize Speech Recognizer and compile constraints.
00196         /// </summary>
00197         /// <param name="recognizerLanguage">Language to use for the speech recognizer</param>
00198         /// <returns>Awaitable task.</returns>
00199         private async Task InitializeRecognizer(Language recognizerLanguage)
00200         {
00201             if (speechRecognizer != null)
00202             {
00203                 // cleanup prior to re-initializing this scenario.
00204                 speechRecognizer.ContinuousRecognitionSession.Completed -= ContinuousRecognitionSession_Completed;
00205                 speechRecognizer.ContinuousRecognitionSession.ResultGenerated -= ContinuousRecognitionSession_ResultGenerated;
00206                 speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged;
00207
00208                 this.speechRecognizer.Dispose();
00209                 this.speechRecognizer = null;
00210             }
00211
00212             try {
00213                 // Initialize the SRGS-compliant XML file.
00214                 // For more information about grammars for Windows apps and how to
00215                 // define and use SRGS-compliant grammars in your app, see
00216                 // https://msdn.microsoft.com/en-us/library/dn596121.aspx
00217
00218                 // determine the language code being used.
00219                 string languageTag = recognizerLanguage.LanguageTag;
00220                 string fileName = String.Format("SRGS\\{0}\\SRGSColors.xml", languageTag);
00221                 StorageFile grammarContentFile = await Package.Current.InstalledLocation.GetFileAsync(fileName);
00222
00223                 resultTextBlock.Text = speechResourceMap.GetValue("SRGSHelpText", speechContext).ValueAsString;
00224
00225                 // Initialize the SpeechRecognizer and add the grammar.
00226                 speechRecognizer = new SpeechRecognizer(recognizerLanguage);
00227
00228                 // Provide feedback to the user about the state of the recognizer. This can be used to provide
00229                 // visual feedback to help the user understand whether they're being heard.
00230                 speechRecognizer.StateChanged += SpeechRecognizer_StateChanged;
00231
00232                 SpeechRecognitionGrammarFileConstraint grammarConstraint = new SpeechRecognitionGrammarFileConstraint(grammarContentFile);
00233                 speechRecognizer.Constraints.Add(grammarConstraint);
00234                 SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync();
00235
00236                 // Check to make sure that the constraints were in a proper format and the recognizer was able to compile them.
00237                 if (compilationResult.Status != SpeechRecognitionResultStatus.Success)
00238                 {
00239                     // Disable the recognition button.
00240                     btnContinuousRecognize.IsEnabled = false;
00241
00242                     // Let the user know that the grammar didn't compile properly.
00243                     resultTextBlock.Text = "Unable to compile grammar.";
00244                 }
00245                 else
00246                 {
00247
00248                     // Set EndSilenceTimeout to give users more time to complete speaking a phrase.
00249                     speechRecognizer.Timeouts.EndSilenceTimeout = TimeSpan.FromSeconds(1.2);
00250
00251                     // Handle continuous recognition events. Completed fires when various error states occur. ResultGenerated fires when
00252                     // some recognized phrases occur, or the garbage rule is hit.
00253                     speechRecognizer.ContinuousRecognitionSession.Completed += ContinuousRecognitionSession_Completed;
00254                     speechRecognizer.ContinuousRecognitionSession.ResultGenerated += ContinuousRecognitionSession_ResultGenerated;
00255
00256
00257                     btnContinuousRecognize.IsEnabled = true;
00258
00259                     resultTextBlock.Text = speechResourceMap.GetValue("SRGSHelpText", speechContext).ValueAsString;
00260                     resultTextBlock.Visibility = Visibility.Visible;
00261                 }
00262             }
00263             catch (Exception ex)
00264             {
00265                 if ((uint)ex.HResult == HResultRecognizerNotFound)
00266                 {
00267                     btnContinuousRecognize.IsEnabled = false;
00268
00269                     resultTextBlock.Visibility = Visibility.Visible;
00270                     resultTextBlock.Text = "Speech Language pack for selected language not installed.";
00271                 }
00272                 else
00273                 {
00274                     var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception");
00275                     await messageDialog.ShowAsync();
00276                 }
00277             }
00278
00279         }
00280
00281         /// <summary>
00282         /// Begin recognition or finish the recognition session.
00283         /// </summary>
00284         /// <param name="sender">The button that generated this event</param>
00285         /// <param name="e">Unused event details</param>
00286         public async void ContinuousRecognize_Click(object sender, RoutedEventArgs e)
00287         {
00288             btnContinuousRecognize.IsEnabled = false;
00289             // The recognizer can only start listening in a continuous fashion if the recognizer is currently idle.
00290             // This prevents an exception from occurring.
00291             if (speechRecognizer.State == SpeechRecognizerState.Idle)
00292             {
00293                 // Reset the text to prompt the user.
00294                 try
00295                 {
00296                     await speechRecognizer.ContinuousRecognitionSession.StartAsync();
00297                     resultTextBlock.Text = speechResourceMap.GetValue("SRGSHelpText", speechContext).ValueAsString;
00298                     ContinuousRecoButtonText.Text = " Stop Continuous Recognition";
00299                     cbLanguageSelection.IsEnabled = false;
00300                 }
00301                 catch (Exception ex)
00302                 {
00303                     var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "StartAsync Exception");
00304                     await messageDialog.ShowAsync();
00305                 }
00306             }
00307             else
00308             {
00309                 try
00310                 {
00311                     // Reset the text to prompt the user.
00312                     ContinuousRecoButtonText.Text = " Continuous Recognition";
00313                     cbLanguageSelection.IsEnabled = true;
00314                     resultTextBlock.Text = speechResourceMap.GetValue("SRGSHelpText", speechContext).ValueAsString;
00315                     // Cancelling recognition prevents any currently recognized speech from
00316                     // generating a ResultGenerated event. StopAsync() will allow the final session to
00317                     // complete.
00318                     await speechRecognizer.ContinuousRecognitionSession.CancelAsync();
00319                 }
00320                 catch (Exception ex)
00321                 {
00322                     var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "CancelAsync Exception");
00323                     await messageDialog.ShowAsync();
00324                 }
00325             }
00326             btnContinuousRecognize.IsEnabled = true;
00327         }
00328
00329         /// <summary>
00330         /// Handle events fired when the session ends, either from a call to
00331         /// CancelAsync() or StopAsync(), or an error condition, such as the
00332         /// microphone becoming unavailable or some transient issues occuring.
00333         /// </summary>
00334         /// <param name="sender">The continuous recognition session</param>
00335         /// <param name="args">The state of the recognizer</param>
00336         private async void ContinuousRecognitionSession_Completed(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionCompletedEventArgs args)
00337         {
00338             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00339             {
00340                 rootPage.NotifyUser("Continuous Recognition Completed: " + args.Status.ToString(), NotifyType.StatusMessage);
00341                 ContinuousRecoButtonText.Text = " Continuous Recognition";
00342                 cbLanguageSelection.IsEnabled = true;
00343             });
00344         }
00345
00346         /// <summary>
00347         /// Handle events fired when a result is generated. This may include a garbage rule that fires when general room noise
00348         /// or side-talk is captured (this will have a confidence of Rejected typically, but may occasionally match a rule with
00349         /// low confidence).
00350         /// </summary>
00351         /// <param name="sender">The Recognition session that generated this result</param>
00352         /// <param name="args">Details about the recognized speech</param>
00353         private async void ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionResultGeneratedEventArgs args)
00354         {
00355             // Developers may decide to use per-phrase confidence levels in order to tune the behavior of their
00356             // grammar based on testing.
00357             if (args.Result.Confidence == SpeechRecognitionConfidence.Medium ||
00358                 args.Result.Confidence == SpeechRecognitionConfidence.High)
00359             {
00360                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00361                 {
00362                     HandleRecognitionResult(args.Result);
00363                 });
00364             }
00365             // Prompt the user if recognition failed or recognition confidence is low.
00366             else if (args.Result.Confidence == SpeechRecognitionConfidence.Rejected ||
00367             args.Result.Confidence == SpeechRecognitionConfidence.Low)
00368             {
00369                 // In some scenarios, a developer may choose to ignore giving the user feedback in this case, if speech
00370                 // is not the primary input mechanism for the application.
00371                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00372                 {
00373                     resultTextBlock.Text = speechResourceMap.GetValue("SRGSGarbagePromptText", speechContext).ValueAsString;
00374                 });
00375             }
00376         }
00377
00378         /// <summary>
00379         /// Provide feedback to the user based on whether the recognizer is receiving their voice input.
00380         /// </summary>
00381         /// <param name="sender">The recognizer that is currently running.</param>
00382         /// <param name="args">The current state of the recognizer.</param>
00383         private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args)
00384         {
00385             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00386             {
00387                 rootPage.NotifyUser(args.State.ToString(), NotifyType.StatusMessage);
00388             });
00389         }
00390
00391         /// <summary>
00392         /// Uses the result from the speech recognizer to change the colors of the shapes.
00393         /// </summary>
00394         /// <param name="recoResult">The result from the recognition event</param>
00395         private void HandleRecognitionResult(SpeechRecognitionResult recoResult)
00396         {
00397             // Check the confidence level of the recognition result.
00398             if (recoResult.Confidence == SpeechRecognitionConfidence.High ||
00399             recoResult.Confidence == SpeechRecognitionConfidence.Medium)
00400             {
00401                 // Declare a string that will contain messages when the color rule matches GARBAGE.
00402                 string garbagePrompt = "";
00403
00404                 // BACKGROUND: Check to see if the recognition result contains the semantic key for the background color,
00405                 // and not a match for the GARBAGE rule, and change the color.
00406                 if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BACKGROUND") && recoResult.SemanticInterpretation.Properties["KEY_BACKGROUND"][0].ToString() != "...")
00407                 {
00408                     string backgroundColor = recoResult.SemanticInterpretation.Properties["KEY_BACKGROUND"][0].ToString();
00409                     colorRectangle.Fill = new SolidColorBrush(getColor(backgroundColor));
00410                 }
00411
00412                 // If "background" was matched, but the color rule matched GARBAGE, prompt the user.
00413                 else if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BACKGROUND") && recoResult.SemanticInterpretation.Properties["KEY_BACKGROUND"][0].ToString() == "...")
00414                 {
00415
00416                     garbagePrompt += speechResourceMap.GetValue("SRGSBackgroundGarbagePromptText", speechContext).ValueAsString;
00417                     resultTextBlock.Text = garbagePrompt;
00418                 }
00419
00420                 // BORDER: Check to see if the recognition result contains the semantic key for the border color,
00421                 // and not a match for the GARBAGE rule, and change the color.
00422                 if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BORDER") && recoResult.SemanticInterpretation.Properties["KEY_BORDER"][0].ToString() != "...")
00423                 {
00424                     string borderColor = recoResult.SemanticInterpretation.Properties["KEY_BORDER"][0].ToString();
00425                     colorRectangle.Stroke = new SolidColorBrush(getColor(borderColor));
00426                 }
00427
00428                 // If "border" was matched, but the color rule matched GARBAGE, prompt the user.
00429                 else if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BORDER") && recoResult.SemanticInterpretation.Properties["KEY_BORDER"][0].ToString() == "...")
00430                 {
00431                     garbagePrompt += speechResourceMap.GetValue("SRGSBorderGarbagePromptText", speechContext).ValueAsString;
00432                     resultTextBlock.Text = garbagePrompt;
00433                 }
00434
00435                 // CIRCLE: Check to see if the recognition result contains the semantic key for the circle color,
00436                 // and not a match for the GARBAGE rule, and change the color.
00437                 if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_CIRCLE") && recoResult.SemanticInterpretation.Properties["KEY_CIRCLE"][0].ToString() != "...")
00438                 {
00439                     string circleColor = recoResult.SemanticInterpretation.Properties["KEY_CIRCLE"][0].ToString();
00440                     colorCircle.Fill = new SolidColorBrush(getColor(circleColor));
00441                 }
00442
00443                 // If "circle" was matched, but the color rule matched GARBAGE, prompt the user.
00444                 else if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_CIRCLE") && recoResult.SemanticInterpretation.Properties["KEY_CIRCLE"][0].ToString() == "...")
00445                 {
00446                     garbagePrompt += speechResourceMap.GetValue("SRGSCircleGarbagePromptText", speechContext).ValueAsString;
00447                     resultTextBlock.Text = garbagePrompt;
00448                 }
00449
00450                 // Initialize a string that will describe the user's color choices.
00451                 string textBoxColors = "You selected (Semantic Interpretation)-> \n";
00452
00453                 // Write the color choices contained in the semantics of the recognition result to the text box.
00454                 foreach (KeyValuePair<String, IReadOnlyList<string>> child in recoResult.SemanticInterpretation.Properties)
00455                 {
00456
00457                     // Check to see if any of the semantic values in recognition result contains a match for the GARBAGE rule.
00458                     if (!child.Value.Equals("..."))
00459                     {
00460
00461                         // Cycle through the semantic keys and values and write them to the text box.
00462                         textBoxColors += (string.Format(" {0} {1}\n",
00463                         child.Value[0], child.Key ?? "null"));
00464
00465                         resultTextBlock.Text = textBoxColors;
00466                     }
00467
00468                     // If there was no match to the colors rule or if it matched GARBAGE, prompt the user.
00469                     else
00470                     {
00471                         resultTextBlock.Text = garbagePrompt;
00472                     }
00473                 }
00474             }
00475
00476             // Prompt the user if recognition failed or recognition confidence is low.
00477             else if (recoResult.Confidence == SpeechRecognitionConfidence.Rejected ||
00478             recoResult.Confidence == SpeechRecognitionConfidence.Low)
00479             {
00480                 resultTextBlock.Text = speechResourceMap.GetValue("SRGSGarbagePromptText", speechContext).ValueAsString;
00481             }
00482         }
00483
00484         /// <summary>
00485         /// Creates a color object from the passed in string.
00486         /// </summary>
00487         /// <param name="colorString">The name of the color</param>
00488         private Color getColor(string colorString)
00489         {
00490             Color newColor = Colors.Transparent;
00491
00492             if (colorLookup.ContainsKey(colorString))
00493             {
00494                 newColor = colorLookup[colorString];
00495             }
00496
00497             return newColor;
00498         }
00499     }
00500 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Basics Member List

This is the complete list of members for Scenario1_Basics, including all inherited members.
Apply_Clicked(winrt::Windows::Foundation::IInspectable const &sender, winrt::Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Basics |
ApplySettingsToLampArray(winrt::Windows::Devices::Lights::LampArray const &lampArray) | Scenario1_Basics | [private]
LampArray_AvailabilityChanged(winrt::Windows::Devices::Lights::LampArray const &sender, winrt::Windows::Foundation::IInspectable const &) | Scenario1_Basics | [private]
m_attachedLampArrays | Scenario1_Basics | [private]
m_deviceAddedRevoker | Scenario1_Basics | [private]
m_deviceRemovedRevoker | Scenario1_Basics | [private]
OnNavigatedFrom(winrt::Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario1_Basics |
OnNavigatedTo(winrt::Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario1_Basics |
Scenario1_Basics() | Scenario1_Basics |
SetGradientPatternToLampArray(winrt::Windows::Devices::Lights::LampArray const &lampArray) | Scenario1_Basics | [private]
SetWasdPatternToLampArray(winrt::Windows::Devices::Lights::LampArray const &lampArray) | Scenario1_Basics | [private]
UpdateLampArrayList() | Scenario1_Basics | [private]
Watcher_Added(winrt::Windows::Devices::Enumeration::DeviceWatcher const &, winrt::Windows::Devices::Enumeration::DeviceInformation const &deviceInformation) | Scenario1_Basics | [private]
Watcher_Removed(winrt::Windows::Devices::Enumeration::DeviceWatcher const &, winrt::Windows::Devices::Enumeration::DeviceInformationUpdate deviceInformationUpdate) | Scenario1_Basics | [private]
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cpp/pch.h Source File

  • FilePicker
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/Content/RenderingHelper.cpp Source File

  • SpatialInteractionSource
  • cpp
  • Content

RenderingHelper.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "RenderingHelper.h"
00003 #include "Common\DirectXHelper.h"
00004
00005 using namespace HolographicPaint;
00006 using namespace Concurrency;
00007 using namespace DirectX;
00008 using namespace Windows::Foundation::Numerics;
00009 using namespace Windows::UI::Input::Spatial;
00010
00011 // Loads vertex and pixel shaders from files and instantiates the cube geometry.
00012 RenderingHelper::RenderingHelper(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00013     m_deviceResources(deviceResources)
00014 {
00015     CreateDeviceDependentResources();
00016 }
00017
00018 void RenderingHelper::SetConstantBuffer(ModelConstantBuffer* pModelConstantBuffer)
00019 {
00020     const auto context = m_deviceResources->GetD3DDeviceContext();
00021     context->UpdateSubresource(m_modelConstantBuffer.Get(), 0, nullptr, pModelConstantBuffer, 0, 0);
00022 }
00023
00024 bool RenderingHelper::PrepareRendering()
00025 {
00026     // Loading is asynchronous. Resources must be created before drawing can occur.
00027     if (!m_loadingComplete)
00028     {
00029         return false;
00030     }
00031
00032     const auto context = m_deviceResources->GetD3DDeviceContext();
00033
00034     // Each vertex is one instance of the VertexPosition struct.
00035     const UINT stride = sizeof(VertexPosition);
00036     const UINT offset = 0;
00037     context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00038     context->IASetInputLayout(m_inputLayout.Get());
00039
00040     // Attach the vertex shader.
00041     context->VSSetShader(
00042         m_vertexShader.Get(),
00043         nullptr,
00044         0
00045         );
00046     // Apply the model constant buffer to the vertex shader.
00047     context->VSSetConstantBuffers(
00048         0,
00049         1,
00050         m_modelConstantBuffer.GetAddressOf()
00051         );
00052
00053     if (!m_usingVprtShaders)
00054     {
00055         // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00056         // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00057         // a pass-through geometry shader is used to set the render target
00058         // array index.
00059         context->GSSetShader(
00060             m_geometryShader.Get(),
00061             nullptr,
00062             0
00063             );
00064     }
00065
00066     // Attach the pixel shader.
00067     context->PSSetShader(
00068         m_pixelShader.Get(),
00069         nullptr,
00070         0
00071         );
00072     return true;
00073 }
00074
00075 void RenderingHelper::CreateDeviceDependentResources()
00076 {
00077     m_usingVprtShaders = m_deviceResources->GetDeviceSupportsVprt();
00078
00079     // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3::
00080     // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature
00081     // we can avoid using a pass-through geometry shader to set the render
00082     // target array index, thus avoiding any overhead that would be
00083     // incurred by setting the geometry shader stage.
00084     std::wstring vertexShaderFileName = m_usingVprtShaders ? L"ms-appx:///VprtVertexShader.cso" : L"ms-appx:///VertexShader.cso";
00085
00086     // Load shaders asynchronously.
00087     task<std::vector<byte>> loadVSTask = DX::ReadDataAsync(vertexShaderFileName);
00088     task<std::vector<byte>> loadPSTask = DX::ReadDataAsync(L"ms-appx:///PixelShader.cso");
00089
00090     task<std::vector<byte>> loadGSTask;
00091     if (!m_usingVprtShaders)
00092     {
00093         // Load the pass-through geometry shader.
00094         loadGSTask = DX::ReadDataAsync(L"ms-appx:///GeometryShader.cso");
00095     }
00096
00097     // After the vertex shader file is loaded, create the shader and input layout.
00098     task<void> createVSTask = loadVSTask.then([this] (const std::vector<byte>& fileData)
00099     {
00100         DX::ThrowIfFailed(
00101             m_deviceResources->GetD3DDevice()->CreateVertexShader(
00102                 fileData.data(),
00103                 fileData.size(),
00104                 nullptr,
00105                 &m_vertexShader
00106                 )
00107             );
00108
00109         constexpr std::array<D3D11_INPUT_ELEMENT_DESC, 1> vertexDesc =
00110         {{
00111             { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0,  0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00112         }};
00113
00114         DX::ThrowIfFailed(
00115             m_deviceResources->GetD3DDevice()->CreateInputLayout(
00116                 vertexDesc.data(),
00117                 static_cast<UINT>(vertexDesc.size()),
00118                 fileData.data(),
00119                 static_cast<UINT>(fileData.size()),
00120                 &m_inputLayout
00121                 )
00122             );
00123     });
00124
00125     // After the pixel shader file is loaded, create the shader and constant buffer.
00126     task<void> createPSTask = loadPSTask.then([this] (const std::vector<byte>& fileData)
00127     {
00128         DX::ThrowIfFailed(
00129             m_deviceResources->GetD3DDevice()->CreatePixelShader(
00130                 fileData.data(),
00131                 fileData.size(),
00132                 nullptr,
00133                 &m_pixelShader
00134                 )
00135             );
00136
00137         const CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00138         DX::ThrowIfFailed(
00139             m_deviceResources->GetD3DDevice()->CreateBuffer(
00140                 &constantBufferDesc,
00141                 nullptr,
00142                 &m_modelConstantBuffer
00143                 )
00144             );
00145     });
00146
00147     task<void> createGSTask;
00148     if (!m_usingVprtShaders)
00149     {
00150         // After the pass-through geometry shader file is loaded, create the shader.
00151         createGSTask = loadGSTask.then([this] (const std::vector<byte>& fileData)
00152         {
00153             DX::ThrowIfFailed(
00154                 m_deviceResources->GetD3DDevice()->CreateGeometryShader(
00155                     fileData.data(),
00156                     fileData.size(),
00157                     nullptr,
00158                     &m_geometryShader
00159                     )
00160                 );
00161         });
00162     }
00163
00164     // Once all shaders are loaded, create the mesh.
00165     task<void> shaderTaskGroup = m_usingVprtShaders ? (createPSTask && createVSTask) : (createPSTask && createVSTask && createGSTask);
00166     task<void> createCubeTask  = shaderTaskGroup.then([this] ()
00167     {
00168         // Load mesh vertices. Each vertex has a position and a color.
00169         // Note that the cube size has changed from the default DirectX app
00170         // template. Windows Holographic is scaled in meters, so to draw the
00171         // cube at a comfortable size we made the cube width 0.2 m (20 cm).
00172         static const std::array<VertexPosition, 8> cubeVertices =
00173         {{
00174             { XMFLOAT3(-0.5f, -0.5f, -0.5f) },
00175             { XMFLOAT3(-0.5f, -0.5f,  0.5f) },
00176             { XMFLOAT3(-0.5f,  0.5f, -0.5f) },
00177             { XMFLOAT3(-0.5f,  0.5f,  0.5f) },
00178             { XMFLOAT3( 0.5f, -0.5f, -0.5f) },
00179             { XMFLOAT3( 0.5f, -0.5f,  0.5f) },
00180             { XMFLOAT3( 0.5f,  0.5f, -0.5f) },
00181             { XMFLOAT3( 0.5f,  0.5f,  0.5f) },
00182         }};
00183
00184         D3D11_SUBRESOURCE_DATA vertexBufferData = {0};
00185         vertexBufferData.pSysMem                = cubeVertices.data();
00186         vertexBufferData.SysMemPitch            = 0;
00187         vertexBufferData.SysMemSlicePitch       = 0;
00188         const CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(VertexPosition) * static_cast<UINT>(cubeVertices.size()), D3D11_BIND_VERTEX_BUFFER);
00189         DX::ThrowIfFailed(
00190             m_deviceResources->GetD3DDevice()->CreateBuffer(
00191                 &vertexBufferDesc,
00192                 &vertexBufferData,
00193                 &m_vertexBuffer
00194                 )
00195             );
00196
00197         // Load mesh indices. Each trio of indices represents
00198         // a triangle to be rendered on the screen.
00199         // For example: 2,1,0 means that the vertices with indexes
00200         // 2, 1, and 0 from the vertex buffer compose the
00201         // first triangle of this mesh.
00202         // Note that the winding order is clockwise by default.
00203         constexpr std::array<VertexIndex_t, 36> cubeIndices =
00204         {{
00205             2,1,0, // -x
00206             2,3,1,
00207
00208             6,4,5, // +x
00209             6,5,7,
00210
00211             0,1,5, // -y
00212             0,5,4,
00213
00214             2,6,7, // +y
00215             2,7,3,
00216
00217             0,4,6, // -z
00218             0,6,2,
00219
00220             1,3,7, // +z
00221             1,7,5,
00222         }};
00223
00224         m_indexCount = static_cast<unsigned int>(cubeIndices.size());
00225
00226         D3D11_SUBRESOURCE_DATA indexBufferData  = {0};
00227         indexBufferData.pSysMem                 = cubeIndices.data();
00228         indexBufferData.SysMemPitch             = 0;
00229         indexBufferData.SysMemSlicePitch        = 0;
00230         CD3D11_BUFFER_DESC indexBufferDesc(sizeof(VertexIndex_t) * static_cast<UINT>(cubeIndices.size()), D3D11_BIND_INDEX_BUFFER);
00231         DX::ThrowIfFailed(
00232         m_deviceResources->GetD3DDevice()->CreateBuffer(
00233                 &indexBufferDesc,
00234                 &indexBufferData,
00235                 &m_indexBuffer
00236                 )
00237             );
00238     });
00239
00240     // Once the cube is loaded, the object is ready to be rendered.
00241     createCubeTask.then([this] ()
00242     {
00243         m_loadingComplete = true;
00244     });
00245 }
00246
00247 void RenderingHelper::DrawCube()
00248 {
00249     const auto context = m_deviceResources->GetD3DDeviceContext();
00250     const UINT stride = sizeof(VertexPosition);
00251     const UINT offset = 0;
00252     context->IASetVertexBuffers(0, 1, m_vertexBuffer.GetAddressOf(), &stride, &offset);
00253     context->IASetIndexBuffer(m_indexBuffer.Get(), DX::GetDxgiFormat(), 0);
00254     context->DrawIndexedInstanced(m_indexCount, 2, 0, 0, 0);
00255 }
00256
00257 void RenderingHelper::ReleaseDeviceDependentResources()
00258 {
00259     m_loadingComplete  = false;
00260     m_usingVprtShaders = false;
00261     m_vertexShader.Reset();
00262     m_inputLayout.Reset();
00263     m_pixelShader.Reset();
00264     m_geometryShader.Reset();
00265     m_modelConstantBuffer.Reset();
00266     m_vertexBuffer.Reset();
00267     m_indexBuffer.Reset();
00268 }
00269
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

OpQueue< T, TOperation > Member List

This is the complete list of members for OpQueue< T, TOperation >, including all inherited members.
DispatchOperation(TOperation *pOp)=0 | OpQueue< T, TOperation > | [protected, pure virtual]
m_critsec | OpQueue< T, TOperation > | [protected]
m_OnProcessQueue | OpQueue< T, TOperation > | [protected]
m_OpQueue | OpQueue< T, TOperation > | [protected]
OpList typedef | OpQueue< T, TOperation > |
OpQueue(CRITICAL_SECTION &critsec) | OpQueue< T, TOperation > | [inline, protected]
ProcessQueue() | OpQueue< T, TOperation > | [protected]
ProcessQueueAsync(IMFAsyncResult *pResult) | OpQueue< T, TOperation > | [protected]
QueueOperation(TOperation *pOp) | OpQueue< T, TOperation > |
ValidateOperation(TOperation *pOp)=0 | OpQueue< T, TOperation > | [protected, pure virtual]
~OpQueue() | OpQueue< T, TOperation > | [inline, protected, virtual]
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Memory Member List

This is the complete list of members for Scenario2_Memory, including all inherited members.
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario2_Memory |
ProtectL1_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Memory |
ProtectL2_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Memory |
ReportProtectedBuffer(Windows::Storage::Streams::IBuffer const &buffer) | Scenario2_Memory | [private]
Scenario2_Memory() | Scenario2_Memory |
Unprotect_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Memory |
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/Content/Panel.cpp Source File

  • HolographicMixedRealityCapture
  • cpp
  • Content

Panel.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "Panel.h"
00003 #include "Common\DirectXHelper.h"
00004
00005 using namespace HolographicMRCSample;
00006 using namespace Concurrency;
00007 using namespace DirectX;
00008 using namespace Windows::Foundation::Numerics;
00009 using namespace Windows::UI::Input::Spatial;
00010
00011 // Loads vertex and pixel shaders from files and instantiates the cube geometry.
00012 Panel::Panel(const float width, const float height, const float depth,
00013              const float red,   const float green,  const float blue, const float alpha) :
00014     m_size(Windows::Foundation::Numerics::float3(width, height, depth)),
00015     m_color(Windows::Foundation::Numerics::float4(red, green, blue, alpha))
00016 {
00017 }
00018
00019 // Called once per frame. Rotates the cube, and calculates and sets the model matrix
00020 // relative to the position transform indicated by hologramPositionTransform.
00021 void Panel::DoUpdate(
00022     const DX::StepTimer& timer,
00023     HolographicFrame^ holographicFrame,
00024     SpatialCoordinateSystem^ currentCoordinateSystem,
00025     SpatialInteractionSourceState^ interactionSource,
00026     const DirectX::XMMATRIX &parentTransform)
00027 {
00028     // Rotate the cube.
00029     const XMMATRIX modelRotation    = XMMatrixRotationRollPitchYawFromVector(XMLoadFloat3(&m_rotation));
00030
00031     // Position the cube.
00032     const XMMATRIX modelTranslation = XMMatrixTranslationFromVector(XMLoadFloat3(&m_position));
00033
00034     // Multiply to get the transform matrix.
00035     // Note that this transform does not enforce a particular coordinate system. The calling
00036     // class is responsible for rendering this content in a consistent manner.
00037     const XMMATRIX modelTransform = modelRotation * modelTranslation * parentTransform;
00038     XMStoreFloat4x4(&m_transform, modelTransform);
00039
00040     // The view and projection matrices are provided by the system; they are associated
00041     // with holographic cameras, and updated on a per-camera basis.
00042     // Here, we provide the model transform for the sample hologram. The model transform
00043     // matrix is transposed to prepare it for the shader.
00044     XMStoreFloat4x4(&m_modelConstantBufferData.model, XMMatrixTranspose(modelTransform));
00045 }
00046
00047 // Renders one frame using the vertex and pixel shaders.
00048 // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00049 // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00050 // a pass-through geometry shader is also used to set the render
00051 // target array index.
00052 void Panel::DoRender()
00053 {
00054     // Loading is asynchronous. Resources must be created before drawing can occur.
00055     if (!m_loadingComplete)
00056     {
00057         return;
00058     }
00059
00060     const auto context = m_deviceResources->GetD3DDeviceContext();
00061
00062     // Update the model transform buffer for the hologram.
00063     context->UpdateSubresource(
00064         m_modelConstantBuffer.Get(),
00065         0,
00066         nullptr,
00067         &m_modelConstantBufferData,
00068         0,
00069         0
00070         );
00071
00072     // Each vertex is one instance of the VertexPositionColor struct.
00073     const UINT stride = sizeof(VertexPositionColor);
00074     const UINT offset = 0;
00075     context->IASetVertexBuffers(
00076         0,
00077         1,
00078         m_vertexBuffer.GetAddressOf(),
00079         &stride,
00080         &offset
00081         );
00082     context->IASetIndexBuffer(
00083         m_indexBuffer.Get(),
00084         DXGI_FORMAT_R16_UINT, // Each index is one 16-bit unsigned integer (short).
00085         0
00086         );
00087     context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00088     context->IASetInputLayout(m_inputLayout.Get());
00089
00090     // Attach the vertex shader.
00091     context->VSSetShader(
00092         m_vertexShader.Get(),
00093         nullptr,
00094         0
00095         );
00096     // Apply the model constant buffer to the vertex shader.
00097     context->VSSetConstantBuffers(
00098         0,
00099         1,
00100         m_modelConstantBuffer.GetAddressOf()
00101         );
00102
00103     if (!m_usingVprtShaders)
00104     {
00105         // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00106         // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00107         // a pass-through geometry shader is used to set the render target
00108         // array index.
00109         context->GSSetShader(
00110             m_geometryShader.Get(),
00111             nullptr,
00112             0
00113             );
00114     }
00115
00116     // Attach the pixel shader.
00117     context->PSSetShader(
00118         m_pixelShader.Get(),
00119         nullptr,
00120         0
00121         );
00122
00123     // Draw the objects.
00124     context->DrawIndexedInstanced(
00125         m_indexCount,   // Index count per instance.
00126         2,              // Instance count.
00127         0,              // Start index location.
00128         0,              // Base vertex location.
00129         0               // Start instance location.
00130         );
00131 }
00132
00133 void Panel::DoCreateDeviceDependentResources()
00134 {
00135     if (m_loadingComplete)
00136     {
00137         return;
00138     }
00139
00140     m_usingVprtShaders = m_deviceResources->GetDeviceSupportsVprt();
00141
00142     // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3::
00143     // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature
00144     // we can avoid using a pass-through geometry shader to set the render
00145     // target array index, thus avoiding any overhead that would be
00146     // incurred by setting the geometry shader stage.
00147
00148     m_vertexShader = m_deviceResources->GetVertexShader(DX::VertexShader_Simple);
00149     m_inputLayout  = m_deviceResources->GetInputLayout(DX::VertexShader_Simple);
00150     m_pixelShader  = m_deviceResources->GetPixelShader(DX::PixelShader_Simple);
00151
00152     if (!m_usingVprtShaders)
00153     {
00154         // Get the pass-through geometry shader.
00155         m_geometryShader = m_deviceResources->GetGeometryShader(DX::GeometryShader_Simple);
00156     }
00157
00158     // After the pixel shader file is loaded, create the shader and constant buffer.
00159     const CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00160     DX::ThrowIfFailed(
00161         m_deviceResources->GetD3DDevice()->CreateBuffer(
00162             &constantBufferDesc,
00163             nullptr,
00164             &m_modelConstantBuffer));
00165
00166     // Once all shaders are loaded, create the mesh.
00167     {
00168         float halfWidth  = m_size.x * 0.5f;
00169         float halfHeight = m_size.y * 0.5f;
00170         float halfDepth  = m_size.z * 0.5f;
00171         XMFLOAT4 color(m_color.x, m_color.y, m_color.z, m_color.w);
00172
00173         // initiate bounding box
00174         m_boundingBox = BoundingOrientedBox(XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(halfWidth, halfHeight, halfDepth), XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f));
00175
00176         // Load mesh vertices. Each vertex has a position and a color.
00177         // Note that the cube size has changed from the default DirectX app
00178         // template. Windows Holographic is scaled in meters, so to draw the
00179         // cube at a comfortable size we made the cube width 0.2 m (20 cm).
00180         const VertexPositionColor cubeVertices[] =
00181         {
00182             { XMFLOAT3(-halfWidth, -halfHeight, -halfDepth), color },
00183             { XMFLOAT3(-halfWidth, -halfHeight,  halfDepth), color },
00184             { XMFLOAT3(-halfWidth,  halfHeight, -halfDepth), color },
00185             { XMFLOAT3(-halfWidth,  halfHeight,  halfDepth), color },
00186             { XMFLOAT3( halfWidth, -halfHeight, -halfDepth), color },
00187             { XMFLOAT3( halfWidth, -halfHeight,  halfDepth), color },
00188             { XMFLOAT3( halfWidth,  halfHeight, -halfDepth), color },
00189             { XMFLOAT3( halfWidth,  halfHeight,  halfDepth), color },
00190         };
00191
00192         D3D11_SUBRESOURCE_DATA vertexBufferData = {0};
00193         vertexBufferData.pSysMem = cubeVertices;
00194         vertexBufferData.SysMemPitch = 0;
00195         vertexBufferData.SysMemSlicePitch = 0;
00196         const CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(cubeVertices), D3D11_BIND_VERTEX_BUFFER);
00197         DX::ThrowIfFailed(
00198             m_deviceResources->GetD3DDevice()->CreateBuffer(
00199                 &vertexBufferDesc,
00200                 &vertexBufferData,
00201                 &m_vertexBuffer
00202                 )
00203             );
00204
00205         // Load mesh indices. Each trio of indices represents
00206         // a triangle to be rendered on the screen.
00207         // For example: 2,1,0 means that the vertices with indexes
00208         // 2, 1, and 0 from the vertex buffer compose the
00209         // first triangle of this mesh.
00210         // Note that the winding order is clockwise by default.
00211         static const unsigned short cubeIndices [] =
00212         {
00213             2,1,0, // -x
00214             2,3,1,
00215
00216             6,4,5, // +x
00217             6,5,7,
00218
00219             0,1,5, // -y
00220             0,5,4,
00221
00222             2,6,7, // +y
00223             2,7,3,
00224
00225             0,4,6, // -z
00226             0,6,2,
00227
00228             1,3,7, // +z
00229             1,7,5,
00230         };
00231
00232         m_indexCount = ARRAYSIZE(cubeIndices);
00233
00234         D3D11_SUBRESOURCE_DATA indexBufferData = {0};
00235         indexBufferData.pSysMem          = cubeIndices;
00236         indexBufferData.SysMemPitch      = 0;
00237         indexBufferData.SysMemSlicePitch = 0;
00238         const CD3D11_BUFFER_DESC indexBufferDesc(sizeof(cubeIndices), D3D11_BIND_INDEX_BUFFER);
00239         DX::ThrowIfFailed(
00240             m_deviceResources->GetD3DDevice()->CreateBuffer(
00241                 &indexBufferDesc,
00242                 &indexBufferData,
00243                 &m_indexBuffer
00244                 )
00245             );
00246     }
00247
00248     // Once the cube is loaded, the object is ready to be rendered.
00249     m_loadingComplete = true;
00250 }
00251
00252 void Panel::DoReleaseDeviceDependentResources()
00253 {
00254     m_inputLayout.Reset();
00255     m_vertexBuffer.Reset();
00256     m_indexBuffer.Reset();
00257     m_vertexShader.Reset();
00258     m_geometryShader.Reset();
00259     m_pixelShader.Reset();
00260     m_modelConstantBuffer.Reset();
00261
00262     m_loadingComplete  = false;
00263     m_usingVprtShaders = false;
00264 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
App() | sealed |
Initialize(Windows::ApplicationModel::Core::CoreApplicationView^applicationView) | sealed | [virtual]
Load(Platform::String^entryPoint) | sealed | [virtual]
m_deviceResources | sealed | [private]
m_main | sealed | [private]
OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^args) | sealed | [protected]
OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnDpiChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnResuming(Platform::Object^sender, Platform::Object^args) | sealed | [protected]
OnStereoEnabledChanged(Windows::Graphics::Display::DisplayInformation^sender, Platform::Object^args) | sealed | [protected]
OnSuspending(Platform::Object^sender, Windows::ApplicationModel::SuspendingEventArgs^args) | sealed | [protected]
OnVisibilityChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::VisibilityChangedEventArgs^args) | sealed | [protected]
OnWindowActivationChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::WindowActivatedEventArgs^args) | sealed | [protected]
OnWindowClosed(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::CoreWindowEventArgs^args) | sealed | [protected]
OnWindowSizeChanged(Windows::UI::Core::CoreWindow^sender, Windows::UI::Core::WindowSizeChangedEventArgs^args) | sealed | [protected]
Run() | sealed | [virtual]
SetWindow(Windows::UI::Core::CoreWindow^window) | sealed | [virtual]
Uninitialize() | sealed | [virtual]
Generated on Fri Nov 15 2024 22:24:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Appointments/cs/SampleConfiguration.cs Source File

  • Appointments
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Foundation;
00015 using Windows.UI.Xaml.Controls;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Appointments";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title = "Define an Appointment", ClassType = typeof(Scenario1_Define) },
00026             new Scenario() { Title = "Add an Appointment", ClassType = typeof(Scenario2_Add) },
00027             new Scenario() { Title = "Replace an Appointment", ClassType = typeof(Scenario3_Replace) },
00028             new Scenario() { Title = "Remove an Appointment", ClassType = typeof(Scenario4_Remove) },
00029             new Scenario() { Title = "Show Time Frame", ClassType = typeof(Scenario5_Show) },
00030             new Scenario() { Title = "Recurring Appointments", ClassType = typeof(Scenario6_Recurrence) },
00031         };
00032
00033         // Helper function to calculate an element's rectangle in root-relative coordinates.
00034         public static Rect GetElementRect(Windows.UI.Xaml.FrameworkElement element)
00035         {
00036             Windows.UI.Xaml.Media.GeneralTransform transform = element.TransformToVisual(null);
00037             Point point = transform.TransformPoint(new Point());
00038             return new Rect(point, new Size(element.ActualWidth, element.ActualHeight));
00039         }
00040
00041     }
00042
00043     public class Scenario
00044     {
00045         public string Title { get; set; }
00046         public Type ClassType { get; set; }
00047     }
00048 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MobileBroadband/cs/AccountWatcher.xaml.cs Source File

  • MobileBroadband
  • cs

AccountWatcher.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using SDKTemplate;
00016 using System;
00017 using Windows.Networking.NetworkOperators;
00018 using System.Text;
00019
00020 namespace MobileBroadband
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class AccountWatcher : Page
00026     {
00027         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00028         // as NotifyUser()
00029         MainPage rootPage = MainPage.Current;
00030
00031         private MobileBroadbandAccountWatcher networkAccountWatcher = new MobileBroadbandAccountWatcher();
00032
00033         public AccountWatcher()
00034         {
00035             this.InitializeComponent();
00036         }
00037
00038         /// <summary>
00039         /// Invoked when this page is about to be displayed in a Frame.
00040         /// </summary>
00041         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00042         /// property is typically used to configure the page.</param>
00043         protected override void OnNavigatedTo(NavigationEventArgs e)
00044         {
00045             PrepScenario2Sample();
00046         }
00047
00048         /// <summary>
00049         /// This is the click handler for the 'Start' button.
00050         /// </summary>
00051         /// <param name="sender"></param>
00052         /// <param name="e"></param>
00053         private void StartMonitoring_Click(object sender, RoutedEventArgs e)
00054         {
00055             Button b = sender as Button;
00056             if (b != null)
00057             {
00058                 if ((networkAccountWatcher.Status == MobileBroadbandAccountWatcherStatus.Started) ||
00059                 (networkAccountWatcher.Status == MobileBroadbandAccountWatcherStatus.EnumerationCompleted))
00060                 {
00061                     rootPage.NotifyUser("Watcher is already started.", NotifyType.StatusMessage);
00062                 }
00063                 else
00064                 {
00065                     networkAccountWatcher.Start();
00066
00067                     rootPage.NotifyUser("Watcher is started successfully.", NotifyType.StatusMessage);
00068                 }
00069             }
00070         }
00071
00072         /// <summary>
00073         /// This is the click handler for the 'Stop' button.
00074         /// </summary>
00075         /// <param name="sender"></param>
00076         /// <param name="e"></param>
00077         private void StopMonitoring_Click(object sender, RoutedEventArgs e)
00078         {
00079             Button b = sender as Button;
00080             if (b != null)
00081             {
00082                 if ((networkAccountWatcher.Status == MobileBroadbandAccountWatcherStatus.Started) ||
00083                 (networkAccountWatcher.Status == MobileBroadbandAccountWatcherStatus.EnumerationCompleted))
00084                 {
00085                     networkAccountWatcher.Stop();
00086
00087                     rootPage.NotifyUser("Watcher is stopped successfully.", NotifyType.StatusMessage);
00088                 }
00089                 else
00090                 {
00091                     rootPage.NotifyUser("Watcher is already stopped.", NotifyType.StatusMessage);
00092                 }
00093             }
00094         }
00095
00096         void PrepScenario2Sample()
00097         {
00098             rootPage.NotifyUser("", NotifyType.StatusMessage);
00099
00100             networkAccountWatcher.AccountAdded +=
00101                 (sender, args) =>
00102                 {
00103                     string message = "[accountadded] ";
00104
00105                     try
00106                     {
00107                         message += args.NetworkAccountId;
00108
00109                         var account = MobileBroadbandAccount.CreateFromNetworkAccountId(args.NetworkAccountId);
00110                         //rootPage.mba = (MobileBroadbandAccount)account;
00111                         message += ", service provider name: " + account.ServiceProviderName;
00112                     }
00113                     catch (Exception ex)
00114                     {
00115                         message += ex.Message;
00116                     }
00117
00118                     DisplayWatcherOutputFromCallback(message);
00119                 };
00120
00121             networkAccountWatcher.AccountUpdated +=
00122                 (sender, args) =>
00123                 {
00124                     string message = "[accountupdated] ";
00125
00126                     try
00127                     {
00128                         message += args.NetworkAccountId + ", (network = " + args.HasNetworkChanged + "; deviceinformation = " + args.HasDeviceInformationChanged + ")" + Environment.NewLine;
00129                         message += DumpPropertyData(args.NetworkAccountId, args.HasDeviceInformationChanged, args.HasNetworkChanged);
00130                     }
00131                     catch (Exception ex)
00132                     {
00133                         message += ex.Message;
00134                     }
00135
00136                     DisplayWatcherOutputFromCallback(message);
00137                 };
00138
00139             networkAccountWatcher.AccountRemoved +=
00140                 (sender, args) =>
00141                 {
00142                     string message = "[accountremoved] ";
00143
00144                     try
00145                     {
00146                         message += args.NetworkAccountId;
00147                     }
00148                     catch (Exception ex)
00149                     {
00150                         message += ex.Message;
00151                     }
00152
00153                     DisplayWatcherOutputFromCallback(message);
00154                 };
00155
00156             networkAccountWatcher.EnumerationCompleted +=
00157                 (sender, args) =>
00158                 {
00159                     string message = "[enumerationcompleted]";
00160
00161                     DisplayWatcherOutputFromCallback(message);
00162                 };
00163
00164             networkAccountWatcher.Stopped +=
00165                 (sender, args) =>
00166                 {
00167                     string message = "[stopped] Watcher is stopped successfully";
00168
00169                     DisplayWatcherOutputFromCallback(message);
00170                 };
00171         }
00172
00173         async void DisplayWatcherOutputFromCallback(string value)
00174         {
00175             await Dispatcher.RunAsync(
00176                 Windows.UI.Core.CoreDispatcherPriority.Normal,
00177                 () =>
00178                 {
00179                     WatcherOutput.Text += value + Environment.NewLine;
00180                 });
00181         }
00182
00183         void DumpAccountDeviceInformation(StringBuilder message, MobileBroadbandDeviceInformation deviceInformation)
00184         {
00185             message.AppendLine("NetworkDeviceStatus: " + deviceInformation.NetworkDeviceStatus.ToString());
00186             message.AppendLine("MobileEquipmentId: " + deviceInformation.MobileEquipmentId);
00187             message.AppendLine("SubscriberId: " + deviceInformation.SubscriberId);
00188             message.AppendLine("SimIccId: " + deviceInformation.SimIccId);
00189             message.AppendLine("DeviceId: " + deviceInformation.DeviceId);
00190             message.AppendLine("RadioState: " + deviceInformation.CurrentRadioState);
00191         }
00192
00193         void DumpAccountNetwork(StringBuilder message, MobileBroadbandNetwork network)
00194         {
00195             string accessPointName = network.AccessPointName;
00196             if (String.IsNullOrEmpty(accessPointName))
00197             {
00198                 accessPointName = "(not connected)";
00199             }
00200
00201             message.AppendLine("NetworkRegistrationState: " + network.NetworkRegistrationState.ToString());
00202             message.AppendLine("RegistrationNetworkError: " + NetErrorToString(network.RegistrationNetworkError));
00203             message.AppendLine("PacketAttachNetworkError: " + NetErrorToString(network.PacketAttachNetworkError));
00204             message.AppendLine("ActivationNetworkError: " + NetErrorToString(network.ActivationNetworkError));
00205             message.AppendLine("AccessPointName: " + accessPointName);
00206         }
00207
00208         string DumpPropertyData(string networkAccountId, bool hasDeviceInformationChanged, bool hasNetworkChanged)
00209         {
00210             StringBuilder message = new StringBuilder();
00211
00212             var account = MobileBroadbandAccount.CreateFromNetworkAccountId(networkAccountId);
00213
00214             if (hasDeviceInformationChanged)
00215             {
00216                 DumpAccountDeviceInformation(message, account.CurrentDeviceInformation);
00217             }
00218
00219             if (hasNetworkChanged)
00220             {
00221                 DumpAccountNetwork(message, account.CurrentNetwork);
00222             }
00223
00224             return message.ToString();
00225         }
00226
00227         string NetErrorToString(uint netError)
00228         {
00229             return netError == 0 ? "none" : netError.ToString();
00230         }
00231     }
00232 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cppwinrt/LoggingSessionScenario.cpp Source File

  • Logging
  • cppwinrt

LoggingSessionScenario.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "LoggingSessionScenario.h"
00014 #include "LoggingScenarioHelpers.h"
00015
00016 #define SCENARIO_PREFIX                     L"LoggingSessionScenario_"
00017 #define DEFAULT_SESSION_NAME                SCENARIO_PREFIX L"Session"
00018 #define DEFAULT_CHANNEL_NAME                SCENARIO_PREFIX L"Channel"
00019 #define OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME SCENARIO_PREFIX L"LogFiles"
00020 #define LOGGING_ENABLED_SETTING_KEY_NAME    SCENARIO_PREFIX L"LoggingEnabled"
00021
00022 using namespace winrt;
00023 using namespace winrt::Windows::ApplicationModel;
00024 using namespace winrt::Windows::Foundation;
00025 using namespace winrt::Windows::Foundation::Diagnostics;
00026 using namespace winrt::Windows::Storage;
00027 using namespace winrt::SDKTemplate;
00028
00029 LoggingSessionScenario::~LoggingSessionScenario()
00030 {
00031 }
00032
00033 LoggingSessionScenario::LoggingSessionScenario()
00034 {
00035     // Create the logging channel.
00036     // When an app logs messages to a channel, the messges will go
00037     // to any sessions which are consuming messages from the channel.
00038     _channel = LoggingChannel(DEFAULT_CHANNEL_NAME);
00039
00040     // This sample listens to the channel's events so it can track
00041     // information about the channel's enablement status.
00042     _channel.LoggingEnabled({ this, &LoggingSessionScenario::OnChannelLoggingEnabled });
00043
00044     // Attach event handlers for Suspend/Resume.
00045     Windows::UI::Xaml::Application app = Windows::UI::Xaml::Application::Current();
00046     app.Suspending({ this, &LoggingSessionScenario::OnAppSuspending });
00047     app.Resuming({ this, &LoggingSessionScenario::OnAppResuming });
00048
00049     // If the app is being launched (not resumed), the following call will
00050     // activate logging if it had been active at the time of the last suspend.
00051     ResumeLoggingIfApplicable();
00052 }
00053
00054 // static
00055 LoggingSessionScenario&
00056 LoggingSessionScenario::Instance()
00057 {
00058     static LoggingSessionScenario instance;
00059     return instance;
00060 }
00061
00062 event_token
00063 LoggingSessionScenario::StatusChanged(StatusChangedHandler const& handler)
00064 {
00065     return _statusChanged.add(handler);
00066 }
00067
00068 void
00069 LoggingSessionScenario::StatusChanged(event_token const& token) noexcept
00070 {
00071     _statusChanged.remove(token);
00072 }
00073
00074 bool
00075 LoggingSessionScenario::IsBusy() const noexcept
00076 {
00077     return _isBusy != 0;
00078 }
00079
00080 int
00081 LoggingSessionScenario::LogFileGeneratedCount() const noexcept
00082 {
00083     return _logFileGeneratedCount;
00084 }
00085
00086 bool
00087 LoggingSessionScenario::LoggingEnabled() const noexcept
00088 {
00089     return _session != nullptr;
00090 }
00091
00092 bool
00093 LoggingSessionScenario::ToggleLoggingEnabledDisabled()
00094 {
00095     BusySetter busy(*this);
00096
00097     if (_session != nullptr)
00098     {
00099         _session.Close();
00100         _session = nullptr;
00101         _settings.Insert(LOGGING_ENABLED_SETTING_KEY_NAME, box_value(false));
00102         _statusChanged(make<implementation::LoggingScenarioEventArgs>(LoggingScenarioEventType::LoggingEnabledDisabled, false));
00103         return false;
00104     }
00105     else
00106     {
00107         StartLogging();
00108         _settings.Insert(LOGGING_ENABLED_SETTING_KEY_NAME, box_value(true));
00109         _statusChanged(make<implementation::LoggingScenarioEventArgs>(LoggingScenarioEventType::LoggingEnabledDisabled, true));
00110         return true;
00111     }
00112 }
00113
00114 IAsyncAction
00115 LoggingSessionScenario::DoScenarioAsync()
00116 {
00117     BusySetter busy(*this);
00118
00119     std::wstring messageToLog;
00120
00121     int messageIndex = 0; // Increments for each logging call.
00122     int lastDelayIndex = 0; // The messageIndex value at the last delay.
00123     int lastAppErrorIndex = 0; // The messageIndex value at the last simulated error.
00124     int startFileCount = LogFileGeneratedCount();
00125
00126     const int NUMBER_OF_LOG_FILES_TO_GENERATE = 3;
00127
00128     while (LogFileGeneratedCount() - startFileCount < NUMBER_OF_LOG_FILES_TO_GENERATE)
00129     {
00130         bool exceptionOccurred = false;
00131         try
00132         {
00133             // Since the channel is added to the session at level Warning,
00134             // the following is logged because it is logged at level LoggingLevel.Critical.
00135             messageToLog = L"Message=";
00136             messageToLog += std::to_wstring(++messageIndex);
00137             messageToLog +=
00138                 L": Lorem ipsum dolor sit amet, consectetur adipiscing elit.In ligula nisi, vehicula nec eleifend vel, rutrum non dolor.Vestibulum ante ipsum "
00139                 L"primis in faucibus orci luctus et ultrices posuere cubilia Curae; Curabitur elementum scelerisque accumsan. In hac habitasse platea dictumst.";
00140             _channel.LogMessage(messageToLog, LoggingLevel::Critical);
00141
00142             // Since the channel is added to the session at level Warning,
00143             // the following is *not* logged because it is logged at LoggingLevel.Information.
00144             messageToLog = L"Message=";
00145             messageToLog += std::to_wstring(++messageIndex);
00146             messageToLog +=
00147                 L": Lorem ipsum dolor sit amet, consectetur adipiscing elit.In ligula nisi, vehicula nec eleifend vel, rutrum non dolor.Vestibulum ante ipsum "
00148                 L"primis in faucibus orci luctus et ultrices posuere cubilia Curae; Curabitur elementum scelerisque accumsan. In hac habitasse platea dictumst.";
00149             _channel.LogMessage(messageToLog, LoggingLevel::Information);
00150
00151             int value = 1000000; // one million, 7 digits, 4-bytes as an int, 14 bytes as a wide character string.
00152             messageToLog = L"Value #";
00153             messageToLog += std::to_wstring(++messageIndex);
00154             messageToLog += L':';
00155             messageToLog += std::to_wstring(value);
00156             _channel.LogMessage(messageToLog, LoggingLevel::Critical); // 'value' is logged as 14 byte wide character string.
00157             ++messageIndex;
00158             _channel.LogValuePair(L"Value", value, LoggingLevel::Critical); // 'value' is logged as a 4-byte integer.
00159
00160             //
00161             // Every once in a while, simulate an application error
00162             // which causes the app to save the current snapshot
00163             // of logging events in memory to a disk ETL file.
00164             //
00165
00166             if (messageIndex - lastAppErrorIndex >= 25000)
00167             {
00168                 lastAppErrorIndex = messageIndex;
00169
00170                 // Before simulating an application error, demonstrate LoggingActivity.
00171                 // A LoggingActivity outputs a pair of begin and end messages to the channel.
00172                 // The first message is logged when the LoggingActivity is created. When
00173                 // exiting the scope of the LoggingActivity, the second message will be logged.
00174                 {
00175                     LoggingActivity activity(L"Add two numbers.", _channel,
00176                         LoggingLevel::Critical);
00177                     int oneNumber = 100;
00178                     int anotherNumber = 200;
00179                     int total = oneNumber + anotherNumber;
00180                     messageToLog = L"Message=";
00181                     messageToLog += std::to_wstring(++messageIndex);
00182                     messageToLog += L": The result of adding two numbers: ";
00183                     messageToLog += std::to_wstring(total);
00184                     _channel.LogMessage(messageToLog, LoggingLevel::Critical);
00185                 } // The LoggingActivity instance will log the end message at this scope exit.
00186
00187                 // Simulate an application error.
00188                 throw std::exception("Some bad app error occurred.");
00189             }
00190
00191             //
00192             // Pause every once in a while to simulate application activity outside of logging.
00193             //
00194
00195             if (messageIndex - lastDelayIndex >= 100)
00196             {
00197                 lastDelayIndex = messageIndex;
00198                 co_await resume_after(std::chrono::milliseconds(5));
00199             }
00200         }
00201         catch (std::exception const& e)
00202         {
00203             // Save in-memory logging buffer to a log file on error.
00204
00205             hstring what;
00206             if (e.what() != nullptr)
00207             {
00208                 what = to_hstring(e.what());
00209             }
00210             else
00211             {
00212                 what = L"Unknown.";
00213             }
00214
00215             // The session added the channel at level Warning. Log the message at
00216             // level Error which is above (more critical than) Warning, which
00217             // means it will actually get logged.
00218             _channel.LogMessage(L"Exception occurred: " + what, LoggingLevel::Error);
00219
00220             // Since co_await is not supported within catch blocks, record the exception.
00221             // After the catch block, we'll notice that an exception occurred and save the log.
00222             exceptionOccurred = true;
00223         }
00224
00225         if (exceptionOccurred)
00226         {
00227             // An exception occurred, so save the in-memory events to disk for analysis.
00228
00229             // Create the app-defined folder under the app's local folder.
00230             // An app defines where/how it wants to store log files.
00231             // This sample uses OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME under
00232             // the app's local folder.
00233             StorageFolder ourSampleAppLogFolder =
00234                 co_await ApplicationData::Current().LocalFolder().CreateFolderAsync(
00235                     OUR_SAMPLE_APP_LOG_FILE_FOLDER_NAME,
00236                     CreationCollisionOption::OpenIfExists);
00237
00238             // Create a new log file name.
00239             std::wstring newLogFileName;
00240             newLogFileName += L"Log-";
00241             newLogFileName += GetTimeStamp();
00242             newLogFileName += L".etl";
00243
00244             StorageFile logFile = co_await _session.SaveToFileAsync(ourSampleAppLogFolder, newLogFileName);
00245             ++_logFileGeneratedCount;
00246             _statusChanged(make<implementation::LoggingScenarioEventArgs>(LoggingScenarioEventType::LogFileGenerated, logFile.Path()));
00247         }
00248     }
00249 }
00250
00251 void
00252 LoggingSessionScenario::StartLogging()
00253 {
00254     // If no session exists, create one.
00255     // NOTE: There are use cases where an application
00256     // may want to create only a channel for sessions outside
00257     // of the application itself. See MSDN for details. This
00258     // sample is the common scenario of an app logging events
00259     // which it wants to place in its own log file, so it creates
00260     // a session and channel as a pair. The channel is created
00261     // during construction of this LoggingSessionScenario class so
00262     // it already exists by the time this function is called.
00263     if (_session == nullptr)
00264     {
00265         _session = LoggingSession(DEFAULT_SESSION_NAME);
00266     }
00267
00268     // This sample adds the channel at level "warning" to
00269     // demonstrate how messages logged at more verbose levels
00270     // are ignored by the session.
00271     _session.AddLoggingChannel(_channel, LoggingLevel::Warning);
00272 }
00273
00274 void
00275 LoggingSessionScenario::PrepareToSuspend()
00276 {
00277     _settings.Insert(LOGGING_ENABLED_SETTING_KEY_NAME, box_value(_session != nullptr));
00278 }
00279
00280 void
00281 LoggingSessionScenario::ResumeLoggingIfApplicable()
00282 {
00283     bool loggingEnabled = unbox_value_or(_settings.TryLookup(LOGGING_ENABLED_SETTING_KEY_NAME), true);
00284     if (loggingEnabled)
00285     {
00286         StartLogging();
00287     }
00288 }
00289
00290 void
00291 LoggingSessionScenario::OnChannelLoggingEnabled(
00292     ILoggingChannel const& sender,
00293     IInspectable const&)
00294 {
00295     // This method is called when the channel is informing us of channel-related state changes.
00296     // Save new channel state. These values can be used for advanced logging scenarios where,
00297     // for example, it's desired to skip blocks of logging code if the channel is not being
00298     // consumed by any sessions.
00299     _isChannelEnabled = sender.Enabled();
00300     _channelLoggingLevel = sender.Level();
00301 }
00302
00303 void
00304 LoggingSessionScenario::OnAppSuspending(
00305     IInspectable const&,
00306     SuspendingEventArgs const& e)
00307 {
00308     auto deferral = e.SuspendingOperation().GetDeferral();
00309     PrepareToSuspend();
00310     deferral.Complete();
00311 }
00312
00313 void
00314 LoggingSessionScenario::OnAppResuming(
00315     IInspectable const&,
00316     IInspectable const&)
00317 {
00318     // If logging was active at the last suspend, ResumeLoggingIfApplicable
00319     // will re-activate logging.
00320     ResumeLoggingIfApplicable();
00321 }
00322
00323 LoggingSessionScenario::BusySetter::~BusySetter()
00324 {
00325     if (0 == --_scenario._isBusy)
00326     {
00327         _scenario._statusChanged(make<implementation::LoggingScenarioEventArgs>(LoggingScenarioEventType::BusyStatusChanged));
00328     }
00329 }
00330
00331 LoggingSessionScenario::BusySetter::BusySetter(LoggingSessionScenario& scenario)
00332     : _scenario(scenario)
00333 {
00334     if (1 == ++_scenario._isBusy)
00335     {
00336         _scenario._statusChanged(make<implementation::LoggingScenarioEventArgs>(LoggingScenarioEventType::BusyStatusChanged));
00337     }
00338 }
Generated on Fri Nov 15 2024 22:20:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaEditing/cpp/pch.cpp Source File

  • MediaEditing
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/CustomVertexShaderMain.h Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

CustomVertexShaderMain.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "BasicTimer.h"
00015 #include "DeviceResources.h"
00016 #include "CustomVertexShaderRenderer.h"
00017 #include "SampleOverlay.h"
00018
00019 // Renders Direct2D and 3D content on the screen.
00020 namespace CustomVertexShader
00021 {
00022     class CustomVertexShaderMain : public DX::IDeviceNotify
00023     {
00024     public:
00025         CustomVertexShaderMain(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00026         ~CustomVertexShaderMain();
00027         void CreateWindowSizeDependentResources();
00028         void UpdateManipulationState(_In_ Windows::UI::Input::ManipulationUpdatedEventArgs^ args);
00029         void Update();
00030         bool Render();
00031
00032         // IDeviceNotify
00033         virtual void OnDeviceLost();
00034         virtual void OnDeviceRestored();
00035
00036         // Process lifetime management handlers.
00037         void SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00038         void LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00039
00040     private:
00041         // Cached pointer to device resources.
00042         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00043
00044         std::unique_ptr<CustomVertexShaderRenderer> m_sceneRenderer;
00045         std::unique_ptr<SampleOverlay> m_sampleOverlay;
00046
00047         BasicTimer^ m_timer;
00048     };
00049 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_CheckUserConsentGroup Member List

This is the complete list of members for Scenario3_CheckUserConsentGroup, including all inherited members.
EvaluateConsentResult(UserAgeConsentResult consentResult) | Scenario3_CheckUserConsentGroup | [inline, private, static]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_CheckUserConsentGroup | [inline, protected]
rootPage | Scenario3_CheckUserConsentGroup | [private]
Scenario3_CheckUserConsentGroup() | Scenario3_CheckUserConsentGroup | [inline]
ShowConsentGroups(object sender, RoutedEventArgs e) | Scenario3_CheckUserConsentGroup | [inline, private]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/Controls/MediaTransportControlsWithCustomCastButton.cs Source File

  • AdvancedCasting
  • cs
  • Controls

MediaTransportControlsWithCustomCastButton.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Controls.Primitives;
00020 using Windows.UI.Xaml.Data;
00021 using Windows.UI.Xaml.Documents;
00022 using Windows.UI.Xaml.Input;
00023 using Windows.UI.Xaml.Media;
00024
00025 namespace ScreenCasting.Controls
00026 {
00027  public sealed class MediaTransportControlsWithCustomCastButton : MediaTransportControls
00028     {
00029
00030         public MediaTransportControlsWithCustomCastButton()
00031         {
00032             this.DefaultStyleKey = typeof(MediaTransportControlsWithCustomCastButton);
00033         }
00034
00035         public event EventHandler CastButtonClicked;
00036         private void CastButton_Click(object sender, RoutedEventArgs e)
00037         {
00038             if (CastButtonClicked != null)
00039                 CastButtonClicked(this, EventArgs.Empty);
00040         }
00041
00042         public Button CastButton
00043         {
00044             get { return this.GetTemplateChild("CustomCastButton") as Button; }
00045         }
00046         protected override void OnApplyTemplate()
00047         {
00048             base.OnApplyTemplate();
00049
00050             this.IsCompact = true;
00051
00052             CastButton.Click += CastButton_Click;
00053         }
00054     }
00055 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/scenario11.xaml.h Source File

  • ApplicationResources
  • cpp

scenario11.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario11.xaml.h
00013 // Declaration of the Scenario11 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario11.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024
00025         /// <summary>
00026         /// An empty page that can be used on its own or navigated to within a Frame.
00027         /// </summary>
00028         [Windows::Foundation::Metadata::WebHostHidden]
00029         public ref class Scenario11 sealed
00030         {
00031         public:
00032             Scenario11();
00033
00034         protected:
00035             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         private:
00037             MainPage^ rootPage;
00038             void Scenario11Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         };
00040
00041 }
Generated on Fri Nov 15 2024 22:17:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cs/Scenario9_Compare.xaml.cs Source File

  • FileAccess
  • cs

Scenario9_Compare.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.IO;
00014 using Windows.Storage;
00015 using Windows.Storage.Pickers;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// Comparing two files to see if they are the same file.
00024     /// </summary>
00025     public sealed partial class Scenario9 : Page
00026     {
00027         MainPage rootPage = MainPage.Current;
00028
00029         public Scenario9()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             rootPage.ValidateFile();
00037         }
00038
00039         private async void CompareFilesButton_Click(object sender, RoutedEventArgs e)
00040         {
00041             StorageFile file = rootPage.sampleFile;
00042             if (file != null)
00043             {
00044                 FileOpenPicker picker = new FileOpenPicker();
00045                 picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
00046                 picker.FileTypeFilter.Add("*");
00047                 StorageFile comparand = await picker.PickSingleFileAsync();
00048                 if (comparand != null)
00049                 {
00050                     try
00051                     {
00052                         if (file.IsEqual(comparand))
00053                         {
00054                             rootPage.NotifyUser("Files are equal", NotifyType.StatusMessage);
00055                         }
00056                         else
00057                         {
00058                             rootPage.NotifyUser("Files are not equal", NotifyType.StatusMessage);
00059                         }
00060                     }
00061                     catch (FileNotFoundException)
00062                     {
00063                         rootPage.NotifyUserFileNotExist();
00064                     }
00065                 }
00066                 else
00067                 {
00068                     rootPage.NotifyUser("Operation cancelled", NotifyType.StatusMessage);
00069                 }
00070             }
00071             else
00072             {
00073                 rootPage.NotifyUserFileNotExist();
00074             }
00075         }
00076     }
00077 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraProfile/cs/Scenario2_ConcurrentProfile.xaml.cs Source File

  • CameraProfile
  • cs

Scenario2_ConcurrentProfile.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace CameraProfile
00013 {
00014     using System;
00015     using System.Globalization;
00016     using System.Linq;
00017     using System.Threading.Tasks;
00018     using Windows.Devices.Enumeration;
00019     using Windows.Media.Capture;
00020     using Windows.UI.Xaml.Controls;
00021     using Windows.UI.Xaml.Navigation;
00022     using SDKTemplate;
00023
00024     /// <summary>
00025     /// ConcurrenProfile page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class Scenario2_ConcurrentProfile : Page
00028     {
00029         /// <summary>
00030         /// Private MainPage object for status updates
00031         /// </summary>
00032         private MainPage rootPage;
00033
00034         /// <summary>
00035         /// Initializes a new instance of the <see cref="Scenario2_ConcurrentProfile"/> class.
00036         /// </summary>
00037         public Scenario2_ConcurrentProfile()
00038         {
00039             this.InitializeComponent();
00040         }
00041
00042         /// <summary>
00043         /// Override default OnNavigateTo to initialize
00044         /// the rootPage object for Status message updates
00045         /// </summary>
00046         /// <param name="e">Contains state information and event data associated with the event</param>
00047         protected override void OnNavigatedTo(NavigationEventArgs e)
00048         {
00049             rootPage = MainPage.Current;
00050         }
00051
00052         /// <summary>
00053         /// Finds the video profile for the front and back camera and queries if
00054         /// both cameras have a matching video recording profile that supports concurrency.
00055         /// If a matching concurrent profile is supported, then we configure media initialization
00056         /// settings for both cameras to the matching profile.
00057         /// </summary>
00058         /// <param name="sender">Contains information regarding button that fired event</param>
00059         /// <param name="e">Contains state information and event data associated with the event</param>
00060         private async void CheckConcurrentProfileBtn_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00061         {
00062             // Initialize our concurrency support flag.
00063             bool concurrencySupported = false;
00064
00065             string frontVideoDeviceId = string.Empty;
00066             string backVideoDeviceId = string.Empty;
00067
00068             MediaCapture mediaCaptureFront = new MediaCapture();
00069             MediaCapture mediaCaptureBack = new MediaCapture();
00070
00071             // Find front and back Device Id of capture device that supports Video Profile
00072             await LogStatusToOutputBox("Looking for all video capture devices on front panel");
00073             frontVideoDeviceId = await GetVideoProfileSupportedDeviceIdAsync(Windows.Devices.Enumeration.Panel.Front);
00074             await LogStatusToOutputBox("Looking for all video capture devices on back panel");
00075             backVideoDeviceId = await GetVideoProfileSupportedDeviceIdAsync(Windows.Devices.Enumeration.Panel.Back);
00076
00077             // First check if the devices support video profiles, if not there's no reason to proceed
00078             if (string.IsNullOrEmpty(frontVideoDeviceId) || string.IsNullOrEmpty(backVideoDeviceId))
00079             {
00080                 await LogStatus("ERROR: A capture device doesn't support Video Profile", NotifyType.ErrorMessage);
00081                 return;
00082             }
00083
00084             await LogStatusToOutputBox("Video Profiles are supported on both cameras");
00085
00086             // Create MediaCaptureInitilization settings for each video capture device
00087             MediaCaptureInitializationSettings mediaInitSettingsFront = new MediaCaptureInitializationSettings();
00088             MediaCaptureInitializationSettings mediaInitSettingsBack = new MediaCaptureInitializationSettings();
00089
00090             mediaInitSettingsFront.VideoDeviceId = frontVideoDeviceId;
00091             mediaInitSettingsBack.VideoDeviceId = backVideoDeviceId;
00092             await LogStatusToOutputBox(string.Format(CultureInfo.InvariantCulture, "Front Device Id located: {0}", frontVideoDeviceId.ToString()));
00093             await LogStatusToOutputBox(string.Format(CultureInfo.InvariantCulture, "Back Device Id located: {0}", backVideoDeviceId.ToString()));
00094
00095             await LogStatusToOutputBox("Querying for concurrent profile");
00096
00097             // Acquire concurrent profiles available to front and back capture devices, then locate a concurrent
00098             // profile Id that matches for both devices
00099             var concurrentProfile = (from frontProfile in MediaCapture.FindConcurrentProfiles(frontVideoDeviceId)
00100                                      from backProfile in MediaCapture.FindConcurrentProfiles(backVideoDeviceId)
00101                                      where frontProfile.Id == backProfile.Id
00102                                      select new { frontProfile, backProfile }).FirstOrDefault();
00103
00104             if (concurrentProfile != null)
00105             {
00106                 mediaInitSettingsFront.VideoProfile = concurrentProfile.frontProfile;
00107                 mediaInitSettingsBack.VideoProfile = concurrentProfile.backProfile;
00108                 concurrencySupported = true;
00109
00110                 await LogStatus("Concurrent profile located, device supports concurrency", NotifyType.StatusMessage);
00111             }
00112             else
00113             {
00114                 // There are no concurrent profiles available on this device, thus
00115                 // there is not profile to select. With a lack of concurrent profile
00116                 // each camera will have to be managed manually and cannot support
00117                 // simultaneous streams. So we set the Video profile to null to
00118                 // indicate that camera must be managed individually.
00119                 mediaInitSettingsFront.VideoProfile = null;
00120                 mediaInitSettingsBack.VideoProfile = null;
00121
00122                 await LogStatus("No Concurrent profiles located, device does not support concurrency", NotifyType.ErrorMessage);
00123             }
00124
00125             await LogStatusToOutputBox("Initializing Front camera settings");
00126             await mediaCaptureFront.InitializeAsync(mediaInitSettingsFront);
00127             if (concurrencySupported)
00128             {
00129                 await LogStatusToOutputBox("Device supports concurrency, initializing Back camera settings");
00130
00131                 // Only initialize the back camera if concurrency is available.  Otherwise,
00132                 // we can only use one camera at a time (which in this case will be the front
00133                 // camera).
00134                 await mediaCaptureBack.InitializeAsync(mediaInitSettingsBack);
00135             }
00136         }
00137
00138         /// <summary>
00139         /// Helper method to obtain a device Id that supports a Video Profile.
00140         /// If no Video Profile is found we return empty string indicating that there isn't a device on
00141         /// the desired panel with a supported Video Profile.
00142         /// </summary>
00143         /// <param name="panel">Contains Device Enumeration information regarding camera panel we are looking for</param>
00144         /// <returns>Device Information Id string</returns>
00145         public async Task<string> GetVideoProfileSupportedDeviceIdAsync(Windows.Devices.Enumeration.Panel panel)
00146         {
00147             string deviceId = string.Empty;
00148
00149             // Finds all video capture devices
00150             DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
00151             await LogStatusToOutputBox(string.Format(CultureInfo.InvariantCulture, "Number of video capture devices found: {0}", devices.Count.ToString()));
00152
00153             foreach (var device in devices)
00154             {
00155                 // Check if the device on the requested panel supports Video Profile
00156                 if (MediaCapture.IsVideoProfileSupported(device.Id) && device.EnclosureLocation.Panel == panel)
00157                 {
00158                     // We've located a device that supports Video Profiles on expected panel
00159                     deviceId = device.Id;
00160                     break;
00161                 }
00162             }
00163
00164             return deviceId;
00165         }
00166
00167         /// <summary>
00168         /// Marshall log message to the UI thread
00169         /// and update outputBox, this method is for more general messages
00170         /// </summary>
00171         /// <param name="message">Message to log to the outputBox</param>
00172         private async Task LogStatusToOutputBox(string message)
00173         {
00174             await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00175             {
00176                 outputBox.Text += message + "\r\n";
00177                 outputScrollViewer.ChangeView(0, outputBox.ActualHeight, 1);
00178             });
00179         }
00180
00181         /// <summary>
00182         /// Method to log Status to Main Status block,
00183         /// this method is for important status messages to be
00184         /// displayed at bottom of scenario page
00185         /// </summary>
00186         /// <param name="message">Message to log to the output box</param>
00187         /// <param name="type">Notification Type for status message</param>
00188         private async Task LogStatus(string message, NotifyType type)
00189         {
00190             await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00191             {
00192                 rootPage.NotifyUser(message, type);
00193             });
00194             await LogStatusToOutputBox(message);
00195         }
00196     }
00197
00198 }
Generated on Fri Nov 15 2024 22:18:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Helpers Member List

This is the complete list of members for Helpers, including all inherited members.
AddAppContentFilesToIndexedFolder() | Helpers | [inline, static]
AddItemsToIndex(Windows.Storage.Search.ContentIndexer indexer) | Helpers | [inline, static]
AppendLine(TextBlock textBlock, string message) | Helpers | [inline, static]
CostGuidance enum name | Helpers | [private]
CreateHttpClientWithPlugIn() | Helpers | [inline, private, static]
CreateItemString(string itemKey, IEnumerable< string > propertyKeys, IReadOnlyDictionary< string, object > properties) | Helpers | [inline, static]
CreateItemString(string itemKey, IEnumerable< string > propertyKeys, IDictionary< string, object > properties) | Helpers | [inline, static]
DisplayTextResultAsync(HttpResponseMessage response, TextBox output, CancellationToken token) | Helpers | [inline, private, static]
DisplayWebError(MainPage rootPage, Exception exception) | Helpers | [inline, private, static]
E_INVALID_STATE | Helpers | [private]
EvaluateAndReportConnectionCost(ConnectionCost connectionCost, TextBlock textBlock) | Helpers | [inline, static]
EvaluateCostAndConnectAsync(ConnectionCost connectionCost, bool optedInToCharges, TextBlock textBlock) | Helpers | [inline, static]
GetFriendlyName(TetheringWiFiBand value) | Helpers | [inline, static]
GetFriendlyName(TetheringWiFiAuthenticationKind value) | Helpers | [inline, static]
GetNetworkCostGuidance(ConnectionCost connectionCost) | Helpers | [inline, private, static]
GetSelectedItemTag< T >(Selector selector) | Helpers | [inline, static]
InitializeRevisionNumber() | Helpers | [inline, static]
IsBandSupported(NetworkOperatorTetheringAccessPointConfiguration configuration, TetheringWiFiBand band) | Helpers | [inline, static]
OnIndexerOperationBegin() | Helpers | [inline, static]
OnIndexerOperationComplete(Windows.Storage.Search.ContentIndexer indexer) | Helpers | [inline, static]
ParseUIntWithFallback(TextBox textBox, double fallback) | Helpers | [inline, static]
ReplaceQueryString(TextBox addressField, string newQueryString) | Helpers | [inline, private, static]
ScenarioCompleted(Button startButton, Button cancelButton) | Helpers | [inline, private, static]
ScenarioStarted(Button startButton, Button cancelButton, TextBox outputField) | Helpers | [inline, private, static]
SendHttpGetRequestAsync() | Helpers | [inline, private, static]
SerializeHeaderCollection(IEnumerable< KeyValuePair< string, string >> headers, StringBuilder output) | Helpers | [inline, private, static]
SerializeHeaders(HttpResponseMessage response) | Helpers | [inline, private, static]
ShouldAttemptToConnectToInternet(NetworkConnectivityLevel connectivityLevel) | Helpers | [inline, static]
StringifyProperty(object property) | Helpers | [inline, static]
TryGetCurrentNetworkOperatorTetheringManager() | Helpers | [inline, static]
TryParseHttpUri(string uriString) | Helpers | [inline, private, static]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_DataEventsBatching Member List

This is the complete list of members for Scenario5_DataEventsBatching, including all inherited members.
accelerometer | Scenario5_DataEventsBatching | [private]
desiredReportInterval | Scenario5_DataEventsBatching | [private]
desiredReportLatency | Scenario5_DataEventsBatching | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario5_DataEventsBatching | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario5_DataEventsBatching | [inline, protected]
ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e) | Scenario5_DataEventsBatching | [inline, private]
rootPage | Scenario5_DataEventsBatching | [private]
Scenario5_DataEventsBatching() | Scenario5_DataEventsBatching | [inline]
ScenarioDisable() | Scenario5_DataEventsBatching | [inline, private]
ScenarioEnable() | Scenario5_DataEventsBatching | [inline, private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario5_DataEventsBatching | [inline, private]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cpp/pch.h Source File

  • WebSocket
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // pch.h
00014 // Header for standard system include files.
00015 //
00016
00017 #pragma once
00018
00019 #include <collection.h>
00020 #include <ppltasks.h>
00021 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_ReadWrite Member List

This is the complete list of members for Scenario3_ReadWrite, including all inherited members.
CancelAllIoTasks() | Scenario3_ReadWrite | [inline, private]
CancelReadTask() | Scenario3_ReadWrite | [inline, private]
CancelWriteTask() | Scenario3_ReadWrite | [inline, private]
DataReaderObject | Scenario3_ReadWrite | [private]
DataWriteObject | Scenario3_ReadWrite | [private]
Dispose() | Scenario3_ReadWrite | [inline]
IsNavigatedAway | Scenario3_ReadWrite | [private]
IsPerformingRead() | Scenario3_ReadWrite | [inline, private]
IsPerformingWrite() | Scenario3_ReadWrite | [inline, private]
IsReadTaskPending | Scenario3_ReadWrite | [private]
IsWriteTaskPending | Scenario3_ReadWrite | [private]
NotifyReadCancelingTask() | Scenario3_ReadWrite | [inline, private]
NotifyReadTaskCanceled() | Scenario3_ReadWrite | [inline, private]
NotifyWriteCancelingTask() | Scenario3_ReadWrite | [inline, private]
NotifyWriteTaskCanceled() | Scenario3_ReadWrite | [inline, private]
OnNavigatedFrom(NavigationEventArgs eventArgs) | Scenario3_ReadWrite | [inline, protected]
OnNavigatedTo(NavigationEventArgs eventArgs) | Scenario3_ReadWrite | [inline, protected]
ReadAsync(CancellationToken cancellationToken) | Scenario3_ReadWrite | [inline, private]
ReadButton_Click(object sender, RoutedEventArgs e) | Scenario3_ReadWrite | [inline, private]
ReadBytesCounter | Scenario3_ReadWrite | [private]
ReadCancelButton_Click(object sender, RoutedEventArgs e) | Scenario3_ReadWrite | [inline, private]
ReadCancellationTokenSource | Scenario3_ReadWrite | [private]
ReadCancelLock | Scenario3_ReadWrite | [private]
ReadTimeoutButton_Click(object sender, RoutedEventArgs e) | Scenario3_ReadWrite | [inline, private]
ResetReadCancellationTokenSource() | Scenario3_ReadWrite | [inline, private]
ResetWriteCancellationTokenSource() | Scenario3_ReadWrite | [inline, private]
rootPage | Scenario3_ReadWrite | [private]
Scenario3_ReadWrite() | Scenario3_ReadWrite | [inline]
UpdateReadButtonStates() | Scenario3_ReadWrite | [inline, private]
UpdateReadBytesCounterView() | Scenario3_ReadWrite | [inline, private]
UpdateReadTimeoutView() | Scenario3_ReadWrite | [inline, private]
UpdateWriteButtonStates() | Scenario3_ReadWrite | [inline, private]
UpdateWriteBytesCounterView() | Scenario3_ReadWrite | [inline, private]
UpdateWriteTimeoutView() | Scenario3_ReadWrite | [inline, private]
WriteAsync(CancellationToken cancellationToken) | Scenario3_ReadWrite | [inline, private]
WriteButton_Click(object sender, RoutedEventArgs e) | Scenario3_ReadWrite | [inline, private]
WriteBytesAvailable | Scenario3_ReadWrite | [private]
WriteBytesCounter | Scenario3_ReadWrite | [private]
WriteBytesInputValue_GotFocus(object sender, RoutedEventArgs e) | Scenario3_ReadWrite | [inline, private]
WriteBytesInputValue_TextChanged(object sender, TextChangedEventArgs e) | Scenario3_ReadWrite | [inline, private]
WriteCancelButton_Click(object sender, RoutedEventArgs e) | Scenario3_ReadWrite | [inline, private]
WriteCancellationTokenSource | Scenario3_ReadWrite | [private]
WriteCancelLock | Scenario3_ReadWrite | [private]
WriteTimeoutButton_Click(object sender, RoutedEventArgs e) | Scenario3_ReadWrite | [inline, private]
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CalligraphicPen Member List

This is the complete list of members for CalligraphicPen, including all inherited members.
CalligraphicPen() | CalligraphicPen | [inline]
CreateInkDrawingAttributesCore(Brush brush, double strokeWidth) | CalligraphicPen | [inline, protected]
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

XmlLoading Member List

This is the complete list of members for XmlLoading, including all inherited members.
LaunchUri(object sender, RoutedEventArgs e) | XmlLoading | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | XmlLoading | [inline, protected]
rootPage | XmlLoading | [private]
Scenario3BtnBuffer_Click(object sender, RoutedEventArgs e) | XmlLoading | [inline, private]
Scenario3BtnFile_Click(object sender, RoutedEventArgs e) | XmlLoading | [inline, private]
Scenario3Init() | XmlLoading | [inline, private]
XmlLoading() | XmlLoading | [inline]
Generated on Fri Nov 15 2024 22:24:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePickerContracts/cs/FileOpenPicker_PickAppFile.xaml.cs Source File

  • FilePickerContracts
  • cs

FileOpenPicker_PickAppFile.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using SDKTemplate;
00012
00013 using System;
00014 using Windows.ApplicationModel;
00015 using Windows.Foundation;
00016 using Windows.Storage;
00017 using Windows.Storage.Pickers.Provider;
00018 using Windows.UI.Core;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace FilePickerContracts
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class FileOpenPicker_PickAppFile : Page
00029     {
00030         private const string id = "MyLocalFile";
00031         FileOpenPickerUI fileOpenPickerUI = FileOpenPickerPage.Current.fileOpenPickerUI;
00032         CoreDispatcher dispatcher = Window.Current.Dispatcher;
00033
00034         public FileOpenPicker_PickAppFile()
00035         {
00036             this.InitializeComponent();
00037             AddLocalFileButton.Click += new RoutedEventHandler(AddLocalFileButton_Click);
00038             RemoveLocalFileButton.Click += new RoutedEventHandler(RemoveLocalFileButton_Click);
00039         }
00040
00041         private void UpdateButtonState(bool fileInBasket)
00042         {
00043             AddLocalFileButton.IsEnabled = !fileInBasket;
00044             RemoveLocalFileButton.IsEnabled = fileInBasket;
00045         }
00046
00047         protected override void OnNavigatedTo(NavigationEventArgs e)
00048         {
00049             UpdateButtonState(fileOpenPickerUI.ContainsFile(id));
00050         }
00051
00052         private async void AddLocalFileButton_Click(object sender, RoutedEventArgs e)
00053         {
00054             StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\squareTile-sdk.png");
00055             bool inBasket;
00056             switch (fileOpenPickerUI.AddFile(id, file))
00057             {
00058                 case AddFileResult.Added:
00059                 case AddFileResult.AlreadyAdded:
00060                     inBasket = true;
00061                     OutputTextBlock.Text = Status.FileAdded;
00062                     break;
00063
00064                 default:
00065                     inBasket = false;
00066                     OutputTextBlock.Text = Status.FileAddFailed;
00067                     break;
00068             }
00069             UpdateButtonState(inBasket);
00070         }
00071
00072         private void RemoveLocalFileButton_Click(object sender, RoutedEventArgs e)
00073         {
00074             if (fileOpenPickerUI.ContainsFile(id))
00075             {
00076                 fileOpenPickerUI.RemoveFile(id);
00077                 OutputTextBlock.Text = Status.FileRemoved;
00078             }
00079             UpdateButtonState(false);
00080         }
00081     }
00082 }
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VertexPositionTex Member List

This is the complete list of members for VertexPositionTex, including all inherited members.
pos | VertexPositionTex
tex | VertexPositionTex
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackButton/cpp/SampleConfiguration.cpp Source File

  • BackButton
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Scenario 1", "SDKTemplate.Scenario1" }
00021 };
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Capabilities/cs/SampleConfiguration.cs Source File

  • Capabilities
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Capabilities";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Check capability and set display message", ClassType=typeof(Scenario1_Check)},
00025             new Scenario() { Title="Request multiple capabilities", ClassType=typeof(Scenario2_RequestMany)},
00026         };
00027     }
00028
00029     public class Scenario
00030     {
00031         public string Title { get; set; }
00032         public Type ClassType { get; set; }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cpp/Scenario2_AdvertiserAccept.xaml.h Source File

  • WiFiDirectServices
  • cpp

Scenario2_AdvertiserAccept.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_AdvertiserAccept.g.h"
00015
00016 namespace SDKTemplate
00017 {
00018     namespace WiFiDirectServices
00019     {
00020         /// <summary>
00021         /// Helper class to display session requests in list with extra data
00022         /// </summary>
00023         [Windows::UI::Xaml::Data::Bindable]
00024         public ref class SessionRequestWrapper sealed
00025         {
00026         public:
00027             SessionRequestWrapper(
00028                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionRequest^ request,
00029                 AdvertisementWrapper^ advertisement
00030                 );
00031
00032             property Platform::String^ Id;
00033             property Platform::String^ ProvisioningInfo;
00034             property Platform::String^ Pin;
00035             property Windows::Storage::Streams::IBuffer^ SessionInfo;
00036
00037             property AdvertisementWrapper^ Advertisement;
00038         };
00039
00040         /// <summary>
00041         /// UI exposing an interface to accept/decline incoming connection requests as an advertiser
00042         /// and to interact with connected sessions
00043         ///
00044         /// Most of the actual logic for Wi-Fi Direct Services is in WiFiDirectServicesManager.h/cpp and WiFiDirectServicesWrappers.h/cpp
00045         /// </summary>
00046         [Windows::Foundation::Metadata::WebHostHidden]
00047         public ref class Scenario2 sealed
00048         {
00049         public:
00050             Scenario2();
00051
00052             void AddSessionRequest(
00053                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionRequest^ request,
00054                 AdvertisementWrapper^ advertiser
00055                 );
00056
00057             void RemoveSessionRequest(
00058                 Windows::Devices::WiFiDirect::Services::WiFiDirectServiceSessionRequest^ request,
00059                 AdvertisementWrapper^ advertiser
00060                 );
00061
00062             void AddAdvertiser(AdvertisementWrapper^ advertiser);
00063
00064             void RemoveAdvertiser(unsigned int index);
00065
00066             void AddSession(SessionWrapper^ session);
00067
00068             void RemoveSession(unsigned int index);
00069
00070             void UpdateAdvertiserStatus(AdvertisementWrapper^ advertiser);
00071
00072         protected:
00073             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00074
00075             virtual void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e) override;
00076
00077         private:
00078             SDKTemplate::MainPage^ _rootPage;
00079             std::mutex _mutex;
00080
00081             void Accept_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00082
00083             void Decline_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00084
00085             void CloseSession_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00086
00087             void SelectSession_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00088
00089             void StopAdvertisement_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00090         };
00091     }
00092 }
Generated on Fri Nov 15 2024 22:22:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

TargetTexture Member List

This is the complete list of members for TargetTexture, including all inherited members.
CreateHitTextureResourceView(_In_ winrt::hstring const &name, _Out_ ID3D11ShaderResourceView **textureResourceView) | TargetTexture |
CreateTextureResourceView(_In_ winrt::hstring const &name, _Out_ ID3D11ShaderResourceView **textureResourceView) | TargetTexture |
m_blackBrush | TargetTexture | [private]
m_blueBrush | TargetTexture | [private]
m_circleGeometry1 | TargetTexture | [private]
m_circleGeometry2 | TargetTexture | [private]
m_circleGeometry3 | TargetTexture | [private]
m_circleGeometry4 | TargetTexture | [private]
m_circleGeometry5 | TargetTexture | [private]
m_clearBrush | TargetTexture | [private]
m_d2dContext | TargetTexture | [private]
m_d2dFactory | TargetTexture | [private]
m_d3dDevice | TargetTexture | [private]
m_dwriteFactory | TargetTexture | [private]
m_greenBrush | TargetTexture | [private]
m_redBrush | TargetTexture | [private]
m_textFormat | TargetTexture | [private]
m_whiteBrush | TargetTexture | [private]
m_yellowBrush | TargetTexture | [private]
TargetTexture(_In_ winrt::com_ptr< ID3D11Device3 > d3dDevice, _In_ ID2D1Factory1 *d2dFactory, _In_ IDWriteFactory1 *dwriteFactory, _In_ ID2D1DeviceContext *d2dContext) | TargetTexture |
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_TriggerCFU Member List

This is the complete list of members for Scenario5_TriggerCFU, including all inherited members.
CreateFileButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario5_TriggerCFU |
GetFileFromFutureAccessListButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario5_TriggerCFU |
m_faToken | Scenario5_TriggerCFU | [private]
PickAFileButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario5_TriggerCFU |
SaveToFutureAccessListButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario5_TriggerCFU |
Scenario5_TriggerCFU() | Scenario5_TriggerCFU |
UpdateButtons() | Scenario5_TriggerCFU | [private]
WriteToFileButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario5_TriggerCFU |
WriteToFileWithExplicitCFUButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario5_TriggerCFU |
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cpp/Server/pch.cpp Source File

  • ProxyStubsForWinRTComponents
  • cpp
  • Server

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LiveDash/cs/LiveDash/LiveDashPlayer.cs Source File

  • LiveDash
  • cs
  • LiveDash

LiveDashPlayer.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Threading.Tasks;
00003 using LiveDash.Models;
00004 using Windows.UI.Xaml.Controls;
00005 using Windows.Media.Core;
00006 using LiveDash.Util;
00007 using Windows.Media.Streaming.Adaptive;
00008 using Windows.Data.Xml.Dom;
00009 using Windows.Storage;
00010
00011 namespace LiveDash
00012 {
00013     public class LiveDashPlayer : ILivePlayer
00014     {
00015         Player player;
00016         private bool haveSetLiveOffset;
00017         private TimeSpan liveOffset;
00018
00019         /// <summary>
00020         /// Sets the offset of where to start playback from the
00021         /// most recent available segment.
00022         /// </summary>
00023         /// <param name="offset">the offset duration, in hns</param>
00024         public void DesiredLiveOffset(TimeSpan offset)
00025         {
00026             haveSetLiveOffset = true;
00027             liveOffset = offset;
00028         }
00029
00030         /// <summary>
00031         /// Goes to the live edge. This is the most recent available
00032         /// segment minus the desired live offset
00033         /// </summary>
00034         public void GoToLive()
00035         {
00036             if (player != null)
00037             {
00038                 if (haveSetLiveOffset)
00039                 {
00040                     player.HasLiveOffsetValue = true;
00041                     player.LiveOffset = liveOffset;
00042                 }
00043                 player.GoToLiveEdge();
00044             }
00045         }
00046
00047         /// <summary>
00048         /// Downloads the manifest from the given source, parses the manifest
00049         /// and sets the source on the media element
00050         /// </summary>
00051         /// <param name="source">The URL of the source MPD</param>
00052         /// <param name="mediaElement">The MediaElement to start playback</param>
00053         /// <returns></returns>
00054         public async Task Initialize(Uri source, MediaElement mediaElement)
00055         {
00056             //1) Download manifest
00057             var sourceUrlText = source.AbsoluteUri;
00058             try
00059             {
00060                 var manifest = new Manifest(sourceUrlText);
00061                 var document = await manifest.LoadManifestAsync(sourceUrlText);
00062
00063                 //2) Parse manifest
00064                 DashManifestParser mpdParser = new DashManifestParser(document, ref manifest);
00065                 if (mpdParser.Parse())
00066                 {
00067
00068                     if (!manifest.IsSupportedProfile)
00069                     {
00070 #if DEBUG
00071                         Logger.Log("The profiles attribute does not contain the \"urn:mpeg:dash:profile:isoff-live:2011\" profile, so it may not work as expected.");
00072 #endif
00073                     }
00074                     if (manifest.IsLive)
00075                     {
00076                         //3) Play using MSE if it is live
00077                         MseStreamSource mseSource = new MseStreamSource();
00078                         player = new Player(mediaElement, mseSource, manifest);
00079                         if (haveSetLiveOffset && manifest.IsLive)
00080                         {
00081                             player.HasLiveOffsetValue = true;
00082                             player.LiveOffset = liveOffset;
00083                         }
00084                         player.Initialize();
00085                     }
00086                     else
00087                     {
00088                         // Otherwise, use our Adaptive Media Source for on demand content
00089                         var result = await AdaptiveMediaSource.CreateFromUriAsync(source);
00090                         if (result.Status != AdaptiveMediaSourceCreationStatus.Success)
00091                         {
00092                             throw new Exception("Unable to create media source because: " + result.Status);
00093                         }
00094                         var adaptiveSource = result.MediaSource;
00095
00096                         mediaElement.SetMediaStreamSource(adaptiveSource);
00097                         mediaElement.Play();
00098                     }
00099
00100
00101                 }
00102
00103                 else
00104                 {
00105 #if DEBUG
00106                     Logger.Log("The Parser failed to parse this mpd");
00107 #endif
00108                     return;
00109                 }
00110             }
00111             catch (Exception e)
00112             {
00113 #if DEBUG
00114                 Logger.Log("Exception when initializing player: " + e.Message + " " + Logger.Display(e));
00115 #endif
00116             }
00117         }
00118
00119         /// <summary>
00120         /// Stops the Timer
00121         /// </summary>
00122         public void Close()
00123         {
00124             if (player != null)
00125             {
00126                 player.Close();
00127                 player = null;
00128             }
00129         }
00130     }
00131 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/SphereMesh.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

SphereMesh.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SphereMesh.h"
00014 #include "ConstantBuffers.h"
00015
00016 using namespace DirectX;
00017
00018 SphereMesh::SphereMesh(_In_ winrt::com_ptr<ID3D11Device3> const& device, uint16_t segments)
00019 {
00020     D3D11_BUFFER_DESC bd = { 0 };
00021     D3D11_SUBRESOURCE_DATA initData = { 0 };
00022
00023     uint16_t slices = segments / 2;
00024     uint16_t numVertices = (slices + 1) * (segments + 1) + 1;
00025     uint16_t numIndices = slices * segments * 3 * 2;
00026
00027     std::vector<PNTVertex> point(numVertices);
00028     std::vector<uint16_t> index(numIndices);
00029
00030     // To make the texture look right on the top and bottom of the sphere
00031     // each slice will have 'segments + 1' vertices. The top and bottom
00032     // vertices will all be coincident, but have different U texture cooordinates.
00033     uint16_t p = 0;
00034     for (uint16_t a = 0; a <= slices; a++)
00035     {
00036         float angle1 = static_cast<float>(a) / static_cast<float>(slices) * XM_PI;
00037         float z = cos(angle1);
00038         float r = sin(angle1);
00039         for (uint16_t b = 0; b <= segments; b++)
00040         {
00041             float angle2 = static_cast<float>(b) / static_cast<float>(segments) * XM_2PI;
00042             point[p].position = XMFLOAT3(r * cos(angle2), r * sin(angle2), z);
00043             point[p].normal = point[p].position;
00044             point[p].textureCoordinate = XMFLOAT2((1.0f - z) / 2.0f, static_cast<float>(b) / static_cast<float>(segments));
00045             p++;
00046         }
00047     }
00048     m_vertexCount = p;
00049
00050     p = 0;
00051     for (uint16_t a = 0; a < slices; a++)
00052     {
00053         uint16_t p1 = a * (segments + 1);
00054         uint16_t p2 = (a + 1) * (segments + 1);
00055
00056         // Generate two triangles for each segment around the slice.
00057         for (uint16_t b = 0; b < segments; b++)
00058         {
00059             if (a < (slices - 1))
00060             {
00061                 // For all but the bottom slice add the triangle with one
00062                 // vertex in the a slice and two vertices in the a + 1 slice.
00063                 // Skip it for the bottom slice since the triangle would be
00064                 // degenerate as all the vertices in the bottom slice are coincident.
00065                 index[p] = b + p1;
00066                 index[p + 1] = b + p2;
00067                 index[p + 2] = b + p2 + 1;
00068                 p = p + 3;
00069             }
00070             if (a > 0)
00071             {
00072                 // For all but the top slice add the triangle with two
00073                 // vertices in the a slice and one vertex in the a + 1 slice.
00074                 // Skip it for the top slice since the triangle would be
00075                 // degenerate as all the vertices in the top slice are coincident.
00076                 index[p] = b + p1;
00077                 index[p + 1] = b + p2 + 1;
00078                 index[p + 2] = b + p1 + 1;
00079                 p = p + 3;
00080             }
00081         }
00082     }
00083     m_indexCount = p;
00084
00085     bd.Usage = D3D11_USAGE_DEFAULT;
00086     bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount;
00087     bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00088     bd.CPUAccessFlags = 0;
00089     initData.pSysMem = point.data();
00090     winrt::check_hresult(
00091         device->CreateBuffer(&bd, &initData, m_vertexBuffer.put())
00092         );
00093
00094     bd.Usage = D3D11_USAGE_DEFAULT;
00095     bd.ByteWidth = sizeof(uint16_t) * m_indexCount;
00096     bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
00097     bd.CPUAccessFlags = 0;
00098     initData.pSysMem = index.data();
00099     winrt::check_hresult(
00100         device->CreateBuffer(&bd, &initData, m_indexBuffer.put())
00101         );
00102 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CacheChangedEventArgs-g< T > Member List

This is the complete list of members for CacheChangedEventArgs-g< T >, including all inherited members.
itemIndex | CacheChangedEventArgs-g< T >
newItem | CacheChangedEventArgs-g< T >
oldItem | CacheChangedEventArgs-g< T >
Generated on Fri Nov 15 2024 22:23:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario7.xaml.h Source File

  • MapControl
  • cpp

Scenario7.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario7.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     // A PlaceLocation represents a location in two forms:
00020     // Geoposition (latitude, longitude, altitude)
00021     // Normalized map coordinates in the unit square from (0,0) to (1,1)
00022     struct PlaceLocation
00023     {
00024         PlaceLocation(double latitude, double longitude);
00025         Windows::Devices::Geolocation::BasicGeoposition Geoposition;
00026         Windows::Foundation::Point MapCoordinates;
00027     private:
00028         static Windows::Foundation::Point GetMapCoordinates(double latitude, double longitude);
00029     };
00030
00031     struct PlaceInfo
00032     {
00033         Platform::String^ Name;
00034         PlaceLocation Location;
00035     };
00036
00037     // A cluster is a group of places that are at almost the same location.
00038     struct Cluster
00039     {
00040         PlaceLocation Location;
00041         std::vector<PlaceInfo> Places;
00042     };
00043
00044     [Windows::Foundation::Metadata::WebHostHidden]
00045     public ref class Scenario7 sealed
00046     {
00047     public:
00048         Scenario7();
00049     private:
00050         MainPage^ rootPage = MainPage::Current;
00051         std::array<Windows::Storage::Streams::RandomAccessStreamReference^, 8> numberIconReferences;
00052         std::vector<PlaceInfo> places;
00053         std::map<int, std::vector<Cluster>> clustersForZoomLevel;
00054         int previousZoomLevel = 0;
00055
00056         Concurrency::task<void> LoadPlaceInfoAsync();
00057         void myMap_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00058         void myMap_ZoomLevelChanged(Windows::UI::Xaml::Controls::Maps::MapControl^ sender, Platform::Object^ args);
00059         void refreshMapIcons();
00060         const std::vector<Cluster>& GetClustersForZoomLevel(int zoomLevel);
00061         std::vector<Cluster> BuildClustersForZoomLevel(int zoomLevel);
00062         static bool ArePointsNear(Windows::Foundation::Point point1, Windows::Foundation::Point point2, double threshold);
00063         PlaceLocation CalculateCenter(const std::vector<PlaceInfo>& places);
00064     };
00065 }
Generated on Fri Nov 15 2024 22:18:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/ComputeShader/CustomComputeShaderRenderer.h Source File

  • D2DCustomEffects
  • cpp
  • ComputeShader

CustomComputeShaderRenderer.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "DeviceResources.h"
00015 #include "DftEffect.h"
00016
00017 namespace CustomComputeShader
00018 {
00019     // This sample renderer instantiates a basic rendering pipeline.
00020     class CustomComputeShaderRenderer
00021     {
00022     public:
00023         CustomComputeShaderRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00024         void CreateDeviceIndependentResources();
00025         void CreateDeviceDependentResources();
00026         void CreateWindowSizeDependentResources();
00027         void ReleaseDeviceDependentResources();
00028         void Update() {};
00029         void Render();
00030
00031         // Process lifetime management handlers.
00032         void SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state) {};
00033         void LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state) {};
00034
00035     private:
00036         void UpdateImageScale(float scale);
00037
00038     private:
00039         // Cached pointer to device resources.
00040         std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00041         Microsoft::WRL::ComPtr<IWICFormatConverter>         m_formatConvert;
00042         Microsoft::WRL::ComPtr<ID2D1ImageSourceFromWic>     m_imageSource;
00043         Microsoft::WRL::ComPtr<ID2D1TransformedImageSource> m_transformedImage;
00044         Microsoft::WRL::ComPtr<ID2D1Effect>                 m_dftEffect;
00045
00046         bool                                                m_isWindowClosed;
00047         D2D1_SIZE_U                                         m_imageSize;
00048         float                                               m_scale;
00049     };
00050 }
00051
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/pch.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

pch.h

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 // Windows Header Files:
00011 #include <windows.h>
00012 #include <mfidl.h>
00013 #include <mfapi.h>
00014 #include <mferror.h>
00015
00016 #include <assert.h>
00017
00018 #include <tchar.h>
00019 #include <Strsafe.h>
00020
00021 #include <windows.foundation.h>
00022 #include <windows.foundation.collections.h>
00023 #include <windows.media.h>
00024 #include <windows.media.capture.h>
00025 #include <windows.media.mediaproperties.h>
00026 #include <windows.networking.sockets.h>
00027
00028 #include <wrl\client.h>
00029 #include <wrl\implements.h>
00030 #include <wrl\ftm.h>
00031 #include <wrl\event.h>
00032 #include <wrl\wrappers\corewrappers.h>
00033
00034 using namespace Platform;
00035 using namespace Microsoft::WRL;
00036 using namespace Microsoft::WRL::Wrappers;
00037 using namespace Windows::Foundation;
00038 using namespace Windows::Foundation::Collections;
00039 using namespace Windows::Storage::Streams;
00040 using namespace Windows::Networking;
00041 using namespace Windows::Networking::Sockets;
00042 using namespace Windows::Media;
00043 using namespace Windows::Media::Capture;
00044 using namespace Windows::Media::MediaProperties;
00045
00046 #include "Trace.h"
00047 #include <CritSec.h>
00048
00049 #include <collection.h>
00050 #include <ppltasks.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cppwinrt/Scenario6_NumeralSystemTranslation.cpp Source File

  • NumberFormatting
  • cppwinrt

Scenario6_NumeralSystemTranslation.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario6_NumeralSystemTranslation.h"
00014 #include "Scenario6_NumeralSystemTranslation.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Globalization::NumberFormatting;
00019 using namespace Windows::UI::Xaml;
00020
00021 namespace winrt::SDKTemplate::implementation
00022 {
00023     Scenario6_NumeralSystemTranslation::Scenario6_NumeralSystemTranslation()
00024     {
00025         InitializeComponent();
00026     }
00027
00028     void Scenario6_NumeralSystemTranslation::Display_Click(IInspectable const&, RoutedEventArgs const&)
00029     {
00030         // Text for which translation of the numeral system will be performed.  Please note that translation only happens between
00031         // Latin and any other supported numeral system.  Translation between numeral systems is not a supported scenario.
00032         std::wstring stringToTranslate = L"These are the 10 digits of a numeral system: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9";
00033
00034         // Variable where we keep the results of the scenario
00035         std::wostringstream results;
00036         results << L"Original string: " << stringToTranslate << std::endl << std::endl;
00037
00038         // The numeral system translator is initialized based on the current application language.
00039         NumeralSystemTranslator numeralTranslator;
00040
00041         // Do translation
00042         results << L"Using application settings (" << std::wstring_view(numeralTranslator.NumeralSystem()) << L"): ";
00043         results << std::wstring_view(numeralTranslator.TranslateNumerals(stringToTranslate)) << std::endl;
00044
00045         // Switch to a different numeral system
00046         numeralTranslator.NumeralSystem(L"hanidec");
00047
00048         // Do translation
00049         results << "Using numeral system via property (" << std::wstring_view(numeralTranslator.NumeralSystem()) << L" ): ";
00050         results << std::wstring_view(numeralTranslator.TranslateNumerals(stringToTranslate)) << std::endl;
00051
00052         // Create a converter using a language list to initialize the numeral system to an appropriate default
00053         numeralTranslator = NumeralSystemTranslator({ L"ar-SA", L"en-US" });
00054
00055         // Do translation
00056         results << L"Using numeral system via language list (" << std::wstring_view(numeralTranslator.NumeralSystem()) << L"): ";
00057         results << std::wstring_view(numeralTranslator.TranslateNumerals(stringToTranslate)) << std::endl;
00058
00059         // Display the results.
00060         OutputTextBlock().Text(results.str());
00061     }
00062 }
Generated on Fri Nov 15 2024 22:20:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_ToggleMobileHotspot Member List

This is the complete list of members for Scenario2_ToggleMobileHotspot, including all inherited members.
m_tetheringManager | Scenario2_ToggleMobileHotspot | [private]
m_toggling | Scenario2_ToggleMobileHotspot | [private]
MobileHotspotToggle_Toggled(object sender, RoutedEventArgs e) | Scenario2_ToggleMobileHotspot | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_ToggleMobileHotspot | [inline, protected]
Scenario2_ToggleMobileHotspot() | Scenario2_ToggleMobileHotspot | [inline]
Generated on Fri Nov 15 2024 22:23:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/VideoGallery.xaml.cs Source File

  • 360VideoPlayback
  • cs

VideoGallery.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.ObjectModel;
00003 using Windows.ApplicationModel.Core;
00004 using Windows.Graphics.Holographic;
00005 using Windows.Perception.Spatial.Surfaces;
00006 using Windows.UI.Core;
00007 using Windows.UI.ViewManagement;
00008 using Windows.UI.Xaml;
00009 using Windows.UI.Xaml.Controls;
00010
00011
00012 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00013
00014 namespace _360VideoPlayback
00015 {
00016     /// <summary>
00017     /// An empty page that can be used on its own or navigated to within a Frame.
00018     /// </summary>
00019     public sealed partial class VideoGallery : Page
00020     {
00021         static public int mainviewId = 0;
00022
00023         public VideoGallery()
00024         {
00025             this.InitializeComponent();
00026             mainviewId = ApplicationView.GetForCurrentView().Id;
00027             this.Loaded += VideoGallery_Loaded;
00028         }
00029
00030         async private void GalleryGridView_ItemClick(object sender, ItemClickEventArgs e)
00031         {
00032             VideoItem selectedVideo = (VideoItem)e.ClickedItem;
00033             if (selectedVideo != null)
00034             {
00035                 if ((HolographicSpace.IsSupported && HolographicSpace.IsAvailable)
00036                     || SpatialSurfaceObserver.IsSupported())
00037                 {
00038                     var appViewSource = new AppViewSource(selectedVideo.SourceUri);
00039                     var appView = CoreApplication.CreateNewView(appViewSource);
00040                     await appView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
00041                     {
00042                         int appviewId = ApplicationView.GetForCurrentView().Id;
00043                         bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(appviewId, ViewSizePreference.Default, mainviewId, ViewSizePreference.Default);
00044                         System.Diagnostics.Debug.Assert(viewShown);
00045                     });
00046                 }
00047                 else
00048                 {
00049                     Frame.Navigate(typeof(PlaybackPage), selectedVideo.SourceUri);
00050                 }
00051             }
00052         }
00053
00054         private class VideoItemInfo
00055         {
00056             public string Title;
00057             public string Source;
00058         }
00059
00060         static VideoItemInfo[] sampleVideos =
00061         {
00062             // You can add more sample videos here.
00063             new VideoItemInfo { Title = "Sample Video", Source = "https://mediaplatstorage1.blob.core.windows.net/windows-universal-samples-media/SampleVideo.mp4" }
00064         };
00065
00066         private void VideoGallery_Loaded(object sender, RoutedEventArgs e)
00067         {
00068             ObservableCollection<VideoItem> videoList = new ObservableCollection<VideoItem>();
00069             foreach (var info in sampleVideos)
00070             {
00071                 videoList.Add(new VideoItem(info.Title, new Uri(info.Source)));
00072             }
00073
00074             GalleryGridView.ItemsSource = videoList;
00075         }
00076     }
00077 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Launch Member List

This is the complete list of members for Scenario2_Launch, including all inherited members.
CheckIf3DBuilderIsInstalled_Click(object sender, RoutedEventArgs e) | Scenario2_Launch | [inline, private]
LaunchAtSize_Click(object sender, RoutedEventArgs e) | Scenario2_Launch | [inline, private]
LaunchFileIn3DBuilder_Click(object sender, RoutedEventArgs e) | Scenario2_Launch | [inline, private]
LaunchInFullScreenModeCheckBox_Click(object sender, RoutedEventArgs e) | Scenario2_Launch | [inline, private]
PackageFamilyName3DBuilder | Scenario2_Launch | [private, static]
rootPage | Scenario2_Launch | [private]
Scenario2_Launch() | Scenario2_Launch | [inline]
Scenario2_Launch() | Scenario2_Launch | [inline]
Scenario2_Launch() | Scenario2_Launch | [inline]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/MrcEffectDefinitions/MrcVideoEffectDefinition.h Source File

  • HolographicMixedRealityCapture
  • cpp
  • MrcEffectDefinitions

MrcVideoEffectDefinition.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002 // This class provides an IAudioEffectDefinition which can be used
00003 // to configure and create a MixedRealityCaptureVideoEffect
00004 // object. See https://developer.microsoft.com/en-us/windows/holographic/mixed_reality_capture_for_developers#creating_a_custom_mixed_reality_capture_.28mrc.29_recorder
00005 // for more information about the effect definition properties.
00006
00007 #define RUNTIMECLASS_MIXEDREALITYCAPTURE_VIDEO_EFFECT L"Windows.Media.MixedRealityCapture.MixedRealityCaptureVideoEffect"
00008
00009 //
00010 // StreamType: Describe which capture stream this effect is used for.
00011 // Type: Windows::Media::Capture::MediaStreamType as UINT32
00012 // Default: VideoRecord
00013 //
00014 #define PROPERTY_STREAMTYPE L"StreamType"
00015
00016 //
00017 // HologramCompositionEnabled: Flag to enable or disable holograms in video capture.
00018 // Type: bool
00019 // Default: True
00020 //
00021 #define PROPERTY_HOLOGRAMCOMPOSITIONENABLED L"HologramCompositionEnabled"
00022
00023 //
00024 // RecordingIndicatorEnabled: Flag to enable or disable recording indicator on screen during hologram capturing.
00025 // Type: bool
00026 // Default: True
00027 //
00028 #define PROPERTY_RECORDINGINDICATORENABLED L"RecordingIndicatorEnabled"
00029
00030
00031 //
00032 // VideoStabilizationEnabled: Flag to enable or disable video stabilization powered by the HoloLens tracker.
00033 // Type : bool
00034 // Default: False
00035 //
00036 #define PROPERTY_VIDEOSTABILIZATIONENABLED L"VideoStabilizationEnabled"
00037
00038 //
00039 // VideoStabilizationBufferLength: Set how many historical frames are used for video stabilization.
00040 // Type : UINT32 (Max num is 30)
00041 // Default: 0
00042 //
00043 #define PROPERTY_VIDEOSTABILIZATIONBUFFERLENGTH L"VideoStabilizationBufferLength"
00044
00045 //
00046 // GlobalOpacityCoefficient: Set global opacity coefficient of hologram.
00047 // Type : float (0.0 to 1.0)
00048 // Default: 0.9
00049 //
00050 #define PROPERTY_GLOBALOPACITYCOEFFICIENT L"GlobalOpacityCoefficient"
00051
00052 //
00053 // BlankOnProtectedContent: Flag to enable or disable returning an empty frame if there is a 2d UWP app showing protected content.
00054 //                          If this flag is false and a 2d UWP app is showing protected content, the 2d UWP app will be replaced by
00055 //                          a protected content texture in the mixed reality capture.
00056 // Type : bool
00057 // Default: false
00058 //
00059 #define PROPERTY_BLANKONPROTECTEDCONTENT L"BlankOnProtectedContent"
00060
00061 //
00062 // ShowHiddenMesh: Flag to enable or disable showing the holographic camera's hidden area mesh and neighboring content.
00063 // Type : bool
00064 // Default: false
00065 //
00066 #define PROPERTY_SHOWHIDDENMESH L"ShowHiddenMesh"
00067
00068 //
00069 // OutputSize: Set the desired output size after cropping for video stabilization. A default crop size is chosen if 0 or an invalid output size is specified.
00070 // Type : Windows.Foundation.Size
00071 // Default: (0,0)
00072 //
00073 #define PROPERTY_OUTPUTSIZE L"OutputSize"
00074
00075 //
00076 // PreferredHologramPerspective: Enum used to indicate which holographic camera view configuration should be captured
00077 // Type: MixedRealityCapturePerspective as UINT32
00078 // 0: App won't be asked to render from the photo/video camera
00079 // 1: App is rendered from the photo/video camera
00080 // Default: 1
00081 //
00082 #define PROPERTY_PREFERREDHOLOGRAMPERSPECTIVE L"PreferredHologramPerspective"
00083
00084 //
00085 // Maximum value of VideoStabilizationBufferLength
00086 // This number is defined and used in MixedRealityCaptureVideoEffect
00087 //
00088 #define PROPERTY_MAX_VSBUFFER 30U
00089
00090 namespace MrcEffectDefinitions
00091 {
00092     public enum class MixedRealityCapturePerspective
00093     {
00094         Display = 0,
00095         PhotoVideoCamera = 1,
00096     };
00097
00098     public ref class MrcVideoEffectDefinition sealed : public Windows::Media::Effects::IVideoEffectDefinition
00099     {
00100     public:
00101         MrcVideoEffectDefinition();
00102
00103         //
00104         // IVideoEffectDefinition
00105         //
00106         property Platform::String^ ActivatableClassId
00107         {
00108             virtual Platform::String^ get()
00109             {
00110                 return m_activatableClassId;
00111             }
00112         }
00113
00114         property Windows::Foundation::Collections::IPropertySet^ Properties
00115         {
00116             virtual Windows::Foundation::Collections::IPropertySet^ get()
00117             {
00118                 return m_propertySet;
00119             }
00120         }
00121
00122         //
00123         // Mixed Reality Capture effect properties
00124         //
00125         property Windows::Media::Capture::MediaStreamType StreamType
00126         {
00127             Windows::Media::Capture::MediaStreamType get()
00128             {
00129                 return GetValueFromPropertySet<uint32_t>(m_propertySet, PROPERTY_STREAMTYPE, DefaultStreamType);
00130             }
00131
00132             void set(Windows::Media::Capture::MediaStreamType newValue)
00133             {
00134                 m_propertySet->Insert(PROPERTY_STREAMTYPE, static_cast<uint32_t>(newValue));
00135             }
00136         }
00137
00138         property bool HologramCompositionEnabled
00139         {
00140             bool get()
00141             {
00142                 return GetValueFromPropertySet<bool>(m_propertySet, PROPERTY_HOLOGRAMCOMPOSITIONENABLED, DefaultHologramCompositionEnabled);
00143             }
00144
00145             void set(bool newValue)
00146             {
00147                 m_propertySet->Insert(PROPERTY_HOLOGRAMCOMPOSITIONENABLED, newValue);
00148             }
00149         }
00150
00151         property bool RecordingIndicatorEnabled
00152         {
00153             bool get()
00154             {
00155                 return GetValueFromPropertySet<bool>(m_propertySet, PROPERTY_RECORDINGINDICATORENABLED, DefaultRecordingIndicatorEnabled);
00156             }
00157
00158             void set(bool newValue)
00159             {
00160                 m_propertySet->Insert(PROPERTY_RECORDINGINDICATORENABLED, newValue);
00161             }
00162         }
00163
00164         property bool VideoStabilizationEnabled
00165         {
00166             bool get()
00167             {
00168                 return GetValueFromPropertySet<bool>(m_propertySet, PROPERTY_VIDEOSTABILIZATIONENABLED, DefaultVideoStabilizationEnabled);
00169             }
00170
00171             void set(bool newValue)
00172             {
00173                 m_propertySet->Insert(PROPERTY_VIDEOSTABILIZATIONENABLED, newValue);
00174             }
00175         }
00176
00177         property uint32_t VideoStabilizationBufferLength
00178         {
00179             uint32_t get()
00180             {
00181                 return GetValueFromPropertySet<uint32_t>(m_propertySet, PROPERTY_VIDEOSTABILIZATIONBUFFERLENGTH, DefaultVideoStabilizationBufferLength);
00182             }
00183
00184             void set(uint32_t newValue)
00185             {
00186                 m_propertySet->Insert(PROPERTY_VIDEOSTABILIZATIONBUFFERLENGTH, (std::min)(newValue, PROPERTY_MAX_VSBUFFER));
00187             }
00188         }
00189
00190         property float GlobalOpacityCoefficient
00191         {
00192             float get()
00193             {
00194                 return GetValueFromPropertySet<float>(m_propertySet, PROPERTY_GLOBALOPACITYCOEFFICIENT, DefaultGlobalOpacityCoefficient);
00195             }
00196
00197             void set(float newValue)
00198             {
00199                 m_propertySet->Insert(PROPERTY_GLOBALOPACITYCOEFFICIENT, newValue);
00200             }
00201         }
00202
00203         property uint32_t VideoStabilizationMaximumBufferLength
00204         {
00205             uint32_t get()
00206             {
00207                 return PROPERTY_MAX_VSBUFFER;
00208             }
00209         }
00210
00211         property bool BlankOnProtectedContent
00212         {
00213             bool get()
00214             {
00215                 return GetValueFromPropertySet<bool>(m_propertySet, PROPERTY_BLANKONPROTECTEDCONTENT, DefaultBlankOnProtectedContent);
00216             }
00217
00218             void set(bool newValue)
00219             {
00220                 m_propertySet->Insert(PROPERTY_BLANKONPROTECTEDCONTENT, newValue);
00221             }
00222         }
00223
00224         property bool ShowHiddenMesh
00225         {
00226             bool get()
00227             {
00228                 return GetValueFromPropertySet<bool>(m_propertySet, PROPERTY_SHOWHIDDENMESH, DefaultShowHiddenMesh);
00229             }
00230
00231             void set(bool newValue)
00232             {
00233                 m_propertySet->Insert(PROPERTY_SHOWHIDDENMESH, newValue);
00234             }
00235         }
00236
00237         property Windows::Foundation::Size OutputSize
00238         {
00239             Windows::Foundation::Size get()
00240             {
00241                 return GetValueFromPropertySet<Windows::Foundation::Size>(m_propertySet, PROPERTY_OUTPUTSIZE, DefaultOutputSize);
00242             }
00243
00244             void set(Windows::Foundation::Size newValue)
00245             {
00246                 m_propertySet->Insert(PROPERTY_OUTPUTSIZE, static_cast<Windows::Foundation::Size>(newValue));
00247             }
00248         }
00249
00250         property MixedRealityCapturePerspective PreferredHologramPerspective
00251         {
00252             MixedRealityCapturePerspective get()
00253             {
00254                 return GetValueFromPropertySet<uint32_t>(m_propertySet, PROPERTY_PREFERREDHOLOGRAMPERSPECTIVE, DefaultPreferredHologramPerspective);
00255             }
00256
00257             void set(MixedRealityCapturePerspective newValue)
00258             {
00259                 m_propertySet->Insert(PROPERTY_PREFERREDHOLOGRAMPERSPECTIVE, static_cast<uint32_t>(newValue));
00260             }
00261         }
00262
00263     private:
00264         static constexpr Windows::Media::Capture::MediaStreamType DefaultStreamType = Windows::Media::Capture::MediaStreamType::VideoRecord;
00265         static constexpr bool DefaultHologramCompositionEnabled = true;
00266         static constexpr bool DefaultRecordingIndicatorEnabled = true;
00267         static constexpr bool DefaultVideoStabilizationEnabled = false;
00268         static constexpr uint32_t DefaultVideoStabilizationBufferLength = 0U;
00269         static constexpr float DefaultGlobalOpacityCoefficient = 0.9f;
00270         static constexpr bool DefaultBlankOnProtectedContent = false;
00271         static constexpr bool DefaultShowHiddenMesh = false;
00272         static constexpr MixedRealityCapturePerspective DefaultPreferredHologramPerspective = MixedRealityCapturePerspective::PhotoVideoCamera;
00273     private:
00274         Platform::String^ m_activatableClassId = ref new Platform::String(RUNTIMECLASS_MIXEDREALITYCAPTURE_VIDEO_EFFECT);
00275         Windows::Foundation::Collections::PropertySet^ m_propertySet = ref new Windows::Foundation::Collections::PropertySet();
00276         Windows::Foundation::Size DefaultOutputSize = { 0,0 };
00277     };
00278 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraAdvancedCapture/cpp/App.xaml.h Source File

  • CameraAdvancedCapture
  • cpp

App.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "App.g.h"
00015
00016 namespace CameraAdvancedCapture
00017 {
00018     /// <summary>
00019     /// Provides application-specific behavior to supplement the default Application class.
00020     /// </summary>
00021     ref class App sealed
00022     {
00023     protected:
00024         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override;
00025
00026     internal:
00027         App();
00028
00029     private:
00030         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
00031         void OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e);
00032     };
00033 }
Generated on Fri Nov 15 2024 22:16:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/scenario12.xaml.h Source File

  • ApplicationResources
  • cpp

scenario12.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario12.xaml.h
00013 // Declaration of the Scenario12 class
00014 //
00015
00016 #pragma once
00017
00018 #include "pch.h"
00019 #include "Scenario12.g.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024
00025         /// <summary>
00026         /// An empty page that can be used on its own or navigated to within a Frame.
00027         /// </summary>
00028         [Windows::Foundation::Metadata::WebHostHidden]
00029         public ref class Scenario12 sealed
00030         {
00031         public:
00032             Scenario12();
00033
00034         protected:
00035             virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036
00037         private:
00038             void Scenario12Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039             MainPage^ rootPage;
00040         };
00041
00042 }
Generated on Fri Nov 15 2024 22:17:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
_tileId | ScenarioElement | [private]
ButtonPinSecondaryTile_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraManualControls/cs/App.xaml.cs Source File

  • CameraManualControls
  • cs

App.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.IO;
00015 using System.Linq;
00016 using System.Runtime.InteropServices.WindowsRuntime;
00017 using Windows.ApplicationModel;
00018 using Windows.ApplicationModel.Activation;
00019 using Windows.Foundation;
00020 using Windows.Foundation.Collections;
00021 using Windows.UI.Xaml;
00022 using Windows.UI.Xaml.Controls;
00023 using Windows.UI.Xaml.Controls.Primitives;
00024 using Windows.UI.Xaml.Data;
00025 using Windows.UI.Xaml.Input;
00026 using Windows.UI.Xaml.Media;
00027 using Windows.UI.Xaml.Navigation;
00028
00029 namespace CameraManualControls
00030 {
00031     /// <summary>
00032     /// Provides application-specific behavior to supplement the default Application class.
00033     /// </summary>
00034     sealed partial class App : Application
00035     {
00036         /// <summary>
00037         /// Initializes the singleton application object.  This is the first line of authored code
00038         /// executed, and as such is the logical equivalent of main() or WinMain().
00039         /// </summary>
00040         public App()
00041         {
00042             this.InitializeComponent();
00043         }
00044
00045         /// <summary>
00046         /// Invoked when the application is launched normally by the end user.  Other entry points
00047         /// will be used such as when the application is launched to open a specific file.
00048         /// </summary>
00049         /// <param name="e">Details about the launch request and process.</param>
00050         protected override void OnLaunched(LaunchActivatedEventArgs e)
00051         {
00052
00053 #if DEBUG
00054             if (System.Diagnostics.Debugger.IsAttached)
00055             {
00056                 this.DebugSettings.EnableFrameRateCounter = true;
00057             }
00058 #endif
00059
00060             Frame rootFrame = Window.Current.Content as Frame;
00061
00062             // Do not repeat app initialization when the Window already has content,
00063             // just ensure that the window is active
00064             if (rootFrame == null)
00065             {
00066                 // Create a Frame to act as the navigation context and navigate to the first page
00067                 rootFrame = new Frame();
00068
00069                 rootFrame.NavigationFailed += OnNavigationFailed;
00070
00071                 // Place the frame in the current Window
00072                 Window.Current.Content = rootFrame;
00073             }
00074
00075             if (rootFrame.Content == null)
00076             {
00077                 // When the navigation stack isn't restored navigate to the first page,
00078                 // configuring the new page by passing required information as a navigation
00079                 // parameter
00080                 rootFrame.Navigate(typeof(MainPage), e.Arguments);
00081             }
00082             // Ensure the current window is active
00083             Window.Current.Activate();
00084         }
00085
00086         /// <summary>
00087         /// Invoked when Navigation to a certain page fails
00088         /// </summary>
00089         /// <param name="sender">The Frame which failed navigation</param>
00090         /// <param name="e">Details about the navigation failure</param>
00091         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00092         {
00093             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00094         }
00095     }
00096 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraFrames/cpp/Scenario2_FindAvailableSourceGroups.xaml.h Source File

  • CameraFrames
  • cpp

Scenario2_FindAvailableSourceGroups.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_FindAvailableSourceGroups.g.h"
00015 #include "MainPage.xaml.h"
00016 #include "SimpleLogger.h"
00017 #include "FrameRenderer.h"
00018 #include "FrameSourceViewModels.h"
00019
00020 namespace SDKTemplate
00021 {
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario2_FindAvailableSourceGroups sealed
00024     {
00025     public:
00026         Scenario2_FindAvailableSourceGroups();
00027
00028     protected:
00029         // Protected UI overrides.
00030         /// <summary>
00031         /// Called when user navigates to this Scenario.
00032         /// Sets the GroupCombobox item source.
00033         /// </summary>
00034         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00035
00036         /// <summary>
00037         /// Called when user navigates away from this Scenario.
00038         /// Stops streaming and disposes of all objects.
00039         /// </summary>
00040         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00041
00042     private:
00043         // Private UI methods.
00044         /// <summary>
00045         /// Stops reading from the previous selection and starts reading frames from the newly selected source group.
00046         /// </summary>
00047         void GroupComboBox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00048
00049         /// <summary>
00050         /// Called when a source is selected.
00051         /// Sets the FormatCombobox item source based on the selected source.
00052         /// </summary>
00053         void SourceComboBox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00054
00055         /// <summary>
00056         /// Called when a format is selected.
00057         /// Sets the format of the currently selected source.
00058         /// </summary>
00059         void FormatComboBox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00060
00061         /// <summary>
00062         /// Called when use clicks the Stop button.
00063         /// </summary>
00064         void StopButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00065
00066         /// <summary>
00067         /// Called when use clicks the Start button.
00068         /// </summary>
00069         void StartButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00070
00071     private:
00072         // Private methods.
00073         /// <summary>
00074         /// Stops reading from the frame reader, disposes of the reader and updates the button state.
00075         /// </summary>
00076         concurrency::task<void> StopReaderAsync();
00077
00078         /// <summary>
00079         /// Closes the MediaCapture object and clears the items from the Format and Source ComboBoxes.
00080         /// Must be called from the UI thread.
00081         /// </summary>
00082         void DisposeMediaCapture();
00083
00084         /// <summary>
00085         /// Starts reading frames from the current reader.
00086         /// Must be called from the UI thread.
00087         /// </summary>
00088         concurrency::task<void> StartReaderAsync();
00089
00090         /// <summary>
00091         /// Creates a reader from the current frame source and registers to handle its frame events.
00092         /// Must be called from the UI thread.
00093         /// </summary>
00094         concurrency::task<void> CreateReaderAsync();
00095
00096         /// <summary>
00097         // Updates the current frame source to the one corresponding to the user's selection.
00098         /// </summary>
00099         void UpdateFrameSource();
00100
00101         /// <summary>
00102         /// Initialize the media capture object.
00103         /// Must be called from the UI thread.
00104         /// </summary>
00105         concurrency::task<bool> TryInitializeCaptureAsync();
00106
00107         /// <summary>
00108         /// Changes the format of the currently selected source.
00109         /// </summary>
00110         concurrency::task<void> ChangeMediaFormatAsync(FrameFormatModel^ format);
00111
00112         /// <summary>
00113         /// Updates the state of the start and stop buttons, based on the current App Model.
00114         /// </summary>
00115         concurrency::task<void> UpdateButtonStateAsync();
00116
00117         /// <summary>
00118         /// Handles the frame arrived event by converting the frame to a dislayable
00119         /// format and rendering it to the screen.
00120         /// </summary>
00121         void Reader_FrameArrived(Windows::Media::Capture::Frames::MediaFrameReader^ reader, Windows::Media::Capture::Frames::MediaFrameArrivedEventArgs^ args);
00122
00123     private:
00124         // Private data.
00125         concurrency::task<void> m_currentTask = concurrency::task_from_result();
00126
00127         // Whether or not we are currently streaming.
00128         bool m_streaming = false;
00129
00130         Platform::Agile<Windows::Media::Capture::MediaCapture^> m_mediaCapture;
00131
00132         Windows::Media::Capture::Frames::MediaFrameSource^ m_source;
00133         Windows::Media::Capture::Frames::MediaFrameReader^ m_reader;
00134         FrameRenderer^ m_frameRenderer;
00135
00136         SourceGroupCollection^ m_groupCollection;
00137         SimpleLogger^ m_logger;
00138
00139         Windows::Foundation::EventRegistrationToken m_frameArrivedToken;
00140     };
00141 } // SDKTemplate
Generated on Fri Nov 15 2024 22:18:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Syndication/cpp/Scenario1_GetFeed.xaml.h Source File

  • Syndication
  • cpp

Scenario1_GetFeed.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1.xaml.h
00014 // Declaration of the Scenario1 class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario1_GetFeed.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::Web::Syndication;
00026 using namespace Platform;
00027
00028 namespace SDKTemplate
00029 {
00030     namespace Syndication
00031     {
00032         /// <summary>
00033         /// An empty page that can be used on its own or navigated to within a Frame.
00034         /// </summary>
00035         [Windows::Foundation::Metadata::WebHostHidden]
00036         public ref class Scenario1 sealed
00037         {
00038         public:
00039             Scenario1();
00040
00041         protected:
00042             virtual void OnNavigatedTo(NavigationEventArgs^ e) override;
00043         private:
00044             MainPage^ rootPage;
00045             SyndicationFeed^ currentFeed;
00046             unsigned int currentItemIndex;
00047
00048             void GetFeed_Click(Object^ sender, RoutedEventArgs^ e);
00049             void PreviousItem_Click(Object^ sender, RoutedEventArgs^ e);
00050             void NextItem_Click(Object^ sender, RoutedEventArgs^ e);
00051             void LinkField_Click(Object^ sender, RoutedEventArgs^ e);
00052             void DisplayFeed();
00053             void DisplayCurrentItem();
00054         };
00055     }
00056 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/SampleConfiguration.cpp Source File

  • ComplexInk
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Custom Dry Scenario", "SDKTemplate.Scenario1_CustomDry" }
00021 };
Generated on Fri Nov 15 2024 22:17:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FolderEnumeration/cppwinrt/Scenario4.cpp Source File

  • FolderEnumeration
  • cppwinrt

Scenario4.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario4.h"
00014 #include "Scenario4.g.cpp"
00015 #include "SampleConfiguration.h"
00016 #include <sstream>
00017
00018 using namespace winrt;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Storage;
00022 using namespace Windows::Storage::Pickers;
00023 using namespace Windows::Storage::Search;
00024 using namespace Windows::UI::Xaml;
00025
00026 namespace winrt::SDKTemplate::implementation
00027 {
00028     Scenario4::Scenario4()
00029     {
00030         InitializeComponent();
00031     }
00032
00033     fire_and_forget Scenario4::GetFilesButton_Click(IInspectable const&, RoutedEventArgs const&)
00034     {
00035         auto lifetime = get_strong();
00036
00037         // Reset output.
00038         OutputPanel().Children().Clear();
00039
00040         // Ask the user to pick a folder.
00041         FolderPicker picker;
00042         picker.FileTypeFilter().Append(L"*");
00043         picker.ViewMode(PickerViewMode::List);
00044         picker.SuggestedStartLocation(PickerLocationId::DocumentsLibrary);
00045         StorageFolder folder = co_await picker.PickSingleFolderAsync();
00046         if (folder != nullptr)
00047         {
00048             // Query the folder.
00049             StorageFileQueryResult query = folder.CreateFileQuery();
00050             IVectorView<StorageFile> fileList = co_await query.GetFilesAsync();
00051
00052
00053             // Display file list with storage provider and availability.
00054             for (StorageFile const& file : fileList)
00055             {
00056                 std::wstringstream output;
00057
00058                 // Create an entry in the list for the item.
00059                 output << std::wstring_view{ file.Name() };
00060
00061                 // Show the item's provider (This PC, OneDrive, Network, or Application Content).
00062                 output << L": On " << std::wstring_view{ file.Provider().DisplayName() };
00063
00064                 // Show if the item is available (OneDrive items are usually available when
00065                 // online or when they are marked for "always available offline").
00066                 output << L" (";
00067                 if (file.IsAvailable())
00068                 {
00069                     output << L"available";
00070                 }
00071                 else
00072                 {
00073                     output << L"not available";
00074                 }
00075                 output << L")";
00076                 OutputPanel().Children().Append(Helpers::CreateLineItemTextBlock(output.str()));
00077             }
00078         }
00079
00080     }
00081 }
Generated on Fri Nov 15 2024 22:19:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1 Member List

This is the complete list of members for Scenario1, including all inherited members.
Grid1_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args) | Scenario1 | [inline, private]
initdata() | Scenario1 | [inline, private]
Scenario1() | Scenario1 | [inline]
Generated on Fri Nov 15 2024 22:23:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/HolographicPaintMain.h Source File

  • SpatialInteractionSource
  • cpp

HolographicPaintMain.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "Common\DeviceResources.h"
00004 #include "Common\StepTimer.h"
00005 #include "Content\RenderingHelper.h"
00006 #include "Content\Stroke.h"
00007 #include "Content\RenderingInterfaces.h"
00008 #include "Content\Tool.h"
00009 #include "Content\ToolCarousel.h"
00010 #include "Content\Whiteboard.h"
00011 #include "SourceHandler.h"
00012 #include "DPadHelper.h"
00013
00014 // Updates, renders, and presents holographic content using Direct3D.
00015 namespace HolographicPaint
00016 {
00017
00018     class HolographicPaintMain : public DX::IDeviceNotify, public ISourceCommandHandler
00019     {
00020     public:
00021         HolographicPaintMain(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00022         ~HolographicPaintMain();
00023
00024         // Sets the holographic space. This is our closest analogue to setting a new window
00025         // for the app.
00026         void SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^ holographicSpace);
00027
00028         // Starts the holographic frame and updates the content.
00029         Windows::Graphics::Holographic::HolographicFrame^ Update();
00030
00031         // Renders holograms, including world-locked content.
00032         bool Render(Windows::Graphics::Holographic::HolographicFrame^ holographicFrame);
00033
00034         // IDeviceNotify
00035         virtual void OnDeviceLost();
00036         virtual void OnDeviceRestored();
00037
00038         // ISourceCommandHandler
00039         virtual void OnDPadAction(SourceHandler* sender, DPadAction action) override;
00040         virtual void OnStrokeAdded(SourceHandler* sender, std::shared_ptr<IBaseRenderedObject> stroke) override;
00041         virtual void OnEnterToolChoice(SourceHandler* sender, Windows::Perception::PerceptionTimestamp^ timestamp) override;
00042         virtual void OnSelectTool(SourceHandler* sender) override;
00043
00044     private:
00045         // Asynchronously creates resources for new holographic cameras.
00046         void OnCameraAdded(
00047             Windows::Graphics::Holographic::HolographicSpace^ sender,
00048             Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs^ args);
00049
00050         // Synchronously releases resources for holographic cameras that are no longer
00051         // attached to the system.
00052         void OnCameraRemoved(
00053             Windows::Graphics::Holographic::HolographicSpace^ sender,
00054             Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs^ args);
00055
00056         // Used to notify the app when the positional tracking state changes.
00057         void OnLocatabilityChanged(
00058             Windows::Perception::Spatial::SpatialLocator^ sender,
00059             Platform::Object^ args);
00060
00061         // Clears event registration state. Used when changing to a new HolographicSpace
00062         // and when tearing down AppMain.
00063         void UnregisterHolographicEventHandlers();
00064
00065         // Events Handlers
00066         void OnSourceDetected(Windows::UI::Input::Spatial::SpatialInteractionManager ^sender, Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs ^args);
00067         void OnSourceLost(Windows::UI::Input::Spatial::SpatialInteractionManager ^sender, Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs ^args);
00068         void OnSourcePressed(Windows::UI::Input::Spatial::SpatialInteractionManager ^sender, Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs ^args);
00069         void OnSourceUpdated(Windows::UI::Input::Spatial::SpatialInteractionManager ^sender, Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs ^args);
00070         void OnInteractionDetected(Windows::UI::Input::Spatial::SpatialInteractionManager ^sender, Windows::UI::Input::Spatial::SpatialInteractionDetectedEventArgs ^args);
00071
00072         // Position tools based on current heading
00073         void PositionTools(Windows::UI::Input::Spatial::SpatialPointerPose^ pointerPose, HandAssignment side);
00074         // Returns the tool's index from a source
00075         size_t FindToolIndex(unsigned int sourceId);
00076         // Assign new tool to a source
00077         void SetToolByIndex(unsigned int sourceId, size_t toolIndex);
00078         // Get the SourceHandler associated to a SpatialInteractionSource Id
00079         SourceHandler* GetSourceHandler(unsigned int sourceId)
00080         {
00081             auto it = m_sourceMap.find(sourceId);
00082             return (it == m_sourceMap.end()) ? nullptr : it->second.get();
00083         }
00084         // Detects on which side the given source is located
00085         HandAssignment TryGetHandedness(SourceHandler* sender, Windows::UI::Input::Spatial::SpatialPointerPose^ pointerPose);
00086
00087         // Renders a colorful holographic cube that's 20 centimeters wide. This sample content
00088         // is used to demonstrate world-locked rendering.
00089         std::unique_ptr<RenderingHelper>                                m_renderingHelper;
00090
00091         // Cached pointer to device resources.
00092         std::shared_ptr<DX::DeviceResources>                            m_deviceResources;
00093
00094         // Render loop timer.
00095         DX::StepTimer                                                   m_timer;
00096
00097         // Represents the holographic space around the user.
00098         Windows::Graphics::Holographic::HolographicSpace^               m_holographicSpace;
00099
00100         // SpatialLocator that is attached to the primary camera.
00101         Windows::Perception::Spatial::SpatialLocator^                   m_locator;
00102
00103         // A reference frame attached to the holographic camera.
00104         Windows::Perception::Spatial::SpatialStationaryFrameOfReference^ m_referenceFrame;
00105
00106         // Event registration tokens.
00107         Windows::Foundation::EventRegistrationToken                     m_cameraAddedToken;
00108         Windows::Foundation::EventRegistrationToken                     m_cameraRemovedToken;
00109         Windows::Foundation::EventRegistrationToken                     m_locatabilityChangedToken;
00110         Windows::Foundation::EventRegistrationToken                     m_sourceDetectedToken;
00111         Windows::Foundation::EventRegistrationToken                     m_sourceLostToken;
00112         Windows::Foundation::EventRegistrationToken                     m_sourcePressedToken;
00113         Windows::Foundation::EventRegistrationToken                     m_sourceUpdatedToken;
00114         Windows::Foundation::EventRegistrationToken                     m_interactionDetectedToken;
00115
00116         Windows::UI::Input::Spatial::SpatialInteractionManager^         m_spatialInteractionManager;
00117
00118         Windows::Foundation::Numerics::float3                           m_focusPoint = { 0.0f, 0.0f, 2.0f };
00119
00120         // Current application mode and slection
00121         ApplicationMode                                                 m_currentMode = ApplicationMode::Drawing;
00122         unsigned int                                                    m_currentSourceId = NoSourceId;
00123         size_t                                                          m_currentToolIndex;
00124
00125         // Currently detected SpatialInteractionSources
00126         std::map<unsigned int, std::shared_ptr<SourceHandler>>          m_sourceMap;
00127         std::vector<std::shared_ptr<SourceHandler>>                     m_sources;
00128
00129         // Drawing itself
00130         std::vector<std::shared_ptr<IBaseRenderedObject>>               m_strokes;
00131
00132         // Tools collection, known tools index, tool layout helper
00133         std::vector<std::shared_ptr<Tool>>                              m_tools;
00134         size_t                                                          m_clearToolIndex;
00135         ToolCarousel                                                    m_toolsCarousel;
00136
00137         std::shared_ptr<Whiteboard>                                     m_whiteboard;
00138     };
00139 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/SourceHandler.h Source File

  • SpatialInteractionSource
  • cpp

SourceHandler.h

Go to the documentation of this file.
00001 #pragma once
00002 #include "Content\Stroke.h"
00003 #include "Content\RenderingInterfaces.h"
00004 #include "Content\Tool.h"
00005 #include "Content\Whiteboard.h"
00006 #include "DPadHelper.h"
00007
00008 namespace HolographicPaint
00009 {
00010     constexpr unsigned int NoSourceId = static_cast<unsigned int>(-1);
00011     constexpr unsigned int AnyHandSourceId = static_cast<unsigned int>(-2);
00012
00013     constexpr float DefaultControllerScale = .05f;
00014
00015     enum class ApplicationMode { Drawing, ChooseTool };
00016
00017     enum class HandAssignment { Unknown, LeftHand, RightHand };
00018
00019     class SourceHandler;
00020
00021     // Callbacks allowing the application to ignore the differences between different kind of SpatialInteractionSource
00022     interface ISourceCommandHandler
00023     {
00024         virtual void OnDPadAction(SourceHandler* sender, DPadAction action) = 0;
00025         virtual void OnStrokeAdded(SourceHandler* sender, std::shared_ptr<IBaseRenderedObject> stroke) = 0;
00026         virtual void OnEnterToolChoice(SourceHandler* sender, Windows::Perception::PerceptionTimestamp^ timestamp) = 0;
00027         virtual void OnSelectTool(SourceHandler* sender) = 0;
00028     };
00029
00030     // This class and the classes derived from it provide identical services and events to the application
00031     // for two kinds of SpatialInteractionSource: Hands and Six DOF Controllers
00032     // It handles input and associates a drawing tool to the SpatialInteractionSource.
00033     class SourceHandler : public IBaseRenderedObject
00034     {
00035     protected:
00036         SourceHandler(Windows::UI::Input::Spatial::SpatialInteractionSource^ source, ISourceCommandHandler* eventsHandler, std::shared_ptr<Whiteboard>& target);
00037
00038     public:
00039         static bool Make(
00040             std::shared_ptr<SourceHandler>* handler,
00041             Windows::UI::Input::Spatial::SpatialInteractionSource^ source,
00042             ISourceCommandHandler* eventsHandler,
00043             std::shared_ptr<Whiteboard>& target);
00044
00045         virtual void Update(ID3D11DeviceContext* pDeviceContext) override;
00046         virtual void Render(ID3D11DeviceContext* pDeviceContext, IRenderer* pRenderingHelper) override;
00047
00048         // Update the source and returns a Pointer pose if applicable
00049         virtual void OnSourceUpdated(Windows::UI::Input::Spatial::SpatialInteractionSourceState^ state, Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem);
00050         virtual void OnInteractionDetected(Windows::UI::Input::Spatial::SpatialInteraction^ interaction, Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem) {}
00051         virtual void OnSourcePressed(Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs^ args) {}
00052
00053         unsigned int SourceId() const { return m_sourceId; }
00054         Windows::UI::Input::Spatial::SpatialInteractionSourceKind GetSourceKind() const { return m_sourceKind; }
00055
00056         bool IsPositionCurrent() const { return m_position.IsCurrent; }
00057         Windows::Foundation::Numerics::float3 GetPosition() const { return m_position.Position; }
00058
00059         void SetCurrentTool(std::shared_ptr<Tool> tool);
00060
00061         Tool* GetCurrentTool() const { return m_currentTool.get(); }
00062
00063         virtual Windows::Foundation::Numerics::float3 GetToolPosition() const
00064         {
00065             return m_toolPosition.Position;
00066         }
00067
00068         virtual Windows::Foundation::Numerics::float3 GetToolScale() const
00069         {
00070             return Windows::Foundation::Numerics::float3(m_currentTool == nullptr ? DefaultControllerScale : m_currentTool->GetDiameter());
00071         }
00072
00073         void SetApplicationMode(ApplicationMode newMode)
00074         {
00075             m_currentMode = newMode;
00076         }
00077
00078     protected:
00079         unsigned int m_sourceId;
00080         Windows::UI::Input::Spatial::SpatialInteractionSourceKind m_sourceKind;
00081
00082         ApplicationMode m_currentMode;
00083
00084         struct PositionInformation
00085         {
00086             bool HasValue = false;
00087             bool IsCurrent= false;
00088             Windows::Foundation::Numerics::float3 Position = Windows::Foundation::Numerics::float3::zero();
00089             Windows::Foundation::Numerics::quaternion Orientation = Windows::Foundation::Numerics::quaternion::identity();
00090             long long LastValueTime = 0;
00091
00092             void CheckIfObsolete(long long now);
00093         };
00094
00095         // A SpatialInteractionSource has a position and can also (in the case of controllers) have a pointing direction
00096         // m_poosition keeps track of the position of the source itself
00097         PositionInformation m_position;
00098         // m_toolPosition keeps track of the position where drawing will happen and is computed either from the pointing
00099         // direction of the controller, or from the gaze in the case of Hands
00100         // It will be either on the target board if the pointing ray intersects the board
00101         // or - in the case of a controller - a few centimeters in the pointing direction if it does not intersect the board
00102         PositionInformation m_toolPosition;
00103
00104         // Currently selected tool
00105         std::shared_ptr<Tool> m_currentTool;
00106
00107         // Caching of location
00108         bool m_refreshModelConstantBufferData = true;
00109         ModelConstantBuffer m_modelConstantBufferData;
00110
00111         ISourceCommandHandler* m_eventsHandler = nullptr;
00112
00113         // Drawing methods and state
00114         virtual void ComposeStroke();
00115         virtual void TerminateStroke();
00116         std::shared_ptr<Stroke> m_currentStroke;
00117
00118         std::shared_ptr<Whiteboard> m_targetBoard;
00119     };
00120
00121 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AccessHandler Member List

This is the complete list of members for AccessHandler, including all inherited members.
AccessHandler(SmartCardConnection ScConnection) | AccessHandler | [inline]
connectionObject | AccessHandler | [private]
GetUidAsync() | AccessHandler | [inline]
ReadAsync(byte blockNumber) | AccessHandler | [inline]
TransparentExchangeAsync(byte[] commandData) | AccessHandler | [inline]
WriteAsync(byte blockNumber, byte[] dataToWrite) | AccessHandler | [inline]
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DecodeEngine Member List

This is the complete list of members for DecodeEngine, including all inherited members.
__pad0__ | DecodeEngine |
ActiveSymbologies | DecodeEngine |
DecodeAsync(SoftwareBitmap bitmap) | DecodeEngine | [inline]
DecodeEngine() | DecodeEngine | [inline]
localSettings | DecodeEngine | [private, static]
m_activeSymbologies | DecodeEngine | [private]
m_ocrEngine | DecodeEngine | [private]
m_supportedSymbologies | DecodeEngine | [private]
ocrEngine | DecodeEngine | [private]
SupportedSymbologies | DecodeEngine |
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/SampleConfiguration.h Source File

  • HttpClient
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt
00016 {
00017     hstring to_hstring(Windows::Web::WebErrorStatus value);
00018     hstring to_hstring(Windows::Web::Http::HttpResponseMessageSource value);
00019     hstring to_hstring(Windows::Web::Http::HttpVersion value);
00020     hstring to_hstring(Windows::Web::Http::HttpProgressStage value);
00021 }
00022
00023 namespace winrt::SDKTemplate
00024 {
00025 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 3DPrinting/cs/SampleConfiguration.cs Source File

  • 3DPrinting
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "3D Printing C# Sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Print a model", ClassType=typeof(Scenario1_Print)},
00025             new Scenario() { Title="Launch 3D Builder", ClassType=typeof(Scenario2_Launch)},
00026         };
00027     }
00028
00029     public class Scenario
00030     {
00031         public string Title { get; set; }
00032         public Type ClassType { get; set; }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cppwinrt/Scenario7.h Source File

  • FileAccess
  • cppwinrt

Scenario7.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario7.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     /// <summary>
00020     /// Persisting access to a storage item for future use.
00021     /// </summary>
00022     struct Scenario7 : Scenario7T<Scenario7>
00023     {
00024         Scenario7();
00025
00026         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00027         void AddToListButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00028         void ShowListButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00029         fire_and_forget OpenFromListButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00030
00031     private:
00032         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00033     };
00034 }
00035
00036 namespace winrt::SDKTemplate::factory_implementation
00037 {
00038     struct Scenario7 : Scenario7T<Scenario7, implementation::Scenario7>
00039     {
00040     };
00041 }
Generated on Fri Nov 15 2024 22:19:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Discovery Member List

This is the complete list of members for Scenario1_Discovery, including all inherited members.
BuildFilters() | Scenario1_Discovery | [inline, private]
deviceWatcher | Scenario1_Discovery | [private]
DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo) | Scenario1_Discovery | [inline, private]
DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object e) | Scenario1_Discovery | [inline, private]
DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) | Scenario1_Discovery | [inline, private]
DeviceWatcher_Stopped(DeviceWatcher sender, object e) | Scenario1_Discovery | [inline, private]
DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate) | Scenario1_Discovery | [inline, private]
EnumerateButton_Click() | Scenario1_Discovery | [inline, private]
FindBluetoothLEDeviceDisplay(string id) | Scenario1_Discovery | [inline, private]
FindUnknownDevices(string id) | Scenario1_Discovery | [inline, private]
isBusy | Scenario1_Discovery | [private]
KnownDevices | Scenario1_Discovery | [private]
m_remoteSystemWatcher | Scenario1_Discovery | [private]
m_rootPage | Scenario1_Discovery | [private]
Not(bool value) | Scenario1_Discovery | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_Discovery | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_Discovery | [inline, protected]
PairButton_Click() | Scenario1_Discovery | [inline, private]
RemoteSystemWatcher_RemoteSystemAdded(RemoteSystemWatcher sender, RemoteSystemAddedEventArgs args) | Scenario1_Discovery | [inline, private]
RemoteSystemWatcher_RemoteSystemRemoved(RemoteSystemWatcher sender, RemoteSystemRemovedEventArgs args) | Scenario1_Discovery | [inline, private]
RemoteSystemWatcher_RemoteSystemUpdated(RemoteSystemWatcher sender, RemoteSystemUpdatedEventArgs args) | Scenario1_Discovery | [inline, private]
rootPage | Scenario1_Discovery | [private]
Scenario1_Discovery() | Scenario1_Discovery | [inline]
Scenario1_Discovery() | Scenario1_Discovery | [inline]
Search_Clicked(object sender, RoutedEventArgs e) | Scenario1_Discovery | [inline, private]
SearchByHostNameAsync() | Scenario1_Discovery | [inline, private]
SearchByRemoteSystemWatcher() | Scenario1_Discovery | [inline, private]
SearchCleanup() | Scenario1_Discovery | [inline, private]
StartBleDeviceWatcher() | Scenario1_Discovery | [inline, private]
StopBleDeviceWatcher() | Scenario1_Discovery | [inline, private]
SystemList | Scenario1_Discovery |
SystemListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario1_Discovery | [inline, private]
UnknownDevices | Scenario1_Discovery | [private]
UpdateStatus(string status, NotifyType statusType) | Scenario1_Discovery | [inline, private]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario8_VisitsBackgroundTask Member List

This is the complete list of members for Scenario8_VisitsBackgroundTask, including all inherited members.
BackgroundTaskEntryPoint | Scenario8_VisitsBackgroundTask | [private, static]
BackgroundTaskName | Scenario8_VisitsBackgroundTask | [private, static]
FillEventListBoxWithExistingEvents() | Scenario8_VisitsBackgroundTask | [private]
m_visitTask | Scenario8_VisitsBackgroundTask | [private]
OnCompleted(Windows::ApplicationModel::Background::IBackgroundTaskRegistration sender, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs e) | Scenario8_VisitsBackgroundTask | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario8_VisitsBackgroundTask |
RegisterBackgroundTask(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario8_VisitsBackgroundTask |
Scenario8_VisitsBackgroundTask() | Scenario8_VisitsBackgroundTask |
UnregisterBackgroundTask(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario8_VisitsBackgroundTask |
UpdateButtonStates() | Scenario8_VisitsBackgroundTask | [private]
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cs/2-PointerPointProperties.xaml.cs Source File

  • BasicInput
  • cs

2-PointerPointProperties.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Input;
00016 using Windows.UI.Xaml.Media;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class Scenario2 : Page
00021     {
00022         Dictionary<uint, StackPanel> popups;
00023
00024         public Scenario2()
00025         {
00026             this.InitializeComponent();
00027
00028             // Contact tracking for UI popups
00029             popups = new Dictionary<uint, StackPanel>();
00030
00031             // Add event handlers
00032             mainCanvas.PointerPressed += new PointerEventHandler(Pointer_Pressed);
00033             mainCanvas.PointerMoved += new PointerEventHandler(Pointer_Moved);
00034             mainCanvas.PointerReleased += new PointerEventHandler(Pointer_Released);
00035             mainCanvas.PointerExited += new PointerEventHandler(Pointer_Released);
00036             mainCanvas.PointerEntered += new PointerEventHandler(Pointer_Entered);
00037             mainCanvas.PointerWheelChanged += new PointerEventHandler(Pointer_Wheel_Changed);
00038         }
00039
00040         void Pointer_Pressed(object sender, PointerRoutedEventArgs e)
00041         {
00042             Windows.UI.Input.PointerPoint currentPoint = e.GetCurrentPoint(mainCanvas);
00043
00044             // Retrieve the properties for the curret PointerPoint and display
00045             // them alongside the pointer's location on screen
00046             CreateOrUpdatePropertyPopUp(currentPoint);
00047         }
00048
00049         void Pointer_Entered(object sender, PointerRoutedEventArgs e)
00050         {
00051             Windows.UI.Input.PointerPoint currentPoint = e.GetCurrentPoint(mainCanvas);
00052
00053             // Determine if the point that entered the canvas is "in contact" with the
00054             // screen (mouse button pressed, finger down, or pen down).
00055             // This will be encountered if the user touches down in the app surface,
00056             // drags their finger off of the app, and drags it back onto the app without
00057             // lifting their finger.
00058             if (currentPoint.IsInContact)
00059             {
00060                 CreateOrUpdatePropertyPopUp(currentPoint);
00061             }
00062         }
00063
00064         void Pointer_Moved(object sender, PointerRoutedEventArgs e)
00065         {
00066             // Retrieve the point associated with the current event
00067             Windows.UI.Input.PointerPoint currentPoint = e.GetCurrentPoint(mainCanvas);
00068
00069             // Create a popup if the pointer being moved is in contact with the screen
00070             if (currentPoint.IsInContact)
00071             {
00072                 CreateOrUpdatePropertyPopUp(currentPoint);
00073             }
00074         }
00075
00076         void Pointer_Released(object sender, PointerRoutedEventArgs e)
00077         {
00078             // Retrieve the point associated with the current event
00079             Windows.UI.Input.PointerPoint currentPoint = e.GetCurrentPoint(mainCanvas);
00080
00081             // Remove the popup corresponding to the pointer
00082             HidePropertyPopUp(currentPoint);
00083         }
00084
00085         void Pointer_Wheel_Changed(object sender, PointerRoutedEventArgs e)
00086         {
00087             // Retrieve the point associated with the current event and record the
00088             // mouse wheel delta
00089             Windows.UI.Input.PointerPoint currentPoint = e.GetCurrentPoint(mainCanvas);
00090             if (currentPoint.IsInContact)
00091             {
00092                 CreateOrUpdatePropertyPopUp(currentPoint);
00093             }
00094         }
00095
00096         void CreateOrUpdatePropertyPopUp(Windows.UI.Input.PointerPoint currentPoint)
00097         {
00098             // Retrieve the properties that are common to all pointers
00099             String pointerProperties = GetPointerProperties(currentPoint);
00100
00101             // Retrieve the properties that are specific to the device type associated
00102             // with the current PointerPoint
00103             String deviceSpecificProperties = GetDeviceSpecificProperties(currentPoint);
00104
00105             RenderPropertyPopUp(pointerProperties, deviceSpecificProperties, currentPoint);
00106         }
00107
00108         // Return the properties that are common to all pointers
00109         String GetPointerProperties(Windows.UI.Input.PointerPoint currentPoint)
00110         {
00111             System.Text.StringBuilder sb = new System.Text.StringBuilder();
00112
00113             sb.Append("ID: " + currentPoint.PointerId);
00114             sb.Append("\nX: " + currentPoint.Position.X);
00115             sb.Append("\nY: " + currentPoint.Position.Y);
00116             sb.Append("\nContact: " + currentPoint.IsInContact + "\n");
00117
00118             return sb.ToString(); ;
00119         }
00120
00121         String GetDeviceSpecificProperties(Windows.UI.Input.PointerPoint currentPoint)
00122         {
00123             String deviceSpecificProperties = "";
00124
00125             // Detect the type of device being used by examining PointerDeviceType
00126             // to distinguish between mouse, touch, and pen
00127             switch (currentPoint.PointerDevice.PointerDeviceType)
00128             {
00129                 case Windows.Devices.Input.PointerDeviceType.Mouse:
00130                     deviceSpecificProperties = GetMouseProperties(currentPoint);
00131                     break;
00132                 case Windows.Devices.Input.PointerDeviceType.Pen:
00133                     deviceSpecificProperties = GetPenProperties(currentPoint);
00134                     break;
00135                 case Windows.Devices.Input.PointerDeviceType.Touch:
00136                     deviceSpecificProperties = GetTouchProperties(currentPoint);
00137                     break;
00138             }
00139
00140             return deviceSpecificProperties;
00141         }
00142
00143         // Return the properties that are specific to mice
00144         String GetMouseProperties(Windows.UI.Input.PointerPoint currentPoint)
00145         {
00146             Windows.UI.Input.PointerPointProperties pointerProperties = currentPoint.Properties;
00147             System.Text.StringBuilder sb = new System.Text.StringBuilder();
00148
00149             sb.Append("Left button: " + pointerProperties.IsLeftButtonPressed);
00150             sb.Append("\nRight button: " + pointerProperties.IsRightButtonPressed);
00151             sb.Append("\nMiddle button: " + pointerProperties.IsMiddleButtonPressed);
00152             sb.Append("\nX1 button: " + pointerProperties.IsXButton1Pressed);
00153             sb.Append("\nX2 button: " + pointerProperties.IsXButton2Pressed);
00154             sb.Append("\nMouse wheel delta: " + pointerProperties.MouseWheelDelta);
00155
00156             return sb.ToString();
00157         }
00158
00159         // Return the properties that are specific to touch
00160         String GetTouchProperties(Windows.UI.Input.PointerPoint currentPoint)
00161         {
00162             Windows.UI.Input.PointerPointProperties pointerProperties = currentPoint.Properties;
00163             System.Text.StringBuilder sb = new System.Text.StringBuilder();
00164
00165             sb.Append("Contact Rect X: " + pointerProperties.ContactRect.X);
00166             sb.Append("\nContact Rect Y: " + pointerProperties.ContactRect.Y);
00167             sb.Append("\nContact Rect Width: " + pointerProperties.ContactRect.Width);
00168             sb.Append("\nContact Rect Height: " + pointerProperties.ContactRect.Height);
00169
00170             return sb.ToString(); ;
00171         }
00172
00173         // Return the properties that are specific to pen
00174         String GetPenProperties(Windows.UI.Input.PointerPoint currentPoint)
00175         {
00176             Windows.UI.Input.PointerPointProperties pointerProperties = currentPoint.Properties;
00177             System.Text.StringBuilder sb = new System.Text.StringBuilder();
00178
00179             sb.Append("Barrel button: " + pointerProperties.IsBarrelButtonPressed);
00180             sb.Append("\nEraser: " + pointerProperties.IsEraser);
00181             sb.Append("\nPressure: " + pointerProperties.Pressure);
00182
00183             return sb.ToString();
00184         }
00185
00186         //
00187         // Popup UI code below
00188         //
00189         void RenderPropertyPopUp(String pointerProperties, String deviceSpecificProperties, Windows.UI.Input.PointerPoint currentPoint)
00190         {
00191             if (popups.ContainsKey(currentPoint.PointerId))
00192             {
00193                 TextBlock pointerText = (TextBlock)popups[currentPoint.PointerId].Children[0];
00194                 pointerText.Text = pointerProperties;
00195                 TextBlock deviceSpecificText = (TextBlock)popups[currentPoint.PointerId].Children[1];
00196                 deviceSpecificText.Text = deviceSpecificProperties;
00197             }
00198             else
00199             {
00200                 StackPanel pointerPanel = new StackPanel();
00201                 TextBlock pointerText = new TextBlock();
00202                 pointerText.Text = pointerProperties;
00203                 pointerPanel.Children.Add(pointerText);
00204
00205                 TextBlock deviceSpecificText = new TextBlock();
00206                 deviceSpecificText.Text = deviceSpecificProperties;
00207
00208                 // Detect the type of device being used by examining PointerDeviceType
00209                 // to distinguish between mouse, touch, and pen
00210                 switch (currentPoint.PointerDevice.PointerDeviceType)
00211                 {
00212                     case Windows.Devices.Input.PointerDeviceType.Mouse:
00213                         deviceSpecificText.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
00214                         break;
00215
00216                     case Windows.Devices.Input.PointerDeviceType.Touch:
00217                         deviceSpecificText.Foreground = new SolidColorBrush(Windows.UI.Colors.Green);
00218                         break;
00219
00220                     case Windows.Devices.Input.PointerDeviceType.Pen:
00221                         deviceSpecificText.Foreground = new SolidColorBrush(Windows.UI.Colors.Yellow);
00222                         break;
00223                 }
00224                 pointerPanel.Children.Add(deviceSpecificText);
00225                 popups[currentPoint.PointerId] = pointerPanel;
00226                 mainCanvas.Children.Add(popups[currentPoint.PointerId]);
00227             }
00228             TranslateTransform transform = new TranslateTransform();
00229             transform.X = currentPoint.Position.X + 24;
00230             transform.Y = currentPoint.Position.Y + 24;
00231             popups[currentPoint.PointerId].RenderTransform = transform;
00232         }
00233
00234         void HidePropertyPopUp(Windows.UI.Input.PointerPoint currentPoint)
00235         {
00236             if (popups.ContainsKey(currentPoint.PointerId))
00237             {
00238                 mainCanvas.Children.Remove(popups[currentPoint.PointerId]);
00239                 popups[currentPoint.PointerId] = null;
00240                 popups.Remove(currentPoint.PointerId);
00241             }
00242         }
00243     }
00244 }
Generated on Fri Nov 15 2024 22:18:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cs/Scenario1_MeteringData.xaml.cs Source File

  • CustomCapability
  • cs

Scenario1_MeteringData.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.UI.Xaml;
00003 using Windows.UI.Xaml.Controls;
00004 using Windows.UI.Xaml.Controls.Primitives;
00005
00006 // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
00007
00008 namespace SDKTemplate
00009 {
00010     /// <summary>
00011     /// An empty page that can be used on its own or navigated to within a Frame.
00012     /// </summary>
00013     public sealed partial class MeteringData : Page
00014     {
00015         public ServiceViewModel ViewModel;
00016
00017         public MeteringData()
00018         {
00019             InitializeComponent();
00020             ViewModel = ServiceViewModel.Current;
00021         }
00022         public async void button_Click_StartMetering(Object sender, RoutedEventArgs e)
00023         {
00024             await ViewModel.StartMetering((int)SamplePeriodSlider.Value);
00025         }
00026
00027         public async void button_Click_StopMetering(Object sender, RoutedEventArgs e)
00028         {
00029             await ViewModel.StopMetering();
00030         }
00031
00032         public void slider_ValueChanged(Object sender, RangeBaseValueChangedEventArgs e)
00033         {
00034             // Ignore slider value changes prior to ViewModel initialization.
00035             if (ViewModel != null)
00036             {
00037                 // Update the sample period in response to slider change.
00038                 ViewModel.SetSamplePeriod((int)SamplePeriodSlider.Value);
00039             }
00040         }
00041     }
00042 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceSelectorInfo Member List

This is the complete list of members for DeviceSelectorInfo, including all inherited members.
DeviceClassSelector | DeviceSelectorInfo
DisplayName | DeviceSelectorInfo
Kind | DeviceSelectorInfo
Selector | DeviceSelectorInfo
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7_ListAllCards Member List

This is the complete list of members for Scenario7_ListAllCards, including all inherited members.
ListSmartCard_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario7_ListAllCards
Scenario7_ListAllCards() | Scenario7_ListAllCards
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/HttpFilters/HttpRetryFilter.h Source File

  • HttpClient
  • HttpFilters

HttpRetryFilter.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "HttpRetryFilter.g.h"
00014
00015 namespace winrt::HttpFilters::implementation
00016 {
00017     struct HttpRetryFilter : HttpRetryFilterT<HttpRetryFilter>
00018     {
00019         HttpRetryFilter(Windows::Web::Http::Filters::IHttpFilter const& innerFilter);
00020         void Close() {}
00021         Windows::Foundation::IAsyncOperationWithProgress<Windows::Web::Http::HttpResponseMessage, Windows::Web::Http::HttpProgress> SendRequestAsync(Windows::Web::Http::HttpRequestMessage request);
00022
00023     private:
00024         Windows::Web::Http::Filters::IHttpFilter m_innerFilter;
00025
00026         static constexpr wchar_t RetriesPropertyName[] = L"HttpFilters.HttpRetryFilter.Retries";
00027         static uint32_t GetRetriesValue(Windows::Web::Http::HttpRequestMessage const& request);
00028         static Windows::Web::Http::HttpRequestMessage CopyRequestMessage(Windows::Web::Http::HttpRequestMessage const& message);
00029     };
00030 }
00031 namespace winrt::HttpFilters::factory_implementation
00032 {
00033     struct HttpRetryFilter : HttpRetryFilterT<HttpRetryFilter, implementation::HttpRetryFilter>
00034     {
00035     };
00036 }
Generated on Fri Nov 15 2024 22:20:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAccountManagement/cs/MultipleAccountsScenario.xaml.cs Source File

  • WebAccountManagement
  • cs

MultipleAccountsScenario.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Threading.Tasks;
00016 using Windows.Security.Authentication.Web.Core;
00017 using Windows.Security.Credentials;
00018 using Windows.Storage;
00019 using Windows.UI.ApplicationSettings;
00020 using Windows.UI.Popups;
00021 using Windows.UI.Xaml;
00022 using Windows.UI.Xaml.Controls;
00023 using Windows.UI.Xaml.Navigation;
00024
00025 namespace Accounts
00026 {
00027
00028     public sealed partial class MultipleAccountsScenario : Page
00029     {
00030         private MainPage rootPage;
00031
00032         const string AppSpecificProviderId = "myproviderid";
00033         const string AppSpecificProviderName = "App specific provider";
00034
00035         const string AccountsContainer = "accountssettingscontainer";
00036         const string ProviderIdSubContainer = "providers";
00037         const string AuthoritySubContainer = "authorities";
00038
00039         const string MicrosoftProviderId = "https://login.microsoft.com";
00040         const string MicrosoftAccountAuthority = "consumers";
00041         const string AzureActiveDirectoryAuthority = "organizations";
00042
00043         const string MicrosoftAccountClientId = "none";
00044         const string MicrosoftAccountScopeRequested = "wl.basic";
00045
00046         // To obtain azureAD tokens, you must register this app on the AzureAD portal, and obtain the client ID
00047         const string AzureActiveDirectoryClientId = "";
00048         const string AzureActiveDirectoryScopeRequested = "";
00049
00050         public MultipleAccountsScenario()
00051         {
00052             this.InitializeComponent();
00053         }
00054
00055         protected override void OnNavigatedTo(NavigationEventArgs e)
00056         {
00057             rootPage = MainPage.Current;
00058
00059             CreateLocalDataContainers();
00060
00061             AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += OnAccountCommandsRequested;
00062
00063             IdentityChecker.SampleIdentityConfigurationCorrect(NotRegisteredWarning, AzureActiveDirectoryClientId);
00064         }
00065
00066         protected override void OnNavigatedFrom(NavigationEventArgs e)
00067         {
00068             AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= OnAccountCommandsRequested;
00069         }
00070
00071         private void Button_ShowAccountSettings(object sender, RoutedEventArgs e)
00072         {
00073             ((Button)sender).IsEnabled = false;
00074
00075             rootPage.NotifyUser("Launching AccountSettingsPane", NotifyType.StatusMessage);
00076
00077             AccountsSettingsPane.Show();
00078
00079             ((Button)sender).IsEnabled = true;
00080         }
00081
00082         private async void Button_Reset(object sender, RoutedEventArgs e)
00083         {
00084             ((Button)sender).IsEnabled = false;
00085
00086             rootPage.NotifyUser("Resetting ", NotifyType.ErrorMessage);
00087
00088             await LogoffAndRemoveAllAccounts();
00089
00090             ((Button)sender).IsEnabled = true;
00091         }
00092
00093         private async Task<List<WebAccount>> GetAllAccounts()
00094         {
00095             List<WebAccount> accounts = new List<WebAccount>();
00096
00097             ApplicationDataContainer AccountListContainer = ApplicationData.Current.LocalSettings.Containers[AccountsContainer];
00098
00099             foreach (Object value in AccountListContainer.Containers[ProviderIdSubContainer].Values.Keys)
00100             {
00101                 String accountID = value as String;
00102                 String providerID = AccountListContainer.Containers[ProviderIdSubContainer].Values[accountID] as String;
00103                 String authority = AccountListContainer.Containers[AuthoritySubContainer].Values[accountID] as String;
00104
00105                 WebAccountProvider provider = await GetProvider(providerID, authority);
00106
00107                 if (providerID == AppSpecificProviderId)
00108                 {
00109                     accounts.Add(new WebAccount(provider, accountID, WebAccountState.None));
00110                 }
00111                 else
00112                 {
00113                     WebAccount loadedAccount = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountID);
00114                     if(loadedAccount != null)
00115                     {
00116                         accounts.Add(loadedAccount);
00117                     }
00118                     else
00119                     {
00120                         // The account has been deleted
00121                         ApplicationDataContainer accountsContainer = ApplicationData.Current.LocalSettings.Containers[AccountsContainer];
00122
00123                         accountsContainer.Containers[ProviderIdSubContainer].Values.Remove(accountID);
00124                         accountsContainer.Containers[AuthoritySubContainer].Values.Remove(accountID);
00125                     }
00126                 }
00127             }
00128
00129             return accounts;
00130         }
00131         private async Task<List<WebAccountProvider>> GetAllProviders()
00132         {
00133             List<WebAccountProvider> providers = new List<WebAccountProvider>();
00134             providers.Add(await GetProvider(MicrosoftProviderId, MicrosoftAccountAuthority));
00135             providers.Add(await GetProvider(MicrosoftProviderId, AzureActiveDirectoryAuthority));
00136             providers.Add(await GetProvider(AppSpecificProviderId));
00137
00138             return providers;
00139         }
00140
00141
00142         private async Task<WebAccountProvider> GetProvider(string ProviderID, string AuthorityId = "")
00143         {
00144             if (ProviderID == AppSpecificProviderId)
00145             {
00146                 return new WebAccountProvider(AppSpecificProviderId, AppSpecificProviderName, new Uri(this.BaseUri, "Assets/smallTile-sdk.png"));
00147             }
00148             else
00149             {
00150                 return await WebAuthenticationCoreManager.FindAccountProviderAsync(ProviderID, AuthorityId);
00151             }
00152         }
00153
00154         private async void OnAccountCommandsRequested(
00155             AccountsSettingsPane sender,
00156             AccountsSettingsPaneCommandsRequestedEventArgs e)
00157         {
00158             // In order to make async calls within this callback, the deferral object is needed
00159             AccountsSettingsPaneEventDeferral deferral = e.GetDeferral();
00160
00161             // This scenario only supports a single account at one time.
00162             // If there already is an account, we do not include a provider in the list
00163             // This will prevent the add account button from showing up.
00164             await AddWebAccountProvidersToPane(e);
00165             await AddWebAccountsToPane(e);
00166             AddLinksAndDescription(e);
00167
00168             deferral.Complete();
00169         }
00170
00171         private void AddLinksAndDescription(AccountsSettingsPaneCommandsRequestedEventArgs e)
00172         {
00173             e.HeaderText = "Describe what adding an account to your application will do for the user";
00174
00175             // You can add links such as privacy policy, help, general account settings
00176             e.Commands.Add(new SettingsCommand("privacypolicy", "Privacy policy", PrivacyPolicyInvoked));
00177             e.Commands.Add(new SettingsCommand("otherlink", "Other link", OtherLinkInvoked));
00178         }
00179
00180         private void OtherLinkInvoked(IUICommand command)
00181         {
00182             rootPage.NotifyUser("Other link pressed by user", NotifyType.StatusMessage);
00183         }
00184
00185         private void PrivacyPolicyInvoked(IUICommand command)
00186         {
00187             rootPage.NotifyUser("Privacy policy clicked by user", NotifyType.StatusMessage);
00188         }
00189
00190         private async Task AddWebAccountProvidersToPane(AccountsSettingsPaneCommandsRequestedEventArgs e)
00191         {
00192             // The order of providers displayed is determined by the order provided to the Accounts pane
00193             List<WebAccountProvider> providers = await GetAllProviders();
00194
00195             foreach (WebAccountProvider provider in providers)
00196             {
00197                 WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);
00198                 e.WebAccountProviderCommands.Add(providerCommand);
00199             }
00200         }
00201
00202         private async Task AddWebAccountsToPane(AccountsSettingsPaneCommandsRequestedEventArgs e)
00203         {
00204             List<WebAccount> accounts = await GetAllAccounts();
00205
00206             foreach (WebAccount account in accounts)
00207             {
00208                 WebAccountCommand command = new WebAccountCommand(account, WebAccountInvoked, SupportedWebAccountActions.Remove | SupportedWebAccountActions.Manage);
00209                 e.WebAccountCommands.Add(command);
00210             }
00211         }
00212
00213         private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
00214         {
00215             if ((command.WebAccountProvider.Id == MicrosoftProviderId) && (command.WebAccountProvider.Authority == MicrosoftAccountAuthority))
00216             {
00217                 // ClientID is ignored by MSA
00218                 await AuthenticateWithRequestToken(command.WebAccountProvider, MicrosoftAccountScopeRequested, MicrosoftAccountClientId);
00219             }
00220             else if ((command.WebAccountProvider.Id == MicrosoftProviderId) && (command.WebAccountProvider.Authority == AzureActiveDirectoryAuthority))
00221             {
00222                 await AuthenticateWithRequestToken(command.WebAccountProvider, AzureActiveDirectoryScopeRequested, AzureActiveDirectoryClientId);
00223             }
00224             else if (command.WebAccountProvider.Id == AppSpecificProviderId)
00225             {
00226                 // Show user registration/login for your app specific account type.
00227                 // Store the user if registration/login successful
00228                 StoreNewAccountDataLocally(new WebAccount(command.WebAccountProvider, "App Specific User(" + DateTime.Now + ")", WebAccountState.None));
00229             }
00230         }
00231
00232         public async Task AuthenticateWithRequestToken(WebAccountProvider Provider, String Scope, String ClientID)
00233         {
00234             try
00235             {
00236                 WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID);
00237
00238                 // Azure Active Directory requires a resource to return a token
00239                 if (Provider.Id == "https://login.microsoft.com" && Provider.Authority == "organizations")
00240                 {
00241                     webTokenRequest.Properties.Add("resource", "https://graph.windows.net");
00242                 }
00243
00244                 // If the user selected a specific account, RequestTokenAsync will return a token for that account.
00245                 // The user may be prompted for credentials or to authorize using that account with your app
00246                 // If the user selected a provider, the user will be prompted for credentials to login to a new account
00247                 WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
00248
00249                 if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
00250                 {
00251                     StoreNewAccountDataLocally(webTokenRequestResult.ResponseData[0].WebAccount);
00252                 }
00253
00254                 OutputTokenResult(webTokenRequestResult);
00255             }
00256             catch (Exception ex)
00257             {
00258                 rootPage.NotifyUser("Web Token request failed: " + ex, NotifyType.ErrorMessage);
00259             }
00260         }
00261
00262         public void StoreNewAccountDataLocally(WebAccount account)
00263         {
00264             ApplicationDataContainer accountsContainer = ApplicationData.Current.LocalSettings.Containers[AccountsContainer];
00265
00266             if (account.Id != "")
00267             {
00268                 accountsContainer.Containers[ProviderIdSubContainer].Values[account.Id] = account.WebAccountProvider.Id;
00269                 accountsContainer.Containers[AuthoritySubContainer].Values[account.Id] = account.WebAccountProvider.Authority;
00270             }
00271             else
00272             {
00273                 accountsContainer.Containers[ProviderIdSubContainer].Values[account.UserName] = account.WebAccountProvider.Id;
00274             }
00275
00276         }
00277
00278         public void OutputTokenResult(WebTokenRequestResult result)
00279         {
00280             if (result.ResponseStatus == WebTokenRequestStatus.Success)
00281             {
00282                 rootPage.NotifyUser("Web Token request successful for user:" + result.ResponseData[0].WebAccount.UserName, NotifyType.StatusMessage);
00283             }
00284             else
00285             {
00286                 rootPage.NotifyUser("Web Token request error: " + result.ResponseError, NotifyType.StatusMessage);
00287             }
00288         }
00289
00290         private async void WebAccountInvoked(WebAccountCommand command, WebAccountInvokedArgs args)
00291         {
00292             if (args.Action == WebAccountAction.Remove)
00293             {
00294                 await LogoffAndRemoveAccount(command.WebAccount);
00295             }
00296             else if (args.Action == WebAccountAction.Manage)
00297             {
00298                 // Display user management UI for this account
00299                 rootPage.NotifyUser("Manage invoked for user: " + command.WebAccount.UserName, NotifyType.StatusMessage);
00300             }
00301         }
00302
00303         private async Task LogoffAndRemoveAccount(WebAccount account)
00304         {
00305             ApplicationDataContainer accountsContainer = ApplicationData.Current.LocalSettings.Containers[AccountsContainer];
00306
00307             if(account.WebAccountProvider.Id != AppSpecificProviderId)
00308             {
00309                 await account.SignOutAsync();
00310
00311                 accountsContainer.Containers[ProviderIdSubContainer].Values.Remove(account.Id);
00312                 accountsContainer.Containers[AuthoritySubContainer].Values.Remove(account.Id);
00313             }
00314             else
00315             {
00316                 //perform any actions needed to log off the app specific account
00317                 accountsContainer.Containers[ProviderIdSubContainer].Values.Remove(account.UserName);
00318             }
00319         }
00320
00321         private async Task LogoffAndRemoveAllAccounts()
00322         {
00323             List<WebAccount> accounts = await GetAllAccounts();
00324
00325             foreach(WebAccount account in accounts)
00326             {
00327                 await LogoffAndRemoveAccount(account);
00328             }
00329
00330             accounts = null;
00331         }
00332
00333         private void CreateLocalDataContainers()
00334         {
00335             ApplicationData.Current.LocalSettings.CreateContainer(AccountsContainer, ApplicationDataCreateDisposition.Always);
00336             ApplicationData.Current.LocalSettings.Containers[AccountsContainer].CreateContainer(ProviderIdSubContainer, ApplicationDataCreateDisposition.Always);
00337             ApplicationData.Current.LocalSettings.Containers[AccountsContainer].CreateContainer(AuthoritySubContainer, ApplicationDataCreateDisposition.Always);
00338         }
00339     }
00340 }
Generated on Fri Nov 15 2024 22:21:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDataVirtualization/cs/Scenario1/FileDataSource.cs Source File

  • XamlDataVirtualization
  • cs
  • Scenario1

FileDataSource.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Collections.Specialized;
00004 using System.Diagnostics;
00005 using System.Linq;
00006 using System.Threading;
00007 using System.Threading.Tasks;
00008 using Windows.Storage;
00009 using Windows.Storage.Search;
00010 using Windows.UI.Core;
00011 using Windows.UI.Xaml.Data;
00012
00013 namespace DataVirtualizationSample
00014 {
00015     //********************************************************************************************
00016     //*
00017     //* Note: This sample uses a custom compiler constant to enable tracing. If you add
00018     //* TRACE_DATASOURCE to the Conditional compilation symbols of the Build tab of the
00019     //* Project Properties window, then the application will spit out trace data to the
00020     //* Output window while debugging.
00021     //*
00022     //********************************************************************************************
00023
00024
00025     /// <summary>
00026     /// A custom datasource over the file system that supports data virtualization
00027     /// </summary>
00028     class FileDataSource : INotifyCollectionChanged, System.Collections.IList, IItemsRangeInfo
00029     {
00030         // Folder that we are browsing
00031         private StorageFolder _folder;
00032         // Query object that will tell us if the folder content changed
00033         private StorageFileQueryResult _queryResult;
00034         // Dispatcher so we can marshal calls back to the UI thread
00035         private CoreDispatcher _dispatcher;
00036
00037         // Cache for the file data that is currently being used
00038         private ItemCacheManager<FileItem> itemCache;
00039
00040         // Total number of files available
00041         private int _count = 1;
00042
00043         public event NotifyCollectionChangedEventHandler CollectionChanged;
00044
00045         private FileDataSource()
00046         {
00047             //Setup the dispatcher for the UI thread
00048             _dispatcher = Windows.UI.Xaml.Window.Current.Dispatcher;
00049
00050             // The ItemCacheManager does most of the heavy lifting. We pass it a callback that it will use to actually fetch data, and the max size of a request
00051             this.itemCache = new ItemCacheManager<FileItem>(fetchDataCallback, 50);
00052             this.itemCache.CacheChanged += ItemCache_CacheChanged;
00053         }
00054
00055         // Factory method to create the datasource
00056         // Requires async work which is why it needs a factory rather than being part of the constructor
00057         public static async Task<FileDataSource> GetDataSoure(string path)
00058         {
00059             FileDataSource ds = new FileDataSource();
00060             StorageFolder f = await StorageFolder.GetFolderFromPathAsync(path);
00061             await ds.SetFolder(f);
00062             return ds;
00063         }
00064
00065         // Set functionality for the folder
00066         public async Task SetFolder(StorageFolder folder)
00067         {
00068             //unhook the old contents changed event if applicable
00069             if (_queryResult != null)
00070             {
00071                 _queryResult.ContentsChanged -= QueryResult_ContentsChanged;
00072             }
00073             // Initialize the query and register for changes
00074             _folder = folder;
00075             QueryOptions options = new QueryOptions();
00076             // options.IndexerOption = IndexerOption.DoNotUseIndexer;
00077             _queryResult = _folder.CreateFileQueryWithOptions(options);
00078             _queryResult.ContentsChanged += QueryResult_ContentsChanged;
00079             await UpdateCount();
00080         }
00081
00082         // Handler for when the filesystem notifies us of a change to the file list
00083         private void QueryResult_ContentsChanged(IStorageQueryResultBase sender, object args)
00084         {
00085             // This callback can occur on a different thread so we need to marshal it back to the UI thread
00086             if (!_dispatcher.HasThreadAccess)
00087             {
00088                 var t = _dispatcher.RunAsync(CoreDispatcherPriority.Normal, ResetCollection);
00089             }
00090             else
00091             {
00092                 ResetCollection();
00093             }
00094         }
00095
00096         // Handles a change notification for the list of files from the OS
00097         private void ResetCollection()
00098         {
00099             // Unhook the old change notification
00100             if (itemCache != null)
00101             {
00102                 this.itemCache.CacheChanged -= ItemCache_CacheChanged;
00103             }
00104
00105             // Create a new instance of the cache manager
00106             this.itemCache = new ItemCacheManager<FileItem>(fetchDataCallback, 50);
00107             this.itemCache.CacheChanged += ItemCache_CacheChanged;
00108             if (CollectionChanged != null)
00109             {
00110                 CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
00111             }
00112         }
00113
00114         async Task UpdateCount()
00115         {
00116             _count = (int)await _queryResult.GetItemCountAsync();
00117             if (CollectionChanged != null)
00118             {
00119                 CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
00120             }
00121         }
00122
00123         #region IList Implementation
00124
00125         public bool Contains(object value)
00126         {
00127             return IndexOf(value) != -1;
00128         }
00129
00130         public int IndexOf(object value)
00131         {
00132             return (value != null) ? itemCache.IndexOf((FileItem)value) : -1;
00133         }
00134
00135         public object this[int index]
00136         {
00137             get
00138             {
00139                 // The cache will return null if it doesn't have the item. Once the item is fetched it will fire a changed event so that we can inform the list control
00140                 return itemCache[index];
00141             }
00142             set
00143             {
00144                 throw new NotImplementedException();
00145             }
00146         }
00147         public int Count
00148         {
00149             get { return _count; }
00150         }
00151
00152         #endregion
00153
00154         //Required for the IItemsRangeInfo interface
00155         public void Dispose()
00156         {
00157             itemCache = null;
00158         }
00159
00160         /// <summary>
00161         /// Primary method for IItemsRangeInfo interface
00162         /// Is called when the list control's view is changed
00163         /// </summary>
00164         /// <param name="visibleRange">The range of items that are actually visible</param>
00165         /// <param name="trackedItems">Additional set of ranges that the list is using, for example the buffer regions and focussed element</param>
00166         public void RangesChanged(ItemIndexRange visibleRange, IReadOnlyList<ItemIndexRange> trackedItems)
00167         {
00168 #if TRACE_DATASOURCE
00169             string s = string.Format("* RangesChanged fired: Visible {0}->{1}", visibleRange.FirstIndex, visibleRange.LastIndex);
00170             foreach (ItemIndexRange r in trackedItems) { s += string.Format(" {0}->{1}", r.FirstIndex, r.LastIndex); }
00171             Debug.WriteLine(s);
00172 #endif
00173             // We know that the visible range is included in the broader range so don't need to hand it to the UpdateRanges call
00174             // Update the cache of items based on the new set of ranges. It will callback for additional data if required
00175             itemCache.UpdateRanges(trackedItems.ToArray());
00176         }
00177
00178         // Callback from itemcache that it needs items to be retrieved
00179         // Using this callback model abstracts the details of this specific datasource from the cache implementation
00180         private async Task<FileItem[]> fetchDataCallback(ItemIndexRange batch, CancellationToken ct)
00181         {
00182             // Fetch file objects from filesystem
00183             IReadOnlyList<StorageFile> results = await _queryResult.GetFilesAsync((uint)batch.FirstIndex, Math.Max(batch.Length, 20)).AsTask(ct);
00184             List<FileItem> files = new List<FileItem>();
00185             if (results != null)
00186             {
00187                 for (int i = 0; i < results.Count; i++)
00188                 {
00189                     // Check if request has been cancelled, if so abort getting additional data
00190                     ct.ThrowIfCancellationRequested();
00191                     // Create our FileItem object with the file data and thumbnail
00192                     FileItem newItem = await FileItem.fromStorageFile(results[i], ct);
00193                     files.Add(newItem);
00194                 }
00195             }
00196             return files.ToArray();
00197         }
00198
00199         // Event fired when items are inserted in the cache
00200         // Used to fire our collection changed event
00201         private void ItemCache_CacheChanged(object sender, CacheChangedEventArgs<FileItem> args)
00202         {
00203             if (CollectionChanged != null)
00204             {
00205                 CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, args.oldItem, args.newItem, args.itemIndex));
00206             }
00207         }
00208
00209         #region Parts of IList Not Implemented
00210
00211         public int Add(object value)
00212         {
00213             throw new NotImplementedException();
00214         }
00215
00216         public void Clear()
00217         {
00218             throw new NotImplementedException();
00219         }
00220
00221         public void Insert(int index, object value)
00222         {
00223             throw new NotImplementedException();
00224         }
00225
00226         public bool IsFixedSize
00227         {
00228             get { return false; }
00229         }
00230
00231         public bool IsReadOnly
00232         {
00233             get { return false; }
00234         }
00235
00236         public void Remove(object value)
00237         {
00238             throw new NotImplementedException();
00239         }
00240
00241         public void RemoveAt(int index)
00242         {
00243             throw new NotImplementedException();
00244         }
00245         public void CopyTo(Array array, int index)
00246         {
00247             throw new NotImplementedException();
00248         }
00249
00250         public bool IsSynchronized
00251         {
00252             get { throw new NotImplementedException(); }
00253         }
00254
00255         public object SyncRoot
00256         {
00257             get { throw new NotImplementedException(); }
00258         }
00259
00260         public System.Collections.IEnumerator GetEnumerator()
00261         {
00262             throw new NotImplementedException();
00263         }
00264
00265         #endregion
00266     }
00267
00268
00269 }
Generated on Fri Nov 15 2024 22:22:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSerialDeviceAccess/cs/Utilities.cs Source File

  • CustomSerialDeviceAccess
  • cs

Utilities.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017
00018 using SDKTemplate;
00019
00020 namespace CustomSerialDeviceAccess
00021 {
00022     /// <summary>
00023     /// This class is intended to host any functionality that will be shared among different
00024     /// scenario/pages such as common error messages.
00025     /// </summary>
00026     public class Utilities
00027     {
00028         /// <summary>
00029         /// Prints an error message stating that device is not connected
00030         /// </summary>
00031         public static void NotifyDeviceNotConnected()
00032         {
00033             MainPage.Current.NotifyUser("Device is not connected, please select a plugged in device to try the scenario again", NotifyType.ErrorMessage);
00034         }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cpp/SampleConfiguration.h Source File

  • Pedometer
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Pedometer";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DateTimeOffsetConverter Member List

This is the complete list of members for DateTimeOffsetConverter, including all inherited members.
Convert(object value, Type targetType, object parameter, string language) | DateTimeOffsetConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | DateTimeOffsetConverter | [inline]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CMarker Member List

This is the complete list of members for CMarker, including all inherited members.
_cRef | CMarker | [private]
_eMarkerType | CMarker | [protected]
_varContextValue | CMarker | [protected]
_varMarkerValue | CMarker | [protected]
CMarker(MFSTREAMSINK_MARKER_TYPE eMarkerType) | CMarker | [private]
Create(MFSTREAMSINK_MARKER_TYPE eMarkerType, const PROPVARIANT *pvarMarkerValue, const PROPVARIANT *pvarContextValue, IMarker **ppMarker) | CMarker | [static]
GetContext(PROPVARIANT *pvar) | CMarker |
GetMarkerType(MFSTREAMSINK_MARKER_TYPE *pType) | CMarker |
GetMarkerValue(PROPVARIANT *pvar) | CMarker |
IFACEMETHOD_(ULONG, AddRef)() | CMarker |
IFACEMETHOD_(ULONG, Release)() | CMarker |
QueryInterface(REFIID riid, void **ppv) | CMarker |
~CMarker() | CMarker | [private, virtual]
Generated on Fri Nov 15 2024 22:23:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cppwinrt/Scenario5.h Source File

  • FileThumbnails
  • cppwinrt

Scenario5.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario5.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario5 : Scenario5T<Scenario5>
00020     {
00021         Scenario5();
00022         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00023         fire_and_forget GetThumbnailButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024
00025     private:
00026         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario5 : Scenario5T<Scenario5, implementation::Scenario5>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:19:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialMapping/cpp/AppView.cpp Source File

  • HolographicSpatialMapping
  • cpp

AppView.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "AppView.h"
00014
00015 #include <ppltasks.h>
00016
00017 using namespace HolographicSpatialMapping;
00018
00019 using namespace concurrency;
00020 using namespace Windows::ApplicationModel;
00021 using namespace Windows::ApplicationModel::Activation;
00022 using namespace Windows::ApplicationModel::Core;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Graphics::Holographic;
00025 using namespace Windows::UI::Core;
00026
00027 // The main function is only used to initialize our IFrameworkView class.
00028 // Under most circumstances, you should not need to modify this function.
00029 [Platform::MTAThread]
00030 int main(Platform::Array<Platform::String^>^)
00031 {
00032     AppViewSource^ appViewSource = ref new ::AppViewSource();
00033     CoreApplication::Run(appViewSource);
00034     return 0;
00035 }
00036
00037 IFrameworkView^ AppViewSource::CreateView()
00038 {
00039     return ref new AppView();
00040 }
00041
00042 AppView::AppView()
00043 {
00044 }
00045
00046
00047 // IFrameworkView methods
00048
00049 // The first method called when the IFrameworkView is being created.
00050 // Use this method to subscribe for Windows shell events and to initialize your app.
00051 void AppView::Initialize(CoreApplicationView^ applicationView)
00052 {
00053     applicationView->Activated +=
00054         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &AppView::OnViewActivated);
00055
00056     // Register event handlers for app lifecycle.
00057     CoreApplication::Suspending +=
00058         ref new EventHandler<SuspendingEventArgs^>(this, &AppView::OnSuspending);
00059
00060     CoreApplication::Resuming +=
00061         ref new EventHandler<Platform::Object^>(this, &AppView::OnResuming);
00062
00063     // At this point we have access to the device and we can create device-dependent
00064     // resources.
00065     m_deviceResources = std::make_shared<DX::DeviceResources>();
00066
00067     m_main = std::make_unique<HolographicSpatialMappingMain>(m_deviceResources);
00068 }
00069
00070 // Called when the CoreWindow object is created (or re-created).
00071 void AppView::SetWindow(CoreWindow^ window)
00072 {
00073     // Register for keypress notifications.
00074     window->KeyDown +=
00075         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &AppView::OnKeyPressed);
00076
00077     // Register for notification that the app window is being closed.
00078     window->Closed +=
00079         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &AppView::OnWindowClosed);
00080
00081     // Register for notifications that the app window is losing focus.
00082     window->VisibilityChanged +=
00083         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &AppView::OnVisibilityChanged);
00084
00085     // Create a holographic space for the core window for the current view.
00086     // Presenting holographic frames that are created by this holographic space will put
00087     // the app into exclusive mode.
00088     m_holographicSpace = HolographicSpace::CreateForCoreWindow(window);
00089
00090     // The DeviceResources class uses the preferred DXGI adapter ID from the holographic
00091     // space (when available) to create a Direct3D device. The HolographicSpace
00092     // uses this ID3D11Device to create and manage device-based resources such as
00093     // swap chains.
00094     m_deviceResources->SetHolographicSpace(m_holographicSpace);
00095
00096     // The main class uses the holographic space for updates and rendering.
00097     m_main->SetHolographicSpace(m_holographicSpace);
00098 }
00099
00100 // The Load method can be used to initialize scene resources or to load a
00101 // previously saved app state.
00102 void AppView::Load(Platform::String^ entryPoint)
00103 {
00104 }
00105
00106 // This method is called after the window becomes active. It oversees the
00107 // update, draw, and present loop, and it also oversees window message processing.
00108 void AppView::Run()
00109 {
00110     while (!m_windowClosed)
00111     {
00112         if (m_windowVisible && (m_holographicSpace != nullptr))
00113         {
00114             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00115
00116             HolographicFrame^ holographicFrame = m_main->Update();
00117
00118             if (m_main->Render(holographicFrame))
00119             {
00120                 // The holographic frame has an API that presents the swap chain for each
00121                 // holographic camera.
00122                 m_deviceResources->Present(holographicFrame);
00123             }
00124         }
00125         else
00126         {
00127             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00128         }
00129     }
00130 }
00131
00132 // Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
00133 // class is torn down while the app is in the foreground.
00134 // This method is not often used, but IFrameworkView requires it and it will be called for
00135 // holographic apps.
00136 void AppView::Uninitialize()
00137 {
00138
00139 }
00140
00141
00142 // Application lifecycle event handlers
00143
00144 // Called when the app view is activated. Activates the app's CoreWindow.
00145 void AppView::OnViewActivated(CoreApplicationView^ sender, IActivatedEventArgs^ args)
00146 {
00147     // Run() won't start until the CoreWindow is activated.
00148     sender->CoreWindow->Activate();
00149 }
00150
00151 void AppView::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
00152 {
00153     // Save app state asynchronously after requesting a deferral. Holding a deferral
00154     // indicates that the application is busy performing suspending operations. Be
00155     // aware that a deferral may not be held indefinitely; after about five seconds,
00156     // the app will be forced to exit.
00157     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
00158
00159     create_task([this, deferral] ()
00160     {
00161         m_deviceResources->Trim();
00162
00163         if (m_main != nullptr)
00164         {
00165             m_main->SaveAppState();
00166         }
00167
00168         deferral->Complete();
00169     });
00170 }
00171
00172 void AppView::OnResuming(Platform::Object^ sender, Platform::Object^ args)
00173 {
00174     // Restore any data or state that was unloaded on suspend. By default, data
00175     // and state are persisted when resuming from suspend. Note that this event
00176     // does not occur if the app was previously terminated.
00177
00178     if (m_main != nullptr)
00179     {
00180         m_main->LoadAppState();
00181     }
00182 }
00183
00184
00185 // Window event handlers
00186
00187 void AppView::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
00188 {
00189     m_windowVisible = args->Visible;
00190 }
00191
00192 void AppView::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
00193 {
00194     m_windowClosed = true;
00195 }
00196
00197
00198 // Input event handlers
00199
00200 void AppView::OnKeyPressed(CoreWindow^ sender, KeyEventArgs^ args)
00201 {
00202     // This code sample does not use keyboard input.
00203 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/Common/DeviceResources.h Source File

  • HolographicTagAlong
  • cpp
  • Common

DeviceResources.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "CameraResources.h"
00015
00016 namespace DX
00017 {
00018     // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created.
00019     interface IDeviceNotify
00020     {
00021         virtual void OnDeviceLost()     = 0;
00022         virtual void OnDeviceRestored() = 0;
00023     };
00024
00025     // Creates and manages a Direct3D device and immediate context, Direct2D device and context (for debug), and the holographic swap chain.
00026     class DeviceResources
00027     {
00028     public:
00029         DeviceResources();
00030
00031         // Public methods related to Direct3D devices.
00032         void HandleDeviceLost();
00033         void RegisterDeviceNotify(IDeviceNotify* deviceNotify);
00034         void Trim();
00035         void Present(Windows::Graphics::Holographic::HolographicFrame^ frame);
00036
00037         // Public methods related to holographic devices.
00038         void SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^ space);
00039         void EnsureCameraResources(
00040             Windows::Graphics::Holographic::HolographicFrame^ frame,
00041             Windows::Graphics::Holographic::HolographicFramePrediction^ prediction);
00042
00043         void AddHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^ camera);
00044         void RemoveHolographicCamera(Windows::Graphics::Holographic::HolographicCamera^ camera);
00045
00046         // Holographic accessors.
00047         template<typename RetType, typename LCallback>
00048         RetType                 UseHolographicCameraResources(const LCallback& callback);
00049
00050         Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^
00051                                 GetD3DInteropDevice() const             { return m_d3dInteropDevice;    }
00052
00053         // D3D accessors.
00054         ID3D11Device4*          GetD3DDevice() const                    { return m_d3dDevice.Get();     }
00055         ID3D11DeviceContext3*   GetD3DDeviceContext() const             { return m_d3dContext.Get();    }
00056         D3D_FEATURE_LEVEL       GetDeviceFeatureLevel() const           { return m_d3dFeatureLevel;     }
00057         bool                    GetDeviceSupportsVprt() const           { return m_supportsVprt;        }
00058
00059         // DXGI acessors.
00060         IDXGIAdapter3*          GetDXGIAdapter() const                  { return m_dxgiAdapter.Get();   }
00061
00062         // D2D accessors.
00063         ID2D1Factory2*          GetD2DFactory() const                   { return m_d2dFactory.Get();    }
00064         IDWriteFactory2*        GetDWriteFactory() const                { return m_dwriteFactory.Get(); }
00065         IWICImagingFactory2*    GetWicImagingFactory() const            { return m_wicFactory.Get();    }
00066
00067     private:
00068         // Private methods related to the Direct3D device, and resources based on that device.
00069         void CreateDeviceIndependentResources();
00070         void InitializeUsingHolographicSpace();
00071         void CreateDeviceResources();
00072
00073         // Direct3D objects.
00074         Microsoft::WRL::ComPtr<ID3D11Device4>                   m_d3dDevice;
00075         Microsoft::WRL::ComPtr<ID3D11DeviceContext3>            m_d3dContext;
00076         Microsoft::WRL::ComPtr<IDXGIAdapter3>                   m_dxgiAdapter;
00077
00078         // Direct3D interop objects.
00079         Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice^ m_d3dInteropDevice;
00080
00081         // Direct2D factories.
00082         Microsoft::WRL::ComPtr<ID2D1Factory2>                   m_d2dFactory;
00083         Microsoft::WRL::ComPtr<IDWriteFactory2>                 m_dwriteFactory;
00084         Microsoft::WRL::ComPtr<IWICImagingFactory2>             m_wicFactory;
00085
00086         // The holographic space provides a preferred DXGI adapter ID.
00087         Windows::Graphics::Holographic::HolographicSpace^       m_holographicSpace = nullptr;
00088
00089         // Properties of the Direct3D device currently in use.
00090         D3D_FEATURE_LEVEL                                       m_d3dFeatureLevel = D3D_FEATURE_LEVEL_10_0;
00091
00092         // The IDeviceNotify can be held directly as it owns the DeviceResources.
00093         IDeviceNotify*                                          m_deviceNotify = nullptr;
00094
00095         // Whether or not the current Direct3D device supports the optional feature
00096         // for setting the render target array index from the vertex shader stage.
00097         bool                                                    m_supportsVprt = false;
00098
00099         // Back buffer resources, etc. for attached holographic cameras.
00100         std::map<UINT32, std::unique_ptr<CameraResources>>      m_cameraResources;
00101         std::mutex                                              m_cameraResourcesLock;
00102     };
00103 }
00104
00105 // Device-based resources for holographic cameras are stored in a std::map. Access this list by providing a
00106 // callback to this function, and the std::map will be guarded from add and remove
00107 // events until the callback returns. The callback is processed immediately and must
00108 // not contain any nested calls to UseHolographicCameraResources.
00109 // The callback takes a parameter of type std::map<UINT32, std::unique_ptr<DX::CameraResources>>&
00110 // through which the list of cameras will be accessed.
00111 template<typename RetType, typename LCallback>
00112 RetType DX::DeviceResources::UseHolographicCameraResources(const LCallback& callback)
00113 {
00114     std::lock_guard<std::mutex> guard(m_cameraResourcesLock);
00115     return callback(m_cameraResources);
00116 }
00117
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteLineSpacingModes/cpp/DWriteLineSpacingModes/Scenario2_UniformSpacing.xaml.h Source File

  • DWriteLineSpacingModes
  • cpp
  • DWriteLineSpacingModes

Scenario2_UniformSpacing.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_UniformSpacing.g.h"
00015
00016 using namespace DWriteTextLayoutImplementation;
00017 using namespace Windows::UI::Xaml::Interop;
00018
00019 namespace SDKTemplate
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class Scenario2_UniformSpacing sealed
00023     {
00024     public:
00025         Scenario2_UniformSpacing();
00026
00027         // bindable view-model properties:
00028
00029         property double LineSpacingHeight
00030         {
00031             double get() { return static_cast<double>(m_textLayout->LineSpacingHeight); }
00032             void set(double value);
00033         }
00034
00035         property double LineSpacingBaseline
00036         {
00037             double get() { return static_cast<double>(m_textLayout->LineSpacingBaseline); }
00038             void set(double value);
00039         }
00040
00041         property Platform::String^ TextLayoutHeight
00042         {
00043             Platform::String^ get() { return m_textLayoutLineMetrics[0]->height.ToString(); }
00044         }
00045
00046         property Platform::String^ TextLayoutBaseline
00047         {
00048             Platform::String^ get() { return m_textLayoutLineMetrics[0]->baseline.ToString(); }
00049         }
00050
00051         property Platform::String^ TextLayoutLeadingBefore
00052         {
00053             Platform::String^ get() { return m_textLayoutLineMetrics[0]->leadingBefore.ToString(); }
00054         }
00055
00056         property Platform::String^ TextLayoutLeadingAfter
00057         {
00058             Platform::String^ get() { return m_textLayoutLineMetrics[0]->leadingAfter.ToString(); }
00059         }
00060
00061     private:
00062         TextLayout^                                     m_textLayout;
00063         TextLayoutImageSource^                          m_textLayoutImageSource;
00064         Platform::Array<LineMetrics^>^                  m_textLayoutLineMetrics;
00065     };
00066 }
Generated on Fri Nov 15 2024 22:19:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Helpers.cpp Source File

  • HttpClient
  • cppwinrt

Helpers.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016 #include "Helpers.h"
00017
00018 using namespace winrt;
00019 using namespace winrt::Windows::Foundation;
00020 using namespace winrt::Windows::Foundation::Collections;
00021 using namespace winrt::Windows::UI::Xaml::Controls;
00022 using namespace winrt::Windows::Web;
00023 using namespace winrt::Windows::Web::Http;
00024 using namespace winrt::Windows::Web::Http::Filters;
00025 using namespace winrt::Windows::Web::Http::Headers;
00026
00027 namespace winrt::SDKTemplate::Helpers
00028 {
00029     hstring ToSimpleString(Windows::Foundation::DateTime dateTime)
00030     {
00031         auto time = clock::to_time_t(dateTime);
00032         char buffer[26];
00033         ctime_s(buffer, ARRAYSIZE(buffer), &time);
00034         buffer[25] = 0; // remove the trailing newline
00035         return to_hstring(buffer);
00036     }
00037
00038     IAsyncAction DisplayTextResultAsync(HttpResponseMessage response, TextBox output)
00039     {
00040         output.Text(output.Text() + SerializeHeaders(response));
00041
00042         auto cancellation = co_await get_cancellation_token();
00043         cancellation.enable_propagation();
00044
00045         std::wstring text{ co_await response.Content().ReadAsStringAsync() };
00046
00047         // Change <BR> to newlines.
00048         for (auto pos = text.find(L"<br>"); pos != std::wstring::npos; pos = text.find(L"<br>", pos + 1))
00049         {
00050             text.replace(pos, 4, L"\n");
00051         }
00052
00053         output.Text(output.Text() + hstring(text));
00054     }
00055
00056     hstring SerializeHeaders(HttpResponseMessage const& response)
00057     {
00058         std::wostringstream output;
00059
00060         auto SerializeHeaderCollection = [&](IIterable<IKeyValuePair<hstring, hstring>> const& headers)
00061         {
00062             for (auto [key, value] : headers)
00063             {
00064                 output << std::wstring_view(key) << L": " << std::wstring_view(value) << L"\n";
00065             }
00066         };
00067
00068         // We cast the StatusCode to an int so we display the numeric value (e.g., "200") rather than the
00069         // name of the enum (e.g., "OK") which would often be redundant with the ReasonPhrase.
00070
00071         output << static_cast<int32_t>(response.StatusCode()) << L" " << std::wstring_view(response.ReasonPhrase()) << L"\n";
00072
00073         SerializeHeaderCollection(response.Headers());
00074         SerializeHeaderCollection(response.Content().Headers());
00075         output << L"\n";
00076         return hstring(output.str());
00077     }
00078
00079     void DisplayWebError(MainPage const& rootPage, hresult const& error)
00080     {
00081         WebErrorStatus webErrorStatus = WebError::GetStatus(error);
00082         if (webErrorStatus == WebErrorStatus::Unknown)
00083         {
00084             rootPage.NotifyUser(L"Unknown Error: " + hresult_error(error).message(), NotifyType::ErrorMessage);
00085         }
00086         else
00087         {
00088             rootPage.NotifyUser(L"Web Error: " + to_hstring(webErrorStatus), NotifyType::ErrorMessage);
00089         }
00090
00091     }
00092
00093     HttpClient CreateHttpClientWithCustomHeaders()
00094     {
00095         // HttpClient functionality can be extended by plugging multiple filters together and providing
00096         // HttpClient with the configured filter pipeline.
00097         IHttpFilter filter = HttpBaseProtocolFilter();
00098         filter = PlugInFilter(filter); // Adds a custom header to every request and response message.
00099         HttpClient httpClient(filter);
00100
00101         // The following line sets a "User-Agent" request header as a default header on the HttpClient instance.
00102         // Default headers will be sent with every request sent from this HttpClient instance.
00103         httpClient.DefaultRequestHeaders().UserAgent().Append(HttpProductInfoHeaderValue(L"Sample", L"v8"));
00104
00105         return httpClient;
00106     }
00107
00108     void ScenarioStarted(Button const& startButton, Button const& cancelButton, TextBox const& outputField)
00109     {
00110         startButton.IsEnabled(false);
00111         cancelButton.IsEnabled(true);
00112         if (outputField != nullptr)
00113         {
00114             outputField.Text(L"");
00115         }
00116     }
00117
00118     void ScenarioCompleted(Button const& startButton, Button const& cancelButton)
00119     {
00120         startButton.IsEnabled(true);
00121         cancelButton.IsEnabled(false);
00122     }
00123
00124     void ReplaceQueryString(TextBox const& addressField, hstring const& newQueryString)
00125     {
00126         hstring resourceAddress = addressField.Text();
00127         std::wstring_view view(resourceAddress);
00128
00129         // Remove previous query string.
00130         auto questionMarkPos = view.find(L'?');
00131         if (questionMarkPos != std::wstring_view::npos)
00132         {
00133             view = view.substr(0, questionMarkPos);
00134         }
00135
00136         addressField.Text(view + newQueryString);
00137     }
00138
00139     Uri TryParseHttpUri(hstring const& uriString)
00140     {
00141         // Note that this app has both "Internet (Client)" and "Home and Work Networking" capabilities set,
00142         // since the user may provide URIs for servers located on the internet or intranet. If apps only
00143         // communicate with servers on the internet, only the "Internet (Client)" capability should be set.
00144         // Similarly if an app is only intended to communicate on the intranet, only the "Home and Work
00145         // Networking" capability should be set.
00146         try
00147         {
00148             Uri uri(uriString);
00149             hstring scheme = uri.SchemeName();
00150             if (scheme == L"http" || scheme == L"https")
00151             {
00152                 return uri;
00153             }
00154         }
00155         catch (hresult_error const& ex)
00156         {
00157             if (ex.code() != E_POINTER && ex.code() != E_INVALIDARG)
00158             {
00159                 throw;
00160             }
00161         }
00162         return nullptr;
00163     }
00164 }
Generated on Fri Nov 15 2024 22:19:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BarcodeScannerInfo Member List

This is the complete list of members for BarcodeScannerInfo, including all inherited members.
BarcodeScannerInfo(String deviceName, String deviceId) | BarcodeScannerInfo | [inline]
DeviceId | BarcodeScannerInfo |
DeviceName | BarcodeScannerInfo | [private]
Name | BarcodeScannerInfo |
Generated on Fri Nov 15 2024 22:23:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppServices/cppwinrt/AppServicesClient/OpenCloseConnectionScenario.h Source File

  • AppServices
  • cppwinrt
  • AppServicesClient

OpenCloseConnectionScenario.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "OpenCloseConnectionScenario.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct OpenCloseConnectionScenario : OpenCloseConnectionScenarioT<OpenCloseConnectionScenario>
00019     {
00020         OpenCloseConnectionScenario();
00021
00022         fire_and_forget GenerateRandomNumber_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023
00024     private:
00025         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00026     };
00027 }
00028
00029 namespace winrt::SDKTemplate::factory_implementation
00030 {
00031     struct OpenCloseConnectionScenario : OpenCloseConnectionScenarioT<OpenCloseConnectionScenario, implementation::OpenCloseConnectionScenario>
00032     {
00033     };
00034 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed::sealed Member List

This is the complete list of members for sealed::sealed, including all inherited members.
Add(INT64 sizeValue) | sealed::sealed |
GetSize() | sealed::sealed |
size | sealed::sealed | [private]
SizeCounter() | sealed::sealed |
Generated on Fri Nov 15 2024 22:24:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PlayReadyHelper Member List

This is the complete list of members for PlayReadyHelper, including all inherited members.
LicenseAcquisitionRequest(PlayReadyLicenseAcquisitionServiceRequest licenseRequest, MediaProtectionServiceCompletion completionNotifier, string url, string challengeCustomData) | PlayReadyHelper | [inline, private]
Log(string message) | PlayReadyHelper | [inline, private]
logger | PlayReadyHelper | [private]
MediaProtectionContainerGuid | PlayReadyHelper | [private]
MediaProtectionSystemId | PlayReadyHelper | [private]
MediaProtectionSystemIdMapping | PlayReadyHelper | [private]
MSPR_E_CONTENT_ENABLING_ACTION_REQUIRED | PlayReadyHelper | [private]
playReadyChallengeCustomData | PlayReadyHelper |
PlayReadyHelper(LogView logger=null) | PlayReadyHelper | [inline]
playReadyLicenseUrl | PlayReadyHelper |
PlayReadyWinRTTrustedInput | PlayReadyHelper | [private]
ProactiveIndividualizationRequest() | PlayReadyHelper | [inline, private]
ProtectionManager_ComponentLoadFailed(MediaProtectionManager sender, ComponentLoadFailedEventArgs e) | PlayReadyHelper | [inline, private]
ProtectionManager_ServiceRequested(MediaProtectionManager sender, ServiceRequestedEventArgs e) | PlayReadyHelper | [inline, private]
ReactiveIndividualizationRequestAsync(PlayReadyIndividualizationServiceRequest individualizationRequest, MediaProtectionServiceCompletion completionNotifier) | PlayReadyHelper | [inline, private]
SetUpProtectionManager(MediaPlayer mediaPlayer) | PlayReadyHelper | [inline]
Generated on Fri Nov 15 2024 22:24:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2 Member List

This is the complete list of members for Scenario2, including all inherited members.
m_scenario2ViewModel | Scenario2 | [private]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario2 | [inline, protected]
Scenario2() | Scenario2 | [inline]
Generated on Fri Nov 15 2024 22:23:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppServices/cppwinrt/AppServicesProvider/SampleConfiguration.cpp Source File

  • AppServices
  • cppwinrt
  • AppServicesProvider

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation::Collections;
00019 using namespace winrt::SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"App service provider C++/WinRT sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Show Package Family Name", xaml_typename<SDKTemplate::ShowPackageFamilyName>() },
00029 });
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/DeviceResources.cpp Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DeviceResources.h"
00014 #include "DirectXHelper.h"
00015
00016 using namespace D2D1;
00017 using namespace DirectX;
00018 using namespace Microsoft::WRL;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Graphics::Display;
00021 using namespace Windows::UI::Core;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Platform;
00024
00025 // Constants used to calculate screen rotations
00026 namespace ScreenRotation
00027 {
00028     // 0-degree Z-rotation
00029     static const XMFLOAT4X4 Rotation0(
00030         1.0f, 0.0f, 0.0f, 0.0f,
00031         0.0f, 1.0f, 0.0f, 0.0f,
00032         0.0f, 0.0f, 1.0f, 0.0f,
00033         0.0f, 0.0f, 0.0f, 1.0f
00034         );
00035
00036     // 90-degree Z-rotation
00037     static const XMFLOAT4X4 Rotation90(
00038         0.0f, 1.0f, 0.0f, 0.0f,
00039         -1.0f, 0.0f, 0.0f, 0.0f,
00040         0.0f, 0.0f, 1.0f, 0.0f,
00041         0.0f, 0.0f, 0.0f, 1.0f
00042         );
00043
00044     // 180-degree Z-rotation
00045     static const XMFLOAT4X4 Rotation180(
00046         -1.0f, 0.0f, 0.0f, 0.0f,
00047         0.0f, -1.0f, 0.0f, 0.0f,
00048         0.0f, 0.0f, 1.0f, 0.0f,
00049         0.0f, 0.0f, 0.0f, 1.0f
00050         );
00051
00052     // 270-degree Z-rotation
00053     static const XMFLOAT4X4 Rotation270(
00054         0.0f, -1.0f, 0.0f, 0.0f,
00055         1.0f, 0.0f, 0.0f, 0.0f,
00056         0.0f, 0.0f, 1.0f, 0.0f,
00057         0.0f, 0.0f, 0.0f, 1.0f
00058         );
00059 };
00060
00061 // Constructor for DeviceResources.
00062 DX::DeviceResources::DeviceResources() :
00063     m_screenViewport(),
00064     m_d3dFeatureLevel(D3D_FEATURE_LEVEL_9_1),
00065     m_d3dRenderTargetSize(),
00066     m_outputSize(),
00067     m_logicalSize(),
00068     m_nativeOrientation(DisplayOrientations::None),
00069     m_currentOrientation(DisplayOrientations::None),
00070     m_dpi(-1.0f),
00071     m_deviceNotify(nullptr)
00072 {
00073     CreateDeviceIndependentResources();
00074     CreateDeviceResources();
00075 }
00076
00077 // Configures resources that don't depend on the Direct3D device.
00078 void DX::DeviceResources::CreateDeviceIndependentResources()
00079 {
00080     // Initialize Direct2D resources.
00081     D2D1_FACTORY_OPTIONS options;
00082     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00083
00084 #if defined(_DEBUG)
00085     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00086     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00087 #endif
00088
00089     // Initialize the Direct2D Factory.
00090     DX::ThrowIfFailed(
00091         D2D1CreateFactory(
00092             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00093             __uuidof(ID2D1Factory2),
00094             &options,
00095             &m_d2dFactory
00096             )
00097         );
00098
00099     // Initialize the DirectWrite Factory.
00100     DX::ThrowIfFailed(
00101         DWriteCreateFactory(
00102             DWRITE_FACTORY_TYPE_SHARED,
00103             __uuidof(IDWriteFactory2),
00104             &m_dwriteFactory
00105             )
00106         );
00107
00108     // Initialize the Windows Imaging Component (WIC) Factory.
00109     DX::ThrowIfFailed(
00110         CoCreateInstance(
00111             CLSID_WICImagingFactory2,
00112             nullptr,
00113             CLSCTX_INPROC_SERVER,
00114             IID_PPV_ARGS(&m_wicFactory)
00115             )
00116         );
00117 }
00118
00119 // Configures the Direct3D device, and stores handles to it and the device context.
00120 void DX::DeviceResources::CreateDeviceResources()
00121 {
00122     // This flag adds support for surfaces with a different color channel ordering
00123     // than the API default. It is required for compatibility with Direct2D.
00124     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00125
00126 #if defined(_DEBUG)
00127     if (DX::SdkLayersAvailable())
00128     {
00129         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00130         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00131     }
00132 #endif
00133
00134     // This array defines the set of DirectX hardware feature levels this app will support.
00135     // Note the ordering should be preserved.
00136     // Don't forget to declare your application's minimum required feature level in its
00137     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00138     D3D_FEATURE_LEVEL featureLevels[] =
00139     {
00140         D3D_FEATURE_LEVEL_11_1,
00141         D3D_FEATURE_LEVEL_11_0,
00142         D3D_FEATURE_LEVEL_10_1,
00143         D3D_FEATURE_LEVEL_10_0,
00144         D3D_FEATURE_LEVEL_9_3,
00145         D3D_FEATURE_LEVEL_9_2,
00146         D3D_FEATURE_LEVEL_9_1
00147     };
00148
00149     // Create the Direct3D 11 API device object and a corresponding context.
00150     ComPtr<ID3D11Device> device;
00151     ComPtr<ID3D11DeviceContext> context;
00152
00153     HRESULT hr = D3D11CreateDevice(
00154         nullptr,                    // Specify nullptr to use the default adapter.
00155         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00156         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00157         creationFlags,              // Set debug and Direct2D compatibility flags.
00158         featureLevels,              // List of feature levels this app can support.
00159         ARRAYSIZE(featureLevels),   // Size of the list above.
00160         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00161         &device,                    // Returns the Direct3D device created.
00162         &m_d3dFeatureLevel,         // Returns feature level of device created.
00163         &context                    // Returns the device immediate context.
00164         );
00165
00166     if (FAILED(hr))
00167     {
00168         // If the initialization fails, fall back to the WARP device.
00169         // For more information on WARP, see:
00170         // http://go.microsoft.com/fwlink/?LinkId=286690
00171         DX::ThrowIfFailed(
00172             D3D11CreateDevice(
00173                 nullptr,
00174                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00175                 0,
00176                 creationFlags,
00177                 featureLevels,
00178                 ARRAYSIZE(featureLevels),
00179                 D3D11_SDK_VERSION,
00180                 &device,
00181                 &m_d3dFeatureLevel,
00182                 &context
00183                 )
00184             );
00185     }
00186
00187     // Store pointers to the Direct3D 11.1 API device and immediate context.
00188     DX::ThrowIfFailed(
00189         device.As(&m_d3dDevice)
00190         );
00191
00192     DX::ThrowIfFailed(
00193         context.As(&m_d3dContext)
00194         );
00195
00196     // Create the Direct2D device object and a corresponding context.
00197     ComPtr<IDXGIDevice3> dxgiDevice;
00198     DX::ThrowIfFailed(
00199         m_d3dDevice.As(&dxgiDevice)
00200         );
00201
00202     DX::ThrowIfFailed(
00203         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00204         );
00205
00206     DX::ThrowIfFailed(
00207         m_d2dDevice->CreateDeviceContext(
00208             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00209             &m_d2dContext
00210             )
00211         );
00212 }
00213
00214 // These resources need to be recreated every time the window size is changed.
00215 void DX::DeviceResources::CreateWindowSizeDependentResources()
00216 {
00217     // Clear the previous window size specific context.
00218     ID3D11RenderTargetView* nullViews[] = {nullptr};
00219     m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00220     m_d3dRenderTargetView = nullptr;
00221     m_d2dContext->SetTarget(nullptr);
00222     m_d2dTargetBitmap = nullptr;
00223     m_d3dDepthStencilView = nullptr;
00224     m_d3dContext->Flush();
00225
00226     // Calculate the necessary render target size in pixels.
00227     m_outputSize.Width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_dpi);
00228     m_outputSize.Height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_dpi);
00229
00230     // Prevent zero size DirectX content from being created.
00231     m_outputSize.Width = max(m_outputSize.Width, 1);
00232     m_outputSize.Height = max(m_outputSize.Height, 1);
00233
00234     // The width and height of the swap chain must be based on the window's
00235     // natively-oriented width and height. If the window is not in the native
00236     // orientation, the dimensions must be reversed.
00237     DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation();
00238
00239     bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270;
00240     m_d3dRenderTargetSize.Width = swapDimensions ? m_outputSize.Height : m_outputSize.Width;
00241     m_d3dRenderTargetSize.Height = swapDimensions ? m_outputSize.Width : m_outputSize.Height;
00242
00243     if (m_swapChain != nullptr)
00244     {
00245         // If the swap chain already exists, resize it.
00246         HRESULT hr = m_swapChain->ResizeBuffers(
00247             2, // Double-buffered swap chain.
00248             lround(m_d3dRenderTargetSize.Width),
00249             lround(m_d3dRenderTargetSize.Height),
00250             DXGI_FORMAT_B8G8R8A8_UNORM,
00251             0
00252             );
00253
00254         if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00255         {
00256             // If the device was removed for any reason, a new device and swap chain will need to be created.
00257             HandleDeviceLost();
00258
00259             // Everything is set up now. Do not continue execution of this method. HandleDeviceLost will reenter this method
00260             // and correctly set up the new device.
00261             return;
00262         }
00263         else
00264         {
00265             DX::ThrowIfFailed(hr);
00266         }
00267     }
00268     else
00269     {
00270         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00271         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00272
00273         swapChainDesc.Width = lround(m_d3dRenderTargetSize.Width); // Match the size of the window.
00274         swapChainDesc.Height = lround(m_d3dRenderTargetSize.Height);
00275         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swap chain format.
00276         swapChainDesc.Stereo = false;
00277         swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling.
00278         swapChainDesc.SampleDesc.Quality = 0;
00279         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00280         swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency.
00281         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Runtime apps must use this SwapEffect.
00282         swapChainDesc.Flags = 0;
00283         swapChainDesc.Scaling = DXGI_SCALING_NONE;
00284         swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
00285
00286         // This sequence obtains the DXGI factory that was used to create the Direct3D device above.
00287         ComPtr<IDXGIDevice3> dxgiDevice;
00288         DX::ThrowIfFailed(
00289             m_d3dDevice.As(&dxgiDevice)
00290             );
00291
00292         ComPtr<IDXGIAdapter> dxgiAdapter;
00293         DX::ThrowIfFailed(
00294             dxgiDevice->GetAdapter(&dxgiAdapter)
00295             );
00296
00297         ComPtr<IDXGIFactory2> dxgiFactory;
00298         DX::ThrowIfFailed(
00299             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00300             );
00301
00302         DX::ThrowIfFailed(
00303             dxgiFactory->CreateSwapChainForCoreWindow(
00304                 m_d3dDevice.Get(),
00305                 reinterpret_cast<IUnknown*>(m_window.Get()),
00306                 &swapChainDesc,
00307                 nullptr,
00308                 &m_swapChain
00309                 )
00310             );
00311
00312         // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and
00313         // ensures that the application will only render after each VSync, minimizing power consumption.
00314         DX::ThrowIfFailed(
00315             dxgiDevice->SetMaximumFrameLatency(1)
00316             );
00317     }
00318
00319     // Set the proper orientation for the swap chain, and generate 2D and
00320     // 3D matrix transformations for rendering to the rotated swap chain.
00321     // Note the rotation angle for the 2D and 3D transforms are different.
00322     // This is due to the difference in coordinate spaces.  Additionally,
00323     // the 3D matrix is specified explicitly to avoid rounding errors.
00324
00325     switch (displayRotation)
00326     {
00327     case DXGI_MODE_ROTATION_IDENTITY:
00328         m_orientationTransform2D = Matrix3x2F::Identity();
00329         m_orientationTransform3D = ScreenRotation::Rotation0;
00330         break;
00331
00332     case DXGI_MODE_ROTATION_ROTATE90:
00333         m_orientationTransform2D =
00334             Matrix3x2F::Rotation(90.0f) *
00335             Matrix3x2F::Translation(m_logicalSize.Height, 0.0f);
00336         m_orientationTransform3D = ScreenRotation::Rotation270;
00337         break;
00338
00339     case DXGI_MODE_ROTATION_ROTATE180:
00340         m_orientationTransform2D =
00341             Matrix3x2F::Rotation(180.0f) *
00342             Matrix3x2F::Translation(m_logicalSize.Width, m_logicalSize.Height);
00343         m_orientationTransform3D = ScreenRotation::Rotation180;
00344         break;
00345
00346     case DXGI_MODE_ROTATION_ROTATE270:
00347         m_orientationTransform2D =
00348             Matrix3x2F::Rotation(270.0f) *
00349             Matrix3x2F::Translation(0.0f, m_logicalSize.Width);
00350         m_orientationTransform3D = ScreenRotation::Rotation90;
00351         break;
00352
00353     default:
00354         throw ref new FailureException();
00355     }
00356
00357     DX::ThrowIfFailed(
00358         m_swapChain->SetRotation(displayRotation)
00359         );
00360
00361     // Create a render target view of the swap chain back buffer.
00362     ComPtr<ID3D11Texture2D> backBuffer;
00363     DX::ThrowIfFailed(
00364         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00365         );
00366
00367     DX::ThrowIfFailed(
00368         m_d3dDevice->CreateRenderTargetView(
00369             backBuffer.Get(),
00370             nullptr,
00371             &m_d3dRenderTargetView
00372             )
00373         );
00374
00375     // Create a depth stencil view for use with 3D rendering if needed.
00376     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00377         DXGI_FORMAT_D24_UNORM_S8_UINT,
00378         lround(m_d3dRenderTargetSize.Width),
00379         lround(m_d3dRenderTargetSize.Height),
00380         1, // This depth stencil view has only one texture.
00381         1, // Use a single mipmap level.
00382         D3D11_BIND_DEPTH_STENCIL
00383         );
00384
00385     ComPtr<ID3D11Texture2D> depthStencil;
00386     DX::ThrowIfFailed(
00387         m_d3dDevice->CreateTexture2D(
00388             &depthStencilDesc,
00389             nullptr,
00390             &depthStencil
00391             )
00392         );
00393
00394     CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
00395     DX::ThrowIfFailed(
00396         m_d3dDevice->CreateDepthStencilView(
00397             depthStencil.Get(),
00398             &depthStencilViewDesc,
00399             &m_d3dDepthStencilView
00400             )
00401         );
00402
00403     // Set the 3D rendering viewport to target the entire window.
00404     m_screenViewport = CD3D11_VIEWPORT(
00405         0.0f,
00406         0.0f,
00407         m_d3dRenderTargetSize.Width,
00408         m_d3dRenderTargetSize.Height
00409         );
00410
00411     m_d3dContext->RSSetViewports(1, &m_screenViewport);
00412
00413     // Create a Direct2D target bitmap associated with the
00414     // swap chain back buffer and set it as the current target.
00415     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00416         D2D1::BitmapProperties1(
00417             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00418             D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00419             m_dpi,
00420             m_dpi
00421             );
00422
00423     ComPtr<IDXGISurface2> dxgiBackBuffer;
00424     DX::ThrowIfFailed(
00425         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00426         );
00427
00428     DX::ThrowIfFailed(
00429         m_d2dContext->CreateBitmapFromDxgiSurface(
00430             dxgiBackBuffer.Get(),
00431             &bitmapProperties,
00432             &m_d2dTargetBitmap
00433             )
00434         );
00435
00436     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00437
00438     // Grayscale text anti-aliasing is recommended for all Windows Runtime apps.
00439     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00440 }
00441
00442 // This method is called when the CoreWindow is created (or re-created).
00443 void DX::DeviceResources::SetWindow(CoreWindow^ window)
00444 {
00445     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00446
00447     m_window = window;
00448     m_logicalSize = Windows::Foundation::Size(window->Bounds.Width, window->Bounds.Height);
00449     m_nativeOrientation = currentDisplayInformation->NativeOrientation;
00450     m_currentOrientation = currentDisplayInformation->CurrentOrientation;
00451     m_dpi = currentDisplayInformation->LogicalDpi;
00452     m_d2dContext->SetDpi(m_dpi, m_dpi);
00453
00454     CreateWindowSizeDependentResources();
00455 }
00456
00457 // This method is called in the event handler for the SizeChanged event.
00458 void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize)
00459 {
00460     if (m_logicalSize != logicalSize)
00461     {
00462         m_logicalSize = logicalSize;
00463         CreateWindowSizeDependentResources();
00464     }
00465 }
00466
00467 // This method is called in the event handler for the DpiChanged event.
00468 void DX::DeviceResources::SetDpi(float dpi)
00469 {
00470     if (dpi != m_dpi)
00471     {
00472         m_dpi = dpi;
00473
00474         // When the display DPI changes, the logical size of the window (measured in Dips) also changes and needs to be updated.
00475         m_logicalSize = Windows::Foundation::Size(m_window->Bounds.Width, m_window->Bounds.Height);
00476
00477         m_d2dContext->SetDpi(m_dpi, m_dpi);
00478         CreateWindowSizeDependentResources();
00479     }
00480 }
00481
00482 // This method is called in the event handler for the OrientationChanged event.
00483 void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation)
00484 {
00485     if (m_currentOrientation != currentOrientation)
00486     {
00487         m_currentOrientation = currentOrientation;
00488         CreateWindowSizeDependentResources();
00489     }
00490 }
00491
00492 // This method is called in the event handler for the DisplayContentsInvalidated event.
00493 void DX::DeviceResources::ValidateDevice()
00494 {
00495     // The D3D Device is no longer valid if the default adapter changed since the device
00496     // was created or if the device has been removed.
00497
00498     // First, get the information for the default adapter from when the device was created.
00499
00500     ComPtr<IDXGIDevice3> dxgiDevice;
00501     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00502
00503     ComPtr<IDXGIAdapter> deviceAdapter;
00504     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00505
00506     ComPtr<IDXGIFactory2> deviceFactory;
00507     DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory)));
00508
00509     ComPtr<IDXGIAdapter1> previousDefaultAdapter;
00510     DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter));
00511
00512     DXGI_ADAPTER_DESC previousDesc;
00513     DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc));
00514
00515     // Next, get the information for the current default adapter.
00516
00517     ComPtr<IDXGIFactory2> currentFactory;
00518     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&currentFactory)));
00519
00520     ComPtr<IDXGIAdapter1> currentDefaultAdapter;
00521     DX::ThrowIfFailed(currentFactory->EnumAdapters1(0, &currentDefaultAdapter));
00522
00523     DXGI_ADAPTER_DESC currentDesc;
00524     DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(&currentDesc));
00525
00526     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00527     // a new D3D device must be created.
00528
00529     if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart ||
00530         previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart ||
00531         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00532     {
00533         // Release references to resources related to the old device.
00534         dxgiDevice = nullptr;
00535         deviceAdapter = nullptr;
00536         deviceFactory = nullptr;
00537         previousDefaultAdapter = nullptr;
00538
00539         // Create a new device and swap chain.
00540         HandleDeviceLost();
00541     }
00542 }
00543
00544 // Recreate all device resources and set them back to the current state.
00545 void DX::DeviceResources::HandleDeviceLost()
00546 {
00547     m_swapChain = nullptr;
00548
00549     if (m_deviceNotify != nullptr)
00550     {
00551         m_deviceNotify->OnDeviceLost();
00552     }
00553
00554     CreateDeviceResources();
00555     m_d2dContext->SetDpi(m_dpi, m_dpi);
00556     CreateWindowSizeDependentResources();
00557
00558     if (m_deviceNotify != nullptr)
00559     {
00560         m_deviceNotify->OnDeviceRestored();
00561     }
00562 }
00563
00564 // Register our DeviceNotify to be informed on device lost and creation.
00565 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00566 {
00567     m_deviceNotify = deviceNotify;
00568 }
00569
00570 // Call this method when the app suspends. It provides a hint to the driver that the app
00571 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00572 void DX::DeviceResources::Trim()
00573 {
00574     ComPtr<IDXGIDevice3> dxgiDevice;
00575     m_d3dDevice.As(&dxgiDevice);
00576
00577     dxgiDevice->Trim();
00578 }
00579
00580 // Present the contents of the swap chain to the screen.
00581 void DX::DeviceResources::Present()
00582 {
00583     // The first argument instructs DXGI to block until VSync, putting the application
00584     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00585     // frames that will never be displayed to the screen.
00586     HRESULT hr = m_swapChain->Present(1, 0);
00587
00588     // Discard the contents of the render target.
00589     // This is a valid operation only when the existing contents will be entirely
00590     // overwritten. If dirty or scroll rects are used, this call should be removed.
00591     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00592
00593     // Discard the contents of the depth stencil.
00594     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00595
00596     // If the device was removed either by a disconnection or a driver upgrade, we
00597     // must recreate all device resources.
00598     if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00599     {
00600         HandleDeviceLost();
00601     }
00602     else
00603     {
00604         DX::ThrowIfFailed(hr);
00605     }
00606 }
00607
00608 // This method determines the rotation between the display device's native Orientation and the
00609 // current display orientation.
00610 DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation()
00611 {
00612     DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
00613
00614     // Note: NativeOrientation can only be Landscape or Portrait even though
00615     // the DisplayOrientations enum has other values.
00616     switch (m_nativeOrientation)
00617     {
00618     case DisplayOrientations::Landscape:
00619         switch (m_currentOrientation)
00620         {
00621         case DisplayOrientations::Landscape:
00622             rotation = DXGI_MODE_ROTATION_IDENTITY;
00623             break;
00624
00625         case DisplayOrientations::Portrait:
00626             rotation = DXGI_MODE_ROTATION_ROTATE270;
00627             break;
00628
00629         case DisplayOrientations::LandscapeFlipped:
00630             rotation = DXGI_MODE_ROTATION_ROTATE180;
00631             break;
00632
00633         case DisplayOrientations::PortraitFlipped:
00634             rotation = DXGI_MODE_ROTATION_ROTATE90;
00635             break;
00636         }
00637         break;
00638
00639     case DisplayOrientations::Portrait:
00640         switch (m_currentOrientation)
00641         {
00642         case DisplayOrientations::Landscape:
00643             rotation = DXGI_MODE_ROTATION_ROTATE90;
00644             break;
00645
00646         case DisplayOrientations::Portrait:
00647             rotation = DXGI_MODE_ROTATION_IDENTITY;
00648             break;
00649
00650         case DisplayOrientations::LandscapeFlipped:
00651             rotation = DXGI_MODE_ROTATION_ROTATE270;
00652             break;
00653
00654         case DisplayOrientations::PortraitFlipped:
00655             rotation = DXGI_MODE_ROTATION_ROTATE180;
00656             break;
00657         }
00658         break;
00659     }
00660     return rotation;
00661 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cs/cpp/Scenario2_OvenClientWRL.xaml.cpp Source File

  • ProxyStubsForWinRTComponents
  • cs
  • cpp

Scenario2_OvenClientWRL.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include "pch.h"
00008 #include "Scenario2_OvenClientWRL.xaml.h"
00009 #include "MainPage.xaml.h"
00010 #include "..\Server\Microsoft.SDKSamples.Kitchen.h"
00011
00012 using namespace SDKSample;
00013 using namespace SDKSample::ProxyStubsForWinRTComponents;
00014
00015 using namespace Microsoft::SDKSamples::Kitchen;
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019
00020 OvenClientWRL::OvenClientWRL()
00021 {
00022     InitializeComponent();
00023 }
00024
00025 void SDKSample::ProxyStubsForWinRTComponents::OvenClientWRL::Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00026 {
00027     Microsoft::WRL::ComPtr<ABI::Microsoft::SDKSamples::Kitchen::IOven> spMyOven;
00028     Microsoft::WRL::ComPtr<ABI::Microsoft::SDKSamples::Kitchen::IOvenFactory> spMyOvenFactory;
00029
00030     // Component Creation: Get the activation factory
00031     HRESULT hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Microsoft_SDKSamples_Kitchen_Oven).Get(), &spMyOvenFactory);
00032     if (SUCCEEDED(hr))
00033     {
00034         ABI::Microsoft::SDKSamples::Kitchen::Dimensions dimensions;
00035         dimensions.Width = 2;
00036         dimensions.Height = 2;
00037         dimensions.Depth = 2;
00038
00039         // Component Creation: Call the factory method to produce an oven object
00040         hr = spMyOvenFactory->CreateOven(dimensions, &spMyOven);
00041     }
00042     if (SUCCEEDED(hr))
00043     {
00044         Microsoft::WRL::ComPtr<ABI::Microsoft::SDKSamples::Kitchen::IAppliance> spMyAppliance;
00045         hr = spMyOven.As(&spMyAppliance);
00046         if (SUCCEEDED(hr))
00047         {
00048             // Getters and setters are accessed using the get_ or put_ methods
00049             double volume;
00050             hr = spMyAppliance->get_Volume(&volume);
00051             if (SUCCEEDED(hr))
00052             {
00053                 // To append to the output text a C++\CX call is made. This call can throw an exception.
00054                 // Catch any Windows Rutnime exceptions and turn them back into HRESULTS
00055                 try
00056                 {
00057                     OvenClientWRLOutput->Text += "Oven volume is: " + volume.ToString() + "\n";
00058                 }
00059                 catch (Platform::COMException^ e)
00060                 {
00061                     hr = e->HResult;
00062                 }
00063             }
00064         }
00065
00066         // Declare handlers for event callbacks
00067         auto spHandler1 = Microsoft::WRL::Callback<ABI::Windows::Foundation::ITypedEventHandler<
00068             ABI::Microsoft::SDKSamples::Kitchen::Oven*,
00069             ABI::Microsoft::SDKSamples::Kitchen::Bread*>>(
00070             [this](ABI::Microsoft::SDKSamples::Kitchen::IOven *pOven, ABI::Microsoft::SDKSamples::Kitchen::IBread *pBread)->HRESULT
00071         {
00072             HRESULT hr = S_OK;
00073             Microsoft::WRL::ComPtr<ABI::Microsoft::SDKSamples::Kitchen::IOven> spOven(pOven);
00074             Microsoft::WRL::ComPtr<ABI::Microsoft::SDKSamples::Kitchen::IBread> spBread(pBread);
00075             Microsoft::WRL::ComPtr<ABI::Microsoft::SDKSamples::Kitchen::IAppliance> spAppliance;
00076
00077             try
00078             {
00079                 // To append to the output text a C++\CX call is made. Catch any Windows Rutnime exceptions and turn them into HRESULTS.
00080                 OvenClientWRLOutput->Text += "Event Handler 1: Invoked\n";
00081             }
00082             catch (Platform::COMException^ e)
00083             {
00084                 hr = e->HResult;
00085             }
00086
00087             if (SUCCEEDED(hr))
00088             {
00089                 hr = spOven.As(&spAppliance);
00090             }
00091             if (SUCCEEDED(hr))
00092             {
00093                 double volume;
00094                 hr = spAppliance->get_Volume(&volume);
00095                 if (SUCCEEDED(hr))
00096                 {
00097                     try
00098                     {
00099                         // To append to the output text a C++\CX call is made. Catch any Windows Rutnime exceptions and turn them into HRESULTS.
00100                         OvenClientWRLOutput->Text += "Event Handler 1: Oven volume is: " + volume.ToString() + "\n";
00101                     }
00102                     catch (Platform::COMException^ e)
00103                     {
00104                         hr = e->HResult;
00105                     }
00106                 }
00107             }
00108             HSTRING hstrBreadFlavor;
00109             hr = spBread->get_Flavor(&hstrBreadFlavor);
00110             if (SUCCEEDED(hr))
00111             {
00112                 try
00113                 {
00114                     // To append to the output text a C++\CX call is made. Catch any Windows Rutnime exceptions and turn them into HRESULTS.
00115                     OvenClientWRLOutput->Text += "Event Handler 1: Bread flavor is: " + ref new Platform::String(hstrBreadFlavor) + "\n";
00116                 }
00117                 catch (Platform::COMException^ e)
00118                 {
00119                     hr = e->HResult;
00120                 }
00121             }
00122             return hr;
00123         });
00124
00125         auto spHandler2 = Microsoft::WRL::Callback<ABI::Windows::Foundation::ITypedEventHandler<
00126             ABI::Microsoft::SDKSamples::Kitchen::Oven*,
00127             ABI::Microsoft::SDKSamples::Kitchen::Bread*>>(
00128             [this](ABI::Microsoft::SDKSamples::Kitchen::IOven *pCurOven, ABI::Microsoft::SDKSamples::Kitchen::IBread *pCurBread)->HRESULT
00129         {
00130             HRESULT hr = S_OK;
00131             try
00132             {
00133                 // To append to the output text a C++\CX call is made. Catch any Windows Rutnime exceptions and turn them into HRESULTS.
00134                 OvenClientWRLOutput->Text += "Event Handler 2: Invoked\n";
00135             }
00136             catch (Platform::COMException^ e)
00137             {
00138                 hr = e->HResult;
00139             }
00140             return hr;
00141         });
00142
00143         auto spHandler3 = Microsoft::WRL::Callback<ABI::Windows::Foundation::ITypedEventHandler<
00144             ABI::Microsoft::SDKSamples::Kitchen::Oven*,
00145             ABI::Microsoft::SDKSamples::Kitchen::Bread*>>(
00146             [this](ABI::Microsoft::SDKSamples::Kitchen::IOven *pCurOven, ABI::Microsoft::SDKSamples::Kitchen::IBread *pCurBread)->HRESULT
00147         {
00148             // Event handler 3 was removed and will not be invoked
00149             HRESULT hr = S_OK;
00150             try
00151             {
00152                 // To append to the output text a C++\CX call is made. Catch any Windows Rutnime exceptions and turn them into HRESULTS.
00153                 OvenClientWRLOutput->Text += "Event Handler 3: Invoked\n";
00154             }
00155             catch (Platform::COMException^ e)
00156             {
00157                 hr = e->HResult;
00158             }
00159             return hr;
00160         });
00161
00162         // Registering event listeners
00163         ::EventRegistrationToken regBread1;
00164         ::EventRegistrationToken regBread2;
00165         ::EventRegistrationToken regBread3;
00166         if (SUCCEEDED(hr))
00167         {
00168             hr = spMyOven->add_BreadBaked(spHandler1.Get(), &regBread1);
00169         }
00170         if (SUCCEEDED(hr))
00171         {
00172             hr = spMyOven->add_BreadBaked(spHandler2.Get(), &regBread2);
00173         }
00174         if (SUCCEEDED(hr))
00175         {
00176             hr = spMyOven->add_BreadBaked(spHandler3.Get(), &regBread3);
00177         }
00178
00179         // Unregister from an event using the registration token
00180         if (SUCCEEDED(hr))
00181         {
00182             hr = spMyOven->remove_BreadBaked(regBread3);
00183         }
00184
00185         // Bake a loaf of bread. This will trigger the BreadBaked event.
00186         if (SUCCEEDED(hr))
00187         {
00188             hr = spMyOven->BakeBread(Microsoft::WRL::Wrappers::HStringReference(L"Sourdough").Get());
00189         }
00190
00191         // Trigger the event again with a different preheat time
00192         if (SUCCEEDED(hr))
00193         {
00194             hr = spMyOven->ConfigurePreheatTemperature(ABI::Microsoft::SDKSamples::Kitchen::OvenTemperature_High);
00195         }
00196         if (SUCCEEDED(hr))
00197         {
00198             hr = spMyOven->BakeBread(Microsoft::WRL::Wrappers::HStringReference(L"Wheat").Get());
00199         }
00200     }
00201 }
00202
Generated on Fri Nov 15 2024 22:21:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SaveStateEventArgs Member List

This is the complete list of members for SaveStateEventArgs, including all inherited members.
PageState | SaveStateEventArgs |
SaveStateEventArgs(Dictionary< string, Object > pageState) | SaveStateEventArgs | [inline]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSuggestion/cpp/Scenario3_ReverseConversion.xaml.cpp Source File

  • TextSuggestion
  • cpp

Scenario3_ReverseConversion.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario3_ReverseConversion.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Platform::Collections;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::UI::Xaml;
00013 using namespace Windows::UI::Xaml::Controls;
00014 using namespace Windows::UI::Xaml::Controls::Primitives;
00015 using namespace Windows::UI::Xaml::Data;
00016 using namespace Windows::UI::Xaml::Input;
00017 using namespace Windows::UI::Xaml::Media;
00018 using namespace Windows::UI::Xaml::Navigation;
00019
00020 Scenario3_ReverseConversion::Scenario3_ReverseConversion()
00021 {
00022     InitializeComponent();
00023 }
00024
00025 /// <summary>
00026 /// This is the click handler for the 'Create Generator' button.
00027 /// When this button is activated, this method will create a reverse conversion
00028 /// generator with the language tag provided by the user. The generator will
00029 /// try to resolve the language tag and check if the language is supported
00030 /// and installed.
00031 /// </summary>
00032 /// <param name="sender">The object that raised the event.</param>
00033 /// <param name="e">Event data that describes the click action on the button.</param>
00034 void Scenario3_ReverseConversion::CreateGeneratorButton_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00035 {
00036     String^ notifyText = ref new String();
00037
00038     // Try to parse the language and create generator accordingly.
00039     generator = ref new Windows::Data::Text::TextReverseConversionGenerator(langTag->Text);
00040
00041     // Only allow generator operation when the language is available and installed.
00042     if (generator == nullptr)
00043     {
00044         if (generatorOperationArea != nullptr)
00045         {
00046             generatorOperationArea->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00047         }
00048
00049         notifyText = "Successfully instantiated a generator.";
00050         MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00051     }
00052     else if (generator->ResolvedLanguage == "und")
00053     {
00054         if (generatorOperationArea != nullptr)
00055         {
00056             generatorOperationArea->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00057         }
00058
00059         notifyText = "Unsupported language.";
00060         MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00061     }
00062     else if (generator->LanguageAvailableButNotInstalled)
00063     {
00064         if (generatorOperationArea != nullptr)
00065         {
00066             generatorOperationArea->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00067         }
00068
00069         notifyText = "Language available but not installed.";
00070         MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00071     }
00072     else
00073     {
00074         if (generatorOperationArea != nullptr)
00075         {
00076             generatorOperationArea->Visibility = Windows::UI::Xaml::Visibility::Visible;
00077         }
00078
00079         notifyText = "Successfully instantiated a generator.";
00080         MainPage::Current->NotifyUser(notifyText, NotifyType::StatusMessage);
00081     }
00082 }
00083
00084 /// <summary>
00085 /// This is the click handler for the 'Execute' button.
00086 /// When this button is activated, the reverse conversion generator will get
00087 /// the reverse conversion result for given input string and language tag,
00088 /// then print it in result column.
00089 /// Using 'concurrency::create_task' to create an asynchronous task and
00090 /// handle the result when it completes.
00091 /// </summary>
00092 /// <param name="sender">The object that raised the event.</param>
00093 /// <param name="e">Event data that describes the click action on the button.</param>
00094 void Scenario3_ReverseConversion::Execute_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00095 {
00096     // Clean up result column.
00097     resultView->ItemsSource = nullptr;
00098
00099     // Clean notification area.
00100     String^ notifyText = ref new String();
00101     MainPage::Current->NotifyUser(notifyText, NotifyType::ErrorMessage);
00102
00103     auto input = Input->Text;
00104
00105     ComboBoxItem^ selectedItem = dynamic_cast<ComboBoxItem^>(methods->SelectedItem);
00106
00107     if ((generator != nullptr) && (selectedItem != nullptr) && !input->IsEmpty())
00108     {
00109         // Specify the candidate number to get.
00110         if ((selectedItem->Tag != nullptr) && selectedItem->Tag->ToString()->Equals("segmented"))
00111         {
00112             // Get the reverse conversion result per phoneme through calling the API and print it in result area.
00113             concurrency::create_task(generator->GetPhonemesAsync(input)).then([this](IVectorView <Windows::Data::Text::TextPhoneme^>^ phonemes)
00114             {
00115                 Vector<String^>^ itemsSource = ref new Vector<String^>();
00116                 for (const auto& phoneme : phonemes)
00117                 {
00118                     itemsSource->Append(phoneme->DisplayText + " -> " + phoneme->ReadingText);
00119                 }
00120                 resultView->ItemsSource = itemsSource;
00121
00122                 if (phonemes->Size == 0)
00123                 {
00124                     MainPage::Current->NotifyUser("No results.", NotifyType::StatusMessage);
00125                 }
00126             });
00127         }
00128         else
00129         {
00130             // Get the reverse conversion result through calling the API and print it in result area.
00131             concurrency::create_task(generator->ConvertBackAsync(input)).then([this](Platform::String^ result)
00132             {
00133                 Vector<String^>^ itemsSource = ref new Vector<String^>();
00134                 itemsSource->Append(result);
00135                 resultView->ItemsSource = itemsSource;
00136
00137                 if ((result == nullptr) || result->IsEmpty())
00138                 {
00139                     MainPage::Current->NotifyUser("No results.", NotifyType::StatusMessage);
00140                 }
00141             });
00142         }
00143     }
00144 }
Generated on Fri Nov 15 2024 22:21:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactCardIntegration/cs/Scenario2_ReceiveContact.xaml.cs Source File

  • ContactCardIntegration
  • cs

Scenario2_ReceiveContact.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using Windows.ApplicationModel.Activation;
00016
00017 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// Page to handle the protocol activation. In this case we simply show the URI and the
00023     /// parameters passed to it.
00024     /// </summary>
00025     public sealed partial class Scenario2_ReceiveContact : Page
00026     {
00027         public Scenario2_ReceiveContact()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         protected override void OnNavigatedTo(NavigationEventArgs e)
00033         {
00034             base.OnNavigatedTo(e);
00035
00036             var args = e.Parameter as ProtocolActivatedEventArgs;
00037             // Display the result of the protocol activation if we got here as a result of being activated for a protocol.
00038             if (args != null)
00039             {
00040                 // Parse the URI to extract the protocol and the contact ids
00041                 Uri uri = args.Uri;
00042
00043                 MainPage.Current.NotifyUser("Activated with protocol = " + uri.Scheme + ", parameters = " + uri.Query, NotifyType.StatusMessage);
00044             }
00045         }
00046     }
00047 }
Generated on Fri Nov 15 2024 22:18:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cs/AdventureWorks/View/TripDetails.xaml.cs Source File

  • CortanaVoiceCommand
  • cs
  • AdventureWorks
  • View

TripDetails.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using AdventureWorks.Common;
00013 using AdventureWorks.Model;
00014 using AdventureWorks.ViewModel;
00015 using System;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 // The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237
00021
00022 namespace AdventureWorks.View
00023 {
00024     /// <summary>
00025     /// Code Behind for a list of trips, including a Save and Delete button. Associated with the
00026     /// TripViewModel for most behaviors and properties.
00027     /// </summary>
00028     public sealed partial class TripDetails : Page
00029     {
00030         private NavigationHelper navigationHelper;
00031         private TripViewModel defaultViewModel;
00032
00033         /// <summary>
00034         /// The ViewModel that provides behaviors and properties associated with displaying a Trip's
00035         /// details.
00036         /// </summary>
00037         public TripViewModel DefaultViewModel
00038         {
00039             get { return this.defaultViewModel; }
00040         }
00041
00042         /// <summary>
00043         /// NavigationHelper is used on each page to aid in navigation and
00044         /// process lifetime management
00045         /// </summary>
00046         public NavigationHelper NavigationHelper
00047         {
00048             get { return this.navigationHelper; }
00049         }
00050
00051
00052         public TripDetails()
00053         {
00054             this.InitializeComponent();
00055             this.navigationHelper = new NavigationHelper(this);
00056             this.navigationHelper.LoadState += navigationHelper_LoadState;
00057             this.navigationHelper.SaveState += navigationHelper_SaveState;
00058         }
00059
00060         /// <summary>
00061         /// Populates the page with content passed during navigation. Any saved state is also
00062         /// provided when recreating a page from a prior session.
00063         /// Resets the state of the view model by passing in the parameters provided by the
00064         /// caller.
00065         /// </summary>
00066         /// <param name="sender">
00067         /// The source of the event; typically <see cref="Common.NavigationHelper"/>
00068         /// </param>
00069         /// <param name="e">Event data that provides both the navigation parameter passed to
00070         /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
00071         /// a dictionary of state preserved by this page during an earlier
00072         /// session. The state will be null the first time a page is visited.</param>
00073         private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
00074         {
00075             defaultViewModel = (TripViewModel)this.DataContext;
00076             if (e.NavigationParameter is Trip)
00077             {
00078                 // Activated via selecting a trip in the main page's list of trips.
00079                 DefaultViewModel.ShowTrip((Trip)e.NavigationParameter);
00080             }
00081             else if (e.NavigationParameter is TripVoiceCommand)
00082             {
00083                 // look up destination, set trip.
00084                 TripVoiceCommand voiceCommand = (TripVoiceCommand)e.NavigationParameter;
00085                 DefaultViewModel.LoadTripFromStore(voiceCommand.destination);
00086
00087                 // artificially populate the page backstack so we have something to
00088                 // go back to to get to the main page.
00089                 PageStackEntry backEntry = new PageStackEntry(typeof(View.TripListView), null, null);
00090                 this.Frame.BackStack.Add(backEntry);
00091             }
00092             else if(e.NavigationParameter is string)
00093             {
00094                 // We've been URI Activated, possibly by a user clicking on a tile in a Cortana session,
00095                 // we should see an argument like destination=<Location>.
00096                 // This should handle finding all of the destinations that match, but currently it only
00097                 // finds the first one.
00098                 string arguments = e.NavigationParameter as string;
00099                 if(arguments != null)
00100                 {
00101                     string[] args = arguments.Split('=');
00102                     if (args.Length == 2 && args[0].ToLowerInvariant() == "destination")
00103                     {
00104                         DefaultViewModel.LoadTripFromStore(args[1]);
00105
00106                         // artificially populate the page backstack so we have something to
00107                         // go back to to get to the main page.
00108                         PageStackEntry backEntry = new PageStackEntry(typeof(View.TripListView), null, null);
00109                         this.Frame.BackStack.Add(backEntry);
00110                     }
00111                 }
00112             }
00113             else
00114             {
00115                 DefaultViewModel.NewTrip();
00116             }
00117         }
00118
00119         /// <summary>
00120         /// Preserves state associated with this page in case the application is suspended or the
00121         /// page is discarded from the navigation cache.  Values must conform to the serialization
00122         /// requirements of <see cref="Common.SuspensionManager.SessionState"/>.
00123         /// </summary>
00124         /// <param name="sender">The source of the event; typically <see cref="Common.NavigationHelper"/></param>
00125         /// <param name="e">Event data that provides an empty dictionary to be populated with
00126         /// serializable state.</param>
00127         private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
00128         {
00129         }
00130
00131         #region NavigationHelper registration
00132
00133         /// The methods provided in this section are simply used to allow
00134         /// NavigationHelper to respond to the page's navigation methods.
00135         ///
00136         /// Page specific logic should be placed in event handlers for the
00137         /// <see cref="Common.NavigationHelper.LoadState"/>
00138         /// and <see cref="Common.NavigationHelper.SaveState"/>.
00139         /// The navigation parameter is available in the LoadState method
00140         /// in addition to page state preserved during an earlier session.
00141
00142         protected override void OnNavigatedTo(NavigationEventArgs e)
00143         {
00144             navigationHelper.OnNavigatedTo(e);
00145         }
00146
00147         protected override void OnNavigatedFrom(NavigationEventArgs e)
00148         {
00149             navigationHelper.OnNavigatedFrom(e);
00150         }
00151
00152         #endregion
00153
00154         /// <summary>
00155         /// Handle footer link clicks.
00156         /// </summary>
00157         /// <param name="sender">The target uri</param>
00158         /// <param name="e">Ignored</param>
00159         async void Footer_Click(object sender, RoutedEventArgs e)
00160         {
00161             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00162         }
00163     }
00164 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_DisplayText Member List

This is the complete list of members for Scenario2_DisplayText, including all inherited members.
DisplayTextButton_Click(object sender, RoutedEventArgs e) | Scenario2_DisplayText | [inline, private]
InitializeAsync() | Scenario2_DisplayText | [inline, private]
lineDisplay | Scenario2_DisplayText | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_DisplayText | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_DisplayText | [inline, protected]
rootPage | Scenario2_DisplayText | [private]
Scenario2_DisplayText() | Scenario2_DisplayText | [inline]
Generated on Fri Nov 15 2024 22:23:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cppwinrt/Scenario2_Binary.h Source File

  • WebSocket
  • cppwinrt

Scenario2_Binary.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Binary.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_Binary : Scenario2_BinaryT<Scenario2_Binary>
00019     {
00020         Scenario2_Binary();
00021
00022         winrt::fire_and_forget OnStart(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00023         void OnStop(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00025
00026     private:
00027         Windows::Foundation::IAsyncAction StartAsync();
00028         Windows::Foundation::IAsyncAction SendDataAsync(Windows::Networking::Sockets::StreamWebSocket activeSocket);
00029         Windows::Foundation::IAsyncAction ReceiveDataAsync(Windows::Networking::Sockets::StreamWebSocket activeSocket);
00030         winrt::fire_and_forget OnServerCustomValidationRequested(Windows::Networking::Sockets::StreamWebSocket const&, Windows::Networking::Sockets::WebSocketServerCustomValidationRequestedEventArgs e);
00031         winrt::fire_and_forget OnClosed(Windows::Networking::Sockets::IWebSocket sender, Windows::Networking::Sockets::WebSocketClosedEventArgs e);
00032         void CloseSocket();
00033         void AppendOutputLine(hstring const& value);
00034         void UpdateVisualState();
00035         void SetBusy(bool value);
00036
00037         SDKTemplate::MainPage m_rootPage{ MainPage::Current() };
00038         Windows::Networking::Sockets::StreamWebSocket m_streamWebSocket{ nullptr };
00039         bool m_busy{ false };
00040     };
00041 }
00042
00043 namespace winrt::SDKTemplate::factory_implementation
00044 {
00045     struct Scenario2_Binary : Scenario2_BinaryT<Scenario2_Binary, implementation::Scenario2_Binary>
00046     {
00047     };
00048 }
Generated on Fri Nov 15 2024 22:22:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cppwinrt/Scenario3_ParameterizedTemplate.h Source File

  • DateTimeFormatting
  • cppwinrt

Scenario3_ParameterizedTemplate.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_ParameterizedTemplate.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario3_ParameterizedTemplate : Scenario3_ParameterizedTemplateT<Scenario3_ParameterizedTemplate>
00019     {
00020         Scenario3_ParameterizedTemplate();
00021
00022         void Display_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario3_ParameterizedTemplate : Scenario3_ParameterizedTemplateT<Scenario3_ParameterizedTemplate, implementation::Scenario3_ParameterizedTemplate>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:19:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Compression/cpp/Scenario2.xaml.cpp Source File

  • Compression
  • cpp

Scenario2.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario2.xaml.cpp
00013 // Implementation of the Scenario2 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario2.xaml.h"
00018 #include "CompressionUtils.h"
00019
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Navigation;
00023 using namespace Windows::UI::ViewManagement;
00024 using namespace Windows::Storage;
00025 using namespace Windows::Storage::Pickers;
00026 using namespace Windows::Storage::Streams;
00027 using namespace Windows::Storage::Compression;
00028
00029 using namespace SDKTemplate::Compression;
00030
00031 using namespace concurrency;
00032
00033 Scenario2::Scenario2()
00034 {
00035     InitializeComponent();
00036 }
00037
00038 /// <summary>
00039 /// Invoked when this page is about to be displayed in a Frame.
00040 /// </summary>
00041 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00042 /// property is typically used to configure the page.</param>
00043 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00044 {
00045     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00046     // as NotifyUser()
00047     rootPage = MainPage::Current;
00048 }
00049
00050
00051 void ::SDKTemplate::Compression::Scenario2::DoScenario(CompressAlgorithm Algorithm)
00052 {
00053     Progress->Text = "";
00054     rootPage->NotifyUser("Working...", NotifyType::StatusMessage);
00055
00056     auto context = std::make_shared<ScenarioContext>();
00057     context->raStream = ref new InMemoryRandomAccessStream();
00058
00059     auto picker = ref new Pickers::FileOpenPicker();
00060     picker->FileTypeFilter->Append("*");
00061
00062     // First pick a test file and open it for reading
00063     create_task(picker->PickSingleFileAsync()).then([=](StorageFile^ OriginalFile)
00064     {
00065         if (!OriginalFile)
00066         {
00067             throw std::runtime_error("No file has been selected");
00068         }
00069
00070         Progress->Text += "File \"" + OriginalFile->Name + "\" has been picked\n";
00071
00072         return OriginalFile->OpenAsync(FileAccessMode::Read);
00073     })
00074
00075     // Then read the whole file into memory buffer
00076     .then([=](IRandomAccessStream^ OriginalStream)
00077     {
00078         return ReadStreamTask(OriginalStream, context->originalData).RunTask();
00079     })
00080
00081     // Then compress data into in-memory stream
00082     .then([=](size_t BytesRead)
00083     {
00084         Progress->Text += BytesRead + " bytes have been read from disk\n";
00085
00086         auto memoryOutputStream = context->raStream->GetOutputStreamAt(0);
00087
00088         // Use default constructor if you don't need any specific algorithm and/or block size, use
00089         // "extended" constructor otherwise. This samples shows both versions for demonstration
00090         // purposes only.
00091         if (Algorithm == CompressAlgorithm::InvalidAlgorithm)
00092         {
00093             context->compressor = ref new Compressor(memoryOutputStream);
00094         }
00095         else
00096         {
00097             context->compressor = ref new Compressor(memoryOutputStream,
00098                                                         Algorithm,
00099                                                         0           // use default block size
00100                                                         );
00101         }
00102
00103         Progress->Text += "Compressor object has been created\n";
00104
00105         auto dataWriter = ref new DataWriter(context->compressor);
00106         context->writer = dataWriter;
00107         auto data = ref new Platform::Array<byte>(context->originalData.data(), (unsigned int)context->originalData.size());
00108         dataWriter->WriteBytes(data);
00109
00110         return dataWriter->StoreAsync();
00111     })
00112
00113     // Then finalize compression stream
00114     .then([=](unsigned int BytesWritten)
00115     {
00116         Progress->Text += BytesWritten + " bytes have been compressed\n";
00117
00118         return context->compressor->FinishAsync();
00119     })
00120
00121     // Then read compressed data into a stream
00122     .then([=](bool)
00123     {
00124         Progress->Text += "Compressed into " + context->raStream->Size + " bytes\n";
00125
00126         return ReadStreamTask(context->raStream->GetInputStreamAt(0), context->compressedData).RunTask();
00127     })
00128
00129     // Then decompressed data using "classic" Compression API
00130     .then([=](size_t BytesRead)
00131     {
00132         // IMPORTANT:
00133         // Tasks, that are created over IAsyncOperation (and the likes) or descended from them
00134         // have their continuations scheduled to the same ASTA apartment effectively blocking
00135         // the GUI for the length of processing continuation. Create an independent task here
00136         // instead of adding continuation on the upper level task (which descends from
00137         // "apartment-aware" task) so we will not block the GUI (ASTA) thread while decompressing.
00138         return task<size_t>([=]
00139         {
00140             // We are by convention the only thread to touch context->compressedData and
00141             // context->decompressedData at this point - no synchronization necessary
00142
00143             DECOMPRESSOR_HANDLE decompressorHandle = nullptr;
00144
00145             try
00146             {
00147                 // Enumaration values of Windows::Storage::Compression::CompressAlgorithm are
00148                 // guaranteed to match values from compressapi.h
00149                 ULONG compressAlgorithm = static_cast<ULONG>(Algorithm);
00150                 SIZE_T uncompressedDataSize = 0;
00151                 std::vector<byte> decompressedData;
00152
00153                 // Compress algorithm should always be explicit for "classic" Compression API
00154                 if (compressAlgorithm == COMPRESS_ALGORITHM_INVALID)
00155                 {
00156                     compressAlgorithm = COMPRESS_ALGORITHM_XPRESS;
00157                 }
00158
00159                 if (!CreateDecompressor(compressAlgorithm, nullptr, &decompressorHandle))
00160                 {
00161                     throw std::runtime_error("Cannot create compressor");
00162                 }
00163
00164                 if (!Decompress(decompressorHandle, context->compressedData.data(), context->compressedData.size(), nullptr, 0, &uncompressedDataSize) &&
00165                     (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
00166                 {
00167                     throw std::runtime_error("Cannot get decompressed data size");
00168                 }
00169
00170                 decompressedData.resize(uncompressedDataSize);
00171
00172                 if (!Decompress(decompressorHandle,
00173                                 context->compressedData.data(),
00174                                 context->compressedData.size(),
00175                                 decompressedData.data(),
00176                                 decompressedData.size(),
00177                                 &uncompressedDataSize))
00178                 {
00179                     throw std::runtime_error("Cannot decompress data");
00180                 }
00181
00182                 CloseDecompressor(decompressorHandle);
00183
00184                 context->decompressedData = std::move(decompressedData);
00185                 return context->decompressedData.size();
00186             }
00187             catch (...)
00188             {
00189                 if (decompressorHandle != nullptr)
00190                 {
00191                     CloseDecompressor(decompressorHandle);
00192                 }
00193
00194                 throw;
00195             }
00196         });
00197     })
00198
00199     // Then verify if any data has been lost in action
00200     .then([=](size_t BytesDecompressed)
00201     {
00202         Progress->Text += BytesDecompressed + " bytes have been decompressed\n";
00203
00204         if (context->decompressedData.size() != BytesDecompressed)
00205         {
00206             throw std::runtime_error("Decompressed data size doesn't match number of bytes read from in-memory stream");
00207         }
00208
00209         if (context->originalData.size() != context->decompressedData.size())
00210         {
00211             throw std::runtime_error("Decompressed data size doesn't match original one");
00212         }
00213
00214         if (!std::equal(context->originalData.begin(), context->originalData.end(), context->decompressedData.begin()))
00215         {
00216             throw std::runtime_error("Decompressed data doesn't match original one");
00217         }
00218
00219         Progress->Text += "Decompressed data matches original\n";
00220     })
00221
00222     // Final task based continuation is used to handle exceptions in the chain above
00223     .then([=](task<void> FinalContinuation)
00224     {
00225         try
00226         {
00227             // Transport all exceptions to this thread. This task is guaranteed to be completed by now.
00228             FinalContinuation.get();
00229
00230             Progress->Text += "All done\n";
00231             rootPage->NotifyUser("Finished", NotifyType::StatusMessage);
00232         }
00233         catch (Platform::Exception ^e)
00234         {
00235             rootPage->NotifyUser(e->Message, NotifyType::ErrorMessage);
00236         }
00237         catch (const std::exception &e)
00238         {
00239             std::wstringstream wss;
00240             wss << e.what();
00241             rootPage->NotifyUser(ref new Platform::String(wss.str().c_str()), NotifyType::ErrorMessage);
00242         }
00243     });
00244 }
00245
00246 void ::SDKTemplate::Compression::Scenario2::CompressFileButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00247 {
00248     ComboBoxItem^ item = safe_cast<ComboBoxItem^>(CompressAlgorithmComboBox->SelectedItem);
00249
00250     if (item == nullptr)
00251     {
00252         return;
00253     }
00254
00255     CompressAlgorithm Algorithm = (CompressAlgorithm) CompressAlgorithmFromComboBoxItem(item);
00256
00257     if (Algorithm == CompressAlgorithm::InvalidAlgorithm)
00258     {
00259         return;
00260     }
00261
00262     DoScenario(Algorithm);
00263 }
00264
00265 void ::SDKTemplate::Compression::Scenario2::CompressAlgorithmComboBox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00266 {
00267     SelectionChangedEventArgs^ args = safe_cast<SelectionChangedEventArgs^>(e);
00268
00269     if (args == nullptr)
00270     {
00271         return;
00272     }
00273     if (CompressAlgorithmComboBox == nullptr)
00274     {
00275         return;
00276     }
00277
00278     if (args->AddedItems->Size != 0 && args->RemovedItems->Size == 0)
00279     {
00280         ComboBoxItem^ addedItem = safe_cast<ComboBoxItem^>(args->AddedItems->GetAt(0));
00281         if (addedItem->Content->Equals("Default"))
00282         {
00283                 UpdateDescriptionVisibility(addedItem, Windows::UI::Xaml::Visibility::Visible);
00284         }
00285         return;
00286     }
00287     else
00288     {
00289         ComboBoxItem^ addedItem = safe_cast<ComboBoxItem^>(args->AddedItems->GetAt(0));
00290         ComboBoxItem^ removedItem = safe_cast<ComboBoxItem^>(args->RemovedItems->GetAt(0));
00291
00292         UpdateDescriptionVisibility(addedItem, Windows::UI::Xaml::Visibility::Visible);
00293         UpdateDescriptionVisibility(removedItem, Windows::UI::Xaml::Visibility::Collapsed);
00294     }
00295 }
00296
00297 void ::SDKTemplate::Compression::Scenario2::UpdateDescriptionVisibility(ComboBoxItem^ item, Windows::UI::Xaml::Visibility visibility)
00298 {
00299     TextBlock^ textBlock = nullptr;
00300
00301     CompressAlgorithm algorithm = (CompressAlgorithm) CompressAlgorithmFromComboBoxItem(item);
00302     switch (algorithm)
00303     {
00304     case CompressAlgorithm::NullAlgorithm:
00305         textBlock = DefaultTextBlock;
00306         break;
00307     case CompressAlgorithm::Xpress:
00308         textBlock = XpressTextBlock;
00309         break;
00310     case CompressAlgorithm::XpressHuff:
00311         textBlock = XpressHuffTextBlock;
00312         break;
00313     case CompressAlgorithm::Mszip:
00314         textBlock = MszipTextBlock;
00315         break;
00316     case CompressAlgorithm::Lzms:
00317         textBlock = LzmsTextBlock;
00318         break;
00319     default:
00320         return;
00321     }
00322
00323     textBlock->Visibility = visibility;
00324 }
00325
00326 int ::SDKTemplate::Compression::Scenario2::CompressAlgorithmFromComboBoxItem(ComboBoxItem^ item)
00327 {
00328     CompressAlgorithm Algorithm = CompressAlgorithm::NullAlgorithm;
00329
00330     if (item == DefaultComboBoxItem)
00331     {
00332         Algorithm = CompressAlgorithm::NullAlgorithm;
00333     }
00334     else if (item == XpressComboBoxItem)
00335     {
00336         Algorithm = CompressAlgorithm::Xpress;
00337     }
00338     else if (item == XpressHuffComboBoxItem)
00339     {
00340         Algorithm = CompressAlgorithm::XpressHuff;
00341     }
00342     else if (item == MszipComboBoxItem)
00343     {
00344         Algorithm = CompressAlgorithm::Mszip;
00345     }
00346     else if (item == LzmsComboBoxItem)
00347     {
00348         Algorithm = CompressAlgorithm::Lzms;
00349     }
00350     else
00351     {
00352         Algorithm = CompressAlgorithm::InvalidAlgorithm;
00353     }
00354
00355     return (int) Algorithm;
00356 }
Generated on Fri Nov 15 2024 22:17:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IGameUIControl Member List

This is the complete list of members for IGameUIControl, including all inherited members.
HideGameInfoOverlay() | IGameUIControl
HideTooSmall() | IGameUIControl
SetAction(GameInfoOverlayCommand action) | IGameUIControl
SetGameLoading(uint32 dots) | IGameUIControl
SetGameOver(bool win, int maxLevel, int hitCount, int shotCount, int highScore) | IGameUIControl
SetGameStats(int maxLevel, int hitCount, int shotCount) | IGameUIControl
SetLevelStart(int level, Platform::String^objective, float timeLimit, float bonusTime) | IGameUIControl
SetPause(int level, int hitCount, int shotCount, float timeRemaining) | IGameUIControl
ShowGameInfoOverlay() | IGameUIControl
ShowTooSmall() | IGameUIControl
Generated on Fri Nov 15 2024 22:24:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
ActivitySensorBackgroundTask() | sealed | [inline]
CancelReason | sealed | [private]
CancelRequested | sealed | [private]
CompletionGroupTask() | sealed |
CreateBackgroundDownloader() | sealed | [static]
CreateTransferGroup() | sealed | [static]
InvokeSimpleToast(int succeeded, int failed) | sealed | [private]
IsFailed(Windows::Networking::BackgroundTransfer::DownloadOperation^download) | sealed | [private]
OnCanceled(IBackgroundTaskInstance^taskInstance, BackgroundTaskCancellationReason reason) | sealed |
OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason) | sealed |
OnCanceled(IBackgroundTaskInstance^taskInstance, BackgroundTaskCancellationReason reason) | sealed |
OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason) | sealed |
OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason) | sealed |
PedometerBackgroundTask() | sealed | [inline]
PeriodicTimer | sealed | [private]
Progress | sealed | [private]
ProximitySensorBackgroundTask() | sealed |
RetryDownloadsAsync(Windows::Foundation::Collections::IVector< Windows::Networking::BackgroundTransfer::DownloadOperation^>^downloads) | sealed | [private]
Run(IBackgroundTaskInstance^taskInstance) | sealed | [virtual]
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance) | sealed | [virtual]
Run(IBackgroundTaskInstance^taskInstance) | sealed | [virtual]
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance) | sealed | [virtual]
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance) | sealed | [virtual]
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^taskInstance) | sealed | [virtual]
ServicingComplete() | sealed |
TaskDeferral | sealed | [private]
TaskInstance | sealed | [private]
TaskInstance | sealed | [private]
~ActivitySensorBackgroundTask() | sealed | [inline, private]
~PedometerBackgroundTask() | sealed | [inline, private]
~ProximitySensorBackgroundTask() | sealed | [inline, private]
~ServicingComplete() | sealed | [private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cppwinrt/Project.idl Source File

  • WiFiDirect
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     runtimeclass Scenario1_Advertiser : Windows.UI.Xaml.Controls.Page
00015     {
00016         Scenario1_Advertiser();
00017         Windows.Foundation.Collections.IObservableVector<ConnectedDevice> ConnectedDevices{ get; };
00018
00019         Windows.UI.Xaml.Controls.CheckBox chkPreferGroupOwnerMode{ get; };
00020         Windows.UI.Xaml.Controls.CheckBox chkLegacySetting{ get; };
00021         Windows.UI.Xaml.Controls.ListView lvConnectedDevices{ get; };
00022         Windows.UI.Xaml.Controls.TextBox txtSendMessage{ get; };
00023         Windows.UI.Xaml.Controls.TextBox txtInformationElement{ get; };
00024     }
00025
00026     runtimeclass Scenario2_Connector : Windows.UI.Xaml.Controls.Page
00027     {
00028         Scenario2_Connector();
00029         Windows.Foundation.Collections.IObservableVector<DiscoveredDevice> DiscoveredDevices{ get; };
00030         Windows.Foundation.Collections.IObservableVector<ConnectedDevice> ConnectedDevices{ get; };
00031
00032         Windows.UI.Xaml.Controls.ListView lvConnectedDevices{ get; };
00033         Windows.UI.Xaml.Controls.ListView lvDiscoveredDevices{ get; };
00034         Windows.UI.Xaml.Controls.TextBox txtSendMessage{ get; };
00035     }
00036
00037     runtimeclass ConnectionSettingsPanel : Windows.UI.Xaml.Controls.UserControl
00038     {
00039         ConnectionSettingsPanel();
00040         void Reset();
00041         Windows.Foundation.IAsyncOperation<Boolean> RequestPairDeviceAsync(Windows.Devices.Enumeration.DeviceInformationPairing pairing);
00042     }
00043
00044     [Windows.UI.Xaml.Data.Bindable]
00045     runtimeclass DiscoveredDevice : Windows.UI.Xaml.Data.INotifyPropertyChanged
00046     {
00047         String DisplayName{ get; };
00048     }
00049
00050     [Windows.UI.Xaml.Data.Bindable]
00051     runtimeclass ConnectedDevice : Windows.Foundation.IClosable
00052     {
00053         String DisplayName{ get; };
00054     }
00055
00056     static runtimeclass Utils
00057     {
00058         static Boolean CanSendMessage(String message, Object connectedDevice);
00059         static Boolean IsNonNull(Object value);
00060         static Boolean IsNonEmptyString(String value);
00061     }
00062 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: NumberFormatting/cs/Scenario7_UsingUnicodeExtensions.xaml.cs Source File

  • NumberFormatting
  • cs

Scenario7_UsingUnicodeExtensions.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Text;
00013 using Windows.Globalization;
00014 using Windows.Globalization.NumberFormatting;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     public sealed partial class Scenario7_UsingUnicodeExtensions: Page
00024     {
00025         public Scenario7_UsingUnicodeExtensions()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         /// <summary>
00031         /// This is the click handler for the 'Display' button.
00032         /// </summary>
00033         /// <param name="sender"></param>
00034         /// <param name="e"></param>
00035         private void Display_Click(object sender, RoutedEventArgs e)
00036         {
00037             // This scenario uses language tags with unicode extensions to construct and use the various
00038             // formatters and NumeralSystemTranslator in Windows.Globalization.NumberFormatting to format numbers
00039
00040             // Keep results of the scenario in a StringBuilder
00041             StringBuilder results = new StringBuilder();
00042
00043             // Create number to format.
00044             double randomNumber = (new Random().NextDouble() * 100000);
00045             results.AppendLine("Random number used by formatters: " + randomNumber);
00046             // Create a string to translate
00047             String stringToTranslate = "These are the 10 digits of a numeral system: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9";
00048             results.AppendLine("String used by NumeralSystemTranslater: " + stringToTranslate);
00049             // Create the rounder and set its increment to 0.01
00050             IncrementNumberRounder rounder = new Windows.Globalization.NumberFormatting.IncrementNumberRounder();
00051             rounder.Increment = 0.001;
00052             results.AppendLine("CurrencyFormatter will be using Euro symbol and all formatters rounding to 0.001 increments");
00053             results.AppendLine();
00054
00055             // The list of language tags with unicode extensions we want to test
00056             String[] languages = new[] { "de-DE-u-nu-telu-ca-buddist-co-phonebk-cu-usd", "ja-jp-u-nu-arab"};
00057
00058             // Create the various formatters, now using the language list with unicode extensions
00059             results.AppendLine("Creating formatters using following languages in the language list:");
00060             foreach(String language in languages)
00061             {
00062                 results.AppendLine("\t" + language);
00063             }
00064             results.AppendLine();
00065
00066             // Create the various formatters.
00067             DecimalFormatter decimalFormatter = new DecimalFormatter(languages, "ZZ");
00068             decimalFormatter.NumberRounder = rounder; decimalFormatter.FractionDigits = 2;
00069             CurrencyFormatter currencyFormatter = new CurrencyFormatter(CurrencyIdentifiers.EUR, languages, "ZZ");
00070             currencyFormatter.NumberRounder = rounder; currencyFormatter.FractionDigits = 2;
00071             PercentFormatter percentFormatter = new PercentFormatter(languages, "ZZ");
00072             percentFormatter.NumberRounder = rounder; percentFormatter.FractionDigits = 2;
00073             PermilleFormatter permilleFormatter = new PermilleFormatter(languages, "ZZ");
00074             permilleFormatter.NumberRounder = rounder; permilleFormatter.FractionDigits = 2;
00075             NumeralSystemTranslator numeralTranslator = new NumeralSystemTranslator(languages);
00076
00077             results.AppendLine("Using resolved language  " + decimalFormatter.ResolvedLanguage + "  : (note that all extension tags other than nu are ignored)");
00078             // Format using formatters and translate using NumeralSystemTranslator.
00079             results.AppendLine("Decimal Formatted:   " + decimalFormatter.Format(randomNumber));
00080             results.AppendLine("Currency formatted:   " + currencyFormatter.Format(randomNumber));
00081             results.AppendLine("Percent formatted:   " + percentFormatter.Format(randomNumber));
00082             results.AppendLine("Permille formatted:   " + permilleFormatter.Format(randomNumber));
00083             results.AppendLine("NumeralTranslator translated:   " + numeralTranslator.TranslateNumerals(stringToTranslate));
00084             results.AppendLine();
00085
00086             // Display the results
00087             OutputTextBlock.Text = results.ToString();
00088         }
00089     }
00090 }
Generated on Fri Nov 15 2024 22:20:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlContextMenu/cs/SampleConfiguration.cs Source File

  • XamlContextMenu
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "XAML Context Menu";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="ContextFlyout on an element", ClassType=typeof(Scenario1)},
00025             new Scenario() { Title="ContextFlyout in ListView", ClassType=typeof(Scenario2)},
00026             new Scenario() { Title="ContextRequested event", ClassType=typeof(Scenario3)},
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PdfDocument/cppwinrt/Scenario1_Render.h Source File

  • PdfDocument
  • cppwinrt

Scenario1_Render.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Render.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1_Render : Scenario1_RenderT<Scenario1_Render>
00020     {
00021         Scenario1_Render();
00022
00023         fire_and_forget LoadDocument(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024         fire_and_forget ViewPage(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00025
00026     private:
00027         SDKTemplate::MainPage rootPage{ SDKTemplate::implementation::MainPage::Current() };
00028         Windows::Data::Pdf::PdfDocument pdfDocument{ nullptr };
00029
00030     };
00031 }
00032
00033 namespace winrt::SDKTemplate::factory_implementation
00034 {
00035     struct Scenario1_Render : Scenario1_RenderT<Scenario1_Render, implementation::Scenario1_Render>
00036     {
00037     };
00038 }
Generated on Fri Nov 15 2024 22:20:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraFrames/cpp/FrameRenderer.cpp Source File

  • CameraFrames
  • cpp

FrameRenderer.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <cmath>
00014 #include <MemoryBuffer.h>
00015 #include "FrameRenderer.h"
00016
00017 using namespace SDKTemplate;
00018
00019 using namespace concurrency;
00020 using namespace Platform;
00021 using namespace Microsoft::WRL;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Graphics::Imaging;
00024 using namespace Windows::Media::Capture::Frames;
00025 using namespace Windows::Media::MediaProperties;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Media::Imaging;
00028
00029 #pragma region Low-level operations on reference pointers
00030
00031 // InterlockedExchange for reference pointer types.
00032 template<typename T, typename U>
00033 T^ InterlockedExchangeRefPointer(T^* target, U value)
00034 {
00035     static_assert(sizeof(T^) == sizeof(void*), "InterlockedExchangePointer is the wrong size");
00036     T^ exchange = value;
00037     void** rawExchange = reinterpret_cast<void**>(&exchange);
00038     void** rawTarget = reinterpret_cast<void**>(target);
00039     *rawExchange = static_cast<IInspectable*>(InterlockedExchangePointer(rawTarget, *rawExchange));
00040     return exchange;
00041 }
00042
00043 // Convert a reference pointer to a specific ComPtr.
00044 template<typename T>
00045 Microsoft::WRL::ComPtr<T> AsComPtr(Platform::Object^ object)
00046 {
00047     Microsoft::WRL::ComPtr<T> p;
00048     reinterpret_cast<IUnknown*>(object)->QueryInterface(IID_PPV_ARGS(&p));
00049     return p;
00050 }
00051 #pragma endregion
00052
00053 // Structure used to access colors stored in 8-bit BGRA format.
00054 struct ColorBGRA
00055 {
00056     byte B, G, R, A;
00057 };
00058
00059 // Colors to map values to based on intensity.
00060 static constexpr std::array<ColorBGRA, 9> colorRamp = {
00061     ColorBGRA{ 0xFF, 0x7F, 0x00, 0x00 },
00062     ColorBGRA{ 0xFF, 0xFF, 0x00, 0x00 },
00063     ColorBGRA{ 0xFF, 0xFF, 0x7F, 0x00 },
00064     ColorBGRA{ 0xFF, 0xFF, 0xFF, 0x00 },
00065     ColorBGRA{ 0xFF, 0x7F, 0xFF, 0x7F },
00066     ColorBGRA{ 0xFF, 0x00, 0xFF, 0xFF },
00067     ColorBGRA{ 0xFF, 0x00, 0x7F, 0xFF },
00068     ColorBGRA{ 0xFF, 0x00, 0x00, 0xFF },
00069     ColorBGRA{ 0xFF, 0x00, 0x00, 0x7F }
00070 };
00071
00072 static ColorBGRA ColorRampInterpolation(float value)
00073 {
00074     static_assert(colorRamp.size() >= 2, "colorRamp table is too small");
00075
00076     // Map value to surrounding indexes on the color ramp.
00077     size_t rampSteps = colorRamp.size() - 1;
00078     float scaled = value * rampSteps;
00079     int integer = static_cast<int>(scaled);
00080     int index = min(static_cast<size_t>(max(0, integer)), rampSteps - 1);
00081     const ColorBGRA& prev = colorRamp[index];
00082     const ColorBGRA& next = colorRamp[index + 1];
00083
00084     // Set color based on a ratio of how closely it matches the surrounding colors.
00085     UINT32 alpha = static_cast<UINT32>((scaled - integer) * 255);
00086     UINT32 beta = 255 - alpha;
00087     return {
00088         static_cast<byte>((prev.A * beta + next.A * alpha) / 255), // Alpha
00089         static_cast<byte>((prev.R * beta + next.R * alpha) / 255), // Red
00090         static_cast<byte>((prev.G * beta + next.G * alpha) / 255), // Green
00091         static_cast<byte>((prev.B * beta + next.B * alpha) / 255)  // Blue
00092     };
00093 }
00094
00095 // Initializes pseudo-color look up table for depth pixels
00096 static ColorBGRA GeneratePseudoColorLookupTable(UINT32 index, UINT32 size)
00097 {
00098     return ColorRampInterpolation(static_cast<float>(index) / static_cast<float>(size));
00099 }
00100
00101 // Initializes the pseudo-color look up table for infrared pixels
00102 static ColorBGRA GenerateInfraredRampLookupTable(UINT32 index, UINT32 size)
00103 {
00104     const float value = static_cast<float>(index) / static_cast<float>(size);
00105
00106     // Adjust to increase color change between lower values in infrared images.
00107     const float alpha = powf(1 - value, 12);
00108
00109     return ColorRampInterpolation(alpha);
00110 }
00111
00112 static LookupTable<ColorBGRA, 1024> colorLookupTable(GeneratePseudoColorLookupTable);
00113 static LookupTable<ColorBGRA, 1024> infraredLookupTable(GenerateInfraredRampLookupTable);
00114
00115 static ColorBGRA PseudoColor(float value)
00116 {
00117     return colorLookupTable.GetValue(value);
00118 }
00119
00120 static ColorBGRA InfraredColor(float value)
00121 {
00122     return infraredLookupTable.GetValue(value);
00123 }
00124
00125 // Maps each pixel in a scanline from a 16 bit depth value to a pseudo-color pixel.
00126 static void PseudoColorForDepth(int pixelWidth, byte* inputRowBytes, byte* outputRowBytes, float depthScale, float minReliableDepth, float maxReliableDepth)
00127 {
00128     // Visualize space in front of your desktop, in meters.
00129     float minInMeters = minReliableDepth * depthScale;
00130     float maxInMeters = maxReliableDepth * depthScale;
00131     float one_min = 1.0f / minInMeters;
00132     float range = 1.0f / maxInMeters - one_min;
00133
00134     UINT16* inputRow = reinterpret_cast<UINT16*>(inputRowBytes);
00135     ColorBGRA* outputRow = reinterpret_cast<ColorBGRA*>(outputRowBytes);
00136     for (int x = 0; x < pixelWidth; x++)
00137     {
00138         float depth = static_cast<float>(inputRow[x]) * depthScale;
00139
00140         // Map invalid depth values to transparent pixels.
00141         // This happens when depth information cannot be calculated, e.g. when objects are too close.
00142         if (depth == 0)
00143         {
00144             outputRow[x] = { 0 };
00145         }
00146         else
00147         {
00148             float alpha = (1.0f / depth - one_min) / range;
00149             outputRow[x] = PseudoColor(alpha * alpha);
00150         }
00151     }
00152 }
00153
00154 // Maps each pixel in a scanline from a 16 bit infrared value to a pseudo-color pixel.
00155 static void PseudoColorFor16BitInfrared(int pixelWidth, byte* inputRowBytes, byte* outputRowBytes)
00156 {
00157     UINT16* inputRow = reinterpret_cast<UINT16*>(inputRowBytes);
00158     ColorBGRA* outputRow = reinterpret_cast<ColorBGRA*>(outputRowBytes);
00159     for (int x = 0; x < pixelWidth; x++)
00160     {
00161         outputRow[x] = InfraredColor(inputRow[x] / static_cast<float>(UINT16_MAX));
00162     }
00163 }
00164
00165 // Maps each pixel in a scanline from a 8 bit infrared value to a pseudo-color pixel.
00166 static void PseudoColorFor8BitInfrared(int pixelWidth, byte* inputRowBytes, byte* outputRowBytes)
00167 {
00168     ColorBGRA* outputRow = reinterpret_cast<ColorBGRA*>(outputRowBytes);
00169     for (int x = 0; x < pixelWidth; x++)
00170     {
00171         outputRow[x] = InfraredColor(inputRowBytes[x] / static_cast<float>(UINT8_MAX));
00172     }
00173 }
00174
00175 FrameRenderer::FrameRenderer(Image^ imageElement)
00176 {
00177     m_imageElement = imageElement;
00178     m_imageElement->Source = ref new SoftwareBitmapSource();
00179 }
00180
00181 Concurrency::task<void> FrameRenderer::DrainBackBufferAsync()
00182 {
00183     // Keep draining frames from the backbuffer until the backbuffer is empty.
00184     SoftwareBitmap^ latestBitmap = InterlockedExchangeRefPointer(&m_backBuffer, nullptr);
00185     if (latestBitmap != nullptr)
00186     {
00187         if (SoftwareBitmapSource^ imageSource = dynamic_cast<SoftwareBitmapSource^>(m_imageElement->Source))
00188         {
00189             return create_task(imageSource->SetBitmapAsync(latestBitmap))
00190                 .then([this]()
00191             {
00192                 return DrainBackBufferAsync();
00193             }, task_continuation_context::use_current());
00194         }
00195     }
00196
00197     // To avoid a race condition against ProcessFrame, we cannot let any other
00198     // tasks run on the UI thread between point that the InterlockedExchangeRefPointer
00199     // reports that there is no more work, and we clear the m_taskRunning flag on
00200     // the UI thread.
00201     m_taskRunning = false;
00202
00203     return task_from_result();
00204 }
00205
00206 void FrameRenderer::ProcessFrame(Windows::Media::Capture::Frames::MediaFrameReference^ frame)
00207 {
00208     if (frame == nullptr)
00209     {
00210         return;
00211     }
00212
00213     SoftwareBitmap^ softwareBitmap = ConvertToDisplayableImage(frame->VideoMediaFrame);
00214     if (softwareBitmap != nullptr)
00215     {
00216         // Swap the processed frame to _backBuffer, and trigger the UI thread to render it.
00217         softwareBitmap = InterlockedExchangeRefPointer(&m_backBuffer, softwareBitmap);
00218
00219         // UI thread always resets m_backBuffer before using it. Unused bitmap should be disposed.
00220         delete softwareBitmap;
00221
00222         // Changes to the XAML ImageElement must happen in the UI thread, via the CoreDispatcher.
00223         m_imageElement->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
00224             ref new Windows::UI::Core::DispatchedHandler([this]()
00225         {
00226             // Don't let two copies of this task run at the same time.
00227             if (m_taskRunning)
00228             {
00229                 return;
00230             }
00231
00232             m_taskRunning = true;
00233
00234             // Keep draining frames from the backbuffer until the backbuffer is empty.
00235             DrainBackBufferAsync();
00236         }));
00237     }
00238 }
00239
00240 String^ FrameRenderer::GetSubtypeForFrameReader(MediaFrameSourceKind kind, MediaFrameFormat^ format)
00241 {
00242     // Note that media encoding subtypes may differ in case.
00243     // https://docs.microsoft.com/en-us/uwp/api/Windows.Media.MediaProperties.MediaEncodingSubtypes
00244
00245     String^ subtype = format->Subtype;
00246     switch (kind)
00247     {
00248         // For color sources, we accept anything and request that it be converted to Bgra8.
00249     case MediaFrameSourceKind::Color:
00250         return MediaEncodingSubtypes::Bgra8;
00251
00252         // The only depth format we can render is D16.
00253     case MediaFrameSourceKind::Depth:
00254         return CompareStringOrdinal(subtype->Data(), -1, MediaEncodingSubtypes::D16->Data(), -1, TRUE) == CSTR_EQUAL ? subtype : nullptr;
00255
00256         // The only infrared formats we can render are NV12, L8, and L16.
00257     case MediaFrameSourceKind::Infrared:
00258         return (CompareStringOrdinal(subtype->Data(), -1, MediaEncodingSubtypes::Nv12->Data(), -1, TRUE) == CSTR_EQUAL ||
00259             CompareStringOrdinal(subtype->Data(), -1, MediaEncodingSubtypes::L8->Data(), -1, TRUE) == CSTR_EQUAL ||
00260             CompareStringOrdinal(subtype->Data(), -1, MediaEncodingSubtypes::L16->Data(), -1, TRUE) == CSTR_EQUAL) ? subtype : nullptr;
00261
00262         // No other source kinds are supported by this class.
00263     default:
00264         return nullptr;
00265     }
00266 }
00267
00268 SoftwareBitmap^ FrameRenderer::ConvertToDisplayableImage(VideoMediaFrame^ inputFrame)
00269 {
00270     if (inputFrame == nullptr)
00271     {
00272         return nullptr;
00273     }
00274
00275     SoftwareBitmap^ inputBitmap = inputFrame->SoftwareBitmap;
00276     auto mode = inputBitmap->BitmapAlphaMode;
00277
00278     switch (inputFrame->FrameReference->SourceKind)
00279     {
00280     case MediaFrameSourceKind::Color:
00281         // XAML requires Bgra8 with premultiplied alpha.
00282         // We requested Bgra8 from the MediaFrameReader, so all that's
00283         // left is fixing the alpha channel if necessary.
00284         if (inputBitmap->BitmapPixelFormat != BitmapPixelFormat::Bgra8)
00285         {
00286             OutputDebugStringW(L"Color format should have been Bgra8.\r\n");
00287         }
00288         else if (inputBitmap->BitmapAlphaMode == BitmapAlphaMode::Premultiplied)
00289         {
00290             // Already in the correct format.
00291             return SoftwareBitmap::Copy(inputBitmap);
00292         }
00293         else
00294         {
00295             // Convert to premultiplied alpha.
00296             return SoftwareBitmap::Convert(inputBitmap, BitmapPixelFormat::Bgra8, BitmapAlphaMode::Premultiplied);
00297         }
00298         return nullptr;
00299
00300     case MediaFrameSourceKind::Depth:
00301         // We requested D16 from the MediaFrameReader, so the frame should
00302         // be in Gray16 format.
00303
00304         if (inputBitmap->BitmapPixelFormat == BitmapPixelFormat::Gray16)
00305         {
00306             using namespace std::placeholders;
00307
00308             // Use a special pseudo color to render 16 bits depth frame.
00309             // Since we must scale the output appropriately we use std::bind to
00310             // create a function that takes the depth scale as input but also matches
00311             // the required signature.
00312             double depthScale = inputFrame->DepthMediaFrame->DepthFormat->DepthScaleInMeters;
00313             unsigned int minReliableDepth = inputFrame->DepthMediaFrame->MinReliableDepth;
00314             unsigned int maxReliableDepth = inputFrame->DepthMediaFrame->MaxReliableDepth;
00315             return TransformBitmap(inputBitmap, std::bind(&PseudoColorForDepth, _1, _2, _3, static_cast<float>(depthScale), minReliableDepth, maxReliableDepth));
00316         }
00317         else
00318         {
00319             OutputDebugStringW(L"Depth format in unexpected format.\r\n");
00320         }
00321         return nullptr;
00322
00323     case MediaFrameSourceKind::Infrared:
00324         // We requested L8 or L16 from the MediaFrameReader, so the frame should
00325         // be in Gray8 or Gray16 format.
00326         switch (inputBitmap->BitmapPixelFormat)
00327         {
00328         case BitmapPixelFormat::Gray8:
00329             // Use pseudo color to render 8 bits frames.
00330             return TransformBitmap(inputBitmap, PseudoColorFor8BitInfrared);
00331
00332         case BitmapPixelFormat::Gray16:
00333             // Use pseudo color to render 16 bits frames.
00334             return TransformBitmap(inputBitmap, PseudoColorFor16BitInfrared);
00335
00336         case BitmapPixelFormat::Nv12:
00337             return SoftwareBitmap::Convert(inputBitmap, BitmapPixelFormat::Bgra8, BitmapAlphaMode::Premultiplied);
00338
00339         default:
00340             OutputDebugStringW(L"Infrared format should have been NV12, Gray8, or Gray16.\r\n");
00341             return nullptr;
00342         }
00343     }
00344
00345     return nullptr;
00346 }
00347
00348 SoftwareBitmap^ FrameRenderer::TransformBitmap(SoftwareBitmap^ inputBitmap, TransformScanline pixelTransformation)
00349 {
00350     // XAML Image control only supports premultiplied Bgra8 format.
00351     SoftwareBitmap^ outputBitmap = ref new SoftwareBitmap(
00352         BitmapPixelFormat::Bgra8,
00353         inputBitmap->PixelWidth,
00354         inputBitmap->PixelHeight,
00355         BitmapAlphaMode::Premultiplied);
00356
00357     BitmapBuffer^ input = inputBitmap->LockBuffer(BitmapBufferAccessMode::Read);
00358     BitmapBuffer^ output = outputBitmap->LockBuffer(BitmapBufferAccessMode::Write);
00359
00360     // Get stride values to calculate buffer position for a given pixel x and y position.
00361     int inputStride = input->GetPlaneDescription(0).Stride;
00362     int outputStride = output->GetPlaneDescription(0).Stride;
00363
00364     int pixelWidth = inputBitmap->PixelWidth;
00365     int pixelHeight = inputBitmap->PixelHeight;
00366
00367     IMemoryBufferReference^ inputReference = input->CreateReference();
00368     IMemoryBufferReference^ outputReference = output->CreateReference();
00369
00370     // Get input and output byte access buffers.
00371     byte* inputBytes;
00372     UINT32 inputCapacity;
00373     AsComPtr<IMemoryBufferByteAccess>(inputReference)->GetBuffer(&inputBytes, &inputCapacity);
00374
00375     byte* outputBytes;
00376     UINT32 outputCapacity;
00377     AsComPtr<IMemoryBufferByteAccess>(outputReference)->GetBuffer(&outputBytes, &outputCapacity);
00378
00379     // Iterate over all pixels, and store the converted value.
00380     for (int y = 0; y < pixelHeight; y++)
00381     {
00382         byte* inputRowBytes = inputBytes + y * inputStride;
00383         byte* outputRowBytes = outputBytes + y * outputStride;
00384
00385         pixelTransformation(pixelWidth, inputRowBytes, outputRowBytes);
00386     }
00387
00388     // Close objects that need closing.
00389     delete outputReference;
00390     delete inputReference;
00391     delete output;
00392     delete input;
00393
00394     return outputBitmap;
00395 }
Generated on Fri Nov 15 2024 22:18:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLInProcessWinRTComponent/cpp/cpp/Scenario1_OvenClient.xaml.h Source File

  • WRLInProcessWinRTComponent
  • cpp
  • cpp

Scenario1_OvenClient.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008 #include "Scenario1_OvenClient.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     namespace WRLInProcessWinRTComponent
00013     {
00014         public ref class OvenClient sealed
00015         {
00016         public:
00017             OvenClient();
00018
00019         private:
00020             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021             void BreadCompletedHandler1(Microsoft::SDKSamples::Kitchen::Oven^ oven, Microsoft::SDKSamples::Kitchen::BreadBakedEventArgs^ args);
00022             void BreadCompletedHandler2(Microsoft::SDKSamples::Kitchen::Oven^ oven, Microsoft::SDKSamples::Kitchen::BreadBakedEventArgs^ args);
00023             void BreadCompletedHandler3(Microsoft::SDKSamples::Kitchen::Oven^ oven, Microsoft::SDKSamples::Kitchen::BreadBakedEventArgs^ args);
00024
00025             Microsoft::SDKSamples::Kitchen::Oven^ _myOven; // keep around since this is an event source
00026         };
00027     }
00028 }
Generated on Fri Nov 15 2024 22:21:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_DataEvents Member List

This is the complete list of members for Scenario1_DataEvents, including all inherited members.
DesiredReportInterval | Scenario1_DataEvents | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_DataEvents | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario1_DataEvents | [inline, protected]
ReadingChanged(object sender, InclinometerReadingChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
rootPage | Scenario1_DataEvents | [private]
Scenario1_DataEvents() | Scenario1_DataEvents | [inline]
ScenarioDisable(object sender, RoutedEventArgs e) | Scenario1_DataEvents | [inline, private]
ScenarioEnable(object sender, RoutedEventArgs e) | Scenario1_DataEvents | [inline, private]
Sensor | Scenario1_DataEvents | [private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_GetAndSetPin Member List

This is the complete list of members for Scenario1_GetAndSetPin, including all inherited members.
GetPinValue_Click(object sender, RoutedEventArgs e) | Scenario1_GetAndSetPin | [inline, private]
LED_PIN | Scenario1_GetAndSetPin | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_GetAndSetPin | [inline, protected]
pin | Scenario1_GetAndSetPin | [private]
Scenario1_GetAndSetPin() | Scenario1_GetAndSetPin | [inline]
SetPinHigh_Click(object sender, RoutedEventArgs e) | Scenario1_GetAndSetPin | [inline, private]
SetPinLow_Click(object sender, RoutedEventArgs e) | Scenario1_GetAndSetPin | [inline, private]
StartScenario() | Scenario1_GetAndSetPin | [inline, private]
StartStopScenario_Click(object sender, RoutedEventArgs e) | Scenario1_GetAndSetPin | [inline, private]
StopScenario() | Scenario1_GetAndSetPin | [inline, private]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LoggingChannelScenario Member List

This is the complete list of members for LoggingChannelScenario, including all inherited members.
CollectExpensiveData() | LoggingChannelScenario | [private]
DemonstrateLogging(Windows::Foundation::Diagnostics::LoggingChannel const &channel) | LoggingChannelScenario | [private]
DoSomething(Windows::Foundation::Diagnostics::ILoggingTarget const &logger) | LoggingChannelScenario | [private]
LogWithWin10Constructor() | LoggingChannelScenario |
LogWithWin81Constructor() | LoggingChannelScenario |
OnLoggingEnabled(Windows::Foundation::Diagnostics::ILoggingChannel const &sender, Windows::Foundation::IInspectable const &e) | LoggingChannelScenario | [private]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/VertexShader/BasicReaderWriter.cpp Source File

  • D2DCustomEffects
  • cpp
  • VertexShader

BasicReaderWriter.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "BasicReaderWriter.h"
00014
00015 using namespace Microsoft::WRL;
00016 using namespace Windows::Storage;
00017 using namespace Windows::Storage::FileProperties;
00018 using namespace Windows::Storage::Streams;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::ApplicationModel;
00021 using namespace concurrency;
00022
00023 BasicReaderWriter::BasicReaderWriter()
00024 {
00025     m_location = Package::Current->InstalledLocation;
00026 }
00027
00028 BasicReaderWriter::BasicReaderWriter(
00029     _In_ Windows::Storage::StorageFolder^ folder
00030     )
00031 {
00032     m_location = folder;
00033     Platform::String^ path = m_location->Path;
00034     if (path->Length() == 0)
00035     {
00036         // Applications are not permitted to access certain
00037         // folders, such as the Documents folder, using this
00038         // code path.  In such cases, the Path property for
00039         // the folder will be an empty string.
00040         throw ref new Platform::FailureException();
00041     }
00042 }
00043
00044 Platform::Array<byte>^ BasicReaderWriter::ReadData(
00045     _In_ Platform::String^ filename
00046     )
00047 {
00048     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00049     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00050     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00051     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00052     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00053     extendedParams.lpSecurityAttributes = nullptr;
00054     extendedParams.hTemplateFile = nullptr;
00055
00056     Wrappers::FileHandle file(
00057         CreateFile2(
00058             filename->Data(),
00059             GENERIC_READ,
00060             FILE_SHARE_READ,
00061             OPEN_EXISTING,
00062             &extendedParams
00063             )
00064         );
00065     if (file.Get() == INVALID_HANDLE_VALUE)
00066     {
00067         throw ref new Platform::FailureException();
00068     }
00069
00070     FILE_STANDARD_INFO fileInfo = {0};
00071     if (!GetFileInformationByHandleEx(
00072         file.Get(),
00073         FileStandardInfo,
00074         &fileInfo,
00075         sizeof(fileInfo)
00076         ))
00077     {
00078         throw ref new Platform::FailureException();
00079     }
00080
00081     if (fileInfo.EndOfFile.HighPart != 0)
00082     {
00083         throw ref new Platform::OutOfMemoryException();
00084     }
00085
00086     Platform::Array<byte>^ fileData = ref new Platform::Array<byte>(fileInfo.EndOfFile.LowPart);
00087
00088     if (!ReadFile(
00089         file.Get(),
00090         fileData->Data,
00091         fileData->Length,
00092         nullptr,
00093         nullptr
00094         ))
00095     {
00096         throw ref new Platform::FailureException();
00097     }
00098
00099     return fileData;
00100 }
00101
00102 task<Platform::Array<byte>^> BasicReaderWriter::ReadDataAsync(
00103     _In_ Platform::String^ filename
00104     )
00105 {
00106     return task<StorageFile^>(m_location->GetFileAsync(filename)).then([=](StorageFile^ file)
00107     {
00108         return FileIO::ReadBufferAsync(file);
00109     }).then([=](IBuffer^ buffer)
00110     {
00111         auto fileData = ref new Platform::Array<byte>(buffer->Length);
00112         DataReader::FromBuffer(buffer)->ReadBytes(fileData);
00113         return fileData;
00114     });
00115 }
00116
00117 uint32 BasicReaderWriter::WriteData(
00118     _In_ Platform::String^ filename,
00119     _In_ const Platform::Array<byte>^ fileData
00120     )
00121 {
00122     CREATEFILE2_EXTENDED_PARAMETERS extendedParams = {0};
00123     extendedParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
00124     extendedParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
00125     extendedParams.dwFileFlags = FILE_FLAG_SEQUENTIAL_SCAN;
00126     extendedParams.dwSecurityQosFlags = SECURITY_ANONYMOUS;
00127     extendedParams.lpSecurityAttributes = nullptr;
00128     extendedParams.hTemplateFile = nullptr;
00129
00130     Wrappers::FileHandle file(
00131         CreateFile2(
00132             filename->Data(),
00133             GENERIC_WRITE,
00134             0,
00135             CREATE_ALWAYS,
00136             &extendedParams
00137             )
00138         );
00139     if (file.Get() == INVALID_HANDLE_VALUE)
00140     {
00141         throw ref new Platform::FailureException();
00142     }
00143
00144     DWORD numBytesWritten;
00145     if (
00146         !WriteFile(
00147             file.Get(),
00148             fileData->Data,
00149             fileData->Length,
00150             &numBytesWritten,
00151             nullptr
00152             ) ||
00153         numBytesWritten != fileData->Length
00154         )
00155     {
00156         throw ref new Platform::FailureException();
00157     }
00158
00159     return numBytesWritten;
00160 }
00161
00162 task<void> BasicReaderWriter::WriteDataAsync(
00163     _In_ Platform::String^ filename,
00164     _In_ const Platform::Array<byte>^ fileData
00165     )
00166 {
00167     return task<StorageFile^>(m_location->CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting)).then([=](StorageFile^ file)
00168     {
00169         FileIO::WriteBytesAsync(file, fileData);
00170     });
00171 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1 Member List

This is the complete list of members for Scenario1, including all inherited members.
Scenario1() Scenario1 [inline]
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactPicker/cpp/Scenario1_Single.xaml.h Source File

  • ContactPicker
  • cpp

Scenario1_Single.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Single.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario1_Single sealed
00021     {
00022     public:
00023         Scenario1_Single();
00024         void PickContactEmail();
00025         void PickContactPhone();
00026
00027     private:
00028         MainPage^ rootPage = MainPage::Current;
00029
00030         void ClearOutputs();
00031         void ReportContactResult(Windows::ApplicationModel::Contacts::Contact^ contact);
00032     };
00033 }
Generated on Fri Nov 15 2024 22:18:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cpp/GameRenderer.cpp Source File

  • Simple3DGameDX
  • cpp

GameRenderer.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "GameRenderer.h"
00014 #include "ConstantBuffers.h"
00015 #include "TargetTexture.h"
00016 #include "BasicLoader.h"
00017 #include "CylinderMesh.h"
00018 #include "FaceMesh.h"
00019 #include "SphereMesh.h"
00020 #include "WorldMesh.h"
00021 #include "Face.h"
00022 #include "Sphere.h"
00023 #include "Cylinder.h"
00024
00025 using namespace concurrency;
00026 using namespace DirectX;
00027 using namespace Microsoft::WRL;
00028 using namespace Windows::UI::Core;
00029 using namespace Simple3DGameDX;
00030
00031 //----------------------------------------------------------------------
00032
00033 GameRenderer::GameRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00034     m_deviceResources(deviceResources),
00035     m_initialized(false),
00036     m_gameResourcesLoaded(false),
00037     m_levelResourcesLoaded(false)
00038 {
00039     m_gameHud = ref new GameHud(
00040         deviceResources,
00041         "Windows platform samples",
00042         "DirectX first-person game sample"
00043         );
00044     m_gameInfoOverlay = ref new GameInfoOverlay(deviceResources);
00045
00046     CreateDeviceDependentResources();
00047     CreateWindowSizeDependentResources();
00048 }
00049
00050 //----------------------------------------------------------------------
00051
00052 void GameRenderer::ReleaseDeviceDependentResources()
00053 {
00054     // On device lost all the device resources are invalid.
00055     // Set the state of the renderer to not have a pointer to the
00056     // Simple3DGame object.  It will be reset as a part of the
00057     // game devices resources being recreated.
00058     m_game = nullptr;
00059     m_gameHud->ReleaseDeviceDependentResources();
00060     m_gameInfoOverlay->ReleaseDeviceDependentResources();
00061 }
00062
00063 //----------------------------------------------------------------------
00064
00065 void GameRenderer::CreateDeviceDependentResources()
00066 {
00067     m_gameResourcesLoaded = false;
00068     m_levelResourcesLoaded = false;
00069
00070     m_gameHud->CreateDeviceDependentResources();
00071     m_gameInfoOverlay->CreateDeviceDependentResources();
00072 }
00073
00074 //----------------------------------------------------------------------
00075
00076 void GameRenderer::CreateWindowSizeDependentResources()
00077 {
00078     m_gameHud->CreateWindowSizeDependentResources();
00079
00080     m_gameInfoOverlaySize.height = GameInfoOverlayConstant::Height;
00081     m_gameInfoOverlaySize.width = GameInfoOverlayConstant::Width;
00082
00083     auto d3dContext = m_deviceResources->GetD3DDeviceContext();
00084     auto renderTargetSize = m_deviceResources->GetRenderTargetSize();
00085
00086     auto bounds = m_deviceResources->GetLogicalSize();
00087     float hudBottomY = GameConstants::HudTopOffset + (GameConstants::HudBodyPointSize + GameConstants::Margin) * 4;
00088     float topY = (bounds.Height - GameInfoOverlayConstant::Height) / 2.0f;
00089
00090     // The default position of the GameInfoOverlay is centered in the window.  There are cases where
00091     // There are cases where this will be adjusted:
00092     // 1) Shift down to allow the Hud to be visible if possible.
00093     // 2) Shift up if after 1) the GameInfoOverlay extends below the bottom of the window.
00094     // 3) Ensure the width of the GameInfoOverlay is not wider than the window, if it is
00095     //    reduce the width to be the same as the window width.
00096     if (hudBottomY > topY)
00097     {
00098         topY = hudBottomY + GameConstants::Margin;
00099     }
00100     if ((topY + m_gameInfoOverlaySize.height) > bounds.Height)
00101     {
00102         topY = bounds.Height - m_gameInfoOverlaySize.height;
00103     }
00104     if (m_gameInfoOverlaySize.width > bounds.Width)
00105     {
00106         m_gameInfoOverlaySize.width = bounds.Width;
00107     }
00108     float topX = (bounds.Width - m_gameInfoOverlaySize.width) / 2.0f;
00109
00110     m_gameInfoOverlayRect = D2D1::RectF(
00111         topX,
00112         topY,
00113         topX + m_gameInfoOverlaySize.width,
00114         topY + m_gameInfoOverlaySize.height
00115         );
00116
00117     m_gameInfoOverlay->CreateWindowSizeDependentResources(m_gameInfoOverlaySize);
00118
00119     if (m_game != nullptr)
00120     {
00121         // Update the Projection Matrix and the associated Constant Buffer.
00122         m_game->GameCamera()->SetProjParams(
00123             XM_PI / 2, renderTargetSize.Width / renderTargetSize.Height,
00124             0.01f,
00125             100.0f
00126             );
00127
00128         XMFLOAT4X4 orientation = m_deviceResources->GetOrientationTransform3D();
00129
00130         ConstantBufferChangeOnResize changesOnResize;
00131         XMStoreFloat4x4(
00132             &changesOnResize.projection,
00133             XMMatrixMultiply(
00134                 XMMatrixTranspose(m_game->GameCamera()->Projection()),
00135                 XMMatrixTranspose(XMLoadFloat4x4(&orientation))
00136                 )
00137             );
00138
00139         d3dContext->UpdateSubresource(
00140             m_constantBufferChangeOnResize.Get(),
00141             0,
00142             nullptr,
00143             &changesOnResize,
00144             0,
00145             0
00146             );
00147     }
00148 }
00149
00150 //----------------------------------------------------------------------
00151
00152 task<void> GameRenderer::CreateGameDeviceResourcesAsync(_In_ Simple3DGame^ game)
00153 {
00154     // Create the device dependent game resources.
00155     // Only the d3dDevice is used in this method.  It is expected
00156     // to not run on the same thread as the GameRenderer was created.
00157     // Create methods on the d3dDevice are free-threaded and are safe while any methods
00158     // in the d3dContext should only be used on a single thread and handled
00159     // in the FinalizeCreateGameDeviceResources method.
00160     m_game = game;
00161
00162     auto d3dDevice = m_deviceResources->GetD3DDevice();
00163
00164     D3D11_BUFFER_DESC bd;
00165     ZeroMemory(&bd, sizeof(bd));
00166
00167     // Create the constant buffers.
00168     bd.Usage = D3D11_USAGE_DEFAULT;
00169     bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
00170     bd.CPUAccessFlags = 0;
00171     bd.ByteWidth = (sizeof(ConstantBufferNeverChanges) + 15) / 16 * 16;
00172     DX::ThrowIfFailed(
00173         d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferNeverChanges)
00174         );
00175
00176     bd.ByteWidth = (sizeof(ConstantBufferChangeOnResize) + 15) / 16 * 16;
00177     DX::ThrowIfFailed(
00178         d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferChangeOnResize)
00179         );
00180
00181     bd.ByteWidth = (sizeof(ConstantBufferChangesEveryFrame) + 15) / 16 * 16;
00182     DX::ThrowIfFailed(
00183         d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferChangesEveryFrame)
00184         );
00185
00186     bd.ByteWidth = (sizeof(ConstantBufferChangesEveryPrim) + 15) / 16 * 16;
00187     DX::ThrowIfFailed(
00188         d3dDevice->CreateBuffer(&bd, nullptr, &m_constantBufferChangesEveryPrim)
00189         );
00190
00191     D3D11_SAMPLER_DESC sampDesc;
00192     ZeroMemory(&sampDesc, sizeof(sampDesc));
00193
00194     sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
00195     sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
00196     sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
00197     sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
00198     sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
00199     sampDesc.MinLOD = 0;
00200     sampDesc.MaxLOD = FLT_MAX;
00201     DX::ThrowIfFailed(
00202         d3dDevice->CreateSamplerState(&sampDesc, &m_samplerLinear)
00203         );
00204
00205     // Start the async tasks to load the shaders and textures.
00206     BasicLoader^ loader = ref new BasicLoader(d3dDevice);
00207
00208     std::vector<task<void>> tasks;
00209
00210     uint32 numElements = ARRAYSIZE(PNTVertexLayout);
00211     tasks.push_back(loader->LoadShaderAsync("VertexShader.cso", PNTVertexLayout, numElements, &m_vertexShader, &m_vertexLayout));
00212     tasks.push_back(loader->LoadShaderAsync("VertexShaderFlat.cso", nullptr, numElements, &m_vertexShaderFlat, nullptr));
00213     tasks.push_back(loader->LoadShaderAsync("PixelShader.cso", &m_pixelShader));
00214     tasks.push_back(loader->LoadShaderAsync("PixelShaderFlat.cso", &m_pixelShaderFlat));
00215
00216     // Make sure the previous versions if any of the textures are released.
00217     m_sphereTexture = nullptr;
00218     m_cylinderTexture = nullptr;
00219     m_ceilingTexture = nullptr;
00220     m_floorTexture = nullptr;
00221     m_wallsTexture = nullptr;
00222
00223     // Load Game specific textures.
00224     tasks.push_back(loader->LoadTextureAsync("Assets\\seafloor.dds", nullptr, &m_sphereTexture));
00225     tasks.push_back(loader->LoadTextureAsync("Assets\\metal_texture.dds", nullptr, &m_cylinderTexture));
00226     tasks.push_back(loader->LoadTextureAsync("Assets\\cellceiling.dds", nullptr, &m_ceilingTexture));
00227     tasks.push_back(loader->LoadTextureAsync("Assets\\cellfloor.dds", nullptr, &m_floorTexture));
00228     tasks.push_back(loader->LoadTextureAsync("Assets\\cellwall.dds", nullptr, &m_wallsTexture));
00229     tasks.push_back(create_task([]()
00230     {
00231         // Simulate loading additional resources by introducing a delay.
00232         wait(GameConstants::InitialLoadingDelay);
00233     }));
00234
00235     // Return the task group of all the async tasks for loading the shader and texture assets.
00236     return when_all(tasks.begin(), tasks.end());
00237 }
00238
00239 //----------------------------------------------------------------------
00240
00241 void GameRenderer::FinalizeCreateGameDeviceResources()
00242 {
00243     // All asynchronously loaded resources have completed loading.
00244     // Now associate all the resources with the appropriate game objects.
00245     // This method is expected to run in the same thread as the GameRenderer
00246     // was created. All work will happen behind the "Loading ..." screen after the
00247     // main loop has been entered.
00248
00249     // Initialize the Constant buffer with the light positions
00250     // These are handled here to ensure that the d3dContext is only
00251     // used in one thread.
00252
00253     auto d3dDevice = m_deviceResources->GetD3DDevice();
00254
00255     ConstantBufferNeverChanges constantBufferNeverChanges;
00256     constantBufferNeverChanges.lightPosition[0] = XMFLOAT4( 3.5f, 2.5f,  5.5f, 1.0f);
00257     constantBufferNeverChanges.lightPosition[1] = XMFLOAT4( 3.5f, 2.5f, -5.5f, 1.0f);
00258     constantBufferNeverChanges.lightPosition[2] = XMFLOAT4(-3.5f, 2.5f, -5.5f, 1.0f);
00259     constantBufferNeverChanges.lightPosition[3] = XMFLOAT4( 3.5f, 2.5f,  5.5f, 1.0f);
00260     constantBufferNeverChanges.lightColor = XMFLOAT4(0.25f, 0.25f, 0.25f, 1.0f);
00261     m_deviceResources->GetD3DDeviceContext()->UpdateSubresource(
00262         m_constantBufferNeverChanges.Get(),
00263         0,
00264         nullptr,
00265         &constantBufferNeverChanges,
00266         0,
00267         0
00268         );
00269
00270     // For the targets, there are two unique generated textures.
00271     // Each texture image includes the number of the texture.
00272     // Make sure the 2D rendering is occurring on the same thread
00273     // as the main rendering.
00274
00275     TargetTexture^ textureGenerator = ref new TargetTexture(
00276         d3dDevice,
00277         m_deviceResources->GetD2DFactory(),
00278         m_deviceResources->GetDWriteFactory(),
00279         m_deviceResources->GetD2DDeviceContext()
00280         );
00281
00282     MeshObject^ cylinderMesh = ref new CylinderMesh(d3dDevice, 26);
00283     MeshObject^ targetMesh = ref new FaceMesh(d3dDevice);
00284     MeshObject^ sphereMesh = ref new SphereMesh(d3dDevice, 26);
00285
00286     Material^ cylinderMaterial = ref new Material(
00287         XMFLOAT4(0.8f, 0.8f, 0.8f, .5f),
00288         XMFLOAT4(0.8f, 0.8f, 0.8f, .5f),
00289         XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f),
00290         15.0f,
00291         m_cylinderTexture.Get(),
00292         m_vertexShader.Get(),
00293         m_pixelShader.Get()
00294         );
00295
00296     Material^ sphereMaterial = ref new Material(
00297         XMFLOAT4(0.8f, 0.4f, 0.0f, 1.0f),
00298         XMFLOAT4(0.8f, 0.4f, 0.0f, 1.0f),
00299         XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f),
00300         50.0f,
00301         m_sphereTexture.Get(),
00302         m_vertexShader.Get(),
00303         m_pixelShader.Get()
00304         );
00305
00306     auto objects = m_game->RenderObjects();
00307
00308     // Attach the textures to the appropriate game objects.
00309     for (auto object = objects.begin(); object != objects.end(); object++)
00310     {
00311         if ((*object)->TargetId() == GameConstants::WorldFloorId)
00312         {
00313             (*object)->NormalMaterial(
00314                 ref new Material(
00315                     XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
00316                     XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
00317                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00318                     150.0f,
00319                     m_floorTexture.Get(),
00320                     m_vertexShaderFlat.Get(),
00321                     m_pixelShaderFlat.Get()
00322                     )
00323                 );
00324             (*object)->Mesh(ref new WorldFloorMesh(d3dDevice));
00325         }
00326         else if ((*object)->TargetId() == GameConstants::WorldCeilingId)
00327         {
00328             (*object)->NormalMaterial(
00329                 ref new Material(
00330                     XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
00331                     XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
00332                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00333                     150.0f,
00334                     m_ceilingTexture.Get(),
00335                     m_vertexShaderFlat.Get(),
00336                     m_pixelShaderFlat.Get()
00337                     )
00338                 );
00339             (*object)->Mesh(ref new WorldCeilingMesh(d3dDevice));
00340         }
00341         else if ((*object)->TargetId() == GameConstants::WorldWallsId)
00342         {
00343             (*object)->NormalMaterial(
00344                 ref new Material(
00345                     XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
00346                     XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
00347                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00348                     150.0f,
00349                     m_wallsTexture.Get(),
00350                     m_vertexShaderFlat.Get(),
00351                     m_pixelShaderFlat.Get()
00352                     )
00353                 );
00354             (*object)->Mesh(ref new WorldWallsMesh(d3dDevice));
00355         }
00356         else if (Cylinder^ cylinder = dynamic_cast<Cylinder^>(*object))
00357         {
00358             cylinder->Mesh(cylinderMesh);
00359             cylinder->NormalMaterial(cylinderMaterial);
00360         }
00361         else if (Face^ target = dynamic_cast<Face^>(*object))
00362         {
00363             const int bufferLength = 16;
00364             char16 str[bufferLength];
00365             int len = swprintf_s(str, bufferLength, L"%d", target->TargetId());
00366             Platform::String^ string = ref new Platform::String(str, len);
00367
00368             ComPtr<ID3D11ShaderResourceView> texture;
00369             textureGenerator->CreateTextureResourceView(string, &texture);
00370             target->NormalMaterial(
00371                 ref new Material(
00372                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00373                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00374                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00375                     5.0f,
00376                     texture.Get(),
00377                     m_vertexShader.Get(),
00378                     m_pixelShader.Get()
00379                     )
00380                 );
00381
00382             textureGenerator->CreateHitTextureResourceView(string, &texture);
00383             target->HitMaterial(
00384                 ref new Material(
00385                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00386                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00387                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00388                     5.0f,
00389                     texture.Get(),
00390                     m_vertexShader.Get(),
00391                     m_pixelShader.Get()
00392                     )
00393                 );
00394
00395             target->Mesh(targetMesh);
00396         }
00397         else if (Sphere^ sphere = dynamic_cast<Sphere^>(*object))
00398         {
00399             sphere->Mesh(sphereMesh);
00400             sphere->NormalMaterial(sphereMaterial);
00401         }
00402     }
00403
00404     // Ensure that the camera has been initialized with the right Projection
00405     // matrix.  The camera is not created at the time the first window resize event
00406     // occurs.
00407     auto renderTargetSize = m_deviceResources->GetRenderTargetSize();
00408     m_game->GameCamera()->SetProjParams(
00409         XM_PI / 2,
00410         renderTargetSize.Width / renderTargetSize.Height,
00411         0.01f,
00412         100.0f
00413         );
00414
00415     // Make sure that Projection matrix has been set in the constant buffer
00416     // now that all the resources are loaded.
00417     // We are handling screen rotations directly to eliminate an unaligned
00418     // fullscreen copy.  As a result, it is necessary to post multiply the rotationTransform3D
00419     // matrix to the camera projection matrix.
00420     // The matrices are transposed due to the shader code expecting the matrices in the opposite
00421     // row/column order from the DirectX math library.
00422
00423     auto orientation = m_deviceResources->GetOrientationTransform3D();
00424
00425     ConstantBufferChangeOnResize changesOnResize;
00426     XMStoreFloat4x4(
00427         &changesOnResize.projection,
00428         XMMatrixMultiply(
00429             XMMatrixTranspose(m_game->GameCamera()->Projection()),
00430             XMMatrixTranspose(XMLoadFloat4x4(&orientation))
00431             )
00432         );
00433
00434     m_deviceResources->GetD3DDeviceContext()->UpdateSubresource(
00435         m_constantBufferChangeOnResize.Get(),
00436         0,
00437         nullptr,
00438         &changesOnResize,
00439         0,
00440         0
00441         );
00442
00443     m_gameResourcesLoaded = true;
00444 }
00445
00446 //----------------------------------------------------------------------
00447
00448 task<void> GameRenderer::LoadLevelResourcesAsync()
00449 {
00450     m_levelResourcesLoaded = false;
00451
00452     return create_task([this]()
00453     {
00454         // This is where additional async loading of level specific resources
00455         // would be done.  Since there aren't any to load, just simulate
00456         // by delaying for some time.
00457         wait(GameConstants::LevelLoadingDelay);
00458     });
00459 }
00460
00461 //----------------------------------------------------------------------
00462
00463 void GameRenderer::FinalizeLoadLevelResources()
00464 {
00465     // Once the level specific resources had been loaded, this method is
00466     // where D3D context specific actions would be handled.  This method
00467     // runs in the same thread context as the GameRenderer was created.
00468
00469     m_levelResourcesLoaded = true;
00470 }
00471
00472 //----------------------------------------------------------------------
00473
00474 void GameRenderer::Render()
00475 {
00476     bool stereoEnabled = m_deviceResources->GetStereoState();
00477
00478     auto d3dContext = m_deviceResources->GetD3DDeviceContext();
00479     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00480
00481     int renderingPasses = 1;
00482     if (stereoEnabled)
00483     {
00484         renderingPasses = 2;
00485     }
00486
00487     for (int i = 0; i < renderingPasses; i++)
00488     {
00489         // Iterate through the number of rendering passes to be completed.
00490         if (i > 0)
00491         {
00492             // Doing the Right Eye View.
00493             ID3D11RenderTargetView *const targets[1] = { m_deviceResources->GetBackBufferRenderTargetViewRight() };
00494
00495             d3dContext->OMSetRenderTargets(1, targets, m_deviceResources->GetDepthStencilView());
00496             d3dContext->ClearDepthStencilView(m_deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH, 1.0f, 0);
00497             d2dContext->SetTarget(m_deviceResources->GetD2DTargetBitmapRight());
00498         }
00499         else
00500         {
00501             // Doing the Mono or Left Eye View.
00502             ID3D11RenderTargetView *const targets[1] = { m_deviceResources->GetBackBufferRenderTargetView() };
00503
00504             d3dContext->OMSetRenderTargets(1, targets, m_deviceResources->GetDepthStencilView());
00505             d3dContext->ClearDepthStencilView(m_deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH, 1.0f, 0);
00506             d2dContext->SetTarget(m_deviceResources->GetD2DTargetBitmap());
00507         }
00508
00509         if (m_game != nullptr && m_gameResourcesLoaded && m_levelResourcesLoaded)
00510         {
00511             // This section is only used after the game state has been initialized and all device
00512             // resources needed for the game have been created and associated with the game objects.
00513             if (stereoEnabled)
00514             {
00515                 // When doing stereo, it is necessary to update the projection matrix once per rendering pass.
00516
00517                 auto orientation = m_deviceResources->GetOrientationTransform3D();
00518
00519                 ConstantBufferChangeOnResize changesOnResize;
00520                 XMStoreFloat4x4(
00521                     &changesOnResize.projection,
00522                     XMMatrixMultiply(
00523                         XMMatrixTranspose(
00524                             i == 0 ?
00525                             m_game->GameCamera()->LeftEyeProjection() :
00526                             m_game->GameCamera()->RightEyeProjection()
00527                             ),
00528                         XMMatrixTranspose(XMLoadFloat4x4(&orientation))
00529                         )
00530                     );
00531
00532                 d3dContext->UpdateSubresource(
00533                     m_constantBufferChangeOnResize.Get(),
00534                     0,
00535                     nullptr,
00536                     &changesOnResize,
00537                     0,
00538                     0
00539                     );
00540             }
00541             // Update variables that change once per frame.
00542
00543             ConstantBufferChangesEveryFrame constantBufferChangesEveryFrame;
00544             XMStoreFloat4x4(
00545                 &constantBufferChangesEveryFrame.view,
00546                 XMMatrixTranspose(m_game->GameCamera()->View())
00547                 );
00548             d3dContext->UpdateSubresource(
00549                 m_constantBufferChangesEveryFrame.Get(),
00550                 0,
00551                 nullptr,
00552                 &constantBufferChangesEveryFrame,
00553                 0,
00554                 0
00555                 );
00556
00557             // Setup the graphics pipeline. This sample uses the same InputLayout and set of
00558             // constant buffers for all shaders, so they only need to be set once per frame.
00559
00560             d3dContext->IASetInputLayout(m_vertexLayout.Get());
00561             d3dContext->VSSetConstantBuffers(0, 1, m_constantBufferNeverChanges.GetAddressOf());
00562             d3dContext->VSSetConstantBuffers(1, 1, m_constantBufferChangeOnResize.GetAddressOf());
00563             d3dContext->VSSetConstantBuffers(2, 1, m_constantBufferChangesEveryFrame.GetAddressOf());
00564             d3dContext->VSSetConstantBuffers(3, 1, m_constantBufferChangesEveryPrim.GetAddressOf());
00565
00566             d3dContext->PSSetConstantBuffers(2, 1, m_constantBufferChangesEveryFrame.GetAddressOf());
00567             d3dContext->PSSetConstantBuffers(3, 1, m_constantBufferChangesEveryPrim.GetAddressOf());
00568             d3dContext->PSSetSamplers(0, 1, m_samplerLinear.GetAddressOf());
00569
00570             auto objects = m_game->RenderObjects();
00571             for (auto object = objects.begin(); object != objects.end(); object++)
00572             {
00573                 (*object)->Render(d3dContext, m_constantBufferChangesEveryPrim.Get());
00574             }
00575         }
00576         else
00577         {
00578             const float ClearColor[4] = {0.5f, 0.5f, 0.8f, 1.0f};
00579
00580             // Only need to clear the background when not rendering the full 3D scene since
00581             // the 3D world is a fully enclosed box and the dynamics prevents the camera from
00582             // moving outside this space.
00583             if (i > 0)
00584             {
00585                 // Doing the Right Eye View.
00586                 d3dContext->ClearRenderTargetView(m_deviceResources->GetBackBufferRenderTargetViewRight(), ClearColor);
00587             }
00588             else
00589             {
00590                 // Doing the Mono or Left Eye View.
00591                 d3dContext->ClearRenderTargetView(m_deviceResources->GetBackBufferRenderTargetView(), ClearColor);
00592             }
00593         }
00594
00595         d3dContext->BeginEventInt(L"D2D BeginDraw", 1);
00596         d2dContext->BeginDraw();
00597
00598         // To handle the swapchain being pre-rotated, set the D2D transformation to include it.
00599         d2dContext->SetTransform(m_deviceResources->GetOrientationTransform2D());
00600
00601         if (m_game != nullptr && m_gameResourcesLoaded)
00602         {
00603             // This is only used after the game state has been initialized.
00604             m_gameHud->Render(m_game);
00605         }
00606
00607         if (m_gameInfoOverlay->Visible())
00608         {
00609             d2dContext->DrawBitmap(
00610                 m_gameInfoOverlay->Bitmap(),
00611                 m_gameInfoOverlayRect
00612                 );
00613         }
00614
00615         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00616         // is lost. It will be handled during the next call to Present.
00617         HRESULT hr = d2dContext->EndDraw();
00618         d3dContext->EndEvent();
00619         if (hr != D2DERR_RECREATE_TARGET)
00620         {
00621             DX::ThrowIfFailed(hr);
00622         }
00623     }
00624 }
00625
00626 //----------------------------------------------------------------------
00627
00628 #if defined(_DEBUG)
00629 void GameRenderer::ReportLiveDeviceObjects()
00630 {
00631     // If the debug layer isn't present on the system then this QI will fail.  In that case
00632     // the routine just exits.   This is a debugging aid to see the active D3D objects and
00633     // is not critical to functional operation of the sample.
00634
00635     ComPtr<ID3D11Debug> debugLayer;
00636     ComPtr<ID3D11Device2>d3dDevice = m_deviceResources->GetD3DDevice();
00637     HRESULT hr = d3dDevice.As(&debugLayer);
00638     if (FAILED(hr))
00639     {
00640         return;
00641     }
00642     DX::ThrowIfFailed(
00643         debugLayer->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL)
00644         );
00645 }
00646
00647 //----------------------------------------------------------------------
00648
00649 #endif
00650
Generated on Fri Nov 15 2024 22:21:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicInput/cpp/3-DeviceCapabilities.xaml.h Source File

  • BasicInput
  • cpp

3-DeviceCapabilities.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "3-DeviceCapabilities.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario3 sealed
00024     {
00025     public:
00026         Scenario3();
00027
00028     private:
00029         MainPage^ rootPage = MainPage::Current;
00030     };
00031 }
Generated on Fri Nov 15 2024 22:18:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothAdvertisement/cs/Tasks/AdvertisementBackgroundTasks.cs Source File

  • BluetoothAdvertisement
  • cs
  • Tasks

AdvertisementBackgroundTasks.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Text;
00015 using System.Threading;
00016 using System.Threading.Tasks;
00017 using Windows.ApplicationModel.Background;
00018 using Windows.Devices.Bluetooth;
00019 using Windows.Devices.Bluetooth.Background;
00020 using Windows.Devices.Bluetooth.Advertisement;
00021 using Windows.Storage;
00022 using Windows.Storage.Streams;
00023
00024 namespace BackgroundTasks
00025 {
00026     // A background task always implements the IBackgroundTask interface.
00027     public sealed class AdvertisementWatcherTask : IBackgroundTask
00028     {
00029         private IBackgroundTaskInstance backgroundTaskInstance;
00030
00031         /// <summary>
00032         /// The entry point of a background task.
00033         /// </summary>
00034         /// <param name="taskInstance">The current background task instance.</param>
00035         public void Run(IBackgroundTaskInstance taskInstance)
00036         {
00037             backgroundTaskInstance = taskInstance;
00038
00039             var details = taskInstance.TriggerDetails as BluetoothLEAdvertisementWatcherTriggerDetails;
00040
00041             if (details != null)
00042             {
00043                 // If the background watcher stopped unexpectedly, an error will be available here.
00044                 var error = details.Error;
00045
00046                 // The Advertisements property is a list of all advertisement events received
00047                 // since the last task triggered. The list of advertisements here might be valid even if
00048                 // the Error status is not Success since advertisements are stored until this task is triggered
00049                 IReadOnlyList<BluetoothLEAdvertisementReceivedEventArgs> advertisements = details.Advertisements;
00050
00051                 // The signal strength filter configuration of the trigger is returned such that further
00052                 // processing can be performed here using these values if necessary. They are read-only here.
00053                 var rssiFilter = details.SignalStrengthFilter;
00054
00055                 // In this example, the background task simply constructs a message communicated
00056                 // to the App. For more interesting applications, a notification can be sent from here instead.
00057                 string eventMessage = "";
00058                 eventMessage += string.Format("ErrorStatus: {0}, EventCount: {1}, HighDBm: {2}, LowDBm: {3}, Timeout: {4}, Sampling: {5}",
00059                     error.ToString(),
00060                     advertisements.Count.ToString(),
00061                     rssiFilter.InRangeThresholdInDBm.ToString(),
00062                     rssiFilter.OutOfRangeThresholdInDBm.ToString(),
00063                     rssiFilter.OutOfRangeTimeout.GetValueOrDefault().TotalMilliseconds.ToString(),
00064                     rssiFilter.SamplingInterval.GetValueOrDefault().TotalMilliseconds.ToString());
00065
00066                 // Advertisements can contain multiple events that were aggregated, each represented by
00067                 // a BluetoothLEAdvertisementReceivedEventArgs object.
00068                 foreach (var eventArgs in advertisements)
00069                 {
00070                     // Check if there are any manufacturer-specific sections.
00071                     // If there is, print the raw data of the first manufacturer section (if there are multiple).
00072                     string manufacturerDataString = "";
00073                     var manufacturerSections = eventArgs.Advertisement.ManufacturerData;
00074                     if (manufacturerSections.Count > 0)
00075                     {
00076                         var manufacturerData = manufacturerSections[0];
00077                         var data = new byte[manufacturerData.Data.Length];
00078                         using (var reader = DataReader.FromBuffer(manufacturerData.Data))
00079                         {
00080                             reader.ReadBytes(data);
00081                         }
00082                         // Print the company ID + the raw data in hex format.
00083                         manufacturerDataString = string.Format("0x{0}: {1}",
00084                             manufacturerData.CompanyId.ToString("X"),
00085                             BitConverter.ToString(data));
00086                     }
00087                     eventMessage += string.Format("\n[{0}] [{1}]: Rssi={2}dBm, localName={3}, manufacturerData=[{4}]",
00088                         eventArgs.Timestamp.ToString("hh\\:mm\\:ss\\.fff"),
00089                         eventArgs.AdvertisementType.ToString(),
00090                         eventArgs.RawSignalStrengthInDBm.ToString(),
00091                         eventArgs.Advertisement.LocalName,
00092                         manufacturerDataString);
00093                 }
00094
00095                 // Store the message in a local settings indexed by this task's name so that the foreground App
00096                 // can display this message.
00097                 ApplicationData.Current.LocalSettings.Values[taskInstance.Task.Name] = eventMessage;
00098             }
00099         }
00100     }
00101
00102     // A background task always implements the IBackgroundTask interface.
00103     public sealed class AdvertisementPublisherTask : IBackgroundTask
00104     {
00105         private IBackgroundTaskInstance backgroundTaskInstance;
00106
00107         /// <summary>
00108         /// The entry point of a background task.
00109         /// </summary>
00110         /// <param name="taskInstance">The current background task instance.</param>
00111         public void Run(IBackgroundTaskInstance taskInstance)
00112         {
00113             backgroundTaskInstance = taskInstance;
00114
00115             var details = taskInstance.TriggerDetails as BluetoothLEAdvertisementPublisherTriggerDetails;
00116
00117             if (details != null)
00118             {
00119                 // If the background publisher stopped unexpectedly, an error will be available here.
00120                 var error = details.Error;
00121
00122                 // The status of the publisher is useful to determine whether the advertisement payload is being serviced
00123                 // It is possible for a publisher to stay in a Waiting state while radio resources are in use.
00124                 var status = details.Status;
00125
00126                 // In this example, the background task simply constructs a message communicated
00127                 // to the App. For more interesting applications, a notification can be sent from here instead.
00128                 string eventMessage = "";
00129                 eventMessage += string.Format("Publisher Status: {0}, Error: {1}",
00130                     status.ToString(),
00131                     error.ToString());
00132
00133                 // Store the message in a local settings indexed by this task's name so that the foreground App
00134                 // can display this message.
00135                 ApplicationData.Current.LocalSettings.Values[taskInstance.Task.Name] = eventMessage;
00136             }
00137         }
00138     }
00139 }
Generated on Fri Nov 15 2024 22:18:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_ShowView Member List

This is the complete list of members for Scenario4_ShowView, including all inherited members.
rootPage | Scenario4_ShowView | [private]
Scenario4_ShowView() | Scenario4_ShowView | [inline]
TextBox_GotFocus(object sender, RoutedEventArgs e) | Scenario4_ShowView | [inline, private]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CashDrawer/cs/Scenario2_CloseDrawer.xaml.cs Source File

  • CashDrawer
  • cs

Scenario2_CloseDrawer.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Devices.PointOfService;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026     public sealed partial class Scenario2_CloseDrawer : Page
00027     {
00028         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00029         // as NotifyUser()
00030         MainPage rootPage = MainPage.Current;
00031
00032         CashDrawer drawer = null;
00033         ClaimedCashDrawer claimedDrawer = null;
00034
00035
00036         public Scenario2_CloseDrawer()
00037         {
00038             this.InitializeComponent();
00039         }
00040
00041         /// <summary>
00042         /// Invoked when this page is about to be displayed in a Frame.
00043         /// </summary>
00044         /// <param name="e">Event data that describes how this page was reached.</param>
00045         protected override void OnNavigatedTo(NavigationEventArgs e)
00046         {
00047             ResetScenarioState();
00048             base.OnNavigatedTo(e);
00049         }
00050
00051         /// <summary>
00052         /// Invoked before the page is unloaded and is no longer the current source of a Frame.
00053         /// </summary>
00054         /// <param name="e">Event data describing the navigation that was requested.</param>
00055         protected override void OnNavigatedFrom(NavigationEventArgs e)
00056         {
00057             ResetScenarioState();
00058             base.OnNavigatedFrom(e);
00059         }
00060
00061         /// <summary>
00062         /// Event handler for Initialize Drawer button.
00063         /// Claims and enables the default cash drawer.
00064         /// </summary>
00065         /// <param name="sender">Button that was clicked.</param>
00066         /// <param name="e">Event data associated with click event.</param>
00067         private async void InitDrawerButton_Click(object sender, RoutedEventArgs e)
00068         {
00069             if (await CreateDefaultCashDrawerObject())
00070             {
00071                 if (await ClaimCashDrawer())
00072                 {
00073                     if (await EnableCashDrawer())
00074                     {
00075                         drawer.StatusUpdated += drawer_StatusUpdated;
00076
00077                         InitDrawerButton.IsEnabled = false;
00078                         DrawerWaitButton.IsEnabled = true;
00079
00080                         UpdateStatusOutput(drawer.Status.StatusKind);
00081                         rootPage.NotifyUser("Successfully enabled cash drawer. Device ID: " + claimedDrawer.DeviceId, NotifyType.StatusMessage);
00082                     }
00083                     else
00084                     {
00085                         rootPage.NotifyUser("Failed to enable cash drawer.", NotifyType.ErrorMessage);
00086                     }
00087                 }
00088                 else
00089                 {
00090                     rootPage.NotifyUser("Failed to claim cash drawer.", NotifyType.ErrorMessage);
00091                 }
00092             }
00093             else
00094             {
00095                 rootPage.NotifyUser("Cash drawer not found. Please connect a cash drawer.", NotifyType.ErrorMessage);
00096             }
00097         }
00098
00099         /// <summary>
00100         /// Set up an alarm and wait for the drawer to close.
00101         /// </summary>
00102         /// <param name="sender">Button that was clicked.</param>
00103         /// <param name="e">Event data associated with click event.</param>
00104         private async void WaitForDrawerCloseButton_Click(object sender, RoutedEventArgs e)
00105         {
00106             if (claimedDrawer == null)
00107             {
00108                 rootPage.NotifyUser("Drawer must be initialized.", NotifyType.ErrorMessage);
00109                 return;
00110             }
00111
00112             var alarm = claimedDrawer.CloseAlarm;
00113             if (alarm == null)
00114             {
00115                 rootPage.NotifyUser("Failed to create drawer alarm.", NotifyType.ErrorMessage);
00116                 return;
00117             }
00118
00119             if (!claimedDrawer.IsDrawerOpen)
00120             {
00121                 rootPage.NotifyUser("Drawer is already closed.", NotifyType.StatusMessage);
00122             }
00123             else
00124             {
00125                 // TimeSpan specifies a time period as (hours, minutes, seconds)
00126                 alarm.AlarmTimeout = new TimeSpan(0, 0, 30);
00127                 alarm.BeepDelay = new TimeSpan(0, 0, 3);
00128                 alarm.BeepDuration = new TimeSpan(0, 0, 1);
00129                 alarm.BeepFrequency = 700;
00130                 alarm.AlarmTimeoutExpired += drawer_AlarmExpired;
00131
00132                 rootPage.NotifyUser("Waiting for drawer to close.", NotifyType.StatusMessage);
00133
00134                 if (await alarm.StartAsync())
00135                     rootPage.NotifyUser("Successfully waited for drawer close.", NotifyType.StatusMessage);
00136                 else
00137                     rootPage.NotifyUser("Failed to wait for drawer close.", NotifyType.ErrorMessage);
00138             }
00139         }
00140
00141         /// <summary>
00142         /// Creates the default cash drawer.
00143         /// </summary>
00144         /// <returns>True if the cash drawer was created, false otherwise.</returns>
00145         private async Task<bool> CreateDefaultCashDrawerObject()
00146         {
00147             rootPage.NotifyUser("Creating cash drawer object.", NotifyType.StatusMessage);
00148
00149             if (drawer == null)
00150             {
00151                 drawer = await DeviceHelpers.GetFirstCashDrawerAsync();
00152                 if (drawer == null)
00153                     return false;
00154             }
00155
00156             return true;
00157         }
00158
00159         /// <summary>
00160         /// Attempt to claim the connected cash drawer.
00161         /// </summary>
00162         /// <returns>True if the cash drawer was successfully claimed, false otherwise.</returns>
00163         private async Task<bool> ClaimCashDrawer()
00164         {
00165             if (drawer == null)
00166                 return false;
00167
00168             if (claimedDrawer == null)
00169             {
00170                 claimedDrawer = await drawer.ClaimDrawerAsync();
00171                 if (claimedDrawer == null)
00172                     return false;
00173             }
00174
00175             return true;
00176         }
00177
00178         /// <summary>
00179         /// Attempt to enabled the claimed cash drawer.
00180         /// </summary>
00181         /// <returns>True if the cash drawer was successfully enabled, false otherwise.</returns>
00182         private async Task<bool> EnableCashDrawer()
00183         {
00184             if (claimedDrawer == null)
00185                 return false;
00186
00187             if (claimedDrawer.IsEnabled)
00188                 return true;
00189
00190             return await claimedDrawer.EnableAsync();
00191         }
00192
00193         /// <summary>
00194         /// Event callback for device status updates.
00195         /// </summary>
00196         /// <param name="drawer">CashDrawer object sending the status update event.</param>
00197         /// <param name="e">Event data associated with the status update.</param>
00198         private async void drawer_StatusUpdated(CashDrawer drawer, CashDrawerStatusUpdatedEventArgs e)
00199         {
00200             await MainPage.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00201             {
00202                 UpdateStatusOutput(e.Status.StatusKind);
00203                 rootPage.NotifyUser("Status updated event: " + e.Status.StatusKind.ToString(), NotifyType.StatusMessage);
00204             });
00205         }
00206
00207         /// <summary>
00208         /// Event callback for the alarm expiring.
00209         /// </summary>
00210         /// <param name="alarm">CashDrawerCloseAlarm that has expired.</param>
00211         /// <param name="sender">Unused by AlarmTimeoutExpired events.</param>
00212         private async void drawer_AlarmExpired(CashDrawerCloseAlarm alarm, object sender)
00213         {
00214             await MainPage.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00215             {
00216                 rootPage.NotifyUser("Alarm expired.  Still waiting for drawer to be closed.", NotifyType.StatusMessage);
00217             });
00218         }
00219
00220         /// <summary>
00221         /// Reset the scenario to its initial state.
00222         /// </summary>
00223         private void ResetScenarioState()
00224         {
00225             if (claimedDrawer != null)
00226             {
00227                 claimedDrawer.Dispose();
00228                 claimedDrawer = null;
00229             }
00230
00231             if (drawer != null)
00232             {
00233                 drawer.Dispose();
00234                 drawer = null;
00235             }
00236
00237             UpdateStatusOutput(CashDrawerStatusKind.Offline);
00238
00239             InitDrawerButton.IsEnabled = true;
00240             DrawerWaitButton.IsEnabled = false;
00241
00242             rootPage.NotifyUser("Click the init drawer button to begin.", NotifyType.StatusMessage);
00243         }
00244
00245         /// <summary>
00246         /// Update the cash drawer text block.
00247         /// </summary>
00248         /// <param name="status">Cash drawer status to be displayed.</param>
00249         private void UpdateStatusOutput(CashDrawerStatusKind status)
00250         {
00251             DrawerStatusBlock.Text = status.ToString();
00252         }
00253     }
00254 }
Generated on Fri Nov 15 2024 22:18:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_PhotoSettings Member List

This is the complete list of members for Scenario2_PhotoSettings, including all inherited members.
_captureFolder | Scenario2_PhotoSettings | [private]
_previewer | Scenario2_PhotoSettings | [private]
CheckIfStreamsAreIdentical() | Scenario2_PhotoSettings | [inline]
InitializeCameraButton_Click(object sender, RoutedEventArgs e) | Scenario2_PhotoSettings | [inline, private]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario2_PhotoSettings | [inline, protected]
PhotoButton_Click(object sender, RoutedEventArgs e) | Scenario2_PhotoSettings | [inline, private]
PhotoSettings_Changed(object sender, RoutedEventArgs e) | Scenario2_PhotoSettings | [inline, private]
PopulateComboBox(MediaStreamType streamType, ComboBox comboBox, bool showFrameRate=true) | Scenario2_PhotoSettings | [inline, private]
PreviewSettings_Changed(object sender, RoutedEventArgs e) | Scenario2_PhotoSettings | [inline, private]
rootPage | Scenario2_PhotoSettings | [private]
Scenario2_PhotoSettings() | Scenario2_PhotoSettings | [inline]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cpp/App.xaml.cpp Source File

  • XamlCommanding
  • cpp

App.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::ApplicationModel::Activation;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Controls::Primitives;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::UI::Xaml::Input;
00027 using namespace Windows::UI::Xaml::Interop;
00028 using namespace Windows::UI::Xaml::Media;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
00032
00033 /// <summary>
00034 /// Initializes the singleton application object.  This is the first line of authored code
00035 /// executed, and as such is the logical equivalent of main() or WinMain().
00036 /// </summary>
00037 App::App()
00038 {
00039     InitializeComponent();
00040     Suspending += ref new Windows::UI::Xaml::SuspendingEventHandler(this, &SDKTemplate::App::OnSuspending);
00041 }
00042
00043 /// <summary>
00044 /// Invoked when the application is launched normally by the end user.  Other entry points
00045 /// will be used such as when the application is launched to open a specific file.
00046 /// </summary>
00047 /// <param name="e">Details about the launch request and process.</param>
00048 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
00049 {
00050 #if _DEBUG
00051     // Show graphics profiling information while debugging.
00052     if (IsDebuggerPresent())
00053     {
00054         // Display the current frame rate counters
00055         DebugSettings->EnableFrameRateCounter = false;
00056     }
00057 #endif
00058
00059     auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00060
00061     // Do not repeat app initialization when the Window already has content,
00062     // just ensure that the window is active
00063     if (rootFrame == nullptr)
00064     {
00065         // Create a Frame to act as the navigation context and associate it with
00066         // a SuspensionManager key
00067         rootFrame = ref new Frame();
00068
00069         // Set the default language
00070         rootFrame->Language = Windows::Globalization::ApplicationLanguages::Languages->GetAt(0);
00071
00072         rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed);
00073
00074         if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
00075         {
00076             // TODO: Restore the saved session state only when appropriate, scheduling the
00077             // final launch steps after the restore is complete
00078         }
00079
00080         if (rootFrame->Content == nullptr)
00081         {
00082             // When the navigation stack isn't restored navigate to the first page,
00083             // configuring the new page by passing required information as a navigation
00084             // parameter
00085             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00086         }
00087         // Place the frame in the current Window
00088         Window::Current->Content = rootFrame;
00089         // Ensure the current window is active
00090         Window::Current->Activate();
00091     }
00092     else
00093     {
00094         if (rootFrame->Content == nullptr)
00095         {
00096             // When the navigation stack isn't restored navigate to the first page,
00097             // configuring the new page by passing required information as a navigation
00098             // parameter
00099             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00100         }
00101         // Ensure the current window is active
00102         Window::Current->Activate();
00103     }
00104 }
00105
00106 /// <summary>
00107 /// Invoked when application execution is being suspended.  Application state is saved
00108 /// without knowing whether the application will be terminated or resumed with the contents
00109 /// of memory still intact.
00110 /// </summary>
00111 /// <param name="sender">The source of the suspend request.</param>
00112 /// <param name="e">Details about the suspend request.</param>
00113 void App::OnSuspending(Object^ /* sender */, SuspendingEventArgs^ /* e */)
00114 {
00115     //TODO: Save application state and stop any background activity
00116 }
00117
00118
00119 /// <summary>
00120 /// Invoked when Navigation to a certain page fails
00121 /// </summary>
00122 /// <param name="sender">The Frame which failed navigation</param>
00123 /// <param name="e">Details about the navigation failure</param>
00124 void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e)
00125 {
00126     throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name);
00127 }
Generated on Fri Nov 15 2024 22:16:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/SampleConfiguration.cpp Source File

  • FileAccess
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace concurrency;
00010 using namespace Platform;
00011 using namespace Windows::Security::Cryptography;
00012 using namespace Windows::Storage;
00013 using namespace Windows::Storage::Streams;
00014
00015 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00016 {
00017     { "Creating a file",                                      "SDKTemplate.Scenario1" },
00018     { "Getting a file's parent folder",                       "SDKTemplate.Scenario2" },
00019     { "Writing and reading text in a file",                   "SDKTemplate.Scenario3" },
00020     { "Writing and reading bytes in a file",                  "SDKTemplate.Scenario4" },
00021     { "Writing and reading using a stream",                   "SDKTemplate.Scenario5" },
00022     { "Displaying file properties",                           "SDKTemplate.Scenario6" },
00023     { "Persisting access to a storage item for future use",   "SDKTemplate.Scenario7" },
00024     { "Copying a file",                                       "SDKTemplate.Scenario8" },
00025     { "Comparing two files to see if they are the same file", "SDKTemplate.Scenario9" },
00026     { "Deleting a file",                                      "SDKTemplate.Scenario10" },
00027     { "Attempting to get a file with no error on failure",    "SDKTemplate.Scenario11" },
00028 };
00029
00030 void MainPage::ValidateFile()
00031 {
00032     create_task(KnownFolders::GetFolderForUserAsync(nullptr /* current user */, KnownFolderId::PicturesLibrary)).then([this](StorageFolder^ picturesFolder)
00033     {
00034         return picturesFolder->TryGetItemAsync(Filename);
00035     }).then([this](IStorageItem^ item)
00036     {
00037         sampleFile = safe_cast<StorageFile^>(item);
00038         if (item == nullptr)
00039         {
00040             // If file doesn't exist, indicate users to use scenario 1
00041             NotifyUserFileNotExist();
00042         }
00043     });
00044 }
00045
00046 void MainPage::NotifyUserFileNotExist()
00047 {
00048     NotifyUser("The file '" + Filename + "' does not exist. Use scenario one to create this file.", NotifyType::ErrorMessage);
00049 }
00050
00051 // I/O errors are reported as exceptions.
00052 void MainPage::HandleIoException(Platform::COMException^ e, Platform::String^ description)
00053 {
00054     if (e->HResult == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
00055     {
00056         NotifyUserFileNotExist();
00057     }
00058     else if (e->HResult == HRESULT_FROM_WIN32(ERROR_NO_UNICODE_TRANSLATION))
00059     {
00060         NotifyUser("File is not UTF-8 encoded.", NotifyType::ErrorMessage);
00061     }
00062     else
00063     {
00064         NotifyUser(description + ": " + e->Message, NotifyType::ErrorMessage);
00065     }
00066 }
00067
00068 IBuffer^ MainPage::GetBufferFromString(String^ string)
00069 {
00070     if (string->IsEmpty())
00071     {
00072         return ref new Buffer(0);
00073     }
00074     else
00075     {
00076         return CryptographicBuffer::ConvertStringToBinary(string, BinaryStringEncoding::Utf8);
00077     }
00078 }
00079
00080 String^ MainPage::GetStringFromBuffer(IBuffer^ buffer)
00081 {
00082     // Throws HRESULT_FROM_WIN32(ERROR_NO_UNICODE_TRANSLATION)
00083     // if the buffer is not properly encoded.
00084     return CryptographicBuffer::ConvertBinaryToString(BinaryStringEncoding::Utf8, buffer);
00085 }
Generated on Fri Nov 15 2024 22:17:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cpp/Scenario1_SampleBackgroundTask.xaml.cpp Source File

  • BackgroundActivation
  • cpp

Scenario1_SampleBackgroundTask.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario1_SampleBackgroundTask.xaml.cpp
00013 // Implementation of the SampleBackgroundTask class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario1_SampleBackgroundTask.xaml.h"
00018 #include "SampleConfiguration.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::ApplicationModel::Background;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 SampleBackgroundTask::SampleBackgroundTask()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Invoked when this page is about to be displayed in a Frame.
00035 /// </summary>
00036 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037 /// property is typically used to configure the page.</param>
00038 void SampleBackgroundTask::OnNavigatedTo(NavigationEventArgs^ e)
00039 {
00040     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00041     // as NotifyUser()
00042     rootPage = MainPage::Current;
00043
00044     //
00045     // Attach progress and completed handlers to any existing tasks.
00046     //
00047     for (auto pair : BackgroundTaskRegistration::AllTasks)
00048     {
00049         auto task = pair->Value;
00050         if (task->Name == SampleBackgroundTaskName)
00051         {
00052             BackgroundTaskSample::UpdateBackgroundTaskRegistrationStatus(task->Name, true);
00053             AttachProgressAndCompletedHandlers(task);
00054             break;
00055         }
00056     }
00057
00058     UpdateUI();
00059 }
00060
00061 /// <summary>
00062 /// Attach progress and completed handers to a background task.
00063 /// </summary>
00064 /// <param name="task">The task to attach progress and completed handlers to.</param>
00065 void SampleBackgroundTask::AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration^ task)
00066 {
00067     task->Progress += ref new BackgroundTaskProgressEventHandler(this, &SampleBackgroundTask::OnProgress);
00068     task->Completed += ref new BackgroundTaskCompletedEventHandler(this, &SampleBackgroundTask::OnCompleted);
00069 }
00070
00071 /// <summary>
00072 /// Register a SampleBackgroundTask.
00073 /// </summary>
00074 /// <param name="sender"></param>
00075 /// <param name="e"></param>
00076 void SampleBackgroundTask::RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00077 {
00078     auto task = BackgroundTaskSample::RegisterBackgroundTask(nullptr,
00079                                                              SampleBackgroundTaskName,
00080                                                              ref new SystemTrigger(SystemTriggerType::TimeZoneChange, false),
00081                                                              nullptr);
00082     AttachProgressAndCompletedHandlers(task);
00083     UpdateUI();
00084 }
00085
00086 /// <summary>
00087 /// Unregister a SampleBackgroundTask.
00088 /// </summary>
00089 /// <param name="sender"></param>
00090 /// <param name="e"></param>
00091 void SampleBackgroundTask::UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00092 {
00093     BackgroundTaskSample::UnregisterBackgroundTasks(SampleBackgroundTaskName);
00094     UpdateUI();
00095 }
00096
00097 /// <summary>
00098 /// Handle background task progress.
00099 /// </summary>
00100 /// <param name="task">The task that is reporting progress.</param>
00101 /// <param name="args">Arguments of the progress report.</param>
00102 void SampleBackgroundTask::OnProgress(BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
00103 {
00104     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00105     {
00106         auto progress = "Progress: " + args->Progress + "%";
00107         BackgroundTaskSample::SampleBackgroundTaskProgress = progress;
00108         UpdateUI();
00109     }));
00110 }
00111
00112 /// <summary>
00113 /// Handle background task completion.
00114 /// </summary>
00115 /// <param name="task">The task that is reporting completion.</param>
00116 /// <param name="args">Arguments of the completion report.</param>
00117 void SampleBackgroundTask::OnCompleted(BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
00118 {
00119     UpdateUI();
00120 }
00121
00122 /// <summary>
00123 /// Update the scenario UI.
00124 /// </summary>
00125 void SampleBackgroundTask::UpdateUI()
00126 {
00127     auto uiDelegate = [this]()
00128     {
00129         RegisterButton->IsEnabled = !BackgroundTaskSample::SampleBackgroundTaskRegistered;
00130         UnregisterButton->IsEnabled = BackgroundTaskSample::SampleBackgroundTaskRegistered;
00131         Progress->Text = BackgroundTaskSample::SampleBackgroundTaskProgress;
00132         Status->Text = BackgroundTaskSample::GetBackgroundTaskStatus(SampleBackgroundTaskName);
00133     };
00134     auto handler = ref new Windows::UI::Core::DispatchedHandler(uiDelegate, Platform::CallbackContext::Any);
00135
00136     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, handler);
00137 }
Generated on Fri Nov 15 2024 22:18:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cs/AdventureWorks/Common/NavigationHelper.cs Source File

  • CortanaVoiceCommand
  • cs
  • AdventureWorks
  • Common

NavigationHelper.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using System.Windows.Input;
00007 using Windows.System;
00008 using Windows.UI.Core;
00009 using Windows.UI.Xaml;
00010 using Windows.UI.Xaml.Controls;
00011 using Windows.UI.Xaml.Navigation;
00012
00013 namespace AdventureWorks.Common
00014 {
00015     /// <summary>
00016     /// NavigationHelper aids in navigation between pages. It manages
00017     /// the backstack and integrates SuspensionManager to handle process
00018     /// lifetime management and state management when navigating between pages.
00019     /// </summary>
00020     /// <example>
00021     /// To make use of NavigationHelper, follow these two steps or
00022     /// start with a BasicPage or any other Page item template other than BlankPage.
00023     ///
00024     /// 1) Create an instance of the NavigationHelper somewhere such as in the
00025     ///     constructor for the page and register a callback for the LoadState and
00026     ///     SaveState events.
00027     /// <code>
00028     ///     public MyPage()
00029     ///     {
00030     ///         this.InitializeComponent();
00031     ///         this.navigationHelper = new NavigationHelper(this);
00032     ///         this.navigationHelper.LoadState += navigationHelper_LoadState;
00033     ///         this.navigationHelper.SaveState += navigationHelper_SaveState;
00034     ///     }
00035     ///
00036     ///     private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
00037     ///     { }
00038     ///     private void navigationHelper_SaveState(object sender, LoadStateEventArgs e)
00039     ///     { }
00040     /// </code>
00041     ///
00042     /// 2) Register the page to call into the NavigationManager whenever the page participates
00043     ///     in navigation by overriding the <see cref="Windows.UI.Xaml.Controls.Page.OnNavigatedTo"/>
00044     ///     and <see cref="Windows.UI.Xaml.Controls.Page.OnNavigatedFrom"/> events.
00045     /// <code>
00046     ///     protected override void OnNavigatedTo(NavigationEventArgs e)
00047     ///     {
00048     ///         navigationHelper.OnNavigatedTo(e);
00049     ///     }
00050     ///
00051     ///     protected override void OnNavigatedFrom(NavigationEventArgs e)
00052     ///     {
00053     ///         navigationHelper.OnNavigatedFrom(e);
00054     ///     }
00055     /// </code>
00056     /// </example>
00057     [Windows.Foundation.Metadata.WebHostHidden]
00058     public class NavigationHelper : DependencyObject
00059     {
00060         private Page Page { get; set; }
00061         private Frame Frame { get { return this.Page.Frame; } }
00062
00063         /// <summary>
00064         /// Initializes a new instance of the <see cref="NavigationHelper"/> class.
00065         /// </summary>
00066         /// <param name="page">A reference to the current page used for navigation.
00067         /// This reference allows for frame manipulation.</param>
00068         public NavigationHelper(Page page)
00069         {
00070             this.Page = page;
00071         }
00072
00073         #region Process lifetime management
00074
00075         private String _pageKey;
00076
00077         /// <summary>
00078         /// Handle this event to populate the page using content passed
00079         /// during navigation as well as any state that was saved by
00080         /// the SaveState event handler.
00081         /// </summary>
00082         public event LoadStateEventHandler LoadState;
00083         /// <summary>
00084         /// Handle this event to save state that can be used by
00085         /// the LoadState event handler. Save the state in case
00086         /// the application is suspended or the page is discarded
00087         /// from the navigation cache.
00088         /// </summary>
00089         public event SaveStateEventHandler SaveState;
00090
00091         /// <summary>
00092         /// Invoked when this page is about to be displayed in a Frame.
00093         /// This method calls <see cref="LoadState"/>, where all page specific
00094         /// navigation and process lifetime management logic should be placed.
00095         /// </summary>
00096         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00097         /// property provides the group to be displayed.</param>
00098         public void OnNavigatedTo(NavigationEventArgs e)
00099         {
00100             var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
00101             this._pageKey = "Page-" + this.Frame.BackStackDepth;
00102
00103             if (e.NavigationMode == NavigationMode.New)
00104             {
00105                 // Clear existing state for forward navigation when adding a new page to the
00106                 // navigation stack
00107                 var nextPageKey = this._pageKey;
00108                 int nextPageIndex = this.Frame.BackStackDepth;
00109                 while (frameState.Remove(nextPageKey))
00110                 {
00111                     nextPageIndex++;
00112                     nextPageKey = "Page-" + nextPageIndex;
00113                 }
00114
00115                 // Pass the navigation parameter to the new page
00116                 if (this.LoadState != null)
00117                 {
00118                     this.LoadState(this, new LoadStateEventArgs(e.Parameter, null));
00119                 }
00120             }
00121             else
00122             {
00123                 // Pass the navigation parameter and preserved page state to the page, using
00124                 // the same strategy for loading suspended state and recreating pages discarded
00125                 // from cache
00126                 if (this.LoadState != null)
00127                 {
00128                     this.LoadState(this, new LoadStateEventArgs(e.Parameter, (Dictionary<String, Object>)frameState[this._pageKey]));
00129                 }
00130             }
00131         }
00132
00133         /// <summary>
00134         /// Invoked when this page will no longer be displayed in a Frame.
00135         /// This method calls <see cref="SaveState"/>, where all page specific
00136         /// navigation and process lifetime management logic should be placed.
00137         /// </summary>
00138         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00139         /// property provides the group to be displayed.</param>
00140         public void OnNavigatedFrom(NavigationEventArgs e)
00141         {
00142             var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
00143             var pageState = new Dictionary<String, Object>();
00144             if (this.SaveState != null)
00145             {
00146                 this.SaveState(this, new SaveStateEventArgs(pageState));
00147             }
00148             frameState[_pageKey] = pageState;
00149         }
00150
00151         #endregion
00152     }
00153
00154     /// <summary>
00155     /// RootFrameNavigationHelper registers for standard mouse and keyboard
00156     /// shortcuts used to go back and forward. There should be only one
00157     /// RootFrameNavigationHelper per view, and it should be associated with the
00158     /// root frame.
00159     /// </summary>
00160     /// <example>
00161     /// To make use of RootFrameNavigationHelper, create an instance of the
00162     /// RootNavigationHelper such as in the constructor of your root page.
00163     /// <code>
00164     ///     public MyRootPage()
00165     ///     {
00166     ///         this.InitializeComponent();
00167     ///         this.rootNavigationHelper = new RootNavigationHelper(MyFrame);
00168     ///     }
00169     /// </code>
00170     /// </example>
00171     [Windows.Foundation.Metadata.WebHostHidden]
00172     public class RootFrameNavigationHelper
00173     {
00174         private Frame Frame { get; set; }
00175         SystemNavigationManager systemNavigationManager;
00176
00177         /// <summary>
00178         /// Initializes a new instance of the <see cref="RootNavigationHelper"/> class.
00179         /// </summary>
00180         /// <param name="rootFrame">A reference to the top-level frame.
00181         /// This reference allows for frame manipulation and to register navigation handlers.</param>
00182         public RootFrameNavigationHelper(Frame rootFrame)
00183         {
00184             this.Frame = rootFrame;
00185
00186             // Handle keyboard and mouse navigation requests
00187             this.systemNavigationManager = SystemNavigationManager.GetForCurrentView();
00188             systemNavigationManager.BackRequested += SystemNavigationManager_BackRequested;
00189             UpdateBackButton();
00190
00191             // Listen to the window directly so we will respond to hotkeys regardless
00192             // of which element has focus.
00193             Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated +=
00194                 CoreDispatcher_AcceleratorKeyActivated;
00195             Window.Current.CoreWindow.PointerPressed +=
00196                 this.CoreWindow_PointerPressed;
00197
00198             // Update the Back button whenever a navigation occurs.
00199             this.Frame.Navigated += (s, e) => UpdateBackButton();
00200         }
00201
00202         private bool TryGoBack()
00203         {
00204             bool navigated = false;
00205             if (this.Frame.CanGoBack)
00206             {
00207                 this.Frame.GoBack();
00208                 navigated = true;
00209             }
00210             return navigated;
00211         }
00212
00213         private bool TryGoForward()
00214         {
00215             bool navigated = false;
00216             if (this.Frame.CanGoForward)
00217             {
00218                 this.Frame.GoForward();
00219                 navigated = true;
00220             }
00221             return navigated;
00222         }
00223
00224
00225         private void SystemNavigationManager_BackRequested(object sender, BackRequestedEventArgs e)
00226         {
00227             if (!e.Handled)
00228             {
00229                 e.Handled = TryGoBack();
00230             }
00231         }
00232
00233         private void UpdateBackButton()
00234         {
00235             systemNavigationManager.AppViewBackButtonVisibility =
00236                 this.Frame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
00237         }
00238
00239         /// <summary>
00240         /// Invoked on every keystroke, including system keys such as Alt key combinations.
00241         /// Used to detect keyboard navigation between pages even when the page itself
00242         /// doesn't have focus.
00243         /// </summary>
00244         /// <param name="sender">Instance that triggered the event.</param>
00245         /// <param name="e">Event data describing the conditions that led to the event.</param>
00246         private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender,
00247             AcceleratorKeyEventArgs e)
00248         {
00249             var virtualKey = e.VirtualKey;
00250
00251             // Only investigate further when Left, Right, or the dedicated Previous or Next keys
00252             // are pressed
00253             if ((e.EventType == CoreAcceleratorKeyEventType.SystemKeyDown ||
00254                 e.EventType == CoreAcceleratorKeyEventType.KeyDown) &&
00255                 (virtualKey == VirtualKey.Left || virtualKey == VirtualKey.Right ||
00256                 (int)virtualKey == 166 || (int)virtualKey == 167))
00257             {
00258                 var coreWindow = Window.Current.CoreWindow;
00259                 var downState = CoreVirtualKeyStates.Down;
00260                 bool menuKey = (coreWindow.GetKeyState(VirtualKey.Menu) & downState) == downState;
00261                 bool controlKey = (coreWindow.GetKeyState(VirtualKey.Control) & downState) == downState;
00262                 bool shiftKey = (coreWindow.GetKeyState(VirtualKey.Shift) & downState) == downState;
00263                 bool noModifiers = !menuKey && !controlKey && !shiftKey;
00264                 bool onlyAlt = menuKey && !controlKey && !shiftKey;
00265
00266                 if (((int)virtualKey == 166 && noModifiers) ||
00267                     (virtualKey == VirtualKey.Left && onlyAlt))
00268                 {
00269                     // When the previous key or Alt+Left are pressed navigate back
00270                     e.Handled = TryGoBack();
00271                 }
00272                 else if (((int)virtualKey == 167 && noModifiers) ||
00273                     (virtualKey == VirtualKey.Right && onlyAlt))
00274                 {
00275                     // When the next key or Alt+Right are pressed navigate forward
00276                     e.Handled = TryGoForward();
00277                 }
00278             }
00279         }
00280
00281         /// <summary>
00282         /// Invoked on every mouse click, touch screen tap, or equivalent interaction.
00283         /// Used to detect browser-style next and previous mouse button clicks
00284         /// to navigate between pages.
00285         /// </summary>
00286         /// <param name="sender">Instance that triggered the event.</param>
00287         /// <param name="e">Event data describing the conditions that led to the event.</param>
00288         private void CoreWindow_PointerPressed(CoreWindow sender,
00289             PointerEventArgs e)
00290         {
00291             var properties = e.CurrentPoint.Properties;
00292
00293             // Ignore button chords with the left, right, and middle buttons
00294             if (properties.IsLeftButtonPressed || properties.IsRightButtonPressed ||
00295                 properties.IsMiddleButtonPressed)
00296                 return;
00297
00298             // If back or foward are pressed (but not both) navigate appropriately
00299             bool backPressed = properties.IsXButton1Pressed;
00300             bool forwardPressed = properties.IsXButton2Pressed;
00301             if (backPressed ^ forwardPressed)
00302             {
00303                 e.Handled = true;
00304                 if (backPressed) this.TryGoBack();
00305                 if (forwardPressed) this.TryGoForward();
00306             }
00307         }
00308     }
00309
00310     /// <summary>
00311     /// Represents the method that will handle the <see cref="NavigationHelper.LoadState"/>event
00312     /// </summary>
00313     public delegate void LoadStateEventHandler(object sender, LoadStateEventArgs e);
00314     /// <summary>
00315     /// Represents the method that will handle the <see cref="NavigationHelper.SaveState"/>event
00316     /// </summary>
00317     public delegate void SaveStateEventHandler(object sender, SaveStateEventArgs e);
00318
00319     /// <summary>
00320     /// Class used to hold the event data required when a page attempts to load state.
00321     /// </summary>
00322     public class LoadStateEventArgs : EventArgs
00323     {
00324         /// <summary>
00325         /// The parameter value passed to <see cref="Frame.Navigate(Type, Object)"/>
00326         /// when this page was initially requested.
00327         /// </summary>
00328         public Object NavigationParameter { get; private set; }
00329         /// <summary>
00330         /// A dictionary of state preserved by this page during an earlier
00331         /// session.  This will be null the first time a page is visited.
00332         /// </summary>
00333         public Dictionary<string, Object> PageState { get; private set; }
00334
00335         /// <summary>
00336         /// Initializes a new instance of the <see cref="LoadStateEventArgs"/> class.
00337         /// </summary>
00338         /// <param name="navigationParameter">
00339         /// The parameter value passed to <see cref="Frame.Navigate(Type, Object)"/>
00340         /// when this page was initially requested.
00341         /// </param>
00342         /// <param name="pageState">
00343         /// A dictionary of state preserved by this page during an earlier
00344         /// session.  This will be null the first time a page is visited.
00345         /// </param>
00346         public LoadStateEventArgs(Object navigationParameter, Dictionary<string, Object> pageState)
00347             : base()
00348         {
00349             this.NavigationParameter = navigationParameter;
00350             this.PageState = pageState;
00351         }
00352     }
00353     /// <summary>
00354     /// Class used to hold the event data required when a page attempts to save state.
00355     /// </summary>
00356     public class SaveStateEventArgs : EventArgs
00357     {
00358         /// <summary>
00359         /// An empty dictionary to be populated with serializable state.
00360         /// </summary>
00361         public Dictionary<string, Object> PageState { get; private set; }
00362
00363         /// <summary>
00364         /// Initializes a new instance of the <see cref="SaveStateEventArgs"/> class.
00365         /// </summary>
00366         /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
00367         public SaveStateEventArgs(Dictionary<string, Object> pageState)
00368             : base()
00369         {
00370             this.PageState = pageState;
00371         }
00372     }
00373 }
Generated on Fri Nov 15 2024 22:18:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/GameUIControl.h Source File

  • Simple3DGameXaml
  • cpp

GameUIControl.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012
00013 // The IGameUIControl interface provides an abstraction to the GameMain class
00014 // for controlling UI elements on the screen in response to game state.  It helps to
00015 // provide separation between the game control and how the UI is displayed to the user.
00016 //    SetGameLoading - is called to have the UI indicate the game is currently loading
00017 //        resources for the game or a particular level.
00018 //    SetGameStats - is called to have the UI indicate the status of the last completed game.
00019 //    SetGameOver - is called to have the UI indicate this iteration of the game as finished.
00020 //    SetLevelStart - is called to have the UI indicate the level is ready to begin.  This includes
00021 //        providing the objectives for the level and other current data.
00022 //    SetPause - is called to have the UI indicate the game is currently in the Paused state.
00023 //    ShowTooSmall - this method indicates the UI should display to the user that the current
00024 //        display configuration is too small for the game to be played.
00025 //    HideTooSmall - this method inticates the UI should stop displaying to the user that the
00026 //        current display configuration is too small for game play.
00027 //    SetAction - is called to have the UI indicate the next action the user should take.
00028 //    ShowGameInfoOverlay - is called to have the UI display to the user the current state
00029 //        as defined by the other interface calls above.
00030 //    HideGameInfoOverlay - is called to have the UI remove the display of the current state
00031 //        when the game transitions into active game play.
00032
00033 namespace Simple3DGameXaml
00034 {
00035     public enum class GameInfoOverlayCommand
00036     {
00037         None,
00038         TapToContinue,
00039         PleaseWait,
00040         PlayAgain,
00041     };
00042
00043     public interface class IGameUIControl
00044     {
00045         void SetGameLoading();
00046         void SetGameStats(int maxLevel, int hitCount, int shotCount);
00047         void SetGameOver(bool win, int maxLevel, int hitCount, int shotCount, int highScore);
00048         void SetLevelStart(int level, Platform::String^ objective, float timeLimit, float bonusTime);
00049         void SetPause(int level, int hitCount, int shotCount, float timeRemaining);
00050         void ShowTooSmall();
00051         void HideTooSmall();
00052         void SetAction(GameInfoOverlayCommand action);
00053         void HideGameInfoOverlay();
00054         void ShowGameInfoOverlay();
00055     };
00056 };
00057
Generated on Fri Nov 15 2024 22:21:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TitleBar/cpp/Scenario2_Extend.xaml.h Source File

  • TitleBar
  • cpp

Scenario2_Extend.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Extend.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario2_Extend sealed
00021     {
00022     public:
00023         Scenario2_Extend();
00024
00025     protected:
00026         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00027         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00028
00029     private:
00030         void ExtendView_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00031         void EnableControls_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032         void ToggleFullScreenModeButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033         void OnWindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args);
00034         void UpdateFullScreenModeStatus();
00035
00036     private:
00037         MainPage^ rootPage = MainPage::Current;
00038
00039         Windows::Foundation::EventRegistrationToken windowSizeChangedToken{};
00040     };
00041 }
Generated on Fri Nov 15 2024 22:21:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PlayerViewModel Member List

This is the complete list of members for PlayerViewModel, including all inherited members.
AudioCategories | PlayerViewModel |
canSkipNext | PlayerViewModel | [private]
CanSkipNext | PlayerViewModel |
CanSkipPrevious | PlayerViewModel |
canSkipPrevious | PlayerViewModel | [private]
dispatcher | PlayerViewModel | [private]
Dispose() | PlayerViewModel | [inline]
disposed | PlayerViewModel | [private]
HandlePlaybackListChanges(IObservableVector< MediaPlaybackItem > vector) | PlayerViewModel | [inline, private]
Items_VectorChanged(IObservableVector< MediaPlaybackItem > sender, IVectorChangedEventArgs args) | PlayerViewModel | [inline, private]
mediaList | PlayerViewModel | [private]
MediaList | PlayerViewModel |
PlaybackSession | PlayerViewModel |
player | PlayerViewModel | [private]
PlayerViewModel(MediaPlayer player, CoreDispatcher dispatcher) | PlayerViewModel | [inline]
PropertyChanged | PlayerViewModel |
RaisePropertyChanged(string propertyName) | PlayerViewModel | [inline, private]
SelectedAudioCategory | PlayerViewModel |
SkipNext() | PlayerViewModel | [inline]
SkipPrevious() | PlayerViewModel | [inline]
subscribedPlaybackList | PlayerViewModel | [private]
SubscribedPlaybackList_CurrentItemChanged(MediaPlaybackList sender, CurrentMediaPlaybackItemChangedEventArgs args) | PlayerViewModel | [inline, private]
TogglePlayPause() | PlayerViewModel | [inline]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_ManageHotspot Member List

This is the complete list of members for Scenario1_ManageHotspot, including all inherited members.
IsBackgroundTaskName(string name) | Scenario1_ManageHotspot | [inline, private, static]
m_network | Scenario1_ManageHotspot | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_ManageHotspot | [inline, protected]
RegisterTasks_Click(object sender, RoutedEventArgs e) | Scenario1_ManageHotspot | [inline, private]
rootPage | Scenario1_ManageHotspot | [private]
SavePropertiesForBackgroundTask() | Scenario1_ManageHotspot | [inline, private]
Scenario1_ManageHotspot() | Scenario1_ManageHotspot | [inline]
UnregisterTasks_Click(object sender, RoutedEventArgs e) | Scenario1_ManageHotspot | [inline, private]
UpdateNowButton_Click(object sender, RoutedEventArgs e) | Scenario1_ManageHotspot | [inline, private]
UpdateOnDemandButton_Click(object sender, RoutedEventArgs e) | Scenario1_ManageHotspot | [inline, private]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppServices/cppwinrt/AppServicesClient/SampleConfiguration.h Source File

  • AppServices
  • cppwinrt
  • AppServicesClient

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     bool TryParseInt32(wchar_t const* text, int32_t& value);
00018
00019     // RAII type for ensuring an object is closed.
00020     struct ensure_close
00021     {
00022         Windows::Foundation::IClosable m_closable;
00023
00024         ensure_close(Windows::Foundation::IClosable closable) : m_closable(std::move(closable)) { }
00025         ~ensure_close() { if (m_closable) m_closable.Close(); }
00026
00027         ensure_close(const ensure_close&) = delete;
00028         ensure_close& operator=(const ensure_close&) = delete;
00029
00030         ensure_close(ensure_close&& other) = default;
00031         ensure_close& operator=(ensure_close&& other) = default;
00032     };
00033
00034
00035 }
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSensors/cpp/Scenario1_DataEvents.xaml.cpp Source File

  • CustomSensors
  • cpp

Scenario1_DataEvents.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario1_DataEvents.xaml.cpp
00013 // Implementation of the Scenario1_DataEvents class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario1_DataEvents.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace concurrency;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::Devices::Enumeration;
00026 using namespace Windows::Devices::Sensors::Custom;
00027 using namespace Windows::Foundation;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::UI::Core;
00030 using namespace Platform;
00031
00032 // The following ID is defined by vendors and is unique to a custom sensor type. Each custom sensor driver should define one unique ID.
00033 //
00034 // The ID below is defined in the custom sensor driver sample available in the SDK. It identifies the custom sensor CO2 emulation sample driver.
00035 const GUID GUID_CustomSensorDevice_VendorDefinedSubTypeID = { 0x4025a865, 0x638c, 0x43aa, 0xa6, 0x88, 0x98, 0x58, 0x9, 0x61, 0xee, 0xae };
00036
00037 // A property key is defined by vendors for each datafield property a custom sensor driver exposes. Property keys are defined
00038 // per custom sensor driver and is unique to each custom sensor type.
00039 //
00040 // The following property key represents the CO2 level as defined in the custom sensor CO2 emulation driver sample available in the WDK.
00041 // In this example only one key is defined, but other drivers may define more than one key by rev'ing up the property key index.
00042 #define CO2_LEVEL_KEY "{74879888-a3cc-45c6-9ea9-058838256433} 1"
00043
00044 Scenario1_DataEvents::Scenario1_DataEvents() : m_RootPage(MainPage::Current), m_DesiredReportInterval(0)
00045 {
00046     Guid customSensorGuid(GUID_CustomSensorDevice_VendorDefinedSubTypeID);
00047
00048     InitializeComponent();
00049
00050     m_DeviceAccessInfo = DeviceAccessInformation::CreateFromDeviceClassId(customSensorGuid);
00051     m_DeviceAccessInfo->AccessChanged += ref new TypedEventHandler<DeviceAccessInformation ^, DeviceAccessChangedEventArgs ^>(this, &Scenario1_DataEvents::OnAccessChanged);
00052
00053     StartWatcher();
00054
00055 }
00056
00057 /// <summary>
00058 /// Invoked each time the custom sensor is created
00059 /// </summary>
00060 void Scenario1_DataEvents::StartWatcher()
00061 {
00062     Guid customSensorGuid(GUID_CustomSensorDevice_VendorDefinedSubTypeID);
00063     String^ customSensorSelector = CustomSensor::GetDeviceSelector(customSensorGuid);
00064     m_Watcher = DeviceInformation::CreateWatcher(customSensorSelector);
00065     m_Watcher->Added += ref new TypedEventHandler<DeviceWatcher^, DeviceInformation^>(this, &Scenario1_DataEvents::OnCustomSensorAdded);
00066     m_Watcher->Start();
00067 }
00068
00069 /// <summary>
00070 /// Invoked when the device watcher finds a matching custom sensor device
00071 /// </summary>
00072 /// <param name="watcher">device watcher</param>
00073 /// <param name="customSensorDevice">device information for the custom sensor that was found</param>
00074 void Scenario1_DataEvents::OnCustomSensorAdded(DeviceWatcher^ watcher, DeviceInformation^ customSensorDevice)
00075 {
00076     create_task(CustomSensor::FromIdAsync(customSensorDevice->Id)).then([this](CustomSensor^ customSensor)
00077     {
00078         if (customSensor != nullptr)
00079         {
00080             // When multiple custom sensors exist on the system, OnCustomSensorAdded
00081             // may be called concurrently using multiple threadpool threads
00082             // Lock the section to protect this->customSensor from concurrent accesses
00083             auto lock = m_CritsecCustomSensor.Lock();
00084
00085             // Just pick the first matching custom sensor, ignore the others
00086             if (nullptr == m_CustomSensor)
00087             {
00088                 m_CustomSensor = customSensor;
00089                 // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00090                 // This value will be used later to activate the sensor.
00091                 // In the case below, we defined a 200ms report interval as being suitable for the purpose of this app.
00092                 uint32 minReportInterval = customSensor->MinimumReportInterval;
00093                 m_DesiredReportInterval = minReportInterval > 200 ? minReportInterval : 200;
00094             }
00095         }
00096         else
00097         {
00098             Dispatcher->RunAsync(
00099                 CoreDispatcherPriority::Normal,
00100                 ref new DispatchedHandler(
00101                     [this]()
00102                     {
00103                         m_RootPage->NotifyUser("Custom sensor not found or access denied", NotifyType::ErrorMessage);
00104                     },
00105                     CallbackContext::Any
00106                 )
00107             );
00108         }
00109     });
00110 }
00111
00112 /// <summary>
00113 /// Invoked when this page is about to be displayed in a Frame.
00114 /// </summary>
00115 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00116 /// property is typically used to configure the page.</param>
00117 void Scenario1_DataEvents::OnNavigatedTo(NavigationEventArgs^ e)
00118 {
00119     ScenarioEnableButton->IsEnabled = true;
00120     ScenarioDisableButton->IsEnabled = false;
00121 }
00122
00123 /// <summary>
00124 /// Invoked when this page is no longer displayed.
00125 /// </summary>
00126 /// <param name="e"></param>
00127 void Scenario1_DataEvents::OnNavigatedFrom(NavigationEventArgs^ e)
00128 {
00129     // If the navigation is external to the app do not clean up.
00130     // This can occur on Phone when suspending the app.
00131     if (e->NavigationMode == NavigationMode::Forward && e->Uri == nullptr)
00132     {
00133         return;
00134     }
00135
00136     if (ScenarioDisableButton->IsEnabled)
00137     {
00138         Window::Current->VisibilityChanged -= m_VisibilityToken;
00139
00140         if (m_CustomSensor != nullptr)
00141         {
00142             m_CustomSensor->ReadingChanged -= m_ReadingToken;
00143         }
00144     }
00145 }
00146
00147 /// <summary>
00148 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00149 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00150 /// </summary>
00151 /// <param name="sender"></param>
00152 /// <param name="e">
00153 /// Event data that can be examined for the current visibility state.
00154 /// </param>
00155 void Scenario1_DataEvents::OnVisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00156 {
00157     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00158     if (m_CustomSensor != nullptr && ScenarioDisableButton->IsEnabled)
00159     {
00160         if (e->Visible)
00161         {
00162             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00163             m_ReadingToken = m_CustomSensor->ReadingChanged += ref new TypedEventHandler<CustomSensor^, CustomSensorReadingChangedEventArgs^>(this, &Scenario1_DataEvents::OnReadingChanged);
00164         }
00165         else
00166         {
00167             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00168             m_CustomSensor->ReadingChanged -= m_ReadingToken;
00169         }
00170     }
00171 }
00172
00173 void Scenario1_DataEvents::OnReadingChanged(CustomSensor^ sender, CustomSensorReadingChangedEventArgs^ e)
00174 {
00175     // We need to dispatch to the UI thread to display the output
00176     Dispatcher->RunAsync(
00177         CoreDispatcherPriority::Normal,
00178         ref new DispatchedHandler(
00179             [this, e]()
00180             {
00181                 CustomSensorReading^ reading = e->Reading;
00182                 IMapView<String^, Object^>^ readingProps = reading->Properties;
00183
00184                 if (readingProps->HasKey(CO2_LEVEL_KEY))
00185                 {
00186                     ScenarioOutput_CO2Level->Text = readingProps->Lookup(CO2_LEVEL_KEY)->ToString();
00187                 }
00188             },
00189             CallbackContext::Any
00190             )
00191         );
00192 }
00193
00194 void Scenario1_DataEvents::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00195 {
00196     if (m_CustomSensor != nullptr)
00197     {
00198         // Establish the report interval
00199         m_CustomSensor->ReportInterval = m_DesiredReportInterval;
00200
00201         m_VisibilityToken = Window::Current->VisibilityChanged += ref new WindowVisibilityChangedEventHandler(this, &Scenario1_DataEvents::OnVisibilityChanged);
00202         m_ReadingToken = m_CustomSensor->ReadingChanged += ref new TypedEventHandler<CustomSensor^, CustomSensorReadingChangedEventArgs^>(this, &Scenario1_DataEvents::OnReadingChanged);
00203
00204         ScenarioEnableButton->IsEnabled = false;
00205         ScenarioDisableButton->IsEnabled = true;
00206     }
00207     else
00208     {
00209         m_RootPage->NotifyUser("Custom sensor not found or access denied", NotifyType::ErrorMessage);
00210     }
00211 }
00212
00213 void Scenario1_DataEvents::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00214 {
00215     Window::Current->VisibilityChanged -= m_VisibilityToken;
00216
00217     if (m_CustomSensor != nullptr)
00218     {
00219         m_CustomSensor->ReadingChanged::remove(m_ReadingToken);
00220
00221         // Restore the default report interval to release resources while the sensor is not in use
00222         m_CustomSensor->ReportInterval = 0;
00223     }
00224
00225     ScenarioEnableButton->IsEnabled = true;
00226     ScenarioDisableButton->IsEnabled = false;
00227 }
00228
00229 /// <summary>
00230 /// Invoked when the privacy settings for this custom sensor have changed
00231 /// </summary>
00232 /// <param name="sender"></param>
00233 /// <param name="e"></param>
00234 void Scenario1_DataEvents::OnAccessChanged(DeviceAccessInformation ^sender, DeviceAccessChangedEventArgs ^args)
00235 {
00236     if (args->Status == DeviceAccessStatus::Allowed)
00237     {
00238         StartWatcher();
00239
00240         Dispatcher->RunAsync(
00241             CoreDispatcherPriority::Normal,
00242             ref new DispatchedHandler(
00243                 [this]()
00244                 {
00245                     m_RootPage->NotifyUser("", NotifyType::StatusMessage);
00246                 },
00247                 CallbackContext::Any
00248             )
00249         );
00250     }
00251     else
00252     {
00253         m_CustomSensor = nullptr;
00254
00255         Dispatcher->RunAsync(
00256             CoreDispatcherPriority::Normal,
00257             ref new DispatchedHandler(
00258                 [this]()
00259                 {
00260                     Window::Current->VisibilityChanged -= m_VisibilityToken;
00261
00262                     ScenarioEnableButton->IsEnabled = true;
00263                     ScenarioDisableButton->IsEnabled = false;
00264
00265                     m_RootPage->NotifyUser("Custom sensor access denied", NotifyType::ErrorMessage);
00266                 },
00267                 CallbackContext::Any
00268             )
00269         );
00270     }
00271 }
Generated on Fri Nov 15 2024 22:17:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario1WinRTComponent/pch.h Source File

  • AllJoyn
  • Common
  • Scenario1WinRTComponent

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //-----------------------------------------------------------------------------
00013 // <auto-generated>
00014 //   This code was generated by a tool.
00015 //
00016 //   Changes to this file may cause incorrect behavior and will be lost if
00017 //   the code is regenerated.
00018 //
00019 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00020 // </auto-generated>
00021 //-----------------------------------------------------------------------------
00022 #pragma once
00023
00024 #include <windows.h>
00025 #include <ppltasks.h>
00026 #include <concrt.h>
00027 #include <collection.h>
00028 #include <windows.devices.alljoyn.interop.h>
00029 #include <map>
00030
00031 #include <alljoyn_c/busattachment.h>
00032 #include <alljoyn_c/dbusstddefines.h>
00033 #include <alljoyn_c/AboutData.h>
00034 #include <alljoyn_c/AboutObj.h>
00035 #include <alljoyn_c/AboutObjectDescription.h>
00036
00037 #include "AllJoynHelpers.h"
00038 #include "AllJoynBusObjectManager.h"
00039
00040 #define PROJECT_NAMESPACE com::microsoft::Samples::SecureInterface
00041
00042 #include "SecureInterfaceStructures.h"
00043 #include "TypeConversionHelpers.h"
00044 #include "SecureInterfaceMethodResults.h"
00045 #include "SecureInterfaceEventArgs.h"
00046 #include "ISecureInterfaceService.h"
00047 #include "SecureInterfaceSignals.h"
00048 #include "SecureInterfaceLegacySignals.h"
00049 #include "SecureInterfaceProducer.h"
00050 #include "SecureInterfaceConsumer.h"
00051 #include "SecureInterfaceServiceEventArgs.h"
00052 #include "SecureInterfaceServiceEventAdapter.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cpp/Scenario7_B2B.xaml.cpp Source File

  • Store
  • cpp

Scenario7_B2B.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario7_B2B.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::Data::Json;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Services::Store;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::Web;
00026 using namespace Windows::Web::Http;
00027 using namespace Windows::Web::Http::Headers;
00028
00029 // Note: 'tenant', 'clientId', "clientSecret" and "appIdUri" will need to be updated based on your particular
00030 // Azure Active Directory configuration. See the README for more information.
00031 // https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx
00032 String^ tenantId = "00000000-0000-0000-0000-000000000000";
00033 String^ clientId = "00000000-0000-0000-0000-000000000000";
00034 String^ clientSecret = "00000000000000000000000000000000000000000000";
00035 String^ appIdUri = "https://contoso.onmicrosoft.com";
00036
00037 Scenario7_B2B::Scenario7_B2B()
00038 {
00039     InitializeComponent();
00040
00041     storeContext = StoreContext::GetDefault();
00042 }
00043
00044
00045 void Scenario7_B2B::GetCustomerCollectionsId(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00046 {
00047     create_task(GetTokenFromAzureOAuthAsync())
00048         .then([this](String^ aadToken)
00049     {
00050         if (aadToken != nullptr)
00051         {
00052             create_task(storeContext->GetCustomerCollectionsIdAsync(aadToken, "kim@example.com"))
00053                 .then([this](String^ id)
00054             {
00055                 Output->Text = id;
00056                 if (id == nullptr)
00057                 {
00058                     rootPage->NotifyUser("GetCustomerCollectionsIdAsync failed.", NotifyType::ErrorMessage);
00059                 }
00060             });
00061         }
00062     });
00063 }
00064
00065 void Scenario7_B2B::GetCustomerPurchaseId(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00066 {
00067     create_task(GetTokenFromAzureOAuthAsync())
00068         .then([this](String^ aadToken)
00069     {
00070         if (aadToken != nullptr)
00071         {
00072             create_task(storeContext->GetCustomerPurchaseIdAsync(aadToken, "kim@example.com"))
00073                 .then([this](String^ id)
00074             {
00075                 Output->Text = id;
00076                 if (id == nullptr)
00077                 {
00078                     rootPage->NotifyUser("GetCustomerCollectionsIdAsync failed.", NotifyType::ErrorMessage);
00079                 }
00080             });
00081         }
00082     });
00083 }
00084
00085 task<String^> Scenario7_B2B::GetTokenFromAzureOAuthAsync()
00086 {
00087     IHttpContent^ content = ref new HttpFormUrlEncodedContent(ref new Map<String^, String^>({
00088         std::pair<String^, String^>("grant_type", "client_credentials"),
00089         std::pair<String^, String^>("client_id", clientId),
00090         std::pair<String^, String^>("client_secret", clientSecret),
00091         std::pair<String^, String^>("resource", appIdUri),
00092     }));
00093
00094     content->Headers->ContentType = ref new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");
00095
00096     HttpClient^ client = ref new HttpClient();
00097     Uri^ uri = ref new Uri("https://login.microsoftonline.com/" + tenantId + "/oauth2/token");
00098     // Networking errors in PostAsync are reported as exceptions.
00099     return create_task(client->PostAsync(uri, content))
00100         .then([this](HttpResponseMessage^ result)
00101     {
00102         return create_task(result->Content->ReadAsStringAsync());
00103     }).then([this](String^ responseString)
00104     {
00105         // JSON parsing errors are reported as exceptions.
00106         JsonValue^ response = JsonValue::Parse(responseString);
00107         return response->GetObject()->GetNamedString("access_token");
00108     }).then([this](task<String^> previousTask)
00109     {
00110         String^ result;
00111         try
00112         {
00113             // Any exceptions in PostAsync or JSON parsing will be rethrown here.
00114             result = previousTask.get();
00115         }
00116         catch (Exception^ ex)
00117         {
00118             this->rootPage->NotifyUser("There were problems getting an Azure OAuth token.", NotifyType::ErrorMessage);
00119         }
00120         return result;
00121     });
00122 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cs/Scenario6_DeleteTPM.xaml.cs Source File

  • SmartCard
  • cs

Scenario6_DeleteTPM.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Threading;
00003 using Windows.Devices.SmartCards;
00004 using Windows.UI.Xaml;
00005 using Windows.UI.Xaml.Controls;
00006
00007 namespace SDKTemplate
00008 {
00009     public sealed partial class Scenario6_DeleteTPM : Page
00010     {
00011         MainPage rootPage = MainPage.Current;
00012
00013         private SmartCardReader reader;
00014         private SynchronizationContext uiContext = null;
00015
00016         public Scenario6_DeleteTPM()
00017         {
00018             this.InitializeComponent();
00019
00020             // Since this class is a page, it will be instantiated on the UI
00021             // thread.  We need to keep a reference to the UI thread's
00022             // synchronization context as a member so that we can access it
00023             // from other threads for event handlers.  See the
00024             // HandleCardRemoved method for more information.
00025             uiContext = SynchronizationContext.Current;
00026         }
00027
00028         /// <summary>
00029         /// Click handler for the 'Delete' button.
00030         /// </summary>
00031         /// <param name="sender"></param>
00032         /// <param name="e"></param>
00033         private async void Delete_Click(object sender, RoutedEventArgs e)
00034         {
00035             if (!rootPage.ValidateTPMSmartCard())
00036             {
00037                 rootPage.NotifyUser("Use Scenario One to create a TPM virtual smart card.", NotifyType.ErrorMessage);
00038                 return;
00039             }
00040
00041             Button b = sender as Button;
00042             b.IsEnabled = false;
00043             rootPage.NotifyUser("Deleting the TPM virtual smart card...", NotifyType.ErrorMessage);
00044
00045             try
00046             {
00047                 SmartCard card = await rootPage.GetSmartCard();
00048
00049                 // The following two lines are not directly related to TPM virtual
00050                 // smart card creation, but are used to demonstrate how to handle
00051                 // CardRemoved events by registering an event handler with a
00052                 // SmartCardReader object.  Since we are using a TPM virtual smart
00053                 // card in this case, the card cannot actually be added to or
00054                 // removed from the reader, but a CardRemoved event will fire
00055                 // when the reader and card are deleted.
00056                 //
00057                 // We must retain a reference to the SmartCardReader object to
00058                 // which we are adding the event handler.  We use += to add the
00059                 // HandleCardRemoved method as an event handler.  The function
00060                 // will be automatically boxed in a TypedEventHandler, but
00061                 // the function signature match the template arguments for
00062                 // the specific event - in this case,
00063                 // <SmartCardReader, CardRemovedEventArgs>
00064                 reader = card.Reader;
00065                 reader.CardRemoved += HandleCardRemoved;
00066
00067                 bool result = await SmartCardProvisioning.RequestVirtualSmartCardDeletionAsync(card);
00068
00069                 if (result)
00070                 {
00071                     rootPage.NotifyUser("TPM virtual smart card deletion completed.", NotifyType.StatusMessage);
00072                     rootPage.SmartCardReaderDeviceId = null;
00073                 }
00074                 else
00075                 {
00076                     rootPage.NotifyUser("TPM virtual smart card deletion was canceled by the user.", NotifyType.StatusMessage);
00077                 }
00078             }
00079             catch (Exception ex)
00080             {
00081                 rootPage.NotifyUser("TPM virtual smartcard deletion failed with exception: " + ex.ToString(), NotifyType.ErrorMessage);
00082             }
00083             finally
00084             {
00085                 b.IsEnabled = true;
00086             }
00087         }
00088
00089         void HandleCardRemoved(SmartCardReader evtReader, CardRemovedEventArgs args)
00090         {
00091             // This event handler will not be invoked on the UI thread.  Hence,
00092             // to perform UI operations we need to post a lambda to be executed
00093             // back on the UI thread; otherwise we may access objects which
00094             // are not marshalled for the current thread, which will result in an
00095             // exception due to RPC_E_WRONG_THREAD.
00096             uiContext.Post((object ignore) =>
00097             {
00098                 rootPage.NotifyUser("Card removed from reader " + evtReader.Name + ".", NotifyType.StatusMessage);
00099             }, null);
00100         }
00101     }
00102 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cs/SampleConfiguration.cs Source File

  • Printing
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using PrintSample;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Printing C# Sample";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Basic", ClassType=typeof(Scenario1Basic)},
00026             new Scenario() { Title="Standard Options", ClassType=typeof(Scenario2StandardOptions)},
00027             new Scenario() { Title="Custom Options", ClassType=typeof(Scenario3CustomOptions)},
00028             new Scenario() { Title="Page Range", ClassType=typeof(Scenario4PageRange)},
00029             new Scenario() { Title="Photos", ClassType=typeof(Scenario5Photos)},
00030             new Scenario() { Title="Disable Preview", ClassType=typeof(Scenario6DisablePreview)}
00031         };
00032     }
00033
00034     public class Scenario
00035     {
00036         public string Title { get; set; }
00037         public Type ClassType { get; set; }
00038     }
00039 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cppwinrt/pch.h Source File

  • IoT-GPIO
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Devices.Enumeration.h"
00008 #include "winrt/Windows.Devices.Gpio.h"
00009 #include "winrt/Windows.System.h"
00010 #include "winrt/Windows.UI.Core.h"
00011 #include "winrt/Windows.UI.Xaml.h"
00012 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.h"
00014 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00015 #include "winrt/Windows.UI.Xaml.Documents.h"
00016 #include "winrt/Windows.UI.Xaml.Interop.h"
00017 #include "winrt/Windows.UI.Xaml.Markup.h"
00018 #include "winrt/Windows.UI.Xaml.Media.h"
00019 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/Content/SpinningCubeRenderer.h Source File

  • BasicHologram
  • cpp
  • Content

SpinningCubeRenderer.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "..\Common\DeviceResources.h"
00004 #include "..\Common\StepTimer.h"
00005 #include "ShaderStructures.h"
00006
00007 namespace BasicHologram
00008 {
00009     // This sample renderer instantiates a basic rendering pipeline.
00010     class SpinningCubeRenderer
00011     {
00012     public:
00013         SpinningCubeRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00014         void CreateDeviceDependentResources();
00015         void ReleaseDeviceDependentResources();
00016         void Update(const DX::StepTimer& timer);
00017         void Render();
00018
00019         // Repositions the sample hologram.
00020         void PositionHologram(Windows::UI::Input::Spatial::SpatialPointerPose^ pointerPose);
00021
00022         // Property accessors.
00023         void SetPosition(Windows::Foundation::Numerics::float3 pos) { m_position = pos;  }
00024         Windows::Foundation::Numerics::float3 GetPosition()         { return m_position; }
00025
00026     private:
00027         // Cached pointer to device resources.
00028         std::shared_ptr<DX::DeviceResources>            m_deviceResources;
00029
00030         // Direct3D resources for cube geometry.
00031         Microsoft::WRL::ComPtr<ID3D11InputLayout>       m_inputLayout;
00032         Microsoft::WRL::ComPtr<ID3D11Buffer>            m_vertexBuffer;
00033         Microsoft::WRL::ComPtr<ID3D11Buffer>            m_indexBuffer;
00034         Microsoft::WRL::ComPtr<ID3D11VertexShader>      m_vertexShader;
00035         Microsoft::WRL::ComPtr<ID3D11GeometryShader>    m_geometryShader;
00036         Microsoft::WRL::ComPtr<ID3D11PixelShader>       m_pixelShader;
00037         Microsoft::WRL::ComPtr<ID3D11Buffer>            m_modelConstantBuffer;
00038
00039         // System resources for cube geometry.
00040         ModelConstantBuffer                             m_modelConstantBufferData;
00041         uint32                                          m_indexCount = 0;
00042
00043         // Variables used with the rendering loop.
00044         bool                                            m_loadingComplete = false;
00045         float                                           m_degreesPerSecond = 45.f;
00046         Windows::Foundation::Numerics::float3           m_position = { 0.f, 0.f, -2.f };
00047
00048         // If the current D3D Device supports VPRT, we can avoid using a geometry
00049         // shader just to set the render target array index.
00050         bool                                            m_usingVprtShaders = false;
00051     };
00052 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cppwinrt/Scenario1_UTF8.h Source File

  • WebSocket
  • cppwinrt

Scenario1_UTF8.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_UTF8.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_UTF8 : Scenario1_UTF8T<Scenario1_UTF8>
00019     {
00020         Scenario1_UTF8();
00021
00022         winrt::fire_and_forget OnConnect(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00023         winrt::fire_and_forget OnSend(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00024         void OnDisconnect(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00025         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00026
00027     private:
00028         Windows::Foundation::IAsyncAction ConnectAsync();
00029         Windows::Foundation::IAsyncAction SendAsync();
00030         winrt::fire_and_forget OnServerCustomValidationRequested(Windows::Networking::Sockets::MessageWebSocket const&, Windows::Networking::Sockets::WebSocketServerCustomValidationRequestedEventArgs e);
00031         winrt::fire_and_forget MessageReceived(Windows::Networking::Sockets::MessageWebSocket const& sender, Windows::Networking::Sockets::MessageWebSocketMessageReceivedEventArgs e);
00032         winrt::fire_and_forget OnClosed(Windows::Networking::Sockets::IWebSocket sender, Windows::Networking::Sockets::WebSocketClosedEventArgs e);
00033         void CloseSocket();
00034         void AppendOutputLine(hstring const& value);
00035         void UpdateVisualState();
00036         void SetBusy(bool value);
00037
00038         SDKTemplate::MainPage m_rootPage{ MainPage::Current() };
00039         Windows::Networking::Sockets::MessageWebSocket m_messageWebSocket{ nullptr };
00040         Windows::Storage::Streams::DataWriter m_messageWriter{ nullptr };
00041         bool m_busy{ false };
00042     };
00043 }
00044
00045 namespace winrt::SDKTemplate::factory_implementation
00046 {
00047     struct Scenario1_UTF8 : Scenario1_UTF8T<Scenario1_UTF8, implementation::Scenario1_UTF8>
00048     {
00049     };
00050 }
Generated on Fri Nov 15 2024 22:22:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RenderBuffer Member List

This is the complete list of members for RenderBuffer, including all inherited members.
Buffer | RenderBuffer |
BufferSize | RenderBuffer |
BytesFilled | RenderBuffer |
Next | RenderBuffer |
RenderBuffer() | RenderBuffer | [inline]
~RenderBuffer() | RenderBuffer | [inline]
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomUsbDeviceAccess/cs/Scenario4_BulkPipes.xaml.cs Source File

  • CustomUsbDeviceAccess
  • cs

Scenario4_BulkPipes.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Globalization;
00015 using System.Threading;
00016 using System.Threading.Tasks;
00017 using Windows.ApplicationModel;
00018 using Windows.Devices.Enumeration;
00019 using Windows.Devices.Usb;
00020 using Windows.Foundation;
00021 using Windows.Storage.Streams;
00022 using Windows.UI.Core;
00023 using Windows.UI.Xaml;
00024 using Windows.UI.Xaml.Controls;
00025 using Windows.UI.Xaml.Navigation;
00026 using SDKTemplate;
00027
00028 namespace CustomUsbDeviceAccess
00029 {
00030     /// <summary>
00031     /// This page demonstrates how to propertly use bulk pipes to read and write to the device.
00032     /// </summary>
00033     public sealed partial class Scenario4_BulkPipes : Page, IDisposable
00034     {
00035         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00036         // as NotifyUser()
00037         private MainPage rootPage = MainPage.Current;
00038
00039         private CancellationTokenSource cancellationTokenSource;
00040
00041         private Object cancelIoLock = new Object();
00042
00043         private Boolean runningReadTask;
00044         private Boolean runningWriteTask;
00045         private Boolean runningReadWriteTask;
00046
00047         // Indicate if we navigate away from this page or not.
00048         private Boolean navigatedAway;
00049
00050         private UInt32 totalBytesWritten;
00051         private UInt32 totalBytesRead;
00052
00053         public Scenario4_BulkPipes()
00054         {
00055             totalBytesRead = 0;
00056             totalBytesWritten = 0;
00057             runningReadTask = false;
00058             runningWriteTask = false;
00059             runningReadWriteTask = false;
00060
00061             this.InitializeComponent();
00062         }
00063
00064         public void Dispose()
00065         {
00066             if (cancellationTokenSource != null)
00067             {
00068                 cancellationTokenSource.Dispose();
00069                 cancellationTokenSource = null;
00070             }
00071         }
00072
00073         /// <summary>
00074         /// Invoked when this page is about to be displayed in a Frame.
00075         ///
00076         /// We will enable/disable parts of the UI if the device doesn't support it.
00077         /// Will will also register a callback for whenever we cancel a task because we want
00078         /// to prevent the user from doing anymore IO (disable buttons to prevent user IO)
00079         /// </summary>
00080         /// <param name="eventArgs">Event data that describes how this page was reached.  The Parameter
00081         /// property is typically used to configure the page.</param>
00082         protected override void OnNavigatedTo(NavigationEventArgs eventArgs)
00083         {
00084             navigatedAway = false;
00085
00086             // Both the OSRFX2 and the SuperMutt use the same scenario
00087             // If no devices are connected, none of the scenarios will be shown and an error will be displayed
00088             Dictionary<DeviceType, UIElement> deviceScenarios = new Dictionary<DeviceType, UIElement>();
00089             deviceScenarios.Add(DeviceType.OsrFx2, GeneralScenario);
00090             deviceScenarios.Add(DeviceType.SuperMutt, GeneralScenario);
00091
00092             Utilities.SetUpDeviceScenarios(deviceScenarios, DeviceScenarioContainer);
00093
00094             // So we can reset future tasks
00095             ResetCancellationTokenSource();
00096
00097             EventHandlerForDevice.Current.OnAppSuspendCallback = new SuspendingEventHandler(this.OnAppSuspension);
00098
00099             // Reset the buttons if the app resumed and the device is reconnected
00100             EventHandlerForDevice.Current.OnDeviceConnected = new TypedEventHandler<EventHandlerForDevice, DeviceInformation>(this.OnDeviceConnected);
00101
00102             UpdateButtonStates();
00103         }
00104
00105         /// <summary>
00106         /// Cancel any on going tasks when navigating away from the page so the device is in a consistent state throughout
00107         /// all the scenarios
00108         /// </summary>
00109         /// <param name="eventArgs"></param>
00110         protected override void OnNavigatedFrom(NavigationEventArgs eventArgs)
00111         {
00112             navigatedAway = true;
00113
00114             CancelAllIoTasks();
00115
00116             // We don't need to worry about app suspend for this scenario anymore
00117             EventHandlerForDevice.Current.OnAppSuspendCallback = null;
00118             EventHandlerForDevice.Current.OnDeviceConnected = null;
00119         }
00120
00121         /// <summary>
00122         /// Stop any pending IO operations because the device will be closed when the app suspends
00123         /// </summary>
00124         /// <param name="sender"></param>
00125         /// <param name="args"></param>
00126         private void OnAppSuspension(Object sender, SuspendingEventArgs args)
00127         {
00128             CancelAllIoTasks();
00129         }
00130
00131         /// <summary>
00132         /// Reset the buttons when the device is reopened
00133         /// </summary>
00134         /// <param name="sender"></param>
00135         /// <param name="onDeviceConnectedEventArgs"></param>
00136         private void OnDeviceConnected(EventHandlerForDevice sender, DeviceInformation onDeviceConnectedEventArgs)
00137         {
00138             UpdateButtonStates();
00139         }
00140
00141         private async void BulkRead_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00142         {
00143             if (EventHandlerForDevice.Current.IsDeviceConnected)
00144             {
00145                 try
00146                 {
00147                     rootPage.NotifyUser("Reading...", NotifyType.StatusMessage);
00148
00149                     // We need to set this to true so that the buttons can be updated to disable the read button. We will not be able to
00150                     // update the button states until after the read completes.
00151                     runningReadTask = true;
00152                     UpdateButtonStates();
00153
00154                     // Both supported devices have the bulk in pipes on index 0
00155                     UInt32 bulkInPipeIndex = 0;
00156
00157                     // Read as much data as possible in one packet
00158                     UInt32 bytesToRead = 512;
00159
00160                     await BulkReadAsync(bulkInPipeIndex, bytesToRead, cancellationTokenSource.Token);
00161                 }
00162                 catch (OperationCanceledException /*ex*/)
00163                 {
00164                     NotifyTaskCanceled();
00165                 }
00166                 finally
00167                 {
00168                     runningReadTask = false;
00169
00170                     UpdateButtonStates();
00171                 }
00172             }
00173             else
00174             {
00175                 Utilities.NotifyDeviceNotConnected();
00176             }
00177         }
00178
00179         private async void BulkWrite_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00180         {
00181             if (EventHandlerForDevice.Current.IsDeviceConnected)
00182             {
00183                 try
00184                 {
00185                     rootPage.NotifyUser("Writing...", NotifyType.StatusMessage);
00186
00187                     // We need to set this to true so that the buttons can be updated to disable the write button. We will not be able to
00188                     // update the button states until after the write completes.
00189                     runningWriteTask = true;
00190                     UpdateButtonStates();
00191
00192                     // Both supported devices have the bulk out pipes on index 0
00193                     UInt32 bulkOutPipeIndex = 0;
00194
00195                     // Write as much data as possible in one packet
00196                     UInt32 bytesToWrite = 512;
00197
00198                     await BulkWriteAsync(bulkOutPipeIndex, bytesToWrite, cancellationTokenSource.Token);
00199                 }
00200                 catch (OperationCanceledException /*ex*/)
00201                 {
00202                     NotifyTaskCanceled();
00203                 }
00204                 finally
00205                 {
00206                     runningWriteTask = false;
00207
00208                     UpdateButtonStates();
00209                 }
00210             }
00211             else
00212             {
00213                 Utilities.NotifyDeviceNotConnected();
00214             }
00215         }
00216
00217         private async void BulkReadWrite_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00218         {
00219             if (EventHandlerForDevice.Current.IsDeviceConnected)
00220             {
00221                 try
00222                 {
00223                     rootPage.NotifyUser("Reading/Writing...", NotifyType.StatusMessage);
00224
00225                     // We need to set this to true so that the buttons can be updated to disable the read and write button,
00226                     // but enable the individual read/write buttons. We will not be able to update the button states until after the read/write completes.
00227                     runningReadWriteTask = true;
00228                     UpdateButtonStates();
00229
00230                     // Both supported devices have the bulk in/out pipes on index 0
00231                     UInt32 bulkOutPipeIndex = 0;
00232                     UInt32 bulkInPipeIndex = 0;
00233
00234                     // Write as much data as possible in one packet
00235                     UInt32 bytesToWrite = 512;
00236
00237                     // Since the read/writes go on indefinitely, we need to be able to cancel both reads and writes at the same time
00238                     await BulkReadWriteAsync(bulkInPipeIndex, bulkOutPipeIndex, bytesToWrite);
00239
00240                     // This line should not be reached unless the bulk read write stopped loops because the device was disconnected.
00241                     await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00242                         new DispatchedHandler(() =>
00243                         {
00244                             // If we navigated away from this page, do not print anything. The dispatch may be handled after
00245                             // we move to a different page.
00246                             if (!navigatedAway)
00247                             {
00248                                 rootPage.NotifyUser("Device was disconnected before we could read/write to it", NotifyType.StatusMessage);
00249                             }
00250                         }));
00251                 }
00252                 catch (OperationCanceledException /*ex*/)
00253                 {
00254                     NotifyTaskCanceled();
00255                 }
00256                 catch (AggregateException exceptions)
00257                 {
00258                     // Check to see if the reads and writes were cancelled
00259                     // If there was an exception other than a cancelled task, pass it up to caller
00260                     foreach (Exception exception in exceptions.InnerExceptions)
00261                     {
00262                         Exception realException;
00263
00264                         if (exception is AggregateException && (exception.InnerException is OperationCanceledException))
00265                         {
00266                             realException = exception.InnerException;
00267                         }
00268                         else
00269                         {
00270                             realException = exception;
00271                         }
00272
00273                         if (realException is OperationCanceledException)
00274                         {
00275                             NotifyTaskCanceled();
00276                         }
00277                         else
00278                         {
00279                             throw;
00280                         }
00281                     }
00282                 }
00283                 finally
00284                 {
00285                     // The read/write operations are no longer running
00286                     runningReadWriteTask = false;
00287
00288                     UpdateButtonStates();
00289                 }
00290             }
00291             else
00292             {
00293                 Utilities.NotifyDeviceNotConnected();
00294             }
00295         }
00296
00297         private void CancelAllIoTasks_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e)
00298         {
00299             if (EventHandlerForDevice.Current.IsDeviceConnected)
00300             {
00301                 CancelAllIoTasks();
00302             }
00303             else
00304             {
00305                 Utilities.NotifyDeviceNotConnected();
00306             }
00307         }
00308
00309         /// <summary>
00310         /// Allow for one operation at a time
00311         /// </summary>
00312         private void UpdateButtonStates()
00313         {
00314             ButtonBulkReadWrite.IsEnabled = !IsPerformingIo();
00315             ButtonBulkRead.IsEnabled = !runningReadWriteTask && !runningReadTask;
00316             ButtonBulkWrite.IsEnabled = !runningReadWriteTask && !runningWriteTask;
00317             ButtonCancelAllIoTasks.IsEnabled = IsPerformingIo();
00318         }
00319
00320         /// <summary>
00321         /// Will write garbage data to the specified output pipe. Since writing to the device may take a while to complete,
00322         /// we provide the write async with a known cancellation token to cancel any pending or running writes.
00323         ///
00324         /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be
00325         /// handled at the end of the task chain.
00326         /// </summary>
00327         /// <param name="pipeIndex">Index of pipe in the list of Device.DefaultInterface.BulkOutPipes</param>
00328         /// <param name="bytesToWrite">Bytes of garbage data to write</param>
00329         /// <param name="cancellationToken">Cancellation token to associate the task with</param>
00330         private async Task BulkWriteAsync(UInt32 bulkPipeIndex, UInt32 bytesToWrite, CancellationToken cancellationToken)
00331         {
00332             // Create an array, all default initialized to 0, and write it to the buffer
00333             // The data inside the buffer will be garbage
00334             var arrayBuffer = new Byte[bytesToWrite];
00335
00336             var stream = EventHandlerForDevice.Current.Device.DefaultInterface.BulkOutPipes[(int)bulkPipeIndex].OutputStream;
00337
00338             var writer = new DataWriter(stream);
00339             writer.WriteBytes(arrayBuffer);
00340
00341             Task<UInt32> storeAsyncTask;
00342
00343             // Don't start any IO if we canceled the task
00344             lock (cancelIoLock)
00345             {
00346                 cancellationToken.ThrowIfCancellationRequested();
00347
00348                 // This is where the data is flushed out to the device.
00349                 //
00350                 // Cancellation Token will be used so we can stop the task operation explicitly
00351                 // The completion function should still be called so that we can properly handle a canceled task
00352                 storeAsyncTask = writer.StoreAsync().AsTask(cancellationToken);
00353             }
00354
00355             UInt32 bytesWritten = await storeAsyncTask;
00356
00357             totalBytesWritten += bytesWritten;
00358
00359             PrintTotalReadWriteBytes();
00360         }
00361
00362         /// <summary>
00363         /// Will read data from the specified input pipe. The data being read is garbage data because the samples devices are giving us garbage data.
00364         /// We use cancellation tokens to cancel reads that are pending or running.
00365         ///
00366         /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be
00367         /// handled at the end of the task chain.
00368         /// </summary>
00369         /// <param name="pipeIndex">Index of pipe in the list of Device.DefaultInterface.BulkInPipes</param>
00370         /// <param name="bytesToRead">Bytes of garbage data to read</param>
00371         /// <param name="cancellationToken">Cancellation token to associate the task with</param>
00372         private async Task BulkReadAsync(UInt32 bulkPipeIndex, UInt32 bytesToRead, CancellationToken cancellationToken)
00373         {
00374             var stream = EventHandlerForDevice.Current.Device.DefaultInterface.BulkInPipes[(int)bulkPipeIndex].InputStream;
00375
00376             DataReader reader = new DataReader(stream);
00377
00378             Task<UInt32> loadAsyncTask;
00379
00380             // Don't start any IO if we canceled the task
00381             lock (cancelIoLock)
00382             {
00383                 cancellationToken.ThrowIfCancellationRequested();
00384
00385                 // Cancellation Token will be used so we can stop the task operation explicitly
00386                 // The completion function should still be called so that we can properly handle a canceled task
00387                 loadAsyncTask = reader.LoadAsync(bytesToRead).AsTask(cancellationToken);
00388             }
00389
00390             UInt32 bytesRead = await loadAsyncTask;
00391
00392             totalBytesRead += bytesRead;
00393
00394             PrintTotalReadWriteBytes();
00395
00396             // The data that is read is stored in the reader object
00397             // e.g. To read a string from the buffer:
00398             // reader.ReadString(bytesRead);
00399         }
00400
00401         /// <summary>
00402         /// A read and a write will be initiated simultaneously. Reads and writes are looped; after each read/write succeeds, another read/write is initiated.
00403         ///
00404         /// We will check if the task has been canceled and if it is, we'll throw an exception because custom made tasks are expected
00405         /// to do so. We cannot rely on BulkReadAsync and BulkWriteAsync to throw task cancelled exceptions because they may complete
00406         /// before the task cancellation takes place.
00407         ///
00408         /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be
00409         /// handled at the end of the task chain.
00410         /// </summary>
00411         /// <param name="bulkInPipeIndex">Index of pipe in the list of Device.DefaultInterface.BulkInPipes</param>
00412         /// <param name="bulkOutPipeIndex">Index of pipe in the list of Device.DefaultInterface.BulkOutPipes</param>
00413         /// <param name="bytesToReadWrite">Bytes of garbage data to read/write</param>
00414         private async Task BulkReadWriteAsync(UInt32 bulkInPipeIndex, UInt32 bulkOutPipeIndex, UInt32 bytesToReadWrite)
00415         {
00416             // A parent task that will wait for the read write child tasks to compelete before this task completes
00417             await Task.Factory.StartNew(() =>
00418             {
00419                 // Save the cancellation token now in case the cancellationTokenSource is reset while IO is going on.
00420                 var cancellationToken = cancellationTokenSource.Token;
00421
00422                 // Loop reads
00423                 var readTask = Task.Factory.StartNew(() =>
00424                 {
00425                     // Keep reading until the task is cancelled
00426                     while (!cancellationTokenSource.IsCancellationRequested && EventHandlerForDevice.Current.IsDeviceConnected)
00427                     {
00428                         // Read and do not continue until it is finished
00429                         BulkReadAsync(bulkInPipeIndex, bytesToReadWrite, cancellationToken).Wait();
00430                     }
00431                 }, cancellationTokenSource.Token, TaskCreationOptions.AttachedToParent, TaskScheduler.Current);
00432
00433                 // loop writes
00434                 var writeTask = Task.Factory.StartNew(() =>
00435                 {
00436                     // Keep writing until the task is cancelled
00437                     while (!cancellationTokenSource.IsCancellationRequested && EventHandlerForDevice.Current.IsDeviceConnected)
00438                     {
00439                         // Write and do not continue until it is finished
00440                         BulkWriteAsync(bulkOutPipeIndex, bytesToReadWrite, cancellationToken).Wait();
00441                     }
00442                 }, cancellationTokenSource.Token, TaskCreationOptions.AttachedToParent, TaskScheduler.Current);
00443
00444             });
00445         }
00446
00447         /// <summary>
00448         /// It is important to be able to cancel tasks that may take a while to complete. Canceling tasks is the only way to stop any pending IO
00449         /// operations asynchronously. If the UsbDevice is closed/deleted while there are pending IOs, the destructor will cancel all pending IO
00450         /// operations.
00451         /// </summary>
00452         private void CancelAllIoTasks()
00453         {
00454             lock (cancelIoLock)
00455             {
00456                 if (!cancellationTokenSource.IsCancellationRequested)
00457                 {
00458                     cancellationTokenSource.Cancel();
00459
00460                     // Existing IO already has a local copy of the old cancellation token so this reset won't affect it
00461                     ResetCancellationTokenSource();
00462                 }
00463             }
00464         }
00465
00466         /// <summary>
00467         /// Determines if we are reading, writing, or reading and writing.
00468         /// </summary>
00469         /// <returns>If we are doing any of the above operations, we return true; false otherwise</returns>
00470         private Boolean IsPerformingIo()
00471         {
00472             return (runningReadTask || runningWriteTask || runningReadWriteTask);
00473         }
00474
00475         private async void PrintTotalReadWriteBytes()
00476         {
00477             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low,
00478                 new DispatchedHandler(() =>
00479                 {
00480                     // If we navigated away from this page, do not print anything. The dispatch may be handled after
00481                     // we move to a different page.
00482                     if (!navigatedAway)
00483                     {
00484                         rootPage.NotifyUser(
00485                             "Total bytes read: " + totalBytesRead.ToString("D", NumberFormatInfo.InvariantInfo) + "; Total bytes written: "
00486                             + totalBytesWritten.ToString("D", NumberFormatInfo.InvariantInfo), NotifyType.StatusMessage);
00487                     }
00488                 }));
00489         }
00490
00491         private void ResetCancellationTokenSource()
00492         {
00493             // Create a new cancellation token source so that can cancel all the tokens again
00494             cancellationTokenSource = new CancellationTokenSource();
00495
00496             // Hook the cancellation callback (called whenever Task.cancel is called)
00497             cancellationTokenSource.Token.Register(() => NotifyCancelingTask());
00498         }
00499
00500         /// <summary>
00501         /// Print a status message saying we are canceling a task and disable all buttons to prevent multiple cancel requests.
00502         /// <summary>
00503         private async void NotifyCancelingTask()
00504         {
00505             // Setting the dispatcher priority to high allows the UI to handle disabling of all the buttons
00506             // before any of the IO completion callbacks get a chance to modify the UI; that way this method
00507             // will never get the opportunity to overwrite UI changes made by IO callbacks
00508             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.High,
00509                 new DispatchedHandler(() =>
00510                 {
00511                     ButtonBulkRead.IsEnabled = false;
00512                     ButtonBulkWrite.IsEnabled = false;
00513                     ButtonBulkReadWrite.IsEnabled = false;
00514                     ButtonCancelAllIoTasks.IsEnabled = false;
00515
00516                     if (!navigatedAway)
00517                     {
00518                         rootPage.NotifyUser("Canceling task... Please wait...", NotifyType.StatusMessage);
00519                     }
00520                 }));
00521         }
00522
00523         /// <summary>
00524         /// Notifies the UI that the operation has been cancelled
00525         /// </summary>
00526         private async void NotifyTaskCanceled()
00527         {
00528             await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00529                 new DispatchedHandler(() =>
00530                 {
00531                     if (!navigatedAway)
00532                     {
00533                         rootPage.NotifyUser("The read or write operation has been cancelled", NotifyType.StatusMessage);
00534                     }
00535                 }));
00536         }
00537     }
00538 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ItemsDataProvider Member List

This is the complete list of members for ItemsDataProvider, including all inherited members.
GetAll(int max_results) | ItemsDataProvider | [pure virtual]
GetFromID(string ID) | ItemsDataProvider | [pure virtual]
GetRandomVideo() | ItemsDataProvider | [pure virtual]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisablingScreenCapture/cppwinrt/Scenario2_Disable.cpp Source File

  • DisablingScreenCapture
  • cppwinrt

Scenario2_Disable.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Disable.h"
00014 #include "Scenario2_Disable.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace winrt::Windows::Foundation;
00018 using namespace winrt::Windows::UI::Xaml;
00019 using namespace winrt::Windows::UI::Xaml::Navigation;
00020
00021 namespace winrt::SDKTemplate::implementation
00022 {
00023     Scenario2_Disable::Scenario2_Disable()
00024     {
00025         InitializeComponent();
00026     }
00027
00028     void Scenario2_Disable::OnNavigatedTo(NavigationEventArgs const&)
00029     {
00030         // Disable screen capture when the user navigates to this page.
00031         Windows::UI::ViewManagement::ApplicationView::GetForCurrentView().IsScreenCaptureEnabled(false);
00032     }
00033
00034     void Scenario2_Disable::OnNavigatedFrom(NavigationEventArgs const&)
00035     {
00036         // Re-enable screen capture when the user navigates away from this page.
00037         Windows::UI::ViewManagement::ApplicationView::GetForCurrentView().IsScreenCaptureEnabled(true);
00038     }
00039 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFont/Scenario_Document3.xaml.h Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFont

Scenario_Document3.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario_Document3.g.h"
00015 #include "MainPage.xaml.h"
00016 #include "DocumentPresenter.h"
00017
00018
00019 namespace SDKTemplate
00020 {
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class Scenario_Document3 sealed
00023     {
00024     public:
00025         Scenario_Document3();
00026
00027     protected:
00028         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029
00030     private:
00031         DocumentPresenter^                              m_documentPresenter;
00032
00033         void TextLayoutFrame_SizeChanged(Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e);
00034     };
00035 }
Generated on Fri Nov 15 2024 22:19:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/Validation.cpp Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

Validation.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "StspDefs.h"
00010
00011 namespace
00012 {
00013     // Function validating just a type of the data.
00014     template <VARTYPE vt>
00015     bool ValidateDataType(PROPVARIANT *pValue)
00016     {
00017         return (pValue->vt == vt);
00018     }
00019
00020     // Function validating a BLOB apart from the type it checks the size as well.
00021     bool ValidateBlob(PROPVARIANT *pValue)
00022     {
00023         return ValidateDataType<MF_ATTRIBUTE_BLOB>(pValue) && pValue->caub.cElems < 128;
00024     }
00025
00026     // Description of an attribute for validation
00027     struct AttributeValidationDescriptor
00028     {
00029         REFGUID guidKey;
00030         bool (*IsValid)(PROPVARIANT *pValue);
00031     };
00032
00033     // Description of an media type for validation
00034     struct MediaTypeValidationDescriptor
00035     {
00036         GUID guidSubtype;
00037         bool fVideo;
00038         size_t cAttributes;
00039         const AttributeValidationDescriptor *attributes;
00040     };
00041
00042     // Valid attibutes for H.264 decoder.
00043     const AttributeValidationDescriptor H264ValidAttributes[] = {
00044         {MF_MT_FRAME_SIZE, ValidateDataType<MF_ATTRIBUTE_UINT64>},
00045         {MF_MT_AVG_BITRATE, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00046         {MF_MT_MPEG_SEQUENCE_HEADER, ValidateBlob},
00047         {MF_MT_MPEG2_PROFILE, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00048         {MF_MT_FRAME_RATE, ValidateDataType<MF_ATTRIBUTE_UINT64>},
00049         {MF_MT_PIXEL_ASPECT_RATIO, ValidateDataType<MF_ATTRIBUTE_UINT64>},
00050         {MF_MT_INTERLACE_MODE, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00051     };
00052
00053     // Valid attributes for AAC decoder
00054     const AttributeValidationDescriptor AACValidAttributes[] = {
00055         {MF_MT_AUDIO_AVG_BYTES_PER_SECOND, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00056         {MF_MT_AVG_BITRATE, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00057         {MF_MT_AUDIO_BLOCK_ALIGNMENT, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00058         {MF_MT_AUDIO_NUM_CHANNELS, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00059         {MF_MT_COMPRESSED, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00060         {MF_MT_AUDIO_SAMPLES_PER_SECOND, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00061         {MF_MT_AAC_AUDIO_PROFILE_LEVEL_INDICATION, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00062         {MF_MT_AUDIO_PREFER_WAVEFORMATEX, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00063         {MF_MT_USER_DATA, ValidateDataType<MF_ATTRIBUTE_BLOB>},
00064         {MF_MT_FIXED_SIZE_SAMPLES, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00065         {MF_MT_AAC_PAYLOAD_TYPE, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00066         {MF_MT_AUDIO_BITS_PER_SAMPLE, ValidateDataType<MF_ATTRIBUTE_UINT32>},
00067     };
00068
00069     // List of valid media types.
00070     const MediaTypeValidationDescriptor ValidMediaTypes[] = {
00071         {MFVideoFormat_H264, true, _countof(H264ValidAttributes), H264ValidAttributes},
00072         {MFAudioFormat_AAC, false, _countof(AACValidAttributes), AACValidAttributes}
00073     };
00074
00075     // Finds media type desciptor based on major type and subtype.
00076     const MediaTypeValidationDescriptor *FindMediaTypeDescriptor(REFGUID guidMajorType, REFGUID guidSubtype)
00077     {
00078         for (UINT32 nIndex = 0; nIndex < _countof(ValidMediaTypes); ++nIndex)
00079         {
00080             if (ValidMediaTypes[nIndex].guidSubtype == guidSubtype &&
00081                 ((guidMajorType == MFMediaType_Video && ValidMediaTypes[nIndex].fVideo) ||
00082                 (guidMajorType == MFMediaType_Audio && !ValidMediaTypes[nIndex].fVideo)))
00083             {
00084                 return &ValidMediaTypes[nIndex];
00085             }
00086         }
00087
00088         return nullptr;
00089     }
00090
00091     // Checks if attribute is valid for a given media type. If it returns FALSE attrubute is optional and shouldn't be used during communication
00092     // between sink and source, if it returns error it means that attribute is correct but its value is somehow corrupted.
00093     bool IsAttributeValid(const MediaTypeValidationDescriptor *validationDescriptor, REFGUID guidKey, PROPVARIANT *pValue)
00094     {
00095         bool isValid = false;
00096
00097         for (UINT32 nIndex = 0; nIndex < validationDescriptor->cAttributes; ++nIndex)
00098         {
00099             if (validationDescriptor->attributes[nIndex].guidKey == guidKey)
00100             {
00101                 if (validationDescriptor->attributes[nIndex].IsValid(pValue))
00102                 {
00103                     isValid = true;
00104                 }
00105                 else
00106                 {
00107                    ThrowIfError(MF_E_INVALIDMEDIATYPE);
00108                 }
00109                 break;
00110             }
00111         }
00112
00113         return isValid;
00114     }
00115 }
00116
00117 // Filters media type's attribute before they can be sent over the network.
00118 void Microsoft::Samples::SimpleCommunication::FilterOutputMediaType(IMFMediaType *pSourceMediaType, IMFMediaType *pDestinationMediaType)
00119 {
00120     HRESULT hr = S_OK;
00121     GUID guidMajorType;
00122     GUID guidSubtype;
00123     const MediaTypeValidationDescriptor *typeDescriptor = nullptr;
00124
00125     ThrowIfError(pSourceMediaType->GetMajorType(&guidMajorType));
00126
00127     ThrowIfError(pSourceMediaType->GetGUID(MF_MT_SUBTYPE, &guidSubtype));
00128
00129     typeDescriptor = FindMediaTypeDescriptor(guidMajorType, guidSubtype);
00130
00131     // Not a valid media type
00132     if (typeDescriptor == nullptr)
00133     {
00134         Throw(MF_E_INVALIDMEDIATYPE);
00135     }
00136
00137     UINT32 cAttributes = 0;
00138     pSourceMediaType->GetCount(&cAttributes);
00139
00140     // Remove optional and not necessary attributes.
00141     for (UINT32 nIndex = 0; nIndex < cAttributes; ++nIndex)
00142     {
00143         GUID guidKey;
00144         PROPVARIANT val;
00145         Exception ^error = nullptr;
00146         PropVariantInit(&val);
00147         ThrowIfError(pSourceMediaType->GetItemByIndex(nIndex, &guidKey, &val));
00148         try
00149         {
00150             if (IsAttributeValid(typeDescriptor, guidKey, &val))
00151             {
00152                 // Copy only attributes that can be sent otherwise skip it.
00153                 ThrowIfError(pDestinationMediaType->SetItem(guidKey, val));
00154             }
00155         }
00156         catch(Exception ^exc)
00157         {
00158             error = exc;
00159         }
00160
00161         PropVariantClear(&val);
00162         if (error != nullptr)
00163         {
00164             throw error;
00165         }
00166     }
00167 }
00168
00169 // Used to validate media type after receiving it from the network.
00170 void Microsoft::Samples::SimpleCommunication::ValidateInputMediaType(REFGUID guidMajorType, REFGUID guidSubtype, IMFMediaType *pMediaType)
00171 {
00172     const MediaTypeValidationDescriptor *typeDescriptor = FindMediaTypeDescriptor(guidMajorType, guidSubtype);
00173
00174     if (typeDescriptor == nullptr)
00175     {
00176         Throw(MF_E_INVALIDMEDIATYPE);
00177     }
00178
00179     UINT32 cAttributes = 0;
00180     pMediaType->GetCount(&cAttributes);
00181
00182     for (UINT32 nIndex = 0; nIndex < cAttributes; ++nIndex)
00183     {
00184         Exception ^error = nullptr;
00185         GUID guidKey;
00186         PROPVARIANT val;
00187         PropVariantInit(&val);
00188
00189         ThrowIfError(pMediaType->GetItemByIndex(nIndex, &guidKey, &val));
00190         try
00191         {
00192             if (!IsAttributeValid(typeDescriptor, guidKey, &val))
00193             {
00194                 ThrowIfError(MF_E_INVALIDMEDIATYPE);
00195             }
00196         }
00197         catch(Exception ^exc)
00198         {
00199             error = exc;
00200         }
00201
00202         PropVariantClear(&val);
00203         if (error != nullptr)
00204         {
00205             throw error;
00206         }
00207     }
00208 }
Generated on Fri Nov 15 2024 22:21:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Trim Member List

This is the complete list of members for Scenario3_Trim, including all inherited members.
_c_sec0 | Scenario3_Trim | [private]
_c_sec1 | Scenario3_Trim | [private]
_cts | Scenario3_Trim | [private]
_dispatcher | Scenario3_Trim | [private]
_InputFile | Scenario3_Trim | [private]
_OutputFile | Scenario3_Trim | [private]
_OutputFileExtension | Scenario3_Trim | [private]
_OutputFileName | Scenario3_Trim | [private]
_OutputType | Scenario3_Trim | [private]
_Profile | Scenario3_Trim | [private]
_Start | Scenario3_Trim | [private]
_Stop | Scenario3_Trim | [private]
_Transcoder | Scenario3_Trim | [private]
DisableButtons() | Scenario3_Trim | [inline, private]
DisableNonSquarePARProfiles() | Scenario3_Trim | [inline, private]
Dispose() | Scenario3_Trim | [inline]
EnableButtons() | Scenario3_Trim | [inline, private]
EnableNonSquarePARProfiles() | Scenario3_Trim | [inline, private]
GetPresetProfile(ComboBox combobox) | Scenario3_Trim | [inline, private]
InputPauseButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3_Trim | [inline, private]
InputPlayButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3_Trim | [inline, private]
InputStopButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3_Trim | [inline, private]
MarkIn(Object sender, RoutedEventArgs e) | Scenario3_Trim | [inline, private]
MarkOut(Object sender, RoutedEventArgs e) | Scenario3_Trim | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_Trim | [inline, protected]
OnTargetFormatChanged(object sender, SelectionChangedEventArgs e) | Scenario3_Trim | [inline, private]
OutputPathText(string text) | Scenario3_Trim | [inline, private]
OutputPauseButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3_Trim | [inline, private]
OutputPlayButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3_Trim | [inline, private]
OutputStopButton_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3_Trim | [inline, private]
OutputText(string text) | Scenario3_Trim | [inline, private]
PickFile(object sender, RoutedEventArgs e) | Scenario3_Trim | [inline, private]
PickOutput(object sender, RoutedEventArgs e) | Scenario3_Trim | [inline, private]
PlayFile(Windows.Storage.StorageFile MediaFile) | Scenario3_Trim | [inline, private]
rootPage | Scenario3_Trim | [private]
Scenario3_Trim() | Scenario3_Trim | [inline]
SetCancelButton(bool isEnabled) | Scenario3_Trim | [inline, private]
SetOutputFileButton(bool isEnabled) | Scenario3_Trim | [inline, private]
SetPickFileButton(bool isEnabled) | Scenario3_Trim | [inline, private]
SetTranscodeButton(bool isEnabled) | Scenario3_Trim | [inline, private]
StopPlayers() | Scenario3_Trim | [inline, private]
TranscodeCancel(object sender, RoutedEventArgs e) | Scenario3_Trim | [inline, private]
TranscodeComplete() | Scenario3_Trim | [inline, private]
TranscodeError(string error) | Scenario3_Trim | [inline, private]
TranscodeFailure(TranscodeFailureReason reason) | Scenario3_Trim | [inline, private]
TranscodeProgress(double percent) | Scenario3_Trim | [inline, private]
TranscodeTrim(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3_Trim | [inline, private]
Generated on Fri Nov 15 2024 22:23:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cppwinrt/OtherScenarios.cpp Source File

  • Clipboard
  • cppwinrt

OtherScenarios.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SampleConfiguration.h"
00014 #include "OtherScenarios.h"
00015 #include "OtherScenarios.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::ApplicationModel::DataTransfer;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     bool OtherScenarios::registerContentChanged = false;
00028
00029     OtherScenarios::OtherScenarios()
00030     {
00031         InitializeComponent();
00032     }
00033
00034     void OtherScenarios::OnNavigatedTo(NavigationEventArgs const&)
00035     {
00036         RegisterClipboardContentChanged().IsChecked(registerContentChanged);
00037     }
00038
00039     void OtherScenarios::ShowFormatButton_Click(IInspectable const&, RoutedEventArgs const&)
00040     {
00041         DisplayFormats();
00042     }
00043
00044     void OtherScenarios::EmptyClipboardButton_Click(IInspectable const&, RoutedEventArgs const&)
00045     {
00046         try
00047         {
00048             Clipboard::Clear();
00049         }
00050         catch (hresult_error const& ex)
00051         {
00052             rootPage.NotifyUser(L"Error emptying clipboard: " + ex.message() + L". Try again", NotifyType::ErrorMessage);
00053         }
00054     }
00055
00056     void OtherScenarios::RegisterClipboardContentChanged_Click(IInspectable const&, RoutedEventArgs const&)
00057     {
00058         bool checked = RegisterClipboardContentChanged().IsChecked().Value();
00059         if (registerContentChanged != checked)
00060         {
00061             registerContentChanged = checked;
00062             ClearOutput();
00063
00064             // In this sample, we register for Clipboard update notifications on the MainPage so that we can
00065             // navigate between scenarios and still receive updates. The sample also registers for window activated
00066             // notifications since the app needs to be in the foreground to access the clipboard. Once we receive
00067             // a clipboard update notification, we display the new content (if the app is in the foreground). If the
00068             // sample is not in the foreground, we defer displaying it until it is.
00069             SampleState::EnableClipboardContentChangedNotifications(registerContentChanged);
00070             if (registerContentChanged)
00071             {
00072                 OutputText().Text(L"Successfully registered for clipboard update notification.");
00073             }
00074             else
00075             {
00076                 OutputText().Text(L"Successfully un-registered for clipboard update notification.");
00077             }
00078         }
00079     }
00080
00081     void OtherScenarios::ClearOutputButton_Click(IInspectable const&, RoutedEventArgs const&)
00082     {
00083         ClearOutput();
00084     }
00085
00086     void OtherScenarios::ClearOutput()
00087     {
00088         rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00089         OutputText().Text(L"");
00090     }
00091
00092     void OtherScenarios::DisplayFormats()
00093     {
00094         rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00095         OutputText().Text(SampleState::BuildClipboardFormatsOutputString());
00096     }
00097 }
00098
Generated on Fri Nov 15 2024 22:18:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cpp/App.xaml.h Source File

  • 360VideoPlayback
  • cpp

App.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // App.xaml.h
00003 // Declaration of the App class.
00004 //
00005
00006 #pragma once
00007
00008 #include "App.g.h"
00009
00010 namespace _360VideoPlayback
00011 {
00012     /// <summary>
00013     /// Provides application-specific behavior to supplement the default Application class.
00014     /// </summary>
00015     ref class App sealed
00016     {
00017     protected:
00018         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override;
00019
00020     internal:
00021         App();
00022
00023     private:
00024         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
00025         void OnNavigationFailed(Platform::Object^ sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs^ e);
00026     };
00027 }
Generated on Fri Nov 15 2024 22:16:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/pch.cpp Source File

  • Simple3DGameDX
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/pch.cpp Source File

  • WindowsAudioSession
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameRenderer.cpp Source File

  • Simple3DGameDX
  • cppwinrt

GameRenderer.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "GameRenderer.h"
00014 #include "TargetTexture.h"
00015 #include "BasicLoader.h"
00016 #include "CylinderMesh.h"
00017 #include "FaceMesh.h"
00018 #include "SphereMesh.h"
00019 #include "WorldMesh.h"
00020 #include "Face.h"
00021 #include "Cylinder.h"
00022
00023 using namespace DirectX;
00024 using namespace winrt::Windows::Foundation;
00025
00026 GameRenderer::GameRenderer(std::shared_ptr<DX::DeviceResources> const& deviceResources) :
00027     m_deviceResources(deviceResources),
00028     m_initialized(false),
00029     m_gameResourcesLoaded(false),
00030     m_levelResourcesLoaded(false),
00031     m_gameInfoOverlay(deviceResources),
00032     m_gameHud(deviceResources, L"Windows platform samples", L"DirectX first-person game sample")
00033 {
00034     CreateDeviceDependentResources();
00035     CreateWindowSizeDependentResources();
00036 }
00037
00038 void GameRenderer::ReleaseDeviceDependentResources()
00039 {
00040     // On device lost all the device resources are invalid.
00041     // Set the state of the renderer to not have a pointer to the
00042     // Simple3DGame object. It will be reset as a part of the
00043     // game devices resources being recreated.
00044     m_game = nullptr;
00045     m_gameHud.ReleaseDeviceDependentResources();
00046     m_gameInfoOverlay.ReleaseDeviceDependentResources();
00047 }
00048
00049 void GameRenderer::CreateDeviceDependentResources()
00050 {
00051     m_gameResourcesLoaded = false;
00052     m_levelResourcesLoaded = false;
00053
00054     m_gameHud.CreateDeviceDependentResources();
00055     m_gameInfoOverlay.CreateDeviceDependentResources();
00056 }
00057
00058 void GameRenderer::CreateWindowSizeDependentResources()
00059 {
00060     m_gameHud.CreateWindowSizeDependentResources();
00061
00062     m_gameInfoOverlaySize.height = GameInfoOverlayConstant::Height;
00063     m_gameInfoOverlaySize.width = GameInfoOverlayConstant::Width;
00064
00065     auto d3dContext = m_deviceResources->GetD3DDeviceContext();
00066     auto renderTargetSize = m_deviceResources->GetRenderTargetSize();
00067
00068     auto bounds = m_deviceResources->GetLogicalSize();
00069     float hudBottomY = GameUIConstants::HudTopOffset + (GameUIConstants::HudBodyPointSize + GameUIConstants::Margin) * 4;
00070     float topY = (bounds.Height - GameInfoOverlayConstant::Height) / 2.0f;
00071
00072     // The default position of the GameInfoOverlay is centered in the window. There are cases where
00073     // There are cases where this will be adjusted:
00074     // 1) Shift down to allow the Hud to be visible if possible.
00075     // 2) Shift up if after 1) the GameInfoOverlay extends below the bottom of the window.
00076     // 3) Ensure the width of the GameInfoOverlay is not wider than the window, if it is
00077     //    reduce the width to be the same as the window width.
00078     if (hudBottomY > topY)
00079     {
00080         topY = hudBottomY + GameUIConstants::Margin;
00081     }
00082     if ((topY + m_gameInfoOverlaySize.height) > bounds.Height)
00083     {
00084         topY = bounds.Height - m_gameInfoOverlaySize.height;
00085     }
00086     if (m_gameInfoOverlaySize.width > bounds.Width)
00087     {
00088         m_gameInfoOverlaySize.width = bounds.Width;
00089     }
00090     float topX = (bounds.Width - m_gameInfoOverlaySize.width) / 2.0f;
00091
00092     m_gameInfoOverlayRect = D2D1::RectF(
00093         topX,
00094         topY,
00095         topX + m_gameInfoOverlaySize.width,
00096         topY + m_gameInfoOverlaySize.height
00097         );
00098
00099     m_gameInfoOverlay.CreateWindowSizeDependentResources(m_gameInfoOverlaySize);
00100
00101     if (m_game != nullptr)
00102     {
00103         // Update the Projection Matrix and the associated Constant Buffer.
00104         m_game->GameCamera().SetProjParams(
00105             XM_PI / 2, renderTargetSize.Width / renderTargetSize.Height,
00106             0.01f,
00107             100.0f
00108             );
00109
00110         XMFLOAT4X4 orientation = m_deviceResources->GetOrientationTransform3D();
00111
00112         ConstantBufferChangeOnResize changesOnResize;
00113         XMStoreFloat4x4(
00114             &changesOnResize.projection,
00115             XMMatrixMultiply(
00116                 XMMatrixTranspose(m_game->GameCamera().Projection()),
00117                 XMMatrixTranspose(XMLoadFloat4x4(&orientation))
00118                 )
00119             );
00120
00121         d3dContext->UpdateSubresource(
00122             m_constantBufferChangeOnResize.get(),
00123             0,
00124             nullptr,
00125             &changesOnResize,
00126             0,
00127             0
00128             );
00129     }
00130 }
00131
00132 IAsyncAction GameRenderer::CreateGameDeviceResourcesAsync(_In_ std::shared_ptr<Simple3DGame> game)
00133 {
00134     auto lifetime = shared_from_this();
00135
00136     // Create the device dependent game resources.
00137     // Only the d3dDevice is used in this method. It is expected
00138     // to not run on the same thread as the GameRenderer was created.
00139     // Create methods on the d3dDevice are free-threaded and are safe while any methods
00140     // in the d3dContext should only be used on a single thread and handled
00141     // in the FinalizeCreateGameDeviceResources method.
00142     m_game = game;
00143
00144     auto d3dDevice = m_deviceResources->GetD3DDevice();
00145
00146     D3D11_BUFFER_DESC bd;
00147     ZeroMemory(&bd, sizeof(bd));
00148
00149     // Create the constant buffers.
00150     bd.Usage = D3D11_USAGE_DEFAULT;
00151     bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
00152     bd.CPUAccessFlags = 0;
00153     bd.ByteWidth = (sizeof(ConstantBufferNeverChanges) + 15) / 16 * 16;
00154     m_constantBufferNeverChanges = nullptr;
00155     winrt::check_hresult(
00156         d3dDevice->CreateBuffer(&bd, nullptr, m_constantBufferNeverChanges.put())
00157         );
00158
00159     bd.ByteWidth = (sizeof(ConstantBufferChangeOnResize) + 15) / 16 * 16;
00160     m_constantBufferChangeOnResize = nullptr;
00161     winrt::check_hresult(
00162         d3dDevice->CreateBuffer(&bd, nullptr, m_constantBufferChangeOnResize.put())
00163         );
00164
00165     bd.ByteWidth = (sizeof(ConstantBufferChangesEveryFrame) + 15) / 16 * 16;
00166     m_constantBufferChangesEveryFrame = nullptr;
00167     winrt::check_hresult(
00168         d3dDevice->CreateBuffer(&bd, nullptr, m_constantBufferChangesEveryFrame.put())
00169         );
00170
00171     bd.ByteWidth = (sizeof(ConstantBufferChangesEveryPrim) + 15) / 16 * 16;
00172     m_constantBufferChangesEveryPrim = nullptr;
00173     winrt::check_hresult(
00174         d3dDevice->CreateBuffer(&bd, nullptr, m_constantBufferChangesEveryPrim.put())
00175         );
00176
00177     D3D11_SAMPLER_DESC sampDesc;
00178     ZeroMemory(&sampDesc, sizeof(sampDesc));
00179
00180     sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
00181     sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
00182     sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
00183     sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
00184     sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
00185     sampDesc.MinLOD = 0;
00186     sampDesc.MaxLOD = FLT_MAX;
00187     m_samplerLinear = nullptr;
00188     winrt::check_hresult(
00189         d3dDevice->CreateSamplerState(&sampDesc, m_samplerLinear.put())
00190         );
00191
00192     // Start the async tasks to load the shaders and textures.
00193     BasicLoader loader{ d3dDevice };
00194
00195     std::vector<IAsyncAction> tasks;
00196
00197     uint32_t numElements = ARRAYSIZE(PNTVertexLayout);
00198     tasks.push_back(loader.LoadShaderAsync(L"VertexShader.cso", PNTVertexLayout, numElements, m_vertexShader.put(), m_vertexLayout.put()));
00199     tasks.push_back(loader.LoadShaderAsync(L"VertexShaderFlat.cso", nullptr, numElements, m_vertexShaderFlat.put(), nullptr));
00200     tasks.push_back(loader.LoadShaderAsync(L"PixelShader.cso", m_pixelShader.put()));
00201     tasks.push_back(loader.LoadShaderAsync(L"PixelShaderFlat.cso", m_pixelShaderFlat.put()));
00202
00203     // Make sure the previous versions if any of the textures are released.
00204     m_sphereTexture = nullptr;
00205     m_cylinderTexture = nullptr;
00206     m_ceilingTexture = nullptr;
00207     m_floorTexture = nullptr;
00208     m_wallsTexture = nullptr;
00209
00210     // Load Game specific textures.
00211     tasks.push_back(loader.LoadTextureAsync(L"Assets\\seafloor.dds", nullptr, m_sphereTexture.put()));
00212     tasks.push_back(loader.LoadTextureAsync(L"Assets\\metal_texture.dds", nullptr, m_cylinderTexture.put()));
00213     tasks.push_back(loader.LoadTextureAsync(L"Assets\\cellceiling.dds", nullptr, m_ceilingTexture.put()));
00214     tasks.push_back(loader.LoadTextureAsync(L"Assets\\cellfloor.dds", nullptr, m_floorTexture.put()));
00215     tasks.push_back(loader.LoadTextureAsync(L"Assets\\cellwall.dds", nullptr, m_wallsTexture.put()));
00216
00217     // Simulate loading additional resources by introducing a delay.
00218     tasks.push_back([]() -> IAsyncAction { co_await winrt::resume_after(GameConstants::InitialLoadingDelay); }());
00219
00220     // Wait for all the tasks to complete.
00221     for (auto&& task : tasks)
00222     {
00223         co_await task;
00224     }
00225 }
00226
00227 void GameRenderer::FinalizeCreateGameDeviceResources()
00228 {
00229     // All asynchronously loaded resources have completed loading.
00230     // Now associate all the resources with the appropriate game objects.
00231     // This method is expected to run in the same thread as the GameRenderer
00232     // was created. All work will happen behind the "Loading ..." screen after the
00233     // main loop has been entered.
00234
00235     // Initialize the Constant buffer with the light positions
00236     // These are handled here to ensure that the d3dContext is only
00237     // used in one thread.
00238
00239     auto d3dDevice = m_deviceResources->GetD3DDevice();
00240
00241     ConstantBufferNeverChanges constantBufferNeverChanges;
00242     constantBufferNeverChanges.lightPosition[0] = XMFLOAT4(3.5f, 2.5f, 5.5f, 1.0f);
00243     constantBufferNeverChanges.lightPosition[1] = XMFLOAT4(3.5f, 2.5f, -5.5f, 1.0f);
00244     constantBufferNeverChanges.lightPosition[2] = XMFLOAT4(-3.5f, 2.5f, -5.5f, 1.0f);
00245     constantBufferNeverChanges.lightPosition[3] = XMFLOAT4(3.5f, 2.5f, 5.5f, 1.0f);
00246     constantBufferNeverChanges.lightColor = XMFLOAT4(0.25f, 0.25f, 0.25f, 1.0f);
00247     m_deviceResources->GetD3DDeviceContext()->UpdateSubresource(
00248         m_constantBufferNeverChanges.get(),
00249         0,
00250         nullptr,
00251         &constantBufferNeverChanges,
00252         0,
00253         0
00254         );
00255
00256     // For the targets, there are two unique generated textures.
00257     // Each texture image includes the number of the texture.
00258     // Make sure the 2D rendering is occurring on the same thread
00259     // as the main rendering.
00260
00261     TargetTexture textureGenerator(
00262         d3dDevice,
00263         m_deviceResources->GetD2DFactory(),
00264         m_deviceResources->GetDWriteFactory(),
00265         m_deviceResources->GetD2DDeviceContext()
00266         );
00267
00268     auto cylinderMesh = std::make_shared<CylinderMesh>(d3dDevice, (uint16_t)26);
00269     auto targetMesh = std::make_shared<FaceMesh>(d3dDevice);
00270     auto sphereMesh = std::make_shared<SphereMesh>(d3dDevice, (uint16_t)26);
00271
00272     auto cylinderMaterial = std::make_shared<Material>(
00273         XMFLOAT4(0.8f, 0.8f, 0.8f, .5f),
00274         XMFLOAT4(0.8f, 0.8f, 0.8f, .5f),
00275         XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f),
00276         15.0f,
00277         m_cylinderTexture.get(),
00278         m_vertexShader.get(),
00279         m_pixelShader.get()
00280         );
00281
00282     auto sphereMaterial = std::make_shared<Material>(
00283         XMFLOAT4(0.8f, 0.4f, 0.0f, 1.0f),
00284         XMFLOAT4(0.8f, 0.4f, 0.0f, 1.0f),
00285         XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f),
00286         50.0f,
00287         m_sphereTexture.get(),
00288         m_vertexShader.get(),
00289         m_pixelShader.get()
00290         );
00291
00292     // Attach the textures to the appropriate game objects.
00293     for (auto&& object : m_game->RenderObjects())
00294     {
00295         if (object->TargetId() == GameConstants::WorldFloorId)
00296         {
00297             object->NormalMaterial(
00298                 std::make_shared<Material>(
00299                     XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
00300                     XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
00301                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00302                     150.0f,
00303                     m_floorTexture.get(),
00304                     m_vertexShaderFlat.get(),
00305                     m_pixelShaderFlat.get()
00306                     )
00307                 );
00308             object->Mesh(std::make_shared<WorldFloorMesh>(d3dDevice));
00309         }
00310         else if (object->TargetId() == GameConstants::WorldCeilingId)
00311         {
00312             object->NormalMaterial(
00313                 std::make_shared<Material>(
00314                     XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
00315                     XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
00316                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00317                     150.0f,
00318                     m_ceilingTexture.get(),
00319                     m_vertexShaderFlat.get(),
00320                     m_pixelShaderFlat.get()
00321                     )
00322                 );
00323             object->Mesh(std::make_shared<WorldCeilingMesh>(d3dDevice));
00324         }
00325         else if (object->TargetId() == GameConstants::WorldWallsId)
00326         {
00327             object->NormalMaterial(
00328                 std::make_shared<Material>(
00329                     XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f),
00330                     XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f),
00331                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00332                     150.0f,
00333                     m_wallsTexture.get(),
00334                     m_vertexShaderFlat.get(),
00335                     m_pixelShaderFlat.get()
00336                     )
00337                 );
00338             object->Mesh(std::make_shared<WorldWallsMesh>(d3dDevice));
00339         }
00340         else if (auto cylinder = dynamic_cast<Cylinder*>(object.get()))
00341         {
00342             cylinder->Mesh(cylinderMesh);
00343             cylinder->NormalMaterial(cylinderMaterial);
00344         }
00345         else if (auto target = dynamic_cast<Face*>(object.get()))
00346         {
00347             const int bufferLength = 16;
00348             wchar_t str[bufferLength];
00349             int len = swprintf_s(str, bufferLength, L"%d", target->TargetId());
00350             auto string{ winrt::hstring(str, len) };
00351
00352             winrt::com_ptr<ID3D11ShaderResourceView> texture;
00353             textureGenerator.CreateTextureResourceView(string, texture.put());
00354             target->NormalMaterial(
00355                 std::make_shared<Material>(
00356                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00357                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00358                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00359                     5.0f,
00360                     texture.get(),
00361                     m_vertexShader.get(),
00362                     m_pixelShader.get()
00363                     )
00364                 );
00365
00366             texture = nullptr;
00367             textureGenerator.CreateHitTextureResourceView(string, texture.put());
00368             target->HitMaterial(
00369                 std::make_shared<Material>(
00370                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00371                     XMFLOAT4(0.8f, 0.8f, 0.8f, 0.5f),
00372                     XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f),
00373                     5.0f,
00374                     texture.get(),
00375                     m_vertexShader.get(),
00376                     m_pixelShader.get()
00377                     )
00378                 );
00379
00380             target->Mesh(targetMesh);
00381         }
00382         else if (auto sphere = dynamic_cast<Sphere*>(object.get()))
00383         {
00384             sphere->Mesh(sphereMesh);
00385             sphere->NormalMaterial(sphereMaterial);
00386         }
00387     }
00388
00389     // Ensure that the camera has been initialized with the right Projection
00390     // matrix. The camera is not created at the time the first window resize event
00391     // occurs.
00392     auto renderTargetSize = m_deviceResources->GetRenderTargetSize();
00393     m_game->GameCamera().SetProjParams(
00394         XM_PI / 2,
00395         renderTargetSize.Width / renderTargetSize.Height,
00396         0.01f,
00397         100.0f
00398         );
00399
00400     // Make sure that Projection matrix has been set in the constant buffer
00401     // now that all the resources are loaded.
00402     // We are handling screen rotations directly to eliminate an unaligned
00403     // fullscreen copy. As a result, it is necessary to post-multiply the rotationTransform3D
00404     // matrix to the camera projection matrix.
00405     // The matrices are transposed due to the shader code expecting the matrices in the opposite
00406     // row/column order from the DirectX math library.
00407
00408     auto orientation = m_deviceResources->GetOrientationTransform3D();
00409
00410     ConstantBufferChangeOnResize changesOnResize;
00411     XMStoreFloat4x4(
00412         &changesOnResize.projection,
00413         XMMatrixMultiply(
00414             XMMatrixTranspose(m_game->GameCamera().Projection()),
00415             XMMatrixTranspose(XMLoadFloat4x4(&orientation))
00416             )
00417         );
00418
00419     m_deviceResources->GetD3DDeviceContext()->UpdateSubresource(
00420         m_constantBufferChangeOnResize.get(),
00421         0,
00422         nullptr,
00423         &changesOnResize,
00424         0,
00425         0
00426         );
00427
00428     m_gameResourcesLoaded = true;
00429 }
00430
00431 IAsyncAction GameRenderer::LoadLevelResourcesAsync()
00432 {
00433     auto lifetime = shared_from_this();
00434
00435     m_levelResourcesLoaded = false;
00436
00437     // This is where additional async loading of level specific resources
00438     // would be done. Since there aren't any to load, just simulate
00439     // by delaying for some time.
00440     co_await winrt::resume_after(GameConstants::LevelLoadingDelay);
00441 }
00442
00443 void GameRenderer::FinalizeLoadLevelResources()
00444 {
00445     // Once the level specific resources had been loaded, this method is
00446     // where D3D context specific actions would be handled. This method
00447     // runs in the same thread context as the GameRenderer was created.
00448
00449     m_levelResourcesLoaded = true;
00450 }
00451
00452 void GameRenderer::Render()
00453 {
00454     bool stereoEnabled{ m_deviceResources->GetStereoState() };
00455
00456     auto d3dContext{ m_deviceResources->GetD3DDeviceContext() };
00457     auto d2dContext{ m_deviceResources->GetD2DDeviceContext() };
00458
00459     int renderingPasses = 1;
00460     if (stereoEnabled)
00461     {
00462         renderingPasses = 2;
00463     }
00464
00465     for (int i = 0; i < renderingPasses; i++)
00466     {
00467         // Iterate through the number of rendering passes to be completed.
00468         if (i > 0)
00469         {
00470             // Doing the Right Eye View.
00471             ID3D11RenderTargetView* const targets[1] = { m_deviceResources->GetBackBufferRenderTargetViewRight() };
00472
00473             d3dContext->OMSetRenderTargets(1, targets, m_deviceResources->GetDepthStencilView());
00474             d3dContext->ClearDepthStencilView(m_deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH, 1.0f, 0);
00475             d2dContext->SetTarget(m_deviceResources->GetD2DTargetBitmapRight());
00476         }
00477         else
00478         {
00479             // Doing the Mono or Left Eye View.
00480             ID3D11RenderTargetView* const targets[1] = { m_deviceResources->GetBackBufferRenderTargetView() };
00481
00482             d3dContext->OMSetRenderTargets(1, targets, m_deviceResources->GetDepthStencilView());
00483             d3dContext->ClearDepthStencilView(m_deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH, 1.0f, 0);
00484             d2dContext->SetTarget(m_deviceResources->GetD2DTargetBitmap());
00485         }
00486
00487         const float clearColor[4] = { 0.5f, 0.5f, 0.8f, 1.0f };
00488
00489         if (i > 0)
00490         {
00491             // Doing the Right Eye View.
00492             d3dContext->ClearRenderTargetView(m_deviceResources->GetBackBufferRenderTargetViewRight(), clearColor);
00493         }
00494         else
00495         {
00496             // Doing the Mono or Left Eye View.
00497             d3dContext->ClearRenderTargetView(m_deviceResources->GetBackBufferRenderTargetView(), clearColor);
00498         }
00499
00500         if (m_game != nullptr && m_gameResourcesLoaded && m_levelResourcesLoaded)
00501         {
00502             // This section is only used after the game state has been initialized and all device
00503             // resources needed for the game have been created and associated with the game objects.
00504             if (stereoEnabled)
00505             {
00506                 // When doing stereo, it is necessary to update the projection matrix once per rendering pass.
00507
00508                 auto orientation = m_deviceResources->GetOrientationTransform3D();
00509
00510                 ConstantBufferChangeOnResize changesOnResize;
00511                 XMStoreFloat4x4(
00512                     &changesOnResize.projection,
00513                     XMMatrixMultiply(
00514                         XMMatrixTranspose(
00515                             i == 0 ?
00516                             m_game->GameCamera().LeftEyeProjection() :
00517                             m_game->GameCamera().RightEyeProjection()
00518                             ),
00519                         XMMatrixTranspose(XMLoadFloat4x4(&orientation))
00520                         )
00521                     );
00522
00523                 d3dContext->UpdateSubresource(
00524                     m_constantBufferChangeOnResize.get(),
00525                     0,
00526                     nullptr,
00527                     &changesOnResize,
00528                     0,
00529                     0
00530                     );
00531             }
00532             // Update variables that change once per frame.
00533
00534             ConstantBufferChangesEveryFrame constantBufferChangesEveryFrameValue;
00535             XMStoreFloat4x4(
00536                 &constantBufferChangesEveryFrameValue.view,
00537                 XMMatrixTranspose(m_game->GameCamera().View())
00538                 );
00539             d3dContext->UpdateSubresource(
00540                 m_constantBufferChangesEveryFrame.get(),
00541                 0,
00542                 nullptr,
00543                 &constantBufferChangesEveryFrameValue,
00544                 0,
00545                 0
00546                 );
00547
00548             // Set up the graphics pipeline. This sample uses the same InputLayout and set of
00549             // constant buffers for all shaders, so they only need to be set once per frame.
00550
00551             d3dContext->IASetInputLayout(m_vertexLayout.get());
00552             ID3D11Buffer* constantBufferNeverChanges{ m_constantBufferNeverChanges.get() };
00553             d3dContext->VSSetConstantBuffers(0, 1, &constantBufferNeverChanges);
00554             ID3D11Buffer* constantBufferChangeOnResize{ m_constantBufferChangeOnResize.get() };
00555             d3dContext->VSSetConstantBuffers(1, 1, &constantBufferChangeOnResize);
00556             ID3D11Buffer* constantBufferChangesEveryFrame{ m_constantBufferChangesEveryFrame.get() };
00557             d3dContext->VSSetConstantBuffers(2, 1, &constantBufferChangesEveryFrame);
00558             ID3D11Buffer* constantBufferChangesEveryPrim{ m_constantBufferChangesEveryPrim.get() };
00559             d3dContext->VSSetConstantBuffers(3, 1, &constantBufferChangesEveryPrim);
00560
00561             d3dContext->PSSetConstantBuffers(2, 1, &constantBufferChangesEveryFrame);
00562             d3dContext->PSSetConstantBuffers(3, 1, &constantBufferChangesEveryPrim);
00563             ID3D11SamplerState* samplerLinear{ m_samplerLinear.get() };
00564             d3dContext->PSSetSamplers(0, 1, &samplerLinear);
00565
00566             for (auto&& object : m_game->RenderObjects())
00567             {
00568                 object->Render(d3dContext, m_constantBufferChangesEveryPrim.get());
00569             }
00570         }
00571
00572         d3dContext->BeginEventInt(L"D2D BeginDraw", 1);
00573         d2dContext->BeginDraw();
00574
00575         // To handle the swapchain being pre-rotated, set the D2D transformation to include it.
00576         d2dContext->SetTransform(m_deviceResources->GetOrientationTransform2D());
00577
00578         if (m_game != nullptr && m_gameResourcesLoaded)
00579         {
00580             // This is only used after the game state has been initialized.
00581             m_gameHud.Render(m_game);
00582         }
00583
00584         if (m_gameInfoOverlay.Visible())
00585         {
00586             d2dContext->DrawBitmap(
00587                 m_gameInfoOverlay.Bitmap(),
00588                 m_gameInfoOverlayRect
00589                 );
00590         }
00591
00592         // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00593         // is lost. It will be handled during the next call to Present.
00594         HRESULT hr = d2dContext->EndDraw();
00595         d3dContext->EndEvent();
00596         if (hr != D2DERR_RECREATE_TARGET)
00597         {
00598             winrt::check_hresult(hr);
00599         }
00600     }
00601 }
00602
00603 #if defined(_DEBUG)
00604 void GameRenderer::ReportLiveDeviceObjects()
00605 {
00606     // If the debug layer isn't present on the system then this QI will fail. In that case
00607     // the routine just exits. This is a debugging aid to see the active D3D objects and
00608     // is not critical to functional operation of the sample.
00609
00610     winrt::com_ptr<ID3D11Device3> d3dDevice;
00611     d3dDevice = m_deviceResources->GetD3DDevice();
00612     auto debugLayer = d3dDevice.try_as<ID3D11Debug>();
00613     if (debugLayer)
00614     {
00615         winrt::check_hresult(
00616             debugLayer->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL)
00617             );
00618     }
00619 }
00620 #endif
Generated on Fri Nov 15 2024 22:21:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Disable Member List

This is the complete list of members for Scenario2_Disable, including all inherited members.
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_Disable | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_Disable | [inline, protected]
Scenario2_Disable() | Scenario2_Disable | [inline]
Generated on Fri Nov 15 2024 22:23:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/PageToPrint.xaml.cpp Source File

  • Printing
  • cpp

PageToPrint.xaml.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "PageToPrint.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Windows::Foundation;
00010 using namespace Windows::Foundation::Collections;
00011 using namespace Windows::UI::Xaml;
00012 using namespace Windows::UI::Xaml::Controls;
00013 using namespace Windows::UI::Xaml::Controls::Primitives;
00014 using namespace Windows::UI::Xaml::Data;
00015 using namespace Windows::UI::Xaml::Input;
00016 using namespace Windows::UI::Xaml::Media;
00017 using namespace Windows::UI::Xaml::Navigation;
00018
00019 PageToPrint::PageToPrint()
00020 {
00021     InitializeComponent();
00022     TextContentBlock = TextContent;
00023 }
Generated on Fri Nov 15 2024 22:20:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePickerContracts/cs/App.xaml.cs Source File

  • FilePickerContracts
  • cs

App.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel;
00014 using Windows.ApplicationModel.Activation;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// Provides application-specific behavior to supplement the default Application class.
00025     /// </summary>
00026     sealed partial class App : Application
00027     {
00028         /// <summary>
00029         /// Initializes the singleton application object.  This is the first line of authored code
00030         /// executed, and as such is the logical equivalent of main() or WinMain().
00031         /// </summary>
00032         public App()
00033         {
00034             this.InitializeComponent();
00035             this.Suspending += OnSuspending;
00036         }
00037
00038         /// <summary>
00039         /// Invoked when the application is launched normally by the end user.  Other entry points
00040         /// will be used such as when the application is launched to open a specific file.
00041         /// </summary>
00042         /// <param name="e">Details about the launch request and process.</param>
00043         protected override void OnLaunched(LaunchActivatedEventArgs e)
00044         {
00045
00046 #if DEBUG
00047             if (System.Diagnostics.Debugger.IsAttached)
00048             {
00049                 this.DebugSettings.EnableFrameRateCounter = false;
00050             }
00051 #endif
00052
00053             Frame rootFrame = Window.Current.Content as Frame;
00054
00055             // Do not repeat app initialization when the Window already has content,
00056             // just ensure that the window is active
00057             if (rootFrame == null)
00058             {
00059                 // Create a Frame to act as the navigation context and navigate to the first page
00060                 rootFrame = new Frame();
00061                 // Set the default language
00062                 rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
00063
00064                 rootFrame.NavigationFailed += OnNavigationFailed;
00065
00066                 if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
00067                 {
00068                     //TODO: Load state from previously suspended application
00069                 }
00070
00071                 // Place the frame in the current Window
00072                 Window.Current.Content = rootFrame;
00073             }
00074
00075             if (rootFrame.Content == null)
00076             {
00077                 // When the navigation stack isn't restored navigate to the first page,
00078                 // configuring the new page by passing required information as a navigation
00079                 // parameter
00080                 rootFrame.Navigate(typeof(MainPage), e.Arguments);
00081             }
00082             // Ensure the current window is active
00083             Window.Current.Activate();
00084         }
00085
00086         /// <summary>
00087         /// Invoked when Navigation to a certain page fails
00088         /// </summary>
00089         /// <param name="sender">The Frame which failed navigation</param>
00090         /// <param name="e">Details about the navigation failure</param>
00091         void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
00092         {
00093             throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
00094         }
00095
00096         /// <summary>
00097         /// Invoked when application execution is being suspended.  Application state is saved
00098         /// without knowing whether the application will be terminated or resumed with the contents
00099         /// of memory still intact.
00100         /// </summary>
00101         /// <param name="sender">The source of the suspend request.</param>
00102         /// <param name="e">Details about the suspend request.</param>
00103         private void OnSuspending(object sender, SuspendingEventArgs e)
00104         {
00105             var deferral = e.SuspendingOperation.GetDeferral();
00106             //TODO: Save application state and stop any background activity
00107             deferral.Complete();
00108         }
00109     }
00110 }
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraFaceDetection/cpp/pch.h Source File

  • CameraFaceDetection
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <collection.h>
00015 #include <ppltasks.h>
00016
00017 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/PixelShader/CustomPixelShaderMain.h Source File

  • D2DCustomEffects
  • cpp
  • PixelShader

CustomPixelShaderMain.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "BasicTimer.h"
00015 #include "DeviceResources.h"
00016 #include "CustomPixelShaderRenderer.h"
00017 #include "SampleOverlay.h"
00018
00019 // Renders Direct2D content on the screen.
00020 namespace CustomPixelShader
00021 {
00022     class CustomPixelShaderMain : public DX::IDeviceNotify
00023     {
00024     public:
00025         CustomPixelShaderMain(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00026         ~CustomPixelShaderMain();
00027         void CreateWindowSizeDependentResources();
00028         void UpdatePointer(_In_ Windows::UI::Core::PointerEventArgs^ args);
00029         void Update();
00030         bool Render();
00031
00032         // IDeviceNotify
00033         virtual void OnDeviceLost();
00034         virtual void OnDeviceRestored();
00035
00036         // Process lifetime management handlers.
00037         void SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00038         void LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00039
00040     private:
00041         // Cached pointer to device resources.
00042         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00043
00044         std::unique_ptr<CustomPixelShaderRenderer> m_sceneRenderer;
00045         std::unique_ptr<SampleOverlay> m_sampleOverlay;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cs/Scenario5_UnicodeExtensions.xaml.cs Source File

  • DateTimeFormatting
  • cs

Scenario5_UnicodeExtensions.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Text;
00014 using Windows.Foundation;
00015 using Windows.Foundation.Collections;
00016 using Windows.Globalization;
00017 using Windows.Globalization.DateTimeFormatting;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario5_UnicodeExtensions : Page
00025     {
00026         public Scenario5_UnicodeExtensions()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         /// <summary>
00032         /// This is the click handler for the 'Display' button.
00033         /// </summary>
00034         private void Display()
00035         {
00036             // This scenario uses the Windows.Globalization.DateTimeFormatting.DateTimeFormatter class
00037             // to format a date/time by using a formatter that uses Unicode extenstion in the specified
00038             // language name
00039
00040             // We keep results in this variable
00041             StringBuilder results = new StringBuilder();
00042             results.AppendLine("Current default application context language: " + ApplicationLanguages.Languages[0]);
00043             results.AppendLine();
00044
00045             // Create formatters using various types of constructors specifying Language list with unicode extension in language names
00046             DateTimeFormatter[] unicodeExtensionFormatters = new[]
00047             {
00048                 // Default application context
00049                 new DateTimeFormatter("longdate longtime"),
00050                 // Telugu language, Gregorian Calendar and Latin Numeral System
00051                 new DateTimeFormatter("longdate longtime", new[] { "te-in-u-ca-gregory-nu-latn", "en-US" }),
00052                 // Hebrew language and Arabic Numeral System - calendar NOT specified in constructor
00053                 new DateTimeFormatter(YearFormat.Default,
00054                     MonthFormat.Default,
00055                     DayFormat.Default,
00056                     DayOfWeekFormat.Default,
00057                     HourFormat.Default,
00058                     MinuteFormat.Default,
00059                     SecondFormat.Default,
00060                     new[] { "he-IL-u-nu-arab", "en-US" }),
00061                 // Hebrew language and calendar - calendar specified in constructor
00062                 // also, which overrides the one specified in Unicode extension
00063                 new DateTimeFormatter(YearFormat.Default,
00064                     MonthFormat.Default,
00065                     DayFormat.Default,
00066                     DayOfWeekFormat.Default,
00067                     HourFormat.Default,
00068                     MinuteFormat.Default,
00069                     SecondFormat.Default,
00070                     new[] { "he-IL-u-ca-hebrew-co-phonebk", "en-US" },
00071                     "US",
00072                     CalendarIdentifiers.Gregorian,
00073                     ClockIdentifiers.TwentyFourHour),
00074              };
00075
00076             // Create date/time to format and display.
00077             DateTime dateTime = DateTime.Now;
00078
00079             // Format and display date/time along with other relevant properites
00080             foreach (DateTimeFormatter formatter in unicodeExtensionFormatters)
00081             {
00082                 // Perform the actual formatting.
00083                 results.AppendLine("Result: " + formatter.Format(dateTime));
00084                 results.AppendLine("    Language List: " + string.Join(", ", formatter.Languages));
00085                 results.AppendLine("    Template: " + formatter.Template);
00086                 results.AppendLine("    Resolved Language: " + formatter.ResolvedLanguage);
00087                 results.AppendLine("    Calendar System: " + formatter.Calendar);
00088                 results.AppendLine("    Numeral System: " + formatter.NumeralSystem);
00089                 results.AppendLine();
00090             }
00091
00092             // Display the results
00093             OutputTextBlock.Text = results.ToString();
00094         }
00095     }
00096 }
Generated on Fri Nov 15 2024 22:19:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PosPrinter/cpp/Scenario1_FindClaimEnable.xaml.cpp Source File

  • PosPrinter
  • cpp

Scenario1_FindClaimEnable.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_FindClaimEnable.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Devices::PointOfService;
00020 using namespace Windows::Devices::Enumeration;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::UI::Xaml::Media;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 Scenario1_FindClaimEnable::Scenario1_FindClaimEnable()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 void Scenario1_FindClaimEnable::OnNavigatedTo(NavigationEventArgs^ e)
00034 {
00035     RetainDeviceCheckBox->IsChecked = rootPage->IsAnImportantTransaction;
00036     rootPage->StateChanged = std::function<void(void)>([this]() { UpdateButtons(); });
00037     UpdateButtons();
00038 }
00039
00040 void Scenario1_FindClaimEnable::OnNavigatedFrom(NavigationEventArgs^ e)
00041 {
00042     rootPage->StateChanged = nullptr;
00043 }
00044
00045 void Scenario1_FindClaimEnable::UpdateButtons()
00046 {
00047     PrinterNameRun->Text = (rootPage->Printer == nullptr) ? "None" : rootPage->deviceInfo->Name + " (" + rootPage->Printer->DeviceId + ")";
00048     if (isBusy)
00049     {
00050         FindButton->IsEnabled = false;
00051         ClaimAndEnableButton->IsEnabled = false;
00052         ReleaseClaimedPrinterButton->IsEnabled = false;
00053         ReleaseAllPrintersButton->IsEnabled = false;
00054     }
00055     else if (rootPage->Printer == nullptr)
00056     {
00057         FindButton->IsEnabled = true;
00058         ClaimAndEnableButton->IsEnabled = false;
00059         ReleaseClaimedPrinterButton->IsEnabled = false;
00060         ReleaseAllPrintersButton->IsEnabled = false;
00061     }
00062     else
00063     {
00064         FindButton->IsEnabled = false;
00065         ReleaseAllPrintersButton->IsEnabled = true;
00066         if (rootPage->ClaimedPrinter == nullptr)
00067         {
00068             ClaimAndEnableButton->IsEnabled = true;
00069             ReleaseClaimedPrinterButton->IsEnabled = false;
00070         }
00071         else
00072         {
00073             ClaimAndEnableButton->IsEnabled = false;
00074             ReleaseClaimedPrinterButton->IsEnabled = true;
00075         }
00076     }
00077 }
00078
00079 void Scenario1_FindClaimEnable::FindPrinter_Click()
00080 {
00081     isBusy = true;
00082     UpdateButtons();
00083
00084     rootPage->NotifyUser("", NotifyType::StatusMessage);
00085
00086     rootPage->ReleaseAllPrinters();
00087
00088     // Select a PosPrinter device using the Device Picker.
00089     DevicePicker^ devicePicker = ref new DevicePicker();
00090     devicePicker->Filter->SupportedDeviceSelectors->Append(PosPrinter::GetDeviceSelector());
00091
00092     // Anchor the picker on the Find button.
00093     GeneralTransform^ ge = FindButton->TransformToVisual(safe_cast<UIElement^>(Window::Current->Content));
00094     Rect rect = ge->TransformBounds(Rect(0, 0, FindButton->ActualWidth, FindButton->ActualHeight));
00095
00096     create_task(devicePicker->PickSingleDeviceAsync(rect)).then([this](DeviceInformation^ deviceInfo)
00097     {
00098         rootPage->deviceInfo = deviceInfo;
00099         if (deviceInfo != nullptr)
00100         {
00101             return create_task(PosPrinter::FromIdAsync(deviceInfo->Id));
00102         }
00103         else
00104         {
00105             return task_from_result<PosPrinter^>(nullptr);
00106         }
00107     }).then([this](PosPrinter^ printer)
00108     {
00109         if (printer && printer->Capabilities->Receipt->IsPrinterPresent)
00110         {
00111             rootPage->Printer = printer;
00112             rootPage->NotifyUser("Found receipt printer.", NotifyType::StatusMessage);
00113         }
00114         else
00115         {
00116             // Get rid of the printer we can't use.
00117             delete printer;
00118             rootPage->NotifyUser("Please select a device whose printer is present.", NotifyType::ErrorMessage);
00119         }
00120
00121         isBusy = false;
00122         UpdateButtons();
00123     });
00124 }
00125
00126 void Scenario1_FindClaimEnable::ClaimAndEnable_Click()
00127 {
00128     isBusy = true;
00129     UpdateButtons();
00130     create_task(rootPage->Printer->ClaimPrinterAsync()).then([this](ClaimedPosPrinter^ claimedPrinter)
00131     {
00132         rootPage->ClaimedPrinter = claimedPrinter;
00133
00134         if (claimedPrinter == nullptr)
00135         {
00136             rootPage->NotifyUser("Unable to claim printer", NotifyType::ErrorMessage);
00137             return task_from_result();
00138         }
00139         else
00140         {
00141             rootPage->NotifyUser("Claimed printer", NotifyType::StatusMessage);
00142
00143             // Register for the ReleaseDeviceRequested event so we know when somebody
00144             // wants to claim the printer away from us.
00145             rootPage->SubscribeToReleaseDeviceRequested();
00146
00147             return create_task(claimedPrinter->EnableAsync()).then([this](bool enabled)
00148             {
00149                 if (enabled)
00150                 {
00151                     rootPage->NotifyUser("Enabled printer.", NotifyType::StatusMessage);
00152                 }
00153                 else
00154                 {
00155                     rootPage->NotifyUser("Could not enable printer", NotifyType::ErrorMessage);
00156                     rootPage->ReleaseClaimedPrinter();
00157                 }
00158             });
00159         }
00160     }).then([this]()
00161     {
00162         isBusy = false;
00163         UpdateButtons();
00164     });
00165 }
00166
00167 void Scenario1_FindClaimEnable::IsImportantTransaction_Click()
00168 {
00169     rootPage->IsAnImportantTransaction = RetainDeviceCheckBox->IsChecked->Value;
00170 }
00171
00172 void Scenario1_FindClaimEnable::ReleaseClaim_Click()
00173 {
00174     rootPage->ReleaseClaimedPrinter();
00175 }
00176
00177 void Scenario1_FindClaimEnable::ReleaseAll_Click()
00178 {
00179     rootPage->ReleaseAllPrinters();
00180 }
Generated on Fri Nov 15 2024 22:20:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Enum Member List

This is the complete list of members for Scenario3_Enum, including all inherited members.
Scenario3_Enum() | Scenario3_Enum
ShowResults_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario3_Enum
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CopyImage Member List

This is the complete list of members for CopyImage, including all inherited members.
CopyBitmap(bool isDelayRendered) | CopyImage | [inline, private]
CopyButton_Click(object sender, RoutedEventArgs e) | CopyImage | [inline, private]
CopyImage() | CopyImage | [inline]
CopyWithDelayedRenderingButton_Click(object sender, RoutedEventArgs e) | CopyImage | [inline, private]
OnDeferredImageRequestedHandler(DataProviderRequest request, StorageFile imageFile) | CopyImage | [inline, private, static]
PasteButton_Click(object sender, RoutedEventArgs e) | CopyImage | [inline, private]
rootPage | CopyImage | [private]
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Notifications Member List

This is the complete list of members for Scenario3_Notifications, including all inherited members.
baseUri | Scenario3_Notifications | [private]
CancelActiveDownloadsAsync() | Scenario3_Notifications | [inline, private]
CreateDownload(BackgroundDownloader downloader, int delaySeconds, string fileName) | Scenario3_Notifications | [inline, private]
DownloadAsync(DownloadOperation download) | Scenario3_Notifications | [inline, private]
IsExceptionHandled(string title, Exception ex, DownloadOperation download=null) | Scenario3_Notifications | [inline, private]
Log(string message) | Scenario3_Notifications | [inline, private]
LogStatus(string message, NotifyType type) | Scenario3_Notifications | [inline, private]
notificationsGroup | Scenario3_Notifications | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_Notifications | [inline, protected]
rootPage | Scenario3_Notifications | [private]
RunDownloadsAsync(BackgroundDownloader downloader, ScenarioType type) | Scenario3_Notifications | [inline, private]
runId | Scenario3_Notifications | [private, static]
Scenario3_Notifications() | Scenario3_Notifications | [inline]
ScenarioType enum name | Scenario3_Notifications | [private]
TileNotificationButton_Click(object sender, RoutedEventArgs e) | Scenario3_Notifications | [inline, private]
ToastNotificationButton_Click(object sender, RoutedEventArgs e) | Scenario3_Notifications | [inline, private]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_ExtractTextSegments Member List

This is the complete list of members for Scenario1_ExtractTextSegments, including all inherited members.
Scenario1_ExtractTextSegments() | Scenario1_ExtractTextSegments
SelectionSegmentsButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_ExtractTextSegments
WordSegmentsButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_ExtractTextSegments
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteLineSpacingModes/cpp/DWriteTextLayoutImplementation/DirectXHelper.h Source File

  • DWriteLineSpacingModes
  • cpp
  • DWriteTextLayoutImplementation

DirectXHelper.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015
00016 namespace DX
00017 {
00018     inline void ThrowIfFailed(HRESULT hr)
00019     {
00020         if (FAILED(hr))
00021         {
00022             // Set a breakpoint on this line to catch Win32 API errors.
00023             throw Platform::Exception::CreateException(hr);
00024         }
00025     }
00026
00027
00028     inline D2D1_COLOR_F ConvertToColorF(Windows::UI::Color color)
00029     {
00030         return D2D1::ColorF(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, color.A / 255.0f);
00031     }
00032
00033
00034 #if defined(_DEBUG)
00035     // Check for SDK Layer support.
00036     inline bool SdkLayersAvailable()
00037     {
00038         HRESULT hr = D3D11CreateDevice(
00039             nullptr,
00040             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00041             0,
00042             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00043             nullptr,                    // Any feature level will do.
00044             0,
00045             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00046             nullptr,                    // No need to keep the D3D device reference.
00047             nullptr,                    // No need to know the feature level.
00048             nullptr                     // No need to keep the D3D device context reference.
00049             );
00050
00051         return SUCCEEDED(hr);
00052     }
00053 #endif
00054 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-GPIO/cpp/pch.cpp Source File

  • IoT-GPIO
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Include the standard header and generate the precompiled header.
00014 //
00015
00016 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CSampleService Member List

This is the complete list of members for CSampleService, including all inherited members.
ConsoleRun() | CSampleService |
CSampleService(PWSTR pszServiceName, BOOL fCanStop=TRUE, BOOL fCanShutdown=TRUE, BOOL fCanPauseContinue=FALSE) | CSampleService |
CServiceBase(PWSTR pszServiceName, BOOL fCanStop=TRUE, BOOL fCanShutdown=TRUE, BOOL fCanPauseContinue=FALSE) | CServiceBase |
IsConsoleRun() | CSampleService | [inline]
m_runningInConsole | CSampleService | [private]
m_work | CSampleService | [private]
OnContinue() | CServiceBase | [protected, virtual]
OnPause() | CServiceBase | [protected, virtual]
OnShutdown() | CServiceBase | [protected, virtual]
OnStart(DWORD dwArgc, PWSTR *pszArgv) override | CSampleService | [protected, virtual]
OnStop() override | CSampleService | [protected, virtual]
Run(CServiceBase &service) | CServiceBase | [static]
SetServiceStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode=NO_ERROR, DWORD dwWaitHint=0) | CServiceBase | [protected]
Stop() | CServiceBase |
WriteErrorLogEntry(PWSTR pszFunction, DWORD dwError=GetLastError()) | CServiceBase | [protected]
WriteEventLogEntry(PWSTR pszMessage, BYTE bLevel) override | CSampleService | [virtual]
~CSampleService(void) | CSampleService | [virtual]
~CServiceBase(void) | CServiceBase | [virtual]
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Files Member List

This is the complete list of members for Scenario1_Files, including all inherited members.
ChooseFile_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Files |
ChooseFolder_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Files |
DisplayOutput() | Scenario1_Files |
filename | Scenario1_Files | [inline, private, static]
Increment_Local_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1_Files |
Increment_LocalCache_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1_Files |
Increment_Temporary_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1_Files |
localCacheCounter | Scenario1_Files | [private]
localCacheFolder | Scenario1_Files | [private]
localCounter | Scenario1_Files | [private]
localFolder | Scenario1_Files | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario1_Files |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_Files |
ProtectL1_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Files |
ProtectL2_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Files |
Read_Local_Counter() | Scenario1_Files | [private]
Read_LocalCache_Counter() | Scenario1_Files | [private]
Read_Temporary_Counter() | Scenario1_Files | [private]
ReportStatus(winrt::hstring const &operation, winrt::Windows::Security::DataProtection::UserDataStorageItemProtectionStatus status) | Scenario1_Files | [private]
Scenario1_Files() | Scenario1_Files |
Scenario1_Files() | Scenario1_Files |
temporaryCounter | Scenario1_Files | [private]
temporaryFolder | Scenario1_Files | [private]
Unprotect_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_Files |
UpdateItem(winrt::Windows::Storage::IStorageItem const &item) | Scenario1_Files | [private]
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboard/cppwinrt/Project.idl Source File

  • TouchKeyboard
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_Launch : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_Launch();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_ShowHideEvents : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_ShowHideEvents();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3_ShowHideMethods : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3_ShowHideMethods();
00030     }
00031
00032     [default_interface]
00033     runtimeclass Scenario4_ShowView : Windows.UI.Xaml.Controls.Page
00034     {
00035         Scenario4_ShowView();
00036     }
00037
00038     [default_interface]
00039     runtimeclass CustomTextBox : Windows.UI.Xaml.Controls.TextBox
00040     {
00041         CustomTextBox();
00042     }
00043 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geotag/cpp/Scenario1_Geotag.xaml.cpp Source File

  • Geotag
  • cpp

Scenario1_Geotag.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario1_Geotag.xaml.h"
00005
00006 using namespace Concurrency;
00007 using namespace Platform;
00008 using namespace SDKTemplate;
00009 using namespace Windows::Devices::Geolocation;
00010 using namespace Windows::Foundation;
00011 using namespace Windows::Foundation::Collections;
00012 using namespace Windows::Storage;
00013 using namespace Windows::Storage::Pickers;
00014 using namespace Windows::Storage::FileProperties;
00015
00016 Scenario1_Geotag::Scenario1_Geotag()
00017 {
00018     InitializeComponent();
00019 }
00020
00021 void Scenario1_Geotag::ChooseFileButton_Click()
00022 {
00023     auto picker = ref new FileOpenPicker();
00024     picker->FileTypeFilter->Append(".jpg");
00025     picker->FileTypeFilter->Append(".jpeg");
00026     picker->FileTypeFilter->Append(".mp4");
00027     picker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00028     create_task(picker->PickSingleFileAsync())
00029         .then([this](StorageFile^ pickedFile)
00030     {
00031         file = pickedFile;
00032         if (file != nullptr)
00033         {
00034             FileDisplayName->Text = file->DisplayName;
00035             FileOperationsPanel->Visibility = Windows::UI::Xaml::Visibility::Visible;
00036         }
00037         else
00038         {
00039             FileOperationsPanel->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00040         }
00041     });
00042 }
00043
00044 void Scenario1_Geotag::GetGeotagButton_Click()
00045 {
00046     create_task(GeotagHelper::GetGeotagAsync(file))
00047         .then([this](Geopoint^ geopoint)
00048     {
00049         if (geopoint != nullptr)
00050         {
00051             rootPage->NotifyUser("Latitude = " + geopoint->Position.Latitude
00052                 + ", Longitude = " + geopoint->Position.Longitude, NotifyType::StatusMessage);
00053         }
00054         else
00055         {
00056             // File I/O errors are converted to "No information".
00057             rootPage->NotifyUser("No location information available", NotifyType::ErrorMessage);
00058         }
00059     });
00060 }
00061
00062 void Scenario1_Geotag::SetGeotagFromGeolocatorButton_Click()
00063 {
00064     // Call RequestAccessAsync from the UI thread to get user permission on location usage.
00065     // Otherwise SetGeotagFromGeolocator will fail.
00066     create_task(Geolocator::RequestAccessAsync())
00067         .then([this](GeolocationAccessStatus status)
00068     {
00069         if (status != GeolocationAccessStatus::Allowed)
00070         {
00071             rootPage->NotifyUser("Location access is not allowed", NotifyType::ErrorMessage);
00072         }
00073         else
00074         {
00075             Geolocator^ geolocator = ref new Geolocator();
00076             geolocator->DesiredAccuracy = PositionAccuracy::High;
00077
00078             create_task(GeotagHelper::SetGeotagFromGeolocatorAsync(file, geolocator))
00079                 .then([this](task<void> previousTask)
00080             {
00081                 try
00082                 {
00083                     previousTask.get();
00084                     rootPage->NotifyUser("Geolocation set to current location", NotifyType::StatusMessage);
00085                 }
00086                 catch (Exception^ ex)
00087                 {
00088                     // File I/O errors are reported as exceptions.
00089                     // AccessDeniedExcetion can be raised if the user revoked location access
00090                     // after RequestAccessAsync completed.
00091                     rootPage->NotifyUser("Exception: " + ex->Message, NotifyType::ErrorMessage);
00092                 }
00093             });
00094         }
00095     });
00096 }
00097
00098 void Scenario1_Geotag::SetGeotagButton_Click()
00099 {
00100     // Set the approximate position of the observation deck of the Seattle Space Needle.
00101     BasicGeoposition position;
00102     position.Latitude = 47.620491;
00103     position.Longitude = -122.349319;
00104     position.Altitude = 158.12;
00105     Geopoint^ geopoint = ref new Geopoint(position);
00106
00107     create_task(GeotagHelper::SetGeotagAsync(file, geopoint))
00108         .then([this](task<void> previousTask)
00109     {
00110         try
00111         {
00112             previousTask.get();
00113             rootPage->NotifyUser("Geolocation set to Seattle Space Needle", NotifyType::StatusMessage);
00114         }
00115         catch (Exception^ ex)
00116         {
00117             // File I/O errors are reported as exceptions
00118             rootPage->NotifyUser("Exception: " + ex->Message, NotifyType::ErrorMessage);
00119         }
00120     });
00121 }
Generated on Fri Nov 15 2024 22:19:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/MrcEffectDefinitions/MrcVideoEffectDefinition.cpp Source File

  • HolographicMixedRealityCapture
  • cpp
  • MrcEffectDefinitions

MrcVideoEffectDefinition.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
00002 #include "MrcVideoEffectDefinition.h"
00003
00004 using namespace MrcEffectDefinitions;
00005
00006 MrcVideoEffectDefinition::MrcVideoEffectDefinition()
00007 {
00008     StreamType = DefaultStreamType;
00009     HologramCompositionEnabled = DefaultHologramCompositionEnabled;
00010     RecordingIndicatorEnabled = DefaultRecordingIndicatorEnabled;
00011     VideoStabilizationEnabled = DefaultVideoStabilizationEnabled;
00012     VideoStabilizationBufferLength = DefaultVideoStabilizationBufferLength;
00013     GlobalOpacityCoefficient = DefaultGlobalOpacityCoefficient;
00014     BlankOnProtectedContent = DefaultBlankOnProtectedContent;
00015     ShowHiddenMesh = DefaultShowHiddenMesh;
00016     OutputSize = DefaultOutputSize;
00017     PreferredHologramPerspective = DefaultPreferredHologramPerspective;
00018 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 3DPrintingFromUnity/Assets/Script/Turn.cs Source File

  • 3DPrintingFromUnity
  • Assets
  • Script

Turn.cs

Go to the documentation of this file.
00001 ﻿using UnityEngine;
00002 using System.Collections;
00003
00004 public class Turn : MonoBehaviour {
00005     public float turningSpeed = 60;
00006
00007     // Use this for initialization
00008     void Start () {
00009
00010   }
00011
00012   // Update is called once per frame
00013   void Update () {
00014         float horizontal = Input.GetAxis("Horizontal") * turningSpeed * Time.deltaTime;
00015         transform.Rotate(0, horizontal, 0);
00016     }
00017 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_BackgroundTask Member List

This is the complete list of members for Scenario1_BackgroundTask, including all inherited members.
Accelerometer | Scenario1_BackgroundTask | [private]
Deferral | Scenario1_BackgroundTask | [private]
Dispose() | Scenario1_BackgroundTask | [inline]
OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) | Scenario1_BackgroundTask | [inline, private]
ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e) | Scenario1_BackgroundTask | [inline, private]
Run(IBackgroundTaskInstance taskInstance) | Scenario1_BackgroundTask | [inline]
SampleCount | Scenario1_BackgroundTask | [private]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

UpdateMetadataTask Member List

This is the complete list of members for UpdateMetadataTask, including all inherited members.
Run(IBackgroundTaskInstance taskInstance) UpdateMetadataTask [inline]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/Scenario8.xaml.cpp Source File

  • SimpleInk
  • cpp

Scenario8.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario8.xaml.h"
00013 #include <math.h>
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Core;
00021 using namespace Windows::UI::Input::Inking;
00022 using namespace Windows::UI::Input::Inking::Core;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 const float Scenario8::radius = 150.0f;
00029 const float Scenario8::circleStrokeThickness = 2.0f;
00030 const float Scenario8::penSize = 4.0f;
00031
00032 Scenario8::Scenario8()
00033 {
00034     InitializeComponent();
00035
00036     inkCanvas->InkPresenter->InputDeviceTypes = CoreInputDeviceTypes::Mouse | CoreInputDeviceTypes::Pen;
00037
00038     auto drawingAttributes = inkCanvas->InkPresenter->CopyDefaultDrawingAttributes();
00039     drawingAttributes->Size = Size(penSize, penSize);
00040     inkCanvas->InkPresenter->UpdateDefaultDrawingAttributes(drawingAttributes);
00041
00042     coreWetStrokeUpdateSource = CoreWetStrokeUpdateSource::Create(inkCanvas->InkPresenter);
00043     coreWetStrokeUpdateSource->WetStrokeStarting += ref new TypedEventHandler<CoreWetStrokeUpdateSource^, CoreWetStrokeUpdateEventArgs^>(this, &Scenario8::CoreWetStrokeUpdateSource_WetStrokeStarting);
00044     coreWetStrokeUpdateSource->WetStrokeContinuing += ref new TypedEventHandler<CoreWetStrokeUpdateSource^, CoreWetStrokeUpdateEventArgs^>(this, &Scenario8::CoreWetStrokeUpdateSource_WetStrokeContinuing);
00045     coreWetStrokeUpdateSource->WetStrokeStopping += ref new TypedEventHandler<CoreWetStrokeUpdateSource^, CoreWetStrokeUpdateEventArgs^>(this, &Scenario8::CoreWetStrokeUpdateSource_WetStrokeStopping);
00046     coreWetStrokeUpdateSource->WetStrokeCompleted += ref new TypedEventHandler<CoreWetStrokeUpdateSource^, CoreWetStrokeUpdateEventArgs^>(this, &Scenario8::CoreWetStrokeUpdateSource_WetStrokeCompleted);
00047     coreWetStrokeUpdateSource->WetStrokeCanceled += ref new TypedEventHandler<CoreWetStrokeUpdateSource^, CoreWetStrokeUpdateEventArgs^>(this, &Scenario8::CoreWetStrokeUpdateSource_WetStrokeCanceled);
00048 }
00049
00050 void Scenario8::InkStackPanel_Loaded(Object^ sender, RoutedEventArgs e)
00051 {
00052     inkCanvas->Width = InkStackPanel->ActualWidth;
00053     inkCanvas->Height = InkStackPanel->ActualHeight;
00054
00055     circleCenter = Point(static_cast<float>(inkCanvas->Width) / 2.0f, static_cast<float>(inkCanvas->Height) / 2.0f);
00056     InkCircle->Center = circleCenter;
00057     InkCircle->RadiusX = radius;
00058     InkCircle->RadiusY = radius;
00059     InkCirclePath->StrokeThickness = circleStrokeThickness;
00060 }
00061
00062 void Scenario8::CoreWetStrokeUpdateSource_WetStrokeStarting(CoreWetStrokeUpdateSource^ sender, CoreWetStrokeUpdateEventArgs^ args)
00063 {
00064     followCircle = disableFollowCircle ? false : FollowCircleTest(args);
00065     if (followCircle)
00066     {
00067         HandleFollowCircleInput(args);
00068     }
00069     else
00070     {
00071         disableFollowCircle = true;
00072         HandleRegularInput(args);
00073     }
00074 }
00075
00076 void Scenario8::CoreWetStrokeUpdateSource_WetStrokeContinuing(CoreWetStrokeUpdateSource^ sender, CoreWetStrokeUpdateEventArgs^ args)
00077 {
00078     if (followCircle)
00079     {
00080         HandleFollowCircleInput(args);
00081     }
00082     else
00083     {
00084         HandleRegularInput(args);
00085     }
00086 }
00087
00088 void Scenario8::CoreWetStrokeUpdateSource_WetStrokeStopping(CoreWetStrokeUpdateSource^ sender, CoreWetStrokeUpdateEventArgs^ args)
00089 {
00090     if (followCircle)
00091     {
00092         HandleFollowCircleInput(args);
00093     }
00094     else
00095     {
00096         HandleRegularInput(args);
00097     }
00098
00099     disableFollowCircle = false;
00100 }
00101
00102 void Scenario8::CoreWetStrokeUpdateSource_WetStrokeCompleted(CoreWetStrokeUpdateSource^ sender, CoreWetStrokeUpdateEventArgs^ args)
00103 {
00104     followCircle = false;
00105     discontinueStroke = false;
00106 }
00107
00108 void Scenario8::CoreWetStrokeUpdateSource_WetStrokeCanceled(CoreWetStrokeUpdateSource^ sender, CoreWetStrokeUpdateEventArgs^ args)
00109 {
00110     followCircle = false;
00111     discontinueStroke = false;
00112     disableFollowCircle = false;
00113 }
00114
00115 bool Scenario8::FollowCircleTest(CoreWetStrokeUpdateEventArgs^ args)
00116 {
00117     auto position = args->NewInkPoints->GetAt(0)->Position;
00118     auto distanceFromCenter = DistanceFromCenter(position);
00119     return InCircleEdgeZone(distanceFromCenter);
00120 }
00121
00122 void Scenario8::HandleFollowCircleInput(CoreWetStrokeUpdateEventArgs^ args)
00123 {
00124     if (!discontinueStroke)
00125     {
00126         int size = static_cast<int>(args->NewInkPoints->Size);
00127         for (int i = 0; i < size; i++)
00128         {
00129             auto position = args->NewInkPoints->GetAt(i)->Position;
00130             auto distanceFromCenter = DistanceFromCenter(position);
00131
00132             if (InCircleEdgeZone(distanceFromCenter))
00133             {
00134                 // Calculate position of new InkPoint so that it lies on the edge of the circle
00135                 auto radians = atan2(position.Y - circleCenter.Y, position.X - circleCenter.X);
00136                 auto totalRadius = (radius + circleStrokeThickness / 2.0f + penSize / 2.0f);
00137                 Point newPoint = Point((cos(radians) * totalRadius) + circleCenter.X, (sin(radians) * totalRadius) + circleCenter.Y);
00138
00139                 args->NewInkPoints->SetAt(i, ref new InkPoint(newPoint, 0.5f));
00140             }
00141             else
00142             {
00143                 // InkPoint is not in the follow circle zone, add no more InkPoints to Stroke
00144                 discontinueStroke = true;
00145
00146                 for (int j = args->NewInkPoints->Size - 1; j >= i; j--)
00147                 {
00148                     args->NewInkPoints->RemoveAt(j);
00149                 }
00150                 break;
00151             }
00152         }
00153     }
00154     else
00155     {
00156         // Stroke has been discontinued, remove all InkPoints
00157         for (int j = args->NewInkPoints->Size - 1; j >= 0; j--)
00158         {
00159             args->NewInkPoints->RemoveAt(j);
00160         }
00161     }
00162 }
00163
00164 void Scenario8::HandleRegularInput(CoreWetStrokeUpdateEventArgs^ args)
00165 {
00166     int size = static_cast<int>(args->NewInkPoints->Size);
00167     for (int i = 0; i < size; i++)
00168     {
00169         auto position = args->NewInkPoints->GetAt(i)->Position;
00170         auto distanceFromCenter = DistanceFromCenter(position);
00171
00172         if (distanceFromCenter < radius + circleStrokeThickness / 2 + penSize / 2)
00173         {
00174             // Ink input entered the circle. Handle this by removing remaining InkPoints
00175             // and completing the stroke.
00176
00177             for (int j = args->NewInkPoints->Size - 1; j >= i; j--)
00178             {
00179                 args->NewInkPoints->RemoveAt(j);
00180             }
00181
00182             args->Disposition = CoreWetStrokeDisposition::Completed;
00183             break;
00184         }
00185     }
00186 }
00187
00188 double Scenario8::DistanceFromCenter(Point position)
00189 {
00190     return hypot(position.X - circleCenter.X, position.Y - circleCenter.Y);
00191 }
00192
00193 bool Scenario8::InCircleEdgeZone(double distanceFromCenter)
00194 {
00195     return (distanceFromCenter > radius * 0.8) && (distanceFromCenter < radius * 1.5);
00196 }
00197
00198
Generated on Fri Nov 15 2024 22:18:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_MultiFile Member List

This is the complete list of members for Scenario2_MultiFile, including all inherited members.
PickFilesButton_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_MultiFile
Scenario2_MultiFile() | Scenario2_MultiFile
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_SymbologyAttributes Member List

This is the complete list of members for Scenario4_SymbologyAttributes, including all inherited members.
claimedScanner | Scenario4_SymbologyAttributes | [private]
claimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args) | Scenario4_SymbologyAttributes | [inline, private]
claimedScanner_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e) | Scenario4_SymbologyAttributes | [inline, private]
listOfSymbologies | Scenario4_SymbologyAttributes | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario4_SymbologyAttributes | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario4_SymbologyAttributes | [inline, protected]
ResetTheScenarioState() | Scenario4_SymbologyAttributes | [inline, private]
rootPage | Scenario4_SymbologyAttributes | [private]
scanner | Scenario4_SymbologyAttributes | [private]
Scenario4_SymbologyAttributes() | Scenario4_SymbologyAttributes | [inline]
ScenarioEndScanButton_Click(object sender, RoutedEventArgs e) | Scenario4_SymbologyAttributes | [inline, private]
ScenarioStartScanButton_Click(object sender, RoutedEventArgs e) | Scenario4_SymbologyAttributes | [inline, private]
SetSymbologyAttributes_Click(object sender, RoutedEventArgs e) | Scenario4_SymbologyAttributes | [inline, private]
symbologyAttributes | Scenario4_SymbologyAttributes | [private]
SymbologySelection_Changed(object sender, SelectionChangedEventArgs args) | Scenario4_SymbologyAttributes | [inline, private]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomEffectState Member List

This is the complete list of members for CustomEffectState, including all inherited members.
CustomEffectState(winrt::Windows::Devices::Lights::LampArray const &lampArray) | CustomEffectState | [inline]
lampColors | CustomEffectState |
lampNormalizedX | CustomEffectState |
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Common/CameraResources.h Source File

  • HolographicFaceTracking
  • cpp
  • Common

CameraResources.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace DX
00015 {
00016     class DeviceResources;
00017
00018     // Constant buffer used to send the view-projection matrices to the shader pipeline.
00019     struct ViewProjectionConstantBuffer
00020     {
00021         Windows::Foundation::Numerics::float4x4 viewProjection[2];
00022     };
00023
00024     // Assert that the constant buffer remains 16-byte aligned (best practice).
00025     static_assert((sizeof(ViewProjectionConstantBuffer) % (sizeof(float) * 4)) == 0, "ViewProjection constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00026
00027     // Manages DirectX device resources that are specific to a holographic camera, such as the
00028     // back buffer, ViewProjection constant buffer, and viewport.
00029     class CameraResources
00030     {
00031     public:
00032         CameraResources(Windows::Graphics::Holographic::HolographicCamera^ holographicCamera);
00033
00034         void CreateResourcesForBackBuffer(
00035             DX::DeviceResources* pDeviceResources,
00036             Windows::Graphics::Holographic::HolographicCameraRenderingParameters^ cameraParameters
00037             );
00038         void ReleaseResourcesForBackBuffer(
00039             DX::DeviceResources* pDeviceResources
00040             );
00041
00042         void UpdateViewProjectionBuffer(
00043             std::shared_ptr<DX::DeviceResources> deviceResources,
00044             Windows::Graphics::Holographic::HolographicCameraPose^ cameraPose,
00045             Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem);
00046
00047         bool AttachViewProjectionBuffer(
00048             std::shared_ptr<DX::DeviceResources> deviceResources);
00049
00050         // Direct3D device resources.
00051         ID3D11RenderTargetView* GetBackBufferRenderTargetView()     const { return m_d3dRenderTargetView.Get();     }
00052         ID3D11DepthStencilView* GetDepthStencilView()               const { return m_d3dDepthStencilView.Get();     }
00053         ID3D11Texture2D*        GetBackBufferTexture2D()            const { return m_d3dBackBuffer.Get();           }
00054         D3D11_VIEWPORT          GetViewport()                       const { return m_d3dViewport;                   }
00055         DXGI_FORMAT             GetBackBufferDXGIFormat()           const { return m_dxgiFormat;                    }
00056
00057         // Render target properties.
00058         Windows::Foundation::Size GetRenderTargetSize()             const { return m_d3dRenderTargetSize;           }
00059         bool                    IsRenderingStereoscopic()           const { return m_isStereo;                      }
00060
00061         // The holographic camera these resources are for.
00062         Windows::Graphics::Holographic::HolographicCamera^ GetHolographicCamera() const { return m_holographicCamera; }
00063
00064     private:
00065         // Direct3D rendering objects. Required for 3D.
00066         Microsoft::WRL::ComPtr<ID3D11RenderTargetView>      m_d3dRenderTargetView;
00067         Microsoft::WRL::ComPtr<ID3D11DepthStencilView>      m_d3dDepthStencilView;
00068         Microsoft::WRL::ComPtr<ID3D11Texture2D>             m_d3dBackBuffer;
00069
00070         // Device resource to store view and projection matrices.
00071         Microsoft::WRL::ComPtr<ID3D11Buffer>                m_viewProjectionConstantBuffer;
00072
00073         // Direct3D rendering properties.
00074         DXGI_FORMAT                                         m_dxgiFormat;
00075         Windows::Foundation::Size                           m_d3dRenderTargetSize;
00076         D3D11_VIEWPORT                                      m_d3dViewport;
00077
00078         // Indicates whether the camera supports stereoscopic rendering.
00079         bool                                                m_isStereo = false;
00080
00081         // Indicates whether this camera has a pending frame.
00082         bool                                                m_framePending = false;
00083
00084         // Pointer to the holographic camera these resources are for.
00085         Windows::Graphics::Holographic::HolographicCamera^  m_holographicCamera = nullptr;
00086     };
00087 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

OcrCapturedImage Member List

This is the complete list of members for OcrCapturedImage, including all inherited members.
Application_Resuming(object sender, object o) | OcrCapturedImage | [inline, private]
Application_Suspending(object sender, SuspendingEventArgs e) | OcrCapturedImage | [inline, private]
CalculatePreviewRotation(out VideoRotation sourceRotation, out int rotationDegrees) | OcrCapturedImage | [inline, private]
CameraButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | OcrCapturedImage | [inline, private]
CleanupCameraAsync() | OcrCapturedImage | [inline, private]
displayInformation | OcrCapturedImage | [private]
DisplayInformation_OrientationChanged(DisplayInformation sender, object args) | OcrCapturedImage | [inline, private]
displayRequest | OcrCapturedImage | [private]
externalCamera | OcrCapturedImage | [private]
ExtractButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | OcrCapturedImage | [inline, private]
FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel) | OcrCapturedImage | [inline, private, static]
InitializeCameraAsync() | OcrCapturedImage | [inline, private]
isInitialized | OcrCapturedImage | [private]
isPreviewing | OcrCapturedImage | [private]
mediaCapture | OcrCapturedImage | [private]
MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) | OcrCapturedImage | [inline, private]
mirroringPreview | OcrCapturedImage | [private]
OcrCapturedImage() | OcrCapturedImage | [inline]
ocrLanguage | OcrCapturedImage | [private]
OnNavigatedTo(NavigationEventArgs e) | OcrCapturedImage | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | OcrCapturedImage | [inline, protected]
PreviewImage_SizeChanged(object sender, SizeChangedEventArgs e) | OcrCapturedImage | [inline, private]
rootPage | OcrCapturedImage | [private]
RotationKey | OcrCapturedImage | [private, static]
SetPreviewRotationAsync() | OcrCapturedImage | [inline, private]
StartCameraAsync() | OcrCapturedImage | [inline, private]
StartPreviewAsync() | OcrCapturedImage | [inline, private]
StopPreviewAsync() | OcrCapturedImage | [inline, private]
UpdateWordBoxTransform() | OcrCapturedImage | [inline, private]
wordBoxes | OcrCapturedImage | [private]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AudioCreation/cs/AudioCreation/Scenario6_CustomEffects.xaml.cs Source File

  • AudioCreation
  • cs
  • AudioCreation

Scenario6_CustomEffects.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using CustomEffect;
00013 using SDKTemplate;
00014 using System;
00015 using System.Threading.Tasks;
00016 using Windows.Foundation.Collections;
00017 using Windows.Media.Audio;
00018 using Windows.Media.Effects;
00019 using Windows.Media.Render;
00020 using Windows.Storage;
00021 using Windows.Storage.Pickers;
00022 using Windows.UI;
00023 using Windows.UI.Xaml;
00024 using Windows.UI.Xaml.Controls;
00025 using Windows.UI.Xaml.Media;
00026 using Windows.UI.Xaml.Navigation;
00027
00028 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00029
00030 namespace AudioCreation
00031 {
00032     /// <summary>
00033     /// Using custom effects with the AudioGraph API.
00034     /// </summary>
00035     public sealed partial class Scenario6_CustomEffects : Page
00036     {
00037         private MainPage rootPage;
00038         private AudioGraph graph;
00039         private AudioFileInputNode fileInputNode;
00040         private AudioDeviceOutputNode deviceOutputNode;
00041
00042         public Scenario6_CustomEffects()
00043         {
00044             this.InitializeComponent();
00045         }
00046
00047         protected override async void OnNavigatedTo(NavigationEventArgs e)
00048         {
00049             rootPage = MainPage.Current;
00050             await CreateAudioGraph();
00051         }
00052
00053         protected override void OnNavigatedFrom(NavigationEventArgs e)
00054         {
00055             if (graph != null)
00056             {
00057                 graph.Dispose();
00058             }
00059         }
00060
00061         private async void File_Click(object sender, RoutedEventArgs e)
00062         {
00063             await SelectInputFile();
00064         }
00065
00066         private async Task SelectInputFile()
00067         {
00068             // If another file is already loaded into the FileInput node
00069             if (fileInputNode != null)
00070             {
00071                 // Release the file and dispose the contents of the node
00072                 fileInputNode.Dispose();
00073                 // Stop playback since a new file is being loaded. Also reset the button UI
00074                 if (graphButton.Content.Equals("Stop Graph"))
00075                 {
00076                     TogglePlay();
00077                 }
00078             }
00079
00080             FileOpenPicker filePicker = new FileOpenPicker();
00081             filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
00082             filePicker.FileTypeFilter.Add(".mp3");
00083             filePicker.ViewMode = PickerViewMode.Thumbnail;
00084             StorageFile file = await filePicker.PickSingleFileAsync();
00085
00086             // File can be null if cancel is hit in the file picker
00087             if (file == null)
00088             {
00089                 return;
00090             }
00091
00092             CreateAudioFileInputNodeResult fileInputNodeResult = await graph.CreateFileInputNodeAsync(file);
00093             if (fileInputNodeResult.Status != AudioFileNodeCreationStatus.Success)
00094             {
00095                 // Cannot read file
00096                 rootPage.NotifyUser(String.Format("Cannot read input file because {0}", fileInputNodeResult.Status.ToString()), NotifyType.ErrorMessage);
00097                 return;
00098             }
00099
00100             fileInputNode = fileInputNodeResult.FileInputNode;
00101             fileInputNode.AddOutgoingConnection(deviceOutputNode);
00102             fileButton.Background = new SolidColorBrush(Colors.Green);
00103
00104             // Event Handler for file completion
00105             fileInputNode.FileCompleted += FileInput_FileCompleted;
00106
00107             // Enable the button to start the graph
00108             graphButton.IsEnabled = true;
00109
00110             // Create the custom effect and apply to the FileInput node
00111             AddCustomEffect();
00112         }
00113
00114         private void Graph_Click(object sender, RoutedEventArgs e)
00115         {
00116             TogglePlay();
00117         }
00118
00119         private void TogglePlay()
00120         {
00121             // Toggle playback
00122             if (graphButton.Content.Equals("Start Graph"))
00123             {
00124                 graph.Start();
00125                 graphButton.Content = "Stop Graph";
00126                 audioPipe.Fill = new SolidColorBrush(Colors.Blue);
00127             }
00128             else
00129             {
00130                 graph.Stop();
00131                 graphButton.Content = "Start Graph";
00132                 audioPipe.Fill = new SolidColorBrush(Color.FromArgb(255, 49, 49, 49));
00133             }
00134         }
00135
00136         private async Task CreateAudioGraph()
00137         {
00138             // Create an AudioGraph with default settings
00139             AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media);
00140             CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings);
00141
00142             if (result.Status != AudioGraphCreationStatus.Success)
00143             {
00144                 // Cannot create graph
00145                 rootPage.NotifyUser(String.Format("AudioGraph Creation Error because {0}", result.Status.ToString()), NotifyType.ErrorMessage);
00146                 return;
00147             }
00148
00149             graph = result.Graph;
00150
00151             // Create a device output node
00152             CreateAudioDeviceOutputNodeResult deviceOutputResult = await graph.CreateDeviceOutputNodeAsync();
00153
00154             if (deviceOutputResult.Status != AudioDeviceNodeCreationStatus.Success)
00155             {
00156                 // Cannot create device output
00157                 rootPage.NotifyUser(String.Format("Audio Device Output unavailable because {0}", deviceOutputResult.Status.ToString()), NotifyType.ErrorMessage);
00158                 speakerContainer.Background = new SolidColorBrush(Colors.Red);
00159                 return;
00160             }
00161
00162             deviceOutputNode = deviceOutputResult.DeviceOutputNode;
00163             rootPage.NotifyUser("Device Output Node successfully created", NotifyType.StatusMessage);
00164             speakerContainer.Background = new SolidColorBrush(Colors.Green);
00165         }
00166
00167         private void AddCustomEffect()
00168         {
00169             // Create a property set and add a property/value pair
00170             PropertySet echoProperties = new PropertySet();
00171             echoProperties.Add("Mix", 0.5f);
00172
00173             // Instantiate the custom effect defined in the 'CustomEffect' project
00174             AudioEffectDefinition echoEffectDefinition = new AudioEffectDefinition(typeof(AudioEchoEffect).FullName, echoProperties);
00175             fileInputNode.EffectDefinitions.Add(echoEffectDefinition);
00176         }
00177
00178         // Event handler for file completion event
00179         private async void FileInput_FileCompleted(AudioFileInputNode sender, object args)
00180         {
00181             // File playback is done. Stop the graph
00182             graph.Stop();
00183
00184             // Reset the file input node so starting the graph will resume playback from beginning of the file
00185             sender.Reset();
00186
00187             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00188             {
00189                 rootPage.NotifyUser("End of file reached", NotifyType.StatusMessage);
00190                 graphButton.Content = "Start Graph";
00191             });
00192         }
00193     }
00194 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Camera.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Camera.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Camera.h"
00014 #include "StereoProjection.h"
00015
00016 using namespace DirectX;
00017
00018 #undef min // Use __min instead.
00019 #undef max // Use __max instead.
00020
00021 Camera::Camera()
00022 {
00023     // Setup the view matrix.
00024     SetViewParams(
00025         XMFLOAT3(0.0f, 0.0f, 0.0f),   // Default eye position.
00026         XMFLOAT3(0.0f, 0.0f, 1.0f),   // Default look at position.
00027         XMFLOAT3(0.0f, 1.0f, 0.0f)    // Default up vector.
00028         );
00029
00030     // Setup the projection matrix.
00031     SetProjParams(XM_PI / 4, 1.0f, 1.0f, 1000.0f);
00032 }
00033
00034 void Camera::LookDirection(_In_ XMFLOAT3 lookDirection)
00035 {
00036     XMFLOAT3 lookAt;
00037     lookAt.x = m_eye.x + lookDirection.x;
00038     lookAt.y = m_eye.y + lookDirection.y;
00039     lookAt.z = m_eye.z + lookDirection.z;
00040
00041     SetViewParams(m_eye, lookAt, m_up);
00042 }
00043
00044 void Camera::Eye(_In_ XMFLOAT3 eye)
00045 {
00046     SetViewParams(eye, m_lookAt, m_up);
00047 }
00048
00049 void Camera::SetViewParams(
00050     _In_ XMFLOAT3 eye,
00051     _In_ XMFLOAT3 lookAt,
00052     _In_ XMFLOAT3 up
00053     )
00054 {
00055     m_eye = eye;
00056     m_lookAt = lookAt;
00057     m_up = up;
00058
00059     // Calculate the view matrix.
00060     XMMATRIX view = XMMatrixLookAtLH(
00061         XMLoadFloat3(&m_eye),
00062         XMLoadFloat3(&m_lookAt),
00063         XMLoadFloat3(&m_up)
00064         );
00065
00066     XMVECTOR det;
00067     XMMATRIX inverseView = XMMatrixInverse(&det, view);
00068     XMStoreFloat4x4(&m_viewMatrix, view);
00069     XMStoreFloat4x4(&m_inverseView, inverseView);
00070
00071     // The axis basis vectors and camera position are stored inside the
00072     // position matrix in the 4 rows of the camera's world matrix.
00073     // To figure out the yaw/pitch of the camera, we just need the Z basis vector.
00074     XMFLOAT3 zBasis;
00075     XMStoreFloat3(&zBasis, inverseView.r[2]);
00076
00077     m_cameraYawAngle = atan2f(zBasis.x, zBasis.z);
00078
00079     float len = sqrtf(zBasis.z * zBasis.z + zBasis.x * zBasis.x);
00080     m_cameraPitchAngle = atan2f(zBasis.y, len);
00081 }
00082
00083 void Camera::SetProjParams(
00084     _In_ float fieldOfView,
00085     _In_ float aspectRatio,
00086     _In_ float nearPlane,
00087     _In_ float farPlane
00088     )
00089 {
00090     // Set attributes for the projection matrix.
00091     m_fieldOfView = fieldOfView;
00092     m_aspectRatio = aspectRatio;
00093     m_nearPlane = nearPlane;
00094     m_farPlane = farPlane;
00095     XMStoreFloat4x4(
00096         &m_projectionMatrix,
00097         XMMatrixPerspectiveFovLH(
00098             m_fieldOfView,
00099             m_aspectRatio,
00100             m_nearPlane,
00101             m_farPlane
00102             )
00103         );
00104
00105     STEREO_PARAMETERS* stereoParams = nullptr;
00106     // Update the projection matrix.
00107     XMStoreFloat4x4(
00108         &m_projectionMatrixLeft,
00109         MatrixStereoProjectionFovLH(
00110             stereoParams,
00111             STEREO_CHANNEL::LEFT,
00112             m_fieldOfView,
00113             m_aspectRatio,
00114             m_nearPlane,
00115             m_farPlane,
00116             STEREO_MODE::NORMAL
00117             )
00118         );
00119
00120     XMStoreFloat4x4(
00121         &m_projectionMatrixRight,
00122         MatrixStereoProjectionFovLH(
00123             stereoParams,
00124             STEREO_CHANNEL::RIGHT,
00125             m_fieldOfView,
00126             m_aspectRatio,
00127             m_nearPlane,
00128             m_farPlane,
00129             STEREO_MODE::NORMAL
00130             )
00131         );
00132 }
00133
00134 DirectX::XMMATRIX Camera::View()
00135 {
00136     return XMLoadFloat4x4(&m_viewMatrix);
00137 }
00138
00139 DirectX::XMMATRIX Camera::Projection()
00140 {
00141     return XMLoadFloat4x4(&m_projectionMatrix);
00142 }
00143
00144 DirectX::XMMATRIX Camera::LeftEyeProjection()
00145 {
00146     return XMLoadFloat4x4(&m_projectionMatrixLeft);
00147 }
00148
00149 DirectX::XMMATRIX Camera::RightEyeProjection()
00150 {
00151     return XMLoadFloat4x4(&m_projectionMatrixRight);
00152 }
00153
00154 DirectX::XMMATRIX Camera::World()
00155 {
00156     return XMLoadFloat4x4(&m_inverseView);
00157 }
00158
00159 DirectX::XMFLOAT3 Camera::Eye()
00160 {
00161     return m_eye;
00162 }
00163
00164 DirectX::XMFLOAT3 Camera::LookAt()
00165 {
00166     return m_lookAt;
00167 }
00168
00169 float Camera::NearClipPlane()
00170 {
00171     return m_nearPlane;
00172 }
00173
00174 float Camera::FarClipPlane()
00175 {
00176     return m_farPlane;
00177 }
00178
00179 float Camera::Pitch()
00180 {
00181     return m_cameraPitchAngle;
00182 }
00183
00184 float Camera::Yaw()
00185 {
00186     return m_cameraYawAngle;
00187 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/Scenario8_TransmitAPDU.h Source File

  • SmartCard
  • cppwinrt

Scenario8_TransmitAPDU.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario8_TransmitAPDU.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario8_TransmitAPDU : Scenario8_TransmitAPDUT<Scenario8_TransmitAPDU>
00019     {
00020         SDKTemplate::MainPage m_rootPage{ SDKTemplate::MainPage::Current() };
00021
00022         Scenario8_TransmitAPDU();
00023
00024         fire_and_forget Transmit_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const&);
00025     };
00026 }
00027
00028 namespace winrt::SDKTemplate::factory_implementation
00029 {
00030     struct Scenario8_TransmitAPDU : Scenario8_TransmitAPDUT<Scenario8_TransmitAPDU, implementation::Scenario8_TransmitAPDU>
00031     {
00032     };
00033 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Simple3DGame Member List

This is the complete list of members for Simple3DGame, including all inherited members.
__pad0__ | Simple3DGame |
BonusTime() | Simple3DGame | [inline]
BonusTime() | Simple3DGame | [inline]
BonusTime() | Simple3DGame | [inline]
ContinueGame() | Simple3DGame |
ContinueGame() | Simple3DGame |
ContinueGame() | Simple3DGame |
CurrentLevel() | Simple3DGame | [inline]
CurrentLevel() | Simple3DGame | [inline]
CurrentLevel() | Simple3DGame | [inline]
CycleBackground() | Simple3DGame |
FinalizeLoadLevel() | Simple3DGame |
FinalizeLoadLevel() | Simple3DGame |
FinalizeLoadLevel() | Simple3DGame |
GameActive() | Simple3DGame | [inline]
GameActive() | Simple3DGame | [inline]
GameActive() | Simple3DGame | [inline]
GameCamera() | Simple3DGame | [inline]
GameCamera() | Simple3DGame | [inline]
GameCamera() | Simple3DGame | [inline]
HighScore() | Simple3DGame | [inline]
HighScore() | Simple3DGame | [inline]
HighScore() | Simple3DGame | [inline]
Initialize(_In_ MoveLookController^controller, _In_ GameRenderer^renderer) | Simple3DGame |
Initialize(_In_ std::shared_ptr< MoveLookController > const &controller, _In_ std::shared_ptr< GameRenderer > const &renderer) | Simple3DGame |
Initialize(_In_ MoveLookController^controller, _In_ GameRenderer^renderer) | Simple3DGame |
InitializeAmmo() | Simple3DGame | [private]
InitializeAmmo() | Simple3DGame | [private]
InitializeAmmo() | Simple3DGame | [private]
InitializeGameConfig() | Simple3DGame | [private]
IsActivePlay() | Simple3DGame | [inline]
IsActivePlay() | Simple3DGame | [inline]
IsActivePlay() | Simple3DGame | [inline]
IsTrial() | Simple3DGame | [inline]
LevelActive() | Simple3DGame | [inline]
LevelActive() | Simple3DGame | [inline]
LevelActive() | Simple3DGame | [inline]
LevelCompleted() | Simple3DGame | [inline]
LevelCompleted() | Simple3DGame | [inline]
LevelCompleted() | Simple3DGame | [inline]
LoadGame() | Simple3DGame |
LoadGame() | Simple3DGame |
LoadGame() | Simple3DGame |
LoadHighScore() | Simple3DGame | [private]
LoadHighScore() | Simple3DGame | [private]
LoadHighScore() | Simple3DGame | [private]
LoadLevelAsync() | Simple3DGame |
LoadLevelAsync() | Simple3DGame |
LoadLevelAsync() | Simple3DGame |
LoadState() | Simple3DGame | [private]
LoadState() | Simple3DGame | [private]
LoadState() | Simple3DGame | [private]
m_activeBackground | Simple3DGame | [private]
m_ammo | Simple3DGame | [private]
m_ammo | Simple3DGame | [private]
m_ammoCount | Simple3DGame | [private]
m_ammoCount | Simple3DGame | [private]
m_ammoNext | Simple3DGame | [private]
m_ammoNext | Simple3DGame | [private]
m_audioController | Simple3DGame | [private]
m_camera | Simple3DGame | [private]
m_controller | Simple3DGame | [private]
m_controller | Simple3DGame | [private]
m_currentLevel | Simple3DGame | [private]
m_currentLevel | Simple3DGame | [private]
m_gameActive | Simple3DGame | [private]
m_gameConfig | Simple3DGame | [private]
m_level | Simple3DGame | [private]
m_level | Simple3DGame | [private]
m_levelActive | Simple3DGame | [private]
m_levelBonusTime | Simple3DGame | [private]
m_levelCount | Simple3DGame | [private]
m_levelCount | Simple3DGame | [private]
m_levelDuration | Simple3DGame | [private]
m_levelTimeRemaining | Simple3DGame | [private]
m_maxBound | Simple3DGame | [private]
m_minBound | Simple3DGame | [private]
m_objects | Simple3DGame | [private]
m_objects | Simple3DGame | [private]
m_player | Simple3DGame | [private]
m_player | Simple3DGame | [private]
m_renderer | Simple3DGame | [private]
m_renderer | Simple3DGame | [private]
m_renderObjects | Simple3DGame | [private]
m_renderObjects | Simple3DGame | [private]
m_savedState | Simple3DGame | [private]
m_timer | Simple3DGame | [private]
m_topScore | Simple3DGame | [private]
m_totalHits | Simple3DGame | [private]
m_totalShots | Simple3DGame | [private]
OnResuming() | Simple3DGame |
OnResuming() | Simple3DGame |
OnResuming() | Simple3DGame |
OnSuspending() | Simple3DGame |
OnSuspending() | Simple3DGame |
OnSuspending() | Simple3DGame |
PauseGame() | Simple3DGame |
PauseGame() | Simple3DGame |
PauseGame() | Simple3DGame |
RenderObjects() | Simple3DGame | [inline]
RenderObjects() | Simple3DGame | [inline]
RenderObjects() | Simple3DGame | [inline]
RunGame() | Simple3DGame |
RunGame() | Simple3DGame |
RunGame() | Simple3DGame |
SaveHighScore() | Simple3DGame | [private]
SaveHighScore() | Simple3DGame | [private]
SaveHighScore() | Simple3DGame | [private]
SaveState() | Simple3DGame | [private]
SaveState() | Simple3DGame | [private]
SaveState() | Simple3DGame | [private]
SetBackground(uint32 background) | Simple3DGame |
SetCurrentLevelToSavedState() | Simple3DGame |
SetCurrentLevelToSavedState() | Simple3DGame |
SetCurrentLevelToSavedState() | Simple3DGame |
Simple3DGame() | Simple3DGame |
StartLevel() | Simple3DGame |
StartLevel() | Simple3DGame |
StartLevel() | Simple3DGame |
TimeRemaining() | Simple3DGame | [inline]
TimeRemaining() | Simple3DGame | [inline]
TimeRemaining() | Simple3DGame | [inline]
TotalHits() | Simple3DGame | [inline]
TotalHits() | Simple3DGame | [inline]
TotalHits() | Simple3DGame | [inline]
TotalShots() | Simple3DGame | [inline]
TotalShots() | Simple3DGame | [inline]
TotalShots() | Simple3DGame | [inline]
UpdateDynamics() | Simple3DGame | [private]
UpdateDynamics() | Simple3DGame | [private]
UpdateDynamics() | Simple3DGame | [private]
UpdateGameConfig(Windows::ApplicationModel::Store::LicenseInformation^licenseInformation) | Simple3DGame |
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ShareFiles Member List

This is the complete list of members for ShareFiles, including all inherited members.
GetShareContent(DataRequest request) | ShareFiles | [inline, protected]
SelectFilesButton_Click(object sender, RoutedEventArgs e) | ShareFiles | [inline, private]
ShareFiles() | ShareFiles | [inline]
storageItems | ShareFiles | [private]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/ShareApplicationLink.xaml.h Source File

  • ShareSource
  • cpp

ShareApplicationLink.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ShareApplicationLink.xaml.h
00014 // Declaration of the ShareApplicationLink class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "SharePage.h"
00021 #include "ShareApplicationLink.g.h"
00022 #include "MainPage.xaml.h"
00023
00024 namespace SDKTemplate
00025 {
00026     public ref class ShareApplicationLink sealed
00027     {
00028     public:
00029         ShareApplicationLink();
00030
00031     protected:
00032         virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request) override;
00033
00034     private:
00035         Windows::UI::Color GetLogoBackgroundColor();
00036     };
00037
00038     [Windows::Foundation::Metadata::WebHostHidden]
00039     public ref class NegatingBoolConverter sealed : Windows::UI::Xaml::Data::IValueConverter
00040     {
00041     public:
00042         virtual Platform::Object^ Convert(Platform::Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^ parameter, Platform::String^ language)
00043         {
00044             bool v = safe_cast<bool>(value);
00045             return !v;
00046         }
00047
00048         virtual Platform::Object^ ConvertBack(Platform::Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^ parameter, Platform::String^ language)
00049         {
00050             bool v = safe_cast<bool>(value);
00051             return !v;
00052         }
00053     };
00054 }
Generated on Fri Nov 15 2024 22:21:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiScan/cs/SampleConfiguration.cs Source File

  • WiFiScan
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using WiFiScan;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "WiFiScan";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Cached Networks", ClassType=typeof(Scenario1_CachedNetworks)},
00026             new Scenario() { Title="Scan", ClassType=typeof(Scenario2_Scan)},
00027             new Scenario() { Title="Register for Scan Updates", ClassType=typeof(Scenario3_RegisterForUpdates)},
00028             new Scenario() { Title="Connect", ClassType=typeof(Scenario4_Connect)}
00029         };
00030     }
00031
00032     public class Scenario
00033     {
00034         public string Title { get; set; }
00035         public Type ClassType { get; set; }
00036     }
00037 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_CreateContacts Member List

This is the complete list of members for Scenario1_CreateContacts, including all inherited members.
_GetContactAnnotationList() | Scenario1_CreateContacts | [inline, private]
_GetContactList() | Scenario1_CreateContacts | [inline, private]
CreateTestContacts() | Scenario1_CreateContacts | [inline, private]
DeleteTestContacts() | Scenario1_CreateContacts | [inline, private]
rootPage | Scenario1_CreateContacts | [private]
Scenario1_CreateContacts() | Scenario1_CreateContacts | [inline]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Send Member List

This is the complete list of members for Scenario1_Send, including all inherited members.
connectedSocket | Scenario1_Send | [private]
OnConnected(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) | Scenario1_Send | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_Send | [inline, protected]
port | Scenario1_Send | [private]
rootPage | Scenario1_Send | [private]
Scenario1_Send() | Scenario1_Send | [inline]
SendButton_Click(object sender, RoutedEventArgs e) | Scenario1_Send | [inline, private]
tcpListener | Scenario1_Send | [private]
Generated on Fri Nov 15 2024 22:24:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SignatureMessage Member List

This is the complete list of members for SignatureMessage, including all inherited members.
PublicKeyHint | SignatureMessage
Signature | SignatureMessage
UserId | SignatureMessage
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DAdvancedColorImages/cpp/D2DAdvancedColorImages/FilmicEffect.h Source File

  • D2DAdvancedColorImages
  • cpp
  • D2DAdvancedColorImages

FilmicEffect.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 DEFINE_GUID(GUID_FilmicEffectPixelShader, 0x4214db42, 0x3bc5, 0x4f17, 0xb8, 0x59, 0x9d, 0x29, 0x15, 0x27, 0x4a, 0x6c);
00013 DEFINE_GUID(CLSID_CustomFilmicEffect, 0x40e0e874, 0x562c, 0x480f, 0x9b, 0x3e, 0x69, 0xf8, 0x42, 0x25, 0x59, 0xc9);
00014
00015 // Our effect contains one transform, which is simply a wrapper around a pixel shader. As such,
00016 // we can simply make the effect itself act as the transform.
00017 class FilmicEffect : public ID2D1EffectImpl, public ID2D1DrawTransform
00018 {
00019 public:
00020     // Declare effect registration methods.
00021     static HRESULT Register(_In_ ID2D1Factory1* pFactory);
00022
00023     static HRESULT __stdcall CreateFilmicImpl(_Outptr_ IUnknown** ppEffectImpl);
00024
00025     // Declare ID2D1EffectImpl implementation methods.
00026     IFACEMETHODIMP Initialize(
00027         _In_ ID2D1EffectContext* pContextInternal,
00028         _In_ ID2D1TransformGraph* pTransformGraph
00029         );
00030
00031     IFACEMETHODIMP PrepareForRender(D2D1_CHANGE_TYPE changeType);
00032
00033     IFACEMETHODIMP SetGraph(_In_ ID2D1TransformGraph* pGraph);
00034
00035     // Declare ID2D1DrawTransform implementation methods.
00036     IFACEMETHODIMP SetDrawInfo(_In_ ID2D1DrawInfo* pRenderInfo);
00037
00038     // Declare ID2D1Transform implementation methods.
00039     IFACEMETHODIMP MapOutputRectToInputRects(
00040         _In_ const D2D1_RECT_L* pOutputRect,
00041         _Out_writes_(inputRectCount) D2D1_RECT_L* pInputRects,
00042         UINT32 inputRectCount
00043         ) const;
00044
00045     IFACEMETHODIMP MapInputRectsToOutputRect(
00046         _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputRects,
00047         _In_reads_(inputRectCount) CONST D2D1_RECT_L* pInputOpaqueSubRects,
00048         UINT32 inputRectCount,
00049         _Out_ D2D1_RECT_L* pOutputRect,
00050         _Out_ D2D1_RECT_L* pOutputOpaqueSubRect
00051         );
00052
00053     IFACEMETHODIMP MapInvalidRect(
00054         UINT32 inputIndex,
00055         D2D1_RECT_L invalidInputRect,
00056         _Out_ D2D1_RECT_L* pInvalidOutputRect
00057         ) const;
00058
00059     // Declare ID2D1TransformNode implementation methods.
00060     IFACEMETHODIMP_(UINT32) GetInputCount() const;
00061
00062     // Declare IUnknown implementation methods.
00063     IFACEMETHODIMP_(ULONG) AddRef();
00064     IFACEMETHODIMP_(ULONG) Release();
00065     IFACEMETHODIMP QueryInterface(_In_ REFIID riid, _Outptr_ void** ppOutput);
00066
00067 private:
00068     FilmicEffect();
00069     HRESULT UpdateConstants();
00070
00071     inline static float Clamp(float v, float low, float high)
00072     {
00073         return (v < low) ? low : (v > high) ? high : v;
00074     }
00075
00076     inline static float Round(float v)
00077     {
00078         return floor(v + 0.5f);
00079     }
00080
00081     // Prevents over/underflows when adding longs.
00082     inline static long SafeAdd(long base, long valueToAdd)
00083     {
00084         if (valueToAdd >= 0)
00085         {
00086             return ((base + valueToAdd) >= base) ? (base + valueToAdd) : LONG_MAX;
00087         }
00088         else
00089         {
00090             return ((base + valueToAdd) <= base) ? (base + valueToAdd) : LONG_MIN;
00091         }
00092     }
00093
00094     // This struct defines the constant buffer of our pixel shader.
00095     struct
00096     {
00097         float dpi;
00098     } m_constants;
00099
00100     Microsoft::WRL::ComPtr<ID2D1DrawInfo>      m_drawInfo;
00101     Microsoft::WRL::ComPtr<ID2D1EffectContext> m_effectContext;
00102     LONG                                       m_refCount;
00103     D2D1_RECT_L                                m_inputRect;
00104     float                                      m_dpi;
00105 };
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampDevice/cpp/Scenario1_GetLamp.xaml.h Source File

  • LampDevice
  • cpp

Scenario1_GetLamp.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_GetLamp.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario1_GetLamp sealed
00021     {
00022     public:
00023         Scenario1_GetLamp();
00024
00025     protected:
00026         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00027
00028     private:
00029         MainPage^ _rootPage;
00030
00031         void InitLampBtn_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032         void GetDefaultAsyncBtn_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033
00034         Concurrency::task<void> LogStatusToOutputBoxAsync(Platform::String^ message);
00035         Concurrency::task<void> LogStatusAsync(Platform::String^ message, NotifyType type);
00036     };
00037 }
Generated on Fri Nov 15 2024 22:20:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/FaceMesh.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

FaceMesh.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "FaceMesh.h"
00014 #include "ConstantBuffers.h"
00015
00016 using namespace DirectX;
00017
00018 FaceMesh::FaceMesh(_In_ winrt::com_ptr<ID3D11Device3> const& device)
00019 {
00020     D3D11_BUFFER_DESC bd = { 0 };
00021     D3D11_SUBRESOURCE_DATA initData = { 0 };
00022
00023     PNTVertex target_vertices[] =
00024     {
00025         {XMFLOAT3(0.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(1.0f, 1.0f)},
00026         {XMFLOAT3(1.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 1.0f)},
00027         {XMFLOAT3(1.0f, 1.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(0.0f, 0.0f)},
00028         {XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT2(1.0f, 0.0f)}
00029     };
00030     WORD target_indices[] =
00031     {
00032         0, 1, 2,
00033         0, 2, 3,
00034         0, 2, 1,
00035         0, 3, 2
00036     };
00037
00038     m_vertexCount = 4;
00039     m_indexCount = 12;
00040
00041     bd.Usage = D3D11_USAGE_DEFAULT;
00042     bd.ByteWidth = sizeof(PNTVertex) * m_vertexCount;
00043     bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
00044     bd.CPUAccessFlags = 0;
00045     initData.pSysMem = target_vertices;
00046     winrt::check_hresult(
00047         device->CreateBuffer(&bd, &initData, m_vertexBuffer.put())
00048         );
00049
00050     bd.Usage = D3D11_USAGE_DEFAULT;
00051     bd.ByteWidth = sizeof(WORD) * m_indexCount;
00052     bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
00053     bd.CPUAccessFlags = 0;
00054     initData.pSysMem = target_indices;
00055     winrt::check_hresult(
00056         device->CreateBuffer(&bd, &initData, m_indexBuffer.put())
00057         );
00058 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cpp/Scenario2_Connector.xaml.cpp Source File

  • WiFiDirect
  • cpp

Scenario2_Connector.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Connector.xaml.h"
00014
00015 using namespace SDKTemplate;
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Controls;
00021 using namespace Windows::UI::Xaml::Controls::Primitives;
00022 using namespace Windows::UI::Xaml::Data;
00023 using namespace Windows::UI::Xaml::Input;
00024 using namespace Windows::UI::Xaml::Media;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace Windows::Devices::WiFiDirect;
00027 using namespace Windows::Devices::Enumeration;
00028 using namespace Platform::Collections;
00029 using namespace Windows::UI::Core;
00030 using namespace Windows::Storage::Streams;
00031 using namespace Windows::Networking::Sockets;
00032 using namespace Windows::Foundation::Collections;
00033 using namespace Windows::UI::Xaml::Data;
00034 using namespace Windows::ApplicationModel::Resources::Core;
00035
00036 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00037
00038 Scenario2_Connector::Scenario2_Connector() : rootPage(MainPage::Current)
00039 {
00040     InitializeComponent();
00041
00042     _discoveredDevices = ref new Vector<DiscoveredDevice^>();
00043     lvDiscoveredDevices->ItemsSource = _discoveredDevices;
00044     lvDiscoveredDevices->SelectionMode = ListViewSelectionMode::Single;
00045
00046     _connectedDevices = ref new Vector<ConnectedDevice^>();
00047     lvConnectedDevices->ItemsSource = _connectedDevices;
00048     lvConnectedDevices->SelectionMode = ListViewSelectionMode::Single;
00049 }
00050
00051 void SDKTemplate::Scenario2_Connector::btnWatcher_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00052 {
00053     if (_fWatcherStarted == false)
00054     {
00055         btnWatcher->Content = "Stop Watcher";
00056         _fWatcherStarted = true;
00057
00058         _discoveredDevices->Clear();
00059         rootPage->NotifyUser("Finding Devices...", NotifyType::StatusMessage);
00060
00061         _deviceWatcher = nullptr;
00062         String^ deviceSelector = WiFiDirectDevice::GetDeviceSelector((cmbDeviceSelector->SelectedItem->ToString()->Equals("Device Interface") == true) ?
00063             WiFiDirectDeviceSelectorType::DeviceInterface : WiFiDirectDeviceSelectorType::AssociationEndpoint);
00064
00065         Vector<String^>^ requestedProperties = ref new Vector<String^>();
00066         requestedProperties->Append("System.Devices.WiFiDirect.InformationElements");
00067
00068         _deviceWatcher = DeviceInformation::CreateWatcher(deviceSelector, requestedProperties);
00069
00070         _deviceAddedToken = _deviceWatcher->Added += ref new TypedEventHandler<DeviceWatcher^, DeviceInformation^>(this,
00071             &Scenario2_Connector::OnDeviceAdded, CallbackContext::Same);
00072
00073         _deviceRemovedToken = _deviceWatcher->Removed += ref new TypedEventHandler<DeviceWatcher^, DeviceInformationUpdate^>(this,
00074             &Scenario2_Connector::OnDeviceRemoved, CallbackContext::Same);
00075
00076         _deviceUpdatedToken = _deviceWatcher->Updated += ref new TypedEventHandler<DeviceWatcher^, DeviceInformationUpdate^>(this,
00077             &Scenario2_Connector::OnDeviceUpdated, CallbackContext::Same);
00078
00079         _deviceWatcherEnumerationCompletedToken = _deviceWatcher->EnumerationCompleted += ref new TypedEventHandler<DeviceWatcher^, Object^>(this,
00080             &Scenario2_Connector::OnEnumerationCompleted, CallbackContext::Same);
00081
00082         _deviceWatcherStoppedToken = _deviceWatcher->Stopped += ref new TypedEventHandler<DeviceWatcher^, Object^>(this,
00083             &Scenario2_Connector::OnStopped, CallbackContext::Same);
00084
00085         _deviceWatcher->Start();
00086     }
00087     else
00088     {
00089         btnWatcher->Content = "Start Watcher";
00090         _fWatcherStarted = false;
00091
00092         _deviceWatcher->Added -= _deviceAddedToken;
00093         _deviceWatcher->Removed -= _deviceRemovedToken;
00094         _deviceWatcher->Updated -= _deviceUpdatedToken;
00095         _deviceWatcher->EnumerationCompleted -= _deviceWatcherEnumerationCompletedToken;
00096         _deviceWatcher->Stopped -= _deviceWatcherStoppedToken;
00097
00098         _deviceWatcher->Stop();
00099     }
00100 }
00101
00102 void SDKTemplate::Scenario2_Connector::OnDeviceAdded(DeviceWatcher^ deviceWatcher, DeviceInformation^ deviceInfo)
00103 {
00104     Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
00105         ref new DispatchedHandler([this, deviceInfo]()
00106     {
00107         std::lock_guard<std::mutex> lock(_discoveryMutex);
00108
00109         _discoveredDevices->Append(ref new DiscoveredDevice(deviceInfo));
00110     }));
00111 }
00112
00113 void SDKTemplate::Scenario2_Connector::OnDeviceRemoved(DeviceWatcher^ deviceWatcher, DeviceInformationUpdate^ deviceInfoUpdate)
00114 {
00115     Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
00116         ref new DispatchedHandler([this, deviceInfoUpdate]()
00117     {
00118         std::lock_guard<std::mutex> lock(_discoveryMutex);
00119
00120         for (UINT idx = 0; idx < _discoveredDevices->Size; idx++)
00121         {
00122             DiscoveredDevice^ discoveredDevice = (DiscoveredDevice^)(_discoveredDevices->GetAt(idx));
00123
00124             if (discoveredDevice->DeviceInfo->Id->ToString()->Equals(deviceInfoUpdate->Id))
00125             {
00126                 _discoveredDevices->RemoveAt(idx);
00127                 break;
00128             }
00129         }
00130     }));
00131 }
00132
00133 void SDKTemplate::Scenario2_Connector::OnDeviceUpdated(DeviceWatcher^ deviceWatcher, DeviceInformationUpdate^ deviceInfoUpdate)
00134 {
00135     Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
00136         ref new DispatchedHandler([this, deviceInfoUpdate]()
00137     {
00138         std::lock_guard<std::mutex> lock(_discoveryMutex);
00139
00140         for (UINT idx = 0; idx < _discoveredDevices->Size; idx++)
00141         {
00142             DiscoveredDevice^ discoveredDevice = (DiscoveredDevice^)(_discoveredDevices->GetAt(idx));
00143
00144             if (discoveredDevice->DeviceInfo->Id->ToString()->Equals(deviceInfoUpdate->Id))
00145             {
00146                 discoveredDevice->DeviceInfo->Update(deviceInfoUpdate);
00147                 _discoveredDevices->SetAt(idx, discoveredDevice);
00148                 break;
00149             }
00150         }
00151     }));
00152 }
00153
00154 void SDKTemplate::Scenario2_Connector::OnEnumerationCompleted(DeviceWatcher^ deviceWatcher, Object^ o)
00155 {
00156     rootPage->NotifyUserFromBackground("DeviceWatcher enumeration completed", NotifyType::StatusMessage);
00157 }
00158
00159 void SDKTemplate::Scenario2_Connector::OnStopped(DeviceWatcher^ deviceWatcher, Object^ o)
00160 {
00161     rootPage->NotifyUserFromBackground("DeviceWatcher stopped", NotifyType::StatusMessage);
00162 }
00163
00164 void SDKTemplate::Scenario2_Connector::btnIe_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00165 {
00166     if (lvDiscoveredDevices->SelectedItems->Size == 0)
00167     {
00168         rootPage->NotifyUser("No device selected, please select one", NotifyType::ErrorMessage);
00169         return;
00170     }
00171
00172     auto selectedDevices = lvDiscoveredDevices->SelectedItems;
00173
00174     for (UINT idx = 0; idx < selectedDevices->Size; idx++)
00175     {
00176         try
00177         {
00178             ListViewItem^ lviDiscoveredDevice = (ListViewItem^)(selectedDevices->GetAt(idx));
00179             auto iECollection = WiFiDirectInformationElement::CreateFromDeviceInformation((DeviceInformation^)lviDiscoveredDevice->Tag);
00180
00181             if (iECollection->Size == 0)
00182             {
00183                 rootPage->NotifyUser("No Information Elements found", NotifyType::StatusMessage);
00184                 return;
00185             }
00186
00187             String^ strIeOutput = "";
00188             String^ strIe = "N/A";
00189
00190             for (UINT idx = 0; idx < iECollection->Size; idx++)
00191             {
00192                 WiFiDirectInformationElement^ ie = iECollection->GetAt(idx);
00193
00194                 if (ie->Oui->Equals(MsftOui))
00195                 {
00196                     strIeOutput->Concat(strIeOutput, "Microsoft IE: ");
00197                 }
00198                 else if (ie->Oui->Equals(WfaOui))
00199                 {
00200                     strIeOutput->Concat(strIeOutput, "WFA IE: ");
00201                 }
00202                 else if (ie->Oui->Equals(CustomOui))
00203                 {
00204                     strIeOutput->Concat(strIeOutput, "Custom IE: ");
00205
00206                     DataReader^ dataReader = DataReader::FromBuffer(ie->Value);
00207                     dataReader->UnicodeEncoding = UnicodeEncoding::Utf8;
00208                     dataReader->ByteOrder = ByteOrder::LittleEndian;
00209
00210                     strIe = dataReader->ReadString(dataReader->ReadUInt32());
00211                 }
00212                 else
00213                 {
00214                     strIeOutput->Concat(strIeOutput, "Unknown IE: ");
00215                 }
00216
00217                 strIeOutput += "OUI Type: " + ie->OuiType.ToString() + " OUI: " + ie->Oui->ToString() + " IE Data: " + strIe;
00218             }
00219
00220             rootPage->NotifyUser(strIeOutput, NotifyType::StatusMessage);
00221         }
00222         catch (Exception^ ex)
00223         {
00224             rootPage->NotifyUser("No Information element found: " + ex->Message, NotifyType::ErrorMessage);
00225         }
00226     }
00227 }
00228
00229
00230 void SDKTemplate::Scenario2_Connector::btnFromId_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00231 {
00232     if (lvDiscoveredDevices->SelectedItems->Size == 0)
00233     {
00234         rootPage->NotifyUser("No device selected, please select atleast one.", NotifyType::ErrorMessage);
00235         return;
00236     }
00237
00238     auto selectedDevices = lvDiscoveredDevices->SelectedItems;
00239
00240     for (UINT idx = 0; idx < selectedDevices->Size; idx++)
00241     {
00242         DiscoveredDevice^ discoveredDevice = (DiscoveredDevice^)selectedDevices->GetAt(idx);
00243         rootPage->NotifyUser("Connecting to " + discoveredDevice->DisplayName + "...", NotifyType::StatusMessage);
00244
00245         try
00246         {
00247             WiFiDirectConnectionParameters^ connectionParams = ref new WiFiDirectConnectionParameters();
00248             connectionParams->GroupOwnerIntent = (short)(wcstoul(txtGOIntent->Text->Data(), nullptr, 10));
00249
00250             // IMPORTANT: FromIdAsync needs to be called from the UI thread
00251             concurrency::task<WiFiDirectDevice^> fromIdTask(WiFiDirectDevice::FromIdAsync(discoveredDevice->DeviceInfo->Id, connectionParams));
00252             fromIdTask.then([this](concurrency::task<WiFiDirectDevice^> fromIdResultTask)
00253             {
00254                 try
00255                 {
00256                     WiFiDirectDevice^ wfdDevice = fromIdResultTask.get();
00257
00258                     // Register for the ConnectionStatusChanged event handler
00259                     wfdDevice->ConnectionStatusChanged += ref new TypedEventHandler<WiFiDirectDevice^, Platform::Object^>(this, &Scenario2_Connector::OnConnectionStatusChanged, CallbackContext::Same);
00260
00261                     auto endpointPairs = wfdDevice->GetConnectionEndpointPairs();
00262
00263                     rootPage->NotifyUser("Devices connected on L2 layer, connecting to IP Address: " + endpointPairs->GetAt(0)->RemoteHostName +
00264                         " Port: " + strServerPort, NotifyType::StatusMessage);
00265
00266                     // Wait for server to start listening on a socket
00267                     Sleep(5000);
00268
00269                     // Connect to Advertiser on L4 layer
00270                     StreamSocket^ clientSocket = ref new StreamSocket();
00271
00272                     concurrency::task<void> listenerTask(clientSocket->ConnectAsync(endpointPairs->GetAt(0)->RemoteHostName, strServerPort));
00273                     listenerTask.then([this, endpointPairs, wfdDevice, clientSocket](concurrency::task<void>)
00274                     {
00275                         SocketReaderWriter^ socketRW = ref new SocketReaderWriter(clientSocket, rootPage);
00276
00277                         String^ sessionId = "Session: " + rand().ToString();
00278
00279                         _connectedDevices->Append(ref new ConnectedDevice(sessionId, wfdDevice, socketRW));
00280
00281                         socketRW->ReadMessage();
00282                         socketRW->WriteMessage(sessionId);
00283
00284                         rootPage->NotifyUserFromBackground("Connected with remote side on L4 layer", NotifyType::StatusMessage);
00285                     });
00286                 }
00287                 catch (Exception^ ex)
00288                 {
00289                     rootPage->NotifyUserFromBackground("FromId operation threw an exception: " + ex->Message, NotifyType::ErrorMessage);
00290                 }
00291             });
00292         }
00293         catch (Exception^ ex)
00294         {
00295             rootPage->NotifyUserFromBackground("Connect operation threw an exception: " + ex->Message, NotifyType::ErrorMessage);
00296         }
00297     }
00298 }
00299
00300 void SDKTemplate::Scenario2_Connector::OnConnectionStatusChanged(WiFiDirectDevice^ sender, Object^ arg)
00301 {
00302     rootPage->NotifyUserFromBackground("Connection status changed: " + sender->ConnectionStatus.ToString(), NotifyType::StatusMessage);
00303 }
00304
00305 void SDKTemplate::Scenario2_Connector::btnSendMessage_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00306 {
00307     if (lvConnectedDevices->SelectedItems->Size == 0)
00308     {
00309         rootPage->NotifyUser("Please select a Session to send data", NotifyType::ErrorMessage);
00310         return;
00311     }
00312
00313     if (txtSendMessage->Text == "")
00314     {
00315         rootPage->NotifyUser("Please type a message to send", NotifyType::ErrorMessage);
00316         return;
00317     }
00318
00319     try
00320     {
00321         for (UINT idx = 0; idx < lvConnectedDevices->SelectedItems->Size; idx++)
00322         {
00323             ConnectedDevice^ connectedDevice = (ConnectedDevice^)(lvConnectedDevices->SelectedItems->GetAt(idx));
00324
00325             connectedDevice->SocketRW->WriteMessage(txtSendMessage->Text);
00326         }
00327     }
00328     catch (Exception^ ex)
00329     {
00330         rootPage->NotifyUser("Send threw an exception: " + ex->Message, NotifyType::ErrorMessage);
00331     }
00332 }
00333
00334 void SDKTemplate::Scenario2_Connector::btnClose_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00335 {
00336     if (lvConnectedDevices->SelectedItems->Size == 0)
00337     {
00338         rootPage->NotifyUser("Please select a device to close", NotifyType::ErrorMessage);
00339         return;
00340     }
00341
00342     try
00343     {
00344         for (UINT idx = 0; idx < lvConnectedDevices->SelectedItems->Size; idx++)
00345         {
00346             ConnectedDevice^ connectedDevice = (ConnectedDevice^)(lvConnectedDevices->SelectedItems->GetAt(idx));
00347
00348             // Close socket
00349             connectedDevice->SocketRW->Close();
00350
00351             // Close WiFiDirectDevice object
00352             delete connectedDevice->WfdDevice;
00353
00354             UINT index = 0;
00355             if (_connectedDevices->IndexOf(connectedDevice, &index))
00356             {
00357                 _connectedDevices->RemoveAt(index);
00358             }
00359
00360             rootPage->NotifyUser(connectedDevice->DisplayName + " closed successfully", NotifyType::StatusMessage);
00361         }
00362     }
00363     catch (Exception^ ex)
00364     {
00365         rootPage->NotifyUser("Close threw an exception: " + ex->Message, NotifyType::ErrorMessage);
00366     }
00367 }
Generated on Fri Nov 15 2024 22:22:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cs/cs/Scenario1_OvenClient.xaml.cs Source File

  • ProxyStubsForWinRTComponents
  • cs
  • cs

Scenario1_OvenClient.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using Microsoft.SDKSamples.Kitchen;
00008
00009 using Windows.Foundation;
00010 using Windows.UI.Xaml;
00011 using Windows.UI.Xaml.Controls;
00012 using Windows.UI.Xaml.Navigation;
00013 using SDKTemplate;
00014 using System;
00015
00016 namespace ProxyStubsForWinRTComponents
00017 {
00018     /// <summary>
00019     /// An empty page that can be used on its own or navigated to within a Frame.
00020     /// </summary>
00021     public sealed partial class OvenClient : Page
00022     {
00023         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00024         // as NotifyUser()
00025         MainPage rootPage = MainPage.Current;
00026
00027         public OvenClient()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         /// <summary>
00033         /// Invoked when this page is about to be displayed in a Frame.
00034         /// </summary>
00035         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00036         /// property is typically used to configure the page.</param>
00037         protected override void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039         }
00040
00041         /// <summary>
00042         /// Use the custom Oven and Bread Windows Runtime components.
00043         /// </summary>
00044         /// <param name="sender">Contains information about the button that fired the event.</param>
00045         /// <param name="e">Contains state information and event data associated with a routed event.</param>
00046         private void Start_Click(object sender, RoutedEventArgs e)
00047         {
00048             Dimensions dimensions;
00049             dimensions.Width = 2;
00050             dimensions.Height = 2;
00051             dimensions.Depth = 2;
00052
00053             // Component Creation
00054             Oven myOven = new Oven(dimensions);
00055
00056             // Getters and setters are accessed using property syntax
00057             OvenClientOutput.Text += "Oven volume is: " + myOven.Volume.ToString() + "\n";
00058
00059             // Register even listeners
00060             myOven.BreadBaked += new TypedEventHandler<Oven, Bread>(BreadCompletedHandler1);
00061             myOven.BreadBaked += new TypedEventHandler<Oven, Bread>(BreadCompletedHandler2);
00062             myOven.BreadBaked += new TypedEventHandler<Oven, Bread>(BreadCompletedHandler3);
00063
00064             // Unregister from an event using the -= syntax and a delegate instance
00065             myOven.BreadBaked -= new TypedEventHandler<Oven, Bread>(BreadCompletedHandler3);
00066
00067             // Bake a loaf of bread. This will trigger the BreadBaked event.
00068             myOven.BakeBread("Sourdough");
00069
00070             // Trigger the event again with a different preheat time
00071             myOven.ConfigurePreheatTemperature(OvenTemperature.High);
00072             myOven.BakeBread("Wheat");
00073         }
00074
00075         async private void BreadCompletedHandler1(Oven oven, Bread bread)
00076         {
00077             Action updateOutputText = () =>
00078                 {
00079                     OvenClientOutput.Text += "Event Handler 1: Invoked\n";
00080                     OvenClientOutput.Text += "Event Handler 1: Oven volume is: " + oven.Volume.ToString() + "\n";
00081                     OvenClientOutput.Text += "Event Handler 1: Bread flavor is: " + bread.Flavor + "\n";
00082                 };
00083
00084             if (OvenClientOutput.Dispatcher.HasThreadAccess)
00085             {
00086                 // If the current thread is the UI thread then execute the lambda.
00087                 updateOutputText();
00088             }
00089             else
00090             {
00091                 // If the current thread is not the UI thread use the dispatcher to execute the lambda on the UI thread.
00092                 await OvenClientOutput.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(updateOutputText));
00093             }
00094         }
00095
00096         async private void BreadCompletedHandler2(Oven oven, Bread bread)
00097         {
00098             Action updateOutputText = () =>
00099                 {
00100                     OvenClientOutput.Text += "Event Handler 2: Invoked\n";
00101                 };
00102
00103             if (OvenClientOutput.Dispatcher.HasThreadAccess)
00104             {
00105                 // If the current thread is the UI thread then execute the lambda.
00106                 updateOutputText();
00107             }
00108             else
00109             {
00110                 // If the current thread is not the UI thread use the dispatcher to execute the lambda on the UI thread.
00111                 await OvenClientOutput.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(updateOutputText));
00112             }
00113         }
00114
00115         async private void BreadCompletedHandler3(Oven oven, Bread bread)
00116         {
00117             // Event handler 3 was removed and will not be invoked
00118             Action updateOutputText = () =>
00119                 {
00120                     OvenClientOutput.Text += "Event Handler 3: Invoked\n";
00121                 };
00122
00123             if (OvenClientOutput.Dispatcher.HasThreadAccess)
00124             {
00125                 // If the current thread is the UI thread then execute the lambda.
00126                 updateOutputText();
00127             }
00128             else
00129             {
00130                 // If the current thread is not the UI thread use the dispatcher to execute the lambda on the UI thread.
00131                 await OvenClientOutput.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(updateOutputText));
00132             }
00133         }
00134     }
00135 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Scenario4_ForegroundGeofence.h Source File

  • Geolocation
  • cppwinrt

Scenario4_ForegroundGeofence.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_ForegroundGeofence.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario4_ForegroundGeofence : Scenario4_ForegroundGeofenceT<Scenario4_ForegroundGeofence>
00019     {
00020         Scenario4_ForegroundGeofence();
00021
00022         fire_and_forget OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00023         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const&);
00024
00025         void OnRemoveGeofenceItem(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00026         void OnRegisteredGeofenceListBoxSelectionChanged(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::Controls::SelectionChangedEventArgs const& e);
00027         fire_and_forget OnSetPositionToHere(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00028         void OnCreateGeofence(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00029
00030     private:
00031         SDKTemplate::MainPage m_rootPage{ MainPage::Current() };
00032
00033         static constexpr Windows::Foundation::TimeSpan defaultDwellTime = std::chrono::seconds(10);
00034
00035         // This special DateTime value is used by the Geofence to mean "start immediately".
00036         static constexpr Windows::Foundation::DateTime startImmediately{};
00037
00038         Windows::Foundation::IAsyncOperation<Windows::Devices::Geolocation::Geoposition> m_pendingOperation;
00039         Windows::Devices::Geolocation::Geofencing::GeofenceMonitor m_geofenceMonitor{ nullptr };
00040
00041         event_token m_visibilityChangedToken{};
00042         event_token m_geofenceStateChangedToken{};
00043         event_token m_geofenceStatusChangedToken{};
00044
00045         void OnVisibilityChanged(Windows::Foundation::IInspectable const&, Windows::UI::Core::VisibilityChangedEventArgs const& e);
00046         fire_and_forget OnGeofenceStatusChanged(Windows::Devices::Geolocation::Geofencing::GeofenceMonitor const& sender, Windows::Foundation::IInspectable const&);
00047         fire_and_forget OnGeofenceStateChanged(Windows::Devices::Geolocation::Geofencing::GeofenceMonitor const& sender, Windows::Foundation::IInspectable const&);
00048
00049         void SetStartDateTimeToUI(Windows::Foundation::DateTime dateTime);
00050         Windows::Devices::Geolocation::Geofencing::Geofence GenerateGeofence();
00051         void RefreshControlsFromGeofence(Windows::Devices::Geolocation::Geofencing::Geofence const& geofence);
00052         bool ParseDoubleFromTextBox(Windows::UI::Xaml::Controls::TextBox const& textBox, hstring const& name, double minValue, double maxValue, double& value);
00053         void AddGeofenceToRegisteredGeofenceListBox(Windows::Devices::Geolocation::Geofencing::Geofence const& geofence);
00054         void AddEventDescription(hstring const& eventDescription);
00055         bool ParseTimeSpan(hstring const& field, Windows::Foundation::TimeSpan defaultValue, Windows::Foundation::TimeSpan& value);
00056     };
00057 }
00058
00059 namespace winrt::SDKTemplate::factory_implementation
00060 {
00061     struct Scenario4_ForegroundGeofence : Scenario4_ForegroundGeofenceT<Scenario4_ForegroundGeofence, implementation::Scenario4_ForegroundGeofence>
00062     {
00063     };
00064 }
Generated on Fri Nov 15 2024 22:19:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LampArrayInfo Member List

This is the complete list of members for LampArrayInfo, including all inherited members.
displayName | LampArrayInfo |
id | LampArrayInfo |
lampArray | LampArrayInfo |
LampArrayInfo(string id, string displayName, LampArray lampArray) | LampArrayInfo | [inline]
Generated on Fri Nov 15 2024 22:23:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cpp/Scenario6_ManipulatingCursorAttributes.xaml.h Source File

  • LineDisplay
  • cpp

Scenario6_ManipulatingCursorAttributes.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario6_ManipulatingCursorAttributes.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     [Windows::UI::Xaml::Data::Bindable]
00021     public ref class Scenario6_ManipulatingCursorAttributes sealed
00022     {
00023     public:
00024         Scenario6_ManipulatingCursorAttributes();
00025
00026         property Windows::Foundation::Collections::IObservableVector<Windows::Devices::PointOfService::LineDisplayCursorType>^ SupportedCursorTypes
00027         {
00028             Windows::Foundation::Collections::IObservableVector<Windows::Devices::PointOfService::LineDisplayCursorType>^ get()
00029             {
00030                 return supportedCursorTypes;
00031             }
00032         }
00033
00034     protected:
00035         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038     private:
00039         MainPage^ rootPage = MainPage::Current;
00040         Windows::Devices::PointOfService::ClaimedLineDisplay^ lineDisplay;
00041
00042         Windows::Foundation::Collections::IObservableVector<Windows::Devices::PointOfService::LineDisplayCursorType>^ supportedCursorTypes =
00043             ref new Platform::Collections::Vector<Windows::Devices::PointOfService::LineDisplayCursorType>;
00044
00045         Concurrency::task<void> InitializeAsync();
00046
00047         void UpdateButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048         void DisplayTextButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049         void ResetButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00050     };
00051 }
Generated on Fri Nov 15 2024 22:20:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cppwinrt/Scenario4_TilePinned.h Source File

  • SecondaryTiles
  • cppwinrt

Scenario4_TilePinned.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_TilePinned.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario4_TilePinned : Scenario4_TilePinnedT<Scenario4_TilePinned>
00020     {
00021         Scenario4_TilePinned();
00022
00023         void TileExists_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024
00025     private:
00026         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario4_TilePinned : Scenario4_TilePinnedT<Scenario4_TilePinned, implementation::Scenario4_TilePinned>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:21:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CServiceBase Member List

This is the complete list of members for CServiceBase, including all inherited members.
Continue() | CServiceBase | [private]
CServiceBase(PWSTR pszServiceName, BOOL fCanStop=TRUE, BOOL fCanShutdown=TRUE, BOOL fCanPauseContinue=FALSE) | CServiceBase |
m_etwRegHandle | CServiceBase | [private]
m_name | CServiceBase | [private]
m_status | CServiceBase | [private]
m_statusHandle | CServiceBase | [private]
OnContinue() | CServiceBase | [protected, virtual]
OnPause() | CServiceBase | [protected, virtual]
OnShutdown() | CServiceBase | [protected, virtual]
OnStart(DWORD dwArgc, PWSTR *pszArgv) | CServiceBase | [protected, virtual]
OnStop() | CServiceBase | [protected, virtual]
Pause() | CServiceBase | [private]
Run(CServiceBase &service) | CServiceBase | [static]
s_service | CServiceBase | [private, static]
ServiceCtrlHandler(DWORD dwCtrl) | CServiceBase | [private, static]
ServiceMain(DWORD dwArgc, LPWSTR *lpszArgv) | CServiceBase | [private, static]
SetServiceStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode=NO_ERROR, DWORD dwWaitHint=0) | CServiceBase | [protected]
Shutdown() | CServiceBase | [private]
Start(DWORD dwArgc, PWSTR *pszArgv) | CServiceBase | [private]
Stop() | CServiceBase |
WriteErrorLogEntry(PWSTR pszFunction, DWORD dwError=GetLastError()) | CServiceBase | [protected]
WriteEventLogEntry(PWSTR pszMessage, BYTE bLevel) | CServiceBase | [protected, virtual]
~CServiceBase(void) | CServiceBase | [virtual]
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PlugInFilter Member List

This is the complete list of members for PlugInFilter, including all inherited members.
Dispose() | PlugInFilter | [inline]
innerFilter | PlugInFilter | [private]
PlugInFilter(IHttpFilter innerFilter) | PlugInFilter | [inline]
SendRequestAsync(HttpRequestMessage request) | PlugInFilter | [inline]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_DisplayRegion Member List

This is the complete list of members for Scenario2_DisplayRegion, including all inherited members.
appWindow | Scenario2_DisplayRegion | [private]
appWindowFrame | Scenario2_DisplayRegion | [private]
Button_Click(object sender, RoutedEventArgs e) | Scenario2_DisplayRegion | [inline, private]
GetOtherDisplayRegion(DisplayRegion currentAppDisplayRegion) | Scenario2_DisplayRegion | [inline, private]
NumberOfAvailableDisplayRegions() | Scenario2_DisplayRegion | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_DisplayRegion | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_DisplayRegion | [inline, protected]
Scenario2_DisplayRegion() | Scenario2_DisplayRegion | [inline]
Generated on Fri Nov 15 2024 22:23:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/DeviceHelpers.cpp Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

DeviceHelpers.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DeviceHelpers.h"
00014
00015 // NOTE: The following header files are only needed in order to demonstrate many of the
00016 // different device selectors available from Windows Runtime APIs. You will only need to include
00017 // the ones for the Windows Runtime API your actual scenario needs.
00018 #include "winrt/Windows.Devices.HumanInterfaceDevice.h"
00019 #include "winrt/Windows.Networking.Proximity.h"
00020 #include "winrt/Windows.Devices.Bluetooth.h"
00021 #include "winrt/Windows.Devices.WiFiDirect.h"
00022 #include "winrt/Windows.Media.Casting.h"
00023 #include "winrt/Windows.Media.DialProtocol.h"
00024 #include "winrt/Windows.Devices.Sensors.h"
00025 #include "winrt/Windows.Devices.PointOfService.h"
00026
00027 using namespace winrt;
00028 using namespace winrt::Windows::Devices::Enumeration;
00029 using namespace winrt::Windows::Foundation;
00030 using namespace winrt::Windows::Foundation::Collections;
00031 using namespace winrt::Windows::UI::Xaml::Media::Imaging;
00032 using namespace winrt::Windows::UI::Xaml::Data;
00033
00034 namespace winrt::SDKTemplate::implementation
00035 {
00036     IObservableVector<SDKTemplate::DeviceSelectorInfo> DeviceSelectorChoices::CommonDeviceSelectors()
00037     {
00038         return single_threaded_observable_vector<SDKTemplate::DeviceSelectorInfo>({
00039             // Pre-canned device class selectors
00040             make<DeviceSelectorInfo>(L"All Device Interfaces (default)", DeviceClass::All),
00041             make<DeviceSelectorInfo>(L"Audio Capture", DeviceClass::AudioCapture),
00042             make<DeviceSelectorInfo>(L"Audio Render", DeviceClass::AudioRender),
00043             make<DeviceSelectorInfo>(L"Image Scanner", DeviceClass::ImageScanner),
00044             make<DeviceSelectorInfo>(L"Location", DeviceClass::Location),
00045             make<DeviceSelectorInfo>(L"Portable Storage", DeviceClass::PortableStorageDevice),
00046             make<DeviceSelectorInfo>(L"Video Capture", DeviceClass::VideoCapture),
00047
00048             // A few examples of selectors built dynamically by windows runtime apis.
00049             make<DeviceSelectorInfo>(L"Human Interface (HID)", Windows::Devices::HumanInterfaceDevice::HidDevice::GetDeviceSelector(0, 0)),
00050             make<DeviceSelectorInfo>(L"Activity Sensor", Windows::Devices::Sensors::ActivitySensor::GetDeviceSelector()),
00051             make<DeviceSelectorInfo>(L"Pedometer", Windows::Devices::Sensors::Pedometer::GetDeviceSelector()),
00052             make<DeviceSelectorInfo>(L"Proximity", Windows::Networking::Proximity::ProximityDevice::GetDeviceSelector()),
00053             make<DeviceSelectorInfo>(L"Proximity Sensor", Windows::Devices::Sensors::ProximitySensor::GetDeviceSelector()), });
00054     }
00055
00056     namespace
00057     {
00058         SDKTemplate::DeviceSelectorInfo Bluetooth()
00059         {
00060             // Currently Bluetooth APIs don't provide a selector to get ALL devices that are both paired and non-paired.  Typically you wouldn't need this for common scenarios, but it's convenient to demonstrate the
00061             // various sample scenarios.
00062             return make<DeviceSelectorInfo>(L"Bluetooth", L"System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\"", DeviceInformationKind::AssociationEndpoint);
00063         }
00064
00065         SDKTemplate::DeviceSelectorInfo BluetoothUnpairedOnly()
00066         {
00067             return make<DeviceSelectorInfo>(L"Bluetooth (unpaired)", Windows::Devices::Bluetooth::BluetoothDevice::GetDeviceSelectorFromPairingState(false));
00068         }
00069
00070         SDKTemplate::DeviceSelectorInfo BluetoothPairedOnly()
00071         {
00072             return make<DeviceSelectorInfo>(L"Bluetooth (paired)", Windows::Devices::Bluetooth::BluetoothDevice::GetDeviceSelectorFromPairingState(true));
00073         }
00074
00075         SDKTemplate::DeviceSelectorInfo BluetoothLE()
00076         {
00077             // Currently Bluetooth APIs don't provide a selector to get ALL devices that are both paired and non-paired.  Typically you wouldn't need this for common scenarios, but it's convenient to demonstrate the
00078             // various sample scenarios.
00079             return make<DeviceSelectorInfo>(L"Bluetooth LE", L"System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\"", DeviceInformationKind::AssociationEndpoint);
00080         }
00081
00082         SDKTemplate::DeviceSelectorInfo BluetoothLEUnpairedOnly()
00083         {
00084             return make<DeviceSelectorInfo>(L"Bluetooth LE (unpaired)", Windows::Devices::Bluetooth::BluetoothLEDevice::GetDeviceSelectorFromPairingState(false));
00085         }
00086
00087         SDKTemplate::DeviceSelectorInfo BluetoothLEPairedOnly()
00088         {
00089             return make<DeviceSelectorInfo>(L"Bluetooth LE (paired)", Windows::Devices::Bluetooth::BluetoothLEDevice::GetDeviceSelectorFromPairingState(true));
00090         }
00091
00092         SDKTemplate::DeviceSelectorInfo WiFiDirect()
00093         {
00094             return make<DeviceSelectorInfo>(L"Wi-Fi Direct", Windows::Devices::WiFiDirect::WiFiDirectDevice::GetDeviceSelector(Windows::Devices::WiFiDirect::WiFiDirectDeviceSelectorType::AssociationEndpoint));
00095         }
00096
00097         SDKTemplate::DeviceSelectorInfo WiFiDirectPairedOnly()
00098         {
00099             return make<DeviceSelectorInfo>(L"Wi-Fi Direct (paired)", Windows::Devices::WiFiDirect::WiFiDirectDevice::GetDeviceSelector());
00100         }
00101
00102         SDKTemplate::DeviceSelectorInfo PointOfServicePrinter()
00103         {
00104             return make<DeviceSelectorInfo>(L"Point of Service Printer", Windows::Devices::PointOfService::PosPrinter::GetDeviceSelector());
00105         }
00106
00107         SDKTemplate::DeviceSelectorInfo VideoCasting()
00108         {
00109             return make<DeviceSelectorInfo>(L"Video Casting", Windows::Media::Casting::CastingDevice::GetDeviceSelector(Windows::Media::Casting::CastingPlaybackTypes::Video));
00110         }
00111
00112         SDKTemplate::DeviceSelectorInfo DialAllApps()
00113         {
00114             return make<DeviceSelectorInfo>(L"DIAL (All apps)", Windows::Media::DialProtocol::DialDevice::GetDeviceSelector(L""));
00115         }
00116
00117         // WSD and UPnP are unique in that there are currently no general WSD or UPnP APIs to USE the devices once you've discovered them.
00118         // You can pair the devices using DeviceInformation.Pairing.PairAsync etc, and you can USE them with the sockets APIs. However, since
00119         // there's no specific API right now, there's no *.GetDeviceSelector available.  That's why we just simply build the device selector
00120         // ourselves and specify the correct DeviceInformationKind (AssociationEndpoint).
00121         SDKTemplate::DeviceSelectorInfo Wsd()
00122         {
00123             return make<DeviceSelectorInfo>(L"Web Services on Devices (WSD)", L"System.Devices.Aep.ProtocolId:=\"{782232aa-a2f9-4993-971b-aedc551346b0}\"", DeviceInformationKind::AssociationEndpoint);
00124         }
00125
00126         SDKTemplate::DeviceSelectorInfo Upnp()
00127         {
00128             return make<DeviceSelectorInfo>(L"UPnP", L"System.Devices.Aep.ProtocolId:=\"{0e261de4-12f0-46e6-91ba-428607ccef64}\"", DeviceInformationKind::AssociationEndpoint);
00129         }
00130
00131         SDKTemplate::DeviceSelectorInfo NetworkCamera()
00132         {
00133             return make<DeviceSelectorInfo>(L"Web Services on Devices (NetworkCamera)", L"System.Devices.Aep.ProtocolId:=\"{43cc0de4-8ca8-4a56-805a-86fc63f21602}\"", DeviceInformationKind::AssociationEndpoint);
00134         }
00135
00136         void AddVideoCastingIfSupported(IObservableVector<SDKTemplate::DeviceSelectorInfo>& selectors)
00137         {
00138             try
00139             {
00140                 selectors.Append(VideoCasting());
00141             }
00142             catch (hresult_error const& ex)
00143             {
00144
00145                 if (ex.code() == HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED))
00146                 {
00147                     // Video casting is not supported by the system.
00148                 }
00149                 else
00150                 {
00151                     throw;
00152                 }
00153             }
00154         }
00155     }
00156
00157     IObservableVector<SDKTemplate::DeviceSelectorInfo> DeviceSelectorChoices::DevicePickerSelectors()
00158     {
00159         // Add all selectors that can be used with the DevicePicker
00160         IObservableVector<SDKTemplate::DeviceSelectorInfo> selectors = CommonDeviceSelectors();
00161         selectors.Append(BluetoothPairedOnly());
00162         selectors.Append(BluetoothUnpairedOnly());
00163         selectors.Append(BluetoothLEPairedOnly());
00164         selectors.Append(BluetoothLEUnpairedOnly());
00165         selectors.Append(WiFiDirect());
00166         selectors.Append(PointOfServicePrinter());
00167         AddVideoCastingIfSupported(selectors);
00168         selectors.Append(DialAllApps());
00169
00170         return selectors;
00171     }
00172
00173     IObservableVector<SDKTemplate::DeviceSelectorInfo> DeviceSelectorChoices::FindAllAsyncSelectors()
00174     {
00175         IObservableVector<SDKTemplate::DeviceSelectorInfo> selectors = CommonDeviceSelectors();
00176
00177         selectors.Append(BluetoothPairedOnly());
00178         selectors.Append(BluetoothLEPairedOnly());
00179         selectors.Append(WiFiDirectPairedOnly());
00180
00181         return selectors;
00182     }
00183
00184     IObservableVector<SDKTemplate::DeviceSelectorInfo> DeviceSelectorChoices::DeviceWatcherSelectors()
00185     {
00186         IObservableVector<SDKTemplate::DeviceSelectorInfo> selectors = CommonDeviceSelectors();
00187
00188         selectors.Append(Bluetooth());
00189         selectors.Append(BluetoothLE());
00190         selectors.Append(WiFiDirect());
00191         selectors.Append(PointOfServicePrinter());
00192         AddVideoCastingIfSupported(selectors);
00193         selectors.Append(DialAllApps());
00194         selectors.Append(Wsd());
00195         selectors.Append(Upnp());
00196
00197         return selectors;
00198     }
00199
00200     IObservableVector<SDKTemplate::DeviceSelectorInfo> DeviceSelectorChoices::BackgroundDeviceWatcherSelectors()
00201     {
00202         IObservableVector<SDKTemplate::DeviceSelectorInfo> selectors = CommonDeviceSelectors();
00203
00204         selectors.Append(BluetoothPairedOnly());
00205         selectors.Append(BluetoothLEPairedOnly());
00206         selectors.Append(WiFiDirectPairedOnly());
00207         selectors.Append(PointOfServicePrinter());
00208         AddVideoCastingIfSupported(selectors);
00209         selectors.Append(DialAllApps());
00210         selectors.Append(Wsd());
00211         selectors.Append(Upnp());
00212
00213         return selectors;
00214     }
00215
00216     IObservableVector<SDKTemplate::DeviceSelectorInfo> DeviceSelectorChoices::PairingSelectors()
00217     {
00218         IObservableVector<SDKTemplate::DeviceSelectorInfo> selectors = single_threaded_observable_vector<SDKTemplate::DeviceSelectorInfo>();
00219
00220         selectors.Append(Bluetooth());
00221         selectors.Append(BluetoothLE());
00222         selectors.Append(WiFiDirect());
00223         selectors.Append(PointOfServicePrinter());
00224         AddVideoCastingIfSupported(selectors);
00225         selectors.Append(Wsd());
00226         selectors.Append(Upnp());
00227         selectors.Append(NetworkCamera());
00228
00229         return selectors;
00230     }
00231
00232     IObservableVector<SDKTemplate::DeviceInformationKindChoice> DeviceInformationKindChoices::Choices()
00233     {
00234         return single_threaded_observable_vector<SDKTemplate::DeviceInformationKindChoice>({
00235             make<DeviceInformationKindChoice>(L"DeviceContainer", std::vector{ DeviceInformationKind::DeviceContainer }),
00236             make<DeviceInformationKindChoice>(L"Device", std::vector{ DeviceInformationKind::Device }),
00237             make<DeviceInformationKindChoice>(L"DeviceInterface (Default)", std::vector{ DeviceInformationKind::DeviceInterface }),
00238             make<DeviceInformationKindChoice>(L"DeviceInterfaceClass", std::vector{ DeviceInformationKind::DeviceInterfaceClass }),
00239             make<DeviceInformationKindChoice>(L"AssociationEndpointContainer", std::vector{ DeviceInformationKind::AssociationEndpointContainer }),
00240             make<DeviceInformationKindChoice>(L"AssociationEndpoint", std::vector{ DeviceInformationKind::AssociationEndpoint }),
00241             make<DeviceInformationKindChoice>(L"AssociationEndpointService", std::vector{ DeviceInformationKind::AssociationEndpointService }),
00242             make<DeviceInformationKindChoice>(L"AssociationEndpointService and DeviceInterface", std::vector{ DeviceInformationKind::AssociationEndpointService, DeviceInformationKind::DeviceInterface }),
00243         });
00244     }
00245
00246     IObservableVector<SDKTemplate::ProtectionLevelSelectorInfo> ProtectionSelectorChoices::Selectors()
00247     {
00248         return single_threaded_observable_vector<SDKTemplate::ProtectionLevelSelectorInfo>({
00249             make<ProtectionLevelSelectorInfo>(L"Default", DevicePairingProtectionLevel::Default),
00250             make<ProtectionLevelSelectorInfo>(L"None", DevicePairingProtectionLevel::None),
00251             make<ProtectionLevelSelectorInfo>(L"Encryption", DevicePairingProtectionLevel::Encryption),
00252             make<ProtectionLevelSelectorInfo>(L"Encryption and authentication", DevicePairingProtectionLevel::EncryptionAndAuthentication),
00253             });
00254     }
00255
00256
00257     DeviceInformationDisplay::DeviceInformationDisplay(::DeviceInformation const& deviceInfoIn)
00258         : m_deviceInfo(deviceInfoIn)
00259     {
00260         UpdateGlyphBitmapImage();
00261     }
00262
00263     void DeviceInformationDisplay::Update(DeviceInformationUpdate const& deviceInfoUpdate)
00264     {
00265         m_deviceInfo.Update(deviceInfoUpdate);
00266
00267         OnPropertyChanged(L"Kind");
00268         OnPropertyChanged(L"Id");
00269         OnPropertyChanged(L"Name");
00270         OnPropertyChanged(L"DeviceInformation");
00271         OnPropertyChanged(L"CanPair");
00272         OnPropertyChanged(L"IsPaired");
00273         OnPropertyChanged(L"GetPropertyForDisplay");
00274
00275         UpdateGlyphBitmapImage();
00276     }
00277
00278     hstring DeviceInformationDisplay::GetPropertyForDisplay(hstring const& key)
00279     {
00280         auto value = Properties().TryLookup(key);
00281         if (auto v = value.try_as<IReference<guid>>(); v)
00282         {
00283             return to_hstring(v.Value());
00284         }
00285
00286         return unbox_value_or<hstring>(value, {});
00287     }
00288
00289     fire_and_forget DeviceInformationDisplay::UpdateGlyphBitmapImage()
00290     {
00291         auto lifetime = get_strong();
00292
00293         DeviceThumbnail deviceThumbnail = co_await m_deviceInfo.GetGlyphThumbnailAsync();
00294         BitmapImage glyphBitmapImage;
00295         co_await glyphBitmapImage.SetSourceAsync(deviceThumbnail);
00296         m_glyphBitmapImage = glyphBitmapImage;
00297         OnPropertyChanged(L"GlyphBitmapImage");
00298     }
00299
00300     void DeviceInformationDisplay::OnPropertyChanged(hstring const& name)
00301     {
00302         m_propertyChanged(*this, PropertyChangedEventArgs(name));
00303     }
00304 }
Generated on Fri Nov 15 2024 22:19:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_DataEvents Member List

This is the complete list of members for Scenario1_DataEvents, including all inherited members.
CO2LevelKey | Scenario1_DataEvents | [private]
customSensor | Scenario1_DataEvents | [private]
desiredReportInterval | Scenario1_DataEvents | [private]
deviceAccessInformation | Scenario1_DataEvents | [private]
GUIDCustomSensorDeviceVendorDefinedTypeID | Scenario1_DataEvents | [private]
OnAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
OnCustomSensorAdded(DeviceWatcher watcher, DeviceInformation customSensorDevice) | Scenario1_DataEvents | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_DataEvents | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario1_DataEvents | [inline, protected]
OnReadingChanged(object sender, CustomSensorReadingChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
OnVisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario1_DataEvents | [inline, private]
rootPage | Scenario1_DataEvents | [private]
Scenario1_DataEvents() | Scenario1_DataEvents | [inline]
ScenarioDisable(object sender, RoutedEventArgs e) | Scenario1_DataEvents | [inline, private]
ScenarioEnable(object sender, RoutedEventArgs e) | Scenario1_DataEvents | [inline, private]
watcher | Scenario1_DataEvents | [private]
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CredentialPicker/cpp/Scenario2_MessageCaption.xaml.h Source File

  • CredentialPicker
  • cpp

Scenario2_MessageCaption.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario2_MessageCaption.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario2_MessageCaption sealed
00012     {
00013     public:
00014         Scenario2_MessageCaption();
00015     private:
00016         void Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00017         void SetResult(Windows::Security::Credentials::UI::CredentialPickerResults^ res);
00018     };
00019 }
Generated on Fri Nov 15 2024 22:19:01 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cs/SampleConfiguration.cs Source File

  • MapControl
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Devices.Geolocation;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Controls.Maps;
00017
00018 namespace SDKTemplate
00019 {
00020     public partial class MainPage : Page
00021     {
00022         public const string FEATURE_NAME = "MapControlSample";
00023
00024         List<Scenario> scenarios = new List<Scenario>
00025         {
00026             new Scenario() { Title="MapControl configuration", ClassType=typeof(Scenario1)},
00027             new Scenario() { Title="Adding MapElements", ClassType=typeof(Scenario2)},
00028             new Scenario() { Title="Adding MapLayers", ClassType=typeof(Scenario10)},
00029             new Scenario() { Title="Adding XAML children", ClassType=typeof(Scenario3)},
00030             new Scenario() { Title="Showing 3D locations", ClassType=typeof(Scenario4)},
00031             new Scenario() { Title="Showing Streetside experience", ClassType=typeof(Scenario5)},
00032             new Scenario() { Title="Launching Maps using URI Schemes", ClassType=typeof(Scenario6)},
00033             new Scenario() { Title="Displaying points with clustering", ClassType=typeof(Scenario7)},
00034             new Scenario() { Title="Find and download Offline Maps", ClassType=typeof(Scenario8)},
00035             new Scenario() { Title="Custom map appearance", ClassType=typeof(Scenario9)},
00036             new Scenario() { Title="Custom map elements appearance", ClassType=typeof(Scenario11)},
00037             new Scenario() { Title="Animated MapTileSource", ClassType=typeof(Scenario12)},
00038         };
00039
00040         public static readonly Geopoint SeattleGeopoint = new Geopoint(new BasicGeoposition() { Latitude = 47.604, Longitude = -122.329 });
00041
00042         public static List<MapElement> CreateCityBuildingsCollection()
00043         {
00044             return new List<MapElement>
00045             {
00046                 new MapIcon { Location = new Geopoint(new BasicGeoposition { Latitude = 47.603830, Longitude = -122.329900 }), Title = "Seattle City Hall" },
00047                 new MapIcon { Location = new Geopoint(new BasicGeoposition { Latitude = 47.606709, Longitude = -122.332672 }), Title = "Seattle Public Library" },
00048                 new MapIcon { Location = new Geopoint(new BasicGeoposition { Latitude = 47.604100, Longitude = -122.329204 }), Title = "Municipal Court of Seattle" },
00049             };
00050         }
00051
00052         public static List<MapElement> CreateCityParksCollection()
00053         {
00054             return new List<MapElement>
00055             {
00056                     new MapIcon { Location = new Geopoint(new BasicGeoposition { Latitude = 47.608313, Longitude = -122.331218 }), Title = "Freeway Park" },
00057                     new MapIcon { Location = new Geopoint(new BasicGeoposition { Latitude = 47.602029, Longitude = -122.333971 }), Title = "Pioneer Square" },
00058                     new MapIcon { Location = new Geopoint(new BasicGeoposition { Latitude = 47.601990, Longitude = -122.330681 }), Title = "City Hall Park" },
00059                     new MapIcon { Location = new Geopoint(new BasicGeoposition { Latitude = 47.600619, Longitude = -122.324957 }), Title = "Kobe Terrace Park" },
00060             };
00061         }
00062     }
00063
00064     public class Scenario
00065     {
00066         public string Title { get; set; }
00067         public Type ClassType { get; set; }
00068     }
00069 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppServices/cs/AppServicesClient/OpenCloseConnectionScenario.xaml.cs Source File

  • AppServices
  • cs
  • AppServicesClient

OpenCloseConnectionScenario.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.AppService;
00014 using Windows.Foundation.Collections;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026     public sealed partial class OpenCloseConnectionScenario : Page
00027     {
00028         private MainPage rootPage;
00029
00030         public OpenCloseConnectionScenario()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         protected override void OnNavigatedTo(NavigationEventArgs e)
00036         {
00037             rootPage = MainPage.Current;
00038         }
00039
00040         private async void GenerateRandomNumber_Click(object sender, RoutedEventArgs e)
00041         {
00042             //Parse user input
00043             int minValueInput = 0;
00044             bool valueParsed = int.TryParse(MinValue.Text, out minValueInput);
00045             if (!valueParsed)
00046             {
00047                 rootPage.NotifyUser("The Minimum Value should be a valid integer", NotifyType.ErrorMessage);
00048                 return;
00049             }
00050
00051             int maxValueInput = 0;
00052             valueParsed = int.TryParse(MaxValue.Text, out maxValueInput);
00053             if (!valueParsed)
00054             {
00055                 rootPage.NotifyUser("The Maximum Value should be a valid integer", NotifyType.ErrorMessage);
00056                 return;
00057             }
00058
00059             if (maxValueInput <= minValueInput)
00060             {
00061                 rootPage.NotifyUser("Maximum Value must be larger than Minimum Value", NotifyType.ErrorMessage);
00062                 return;
00063             }
00064
00065             using (var connection = new AppServiceConnection())
00066             {
00067                 //Set up a new app service connection
00068                 connection.AppServiceName = "com.microsoft.randomnumbergenerator";
00069                 connection.PackageFamilyName = "Microsoft.SDKSamples.AppServicesProvider.CS_8wekyb3d8bbwe";
00070                 AppServiceConnectionStatus status = await connection.OpenAsync();
00071
00072                 switch (status)
00073                 {
00074                     case AppServiceConnectionStatus.Success:
00075                         // The new connection opened successfully
00076                         rootPage.NotifyUser("Connection established", NotifyType.StatusMessage);
00077                         break;
00078
00079                     case AppServiceConnectionStatus.AppNotInstalled:
00080                         rootPage.NotifyUser("The app AppServicesProvider is not installed. Deploy AppServicesProvider to this device and try again.", NotifyType.ErrorMessage);
00081                         return;
00082
00083                     case AppServiceConnectionStatus.AppUnavailable:
00084                         rootPage.NotifyUser("The app AppServicesProvider is not available. This could be because it is currently being updated or was installed to a removable device that is no longer available.", NotifyType.ErrorMessage);
00085                         return;
00086
00087                     case AppServiceConnectionStatus.AppServiceUnavailable:
00088                         rootPage.NotifyUser($"The app AppServicesProvider is installed but it does not provide the app service {connection.AppServiceName}", NotifyType.ErrorMessage);
00089                         return;
00090
00091                     default:
00092                     case AppServiceConnectionStatus.Unknown:
00093                         rootPage.NotifyUser("An unknown error occurred while we were trying to open an AppServiceConnection.", NotifyType.ErrorMessage);
00094                         return;
00095                 }
00096
00097                 //Set up the inputs and send a message to the service
00098                 var inputs = new ValueSet();
00099                 inputs.Add("minvalue", minValueInput);
00100                 inputs.Add("maxvalue", maxValueInput);
00101                 AppServiceResponse response = await connection.SendMessageAsync(inputs);
00102
00103                 //If the service responded with success display the result and walk away
00104                 if (response.Status == AppServiceResponseStatus.Success &&
00105                     response.Message.ContainsKey("result"))
00106                 {
00107                     var resultText = response.Message["result"].ToString();
00108                     if (!string.IsNullOrEmpty(resultText))
00109                     {
00110                         Result.Text = resultText;
00111                         rootPage.NotifyUser("App service responded with a result", NotifyType.StatusMessage);
00112                     }
00113                     else
00114                     {
00115                         rootPage.NotifyUser("App service did not respond with a result", NotifyType.ErrorMessage);
00116                     }
00117
00118                     return;
00119                 }
00120
00121                 //Something went wrong while sending a message. Let display
00122                 //a meaningful error message
00123                 switch (response.Status)
00124                 {
00125                     case AppServiceResponseStatus.Failure:
00126                         rootPage.NotifyUser("The service failed to acknowledge the message we sent it. It may have been terminated or its RequestReceived handler might not be handling incoming messages correctly.", NotifyType.ErrorMessage);
00127                         return;
00128
00129                     case AppServiceResponseStatus.ResourceLimitsExceeded:
00130                         rootPage.NotifyUser("The service exceeded the resources allocated to it and had to be terminated.", NotifyType.ErrorMessage);
00131                         return;
00132
00133                     default:
00134                     case AppServiceResponseStatus.Unknown:
00135                         rootPage.NotifyUser("An unknown error occurred while we were trying to send a message to the service.", NotifyType.ErrorMessage);
00136                         return;
00137                 }
00138             }
00139         }
00140     }
00141 }
Generated on Fri Nov 15 2024 22:18:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_InkCanvasTactileFeedback Member List

This is the complete list of members for Scenario1_InkCanvasTactileFeedback, including all inherited members.
OnSizeChanged(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::SizeChangedEventArgs const &e) | Scenario1_InkCanvasTactileFeedback
Scenario1_InkCanvasTactileFeedback() | Scenario1_InkCanvasTactileFeedback
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothLE/cppwinrt/Scenario1_Discovery.cpp Source File

  • BluetoothLE
  • cppwinrt

Scenario1_Discovery.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_Discovery.h"
00014 #include "Scenario1_Discovery.g.cpp"
00015 #include "SampleConfiguration.h"
00016 #include "BluetoothLEDeviceDisplay.h"
00017
00018 using namespace winrt;
00019 using namespace Windows::Devices::Enumeration;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::UI::Core;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Navigation;
00024
00025 namespace winrt
00026 {
00027     hstring to_hstring(DevicePairingResultStatus status)
00028     {
00029         switch (status)
00030         {
00031         case DevicePairingResultStatus::Paired: return L"Paired";
00032         case DevicePairingResultStatus::NotReadyToPair: return L"NotReadyToPair";
00033         case DevicePairingResultStatus::NotPaired: return L"NotPaired";
00034         case DevicePairingResultStatus::AlreadyPaired: return L"AlreadyPaired";
00035         case DevicePairingResultStatus::ConnectionRejected: return L"ConnectionRejected";
00036         case DevicePairingResultStatus::TooManyConnections: return L"TooManyConnections";
00037         case DevicePairingResultStatus::HardwareFailure: return L"HardwareFailure";
00038         case DevicePairingResultStatus::AuthenticationTimeout: return L"AuthenticationTimeout";
00039         case DevicePairingResultStatus::AuthenticationNotAllowed: return L"AuthenticationNotAllowed";
00040         case DevicePairingResultStatus::AuthenticationFailure: return L"AuthenticationFailure";
00041         case DevicePairingResultStatus::NoSupportedProfiles: return L"NoSupportedProfiles";
00042         case DevicePairingResultStatus::ProtectionLevelCouldNotBeMet: return L"ProtectionLevelCouldNotBeMet";
00043         case DevicePairingResultStatus::AccessDenied: return L"AccessDenied";
00044         case DevicePairingResultStatus::InvalidCeremonyData: return L"InvalidCeremonyData";
00045         case DevicePairingResultStatus::PairingCanceled: return L"PairingCanceled";
00046         case DevicePairingResultStatus::OperationAlreadyInProgress: return L"OperationAlreadyInProgress";
00047         case DevicePairingResultStatus::RequiredHandlerNotRegistered: return L"RequiredHandlerNotRegistered";
00048         case DevicePairingResultStatus::RejectedByHandler: return L"RejectedByHandler";
00049         case DevicePairingResultStatus::RemoteDeviceHasAssociation: return L"RemoteDeviceHasAssociation";
00050         case DevicePairingResultStatus::Failed: return L"Failed";
00051         }
00052         return L"Code " + to_hstring(static_cast<int>(status));
00053     }
00054 }
00055
00056 namespace winrt::SDKTemplate::implementation
00057 {
00058     // This scenario uses a DeviceWatcher to enumerate nearby Bluetooth Low Energy devices,
00059     // displays them in a ListView, and lets the user select a device and pair it.
00060     // This device will be used by future scenarios.
00061     // For more information about device discovery and pairing, including examples of
00062     // customizing the pairing process, see the DeviceEnumerationAndPairing sample.
00063
00064 #pragma region UI Code
00065
00066     Scenario1_Discovery::Scenario1_Discovery()
00067     {
00068         InitializeComponent();
00069     }
00070
00071     void Scenario1_Discovery::OnNavigatedFrom(NavigationEventArgs const&)
00072     {
00073         StopBleDeviceWatcher();
00074
00075         // Save the selected device's ID for use in other scenarios.
00076         auto bleDeviceDisplay = ResultsListView().SelectedItem().as<SDKTemplate::BluetoothLEDeviceDisplay>();
00077         if (bleDeviceDisplay != nullptr)
00078         {
00079             SampleState::SelectedBleDeviceId = bleDeviceDisplay.Id();
00080             SampleState::SelectedBleDeviceName = bleDeviceDisplay.Name();
00081         }
00082     }
00083
00084     void Scenario1_Discovery::EnumerateButton_Click()
00085     {
00086         if (deviceWatcher == nullptr)
00087         {
00088             StartBleDeviceWatcher();
00089             EnumerateButton().Content(box_value(L"Stop enumerating"));
00090             rootPage.NotifyUser(L"Device watcher started.", NotifyType::StatusMessage);
00091         }
00092         else
00093         {
00094             StopBleDeviceWatcher();
00095             EnumerateButton().Content(box_value(L"Start enumerating"));
00096             rootPage.NotifyUser(L"Device watcher stopped.", NotifyType::StatusMessage);
00097         }
00098     }
00099 #pragma endregion
00100
00101 #pragma region Device discovery
00102     /// <summary>
00103     /// Starts a device watcher that looks for all nearby Bluetooth devices (paired or unpaired).
00104     /// Attaches event handlers to populate the device collection.
00105     /// </summary>
00106     void Scenario1_Discovery::StartBleDeviceWatcher()
00107     {
00108         // Additional properties we would like about the device.
00109         // Property strings are documented here https://msdn.microsoft.com/en-us/library/windows/desktop/ff521659(v=vs.85).aspx
00110         auto requestedProperties = single_threaded_vector<hstring>({ L"System.Devices.Aep.DeviceAddress", L"System.Devices.Aep.IsConnected", L"System.Devices.Aep.Bluetooth.Le.IsConnectable" });
00111
00112         // BT_Code: Example showing paired and non-paired in a single query.
00113         hstring aqsAllBluetoothLEDevices = L"(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";
00114
00115         deviceWatcher =
00116             Windows::Devices::Enumeration::DeviceInformation::CreateWatcher(
00117                 aqsAllBluetoothLEDevices,
00118                 requestedProperties,
00119                 DeviceInformationKind::AssociationEndpoint);
00120
00121         // Register event handlers before starting the watcher.
00122         deviceWatcherAddedToken = deviceWatcher.Added({ get_weak(), &Scenario1_Discovery::DeviceWatcher_Added });
00123         deviceWatcherUpdatedToken = deviceWatcher.Updated({ get_weak(), &Scenario1_Discovery::DeviceWatcher_Updated });
00124         deviceWatcherRemovedToken = deviceWatcher.Removed({ get_weak(), &Scenario1_Discovery::DeviceWatcher_Removed });
00125         deviceWatcherEnumerationCompletedToken = deviceWatcher.EnumerationCompleted({ get_weak(), &Scenario1_Discovery::DeviceWatcher_EnumerationCompleted });
00126         deviceWatcherStoppedToken = deviceWatcher.Stopped({ get_weak(), &Scenario1_Discovery::DeviceWatcher_Stopped });
00127
00128         // Start over with an empty collection.
00129         m_knownDevices.Clear();
00130
00131         // Start the watcher. Active enumeration is limited to approximately 30 seconds.
00132         // This limits power usage and reduces interference with other Bluetooth activities.
00133         // To monitor for the presence of Bluetooth LE devices for an extended period,
00134         // use the BluetoothLEAdvertisementWatcher runtime class. See the BluetoothAdvertisement
00135         // sample for an example.
00136         deviceWatcher.Start();
00137     }
00138
00139     /// <summary>
00140     /// Stops watching for all nearby Bluetooth devices.
00141     /// </summary>
00142     void Scenario1_Discovery::StopBleDeviceWatcher()
00143     {
00144         if (deviceWatcher != nullptr)
00145         {
00146             // Unregister the event handlers.
00147             deviceWatcher.Added(deviceWatcherAddedToken);
00148             deviceWatcher.Updated(deviceWatcherUpdatedToken);
00149             deviceWatcher.Removed(deviceWatcherRemovedToken);
00150             deviceWatcher.EnumerationCompleted(deviceWatcherEnumerationCompletedToken);
00151             deviceWatcher.Stopped(deviceWatcherStoppedToken);
00152
00153             // Stop the watcher.
00154             deviceWatcher.Stop();
00155             deviceWatcher = nullptr;
00156         }
00157     }
00158
00159     std::tuple<SDKTemplate::BluetoothLEDeviceDisplay, uint32_t> Scenario1_Discovery::FindBluetoothLEDeviceDisplay(hstring const& id)
00160     {
00161         uint32_t size = m_knownDevices.Size();
00162         for (uint32_t index = 0; index < size; index++)
00163         {
00164             auto bleDeviceDisplay = m_knownDevices.GetAt(index).as<SDKTemplate::BluetoothLEDeviceDisplay>();
00165             if (bleDeviceDisplay.Id() == id)
00166             {
00167                 return { bleDeviceDisplay, index };
00168             }
00169         }
00170         return { nullptr, 0-1U };
00171     }
00172
00173     std::vector<Windows::Devices::Enumeration::DeviceInformation>::iterator Scenario1_Discovery::FindUnknownDevices(hstring const& id)
00174     {
00175         return std::find_if(UnknownDevices.begin(), UnknownDevices.end(), [&](auto&& bleDeviceInfo)
00176         {
00177             return bleDeviceInfo.Id() == id;
00178         });
00179     }
00180
00181     fire_and_forget Scenario1_Discovery::DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo)
00182     {
00183         // We must update the collection on the UI thread because the collection is databound to a UI element.
00184         auto lifetime = get_strong();
00185         co_await resume_foreground(Dispatcher());
00186
00187         OutputDebugStringW((L"Added " + deviceInfo.Id() + deviceInfo.Name()).c_str());
00188
00189         // Protect against race condition if the task runs after the app stopped the deviceWatcher.
00190         if (sender == deviceWatcher)
00191         {
00192             // Make sure device isn't already present in the list.
00193             if (std::get<0>(FindBluetoothLEDeviceDisplay(deviceInfo.Id())) == nullptr)
00194             {
00195                 if (!deviceInfo.Name().empty())
00196                 {
00197                     // If device has a friendly name display it immediately.
00198                     m_knownDevices.Append(make<BluetoothLEDeviceDisplay>(deviceInfo));
00199                 }
00200                 else
00201                 {
00202                     // Add it to a list in case the name gets updated later.
00203                     UnknownDevices.push_back(deviceInfo);
00204                 }
00205             }
00206         }
00207     }
00208
00209     fire_and_forget Scenario1_Discovery::DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
00210     {
00211         // We must update the collection on the UI thread because the collection is databound to a UI element.
00212         auto lifetime = get_strong();
00213         co_await resume_foreground(Dispatcher());
00214
00215         OutputDebugStringW((L"Updated " + deviceInfoUpdate.Id()).c_str());
00216
00217         // Protect against race condition if the task runs after the app stopped the deviceWatcher.
00218         if (sender == deviceWatcher)
00219         {
00220             SDKTemplate::BluetoothLEDeviceDisplay bleDeviceDisplay = std::get<0>(FindBluetoothLEDeviceDisplay(deviceInfoUpdate.Id()));
00221             if (bleDeviceDisplay != nullptr)
00222             {
00223                 // Device is already being displayed - update UX.
00224                 bleDeviceDisplay.Update(deviceInfoUpdate);
00225                 co_return;
00226             }
00227
00228             auto deviceInfo = FindUnknownDevices(deviceInfoUpdate.Id());
00229             if (deviceInfo != UnknownDevices.end())
00230             {
00231                 deviceInfo->Update(deviceInfoUpdate);
00232                 // If device has been updated with a friendly name it's no longer unknown.
00233                 if (!deviceInfo->Name().empty())
00234                 {
00235                     m_knownDevices.Append(make<BluetoothLEDeviceDisplay>(*deviceInfo));
00236                     UnknownDevices.erase(deviceInfo);
00237                 }
00238             }
00239         }
00240     }
00241
00242     fire_and_forget Scenario1_Discovery::DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
00243     {
00244         // We must update the collection on the UI thread because the collection is databound to a UI element.
00245         auto lifetime = get_strong();
00246         co_await resume_foreground(Dispatcher());
00247
00248         OutputDebugStringW((L"Removed " + deviceInfoUpdate.Id()).c_str());
00249
00250         // Protect against race condition if the task runs after the app stopped the deviceWatcher.
00251         if (sender == deviceWatcher)
00252         {
00253             // Find the corresponding DeviceInformation in the collection and remove it.
00254             auto[bleDeviceDisplay, index] = FindBluetoothLEDeviceDisplay(deviceInfoUpdate.Id());
00255             if (bleDeviceDisplay != nullptr)
00256             {
00257                 m_knownDevices.RemoveAt(index);
00258             }
00259
00260             auto deviceInfo = FindUnknownDevices(deviceInfoUpdate.Id());
00261             if (deviceInfo != UnknownDevices.end())
00262             {
00263                 UnknownDevices.erase(deviceInfo);
00264             }
00265         }
00266     }
00267
00268     fire_and_forget Scenario1_Discovery::DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, IInspectable const&)
00269     {
00270         // Access this->deviceWatcher on the UI thread to avoid race conditions.
00271         auto lifetime = get_strong();
00272         co_await resume_foreground(Dispatcher());
00273
00274         // Protect against race condition if the task runs after the app stopped the deviceWatcher.
00275         if (sender == deviceWatcher)
00276         {
00277             rootPage.NotifyUser(to_hstring(m_knownDevices.Size()) + L" devices found. Enumeration completed.",
00278                 NotifyType::StatusMessage);
00279         }
00280     }
00281
00282     fire_and_forget Scenario1_Discovery::DeviceWatcher_Stopped(DeviceWatcher sender, IInspectable const&)
00283     {
00284         // Access this->deviceWatcher on the UI thread to avoid race conditions.
00285         auto lifetime = get_strong();
00286         co_await resume_foreground(Dispatcher());
00287
00288         // Protect against race condition if the task runs after the app stopped the deviceWatcher.
00289         if (sender == deviceWatcher)
00290         {
00291             rootPage.NotifyUser(L"No longer watching for devices.",
00292                 sender.Status() == DeviceWatcherStatus::Aborted ? NotifyType::ErrorMessage : NotifyType::StatusMessage);
00293         }
00294     }
00295 #pragma endregion
00296
00297 #pragma region Pairing
00298     fire_and_forget Scenario1_Discovery::PairButton_Click()
00299     {
00300         auto lifetime = get_strong();
00301         EnumerateButton().IsEnabled(false);
00302
00303         rootPage.NotifyUser(L"Pairing started. Please wait...", NotifyType::StatusMessage);
00304
00305         // For more information about device pairing, including examples of
00306         // customizing the pairing process, see the DeviceEnumerationAndPairing sample.
00307
00308         // Capture the current selected item in case the user changes it while we are pairing.
00309         auto bleDeviceDisplay = ResultsListView().SelectedItem().as<SDKTemplate::BluetoothLEDeviceDisplay>();
00310
00311         // BT_Code: Pair the currently selected device.
00312         DevicePairingResult result = co_await bleDeviceDisplay.DeviceInformation().Pairing().PairAsync();
00313         DevicePairingResultStatus status = result.Status();
00314         rootPage.NotifyUser(L"Pairing result = " + to_hstring(status),
00315             status == DevicePairingResultStatus::Paired || status == DevicePairingResultStatus::AlreadyPaired
00316             ? NotifyType::StatusMessage
00317             : NotifyType::ErrorMessage);
00318
00319         EnumerateButton().IsEnabled(true);
00320     }
00321 #pragma endregion
00322 }
Generated on Fri Nov 15 2024 22:18:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VertexPosition Member List

This is the complete list of members for VertexPosition, including all inherited members.
pos VertexPosition
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6_DeleteTPM Member List

This is the complete list of members for Scenario6_DeleteTPM, including all inherited members.
Delete_Click(object sender, RoutedEventArgs e) | Scenario6_DeleteTPM | [inline, private]
HandleCardRemoved(SmartCardReader evtReader, CardRemovedEventArgs args) | Scenario6_DeleteTPM | [inline, private]
reader | Scenario6_DeleteTPM | [private]
rootPage | Scenario6_DeleteTPM | [private]
Scenario6_DeleteTPM() | Scenario6_DeleteTPM | [inline]
uiContext | Scenario6_DeleteTPM | [private]
Generated on Fri Nov 15 2024 22:23:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RadialController/cpp/pch.h Source File

  • RadialController
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScannerProvider/cs/BarcodeDecoder/DecodeEngine.cs Source File

  • BarcodeScannerProvider
  • cs
  • BarcodeDecoder

DecodeEngine.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Devices.PointOfService;
00016 using Windows.Globalization;
00017 using Windows.Graphics.Imaging;
00018 using Windows.Media.Ocr;
00019 using Windows.Storage;
00020
00021 namespace BarcodeDecoder
00022 {
00023     internal class DecodeResult
00024     {
00025         public uint Symbology { get; set; }
00026         public string Text { get; set; }
00027
00028         public override bool Equals(Object obj)
00029         {
00030             DecodeResult other = obj as DecodeResult;
00031             if (other == null)
00032             {
00033                 return false;
00034             }
00035             return (Symbology == other.Symbology) && (Text == other.Text);
00036         }
00037
00038         public override int GetHashCode()
00039         {
00040             return Text.GetHashCode() ^ (int)Symbology;
00041         }
00042     };
00043
00044     // Simple OCR-based decoder engine.
00045     internal class DecodeEngine
00046     {
00047         private OcrEngine ocrEngine = null;
00048         private static ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
00049
00050         public List<uint> SupportedSymbologies { get; private set; }
00051         public List<uint> ActiveSymbologies { get; set; }
00052
00053         public DecodeEngine()
00054         {
00055             // Create OCR engine from the language set in scenario 1 configuration.
00056             string languageTag = localSettings.Values["decoderLanguage"] as string;
00057
00058             foreach (Language lang in OcrEngine.AvailableRecognizerLanguages)
00059             {
00060                 if (lang.LanguageTag == languageTag)
00061                 {
00062                     ocrEngine = OcrEngine.TryCreateFromLanguage(lang);
00063                     break;
00064                 }
00065             }
00066
00067             if (ocrEngine == null)
00068             {
00069                 ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages();
00070             }
00071
00072             SupportedSymbologies = new List<uint> { BarcodeSymbologies.OcrA };
00073             ActiveSymbologies = SupportedSymbologies;
00074         }
00075
00076         public async Task<DecodeResult> DecodeAsync(SoftwareBitmap bitmap)
00077         {
00078             // The only thing we decode is OCR.
00079             if (!ActiveSymbologies.Contains(BarcodeSymbologies.OcrA))
00080             {
00081                 return null;
00082             }
00083
00084             OcrResult ocrResult = await ocrEngine.RecognizeAsync(bitmap);
00085
00086             // Get the text in the first non-empty line as result
00087             foreach (OcrLine line in ocrResult.Lines)
00088             {
00089                 if (!string.IsNullOrEmpty(line.Text))
00090                 {
00091                     return new DecodeResult
00092                     {
00093                         Symbology = BarcodeSymbologies.OcrA,
00094                         Text = line.Text
00095                     };
00096                 }
00097             }
00098             return null;
00099         }
00100     }
00101 }
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Server/Metering.cpp Source File

  • CustomCapability
  • Service
  • Server

Metering.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "stdafx.h"
00013 #include "Metering.h"
00014 #include <assert.h>
00015 #include "RpcInterface_h.h"
00016
00017 using namespace RpcServer;
00018
00019 //
00020 // Thread pool callback method for metering worker
00021 //
00022 void CALLBACK MeteringWorkerTpCallback(
00023     _In_ PTP_CALLBACK_INSTANCE /*iTimerInstance*/,
00024     _In_ PVOID pContext,
00025     _In_ PTP_TIMER /*pTimer*/)
00026 {
00027     Metering *metering = static_cast<Metering *>(pContext);
00028
00029     if (metering != nullptr)
00030     {
00031         // Run the metering worker for this instance of metering
00032         metering->MeteringWorker();
00033     }
00034 }
00035
00036 //
00037 // ctor for Metering
00038 //
00039 Metering::Metering(
00040     _In_ __int64 period)
00041 {
00042     tpTimer = CreateThreadpoolTimer(::MeteringWorkerTpCallback, this, nullptr);
00043     // TODO: Handle if CreateThreadpoolTimer fails i.e tpTimer == nullptr
00044
00045     samplePeriod = period;
00046     event = CreateEvent(
00047         nullptr,  // default security attributes
00048         FALSE,    // auto-reset event object
00049         FALSE,    // initial state is nonsignaled
00050         nullptr); // unnamed object
00051 }
00052
00053 //
00054 // dtor for Metering
00055 //
00056 Metering::~Metering()
00057 {
00058     if (tpTimer != nullptr)
00059     {
00060         // How to close threadpool timer when there are outstanding callbacks:
00061         // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682040(v=vs.85).aspx
00062         SetThreadpoolTimer(tpTimer, nullptr, 0, 0);
00063         WaitForThreadpoolTimerCallbacks(tpTimer, true);
00064         CloseThreadpoolTimer(tpTimer);
00065         tpTimer = nullptr;
00066     }
00067     CloseHandle(event);
00068 }
00069
00070 //
00071 // Set the lowest sample period
00072 //
00073 void Metering::SetSamplePeriod(_In_ __int64 period)
00074 {
00075     if (period < 1)
00076     {
00077         // Don't allow 0 (too fast) or negative numbers.
00078         period = 1;
00079     }
00080     if (period > 1000)
00081     {
00082         // Don't let the period be too long, or we will be
00083         // slow to shut down.
00084         period = 1000;
00085     }
00086     samplePeriod = period;
00087 }
00088
00089 //
00090 // Get last known metering data
00091 //
00092 __int64 Metering::GetMeteringData() const
00093 {
00094     return _data;
00095 }
00096
00097 //
00098 // Metering worker that updates metering data
00099 //
00100 void Metering::MeteringWorker()
00101 {
00102     // Get the value from the imaginary driver and update the data
00103     _data = GetTickCount();
00104     SetEvent(event);
00105 }
00106
00107 //
00108 // Set the thread poot timer and wait for metering data.
00109 //
00110 void Metering::WaitForMeteringData() const
00111 {
00112     ULARGE_INTEGER ulDueTime;
00113     FILETIME FileDueTime;
00114     ulDueTime.QuadPart = static_cast<ULONGLONG>(-(1 * 10 * 1000 * samplePeriod));
00115     FileDueTime.dwHighDateTime = ulDueTime.HighPart;
00116     FileDueTime.dwLowDateTime = ulDueTime.LowPart;
00117
00118     SetThreadpoolTimer(tpTimer,
00119                        &FileDueTime,
00120                        0,
00121                        0);
00122
00123     WaitForSingleObject(event, INFINITE);
00124 }
00125
00126 void Metering::StartMetering(
00127     _In_ __int64 samplePeriod,
00128     _In_ __int64 context)
00129 {
00130     stopMeteringRequested = false;
00131     SetSamplePeriod(samplePeriod);
00132
00133     while (true)
00134     {
00135         WaitForMeteringData();
00136         if (stopMeteringRequested || ShutdownRequested)
00137         {
00138             break;
00139         }
00140         MeteringDataEvent(GetMeteringData(), context);
00141     }
00142 }
00143
00144 void Metering::StopMetering()
00145 {
00146     stopMeteringRequested = true;
00147 }
00148
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/pch.cpp Source File

  • ComplexInk
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProximitySensor/cpp/Scenario2_Polling.xaml.cpp Source File

  • ProximitySensor
  • cpp

Scenario2_Polling.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_Polling.xaml.cpp
00014 // Implementation of the Scenario2_Polling class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario2_Polling.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Windows::Devices::Enumeration;
00024 using namespace Windows::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Globalization::DateTimeFormatting;
00027 using namespace Windows::UI::Core;
00028 using namespace Windows::UI::Xaml;
00029 using namespace Windows::UI::Xaml::Controls;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 Scenario2_Polling::Scenario2_Polling() : rootPage(MainPage::Current)
00033 {
00034     InitializeComponent();
00035
00036     watcher = DeviceInformation::CreateWatcher(ProximitySensor::GetDeviceSelector());
00037     watcher->Added += ref new TypedEventHandler<DeviceWatcher^, DeviceInformation^>(this, &Scenario2_Polling::OnProximitySensorAdded);
00038     watcher->Start();
00039 }
00040
00041 /// <summary>
00042 /// Invoked when the device watcher finds a proximity sensor
00043 /// </summary>
00044 /// <param name="sender">The device watcher</param>
00045 /// <param name="device">Device information for the proximity sensor that was found</param>
00046 void Scenario2_Polling::OnProximitySensorAdded(DeviceWatcher^ /*sender*/, DeviceInformation^ device)
00047 {
00048     if (nullptr == sensor)
00049     {
00050         ProximitySensor^ foundSensor = ProximitySensor::FromId(device->Id);
00051         if (nullptr != foundSensor)
00052         {
00053             // Optionally check the ProximitySensor.MaxDistanceInCentimeters/MinDistanceInCentimeters
00054             // properties here. Refer to Scenario 1 for details.
00055             sensor = foundSensor;
00056         }
00057         else
00058         {
00059             Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00060             {
00061                 rootPage->NotifyUser("Could not get a proximity sensor from the device id", NotifyType::ErrorMessage);
00062             }, CallbackContext::Any));
00063         }
00064     }
00065 }
00066
00067 /// <summary>
00068 /// This is the click handler for the 'GetData' button.
00069 /// </summary>
00070 /// <param name="sender"></param>
00071 /// <param name="e"></param>
00072 void Scenario2_Polling::ScenarioGetData(Object^ sender, RoutedEventArgs^ e)
00073 {
00074     if (nullptr != sensor)
00075     {
00076         ProximitySensorReading^ reading = sensor->GetCurrentReading();
00077         if (nullptr != reading)
00078         {
00079             ScenarioOutput_DetectionState->Text = reading->IsDetected ? "Detected" : "Not detected";
00080
00081             auto timestampFormatter = ref new DateTimeFormatter("day month year hour minute second");
00082             ScenarioOutput_Timestamp->Text = timestampFormatter->Format(reading->Timestamp);
00083
00084             // Show the detection distance, if available
00085             if (nullptr != reading->DistanceInMillimeters)
00086             {
00087                 ScenarioOutput_DetectionDistance->Text = reading->DistanceInMillimeters->Value.ToString();
00088             }
00089         }
00090     }
00091     else
00092     {
00093         rootPage->NotifyUser("No proximity sensor found", NotifyType::ErrorMessage);
00094     }
00095 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cs/RecognizerHelper.cs Source File

  • SimpleInk
  • cs

RecognizerHelper.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003
00004 namespace SDKTemplate
00005 {
00006     static class RecognizerHelper
00007     {
00008         private static Dictionary<string, string> Bcp47ToRecognizerNameDictionary =
00009             new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
00010             {
00011                 { "en-US", "Microsoft English (US) Handwriting Recognizer" },
00012                 { "en-GB", "Microsoft English (UK) Handwriting Recognizer" },
00013                 { "en-CA", "Microsoft English (Canada) Handwriting Recognizer" },
00014                 { "en-AU", "Microsoft English (Australia) Handwriting Recognizer" },
00015                 { "de-DE", "Microsoft-Handschrifterkennung - Deutsch" },
00016                 { "de-CH", "Microsoft-Handschrifterkennung - Deutsch (Schweiz)" },
00017                 { "es-ES", "Reconocimiento de escritura a mano en español de Microsoft" },
00018                 { "es-MX", "Reconocedor de escritura en Español (México) de Microsoft" },
00019                 { "es-AR", "Reconocedor de escritura en Español (Argentina) de Microsoft" },
00020                 { "fr", "Reconnaissance d'écriture Microsoft - Français" },
00021                 { "fr-FR", "Reconnaissance d'écriture Microsoft - Français" },
00022                 { "ja", "Microsoft 日本語手書き認識エンジン" },
00023                 { "ja-JP", "Microsoft 日本語手書き認識エンジン" },
00024                 { "it", "Riconoscimento grafia italiana Microsoft" },
00025                 { "nl-NL", "Microsoft Nederlandstalige handschriftherkenning" },
00026                 { "nl-BE", "Microsoft Nederlandstalige (België) handschriftherkenning" },
00027                 { "zh", "Microsoft 中文(简体)手写识别器" },
00028                 { "zh-CN", "Microsoft 中文(简体)手写识别器" },
00029                 { "zh-Hans-CN", "Microsoft 中文(简体)手写识别器" },
00030                 { "zh-Hant", "Microsoft 中文(繁體)手寫辨識器" },
00031                 { "zh-TW", "Microsoft 中文(繁體)手寫辨識器" },
00032                 { "ru", "Microsoft система распознавания русского рукописного ввода" },
00033                 { "pt-BR", "Reconhecedor de Manuscrito da Microsoft para Português (Brasil)" },
00034                 { "pt-PT", "Reconhecedor de escrita manual da Microsoft para português" },
00035                 { "ko", "Microsoft 한글 필기 인식기" },
00036                 { "pl", "System rozpoznawania polskiego pisma odręcznego firmy Microsoft" },
00037                 { "sv", "Microsoft Handskriftstolk för svenska" },
00038                 { "cs", "Microsoft rozpoznávač rukopisu pro český jazyk" },
00039                 { "da", "Microsoft Genkendelse af dansk håndskrift" },
00040                 { "nb", "Microsoft Håndskriftsgjenkjenner for norsk" },
00041                 { "nn", "Microsoft Håndskriftsgjenkjenner for nynorsk" },
00042                 { "fi", "Microsoftin suomenkielinen käsinkirjoituksen tunnistus" },
00043                 { "ro", "Microsoft recunoaştere grafie - Română" },
00044                 { "hr", "Microsoftov hrvatski rukopisni prepoznavač" },
00045                 { "sr-Latn", "Microsoft prepoznavač rukopisa za srpski (latinica)" },
00046                 { "sr", "Microsoft препознавач рукописа за српски (ћирилица)" },
00047                 { "ca", "Reconeixedor d'escriptura manual en català de Microsoft" },
00048             };
00049
00050         public static string LanguageTagToRecognizerName(string bcp47tag)
00051         {
00052             string recognizerName;
00053             if (!Bcp47ToRecognizerNameDictionary.TryGetValue(bcp47tag, out recognizerName))
00054             {
00055                 recognizerName = string.Empty;
00056             }
00057
00058             return recognizerName;
00059         }
00060     }
00061 }
Generated on Fri Nov 15 2024 22:21:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RelativeInclinometer/cpp/Scenario2_Polling.xaml.h Source File

  • RelativeInclinometer
  • cpp

Scenario2_Polling.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_Polling.xaml.h
00014 // Declaration of the Scenario2_Polling class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario2_Polling.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario2_Polling sealed
00030     {
00031     public:
00032         Scenario2_Polling();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038     private:
00039         SDKTemplate::MainPage^ rootPage;
00040         Windows::UI::Core::CoreDispatcher^ dispatcher;
00041         Windows::Devices::Sensors::Inclinometer^ inclinometer;
00042
00043         void GetData(Platform::Object^ sender, Platform::Object^ e);
00044     };
00045 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SetCardDataScenario Member List

This is the complete list of members for SetCardDataScenario, including all inherited members.
AID_MC | SetCardDataScenario | [private, static]
AID_NONPAYMENT | SetCardDataScenario | [private, static]
AID_PPSE | SetCardDataScenario | [private, static]
AID_V | SetCardDataScenario | [private, static]
btnAddCard_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | SetCardDataScenario | [inline, private]
btnCancel_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | SetCardDataScenario | [inline, private]
BuildReadRecordResponseMC(string pan, string exp, string serviceCode, string cardholderName, string track1Discretionary, string track2Discretionary) | SetCardDataScenario | [inline, private]
BuildReadRecordResponseV(string track2, string cardholderName, string track1Discretionary) | SetCardDataScenario | [inline, private]
optCardTypeGroup_CheckedUnchecked(object sender, Windows.UI.Xaml.RoutedEventArgs e) | SetCardDataScenario | [inline, private]
ProtectDataAsync(byte[] data, String strDescriptor) | SetCardDataScenario | [inline]
SetCardDataScenario() | SetCardDataScenario | [inline]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Helpers::sealed Member List

This is the complete list of members for Helpers::sealed, including all inherited members.
BufferConverter() | Helpers::sealed | [inline]
Convert(Platform::Object^value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^parameter, Platform::String^language) | Helpers::sealed | [inline, virtual]
Convert(Platform::Object^value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^parameter, Platform::String^language) | Helpers::sealed | [inline, virtual]
ConvertBack(Platform::Object^value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^parameter, Platform::String^language) | Helpers::sealed | [inline, virtual]
ConvertBack(Platform::Object^value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^parameter, Platform::String^language) | Helpers::sealed | [inline, virtual]
ServiceStatusConverter() | Helpers::sealed | [inline]
~BufferConverter() | Helpers::sealed | [inline, virtual]
~ServiceStatusConverter() | Helpers::sealed | [inline, virtual]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_AspectRatio Member List

This is the complete list of members for Scenario3_AspectRatio, including all inherited members.
_captureFolder | Scenario3_AspectRatio | [private]
_previewer | Scenario3_AspectRatio | [private]
CheckIfStreamsAreIdentical() | Scenario3_AspectRatio | [inline, private]
InitializeCameraButton_Click(object sender, RoutedEventArgs e) | Scenario3_AspectRatio | [inline, private]
MatchPreviewAspectRatio() | Scenario3_AspectRatio | [inline, private]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario3_AspectRatio | [inline, protected]
PopulateComboBoxes() | Scenario3_AspectRatio | [inline, private]
PreviewSettings_Changed(object sender, RoutedEventArgs e) | Scenario3_AspectRatio | [inline, private]
rootPage | Scenario3_AspectRatio | [private]
Scenario3_AspectRatio() | Scenario3_AspectRatio | [inline]
VideoButton_Click(object sender, RoutedEventArgs e) | Scenario3_AspectRatio | [inline, private]
VideoSettings_Changed(object sender, RoutedEventArgs e) | Scenario3_AspectRatio | [inline, private]
Generated on Fri Nov 15 2024 22:23:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationData/cppwinrt/Scenario5_Msappdata.cpp Source File

  • ApplicationData
  • cppwinrt

Scenario5_Msappdata.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario5_Msappdata.h"
00014 #include "Scenario5_Msappdata.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Storage;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Media::Imaging;
00021 using namespace Windows::UI::Xaml::Navigation;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario5_Msappdata::Scenario5_Msappdata()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     IAsyncAction Scenario5_Msappdata::CopyAssetToFolderIfNecessaryAsync(hstring name, StorageFolder const& folder)
00031     {
00032         if (co_await folder.TryGetItemAsync(name) == nullptr)
00033         {
00034             auto sourceFile = co_await StorageFile::GetFileFromApplicationUriAsync(Uri{ L"ms-appx:///assets/" + name });
00035             co_await sourceFile.CopyAsync(folder);
00036         }
00037     }
00038
00039     fire_and_forget Scenario5_Msappdata::OnNavigatedTo(NavigationEventArgs const&)
00040     {
00041         auto strong = get_strong();
00042         ApplicationData appData = ApplicationData::Current();
00043
00044         co_await CopyAssetToFolderIfNecessaryAsync(L"appDataLocal.png", appData.LocalFolder());
00045         co_await CopyAssetToFolderIfNecessaryAsync(L"appDataRoaming.png", appData.RoamingFolder());
00046         co_await CopyAssetToFolderIfNecessaryAsync(L"appDataTemp.png", appData.TemporaryFolder());
00047
00048         LocalImage().Source(BitmapImage{ Uri{L"ms-appdata:///local/appDataLocal.png"} });
00049         RoamingImage().Source(BitmapImage{ Uri{L"ms-appdata:///roaming/appDataRoaming.png"} });
00050         TempImage().Source(BitmapImage{ Uri{L"ms-appdata:///temp/appDataTemp.png"} });
00051     }
00052
00053     void Scenario5_Msappdata::OnNavigatingFrom(NavigatingCancelEventArgs const&)
00054     {
00055         LocalImage().Source(nullptr);
00056         RoamingImage().Source(nullptr);
00057         TempImage().Source(nullptr);
00058     }
00059
00060 }
00061
Generated on Fri Nov 15 2024 22:17:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceWatcherHelper Member List

This is the complete list of members for DeviceWatcherHelper, including all inherited members.
deviceChanged | DeviceWatcherHelper | [private]
DeviceChanged(Windows::Foundation::TypedEventHandler< Windows::Devices::Enumeration::DeviceWatcher, hstring > const &handler) | DeviceWatcherHelper | [inline]
DeviceChanged(event_token const &token) | DeviceWatcherHelper | [inline]
DeviceWatcherHelper(Windows::Foundation::Collections::IObservableVector< SDKTemplate::DeviceInformationDisplay > const &resultCollection, Windows::UI::Core::CoreDispatcher const &dispatcher) | DeviceWatcherHelper | [inline]
IsWatcherRunning() | DeviceWatcherHelper |
IsWatcherStarted(Windows::Devices::Enumeration::DeviceWatcher const &deviceWatcher) | DeviceWatcherHelper | [private, static]
RaiseDeviceChanged(Windows::Devices::Enumeration::DeviceWatcher const &sender, hstring const &id) | DeviceWatcherHelper | [private]
Reset() | DeviceWatcherHelper |
StartWatcher(Windows::Devices::Enumeration::DeviceWatcher const &deviceWatcher) | DeviceWatcherHelper |
StopWatcher() | DeviceWatcherHelper |
updateStatus | DeviceWatcherHelper | [private]
UpdateStatus(bool update) | DeviceWatcherHelper | [inline]
Watcher_DeviceAdded(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Devices::Enumeration::DeviceInformation deviceInfo) | DeviceWatcherHelper | [private]
Watcher_DeviceRemoved(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Devices::Enumeration::DeviceInformationUpdate deviceInfoUpdate) | DeviceWatcherHelper | [private]
Watcher_DeviceUpdated(Windows::Devices::Enumeration::DeviceWatcher sender, Windows::Devices::Enumeration::DeviceInformationUpdate deviceInfoUpdate) | DeviceWatcherHelper | [private]
Watcher_EnumerationCompleted(Windows::Devices::Enumeration::DeviceWatcher sender, IInspectable const &) | DeviceWatcherHelper | [private]
Watcher_Stopped(Windows::Devices::Enumeration::DeviceWatcher sender, IInspectable const &) | DeviceWatcherHelper | [private]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/LiveTiles/AdaptiveTemplates/Branding/NameAndLogo/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • LiveTiles
  • AdaptiveTemplates
  • Branding
  • NameAndLogo

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Xaml.Controls;
00002
00003 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00004
00005 namespace Notifications.ScenarioPages.LiveTiles.AdaptiveTemplates.Branding.NameAndLogo
00006 {
00007     /// <summary>
00008     /// An empty page that can be used on its own or navigated to within a Frame.
00009     /// </summary>
00010     public sealed partial class ScenarioElement : UserControl
00011     {
00012         public ScenarioElement()
00013         {
00014             this.InitializeComponent();
00015
00016             // Because different densities might be able to display more, we just set tons of text wrapped to make sure it overflows at some point
00017             string fillerText = "<text hint-wrap='true'>bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb</text>";
00018
00019             updateFourTilesControl.SetTilePayload($@"
00020                 <tile version='3'>
00021                     <visual>
00022
00023                         <binding template='TileSmall' branding='nameAndLogo'>
00024                             <text>nameAndLogo</text>
00025                             {fillerText}
00026                         </binding>
00027
00028                         <binding template='TileMedium' branding='nameAndLogo'>
00029                             <text hint-wrap='true'>nameAndLogo</text>
00030                             {fillerText}
00031                         </binding>
00032
00033                         <binding template='TileWide' branding='nameAndLogo'>
00034                             <text hint-wrap='true'>branding: nameAndLogo</text>
00035                             {fillerText}
00036                         </binding>
00037
00038                         <binding template='TileLarge' branding='nameAndLogo'>
00039                             <text hint-wrap='true'>branding: nameAndLogo</text>
00040                             {fillerText}
00041                         </binding>
00042
00043                     </visual>
00044                 </tile>");
00045         }
00046     }
00047 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cpp/Scenario3.xaml.cpp Source File

  • Logging
  • cpp

Scenario3.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3.xaml.h"
00014 #include "MainPage.xaml.h"
00015
00016 using namespace SDKTemplate;
00017
00018 using namespace Windows::UI::Xaml;
00019 using namespace Windows::UI::Xaml::Controls;
00020 using namespace concurrency;
00021
00022 Scenario3::Scenario3()
00023 {
00024     // This sample UI is interested in events from
00025     // the LoggingScenario class so the UI can be updated.
00026     LoggingScenario->StatusChanged += ref new StatusChangedHandler(this, &Scenario3::OnStatusChanged);
00027     InitializeComponent();
00028 }
00029
00030 void Scenario3::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00031 {
00032     UpdateControls();
00033 }
00034
00035 // This function finds a TextBlock's ScrollViewer.
00036 Windows::UI::Xaml::Controls::ScrollViewer^ Scenario3::FindScrollViewer(DependencyObject^ depObject)
00037 {
00038     if (depObject == nullptr)
00039     {
00040         return nullptr;
00041     }
00042
00043     int countThisLevel = Windows::UI::Xaml::Media::VisualTreeHelper::GetChildrenCount(depObject);
00044     if (countThisLevel <= 0)
00045     {
00046         return nullptr;
00047     }
00048
00049     for (int childIndex = 0; childIndex < countThisLevel; childIndex++)
00050     {
00051         DependencyObject^ childDepObject = Windows::UI::Xaml::Media::VisualTreeHelper::GetChild(depObject, childIndex);
00052         ScrollViewer^ sv = dynamic_cast<ScrollViewer^>(childDepObject);
00053         if (sv != nullptr)
00054         {
00055             return sv;
00056         }
00057
00058         sv = FindScrollViewer(childDepObject);
00059         if (sv != nullptr)
00060         {
00061             return sv;
00062         }
00063     }
00064
00065     return nullptr;
00066 }
00067
00068 // Add a message to the UI control which displays status while the sample is running.
00069 void Scenario3::AddMessage(Platform::String^ message)
00070 {
00071     Platform::String^ messageToAdd = "";
00072     messageToAdd += message;
00073     messageToAdd += "\r\n";
00074     StatusMessageList->Text += messageToAdd;
00075     StatusMessageList->Select(StatusMessageList->Text->Length(), 0);
00076
00077     ScrollViewer^ sv = FindScrollViewer(StatusMessageList);
00078     if (sv != nullptr)
00079     {
00080         sv->ChangeView(nullptr, StatusMessageList->ActualHeight, nullptr);
00081     }
00082
00083 }
00084
00085 // Call AddMessage on the UI thread.
00086 task<void> Scenario3::AddMessageDispatch(Platform::String^ message)
00087 {
00088     return create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]() {
00089         AddMessage(message);
00090     })));
00091 }
00092
00093 // AddLogFileMessageDispatch updates the UI with status information when
00094 // a new log file is created.
00095 task<void> Scenario3::AddLogFileMessageDispatch(Platform::String^ message, const std::wstring& logFileFullPath)
00096 {
00097     return create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]() {
00098
00099         // On the UI thread...
00100
00101         Platform::String^ finalMessage;
00102         if (!logFileFullPath.empty())
00103         {
00104             // Add a message to the UI indicating a new log file was created.
00105             Platform::String^ path = ref new Platform::String(logFileFullPath.c_str());
00106             Platform::String^ directoryName;
00107             Platform::String^ fileName;
00108             std::wstring::size_type posLastSlash = logFileFullPath.find_last_of(L'\\');
00109             if (posLastSlash > 0 && posLastSlash < logFileFullPath.size() - 1)
00110             {
00111                 directoryName = ref new Platform::String(logFileFullPath.substr(0, posLastSlash).c_str());
00112                 fileName = ref new Platform::String(logFileFullPath.substr(posLastSlash + 1, logFileFullPath.size() - (posLastSlash + 1)).c_str());
00113             }
00114             else
00115             {
00116                 directoryName = "";
00117                 fileName = "";
00118             }
00119             finalMessage = message + ": " + fileName;
00120             finalMessage = message + ": " + fileName;
00121             ViewLogInfo->Text =
00122                 "Log folder: \"" + directoryName + "\"\r\n" +
00123                 "- To view with tracerpt: tracerpt.exe \"" + path + "\" -of XML -o LogFile.xml\r\n" +
00124                 "- To view with Windows Performance Toolkit (WPT):\n" +
00125                 "   xperf -merge \"" + path + "\" merged.etl\n" +
00126                 "   wpa.exe merged.etl";
00127
00128         }
00129         else
00130         {
00131             finalMessage = message + ": none, nothing logged since saving the last file.";
00132         }
00133         AddMessage(finalMessage);
00134     })));
00135 }
00136
00137 // For this sample, the logging sample code is in LoggingScenario.
00138 // The following method handles status events from LoggingScenario as
00139 // it runs the scenario.
00140 void Scenario3::OnStatusChanged(Platform::Object^ sender, LoggingScenarioEventArgs^ e)
00141 {
00142     if (e->Type == LoggingScenarioEventType::BusyStatusChanged)
00143     {
00144         create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]() {
00145             UpdateControls();
00146         })));
00147     }
00148     else if (e->Type == LoggingScenarioEventType::LogFileGenerated)
00149     {
00150         AddLogFileMessageDispatch("LogFileGenerated", e->LogFileFullPath).then([]() {
00151         });
00152     }
00153     else if (e->Type == LoggingScenarioEventType::LogFileGeneratedAtSuspend)
00154     {
00155         AddLogFileMessageDispatch("Log file at suspend", e->LogFileFullPath).then([]() {
00156         });
00157     }
00158     else if (e->Type == LoggingScenarioEventType::LogFileGeneratedAtDisable)
00159     {
00160         AddLogFileMessageDispatch("Log file at disable", e->LogFileFullPath).then([]() {
00161         });
00162     }
00163     else if (e->Type == LoggingScenarioEventType::LoggingEnabledDisabled)
00164     {
00165         Platform::String^ message = "Logging has been " + (e->Enabled ? "enabled" : "disabled") + ".";
00166         AddMessageDispatch(message);
00167     }
00168 }
00169
00170 // Adjust UI controls based on what the sample is doing.
00171 void Scenario3::UpdateControls()
00172 {
00173     if (LoggingScenario->LoggingEnabled)
00174     {
00175         InputTextBlock1->Text = "Logging is enabled. Click 'Disable Logging' to disable logging. With logging enabled, you can click 'Log Messages' to use the logging API to generate log files.";
00176         EnableDisableLoggingButton->Content = "Disable Logging";
00177         if (LoggingScenario->IsBusy)
00178         {
00179             EnableDisableLoggingButton->IsEnabled = false;
00180             DoScenarioButton->IsEnabled = false;
00181         }
00182         else
00183         {
00184             EnableDisableLoggingButton->IsEnabled = true;
00185             DoScenarioButton->IsEnabled = true;
00186         }
00187     }
00188     else
00189     {
00190         InputTextBlock1->Text = "Logging is disabled. Click 'Enable Logging' to enable logging. After you enable logging you can click 'Log Messages' to use the logging API to generate log files.";
00191         EnableDisableLoggingButton->Content = "Enable Logging";
00192         DoScenarioButton->IsEnabled = false;
00193         if (LoggingScenario->IsBusy)
00194         {
00195             EnableDisableLoggingButton->IsEnabled = false;
00196         }
00197         else
00198         {
00199             EnableDisableLoggingButton->IsEnabled = true;
00200         }
00201     }
00202 }
00203
00204 // Enabled/disabled logging.
00205 void Scenario3::EnableDisableLogging(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00206 {
00207     if (LoggingScenario->LoggingEnabled)
00208     {
00209         MainPage::Current->NotifyUser("Disabling logging...", NotifyType::StatusMessage);
00210     }
00211     else
00212     {
00213         MainPage::Current->NotifyUser("Enabling logging...", NotifyType::StatusMessage);
00214     }
00215
00216     LoggingScenario->ToggleLoggingEnabledDisabledAsync().then([this](bool isEnabled) {
00217
00218         UNREFERENCED_PARAMETER(isEnabled);
00219
00220         UpdateControls();
00221
00222         if (this->LoggingScenario->LoggingEnabled)
00223         {
00224             MainPage::Current->NotifyUser("Logging enabled.", NotifyType::StatusMessage);
00225         }
00226         else
00227         {
00228             MainPage::Current->NotifyUser("Logging disabled.", NotifyType::StatusMessage);
00229         }
00230
00231     }, task_continuation_context::use_current());
00232 }
00233
00234 // Run a sample scenario which logs lots of messages to produce several log files.
00235 void Scenario3::DoScenario(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00236 {
00237     DoScenarioButton->IsEnabled = false;
00238     MainPage::Current->NotifyUser("Scenario running...", NotifyType::StatusMessage);
00239     // Allow the UI to update...
00240     create_task(DoScenarioButton->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]() {}))).then([this]()
00241     {
00242         // Run the scenario asynchronously.
00243         return LoggingScenario->DoScenarioAsync();
00244     }).then([this](task<void> previousTask) {
00245         // After the scenario completes, re-enable UI controls and display a message.
00246         DoScenarioButton->IsEnabled = true;
00247         MainPage::Current->NotifyUser("Scenario finished.", NotifyType::StatusMessage);
00248     }, task_continuation_context::use_current());
00249 }
Generated on Fri Nov 15 2024 22:18:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/Scenario3_BackgroundDeviceWatcher.xaml.h Source File

  • DeviceEnumerationAndPairing
  • cpp

Scenario3_BackgroundDeviceWatcher.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario3_BackgroundDeviceWatcher.g.h"
00006 #include "MainPage.xaml.h"
00007 #include "DisplayHelpers.h"
00008
00009 namespace SDKTemplate
00010 {
00011     [Windows::Foundation::Metadata::WebHostHidden]
00012     public ref class Scenario3_BackgroundDeviceWatcher sealed
00013     {
00014     public:
00015         Scenario3_BackgroundDeviceWatcher();
00016
00017     protected:
00018         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00019         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00020
00021     private:
00022         void StartWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00023         void StopWatcherButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00024
00025         void StartWatcher();
00026         void StopWatcher();
00027
00028         void RegisterBackgroundTask(Windows::ApplicationModel::Background::DeviceWatcherTrigger^ deviceWatcherTrigger);
00029         void UnregisterBackgroundTask(Windows::ApplicationModel::Background::IBackgroundTaskRegistration^ taskReg);
00030
00031         MainPage^ rootPage = MainPage::Current;
00032         Windows::ApplicationModel::Background::IBackgroundTaskRegistration^ backgroundTaskRegistration;
00033         Windows::Foundation::EventRegistrationToken backgroundTaskCompletedToken{};
00034         Platform::String^ backgroundTaskName = "DeviceEnumerationCpp_BackgroundTaskName";
00035     };
00036 }
Generated on Fri Nov 15 2024 22:19:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario11_DeleteCookie.h Source File

  • HttpClient
  • cppwinrt

Scenario11_DeleteCookie.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario11_DeleteCookie.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario11_DeleteCookie : Scenario11_DeleteCookieT<Scenario11_DeleteCookie>
00020     {
00021         Scenario11_DeleteCookie();
00022
00023         void DeleteCookie_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024
00025     private:
00026         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario11_DeleteCookie : Scenario11_DeleteCookieT<Scenario11_DeleteCookie, implementation::Scenario11_DeleteCookie>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:19:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCoordinateMapper/cpp/Content/GpuCoordinateMapper.h Source File

  • CameraStreamCoordinateMapper
  • cpp
  • Content

GpuCoordinateMapper.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015 #include "ShaderStructures.h"
00016
00017 namespace CameraStreamCoordinateMapper
00018 {
00019     ////////////////////////////////////////////////////////////////////////////////
00020     // GpuCoordinateMapper
00021     //
00022     // This class is the core class for mapping image data between the correlated cameras
00023     //
00024     // It uses triangle rasterization on the gpu to increase performance of processing
00025     // the depth image. This is particuarly useful when the depth + color cameras do
00026     // not have matching frame sizes. For example on Kinect V2 the depth camera is 512x424
00027     // and the color camera is 1920x1080.
00028     //
00029     // This means there are almost 4 color pixels for each depth pixel (along the x-axis).
00030     // We can use triangle rasterization to interpolate the missing values to give us the
00031     // most accurate result.
00032
00033     class GpuCoordinateMapper
00034     {
00035     public:
00036
00037         // This is used to detect when the CameraIntrinsics from the VideoMediaFrame have
00038         // changed. We store the underlying intrinsics values to compare against on a
00039         // frame-by-frame basis. If they change, then we can recreate resources that were
00040         // dependent on the intrinsics values (e.g. Distortion and Unprojection look up tables)
00041         struct CameraIntrinsics
00042         {
00043             CameraIntrinsics() = default;
00044
00045             explicit CameraIntrinsics(Windows::Media::Devices::Core::CameraIntrinsics^ intrinsics) :
00046                 imageWidth(intrinsics->ImageWidth),
00047                 imageHeight(intrinsics->ImageHeight),
00048                 principalPoint(intrinsics->PrincipalPoint),
00049                 focalLength(intrinsics->FocalLength),
00050                 radialDistortion(intrinsics->RadialDistortion),
00051                 tangentialDistortion(intrinsics->TangentialDistortion)
00052             {}
00053
00054             inline bool operator!=(const CameraIntrinsics& rhs) const
00055             {
00056                 return std::memcmp(this, &rhs, sizeof(CameraIntrinsics)) != 0;
00057             }
00058
00059             uint32_t imageWidth;
00060             uint32_t imageHeight;
00061             Windows::Foundation::Numerics::float2 principalPoint;
00062             Windows::Foundation::Numerics::float2 focalLength;
00063             Windows::Foundation::Numerics::float3 radialDistortion;
00064             Windows::Foundation::Numerics::float2 tangentialDistortion;
00065         };
00066
00067         struct RasterizedFrameBlob {
00068             CameraIntrinsics depthIntrinsics;
00069             CameraIntrinsics sourceIntrinsics;
00070             CameraIntrinsics targetIntrinsics;
00071             Windows::Foundation::Numerics::float4x4 depthToSource;
00072             Windows::Foundation::Numerics::float4x4 depthToTarget;
00073             Windows::Foundation::Numerics::float4x4 sourceProjectionMatrix;
00074             Windows::Foundation::Numerics::float4x4 targetProjectionMatrix;
00075             float depthScaleInMeters;
00076             float depthRangeMinimumInMeters;
00077             float depthRangeMaximumInMeters;
00078             Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> depthImage;
00079             Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> depthUnprojectionMap;
00080             Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> sourceImage;
00081             Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> sourceDistortionMap;
00082             Microsoft::WRL::ComPtr<ID3D11RenderTargetView> targetImage;
00083             Microsoft::WRL::ComPtr<ID3D11DepthStencilView> targetRasterizedDepth;
00084             Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> targetDistortionMap;
00085         };
00086
00087         struct VisualizeFrameBlob {
00088             Windows::Foundation::Numerics::float4x4 worldToView;
00089             Windows::Foundation::Numerics::float4x4 viewToProj;
00090             Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> targetImage;
00091             Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> targetImageDepthBuffer;
00092             Microsoft::WRL::ComPtr<ID3D11RenderTargetView> renderTarget;
00093             Microsoft::WRL::ComPtr<ID3D11DepthStencilView> renderTargetDepthBuffer;
00094             D3D11_VIEWPORT viewport;
00095         };
00096
00097         GpuCoordinateMapper(
00098             const std::shared_ptr<DX::DeviceResources>& deviceResources);
00099
00100         void CreateDeviceDependentResources();
00101         void ReleaseDeviceDependentResources();
00102
00103         ////////////////////////////////////////////////////////////////////////////////
00104         // RunCoordinateMapping - executes the correlation algorithm for this set of frame data
00105         void RunCoordinateMapping(
00106             const RasterizedFrameBlob& frameBlob);
00107
00108         ////////////////////////////////////////////////////////////////////////////////
00109         // VisualizeCoordinateMapping - executes the correlation algorithm for this set of frame data
00110         //   except visualized from another perspective, using depth information from the previous pass
00111         //   in order to occlude pixels that weren't visible from the original target camera's perspective
00112         void VisualizeCoordinateMapping(
00113             const RasterizedFrameBlob& rasterizedFrameBlob,
00114             const VisualizeFrameBlob& visualizeFrameBlob);
00115
00116     private:
00117         std::shared_ptr<DX::DeviceResources> m_deviceResources;
00118
00119         Microsoft::WRL::ComPtr<ID3D11VertexShader> m_rasterizeDepthMeshVertexShader;
00120         Microsoft::WRL::ComPtr<ID3D11InputLayout>  m_rasterizeDepthMeshInputLayout;
00121         Microsoft::WRL::ComPtr<ID3D11PixelShader>  m_rasterizeDepthMeshPixelShader;
00122
00123         Microsoft::WRL::ComPtr<ID3D11VertexShader> m_visualizeDepthMeshVertexShader;
00124         Microsoft::WRL::ComPtr<ID3D11InputLayout>  m_visualizeDepthMeshInputLayout;
00125         Microsoft::WRL::ComPtr<ID3D11PixelShader>  m_visualizeDepthMeshPixelShader;
00126
00127         Microsoft::WRL::ComPtr<ID3D11Buffer>       m_rasterizeDepthMeshConstants;
00128         Microsoft::WRL::ComPtr<ID3D11Buffer>       m_visualizeDepthMeshConstants;
00129         Microsoft::WRL::ComPtr<ID3D11Buffer>       m_vertexBuffer;
00130         Microsoft::WRL::ComPtr<ID3D11SamplerState> m_samplerState;
00131
00132         uint32_t m_vertexCount;
00133     };
00134 }
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PrintHelper Member List

This is the complete list of members for PrintHelper, including all inherited members.
AddOnePrintPreviewPage(RichTextBlockOverflow lastRTBOAdded, PrintPageDescription printPageDescription) | PrintHelper | [inline, protected, virtual]
AddPrintPages(object sender, AddPagesEventArgs e) | PrintHelper | [inline, protected, virtual]
ApplicationContentMarginLeft | PrintHelper | [protected]
ApplicationContentMarginTop | PrintHelper | [protected]
CreatePrintPreviewPages(object sender, PaginateEventArgs e) | PrintHelper | [inline, protected, virtual]
firstPage | PrintHelper | [protected]
GetPrintPreviewPage(object sender, GetPreviewPageEventArgs e) | PrintHelper | [inline, protected, virtual]
PreparePrintContent(Page page) | PrintHelper | [inline, virtual]
PreviewPagesCreated | PrintHelper | [protected]
PrintCanvas | PrintHelper | [protected]
printDocument | PrintHelper | [protected]
printDocumentSource | PrintHelper | [protected]
PrintHelper(Page scenarioPage) | PrintHelper | [inline]
printPreviewPages | PrintHelper | [private]
PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e) | PrintHelper | [inline, protected, virtual]
RegisterForPrinting() | PrintHelper | [inline, virtual]
scenarioPage | PrintHelper | [protected]
ShowPrintUIAsync() | PrintHelper | [inline]
UnregisterForPrinting() | PrintHelper | [inline, virtual]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

EnableHelloPage Member List

This is the complete list of members for EnableHelloPage, including all inherited members.
CreatePassportKeyCredentialAsync() | EnableHelloPage | [inline, private]
EnableHelloPage() | EnableHelloPage | [inline]
LaunchHyperlink(object sender, RoutedEventArgs e) | EnableHelloPage | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | EnableHelloPage | [inline, protected]
RegisterPassportCredentialWithServerAsync(IBuffer publicKey) | EnableHelloPage | [inline, private]
SkipSetup() | EnableHelloPage | [inline, private]
StartUsingWindowsHello() | EnableHelloPage | [inline, private]
userId | EnableHelloPage | [private]
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Calibration Member List

This is the complete list of members for Scenario3_Calibration, including all inherited members.
calibrationBar | Scenario3_Calibration | [private]
OnApproximateAccuracy(object sender, RoutedEventArgs e) | Scenario3_Calibration | [inline, private]
OnHighAccuracy(object sender, RoutedEventArgs e) | Scenario3_Calibration | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_Calibration | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario3_Calibration | [inline, protected]
OnUnreliableAccuracy(object sender, RoutedEventArgs e) | Scenario3_Calibration | [inline, private]
rootPage | Scenario3_Calibration | [private]
Scenario3_Calibration() | Scenario3_Calibration | [inline]
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cs/Scenario3CustomOptions.xaml.cs Source File

  • Printing
  • cs

Scenario3CustomOptions.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018 using Windows.UI.Xaml.Printing;
00019 using Windows.Graphics.Printing;
00020 using Windows.Graphics.Printing.OptionDetails;
00021 using Windows.Storage.Streams;
00022 using SDKTemplate;
00023
00024 namespace PrintSample
00025 {
00026     [Flags]
00027     internal enum DisplayContent : int
00028     {
00029         /// <summary>
00030         /// Show only text
00031         /// </summary>
00032         Text = 1,
00033
00034         /// <summary>
00035         /// Show only images
00036         /// </summary>
00037         Images = 2,
00038
00039         /// <summary>
00040         /// Show a combination of images and text
00041         /// </summary>
00042         TextAndImages = 3
00043     }
00044
00045     class CustomOptionsPrintHelper : PrintHelper
00046     {
00047         /// <summary>
00048         /// A flag that determines if text & images are to be shown
00049         /// </summary>
00050         internal DisplayContent imageText = DisplayContent.TextAndImages;
00051
00052         /// <summary>
00053         /// Helper getter for text showing
00054         /// </summary>
00055         private bool ShowText
00056         {
00057             get { return (imageText & DisplayContent.Text) == DisplayContent.Text; }
00058         }
00059
00060         /// <summary>
00061         /// Helper getter for image showing
00062         /// </summary>
00063         private bool ShowImage
00064         {
00065             get { return (imageText & DisplayContent.Images) == DisplayContent.Images; }
00066         }
00067
00068         private bool showHeader = true;
00069
00070         Task<IRandomAccessStreamWithContentType> wideMarginsIconTask;
00071         Task<IRandomAccessStreamWithContentType> moderateMarginsIconTask;
00072         Task<IRandomAccessStreamWithContentType> narrowMarginsIconTask;
00073
00074         public CustomOptionsPrintHelper(Page scenarioPage) : base(scenarioPage)
00075         {
00076             // Start these tasks early because we know we're going to need the
00077             // streams in PrintTaskRequested.
00078             RandomAccessStreamReference wideMarginsIconReference = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/wideMargins.svg"));
00079             wideMarginsIconTask = wideMarginsIconReference.OpenReadAsync().AsTask();
00080
00081             RandomAccessStreamReference moderateMarginsIconReference = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/moderateMargins.svg"));
00082             moderateMarginsIconTask = moderateMarginsIconReference.OpenReadAsync().AsTask();
00083
00084             RandomAccessStreamReference narrowMarginsIconReference = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/narrowMargins.svg"));
00085             narrowMarginsIconTask = narrowMarginsIconReference.OpenReadAsync().AsTask();
00086         }
00087
00088         /// <summary>
00089         /// This is the event handler for PrintManager.PrintTaskRequested.
00090         /// In order to ensure a good user experience, the system requires that the app handle the PrintTaskRequested event within the time specified by PrintTaskRequestedEventArgs.Request.Deadline.
00091         /// Therefore, we use this handler to only create the print task.
00092         /// The print settings customization can be done when the print document source is requested.
00093         /// </summary>
00094         /// <param name="sender">PrintManager</param>
00095         /// <param name="e">PrintTaskRequestedEventArgs</param>
00096         protected override void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e)
00097         {
00098             PrintTask printTask = null;
00099             printTask = e.Request.CreatePrintTask("C# Printing SDK Sample", async sourceRequestedArgs =>
00100             {
00101                 var deferral = sourceRequestedArgs.GetDeferral();
00102                 PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(printTask.Options);
00103                 IList<string> displayedOptions = printDetailedOptions.DisplayedOptions;
00104
00105                 // Choose the printer options to be shown.
00106                 // The order in which the options are appended determines the order in which they appear in the UI
00107                 displayedOptions.Clear();
00108
00109                 displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.Copies);
00110                 displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.Orientation);
00111                 displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.ColorMode);
00112
00113                 // Create a new list option
00114                 PrintCustomItemListOptionDetails pageFormat = printDetailedOptions.CreateItemListOption("PageContent", "Pictures");
00115                 pageFormat.AddItem("PicturesText", "Pictures and text");
00116                 pageFormat.AddItem("PicturesOnly", "Pictures only");
00117                 pageFormat.AddItem("TextOnly", "Text only");
00118
00119                 // Add the custom option to the option list
00120                 displayedOptions.Add("PageContent");
00121
00122                 // Create a new toggle option "Show header".
00123                 PrintCustomToggleOptionDetails header = printDetailedOptions.CreateToggleOption("Header", "Show header");
00124
00125                 // App tells the user some more information about what the feature means.
00126                 header.Description = "Display a header on the first page";
00127
00128                 // Set the default value
00129                 header.TrySetValue(showHeader);
00130
00131                 // Add the custom option to the option list
00132                 displayedOptions.Add("Header");
00133
00134                 // Create a new list option
00135                 PrintCustomItemListOptionDetails margins = printDetailedOptions.CreateItemListOption("Margins", "Margins");
00136                 margins.AddItem("WideMargins", "Wide", "Each margin is 20% of the paper size", await wideMarginsIconTask);
00137                 margins.AddItem("ModerateMargins", "Moderate", "Each margin is 10% of the paper size", await moderateMarginsIconTask);
00138                 margins.AddItem("NarrowMargins", "Narrow", "Each margin is 5% of the paper size", await narrowMarginsIconTask);
00139
00140                 // The default is ModerateMargins
00141                 ApplicationContentMarginTop = 0.1;
00142                 ApplicationContentMarginLeft = 0.1;
00143                 margins.TrySetValue("ModerateMargins");
00144
00145                 // App tells the user some more information about what the feature means.
00146                 margins.Description = "The space between the content of your document and the edge of the paper";
00147
00148                 // Add the custom option to the option list
00149                 displayedOptions.Add("Margins");
00150
00151                 printDetailedOptions.OptionChanged += printDetailedOptions_OptionChanged;
00152
00153                 // Print Task event handler is invoked when the print job is completed.
00154                 printTask.Completed += (s, args) =>
00155                 {
00156                     // Notify the user when the print operation fails.
00157                     if (args.Completion == PrintTaskCompletion.Failed)
00158                     {
00159                         MainPage.Current.NotifyUser("Failed to print.", NotifyType.ErrorMessage);
00160                     }
00161                 };
00162
00163                 sourceRequestedArgs.SetSource(printDocumentSource);
00164
00165                 deferral.Complete();
00166             });
00167         }
00168
00169         /// <summary>
00170         /// This is the event handler for whenever the user makes changes to the options.
00171         /// In this case, the options of interest are PageContent, Margins and Header.
00172         /// </summary>
00173         /// <param name="sender">PrintTaskOptionDetails</param>
00174         /// <param name="args">PrintTaskOptionChangedEventArgs</param>
00175         async void printDetailedOptions_OptionChanged(PrintTaskOptionDetails sender, PrintTaskOptionChangedEventArgs args)
00176         {
00177             bool invalidatePreview = false;
00178
00179             string optionId = args.OptionId as string;
00180             if (string.IsNullOrEmpty(optionId))
00181             {
00182                 return;
00183             }
00184
00185             if (optionId == "PageContent")
00186             {
00187                 invalidatePreview = true;
00188             }
00189
00190             if (optionId == "Margins")
00191             {
00192                 PrintCustomItemListOptionDetails marginsOption = (PrintCustomItemListOptionDetails)sender.Options["Margins"];
00193                 string marginsValue = marginsOption.Value.ToString();
00194
00195                 switch (marginsValue)
00196                 {
00197                     case "WideMargins":
00198                         ApplicationContentMarginTop = 0.2;
00199                         ApplicationContentMarginLeft = 0.2;
00200                         break;
00201                     case "ModerateMargins":
00202                         ApplicationContentMarginTop = 0.1;
00203                         ApplicationContentMarginLeft = 0.1;
00204                         break;
00205                     case "NarrowMargins":
00206                         ApplicationContentMarginTop = 0.05;
00207                         ApplicationContentMarginLeft = 0.05;
00208                         break;
00209                 }
00210
00211                 if (marginsValue == "NarrowMargins")
00212                 {
00213                     marginsOption.WarningText = "Narrow margins may not be supported by some printers";
00214                 }
00215                 else
00216                 {
00217                     marginsOption.WarningText = "";
00218                 }
00219
00220                 invalidatePreview = true;
00221             }
00222
00223             if (optionId == "Header")
00224             {
00225                 PrintCustomToggleOptionDetails headerOption = (PrintCustomToggleOptionDetails)sender.Options["Header"];
00226                 showHeader = (bool)headerOption.Value;
00227                 invalidatePreview = true;
00228             }
00229
00230             if (invalidatePreview)
00231             {
00232                 await scenarioPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00233                 {
00234                     printDocument.InvalidatePreview();
00235                 });
00236             }
00237         }
00238
00239         #region PrintPreview
00240
00241         protected override RichTextBlockOverflow AddOnePrintPreviewPage(RichTextBlockOverflow lastRTBOAdded, PrintPageDescription printPageDescription)
00242         {
00243             // Check if we need to hide/show text & images for this scenario
00244             // Since all is rulled by the first page (page flow), here is where we must start
00245             if (lastRTBOAdded == null)
00246             {
00247                 // Get a refference to page objects
00248                 Grid pageContent = (Grid)firstPage.FindName("PrintableArea");
00249                 Image scenarioImage = (Image)firstPage.FindName("ScenarioImage");
00250                 RichTextBlock mainText = (RichTextBlock)firstPage.FindName("TextContent");
00251                 RichTextBlockOverflow firstLink = (RichTextBlockOverflow)firstPage.FindName("FirstLinkedContainer");
00252                 RichTextBlockOverflow continuationLink = (RichTextBlockOverflow)firstPage.FindName("ContinuationPageLinkedContainer");
00253
00254                 // Hide(collapse) and move elements in different grid cells depending by the viewable content(only text, only pictures)
00255
00256                 scenarioImage.Visibility = ShowImage ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed;
00257                 firstLink.SetValue(Grid.ColumnSpanProperty, ShowImage ? 1 : 2);
00258
00259                 scenarioImage.SetValue(Grid.RowProperty, ShowText ? 2 : 1);
00260                 scenarioImage.SetValue(Grid.ColumnProperty, ShowText ? 1 : 0);
00261
00262                 pageContent.ColumnDefinitions[0].Width = new GridLength(ShowText ? 6 : 4, GridUnitType.Star);
00263                 pageContent.ColumnDefinitions[1].Width = new GridLength(ShowText ? 4 : 6, GridUnitType.Star);
00264
00265                 // Break the text flow if the app is not printing text in order not to spawn pages with blank content
00266                 mainText.Visibility = ShowText ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed;
00267                 continuationLink.Visibility = ShowText ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed;
00268
00269                 // Hide header if appropriate
00270                 StackPanel header = (StackPanel)firstPage.FindName("Header");
00271                 header.Visibility = showHeader ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed;
00272             }
00273
00274             //Continue with the rest of the base printing layout processing (paper size, printable page size)
00275             return base.AddOnePrintPreviewPage(lastRTBOAdded, printPageDescription);
00276         }
00277
00278         protected override void CreatePrintPreviewPages(object sender, PaginateEventArgs e)
00279         {
00280             // Get PageContent property
00281             PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(e.PrintTaskOptions);
00282             string pageContent = (printDetailedOptions.Options["PageContent"].Value as string).ToLowerInvariant();
00283
00284             // Set the text & image display flag
00285             imageText = (DisplayContent)((Convert.ToInt32(pageContent.Contains("pictures")) << 1) | Convert.ToInt32(pageContent.Contains("text")));
00286
00287             base.CreatePrintPreviewPages(sender, e);
00288         }
00289
00290         #endregion
00291
00292     }
00293
00294     /// <summary>
00295     /// Scenario that demos how to add custom options (specific for the application)
00296     /// </summary>
00297     public sealed partial class Scenario3CustomOptions : Page
00298     {
00299         private CustomOptionsPrintHelper printHelper;
00300
00301         public Scenario3CustomOptions()
00302         {
00303             this.InitializeComponent();
00304         }
00305
00306         /// <summary>
00307         /// This is the click handler for the 'Print' button.
00308         /// </summary>
00309         /// <param name="sender"></param>
00310         /// <param name="e"></param>
00311         private async void OnPrintButtonClick(object sender, RoutedEventArgs e)
00312         {
00313             await printHelper.ShowPrintUIAsync();
00314         }
00315
00316         protected override void OnNavigatedTo(NavigationEventArgs e)
00317         {
00318             if (PrintManager.IsSupported())
00319             {
00320                 // Tell the user how to print
00321                 MainPage.Current.NotifyUser("Print contract registered with customization, use the Print button to print.", NotifyType.StatusMessage);
00322             }
00323             else
00324             {
00325                 // Remove the print button
00326                 InvokePrintingButton.Visibility = Visibility.Collapsed;
00327
00328                 // Inform user that Printing is not supported
00329                 MainPage.Current.NotifyUser("Printing is not supported.", NotifyType.ErrorMessage);
00330
00331                 // Printing-related event handlers will never be called if printing
00332                 // is not supported, but it's okay to register for them anyway.
00333             }
00334
00335             // Initalize common helper class and register for printing
00336             printHelper = new CustomOptionsPrintHelper(this);
00337             printHelper.RegisterForPrinting();
00338
00339             // Initialize print content for this scenario
00340             printHelper.PreparePrintContent(new PageToPrint());
00341         }
00342
00343         protected override void OnNavigatedFrom(NavigationEventArgs e)
00344         {
00345             if (printHelper != null)
00346             {
00347                 printHelper.UnregisterForPrinting();
00348             }
00349         }
00350     }
00351 }
Generated on Fri Nov 15 2024 22:21:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VideoItemInfo Member List

This is the complete list of members for VideoItemInfo, including all inherited members.
source | VideoItemInfo
title | VideoItemInfo
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Manage Member List

This is the complete list of members for Scenario2_Manage, including all inherited members.
RemoveCredentials_Click(Windows::Foundation::IInspectable const &, Windows::Foundation::IInspectable const &) | Scenario2_Manage
RetrieveCredentials_Click(Windows::Foundation::IInspectable const &, Windows::Foundation::IInspectable const &) | Scenario2_Manage
RevealPasswords_Click(Windows::Foundation::IInspectable const &, Windows::Foundation::IInspectable const &) | Scenario2_Manage
Scenario2_Manage() | Scenario2_Manage
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cpp/Scenario1_SelectDisplay.xaml.cpp Source File

  • LineDisplay
  • cpp

Scenario1_SelectDisplay.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_SelectDisplay.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Concurrency;
00017 using namespace Platform;
00018 using namespace Windows::Devices::Enumeration;
00019 using namespace Windows::Devices::PointOfService;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 Scenario1_SelectDisplay::Scenario1_SelectDisplay()
00027 {
00028     InitializeComponent();
00029 }
00030
00031 void Scenario1_SelectDisplay::OnNavigatedTo(NavigationEventArgs^ e)
00032 {
00033     RestartWatcher();
00034 }
00035
00036 void Scenario1_SelectDisplay::OnNavigatedFrom(NavigationEventArgs^ e)
00037 {
00038     StopWatcher();
00039 }
00040
00041 void Scenario1_SelectDisplay::RestartWatcher()
00042 {
00043     StopWatcher();
00044
00045     // Clear any old LineDisplay devices from the list box.
00046     DisplaysListBox->Items->Clear();
00047
00048     // Enumerate the LineDisplay devices and put them in our list box.
00049     watcher = DeviceInformation::CreateWatcher(LineDisplay::GetDeviceSelector(PosConnectionTypes::All));
00050     watcher->Added += ref new TypedEventHandler<DeviceWatcher^, DeviceInformation^>(this, &Scenario1_SelectDisplay::Watcher_Added);
00051     watcher->EnumerationCompleted += ref new TypedEventHandler<DeviceWatcher^, Object^>(this, &Scenario1_SelectDisplay::Watcher_EnumerationCompleted);
00052     watcher->Start();
00053 }
00054
00055 void Scenario1_SelectDisplay::StopWatcher()
00056 {
00057     if (watcher && (watcher->Status == DeviceWatcherStatus::Started))
00058     {
00059         watcher->Stop();
00060     }
00061     watcher = nullptr;
00062 }
00063
00064 void Scenario1_SelectDisplay::Watcher_Added(DeviceWatcher^ watcher, DeviceInformation^ deviceInfo)
00065 {
00066     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
00067         ref new Windows::UI::Core::DispatchedHandler([this, deviceInfo]
00068     {
00069         auto item = ref new ListBoxItem();
00070         item->Content = deviceInfo->Name;
00071         item->Tag = deviceInfo->Id;
00072         DisplaysListBox->Items->Append(item);
00073     }));
00074 }
00075
00076 void Scenario1_SelectDisplay::Watcher_EnumerationCompleted(DeviceWatcher^ watcher, Object^ e)
00077 {
00078     watcher->Stop();
00079 }
00080
00081 void Scenario1_SelectDisplay::SelectButton_Click(Object^ sender, RoutedEventArgs^ e)
00082 {
00083     invoke_async_lambda([=]() -> task<void>
00084     {
00085         SelectButton->IsEnabled = false;
00086
00087         auto item = safe_cast<ListBoxItem^>(DisplaysListBox->SelectedValue);
00088
00089         auto name = safe_cast<String^>(item->Content);
00090         auto deviceId = safe_cast<String^>(item->Tag);
00091         ClaimedLineDisplay^ lineDisplay = co_await ClaimedLineDisplay::FromIdAsync(deviceId);
00092         if (lineDisplay != nullptr)
00093         {
00094             co_await lineDisplay->DefaultWindow->TryClearTextAsync();
00095
00096             rootPage->NotifyUser("Selected: " + name, NotifyType::StatusMessage);
00097
00098             // Save this device ID for other scenarios.
00099             rootPage->LineDisplayId = deviceId;
00100
00101             // Close the claimed line display.
00102             delete lineDisplay;
00103         }
00104         else
00105         {
00106             rootPage->NotifyUser("Unable to claim the Line Display", NotifyType::ErrorMessage);
00107         }
00108
00109         SelectButton->IsEnabled = true;
00110     });
00111 }
00112
00113 void Scenario1_SelectDisplay::RefreshButton_Click(Object^ sender, RoutedEventArgs^ e)
00114 {
00115     RestartWatcher();
00116 }
Generated on Fri Nov 15 2024 22:20:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cppwinrt/Scenario6_TimeZone.h Source File

  • DateTimeFormatting
  • cppwinrt

Scenario6_TimeZone.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario6_TimeZone.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario6_TimeZone : Scenario6_TimeZoneT<Scenario6_TimeZone>
00019     {
00020         Scenario6_TimeZone();
00021
00022         void Display_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario6_TimeZone : Scenario6_TimeZoneT<Scenario6_TimeZone, implementation::Scenario6_TimeZone>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:19:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserDataAccountManager/cs/Scenario3_FixAccount.xaml.cs Source File

  • UserDataAccountManager
  • cs

Scenario3_FixAccount.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.ApplicationModel.UserDataAccounts;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016 using System.Collections.Generic;
00017 using Windows.UI.Xaml;
00018 using Windows.ApplicationModel.Email;
00019 using Windows.ApplicationModel.Appointments;
00020 using Windows.ApplicationModel.Contacts;
00021 using System.Threading.Tasks;
00022 using System.Collections.ObjectModel;
00023
00024 namespace SDKTemplate
00025 {
00026
00027     public sealed partial class Scenario3_FixAccount : Page
00028     {
00029         private MainPage rootPage = MainPage.Current;
00030         private bool isLaunched = false;
00031
00032         public Scenario3_FixAccount()
00033         {
00034             this.InitializeComponent();
00035         }
00036
00037         protected override async void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039             await rootPage.LoadDataAccountsAsync(AccountsListComboBox);
00040         }
00041
00042         private async void Fix_Click(object sender, RoutedEventArgs e)
00043         {
00044             // only one instance of the UserDataAccountManager pane can be launched at once per thread
00045             if (isLaunched == false)
00046             {
00047                 isLaunched = true;
00048                 rootPage.NotifyUser("", NotifyType.StatusMessage);
00049
00050                 var selectedAccount = (UserDataAccount)AccountsListComboBox.SelectedValue;
00051                 if (selectedAccount != null)
00052                 {
00053                     if (await IsFixNeededAsync(selectedAccount))
00054                     {
00055                         await UserDataAccountManager.ShowAccountErrorResolverAsync(selectedAccount.Id);
00056                     }
00057                     else
00058                     {
00059                         rootPage.NotifyUser("Account is not in an error state", NotifyType.ErrorMessage);
00060                     }
00061
00062                     await rootPage.LoadDataAccountsAsync(AccountsListComboBox);
00063                 }
00064
00065                 isLaunched = false;
00066             }
00067         }
00068
00069         /// <summary>
00070         /// Check the mailboxes, calendars, and contact lists for sync errors
00071         /// </summary>
00072         /// <param name="selectedAccount"></param>
00073         /// <returns>True if there is an sync error for email, calendar, or contacts. False if nothing is syncing or everything is syncing correctly</returns>
00074         private async Task<bool> IsFixNeededAsync(UserDataAccount selectedAccount)
00075         {
00076             foreach (EmailMailbox mailbox in await selectedAccount.FindEmailMailboxesAsync())
00077             {
00078                 if (mailbox.SyncManager != null)
00079                 {
00080                     switch (mailbox.SyncManager.Status)
00081                     {
00082                         case EmailMailboxSyncStatus.AuthenticationError:
00083                         case EmailMailboxSyncStatus.PolicyError:
00084                         case EmailMailboxSyncStatus.UnknownError:
00085                             return true;
00086                     }
00087                 }
00088             }
00089
00090             foreach (AppointmentCalendar calendar in await selectedAccount.FindAppointmentCalendarsAsync())
00091             {
00092                 if (calendar.SyncManager != null)
00093                 {
00094                     switch (calendar.SyncManager.Status)
00095                     {
00096                         case AppointmentCalendarSyncStatus.AuthenticationError:
00097                         case AppointmentCalendarSyncStatus.PolicyError:
00098                         case AppointmentCalendarSyncStatus.UnknownError:
00099                             return true;
00100                     }
00101                 }
00102             }
00103
00104             foreach (ContactList contactList in await selectedAccount.FindContactListsAsync())
00105             {
00106                 if (contactList.SyncManager != null)
00107                 {
00108                     switch (contactList.SyncManager.Status)
00109                     {
00110                         case ContactListSyncStatus.AuthenticationError:
00111                         case ContactListSyncStatus.PolicyError:
00112                         case ContactListSyncStatus.UnknownError:
00113                             return true;
00114                     }
00115                 }
00116             }
00117
00118             return false;
00119         }
00120     }
00121 }
Generated on Fri Nov 15 2024 22:21:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

NV12VideoTexture Member List

This is the complete list of members for NV12VideoTexture, including all inherited members.
CopyFromVideoMediaFrame(Windows::Media::Capture::Frames::VideoMediaFrame^source) | NV12VideoTexture |
CreateDeviceDependentResourcesAsync() override | NV12VideoTexture | [virtual]
GetChrominanceTexture(void) const | NV12VideoTexture | [inline]
GetLuminanceTexture(void) const | NV12VideoTexture | [inline]
GetTexture(void) const | NV12VideoTexture | [inline]
m_chrominanceView | NV12VideoTexture | [protected]
m_deviceResources | Resource | [protected]
m_height | NV12VideoTexture | [protected]
m_luminanceView | NV12VideoTexture | [protected]
m_texture | NV12VideoTexture | [protected]
m_width | NV12VideoTexture | [protected]
NV12VideoTexture(std::shared_ptr< DX::DeviceResources > deviceResources, uint32_t width, uint32_t height) | NV12VideoTexture |
ReleaseDeviceDependentResources() override | NV12VideoTexture | [virtual]
Resource(std::shared_ptr< DeviceResources > deviceResources) | Resource | [inline]
~Resource() | Resource | [virtual]
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ManageSession Member List

This is the complete list of members for ManageSession, including all inherited members.
ApduCommand(byte cla, byte ins, byte p1, byte p2, byte[] commandData, byte?le) | ApduCommand | [inline]
ApduResponseType | ApduCommand |
CLA | ApduCommand |
CommandData | ApduCommand |
DataObjectType enum name | ManageSession |
GetBuffer() | ApduCommand | [inline]
INS | ApduCommand |
Le | ApduCommand |
ManageSession(byte[] dataObjects) | ManageSession | [inline]
P1 | ApduCommand |
P2 | ApduCommand |
ToString() | ApduCommand | [inline]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Compression/cpp/pch.cpp Source File

  • Compression
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // pch.cpp
00013 // Include the standard header and generate the precompiled header.
00014 //
00015
00016 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks/ViewModel/ViewModelBase.cpp Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks
  • ViewModel

ViewModelBase.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "ViewModelBase.h"
00013
00014 using namespace AdventureWorks;
00015
00016 using namespace Platform;
00017 using namespace Windows::ApplicationModel::Core;
00018 using namespace Windows::UI::Core;
00019 using namespace Windows::UI::Xaml::Data;
00020
00021 ViewModelBase::ViewModelBase()
00022 {
00023 }
00024
00025 /// <summary> Propagate a PropertyChanged notification to any object inheriting from this
00026 /// base</summary>
00027 /// <param name="propertyName">The property the UI should refresh</param>
00028 void ViewModelBase::NotifyPropertyChanged(String^ propertyName)
00029 {
00030     CoreApplicationView^ view = CoreApplication::MainView;
00031     view->CoreWindow->Dispatcher->RunAsync(
00032         CoreDispatcherPriority::Normal,
00033         ref new DispatchedHandler([this, propertyName]()
00034     {
00035         PropertyChanged(this, ref new PropertyChangedEventArgs(propertyName));
00036
00037     }));
00038 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Pedometer/cs/Scenario4_BackgroundTask.xaml.cs Source File

  • Pedometer
  • cs

Scenario4_BackgroundTask.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013
00014 using System;
00015 using Windows.ApplicationModel.Background;
00016 using Windows.Devices.Enumeration;
00017 using Windows.Devices.Sensors;
00018 using Windows.Globalization.DateTimeFormatting;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021 using Windows.UI.Core;
00022 using Windows.Storage;
00023
00024 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00025
00026 namespace PedometerCS
00027 {
00028     /// <summary>
00029     /// An empty page that can be used on its own or navigated to within a Frame.
00030     /// </summary>
00031     public sealed partial class Scenario4_BackgroundPedometer : Page
00032     {
00033         // Background task details
00034         public const string SampleBackgroundTaskName = "Scenario4_PedometerBackgroundTask";
00035         public const string SampleBackgroundTaskEntryPoint = "Tasks.PedometerBackgroundTask";
00036
00037         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00038         // as NotifyUser()
00039         MainPage rootPage = MainPage.Current;
00040         bool backgroundTaskRegistered = false;
00041         int stepCount = 0;
00042         int stepGoal = 0;
00043         Pedometer sensor = null;
00044         // define a step goal of 50 steps from the current step count
00045         const int stepGoalOffset = 50;
00046
00047         public Scenario4_BackgroundPedometer()
00048         {
00049             this.InitializeComponent();
00050         }
00051
00052         /// <summary>
00053         /// Invoked when this page is about to be displayed in a Frame.
00054         /// </summary>
00055         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00056         /// property is typically used to configure the page.</param>
00057         protected override void OnNavigatedTo(NavigationEventArgs e)
00058         {
00059             foreach (var task in BackgroundTaskRegistration.AllTasks)
00060             {
00061                 if (task.Value.Name == Scenario4_BackgroundPedometer.SampleBackgroundTaskName)
00062                 {
00063                     backgroundTaskRegistered = true;
00064                     break;
00065                 }
00066             }
00067             UpdateUIAsync(backgroundTaskRegistered ? "Registered" : "Unregistered");
00068         }
00069
00070         /// <summary>
00071         /// Invoked when 'Register Task' button is clicked. Attempts to find a default
00072         /// Pedometer and registers a background task with a step goal of 50 steps.
00073         /// Adds a
00074         /// </summary>
00075         private async void ScenarioRegisterTask_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00076         {
00077             try
00078             {
00079                 sensor = await Pedometer.GetDefaultAsync();
00080                 if (sensor != null)
00081                 {
00082                     var status = await BackgroundExecutionManager.RequestAccessAsync();
00083
00084                     if ((BackgroundAccessStatus.AlwaysAllowed == status) ||
00085                         (BackgroundAccessStatus.AllowedSubjectToSystemPolicy == status))
00086                     {
00087                         RegisterBackgroundTask();
00088                     }
00089                     else
00090                     {
00091                         rootPage.NotifyUser("Background tasks may be disabled for this app", NotifyType.ErrorMessage);
00092                     }
00093                 }
00094                 else
00095                 {
00096                     rootPage.NotifyUser("No pedometer sensors found", NotifyType.ErrorMessage);
00097                 }
00098             }
00099             catch (UnauthorizedAccessException)
00100             {
00101                 rootPage.NotifyUser("User has denied access to Pedometer history", NotifyType.ErrorMessage);
00102             }
00103         }
00104
00105         /// <summary>
00106         /// Registers the pedometer background task with a step goal of 50 steps.
00107         /// </summary>
00108         private void RegisterBackgroundTask()
00109         {
00110             // build the background task with the known entry points for Pedometer background task
00111             var builder = new BackgroundTaskBuilder()
00112             {
00113                 Name = SampleBackgroundTaskName,
00114                 TaskEntryPoint = SampleBackgroundTaskEntryPoint
00115             };
00116
00117             // Get the current readings to find the current step counters
00118             var currentReadings = sensor.GetCurrentReadings();
00119             stepCount = 0;
00120             foreach (PedometerStepKind kind in Enum.GetValues(typeof(PedometerStepKind)))
00121             {
00122                 PedometerReading reading;
00123                 if (currentReadings.TryGetValue(kind, out reading))
00124                 {
00125                     stepCount += reading.CumulativeSteps;
00126                 }
00127             }
00128
00129             // set a new step goal
00130             stepGoal = stepCount + Scenario4_BackgroundPedometer.stepGoalOffset;
00131             // create a Pedometer data threshold for that step goal
00132             var threshold = new PedometerDataThreshold(sensor, stepGoal);
00133             // create a sensor trigger using the above threshold
00134             var trigger = new SensorDataThresholdTrigger(threshold);
00135
00136             builder.SetTrigger(trigger);
00137
00138             BackgroundTaskRegistration task = builder.Register();
00139             task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
00140
00141             backgroundTaskRegistered = true;
00142             UpdateUIAsync("Registered");
00143         }
00144
00145         /// <summary>
00146         /// This is the event handler for background task completion.
00147         /// </summary>
00148         /// <param name="task">The task that is reporting completion.</param>
00149         /// <param name="args">The completion report arguments.</param>
00150         private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
00151         {
00152             string status = "Completed and Unregistered";
00153             try
00154             {
00155                 // check for the result from the background task
00156                 args.CheckResult();
00157             }
00158             catch (Exception e)
00159             {
00160                 status = e.Message;
00161             }
00162             // Pedometer background triggers are unique in a way as the background
00163             // events are one-shot - Once the step-goal associated with the original
00164             // task registration has been reached, that step count is a thing-of-past
00165             // and shall not fire as the stepcount on that pedometer changes.
00166             // Unregister the background task or update the step goals here.
00167             task.Unregister(false);
00168             backgroundTaskRegistered = false;
00169             UpdateUIAsync(status);
00170         }
00171
00172         /// <summary>
00173         /// Invoked when 'Unregister Task' button is clicked.
00174         /// </summary>
00175         private void ScenarioUnregisterTask_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00176         {
00177             // Loop through all background tasks and unregister any with SampleBackgroundTaskName
00178             foreach (var cur in BackgroundTaskRegistration.AllTasks)
00179             {
00180                 if (SampleBackgroundTaskName == cur.Value.Name)
00181                 {
00182                     cur.Value.Unregister(true /*cancelTask*/);
00183                     backgroundTaskRegistered = false;
00184                     break;
00185                 }
00186             }
00187
00188             if (!backgroundTaskRegistered)
00189             {
00190                 UpdateUIAsync("Unregistered");
00191             }
00192         }
00193
00194         /// <summary>
00195         /// Updates the scenario UI.
00196         /// </summary>
00197         /// <param name="status">The status string to display.</param>
00198         async private void UpdateUIAsync(string status)
00199         {
00200             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00201             {
00202                 ScenarioRegisterTaskButton.IsEnabled = !backgroundTaskRegistered;
00203                 ScenarioUnregisterTaskButton.IsEnabled = backgroundTaskRegistered;
00204                 ScenarioOutput_TaskRegistration.Text = status;
00205
00206                 var settings = ApplicationData.Current.LocalSettings;
00207
00208                 ScenarioOutput_CurrentCount.Text = stepCount.ToString();
00209                 ScenarioOutput_StepGoal.Text = stepGoal.ToString();
00210
00211                 ScenarioOutput_UnknownCount.Text = "0";
00212                 ScenarioOutput_WalkingCount.Text = "0";
00213                 ScenarioOutput_RunningCount.Text = "0";
00214
00215                 Object value;
00216
00217                 if (settings.Values.TryGetValue("ReportCount", out value))
00218                 {
00219                     ScenarioOutput_ReportCount.Text = value.ToString(); // stored as a string
00220                 }
00221                 if (settings.Values.TryGetValue("TaskStatus", out value))
00222                 {
00223                     ScenarioOutput_TaskStatus.Text = value.ToString();
00224                 }
00225                 if (settings.Values.TryGetValue("LastTimestamp", out value))
00226                 {
00227                     ScenarioOutput_LastTimestamp.Text = value.ToString();
00228                     foreach (PedometerStepKind kind in Enum.GetValues(typeof(PedometerStepKind)))
00229                     {
00230                         if (settings.Values.TryGetValue(kind.ToString(), out value))
00231                         {
00232                             switch (kind)
00233                             {
00234                                 case PedometerStepKind.Unknown:
00235                                     ScenarioOutput_UnknownCount.Text = value.ToString();
00236                                     break;
00237                                 case PedometerStepKind.Walking:
00238                                     ScenarioOutput_WalkingCount.Text = value.ToString();
00239                                     break;
00240                                 case PedometerStepKind.Running:
00241                                     ScenarioOutput_RunningCount.Text = value.ToString();
00242                                     break;
00243                                 default:
00244                                     break;
00245                             }
00246                         }
00247                     }
00248                 }
00249             });
00250         }
00251     }
00252 }
Generated on Fri Nov 15 2024 22:20:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cs/Scenario2_SimpleGridView.xaml.cs Source File

  • XamlListView
  • cs

Scenario2_SimpleGridView.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013
00014 namespace SDKTemplate
00015 {
00016     public sealed partial class Scenario2_SimpleGridView : Page
00017     {
00018         public Scenario2_SimpleGridView()
00019         {
00020             InitializeComponent();
00021             ContactsCVS.Source = Contact.GetContactsGrouped(250);
00022         }
00023     }
00024 }
Generated on Fri Nov 15 2024 22:22:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cpp/Scenario4_OrientationChanged.xaml.h Source File

  • Accelerometer
  • cpp

Scenario4_OrientationChanged.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario4_OrientationChanged.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class Scenario4_OrientationChanged sealed
00025     {
00026     public:
00027         Scenario4_OrientationChanged();
00028
00029     protected:
00030         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00031         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00032
00033         void ScenarioEnable();
00034         void ScenarioDisable();
00035
00036     private:
00037         SDKTemplate::MainPage^ rootPage = MainPage::Current;
00038         Windows::Devices::Sensors::Accelerometer^ accelerometerOriginal;
00039         Windows::Devices::Sensors::Accelerometer^ accelerometerReadingTransform;
00040         Windows::Foundation::EventRegistrationToken visibilityToken;
00041         Windows::Foundation::EventRegistrationToken readingTokenOriginal;
00042         Windows::Foundation::EventRegistrationToken readingTokenReadingTransform;
00043         Windows::Foundation::EventRegistrationToken orientationChangedToken;
00044         Windows::Graphics::Display::DisplayInformation^ displayInformation;
00045
00046         void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00047         void ReadingChangedOriginal(Windows::Devices::Sensors::Accelerometer^ sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^ e);
00048         void ReadingChangedReadingTransform(Windows::Devices::Sensors::Accelerometer^ sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^ e);
00049         void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation ^sender, Platform::Object ^args);
00050     };
00051 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario2WinRTComponent/OnboardingSignals.h Source File

  • AllJoyn
  • Common
  • Scenario2WinRTComponent

OnboardingSignals.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #pragma once
00022
00023 namespace org { namespace alljoyn { namespace Onboarding {
00024
00025 ref class OnboardingSignals;
00026
00027 public interface class IOnboardingSignals
00028 {
00029     event Windows::Foundation::TypedEventHandler<OnboardingSignals^, OnboardingConnectionResultReceivedEventArgs^>^ ConnectionResultReceived;
00030 };
00031
00032 public ref class OnboardingSignals sealed : [Windows::Foundation::Metadata::Default] IOnboardingSignals
00033 {
00034 public:
00035     // "This signal is emitted when the connection attempt against the personal AP is completed"
00036     // Calling this method will send the ConnectionResult signal to every member of the session.
00037     void ConnectionResult(_In_ Onboarding^ interfaceMemberArg);
00038
00039     // This event fires whenever the ConnectionResult signal is sent by another member of the session.
00040     virtual event Windows::Foundation::TypedEventHandler<OnboardingSignals^, OnboardingConnectionResultReceivedEventArgs^>^ ConnectionResultReceived
00041     {
00042         Windows::Foundation::EventRegistrationToken add(Windows::Foundation::TypedEventHandler<OnboardingSignals^, OnboardingConnectionResultReceivedEventArgs^>^ handler)
00043         {
00044             return _ConnectionResultReceived += ref new Windows::Foundation::EventHandler<Platform::Object^>
00045             ([handler](Platform::Object^ sender, Platform::Object^ args)
00046             {
00047                 handler->Invoke(safe_cast<OnboardingSignals^>(sender), safe_cast<OnboardingConnectionResultReceivedEventArgs^>(args));
00048             }, Platform::CallbackContext::Same);
00049         }
00050         void remove(Windows::Foundation::EventRegistrationToken token)
00051         {
00052             _ConnectionResultReceived -= token;
00053         }
00054     internal:
00055         void raise(OnboardingSignals^ sender, OnboardingConnectionResultReceivedEventArgs^ args)
00056         {
00057             _ConnectionResultReceived(sender, args);
00058         }
00059     }
00060
00061 internal:
00062     void Initialize(_In_ ISignalEmitter^ emitter);
00063     void CallConnectionResultReceived(_In_ OnboardingSignals^ sender, _In_ OnboardingConnectionResultReceivedEventArgs^ args);
00064
00065 private:
00066     ISignalEmitter^ m_emitter;
00067
00068     virtual event Windows::Foundation::EventHandler<Platform::Object^>^ _ConnectionResultReceived;
00069
00070     alljoyn_interfacedescription_member m_memberConnectionResult;
00071 };
00072
00073 } } }
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cs/Scenario3_Enum.xaml.cs Source File

  • Calendar
  • cs

Scenario3_Enum.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Text;
00014 using Windows.Foundation;
00015 using Windows.Globalization;
00016 using Windows.Globalization.DateTimeFormatting;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class Scenario3_Enum : Page
00023     {
00024         public Scenario3_Enum()
00025         {
00026             this.InitializeComponent();
00027         }
00028
00029         private void ShowResults_Click(object sender, RoutedEventArgs e)
00030         {
00031             // This scenario uses the Windows.Globalization.Calendar class to enumerate through a calendar and
00032             // perform calendar math
00033             StringBuilder results = new StringBuilder();
00034
00035             results.AppendLine("The number of years in each era of the Japanese era calendar is not regular. " +
00036                                "It is determined by the length of the given imperial era:");
00037             results.AppendLine();
00038
00039             // Create Japanese calendar.
00040             Calendar calendar = new Calendar(new[] { "en-US" }, CalendarIdentifiers.Japanese, ClockIdentifiers.TwentyFourHour);
00041
00042             // Enumerate all supported years in all supported Japanese eras.
00043             for (calendar.Era = calendar.FirstEra; true; calendar.AddYears(1))
00044             {
00045                 // Process current era.
00046                 results.AppendLine("Era " + calendar.EraAsString() + " contains " + calendar.NumberOfYearsInThisEra + " year(s)");
00047
00048                 // Enumerate all years in this era.
00049                 for (calendar.Year = calendar.FirstYearInThisEra; true; calendar.AddYears(1))
00050                 {
00051                     // Begin sample processing of current year.
00052
00053                     // Move to first day of year. Change of month can affect day so order of assignments is important.
00054                     calendar.Month = calendar.FirstMonthInThisYear;
00055                     calendar.Day = calendar.FirstDayInThisMonth;
00056
00057                     // Set time to midnight (local).
00058                     calendar.Period = calendar.FirstPeriodInThisDay;    // All days have 1 or 2 periods depending on clock type
00059                     calendar.Hour = calendar.FirstHourInThisPeriod;     // Hours start from 12 or 0 depending on clock type
00060                     calendar.Minute = 0;
00061                     calendar.Second = 0;
00062                     calendar.Nanosecond = 0;
00063
00064                     if (calendar.Year % 1000 == 0)
00065                     {
00066                         results.AppendLine();
00067                     }
00068                     else if (calendar.Year % 10 == 0)
00069                     {
00070                         results.Append(".");
00071                     }
00072
00073                     // End sample processing of current year.
00074
00075                     // Break after processing last year.
00076                     if (calendar.Year == calendar.LastYearInThisEra)
00077                     {
00078                         break;
00079                     }
00080                 }
00081                 results.AppendLine();
00082
00083                 // Break after processing last era.
00084                 if (calendar.Era == calendar.LastEra)
00085                 {
00086                     break;
00087                 }
00088             }
00089             results.AppendLine();
00090
00091             // This section shows enumeration through the hours in a day to demonstrate that the number of time units in a given period (hours in a day, minutes in an hour, etc.)
00092             // should not be regarded as fixed. With Daylight Saving Time and other local calendar adjustments, a given day may have not have 24 hours, and
00093             // a given hour may not have 60 minutes, etc.
00094             results.AppendLine("The number of hours in a day is not constant. " +
00095                                "The US calendar transitions from daylight saving time to standard time on 4 November 2012:\n");
00096
00097             // Create a DateTimeFormatter to display dates
00098             DateTimeFormatter displayDate = new DateTimeFormatter("longdate");
00099
00100             // Create a gregorian calendar for the US with 12-hour clock format
00101             Calendar currentCal = new Windows.Globalization.Calendar(new string[] { "en-US" }, CalendarIdentifiers.Gregorian, ClockIdentifiers.TwentyFourHour, "America/Los_Angeles");
00102
00103             // Set the calendar to a the date of the Daylight Saving Time-to-Standard Time transition for the US in 2012.
00104             // DST ends in the America/Los_Angeles time zone at 4 November 2012 02:00 PDT = 4 November 2012 09:00 UTC.
00105             DateTime dstDate = new DateTime(2012, 11, 4, 9, 0, 0, DateTimeKind.Utc);
00106             currentCal.SetDateTime(dstDate);
00107
00108             // Set the current calendar to one day before DST change. Create a second calendar for comparision and set it to one day after DST change.
00109             Calendar endDate = currentCal.Clone();
00110             currentCal.AddDays(-1);
00111             endDate.AddDays(1);
00112
00113             // Enumerate the day before, the day of, and the day after the 2012 DST-to-Standard time transition
00114             while (currentCal.Day <= endDate.Day)
00115             {
00116                 // Process current day.
00117                 DateTimeOffset date = currentCal.GetDateTime();
00118                 results.AppendFormat("{0} contains {1} hour(s)\n", displayDate.Format(date), currentCal.NumberOfHoursInThisPeriod);
00119
00120                 // Enumerate all hours in this day.
00121                 // Create a calendar to represent the following day.
00122                 Calendar nextDay = currentCal.Clone();
00123                 nextDay.AddDays(1);
00124                 for (currentCal.Hour = currentCal.FirstHourInThisPeriod; true; currentCal.AddHours(1))
00125                 {
00126                     // Display the hour for each hour in the day.
00127                     results.AppendFormat("{0} ", currentCal.HourAsPaddedString(2));
00128
00129                     // Break upon reaching the next period (i.e. the first period in the following day).
00130                     if (currentCal.Day == nextDay.Day && currentCal.Period == nextDay.Period)
00131                     {
00132                         break;
00133                     }
00134                 }
00135                 results.AppendLine();
00136             }
00137
00138             // Display results
00139             OutputTextBlock.Text = results.ToString();
00140         }
00141     }
00142 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactCards/cpp/pch.h Source File

  • ContactCards
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cs/SetErrorMessage.xaml.cs Source File

  • ShareSource
  • cs

SetErrorMessage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.DataTransfer;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public sealed partial class SetErrorMessage
00019     {
00020         public SetErrorMessage()
00021         {
00022             this.InitializeComponent();
00023         }
00024
00025         protected override bool GetShareContent(DataRequest request)
00026         {
00027             string errorMessage = CustomErrorText.Text;
00028             if (String.IsNullOrEmpty(errorMessage))
00029             {
00030                 errorMessage = "Enter a failure display text and try again.";
00031             }
00032             request.FailWithDisplayText(errorMessage);
00033             return false;
00034         }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5 Member List

This is the complete list of members for Scenario5, including all inherited members.
AudioTracks_SelectedIndexChanged(ISingleSelectMediaTrackList sender, object args) | Scenario5 | [inline, private]
GetThumbnailButton_Click(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
InertiaSwitch_Toggled(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
InitOptions() | Scenario5 | [inline, private]
item | Scenario5 | [private]
manipulationProcessor | Scenario5 | [private]
movementAxis_Changed(object sender, SelectionChangedEventArgs e) | Scenario5 | [inline, private]
mpiLogger | Scenario5 | [private]
myMap_Loaded(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario5 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario5 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario5 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario5 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario5 | [inline, protected]
OnSizeChanged(object sender, SizeChangedEventArgs e) | Scenario5 | [inline, private]
ReadFromStreamButton_Click(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
recognizer | Scenario5 | [private]
resetButton_Pressed(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
rootPage | Scenario5 | [private]
Scenario5() | Scenario5 | [inline]
Scenario5() | Scenario5 | [inline]
Scenario5() | Scenario5 | [inline]
Scenario5() | Scenario5 | [inline]
Scenario5() | Scenario5 | [inline]
Scenario5() | Scenario5 | [inline]
Scenario5() | Scenario5 | [inline]
Scenario5Button_Show_Click(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
showStreetSideNearSpaceneedle_Click(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
TrackButton_Click(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
WriteToStreamButton_Click(object sender, RoutedEventArgs e) | Scenario5 | [inline, private]
Generated on Fri Nov 15 2024 22:23:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: EnterpriseDataProtection/cs/Scenario9_ClipboardTarget.xaml.cs Source File

  • EnterpriseDataProtection
  • cs

Scenario9_ClipboardTarget.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using System.Threading.Tasks;
00017 using SDKTemplate;
00018 using Windows.Security.EnterpriseData;
00019
00020
00021 namespace EdpSample
00022 {
00023     public sealed partial class Scenario9_ClipboardTarget : Page
00024     {
00025         private MainPage rootPage;
00026
00027         public Scenario9_ClipboardTarget()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         protected override void OnNavigatedTo(NavigationEventArgs e)
00033         {
00034             rootPage = MainPage.Current;
00035
00036             var protectionPolicyManager = ProtectionPolicyManager.GetForCurrentView();
00037             protectionPolicyManager.Identity = ""; // personal context
00038             InputTxtBox.PlaceholderText = "Copy Text here from a non-enterprise app";
00039         }
00040
00041         private async void PasteButton_Click(object sender, TextControlPasteEventArgs e)
00042         {
00043             // Mark the event as handled first. Otherwise, the
00044             // default paste action will happen, then the custom paste
00045             // action, and the user will see the text box content change.
00046             e.Handled = true;
00047
00048             // Get content from the clipboard.
00049             var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
00050             if (dataPackageView.Contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.Text))
00051             {
00052                 var response = await dataPackageView.RequestAccessAsync();
00053                 if (response == ProtectionPolicyEvaluationResult.Allowed)
00054                 {
00055                     (sender as TextBox).Text = await dataPackageView.GetTextAsync();
00056                     string sourceId = dataPackageView.Properties.EnterpriseId != null ? dataPackageView.Properties.EnterpriseId : "<Personal>";
00057                     string targetId = ProtectionPolicyManager.GetForCurrentView().Identity != null ? dataPackageView.Properties.EnterpriseId : "<Personal>";
00058                     string message = "Successfully pasted text from EnterpriseId " + sourceId + " to EnterpriseId " + targetId;
00059                     rootPage.NotifyUser(message, NotifyType.StatusMessage);
00060                 }
00061                 else
00062                 {
00063                     rootPage.NotifyUser("User or policy blocked access", NotifyType.StatusMessage);
00064                 }
00065             }
00066         }
00067     }
00068 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialMapping/cpp/Content/RealtimeSurfaceMeshRenderer.cpp Source File

  • HolographicSpatialMapping
  • cpp
  • Content

RealtimeSurfaceMeshRenderer.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013
00014
00015 #include "Common\DirectXHelper.h"
00016 #include "RealtimeSurfaceMeshRenderer.h"
00017
00018 using namespace WindowsHolographicCodeSamples;
00019
00020 using namespace Concurrency;
00021 using namespace DX;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Foundation::Numerics;
00024 using namespace Windows::Perception::Spatial;
00025 using namespace Windows::Perception::Spatial::Surfaces;
00026
00027 using namespace Platform;
00028
00029 RealtimeSurfaceMeshRenderer::RealtimeSurfaceMeshRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00030     m_deviceResources(deviceResources)
00031 {
00032     m_meshCollection.clear();
00033     CreateDeviceDependentResources();
00034 };
00035
00036 // Called once per frame, maintains and updates the mesh collection.
00037 void RealtimeSurfaceMeshRenderer::Update(
00038     DX::StepTimer const& timer,
00039     SpatialCoordinateSystem^ coordinateSystem
00040     )
00041 {
00042     std::lock_guard<std::mutex> guard(m_meshCollectionLock);
00043
00044     const float timeElapsed = static_cast<float>(timer.GetTotalSeconds());
00045
00046     // Update meshes as needed, based on the current coordinate system.
00047     // Also remove meshes that are inactive for too long.
00048     for (auto iter = m_meshCollection.begin(); iter != m_meshCollection.end(); )
00049     {
00050         auto& pair = *iter;
00051         auto& surfaceMesh = pair.second;
00052
00053         // Update the surface mesh.
00054         surfaceMesh.UpdateTransform(
00055             m_deviceResources->GetD3DDevice(),
00056             m_deviceResources->GetD3DDeviceContext(),
00057             timer,
00058             coordinateSystem
00059         );
00060
00061         // Check to see if the mesh has expired.
00062         float lastActiveTime = surfaceMesh.GetLastActiveTime();
00063         float inactiveDuration = timeElapsed - lastActiveTime;
00064         if (inactiveDuration > c_maxInactiveMeshTime)
00065         {
00066             // Surface mesh is expired.
00067             m_meshCollection.erase(iter++);
00068         }
00069         else
00070         {
00071             ++iter;
00072         }
00073     };
00074 }
00075
00076 void RealtimeSurfaceMeshRenderer::AddSurface(Guid id, SpatialSurfaceInfo^ newSurface)
00077 {
00078     auto fadeInMeshTask = AddOrUpdateSurfaceAsync(id, newSurface).then([this, id] ()
00079     {
00080         if (HasSurface(id))
00081         {
00082             std::lock_guard<std::mutex> guard(m_meshCollectionLock);
00083
00084             // In this example, new surfaces are treated differently by highlighting them in a different
00085             // color. This allows you to observe changes in the spatial map that are due to new meshes,
00086             // as opposed to mesh updates.
00087             auto& surfaceMesh = m_meshCollection[id];
00088             surfaceMesh.SetColorFadeTimer(c_surfaceMeshFadeInTime);
00089         }
00090     });
00091 }
00092
00093 void RealtimeSurfaceMeshRenderer::UpdateSurface(Guid id, SpatialSurfaceInfo^ newSurface)
00094 {
00095     AddOrUpdateSurfaceAsync(id, newSurface);
00096 }
00097
00098 Concurrency::task<void> RealtimeSurfaceMeshRenderer::AddOrUpdateSurfaceAsync(Guid id, SpatialSurfaceInfo^ newSurface)
00099 {
00100     auto options = ref new SpatialSurfaceMeshOptions();
00101     options->IncludeVertexNormals = true;
00102
00103     // The level of detail setting is used to limit mesh complexity, by limiting the number
00104     // of triangles per cubic meter.
00105     auto createMeshTask = create_task(newSurface->TryComputeLatestMeshAsync(m_maxTrianglesPerCubicMeter, options));
00106     auto processMeshTask = createMeshTask.then([this, id](SpatialSurfaceMesh^ mesh)
00107     {
00108         if (mesh != nullptr)
00109         {
00110             std::lock_guard<std::mutex> guard(m_meshCollectionLock);
00111
00112             auto& surfaceMesh = m_meshCollection[id];
00113             surfaceMesh.UpdateSurface(mesh);
00114             surfaceMesh.SetIsActive(true);
00115         }
00116     }, task_continuation_context::use_current());
00117
00118     return processMeshTask;
00119 }
00120
00121 void RealtimeSurfaceMeshRenderer::RemoveSurface(Guid id)
00122 {
00123     std::lock_guard<std::mutex> guard(m_meshCollectionLock);
00124     m_meshCollection.erase(id);
00125 }
00126
00127 void RealtimeSurfaceMeshRenderer::ClearSurfaces()
00128 {
00129     std::lock_guard<std::mutex> guard(m_meshCollectionLock);
00130     m_meshCollection.clear();
00131 }
00132
00133 void RealtimeSurfaceMeshRenderer::HideInactiveMeshes(IMapView<Guid, SpatialSurfaceInfo^>^ const& surfaceCollection)
00134 {
00135     std::lock_guard<std::mutex> guard(m_meshCollectionLock);
00136
00137     // Hide surfaces that aren't actively listed in the surface collection.
00138     for (auto& pair : m_meshCollection)
00139     {
00140         const auto& id = pair.first;
00141         auto& surfaceMesh = pair.second;
00142
00143         surfaceMesh.SetIsActive(surfaceCollection->HasKey(id) ? true : false);
00144     };
00145 }
00146
00147 // Renders one frame using the vertex, geometry, and pixel shaders.
00148 void RealtimeSurfaceMeshRenderer::Render(bool isStereo, bool useWireframe)
00149 {
00150     // Loading is asynchronous. Only draw geometry after it's loaded.
00151     if (!m_loadingComplete)
00152     {
00153         return;
00154     }
00155
00156     auto context = m_deviceResources->GetD3DDeviceContext();
00157
00158     context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00159     context->IASetInputLayout(m_inputLayout.Get());
00160
00161     // Attach our vertex shader.
00162     context->VSSetShader(
00163         m_vertexShader.Get(),
00164         nullptr,
00165         0
00166         );
00167
00168     // The constant buffer is per-mesh, and will be set for each one individually.
00169     if (!m_usingVprtShaders)
00170     {
00171         // Attach the passthrough geometry shader.
00172         context->GSSetShader(
00173             m_geometryShader.Get(),
00174             nullptr,
00175             0
00176             );
00177     }
00178
00179     if (useWireframe)
00180     {
00181         // Use a wireframe rasterizer state.
00182         m_deviceResources->GetD3DDeviceContext()->RSSetState(m_wireframeRasterizerState.Get());
00183
00184         // Attach a pixel shader to render a solid color wireframe.
00185         context->PSSetShader(
00186             m_colorPixelShader.Get(),
00187             nullptr,
00188             0
00189         );
00190     }
00191     else
00192     {
00193         // Use the default rasterizer state.
00194         m_deviceResources->GetD3DDeviceContext()->RSSetState(m_defaultRasterizerState.Get());
00195
00196         // Attach a pixel shader that can do lighting.
00197         context->PSSetShader(
00198             m_lightingPixelShader.Get(),
00199             nullptr,
00200             0
00201         );
00202     }
00203
00204     {
00205         std::lock_guard<std::mutex> guard(m_meshCollectionLock);
00206
00207         // Draw the meshes.
00208         auto device = m_deviceResources->GetD3DDevice();
00209         for (auto& pair : m_meshCollection)
00210         {
00211             auto& id = pair.first;
00212             auto& surfaceMesh = pair.second;
00213
00214             surfaceMesh.Draw(device, context, m_usingVprtShaders, isStereo);
00215         }
00216     }
00217 }
00218
00219 void RealtimeSurfaceMeshRenderer::CreateDeviceDependentResources()
00220 {
00221     m_usingVprtShaders = m_deviceResources->GetDeviceSupportsVprt();
00222
00223     // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3::
00224     // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature
00225     // we can avoid using a pass-through geometry shader to set the render
00226     // target array index, thus avoiding any overhead that would be
00227     // incurred by setting the geometry shader stage.
00228     std::wstring vertexShaderFileName = m_usingVprtShaders ? L"ms-appx:///SurfaceVprtVertexShader.cso" : L"ms-appx:///SurfaceVertexShader.cso";
00229
00230     // Load shaders asynchronously.
00231     task<std::vector<byte>> loadVSTask = DX::ReadDataAsync(vertexShaderFileName);
00232     task<std::vector<byte>> loadLightingPSTask = DX::ReadDataAsync(L"ms-appx:///SimpleLightingPixelShader.cso");
00233     task<std::vector<byte>> loadWireframePSTask = DX::ReadDataAsync(L"ms-appx:///SolidColorPixelShader.cso");
00234
00235     task<std::vector<byte>> loadGSTask;
00236     if (!m_usingVprtShaders)
00237     {
00238         // Load the pass-through geometry shader.
00239         loadGSTask = DX::ReadDataAsync(L"ms-appx:///SurfaceGeometryShader.cso");
00240     }
00241
00242     // After the vertex shader file is loaded, create the shader and input layout.
00243     auto createVSTask = loadVSTask.then([this](const std::vector<byte>& fileData) {
00244         DX::ThrowIfFailed(
00245             m_deviceResources->GetD3DDevice()->CreateVertexShader(
00246                 &fileData[0],
00247                 fileData.size(),
00248                 nullptr,
00249                 &m_vertexShader
00250                 )
00251             );
00252
00253         static const D3D11_INPUT_ELEMENT_DESC vertexDesc [] =
00254         {
00255             { "POSITION", 0, DXGI_FORMAT_R16G16B16A16_SNORM, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00256             { "NORMAL",   0, DXGI_FORMAT_R8G8B8A8_SNORM,     1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00257         };
00258
00259         DX::ThrowIfFailed(
00260             m_deviceResources->GetD3DDevice()->CreateInputLayout(
00261                 vertexDesc,
00262                 ARRAYSIZE(vertexDesc),
00263                 &fileData[0],
00264                 fileData.size(),
00265                 &m_inputLayout
00266                 )
00267             );
00268     });
00269
00270     // After the pixel shader file is loaded, create the shader and constant buffer.
00271     auto createLightingPSTask = loadLightingPSTask.then([this](const std::vector<byte>& fileData) {
00272         DX::ThrowIfFailed(
00273             m_deviceResources->GetD3DDevice()->CreatePixelShader(
00274                 &fileData[0],
00275                 fileData.size(),
00276                 nullptr,
00277                 &m_lightingPixelShader
00278                 )
00279             );
00280     });
00281
00282     // After the pixel shader file is loaded, create the shader and constant buffer.
00283     auto createWireframePSTask = loadWireframePSTask.then([this](const std::vector<byte>& fileData) {
00284         DX::ThrowIfFailed(
00285             m_deviceResources->GetD3DDevice()->CreatePixelShader(
00286                 &fileData[0],
00287                 fileData.size(),
00288                 nullptr,
00289                 &m_colorPixelShader
00290             )
00291         );
00292     });
00293
00294     task<void> createGSTask;
00295     if (!m_usingVprtShaders)
00296     {
00297         // After the pass-through geometry shader file is loaded, create the shader.
00298         createGSTask = loadGSTask.then([this](const std::vector<byte>& fileData)
00299         {
00300             DX::ThrowIfFailed(
00301                 m_deviceResources->GetD3DDevice()->CreateGeometryShader(
00302                     &fileData[0],
00303                     fileData.size(),
00304                     nullptr,
00305                     &m_geometryShader
00306                     )
00307                 );
00308         });
00309     }
00310
00311     // Once all shaders are loaded, create the mesh.
00312     task<void> shaderTaskGroup = m_usingVprtShaders ?
00313         (createLightingPSTask && createWireframePSTask && createVSTask) :
00314         (createLightingPSTask && createWireframePSTask && createVSTask && createGSTask);
00315
00316     // Once the cube is loaded, the object is ready to be rendered.
00317     auto finishLoadingTask = shaderTaskGroup.then([this]() {
00318
00319         // Recreate device-based surface mesh resources.
00320         std::lock_guard<std::mutex> guard(m_meshCollectionLock);
00321         for (auto& iter : m_meshCollection)
00322         {
00323             iter.second.ReleaseDeviceDependentResources();
00324             iter.second.CreateDeviceDependentResources(m_deviceResources->GetD3DDevice());
00325         }
00326
00327         // Create a default rasterizer state descriptor.
00328         D3D11_RASTERIZER_DESC rasterizerDesc = CD3D11_RASTERIZER_DESC(D3D11_DEFAULT);
00329
00330         // Create the default rasterizer state.
00331         m_deviceResources->GetD3DDevice()->CreateRasterizerState(&rasterizerDesc, m_defaultRasterizerState.GetAddressOf());
00332
00333         // Change settings for wireframe rasterization.
00334         rasterizerDesc.AntialiasedLineEnable = true;
00335         rasterizerDesc.CullMode = D3D11_CULL_NONE;
00336         rasterizerDesc.FillMode = D3D11_FILL_WIREFRAME;
00337
00338         // Create a wireframe rasterizer state.
00339         m_deviceResources->GetD3DDevice()->CreateRasterizerState(&rasterizerDesc, m_wireframeRasterizerState.GetAddressOf());
00340
00341         m_loadingComplete = true;
00342     });
00343 }
00344
00345 void RealtimeSurfaceMeshRenderer::ReleaseDeviceDependentResources()
00346 {
00347     m_loadingComplete = false;
00348
00349     m_vertexShader.Reset();
00350     m_inputLayout.Reset();
00351     m_geometryShader.Reset();
00352     m_lightingPixelShader.Reset();
00353     m_colorPixelShader.Reset();
00354
00355     m_defaultRasterizerState.Reset();
00356     m_wireframeRasterizerState.Reset();
00357
00358     std::lock_guard<std::mutex> guard(m_meshCollectionLock);
00359     for (auto& iter : m_meshCollection)
00360     {
00361         iter.second.ReleaseDeviceDependentResources();
00362     }
00363 }
00364
00365 bool RealtimeSurfaceMeshRenderer::HasSurface(Platform::Guid id)
00366 {
00367     std::lock_guard<std::mutex> guard(m_meshCollectionLock);
00368     return m_meshCollection.find(id) != m_meshCollection.end();
00369 }
00370
00371 Windows::Foundation::DateTime RealtimeSurfaceMeshRenderer::GetLastUpdateTime(Platform::Guid id)
00372 {
00373     std::lock_guard<std::mutex> guard(m_meshCollectionLock);
00374     auto& meshIter = m_meshCollection.find(id);
00375     if (meshIter != m_meshCollection.end())
00376     {
00377         auto const& mesh = meshIter->second;
00378         return mesh.GetLastUpdateTime();
00379     }
00380     else
00381     {
00382         static const Windows::Foundation::DateTime zero;
00383         return zero;
00384     }
00385 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/SmartCardHelpers.h Source File

  • SmartCard
  • cppwinrt

SmartCardHelpers.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 namespace winrt::SDKTemplate
00004 {
00005     const uint32_t ADMIN_KEY_LENGTH_IN_BYTES = 24;
00006
00007     bool ValidateTPMSmartCard();
00008
00009     winrt::hstring GetSmartCardReaderDeviceId();
00010     void SetSmartCardReaderDeviceId(winrt::hstring const& id);
00011
00012     winrt::Windows::Storage::Streams::IBuffer GetAdminKey();
00013     void SetAdminKey(winrt::Windows::Storage::Streams::IBuffer const& buffer);
00014
00015     Windows::Foundation::IAsyncOperation<Windows::Devices::SmartCards::SmartCard> GetSmartCardAsync();
00016
00017     Windows::Storage::Streams::IBuffer CalculateChallengeResponse(
00018         Windows::Storage::Streams::IBuffer const& challenge,
00019         Windows::Storage::Streams::IBuffer const& adminKey);
00020 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Resource Member List

This is the complete list of members for Resource, including all inherited members.
CreateDeviceDependentResourcesAsync()=0 | Resource | [pure virtual]
m_deviceResources | Resource | [protected]
ReleaseDeviceDependentResources()=0 | Resource | [pure virtual]
Resource(std::shared_ptr< DeviceResources > deviceResources) | Resource | [inline]
~Resource() | Resource | [virtual]
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomEditControl/cs/SampleConfiguration.cs Source File

  • CustomEditControl
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Custom text control C# Sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Text input", ClassType=typeof(Scenario1_Input)},
00025         };
00026     }
00027
00028     public class Scenario
00029     {
00030         public string Title { get; set; }
00031         public Type ClassType { get; set; }
00032     }
00033 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cpp/Scenario2_ShakeEvents.xaml.h Source File

  • Accelerometer
  • cpp

Scenario2_ShakeEvents.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_ShakeEvents.xaml.h
00014 // Declaration of the Scenario2_ShakeEvents class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario2_ShakeEvents.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario2_ShakeEvents sealed
00030     {
00031     public:
00032         Scenario2_ShakeEvents();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038         void ScenarioEnable();
00039         void ScenarioDisable();
00040
00041     private:
00042         SDKTemplate::MainPage^ rootPage = MainPage::Current;
00043         Windows::UI::Core::CoreDispatcher^ dispatcher;
00044         Windows::Devices::Sensors::Accelerometer^ accelerometer;
00045         Windows::Foundation::EventRegistrationToken visibilityToken;
00046         Windows::Foundation::EventRegistrationToken shakenToken;
00047         uint16 shakeCounter = 0;
00048
00049         void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00050         void Shaken(Windows::Devices::Sensors::Accelerometer^ sender, Windows::Devices::Sensors::AccelerometerShakenEventArgs^ e);
00051     };
00052 }
Generated on Fri Nov 15 2024 22:17:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Projection/cpp/Scenario1.xaml.h Source File

  • Projection
  • cpp

Scenario1.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1.g.h"
00015 #include "MainPage.xaml.h"
00016 #include "ViewLifetimeControl.h"
00017
00018 namespace SDKSample
00019 {
00020     [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class Scenario1 sealed
00022     {
00023     public:
00024         Scenario1();
00025
00026     private:
00027         int thisViewId;
00028         void StartProjecting_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029     };
00030 }
Generated on Fri Nov 15 2024 22:17:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: KeyCredentialManager/cpp/SampleConfiguration.h Source File

  • KeyCredentialManager
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Microsoft Passport";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7_B2B Member List

This is the complete list of members for Scenario7_B2B, including all inherited members.
appIdUri | Scenario7_B2B | [private]
clientId | Scenario7_B2B | [private]
clientSecret | Scenario7_B2B | [private]
GetCustomerCollectionsId() | Scenario7_B2B | [inline, private]
GetCustomerPurchaseId() | Scenario7_B2B | [inline, private]
GetTokenFromAzureOAuthAsync() | Scenario7_B2B | [inline, private]
rootPage | Scenario7_B2B | [private]
Scenario7_B2B() | Scenario7_B2B | [inline]
storeContext | Scenario7_B2B | [private]
tenantId | Scenario7_B2B | [private]
Generated on Fri Nov 15 2024 22:23:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PlayReady/cs/Scenario2_ProactiveRequest.xaml.cs Source File

  • PlayReady
  • cs

Scenario2_ProactiveRequest.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate.ViewModels;
00013 using Windows.UI.Xaml.Controls;
00014
00015 namespace SDKTemplate
00016 {
00017     public sealed partial class Scenario2_ProactiveRequest : Page
00018     {
00019         public Scenario2_ProactiveRequest()
00020         {
00021             this.InitializeComponent();
00022             this.DataContext = new ProactiveViewModel(mediaElement);
00023         }
00024     }
00025 }
Generated on Fri Nov 15 2024 22:20:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SuperMutt::Pipe Member List

This is the complete list of members for SuperMutt::Pipe, including all inherited members.
BulkInPipeIndex | SuperMutt::Pipe
BulkOutPipeIndex | SuperMutt::Pipe
InterruptInPipeIndex | SuperMutt::Pipe
InterruptOutPipeIndex | SuperMutt::Pipe
Generated on Fri Nov 15 2024 22:23:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FullScreenMode/cppwinrt/Scenario2_Launch.cpp Source File

  • FullScreenMode
  • cppwinrt

Scenario2_Launch.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Launch.h"
00014 #include "Scenario2_Launch.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::UI::ViewManagement;
00019 using namespace Windows::UI::Xaml;
00020
00021 namespace winrt::SDKTemplate::implementation
00022 {
00023     Scenario2_Launch::Scenario2_Launch()
00024     {
00025         InitializeComponent();
00026         LaunchInFullScreenModeCheckBox().IsChecked(ApplicationView::PreferredLaunchWindowingMode() == ApplicationViewWindowingMode::FullScreen);
00027
00028     }
00029
00030     void Scenario2_Launch::LaunchInFullScreenModeCheckBox_Click(IInspectable const&, RoutedEventArgs const&)
00031     {
00032         ApplicationView::PreferredLaunchWindowingMode(LaunchInFullScreenModeCheckBox().IsChecked().Value() ? ApplicationViewWindowingMode::FullScreen : ApplicationViewWindowingMode::Auto);
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboard/cs/Scenario2_ShowHideEvents.xaml.cs Source File

  • TouchKeyboard
  • cs

Scenario2_ShowHideEvents.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.ViewManagement;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Media;
00015 using Windows.Foundation;
00016 using Windows.UI.Xaml.Navigation;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Sample page to subscribe show/hide event of Touch Keyboard.
00022     /// </summary>
00023     public sealed partial class Scenario2_ShowHideEvents : Page
00024     {
00025         public Scenario2_ShowHideEvents()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         protected override void OnNavigatedTo(NavigationEventArgs e)
00031         {
00032             InputPane currentInputPane = InputPane.GetForCurrentView();
00033
00034             // Subscribe to Showing/Hiding events
00035             currentInputPane.Showing += OnShowing;
00036             currentInputPane.Hiding += OnHiding;
00037         }
00038
00039         protected override void OnNavigatedFrom(NavigationEventArgs e)
00040         {
00041             InputPane currentInputPane = InputPane.GetForCurrentView();
00042
00043             // Unsubscribe from Showing/Hiding events
00044             currentInputPane.Showing -= OnShowing;
00045             currentInputPane.Hiding -= OnHiding;
00046         }
00047
00048         void OnShowing(InputPane sender, InputPaneVisibilityEventArgs e)
00049         {
00050             LastInputPaneEventRun.Text = "Showing";
00051         }
00052
00053         void OnHiding(InputPane sender, InputPaneVisibilityEventArgs e)
00054         {
00055             LastInputPaneEventRun.Text = "Hiding";
00056         }
00057     }
00058 }
Generated on Fri Nov 15 2024 22:21:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DPhotoAdjustment/cpp/PhotoAdjustmentRenderer.cpp Source File

  • D2DPhotoAdjustment
  • cpp

PhotoAdjustmentRenderer.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "PhotoAdjustmentRenderer.h"
00014 #include "DirectXPage.xaml.h"
00015 #include "Common\DirectXHelper.h"
00016
00017 using namespace D2DPhotoAdjustment;
00018
00019 using namespace concurrency;
00020 using namespace DirectX;
00021 using namespace Microsoft::WRL;
00022 using namespace Platform;
00023 using namespace std;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Foundation::Collections;
00026 using namespace Windows::Graphics::Display;
00027 using namespace Windows::Storage::Streams;
00028 using namespace Windows::UI::Input;
00029
00030 PhotoAdjustmentRenderer::PhotoAdjustmentRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00031     m_deviceResources(deviceResources),
00032     m_maxZoom(1.0f), // Never allow upscaling.
00033     m_imageSize(),
00034     m_panelSize(),
00035     m_isWindowClosed(false),
00036     m_zoom()
00037 {
00038     // Register to be notified if the GPU device is lost or recreated.
00039     m_deviceResources->RegisterDeviceNotify(this);
00040
00041     CreateDeviceIndependentResources();
00042     CreateDeviceDependentResources();
00043     CreateWindowSizeDependentResources();
00044 }
00045
00046 PhotoAdjustmentRenderer::~PhotoAdjustmentRenderer()
00047 {
00048     // Deregister device notification.
00049     m_deviceResources->RegisterDeviceNotify(nullptr);
00050 }
00051
00052 void PhotoAdjustmentRenderer::CreateDeviceIndependentResources()
00053 {
00054     auto wicFactory = m_deviceResources->GetWicImagingFactory();
00055     auto d2dFactory = m_deviceResources->GetD2DFactory();
00056
00057     // Use WIC to decode the JPEG image and load it into Direct2D.
00058     ComPtr<IWICBitmapDecoder> decoder;
00059     DX::ThrowIfFailed(wicFactory->CreateDecoderFromFilename(
00060         L"Assets\\rainier.jpg",
00061         nullptr,
00062         GENERIC_READ,
00063         WICDecodeMetadataCacheOnDemand,
00064         &decoder
00065         ));
00066
00067     ComPtr<IWICBitmapFrameDecode> frame;
00068     DX::ThrowIfFailed(decoder->GetFrame(0, &frame));
00069
00070     // Convert the image to a pixel format supported by Direct2D. 32bppPBGRA is
00071     // guaranteed to be supported on all hardware.
00072     DX::ThrowIfFailed(wicFactory->CreateFormatConverter(&m_formatConvert));
00073     DX::ThrowIfFailed(m_formatConvert->Initialize(
00074         frame.Get(),
00075         GUID_WICPixelFormat32bppPBGRA,
00076         WICBitmapDitherTypeNone,
00077         nullptr,
00078         0.0f,
00079         WICBitmapPaletteTypeCustom
00080         ));
00081
00082     UINT width;
00083     UINT height;
00084     DX::ThrowIfFailed(m_formatConvert->GetSize(&width, &height));
00085     m_imageSize = Size(static_cast<float>(width), static_cast<float>(height));
00086
00087     // Attempt to read the embedded color profile from the image; use sRGB if the data doesn't exist.
00088     UINT actualCount;
00089     DX::ThrowIfFailed(wicFactory->CreateColorContext(&m_wicColorContext));
00090     DX::ThrowIfFailed(frame->GetColorContexts(1, m_wicColorContext.GetAddressOf(), &actualCount));
00091
00092     if (actualCount == 0)
00093     {
00094         m_wicColorContext->InitializeFromExifColorSpace(1); // 1 = sRGB.
00095     }
00096 }
00097
00098 void PhotoAdjustmentRenderer::CreateDeviceDependentResources()
00099 {
00100     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00101     auto d2dDevice = m_deviceResources->GetD2DDevice();
00102
00103     // Load the image from WIC using ID2D1ImageSource. The image source selects optimal image loading
00104     // and caching behavior for the scenario and also supports greater than max texture size images.
00105     // Scaling is accomplished using ID2D1TransformedImageSource in UpdateZoomState().
00106     DX::ThrowIfFailed(d2dContext->CreateImageSourceFromWic(m_formatConvert.Get(), &m_imageSource));
00107
00108     // Create the photo adjustment pipeline.
00109     DX::ThrowIfFailed(d2dContext->CreateEffect(CLSID_D2D1ColorManagement, &m_colorManagement));
00110     DX::ThrowIfFailed(d2dContext->CreateEffect(CLSID_D2D1Straighten, &m_straighten));
00111     DX::ThrowIfFailed(d2dContext->CreateEffect(CLSID_D2D1TemperatureTint, &m_temperatureTint));
00112     DX::ThrowIfFailed(d2dContext->CreateEffect(CLSID_D2D1Saturation, &m_saturation));
00113     DX::ThrowIfFailed(d2dContext->CreateEffect(CLSID_D2D1Contrast, &m_contrast));
00114     DX::ThrowIfFailed(d2dContext->CreateEffect(CLSID_D2D1HighlightsShadows, &m_highlightsShadows));
00115
00116     // Chain the individual photo adjustment effects together.
00117     // The input to the first effect (color management) is set during UpdateZoomState.
00118     m_straighten->SetInputEffect(0, m_colorManagement.Get());
00119     m_temperatureTint->SetInputEffect(0, m_straighten.Get());
00120     m_saturation->SetInputEffect(0, m_temperatureTint.Get());
00121     m_contrast->SetInputEffect(0, m_saturation.Get());
00122     m_highlightsShadows->SetInputEffect(0, m_contrast.Get());
00123
00124     // m_outputEffect always points to the photo pipeline output.
00125     DX::ThrowIfFailed(m_highlightsShadows.CopyTo(&m_outputEffect));
00126
00127     // Do one-time configuration of the photo pipeline.
00128     m_straighten->SetValue(D2D1_STRAIGHTEN_PROP_MAINTAIN_SIZE, TRUE);
00129
00130     // Consider using a higher quality mode for offline processing, like saving the image to disk.
00131     m_colorManagement->SetValue(D2D1_COLORMANAGEMENT_PROP_QUALITY, D2D1_COLORMANAGEMENT_QUALITY_PROOF);
00132
00133     ComPtr<ID2D1ColorContext> sourceContext;
00134     DX::ThrowIfFailed(d2dContext->CreateColorContextFromWicColorContext(m_wicColorContext.Get(), &sourceContext));
00135     m_colorManagement->SetValue(D2D1_COLORMANAGEMENT_PROP_SOURCE_COLOR_CONTEXT, sourceContext.Get());
00136
00137     // Force loading the current display color context.
00138     OnColorProfileChanged(DisplayInformation::GetForCurrentView());
00139 }
00140
00141 void PhotoAdjustmentRenderer::ReleaseDeviceDependentResources()
00142 {
00143     m_imageSource.Reset();
00144     m_scaledImage.Reset();
00145     m_colorManagement.Reset();
00146     m_straighten.Reset();
00147     m_temperatureTint.Reset();
00148     m_saturation.Reset();
00149     m_contrast.Reset();
00150     m_highlightsShadows.Reset();
00151     m_outputEffect.Reset();
00152 }
00153
00154 void PhotoAdjustmentRenderer::CreateWindowSizeDependentResources()
00155 {
00156     m_panelSize = m_deviceResources->GetLogicalSize();
00157
00158     // Scale the image to fill the window, but never exceed max scale.
00159     m_zoom = min(
00160         max(
00161             m_panelSize.Width / m_imageSize.Width,
00162             m_panelSize.Height / m_imageSize.Height),
00163         m_maxZoom);
00164
00165     UpdateZoomState();
00166 }
00167
00168 // Update render pipeline to reflect the new zoom state.
00169 void PhotoAdjustmentRenderer::UpdateZoomState()
00170 {
00171     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00172
00173     // When using ID2D1ImageSource, the recommend method of scaling is to use
00174     // ID2D1TransformedImageSource. It is inexpensive to recreate this object.
00175     D2D1_TRANSFORMED_IMAGE_SOURCE_PROPERTIES props =
00176     {
00177         D2D1_ORIENTATION_DEFAULT,
00178         m_zoom,
00179         m_zoom,
00180         D2D1_INTERPOLATION_MODE_LINEAR, // This is ignored when using DrawImage.
00181         D2D1_TRANSFORMED_IMAGE_SOURCE_OPTIONS_NONE
00182     };
00183
00184     DX::ThrowIfFailed(d2dContext->CreateTransformedImageSource(
00185         m_imageSource.Get(),
00186         &props,
00187         &m_scaledImage
00188         ));
00189
00190     m_colorManagement->SetInput(0, m_scaledImage.Get());
00191
00192     // Adjust DIP properties for the new zoom and/or DPI.
00193     m_highlightsShadows->SetValue(
00194         D2D1_HIGHLIGHTSANDSHADOWS_PROP_MASK_BLUR_RADIUS,
00195         ConvertDipProperty(m_hsMaskRadiusDips));
00196 }
00197
00198 void PhotoAdjustmentRenderer::Draw()
00199 {
00200     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00201
00202     d2dContext->BeginDraw();
00203
00204     // DeviceResources explicitly handles screen rotation by setting the rotation on the swap chain.
00205     // In order for Direct2D content to appear correctly on this swap chain, the app is responsible for
00206     // explicitly "prerotating" by setting the appropriate transform before drawing.
00207     m_deviceResources->GetD2DDeviceContext()->SetTransform(m_deviceResources->GetOrientationTransform2D());
00208     d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
00209
00210     d2dContext->DrawImage(m_outputEffect.Get());
00211
00212     // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
00213     // is lost. It will be handled during the next call to Present.
00214     HRESULT hr = d2dContext->EndDraw();
00215     if (hr != D2DERR_RECREATE_TARGET)
00216     {
00217         DX::ThrowIfFailed(hr);
00218     }
00219
00220     m_deviceResources->Present();
00221 }
00222
00223 // Notifies renderers that device resources need to be released.
00224 void PhotoAdjustmentRenderer::OnDeviceLost()
00225 {
00226     ReleaseDeviceDependentResources();
00227 }
00228
00229 // Notifies renderers that device resources may now be recreated.
00230 void PhotoAdjustmentRenderer::OnDeviceRestored()
00231 {
00232     CreateDeviceDependentResources();
00233 }
00234
00235 void PhotoAdjustmentRenderer::OnColorProfileChanged(_In_ DisplayInformation^ sender)
00236 {
00237     if (m_colorManagement != nullptr)
00238     {
00239         // The color profile is stored in the DisplayInformation object.
00240         // We need to kick off an asynchronous operation to load the information
00241         // before passing it to the renderer to update the effect pipeline.
00242         shared_ptr<DataReader^> profileReaderPtr = make_shared<DataReader^>();
00243
00244         create_task(sender->GetColorProfileAsync()).then([=](IRandomAccessStream^ profileStream)
00245         {
00246             // Extract the profile bytes from the IRandomAccessStream to initialize the Direct2D color context.
00247             *profileReaderPtr = ref new DataReader(profileStream);
00248
00249             return (*profileReaderPtr)->LoadAsync(static_cast<unsigned int>(profileStream->Size));
00250         }).then([=](unsigned int readBytes)
00251         {
00252             // Direct2D was initialized using D2D1_FACTORY_TYPE_SINGLE_THREADED. Therefore, we must
00253             // ensure that async continuations are executed in the UI thread context. Here, this is done
00254             // for us automatically because create_task wraps a Windows Runtime async operation.
00255             UpdateDisplayColorContext(*profileReaderPtr);
00256             Draw();
00257         }).then([=](task<void> previousTask)
00258         {
00259             try
00260             {
00261                 // DisplayInformation::GetColorProfileAsync() fails if there isn't a valid ICC color
00262                 // profile associated with the display. This is expected and handled below.
00263                 previousTask.get();
00264             }
00265             catch (Platform::COMException^ e)
00266             {
00267                 if (e->HResult == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) ||
00268                     e->HResult == HRESULT_FROM_WIN32(ERROR_INVALID_PROFILE))
00269                 {
00270                     UpdateDisplayColorContext(nullptr);
00271                     Draw();
00272                 }
00273                 else
00274                 {
00275                     throw e;
00276                 }
00277             }
00278         });
00279     }
00280 }
00281
00282 // Pass in nullptr to use the standard sRGB color space.
00283 void PhotoAdjustmentRenderer::UpdateDisplayColorContext(
00284     _In_opt_ DataReader^ colorProfileDataReader
00285     )
00286 {
00287     ComPtr<ID2D1ColorContext> displayColorContext;
00288     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00289
00290     if (colorProfileDataReader == nullptr)
00291     {
00292         DX::ThrowIfFailed(
00293             d2dContext->CreateColorContext(D2D1_COLOR_SPACE_SRGB, nullptr, 0, &displayColorContext)
00294             );
00295     }
00296     else
00297     {
00298         Array<byte>^ profileBytes = ref new Array<byte>(colorProfileDataReader->UnconsumedBufferLength);
00299         colorProfileDataReader->ReadBytes(profileBytes);
00300         DX::ThrowIfFailed(d2dContext->CreateColorContext(
00301             D2D1_COLOR_SPACE_CUSTOM,
00302             profileBytes->Data,
00303             profileBytes->Length,
00304             &displayColorContext
00305             ));
00306     }
00307
00308     DX::ThrowIfFailed(m_colorManagement->SetValue(
00309         D2D1_COLORMANAGEMENT_PROP_DESTINATION_COLOR_CONTEXT,
00310         displayColorContext.Get()
00311         ));
00312 }
00313
00314 // Converts an effect property from DIPs to pixels in the unscaled image's coordinate
00315 // space. This compensates for screen DPI and image scaling, which is needed for
00316 // correct behavior in a photo adjustment pipeline.
00317 float PhotoAdjustmentRenderer::ConvertDipProperty(float valueInDips)
00318 {
00319     float dpiX, dpiY;
00320     m_deviceResources->GetD2DDeviceContext()->GetDpi(&dpiX, &dpiY);
00321     return valueInDips * m_zoom * 96.0f / dpiX;
00322 }
00323
00324 // Invoked when one or more of the photo adjustment pipeline values have changed.
00325 void PhotoAdjustmentRenderer::UpdatePhotoAdjustmentValues(PhotoAdjustmentProperties properties)
00326 {
00327     // Testing for the validity of one of the device-dependent resources is sufficient.
00328     if (m_imageSource != nullptr)
00329     {
00330         DX::ThrowIfFailed(m_straighten->SetValue(
00331             D2D1_STRAIGHTEN_PROP_ANGLE,
00332             static_cast<float>(properties.StraightenValue)));
00333
00334         DX::ThrowIfFailed(m_temperatureTint->SetValue(
00335             D2D1_TEMPERATUREANDTINT_PROP_TEMPERATURE,
00336             static_cast<float>(properties.TemperatureValue)));
00337
00338         DX::ThrowIfFailed(m_temperatureTint->SetValue(
00339             D2D1_TEMPERATUREANDTINT_PROP_TINT,
00340             static_cast<float>(properties.TintValue)));
00341
00342         DX::ThrowIfFailed(m_saturation->SetValue(
00343             D2D1_SATURATION_PROP_SATURATION,
00344             static_cast<float>(properties.SaturationValue)));
00345
00346         DX::ThrowIfFailed(m_contrast->SetValue(
00347             D2D1_CONTRAST_PROP_CONTRAST,
00348             static_cast<float>(properties.ContrastValue)));
00349
00350         DX::ThrowIfFailed(m_highlightsShadows->SetValue(
00351             D2D1_HIGHLIGHTSANDSHADOWS_PROP_SHADOWS,
00352             static_cast<float>(properties.ShadowsValue)));
00353
00354         DX::ThrowIfFailed(m_highlightsShadows->SetValue(
00355             D2D1_HIGHLIGHTSANDSHADOWS_PROP_CLARITY,
00356             static_cast<float>(properties.ClarityValue)));
00357
00358         DX::ThrowIfFailed(m_highlightsShadows->SetValue(
00359             D2D1_HIGHLIGHTSANDSHADOWS_PROP_HIGHLIGHTS,
00360             static_cast<float>(properties.HighlightsValue)));
00361
00362         m_hsMaskRadiusDips = static_cast<float>(properties.HsMaskRadiusValue);
00363         DX::ThrowIfFailed(m_highlightsShadows->SetValue(
00364             D2D1_HIGHLIGHTSANDSHADOWS_PROP_MASK_BLUR_RADIUS,
00365             ConvertDipProperty(m_hsMaskRadiusDips)));
00366     }
00367 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/VideoItem.cs Source File

  • 360VideoPlayback
  • cs

VideoItem.cs

Go to the documentation of this file.
00001 ﻿using System;
00002
00003 namespace _360VideoPlayback
00004 {
00005     public class VideoItem
00006     {
00007         public VideoItem(string title, Uri sourceUri)
00008         {
00009             Title = title;
00010             SourceUri = sourceUri;
00011         }
00012         public string Title { get; private set; }
00013         public Uri SourceUri { get; private set; }
00014     }
00015 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RfcommServerTask Member List

This is the complete list of members for RfcommServerTask, including all inherited members.
cancelReason | RfcommServerTask | [private]
cancelRequested | RfcommServerTask | [private]
deferral | RfcommServerTask | [private]
OnCanceled(IBackgroundTaskInstance taskInstance, BackgroundTaskCancellationReason reason) | RfcommServerTask | [inline, private]
periodicTimer | RfcommServerTask | [private]
PeriodicTimerCallback(ThreadPoolTimer timer) | RfcommServerTask | [inline, private]
reader | RfcommServerTask | [private]
ReceiveDataAsync() | RfcommServerTask | [inline, private]
remoteDevice | RfcommServerTask | [private]
Run(IBackgroundTaskInstance taskInstance) | RfcommServerTask | [inline]
socket | RfcommServerTask | [private]
taskInstance | RfcommServerTask | [private]
writer | RfcommServerTask | [private]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_AamvaCards Member List

This is the complete list of members for Scenario2_AamvaCards, including all inherited members.
_claimedReader | Scenario2_AamvaCards | [private]
_reader | Scenario2_AamvaCards | [private]
ClaimReader() | Scenario2_AamvaCards | [inline, private]
CreateDefaultMagneticStripeReaderObject() | Scenario2_AamvaCards | [inline, private]
OnAamvaCardDataReceived(object sender, MagneticStripeReaderAamvaCardDataReceivedEventArgs args) | Scenario2_AamvaCards | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_AamvaCards | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_AamvaCards | [inline, protected]
OnReleaseDeviceRequested(object sender, ClaimedMagneticStripeReader args) | Scenario2_AamvaCards | [inline, private]
ResetTheScenarioState() | Scenario2_AamvaCards | [inline, private]
rootPage | Scenario2_AamvaCards | [private]
Scenario2_AamvaCards() | Scenario2_AamvaCards | [inline]
ScenarioEndReadButton_Click(object sender, RoutedEventArgs e) | Scenario2_AamvaCards | [inline, private]
ScenarioStartReadButton_Click(object sender, RoutedEventArgs e) | Scenario2_AamvaCards | [inline, private]
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cpp/Scenario2.xaml.h Source File

  • FileThumbnails
  • cpp

Scenario2.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2.xaml.h
00014 // Declaration of the Scenario2 class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario2.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     [Windows::Foundation::Metadata::WebHostHidden]
00026     public ref class Scenario2 sealed
00027     {
00028     public:
00029         Scenario2();
00030
00031     protected:
00032         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00033
00034     private:
00035         MainPage^ rootPage;
00036
00037         void GetThumbnailButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038     };
00039 }
Generated on Fri Nov 15 2024 22:18:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Remove Member List

This is the complete list of members for Scenario2_Remove, including all inherited members.
RemoveJumpList_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_Remove
Scenario2_Remove() | Scenario2_Remove
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LinguisticServices/cs/SampleConfiguration.cs Source File

  • LinguisticServices
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Linguistic services C# sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title = "Language Detection", ClassType = typeof(Scenario1_LanguageDetection) },
00025             new Scenario() { Title = "Script Detection", ClassType = typeof(Scenario2_ScriptDetection) },
00026             new Scenario() { Title = "Transliteration", ClassType = typeof(Scenario3_Transliteration) },
00027             new Scenario() { Title = "Character Grouping", ClassType = typeof(Scenario4_CharacterGrouping) },
00028         };
00029     }
00030
00031     public class Scenario
00032     {
00033         public string Title { get; set; }
00034         public Type ClassType { get; set; }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cs/Scenario_SynthesizeTextBoundaries.xaml.cs Source File

  • SpeechRecognitionAndSynthesis
  • cs

Scenario_SynthesizeTextBoundaries.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Linq;
00014 using Windows.ApplicationModel.Resources.Core;
00015 using Windows.Foundation.Collections;
00016 using Windows.Media.Core;
00017 using Windows.Media.Playback;
00018 using Windows.Media.SpeechSynthesis;
00019 using Windows.UI.Core;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022
00023 namespace SDKTemplate
00024 {
00025     public sealed partial class Scenario_SynthesizeTextBoundaries : Page
00026     {
00027         private SpeechSynthesizer synthesizer;
00028         private ResourceContext speechContext;
00029         private ResourceMap speechResourceMap;
00030
00031         public Scenario_SynthesizeTextBoundaries()
00032         {
00033             InitializeComponent();
00034             synthesizer = new SpeechSynthesizer();
00035
00036             speechContext = ResourceContext.GetForCurrentView();
00037             speechContext.Languages = new string[] { SpeechSynthesizer.DefaultVoice.Language };
00038
00039             speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationTTSResources");
00040
00041             MediaPlayer player = new MediaPlayer();
00042             player.AutoPlay = false;
00043             player.MediaEnded += media_MediaEnded;
00044
00045             media.SetMediaPlayer(player);
00046
00047             InitializeListboxVoiceChooser();
00048         }
00049
00050         /// <summary>
00051         /// This is invoked when the user clicks on the speak/stop button.
00052         /// </summary>
00053         /// <param name="sender">Button that triggered this event</param>
00054         /// <param name="e">State information about the routed event</param>
00055         private async void Speak_Click(object sender, RoutedEventArgs e)
00056         {
00057             // If the media is playing, the user has pressed the button to stop the playback.
00058             if (media.MediaPlayer.PlaybackSession.PlaybackState == MediaPlaybackState.Playing)
00059             {
00060                 media.MediaPlayer.Pause();
00061                 btnSpeak.Content = "Speak";
00062             }
00063             else
00064             {
00065                 string text = textToSynthesize.Text;
00066                 if (!String.IsNullOrEmpty(text))
00067                 {
00068                     // Change the button label. You could also just disable the button if you don't want any user control.
00069                     btnSpeak.Content = "Stop";
00070
00071                     try
00072                     {
00073                         // Enable word marker generation (false by default).
00074                         synthesizer.Options.IncludeWordBoundaryMetadata = true;
00075                         synthesizer.Options.IncludeSentenceBoundaryMetadata = true;
00076
00077                         SpeechSynthesisStream synthesisStream = await synthesizer.SynthesizeTextToStreamAsync(text);
00078
00079                         // Create a media source from the stream:
00080                         var mediaSource = MediaSource.CreateFromStream(synthesisStream, synthesisStream.ContentType);
00081
00082                         //Create a Media Playback Item
00083                         var mediaPlaybackItem = new MediaPlaybackItem(mediaSource);
00084
00085                         // Ensure that the app is notified for cues.
00086                         RegisterForWordBoundaryEvents(mediaPlaybackItem);
00087
00088                         // Set the source of the MediaElement or MediaPlayerElement to the MediaPlaybackItem
00089                         // and start playing the synthesized audio stream.
00090                         media.Source = mediaPlaybackItem;
00091                         media.MediaPlayer.Play();
00092                     }
00093                     catch (System.IO.FileNotFoundException)
00094                     {
00095                         // If media player components are unavailable, (eg, using a N SKU of windows), we won't
00096                         // be able to start media playback. Handle this gracefully
00097                         btnSpeak.Content = "Speak";
00098                         btnSpeak.IsEnabled = false;
00099                         textToSynthesize.IsEnabled = false;
00100                         listboxVoiceChooser.IsEnabled = false;
00101                         var messageDialog = new Windows.UI.Popups.MessageDialog("Media player components unavailable");
00102                         await messageDialog.ShowAsync();
00103                     }
00104                     catch (Exception)
00105                     {
00106                         // If the text is unable to be synthesized, throw an error message to the user.
00107                         btnSpeak.Content = "Speak";
00108                         media.AutoPlay = false;
00109                         var messageDialog = new Windows.UI.Popups.MessageDialog("Unable to synthesize text");
00110                         await messageDialog.ShowAsync();
00111                     }
00112                 }
00113             }
00114         }
00115
00116         /// <summary>
00117         /// This is invoked when the stream is finished playing.
00118         /// </summary>
00119         /// <remarks>
00120         /// In this case, we're changing the button label based on the state.
00121         /// </remarks>
00122         /// <param name="sender">unused object parameter</param>
00123         /// <param name="e">unused event parameter</param>
00124         async void media_MediaEnded(MediaPlayer sender, object e)
00125         {
00126             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00127              () =>
00128              {
00129                  // Your UI update code goes here!
00130                  btnSpeak.Content = "Speak";
00131              });
00132         }
00133
00134         /// <summary>
00135         /// This creates items out of the system installed voices. The voices are then displayed in a listbox.
00136         /// This allows the user to change the voice of the synthesizer in your app based on their preference.
00137         /// </summary>
00138         private void InitializeListboxVoiceChooser()
00139         {
00140             // Get all of the installed voices.
00141             var voices = SpeechSynthesizer.AllVoices;
00142
00143             // Get the currently selected voice.
00144             VoiceInformation currentVoice = synthesizer.Voice;
00145
00146             foreach (VoiceInformation voice in voices.OrderBy(p => p.Language))
00147             {
00148                 ComboBoxItem item = new ComboBoxItem();
00149                 item.Name = voice.DisplayName;
00150                 item.Tag = voice;
00151                 item.Content = voice.DisplayName + " (Language: " + voice.Language + ")";
00152                 listboxVoiceChooser.Items.Add(item);
00153
00154                 // Check to see if we're looking at the current voice and set it as selected in the listbox.
00155                 if (currentVoice.Id == voice.Id)
00156                 {
00157                     item.IsSelected = true;
00158                     listboxVoiceChooser.SelectedItem = item;
00159                 }
00160             }
00161         }
00162
00163         /// <summary>
00164         /// This is called when the user has selects a voice from the drop down.
00165         /// </summary>
00166         /// <param name="sender">unused object parameter</param>
00167         /// <param name="e">unused event parameter</param>
00168         private void ListboxVoiceChooser_SelectionChanged(object sender, SelectionChangedEventArgs e)
00169         {
00170             ComboBoxItem item = (ComboBoxItem)(listboxVoiceChooser.SelectedItem);
00171             VoiceInformation voice = (VoiceInformation)(item.Tag);
00172             synthesizer.Voice = voice;
00173
00174             // update UI text to be an appropriate default translation.
00175             speechContext.Languages = new string[] { voice.Language };
00176             textToSynthesize.Text = speechResourceMap.GetValue("SynthesizeTextBoundariesDefaultText", speechContext).ValueAsString;
00177         }
00178
00179         /// <summary>
00180         /// This function executes when a SpeechCue is hit and calls the functions to update the UI
00181         /// </summary>
00182         /// <param name="timedMetadataTrack">The timedMetadataTrack associated with the event.</param>
00183         /// <param name="args">the arguments associated with the event.</param>
00184         private async void metadata_SpeechCueEntered(TimedMetadataTrack timedMetadataTrack, MediaCueEventArgs args)
00185         {
00186             // Check in case there are different tracks and the handler was used for more tracks
00187             if (timedMetadataTrack.TimedMetadataKind == TimedMetadataKind.Speech)
00188             {
00189                 var cue = args.Cue as SpeechCue;
00190                 if (cue != null)
00191                 {
00192                     System.Diagnostics.Debug.WriteLine("Hit Cue with start:" + cue.StartPositionInInput + " and end:" + cue.EndPositionInInput);
00193                     System.Diagnostics.Debug.WriteLine("Cue text:[" + cue.Text + "]");
00194                     // Do something with the cue
00195                     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00196                      () =>
00197                      {
00198                          // Your UI update code goes here!
00199                          HighlightTextOnScreen(cue.StartPositionInInput, cue.EndPositionInInput);
00200                          FillTextBoxes(cue, timedMetadataTrack);
00201                      });
00202                 }
00203             }
00204         }
00205
00206         /// <summary>
00207         /// This function executes when a SpeechCue is hit and calls the functions to update the UI
00208         /// </summary>
00209         /// <param name="timedMetadataTrack">The timedMetadataTrack associated with the event.</param>
00210         /// <param name="cue">the SpeechCue object.</param>
00211         private void FillTextBoxes(SpeechCue cue, TimedMetadataTrack timedMetadataTrack)
00212         {
00213             //if it is a sentence cue, populate the sentence text box.
00214             if(timedMetadataTrack.Id == "SpeechSentence")
00215             {
00216                 textBoxLastSpeechSentence.Text = cue.Text;
00217             }
00218             //if it is a word cue, populate the word text box
00219             if(timedMetadataTrack.Id == "SpeechWord")
00220             {
00221                 textBoxLastSpeechWord.Text = cue.Text;
00222             }
00223         }
00224
00225         /// <summary>
00226         /// This function selects the text associated with the start and end positions.
00227         /// </summary>
00228         /// <param name="startPositionInput"> the starting index of the word </param>
00229         /// <param name="endPositionInInput"> the ending index of the word </param>
00230         private void HighlightTextOnScreen(int? startPositionInInput, int? endPositionInInput)
00231         {
00232             if (startPositionInInput != null && endPositionInInput != null)
00233             {
00234                 textToSynthesize.Select(startPositionInInput.Value, endPositionInInput.Value - startPositionInInput.Value + 1);
00235             }
00236         }
00237
00238         /// <summary>
00239         /// Register for all boundary events and register a function to add any new events if they arise.
00240         /// </summary>
00241         /// <param name="mediaPlaybackItem">The Media PLayback Item add handlers to.</param>
00242         private void RegisterForWordBoundaryEvents(MediaPlaybackItem mediaPlaybackItem)
00243         {
00244             // If tracks were available at source resolution time, itterate through and register:
00245             for (int index = 0; index < mediaPlaybackItem.TimedMetadataTracks.Count; index++)
00246             {
00247                 RegisterMetadataHandlerForWords(mediaPlaybackItem, index);
00248                 RegisterMetadataHandlerForSentences(mediaPlaybackItem, index);
00249             }
00250
00251             // Since the tracks are added later we will
00252             // monitor the tracks being added and subscribe to the ones of interest
00253             mediaPlaybackItem.TimedMetadataTracksChanged += (MediaPlaybackItem sender, IVectorChangedEventArgs args) =>
00254             {
00255                 if (args.CollectionChange == CollectionChange.ItemInserted)
00256                 {
00257                     RegisterMetadataHandlerForWords(sender, (int)args.Index);
00258                     RegisterMetadataHandlerForSentences(mediaPlaybackItem, (int)args.Index);
00259                 }
00260                 else if (args.CollectionChange == CollectionChange.Reset)
00261                 {
00262                     for (int index = 0; index < sender.TimedMetadataTracks.Count; index++)
00263                     {
00264                         RegisterMetadataHandlerForWords(sender, index);
00265                         RegisterMetadataHandlerForSentences(mediaPlaybackItem, index);
00266                     }
00267                 }
00268             };
00269         }
00270
00271         /// <summary>
00272         /// Register for just word boundary events.
00273         /// </summary>
00274         /// <param name="mediaPlaybackItem">The Media Playback Item to register handlers for.</param>
00275         /// <param name="index">Index of the timedMetadataTrack within the mediaPlaybackItem.</param>
00276         private void RegisterMetadataHandlerForWords(MediaPlaybackItem mediaPlaybackItem, int index)
00277         {
00278             var timedTrack = mediaPlaybackItem.TimedMetadataTracks[index];
00279             //register for only word cues
00280             if (timedTrack.Id == "SpeechWord" && checkBoxWordBoundaries.IsChecked.Value)
00281             {
00282                 timedTrack.CueEntered += metadata_SpeechCueEntered;
00283                 mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode((uint)index, TimedMetadataTrackPresentationMode.ApplicationPresented);
00284             }
00285         }
00286
00287         /// <summary>
00288         /// Register for just sentence boundary events.
00289         /// </summary>
00290         /// <param name="mediaPlaybackItem">The Media Playback Item to register handlers for.</param>
00291         /// <param name="index">Index of the timedMetadataTrack within the mediaPlaybackItem.</param>
00292         private void RegisterMetadataHandlerForSentences(MediaPlaybackItem mediaPlaybackItem, int index)
00293         {
00294             var timedTrack = mediaPlaybackItem.TimedMetadataTracks[index];
00295             //register for only sentence cues
00296             if (timedTrack.Id == "SpeechSentence" && checkBoxSentenceBoundaries.IsChecked.Value)
00297             {
00298                 timedTrack.CueEntered += metadata_SpeechCueEntered;
00299                 mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode((uint)index, TimedMetadataTrackPresentationMode.ApplicationPresented);
00300             }
00301         }
00302     }
00303 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ISecureInterfaceService Member List

This is the complete list of members for ISecureInterfaceService, including all inherited members.
ConcatenateAsync(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^info, _In_ Platform::String^interfaceMemberInStr1, _In_ Platform::String^interfaceMemberInStr2) | ISecureInterfaceService
GetIsUpperCaseEnabledAsync(Windows::Devices::AllJoyn::AllJoynMessageInfo^info) | ISecureInterfaceService
SetIsUpperCaseEnabledAsync(Windows::Devices::AllJoyn::AllJoynMessageInfo^info, bool value) | ISecureInterfaceService
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RadioManager/cppwinrt/pch.cpp Source File

  • RadioManager
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlStateTriggers/cs/ViewModel/MainViewModel.cs Source File

  • XamlStateTriggers
  • cs
  • ViewModel

MainViewModel.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Collections.ObjectModel;
00004 using System.Linq;
00005 using System.Text;
00006 using System.Threading.Tasks;
00007
00008 namespace StateTriggersSample.ViewModel
00009 {
00010     public class MainViewModel
00011     {
00012         private ObservableCollection<Model> _items;
00013         public ObservableCollection<Model> Items
00014         {
00015             get
00016             {
00017                 return _items;
00018             }
00019
00020             set
00021             {
00022                 _items = value;
00023             }
00024         }
00025         public MainViewModel()
00026         {
00027             Items = new ObservableCollection<Model>();
00028             Items.Clear();
00029             Items.Add(new Model { Name = "Item1", Description = "First item that is plain and simple", IsColorEnabled = false });
00030             Items.Add(new Model { Name = "Item2", Description = "Second item uses a ViewModel property in a custom trigger for color variation", IsColorEnabled = true });
00031             Items.Add(new Model { Name = "Item3", Description = "Third item without color in ViewModel property, but has a lot of text that increases its size. This larger size driven by the content drives changes to the colors in XAML using a custom ControlSizeTrigger", IsColorEnabled = false });
00032         }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ModelColorConstantBuffer Member List

This is the complete list of members for ModelColorConstantBuffer, including all inherited members.
color | ModelColorConstantBuffer
model | ModelColorConstantBuffer
Generated on Fri Nov 15 2024 22:23:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cpp/pch.h Source File

  • Logging
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cs/ShareWebLink.xaml.cs Source File

  • ShareSource
  • cs

ShareWebLink.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.DataTransfer;
00014
00015 namespace SDKTemplate
00016 {
00017     public sealed partial class ShareWebLink
00018     {
00019         public ShareWebLink()
00020         {
00021             this.InitializeComponent();
00022         }
00023
00024         protected override bool GetShareContent(DataRequest request)
00025         {
00026             bool succeeded = false;
00027
00028             // The URI used in this sample is provided by the user so we need to ensure it's a well formatted absolute URI
00029             // before we try to share it.
00030             rootPage.NotifyUser("", NotifyType.StatusMessage);
00031             Uri dataPackageUri = ValidateAndGetUri(UriToShare.Text);
00032             if (dataPackageUri != null)
00033             {
00034                 DataPackage requestData = request.Data;
00035                 requestData.Properties.Title = TitleInputBox.Text;
00036                 requestData.Properties.Description = DescriptionInputBox.Text; // The description is optional.
00037                 requestData.Properties.ContentSourceApplicationLink = ApplicationLink;
00038                 requestData.SetWebLink(dataPackageUri);
00039                 succeeded = true;
00040             }
00041             else
00042             {
00043                 request.FailWithDisplayText("Enter the web link you would like to share and try again.");
00044             }
00045             return succeeded;
00046         }
00047
00048         private Uri ValidateAndGetUri(string uriString)
00049         {
00050             Uri uri = null;
00051             try
00052             {
00053                 uri = new Uri(uriString);
00054             }
00055             catch (FormatException)
00056             {
00057                 this.rootPage.NotifyUser("The web link provided is not a valid absolute URI.", NotifyType.ErrorMessage);
00058             }
00059             return uri;
00060         }
00061     }
00062 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/Common/CameraResources.cpp Source File

  • HolographicTagAlong
  • cpp
  • Common

CameraResources.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013
00014 #include "CameraResources.h"
00015 #include "Common\DirectXHelper.h"
00016 #include "DeviceResources.h"
00017 #include <windows.graphics.directx.direct3d11.interop.h>
00018
00019 using namespace DirectX;
00020 using namespace Microsoft::WRL;
00021 using namespace Windows::Graphics::DirectX::Direct3D11;
00022 using namespace Windows::Graphics::Holographic;
00023 using namespace Windows::Perception::Spatial;
00024
00025 DX::CameraResources::CameraResources(HolographicCamera^ camera) :
00026     m_holographicCamera(camera),
00027     m_isStereo(camera->IsStereo),
00028     m_d3dRenderTargetSize(camera->RenderTargetSize)
00029 {
00030     m_d3dViewport = CD3D11_VIEWPORT(
00031         0.f, 0.f,
00032         m_d3dRenderTargetSize.Width,
00033         m_d3dRenderTargetSize.Height
00034         );
00035 };
00036
00037 // Updates resources associated with a holographic camera's swap chain.
00038 // The app does not access the swap chain directly, but it does create
00039 // resource views for the back buffer.
00040 void DX::CameraResources::CreateResourcesForBackBuffer(
00041     DX::DeviceResources* pDeviceResources,
00042     HolographicCameraRenderingParameters^ cameraParameters
00043     )
00044 {
00045     const auto device = pDeviceResources->GetD3DDevice();
00046
00047     // Get the WinRT object representing the holographic camera's back buffer.
00048     IDirect3DSurface^ surface = cameraParameters->Direct3D11BackBuffer;
00049
00050     // Get a DXGI interface for the holographic camera's back buffer.
00051     // Holographic cameras do not provide the DXGI swap chain, which is owned
00052     // by the system. The Direct3D back buffer resource is provided using WinRT
00053     // interop APIs.
00054     ComPtr<ID3D11Resource> resource;
00055     ThrowIfFailed(
00056         GetDXGIInterfaceFromObject(surface, IID_PPV_ARGS(&resource))
00057         );
00058
00059     // Get a Direct3D interface for the holographic camera's back buffer.
00060     ComPtr<ID3D11Texture2D> cameraBackBuffer;
00061     ThrowIfFailed(
00062         resource.As(&cameraBackBuffer)
00063         );
00064
00065     // Determine if the back buffer has changed. If so, ensure that the render target view
00066     // is for the current back buffer.
00067     if (m_d3dBackBuffer.Get() != cameraBackBuffer.Get())
00068     {
00069         // This can change every frame as the system moves to the next buffer in the
00070         // swap chain. This mode of operation will occur when certain rendering modes
00071         // are activated.
00072         m_d3dBackBuffer = cameraBackBuffer;
00073
00074         // Create a render target view of the back buffer.
00075         // Creating this resource is inexpensive, and is better than keeping track of
00076         // the back buffers in order to pre-allocate render target views for each one.
00077         DX::ThrowIfFailed(
00078             device->CreateRenderTargetView(
00079                 m_d3dBackBuffer.Get(),
00080                 nullptr,
00081                 &m_d3dRenderTargetView
00082                 )
00083             );
00084
00085         // Get the DXGI format for the back buffer.
00086         // This information can be accessed by the app using CameraResources::GetBackBufferDXGIFormat().
00087         D3D11_TEXTURE2D_DESC backBufferDesc;
00088         m_d3dBackBuffer->GetDesc(&backBufferDesc);
00089         m_dxgiFormat = backBufferDesc.Format;
00090
00091         // Check for render target size changes.
00092         Windows::Foundation::Size currentSize = m_holographicCamera->RenderTargetSize;
00093         if (m_d3dRenderTargetSize != currentSize)
00094         {
00095             // Set render target size.
00096             m_d3dRenderTargetSize = currentSize;
00097
00098             // A new depth stencil view is also needed.
00099             m_d3dDepthStencilView.Reset();
00100         }
00101     }
00102
00103     // Refresh depth stencil resources, if needed.
00104     if (m_d3dDepthStencilView == nullptr)
00105     {
00106         // Create a depth stencil view for use with 3D rendering if needed.
00107         CD3D11_TEXTURE2D_DESC depthStencilDesc(
00108             DXGI_FORMAT_D16_UNORM,
00109             static_cast<UINT>(m_d3dRenderTargetSize.Width),
00110             static_cast<UINT>(m_d3dRenderTargetSize.Height),
00111             m_isStereo ? 2 : 1, // Create two textures when rendering in stereo.
00112             1, // Use a single mipmap level.
00113             D3D11_BIND_DEPTH_STENCIL
00114             );
00115
00116         ComPtr<ID3D11Texture2D> depthStencil;
00117         DX::ThrowIfFailed(
00118             device->CreateTexture2D(
00119                 &depthStencilDesc,
00120                 nullptr,
00121                 &depthStencil
00122                 )
00123             );
00124
00125         CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(
00126             m_isStereo ? D3D11_DSV_DIMENSION_TEXTURE2DARRAY : D3D11_DSV_DIMENSION_TEXTURE2D
00127             );
00128         DX::ThrowIfFailed(
00129             device->CreateDepthStencilView(
00130                 depthStencil.Get(),
00131                 &depthStencilViewDesc,
00132                 &m_d3dDepthStencilView
00133                 )
00134             );
00135     }
00136
00137     // Create the constant buffer, if needed.
00138     if (m_viewProjectionConstantBuffer == nullptr)
00139     {
00140         // Create a constant buffer to store view and projection matrices for the camera.
00141         CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ViewProjectionConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00142         DX::ThrowIfFailed(
00143             device->CreateBuffer(
00144                 &constantBufferDesc,
00145                 nullptr,
00146                 &m_viewProjectionConstantBuffer
00147                 )
00148             );
00149     }
00150 }
00151
00152 // Releases resources associated with a back buffer.
00153 void DX::CameraResources::ReleaseResourcesForBackBuffer(DX::DeviceResources* pDeviceResources)
00154 {
00155     const auto context = pDeviceResources->GetD3DDeviceContext();
00156
00157     // Release camera-specific resources.
00158     m_d3dBackBuffer.Reset();
00159     m_d3dRenderTargetView.Reset();
00160     m_d3dDepthStencilView.Reset();
00161     m_viewProjectionConstantBuffer.Reset();
00162
00163     // Ensure system references to the back buffer are released by clearing the render
00164     // target from the graphics pipeline state, and then flushing the Direct3D context.
00165     ID3D11RenderTargetView* nullViews[D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT] = { nullptr };
00166     context->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00167     context->Flush();
00168 }
00169
00170 // Updates the view/projection constant buffer for a holographic camera.
00171 void DX::CameraResources::UpdateViewProjectionBuffer(
00172     std::shared_ptr<DX::DeviceResources> deviceResources,
00173     HolographicCameraPose^ cameraPose,
00174     SpatialCoordinateSystem^ coordinateSystem
00175     )
00176 {
00177     // The system changes the viewport on a per-frame basis for system optimizations.
00178     m_d3dViewport = CD3D11_VIEWPORT(
00179         cameraPose->Viewport.Left,
00180         cameraPose->Viewport.Top,
00181         cameraPose->Viewport.Width,
00182         cameraPose->Viewport.Height
00183         );
00184
00185     // The projection transform for each frame is provided by the HolographicCameraPose.
00186     HolographicStereoTransform cameraProjectionTransform = cameraPose->ProjectionTransform;
00187
00188     // Get a container object with the view and projection matrices for the given
00189     // pose in the given coordinate system.
00190     Platform::IBox<HolographicStereoTransform>^ viewTransformContainer = cameraPose->TryGetViewTransform(coordinateSystem);
00191
00192     // If TryGetViewTransform returns a null pointer, that means the pose and coordinate
00193     // system cannot be understood relative to one another; content cannot be rendered
00194     // in this coordinate system for the duration of the current frame.
00195     // This usually means that positional tracking is not active for the current frame, in
00196     // which case it is possible to use a SpatialLocatorAttachedFrameOfReference to render
00197     // content that is not world-locked instead.
00198     DX::ViewProjectionConstantBuffer viewProjectionConstantBufferData;
00199     bool viewTransformAcquired = viewTransformContainer != nullptr;
00200     if (viewTransformAcquired)
00201     {
00202         // Otherwise, the set of view transforms can be retrieved.
00203         HolographicStereoTransform viewCoordinateSystemTransform = viewTransformContainer->Value;
00204
00205         // Update the view matrices. Holographic cameras (such as Microsoft HoloLens) are
00206         // constantly moving relative to the world. The view matrices need to be updated
00207         // every frame.
00208         XMStoreFloat4x4(
00209             &viewProjectionConstantBufferData.viewProjection[0],
00210             XMMatrixTranspose(XMLoadFloat4x4(&viewCoordinateSystemTransform.Left) * XMLoadFloat4x4(&cameraProjectionTransform.Left))
00211             );
00212         XMStoreFloat4x4(
00213             &viewProjectionConstantBufferData.viewProjection[1],
00214             XMMatrixTranspose(XMLoadFloat4x4(&viewCoordinateSystemTransform.Right) * XMLoadFloat4x4(&cameraProjectionTransform.Right))
00215             );
00216     }
00217
00218     // Use the D3D device context to update Direct3D device-based resources.
00219     const auto context = deviceResources->GetD3DDeviceContext();
00220
00221     // Loading is asynchronous. Resources must be created before they can be updated.
00222     if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || !viewTransformAcquired)
00223     {
00224         m_framePending = false;
00225     }
00226     else
00227     {
00228         // Update the view and projection matrices.
00229         context->UpdateSubresource(
00230             m_viewProjectionConstantBuffer.Get(),
00231             0,
00232             nullptr,
00233             &viewProjectionConstantBufferData,
00234             0,
00235             0
00236             );
00237
00238         m_framePending = true;
00239     }
00240 }
00241
00242 // Gets the view-projection constant buffer for the HolographicCamera and attaches it
00243 // to the shader pipeline.
00244 bool DX::CameraResources::AttachViewProjectionBuffer(
00245     std::shared_ptr<DX::DeviceResources> deviceResources
00246     )
00247 {
00248     // This method uses Direct3D device-based resources.
00249     const auto context = deviceResources->GetD3DDeviceContext();
00250
00251     // Loading is asynchronous. Resources must be created before they can be updated.
00252     // Cameras can also be added asynchronously, in which case they must be initialized
00253     // before they can be used.
00254     if (context == nullptr || m_viewProjectionConstantBuffer == nullptr || m_framePending == false)
00255     {
00256         return false;
00257     }
00258
00259     // Set the viewport for this camera.
00260     context->RSSetViewports(1, &m_d3dViewport);
00261
00262     // Send the constant buffer to the vertex shader.
00263     context->VSSetConstantBuffers(
00264         1,
00265         1,
00266         m_viewProjectionConstantBuffer.GetAddressOf()
00267         );
00268
00269     m_framePending = false;
00270
00271     return true;
00272 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OCR/cppwinrt/pch.h Source File

  • OCR
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.ApplicationModel.Activation.h"
00005 #include "winrt/Windows.Devices.Enumeration.h"
00006 #include "winrt/Windows.Foundation.h"
00007 #include "winrt/Windows.Foundation.Collections.h"
00008 #include "winrt/Windows.Globalization.h"
00009 #include "winrt/Windows.Graphics.Imaging.h"
00010 #include "winrt/Windows.Graphics.Display.h"
00011 #include "winrt/Windows.Media.h"
00012 #include "winrt/Windows.Media.Capture.h"
00013 #include "winrt/Windows.Media.Devices.h"
00014 #include "winrt/Windows.Media.MediaProperties.h"
00015 #include "winrt/Windows.Media.Ocr.h"
00016 #include "winrt/Windows.UI.Core.h"
00017 #include "winrt/Windows.UI.Xaml.h"
00018 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00019 #include "winrt/Windows.UI.Xaml.Controls.h"
00020 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00021 #include "winrt/Windows.UI.Xaml.Data.h"
00022 #include "winrt/Windows.UI.Xaml.Documents.h"
00023 #include "winrt/Windows.UI.Xaml.Input.h"
00024 #include "winrt/Windows.UI.Xaml.Interop.h"
00025 #include "winrt/Windows.UI.Xaml.Markup.h"
00026 #include "winrt/Windows.UI.Xaml.Media.h"
00027 #include "winrt/Windows.UI.Xaml.Media.Imaging.h"
00028 #include "winrt/Windows.UI.Xaml.Navigation.h"
00029 #include "winrt/Windows.Storage.h"
00030 #include "winrt/Windows.Storage.Pickers.h"
00031 #include "winrt/Windows.System.h"
00032 #include "winrt/Windows.System.Display.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Geotag Member List

This is the complete list of members for Scenario1_Geotag, including all inherited members.
ChooseFileButton_Click() | Scenario1_Geotag | [inline, private]
file | Scenario1_Geotag | [private]
GetGeotagButton_Click() | Scenario1_Geotag | [inline, private]
rootPage | Scenario1_Geotag | [private]
Scenario1_Geotag() | Scenario1_Geotag | [inline]
SetGeotagButton_Click() | Scenario1_Geotag | [inline, private]
SetGeotagFromGeolocatorButton_Click() | Scenario1_Geotag | [inline, private]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PdfDocument/cpp/Scenario1_Render.xaml.h Source File

  • PdfDocument
  • cpp

Scenario1_Render.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Render.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario1_Render sealed
00021     {
00022     public:
00023         Scenario1_Render();
00024
00025         void LoadDocument();
00026         void ViewPage();
00027
00028     private:
00029         MainPage^ rootPage = MainPage::Current;
00030         Windows::Data::Pdf::PdfDocument^ pdfDocument;
00031     };
00032 }
Generated on Fri Nov 15 2024 22:20:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RouteConfig Member List

This is the complete list of members for RouteConfig, including all inherited members.
RegisterRoutes(RouteCollection routes) RouteConfig [inline, static]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FrameSourceGroupModel Member List

This is the complete list of members for FrameSourceGroupModel, including all inherited members.
DisplayName | FrameSourceGroupModel |
FrameSourceGroupModel(MediaFrameSourceGroup group) | FrameSourceGroupModel | [inline]
Id | FrameSourceGroupModel |
SourceGroup | FrameSourceGroupModel |
SourceInfos | FrameSourceGroupModel |
ToString() | FrameSourceGroupModel | [inline]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cpp/pch.cpp Source File

  • FilePicker
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_MIDIDeviceEnumeration Member List

This is the complete list of members for Scenario1_MIDIDeviceEnumeration, including all inherited members.
ClearAllDeviceValues() | Scenario1_MIDIDeviceEnumeration | [inline, private]
DeviceAutoDetectToggle_Toggled(object sender, RoutedEventArgs e) | Scenario1_MIDIDeviceEnumeration | [inline, private]
DisplayDeviceProperties(DeviceInformation devInfo, ListBox propertiesList) | Scenario1_MIDIDeviceEnumeration | [inline, private]
EnumerateMidiInputDevices() | Scenario1_MIDIDeviceEnumeration | [inline, private]
EnumerateMidiOutputDevices() | Scenario1_MIDIDeviceEnumeration | [inline, private]
inputDevices_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario1_MIDIDeviceEnumeration | [inline, private]
listInputDevicesButton_Click(object sender, RoutedEventArgs e) | Scenario1_MIDIDeviceEnumeration | [inline, private]
listOutputDevicesButton_Click(object sender, RoutedEventArgs e) | Scenario1_MIDIDeviceEnumeration | [inline, private]
midiInDeviceWatcher | Scenario1_MIDIDeviceEnumeration | [private]
midiOutDeviceWatcher | Scenario1_MIDIDeviceEnumeration | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_MIDIDeviceEnumeration | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_MIDIDeviceEnumeration | [inline, protected]
outputDevices_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario1_MIDIDeviceEnumeration | [inline, private]
rootPage | Scenario1_MIDIDeviceEnumeration | [private]
Scenario1_MIDIDeviceEnumeration() | Scenario1_MIDIDeviceEnumeration | [inline]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_TriggerCFU Member List

This is the complete list of members for Scenario5_TriggerCFU, including all inherited members.
CreateFileButton_Click(object sender, RoutedEventArgs e) | Scenario5_TriggerCFU | [inline, private]
GetFileFromFutureAccessListButton_Click(Object sender, RoutedEventArgs e) | Scenario5_TriggerCFU | [inline, private]
m_afterWriteFile | Scenario5_TriggerCFU | [private]
m_beforeReadFile | Scenario5_TriggerCFU | [private]
m_faToken | Scenario5_TriggerCFU | [private]
PickAFileButton_Click(Object sender, RoutedEventArgs e) | Scenario5_TriggerCFU | [inline, private]
rootPage | Scenario5_TriggerCFU | [private]
SaveToFutureAccessListButton_Click(Object sender, RoutedEventArgs e) | Scenario5_TriggerCFU | [inline, private]
Scenario5_TriggerCFU() | Scenario5_TriggerCFU | [inline]
UpdateButtons() | Scenario5_TriggerCFU | [inline, private]
WriteToFileButton_Click(Object sender, RoutedEventArgs e) | Scenario5_TriggerCFU | [inline, private]
WriteToFileWithExplicitCFUButton_Click(Object sender, RoutedEventArgs e) | Scenario5_TriggerCFU | [inline, private]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DAdvancedColorImages/cpp/D2DAdvancedColorImages/App.xaml.h Source File

  • D2DAdvancedColorImages
  • cpp
  • D2DAdvancedColorImages

App.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "App.g.h"
00015 #include "DirectXPage.xaml.h"
00016
00017 namespace D2DAdvancedColorImages
00018 {
00019     /// <summary>
00020     /// Provides application-specific behavior to supplement the default Application class.
00021     /// </summary>
00022     ref class App sealed
00023     {
00024     public:
00025         App();
00026         virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override;
00027         virtual void OnFileActivated(Windows::ApplicationModel::Activation::FileActivatedEventArgs^ e) override;
00028
00029     private:
00030         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
00031         void OnResuming(Platform::Object ^sender, Platform::Object ^args);
00032         DirectXPage^ m_directXPage;
00033     };
00034 }
Generated on Fri Nov 15 2024 22:16:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/SampleConfiguration.h Source File

  • ShareSource
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class App
00011     {
00012     protected:
00013         void OnActivated(Windows::ApplicationModel::Activation::IActivatedEventArgs^ args) override;
00014     };
00015
00016     partial ref class MainPage
00017     {
00018     internal:
00019         static property Platform::String^ FEATURE_NAME
00020         {
00021             Platform::String^ get()
00022             {
00023                 return "Share source C++ sample";
00024             }
00025         }
00026
00027         static property Platform::String^ MissingTitleError
00028         {
00029             Platform::String^ get()
00030             {
00031                 return "Enter a title for what you are sharing and try again.";
00032             }
00033         }
00034
00035         static property Platform::Array<Scenario>^ scenarios
00036         {
00037             Platform::Array<Scenario>^ get()
00038             {
00039                 return scenariosInner;
00040             }
00041         }
00042
00043         void LoadScenarioForProtocolActivation(Windows::ApplicationModel::Activation::ProtocolActivatedEventArgs^ args);
00044
00045     private:
00046         static Platform::Array<Scenario>^ scenariosInner;
00047     };
00048
00049     public value struct Scenario
00050     {
00051         Platform::String^ Title;
00052         Platform::String^ ClassName;
00053     };
00054 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cs/BackgroundTransfer/Scenario7_DownloadReordering.xaml.cs Source File

  • BackgroundTransfer
  • cs
  • BackgroundTransfer

Scenario7_DownloadReordering.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Collections.ObjectModel;
00015 using System.ComponentModel;
00016 using System.Globalization;
00017 using System.IO;
00018 using System.Threading;
00019 using System.Threading.Tasks;
00020 using Windows.Networking.BackgroundTransfer;
00021 using Windows.Storage;
00022 using Windows.UI.Core;
00023 using Windows.UI.Xaml;
00024 using Windows.UI.Xaml.Controls;
00025 using Windows.UI.Xaml.Navigation;
00026 using Windows.Web;
00027
00028 namespace SDKTemplate
00029 {
00030     // Class for each download and its row in the UI.
00031     public class DownloadOperationItem : INotifyPropertyChanged
00032     {
00033         public DownloadOperationItem(DownloadOperation download)
00034         {
00035             _download = download;
00036             _percentComplete = 0;
00037             _stateText = "Idle";
00038         }
00039
00040         public event PropertyChangedEventHandler PropertyChanged;
00041
00042         public DownloadOperation download
00043         {
00044             get
00045             {
00046                 return _download;
00047             }
00048         }
00049
00050         public int percentComplete
00051         {
00052             get
00053             {
00054                 return _percentComplete;
00055             }
00056
00057             set
00058             {
00059                 _percentComplete = value;
00060                 if (PropertyChanged != null)
00061                 {
00062                     PropertyChanged(this, new PropertyChangedEventArgs("percentComplete"));
00063                 }
00064             }
00065         }
00066
00067         public string stateText
00068         {
00069             get
00070             {
00071                 return _stateText;
00072             }
00073
00074             set
00075             {
00076                 _stateText = value;
00077                 if (PropertyChanged != null)
00078                 {
00079                     PropertyChanged(this, new PropertyChangedEventArgs("stateText"));
00080                 }
00081             }
00082         }
00083
00084         private DownloadOperation _download;
00085         private int _percentComplete;
00086         private string _stateText;
00087     }
00088
00089     public sealed partial class Scenario7_DownloadReordering : Page
00090     {
00091         private const int NumDownloads = 5;
00092
00093         private MainPage rootPage;
00094         private BackgroundTransferGroup reorderGroup;
00095         public ObservableCollection<DownloadOperationItem> downloadCollection { get; } =
00096             new ObservableCollection<DownloadOperationItem>();
00097
00098         public Scenario7_DownloadReordering()
00099         {
00100             reorderGroup = BackgroundTransferGroup.CreateGroup("{7421B969-18D4-4532-B6BD-22BDABF71C08}");
00101             reorderGroup.TransferBehavior = BackgroundTransferBehavior.Serialized;
00102             this.DataContext = this;
00103             this.InitializeComponent();
00104         }
00105
00106         protected async override void OnNavigatedTo(NavigationEventArgs e)
00107         {
00108             rootPage = MainPage.Current;
00109             await CancelActiveDownloadsAsync();
00110         }
00111
00112         private async Task CancelActiveDownloadsAsync()
00113         {
00114             // Only the downloads that belong to the transfer group used by this sample scenario
00115             // will be canceled.
00116             IReadOnlyList<DownloadOperation> downloads = null;
00117             try
00118             {
00119                 downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(reorderGroup);
00120             }
00121             catch (Exception ex)
00122             {
00123                 if (!IsWebException("Discovery error", ex))
00124                 {
00125                     throw;
00126                 }
00127                 return;
00128             }
00129
00130             // If previous instances of this scenario started transfers that haven't completed yet,
00131             // cancel them now so that we can start this scenario cleanly.
00132             if (downloads.Count > 0)
00133             {
00134                 CancellationTokenSource cancellationToken = new CancellationTokenSource();
00135                 cancellationToken.Cancel();
00136
00137                 Task[] tasks = new Task[downloads.Count];
00138                 for (int i = 0; i < downloads.Count; i++)
00139                 {
00140                     tasks[i] = downloads[i].AttachAsync().AsTask(cancellationToken.Token);
00141                 }
00142
00143                 // Cancel each download and ignore the cancellation exception.
00144                 try
00145                 {
00146                     await Task.WhenAll(tasks);
00147                 }
00148                 catch (TaskCanceledException)
00149                 {
00150                 }
00151             }
00152         }
00153
00154         private async void StartDownload_Click(object sender, RoutedEventArgs e)
00155         {
00156             startDownloadButton.IsEnabled = false;
00157
00158             // Create and start downloads.
00159             await RunDownloadsAsync();
00160
00161             // After all downloads are complete, let the user start new ones again.
00162             startDownloadButton.IsEnabled = true;
00163         }
00164
00165         private void MakeCurrent_Click(object sender, RoutedEventArgs e)
00166         {
00167             Button button = sender as Button;
00168             DownloadOperationItem item = button.DataContext as DownloadOperationItem;
00169
00170             // Make the selected operation current.
00171             item.download.MakeCurrentInTransferGroup();
00172         }
00173
00174         private async Task RunDownloadsAsync()
00175         {
00176             // Create a downloader and associate all its downloads with the transfer group used for
00177             // this scenario.
00178             BackgroundDownloader downloader = new BackgroundDownloader();
00179             downloader.TransferGroup = reorderGroup;
00180
00181             // Validating the URI is required since it was received from an untrusted source (user
00182             // input).
00183             // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings
00184             // that are not valid URIs.
00185             // Note that when enabling the text box users may provide URIs to machines on the
00186             // intranet that require the "Private Networks (Client and Server)" capability.
00187             string remoteAddress = remoteAddressField.Text.Trim();
00188             Uri tmpUri;
00189             if (!Uri.TryCreate(remoteAddress, UriKind.Absolute, out tmpUri))
00190             {
00191                 rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
00192                 return;
00193             }
00194
00195             string fileName = fileNameField.Text.Trim();
00196             if (string.IsNullOrWhiteSpace(fileName))
00197             {
00198                 rootPage.NotifyUser("A local file name is required.", NotifyType.ErrorMessage);
00199                 return;
00200             }
00201
00202             // Try to create some downloads.
00203             DownloadOperation[] downloads = new DownloadOperation[NumDownloads];
00204             try
00205             {
00206                 for (int i = 0; i < NumDownloads; i++)
00207                 {
00208                     string currRemoteAddress = $"{remoteAddress}?id={i}";
00209                     string currFileName = $"{i}.{fileName}";
00210                     downloads[i] = await CreateDownload(downloader, currRemoteAddress, currFileName);
00211                 }
00212             }
00213             catch (FileNotFoundException ex)
00214             {
00215                 rootPage.NotifyUser($"Error while creating file: {ex.Message}", NotifyType.ErrorMessage);
00216                 return;
00217             }
00218
00219             // Once all downloads have been created, start them.
00220             Task[] downloadTasks = new Task[downloads.Length];
00221             downloadCollection.Clear();
00222             for (int i = 0; i < downloads.Length; i++)
00223             {
00224                 DownloadOperationItem item = new DownloadOperationItem(downloads[i]);
00225                 downloadTasks[i] = DownloadAsync(item);
00226                 downloadCollection.Add(item);
00227             }
00228
00229             await Task.WhenAll(downloadTasks);
00230         }
00231
00232         private async Task<DownloadOperation> CreateDownload(
00233             BackgroundDownloader downloader,
00234             string remoteAddress,
00235             string fileName)
00236         {
00237             Uri source = new Uri(remoteAddress);
00238
00239             StorageFile destinationFile;
00240             try
00241             {
00242                 destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
00243                     fileName,
00244                     CreationCollisionOption.GenerateUniqueName);
00245             }
00246             catch (FileNotFoundException ex)
00247             {
00248                 rootPage.NotifyUser($"Error while creating file: {ex.Message}", NotifyType.ErrorMessage);
00249                 throw;
00250             }
00251
00252             return downloader.CreateDownload(source, destinationFile);
00253         }
00254
00255         private async Task DownloadAsync(DownloadOperationItem item)
00256         {
00257             Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(
00258                 (operation) => DownloadProgress(item));
00259
00260             try
00261             {
00262                 await item.download.StartAsync().AsTask(progressCallback);
00263
00264                 item.stateText = item.download.Progress.Status.ToString();
00265                 rootPage.NotifyUser(
00266                     $"Downloading {item.download.ResultFile.Name} completed.",
00267                     NotifyType.StatusMessage);
00268             }
00269             catch (Exception ex)
00270             {
00271                 // Ignore canceled downloads since they are not displayed.
00272                 if (item.download.Progress.Status != BackgroundTransferStatus.Canceled)
00273                 {
00274                     // Ensure that we reach 100% even for errors.
00275                     item.percentComplete = 100;
00276                     item.stateText = item.download.Progress.Status.ToString();
00277                     if (!IsWebException("Execution error", ex, item.download))
00278                     {
00279                         throw;
00280                     }
00281                 }
00282             }
00283         }
00284
00285         private void DownloadProgress(DownloadOperationItem item)
00286         {
00287             BackgroundDownloadProgress currentProgress = item.download.Progress;
00288             BackgroundTransferStatus status = currentProgress.Status;
00289             int percentComplete = 0;
00290
00291             if (currentProgress.TotalBytesToReceive > 0)
00292             {
00293                 percentComplete = (int)((currentProgress.BytesReceived * 100) / currentProgress.TotalBytesToReceive);
00294             }
00295
00296             var ignore = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00297             {
00298                 item.stateText = status.ToString();
00299                 item.percentComplete = percentComplete;
00300             });
00301         }
00302
00303         private bool IsWebException(string title, Exception ex, DownloadOperation download = null)
00304         {
00305             WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
00306             bool result = (error != WebErrorStatus.Unknown);
00307             string message = result ? error.ToString() : ex.Message;
00308
00309             if (download == null)
00310             {
00311                 rootPage.NotifyUser($"{title}: {message}", NotifyType.ErrorMessage);
00312             }
00313             else
00314             {
00315                 rootPage.NotifyUser($"{download.ResultFile.Name} - {title}: {message}", NotifyType.ErrorMessage);
00316             }
00317
00318             return result;
00319         }
00320     }
00321 }
Generated on Fri Nov 15 2024 22:18:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cpp/Scenario1_Create.xaml.cpp Source File

  • Playlists
  • cpp

Scenario1_Create.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario1_Create.xaml.h"
00005 #include <sstream>
00006
00007 using namespace SDKTemplate;
00008
00009 using namespace concurrency;
00010 using namespace Platform;
00011 using namespace Windows::Foundation;
00012 using namespace Windows::Foundation::Collections;
00013 using namespace Windows::Media::Playlists;
00014 using namespace Windows::Storage;
00015 using namespace Windows::Storage::Pickers;
00016 using namespace Windows::UI::Xaml;
00017 using namespace Windows::UI::Xaml::Controls;
00018 using namespace Windows::UI::Xaml::Controls::Primitives;
00019 using namespace Windows::UI::Xaml::Data;
00020 using namespace Windows::UI::Xaml::Input;
00021 using namespace Windows::UI::Xaml::Media;
00022 using namespace Windows::UI::Xaml::Navigation;
00023
00024 Scenario1_Create::Scenario1_Create() : rootPage(MainPage::Current)
00025 {
00026     InitializeComponent();
00027 }
00028
00029 void Scenario1_Create::PickAudioButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00030 {
00031     // Pick multiple files, then create the playlist.
00032     FileOpenPicker^ picker = MainPage::CreateFilePicker(MainPage::audioExtensions);
00033
00034     create_task(picker->PickMultipleFilesAsync()).then([this](IVectorView<StorageFile^>^ files)
00035     {
00036         if (files->Size > 0)
00037         {
00038             Playlist^ playlist = ref new Playlist();
00039
00040             for (StorageFile^ file : files)
00041             {
00042                 playlist->Files->Append(file);
00043             }
00044
00045             StorageFolder^ folder = KnownFolders::MusicLibrary;
00046             String^ name = "Sample";
00047             NameCollisionOption collisionOption = NameCollisionOption::ReplaceExisting;
00048             PlaylistFormat format = PlaylistFormat::WindowsMedia;
00049
00050             create_task(playlist->SaveAsAsync(folder, name, collisionOption, format)).then([this, files](task<StorageFile^> fileTask)
00051             {
00052                 try
00053                 {
00054                     StorageFile^ file = fileTask.get();
00055                     this->rootPage->NotifyUser("The playlist " + file->Name + " was created and saved with " + files->Size.ToString() + " files.", NotifyType::StatusMessage);
00056                 }
00057                 catch (Exception^ ex)
00058                 {
00059                     this->rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00060                 }
00061             });
00062         }
00063         else
00064         {
00065             rootPage->NotifyUser("No files picked.", NotifyType::ErrorMessage);
00066         }
00067     });
00068 }
Generated on Fri Nov 15 2024 22:19:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cpp/pch.cpp Source File

  • XamlCommanding
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/SampleConfiguration.cpp Source File

  • DeviceEnumerationAndPairing
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Device Picker Common Control", "SDKTemplate.Scenario1_DevicePicker" },
00012     { "Enumerate and Watch Devices", "SDKTemplate.Scenario2_DeviceWatcher" },
00013     { "Enumerate and Watch Devices in a Background Task", "SDKTemplate.Scenario3_BackgroundDeviceWatcher" },
00014     { "Enumerate Snapshot of Devices", "SDKTemplate.Scenario4_Snapshot" },
00015     { "Get Single Device", "SDKTemplate.Scenario5_GetSingleDevice" },
00016     { "Custom Filter with Additional Properties", "SDKTemplate.Scenario6_CustomFilterAddedProps" },
00017     { "Request Specific DeviceInformationKind", "SDKTemplate.Scenario7_DeviceInformationKind" },
00018     { "Basic Device Pairing", "SDKTemplate.Scenario8_PairDevice" },
00019     { "Custom Device Pairing", "SDKTemplate.Scenario9_CustomPairDevice" }
00020 };
Generated on Fri Nov 15 2024 22:17:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SdkSample Member List

This is the complete list of members for SdkSample, including all inherited members.
__pad0__ | SdkSample |
_dispatcher | SdkSample | [private]
_rootPage | SdkSample | [private]
ClearLastStatus() | SdkSample |
Deinitialize() | SdkSample |
DisplayError(Platform::String^msg) | SdkSample |
DisplayStatus(Platform::String^msg) | SdkSample |
FormatError(HResult err, Platform::String^msg, Platform::String^prefix) | SdkSample |
FormatError(CaptureFailedEventArgs^e, Platform::String^prefix) | SdkSample |
Log(Platform::String^message) | SdkSample | [private]
Log(Platform::String^message, Platform::String^tag, Platform::String^type) | SdkSample | [private]
Generated on Fri Nov 15 2024 22:24:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampDevice/cpp/SampleConfiguration.cpp Source File

  • LampDevice
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Get Lamp Instance", "SDKTemplate.Scenario1_GetLamp" },
00021     { "Enable Lamp and Settings Adjustment", "SDKTemplate.Scenario2_EnableSettings" },
00022     { "Lamp Device Change Events", "SDKTemplate.Scenario3_AvailabilityChanged" }
00023 };
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaEditing/cpp/Scenario1_TrimAndSaveClip.xaml.cpp Source File

  • MediaEditing
  • cpp

Scenario1_TrimAndSaveClip.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_TrimAndSaveClip.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace concurrency;
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Core;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Media;
00027 using namespace Windows::UI::Xaml::Navigation;
00028 using namespace Windows::Media::Core;
00029 using namespace Windows::Media::Editing;
00030 using namespace Windows::Media::Transcoding;
00031 using namespace Windows::Storage;
00032 using namespace Windows::Storage::Pickers;
00033 using namespace Windows::Storage::Streams;
00034 using namespace Windows::Storage::AccessCache;
00035
00036 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00037
00038 Scenario1_TrimAndSaveClip::Scenario1_TrimAndSaveClip() : rootPage(MainPage::Current)
00039 {
00040     InitializeComponent();
00041 }
00042
00043 void Scenario1_TrimAndSaveClip::OnNavigatedTo(NavigationEventArgs^ e)
00044 {
00045     // Make sure we don't run out of entries in StoreItemAccessList.
00046     // As we don't need to persist this across app sessions/pages, clearing
00047     // every time is sufficient for this sample
00048     storageItemAccessList = StorageApplicationPermissions::FutureAccessList;
00049     storageItemAccessList->Clear();
00050 }
00051
00052 void Scenario1_TrimAndSaveClip::OnNavigatedFrom(NavigationEventArgs^ e)
00053 {
00054     mediaElement->Source = nullptr;
00055     mediaStreamSource = nullptr;
00056 }
00057
00058 void Scenario1_TrimAndSaveClip::ChooseFile_Click(Object^ sender, RoutedEventArgs^ e)
00059 {
00060     // Get file
00061     auto picker = ref new FileOpenPicker();
00062     picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00063     picker->FileTypeFilter->Append(".mp4");
00064
00065     create_task(picker->PickSingleFileAsync()).then([this](StorageFile^ videoFile)
00066     {
00067         if (videoFile == nullptr)
00068         {
00069             rootPage->NotifyUser("File picking cancelled", NotifyType::ErrorMessage);
00070             return;
00071         }
00072
00073         this->pickedFile = videoFile;
00074
00075         // These files could be picked from a location that we won't have access to later
00076         // (especially if persisting the MediaComposition to disk and loading it later).
00077         // Use the StorageItemAccessList in order to keep access permissions to that
00078         // file for later use. Be aware that this access list needs to be cleared
00079         // periodically or the app will run out of entries.
00080         storageItemAccessList->Add(this->pickedFile);
00081
00082         create_task(this->pickedFile->OpenReadAsync()).then([this](IRandomAccessStreamWithContentType^ videoSource)
00083         {
00084             mediaElement->SetSource(videoSource, this->pickedFile->ContentType);
00085             trimClip->IsEnabled = true;
00086         });
00087     });
00088 }
00089
00090 void Scenario1_TrimAndSaveClip::TrimClip_Click(Object^ sender, RoutedEventArgs^ e)
00091 {
00092     create_task(MediaClip::CreateFromFileAsync(this->pickedFile)).then([this](MediaClip^ clip)
00093     {
00094         // Trim the front and back 25% from the clip
00095         TimeSpan trimFromStart;
00096         trimFromStart.Duration = (long long)(clip->OriginalDuration.Duration * 0.25);
00097         clip->TrimTimeFromStart = trimFromStart;
00098         TimeSpan trimFromEnd;
00099         trimFromEnd.Duration = (long long)(clip->OriginalDuration.Duration * 0.25);
00100         clip->TrimTimeFromEnd = trimFromEnd;
00101
00102         // Create a MediaComposition containing the clip and set it on the MediaElement.
00103         composition = ref new MediaComposition();
00104         composition->Clips->Append(clip);
00105         mediaStreamSource = composition->GeneratePreviewMediaStreamSource((int)mediaElement->ActualWidth, (int)mediaElement->ActualHeight);
00106         mediaElement->SetMediaStreamSource(mediaStreamSource);
00107         rootPage->NotifyUser("Clip trimmed", NotifyType::StatusMessage);
00108         save->IsEnabled = true;
00109     });
00110 }
00111
00112 void Scenario1_TrimAndSaveClip::Save_Click(Object^ sender, RoutedEventArgs^ e)
00113 {
00114     EnableButtons(false);
00115     rootPage->NotifyUser("Requesting file to save to", NotifyType::StatusMessage);
00116
00117     auto picker = ref new FileSavePicker();
00118     picker->SuggestedStartLocation = PickerLocationId::VideosLibrary;
00119
00120     auto filter = ref new Platform::Collections::Vector<String^>();
00121     filter->Append(".mp4");
00122     picker->FileTypeChoices->Insert("MP4 files", filter);
00123     picker->SuggestedFileName = "TrimmedClip.mp4";
00124
00125     create_task(picker->PickSaveFileAsync()).then([this](StorageFile^ file)
00126     {
00127         if (file != nullptr)
00128         {
00129             auto saveOperation = composition->RenderToFileAsync(file, MediaTrimmingPreference::Precise);
00130             saveOperation->Progress = ref new AsyncOperationProgressHandler<TranscodeFailureReason, double>([this](
00131                 IAsyncOperationWithProgress<TranscodeFailureReason, double>^ info, double value)
00132             {
00133                 create_task(this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this,info,value]()
00134                 {
00135                     rootPage->NotifyUser("Saving file... Progress: " + value.ToString() + "%", NotifyType::StatusMessage);
00136                 }))).wait();
00137             });
00138
00139             saveOperation->Completed = ref new AsyncOperationWithProgressCompletedHandler<TranscodeFailureReason, double>([this](
00140                 IAsyncOperationWithProgress<TranscodeFailureReason, double>^ info, AsyncStatus status)
00141             {
00142                 create_task(this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, info, status]()
00143                 {
00144                     auto results = info->GetResults();
00145                     if (results != TranscodeFailureReason::None || status != AsyncStatus::Completed)
00146                     {
00147                         rootPage->NotifyUser("Saving was unsuccessful", NotifyType::ErrorMessage);
00148                     }
00149                     else
00150                     {
00151                         rootPage->NotifyUser("Trimmed clip saved to file", NotifyType::StatusMessage);
00152                     }
00153
00154                     EnableButtons(true);
00155                 }))).wait();
00156             });
00157         }
00158         else
00159         {
00160             rootPage->NotifyUser("User cancelled the file selection", NotifyType::StatusMessage);
00161             EnableButtons(true);
00162         }
00163     });
00164 }
00165
00166
00167 void Scenario1_TrimAndSaveClip::EnableButtons(bool isEnabled)
00168 {
00169     chooseFile->IsEnabled = isEnabled;
00170     save->IsEnabled = isEnabled;
00171     trimClip->IsEnabled = isEnabled;
00172 }
Generated on Fri Nov 15 2024 22:20:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Watcher Member List

This is the complete list of members for Scenario1_Watcher, including all inherited members.
App_Resuming(object sender, object e) | Scenario1_Watcher | [inline, private]
App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) | Scenario1_Watcher | [inline, private]
OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs) | Scenario1_Watcher | [inline, private]
OnAdvertisementWatcherStopped(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementWatcherStoppedEventArgs eventArgs) | Scenario1_Watcher | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_Watcher | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario1_Watcher | [inline, protected]
rootPage | Scenario1_Watcher | [private]
RunButton_Click(object sender, RoutedEventArgs e) | Scenario1_Watcher | [inline, private]
Scenario1_Watcher() | Scenario1_Watcher | [inline]
StopButton_Click(object sender, RoutedEventArgs e) | Scenario1_Watcher | [inline, private]
watcher | Scenario1_Watcher | [private]
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HolographicFaceTrackerMain Member List

This is the complete list of members for HolographicFaceTrackerMain, including all inherited members.
HolographicFaceTrackerMain(const std::shared_ptr< DX::DeviceResources > &deviceResources) | HolographicFaceTrackerMain |
IsReadyToRender(void) const | HolographicFaceTrackerMain | [inline]
LoadAppState() | HolographicFaceTrackerMain |
m_cameraAddedToken | HolographicFaceTrackerMain | [private]
m_cameraRemovedToken | HolographicFaceTrackerMain | [private]
m_deviceResources | HolographicFaceTrackerMain | [private]
m_faceTrackerProcessor | HolographicFaceTrackerMain | [private]
m_holographicSpace | HolographicFaceTrackerMain | [private]
m_isReadyToRender | HolographicFaceTrackerMain | [private]
m_locatabilityChangedToken | HolographicFaceTrackerMain | [private]
m_locator | HolographicFaceTrackerMain | [private]
m_previousFrameTimestamp | HolographicFaceTrackerMain | [private]
m_quadRenderer | HolographicFaceTrackerMain | [private]
m_referenceFrame | HolographicFaceTrackerMain | [private]
m_spinningCubeRenderer | HolographicFaceTrackerMain | [private]
m_textRenderer | HolographicFaceTrackerMain | [private]
m_timer | HolographicFaceTrackerMain | [private]
m_trackingFaces | HolographicFaceTrackerMain | [private]
m_videoFrameProcessor | HolographicFaceTrackerMain | [private]
m_videoTexture | HolographicFaceTrackerMain | [private]
OnCameraAdded(Windows::Graphics::Holographic::HolographicSpace^sender, Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs^args) | HolographicFaceTrackerMain | [private]
OnCameraRemoved(Windows::Graphics::Holographic::HolographicSpace^sender, Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs^args) | HolographicFaceTrackerMain | [private]
OnDeviceLost() | HolographicFaceTrackerMain | [virtual]
OnDeviceRestored() | HolographicFaceTrackerMain | [virtual]
OnLocatabilityChanged(Windows::Perception::Spatial::SpatialLocator^sender, Platform::Object^args) | HolographicFaceTrackerMain | [private]
ProcessFaces(std::vector< Windows::Graphics::Imaging::BitmapBounds > const &faces, Windows::Media::Capture::Frames::MediaFrameReference^frame, Windows::Perception::Spatial::SpatialCoordinateSystem^worldCoordSystem) | HolographicFaceTrackerMain | [private]
Render(Windows::Graphics::Holographic::HolographicFrame^holographicFrame) | HolographicFaceTrackerMain |
SaveAppState() | HolographicFaceTrackerMain |
SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^holographicSpace) | HolographicFaceTrackerMain |
UnregisterHolographicEventHandlers() | HolographicFaceTrackerMain | [private]
Update() | HolographicFaceTrackerMain |
~HolographicFaceTrackerMain() | HolographicFaceTrackerMain |
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactCards/cpp/Scenario3_Full.xaml.h Source File

  • ContactCards
  • cpp

Scenario3_Full.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_Full.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario3_Full sealed
00021     {
00022     public:
00023         Scenario3_Full();
00024
00025     private:
00026         MainPage^ rootPage = MainPage::Current;
00027
00028         void ShowContactCard_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029     };
00030 }
Generated on Fri Nov 15 2024 22:18:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario10 Member List

This is the complete list of members for Scenario10, including all inherited members.
AddLayer1() | Scenario10 | [inline, private]
AddLayer2() | Scenario10 | [inline, private]
ColorizeCustomButtonAsync(Windows.UI.Color newColor) | Scenario10 | [inline, private]
CreateLayers() | Scenario10 | [inline, private]
DeleteFileButton_Click(object sender, RoutedEventArgs e) | Scenario10 | [inline, private]
inkToolbar_InkDrawingAttributesChanged(InkToolbar sender, object args) | Scenario10 | [inline, private]
inkToolbar_Loaded(object sender, RoutedEventArgs e) | Scenario10 | [inline, private]
mapElementsLayer1Button_Click(object sender, RoutedEventArgs e) | Scenario10 | [inline, private]
mapElementsLayer2Button_Click(object sender, RoutedEventArgs e) | Scenario10 | [inline, private]
myLayer1 | Scenario10 | [private]
myLayer2 | Scenario10 | [private]
myLayers | Scenario10 | [private]
MyMap_Loaded(object sender, RoutedEventArgs e) | Scenario10 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario10 | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario10 | [inline, protected]
OnSizeChanged(object sender, SizeChangedEventArgs e) | Scenario10 | [inline, private]
rootPage | Scenario10 | [private]
Scenario10() | Scenario10 | [inline]
Scenario10() | Scenario10 | [inline]
Scenario10() | Scenario10 | [inline]
Scenario10() | Scenario10 | [inline]
Scenario10_SearchMultipleResourceIds(ResourceContext context, string[] resourceIds) | Scenario10 | [inline, private]
Scenario10_ShowCandidates(string resourceId, IReadOnlyList< ResourceCandidate > resourceCandidates) | Scenario10 | [inline, private]
Scenario10Button_Show_Click(object sender, RoutedEventArgs e) | Scenario10 | [inline, private]
SelectLayer(MapElementsLayer selectedLayer) | Scenario10 | [inline, private]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RenderBuffer Member List

This is the complete list of members for RenderBuffer, including all inherited members.
Buffer | RenderBuffer |
BufferSize | RenderBuffer |
BytesFilled | RenderBuffer |
RenderBuffer(uint32_t size) | RenderBuffer | [inline]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Content/QuadRenderer.h Source File

  • HolographicFaceTracking
  • cpp
  • Content

QuadRenderer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015 #include "Common\StepTimer.h"
00016 #include "ShaderStructures.h"
00017
00018 namespace HolographicFaceTracker
00019 {
00020     // This sample renderer instantiates a basic rendering pipeline.
00021     class QuadRenderer : public DX::Resource
00022     {
00023     public:
00024         QuadRenderer(std::shared_ptr<DX::DeviceResources> deviceResources);
00025
00026         // DX::Resource Interface
00027         concurrency::task<void> CreateDeviceDependentResourcesAsync() override;
00028         void ReleaseDeviceDependentResources() override;
00029
00030         // Repositions the sample hologram.
00031         void Update(
00032             Windows::UI::Input::Spatial::SpatialPointerPose^ pointerPose,
00033             Windows::Foundation::Numerics::float3 const& offset,
00034             DX::StepTimer const& timer);
00035
00036         // Renders an NV12 image onto the quad, requires two shader resource views for each channel.
00037         void RenderNV12(
00038             ID3D11ShaderResourceView* luminanceTexture,
00039             ID3D11ShaderResourceView* chrominanceTexture);
00040
00041         // Renders an RGB image onto the quad, only requires one texture..
00042         void RenderRGB(
00043             ID3D11ShaderResourceView* rgbTexture);
00044
00045         // Updates the texture coordinates.
00046         void SetTexCoordScaleAndOffset(
00047             Windows::Foundation::Numerics::float2 const& texCoordScale,
00048             Windows::Foundation::Numerics::float2 const& texCoordOffset);
00049
00050         void ResetTexCoordScaleAndOffset(
00051             Windows::Foundation::Numerics::float2 const& texCoordScale = { 1.0f, 1.0f },
00052             Windows::Foundation::Numerics::float2 const& texCoordOffset = { 0.0f, 0.0f });
00053
00054         Windows::Foundation::Numerics::float3 const& GetPosition() const { return m_position; }
00055         Windows::Foundation::Numerics::float3 const& GetVelocity() const { return m_velocity; }
00056         Windows::Foundation::Numerics::float3 const& GetNormal() const   { return m_normal; }
00057
00058     protected:
00059         void RenderInternal(void);
00060
00061     private:
00062         // Direct3D resources for quad geometry.
00063         Microsoft::WRL::ComPtr<ID3D11InputLayout>           m_inputLayout;
00064         Microsoft::WRL::ComPtr<ID3D11Buffer>                m_vertexBuffer;
00065         Microsoft::WRL::ComPtr<ID3D11Buffer>                m_indexBuffer;
00066         Microsoft::WRL::ComPtr<ID3D11VertexShader>          m_vertexShader;
00067         Microsoft::WRL::ComPtr<ID3D11GeometryShader>        m_geometryShader;
00068         Microsoft::WRL::ComPtr<ID3D11PixelShader>           m_pixelShaderRGB;
00069         Microsoft::WRL::ComPtr<ID3D11PixelShader>           m_pixelShaderNV12;
00070         Microsoft::WRL::ComPtr<ID3D11Buffer>                m_modelConstantBuffer;
00071
00072         // Direct3D resources for the default texture.
00073         Microsoft::WRL::ComPtr<ID3D11SamplerState>          m_samplerState;
00074
00075         // System resources for quad geometry.
00076         QuadModelConstantBuffer                             m_modelConstantBufferData;
00077         uint32                                              m_indexCount = 0;
00078
00079         // Variables used with the rendering loop.
00080         float                                               m_degreesPerSecond = 45.f;
00081         Windows::Foundation::Numerics::float3               m_targetPosition = { 0.f, 0.f, -2.f };
00082         Windows::Foundation::Numerics::float3               m_targetUp = { 0.f, 1.f, 0.f };
00083         Windows::Foundation::Numerics::float3               m_targetForward = { 0.f, 0.f, -1.f };
00084         Windows::Foundation::Numerics::float3               m_position = { 0.f, 0.f, -2.f };
00085         Windows::Foundation::Numerics::float3               m_velocity = { 0.f, 0.f, 0.f };
00086         Windows::Foundation::Numerics::float3               m_normal = { 0.f, 0.f, 1.f };
00087
00088         Windows::Foundation::Numerics::float2               m_targetTexCoordScale = { 1.0f, 1.0f };
00089         Windows::Foundation::Numerics::float2               m_targetTexCoordOffset = { 0.0f, 0.0f };
00090         Windows::Foundation::Numerics::float2               m_texCoordScale = { 1.0f, 1.0f };
00091         Windows::Foundation::Numerics::float2               m_texCoordOffset = { 0.0f, 0.0f };
00092
00093         // If the current D3D Device supports VPRT, we can avoid using a geometry
00094         // shader just to set the render target array index.
00095         bool                                                m_usingVprtShaders = false;
00096
00097         // This is the rate at which the hologram position is interpolated (LERPed) to the current location.
00098         const float                                         c_lerpRate = 6.0f;
00099     };
00100 }
Generated on Fri Nov 15 2024 22:18:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SampleState Member List

This is the complete list of members for SampleState, including all inherited members.
activatedToken | SampleState | [private, static]
AddClipboardFormatsOutputString(std::wostringstream &output) | SampleState | [private, static]
AddCustomTitleBar() | SampleState | [static]
AreControlsInTitleBar(bool value) | SampleState | [static]
AreControlsInTitleBar() | SampleState | [inline, static]
areControlsInTitleBar | SampleState | [private, static]
BuildClipboardFormatsOutputString() | SampleState | [static]
clipboardContentChangedToken | SampleState | [private, static]
CurrentApp | SampleState | [static]
customTitleBar | SampleState | [private, static]
DisplayChangedFormats() | SampleState | [private, static]
DisplayToast(hstring const &message) | SampleState | [static]
EnableClipboardContentChangedNotifications(bool enable) | SampleState | [static]
FalToken() | SampleState | [inline, static]
FalToken(hstring value) | SampleState | [inline, static]
falToken | SampleState | [private, static]
fileName | SampleState | [private, static]
FileName() | SampleState | [inline, static]
GetBufferFromString(hstring const &string) | SampleState | [static]
GetStringFromBuffer(Windows::Storage::Streams::IBuffer const &buffer) | SampleState | [static]
HandleClipboardChanged() | SampleState | [private, static]
isApplicationWindowActive | SampleState | [private, static]
IsClipboardContentChangedEnabled() | SampleState | [static]
isClipboardContentChangedEnabled | SampleState | [private, static]
MainDispatcher | SampleState | [static]
MainViewId | SampleState | [static]
MruToken() | SampleState | [inline, static]
MruToken(hstring value) | SampleState | [inline, static]
mruToken | SampleState | [private, static]
needToPrintClipboardFormat | SampleState | [private, static]
NotifyUserFileNotExist() | SampleState | [static]
OnClipboardChanged(Windows::Foundation::IInspectable const &sender, Windows::Foundation::IInspectable const &e) | SampleState | [private, static]
OnWindowActivated(Windows::Foundation::IInspectable const &sender, Windows::UI::Core::WindowActivatedEventArgs const &e) | SampleState | [private, static]
RemoveCustomTitleBar() | SampleState | [static]
SampleFile() | SampleState | [inline, static]
SampleFile(Windows::Storage::StorageFile value) | SampleState | [inline, static]
sampleFile | SampleState | [private, static]
SecondaryViews | SampleState | [static]
SelectedBleDeviceId | SampleState | [static]
SelectedBleDeviceName | SampleState | [static]
UpdateTitle(hstring newTitle, int32_t viewId) | SampleState | [static]
ValidateFile() | SampleState | [static]
Generated on Fri Nov 15 2024 22:24:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAuthenticationBroker/cs/Scenario1_Facebook.xaml.cs Source File

  • WebAuthenticationBroker
  • cs

Scenario1_Facebook.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using System.Threading.Tasks;
00015 using Windows.Data.Json;
00016 using Windows.Foundation;
00017 using Windows.Security.Authentication.Web;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.Web.Http;
00021
00022 namespace WebAuthentication
00023 {
00024     public sealed partial class Scenario1_Facebook : Page
00025     {
00026         private MainPage rootPage = MainPage.Current;
00027         bool authzInProgress = false;
00028
00029         public Scenario1_Facebook()
00030         {
00031             this.InitializeComponent();
00032
00033             // Use these SIDs to register the app with Facebook.
00034             WindowsStoreSidTextBlock.Text = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host;
00035             WindowsPhoneStoreSidTextBlock.Text = "feaebe20-b974-4857-a51c-3525e4dfe2a8"; // copied from Package.appxmanifest
00036         }
00037
00038         private async void Launch_Click(object sender, RoutedEventArgs e)
00039         {
00040             if (authzInProgress)
00041             {
00042                 return;
00043             }
00044
00045             FacebookReturnedToken.Text = "";
00046             FacebookUserName.Text = "";
00047
00048             if (String.IsNullOrEmpty(FacebookClientID.Text))
00049             {
00050                 rootPage.NotifyUser("Please enter a Client ID.", NotifyType.StatusMessage);
00051                 return;
00052             }
00053
00054             Uri callbackUri;
00055             if (!Uri.TryCreate(FacebookCallbackUrl.Text, UriKind.Absolute, out callbackUri))
00056             {
00057                 rootPage.NotifyUser("Please enter a Callback URL.", NotifyType.StatusMessage);
00058                 return;
00059             }
00060
00061             Uri facebookStartUri = new Uri($"https://www.facebook.com/dialog/oauth?client_id={Uri.EscapeDataString(FacebookClientID.Text)}&redirect_uri={Uri.EscapeDataString(callbackUri.AbsoluteUri)}&scope=email&display=popup&response_type=token");
00062
00063             rootPage.NotifyUser($"Navigating to {facebookStartUri}", NotifyType.StatusMessage);
00064
00065             authzInProgress = true;
00066             try
00067             {
00068                 WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, facebookStartUri, callbackUri);
00069                 if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
00070                 {
00071                     FacebookReturnedToken.Text = WebAuthenticationResult.ResponseData;
00072                     await GetFacebookUserNameAsync(WebAuthenticationResult.ResponseData);
00073                 }
00074                 else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
00075                 {
00076                     FacebookReturnedToken.Text = $"HTTP error: {WebAuthenticationResult.ResponseErrorDetail}";
00077                 }
00078                 else
00079                 {
00080                     FacebookReturnedToken.Text = $"Error: {WebAuthenticationResult.ResponseStatus}";
00081                 }
00082
00083             }
00084             catch (Exception Error)
00085             {
00086                 rootPage.NotifyUser(Error.Message, NotifyType.ErrorMessage);
00087             }
00088
00089             authzInProgress = false;
00090         }
00091
00092         /// <summary>
00093         /// This function extracts access_token from the response returned from web authentication broker
00094         /// and uses that token to get user information using facebook graph api.
00095         /// </summary>
00096         /// <param name="responseData">responseData returned from AuthenticateAsync result.</param>
00097         private async Task GetFacebookUserNameAsync(string responseData)
00098         {
00099             var decoder = new WwwFormUrlDecoder(responseData);
00100             var error = decoder.TryGetValue("error");
00101             if (error != null)
00102             {
00103                 FacebookUserName.Text = $"Error: {error}";
00104                 return;
00105             }
00106
00107             // You can store access token locally for further use.
00108             string access_token = decoder.GetFirstValueByName("access_token");
00109             string expires_in = decoder.TryGetValue("expires_in"); // expires_in is optional
00110
00111             HttpClient httpClient = new HttpClient();
00112             Uri uri = new Uri($"https://graph.facebook.com/me?access_token={Uri.EscapeDataString(access_token)}");
00113
00114             HttpGetStringResult result = await httpClient.TryGetStringAsync(uri);
00115             if (result.Succeeded)
00116             {
00117                 JsonObject userInfo = JsonObject.Parse(result.Value).GetObject();
00118                 FacebookUserName.Text = userInfo.GetNamedString("name");
00119             }
00120             else
00121             {
00122                 FacebookUserName.Text = "Error contacting Facebook";
00123             }
00124         }
00125     }
00126 }
Generated on Fri Nov 15 2024 22:21:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCommanding/cpp/Scenario6_Styling.xaml.h Source File

  • XamlCommanding
  • cpp

Scenario6_Styling.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // Scenario6_Styling.xaml.h
00003 // Declaration of the Scenario6_Styling class
00004 //
00005
00006 #pragma once
00007
00008 #include "Scenario6_Styling.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     /// <summary>
00013     /// An empty page that can be used on its own or navigated to within a Frame.
00014     /// </summary>
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class Scenario6_Styling sealed
00017     {
00018     public:
00019         Scenario6_Styling();
00020     };
00021 }
Generated on Fri Nov 15 2024 22:22:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DatagramSocket/cpp/pch.cpp Source File

  • DatagramSocket
  • cpp

pch.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // pch.cpp
00014 // Include the standard header and generate the precompiled header.
00015 //
00016
00017 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cs/AdventureWorks/ViewModel/ViewModelLocator.cs Source File

  • CortanaVoiceCommand
  • cs
  • AdventureWorks
  • ViewModel

ViewModelLocator.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using AdventureWorks.Model;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Linq;
00016 using System.Text;
00017 using System.Threading.Tasks;
00018
00019 namespace AdventureWorks.ViewModel
00020 {
00021     /// <summary>
00022     /// ViewModelLocator ensures that viewmodels can be instantiated with a common reference to the TripStore.
00023     /// This allows for easier decoupling of the store implementation and the view models, and allows for
00024     /// less viewmodel specific code in the views.
00025     /// </summary>
00026     public class ViewModelLocator
00027     {
00028         private Dictionary<string, ViewModelBase> modelSet = new Dictionary<string, ViewModelBase>();
00029
00030         /// <summary>
00031         /// Set up all of the known view models, and instantiate the trip repository.
00032         /// </summary>
00033         public ViewModelLocator()
00034         {
00035             TripStore store = new TripStore();
00036             InitializeStore(store);
00037             modelSet.Add("TripListViewModel", new TripListViewModel(store));
00038             modelSet.Add("TripViewModel", new TripViewModel(store));
00039         }
00040
00041         private async void InitializeStore(TripStore store)
00042         {
00043             await store.LoadTrips();
00044         }
00045
00046         /// <summary>
00047         /// TripList (main page) view model. The TripListView is databound to this property.
00048         /// </summary>
00049         public TripListViewModel TripListViewModel
00050         {
00051             get
00052             {
00053                 return (TripListViewModel)modelSet["TripListViewModel"];
00054             }
00055         }
00056
00057         /// <summary>
00058         /// Trip (detail page) view model. TripDetails page is databound to this property.
00059         /// </summary>
00060         public TripViewModel TripViewModel
00061         {
00062             get
00063             {
00064                 return (TripViewModel)modelSet["TripViewModel"];
00065             }
00066         }
00067     }
00068 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cpp/Scenario6_AppListingURI.xaml.h Source File

  • Store
  • cpp

Scenario6_AppListingURI.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario6_AppListingURI.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class Scenario6_AppListingURI sealed
00022     {
00023     public:
00024         Scenario6_AppListingURI();
00025
00026     protected:
00027         void DisplayLink(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00028
00029     private:
00030         MainPage^ rootPage = MainPage::Current;
00031         Windows::Services::Store::StoreContext^ storeContext;
00032     };
00033 }
Generated on Fri Nov 15 2024 22:21:41 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LoadStateEventArgs Member List

This is the complete list of members for LoadStateEventArgs, including all inherited members.
LoadStateEventArgs(Object navigationParameter, Dictionary< string, Object > pageState) | LoadStateEventArgs | [inline]
NavigationParameter | LoadStateEventArgs |
PageState | LoadStateEventArgs |
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Content/SpinningCubeRenderer.h Source File

  • HolographicVoiceInput
  • cpp
  • Content

SpinningCubeRenderer.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 #include "..\Common\DeviceResources.h"
00014 #include "..\Common\StepTimer.h"
00015 #include "ShaderStructures.h"
00016
00017 namespace HolographicVoiceInput
00018 {
00019     // This sample renderer instantiates a basic rendering pipeline.
00020     class SpinningCubeRenderer
00021     {
00022     public:
00023         SpinningCubeRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00024         void CreateDeviceDependentResources();
00025         void ReleaseDeviceDependentResources();
00026         void Update(const DX::StepTimer& timer);
00027         void Render();
00028
00029         // Repositions the sample hologram.
00030         void PositionHologram(Windows::UI::Input::Spatial::SpatialPointerPose^ pointerPose);
00031
00032         // Property accessors.
00033         void SetPosition(Windows::Foundation::Numerics::float3 pos) { m_position = pos;  }
00034         Windows::Foundation::Numerics::float3 GetPosition()         { return m_position; }
00035
00036         // For speech example.
00037         void SetColor(Windows::Foundation::Numerics::float4 const& color) { m_modelConstantBufferData.color = *reinterpret_cast<DirectX::XMFLOAT4 const*>(&color); }
00038
00039     private:
00040         // Cached pointer to device resources.
00041         std::shared_ptr<DX::DeviceResources>            m_deviceResources;
00042
00043         // Direct3D resources for cube geometry.
00044         Microsoft::WRL::ComPtr<ID3D11InputLayout>       m_inputLayout;
00045         Microsoft::WRL::ComPtr<ID3D11Buffer>            m_vertexBuffer;
00046         Microsoft::WRL::ComPtr<ID3D11Buffer>            m_indexBuffer;
00047         Microsoft::WRL::ComPtr<ID3D11VertexShader>      m_vertexShader;
00048         Microsoft::WRL::ComPtr<ID3D11GeometryShader>    m_geometryShader;
00049         Microsoft::WRL::ComPtr<ID3D11PixelShader>       m_pixelShader;
00050         Microsoft::WRL::ComPtr<ID3D11Buffer>            m_modelConstantBuffer;
00051
00052         // System resources for cube geometry.
00053         ModelColorConstantBuffer                        m_modelConstantBufferData;
00054         uint32                                          m_indexCount = 0;
00055
00056         // Variables used with the rendering loop.
00057         bool                                            m_loadingComplete = false;
00058         float                                           m_degreesPerSecond = 45.f;
00059         Windows::Foundation::Numerics::float3           m_position = { 0.f, 0.f, -2.f };
00060
00061         // If the current D3D Device supports VPRT, we can avoid using a geometry
00062         // shader just to set the render target array index.
00063         bool                                            m_usingVprtShaders = false;
00064     };
00065 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/Scenario_SynthesizeSSML.xaml.cpp Source File

  • SpeechRecognitionAndSynthesis
  • cpp

Scenario_SynthesizeSSML.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario_SynthesizeSSML.xaml.h"
00014 #include <pplawait.h>
00015
00016 using namespace SDKTemplate;
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::ApplicationModel::Resources::Core;
00021 using namespace Windows::Data::Xml::Dom;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::Media::Core;
00025 using namespace Windows::Media::Playback;
00026 using namespace Windows::Media::SpeechSynthesis;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Controls::Primitives;
00030 using namespace Windows::UI::Xaml::Data;
00031 using namespace Windows::UI::Xaml::Input;
00032 using namespace Windows::UI::Xaml::Media;
00033 using namespace Windows::UI::Xaml::Navigation;
00034
00035 Scenario_SynthesizeSSML::Scenario_SynthesizeSSML() : rootPage(MainPage::Current)
00036 {
00037     InitializeComponent();
00038     synthesizer = ref new SpeechSynthesizer();
00039
00040     // initialize localization for SSML text blob
00041     speechContext = ResourceContext::GetForCurrentView();
00042     speechContext->Languages = ref new VectorView<String^>(1, SpeechSynthesizer::DefaultVoice->Language);
00043
00044     speechResourceMap = ResourceManager::Current->MainResourceMap->GetSubtree(L"LocalizationTTSResources");
00045
00046     InitializeListboxVoiceChooser();
00047     UpdateSSMLText();
00048
00049     MediaPlayer^ player = ref new MediaPlayer();
00050     player->AutoPlay = false;
00051     player->MediaEnded += ref new  TypedEventHandler<MediaPlayer^, Object^>(this, &Scenario_SynthesizeSSML::media_MediaEnded);
00052
00053     media->SetMediaPlayer(player);
00054 }
00055
00056 /// <summary>
00057 /// This is invoked when the user clicks on the speak/stop button.
00058 /// </summary>
00059 /// <param name="sender">Button that triggered this event</param>
00060 /// <param name="e">State information about the routed event</param>
00061 void Scenario_SynthesizeSSML::Speak_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00062 {
00063     // If the media is playing, the user has pressed the button to stop the playback.
00064     if (media->MediaPlayer->PlaybackSession->PlaybackState == MediaPlaybackState::Playing)
00065     {
00066         media->MediaPlayer->Pause();
00067         btnSpeak->Content = "Speak";
00068     }
00069     else
00070     {
00071         String^ text = textToSynthesize->Text;
00072         if (!text->IsEmpty())
00073         {
00074             // Change the button label. You could also just disable the button if you don't want any user control.
00075             btnSpeak->Content = "Stop";
00076
00077             // Create a stream from the text. This will be played using a media element.
00078             SynthesizeSSMLStream();
00079         }
00080     }
00081 }
00082
00083 task<void> Scenario_SynthesizeSSML::SynthesizeSSMLStream()
00084 {
00085     String^ text = textToSynthesize->Text;
00086
00087     return create_task(synthesizer->SynthesizeSsmlToStreamAsync(text))
00088         .then([this](task<SpeechSynthesisStream^> previousTask)
00089     {
00090         try
00091         {
00092             synthesisStream = previousTask.get();
00093
00094             // Create a media source from the stream:
00095             MediaSource^ mediaSource = MediaSource::CreateFromStream(synthesisStream, synthesisStream->ContentType);
00096
00097             //Create a Media Playback Item
00098             MediaPlaybackItem^ mediaPlaybackItem = ref new MediaPlaybackItem(mediaSource);
00099
00100             // Ensure that the app is notified for cues.
00101             RegisterForMarkEvents(mediaPlaybackItem);
00102
00103             // Set the source of the MediaElement or MediaPlayerElement to the MediaPlaybackItem
00104             // and start playing the synthesized audio stream.
00105             media->Source = mediaPlaybackItem;
00106             media->MediaPlayer->Play();
00107         }
00108         catch (Exception^ ex)
00109         {
00110             if (ex->HResult == HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND))
00111             {
00112                 btnSpeak->Content = L"Speak";
00113                 btnSpeak->IsEnabled = false;
00114                 listboxVoiceChooser->IsEnabled = false;
00115                 Windows::UI::Popups::MessageDialog^ dialog = ref new Windows::UI::Popups::MessageDialog(ex->Message, "Media playback components unavailable.");
00116                 create_task(dialog->ShowAsync());
00117             }
00118             else
00119             {
00120                 // If the text is not able to be synthesized, throw an error message to the user.
00121                 btnSpeak->Content = L"Speak";
00122                 Windows::UI::Popups::MessageDialog^ dialog = ref new Windows::UI::Popups::MessageDialog(ex->Message, "Unable to synthesize text");
00123                 create_task(dialog->ShowAsync());
00124             }
00125         }
00126     });
00127 }
00128
00129 /// <summary>
00130 /// Register for all mark events
00131 /// </summary>
00132 /// <param name="mediaPlaybackItem">The Media PLayback Item add handlers to.</param>
00133 void Scenario_SynthesizeSSML::RegisterForMarkEvents(Windows::Media::Playback::MediaPlaybackItem^ mediaPlaybackItem)
00134 {
00135     // If tracks were available at source resolution time, itterate through and register:
00136     for (unsigned int index = 0; index < mediaPlaybackItem->TimedMetadataTracks->Size; index++)
00137     {
00138         RegisterMetadataHandlerForMarks(mediaPlaybackItem, index);
00139     }
00140 }
00141
00142 /// <summary>
00143 /// Register for just word bookmark events.
00144 /// </summary>
00145 /// <param name="mediaPlaybackItem">The Media Playback Item to register handlers for.</param>
00146 /// <param name="index">Index of the timedMetadataTrack within the mediaPlaybackItem.</param>
00147 void Scenario_SynthesizeSSML::RegisterMetadataHandlerForMarks(Windows::Media::Playback::MediaPlaybackItem^ mediaPlaybackItem, int index)
00148 {
00149     auto timedTrack = mediaPlaybackItem->TimedMetadataTracks->GetAt(index);
00150     //register for only mark cues
00151     if (timedTrack->Id == "SpeechBookmark" )
00152     {
00153         timedTrack->CueEntered += ref new  TypedEventHandler<TimedMetadataTrack^, MediaCueEventArgs^>(this, &Scenario_SynthesizeSSML::metadata_MarkCueEntered);
00154         mediaPlaybackItem->TimedMetadataTracks->SetPresentationMode(index, TimedMetadataTrackPresentationMode::ApplicationPresented);
00155     }
00156 }
00157
00158 /// <summary>
00159 /// This is called when the user has selects a voice from the drop down.
00160 /// </summary>
00161 /// <param name="sender">unused object parameter</param>
00162 /// <param name="e">unused event parameter</param>
00163 void Scenario_SynthesizeSSML::ListboxVoiceChooser_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
00164 {
00165     if (e->AddedItems->Size > 0)
00166     {
00167         ComboBoxItem^ first = safe_cast<ComboBoxItem^>(e->AddedItems->GetAt(0));
00168         VoiceInformation^ voice = safe_cast<VoiceInformation^>(first->Tag);
00169         synthesizer->Voice = voice;
00170
00171         // update UI text to be an appropriate default translation.
00172         speechContext->Languages = ref new VectorView<String^>(1, { voice->Language });
00173         textToSynthesize->Text = speechResourceMap->GetValue("SynthesizeSSMLDefaultText", speechContext)->ValueAsString;
00174
00175         UpdateSSMLText();
00176
00177     }
00178 }
00179
00180 /// <summary>
00181 /// This is invoked when the stream is finished playing.
00182 /// </summary>
00183 /// <remarks>
00184 /// In this case, we're changing the button label based on the state.
00185 /// </remarks>
00186 /// <param name="sender">unused object parameter</param>
00187 /// <param name="e">unused event parameter</param>
00188 void Scenario_SynthesizeSSML::media_MediaEnded(Windows::Media::Playback::MediaPlayer^ timedMetadataTrack, Platform::Object^ e)
00189 {
00190     // Because this call is not awaited, execution of the current method continues before the call is completed
00191     Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
00192         ref new Windows::UI::Core::DispatchedHandler([this]()
00193     {
00194         btnSpeak->Content = "Speak";
00195     }));
00196 }
00197
00198 /// <summary>
00199 /// This function executes when a SpeechCue is hit and calls the functions to update the UI
00200 /// </summary>
00201 /// <param name="timedMetadataTrack">The timedMetadataTrack associated with the event.</param>
00202 /// <param name="args">the arguments associated with the event.</param>
00203 void Scenario_SynthesizeSSML::metadata_MarkCueEntered(Windows::Media::Core::TimedMetadataTrack^ timedMetadataTrack, Windows::Media::Core::MediaCueEventArgs^ args)
00204 {
00205     // Check in case there are different tracks and the handler was used for more tracks
00206     if (timedMetadataTrack->TimedMetadataKind == TimedMetadataKind::Speech)
00207     {
00208         auto cue = (SpeechCue^)args->Cue;
00209         if (cue != nullptr)
00210         {
00211             wprintf(L"Cue text:[%s]\r\n", cue->Text->Data());
00212
00213             // Do something with the cue
00214             // Because this call is not awaited, execution of the current method continues before the call is completed
00215             Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
00216                 ref new Windows::UI::Core::DispatchedHandler([this, cue, timedMetadataTrack]()
00217             {
00218                 // Your UI update code goes here!
00219                 FillTextBox(cue);
00220             }));
00221         }
00222     }
00223 }
00224
00225 /// <summary>
00226 /// Update the UI with text from the mark
00227 /// </summary>
00228 /// <param name="cue">The cue containing the text</param>
00229 void Scenario_SynthesizeSSML::FillTextBox(SpeechCue^ cue)
00230 {
00231     textBoxLastMarkTriggered->Text = cue->Text;
00232 }
00233
00234 /// <summary>
00235 /// This creates items out of the system installed voices. The voices are then displayed in a listbox.
00236 /// This allows the user to change the voice of the synthesizer in your app based on their preference.
00237 /// </summary>
00238 void Scenario_SynthesizeSSML::InitializeListboxVoiceChooser()
00239 {
00240     // Get all of the installed voices.
00241     IVectorView<VoiceInformation^>^ voices = SpeechSynthesizer::AllVoices;
00242
00243     // Get the currently selected voice.
00244     VoiceInformation^ currentVoice = synthesizer->Voice;
00245
00246     // Copy the read-only voice information IVectorView into a mutable std::vector
00247     std::vector<VoiceInformation^> sortedVoices(voices->Size);
00248     std::copy(begin(voices), end(voices), sortedVoices.begin());
00249
00250     // Sort it based on the language tag (en-US, fr-FR, etc)
00251     std::sort(begin(sortedVoices), end(sortedVoices), [](VoiceInformation^ a, VoiceInformation^ b)
00252     {
00253         return b->Language > a->Language;
00254     });
00255
00256     // Add them to the combo box in order.
00257     std::for_each(begin(sortedVoices), end(sortedVoices), [&](VoiceInformation^ voice)
00258     {
00259         ComboBoxItem^ item = ref new ComboBoxItem();
00260         item->Name = voice->DisplayName;
00261         item->Tag = voice;
00262         item->Content = voice->DisplayName + L" (" + voice->Language + L")";
00263         listboxVoiceChooser->Items->Append(item);
00264
00265         // Check to see if we're looking at the current voice and set it as selected in the listbox.
00266         if (currentVoice->Id == voice->Id)
00267         {
00268             item->IsSelected = true;
00269             listboxVoiceChooser->SelectedItem = item;
00270         }
00271     });
00272 }
00273
00274 /// <summary>
00275 /// Update the text in the SSML field to match the language of the chosen synthesizer voice.
00276 /// </summary>
00277 /// <remarks>
00278 /// SSML language takes priority over the chosen synthesizer language.
00279 /// Thus, when changing voices, we need to update the SSML language to match.
00280 /// </remarks>
00281 void Scenario_SynthesizeSSML::UpdateSSMLText()
00282 {
00283     try
00284     {
00285         String^ text = textToSynthesize->Text;
00286         String^ language = synthesizer->Voice->Language;
00287
00288         XmlDocument^ doc = ref new XmlDocument();
00289         doc->LoadXml(text);
00290
00291         auto LangAttribute = doc->DocumentElement->GetAttributeNode("xml:lang");
00292         LangAttribute->InnerText = language;
00293
00294         textToSynthesize->Text = doc->GetXml();
00295     }
00296     catch (Exception^)
00297     {
00298         // This can fail if the user is in the process of editing the XML.
00299         // In this case, we don't update the SSML language but also don't throw a failure.
00300     }
00301 }
Generated on Fri Nov 15 2024 22:21:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ItemCacheManager< T > Member List

This is the complete list of members for ItemCacheManager< T >, including all inherited members.
AddOrExtendBlock(int index, T value, int insertBeforeBlock) | ItemCacheManager< T > | [inline, private]
cacheBlocks | ItemCacheManager< T > | [private]
CacheChanged | ItemCacheManager< T > |
cachedResults | ItemCacheManager< T > | [private]
cancelTokenSource | ItemCacheManager< T > | [private]
fetchData() | ItemCacheManager< T > | [inline]
fetchDataCallback | ItemCacheManager< T > | [private]
fetchDataCallbackHandler(ItemIndexRange range, CancellationToken ct) | ItemCacheManager< T > |
GetFirstRequestBlock(int maxsize=50) | ItemCacheManager< T > | [inline]
HasRangesChanged(ItemIndexRange[] ranges) | ItemCacheManager< T > | [inline, private]
IndexOf(T value) | ItemCacheManager< T > | [inline]
ItemCacheManager(fetchDataCallbackHandler callback, int batchsize=50, string debugName="ItemCacheManager") | ItemCacheManager< T > | [inline]
maxBatchFetchSize | ItemCacheManager< T > | [private]
NormalizeRanges(ItemIndexRange[] ranges) | ItemCacheManager< T > | [inline, private]
requestInProgress | ItemCacheManager< T > | [private]
requests | ItemCacheManager< T > | [private]
startFetchData() | ItemCacheManager< T > | [inline]
this | ItemCacheManager< T > |
timer | ItemCacheManager< T > | [private]
UpdateRanges(ItemIndexRange[] ranges) | ItemCacheManager< T > | [inline]
Generated on Fri Nov 15 2024 22:23:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Altimeter/cpp/Scenario1_DataEvents.xaml.h Source File

  • Altimeter
  • cpp

Scenario1_DataEvents.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_DataEvents.xaml.h
00014 // Declaration of the Scenario1_DataEvents class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario1_DataEvents.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario1_DataEvents sealed
00030     {
00031     public:
00032         Scenario1_DataEvents();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038     private:
00039         SDKTemplate::MainPage^ rootPage;
00040         Windows::Devices::Sensors::Altimeter^ sensor;
00041         Windows::Foundation::EventRegistrationToken visibilityToken;
00042         Windows::Foundation::EventRegistrationToken readingToken;
00043         uint32 desiredReportIntervalMs;
00044
00045         void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00046         void ReadingChanged(Windows::Devices::Sensors::Altimeter^ sender, Windows::Devices::Sensors::AltimeterReadingChangedEventArgs^ e);
00047         void ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048         void ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049     };
00050 }
Generated on Fri Nov 15 2024 22:17:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Syndication/cpp/Scenario1_GetFeed.xaml.cpp Source File

  • Syndication
  • cpp

Scenario1_GetFeed.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1.xaml.cpp
00014 // Implementation of the Scenario1 class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario1_GetFeed.xaml.h"
00019
00020 using namespace SDKTemplate::Syndication;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::Web::Syndication;
00026 using namespace Windows::Foundation;
00027 using namespace Platform;
00028 using namespace Platform::Collections;
00029 using namespace Concurrency;
00030
00031 Scenario1::Scenario1()
00032 {
00033     currentFeed = nullptr;
00034
00035     InitializeComponent();
00036 }
00037
00038 /// <summary>
00039 /// Invoked when this page is about to be displayed in a Frame.
00040 /// </summary>
00041 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00042 /// property is typically used to configure the page.</param>
00043 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00044 {
00045     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00046     // as NotifyUser()
00047     rootPage = MainPage::Current;
00048 }
00049
00050 void SDKTemplate::Syndication::Scenario1::GetFeed_Click(Object^ sender, RoutedEventArgs^ e)
00051 {
00052     OutputField->Text = "";
00053
00054     // By default 'FeedUri' is disabled and URI validation is not required. When enabling the text box
00055     // validating the URI is required since it was received from an untrusted source (user input).
00056     // The URI is validated by calling TryGetUri() that will return 'false' for strings that are not valid URIs.
00057     // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require the
00058     // "Home or Work Networking" capability.
00059     Uri^ uri;
00060     if (!rootPage->TryGetUri(FeedUri->Text, &uri))
00061     {
00062         return;
00063     }
00064
00065     SyndicationClient^ client = ref new SyndicationClient();
00066     client->BypassCacheOnRetrieve = true;
00067
00068     // Some servers require a user-agent.
00069     client->SetRequestHeader("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
00070
00071     rootPage->NotifyUser("Downloading feed...", NotifyType::StatusMessage);
00072     OutputField->Text = "Downloading feed: " + uri->DisplayUri + "\r\n";
00073
00074     task<SyndicationFeed^>(client->RetrieveFeedAsync(uri)).then([this] (SyndicationFeed^ feed)
00075     {
00076         currentFeed = feed;
00077         rootPage->NotifyUser("Feed download complete.", NotifyType::StatusMessage);
00078
00079         DisplayFeed();
00080     }).then([this] (task<void> t)
00081     {
00082         try
00083         {
00084             t.get();
00085         }
00086         catch (Exception^ exception)
00087         {
00088             rootPage->NotifyUser(exception->Message, NotifyType::ErrorMessage);
00089
00090             // Match HResult with a SyndicationErrorStatus value.
00091             // WebErrorStatus is also available WebErrorStatus for HTTP status error codes.
00092             SyndicationErrorStatus status = SyndicationError::GetStatus(exception->HResult);
00093             if (status == SyndicationErrorStatus::InvalidXml)
00094             {
00095                 OutputField->Text += "An invalid XML exception was thrown. " +
00096                     "Please make sure to use a URI that points to a RSS or Atom feed.";
00097             }
00098         }
00099     });
00100 }
00101
00102 void SDKTemplate::Syndication::Scenario1::DisplayFeed()
00103 {
00104     ISyndicationText^ title = currentFeed->Title;
00105     FeedTitleField->Text = title != nullptr ? title->Text : "(no title)";
00106
00107     currentItemIndex = 0;
00108     if (currentFeed->Items->Size > 0)
00109     {
00110         DisplayCurrentItem();
00111     }
00112
00113     // List the items.
00114     OutputField->Text += "Items: " + currentFeed->Items->Size + "\r\n";
00115 }
00116
00117 void SDKTemplate::Syndication::Scenario1::PreviousItem_Click(Object^ sender, RoutedEventArgs^ e)
00118 {
00119     if (currentFeed != nullptr && currentItemIndex > 0)
00120     {
00121         currentItemIndex--;
00122         DisplayCurrentItem();
00123     }
00124 }
00125
00126 void SDKTemplate::Syndication::Scenario1::NextItem_Click(Object^ sender, RoutedEventArgs^ e)
00127 {
00128     if (currentFeed != nullptr && currentItemIndex < (currentFeed->Items->Size - 1))
00129     {
00130         currentItemIndex++;
00131         DisplayCurrentItem();
00132     }
00133 }
00134
00135 void SDKTemplate::Syndication::Scenario1::DisplayCurrentItem()
00136 {
00137     SyndicationItem^ item = currentFeed->Items->GetAt(currentItemIndex);
00138
00139     // Display item number.
00140     IndexField->Text = (currentItemIndex + 1).ToString() + " of " + currentFeed->Items->Size.ToString();
00141
00142     // Display title.
00143     ItemTitleField->Text = item->Title != nullptr ? item->Title->Text : "(no title)";
00144
00145     // Display the main link.
00146     String^ link = nullptr;
00147     if (item->Links->Size > 0)
00148     {
00149         link = item->Links->GetAt(0)->Uri->AbsoluteUri;
00150     }
00151     LinkField->Content = link;
00152
00153     // Display element extensions. The ElementExtensions collection contains all the additional child elements within
00154     // the current element that do not belong to the Atom or RSS standards (e.g., Dublin Core extension elements).
00155     auto items = ref new Vector<Platform::Object^>();
00156     for (ISyndicationNode^ elementExtension : item->ElementExtensions)
00157     {
00158         auto bindableNode = ref new BindableNode(
00159             elementExtension->NodeName,
00160             elementExtension->NodeNamespace,
00161             elementExtension->NodeValue);
00162         items->Append(bindableNode);
00163     }
00164     ExtensionsField->ItemsSource = items;
00165
00166     // Display the body as HTML.
00167     String^ content = "(no content)";
00168     if (item->Content != nullptr)
00169     {
00170         content = item->Content->Text;
00171     }
00172     else if (item->Summary != nullptr)
00173     {
00174         content = item->Summary->Text;
00175     }
00176     ContentWebView->NavigateToString(content);
00177 }
00178
00179 void SDKTemplate::Syndication::Scenario1::LinkField_Click(Object^ sender, RoutedEventArgs^ e)
00180 {
00181     Windows::System::Launcher::LaunchUriAsync(ref new Uri(((HyperlinkButton^)sender)->Content->ToString()));
00182 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlMasterDetail/cppwinrt/Project.idl Source File

  • XamlMasterDetail
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace MasterDetailApp
00013 {
00014     [default_interface]
00015     runtimeclass MasterDetailPage : Windows.UI.Xaml.Controls.Page
00016     {
00017         MasterDetailPage();
00018
00019         Windows.UI.Xaml.Controls.ListView MasterListView{ get; };
00020     }
00021
00022     runtimeclass DetailPage : Windows.UI.Xaml.Controls.Page
00023     {
00024         DetailPage();
00025
00026         MasterDetailApp.ViewModels.ItemViewModel Item{ get; };
00027
00028         static Windows.UI.Xaml.DependencyProperty ItemProperty{ get; };
00029     }
00030 }
00031
00032 namespace MasterDetailApp.Data
00033 {
00034     runtimeclass Item
00035     {
00036         Item(Int32 itemId, Windows.Foundation.DateTime dateCreated, String title, String text);
00037
00038         Int32 ItemId;
00039         String Title;
00040         String Text;
00041         Windows.Foundation.DateTime DateCreated;
00042     }
00043 }
00044
00045 namespace MasterDetailApp.ViewModels
00046 {
00047     runtimeclass ItemViewModel
00048     {
00049         Int32 ItemId { get; };
00050         String DateCreatedHourMinute{ get; };
00051         String Title{ get; };
00052         String Text{ get; };
00053         Windows.Foundation.DateTime DateCreated{ get; };
00054
00055         static ItemViewModel FromItem(MasterDetailApp.Data.Item item);
00056     }
00057 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/Common/BasicShapes.h Source File

  • Simple3DGameXaml
  • cpp
  • Common

BasicShapes.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include "BasicMath.h"
00011
00012 // Defines the vertex format for the shapes generated in the functions below.
00013 struct BasicVertex
00014 {
00015     float3 pos;  // position
00016     float3 norm; // surface normal vector
00017     float2 tex;  // texture coordinate
00018 };
00019
00020 // Defines the vertex format for all shapes generated in the functions below.
00021 struct TangentVertex
00022 {
00023     float3 pos;  // position
00024     float2 tex;  // texture coordinate
00025     float3 uTan; // texture coordinate u-tangent vector
00026     float3 vTan; // texture coordinate v-tangent vector
00027 };
00028
00029 // A helper class that provides convenient functions for creating common
00030 // geometrical shapes used by DirectX SDK samples.
00031 ref class BasicShapes
00032 {
00033 internal:
00034     BasicShapes(ID3D11Device *d3dDevice);
00035     void CreateCube(
00036         _Out_ ID3D11Buffer **vertexBuffer,
00037         _Out_ ID3D11Buffer **indexBuffer,
00038         _Out_opt_ unsigned int *vertexCount,
00039         _Out_opt_ unsigned int *indexCount
00040         );
00041     void CreateBox(
00042         float3 radii,
00043         _Out_ ID3D11Buffer **vertexBuffer,
00044         _Out_ ID3D11Buffer **indexBuffer,
00045         _Out_opt_ unsigned int *vertexCount,
00046         _Out_opt_ unsigned int *indexCount
00047         );
00048     void CreateSphere(
00049         _Out_ ID3D11Buffer **vertexBuffer,
00050         _Out_ ID3D11Buffer **indexBuffer,
00051         _Out_opt_ unsigned int *vertexCount,
00052         _Out_opt_ unsigned int *indexCount
00053         );
00054     void CreateTangentSphere(
00055         _Out_ ID3D11Buffer **vertexBuffer,
00056         _Out_ ID3D11Buffer **indexBuffer,
00057         _Out_opt_ unsigned int *vertexCount,
00058         _Out_opt_ unsigned int *indexCount
00059         );
00060     void CreateReferenceAxis(
00061         _Out_ ID3D11Buffer **vertexBuffer,
00062         _Out_ ID3D11Buffer **indexBuffer,
00063         _Out_opt_ unsigned int *vertexCount,
00064         _Out_opt_ unsigned int *indexCount
00065         );
00066
00067 private:
00068     Microsoft::WRL::ComPtr<ID3D11Device> m_d3dDevice;
00069
00070     void CreateVertexBuffer(
00071         _In_ unsigned int numVertices,
00072         _In_ BasicVertex *vertexData,
00073         _Out_ ID3D11Buffer **vertexBuffer
00074         );
00075
00076     void CreateIndexBuffer(
00077         _In_ unsigned int numIndices,
00078         _In_ unsigned short *indexData,
00079         _Out_ ID3D11Buffer **indexBuffer
00080         );
00081
00082     void CreateTangentVertexBuffer(
00083         _In_ unsigned int numVertices,
00084         _In_ TangentVertex *vertexData,
00085         _Out_ ID3D11Buffer **vertexBuffer
00086         );
00087
00088 };
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Clipboard/cs/CopyImage.xaml.cs Source File

  • Clipboard
  • cs

CopyImage.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.ApplicationModel.DataTransfer;
00015 using Windows.Graphics.Imaging;
00016 using Windows.Storage;
00017 using Windows.Storage.Pickers;
00018 using Windows.Storage.Streams;
00019 using Windows.UI.Core;
00020 using Windows.UI.Xaml;
00021 using Windows.UI.Xaml.Controls;
00022 using Windows.UI.Xaml.Media.Imaging;
00023
00024 namespace SDKTemplate
00025 {
00026     public sealed partial class CopyImage : Page
00027     {
00028         MainPage rootPage = MainPage.Current;
00029
00030         public CopyImage()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         void CopyButton_Click(object sender, RoutedEventArgs e)
00036         {
00037             this.CopyBitmap(false);
00038         }
00039
00040         void CopyWithDelayedRenderingButton_Click(object sender, RoutedEventArgs e)
00041         {
00042             this.CopyBitmap(true);
00043         }
00044
00045         async void PasteButton_Click(object sender, RoutedEventArgs e)
00046         {
00047             rootPage.NotifyUser("", NotifyType.StatusMessage);
00048
00049             // Get the bitmap and display it.
00050             var dataPackageView = Clipboard.GetContent();
00051             if (dataPackageView.Contains(StandardDataFormats.Bitmap))
00052             {
00053                 IRandomAccessStreamReference imageReceived = null;
00054                 try
00055                 {
00056                     imageReceived = await dataPackageView.GetBitmapAsync();
00057                 }
00058                 catch (Exception ex)
00059                 {
00060                     rootPage.NotifyUser("Error retrieving image from Clipboard: " + ex.Message, NotifyType.ErrorMessage);
00061                 }
00062
00063                 if (imageReceived != null)
00064                 {
00065                     using (var imageStream = await imageReceived.OpenReadAsync())
00066                     {
00067                         var bitmapImage = new BitmapImage();
00068                         bitmapImage.SetSource(imageStream);
00069                         OutputImage.Source = bitmapImage;
00070                         OutputImage.Visibility = Visibility.Visible;
00071                         OutputText.Text = "Image is retrieved from the clipboard and pasted successfully.";
00072                     }
00073                 }
00074             }
00075             else
00076             {
00077                 OutputText.Text = "Bitmap format is not available in clipboard";
00078                 OutputImage.Visibility = Visibility.Collapsed;
00079             }
00080         }
00081
00082         async private static void OnDeferredImageRequestedHandler(DataProviderRequest request, StorageFile imageFile)
00083         {
00084             // Since this method is using "await" prior to setting the data in DataPackage,
00085             // deferral object must be used
00086             var deferral = request.GetDeferral();
00087
00088             // Use try/finally to ensure that we always complete the deferral.
00089             try
00090             {
00091                 using (var imageStream = await imageFile.OpenAsync(FileAccessMode.Read))
00092                 {
00093                     // Decode the image
00094                     var imageDecoder = await BitmapDecoder.CreateAsync(imageStream);
00095
00096                     // Re-encode the image at 50% width and height
00097                     var inMemoryStream = new InMemoryRandomAccessStream();
00098                     var imageEncoder = await BitmapEncoder.CreateForTranscodingAsync(inMemoryStream, imageDecoder);
00099                     imageEncoder.BitmapTransform.ScaledWidth = (uint)(imageDecoder.OrientedPixelWidth * 0.5);
00100                     imageEncoder.BitmapTransform.ScaledHeight = (uint)(imageDecoder.OrientedPixelHeight * 0.5);
00101                     await imageEncoder.FlushAsync();
00102
00103                     request.SetData(RandomAccessStreamReference.CreateFromStream(inMemoryStream));
00104                 }
00105             }
00106             finally
00107             {
00108                 deferral.Complete();
00109             }
00110
00111             MainPage.DisplayToast("Image has been set via deferral.");
00112         }
00113
00114         async private void CopyBitmap(bool isDelayRendered)
00115         {
00116             rootPage.NotifyUser("", NotifyType.StatusMessage);
00117
00118             var imagePicker = new FileOpenPicker
00119             {
00120                 ViewMode = PickerViewMode.Thumbnail,
00121                 SuggestedStartLocation = PickerLocationId.PicturesLibrary,
00122                 FileTypeFilter = { ".jpg", ".png", ".bmp", ".gif", ".tif" }
00123             };
00124
00125             var imageFile = await imagePicker.PickSingleFileAsync();
00126             if (imageFile != null)
00127             {
00128                 var dataPackage = new DataPackage();
00129
00130                 string message;
00131                 if (isDelayRendered)
00132                 {
00133                     dataPackage.SetDataProvider(StandardDataFormats.Bitmap, request => OnDeferredImageRequestedHandler(request, imageFile));
00134                     message = "Image has been copied using delayed rendering";
00135                 }
00136                 else
00137                 {
00138                     dataPackage.SetBitmap(RandomAccessStreamReference.CreateFromFile(imageFile));
00139                     message = "Image has been copied";
00140                 }
00141
00142                 if (Clipboard.SetContentWithOptions(dataPackage, null))
00143                 {
00144                     rootPage.NotifyUser(message, NotifyType.StatusMessage);
00145                 }
00146                 else
00147                 {
00148                     // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
00149                     rootPage.NotifyUser("Error copying content to clipboard.", NotifyType.ErrorMessage);
00150                 }
00151             }
00152         }
00153     }
00154 }
Generated on Fri Nov 15 2024 22:18:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/ShareImage.xaml.h Source File

  • ShareSource
  • cpp

ShareImage.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ShareImage.xaml.h
00014 // Declaration of the ShareImage class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "SharePage.h"
00021 #include "ShareImage.g.h"
00022 #include "MainPage.xaml.h"
00023
00024 namespace SDKTemplate
00025 {
00026     [Windows::Foundation::Metadata::WebHostHidden]
00027     public ref class ShareImage sealed
00028     {
00029     public:
00030         ShareImage();
00031
00032     protected:
00033         virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request) override;
00034
00035     private:
00036         Windows::Storage::StorageFile^ imageFile;
00037
00038         void SelectImageButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039     };
00040 }
Generated on Fri Nov 15 2024 22:21:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomFocusVisuals Member List

This is the complete list of members for CustomFocusVisuals, including all inherited members.
CustomFocusVisuals() | CustomFocusVisuals | [inline]
OnNavigatedTo(NavigationEventArgs e) | CustomFocusVisuals | [inline, protected]
rootPage | CustomFocusVisuals | [private]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cs/Scenario9.xaml.cs Source File

  • MapControl
  • cs

Scenario9.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Foundation.Metadata;
00014 using Windows.UI.Core;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Controls.Maps;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// Shows how to customize the look and feel of the map
00023     /// </summary>
00024     public sealed partial class Scenario9 : Page
00025     {
00026         public Scenario9()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         private void MyMap_Loaded(object sender, RoutedEventArgs e)
00032         {
00033             myMap.Center = MainPage.SeattleGeopoint;
00034             myMap.ZoomLevel = 12;
00035             SetMapStyleSheet();
00036         }
00037
00038         private void SetDefaultStyleCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
00039         {
00040             // Protect against events that are raised before we are fully initialized.
00041             if (myMap != null)
00042             {
00043                 SetMapStyleSheet();
00044             }
00045         }
00046
00047         private void SetMapStyleSheet()
00048         {
00049             switch (setDefaultStyleCombobox.SelectedIndex)
00050             {
00051                 case 0:
00052                     myMap.StyleSheet = MapStyleSheet.Aerial();
00053                     break;
00054                 case 1:
00055                     myMap.StyleSheet = MapStyleSheet.AerialWithOverlay();
00056                     break;
00057                 case 2:
00058                     myMap.StyleSheet = MapStyleSheet.RoadDark();
00059                     break;
00060                 case 3:
00061                     myMap.StyleSheet = MapStyleSheet.RoadLight();
00062                     break;
00063                 case 4:
00064                     myMap.StyleSheet = MapStyleSheet.RoadHighContrastDark();
00065                     break;
00066                 case 5:
00067                     myMap.StyleSheet = MapStyleSheet.RoadHighContrastLight();
00068                     break;
00069                 case 6:
00070                     myMap.StyleSheet = MapStyleSheet.ParseFromJson(@"
00071                         {
00072                             ""version"": ""1.0"",
00073                             ""settings"": {
00074                                 ""landColor"": ""#FFFFFF"",
00075                                 ""spaceColor"": ""#000000""
00076                             },
00077                             ""elements"": {
00078                                 ""mapElement"": {
00079                                     ""labelColor"": ""#000000"",
00080                                     ""labelOutlineColor"": ""#FFFFFF""
00081                                 },
00082                                 ""water"": {
00083                                     ""fillColor"": ""#DDDDDD""
00084                                 },
00085                                 ""area"": {
00086                                     ""fillColor"": ""#EEEEEE""
00087                                 },
00088                                 ""political"": {
00089                                     ""borderStrokeColor"": ""#CCCCCC"",
00090                                     ""borderOutlineColor"": ""#00000000""
00091                                 }
00092                             }
00093                         }
00094                     ");
00095                     break;
00096             }
00097         }
00098     }
00099 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cppwinrt/SymbologyListEntry.h Source File

  • BarcodeScanner
  • cppwinrt

SymbologyListEntry.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "SymbologyListEntry.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct SymbologyListEntry : SymbologyListEntryT<SymbologyListEntry>
00019     {
00020         SymbologyListEntry(uint32_t symbologyId, bool symbologyEnabled = true) :
00021             m_id(symbologyId),
00022             m_enabled(symbologyEnabled)
00023         {
00024         }
00025
00026         uint32_t Id()
00027         {
00028             return m_id;
00029         }
00030
00031         bool IsEnabled()
00032         {
00033             return m_enabled;
00034         }
00035
00036         void IsEnabled(bool enabled)
00037         {
00038             m_enabled = enabled;
00039         }
00040
00041         winrt::hstring Name()
00042         {
00043             return winrt::Windows::Devices::PointOfService::BarcodeSymbologies::GetName(m_id);
00044         }
00045
00046     private:
00047         uint32_t m_id;
00048         bool m_enabled;
00049     };
00050 }
00051
00052 namespace winrt::SDKTemplate::factory_implementation
00053 {
00054     struct SymbologyListEntry : SymbologyListEntryT<SymbologyListEntry, implementation::SymbologyListEntry>
00055     {
00056     };
00057 }
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario01 Member List

This is the complete list of members for Scenario01, including all inherited members.
OnNavigatedTo(NavigationEventArgs e) | Scenario01 | [inline, protected]
Player_CurrentStateChanged(object sender, RoutedEventArgs e) | Scenario01 | [inline, private]
Player_MediaFailed(object sender, ExceptionRoutedEventArgs e) | Scenario01 | [inline, private]
Player_MediaOpened(object sender, RoutedEventArgs e) | Scenario01 | [inline, private]
rootPage | Scenario01 | [private]
Scenario01() | Scenario01 | [inline]
video | Scenario01 | [private]
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cpp/Scenario6_TimeZone.xaml.h Source File

  • DateTimeFormatting
  • cpp

Scenario6_TimeZone.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario6_TimeZone.g.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario6_TimeZone sealed
00021     {
00022     public:
00023         Scenario6_TimeZone();
00024         void Display();
00025     };
00026 }
Generated on Fri Nov 15 2024 22:19:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/ShareText.xaml.cpp Source File

  • ShareSource
  • cpp

ShareText.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ShareText.xaml.cpp
00014 // Implementation of the ShareText class
00015 //
00016
00017 #include "pch.h"
00018 #include "ShareText.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Windows::ApplicationModel::DataTransfer;
00024
00025 ShareText::ShareText()
00026 {
00027     InitializeComponent();
00028 }
00029
00030 bool ShareText::GetShareContent(DataRequest^ request)
00031 {
00032     bool succeeded = false;
00033
00034     auto dataPackageText = TextToShare->Text;
00035     if (dataPackageText != nullptr)
00036     {
00037         auto requestData = request->Data;
00038         requestData->Properties->Title = TitleInputBox->Text;
00039         requestData->Properties->Description = DescriptionInputBox->Text; // The description is optional.
00040         requestData->Properties->ContentSourceApplicationLink = ApplicationLink;
00041         requestData->SetText(dataPackageText);
00042         succeeded = true;
00043     }
00044     else
00045     {
00046         request->FailWithDisplayText("Enter the text you would like to share and try again.");
00047     }
00048     return succeeded;
00049 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ServicingCompleteTask Member List

This is the complete list of members for ServicingCompleteTask, including all inherited members.
AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task) | ServicingCompleteTask | [inline, private]
AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task) | ServicingCompleteTask | [inline, private]
OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) | ServicingCompleteTask | [inline, private]
OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) | ServicingCompleteTask | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | ServicingCompleteTask | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | ServicingCompleteTask | [inline, protected]
OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args) | ServicingCompleteTask | [inline, private]
OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args) | ServicingCompleteTask | [inline, private]
RegisterBackgroundTask(object sender, RoutedEventArgs e) | ServicingCompleteTask | [inline, private]
RegisterBackgroundTask(object sender, RoutedEventArgs e) | ServicingCompleteTask | [inline, private]
rootPage | ServicingCompleteTask | [private]
ServicingCompleteTask() | ServicingCompleteTask | [inline]
ServicingCompleteTask() | ServicingCompleteTask | [inline]
UnregisterBackgroundTask(object sender, RoutedEventArgs e) | ServicingCompleteTask | [inline, private]
UnregisterBackgroundTask(object sender, RoutedEventArgs e) | ServicingCompleteTask | [inline, private]
UpdateUI() | ServicingCompleteTask | [inline, private]
UpdateUI() | ServicingCompleteTask | [inline, private]
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/StspSchemeHandler.cpp Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

StspSchemeHandler.cpp

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include <InitGuid.h>
00010 #include "StspSchemeHandler.h"
00011 #include "StspMediaSource.h"
00012 #include <wrl/module.h>
00013
00014 using namespace Microsoft::Samples::SimpleCommunication;
00015 using namespace Microsoft::Samples::SimpleCommunication::Network;
00016
00017 ActivatableClass(CSchemeHandler);
00018
00019 CSchemeHandler::CSchemeHandler(void)
00020 {
00021 }
00022
00023 CSchemeHandler::~CSchemeHandler(void)
00024 {
00025 }
00026
00027 // IMediaExtension methods
00028 IFACEMETHODIMP CSchemeHandler::SetProperties (ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration)
00029 {
00030     return S_OK;
00031 }
00032
00033 // IMFSchemeHandler methods
00034 IFACEMETHODIMP CSchemeHandler::BeginCreateObject(
00035         _In_ LPCWSTR pwszURL,
00036         _In_ DWORD dwFlags,
00037         _In_ IPropertyStore *pProps,
00038         _COM_Outptr_opt_  IUnknown **ppIUnknownCancelCookie,
00039         _In_ IMFAsyncCallback *pCallback,
00040         _In_ IUnknown *punkState)
00041 {
00042     HRESULT hr = S_OK;
00043     ComPtr<CMediaSource> spSource;
00044
00045     try
00046     {
00047         if (ppIUnknownCancelCookie != nullptr)
00048         {
00049             *ppIUnknownCancelCookie = nullptr;
00050         }
00051
00052         if (pwszURL == nullptr || pCallback == nullptr)
00053         {
00054             Throw(E_INVALIDARG);
00055         }
00056
00057         if ((dwFlags & MF_RESOLUTION_MEDIASOURCE) == 0)
00058         {
00059             Throw(E_INVALIDARG);
00060         }
00061
00062         ComPtr<IMFAsyncResult> spResult;
00063         ThrowIfError(CMediaSource::CreateInstance(&spSource));
00064
00065         ComPtr<IUnknown> spSourceUnk;
00066         ThrowIfError(spSource.As(&spSourceUnk));
00067         ThrowIfError(MFCreateAsyncResult(spSourceUnk.Get(), pCallback, punkState, &spResult));
00068
00069         ComPtr<CSchemeHandler> spThis = this;
00070         spSource->OpenAsync(pwszURL).then([this, spThis, spResult, spSource](concurrency::task<void>& openTask)
00071         {
00072             try
00073             {
00074                 if (spResult == nullptr)
00075                 {
00076                     ThrowIfError(MF_E_UNEXPECTED);
00077                 }
00078
00079                 openTask.get();
00080             }
00081             catch(Exception ^exc)
00082             {
00083                 if (spResult != nullptr)
00084                 {
00085                     spResult->SetStatus(exc->HResult);
00086                 }
00087             }
00088
00089             if (spResult != nullptr)
00090             {
00091                 MFInvokeCallback(spResult.Get());
00092             }
00093         });
00094     }
00095     catch(Exception ^exc)
00096     {
00097         if (spSource != nullptr)
00098         {
00099             spSource->Shutdown();
00100         }
00101         hr = exc->HResult;
00102     }
00103
00104     TRACEHR_RET(hr);
00105 }
00106
00107 IFACEMETHODIMP CSchemeHandler::EndCreateObject(
00108         _In_ IMFAsyncResult *pResult,
00109         _Out_  MF_OBJECT_TYPE *pObjectType,
00110         _Out_  IUnknown **ppObject)
00111 {
00112     if (pResult == nullptr || pObjectType == nullptr || ppObject == nullptr)
00113     {
00114         return E_INVALIDARG;
00115     }
00116
00117     HRESULT hr = pResult->GetStatus();
00118     *pObjectType = MF_OBJECT_INVALID;
00119     *ppObject = nullptr;
00120
00121     if (SUCCEEDED(hr))
00122     {
00123         ComPtr<IUnknown> punkSource;
00124         hr = pResult->GetObject(&punkSource);
00125         if (SUCCEEDED(hr))
00126         {
00127             *pObjectType = MF_OBJECT_MEDIASOURCE;
00128             *ppObject = punkSource.Detach();
00129         }
00130     }
00131
00132     TRACEHR_RET(hr);
00133 }
00134
00135 IFACEMETHODIMP CSchemeHandler::CancelObjectCreation(
00136             _In_ IUnknown *pIUnknownCancelCookie)
00137 {
00138     return E_NOTIMPL;
00139 }
Generated on Fri Nov 15 2024 22:21:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_StartDragAsync Member List

This is the complete list of members for Scenario3_StartDragAsync, including all inherited members.
_dragOperation | Scenario3_StartDragAsync | [private]
_isActive | Scenario3_StartDragAsync | [private]
_rnd | Scenario3_StartDragAsync | [private]
_symbol | Scenario3_StartDragAsync | [private]
_symbols | Scenario3_StartDragAsync | [private]
_timer | Scenario3_StartDragAsync | [private]
DragCompleted(IAsyncOperation< DataPackageOperation > asyncInfo, AsyncStatus asyncStatus) | Scenario3_StartDragAsync | [inline, private]
DropBorder_DragEnter(object sender, Windows.UI.Xaml.DragEventArgs e) | Scenario3_StartDragAsync | [inline, private]
DropBorder_Drop(object sender, Windows.UI.Xaml.DragEventArgs e) | Scenario3_StartDragAsync | [inline, private]
EndRound(bool hasWon) | Scenario3_StartDragAsync | [inline, private]
IsSymbolTargetBorder(object sender) | Scenario3_StartDragAsync | [inline, private]
OnTick(object sender, object args) | Scenario3_StartDragAsync | [inline, private]
Scenario3_StartDragAsync() | Scenario3_StartDragAsync | [inline]
Scenario3_StartDragAsync_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3_StartDragAsync | [inline, private]
SourceTextBlock_DragStarting(Windows.UI.Xaml.UIElement sender, Windows.UI.Xaml.DragStartingEventArgs e) | Scenario3_StartDragAsync | [inline, private]
SourceTextBlock_PointerMoved(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e) | Scenario3_StartDragAsync | [inline, private]
StartButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario3_StartDragAsync | [inline, private]
Generated on Fri Nov 15 2024 22:23:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DAdvancedColorImages/cpp/D2DAdvancedColorImages/DeviceResources.h Source File

  • D2DAdvancedColorImages
  • cpp
  • D2DAdvancedColorImages

DeviceResources.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace DX
00015 {
00016     // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created.
00017     interface IDeviceNotify
00018     {
00019         virtual void OnDeviceLost() = 0;
00020         virtual void OnDeviceRestored() = 0;
00021     };
00022
00023     // Controls all the DirectX device resources.
00024     class DeviceResources
00025     {
00026     public:
00027         DeviceResources();
00028         void SetSwapChainPanel(Windows::UI::Xaml::Controls::SwapChainPanel^ panel);
00029         void SetLogicalSize(Windows::Foundation::Size logicalSize);
00030         void SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation);
00031         void SetDpi(float dpi);
00032         void SetCompositionScale(float compositionScaleX, float compositionScaleY);
00033         void ValidateDevice();
00034         void HandleDeviceLost();
00035         void RegisterDeviceNotify(IDeviceNotify* deviceNotify);
00036         void Trim();
00037         void Present();
00038
00039         // Device Accessors.
00040         Windows::Foundation::Size   GetOutputSize() const                   { return m_outputSize; }
00041         Windows::Foundation::Size   GetLogicalSize() const                  { return m_logicalSize; }
00042         float                       GetDpi() const                          { return m_dpi; }
00043
00044         // D3D Accessors.
00045         ID3D11Device2*              GetD3DDevice() const                    { return m_d3dDevice.Get(); }
00046         ID3D11DeviceContext3*       GetD3DDeviceContext() const             { return m_d3dContext.Get(); }
00047         IDXGISwapChain3*            GetSwapChain() const                    { return m_swapChain.Get(); }
00048         D3D_FEATURE_LEVEL           GetDeviceFeatureLevel() const           { return m_d3dFeatureLevel; }
00049         ID3D11RenderTargetView*     GetBackBufferRenderTargetView() const   { return m_d3dRenderTargetView.Get(); }
00050         ID3D11DepthStencilView*     GetDepthStencilView() const             { return m_d3dDepthStencilView.Get(); }
00051         D3D11_VIEWPORT              GetScreenViewport() const               { return m_screenViewport; }
00052         DirectX::XMFLOAT4X4         GetOrientationTransform3D() const       { return m_orientationTransform3D; }
00053
00054         // D2D Accessors.
00055         ID2D1Factory6*              GetD2DFactory() const                   { return m_d2dFactory.Get(); }
00056         ID2D1Device5*               GetD2DDevice() const                    { return m_d2dDevice.Get(); }
00057         ID2D1DeviceContext5*        GetD2DDeviceContext() const             { return m_d2dContext.Get(); }
00058         ID2D1Bitmap1*               GetD2DTargetBitmap() const              { return m_d2dTargetBitmap.Get(); }
00059         IDWriteFactory2*            GetDWriteFactory() const                { return m_dwriteFactory.Get(); }
00060         IWICImagingFactory2*        GetWicImagingFactory() const            { return m_wicFactory.Get(); }
00061         D2D1::Matrix3x2F            GetOrientationTransform2D() const       { return m_orientationTransform2D; }
00062
00063     private:
00064         void CreateDeviceIndependentResources();
00065         void CreateDeviceResources();
00066         void CreateWindowSizeDependentResources();
00067         DXGI_MODE_ROTATION ComputeDisplayRotation();
00068
00069         // Direct3D objects.
00070         Microsoft::WRL::ComPtr<ID3D11Device2>           m_d3dDevice;
00071         Microsoft::WRL::ComPtr<ID3D11DeviceContext3>    m_d3dContext;
00072         Microsoft::WRL::ComPtr<IDXGIFactory2>           m_dxgiFactory;
00073         Microsoft::WRL::ComPtr<IDXGISwapChain3>         m_swapChain;
00074
00075         // Direct3D rendering objects. Required for 3D.
00076         Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00077         Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00078         D3D11_VIEWPORT                                  m_screenViewport;
00079
00080         // Direct2D drawing components.
00081         Microsoft::WRL::ComPtr<ID2D1Factory6>           m_d2dFactory;
00082         Microsoft::WRL::ComPtr<ID2D1Device5>            m_d2dDevice;
00083         Microsoft::WRL::ComPtr<ID2D1DeviceContext5>     m_d2dContext;
00084         Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
00085
00086         // DirectWrite drawing components.
00087         Microsoft::WRL::ComPtr<IDWriteFactory2>         m_dwriteFactory;
00088         Microsoft::WRL::ComPtr<IWICImagingFactory2>     m_wicFactory;
00089
00090         // Cached reference to the XAML panel.
00091         Windows::UI::Xaml::Controls::SwapChainPanel^    m_swapChainPanel;
00092
00093         // Cached device properties.
00094         D3D_FEATURE_LEVEL                               m_d3dFeatureLevel;
00095         Windows::Foundation::Size                       m_d3dRenderTargetSize;
00096         Windows::Foundation::Size                       m_outputSize;
00097         Windows::Foundation::Size                       m_logicalSize;
00098         Windows::Graphics::Display::DisplayOrientations m_nativeOrientation;
00099         Windows::Graphics::Display::DisplayOrientations m_currentOrientation;
00100         float                                           m_dpi;
00101         float                                           m_compositionScaleX;
00102         float                                           m_compositionScaleY;
00103
00104
00105         // Transforms used for display orientation.
00106         D2D1::Matrix3x2F                                m_orientationTransform2D;
00107         DirectX::XMFLOAT4X4                             m_orientationTransform3D;
00108
00109         // The IDeviceNotify can be held directly as it owns the DeviceResources.
00110         IDeviceNotify*                                  m_deviceNotify;
00111     };
00112 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothLE/cppwinrt/SampleConfiguration.cpp Source File

  • BluetoothLE
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace SDKTemplate;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022
00023 hstring implementation::MainPage::FEATURE_NAME()
00024 {
00025     return L"BluetoothLE C++/WinRT Sample";
00026 }
00027
00028 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00029 {
00030     Scenario{ L"Client: Discover servers", xaml_typename<SDKTemplate::Scenario1_Discovery>() },
00031     Scenario{ L"Client: Connect to a server", xaml_typename<SDKTemplate::Scenario2_Client>() },
00032     Scenario{ L"Server: Publish foreground", xaml_typename<SDKTemplate::Scenario3_ServerForeground>() },
00033 });
00034
00035 hstring SampleState::SelectedBleDeviceId;
00036 hstring SampleState::SelectedBleDeviceName{ L"No device selected" };
00037
00038 Rect winrt::SDKTemplate::GetElementRect(FrameworkElement const& element)
00039 {
00040     auto transform = element.TransformToVisual(nullptr);
00041     Point point = transform.TransformPoint({});
00042     return { point, { static_cast<float>(element.ActualWidth()), static_cast<float>(element.ActualHeight()) } };
00043 }
Generated on Fri Nov 15 2024 22:17:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MediaReader Member List

This is the complete list of members for MediaReader, including all inherited members.
GetOutputWaveFormatEx() | MediaReader |
LoadMedia(_In_ winrt::hstring const &filename) | MediaReader |
m_installedLocationPath | MediaReader | [private]
m_waveFormat | MediaReader | [private]
MediaReader() | MediaReader |
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6_AppListingURI Member List

This is the complete list of members for Scenario6_AppListingURI, including all inherited members.
DisplayLink() | Scenario6_AppListingURI | [inline, private]
rootPage | Scenario6_AppListingURI | [private]
Scenario6_AppListingURI() | Scenario6_AppListingURI | [inline]
storeContext | Scenario6_AppListingURI | [private]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/HolographicMRCSampleMain.h Source File

  • HolographicMixedRealityCapture
  • cpp

HolographicMRCSampleMain.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 //
00004 // Comment out this preprocessor definition to disable all of the
00005 // sample content.
00006 //
00007 // To remove the content after disabling it:
00008 //     * Remove the unused code from your app's Main class.
00009 //     * Delete the Content folder provided with this template.
00010 //
00011 #define DRAW_SAMPLE_CONTENT
00012
00013 #include "Common\DeviceResources.h"
00014 #include "Common\StepTimer.h"
00015
00016 #ifdef DRAW_SAMPLE_CONTENT
00017 #include "Content\SpinningCubeRenderer.h"
00018 #include "Content\Panel.h"
00019 #include "Content\Button.h"
00020 #include "Content\Cursor.h"
00021 #include "Content\SpatialInputHandler.h"
00022
00023 #include "MediaCaptureManager.h"
00024 #endif
00025
00026 // Updates, renders, and presents holographic content using Direct3D.
00027 namespace HolographicMRCSample
00028 {
00029     class HolographicMRCSampleMain : public DX::IDeviceNotify
00030     {
00031     public:
00032         HolographicMRCSampleMain(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00033         ~HolographicMRCSampleMain();
00034
00035         // Sets the holographic space. This is our closest analogue to setting a new window
00036         // for the app.
00037         void SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^ holographicSpace);
00038
00039         // Starts the holographic frame and updates the content.
00040         Windows::Graphics::Holographic::HolographicFrame^ Update();
00041
00042         // Renders holograms, including world-locked content.
00043         bool Render(Windows::Graphics::Holographic::HolographicFrame^ holographicFrame);
00044
00045         // Handle saving and loading of app state owned by AppMain.
00046         void SaveAppState();
00047         void LoadAppState();
00048
00049         // IDeviceNotify
00050         virtual void OnDeviceLost();
00051         virtual void OnDeviceRestored();
00052
00053     private:
00054         // Asynchronously creates resources for new holographic cameras.
00055         void OnCameraAdded(
00056             Windows::Graphics::Holographic::HolographicSpace^ sender,
00057             Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs^ args);
00058
00059         // Synchronously releases resources for holographic cameras that are no longer
00060         // attached to the system.
00061         void OnCameraRemoved(
00062             Windows::Graphics::Holographic::HolographicSpace^ sender,
00063             Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs^ args);
00064
00065         // Used to notify the app when the positional tracking state changes.
00066         void OnLocatabilityChanged(
00067             Windows::Perception::Spatial::SpatialLocator^ sender,
00068             Platform::Object^ args);
00069
00070         // Clears event registration state. Used when changing to a new HolographicSpace
00071         // and when tearing down AppMain.
00072         void UnregisterHolographicEventHandlers();
00073
00074         void OnButtonInitTapped();
00075         void OnButtonVideoTapped();
00076         void OnButtonPhotoTapped();
00077         void OnButtonHologramTapped();
00078         void OnButtonSysAudioTapped();
00079
00080         void DisableAllButtons();
00081
00082 #ifdef DRAW_SAMPLE_CONTENT
00083         // Renders a colorful holographic cube that's 20 centimeters wide. This sample content
00084         // is used to demonstrate world-locked rendering.
00085         std::unique_ptr<SpinningCubeRenderer>                           m_cube1;
00086         std::unique_ptr<SpinningCubeRenderer>                           m_cube2;
00087         std::unique_ptr<SpinningCubeRenderer>                           m_cube3;
00088         std::unique_ptr<SpinningCubeRenderer>                           m_cube4;
00089
00090         std::unique_ptr<Panel>                                          m_mainPanel;
00091         std::shared_ptr<Button>                                         m_lockButton;
00092         std::shared_ptr<Button>                                         m_initButton;
00093         std::shared_ptr<Button>                                         m_photoButton;
00094         std::shared_ptr<Button>                                         m_videoButton;
00095         std::shared_ptr<Button>                                         m_hologramButton;
00096         std::shared_ptr<Button>                                         m_sysAudioButton;
00097
00098         std::unique_ptr<Cursor>                                         m_cursor;
00099
00100         // Listens for the Pressed spatial input event.
00101         std::shared_ptr<SpatialInputHandler>                            m_spatialInputHandler;
00102 #endif
00103
00104         // Cached pointer to device resources.
00105         std::shared_ptr<DX::DeviceResources>                            m_deviceResources;
00106
00107         // Render loop timer.
00108         DX::StepTimer                                                   m_timer;
00109
00110         // Represents the holographic space around the user.
00111         Windows::Graphics::Holographic::HolographicSpace^               m_holographicSpace;
00112
00113         // SpatialLocator that is attached to the primary camera.
00114         Windows::Perception::Spatial::SpatialLocator^                   m_locator;
00115
00116         // A reference frame attached to the holographic camera.
00117         Windows::Perception::Spatial::SpatialStationaryFrameOfReference^ m_referenceFrame;
00118
00119         // Event registration tokens.
00120         Windows::Foundation::EventRegistrationToken                     m_cameraAddedToken;
00121         Windows::Foundation::EventRegistrationToken                     m_cameraRemovedToken;
00122         Windows::Foundation::EventRegistrationToken                     m_locatabilityChangedToken;
00123
00124         // Mixed Reality Capture
00125         std::unique_ptr<MediaCaptureManager>                            m_mediaCapture;
00126         bool                                                            m_recording;
00127     };
00128 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundMediaPlayback/cs/DataModels/VideoItem.cs Source File

  • BackgroundMediaPlayback
  • cs
  • DataModels

VideoItem.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using Windows.Data.Json;
00007 using Windows.Media;
00008 using Windows.Media.Playback;
00009
00010 namespace BackgroundMediaPlayback.DataModels
00011 {
00012     class VideoItem : MediaItem
00013     {
00014         public Uri VideoPreviewImageUri { get; set; }
00015
00016         public override Uri PreviewImageUri
00017         {
00018             get
00019             {
00020                 return VideoPreviewImageUri;
00021             }
00022
00023             set
00024             {
00025                 VideoPreviewImageUri = value;
00026             }
00027         }
00028
00029         public VideoItem()
00030         {
00031         }
00032
00033         public VideoItem(JsonObject json) : base(json)
00034         {
00035             if (json.Keys.Contains("videoPreviewImageUri"))
00036                 VideoPreviewImageUri = new Uri(json.GetNamedString("videoPreviewImageUri"));
00037         }
00038
00039         public override MediaPlaybackItem ToPlaybackItem()
00040         {
00041             var playbackItem = base.ToPlaybackItem();
00042
00043             var displayProperties = playbackItem.GetDisplayProperties();
00044             displayProperties.Type = MediaPlaybackType.Video;
00045             displayProperties.VideoProperties.Title = Title;
00046             playbackItem.ApplyDisplayProperties(displayProperties);
00047
00048             return playbackItem;
00049         }
00050     }
00051 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MPEUserControl Member List

This is the complete list of members for MPEUserControl, including all inherited members.
Control_Loaded(object sender, RoutedEventArgs e) | MPEUserControl | [inline, private]
Control_Unloaded(object sender, RoutedEventArgs e) | MPEUserControl | [inline, private]
FrameStepBackward_Click(object sender, RoutedEventArgs e) | MPEUserControl | [inline, private]
FrameStepForward_Click(object sender, RoutedEventArgs e) | MPEUserControl | [inline, private]
MPE | MPEUserControl | [private]
MPEUserControl() | MPEUserControl | [inline]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: EnterpriseDataProtection/cs/Scenario6_ProtectBuffer.xaml.cs Source File

  • EnterpriseDataProtection
  • cs

Scenario6_ProtectBuffer.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Storage;
00014 using Windows.Storage.Streams;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018 using Windows.Security.EnterpriseData;
00019 using Windows.Security.Cryptography;
00020 using SDKTemplate;
00021
00022
00023 namespace EdpSample
00024 {
00025     public sealed partial class Scenario6 : Page
00026     {
00027         private MainPage rootPage;
00028         private string m_protectedMessage = "Hello World";
00029         IBuffer m_protectedBuffer = null;
00030         IBuffer m_unprotectedBuffer = null;
00031
00032         private string m_protectBufferScenario = "An app has retrieved sensitive data from a document that belongs to an enterprise. When " +
00033                                                "transferring this data within and outside the device, the app must ensure that there are no data " +
00034                                                "leaks. In order to do so, it protects the data to the enterprise identity it belongs to. This allows " +
00035                                                "wiping the data when required by the enterprise.";
00036
00037         private string m_statusBufferScenario = "\n\nAn app has previously protected a buffer that it must prevent unauthorized access to. " +
00038                                                "In order to retrieve its contents back when needed, it can check the status of the buffer. " +
00039                                                "Alternatively, if the app is denied access to the buffer when unprotecting it, it can " +
00040                                                "check the status of the buffer.";
00041
00042         public Scenario6()
00043         {
00044             this.InitializeComponent();
00045         }
00046
00047         protected override void OnNavigatedTo(NavigationEventArgs e)
00048         {
00049             ScenarioTxtBlk.Text = m_protectBufferScenario + m_statusBufferScenario;
00050             rootPage = MainPage.Current;
00051         }
00052
00053         private async void UnprotectAsyncBuffer_Click(object sender, RoutedEventArgs e)
00054         {
00055             string outputStr = "";
00056             string plainMessage = "";
00057
00058             if (m_protectedBuffer != null)
00059             {
00060                 BufferProtectUnprotectResult unBuffer = await DataProtectionManager.UnprotectAsync(m_protectedBuffer);
00061                 m_unprotectedBuffer = unBuffer.Buffer;
00062                 plainMessage = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8,
00063                                                                             m_unprotectedBuffer
00064                                                                             );
00065                 outputStr += "\n Status: " + unBuffer.ProtectionInfo.Status;
00066                 outputStr += "\n Unprotected string:" + plainMessage;
00067                 rootPage.NotifyUser(outputStr, NotifyType.StatusMessage);
00068             }
00069             else
00070             {
00071                 rootPage.NotifyUser("Please protect a buffer to unprotect", NotifyType.ErrorMessage);
00072             }
00073         }
00074
00075         private async void GetBuffersStatus_Click(object sender, RoutedEventArgs e)
00076         {
00077             string outputStr = "";
00078
00079             if (m_protectedBuffer != null)
00080             {
00081                 DataProtectionInfo procStatus = await DataProtectionManager.GetProtectionInfoAsync(m_protectedBuffer);
00082                 outputStr += "\n protection status: " + procStatus.Status;
00083                 rootPage.NotifyUser(outputStr, NotifyType.StatusMessage);
00084             }
00085             else
00086             {
00087                 outputStr += "\n Buffer is null because Protect API did not run successfully";
00088                 rootPage.NotifyUser(outputStr, NotifyType.ErrorMessage);
00089             }
00090         }
00091
00092         private async void ProtectAsyncBuffer_Click(object sender, RoutedEventArgs e)
00093         {
00094             string outputStr = "\n Protecting string:" + m_protectedMessage;
00095             IBuffer inputBuffer = CryptographicBuffer.ConvertStringToBinary(m_protectedMessage,
00096                                                                             BinaryStringEncoding.Utf8);
00097             BufferProtectUnprotectResult procBuffer = await DataProtectionManager.ProtectAsync(inputBuffer, Scenario1.m_enterpriseId);
00098             m_protectedBuffer = procBuffer.Buffer;
00099             outputStr += "\n Status: " + procBuffer.ProtectionInfo.Status;
00100             outputStr += "\n Protected string:";
00101             outputStr += CryptographicBuffer.EncodeToHexString(m_protectedBuffer).Substring(0, 20);
00102             rootPage.NotifyUser(outputStr, NotifyType.StatusMessage);
00103         }
00104     }
00105 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Common/DeviceResources.cpp Source File

  • HolographicVoiceInput
  • cpp
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
00012 #include "DeviceResources.h"
00013 #include "DirectXHelper.h"
00014
00015 #include <Collection.h>
00016 #include <windows.graphics.directx.direct3d11.interop.h>
00017
00018 using namespace D2D1;
00019 using namespace Microsoft::WRL;
00020 using namespace Windows::Graphics::DirectX::Direct3D11;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::Graphics::Holographic;
00023
00024 // Constructor for DeviceResources.
00025 DX::DeviceResources::DeviceResources()
00026 {
00027     CreateDeviceIndependentResources();
00028 }
00029
00030 // Configures resources that don't depend on the Direct3D device.
00031 void DX::DeviceResources::CreateDeviceIndependentResources()
00032 {
00033     // Initialize Direct2D resources.
00034     D2D1_FACTORY_OPTIONS options {};
00035
00036 #if defined(_DEBUG)
00037     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00038     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00039 #endif
00040
00041     // Initialize the Direct2D Factory.
00042     DX::ThrowIfFailed(
00043         D2D1CreateFactory(
00044             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00045             __uuidof(ID2D1Factory2),
00046             &options,
00047             &m_d2dFactory
00048             )
00049         );
00050
00051     // Initialize the DirectWrite Factory.
00052     DX::ThrowIfFailed(
00053         DWriteCreateFactory(
00054             DWRITE_FACTORY_TYPE_SHARED,
00055             __uuidof(IDWriteFactory2),
00056             &m_dwriteFactory
00057             )
00058         );
00059
00060     // Initialize the Windows Imaging Component (WIC) Factory.
00061     DX::ThrowIfFailed(
00062         CoCreateInstance(
00063             CLSID_WICImagingFactory2,
00064             nullptr,
00065             CLSCTX_INPROC_SERVER,
00066             IID_PPV_ARGS(&m_wicFactory)
00067             )
00068         );
00069 }
00070
00071 void DX::DeviceResources::SetHolographicSpace(HolographicSpace^ holographicSpace)
00072 {
00073     // Cache the holographic space. Used to re-initalize during device-lost scenarios.
00074     m_holographicSpace = holographicSpace;
00075
00076     InitializeUsingHolographicSpace();
00077 }
00078
00079 void DX::DeviceResources::InitializeUsingHolographicSpace()
00080 {
00081     // The holographic space might need to determine which adapter supports
00082     // holograms, in which case it will specify a non-zero PrimaryAdapterId.
00083     LUID id =
00084     {
00085         m_holographicSpace->PrimaryAdapterId.LowPart,
00086         m_holographicSpace->PrimaryAdapterId.HighPart
00087     };
00088
00089     // When a primary adapter ID is given to the app, the app should find
00090     // the corresponding DXGI adapter and use it to create Direct3D devices
00091     // and device contexts. Otherwise, there is no restriction on the DXGI
00092     // adapter the app can use.
00093     if ((id.HighPart != 0) && (id.LowPart != 0))
00094     {
00095         UINT createFlags = 0;
00096 #ifdef DEBUG
00097         if (DX::SdkLayersAvailable())
00098         {
00099             createFlags |= DXGI_CREATE_FACTORY_DEBUG;
00100         }
00101 #endif
00102         // Create the DXGI factory.
00103         ComPtr<IDXGIFactory1> dxgiFactory;
00104         DX::ThrowIfFailed(
00105             CreateDXGIFactory2(
00106                 createFlags,
00107                 IID_PPV_ARGS(&dxgiFactory)
00108                 )
00109             );
00110         ComPtr<IDXGIFactory4> dxgiFactory4;
00111         DX::ThrowIfFailed(dxgiFactory.As(&dxgiFactory4));
00112
00113         // Retrieve the adapter specified by the holographic space.
00114         DX::ThrowIfFailed(
00115             dxgiFactory4->EnumAdapterByLuid(
00116                 id,
00117                 IID_PPV_ARGS(&m_dxgiAdapter)
00118                 )
00119             );
00120     }
00121     else
00122     {
00123         m_dxgiAdapter.Reset();
00124     }
00125
00126     CreateDeviceResources();
00127
00128     m_holographicSpace->SetDirect3D11Device(m_d3dInteropDevice);
00129 }
00130
00131 // Configures the Direct3D device, and stores handles to it and the device context.
00132 void DX::DeviceResources::CreateDeviceResources()
00133 {
00134     // This flag adds support for surfaces with a different color channel ordering
00135     // than the API default. It is required for compatibility with Direct2D.
00136     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00137
00138 #if defined(_DEBUG)
00139     if (DX::SdkLayersAvailable())
00140     {
00141         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00142         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00143     }
00144 #endif
00145
00146     // This array defines the set of DirectX hardware feature levels this app will support.
00147     // Note the ordering should be preserved.
00148     // Note that HoloLens supports feature level 11.1. The HoloLens emulator is also capable
00149     // of running on graphics cards starting with feature level 10.0.
00150     D3D_FEATURE_LEVEL featureLevels [] =
00151     {
00152         D3D_FEATURE_LEVEL_12_1,
00153         D3D_FEATURE_LEVEL_12_0,
00154         D3D_FEATURE_LEVEL_11_1,
00155         D3D_FEATURE_LEVEL_11_0,
00156         D3D_FEATURE_LEVEL_10_1,
00157         D3D_FEATURE_LEVEL_10_0
00158     };
00159
00160     // Create the Direct3D 11 API device object and a corresponding context.
00161     ComPtr<ID3D11Device> device;
00162     ComPtr<ID3D11DeviceContext> context;
00163
00164     const HRESULT hr = D3D11CreateDevice(
00165         m_dxgiAdapter.Get(),        // Either nullptr, or the primary adapter determined by Windows Holographic.
00166         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00167         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00168         creationFlags,              // Set debug and Direct2D compatibility flags.
00169         featureLevels,              // List of feature levels this app can support.
00170         ARRAYSIZE(featureLevels),   // Size of the list above.
00171         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00172         &device,                    // Returns the Direct3D device created.
00173         &m_d3dFeatureLevel,         // Returns feature level of device created.
00174         &context                    // Returns the device immediate context.
00175         );
00176
00177     if (FAILED(hr))
00178     {
00179         // If the initialization fails, fall back to the WARP device.
00180         // For more information on WARP, see:
00181         // http://go.microsoft.com/fwlink/?LinkId=286690
00182         DX::ThrowIfFailed(
00183             D3D11CreateDevice(
00184                 nullptr,              // Use the default DXGI adapter for WARP.
00185                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00186                 0,
00187                 creationFlags,
00188                 featureLevels,
00189                 ARRAYSIZE(featureLevels),
00190                 D3D11_SDK_VERSION,
00191                 &device,
00192                 &m_d3dFeatureLevel,
00193                 &context
00194                 )
00195             );
00196     }
00197
00198     // Store pointers to the Direct3D device and immediate context.
00199     DX::ThrowIfFailed(
00200         device.As(&m_d3dDevice)
00201         );
00202
00203     DX::ThrowIfFailed(
00204         context.As(&m_d3dContext)
00205         );
00206
00207     // Acquire the DXGI interface for the Direct3D device.
00208     ComPtr<IDXGIDevice3> dxgiDevice;
00209     DX::ThrowIfFailed(
00210         m_d3dDevice.As(&dxgiDevice)
00211         );
00212
00213     // Wrap the native device using a WinRT interop object.
00214     m_d3dInteropDevice = CreateDirect3DDevice(dxgiDevice.Get());
00215
00216     // Cache the DXGI adapter.
00217     // This is for the case of no preferred DXGI adapter, or fallback to WARP.
00218     ComPtr<IDXGIAdapter> dxgiAdapter;
00219     DX::ThrowIfFailed(
00220         dxgiDevice->GetAdapter(&dxgiAdapter)
00221         );
00222     DX::ThrowIfFailed(
00223         dxgiAdapter.As(&m_dxgiAdapter)
00224         );
00225
00226     // Check for device support for the optional feature that allows setting the render target array index from the vertex shader stage.
00227     D3D11_FEATURE_DATA_D3D11_OPTIONS3 options;
00228     m_d3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS3, &options, sizeof(options));
00229     if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer)
00230     {
00231         m_supportsVprt = true;
00232     }
00233 }
00234
00235 // Validates the back buffer for each HolographicCamera and recreates
00236 // resources for back buffers that have changed.
00237 // Locks the set of holographic camera resources until the function exits.
00238 void DX::DeviceResources::EnsureCameraResources(
00239     HolographicFrame^ frame,
00240     HolographicFramePrediction^ prediction)
00241 {
00242     UseHolographicCameraResources<void>([this, frame, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00243     {
00244         for (HolographicCameraPose^ pose : prediction->CameraPoses)
00245         {
00246             HolographicCameraRenderingParameters^ renderingParameters = frame->GetRenderingParameters(pose);
00247             CameraResources* pCameraResources = cameraResourceMap[pose->HolographicCamera->Id].get();
00248
00249             pCameraResources->CreateResourcesForBackBuffer(this, renderingParameters);
00250         }
00251     });
00252 }
00253
00254 // Prepares to allocate resources and adds resource views for a camera.
00255 // Locks the set of holographic camera resources until the function exits.
00256 void DX::DeviceResources::AddHolographicCamera(HolographicCamera^ camera)
00257 {
00258     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00259     {
00260         cameraResourceMap[camera->Id] = std::make_unique<CameraResources>(camera);
00261     });
00262 }
00263
00264 // Deallocates resources for a camera and removes the camera from the set.
00265 // Locks the set of holographic camera resources until the function exits.
00266 void DX::DeviceResources::RemoveHolographicCamera(HolographicCamera^ camera)
00267 {
00268     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00269     {
00270         CameraResources* pCameraResources = cameraResourceMap[camera->Id].get();
00271
00272         if (pCameraResources != nullptr)
00273         {
00274             pCameraResources->ReleaseResourcesForBackBuffer(this);
00275             cameraResourceMap.erase(camera->Id);
00276         }
00277     });
00278 }
00279
00280 // Recreate all device resources and set them back to the current state.
00281 // Locks the set of holographic camera resources until the function exits.
00282 void DX::DeviceResources::HandleDeviceLost()
00283 {
00284     if (m_deviceNotify != nullptr)
00285     {
00286         m_deviceNotify->OnDeviceLost();
00287     }
00288
00289     UseHolographicCameraResources<void>([this](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00290     {
00291         for (auto& pair : cameraResourceMap)
00292         {
00293             CameraResources* pCameraResources = pair.second.get();
00294             pCameraResources->ReleaseResourcesForBackBuffer(this);
00295         }
00296     });
00297
00298     InitializeUsingHolographicSpace();
00299
00300     if (m_deviceNotify != nullptr)
00301     {
00302         m_deviceNotify->OnDeviceRestored();
00303     }
00304 }
00305
00306 // Register our DeviceNotify to be informed on device lost and creation.
00307 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00308 {
00309     m_deviceNotify = deviceNotify;
00310 }
00311
00312 // Call this method when the app suspends. It provides a hint to the driver that the app
00313 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00314 void DX::DeviceResources::Trim()
00315 {
00316     m_d3dContext->ClearState();
00317
00318     ComPtr<IDXGIDevice3> dxgiDevice;
00319     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00320     dxgiDevice->Trim();
00321 }
00322
00323 // Present the contents of the swap chain to the screen.
00324 // Locks the set of holographic camera resources until the function exits.
00325 void DX::DeviceResources::Present(HolographicFrame^ frame)
00326 {
00327     // By default, this API waits for the frame to finish before it returns.
00328     // Holographic apps should wait for the previous frame to finish before
00329     // starting work on a new frame. This allows for better results from
00330     // holographic frame predictions.
00331     HolographicFramePresentResult presentResult = frame->PresentUsingCurrentPrediction();
00332
00333     HolographicFramePrediction^ prediction = frame->CurrentPrediction;
00334     UseHolographicCameraResources<void>([this, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00335     {
00336         for (auto cameraPose : prediction->CameraPoses)
00337         {
00338             // This represents the device-based resources for a HolographicCamera.
00339             DX::CameraResources* pCameraResources = cameraResourceMap[cameraPose->HolographicCamera->Id].get();
00340
00341             // Discard the contents of the render target.
00342             // This is a valid operation only when the existing contents will be
00343             // entirely overwritten. If dirty or scroll rects are used, this call
00344             // should be removed.
00345             m_d3dContext->DiscardView(pCameraResources->GetBackBufferRenderTargetView());
00346
00347             // Discard the contents of the depth stencil.
00348             m_d3dContext->DiscardView(pCameraResources->GetDepthStencilView());
00349         }
00350     });
00351
00352     // The PresentUsingCurrentPrediction API will detect when the graphics device
00353     // changes or becomes invalid. When this happens, it is considered a Direct3D
00354     // device lost scenario.
00355     if (presentResult == HolographicFramePresentResult::DeviceRemoved)
00356     {
00357         // The Direct3D device, context, and resources should be recreated.
00358         HandleDeviceLost();
00359     }
00360 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/PreviewUnavailable.xaml.cpp Source File

  • Printing
  • cpp

PreviewUnavailable.xaml.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "PreviewUnavailable.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Windows::Foundation;
00010 using namespace Windows::Foundation::Collections;
00011 using namespace Windows::UI::Xaml;
00012 using namespace Windows::UI::Xaml::Controls;
00013 using namespace Windows::UI::Xaml::Controls::Primitives;
00014 using namespace Windows::UI::Xaml::Data;
00015 using namespace Windows::UI::Xaml::Input;
00016 using namespace Windows::UI::Xaml::Media;
00017 using namespace Windows::UI::Xaml::Navigation;
00018
00019 PreviewUnavailable::PreviewUnavailable()
00020 {
00021     InitializeComponent();
00022 }
00023
00024 PreviewUnavailable::PreviewUnavailable(Size paperSize, Size printableSize)
00025 {
00026     InitializeComponent();
00027
00028     Page->Width = paperSize.Width;
00029     Page->Height = paperSize.Height;
00030
00031     PrintablePage->Width = printableSize.Width;
00032     PrintablePage->Height = printableSize.Height;
00033 }
Generated on Fri Nov 15 2024 22:20:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XmlLite/cppwinrt/Scenario3_XmlWriterLite.h Source File

  • XmlLite
  • cppwinrt

Scenario3_XmlWriterLite.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_XmlWriterLite.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario3_XmlWriterLite : Scenario3_XmlWriterLiteT<Scenario3_XmlWriterLite>
00020     {
00021         Scenario3_XmlWriterLite();
00022
00023         fire_and_forget DoSomething_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00024
00025     private:
00026         void ReadAndWrite(com_ptr<IStream> const& readStream, com_ptr<IStream> const& writeStream);
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario3_XmlWriterLite : Scenario3_XmlWriterLiteT<Scenario3_XmlWriterLite, implementation::Scenario3_XmlWriterLite>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:22:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/Tasks/pch.h Source File

  • DeviceEnumerationAndPairing
  • cpp
  • Tasks

pch.h

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft Corporation. All rights reserved.
00002
00003 #pragma once
00004
00005 #include <collection.h>
00006 #include <ppltasks.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_ReceiveMIDIMessages Member List

This is the complete list of members for Scenario2_ReceiveMIDIMessages, including all inherited members.
inputDevices_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario2_ReceiveMIDIMessages | [inline, private]
midiInDeviceWatcher | Scenario2_ReceiveMIDIMessages | [private]
midiInPorts | Scenario2_ReceiveMIDIMessages | [private]
MidiInputDevice_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args) | Scenario2_ReceiveMIDIMessages | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario2_ReceiveMIDIMessages | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_ReceiveMIDIMessages | [inline, protected]
rootPage | Scenario2_ReceiveMIDIMessages | [private]
Scenario2_ReceiveMIDIMessages() | Scenario2_ReceiveMIDIMessages | [inline]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomHidDeviceAccess/cpp/EventHandlerForDevice.cpp Source File

  • CustomHidDeviceAccess
  • cpp

EventHandlerForDevice.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include "pch.h"
00008 #include "EventHandlerForDevice.h"
00009 #include "MainPage.xaml.h"
00010 #include "App.xaml.h"
00011
00012 using namespace SDKTemplate;
00013 using namespace Platform;
00014 using namespace Concurrency;
00015 using namespace Windows::ApplicationModel;
00016 using namespace Windows::Devices;
00017 using namespace Windows::Devices::Enumeration;
00018 using namespace Windows::Devices::HumanInterfaceDevice;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Storage;
00021 using namespace Windows::UI::Core;
00022 using namespace Windows::UI::Xaml;
00023
00024 EventHandlerForDevice^ EventHandlerForDevice::eventHandlerForDevice = nullptr;
00025
00026 SRWLOCK EventHandlerForDevice::srwSingletonCreationLock = SRWLOCK_INIT;
00027
00028 /// <summary>
00029 /// Enforces the singleton pattern so that there is only one object handling app events
00030 /// as it relates to the UsbDevice because this sample app only supports communicating with one device at a time.
00031 ///
00032 /// An instance of EventHandlerForDevice is globally available because the device needs to persist across scenario pages.
00033 ///
00034 /// If there is no instance of EventHandlerForDevice created before this property is called,
00035 /// an EventHandlerForDevice will be created.
00036 /// </summary>
00037 EventHandlerForDevice^ EventHandlerForDevice::Current::get(void)
00038 {
00039     // Acquiring Shared lock is much quicker than an exclusive lock, so avoid exclusive lock unless it's necessary
00040     AcquireSRWLockShared(&srwSingletonCreationLock);
00041
00042     if (eventHandlerForDevice == nullptr)
00043     {
00044         // Multiple threads could have entered here, so acquire exclusive lock to make sure only one instance is created.
00045         ReleaseSRWLockShared(&srwSingletonCreationLock);
00046
00047         AcquireSRWLockExclusive(&srwSingletonCreationLock);
00048
00049         if (eventHandlerForDevice == nullptr)
00050         {
00051             CreateNewEventHandlerForDevice();
00052         }
00053
00054         ReleaseSRWLockExclusive(&srwSingletonCreationLock);
00055     }
00056     else
00057     {
00058         ReleaseSRWLockShared(&srwSingletonCreationLock);
00059     }
00060
00061     return eventHandlerForDevice;
00062 }
00063
00064 /// <summary>
00065 /// Creates a new instance of EventHandlerForDevice, enables auto reconnect, and uses it as the Current instance.
00066 /// </summary>
00067 void EventHandlerForDevice::CreateNewEventHandlerForDevice(void)
00068 {
00069     eventHandlerForDevice = ref new EventHandlerForDevice();
00070 }
00071
00072 /// <summary>
00073 /// This method opens the device using the WinRT Hid API. After the device is opened, we will save the device
00074 /// so that it can be used across scenarios.
00075 ///
00076 /// It is important that the FromIdAsync call is made on the UI thread because the consent prompt can only be displayed
00077 /// on the UI thread.
00078 ///
00079 /// This method is used to reopen the device after the device reconnects to the computer and when the app resumes.
00080 /// </summary>
00081 /// <param name="deviceInfo">Device information of the device to be opened</param>
00082 /// <param name="deviceSelector">The AQS used to find this device</param>
00083 /// <returns>True if the device was successfully opened, false if the device could not be opened for well known reasons.
00084 /// An exception may be thrown if the device could not be opened for extraordinary reasons.</returns>
00085 IAsyncOperation<bool>^ EventHandlerForDevice::OpenDeviceAsync(Enumeration::DeviceInformation^ deviceInfo, String^ deviceSelectorString)
00086 {
00087     // This sample uses FileAccessMode.ReadWrite to open the device because we do not want other apps opening our device and
00088     // changing the state of our device. FileAccessMode.Read can be used instead.
00089     return create_async([this, deviceInfo, deviceSelectorString]()
00090     {
00091         return create_task(HidDevice::FromIdAsync(deviceInfo->Id, FileAccessMode::ReadWrite))
00092             .then([this, deviceInfo, deviceSelectorString](task<HidDevice^> deviceTask)
00093             {
00094                 bool successfullyOpenedDevice = false;
00095                 NotifyType notificationStatus;
00096                 String^ notificationMessage = nullptr;
00097
00098                 // This may throw an exception or return null if we could not open the device
00099                 device = deviceTask.get();
00100
00101                 // Device could have been blocked by user or the device has already been opened by another app.
00102                 if (device != nullptr)
00103                 {
00104                     successfullyOpenedDevice = true;
00105
00106                     deviceInformation = deviceInfo;
00107                     this->deviceSelector = deviceSelector;
00108
00109                     notificationStatus = NotifyType::StatusMessage;
00110                     notificationMessage = "Device " + deviceInformation->Id + " opened";
00111
00112                     if (appSuspendEventToken.Value == 0 || appResumeEventToken.Value == 0)
00113                     {
00114                         RegisterForAppEvents();
00115                     }
00116
00117                     // User can block the device after it has been opened in the Settings charm. We can detect this by registering for the
00118                     // DeviceAccessInformation->AccessChanged event
00119                     if (deviceAccessInformation == nullptr)
00120                     {
00121                         RegisterForDeviceAccessStatusChange();
00122                     }
00123
00124                     // Create and register device watcher events for the device to be opened unless we're reopening the device
00125                     if (deviceWatcher == nullptr)
00126                     {
00127                         deviceWatcher = Enumeration::DeviceInformation::CreateWatcher(this->deviceSelector);
00128
00129                         RegisterForDeviceWatcherEvents();
00130                     }
00131
00132                     if (!watcherStarted)
00133                     {
00134                         // Start the device watcher after we made sure that the device is opened.
00135                         StartDeviceWatcher();
00136                     }
00137                 }
00138                 else
00139                 {
00140                     successfullyOpenedDevice = false;
00141
00142                     notificationStatus = NotifyType::ErrorMessage;
00143
00144                     auto deviceAccessStatus = Enumeration::DeviceAccessInformation::CreateFromId(deviceInfo->Id)->CurrentStatus;
00145
00146                     if (deviceAccessStatus == DeviceAccessStatus::DeniedByUser)
00147                     {
00148                         notificationMessage = "Access to the device was blocked by the user : " + deviceInfo->Id;
00149                     }
00150                     else if (deviceAccessStatus == DeviceAccessStatus::DeniedBySystem)
00151                     {
00152                         // This status is most likely caused by app permissions (did not declare the device in the app's package.appxmanifest)
00153                         // This status does not cover the case where the device is already opened by another app.
00154                         notificationMessage = "Access to the device was blocked by the system : " + deviceInfo->Id;
00155                     }
00156                     else
00157                     {
00158                         // Most likely the device is opened by another app, but cannot be sure
00159                         notificationMessage = "Unknown error, possibly opened by another app : " + deviceInfo->Id;
00160                     }
00161                 }
00162
00163                 MainPage::Current->NotifyUser(notificationMessage, notificationStatus);
00164
00165                 // Notify registered callback handle whether or not the device has been opened
00166                 if (deviceConnectedCallback != nullptr)
00167                 {
00168                     auto deviceConnectedEventArgs = ref new OnDeviceConnectedEventArgs(successfullyOpenedDevice, deviceInfo);
00169
00170                     deviceConnectedCallback(this, deviceConnectedEventArgs);
00171                 }
00172
00173                 return successfullyOpenedDevice;
00174             });
00175     });
00176 }
00177
00178 /// <summary>
00179 /// Closes the device, stops the device watcher, stops listening for app events, and resets object state to before a device
00180 /// was ever connected.
00181 /// </summary>
00182 void EventHandlerForDevice::CloseDevice(void)
00183 {
00184     if (IsDeviceConnected)
00185     {
00186         CloseCurrentlyConnectedDevice();
00187     }
00188
00189     if (deviceWatcher != nullptr)
00190     {
00191         if (watcherStarted)
00192         {
00193             StopDeviceWatcher();
00194
00195             UnregisterFromDeviceWatcherEvents();
00196         }
00197
00198         deviceWatcher = nullptr;
00199     }
00200
00201     if (deviceAccessInformation != nullptr)
00202     {
00203         UnregisterFromDeviceAccessStatusChange();
00204
00205         deviceAccessInformation = nullptr;
00206     }
00207
00208     if (appSuspendEventToken.Value != 0 || appResumeEventToken.Value != 0)
00209     {
00210         UnregisterFromAppEvents();
00211     }
00212
00213     deviceInformation = nullptr;
00214     deviceSelector = nullptr;
00215
00216     deviceConnectedCallback = nullptr;
00217     deviceCloseCallback = nullptr;
00218
00219     isEnabledAutoReconnect = true;
00220 }
00221
00222 EventHandlerForDevice::EventHandlerForDevice(void) :
00223     watcherStarted(false),
00224     watcherSuspended(false),
00225     isEnabledAutoReconnect(true)
00226 {
00227 }
00228
00229 EventHandlerForDevice::~EventHandlerForDevice()
00230 {
00231     if (IsDeviceConnected)
00232     {
00233         CloseDevice();
00234     }
00235 }
00236
00237 /// <summary>
00238 /// This method demonstrates how to close the device properly using the WinRT Hid API.
00239 ///
00240 /// When the HidDevice is closing, it will cancel all IO operations that are still pending (not complete).
00241 /// The close will not wait for any IO completion callbacks to be called, so the close call may complete before any of
00242 /// the IO completion callbacks are called.
00243 /// The pending IO operations will still call their respective completion callbacks with either a task
00244 /// cancelled error or the operation completed.
00245 /// </summary>
00246 void EventHandlerForDevice::CloseCurrentlyConnectedDevice(void)
00247 {
00248     if (device != nullptr)
00249     {
00250         if (deviceCloseCallback != nullptr)
00251         {
00252             deviceCloseCallback(this, deviceInformation);
00253         }
00254
00255         // This closes the handle to the device
00256         delete device;
00257
00258         device = nullptr;
00259
00260         // Save the deviceInformation->Id in case deviceInformation is set to null when closing the
00261         // device
00262         String^ deviceId = deviceInformation->Id;
00263
00264         MainPage::Current->Dispatcher->RunAsync(
00265             CoreDispatcherPriority::Normal,
00266             ref new DispatchedHandler([deviceId]()
00267         {
00268             MainPage::Current->NotifyUser(deviceId + " is closed", NotifyType::StatusMessage);
00269         }));
00270     }
00271 }
00272
00273 /// <summary>
00274 /// Register for app suspension/resume events. See the comments
00275 /// for the event handlers for more information on what is being done to the device.
00276 ///
00277 /// We will also register for when the app exists so that we may close the device handle.
00278 /// </summary>
00279 void EventHandlerForDevice::RegisterForAppEvents()
00280 {
00281     // This event is raised when the app is exited and when the app is suspended
00282     appSuspendEventToken = App::Current->Suspending += ref new SuspendingEventHandler(this, &EventHandlerForDevice::OnAppSuspension);
00283
00284     appResumeEventToken = App::Current->Resuming += ref new EventHandler<Object^>(this, &EventHandlerForDevice::OnAppResume);
00285 }
00286
00287 void EventHandlerForDevice::UnregisterFromAppEvents()
00288 {
00289     App::Current->Suspending -= appSuspendEventToken;
00290     appSuspendEventToken.Value = 0;
00291
00292     App::Current->Resuming -= appResumeEventToken;
00293     appResumeEventToken.Value = 0;
00294 }
00295
00296 /// <summary>
00297 /// Register for Added and Removed events
00298 /// Note that, when disconnecting the device, the device may be closed by the system before the OnDeviceRemoved callback is invoked.
00299 /// </summary>
00300 void EventHandlerForDevice::RegisterForDeviceWatcherEvents()
00301 {
00302     deviceAddedEventToken = deviceWatcher->Added += ref new TypedEventHandler<DeviceWatcher^, Enumeration::DeviceInformation^>(
00303         this, &EventHandlerForDevice::OnDeviceAdded);
00304
00305     deviceRemovedEventToken = deviceWatcher->Removed += ref new TypedEventHandler<DeviceWatcher^, DeviceInformationUpdate^>(
00306         this, &EventHandlerForDevice::OnDeviceRemoved);
00307 }
00308
00309 void EventHandlerForDevice::UnregisterFromDeviceWatcherEvents()
00310 {
00311     deviceWatcher->Added -= deviceAddedEventToken;
00312     deviceAddedEventToken.Value = 0;
00313
00314     deviceWatcher->Removed -= deviceRemovedEventToken;
00315     deviceRemovedEventToken.Value = 0;
00316 }
00317
00318 /// <summary>
00319 /// Listen for any changed in device access permission. The user can block access to the device while the device is in use.
00320 /// If the user blocks access to the device while the device is opened, the device's handle will be closed automatically by
00321 /// the system; it is still a good idea to close the device explicitly so that resources are cleaned up.
00322 ///
00323 /// Note that by the time the AccessChanged event is raised, the device handle may already be closed by the system.
00324 /// </summary>
00325 void EventHandlerForDevice::RegisterForDeviceAccessStatusChange()
00326 {
00327     deviceAccessInformation = Enumeration::DeviceAccessInformation::CreateFromId(deviceInformation->Id);
00328
00329     deviceAccessChangedEventToken = deviceAccessInformation->AccessChanged
00330         += ref new TypedEventHandler<Enumeration::DeviceAccessInformation^, DeviceAccessChangedEventArgs^>(this, &EventHandlerForDevice::OnDeviceAccessChanged);
00331 }
00332
00333 void EventHandlerForDevice::UnregisterFromDeviceAccessStatusChange()
00334 {
00335     deviceAccessInformation->AccessChanged -= deviceAccessChangedEventToken;
00336     deviceAccessChangedEventToken.Value = 0;
00337 }
00338
00339 void EventHandlerForDevice::StartDeviceWatcher(void)
00340 {
00341     watcherStarted = true;
00342
00343     if ((deviceWatcher->Status != DeviceWatcherStatus::Started)
00344         && (deviceWatcher->Status != DeviceWatcherStatus::EnumerationCompleted))
00345     {
00346         deviceWatcher->Start();
00347     }
00348 }
00349
00350 void EventHandlerForDevice::StopDeviceWatcher(void)
00351 {
00352     if ((deviceWatcher->Status == DeviceWatcherStatus::Started)
00353         || (deviceWatcher->Status == DeviceWatcherStatus::EnumerationCompleted))
00354     {
00355         deviceWatcher->Stop();
00356     }
00357
00358     watcherStarted = false;
00359 }
00360
00361 /// <summary>
00362 /// If a HidDevice object has been instantiated (a handle to the device is opened), we must close it before the app
00363 /// goes into suspension because the API automatically closes it for us if we don't. When resuming, the API will
00364 /// not reopen the device automatically, so we need to explicitly open the device in the app (Scenario1_DeviceConnect).
00365 ///
00366 /// Since we have to reopen the device ourselves when the app resumes, it is good practice to explicitly call the close
00367 /// in the app as well (For every open there is a close).
00368 ///
00369 /// We must stop the DeviceWatcher because it will continue to raise events even if
00370 /// the app is in suspension, which is not desired (drains battery). We resume the device watcher once the app resumes again.
00371 /// </summary>
00372 /// <param name="sender"></param>
00373 /// <param name="eventArgs"></param>
00374 void EventHandlerForDevice::OnAppSuspension(Object^ /* sender */, SuspendingEventArgs^ /* eventArgs */)
00375 {
00376     if (watcherStarted)
00377     {
00378         watcherSuspended = true;
00379         StopDeviceWatcher();
00380     }
00381     else
00382     {
00383         watcherSuspended = false;
00384     }
00385
00386     CloseCurrentlyConnectedDevice();
00387 }
00388
00389 /// <summary>
00390 /// When resume into the application, we should reopen a handle to the Usb device again. This will automatically
00391 /// happen when we start the device watcher again; the device will be re-enumerated and we will attempt to reopen it
00392 /// if IsEnabledAutoReconnect property is enabled.
00393 ///
00394 /// See OnAppSuspension for why we are starting the device watcher again
00395 /// </summary>
00396 /// <param name="sender"></param>
00397 /// <param name="args"></param>
00398 void EventHandlerForDevice::OnAppResume(Object^ /* sender */, Object^ /* args */)
00399 {
00400     if (watcherSuspended)
00401     {
00402         watcherSuspended = false;
00403         StartDeviceWatcher();
00404     }
00405 }
00406
00407 /// <summary>
00408 /// Close the device that is opened so that all pending operations are canceled properly.
00409 /// </summary>
00410 /// <param name="sender"></param>
00411 /// <param name="deviceInformationUpdate"></param>
00412 void EventHandlerForDevice::OnDeviceRemoved(DeviceWatcher^ /* sender */, DeviceInformationUpdate^ deviceInformationUpdate)
00413 {
00414     if (IsDeviceConnected && (deviceInformationUpdate->Id == deviceInformation->Id))
00415     {
00416         // The main reasons to close the device explicitly is to clean up resources, to properly handle errors,
00417         // and stop talking to the disconnected device.
00418         CloseCurrentlyConnectedDevice();
00419     }
00420 }
00421
00422 /// <summary>
00423 /// Open the device that the user wanted to open if it hasn't been opened yet and auto reconnect is enabled.
00424 /// </summary>
00425 /// <param name="sender"></param>
00426 /// <param name="deviceInfo"></param>
00427 void EventHandlerForDevice::OnDeviceAdded(DeviceWatcher^ /* sender */, Enumeration::DeviceInformation^ deviceInfo)
00428 {
00429     if ((deviceInformation != nullptr) && (deviceInfo->Id == deviceInformation->Id) && !IsDeviceConnected && isEnabledAutoReconnect)
00430     {
00431         MainPage::Current->Dispatcher->RunAsync(
00432             CoreDispatcherPriority::Normal,
00433             ref new DispatchedHandler([this]()
00434         {
00435             // If we failed to reconnect to the device, don't try to connect anymore
00436             create_task(OpenDeviceAsync(deviceInformation, deviceSelector)).then([this](task<bool> openDeviceSuccess)
00437             {
00438                 isEnabledAutoReconnect = openDeviceSuccess.get();
00439             });
00440
00441             // Any app specific device intialization should be done here because we don't know the state of the device when it is re-enumerated.
00442         }));
00443     }
00444 }
00445
00446 /// <summary>
00447 /// Close the device if the device access was denied by anyone (system or the user) and reopen it if permissions are allowed again
00448 /// </summary>
00449 /// <param name="sender"></param>
00450 /// <param name="eventArgs"></param>
00451 void EventHandlerForDevice::OnDeviceAccessChanged(Enumeration::DeviceAccessInformation^ sender, DeviceAccessChangedEventArgs^ eventArgs)
00452 {
00453     if ((eventArgs->Status == DeviceAccessStatus::DeniedBySystem)
00454         || (eventArgs->Status == DeviceAccessStatus::DeniedByUser))
00455     {
00456         CloseCurrentlyConnectedDevice();
00457     }
00458     else if ((eventArgs->Status == DeviceAccessStatus::Allowed) && (deviceInformation != nullptr) && isEnabledAutoReconnect)
00459     {
00460         MainPage::Current->Dispatcher->RunAsync(
00461             CoreDispatcherPriority::Normal,
00462             ref new DispatchedHandler([this]()
00463         {
00464             // If we failed to reconnect to the device, don't try to connect anymore
00465             create_task(OpenDeviceAsync(deviceInformation, deviceSelector)).then([this](task<bool> openDeviceSuccess)
00466             {
00467                 isEnabledAutoReconnect = openDeviceSuccess.get();
00468             });
00469
00470             // Any app specific device intialization should be done here because we don't know the state of the device when it is re-enumerated.
00471         }));
00472     }
00473 }
Generated on Fri Nov 15 2024 22:19:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ItemViewModel Member List

This is the complete list of members for ItemViewModel, including all inherited members.
_itemId | ItemViewModel | [private]
DateCreated | ItemViewModel |
DateCreatedHourMinute | ItemViewModel |
FromItem(Item item) | ItemViewModel | [inline, static]
ItemId | ItemViewModel |
ItemViewModel() | ItemViewModel | [inline]
Text | ItemViewModel |
Title | ItemViewModel |
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SemanticTextQuery/cpp/pch.h Source File

  • SemanticTextQuery
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Barometer/cpp/Scenario2_Polling.xaml.cpp Source File

  • Barometer
  • cpp

Scenario2_Polling.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2_Polling.xaml.cpp
00014 // Implementation of the Scenario2_Polling class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario2_Polling.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Windows::Devices::Sensors;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::UI::Core;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 Scenario2_Polling::Scenario2_Polling() : rootPage(MainPage::Current)
00031 {
00032     InitializeComponent();
00033
00034     sensor = Barometer::GetDefault();
00035     if (nullptr == sensor)
00036     {
00037         rootPage->NotifyUser("No barometer found", NotifyType::ErrorMessage);
00038     }
00039 }
00040
00041 void Scenario2_Polling::ScenarioGetData(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00042 {
00043     if (nullptr != sensor)
00044     {
00045         BarometerReading^ reading = sensor->GetCurrentReading();
00046         if (nullptr != reading)
00047         {
00048             ScenarioOutput_hPa->Text = reading->StationPressureInHectopascals.ToString();
00049         }
00050     }
00051     else
00052     {
00053         rootPage->NotifyUser("No barometer found", NotifyType::ErrorMessage);
00054     }
00055 }
Generated on Fri Nov 15 2024 22:17:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RawSMBIOSData Member List

This is the complete list of members for RawSMBIOSData, including all inherited members.
DmiRevision | RawSMBIOSData
Length | RawSMBIOSData
SMBIOSMajorVersion | RawSMBIOSData
SMBIOSMinorVersion | RawSMBIOSData
SMBIOSTableData | RawSMBIOSData
Used20CallingMethod | RawSMBIOSData
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/HistoryChangedTrigger/RespondingToToasts/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • HistoryChangedTrigger
  • RespondingToToasts

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using BackgroundTasks.Helpers;
00002 using System;
00003 using System.Collections.ObjectModel;
00004 using System.Linq;
00005 using System.Threading.Tasks;
00006 using Windows.ApplicationModel.Background;
00007 using Windows.ApplicationModel.Core;
00008 using Windows.UI.Notifications;
00009 using Windows.UI.Popups;
00010 using Windows.UI.Xaml;
00011 using Windows.UI.Xaml.Controls;
00012
00013 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00014
00015 namespace Notifications.ScenarioPages.Toasts.HistoryChangedTrigger.RespondingToToasts
00016 {
00017     /// <summary>
00018     /// An empty page that can be used on its own or navigated to within a Frame.
00019     /// </summary>
00020     public sealed partial class ScenarioElement : UserControl
00021     {
00022         private static readonly string BACKGROUND_TASK_NAME = "ToastNotificationHistoryChangedTriggerTask";
00023
00024         private ObservableCollection<ToastHistoryChangedType> _changeEvents = new ObservableCollection<ToastHistoryChangedType>();
00025
00026         public ScenarioElement()
00027         {
00028             this.InitializeComponent();
00029
00030             ItemsControlChangeEvents.ItemsSource = _changeEvents;
00031
00032             Initialize();
00033         }
00034
00035         private int _step = 1;
00036
00037         private async void Initialize()
00038         {
00039             scrollViewer.IsEnabled = false;
00040
00041             // Clear all existing notifications
00042             ToastNotificationManager.History.Clear();
00043
00044             // Register background task
00045             if (!await RegisterBackgroundTask())
00046             {
00047                 await new MessageDialog("ERROR: Couldn't register background task.").ShowAsync();
00048                 return;
00049             }
00050
00051             // Pop all the notifications
00052             ToastHelper.PopToast("ignore me 1", "Content of ignore me 1");
00053             ToastHelper.PopToast("SWIPE ME", "Swipe me away");
00054             ToastHelper.PopToast("ignore me 2", "Content of ignore me 2");
00055
00056             StackPanelStep1.Visibility = Visibility.Visible;
00057
00058             scrollViewer.IsEnabled = true;
00059         }
00060
00061         private async Task<bool> RegisterBackgroundTask()
00062         {
00063             // Unregister any previous exising background task
00064             UnregisterBackgroundTask();
00065
00066             // Request access
00067             BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
00068
00069             // If denied
00070             if (status != BackgroundAccessStatus.AlwaysAllowed && status != BackgroundAccessStatus.AllowedSubjectToSystemPolicy)
00071                 return false;
00072
00073             // Construct the background task
00074             BackgroundTaskBuilder builder = new BackgroundTaskBuilder()
00075             {
00076                 Name = BACKGROUND_TASK_NAME,
00077                 TaskEntryPoint = "BackgroundTasks.ToastNotificationHistoryChangedTriggerTask"
00078             };
00079
00080             // Set trigger for Toast History Changed
00081             builder.SetTrigger(new ToastNotificationHistoryChangedTrigger());
00082
00083             // And register the background task
00084             BackgroundTaskRegistration registration = builder.Register();
00085
00086             // And then listen for when the background task updates progress (it passes the toast change type)
00087             registration.Progress += BackgroundTask_Progress;
00088
00089             return true;
00090         }
00091
00092         private void BackgroundTask_Progress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args)
00093         {
00094             ToastHistoryChangedType changedType = (ToastHistoryChangedType)args.Progress;
00095
00096             CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, delegate
00097             {
00098                 OnHistoryChanged(changedType);
00099             });
00100         }
00101
00102         private DispatcherTimer _timerStep3;
00103
00104         private async void OnHistoryChanged(ToastHistoryChangedType changedType)
00105         {
00106             _changeEvents.Add(changedType);
00107
00108             switch (_step)
00109             {
00110                 case 1:
00111
00112                     if (changedType == ToastHistoryChangedType.Removed)
00113                     {
00114                         _step = 2;
00115                         StackPanelStep1.Visibility = Visibility.Collapsed;
00116                         StackPanelStep2.Visibility = Visibility.Visible;
00117                     }
00118
00119                     else
00120                     {
00121                         await new MessageDialog("ERROR: Step 1 - expected Removed but was " + changedType).ShowAsync();
00122                     }
00123
00124                     break;
00125
00126
00127                 case 2:
00128
00129                     if (changedType == ToastHistoryChangedType.Removed)
00130                     {
00131                         _step = 3;
00132                         StackPanelStep2.Visibility = Visibility.Collapsed;
00133                         StackPanelStep3.Visibility = Visibility.Visible;
00134
00135                         _timerStep3 = new DispatcherTimer()
00136                         {
00137                             Interval = TimeSpan.FromSeconds(10)
00138                         };
00139                         _timerStep3.Tick += _timerStep3_Tick;
00140                         _timerStep3.Start();
00141                     }
00142
00143                     else
00144                     {
00145                         await new MessageDialog("ERROR: Step 2 - expected Removed but was " + changedType).ShowAsync();
00146                     }
00147
00148                     break;
00149
00150
00151                 case 3:
00152
00153                     if (_timerStep3 != null)
00154                         _timerStep3.Stop();
00155
00156                     await new MessageDialog("ERROR: Step 3 - wasn't expecting any changes, but received " + changedType).ShowAsync();
00157                     break;
00158
00159
00160                 case 4:
00161                     break;
00162
00163
00164                 default:
00165                     throw new NotImplementedException("Didn't handle step " + _step);
00166
00167             }
00168         }
00169
00170         private void _timerStep3_Tick(object sender, object e)
00171         {
00172             (sender as DispatcherTimer).Stop();
00173
00174             _step = 4;
00175             StackPanelStep3.Visibility = Visibility.Collapsed;
00176             StackPanelStep4.Visibility = Visibility.Visible;
00177         }
00178
00179         private static void UnregisterBackgroundTask()
00180         {
00181             var task = BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault(i => i.Name.Equals(BACKGROUND_TASK_NAME));
00182
00183             if (task != null)
00184                 task.Unregister(true);
00185         }
00186     }
00187 }
Generated on Fri Nov 15 2024 22:20:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MicrosoftPassport/cs/EnableHelloPage.xaml.cs Source File

  • MicrosoftPassport
  • cs

EnableHelloPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 // Please refer to the Microsoft Passport and Windows Hello
00012 // whitepaper on the Windows Dev Center for a complete
00013 // explanation of Microsoft Passport and Windows Hello
00014 // implementation:
00015 // http://go.microsoft.com/fwlink/p/?LinkId=522066
00016 //*********************************************************
00017 using System;
00018 using System.Linq;
00019 using System.Threading.Tasks;
00020 using Windows.Data.Json;
00021 using Windows.Networking.Connectivity;
00022 using Windows.Security.Credentials;
00023 using Windows.Security.Cryptography;
00024 using Windows.Security.Cryptography.Core;
00025 using Windows.Storage;
00026 using Windows.Storage.Streams;
00027 using Windows.UI.Popups;
00028 using Windows.UI.Xaml;
00029 using Windows.UI.Xaml.Controls;
00030 using Windows.UI.Xaml.Navigation;
00031
00032 namespace SDKTemplate
00033 {
00034     public sealed partial class EnableHelloPage : Page
00035     {
00036         private string userId;
00037
00038         public EnableHelloPage()
00039         {
00040             InitializeComponent();
00041         }
00042
00043         protected override void OnNavigatedTo(NavigationEventArgs e)
00044         {
00045             userId = e.Parameter.ToString();
00046             WelcomeUserId.Text = userId;
00047         }
00048
00049         private void SkipSetup()
00050         {
00051             // The user already signed in on the previous page, so we can go directly to the signed-in state.
00052             Frame.Navigate(typeof(AccountOverviewPage));
00053         }
00054
00055         private async void StartUsingWindowsHello()
00056         {
00057             ProgressRing.IsActive = true;
00058             LaterButton.IsEnabled = false;
00059             StartUsingWindowsHelloButton.IsEnabled = false;
00060
00061             // Create the key credential with Passport APIs
00062             IBuffer publicKey = await CreatePassportKeyCredentialAsync();
00063             if (publicKey != null)
00064             {
00065                 // Register the public key and attestation of the key credential with the server
00066                 // In a real-world scenario, this would likely also include:
00067                 // - Certificate chain for attestation endorsement if available
00068                 // - Status code of the Key Attestation result : Included / retrieved later / retry type
00069                 if (await RegisterPassportCredentialWithServerAsync(publicKey))
00070                 {
00071                     // Remember that this is the user whose credentials have been registered
00072                     // with the server.
00073                     ApplicationData.Current.LocalSettings.Values["userId"] = userId;
00074
00075                     // When communicating with the server in the future, we pass a hash of the
00076                     // public key in order to identify which key the server should use to verify the challenge.
00077                     HashAlgorithmProvider hashProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
00078                     IBuffer publicKeyHash = hashProvider.HashData(publicKey);
00079                     ApplicationData.Current.LocalSettings.Values["publicKeyHint"] = CryptographicBuffer.EncodeToBase64String(publicKeyHash);
00080
00081                     // Registration successful. Continue to the signed-in state.
00082                     Frame.Navigate(typeof(AccountOverviewPage));
00083                 }
00084                 else
00085                 {
00086                     // Delete the failed credentials from the device.
00087                     await Util.TryDeleteCredentialAccountAsync(userId);
00088
00089                     MessageDialog message = new MessageDialog("Failed to register with the server.");
00090                     await message.ShowAsync();
00091                 }
00092             }
00093             ProgressRing.IsActive = false;
00094             LaterButton.IsEnabled = true;
00095             StartUsingWindowsHelloButton.IsEnabled = true;
00096         }
00097
00098         private async Task<IBuffer> CreatePassportKeyCredentialAsync()
00099         {
00100             // Create a new KeyCredential for the user on the device.
00101             KeyCredentialRetrievalResult keyCreationResult = await KeyCredentialManager.RequestCreateAsync(userId, KeyCredentialCreationOption.ReplaceExisting);
00102             if (keyCreationResult.Status == KeyCredentialStatus.Success)
00103             {
00104                 // User has autheniticated with Windows Hello and the key credential is created.
00105                 KeyCredential userKey = keyCreationResult.Credential;
00106                 return userKey.RetrievePublicKey();
00107             }
00108             else if (keyCreationResult.Status == KeyCredentialStatus.NotFound)
00109             {
00110                 MessageDialog message = new MessageDialog("To proceed, Windows Hello needs to be configured in Windows Settings (Accounts -> Sign-in options)");
00111                 await message.ShowAsync();
00112
00113                 return null;
00114             }
00115             else if (keyCreationResult.Status == KeyCredentialStatus.UnknownError)
00116             {
00117                 MessageDialog message = new MessageDialog("The key credential could not be created. Please try again.");
00118                 await message.ShowAsync();
00119
00120                 return null;
00121             }
00122
00123             return null;
00124         }
00125
00126
00127         // Register the user and device with the server
00128         private async Task<bool> RegisterPassportCredentialWithServerAsync(IBuffer publicKey)
00129         {
00130             // Include the name of the current device for the benefit of the user.
00131             // The server could support a Web interface that shows the user all the devices they
00132             // have signed in from and revoke access from devices they have lost.
00133
00134             var hostNames = NetworkInformation.GetHostNames();
00135             var localName = hostNames.FirstOrDefault(name => name.DisplayName.Contains(".local"));
00136             string computerName = localName.DisplayName.Replace(".local", "");
00137
00138             JsonValue jsonResult = await JsonRequest.Create()
00139                 .AddString("userId", userId)
00140                 .AddString("publicKey", CryptographicBuffer.EncodeToBase64String(publicKey))
00141                 .AddString("deviceName", computerName)
00142                 .PostAsync("api/Authentication/Register");
00143             bool result = (jsonResult != null) && jsonResult.GetBoolean();
00144
00145             return result;
00146         }
00147
00148         private async void LaunchHyperlink(object sender, RoutedEventArgs e)
00149         {
00150             var element = (FrameworkElement)sender;
00151             var target = (string)element.Tag;
00152             await Windows.System.Launcher.LaunchUriAsync(new Uri(target));
00153
00154         }
00155     }
00156 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

STEREO_PARAMETERS Member List

This is the complete list of members for STEREO_PARAMETERS, including all inherited members.
displaySizeInches | STEREO_PARAMETERS
pixelResolutionHeight | STEREO_PARAMETERS
pixelResolutionWidth | STEREO_PARAMETERS
stereoExaggerationFactor | STEREO_PARAMETERS
stereoSeparationFactor | STEREO_PARAMETERS
viewerDistanceInches | STEREO_PARAMETERS
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DatagramSocket/cpp/pch.h Source File

  • DatagramSocket
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // pch.h
00014 // Header for standard system include files.
00015 //
00016
00017 #pragma once
00018
00019 #include <ppltasks.h>
00020 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSuggestion/cpp/Scenario2_Prediction.xaml.h Source File

  • TextSuggestion
  • cpp

Scenario2_Prediction.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario2_Prediction.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     /// <summary>
00011     /// An empty page that can be used on its own or navigated to within a Frame.
00012     /// </summary>
00013     [Windows::Foundation::Metadata::WebHostHidden]
00014     public ref class Scenario2_Prediction sealed
00015     {
00016     public:
00017         Scenario2_Prediction();
00018     private:
00019         MainPage^ rootPage;
00020
00021         void CreateGeneratorButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00022         void Methods_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00023         void Execute_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00024
00025         void DisplayMultipleCandidates(Windows::Foundation::Collections::IVectorView<Platform::String^>^ candidates);
00026
00027         Windows::Data::Text::TextPredictionGenerator^ generator;
00028     };
00029 }
Generated on Fri Nov 15 2024 22:21:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LowLatencyInput/cpp/pch.cpp Source File

  • LowLatencyInput
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ExtendedExecution/cs/Scenario4_MultipleTasks.xaml.cs Source File

  • ExtendedExecution
  • cs

Scenario4_MultipleTasks.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.IO;
00004 using System.Linq;
00005 using System.Runtime.InteropServices.WindowsRuntime;
00006 using System.Threading;
00007 using System.Threading.Tasks;
00008 using Windows.ApplicationModel.ExtendedExecution;
00009 using Windows.Foundation;
00010 using Windows.Foundation.Collections;
00011 using Windows.UI.Core;
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Controls.Primitives;
00015 using Windows.UI.Xaml.Data;
00016 using Windows.UI.Xaml.Input;
00017 using Windows.UI.Xaml.Media;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     public sealed partial class MultipleTasks : Page
00023     {
00024         private MainPage rootPage = MainPage.Current;
00025
00026         private ExtendedExecutionSession session = null;
00027         private CancellationTokenSource cancellationTokenSource;
00028         private int taskCount = 0;
00029
00030         public MultipleTasks()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00036         {
00037             // End the Extended Execution Session.
00038             // Only one extended execution session can be held by an application at one time.
00039             ClearExtendedExecution();
00040         }
00041
00042         void ClearExtendedExecution()
00043         {
00044             // Cancel any outstanding tasks.
00045             if (cancellationTokenSource != null)
00046             {
00047                 // Save a copy of cancellationTokenSource because the call
00048                 // to cancellationTokenSource.Cancel() will cause other code
00049                 // to run, which might in turn call ClearExtendedExecution.
00050                 var localCancellationTokenSource = cancellationTokenSource;
00051                 cancellationTokenSource = null;
00052
00053                 localCancellationTokenSource.Cancel();
00054                 localCancellationTokenSource.Dispose();
00055             }
00056
00057             // Dispose any outstanding session.
00058             if (session != null)
00059             {
00060                 session.Revoked -= SessionRevoked;
00061                 session.Dispose();
00062                 session = null;
00063             }
00064         }
00065
00066         private void UpdateUI()
00067         {
00068             if (session == null)
00069             {
00070                 Status.Text = "Not requested";
00071                 RequestButton.IsEnabled = true;
00072                 CloseButton.IsEnabled = false;
00073
00074             }
00075             else
00076             {
00077                 Status.Text = "Requested";
00078                 RequestButton.IsEnabled = false;
00079                 CloseButton.IsEnabled = true;
00080             }
00081         }
00082
00083         private void OnTaskCompleted()
00084         {
00085             taskCount--;
00086             if (taskCount == 0 && session != null)
00087             {
00088                 EndExtendedExecution();
00089                 MainPage.DisplayToast("All Tasks Completed, ending Extended Execution.");
00090             }
00091         }
00092
00093         private Deferral GetExecutionDeferral()
00094         {
00095             if (session == null)
00096             {
00097                 throw new InvalidOperationException("No extended execution session is active");
00098             }
00099
00100             taskCount++;
00101             return new Deferral(OnTaskCompleted);
00102         }
00103
00104         private async void BeginExtendedExecution()
00105         {
00106             // The previous Extended Execution must be closed before a new one can be requested.
00107             // This code is redundant here because the sample doesn't allow a new extended
00108             // execution to begin until the previous one ends, but we leave it here for illustration.
00109             ClearExtendedExecution();
00110
00111             var newSession = new ExtendedExecutionSession();
00112             newSession.Reason = ExtendedExecutionReason.Unspecified;
00113             newSession.Description = "Running multiple tasks";
00114             newSession.Revoked += SessionRevoked;
00115             ExtendedExecutionResult result = await newSession.RequestExtensionAsync();
00116
00117             switch (result)
00118             {
00119                 case ExtendedExecutionResult.Allowed:
00120                     rootPage.NotifyUser("Extended execution allowed.", NotifyType.StatusMessage);
00121                     session = newSession;
00122                     break;
00123
00124                 default:
00125                 case ExtendedExecutionResult.Denied:
00126                     rootPage.NotifyUser("Extended execution denied.", NotifyType.ErrorMessage);
00127                     newSession.Dispose();
00128                     break;
00129             }
00130             UpdateUI();
00131
00132             if (session != null)
00133             {
00134                 cancellationTokenSource = new CancellationTokenSource();
00135
00136                 // Start up a few tasks that all share this session.
00137                 using (var deferral = GetExecutionDeferral())
00138                 {
00139                     var random = new Random();
00140                     for (int i = 0; i < 3; i++)
00141                     {
00142                         RaiseToastAfterDelay(i, random.Next(5, 10));
00143                     }
00144                 }
00145             }
00146         }
00147
00148         private async void RaiseToastAfterDelay(int id, int seconds)
00149         {
00150             using (var deferral = GetExecutionDeferral())
00151             {
00152                 try
00153                 {
00154                     await Task.Delay(seconds * 1000, cancellationTokenSource.Token);
00155                     MainPage.DisplayToast($"Task {id} completed after {seconds} seconds");
00156                 }
00157                 catch (TaskCanceledException)
00158                 {
00159                     MainPage.DisplayToast($"Task {id} canceled");
00160                 }
00161             }
00162         }
00163
00164         private void EndExtendedExecution()
00165         {
00166             ClearExtendedExecution();
00167             UpdateUI();
00168         }
00169
00170         private async void SessionRevoked(object sender, ExtendedExecutionRevokedEventArgs args)
00171         {
00172             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00173             {
00174                 switch (args.Reason)
00175                 {
00176                     case ExtendedExecutionRevokedReason.Resumed:
00177                         rootPage.NotifyUser("Extended execution revoked due to returning to foreground.", NotifyType.StatusMessage);
00178                         break;
00179
00180                     case ExtendedExecutionRevokedReason.SystemPolicy:
00181                         rootPage.NotifyUser("Extended execution revoked due to system policy.", NotifyType.StatusMessage);
00182                         break;
00183                 }
00184
00185                 ClearExtendedExecution();
00186             });
00187         }
00188     }
00189 }
Generated on Fri Nov 15 2024 22:19:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

RawSMBIOSSystemInfo Member List

This is the complete list of members for RawSMBIOSSystemInfo, including all inherited members.
Family | RawSMBIOSSystemInfo
Handle | RawSMBIOSTable
Length | RawSMBIOSTable
Manufacturer | RawSMBIOSSystemInfo
ProductName | RawSMBIOSSystemInfo
SerialNumber | RawSMBIOSSystemInfo
SKUNumber | RawSMBIOSSystemInfo
Type | RawSMBIOSTable
UUID | RawSMBIOSSystemInfo
Version | RawSMBIOSSystemInfo
Wakeup_Type | RawSMBIOSSystemInfo
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1ViewModel Member List

This is the complete list of members for Scenario1ViewModel, including all inherited members.
AttemptAuthentication | Scenario1ViewModel |
Authenticate() | Scenario1ViewModel | [inline, private]
AuthenticationVisibility | Scenario1ViewModel |
BusAttachment_AuthenticationComplete(AllJoynBusAttachment sender, AllJoynAuthenticationCompleteEventArgs args) | Scenario1ViewModel | [inline, private]
BusAttachment_CredentialsRequested(AllJoynBusAttachment sender, AllJoynCredentialsRequestedEventArgs args) | Scenario1ViewModel | [inline, private]
BusAttachment_StateChanged(AllJoynBusAttachment sender, AllJoynBusAttachmentStateChangedEventArgs args) | Scenario1ViewModel | [inline, private]
ConcatenateAsync() | Scenario1ViewModel | [inline, private]
ConnectToProducer | Scenario1ViewModel |
Consumer_IsUpperCaseEnabledChanged(SecureInterfaceConsumer sender, object args) | Scenario1ViewModel | [inline, private]
Consumer_SessionLost(AllJoynSession sender, AllJoynSessionLostEventArgs args) | Scenario1ViewModel | [inline, private]
ConsumerOptionsVisibility | Scenario1ViewModel |
DisposeConsumer() | Scenario1ViewModel | [inline, private]
DisposeWatcher() | Scenario1ViewModel | [inline, private]
EnteredKey | Scenario1ViewModel |
InputString1 | Scenario1ViewModel |
InputString2 | Scenario1ViewModel |
IsUpperCaseEnabled | Scenario1ViewModel |
m_authenticateClicked | Scenario1ViewModel | [private]
m_authVisibility | Scenario1ViewModel | [private]
m_busAttachment | Scenario1ViewModel | [private]
m_callSetProperty | Scenario1ViewModel | [private]
m_consumer | Scenario1ViewModel | [private]
m_consumerOptionsVisibility | Scenario1ViewModel | [private]
m_dispatcher | Scenario1ViewModel | [private]
m_isAuthenticated | Scenario1ViewModel | [private]
m_isCredentialsRequested | Scenario1ViewModel | [private]
m_isUpperCaseEnabled | Scenario1ViewModel | [private]
m_key | Scenario1ViewModel | [private]
m_rootPage | Scenario1ViewModel | [private]
m_watcher | Scenario1ViewModel | [private]
PropertyChanged | Scenario1ViewModel |
RaisePropertyChangedEventAsync([CallerMemberName] string name="") | Scenario1ViewModel | [inline, protected]
RequestConcatenate | Scenario1ViewModel |
Scenario1ViewModel() | Scenario1ViewModel | [inline]
ScenarioCleanup() | Scenario1ViewModel | [inline]
SetIsUpperCaseEnabledAsync(bool value) | Scenario1ViewModel | [inline, private]
Signals_TextSentReceived(SecureInterfaceSignals sender, SecureInterfaceTextSentReceivedEventArgs args) | Scenario1ViewModel | [inline, private]
Start() | Scenario1ViewModel | [inline, private]
UpdateIsUpperCaseEnabledAsync() | Scenario1ViewModel | [inline, private]
UpdateStatusAsync(string status, NotifyType statusType) | Scenario1ViewModel | [inline, private]
Watcher_Added(DeviceWatcher sender, DeviceInformation args) | Scenario1ViewModel | [inline, private]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cs/Scenario3_ActiveSymbologies.xaml.cs Source File

  • BarcodeScanner
  • cs

Scenario3_ActiveSymbologies.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Collections.ObjectModel;
00015 using System.Threading.Tasks;
00016 using Windows.Devices.PointOfService;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario3_ActiveSymbologies : Page
00025     {
00026         MainPage rootPage = MainPage.Current;
00027         BarcodeScanner scanner = null;
00028         ClaimedBarcodeScanner claimedScanner = null;
00029
00030         ObservableCollection<SymbologyListEntry> listOfSymbologies = null;
00031
00032         public Scenario3_ActiveSymbologies()
00033         {
00034             this.InitializeComponent();
00035
00036             listOfSymbologies = new ObservableCollection<SymbologyListEntry>();
00037             SymbologyListSource.Source = listOfSymbologies;
00038         }
00039
00040         /// <summary>
00041         /// Invoked when this page is about to be displayed in a Frame.
00042         /// </summary>
00043         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00044         /// property is typically used to configure the page.</param>
00045         protected override void OnNavigatedTo(NavigationEventArgs e)
00046         {
00047             ResetTheScenarioState();
00048         }
00049
00050         /// <summary>
00051         /// Invoked when this page is no longer displayed.
00052         /// </summary>
00053         /// <param name="e">Event data that describes how this page was exited.  The Parameter
00054         /// property is typically used to configure the page.</param>
00055         protected override void OnNavigatedFrom(NavigationEventArgs e)
00056         {
00057             ResetTheScenarioState();
00058         }
00059
00060         /// <summary>
00061         /// Event Handler for Start Scan Button Click.
00062         /// Sets up the barcode scanner to be ready to receive the data events from the scan.
00063         /// </summary>
00064         /// <param name="sender"></param>
00065         /// <param name="e"></param>
00066         private async void ScenarioStartScanButton_Click(object sender, RoutedEventArgs e)
00067         {
00068             ScenarioStartScanButton.IsEnabled = false;
00069
00070             rootPage.NotifyUser("Acquiring barcode scanner object.", NotifyType.StatusMessage);
00071
00072             // create the barcode scanner.
00073             scanner = await DeviceHelpers.GetFirstBarcodeScannerAsync();
00074
00075             if (scanner != null)
00076             {
00077                 // Claim the scanner for exclusive use and enable it so raises DataReceived events.
00078                 claimedScanner = await scanner.ClaimScannerAsync();
00079                 if (claimedScanner != null)
00080                 {
00081                     // It is always a good idea to have a release device requested event handler.
00082                     // If this event is not handled, then another app can claim ownership of the barcode scanner.
00083                     claimedScanner.ReleaseDeviceRequested += claimedScanner_ReleaseDeviceRequested;
00084
00085                     // after successfully claiming, attach the datareceived event handler.
00086                     claimedScanner.DataReceived += claimedScanner_DataReceived;
00087
00088                     // Ask the platform to decode the data by default. When this is set, the platform
00089                     // will decode the raw data from the barcode scanner and include in the
00090                     // BarcodeScannerReport.ScanDataLabel and ScanDataType in the DataReceived event.
00091                     claimedScanner.IsDecodeDataEnabled = true;
00092
00093                     // Enable the scanner so it raises DataReceived events.
00094                     // Do this after adding the DataReceived event handler.
00095                     await claimedScanner.EnableAsync();
00096
00097                     // after successful claim, list supported symbologies
00098                     IReadOnlyList<uint> supportedSymbologies = await scanner.GetSupportedSymbologiesAsync();
00099                     foreach (uint symbology in supportedSymbologies)
00100                     {
00101                         listOfSymbologies.Add(new SymbologyListEntry(symbology));
00102                     }
00103
00104                     // reset the button state
00105                     ScenarioEndScanButton.IsEnabled = true;
00106                     SetActiveSymbologiesButton.IsEnabled = true;
00107
00108                     rootPage.NotifyUser("Ready to scan. Device ID: " + claimedScanner.DeviceId, NotifyType.StatusMessage);
00109                 }
00110                 else
00111                 {
00112                     scanner.Dispose();
00113                     scanner = null;
00114                     ScenarioStartScanButton.IsEnabled = true;
00115                     rootPage.NotifyUser("Claim barcode scanner failed.", NotifyType.ErrorMessage);
00116                 }
00117             }
00118             else
00119             {
00120                 ScenarioStartScanButton.IsEnabled = true;
00121                 rootPage.NotifyUser("Barcode scanner not found. Please connect a barcode scanner.", NotifyType.ErrorMessage);
00122             }
00123         }
00124
00125         /// <summary>
00126         /// Event handler for the Release Device Requested event fired when barcode scanner receives Claim request from another application
00127         /// </summary>
00128         /// <param name="sender"></param>
00129         /// <param name="args"> Contains the ClamiedBarcodeScanner that is sending this request</param>
00130         void claimedScanner_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e)
00131         {
00132             // always retain the device
00133             e.RetainDevice();
00134             rootPage.NotifyUser("Event ReleaseDeviceRequested received. Retaining the barcode scanner.", NotifyType.StatusMessage);
00135         }
00136
00137         /// <summary>
00138         /// Event handler for the DataReceived event fired when a barcode is scanned by the barcode scanner
00139         /// </summary>
00140         /// <param name="sender"></param>
00141         /// <param name="args"> Contains the BarcodeScannerReport which contains the data obtained in the scan</param>
00142         async void claimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
00143         {
00144             // need to update the UI data on the dispatcher thread.
00145             // update the UI with the data received from the scan.
00146             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00147             {
00148                 // read the data from the buffer and convert to string.
00149                 ScenarioOutputScanDataLabel.Text = DataHelpers.GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType);
00150                 ScenarioOutputScanData.Text = DataHelpers.GetDataString(args.Report.ScanData);
00151                 ScenarioOutputScanDataType.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType);
00152             });
00153         }
00154
00155         /// <summary>
00156         /// Reset the Scenario state
00157         /// </summary>
00158         private void ResetTheScenarioState()
00159         {
00160             if (claimedScanner != null)
00161             {
00162                 // Detach the event handlers
00163                 claimedScanner.DataReceived -= claimedScanner_DataReceived;
00164                 claimedScanner.ReleaseDeviceRequested -= claimedScanner_ReleaseDeviceRequested;
00165                 // Release the Barcode Scanner and set to null
00166                 claimedScanner.Dispose();
00167                 claimedScanner = null;
00168             }
00169
00170             if (scanner != null)
00171             {
00172                 scanner.Dispose();
00173                 scanner = null;
00174             }
00175
00176             // Reset the UI if we are still the current page.
00177             if (Frame.Content == this)
00178             {
00179                 rootPage.NotifyUser("Click the start scanning button to begin.", NotifyType.StatusMessage);
00180                 this.ScenarioOutputScanData.Text = "No data";
00181                 this.ScenarioOutputScanDataLabel.Text = "No data";
00182                 this.ScenarioOutputScanDataType.Text = "No data";
00183
00184                 // reset the button state
00185                 SetActiveSymbologiesButton.IsEnabled = false;
00186                 ScenarioEndScanButton.IsEnabled = false;
00187                 ScenarioStartScanButton.IsEnabled = true;
00188
00189                 // reset symbology list
00190                 listOfSymbologies.Clear();
00191             }
00192         }
00193
00194         /// <summary>
00195         /// Event handler for End Scan Button Click.
00196         /// Releases the Barcode Scanner and resets the text in the UI
00197         /// </summary>
00198         /// <param name="sender"></param>
00199         /// <param name="e"></param>
00200         private void ScenarioEndScanButton_Click(object sender, RoutedEventArgs e)
00201         {
00202             ResetTheScenarioState();
00203         }
00204
00205         private async void SetActiveSymbologies_Click(object sender, RoutedEventArgs e)
00206         {
00207             if (claimedScanner != null)
00208             {
00209                 var symbologyList = new List<uint>();
00210                 foreach (var symbologyListEntry in listOfSymbologies)
00211                 {
00212                     if (symbologyListEntry.IsEnabled)
00213                     {
00214                         symbologyList.Add(symbologyListEntry.Id);
00215                     }
00216                 }
00217                 await claimedScanner.SetActiveSymbologiesAsync(symbologyList);
00218             }
00219         }
00220     }
00221 }
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: KeyCredentialManager/cs/AccountsHelper.cs Source File

  • KeyCredentialManager
  • cs

AccountsHelper.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.IO;
00004 using System.Linq;
00005 using System.Text;
00006 using System.Threading.Tasks;
00007 using System.Xml;
00008 using System.Xml.Linq;
00009 using System.Xml.Serialization;
00010 using Windows.Storage;
00011
00012 namespace SDKTemplate
00013 {
00014     public class AccountsHelper
00015     {
00016         private const string USER_LIST_FILE_NAME = "accountlist.txt";
00017
00018         /// <summary>
00019         /// Gets the account list file and deserializes it from XML to a list of accounts object.
00020         /// </summary>
00021         /// <returns>List of account objects</returns>
00022         static public async Task<List<Account>> LoadAccountList()
00023         {
00024             try
00025             {
00026                 StorageFile accountsFile = await ApplicationData.Current.LocalFolder.GetFileAsync(USER_LIST_FILE_NAME);
00027                 string accountsXml = await Windows.Storage.FileIO.ReadTextAsync(accountsFile);
00028                 return AccountsHelper.DeserializeXmlToAccountList(accountsXml);
00029             }
00030             catch (FileNotFoundException e)
00031             {
00032                 List<Account> emptyAccountList = new List<Account>();
00033                 return emptyAccountList;
00034             }
00035         }
00036
00037         /// <summary>
00038         /// Takes a list of accounts and create an account list file. (Replacing the old one)
00039         /// </summary>
00040         /// <param name="accountList">List object of accounts</param>
00041         static public async void SaveAccountList(List<Account> accountList)
00042         {
00043             string accountsXml = SerializeAccountListToXml(accountList);
00044
00045             try
00046             {
00047                 StorageFile accountsFile = await ApplicationData.Current.LocalFolder.GetFileAsync(USER_LIST_FILE_NAME);
00048                 await Windows.Storage.FileIO.WriteTextAsync(accountsFile, accountsXml);
00049             }
00050             catch (FileNotFoundException e)
00051             {
00052                 StorageFile accountsFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(USER_LIST_FILE_NAME);
00053                 await Windows.Storage.FileIO.WriteTextAsync(accountsFile, accountsXml);
00054             }
00055         }
00056
00057         /// <summary>
00058         /// Takes a list of accounts and returns an XML formatted string representing the list
00059         /// </summary>
00060         /// <param name="list">List object of accounts</param>
00061         /// <returns>XML formatted list of accounts</returns>
00062         static public string SerializeAccountListToXml(List<Account> list)
00063         {
00064             XmlSerializer xmlizer = new XmlSerializer(typeof(List<Account>));
00065             StringWriter writer = new StringWriter();
00066             xmlizer.Serialize(writer, list);
00067             return writer.ToString();
00068         }
00069
00070         /// <summary>
00071         /// Takes an XML formatted string representing a list of accounts and returns a list object of accounts
00072         /// </summary>
00073         /// <param name="listAsXml">XML formatted list of accounts</param>
00074         /// <returns>List object of accounts</returns>
00075         static public List<Account> DeserializeXmlToAccountList(string listAsXml)
00076         {
00077             XmlSerializer xmlizer = new XmlSerializer(typeof(List<Account>));
00078             List<Account> accounts = new List<Account>();
00079             TextReader textreader = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(listAsXml)));
00080             accounts = (xmlizer.Deserialize(textreader)) as List<Account>;
00081             return accounts;
00082         }
00083     }
00084 }
Generated on Fri Nov 15 2024 22:20:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cpp/Scenario3_UsingWindows.xaml.cpp Source File

  • LineDisplay
  • cpp

Scenario3_UsingWindows.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_UsingWindows.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Devices::PointOfService;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 Scenario3_UsingWindows::Scenario3_UsingWindows()
00028 {
00029     InitializeComponent();
00030     DataContext = this;
00031 }
00032
00033 void Scenario3_UsingWindows::OnNavigatedTo(NavigationEventArgs^ e)
00034 {
00035     InitializeAsync();
00036 }
00037
00038 void Scenario3_UsingWindows::OnNavigatedFrom(NavigationEventArgs^ e)
00039 {
00040     delete lineDisplay;
00041     lineDisplay = nullptr;
00042 }
00043
00044 task<void> Scenario3_UsingWindows::InitializeAsync()
00045 {
00046     lineDisplay = co_await rootPage->ClaimScenarioLineDisplayAsync();
00047
00048     maxWindows = (lineDisplay == nullptr) ? 0 : lineDisplay->Capabilities->SupportedWindows;
00049     if (maxWindows >= 1)
00050     {
00051         // Create an entry to represent the default window.
00052         WindowList->Append(ref new WindowInfo(lineDisplay->DefaultWindow, nextWindowId));
00053         nextWindowId++;
00054     }
00055 }
00056
00057 void Scenario3_UsingWindows::NewWindowButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00058 {
00059     invoke_async_lambda([=]() -> task<void>
00060     {
00061         Rect viewportBounds =
00062         {
00063             Helpers::ParseUIntWithFallback(NewViewportX, -1.0f),
00064             Helpers::ParseUIntWithFallback(NewViewportY, -1.0f),
00065             Helpers::ParseUIntWithFallback(NewViewportWidth, 0.0f),
00066             Helpers::ParseUIntWithFallback(NewViewportHeight, 0.0f),
00067         };
00068
00069         if ((viewportBounds.Width <= 0) || (viewportBounds.Height <= 0))
00070         {
00071             rootPage->NotifyUser("Viewport size must be be positive.", NotifyType::ErrorMessage);
00072             return;
00073         }
00074
00075         // Viewport cannot extend beyond the screen.
00076         Size screenSizeInCharacters = lineDisplay->GetAttributes()->ScreenSizeInCharacters;
00077         if ((viewportBounds.X < 0) || (viewportBounds.Y < 0) ||
00078             (viewportBounds.X + viewportBounds.Width > screenSizeInCharacters.Width) ||
00079             (viewportBounds.Y + viewportBounds.Height > screenSizeInCharacters.Height))
00080         {
00081             rootPage->NotifyUser("Viewport cannot extend beyond the screen.", NotifyType::ErrorMessage);
00082             return;
00083         }
00084
00085         Size windowSize =
00086         {
00087             Helpers::ParseUIntWithFallback(NewWindowWidth, 0.0f),
00088             Helpers::ParseUIntWithFallback(NewWindowHeight, 0.0f),
00089         };
00090
00091         if ((windowSize.Width <= 0) || (windowSize.Height <= 0))
00092         {
00093             rootPage->NotifyUser("Window size must be be positive.", NotifyType::ErrorMessage);
00094             return;
00095         }
00096
00097         // Window taller than viewport requires IsVerticalMarqueeSupported.
00098         if ((windowSize.Height > viewportBounds.Height) && !lineDisplay->Capabilities->IsVerticalMarqueeSupported)
00099         {
00100             rootPage->NotifyUser("Window cannot be taller than viewport on this line display.", NotifyType::ErrorMessage);
00101             return;
00102         }
00103
00104         // Window wider than viewport requires IsHorizontalMarqueeSupported.
00105         if ((windowSize.Width > viewportBounds.Width) && !lineDisplay->Capabilities->IsHorizontalMarqueeSupported)
00106         {
00107             rootPage->NotifyUser("Window cannot be wider than viewport on this line display.", NotifyType::ErrorMessage);
00108             return;
00109         }
00110
00111         // Window cannot be larger than viewport in both directions.
00112         // (Two-dimensional scrolling is not supported.)
00113         if ((windowSize.Width > viewportBounds.Width) && (windowSize.Height > viewportBounds.Height))
00114         {
00115             rootPage->NotifyUser("Window cannot be larger than viewport in both dimensions.", NotifyType::ErrorMessage);
00116             return;
00117         }
00118
00119         LineDisplayWindow^ newWindow = co_await lineDisplay->TryCreateWindowAsync(viewportBounds, windowSize);
00120
00121         if (newWindow != nullptr)
00122         {
00123             WindowInfo^ newWindowInfo = ref new WindowInfo(newWindow, nextWindowId);
00124             WindowList->Append(newWindowInfo);
00125             nextWindowId++;
00126             rootPage->NotifyUser("Created window " + newWindowInfo->Id + ".", NotifyType::StatusMessage);
00127         }
00128         else
00129         {
00130             rootPage->NotifyUser("Failed to create a new window.", NotifyType::ErrorMessage);
00131         }
00132     });
00133 }
00134
00135 void Scenario3_UsingWindows::RefreshWindowButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00136 {
00137     invoke_async_lambda([=]() -> task<void>
00138     {
00139         WindowInfo^ targetWindow = safe_cast<WindowInfo^>(WindowsListBox->SelectedItem);
00140         if (co_await targetWindow->Window->TryRefreshAsync())
00141         {
00142             rootPage->NotifyUser("Refreshed window " + targetWindow->Id + ".", NotifyType::StatusMessage);
00143         }
00144         else
00145         {
00146             // We probably lost our claim.
00147             rootPage->NotifyUser("Failed to refresh window " + targetWindow->Id + ".", NotifyType::ErrorMessage);
00148         }
00149     });
00150 }
00151
00152 void Scenario3_UsingWindows::DestroyWindowButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00153 {
00154     WindowInfo^ targetWindow = safe_cast<WindowInfo^>(WindowsListBox->SelectedItem);
00155     WindowList->RemoveAt(WindowsListBox->SelectedIndex);
00156
00157     // The LineDisplayWindow class implements IDispose. Disposing of a LineDisplayWindow
00158     // results in its destruction on the line display device and invalidation of the object.
00159     delete targetWindow->Window;
00160
00161     rootPage->NotifyUser("Destroyed window " + targetWindow->Id + ".", NotifyType::StatusMessage);
00162 }
00163
00164 void Scenario3_UsingWindows::DisplayTextButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00165 {
00166     invoke_async_lambda([=]() -> task<void>
00167     {
00168         WindowInfo^ targetWindow = safe_cast<WindowInfo^>(WindowsListBox->SelectedItem);
00169         if (co_await targetWindow->Window->TryDisplayTextAsync(DisplayTextTextbox->Text))
00170         {
00171             rootPage->NotifyUser("Displayed \"" + DisplayTextTextbox->Text + "\" to window " + targetWindow->Id + ".", NotifyType::StatusMessage);
00172         }
00173         else
00174         {
00175             // We probably lost our claim.
00176             rootPage->NotifyUser("Failed to display text to window " + targetWindow->Id + ".", NotifyType::ErrorMessage);
00177         }
00178     });
00179 }
Generated on Fri Nov 15 2024 22:20:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
_tileId | ScenarioElement | [private]
ButtonPinTile_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ButtonSendNotification_Click(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
Generated on Fri Nov 15 2024 22:23:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/Audio/Default/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • Audio
  • Default

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Xaml.Controls;
00002
00003 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00004
00005 namespace Notifications.ScenarioPages.Toasts.Audio.Default
00006 {
00007     /// <summary>
00008     /// An empty page that can be used on its own or navigated to within a Frame.
00009     /// </summary>
00010     public sealed partial class ScenarioElement : UserControl
00011     {
00012         public ScenarioElement()
00013         {
00014             this.InitializeComponent();
00015
00016             Initialize();
00017         }
00018
00019         private void Initialize()
00020         {
00021             // Specify the toast payload
00022             popToastControl.Payload =
00023 $@"<toast>
00024     <visual>
00025         <binding template='ToastGeneric'>
00026             <text>Default Audio Toast</text>
00027             <text>This toast's audio is not specified, and thus uses the system default.</text>
00028         </binding>
00029     </visual>
00030
00031 </toast>";
00032         }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:20:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlMasterDetail/cppwinrt/Item.cpp Source File

  • XamlMasterDetail
  • cppwinrt

Item.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/MasterDetailApp.Data.h>
00014 #include "Data.Item.g.h"
00015
00016 namespace winrt::MasterDetailApp::Data::implementation
00017 {
00018     using namespace Windows::Foundation;
00019
00020     struct Item : ItemT<Item>
00021     {
00022     public:
00023         Item(int id, DateTime dateCreated, hstring title, hstring text) :
00024             m_id{ id }, m_dateCreated{ dateCreated }, m_title{ std::move(title) }, m_text{ std::move(text) }
00025         {
00026         }
00027
00028         int ItemId() { return m_id; }
00029         void ItemId(int value) { m_id = value; }
00030
00031         Windows::Foundation::DateTime DateCreated() { return m_dateCreated; }
00032         void DateCreated(Windows::Foundation::DateTime value) { m_dateCreated = value; }
00033
00034         hstring Title() { return m_title; }
00035         void Title(hstring value) { m_title = value; }
00036
00037         hstring Text() { return m_text; }
00038         void Text(hstring value) { m_text = value; }
00039
00040     private:
00041         int m_id;
00042         Windows::Foundation::DateTime m_dateCreated;
00043         hstring m_title;
00044         hstring m_text;
00045     };
00046 }
00047
00048 namespace winrt::MasterDetailApp::Data::factory_implementation
00049 {
00050     struct Item : ItemT<Item, implementation::Item>
00051     {
00052     };
00053 }
00054
00055 #include "Data.Item.g.cpp"
Generated on Fri Nov 15 2024 22:22:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaTranscoding/cpp/Scenario3_Trim.xaml.h Source File

  • MediaTranscoding
  • cpp

Scenario3_Trim.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_Trim.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario3_Trim sealed
00024     {
00025     public:
00026         Scenario3_Trim();
00027
00028     protected:
00029         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         void GetPresetProfile(Windows::UI::Xaml::Controls::ComboBox^ comboBox);
00033         void PickFile(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void PickOutput(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035         void OnTargetFormatChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00036         void SetPickFileButton(bool isEnabled);
00037         void SetOutputFileButton(bool isEnabled);
00038         void SetTranscodeButton(bool isEnabled);
00039         void StopPlayers();
00040         void PlayFile(Windows::Storage::StorageFile^ MediaFile);
00041
00042         // Trim point setters
00043         void MarkIn(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00044         void MarkOut(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00045
00046         void TranscodeTrim(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00047         void TranscodeCancel(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048         void TranscodeProgress(Windows::Foundation::IAsyncActionWithProgress<double>^ asyncInfo, double percent);
00049         void TranscodeError(Platform::String^ error);
00050         void TranscodeFailure(Windows::Media::Transcoding::TranscodeFailureReason reason);
00051         void SetCancelButton(bool isEnabled);
00052         void EnableButtons();
00053         void DisableButtons();
00054         void EnableNonSquarePARProfiles();
00055         void DisableNonSquarePARProfiles();
00056
00057         // Media Controls
00058         void InputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00059         void InputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00060         void InputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00061         void OutputPlayButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00062         void OutputPauseButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00063         void OutputStopButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00064
00065         Platform::String^ _OutputFileName;
00066         Windows::Media::MediaProperties::MediaEncodingProfile^ _Profile;
00067         Windows::Storage::StorageFile^ _InputFile;
00068         Windows::Storage::StorageFile^ _OutputFile;
00069         Windows::Media::Transcoding::MediaTranscoder^ _Transcoder;
00070         Concurrency::cancellation_token_source _CTS;
00071
00072         Windows::Foundation::TimeSpan _start;
00073         Windows::Foundation::TimeSpan _stop;
00074
00075         Platform::String^ _OutputType;
00076         Platform::String^ _OutputFileExtension;
00077
00078         SDKTemplate::MainPage^ rootPage;
00079     };
00080 }
Generated on Fri Nov 15 2024 22:20:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/Common/DeviceResources.h Source File

  • ComplexInk
  • cpp
  • Common

DeviceResources.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include "pch.h"
00004 #include "DirectXHelper.h"
00005 #include <windows.ui.xaml.media.dxinterop.h>
00006 #include <math.h>
00007
00008 namespace DX
00009 {
00010     // Controls all the DirectX device resources.
00011     class DeviceResources
00012     {
00013     public:
00014         DeviceResources(Windows::Foundation::Size sizeContent, Windows::Foundation::Size sizeViewport);
00015         void BeginDraw(_In_opt_ const RECT* pUpdateRect = nullptr);
00016         void EndDraw();
00017         void CreateDeviceResources();
00018         void ClearTarget();
00019         void SetContentSize(Windows::Foundation::Size size);
00020         Windows::Foundation::Size GetContentSize() { return _contentSize; };
00021         void SetViewSize(Windows::Foundation::Size size);
00022         Windows::Foundation::Size GetViewSize() { return _viewSize; };
00023         void SetDPI(float dpi);
00024         float GetDPI() { return _logicalDPI; };
00025         void SetContentZoomFactor(float contentZoomFactor);
00026         float GetContentZoomFactor() { return _contentZoomFactor; };
00027         void Trim();
00028
00029         void GetUpdateRects(_Outptr_ RECT** ppUpdateRects, _Out_ ULONG* pUpdateRectsCount);
00030         void InvalidateRect(RECT const& updateRect);
00031         void InvalidateContentRect();
00032         // Ensure update rect is within content rect's boundary
00033         RECT AdjustUpdateRect(RECT const& updateRect);
00034
00035         // D3D Accessors.
00036         ID3D11Device*           GetD3DDevice() const                    { return _d3dDevice.Get(); }
00037         ID3D11DeviceContext2*   GetD3DDeviceContext() const             { return _d3dContext.Get(); }
00038
00039         // D2D Accessors.
00040         ID2D1Device*            GetD2DDevice() const                    { return _d2dDevice.Get(); }
00041         ID2D1DeviceContext*     GetD2DDeviceContext() const             { return _d2dContext.Get(); }
00042         ID2D1Factory2*          GetD2DFactory() const                   { return _d2dFactory.Get(); }
00043
00044         // VirtualSurfaceImageSource Accessors
00045         Windows::UI::Xaml::Media::Imaging::VirtualSurfaceImageSource^ GetImageSource()const { return _vsis; }
00046         Microsoft::WRL::ComPtr<IVirtualSurfaceImageSourceNative> GetImageSourceNative()const  { return _vsisNative; }
00047
00048     private:
00049         // method
00050         void InvalidateAndResizeVSIS();
00051         float ConvertFromDIPToPixelUnit(float val, bool rounded = true) {
00052             float pixelVal = val * _dpiAdjustmentRatio;
00053             return rounded? floorf(pixelVal + 0.5f) : pixelVal;
00054         };
00055         float ConvertFromPixelToDIPUnit(float val, bool rounded = true) {
00056             float dipVal = (_dpiAdjustmentRatio == 0) ? val : val / _dpiAdjustmentRatio;
00057             return rounded ? floorf(dipVal + 0.5f) : dipVal;
00058         };
00059         bool ShouldApplyContentZoomFactor(float contentZoomFactor) {
00060             return (contentZoomFactor > 0) && (_contentZoomFactor != contentZoomFactor);
00061         };
00062
00063         void RefreshScaleFactor();
00064
00065         // member variables
00066         const float DEFAULT_DPI = 96.f;
00067
00068         // Direct3D device
00069         Microsoft::WRL::ComPtr<ID3D11Device>                _d3dDevice;
00070         Microsoft::WRL::ComPtr<ID3D11DeviceContext2>        _d3dContext;
00071
00072         // Direct2D objects
00073         Microsoft::WRL::ComPtr<ID2D1Device>                 _d2dDevice;
00074         Microsoft::WRL::ComPtr<ID2D1DeviceContext>          _d2dContext;
00075         Microsoft::WRL::ComPtr<ID2D1Factory2>               _d2dFactory;
00076
00077         float                                               _logicalDPI;
00078         float                                               _dpiAdjustmentRatio;
00079         float                                               _contentZoomFactor;
00080
00081         Microsoft::WRL::ComPtr<IVirtualSurfaceImageSourceNative>        _vsisNative;
00082         Windows::UI::Xaml::Media::Imaging::VirtualSurfaceImageSource^   _vsis;
00083
00084         Windows::Foundation::Size _contentSize;
00085         Windows::Foundation::Size _viewSize;
00086
00087         bool _beginDrawStarted;
00088     };
00089 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SplashScreen/cs/common/SuspensionManager.cs Source File

  • SplashScreen
  • cs
  • common

SuspensionManager.cs

Go to the documentation of this file.
00001 using System;
00002 using System.Collections.Generic;
00003 using System.IO;
00004 using System.Linq;
00005 using System.Runtime.Serialization;
00006 using System.Text;
00007 using System.Threading.Tasks;
00008 using Windows.ApplicationModel;
00009 using Windows.Storage;
00010 using Windows.Storage.Streams;
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013
00014 namespace SDKTemplate.Common
00015 {
00016     /// <summary>
00017     /// SuspensionManager captures global session state to simplify process lifetime management
00018     /// for an application.  Note that session state will be automatically cleared under a variety
00019     /// of conditions and should only be used to store information that would be convenient to
00020     /// carry across sessions, but that should be discarded when an application crashes or is
00021     /// upgraded.
00022     /// </summary>
00023     internal sealed class SuspensionManager
00024     {
00025         private static Dictionary<string, object> _sessionState = new Dictionary<string, object>();
00026         private static List<Type> _knownTypes = new List<Type>();
00027         private const string sessionStateFilename = "_sessionState.xml";
00028
00029         /// <summary>
00030         /// Provides access to global session state for the current session.  This state is
00031         /// serialized by <see cref="SaveAsync"/> and restored by
00032         /// <see cref="RestoreAsync"/>, so values must be serializable by
00033         /// <see cref="DataContractSerializer"/> and should be as compact as possible.  Strings
00034         /// and other self-contained data types are strongly recommended.
00035         /// </summary>
00036         public static Dictionary<string, object> SessionState
00037         {
00038             get { return _sessionState; }
00039         }
00040
00041         /// <summary>
00042         /// List of custom types provided to the <see cref="DataContractSerializer"/> when
00043         /// reading and writing session state.  Initially empty, additional types may be
00044         /// added to customize the serialization process.
00045         /// </summary>
00046         public static List<Type> KnownTypes
00047         {
00048             get { return _knownTypes; }
00049         }
00050
00051         /// <summary>
00052         /// Save the current <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00053         /// registered with <see cref="RegisterFrame"/> will also preserve their current
00054         /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
00055         /// to save its state.
00056         /// </summary>
00057         /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
00058         public static async Task SaveAsync()
00059         {
00060             try
00061             {
00062                 // Save the navigation state for all registered frames
00063                 foreach (var weakFrameReference in _registeredFrames)
00064                 {
00065                     Frame frame;
00066                     if (weakFrameReference.TryGetTarget(out frame))
00067                     {
00068                         SaveFrameNavigationState(frame);
00069                     }
00070                 }
00071
00072                 // Serialize the session state synchronously to avoid asynchronous access to shared
00073                 // state
00074                 MemoryStream sessionData = new MemoryStream();
00075                 DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
00076                 serializer.WriteObject(sessionData, _sessionState);
00077
00078                 // Get an output stream for the SessionState file and write the state asynchronously
00079                 StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
00080                 using (Stream fileStream = await file.OpenStreamForWriteAsync())
00081                 {
00082                     sessionData.Seek(0, SeekOrigin.Begin);
00083                     await sessionData.CopyToAsync(fileStream);
00084                 }
00085             }
00086             catch (Exception e)
00087             {
00088                 throw new SuspensionManagerException(e);
00089             }
00090         }
00091
00092         /// <summary>
00093         /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances
00094         /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
00095         /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
00096         /// state.
00097         /// </summary>
00098         /// <param name="sessionBaseKey">An optional key that identifies the type of session.
00099         /// This can be used to distinguish between multiple application launch scenarios.</param>
00100         /// <returns>An asynchronous task that reflects when session state has been read.  The
00101         /// content of <see cref="SessionState"/> should not be relied upon until this task
00102         /// completes.</returns>
00103         public static async Task RestoreAsync(String sessionBaseKey = null)
00104         {
00105             _sessionState = new Dictionary<String, Object>();
00106
00107             try
00108             {
00109                 // Get the input stream for the SessionState file
00110                 StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename);
00111                 using (IInputStream inStream = await file.OpenSequentialReadAsync())
00112                 {
00113                     // Deserialize the Session State
00114                     DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
00115                     _sessionState = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
00116                 }
00117
00118                 // Restore any registered frames to their saved state
00119                 foreach (var weakFrameReference in _registeredFrames)
00120                 {
00121                     Frame frame;
00122                     if (weakFrameReference.TryGetTarget(out frame) && (string)frame.GetValue(FrameSessionBaseKeyProperty) == sessionBaseKey)
00123                     {
00124                         frame.ClearValue(FrameSessionStateProperty);
00125                         RestoreFrameNavigationState(frame);
00126                     }
00127                 }
00128             }
00129             catch (Exception e)
00130             {
00131                 throw new SuspensionManagerException(e);
00132             }
00133         }
00134
00135         private static DependencyProperty FrameSessionStateKeyProperty =
00136             DependencyProperty.RegisterAttached("_FrameSessionStateKey", typeof(String), typeof(SuspensionManager), null);
00137         private static DependencyProperty FrameSessionBaseKeyProperty =
00138             DependencyProperty.RegisterAttached("_FrameSessionBaseKeyParams", typeof(String), typeof(SuspensionManager), null);
00139         private static DependencyProperty FrameSessionStateProperty =
00140             DependencyProperty.RegisterAttached("_FrameSessionState", typeof(Dictionary<String, Object>), typeof(SuspensionManager), null);
00141         private static List<WeakReference<Frame>> _registeredFrames = new List<WeakReference<Frame>>();
00142
00143         /// <summary>
00144         /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
00145         /// and restored from <see cref="SessionState"/>.  Frames should be registered once
00146         /// immediately after creation if they will participate in session state management.  Upon
00147         /// registration if state has already been restored for the specified key
00148         /// the navigation history will immediately be restored.  Subsequent invocations of
00149         /// <see cref="RestoreAsync"/> will also restore navigation history.
00150         /// </summary>
00151         /// <param name="frame">An instance whose navigation history should be managed by
00152         /// <see cref="SuspensionManager"/></param>
00153         /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
00154         /// store navigation-related information.</param>
00155         /// <param name="sessionBaseKey">An optional key that identifies the type of session.
00156         /// This can be used to distinguish between multiple application launch scenarios.</param>
00157         public static void RegisterFrame(Frame frame, String sessionStateKey, String sessionBaseKey = null)
00158         {
00159             if (frame.GetValue(FrameSessionStateKeyProperty) != null)
00160             {
00161                 throw new InvalidOperationException("Frames can only be registered to one session state key");
00162             }
00163
00164             if (frame.GetValue(FrameSessionStateProperty) != null)
00165             {
00166                 throw new InvalidOperationException("Frames must be either be registered before accessing frame session state, or not registered at all");
00167             }
00168
00169             if (!string.IsNullOrEmpty(sessionBaseKey))
00170             {
00171                 frame.SetValue(FrameSessionBaseKeyProperty, sessionBaseKey);
00172                 sessionStateKey = sessionBaseKey + "_" + sessionStateKey;
00173             }
00174
00175             // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
00176             // navigation state should be managed
00177             frame.SetValue(FrameSessionStateKeyProperty, sessionStateKey);
00178             _registeredFrames.Add(new WeakReference<Frame>(frame));
00179
00180             // Check to see if navigation state can be restored
00181             RestoreFrameNavigationState(frame);
00182         }
00183
00184         /// <summary>
00185         /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
00186         /// from <see cref="SessionState"/>.  Any navigation state previously captured will be
00187         /// removed.
00188         /// </summary>
00189         /// <param name="frame">An instance whose navigation history should no longer be
00190         /// managed.</param>
00191         public static void UnregisterFrame(Frame frame)
00192         {
00193             // Remove session state and remove the frame from the list of frames whose navigation
00194             // state will be saved (along with any weak references that are no longer reachable)
00195             SessionState.Remove((String)frame.GetValue(FrameSessionStateKeyProperty));
00196             _registeredFrames.RemoveAll((weakFrameReference) =>
00197             {
00198                 Frame testFrame;
00199                 return !weakFrameReference.TryGetTarget(out testFrame) || testFrame == frame;
00200             });
00201         }
00202
00203         /// <summary>
00204         /// Provides storage for session state associated with the specified <see cref="Frame"/>.
00205         /// Frames that have been previously registered with <see cref="RegisterFrame"/> have
00206         /// their session state saved and restored automatically as a part of the global
00207         /// <see cref="SessionState"/>.  Frames that are not registered have transient state
00208         /// that can still be useful when restoring pages that have been discarded from the
00209         /// navigation cache.
00210         /// </summary>
00211         /// <remarks>Apps may choose to rely on <see cref="NavigationHelper"/> to manage
00212         /// page-specific state instead of working with frame session state directly.</remarks>
00213         /// <param name="frame">The instance for which session state is desired.</param>
00214         /// <returns>A collection of state subject to the same serialization mechanism as
00215         /// <see cref="SessionState"/>.</returns>
00216         public static Dictionary<String, Object> SessionStateForFrame(Frame frame)
00217         {
00218             var frameState = (Dictionary<String, Object>)frame.GetValue(FrameSessionStateProperty);
00219
00220             if (frameState == null)
00221             {
00222                 var frameSessionKey = (String)frame.GetValue(FrameSessionStateKeyProperty);
00223                 if (frameSessionKey != null)
00224                 {
00225                     // Registered frames reflect the corresponding session state
00226                     if (!_sessionState.ContainsKey(frameSessionKey))
00227                     {
00228                         _sessionState[frameSessionKey] = new Dictionary<String, Object>();
00229                     }
00230                     frameState = (Dictionary<String, Object>)_sessionState[frameSessionKey];
00231                 }
00232                 else
00233                 {
00234                     // Frames that aren't registered have transient state
00235                     frameState = new Dictionary<String, Object>();
00236                 }
00237                 frame.SetValue(FrameSessionStateProperty, frameState);
00238             }
00239             return frameState;
00240         }
00241
00242         private static void RestoreFrameNavigationState(Frame frame)
00243         {
00244             var frameState = SessionStateForFrame(frame);
00245             if (frameState.ContainsKey("Navigation"))
00246             {
00247                 frame.SetNavigationState((String)frameState["Navigation"]);
00248             }
00249         }
00250
00251         private static void SaveFrameNavigationState(Frame frame)
00252         {
00253             var frameState = SessionStateForFrame(frame);
00254             frameState["Navigation"] = frame.GetNavigationState();
00255         }
00256     }
00257     public class SuspensionManagerException : Exception
00258     {
00259         public SuspensionManagerException()
00260         {
00261         }
00262
00263         public SuspensionManagerException(Exception e)
00264             : base("SuspensionManager failed", e)
00265         {
00266
00267         }
00268     }
00269 }
Generated on Fri Nov 15 2024 22:18:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomSensors/cs/SampleConfiguration.cs Source File

  • CustomSensors
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using CustomSensors;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "CustomSensors";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title = "Data events", ClassType = typeof(Scenario1_DataEvents) },
00026             new Scenario() { Title = "Polling", ClassType = typeof(Scenario2_Polling) }
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/PixelShader/App.cpp Source File

  • D2DCustomEffects
  • cpp
  • PixelShader

App.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "App.h"
00014
00015 #include <ppltasks.h>
00016
00017 using namespace CustomPixelShader;
00018
00019 using namespace Windows::ApplicationModel;
00020 using namespace Windows::ApplicationModel::Core;
00021 using namespace Windows::ApplicationModel::Activation;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Graphics::Display;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::UI::Input;
00026 using namespace Windows::Storage;
00027 using namespace Windows::System;
00028
00029 using namespace concurrency;
00030
00031 // The main function is only used to initialize our IFrameworkView class.
00032 [Platform::MTAThread]
00033 int main(Platform::Array<Platform::String^>^)
00034 {
00035     auto direct3DApplicationSource = ref new Direct3DApplicationSource();
00036     CoreApplication::Run(direct3DApplicationSource);
00037     return 0;
00038 }
00039
00040 IFrameworkView^ Direct3DApplicationSource::CreateView()
00041 {
00042     return ref new App();
00043 }
00044
00045 App::App() :
00046     m_windowClosed(false),
00047     m_windowVisible(true)
00048 {
00049 }
00050
00051 // The first method called when the IFrameworkView is being created.
00052 void App::Initialize(_In_ CoreApplicationView^ applicationView)
00053 {
00054     // Register event handlers for app lifecycle. This example includes Activated, so that we
00055     // can make the CoreWindow active and start rendering on the window.
00056     applicationView->Activated +=
00057         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated);
00058
00059     CoreApplication::Suspending +=
00060         ref new EventHandler<SuspendingEventArgs^>(this, &App::OnSuspending);
00061
00062     CoreApplication::Resuming +=
00063         ref new EventHandler<Platform::Object^>(this, &App::OnResuming);
00064
00065     // At this point we have access to the device.
00066     // We can create the device-dependent resources.
00067     m_deviceResources = std::make_shared<DX::DeviceResources>();
00068 }
00069
00070 // Called when the CoreWindow object is created (or re-created).
00071 void App::SetWindow(_In_ CoreWindow^ window)
00072 {
00073     window->SizeChanged +=
00074         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &App::OnWindowSizeChanged);
00075
00076     window->VisibilityChanged +=
00077         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &App::OnVisibilityChanged);
00078
00079     window->Closed +=
00080         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::OnWindowClosed);
00081
00082     window->PointerPressed +=
00083         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerPressed);
00084
00085     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00086
00087     currentDisplayInformation->DpiChanged +=
00088         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDpiChanged);
00089
00090     currentDisplayInformation->OrientationChanged +=
00091         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnOrientationChanged);
00092
00093     DisplayInformation::DisplayContentsInvalidated +=
00094         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDisplayContentsInvalidated);
00095
00096     // Disable all pointer visual feedback for better performance when touching.
00097     auto pointerVisualizationSettings = PointerVisualizationSettings::GetForCurrentView();
00098     pointerVisualizationSettings->IsContactFeedbackEnabled = false;
00099     pointerVisualizationSettings->IsBarrelButtonFeedbackEnabled = false;
00100
00101     m_deviceResources->SetWindow(window);
00102 }
00103
00104 // Initializes scene resources, or loads a previously saved app state.
00105 void App::Load(_In_ Platform::String^ entryPoint)
00106 {
00107     if (m_main == nullptr)
00108     {
00109         m_main = std::unique_ptr<CustomPixelShaderMain>(new CustomPixelShaderMain(m_deviceResources));
00110     }
00111 }
00112
00113 // This method is called after the window becomes active.
00114 void App::Run()
00115 {
00116     while (!m_windowClosed)
00117     {
00118         if (m_windowVisible)
00119         {
00120             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00121
00122             m_main->Update();
00123
00124             if (m_main->Render())
00125             {
00126                 m_deviceResources->Present();
00127             }
00128         }
00129         else
00130         {
00131             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00132         }
00133     }
00134 }
00135
00136 // Required for IFrameworkView.
00137 // Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
00138 // class is torn down while the app is in the foreground.
00139 void App::Uninitialize()
00140 {
00141 }
00142
00143 // Application lifecycle event handlers.
00144
00145 void App::OnActivated(_In_ CoreApplicationView^ applicationView, _In_ IActivatedEventArgs^ args)
00146 {
00147     // Run() won't start until the CoreWindow is activated.
00148     CoreWindow::GetForCurrentThread()->Activate();
00149 }
00150
00151 void App::OnSuspending(_In_ Platform::Object^ sender, _In_ SuspendingEventArgs^ args)
00152 {
00153     // Save app state asynchronously after requesting a deferral. Holding a deferral
00154     // indicates that the application is busy performing suspending operations. Be
00155     // aware that a deferral may not be held indefinitely. After about five seconds,
00156     // the app will be forced to exit.
00157     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
00158
00159     create_task([this, deferral]()
00160     {
00161         m_deviceResources->Trim();
00162
00163         m_main->SaveInternalState(ApplicationData::Current->LocalSettings->Values);
00164
00165         deferral->Complete();
00166     });
00167 }
00168
00169 void App::OnResuming(_In_ Platform::Object^ sender, _In_ Platform::Object^ args)
00170 {
00171     // Restore any data or state that was unloaded on suspend. By default, data
00172     // and state are persisted when resuming from suspend. Note that this event
00173     // does not occur if the app was previously terminated.
00174
00175     m_main->LoadInternalState(ApplicationData::Current->LocalSettings->Values);
00176 }
00177
00178 // Window event handlers.
00179
00180 void App::OnWindowSizeChanged(_In_ CoreWindow^ sender, _In_ WindowSizeChangedEventArgs^ args)
00181 {
00182     m_deviceResources->SetLogicalSize(Size(sender->Bounds.Width, sender->Bounds.Height));
00183     m_main->CreateWindowSizeDependentResources();
00184 }
00185
00186 void App::OnVisibilityChanged(_In_ CoreWindow^ sender, _In_ VisibilityChangedEventArgs^ args)
00187 {
00188     m_windowVisible = args->Visible;
00189 }
00190
00191 void App::OnWindowClosed(_In_ CoreWindow^ sender, _In_ CoreWindowEventArgs^ args)
00192 {
00193     m_windowClosed = true;
00194 }
00195
00196 void App::OnPointerPressed(_In_ CoreWindow^ sender, _In_ PointerEventArgs^ args)
00197 {
00198     m_main->UpdatePointer(args);
00199 }
00200
00201 // DisplayInformation event handlers.
00202
00203 void App::OnDpiChanged(_In_ DisplayInformation^ sender, _In_ Object^ args)
00204 {
00205     m_deviceResources->SetDpi(sender->LogicalDpi);
00206     m_main->CreateWindowSizeDependentResources();
00207 }
00208
00209 void App::OnOrientationChanged(_In_ DisplayInformation^ sender, _In_ Object^ args)
00210 {
00211     m_deviceResources->SetCurrentOrientation(sender->CurrentOrientation);
00212     m_main->CreateWindowSizeDependentResources();
00213 }
00214
00215 void App::OnDisplayContentsInvalidated(_In_ DisplayInformation^ sender, _In_ Object^ args)
00216 {
00217     m_deviceResources->ValidateDevice();
00218 }
Generated on Fri Nov 15 2024 22:18:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProximitySensor/cpp/Scenario1_DataEvents.xaml.cpp Source File

  • ProximitySensor
  • cpp

Scenario1_DataEvents.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_DataEvents.xaml.cpp
00014 // Implementation of the Scenario1_DataEvents class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario1_DataEvents.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Windows::Devices::Enumeration;
00024 using namespace Windows::Devices::Sensors;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Globalization::DateTimeFormatting;
00027 using namespace Windows::UI::Core;
00028 using namespace Windows::UI::Xaml;
00029 using namespace Windows::UI::Xaml::Controls;
00030 using namespace Windows::UI::Xaml::Navigation;
00031
00032 Scenario1_DataEvents::Scenario1_DataEvents() : rootPage(MainPage::Current)
00033 {
00034     InitializeComponent();
00035
00036     watcher = DeviceInformation::CreateWatcher(ProximitySensor::GetDeviceSelector());
00037     watcher->Added += ref new TypedEventHandler<DeviceWatcher^, DeviceInformation^>(this, &Scenario1_DataEvents::OnProximitySensorAdded);
00038     watcher->Start();
00039 }
00040
00041 /// <summary>
00042 /// Invoked when the device watcher finds a proximity sensor
00043 /// </summary>
00044 /// <param name="sender">The device watcher</param>
00045 /// <param name="device">Device information for the proximity sensor that was found</param>
00046 void Scenario1_DataEvents::OnProximitySensorAdded(DeviceWatcher^ /*sender*/, DeviceInformation^ device)
00047 {
00048     if (nullptr == sensor)
00049     {
00050         ProximitySensor^ foundSensor = ProximitySensor::FromId(device->Id);
00051         if (nullptr != foundSensor)
00052         {
00053             if (nullptr != foundSensor->MaxDistanceInMillimeters)
00054             {
00055                 // Check if this is the sensor that matches our ranges.
00056
00057                 // TODO: Customize these values to your application's needs.
00058                 // Here, we are looking for a sensor that can detect close objects
00059                 // up to 3cm away, so we check the upper bound of the detection range.
00060                 const unsigned int distanceInMillimetersLValue = 30; // 3 cm
00061                 const unsigned int distanceInMillimetersRValue = 50; // 5 cm
00062
00063                 if (foundSensor->MaxDistanceInMillimeters->Value >= distanceInMillimetersLValue &&
00064                     foundSensor->MaxDistanceInMillimeters->Value <= distanceInMillimetersRValue)
00065                 {
00066                     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00067                     {
00068                         rootPage->NotifyUser("Found a proximity sensor that meets the detection range", NotifyType::StatusMessage);
00069                     }, CallbackContext::Any));
00070                 }
00071                 else
00072                 {
00073                     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00074                     {
00075                         // We'll use the sensor anyway, to demonstrate how events work.
00076                         // Your app may decide not to use the sensor.
00077                         rootPage->NotifyUser("Proximity sensor does not meet the detection range, using it anyway", NotifyType::StatusMessage);
00078                     }, CallbackContext::Any));
00079                 }
00080             }
00081             else
00082             {
00083                 Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00084                 {
00085                     rootPage->NotifyUser("Proximity sensor does not report detection ranges, using it anyway", NotifyType::StatusMessage);
00086                 }, CallbackContext::Any));
00087             }
00088
00089             if (nullptr != foundSensor)
00090             {
00091                 sensor = foundSensor;
00092             }
00093         }
00094         else
00095         {
00096             Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00097             {
00098                 rootPage->NotifyUser("Could not get a proximity sensor from the device id", NotifyType::ErrorMessage);
00099             }, CallbackContext::Any));
00100         }
00101     }
00102 }
00103
00104 /// <summary>
00105 /// Invoked when this page is about to be displayed in a Frame.
00106 /// </summary>
00107 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00108 /// property is typically used to configure the page.</param>
00109 void Scenario1_DataEvents::OnNavigatedTo(NavigationEventArgs^ e)
00110 {
00111     ScenarioEnableButton->IsEnabled = true;
00112     ScenarioDisableButton->IsEnabled = false;
00113 }
00114
00115 /// <summary>
00116 /// Invoked when this page is no longer displayed.
00117 /// </summary>
00118 /// <param name="e"></param>
00119 void Scenario1_DataEvents::OnNavigatedFrom(NavigationEventArgs^ e)
00120 {
00121     // If the navigation is external to the app do not clean up.
00122     // This can occur on Phone when suspending the app.
00123     if (NavigationMode::Forward == e->NavigationMode && nullptr == e->Uri)
00124     {
00125         return;
00126     }
00127
00128     if (ScenarioDisableButton->IsEnabled)
00129     {
00130         sensor->ReadingChanged::remove(readingToken);
00131     }
00132 }
00133
00134 void Scenario1_DataEvents::ReadingChanged(ProximitySensor^ sender, ProximitySensorReadingChangedEventArgs^ e)
00135 {
00136     // We need to dispatch to the UI thread to display the output
00137     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, e]()
00138     {
00139         ProximitySensorReading^ reading = e->Reading;
00140         if (nullptr != reading)
00141         {
00142             ScenarioOutput_DetectionState->Text = reading->IsDetected ? "Detected" : "Not detected";
00143
00144             auto timestampFormatter = ref new DateTimeFormatter("day month year hour minute second");
00145             ScenarioOutput_Timestamp->Text = timestampFormatter->Format(reading->Timestamp);
00146
00147             // Show the detection distance, if available
00148             if (nullptr != reading->DistanceInMillimeters)
00149             {
00150                 ScenarioOutput_DetectionDistance->Text = reading->DistanceInMillimeters->Value.ToString();
00151             }
00152         }
00153     }, CallbackContext::Any));
00154 }
00155
00156 /// <summary>
00157 /// This is the click handler for the 'Enable' button.
00158 /// </summary>
00159 /// <param name="sender"></param>
00160 /// <param name="e"></param>
00161 void Scenario1_DataEvents::ScenarioEnable(Object^ sender, RoutedEventArgs^ e)
00162 {
00163     if (nullptr != sensor)
00164     {
00165         // Establish the report interval
00166         readingToken = sensor->ReadingChanged::add(ref new TypedEventHandler<ProximitySensor^, ProximitySensorReadingChangedEventArgs^>(this, &Scenario1_DataEvents::ReadingChanged));
00167
00168         ScenarioEnableButton->IsEnabled = false;
00169         ScenarioDisableButton->IsEnabled = true;
00170     }
00171     else
00172     {
00173         rootPage->NotifyUser("No proximity sensor found", NotifyType::ErrorMessage);
00174     }
00175 }
00176
00177 /// <summary>
00178 /// This is the click handler for the 'Disable' button.
00179 /// </summary>
00180 /// <param name="sender"></param>
00181 /// <param name="e"></param>
00182 void Scenario1_DataEvents::ScenarioDisable(Object^ sender, RoutedEventArgs^ e)
00183 {
00184     sensor->ReadingChanged::remove(readingToken);
00185
00186     ScenarioEnableButton->IsEnabled = true;
00187     ScenarioDisableButton->IsEnabled = false;
00188 }
Generated on Fri Nov 15 2024 22:17:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Inclinometer/cs/CalibrationBar.xaml.cs Source File

  • Inclinometer
  • cs

CalibrationBar.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.IO;
00015 using System.Linq;
00016 using System.Runtime.InteropServices.WindowsRuntime;
00017 using Windows.Foundation;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Controls.Primitives;
00021 using Windows.UI.Xaml.Data;
00022 using Windows.UI.Xaml.Input;
00023 using Windows.UI.Xaml.Media;
00024 using Windows.UI.Xaml.Media.Imaging;
00025 using Windows.UI.Xaml.Navigation;
00026 using Windows.Devices.Sensors;
00027
00028 namespace Microsoft.Samples.Devices.Sensors.Calibration
00029 {
00030     public sealed partial class CalibrationBar : Page
00031     {
00032         // Constants specifying when the calibration bar is shown:
00033         //   * suppress duration determines how long (in minutes) to wait before
00034         //     showing the calibration bar again
00035         //   * auto dismiss time determines when to auto dismiss the bar
00036         //     if it's shown too long
00037         private const double SUPPRESS_DURATION_APPROXIMATE_MIN = 10.0;
00038         private const double SUPPRESS_DURATION_UNRELIABLE_MIN = 5.0;
00039         private TimeSpan CALIBRATION_POPUP_AUTO_DIMSMISS_TIME = new TimeSpan(0, 0, 30); // 30 seconds
00040
00041         private const double LAYOUT_WIDTH_768 = 768.0;
00042
00043         private DateTime _lastCalibrationTime = new DateTime(0);
00044         private bool _barDismissed = false;
00045         private DispatcherTimer _calibrationTimer;
00046
00047         public CalibrationBar()
00048         {
00049             this.InitializeComponent();
00050             _calibrationTimer = new DispatcherTimer();
00051             _calibrationTimer.Tick += OnAutoDismissTimerExpired;
00052             _calibrationTimer.Interval = CALIBRATION_POPUP_AUTO_DIMSMISS_TIME;
00053         }
00054
00055         /// <summary>
00056         /// Called when the application would like to show the calibration bar to the user
00057         /// to improve sensor accuracy.
00058         /// </summary>
00059         /// <param name="accuracy">Current accuracy of the sensor.</param>
00060         public void RequestCalibration(MagnetometerAccuracy accuracy)
00061         {
00062             // Only show the calibration bar if it is hidden and sufficient
00063             // time has passed since it was last hidden.
00064             if (!CalibrationPopup.IsOpen && CanShowCalibrationBar(accuracy))
00065             {
00066                 InvalidateLayout();
00067                 Window.Current.SizeChanged += OnWindowSizeChanged;
00068                 HideGuidance(); // Calibration image hidden by default
00069                 CalibrationPopup.IsOpen = true;
00070                 _calibrationTimer.Start();
00071             }
00072         }
00073
00074         /// <summary>
00075         /// Called when sensor accuracy is sufficient and the application would like to
00076         /// hide the calibration bar.
00077         /// </summary>
00078         public void Hide()
00079         {
00080             if (CalibrationPopup.IsOpen)
00081             {
00082                 // Hide the calibration bar and save the current time.
00083                 _lastCalibrationTime = DateTime.Now;
00084                 HideGuidance();
00085                 CalibrationPopup.IsOpen = false;
00086                 Window.Current.SizeChanged -= OnWindowSizeChanged;
00087                 _calibrationTimer.Stop();
00088             }
00089         }
00090
00091         /// <summary>
00092         /// Invoked when the window size is updated.
00093         /// </summary>
00094         /// <param name="sender">Instance that triggered the event.</param>
00095         /// <param name="e">Event data describing the conditions that led to the event.</param>
00096         void OnWindowSizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
00097         {
00098             InvalidateLayout();
00099         }
00100
00101         /// <summary>
00102         /// Updates the calibration bar layout based on the current window width.
00103         /// </summary>
00104         private void InvalidateLayout()
00105         {
00106             CalibrationGrid.Width = Window.Current.Bounds.Width;
00107
00108             if (CalibrationGrid.Width < LAYOUT_WIDTH_768)
00109             {
00110                 Grid.SetRow(DismissPopup, 1);
00111                 Grid.SetColumn(DismissPopup, 1);
00112
00113                 CalibrationGridTop.Margin = new Thickness(0, 24, 20, 15);
00114                 DismissPopup.Margin = new Thickness(66, 15, 0, 0);
00115             }
00116             else
00117             {
00118                 Grid.SetRow(DismissPopup, 0);
00119                 Grid.SetColumn(DismissPopup, 2);
00120
00121                 CalibrationGridTop.Margin = new Thickness(0, 19, 66, 19);
00122                 DismissPopup.Margin = new Thickness(66, 0, 0, 0);
00123             }
00124         }
00125
00126         /// <summary>
00127         /// Called to determine if sufficient time has passed since the calibration bar
00128         /// was hidden to show the calibration bar again. This suppression time is
00129         /// dependent on the current sensor accuracy.
00130         /// </summary>
00131         /// <param name="accuracy">Current accuracy of the sensor.</param>
00132         private bool CanShowCalibrationBar(MagnetometerAccuracy accuracy)
00133         {
00134             bool showBar = false;
00135             if (!_barDismissed)
00136             {
00137                 if ((accuracy == MagnetometerAccuracy.Approximate) &&
00138                     (DateTime.Now.CompareTo(_lastCalibrationTime.AddMinutes(SUPPRESS_DURATION_APPROXIMATE_MIN)) >= 0))
00139                 {
00140                     showBar = true;
00141                 }
00142                 else if ((accuracy == MagnetometerAccuracy.Unreliable) &&
00143                     (DateTime.Now.CompareTo(_lastCalibrationTime.AddMinutes(SUPPRESS_DURATION_UNRELIABLE_MIN)) >= 0))
00144                 {
00145                     showBar = true;
00146                 }
00147             }
00148             return showBar;
00149         }
00150
00151         /// <summary>
00152         /// This is the click handler for the show guidance button.
00153         /// </summary>
00154         /// <param name="sender"></param>
00155         /// <param name="e"></param>
00156         private void ShowGuidanceButton_Click(object sender, RoutedEventArgs e)
00157         {
00158             if (Guidance.Visibility == Windows.UI.Xaml.Visibility.Collapsed)
00159             {
00160                 ShowGuidance();
00161             }
00162         }
00163
00164         /// <summary>
00165         /// This is the click handler for the hide guidance button.
00166         /// </summary>
00167         /// <param name="sender"></param>
00168         /// <param name="e"></param>
00169         private void HideGuidanceButton_Click(object sender, RoutedEventArgs e)
00170         {
00171             if (Guidance.Visibility == Windows.UI.Xaml.Visibility.Visible)
00172             {
00173                 HideGuidance();
00174             }
00175         }
00176
00177         /// <summary>
00178         /// This is the click handler for the dismiss popup button. It hides the
00179         /// calibration bar and prevents it from being shown again for the lifetime
00180         /// of the app.
00181         /// </summary>
00182         /// <param name="sender"></param>
00183         /// <param name="e"></param>
00184         private void DismissPopup_Click(object sender, RoutedEventArgs e)
00185         {
00186             // Don't show the calibration bar again.
00187             _barDismissed = true;
00188             Hide();
00189         }
00190
00191         /// <summary>
00192         /// Expands the calibration bar to show the calibration image to the user.
00193         /// </summary>
00194         /// <param name="sender"></param>
00195         /// <param name="e"></param>
00196         private void ShowGuidance()
00197         {
00198             ShowGuidanceButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00199             HideGuidanceButton.Visibility = Windows.UI.Xaml.Visibility.Visible;
00200             Guidance.Visibility = Windows.UI.Xaml.Visibility.Visible;
00201         }
00202
00203         /// <summary>
00204         /// Collapses the calibration bar to hide the calibration image from the user.
00205         /// </summary>
00206         /// <param name="sender"></param>
00207         /// <param name="e"></param>
00208         private void HideGuidance()
00209         {
00210             HideGuidanceButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00211             ShowGuidanceButton.Visibility = Windows.UI.Xaml.Visibility.Visible;
00212             Guidance.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00213         }
00214
00215         /// <summary>
00216         /// This is the handler for the auto dismiss timer. After the calibraiton bar
00217         /// has been shown for the maximum time, it is automatically hidden.
00218         /// </summary>
00219         /// <param name="sender"></param>
00220         /// <param name="e"></param>
00221         private void OnAutoDismissTimerExpired(object sender, object e)
00222         {
00223             Hide();
00224         }
00225     }
00226 }
Generated on Fri Nov 15 2024 22:18:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PlaybackService Member List

This is the complete list of members for PlaybackService, including all inherited members.
CurrentPlaylist | PlaybackService |
instance | PlaybackService | [private, static]
Instance | PlaybackService | [static]
PlaybackService() | PlaybackService | [inline]
Player | PlaybackService |
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundSensors/cpp/SampleConfiguration.cpp Source File

  • BackgroundSensors
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Accelerometer DeviceUse", "SDKTemplate.Scenario1_DeviceUse" }
00012 };
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

WordOverlay Member List

This is the complete list of members for WordOverlay, including all inherited members.
CreateBinding(string propertyName) | WordOverlay | [private]
CreateBorder(Style style, UIElement child=null) | WordOverlay | [inline]
OnPropertyChanged(string PropertyName) | WordOverlay | [inline, protected]
PropertyChanged | WordOverlay |
Transform(ScaleTransform scale) | WordOverlay | [inline]
UpdateProps(Rect wordBoundingBox) | WordOverlay | [inline, private]
word | WordOverlay | [private]
wordBoundingRect | WordOverlay | [private]
WordHeight | WordOverlay |
WordOverlay(OcrWord ocrWord) | WordOverlay | [inline]
WordPosition | WordOverlay |
WordWidth | WordOverlay |
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario05_PostStream Member List

This is the complete list of members for Scenario05_PostStream, including all inherited members.
Cancel_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario05_PostStream |
CancelableRequestAsync(Windows::Web::Http::HttpRequestMessage request) | Scenario05_PostStream | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario05_PostStream |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario05_PostStream |
Scenario05_PostStream() | Scenario05_PostStream |
Start_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario05_PostStream |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppWindow/cppwinrt/Scenario1_SecondaryWindow.cpp Source File

  • AppWindow
  • cppwinrt

Scenario1_SecondaryWindow.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_SecondaryWindow.h"
00014 #include "Scenario1_SecondaryWindow.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::UI::WindowManagement;
00019 using namespace Windows::UI::Xaml;
00020 using namespace Windows::UI::Xaml::Hosting;
00021 using namespace Windows::UI::Xaml::Navigation;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario1_SecondaryWindow::Scenario1_SecondaryWindow()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     fire_and_forget Scenario1_SecondaryWindow::OnNavigatedFrom(NavigationEventArgs const&)
00031     {
00032         if (appWindow != nullptr)
00033         {
00034             co_await appWindow.CloseAsync();
00035         }
00036     }
00037
00038     fire_and_forget Scenario1_SecondaryWindow::Button_Click(IInspectable const&, RoutedEventArgs const&)
00039     {
00040         auto lifetime = get_strong();
00041
00042         showWindowBtn().IsEnabled(false);
00043
00044         // Only ever create one window. If the AppWindow already exists call TryShow on it to bring it to foreground.
00045         if (appWindow == nullptr)
00046         {
00047             // Create a new window
00048             appWindow = co_await AppWindow::TryCreateAsync();
00049             // Clean up when the window is closed
00050             appWindow.Closed({ get_weak(), &Scenario1_SecondaryWindow::OnWindowClosed });
00051             // Navigate the frame to the page we want to show in the new window
00052             appWindowFrame.Navigate(xaml_typename<SDKTemplate::SecondaryAppWindowPage>());
00053             // Attach the XAML content to our window
00054             ElementCompositionPreview::SetAppWindowContent(appWindow, appWindowFrame);
00055         }
00056
00057         // Now show the window
00058         co_await appWindow.TryShowAsync();
00059
00060         showWindowBtn().IsEnabled(true);
00061     }
00062
00063     void Scenario1_SecondaryWindow::OnWindowClosed(AppWindow const&, IInspectable const&)
00064     {
00065         // Make sure we release the reference to this window, and release XAML resources.
00066         appWindow = nullptr;
00067         appWindowFrame.Content(nullptr);
00068     }
00069
00070 }
Generated on Fri Nov 15 2024 22:18:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cpp/WiFiDirectServicesManager.cpp Source File

  • WiFiDirectServices
  • cpp

WiFiDirectServicesManager.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "WiFiDirectServicesManager.h"
00014
00015 #include "Scenario1_AdvertiserCreate.xaml.h"
00016 #include "Scenario2_AdvertiserAccept.xaml.h"
00017 #include "Scenario3_SeekerDiscover.xaml.h"
00018 #include "Scenario4_SeekerSession.xaml.h"
00019 #include "Scenario5_SendData.xaml.h"
00020
00021 using namespace SDKTemplate;
00022 using namespace SDKTemplate::WiFiDirectServices;
00023 using namespace Concurrency;
00024 using namespace Platform;
00025 using namespace Platform::Collections;
00026 using namespace Windows::Devices::Enumeration;
00027 using namespace Windows::Devices::WiFiDirect::Services;
00028 using namespace Windows::Foundation::Collections;
00029 using namespace Windows::Storage::Streams;
00030 using namespace Windows::UI::Core;
00031 using namespace std;
00032
00033 WiFiDirectServiceManager^ WiFiDirectServiceManager::_instance = nullptr;
00034
00035 WiFiDirectServiceManager::WiFiDirectServiceManager()
00036 {
00037     _rootPage = MainPage::Current;
00038 }
00039
00040 WiFiDirectServiceManager^ WiFiDirectServiceManager::Instance::get()
00041 {
00042     if (_instance == nullptr)
00043     {
00044         _instance = ref new WiFiDirectServiceManager();
00045     }
00046     return _instance;
00047 }
00048
00049 MainPage^ WiFiDirectServiceManager::RootPage::get()
00050 {
00051     if (_rootPage == nullptr)
00052     {
00053         _rootPage = MainPage::Current;
00054     }
00055     return _rootPage;
00056 }
00057
00058 void WiFiDirectServiceManager::NotifyUser(String ^ strMessage, NotifyType type)
00059 {
00060     // Always dispatch to UI thread
00061     _rootPage->Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
00062         ref new DispatchedHandler([this, strMessage, type]()
00063         {
00064             _rootPage->NotifyUser(strMessage, type);
00065         }));
00066 }
00067
00068 void WiFiDirectServiceManager::StartAdvertisement(
00069     String^ serviceName,
00070     bool autoAccept,
00071     bool preferGO,
00072     String^ pin,
00073     IVector<WiFiDirectServiceConfigurationMethod>^ configMethods,
00074     WiFiDirectServiceStatus status,
00075     unsigned int customStatus,
00076     String^ serviceInfo,
00077     String^ deferredServiceInfo,
00078     IVector<String^>^ prefixList
00079     )
00080 {
00081     // Create Advertiser object for the service
00082     // NOTE: service name is internally limited to up to 255 bytes in UTF-8 encoding
00083     // Valid characters include alpha-numeric, '.', '-', and any multi-byte character
00084     // characters a-z, A-Z are case-insensitive when discovering services
00085     WiFiDirectServiceAdvertiser^ advertiser = ref new WiFiDirectServiceAdvertiser(serviceName);
00086
00087     // Auto-accept services will connect without interaction from advertiser
00088     // NOTE: if the config method used for a connection requires a PIN, then the advertiser will have to accept the connection
00089     advertiser->AutoAcceptSession = autoAccept;
00090
00091     // Set the Group Owner intent to a large value so that the advertiser will try to become the group owner (GO)
00092     // NOTE: The GO of a P2P connection can connect to multiple clients while the client can connect to a single GO only
00093     advertiser->PreferGroupOwnerMode = preferGO;
00094
00095     // Default status is "Available", but services may use a custom status code (value > 1) if applicable
00096     advertiser->ServiceStatus = status;
00097     advertiser->CustomServiceStatusCode = customStatus;
00098
00099     // Service information can be up to 65000 bytes.
00100     // Service Seeker may explicitly discover this by specifying a short buffer that is a subset of this buffer.
00101     // If seeker portion matches, then entire buffer is returned, otherwise, the service information is not returned to the seeker
00102     // This sample uses a string for the buffer but it can be any data
00103     if (serviceInfo != nullptr && serviceInfo->Length() > 0)
00104     {
00105         auto serviceInfoDataWriter = ref new DataWriter(ref new InMemoryRandomAccessStream());
00106         serviceInfoDataWriter->WriteString(serviceInfo);
00107         advertiser->ServiceInfo = serviceInfoDataWriter->DetachBuffer();
00108     }
00109     else
00110     {
00111         advertiser->ServiceInfo = nullptr;
00112     }
00113
00114     // This is a buffer of up to 144 bytes that is sent to the seeker in case the connection is "deferred" (i.e. not auto-accepted)
00115     // This buffer will be sent when auto-accept is false, or if a PIN is required to complete the connection
00116     // For the sample, we use a string, but it can contain any data
00117     if (deferredServiceInfo != nullptr && deferredServiceInfo->Length() > 0)
00118     {
00119         auto deferredSessionInfoDataWriter = ref new DataWriter(ref new InMemoryRandomAccessStream());
00120         deferredSessionInfoDataWriter->WriteString(deferredServiceInfo);
00121         advertiser->DeferredSessionInfo = deferredSessionInfoDataWriter->DetachBuffer();
00122     }
00123     else
00124     {
00125         advertiser->DeferredSessionInfo = nullptr;
00126     }
00127
00128     // The advertiser supported configuration methods
00129     // Valid values are PIN-only (either keypad entry, display, or both), or PIN (keypad entry, display, or both) and WFD Services default
00130     // WFD Services Default config method does not require explicit PIN entry and offers a more seamless connection experience
00131     // Typically, an advertiser will support PIN display (and WFD Services Default), and a seeker will connect with either PIN entry or WFD Services Default
00132     if (configMethods != nullptr)
00133     {
00134         advertiser->PreferredConfigurationMethods->Clear();
00135         for (auto&& configMethod : configMethods)
00136         {
00137             advertiser->PreferredConfigurationMethods->Append(configMethod);
00138         }
00139     }
00140
00141     // Advertiser may also be discoverable by a prefix of the service name. Must explicitly specify prefixes allowed here.
00142     if (prefixList != nullptr && prefixList->Size > 0)
00143     {
00144         advertiser->ServiceNamePrefixes->Clear();
00145         for (auto&& prefix : prefixList)
00146         {
00147             advertiser->ServiceNamePrefixes->Append(prefix);
00148         }
00149     }
00150
00151     // For this sample, we wrap the advertiser in our own object which handles the advertiser events
00152     AdvertisementWrapper^ advertiserWrapper = ref new AdvertisementWrapper(advertiser, this, pin);
00153
00154     AddAdvertiser(advertiserWrapper);
00155
00156     RootPage->NotifyUser("Starting service...", NotifyType::StatusMessage);
00157
00158     try
00159     {
00160         // This may fail if the driver is unable to handle the request or if services is not supported
00161         // NOTE: this must be called from the UI thread of the app
00162         advertiser->Start();
00163     }
00164     catch (Exception^ ex)
00165     {
00166         RootPage->NotifyUser("Failed to start service: " + ex->Message, NotifyType::ErrorMessage);
00167         throw;
00168     }
00169 }
00170
00171 void WiFiDirectServiceManager::UnpublishService(unsigned int index)
00172 {
00173     AdvertisementWrapper^ advertiser = nullptr;
00174
00175     {
00176         lock_guard<mutex> lock(_managerMutex);
00177         if (index > _advertisers->Size - 1)
00178         {
00179             throw ref new OutOfBoundsException("Attempted to stop service not found in list");
00180         }
00181
00182         advertiser = _advertisers->GetAt(index);
00183     }
00184
00185     try
00186     {
00187         advertiser->Advertiser->Stop();
00188     }
00189     catch (Exception^ ex)
00190     {
00191         RootPage->NotifyUser("Stop Advertisement Failed: " + ex->Message, NotifyType::ErrorMessage);
00192     }
00193 }
00194
00195 void WiFiDirectServiceManager::DiscoverServicesAsync(String^ serviceName, String^ requestedServiceInfo)
00196 {
00197     RootPage->NotifyUser("Discover services... (name='" + serviceName + "', requestedInfo='" + requestedServiceInfo + "')", NotifyType::StatusMessage);
00198
00199     // Clear old results
00200     _discoveredDevices->Clear();
00201
00202     // Discovery depends on whether service information is requested
00203     String^ serviceSelector = "";
00204     if (requestedServiceInfo == "")
00205     {
00206         // Just search by name
00207         serviceSelector = WiFiDirectService::GetSelector(serviceName);
00208     }
00209     else
00210     {
00211         auto serviceInfoDataWriter = ref new DataWriter(ref new InMemoryRandomAccessStream());
00212         serviceInfoDataWriter->WriteString(requestedServiceInfo);
00213         // Discover by name and try to discover service information
00214         serviceSelector = WiFiDirectService::GetSelector(serviceName, serviceInfoDataWriter->DetachBuffer());
00215     }
00216
00217     auto additionalProperties = ref new Vector<String^>();
00218     additionalProperties->Append("System.Devices.WiFiDirectServices.ServiceAddress");
00219     additionalProperties->Append("System.Devices.WiFiDirectServices.ServiceName");
00220     additionalProperties->Append("System.Devices.WiFiDirectServices.ServiceInformation");
00221     additionalProperties->Append("System.Devices.WiFiDirectServices.AdvertisementId");
00222     additionalProperties->Append("System.Devices.WiFiDirectServices.ServiceConfigMethods");
00223
00224     // Note: This sample demonstrates finding services with FindAllAsync, which does a discovery and returns a list
00225     // It is also possible to use DeviceWatcher to receive updates as soon as services are found and to continue the discovery until it is stopped
00226     // See the DeviceWatcher sample for an example on how to use that class instead of DeviceInformation.FindAllAsync
00227     create_task(DeviceInformation::FindAllAsync(serviceSelector, additionalProperties)).then([this](DeviceInformationCollection^ deviceInfoCollection)
00228     {
00229         if (deviceInfoCollection != nullptr && deviceInfoCollection->Size > 0)
00230         {
00231             NotifyUser("Done discovering services, found " + deviceInfoCollection->Size + " services", NotifyType::StatusMessage);
00232
00233             for (auto&& device : deviceInfoCollection)
00234             {
00235                 _discoveredDevices->Append(ref new DiscoveredDeviceWrapper(device, this));
00236             }
00237         }
00238         else
00239         {
00240             NotifyUser("Done discovering services, No services found", NotifyType::StatusMessage);
00241         }
00242
00243         // Update UI list
00244         if (_scenario3 != nullptr)
00245         {
00246             _scenario3->UpdateDiscoveryList(_discoveredDevices);
00247         }
00248     }).then([this](task<void> previousTask)
00249     {
00250         try
00251         {
00252             // Try getting all exceptions from the continuation chain above this point.
00253             previousTask.get();
00254         }
00255         catch (Exception^ ex)
00256         {
00257             NotifyUser("FindAllAsync Failed: " + ex->Message, NotifyType::ErrorMessage);
00258         }
00259     });
00260 }
00261
00262 void WiFiDirectServiceManager::RemoveAdvertiser(AdvertisementWrapper^ advertiser)
00263 {
00264     unsigned int index = 0;
00265     bool fFound = false;
00266
00267     {
00268         lock_guard<mutex> lock(_managerMutex);
00269         // Lookup the index
00270         for (auto&& a : _advertisers)
00271         {
00272             if (a->InternalId == advertiser->InternalId)
00273             {
00274                 fFound = true;
00275                 break;
00276             }
00277             ++index;
00278         }
00279     }
00280
00281     if (fFound)
00282     {
00283         RemoveAdvertiser(index);
00284     }
00285     else
00286     {
00287         NotifyUser("Advertiser not found in list", NotifyType::ErrorMessage);
00288     }
00289 }
00290
00291 void WiFiDirectServiceManager::AddSessionRequest(WiFiDirectServiceSessionRequest^ request, AdvertisementWrapper^ advertiser)
00292 {
00293     // Update UI to add this to list
00294     if (_scenario2 != nullptr)
00295     {
00296         _scenario2->AddSessionRequest(request, advertiser);
00297     }
00298 }
00299
00300 void WiFiDirectServiceManager::RemoveSessionRequest(WiFiDirectServiceSessionRequest^ request, AdvertisementWrapper^ advertiser)
00301 {
00302     // Update UI to remove from list
00303     if (_scenario2 != nullptr)
00304     {
00305         _scenario2->RemoveSessionRequest(request, advertiser);
00306     }
00307 }
00308
00309 void WiFiDirectServiceManager::AdvertiserStatusChanged(AdvertisementWrapper^ advertiser)
00310 {
00311     if (advertiser->Advertiser->AdvertisementStatus == WiFiDirectServiceAdvertisementStatus::Aborted ||
00312         advertiser->Advertiser->AdvertisementStatus == WiFiDirectServiceAdvertisementStatus::Stopped)
00313     {
00314         RemoveAdvertiser(advertiser);
00315     }
00316     else
00317     {
00318         if (_scenario2 != nullptr)
00319         {
00320             _scenario2->UpdateAdvertiserStatus(advertiser);
00321         }
00322     }
00323 }
00324
00325 void WiFiDirectServiceManager::AddSession(SessionWrapper^ session)
00326 {
00327     {
00328         lock_guard<mutex> lock(_managerMutex);
00329         _connectedSessions->Append(session);
00330     }
00331
00332     // Update UI to add this to list
00333     if (_scenario2 != nullptr)
00334     {
00335         _scenario2->AddSession(session);
00336     }
00337     if (_scenario4 != nullptr)
00338     {
00339         _scenario4->AddSession(session);
00340     }
00341
00342     if (_scenario3 != nullptr)
00343     {
00344         _scenario3->SessionConnected();
00345     }
00346 }
00347
00348 void WiFiDirectServiceManager::RemoveSession(unsigned int index)
00349 {
00350     {
00351         lock_guard<mutex> lock(_managerMutex);
00352         // Invalidate selection
00353         _selectedSession = -1;
00354         _connectedSessions->RemoveAt(index);
00355     }
00356
00357     // Update UI to remove from list
00358     if (_scenario2 != nullptr)
00359     {
00360         _scenario2->RemoveSession(index);
00361     }
00362     if (_scenario4 != nullptr)
00363     {
00364         _scenario4->RemoveSession(index);
00365     }
00366 }
00367
00368 void WiFiDirectServiceManager::RemoveSession(SessionWrapper^ session)
00369 {
00370     int index = 0;
00371     bool fFound = false;
00372
00373     {
00374         lock_guard<mutex> lock(_managerMutex);
00375         // Lookup the index
00376         for (auto&& s : _connectedSessions)
00377         {
00378             if (!s->Session ||
00379                 (s->Session->SessionId == session->Session->SessionId &&
00380                 s->Session->SessionAddress == session->Session->SessionAddress &&
00381                 s->Session->AdvertisementId == session->Session->AdvertisementId &&
00382                 s->Session->ServiceAddress == session->Session->ServiceAddress))
00383             {
00384                 fFound = true;
00385                 break;
00386             }
00387             ++index;
00388         }
00389     }
00390
00391     if (fFound)
00392     {
00393         RemoveSession(index);
00394     }
00395     else
00396     {
00397         NotifyUser("Session not found in list", NotifyType::ErrorMessage);
00398     }
00399 }
00400
00401 void WiFiDirectServiceManager::CloseSession(unsigned int index)
00402 {
00403     SessionWrapper^ session = nullptr;
00404
00405     // First remove from list
00406     {
00407         lock_guard<mutex> lock(_managerMutex);
00408         if (index > _connectedSessions->Size - 1)
00409         {
00410             throw ref new OutOfBoundsException("Attempted to close session not found in list");
00411         }
00412
00413         session = _connectedSessions->GetAt(index);
00414         // Session will remove self from list when its status changes
00415     }
00416
00417     // Close session by disposing underlying WiFiDirectServiceSession
00418     session->Close();
00419     RootPage->NotifyUser("Closed Session", NotifyType::StatusMessage);
00420 }
00421
00422 void WiFiDirectServiceManager::SelectSession(unsigned int index)
00423 {
00424     {
00425         lock_guard<mutex> lock(_managerMutex);
00426         if (index > _connectedSessions->Size - 1)
00427         {
00428             throw ref new OutOfBoundsException("Attempted to select session not found in list");
00429         }
00430         _selectedSession = index;
00431     }
00432 }
00433
00434 void WiFiDirectServiceManager::AddSocket(SocketWrapper^ socket)
00435 {
00436     // Update UI to add this to list
00437     if (_scenario5 != nullptr)
00438     {
00439         _scenario5->AddSocket(socket);
00440     }
00441 }
00442
00443 void WiFiDirectServiceManager::AddAdvertiser(AdvertisementWrapper^ advertiser)
00444 {
00445     {
00446         lock_guard<mutex> lock(_managerMutex);
00447         _advertisers->Append(advertiser);
00448     }
00449
00450     // Update UI to add this to list
00451     if (_scenario2 != nullptr)
00452     {
00453         _scenario2->AddAdvertiser(advertiser);
00454     }
00455 }
00456
00457 void WiFiDirectServiceManager::RemoveAdvertiser(unsigned int index)
00458 {
00459     {
00460         lock_guard<mutex> lock(_managerMutex);
00461         _advertisers->RemoveAt(index);
00462     }
00463
00464     // Update UI to add this to list
00465     if (_scenario2 != nullptr)
00466     {
00467         _scenario2->RemoveAdvertiser(index);
00468     }
00469 }
Generated on Fri Nov 15 2024 22:22:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cppwinrt/pch.h Source File

  • SecondaryTiles
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Data.Xml.Dom.h"
00008 #include "winrt/Windows.System.h"
00009 #include "winrt/Windows.UI.Core.h"
00010 #include "winrt/Windows.UI.Notifications.h"
00011 #include "winrt/Windows.UI.StartScreen.h"
00012 #include "winrt/Windows.UI.Xaml.h"
00013 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00014 #include "winrt/Windows.UI.Xaml.Controls.h"
00015 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00016 #include "winrt/Windows.UI.Xaml.Documents.h"
00017 #include "winrt/Windows.UI.Xaml.Interop.h"
00018 #include "winrt/Windows.UI.Xaml.Markup.h"
00019 #include "winrt/Windows.UI.Xaml.Media.h"
00020 #include "winrt/Windows.UI.Xaml.Navigation.h"
00021 #include "winrt/NotificationsExtensions.h"
00022 #include "winrt/NotificationsExtensions.Badges.h"
00023 #include "winrt/NotificationsExtensions.Tiles.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Compass/cpp/pch.cpp Source File

  • Compass
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/ToastNotificationManagerHistory/GetHistory/Visualizer/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • ToastNotificationManagerHistory
  • GetHistory
  • Visualizer

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Notifications;
00002 using Windows.UI.Xaml;
00003 using Windows.UI.Xaml.Controls;
00004
00005 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00006
00007 namespace Notifications.ScenarioPages.Toasts.ToastNotificationManagerHistory.GetHistory.Visualizer
00008 {
00009     /// <summary>
00010     /// An empty page that can be used on its own or navigated to within a Frame.
00011     /// </summary>
00012     public sealed partial class ScenarioElement : UserControl
00013     {
00014         public ScenarioElement()
00015         {
00016             this.InitializeComponent();
00017
00018             ButtonUpdate_Click(this, null);
00019         }
00020
00021         private void ButtonUpdate_Click(object sender, RoutedEventArgs e)
00022         {
00023             var toasts = ToastNotificationManager.History.GetHistory();
00024
00025             ListViewHistory.ItemsSource = toasts;
00026         }
00027     }
00028 }
Generated on Fri Nov 15 2024 22:20:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Tasks/pch.cpp Source File

  • Geolocation
  • cppwinrt
  • Tasks

pch.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ConnectedTask Member List

This is the complete list of members for ConnectedTask, including all inherited members.
Run(IBackgroundTaskInstance taskInstance) ConnectedTask [inline]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ItemList Member List

This is the complete list of members for ItemList, including all inherited members.
CreateDefaultItemList() | ItemList | [inline, static]
ItemList() | ItemList | [inline]
Generated on Fri Nov 15 2024 22:23:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cppwinrt/Scenario3_EnumerateTiles.cpp Source File

  • SecondaryTiles
  • cppwinrt

Scenario3_EnumerateTiles.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_EnumerateTiles.h"
00014 #include "Scenario3_EnumerateTiles.g.cpp"
00015 #include <sstream>
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::StartScreen;
00021 using namespace Windows::UI::Xaml;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario3_EnumerateTiles::Scenario3_EnumerateTiles()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     fire_and_forget Scenario3_EnumerateTiles::EnumerateSecondaryTiles_Click(IInspectable const&, RoutedEventArgs const&)
00031     {
00032         auto lifetime = get_strong();
00033
00034         // Get secondary tile ids for this package
00035         IVectorView<SecondaryTile> tilelist = co_await SecondaryTile::FindAllAsync();
00036         if (tilelist.Size() > 0)
00037         {
00038             std::wostringstream output;
00039             for (SecondaryTile tile : tilelist)
00040             {
00041                 output << L"Tile \"" << std::wstring_view{ tile.TileId() } <<
00042                     L"\", Display name = \"" << std::wstring_view{ tile.DisplayName() } << L"\"" << std::endl;
00043             }
00044             rootPage.NotifyUser(output.str(), NotifyType::StatusMessage);
00045         }
00046         else
00047         {
00048             rootPage.NotifyUser(L"No secondary tiles are available for this appId.", NotifyType::ErrorMessage);
00049         }
00050     }
00051 }
Generated on Fri Nov 15 2024 22:21:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cpp/SampleConfiguration.h Source File

  • WiFiDirectServices
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Wi-Fi Direct Services";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038         void GoToScenario(unsigned int index);
00039
00040     private:
00041         static Platform::Array<Scenario>^ scenariosInner;
00042     };
00043
00044     public value struct Scenario
00045     {
00046         Platform::String^ Title;
00047         Platform::String^ ClassName;
00048     };
00049 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario12.xaml.cpp Source File

  • MapControl
  • cpp

Scenario12.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario12.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Platform::Collections;
00018 using namespace Windows::Devices::Geolocation;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::UI::Core;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Maps;
00024 using namespace Windows::UI::Xaml::Input;
00025 using namespace std::literals;
00026
00027 // The data source is contributed by Iowa Environmental Mesonet of Iowa State University.
00028 const std::wstring urlTemplate = L"http://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q-{timestamp}/{zoomlevel}/{x}/{y}.png";
00029 //The time stamps values for the IEM service for the last 50 minutes broken up into 5 minute increments.
00030 const std::vector<std::wstring> timestamps{ L"900913-m50m", L"900913-m45m", L"900913-m40m", L"900913-m35m", L"900913-m30m", L"900913-m25m", L"900913-m20m", L"900913-m15m", L"900913-m10m", L"900913-m05m", L"900913" };
00031
00032 Scenario12::Scenario12()
00033 {
00034     InitializeComponent();
00035 }
00036
00037 void Scenario12::MyMapLoaded(Object^ sender, RoutedEventArgs^ e)
00038 {
00039     myMap->Center = ref new Geopoint({ 39.1887643719098, -92.8261546188403 });
00040     myMap->ZoomLevel = 5;
00041
00042     std::wstring timestampStr = L"{timestamp}";
00043     size_t index = urlTemplate.find(timestampStr);
00044
00045     for (auto timestamp : timestamps)
00046     {
00047         std::wstring url(urlTemplate);
00048         urls.push_back(ref new String(url.replace(index, timestampStr.size(), timestamp).c_str()));
00049     }
00050 }
00051
00052 void Scenario12::AddAnimatedTilesClick(Object^ sender, RoutedEventArgs^ e)
00053 {
00054     if (httpTileSource == nullptr)
00055     {
00056         auto httpMapTileDataSource = ref new HttpMapTileDataSource();
00057         httpMapTileDataSource->UriRequested += ref new TypedEventHandler<HttpMapTileDataSource^, MapTileUriRequestedEventArgs^>(this, &Scenario12::HttpMapTileDataSourceUriRequested);
00058         httpTileSource = ref new MapTileSource(httpMapTileDataSource);
00059         httpTileSource->FrameCount = (int)timestamps.size();
00060         typedef std::chrono::duration<INT64, std::ratio_multiply<std::ratio<100>, std::nano>> timespan_units;
00061         httpTileSource->FrameDuration = TimeSpan{ timespan_units(500ms).count() };
00062         myMap->TileSources->Append(httpTileSource);
00063     }
00064 }
00065
00066 void Scenario12::ClearMapClick(Object^ sender, RoutedEventArgs^ e)
00067 {
00068     myMap->TileSources->Clear();
00069     httpTileSource = nullptr;
00070 }
00071
00072 void Scenario12::HttpMapTileDataSourceUriRequested(HttpMapTileDataSource^ sender, MapTileUriRequestedEventArgs^ e)
00073 {
00074     e->Request->Uri = ref new Uri(urls[e->FrameIndex]);
00075 }
00076
00077 void Scenario12::PlayAnimationTapped(Object^ sender, TappedRoutedEventArgs^ e)
00078 {
00079     if (httpTileSource != nullptr)
00080     {
00081         httpTileSource->Play();
00082     }
00083 }
00084
00085 void Scenario12::PauseAnimationTapped(Object^ sender, TappedRoutedEventArgs^ e)
00086 {
00087     if (httpTileSource != nullptr)
00088     {
00089         httpTileSource->Pause();
00090     }
00091 }
00092
00093 void Scenario12::StopAnimationTapped(Object^ sender, TappedRoutedEventArgs^ e)
00094 {
00095     if (httpTileSource != nullptr)
00096     {
00097         httpTileSource->Stop();
00098     }
00099 }
Generated on Fri Nov 15 2024 22:17:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaEditing/cs/Scenario2_AppendClips.xaml.cs Source File

  • MediaEditing
  • cs

Scenario2_AppendClips.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using Windows.Storage;
00017 using Windows.Media.Editing;
00018 using Windows.Media.Core;
00019 using SDKTemplate;
00020
00021 namespace MediaEditingSample
00022 {
00023     public sealed partial class Scenario2_AppendClips : Page
00024     {
00025         private MainPage rootPage;
00026         private MediaComposition composition;
00027         private StorageFile firstVideoFile;
00028         private StorageFile secondVideoFile;
00029         private MediaStreamSource mediaStreamSource;
00030
00031         public Scenario2_AppendClips()
00032         {
00033             this.InitializeComponent();
00034         }
00035
00036         protected override void OnNavigatedTo(NavigationEventArgs e)
00037         {
00038             rootPage = MainPage.Current;
00039         }
00040
00041         protected override void OnNavigatedFrom(NavigationEventArgs e)
00042         {
00043             mediaElement.Source = null;
00044             mediaStreamSource = null;
00045             base.OnNavigatedFrom(e);
00046         }
00047
00048         private async void ChooseFirstVideo_Click(object sender, RoutedEventArgs e)
00049         {
00050             // Get first file
00051             var picker = new Windows.Storage.Pickers.FileOpenPicker();
00052             picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
00053             picker.FileTypeFilter.Add(".mp4");
00054             firstVideoFile = await picker.PickSingleFileAsync();
00055             if (firstVideoFile == null)
00056             {
00057                 rootPage.NotifyUser("File picking cancelled", NotifyType.ErrorMessage);
00058                 return;
00059             }
00060
00061             mediaElement.SetSource(await firstVideoFile.OpenReadAsync(), firstVideoFile.ContentType);
00062             chooseSecondFile.IsEnabled = true;
00063         }
00064
00065         private async void ChooseSecondVideo_Click(object sender, RoutedEventArgs e)
00066         {
00067             // Get second file
00068             var picker = new Windows.Storage.Pickers.FileOpenPicker();
00069             picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
00070             picker.FileTypeFilter.Add(".mp4");
00071             secondVideoFile = await picker.PickSingleFileAsync();
00072             if (secondVideoFile == null)
00073             {
00074                 rootPage.NotifyUser("File picking cancelled", NotifyType.ErrorMessage);
00075                 return;
00076             }
00077
00078             mediaElement.SetSource(await secondVideoFile.OpenReadAsync(), secondVideoFile.ContentType);
00079             appendFiles.IsEnabled = true;
00080         }
00081
00082         private async void AppendVideos_Click(object sender, RoutedEventArgs e)
00083         {
00084             // Combine two video files together into one
00085             var firstClip = await MediaClip.CreateFromFileAsync(firstVideoFile);
00086             var secondClip = await MediaClip.CreateFromFileAsync(secondVideoFile);
00087
00088             composition = new MediaComposition();
00089             composition.Clips.Add(firstClip);
00090             composition.Clips.Add(secondClip);
00091
00092             // Render to MediaElement.
00093             mediaElement.Position = TimeSpan.Zero;
00094             mediaStreamSource = composition.GeneratePreviewMediaStreamSource((int)mediaElement.ActualWidth, (int)mediaElement.ActualHeight);
00095             mediaElement.SetMediaStreamSource(mediaStreamSource);
00096             rootPage.NotifyUser("Clips appended", NotifyType.StatusMessage);
00097         }
00098     }
00099 }
Generated on Fri Nov 15 2024 22:20:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLOutOfProcessWinRTComponent/cpp/cpp/Scenario3_CustomException.xaml.cpp Source File

  • WRLOutOfProcessWinRTComponent
  • cpp
  • cpp

Scenario3_CustomException.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include "pch.h"
00008 #include "Scenario3_CustomException.xaml.h"
00009 #include "MainPage.xaml.h"
00010 #include "Microsoft.SDKSamples.Kitchen.h"
00011
00012 using namespace SDKTemplate::WRLOutOfProcessWinRTComponent;
00013
00014 using namespace Microsoft::SDKSamples::Kitchen;
00015
00016 using namespace Windows::UI::Xaml;
00017 using namespace Windows::UI::Xaml::Controls;
00018
00019 CustomException::CustomException()
00020 {
00021     InitializeComponent();
00022 }
00023
00024 void CustomException::Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00025 {
00026     // Component Creation
00027     auto myOven = ref new Oven();
00028
00029     try
00030     {
00031         // Intentionally pass an invalid value
00032         myOven->ConfigurePreheatTemperature(static_cast<Microsoft::SDKSamples::Kitchen::OvenTemperature>(5));
00033     }
00034     catch (Platform::InvalidArgumentException^ e)
00035     {
00036         CustomExceptionOutput->Text += L"Exception caught. Please attach a debugger and enable first chance native exceptions to view exception details.\n";
00037     }
00038 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2ViewModel Member List

This is the complete list of members for Scenario2ViewModel, including all inherited members.
AttemptAuthentication | Scenario2ViewModel |
AttemptConnectionAsync() | Scenario2ViewModel | [inline, private]
AttemptOnboardingAsync(string ssid, string password, short authType) | Scenario2ViewModel | [inline, private]
Authenticate() | Scenario2ViewModel | [inline, private]
AuthenticationVisibility | Scenario2ViewModel |
AuthTypeArray | Scenario2ViewModel |
BusAttachment_AuthenticationComplete(AllJoynBusAttachment sender, AllJoynAuthenticationCompleteEventArgs args) | Scenario2ViewModel | [inline, private]
BusAttachment_CredentialsRequested(AllJoynBusAttachment sender, AllJoynCredentialsRequestedEventArgs args) | Scenario2ViewModel | [inline, private]
BusAttachment_StateChanged(AllJoynBusAttachment sender, AllJoynBusAttachmentStateChangedEventArgs args) | Scenario2ViewModel | [inline, private]
ClearPasswords() | Scenario2ViewModel | [inline, private]
Connect | Scenario2ViewModel |
ConnectPanelVisibility | Scenario2ViewModel |
ConnectToSoftAPAsync() | Scenario2ViewModel | [inline, private]
Consumer_SessionLost(AllJoynSession sender, AllJoynSessionLostEventArgs args) | Scenario2ViewModel | [inline, private]
ConvertUtf8ToHex(string inputString) | Scenario2ViewModel | [inline, private, static]
DisposeConsumer() | Scenario2ViewModel | [inline, private]
DisposeWatcher() | Scenario2ViewModel | [inline, private]
EnteredKey | Scenario2ViewModel |
GetOnboardeeNetworkListAsync() | Scenario2ViewModel | [inline, private]
GetOnboardingConfiguration() | Scenario2ViewModel | [inline, private]
m_authenticateClicked | Scenario2ViewModel | [private]
m_authenticationVisibility | Scenario2ViewModel | [private]
m_busAttachment | Scenario2ViewModel | [private]
m_connectPanelVisibility | Scenario2ViewModel | [private]
m_consumer | Scenario2ViewModel | [private]
m_dispatcher | Scenario2ViewModel | [private]
m_key | Scenario2ViewModel | [private]
m_manualSsid | Scenario2ViewModel | [private]
m_manualSsidIsChecked | Scenario2ViewModel | [private]
m_manualSsidTextBoxVisibility | Scenario2ViewModel | [private]
m_onboardeeNetworkList | Scenario2ViewModel | [private]
m_onboardeeSsidListVisibility | Scenario2ViewModel | [private]
m_onboarderNetworkList | Scenario2ViewModel | [private]
m_onboarderSsidListVisibility | Scenario2ViewModel | [private]
m_onboardingConfigurationVisibility | Scenario2ViewModel | [private]
m_onboardingPassword | Scenario2ViewModel | [private]
m_onboardingProducerIsChecked | Scenario2ViewModel | [private]
m_onboardSessionAlreadyJoined | Scenario2ViewModel | [private]
m_passwordVisibility | Scenario2ViewModel | [private]
m_physicalDeviceIsChecked | Scenario2ViewModel | [private]
m_rootPage | Scenario2ViewModel | [private]
m_savedProfileName | Scenario2ViewModel | [private]
m_scanPanelVisibility | Scenario2ViewModel | [private]
m_selectedAuthType | Scenario2ViewModel | [private]
m_selectedOnboardeeNetwork | Scenario2ViewModel | [private]
m_selectedOnboarderNetwork | Scenario2ViewModel | [private]
m_selectedSoftAPNetwork | Scenario2ViewModel | [private]
m_selectedWiFiAdapterIndex | Scenario2ViewModel | [private]
m_showOnboardeeSsidList | Scenario2ViewModel | [private]
m_showOnboarderSsidList | Scenario2ViewModel | [private]
m_softAPPassword | Scenario2ViewModel | [private]
m_watcher | Scenario2ViewModel | [private]
m_wiFiAdapter | Scenario2ViewModel | [private]
m_wiFiAdapterDisplayNames | Scenario2ViewModel | [private]
m_wiFiAdapterList | Scenario2ViewModel | [private]
m_wiFiAdapterListVisibility | Scenario2ViewModel | [private]
ManualSsid | Scenario2ViewModel |
ManualSsidIsChecked | Scenario2ViewModel |
ManualSsidTextBoxVisibility | Scenario2ViewModel |
NetworkInformation_NetworkStatusChanged(object sender) | Scenario2ViewModel | [inline, private]
Onboard | Scenario2ViewModel |
OnboardeeNetworkList | Scenario2ViewModel |
OnboardeeSsidListVisibility | Scenario2ViewModel |
OnboarderNetworkList | Scenario2ViewModel |
OnboarderSsidListVisibility | Scenario2ViewModel |
OnboardingConfigurationVisibility | Scenario2ViewModel |
OnboardingPassword | Scenario2ViewModel |
OnboardingProducerIsChecked | Scenario2ViewModel |
PasswordVisibility | Scenario2ViewModel |
PhysicalDeviceIsChecked | Scenario2ViewModel |
PropertyChanged | Scenario2ViewModel |
RaisePropertyChangedEventAsync([CallerMemberName] string name="") | Scenario2ViewModel | [inline, protected]
ResetControls() | Scenario2ViewModel | [inline, private]
ScanForOnboardingInterfaces() | Scenario2ViewModel | [inline, private]
ScanForWiFiAdaptersAsync() | Scenario2ViewModel | [inline, private]
ScanForWiFiNetworksAsync() | Scenario2ViewModel | [inline, private]
ScanPanelVisibility | Scenario2ViewModel |
Scenario2ViewModel() | Scenario2ViewModel | [inline]
ScenarioCleanup() | Scenario2ViewModel | [inline]
SelectedAuthType | Scenario2ViewModel |
SelectedOnboardeeNetwork | Scenario2ViewModel |
SelectedOnboarderNetwork | Scenario2ViewModel |
SelectedSoftAPNetwork | Scenario2ViewModel |
SelectedWiFiAdapterIndex | Scenario2ViewModel |
ShowOnboardeeSsidList() | Scenario2ViewModel | [inline, private]
ShowOnboarderSsidList() | Scenario2ViewModel | [inline, private]
Signals_ConnectionResultReceived(OnboardingSignals sender, OnboardingConnectionResultReceivedEventArgs args) | Scenario2ViewModel | [inline, private]
SoftAPPassword | Scenario2ViewModel |
StartScan | Scenario2ViewModel |
StartScanning() | Scenario2ViewModel | [inline, private]
UpdateConnectivityStatusAsync() | Scenario2ViewModel | [inline, private]
UpdateStatusAsync(string status, NotifyType statusType) | Scenario2ViewModel | [inline, private]
Watcher_Added(DeviceWatcher sender, DeviceInformation args) | Scenario2ViewModel | [inline, private]
WiFiAdapterDisplayNames | Scenario2ViewModel |
WiFiAdapterListVisibility | Scenario2ViewModel |
Generated on Fri Nov 15 2024 22:23:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MultipleViews/cppwinrt/SampleConfiguration.cpp Source File

  • MultipleViews
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016 #include "ViewLifetimeControl.h"
00017
00018 using namespace winrt;
00019 using namespace Windows::ApplicationModel::Activation;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Core;
00023 using namespace Windows::UI::ViewManagement;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace SDKTemplate;
00027
00028 hstring implementation::MainPage::FEATURE_NAME()
00029 {
00030     return L"Multiple Views";
00031 }
00032
00033 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00034 {
00035     Scenario{ L"Creating and showing multiple views", xaml_typename<SDKTemplate::Scenario1>() },
00036     Scenario{ L"Using animations when switching", xaml_typename<SDKTemplate::Scenario3>() },
00037 });
00038
00039 implementation::App* SampleState::CurrentApp = nullptr;
00040 IObservableVector<IInspectable> SampleState::SecondaryViews = single_threaded_observable_vector<IInspectable>();
00041 CoreDispatcher SampleState::MainDispatcher{ nullptr };
00042 int32_t SampleState::MainViewId = 0;
00043
00044 namespace
00045 {
00046     ViewLifetimeControl TryFindViewLifetimeControlForViewId(int32_t viewId)
00047     {
00048         for (IInspectable const& item : SampleState::SecondaryViews)
00049         {
00050             auto viewLifetimeControl = item.as<ViewLifetimeControl>();
00051             if (viewLifetimeControl.Id() == viewId)
00052             {
00053                 return viewLifetimeControl;
00054             }
00055         }
00056         return nullptr;
00057     }
00058 }
00059
00060 // This method is designed to always be run on the thread that's
00061 // binding to the list above
00062 void SampleState::UpdateTitle(hstring newTitle, int32_t viewId)
00063 {
00064     ViewLifetimeControl foundData = TryFindViewLifetimeControlForViewId(viewId);
00065     if (foundData)
00066     {
00067         foundData.Title(newTitle);
00068     }
00069     else
00070     {
00071         throw hresult_error(HRESULT_FROM_WIN32(ERROR_NO_MATCH), L"Couldn't find the view ID in the collection");
00072     }
00073 }
00074
00075 bool winrt::SDKTemplate::App_OverrideOnLaunched(LaunchActivatedEventArgs const& e)
00076 {
00077     // Check if a secondary view is supposed to be shown
00078     ViewLifetimeControl viewLifetimeControl = TryFindViewLifetimeControlForViewId(e.CurrentlyShownApplicationViewId());
00079     if (viewLifetimeControl)
00080     {
00081         viewLifetimeControl.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [=]()
00082         {
00083             Window::Current().Activate();
00084         });
00085         return true;
00086     }
00087
00088     // Activating the main view.
00089     if (!SampleState::MainDispatcher)
00090     {
00091         SampleState::MainDispatcher = Window::Current().Dispatcher();
00092         SampleState::MainViewId = ApplicationView::GetForCurrentView().Id();
00093     }
00094     return false;
00095 }
00096
00097 fire_and_forget winrt::SDKTemplate::App_OnActivated(IActivatedEventArgs const& e)
00098 {
00099     if (e.Kind() == ActivationKind::Protocol)
00100     {
00101         auto protocolArgs = e.as<ProtocolActivatedEventArgs>();
00102
00103         // Capture the activation arguments before we co_await.
00104         Uri uri = protocolArgs.Uri();
00105
00106         // Find out which window the system chose to display
00107         // Unless you've set DisableShowingMainViewOnActivation,
00108         // it will always be your main view.
00109         ViewLifetimeControl viewControl = TryFindViewLifetimeControlForViewId(protocolArgs.CurrentlyShownApplicationViewId());
00110         if (viewControl)
00111         {
00112             co_await resume_foreground(viewControl.Dispatcher());
00113
00114             // We are now in the secondary page.
00115             auto currentPage = Window::Current().Content().as<Frame>().Content().as<SecondaryViewPage>();
00116             currentPage.HandleProtocolLaunch(uri);
00117             Window::Current().Activate();
00118         }
00119         else
00120         {
00121             // We don't have the specified view in the collection, likely because it's the main view
00122             // that got shown. Set up the main view to display.
00123             Frame rootFrame = SampleState::CurrentApp->CreateRootFrame();
00124             if (rootFrame.Content() == nullptr)
00125             {
00126                 rootFrame.Navigate(xaml_typename<SDKTemplate::MainPage>());
00127                 SampleState::MainDispatcher = Window::Current().Dispatcher();
00128                 SampleState::MainViewId = ApplicationView::GetForCurrentView().Id();
00129             }
00130
00131             auto rootPage = MainPage::Current();
00132             rootPage.Navigate(xaml_typename<Scenario3>(), nullptr);
00133                 rootPage.NotifyUser(L"Main window was launched with protocol: " + uri.AbsoluteUri(),
00134                     NotifyType::StatusMessage);
00135             Window::Current().Activate();
00136         }
00137     }
00138 }
Generated on Fri Nov 15 2024 22:17:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cs/Scenario3_ServicingCompleteTask.xaml.cs Source File

  • BackgroundActivation
  • cs

Scenario3_ServicingCompleteTask.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using SDKTemplate;
00014 using Windows.ApplicationModel.Background;
00015 using Windows.Storage;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class ServicingCompleteTask : Page
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         MainPage rootPage = MainPage.Current;
00033
00034         public ServicingCompleteTask()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         /// <summary>
00040         /// Invoked when this page is about to be displayed in a Frame.
00041         /// </summary>
00042         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00043         /// property is typically used to configure the page.</param>
00044         protected override void OnNavigatedTo(NavigationEventArgs e)
00045         {
00046             foreach (var task in BackgroundTaskRegistration.AllTasks)
00047             {
00048                 if (task.Value.Name == BackgroundTaskSample.ServicingCompleteTaskName)
00049                 {
00050                     AttachProgressAndCompletedHandlers(task.Value);
00051                     BackgroundTaskSample.UpdateBackgroundTaskRegistrationStatus(BackgroundTaskSample.ServicingCompleteTaskName, true);
00052                     break;
00053                 }
00054             }
00055
00056             UpdateUI();
00057         }
00058
00059         /// <summary>
00060         /// Register a ServicingCompleteTask.
00061         /// </summary>
00062         /// <param name="sender"></param>
00063         /// <param name="e"></param>
00064         private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
00065         {
00066             var task = BackgroundTaskSample.RegisterBackgroundTask(null,
00067                                                                    BackgroundTaskSample.ServicingCompleteTaskName,
00068                                                                    new SystemTrigger(SystemTriggerType.ServicingComplete, false),
00069                                                                    null);
00070             AttachProgressAndCompletedHandlers(task);
00071             UpdateUI();
00072         }
00073
00074         /// <summary>
00075         /// Unregister a ServicingCompleteTask.
00076         /// </summary>
00077         /// <param name="sender"></param>
00078         /// <param name="e"></param>
00079         private void UnregisterBackgroundTask(object sender, RoutedEventArgs e)
00080         {
00081             BackgroundTaskSample.UnregisterBackgroundTasks(BackgroundTaskSample.ServicingCompleteTaskName);
00082             UpdateUI();
00083         }
00084
00085         /// <summary>
00086         /// Attach progress and completed handers to a background task.
00087         /// </summary>
00088         /// <param name="task">The task to attach progress and completed handlers to.</param>
00089         private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
00090         {
00091             task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
00092             task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
00093         }
00094
00095         /// <summary>
00096         /// Handle background task progress.
00097         /// </summary>
00098         /// <param name="task">The task that is reporting progress.</param>
00099         /// <param name="e">Arguments of the progress report.</param>
00100         private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
00101         {
00102             var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00103             {
00104                 var progress = "Progress: " + args.Progress + "%";
00105                 BackgroundTaskSample.ServicingCompleteTaskProgress = progress;
00106                 UpdateUI();
00107             });
00108         }
00109
00110         /// <summary>
00111         /// Handle background task completion.
00112         /// </summary>
00113         /// <param name="task">The task that is reporting completion.</param>
00114         /// <param name="e">Arguments of the completion report.</param>
00115         private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
00116         {
00117             UpdateUI();
00118         }
00119
00120         /// <summary>
00121         /// Update the scenario UI.
00122         /// </summary>
00123         private async void UpdateUI()
00124         {
00125             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
00126             () =>
00127             {
00128                 RegisterButton.IsEnabled = !BackgroundTaskSample.ServicingCompleteTaskRegistered;
00129                 UnregisterButton.IsEnabled = BackgroundTaskSample.ServicingCompleteTaskRegistered;
00130                 Progress.Text = BackgroundTaskSample.ServicingCompleteTaskProgress;
00131                 Status.Text = BackgroundTaskSample.GetBackgroundTaskStatus(BackgroundTaskSample.ServicingCompleteTaskName);
00132             });
00133         }
00134
00135     }
00136 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/common/MediaExtensions/Microsoft.Samples.SimpleCommunication/StspStreamSink.h Source File

  • SimpleCommunication
  • common
  • MediaExtensions
  • Microsoft.Samples.SimpleCommunication

StspStreamSink.h

Go to the documentation of this file.
00001 //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009 #include <CritSec.h>
00010 #include <AsyncCB.h>
00011 #include <linklist.h>
00012 #include <StspNetwork.h>
00013 #include <StspDefs.h>
00014
00015 namespace Microsoft { namespace Samples { namespace SimpleCommunication {
00016
00017 class CMediaSink;
00018
00019 class CStreamSink : public IMFStreamSink, public IMFMediaTypeHandler
00020 {
00021 public:
00022     // State enum: Defines the current state of the stream.
00023     enum State
00024     {
00025         State_TypeNotSet = 0,    // No media type is set
00026         State_Ready,             // Media type is set, Start has never been called.
00027         State_Started,
00028         State_Stopped,
00029         State_Paused,
00030         State_Count              // Number of states
00031     };
00032
00033     // StreamOperation: Defines various operations that can be performed on the stream.
00034     enum StreamOperation
00035     {
00036         OpSetMediaType = 0,
00037         OpStart,
00038         OpRestart,
00039         OpPause,
00040         OpStop,
00041         OpProcessSample,
00042         OpPlaceMarker,
00043
00044         Op_Count                // Number of operations
00045     };
00046
00047     // CAsyncOperation:
00048     // Used to queue asynchronous operations. When we call MFPutWorkItem, we use this
00049     // object for the callback state (pState). Then, when the callback is invoked,
00050     // we can use the object to determine which asynchronous operation to perform.
00051
00052     class CAsyncOperation : public IUnknown
00053     {
00054     public:
00055         CAsyncOperation(StreamOperation op);
00056
00057         StreamOperation m_op;   // The operation to perform.
00058
00059         // IUnknown methods.
00060         STDMETHODIMP QueryInterface(REFIID iid, void **ppv);
00061         STDMETHODIMP_(ULONG) AddRef();
00062         STDMETHODIMP_(ULONG) Release();
00063
00064     private:
00065         long    _cRef;
00066         virtual ~CAsyncOperation();
00067     };
00068
00069 public:
00070     // IUnknown
00071     IFACEMETHOD (QueryInterface) (REFIID riid, void **ppv);
00072     IFACEMETHOD_(ULONG, AddRef) ();
00073     IFACEMETHOD_(ULONG, Release) ();
00074
00075     // IMFMediaEventGenerator
00076     IFACEMETHOD (BeginGetEvent)(IMFAsyncCallback *pCallback,IUnknown *punkState);
00077     IFACEMETHOD (EndGetEvent) (IMFAsyncResult *pResult, IMFMediaEvent **ppEvent);
00078     IFACEMETHOD (GetEvent) (DWORD dwFlags, IMFMediaEvent **ppEvent);
00079     IFACEMETHOD (QueueEvent) (MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, PROPVARIANT const *pvValue);
00080
00081     // IMFStreamSink
00082     IFACEMETHOD (GetMediaSink) (IMFMediaSink **ppMediaSink);
00083     IFACEMETHOD (GetIdentifier) (DWORD *pdwIdentifier);
00084     IFACEMETHOD (GetMediaTypeHandler) (IMFMediaTypeHandler **ppHandler);
00085     IFACEMETHOD (ProcessSample) (IMFSample *pSample);
00086
00087     IFACEMETHOD (PlaceMarker) (
00088         /* [in] */ MFSTREAMSINK_MARKER_TYPE eMarkerType,
00089         /* [in] */ PROPVARIANT const *pvarMarkerValue,
00090         /* [in] */ PROPVARIANT const *pvarContextValue);
00091
00092     IFACEMETHOD (Flush)();
00093
00094     // IMFMediaTypeHandler
00095     IFACEMETHOD (IsMediaTypeSupported) (IMFMediaType *pMediaType, IMFMediaType **ppMediaType);
00096     IFACEMETHOD (GetMediaTypeCount) (DWORD *pdwTypeCount);
00097     IFACEMETHOD (GetMediaTypeByIndex) (DWORD dwIndex, IMFMediaType **ppType);
00098     IFACEMETHOD (SetCurrentMediaType) (IMFMediaType *pMediaType);
00099     IFACEMETHOD (GetCurrentMediaType) (IMFMediaType **ppMediaType);
00100     IFACEMETHOD (GetMajorType) (GUID *pguidMajorType);
00101
00102     // ValidStateMatrix: Defines a look-up table that says which operations
00103     // are valid from which states.
00104     static BOOL ValidStateMatrix[State_Count][Op_Count];
00105
00106
00107     CStreamSink(DWORD dwIdentifier);
00108     virtual ~CStreamSink();
00109
00110     HRESULT Initialize(CMediaSink *pParent, Network::INetworkChannel ^sender);
00111
00112     HRESULT CheckShutdown() const
00113     {
00114         if (_IsShutdown)
00115         {
00116             return MF_E_SHUTDOWN;
00117         }
00118         else
00119         {
00120             return S_OK;
00121         }
00122     }
00123
00124
00125     HRESULT     Start(MFTIME start);
00126     HRESULT     Restart();
00127     HRESULT     Stop();
00128     HRESULT     Pause();
00129     HRESULT     Shutdown();
00130     bool        IsVideo() const {return _fIsVideo;}
00131     HRESULT     SetConnected(bool fConnected, LONGLONG llCurrentTime);
00132     ComPtr<Network::IMediaBufferWrapper>  FillStreamDescription(IMFMediaType *pMediaType, StspStreamDescription *pStreamDescription);
00133
00134 private:
00135     HRESULT     ValidateOperation(StreamOperation op);
00136
00137     HRESULT     QueueAsyncOperation(StreamOperation op);
00138
00139     HRESULT     OnDispatchWorkItem(IMFAsyncResult *pAsyncResult);
00140     void        DispatchProcessSample(CAsyncOperation *pOp);
00141
00142     bool        DropSamplesFromQueue();
00143     bool        SendSampleFromQueue();
00144     bool        ProcessSamplesFromQueue(bool fFlush);
00145     void        ProcessFormatChange(IMFMediaType *pMediaType);
00146
00147     ComPtr<Network::IBufferPacket> PrepareSample(IMFSample *pSample, bool fForce);
00148     ComPtr<Network::IBufferPacket> PrepareFormatChange(IMFMediaType *pMediaType);
00149
00150     HRESULT     AppendParameterSets(IMFSample *pCopyFrom, Network::IBufferPacket *pPacket);
00151     void        HandleError(HRESULT hr);
00152
00153 private:
00154     long                        _cRef;                      // reference count
00155     CritSec                     _critSec;                   // critical section for thread safety
00156
00157     DWORD                       _dwIdentifier;
00158     State                       _state;
00159     bool                        _IsShutdown;                // Flag to indicate if Shutdown() method was called.
00160     bool                        _Connected;
00161     bool                        _fGetStartTimeFromSample;
00162     bool                        _fIsVideo;
00163     bool                        _fWaitingForFirstSample;
00164     bool                        _fFirstSampleAfterConnect;
00165     GUID                        _guiCurrentSubtype;
00166
00167     DWORD                       _WorkQueueId;               // ID of the work queue for asynchronous operations.
00168     MFTIME                      _StartTime;                 // Presentation time when the clock started.
00169
00170     ComPtr<IMFMediaSink>        _spSink;                    // Parent media sink
00171     CMediaSink                  *_pParent;
00172
00173     ComPtr<IMFMediaEventQueue>  _spEventQueue;              // Event queue
00174     ComPtr<IMFByteStream>       _spByteStream;              // Bytestream where we write the data.
00175     ComPtr<IMFMediaType>        _spCurrentType;
00176     ComPtr<IMFSample>           _spFirstVideoSample;
00177
00178     ComPtrList<IUnknown>        _SampleQueue;               // Queue to hold samples and markers.
00179                                                             // Applies to: ProcessSample, PlaceMarker
00180
00181     Network::INetworkChannel^    _networkSender;
00182
00183     AsyncCallback<CStreamSink>  _WorkQueueCB;              // Callback for the work queue.
00184
00185     ComPtr<IUnknown>            _spFTM;
00186 };
00187
00188 }}} // namespace Microsoft::Samples::SimpleCommunication
Generated on Fri Nov 15 2024 22:21:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IGameUIControl Member List

This is the complete list of members for IGameUIControl, including all inherited members.
HideGameInfoOverlay() | IGameUIControl
HideTooSmall() | IGameUIControl
SetAction(GameInfoOverlayCommand action) | IGameUIControl
SetGameLoading() | IGameUIControl
SetGameOver(bool win, int maxLevel, int hitCount, int shotCount, int highScore) | IGameUIControl
SetGameStats(int maxLevel, int hitCount, int shotCount) | IGameUIControl
SetLevelStart(int level, Platform::String^objective, float timeLimit, float bonusTime) | IGameUIControl
SetPause(int level, int hitCount, int shotCount, float timeRemaining) | IGameUIControl
ShowGameInfoOverlay() | IGameUIControl
ShowTooSmall() | IGameUIControl
Generated on Fri Nov 15 2024 22:24:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Animate Member List

This is the complete list of members for Animate, including all inherited members.
Animate() | Animate |
Continuous() | Animate |
Continuous(_In_ bool continuous) | Animate |
Duration() | Animate |
Duration(_In_ float duration) | Animate |
Evaluate(_In_ float t)=0 | Animate | [pure virtual]
IsActive(_In_ float t) | Animate | [inline]
IsFinished(_In_ float t) | Animate | [inline]
m_continuous | Animate | [protected]
m_duration | Animate | [protected]
m_startTime | Animate | [protected]
Start() | Animate |
Start(_In_ float start) | Animate |
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialMapping/cpp/Content/SpatialInputHandler.h Source File

  • HolographicSpatialMapping
  • cpp
  • Content

SpatialInputHandler.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace HolographicSpatialMapping
00015 {
00016     // Sample gesture handler.
00017     // Hooks up events to recognize a tap gesture, and keeps track of input using a boolean value.
00018     class SpatialInputHandler
00019     {
00020     public:
00021         SpatialInputHandler();
00022         ~SpatialInputHandler();
00023
00024         Windows::UI::Input::Spatial::SpatialInteractionSourceState^ CheckForInput();
00025
00026     private:
00027         // Interaction event handler.
00028         void OnSourcePressed(
00029             Windows::UI::Input::Spatial::SpatialInteractionManager^ sender,
00030             Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs^ args);
00031
00032         // API objects used to process gesture input, and generate gesture events.
00033         Windows::UI::Input::Spatial::SpatialInteractionManager^     m_interactionManager;
00034
00035         // Event registration token.
00036         Windows::Foundation::EventRegistrationToken                 m_sourcePressedEventToken;
00037
00038         // Used to indicate that a Pressed input event was received this frame.
00039         Windows::UI::Input::Spatial::SpatialInteractionSourceState^ m_sourceState = nullptr;
00040     };
00041 }
Generated on Fri Nov 15 2024 22:16:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cpp/cpp/pch.cpp Source File

  • ProxyStubsForWinRTComponents
  • cpp
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicTagAlong/cpp/HolographicTagAlongSampleMain.h Source File

  • HolographicTagAlong
  • cpp

HolographicTagAlongSampleMain.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Comment out this preprocessor definition to disable all of the
00015 // sample content.
00016 #define DRAW_SAMPLE_CONTENT
00017
00018 #include "Common\DeviceResources.h"
00019 #include "Common\StepTimer.h"
00020
00021 #ifdef DRAW_SAMPLE_CONTENT
00022 #include "Content\DistanceFieldRenderer.h"
00023 #include "Content\SpatialInputHandler.h"
00024 #include "Content\TextRenderer.h"
00025 #include "Content\QuadRenderer.h"
00026 #endif
00027
00028 // Updates, renders, and presents holographic content using Direct3D.
00029 namespace HolographicTagAlongSample
00030 {
00031     class HolographicTagAlongSampleMain : public DX::IDeviceNotify
00032     {
00033     public:
00034         HolographicTagAlongSampleMain(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00035         ~HolographicTagAlongSampleMain();
00036
00037         // Sets the holographic space. This is our closest analogue to setting a new window
00038         // for the app.
00039         void SetHolographicSpace(Windows::Graphics::Holographic::HolographicSpace^ holographicSpace);
00040
00041         // Starts the holographic frame and updates the content.
00042         Windows::Graphics::Holographic::HolographicFrame^ Update();
00043
00044         // Renders holograms, including world-locked content.
00045         bool Render(Windows::Graphics::Holographic::HolographicFrame^ holographicFrame);
00046
00047         // Handle saving and loading of app state owned by AppMain.
00048         void SaveAppState();
00049         void LoadAppState();
00050
00051         // IDeviceNotify
00052         virtual void OnDeviceLost();
00053         virtual void OnDeviceRestored();
00054
00055     private:
00056         // Sets up the texture for the hologram.
00057         void RenderOffscreenTexture();
00058
00059         // Asynchronously creates resources for new holographic cameras.
00060         void OnCameraAdded(
00061             Windows::Graphics::Holographic::HolographicSpace^ sender,
00062             Windows::Graphics::Holographic::HolographicSpaceCameraAddedEventArgs^ args);
00063
00064         // Synchronously releases resources for holographic cameras that are no longer
00065         // attached to the system.
00066         void OnCameraRemoved(
00067             Windows::Graphics::Holographic::HolographicSpace^ sender,
00068             Windows::Graphics::Holographic::HolographicSpaceCameraRemovedEventArgs^ args);
00069
00070         // Used to notify the app when the positional tracking state changes.
00071         void OnLocatabilityChanged(
00072             Windows::Perception::Spatial::SpatialLocator^ sender,
00073             Platform::Object^ args);
00074
00075         // Clears event registration state. Used when changing to a new HolographicSpace
00076         // and when tearing down AppMain.
00077         void UnregisterHolographicEventHandlers();
00078
00079 #ifdef DRAW_SAMPLE_CONTENT
00080         // Renders a textured quad. Used to demonstrate a body-locked hologram.
00081         std::unique_ptr<QuadRenderer>                                           m_quadRenderer;
00082
00083         // Renders text off-screen. Used to create a texture to render on the quad.
00084         std::unique_ptr<TextRenderer>                                           m_textRenderer;
00085
00086         // Performs a gather operation to create a 2D pixel distance map.
00087         std::unique_ptr<DistanceFieldRenderer>                                  m_distanceFieldRenderer;
00088
00089         // Listens for the Pressed spatial input event.
00090         std::shared_ptr<SpatialInputHandler>                                    m_spatialInputHandler;
00091 #endif
00092
00093         // Cached pointer to device resources.
00094         std::shared_ptr<DX::DeviceResources>                                    m_deviceResources;
00095
00096         // Render loop timer.
00097         DX::StepTimer                                                           m_timer;
00098
00099         // Represents the holographic space around the user.
00100         Windows::Graphics::Holographic::HolographicSpace^                       m_holographicSpace;
00101
00102         // SpatialLocator that is attached to the primary camera.
00103         Windows::Perception::Spatial::SpatialLocator^                           m_locator;
00104
00105         // A reference frame attached to the holographic camera.
00106         Windows::Perception::Spatial::SpatialLocatorAttachedFrameOfReference^   m_attachedReferenceFrame;
00107
00108         // A reference frame placed in the environment.
00109         Windows::Perception::Spatial::SpatialStationaryFrameOfReference^        m_stationaryReferenceFrame;
00110
00111         // Event registration tokens.
00112         Windows::Foundation::EventRegistrationToken                             m_cameraAddedToken;
00113         Windows::Foundation::EventRegistrationToken                             m_cameraRemovedToken;
00114         Windows::Foundation::EventRegistrationToken                             m_locatabilityChangedToken;
00115
00116         bool                                                                    m_dropHologram = false;
00117     };
00118 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: VideoPlayback/cs/Scenario8_TransferMediaPlayer1.xaml.cs Source File

  • VideoPlayback
  • cs

Scenario8_TransferMediaPlayer1.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015
00016 namespace SDKTemplate
00017 {
00018     /// <summary>
00019     /// This scenario demonstrates how the lifetime of a MediaPlayer is independent of the MediaPlayerElement.
00020     ///
00021     /// The MediaPlayer created on this page can continue to play in the background, then be rebound to another
00022     /// scenario page.
00023     /// </summary>
00024     public sealed partial class Scenario8_TransferMediaPlayer1 : Page
00025     {
00026         private MainPage rootPage = MainPage.Current;
00027
00028         public Scenario8_TransferMediaPlayer1()
00029         {
00030             this.InitializeComponent();
00031         }
00032         protected override void OnNavigatedTo(NavigationEventArgs e)
00033         {
00034             // Attach any existing MediaPlayer to the MediaPlayerElement on this page.
00035             mediaPlayerElement.SetMediaPlayer(rootPage.commonMediaPlayer);
00036         }
00037         private void OnNavigatedFrom(object sender, RoutedEventArgs e)
00038         {
00039             // Detach the MediaPlayer from the MediaPlayerElement, but do not dispose it.
00040             // The MediaPlayer will continue to run, and it can be attached to another MediaPlayerElement.
00041             mediaPlayerElement.SetMediaPlayer(null);
00042         }
00043
00044         private void CreateMediaPlayer_Click(object sender, RoutedEventArgs e)
00045         {
00046             if (rootPage.commonMediaPlayer == null)
00047             {
00048                 rootPage.commonMediaPlayer = new Windows.Media.Playback.MediaPlayer();
00049                 rootPage.commonMediaPlayer.AutoPlay = true;
00050                 rootPage.commonMediaPlayer.Source = Windows.Media.Core.MediaSource.CreateFromUri(rootPage.CaptionedMediaUri);
00051
00052                 mediaPlayerElement.SetMediaPlayer(rootPage.commonMediaPlayer);
00053                 rootPage.NotifyUser("Created MediaPlayer.", NotifyType.StatusMessage);
00054             }
00055             else
00056             {
00057                 rootPage.NotifyUser("MediaPlayer already exists.", NotifyType.ErrorMessage);
00058             }
00059         }
00060     }
00061 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VertexPositionNormalColor Member List

This is the complete list of members for VertexPositionNormalColor, including all inherited members.
color | VertexPositionNormalColor
normal | VertexPositionNormalColor
pos | VertexPositionNormalColor
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cs/Content/SpatialInputHandler.cs Source File

  • BasicHologram
  • cs
  • Content

SpatialInputHandler.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Input.Spatial;
00002
00003 namespace BasicHologram.Common
00004 {
00005     // Sample gesture handler.
00006     // Hooks up events to recognize a tap gesture, and keeps track of input using a boolean value.
00007     public class SpatialInputHandler
00008     {
00009         // API objects used to process gesture input, and generate gesture events.
00010         private SpatialInteractionManager interactionManager;
00011
00012         // Used to indicate that a Pressed input event was received this frame.
00013         private SpatialInteractionSourceState sourceState;
00014
00015         // Creates and initializes a GestureRecognizer that listens to a Person.
00016         public SpatialInputHandler()
00017         {
00018             // The interaction manager provides an event that informs the app when
00019             // spatial interactions are detected.
00020             interactionManager = SpatialInteractionManager.GetForCurrentView();
00021
00022             // Bind a handler to the SourcePressed event.
00023             interactionManager.SourcePressed += this.OnSourcePressed;
00024
00025             //
00026             // TODO: Expand this class to use other gesture-based input events as applicable to
00027             //       your app.
00028             //
00029         }
00030
00031         // Checks if the user performed an input gesture since the last call to this method.
00032         // Allows the main update loop to check for asynchronous changes to the user
00033         // input state.
00034         public SpatialInteractionSourceState CheckForInput()
00035         {
00036             SpatialInteractionSourceState sourceState = this.sourceState;
00037             this.sourceState = null;
00038             return sourceState;
00039         }
00040
00041         public void OnSourcePressed(SpatialInteractionManager sender, SpatialInteractionSourceEventArgs args)
00042         {
00043             sourceState = args.State;
00044
00045             //
00046             // TODO: In your app or game engine, rewrite this method to queue
00047             //       input events in your input class or event handler.
00048             //
00049         }
00050     }
00051 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

VideoMetaData Member List

This is the complete list of members for VideoMetaData, including all inherited members.
Id | VideoMetaData
License | VideoMetaData
PubDate | VideoMetaData
Thumbnail | VideoMetaData
Title | VideoMetaData
VideoLink | VideoMetaData
WebPageLink | VideoMetaData
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisplayOrientation/cpp/SampleConfiguration.cpp Source File

  • DisplayOrientation
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Show and lock orientation", "SDKTemplate.Scenario1_Orientation" },
00021 };
Generated on Fri Nov 15 2024 22:17:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cppwinrt/Scenario1.cpp Source File

  • Logging
  • cppwinrt

Scenario1.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1.h"
00014 #include "Scenario1.g.cpp"
00015 #include "LoggingChannelScenario.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::SDKTemplate::implementation;
00019
00020 Scenario1::Scenario1()
00021 {
00022     InitializeComponent();
00023 }
00024
00025 void Scenario1::DoWin81Mode(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00026 {
00027     LoggingChannelScenario().LogWithWin81Constructor();
00028     MainPage::Current().NotifyUser(L"Complete: Windows 8 mode", NotifyType::StatusMessage);
00029 }
00030
00031 void Scenario1::DoWin10Mode(IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&)
00032 {
00033     LoggingChannelScenario().LogWithWin10Constructor();
00034     MainPage::Current().NotifyUser(L"Complete: Windows 10 mode", NotifyType::StatusMessage);
00035 }
Generated on Fri Nov 15 2024 22:19:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: VersionAdaptiveCode/cs/MEUserControl.xaml.cs Source File

  • VersionAdaptiveCode
  • cs

MEUserControl.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml.Controls;
00014
00015 // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class MEUserControl : UserControl
00020     {
00021         public MEUserControl()
00022         {
00023             this.InitializeComponent();
00024         }
00025     }
00026 }
Generated on Fri Nov 15 2024 22:21:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GroupedBackgroundTask Member List

This is the complete list of members for GroupedBackgroundTask, including all inherited members.
AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task) | GroupedBackgroundTask | [inline, private]
AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task) | GroupedBackgroundTask | [inline, private]
group | GroupedBackgroundTask | [private]
GroupedBackgroundTask() | GroupedBackgroundTask | [inline]
GroupedBackgroundTask() | GroupedBackgroundTask | [inline]
OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) | GroupedBackgroundTask | [inline, private]
OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) | GroupedBackgroundTask | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | GroupedBackgroundTask | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | GroupedBackgroundTask | [inline, protected]
OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args) | GroupedBackgroundTask | [inline, private]
OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args) | GroupedBackgroundTask | [inline, private]
RegisterGroupedBackgroundTask(object sender, RoutedEventArgs e) | GroupedBackgroundTask | [inline, private]
RegisterGroupedBackgroundTask(object sender, RoutedEventArgs e) | GroupedBackgroundTask | [inline, private]
rootPage | GroupedBackgroundTask | [private]
UnregisterGroupedTask(object sender, RoutedEventArgs e) | GroupedBackgroundTask | [inline, private]
UnregisterGroupedTask(object sender, RoutedEventArgs e) | GroupedBackgroundTask | [inline, private]
UnregisterUngroupedTasks(object sender, RoutedEventArgs e) | GroupedBackgroundTask | [inline, private]
UnregisterUngroupedTasks(object sender, RoutedEventArgs e) | GroupedBackgroundTask | [inline, private]
UpdateUI() | GroupedBackgroundTask | [inline, private]
UpdateUI() | GroupedBackgroundTask | [inline, private]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

TextMessage Member List

This is the complete list of members for TextMessage, including all inherited members.
Body | TextMessage
DisplayTime | TextMessage
IsReceived | TextMessage
IsSent | TextMessage
Generated on Fri Nov 15 2024 22:24:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ClientDeviceInformation/cpp/Scenario1_GetDeviceInformation.xaml.h Source File

  • ClientDeviceInformation
  • cpp

Scenario1_GetDeviceInformation.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario1_GetDeviceInformation.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario1_GetDeviceInformation sealed
00012     {
00013     public:
00014         Scenario1_GetDeviceInformation();
00015     private:
00016         void Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00017         void Reset_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00018
00019         SDKTemplate::MainPage^ rootPage;
00020     };
00021 }
Generated on Fri Nov 15 2024 22:18:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7_DownloadReordering Member List

This is the complete list of members for Scenario7_DownloadReordering, including all inherited members.
CancelActiveDownloadsAsync() | Scenario7_DownloadReordering | [inline, private]
CreateDownload(BackgroundDownloader downloader, string remoteAddress, string fileName) | Scenario7_DownloadReordering | [inline, private]
DownloadAsync(DownloadOperationItem item) | Scenario7_DownloadReordering | [inline, private]
downloadCollection | Scenario7_DownloadReordering |
DownloadProgress(DownloadOperationItem item) | Scenario7_DownloadReordering | [inline, private]
IsWebException(string title, Exception ex, DownloadOperation download=null) | Scenario7_DownloadReordering | [inline, private]
MakeCurrent_Click(object sender, RoutedEventArgs e) | Scenario7_DownloadReordering | [inline, private]
NumDownloads | Scenario7_DownloadReordering | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario7_DownloadReordering | [inline, protected]
reorderGroup | Scenario7_DownloadReordering | [private]
rootPage | Scenario7_DownloadReordering | [private]
RunDownloadsAsync() | Scenario7_DownloadReordering | [inline, private]
Scenario7_DownloadReordering() | Scenario7_DownloadReordering | [inline]
StartDownload_Click(object sender, RoutedEventArgs e) | Scenario7_DownloadReordering | [inline, private]
Generated on Fri Nov 15 2024 22:23:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario6_Properties.xaml.h Source File

  • FileAccess
  • cpp

Scenario6_Properties.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario6_Properties.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// Displaying file properties.
00022     /// </summary>
00023     [Windows::Foundation::Metadata::WebHostHidden]
00024     public ref class Scenario6 sealed
00025     {
00026     public:
00027         Scenario6();
00028         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029
00030     private:
00031         MainPage^ rootPage = MainPage::Current;
00032
00033         void ShowPropertiesButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034     };
00035 }
Generated on Fri Nov 15 2024 22:19:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFont/pch.h Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFont

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020
00021 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cppwinrt/LoggingScenarioEventArgs.h Source File

  • Logging
  • cppwinrt

LoggingScenarioEventArgs.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "LoggingScenarioEventArgs.g.h"
00014
00015 namespace winrt::SDKTemplate::implementation
00016 {
00017     struct LoggingScenarioEventArgs : LoggingScenarioEventArgsT<LoggingScenarioEventArgs>
00018     {
00019         // e.g. for BusyStatusChanged
00020         LoggingScenarioEventArgs(LoggingScenarioEventType type)
00021             : _type(type) {}
00022
00023         // e.g. for LogFileGenerated
00024         LoggingScenarioEventArgs(LoggingScenarioEventType type, hstring const& logFileFullPath)
00025             : _type(type), _logFileFullPath(logFileFullPath) {}
00026
00027         // e.g. for LoggingEnabledDisabled
00028         LoggingScenarioEventArgs(LoggingScenarioEventType type, bool enabled)
00029             : _type(type), _enabled(enabled) {}
00030
00031         LoggingScenarioEventType Type() const noexcept { return _type; }
00032         bool Enabled() const noexcept { return _enabled; }
00033         hstring LogFileFullPath() const noexcept { return _logFileFullPath; }
00034
00035     private:
00036         LoggingScenarioEventType _type;
00037         bool _enabled = false;
00038         hstring _logFileFullPath;
00039     };
00040 }
Generated on Fri Nov 15 2024 22:20:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlPivot/cs/Scenario2.xaml.cs Source File

  • XamlPivot
  • cs

Scenario2.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Collections.ObjectModel;
00015 using System.Linq;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Media.Imaging;
00019
00020 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00021
00022 namespace PivotCS
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class Scenario2 : Page
00028     {
00029         public ObservableCollection<SampleDataModel> Suggestions { get; private set; }
00030         public List<SampleDataModel> NewItems = null;
00031         public List<SampleDataModel> FlaggedItems = null;
00032         public List<SampleDataModel> AllItems = null;
00033
00034         public Scenario2()
00035         {
00036             this.InitializeComponent();
00037             NewItems = SampleDataModel.GetSampleData().Where(x => x.IsNew).ToList();
00038             FlaggedItems = SampleDataModel.GetSampleData().Where(x => x.IsFlagged).ToList();
00039             AllItems = SampleDataModel.GetSampleData().ToList();
00040             this.Suggestions = new ObservableCollection<SampleDataModel>();
00041
00042             this.DataContext = this;
00043         }
00044
00045
00046         private void BackButton_Click(object sender, RoutedEventArgs e)
00047         {
00048             if (this.Frame.CanGoBack)
00049                 this.Frame.GoBack();
00050         }
00051
00052         private void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
00053         {
00054             // TODO: not being called from flyout
00055             if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
00056             {
00057                 Suggestions.Clear();
00058                 foreach (var Item in AllItems)
00059                 {
00060                     if (Item.Title.IndexOf(sender.Text, StringComparison.OrdinalIgnoreCase) >= 0)
00061                     {
00062                         Suggestions.Add(Item);
00063                     }
00064                 }
00065             }
00066         }
00067
00068
00069         private void AutoSuggestBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
00070         {
00071             SampleDataModel FoundItem = null;
00072
00073             if (args.ChosenSuggestion != null && args.ChosenSuggestion is SampleDataModel)
00074             {
00075                 FoundItem = args.ChosenSuggestion as SampleDataModel;
00076             }
00077             else if (String.IsNullOrEmpty(args.QueryText) == false)
00078             {
00079                 foreach (var Item in AllItems)
00080                 {
00081                     if (Item.Title.Equals(args.QueryText, StringComparison.OrdinalIgnoreCase))
00082                     {
00083                         FoundItem = Item;
00084                         break;
00085                     }
00086                 }
00087             }
00088
00089             ShowItem(FoundItem);
00090         }
00091
00092         async private void ShowItem(SampleDataModel model)
00093         {
00094             var MyDialog = new ContentDialog();
00095
00096             if (model != null)
00097             {
00098                 var MyImage = new Image();
00099                 MyImage.Source = new BitmapImage(new Uri(model.ImagePath));
00100                 MyImage.HorizontalAlignment = HorizontalAlignment.Stretch;
00101                 MyImage.VerticalAlignment = VerticalAlignment.Stretch;
00102                 MyImage.Stretch = Windows.UI.Xaml.Media.Stretch.UniformToFill;
00103                 MyDialog.Title = String.Format("You have selected {0}", model.ToString());
00104                 MyDialog.Content = MyImage;
00105             }
00106             else
00107             {
00108                 MyDialog.Title = "No item found";
00109             }
00110
00111             MyDialog.PrimaryButtonText = "OK";
00112             await MyDialog.ShowAsync();
00113
00114         }
00115
00116         private void ListView_ItemClicked(object sender, ItemClickEventArgs e)
00117         {
00118             SampleDataModel SelectedItem = e.ClickedItem as SampleDataModel;
00119             ShowItem(SelectedItem);
00120         }
00121     }
00122 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ShowConnection Member List

This is the complete list of members for ShowConnection, including all inherited members.
deviceAccountId | ShowConnection | [private]
OnNavigatedTo(NavigationEventArgs e) | ShowConnection | [inline, protected]
PrepareScenario() | ShowConnection | [inline, private]
rootPage | ShowConnection | [private]
ShowConnection() | ShowConnection | [inline]
ShowConnectionUI_Click(object sender, RoutedEventArgs e) | ShowConnection | [inline, private]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/xBindSampleModel/BoolToVisibilityConverter.cs Source File

  • XamlBind
  • cpp
  • xBindSampleModel

BoolToVisibilityConverter.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using Windows.UI.Xaml.Data;
00007
00008 namespace xBindSampleModel
00009 {
00010     public sealed class BoolToVisibilityConverter : IValueConverter
00011     {
00012         object IValueConverter.Convert(object value, Type targetType, object parameter, string language)
00013         {
00014             if (!value.GetType().Equals(typeof(bool)))
00015             {
00016                 throw new ArgumentException("Only Boolean is supported");
00017             }
00018             if (targetType.Equals(typeof(Windows.UI.Xaml.Visibility)))
00019             {
00020                 return ((bool)value) ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed;
00021             }
00022             else
00023             {
00024                 throw new ArgumentException("Unsuported type {0}", targetType.FullName);
00025             }
00026         }
00027
00028         object IValueConverter.ConvertBack(object value, Type targetType, object parameter, string language)
00029         {
00030             throw new NotImplementedException();
00031         }
00032     }
00033 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlMasterDetail/cppwinrt/SampleConfiguration.cpp Source File

  • XamlMasterDetail
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"Resize app view";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Resizing the view", xaml_typename<SDKTemplate::Scenario1_Basic>() },
00029     Scenario{ L"Launching at a custom size", xaml_typename<SDKTemplate::Scenario2_Launch>() },
00030 });
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FileDataSource Member List

This is the complete list of members for FileDataSource, including all inherited members.
_count | FileDataSource | [private]
_dispatcher | FileDataSource | [private]
_folder | FileDataSource | [private]
_queryResult | FileDataSource | [private]
Add(object value) | FileDataSource | [inline]
Clear() | FileDataSource | [inline]
CollectionChanged | FileDataSource |
Contains(object value) | FileDataSource | [inline]
CopyTo(Array array, int index) | FileDataSource | [inline]
Count | FileDataSource |
Dispose() | FileDataSource | [inline]
fetchDataCallback(ItemIndexRange batch, CancellationToken ct) | FileDataSource | [inline, private]
FileDataSource() | FileDataSource | [inline, private]
GetDataSoure(string path) | FileDataSource | [inline, static]
GetEnumerator() | FileDataSource | [inline]
IndexOf(object value) | FileDataSource | [inline]
Insert(int index, object value) | FileDataSource | [inline]
IsFixedSize | FileDataSource |
IsReadOnly | FileDataSource |
IsSynchronized | FileDataSource |
itemCache | FileDataSource | [private]
ItemCache_CacheChanged(object sender, CacheChangedEventArgs< FileItem > args) | FileDataSource | [inline, private]
QueryResult_ContentsChanged(IStorageQueryResultBase sender, object args) | FileDataSource | [inline, private]
RangesChanged(ItemIndexRange visibleRange, IReadOnlyList< ItemIndexRange > trackedItems) | FileDataSource | [inline]
Remove(object value) | FileDataSource | [inline]
RemoveAt(int index) | FileDataSource | [inline]
ResetCollection() | FileDataSource | [inline, private]
SetFolder(StorageFolder folder) | FileDataSource | [inline]
SyncRoot | FileDataSource |
this | FileDataSource |
UpdateCount() | FileDataSource | [inline, private]
Generated on Fri Nov 15 2024 22:23:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cpp/Tasks/ActivitySensorBackgroundTask.cpp Source File

  • ActivitySensor
  • cpp
  • Tasks

ActivitySensorBackgroundTask.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ActivitySensorBackgroundTask.cpp
00014 // Implementation of the ActivitySensorBackgroundTask class
00015 //
00016
00017 #include "pch.h"
00018 #include "ActivitySensorBackgroundTask.h"
00019
00020 using namespace Windows::Devices::Sensors;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Globalization;
00023 using namespace Windows::Globalization::DateTimeFormatting;
00024 using namespace Windows::Storage;
00025
00026 using namespace Tasks;
00027
00028 /// <summary>
00029 /// The entry point of a background task.
00030 /// </summary>
00031 /// <param name="taskInstance">The current background task instance.</param>
00032 void ActivitySensorBackgroundTask::Run(IBackgroundTaskInstance^ taskInstance)
00033 {
00034     // Associate a cancellation handler with the background task.
00035     // Even though this task isn't performing much work, it can still be cancelled.
00036     taskInstance->Canceled += ref new BackgroundTaskCanceledEventHandler(this, &ActivitySensorBackgroundTask::OnCanceled);
00037
00038     // Read the activity reports
00039     ActivitySensorTriggerDetails^ triggerDetails = safe_cast<ActivitySensorTriggerDetails^>(taskInstance->TriggerDetails);
00040     auto reports = triggerDetails->ReadReports();
00041
00042     auto settings = ApplicationData::Current->LocalSettings;
00043     settings->Values->Insert("ReportCount", reports->Size.ToString());
00044
00045     auto timestampFormatter = ref new DateTimeFormatter("day month year hour minute second");
00046     if (reports->Size > 0)
00047     {
00048         auto lastReading = reports->GetAt(reports->Size - 1)->Reading;
00049         settings->Values->Insert("LastActivity", lastReading->Activity.ToString());
00050         settings->Values->Insert("LastConfidence", lastReading->Confidence.ToString());
00051         settings->Values->Insert("LastTimestamp", timestampFormatter->Format(lastReading->Timestamp));
00052     }
00053     else
00054     {
00055         settings->Values->Insert("LastActivity", "No data");
00056         settings->Values->Insert("LastConfidence", "No data");
00057         settings->Values->Insert("LastTimestamp", "No data");
00058     }
00059
00060     auto calendar = ref new Calendar();
00061     calendar->SetToNow();
00062     settings->Values->Insert("TaskStatus", "Completed at " + timestampFormatter->Format(calendar->GetDateTime()));
00063     // No deferral is held on taskInstance because we are returning immediately.
00064 }
00065
00066 /// <summary>
00067 /// Handles background task cancellation.
00068 /// </summary>
00069 /// <param name="sender">The background task instance being cancelled.</param>
00070 /// <param name="reason">The cancellation reason.</param>
00071 void ActivitySensorBackgroundTask::OnCanceled(IBackgroundTaskInstance^ /*taskInstance*/, BackgroundTaskCancellationReason reason)
00072 {
00073     auto settings = ApplicationData::Current->LocalSettings;
00074     auto timestampFormatter = ref new DateTimeFormatter("day month year hour minute second");
00075
00076     auto calendar = ref new Calendar();
00077     calendar->SetToNow();
00078     settings->Values->Insert("TaskStatus", reason.ToString() + " at " + timestampFormatter->Format(calendar->GetDateTime()));
00079 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisablingScreenCapture/cpp/Scenario1_Enable.xaml.h Source File

  • DisablingScreenCapture
  • cpp

Scenario1_Enable.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Enable.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario1_Enable sealed
00021     {
00022     public:
00023         Scenario1_Enable();
00024     };
00025 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cs/ShareCustomData.xaml.cs Source File

  • ShareSource
  • cs

ShareCustomData.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.DataTransfer;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public sealed partial class ShareCustomData
00019     {
00020         public ShareCustomData()
00021         {
00022             this.InitializeComponent();
00023             CustomDataTextBox.Text =
00024             @"{
00025                ""type"" : ""http://schema.org/Book"",
00026                ""properties"" :
00027                {
00028                 ""image"" : ""http://sourceurl.com/catcher-in-the-rye-book-cover.jpg"",
00029                 ""name"" : ""The Catcher in the Rye"",
00030                 ""bookFormat"" : ""http://schema.org/Paperback"",
00031                 ""author"" : ""http://sourceurl.com/author/jd_salinger.html"",
00032                 ""numberOfPages"" : 224,
00033                 ""publisher"" : ""Little, Brown, and Company"",
00034                 ""datePublished"" : ""1991-05-01"",
00035                 ""inLanguage"" : ""English"",
00036                 ""isbn"" : ""0316769487""
00037                 }
00038             }";
00039         }
00040
00041         protected override bool GetShareContent(DataRequest request)
00042         {
00043             bool succeeded = false;
00044
00045             string dataPackageFormat = DataFormatInputBox.Text;
00046             if (!String.IsNullOrEmpty(dataPackageFormat))
00047             {
00048                 string dataPackageText = CustomDataTextBox.Text;
00049                 if (!String.IsNullOrEmpty(dataPackageText))
00050                 {
00051                     DataPackage requestData = request.Data;
00052                     requestData.Properties.Title = TitleInputBox.Text;
00053                     requestData.Properties.Description = DescriptionInputBox.Text; // The description is optional.
00054                     requestData.Properties.ContentSourceApplicationLink = ApplicationLink;
00055                     requestData.SetData(dataPackageFormat, dataPackageText);
00056                     succeeded = true;
00057                 }
00058                 else
00059                 {
00060                     request.FailWithDisplayText("Enter the custom data you would like to share and try again.");
00061                 }
00062             }
00063             else
00064             {
00065                 request.FailWithDisplayText("Enter a custom data format and try again.");
00066             }
00067             return succeeded;
00068         }
00069     }
00070 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cppwinrt/Scenario5_LaunchedFromSecondaryTile.h Source File

  • SecondaryTiles
  • cppwinrt

Scenario5_LaunchedFromSecondaryTile.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario5_LaunchedFromSecondaryTile.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario5_LaunchedFromSecondaryTile : Scenario5_LaunchedFromSecondaryTileT<Scenario5_LaunchedFromSecondaryTile>
00020     {
00021         Scenario5_LaunchedFromSecondaryTile();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024
00025     private:
00026         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario5_LaunchedFromSecondaryTile : Scenario5_LaunchedFromSecondaryTileT<Scenario5_LaunchedFromSecondaryTile, implementation::Scenario5_LaunchedFromSecondaryTile>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:21:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Barometer/cs/Scenario2_Polling.xaml.cs Source File

  • Barometer
  • cs

Scenario2_Polling.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Devices.Sensors;
00015 using Windows.Foundation;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario2_Polling : Page
00024     {
00025         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00026         // as NotifyUser()
00027         MainPage rootPage = MainPage.Current;
00028
00029         private Barometer sensor;
00030
00031         public Scenario2_Polling()
00032         {
00033             this.InitializeComponent();
00034
00035             sensor = Barometer.GetDefault();
00036             if (null == sensor)
00037             {
00038                 rootPage.NotifyUser("No barometer found", NotifyType.ErrorMessage);
00039             }
00040         }
00041
00042         /// <summary>
00043         /// This is the click handler for the 'GetData' button.
00044         /// </summary>
00045         /// <param name="sender"></param>
00046         /// <param name="e"></param>
00047         private void ScenarioGetData(object sender, RoutedEventArgs e)
00048         {
00049             if (null != sensor)
00050             {
00051                 BarometerReading reading = sensor.GetCurrentReading();
00052                 if (null != reading)
00053                 {
00054                     ScenarioOutput_hPa.Text = String.Format("{0,5:0.00}", reading.StationPressureInHectopascals);
00055                 }
00056             }
00057             else
00058             {
00059                 rootPage.NotifyUser("No barometer found", NotifyType.ErrorMessage);
00060             }
00061         }
00062     }
00063 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TitleBar/cpp/Scenario2_Extend.xaml.cpp Source File

  • TitleBar
  • cpp

Scenario2_Extend.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Extend.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::ApplicationModel::Core;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Core;
00022 using namespace Windows::UI::ViewManagement;
00023 using namespace Windows::UI::Xaml;
00024 using namespace Windows::UI::Xaml::Controls;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 Scenario2_Extend::Scenario2_Extend()
00028 {
00029     InitializeComponent();
00030     ExtendView->IsChecked = CoreApplication::GetCurrentView()->TitleBar->ExtendViewIntoTitleBar;
00031     EnableControls->Visibility = ExtendView->IsChecked->Value ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00032     EnableControls->IsChecked = rootPage->AreControlsInTitleBar;
00033 }
00034
00035 void Scenario2_Extend::OnNavigatedTo(NavigationEventArgs^ args)
00036 {
00037     // The SizeChanged event is raised when full screen mode changes.
00038     windowSizeChangedToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &Scenario2_Extend::OnWindowSizeChanged);
00039     UpdateFullScreenModeStatus();
00040 }
00041
00042 void Scenario2_Extend::OnNavigatedFrom(NavigationEventArgs^ e)
00043 {
00044     Window::Current->SizeChanged -= windowSizeChangedToken;
00045 }
00046
00047 void Scenario2_Extend::ExtendView_Click(Object^ sender, RoutedEventArgs^ e)
00048 {
00049     bool extend = ExtendView->IsChecked->Value;
00050     CoreApplication::GetCurrentView()->TitleBar->ExtendViewIntoTitleBar = extend;
00051     EnableControls->Visibility = extend ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00052     if (extend)
00053     {
00054         rootPage->AddCustomTitleBar();
00055     }
00056     else
00057     {
00058         rootPage->RemoveCustomTitleBar();
00059     }
00060 }
00061
00062 void Scenario2_Extend::EnableControls_Click(Object^ sender, RoutedEventArgs^ e)
00063 {
00064     rootPage->AreControlsInTitleBar = EnableControls->IsChecked->Value;
00065 }
00066
00067 void Scenario2_Extend::ToggleFullScreenModeButton_Click(Object^ sender, RoutedEventArgs^ e)
00068 {
00069     ApplicationView^ view = ApplicationView::GetForCurrentView();
00070     if (view->IsFullScreenMode)
00071     {
00072         view->ExitFullScreenMode();
00073         rootPage->NotifyUser("Exited full screen mode", NotifyType::StatusMessage);
00074     }
00075     else
00076     {
00077         if (view->TryEnterFullScreenMode())
00078         {
00079             rootPage->NotifyUser("Entered full screen mode", NotifyType::StatusMessage);
00080         }
00081         else
00082         {
00083             rootPage->NotifyUser("Failed to enter full screen mode", NotifyType::ErrorMessage);
00084         }
00085     }
00086 }
00087
00088 void Scenario2_Extend::OnWindowSizeChanged(Object^ sender, WindowSizeChangedEventArgs^ args)
00089 {
00090     UpdateFullScreenModeStatus();
00091 }
00092
00093 void Scenario2_Extend::UpdateFullScreenModeStatus()
00094 {
00095     ApplicationView^ view = ApplicationView::GetForCurrentView();
00096     bool isFullScreenMode = view->IsFullScreenMode;
00097     ToggleFullScreenModeSymbol->Symbol = isFullScreenMode ? Symbol::BackToWindow : Symbol::FullScreen;
00098     ReportFullScreenMode->Text = isFullScreenMode ? "is in" : "is not in";
00099 }
Generated on Fri Nov 15 2024 22:21:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
currentFeed | sealed | [private]
currentItemIndex | sealed | [private]
DisplayCurrentItem() | sealed | [private]
DisplayFeed() | sealed | [private]
GetFeed_Click(Object^sender, RoutedEventArgs^e) | sealed | [private]
LinkField_Click(Object^sender, RoutedEventArgs^e) | sealed | [private]
NextItem_Click(Object^sender, RoutedEventArgs^e) | sealed | [private]
OnNavigatedTo(NavigationEventArgs^e) override | sealed | [protected, virtual]
PreviousItem_Click(Object^sender, RoutedEventArgs^e) | sealed | [private]
rootPage | sealed | [private]
Scenario1() | sealed |
Generated on Fri Nov 15 2024 22:24:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Package/cpp/pch.cpp Source File

  • Package
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/BackgroundTask/SampleConfiguration.cpp Source File

  • BackgroundTask
  • cpp
  • BackgroundTask

SampleConfiguration.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
00012 #include "MainPage.xaml.h"
00013 #include "SampleConfiguration.h"
00014
00015 using namespace SDKTemplate;
00016
00017 String^ BackgroundTaskSample::SampleBackgroundTaskProgress = "";
00018 bool BackgroundTaskSample::SampleBackgroundTaskRegistered = false;
00019
00020 String^ BackgroundTaskSample::SampleBackgroundTaskWithConditionProgress = "";
00021 bool BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered = false;
00022
00023 String^ BackgroundTaskSample::ServicingCompleteTaskProgress = "";
00024 bool BackgroundTaskSample::ServicingCompleteTaskRegistered = false;
00025
00026 String^ BackgroundTaskSample::TimeTriggeredTaskProgress = "";
00027 bool BackgroundTaskSample::TimeTriggeredTaskRegistered = false;
00028
00029 String^ BackgroundTaskSample::ApplicationTriggerTaskProgress = "";
00030 bool BackgroundTaskSample::ApplicationTriggerTaskRegistered = false;
00031 String^ BackgroundTaskSample::ApplicationTriggerTaskResult = "";
00032
00033 String^ BackgroundTaskSample::GroupedBackgroundTaskProgress = "";
00034 bool BackgroundTaskSample::GroupedBackgroundTaskRegistered = false;
00035
00036 Array<Scenario>^ MainPage::scenariosInner = ref new Array<Scenario>
00037 {
00038     // The format here is the following:
00039     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00040     { "Background task", "SDKTemplate.SampleBackgroundTask" },
00041     { "Background task with a condition", "SDKTemplate.SampleBackgroundTaskWithCondition" },
00042     { "Servicing complete task", "SDKTemplate.ServicingCompleteTask" },
00043     { "Background task with time trigger", "SDKTemplate.TimeTriggeredTask" },
00044     { "Background task with application trigger", "SDKTemplate.ApplicationTriggerTask" },
00045     { "Grouped background task", "SDKTemplate.GroupedBackgroundTask" },
00046 };
00047
00048 String^ BackgroundTaskSample::GetBackgroundTaskStatus(String^ name)
00049 {
00050     auto registered = false;
00051     if (name == SampleBackgroundTaskName)
00052     {
00053         registered = BackgroundTaskSample::SampleBackgroundTaskRegistered;
00054     }
00055     else if (name == SampleBackgroundTaskWithConditionName)
00056     {
00057         registered = BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered;
00058     }
00059     else if (name == ServicingCompleteTaskName)
00060     {
00061         registered = BackgroundTaskSample::ServicingCompleteTaskRegistered;
00062     }
00063     else if (name == TimeTriggeredTaskName)
00064     {
00065         registered = BackgroundTaskSample::TimeTriggeredTaskRegistered;
00066     }
00067     else if (name == ApplicationTriggerTaskName)
00068     {
00069         registered = BackgroundTaskSample::ApplicationTriggerTaskRegistered;
00070     }
00071     else if (name == GroupedBackgroundTaskName)
00072     {
00073         registered = BackgroundTaskSample::GroupedBackgroundTaskRegistered;
00074     }
00075
00076     String^ status = registered ? "Registered" : "Unregistered";
00077
00078     auto settings = ApplicationData::Current->LocalSettings->Values;
00079     if (settings->HasKey(name))
00080     {
00081         status += " - " + dynamic_cast<String^>(settings->Lookup(name));
00082     }
00083
00084     return status;
00085 }
00086
00087 BackgroundTaskRegistration^ BackgroundTaskSample::RegisterBackgroundTask(String^ taskEntryPoint, String^ name, IBackgroundTrigger^ trigger, IBackgroundCondition^ condition, BackgroundTaskRegistrationGroup^ group)
00088 {
00089     if (TaskRequiresBackgroundAccess(name))
00090     {
00091         BackgroundExecutionManager::RequestAccessAsync();
00092     }
00093
00094     auto builder = ref new BackgroundTaskBuilder();
00095
00096     builder->Name = name;
00097     builder->TaskEntryPoint = taskEntryPoint;
00098     builder->SetTrigger(trigger);
00099
00100     if (condition != nullptr)
00101     {
00102         builder->AddCondition(condition);
00103
00104         //
00105         // If the condition changes while the background task is executing then it will
00106         // be canceled.
00107         //
00108         builder->CancelOnConditionLoss = true;
00109     }
00110
00111     if (group != nullptr)
00112     {
00113         builder->TaskGroup = group;
00114     }
00115
00116     auto task = builder->Register();
00117
00118     UpdateBackgroundTaskRegistrationStatus(name, true);
00119
00120     //
00121     // Remove previous completion status from local settings.
00122     //
00123     auto settings = ApplicationData::Current->LocalSettings->Values;
00124     settings->Remove(name);
00125
00126     return task;
00127 }
00128
00129 bool BackgroundTaskSample::TaskRequiresBackgroundAccess(String^ name)
00130 {
00131     if ((name == TimeTriggeredTaskName) ||
00132         (name == ApplicationTriggerTaskName))
00133     {
00134         return true;
00135     }
00136     else
00137     {
00138         return false;
00139     }
00140 }
00141
00142 void BackgroundTaskSample::UnregisterBackgroundTasks(String^ name, BackgroundTaskRegistrationGroup^ group)
00143 {
00144     //
00145     // If the given task group is registered then loop through all background tasks associated with it
00146     // and unregister any with the name passed into this function.
00147     //
00148     if (group != nullptr)
00149     {
00150         for (auto pair : group->AllTasks)
00151         {
00152             auto task = pair->Value;
00153             if (task->Name == name)
00154             {
00155                 task->Unregister(true);
00156             }
00157         }
00158     }
00159     else
00160     {
00161         //
00162         // Loop through all ungrouped background tasks and unregister any with the name passed into this function.
00163         //
00164         for (auto pair : BackgroundTaskRegistration::AllTasks)
00165         {
00166             auto task = pair->Value;
00167             if (task->Name == name)
00168             {
00169                 task->Unregister(true);
00170             }
00171         }
00172     }
00173
00174     UpdateBackgroundTaskRegistrationStatus(name, false);
00175 }
00176
00177 BackgroundTaskRegistrationGroup^ BackgroundTaskSample::GetTaskGroup(String^ id, String^ groupName)
00178 {
00179     auto group = BackgroundTaskRegistration::GetTaskGroup(id);
00180
00181     if (group == nullptr)
00182     {
00183         group = ref new BackgroundTaskRegistrationGroup(id, groupName);
00184     }
00185
00186     return group;
00187 }
00188
00189 void BackgroundTaskSample::UpdateBackgroundTaskRegistrationStatus(String^ name, bool registered)
00190 {
00191     if (name == SampleBackgroundTaskName)
00192     {
00193         BackgroundTaskSample::SampleBackgroundTaskRegistered = registered;
00194     }
00195     else if (name == SampleBackgroundTaskWithConditionName)
00196     {
00197         BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered = registered;
00198     }
00199     else if (name == ServicingCompleteTaskName)
00200     {
00201         BackgroundTaskSample::ServicingCompleteTaskRegistered = registered;
00202     }
00203     else if (name == TimeTriggeredTaskName)
00204     {
00205         BackgroundTaskSample::TimeTriggeredTaskRegistered = registered;
00206     }
00207     else if (name == ApplicationTriggerTaskName)
00208     {
00209         BackgroundTaskSample::ApplicationTriggerTaskRegistered = registered;
00210     }
00211     else if (name == GroupedBackgroundTaskName)
00212     {
00213         BackgroundTaskSample::GroupedBackgroundTaskRegistered = registered;
00214     }
00215 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Playlists/cs/Scenario5_Clear.xaml.cs Source File

  • Playlists
  • cs

Scenario5_Clear.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Media.Playlists;
00015 using Windows.Storage;
00016 using Windows.Storage.Pickers;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario5_Clear : Page
00024     {
00025         private MainPage rootPage = MainPage.Current;
00026
00027         public Scenario5_Clear()
00028         {
00029             this.InitializeComponent();
00030         }
00031
00032         /// <summary>
00033         /// Clears the playlist picked by the user in the FilePicker
00034         /// </summary>
00035         /// <param name="sender"></param>
00036         /// <param name="e"></param>
00037         async private void PickPlaylistButton_Click(object sender, RoutedEventArgs e)
00038         {
00039             Playlist playlist = await rootPage.PickPlaylistAsync();
00040
00041             if (playlist != null)
00042             {
00043                 playlist.Files.Clear();
00044
00045                 if (await rootPage.TrySavePlaylistAsync(playlist))
00046                 {
00047                     this.rootPage.NotifyUser("Playlist cleared.", NotifyType.StatusMessage);
00048                 }
00049             }
00050         }
00051     }
00052 }
Generated on Fri Nov 15 2024 22:20:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cs/Scenario4_ChangeAdminKey.xaml.cs Source File

  • SmartCard
  • cs

Scenario4_ChangeAdminKey.xaml.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using Windows.Devices.SmartCards;
00003 using Windows.Security.Cryptography;
00004 using Windows.Storage.Streams;
00005 using Windows.UI.Xaml;
00006 using Windows.UI.Xaml.Controls;
00007
00008 namespace SDKTemplate
00009 {
00010     public sealed partial class Scenario4_ChangeAdminKey : Page
00011     {
00012         private MainPage rootPage = MainPage.Current;
00013
00014         public Scenario4_ChangeAdminKey()
00015         {
00016             this.InitializeComponent();
00017         }
00018
00019         /// <summary>
00020         /// Click handler for the 'ChangeAdminKey' button.
00021         /// </summary>
00022         /// <param name="sender"></param>
00023         /// <param name="e"></param>
00024         private async void ChangeAdminKey_Click(object sender, RoutedEventArgs e)
00025         {
00026             if (!rootPage.ValidateTPMSmartCard())
00027             {
00028                 rootPage.NotifyUser("Use Scenario One to create a TPM virtual smart card.", NotifyType.ErrorMessage);
00029                 return;
00030             }
00031
00032             Button b = sender as Button;
00033             b.IsEnabled = false;
00034
00035             try
00036             {
00037                 IBuffer newadminkey = CryptographicBuffer.GenerateRandom(MainPage.ADMIN_KEY_LENGTH_IN_BYTES);
00038
00039                 SmartCard card = await rootPage.GetSmartCard();
00040                 SmartCardProvisioning provisioning = await SmartCardProvisioning.FromSmartCardAsync(card);
00041
00042                 rootPage.NotifyUser("Changing smart card admin key...", NotifyType.StatusMessage);
00043
00044                 using (SmartCardChallengeContext context = await provisioning.GetChallengeContextAsync())
00045                 {
00046                     IBuffer response = ChallengeResponseAlgorithm.CalculateResponse(context.Challenge, rootPage.AdminKey);
00047
00048                     await context.ChangeAdministrativeKeyAsync(response, newadminkey);
00049                     rootPage.AdminKey = newadminkey;
00050                 }
00051
00052                 rootPage.NotifyUser("Smart card change admin key operation completed.", NotifyType.StatusMessage);
00053             }
00054             catch (Exception ex)
00055             {
00056                 rootPage.NotifyUser("Changing smart card admin key operation failed with exception: " + ex.ToString(), NotifyType.ErrorMessage);
00057             }
00058             finally
00059             {
00060                 b.IsEnabled = true;
00061             }
00062         }
00063     }
00064 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
__pad0__ | sealed |
_customDataType | sealed | [private]
_dataSize | sealed | [private]
_entities | sealed | [private]
_entityId | sealed | [private]
_entityIndex | sealed | [private]
_frame | sealed | [private]
_frameBuffer | sealed | [private]
_isTracked | sealed | [private]
_mediaFrameReference | sealed | [private]
_offset | sealed |
_offset(offset) | sealed |
_posesCount | sealed | [private]
_poseSetId | sealed | [private]
_size | sealed |
_size(size) | sealed | [inline]
_status | sealed | [private]
_status(status) | sealed | [inline]
entityHeader | sealed |
entityIndex | sealed |
GetCustomData() | sealed |
GetCustomData() | sealed |
GetPoses(_In_ const Platform::Array< unsigned int >^indices, _Out_ Platform::WriteOnlyArray< TrackedPose >^poses) | sealed |
offset | sealed |
PoseTrackingFrame(Windows::Media::Capture::Frames::MediaFrameReference^mediaFrameReference, _In_ REFIID customDataType, _In_ Windows::Storage::Streams::IBuffer^frameBuffer, _In_ Windows::Foundation::Collections::IVectorView< PoseTrackingEntity^>^entities) | sealed | [private]
size | sealed |
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BasicLoader Member List

This is the complete list of members for BasicLoader, including all inherited members.
__pad0__ | BasicLoader |
BasicLoader(_In_ winrt::com_ptr< ID3D11Device3 > d3dDevice, _In_opt_ IWICImagingFactory2 *wicFactory=nullptr) | BasicLoader |
CreateInputLayout(_In_reads_bytes_(bytecodeSize) byte *bytecode, _In_ uint32 bytecodeSize, _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC *layoutDesc, _In_ uint32 layoutDescNumElements, _Out_ ID3D11InputLayout **layout) | BasicLoader | [private]
CreateInputLayout(_In_reads_bytes_(bytecodeSize) const byte *bytecode, _In_ uint32_t bytecodeSize, _In_reads_opt_(layoutDescNumElements) const D3D11_INPUT_ELEMENT_DESC *layoutDesc, _In_ uint32_t layoutDescNumElements, _Out_ ID3D11InputLayout **layout) | BasicLoader | [private]
CreateInputLayout(_In_reads_bytes_(bytecodeSize) byte *bytecode, _In_ uint32 bytecodeSize, _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC *layoutDesc, _In_ uint32 layoutDescNumElements, _Out_ ID3D11InputLayout **layout) | BasicLoader | [private]
CreateMesh(_In_ byte *meshData, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount, _In_opt_ Platform::String^debugName) | BasicLoader | [private]
CreateMesh(_In_ byte *meshData, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32_t *vertexCount, _Out_opt_ uint32_t *indexCount, _In_opt_ winrt::hstring const &debugName) | BasicLoader | [private]
CreateMesh(_In_ byte *meshData, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount, _In_opt_ Platform::String^debugName) | BasicLoader | [private]
CreateTexture(_In_ bool decodeAsDDS, _In_reads_bytes_(dataSize) byte *data, _In_ uint32 dataSize, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView, _In_opt_ Platform::String^debugName) | BasicLoader | [private]
CreateTexture(_In_ bool decodeAsDDS, _In_reads_bytes_(dataSize) const byte *data, _In_ uint32_t dataSize, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView, _In_opt_ winrt::hstring const &debugName) | BasicLoader | [private]
CreateTexture(_In_ bool decodeAsDDS, _In_reads_bytes_(dataSize) byte *data, _In_ uint32 dataSize, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView, _In_opt_ Platform::String^debugName) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
GetExtension(_In_ winrt::hstring const &filename) | BasicLoader | [private]
GetExtension(_In_ Platform::String^filename) | BasicLoader | [private]
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMesh(_In_ winrt::hstring const &filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32_t *vertexCount, _Out_opt_ uint32_t *indexCount) | BasicLoader |
LoadMesh(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMeshAsync(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadMeshAsync(_In_ winrt::hstring filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32_t *vertexCount, _Out_opt_ uint32_t *indexCount) | BasicLoader |
LoadMeshAsync(_In_ Platform::String^filename, _Out_ ID3D11Buffer **vertexBuffer, _Out_ ID3D11Buffer **indexBuffer, _Out_opt_ uint32 *vertexCount, _Out_opt_ uint32 *indexCount) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[], _In_ uint32 layoutDescNumElements, _Out_ ID3D11VertexShader **shader, _Out_opt_ ID3D11InputLayout **layout) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _Out_ ID3D11PixelShader **shader) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _Out_ ID3D11ComputeShader **shader) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _Out_ ID3D11GeometryShader **shader) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY *streamOutDeclaration, _In_ uint32 numEntries, _In_reads_opt_(numStrides) const uint32 *bufferStrides, _In_ uint32 numStrides, _In_ uint32 rasterizedStream, _Out_ ID3D11GeometryShader **shader) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _Out_ ID3D11HullShader **shader) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _Out_ ID3D11DomainShader **shader) | BasicLoader |
LoadShader(_In_ winrt::hstring const &filename, _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC const layoutDesc[], _In_ uint32_t layoutDescNumElements, _Out_ ID3D11VertexShader **shader, _Out_opt_ ID3D11InputLayout **layout) | BasicLoader |
LoadShader(_In_ winrt::hstring const &filename, _Out_ ID3D11PixelShader **shader) | BasicLoader |
LoadShader(_In_ winrt::hstring const &filename, _Out_ ID3D11ComputeShader **shader) | BasicLoader |
LoadShader(_In_ winrt::hstring const &filename, _Out_ ID3D11GeometryShader **shader) | BasicLoader |
LoadShader(_In_ winrt::hstring const &filename, _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY *streamOutDeclaration, _In_ uint32_t numEntries, _In_reads_opt_(numStrides) const uint32_t *bufferStrides, _In_ uint32_t numStrides, _In_ uint32_t rasterizedStream, _Out_ ID3D11GeometryShader **shader) | BasicLoader |
LoadShader(_In_ winrt::hstring const &filename, _Out_ ID3D11HullShader **shader) | BasicLoader |
LoadShader(_In_ winrt::hstring const &filename, _Out_ ID3D11DomainShader **shader) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[], _In_ uint32 layoutDescNumElements, _Out_ ID3D11VertexShader **shader, _Out_opt_ ID3D11InputLayout **layout) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _Out_ ID3D11PixelShader **shader) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _Out_ ID3D11ComputeShader **shader) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _Out_ ID3D11GeometryShader **shader) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY *streamOutDeclaration, _In_ uint32 numEntries, _In_reads_opt_(numStrides) const uint32 *bufferStrides, _In_ uint32 numStrides, _In_ uint32 rasterizedStream, _Out_ ID3D11GeometryShader **shader) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _Out_ ID3D11HullShader **shader) | BasicLoader |
LoadShader(_In_ Platform::String^filename, _Out_ ID3D11DomainShader **shader) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[], _In_ uint32 layoutDescNumElements, _Out_ ID3D11VertexShader **shader, _Out_opt_ ID3D11InputLayout **layout) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _Out_ ID3D11PixelShader **shader) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _Out_ ID3D11ComputeShader **shader) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _Out_ ID3D11GeometryShader **shader) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY *streamOutDeclaration, _In_ uint32 numEntries, _In_reads_opt_(numStrides) const uint32 *bufferStrides, _In_ uint32 numStrides, _In_ uint32 rasterizedStream, _Out_ ID3D11GeometryShader **shader) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _Out_ ID3D11HullShader **shader) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _Out_ ID3D11DomainShader **shader) | BasicLoader |
LoadShaderAsync(_In_ winrt::hstring filename, _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC const layoutDesc[], _In_ uint32_t layoutDescNumElements, _Out_ ID3D11VertexShader **shader, _Out_opt_ ID3D11InputLayout **layout) | BasicLoader |
LoadShaderAsync(_In_ winrt::hstring filename, _Out_ ID3D11PixelShader **shader) | BasicLoader |
LoadShaderAsync(_In_ winrt::hstring const filename, _Out_ ID3D11ComputeShader **shader) | BasicLoader |
LoadShaderAsync(_In_ winrt::hstring filename, _Out_ ID3D11GeometryShader **shader) | BasicLoader |
LoadShaderAsync(_In_ winrt::hstring filename, _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY *streamOutDeclaration, _In_ uint32_t numEntries, _In_reads_opt_(numStrides) const uint32_t *bufferStrides, _In_ uint32_t numStrides, _In_ uint32_t rasterizedStream, _Out_ ID3D11GeometryShader **shader) | BasicLoader |
LoadShaderAsync(_In_ winrt::hstring filename, _Out_ ID3D11HullShader **shader) | BasicLoader |
LoadShaderAsync(_In_ winrt::hstring filename, _Out_ ID3D11DomainShader **shader) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC layoutDesc[], _In_ uint32 layoutDescNumElements, _Out_ ID3D11VertexShader **shader, _Out_opt_ ID3D11InputLayout **layout) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _Out_ ID3D11PixelShader **shader) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _Out_ ID3D11ComputeShader **shader) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _Out_ ID3D11GeometryShader **shader) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY *streamOutDeclaration, _In_ uint32 numEntries, _In_reads_opt_(numStrides) const uint32 *bufferStrides, _In_ uint32 numStrides, _In_ uint32 rasterizedStream, _Out_ ID3D11GeometryShader **shader) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _Out_ ID3D11HullShader **shader) | BasicLoader |
LoadShaderAsync(_In_ Platform::String^filename, _Out_ ID3D11DomainShader **shader) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ winrt::hstring const &filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTexture(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTextureAsync(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTextureAsync(_In_ winrt::hstring filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
LoadTextureAsync(_In_ Platform::String^filename, _Out_opt_ ID3D11Texture2D **texture, _Out_opt_ ID3D11ShaderResourceView **textureView) | BasicLoader |
m_basicReaderWriter | BasicLoader | [private]
m_d3dDevice | BasicLoader | [private]
m_d3dDevice | BasicLoader | [private]
m_wicFactory | BasicLoader | [private]
m_wicFactory | BasicLoader | [private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ winrt::hstring const &name) | BasicLoader | [inline, private]
SetDebugName(_In_ DeviceChildType *object, _In_ Platform::String^name) | BasicLoader | [inline, private]
wicFactory | BasicLoader |
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSegmentation/cppwinrt/Scenario1_ExtractTextSegments.h Source File

  • TextSegmentation
  • cppwinrt

Scenario1_ExtractTextSegments.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_ExtractTextSegments.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_ExtractTextSegments : Scenario1_ExtractTextSegmentsT<Scenario1_ExtractTextSegments>
00019     {
00020         Scenario1_ExtractTextSegments();
00021
00022         void WordSegmentsButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023         void SelectionSegmentsButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024
00025     private:
00026         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00027     };
00028 }
00029
00030 namespace winrt::SDKTemplate::factory_implementation
00031 {
00032     struct Scenario1_ExtractTextSegments : Scenario1_ExtractTextSegmentsT<Scenario1_ExtractTextSegments, implementation::Scenario1_ExtractTextSegments>
00033     {
00034     };
00035 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboard/cppwinrt/Scenario1_Launch.cpp Source File

  • TouchKeyboard
  • cppwinrt

Scenario1_Launch.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_Launch.h"
00014 #include "Scenario1_Launch.g.cpp"
00015 #include "CustomTextBox.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::UI::Xaml;
00020
00021 namespace winrt::SDKTemplate::implementation
00022 {
00023     Scenario1_Launch::Scenario1_Launch()
00024     {
00025         InitializeComponent();
00026     }
00027 }
Generated on Fri Nov 15 2024 22:21:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DAdvancedColorImages/cpp/D2DAdvancedColorImages/DirectXPage.xaml.h Source File

  • D2DAdvancedColorImages
  • cpp
  • D2DAdvancedColorImages

DirectXPage.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "DirectXPage.g.h"
00015
00016 #include "DeviceResources.h"
00017 #include "D2DAdvancedColorImagesRenderer.h"
00018 #include "RenderOptions.h"
00019
00020 namespace D2DAdvancedColorImages
00021 {
00022     /// <summary>
00023     /// A page that hosts the Direct2D app in a SwapChainPanel, and app UI in XAML.
00024     /// </summary>
00025     public ref class DirectXPage sealed
00026     {
00027     public:
00028         DirectXPage();
00029         virtual ~DirectXPage();
00030
00031         void SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00032         void LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^ state);
00033
00034         void LoadDefaultImage();
00035         void LoadImage(_In_ Windows::Storage::StorageFile^ imageFile);
00036
00037         property RenderOptionsViewModel^ ViewModel
00038         {
00039             RenderOptionsViewModel^ get() { return m_renderOptionsViewModel; }
00040         }
00041
00042     private:
00043         // UI element event handlers.
00044         void LoadImageButtonClick(_In_ Platform::Object^ sender, _In_ Windows::UI::Xaml::RoutedEventArgs^ e);
00045         void ResetButtonClick(_In_ Platform::Object^ sender, _In_ Windows::UI::Xaml::RoutedEventArgs^ e);
00046         void CheckBoxChanged(_In_ Platform::Object^ sender, _In_ Windows::UI::Xaml::RoutedEventArgs^ e);
00047         void OnKeyUp(_In_ Windows::UI::Core::CoreWindow^ sender, _In_ Windows::UI::Core::KeyEventArgs^ args);
00048         void SliderChanged(_In_ Platform::Object^ sender, _In_ Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e);
00049         void ComboChanged(_In_ Platform::Object^ sender, _In_ Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00050
00051         void UpdateDisplayACState(_In_ Windows::Graphics::Display::AdvancedColorInfo^ info);
00052         void UpdateDefaultRenderOptions();
00053         void UpdateRenderOptions();
00054
00055         // XAML low-level rendering event handler.
00056         void OnRendering(_In_ Platform::Object^ sender, _In_ Platform::Object^ args);
00057
00058         // Window event handlers.
00059         void OnVisibilityChanged(_In_ Windows::UI::Core::CoreWindow^ sender, _In_ Windows::UI::Core::VisibilityChangedEventArgs^ args);
00060         void OnResizeCompleted(_In_ Windows::UI::Core::CoreWindow ^sender, _In_ Platform::Object ^args);
00061
00062         // DisplayInformation event handlers.
00063         void OnDpiChanged(_In_ Windows::Graphics::Display::DisplayInformation^ sender, _In_ Platform::Object^ args);
00064         void OnOrientationChanged(_In_ Windows::Graphics::Display::DisplayInformation^ sender, _In_ Platform::Object^ args);
00065         void OnDisplayContentsInvalidated(_In_ Windows::Graphics::Display::DisplayInformation^ sender, _In_ Platform::Object^ args);
00066         void OnAdvancedColorInfoChanged(_In_ Windows::Graphics::Display::DisplayInformation ^sender, _In_ Platform::Object ^args);
00067
00068         // Pointer input event handlers (for pan and zoom).
00069         void OnPointerPressed(_In_ Platform::Object ^sender, _In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs ^e);
00070         void OnPointerMoved(_In_ Platform::Object ^sender, _In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs ^e);
00071         void OnPointerReleased(_In_ Platform::Object ^sender, _In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs ^e);
00072         void OnManipulationStarted(_In_ Windows::UI::Input::GestureRecognizer ^sender, _In_ Windows::UI::Input::ManipulationStartedEventArgs ^args);
00073         void OnManipulationUpdated(_In_ Windows::UI::Input::GestureRecognizer ^sender, _In_ Windows::UI::Input::ManipulationUpdatedEventArgs ^args);
00074         void OnManipulationCompleted(_In_ Windows::UI::Input::GestureRecognizer ^sender, _In_ Windows::UI::Input::ManipulationCompletedEventArgs ^args);
00075         void OnPointerCanceled(_In_ Platform::Object ^sender, _In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs ^e);
00076         void OnPointerWheelChanged(_In_ Platform::Object ^sender, _In_ Windows::UI::Xaml::Input::PointerRoutedEventArgs ^e);
00077
00078         // Other event handlers.
00079         void OnCompositionScaleChanged(_In_ Windows::UI::Xaml::Controls::SwapChainPanel^ sender, _In_ Object^ args);
00080         void OnSwapChainPanelSizeChanged(_In_ Platform::Object^ sender, _In_ Windows::UI::Xaml::SizeChangedEventArgs^ e);
00081
00082         Platform::String^ ConvertACKindToString(Windows::Graphics::Display::AdvancedColorKind kind);
00083
00084         // Resources used to draw the DirectX content in the XAML page.
00085         std::shared_ptr<DX::DeviceResources>            m_deviceResources;
00086         std::unique_ptr<D2DAdvancedColorImagesRenderer> m_renderer;
00087         Windows::UI::Input::GestureRecognizer^          m_gestureRecognizer;
00088         bool                                            m_isWindowVisible;
00089
00090         // Cached information for UI.
00091         D2DAdvancedColorImages::ImageInfo               m_imageInfo;
00092         float                                           m_imageMaxCLL;
00093         bool                                            m_isImageValid;
00094         Windows::Graphics::Display::AdvancedColorInfo^  m_dispInfo;
00095         RenderOptionsViewModel^                         m_renderOptionsViewModel;
00096     };
00097 }
00098
Generated on Fri Nov 15 2024 22:19:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cpp/SampleConfiguration.cpp Source File

  • BackgroundActivation
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #include "pch.h"
00012 #include "MainPage.xaml.h"
00013 #include "SampleConfiguration.h"
00014 #include "BackgroundActivity.h"
00015
00016 using namespace SDKTemplate;
00017 using namespace Windows::ApplicationModel;
00018 using namespace Windows::ApplicationModel::Activation;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021
00022 String^ BackgroundTaskSample::SampleBackgroundTaskProgress = "";
00023 bool BackgroundTaskSample::SampleBackgroundTaskRegistered = false;
00024
00025 String^ BackgroundTaskSample::SampleBackgroundTaskWithConditionProgress = "";
00026 bool BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered = false;
00027
00028 String^ BackgroundTaskSample::ServicingCompleteTaskProgress = "";
00029 bool BackgroundTaskSample::ServicingCompleteTaskRegistered = false;
00030
00031 String^ BackgroundTaskSample::TimeTriggeredTaskProgress = "";
00032 bool BackgroundTaskSample::TimeTriggeredTaskRegistered = false;
00033
00034 String^ BackgroundTaskSample::ApplicationTriggerTaskProgress = "";
00035 bool BackgroundTaskSample::ApplicationTriggerTaskRegistered = false;
00036 String^ BackgroundTaskSample::ApplicationTriggerTaskResult = "";
00037
00038 String^ BackgroundTaskSample::GroupedBackgroundTaskProgress = "";
00039 bool BackgroundTaskSample::GroupedBackgroundTaskRegistered = false;
00040
00041
00042 PropertySet^ BackgroundTaskSample::TaskStatuses = ref new PropertySet();
00043
00044 Array<Scenario>^ MainPage::scenariosInner = ref new Array<Scenario>
00045 {
00046     // The format here is the following:
00047     //     { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
00048     { "Background task", "SDKTemplate.SampleBackgroundTask" },
00049     { "Background task with a condition", "SDKTemplate.SampleBackgroundTaskWithCondition" },
00050     { "Servicing complete task", "SDKTemplate.ServicingCompleteTask" },
00051     { "Background task with time trigger", "SDKTemplate.TimeTriggeredTask" },
00052     { "Background task with application trigger", "SDKTemplate.ApplicationTriggerTask" },
00053     { "Grouped background task", "SDKTemplate.GroupedBackgroundTask" },
00054 };
00055
00056 String^ BackgroundTaskSample::GetBackgroundTaskStatus(String^ name)
00057 {
00058     auto registered = false;
00059     if (name == SampleBackgroundTaskName)
00060     {
00061         registered = BackgroundTaskSample::SampleBackgroundTaskRegistered;
00062     }
00063     else if (name == SampleBackgroundTaskWithConditionName)
00064     {
00065         registered = BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered;
00066     }
00067     else if (name == ServicingCompleteTaskName)
00068     {
00069         registered = BackgroundTaskSample::ServicingCompleteTaskRegistered;
00070     }
00071     else if (name == TimeTriggeredTaskName)
00072     {
00073         registered = BackgroundTaskSample::TimeTriggeredTaskRegistered;
00074     }
00075     else if (name == ApplicationTriggerTaskName)
00076     {
00077         registered = BackgroundTaskSample::ApplicationTriggerTaskRegistered;
00078     }
00079     else if (name == GroupedBackgroundTaskName)
00080     {
00081         registered = BackgroundTaskSample::GroupedBackgroundTaskRegistered;
00082     }
00083
00084     String^ status = registered ? "Registered" : "Unregistered";
00085
00086     if (TaskStatuses->HasKey(name))
00087     {
00088         status += " - " + TaskStatuses->Lookup(name)->ToString();
00089     }
00090
00091     return status;
00092 }
00093
00094 BackgroundTaskRegistration^ BackgroundTaskSample::RegisterBackgroundTask(String^ taskEntryPoint, String^ name, IBackgroundTrigger^ trigger, IBackgroundCondition^ condition, BackgroundTaskRegistrationGroup^ group)
00095 {
00096     if (TaskRequiresBackgroundAccess(name))
00097     {
00098         BackgroundExecutionManager::RequestAccessAsync();
00099     }
00100
00101     auto builder = ref new BackgroundTaskBuilder();
00102
00103     builder->Name = name;
00104
00105     if (taskEntryPoint != nullptr)
00106     {
00107         // If you leave the TaskEntryPoint at its default value, then the task runs
00108         // inside the main process from OnBackgroundActivated rather than as a separate process.
00109         builder->TaskEntryPoint = taskEntryPoint;
00110     }
00111
00112     builder->SetTrigger(trigger);
00113
00114     if (condition != nullptr)
00115     {
00116         builder->AddCondition(condition);
00117
00118         //
00119         // If the condition changes while the background task is executing then it will
00120         // be canceled.
00121         //
00122         builder->CancelOnConditionLoss = true;
00123     }
00124
00125     if (group != nullptr)
00126     {
00127         builder->TaskGroup = group;
00128     }
00129
00130     auto task = builder->Register();
00131
00132     UpdateBackgroundTaskRegistrationStatus(name, true);
00133
00134     //
00135     // Remove previous completion status.
00136     //
00137     RemoveBackgroundTaskStatus(name);
00138
00139     return task;
00140 }
00141
00142 bool BackgroundTaskSample::TaskRequiresBackgroundAccess(String^ name)
00143 {
00144     if ((name == TimeTriggeredTaskName) ||
00145         (name == ApplicationTriggerTaskName))
00146     {
00147         return true;
00148     }
00149     else
00150     {
00151         return false;
00152     }
00153 }
00154
00155 void BackgroundTaskSample::UnregisterBackgroundTasks(String^ name, BackgroundTaskRegistrationGroup^ group)
00156 {
00157     //
00158     // If the given task group is registered then loop through all background tasks associated with it
00159     // and unregister any with the name passed into this function.
00160     //
00161     if (group != nullptr)
00162     {
00163         for (auto pair : group->AllTasks)
00164         {
00165             auto task = pair->Value;
00166             if (task->Name == name)
00167             {
00168                 task->Unregister(true);
00169             }
00170         }
00171     }
00172     else
00173     {
00174         //
00175         // Loop through all ungrouped background tasks and unregister any with the name passed into this function.
00176         //
00177         for (auto pair : BackgroundTaskRegistration::AllTasks)
00178         {
00179             auto task = pair->Value;
00180             if (task->Name == name)
00181             {
00182                 task->Unregister(true);
00183             }
00184         }
00185     }
00186
00187     UpdateBackgroundTaskRegistrationStatus(name, false);
00188 }
00189
00190
00191 BackgroundTaskRegistrationGroup^ BackgroundTaskSample::GetTaskGroup(String^ id, String^ groupName)
00192 {
00193     auto group = BackgroundTaskRegistration::GetTaskGroup(id);
00194
00195     if (group == nullptr)
00196     {
00197         group = ref new BackgroundTaskRegistrationGroup(id, groupName);
00198     }
00199
00200     return group;
00201 }
00202
00203
00204 void BackgroundTaskSample::UpdateBackgroundTaskRegistrationStatus(String^ name, bool registered)
00205 {
00206     if (name == SampleBackgroundTaskName)
00207     {
00208         BackgroundTaskSample::SampleBackgroundTaskRegistered = registered;
00209     }
00210     else if (name == SampleBackgroundTaskWithConditionName)
00211     {
00212         BackgroundTaskSample::SampleBackgroundTaskWithConditionRegistered = registered;
00213     }
00214     else if (name == ServicingCompleteTaskName)
00215     {
00216         BackgroundTaskSample::ServicingCompleteTaskRegistered = registered;
00217     }
00218     else if (name == TimeTriggeredTaskName)
00219     {
00220         BackgroundTaskSample::TimeTriggeredTaskRegistered = registered;
00221     }
00222     else if (name == ApplicationTriggerTaskName)
00223     {
00224         BackgroundTaskSample::ApplicationTriggerTaskRegistered = registered;
00225     }
00226     else if (name == GroupedBackgroundTaskName)
00227     {
00228         BackgroundTaskSample::GroupedBackgroundTaskRegistered = registered;
00229     }
00230 }
00231
00232 void BackgroundTaskSample::RemoveBackgroundTaskStatus(String^ name)
00233 {
00234     if (TaskStatuses->HasKey(name))
00235     {
00236         TaskStatuses->Remove(name);
00237     }
00238 }
00239
00240 void App::OnBackgroundActivated(BackgroundActivatedEventArgs^ args)
00241 {
00242     BackgroundActivity::Start(args->TaskInstance);
00243 }
00244
00245 void App::Partial_Construct()
00246 {
00247     auto group = BackgroundTaskSample::GetTaskGroup(BackgroundTaskGroupId, BackgroundTaskGroupFriendlyName);
00248     group->BackgroundActivated += ref new TypedEventHandler<BackgroundTaskRegistrationGroup ^, BackgroundActivatedEventArgs ^>(&BackgroundActivity::OnStart, CallbackContext::Same);
00249 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Appointments/cs/Scenario4_Remove.xaml.cs Source File

  • Appointments
  • cs

Scenario4_Remove.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario4_Remove : Page
00020     {
00021         private MainPage rootPage = MainPage.Current;
00022
00023         public Scenario4_Remove()
00024         {
00025             this.InitializeComponent();
00026         }
00027
00028         /// <summary>
00029         /// Removes the appointment associated with a particular appointment id string from the defaul appointment provider app.
00030         /// </summary>
00031         /// <param name="sender"></param>
00032         /// <param name="e"></param>
00033         private async void Remove_Click(object sender, RoutedEventArgs e)
00034         {
00035             // The appointment id argument for ShowRemoveAppointmentAsync is typically retrieved from AddAppointmentAsync and stored in app data.
00036             String appointmentId = AppointmentIdTextBox.Text;
00037
00038             // The appointment id cannot be null or empty.
00039             if (String.IsNullOrEmpty(appointmentId))
00040             {
00041                 rootPage.NotifyUser("The appointment id cannot be empty", NotifyType.ErrorMessage);
00042             }
00043             else
00044             {
00045                 // Get the selection rect of the button pressed to remove this appointment
00046                 var rect = MainPage.GetElementRect(sender as FrameworkElement);
00047
00048                 // ShowRemoveAppointmentAsync returns a boolean indicating whether or not the appointment related to the appointment id given was removed.
00049                 // An optional instance start time can be provided to indicate that a specific instance on that date should be removed
00050                 // in the case of a recurring appointment.
00051                 bool removed;
00052                 if (InstanceStartDateCheckBox.IsChecked.Value)
00053                 {
00054                     // Remove a specific instance starting on the date provided.
00055                     var instanceStartDate = InstanceStartDateDatePicker.Date;
00056                     removed = await Windows.ApplicationModel.Appointments.AppointmentManager.ShowRemoveAppointmentAsync(appointmentId, rect, Windows.UI.Popups.Placement.Default, instanceStartDate);
00057                 }
00058                 else
00059                 {
00060                     // Remove an appointment that occurs only once or in the case of a recurring appointment, replace the entire series.
00061                     removed = await Windows.ApplicationModel.Appointments.AppointmentManager.ShowRemoveAppointmentAsync(appointmentId, rect, Windows.UI.Popups.Placement.Default);
00062                 }
00063
00064                 if (removed)
00065                 {
00066                     rootPage.NotifyUser("Appointment removed", NotifyType.StatusMessage);
00067                 }
00068                 else
00069                 {
00070                     rootPage.NotifyUser("Appointment not removed", NotifyType.ErrorMessage);
00071                 }
00072             }
00073         }
00074     }
00075 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Nfc/PcscSdk/CommonDefs.cs Source File

  • Nfc
  • PcscSdk

CommonDefs.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace Pcsc.Common
00013 {
00014     /// <summary>
00015     /// ICC Device class
00016     /// </summary>
00017     public enum DeviceClass : byte
00018     {
00019         Unknown             = 0x00,
00020         StorageClass        = 0x01,  // for PCSC class, there will be subcategory to identify the physical icc
00021         Iso14443P4          = 0x02,
00022         MifareDesfire       = 0x03,
00023     }
00024 }
Generated on Fri Nov 15 2024 22:20:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_History Member List

This is the complete list of members for Scenario2_History, including all inherited members.
AllHistory_Checked(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_History | [inline, private]
getAllHistory | Scenario2_History | [private]
GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_History | [inline, private]
historyRecords | Scenario2_History | [private]
PedometerClassId | Scenario2_History | [private]
rootPage | Scenario2_History | [private]
Scenario2_History() | Scenario2_History | [inline]
SpecificHistory_Checked(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_History | [inline, private]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_DevicePicker Member List

This is the complete list of members for Scenario1_DevicePicker, including all inherited members.
OnDevicePickerDismissed(Windows::Devices::Enumeration::DevicePicker const &, IInspectable const &) | Scenario1_DevicePicker | [private]
OnDeviceSelected(Windows::Devices::Enumeration::DevicePicker const &, Windows::Devices::Enumeration::DeviceSelectedEventArgs args) | Scenario1_DevicePicker | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_DevicePicker |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_DevicePicker |
PickSingleDeviceButton_Click(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_DevicePicker |
resultCollection | Scenario1_DevicePicker | [private]
Scenario1_DevicePicker() | Scenario1_DevicePicker |
ShowDevicePicker(bool pickSingle) | Scenario1_DevicePicker | [private]
ShowDevicePickerButton_Click(IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_DevicePicker |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundMediaPlayback/cs/DataModels/MediaList.cs Source File

  • BackgroundMediaPlayback
  • cs
  • DataModels

MediaList.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using Windows.Storage;
00007 using Windows.Data.Json;
00008 using Windows.Media.Playback;
00009 using Windows.Media.Core;
00010 using Windows.Media;
00011 using Windows.Storage.Streams;
00012
00013 namespace BackgroundMediaPlayback.DataModels
00014 {
00015     public class MediaList : List<MediaItem>
00016     {
00017         public string Title { get; set; }
00018
00019         public MediaList()
00020         {
00021         }
00022
00023         public async Task LoadFromApplicationUriAsync(string uri)
00024         {
00025             await LoadFromApplicationUriAsync(new Uri(uri));
00026         }
00027
00028         public async Task LoadFromApplicationUriAsync(Uri uri)
00029         {
00030             Clear();
00031
00032             var storageFile = await StorageFile.GetFileFromApplicationUriAsync(uri);
00033             var jsonText = await FileIO.ReadTextAsync(storageFile);
00034             var json = JsonObject.Parse(jsonText);
00035             json = json.GetNamedObject("mediaList");
00036
00037             Title = json["title"].GetString();
00038             var items = json["items"].GetArray();
00039             foreach (var jsonItem in items)
00040             {
00041                 Add(LoadItem(jsonItem.GetObject()));
00042             }
00043         }
00044
00045         MediaItem LoadItem(JsonObject json)
00046         {
00047             var mediaType = json["mediaType"].GetString();
00048             switch (mediaType)
00049             {
00050                 case "music":
00051                     return new MusicItem(json);
00052                 case "video":
00053                     return new VideoItem(json);
00054                 default:
00055                     return new MediaItem(json);
00056             }
00057         }
00058
00059         public MediaPlaybackList ToPlaybackList()
00060         {
00061             var playbackList = new MediaPlaybackList();
00062
00063             // Make a new list and enable looping
00064             playbackList.AutoRepeatEnabled = true;
00065
00066             // Add playback items to the list
00067             foreach (var mediaItem in this)
00068             {
00069                 playbackList.Items.Add(mediaItem.ToPlaybackItem());
00070             }
00071
00072             return playbackList;
00073         }
00074     }
00075 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cppwinrt/Scenario2_StringTemplate.h Source File

  • DateTimeFormatting
  • cppwinrt

Scenario2_StringTemplate.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_StringTemplate.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_StringTemplate : Scenario2_StringTemplateT<Scenario2_StringTemplate>
00019     {
00020         Scenario2_StringTemplate();
00021
00022         void Display_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario2_StringTemplate : Scenario2_StringTemplateT<Scenario2_StringTemplate, implementation::Scenario2_StringTemplate>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:19:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cs/Scenario2_AdvertiserAccept.xaml.cs Source File

  • WiFiDirectServices
  • cs

Scenario2_AdvertiserAccept.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Devices.WiFiDirect.Services;
00014 using Windows.Storage.Streams;
00015 using Windows.UI.Core;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Navigation;
00018
00019 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00020
00021 namespace SDKTemplate
00022 {
00023     namespace WiFiDirectServices
00024     {
00025         /// <summary>
00026         /// Helper class to display session requests in list with extra data
00027         /// </summary>
00028         public class SessionRequestWrapper
00029         {
00030             public SessionRequestWrapper(WiFiDirectServiceSessionRequest request, AdvertisementWrapper advertisement)
00031             {
00032                 this.Id = request.DeviceInformation.Id;
00033                 this.Advertisement = advertisement;
00034                 this.Pin = "";
00035                 this.ProvisioningInfo = "GroupFormation? " + (request.ProvisioningInfo.IsGroupFormationNeeded ? "Yes" : "No")
00036                     + ", ConfigMethod: " + request.ProvisioningInfo.SelectedConfigurationMethod.ToString();
00037
00038                 if (request.ProvisioningInfo.SelectedConfigurationMethod == WiFiDirectServiceConfigurationMethod.PinDisplay)
00039                 {
00040                     this.Pin = advertisement.Pin;
00041                 }
00042
00043                 this.SessionInfo = request.SessionInfo;
00044             }
00045
00046             public string Id { get; set; }
00047             public string ProvisioningInfo { get; set; }
00048             public string Pin { get; set; }
00049             public IBuffer SessionInfo { get; set; }
00050
00051             public AdvertisementWrapper Advertisement { get; set; }
00052         }
00053
00054         /// <summary>
00055         /// UI exposing an interface to accept/decline incoming connection requests as an advertiser
00056         /// and to interact with connected sessions
00057         ///
00058         /// Most of the actual logic for Wi-Fi Direct Services is in WiFiDirectServicesManager.cs and WiFiDirectServicesWrappers.cs
00059         /// </summary>
00060         public sealed partial class Scenario2 : Page
00061         {
00062             private Object thisLock = new Object();
00063
00064             private MainPage rootPage;
00065
00066             public Scenario2()
00067             {
00068                 this.InitializeComponent();
00069             }
00070
00071             protected override void OnNavigatedTo(NavigationEventArgs e)
00072             {
00073                 lock (thisLock)
00074                 {
00075                     rootPage = MainPage.Current;
00076
00077                     MainUI.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00078                     PlaceholderUI.Visibility = Windows.UI.Xaml.Visibility.Visible;
00079
00080                     // Fill in all existing data
00081                     if (WiFiDirectServiceManager.Instance.Advertisers.Count > 0)
00082                     {
00083                         // Session Requests
00084                         SessionRequests.Items.Clear();
00085
00086                         // Advertisers
00087                         Advertisements.Items.Clear();
00088                         foreach (var advertiser in WiFiDirectServiceManager.Instance.Advertisers)
00089                         {
00090                             Advertisements.Items.Add(advertiser);
00091
00092                             foreach (var request in advertiser.SessionRequestList)
00093                             {
00094                                 SessionRequestWrapper sessionRequest = new SessionRequestWrapper(request, advertiser);
00095                                 SessionRequests.Items.Add(sessionRequest);
00096                             }
00097                         }
00098
00099                         // Connected Sessions
00100                         ConnectedSessions.Items.Clear();
00101                         foreach (var session in WiFiDirectServiceManager.Instance.ConnectedSessionList)
00102                         {
00103                             ConnectedSessions.Items.Add(session);
00104                         }
00105
00106                         MainUI.Visibility = Windows.UI.Xaml.Visibility.Visible;
00107                         PlaceholderUI.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
00108                     }
00109                 }
00110                 WiFiDirectServiceManager.Instance.Scenario2 = this;
00111             }
00112
00113             protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00114             {
00115                 WiFiDirectServiceManager.Instance.Scenario2 = null;
00116             }
00117
00118             public async void AddSessionRequest(WiFiDirectServiceSessionRequest request, AdvertisementWrapper advertiser)
00119             {
00120                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00121                 {
00122                     lock (thisLock)
00123                     {
00124                         SessionRequestWrapper sessionRequest = new SessionRequestWrapper(request, advertiser);
00125                         SessionRequests.Items.Add(sessionRequest);
00126                     }
00127                 });
00128             }
00129
00130             public async void RemoveSessionRequest(WiFiDirectServiceSessionRequest request, AdvertisementWrapper advertiser)
00131             {
00132                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00133                 {
00134                     lock (thisLock)
00135                     {
00136                         foreach (SessionRequestWrapper r in SessionRequests.Items)
00137                         {
00138                             if (r.Advertisement.InternalId == advertiser.InternalId &&
00139                                 r.Id == request.DeviceInformation.Id)
00140                             {
00141                                 SessionRequests.Items.Remove(r);
00142                                 break;
00143                             }
00144                         }
00145                     }
00146                 });
00147             }
00148
00149             public async void AddAdvertiser(AdvertisementWrapper advertiser)
00150             {
00151                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00152                 {
00153                     lock (thisLock)
00154                     {
00155                         Advertisements.Items.Add(advertiser);
00156                     }
00157                 });
00158             }
00159
00160             public async void RemoveAdvertiser(int index)
00161             {
00162                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00163                 {
00164                     lock (thisLock)
00165                     {
00166                         if (index > Advertisements.Items.Count - 1)
00167                         {
00168                             throw new IndexOutOfRangeException("Attempted to remove advertiser no longer in list");
00169                         }
00170
00171                         Advertisements.Items.RemoveAt(index);
00172
00173                         if (Advertisements.Items.Count == 0)
00174                         {
00175                             // Force navigation to the previous page for smoother experience
00176                             // This takes us to the scenario to create a new advertisement
00177                             rootPage.GoToScenario(0);
00178                         }
00179                     }
00180                 });
00181             }
00182
00183             public async void AddSession(SessionWrapper session)
00184             {
00185                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00186                 {
00187                     lock (thisLock)
00188                     {
00189                         ConnectedSessions.Items.Add(session);
00190                     }
00191                 });
00192             }
00193
00194             public async void RemoveSession(int index)
00195             {
00196                 await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00197                 {
00198                     lock (thisLock)
00199                     {
00200                         if (index > ConnectedSessions.Items.Count - 1)
00201                         {
00202                             throw new IndexOutOfRangeException("Attempted to remove session no longer in list");
00203                         }
00204
00205                         ConnectedSessions.Items.RemoveAt(index);
00206                     }
00207                 });
00208             }
00209
00210             public void UpdateAdvertiserStatus(AdvertisementWrapper advertiser)
00211             {
00212                 // Update list
00213             }
00214
00215             private void Accept_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00216             {
00217                 if (SessionRequests.Items.Count > 0)
00218                 {
00219                     int requestIndex = SessionRequests.SelectedIndex;
00220                     if (requestIndex >= 0)
00221                     {
00222                         SessionRequestWrapper request = SessionRequests.Items[requestIndex] as SessionRequestWrapper;
00223                         request.Advertisement.AcceptSessionRequest(request.Id, AcceptPin.Text);
00224                     }
00225                 }
00226             }
00227
00228             private void Decline_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00229             {
00230                 if (SessionRequests.Items.Count > 0)
00231                 {
00232                     int requestIndex = SessionRequests.SelectedIndex;
00233                     if (requestIndex >= 0)
00234                     {
00235                         SessionRequestWrapper request = SessionRequests.Items[requestIndex] as SessionRequestWrapper;
00236                         request.Advertisement.DeclineSessionRequest(request.Id);
00237                     }
00238                 }
00239             }
00240
00241             private void CloseSession_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00242             {
00243                 if (ConnectedSessions.Items.Count > 0)
00244                 {
00245                     int index = ConnectedSessions.SelectedIndex;
00246                     if (index >= 0)
00247                     {
00248                         WiFiDirectServiceManager.Instance.CloseSession(index);
00249                     }
00250                 }
00251             }
00252
00253             private void SelectSession_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00254             {
00255                 if (ConnectedSessions.Items.Count > 0)
00256                 {
00257                     int index = ConnectedSessions.SelectedIndex;
00258                     if (index >= 0)
00259                     {
00260                         WiFiDirectServiceManager.Instance.SelectSession(index);
00261
00262                         // Force navigation to the next page for smoother experience
00263                         // This takes us to the scenario to send and receive data for a selected session
00264                         rootPage.GoToScenario(4);
00265                     }
00266                 }
00267             }
00268
00269             private void StopAdvertisement_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00270             {
00271                 if (Advertisements.Items.Count > 0)
00272                 {
00273                     int index = Advertisements.SelectedIndex;
00274                     if (index >= 0)
00275                     {
00276                         WiFiDirectServiceManager.Instance.UnpublishService(index);
00277                     }
00278                 }
00279             }
00280         }
00281     }
00282 }
Generated on Fri Nov 15 2024 22:22:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

UpdateMetadataTask Member List

This is the complete list of members for UpdateMetadataTask, including all inherited members.
Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance const &taskInstance) UpdateMetadataTask
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_ForegroundGeofence Member List

This is the complete list of members for Scenario4_ForegroundGeofence, including all inherited members.
AddEventDescription(hstring const &eventDescription) | Scenario4_ForegroundGeofence | [private]
AddGeofenceToRegisteredGeofenceListBox(Windows::Devices::Geolocation::Geofencing::Geofence const &geofence) | Scenario4_ForegroundGeofence | [private]
defaultDwellTime | Scenario4_ForegroundGeofence | [private, static]
GenerateGeofence() | Scenario4_ForegroundGeofence | [private]
m_pendingOperation | Scenario4_ForegroundGeofence | [private]
OnCreateGeofence(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario4_ForegroundGeofence |
OnGeofenceStateChanged(Windows::Devices::Geolocation::Geofencing::GeofenceMonitor const &sender, Windows::Foundation::IInspectable const &) | Scenario4_ForegroundGeofence | [private]
OnGeofenceStatusChanged(Windows::Devices::Geolocation::Geofencing::GeofenceMonitor const &sender, Windows::Foundation::IInspectable const &) | Scenario4_ForegroundGeofence | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario4_ForegroundGeofence |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario4_ForegroundGeofence |
OnRegisteredGeofenceListBoxSelectionChanged(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::Controls::SelectionChangedEventArgs const &e) | Scenario4_ForegroundGeofence |
OnRemoveGeofenceItem(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario4_ForegroundGeofence |
OnSetPositionToHere(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario4_ForegroundGeofence |
OnVisibilityChanged(Windows::Foundation::IInspectable const &, Windows::UI::Core::VisibilityChangedEventArgs const &e) | Scenario4_ForegroundGeofence | [private]
ParseDoubleFromTextBox(Windows::UI::Xaml::Controls::TextBox const &textBox, hstring const &name, double minValue, double maxValue, double &value) | Scenario4_ForegroundGeofence | [private]
ParseTimeSpan(hstring const &field, Windows::Foundation::TimeSpan defaultValue, Windows::Foundation::TimeSpan &value) | Scenario4_ForegroundGeofence | [private]
RefreshControlsFromGeofence(Windows::Devices::Geolocation::Geofencing::Geofence const &geofence) | Scenario4_ForegroundGeofence | [private]
Scenario4_ForegroundGeofence() | Scenario4_ForegroundGeofence |
SetStartDateTimeToUI(Windows::Foundation::DateTime dateTime) | Scenario4_ForegroundGeofence | [private]
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicSpatialMapping/cpp/AppView.h Source File

  • HolographicSpatialMapping
  • cpp

AppView.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015 #include "HolographicSpatialMappingMain.h"
00016
00017 namespace HolographicSpatialMapping
00018 {
00019     // IFrameworkView class. Connects the app with the Windows shell and handles application lifecycle events.
00020     ref class AppView sealed : public Windows::ApplicationModel::Core::IFrameworkView
00021     {
00022     public:
00023         AppView();
00024
00025         // IFrameworkView methods.
00026         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00027         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00028         virtual void Load(Platform::String^ entryPoint);
00029         virtual void Run();
00030         virtual void Uninitialize();
00031
00032     protected:
00033         // Application lifecycle event handlers.
00034         void OnViewActivated(Windows::ApplicationModel::Core::CoreApplicationView^ sender, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00035         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00036         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00037
00038         // Window event handlers.
00039         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00040         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00041
00042         // CoreWindow input event handlers.
00043         void OnKeyPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args);
00044
00045     private:
00046         std::unique_ptr<HolographicSpatialMappingMain> m_main;
00047
00048         std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00049         bool                                                m_windowClosed  = false;
00050         bool                                                m_windowVisible = true;
00051
00052         // The holographic space the app will use for rendering.
00053         Windows::Graphics::Holographic::HolographicSpace^   m_holographicSpace = nullptr;
00054     };
00055
00056     // The entry point for the app.
00057     ref class AppViewSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00058     {
00059     public:
00060         virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00061     };
00062 }
00063
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cs/SampleConfiguration.cs Source File

  • Logging
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Logging C#";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="LoggingChannel", ClassType=typeof(Scenario1)},
00025             new Scenario() { Title="LoggingSession", ClassType=typeof(Scenario2)},
00026             new Scenario() { Title="FileLoggingSession", ClassType=typeof(Scenario3)}
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: KeyCredentialManager/cpp/Account.cpp Source File

  • KeyCredentialManager
  • cpp

Account.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "Account.h"
00003
00004 using namespace Platform;
00005
00006 String^ SDKTemplate::Account::Name::get()
00007 {
00008     return m_Name;
00009 }
00010
00011 void SDKTemplate::Account::Name::set(String^ value)
00012 {
00013     m_Name = value;
00014 }
Generated on Fri Nov 15 2024 22:20:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LibraryManagement/cs/SampleConfiguration.cs Source File

  • LibraryManagement
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Library management C# sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title = "Adding a folder to the Pictures library",     ClassType = typeof(Scenario1) },
00025             new Scenario() { Title = "Listing folders in the Pictures library",     ClassType = typeof(Scenario2) },
00026             new Scenario() { Title = "Removing a folder from the Pictures library", ClassType = typeof(Scenario3) }
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MobileBroadband/cs/ModemDeviceServices.xaml.cs Source File

  • MobileBroadband
  • cs

ModemDeviceServices.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012
00013 using System;
00014 using System.Collections.Generic;
00015 using System.IO;
00016 using System.Linq;
00017 using System.Runtime.InteropServices.WindowsRuntime;
00018 using System.Text;
00019 using Windows.Foundation;
00020 using Windows.Foundation.Collections;
00021 using Windows.UI.Xaml;
00022 using Windows.UI.Xaml.Controls;
00023 using Windows.UI.Xaml.Controls.Primitives;
00024 using Windows.UI.Xaml.Data;
00025 using Windows.UI.Xaml.Input;
00026 using Windows.UI.Xaml.Media;
00027 using Windows.UI.Xaml.Navigation;
00028 using Windows.Networking.NetworkOperators;
00029 using Windows.Networking.Connectivity;
00030 using SDKTemplate;
00031
00032 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00033
00034 namespace MobileBroadband
00035 {
00036     /// <summary>
00037     /// An empty page that can be used on its own or navigated to within a Frame.
00038     /// </summary>
00039     public sealed partial class ModemDeviceServices : Page
00040     {
00041         MainPage rootPage = MainPage.Current;
00042         public ModemDeviceServices()
00043         {
00044             this.InitializeComponent();
00045         }
00046
00047
00048         private void btnDeviceService_Click(object sender, RoutedEventArgs e)
00049         {
00050             var modem = MobileBroadbandModem.GetDefault();
00051             var deviceService = modem.DeviceServices;
00052             if (deviceService != null)
00053             {
00054                 StringBuilder sb = new StringBuilder();
00055                 foreach (var d in deviceService)
00056                 {
00057                     sb.AppendLine(String.Format("DeviceService ID:{0}, Read Allowed:{1}, Write Allowed:{2}", d.DeviceServiceId.ToString(), d.IsDataReadSupported.ToString(), d.IsDataWriteSupported.ToString()));
00058                 }
00059                 txtModemInformation.Text = sb.ToString();
00060             }
00061             else
00062             {
00063                 rootPage.NotifyUser("No Device Services found.", NotifyType.ErrorMessage);
00064
00065             }
00066         }
00067     }
00068 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SplashScreen/cs/ExtendedSplash.xaml.cs Source File

  • SplashScreen
  • cs

ExtendedSplash.xaml.cs

Go to the documentation of this file.
00001 ﻿// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 // PARTICULAR PURPOSE.
00005 //
00006 // Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 using SDKTemplate;
00009
00010 using SDKTemplate.Common;
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.ApplicationModel.Activation;
00015 using Windows.Foundation;
00016 using Windows.Graphics.Display;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Data;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace SplashScreenSample
00024 {
00025     partial class ExtendedSplash
00026     {
00027         internal Rect splashImageRect; // Rect to store splash screen image coordinates.
00028         internal bool dismissed = false; // Variable to track splash screen dismissal status.
00029         internal Frame rootFrame;
00030
00031         private SplashScreen splash; // Variable to hold the splash screen object.
00032         private double ScaleFactor; //Variable to hold the device scale factor (use to determine phone screen resolution)
00033
00034         public ExtendedSplash(SplashScreen splashscreen, bool loadState)
00035         {
00036             InitializeComponent();
00037
00038             LearnMoreButton.Click += new RoutedEventHandler(LearnMoreButton_Click);
00039             // Listen for window resize events to reposition the extended splash screen image accordingly.
00040             // This is important to ensure that the extended splash screen is formatted properly in response to snapping, unsnapping, rotation, etc...
00041             Window.Current.SizeChanged += new WindowSizeChangedEventHandler(ExtendedSplash_OnResize);
00042
00043             ScaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
00044
00045             splash = splashscreen;
00046
00047             if (splash != null)
00048             {
00049                 // Register an event handler to be executed when the splash screen has been dismissed.
00050                 splash.Dismissed += new TypedEventHandler<SplashScreen, Object>(DismissedEventHandler);
00051
00052                 // Retrieve the window coordinates of the splash screen image.
00053                 splashImageRect = splash.ImageLocation;
00054                 PositionImage();
00055             }
00056
00057             // Create a Frame to act as the navigation context
00058             rootFrame = new Frame();
00059
00060             // Restore the saved session state if necessary
00061             RestoreStateAsync(loadState);
00062         }
00063
00064         async void RestoreStateAsync(bool loadState)
00065         {
00066             if (loadState)
00067                 await SuspensionManager.RestoreAsync();
00068
00069             // Normally you should start the time consuming task asynchronously here and
00070             // dismiss the extended splash screen in the completed handler of that task
00071             // This sample dismisses extended splash screen  in the handler for "Learn More" button for demonstration
00072         }
00073
00074         // Position the extended splash screen image in the same location as the system splash screen image.
00075         void PositionImage()
00076         {
00077             extendedSplashImage.SetValue(Canvas.LeftProperty, splashImageRect.Left);
00078             extendedSplashImage.SetValue(Canvas.TopProperty, splashImageRect.Top);
00079             if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00080             {
00081                 extendedSplashImage.Height = splashImageRect.Height / ScaleFactor;
00082                 extendedSplashImage.Width = splashImageRect.Width / ScaleFactor;
00083             }
00084             else
00085             {
00086                 extendedSplashImage.Height = splashImageRect.Height;
00087                 extendedSplashImage.Width = splashImageRect.Width;
00088             }
00089         }
00090
00091         void ExtendedSplash_OnResize(Object sender, WindowSizeChangedEventArgs e)
00092         {
00093             // Safely update the extended splash screen image coordinates. This function will be fired in response to snapping, unsnapping, rotation, etc...
00094             if (splash != null)
00095             {
00096                 // Update the coordinates of the splash screen image.
00097                 splashImageRect = splash.ImageLocation;
00098                 PositionImage();
00099             }
00100         }
00101
00102         void LearnMoreButton_Click(object sender, RoutedEventArgs e)
00103         {
00104             // Navigate to mainpage
00105             rootFrame.Navigate(typeof(MainPage));
00106
00107             // Set extended splash info on main page
00108             ((MainPage)rootFrame.Content).SetExtendedSplashInfo(splashImageRect, dismissed);
00109
00110             // Place the frame in the current Window
00111             Window.Current.Content = rootFrame;
00112         }
00113
00114         // Include code to be executed when the system has transitioned from the splash screen to the extended splash screen (application's first view).
00115         void DismissedEventHandler(SplashScreen sender, object e)
00116         {
00117             dismissed = true;
00118
00119             // Navigate away from the app's extended splash screen after completing setup operations here...
00120             // This sample navigates away from the extended splash screen when the "Learn More" button is clicked.
00121         }
00122     }
00123 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContactCards/cs/SampleConfiguration.cs Source File

  • ContactCards
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.ApplicationModel.Contacts;
00015 using Windows.Foundation;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018
00019 namespace SDKTemplate
00020 {
00021     public partial class MainPage : Page
00022     {
00023         public const string FEATURE_NAME = "Contact cards C# sample";
00024
00025         List<Scenario> scenarios = new List<Scenario>
00026         {
00027             new Scenario() { Title="Show mini contact card", ClassType=typeof(Scenario1_Mini)},
00028             new Scenario() { Title="Show mini contact card with delayed information", ClassType=typeof(Scenario2_DelayMini)},
00029             new Scenario() { Title="Show full contact card", ClassType=typeof(Scenario3_Full)},
00030         };
00031
00032         public Contact CreateContactFromUserInput(TextBox EmailAddress, TextBox PhoneNumber)
00033         {
00034             if (EmailAddress.Text.Length == 0 && PhoneNumber.Text.Length == 0)
00035             {
00036                 NotifyUser("You must enter an email address and/or phone number.", NotifyType.ErrorMessage);
00037                 return null;
00038             }
00039
00040             Contact contact = new Contact();
00041
00042             // Maximum length for email address is 321, enforced by XAML markup.
00043             if (EmailAddress.Text.Length > 0)
00044             {
00045                 ContactEmail email = new ContactEmail() { Address = EmailAddress.Text };
00046                 contact.Emails.Add(email);
00047             }
00048
00049             // Maximum length for phone number is 50, enforced by XAML markup.
00050             if (PhoneNumber.Text.Length > 0)
00051             {
00052                 ContactPhone phone = new ContactPhone() { Number = PhoneNumber.Text };
00053                 contact.Phones.Add(phone);
00054             }
00055
00056             return contact;
00057         }
00058
00059         public static Rect GetElementRect(FrameworkElement element)
00060         {
00061             Windows.UI.Xaml.Media.GeneralTransform buttonTransform = element.TransformToVisual(null);
00062             Point point = buttonTransform.TransformPoint(new Point());
00063             return new Rect(point, new Size(element.ActualWidth, element.ActualHeight));
00064         }
00065     }
00066
00067     public class Scenario
00068     {
00069         public string Title { get; set; }
00070         public Type ClassType { get; set; }
00071     }
00072 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SaveStateEventArgs Member List

This is the complete list of members for SaveStateEventArgs, including all inherited members.
PageState | SaveStateEventArgs |
SaveStateEventArgs(Dictionary< string, Object > pageState) | SaveStateEventArgs | [inline]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cs/AdventureWorks/Common/INavigationService.cs Source File

  • CortanaVoiceCommand
  • cs
  • AdventureWorks
  • Common

INavigationService.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013
00014 namespace AdventureWorks.Common
00015 {
00016     /// <summary>
00017     /// Navigation service interface, allows a test implementation to be substituted in its place.
00018     /// </summary>
00019     public interface INavigationService
00020     {
00021         bool Navigate<T>(object parameter = null);
00022
00023         bool Navigate(Type source, object parameter = null);
00024
00025         void GoBack();
00026     }
00027 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cpp/Common/DeviceResources.cpp Source File

  • 360VideoPlayback
  • cpp
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
00002 #include "DeviceResources.h"
00003 #include "DirectXHelper.h"
00004
00005 #include <Collection.h>
00006 #include <windows.graphics.directx.direct3d11.interop.h>
00007
00008 using namespace D2D1;
00009 using namespace Microsoft::WRL;
00010 using namespace Windows::Graphics::DirectX::Direct3D11;
00011 using namespace Windows::Graphics::Display;
00012 using namespace Windows::Graphics::Holographic;
00013
00014 const FLOAT dxgiDefaultDPI = 96;
00015
00016 // Constructor for DeviceResources.
00017 DX::DeviceResources::DeviceResources()
00018 {
00019     CreateDeviceIndependentResources();
00020 }
00021
00022 // Configures resources that don't depend on the Direct3D device.
00023 void DX::DeviceResources::CreateDeviceIndependentResources()
00024 {
00025     // Initialize Direct2D resources.
00026     D2D1_FACTORY_OPTIONS options{};
00027
00028 #if defined(_DEBUG)
00029     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00030     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00031 #endif
00032
00033     // Initialize the Direct2D Factory.
00034     DX::ThrowIfFailed(
00035         D2D1CreateFactory(
00036             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00037             __uuidof(ID2D1Factory2),
00038             &options,
00039             &m_d2dFactory
00040         )
00041     );
00042
00043     // Initialize the DirectWrite Factory.
00044     DX::ThrowIfFailed(
00045         DWriteCreateFactory(
00046             DWRITE_FACTORY_TYPE_SHARED,
00047             __uuidof(IDWriteFactory2),
00048             &m_dwriteFactory
00049         )
00050     );
00051
00052     // Initialize the Windows Imaging Component (WIC) Factory.
00053     DX::ThrowIfFailed(
00054         CoCreateInstance(
00055             CLSID_WICImagingFactory2,
00056             nullptr,
00057             CLSCTX_INPROC_SERVER,
00058             IID_PPV_ARGS(&m_wicFactory)
00059         )
00060     );
00061 }
00062
00063 void DX::DeviceResources::SetHolographicSpace(HolographicSpace^ holographicSpace)
00064 {
00065     // Cache the holographic space. Used to re-initalize during device-lost scenarios.
00066     m_holographicSpace = holographicSpace;
00067
00068     InitializeUsingHolographicSpace();
00069 }
00070
00071 void DX::DeviceResources::InitializeUsingHolographicSpace()
00072 {
00073     // The holographic space might need to determine which adapter supports
00074     // holograms, in which case it will specify a non-zero PrimaryAdapterId.
00075     LUID id =
00076     {
00077         m_holographicSpace->PrimaryAdapterId.LowPart,
00078         m_holographicSpace->PrimaryAdapterId.HighPart
00079     };
00080
00081     // When a primary adapter ID is given to the app, the app should find
00082     // the corresponding DXGI adapter and use it to create Direct3D devices
00083     // and device contexts. Otherwise, there is no restriction on the DXGI
00084     // adapter the app can use.
00085     if ((id.HighPart != 0) || (id.LowPart != 0))
00086     {
00087         UINT createFlags = 0;
00088 #ifdef DEBUG
00089         if (DX::SdkLayersAvailable())
00090         {
00091             createFlags |= DXGI_CREATE_FACTORY_DEBUG;
00092         }
00093 #endif
00094         // Create the DXGI factory.
00095         ComPtr<IDXGIFactory1> dxgiFactory;
00096         DX::ThrowIfFailed(
00097             CreateDXGIFactory2(
00098                 createFlags,
00099                 IID_PPV_ARGS(&dxgiFactory)
00100             )
00101         );
00102         ComPtr<IDXGIFactory4> dxgiFactory4;
00103         DX::ThrowIfFailed(dxgiFactory.As(&dxgiFactory4));
00104
00105         // Retrieve the adapter specified by the holographic space.
00106         DX::ThrowIfFailed(
00107             dxgiFactory4->EnumAdapterByLuid(
00108                 id,
00109                 IID_PPV_ARGS(&m_dxgiAdapter)
00110             )
00111         );
00112     }
00113     else
00114     {
00115         m_dxgiAdapter.Reset();
00116     }
00117
00118     CreateDeviceResources();
00119
00120     m_holographicSpace->SetDirect3D11Device(m_d3dInteropDevice);
00121 }
00122
00123 // Configures the Direct3D device, and stores handles to it and the device context.
00124 void DX::DeviceResources::CreateDeviceResources()
00125 {
00126     // This flag adds support for surfaces with a different color channel ordering
00127     // than the API default. It is required for compatibility with Direct2D.
00128     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00129
00130 #if defined(_DEBUG)
00131     if (DX::SdkLayersAvailable())
00132     {
00133         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00134         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00135     }
00136 #endif
00137
00138     // This array defines the set of DirectX hardware feature levels this app will support.
00139     // Note the ordering should be preserved.
00140     // Note that HoloLens supports feature level 11.1. The HoloLens emulator is also capable
00141     // of running on graphics cards starting with feature level 10.0.
00142     D3D_FEATURE_LEVEL featureLevels[] =
00143     {
00144         D3D_FEATURE_LEVEL_12_1,
00145         D3D_FEATURE_LEVEL_12_0,
00146         D3D_FEATURE_LEVEL_11_1,
00147         D3D_FEATURE_LEVEL_11_0,
00148         D3D_FEATURE_LEVEL_10_1,
00149         D3D_FEATURE_LEVEL_10_0
00150     };
00151
00152     D3D11_RASTERIZER_DESC rasterDesc{
00153             D3D11_FILL_SOLID,
00154             D3D11_CULL_NONE,
00155             false,
00156             0,
00157             0.0f,
00158             0.0f,
00159             true,
00160             false,
00161             true,
00162             true };
00163
00164
00165     // Create the Direct3D 11 API device object and a corresponding context.
00166     ComPtr<ID3D11Device> device;
00167     ComPtr<ID3D11DeviceContext> context;
00168
00169     const D3D_DRIVER_TYPE driverType = m_dxgiAdapter == nullptr ? D3D_DRIVER_TYPE_HARDWARE : D3D_DRIVER_TYPE_UNKNOWN;
00170     const HRESULT hr = D3D11CreateDevice(
00171         m_dxgiAdapter.Get(),        // Either nullptr, or the primary adapter determined by Windows Holographic.
00172         driverType,                 // Create a device using the hardware graphics driver.
00173         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00174         creationFlags,              // Set debug and Direct2D compatibility flags.
00175         featureLevels,              // List of feature levels this app can support.
00176         ARRAYSIZE(featureLevels),   // Size of the list above.
00177         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00178         &device,                    // Returns the Direct3D device created.
00179         &m_d3dFeatureLevel,         // Returns feature level of device created.
00180         &context                    // Returns the device immediate context.
00181     );
00182
00183     if (FAILED(hr))
00184     {
00185         // If the initialization fails, fall back to the WARP device.
00186         // For more information on WARP, see:
00187         // http://go.microsoft.com/fwlink/?LinkId=286690
00188         DX::ThrowIfFailed(
00189             D3D11CreateDevice(
00190                 nullptr,              // Use the default DXGI adapter for WARP.
00191                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00192                 0,
00193                 creationFlags,
00194                 featureLevels,
00195                 ARRAYSIZE(featureLevels),
00196                 D3D11_SDK_VERSION,
00197                 &device,
00198                 &m_d3dFeatureLevel,
00199                 &context
00200             )
00201         );
00202     }
00203
00204
00205     // Store pointers to the Direct3D device and immediate context.
00206     DX::ThrowIfFailed(
00207         device.As(&m_d3dDevice)
00208     );
00209
00210     DX::ThrowIfFailed(
00211         context.As(&m_d3dContext)
00212     );
00213
00214     // Acquire the DXGI interface for the Direct3D device.
00215     ComPtr<IDXGIDevice3> dxgiDevice;
00216     DX::ThrowIfFailed(
00217         m_d3dDevice.As(&dxgiDevice)
00218     );
00219
00220     // Wrap the native device using a WinRT interop object.
00221     m_d3dInteropDevice = CreateDirect3DDevice(dxgiDevice.Get());
00222
00223     // Cache the DXGI adapter.
00224     // This is for the case of no preferred DXGI adapter, or fallback to WARP.
00225     ComPtr<IDXGIAdapter> dxgiAdapter;
00226     DX::ThrowIfFailed(
00227         dxgiDevice->GetAdapter(&dxgiAdapter)
00228     );
00229     DX::ThrowIfFailed(
00230         dxgiAdapter.As(&m_dxgiAdapter)
00231     );
00232
00233
00234     DX::ThrowIfFailed(
00235         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00236     );
00237
00238     DX::ThrowIfFailed(
00239         m_d2dDevice->CreateDeviceContext(
00240             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00241             &m_d2dContext
00242         )
00243     );
00244     // Set DPI that will be used when drawing to D2D
00245     m_d2dContext->SetDpi(dxgiDefaultDPI, dxgiDefaultDPI);
00246
00247     // Check for device support for the optional feature that allows setting the render target array index from the vertex shader stage.
00248     D3D11_FEATURE_DATA_D3D11_OPTIONS3 options;
00249     m_d3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS3, &options, sizeof(options));
00250     if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer)
00251     {
00252         m_supportsVprt = true;
00253     }
00254
00255     ID3D11RasterizerState* praster;
00256     DX::ThrowIfFailed(m_d3dDevice->CreateRasterizerState(&rasterDesc, &praster));
00257     m_d3dContext->RSSetState(praster);
00258
00259     ComPtr<ID3D10Multithread> spMultithread;
00260     DX::ThrowIfFailed(
00261         m_d3dDevice->QueryInterface(IID_PPV_ARGS(&spMultithread))
00262     );
00263     spMultithread->SetMultithreadProtected(TRUE);
00264 }
00265
00266 // Validates the back buffer for each HolographicCamera and recreates
00267 // resources for back buffers that have changed.
00268 // Locks the set of holographic camera resources until the function exits.
00269 void DX::DeviceResources::EnsureCameraResources(
00270     HolographicFrame^ frame,
00271     HolographicFramePrediction^ prediction)
00272 {
00273     UseHolographicCameraResources<void>([this, frame, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00274     {
00275         for (HolographicCameraPose^ pose : prediction->CameraPoses)
00276         {
00277             HolographicCameraRenderingParameters^ renderingParameters = frame->GetRenderingParameters(pose);
00278             CameraResources* pCameraResources = cameraResourceMap[pose->HolographicCamera->Id].get();
00279
00280             pCameraResources->CreateResourcesForBackBuffer(this, renderingParameters);
00281         }
00282     });
00283 }
00284
00285 // Prepares to allocate resources and adds resource views for a camera.
00286 // Locks the set of holographic camera resources until the function exits.
00287 void DX::DeviceResources::AddHolographicCamera(HolographicCamera^ camera)
00288 {
00289     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00290     {
00291         cameraResourceMap[camera->Id] = std::make_unique<CameraResources>(camera);
00292     });
00293 }
00294
00295 // Deallocates resources for a camera and removes the camera from the set.
00296 // Locks the set of holographic camera resources until the function exits.
00297 void DX::DeviceResources::RemoveHolographicCamera(HolographicCamera^ camera)
00298 {
00299     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00300     {
00301         CameraResources* pCameraResources = cameraResourceMap[camera->Id].get();
00302
00303         if (pCameraResources != nullptr)
00304         {
00305             pCameraResources->ReleaseResourcesForBackBuffer(this);
00306             cameraResourceMap.erase(camera->Id);
00307         }
00308     });
00309 }
00310
00311 // Recreate all device resources and set them back to the current state.
00312 // Locks the set of holographic camera resources until the function exits.
00313 void DX::DeviceResources::HandleDeviceLost()
00314 {
00315     if (m_deviceNotify != nullptr)
00316     {
00317         m_deviceNotify->OnDeviceLost();
00318     }
00319
00320     UseHolographicCameraResources<void>([this](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00321     {
00322         for (auto& pair : cameraResourceMap)
00323         {
00324             CameraResources* pCameraResources = pair.second.get();
00325             pCameraResources->ReleaseResourcesForBackBuffer(this);
00326         }
00327     });
00328
00329     InitializeUsingHolographicSpace();
00330
00331     if (m_deviceNotify != nullptr)
00332     {
00333         m_deviceNotify->OnDeviceRestored();
00334     }
00335 }
00336
00337 // Register our DeviceNotify to be informed on device lost and creation.
00338 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00339 {
00340     m_deviceNotify = deviceNotify;
00341 }
00342
00343 // Call this method when the app suspends. It provides a hint to the driver that the app
00344 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00345 void DX::DeviceResources::Trim()
00346 {
00347     m_d3dContext->ClearState();
00348
00349     ComPtr<IDXGIDevice3> dxgiDevice;
00350     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00351     dxgiDevice->Trim();
00352 }
00353
00354 // Present the contents of the swap chain to the screen.
00355 // Locks the set of holographic camera resources until the function exits.
00356 void DX::DeviceResources::Present(HolographicFrame^ frame)
00357 {
00358     // By default, this API waits for the frame to finish before it returns.
00359     // Holographic apps should wait for the previous frame to finish before
00360     // starting work on a new frame. This allows for better results from
00361     // holographic frame predictions.
00362     HolographicFramePresentResult presentResult = frame->PresentUsingCurrentPrediction();
00363
00364     // The PresentUsingCurrentPrediction API will detect when the graphics device
00365     // changes or becomes invalid. When this happens, it is considered a Direct3D
00366     // device lost scenario.
00367     if (presentResult == HolographicFramePresentResult::DeviceRemoved)
00368     {
00369         // The Direct3D device, context, and resources should be recreated.
00370         HandleDeviceLost();
00371     }
00372 }
Generated on Fri Nov 15 2024 22:16:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomTextBox Member List

This is the complete list of members for CustomTextBox, including all inherited members.
CustomTextBox() CustomTextBox [inline]
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SuspensionManagerException Member List

This is the complete list of members for SuspensionManagerException, including all inherited members.
SuspensionManagerException() | SuspensionManagerException | [inline]
SuspensionManagerException(Exception e) | SuspensionManagerException | [inline]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IOven Member List

This is the complete list of members for IOven, including all inherited members.
BakeBread(Platform::String^flavor) | IOven
BakeBread(String flavor) | IOven
BakeBread([in] HSTRING flavor) | IOven
BakeBread([in] HSTRING flavor) | IOven
BreadBaked | IOven
BreadBaked | IOven
BreadBaked([in] Windows.Foundation.TypedEventHandler< Oven *, BreadBakedEventArgs * > *handler,[out, retval] EventRegistrationToken *token) | IOven
BreadBaked([in] EventRegistrationToken token) | IOven
BreadBaked([in] Windows.Foundation.TypedEventHandler< Oven *, BreadBakedEventArgs * > *handler,[out, retval] EventRegistrationToken *token) | IOven
BreadBaked([in] EventRegistrationToken token) | IOven
ConfigurePreheatTemperature(OvenTemperature temperature) | IOven
ConfigurePreheatTemperature(OvenTemperature level) | IOven
ConfigurePreheatTemperature([in] OvenTemperature temperature) | IOven
ConfigurePreheatTemperature([in] OvenTemperature temperature) | IOven
Volume | IAppliance
Volume([out, retval] double *value) | IAppliance
Volume([out, retval] double *value) | IAppliance
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario7_FutureAccess.xaml.cpp Source File

  • FileAccess
  • cpp

Scenario7_FutureAccess.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario7_FutureAccess.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Storage;
00020 using namespace Windows::Storage::AccessCache;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Navigation;
00023
00024 Scenario7::Scenario7()
00025 {
00026     InitializeComponent();
00027 }
00028
00029 void Scenario7::OnNavigatedTo(NavigationEventArgs^ e)
00030 {
00031     rootPage->ValidateFile();
00032 }
00033
00034 void Scenario7::AddToListButton_Click(Object^ sender, RoutedEventArgs^ e)
00035 {
00036     StorageFile^ file = rootPage->SampleFile;
00037     if (file != nullptr)
00038     {
00039         if (MRURadioButton->IsChecked->Value)
00040         {
00041             // Add the file to app MRU and possibly system MRU
00042             RecentStorageItemVisibility visibility = SystemMRUCheckBox->IsChecked->Value ? RecentStorageItemVisibility::AppAndSystem : RecentStorageItemVisibility::AppOnly;
00043             mruToken = StorageApplicationPermissions::MostRecentlyUsedList->Add(file, file->Name, visibility);
00044             rootPage->NotifyUser("The file '" + file->Name + "' was added to the MRU list and a token was stored.", NotifyType::StatusMessage);
00045         }
00046         else
00047         {
00048             // Add the file to the FAL
00049             try
00050             {
00051                 falToken = StorageApplicationPermissions::FutureAccessList->Add(file, file->Name);
00052                 rootPage->NotifyUser("The file '" + file->Name + "' was added to the FAL list and a token was stored.", NotifyType::StatusMessage);
00053             }
00054             catch (COMException^ ex)
00055             {
00056                 if (ex->HResult == FA_E_MAX_PERSISTED_ITEMS_REACHED)
00057                 {
00058                     // A real program would call Remove() to create room in the FAL.
00059                     rootPage->NotifyUser("The file '" + file->Name + "' was not added to the FAL list because the FAL list is full.", NotifyType::ErrorMessage);
00060                 }
00061                 else
00062                 {
00063                     throw;
00064                 }
00065             }
00066         }
00067     }
00068     else
00069     {
00070         rootPage->NotifyUserFileNotExist();
00071     }
00072 }
00073
00074 void Scenario7::ShowListButton_Click(Object^ sender, RoutedEventArgs^ e)
00075 {
00076     AccessListEntryView^ entries = nullptr;
00077     String^ listName;
00078
00079     if (MRURadioButton->IsChecked->Value)
00080     {
00081         listName = "MRU";
00082         entries = StorageApplicationPermissions::MostRecentlyUsedList->Entries;
00083     }
00084     else
00085     {
00086         listName = "FAL";
00087         entries = StorageApplicationPermissions::FutureAccessList->Entries;
00088     }
00089
00090     if (entries->Size > 0)
00091     {
00092         String^ outputText = "The " + listName + " + list contains the following item(s):";
00093         for (const AccessListEntry& entry : entries)
00094         {
00095             outputText += "\n" + entry.Metadata; // Application previously chose to store file->Name in this field
00096         }
00097         rootPage->NotifyUser(outputText, NotifyType::StatusMessage);
00098     }
00099     else
00100     {
00101         rootPage->NotifyUser("The " + listName + " list is empty.", NotifyType::ErrorMessage);
00102     }
00103 }
00104
00105 void Scenario7::OpenFromListButton_Click(Object^ sender, RoutedEventArgs^ e)
00106 {
00107     task<StorageFile^> fileTask = task_from_result<StorageFile^>(nullptr);
00108
00109     if (MRURadioButton->IsChecked->Value)
00110     {
00111         if (mruToken != nullptr)
00112         {
00113             // When the MRU becomes full, older entries are automatically deleted, so check if the
00114             // token is still valid before using it.
00115             if (StorageApplicationPermissions::MostRecentlyUsedList->ContainsItem(mruToken))
00116             {
00117                 // Open the file via the token that was stored when adding this file into the MRU list
00118                 fileTask = create_task(StorageApplicationPermissions::MostRecentlyUsedList->GetFileAsync(mruToken));
00119             }
00120             else
00121             {
00122                 rootPage->NotifyUser("The token is no longer valid.", NotifyType::ErrorMessage);
00123             }
00124         }
00125         else
00126         {
00127             rootPage->NotifyUser("This operation requires a token. Add file to the MRU list first.", NotifyType::ErrorMessage);
00128         }
00129     }
00130     else
00131     {
00132         if (falToken != nullptr)
00133         {
00134             // Open the file via the token that was stored when adding this file into the FAL list.
00135             // The token remains valid until we explicitly remove it.
00136             fileTask = create_task(StorageApplicationPermissions::FutureAccessList->GetFileAsync(falToken));
00137         }
00138         else
00139         {
00140             rootPage->NotifyUser("This operation requires a token. Add file to the FAL list first.", NotifyType::ErrorMessage);
00141         }
00142     }
00143
00144     fileTask.then([this](StorageFile^ file)
00145     {
00146         if (file != nullptr)
00147         {
00148             create_task(FileIO::ReadTextAsync(file)).then([this, file](task<String^> task)
00149             {
00150                 try
00151                 {
00152                     String^ fileContent = task.get();
00153                     rootPage->NotifyUser("The file '" + file->Name + "' was opened by a stored token. It contains the following text:\n" + fileContent, NotifyType::StatusMessage);
00154                 }
00155                 catch (COMException^ ex)
00156                 {
00157                     // I/O errors are reported as exceptions.
00158                     rootPage->HandleIoException(ex, "Error reading file opened from list");
00159                 }
00160             });
00161         }
00162     });
00163 }
Generated on Fri Nov 15 2024 22:19:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Message Member List

This is the complete list of members for Scenario1_Message, including all inherited members.
Launch_Click(object sender, RoutedEventArgs e) | Scenario1_Message | [inline, private]
rootPage | Scenario1_Message | [private]
Scenario1_Message() | Scenario1_Message | [inline]
SetError(string err) | Scenario1_Message | [inline, private]
SetResult(CredentialPickerResults res) | Scenario1_Message | [inline, private]
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario6_CustomFilterAddedProps Member List

This is the complete list of members for Scenario6_CustomFilterAddedProps, including all inherited members.
deviceWatcherHelper | Scenario6_CustomFilterAddedProps | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario6_CustomFilterAddedProps |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario6_CustomFilterAddedProps |
resultCollection | Scenario6_CustomFilterAddedProps | [private]
Scenario6_CustomFilterAddedProps() | Scenario6_CustomFilterAddedProps |
StartWatcher() | Scenario6_CustomFilterAddedProps | [private]
StartWatcherButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario6_CustomFilterAddedProps |
StopWatcher() | Scenario6_CustomFilterAddedProps | [private]
StopWatcherButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario6_CustomFilterAddedProps |
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MobileHotspot/cppwinrt/pch.h Source File

  • MobileHotspot
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <unknwn.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 //#include "winrt/Windows.ApplicationModel.Background.h"
00008 #include "winrt/Windows.Networking.Connectivity.h"
00009 #include "winrt/Windows.Networking.NetworkOperators.h"
00010 //#include "winrt/Windows.Security.Credentials.h"
00011 //#include "winrt/Windows.Storage.h"
00012 #include "winrt/Windows.System.h"
00013 #include "winrt/Windows.UI.Core.h"
00014 #include "winrt/Windows.UI.Xaml.h"
00015 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00016 #include "winrt/Windows.UI.Xaml.Controls.h"
00017 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00018 #include "winrt/Windows.UI.Xaml.Documents.h"
00019 //#include "winrt/Windows.UI.Xaml.Interop.h"
00020 #include "winrt/Windows.UI.Xaml.Markup.h"
00021 #include "winrt/Windows.UI.Xaml.Media.h"
00022 #include "winrt/Windows.UI.Xaml.Navigation.h"
00023 #include "SampleConfiguration.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DSvgImage/cpp/Common/DirectXHelper.h Source File

  • D2DSvgImage
  • cpp
  • Common

DirectXHelper.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <ppltasks.h>
00015
00016 namespace DX
00017 {
00018     inline void ThrowIfFailed(HRESULT hr)
00019     {
00020         if (FAILED(hr))
00021         {
00022             // Set a breakpoint on this line to catch Win32 API errors.
00023             throw Platform::Exception::CreateException(hr);
00024         }
00025     }
00026
00027     // Function that reads from a binary file asynchronously.
00028     inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename)
00029     {
00030         using namespace Windows::Storage;
00031         using namespace Concurrency;
00032
00033         auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
00034
00035         return create_task(folder->GetFileAsync(Platform::StringReference(filename.c_str()))).then([] (StorageFile^ file)
00036         {
00037             return FileIO::ReadBufferAsync(file);
00038         }).then([] (Streams::IBuffer^ fileBuffer) -> std::vector<byte>
00039         {
00040             std::vector<byte> returnBuffer;
00041             returnBuffer.resize(fileBuffer->Length);
00042             Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), fileBuffer->Length));
00043             return returnBuffer;
00044         });
00045     }
00046
00047     // Converts a length in device-independent pixels (DIPs) to a length in physical pixels.
00048     inline float ConvertDipsToPixels(float dips, float dpi)
00049     {
00050         static const float dipsPerInch = 96.0f;
00051         return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00052     }
00053
00054     // Converts a length in physical pixels to a length in device-independent pixels (DIPs).
00055     inline float ConvertPixelsToDips(float pixels)
00056     {
00057         static const float dipsPerInch = 96.0f;
00058         return pixels * dipsPerInch / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->LogicalDpi; // Do not round.
00059     }
00060
00061     // Converts a length in physical pixels to a length in device-independent pixels (DIPs) using the provided DPI. This removes the need
00062     // to call this function from a thread associated with a CoreWindow, which is required by DisplayInformation::GetForCurrentView().
00063     inline float ConvertPixelsToDips(float pixels, float dpi)
00064     {
00065         static const float dipsPerInch = 96.0f;
00066         return pixels * dipsPerInch / dpi; // Do not round.
00067     }
00068
00069 #if defined(_DEBUG)
00070     // Check for SDK Layer support.
00071     inline bool SdkLayersAvailable()
00072     {
00073         HRESULT hr = D3D11CreateDevice(
00074             nullptr,
00075             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00076             0,
00077             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00078             nullptr,                    // Any feature level will do.
00079             0,
00080             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00081             nullptr,                    // No need to keep the D3D device reference.
00082             nullptr,                    // No need to know the feature level.
00083             nullptr                     // No need to keep the D3D device context reference.
00084             );
00085
00086         return SUCCEEDED(hr);
00087     }
00088 #endif
00089 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MicrosoftPassport/Server/Data/DAL.cs Source File

  • MicrosoftPassport
  • Server
  • Data

DAL.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 // Please refer to the Microsoft Passport and Windows Hello
00012 // whitepaper on the Windows Dev Center for a complete
00013 // explanation of Microsoft Passport and Windows Hello
00014 // implementation:
00015 // http://go.microsoft.com/fwlink/p/?LinkId=522066
00016 //*********************************************************
00017 using MicrosoftPassport.Models;
00018 using System.Collections.Generic;
00019 using System.Linq;
00020 using System.Security.Cryptography;
00021
00022 namespace MicrosoftPassport.Server.Data
00023 {
00024     public class DAL
00025     {
00026         public static DAL Instance { get; } = new DAL();
00027
00028         // In this sample, we keep a list of users and devices in memory, this will be cleared when the
00029         // server is stopped. In a real-world scenario, you would store this information in a database.
00030
00031         private class RegisteredUser
00032         {
00033             public string UserId;
00034             public byte[] PublicKey;
00035             public string PublicKeyHash;
00036             public string DeviceName;
00037             public byte[] ActiveChallenge;
00038         }
00039         private List<RegisteredUser> Users { get; } = new List<RegisteredUser>();
00040
00041         private DAL()
00042         {
00043         }
00044
00045         public bool RegisterUser(string userId, byte[] publicKey, string publicKeyHash, string deviceName)
00046         {
00047             Users.Add(new RegisteredUser
00048             {
00049                 UserId = userId,
00050                 PublicKey = publicKey,
00051                 PublicKeyHash = publicKeyHash,
00052                 DeviceName = deviceName
00053             });
00054             return true;
00055         }
00056
00057         public bool RemoveRegisteredKey(string userId, string publicKeyHash)
00058         {
00059             Users.RemoveAll(u => u.UserId == userId && u.PublicKeyHash == publicKeyHash);
00060             return true;
00061         }
00062
00063         public byte[] GetPublicKeyForUser(string userId, string publicKeyHash, out byte[] challenge)
00064         {
00065             RegisteredUser user = Users.FirstOrDefault(u => u.UserId == userId && u.PublicKeyHash == publicKeyHash);
00066
00067             // Each challenge is valid only once. Prevent replay attack.
00068             challenge = user.ActiveChallenge;
00069             user.ActiveChallenge = null;
00070
00071             return user.PublicKey;
00072         }
00073
00074         public bool SetActiveChallenge(string userId, string publicKeyHash, byte[] challenge)
00075         {
00076             RegisteredUser user = Users.FirstOrDefault(u => u.UserId == userId && u.PublicKeyHash == publicKeyHash);
00077             user.ActiveChallenge = challenge;
00078             return true;
00079         }
00080     }
00081 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraProfile/cpp/pch.cpp Source File

  • CameraProfile
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cs/Scenario14_MeteredConnectionFilter.xaml.cs Source File

  • HttpClient
  • cs

Scenario14_MeteredConnectionFilter.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using HttpFilters;
00013 using System;
00014 using System.Threading;
00015 using System.Threading.Tasks;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019 using Windows.Web.Http;
00020 using Windows.Web.Http.Filters;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario14_MeteredConnectionFilter : Page
00025     {
00026         MainPage rootPage = MainPage.Current;
00027
00028         private HttpMeteredConnectionFilter meteredConnectionFilter;
00029         private HttpClient httpClient;
00030         private CancellationTokenSource cts;
00031
00032         public Scenario14_MeteredConnectionFilter()
00033         {
00034             this.InitializeComponent();
00035         }
00036
00037         protected override void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039             HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter();
00040             meteredConnectionFilter = new HttpMeteredConnectionFilter(baseProtocolFilter);
00041             httpClient = new HttpClient(meteredConnectionFilter);
00042             cts = new CancellationTokenSource();
00043         }
00044
00045         protected override void OnNavigatedFrom(NavigationEventArgs e)
00046         {
00047             cts.Cancel();
00048             cts.Dispose();
00049             httpClient.Dispose();
00050             meteredConnectionFilter.Dispose();
00051         }
00052
00053         private async void Start_Click(object sender, RoutedEventArgs e)
00054         {
00055             // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
00056             // valid, absolute URI, we'll notify the user about the incorrect input.
00057             Uri resourceUri = Helpers.TryParseHttpUri(AddressField.Text);
00058             if (resourceUri == null)
00059             {
00060                 rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
00061                 return;
00062             }
00063
00064             Helpers.ScenarioStarted(StartButton, CancelButton, OutputField);
00065             rootPage.NotifyUser("In progress", NotifyType.StatusMessage);
00066
00067             HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, resourceUri);
00068
00069             MeteredConnectionPriority priority = MeteredConnectionPriority.Low;
00070             if (MediumRadio.IsChecked.Value)
00071             {
00072                 priority = MeteredConnectionPriority.Medium;
00073             }
00074             else if (HighRadio.IsChecked.Value)
00075             {
00076                 priority = MeteredConnectionPriority.High;
00077             }
00078             request.Properties[HttpMeteredConnectionFilter.MeteredConnectionPriorityPropertyName] = priority;
00079
00080             // This sample uses a "try" in order to support TaskCanceledException.
00081             // If you don't need to support cancellation, then the "try" is not needed.
00082             try
00083             {
00084                 HttpRequestResult result = await httpClient.TrySendRequestAsync(request).AsTask(cts.Token);
00085
00086                 if (result.Succeeded)
00087                 {
00088                     await Helpers.DisplayTextResultAsync(result.ResponseMessage, OutputField, cts.Token);
00089
00090                     rootPage.NotifyUser("Completed", NotifyType.StatusMessage);
00091                 }
00092                 else
00093                 {
00094                     Helpers.DisplayWebError(rootPage, result.ExtendedError);
00095                 }
00096             }
00097             catch (TaskCanceledException)
00098             {
00099                 rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
00100             }
00101
00102             Helpers.ScenarioCompleted(StartButton, CancelButton);
00103         }
00104
00105         private void Cancel_Click(object sender, RoutedEventArgs e)
00106         {
00107             cts.Cancel();
00108             cts.Dispose();
00109
00110             // Re-create the CancellationTokenSource.
00111             cts = new CancellationTokenSource();
00112         }
00113
00114         private void OptInSwitch_Toggled(object sender, RoutedEventArgs e)
00115         {
00116             meteredConnectionFilter.OptIn = OptInSwitch.IsOn;
00117         }
00118     }
00119 }
Generated on Fri Nov 15 2024 22:20:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario3.xaml.h Source File

  • MapControl
  • cpp

Scenario3.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::UI::Xaml::Data::Bindable]
00020     public ref class PointOfInterest sealed
00021     {
00022     public:
00023         property Platform::String^ DisplayName;
00024         property Windows::Devices::Geolocation::Geopoint^ Location;
00025         property Windows::Foundation::Uri^ ImageSourceUri;
00026         property Windows::Foundation::Point NormalizedAnchorPoint;
00027     };
00028
00029     [Windows::Foundation::Metadata::WebHostHidden]
00030     public ref class Scenario3 sealed
00031     {
00032     public:
00033         Scenario3();
00034     private:
00035         MainPage^ rootPage = MainPage::Current;
00036         void MyMap_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         void addXamlChildrenButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         void mapItemButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039     };
00040 }
Generated on Fri Nov 15 2024 22:18:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFontImplementation/FontDownloadListener.cpp Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFontImplementation

FontDownloadListener.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "FontDownloadListener.h"
00014 #include "DirectXHelper.h"
00015
00016 using namespace DWriteTextLayoutCloudFontImplementation;
00017
00018
00019 // Only one instance of FontDownloadListener will be needed for the app, so
00020 // declaring this as a global.
00021 FontDownloadListener^ g_listener;
00022
00023
00024 // DownloadListener implementation:
00025
00026 HRESULT STDMETHODCALLTYPE Listener::QueryInterface(
00027     REFIID riid,
00028     _COM_Outptr_ void **obj
00029     )
00030 {
00031     *obj = nullptr;
00032     if (riid == __uuidof(IDWriteFontDownloadListener) || riid == __uuidof(IUnknown))
00033     {
00034         AddRef();
00035         *obj = this;
00036         return S_OK;
00037     }
00038     return E_NOINTERFACE;
00039 }
00040
00041
00042 ULONG STDMETHODCALLTYPE Listener::AddRef()
00043 {
00044     return InterlockedIncrement(&m_refCount);
00045 }
00046
00047 ULONG STDMETHODCALLTYPE Listener::Release()
00048 {
00049     uint32 newCount = InterlockedDecrement(&m_refCount);
00050     if (newCount == 0)
00051         delete this;
00052     return newCount;
00053 }
00054
00055
00056 void STDMETHODCALLTYPE Listener::DownloadCompleted(
00057     _In_ IDWriteFontDownloadQueue* downloadQueue,
00058     _In_opt_ IUnknown* context,
00059     HRESULT downloadResult
00060     )
00061 {
00062     // Since this is a platform callback that doesn't expect exceptions,
00063     // we shouldn't leave any exceptions unhandled.
00064     try
00065     {
00066         if (SUCCEEDED(downloadResult))
00067         {
00068             // If we had passed a context in the BeginDownload call, we could test
00069             // for that context now.
00070             //
00071             // Note, however: relying on a context isn't useful if the font download
00072             // queue is shared with other things, such as the XAML framework, that
00073             // may also be calling BeginDownload. That's because you may do something,
00074             // such as creating or modifying a text layout, that results in requests
00075             // being added to the download queue, but XAML may detect that the queue
00076             // is not empty and call BeginDownload before you do, and it won't pass in
00077             // the context you'd be expecting.
00078
00079             FontDownloadListener::RaiseDownloadCompleted();
00080         }
00081     }
00082     catch (...)
00083     {
00084         return;
00085     }
00086 }
00087
00088
00089
00090 // FontDownloadListener implementation:
00091
00092 FontDownloadListener::FontDownloadListener()
00093 {
00094     // Get the system's font download queue.
00095
00096     Microsoft::WRL::ComPtr<IDWriteFactory3> dwriteFactory;
00097
00098     DX::ThrowIfFailed(
00099         DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory3), &dwriteFactory)
00100         );
00101
00102     DX::ThrowIfFailed(
00103         dwriteFactory->GetFontDownloadQueue(&m_downloadQueue)
00104         );
00105
00106     // We will need an instance of our IDWriteFontDownloadListener class.
00107     m_registeredListener = new Listener();
00108
00109     // To get notified when downloads complete, we can either register this
00110     // listener now by calling m_downloadQueue->AddListener, or we can pass the
00111     // listener when BeginDownload is called. If we only pass the listener when
00112     // calling BeginDownload, then the effect of that would be that this listener
00113     // will receive the DownloadCompleted callback only as a result of those
00114     // BeginDownload calls that we make. But if something else calls BeginDownload
00115     // on the queue, then this listener won't get called.
00116     //
00117     // Note that our app is hosted within XAML, and the XAML framework shares and
00118     // also interacts with the same font download queue. We should assume that,
00119     // as the app runs, the other object sharing the queue might also make calls
00120     // to BeginDownload.
00121     //
00122     // For example, suppose we create a text layout that uses a downloadable font
00123     // and then call BeginDownload. If we then call SetMaxWidth on that text layout
00124     // before the download completes, another request for the same font data will
00125     // get added to the queue. (This won't result in the data being downloaded
00126     // multiple times, however.) XAML checks the queue regularly, will see that
00127     // it's not empty, and will call BeginDownload.
00128     //
00129     // In this sample, our code that created a text layout and called BeginDownload
00130     // is running in the UI thread along with XAML. In this situation, then, it
00131     // would work okay to pass our listener when calling BeginDownload: there is no
00132     // possibility that XAML would call BeginDownload between the point we created
00133     // the layout and when we checked the queue. But in other apps, things may not
00134     // be so predictable. For that reason, this sample demonstrates use of a global
00135     // listener rather than passing a listener when BeginDownload is called.
00136     //
00137     // In general, if your app has a download queue that's shared between
00138     // different objects that can independently call BeginDownload, you should
00139     // always register a listener so that any of your objects that may need to
00140     // respond will see all DownloadCompleted events.
00141     //
00142     // This does create the possibility that an object could get multiple
00143     // DownloadCompleted calls while it only called BeginDownload once, or that
00144     // it gets DownloadCompleted calls resulting from download requests that
00145     // another object generated. There are mitigations that can be put in place
00146     // in the UI layer to avoid doing redundant work. See DocumentPresenter.cpp
00147     // for an example of this: the DownloadCompleted handler calls
00148     // RequestTextLayoutUpdate which schedules the actual update as a low-priority
00149     // task, allowing response for multiple events occurring in rapid succession to
00150     // be consolidated.
00151
00152     DX::ThrowIfFailed(
00153         m_downloadQueue->AddListener(m_registeredListener.Get(), &m_token)
00154         );
00155 }
00156
00157
00158 FontDownloadListener::~FontDownloadListener()
00159 {
00160     if (m_registeredListener != nullptr)
00161     {
00162         m_downloadQueue->RemoveListener(m_token);
00163     }
00164 }
00165
00166
00167 void FontDownloadListener::Initialize()
00168 {
00169     if (g_listener == nullptr)
00170     {
00171         g_listener = ref new FontDownloadListener();
00172     }
00173 }
00174
00175
00176 void FontDownloadListener::BeginDownload()
00177 {
00178     if (g_listener != nullptr)
00179     {
00180         // Don't request a download if the queue is empty.
00181         if (!g_listener->m_downloadQueue->IsEmpty())
00182         {
00183             g_listener->m_downloadQueue->BeginDownload();
00184         }
00185     }
00186 }
00187
00188
00189 void FontDownloadListener::RaiseDownloadCompleted()
00190 {
00191     DownloadCompleted();
00192 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LibraryManagement/cpp/S2_ListFolders.xaml.cpp Source File

  • LibraryManagement
  • cpp

S2_ListFolders.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario2.xaml.cpp
00014 // Implementation of the Scenario2 class
00015 //
00016
00017 #include "pch.h"
00018 #include "S2_ListFolders.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace concurrency;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Foundation::Collections;
00025 using namespace Windows::Storage;
00026 using namespace Windows::UI::Core;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029
00030 Scenario2::Scenario2()
00031 {
00032     InitializeComponent();
00033 }
00034
00035 /// <summary>
00036 /// Obtains the list of folders that make up the Pictures library and binds the FoldersListView
00037 /// to this list.
00038 /// </summary>
00039 /// <param name="sender"></param>
00040 /// <param name="e"></param>
00041 void Scenario2::ListFoldersButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00042 {
00043     ListFoldersButton->IsEnabled = false;
00044     create_task(StorageLibrary::GetLibraryAsync(KnownLibraryId::Pictures)).then([this](StorageLibrary^ library)
00045     {
00046         picturesLibrary = library;
00047
00048         // Bind the FoldersListView to the list of folders that make up the library
00049         FoldersListView->ItemsSource = picturesLibrary->Folders;
00050
00051         // Register for the DefinitionChanged event to be notified if other apps modify the library
00052         picturesLibrary->DefinitionChanged += ref new TypedEventHandler<StorageLibrary^, Platform::Object^>(
00053             [this](StorageLibrary^ /*sender*/, Platform::Object^ /*e*/)
00054         {
00055             Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this]()
00056             {
00057                 UpdateHeaderText();
00058             }));
00059         });
00060         UpdateHeaderText();
00061     });
00062 }
00063
00064 /// <summary>
00065 /// Updates the FoldersListHeaderTextBlock with the count of folders in the Pictures library.
00066 /// </summary>
00067 void Scenario2::UpdateHeaderText()
00068 {
00069     FoldersListHeaderTextBlock->Text = "Pictures library (" + picturesLibrary->Folders->Size + " folders)";
00070 }
00071
00072
Generated on Fri Nov 15 2024 22:20:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomVertexShaderMain Member List

This is the complete list of members for CustomVertexShaderMain, including all inherited members.
CreateWindowSizeDependentResources() | CustomVertexShaderMain |
CustomVertexShaderMain(const std::shared_ptr< DX::DeviceResources > &deviceResources) | CustomVertexShaderMain |
LoadInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | CustomVertexShaderMain |
m_deviceResources | CustomVertexShaderMain | [private]
m_sampleOverlay | CustomVertexShaderMain | [private]
m_sceneRenderer | CustomVertexShaderMain | [private]
m_timer | CustomVertexShaderMain | [private]
OnDeviceLost() | CustomVertexShaderMain | [virtual]
OnDeviceRestored() | CustomVertexShaderMain | [virtual]
Render() | CustomVertexShaderMain |
SaveInternalState(_In_ Windows::Foundation::Collections::IPropertySet^state) | CustomVertexShaderMain |
Update() | CustomVertexShaderMain |
UpdateManipulationState(_In_ Windows::UI::Input::ManipulationUpdatedEventArgs^args) | CustomVertexShaderMain |
~CustomVertexShaderMain() | CustomVertexShaderMain |
Generated on Fri Nov 15 2024 22:23:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Button Member List

This is the complete list of members for Button, including all inherited members.
AddChildElement(const std::shared_ptr< BaseElement > &childElement) | BaseElement |
ArrangeElements() override | Button | [virtual]
BaseElement() | BaseElement |
Button(UINT initialSize=BUTTON_SIZE, ButtonShape shape=ButtonShape::Rectangle) | Button |
FocusableElement() | FocusableElement |
FocusUpdate() override | Button | [virtual]
GetElementMargin() | BaseElement | [inline]
GetElementSize() | BaseElement | [inline]
GetIgnoreLayout() | BaseElement | [inline]
GetIsRenderPassNeeded() | BaseElement | [inline]
GetIsVisible() | BaseElement | [inline]
Initialize() override | Button | [virtual]
IsFocused() | FocusableElement | [inline, virtual]
m_brush | Button | [protected]
m_buttonState | Button | [protected]
m_deviceResources | BaseElement | [protected]
m_elementCoordIntersectionPoint | FocusableElement | [protected]
m_elementMargin | BaseElement | [protected]
m_elementSize | BaseElement | [protected]
m_ElliFocusOutline | Button | [private]
m_ElliPressedBackgroundFill | Button | [private]
m_forceIconCentered | Button | [protected]
m_ignoreLayout | BaseElement | [protected]
m_isFocused | FocusableElement | [protected]
m_isFocusIntersectionCalculated | FocusableElement | [protected]
m_isInitialized | BaseElement | [protected]
m_isLayoutHorizontal | BaseElement | [protected]
m_isParentFocused | FocusableElement | [protected]
m_isRenderPassNeeded | BaseElement | [protected]
m_isVisible | BaseElement | [protected]
m_maxSecondsInPressingState | Button | [protected]
m_parentControlTransform | Button | [protected]
m_parentFocusedPosition | FocusableElement | [protected]
m_parentTextureHeight | FocusableElement | [protected]
m_parentTextureWidth | FocusableElement | [protected]
m_parentTranslation | BaseElement | [protected]
m_pressingTimeOut | Button | [protected]
m_RectFocusOutline | Button | [private]
m_RectPressedBackgroundFill | Button | [private]
m_shape | Button | [protected]
m_transformedTranslation | BaseElement | [protected]
m_transformMatrix | BaseElement | [protected]
m_transformRecalculationNeeded | BaseElement | [protected]
m_translation | BaseElement | [protected]
PerformAction() override | Button | [virtual]
Render() | BaseElement | [protected, virtual]
SetBrush(ID2D1SolidColorBrush *brush) | BaseElement |
SetElementMargin(ElementMargin margin) | BaseElement | [inline]
SetElementSize(Windows::Foundation::Numerics::float2 size) | BaseElement | [inline]
SetIgnoreLayout(bool ignoreLayout) | BaseElement | [inline]
SetIsVisible(bool visible) | BaseElement |
SetLayoutHorizontal(bool isLayoutHorizontal) | BaseElement | [inline]
SetParentControlInformation(bool focused, Windows::Foundation::Numerics::float2 focusedPosition, UINT parentTextureWidth, UINT parentTextureHeight) | FocusableElement | [virtual]
SetParentTransform(Windows::Foundation::Numerics::float2 translation) | BaseElement |
SetTranslation(Windows::Foundation::Numerics::float2 translation) | BaseElement | [virtual]
TryRender() | BaseElement |
Update(const DX::StepTimer &timer, Windows::UI::Input::Spatial::SpatialPointerPose^cameraPose) override | Button | [virtual]
~BaseElement() | BaseElement | [virtual]
~FocusableElement() | FocusableElement | [virtual]
Generated on Fri Nov 15 2024 22:23:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7_SetVersion Member List

This is the complete list of members for Scenario7_SetVersion, including all inherited members.
appData | Scenario7_SetVersion | [private]
DisplayOutput() | Scenario7_SetVersion |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario7_SetVersion |
Scenario7_SetVersion() | Scenario7_SetVersion |
settingName | Scenario7_SetVersion | [inline, private, static]
settingValue0 | Scenario7_SetVersion | [inline, private, static]
settingValue1 | Scenario7_SetVersion | [inline, private, static]
SetVersion0_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario7_SetVersion |
SetVersion1_Click(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario7_SetVersion |
SetVersionHandler0(Windows::Storage::SetVersionRequest const &request) | Scenario7_SetVersion | [private]
SetVersionHandler1(Windows::Storage::SetVersionRequest const &request) | Scenario7_SetVersion | [private]
Generated on Fri Nov 15 2024 22:24:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Gyrometer/cpp/Scenario1_DataEvents.xaml.h Source File

  • Gyrometer
  • cpp

Scenario1_DataEvents.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_DataEvents.xaml.h
00014 // Declaration of the Scenario1_DataEvents class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario1_DataEvents.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     [Windows::Foundation::Metadata::WebHostHidden]
00029     public ref class Scenario1_DataEvents sealed
00030     {
00031     public:
00032         Scenario1_DataEvents();
00033
00034     protected:
00035         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00036         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00037
00038     private:
00039         SDKTemplate::MainPage^ rootPage;
00040         Windows::Devices::Sensors::Gyrometer^ gyrometer;
00041         Windows::Foundation::EventRegistrationToken visibilityToken;
00042         Windows::Foundation::EventRegistrationToken readingToken;
00043         uint32 desiredReportInterval;
00044
00045         void VisibilityChanged(Platform::Object^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ e);
00046         void ReadingChanged(Windows::Devices::Sensors::Gyrometer^ sender, Windows::Devices::Sensors::GyrometerReadingChangedEventArgs^ e);
00047         void ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00048         void ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00049     };
00050 }
Generated on Fri Nov 15 2024 22:17:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/pch.h Source File

  • BasicHologram
  • cpp

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <agile.h>
00004 #include <array>
00005 #include <d2d1_2.h>
00006 #include <d3d11_4.h>
00007 #include <DirectXColors.h>
00008 #include <dwrite_2.h>
00009 #include <map>
00010 #include <mutex>
00011 #include <vector>
00012 #include <wincodec.h>
00013 #include <WindowsNumerics.h>
00014
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/SampleConfiguration.cpp Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016 #include "DeviceHelpers.h"
00017
00018 using namespace winrt;
00019 using namespace winrt::SDKTemplate;
00020 using namespace winrt::Windows::Devices::Enumeration;
00021 using namespace winrt::Windows::Foundation;
00022 using namespace winrt::Windows::Foundation::Collections;
00023
00024 hstring implementation::MainPage::FEATURE_NAME()
00025 {
00026     return L"DeviceEnumeration C++/WinRT Sample";
00027 }
00028
00029 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>({
00030     Scenario{ L"Device Picker Common Control", xaml_typename<SDKTemplate::Scenario1_DevicePicker>() },
00031     Scenario{ L"Enumerate and Watch Devices", xaml_typename<SDKTemplate::Scenario2_DeviceWatcher>() },
00032     Scenario{ L"Enumerate and Watch Devices in a Background Task", xaml_typename<SDKTemplate::Scenario3_BackgroundDeviceWatcher>() },
00033     Scenario{ L"Enumerate Snapshot of Devices", xaml_typename<SDKTemplate::Scenario4_Snapshot>() },
00034     Scenario{ L"Get Single Device", xaml_typename<SDKTemplate::Scenario5_GetSingleDevice>() },
00035     Scenario{ L"Custom Filter with Additional Properties", xaml_typename<SDKTemplate::Scenario6_CustomFilterAddedProps>() },
00036     Scenario{ L"Request Specific DeviceInformationKind", xaml_typename<SDKTemplate::Scenario7_DeviceInformationKind>() },
00037     Scenario{ L"Basic Device Pairing", xaml_typename<SDKTemplate::Scenario8_PairDevice>() },
00038     Scenario{ L"Custom Device Pairing", xaml_typename<SDKTemplate::Scenario9_CustomPairDevice>() },
00039 });
00040
00041 hstring winrt::to_hstring(DevicePairingResultStatus status)
00042 {
00043     switch (status)
00044     {
00045     case DevicePairingResultStatus::Paired: return L"Paired";
00046     case DevicePairingResultStatus::NotReadyToPair: return L"NotReadyToPair";
00047     case DevicePairingResultStatus::NotPaired: return L"NotPaired";
00048     case DevicePairingResultStatus::AlreadyPaired: return L"AlreadyPaired";
00049     case DevicePairingResultStatus::ConnectionRejected: return L"ConnectionRejected";
00050     case DevicePairingResultStatus::TooManyConnections: return L"TooManyConnections";
00051     case DevicePairingResultStatus::HardwareFailure: return L"HardwareFailure";
00052     case DevicePairingResultStatus::AuthenticationTimeout: return L"AuthenticationTimeout";
00053     case DevicePairingResultStatus::AuthenticationNotAllowed: return L"AuthenticationNotAllowed";
00054     case DevicePairingResultStatus::AuthenticationFailure: return L"AuthenticationFailure";
00055     case DevicePairingResultStatus::NoSupportedProfiles: return L"NoSupportedProfiles";
00056     case DevicePairingResultStatus::ProtectionLevelCouldNotBeMet: return L"ProtectionLevelCouldNotBeMet";
00057     case DevicePairingResultStatus::AccessDenied: return L"AccessDenied";
00058     case DevicePairingResultStatus::InvalidCeremonyData: return L"InvalidCeremonyData";
00059     case DevicePairingResultStatus::PairingCanceled: return L"PairingCanceled";
00060     case DevicePairingResultStatus::OperationAlreadyInProgress: return L"OperationAlreadyInProgress";
00061     case DevicePairingResultStatus::RequiredHandlerNotRegistered: return L"RequiredHandlerNotRegistered";
00062     case DevicePairingResultStatus::RejectedByHandler: return L"RejectedByHandler";
00063     case DevicePairingResultStatus::RemoteDeviceHasAssociation: return L"RemoteDeviceHasAssociation";
00064     case DevicePairingResultStatus::Failed: return L"Failed";
00065     }
00066     return to_hstring(static_cast<uint32_t>(status));
00067 }
00068
00069 hstring winrt::to_hstring(DeviceUnpairingResultStatus status)
00070 {
00071     switch (status)
00072     {
00073     case DeviceUnpairingResultStatus::Unpaired: return L"Unpaired";
00074     case DeviceUnpairingResultStatus::AlreadyUnpaired: return L"AlreadyUnpaired";
00075     case DeviceUnpairingResultStatus::OperationAlreadyInProgress: return L"OperationAlreadyInProgress";
00076     case DeviceUnpairingResultStatus::AccessDenied: return L"AccessDenied";
00077     case DeviceUnpairingResultStatus::Failed: return L"Failed";
00078     }
00079     return to_hstring(static_cast<uint32_t>(status));
00080 }
00081
00082 hstring winrt::to_hstring(DeviceInformationKind kind)
00083 {
00084     switch (kind)
00085     {
00086     case DeviceInformationKind::Unknown: return L"Unknown";
00087     case DeviceInformationKind::DeviceInterface: return L"DeviceInterface";
00088     case DeviceInformationKind::DeviceContainer: return L"DeviceContainer";
00089     case DeviceInformationKind::Device: return L"Device";
00090     case DeviceInformationKind::DeviceInterfaceClass: return L"DeviceInterfaceClass";
00091     case DeviceInformationKind::AssociationEndpoint: return L"AssociationEndpoint";
00092     case DeviceInformationKind::AssociationEndpointContainer: return L"AssociationEndpointContainer";
00093     case DeviceInformationKind::AssociationEndpointService: return L"AssociationEndpointService";
00094     case DeviceInformationKind::DevicePanel: return L"DevicePanel";
00095     }
00096     return to_hstring(static_cast<uint32_t>(kind));
00097 }
Generated on Fri Nov 15 2024 22:17:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cpp/scenario3.xaml.cpp Source File

  • ApplicationResources
  • cpp

scenario3.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario3.xaml.cpp
00013 // Implementation of the Scenario3 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario3.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Navigation;
00024 using namespace Windows::ApplicationModel::Resources;
00025
00026 Scenario3::Scenario3()
00027 {
00028     InitializeComponent();
00029 }
00030
00031 /// <summary>
00032 /// Invoked when this page is about to be displayed in a Frame.
00033 /// </summary>
00034 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00035 /// property is typically used to configure the page.</param>
00036 void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
00037 {
00038     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00039     // as NotifyUser()
00040     rootPage = MainPage::Current;
00041 }
00042
00043
00044 void SDKTemplate::Scenario3::Scenario3Button_Show_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046     Button^ b = safe_cast<Button^>(sender);
00047     if (b != nullptr)
00048     {
00049         auto resourceLoader = ResourceLoader::GetForCurrentView();
00050         // Replace the TextBlock's content with a string resource, String1, for the most appropriate language
00051         // String1 can be found in a resource file strings/.../resources.resw
00052         Scenario3TextBlock->Text = resourceLoader->GetString("string1");
00053     }
00054 }
Generated on Fri Nov 15 2024 22:18:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cpp/SampleConfiguration.cpp Source File

  • WiFiDirectServices
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace Platform;
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace Windows::UI::Xaml::Interop;
00020 using namespace SDKTemplate;
00021
00022 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00023 {
00024     { "Create Advertiser", "SDKTemplate.WiFiDirectServices.Scenario1" },
00025     { "Advertiser Accept", "SDKTemplate.WiFiDirectServices.Scenario2" },
00026     { "Discover/Connect Services", "SDKTemplate.WiFiDirectServices.Scenario3" },
00027     { "Select Session (Seeker)", "SDKTemplate.WiFiDirectServices.Scenario4" },
00028     { "Send Data", "SDKTemplate.WiFiDirectServices.Scenario5" }
00029 };
00030
00031 void MainPage::GoToScenario(unsigned int index)
00032 {
00033     if (index >= scenariosInner->Length)
00034     {
00035         throw ref new OutOfBoundsException;
00036     }
00037
00038     ScenarioControl->SelectedIndex = index;
00039 }
Generated on Fri Nov 15 2024 22:17:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PersonalDataEncryption/cs/Scenario1_Files.xaml.cs Source File

  • PersonalDataEncryption
  • cs

Scenario1_Files.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Security.DataProtection;
00014 using Windows.Storage;
00015 using Windows.Storage.Pickers;
00016 using Windows.System.Update;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario1_Files : Page
00024     {
00025         private MainPage rootPage = MainPage.Current;
00026         UserDataProtectionManager userDataProtectionManager = null;
00027         IStorageItem selectedItem = null;
00028
00029         public Scenario1_Files()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         protected override void OnNavigatedTo(NavigationEventArgs e)
00035         {
00036             userDataProtectionManager = UserDataProtectionManager.TryGetDefault();
00037             if (userDataProtectionManager != null)
00038             {
00039                 AvailablePanel.Visibility = Visibility.Visible;
00040                 UnavailablePanel.Visibility = Visibility.Collapsed;
00041             }
00042             else
00043             {
00044                 AvailablePanel.Visibility = Visibility.Collapsed;
00045                 UnavailablePanel.Visibility = Visibility.Visible;
00046             }
00047         }
00048
00049         private async void ChooseFile_Click(object sender, RoutedEventArgs e)
00050         {
00051             var picker = new FileOpenPicker();
00052             picker.FileTypeFilter.Add("*");
00053             UpdateItem(await picker.PickSingleFileAsync());
00054         }
00055
00056         private async void ChooseFolder_Click(object sender, RoutedEventArgs e)
00057         {
00058             var picker = new FolderPicker();
00059             UpdateItem(await picker.PickSingleFolderAsync());
00060         }
00061
00062         private void UpdateItem(IStorageItem item)
00063         {
00064             selectedItem = item;
00065             if (selectedItem != null)
00066             {
00067                 ItemOperationsPanel.Visibility = Visibility.Visible;
00068                 ItemNameBlock.Text = item.Path;
00069             }
00070             else
00071             {
00072                 ItemOperationsPanel.Visibility = Visibility.Collapsed;
00073             }
00074         }
00075
00076         private async void ProtectL1_Click(object sender, RoutedEventArgs e)
00077         {
00078             UserDataStorageItemProtectionStatus status = await userDataProtectionManager.ProtectStorageItemAsync(selectedItem, UserDataAvailability.AfterFirstUnlock);
00079             ReportStatus("Protect L1", status);
00080         }
00081
00082         private async void ProtectL2_Click(object sender, RoutedEventArgs e)
00083         {
00084             UserDataStorageItemProtectionStatus status = await userDataProtectionManager.ProtectStorageItemAsync(selectedItem, UserDataAvailability.WhileUnlocked);
00085             ReportStatus("Protect L2", status);
00086         }
00087
00088         private async void Unprotect_Click(object sender, RoutedEventArgs e)
00089         {
00090             UserDataStorageItemProtectionStatus status = await userDataProtectionManager.ProtectStorageItemAsync(selectedItem, UserDataAvailability.Always);
00091             ReportStatus("Unprotect", status);
00092         }
00093
00094         private void ReportStatus(string operation, UserDataStorageItemProtectionStatus status)
00095         {
00096             switch (status)
00097             {
00098                 case UserDataStorageItemProtectionStatus.Succeeded:
00099                     rootPage.NotifyUser(operation + " succeeded", NotifyType.StatusMessage);
00100                     break;
00101
00102                 case UserDataStorageItemProtectionStatus.NotProtectable:
00103                     rootPage.NotifyUser(operation + " failed: Not protectable", NotifyType.ErrorMessage);
00104                     break;
00105
00106                 case UserDataStorageItemProtectionStatus.DataUnavailable:
00107                     rootPage.NotifyUser(operation + " failed: Data unavailable", NotifyType.ErrorMessage);
00108                     break;
00109
00110                 default:
00111                     rootPage.NotifyUser(operation + " failed: Unknown failure", NotifyType.ErrorMessage);
00112                     break;
00113             }
00114         }
00115     }
00116 }
Generated on Fri Nov 15 2024 22:17:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/AppView.h Source File

  • HolographicFaceTracking
  • cpp

AppView.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015 #include "HolographicFaceTrackerMain.h"
00016
00017 namespace HolographicFaceTracker
00018 {
00019     // IFrameworkView class. Connects the app with the Windows shell and handles application lifecycle events.
00020     ref class AppView sealed : public Windows::ApplicationModel::Core::IFrameworkView
00021     {
00022     public:
00023         AppView();
00024
00025         // IFrameworkView methods.
00026         virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
00027         virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
00028         virtual void Load(Platform::String^ entryPoint);
00029         virtual void Run();
00030         virtual void Uninitialize();
00031
00032     protected:
00033         // Application lifecycle event handlers.
00034         void OnViewActivated(Windows::ApplicationModel::Core::CoreApplicationView^ sender, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
00035         void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
00036         void OnResuming(Platform::Object^ sender, Platform::Object^ args);
00037
00038         // Window event handlers.
00039         void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
00040         void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
00041
00042         // CoreWindow input event handlers.
00043         void OnKeyPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args);
00044
00045     private:
00046         std::unique_ptr<HolographicFaceTrackerMain> m_main;
00047
00048         std::shared_ptr<DX::DeviceResources>                m_deviceResources;
00049         bool                                                m_windowClosed  = false;
00050         bool                                                m_windowVisible = true;
00051
00052         // The holographic space the app will use for rendering.
00053         Windows::Graphics::Holographic::HolographicSpace^   m_holographicSpace = nullptr;
00054     };
00055
00056     // The entry point for the app.
00057     ref class AppViewSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
00058     {
00059     public:
00060         virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
00061     };
00062 }
00063
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ExtendedExecution/cs/SampleConfiguration.cs Source File

  • ExtendedExecution
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.ApplicationModel.Background;
00015 using Windows.Data.Xml.Dom;
00016 using Windows.UI.Notifications;
00017 using Windows.UI.Xaml.Controls;
00018
00019
00020 namespace SDKTemplate
00021 {
00022     public partial class MainPage : Page
00023     {
00024         public const string FEATURE_NAME = "Extended Execution";
00025
00026         List<Scenario> scenarios = new List<Scenario>
00027         {
00028             new Scenario() { Title="Unspecified Reason", ClassType=typeof(UnspecifiedReason)},
00029             new Scenario() { Title="Saving Data Reason", ClassType=typeof(SavingDataReason)},
00030             new Scenario() { Title="Location Tracking Reason", ClassType=typeof(LocationTrackingReason)},
00031             new Scenario() { Title="Using Multiple Tasks", ClassType=typeof(MultipleTasks)},
00032         };
00033
00034         public static ToastNotification DisplayToast(string content)
00035         {
00036             string xml = $@"<toast activationType='foreground'>
00037                                             <visual>
00038                                                 <binding template='ToastGeneric'>
00039                                                     <text>Extended Execution</text>
00040                                                 </binding>
00041                                             </visual>
00042                                         </toast>";
00043
00044             XmlDocument doc = new XmlDocument();
00045             doc.LoadXml(xml);
00046
00047             var binding = doc.SelectSingleNode("//binding");
00048
00049             var el = doc.CreateElement("text");
00050             el.InnerText = content;
00051             binding.AppendChild(el); //Add content to notification
00052
00053             var toast = new ToastNotification(doc);
00054
00055             ToastNotificationManager.CreateToastNotifier().Show(toast); //Show the toast
00056
00057             return toast;
00058         }
00059     }
00060
00061     public class Scenario
00062     {
00063         public string Title { get; set; }
00064         public Type ClassType { get; set; }
00065     }
00066 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MultipleViews/cppwinrt/Scenario3.cpp Source File

  • MultipleViews
  • cppwinrt

Scenario3.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3.h"
00014 #include "Scenario3.g.cpp"
00015 #include "SampleConfiguration.h"
00016 #include "SecondaryViewPage.h"
00017
00018 using namespace winrt;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::UI::Core;
00021 using namespace Windows::UI::ViewManagement;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Media::Animation;
00025 using namespace Windows::UI::Xaml::Navigation;
00026 using namespace std::chrono_literals;
00027
00028 namespace
00029 {
00030     handle duplicate(handle const& other)
00031     {
00032         handle result;
00033         if (other)
00034         {
00035             check_bool(DuplicateHandle(GetCurrentProcess(), other.get(), GetCurrentProcess(), result.put(), 0, FALSE, DUPLICATE_SAME_ACCESS));
00036         }
00037         return result;
00038     }
00039 }
00040
00041 namespace winrt::SDKTemplate::implementation
00042 {
00043     Scenario3::Scenario3()
00044     {
00045         InitializeComponent();
00046
00047         ViewChooser().ItemsSource(SampleState::SecondaryViews);
00048
00049         FadeOutThemeAnimation fadeOut;
00050         fadeOutStoryboard.Children().Append(fadeOut);
00051
00052         // Normally you can point directly to an object named in your XAML. Since
00053         // the sample hosts multiple pages, it's convenient for this scenario to
00054         // get the root element
00055         Storyboard::SetTarget(fadeOut, rootPage.Content().as<FrameworkElement>().FindName(L"Splitter").as<DependencyObject>());
00056     }
00057
00058     void Scenario3::CompleteCurrentAnimation()
00059     {
00060         // Must be called from the UI thread to avoid race conditions.
00061         if (animationCompleteEvent)
00062         {
00063             SetEvent(animationCompleteEvent.get());
00064             animationCompleteEvent.close();
00065         }
00066     }
00067
00068     void Scenario3::Fade_Completed(IInspectable const&, IInspectable const&)
00069     {
00070         // This event always fires on the UI thread, along with Current_VisibilityChanged.
00071         CompleteCurrentAnimation();
00072     }
00073
00074     void Scenario3::StartFadeOutContents()
00075     {
00076         CompleteCurrentAnimation();
00077         animationCompleteEvent.attach(CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_MODIFY_STATE | SYNCHRONIZE));
00078         check_bool(static_cast<bool>(animationCompleteEvent));
00079
00080         fadeOutStoryboard.Begin();
00081     }
00082
00083     void Scenario3::OnNavigatedTo(NavigationEventArgs const&)
00084     {
00085         visibilityToken = Window::Current().VisibilityChanged({ this, &Scenario3::Current_VisibilityChanged });
00086         fadeOutToken = fadeOutStoryboard.Completed({ this, &Scenario3::Fade_Completed });
00087     }
00088
00089     void Scenario3::OnNavigatedFrom(NavigationEventArgs const&)
00090     {
00091         Window::Current().VisibilityChanged(visibilityToken);
00092         fadeOutStoryboard.Completed(fadeOutToken);
00093     }
00094
00095     void Scenario3::Current_VisibilityChanged(IInspectable const&, VisibilityChangedEventArgs const& e)
00096     {
00097         auto now = clock::now();
00098         // Timeout the animation if the secondary window fails to respond in 500
00099         // ms. Since this animation clears out the main view of the app, it's not desirable
00100         // to leave it unusable
00101         if (e.Visible() || (now - lastFadeOutTime) > 500ms)
00102         {
00103             // This event always fires on the UI thread, along with Fade_Completed.
00104             CompleteCurrentAnimation();
00105             fadeOutStoryboard.Stop();
00106         }
00107     }
00108
00109     fire_and_forget Scenario3::AnimatedSwitch_Click(IInspectable const&, RoutedEventArgs const&)
00110     {
00111         auto lifetime = get_strong();
00112
00113         // The sample demonstrates a general strategy for doing custom animations when switching view
00114         // It's technically only possible to animate the contents of a particular view. But, it is possible
00115         // to animate the outgoing view to some common visual (like a blank background), have the incoming
00116         // view draw that same visual, switch in the incoming window (which will be imperceptible to the
00117         // user since both windows will be showing the same thing), then animate the contents of the incoming
00118         // view in from the common visual.
00119         auto selectedItem = ViewChooser().SelectedItem().as<ViewLifetimeControl>();
00120         if (selectedItem == nullptr)
00121         {
00122             rootPage.NotifyUser(L"Select a window to see a switch animation. You can create a window in scenario 1", NotifyType::ErrorMessage);
00123             co_return;
00124         }
00125
00126         try
00127         {
00128             // Prevent the view from being closed while switching to it
00129             selectedItem.StartViewInUse();
00130
00131             // Signal that the window is about to be switched to
00132             // If the view is already shown to the user, then the app
00133             // shouldn't run any extra animations
00134             auto currentId = ApplicationView::GetForCurrentView().Id();
00135
00136             bool useFallback = false;
00137             bool isViewVisible = false;
00138             try
00139             {
00140                 isViewVisible = co_await ApplicationViewSwitcher::PrepareForCustomAnimatedSwitchAsync(
00141                     selectedItem.Id(),
00142                     currentId,
00143                     ApplicationViewSwitchingOptions::SkipAnimation);
00144             }
00145             catch (hresult_not_implemented&)
00146             {
00147                 // The device family does not support PrepareForCustomAnimatedSwitchAsync.
00148                 // Fall back to switching with standard animation.
00149                 useFallback = true;
00150             }
00151
00152             if (useFallback)
00153             {
00154                 isViewVisible = true;
00155                 co_await ApplicationViewSwitcher::SwitchAsync(selectedItem.Id(), currentId);
00156             }
00157
00158             // The view may already be on screen, in which case there's no need to animate its
00159             // contents (or animate out the contents of the current window).
00160             if (!isViewVisible)
00161             {
00162                 // The view isn't visible, so animate it on screen
00163                 lastFadeOutTime = clock::now();
00164
00165                 // Make the current window totally blank. The incoming window is
00166                 // going to be totally blank as well when the two windows switch,
00167                 StartFadeOutContents();
00168
00169                 // Wait for the animation to complete. Make a duplicate of animationCompleteEvent
00170                 // because it will be closed when the animation completes.
00171                 handle localEvent = duplicate(animationCompleteEvent);
00172                 co_await resume_on_signal(localEvent.get());
00173
00174                 // Once the current view is blank, switch in the other window
00175                 co_await resume_foreground(selectedItem.Dispatcher());
00176
00177                 // We are now in the switched-to window.
00178
00179                 // More details are in SecondaryViewPage.cpp
00180                 // This function makes the view totally blank, swaps the two view (which
00181                 // is not apparent to the user since both windows are blank), then animates
00182                 // in the content of newly visible view
00183                 auto currentPage = Window::Current().Content().as<Controls::Frame>().Content().as<SDKTemplate::SecondaryViewPage>();
00184                 currentPage.SwitchAndAnimate(currentId);
00185
00186                 selectedItem.StopViewInUse();
00187             }
00188         }
00189         catch (hresult_error& ex)
00190         {
00191             if (ex.to_abi() == RO_E_CLOSED)
00192             {
00193                 // The view could be in the process of closing, and
00194                 // this thread just hasn't updated. As part of being closed,
00195                 // this thread will be informed to clean up its list of
00196                 // views (see SecondaryViewPage.cpp)
00197             }
00198             else
00199             {
00200                 throw;
00201             }
00202         }
00203     }
00204 }
Generated on Fri Nov 15 2024 22:19:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RadialController/cpp/Scenario1_EventAndMenuHookup.xaml.cpp Source File

  • RadialController
  • cpp

Scenario1_EventAndMenuHookup.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_EventAndMenuHookup.xaml.h"
00013 #include <string>
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Primitives;
00023 using namespace Windows::UI::Xaml::Data;
00024 using namespace Windows::UI::Xaml::Input;
00025 using namespace Windows::UI::Xaml::Media;
00026 using namespace Windows::UI::Xaml::Navigation;
00027 using namespace Windows::UI::Input;
00028 using namespace Windows::Storage::Streams;
00029 using std::vector;
00030
00031 Scenario1_EventAndMenuHookup::Scenario1_EventAndMenuHookup()
00032 {
00033     InitializeComponent();
00034
00035     InitializeController();
00036     CreateMenuItems();
00037 }
00038
00039 void Scenario1_EventAndMenuHookup::OnNavigatedFrom(NavigationEventArgs^ e)
00040 {
00041     if (controller != nullptr)
00042     {
00043         controller->Menu->Items->Clear();
00044     }
00045 }
00046
00047 void Scenario1_EventAndMenuHookup::InitializeController()
00048 {
00049     controller = RadialController::CreateForCurrentView();
00050     controller->RotationResolutionInDegrees = 1;
00051
00052     // Wire events
00053     controller->RotationChanged += ref new TypedEventHandler<RadialController^, RadialControllerRotationChangedEventArgs^>(this, &Scenario1_EventAndMenuHookup::OnRotationChanged);
00054     controller->ButtonClicked += ref new TypedEventHandler<RadialController^, RadialControllerButtonClickedEventArgs^>(this, &Scenario1_EventAndMenuHookup::OnButtonClicked);
00055     controller->ScreenContactStarted += ref new TypedEventHandler<RadialController^, RadialControllerScreenContactStartedEventArgs^>(this, &Scenario1_EventAndMenuHookup::OnScreenContactStarted);
00056     controller->ScreenContactContinued += ref new TypedEventHandler<RadialController^, RadialControllerScreenContactContinuedEventArgs^>(this, &Scenario1_EventAndMenuHookup::OnScreenContactContinued);
00057     controller->ScreenContactEnded += ref new TypedEventHandler<RadialController^, Object^>(this, &Scenario1_EventAndMenuHookup::OnScreenContactEnded);
00058     controller->ControlAcquired += ref new TypedEventHandler<RadialController^, RadialControllerControlAcquiredEventArgs^>(this, &Scenario1_EventAndMenuHookup::OnControlAcquired);
00059     controller->ControlLost += ref new TypedEventHandler<RadialController^, Object^>(this, &Scenario1_EventAndMenuHookup::OnControlLost);
00060 }
00061
00062 void Scenario1_EventAndMenuHookup::CreateMenuItems()
00063 {
00064     AddKnownIconItems();
00065     AddCustomIconItems();
00066     AddFontGlyphItems();
00067
00068     // Set the invoked callbacks for each menu item
00069     for (unsigned int i = 0; i < menuItems.size(); ++i)
00070     {
00071         RadialControllerMenuItem^ radialControllerItem = menuItems[i];
00072         SetItemInvokedCallback(radialControllerItem, i);
00073     }
00074 }
00075
00076 void Scenario1_EventAndMenuHookup::AddKnownIconItems()
00077 {
00078     menuItems.push_back(RadialControllerMenuItem::CreateFromKnownIcon("Item 0", RadialControllerMenuKnownIcon::InkColor));
00079     sliders.push_back(slider0);
00080     toggles.push_back(toggle0);
00081
00082     menuItems.push_back(RadialControllerMenuItem::CreateFromKnownIcon("Item 1", RadialControllerMenuKnownIcon::NextPreviousTrack));
00083     sliders.push_back(slider1);
00084     toggles.push_back(toggle1);
00085 }
00086
00087 void Scenario1_EventAndMenuHookup::AddCustomIconItems()
00088 {
00089     menuItems.push_back(RadialControllerMenuItem::CreateFromIcon(L"Item 2", RandomAccessStreamReference::CreateFromUri(ref new Uri(L"ms-appx:///Assets/Item2.png"))));
00090     sliders.push_back(slider2);
00091     toggles.push_back(toggle2);
00092
00093     menuItems.push_back(RadialControllerMenuItem::CreateFromIcon(L"Item 3", RandomAccessStreamReference::CreateFromUri(ref new Uri(L"ms-appx:///Assets/Item3.png"))));
00094     sliders.push_back(slider3);
00095     toggles.push_back(toggle3);
00096 }
00097
00098 void Scenario1_EventAndMenuHookup::AddFontGlyphItems()
00099 {
00100     menuItems.push_back(RadialControllerMenuItem::CreateFromFontGlyph(L"Item 4", L"\x2764", L"Segoe UI Emoji"));
00101     sliders.push_back(slider4);
00102     toggles.push_back(toggle4);
00103
00104     menuItems.push_back(RadialControllerMenuItem::CreateFromFontGlyph(L"Item 5", L"\ue102", L"Symbols", ref new Uri(L"ms-appx:///Assets/Symbols.ttf")));
00105     sliders.push_back(slider5);
00106     toggles.push_back(toggle5);
00107 }
00108
00109 void Scenario1_EventAndMenuHookup::SetItemInvokedCallback(RadialControllerMenuItem^ menuItem, unsigned int index)
00110 {
00111     // Register Invoked callback to set active item index
00112     auto weakThis = WeakReference(this);
00113     menuItem->Invoked += ref new TypedEventHandler<RadialControllerMenuItem^, Object^>(
00114         [weakThis, index](RadialControllerMenuItem^ sender, Object^ args)
00115     {
00116         auto strongThis = weakThis.Resolve<Scenario1_EventAndMenuHookup>();
00117         if (strongThis)
00118         {
00119             strongThis->OnItemInvoked(index);
00120         }
00121     });
00122 }
00123
00124 void Scenario1_EventAndMenuHookup::OnItemInvoked(unsigned int selectedItemIndex)
00125 {
00126     activeItemIndex = selectedItemIndex;
00127 }
00128
00129 void Scenario1_EventAndMenuHookup::AddItem(Object^ sender, RoutedEventArgs^ args)
00130 {
00131     RadialControllerMenuItem^ radialControllerMenuItem = GetRadialControllerMenuItemFromSender(sender);
00132
00133     if (!IsItemInMenu(radialControllerMenuItem))
00134     {
00135         controller->Menu->Items->Append(radialControllerMenuItem);
00136         log->Text += "\n Added : " + radialControllerMenuItem->DisplayText;
00137     }
00138 }
00139
00140 void Scenario1_EventAndMenuHookup::RemoveItem(Object^ sender, RoutedEventArgs^ args)
00141 {
00142     RadialControllerMenuItem^ radialControllerMenuItem = GetRadialControllerMenuItemFromSender(sender);
00143
00144     if (IsItemInMenu(radialControllerMenuItem))
00145     {
00146         unsigned int index = GetItemIndex(radialControllerMenuItem);
00147         controller->Menu->Items->RemoveAt(index);
00148         log->Text += "\n Removed : " + radialControllerMenuItem->DisplayText;
00149     }
00150 }
00151
00152 void Scenario1_EventAndMenuHookup::SelectItem(Object^ sender, RoutedEventArgs^ args)
00153 {
00154     RadialControllerMenuItem^ radialControllerMenuItem = GetRadialControllerMenuItemFromSender(sender);
00155
00156     if (IsItemInMenu(radialControllerMenuItem))
00157     {
00158         controller->Menu->SelectMenuItem(radialControllerMenuItem);
00159         PrintSelectedItem();
00160     }
00161 }
00162
00163 void Scenario1_EventAndMenuHookup::SelectPreviouslySelectedItem(Object^ sender, RoutedEventArgs^ args)
00164 {
00165     controller->Menu->TrySelectPreviouslySelectedMenuItem();
00166     PrintSelectedItem();
00167 }
00168
00169 unsigned int Scenario1_EventAndMenuHookup::GetItemIndex(RadialControllerMenuItem^ item)
00170 {
00171     unsigned int index = 0;
00172     controller->Menu->Items->IndexOf(item, &index);
00173
00174     return index;
00175 }
00176
00177 bool Scenario1_EventAndMenuHookup::IsItemInMenu(RadialControllerMenuItem^ item)
00178 {
00179     unsigned int index = 0;
00180     return controller->Menu->Items->IndexOf(item, &index);
00181 }
00182
00183
00184 RadialControllerMenuItem^ Scenario1_EventAndMenuHookup::GetRadialControllerMenuItemFromSender(Object^ sender)
00185 {
00186     Button^ button = safe_cast<Button^>(sender);
00187     String^ indexString = button->CommandParameter->ToString();
00188     int index = std::stoi(indexString->Data());
00189
00190     return menuItems[index];
00191 }
00192
00193 void Scenario1_EventAndMenuHookup::PrintSelectedItem(Object^ sender, RoutedEventArgs^ args)
00194 {
00195     PrintSelectedItem();
00196 }
00197
00198 void Scenario1_EventAndMenuHookup::PrintSelectedItem()
00199 {
00200     RadialControllerMenuItem^ selectedMenuItem = controller->Menu->GetSelectedMenuItem();
00201     String^ itemName = nullptr;
00202
00203     if (selectedMenuItem)
00204     {
00205         itemName = selectedMenuItem->DisplayText;
00206     }
00207     else if (selectedMenuItem == nullptr)
00208     {
00209         itemName = L"System Item";
00210     }
00211
00212     if (itemName != nullptr)
00213     {
00214         log->Text += "\n Selected : " + itemName;
00215     }
00216 }
00217
00218 void Scenario1_EventAndMenuHookup::OnLogSizeChanged(Object^ sender, Object^ args)
00219 {
00220     logViewer->ChangeView(nullptr, logViewer->ExtentHeight, nullptr);
00221 }
00222
00223 void Scenario1_EventAndMenuHookup::OnControlAcquired(RadialController^ sender, RadialControllerControlAcquiredEventArgs^ args)
00224 {
00225     log->Text += "\n Control Acquired";
00226     LogContactInfo(args->Contact);
00227 }
00228
00229 void Scenario1_EventAndMenuHookup::OnControlLost(RadialController^ sender, Object^ args)
00230 {
00231     log->Text += "\n Control Lost";
00232 }
00233
00234 void Scenario1_EventAndMenuHookup::OnScreenContactStarted(RadialController^ sender, RadialControllerScreenContactStartedEventArgs^ args)
00235 {
00236     log->Text += "\n Contact Started ";
00237     LogContactInfo(args->Contact);
00238 }
00239
00240 void Scenario1_EventAndMenuHookup::OnScreenContactContinued(RadialController^ sender, RadialControllerScreenContactContinuedEventArgs^ args)
00241 {
00242     log->Text += "\n Contact Continued ";
00243     LogContactInfo(args->Contact);
00244 }
00245
00246 void Scenario1_EventAndMenuHookup::OnScreenContactEnded(RadialController^ sender, Object^ args)
00247 {
00248     log->Text += "\n Contact Ended";
00249 }
00250
00251 void Scenario1_EventAndMenuHookup::ToggleMenuSuppression(Object^ sender, RoutedEventArgs^ args)
00252 {
00253     RadialControllerConfiguration^ radialControllerConfig = RadialControllerConfiguration::GetForCurrentView();
00254
00255     if (MenuSuppressionToggleSwitch->IsOn)
00256     {
00257         radialControllerConfig->ActiveControllerWhenMenuIsSuppressed = controller;
00258     }
00259
00260     radialControllerConfig->IsMenuSuppressed = MenuSuppressionToggleSwitch->IsOn;
00261 }
00262
00263 void Scenario1_EventAndMenuHookup::OnButtonClicked(RadialController^ sender, RadialControllerButtonClickedEventArgs^ args)
00264 {
00265     log->Text += "\n Button Clicked ";
00266     LogContactInfo(args->Contact);
00267
00268     ToggleSwitch^ toggle = toggles[activeItemIndex];
00269     toggle->IsOn = !toggle->IsOn;
00270 }
00271
00272 void Scenario1_EventAndMenuHookup::OnRotationChanged(RadialController^ sender, RadialControllerRotationChangedEventArgs^ args)
00273 {
00274     log->Text += "\n Rotation Changed Delta = " + args->RotationDeltaInDegrees;
00275     LogContactInfo(args->Contact);
00276
00277     sliders[activeItemIndex]->Value += args->RotationDeltaInDegrees;
00278 }
00279
00280 void Scenario1_EventAndMenuHookup::LogContactInfo(RadialControllerScreenContact^ contact)
00281 {
00282     if (contact != nullptr)
00283     {
00284         log->Text += "\n Bounds = " + contact->Bounds.ToString();
00285         log->Text += "\n Position = " + contact->Position.ToString();
00286     }
00287 }
Generated on Fri Nov 15 2024 22:21:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SingleAccountScenario Member List

This is the complete list of members for SingleAccountScenario, including all inherited members.
AddLinksAndDescription(AccountsSettingsPaneCommandsRequestedEventArgs e) | SingleAccountScenario | [inline, private]
AddWebAccountProvidersToPane(AccountsSettingsPaneCommandsRequestedEventArgs e) | SingleAccountScenario | [inline, private]
AddWebAccountToPane(AccountsSettingsPaneCommandsRequestedEventArgs e) | SingleAccountScenario | [inline, private]
AppSpecificProviderId | SingleAccountScenario | [private]
AppSpecificProviderName | SingleAccountScenario | [private]
AuthenticateWithRequestToken(WebAccountProvider Provider, String Scope, String ClientID) | SingleAccountScenario | [inline]
AzureActiveDirectoryAuthority | SingleAccountScenario | [private]
AzureActiveDirectoryClientId | SingleAccountScenario | [private]
AzureActiveDirectoryScopeRequested | SingleAccountScenario | [private]
Button_Reset(object sender, RoutedEventArgs e) | SingleAccountScenario | [inline, private]
Button_ShowAccountSettings(object sender, RoutedEventArgs e) | SingleAccountScenario | [inline, private]
GetProvider(string ProviderID, string AuthorityId="") | SingleAccountScenario | [inline, private]
GetWebAccount() | SingleAccountScenario | [inline, private]
HasAccountStored() | SingleAccountScenario | [inline, private]
LogoffAndRemoveAccount() | SingleAccountScenario | [inline, private]
MicrosoftAccountAuthority | SingleAccountScenario | [private]
MicrosoftAccountClientId | SingleAccountScenario | [private]
MicrosoftAccountScopeRequested | SingleAccountScenario | [private]
MicrosoftProviderId | SingleAccountScenario | [private]
OnAccountCommandsRequested(AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs e) | SingleAccountScenario | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | SingleAccountScenario | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | SingleAccountScenario | [inline, protected]
OtherLinkInvoked(IUICommand command) | SingleAccountScenario | [inline, private]
OutputTokenResult(WebTokenRequestResult result) | SingleAccountScenario | [inline]
PrivacyPolicyInvoked(IUICommand command) | SingleAccountScenario | [inline, private]
RemoveAccountData() | SingleAccountScenario | [inline, private]
rootPage | SingleAccountScenario | [private]
SingleAccountScenario() | SingleAccountScenario | [inline]
StoredAccountIdKey | SingleAccountScenario | [private]
StoredAuthorityKey | SingleAccountScenario | [private]
StoredProviderIdKey | SingleAccountScenario | [private]
StoreNewAccountDataLocally(WebAccount account) | SingleAccountScenario | [inline]
WebAccountInvoked(WebAccountCommand command, WebAccountInvokedArgs args) | SingleAccountScenario | [inline, private]
WebAccountProviderCommandInvoked(WebAccountProviderCommand command) | SingleAccountScenario | [inline, private]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GpuCoordinateMapper::VisualizeFrameBlob Member List

This is the complete list of members for GpuCoordinateMapper::VisualizeFrameBlob, including all inherited members.
renderTarget | GpuCoordinateMapper::VisualizeFrameBlob
renderTargetDepthBuffer | GpuCoordinateMapper::VisualizeFrameBlob
targetImage | GpuCoordinateMapper::VisualizeFrameBlob
targetImageDepthBuffer | GpuCoordinateMapper::VisualizeFrameBlob
viewport | GpuCoordinateMapper::VisualizeFrameBlob
viewToProj | GpuCoordinateMapper::VisualizeFrameBlob
worldToView | GpuCoordinateMapper::VisualizeFrameBlob
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Unicode/cppwinrt/pch.h Source File

  • Unicode
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.System.h"
00008 #include "winrt/Windows.UI.Core.h"
00009 #include "winrt/Windows.Data.Text.h"
00010 #include "winrt/Windows.UI.Xaml.h"
00011 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00012 #include "winrt/Windows.UI.Xaml.Controls.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00014 #include "winrt/Windows.UI.Xaml.Documents.h"
00015 #include "winrt/Windows.UI.Xaml.Interop.h"
00016 #include "winrt/Windows.UI.Xaml.Markup.h"
00017 #include "winrt/Windows.UI.Xaml.Media.h"
00018 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cs/scenario10.xaml.cs Source File

  • ApplicationResources
  • cs

scenario10.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using SDKTemplate;
00015 using System;
00016 using Windows.ApplicationModel.Resources.Core;
00017 using System.Collections.Generic;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class Scenario10 : Page
00025     {
00026         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00027         // as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         public Scenario10()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         /// <summary>
00036         /// Invoked when this page is about to be displayed in a Frame.
00037         /// </summary>
00038         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00039         /// property is typically used to configure the page.</param>
00040         protected override void OnNavigatedTo(NavigationEventArgs e)
00041         {
00042         }
00043
00044         /// <summary>
00045         /// This is the click handler for the 'Scenario10Button_Show' button.  You would replace this with your own handler
00046         /// if you have a button or buttons on this page.
00047         /// </summary>
00048         /// <param name="sender"></param>
00049         /// <param name="e"></param>
00050         private void Scenario10Button_Show_Click(object sender, RoutedEventArgs e)
00051         {
00052             Button b = sender as Button;
00053             if (b != null)
00054             {
00055                 // use a cloned context for this scenario so that qualifier values set
00056                 // in this scenario don't impact behaviour in other scenarios that
00057                 // use a default context for the view (crossover effects between
00058                 // the scenarios will not be expected)
00059                 var context = ResourceContext.GetForCurrentView().Clone();
00060
00061                 var selectedLanguage = Scenario10ComboBox_Language.SelectedValue;
00062                 var selectedScale = Scenario10ComboBox_Scale.SelectedValue;
00063                 var selectedContrast = Scenario10ComboBox_Contrast.SelectedValue;
00064                 var selectedHomeRegion = Scenario10ComboBox_HomeRegion.SelectedValue;
00065
00066                 if (selectedLanguage != null)
00067                 {
00068                     context.QualifierValues["language"] = selectedLanguage.ToString();
00069                 }
00070                 if (selectedScale != null)
00071                 {
00072                     context.QualifierValues["scale"] = selectedScale.ToString();
00073                 }
00074                 if (selectedContrast != null)
00075                 {
00076                     context.QualifierValues["contrast"] = selectedContrast.ToString();
00077                 }
00078                 if (selectedHomeRegion != null)
00079                 {
00080                     context.QualifierValues["homeregion"] = selectedHomeRegion.ToString();
00081                 }
00082
00083                 Scenario10_SearchMultipleResourceIds(context, new string[] { "LanguageOnly", "ScaleOnly", "ContrastOnly", "HomeRegionOnly", "MultiDimensional" });
00084             }
00085         }
00086
00087         void Scenario10_SearchMultipleResourceIds(ResourceContext context, string[] resourceIds)
00088         {
00089             this.Scenario10TextBlock.Text = "";
00090             var dimensionMap = ResourceManager.Current.MainResourceMap.GetSubtree("dimensions");
00091
00092             foreach (var id in resourceIds)
00093             {
00094                 NamedResource namedResource;
00095                 if (dimensionMap.TryGetValue(id, out namedResource))
00096                 {
00097                     var resourceCandidates = namedResource.ResolveAll(context);
00098                     Scenario10_ShowCandidates(id, resourceCandidates);
00099                 }
00100             }
00101         }
00102
00103         void Scenario10_ShowCandidates(string resourceId, IReadOnlyList<ResourceCandidate> resourceCandidates)
00104         {
00105             // print 'resourceId', 'found value', 'qualifer info', 'matching condition'
00106             string outText = "resourceId: dimensions\\" + resourceId + "\r\n";
00107             int i = 0;
00108             foreach (var candidate in resourceCandidates)
00109             {
00110                 var value = candidate.ValueAsString;
00111                 outText += "    Candidate " + i.ToString() + ":" + value + "\r\n";
00112                 int j = 0;
00113                 foreach (var qualifier in candidate.Qualifiers)
00114                 {
00115                     var qualifierName = qualifier.QualifierName;
00116                     var qualifierValue = qualifier.QualifierValue;
00117                     outText += "        Qualifer: " + qualifierName + ": " + qualifierValue + "\r\n";
00118                     outText += "        Matching: IsMatch (" + qualifier.IsMatch.ToString() + ")  " + "IsDefault (" + qualifier.IsDefault.ToString() + ")" + "\r\n";
00119                     j++;
00120                 }
00121                 i++;
00122             }
00123
00124             this.Scenario10TextBlock.Text += outText + "\r\n";
00125
00126         }
00127
00128     }
00129 }
00130
Generated on Fri Nov 15 2024 22:18:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Level3.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Level3.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Level3.h"
00014 #include "Face.h"
00015 #include "Animate.h"
00016
00017 using namespace DirectX;
00018
00019 Level3::Level3()
00020 {
00021     m_timeLimit = 30.0f;
00022     m_objective = L"Hit each of the moving targets before time runs out.";
00023 }
00024
00025 void Level3::Initialize(std::vector<std::shared_ptr<GameObject>> const& objects)
00026 {
00027     static constexpr XMFLOAT3 position[] =
00028     {
00029         XMFLOAT3(-2.5f, -1.0f, -1.5f),
00030         XMFLOAT3(-1.0f,  1.0f, -3.0f),
00031         XMFLOAT3(1.5f,  0.0f, -5.5f),
00032         XMFLOAT3(-2.5f, -1.0f, -5.5f),
00033         XMFLOAT3(0.5f, -2.0f, -5.0f),
00034         XMFLOAT3(1.5f, -2.0f, -5.5f),
00035         XMFLOAT3(0.0f, -3.6f,  0.0f),
00036         XMFLOAT3(0.0f, -3.6f,  0.0f),
00037         XMFLOAT3(0.0f, -3.6f,  0.0f)
00038     };
00039     static constexpr XMFLOAT3 LineList1[] =
00040     {
00041         XMFLOAT3(-2.5f, -1.0f, -1.5f),
00042         XMFLOAT3(-0.5f,  1.0f,  1.0f),
00043         XMFLOAT3(-0.5f, -2.5f,  1.0f),
00044         XMFLOAT3(-2.5f, -1.0f, -1.5f),
00045     };
00046     static constexpr XMFLOAT3 LineList2[] =
00047     {
00048         XMFLOAT3(-1.0f,  1.0f, -3.0f),
00049         XMFLOAT3(-2.0f,  2.0f, -1.5f),
00050         XMFLOAT3(-2.0f, -2.5f, -1.5f),
00051         XMFLOAT3(1.5f, -2.5f, -1.5f),
00052         XMFLOAT3(1.5f, -2.5f, -3.0f),
00053         XMFLOAT3(-1.0f,  1.0f, -3.0f),
00054     };
00055     static constexpr XMFLOAT3 LineList3[] =
00056     {
00057         XMFLOAT3(1.5f,  0.0f, -5.5f),
00058         XMFLOAT3(1.5f,  1.0f, -5.5f),
00059         XMFLOAT3(1.5f, -2.5f, -5.5f),
00060         XMFLOAT3(1.5f,  0.0f, -5.5f),
00061     };
00062     static constexpr XMFLOAT3 LineList4[] =
00063     {
00064         XMFLOAT3(-2.5f, -1.0f, -5.5f),
00065         XMFLOAT3(1.0f, -1.0f, -5.5f),
00066         XMFLOAT3(1.0f,  1.0f, -5.5f),
00067         XMFLOAT3(-2.5f,  1.0f, -5.5f),
00068         XMFLOAT3(-2.5f, -1.0f, -5.5f),
00069     };
00070     static constexpr XMFLOAT3 LineList5[] =
00071     {
00072         XMFLOAT3(0.5f, -2.0f, -5.0f),
00073         XMFLOAT3(2.0f, -2.0f, -5.0f),
00074         XMFLOAT3(2.0f,  1.0f, -5.0f),
00075         XMFLOAT3(-2.5f,  1.0f, -5.0f),
00076         XMFLOAT3(-2.5f, -2.0f, -5.0f),
00077         XMFLOAT3(0.5f, -2.0f, -5.0f),
00078     };
00079     static constexpr XMFLOAT3 LineList6[] =
00080     {
00081         XMFLOAT3(1.5f, -2.0f, -5.5f),
00082         XMFLOAT3(-2.5f, -2.0f, -5.5f),
00083         XMFLOAT3(-2.5f,  1.0f, -5.5f),
00084         XMFLOAT3(1.5f,  1.0f, -5.5f),
00085         XMFLOAT3(1.5f, -2.0f, -5.5f),
00086     };
00087
00088     int targetCount = 0;
00089     for (auto&& object : objects)
00090     {
00091         if (auto target = dynamic_cast<Face*>(object.get()))
00092         {
00093             if (targetCount < 9)
00094             {
00095                 target->Active(true);
00096                 target->Target(true);
00097                 target->Hit(false);
00098                 target->Position(position[targetCount]);
00099                 switch (targetCount)
00100                 {
00101                 case 0:
00102                     target->AnimatePosition(std::make_shared<AnimateLineListPosition>(4, LineList1, 10.0f, true));
00103                     break;
00104                 case 1:
00105                     target->AnimatePosition(std::make_shared<AnimateLineListPosition>(6, LineList2, 15.0f, true));
00106                     break;
00107                 case 2:
00108                     target->AnimatePosition(std::make_shared<AnimateLineListPosition>(4, LineList3, 15.0f, true));
00109                     break;
00110                 case 3:
00111                     target->AnimatePosition(std::make_shared<AnimateLineListPosition>(5, LineList4, 15.0f, true));
00112                     break;
00113                 case 4:
00114                     target->AnimatePosition(std::make_shared<AnimateLineListPosition>(6, LineList5, 15.0f, true));
00115                     break;
00116                 case 5:
00117                     target->AnimatePosition(std::make_shared<AnimateLineListPosition>(5, LineList6, 15.0f, true));
00118                     break;
00119                 case 6:
00120                     target->AnimatePosition(
00121                         std::make_shared<AnimateCirclePosition>(
00122                             XMFLOAT3(0.0f, -2.5f, 0.0f),
00123                             XMFLOAT3(0.0f, -3.6f, 0.0f),
00124                             XMFLOAT3(0.0f, 0.0f, 1.0f),
00125                             9.0f,
00126                             true,
00127                             true
00128                             )
00129                         );
00130                     break;
00131                 case 7:
00132                     target->AnimatePosition(
00133                         std::make_shared<AnimateCirclePosition>(
00134                             XMFLOAT3(0.0f, -2.5f, 0.0f),
00135                             XMFLOAT3(0.0f, -3.6f, 0.0f),
00136                             XMFLOAT3(0.0f, 0.0f, 1.0f),
00137                             9.0f,
00138                             true,
00139                             true
00140                             )
00141                         );
00142                     target->AnimatePosition()->Start(3.0f);
00143                     break;
00144                 case 8:
00145                     target->AnimatePosition(
00146                         std::make_shared<AnimateCirclePosition>(
00147                             XMFLOAT3(0.0f, -2.5f, 0.0f),
00148                             XMFLOAT3(0.0f, -3.6f, 0.0f),
00149                             XMFLOAT3(0.0f, 0.0f, 1.0f),
00150                             9.0f,
00151                             true,
00152                             true
00153                             )
00154                         );
00155                     target->AnimatePosition()->Start(6.0f);
00156                     break;
00157                 }
00158                 targetCount++;
00159             }
00160             else
00161             {
00162                 target->Active(false);
00163             }
00164         }
00165         else
00166         {
00167             object->Active(false);
00168         }
00169     }
00170 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cpp/Scenario_PredefinedDictationGrammar.xaml.cpp Source File

  • SpeechRecognitionAndSynthesis
  • cpp

Scenario_PredefinedDictationGrammar.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario_PredefinedDictationGrammar.xaml.h"
00014 #include "AudioCapturePermissions.h"
00015
00016 using namespace SDKTemplate;
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::ApplicationModel::Resources::Core;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Media::SpeechRecognition;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Controls::Primitives;
00028 using namespace Windows::UI::Xaml::Data;
00029 using namespace Windows::UI::Xaml::Documents;
00030 using namespace Windows::UI::Xaml::Input;
00031 using namespace Windows::UI::Xaml::Media;
00032 using namespace Windows::UI::Xaml::Navigation;
00033
00034 Scenario_PredefinedDictationGrammar::Scenario_PredefinedDictationGrammar() : rootPage(MainPage::Current)
00035 {
00036     InitializeComponent();
00037 }
00038
00039 /// <summary>
00040 /// When activating the scenario, ensure we have permission from the user to access their microphone, and
00041 /// provide an appropriate path for the user to enable access to the microphone if they haven't
00042 /// given explicit permission for it.
00043 /// </summary>
00044 /// <param name="e">The navigation event details</param>
00045 void Scenario_PredefinedDictationGrammar::OnNavigatedTo(NavigationEventArgs^ e)
00046 {
00047     Page::OnNavigatedTo(e);
00048
00049     // Save the UI thread dispatcher to allow speech status messages to be shown on the UI.
00050     dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
00051
00052     create_task(AudioCapturePermissions::RequestMicrophonePermissionAsync(), task_continuation_context::use_current())
00053         .then([this](bool permissionGained)
00054     {
00055         if (permissionGained)
00056         {
00057             // Enable the recognition buttons.
00058             this->btnRecognizeWithUI->IsEnabled = true;
00059             this->btnRecognizeWithoutUI->IsEnabled = true;
00060
00061       Windows::Globalization::Language^ speechLanguage = SpeechRecognizer::SystemSpeechLanguage;
00062       speechContext = ResourceContext::GetForCurrentView();
00063       speechContext->Languages = ref new VectorView<String^>(1, speechLanguage->LanguageTag);
00064
00065       speechResourceMap = ResourceManager::Current->MainResourceMap->GetSubtree(L"LocalizationSpeechResources");
00066
00067       PopulateLanguageDropdown();
00068       InitializeRecognizer(SpeechRecognizer::SystemSpeechLanguage);
00069         }
00070         else
00071         {
00072             this->resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00073             this->resultTextBlock->Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone.";
00074       this->cbLanguageSelection->IsEnabled = false;
00075         }
00076   });
00077 }
00078
00079 /// <summary>
00080 /// Creates a SpeechRecognizer instance and initializes the grammar.
00081 /// </summary>
00082 void Scenario_PredefinedDictationGrammar::InitializeRecognizer(Windows::Globalization::Language^ recognizerLanguage)
00083 {
00084     // If reinitializing the recognizer (ie, changing the speech language), clean up the old recognizer first.
00085     // Avoid doing this while the recognizer is active by disabling the ability to change languages while listening.
00086     if (this->speechRecognizer != nullptr)
00087     {
00088         speechRecognizer->StateChanged -= stateChangedToken;
00089
00090         delete this->speechRecognizer;
00091         this->speechRecognizer = nullptr;
00092     }
00093
00094     // Create an instance of SpeechRecognizer.
00095     this->speechRecognizer = ref new SpeechRecognizer(recognizerLanguage);
00096
00097     // Provide feedback to the user about the state of the recognizer.
00098     stateChangedToken = speechRecognizer->StateChanged +=
00099         ref new Windows::Foundation::TypedEventHandler<
00100         SpeechRecognizer ^,
00101         SpeechRecognizerStateChangedEventArgs ^>(
00102             this,
00103             &Scenario_PredefinedDictationGrammar::SpeechRecognizer_StateChanged);
00104
00105     // Compile the dictation topic constraint, which optimizes for dictated speech.
00106     auto dictationConstraint = ref new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario::Dictation, "dictation");
00107     speechRecognizer->Constraints->Append(dictationConstraint);
00108
00109     // RecognizeWithUIAsync allows developers to customize the prompts.
00110     speechRecognizer->UIOptions->AudiblePrompt = L"Dictate a phrase or sentence...";
00111     speechRecognizer->UIOptions->ExampleText = speechResourceMap->GetValue("DictationUIOptionsExampleText", speechContext)->ValueAsString;
00112
00113     create_task(speechRecognizer->CompileConstraintsAsync(), task_continuation_context::use_current())
00114         .then([this](task<SpeechRecognitionCompilationResult^> previousTask)
00115     {
00116         SpeechRecognitionCompilationResult^ compilationResult = previousTask.get();
00117
00118         // Check to make sure that the constraints were in a proper format and the recognizer was able to compile it.
00119         if (compilationResult->Status != SpeechRecognitionResultStatus::Success)
00120         {
00121             // Disable the recognition buttons.
00122             btnRecognizeWithUI->IsEnabled = false;
00123             btnRecognizeWithoutUI->IsEnabled = false;
00124
00125             // Let the user know that the grammar didn't compile properly.
00126             resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00127             resultTextBlock->Text = "Unable to compile grammar.";
00128         }
00129     }, task_continuation_context::use_current());
00130 }
00131
00132 /// <summary>
00133 /// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks.
00134 /// </summary>
00135 /// <param name="e">Details about the navigation event</param>
00136 void Scenario_PredefinedDictationGrammar::OnNavigatedFrom(NavigationEventArgs^ e)
00137 {
00138     Page::OnNavigatedFrom(e);
00139
00140     if (speechRecognizer != nullptr)
00141     {
00142         speechRecognizer->StateChanged -= stateChangedToken;
00143
00144         delete speechRecognizer;
00145         speechRecognizer = nullptr;
00146     }
00147 }
00148
00149 /// <summary>
00150 /// Uses the recognizer constructed earlier to listen for speech from the user before displaying
00151 /// it back on the screen. Uses the built-in speech recognition UI.
00152 /// </summary>
00153 /// <param name="sender">Button that triggered this event</param>
00154 /// <param name="e">State information about the routed event</param>
00155 void Scenario_PredefinedDictationGrammar::RecognizeWithUIDictationGrammar_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00156 {
00157     heardYouSayTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00158     hlOpenPrivacySettings->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00159
00160     try
00161     {
00162         // Start recognition.
00163         create_task(speechRecognizer->RecognizeWithUIAsync(), task_continuation_context::use_current())
00164             .then([this](task<SpeechRecognitionResult^> recognitionTask)
00165         {
00166             try
00167             {
00168                 SpeechRecognitionResult^ speechRecognitionResult = recognitionTask.get();
00169                 // If successful, display the recognition result.
00170                 if (speechRecognitionResult->Status == SpeechRecognitionResultStatus::Success)
00171                 {
00172                     heardYouSayTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00173                     resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00174                     resultTextBlock->Text = speechRecognitionResult->Text;
00175                 }
00176                 else
00177                 {
00178                     heardYouSayTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00179                     resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00180                     resultTextBlock->Text = L"Speech Recognition Failure, Status: " + speechRecognitionResult->Status.ToString();
00181                 }
00182             }
00183             catch (ObjectDisposedException^ exception)
00184             {
00185                 // ObjectDisposedException will be thrown if you exit the scenario while the recogizer is actively
00186                 // processing speech. Since this happens here when we navigate out of the scenario, don't try to
00187                 // show a message dialog for this exception.
00188                 OutputDebugString(L"ObjectDisposedException caught while recognition in progress (can be ignored):");
00189                 OutputDebugString(exception->ToString()->Data());
00190             }
00191             catch (Exception^ exception)
00192             {
00193                 auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00194                 create_task(messageDialog->ShowAsync());
00195             }
00196         });
00197     }
00198     catch (COMException^ exception)
00199     {
00200         if ((unsigned int)exception->HResult == Scenario_PredefinedDictationGrammar::HResultPrivacyStatementDeclined)
00201         {
00202             // If the privacy policy hasn't been accepted, attempting to create a task out of RecognizeAsync fails immediately with a
00203             // COMException and this specific HResult.
00204             hlOpenPrivacySettings->Visibility = Windows::UI::Xaml::Visibility::Visible;
00205         }
00206         else
00207         {
00208             auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00209             create_task(messageDialog->ShowAsync());
00210         }
00211     }
00212 }
00213
00214 /// <summary>
00215 /// Uses the recognizer constructed earlier to listen for speech from the user before displaying
00216 /// it back on the screen. Uses developer-provided UI for user feedback.
00217 /// </summary>
00218 /// <param name="sender">Button that triggered this event</param>
00219 /// <param name="e">State information about the routed event</param>
00220 void Scenario_PredefinedDictationGrammar::RecognizeWithoutUIDictationGrammar_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00221 {
00222     heardYouSayTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00223     hlOpenPrivacySettings->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00224
00225     // Disable the UI while recognition is occurring, and provide feedback to the user about current state.
00226     btnRecognizeWithUI->IsEnabled = false;
00227     btnRecognizeWithoutUI->IsEnabled = false;
00228     listenWithoutUIButtonText->Text = " listening for speech...";
00229     cbLanguageSelection->IsEnabled = false;
00230
00231     try
00232     {
00233         // Start recognition.
00234         create_task(speechRecognizer->RecognizeAsync(), task_continuation_context::use_current())
00235             .then([this](task<SpeechRecognitionResult^> recognitionTask)
00236         {
00237             try
00238             {
00239                 SpeechRecognitionResult^ speechRecognitionResult = recognitionTask.get();
00240                 // If successful, display the recognition result.
00241                 if (speechRecognitionResult->Status == SpeechRecognitionResultStatus::Success)
00242                 {
00243                     heardYouSayTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00244                     resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00245                     resultTextBlock->Text = speechRecognitionResult->Text;
00246                 }
00247                 else
00248                 {
00249                     heardYouSayTextBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00250                     resultTextBlock->Visibility = Windows::UI::Xaml::Visibility::Visible;
00251                     resultTextBlock->Text = L"Speech Recognition Failure, Status: " + speechRecognitionResult->Status.ToString();
00252                 }
00253             }
00254             catch (ObjectDisposedException^ exception)
00255             {
00256                 // ObjectDisposedException will be thrown if you exit the scenario while the recogizer is actively
00257                 // processing speech. Since this happens here when we navigate out of the scenario, don't try to
00258                 // show a message dialog for this exception.
00259                 OutputDebugString(L"ObjectDisposedException caught while recognition in progress (can be ignored):");
00260                 OutputDebugString(exception->ToString()->Data());
00261             }
00262             catch (Exception^ exception)
00263             {
00264                 auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00265                 create_task(messageDialog->ShowAsync());
00266             }
00267
00268             // Reset UI state.
00269             listenWithoutUIButtonText->Text = " without UI";
00270             btnRecognizeWithUI->IsEnabled = true;
00271             btnRecognizeWithoutUI->IsEnabled = true;
00272             cbLanguageSelection->IsEnabled = true;
00273         });
00274     }
00275     catch (COMException^ exception)
00276     {
00277         if ((unsigned int)exception->HResult == Scenario_PredefinedDictationGrammar::HResultPrivacyStatementDeclined)
00278         {
00279             // If the privacy policy hasn't been accepted, attempting to create a task out of RecognizeAsync fails immediately with a
00280             // COMException and this specific HResult.
00281             hlOpenPrivacySettings->Visibility = Windows::UI::Xaml::Visibility::Visible;
00282         }
00283         else
00284         {
00285             auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00286             create_task(messageDialog->ShowAsync());
00287         }
00288
00289         listenWithoutUIButtonText->Text = " without UI";
00290         btnRecognizeWithUI->IsEnabled = true;
00291         btnRecognizeWithoutUI->IsEnabled = true;
00292         cbLanguageSelection->IsEnabled = true;
00293     }
00294 }
00295
00296 /// <summary>
00297 /// Handle SpeechRecognizer state changed events by updating a UI component.
00298 /// </summary>
00299 /// <param name="sender">Speech recognizer that generated this status event</param>
00300 /// <param name="args">The recognizer's status</param>
00301 void Scenario_PredefinedDictationGrammar::SpeechRecognizer_StateChanged(SpeechRecognizer ^sender, SpeechRecognizerStateChangedEventArgs ^args)
00302 {
00303     dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00304     {
00305         rootPage->NotifyUser("Speech recognizer state: " + args->State.ToString(), NotifyType::StatusMessage);
00306     }));
00307
00308 }
00309
00310 /// <summary>
00311 /// Populate language dropdown with supported Dictation languages.
00312 /// </summary>
00313 void Scenario_PredefinedDictationGrammar::PopulateLanguageDropdown()
00314 {
00315     Windows::Globalization::Language^ defaultLanguage = SpeechRecognizer::SystemSpeechLanguage;
00316     auto supportedLanguages = SpeechRecognizer::SupportedTopicLanguages;
00317     std::for_each(begin(supportedLanguages), end(supportedLanguages), [&](Windows::Globalization::Language^ lang)
00318     {
00319         ComboBoxItem^ item = ref new ComboBoxItem();
00320         item->Tag = lang;
00321         item->Content = lang->DisplayName;
00322
00323         cbLanguageSelection->Items->Append(item);
00324         if (lang->LanguageTag == defaultLanguage->LanguageTag)
00325         {
00326             item->IsSelected = true;
00327             cbLanguageSelection->SelectedItem = item;
00328         }
00329     });
00330 }
00331
00332 /// <summary>
00333 /// Re-initialize the recognizer based on selections from the language combobox.
00334 /// </summary>
00335 void Scenario_PredefinedDictationGrammar::cbLanguageSelection_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e)
00336 {
00337     if (this->speechRecognizer != nullptr)
00338     {
00339         ComboBoxItem^ item = (ComboBoxItem^)(cbLanguageSelection->SelectedItem);
00340         Windows::Globalization::Language^ newLanguage = (Windows::Globalization::Language^)item->Tag;
00341         if (speechRecognizer->CurrentLanguage != newLanguage)
00342         {
00343             try
00344             {
00345                 speechContext->Languages = ref new VectorView<String^>(1, newLanguage->LanguageTag);
00346
00347                 InitializeRecognizer(newLanguage);
00348             }
00349             catch (Exception^ exception)
00350             {
00351                 auto messageDialog = ref new Windows::UI::Popups::MessageDialog(exception->Message, "Exception");
00352                 create_task(messageDialog->ShowAsync());
00353             }
00354         }
00355     }
00356 }
00357
00358 /// <summary>
00359 /// Open the Speech, Inking and Typing page under Settings -> Privacy, enabling a user to accept the
00360 /// Microsoft Privacy Policy, and enable personalization.
00361 /// </summary>
00362 /// <param name="sender">Ignored</param>
00363 /// <param name="args">Ignored</param>
00364 void Scenario_PredefinedDictationGrammar::openPrivacySettings_Click(Hyperlink^ sender, HyperlinkClickEventArgs^ args)
00365 {
00366     create_task(Windows::System::Launcher::LaunchUriAsync(ref new Uri(L"ms-settings:privacy-speech")));
00367 }
Generated on Fri Nov 15 2024 22:21:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-I2C/cpp/SampleConfiguration.h Source File

  • IoT-I2C
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012
00013 namespace SDKTemplate
00014 {
00015     value struct Scenario;
00016
00017     partial ref class MainPage
00018     {
00019     internal:
00020         static property Platform::String^ FEATURE_NAME
00021         {
00022             Platform::String^ get()
00023             {
00024                 return "I2C C++ Sample";
00025             }
00026         }
00027
00028         static property Platform::Array<Scenario>^ scenarios
00029         {
00030             Platform::Array<Scenario>^ get()
00031             {
00032                 return scenariosInner;
00033             }
00034         }
00035
00036     private:
00037         static Platform::Array<Scenario>^ scenariosInner;
00038     };
00039
00040     public value struct Scenario
00041     {
00042         Platform::String^ Title;
00043         Platform::String^ ClassName;
00044     };
00045 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cpp/AppView.cpp Source File

  • BasicHologram
  • cpp

AppView.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
00002 #include "AppView.h"
00003
00004 #include <ppltasks.h>
00005
00006 using namespace BasicHologram;
00007 using namespace concurrency;
00008 using namespace Windows::ApplicationModel;
00009 using namespace Windows::ApplicationModel::Activation;
00010 using namespace Windows::ApplicationModel::Core;
00011 using namespace Windows::Foundation;
00012 using namespace Windows::Graphics::Holographic;
00013 using namespace Windows::UI::Core;
00014
00015 // The main function is only used to initialize our IFrameworkView class.
00016 // Under most circumstances, you should not need to modify this function.
00017 [Platform::MTAThread]
00018 int main(Platform::Array<Platform::String^>^)
00019 {
00020     AppViewSource^ appViewSource = ref new ::AppViewSource();
00021     CoreApplication::Run(appViewSource);
00022     return 0;
00023 }
00024
00025 IFrameworkView^ AppViewSource::CreateView()
00026 {
00027     return ref new AppView();
00028 }
00029
00030 AppView::AppView()
00031 {
00032 }
00033
00034
00035 // IFrameworkView methods
00036
00037 // The first method called when the IFrameworkView is being created.
00038 // Use this method to subscribe for Windows shell events and to initialize your app.
00039 void AppView::Initialize(CoreApplicationView^ applicationView)
00040 {
00041     applicationView->Activated +=
00042         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &AppView::OnViewActivated);
00043
00044     // Register event handlers for app lifecycle.
00045     CoreApplication::Suspending +=
00046         ref new EventHandler<SuspendingEventArgs^>(this, &AppView::OnSuspending);
00047
00048     CoreApplication::Resuming +=
00049         ref new EventHandler<Platform::Object^>(this, &AppView::OnResuming);
00050
00051     // At this point we have access to the device and we can create device-dependent
00052     // resources.
00053     m_deviceResources = std::make_shared<DX::DeviceResources>();
00054
00055     m_main = std::make_unique<BasicHologramMain>(m_deviceResources);
00056 }
00057
00058 // Called when the CoreWindow object is created (or re-created).
00059 void AppView::SetWindow(CoreWindow^ window)
00060 {
00061     // Register for keypress notifications.
00062     window->KeyDown +=
00063         ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &AppView::OnKeyPressed);
00064
00065     // Register for pointer pressed notifications.
00066     window->PointerPressed +=
00067         ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &AppView::OnPointerPressed);
00068
00069     // Register for notification that the app window is being closed.
00070     window->Closed +=
00071         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &AppView::OnWindowClosed);
00072
00073     // Register for notifications that the app window is losing focus.
00074     window->VisibilityChanged +=
00075         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &AppView::OnVisibilityChanged);
00076
00077     // Create a holographic space for the core window for the current view.
00078     // Presenting holographic frames that are created by this holographic space will put
00079     // the app into exclusive mode.
00080     m_holographicSpace = HolographicSpace::CreateForCoreWindow(window);
00081
00082     // The DeviceResources class uses the preferred DXGI adapter ID from the holographic
00083     // space (when available) to create a Direct3D device. The HolographicSpace
00084     // uses this ID3D11Device to create and manage device-based resources such as
00085     // swap chains.
00086     m_deviceResources->SetHolographicSpace(m_holographicSpace);
00087
00088     // The main class uses the holographic space for updates and rendering.
00089     m_main->SetHolographicSpace(m_holographicSpace);
00090 }
00091
00092 // The Load method can be used to initialize scene resources or to load a
00093 // previously saved app state.
00094 void AppView::Load(Platform::String^ entryPoint)
00095 {
00096 }
00097
00098 // This method is called after the window becomes active. It oversees the
00099 // update, draw, and present loop, and it also oversees window message processing.
00100 void AppView::Run()
00101 {
00102     while (!m_windowClosed)
00103     {
00104         if (m_windowVisible && (m_holographicSpace != nullptr))
00105         {
00106             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00107
00108             HolographicFrame^ holographicFrame = m_main->Update();
00109
00110             if (m_main->Render(holographicFrame))
00111             {
00112                 // The holographic frame has an API that presents the swap chain for each
00113                 // holographic camera.
00114                 m_deviceResources->Present(holographicFrame);
00115             }
00116         }
00117         else
00118         {
00119             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00120         }
00121     }
00122 }
00123
00124 // Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
00125 // class is torn down while the app is in the foreground.
00126 // This method is not often used, but IFrameworkView requires it and it will be called for
00127 // holographic apps.
00128 void AppView::Uninitialize()
00129 {
00130
00131 }
00132
00133
00134 // Application lifecycle event handlers
00135
00136 // Called when the app is prelaunched. Use this method to load resources ahead of time
00137 // and enable faster launch times.
00138 void AppView::OnLaunched(LaunchActivatedEventArgs^ args)
00139 {
00140     if (args->PrelaunchActivated)
00141     {
00142         //
00143         // TODO: Insert code to preload resources here.
00144         //
00145     }
00146 }
00147
00148 // Called when the app view is activated. Activates the app's CoreWindow.
00149 void AppView::OnViewActivated(CoreApplicationView^ sender, IActivatedEventArgs^ args)
00150 {
00151     // Run() won't start until the CoreWindow is activated.
00152     sender->CoreWindow->Activate();
00153 }
00154
00155 void AppView::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
00156 {
00157     // Save app state asynchronously after requesting a deferral. Holding a deferral
00158     // indicates that the application is busy performing suspending operations. Be
00159     // aware that a deferral may not be held indefinitely; after about five seconds,
00160     // the app will be forced to exit.
00161     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
00162
00163     create_task([this, deferral] ()
00164     {
00165         m_deviceResources->Trim();
00166
00167         if (m_main != nullptr)
00168         {
00169             m_main->SaveAppState();
00170         }
00171
00172         //
00173         // TODO: Insert code here to save your app state.
00174         //
00175
00176         deferral->Complete();
00177     });
00178 }
00179
00180 void AppView::OnResuming(Platform::Object^ sender, Platform::Object^ args)
00181 {
00182     // Restore any data or state that was unloaded on suspend. By default, data
00183     // and state are persisted when resuming from suspend. Note that this event
00184     // does not occur if the app was previously terminated.
00185
00186     if (m_main != nullptr)
00187     {
00188         m_main->LoadAppState();
00189     }
00190
00191     //
00192     // TODO: Insert code here to load your app state.
00193     //
00194 }
00195
00196
00197 // Window event handlers
00198
00199 void AppView::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
00200 {
00201     m_windowVisible = args->Visible;
00202 }
00203
00204 void AppView::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
00205 {
00206     m_windowClosed = true;
00207 }
00208
00209
00210 // Input event handlers
00211
00212 void AppView::OnKeyPressed(CoreWindow^ sender, KeyEventArgs^ args)
00213 {
00214     //
00215     // TODO: Bluetooth keyboards are supported by HoloLens. You can use this method for
00216     //       keyboard input if you want to support it as an optional input method for
00217     //       your holographic app.
00218     //
00219 }
00220
00221 void AppView::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
00222 {
00223     // Allow the user to interact with the holographic world using the mouse.
00224     if (m_main != nullptr)
00225     {
00226         m_main->OnPointerPressed();
00227     }
00228 }
00229
Generated on Fri Nov 15 2024 22:16:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CompositionVisual/cpp/pch.h Source File

  • CompositionVisual
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserInfo/cppwinrt/Scenario1_FindUsers.cpp Source File

  • UserInfo
  • cppwinrt

Scenario1_FindUsers.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_FindUsers.h"
00014 #include "SampleConfiguration.h"
00015 #include "Scenario1_FindUsers.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::Foundation::Collections;
00020 using namespace winrt::Windows::Storage::Streams;
00021 using namespace winrt::Windows::System;
00022 using namespace winrt::Windows::UI::Xaml;
00023 using namespace winrt::Windows::UI::Xaml::Media::Imaging;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario1_FindUsers::Scenario1_FindUsers()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     fire_and_forget Scenario1_FindUsers::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&)
00033     {
00034         auto lifetime = get_strong();
00035
00036         auto users = co_await Helpers::GetUserViewModelsAsync();
00037         UserList().DataContext(users);
00038         if (users.Size() > 0)
00039         {
00040             UserList().SelectedIndex(0);
00041         }
00042     }
00043
00044     fire_and_forget Scenario1_FindUsers::ShowProperties()
00045     {
00046         auto lifetime = get_strong();
00047
00048         auto selectedUser = UserList().SelectedValue().as<SDKTemplate::UserViewModel>();
00049         if (selectedUser != nullptr)
00050         {
00051             ResultsText().Text(L"");
00052             ProfileImage().Source(nullptr);
00053             rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00054             try
00055             {
00056                 User user = User::GetFromId(selectedUser.UserId());
00057
00058                 // Start with some fixed properties.
00059                 hstring result = L"NonRoamableId: " + user.NonRoamableId ()+ L"\n"
00060                 + L"Type: " + to_hstring(user.Type()) + L"\n";
00061                 + L"AuthenticationStatus: " + to_hstring(user.AuthenticationStatus()) + L"\n";
00062
00063                 // Build a list of all the properties we want.
00064                 IVector<hstring> desiredProperties = single_threaded_vector<hstring>(
00065                 {
00066                     KnownUserProperties::FirstName(),
00067                     KnownUserProperties::LastName(),
00068                     KnownUserProperties::ProviderName(),
00069                     KnownUserProperties::AccountName(),
00070                     KnownUserProperties::GuestHost(),
00071                     KnownUserProperties::PrincipalName(),
00072                     KnownUserProperties::DomainName(),
00073                     KnownUserProperties::SessionInitiationProtocolUri(),
00074                 });
00075                 // Issue a bulk query for all of the properties.
00076                 IPropertySet values = co_await user.GetPropertiesAsync(desiredProperties.GetView());
00077
00078                 // Add those properties to our results.
00079                 for (auto property : desiredProperties)
00080                 {
00081                     result = result + property + L": " + values.Lookup(property).as<hstring>() + L"\n";
00082                 }
00083                 ResultsText().Text(result);
00084
00085                 // Get the user's picture.
00086                 IRandomAccessStreamReference streamReference = co_await user.GetPictureAsync(UserPictureSize::Size64x64);
00087                 if (streamReference != nullptr)
00088                 {
00089                     IRandomAccessStream stream = co_await streamReference.OpenReadAsync();
00090                     BitmapImage bitmapImage;
00091                     bitmapImage.SetSource(stream);
00092                     ProfileImage().Source(bitmapImage);
00093                 }
00094             }
00095             catch (hresult_error const& ex)
00096             {
00097                 rootPage.NotifyUser(ex.message(), NotifyType::ErrorMessage);
00098             }
00099         }
00100     }
00101 }
00102
Generated on Fri Nov 15 2024 22:21:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cpp/cpp/SampleConfiguration.h Source File

  • ProxyStubsForWinRTComponents
  • cpp
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Proxy and stub generation for Windows Runtime components";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cpp/Scenario3_ParameterizedTemplate.xaml.cpp Source File

  • DateTimeFormatting
  • cpp

Scenario3_ParameterizedTemplate.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_ParameterizedTemplate.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::Globalization;
00021 using namespace Windows::Globalization::DateTimeFormatting;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 Scenario3_ParameterizedTemplate::Scenario3_ParameterizedTemplate()
00027 {
00028     InitializeComponent();
00029 }
00030
00031 void Scenario3_ParameterizedTemplate::Display()
00032 {
00033     // This scenario uses the Windows.Globalization.DateTimeFormatting.DateTimeFormatter class
00034     // to format a date/time by specifying a template via parameters.  Note that the current application language
00035     // language and region value will determine the pattern of the date returned based on the
00036     // specified parts.
00037
00038     //Get the current application context language
00039     String^ currentLanguage = ApplicationLanguages::Languages->GetAt(0);
00040
00041     // Formatters for dates
00042     Array<DateTimeFormatter^>^ dateFormatters = {
00043         ref new DateTimeFormatter(
00044             YearFormat::Full,
00045             MonthFormat::Abbreviated,
00046             DayFormat::Default,
00047             DayOfWeekFormat::Abbreviated),
00048
00049         ref new DateTimeFormatter(
00050             YearFormat::Abbreviated,
00051             MonthFormat::Abbreviated,
00052             DayFormat::Default,
00053             DayOfWeekFormat::None),
00054
00055         ref new DateTimeFormatter(
00056             YearFormat::Full,
00057             MonthFormat::Full,
00058             DayFormat::None,
00059             DayOfWeekFormat::None),
00060
00061         ref new DateTimeFormatter(
00062             YearFormat::None,
00063             MonthFormat::Full,
00064             DayFormat::Default,
00065             DayOfWeekFormat::None),
00066     };
00067
00068     // Formatters for times
00069     Array<DateTimeFormatter^>^ timeFormatters = {
00070         ref new DateTimeFormatter(
00071             HourFormat::Default,
00072             MinuteFormat::Default,
00073             SecondFormat::Default),
00074
00075         ref new DateTimeFormatter(
00076             HourFormat::Default,
00077             MinuteFormat::Default,
00078             SecondFormat::None),
00079
00080         ref new DateTimeFormatter(
00081             HourFormat::Default,
00082             MinuteFormat::None,
00083             SecondFormat::None),
00084     };
00085
00086     // Obtain the date that will be formatted.
00087     Windows::Globalization::Calendar^ cal = ref new Windows::Globalization::Calendar();
00088     Windows::Foundation::DateTime dateToFormat = cal->GetDateTime();
00089
00090     // Keep the results here
00091     String^ results = "";
00092     results = results + "Current application context language: " + currentLanguage + "\n\n";
00093     results = results + "Dates:\n";
00094
00095     // Generate the results.
00096     for (auto formatter : dateFormatters)
00097     {
00098         // Perform the actual formatting.
00099         results = results + formatter->Template + ": " + formatter->Format(dateToFormat) + "\n";
00100     }
00101
00102     results = results + "\n";
00103     results = results + "Times:\n";
00104
00105     // Generate the results.
00106     for (auto formatter : timeFormatters)
00107     {
00108         // Perform the actual formatting.
00109         results = results + formatter->Template + ": " + formatter->Format(dateToFormat) + "\n";
00110     }
00111
00112     // Display the results.
00113     OutputTextBlock->Text = results;
00114 }
Generated on Fri Nov 15 2024 22:19:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceInformationDisplay Member List

This is the complete list of members for DeviceInformationDisplay, including all inherited members.
CanPair() const | DeviceInformationDisplay | [inline]
DeviceInformation() const | DeviceInformationDisplay | [inline]
DeviceInformationDisplay(Windows::Devices::Enumeration::DeviceInformation const &deviceInfoIn) | DeviceInformationDisplay |
GetPropertyForDisplay(hstring const &key) | DeviceInformationDisplay |
GlyphBitmapImage() const | DeviceInformationDisplay | [inline]
Id() const | DeviceInformationDisplay | [inline]
IsPaired() const | DeviceInformationDisplay | [inline]
Kind() const | DeviceInformationDisplay | [inline]
m_propertyChanged | DeviceInformationDisplay | [private]
Name() const | DeviceInformationDisplay | [inline]
OnPropertyChanged(hstring const &name) | DeviceInformationDisplay | [private]
Properties() | DeviceInformationDisplay | [inline]
PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const &handler) | DeviceInformationDisplay | [inline]
PropertyChanged(event_token const &token) | DeviceInformationDisplay | [inline]
Stuff() | DeviceInformationDisplay | [inline]
Update(Windows::Devices::Enumeration::DeviceInformationUpdate const &deviceInfoUpdate) | DeviceInformationDisplay |
UpdateGlyphBitmapImage() | DeviceInformationDisplay | [private]
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cppwinrt/Project.idl Source File

  • Calendar
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_Data : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_Data();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_Stats : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_Stats();
00024     }
00025
00026     [default_interface]
00027     runtimeclass Scenario3_Enum : Windows.UI.Xaml.Controls.Page
00028     {
00029         Scenario3_Enum();
00030     }
00031
00032     [default_interface]
00033     runtimeclass Scenario4_UnicodeExtensions : Windows.UI.Xaml.Controls.Page
00034     {
00035         Scenario4_UnicodeExtensions();
00036     }
00037
00038     [default_interface]
00039     runtimeclass Scenario5_TimeZone : Windows.UI.Xaml.Controls.Page
00040     {
00041         Scenario5_TimeZone();
00042     }
00043 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MessageDialog/cpp/DefaultCloseCommand.xaml.cpp Source File

  • MessageDialog
  • cpp

DefaultCloseCommand.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // CustomCommand.xaml.cpp
00013 // Implementation of the CustomCommand class
00014 //
00015
00016 #include "pch.h"
00017 #include "DefaultCloseCommand.xaml.h"
00018
00019 using namespace SDKTemplate;
00020
00021 using namespace concurrency;
00022 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::UI::Popups;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 DefaultCloseCommand::DefaultCloseCommand()
00030 {
00031     InitializeComponent();
00032 }
00033
00034 void DefaultCloseCommand::OnNavigatedTo(NavigationEventArgs^ e)
00035 {
00036     rootPage = MainPage::Current;
00037 }
00038
00039 /// <summary>
00040 /// Click handler for the 'DefaultCloseCommandButton' button.
00041 /// Demonstrates showing a message dialog with a default close command and content.
00042 /// A message will be displayed indicating that the dialog has been closed.
00043 /// In this scenario, the only command is the default 'Close' command that is used if no other commands are specified.
00044 /// </summary>
00045 /// <param name="sender">The Object that caused this event to be fired.</param>
00046 /// <param name="e">State information and event data associated with the routed event.</param>
00047 void DefaultCloseCommand::DefaultCloseCommandButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00048 {
00049     // Create the message dialog and set its content; it will get a default "Close" command since there aren't any other commands being added
00050     auto messageDialog = ref new MessageDialog("You've exceeded your trial period.");
00051
00052     // Show the message dialog
00053     create_task(messageDialog->ShowAsync()).then([this](IUICommand^ command)
00054     {
00055         rootPage->NotifyUser("The dialog has now been closed", NotifyType::StatusMessage);
00056     });
00057 }
Generated on Fri Nov 15 2024 22:20:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Check Member List

This is the complete list of members for Check, including all inherited members.
Address | ReadBinary |
ApduCommand(byte cla, byte ins, byte p1, byte p2, byte[] commandData, byte?le) | ApduCommand | [inline]
ApduResponseType | ApduCommand |
BlockCount | Check |
BlockList | Check |
Check(byte serviceCount, byte[] serviceCodeList, byte blockCount, byte[] blockList) | Check | [inline]
CLA | ApduCommand |
CommandData | ApduCommand |
GetBuffer() | ApduCommand | [inline]
GetDataIn(byte serviceCount, byte[] serviceCodeList, byte blockCount, byte[] blockList) | Check | [inline, private, static]
INS | ApduCommand |
Le | ApduCommand |
P1 | ApduCommand |
P2 | ApduCommand |
ReadBinary(ushort address, byte?expectedReturnBytes) | ReadBinary | [inline]
ServiceCodeList | Check |
ServiceCount | Check |
ToString() | ApduCommand | [inline]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LanguageFont/cppwinrt/Scenario2_DocumentFonts.h Source File

  • LanguageFont
  • cppwinrt

Scenario2_DocumentFonts.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_DocumentFonts.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_DocumentFonts : Scenario2_DocumentFontsT<Scenario2_DocumentFonts>
00019     {
00020         Scenario2_DocumentFonts();
00021
00022         void ApplyFonts_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario2_DocumentFonts : Scenario2_DocumentFontsT<Scenario2_DocumentFonts, implementation::Scenario2_DocumentFonts>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:20:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SystemMediaTransportControls/cs/SampleConfiguration.cs Source File

  • SystemMediaTransportControls
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         // Change the string below to reflect the name of your sample.
00021         // This is used on the main page as the title of the sample.
00022         public const string FEATURE_NAME = "System Media Transport Controls C# Sample";
00023
00024         // Change the array below to reflect the name of your scenarios.
00025         // This will be used to populate the list of scenarios on the main page with
00026         // which the user will choose the specific scenario that they are interested in.
00027         // These should be in the form: "Navigating to a web page".
00028         // The code in MainPage will take care of turning this into: "1) Navigating to a web page"
00029         List<Scenario> scenarios = new List<Scenario>
00030         {
00031             new Scenario() { Title = "System media transport controls", ClassType = typeof(Scenario1) },
00032         };
00033     }
00034
00035     public class Scenario
00036     {
00037         public string Title { get; set; }
00038         public Type ClassType { get; set; }
00039     }
00040 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBottomUpList/cpp/Scenario1_Basic.xaml.h Source File

  • XamlBottomUpList
  • cpp

Scenario1_Basic.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Basic.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario1_Basic sealed
00021     {
00022     public:
00023         Scenario1_Basic();
00024
00025     protected:
00026         void AddItemToEnd();
00027         void DeleteSelectedItem();
00028         void SaveScrollPosition();
00029         void RestoreScrollPosition();
00030
00031     private:
00032         int messageNumber = 0;
00033         Platform::String^ savedScrollPosition;
00034     };
00035 }
Generated on Fri Nov 15 2024 22:19:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario2WinRTComponent/OnboardingSignals.cpp Source File

  • AllJoyn
  • Common
  • Scenario2WinRTComponent

OnboardingSignals.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #include "pch.h"
00022
00023 using namespace Microsoft::WRL;
00024 using namespace Platform;
00025 using namespace Windows::Devices::AllJoyn;
00026 using namespace Windows::Foundation;
00027 using namespace org::alljoyn::Onboarding;
00028
00029 void OnboardingSignals::Initialize(_In_ ISignalEmitter^ emitter)
00030 {
00031     m_emitter = emitter;
00032     alljoyn_busattachment nativeBusAttachment = AllJoynHelpers::GetInternalBusAttachment(m_emitter->BusObject->BusAttachment);
00033     auto interfaceDefinition = alljoyn_busattachment_getinterface(nativeBusAttachment, "org.alljoyn.Onboarding");
00034     alljoyn_interfacedescription_getmember(interfaceDefinition, "ConnectionResult", &m_memberConnectionResult);
00035 }
00036
00037 void OnboardingSignals::ConnectionResult(_In_ Onboarding^ interfaceMemberArg)
00038 {
00039     if (nullptr == AllJoynHelpers::GetInternalBusObject(m_emitter->BusObject))
00040     {
00041         return;
00042     }
00043
00044     size_t argCount = 1;
00045     alljoyn_msgarg arguments = alljoyn_msgarg_array_create(argCount);
00046     (void)TypeConversionHelpers::SetAllJoynMessageArg(alljoyn_msgarg_array_element(arguments, 0), "(ns)", interfaceMemberArg);
00047
00048     alljoyn_busobject_signal(
00049         AllJoynHelpers::GetInternalBusObject(m_emitter->BusObject),
00050         NULL,  // Generated code only supports broadcast signals.
00051         m_emitter->Session->Id,
00052         m_memberConnectionResult,
00053         arguments,
00054         argCount,
00055         0, // A signal with a TTL of 0 will be sent to every member of the session, regardless of how long it takes to deliver the message
00056         ALLJOYN_MESSAGE_FLAG_GLOBAL_BROADCAST, // Broadcast to everyone in the session.
00057         NULL); // The generated code does not need the generated signal message
00058
00059     alljoyn_msgarg_destroy(arguments);
00060 }
00061
00062 void OnboardingSignals::CallConnectionResultReceived(_In_ OnboardingSignals^ sender, _In_ OnboardingConnectionResultReceivedEventArgs^ args)
00063 {
00064     ConnectionResultReceived(sender, args);
00065 }
00066
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraFaceDetection/cpp/MainPage.xaml.cpp Source File

  • CameraFaceDetection
  • cpp

MainPage.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include <sstream>
00015
00016 using namespace Concurrency;
00017 using namespace FaceDetection;
00018 using namespace Platform;
00019 using namespace Windows::Devices::Sensors;
00020 using namespace Windows::Devices::Enumeration;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Graphics::Imaging;
00024 using namespace Windows::Graphics::Display;
00025 using namespace Windows::Media;
00026 using namespace Windows::Media::Core;
00027 using namespace Windows::Media::FaceAnalysis;
00028 using namespace Windows::Phone::UI::Input;
00029 using namespace Windows::Storage;
00030 using namespace Windows::UI::Xaml;
00031 using namespace Windows::UI::Xaml::Controls;
00032 using namespace Windows::UI::Xaml::Controls::Primitives;
00033 using namespace Windows::UI::Xaml::Data;
00034 using namespace Windows::UI::Xaml::Input;
00035 using namespace Windows::UI::Xaml::Media;
00036 using namespace Windows::UI::Xaml::Navigation;
00037 using namespace Windows::UI::Xaml::Shapes;
00038
00039 MainPage::MainPage()
00040     : _mediaCapture(nullptr)
00041     , _previewProperties(nullptr)
00042     , _isInitialized(false)
00043     , _isRecording(false)
00044     , _externalCamera(false)
00045     , _mirroringPreview(false)
00046     , _deviceOrientation(SimpleOrientation::NotRotated)
00047     , _displayOrientation(DisplayOrientations::Portrait)
00048     , _displayRequest(ref new Windows::System::Display::DisplayRequest())
00049     , RotationKey({ 0xC380465D, 0x2271, 0x428C,{ 0x9B, 0x83, 0xEC, 0xEA, 0x3B, 0x4A, 0x85, 0xC1 } })
00050     , _captureFolder(nullptr)
00051 {
00052     InitializeComponent();
00053
00054     _orientationSensor = SimpleOrientationSensor::GetDefault();
00055     _displayInformation = DisplayInformation::GetForCurrentView();
00056     _systemMediaControls = SystemMediaTransportControls::GetForCurrentView();
00057
00058     // Do not cache the state of the UI when suspending/navigating
00059     Page::NavigationCacheMode = Navigation::NavigationCacheMode::Disabled;
00060
00061     // Useful to know when to initialize/clean up the camera
00062     _applicationSuspendingEventToken =
00063         Application::Current->Suspending += ref new SuspendingEventHandler(this, &MainPage::Application_Suspending);
00064     _applicationResumingEventToken =
00065         Application::Current->Resuming += ref new EventHandler<Object^>(this, &MainPage::Application_Resuming);
00066 }
00067
00068 MainPage::~MainPage()
00069 {
00070     Application::Current->Suspending -= _applicationSuspendingEventToken;
00071     Application::Current->Resuming -= _applicationResumingEventToken;
00072 }
00073
00074 /// <summary>
00075 /// Initializes the MediaCapture, registers events, gets camera device information for mirroring and rotating, starts preview and unlocks the UI
00076 /// </summary>
00077 /// <returns></returns>
00078 task<void> MainPage::InitializeCameraAsync()
00079 {
00080     WriteLine("InitializeCameraAsync");
00081
00082     // Get available devices for capturing pictures
00083     return FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel::Front)
00084         .then([this](DeviceInformation^ camera)
00085     {
00086         if (camera == nullptr)
00087         {
00088             WriteLine("No camera device found!");
00089             return;
00090         }
00091         // Figure out where the camera is located
00092         if (camera->EnclosureLocation == nullptr || camera->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Unknown)
00093         {
00094             // No information on the location of the camera, assume it's an external camera, not integrated on the device
00095             _externalCamera = true;
00096         }
00097         else
00098         {
00099             // Camera is fixed on the device
00100             _externalCamera = false;
00101
00102             // Only mirror the preview if the camera is on the front panel
00103             _mirroringPreview = (camera->EnclosureLocation->Panel == Windows::Devices::Enumeration::Panel::Front);
00104         }
00105
00106         _mediaCapture = ref new Capture::MediaCapture();
00107
00108         // Register for a notification when video recording has reached the maximum time and when something goes wrong
00109         _recordLimitationExceededEventToken =
00110             _mediaCapture->RecordLimitationExceeded += ref new Capture::RecordLimitationExceededEventHandler(this, &MainPage::MediaCapture_RecordLimitationExceeded);
00111         _mediaCaptureFailedEventToken =
00112             _mediaCapture->Failed += ref new Capture::MediaCaptureFailedEventHandler(this, &MainPage::MediaCapture_Failed);
00113
00114         auto settings = ref new Capture::MediaCaptureInitializationSettings();
00115         settings->VideoDeviceId = camera->Id;
00116         settings->StreamingCaptureMode = Capture::StreamingCaptureMode::AudioAndVideo;
00117
00118         // Initialize media capture and start the preview
00119         create_task(_mediaCapture->InitializeAsync(settings))
00120             .then([this]()
00121         {
00122             _isInitialized = true;
00123
00124             return StartPreviewAsync()
00125                 .then([this]()
00126             {
00127                 UpdateCaptureControls();
00128             });
00129         }).then([this](task<void> previousTask)
00130         {
00131             try
00132             {
00133                 previousTask.get();
00134             }
00135             catch (AccessDeniedException^ ex)
00136             {
00137                 WriteLine("The app was denied access to the camera");
00138             }
00139         });
00140     });
00141 }
00142
00143 /// <summary>
00144 /// Cleans up the camera resources (after stopping any video recording and/or preview if necessary) and unregisters from MediaCapture events
00145 /// </summary>
00146 /// <returns></returns>
00147 Concurrency::task<void> MainPage::CleanupCameraAsync()
00148 {
00149     WriteLine("CleanupCameraAsync");
00150
00151     std::vector<task<void>> taskList;
00152
00153     if (_isInitialized)
00154     {
00155         // If a recording is in progress during cleanup, stop it to save the recording
00156         if (_isRecording)
00157         {
00158             auto stopRecordTask = StopRecordingAsync();
00159             taskList.push_back(stopRecordTask);
00160         }
00161
00162         if (_faceDetectionEffect)
00163         {
00164             auto cleanFaceDetectionTask = CleanUpFaceDetectionEffectAsync();
00165             taskList.push_back(cleanFaceDetectionTask);
00166         }
00167
00168         if (_previewProperties)
00169         {
00170             auto stopPreviewTask = StopPreviewAsync();
00171             taskList.push_back(stopPreviewTask);
00172         }
00173
00174         _isInitialized = false;
00175     }
00176
00177     // When all our tasks complete, clean up MediaCapture
00178     return when_all(taskList.begin(), taskList.end())
00179         .then([this]()
00180     {
00181         if (_mediaCapture != nullptr)
00182         {
00183             _mediaCapture->RecordLimitationExceeded -= _recordLimitationExceededEventToken;
00184             _mediaCapture->Failed -= _mediaCaptureFailedEventToken;
00185             _mediaCapture = nullptr;
00186         }
00187     });
00188 }
00189
00190 /// <summary>
00191 /// Starts the preview and adjusts it for for rotation and mirroring after making a request to keep the screen on
00192 /// </summary>
00193 /// <returns></returns>
00194 task<void> MainPage::StartPreviewAsync()
00195 {
00196     // Prevent the device from sleeping while the preview is running
00197     _displayRequest->RequestActive();
00198
00199     // Set the preview source in the UI and mirror it if necessary
00200     PreviewControl->Source = _mediaCapture.Get();
00201     PreviewControl->FlowDirection = _mirroringPreview ? Windows::UI::Xaml::FlowDirection::RightToLeft : Windows::UI::Xaml::FlowDirection::LeftToRight;
00202
00203     // Start the preview
00204     return create_task(_mediaCapture->StartPreviewAsync())
00205         .then([this](task<void> previousTask)
00206     {
00207         _previewProperties = _mediaCapture->VideoDeviceController->GetMediaStreamProperties(Capture::MediaStreamType::VideoPreview);
00208
00209         // Only need to update the orientation if the camera is mounted on the device
00210         if (!_externalCamera)
00211         {
00212             _displayOrientation = _displayInformation->CurrentOrientation;
00213             return SetPreviewRotationAsync();
00214         }
00215
00216         // Not external, just return the previous task
00217         return previousTask;
00218     });
00219 }
00220
00221 /// <summary>
00222 /// Gets the current orientation of the UI in relation to the device (when AutoRotationPreferences cannot be honored) and applies a corrective rotation to the preview
00223 /// </summary>
00224 /// <returns></returns>
00225 task<void> MainPage::SetPreviewRotationAsync()
00226 {
00227     // Calculate which way and how far to rotate the preview
00228     int rotationDegrees = ConvertDisplayOrientationToDegrees(_displayOrientation);
00229
00230     // The rotation direction needs to be inverted if the preview is being mirrored
00231     if (_mirroringPreview)
00232     {
00233         rotationDegrees = (360 - rotationDegrees) % 360;
00234     }
00235
00236     // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames
00237     auto props = _mediaCapture->VideoDeviceController->GetMediaStreamProperties(Capture::MediaStreamType::VideoPreview);
00238     props->Properties->Insert(RotationKey, rotationDegrees);
00239     return create_task(_mediaCapture->SetEncodingPropertiesAsync(Capture::MediaStreamType::VideoPreview, props, nullptr));
00240 }
00241
00242 /// <summary>
00243 /// Stops the preview and deactivates a display request, to allow the screen to go into power saving modes
00244 /// </summary>
00245 /// <returns></returns>
00246 task<void> MainPage::StopPreviewAsync()
00247 {
00248     _previewProperties = nullptr;
00249
00250     return create_task(_mediaCapture->StopPreviewAsync())
00251         .then([this]()
00252     {
00253         // Use the dispatcher because this method is sometimes called from non-UI threads
00254         return Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
00255         {
00256             // Cleanup the UI
00257             PreviewControl->Source = nullptr;
00258             // Allow the device screen to sleep now that the preview is stopped
00259             _displayRequest->RequestRelease();
00260         }));
00261     });
00262 }
00263
00264 /// <summary>
00265 /// Adds face detection to the preview stream, registers for its events, enables it, and gets the FaceDetectionEffect instance
00266 /// </summary>
00267 /// <returns></returns>
00268 task<void> MainPage::CreateFaceDetectionEffectAsync()
00269 {
00270     // Create the definition, which will contain some initialization settings
00271     auto definition = ref new FaceDetectionEffectDefinition();
00272
00273     // To ensure preview smoothness, do not delay incoming samples
00274     definition->SynchronousDetectionEnabled = false;
00275
00276     // In this scenario, choose detection speed over accuracy
00277     definition->DetectionMode = FaceDetectionMode::HighPerformance;
00278
00279     // Add the effect to the preview stream
00280     return create_task(_mediaCapture->AddVideoEffectAsync(definition, Capture::MediaStreamType::VideoPreview))
00281         .then([this](IMediaExtension^ extension)
00282     {
00283         _faceDetectionEffect = static_cast<FaceDetectionEffect^>(extension);
00284
00285         // Register for face detection events
00286         _faceDetectedEventToken =
00287             _faceDetectionEffect->FaceDetected += ref new TypedEventHandler<FaceDetectionEffect^, FaceDetectedEventArgs^>(this, &MainPage::FaceDetectionEffect_FaceDetected);
00288
00289         // Choose the shortest interval between detection events
00290         Windows::Foundation::TimeSpan duration = Windows::Foundation::TimeSpan();
00291         duration.Duration = 330000; // hundreds of nanoseconds (33ms)
00292         _faceDetectionEffect->DesiredDetectionInterval = duration;
00293
00294         // Start detecting faces
00295         _faceDetectionEffect->Enabled = true;
00296     });
00297 }
00298
00299 /// <summary>
00300 ///  Disables and removes the face detection effect, and unregisters the event handler for face detection
00301 /// </summary>
00302 /// <returns></returns>
00303 task<void> MainPage::CleanUpFaceDetectionEffectAsync()
00304 {
00305     // Disable detection
00306     _faceDetectionEffect->Enabled = false;
00307
00308     // Unregister the event handler
00309     _faceDetectionEffect->FaceDetected -= _faceDetectedEventToken;
00310
00311     // Remove the effect (see ClearEffectsAsync method to remove all effects from a stream)
00312     return create_task(_mediaCapture->RemoveEffectAsync(_faceDetectionEffect))
00313         .then([this]()
00314     {
00315         // Clear the member variable that held the effect instance
00316         _faceDetectionEffect = nullptr;
00317     });
00318 }
00319
00320 /// <summary>
00321 /// Takes a photo to a StorageFile and adds rotation metadata to it
00322 /// </summary>
00323 /// <returns></returns>
00324 task<void> MainPage::TakePhotoAsync()
00325 {
00326     // While taking a photo, keep the video button enabled only if the camera supports simultaneously taking pictures and recording video
00327     VideoButton->IsEnabled = _mediaCapture->MediaCaptureSettings->ConcurrentRecordAndPhotoSupported;
00328     // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
00329     VideoButton->Opacity = VideoButton->IsEnabled ? 1 : 0;
00330
00331     auto inputStream = ref new Streams::InMemoryRandomAccessStream();
00332
00333     // Take the picture
00334     WriteLine("Taking photo...");
00335     return create_task(_mediaCapture->CapturePhotoToStreamAsync(Windows::Media::MediaProperties::ImageEncodingProperties::CreateJpeg(), inputStream))
00336         .then([this, inputStream]()
00337     {
00338         return create_task(_captureFolder->CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption::GenerateUniqueName));
00339     }).then([this, inputStream](StorageFile^ file)
00340     {
00341         WriteLine("Photo taken! Saving to " + file->Path);
00342
00343         // Done taking a photo, so re-enable the button
00344         VideoButton->IsEnabled = true;
00345         VideoButton->Opacity = 1;
00346
00347         auto photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
00348         return ReencodeAndSavePhotoAsync(inputStream, file, photoOrientation);
00349     }).then([this](task<void> previousTask)
00350     {
00351         try
00352         {
00353             previousTask.get();
00354         }
00355         catch (Exception^ ex)
00356         {
00357             // File I/O errors are reported as exceptions
00358             WriteException(ex);
00359         }
00360     });
00361 }
00362
00363 /// <summary>
00364 /// Records an MP4 video to a StorageFile and adds rotation metadata to it
00365 /// </summary>
00366 /// <returns></returns>
00367 task<void> MainPage::StartRecordingAsync()
00368 {
00369     return create_task(_captureFolder->CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption::GenerateUniqueName))
00370         .then([this](StorageFile^ file)
00371     {
00372         // Calculate rotation angle, taking mirroring into account if necessary
00373         auto rotationAngle = 360 - ConvertDeviceOrientationToDegrees(GetCameraOrientation());
00374         auto encodingProfile = MediaProperties::MediaEncodingProfile::CreateMp4(MediaProperties::VideoEncodingQuality::Auto);
00375         encodingProfile->Video->Properties->Insert(RotationKey, rotationAngle);
00376
00377         return create_task(_mediaCapture->StartRecordToStorageFileAsync(encodingProfile, file))
00378             .then([this, file]()
00379         {
00380             _isRecording = true;
00381             WriteLine("Started recording to " + file->Path);
00382         });
00383     }).then([this](task<void> previousTask)
00384     {
00385         try
00386         {
00387             previousTask.get();
00388         }
00389         catch (Exception^ ex)
00390         {
00391             // File I/O errors are reported as exceptions
00392             WriteException(ex);
00393         }
00394     });
00395 }
00396
00397 /// <summary>
00398 /// Stops recording a video
00399 /// </summary>
00400 /// <returns></returns>
00401 task<void> MainPage::StopRecordingAsync()
00402 {
00403     _isRecording = false;
00404
00405     WriteLine("Stopping recording...");
00406     return create_task(_mediaCapture->StopRecordAsync())
00407         .then([this]()
00408     {
00409         WriteLine("Stopped recording!");
00410     });
00411 }
00412
00413 /// <summary>
00414 /// Attempts to find and return a device mounted on the panel specified, and on failure to find one it will return the first device listed
00415 /// </summary>
00416 /// <param name="panel">The desired panel on which the returned device should be mounted, if available</param>
00417 /// <returns></returns>
00418 task<DeviceInformation^> MainPage::FindCameraDeviceByPanelAsync(Windows::Devices::Enumeration::Panel panel)
00419 {
00420     // Get available devices for capturing pictures
00421     auto allVideoDevices = DeviceInformation::FindAllAsync(DeviceClass::VideoCapture);
00422
00423     auto deviceEnumTask = create_task(allVideoDevices);
00424     return deviceEnumTask.then([panel](DeviceInformationCollection^ devices)
00425     {
00426         for (auto cameraDeviceInfo : devices)
00427         {
00428             if (cameraDeviceInfo->EnclosureLocation != nullptr && cameraDeviceInfo->EnclosureLocation->Panel == panel)
00429             {
00430                 return cameraDeviceInfo;
00431             }
00432         }
00433
00434         // Nothing matched, just return the first
00435         if (devices->Size > 0)
00436         {
00437             return devices->GetAt(0);
00438         }
00439
00440         // We didn't find any devices, so return a null instance
00441         DeviceInformation^ camera = nullptr;
00442         return camera;
00443     });
00444 }
00445
00446 /// <summary>
00447 /// Applies the given orientation to a photo stream and saves it as a StorageFile
00448 /// </summary>
00449 /// <param name="stream">The photo stream</param>
00450 /// <param name="file">The StorageFile in which the photo stream will be saved</param>
00451 /// <param name="photoOrientation">The orientation metadata to apply to the photo</param>
00452 /// <returns></returns>
00453 task<void> MainPage::ReencodeAndSavePhotoAsync(Streams::IRandomAccessStream^ stream, StorageFile^ file, FileProperties::PhotoOrientation photoOrientation)
00454 {
00455     // Using this state variable to pass multiple values through our task chain
00456     ReencodeState^ state = ref new ReencodeState();
00457     state->File = file;
00458     state->Orientation = photoOrientation;
00459
00460     return create_task(BitmapDecoder::CreateAsync(stream))
00461         .then([state](BitmapDecoder^ decoder)
00462     {
00463         state->Decoder = decoder;
00464         return create_task(state->File->OpenAsync(FileAccessMode::ReadWrite));
00465     }).then([state](Streams::IRandomAccessStream^ outputStream)
00466     {
00467         return create_task(BitmapEncoder::CreateForTranscodingAsync(outputStream, state->Decoder));
00468     }).then([state](BitmapEncoder^ encoder)
00469     {
00470         state->Encoder = encoder;
00471         auto properties = ref new Windows::Graphics::Imaging::BitmapPropertySet();
00472         properties->Insert("System.Photo.Orientation", ref new BitmapTypedValue((unsigned short)state->Orientation, Windows::Foundation::PropertyType::UInt16));
00473
00474         return create_task(state->Encoder->BitmapProperties->SetPropertiesAsync(properties));
00475     }).then([state]()
00476     {
00477         return state->Encoder->FlushAsync();
00478     });
00479 }
00480
00481 /// <summary>
00482 /// This method will update the icons, enable/disable and show/hide the photo/video buttons depending on the current state of the app and the capabilities of the device
00483 /// </summary>
00484 void MainPage::UpdateCaptureControls()
00485 {
00486     // The buttons should only be enabled if the preview started sucessfully
00487     PhotoButton->IsEnabled = _previewProperties != nullptr;
00488     VideoButton->IsEnabled = _previewProperties != nullptr;
00489     FaceDetectionButton->IsEnabled = _previewProperties != nullptr;
00490
00491     // Update the face detection icon depending on whether the effect exists or not
00492     FaceDetectionDisabledIcon->Visibility = (_faceDetectionEffect == nullptr ||
00493         !_faceDetectionEffect->Enabled) ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00494     FaceDetectionEnabledIcon->Visibility = (_faceDetectionEffect != nullptr &&
00495         _faceDetectionEffect->Enabled) ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00496
00497     // Hide the face detection canvas and clear it
00498     FacesCanvas->Visibility = (_faceDetectionEffect != nullptr &&
00499         _faceDetectionEffect->Enabled) ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00500
00501     // Update recording button to show "Stop" icon instead of red "Record" icon
00502     StartRecordingIcon->Visibility = _isRecording ? Windows::UI::Xaml::Visibility::Collapsed : Windows::UI::Xaml::Visibility::Visible;
00503     StopRecordingIcon->Visibility = _isRecording ? Windows::UI::Xaml::Visibility::Visible : Windows::UI::Xaml::Visibility::Collapsed;
00504
00505     // If the camera doesn't support simultaneously taking pictures and recording video, disable the photo button on record
00506     if (_isInitialized && !_mediaCapture->MediaCaptureSettings->ConcurrentRecordAndPhotoSupported)
00507     {
00508         PhotoButton->IsEnabled = !_isRecording;
00509
00510         // Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
00511         PhotoButton->Opacity = PhotoButton->IsEnabled ? 1 : 0;
00512     }
00513 }
00514
00515 /// <summary>
00516 /// Attempts to lock the page orientation, hide the StatusBar (on Phone) and registers event handlers for hardware buttons and orientation sensors
00517 /// </summary>
00518 /// <returns></returns>
00519 task<void> MainPage::SetupUiAsync()
00520 {
00521     // Attempt to lock page to landscape orientation to prevent the CaptureElement from rotating, as this gives a better experience
00522     DisplayInformation::AutoRotationPreferences = DisplayOrientations::Landscape;
00523
00524     RegisterEventHandlers();
00525
00526     // Populate orientation variables with the current state
00527     _displayOrientation = _displayInformation->CurrentOrientation;
00528     if (_orientationSensor != nullptr)
00529     {
00530         _deviceOrientation = _orientationSensor->GetCurrentOrientation();
00531     }
00532
00533     create_task(StorageLibrary::GetLibraryAsync(KnownLibraryId::Pictures))
00534         .then([this](StorageLibrary^ picturesLibrary)
00535     {
00536         _captureFolder = picturesLibrary->SaveFolder;
00537         if (_captureFolder == nullptr)
00538         {
00539             // In this case fall back to the local app storage since the Pictures Library is not available
00540             _captureFolder = ApplicationData::Current->LocalFolder;
00541         }
00542     });
00543
00544     // Hide the status bar
00545     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00546     {
00547         return create_task(Windows::UI::ViewManagement::StatusBar::GetForCurrentView()->HideAsync());
00548     }
00549     else
00550     {
00551         return EmptyTask();
00552     }
00553 }
00554
00555 /// <summary>
00556 /// Unregisters event handlers for hardware buttons and orientation sensors, allows the StatusBar (on Phone) to show, and removes the page orientation lock
00557 /// </summary>
00558 /// <returns></returns>
00559 task<void> MainPage::CleanupUiAsync()
00560 {
00561     UnregisterEventHandlers();
00562
00563     // Revert orientation preferences
00564     DisplayInformation::AutoRotationPreferences = DisplayOrientations::None;
00565
00566     // Show the status bar
00567     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
00568     {
00569         return create_task(Windows::UI::ViewManagement::StatusBar::GetForCurrentView()->ShowAsync());
00570     }
00571     else
00572     {
00573         return EmptyTask();
00574     }
00575 }
00576
00577 /// <summary>
00578 /// Registers event handlers for hardware buttons and orientation sensors, and performs an initial update of the UI rotation
00579 /// </summary>
00580 void MainPage::RegisterEventHandlers()
00581 {
00582     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00583     {
00584         _hardwareCameraButtonEventToken =
00585             HardwareButtons::CameraPressed += ref new Windows::Foundation::EventHandler<CameraEventArgs^>(this, &MainPage::HardwareButtons_CameraPress);
00586     }
00587
00588     // If there is an orientation sensor present on the device, register for notifications
00589     if (_orientationSensor != nullptr)
00590     {
00591         _orientationChangedEventToken =
00592             _orientationSensor->OrientationChanged += ref new TypedEventHandler<SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^>(this, &MainPage::OrientationSensor_OrientationChanged);
00593
00594         // Update orientation of buttons with the current orientation
00595         UpdateButtonOrientation();
00596     }
00597
00598     _displayInformationEventToken =
00599         _displayInformation->OrientationChanged += ref new TypedEventHandler<DisplayInformation^, Object^>(this, &MainPage::DisplayInformation_OrientationChanged);
00600
00601     _mediaControlPropChangedEventToken =
00602         _systemMediaControls->PropertyChanged += ref new TypedEventHandler<SystemMediaTransportControls^, SystemMediaTransportControlsPropertyChangedEventArgs^>(this, &MainPage::SystemMediaControls_PropertyChanged);
00603 }
00604
00605 /// <summary>
00606 /// Unregisters event handlers for hardware buttons and orientation sensors
00607 /// </summary>
00608 void MainPage::UnregisterEventHandlers()
00609 {
00610     if (Windows::Foundation::Metadata::ApiInformation::IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
00611     {
00612         HardwareButtons::CameraPressed -= _hardwareCameraButtonEventToken;
00613     }
00614
00615     if (_orientationSensor != nullptr)
00616     {
00617         _orientationSensor->OrientationChanged -= _orientationChangedEventToken;
00618     }
00619
00620     _displayInformation->OrientationChanged -= _displayInformationEventToken;
00621     _systemMediaControls->PropertyChanged -= _mediaControlPropChangedEventToken;
00622 }
00623
00624 /// <summary>
00625 /// Writes a given string to the output window
00626 /// </summary>
00627 /// <param name="str">String to be written</param>
00628 void MainPage::WriteLine(String^ str)
00629 {
00630     std::wstringstream wStringstream;
00631     wStringstream << str->Data() << "\n";
00632     OutputDebugString(wStringstream.str().c_str());
00633 }
00634
00635 /// <summary>
00636 /// Writes a given exception message and hresult to the output window
00637 /// </summary>
00638 /// <param name="ex">Exception to be written</param>
00639 void MainPage::WriteException(Exception^ ex)
00640 {
00641     std::wstringstream wStringstream;
00642     wStringstream << "0x" << ex->HResult << ": " << ex->Message->Data();
00643     OutputDebugString(wStringstream.str().c_str());
00644 }
00645
00646 /// <summary>
00647 /// Sometimes we need to conditionally return a task. If certain parameters are not met we cannot
00648 /// return null, but we can return a task that does nothing.
00649 /// </summary>
00650 /// <returns></returns>
00651 task<void> MainPage::EmptyTask()
00652 {
00653     return create_task([] {});
00654 }
00655
00656 /// <summary>
00657 /// Calculates the current camera orientation from the device orientation by taking into account whether the camera is external or facing the user
00658 /// </summary>
00659 /// <returns>The camera orientation in space, with an inverted rotation in the case the camera is mounted on the device and is facing the user</returns>
00660 SimpleOrientation MainPage::GetCameraOrientation()
00661 {
00662     if (_externalCamera)
00663     {
00664         // Cameras that are not attached to the device do not rotate along with it, so apply no rotation
00665         return SimpleOrientation::NotRotated;
00666     }
00667
00668     auto result = _deviceOrientation;
00669
00670     // Account for the fact that, on portrait-first devices, the camera sensor is mounted at a 90 degree offset to the native orientation
00671     if (_displayInformation->NativeOrientation == DisplayOrientations::Portrait)
00672     {
00673         switch (result)
00674         {
00675         case SimpleOrientation::Rotated90DegreesCounterclockwise:
00676             result = SimpleOrientation::NotRotated;
00677             break;
00678         case SimpleOrientation::Rotated180DegreesCounterclockwise:
00679             result = SimpleOrientation::Rotated90DegreesCounterclockwise;
00680             break;
00681         case SimpleOrientation::Rotated270DegreesCounterclockwise:
00682             result = SimpleOrientation::Rotated180DegreesCounterclockwise;
00683             break;
00684         case SimpleOrientation::NotRotated:
00685         default:
00686             result = SimpleOrientation::Rotated270DegreesCounterclockwise;
00687             break;
00688         }
00689     }
00690
00691     // If the preview is being mirrored for a front-facing camera, then the rotation should be inverted
00692     if (_mirroringPreview)
00693     {
00694         // This only affects the 90 and 270 degree cases, because rotating 0 and 180 degrees is the same clockwise and counter-clockwise
00695         switch (result)
00696         {
00697         case SimpleOrientation::Rotated90DegreesCounterclockwise:
00698             return SimpleOrientation::Rotated270DegreesCounterclockwise;
00699         case SimpleOrientation::Rotated270DegreesCounterclockwise:
00700             return SimpleOrientation::Rotated90DegreesCounterclockwise;
00701         }
00702     }
00703
00704     return result;
00705 }
00706
00707 /// <summary>
00708 /// Converts the given orientation of the device in space to the metadata that can be added to captured photos
00709 /// </summary>
00710 /// <param name="orientation">The orientation of the device in space</param>
00711 /// <returns></returns>
00712 FileProperties::PhotoOrientation MainPage::ConvertOrientationToPhotoOrientation(SimpleOrientation orientation)
00713 {
00714     switch (orientation)
00715     {
00716     case SimpleOrientation::Rotated90DegreesCounterclockwise:
00717         return FileProperties::PhotoOrientation::Rotate90;
00718     case SimpleOrientation::Rotated180DegreesCounterclockwise:
00719         return FileProperties::PhotoOrientation::Rotate180;
00720     case SimpleOrientation::Rotated270DegreesCounterclockwise:
00721         return FileProperties::PhotoOrientation::Rotate270;
00722     case SimpleOrientation::NotRotated:
00723     default:
00724         return FileProperties::PhotoOrientation::Normal;
00725     }
00726 }
00727
00728 /// <summary>
00729 /// Converts the given orientation of the device in space to the corresponding rotation in degrees
00730 /// </summary>
00731 /// <param name="orientation">The orientation of the device in space</param>
00732 /// <returns>An orientation in degrees</returns>
00733 int MainPage::ConvertDeviceOrientationToDegrees(SimpleOrientation orientation)
00734 {
00735     switch (orientation)
00736     {
00737     case SimpleOrientation::Rotated90DegreesCounterclockwise:
00738         return 90;
00739     case SimpleOrientation::Rotated180DegreesCounterclockwise:
00740         return 180;
00741     case SimpleOrientation::Rotated270DegreesCounterclockwise:
00742         return 270;
00743     case SimpleOrientation::NotRotated:
00744     default:
00745         return 0;
00746     }
00747 }
00748
00749 /// <summary>
00750 /// Converts the given orientation of the app on the screen to the corresponding rotation in degrees
00751 /// </summary>
00752 /// <param name="orientation">The orientation of the app on the screen</param>
00753 /// <returns>An orientation in degrees</returns>
00754 int MainPage::ConvertDisplayOrientationToDegrees(DisplayOrientations orientation)
00755 {
00756     switch (orientation)
00757     {
00758     case DisplayOrientations::Portrait:
00759         return 90;
00760     case DisplayOrientations::LandscapeFlipped:
00761         return 180;
00762     case DisplayOrientations::PortraitFlipped:
00763         return 270;
00764     case DisplayOrientations::Landscape:
00765     default:
00766         return 0;
00767     }
00768 }
00769
00770 /// <summary>
00771 /// Uses the current device orientation in space and page orientation on the screen to calculate the rotation
00772 /// transformation to apply to the controls
00773 /// </summary>
00774 void MainPage::UpdateButtonOrientation()
00775 {
00776     int device = ConvertDeviceOrientationToDegrees(_deviceOrientation);
00777     int display = ConvertDisplayOrientationToDegrees(_displayOrientation);
00778
00779     if (_displayInformation->NativeOrientation == DisplayOrientations::Portrait)
00780     {
00781         device -= 90;
00782     }
00783
00784     // Combine both rotations and make sure that 0 <= result < 360
00785     auto angle = (360 + display + device) % 360;
00786
00787     // Rotate the buttons in the UI to match the rotation of the device
00788     auto transform = ref new RotateTransform();
00789     transform->Angle = angle;
00790
00791     // The RenderTransform is safe to use (i.e. it won't cause layout issues) in this case, because these buttons have a 1:1 aspect ratio
00792     PhotoButton->RenderTransform = transform;
00793     VideoButton->RenderTransform = transform;
00794     FaceDetectionButton->RenderTransform = transform;
00795 }
00796
00797 /// <summary>
00798 /// Uses the current display orientation to calculate the rotation transformation to apply to the face detection bounding box canvas
00799 /// and mirrors it if the preview is being mirrored
00800 /// </summary>
00801 void MainPage::SetFacesCanvasRotation()
00802 {
00803     // Calculate how much to rotate the canvas
00804     int rotationDegrees = ConvertDisplayOrientationToDegrees(_displayOrientation);
00805
00806     // The rotation direction needs to be inverted if the preview is being mirrored, just like in SetPreviewRotationAsync
00807     if (_mirroringPreview)
00808     {
00809         rotationDegrees = (360 - rotationDegrees) % 360;
00810     }
00811
00812     // Apply the rotation
00813     auto transform = ref new RotateTransform();
00814     transform->Angle = rotationDegrees;
00815     FacesCanvas->RenderTransform = transform;
00816
00817     auto previewArea = GetPreviewStreamRectInControl(static_cast<MediaProperties::VideoEncodingProperties^>(_previewProperties), PreviewControl);
00818
00819     // For portrait mode orientations, swap the width and height of the canvas after the rotation, so the control continues to overlap the preview
00820     if (_displayOrientation == DisplayOrientations::Portrait || _displayOrientation == DisplayOrientations::PortraitFlipped)
00821     {
00822         FacesCanvas->Width = previewArea.Height;
00823         FacesCanvas->Height = previewArea.Width;
00824
00825         // The position of the canvas also needs to be adjusted, as the size adjustment affects the centering of the control
00826         Canvas::SetLeft(FacesCanvas, previewArea.X - (previewArea.Height - previewArea.Width) / 2);
00827         Canvas::SetTop(FacesCanvas, previewArea.Y - (previewArea.Width - previewArea.Height) / 2);
00828     }
00829     else
00830     {
00831         FacesCanvas->Width = previewArea.Width;
00832         FacesCanvas->Height = previewArea.Height;
00833
00834         Canvas::SetLeft(FacesCanvas, previewArea.X);
00835         Canvas::SetTop(FacesCanvas, previewArea.Y);
00836     }
00837
00838     // Also mirror the canvas if the preview is being mirrored
00839     FacesCanvas->FlowDirection = _mirroringPreview ? Windows::UI::Xaml::FlowDirection::RightToLeft : Windows::UI::Xaml::FlowDirection::LeftToRight;
00840 }
00841
00842 /// <summary>
00843 /// Iterates over all detected faces, creating and adding Rectangles to the FacesCanvas as face bounding boxes
00844 /// </summary>
00845 /// <param name="faces">The list of detected faces from the FaceDetected event of the effect</param>
00846 void MainPage::HighlightDetectedFaces(Windows::Foundation::Collections::IVectorView<DetectedFace^>^ faces)
00847 {
00848     // Remove any existing rectangles from previous events
00849     FacesCanvas->Children->Clear();
00850
00851     // For each detected face
00852     for (unsigned int i = 0; i < faces->Size; i++)
00853     {
00854         // Face coordinate units are preview resolution pixels, which can be a different scale from our display resolution, so a conversion may be necessary
00855         Rectangle^ faceBoundingBox = ConvertPreviewToUiRectangle(faces->GetAt(i)->FaceBox);
00856
00857         // Set bounding box stroke properties
00858         faceBoundingBox->StrokeThickness = 2;
00859
00860         // Highlight the first face in the set
00861         faceBoundingBox->Stroke = (i == 0 ? ref new SolidColorBrush(Windows::UI::Colors::Blue) : ref new SolidColorBrush(Windows::UI::Colors::DeepSkyBlue));
00862
00863         // Add grid to canvas containing all face UI objects
00864         FacesCanvas->Children->Append(faceBoundingBox);
00865     }
00866
00867     // Update the face detection bounding box canvas orientation
00868     SetFacesCanvasRotation();
00869 }
00870
00871 /// <summary>
00872 /// Takes face information defined in preview coordinates and returns one in UI coordinates, taking
00873 /// into account the position and size of the preview control.
00874 /// </summary>
00875 /// <param name="faceBoxInPreviewCoordinates">Face coordinates as retried from the FaceBox property of a DetectedFace, in preview coordinates.</param>
00876 /// <returns>Rectangle in UI (CaptureElement) coordinates, to be used in a Canvas control.</returns>
00877 Rectangle^ MainPage::ConvertPreviewToUiRectangle(BitmapBounds faceBoxInPreviewCoordinates)
00878 {
00879     auto result = ref new Rectangle();
00880     auto previewStream = static_cast<MediaProperties::VideoEncodingProperties^>(_previewProperties);
00881
00882     // If there is no available information about the preview, return an empty rectangle, as re-scaling to the screen coordinates will be impossible
00883     if (previewStream == nullptr)
00884     {
00885         return result;
00886     }
00887
00888     // Similarly, if any of the dimensions is zero (which would only happen in an error case) return an empty rectangle
00889     if (previewStream->Width == 0 || previewStream->Height == 0)
00890     {
00891         return result;
00892     }
00893
00894     double streamWidth = previewStream->Width;
00895     double streamHeight = previewStream->Height;
00896
00897     // For portrait orientations, the width and height need to be swapped
00898     if (_displayOrientation == DisplayOrientations::Portrait || _displayOrientation == DisplayOrientations::PortraitFlipped)
00899     {
00900         streamHeight = previewStream->Width;
00901         streamWidth = previewStream->Height;
00902     }
00903
00904     auto previewInUI = GetPreviewStreamRectInControl(previewStream, PreviewControl);
00905
00906     // Scale the width and height from preview stream coordinates to window coordinates
00907     result->Width = (faceBoxInPreviewCoordinates.Width / streamWidth) * previewInUI.Width;
00908     result->Height = (faceBoxInPreviewCoordinates.Height / streamHeight) * previewInUI.Height;
00909
00910     // Scale the X and Y coordinates from preview stream coordinates to window coordinates
00911     auto x = (faceBoxInPreviewCoordinates.X / streamWidth) * previewInUI.Width;
00912     auto y = (faceBoxInPreviewCoordinates.Y / streamHeight) * previewInUI.Height;
00913     Canvas::SetLeft(result, x);
00914     Canvas::SetTop(result, y);
00915
00916     return result;
00917 }
00918
00919 /// <summary>
00920 /// Calculates the size and location of the rectangle that contains the preview stream within the preview control, when the scaling mode is Uniform
00921 /// </summary>
00922 /// <param name="previewResolution">The resolution at which the preview is running</param>
00923 /// <param name="previewControl">The control that is displaying the preview using Uniform as the scaling mode</param>
00924 /// <returns></returns>
00925 Windows::Foundation::Rect MainPage::GetPreviewStreamRectInControl(MediaProperties::VideoEncodingProperties^ previewResolution, Controls::CaptureElement^ previewControl)
00926 {
00927     // In case this function is called before everything is initialized correctly, return an empty result
00928     if (previewControl == nullptr || previewControl->ActualHeight < 1 || previewControl->ActualWidth < 1 ||
00929         previewResolution == nullptr || previewResolution->Height == 0 || previewResolution->Width == 0)
00930     {
00931         return RectHelper::FromCoordinatesAndDimensions(0, 0, 0, 0);
00932     }
00933
00934     auto streamWidth = previewResolution->Width;
00935     auto streamHeight = previewResolution->Height;
00936
00937     // For portrait orientations, the width and height need to be swapped
00938     if (_displayOrientation == DisplayOrientations::Portrait || _displayOrientation == DisplayOrientations::PortraitFlipped)
00939     {
00940         streamWidth = previewResolution->Height;
00941         streamHeight = previewResolution->Width;
00942     }
00943
00944     // Start by assuming the preview display area in the control spans the entire width and height both (this is corrected in the next if for the necessary dimension)
00945     auto width = previewControl->ActualWidth;
00946     auto height = previewControl->ActualHeight;
00947     double x = 0.0;
00948     double y = 0.0;
00949
00950     // If UI is "wider" than preview, letterboxing will be on the sides
00951     if ((previewControl->ActualWidth / previewControl->ActualHeight > streamWidth / static_cast<double>(streamHeight)))
00952     {
00953         auto scale = previewControl->ActualHeight / streamHeight;
00954         auto scaledWidth = streamWidth * scale;
00955
00956         x = (previewControl->ActualWidth - scaledWidth) / 2.0;
00957         width = scaledWidth;
00958     }
00959     else // Preview stream is "wider" than UI, so letterboxing will be on the top+bottom
00960     {
00961         auto scale = previewControl->ActualWidth / streamWidth;
00962         auto scaledHeight = streamHeight * scale;
00963
00964         y = static_cast<float>((previewControl->ActualHeight - scaledHeight) / 2.0);
00965         height = scaledHeight;
00966     }
00967
00968     return RectHelper::FromCoordinatesAndDimensions(
00969         static_cast<float>(x),
00970         static_cast<float>(y),
00971         static_cast<float>(width),
00972         static_cast<float>(height));
00973 }
00974
00975 void MainPage::Application_Suspending(Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e)
00976 {
00977     // Handle global application events only if this page is active
00978     if (Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name)
00979     {
00980         auto deferral = e->SuspendingOperation->GetDeferral();
00981         CleanupUiAsync()
00982             .then([this, deferral]()
00983         {
00984             CleanupCameraAsync();
00985         }).then([this, deferral]()
00986         {
00987             deferral->Complete();
00988         });
00989     }
00990 }
00991
00992 void MainPage::Application_Resuming(Platform::Object^ sender, Platform::Object^ args)
00993 {
00994     // Handle global application events only if this page is active
00995     if (Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name)
00996     {
00997         SetupUiAsync();
00998         InitializeCameraAsync();
00999     }
01000 }
01001
01002 /// <summary>
01003 /// This event will fire when the page is rotated, when the DisplayInformation.AutoRotationPreferences value set in the SetupUiAsync() method cannot be not honored.
01004 /// </summary>
01005 /// <param name="sender">The event source.</param>
01006 /// <param name="args">The event data.</param>
01007 void MainPage::DisplayInformation_OrientationChanged(DisplayInformation^ sender, Object^ args)
01008 {
01009     _displayOrientation = sender->CurrentOrientation;
01010
01011     if (_previewProperties != nullptr)
01012     {
01013         SetPreviewRotationAsync();
01014     }
01015
01016     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
01017     {
01018         UpdateButtonOrientation();
01019     }));
01020 }
01021
01022 void MainPage::PhotoButton_Click(Object^, Windows::UI::Xaml::RoutedEventArgs^)
01023 {
01024     TakePhotoAsync();
01025 }
01026
01027 void MainPage::VideoButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
01028 {
01029     task<void> taskToExecute;
01030     if (!_isRecording)
01031     {
01032         taskToExecute = StartRecordingAsync();
01033     }
01034     else
01035     {
01036         taskToExecute = StopRecordingAsync();
01037     }
01038
01039     taskToExecute.then([this](task<void> previousTask)
01040     {
01041         // After starting or stopping video recording, update the UI to reflect the MediaCapture state
01042         UpdateCaptureControls();
01043     });
01044 }
01045
01046 void MainPage::FaceDetectionButton_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
01047 {
01048     task<void> taskToExecute;
01049
01050     if (_faceDetectionEffect == nullptr || !_faceDetectionEffect->Enabled)
01051     {
01052         // Clear any rectangles that may have been left over from a previous instance of the effect
01053         FacesCanvas->Children->Clear();
01054
01055         taskToExecute = CreateFaceDetectionEffectAsync();
01056     }
01057     else
01058     {
01059         taskToExecute = CleanUpFaceDetectionEffectAsync();
01060     }
01061
01062     taskToExecute
01063         .then([this]()
01064     {
01065         UpdateCaptureControls();
01066     });
01067 }
01068
01069 /// <summary>
01070 /// In the event of the app being minimized this method handles media property change events. If the app receives a mute
01071 /// notification, it is no longer in the foregroud.
01072 /// </summary>
01073 /// <param name="sender"></param>
01074 /// <param name="args"></param>
01075 void MainPage::SystemMediaControls_PropertyChanged(SystemMediaTransportControls^ sender, SystemMediaTransportControlsPropertyChangedEventArgs^ args)
01076 {
01077     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, sender, args]()
01078     {
01079         // Only handle this event if this page is currently being displayed
01080         if (args->Property == SystemMediaTransportControlsProperty::SoundLevel && Frame->CurrentSourcePageType.Name == Interop::TypeName(MainPage::typeid).Name)
01081         {
01082             // Check to see if the app is being muted. If so, it is being minimized.
01083             // Otherwise if it is not initialized, it is being brought into focus.
01084             if (sender->SoundLevel == SoundLevel::Muted)
01085             {
01086                 CleanupCameraAsync();
01087             }
01088             else if (!_isInitialized)
01089             {
01090                 InitializeCameraAsync();
01091             }
01092         }
01093     }));
01094 }
01095
01096 /// <summary>
01097 /// Occurs each time the simple orientation sensor reports a new sensor reading.
01098 /// </summary>
01099 /// <param name="args">The event data.</param>
01100 void MainPage::OrientationSensor_OrientationChanged(SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^ args)
01101 {
01102     // If the device is parallel to the ground, keep the last orientation used. This allows users to take pictures of documents (FaceUp)
01103     // or the ceiling (FaceDown) in any orientation, by first holding the device in the desired orientation, and then pointing the camera
01104     // at the desired subject.
01105     if (args->Orientation != SimpleOrientation::Faceup && args->Orientation != SimpleOrientation::Facedown)
01106     {
01107         _deviceOrientation = args->Orientation;
01108
01109         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
01110         {
01111             UpdateButtonOrientation();
01112         }));
01113     }
01114 }
01115
01116 void MainPage::HardwareButtons_CameraPress(Platform::Object^, Windows::Phone::UI::Input::CameraEventArgs^)
01117 {
01118     TakePhotoAsync();
01119 }
01120
01121 /// <summary>
01122 /// This is a notification that recording has to stop, and the app is expected to finalize the recording
01123 /// </summary>
01124 /// <param name="args">The event data.</param>
01125 void MainPage::MediaCapture_RecordLimitationExceeded(Capture::MediaCapture^)
01126 {
01127     StopRecordingAsync()
01128         .then([this]()
01129     {
01130         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
01131         {
01132             UpdateCaptureControls();
01133         }));
01134     });
01135 }
01136
01137 void MainPage::MediaCapture_Failed(Capture::MediaCapture ^currentCaptureObject, Capture::MediaCaptureFailedEventArgs^ errorEventArgs)
01138 {
01139     std::wstringstream ss;
01140     ss << "MediaCapture_Failed: 0x" << errorEventArgs->Code << ": " << errorEventArgs->Message->Data();
01141     WriteLine(ref new String(ss.str().c_str()));
01142
01143     CleanupCameraAsync()
01144         .then([this]()
01145     {
01146         Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]()
01147         {
01148             UpdateCaptureControls();
01149         }));
01150     });
01151 }
01152
01153 void MainPage::FaceDetectionEffect_FaceDetected(Windows::Media::Core::FaceDetectionEffect^ sender, FaceDetectedEventArgs^ args)
01154 {
01155     // Ask the UI thread to render the face bounding boxes
01156     Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, args]()
01157     {
01158         HighlightDetectedFaces(args->ResultFrame->DetectedFaces);
01159     }));
01160 }
01161
01162 void MainPage::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
01163 {
01164     SetupUiAsync();
01165     InitializeCameraAsync();
01166 }
01167
01168 void MainPage::OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e)
01169 {
01170     // Handling of this event is included for completeness, as it will only fire when navigating between pages and this sample only includes one page
01171     CleanupCameraAsync();
01172     CleanupUiAsync();
01173 }
Generated on Fri Nov 15 2024 22:16:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cpp/SampleConfiguration.cpp Source File

  • Calendar
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00019 {
00020     { "Display a calendar", "SDKTemplate.Scenario1_Data" },
00021     { "Retrieve calendar statistics", "SDKTemplate.Scenario2_Stats" },
00022     { "Calendar enumeration and math", "SDKTemplate.Scenario3_Enum" },
00023     { "Calendar with Unicode extensions in languages", "SDKTemplate.Scenario4_UnicodeExtensions" },
00024     { "Calendar time zone support", "SDKTemplate.Scenario5_TimeZone" }
00025 };
Generated on Fri Nov 15 2024 22:17:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteLineSpacingModes/cpp/DWriteLineSpacingModes/Scenario3_ProportionalSpacing.xaml.h Source File

  • DWriteLineSpacingModes
  • cpp
  • DWriteLineSpacingModes

Scenario3_ProportionalSpacing.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_ProportionalSpacing.g.h"
00015
00016 using namespace DWriteTextLayoutImplementation;
00017
00018 namespace SDKTemplate
00019 {
00020     [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class Scenario3_ProportionalSpacing sealed
00022     {
00023     public:
00024         Scenario3_ProportionalSpacing();
00025
00026         // bindable view-model properties:
00027
00028         property bool IsFontLineGapUsageEnabled
00029         {
00030             bool get() { return (m_textLayout->FontLineGapUsage == FontLineGapUsage::Enabled); }
00031             void set(bool value);
00032         }
00033
00034         property double LineSpacingHeight
00035         {
00036             double get() { return static_cast<double>(m_textLayout->LineSpacingHeight); }
00037             void set(double value);
00038         }
00039
00040         property double LineSpacingBaseline
00041         {
00042             double get() { return static_cast<double>(m_textLayout->LineSpacingBaseline); }
00043             void set(double value);
00044         }
00045
00046         property double LineSpacingLeadingBefore
00047         {
00048             double get() { return static_cast<double>(m_textLayout->LineSpacingLeadingBefore); }
00049             void set(double value);
00050         }
00051
00052         property Platform::String^ TextLayoutHeight
00053         {
00054             Platform::String^ get() { return m_textLayoutLineMetrics[0]->height.ToString(); }
00055         }
00056
00057         property Platform::String^ TextLayoutBaseline
00058         {
00059             Platform::String^ get() { return m_textLayoutLineMetrics[0]->baseline.ToString(); }
00060         }
00061
00062         property Platform::String^ TextLayoutLeadingBefore
00063         {
00064             Platform::String^ get() { return m_textLayoutLineMetrics[0]->leadingBefore.ToString(); }
00065         }
00066
00067         property Platform::String^ TextLayoutLeadingAfter
00068         {
00069             Platform::String^ get() { return m_textLayoutLineMetrics[0]->leadingAfter.ToString(); }
00070         }
00071
00072     private:
00073         TextLayout^                                     m_textLayout;
00074         TextLayoutImageSource^                          m_textLayoutImageSource;
00075         Platform::Array<LineMetrics^>^                  m_textLayoutLineMetrics;
00076
00077         void SingleSpace_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00078         void OneAndHalfSpace_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00079         void DoubleSpace_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00080         void DoubleSpaceHalfLeading_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00081     };
00082 }
Generated on Fri Nov 15 2024 22:19:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SampleOverlay Member List

This is the complete list of members for SampleOverlay, including all inherited members.
CreateDeviceDependentResources() | SampleOverlay |
CreateWindowSizeDependentResources() | SampleOverlay |
GetTitleHeightInDips() | SampleOverlay |
m_caption | SampleOverlay | [private]
m_deviceResources | SampleOverlay | [private]
m_drawOverlay | SampleOverlay | [private]
m_idIncrement | SampleOverlay | [private]
m_logoBitmap | SampleOverlay | [private]
m_logoSize | SampleOverlay | [private]
m_overlayWidth | SampleOverlay | [private]
m_padding | SampleOverlay | [private]
m_stateBlock | SampleOverlay | [private]
m_textLayout | SampleOverlay | [private]
m_textVerticalOffset | SampleOverlay | [private]
m_whiteBrush | SampleOverlay | [private]
ReleaseDeviceDependentResources() | SampleOverlay |
Render() | SampleOverlay |
SampleOverlay(const std::shared_ptr< DX::DeviceResources > &deviceResources, const std::wstring &caption) | SampleOverlay |
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Account Member List

This is the complete list of members for Account, including all inherited members.
Email | Account
Name | Account
UsesPassport | Account
Generated on Fri Nov 15 2024 22:23:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

StepTimer Member List

This is the complete list of members for StepTimer, including all inherited members.
ElapsedSeconds | StepTimer |
ElapsedTicks | StepTimer |
FrameCount | StepTimer |
FramesPerSecond | StepTimer |
framesThisSecond | StepTimer | [private]
IsFixedTimeStep | StepTimer |
leftOverTicks | StepTimer | [private]
qpcFrequency | StepTimer | [private]
qpcLastTime | StepTimer | [private]
qpcMaxDelta | StepTimer | [private]
qpcSecondCounter | StepTimer | [private]
ResetElapsedTime() | StepTimer | [inline]
SecondsToTicks(double seconds) | StepTimer | [inline, private, static]
StepTimer() | StepTimer | [inline]
TargetElapsedSeconds | StepTimer |
TargetElapsedTicks | StepTimer |
Tick(Action update) | StepTimer | [inline]
TicksPerSecond | StepTimer | [private]
TicksToSeconds(long ticks) | StepTimer | [inline, private, static]
TotalSeconds | StepTimer |
TotalTicks | StepTimer |
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicFaceTracking/cppwinrt/SampleConfiguration.h Source File

  • BasicFaceTracking
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt
00016 {
00017     hstring to_hstring(Windows::Graphics::Imaging::BitmapPixelFormat format);
00018 }
00019
00020 namespace winrt::SDKTemplate
00021 {
00022 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaImport/cs/DataBinding/GeneratorIncrementalLoadingClass.cs Source File

  • MediaImport
  • cs
  • DataBinding

GeneratorIncrementalLoadingClass.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using System.Collections.Generic;
00013 using System.Linq;
00014 using System.Threading.Tasks;
00015
00016 namespace DataBinding
00017 {
00018     // This class implements IncrementalLoadingBase.
00019     // To create your own Infinite List, you can create a class like this one that doesn't have 'generator' or 'maxcount',
00020     //  and instead downloads items from a live data source in LoadMoreItemsOverrideAsync.
00021     public class GeneratorIncrementalLoadingClass<T> : IncrementalLoadingBase
00022     {
00023         public GeneratorIncrementalLoadingClass(uint maxCount, Func<int, T> generator)
00024         {
00025             _generator = generator;
00026             _maxCount = maxCount;
00027         }
00028
00029        protected async override Task<IList<object>> LoadMoreItemsOverrideAsync(System.Threading.CancellationToken c, uint count)
00030         {
00031             uint toGenerate = System.Math.Min(count, _maxCount - _count);
00032
00033             // This code simply generates
00034             var values = from j in Enumerable.Range((int)_count, (int)toGenerate)
00035                          select (object)_generator(j);
00036             _count += toGenerate;
00037
00038             return await Task.FromResult<IList<object>>(values.ToArray());
00039         }
00040
00041         protected override bool HasMoreItemsOverride()
00042         {
00043             return _count < _maxCount;
00044         }
00045
00046         #region State
00047
00048         Func<int, T> _generator;
00049         uint _count = 0;
00050         uint _maxCount;
00051
00052         #endregion
00053     }
00054 }
Generated on Fri Nov 15 2024 22:20:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BluetoothLE/cppwinrt/Scenario2_Client.cpp Source File

  • BluetoothLE
  • cppwinrt

Scenario2_Client.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Client.h"
00014 #include "Scenario2_Client.g.cpp"
00015 #include "SampleConfiguration.h"
00016 #include "BluetoothLEAttributeDisplay.h"
00017
00018 using namespace winrt;
00019 using namespace Windows::Devices::Bluetooth;
00020 using namespace Windows::Devices::Bluetooth::GenericAttributeProfile;
00021 using namespace Windows::Devices::Enumeration;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::Globalization;
00025 using namespace Windows::Security::Cryptography;
00026 using namespace Windows::Storage::Streams;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 namespace
00032 {
00033     void SetVisibility(UIElement const& element, bool visible)
00034     {
00035         element.Visibility(visible ? Visibility::Visible : Visibility::Collapsed);
00036     }
00037
00038     // Utility function to convert a string to an int32_t and detect bad input
00039     bool TryParseInt(const wchar_t* str, int32_t& result)
00040     {
00041         wchar_t* end;
00042         errno = 0;
00043         result = std::wcstol(str, &end, 0);
00044
00045         if (str == end)
00046         {
00047             // Not parseable.
00048             return false;
00049         }
00050
00051         if (errno == ERANGE || result < INT_MIN || INT_MAX < result)
00052         {
00053             // Out of range.
00054             return false;
00055         }
00056
00057         if (*end != L'\0')
00058         {
00059             // Extra unparseable characters at the end.
00060             return false;
00061         }
00062
00063         return true;
00064     }
00065
00066     template<typename T>
00067     T Read(DataReader const& reader);
00068
00069     template<>
00070     uint32_t Read<uint32_t>(DataReader const& reader)
00071     {
00072         return reader.ReadUInt32();
00073     }
00074
00075     template<>
00076     int32_t Read<int32_t>(DataReader const& reader)
00077     {
00078         return reader.ReadInt32();
00079     }
00080
00081     template<>
00082     uint8_t Read<uint8_t>(DataReader const& reader)
00083     {
00084         return reader.ReadByte();
00085     }
00086
00087     template<typename T>
00088     bool TryExtract(IBuffer const& buffer, T& result)
00089     {
00090         if (buffer.Length() >= sizeof(T))
00091         {
00092             DataReader reader = DataReader::FromBuffer(buffer);
00093             result = Read<T>(reader);
00094             return true;
00095         }
00096         return false;
00097     }
00098 }
00099
00100 namespace winrt
00101 {
00102     hstring to_hstring(GattCommunicationStatus status)
00103     {
00104         switch (status)
00105         {
00106         case GattCommunicationStatus::Success: return L"Success";
00107         case GattCommunicationStatus::Unreachable: return L"Unreachable";
00108         case GattCommunicationStatus::ProtocolError: return L"ProtocolError";
00109         case GattCommunicationStatus::AccessDenied: return L"AccessDenied";
00110         }
00111         return to_hstring(static_cast<int>(status));
00112     }
00113 }
00114
00115 namespace winrt::SDKTemplate::implementation
00116 {
00117 #pragma region UI Code
00118     Scenario2_Client::Scenario2_Client()
00119     {
00120         InitializeComponent();
00121     }
00122
00123     void Scenario2_Client::OnNavigatedTo(NavigationEventArgs const&)
00124     {
00125         SelectedDeviceRun().Text(SampleState::SelectedBleDeviceName);
00126         if (SampleState::SelectedBleDeviceId.empty())
00127         {
00128             ConnectButton().IsEnabled(false);
00129         }
00130     }
00131
00132     fire_and_forget Scenario2_Client::OnNavigatedFrom(NavigationEventArgs const&)
00133     {
00134         auto lifetime = get_strong();
00135         if (!co_await ClearBluetoothLEDeviceAsync())
00136         {
00137             rootPage.NotifyUser(L"Error: Unable to reset app state", NotifyType::ErrorMessage);
00138         }
00139     }
00140 #pragma endregion
00141
00142 #pragma region Enumerating Services
00143     IAsyncOperation<bool> Scenario2_Client::ClearBluetoothLEDeviceAsync()
00144     {
00145         auto lifetime = get_strong();
00146
00147         if (notificationsToken)
00148         {
00149             // Need to clear the CCCD from the remote device so we stop receiving notifications
00150             GattCommunicationStatus result = co_await registeredCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue::None);
00151             if (result != GattCommunicationStatus::Success)
00152             {
00153                 co_return false;
00154             }
00155             else
00156             {
00157                 selectedCharacteristic.ValueChanged(std::exchange(notificationsToken, {}));
00158             }
00159         }
00160
00161         if (bluetoothLeDevice != nullptr)
00162         {
00163             bluetoothLeDevice.Close();
00164             bluetoothLeDevice = nullptr;
00165         }
00166         co_return true;
00167     }
00168
00169     fire_and_forget Scenario2_Client::ConnectButton_Click()
00170     {
00171         auto lifetime = get_strong();
00172
00173         ConnectButton().IsEnabled(false);
00174
00175         if (!co_await ClearBluetoothLEDeviceAsync())
00176         {
00177             rootPage.NotifyUser(L"Error: Unable to reset state, try again.", NotifyType::ErrorMessage);
00178             ConnectButton().IsEnabled(true);
00179             co_return;
00180         }
00181
00182         try
00183         {
00184             // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
00185             bluetoothLeDevice = co_await BluetoothLEDevice::FromIdAsync(SampleState::SelectedBleDeviceId);
00186
00187             if (bluetoothLeDevice == nullptr)
00188             {
00189                 rootPage.NotifyUser(L"Failed to connect to device.", NotifyType::ErrorMessage);
00190             }
00191         }
00192         catch (hresult_error& ex)
00193         {
00194             if (ex.to_abi() == HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE))
00195             {
00196                 rootPage.NotifyUser(L"Bluetooth radio is not on.", NotifyType::ErrorMessage);
00197             }
00198             else
00199             {
00200                 throw;
00201             }
00202         }
00203
00204         if (bluetoothLeDevice != nullptr)
00205         {
00206             // Note: BluetoothLEDevice.GattServices property will return an empty list for unpaired devices. For all uses we recommend using the GetGattServicesAsync method.
00207             // BT_Code: GetGattServicesAsync returns a list of all the supported services of the device (even if it's not paired to the system).
00208             // If the services supported by the device are expected to change during BT usage, subscribe to the GattServicesChanged event.
00209             GattDeviceServicesResult result = co_await bluetoothLeDevice.GetGattServicesAsync(BluetoothCacheMode::Uncached);
00210
00211             if (result.Status() == GattCommunicationStatus::Success)
00212             {
00213                 IVectorView<GattDeviceService> services = result.Services();
00214                 rootPage.NotifyUser(L"Found " + to_hstring(services.Size()) + L" services", NotifyType::StatusMessage);
00215                 for (auto&& service : services)
00216                 {
00217                     ComboBoxItem item;
00218                     item.Content(box_value(DisplayHelpers::GetServiceName(service)));
00219                     item.Tag(service);
00220                     ServiceList().Items().Append(item);
00221                 }
00222                 ConnectButton().Visibility(Visibility::Collapsed);
00223                 ServiceList().Visibility(Visibility::Visible);
00224             }
00225             else
00226             {
00227                 rootPage.NotifyUser(L"Device unreachable", NotifyType::ErrorMessage);
00228             }
00229         }
00230         ConnectButton().IsEnabled(true);
00231     }
00232
00233 #pragma region Enumerating Characteristics
00234     fire_and_forget Scenario2_Client::ServiceList_SelectionChanged()
00235     {
00236         auto lifetime = get_strong();
00237
00238         auto selectedItem = ServiceList().SelectedItem().as<ComboBoxItem>();
00239         GattDeviceService service = selectedItem ? selectedItem.Tag().as<GattDeviceService>() : nullptr;
00240
00241         CharacteristicList().Items().Clear();
00242         RemoveValueChangedHandler();
00243
00244         IVectorView<GattCharacteristic> characteristics{ nullptr };
00245         try
00246         {
00247             // Ensure we have access to the device.
00248             auto accessStatus = co_await service.RequestAccessAsync();
00249             if (accessStatus == DeviceAccessStatus::Allowed)
00250             {
00251                 // BT_Code: Get all the child characteristics of a service. Use the cache mode to specify uncached characterstics only
00252                 // and the new Async functions to get the characteristics of unpaired devices as well.
00253                 GattCharacteristicsResult result = co_await service.GetCharacteristicsAsync(BluetoothCacheMode::Uncached);
00254                 if (result.Status() == GattCommunicationStatus::Success)
00255                 {
00256                     characteristics = result.Characteristics();
00257                 }
00258                 else
00259                 {
00260                     rootPage.NotifyUser(L"Error accessing service.", NotifyType::ErrorMessage);
00261                 }
00262             }
00263             else
00264             {
00265                 // Not granted access
00266                 rootPage.NotifyUser(L"Error accessing service.", NotifyType::ErrorMessage);
00267
00268             }
00269         }
00270         catch (hresult_error& ex)
00271         {
00272             rootPage.NotifyUser(L"Restricted service. Can't read characteristics: " + ex.message(), NotifyType::ErrorMessage);
00273         }
00274
00275         if (characteristics)
00276         {
00277             for (GattCharacteristic&& c : characteristics)
00278             {
00279                 ComboBoxItem item;
00280                 item.Content(box_value(DisplayHelpers::GetCharacteristicName(c)));
00281                 item.Tag(c);
00282                 CharacteristicList().Items().Append(item);
00283             }
00284         }
00285         CharacteristicList().Visibility(Visibility::Visible);
00286     }
00287 #pragma endregion
00288
00289     void Scenario2_Client::AddValueChangedHandler()
00290     {
00291         ValueChangedSubscribeToggle().Content(box_value(L"Unsubscribe from value changes"));
00292         if (!notificationsToken)
00293         {
00294             registeredCharacteristic = selectedCharacteristic;
00295             notificationsToken = registeredCharacteristic.ValueChanged({ get_weak(), &Scenario2_Client::Characteristic_ValueChanged });
00296         }
00297     }
00298     void Scenario2_Client::RemoveValueChangedHandler()
00299     {
00300         ValueChangedSubscribeToggle().Content(box_value(L"Subscribe to value changes"));
00301         if (notificationsToken)
00302         {
00303             registeredCharacteristic.ValueChanged(std::exchange(notificationsToken, {}));
00304             registeredCharacteristic = nullptr;
00305         }
00306     }
00307
00308     fire_and_forget Scenario2_Client::CharacteristicList_SelectionChanged()
00309     {
00310         auto lifetime = get_strong();
00311
00312         auto selectedItem = CharacteristicList().SelectedItem().as<ComboBoxItem>();
00313         selectedCharacteristic = selectedItem ? selectedItem.Tag().as<GattCharacteristic>() : nullptr;
00314
00315         if (selectedCharacteristic == nullptr)
00316         {
00317             EnableCharacteristicPanels(GattCharacteristicProperties::None);
00318             rootPage.NotifyUser(L"No characteristic selected", NotifyType::ErrorMessage);
00319             co_return;
00320         }
00321
00322         // Get all the child descriptors of a characteristics. Use the cache mode to specify uncached descriptors only
00323         // and the new Async functions to get the descriptors of unpaired devices as well.
00324         GattDescriptorsResult result = co_await selectedCharacteristic.GetDescriptorsAsync(BluetoothCacheMode::Uncached);
00325         if (result.Status() != GattCommunicationStatus::Success)
00326         {
00327             rootPage.NotifyUser(L"Descriptor read failure: " + to_hstring(result.Status()), NotifyType::ErrorMessage);
00328         }
00329
00330         // BT_Code: There's no need to access presentation format unless there's at least one.
00331         presentationFormat = nullptr;
00332         if (selectedCharacteristic.PresentationFormats().Size() > 0)
00333         {
00334
00335             if (selectedCharacteristic.PresentationFormats().Size() == 1)
00336             {
00337                 // Get the presentation format since there's only one way of presenting it
00338                 presentationFormat = selectedCharacteristic.PresentationFormats().GetAt(0);
00339             }
00340             else
00341             {
00342                 // It's difficult to figure out how to split up a characteristic and encode its different parts properly.
00343                 // In this case, we'll just encode the whole thing to a string to make it easy to print out.
00344             }
00345         }
00346
00347         // Enable/disable operations based on the GattCharacteristicProperties.
00348         EnableCharacteristicPanels(selectedCharacteristic.CharacteristicProperties());
00349     }
00350
00351     void Scenario2_Client::EnableCharacteristicPanels(GattCharacteristicProperties properties)
00352     {
00353         // BT_Code: Hide the controls which do not apply to this characteristic.
00354         SetVisibility(CharacteristicReadButton(),
00355             (properties & GattCharacteristicProperties::Read) != GattCharacteristicProperties::None);
00356
00357         SetVisibility(CharacteristicWritePanel(),
00358             (properties & (GattCharacteristicProperties::Write | GattCharacteristicProperties::WriteWithoutResponse)) != GattCharacteristicProperties::None);
00359         CharacteristicWriteValue().Text(L"");
00360
00361         SetVisibility(ValueChangedSubscribeToggle(),
00362             (properties & (GattCharacteristicProperties::Indicate | GattCharacteristicProperties::Notify)) != GattCharacteristicProperties::None);
00363     }
00364
00365     fire_and_forget Scenario2_Client::CharacteristicReadButton_Click()
00366     {
00367         auto lifetime = get_strong();
00368
00369         // BT_Code: Read the actual value from the device by using Uncached.
00370         GattReadResult result = co_await selectedCharacteristic.ReadValueAsync(BluetoothCacheMode::Uncached);
00371         if (result.Status() == GattCommunicationStatus::Success)
00372         {
00373             rootPage.NotifyUser(L"Read result: " + FormatValueByPresentation(result.Value(), presentationFormat), NotifyType::StatusMessage);
00374         }
00375         else
00376         {
00377             rootPage.NotifyUser(L"Read failed: Status = " + to_hstring(result.Status()), NotifyType::ErrorMessage);
00378         }
00379     }
00380
00381     fire_and_forget Scenario2_Client::CharacteristicWriteButton_Click()
00382     {
00383         auto lifetime = get_strong();
00384
00385         hstring text = CharacteristicWriteValue().Text();
00386         if (!text.empty())
00387         {
00388             IBuffer writeBuffer = CryptographicBuffer::ConvertStringToBinary(CharacteristicWriteValue().Text(), BinaryStringEncoding::Utf8);
00389
00390             co_await WriteBufferToSelectedCharacteristicAsync(writeBuffer);
00391         }
00392         else
00393         {
00394             rootPage.NotifyUser(L"No data to write to device", NotifyType::ErrorMessage);
00395         }
00396     }
00397
00398     fire_and_forget Scenario2_Client::CharacteristicWriteButtonInt_Click()
00399     {
00400         auto lifetime = get_strong();
00401
00402         int32_t readValue;
00403         if (TryParseInt(CharacteristicWriteValue().Text().begin(), readValue))
00404         {
00405             DataWriter writer;
00406             writer.ByteOrder(ByteOrder::LittleEndian);
00407             writer.WriteInt32(readValue);
00408
00409             co_await WriteBufferToSelectedCharacteristicAsync(writer.DetachBuffer());
00410         }
00411         else
00412         {
00413             rootPage.NotifyUser(L"Data to write has to be an int32", NotifyType::ErrorMessage);
00414         }
00415     }
00416
00417     IAsyncOperation<bool> Scenario2_Client::WriteBufferToSelectedCharacteristicAsync(IBuffer buffer)
00418     {
00419         auto lifetime = get_strong();
00420
00421         try
00422         {
00423             // BT_Code: Writes the value from the buffer to the characteristic.
00424             GattWriteResult result = co_await selectedCharacteristic.WriteValueWithResultAsync(buffer);
00425
00426             if (result.Status() == GattCommunicationStatus::Success)
00427             {
00428                 rootPage.NotifyUser(L"Successfully wrote value to device", NotifyType::StatusMessage);
00429                 co_return true;
00430             }
00431             else
00432             {
00433                 rootPage.NotifyUser(L"Write failed: Status = " + to_hstring(result.Status()), NotifyType::ErrorMessage);
00434                 co_return false;
00435             }
00436         }
00437         catch (hresult_error& ex)
00438         {
00439             if (ex.code() == E_BLUETOOTH_ATT_INVALID_PDU)
00440             {
00441                 rootPage.NotifyUser(ex.message(), NotifyType::ErrorMessage);
00442                 co_return false;
00443             }
00444             if (ex.code() == E_BLUETOOTH_ATT_WRITE_NOT_PERMITTED || ex.code() == E_ACCESSDENIED)
00445             {
00446                 // This usually happens when a device reports that it support writing, but it actually doesn't.
00447                 rootPage.NotifyUser(ex.message(), NotifyType::ErrorMessage);
00448                 co_return false;
00449             }
00450             throw;
00451         }
00452     }
00453
00454     fire_and_forget Scenario2_Client::ValueChangedSubscribeToggle_Click()
00455     {
00456         auto lifetime = get_strong();
00457
00458         if (!notificationsToken)
00459         {
00460             GattClientCharacteristicConfigurationDescriptorValue cccdValue = GattClientCharacteristicConfigurationDescriptorValue::None;
00461             if ((selectedCharacteristic.CharacteristicProperties() & GattCharacteristicProperties::Indicate) != GattCharacteristicProperties::None)
00462             {
00463                 cccdValue = GattClientCharacteristicConfigurationDescriptorValue::Indicate;
00464             }
00465
00466             else if ((selectedCharacteristic.CharacteristicProperties() & GattCharacteristicProperties::Notify) != GattCharacteristicProperties::None)
00467             {
00468                 cccdValue = GattClientCharacteristicConfigurationDescriptorValue::Notify;
00469             }
00470
00471             try
00472             {
00473                 // BT_Code: Must write the CCCD in order for server to send indications.
00474                 // We receive them in the ValueChanged event handler.
00475                 GattCommunicationStatus status = co_await selectedCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(cccdValue);
00476
00477                 if (status == GattCommunicationStatus::Success)
00478                 {
00479                     AddValueChangedHandler();
00480                     rootPage.NotifyUser(L"Successfully subscribed for value changes", NotifyType::StatusMessage);
00481                 }
00482                 else
00483                 {
00484                     rootPage.NotifyUser(L"Error registering for value changes: Status = " + to_hstring(status), NotifyType::ErrorMessage);
00485                 }
00486             }
00487             catch (hresult_access_denied& ex)
00488             {
00489                 // This usually happens when a device reports that it support indicate, but it actually doesn't.
00490                 rootPage.NotifyUser(ex.message(), NotifyType::ErrorMessage);
00491             }
00492         }
00493         else
00494         {
00495             try
00496             {
00497                 // BT_Code: Must write the CCCD in order for server to send notifications.
00498                 // We receive them in the ValueChanged event handler.
00499                 // Note that this sample configures either Indicate or Notify, but not both.
00500                 GattCommunicationStatus result = co_await
00501                     selectedCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
00502                         GattClientCharacteristicConfigurationDescriptorValue::None);
00503                 if (result == GattCommunicationStatus::Success)
00504                 {
00505                     RemoveValueChangedHandler();
00506                     rootPage.NotifyUser(L"Successfully un-registered for notifications", NotifyType::StatusMessage);
00507                 }
00508                 else
00509                 {
00510                     rootPage.NotifyUser(L"Error un-registering for notifications: Status = " + to_hstring(result), NotifyType::ErrorMessage);
00511                 }
00512             }
00513             catch (hresult_access_denied& ex)
00514             {
00515                 // This usually happens when a device reports that it support notify, but it actually doesn't.
00516                 rootPage.NotifyUser(ex.message(), NotifyType::ErrorMessage);
00517             }
00518         }
00519     }
00520
00521     fire_and_forget Scenario2_Client::Characteristic_ValueChanged(GattCharacteristic const&, GattValueChangedEventArgs args)
00522     {
00523         auto lifetime = get_strong();
00524
00525         // BT_Code: An Indicate or Notify reported that the value has changed.
00526         // Display the new value with a timestamp.
00527         hstring newValue = FormatValueByPresentation(args.CharacteristicValue(), presentationFormat);
00528         std::time_t now = clock::to_time_t(clock::now());
00529         char buffer[26];
00530         ctime_s(buffer, ARRAYSIZE(buffer), &now);
00531         hstring message = L"Value at " + to_hstring(buffer) + L": " + newValue;
00532         co_await resume_foreground(Dispatcher());
00533         CharacteristicLatestValue().Text(message);
00534     }
00535
00536     /// <summary>
00537     /// Process the raw data received from the device into application usable data,
00538     /// according the the Bluetooth Heart Rate Profile.
00539     /// https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.heart_rate_measurement.xml&u=org.bluetooth.characteristic.heart_rate_measurement.xml
00540     /// This function throws an std::out_of_range if the data cannot be parsed.
00541     /// </summary>
00542     /// <param name="data">Raw data received from the heart rate monitor.</param>
00543     /// <returns>The heart rate measurement value.</returns>
00544     int32_t ParseHeartRateValue(IBuffer const& buffer)
00545     {
00546         // Heart Rate profile defined flag values
00547         const uint8_t heartRateValueFormat = 0x1;
00548
00549         com_array<uint8_t> bytes;
00550         CryptographicBuffer::CopyToByteArray(buffer, bytes);
00551
00552         if (bytes.at(0) & heartRateValueFormat)
00553         {
00554             return bytes.at(1) | (bytes.at(2) << 8);
00555         }
00556         return bytes.at(1);
00557     }
00558
00559     hstring Scenario2_Client::FormatValueByPresentation(IBuffer const& buffer, GenericAttributeProfile::GattPresentationFormat const& format)
00560     {
00561         // BT_Code: For the purpose of this sample, this function converts only UInt32 and
00562         // UTF-8 buffers to readable text. It can be extended to support other formats if your app needs them.
00563         if (format != nullptr)
00564         {
00565             if (format.FormatType() == GattPresentationFormatTypes::UInt32())
00566             {
00567                 uint32_t value;
00568                 if (TryExtract(buffer, value))
00569                 {
00570                     return to_hstring(value);
00571                 }
00572                 return L"(error: Invalid UInt32)";
00573
00574             }
00575             else if (format.FormatType() == GattPresentationFormatTypes::Utf8())
00576             {
00577                 try
00578                 {
00579                     return CryptographicBuffer::ConvertBinaryToString(BinaryStringEncoding::Utf8, buffer);
00580                 }
00581                 catch (hresult_invalid_argument&)
00582                 {
00583                     return L"(error: Invalid UTF-8 string)";
00584                 }
00585             }
00586             else
00587             {
00588                 // Add support for other format types as needed.
00589                 return L"Unsupported format: " + CryptographicBuffer::EncodeToHexString(buffer);
00590             }
00591         }
00592         else if (buffer != nullptr)
00593         {
00594             // We don't know what format to use. Let's try some well-known profiles, or default back to UTF-8.
00595             if (selectedCharacteristic.Uuid() == GattCharacteristicUuids::HeartRateMeasurement())
00596             {
00597                 try
00598                 {
00599                     return L"Heart Rate: " + to_hstring(ParseHeartRateValue(buffer));
00600                 }
00601                 catch (std::out_of_range&)
00602                 {
00603                     return L"Heart Rate: (unable to parse)";
00604                 }
00605             }
00606             else if (selectedCharacteristic.Uuid() == GattCharacteristicUuids::BatteryLevel())
00607             {
00608                 // battery level is encoded as a percentage value in the first byte according to
00609                 // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.battery_level.xml
00610                 uint8_t percent;
00611                 if (TryExtract(buffer, percent))
00612                 {
00613                     return L"Battery Level: " + to_hstring(percent) + L"%";
00614                 }
00615                 return L"Battery Level: (unable to parse)";
00616             }
00617             // This is our custom calc service Result UUID. Format it like an Int
00618             else if (selectedCharacteristic.Uuid() == Constants::ResultCharacteristicUuid)
00619             {
00620                 int32_t value;
00621                 if (TryExtract(buffer, value))
00622                 {
00623                     return to_hstring(value);
00624                 }
00625                 return L"Invalid response from calc server";
00626             }
00627             // No guarantees on if a characteristic is registered for notifications.
00628             else if (registeredCharacteristic != nullptr)
00629             {
00630                 // This is our custom calc service Result UUID. Format it like an Int
00631                 if (registeredCharacteristic.Uuid() == Constants::ResultCharacteristicUuid)
00632                 {
00633                     int32_t value;
00634                     if (TryExtract(buffer, value))
00635                     {
00636                         return to_hstring(value);
00637                     }
00638                     return L"Invalid response from calc server";
00639                 }
00640             }
00641             else
00642             {
00643                 try
00644                 {
00645                     return L"Unknown format: " + CryptographicBuffer::ConvertBinaryToString(BinaryStringEncoding::Utf8, buffer);
00646
00647                 }
00648                 catch (hresult_invalid_argument&)
00649                 {
00650                     return L"Unknown format";
00651                 }
00652             }
00653         }
00654         else
00655         {
00656             return L"Empty data received";
00657         }
00658         return L"Unknown format";
00659     }
00660 }
Generated on Fri Nov 15 2024 22:18:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_CurrentActivity Member List

This is the complete list of members for Scenario1_CurrentActivity, including all inherited members.
ActivitySensorClassId | Scenario1_CurrentActivity | [private]
rootPage | Scenario1_CurrentActivity | [private]
Scenario1_CurrentActivity() | Scenario1_CurrentActivity | [inline]
ScenarioGetCurrentActivity(object sender, RoutedEventArgs e) | Scenario1_CurrentActivity | [inline, private]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/pch.cpp Source File

  • SmartCard
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/pch.h Source File

  • MapControl
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTask/cpp/Tasks/ServicingComplete.h Source File

  • BackgroundTask
  • cpp
  • Tasks

ServicingComplete.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 #include "pch.h"
00014
00015 using namespace Windows::ApplicationModel::Background;
00016
00017 namespace Tasks
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class ServicingComplete sealed : public IBackgroundTask
00021     {
00022
00023     public:
00024         ServicingComplete();
00025
00026         virtual void Run(IBackgroundTaskInstance^ taskInstance);
00027         void OnCanceled(IBackgroundTaskInstance^ taskInstance, BackgroundTaskCancellationReason reason);
00028
00029     private:
00030         ~ServicingComplete();
00031
00032         volatile bool CancelRequested;
00033     };
00034 }
Generated on Fri Nov 15 2024 22:18:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cpp/SampleConfiguration.h Source File

  • WebSocket
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <collection.h>
00015
00016 namespace SDKTemplate
00017 {
00018     public value struct Scenario
00019     {
00020         Platform::String^ Title;
00021         Platform::String^ ClassName;
00022     };
00023
00024     partial ref class MainPage
00025     {
00026     public:
00027         static property Platform::String^ FEATURE_NAME
00028         {
00029             Platform::String^ get()
00030             {
00031                 return "WebSocket C++ Sample";
00032             }
00033         }
00034
00035         static property Platform::Array<Scenario>^ scenarios
00036         {
00037             Platform::Array<Scenario>^ get()
00038             {
00039                 return scenariosInner;
00040             }
00041         }
00042
00043     internal:
00044         Windows::Foundation::Uri^ TryGetUri(Platform::String^ uriString);
00045         static Platform::String^ BuildWebSocketError(Platform::Exception^ ex);
00046         static concurrency::task<bool> AreCertificateAndCertChainValidAsync(
00047             Windows::Security::Cryptography::Certificates::Certificate^ serverCert,
00048             Windows::Foundation::Collections::IVectorView<Windows::Security::Cryptography::Certificates::Certificate^>^ certChain);
00049
00050     private:
00051         static Platform::Array<Scenario>^ scenariosInner;
00052
00053         static concurrency::task<bool> IsCertificateValidAsync(Windows::Security::Cryptography::Certificates::Certificate^ serverCert);
00054     };
00055 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserDataAccountManager/cpp/Scenario1_AddAccount.xaml.cpp Source File

  • UserDataAccountManager
  • cpp

Scenario1_AddAccount.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_AddAccount.xaml.h"
00013 #include <ppltasks.h>
00014
00015 using namespace SDKTemplate;
00016 using namespace concurrency;
00017
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Media;
00027 using namespace Windows::UI::Xaml::Navigation;
00028 using namespace Windows::ApplicationModel;
00029 using namespace Windows::ApplicationModel::UserDataAccounts;
00030
00031
00032 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00033
00034 Scenario1_AddAccount::Scenario1_AddAccount() : rootPage(MainPage::Current)
00035 {
00036     InitializeComponent();
00037     addAccountLaunched = false;
00038 }
00039
00040 void Scenario1_AddAccount::AddAccount_Click(Object^ sender, RoutedEventArgs^ e)
00041 {
00042     rootPage->NotifyUser("Add account launched", NotifyType::StatusMessage);
00043
00044     // only one instance of the UserDataAccountManager pane can be launched at once per thread
00045     if(addAccountLaunched == false)
00046     {
00047         addAccountLaunched = true;
00048
00049         // Allow user to add email, contact, and appointment accounts
00050         create_task(UserDataAccounts::UserDataAccountManager::ShowAddAccountAsync(UserDataAccountContentKinds::Email | UserDataAccountContentKinds::Appointment | UserDataAccountContentKinds::Contact))
00051             .then([this](Platform::String^ userDataAccountId)
00052         {
00053             if (userDataAccountId->IsEmpty())
00054             {
00055                 rootPage->NotifyUser("User cancelled or add account failed", NotifyType::StatusMessage);
00056                 return create_task([] {});
00057             }
00058             else
00059             {
00060                 return DisplayUserInformationAsync(userDataAccountId);
00061             }
00062         }).then([this]
00063         {
00064             addAccountLaunched = false;
00065         });
00066     }
00067 }
00068
00069 task<void> Scenario1_AddAccount::DisplayUserInformationAsync(String^ userId)
00070 {
00071     auto getStoreTask = create_task(UserDataAccounts::UserDataAccountManager::RequestStoreAsync(UserDataAccountStoreAccessType::AllAccountsReadOnly));
00072
00073     return getStoreTask.then([this, userId](UserDataAccountStore^ store)
00074     {
00075         // If the store is null, that means all access to Contacts, Calendar and Email data
00076         // has been revoked.
00077         if (store == nullptr)
00078         {
00079             rootPage->NotifyUser("Access to Contacts, Calendar and Email has been revoked", NotifyType::ErrorMessage);
00080             return create_task([] {});
00081         }
00082
00083         return create_task(store->GetAccountAsync(userId)).then([this](UserDataAccount^ account)
00084         {
00085             if (account != nullptr)
00086             {
00087                 rootPage->NotifyUser("Added user: " + account->UserDisplayName, NotifyType::StatusMessage);
00088             }
00089         });
00090     });
00091 }
00092
Generated on Fri Nov 15 2024 22:21:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OnDemandHotspot/cppwinrt/pch.h Source File

  • OnDemandHotspot
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.ApplicationModel.Background.h"
00008 #include "winrt/Windows.Devices.Enumeration.h"
00009 #include "winrt/Windows.Devices.Sensors.h"
00010 #include "winrt/Windows.Devices.WiFi.h"
00011 #include "winrt/Windows.Security.Credentials.h"
00012 #include "winrt/Windows.Storage.h"
00013 #include "winrt/Windows.System.h"
00014 #include "winrt/Windows.UI.Core.h"
00015 #include "winrt/Windows.UI.Xaml.h"
00016 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00017 #include "winrt/Windows.UI.Xaml.Controls.h"
00018 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00019 #include "winrt/Windows.UI.Xaml.Documents.h"
00020 #include "winrt/Windows.UI.Xaml.Interop.h"
00021 #include "winrt/Windows.UI.Xaml.Markup.h"
00022 #include "winrt/Windows.UI.Xaml.Media.h"
00023 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCoordinateMapper/cpp/Content/TextRenderer.h Source File

  • CameraStreamCoordinateMapper
  • cpp
  • Content

TextRenderer.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Common\DeviceResources.h"
00015 #include "Common\StepTimer.h"
00016
00017 namespace CameraStreamCoordinateMapper
00018 {
00019     // Renders the current FPS value in the bottom right corner of the screen using Direct2D and DirectWrite.
00020     class TextRenderer
00021     {
00022     public:
00023         enum class TextAlignment
00024         {
00025             TopLeft, TopRight, BottomLeft, BottomRight
00026         };
00027
00028         TextRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources);
00029         void CreateDeviceDependentResources();
00030         void ReleaseDeviceDependentResources();
00031         void Update(std::wstring_view text);
00032         void Render(TextAlignment alignment);
00033
00034     private:
00035         // Cached pointer to device resources.
00036         std::shared_ptr<DX::DeviceResources>           m_deviceResources;
00037
00038         // Resources related to text rendering.
00039         DWRITE_TEXT_METRICS                            m_textMetrics = {};
00040         Microsoft::WRL::ComPtr<ID2D1SolidColorBrush>   m_whiteBrush;
00041         Microsoft::WRL::ComPtr<ID2D1DrawingStateBlock> m_stateBlock;
00042         Microsoft::WRL::ComPtr<IDWriteTextLayout>      m_textLayout;
00043         Microsoft::WRL::ComPtr<IDWriteTextFormat>      m_textFormat;
00044     };
00045 }
Generated on Fri Nov 15 2024 22:18:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameXaml/cpp/Common/DDSTextureLoader.cpp Source File

  • Simple3DGameXaml
  • cpp
  • Common

DDSTextureLoader.cpp

Go to the documentation of this file.
00001 //--------------------------------------------------------------------------------------
00002 // File: DDSTextureLoader.cpp
00003 //
00004 // Functions for loading a DDS texture and creating a Direct3D 11 runtime resource for it
00005 //
00006 // Note these functions are useful as a light-weight runtime loader for DDS files. For
00007 // a full-featured DDS file reader, writer, and texture processing pipeline see
00008 // the 'Texconv' sample and the 'DirectXTex' library.
00009 //
00010 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00011 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00012 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00013 // PARTICULAR PURPOSE.
00014 //
00015 // Copyright (c) Microsoft Corporation. All rights reserved.
00016 //
00017 // http://go.microsoft.com/fwlink/?LinkId=248926
00018 // http://go.microsoft.com/fwlink/?LinkId=248929
00019 //--------------------------------------------------------------------------------------
00020
00021 #include "pch.h"
00022 #include <dxgiformat.h>
00023 #include <assert.h>
00024 #include <memory>
00025 #include <algorithm>
00026 #include "DDSTextureLoader.h"
00027 #include "DirectXSample.h"
00028
00029 using namespace Microsoft::WRL;
00030
00031 //--------------------------------------------------------------------------------------
00032 // Macros
00033 //--------------------------------------------------------------------------------------
00034 #ifndef MAKEFOURCC
00035     #define MAKEFOURCC(ch0, ch1, ch2, ch3)                              \
00036                 ((uint32)(byte)(ch0) | ((uint32)(byte)(ch1) << 8) |       \
00037                 ((uint32)(byte)(ch2) << 16) | ((uint32)(byte)(ch3) << 24))
00038 #endif /* defined(MAKEFOURCC) */
00039
00040 //--------------------------------------------------------------------------------------
00041 // DDS file structure definitions
00042 //
00043 // See DDS.h in the 'Texconv' sample and the 'DirectXTex' library
00044 //--------------------------------------------------------------------------------------
00045 #pragma pack(push, 1)
00046
00047 #define DDS_MAGIC 0x20534444 // "DDS "
00048
00049 struct DDS_PIXELFORMAT
00050 {
00051     uint32  size;
00052     uint32  flags;
00053     uint32  fourCC;
00054     uint32  RGBBitCount;
00055     uint32  RBitMask;
00056     uint32  GBitMask;
00057     uint32  BBitMask;
00058     uint32  ABitMask;
00059 };
00060
00061 #define DDS_FOURCC      0x00000004  // DDPF_FOURCC
00062 #define DDS_RGB         0x00000040  // DDPF_RGB
00063 #define DDS_RGBA        0x00000041  // DDPF_RGB | DDPF_ALPHAPIXELS
00064 #define DDS_LUMINANCE   0x00020000  // DDPF_LUMINANCE
00065 #define DDS_LUMINANCEA  0x00020001  // DDPF_LUMINANCE | DDPF_ALPHAPIXELS
00066 #define DDS_ALPHA       0x00000002  // DDPF_ALPHA
00067 #define DDS_PAL8        0x00000020  // DDPF_PALETTEINDEXED8
00068
00069 #define DDS_HEADER_FLAGS_TEXTURE        0x00001007  // DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
00070 #define DDS_HEADER_FLAGS_MIPMAP         0x00020000  // DDSD_MIPMAPCOUNT
00071 #define DDS_HEADER_FLAGS_VOLUME         0x00800000  // DDSD_DEPTH
00072 #define DDS_HEADER_FLAGS_PITCH          0x00000008  // DDSD_PITCH
00073 #define DDS_HEADER_FLAGS_LINEARSIZE     0x00080000  // DDSD_LINEARSIZE
00074
00075 #define DDS_HEIGHT 0x00000002 // DDSD_HEIGHT
00076 #define DDS_WIDTH  0x00000004 // DDSD_WIDTH
00077
00078 #define DDS_SURFACE_FLAGS_TEXTURE 0x00001000 // DDSCAPS_TEXTURE
00079 #define DDS_SURFACE_FLAGS_MIPMAP  0x00400008 // DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
00080 #define DDS_SURFACE_FLAGS_CUBEMAP 0x00000008 // DDSCAPS_COMPLEX
00081
00082 #define DDS_CUBEMAP_POSITIVEX 0x00000600 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
00083 #define DDS_CUBEMAP_NEGATIVEX 0x00000a00 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
00084 #define DDS_CUBEMAP_POSITIVEY 0x00001200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
00085 #define DDS_CUBEMAP_NEGATIVEY 0x00002200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
00086 #define DDS_CUBEMAP_POSITIVEZ 0x00004200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
00087 #define DDS_CUBEMAP_NEGATIVEZ 0x00008200 // DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
00088
00089 #define DDS_CUBEMAP_ALLFACES (DDS_CUBEMAP_POSITIVEX | DDS_CUBEMAP_NEGATIVEX |\
00090                               DDS_CUBEMAP_POSITIVEY | DDS_CUBEMAP_NEGATIVEY |\
00091                               DDS_CUBEMAP_POSITIVEZ | DDS_CUBEMAP_NEGATIVEZ)
00092
00093 #define DDS_CUBEMAP 0x00000200 // DDSCAPS2_CUBEMAP
00094
00095 #define DDS_FLAGS_VOLUME 0x00200000 // DDSCAPS2_VOLUME
00096
00097 enum DDS_MISC_FLAGS2
00098 {
00099     DDS_MISC_FLAGS2_ALPHA_MODE_MASK = 0x7L,
00100 };
00101
00102 enum DDS_ALPHA_MODE
00103 {
00104     DDS_ALPHA_MODE_UNKNOWN       = 0,
00105     DDS_ALPHA_MODE_STRAIGHT      = 1,
00106     DDS_ALPHA_MODE_PREMULTIPLIED = 2,
00107     DDS_ALPHA_MODE_OPAQUE        = 3,
00108     DDS_ALPHA_MODE_CUSTOM        = 4,
00109 };
00110
00111 typedef struct
00112 {
00113     uint32          size;
00114     uint32          flags;
00115     uint32          height;
00116     uint32          width;
00117     uint32          pitchOrLinearSize;
00118     uint32          depth; // only if DDS_HEADER_FLAGS_VOLUME is set in flags
00119     uint32          mipMapCount;
00120     uint32          reserved1[11];
00121     DDS_PIXELFORMAT ddspf;
00122     uint32          caps;
00123     uint32          caps2;
00124     uint32          caps3;
00125     uint32          caps4;
00126     uint32          reserved2;
00127 } DDS_HEADER;
00128
00129 typedef struct
00130 {
00131     DXGI_FORMAT dxgiFormat;
00132     uint32      resourceDimension;
00133     uint32      miscFlag; // see D3D11_RESOURCE_MISC_FLAG
00134     uint32      arraySize;
00135     uint32      miscFlags2;
00136 } DDS_HEADER_DXT10;
00137
00138 #pragma pack(pop)
00139
00140 //--------------------------------------------------------------------------------------
00141 // Return the BPP for a particular format
00142 //--------------------------------------------------------------------------------------
00143 static size_t BitsPerPixel(_In_ DXGI_FORMAT fmt)
00144 {
00145     switch (fmt)
00146     {
00147     case DXGI_FORMAT_R32G32B32A32_TYPELESS:
00148     case DXGI_FORMAT_R32G32B32A32_FLOAT:
00149     case DXGI_FORMAT_R32G32B32A32_UINT:
00150     case DXGI_FORMAT_R32G32B32A32_SINT:
00151         return 128;
00152
00153     case DXGI_FORMAT_R32G32B32_TYPELESS:
00154     case DXGI_FORMAT_R32G32B32_FLOAT:
00155     case DXGI_FORMAT_R32G32B32_UINT:
00156     case DXGI_FORMAT_R32G32B32_SINT:
00157         return 96;
00158
00159     case DXGI_FORMAT_R16G16B16A16_TYPELESS:
00160     case DXGI_FORMAT_R16G16B16A16_FLOAT:
00161     case DXGI_FORMAT_R16G16B16A16_UNORM:
00162     case DXGI_FORMAT_R16G16B16A16_UINT:
00163     case DXGI_FORMAT_R16G16B16A16_SNORM:
00164     case DXGI_FORMAT_R16G16B16A16_SINT:
00165     case DXGI_FORMAT_R32G32_TYPELESS:
00166     case DXGI_FORMAT_R32G32_FLOAT:
00167     case DXGI_FORMAT_R32G32_UINT:
00168     case DXGI_FORMAT_R32G32_SINT:
00169     case DXGI_FORMAT_R32G8X24_TYPELESS:
00170     case DXGI_FORMAT_D32_FLOAT_S8X24_UINT:
00171     case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS:
00172     case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT:
00173         return 64;
00174
00175     case DXGI_FORMAT_R10G10B10A2_TYPELESS:
00176     case DXGI_FORMAT_R10G10B10A2_UNORM:
00177     case DXGI_FORMAT_R10G10B10A2_UINT:
00178     case DXGI_FORMAT_R11G11B10_FLOAT:
00179     case DXGI_FORMAT_R8G8B8A8_TYPELESS:
00180     case DXGI_FORMAT_R8G8B8A8_UNORM:
00181     case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
00182     case DXGI_FORMAT_R8G8B8A8_UINT:
00183     case DXGI_FORMAT_R8G8B8A8_SNORM:
00184     case DXGI_FORMAT_R8G8B8A8_SINT:
00185     case DXGI_FORMAT_R16G16_TYPELESS:
00186     case DXGI_FORMAT_R16G16_FLOAT:
00187     case DXGI_FORMAT_R16G16_UNORM:
00188     case DXGI_FORMAT_R16G16_UINT:
00189     case DXGI_FORMAT_R16G16_SNORM:
00190     case DXGI_FORMAT_R16G16_SINT:
00191     case DXGI_FORMAT_R32_TYPELESS:
00192     case DXGI_FORMAT_D32_FLOAT:
00193     case DXGI_FORMAT_R32_FLOAT:
00194     case DXGI_FORMAT_R32_UINT:
00195     case DXGI_FORMAT_R32_SINT:
00196     case DXGI_FORMAT_R24G8_TYPELESS:
00197     case DXGI_FORMAT_D24_UNORM_S8_UINT:
00198     case DXGI_FORMAT_R24_UNORM_X8_TYPELESS:
00199     case DXGI_FORMAT_X24_TYPELESS_G8_UINT:
00200     case DXGI_FORMAT_R9G9B9E5_SHAREDEXP:
00201     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00202     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00203     case DXGI_FORMAT_B8G8R8A8_UNORM:
00204     case DXGI_FORMAT_B8G8R8X8_UNORM:
00205     case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:
00206     case DXGI_FORMAT_B8G8R8A8_TYPELESS:
00207     case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
00208     case DXGI_FORMAT_B8G8R8X8_TYPELESS:
00209     case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB:
00210         return 32;
00211
00212     case DXGI_FORMAT_R8G8_TYPELESS:
00213     case DXGI_FORMAT_R8G8_UNORM:
00214     case DXGI_FORMAT_R8G8_UINT:
00215     case DXGI_FORMAT_R8G8_SNORM:
00216     case DXGI_FORMAT_R8G8_SINT:
00217     case DXGI_FORMAT_R16_TYPELESS:
00218     case DXGI_FORMAT_R16_FLOAT:
00219     case DXGI_FORMAT_D16_UNORM:
00220     case DXGI_FORMAT_R16_UNORM:
00221     case DXGI_FORMAT_R16_UINT:
00222     case DXGI_FORMAT_R16_SNORM:
00223     case DXGI_FORMAT_R16_SINT:
00224     case DXGI_FORMAT_B5G6R5_UNORM:
00225     case DXGI_FORMAT_B5G5R5A1_UNORM:
00226     case DXGI_FORMAT_B4G4R4A4_UNORM:
00227         return 16;
00228
00229     case DXGI_FORMAT_R8_TYPELESS:
00230     case DXGI_FORMAT_R8_UNORM:
00231     case DXGI_FORMAT_R8_UINT:
00232     case DXGI_FORMAT_R8_SNORM:
00233     case DXGI_FORMAT_R8_SINT:
00234     case DXGI_FORMAT_A8_UNORM:
00235         return 8;
00236
00237     case DXGI_FORMAT_R1_UNORM:
00238         return 1;
00239
00240     case DXGI_FORMAT_BC1_TYPELESS:
00241     case DXGI_FORMAT_BC1_UNORM:
00242     case DXGI_FORMAT_BC1_UNORM_SRGB:
00243     case DXGI_FORMAT_BC4_TYPELESS:
00244     case DXGI_FORMAT_BC4_UNORM:
00245     case DXGI_FORMAT_BC4_SNORM:
00246         return 4;
00247
00248     case DXGI_FORMAT_BC2_TYPELESS:
00249     case DXGI_FORMAT_BC2_UNORM:
00250     case DXGI_FORMAT_BC2_UNORM_SRGB:
00251     case DXGI_FORMAT_BC3_TYPELESS:
00252     case DXGI_FORMAT_BC3_UNORM:
00253     case DXGI_FORMAT_BC3_UNORM_SRGB:
00254     case DXGI_FORMAT_BC5_TYPELESS:
00255     case DXGI_FORMAT_BC5_UNORM:
00256     case DXGI_FORMAT_BC5_SNORM:
00257     case DXGI_FORMAT_BC6H_TYPELESS:
00258     case DXGI_FORMAT_BC6H_UF16:
00259     case DXGI_FORMAT_BC6H_SF16:
00260     case DXGI_FORMAT_BC7_TYPELESS:
00261     case DXGI_FORMAT_BC7_UNORM:
00262     case DXGI_FORMAT_BC7_UNORM_SRGB:
00263         return 8;
00264
00265     default:
00266         return 0;
00267     }
00268 }
00269
00270
00271 //--------------------------------------------------------------------------------------
00272 // Get surface information for a particular format
00273 //--------------------------------------------------------------------------------------
00274 static void GetSurfaceInfo(
00275     _In_ size_t width,
00276     _In_ size_t height,
00277     _In_ DXGI_FORMAT fmt,
00278     _Out_opt_ size_t* outNumBytes,
00279     _Out_opt_ size_t* outRowBytes,
00280     _Out_opt_ size_t* outNumRows
00281     )
00282 {
00283     size_t numBytes = 0;
00284     size_t rowBytes = 0;
00285     size_t numRows = 0;
00286
00287     bool bc = false;
00288     bool packed  = false;
00289     size_t bcnumBytesPerBlock = 0;
00290     switch (fmt)
00291     {
00292     case DXGI_FORMAT_BC1_TYPELESS:
00293     case DXGI_FORMAT_BC1_UNORM:
00294     case DXGI_FORMAT_BC1_UNORM_SRGB:
00295     case DXGI_FORMAT_BC4_TYPELESS:
00296     case DXGI_FORMAT_BC4_UNORM:
00297     case DXGI_FORMAT_BC4_SNORM:
00298         bc = true;
00299         bcnumBytesPerBlock = 8;
00300         break;
00301
00302     case DXGI_FORMAT_BC2_TYPELESS:
00303     case DXGI_FORMAT_BC2_UNORM:
00304     case DXGI_FORMAT_BC2_UNORM_SRGB:
00305     case DXGI_FORMAT_BC3_TYPELESS:
00306     case DXGI_FORMAT_BC3_UNORM:
00307     case DXGI_FORMAT_BC3_UNORM_SRGB:
00308     case DXGI_FORMAT_BC5_TYPELESS:
00309     case DXGI_FORMAT_BC5_UNORM:
00310     case DXGI_FORMAT_BC5_SNORM:
00311     case DXGI_FORMAT_BC6H_TYPELESS:
00312     case DXGI_FORMAT_BC6H_UF16:
00313     case DXGI_FORMAT_BC6H_SF16:
00314     case DXGI_FORMAT_BC7_TYPELESS:
00315     case DXGI_FORMAT_BC7_UNORM:
00316     case DXGI_FORMAT_BC7_UNORM_SRGB:
00317         bc = true;
00318         bcnumBytesPerBlock = 16;
00319         break;
00320
00321     case DXGI_FORMAT_R8G8_B8G8_UNORM:
00322     case DXGI_FORMAT_G8R8_G8B8_UNORM:
00323         packed = true;
00324         break;
00325     }
00326
00327     if (bc)
00328     {
00329         size_t numBlocksWide = 0;
00330         if (width > 0)
00331         {
00332             numBlocksWide = std::max<size_t>(1, (width + 3) / 4);
00333         }
00334         size_t numBlocksHigh = 0;
00335         if (height > 0)
00336         {
00337             numBlocksHigh = std::max<size_t>(1, (height + 3) / 4);
00338         }
00339         rowBytes = numBlocksWide * bcnumBytesPerBlock;
00340         numRows = numBlocksHigh;
00341     }
00342     else if (packed)
00343     {
00344         rowBytes = ((width + 1) >> 1) * 4;
00345         numRows = height;
00346     }
00347     else
00348     {
00349         size_t bpp = BitsPerPixel(fmt);
00350         rowBytes = (width * bpp + 7) / 8; // round up to nearest byte
00351         numRows = height;
00352     }
00353
00354     numBytes = rowBytes * numRows;
00355     if (outNumBytes)
00356     {
00357         *outNumBytes = numBytes;
00358     }
00359     if (outRowBytes)
00360     {
00361         *outRowBytes = rowBytes;
00362     }
00363     if (outNumRows)
00364     {
00365         *outNumRows = numRows;
00366     }
00367 }
00368
00369
00370 //--------------------------------------------------------------------------------------
00371 #define ISBITMASK(r, g, b, a) (ddpf.RBitMask == r && ddpf.GBitMask == g && ddpf.BBitMask == b && ddpf.ABitMask == a)
00372
00373 static DXGI_FORMAT GetDXGIFormat(const DDS_PIXELFORMAT& ddpf)
00374 {
00375     if (ddpf.flags & DDS_RGB)
00376     {
00377         // Note that sRGB formats are written using the "DX10" extended header
00378
00379         switch (ddpf.RGBBitCount)
00380         {
00381         case 32:
00382             if (ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000))
00383             {
00384                 return DXGI_FORMAT_R8G8B8A8_UNORM;
00385             }
00386
00387             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000))
00388             {
00389                 return DXGI_FORMAT_B8G8R8A8_UNORM;
00390             }
00391
00392             if (ISBITMASK(0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000))
00393             {
00394                 return DXGI_FORMAT_B8G8R8X8_UNORM;
00395             }
00396
00397             // No DXGI format maps to ISBITMASK(0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000) aka D3DFMT_X8B8G8R8
00398
00399             // Note that many common DDS reader/writers (including D3DX) swap the
00400             // the RED/BLUE masks for 10:10:10:2 formats. We assumme
00401             // below that the 'backwards' header mask is being used since it is most
00402             // likely written by D3DX. The more robust solution is to use the 'DX10'
00403             // header extension and specify the DXGI_FORMAT_R10G10B10A2_UNORM format directly
00404
00405             // For 'correct' writers, this should be 0x000003ff, 0x000ffc00, 0x3ff00000 for RGB data
00406             if (ISBITMASK(0x3ff00000, 0x000ffc00, 0x000003ff, 0xc0000000))
00407             {
00408                 return DXGI_FORMAT_R10G10B10A2_UNORM;
00409             }
00410
00411             // No DXGI format maps to ISBITMASK(0x000003ff, 0x000ffc00, 0x3ff00000, 0xc0000000) aka D3DFMT_A2R10G10B10
00412
00413             if (ISBITMASK(0x0000ffff, 0xffff0000, 0x00000000, 0x00000000))
00414             {
00415                 return DXGI_FORMAT_R16G16_UNORM;
00416             }
00417
00418             if (ISBITMASK(0xffffffff, 0x00000000, 0x00000000, 0x00000000))
00419             {
00420                 // Only 32-bit color channel format in D3D9 was R32F
00421                 return DXGI_FORMAT_R32_FLOAT; // D3DX writes this out as a FourCC of 114
00422             }
00423             break;
00424
00425         case 24:
00426             // No 24bpp DXGI formats aka D3DFMT_R8G8B8
00427             break;
00428
00429         case 16:
00430             if (ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x8000))
00431             {
00432                 return DXGI_FORMAT_B5G5R5A1_UNORM;
00433             }
00434             if (ISBITMASK(0xf800, 0x07e0, 0x001f, 0x0000))
00435             {
00436                 return DXGI_FORMAT_B5G6R5_UNORM;
00437             }
00438
00439             // No DXGI format maps to ISBITMASK(0x7c00, 0x03e0, 0x001f, 0x0000) aka D3DFMT_X1R5G5B5
00440             if (ISBITMASK(0x0f00, 0x00f0, 0x000f, 0xf000))
00441             {
00442                 return DXGI_FORMAT_B4G4R4A4_UNORM;
00443             }
00444
00445             // No DXGI format maps to ISBITMASK(0x0f00, 0x00f0, 0x000f, 0x0000) aka D3DFMT_X4R4G4B4
00446
00447             // No 3:3:2, 3:3:2:8, or paletted DXGI formats aka D3DFMT_A8R3G3B2, D3DFMT_R3G3B2, D3DFMT_P8, D3DFMT_A8P8, etc.
00448             break;
00449         }
00450     }
00451     else if (ddpf.flags & DDS_LUMINANCE)
00452     {
00453         if (8 == ddpf.RGBBitCount)
00454         {
00455             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x00000000))
00456             {
00457                 return DXGI_FORMAT_R8_UNORM; // D3DX10/11 writes this out as DX10 extension
00458             }
00459
00460             // No DXGI format maps to ISBITMASK(0x0f, 0x00, 0x00, 0xf0) aka D3DFMT_A4L4
00461         }
00462
00463         if (16 == ddpf.RGBBitCount)
00464         {
00465             if (ISBITMASK(0x0000ffff, 0x00000000, 0x00000000, 0x00000000))
00466             {
00467                 return DXGI_FORMAT_R16_UNORM; // D3DX10/11 writes this out as DX10 extension
00468             }
00469             if (ISBITMASK(0x000000ff, 0x00000000, 0x00000000, 0x0000ff00))
00470             {
00471                 return DXGI_FORMAT_R8G8_UNORM; // D3DX10/11 writes this out as DX10 extension
00472             }
00473         }
00474     }
00475     else if (ddpf.flags & DDS_ALPHA)
00476     {
00477         if (8 == ddpf.RGBBitCount)
00478         {
00479             return DXGI_FORMAT_A8_UNORM;
00480         }
00481     }
00482     else if (ddpf.flags & DDS_FOURCC)
00483     {
00484         if (MAKEFOURCC('D', 'X', 'T', '1') == ddpf.fourCC)
00485         {
00486             return DXGI_FORMAT_BC1_UNORM;
00487         }
00488         if (MAKEFOURCC('D', 'X', 'T', '3') == ddpf.fourCC)
00489         {
00490             return DXGI_FORMAT_BC2_UNORM;
00491         }
00492         if (MAKEFOURCC('D', 'X', 'T', '5') == ddpf.fourCC)
00493         {
00494             return DXGI_FORMAT_BC3_UNORM;
00495         }
00496
00497         // While pre-mulitplied alpha isn't directly supported by the DXGI formats,
00498         // they are basically the same as these BC formats so they can be mapped
00499         if (MAKEFOURCC('D', 'X', 'T', '2') == ddpf.fourCC)
00500         {
00501             return DXGI_FORMAT_BC2_UNORM;
00502         }
00503         if (MAKEFOURCC('D', 'X', 'T', '4') == ddpf.fourCC)
00504         {
00505             return DXGI_FORMAT_BC3_UNORM;
00506         }
00507
00508         if (MAKEFOURCC('A', 'T', 'I', '1') == ddpf.fourCC)
00509         {
00510             return DXGI_FORMAT_BC4_UNORM;
00511         }
00512         if (MAKEFOURCC('B', 'C', '4', 'U') == ddpf.fourCC)
00513         {
00514             return DXGI_FORMAT_BC4_UNORM;
00515         }
00516         if (MAKEFOURCC('B', 'C', '4', 'S') == ddpf.fourCC)
00517         {
00518             return DXGI_FORMAT_BC4_SNORM;
00519         }
00520
00521         if (MAKEFOURCC('A', 'T', 'I', '2') == ddpf.fourCC)
00522         {
00523             return DXGI_FORMAT_BC5_UNORM;
00524         }
00525         if (MAKEFOURCC('B', 'C', '5', 'U') == ddpf.fourCC)
00526         {
00527             return DXGI_FORMAT_BC5_UNORM;
00528         }
00529         if (MAKEFOURCC('B', 'C', '5', 'S') == ddpf.fourCC)
00530         {
00531             return DXGI_FORMAT_BC5_SNORM;
00532         }
00533
00534         // BC6H and BC7 are written using the "DX10" extended header
00535
00536         if (MAKEFOURCC('R', 'G', 'B', 'G') == ddpf.fourCC)
00537         {
00538             return DXGI_FORMAT_R8G8_B8G8_UNORM;
00539         }
00540         if (MAKEFOURCC('G', 'R', 'G', 'B') == ddpf.fourCC)
00541         {
00542             return DXGI_FORMAT_G8R8_G8B8_UNORM;
00543         }
00544
00545         // Check for D3DFORMAT enums being set here
00546         switch (ddpf.fourCC)
00547         {
00548         case 36: // D3DFMT_A16B16G16R16
00549             return DXGI_FORMAT_R16G16B16A16_UNORM;
00550
00551         case 110: // D3DFMT_Q16W16V16U16
00552             return DXGI_FORMAT_R16G16B16A16_SNORM;
00553
00554         case 111: // D3DFMT_R16F
00555             return DXGI_FORMAT_R16_FLOAT;
00556
00557         case 112: // D3DFMT_G16R16F
00558             return DXGI_FORMAT_R16G16_FLOAT;
00559
00560         case 113: // D3DFMT_A16B16G16R16F
00561             return DXGI_FORMAT_R16G16B16A16_FLOAT;
00562
00563         case 114: // D3DFMT_R32F
00564             return DXGI_FORMAT_R32_FLOAT;
00565
00566         case 115: // D3DFMT_G32R32F
00567             return DXGI_FORMAT_R32G32_FLOAT;
00568
00569         case 116: // D3DFMT_A32B32G32R32F
00570             return DXGI_FORMAT_R32G32B32A32_FLOAT;
00571         }
00572     }
00573
00574     return DXGI_FORMAT_UNKNOWN;
00575 }
00576
00577
00578 //--------------------------------------------------------------------------------------
00579 static DXGI_FORMAT MakeSRGB(_In_ DXGI_FORMAT format)
00580 {
00581     switch (format)
00582     {
00583     case DXGI_FORMAT_R8G8B8A8_UNORM:
00584         return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
00585
00586     case DXGI_FORMAT_BC1_UNORM:
00587         return DXGI_FORMAT_BC1_UNORM_SRGB;
00588
00589     case DXGI_FORMAT_BC2_UNORM:
00590         return DXGI_FORMAT_BC2_UNORM_SRGB;
00591
00592     case DXGI_FORMAT_BC3_UNORM:
00593         return DXGI_FORMAT_BC3_UNORM_SRGB;
00594
00595     case DXGI_FORMAT_B8G8R8A8_UNORM:
00596         return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
00597
00598     case DXGI_FORMAT_B8G8R8X8_UNORM:
00599         return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB;
00600
00601     case DXGI_FORMAT_BC7_UNORM:
00602         return DXGI_FORMAT_BC7_UNORM_SRGB;
00603
00604     default:
00605         return format;
00606     }
00607 }
00608
00609
00610 //--------------------------------------------------------------------------------------
00611 static void FillInitData(
00612     _In_ size_t width,
00613     _In_ size_t height,
00614     _In_ size_t depth,
00615     _In_ size_t mipCount,
00616     _In_ size_t arraySize,
00617     _In_ DXGI_FORMAT format,
00618     _In_ size_t maxsize,
00619     _In_ size_t bitSize,
00620     _In_reads_bytes_(bitSize) const byte* bitData,
00621     _Out_ size_t& twidth,
00622     _Out_ size_t& theight,
00623     _Out_ size_t& tdepth,
00624     _Out_ size_t& skipMip,
00625     _Out_writes_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData
00626     )
00627 {
00628     if (!bitData || !initData)
00629     {
00630         throw ref new Platform::InvalidArgumentException();
00631     }
00632
00633     skipMip = 0;
00634     twidth = 0;
00635     theight = 0;
00636     tdepth = 0;
00637
00638     size_t NumBytes = 0;
00639     size_t RowBytes = 0;
00640     size_t NumRows = 0;
00641     const byte* pSrcBits = bitData;
00642     const byte* pEndBits = bitData + bitSize;
00643
00644     size_t index = 0;
00645     for (size_t j = 0; j < arraySize; j++)
00646     {
00647         size_t w = width;
00648         size_t h = height;
00649         size_t d = depth;
00650         for (size_t i = 0; i < mipCount; i++)
00651         {
00652             GetSurfaceInfo(w, h, format, &NumBytes, &RowBytes, &NumRows);
00653
00654             if ((mipCount <= 1) || !maxsize || (w <= maxsize && h <= maxsize && d <= maxsize))
00655             {
00656                 if (!twidth)
00657                 {
00658                     twidth = w;
00659                     theight = h;
00660                     tdepth = d;
00661                 }
00662
00663                 assert(index < mipCount * arraySize);
00664                 _Analysis_assume_(index < mipCount * arraySize);
00665                 initData[index].pSysMem = (const void*)pSrcBits;
00666                 initData[index].SysMemPitch = static_cast<UINT>(RowBytes);
00667                 initData[index].SysMemSlicePitch = static_cast<UINT>(NumBytes);
00668                 ++index;
00669             }
00670             else if (!j)
00671             {
00672                 // Count number of skipped mipmaps (first item only)
00673                 ++skipMip;
00674             }
00675
00676             if (pSrcBits + (NumBytes*d) > pEndBits)
00677             {
00678                 throw ref new Platform::OutOfBoundsException();
00679             }
00680
00681             pSrcBits += NumBytes * d;
00682
00683             w = w >> 1;
00684             h = h >> 1;
00685             d = d >> 1;
00686             if (w == 0)
00687             {
00688                 w = 1;
00689             }
00690             if (h == 0)
00691             {
00692                 h = 1;
00693             }
00694             if (d == 0)
00695             {
00696                 d = 1;
00697             }
00698         }
00699     }
00700
00701     if (!index)
00702     {
00703         throw ref new Platform::FailureException();
00704     }
00705 }
00706
00707
00708 //--------------------------------------------------------------------------------------
00709 static HRESULT CreateD3DResources(
00710     _In_ ID3D11Device* d3dDevice,
00711     _In_ uint32 resDim,
00712     _In_ size_t width,
00713     _In_ size_t height,
00714     _In_ size_t depth,
00715     _In_ size_t mipCount,
00716     _In_ size_t arraySize,
00717     _In_ DXGI_FORMAT format,
00718     _In_ D3D11_USAGE usage,
00719     _In_ unsigned int bindFlags,
00720     _In_ unsigned int cpuAccessFlags,
00721     _In_ unsigned int miscFlags,
00722     _In_ bool forceSRGB,
00723     _In_ bool isCubeMap,
00724     _In_reads_(mipCount*arraySize) D3D11_SUBRESOURCE_DATA* initData,
00725     _Outptr_opt_ ID3D11Resource** texture,
00726     _Outptr_opt_ ID3D11ShaderResourceView** textureView
00727     )
00728 {
00729     if (!d3dDevice || !initData)
00730     {
00731         return E_INVALIDARG;
00732     }
00733
00734     HRESULT hr = E_FAIL;
00735
00736     if (forceSRGB)
00737     {
00738         format = MakeSRGB(format);
00739     }
00740
00741     switch (resDim)
00742     {
00743         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00744             {
00745                 D3D11_TEXTURE1D_DESC desc;
00746                 desc.Width = static_cast<UINT>(width);
00747                 desc.MipLevels = static_cast<UINT>(mipCount);
00748                 desc.ArraySize = static_cast<UINT>(arraySize);
00749                 desc.Format = format;
00750                 desc.Usage = usage;
00751                 desc.BindFlags = bindFlags;
00752                 desc.CPUAccessFlags = cpuAccessFlags;
00753                 desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE;
00754
00755                 ID3D11Texture1D* tex = nullptr;
00756                 hr = d3dDevice->CreateTexture1D(&desc, initData, &tex);
00757
00758                 if (SUCCEEDED(hr) && tex != 0)
00759                 {
00760                     if (textureView != 0)
00761                     {
00762                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00763                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00764                         SRVDesc.Format = format;
00765
00766                         if (arraySize > 1)
00767                         {
00768                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1DARRAY;
00769                             SRVDesc.Texture1DArray.MipLevels = desc.MipLevels;
00770                             SRVDesc.Texture1DArray.ArraySize = static_cast<UINT>(arraySize);
00771                         }
00772                         else
00773                         {
00774                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE1D;
00775                             SRVDesc.Texture1D.MipLevels = desc.MipLevels;
00776                         }
00777
00778                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00779
00780                         if (FAILED(hr))
00781                         {
00782                             tex->Release();
00783                             return hr;
00784                         }
00785                     }
00786
00787                     if (texture != 0)
00788                     {
00789                         *texture = tex;
00790                     }
00791                     else
00792                     {
00793                         tex->Release();
00794                     }
00795                 }
00796             }
00797             break;
00798
00799         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00800             {
00801                 D3D11_TEXTURE2D_DESC desc;
00802                 desc.Width = static_cast<UINT>(width);
00803                 desc.Height = static_cast<UINT>(height);
00804                 desc.MipLevels = static_cast<UINT>(mipCount);
00805                 desc.ArraySize = static_cast<UINT>(arraySize);
00806                 desc.Format = format;
00807                 desc.SampleDesc.Count = 1;
00808                 desc.SampleDesc.Quality = 0;
00809                 desc.Usage = usage;
00810                 desc.BindFlags = bindFlags;
00811                 desc.CPUAccessFlags = cpuAccessFlags;
00812                 if (isCubeMap)
00813                 {
00814                     desc.MiscFlags = miscFlags | D3D11_RESOURCE_MISC_TEXTURECUBE;
00815                 }
00816                 else
00817                 {
00818                     desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE;
00819                 }
00820
00821                 ID3D11Texture2D* tex = nullptr;
00822                 hr = d3dDevice->CreateTexture2D(&desc, initData, &tex);
00823
00824                 if (SUCCEEDED(hr) && tex != 0)
00825                 {
00826                     if (textureView != 0)
00827                     {
00828                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00829                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00830                         SRVDesc.Format = format;
00831
00832                         if (isCubeMap)
00833                         {
00834                             if (arraySize > 6)
00835                             {
00836                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBEARRAY;
00837                                 SRVDesc.TextureCubeArray.MipLevels = desc.MipLevels;
00838
00839                                 // Earlier we set arraySize to (NumCubes * 6)
00840                                 SRVDesc.TextureCubeArray.NumCubes = static_cast<UINT>(arraySize / 6);
00841                             }
00842                             else
00843                             {
00844                                 SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURECUBE;
00845                                 SRVDesc.TextureCube.MipLevels = desc.MipLevels;
00846                             }
00847                         }
00848                         else if (arraySize > 1)
00849                         {
00850                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2DARRAY;
00851                             SRVDesc.Texture2DArray.MipLevels = desc.MipLevels;
00852                             SRVDesc.Texture2DArray.ArraySize = static_cast<UINT>(arraySize);
00853                         }
00854                         else
00855                         {
00856                             SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE2D;
00857                             SRVDesc.Texture2D.MipLevels = desc.MipLevels;
00858                         }
00859
00860                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00861
00862                         if (FAILED(hr))
00863                         {
00864                             tex->Release();
00865                             return hr;
00866                         }
00867                     }
00868
00869                     if (texture != 0)
00870                     {
00871                         *texture = tex;
00872                     }
00873                     else
00874                     {
00875                         tex->Release();
00876                     }
00877                 }
00878             }
00879             break;
00880
00881         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
00882             {
00883                 D3D11_TEXTURE3D_DESC desc;
00884                 desc.Width = static_cast<UINT>(width);
00885                 desc.Height = static_cast<UINT>(height);
00886                 desc.Depth = static_cast<UINT>(depth);
00887                 desc.MipLevels = static_cast<UINT>(mipCount);
00888                 desc.Format = format;
00889                 desc.Usage = usage;
00890                 desc.BindFlags = bindFlags;
00891                 desc.CPUAccessFlags = cpuAccessFlags;
00892                 desc.MiscFlags = miscFlags & ~D3D11_RESOURCE_MISC_TEXTURECUBE;
00893
00894                 ID3D11Texture3D* tex = nullptr;
00895                 hr = d3dDevice->CreateTexture3D(&desc, initData, &tex);
00896
00897                 if (SUCCEEDED(hr) && tex != 0)
00898                 {
00899                     if (textureView != 0)
00900                     {
00901                         D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc;
00902                         memset(&SRVDesc, 0, sizeof(SRVDesc));
00903                         SRVDesc.Format = format;
00904                         SRVDesc.ViewDimension = D3D_SRV_DIMENSION_TEXTURE3D;
00905                         SRVDesc.Texture3D.MipLevels = desc.MipLevels;
00906
00907                         hr = d3dDevice->CreateShaderResourceView(tex, &SRVDesc, textureView);
00908
00909                         if (FAILED(hr))
00910                         {
00911                             tex->Release();
00912                             return hr;
00913                         }
00914                     }
00915
00916                     if (texture != 0)
00917                     {
00918                         *texture = tex;
00919                     }
00920                     else
00921                     {
00922                         tex->Release();
00923                     }
00924                 }
00925             }
00926             break;
00927     }
00928
00929     return hr;
00930 }
00931
00932
00933 //--------------------------------------------------------------------------------------
00934 static void CreateTextureFromDDS(
00935     _In_ ID3D11Device* d3dDevice,
00936     _In_ const DDS_HEADER* header,
00937     _In_reads_bytes_(bitSize) const byte* bitData,
00938     _In_ size_t bitSize,
00939     _In_ size_t maxsize,
00940     _In_ D3D11_USAGE usage,
00941     _In_ unsigned int bindFlags,
00942     _In_ unsigned int cpuAccessFlags,
00943     _In_ unsigned int miscFlags,
00944     _In_ bool forceSRGB,
00945     _Outptr_opt_ ID3D11Resource** texture,
00946     _Outptr_opt_ ID3D11ShaderResourceView** textureView
00947     )
00948 {
00949     HRESULT hr = S_OK;
00950
00951     size_t width = header->width;
00952     size_t height = header->height;
00953     size_t depth = header->depth;
00954
00955     uint32 resDim = D3D11_RESOURCE_DIMENSION_UNKNOWN;
00956     size_t arraySize = 1;
00957     DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
00958     bool isCubeMap = false;
00959
00960     size_t mipCount = header->mipMapCount;
00961     if (0 == mipCount)
00962     {
00963         mipCount = 1;
00964     }
00965
00966     if ((header->ddspf.flags & DDS_FOURCC) &&
00967         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
00968     {
00969         auto d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER));
00970
00971         arraySize = d3d10ext->arraySize;
00972         if (arraySize == 0)
00973         {
00974             throw ref new Platform::FailureException();
00975         }
00976
00977         if (BitsPerPixel(d3d10ext->dxgiFormat) == 0)
00978         {
00979             throw ref new Platform::FailureException();
00980         }
00981
00982         format = d3d10ext->dxgiFormat;
00983
00984         switch (d3d10ext->resourceDimension)
00985         {
00986         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
00987             // D3DX writes 1D textures with a fixed Height of 1
00988             if ((header->flags & DDS_HEIGHT) && height != 1)
00989             {
00990                 throw ref new Platform::FailureException();
00991             }
00992             height = depth = 1;
00993             break;
00994
00995         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
00996             if (d3d10ext->miscFlag & D3D11_RESOURCE_MISC_TEXTURECUBE)
00997             {
00998                 arraySize *= 6;
00999                 isCubeMap = true;
01000             }
01001             depth = 1;
01002             break;
01003
01004         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
01005             if (!(header->flags & DDS_HEADER_FLAGS_VOLUME))
01006             {
01007                 throw ref new Platform::FailureException();
01008             }
01009
01010             if (arraySize > 1)
01011             {
01012                 throw ref new Platform::FailureException();
01013             }
01014             break;
01015
01016         default:
01017             return throw ref new Platform::FailureException();
01018         }
01019
01020         resDim = d3d10ext->resourceDimension;
01021     }
01022     else
01023     {
01024         format = GetDXGIFormat(header->ddspf);
01025
01026         if (format == DXGI_FORMAT_UNKNOWN)
01027         {
01028             return throw ref new Platform::FailureException();
01029         }
01030
01031         if (header->flags & DDS_HEADER_FLAGS_VOLUME)
01032         {
01033             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE3D;
01034         }
01035         else
01036         {
01037             if (header->caps2 & DDS_CUBEMAP)
01038             {
01039                 // We require all six faces to be defined
01040                 if ((header->caps2 & DDS_CUBEMAP_ALLFACES) != DDS_CUBEMAP_ALLFACES)
01041                 {
01042                     return throw ref new Platform::FailureException();
01043                 }
01044
01045                 arraySize = 6;
01046                 isCubeMap = true;
01047             }
01048
01049             depth = 1;
01050             resDim = D3D11_RESOURCE_DIMENSION_TEXTURE2D;
01051
01052             // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture
01053         }
01054
01055         assert(BitsPerPixel(format) != 0);
01056     }
01057
01058     // Bound sizes (for security purposes we don't trust DDS file metadata larger than the D3D 11.x hardware requirements)
01059     if (mipCount > D3D11_REQ_MIP_LEVELS)
01060     {
01061         return throw ref new Platform::FailureException();
01062     }
01063
01064     switch (resDim)
01065     {
01066         case D3D11_RESOURCE_DIMENSION_TEXTURE1D:
01067             if ((arraySize > D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION) ||
01068                 (width > D3D11_REQ_TEXTURE1D_U_DIMENSION))
01069             {
01070                 return throw ref new Platform::FailureException();
01071             }
01072             break;
01073
01074         case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
01075             if (isCubeMap)
01076             {
01077                 // This is the right bound because we set arraySize to (NumCubes*6) above
01078                 if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01079                     (width > D3D11_REQ_TEXTURECUBE_DIMENSION) ||
01080                     (height > D3D11_REQ_TEXTURECUBE_DIMENSION))
01081                 {
01082                     return throw ref new Platform::FailureException();
01083                 }
01084             }
01085             else if ((arraySize > D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION) ||
01086                     (width > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION) ||
01087                     (height > D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION))
01088             {
01089                 return throw ref new Platform::FailureException();
01090             }
01091             break;
01092
01093         case D3D11_RESOURCE_DIMENSION_TEXTURE3D:
01094             if ((arraySize > 1) ||
01095                 (width > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01096                 (height > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION) ||
01097                 (depth > D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION))
01098             {
01099                 return throw ref new Platform::FailureException();
01100             }
01101             break;
01102     }
01103
01104     // Create the texture
01105     std::unique_ptr<D3D11_SUBRESOURCE_DATA[]> initData(new D3D11_SUBRESOURCE_DATA[mipCount * arraySize]);
01106
01107     size_t skipMip = 0;
01108     size_t twidth = 0;
01109     size_t theight = 0;
01110     size_t tdepth = 0;
01111     FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01112
01113     hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, isCubeMap, initData.get(), texture, textureView);
01114
01115     if (FAILED(hr) && !maxsize && (mipCount > 1))
01116     {
01117         // Retry with a maxsize determined by feature level
01118         switch (d3dDevice->GetFeatureLevel())
01119         {
01120         case D3D_FEATURE_LEVEL_9_1:
01121         case D3D_FEATURE_LEVEL_9_2:
01122             if (isCubeMap)
01123             {
01124                 maxsize = D3D_FL9_1_REQ_TEXTURECUBE_DIMENSION;
01125             }
01126             else
01127             {
01128                 maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01129                     ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01130                     : D3D_FL9_1_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01131             }
01132             break;
01133
01134         case D3D_FEATURE_LEVEL_9_3:
01135             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01136                 ? D3D_FL9_1_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01137                 : D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01138             break;
01139
01140         default: // D3D_FEATURE_LEVEL_10_0 & D3D_FEATURE_LEVEL_10_1
01141             maxsize = (resDim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
01142                 ? D3D10_REQ_TEXTURE3D_U_V_OR_W_DIMENSION
01143                 : D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
01144             break;
01145         }
01146
01147         FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, twidth, theight, tdepth, skipMip, initData.get());
01148
01149         hr = CreateD3DResources(d3dDevice, resDim, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, isCubeMap, initData.get(), texture, textureView);
01150     }
01151
01152     DX::ThrowIfFailed(hr);
01153 }
01154
01155
01156 //--------------------------------------------------------------------------------------
01157 static D2D1_ALPHA_MODE GetAlphaMode(_In_ const DDS_HEADER* header)
01158 {
01159     if (header->ddspf.flags & DDS_FOURCC)
01160     {
01161         if (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC)
01162         {
01163             auto d3d10ext = reinterpret_cast<const DDS_HEADER_DXT10*>((const char*)header + sizeof(DDS_HEADER));
01164             switch (d3d10ext->miscFlags2 & DDS_MISC_FLAGS2_ALPHA_MODE_MASK)
01165             {
01166             case DDS_ALPHA_MODE_STRAIGHT:
01167                 return D2D1_ALPHA_MODE_STRAIGHT;
01168
01169             case DDS_ALPHA_MODE_PREMULTIPLIED:
01170                 return D2D1_ALPHA_MODE_PREMULTIPLIED;
01171
01172             case DDS_ALPHA_MODE_OPAQUE:
01173             case DDS_ALPHA_MODE_CUSTOM:
01174                 // No D2D1_ALPHA_MODE equivalent, so return "Ignore" for now
01175                 return D2D1_ALPHA_MODE_IGNORE;
01176             }
01177         }
01178         else if ((MAKEFOURCC('D', 'X', 'T', '2') == header->ddspf.fourCC)
01179                   || (MAKEFOURCC('D', 'X', 'T', '4') == header->ddspf.fourCC))
01180         {
01181             return D2D1_ALPHA_MODE_PREMULTIPLIED;
01182         }
01183         // DXT1, DXT3, and DXT5 legacy files could be straight alpha or something else, so return "Unknown" to leave it up to the app
01184     }
01185
01186     return D2D1_ALPHA_MODE_UNKNOWN;
01187 }
01188
01189
01190 //--------------------------------------------------------------------------------------
01191 _Use_decl_annotations_
01192 void CreateDDSTextureFromMemory(
01193     ID3D11Device* d3dDevice,
01194     const uint8_t* ddsData,
01195     size_t ddsDataSize,
01196     ID3D11Resource** texture,
01197     ID3D11ShaderResourceView** textureView,
01198     size_t maxsize,
01199     D2D1_ALPHA_MODE* alphaMode
01200     )
01201 {
01202     return CreateDDSTextureFromMemoryEx(d3dDevice, ddsData, ddsDataSize, maxsize, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, false, texture, textureView, alphaMode);
01203 }
01204
01205
01206 //--------------------------------------------------------------------------------------
01207 _Use_decl_annotations_
01208 void CreateDDSTextureFromMemoryEx(
01209     ID3D11Device* d3dDevice,
01210     const uint8_t* ddsData,
01211     size_t ddsDataSize,
01212     size_t maxsize,
01213     D3D11_USAGE usage,
01214     unsigned int bindFlags,
01215     unsigned int cpuAccessFlags,
01216     unsigned int miscFlags,
01217     bool forceSRGB,
01218     ID3D11Resource** texture,
01219     ID3D11ShaderResourceView** textureView,
01220     D2D1_ALPHA_MODE* alphaMode
01221     )
01222 {
01223     if (texture)
01224     {
01225         *texture = nullptr;
01226     }
01227     if (textureView)
01228     {
01229         *textureView = nullptr;
01230     }
01231     if (alphaMode)
01232     {
01233         *alphaMode = D2D1_ALPHA_MODE_UNKNOWN;
01234     }
01235
01236     if (!d3dDevice || !ddsData || (!texture && !textureView))
01237     {
01238         throw ref new Platform::InvalidArgumentException();
01239     }
01240
01241     // Validate DDS file in memory
01242     if (ddsDataSize < (sizeof(uint32) + sizeof(DDS_HEADER)))
01243     {
01244         throw ref new Platform::FailureException();
01245     }
01246
01247     uint32 dwMagicNumber = *(const uint32*)(ddsData);
01248     if (dwMagicNumber != DDS_MAGIC)
01249     {
01250         throw ref new Platform::FailureException();
01251     }
01252
01253     auto header = reinterpret_cast<const DDS_HEADER*>(ddsData + sizeof(uint32));
01254
01255     // Verify header to validate DDS file
01256     if (header->size != sizeof(DDS_HEADER) ||
01257         header->ddspf.size != sizeof(DDS_PIXELFORMAT))
01258     {
01259         throw ref new Platform::FailureException();
01260     }
01261
01262     // Check for DX10 extension
01263     bool bDXT10Header = false;
01264     if ((header->ddspf.flags & DDS_FOURCC) &&
01265         (MAKEFOURCC('D', 'X', '1', '0') == header->ddspf.fourCC))
01266     {
01267         // Must be long enough for both headers and magic value
01268         if (ddsDataSize < (sizeof(DDS_HEADER) + sizeof(uint32) + sizeof(DDS_HEADER_DXT10)))
01269         {
01270             throw ref new Platform::FailureException();
01271         }
01272
01273         bDXT10Header = true;
01274     }
01275
01276     ptrdiff_t offset = sizeof(uint32) + sizeof(DDS_HEADER) + (bDXT10Header ? sizeof(DDS_HEADER_DXT10) : 0);
01277
01278     CreateTextureFromDDS(d3dDevice, header, ddsData + offset, ddsDataSize - offset, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, texture, textureView);
01279
01280     if (alphaMode)
01281         *alphaMode = GetAlphaMode(header);
01282 }
Generated on Fri Nov 15 2024 22:19:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CStartOperation Member List

This is the complete list of members for CStartOperation, including all inherited members.
_spPD | CStartOperation | [private]
CSourceOperation(Type opType) | CSourceOperation |
CStartOperation(IMFPresentationDescriptor *pPD) | CStartOperation |
GetData() const | CSourceOperation | [inline]
GetOperationType() const | CSourceOperation | [inline]
GetPresentationDescriptor() | CStartOperation | [inline]
IFACEMETHOD_(ULONG, AddRef)() | CSourceOperation |
IFACEMETHOD_(ULONG, Release)() | CSourceOperation |
Operation_SetRate enum value | CSourceOperation |
Operation_Start enum value | CSourceOperation |
Operation_Stop enum value | CSourceOperation |
QueryInterface(REFIID riid, void **ppv) | CSourceOperation |
SetData(const PROPVARIANT &varData) | CSourceOperation |
Type enum name | CSourceOperation |
~CSourceOperation() | CSourceOperation | [virtual]
~CStartOperation() | CStartOperation |
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ScenarioElement Member List

This is the complete list of members for ScenarioElement, including all inherited members.
Error(string message) | ScenarioElement | [inline, private]
Initialize() | ScenarioElement | [inline, private]
ScenarioElement() | ScenarioElement | [inline]
TimerWaitForTwoMins_Tick(object sender, object e) | ScenarioElement | [inline, private]
UserControl_Loaded(object sender, RoutedEventArgs e) | ScenarioElement | [inline, private]
Generated on Fri Nov 15 2024 22:23:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Nfc/Nfc/MainPage.xaml.cs Source File

  • Nfc
  • Nfc

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Data;
00017 using Windows.UI.Xaml.Media;
00018 using Windows.UI.Xaml.Navigation;
00019 using NfcSample;
00020
00021 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class MainPage : Page
00029     {
00030         public Windows.ApplicationModel.Activation.LaunchActivatedEventArgs LaunchArgs
00031         {
00032             get
00033             {
00034                 return ((App)App.Current).LaunchArgs;
00035             }
00036         }
00037
00038         public static MainPage Current;
00039
00040         public MainPage()
00041         {
00042             this.InitializeComponent();
00043
00044             // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00045             // in order to call methods that are in this class.
00046             Current = this;
00047             SampleTitle.Text = FEATURE_NAME;
00048         }
00049
00050         protected override void OnNavigatedTo(NavigationEventArgs e)
00051         {
00052             // Populate the scenario list from the SampleConfiguration.cs file
00053             ScenarioControl.ItemsSource = scenarios;
00054             if (Window.Current.Bounds.Width < 640)
00055             {
00056                 ScenarioControl.SelectedIndex = -1;
00057             }
00058             else
00059             {
00060                 ScenarioControl.SelectedIndex = 0;
00061             }
00062
00063             if (e.Parameter is string)
00064             {
00065                 var param = (string)e.Parameter;
00066                 if (!string.IsNullOrWhiteSpace(param))
00067                 {
00068                     NavigateToScenario(typeof(ReceiptView), param);
00069                 }
00070             }
00071         }
00072
00073         /// <summary>
00074         /// Called whenever the user changes selection in the scenarios list.  This method will navigate to the respective
00075         /// sample scenario page.
00076         /// </summary>
00077         /// <param name="sender"></param>
00078         /// <param name="e"></param>
00079         private void ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
00080         {
00081             // Clear the status block when navigating scenarios.
00082             NotifyUser(String.Empty, NotifyType.StatusMessage);
00083
00084             ListBox scenarioListBox = sender as ListBox;
00085             Scenario s = scenarioListBox.SelectedItem as Scenario;
00086             if (s != null)
00087             {
00088                 NavigateToScenario(s.ClassType);
00089             }
00090         }
00091
00092         private void NavigateToScenario(Type scenario, object param = null)
00093         {
00094             ScenarioFrame.Navigate(scenario, param);
00095             if (Window.Current.Bounds.Width < 640)
00096             {
00097                 Splitter.IsPaneOpen = false;
00098                 StatusBorder.Visibility = Visibility.Collapsed;
00099             }
00100
00101             if (scenario == typeof(CardReader))
00102             {
00103                 StatusBlockScroller.MaxHeight = Math.Max(300, Window.Current.Bounds.Height - 200);
00104             }
00105             else
00106             {
00107                 StatusBlockScroller.MaxHeight = 300;
00108             }
00109         }
00110
00111         public List<Scenario> Scenarios
00112         {
00113             get { return this.scenarios; }
00114         }
00115
00116         /// <summary>
00117         /// Used to display messages to the user
00118         /// </summary>
00119         /// <param name="strMessage"></param>
00120         /// <param name="type"></param>
00121         public void NotifyUser(string strMessage, NotifyType type, bool clearPrevious = false)
00122         {
00123             if (!this.Dispatcher.HasThreadAccess)
00124             {
00125                 var ignored = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { NotifyUser(strMessage, type, clearPrevious); });
00126                 return;
00127             }
00128
00129             switch (type)
00130             {
00131                 case NotifyType.StatusMessage:
00132                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green);
00133                     break;
00134                 case NotifyType.ErrorMessage:
00135                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red);
00136                     break;
00137             }
00138             if (clearPrevious)
00139             {
00140                 StatusBlock.Text = strMessage;
00141             }
00142             else
00143             {
00144                 if (StatusBlock.Text != "")
00145                 {
00146                     StatusBlock.Text += "\r\n";
00147                 }
00148                 StatusBlock.Text += strMessage;
00149             }
00150             StatusBlockScroller.ChangeView(0, StatusBlockScroller.ExtentHeight, 1);
00151
00152             // Collapse the StatusBlock if it has no text to conserve real estate.
00153             StatusBorder.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed;
00154         }
00155
00156         async void Footer_Click(object sender, RoutedEventArgs e)
00157         {
00158             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00159         }
00160
00161         private void Button_Click(object sender, RoutedEventArgs e)
00162         {
00163             Splitter.IsPaneOpen = (Splitter.IsPaneOpen == true) ? false : true;
00164             StatusBorder.Visibility = Visibility.Collapsed;
00165         }
00166     }
00167
00168     public class ScenarioBindingConverter : IValueConverter
00169     {
00170         public object Convert(object value, Type targetType, object parameter, string language)
00171         {
00172             Scenario s = value as Scenario;
00173             return (MainPage.Current.Scenarios.IndexOf(s) + 1) + ") " + s.Title;
00174         }
00175
00176         public object ConvertBack(object value, Type targetType, object parameter, string language)
00177         {
00178             return true;
00179         }
00180     }
00181 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraFaceDetection/cpp/App.xaml.cpp Source File

  • CameraFaceDetection
  • cpp

App.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014
00015 using namespace FaceDetection;
00016 using namespace Platform;
00017 using namespace Windows::ApplicationModel;
00018 using namespace Windows::ApplicationModel::Activation;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Controls::Primitives;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Input;
00026 using namespace Windows::UI::Xaml::Interop;
00027 using namespace Windows::UI::Xaml::Media;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 /// <summary>
00031 /// Initializes the singleton application object.  This is the first line of authored code
00032 /// executed, and as such is the logical equivalent of main() or WinMain().
00033 /// </summary>
00034 App::App()
00035 {
00036     InitializeComponent();
00037 }
00038
00039 /// <summary>
00040 /// Invoked when the application is launched normally by the end user.  Other entry points
00041 /// will be used such as when the application is launched to open a specific file.
00042 /// </summary>
00043 /// <param name="e">Details about the launch request and process.</param>
00044 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
00045 {
00046
00047 #if _DEBUG
00048         // Show graphics profiling information while debugging.
00049         if (IsDebuggerPresent())
00050         {
00051             // Display the current frame rate counters
00052             DebugSettings->EnableFrameRateCounter = true;
00053         }
00054 #endif
00055
00056     auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00057
00058     // Do not repeat app initialization when the Window already has content,
00059     // just ensure that the window is active
00060     if (rootFrame == nullptr)
00061     {
00062         // Create a Frame to act as the navigation context and associate it with
00063         // a SuspensionManager key
00064         rootFrame = ref new Frame();
00065
00066         rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed);
00067
00068         if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
00069         {
00070         }
00071
00072         if (rootFrame->Content == nullptr)
00073         {
00074             // When the navigation stack isn't restored navigate to the first page,
00075             // configuring the new page by passing required information as a navigation
00076             // parameter
00077             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00078         }
00079         // Place the frame in the current Window
00080         Window::Current->Content = rootFrame;
00081         // Ensure the current window is active
00082         Window::Current->Activate();
00083     }
00084     else
00085     {
00086         if (rootFrame->Content == nullptr)
00087         {
00088             // When the navigation stack isn't restored navigate to the first page,
00089             // configuring the new page by passing required information as a navigation
00090             // parameter
00091             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00092         }
00093         // Ensure the current window is active
00094         Window::Current->Activate();
00095     }
00096 }
00097
00098 /// <summary>
00099 /// Invoked when Navigation to a certain page fails
00100 /// </summary>
00101 /// <param name="sender">The Frame which failed navigation</param>
00102 /// <param name="e">Details about the navigation failure</param>
00103 void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e)
00104 {
00105     throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name);
00106 }
Generated on Fri Nov 15 2024 22:16:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/shared/AllJoynBusObjectManager.h Source File

  • AllJoyn
  • shared

AllJoynBusObjectManager.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #pragma once
00022
00023 class AllJoynBusObjectManager
00024 {
00025 public:
00026     // Retrieve the BusObject that is mapped to the specified BusAttachment and ObjectPath, or create one if it does not yet exist.
00027     static QStatus GetBusObject(_In_ const alljoyn_busattachment busAttachment, _In_ const PCSTR objectPath, _Out_ alljoyn_busobject* busObject);
00028
00029     // Indicate to AllJoynBusObjectManager that a reference to the BusObject which is mapped to the specified BusAttachment and ObjectPath
00030     // is no longer being used. This should be invoked whenever a Consumer is destroyed.
00031     static QStatus ReleaseBusObject(_Inout_ alljoyn_busattachment busAttachment, _In_ const PCSTR objectPath);
00032
00033     // If the BusObject is not already registered on the BusAttachment, it becomes registered. Otherwise, no action is taken.
00034     static QStatus TryRegisterBusObject(_Inout_ alljoyn_busattachment busAttachment, _In_ const alljoyn_busobject busObject, _In_ const bool secure);
00035
00036     // Determine whether a BusObject with the specified ObjectPath has been mapped to the specified BusAttachment.
00037     static bool BusObjectExists(_In_ const alljoyn_busattachment busAttachment, _In_ const PCSTR objectPath);
00038
00039     // Determine whether the specified BusObject is registered on the specified BusAttachment.
00040     static bool BusObjectIsRegistered(_In_ const alljoyn_busattachment busAttachment, _In_ const alljoyn_busobject busObject);
00041 private:
00042     // Lock public methods that result in modifications to BusAttachmentMap to ensure thread-safety.
00043     static std::mutex ModifyBusObjectMap;
00044
00045     // A nested map of BusObjects that is keyed first by BusAttachment, and then by ObjectPath, allowing a BusObject to be addressed
00046     // by its ObjectPath and the BusAttachment on which it is registered.
00047     // Each innermost element (a tuple) contains three fields:
00048     //   (0) The BusObject
00049     //   (1) Whether the BusObject has been registered on the associated BusAttachment
00050     //   (2) The number of references to the entry
00051     static std::map<alljoyn_busattachment, std::shared_ptr<std::map<std::string, std::tuple<alljoyn_busobject, bool, int>>>> BusAttachmentMap;
00052
00053     // Create a BusObject that has no callbacks and uses the specified ObjectPath.
00054     static QStatus CreateBusObject(_In_ const PCSTR objectPath, _Out_ alljoyn_busobject* busObject);
00055
00056     // Save the given BusObject in BusAttachmentMap, keyed by busAttachment and objectPath.
00057     static QStatus SaveBusObject(_In_ const alljoyn_busattachment busAttachment, _In_ const PCSTR objectPath, _In_ const alljoyn_busobject busObject);
00058
00059     // If the BusObject is registered on the specified BusAttachment, unregister it. Then destroy the BusObject.
00060     static QStatus UnregisterAndDestroyBusObject(_Inout_ alljoyn_busattachment busAttachment, _In_ const PCSTR objectPath);
00061 };
00062
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Client Member List

This is the complete list of members for Scenario2_Client, including all inherited members.
AddValueChangedHandler() | Scenario2_Client | [private]
Characteristic_ValueChanged(Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristic const &, Windows::Devices::Bluetooth::GenericAttributeProfile::GattValueChangedEventArgs args) | Scenario2_Client | [private]
CharacteristicList_SelectionChanged() | Scenario2_Client |
CharacteristicReadButton_Click() | Scenario2_Client |
CharacteristicWriteButton_Click() | Scenario2_Client |
CharacteristicWriteButtonInt_Click() | Scenario2_Client |
ClearBluetoothLEDeviceAsync() | Scenario2_Client | [private]
ConnectButton_Click() | Scenario2_Client |
EnableCharacteristicPanels(Windows::Devices::Bluetooth::GenericAttributeProfile::GattCharacteristicProperties properties) | Scenario2_Client | [private]
FormatValueByPresentation(Windows::Storage::Streams::IBuffer const &buffer, Windows::Devices::Bluetooth::GenericAttributeProfile::GattPresentationFormat const &format) | Scenario2_Client | [private]
notificationsToken | Scenario2_Client | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario2_Client |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario2_Client |
RemoveValueChangedHandler() | Scenario2_Client | [private]
Scenario2_Client() | Scenario2_Client |
ServiceList_SelectionChanged() | Scenario2_Client |
ValueChangedSubscribeToggle_Click() | Scenario2_Client |
WriteBufferToSelectedCharacteristicAsync(Windows::Storage::Streams::IBuffer buffer) | Scenario2_Client | [private]
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario4_ChangeAdminKey Member List

This is the complete list of members for Scenario4_ChangeAdminKey, including all inherited members.
ChangeAdminKey_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario4_ChangeAdminKey
Scenario4_ChangeAdminKey() | Scenario4_ChangeAdminKey
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IOnboardingProducer Member List

This is the complete list of members for IOnboardingProducer, including all inherited members.
SessionLost | IOnboardingProducer
SessionMemberAdded | IOnboardingProducer
SessionMemberRemoved | IOnboardingProducer
Stopped | IOnboardingProducer
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Content/ShaderStructures.h Source File

  • HolographicFaceTracking
  • cpp
  • Content

ShaderStructures.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 namespace HolographicFaceTracker
00004 {
00005     // Constant buffers used to send hologram position transform to the shader pipeline.
00006     struct CubeModelConstantBuffer
00007     {
00008         Windows::Foundation::Numerics::float4x4 model;
00009     };
00010
00011     // Assert that the constant buffer remains 16-byte aligned (best practice).
00012     static_assert((sizeof(CubeModelConstantBuffer) % (sizeof(float) * 4)) == 0, "Model constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00013
00014     struct QuadModelConstantBuffer
00015     {
00016         Windows::Foundation::Numerics::float4x4 model;
00017         Windows::Foundation::Numerics::float2 texCoordScale;
00018         Windows::Foundation::Numerics::float2 texCoordOffset;
00019     };
00020
00021     // Assert that the constant buffer remains 16-byte aligned (best practice).
00022     static_assert((sizeof(QuadModelConstantBuffer) % (sizeof(float) * 4)) == 0, "Model constant buffer size must be 16-byte aligned (16 bytes is the length of four floats).");
00023
00024     // Used to send per-vertex data to the vertex shader.
00025     struct VertexPositionColor
00026     {
00027         Windows::Foundation::Numerics::float3 pos;
00028         Windows::Foundation::Numerics::float3 color;
00029     };
00030
00031     struct VertexPositionTex
00032     {
00033         Windows::Foundation::Numerics::float3 pos;
00034         Windows::Foundation::Numerics::float2 tex;
00035     };
00036 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7 Member List

This is the complete list of members for Scenario7, including all inherited members.
GetStreamStatus_Click(object sender, RoutedEventArgs e) | Scenario7 | [inline, private]
m_getstreamStreamScenario | Scenario7 | [private]
m_protectedStream | Scenario7 | [private]
m_protectStreamScenario | Scenario7 | [private]
m_unprotectedStream | Scenario7 | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario7 | [inline, protected]
ProtectStreamAsync_Click(object sender, RoutedEventArgs e) | Scenario7 | [inline, private]
rootPage | Scenario7 | [private]
Scenario7() | Scenario7 | [inline]
UnprotectAsyncBuffer_Click(object sender, RoutedEventArgs e) | Scenario7 | [inline, private]
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaEditing/cpp/SampleConfiguration.h Source File

  • MediaEditing
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Media Editing";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cpp/Scenario3.xaml.cpp Source File

  • SimpleInk
  • cpp

Scenario3.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3.xaml.h"
00014 #include <WindowsNumerics.h>
00015
00016 #define _USE_MATH_DEFINES
00017 #include <math.h>
00018 #include <ppltasks.h>
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace concurrency;
00023 using namespace Platform;
00024 using namespace Platform::Collections;
00025 using namespace Windows::Foundation;
00026 using namespace Windows::Foundation::Collections;
00027 using namespace Windows::Foundation::Numerics;
00028 using namespace Windows::Storage;
00029 using namespace Windows::Storage::Pickers;
00030 using namespace Windows::Storage::Streams;
00031 using namespace Windows::UI::Xaml;
00032 using namespace Windows::UI::Xaml::Controls;
00033 using namespace Windows::UI::Xaml::Controls::Primitives;
00034 using namespace Windows::UI::Xaml::Data;
00035 using namespace Windows::UI::Xaml::Input;
00036 using namespace Windows::UI::Xaml::Media;
00037 using namespace Windows::UI::Xaml::Navigation;
00038 using namespace Windows::UI::Input::Inking;
00039 using namespace Windows::UI::Core;
00040
00041 Scenario3::Scenario3() : rootPage(MainPage::Current)
00042 {
00043     InitializeComponent();
00044
00045     penSize = minPenSize + penSizeIncrement * PenThickness->SelectedIndex;
00046
00047     InkDrawingAttributes^ drawingAttributes = ref new InkDrawingAttributes();
00048     drawingAttributes->Color = Windows::UI::Colors::Red;
00049     drawingAttributes->Size = Size((float)penSize, (float)penSize);
00050     drawingAttributes->IgnorePressure = false;
00051     drawingAttributes->FitToCurve = true;
00052
00053     inkCanvas->InkPresenter->UpdateDefaultDrawingAttributes(drawingAttributes);
00054     inkCanvas->InkPresenter->InputDeviceTypes = CoreInputDeviceTypes::Mouse | CoreInputDeviceTypes::Pen;
00055     inkCanvas->InkPresenter->StrokesCollected += ref new TypedEventHandler<InkPresenter^, InkStrokesCollectedEventArgs^>(this, &Scenario3::InkPresenter_StrokesCollected);
00056     inkCanvas->InkPresenter->StrokesErased += ref new TypedEventHandler<InkPresenter^, InkStrokesErasedEventArgs^>(this, &Scenario3::InkPresenter_StrokesErased);
00057 }
00058
00059 void Scenario3::OnSizeChanged(Object^ sender, SizeChangedEventArgs e)
00060 {
00061     HelperFunctions::UpdateCanvasSize(RootGrid, outputGrid, inkCanvas);
00062 }
00063
00064 void Scenario3::InkPresenter_StrokesErased(InkPresenter^ sender, InkStrokesErasedEventArgs^ args)
00065 {
00066     rootPage->NotifyUser(args->Strokes->Size + " stroke(s) erased!", NotifyType::StatusMessage);
00067 }
00068
00069 void Scenario3::InkPresenter_StrokesCollected(InkPresenter^ sender, InkStrokesCollectedEventArgs^ args)
00070 {
00071     rootPage->NotifyUser(args->Strokes->Size + " stroke(s) collected!", NotifyType::StatusMessage);
00072 }
00073
00074 void Scenario3::OnSizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00075 {
00076     HelperFunctions::UpdateCanvasSize(RootGrid, outputGrid, inkCanvas);
00077 }
00078
00079 void Scenario3::OnPenColorChanged(Object^ sender, RoutedEventArgs^ e)
00080 {
00081     if (inkCanvas != nullptr)
00082     {
00083         InkDrawingAttributes^ drawingAttributes = inkCanvas->InkPresenter->CopyDefaultDrawingAttributes();
00084
00085         // Use button's background to set new pen's color
00086         auto btnSender = safe_cast<Button^>(sender);
00087         auto brush = safe_cast<Media::SolidColorBrush^>(btnSender->Background);
00088
00089         drawingAttributes->Color = brush->Color;
00090         inkCanvas->InkPresenter->UpdateDefaultDrawingAttributes(drawingAttributes);
00091     }
00092 }
00093
00094 void Scenario3::OnPenThicknessChanged(Object^ sender, RoutedEventArgs^ e)
00095 {
00096     if (inkCanvas != nullptr)
00097     {
00098         InkDrawingAttributes^ drawingAttributes = inkCanvas->InkPresenter->CopyDefaultDrawingAttributes();
00099         penSize = minPenSize + penSizeIncrement * PenThickness->SelectedIndex;
00100         String^ value = safe_cast<ComboBoxItem^>(PenType->SelectedItem)->Content->ToString();
00101         if (value == "Highlighter" || value == "Calligraphy")
00102         {
00103             // Make the pen tip rectangular for highlighter and calligraphy pen
00104             drawingAttributes->Size = Size((float)penSize, (float)(penSize * 2));
00105         }
00106         else
00107         {
00108             // Otherwise, use a square pen tip.
00109             drawingAttributes->Size = Size((float)penSize, (float)penSize);
00110         }
00111         inkCanvas->InkPresenter->UpdateDefaultDrawingAttributes(drawingAttributes);
00112     }
00113 }
00114
00115 void Scenario3::OnPenTypeChanged(Object^ sender, RoutedEventArgs^ e)
00116 {
00117     if (inkCanvas != nullptr)
00118     {
00119         InkDrawingAttributes^ drawingAttributes = inkCanvas->InkPresenter->CopyDefaultDrawingAttributes();
00120         String^ value = safe_cast<ComboBoxItem^>(PenType->SelectedItem)->Content->ToString();
00121
00122         if (value == "Ballpoint")
00123         {
00124             if (drawingAttributes->Kind != InkDrawingAttributesKind::Default)
00125             {
00126                 auto newDrawingAttributes = ref new InkDrawingAttributes();
00127                 newDrawingAttributes->Color = drawingAttributes->Color;
00128                 drawingAttributes = newDrawingAttributes;
00129             }
00130             drawingAttributes->Size = Size((float)penSize, (float)penSize);
00131             drawingAttributes->PenTip = PenTipShape::Circle;
00132             drawingAttributes->DrawAsHighlighter = false;
00133             drawingAttributes->PenTipTransform = float3x2::identity();
00134         }
00135         else if (value == "Highlighter")
00136         {
00137             if (drawingAttributes->Kind != InkDrawingAttributesKind::Default)
00138             {
00139                 auto newDrawingAttributes = ref new InkDrawingAttributes();
00140                 newDrawingAttributes->Color = drawingAttributes->Color;
00141                 drawingAttributes = newDrawingAttributes;
00142             }
00143             // Make the pen rectangular for highlighter
00144             drawingAttributes->Size = Size((float)penSize, (float)(penSize * 2));
00145             drawingAttributes->PenTip = PenTipShape::Rectangle;
00146             drawingAttributes->DrawAsHighlighter = true;
00147             drawingAttributes->PenTipTransform = float3x2::identity();
00148         }
00149         else if (value == "Calligraphy")
00150         {
00151             if (drawingAttributes->Kind != InkDrawingAttributesKind::Default)
00152             {
00153                 auto newDrawingAttributes = ref new InkDrawingAttributes();
00154                 newDrawingAttributes->Color = drawingAttributes->Color;
00155                 drawingAttributes = newDrawingAttributes;
00156             }
00157             drawingAttributes->Size = Size((float)penSize, (float)(penSize * 2));
00158             drawingAttributes->PenTip = PenTipShape::Rectangle;
00159             drawingAttributes->DrawAsHighlighter = false;
00160
00161             // Set a 45 degree rotation on the pen tip
00162             double radians = 45.0 * M_PI / 180.0;
00163             drawingAttributes->PenTipTransform = make_float3x2_rotation((float)radians);
00164         }
00165         else if (value == "Pencil")
00166         {
00167             if (drawingAttributes->Kind != InkDrawingAttributesKind::Pencil)
00168             {
00169                 auto newDrawingAttributes = InkDrawingAttributes::CreateForPencil();
00170                 newDrawingAttributes->Color = drawingAttributes->Color;
00171                 newDrawingAttributes->Size = drawingAttributes->Size;
00172                 drawingAttributes = newDrawingAttributes;
00173             }
00174         }
00175         inkCanvas->InkPresenter->UpdateDefaultDrawingAttributes(drawingAttributes);
00176     }
00177 }
00178
00179 void Scenario3::OnClear(Object^ sender, RoutedEventArgs^ e)
00180 {
00181     inkCanvas->InkPresenter->StrokeContainer->Clear();
00182     rootPage->NotifyUser("Cleared Canvas", NotifyType::StatusMessage);
00183 }
00184
00185 void Scenario3::OnSaveAsync(Object^ sender, RoutedEventArgs^ e)
00186 {
00187     // We don't want to save an empty file
00188     if (inkCanvas->InkPresenter->StrokeContainer->GetStrokes()->Size == 0)
00189     {
00190         rootPage->NotifyUser("There is no ink to save.", NotifyType::ErrorMessage);
00191         return;
00192     }
00193
00194     auto savePicker = ref new FileSavePicker();
00195     savePicker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00196     savePicker->FileTypeChoices->Insert("Gif with embedded ISF", ref new Vector<String^>({ ".gif" }));
00197     savePicker->SuggestedFileName = "Scenario3";
00198
00199     create_task(savePicker->PickSaveFileAsync()).then([this](StorageFile^ file)
00200     {
00201         if (file != nullptr)
00202         {
00203             // write to file
00204             return create_task(file->OpenAsync(FileAccessMode::ReadWrite))
00205                 .then([this](IRandomAccessStream^ stream)
00206             {
00207                 return create_task(inkCanvas->InkPresenter->StrokeContainer->SaveAsync(stream))
00208                     .then([this, stream](task<unsigned int> saveTask)
00209                 {
00210                     // Always close the stream, even if an error occurs.
00211                     delete stream;
00212
00213                     return saveTask;
00214                 });
00215             }).then([this, file](task<unsigned int> openSaveTask)
00216             {
00217                 // Report whether the file was successfully saved.
00218                 try
00219                 {
00220                     openSaveTask.get();
00221                     rootPage->NotifyUser(inkCanvas->InkPresenter->StrokeContainer->GetStrokes()->Size.ToString() + " stroke(s) saved!", NotifyType::StatusMessage);
00222                 }
00223                 catch (Platform::Exception^ ex)
00224                 {
00225                     //Example output: The system cannot find the specified file.
00226                     rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00227                 }
00228             });
00229         }
00230         else
00231         {
00232             return task_from_result();
00233         }
00234     });
00235 }
00236
00237 void Scenario3::OnLoadAsync(Object^ sender, RoutedEventArgs^ e)
00238 {
00239     auto openPicker = ref new FileOpenPicker();
00240     openPicker->SuggestedStartLocation = PickerLocationId::PicturesLibrary;
00241     openPicker->FileTypeFilter->Append(".gif");
00242     openPicker->FileTypeFilter->Append(".isf");
00243
00244     create_task(openPicker->PickSingleFileAsync()).then([this](StorageFile^ file)
00245     {
00246         if (file != nullptr)
00247         {
00248             return create_task(file->OpenSequentialReadAsync())
00249                 .then([this, file](IInputStream^ stream)
00250             {
00251                 return create_task(inkCanvas->InkPresenter->StrokeContainer->LoadAsync(stream))
00252                     .then([stream](task<void> loadTask)
00253                 {
00254                     // Always close the stream, even if an error occurs.
00255                     delete stream;
00256
00257                     return loadTask;
00258                 });
00259             }).then([this](task<void> openLoadTask)
00260             {
00261                 // Report whether the file was successfully loaded.
00262                 try
00263                 {
00264                     openLoadTask.get();
00265                     rootPage->NotifyUser(inkCanvas->InkPresenter->StrokeContainer->GetStrokes()->Size.ToString() + " stroke(s) loaded!", NotifyType::StatusMessage);
00266                 }
00267                 catch (Platform::Exception^ ex)
00268                 {
00269                     // Report any I/O errors.
00270                     rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
00271                 }
00272             });
00273         }
00274         else
00275         {
00276             return task_from_result();
00277         }
00278     });
00279 }
00280
00281 void Scenario3::TouchInkingCheckBox_Checked(Object^ sender, RoutedEventArgs^ e)
00282 {
00283     auto types = inkCanvas->InkPresenter->InputDeviceTypes | CoreInputDeviceTypes::Touch;
00284     inkCanvas->InkPresenter->InputDeviceTypes = types;
00285     rootPage->NotifyUser("Enable Touch Inking", NotifyType::StatusMessage);
00286 }
00287
00288 void Scenario3::TouchInkingCheckBox_Unchecked(Object^ sender, RoutedEventArgs^ e)
00289 {
00290     auto types = inkCanvas->InkPresenter->InputDeviceTypes & ~CoreInputDeviceTypes::Touch;
00291     inkCanvas->InkPresenter->InputDeviceTypes = types;
00292     rootPage->NotifyUser("Disable Touch Inking", NotifyType::StatusMessage);
00293 }
00294
00295 void Scenario3::ErasingModeCheckBox_Checked(Object^ sender, RoutedEventArgs^ e)
00296 {
00297     inkCanvas->InkPresenter->InputProcessingConfiguration->Mode = InkInputProcessingMode::Erasing;
00298     rootPage->NotifyUser("Enable Erasing Mode", NotifyType::StatusMessage);
00299 }
00300
00301 void Scenario3::ErasingModeCheckBox_Unchecked(Object^ sender, RoutedEventArgs^ e)
00302 {
00303     inkCanvas->InkPresenter->InputProcessingConfiguration->Mode = InkInputProcessingMode::Inking;
00304     rootPage->NotifyUser("Disable Erasing Mode", NotifyType::StatusMessage);
00305 }
Generated on Fri Nov 15 2024 22:18:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cs/Scenario7_ForegroundVisits.xaml.cs Source File

  • Geolocation
  • cs

Scenario7_ForegroundVisits.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using Windows.Devices.Geolocation;
00015 using Windows.Foundation;
00016 using Windows.UI.Core;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     public sealed partial class Scenario7_ForegroundVisits : Page
00024     {
00025         // Provides access to visits
00026         private GeovisitMonitor _visitMonitor = null;
00027
00028         // A pointer to the main page
00029         private MainPage _rootPage = MainPage.Current;
00030
00031         public Scenario7_ForegroundVisits()
00032         {
00033             this.InitializeComponent();
00034         }
00035
00036         protected override void OnNavigatedFrom(NavigationEventArgs e)
00037         {
00038             if (_visitMonitor != null)
00039             {
00040                 _visitMonitor.Stop();
00041                 _visitMonitor.VisitStateChanged -= OnVisitStateChanged;
00042             }
00043         }
00044
00045         /// <summary>
00046         /// This is the click handler for the 'StartMonitoring' button.
00047         /// </summary>
00048         /// <param name="sender"></param>
00049         /// <param name="e"></param>
00050         private async void StartMonitoring(object sender, RoutedEventArgs e)
00051         {
00052             // Request permission to access location
00053             var accessStatus = await Geolocator.RequestAccessAsync();
00054
00055             switch (accessStatus)
00056             {
00057                 case GeolocationAccessStatus.Allowed:
00058
00059                     _visitMonitor = new GeovisitMonitor();
00060
00061                     // Add visit state changed event handler.
00062                     _visitMonitor.VisitStateChanged += OnVisitStateChanged;
00063
00064                     // Start monitoring with the desired scope.
00065                     // For higher granularity such as building/venue level changes, choose venue.
00066                     // For lower granularity more or less in the range of zipcode level changes, choose city.
00067                     // Choosing Venue here as an example.
00068                     _visitMonitor.Start(VisitMonitoringScope.Venue);
00069
00070                     LocationDisabledMessage.Visibility = Visibility.Collapsed;
00071                     _rootPage.NotifyUser("Waiting for update...", NotifyType.StatusMessage);
00072
00073                     StartMonitoringButton.IsEnabled = false;
00074                     StopMonitoringButton.IsEnabled = true;
00075                     break;
00076
00077                 case GeolocationAccessStatus.Denied:
00078                     _rootPage.NotifyUser("Access to location is denied.", NotifyType.ErrorMessage);
00079                     LocationDisabledMessage.Visibility = Visibility.Visible;
00080                     break;
00081
00082                 default:
00083                 case GeolocationAccessStatus.Unspecified:
00084                     _rootPage.NotifyUser("Unspecificed error!", NotifyType.ErrorMessage);
00085                     LocationDisabledMessage.Visibility = Visibility.Collapsed;
00086                     break;
00087             }
00088         }
00089
00090         /// <summary>
00091         /// This is the click handler for the 'StopMonitoring' button.
00092         /// </summary>
00093         /// <param name="sender"></param>
00094         /// <param name="e"></param>
00095         private void StopMonitoring(object sender, RoutedEventArgs e)
00096         {
00097             // Stop visit monitoring.
00098             _visitMonitor.Stop();
00099             _visitMonitor.VisitStateChanged -= OnVisitStateChanged;
00100             _visitMonitor = null;
00101
00102             StartMonitoringButton.IsEnabled = true;
00103             StopMonitoringButton.IsEnabled = false;
00104
00105             // Clear status
00106             _rootPage.NotifyUser("", NotifyType.StatusMessage);
00107         }
00108
00109         /// <summary>
00110         /// Event handler for VisitStateChanged events. It is raised when
00111         /// a new visit state change is available based on the monitoring scope specified.
00112         /// </summary>
00113         /// <param name="sender">Geovisitmonitor instance</param>
00114         /// <param name="args">VisitStateChanged args data</param>
00115         async private void OnVisitStateChanged(GeovisitMonitor sender, GeovisitStateChangedEventArgs args)
00116         {
00117             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00118             {
00119                 _rootPage.NotifyUser("Visit state changed.", NotifyType.StatusMessage);
00120                 UpdateVisitData(args.Visit);
00121             });
00122         }
00123
00124         /// <summary>
00125         /// Updates the user interface with the Geovisit data provided
00126         /// </summary>
00127         /// <param name="visit">Geovisit to display its details</param>
00128         private void UpdateVisitData(Geovisit visit)
00129         {
00130             // A valid visit is available, extract the state change and Timestamp.
00131             ScenarioOutput_VisitStateChange.Text = visit.StateChange.ToString();
00132             ScenarioOutput_Timestamp.Text = visit.Timestamp.ToString();
00133
00134             // If a valid position is available, extract the position information that caused the state change to happen.
00135             if (visit.Position == null)
00136             {
00137                 ScenarioOutput_Latitude.Text   = "No data";
00138                 ScenarioOutput_Longitude.Text  = "No data";
00139                 ScenarioOutput_Accuracy.Text   = "No data";
00140                 ScenarioOutput_IsRemoteSource.Text = "No data";
00141             }
00142             else
00143             {
00144                 ScenarioOutput_Latitude.Text    = visit.Position.Coordinate.Point.Position.Latitude.ToString();
00145                 ScenarioOutput_Longitude.Text   = visit.Position.Coordinate.Point.Position.Longitude.ToString();
00146                 ScenarioOutput_Accuracy.Text    = visit.Position.Coordinate.Accuracy.ToString();
00147                 ScenarioOutput_IsRemoteSource.Text = visit.Position.Coordinate.IsRemoteSource.ToString();
00148             }
00149         }
00150     }
00151 }
Generated on Fri Nov 15 2024 22:19:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_ScriptDetection Member List

This is the complete list of members for Scenario2_ScriptDetection, including all inherited members.
Go_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_ScriptDetection
Scenario2_ScriptDetection() | Scenario2_ScriptDetection
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAccountManagement/cs/SingleMicrosoftAccountScenario.xaml.cs Source File

  • WebAccountManagement
  • cs

SingleMicrosoftAccountScenario.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.ApplicationSettings;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using SDKTemplate;
00017 using Windows.Security.Credentials;
00018 using Windows.Security.Authentication.Web.Core;
00019 using System;
00020 using Windows.Storage;
00021 using System.Threading.Tasks;
00022 using Windows.UI.Popups;
00023 using Windows.Security.Authentication.Web.Provider;
00024
00025 namespace Accounts
00026 {
00027     public sealed partial class SingleMicrosoftAccountScenario : Page
00028     {
00029         private MainPage rootPage;
00030
00031         // To obtain Microsoft account tokens, you must register your application online
00032         // Then, you must associate the app with the store.
00033         const string MicrosoftAccountProviderId = "https://login.microsoft.com";
00034         const string ConsumerAuthority = "consumers";
00035         const string AccountScopeRequested = "wl.basic";
00036         const string AccountClientId = "none";
00037         const string StoredAccountKey = "accountid";
00038
00039         public SingleMicrosoftAccountScenario()
00040         {
00041             this.InitializeComponent();
00042         }
00043
00044         protected override void OnNavigatedTo(NavigationEventArgs e)
00045         {
00046             rootPage = MainPage.Current;
00047
00048             // The AccountCommandsRequested event triggers before the Accounts settings pane is displayed
00049             AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += OnAccountCommandsRequested;
00050
00051             IdentityChecker.SampleIdentityConfigurationCorrect(NotRegisteredWarning);
00052         }
00053
00054         protected override void OnNavigatedFrom(NavigationEventArgs e)
00055         {
00056             AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= OnAccountCommandsRequested;
00057         }
00058
00059
00060         private void Button_ShowAccountSettings(object sender, RoutedEventArgs e)
00061         {
00062             ((Button)sender).IsEnabled = false;
00063
00064             rootPage.NotifyUser("Launching AccountSettingsPane", NotifyType.StatusMessage);
00065
00066             AccountsSettingsPane.Show();
00067
00068             ((Button)sender).IsEnabled = true;
00069         }
00070
00071         private async void Button_Reset(object sender, RoutedEventArgs e)
00072         {
00073             ((Button)sender).IsEnabled = false;
00074
00075             rootPage.NotifyUser("Resetting...", NotifyType.StatusMessage);
00076
00077             await LogoffAndRemoveAccount();
00078
00079             ((Button)sender).IsEnabled = true;
00080
00081         }
00082
00083
00084         // This event handler is called when the Account settings pane is to be launched.
00085         private async void OnAccountCommandsRequested(
00086             AccountsSettingsPane sender,
00087             AccountsSettingsPaneCommandsRequestedEventArgs e)
00088         {
00089             // In order to make async calls within this callback, the deferral object is needed
00090             AccountsSettingsPaneEventDeferral deferral = e.GetDeferral();
00091
00092             // This scenario only lets the user have one account at a time.
00093             // If there already is an account, we do not include a provider in the list
00094             // This will prevent the add account button from showing up.
00095             bool isPresent = ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAccountKey);
00096
00097             if (isPresent)
00098             {
00099                 await AddWebAccount(e);
00100             }
00101             else
00102             {
00103                 await AddWebAccountProvider(e);
00104             }
00105
00106             AddLinksAndDescription(e);
00107
00108             deferral.Complete();
00109         }
00110
00111
00112         private async Task AddWebAccountProvider(AccountsSettingsPaneCommandsRequestedEventArgs e)
00113         {
00114             // FindAccountProviderAsync returns the WebAccountProvider of an installed plugin
00115             // The Provider and Authority specifies the specific plugin
00116             // This scenario only supports Microsoft accounts.
00117
00118             // The Microsoft account provider is always present in Windows 10 devices, as is the Azure AD plugin.
00119             // If a non-installed plugin or incorect identity is specified, FindAccountProviderAsync will return null
00120             WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority);
00121
00122             WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);
00123             e.WebAccountProviderCommands.Add(providerCommand);
00124         }
00125
00126         private async Task AddWebAccount(AccountsSettingsPaneCommandsRequestedEventArgs e)
00127         {
00128             WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority);
00129
00130             String accountID = (String)ApplicationData.Current.LocalSettings.Values[StoredAccountKey];
00131             WebAccount account = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountID);
00132
00133             if (account == null)
00134             {
00135                 // The account has most likely been deleted in Windows settings
00136                 // Unless there would be significant data loss, you should just delete the account
00137                 // If there would be significant data loss, prompt the user to either re-add the account, or to remove it
00138                 ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey);
00139             }
00140
00141             WebAccountCommand command = new WebAccountCommand(account, WebAccountInvoked, SupportedWebAccountActions.Remove);
00142             e.WebAccountCommands.Add(command);
00143         }
00144
00145         private void AddLinksAndDescription(AccountsSettingsPaneCommandsRequestedEventArgs e)
00146         {
00147             e.HeaderText = "Describe what adding an account to your application will do for the user";
00148
00149             // You can add links such as privacy policy, help, general account settings
00150             e.Commands.Add(new SettingsCommand("privacypolicy", "Privacy policy", PrivacyPolicyInvoked));
00151             e.Commands.Add(new SettingsCommand("otherlink", "Other link", OtherLinkInvoked));
00152         }
00153
00154         private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
00155         {
00156             // ClientID is ignored by MSA
00157             await RequestTokenAndSaveAccount(command.WebAccountProvider, AccountScopeRequested, AccountClientId);
00158         }
00159
00160         private async void WebAccountInvoked(WebAccountCommand command, WebAccountInvokedArgs args)
00161         {
00162             if (args.Action == WebAccountAction.Remove)
00163             {
00164                 rootPage.NotifyUser("Removing account", NotifyType.StatusMessage);
00165                 await LogoffAndRemoveAccount();
00166             }
00167         }
00168
00169         private void PrivacyPolicyInvoked(IUICommand command)
00170         {
00171             rootPage.NotifyUser("Privacy policy clicked by user", NotifyType.StatusMessage);
00172         }
00173
00174         private void OtherLinkInvoked(IUICommand command)
00175         {
00176             rootPage.NotifyUser("Other link pressed by user", NotifyType.StatusMessage);
00177         }
00178
00179         private async Task RequestTokenAndSaveAccount(WebAccountProvider Provider, String Scope, String ClientID)
00180         {
00181             try
00182             {
00183                 WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID);
00184                 rootPage.NotifyUser("Requesting Web Token", NotifyType.StatusMessage);
00185
00186                 // If the user selected a specific account, RequestTokenAsync will return a token for that account.
00187                 // The user may be prompted for credentials or to authorize using that account with your app
00188                 // If the user selected a provider, the user will be prompted for credentials to login to a new account
00189                 WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
00190
00191                 // If a token was successfully returned, then store the WebAccount Id into local app data
00192                 // This Id can be used to retrieve the account whenever needed. To later get a token with that account
00193                 // First retrieve the account with FindAccountAsync, and include that webaccount
00194                 // as a parameter to RequestTokenAsync or RequestTokenSilentlyAsync
00195                 if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
00196                 {
00197                     ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey);
00198
00199                     ApplicationData.Current.LocalSettings.Values[StoredAccountKey] = webTokenRequestResult.ResponseData[0].WebAccount.Id;
00200                 }
00201
00202                 OutputTokenResult(webTokenRequestResult);
00203             }
00204             catch (Exception ex)
00205             {
00206                 rootPage.NotifyUser("Web Token request failed: " + ex.Message, NotifyType.ErrorMessage);
00207             }
00208         }
00209
00210         private void OutputTokenResult(WebTokenRequestResult result)
00211         {
00212             if (result.ResponseStatus == WebTokenRequestStatus.Success)
00213             {
00214                 rootPage.NotifyUser("Web Token request successful for user: " + result.ResponseData[0].WebAccount.UserName, NotifyType.StatusMessage);
00215                 SignInButton.Content = "Account";
00216             }
00217             else
00218             {
00219                 rootPage.NotifyUser("Web Token request error: " + result.ResponseError, NotifyType.StatusMessage);
00220             }
00221         }
00222
00223         private async Task LogoffAndRemoveAccount()
00224         {
00225             if (ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAccountKey))
00226             {
00227                 WebAccountProvider providertoDelete = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority);
00228
00229                 WebAccount accountToDelete = await WebAuthenticationCoreManager.FindAccountAsync(providertoDelete, (string)ApplicationData.Current.LocalSettings.Values[StoredAccountKey]);
00230
00231                 if(accountToDelete != null)
00232                 {
00233                     await accountToDelete.SignOutAsync();
00234                 }
00235
00236                 ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey);
00237
00238                 SignInButton.Content = "Sign in";
00239             }
00240         }
00241     }
00242 }
Generated on Fri Nov 15 2024 22:21:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cppwinrt/Scenario2_Connector.h Source File

  • WiFiDirect
  • cppwinrt

Scenario2_Connector.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_Connector.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario2_Connector : Scenario2_ConnectorT<Scenario2_Connector>
00019     {
00020         Scenario2_Connector();
00021
00022         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00023
00024         auto DiscoveredDevices() { return discoveredDevices; }
00025         auto ConnectedDevices() { return connectedDevices; }
00026
00027         void btnWatcher_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void btnIe_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029         fire_and_forget btnFromId_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00030         fire_and_forget btnSendMessage_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00031         void btnClose_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00032         fire_and_forget btnUnpair_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00033
00034     private:
00035         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00036         Windows::Devices::Enumeration::DeviceWatcher deviceWatcher{ nullptr };
00037         Windows::Devices::WiFiDirect::WiFiDirectAdvertisementPublisher publisher;
00038
00039         Windows::Foundation::Collections::IObservableVector<SDKTemplate::DiscoveredDevice> discoveredDevices{ single_threaded_observable_vector<SDKTemplate::DiscoveredDevice>() };
00040         Windows::Foundation::Collections::IObservableVector<SDKTemplate::ConnectedDevice> connectedDevices{ single_threaded_observable_vector<SDKTemplate::ConnectedDevice>() };
00041
00042         event_token watcherAddedToken;
00043         event_token watcherRemovedToken;
00044         event_token watcherUpdatedToken;
00045         event_token watcherEnumerationCompletedToken;
00046         event_token watcherStoppedToken;
00047
00048         void StopWatcher();
00049         fire_and_forget OnDeviceAdded(Windows::Devices::Enumeration::DeviceWatcher const&, Windows::Devices::Enumeration::DeviceInformation deviceInfo);
00050         fire_and_forget OnDeviceRemoved(Windows::Devices::Enumeration::DeviceWatcher const&, Windows::Devices::Enumeration::DeviceInformationUpdate deviceInfoUpdate);
00051         fire_and_forget OnDeviceUpdated(Windows::Devices::Enumeration::DeviceWatcher const&, Windows::Devices::Enumeration::DeviceInformationUpdate deviceInfoUpdate);
00052         void OnEnumerationCompleted(Windows::Devices::Enumeration::DeviceWatcher const&, Windows::Foundation::IInspectable const&);
00053         void OnStopped(Windows::Devices::Enumeration::DeviceWatcher const&, Windows::Foundation::IInspectable const&);
00054
00055         void OnConnectionStatusChanged(Windows::Devices::WiFiDirect::WiFiDirectDevice const& sender, Windows::Foundation::IInspectable const&);
00056     };
00057 }
00058
00059 namespace winrt::SDKTemplate::factory_implementation
00060 {
00061     struct Scenario2_Connector : Scenario2_ConnectorT<Scenario2_Connector, implementation::Scenario2_Connector>
00062     {
00063     };
00064 }
Generated on Fri Nov 15 2024 22:22:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/PlotData.h Source File

  • WindowsAudioSession
  • cppwinrt

PlotData.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012 #include "PlotDataReadyEventArgs.g.h"
00013
00014 namespace winrt::SDKTemplate::implementation
00015 {
00016     // Class for PlotDataReady events
00017     struct PlotDataReadyEventArgs : PlotDataReadyEventArgsT<PlotDataReadyEventArgs>
00018     {
00019         PlotDataReadyEventArgs(Windows::Storage::Streams::IBuffer const& buffer) : m_buffer(buffer) {}
00020
00021         auto Points() { return m_buffer; }
00022
00023     private:
00024         Windows::Storage::Streams::IBuffer const m_buffer;
00025     };
00026
00027     template<typename D>
00028     struct PlotDataSourceT
00029     {
00030         event_token PlotDataReady(Windows::Foundation::TypedEventHandler<IPlotDataSource, SDKTemplate::PlotDataReadyEventArgs> const& handler)
00031         {
00032             return m_plotDataReady.add(handler);
00033         }
00034         void PlotDataReady(event_token token)
00035         {
00036             return m_plotDataReady.remove(token);
00037         }
00038
00039     protected:
00040         event<Windows::Foundation::TypedEventHandler<IPlotDataSource, SDKTemplate::PlotDataReadyEventArgs>> m_plotDataReady;
00041
00042         void ReportPlotDataReady(Windows::Storage::Streams::IBuffer const& buffer)
00043         {
00044             m_plotDataReady(*static_cast<D*>(this), make<implementation::PlotDataReadyEventArgs>(buffer));
00045         }
00046     };
00047 }
Generated on Fri Nov 15 2024 22:22:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppWindow/cppwinrt/Scenario2_DisplayRegion.cpp Source File

  • AppWindow
  • cppwinrt

Scenario2_DisplayRegion.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_DisplayRegion.h"
00014 #include "Scenario2_DisplayRegion.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::ViewManagement;
00021 using namespace Windows::UI::WindowManagement;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Hosting;
00024 using namespace Windows::UI::Xaml::Navigation;
00025
00026 namespace winrt::SDKTemplate::implementation
00027 {
00028     Scenario2_DisplayRegion::Scenario2_DisplayRegion()
00029     {
00030         InitializeComponent();
00031     }
00032
00033     void Scenario2_DisplayRegion::OnNavigatedTo(NavigationEventArgs const&)
00034     {
00035         // Check to see if we have more than one DisplayRegion, if not we disable the button since the scenario will not work
00036
00037         showWindowBtn().IsEnabled(NumberOfAvailableDisplayRegions() > 1);
00038     }
00039
00040     fire_and_forget Scenario2_DisplayRegion::OnNavigatedFrom(NavigationEventArgs const&)
00041     {
00042         if (appWindow != nullptr)
00043         {
00044             co_await appWindow.CloseAsync();
00045         }
00046     }
00047
00048     int Scenario2_DisplayRegion::NumberOfAvailableDisplayRegions()
00049     {
00050         // Get the list of all DisplayRegions defined for the WindowingEnvironment that our application is currently in
00051         IVectorView<DisplayRegion> displayRegions = ApplicationView::GetForCurrentView().WindowingEnvironment().GetDisplayRegions();
00052
00053         int availableDisplayRegions = 0;
00054         // count all the DisplayRegions that are marked as available to the app for use.
00055         for (DisplayRegion const& displayregion : displayRegions)
00056         {
00057             if (displayregion.IsVisible())
00058             {
00059                 availableDisplayRegions++;
00060             }
00061         }
00062         return availableDisplayRegions;
00063     }
00064
00065     DisplayRegion Scenario2_DisplayRegion::GetOtherDisplayRegion(DisplayRegion currentAppDisplayRegion)
00066     {
00067         // Get the list of all DisplayRegions defined for the WindowingEnvironment that our application is currently in
00068         IVectorView<DisplayRegion> displayRegions = ApplicationView::GetForCurrentView().WindowingEnvironment().GetDisplayRegions();
00069         for (DisplayRegion const& displayRegion : displayRegions)
00070         {
00071             if (displayRegion != currentAppDisplayRegion && displayRegion.IsVisible())
00072             {
00073                 return displayRegion;
00074             }
00075         }
00076
00077         return nullptr;
00078     }
00079
00080     fire_and_forget Scenario2_DisplayRegion::Button_Click(IInspectable const&, RoutedEventArgs const&)
00081     {
00082         auto lifetime = get_strong();
00083
00084         unique_disabled_control re_enabled{ showWindowBtn() };
00085
00086         // Only ever create one window. If the AppWindow already exists call TryShow on it to bring it to foreground.
00087         if (appWindow == nullptr)
00088         {
00089             // Create a new window
00090             appWindow = co_await AppWindow::TryCreateAsync();
00091             // Clean up when the window is closed
00092             appWindow.Closed({ get_weak(), &Scenario2_DisplayRegion::OnWindowClosed });
00093             // Navigate the frame to the page we want to show in the new window
00094             appWindowFrame.Navigate(xaml_typename<SDKTemplate::SecondaryAppWindowPage>());
00095             // Attach the XAML content to our window
00096             ElementCompositionPreview::SetAppWindowContent(appWindow, appWindowFrame);
00097         }
00098
00099         // Get DisplayRegion to position our window on
00100         DisplayRegion secondaryDisplayRegion = GetOtherDisplayRegion(ApplicationView::GetForCurrentView().GetDisplayRegions().GetAt(0));
00101         if (secondaryDisplayRegion != nullptr)
00102         {
00103             appWindow.RequestMoveToDisplayRegion(secondaryDisplayRegion);
00104         }
00105
00106         // If the window is not visible, show it and/or bring it to foreground
00107         if (!appWindow.IsVisible())
00108         {
00109             co_await appWindow.TryShowAsync();
00110         }
00111     }
00112
00113     void Scenario2_DisplayRegion::OnWindowClosed(AppWindow const&, IInspectable const&)
00114     {
00115         // Make sure we release the reference to this window, and release XAML resources.
00116         appWindow = nullptr;
00117         appWindowFrame.Content(nullptr);
00118     }
00119
00120 }
Generated on Fri Nov 15 2024 22:18:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSuggestion/cpp/Scenario1_Conversion.xaml.h Source File

  • TextSuggestion
  • cpp

Scenario1_Conversion.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario1_Conversion.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     /// <summary>
00011     /// An empty page that can be used on its own or navigated to within a Frame.
00012     /// </summary>
00013     [Windows::Foundation::Metadata::WebHostHidden]
00014     public ref class Scenario1_Conversion sealed
00015     {
00016     public:
00017         Scenario1_Conversion();
00018     private:
00019         MainPage^ rootPage;
00020
00021         void CreateGeneratorButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00022         void Methods_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
00023         void Execute_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00024
00025         void DisplayMultipleCandidates(Windows::Foundation::Collections::IVectorView<Platform::String^>^ candidates);
00026
00027         Windows::Data::Text::TextConversionGenerator^ generator;
00028     };
00029 }
00030
Generated on Fri Nov 15 2024 22:21:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Settings Member List

This is the complete list of members for Scenario2_Settings, including all inherited members.
DeleteSetting_Click(Object sender, RoutedEventArgs e) | Scenario2_Settings | [inline, private]
DisplayOutput() | Scenario2_Settings | [inline, private]
localSettings | Scenario2_Settings | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_Settings | [inline, protected]
Scenario2_Settings() | Scenario2_Settings | [inline]
SettingName | Scenario2_Settings | [private]
WriteSetting_Click(Object sender, RoutedEventArgs e) | Scenario2_Settings | [inline, private]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

App Member List

This is the complete list of members for App, including all inherited members.
App() | App | [inline]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
Generated on Fri Nov 15 2024 22:23:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LowLatencyInputMain Member List

This is the complete list of members for LowLatencyInputMain, including all inherited members.
criticalSection | LowLatencyInputMain | [private]
deviceResources | LowLatencyInputMain | [private]
GetCriticalSection() | LowLatencyInputMain | [inline]
HitTest(Windows::Foundation::Point position) | LowLatencyInputMain |
LowLatencyInputMain(const std::shared_ptr< DX::DeviceResources > &deviceResources) | LowLatencyInputMain |
OnDeviceLost() | LowLatencyInputMain | [virtual]
OnDeviceRestored() | LowLatencyInputMain | [virtual]
Render() | LowLatencyInputMain | [private]
renderLoopWorker | LowLatencyInputMain | [private]
ResetRect() | LowLatencyInputMain |
sceneRenderer | LowLatencyInputMain | [private]
SetBrushColor(D2D1::ColorF color) | LowLatencyInputMain |
SetRectSize(float newSize) | LowLatencyInputMain |
StartRenderLoop() | LowLatencyInputMain |
StopRenderLoop() | LowLatencyInputMain |
UpdateRectTransform(Windows::Foundation::Point newPosition, Windows::UI::Input::ManipulationDelta newDelta) | LowLatencyInputMain |
~LowLatencyInputMain() | LowLatencyInputMain |
Generated on Fri Nov 15 2024 22:23:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario_PredefinedWebSearchGrammar Member List

This is the complete list of members for Scenario_PredefinedWebSearchGrammar, including all inherited members.
cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e) | Scenario_PredefinedWebSearchGrammar | [inline, private]
HResultPrivacyStatementDeclined | Scenario_PredefinedWebSearchGrammar | [private, static]
InitializeRecognizer(Language recognizerLanguage) | Scenario_PredefinedWebSearchGrammar | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario_PredefinedWebSearchGrammar | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario_PredefinedWebSearchGrammar | [inline, protected]
openPrivacySettings_Click(Hyperlink sender, HyperlinkClickEventArgs args) | Scenario_PredefinedWebSearchGrammar | [inline, private]
PopulateLanguageDropDown() | Scenario_PredefinedWebSearchGrammar | [inline, private]
recognitionOperation | Scenario_PredefinedWebSearchGrammar | [private]
RecognizeWithoutUIWebSearchGrammar_Click(object sender, RoutedEventArgs e) | Scenario_PredefinedWebSearchGrammar | [inline, private]
RecognizeWithUIWebSearchGrammar_Click(object sender, RoutedEventArgs e) | Scenario_PredefinedWebSearchGrammar | [inline, private]
Scenario_PredefinedWebSearchGrammar() | Scenario_PredefinedWebSearchGrammar | [inline]
speechContext | Scenario_PredefinedWebSearchGrammar | [private]
speechRecognizer | Scenario_PredefinedWebSearchGrammar | [private]
SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args) | Scenario_PredefinedWebSearchGrammar | [inline, private]
speechResourceMap | Scenario_PredefinedWebSearchGrammar | [private]
Generated on Fri Nov 15 2024 22:24:01 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAuthenticationBroker/cpp/pch.h Source File

  • WebAuthenticationBroker
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Cursor Member List

This is the complete list of members for Cursor, including all inherited members.
CreateDeviceDependentResources() | Cursor |
Cursor(const float width, const float height) | Cursor |
Initialize(const std::shared_ptr< DX::DeviceResources > &deviceResources) | Cursor |
m_cursorTextureView | Cursor | [private]
m_deviceResources | Cursor | [private]
m_distance | Cursor | [private]
m_geometryShader | Cursor | [private]
m_indexBuffer | Cursor | [private]
m_indexCount | Cursor | [private]
m_inputLayout | Cursor | [private]
m_loadingComplete | Cursor | [private]
m_modelConstantBuffer | Cursor | [private]
m_modelConstantBufferData | Cursor | [private]
m_pixelShader | Cursor | [private]
m_samplerState | Cursor | [private]
m_size | Cursor | [private]
m_textureIndex | Cursor | [private]
m_usingVprtShaders | Cursor | [private]
m_vertexBuffer | Cursor | [private]
m_vertexShader | Cursor | [private]
PositionCursor(Windows::UI::Input::Spatial::SpatialPointerPose^pointerPose, DirectX::XMMATRIX &modelTransform) | Cursor | [private]
ReleaseDeviceDependentResources() | Cursor |
Render() | Cursor |
SetDistance(const float distance) | Cursor | [inline]
Update(const DX::StepTimer &timer, HolographicFrame^holographicFrame, SpatialCoordinateSystem^currentCoordinateSystem, SpatialInteractionSourceState^interactionSource) | Cursor |
Generated on Fri Nov 15 2024 22:23:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_Polling Member List

This is the complete list of members for Scenario2_Polling, including all inherited members.
_compass | Scenario2_Polling | [private]
_desiredReportInterval | Scenario2_Polling | [private]
_dispatcherTimer | Scenario2_Polling | [private]
_magnetometer | Scenario2_Polling | [private]
_sensor | Scenario2_Polling | [private]
DisplayCurrentReading(object sender, object args) | Scenario2_Polling | [inline, private]
DisplayCurrentReading(object sender, object args) | Scenario2_Polling | [inline, private]
DisplayCurrentReading(object sender, object args) | Scenario2_Polling | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_Polling | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_Polling | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_Polling | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario2_Polling | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario2_Polling | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario2_Polling | [inline, protected]
rootPage | Scenario2_Polling | [private]
Scenario2_Polling() | Scenario2_Polling | [inline]
Scenario2_Polling() | Scenario2_Polling | [inline]
Scenario2_Polling() | Scenario2_Polling | [inline]
Scenario2_Polling() | Scenario2_Polling | [inline]
Scenario2_Polling() | Scenario2_Polling | [inline]
Scenario2_Polling() | Scenario2_Polling | [inline]
ScenarioDisable(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
ScenarioDisable(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
ScenarioDisable() | Scenario2_Polling | [inline, private]
ScenarioEnable(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
ScenarioEnable(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
ScenarioEnable() | Scenario2_Polling | [inline, private]
ScenarioGetData(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
ScenarioGetData(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
ScenarioGetData_Click(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
ScenarioGetSensor_Click(object sender, RoutedEventArgs e) | Scenario2_Polling | [inline, private]
sensor | Scenario2_Polling | [private]
sensor | Scenario2_Polling | [private]
sensor | Scenario2_Polling | [private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario2_Polling | [inline, private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario2_Polling | [inline, private]
VisibilityChanged(object sender, VisibilityChangedEventArgs e) | Scenario2_Polling | [inline, private]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 3DPrintingFromUnity/Assets/Script/Print3D.cs Source File

  • 3DPrintingFromUnity
  • Assets
  • Script

Print3D.cs

Go to the documentation of this file.
00001 ﻿using UnityEngine;
00002 using System.Collections;
00003 using System;
00004 using System.IO;
00005 using System.Threading;
00006 using System.ComponentModel;
00007 #if UNITY_WSA && !UNITY_EDITOR
00008 using System.Collections.Generic;
00009 using System.Linq;
00010 using System.Xml.Linq;
00011 using System.Text;
00012 using Windows.ApplicationModel.Core;
00013 using Windows.Graphics.Printing3D;
00014 using Windows.UI.Core;
00015 using System.Numerics;
00016 using System.Runtime.InteropServices.WindowsRuntime;
00017 using System.Threading.Tasks;
00018 using Windows.Devices.Geolocation;
00019 using Windows.Foundation;
00020 using Windows.Storage;
00021 using Windows.Storage.Streams;
00022 using Windows.UI.Xaml;
00023 using Windows.UI.Xaml.Controls;
00024 using Windows.UI.Xaml.Navigation;
00025 #endif
00026
00027 public class Print3D : MonoBehaviour
00028 {
00029     private static string Step1 = "Get mesh/texture from Game Object";
00030     private static string Step2 = "Store into Printing3d API";
00031     private static string Step3 = "Launch printing dialog";
00032     private static string labelText = "Status for printing";
00033
00034     private static bool enableButton = true;
00035
00036     private static UInt32[] indicesPrint;
00037     private static double[] verticesPrint;
00038     private static UInt32[] indicesMaterialPrint;
00039
00040     private static UInt32 groupId;
00041     private static double[] uvPrint;
00042
00043     private static byte[] pngBytes;
00044     private static byte a, r, g, b;
00045
00046     private static uint indicesCount;
00047     private static uint verticesCount;
00048     private static uint verticesMaterialCount;
00049
00050
00051     public GameObject ObjectToPrint;
00052
00053     // Use this for adding GUI
00054     void OnGUI()
00055     {
00056         GUI.Label(new UnityEngine.Rect(20, 100, 400, 60), labelText, new GUIStyle { fontSize = 36 });
00057
00058         if (GUI.Button(new UnityEngine.Rect(20, 20, 80, 80), "3D Print"))
00059         {
00060             StartPrinting();
00061         }
00062     }
00063
00064     private void StartPrinting()
00065     {
00066         // ignore button click until launch print dialog
00067         if (enableButton)
00068         {
00069             enableButton = false;
00070         }
00071         else
00072         {
00073             return;
00074         }
00075
00076         labelText = Step1;
00077
00078         Mesh mesh = null;
00079
00080         // assign one obj to ObjectToPrint or
00081         // put this Print3D.cs under model
00082         if (ObjectToPrint != null)
00083         {
00084             var meshFilter = ObjectToPrint.GetComponentInChildren<MeshFilter>();
00085
00086             var meshRenderer = ObjectToPrint.GetComponentInChildren<MeshRenderer>();
00087
00088             if (meshRenderer.sharedMaterial.GetTexture("_MainTex") != null)
00089             {
00090                 // get texture bytes from Unity
00091                 var texture = meshRenderer.sharedMaterial.GetTexture("_MainTex") as Texture2D;
00092                 pngBytes = texture.EncodeToPNG();
00093             }
00094             else
00095             {
00096                 // get color from Unity, convert to byte
00097                 Color color = meshRenderer.sharedMaterial.color;
00098                 a = (byte)(color.a * 255);
00099                 r = (byte)(color.r * 255);
00100                 g = (byte)(color.g * 255);
00101                 b = (byte)(color.b * 255);
00102             }
00103             // get mesh information from Unity
00104             mesh = meshFilter.sharedMesh;
00105         }
00106         else
00107         {
00108             // get texture bytes from Unity
00109             var texture = transform.GetComponent<SkinnedMeshRenderer>().material.GetTexture("_MainTex") as Texture2D;
00110             pngBytes = texture.EncodeToPNG();
00111             // get mesh information from Unity
00112             mesh = transform.GetComponent<SkinnedMeshRenderer>().sharedMesh;
00113         }
00114
00115         indicesCount = (uint)mesh.triangles.Length / 3;
00116         verticesCount = (uint)mesh.vertices.Length;
00117         verticesMaterialCount = (uint)mesh.triangles.Length / 3;
00118
00119         indicesPrint = new UInt32[mesh.triangles.Length];
00120         verticesPrint = new double[mesh.vertices.Length * 3];
00121         indicesMaterialPrint = new UInt32[mesh.triangles.Length / 3 * 4];
00122
00123         if (pngBytes != null)
00124         {
00125       // need UV mapping
00126             uvPrint = new double[mesh.uv.Length * 2];
00127         }
00128
00129         groupId = 1;
00130
00131         int j = 0;
00132
00133         labelText = "Getting indices";
00134         System.Diagnostics.Debug.WriteLine("Getting indices");
00135         // get indices and indices for material
00136         for (int i = 0; i < mesh.triangles.Length; i++)
00137         {
00138             indicesPrint[i] = (UInt32)mesh.triangles[i];
00139
00140             // vertex corresponding to uv
00141             if (i % 3 == 0)
00142             {
00143                 indicesMaterialPrint[j] = groupId;
00144                 j++;
00145             }
00146
00147             if (pngBytes != null)
00148             {
00149         // UV mapping indices
00150                 indicesMaterialPrint[j] = (UInt32)mesh.triangles[i];
00151             }
00152             else
00153             {
00154         // only color color material, index is 0
00155                 indicesMaterialPrint[j] = 0;
00156             }
00157             j++;
00158         }
00159
00160         labelText = "Getting vertices";
00161         System.Diagnostics.Debug.WriteLine("Getting vertices");
00162
00163         // get vertices
00164         for (int i = 0; i < mesh.vertices.Length; i++)
00165         {
00166             verticesPrint[i * 3] = (double)mesh.vertices[i].x;
00167             verticesPrint[i * 3 + 1] = (double)mesh.vertices[i].y;
00168             verticesPrint[i * 3 + 2] = (double)mesh.vertices[i].z;
00169         }
00170
00171         if (pngBytes != null)
00172         {
00173             labelText = "Getting texture coordinates";
00174             System.Diagnostics.Debug.WriteLine("Getting texture coordinates");
00175             // get UVs
00176             for (int i = 0; i < mesh.uv.Length; i++)
00177             {
00178                 uvPrint[i * 2] = (double)mesh.uv[i].x;
00179                 uvPrint[i * 2 + 1] = (double)mesh.uv[i].y;
00180             }
00181         }
00182
00183         labelText = "Launching 3D Print UI";
00184
00185         System.Diagnostics.Debug.WriteLine("Launching 3D Print UI.");
00186
00187 #if UNITY_WSA && !UNITY_EDITOR
00188         // start to pass the mesh/texture into Printing3D API
00189         // launch the print dialog
00190         UIThread();
00191 #else
00192         enableButton = true;
00193 #endif
00194     }
00195
00196     // Use this for initialization
00197     void Start()
00198     {
00199
00200     }
00201
00202     // Update is called once per frame
00203     void Update()
00204     {
00205
00206     }
00207
00208 #if UNITY_WSA && !UNITY_EDITOR
00209     private static async void UIThread()
00210     {
00211         // convert to UI thread and then launch the printing dialog
00212         // print dialog only works in UI thread
00213         await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
00214             var print = new Print3D();
00215             print.LaunchPrintDialog();
00216         });
00217     }
00218
00219     private Print3DTask printTask;
00220     private Printing3D3MFPackage package;
00221
00222     private async void LaunchPrintDialog()
00223     {
00224         labelText = Step2;
00225         // use CreateData to create 3MFPackage from a string stream
00226         await CreateData();
00227
00228         labelText = Step3;
00229         // register the PrintTaskRequest callback to get the Printing3D3MFPackage
00230         Print3DManager.GetForCurrentView().TaskRequested += MainPage_TaskRequested;
00231
00232         // show the PrintUI
00233         await Print3DManager.ShowPrintUIAsync();
00234
00235         // remove the print task request after dialog is shown
00236         Print3DManager.GetForCurrentView().TaskRequested -= MainPage_TaskRequested;
00237
00238         // set back
00239         enableButton = true;
00240     }
00241
00242     private void MainPage_TaskRequested(Print3DManager sender, Print3DTaskRequestedEventArgs args)
00243     {
00244         Print3DTask printTaskRef = null;
00245
00246         Print3DTaskSourceRequestedHandler sourceHandler = delegate (Print3DTaskSourceRequestedArgs sourceRequestedArgs)
00247         {
00248             sourceRequestedArgs.SetSource(package);
00249         };
00250         printTaskRef = args.Request.CreateTask("Model", "Default", sourceHandler);
00251
00252         this.printTask = printTaskRef;
00253
00254         printTaskRef.Completed += Task_Completed;
00255         printTaskRef.Submitting += Task_Submitting;
00256     }
00257
00258     private async Task CreateData()
00259     {
00260         package = new Printing3D3MFPackage();
00261
00262         var model = new Printing3DModel();
00263
00264         model.Unit = Printing3DModelUnit.Millimeter;
00265
00266         var mesh = new Printing3DMesh();
00267
00268         // save vertices
00269         await GetVerticesAsync(mesh);
00270
00271         // save indices
00272         await GetIndicesAsync(mesh);
00273
00274         // save material indices
00275         await GetMaterialIndicesAsync(mesh);
00276
00277         // to make sure we don't use the same byte array from Unity
00278         if (pngBytes != null)
00279         {
00280             // texture2Coord Group
00281             var tex2CoordGroup = new Printing3DTexture2CoordMaterialGroup(groupId);
00282
00283             // save texture coords
00284             for (int i = 0; i < uvPrint.Length / 2; i++)
00285             {
00286                 var tex2CoordMaterial = new Printing3DTexture2CoordMaterial();
00287                 tex2CoordMaterial.U = uvPrint[i * 2];
00288                 tex2CoordMaterial.V = uvPrint[i * 2 + 1];
00289                 tex2CoordGroup.Texture2Coords.Add(tex2CoordMaterial);
00290             }
00291
00292             var copyPngBytes = new byte[pngBytes.Length];
00293             pngBytes.CopyTo(copyPngBytes, 0);
00294
00295             var randomAccessStream = new InMemoryRandomAccessStream();
00296             await randomAccessStream.WriteAsync(copyPngBytes.AsBuffer());
00297             randomAccessStream.Seek(0);
00298
00299             var texture = new Printing3DModelTexture();
00300             Printing3DTextureResource texResource = new Printing3DTextureResource();
00301             texResource.Name = "/3D/Texture/skeleton.png";
00302             texResource.TextureData = new MyRandomAccessStream(randomAccessStream);
00303             package.Textures.Add(texResource);
00304
00305             // add metadata about the texture
00306             model.Metadata.Add("tex" + groupId, "/3D/Texture/skeleton.png");
00307             model.Material.Texture2CoordGroups.Add(tex2CoordGroup);
00308         }
00309         else
00310         {
00311       // put color material into material group
00312             var newColor = Windows.UI.Color.FromArgb(a, r, g, b);
00313             var colrMat = new Printing3DColorMaterial();
00314             colrMat.Color = newColor;
00315
00316             var colorGroup = new Printing3DColorMaterialGroup(groupId);
00317             colorGroup.Colors.Add(colrMat);
00318             model.Material.ColorGroups.Add(colorGroup);
00319         }
00320
00321         model.Meshes.Add(mesh);
00322
00323         Printing3DComponent component = new Printing3DComponent();
00324
00325         component.Mesh = mesh;
00326
00327         model.Components.Add(component);
00328
00329         var componentWithMatrix = new Printing3DComponentWithMatrix();
00330
00331         componentWithMatrix.Component = component;
00332
00333         componentWithMatrix.Matrix = System.Numerics.Matrix4x4.Identity;
00334
00335         model.Build.Components.Add(componentWithMatrix);
00336
00337         await package.SaveModelToPackageAsync(model);
00338
00339         var modelStream = package.ModelPart;
00340         package.ModelPart = await FixTextureContentType(modelStream);
00341
00342         // save to file and easy to debug
00343         // var stream = await package.SaveAsync();
00344         // await SaveStreamTo3MF(stream);
00345     }
00346
00347     private async Task<IRandomAccessStream> FixTextureContentType(IRandomAccessStream modelStream)
00348     {
00349         XDocument xmldoc = XDocument.Load(modelStream.AsStreamForRead());
00350
00351         var outputStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
00352         var writer = new Windows.Storage.Streams.DataWriter(outputStream);
00353         writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
00354         writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;
00355
00356         var text = xmldoc.ToString();
00357
00358         var replacedText = text.Replace("contenttype=\"\"", "contenttype=\"image/png\"");
00359         writer.WriteString(replacedText);
00360
00361         await writer.StoreAsync();
00362         await writer.FlushAsync();
00363         writer.DetachStream();
00364         return outputStream;
00365     }
00366
00367     private async static Task<bool> SaveStreamTo3MF(Windows.Storage.Streams.IRandomAccessStream stream)
00368     {
00369         // set back
00370         stream.Seek(0);
00371         using (var dataReader = new Windows.Storage.Streams.DataReader(stream))
00372         {
00373
00374             var dataLoad = await dataReader.LoadAsync((uint)stream.Size);
00375             if (dataLoad > 0)
00376             {
00377                 var buffer = dataReader.ReadBuffer((uint)stream.Size);
00378
00379                 StorageFolder localFolder = ApplicationData.Current.LocalFolder;
00380                 var outputfile = await localFolder.CreateFileAsync("output.3mf", CreationCollisionOption.ReplaceExisting);
00381                 await Windows.Storage.FileIO.WriteBufferAsync(outputfile, buffer);
00382                 var options = new Windows.System.LauncherOptions();
00383                 options.TargetApplicationPackageFamilyName = "Microsoft.3DBuilder_8wekyb3d8bbwe";
00384             }
00385         }
00386
00387         return true;
00388     }
00389
00390     private void Task_Submitting(Print3DTask sender, object args)
00391     {
00392         // notify user if required
00393     }
00394
00395     private void Task_Completed(Print3DTask sender, Print3DTaskCompletedEventArgs args)
00396     {
00397         // notify user if required
00398     }
00399
00400     private async Task GetVerticesAsync(Printing3DMesh mesh)
00401     {
00402         Printing3DBufferDescription description;
00403
00404         description.Format = Printing3DBufferFormat.Printing3DDouble;
00405         description.Stride = 3;
00406         mesh.VertexCount = verticesCount;
00407         mesh.CreateVertexPositions(sizeof(double) * 3 * mesh.VertexCount);
00408         mesh.VertexPositionsDescription = description;
00409
00410         using (var stream = mesh.GetVertexPositions().AsStream())
00411         {
00412             var data = verticesPrint.SelectMany(v => BitConverter.GetBytes(v)).ToArray();
00413             await stream.WriteAsync(data, 0, data.Length);
00414         }
00415     }
00416
00417     private static async Task GetIndicesAsync(Printing3DMesh mesh)
00418     {
00419         Printing3DBufferDescription description;
00420
00421         description.Format = Printing3DBufferFormat.Printing3DUInt;
00422         description.Stride = 3;
00423         mesh.IndexCount = indicesCount;
00424         mesh.TriangleIndicesDescription = description;
00425
00426         mesh.CreateTriangleIndices(sizeof(UInt32) * 3 * mesh.IndexCount);
00427
00428         var stream = mesh.GetTriangleIndices().AsStream();
00429         {
00430             var data = indicesPrint.SelectMany(v => BitConverter.GetBytes(v)).ToArray();
00431             await stream.WriteAsync(data, 0, data.Length);
00432         }
00433
00434     }
00435
00436     private static async Task GetMaterialIndicesAsync(Printing3DMesh mesh)
00437     {
00438         Printing3DBufferDescription description;
00439
00440         description.Format = Printing3DBufferFormat.Printing3DUInt;
00441         description.Stride = 4;
00442         mesh.IndexCount = verticesMaterialCount;
00443         mesh.TriangleMaterialIndicesDescription = description;
00444
00445         mesh.CreateTriangleMaterialIndices(sizeof(UInt32) * 4 * mesh.IndexCount);
00446
00447         var stream = mesh.GetTriangleMaterialIndices().AsStream();
00448         {
00449             var data = indicesMaterialPrint.SelectMany(v => BitConverter.GetBytes(v)).ToArray();
00450             await stream.WriteAsync(data, 0, data.Length);
00451         }
00452     }
00453
00454     // create one IRandomAccessStreamWithContentType class
00455     // in WinRT API, there is no instance for IRandomAccessStreamWithContentType
00456     // for the user, you just need to copy this class, change the value for "ContentType"
00457     public class MyRandomAccessStream : IRandomAccessStreamWithContentType
00458     {
00459         private IRandomAccessStream _stream;
00460
00461         public bool CanRead
00462         {
00463             get
00464             {
00465                 return _stream.CanRead;
00466             }
00467         }
00468
00469         public bool CanWrite
00470         {
00471             get
00472             {
00473                 return _stream.CanWrite;
00474             }
00475         }
00476
00477         public ulong Position
00478         {
00479             get
00480             {
00481                 return _stream.Position;
00482             }
00483         }
00484
00485         public ulong Size
00486         {
00487             get
00488             {
00489                 return _stream.Size;
00490             }
00491
00492             set
00493             {
00494                 _stream.Size = value;
00495             }
00496         }
00497
00498         public string ContentType
00499         {
00500             get
00501             {
00502                 // depending on the real data type
00503                 return "image/png";
00504             }
00505         }
00506
00507         public MyRandomAccessStream(IRandomAccessStream stream)
00508         {
00509             _stream = stream;
00510         }
00511
00512         public IRandomAccessStream CloneStream()
00513         {
00514             return _stream.CloneStream();
00515         }
00516
00517         public void Dispose()
00518         {
00519             _stream.Dispose();
00520         }
00521
00522         public IAsyncOperation<bool> FlushAsync()
00523         {
00524             return _stream.FlushAsync();
00525         }
00526
00527         public IInputStream GetInputStreamAt(ulong position)
00528         {
00529             return _stream.GetInputStreamAt(position);
00530         }
00531
00532         public IOutputStream GetOutputStreamAt(ulong position)
00533         {
00534             return _stream.GetOutputStreamAt(position);
00535         }
00536
00537         public IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
00538         {
00539             return _stream.ReadAsync(buffer, count, options);
00540         }
00541
00542         public void Seek(ulong position)
00543         {
00544             _stream.Seek(position);
00545         }
00546
00547         public IAsyncOperationWithProgress<UInt32, UInt32> WriteAsync(IBuffer buffer)
00548         {
00549             return _stream.WriteAsync(buffer);
00550         }
00551     }
00552 #endif
00553 }
00554
00555
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SerialArduino/cs/EventHandlerForDevice.cs Source File

  • SerialArduino
  • cs

EventHandlerForDevice.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017
00018 using Windows.Devices.Enumeration;
00019 using Windows.Devices.SerialCommunication;
00020
00021 using Windows.ApplicationModel;
00022 using Windows.Foundation;
00023
00024 using Windows.UI.Core;
00025 using Windows.UI.Xaml;
00026
00027 using SDKTemplate;
00028
00029 namespace SerialArduino
00030 {
00031     /// <summary>
00032     /// The purpose of this class is to demonstrate the expected application behavior for app events
00033     /// such as suspension and resume or when the device is disconnected. In addition to handling
00034     /// the SerialDevice, the app's state should also be saved upon app suspension (will not be demonstrated here).
00035     ///
00036     /// This class will also demonstrate how to handle device watcher events.
00037     ///
00038     /// For simplicity, this class will only allow at most one device to be connected at any given time. In order
00039     /// to make this class support multiple devices, make this class a non-singleton and create multiple instances
00040     /// of this class; each instance should watch one connected device.
00041     /// </summary>
00042     public class EventHandlerForDevice
00043     {
00044         /// <summary>
00045         /// Allows for singleton EventHandlerForDevice
00046         /// </summary>
00047         private static EventHandlerForDevice eventHandlerForDevice;
00048
00049         /// <summary>
00050         /// Used to synchronize threads to avoid multiple instantiations of eventHandlerForDevice.
00051         /// </summary>
00052         private static Object singletonCreationLock = new Object();
00053
00054         private String deviceSelector;
00055         private DeviceWatcher deviceWatcher;
00056
00057         private DeviceInformation deviceInformation;
00058         private DeviceAccessInformation deviceAccessInformation;
00059         private SerialDevice device;
00060
00061         private SuspendingEventHandler appSuspendEventHandler;
00062         private EventHandler<Object> appResumeEventHandler;
00063
00064         private TypedEventHandler<EventHandlerForDevice, DeviceInformation> deviceCloseCallback;
00065         private TypedEventHandler<EventHandlerForDevice, DeviceInformation> deviceConnectedCallback;
00066
00067         private TypedEventHandler<DeviceWatcher, DeviceInformation> deviceAddedEventHandler;
00068         private TypedEventHandler<DeviceWatcher, DeviceInformationUpdate> deviceRemovedEventHandler;
00069         private TypedEventHandler<DeviceAccessInformation, DeviceAccessChangedEventArgs> deviceAccessEventHandler;
00070
00071         private Boolean watcherSuspended;
00072         private Boolean watcherStarted;
00073         private Boolean isEnabledAutoReconnect;
00074
00075         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00076         // as NotifyUser()
00077         private MainPage rootPage = MainPage.Current;
00078
00079         /// <summary>
00080         /// Enforces the singleton pattern so that there is only one object handling app events
00081         /// as it relates to the SerialDevice because this sample app only supports communicating with one device at a time.
00082         ///
00083         /// An instance of EventHandlerForDevice is globally available because the device needs to persist across scenario pages.
00084         ///
00085         /// If there is no instance of EventHandlerForDevice created before this property is called,
00086         /// an EventHandlerForDevice will be created.
00087         /// </summary>
00088         public static EventHandlerForDevice Current
00089         {
00090             get
00091             {
00092                 if (eventHandlerForDevice == null)
00093                 {
00094                     lock (singletonCreationLock)
00095                     {
00096                         if (eventHandlerForDevice == null)
00097                         {
00098                             CreateNewEventHandlerForDevice();
00099                         }
00100                     }
00101                 }
00102
00103                 return eventHandlerForDevice;
00104             }
00105         }
00106
00107         /// <summary>
00108         /// Creates a new instance of EventHandlerForDevice, enables auto reconnect, and uses it as the Current instance.
00109         /// </summary>
00110         public static void CreateNewEventHandlerForDevice()
00111         {
00112             eventHandlerForDevice = new EventHandlerForDevice();
00113         }
00114
00115         public TypedEventHandler<EventHandlerForDevice, DeviceInformation> OnDeviceClose
00116         {
00117             get
00118             {
00119                 return deviceCloseCallback;
00120             }
00121
00122             set
00123             {
00124                 deviceCloseCallback = value;
00125             }
00126         }
00127
00128         public TypedEventHandler<EventHandlerForDevice, DeviceInformation> OnDeviceConnected
00129         {
00130             get
00131             {
00132                 return deviceConnectedCallback;
00133             }
00134
00135             set
00136             {
00137                 deviceConnectedCallback = value;
00138             }
00139         }
00140
00141         public Boolean IsDeviceConnected
00142         {
00143             get
00144             {
00145                 return (device != null);
00146             }
00147         }
00148
00149         public SerialDevice Device
00150         {
00151             get
00152             {
00153                 return device;
00154             }
00155         }
00156
00157         /// <summary>
00158         /// This DeviceInformation represents which device is connected or which device will be reconnected when
00159         /// the device is plugged in again (if IsEnabledAutoReconnect is true);.
00160         /// </summary>
00161         public DeviceInformation DeviceInformation
00162         {
00163             get
00164             {
00165                 return deviceInformation;
00166             }
00167         }
00168
00169         /// <summary>
00170         /// Returns DeviceAccessInformation for the device that is currently connected using this EventHandlerForDevice
00171         /// object.
00172         /// </summary>
00173         public DeviceAccessInformation DeviceAccessInformation
00174         {
00175             get
00176             {
00177                 return deviceAccessInformation;
00178             }
00179         }
00180
00181         /// <summary>
00182         /// DeviceSelector AQS used to find this device
00183         /// </summary>
00184         public String DeviceSelector
00185         {
00186             get
00187             {
00188                 return deviceSelector;
00189             }
00190         }
00191
00192         /// <summary>
00193         /// True if EventHandlerForDevice will attempt to reconnect to the device once it is plugged into the computer again
00194         /// </summary>
00195         public Boolean IsEnabledAutoReconnect
00196         {
00197             get
00198             {
00199                 return isEnabledAutoReconnect;
00200             }
00201             set
00202             {
00203                 isEnabledAutoReconnect = value;
00204             }
00205         }
00206
00207         /// <summary>
00208         /// This method opens the device using the WinRT Serial API. After the device is opened, save the device
00209         /// so that it can be used across scenarios.
00210         ///
00211         /// It is important that the FromIdAsync call is made on the UI thread because the consent prompt can only be displayed
00212         /// on the UI thread.
00213         ///
00214         /// This method is used to reopen the device after the device reconnects to the computer and when the app resumes.
00215         /// </summary>
00216         /// <param name="deviceInfo">Device information of the device to be opened</param>
00217         /// <param name="deviceSelector">The AQS used to find this device</param>
00218         /// <returns>True if the device was successfully opened, false if the device could not be opened for well known reasons.
00219         /// An exception may be thrown if the device could not be opened for extraordinary reasons.</returns>
00220         public async Task<Boolean> OpenDeviceAsync(DeviceInformation deviceInfo, String deviceSelector)
00221         {
00222             device = await SerialDevice.FromIdAsync(deviceInfo.Id);
00223
00224             Boolean successfullyOpenedDevice = false;
00225             NotifyType notificationStatus;
00226             String notificationMessage = null;
00227
00228             // Device could have been blocked by user or the device has already been opened by another app.
00229             if (device != null)
00230             {
00231                 successfullyOpenedDevice = true;
00232
00233                 deviceInformation = deviceInfo;
00234                 this.deviceSelector = deviceSelector;
00235
00236                 notificationStatus = NotifyType.StatusMessage;
00237                 notificationMessage = "Device " + deviceInformation.Id + " opened";
00238
00239                 // Notify registered callback handle that the device has been opened
00240                 if (deviceConnectedCallback != null)
00241                 {
00242                     deviceConnectedCallback(this, deviceInformation);
00243                 }
00244
00245                 if (appSuspendEventHandler == null || appResumeEventHandler == null)
00246                 {
00247                     RegisterForAppEvents();
00248                 }
00249
00250                 // Register for DeviceAccessInformation.AccessChanged event and react to any changes to the
00251                 // user access after the device handle was opened.
00252                 if (deviceAccessEventHandler == null)
00253                 {
00254                     RegisterForDeviceAccessStatusChange();
00255                 }
00256
00257                 // Create and register device watcher events for the device to be opened unless we're reopening the device
00258                 if (deviceWatcher == null)
00259                 {
00260                     deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector);
00261
00262                     RegisterForDeviceWatcherEvents();
00263                 }
00264
00265                 if (!watcherStarted)
00266                 {
00267                     // Start the device watcher after we made sure that the device is opened.
00268                     StartDeviceWatcher();
00269                 }
00270             }
00271             else
00272             {
00273                 successfullyOpenedDevice = false;
00274
00275                 notificationStatus = NotifyType.ErrorMessage;
00276
00277                 var deviceAccessStatus = DeviceAccessInformation.CreateFromId(deviceInfo.Id).CurrentStatus;
00278
00279                 if (deviceAccessStatus == DeviceAccessStatus.DeniedByUser)
00280                 {
00281                     notificationMessage = "Access to the device was blocked by the user : " + deviceInfo.Id;
00282                 }
00283                 else if (deviceAccessStatus == DeviceAccessStatus.DeniedBySystem)
00284                 {
00285                     // This status is most likely caused by app permissions (did not declare the device in the app's package.appxmanifest)
00286                     // This status does not cover the case where the device is already opened by another app.
00287                     notificationMessage = "Access to the device was blocked by the system : " + deviceInfo.Id;
00288                 }
00289                 else
00290                 {
00291                     // Most likely the device is opened by another app, but cannot be sure
00292                     notificationMessage = "Unknown error, possibly opened by another app : " + deviceInfo.Id;
00293                 }
00294             }
00295
00296             MainPage.Current.NotifyUser(notificationMessage, notificationStatus);
00297
00298             return successfullyOpenedDevice;
00299         }
00300
00301         /// <summary>
00302         /// Closes the device, stops the device watcher, stops listening for app events, and resets object state to before a device
00303         /// was ever connected.
00304         /// </summary>
00305         public void CloseDevice()
00306         {
00307             if (IsDeviceConnected)
00308             {
00309                 CloseCurrentlyConnectedDevice();
00310             }
00311
00312             if (deviceWatcher != null)
00313             {
00314                 if (watcherStarted)
00315                 {
00316                     StopDeviceWatcher();
00317
00318                     UnregisterFromDeviceWatcherEvents();
00319                 }
00320
00321                 deviceWatcher = null;
00322             }
00323
00324             if (deviceAccessInformation != null)
00325             {
00326                 UnregisterFromDeviceAccessStatusChange();
00327
00328                 deviceAccessInformation = null;
00329             }
00330
00331             if (appSuspendEventHandler != null || appResumeEventHandler != null)
00332             {
00333                 UnregisterFromAppEvents();
00334             }
00335
00336             deviceInformation = null;
00337             deviceSelector = null;
00338
00339             deviceConnectedCallback = null;
00340             deviceCloseCallback = null;
00341
00342             isEnabledAutoReconnect = true;
00343         }
00344
00345
00346         /// <summary>
00347         /// Configures connection parameters for the device that is currently connected
00348         /// </summary>
00349         public void ConfigureCurrentlyConnectedDevice()
00350         {
00351             if (IsDeviceConnected)
00352             {
00353                 if (device != null)
00354                 {
00355                     device.BaudRate = 9600;
00356                     device.Parity = SerialParity.None;
00357                     device.StopBits = SerialStopBitCount.One;
00358                     device.Handshake = SerialHandshake.None;
00359                     device.DataBits = 8;
00360                 }
00361             }
00362
00363         }
00364
00365         private EventHandlerForDevice()
00366         {
00367             watcherStarted = false;
00368             watcherSuspended = false;
00369             isEnabledAutoReconnect = true;
00370         }
00371
00372         /// <summary>
00373         /// This method demonstrates how to close the device properly using the WinRT Serial API.
00374         ///
00375         /// When the SerialDevice is closing, it will cancel all IO operations that are still pending (not complete).
00376         /// The close will not wait for any IO completion callbacks to be called, so the close call may complete before any of
00377         /// the IO completion callbacks are called.
00378         /// The pending IO operations will still call their respective completion callbacks with either a task
00379         /// cancelled error or the operation completed.
00380         /// </summary>
00381         private async void CloseCurrentlyConnectedDevice()
00382         {
00383             if (device != null)
00384             {
00385                 // Notify callback that we're about to close the device
00386                 if (deviceCloseCallback != null)
00387                 {
00388                     deviceCloseCallback(this, deviceInformation);
00389                 }
00390
00391                 // This closes the handle to the device
00392                 device.Dispose();
00393
00394                 device = null;
00395
00396                 // Save the deviceInformation.Id in case deviceInformation is set to null when closing the
00397                 // device
00398                 String deviceId = deviceInformation.Id;
00399
00400                 await rootPage.Dispatcher.RunAsync(
00401                     CoreDispatcherPriority.Normal,
00402                     new DispatchedHandler(() =>
00403                     {
00404                         MainPage.Current.NotifyUser(deviceId + " is closed", NotifyType.StatusMessage);
00405                     }));
00406             }
00407         }
00408
00409         /// <summary>
00410         /// Register for app suspension/resume events. See the comments
00411         /// for the event handlers for more information on the exact device operation performed.
00412         ///
00413         /// We will also register for when the app exists so that we may close the device handle.
00414         /// </summary>
00415         private void RegisterForAppEvents()
00416         {
00417             appSuspendEventHandler = new SuspendingEventHandler(EventHandlerForDevice.Current.OnAppSuspension);
00418             appResumeEventHandler = new EventHandler<Object>(EventHandlerForDevice.Current.OnAppResume);
00419
00420             // This event is raised when the app is exited and when the app is suspended
00421             App.Current.Suspending += appSuspendEventHandler;
00422
00423             App.Current.Resuming += appResumeEventHandler;
00424         }
00425
00426         private void UnregisterFromAppEvents()
00427         {
00428             // This event is raised when the app is exited and when the app is suspended
00429             App.Current.Suspending -= appSuspendEventHandler;
00430             appSuspendEventHandler = null;
00431
00432             App.Current.Resuming -= appResumeEventHandler;
00433             appResumeEventHandler = null;
00434         }
00435
00436         /// <summary>
00437         /// Register for Added and Removed events.
00438         /// Note that, when disconnecting the device, the device may be closed by the system before the OnDeviceRemoved callback is invoked.
00439         /// </summary>
00440         private void RegisterForDeviceWatcherEvents()
00441         {
00442             deviceAddedEventHandler = new TypedEventHandler<DeviceWatcher, DeviceInformation>(this.OnDeviceAdded);
00443
00444             deviceRemovedEventHandler = new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(this.OnDeviceRemoved);
00445
00446             deviceWatcher.Added += deviceAddedEventHandler;
00447
00448             deviceWatcher.Removed += deviceRemovedEventHandler;
00449         }
00450
00451         private void UnregisterFromDeviceWatcherEvents()
00452         {
00453             deviceWatcher.Added -= deviceAddedEventHandler;
00454             deviceAddedEventHandler = null;
00455
00456             deviceWatcher.Removed -= deviceRemovedEventHandler;
00457             deviceRemovedEventHandler = null;
00458         }
00459
00460         /// <summary>
00461         /// Listen for any changed in device access permission. The user can block access to the device while the device is in use.
00462         /// If the user blocks access to the device while the device is opened, the device's handle will be closed automatically by
00463         /// the system; it is still a good idea to close the device explicitly so that resources are cleaned up.
00464         ///
00465         /// Note that by the time the AccessChanged event is raised, the device handle may already be closed by the system.
00466         /// </summary>
00467         private void RegisterForDeviceAccessStatusChange()
00468         {
00469             // Enable the following registration ONLY if the Serial device under test is non-internal.
00470             //
00471
00472             //deviceAccessInformation = DeviceAccessInformation.CreateFromId(deviceInformation.Id);
00473             //deviceAccessEventHandler = new TypedEventHandler<DeviceAccessInformation, DeviceAccessChangedEventArgs>(this.OnDeviceAccessChanged);
00474             //deviceAccessInformation.AccessChanged += deviceAccessEventHandler;
00475         }
00476
00477         private void UnregisterFromDeviceAccessStatusChange()
00478         {
00479             deviceAccessInformation.AccessChanged -= deviceAccessEventHandler;
00480
00481             deviceAccessEventHandler = null;
00482         }
00483
00484         private void StartDeviceWatcher()
00485         {
00486             watcherStarted = true;
00487
00488             if ((deviceWatcher.Status != DeviceWatcherStatus.Started)
00489                 && (deviceWatcher.Status != DeviceWatcherStatus.EnumerationCompleted))
00490             {
00491                 deviceWatcher.Start();
00492             }
00493         }
00494
00495         private void StopDeviceWatcher()
00496         {
00497             if ((deviceWatcher.Status == DeviceWatcherStatus.Started)
00498                 || (deviceWatcher.Status == DeviceWatcherStatus.EnumerationCompleted))
00499             {
00500                 deviceWatcher.Stop();
00501             }
00502
00503             watcherStarted = false;
00504         }
00505
00506         /// <summary>
00507         /// If a Serial object has been instantiated (a handle to the device is opened), we must close it before the app
00508         /// goes into suspension because the API automatically closes it for us if we don't. When resuming, the API will
00509         /// not reopen the device automatically, so we need to explicitly open the device in the app (Scenario1_ConnectDisconnect).
00510         ///
00511         /// Since we have to reopen the device ourselves when the app resumes, it is good practice to explicitly call the close
00512         /// in the app as well (For every open there is a close).
00513         ///
00514         /// We must stop the DeviceWatcher because it will continue to raise events even if
00515         /// the app is in suspension, which is not desired (drains battery). We resume the device watcher once the app resumes again.
00516         /// </summary>
00517         /// <param name="sender"></param>
00518         /// <param name="eventArgs"></param>
00519         private void OnAppSuspension(Object sender, SuspendingEventArgs args)
00520         {
00521             if (watcherStarted)
00522             {
00523                 watcherSuspended = true;
00524                 StopDeviceWatcher();
00525             }
00526             else
00527             {
00528                 watcherSuspended = false;
00529             }
00530
00531             CloseCurrentlyConnectedDevice();
00532         }
00533
00534         /// <summary>
00535         /// When resume into the application, we should reopen a handle to the Serial device again. This will automatically
00536         /// happen when we start the device watcher again; the device will be re-enumerated and we will attempt to reopen it
00537         /// if IsEnabledAutoReconnect property is enabled.
00538         ///
00539         /// See OnAppSuspension for why we are starting the device watcher again
00540         /// </summary>
00541         /// <param name="sender"></param>
00542         /// <param name="arg"></param>
00543         private void OnAppResume(Object sender, Object args)
00544         {
00545             if (watcherSuspended)
00546             {
00547                 watcherSuspended = false;
00548                 StartDeviceWatcher();
00549             }
00550         }
00551
00552         /// <summary>
00553         /// Close the device that is opened so that all pending operations are canceled properly.
00554         /// </summary>
00555         /// <param name="sender"></param>
00556         /// <param name="deviceInformationUpdate"></param>
00557         private void OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceInformationUpdate)
00558         {
00559             if (IsDeviceConnected && (deviceInformationUpdate.Id == deviceInformation.Id))
00560             {
00561                 // The main reasons to close the device explicitly is to clean up resources, to properly handle errors,
00562                 // and stop talking to the disconnected device.
00563                 CloseCurrentlyConnectedDevice();
00564             }
00565         }
00566
00567         /// <summary>
00568         /// Open the device that the user wanted to open if it hasn't been opened yet and auto reconnect is enabled.
00569         /// </summary>
00570         /// <param name="sender"></param>
00571         /// <param name="deviceInfo"></param>
00572         private async void OnDeviceAdded(DeviceWatcher sender, DeviceInformation deviceInfo)
00573         {
00574             if ((deviceInformation != null) && (deviceInfo.Id == deviceInformation.Id) && !IsDeviceConnected && isEnabledAutoReconnect)
00575             {
00576                 await rootPage.Dispatcher.RunAsync(
00577                     CoreDispatcherPriority.Normal,
00578                     new DispatchedHandler(async () =>
00579                     {
00580                         await OpenDeviceAsync(deviceInformation, deviceSelector);
00581
00582                         // Any app specific device intialization should be done here because we don't know the state of the device when it is re-enumerated.
00583                     }));
00584             }
00585         }
00586
00587         /// <summary>
00588         /// Close the device if the device access was denied by anyone (system or the user) and reopen it if permissions are allowed again
00589         /// </summary>
00590         /// <param name="sender"></param>
00591         /// <param name="eventArgs"></param>
00592         private async void OnDeviceAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs eventArgs)
00593         {
00594             if ((eventArgs.Status == DeviceAccessStatus.DeniedBySystem)
00595                 || (eventArgs.Status == DeviceAccessStatus.DeniedByUser))
00596             {
00597                 CloseCurrentlyConnectedDevice();
00598             }
00599             else if ((eventArgs.Status == DeviceAccessStatus.Allowed) && (deviceInformation != null) && isEnabledAutoReconnect)
00600             {
00601                 await rootPage.Dispatcher.RunAsync(
00602                     CoreDispatcherPriority.Normal,
00603                     new DispatchedHandler(async () =>
00604                     {
00605                         await OpenDeviceAsync(deviceInformation, deviceSelector);
00606
00607                         // Any app specific device intialization should be done here because we don't know the state of the device when it is re-enumerated.
00608                     }));
00609             }
00610         }
00611     }
00612 }
Generated on Fri Nov 15 2024 22:19:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LowLatencyInput/cpp/Common/DeviceResources.h Source File

  • LowLatencyInput
  • cpp
  • Common

DeviceResources.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace DX
00015 {
00016     // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created.
00017     interface IDeviceNotify
00018     {
00019         virtual void OnDeviceLost() = 0;
00020         virtual void OnDeviceRestored() = 0;
00021     };
00022
00023     // Controls all the DirectX device resources.
00024     class DeviceResources
00025     {
00026     public:
00027         DeviceResources();
00028         void SetSwapChainPanel(Windows::UI::Xaml::Controls::SwapChainPanel^ panel);
00029         void SetLogicalSize(Windows::Foundation::Size logicalSize);
00030         void SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation);
00031         void SetDpi(float dpi);
00032         void SetCompositionScale(float compositionScaleX, float compositionScaleY);
00033         void ValidateDevice();
00034         void HandleDeviceLost();
00035         void RegisterDeviceNotify(IDeviceNotify* deviceNotify);
00036         void Trim();
00037         void Present();
00038
00039         //Used to achieve lowest output latency
00040         void WaitOnSwapChain();
00041
00042         // Device Accessors.
00043         Windows::Foundation::Size GetOutputSize() const                 { return m_outputSize; }
00044         Windows::Foundation::Size GetLogicalSize() const                { return m_logicalSize; }
00045
00046         // D3D Accessors.
00047         ID3D11Device2*          GetD3DDevice() const                    { return m_d3dDevice.Get(); }
00048         ID3D11DeviceContext2*   GetD3DDeviceContext() const             { return m_d3dContext.Get(); }
00049         IDXGISwapChain1*        GetSwapChain() const                    { return m_swapChain.Get(); }
00050         D3D_FEATURE_LEVEL       GetDeviceFeatureLevel() const           { return m_d3dFeatureLevel; }
00051         ID3D11RenderTargetView* GetBackBufferRenderTargetView() const   { return m_d3dRenderTargetView.Get(); }
00052         ID3D11DepthStencilView* GetDepthStencilView() const             { return m_d3dDepthStencilView.Get(); }
00053         D3D11_VIEWPORT          GetScreenViewport() const               { return m_screenViewport; }
00054         DirectX::XMFLOAT4X4     GetOrientationTransform3D() const       { return m_orientationTransform3D; }
00055
00056         // D2D Accessors.
00057         ID2D1Factory2*          GetD2DFactory() const                   { return m_d2dFactory.Get(); }
00058         ID2D1Device1*           GetD2DDevice() const                    { return m_d2dDevice.Get(); }
00059         ID2D1DeviceContext1*    GetD2DDeviceContext() const             { return m_d2dContext.Get(); }
00060         ID2D1Bitmap1*           GetD2DTargetBitmap() const              { return m_d2dTargetBitmap.Get(); }
00061         IDWriteFactory2*        GetDWriteFactory() const                { return m_dwriteFactory.Get();  }
00062         IWICImagingFactory2*    GetWicImagingFactory() const            { return m_wicFactory.Get(); }
00063         D2D1::Matrix3x2F        GetOrientationTransform2D() const       { return m_orientationTransform2D; }
00064
00065     private:
00066         void CreateDeviceIndependentResources();
00067         void CreateDeviceResources();
00068         void CreateWindowSizeDependentResources();
00069         DXGI_MODE_ROTATION ComputeDisplayRotation();
00070
00071         // Direct3D objects.
00072         Microsoft::WRL::ComPtr<ID3D11Device2>           m_d3dDevice;
00073         Microsoft::WRL::ComPtr<ID3D11DeviceContext2>    m_d3dContext;
00074         Microsoft::WRL::ComPtr<IDXGISwapChain1>         m_swapChain;
00075
00076         // Direct3D rendering objects. Required for 3D.
00077         Microsoft::WRL::ComPtr<ID3D11RenderTargetView>  m_d3dRenderTargetView;
00078         Microsoft::WRL::ComPtr<ID3D11DepthStencilView>  m_d3dDepthStencilView;
00079         D3D11_VIEWPORT                                  m_screenViewport;
00080
00081         // Direct2D drawing components.
00082         Microsoft::WRL::ComPtr<ID2D1Factory2>       m_d2dFactory;
00083         Microsoft::WRL::ComPtr<ID2D1Device1>        m_d2dDevice;
00084         Microsoft::WRL::ComPtr<ID2D1DeviceContext1> m_d2dContext;
00085         Microsoft::WRL::ComPtr<ID2D1Bitmap1>        m_d2dTargetBitmap;
00086
00087         // DirectWrite drawing components.
00088         Microsoft::WRL::ComPtr<IDWriteFactory2>     m_dwriteFactory;
00089         Microsoft::WRL::ComPtr<IWICImagingFactory2> m_wicFactory;
00090
00091         // Cached reference to the XAML panel.
00092         Windows::UI::Xaml::Controls::SwapChainPanel^    m_swapChainPanel;
00093
00094         // Used to achieve lowest output latency
00095         HANDLE m_frameLatencyWaitableObject;
00096
00097         // Cached device properties.
00098         D3D_FEATURE_LEVEL                               m_d3dFeatureLevel;
00099         Windows::Foundation::Size                       m_d3dRenderTargetSize;
00100         Windows::Foundation::Size                       m_outputSize;
00101         Windows::Foundation::Size                       m_logicalSize;
00102         Windows::Graphics::Display::DisplayOrientations m_nativeOrientation;
00103         Windows::Graphics::Display::DisplayOrientations m_currentOrientation;
00104         float                                           m_dpi;
00105         float                                           m_compositionScaleX;
00106         float                                           m_compositionScaleY;
00107
00108         // Transforms used for display orientation.
00109         D2D1::Matrix3x2F    m_orientationTransform2D;
00110         DirectX::XMFLOAT4X4 m_orientationTransform3D;
00111
00112         // The IDeviceNotify can be held directly as it owns the DeviceResources.
00113         IDeviceNotify* m_deviceNotify;
00114     };
00115 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cppwinrt/Scenario2_Remove.cpp Source File

  • JumpList
  • cppwinrt

Scenario2_Remove.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_Remove.h"
00014 #include "Scenario2_Remove.g.cpp"
00015
00016 using namespace winrt;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::UI::StartScreen;
00019 using namespace Windows::UI::Xaml;
00020
00021 namespace winrt::SDKTemplate::implementation
00022 {
00023     Scenario2_Remove::Scenario2_Remove()
00024     {
00025         InitializeComponent();
00026     }
00027
00028     fire_and_forget Scenario2_Remove::RemoveJumpList_Click(IInspectable const&, RoutedEventArgs const&)
00029     {
00030         auto lifetime = get_strong();
00031
00032         JumpList jumpList = co_await JumpList::LoadCurrentAsync();
00033         jumpList.SystemGroupKind(JumpListSystemGroupKind::None);
00034         jumpList.Items().Clear();
00035         co_await jumpList.SaveAsync();
00036     }
00037 }
Generated on Fri Nov 15 2024 22:20:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppServices/cppwinrt/AppServicesClient/SampleConfiguration.cpp Source File

  • AppServices
  • cppwinrt
  • AppServicesClient

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation::Collections;
00019 using namespace winrt::SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"AppServicesClient C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Open/Close Connection", xaml_typename<OpenCloseConnectionScenario>() },
00029     Scenario{ L"Keep Connection Open", xaml_typename<KeepConnectionOpenScenario>() },
00030 });
00031
00032 bool SDKTemplate::TryParseInt32(wchar_t const* text, int32_t& value)
00033 {
00034     wchar_t* end;
00035     errno = 0;
00036     value = std::wcstol(text, &end, 10);
00037
00038     if (text == end || *end != L'\0')
00039     {
00040         // Not parseable.
00041         return false;
00042     }
00043
00044     if (errno == ERANGE)
00045     {
00046         // Out of range.
00047         return false;
00048     }
00049
00050     return true;
00051 }
Generated on Fri Nov 15 2024 22:17:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cppwinrt/Scenario5_DisplayingBarcodePreview.cpp Source File

  • BarcodeScanner
  • cppwinrt

Scenario5_DisplayingBarcodePreview.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario5_DisplayingBarcodePreview.h"
00014 #include "Scenario5_DisplayingBarcodePreview.g.cpp"
00015
00016 namespace winrt
00017 {
00018     using namespace Windows::Foundation;
00019     using namespace Windows::Foundation::Collections;
00020     using namespace Windows::Devices;
00021     using namespace Windows::Devices::Enumeration;
00022     using namespace Windows::Devices::PointOfService;
00023     using namespace Windows::Graphics::Display;
00024     using namespace Windows::System::Display;
00025     using namespace Windows::UI::Xaml;
00026     using namespace Windows::UI::Xaml::Controls;
00027     using namespace Windows::UI::Xaml::Data;
00028     using namespace Windows::UI::Xaml::Navigation;
00029     using namespace Windows::Media::Capture;
00030 }
00031
00032 namespace winrt::SDKTemplate::implementation
00033 {
00034     Scenario5_DisplayingBarcodePreview::Scenario5_DisplayingBarcodePreview()
00035     {
00036         InitializeComponent();
00037
00038         ScannerListSource().Source(m_barcodeScanners);
00039         m_watcher = DeviceInformation::CreateWatcher(BarcodeScanner::GetDeviceSelector());
00040         m_watcher.Added({ get_weak(), &Scenario5_DisplayingBarcodePreview::Watcher_Added });
00041         m_watcher.Removed({ get_weak(), &Scenario5_DisplayingBarcodePreview::Watcher_Removed });
00042         m_watcher.Updated({ get_weak(), &Scenario5_DisplayingBarcodePreview::Watcher_Updated });
00043         m_watcher.Start();
00044
00045         DataContext(*this);
00046     }
00047
00048     fire_and_forget Scenario5_DisplayingBarcodePreview::Watcher_Added(DeviceWatcher const& sender, DeviceInformation args)
00049     {
00050         auto lifetime = get_strong();
00051         co_await Dispatcher();
00052
00053         m_barcodeScanners.Append({ args.Name(), args.Id() });
00054
00055         if (m_barcodeScanners.Size() == 1)
00056         {
00057             ScannerListBox().SelectedIndex(0);
00058         }
00059     }
00060
00061     fire_and_forget Scenario5_DisplayingBarcodePreview::Watcher_Removed(DeviceWatcher const&, DeviceInformationUpdate const&)
00062     {
00063         // We don't do anything here, but this event needs to be handled to enable realtime updates.
00064         // See https://aka.ms/devicewatcher_added.
00065         co_return;
00066     }
00067
00068     fire_and_forget Scenario5_DisplayingBarcodePreview::Watcher_Updated(DeviceWatcher const&, DeviceInformationUpdate const&)
00069     {
00070         // We don't do anything here, but this event needs to be handled to enable realtime updates.
00071         //See https://aka.ms/devicewatcher_added.
00072         co_return;
00073     }
00074
00075     fire_and_forget Scenario5_DisplayingBarcodePreview::OnNavigatedFrom(NavigationEventArgs const&)
00076     {
00077         auto lifetime = get_strong();
00078
00079         m_watcher.Stop();
00080
00081         if (m_isSelectionChanging)
00082         {
00083             isStopPending = true;
00084         }
00085         else
00086         {
00087             co_await CloseScannerResourcesAsync();
00088         }
00089     }
00090
00091     /// <summary>
00092     /// Starts previewing the selected scanner's video feed and prevents the display from going to sleep.
00093     /// </summary>
00094     IAsyncAction Scenario5_DisplayingBarcodePreview::StartMediaCaptureAsync(hstring videoDeviceId)
00095     {
00096         auto lifetime = get_strong();
00097         m_mediaCapture = MediaCapture();
00098
00099         // Register for a notification when something goes wrong
00100         m_mediaCapture.Failed({ get_weak(), &Scenario5_DisplayingBarcodePreview::MediaCapture_Failed });
00101
00102         auto settings = MediaCaptureInitializationSettings();
00103         settings.VideoDeviceId(videoDeviceId);
00104         settings.StreamingCaptureMode(StreamingCaptureMode::Video);
00105         settings.SharingMode(MediaCaptureSharingMode::SharedReadOnly);
00106
00107         // Initialize MediaCapture
00108         bool captureInitialized = false;
00109         try
00110         {
00111             co_await m_mediaCapture.InitializeAsync(settings);
00112             captureInitialized = true;
00113         }
00114         catch (hresult_access_denied const&)
00115         {
00116             m_rootPage.NotifyUser(L"The app was denied access to the camera", NotifyType::ErrorMessage);
00117         }
00118         catch (hresult_error const& e)
00119         {
00120             m_rootPage.NotifyUser(L"Failed to initialize the camera: " + e.message(), NotifyType::ErrorMessage);
00121         }
00122
00123         if (captureInitialized)
00124         {
00125             // Prevent the device from sleeping while the preview is running.
00126             m_displayRequest.RequestActive();
00127
00128             PreviewControl().Source(m_mediaCapture);
00129             co_await m_mediaCapture.StartPreviewAsync();
00130             co_await SetPreviewRotationAsync(DisplayInformation::GetForCurrentView().CurrentOrientation());
00131             IsPreviewing(true);
00132             RaisePropertyChanged(L"IsPreviewing");
00133         }
00134         else
00135         {
00136             m_mediaCapture.Close();
00137             m_mediaCapture = nullptr;
00138         }
00139     }
00140
00141     /// <summary>
00142     /// Close the scanners and stop the preview.
00143     /// </summary>
00144     IAsyncAction Scenario5_DisplayingBarcodePreview::CloseScannerResourcesAsync()
00145     {
00146         auto lifetime = get_strong();
00147         if (m_claimedScanner)
00148         {
00149             m_claimedScanner.Close();
00150             m_claimedScanner = nullptr;
00151         }
00152
00153         if (m_selectedScanner)
00154         {
00155             m_selectedScanner.Close();
00156             m_selectedScanner = nullptr;
00157         }
00158
00159         SoftwareTriggerStarted(false);
00160         RaisePropertyChanged(L"SoftwareTriggerStarted");
00161
00162         if (!IsPreviewing())
00163         {
00164             co_return;
00165         }
00166
00167         if (m_mediaCapture)
00168         {
00169             co_await m_mediaCapture.StopPreviewAsync();
00170             m_mediaCapture.Close();
00171             m_mediaCapture = nullptr;
00172         }
00173
00174         if (m_displayRequest)
00175         {
00176             m_displayRequest.RequestRelease();
00177             IsPreviewing(false);
00178             RaisePropertyChanged(L"IsPreviewing");
00179         }
00180     }
00181
00182     /// <summary>
00183     /// Set preview rotation and mirroring state to adjust for the orientation of the camera, and for embedded cameras, the rotation of the device.
00184     /// </summary>
00185     /// <param name="message"></param>
00186     /// <param name="type"></param>
00187     IAsyncAction Scenario5_DisplayingBarcodePreview::SetPreviewRotationAsync(DisplayOrientations displayOrientation)
00188     {
00189         auto lifetime = get_strong();
00190         bool isExternalCamera;
00191         bool isPreviewMirrored;
00192
00193         // Figure out where the camera is located to account for mirroring and later adjust rotation accordingly.
00194         DeviceInformation cameraInformation = co_await DeviceInformation::CreateFromIdAsync(m_selectedScanner.VideoDeviceId());
00195
00196         if ((cameraInformation.EnclosureLocation() == nullptr) || (cameraInformation.EnclosureLocation().Panel() == Windows::Devices::Enumeration::Panel::Unknown))
00197         {
00198             isExternalCamera = true;
00199             isPreviewMirrored = false;
00200         }
00201         else
00202         {
00203             isExternalCamera = false;
00204             isPreviewMirrored = (cameraInformation.EnclosureLocation().Panel() == Windows::Devices::Enumeration::Panel::Front);
00205         }
00206
00207         PreviewControl().FlowDirection(isPreviewMirrored ? FlowDirection::RightToLeft : FlowDirection::LeftToRight);
00208
00209         if (!isExternalCamera)
00210         {
00211             // Calculate which way and how far to rotate the preview.
00212             int rotationDegrees = 0;
00213             switch (displayOrientation)
00214             {
00215             case DisplayOrientations::Portrait:
00216                 rotationDegrees = 90;
00217                 break;
00218             case DisplayOrientations::LandscapeFlipped:
00219                 rotationDegrees = 180;
00220                 break;
00221             case DisplayOrientations::PortraitFlipped:
00222                 rotationDegrees = 270;
00223                 break;
00224             case DisplayOrientations::Landscape:
00225             default:
00226                 rotationDegrees = 0;
00227                 break;
00228             }
00229
00230             // The rotation direction needs to be inverted if the preview is being mirrored.
00231             if (isPreviewMirrored)
00232             {
00233                 rotationDegrees = (360 - rotationDegrees) % 360;
00234             }
00235
00236             // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames.
00237             auto streamProperties = m_mediaCapture.VideoDeviceController().GetMediaStreamProperties(MediaStreamType::VideoPreview);
00238             static constexpr guid rotationGuid(0xC380465D, 0x2271, 0x428C, { 0x9B, 0x83, 0xEC, 0xEA, 0x3B, 0x4A, 0x85, 0xC1 });
00239             streamProperties.Properties().Insert(rotationGuid, box_value(rotationDegrees));
00240             co_await m_mediaCapture.SetEncodingPropertiesAsync(MediaStreamType::VideoPreview, streamProperties, nullptr);
00241         }
00242     }
00243
00244     /// <summary>
00245     /// Media capture failed, potentially due to the camera being unplugged.
00246     /// </summary>
00247     /// <param name="sender"></param>
00248     /// <param name="errorEventArgs"></param>
00249     void Scenario5_DisplayingBarcodePreview::MediaCapture_Failed(MediaCapture const&, MediaCaptureFailedEventArgs const&)
00250     {
00251         m_rootPage.NotifyUser(L"Media capture failed. Make sure the camera is still connected.", NotifyType::ErrorMessage);
00252     }
00253
00254     /// <summary>
00255     /// Event Handler for Show Preview Button Click.
00256     /// Displays the preview window for the selected barcode scanner.
00257     /// </summary>
00258     /// <param name="sender"></param>
00259     /// <param name="e"></param>
00260     fire_and_forget Scenario5_DisplayingBarcodePreview::ShowPreviewButton_Click(IInspectable const&, RoutedEventArgs const&)
00261     {
00262         auto lifetime = get_strong();
00263
00264         if (m_claimedScanner)
00265         {
00266             co_await m_claimedScanner.ShowVideoPreviewAsync();
00267         }
00268     }
00269
00270     /// <summary>
00271     /// Event Handler for Hide Preview Button Click.
00272     /// Hides the preview window for the selected barcode scanner.
00273     /// </summary>
00274     /// <param name="sender"></param>
00275     /// <param name="e"></param>
00276     void Scenario5_DisplayingBarcodePreview::HidePreviewButton_Click(IInspectable const&, RoutedEventArgs const&)
00277     {
00278         if (m_claimedScanner)
00279         {
00280             m_claimedScanner.HideVideoPreview();
00281         }
00282     }
00283
00284     /// <summary>
00285     /// Event Handler for Start Software Trigger Button Click.
00286     /// Starts scanning.
00287     /// </summary>
00288     /// <param name="sender"></param>
00289     /// <param name="e"></param>
00290     fire_and_forget Scenario5_DisplayingBarcodePreview::StartSoftwareTriggerButton_Click(IInspectable const&, RoutedEventArgs const&)
00291     {
00292         auto lifetime = get_strong();
00293
00294         if (m_claimedScanner)
00295         {
00296             co_await m_claimedScanner.StartSoftwareTriggerAsync();
00297
00298             SoftwareTriggerStarted(true);
00299             RaisePropertyChanged(L"SoftwareTriggerStarted");
00300         }
00301     }
00302
00303     /// <summary>
00304     /// Event Handler for Stop Software Trigger Button Click.
00305     /// Stops scanning.
00306     /// </summary>
00307     /// <param name="sender"></param>
00308     /// <param name="e"></param>
00309     fire_and_forget Scenario5_DisplayingBarcodePreview::StopSoftwareTriggerButton_Click(IInspectable const&, RoutedEventArgs const&)
00310     {
00311         auto lifetime = get_strong();
00312
00313         if (m_claimedScanner)
00314         {
00315             co_await m_claimedScanner.StopSoftwareTriggerAsync();
00316
00317             SoftwareTriggerStarted(false);
00318             RaisePropertyChanged(L"SoftwareTriggerStarted");
00319         }
00320     }
00321
00322     /// <summary>
00323     /// Event Handler for Flip Preview Button Click.
00324     /// Stops scanning.
00325     /// </summary>
00326     /// <param name="sender"></param>
00327     /// <param name="e"></param>
00328     void Scenario5_DisplayingBarcodePreview::FlipPreview_Click(IInspectable const&, RoutedEventArgs const&)
00329     {
00330         if (PreviewControl().FlowDirection() == FlowDirection::LeftToRight)
00331         {
00332             PreviewControl().FlowDirection(FlowDirection::RightToLeft);
00333         }
00334         else
00335         {
00336             PreviewControl().FlowDirection(FlowDirection::LeftToRight);
00337         }
00338     }
00339
00340     /// <summary>
00341     /// Event handler for scanner listbox selection changed
00342     /// </summary>
00343     /// <param name="sender"></param>
00344     /// <param name="args"></param>
00345     fire_and_forget Scenario5_DisplayingBarcodePreview::ScannerSelection_Changed(IInspectable const& sender, SelectionChangedEventArgs const& args)
00346     {
00347         auto lifetime = get_strong();
00348         auto selectedScannerInfo = args.AddedItems().GetAt(0).as<SDKTemplate::BarcodeScannerInfo>();
00349         auto deviceId = selectedScannerInfo.DeviceId();
00350
00351         if (m_isSelectionChanging)
00352         {
00353             m_pendingSelectionDeviceId = deviceId;
00354             return;
00355         }
00356
00357         do
00358         {
00359             co_await SelectScannerAsync(deviceId);
00360
00361             // Stop takes precedence over updating the selection.
00362             if (isStopPending)
00363             {
00364                 co_await CloseScannerResourcesAsync();
00365                 break;
00366             }
00367
00368             deviceId = m_pendingSelectionDeviceId;
00369             m_pendingSelectionDeviceId.clear();
00370         } while (!deviceId.empty());
00371     }
00372
00373     /// <summary>
00374     /// Select the scanner specified by its device ID.
00375     /// </summary>
00376     /// <param name="scannerDeviceId"></param>
00377     IAsyncAction Scenario5_DisplayingBarcodePreview::SelectScannerAsync(hstring scannerDeviceId)
00378     {
00379         auto lifetime = get_strong();
00380         m_isSelectionChanging = true;
00381
00382         co_await CloseScannerResourcesAsync();
00383
00384         m_selectedScanner = co_await BarcodeScanner::FromIdAsync(scannerDeviceId);
00385
00386         if (m_selectedScanner)
00387         {
00388             m_claimedScanner = co_await m_selectedScanner.ClaimScannerAsync();
00389             if (m_claimedScanner)
00390             {
00391                 co_await m_claimedScanner.EnableAsync();
00392                 m_claimedScanner.Closed({ get_weak(), &Scenario5_DisplayingBarcodePreview::ClaimedScanner_Closed });
00393                 ScannerSupportsPreview(!m_selectedScanner.VideoDeviceId().empty());
00394                 RaisePropertyChanged(L"ScannerSupportsPreview");
00395
00396                 m_claimedScanner.DataReceived({ get_weak(), &Scenario5_DisplayingBarcodePreview::ClaimedScanner_DataReceived });
00397
00398                 if (ScannerSupportsPreview())
00399                 {
00400                     co_await StartMediaCaptureAsync(m_selectedScanner.VideoDeviceId());
00401                 }
00402             }
00403             else
00404             {
00405                 m_rootPage.NotifyUser(L"Failed to claim the selected barcode scanner", NotifyType::ErrorMessage);
00406             }
00407
00408         }
00409         else
00410         {
00411             m_rootPage.NotifyUser(L"Failed to create a barcode scanner object", NotifyType::ErrorMessage);
00412         }
00413
00414         IsScannerClaimed(m_claimedScanner != nullptr);
00415         RaisePropertyChanged(L"IsScannerClaimed");
00416
00417         m_isSelectionChanging = false;
00418     }
00419
00420     /// <summary>
00421     /// Closed notification was received from the selected scanner.
00422     /// </summary>
00423     /// <param name="sender"></param>
00424     /// <param name="args"></param>
00425     void Scenario5_DisplayingBarcodePreview::ClaimedScanner_Closed(ClaimedBarcodeScanner const&, ClaimedBarcodeScannerClosedEventArgs const&)
00426     {
00427         // Resources associated to the claimed barcode scanner can be cleaned up here
00428     }
00429
00430     /// <summary>
00431     /// Scan data was received from the selected scanner.
00432     /// </summary>
00433     /// <param name="sender"></param>
00434     /// <param name="args"></param>
00435     fire_and_forget Scenario5_DisplayingBarcodePreview::ClaimedScanner_DataReceived(ClaimedBarcodeScanner const&, BarcodeScannerDataReceivedEventArgs args)
00436     {
00437         auto lifetime = get_strong();
00438         co_await Dispatcher();
00439         ScenarioOutputScanDataLabel().Text(GetDataLabelString(args.Report().ScanDataLabel(), args.Report().ScanDataType()));
00440         ScenarioOutputScanData().Text(GetDataString(args.Report().ScanData()));
00441         ScenarioOutputScanDataType().Text(BarcodeSymbologies::GetName(args.Report().ScanDataType()));
00442     }
00443
00444     /// <summary>
00445     /// Update listeners that a property was changed so that data bindings can be updated.
00446     /// </summary>
00447     /// <param name="propertyName"></param>
00448     void Scenario5_DisplayingBarcodePreview::RaisePropertyChanged(hstring propertyName)
00449     {
00450         m_propertyChanged(*this, PropertyChangedEventArgs(propertyName));
00451     }
00452
00453 }
Generated on Fri Nov 15 2024 22:18:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Package/cs/scenario2_installedlocation.xaml.cs Source File

  • Package
  • cs

scenario2_installedlocation.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using SDKTemplate;
00015 using System;
00016 using Windows.ApplicationModel;
00017
00018 namespace SDKTemplate
00019 {
00020     /// <summary>
00021     /// An empty page that can be used on its own or navigated to within a Frame.
00022     /// </summary>
00023     public sealed partial class Scenario2 : Page
00024     {
00025         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00026         // as NotifyUser()
00027         MainPage rootPage = MainPage.Current;
00028
00029         public Scenario2()
00030         {
00031             this.InitializeComponent();
00032         }
00033
00034         void GetInstalledLocation_Click(Object sender, RoutedEventArgs e)
00035         {
00036             // This will give the Installed Location.  You can use this location to access files, if you need them.
00037             Windows.Storage.StorageFolder installedLocation = Package.Current.InstalledLocation;
00038
00039             OutputTextBlock.Text = String.Format("Installed Location: {0}", installedLocation.Path); ;
00040         }
00041
00042         /// <summary>
00043         /// Invoked when this page is about to be displayed in a Frame.
00044         /// </summary>
00045         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00046         /// property is typically used to configure the page.</param>
00047         protected override void OnNavigatedTo(NavigationEventArgs e)
00048         {
00049         }
00050     }
00051 }
Generated on Fri Nov 15 2024 22:20:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_BasicFunctionality Member List

This is the complete list of members for Scenario1_BasicFunctionality, including all inherited members.
claimedScanner | Scenario1_BasicFunctionality | [private]
claimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args) | Scenario1_BasicFunctionality | [inline, private]
claimedScanner_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e) | Scenario1_BasicFunctionality | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_BasicFunctionality | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_BasicFunctionality | [inline, protected]
ResetTheScenarioState() | Scenario1_BasicFunctionality | [inline, private]
rootPage | Scenario1_BasicFunctionality | [private]
scanner | Scenario1_BasicFunctionality | [private]
Scenario1_BasicFunctionality() | Scenario1_BasicFunctionality | [inline]
ScenarioEndScanButton_Click(object sender, RoutedEventArgs e) | Scenario1_BasicFunctionality | [inline, private]
ScenarioStartScanButton_Click(object sender, RoutedEventArgs e) | Scenario1_BasicFunctionality | [inline, private]
ScenarioStartTriggerButton_Click(object sender, RoutedEventArgs e) | Scenario1_BasicFunctionality | [inline, private]
ScenarioStopTriggerButton_Click(object sender, RoutedEventArgs e) | Scenario1_BasicFunctionality | [inline, private]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1 Member List

This is the complete list of members for Scenario1, including all inherited members.
CompressAlgorithmComboBox_SelectionChanged(object sender, RoutedEventArgs e) | Scenario1 | [inline, private]
CompressAlgorithmFromComboBoxItem(ComboBoxItem item) | Scenario1 | [inline, private]
CompressFile(CompressAlgorithm?Algorithm, StorageFile originalFile) | Scenario1 | [inline, private]
CompressFileButton_Click(object sender, RoutedEventArgs e) | Scenario1 | [inline, private]
DoScenario(CompressAlgorithm?Algorithm) | Scenario1 | [inline, private]
rootPage | Scenario1 | [private]
Scenario1() | Scenario1 | [inline]
UpdateDescriptionVisibility(ComboBoxItem item, Visibility visibility) | Scenario1 | [inline, private]
Generated on Fri Nov 15 2024 22:23:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

sealed Member List

This is the complete list of members for sealed, including all inherited members.
CompressAlgorithmComboBox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CompressAlgorithmComboBox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CompressAlgorithmComboBox_SelectionChanged(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CompressAlgorithmFromComboBoxItem(Windows::UI::Xaml::Controls::ComboBoxItem^item) | sealed | [private]
CompressAlgorithmFromComboBoxItem(Windows::UI::Xaml::Controls::ComboBoxItem^item) | sealed | [private]
CompressAlgorithmFromComboBoxItem(Windows::UI::Xaml::Controls::ComboBoxItem^item) | sealed | [private]
CompressFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CompressFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
CompressFileButton_Click(Platform::Object^sender, Windows::UI::Xaml::RoutedEventArgs^e) | sealed | [private]
DoScenario(Windows::Storage::Compression::CompressAlgorithm Algorithm) | sealed | [private]
DoScenario(Windows::Storage::Compression::CompressAlgorithm Algorithm) | sealed | [private]
DoScenario(Windows::Storage::Compression::CompressAlgorithm Algorithm) | sealed | [private]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^e) override | sealed | [protected, virtual]
rootPage | sealed | [private]
Scenario1() | sealed |
Scenario2() | sealed |
Scenario3() | sealed |
UpdateDescriptionVisibility(Windows::UI::Xaml::Controls::ComboBoxItem^item, Windows::UI::Xaml::Visibility visibility) | sealed | [private]
UpdateDescriptionVisibility(Windows::UI::Xaml::Controls::ComboBoxItem^item, Windows::UI::Xaml::Visibility visibility) | sealed | [private]
UpdateDescriptionVisibility(Windows::UI::Xaml::Controls::ComboBoxItem^item, Windows::UI::Xaml::Visibility visibility) | sealed | [private]
Generated on Fri Nov 15 2024 22:24:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TouchKeyboard/cppwinrt/Scenario4_ShowView.h Source File

  • TouchKeyboard
  • cppwinrt

Scenario4_ShowView.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_ShowView.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario4_ShowView : Scenario4_ShowViewT<Scenario4_ShowView>
00020     {
00021         Scenario4_ShowView();
00022
00023         void TextBox_GotFocus(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024     };
00025 }
00026
00027 namespace winrt::SDKTemplate::factory_implementation
00028 {
00029     struct Scenario4_ShowView : Scenario4_ShowViewT<Scenario4_ShowView, implementation::Scenario4_ShowView>
00030     {
00031     };
00032 }
Generated on Fri Nov 15 2024 22:21:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SetConnectedFunc Member List

This is the complete list of members for SetConnectedFunc, including all inherited members.
_fConnected | SetConnectedFunc |
_llStartTime | SetConnectedFunc |
operator()(IMFStreamSink *pStream) const | SetConnectedFunc | [inline]
SetConnectedFunc(bool fConnected, LONGLONG llStartTime) | SetConnectedFunc | [inline]
Generated on Fri Nov 15 2024 22:23:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Capabilities/cs/Scenario2_RequestMany.xaml.cs Source File

  • Capabilities
  • cs

Scenario2_RequestMany.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.Foundation;
00015 using Windows.Security.Authorization.AppCapabilityAccess;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018
00019 namespace SDKTemplate
00020 {
00021     public sealed partial class Scenario2_RequestMany : Page
00022     {
00023         MainPage rootPage = MainPage.Current;
00024
00025         public Scenario2_RequestMany()
00026         {
00027             this.InitializeComponent();
00028         }
00029
00030         async void RequestAccessButton_Click(object sender, RoutedEventArgs e)
00031         {
00032             // This will prompt for any capabilities whose current status is UserPromptRequired.
00033             IReadOnlyDictionary<string, AppCapabilityAccessStatus> result =
00034                 await AppCapability.RequestAccessForCapabilitiesAsync(new[] { "location", "webcam" });
00035             string locationMessage;
00036             if (result["location"] == AppCapabilityAccessStatus.Allowed)
00037             {
00038                 locationMessage = "Location access is granted. ";
00039             }
00040             else
00041             {
00042                 // We could inspect the specific status to provide better feedback,
00043                 // but for the purpose of this sample, we merely report whether access was granted
00044                 // and do not study the reason why.
00045                 locationMessage = "Location access is not granted. ";
00046             }
00047             string webcamMessage;
00048             if (result["webcam"] == AppCapabilityAccessStatus.Allowed)
00049             {
00050                 webcamMessage = "Webcam access is granted. ";
00051             }
00052             else
00053             {
00054                 // We could inspect the specific status to provide better feedback,
00055                 // but for the purpose of this sample, we merely report whether access was granted
00056                 // and do not study the reason why.
00057                 webcamMessage = "Webcam access is not granted. ";
00058             }
00059             rootPage.NotifyUser(locationMessage + webcamMessage, NotifyType.StatusMessage);
00060         }
00061     }
00062 }
Generated on Fri Nov 15 2024 22:18:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RadioManager/cppwinrt/SampleConfiguration.h Source File

  • RadioManager
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ActivitySensor/cpp/Tasks/pch.h Source File

  • ActivitySensor
  • cpp
  • Tasks

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LowLatencyInput/cpp/pch.h Source File

  • LowLatencyInput
  • cpp

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020 #include "App.xaml.h"
00021
00022 //Added from DirectX/XAML template
00023 #include <wrl.h>
00024 #include <wrl/client.h>
00025 #include <d3d11_2.h>
00026 #include <d2d1_2.h>
00027 #include <d2d1effects_1.h>
00028 #include <dwrite_2.h>
00029 #include <wincodec.h>
00030 #include <DirectXColors.h>
00031 #include <DirectXMath.h>
00032 #include <memory>
00033 #include <agile.h>
00034 #include <concrt.h>
00035
00036
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SecondaryTiles/cs/Scenario8_UpdateAsync.xaml.cs Source File

  • SecondaryTiles
  • cs

Scenario8_UpdateAsync.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using System;
00012 using Windows.UI.StartScreen;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public sealed partial class Scenario8_UpdateAsync : Page
00019     {
00020         MainPage rootPage = MainPage.Current;
00021
00022         public Scenario8_UpdateAsync()
00023         {
00024             this.InitializeComponent();
00025         }
00026
00027         private async void UpdateDefaultLogo_Click(object sender, RoutedEventArgs e)
00028         {
00029             if (SecondaryTile.Exists(MainPage.logoSecondaryTileId))
00030             {
00031                 // Add the properties we want to update (logo in this example)
00032                 SecondaryTile secondaryTile = new SecondaryTile(MainPage.logoSecondaryTileId);
00033                 secondaryTile.VisualElements.Square150x150Logo = new Uri("ms-appx:///Assets/squareTileLogoUpdate-sdk.png");
00034                 bool isUpdated = await secondaryTile.UpdateAsync();
00035
00036                 if (isUpdated)
00037                 {
00038                     rootPage.NotifyUser("Secondary tile logo updated.", NotifyType.StatusMessage);
00039                 }
00040                 else
00041                 {
00042                     rootPage.NotifyUser("Secondary tile logo not updated.", NotifyType.ErrorMessage);
00043                 }
00044             }
00045             else
00046             {
00047                 rootPage.NotifyUser("Please pin a secondary tile using scenario 1 before updating the logo.", NotifyType.ErrorMessage);
00048             }
00049         }
00050     }
00051 }
Generated on Fri Nov 15 2024 22:21:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SmartCard/cppwinrt/Scenario3_ResetPIN.cpp Source File

  • SmartCard
  • cppwinrt

Scenario3_ResetPIN.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_ResetPIN.h"
00014 #include "Scenario3_ResetPIN.g.cpp"
00015
00016 namespace winrt
00017 {
00018     using namespace Windows::Devices::SmartCards;
00019     using namespace Windows::Foundation;
00020     using namespace Windows::Storage::Streams;
00021     using namespace Windows::UI::Xaml;
00022     using namespace Windows::UI::Xaml::Controls;
00023 }
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario3_ResetPIN::Scenario3_ResetPIN()
00028     {
00029         InitializeComponent();
00030     }
00031
00032     /// <summary>
00033     /// Click handler for the 'ResetPin' button.
00034     /// </summary>
00035     /// <param name="sender"></param>
00036     fire_and_forget Scenario3_ResetPIN::ResetPin_Click(IInspectable const& sender, RoutedEventArgs const&)
00037     {
00038         auto lifetime = get_strong();
00039
00040         if (!ValidateTPMSmartCard())
00041         {
00042             m_rootPage.NotifyUser(L"Use Scenario One to create a TPM virtual smart card.", NotifyType::ErrorMessage);
00043             co_return;
00044         }
00045
00046         auto b = sender.as<Button>();
00047         b.IsEnabled(false);
00048
00049         try
00050         {
00051             SmartCard card = co_await GetSmartCardAsync();
00052             SmartCardProvisioning provisioning = co_await SmartCardProvisioning::FromSmartCardAsync(card);
00053
00054             m_rootPage.NotifyUser(L"Resetting smart card PIN...", NotifyType::StatusMessage);
00055
00056             // When requesting a PIN reset, a SmartCardPinResetHandler must be
00057             // provided as an argument.  This handler must use the challenge
00058             // it receives and the card's admin key to calculate and set the
00059             // response.
00060             auto resetHandler = [this, self = get_strong()](SmartCardProvisioning const&, SmartCardPinResetRequest const& request)
00061             {
00062                 SmartCardPinResetDeferral deferral = request.GetDeferral();
00063                 IBuffer response = CalculateChallengeResponse(request.Challenge(), GetAdminKey());
00064                 request.SetResponse(response);
00065             };
00066
00067             bool result = co_await provisioning.RequestPinResetAsync(resetHandler);
00068
00069             if (result)
00070             {
00071                 m_rootPage.NotifyUser(L"Smart card PIN reset operation completed.", NotifyType::StatusMessage);
00072             }
00073             else
00074             {
00075                 m_rootPage.NotifyUser(L"Smart card PIN reset operation was canceled by the user.", NotifyType::StatusMessage);
00076             }
00077         }
00078         catch (hresult_error const& ex)
00079         {
00080             m_rootPage.NotifyUser(L"Resetting smart card PIN failed with exception: " + ex.message(), NotifyType::ErrorMessage);
00081         }
00082
00083         b.IsEnabled(true);
00084     }
00085 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/cs/Scenario2_VideoChat.xaml.cs Source File

  • SimpleCommunication
  • cs

Scenario2_VideoChat.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Microsoft.Samples.SimpleCommunication;
00012 using SDKTemplate;
00013 using System;
00014 using System.Threading;
00015 using System.Threading.Tasks;
00016 using Windows.Media.MediaProperties;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SimpleCommunication
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class VideoChat : Page
00028     {
00029         // A pointer back to the main page.  This is needed if you want to CallButton. methods in MainPage such
00030         // as NotifyUser()
00031         MainPage rootPage = MainPage.Current;
00032
00033         CaptureDevice device = null;
00034         bool? roleIsActive = null;
00035         int isTerminator = 0;
00036         bool activated = false;
00037
00038         public VideoChat()
00039         {
00040             this.InitializeComponent();
00041
00042             rootPage.EnsureMediaExtensionManager();
00043         }
00044
00045         /// <summary>
00046         /// Invoked when this page is about to be displayed in a Frame.
00047         /// </summary>
00048         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00049         /// property is typically used to configure the page.</param>
00050         protected async override void OnNavigatedTo(NavigationEventArgs e)
00051         {
00052             var cameraFound = await CaptureDevice.CheckForRecordingDeviceAsync();
00053
00054             if (cameraFound)
00055             {
00056                 device = new CaptureDevice();
00057                 await InitializeAsync();
00058                 device.IncomingConnectionArrived += Device_IncomingConnectionArrived;
00059                 device.CaptureFailed += Device_CaptureFailed;
00060                 RemoteVideo.MediaFailed += RemoteVideo_MediaFailed;
00061             }
00062             else
00063             {
00064                 rootPage.NotifyUser("A machine with a camera and a microphone is required to run this sample.", NotifyType.ErrorMessage);
00065             }
00066         }
00067
00068         protected async override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00069         {
00070             base.OnNavigatingFrom(e);
00071
00072             if (activated)
00073             {
00074                 RemoteVideo.Stop();
00075                 RemoteVideo.Source = null;
00076             }
00077
00078             if (device != null)
00079             {
00080                 await device.CleanUpAsync();
00081                 device = null;
00082             }
00083         }
00084
00085         private async Task InitializeAsync(CancellationToken cancel = default(CancellationToken))
00086         {
00087             rootPage.NotifyUser("Initializing..", NotifyType.StatusMessage);
00088
00089             try
00090             {
00091                 await device.InitializeAsync();
00092                 await StartRecordToCustomSink();
00093
00094                 HostNameTextbox.IsEnabled = CallButton.IsEnabled = true;
00095                 EndCallButton.IsEnabled = false;
00096                 RemoteVideo.Source = null;
00097
00098                 // Each client starts out as passive
00099                 roleIsActive = false;
00100                 Interlocked.Exchange(ref isTerminator, 0);
00101
00102                 rootPage.NotifyUser("Tap 'CallButton.' button to start CallButton.", NotifyType.StatusMessage);
00103             }
00104             catch (Exception)
00105             {
00106                 rootPage.NotifyUser("Initialization error. Restart the sample to try again.", NotifyType.ErrorMessage);
00107             }
00108
00109         }
00110
00111         async void RemoteVideo_MediaFailed(object sender, ExceptionRoutedEventArgs e)
00112         {
00113             if (Interlocked.CompareExchange(ref isTerminator, 1, 0) == 0)
00114             {
00115                 await EndCallAsync();
00116             }
00117         }
00118
00119         async void Device_IncomingConnectionArrived(object sender, IncomingConnectionEventArgs e)
00120         {
00121             e.Accept();
00122
00123             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, (() =>
00124             {
00125                 activated = true;
00126                 var remoteAddress = e.RemoteUrl;
00127                 EndCallButton.IsEnabled = true;
00128                 Interlocked.Exchange(ref isTerminator, 0);
00129
00130                 if (!((bool)roleIsActive))
00131                 {
00132                     // Passive client
00133                     RemoteVideo.Source = new Uri(remoteAddress);
00134                     HostNameTextbox.IsEnabled = CallButton.IsEnabled = false;
00135                 }
00136
00137                 remoteAddress = remoteAddress.Replace("stsp://", "");
00138                 rootPage.NotifyUser("Connected. Remote machine address: " + remoteAddress, NotifyType.StatusMessage);
00139             }));
00140         }
00141
00142         async void Device_CaptureFailed(object sender, Windows.Media.Capture.MediaCaptureFailedEventArgs e)
00143         {
00144             if (Interlocked.CompareExchange(ref isTerminator, 1, 0) == 0)
00145             {
00146                 await EndCallAsync();
00147             }
00148         }
00149
00150         private async Task StartRecordToCustomSink()
00151         {
00152             MediaEncodingProfile mep = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Qvga);
00153
00154             mep.Video.FrameRate.Numerator = 15;
00155             mep.Video.FrameRate.Denominator = 1;
00156             mep.Container = null;
00157
00158             await device.StartRecordingAsync(mep);
00159         }
00160
00161         /// <summary>
00162         /// This is the click handler for the 'Default' button.  You would replace this with your own handler
00163         /// if you have a button or buttons on this page.
00164         /// </summary>
00165         /// <param name="sender"></param>
00166         /// <param name="e"></param>
00167         private void CallButton_Click(object sender, RoutedEventArgs e)
00168         {
00169             Button b = sender as Button;
00170             var address = HostNameTextbox.Text;
00171
00172             if (b != null && !String.IsNullOrEmpty(address))
00173             {
00174                 roleIsActive = true;
00175                 RemoteVideo.Source = new Uri("stsp://" + address);
00176                 HostNameTextbox.IsEnabled = CallButton.IsEnabled = false;
00177                 rootPage.NotifyUser("Initiating connection.. Please wait.", NotifyType.StatusMessage);
00178             }
00179         }
00180
00181         /// <summary>
00182         /// This is the click handler for the 'Other' button.  You would replace this with your own handler
00183         /// if you have a button or buttons on this page.
00184         /// </summary>
00185         /// <param name="sender"></param>
00186         /// <param name="e"></param>
00187         private async void EndCallButton_Click(object sender, RoutedEventArgs e)
00188         {
00189             Button b = sender as Button;
00190             if (b != null && Interlocked.CompareExchange(ref isTerminator, 1, 0) == 0)
00191             {
00192                 await EndCallAsync();
00193             }
00194         }
00195
00196         private async Task EndCallAsync()
00197         {
00198             await device.CleanUpAsync();
00199
00200             // end the CallButton. session
00201             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, (() =>
00202             {
00203                 RemoteVideo.Stop();
00204                 RemoteVideo.Source = null;
00205             }));
00206
00207             // Start waiting for a new CallButton.
00208             await InitializeAsync();
00209         }
00210     }
00211 }
Generated on Fri Nov 15 2024 22:21:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cpp/Scenario5_DataEventsBatching.xaml.cpp Source File

  • Accelerometer
  • cpp

Scenario5_DataEventsBatching.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario5_DataEventsBatching.xaml.cpp
00014 // Implementation of the Scenario5_DataEventsBatching class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario5_DataEventsBatching.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Windows::Devices::Sensors;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::UI::Core;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 Scenario5_DataEventsBatching::Scenario5_DataEventsBatching()
00031 {
00032     InitializeComponent();
00033 }
00034
00035 void Scenario5_DataEventsBatching::OnNavigatedTo(NavigationEventArgs^ e)
00036 {
00037     accelerometer = Accelerometer::GetDefault(rootPage->AccelerometerReadingType);
00038     if (accelerometer != nullptr)
00039     {
00040         // Select a report interval and report latency that is both suitable for the purposes of the app and supported by the sensor.
00041         // This value will be used later to activate the sensor.
00042         desiredReportInterval = (std::max)(accelerometer->MinimumReportInterval, 16U);
00043
00044         // MaxBatchSize will be 0 if the accelerometer does not support batching.
00045         desiredReportLatency = (std::min)(desiredReportInterval * accelerometer->MaxBatchSize, 10000U);
00046
00047         rootPage->NotifyUser(rootPage->AccelerometerReadingType.ToString() + " accelerometer ready", NotifyType::StatusMessage);
00048         ScenarioEnableButton->IsEnabled = true;
00049     }
00050     else
00051     {
00052         rootPage->NotifyUser(rootPage->AccelerometerReadingType.ToString() + " accelerometer not found", NotifyType::ErrorMessage);
00053     }
00054 }
00055
00056 void Scenario5_DataEventsBatching::OnNavigatedFrom(NavigationEventArgs^ e)
00057 {
00058     if (ScenarioDisableButton->IsEnabled)
00059     {
00060         ScenarioDisable();
00061     }
00062 }
00063
00064 /// <summary>
00065 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00066 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00067 /// </summary>
00068 /// <param name="sender"></param>
00069 /// <param name="e">
00070 /// Event data that can be examined for the current visibility state.
00071 /// </param>
00072 void Scenario5_DataEventsBatching::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00073 {
00074     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00075     if (ScenarioDisableButton->IsEnabled)
00076     {
00077         if (e->Visible)
00078         {
00079             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00080             readingToken = accelerometer->ReadingChanged += ref new TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^>(this, &Scenario5_DataEventsBatching::ReadingChanged);
00081         }
00082         else
00083         {
00084             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00085             accelerometer->ReadingChanged -= readingToken;
00086         }
00087     }
00088 }
00089
00090 void Scenario5_DataEventsBatching::ReadingChanged(Accelerometer^ sender, AccelerometerReadingChangedEventArgs^ e)
00091 {
00092     // We need to dispatch to the UI thread to display the output
00093     Dispatcher->RunAsync(
00094         CoreDispatcherPriority::Normal,
00095         ref new DispatchedHandler(
00096             [this, e]()
00097             {
00098                 MainPage::SetReadingText(ScenarioOutput, e->Reading);
00099             },
00100             CallbackContext::Any
00101             )
00102         );
00103 }
00104
00105 void Scenario5_DataEventsBatching::ScenarioEnable()
00106 {
00107     // Establish the report interval
00108     accelerometer->ReportInterval = desiredReportInterval;
00109
00110     // Establish the report latency. This is a no-op if the accelerometer does not support batching
00111     accelerometer->ReportLatency = desiredReportLatency;
00112
00113     visibilityToken = Window::Current->VisibilityChanged += ref new WindowVisibilityChangedEventHandler(this, &Scenario5_DataEventsBatching::VisibilityChanged);
00114     readingToken = accelerometer->ReadingChanged += ref new TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^>(this, &Scenario5_DataEventsBatching::ReadingChanged);
00115
00116     ScenarioEnableButton->IsEnabled = false;
00117     ScenarioDisableButton->IsEnabled = true;
00118 }
00119
00120 void Scenario5_DataEventsBatching::ScenarioDisable()
00121 {
00122     Window::Current->VisibilityChanged -= visibilityToken;
00123     accelerometer->ReadingChanged -= readingToken;
00124
00125     // Restore the default report interval to release resources while the sensor is not in use
00126     accelerometer->ReportInterval = 0;
00127
00128     ScenarioEnableButton->IsEnabled = true;
00129     ScenarioDisableButton->IsEnabled = false;
00130 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cpp/ServiceViewModel.h Source File

  • CustomCapability
  • cpp

ServiceViewModel.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include "RpcClientApi.h"
00004 #include <memory>
00005
00006 namespace SDKTemplate
00007 {
00008     [Windows::UI::Xaml::Data::Bindable]
00009     public ref class ServiceViewModel sealed : Windows::UI::Xaml::Data::INotifyPropertyChanged
00010     {
00011     public:
00012         void StartMetering(int sampleRate);
00013         void SetSamplePeriod(int rate);
00014         void StopMetering();
00015         static property ServiceViewModel^ Current {ServiceViewModel^ get(); };
00016         property Platform::String^ ExpectedRpcCallbackRate
00017         {
00018             Platform::String^ get();
00019             void set(Platform::String^ value);
00020         }
00021         property Platform::String^ ActualRpcCallbackRate
00022         {
00023             Platform::String^ get();
00024             void set(Platform::String^ value);
00025         }
00026         property Platform::String^ SampleMessage
00027         {
00028             Platform::String^ get();
00029             void set(Platform::String^ value);
00030         }
00031         property bool StartButtonEnabled
00032         {
00033             bool get();
00034             void set(bool value);
00035         }
00036         property bool StopButtonEnabled
00037         {
00038             bool get();
00039             void set(bool value);
00040         }
00041         property bool SliderEnabled
00042         {
00043             bool get();
00044             void set(bool value);
00045         }
00046         property double SliderValue
00047         {
00048             double get();
00049             void set(double value);
00050         }
00051         virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged;
00052
00053     private:
00054         ServiceViewModel();
00055         static ServiceViewModel^ _Current;
00056         volatile bool meteringOn;
00057         bool meteringOnWhileSuspension;
00058         Windows::UI::Core::ICoreDispatcher^ dispatcher;
00059         int samplePeriod;
00060         ULARGE_INTEGER lastUpdateTime;
00061         __int64 rpcDataCountOld = 0;
00062         unsigned int sampleRefreshCount = 0;
00063         RPC_CLIENT_HANDLE rpcclient;
00064         bool stopMeteringRequested;
00065         bool NotifyIfAnyError(__int64 errCode);
00066
00067         // Variables backing UI bindings
00068         Platform::String^ sampleMessage;
00069         Platform::String^ expectedRpcCallbackRate;
00070         Platform::String^ actualRpcCallbackRate;
00071         bool startButtonEnabled;
00072         bool stopButtonEnabled;
00073         bool sliderEnabled;
00074         double sliderValue;
00075
00076         void NotifyPropertyChanged(Platform::String^ prop);
00077         void ServiceViewModel::SuspendMeteringService(Object^, Windows::ApplicationModel::SuspendingEventArgs^);
00078         void ServiceViewModel::ResumeMeteringService(Object^, Object^);
00079
00080         Platform::Array<__int64>^ sampleArray;
00081     };
00082 }
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/ContinuationPage.xaml.cpp Source File

  • Printing
  • cpp

ContinuationPage.xaml.cpp

Go to the documentation of this file.
00001 ﻿// Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "ContinuationPage.xaml.h"
00005
00006 using namespace SDKTemplate;
00007 using namespace Windows::UI::Xaml::Controls;
00008
00009 ContinuationPage::ContinuationPage(RichTextBlockOverflow^ textLinkContainer)
00010 {
00011     InitializeComponent();
00012     textLinkContainer->OverflowContentTarget = ContinuationPageLinkedContainer;
00013 }
Generated on Fri Nov 15 2024 22:20:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SemanticTextQuery/cpp/Find.xaml.h Source File

  • SemanticTextQuery
  • cpp

Find.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Find.xaml.h
00014 // Declaration of the Scenario1 class
00015 //
00016
00017 #pragma once
00018 #include "Find.g.h"
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public ref class Scenario1 sealed
00026     {
00027     public:
00028         Scenario1();
00029
00030     private:
00031         void Find_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00032     };
00033 }
Generated on Fri Nov 15 2024 22:21:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirectServices/cpp/pch.cpp Source File

  • WiFiDirectServices
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Include the standard header and generate the precompiled header.
00014 //
00015
00016 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProximitySensor/cs/Scenario2_Polling.xaml.cs Source File

  • ProximitySensor
  • cs

Scenario2_Polling.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using Windows.Devices.Enumeration;
00015 using Windows.Devices.Sensors;
00016 using Windows.Foundation;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace ProximityCS
00023 {
00024     public sealed partial class Scenario2_Polling : Page
00025     {
00026         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00027         // as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         private ProximitySensor sensor;
00031         private DeviceWatcher watcher;
00032
00033         public Scenario2_Polling()
00034         {
00035             this.InitializeComponent();
00036
00037             watcher = DeviceInformation.CreateWatcher(ProximitySensor.GetDeviceSelector());
00038             watcher.Added += OnProximitySensorAdded;
00039             watcher.Start();
00040         }
00041
00042         /// <summary>
00043         /// Invoked when the device watcher finds a proximity sensor
00044         /// </summary>
00045         /// <param name="sender">The device watcher</param>
00046         /// <param name="device">Device information for the proximity sensor that was found</param>
00047         private async void OnProximitySensorAdded(DeviceWatcher sender, DeviceInformation device)
00048         {
00049             if (null == sensor)
00050             {
00051                 ProximitySensor foundSensor = ProximitySensor.FromId(device.Id);
00052                 if (null != foundSensor)
00053                 {
00054                     // Optionally check the ProximitySensor.MaxDistanceInCentimeters/MinDistanceInCentimeters
00055                     // properties here. Refer to Scenario 1 for details.
00056                     sensor = foundSensor;
00057                 }
00058                 else
00059                 {
00060                     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00061                     {
00062                         rootPage.NotifyUser("Could not get a proximity sensor from the device id", NotifyType.ErrorMessage);
00063                     });
00064                 }
00065             }
00066         }
00067
00068         /// <summary>
00069         /// This is the click handler for the 'GetData' button.
00070         /// </summary>
00071         /// <param name="sender"></param>
00072         /// <param name="e"></param>
00073         private void ScenarioGetData(object sender, RoutedEventArgs e)
00074         {
00075             if (null != sensor)
00076             {
00077                 ProximitySensorReading reading = sensor.GetCurrentReading();
00078                 if (null != reading)
00079                 {
00080                     ScenarioOutput_DetectionState.Text = reading.IsDetected ? "Detected" : "Not detected";
00081                     ScenarioOutput_Timestamp.Text = reading.Timestamp.ToString("u");
00082
00083                     // Show the detection distance, if available
00084                     if (null != reading.DistanceInMillimeters)
00085                     {
00086                         ScenarioOutput_DetectionDistance.Text = reading.DistanceInMillimeters.ToString();
00087                     }
00088                 }
00089             }
00090             else
00091             {
00092                 rootPage.NotifyUser("No proximity sensor found", NotifyType.ErrorMessage);
00093             }
00094         }
00095     }
00096 }
Generated on Fri Nov 15 2024 22:17:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampArray/cppwinrt/Project.idl Source File

  • LampArray
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_Basics : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_Basics();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_Effects : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_Effects();
00024     }
00025 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JapanesePhoneticAnalysis/cpp/Scenario1_Analyze.xaml.cpp Source File

  • JapanesePhoneticAnalysis
  • cpp

Scenario1_Analyze.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "MainPage.xaml.h"
00013 #include "Scenario1_Analyze.xaml.h"
00014
00015 using namespace Platform;
00016 using namespace SDKTemplate;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::Globalization;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Primitives;
00023 using namespace Windows::UI::Xaml::Data;
00024 using namespace Windows::UI::Xaml::Input;
00025 using namespace Windows::UI::Xaml::Media;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 Scenario1_Analyze::Scenario1_Analyze()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 void Scenario1_Analyze::AnalyzeButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00034 {
00035     String^ input = InputTextBox->Text;
00036     String^ output = L"";
00037
00038     // monoRuby = false means that each element in the result corresponds to a single Japanese word.
00039     // monoRuby = true means that each element in the result corresponds to one or more characters which are pronounced as a single unit.
00040     bool monoRuby = MonoRubyRadioButton->IsChecked->Value;
00041
00042     // Analyze the Japanese text according to the specified algorithm.
00043     // The maximum length of the input string is 100 characters.
00044     IVectorView<JapanesePhoneme^>^ words = JapanesePhoneticAnalyzer::GetWords(input, monoRuby);
00045     for (JapanesePhoneme^ word : words)
00046     {
00047         // Put each phrase on its own line.
00048         if (output->Length() != 0 && word->IsPhraseStart)
00049         {
00050             output += L"\r\n";
00051         }
00052         // DisplayText is the display text of the word, which has same characters as the input of GetWords().
00053         // YomiText is the reading text of the word, as known as Yomi, which typically consists of Hiragana characters.
00054         // However, please note that the reading can contains some non-Hiragana characters for some display texts such as emoticons or symbols.
00055         output += word->DisplayText + L"(" + word->YomiText + L")";
00056     }
00057
00058     // Display the result.
00059     OutputTextBlock->Text = output;
00060     if (input != L"" && output == L"")
00061     {
00062         // If the result from GetWords() is empty but the input is not empty,
00063         // it means the given input is too long to analyze.
00064         MainPage::Current->NotifyUser("Failed to get words from the input text.  The input text is too long to analyze.", NotifyType::ErrorMessage);
00065     }
00066     else
00067     {
00068         // Otherwise, the analysis has been done successfully.
00069         MainPage::Current->NotifyUser("Got words from the input text successfully.", NotifyType::StatusMessage);
00070     }
00071 }
Generated on Fri Nov 15 2024 22:20:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SemanticTextQuery/cpp/GetMatchingPropertiesWithRanges.xaml.cpp Source File

  • SemanticTextQuery
  • cpp

GetMatchingPropertiesWithRanges.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 //
00008 // Scenario3.xaml.cpp
00009 // Implementation of the Scenario3 class
00010 //
00011
00012 #include "pch.h"
00013 #include <ppltasks.h>
00014 #include "GetMatchingPropertiesWithRanges.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace SDKTemplate;
00018 using namespace concurrency;
00019 using namespace Platform;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Storage;
00023 using namespace Windows::Storage::FileProperties;
00024 using namespace Windows::Storage::Search;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Documents;
00028
00029 Scenario3::Scenario3()
00030 {
00031     InitializeComponent();
00032     FindQueryText->Text = "a AND datemodified:>2/1/2013";
00033 }
00034
00035 void Scenario3::Find_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00036 {
00037     ContentTextOutput->Text = "";
00038     if (FindQueryText->Text == "")
00039     {
00040         return;
00041     }
00042
00043     auto propertyNames = ref new Platform::Collections::Vector<String^>();
00044     propertyNames->Append("System.FileName");
00045
00046     auto queryOptions = ref new QueryOptions();
00047     queryOptions->IndexerOption = IndexerOption::OnlyUseIndexer;
00048     queryOptions->UserSearchFilter = FindQueryText->Text;
00049     queryOptions->SetPropertyPrefetch(Windows::Storage::FileProperties::PropertyPrefetchOptions::DocumentProperties, propertyNames);
00050     // Query the Pictures library.
00051     create_task(KnownFolders::GetFolderForUserAsync(nullptr /* current user */, KnownFolderId::PicturesLibrary))
00052         .then([this, queryOptions](StorageFolder^ picturesLibrary)
00053     {
00054         StorageFileQueryResult^ queryResult = picturesLibrary->CreateFileQueryWithOptions(queryOptions);
00055         return create_task(queryResult->GetFilesAsync(0, 20)) // Get at most 20 files.
00056             .then([this, queryResult](IVectorView<StorageFile^>^ files)
00057         {
00058             std::for_each(begin(files), end(files), [this, queryResult](StorageFile^ file)
00059             {
00060                 IMap<String^, IVectorView<Windows::Data::Text::TextSegment>^>^ fileRangeProperties = queryResult->GetMatchingPropertiesWithRanges(file);
00061                 if (fileRangeProperties->HasKey("System.FileName"))
00062                 {
00063                     IVectorView<Windows::Data::Text::TextSegment>^ ranges = fileRangeProperties->Lookup("System.FileName");
00064                     HighlightRanges(ContentTextOutput, file->DisplayName, ranges);
00065                 }
00066                 // Note: You can continue looking for other properties you would like to highlight on the file here.
00067             });
00068             if (files->Size == 0)
00069             {
00070                 ContentTextOutput->Text = "There were no matching files in your Pictures Library";
00071             }
00072         });
00073     });
00074 }
00075
Generated on Fri Nov 15 2024 22:21:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2 Member List

This is the complete list of members for Scenario2, including all inherited members.
Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2 | [inline, private]
Scenario2() | Scenario2 | [inline]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AppServices/cppwinrt/RandomNumberService/pch.cpp Source File

  • AppServices
  • cppwinrt
  • RandomNumberService

pch.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/ComputeShader/pch.h Source File

  • D2DCustomEffects
  • cpp
  • ComputeShader

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <wrl.h>
00015 #include <wrl/client.h>
00016 #include <memory>
00017 #include <agile.h>
00018 #include <concrt.h>
00019
00020 #include <d3d11_3.h>
00021 #include <d2d1_3.h>
00022 #include <d2d1effects_2.h>
00023 #include <dwrite_3.h>
00024 #include <wincodec.h>
00025 #include <DirectXMath.h>
00026
00027 #include <d2d1effectauthor_1.h>
00028 #include <d2d1effecthelpers.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Face.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Face.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Face.h"
00014
00015 using namespace DirectX;
00016
00017 Face::Face()
00018 {
00019     SetPlane(
00020         XMFLOAT3(0.0f, 0.0f, 0.0f),
00021         XMFLOAT3(1.0f, 0.0f, 0.0f),
00022         XMFLOAT3(0.0f, 1.0f, 0.0f)
00023         );
00024 }
00025
00026 Face::Face(
00027     XMFLOAT3 origin,
00028     XMFLOAT3 p1,
00029     XMFLOAT3 p2
00030     )
00031 {
00032     SetPlane(origin, p1, p2);
00033 }
00034
00035 void Face::SetPlane(
00036     XMFLOAT3 origin,
00037     XMFLOAT3 p1,
00038     XMFLOAT3 p2
00039     )
00040 {
00041     m_position = origin;
00042     XMStoreFloat3(&m_widthVector, XMLoadFloat3(&p1) - XMLoadFloat3(&origin));
00043     XMStoreFloat3(&m_heightVector, XMLoadFloat3(&p2) - XMLoadFloat3(&origin));
00044
00045     m_point[0] = m_position;
00046     m_point[1] = p1;
00047     m_point[3] = p2;
00048     XMStoreFloat3(&m_point[2], XMLoadFloat3(&p1) + XMLoadFloat3(&m_heightVector));
00049
00050     XMStoreFloat(&m_width, XMVector3Length(XMLoadFloat3(&m_widthVector)));
00051     XMStoreFloat(&m_height, XMVector3Length(XMLoadFloat3(&m_heightVector)));
00052
00053     XMStoreFloat3(
00054         &m_normal,
00055         XMVector3Normalize(
00056             XMVector3Cross(
00057                 XMLoadFloat3(&m_widthVector),
00058                 XMLoadFloat3(&m_heightVector)
00059                 )
00060             )
00061         );
00062     UpdateMatrix();
00063 }
00064
00065 void Face::UpdatePosition()
00066 {
00067     m_point[0] = m_position;
00068     XMStoreFloat3(&m_point[1], XMLoadFloat3(&m_position) + XMLoadFloat3(&m_widthVector));
00069     XMStoreFloat3(&m_point[3], XMLoadFloat3(&m_position) + XMLoadFloat3(&m_heightVector));
00070     XMStoreFloat3(&m_point[2], XMLoadFloat3(&m_point[1]) + XMLoadFloat3(&m_heightVector));
00071
00072     XMStoreFloat4x4(
00073         &m_modelMatrix,
00074         XMMatrixScaling(m_width, m_height, 1.0f) *
00075         XMLoadFloat4x4(&m_rotationMatrix) *
00076         XMMatrixTranslation(m_position.x, m_position.y, m_position.z)
00077         );
00078 }
00079
00080 bool Face::IsTouching(
00081     XMFLOAT3 point,
00082     float radius,
00083     _Out_ XMFLOAT3* contact,
00084     _Out_ XMFLOAT3* normal
00085     )
00086 {
00087     float dist;
00088
00089     // Determine if a point is within radius distance of the face and
00090     // return the point of contact (projection of the point onto the face).
00091
00092     XMStoreFloat(
00093         &dist,
00094         XMVector3Dot(
00095             XMLoadFloat3(&m_normal),
00096             XMLoadFloat3(&point) - XMLoadFloat3(&m_position)
00097             )
00098         );
00099
00100     // Determine the point of contact by projecting the point along the Normal
00101     // vector the distance the point is from the plane.
00102     XMStoreFloat3(contact, XMLoadFloat3(&point) - (XMLoadFloat3(&m_normal) * dist));
00103     normal->x = m_normal.x;
00104     normal->y = m_normal.y;
00105     normal->z = m_normal.z;
00106
00107     if (dist < 0.0f)
00108     {
00109         dist *= -1.0f;
00110         normal->x = -m_normal.x;
00111         normal->y = -m_normal.y;
00112         normal->z = -m_normal.z;
00113     }
00114     else
00115     {
00116         normal->x = m_normal.x;
00117         normal->y = m_normal.y;
00118         normal->z = m_normal.z;
00119     }
00120
00121     if (dist < radius)
00122     {
00123         // point is within radius of the plane
00124         //
00125         // Determine if the point of contact is inside the parallelogram of the target.
00126         // This is true if distance from each of the parallel lines defining the half
00127         // spaces is less than the distance between the parallel lines for both sets of
00128         // parallel lines.
00129         // To catch the cases where the contact point is just outside the parallelogram
00130         // but less than the radius we extend the parallelogram to accept points that are
00131         // the distance between the parallel lines plus the radius.
00132         //
00133
00134         float dist1, dist2, dist3, dist4;
00135
00136         XMStoreFloat(
00137             &dist1,
00138             XMVector3LinePointDistance(
00139                 XMLoadFloat3(&m_point[0]),
00140                 XMLoadFloat3(&m_point[1]),
00141                 XMLoadFloat3(contact)
00142                 )
00143             );
00144         XMStoreFloat(
00145             &dist2,
00146             XMVector3LinePointDistance(
00147                 XMLoadFloat3(&m_point[3]),
00148                 XMLoadFloat3(&m_point[2]),
00149                 XMLoadFloat3(contact)
00150                 )
00151             );
00152         XMStoreFloat(
00153             &dist3,
00154             XMVector3LinePointDistance(
00155                 XMLoadFloat3(&m_point[0]),
00156                 XMLoadFloat3(&m_point[3]),
00157                 XMLoadFloat3(contact)
00158                 )
00159             );
00160         XMStoreFloat(
00161             &dist4,
00162             XMVector3LinePointDistance(
00163                 XMLoadFloat3(&m_point[1]),
00164                 XMLoadFloat3(&m_point[2]),
00165                 XMLoadFloat3(contact)
00166                 )
00167             );
00168
00169         if (dist1 < (m_height + radius) &&
00170             dist2 < (m_height + radius) &&
00171             dist3 < (m_width + radius) &&
00172             dist4 < (m_width + radius))
00173         {
00174             return true;
00175         }
00176         else
00177         {
00178             return false;
00179         }
00180     }
00181     return false;
00182 }
00183
00184 void Face::UpdateMatrix()
00185 {
00186     // Determine the Model transform for the cannonical face to align with the position
00187     // and orientation of the defined face. The cannonical face geometry is
00188     // a rectangle at the origin extending 1 unit in the +X and 1 unit in the +Y direction.
00189
00190     XMVECTOR w = XMVectorSet(1.0f, 0.0f, 0.0f, 1.0f);
00191     XMVECTOR h = XMVectorSet(0.0f, 1.0f, 0.0f, 1.0f);
00192     XMVECTOR epsilon = XMVectorReplicate(0.0001f);
00193     XMVECTOR width = XMVectorScale(XMLoadFloat3(&m_widthVector), 1.0f / m_width);
00194     XMVECTOR height = XMVectorScale(XMLoadFloat3(&m_heightVector), 1.0f / m_height);
00195     XMMATRIX mat1 = XMMatrixIdentity();
00196     XMMATRIX mat2 = XMMatrixIdentity();
00197
00198     // Determine the necessary rotation to align the widthVector with the +X axis.
00199     // Then apply the rotation to the cannonical H vector (+Y).
00200     if (!XMVector3NearEqual(w, width, epsilon))
00201     {
00202         float angle1 = XMVectorGetX(
00203             XMVector3AngleBetweenVectors(w, width)
00204             );
00205
00206         if (XMVector3NearEqual(w, XMVectorNegate(width), epsilon))
00207         {
00208             // The angle between w and width is ~180 degrees, so
00209             // pick a axis of rotation perpendicular to the W vector.
00210             mat1 = XMMatrixRotationAxis(XMVector3Orthogonal(w), angle1);
00211             h = XMVector3TransformCoord(h, mat1);
00212         }
00213         else if ((angle1 * angle1) > 0.025)
00214         {
00215             // Take the cross product between the w and width vectors to
00216             // determine the axis to rotate that is perpendicular to both vectors.
00217             XMVECTOR axis1 = XMVector3Cross(w, width);
00218             mat1 = XMMatrixRotationAxis(axis1, angle1);
00219             h = XMVector3TransformCoord(h, mat1);
00220         }
00221     }
00222
00223     // Determine the necessary rotation to align the transformed heightVector
00224     // with the transformed H vector.
00225     if (!XMVector3NearEqual(h, height, epsilon))
00226     {
00227         float angle2 = XMVectorGetX(
00228             XMVector3AngleBetweenVectors(h, height)
00229             );
00230
00231         if (XMVector3NearEqual(h, XMVectorNegate(height), epsilon))
00232         {
00233             // The angle between the h' and height vectors is ~180 degrees,
00234             // so rotate around the width vector to keep it aligned in the right
00235             // place.
00236             mat2 = XMMatrixRotationAxis(width, angle2);
00237         }
00238         else if ((angle2 * angle2) > 0.025)
00239         {
00240             // Take the cross product between the h' and height vectors
00241             // to determine the axis to rotate that is perpendicular to both vectors.
00242             XMVECTOR axis2 = XMVector3Cross(h, height);
00243             mat2 = XMMatrixRotationAxis(axis2, angle2);
00244         }
00245     }
00246     XMStoreFloat4x4(&m_rotationMatrix, mat1 * mat2);
00247
00248     // Generate the composite matrix to scale, rotate and translate to cannonical
00249     // face geometry to be positioned correctly in world space.
00250     XMStoreFloat4x4(
00251         &m_modelMatrix,
00252         XMMatrixScaling(m_width, m_height, 1.0f) *
00253         mat1 *
00254         mat2 *
00255         XMMatrixTranslation(m_position.x, m_position.y, m_position.z)
00256         );
00257 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SemanticTextQuery/cs/GetMatchingPropertiesWithRanges.xaml.cs Source File

  • SemanticTextQuery
  • cs

GetMatchingPropertiesWithRanges.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System.Collections.Generic;
00013 using Windows.Foundation;
00014 using Windows.Storage;
00015 using Windows.Storage.Search;
00016 using Windows.UI.Text;
00017 using Windows.UI.Xaml.Documents;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021 using System;
00022
00023 namespace SDKTemplate
00024 {
00025     /// <summary>
00026     /// An empty page that can be used on its own or navigated to within a Frame.
00027     /// </summary>
00028     public sealed partial class Scenario3
00029     {
00030         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00031         // as NotifyUser()
00032         MainPage rootPage = MainPage.Current;
00033
00034         public Scenario3()
00035         {
00036             this.InitializeComponent();
00037         }
00038
00039         /// <summary>
00040         /// Invoked when this page is about to be displayed in a Frame.
00041         /// </summary>
00042         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00043         /// property is typically used to configure the page.</param>
00044         protected override void OnNavigatedTo(NavigationEventArgs e)
00045         {
00046             FindQueryText.Text = "a AND datemodified:>2/1/2013";
00047         }
00048
00049         private async void Find_Click(object sender, RoutedEventArgs e)
00050         {
00051             ContentTextOutput.Text = "";
00052             if (FindQueryText.Text == "")
00053             {
00054                 return;
00055             }
00056
00057             List<string> propertyNames = new List<string>();
00058             propertyNames.Add("System.FileName");
00059             var queryOptions = new Windows.Storage.Search.QueryOptions();
00060             queryOptions.IndexerOption = Windows.Storage.Search.IndexerOption.OnlyUseIndexer;
00061             queryOptions.UserSearchFilter = FindQueryText.Text;
00062             queryOptions.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.DocumentProperties, propertyNames);
00063
00064             // Query the Pictures library.
00065             StorageFolder picturesLibrary = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
00066             StorageFileQueryResult queryResult = picturesLibrary.CreateFileQueryWithOptions(queryOptions);
00067             IReadOnlyList<StorageFile> files = await queryResult.GetFilesAsync(0, 20); // limit to 20 results
00068             foreach (StorageFile file in files)
00069             {
00070                 IDictionary<String, IReadOnlyList<Windows.Data.Text.TextSegment>> fileRangeProperties = queryResult.GetMatchingPropertiesWithRanges(file);
00071                 if (fileRangeProperties.ContainsKey("System.FileName"))
00072                 {
00073                     IReadOnlyList<Windows.Data.Text.TextSegment> ranges;
00074                     fileRangeProperties.TryGetValue("System.FileName", out ranges);
00075                     rootPage.HighlightRanges(ContentTextOutput, file.DisplayName, ranges);
00076                 }
00077                 // Note: You can continue looking for other properties you would like to highlight on the file here.
00078             }
00079             if (files.Count == 0)
00080             {
00081                 ContentTextOutput.Text = "There were no matching files in your Pictures Library";
00082             }
00083         }
00084     }
00085 }
Generated on Fri Nov 15 2024 22:21:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cppwinrt/SampleConfiguration.cpp Source File

  • FileThumbnails
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016 #include <sstream>
00017
00018 using namespace winrt;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Storage;
00022 using namespace Windows::Storage::FileProperties;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Media::Imaging;
00025 using namespace SDKTemplate;
00026
00027 hstring implementation::MainPage::FEATURE_NAME()
00028 {
00029     return L"File thumbnails C++/WinRT sample";
00030 }
00031
00032 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00033 {
00034     Scenario{ L"Display a thumbnail for a picture",    xaml_typename<SDKTemplate::Scenario1>() },
00035     Scenario{ L"Display album art for a song",         xaml_typename<SDKTemplate::Scenario2>() },
00036     Scenario{ L"Display an icon for a document",       xaml_typename<SDKTemplate::Scenario3>() },
00037     Scenario{ L"Display a thumbnail for a folder",     xaml_typename<SDKTemplate::Scenario4>() },
00038     Scenario{ L"Display a thumbnail for a file group", xaml_typename<SDKTemplate::Scenario5>() },
00039     Scenario{ L"Display a scaled image",               xaml_typename<SDKTemplate::Scenario6>() },
00040 });
00041
00042 hstring winrt::to_hstring(ThumbnailMode thumbnailMode)
00043 {
00044     switch (thumbnailMode)
00045     {
00046     case ThumbnailMode::PicturesView: return L"PicturesView";
00047     case ThumbnailMode::VideosView: return L"VideosView";
00048     case ThumbnailMode::MusicView: return L"MusicView";
00049     case ThumbnailMode::DocumentsView: return L"DocumentsView";
00050     case ThumbnailMode::ListView: return L"ListView";
00051     case ThumbnailMode::SingleItem: return L"SingleItem";
00052     default: return L"Unknown " + to_hstring((uint32_t)thumbnailMode);
00053     }
00054 }
00055
00056 std::vector<hstring> const& FileExtensions::Document()
00057 {
00058     static std::vector<hstring> document{ L".doc", L".xls", L".ppt", L".docx", L".xlsx", L".pptx", L".pdf", L".txt", L".rtf" };
00059     return document;
00060 }
00061
00062 std::vector<hstring> const& FileExtensions::Image()
00063 {
00064     static std::vector<hstring> image{ L".jpg", L".png", L".bmp", L".gif", L".tif" };
00065     return image;
00066 }
00067
00068 std::vector<hstring> const& FileExtensions::Music()
00069 {
00070     static std::vector<hstring> music{ L".mp3", L".wma", L".m4a", L".aac" };
00071     return music;
00072 }
00073
00074 BitmapImage Helpers::PlaceholderImage()
00075 {
00076     static BitmapImage placeholder{ Uri{ L"ms-appx:///Assets/placeholder-sdk.png" } };
00077     return placeholder;
00078 }
00079
00080 void Helpers::DisplayResult(Image const& image, TextBlock const& textBlock,
00081     ThumbnailMode thumbnailMode, uint32_t size, IStorageItem const& item,
00082     StorageItemThumbnail const& thumbnail, bool isGroup)
00083 {
00084     BitmapImage bitmapImage;
00085     bitmapImage.SetSource(thumbnail);
00086     image.Source(bitmapImage);
00087
00088     std::wstringstream text;
00089     text << L"ThumbnailMode." << std::wstring_view{ to_hstring(thumbnailMode) } << std::endl;
00090     text << (isGroup ? L"Group" : item.IsOfType(StorageItemTypes::File) ? L"File" : L"Folder")
00091         << L" used: " << std::wstring_view{ item.Name() } << std::endl;
00092     text << L"Requested size: " << size << std::endl;
00093     text << L"Returned size: " << thumbnail.OriginalWidth() << L"x" << thumbnail.OriginalHeight() << std::endl;
00094     textBlock.Text(text.str());
00095 }
00096
00097 void Helpers::ResetOutput(MainPage const& rootPage, Image const& image, TextBlock const& output, TextBlock const& outputDetails)
00098 {
00099     image.Source(PlaceholderImage());
00100     rootPage.NotifyUser(L"", NotifyType::StatusMessage);
00101     output.Text(L"");
00102     if (outputDetails)
00103     {
00104         outputDetails.Text(L"");
00105     }
00106 }
00107
Generated on Fri Nov 15 2024 22:17:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Content/SpinningCubeRenderer.cpp Source File

  • HolographicFaceTracking
  • cpp
  • Content

SpinningCubeRenderer.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SpinningCubeRenderer.h"
00014 #include "Common\DirectXHelper.h"
00015
00016 using namespace HolographicFaceTracker;
00017 using namespace Concurrency;
00018 using namespace DirectX;
00019 using namespace Windows::Foundation::Numerics;
00020
00021 // Loads vertex and pixel shaders from files and instantiates the cube geometry.
00022 SpinningCubeRenderer::SpinningCubeRenderer(std::shared_ptr<DX::DeviceResources> deviceResources) :
00023     DX::Resource(std::move(deviceResources))
00024 {
00025 }
00026
00027 // Called once per frame. Rotates the cube, and calculates and sets the model matrix
00028 // relative to the position transform indicated by hologramPositionTransform.
00029 void SpinningCubeRenderer::Update(const DX::StepTimer& timer)
00030 {
00031     float const deltaTime = static_cast<float>(timer.GetElapsedSeconds());
00032     float const lerpDeltaTime = deltaTime * c_lerpRate;
00033
00034     float3 const prevPosition = m_position;
00035     m_position = lerp(m_position, m_targetPosition, lerpDeltaTime);
00036
00037     m_velocity = (prevPosition - m_position) / deltaTime;
00038
00039     // Rotate the cube.
00040     // Convert degrees to radians, then convert seconds to rotation angle.
00041     float const radiansPerSecond = XMConvertToRadians(m_degreesPerSecond);
00042     float const totalRotation    = static_cast<float>(timer.GetTotalSeconds()) * radiansPerSecond;
00043
00044     // Scale the cube down to 10cm
00045     float4x4 const modelScale = make_float4x4_scale({ 0.1f });
00046     float4x4 const modelRotation = make_float4x4_rotation_y(totalRotation);
00047     float4x4 const modelTranslation = make_float4x4_translation(m_position);
00048
00049     m_modelConstantBufferData.model = modelScale * modelRotation * modelTranslation;
00050
00051     // Use the D3D device context to update Direct3D device-based resources.
00052     const auto context = m_deviceResources->GetD3DDeviceContext();
00053
00054     // Update the model transform buffer for the hologram.
00055     context->UpdateSubresource(
00056         m_modelConstantBuffer.Get(),
00057         0,
00058         nullptr,
00059         &m_modelConstantBufferData,
00060         0,
00061         0
00062         );
00063 }
00064
00065 // Renders one frame using the vertex and pixel shaders.
00066 // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00067 // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00068 // a pass-through geometry shader is also used to set the render
00069 // target array index.
00070 void SpinningCubeRenderer::Render()
00071 {
00072     const auto context = m_deviceResources->GetD3DDeviceContext();
00073
00074     // Each vertex is one instance of the VertexPositionColor struct.
00075     const UINT stride = sizeof(VertexPositionColor);
00076     const UINT offset = 0;
00077     context->IASetVertexBuffers(
00078         0,
00079         1,
00080         m_vertexBuffer.GetAddressOf(),
00081         &stride,
00082         &offset
00083         );
00084     context->IASetIndexBuffer(
00085         m_indexBuffer.Get(),
00086         DXGI_FORMAT_R16_UINT, // Each index is one 16-bit unsigned integer (short).
00087         0
00088         );
00089     context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00090     context->IASetInputLayout(m_inputLayout.Get());
00091
00092     // Attach the vertex shader.
00093     context->VSSetShader(
00094         m_vertexShader.Get(),
00095         nullptr,
00096         0
00097         );
00098     // Apply the model constant buffer to the vertex shader.
00099     context->VSSetConstantBuffers(
00100         0,
00101         1,
00102         m_modelConstantBuffer.GetAddressOf()
00103         );
00104
00105     if (!m_usingVprtShaders)
00106     {
00107         // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00108         // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00109         // a pass-through geometry shader is used to set the render target
00110         // array index.
00111         context->GSSetShader(
00112             m_geometryShader.Get(),
00113             nullptr,
00114             0
00115             );
00116     }
00117
00118     // Attach the pixel shader.
00119     context->PSSetShader(
00120         m_pixelShader.Get(),
00121         nullptr,
00122         0
00123         );
00124
00125     // Draw the objects.
00126     context->DrawIndexedInstanced(
00127         m_indexCount,   // Index count per instance.
00128         2,              // Instance count.
00129         0,              // Start index location.
00130         0,              // Base vertex location.
00131         0               // Start instance location.
00132         );
00133 }
00134
00135 task<void> SpinningCubeRenderer::CreateDeviceDependentResourcesAsync()
00136 {
00137     m_usingVprtShaders = m_deviceResources->GetDeviceSupportsVprt();
00138
00139     // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3::
00140     // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature
00141     // we can avoid using a pass-through geometry shader to set the render
00142     // target array index, thus avoiding any overhead that would be
00143     // incurred by setting the geometry shader stage.
00144     std::wstring vertexShaderFileName = m_usingVprtShaders ? L"ms-appx:///CubeVPRTVertexShader.cso" : L"ms-appx:///CubeVertexShader.cso";
00145
00146     // Load shaders asynchronously.
00147     task<std::vector<byte>> loadVSTask = DX::ReadDataAsync(vertexShaderFileName);
00148     task<std::vector<byte>> loadPSTask = DX::ReadDataAsync(L"ms-appx:///CubePixelShader.cso");
00149
00150     task<std::vector<byte>> loadGSTask;
00151     if (!m_usingVprtShaders)
00152     {
00153         // Load the pass-through geometry shader.
00154         loadGSTask = DX::ReadDataAsync(L"ms-appx:///CubeGeometryShader.cso");
00155     }
00156
00157     // After the vertex shader file is loaded, create the shader and input layout.
00158     task<void> createVSTask = loadVSTask.then([this] (const std::vector<byte>& fileData)
00159     {
00160         DX::ThrowIfFailed(
00161             m_deviceResources->GetD3DDevice()->CreateVertexShader(
00162                 fileData.data(),
00163                 fileData.size(),
00164                 nullptr,
00165                 &m_vertexShader
00166                 )
00167             );
00168
00169         constexpr std::array<D3D11_INPUT_ELEMENT_DESC, 2> vertexDesc = {{
00170             { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(VertexPositionColor, pos),   D3D11_INPUT_PER_VERTEX_DATA, 0 },
00171             { "COLOR",    0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(VertexPositionColor, color), D3D11_INPUT_PER_VERTEX_DATA, 0 },
00172         }};
00173
00174         DX::ThrowIfFailed(
00175             m_deviceResources->GetD3DDevice()->CreateInputLayout(
00176                 vertexDesc.data(),
00177                 vertexDesc.size(),
00178                 fileData.data(),
00179                 fileData.size(),
00180                 &m_inputLayout
00181                 )
00182             );
00183     });
00184
00185     // After the pixel shader file is loaded, create the shader and constant buffer.
00186     task<void> createPSTask = loadPSTask.then([this] (const std::vector<byte>& fileData)
00187     {
00188         DX::ThrowIfFailed(
00189             m_deviceResources->GetD3DDevice()->CreatePixelShader(
00190                 fileData.data(),
00191                 fileData.size(),
00192                 nullptr,
00193                 &m_pixelShader
00194                 )
00195             );
00196
00197         const CD3D11_BUFFER_DESC constantBufferDesc(sizeof(CubeModelConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00198         DX::ThrowIfFailed(
00199             m_deviceResources->GetD3DDevice()->CreateBuffer(
00200                 &constantBufferDesc,
00201                 nullptr,
00202                 &m_modelConstantBuffer
00203                 )
00204             );
00205     });
00206
00207     task<void> createGSTask;
00208     if (!m_usingVprtShaders)
00209     {
00210         // After the pass-through geometry shader file is loaded, create the shader.
00211         createGSTask = loadGSTask.then([this] (const std::vector<byte>& fileData)
00212         {
00213             DX::ThrowIfFailed(
00214                 m_deviceResources->GetD3DDevice()->CreateGeometryShader(
00215                     &fileData[0],
00216                     fileData.size(),
00217                     nullptr,
00218                     &m_geometryShader
00219                     )
00220                 );
00221         });
00222     }
00223
00224     // Once all shaders are loaded, create the mesh.
00225     task<void> shaderTaskGroup = m_usingVprtShaders ? (createPSTask && createVSTask) : (createPSTask && createVSTask && createGSTask);
00226     task<void> finalLoadingTask  = shaderTaskGroup.then([this] ()
00227     {
00228         static const std::array<VertexPositionColor, 8> cubeVertices =
00229         {{
00230             { float3(-0.5f, -0.5f, -0.5f), float3(0.0f, 0.0f, 0.0f) },
00231             { float3(-0.5f, -0.5f,  0.5f), float3(0.0f, 0.0f, 1.0f) },
00232             { float3(-0.5f,  0.5f, -0.5f), float3(0.0f, 1.0f, 0.0f) },
00233             { float3(-0.5f,  0.5f,  0.5f), float3(0.0f, 1.0f, 1.0f) },
00234             { float3( 0.5f, -0.5f, -0.5f), float3(1.0f, 0.0f, 0.0f) },
00235             { float3( 0.5f, -0.5f,  0.5f), float3(1.0f, 0.0f, 1.0f) },
00236             { float3( 0.5f,  0.5f, -0.5f), float3(1.0f, 1.0f, 0.0f) },
00237             { float3( 0.5f,  0.5f,  0.5f), float3(1.0f, 1.0f, 1.0f) },
00238         }};
00239
00240         D3D11_SUBRESOURCE_DATA vertexBufferData = {0};
00241         vertexBufferData.pSysMem = cubeVertices.data();
00242         vertexBufferData.SysMemPitch = 0;
00243         vertexBufferData.SysMemSlicePitch = 0;
00244         const CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(cubeVertices), D3D11_BIND_VERTEX_BUFFER);
00245         DX::ThrowIfFailed(
00246             m_deviceResources->GetD3DDevice()->CreateBuffer(
00247                 &vertexBufferDesc,
00248                 &vertexBufferData,
00249                 &m_vertexBuffer
00250                 )
00251             );
00252
00253         constexpr std::array<uint16_t, 36> cubeIndices =
00254         {{
00255             2,1,0, // -x
00256             2,3,1,
00257
00258             6,4,5, // +x
00259             6,5,7,
00260
00261             0,1,5, // -y
00262             0,5,4,
00263
00264             2,6,7, // +y
00265             2,7,3,
00266
00267             0,4,6, // -z
00268             0,6,2,
00269
00270             1,3,7, // +z
00271             1,7,5,
00272         }};
00273
00274         m_indexCount = cubeIndices.size();
00275
00276         D3D11_SUBRESOURCE_DATA indexBufferData = {0};
00277         indexBufferData.pSysMem          = cubeIndices.data();
00278         indexBufferData.SysMemPitch      = 0;
00279         indexBufferData.SysMemSlicePitch = 0;
00280         const CD3D11_BUFFER_DESC indexBufferDesc(sizeof(cubeIndices), D3D11_BIND_INDEX_BUFFER);
00281         DX::ThrowIfFailed(
00282             m_deviceResources->GetD3DDevice()->CreateBuffer(
00283                 &indexBufferDesc,
00284                 &indexBufferData,
00285                 &m_indexBuffer
00286                 )
00287             );
00288     });
00289
00290     return finalLoadingTask;
00291 }
00292
00293 void SpinningCubeRenderer::ReleaseDeviceDependentResources()
00294 {
00295     m_usingVprtShaders = false;
00296
00297     m_vertexShader.Reset();
00298     m_inputLayout.Reset();
00299     m_pixelShader.Reset();
00300     m_geometryShader.Reset();
00301     m_modelConstantBuffer.Reset();
00302     m_vertexBuffer.Reset();
00303     m_indexBuffer.Reset();
00304 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Text Member List

This is the complete list of members for Text, including all inherited members.
AddChildElement(const std::shared_ptr< BaseElement > &childElement) | BaseElement |
ArrangeElements() | BaseElement | [virtual]
BaseElement() | BaseElement |
CreateTextContext() | Text | [private]
GetElementMargin() | BaseElement | [inline]
GetElementSize() | BaseElement | [inline]
GetIgnoreLayout() | BaseElement | [inline]
GetIsRenderPassNeeded() | BaseElement | [inline]
GetIsVisible() | BaseElement | [inline]
Initialize() | BaseElement | [virtual]
m_deviceResources | BaseElement | [protected]
m_elementMargin | BaseElement | [protected]
m_elementSize | BaseElement | [protected]
m_fontWeight | Text | [private]
m_ignoreLayout | BaseElement | [protected]
m_isInitialized | BaseElement | [protected]
m_isLayoutHorizontal | BaseElement | [protected]
m_isRenderPassNeeded | BaseElement | [protected]
m_isVisible | BaseElement | [protected]
m_parentTranslation | BaseElement | [protected]
m_text | Text | [private]
m_textFormat | Text | [private]
m_textLayout | Text | [private]
m_transformedFontSize | Text | [private]
m_transformedTranslation | BaseElement | [protected]
m_transformMatrix | BaseElement | [protected]
m_transformRecalculationNeeded | BaseElement | [protected]
m_translation | BaseElement | [protected]
Render() override | Text | [protected, virtual]
SetBrush(ID2D1SolidColorBrush *brush) | BaseElement |
SetElementMargin(ElementMargin margin) | BaseElement | [inline]
SetElementSize(Windows::Foundation::Numerics::float2 size) | BaseElement | [inline]
SetIgnoreLayout(bool ignoreLayout) | BaseElement | [inline]
SetIsVisible(bool visible) | BaseElement |
SetLayoutHorizontal(bool isLayoutHorizontal) | BaseElement | [inline]
SetParentTransform(Windows::Foundation::Numerics::float2 translation) | BaseElement |
SetText(std::wstring text) | Text |
SetTranslation(Windows::Foundation::Numerics::float2 translation) | BaseElement | [virtual]
Text(std::wstring text, FLOAT fontSize, DWRITE_FONT_WEIGHT fontWeight=DWRITE_FONT_WEIGHT_ULTRA_BOLD) | Text |
TryRender() | BaseElement |
Update(const DX::StepTimer &timer, Windows::UI::Input::Spatial::SpatialPointerPose^cameraPose) | BaseElement | [virtual]
~BaseElement() | BaseElement | [virtual]
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Content/SpatialInputHandler.h Source File

  • HolographicVoiceInput
  • cpp
  • Content

SpatialInputHandler.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 namespace HolographicVoiceInput
00014 {
00015     // Sample gesture handler.
00016     // Hooks up events to recognize a tap gesture, and keeps track of input using a boolean value.
00017     class SpatialInputHandler
00018     {
00019     public:
00020         SpatialInputHandler();
00021         ~SpatialInputHandler();
00022
00023         Windows::UI::Input::Spatial::SpatialInteractionSourceState^ CheckForInput();
00024
00025     private:
00026         // Interaction event handler.
00027         void OnSourcePressed(
00028             Windows::UI::Input::Spatial::SpatialInteractionManager^ sender,
00029             Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs^ args);
00030
00031         // API objects used to process gesture input, and generate gesture events.
00032         Windows::UI::Input::Spatial::SpatialInteractionManager^     m_interactionManager;
00033
00034         // Event registration token.
00035         Windows::Foundation::EventRegistrationToken                 m_sourcePressedEventToken;
00036
00037         // Used to indicate that a Pressed input event was received this frame.
00038         Windows::UI::Input::Spatial::SpatialInteractionSourceState^ m_sourceState = nullptr;
00039     };
00040 }
Generated on Fri Nov 15 2024 22:16:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario7.xaml.cpp Source File

  • MapControl
  • cpp

Scenario7.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario7.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Concurrency;
00017 using namespace Platform;
00018 using namespace Platform::Collections;
00019 using namespace Windows::Devices::Geolocation;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::Storage;
00023 using namespace Windows::Storage::Streams;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Controls::Maps;
00027
00028 constexpr static long double Pi = 3.14159265358979323846264338327950288L;
00029
00030 PlaceLocation::PlaceLocation(double latitude, double longitude) :
00031     Geoposition{ latitude, longitude },
00032     MapCoordinates(GetMapCoordinates(latitude, longitude))
00033 {
00034 }
00035
00036 Point PlaceLocation::GetMapCoordinates(double latitude, double longitude)
00037 {
00038     // This formula comes from https://msdn.microsoft.com/en-us/library/bb259689.aspx
00039
00040     // Clamp latitude to the range -85.05112878 to 85.05112878.
00041     // This keeps Y in range and avoids the singularities at the poles.
00042     latitude = (std::max)((std::min)(latitude, 85.05112878), -85.05112878);
00043
00044     double sinLatitude = sin(latitude * Pi / 180.0);
00045     return Point{
00046         static_cast<float>((longitude + 180.0) / 360.0),
00047         static_cast<float>(0.5 - log((1.0 + sinLatitude) / (1.0 - sinLatitude)) / (4 * Pi))
00048     };
00049 }
00050
00051 Scenario7::Scenario7()
00052 {
00053     InitializeComponent();
00054
00055     // Prepare the custom icons we use to represent clusters of various sizes.
00056     for (int i = 2; i <= 9; i++)
00057     {
00058         numberIconReferences[i - 2] = RandomAccessStreamReference::CreateFromUri(ref new Uri("ms-appx:///Assets/Numbers/" + i.ToString() + ".png"));
00059     }
00060 }
00061
00062 task<void> Scenario7::LoadPlaceInfoAsync()
00063 {
00064     auto dataUri = ref new Uri("ms-appx:///places.txt");
00065
00066     return create_task(StorageFile::GetFileFromApplicationUriAsync(dataUri)).then([](StorageFile^ file)
00067     {
00068         return create_task(FileIO::ReadLinesAsync(file));
00069     }).then([this](IVector<String^>^ lines)
00070     {
00071         // In the places.txt file, each place is represented by three lines:
00072         // Place name, latitude, and longitude.
00073         for (unsigned int i = 0; i < lines->Size; i += 3)
00074         {
00075             places.push_back(PlaceInfo{
00076                 lines->GetAt(i),
00077                 PlaceLocation(_wtof(lines->GetAt(i + 1)->Data()), _wtof(lines->GetAt(i + 2)->Data())) });
00078         }
00079     });
00080 }
00081
00082 void Scenario7::myMap_Loaded(Object^ sender, RoutedEventArgs^ e)
00083 {
00084     LoadPlaceInfoAsync().then([this]()
00085     {
00086         // Zoom in to the level that shows all our points of interest.
00087         std::vector<BasicGeoposition> positions(places.size());
00088         std::transform(places.begin(), places.end(), positions.begin(),
00089             [](const PlaceInfo& place) { return place.Location.Geoposition; });
00090         GeoboundingBox^ boundingBox = GeoboundingBox::TryCompute(ref new Vector<BasicGeoposition, GeoEquals>(positions));
00091         return create_task(myMap->TrySetViewBoundsAsync(boundingBox, nullptr, MapAnimationKind::None));
00092     }, task_continuation_context::get_current_winrt_context()).then([this](bool)
00093     {
00094         refreshMapIcons();
00095     }, task_continuation_context::get_current_winrt_context());
00096 }
00097
00098 void Scenario7::myMap_ZoomLevelChanged(MapControl^ sender, Object^ args)
00099 {
00100     int intZoomLevel = (int)myMap->ZoomLevel;
00101     if (previousZoomLevel != intZoomLevel)
00102     {
00103         previousZoomLevel = intZoomLevel;
00104         refreshMapIcons();
00105     }
00106 }
00107
00108 void Scenario7::refreshMapIcons()
00109 {
00110     // Erase the old map icons.
00111     myMap->MapElements->Clear();
00112
00113     // Create an icon for each cluster.
00114     for (const Cluster& cluster : GetClustersForZoomLevel(previousZoomLevel))
00115     {
00116         MapIcon^ mapIcon = ref new MapIcon();
00117         mapIcon->Location = ref new Geopoint(cluster.Location.Geoposition);
00118         mapIcon->CollisionBehaviorDesired = MapElementCollisionBehavior::RemainVisible;
00119
00120         if (cluster.Places.size() > 1)
00121         {
00122             // The cluster represents more than one place. Use a custom marker that shows
00123             // how many places are represented by this cluster, and place the marker
00124             // centered at the cluster.
00125             mapIcon->Image = numberIconReferences[std::min<size_t>(cluster.Places.size(), 9) - 2];
00126             mapIcon->NormalizedAnchorPoint = Point(0.5, 0.5);
00127         }
00128         else
00129         {
00130             // The cluster represents a single place. Label the cluster with the place name.
00131             mapIcon->Title = cluster.Places[0].Name;
00132         }
00133         myMap->MapElements->Append(mapIcon);
00134     }
00135 }
00136
00137 const std::vector<Cluster>& Scenario7::GetClustersForZoomLevel(int zoomLevel)
00138 {
00139     // See if we have built the clusters for this zoom level already.
00140     auto found = clustersForZoomLevel.find(zoomLevel);
00141     if (found != clustersForZoomLevel.end())
00142     {
00143         // Yes, return it.
00144         return found->second;
00145     }
00146
00147     // No. Go build the clusters, cache them for next time, and return them.
00148     return clustersForZoomLevel[zoomLevel] = BuildClustersForZoomLevel(zoomLevel);
00149 }
00150
00151 // Note that we use a very simple clustering algorithm for the purpose of this sample.
00152 // The algorithm is sensitive to the order of the items in the "places" list.
00153 std::vector<Cluster> Scenario7::BuildClustersForZoomLevel(int zoomLevel)
00154 {
00155     // For a particular zoom level, the map is 2^(zoomLevel + 8) pixels wide.
00156     // See https://msdn.microsoft.com/en-us/library/bb259689.aspx for more information.
00157     double scale = pow(2, zoomLevel + 8);
00158
00159     // Say that each cluster covers a 100-pixel radius.
00160     const double clusterRadius = 100.0;
00161
00162     double scaledclusterRadius = clusterRadius / scale;
00163
00164     std::vector<Cluster> clusters;
00165     for (const PlaceInfo& place : places)
00166     {
00167         // Look for a cluster that is close to this place. If there is more than one,
00168         // we pick the first one arbitrarily.
00169         auto found = std::find_if(clusters.begin(), clusters.end(),
00170             [place, scaledclusterRadius](const Cluster& cluster)
00171         {
00172             return ArePointsNear(place.Location.MapCoordinates, cluster.Location.MapCoordinates, scaledclusterRadius);
00173         });
00174
00175         if (found == clusters.end())
00176         {
00177             // No such cluster exists yet. Make one.
00178             found = clusters.insert(clusters.end(), Cluster{ place.Location });
00179         }
00180         // Add the place to that cluster.
00181         found->Places.push_back(place);
00182     }
00183
00184     // Update the Location of each cluster to the center of all the places within it.
00185     for (Cluster& cluster : clusters)
00186     {
00187         cluster.Location = CalculateCenter(cluster.Places);
00188     }
00189
00190     return clusters;
00191 }
00192
00193 // Note that this algorithm breaks down if the points straddle longitude +180/-180.
00194 bool Scenario7::ArePointsNear(Point point1, Point point2, double threshold)
00195 {
00196     double dx = point1.X - point2.X;
00197     double dy = point1.Y - point2.Y;
00198     double distanceSquared = dx * dx + dy * dy;
00199     return distanceSquared < threshold * threshold;
00200 }
00201
00202 // Calculate the center of the cluster by taking the average longitude and latitude.
00203 // Note that this algorithm breaks down if the points straddle longitude +180/-180.
00204 PlaceLocation Scenario7::CalculateCenter(const std::vector<PlaceInfo>& places)
00205 {
00206     double totalLatitude = 0.0;
00207     double totalLongitude = 0.0;
00208
00209     for (const PlaceInfo& place : places)
00210     {
00211         totalLatitude += place.Location.Geoposition.Latitude;
00212         totalLongitude += place.Location.Geoposition.Longitude;
00213     }
00214
00215     return PlaceLocation(totalLatitude / places.size(), totalLongitude / places.size());
00216 }
Generated on Fri Nov 15 2024 22:18:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

WICTranslate Member List

This is the complete list of members for WICTranslate, including all inherited members.
format | WICTranslate
wic | WICTranslate
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario7_Share Member List

This is the complete list of members for Scenario7_Share, including all inherited members.
DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args) | Scenario7_Share | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario7_Share | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario7_Share | [inline, protected]
rootPage | Scenario7_Share | [private]
Scenario7_Share() | Scenario7_Share | [inline]
ShareContent_Click(object sender, RoutedEventArgs e) | Scenario7_Share | [inline, private]
WebViewControl_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args) | Scenario7_Share | [inline, private]
WebViewControl_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) | Scenario7_Share | [inline, private]
Generated on Fri Nov 15 2024 22:23:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cpp/Common/BaseElement.cpp Source File

  • 360VideoPlayback
  • cpp
  • Common

BaseElement.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "BaseElement.h"
00003 #include "DirectXHelper.h"
00004 #include "..\360VideoPlaybackMain.h"
00005
00006 using namespace _360VideoPlayback;
00007 using namespace D2D1;
00008 using namespace DirectX;
00009 using namespace DX;
00010 using namespace Microsoft::WRL;
00011 using namespace Platform;
00012 using namespace Windows::Foundation::Numerics;
00013 using namespace Windows::UI::Input::Spatial;
00014
00015 const float MAX_TEXT_LAYOUT_SIZE = 500;
00016
00017 BaseElement::BaseElement() :
00018     m_isInitialized(false),
00019     m_transformRecalculationNeeded(false),
00020     m_isRenderPassNeeded(true),
00021     m_isVisible(true),
00022     m_translation(0.0f, 0.0f),
00023     m_transformedTranslation(0.0f, 0.0f),
00024     m_parentTranslation(0.0f, 0.0f),
00025     m_elementSize(0.0f, 0.0f),
00026     m_ignoreLayout(true),
00027     m_brush(nullptr)
00028 {
00029     m_deviceResources = _360VideoPlaybackMain::GetDeviceResources();
00030 }
00031 void BaseElement::ArrangeElements()
00032 {
00033     float maxWidth = 0.0f;
00034     float maxHeight = 0.0f;
00035     float containerWidth = 0.0f;
00036     float containerHeight = 0.0f;
00037
00038     // Arrange Children And Compute whole ContainerSize
00039     for (const auto& element : m_childElements)
00040     {
00041         if (!element->GetIgnoreLayout())
00042         {
00043             // Skip stuff that doesn't want to be stacked in its container (like the focus rect).
00044             continue;
00045         }
00046
00047         maxWidth = max(maxWidth, element->GetElementSize().x);
00048         maxHeight = max(maxHeight, element->GetElementSize().y);
00049
00050         if (m_isLayoutHorizontal)
00051         {
00052             containerWidth += element->GetElementSize().x + element->GetElementMargin().left + element->GetElementMargin().right;
00053             containerHeight = max(containerHeight, element->GetElementSize().y + element->GetElementMargin().top + element->GetElementMargin().bottom);
00054         }
00055         else
00056         {
00057             containerWidth = max(containerWidth, element->GetElementSize().x + element->GetElementMargin().left + element->GetElementMargin().right);
00058             containerHeight = max(containerHeight, element->GetElementSize().y + element->GetElementMargin().top + element->GetElementMargin().bottom);
00059         }
00060     }
00061
00062     float minWidth = m_elementSize.x;
00063     float minHeight = m_elementSize.y;
00064
00065     containerWidth = max(minWidth, containerWidth);
00066     containerHeight = max(minHeight, containerHeight);
00067     m_elementSize.x = containerWidth;
00068     m_elementSize.y = containerHeight;
00069
00070     // Actually position the elements. We need to do this after calculating the container size so we can center the elements.
00071     float currentStackPosition = 0.0;
00072     for (const auto& element : m_childElements)
00073     {
00074         if (!element->GetIgnoreLayout())
00075         {
00076             // Skip stuff that doesn't want to be stacked in its container (like the focus rect).
00077             continue;
00078         }
00079
00080         if (m_isLayoutHorizontal)
00081         {
00082             // Position element along the stacking axis
00083             float elementPositionX = currentStackPosition + element->GetElementMargin().left;
00084
00085             // Center the element so the stacking axis bisects the element
00086             float elementPositionY = (containerHeight / 2.0f) - (element->GetElementSize().y / 2.0f);
00087
00088             // Adjust centered position to respect top margin
00089             if (elementPositionY < element->GetElementMargin().top)
00090             {
00091                 elementPositionY = element->GetElementMargin().top;
00092             }
00093
00094             // Adjust centered position to respect bottom margin
00095             if (elementPositionY + element->GetElementSize().y + element->GetElementMargin().bottom > containerHeight)
00096             {
00097                 elementPositionY = containerHeight - element->GetElementSize().y - element->GetElementMargin().bottom;
00098             }
00099
00100             element->SetTranslation({ elementPositionX, elementPositionY });
00101
00102             currentStackPosition += element->GetElementMargin().left + element->GetElementSize().x + element->GetElementMargin().right;
00103         }
00104         else
00105         {
00106             float elementPositionX = (containerWidth / 2.0f) - (element->GetElementSize().x / 2.0f);
00107             float elementPositionY = (containerHeight / 2.0f) - (element->GetElementSize().y / 2.0f);
00108             element->SetTranslation({ elementPositionX, elementPositionY });
00109         }
00110     }
00111 }
00112
00113 void BaseElement::Initialize()
00114 {
00115     for (const auto& child : m_childElements)
00116     {
00117         child->Initialize();
00118     }
00119     m_isInitialized = true;
00120 }
00121
00122 void BaseElement::SetBrush(ID2D1SolidColorBrush* brush)
00123 {
00124     m_brush = brush;
00125     m_isRenderPassNeeded = true;
00126 }
00127
00128 void BaseElement::Update(const DX::StepTimer& timer, SpatialPointerPose^ cameraPose)
00129 {
00130     // If one of BaseElement's transforms have changed or its parent's transforms have been updated
00131     // we will recalculate the BaseElement's transforms and tell its children to update their transforms
00132     // as well.
00133     // NOTE: For BaseElement's with complex nested children we should try not to update the transforms too
00134     // frequently because this can cause perf issues. (fonts, textures, and glyphs may need to be resized)
00135     if (m_transformRecalculationNeeded)
00136     {
00137         m_transformedTranslation = m_translation + m_parentTranslation;
00138         m_transformMatrix = D2D1::Matrix3x2F::Translation(m_transformedTranslation.x, m_transformedTranslation.y);
00139
00140         // Update children with updated transforms
00141         for (const auto& child : m_childElements)
00142         {
00143             child->SetParentTransform(m_transformedTranslation);
00144         }
00145
00146         m_transformRecalculationNeeded = false;
00147         m_isRenderPassNeeded = true;
00148     }
00149
00150     if (!m_isInitialized)
00151     {
00152         Initialize();
00153     }
00154
00155     for (const auto& child : m_childElements)
00156     {
00157         child->Update(timer, cameraPose);
00158         m_isRenderPassNeeded |= child->GetIsRenderPassNeeded();
00159     }
00160 }
00161
00162 void BaseElement::TryRender()
00163 {
00164     if (m_isVisible)
00165     {
00166         Render();
00167
00168         for (const auto& child : m_childElements)
00169         {
00170             child->TryRender();
00171         }
00172     }
00173
00174     m_isRenderPassNeeded = false;
00175 }
00176
00177 void BaseElement::Render()
00178 {
00179 }
00180
00181 void BaseElement::SetTranslation(float2 translation)
00182 {
00183     m_transformRecalculationNeeded |= m_translation != translation;
00184     m_translation = translation;
00185 }
00186
00187 void BaseElement::SetParentTransform(float2 translation)
00188 {
00189     m_transformRecalculationNeeded |= (m_parentTranslation != translation);
00190     m_parentTranslation = translation;
00191 }
00192
00193 void BaseElement::AddChildElement(const std::shared_ptr<BaseElement>& childElement)
00194 {
00195     childElement->SetParentTransform(m_transformedTranslation);
00196     m_childElements.push_back(childElement);
00197 }
00198
00199 void BaseElement::SetIsVisible(bool visible)
00200 {
00201     m_isRenderPassNeeded |= (visible != m_isVisible);
00202     m_isVisible = visible;
00203 };
00204
00205 FocusableElement::FocusableElement() :
00206     BaseElement(),
00207     m_isFocused(false),
00208     m_isParentFocused(false),
00209     m_isFocusIntersectionCalculated(false),
00210     m_elementCoordIntersectionPoint({ 0.0f,0.0f }),
00211     m_parentTextureWidth(0),
00212     m_parentTextureHeight(0),
00213     m_parentFocusedPosition(float2(0.0f))
00214 {
00215 }
00216
00217 void FocusableElement::Update(const StepTimer& timer, SpatialPointerPose^ cameraPose)
00218 {
00219     __super::Update(timer, cameraPose);
00220     if (m_isParentFocused)
00221     {
00222         bool isFocused = false;
00223
00224         float2 minBounds = m_transformedTranslation;
00225         float2 maxBounds = m_transformedTranslation + m_elementSize;
00226         // The focused position is relative to the model size, so we need to scale it to the texture size
00227         float2 textureScaledParentFocusedPosition = float2(m_parentFocusedPosition.x * m_parentTextureWidth, m_parentFocusedPosition.y * m_parentTextureHeight);
00228         if (minBounds.x <= textureScaledParentFocusedPosition.x && minBounds.y <= textureScaledParentFocusedPosition.y &&
00229             textureScaledParentFocusedPosition.x <= maxBounds.x && textureScaledParentFocusedPosition.y <= maxBounds.y)
00230         {
00231             isFocused = true;
00232         }
00233
00234         if (m_isFocused != isFocused)
00235         {
00236             m_isRenderPassNeeded = true; // If this is a change in focus, mark we need a render pass
00237             m_isFocused = isFocused;
00238             FocusUpdate();
00239         }
00240
00241         if (m_isFocused && m_isFocusIntersectionCalculated) // This is mainly used by Slider Elements, which is why its behind a flag
00242         {
00243             m_elementCoordIntersectionPoint = float2(
00244                 textureScaledParentFocusedPosition.x - (m_parentTextureWidth - m_elementSize.x),
00245                 textureScaledParentFocusedPosition.y - (m_parentTextureHeight - m_elementSize.y));
00246         }
00247     }
00248     else
00249     {
00250         m_isFocused = false;
00251     }
00252 }
00253
00254 void FocusableElement::SetParentControlInformation(bool focused, Windows::Foundation::Numerics::float2 focusedPosition, UINT parentTextureWidth, UINT parentTextureHeight)
00255 {
00256     m_isParentFocused = focused;
00257     if (!m_isParentFocused)
00258     {
00259         if (m_isFocused)
00260         {
00261             m_isFocused = false;
00262             FocusUpdate();
00263         }
00264     }
00265     m_parentFocusedPosition = focusedPosition;
00266     m_parentTextureWidth = parentTextureWidth;
00267     m_parentTextureHeight = parentTextureHeight;
00268 }
00269
00270 Text::Text(std::wstring text, FLOAT fontSize, DWRITE_FONT_WEIGHT fontWeight) :
00271     m_transformedFontSize(fontSize),
00272     m_fontWeight(fontWeight)
00273 {
00274     this->SetText(text);
00275 }
00276
00277 void Text::Render()
00278 {
00279     D2D1_SIZE_F renderTargetSize = m_deviceResources->GetD2DDeviceContext()->GetSize();
00280     D2D1_POINT_2F textOrigin{ 0.0, 0.0 };
00281     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00282     d2dContext->SetTransform(D2D1::Matrix3x2F::Translation(m_transformedTranslation.x, m_transformedTranslation.y));
00283     d2dContext->DrawTextLayout(textOrigin, m_textLayout.Get(), m_brush.Get());
00284     d2dContext->SetTransform(D2D1::IdentityMatrix());
00285 }
00286
00287 void Text::CreateTextContext()
00288 {
00289     DX::ThrowIfFailed(m_deviceResources->GetDWriteFactory()->CreateTextFormat(
00290         L"Segoe UI",
00291         nullptr,
00292         m_fontWeight,
00293         DWRITE_FONT_STYLE_NORMAL,
00294         DWRITE_FONT_STRETCH_NORMAL,
00295         m_transformedFontSize,
00296         Windows::Globalization::ApplicationLanguages::Languages->GetAt(0)->Data(),
00297         &m_textFormat));
00298
00299     m_textFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
00300
00301     DX::ThrowIfFailed(m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING));
00302     DX::ThrowIfFailed(m_deviceResources->GetDWriteFactory()->CreateTextLayout(
00303         m_text.data(),
00304         static_cast<UINT32>(m_text.size()),
00305         m_textFormat.Get(),
00306         MAX_TEXT_LAYOUT_SIZE,
00307         MAX_TEXT_LAYOUT_SIZE,
00308         &m_textLayout));
00309
00310     DWRITE_TEXT_METRICS textMetrics;
00311     m_textLayout->GetMetrics(&textMetrics);
00312     m_elementSize = { textMetrics.width, textMetrics.height };
00313     m_isRenderPassNeeded = true;
00314 }
00315
00316 void Text::SetText(std::wstring text)
00317 {
00318     if (text != m_text)
00319     {
00320         m_text = text;
00321         this->CreateTextContext();
00322     }
00323 }
00324
00325 Line::Line(FLOAT strokeThickness) :
00326     m_strokeThickness(strokeThickness)
00327 {
00328     m_lineStart = D2D1::Point2F(0.0f, 0.0f);
00329     m_lineEnd = D2D1::Point2F(1.0f, 0.0f);
00330 }
00331
00332 void Line::Render()
00333 {
00334     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00335     d2dContext->SetTransform(m_transformMatrix);
00336     d2dContext->DrawLine(m_lineStart, m_lineEnd, m_brush.Get(), m_strokeThickness);
00337     d2dContext->SetTransform(D2D1::IdentityMatrix());
00338 }
00339
00340 void Line::SetStartPoint(D2D1_POINT_2F& point)
00341 {
00342     m_transformRecalculationNeeded |= (point.x != m_lineStart.x || point.y != m_lineStart.y);
00343     m_lineStart = point;
00344 }
00345
00346 void Line::SetEndPoint(D2D1_POINT_2F& point)
00347 {
00348     m_transformRecalculationNeeded |= (point.x != m_lineEnd.x || point.y != m_lineEnd.y);
00349     m_lineEnd = point;
00350 }
00351
00352 Ellipse::Ellipse(FLOAT radiusX, FLOAT radiusY, FLOAT strokeThickness, ColorF brushColor) :
00353     BaseElement(),
00354     m_radiusX(radiusX),
00355     m_radiusY(radiusY),
00356     m_strokeThickness(strokeThickness),
00357     m_brushColor(brushColor)
00358 {
00359     this->SetRadius(radiusX, radiusY);
00360 }
00361
00362 void Ellipse::Initialize()
00363 {
00364     if (m_brush == nullptr)
00365     {
00366         const auto d2dcontext = m_deviceResources->GetD2DDeviceContext();
00367         DX::ThrowIfFailed(d2dcontext->CreateSolidColorBrush(
00368             m_brushColor,
00369             &m_brush));
00370     }
00371     __super::Initialize();
00372 }
00373
00374 void Ellipse::SetRadius(FLOAT x, FLOAT y)
00375 {
00376     m_radiusX = x; m_radiusY = y;
00377     m_elementSize = { m_radiusX * 2.0f, m_radiusY * 2.0f };
00378     m_ellipse = D2D1::Ellipse(D2D1::Point2F(m_radiusX, m_radiusY), m_radiusX, m_radiusY);
00379 }
00380
00381 void Ellipse::Render()
00382 {
00383     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00384     d2dContext->SetTransform(m_transformMatrix);
00385     d2dContext->DrawEllipse(m_ellipse, m_brush.Get(), m_strokeThickness);
00386     d2dContext->SetTransform(D2D1::IdentityMatrix());
00387 }
00388
00389 FilledEllipse::FilledEllipse(FLOAT radiusX, FLOAT radiusY, ColorF brushColor) :
00390     BaseElement(),
00391     m_radiusX(radiusX),
00392     m_radiusY(radiusY),
00393     m_brushColor(brushColor)
00394 {
00395     this->SetRadius(radiusX, radiusY);
00396 }
00397
00398 void FilledEllipse::SetRadius(FLOAT x, FLOAT y)
00399 {
00400     m_radiusX = x; m_radiusY = y;
00401     m_elementSize = { m_radiusX * 2.0f, m_radiusY * 2.0f };
00402     m_ellipse = D2D1::Ellipse(D2D1::Point2F(m_radiusX, m_radiusY), m_radiusX, m_radiusY);
00403 }
00404
00405 void FilledEllipse::Initialize()
00406 {
00407     if (m_brush == nullptr)
00408     {
00409         const auto d2dcontext = m_deviceResources->GetD2DDeviceContext();
00410         d2dcontext->CreateSolidColorBrush(
00411             m_brushColor,
00412             &m_brush);
00413     }
00414     __super::Initialize();
00415 }
00416
00417 void FilledEllipse::Render()
00418 {
00419     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00420     d2dContext->SetTransform(m_transformMatrix);
00421     d2dContext->FillEllipse(m_ellipse, m_brush.Get());
00422     d2dContext->SetTransform(D2D1::IdentityMatrix());
00423 }
00424
00425 Rectangle::Rectangle(FLOAT width, FLOAT height, FLOAT strokeThickness, ColorF brushColor) :
00426     BaseElement(),
00427     m_rect(D2D1::RectF(0.0f, 0.0f, width, height)),
00428     m_strokeThickness(strokeThickness),
00429     m_brushColor(brushColor)
00430 {
00431 }
00432
00433 void Rectangle::Initialize()
00434 {
00435     if (m_brush == nullptr)
00436     {
00437         const auto d2dcontext = m_deviceResources->GetD2DDeviceContext();
00438         DX::ThrowIfFailed(d2dcontext->CreateSolidColorBrush(
00439             m_brushColor,
00440             &m_brush));
00441     }
00442
00443     __super::Initialize();
00444 }
00445
00446 void Rectangle::Render()
00447 {
00448     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00449     d2dContext->SetTransform(m_transformMatrix);
00450     d2dContext->DrawRectangle(m_rect, m_brush.Get(), m_strokeThickness);
00451     d2dContext->SetTransform(D2D1::IdentityMatrix());
00452 }
00453
00454 FilledRectangle::FilledRectangle(FLOAT width, FLOAT height, ColorF brushColor) :
00455     BaseElement(),
00456     m_rect(D2D1::RectF(0.0f, 0.0f, width, height)),
00457     m_brushColor(brushColor)
00458 {
00459 }
00460
00461 void FilledRectangle::Initialize()
00462 {
00463     if (m_brush == nullptr)
00464     {
00465         const auto d2dcontext = m_deviceResources->GetD2DDeviceContext();
00466         d2dcontext->CreateSolidColorBrush(
00467             m_brushColor,
00468             &m_brush
00469         );
00470     }
00471     __super::Initialize();
00472 }
00473
00474 void FilledRectangle::Render()
00475 {
00476     auto d2dContext = m_deviceResources->GetD2DDeviceContext();
00477     d2dContext->SetTransform(m_transformMatrix);
00478     d2dContext->FillRectangle(m_rect, m_brush.Get());
00479     d2dContext->SetTransform(D2D1::IdentityMatrix());
00480 }
Generated on Fri Nov 15 2024 22:16:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DataReaderWriter/cpp/SampleConfiguration.cpp Source File

  • DataReaderWriter
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Read and write simple structured data.", "SDKTemplate.WriteReadStream" },
00012     { "Dump file contents using ReadBytes().", "SDKTemplate.ReadBytes" }
00013 };
Generated on Fri Nov 15 2024 22:17:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SessionRequestWrapper Member List

This is the complete list of members for SessionRequestWrapper, including all inherited members.
Advertisement | SessionRequestWrapper |
Id | SessionRequestWrapper |
Pin | SessionRequestWrapper |
ProvisioningInfo | SessionRequestWrapper |
SessionInfo | SessionRequestWrapper |
SessionRequestWrapper(WiFiDirectServiceSessionRequest request, AdvertisementWrapper advertisement) | SessionRequestWrapper | [inline]
Generated on Fri Nov 15 2024 22:24:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundActivation/cpp/Scenario6_GroupedTask.xaml.cpp Source File

  • BackgroundActivation
  • cpp

Scenario6_GroupedTask.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario6_GroupedTask.xaml.cpp
00013 // Implementation of the GroupedBackgroundTask class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario6_GroupedTask.xaml.h"
00018 #include "SampleConfiguration.h"
00019
00020 using namespace SDKTemplate;
00021 using namespace concurrency;
00022 using namespace Windows::ApplicationModel::Background;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Xaml;
00025 using namespace Windows::UI::Xaml::Controls;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028 GroupedBackgroundTask::GroupedBackgroundTask()
00029 {
00030     InitializeComponent();
00031 }
00032
00033 /// <summary>
00034 /// Invoked when this page is about to be displayed in a Frame.
00035 /// </summary>
00036 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00037 /// property is typically used to configure the page.</param>
00038 void GroupedBackgroundTask::OnNavigatedTo(NavigationEventArgs^ e)
00039 {
00040     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00041     // as NotifyUser()
00042     rootPage = MainPage::Current;
00043
00044     group = BackgroundTaskSample::GetTaskGroup(BackgroundTaskGroupId, BackgroundTaskGroupFriendlyName);
00045
00046     //
00047     // Attach progress and completed handlers to any existing tasks.
00048     //
00049     for (auto pair : group->AllTasks)
00050     {
00051         auto task = pair->Value;
00052         if (task->Name == GroupedBackgroundTaskName)
00053         {
00054             BackgroundTaskSample::UpdateBackgroundTaskRegistrationStatus(task->Name, true);
00055             AttachProgressAndCompletedHandlers(task);
00056             break;
00057         }
00058     }
00059
00060     UpdateUI();
00061 }
00062
00063 /// <summary>
00064 /// Attach progress and completed handers to a background task.
00065 /// </summary>
00066 /// <param name="task">The task to attach progress and completed handlers to.</param>
00067 void GroupedBackgroundTask::AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration^ task)
00068 {
00069     task->Progress += ref new BackgroundTaskProgressEventHandler(this, &GroupedBackgroundTask::OnProgress);
00070     task->Completed += ref new BackgroundTaskCompletedEventHandler(this, &GroupedBackgroundTask::OnCompleted);
00071 }
00072
00073 /// <summary>
00074 /// Register a Grouped Background Task.
00075 /// </summary>
00076 /// <param name="sender"></param>
00077 /// <param name="e"></param>
00078 void GroupedBackgroundTask::RegisterGroupedBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00079 {
00080     auto task = BackgroundTaskSample::RegisterBackgroundTask(nullptr,
00081         GroupedBackgroundTaskName,
00082         ref new SystemTrigger(SystemTriggerType::TimeZoneChange, false),
00083         nullptr,
00084         group);
00085     AttachProgressAndCompletedHandlers(task);
00086     UpdateUI();
00087 }
00088
00089 /// <summary>
00090 /// Unregister a Grouped Background Task.
00091 /// </summary>
00092 /// <param name="sender"></param>
00093 /// <param name="e"></param>
00094 void GroupedBackgroundTask::UnregisterGroupedTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00095 {
00096     BackgroundTaskSample::UnregisterBackgroundTasks(GroupedBackgroundTaskName, group);
00097     UpdateUI();
00098 }
00099
00100 /// <summary>
00101 /// Unregister all Background Tasks that are not grouped.
00102 /// </summary>
00103 /// <param name="sender"></param>
00104 /// <param name="e"></param>
00105 void GroupedBackgroundTask::UnregisterUngroupedTasks(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00106 {
00107     for (auto pair : BackgroundTaskRegistration::AllTasks)
00108     {
00109         auto task = pair->Value;
00110         task->Unregister(true);
00111         BackgroundTaskSample::UpdateBackgroundTaskRegistrationStatus(task->Name, false);
00112     }
00113 }
00114
00115 /// <summary>
00116 /// Handle background task progress.
00117 /// </summary>
00118 /// <param name="task">The task that is reporting progress.</param>
00119 /// <param name="args">Arguments of the progress report.</param>
00120 void GroupedBackgroundTask::OnProgress(BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
00121 {
00122     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
00123     {
00124         auto progress = "Progress: " + args->Progress + "%";
00125         BackgroundTaskSample::GroupedBackgroundTaskProgress = progress;
00126         UpdateUI();
00127     }));
00128 }
00129
00130 /// <summary>
00131 /// Handle background task completion.
00132 /// </summary>
00133 /// <param name="task">The task that is reporting completion.</param>
00134 /// <param name="args">Arguments of the completion report.</param>
00135 void GroupedBackgroundTask::OnCompleted(BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
00136 {
00137     UpdateUI();
00138 }
00139
00140 /// <summary>
00141 /// Update the scenario UI.
00142 /// </summary>
00143 void GroupedBackgroundTask::UpdateUI()
00144 {
00145     auto uiDelegate = [this]()
00146     {
00147         RegisterButton->IsEnabled = !BackgroundTaskSample::GroupedBackgroundTaskRegistered;
00148         UnregisterGroupedButton->IsEnabled = BackgroundTaskSample::GroupedBackgroundTaskRegistered;
00149         Progress->Text = BackgroundTaskSample::GroupedBackgroundTaskProgress;
00150         Status->Text = BackgroundTaskSample::GetBackgroundTaskStatus(GroupedBackgroundTaskName);
00151     };
00152     auto handler = ref new Windows::UI::Core::DispatchedHandler(uiDelegate, Platform::CallbackContext::Any);
00153
00154     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, handler);
00155 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DGradientMesh/cpp/DirectXHelper.h Source File

  • D2DGradientMesh
  • cpp

DirectXHelper.h

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include <ppltasks.h>
00011
00012 namespace DX
00013 {
00014     inline void ThrowIfFailed(HRESULT hr)
00015     {
00016         if (FAILED(hr))
00017         {
00018             // Set a breakpoint on this line to catch Win32 API errors.
00019             throw Platform::Exception::CreateException(hr);
00020         }
00021     }
00022
00023     // Function that reads from a binary file asynchronously.
00024     inline Concurrency::task<std::vector<byte>> ReadDataAsync(const std::wstring& filename)
00025     {
00026         using namespace Windows::Storage;
00027         using namespace Concurrency;
00028
00029         auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
00030
00031         return create_task(folder->GetFileAsync(Platform::StringReference(filename.c_str()))).then([] (StorageFile^ file)
00032         {
00033             return FileIO::ReadBufferAsync(file);
00034         }).then([] (Streams::IBuffer^ fileBuffer) -> std::vector<byte>
00035         {
00036             std::vector<byte> returnBuffer;
00037             returnBuffer.resize(fileBuffer->Length);
00038             Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference<byte>(returnBuffer.data(), fileBuffer->Length));
00039             return returnBuffer;
00040         });
00041     }
00042
00043     // Converts a length in device-independent pixels (DIPs) to a length in physical pixels.
00044     inline float ConvertDipsToPixels(float dips, float dpi)
00045     {
00046         static const float dipsPerInch = 96.0f;
00047         return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
00048     }
00049
00050     // Converts a length in physical pixels to a length in device-independent pixels (DIPs).
00051     inline float ConvertPixelsToDips(float pixels)
00052     {
00053         static const float dipsPerInch = 96.0f;
00054         return pixels * dipsPerInch / Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->LogicalDpi; // Do not round.
00055     }
00056
00057     // Converts a length in physical pixels to a length in device-independent pixels (DIPs) using the provided DPI. This removes the need
00058     // to call this function from a thread associated with a CoreWindow, which is required by DisplayInformation::GetForCurrentView().
00059     inline float ConvertPixelsToDips(float pixels, float dpi)
00060     {
00061         static const float dipsPerInch = 96.0f;
00062         return pixels * dipsPerInch / dpi; // Do not round.
00063     }
00064
00065 #if defined(_DEBUG)
00066     // Check for SDK Layer support.
00067     inline bool SdkLayersAvailable()
00068     {
00069         HRESULT hr = D3D11CreateDevice(
00070             nullptr,
00071             D3D_DRIVER_TYPE_NULL,       // There is no need to create a real hardware device.
00072             0,
00073             D3D11_CREATE_DEVICE_DEBUG,  // Check for the SDK layers.
00074             nullptr,                    // Any feature level will do.
00075             0,
00076             D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00077             nullptr,                    // No need to keep the D3D device reference.
00078             nullptr,                    // No need to know the feature level.
00079             nullptr                     // No need to keep the D3D device context reference.
00080             );
00081
00082         return SUCCEEDED(hr);
00083     }
00084 #endif
00085 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cppwinrt/WASAPICapture.h Source File

  • WindowsAudioSession
  • cppwinrt

WASAPICapture.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012 #include "DeviceState.h"
00013 #include "PlotData.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     // Primary WASAPI Capture Class
00018     struct WASAPICapture : winrt::implements<WASAPICapture, IActivateAudioInterfaceCompletionHandler, IDeviceStateSource, IPlotDataSource>,
00019         implementation::DeviceStateSourceT<WASAPICapture>,
00020         implementation::PlotDataSourceT<WASAPICapture>
00021     {
00022     public:
00023         WASAPICapture();
00024
00025         void SetLowLatencyCapture(bool value) { m_isLowLatency = value; }
00026         void AsyncInitializeAudioDevice() noexcept;
00027         void AsyncStartCapture();
00028         void AsyncStopCapture();
00029
00030         // IActivateAudioInterfaceCompletionHandler
00031         STDMETHOD(ActivateCompleted)(IActivateAudioInterfaceAsyncOperation* operation);
00032
00033     private:
00034         HRESULT OnStartCapture(IMFAsyncResult* pResult);
00035         HRESULT OnStopCapture(IMFAsyncResult* pResult);
00036         HRESULT OnFinishCapture(IMFAsyncResult* pResult);
00037         HRESULT OnSampleReady(IMFAsyncResult* pResult);
00038         HRESULT OnSendScopeData(IMFAsyncResult* pResult);
00039
00040         EmbeddedMFAsyncCallback<&WASAPICapture::OnStartCapture> m_StartCaptureCallback{ this };
00041         EmbeddedMFAsyncCallback<&WASAPICapture::OnStopCapture> m_StopCaptureCallback{ this };
00042         EmbeddedMFAsyncCallback<&WASAPICapture::OnSampleReady> m_SampleReadyCallback{ this };
00043         EmbeddedMFAsyncCallback<&WASAPICapture::OnFinishCapture> m_FinishCaptureCallback{ this };
00044         EmbeddedMFAsyncCallback<&WASAPICapture::OnSendScopeData> m_SendScopeDataCallback{ this };
00045
00046         fire_and_forget CreateWAVFile();
00047         fire_and_forget FixWAVHeader();
00048         void OnAudioSampleRequested();
00049         void InitializeScopeData();
00050         void ProcessScopeData(array_view<uint8_t> rawBytes);
00051         fire_and_forget AsyncStoreData();
00052
00053     private:
00054         uint32_t m_bufferFrames = 0;
00055
00056         // Event for sample ready or user stop
00057         handle m_SampleReadyEvent{ check_pointer(CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS)) };
00058
00059         MFWORKITEM_KEY m_sampleReadyKey = 0;
00060         slim_mutex m_lock;
00061         unique_shared_work_queue m_queueId{ L"Capture" };
00062
00063         uint32_t m_headerSize = 0;
00064         uint32_t m_dataSize = 0;
00065         uint32_t m_bytesSinceLastFlush = 0;
00066         bool m_writing = false;
00067         bool m_isLowLatency = false;
00068
00069         Windows::Storage::Streams::IRandomAccessStream m_contentStream;
00070         Windows::Storage::Streams::IOutputStream m_outputStream;
00071         Windows::Storage::Streams::DataWriter m_dataWriter{ nullptr };
00072         unique_cotaskmem_ptr<WAVEFORMATEX> m_mixFormat;
00073         com_ptr<IAudioClient3> m_audioClient;
00074         uint32_t m_defaultPeriodInFrames;
00075         uint32_t m_fundamentalPeriodInFrames;
00076         uint32_t m_maxPeriodInFrames;
00077         uint32_t m_minPeriodInFrames;
00078         com_ptr<IAudioCaptureClient> m_audioCaptureClient;
00079         com_ptr<IMFAsyncResult> m_sampleReadyAsyncResult;
00080
00081         Windows::Storage::Streams::IBuffer m_plotDataBuffer;
00082         uint32_t m_plotDataMaxPoints;
00083         uint32_t m_plotDataPointsFilled;
00084     };
00085 }
Generated on Fri Nov 15 2024 22:22:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Appointments/cs/Scenario2_Add.xaml.cs Source File

  • Appointments
  • cs

Scenario2_Add.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016
00017 namespace SDKTemplate
00018 {
00019     public sealed partial class Scenario2_Add : Page
00020     {
00021         private MainPage rootPage = MainPage.Current;
00022
00023         public Scenario2_Add()
00024         {
00025             this.InitializeComponent();
00026         }
00027
00028         /// <summary>
00029         /// Adds an appointment to the default appointment provider app.
00030         /// </summary>
00031         /// <param name="sender"></param>
00032         /// <param name="e"></param>
00033         private async void Add_Click(object sender, RoutedEventArgs e)
00034         {
00035             // Create an Appointment that should be added the user's appointments provider app.
00036             var appointment = new Windows.ApplicationModel.Appointments.Appointment();
00037
00038             // Get the selection rect of the button pressed to add this appointment
00039             var rect = MainPage.GetElementRect(sender as FrameworkElement);
00040
00041             // ShowAddAppointmentAsync returns an appointment id if the appointment given was added to the user's calendar.
00042             // This value should be stored in app data and roamed so that the appointment can be replaced or removed in the future.
00043             // An empty string return value indicates that the user canceled the operation before the appointment was added.
00044             String appointmentId = await Windows.ApplicationModel.Appointments.AppointmentManager.ShowAddAppointmentAsync(appointment, rect, Windows.UI.Popups.Placement.Default);
00045             if (appointmentId != String.Empty)
00046             {
00047                 rootPage.NotifyUser("Appointment Id: " + appointmentId, NotifyType.StatusMessage);
00048             }
00049             else
00050             {
00051                 rootPage.NotifyUser("Appointment not added.", NotifyType.ErrorMessage);
00052             }
00053         }
00054     }
00055 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/DetailsPage.cpp Source File

  • XamlListView
  • cppwinrt

DetailsPage.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DetailsPage.h"
00014 #include "DetailsPage.g.cpp"
00015
00016 using namespace winrt::Windows::UI::Core;
00017 using namespace winrt::Windows::UI::Xaml;
00018 using namespace winrt::Windows::UI::Xaml::Controls;
00019 using namespace winrt::Windows::UI::Xaml::Media::Animation;
00020 using namespace winrt::Windows::UI::Xaml::Navigation;
00021
00022 namespace winrt::SDKTemplate::implementation
00023 {
00024     DetailsPage::DetailsPage()
00025     {
00026         InitializeComponent();
00027     }
00028
00029     void DetailsPage::OnLoaded(IInspectable const&, RoutedEventArgs const&)
00030     {
00031         if (ShouldGoToWideState())
00032         {
00033             // We shouldn't see this page since we are in "wide master-detail" mode.
00034             // Play a transition as we are navigating from a separate page.
00035             NavigateBackForWideState(/* useTransition */ true);
00036         }
00037         else
00038         {
00039             // Realize the main page content.
00040             FindName(L"RootPanel");
00041         }
00042
00043         windowSizeChangedToken = Window::Current().SizeChanged({ get_weak(), &DetailsPage::OnWindowSizeChanged });
00044     }
00045
00046     void DetailsPage::OnNavigatedTo(NavigationEventArgs const& e)
00047     {
00048         selectedContact = e.Parameter().as<SDKTemplate::Contact>();
00049         // Register for hardware and software back request from the system
00050         SystemNavigationManager systemNavigationManager = SystemNavigationManager::GetForCurrentView();
00051         backRequestedToken = systemNavigationManager.BackRequested({ get_weak(), &DetailsPage::OnBackRequested });
00052         systemNavigationManager.AppViewBackButtonVisibility(AppViewBackButtonVisibility::Visible);
00053     }
00054
00055     void DetailsPage::OnNavigatedFrom(NavigationEventArgs const&)
00056     {
00057         SystemNavigationManager systemNavigationManager = SystemNavigationManager::GetForCurrentView();
00058         systemNavigationManager.BackRequested(backRequestedToken);
00059         systemNavigationManager.AppViewBackButtonVisibility(AppViewBackButtonVisibility::Collapsed);
00060     }
00061
00062     void DetailsPage::OnBackRequested(IInspectable const&, BackRequestedEventArgs const& e)
00063     {
00064         // Mark event as handled so we don't leave the app.
00065         e.Handled(true);
00066         // Page above us will be our master view.
00067         // Make sure we are using the "drill out" animation in this transition.
00068         Frame().Navigate(xaml_typename<SDKTemplate::Scenario3_MasterDetail>(), box_value(L"B" + SelectedContact().Id()), EntranceNavigationTransitionInfo());
00069     }
00070
00071     void DetailsPage::NavigateBackForWideState(bool useTransition)
00072     {
00073         // Evict this page from the cache as we may not need it again.
00074         NavigationCacheMode(NavigationCacheMode::Disabled);
00075
00076         if (useTransition)
00077         {
00078             Frame().GoBack(EntranceNavigationTransitionInfo());
00079         }
00080         else
00081         {
00082             Frame().GoBack(SuppressNavigationTransitionInfo());
00083         }
00084     }
00085
00086     bool DetailsPage::ShouldGoToWideState()
00087     {
00088         return Window::Current().Bounds().Width >= 720;
00089     }
00090
00091     void DetailsPage::OnUnloaded(IInspectable const&, RoutedEventArgs const&)
00092     {
00093         Window::Current().SizeChanged(windowSizeChangedToken);
00094     }
00095
00096     void DetailsPage::OnWindowSizeChanged(IInspectable const&, WindowSizeChangedEventArgs const&)
00097     {
00098         if (ShouldGoToWideState())
00099         {
00100             // Make sure we are no longer listening to window change events.
00101             Window::Current().SizeChanged(windowSizeChangedToken);
00102
00103             // We shouldn't see this page since we are in "wide master-detail" mode.
00104             NavigateBackForWideState(/* useTransition */ false);
00105         }
00106     }
00107
00108     void DetailsPage::DeleteItem(IInspectable const&, RoutedEventArgs const&)
00109     {
00110         Frame().Navigate(xaml_typename<SDKTemplate::Scenario3_MasterDetail>(), box_value(L"D" + SelectedContact().Id()), EntranceNavigationTransitionInfo());
00111     }
00112
00113 }
Generated on Fri Nov 15 2024 22:22:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GpuPerformanceTimer Member List

This is the complete list of members for GpuPerformanceTimer, including all inherited members.
EndTimerForFrame() | GpuPerformanceTimer |
GetAvgFrameTime() const | GpuPerformanceTimer |
GetFrameTime() const | GpuPerformanceTimer |
GetMaxFrameTime() const | GpuPerformanceTimer |
GetMinFrameTime() const | GpuPerformanceTimer |
GpuPerformanceTimer(const std::shared_ptr< DX::DeviceResources > &deviceResources) | GpuPerformanceTimer |
m_currentFrameIndex | GpuPerformanceTimer | [private]
m_currentQuery | GpuPerformanceTimer | [private]
m_deviceResources | GpuPerformanceTimer | [private]
m_disjointQuery | GpuPerformanceTimer | [private]
m_endTimestampQuery | GpuPerformanceTimer | [private]
m_processingTimeAvgMs | GpuPerformanceTimer | [private]
m_processingTimeHistory | GpuPerformanceTimer | [private]
m_processingTimeHistoryIndex | GpuPerformanceTimer | [private]
m_processingTimeMaxMs | GpuPerformanceTimer | [private]
m_processingTimeMinMs | GpuPerformanceTimer | [private]
m_processingTimeMs | GpuPerformanceTimer | [private]
m_startTimestampQuery | GpuPerformanceTimer | [private]
QueryCount | GpuPerformanceTimer | [private, static]
StartTimerForFrame() | GpuPerformanceTimer |
TimeHistoryCount | GpuPerformanceTimer | [private, static]
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Inclinometer/cpp/pch.h Source File

  • Inclinometer
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario15_ServerCertificateValidation Member List

This is the complete list of members for Scenario15_ServerCertificateValidation, including all inherited members.
Cancel_Click(object sender, RoutedEventArgs e) | Scenario15_ServerCertificateValidation | [inline, private]
cts | Scenario15_ServerCertificateValidation | [private]
DefaultAndCustomValidation_Checked(object sender, RoutedEventArgs e) | Scenario15_ServerCertificateValidation | [inline, private]
DefaultOSValidation_Checked(object sender, RoutedEventArgs e) | Scenario15_ServerCertificateValidation | [inline, private]
filter | Scenario15_ServerCertificateValidation | [private]
httpClient | Scenario15_ServerCertificateValidation | [private]
IgnoreErrorsAndCustomValidation_Checked(object sender, RoutedEventArgs e) | Scenario15_ServerCertificateValidation | [inline, private]
IsCertificateValidAsync(Certificate serverCert) | Scenario15_ServerCertificateValidation | [inline, private]
MyCustomServerCertificateValidator(HttpBaseProtocolFilter sender, HttpServerCustomValidationRequestedEventArgs args) | Scenario15_ServerCertificateValidation | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario15_ServerCertificateValidation | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario15_ServerCertificateValidation | [inline, protected]
rootPage | Scenario15_ServerCertificateValidation | [private]
Scenario15_ServerCertificateValidation() | Scenario15_ServerCertificateValidation | [inline]
Start_Click(object sender, RoutedEventArgs e) | Scenario15_ServerCertificateValidation | [inline, private]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicHologram/cppwinrt/BasicHologramMain.cpp Source File

  • BasicHologram
  • cppwinrt

BasicHologramMain.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "BasicHologramMain.h"
00003 #include "Common\DirectXHelper.h"
00004
00005 #include <windows.graphics.directx.direct3d11.interop.h>
00006
00007 using namespace BasicHologram;
00008 using namespace concurrency;
00009 using namespace Microsoft::WRL;
00010 using namespace std::placeholders;
00011 using namespace winrt::Windows::Foundation::Numerics;
00012 using namespace winrt::Windows::Gaming::Input;
00013 using namespace winrt::Windows::Graphics::Holographic;
00014 using namespace winrt::Windows::Graphics::DirectX::Direct3D11;
00015 using namespace winrt::Windows::Perception::Spatial;
00016 using namespace winrt::Windows::UI::Input::Spatial;
00017
00018 // Loads and initializes application assets when the application is loaded.
00019 BasicHologramMain::BasicHologramMain(std::shared_ptr<DX::DeviceResources> const& deviceResources) :
00020     m_deviceResources(deviceResources)
00021 {
00022     // Register to be notified if the device is lost or recreated.
00023     m_deviceResources->RegisterDeviceNotify(this);
00024
00025     // If connected, a game controller can also be used for input.
00026     m_gamepadAddedEventToken = Gamepad::GamepadAdded(bind(&BasicHologramMain::OnGamepadAdded, this, _1, _2));
00027     m_gamepadRemovedEventToken = Gamepad::GamepadRemoved(bind(&BasicHologramMain::OnGamepadRemoved, this, _1, _2));
00028
00029     for (Gamepad const& gamepad : Gamepad::Gamepads())
00030     {
00031         OnGamepadAdded(nullptr, gamepad);
00032     }
00033
00034     m_canGetHolographicDisplayForCamera = winrt::Windows::Foundation::Metadata::ApiInformation::IsPropertyPresent(L"Windows.Graphics.Holographic.HolographicCamera", L"Display");
00035     m_canGetDefaultHolographicDisplay = winrt::Windows::Foundation::Metadata::ApiInformation::IsMethodPresent(L"Windows.Graphics.Holographic.HolographicDisplay", L"GetDefault");
00036     m_canCommitDirect3D11DepthBuffer = winrt::Windows::Foundation::Metadata::ApiInformation::IsMethodPresent(L"Windows.Graphics.Holographic.HolographicCameraRenderingParameters", L"CommitDirect3D11DepthBuffer");
00037 }
00038
00039 void BasicHologramMain::SetHolographicSpace(HolographicSpace const& holographicSpace)
00040 {
00041     UnregisterHolographicEventHandlers();
00042
00043     m_holographicSpace = holographicSpace;
00044
00045     //
00046     // TODO: Add code here to initialize your holographic content.
00047     //
00048
00049 #ifdef DRAW_SAMPLE_CONTENT
00050     // Initialize the sample hologram.
00051     m_spinningCubeRenderer = std::make_unique<SpinningCubeRenderer>(m_deviceResources);
00052     m_spatialInputHandler = std::make_unique<SpatialInputHandler>();
00053 #endif
00054
00055     if (m_canGetDefaultHolographicDisplay)
00056     {
00057         // Subscribe for notifications about changes to the state of the default HolographicDisplay
00058         // and its SpatialLocator.
00059         m_holographicDisplayIsAvailableChangedEventToken = HolographicSpace::IsAvailableChanged(bind(&BasicHologramMain::OnHolographicDisplayIsAvailableChanged, this, _1, _2));
00060     }
00061
00062     // Acquire the current state of the default HolographicDisplay and its SpatialLocator.
00063     OnHolographicDisplayIsAvailableChanged(nullptr, nullptr);
00064
00065     // Respond to camera added events by creating any resources that are specific
00066     // to that camera, such as the back buffer render target view.
00067     // When we add an event handler for CameraAdded, the API layer will avoid putting
00068     // the new camera in new HolographicFrames until we complete the deferral we created
00069     // for that handler, or return from the handler without creating a deferral. This
00070     // allows the app to take more than one frame to finish creating resources and
00071     // loading assets for the new holographic camera.
00072     // This function should be registered before the app creates any HolographicFrames.
00073     m_cameraAddedToken = m_holographicSpace.CameraAdded(std::bind(&BasicHologramMain::OnCameraAdded, this, _1, _2));
00074
00075     // Respond to camera removed events by releasing resources that were created for that
00076     // camera.
00077     // When the app receives a CameraRemoved event, it releases all references to the back
00078     // buffer right away. This includes render target views, Direct2D target bitmaps, and so on.
00079     // The app must also ensure that the back buffer is not attached as a render target, as
00080     // shown in DeviceResources::ReleaseResourcesForBackBuffer.
00081     m_cameraRemovedToken = m_holographicSpace.CameraRemoved(std::bind(&BasicHologramMain::OnCameraRemoved, this, _1, _2));
00082
00083     // Notes on spatial tracking APIs:
00084     // * Stationary reference frames are designed to provide a best-fit position relative to the
00085     //   overall space. Individual positions within that reference frame are allowed to drift slightly
00086     //   as the device learns more about the environment.
00087     // * When precise placement of individual holograms is required, a SpatialAnchor should be used to
00088     //   anchor the individual hologram to a position in the real world - for example, a point the user
00089     //   indicates to be of special interest. Anchor positions do not drift, but can be corrected; the
00090     //   anchor will use the corrected position starting in the next frame after the correction has
00091     //   occurred.
00092 }
00093
00094 void BasicHologramMain::UnregisterHolographicEventHandlers()
00095 {
00096     if (m_holographicSpace != nullptr)
00097     {
00098         // Clear previous event registrations.
00099         m_holographicSpace.CameraAdded(m_cameraAddedToken);
00100         m_cameraAddedToken = {};
00101         m_holographicSpace.CameraRemoved(m_cameraRemovedToken);
00102         m_cameraRemovedToken = {};
00103     }
00104
00105     if (m_spatialLocator != nullptr)
00106     {
00107         m_spatialLocator.LocatabilityChanged(m_locatabilityChangedToken);
00108     }
00109 }
00110
00111 BasicHologramMain::~BasicHologramMain()
00112 {
00113     // Deregister device notification.
00114     m_deviceResources->RegisterDeviceNotify(nullptr);
00115
00116     UnregisterHolographicEventHandlers();
00117
00118     Gamepad::GamepadAdded(m_gamepadAddedEventToken);
00119     Gamepad::GamepadRemoved(m_gamepadRemovedEventToken);
00120     HolographicSpace::IsAvailableChanged(m_holographicDisplayIsAvailableChangedEventToken);
00121 }
00122
00123 // Updates the application state once per frame.
00124 HolographicFrame BasicHologramMain::Update()
00125 {
00126     // Before doing the timer update, there is some work to do per-frame
00127     // to maintain holographic rendering. First, we will get information
00128     // about the current frame.
00129
00130     // The HolographicFrame has information that the app needs in order
00131     // to update and render the current frame. The app begins each new
00132     // frame by calling CreateNextFrame.
00133     HolographicFrame holographicFrame = m_holographicSpace.CreateNextFrame();
00134
00135     // Get a prediction of where holographic cameras will be when this frame
00136     // is presented.
00137     HolographicFramePrediction prediction = holographicFrame.CurrentPrediction();
00138
00139     // Back buffers can change from frame to frame. Validate each buffer, and recreate
00140     // resource views and depth buffers as needed.
00141     m_deviceResources->EnsureCameraResources(holographicFrame, prediction);
00142
00143 #ifdef DRAW_SAMPLE_CONTENT
00144     if (m_stationaryReferenceFrame != nullptr)
00145     {
00146         // Check for new input state since the last frame.
00147         for (GamepadWithButtonState& gamepadWithButtonState : m_gamepads)
00148         {
00149             bool buttonDownThisUpdate = ((gamepadWithButtonState.gamepad.GetCurrentReading().Buttons & GamepadButtons::A) == GamepadButtons::A);
00150             if (buttonDownThisUpdate && !gamepadWithButtonState.buttonAWasPressedLastFrame)
00151             {
00152                 m_pointerPressed = true;
00153             }
00154             gamepadWithButtonState.buttonAWasPressedLastFrame = buttonDownThisUpdate;
00155         }
00156
00157         SpatialInteractionSourceState pointerState = m_spatialInputHandler->CheckForInput();
00158         SpatialPointerPose pose = nullptr;
00159         if (pointerState != nullptr)
00160         {
00161             pose = pointerState.TryGetPointerPose(m_stationaryReferenceFrame.CoordinateSystem());
00162         }
00163         else if (m_pointerPressed)
00164         {
00165             pose = SpatialPointerPose::TryGetAtTimestamp(m_stationaryReferenceFrame.CoordinateSystem(), prediction.Timestamp());
00166         }
00167         m_pointerPressed = false;
00168
00169         // When a Pressed gesture is detected, the sample hologram will be repositioned
00170         // two meters in front of the user.
00171         m_spinningCubeRenderer->PositionHologram(pose);
00172     }
00173 #endif
00174
00175     m_timer.Tick([this]()
00176     {
00177         //
00178         // TODO: Update scene objects.
00179         //
00180         // Put time-based updates here. By default this code will run once per frame,
00181         // but if you change the StepTimer to use a fixed time step this code will
00182         // run as many times as needed to get to the current step.
00183         //
00184
00185 #ifdef DRAW_SAMPLE_CONTENT
00186         m_spinningCubeRenderer->Update(m_timer);
00187 #endif
00188     });
00189     if (!m_canCommitDirect3D11DepthBuffer)
00190     {
00191         // On versions of the platform that do not support the CommitDirect3D11DepthBuffer API, we can control
00192         // image stabilization by setting a focus point with optional plane normal and velocity.
00193         for (HolographicCameraPose const& cameraPose : prediction.CameraPoses())
00194         {
00195 #ifdef DRAW_SAMPLE_CONTENT
00196             // The HolographicCameraRenderingParameters class provides access to set
00197             // the image stabilization parameters.
00198             HolographicCameraRenderingParameters renderingParameters = holographicFrame.GetRenderingParameters(cameraPose);
00199
00200             // SetFocusPoint informs the system about a specific point in your scene to
00201             // prioritize for image stabilization. The focus point is set independently
00202                 // for each holographic camera. When setting the focus point, put it on or
00203                 // near content that the user is looking at.
00204                 // In this example, we put the focus point at the center of the sample hologram.
00205                 // You can also set the relative velocity and facing of the stabilization
00206                 // plane using overloads of this method.
00207             if (m_stationaryReferenceFrame != nullptr)
00208             {
00209                 renderingParameters.SetFocusPoint(
00210                     m_stationaryReferenceFrame.CoordinateSystem(),
00211                     m_spinningCubeRenderer->GetPosition()
00212                 );
00213             }
00214 #endif
00215         }
00216     }
00217
00218     // The holographic frame will be used to get up-to-date view and projection matrices and
00219     // to present the swap chain.
00220     return holographicFrame;
00221 }
00222
00223 // Renders the current frame to each holographic camera, according to the
00224 // current application and spatial positioning state. Returns true if the
00225 // frame was rendered to at least one camera.
00226 bool BasicHologramMain::Render(HolographicFrame const& holographicFrame)
00227 {
00228     // Don't try to render anything before the first Update.
00229     if (m_timer.GetFrameCount() == 0)
00230     {
00231         return false;
00232     }
00233
00234     //
00235     // TODO: Add code for pre-pass rendering here.
00236     //
00237     // Take care of any tasks that are not specific to an individual holographic
00238     // camera. This includes anything that doesn't need the final view or projection
00239     // matrix, such as lighting maps.
00240     //
00241
00242     // Lock the set of holographic camera resources, then draw to each camera
00243     // in this frame.
00244     return m_deviceResources->UseHolographicCameraResources<bool>(
00245         [this, holographicFrame](std::map<UINT32, std::unique_ptr<DX::CameraResources>>& cameraResourceMap)
00246     {
00247         // Up-to-date frame predictions enhance the effectiveness of image stablization and
00248         // allow more accurate positioning of holograms.
00249         holographicFrame.UpdateCurrentPrediction();
00250         HolographicFramePrediction prediction = holographicFrame.CurrentPrediction();
00251
00252         bool atLeastOneCameraRendered = false;
00253         for (HolographicCameraPose const& cameraPose : prediction.CameraPoses())
00254         {
00255             // This represents the device-based resources for a HolographicCamera.
00256             DX::CameraResources* pCameraResources = cameraResourceMap[cameraPose.HolographicCamera().Id()].get();
00257
00258             // Get the device context.
00259             const auto context = m_deviceResources->GetD3DDeviceContext();
00260             const auto depthStencilView = pCameraResources->GetDepthStencilView();
00261
00262             // Set render targets to the current holographic camera.
00263             ID3D11RenderTargetView *const targets[1] = { pCameraResources->GetBackBufferRenderTargetView() };
00264             context->OMSetRenderTargets(1, targets, depthStencilView);
00265
00266             // Clear the back buffer and depth stencil view.
00267             if (m_canGetHolographicDisplayForCamera &&
00268                 cameraPose.HolographicCamera().Display().IsOpaque())
00269             {
00270                 context->ClearRenderTargetView(targets[0], DirectX::Colors::CornflowerBlue);
00271             }
00272             else
00273             {
00274                 context->ClearRenderTargetView(targets[0], DirectX::Colors::Transparent);
00275             }
00276             context->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
00277
00278             //
00279             // TODO: Replace the sample content with your own content.
00280             //
00281             // Notes regarding holographic content:
00282             //    * For drawing, remember that you have the potential to fill twice as many pixels
00283             //      in a stereoscopic render target as compared to a non-stereoscopic render target
00284             //      of the same resolution. Avoid unnecessary or repeated writes to the same pixel,
00285             //      and only draw holograms that the user can see.
00286             //    * To help occlude hologram geometry, you can create a depth map using geometry
00287             //      data obtained via the surface mapping APIs. You can use this depth map to avoid
00288             //      rendering holograms that are intended to be hidden behind tables, walls,
00289             //      monitors, and so on.
00290             //    * On HolographicDisplays that are transparent, black pixels will appear transparent
00291             //      to the user. On such devices, you should clear the screen to Transparent as shown
00292             //      above. You should still use alpha blending to draw semitransparent holograms.
00293             //
00294
00295
00296             // The view and projection matrices for each holographic camera will change
00297             // every frame. This function refreshes the data in the constant buffer for
00298             // the holographic camera indicated by cameraPose.
00299             if (m_stationaryReferenceFrame)
00300             {
00301                 pCameraResources->UpdateViewProjectionBuffer(m_deviceResources, cameraPose, m_stationaryReferenceFrame.CoordinateSystem());
00302             }
00303
00304             // Attach the view/projection constant buffer for this camera to the graphics pipeline.
00305             bool cameraActive = pCameraResources->AttachViewProjectionBuffer(m_deviceResources);
00306
00307 #ifdef DRAW_SAMPLE_CONTENT
00308             // Only render world-locked content when positional tracking is active.
00309             if (cameraActive)
00310             {
00311                 // Draw the sample hologram.
00312                 m_spinningCubeRenderer->Render();
00313                 if (m_canCommitDirect3D11DepthBuffer)
00314                 {
00315                     // On versions of the platform that support the CommitDirect3D11DepthBuffer API, we can
00316                     // provide the depth buffer to the system, and it will use depth information to stabilize
00317                     // the image at a per-pixel level.
00318                     HolographicCameraRenderingParameters renderingParameters = holographicFrame.GetRenderingParameters(cameraPose);
00319
00320                     IDirect3DSurface interopSurface = DX::CreateDepthTextureInteropObject(pCameraResources->GetDepthStencilTexture2D());
00321
00322                     // Calling CommitDirect3D11DepthBuffer causes the system to queue Direct3D commands to
00323                     // read the depth buffer. It will then use that information to stabilize the image as
00324                     // the HolographicFrame is presented.
00325                     renderingParameters.CommitDirect3D11DepthBuffer(interopSurface);
00326                 }
00327             }
00328 #endif
00329             atLeastOneCameraRendered = true;
00330         }
00331
00332         return atLeastOneCameraRendered;
00333     });
00334 }
00335
00336 void BasicHologramMain::SaveAppState()
00337 {
00338     //
00339     // TODO: Insert code here to save your app state.
00340     //       This method is called when the app is about to suspend.
00341     //
00342     //       For example, store information in the SpatialAnchorStore.
00343     //
00344 }
00345
00346 void BasicHologramMain::LoadAppState()
00347 {
00348     //
00349     // TODO: Insert code here to load your app state.
00350     //       This method is called when the app resumes.
00351     //
00352     //       For example, load information from the SpatialAnchorStore.
00353     //
00354 }
00355
00356 void BasicHologramMain::OnPointerPressed()
00357 {
00358     m_pointerPressed = true;
00359 }
00360
00361 // Notifies classes that use Direct3D device resources that the device resources
00362 // need to be released before this method returns.
00363 void BasicHologramMain::OnDeviceLost()
00364 {
00365 #ifdef DRAW_SAMPLE_CONTENT
00366     m_spinningCubeRenderer->ReleaseDeviceDependentResources();
00367 #endif
00368 }
00369
00370 // Notifies classes that use Direct3D device resources that the device resources
00371 // may now be recreated.
00372 void BasicHologramMain::OnDeviceRestored()
00373 {
00374 #ifdef DRAW_SAMPLE_CONTENT
00375     m_spinningCubeRenderer->CreateDeviceDependentResources();
00376 #endif
00377 }
00378
00379 void BasicHologramMain::OnLocatabilityChanged(SpatialLocator const& sender, winrt::Windows::Foundation::IInspectable const& args)
00380 {
00381     switch (sender.Locatability())
00382     {
00383     case SpatialLocatability::Unavailable:
00384         // Holograms cannot be rendered.
00385     {
00386         std::wstring message = L"Warning! Positional tracking is " + std::to_wstring(int(sender.Locatability())) + L".\n";
00387         OutputDebugStringW(message.c_str());
00388     }
00389     break;
00390
00391     // In the following three cases, it is still possible to place holograms using a
00392     // SpatialLocatorAttachedFrameOfReference.
00393     case SpatialLocatability::PositionalTrackingActivating:
00394         // The system is preparing to use positional tracking.
00395
00396     case SpatialLocatability::OrientationOnly:
00397         // Positional tracking has not been activated.
00398
00399     case SpatialLocatability::PositionalTrackingInhibited:
00400         // Positional tracking is temporarily inhibited. User action may be required
00401         // in order to restore positional tracking.
00402         break;
00403
00404     case SpatialLocatability::PositionalTrackingActive:
00405         // Positional tracking is active. World-locked content can be rendered.
00406         break;
00407     }
00408 }
00409
00410 void BasicHologramMain::OnCameraAdded(
00411     HolographicSpace const& sender,
00412     HolographicSpaceCameraAddedEventArgs const& args
00413 )
00414 {
00415     winrt::Windows::Foundation::Deferral deferral = args.GetDeferral();
00416     HolographicCamera holographicCamera = args.Camera();
00417     create_task([this, deferral, holographicCamera]()
00418     {
00419         //
00420         // TODO: Allocate resources for the new camera and load any content specific to
00421         //       that camera. Note that the render target size (in pixels) is a property
00422         //       of the HolographicCamera object, and can be used to create off-screen
00423         //       render targets that match the resolution of the HolographicCamera.
00424         //
00425
00426         // Create device-based resources for the holographic camera and add it to the list of
00427         // cameras used for updates and rendering. Notes:
00428         //   * Since this function may be called at any time, the AddHolographicCamera function
00429         //     waits until it can get a lock on the set of holographic camera resources before
00430         //     adding the new camera. At 60 frames per second this wait should not take long.
00431         //   * A subsequent Update will take the back buffer from the RenderingParameters of this
00432         //     camera's CameraPose and use it to create the ID3D11RenderTargetView for this camera.
00433         //     Content can then be rendered for the HolographicCamera.
00434         m_deviceResources->AddHolographicCamera(holographicCamera);
00435
00436         // Holographic frame predictions will not include any information about this camera until
00437         // the deferral is completed.
00438         deferral.Complete();
00439     });
00440 }
00441
00442 void BasicHologramMain::OnCameraRemoved(
00443     HolographicSpace const& sender,
00444     HolographicSpaceCameraRemovedEventArgs const& args
00445 )
00446 {
00447     create_task([this]()
00448     {
00449         //
00450         // TODO: Asynchronously unload or deactivate content resources (not back buffer
00451         //       resources) that are specific only to the camera that was removed.
00452         //
00453     });
00454
00455     // Before letting this callback return, ensure that all references to the back buffer
00456     // are released.
00457     // Since this function may be called at any time, the RemoveHolographicCamera function
00458     // waits until it can get a lock on the set of holographic camera resources before
00459     // deallocating resources for this camera. At 60 frames per second this wait should
00460     // not take long.
00461     m_deviceResources->RemoveHolographicCamera(args.Camera());
00462 }
00463
00464 void BasicHologramMain::OnGamepadAdded(winrt::Windows::Foundation::IInspectable, Gamepad const& args)
00465 {
00466     for (GamepadWithButtonState const& gamepadWithButtonState : m_gamepads)
00467     {
00468         if (args == gamepadWithButtonState.gamepad)
00469         {
00470             // This gamepad is already in the list.
00471             return;
00472         }
00473     }
00474
00475     GamepadWithButtonState newGamepad = { args, false };
00476     m_gamepads.push_back(newGamepad);
00477 }
00478
00479 void BasicHologramMain::OnGamepadRemoved(winrt::Windows::Foundation::IInspectable, Gamepad const& args)
00480 {
00481     m_gamepads.erase(std::remove_if(m_gamepads.begin(), m_gamepads.end(), [&](GamepadWithButtonState& gamepadWithState)
00482         {
00483             return gamepadWithState.gamepad == args;
00484         }),
00485         m_gamepads.end());
00486 }
00487
00488 void BasicHologramMain::OnHolographicDisplayIsAvailableChanged(winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable)
00489 {
00490     // Get the spatial locator for the default HolographicDisplay, if one is available.
00491     SpatialLocator spatialLocator = nullptr;
00492     if (m_canGetDefaultHolographicDisplay)
00493     {
00494         HolographicDisplay defaultHolographicDisplay = HolographicDisplay::GetDefault();
00495         if (defaultHolographicDisplay)
00496         {
00497             spatialLocator = defaultHolographicDisplay.SpatialLocator();
00498         }
00499     }
00500     else
00501     {
00502         spatialLocator = SpatialLocator::GetDefault();
00503     }
00504
00505     if (m_spatialLocator != spatialLocator)
00506     {
00507         // If the spatial locator is disconnected or replaced, we should discard all state that was
00508         // based on it.
00509         if (m_spatialLocator != nullptr)
00510         {
00511             m_spatialLocator.LocatabilityChanged(m_locatabilityChangedToken);
00512             m_spatialLocator = nullptr;
00513         }
00514
00515         m_stationaryReferenceFrame = nullptr;
00516
00517         if (spatialLocator != nullptr)
00518         {
00519             // Use the SpatialLocator from the default HolographicDisplay to track the motion of the device.
00520             m_spatialLocator = spatialLocator;
00521
00522             // Respond to changes in the positional tracking state.
00523             m_locatabilityChangedToken = m_spatialLocator.LocatabilityChanged(std::bind(&BasicHologramMain::OnLocatabilityChanged, this, _1, _2));
00524
00525             // The simplest way to render world-locked holograms is to create a stationary reference frame
00526             // based on a SpatialLocator. This is roughly analogous to creating a "world" coordinate system
00527             // with the origin placed at the device's position as the app is launched.
00528             m_stationaryReferenceFrame = m_spatialLocator.CreateStationaryFrameOfReferenceAtCurrentLocation();
00529         }
00530     }
00531 }
00532
00533
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cpp/Scenario6_ManipulatingCursorAttributes.xaml.cpp Source File

  • LineDisplay
  • cpp

Scenario6_ManipulatingCursorAttributes.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario6_ManipulatingCursorAttributes.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Devices::PointOfService;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Data;
00025 using namespace Windows::UI::Xaml::Navigation;
00026
00027 Scenario6_ManipulatingCursorAttributes::Scenario6_ManipulatingCursorAttributes()
00028 {
00029     InitializeComponent();
00030     DataContext = this;
00031 }
00032
00033 void Scenario6_ManipulatingCursorAttributes::OnNavigatedTo(NavigationEventArgs^ e)
00034 {
00035     InitializeAsync();
00036 }
00037
00038 void Scenario6_ManipulatingCursorAttributes::OnNavigatedFrom(NavigationEventArgs^ e)
00039 {
00040     delete lineDisplay;
00041     lineDisplay = nullptr;
00042 }
00043
00044 task<void> Scenario6_ManipulatingCursorAttributes::InitializeAsync()
00045 {
00046     UpdateButton->IsEnabled = false;
00047     DisplayTextButton->IsEnabled = false;
00048     ResetButton->IsEnabled = false;
00049     CursorTypeComboBox->Items->Clear();
00050
00051     lineDisplay = co_await rootPage->ClaimScenarioLineDisplayAsync();
00052
00053     CursorTypeComboBox->IsEnabled = (lineDisplay != nullptr) && lineDisplay->DefaultWindow->Cursor->CanCustomize;
00054     if (CursorTypeComboBox->IsEnabled)
00055     {
00056         if (lineDisplay->DefaultWindow->Cursor->IsBlockSupported)
00057         {
00058             Helpers::AddItem(CursorTypeComboBox, LineDisplayCursorType::Block);
00059         }
00060
00061         if (lineDisplay->DefaultWindow->Cursor->IsHalfBlockSupported)
00062         {
00063             Helpers::AddItem(CursorTypeComboBox, LineDisplayCursorType::HalfBlock);
00064         }
00065
00066         if (lineDisplay->DefaultWindow->Cursor->IsOtherSupported)
00067         {
00068             Helpers::AddItem(CursorTypeComboBox, LineDisplayCursorType::Other);
00069         }
00070
00071         if (lineDisplay->DefaultWindow->Cursor->IsReverseSupported)
00072         {
00073             Helpers::AddItem(CursorTypeComboBox, LineDisplayCursorType::Reverse);
00074         }
00075
00076         if (lineDisplay->DefaultWindow->Cursor->IsUnderlineSupported)
00077         {
00078             Helpers::AddItem(CursorTypeComboBox, LineDisplayCursorType::Underline);
00079         }
00080
00081         if (SupportedCursorTypes->Size > 0)
00082         {
00083             CursorTypeComboBox->SelectedIndex = 0;
00084         }
00085     }
00086
00087     CursorTypeComboBox->IsEnabled = true;//rjc
00088     Helpers::AddItem(CursorTypeComboBox, LineDisplayCursorType::HalfBlock);
00089     CursorTypeComboBox->SelectedIndex = 0;
00090
00091     IsAutoAdvanceEnabledCheckbox->IsEnabled = (lineDisplay != nullptr);
00092
00093     IsBlinkEnabledCheckbox->IsEnabled = (lineDisplay != nullptr) && lineDisplay->DefaultWindow->Cursor->IsBlinkSupported;
00094     SetCursorPositionCheckbox->IsEnabled = (lineDisplay != nullptr);
00095     UpdateButton->IsEnabled = (lineDisplay != nullptr);
00096     DisplayTextButton->IsEnabled = (lineDisplay != nullptr);
00097
00098     ResetButton->IsEnabled = true;
00099 }
00100
00101 void Scenario6_ManipulatingCursorAttributes::UpdateButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00102 {
00103     invoke_async_lambda([=]() -> task<void>
00104     {
00105         LineDisplayCursorAttributes^ cursorAttributes = lineDisplay->DefaultWindow->Cursor->GetAttributes();
00106         cursorAttributes->IsAutoAdvanceEnabled = IsAutoAdvanceEnabledCheckbox->IsChecked->Value;
00107
00108         if (lineDisplay->DefaultWindow->Cursor->CanCustomize)
00109         {
00110             cursorAttributes->CursorType = Helpers::GetSelectedItemTag<LineDisplayCursorType>(CursorTypeComboBox);
00111         }
00112
00113         if (lineDisplay->DefaultWindow->Cursor->IsBlinkSupported)
00114         {
00115             cursorAttributes->IsBlinkEnabled = IsBlinkEnabledCheckbox->IsChecked->Value;
00116         }
00117
00118         if (SetCursorPositionCheckbox->IsChecked->Value)
00119         {
00120             Point position = Point
00121             {
00122                 Helpers::ParseUIntWithFallback(CursorPositionXTextBox, -1.0f),
00123                 Helpers::ParseUIntWithFallback(CursorPositionYTextBox, -1.0f),
00124             };
00125
00126             Size windowSizeInCharacters = lineDisplay->DefaultWindow->SizeInCharacters;
00127             if ((position.X < 0) || (position.X >= windowSizeInCharacters.Width) ||
00128                 (position.Y < 0) || (position.Y >= windowSizeInCharacters.Height))
00129             {
00130                 rootPage->NotifyUser("Cursor position must be within the window", NotifyType::ErrorMessage);
00131                 return;
00132             }
00133
00134             cursorAttributes->Position = position;
00135         }
00136
00137         if (co_await lineDisplay->DefaultWindow->Cursor->TryUpdateAttributesAsync(cursorAttributes))
00138         {
00139             rootPage->NotifyUser("Cursor updated.", NotifyType::StatusMessage);
00140         }
00141         else
00142         {
00143             rootPage->NotifyUser("Failed to update the cursor.", NotifyType::ErrorMessage);
00144         }
00145     });
00146 }
00147
00148 void Scenario6_ManipulatingCursorAttributes::DisplayTextButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00149 {
00150     invoke_async_lambda([=]() -> task<void>
00151     {
00152         if (co_await lineDisplay->DefaultWindow->TryDisplayTextAsync("Text"))
00153         {
00154             rootPage->NotifyUser("Text displayed.", NotifyType::StatusMessage);
00155         }
00156         else
00157         {
00158             rootPage->NotifyUser("Failed to display text.", NotifyType::ErrorMessage);
00159         }
00160     });
00161 }
00162
00163 void Scenario6_ManipulatingCursorAttributes::ResetButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00164 {
00165     invoke_async_lambda([=]()->task<void>
00166     {
00167         delete lineDisplay;
00168         lineDisplay = nullptr;
00169         co_await InitializeAsync();
00170     });
00171 }
Generated on Fri Nov 15 2024 22:20:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: OCR/cppwinrt/OcrFileImage.h Source File

  • OCR
  • cppwinrt

OcrFileImage.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include "pch.h"
00004 #include "MainPage.h"
00005 #include "WordOverlay.h"
00006 #include "OcrFileImage.g.h"
00007
00008 namespace winrt::SDKTemplate::implementation
00009 {
00010     struct OcrFileImage : OcrFileImageT<OcrFileImage>
00011     {
00012         OcrFileImage();
00013
00014         fire_and_forget OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00015
00016         fire_and_forget ExtractButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00017         void UserLanguageToggle_Toggled(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00018
00019         fire_and_forget SampleButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00020         Windows::Foundation::IAsyncAction LoadButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00021         void LanguageList_SelectionChanged(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00022         void PreviewImage_SizeChanged(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023
00024     private:
00025         Windows::Foundation::IAsyncAction LoadSampleImageAsync();
00026         Windows::Foundation::IAsyncAction LoadImageAsync(Windows::Storage::StorageFile const& file);
00027
00028         void UpdateAvailableLanguages();
00029         void ClearResults();
00030         void UpdateWordBoxTransform();
00031
00032     private:
00033         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00034         Windows::Graphics::Imaging::SoftwareBitmap bitmap{ nullptr };
00035         std::vector<com_ptr<WordOverlay>> wordBoxes;
00036
00037     };
00038 }
00039
00040 namespace winrt::SDKTemplate::factory_implementation
00041 {
00042     struct OcrFileImage : OcrFileImageT<OcrFileImage, implementation::OcrFileImage>
00043     {
00044     };
00045 }
Generated on Fri Nov 15 2024 22:20:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MasterDetailPage Member List

This is the complete list of members for MasterDetailPage, including all inherited members.
_lastSelectedItem | MasterDetailPage | [private]
AdaptiveStates_CurrentStateChanged(object sender, VisualStateChangedEventArgs e) | MasterDetailPage | [inline, private]
DisableContentTransitions() | MasterDetailPage | [inline, private]
EnableContentTransitions() | MasterDetailPage | [inline, private]
LayoutRoot_Loaded(object sender, RoutedEventArgs e) | MasterDetailPage | [inline, private]
MasterDetailPage() | MasterDetailPage | [inline]
MasterListView_ItemClick(object sender, ItemClickEventArgs e) | MasterDetailPage | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | MasterDetailPage | [inline, protected]
UpdateForVisualState(VisualState newState, VisualState oldState=null) | MasterDetailPage | [inline, private]
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_DisplayDepthColorIR Member List

This is the complete list of members for Scenario1_DisplayDepthColorIR, including all inherited members.
_frameRenderers | Scenario1_DisplayDepthColorIR | [private]
_groupSelectionIndex | Scenario1_DisplayDepthColorIR | [private]
_logger | Scenario1_DisplayDepthColorIR | [private]
_mediaCapture | Scenario1_DisplayDepthColorIR | [private]
_sourceReaders | Scenario1_DisplayDepthColorIR | [private]
CleanupMediaCaptureAsync() | Scenario1_DisplayDepthColorIR | [inline, private]
FrameReader_FrameArrived(MediaFrameReader sender, MediaFrameArrivedEventArgs args) | Scenario1_DisplayDepthColorIR | [inline, private]
InitializeMediaCaptureAsync(MediaFrameSourceGroup sourceGroup) | Scenario1_DisplayDepthColorIR | [inline, private]
NextButton_Click(object eventSender, RoutedEventArgs eventArgs) | Scenario1_DisplayDepthColorIR | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario1_DisplayDepthColorIR | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario1_DisplayDepthColorIR | [inline, protected]
PickNextMediaSourceAsync() | Scenario1_DisplayDepthColorIR | [inline, private]
PickNextMediaSourceWorkerAsync() | Scenario1_DisplayDepthColorIR | [inline, private]
Scenario1_DisplayDepthColorIR() | Scenario1_DisplayDepthColorIR | [inline]
Generated on Fri Nov 15 2024 22:23:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cs/AdventureWorks/ViewModel/TripVoiceCommand.cs Source File

  • CortanaVoiceCommand
  • cs
  • AdventureWorks
  • ViewModel

TripVoiceCommand.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017
00018 namespace AdventureWorks.ViewModel
00019 {
00020     /// <summary>
00021     /// Simple struct to pass voice-command arguments to the appropriate view, in order to execute the
00022     /// action requested by the user. Reference OnActivated() in App.xaml.cs, and AdventureWorksCommands.xml
00023     /// for context on what should go in here.
00024     /// </summary>
00025     public struct TripVoiceCommand
00026     {
00027         public string voiceCommand;
00028         public string commandMode;
00029         public string textSpoken;
00030         public string destination;
00031
00032         /// <summary>
00033         /// Set up the voice command struct with the provided details about the voice command.
00034         /// Oriented around the "showTripToDestination" VCD command (See AdventureWorksCommands.xml)
00035         /// </summary>
00036         /// <param name="voiceCommand">The voice command (the Command element in the VCD xml) </param>
00037         /// <param name="commandMode">The command mode (whether it was voice or text activation)</param>
00038         /// <param name="textSpoken">The raw voice command text.</param>
00039         /// <param name="destination">The destination parameter.</param>
00040         public TripVoiceCommand(string voiceCommand, string commandMode, string textSpoken, string destination)
00041         {
00042             this.voiceCommand = voiceCommand;
00043             this.commandMode = commandMode;
00044             this.textSpoken = textSpoken;
00045             this.destination = destination;
00046         }
00047     }
00048 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cs/Scenario7_B2B.xaml.cs Source File

  • Store
  • cs

Scenario7_B2B.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Data.Json;
00016 using Windows.Services.Store;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.Web.Http;
00019 using Windows.Web.Http.Headers;
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// For more details on the business to business APIs, see:
00025     /// https://msdn.microsoft.com/en-us/library/windows/apps/mt609002.aspx
00026     /// </summary>
00027     public sealed partial class Scenario7_B2B : Page
00028     {
00029         private MainPage rootPage = MainPage.Current;
00030         private StoreContext storeContext = StoreContext.GetDefault();
00031
00032         // Note: "tenant", "clientId", "clientSecret" and "appIdUri" will need to be updated based on your particular
00033         // Azure Active Directory configuration. See the README for more information.
00034         // https://msdn.microsoft.com/en-us/library/azure/dn645542.aspx
00035         readonly string tenantId = "00000000-0000-0000-0000-000000000000";
00036         readonly string clientId = "00000000-0000-0000-0000-000000000000";
00037         readonly string clientSecret = "00000000000000000000000000000000000000000000";
00038         readonly string appIdUri = "https://contoso.onmicrosoft.com";
00039
00040         public Scenario7_B2B()
00041         {
00042             this.InitializeComponent();
00043         }
00044
00045         private async void GetCustomerCollectionsId()
00046         {
00047             string aadToken = await GetTokenFromAzureOAuthAsync();
00048             if (!String.IsNullOrEmpty(aadToken))
00049             {
00050                 string id = await storeContext.GetCustomerCollectionsIdAsync(aadToken, "kim@example.com");
00051                 Output.Text = id;
00052                 if (String.IsNullOrEmpty(id))
00053                 {
00054                     rootPage.NotifyUser("GetCustomerCollectionsIdAsync failed.", NotifyType.ErrorMessage);
00055                 }
00056             }
00057         }
00058
00059         private async void GetCustomerPurchaseId()
00060         {
00061             String aadToken = await GetTokenFromAzureOAuthAsync();
00062             if (!String.IsNullOrEmpty(aadToken))
00063             {
00064                 string id = await storeContext.GetCustomerPurchaseIdAsync(aadToken, "kim@example.com");
00065                 Output.Text = id;
00066                 if (String.IsNullOrEmpty(id))
00067                 {
00068                     rootPage.NotifyUser("GetCustomerPurchaseIdAsync failed.", NotifyType.ErrorMessage);
00069                 }
00070             }
00071         }
00072
00073         private async Task<string> GetTokenFromAzureOAuthAsync()
00074         {
00075             var content = new HttpFormUrlEncodedContent(new Dictionary<string, string>
00076             {
00077                 { "grant_type", "client_credentials" },
00078                 { "client_id", clientId },
00079                 { "client_secret", clientSecret },
00080                 { "resource", appIdUri },
00081             });
00082             content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");
00083             try
00084             {
00085                 HttpClient client = new HttpClient();
00086                 HttpResponseMessage result = await client.PostAsync(
00087                     new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/token"), content);
00088
00089                 string responseString = await result.Content.ReadAsStringAsync();
00090                 JsonValue response = JsonValue.Parse(responseString);
00091
00092                 return response.GetObject().GetNamedString("access_token");
00093             }
00094             catch (Exception ex)
00095             {
00096                 // Networking errors in PostAsync are reported as exceptions.
00097                 // JSON parsing errors are also reported as exceptions.
00098                 Output.Text = $"Failed to load Azure OAuth Token: {ex}";
00099                 return String.Empty;
00100             }
00101         }
00102     }
00103 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BoolToVisibilityConverter Member List

This is the complete list of members for BoolToVisibilityConverter, including all inherited members.
Convert(object value, Type targetType, object parameter, string language) | BoolToVisibilityConverter | [inline, private]
Convert(object value, Type targetType, object parameter, string language) | BoolToVisibilityConverter | [inline, private]
ConvertBack(object value, Type targetType, object parameter, string language) | BoolToVisibilityConverter | [inline, private]
ConvertBack(object value, Type targetType, object parameter, string language) | BoolToVisibilityConverter | [inline, private]
Generated on Fri Nov 15 2024 22:24:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLInProcessWinRTComponent/cpp/cpp/pch.cpp Source File

  • WRLInProcessWinRTComponent
  • cpp
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/Scenario4.xaml.cpp Source File

  • WindowsAudioSession
  • cpp

Scenario4.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario4.xaml.cpp
00013 // Implementation of the Scenario4 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario4.xaml.h"
00018
00019 using namespace SDKSample;
00020 using namespace SDKSample::WASAPIAudio;
00021
00022 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Media;
00025 using namespace Windows::UI::Core;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030 Scenario4::Scenario4() :
00031     m_IsMFLoaded( false ),
00032     m_StateChangedEvent( nullptr ),
00033     m_spCapture( nullptr )
00034 {
00035     InitializeComponent();
00036
00037     // Initialize MF
00038     HRESULT hr = MFStartup( MF_VERSION, MFSTARTUP_LITE );
00039     if (SUCCEEDED( hr ))
00040     {
00041         m_IsMFLoaded = true;
00042     }
00043     else
00044     {
00045         ThrowIfFailed( hr );
00046     }
00047
00048     m_CoreDispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;
00049     m_Oscilloscope = safe_cast<Windows::UI::Xaml::Shapes::Polyline^>(static_cast<IFrameworkElement^>(this)->FindName("Oscilloscope"));
00050 }
00051
00052 Scenario4::~Scenario4()
00053 {
00054     if (m_deviceStateChangeToken.Value != 0)
00055     {
00056         m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00057
00058         m_StateChangedEvent = nullptr;
00059         m_deviceStateChangeToken.Value = 0;
00060     }
00061
00062     if (m_plotDataReadyToken.Value != 0)
00063     {
00064         PlotDataReadyEvent::PlotDataReady -= m_plotDataReadyToken;
00065         m_plotDataReadyToken.Value = 0;
00066     }
00067
00068     // Uninitialize MF
00069     if (m_IsMFLoaded)
00070     {
00071         MFShutdown();
00072         m_IsMFLoaded = false;
00073     }
00074 }
00075
00076 /// <summary>
00077 /// Invoked when this page is about to be displayed in a Frame.
00078 /// </summary>
00079 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00080 /// property is typically used to configure the page.</param>
00081 void Scenario4::OnNavigatedTo(NavigationEventArgs^ e)
00082 {
00083     // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00084     // as NotifyUser()
00085     rootPage = MainPage::Current;
00086 }
00087
00088 /// <summary>
00089 /// Invoked when about to leave this page.
00090 /// </summary>
00091 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00092 /// property is typically used to configure the page.</param>
00093 void Scenario4::OnNavigatedFrom(NavigationEventArgs^ e)
00094 {
00095     if (nullptr != m_StateChangedEvent)
00096     {
00097         DeviceState deviceState = m_StateChangedEvent->GetState();
00098
00099         if (deviceState == DeviceState::DeviceStateCapturing)
00100         {
00101             StopCapture( this, e );
00102         }
00103     }
00104 }
00105
00106 #pragma region UI Related Code
00107 void Scenario4::ShowStatusMessage( Platform::String^ str, NotifyType messageType )
00108 {
00109     m_CoreDispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00110         [this, str, messageType]()
00111     {
00112         rootPage->NotifyUser( str, messageType );
00113     }));
00114 }
00115
00116 // Updates transport controls based on current playstate
00117 void Scenario4::UpdateMediaControlUI( DeviceState deviceState )
00118 {
00119     switch( deviceState )
00120     {
00121     case DeviceState::DeviceStateCapturing:
00122         btnStartCapture->IsEnabled = false;
00123         btnStopCapture->IsEnabled = true;
00124         toggleMinimumLatency->IsEnabled = false;
00125         break;
00126
00127     case DeviceState::DeviceStateStopped:
00128         btnStartCapture->IsEnabled = true;
00129         btnStopCapture->IsEnabled = false;
00130         toggleMinimumLatency->IsEnabled = true;
00131         break;
00132
00133     case DeviceState::DeviceStateInitialized:
00134     case DeviceState::DeviceStateStarting:
00135     case DeviceState::DeviceStateStopping:
00136     case DeviceState::DeviceStateFlushing:
00137     case DeviceState::DeviceStateInError:
00138         btnStartCapture->IsEnabled = false;
00139         btnStopCapture->IsEnabled = false;
00140         break;
00141     }
00142 }
00143 #pragma endregion
00144
00145 #pragma region UI Event Handlers
00146 void Scenario4::btnStartCapture_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00147 {
00148     ShowStatusMessage( "", NotifyType::StatusMessage );
00149     InitializeCapture( sender, e );
00150 }
00151
00152 void Scenario4::btnStopCapture_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00153 {
00154     StopCapture( sender, e );
00155 }
00156 #pragma endregion
00157
00158 // Event callback from WASAPI capture for changes in device state
00159 void Scenario4::OnDeviceStateChange( Object^ sender, DeviceStateChangedEventArgs^ e )
00160 {
00161     String^ strMessage = "";
00162
00163     // Get the current time for messages
00164     auto t = Windows::Globalization::DateTimeFormatting::DateTimeFormatter::LongTime;
00165     Windows::Globalization::Calendar^ calendar = ref new Windows::Globalization::Calendar();
00166     calendar->SetToNow();
00167
00168     // Update Control Buttons
00169     m_CoreDispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00170         [this, e]()
00171     {
00172         UpdateMediaControlUI( e->State );
00173     }));
00174
00175     // Handle state specific messages
00176     switch( e->State )
00177     {
00178     case DeviceState::DeviceStateInitialized:
00179         m_spCapture->StartCaptureAsync();
00180         break;
00181
00182     case DeviceState::DeviceStateCapturing:
00183         if (m_IsLowLatency == true)
00184         {
00185             strMessage = "Capture Started (minimum latency) @" + t->Format(calendar->GetDateTime());
00186         }
00187         else
00188         {
00189             strMessage = "Capture Started (normal latency) @" + t->Format(calendar->GetDateTime());
00190         }
00191
00192         ShowStatusMessage( strMessage, NotifyType::StatusMessage );
00193         break;
00194
00195     case DeviceState::DeviceStateDiscontinuity:
00196         {
00197             m_DiscontinuityCount++;
00198
00199             // Should always have a discontinuity when starting the capture, so will disregard it
00200             if (m_DiscontinuityCount > 1)
00201             {
00202                 strMessage = "DISCONTINUITY DETECTED: " + t->Format( calendar->GetDateTime() ) + " (Count = " + (m_DiscontinuityCount - 1) + ")";
00203                 ShowStatusMessage( strMessage, NotifyType::StatusMessage );
00204             }
00205         }
00206         break;
00207
00208     case DeviceState::DeviceStateFlushing:
00209         PlotDataReadyEvent::PlotDataReady -= m_plotDataReadyToken;
00210         m_plotDataReadyToken.Value = 0;
00211
00212         ShowStatusMessage( "Finalizing WAV Header.  This may take a few minutes...", NotifyType::StatusMessage );
00213
00214         m_CoreDispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00215             [this]()
00216         {
00217             m_Oscilloscope->Points->Clear();
00218
00219             Windows::Foundation::Point p;
00220             p.X = OSC_START_X;
00221             p.Y = OSC_START_Y;
00222
00223             m_Oscilloscope->Points->Append( p );
00224
00225             p.X = OSC_X_LENGTH;
00226             p.Y = OSC_START_Y;
00227
00228             m_Oscilloscope->Points->Append( p );
00229         }));
00230         break;
00231
00232     case DeviceState::DeviceStateStopped:
00233         // For the stopped state, completely tear down the audio device
00234         m_spCapture = nullptr;
00235
00236         if (m_deviceStateChangeToken.Value != 0)
00237         {
00238             m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00239             m_StateChangedEvent = nullptr;
00240             m_deviceStateChangeToken.Value = 0;
00241         }
00242
00243         ShowStatusMessage( "Capture Stopped", NotifyType::StatusMessage );
00244         break;
00245
00246     case DeviceState::DeviceStateInError:
00247         HRESULT hr = e->hr;
00248
00249         if (m_deviceStateChangeToken.Value != 0)
00250         {
00251             m_StateChangedEvent->StateChangedEvent -= m_deviceStateChangeToken;
00252             m_StateChangedEvent = nullptr;
00253             m_deviceStateChangeToken.Value = 0;
00254         }
00255
00256         m_spCapture = nullptr;
00257
00258         wchar_t hrVal[11];
00259         swprintf_s( hrVal, 11, L"0x%08x\0", hr );
00260         String^ strHRVal = ref new String( hrVal );
00261
00262         // Specifically handle a couple of known errors
00263         switch( hr )
00264         {
00265         case __HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND ):
00266             strMessage = "ERROR: File Not Found (" + strHRVal + "). Check the Sound control panel for an active recording device.";
00267             ShowStatusMessage(strMessage, NotifyType::ErrorMessage);
00268             break;
00269
00270         case AUDCLNT_E_RESOURCES_INVALIDATED:
00271             strMessage = "ERROR: Endpoint Lost Access To Resources (" + strHRVal + ")";
00272             ShowStatusMessage( strMessage, NotifyType::ErrorMessage );
00273             break;
00274
00275         case E_ACCESSDENIED:
00276             strMessage = "ERROR: Access Denied (" + strHRVal + ").  Check 'Settings->Permissions' for access to Microphone.";
00277             ShowStatusMessage( strMessage, NotifyType::ErrorMessage );
00278             break;
00279
00280         default:
00281             strMessage = "ERROR: " + strHRVal + " has occurred.";
00282             ShowStatusMessage( strMessage, NotifyType::ErrorMessage );
00283         }
00284     }
00285 }
00286
00287 // Event callback when visualization data is ready to be plotted
00288 void Scenario4::OnPlotDataReady( Object^ sender, PlotDataReadyEventArgs^ e )
00289 {
00290     Platform::Array<int,1>^ Points = e->Points;
00291     UINT32 Size = e->Size;
00292
00293     m_CoreDispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler(
00294         [this, Points, Size]()
00295     {
00296         // The last point value gives the maximum and minimum values in the data
00297         // Get absolute value of the minimum
00298         float y_max = static_cast<float>( abs( Points[Size - 1] ) );
00299
00300         // Scale the incoming point list so that it fills our scope
00301         float x_inc = static_cast<float>( OSC_X_LENGTH ) / static_cast<float>( Size - 2 );
00302
00303         UINT32 existingPoints = m_Oscilloscope->Points->Size;
00304
00305         for (UINT32 i = 0; i < Size - 1; i++)
00306         {
00307             Point p;
00308
00309             // Fixup the x and y coordinates and set it back into the collection
00310             p.X = OSC_START_X + i * x_inc;
00311             p.Y = OSC_START_Y - ( Points[i] * OSC_TOTAL_HEIGHT ) / ( 2.0F * y_max );
00312
00313             if (i < existingPoints)
00314             {
00315                 m_Oscilloscope->Points->SetAt(i, p);
00316             }
00317             else
00318             {
00319                 m_Oscilloscope->Points->Append(p);
00320             }
00321         }
00322     }));
00323 }
00324
00325 //
00326 //  InitializeCapture()
00327 //
00328 void Scenario4::InitializeCapture( Platform::Object^ sender, Object^ e )
00329 {
00330     HRESULT hr = S_OK;
00331
00332     if (m_spCapture)
00333     {
00334         m_spCapture = nullptr;
00335     }
00336
00337     // Create a new WASAPI capture instance
00338     m_spCapture = Make<WASAPICapture>();
00339
00340     if (nullptr == m_spCapture)
00341     {
00342         OnDeviceStateChange( this, ref new DeviceStateChangedEventArgs( DeviceState::DeviceStateInError, E_OUTOFMEMORY ));
00343         return;
00344     }
00345
00346     // Get a pointer to the device event interface
00347     m_StateChangedEvent = m_spCapture->GetDeviceStateEvent();
00348
00349     if (nullptr == m_StateChangedEvent)
00350     {
00351         OnDeviceStateChange( this, ref new DeviceStateChangedEventArgs( DeviceState::DeviceStateInError, E_FAIL ));
00352         return;
00353     }
00354
00355     // Register for events
00356     m_deviceStateChangeToken = m_StateChangedEvent->StateChangedEvent += ref new DeviceStateChangedHandler( this, &Scenario4::OnDeviceStateChange );
00357     m_plotDataReadyToken = PlotDataReadyEvent::PlotDataReady += ref new PlotDataReadyHandler( this, &Scenario4::OnPlotDataReady );
00358
00359     // Reset discontinuity counter
00360     m_DiscontinuityCount = 0;
00361
00362     // Configure user based properties
00363     CAPTUREDEVICEPROPS props;
00364
00365     m_IsLowLatency = static_cast<Platform::Boolean>(toggleMinimumLatency->IsOn);
00366     props.IsLowLatency = m_IsLowLatency;
00367     m_spCapture->SetProperties(props);
00368
00369     // Perform the initialization
00370     m_spCapture->InitializeAudioDeviceAsync();
00371 }
00372
00373 //
00374 //  StopCapture()
00375 //
00376 void Scenario4::StopCapture( Platform::Object^ sender, Object^ e )
00377 {
00378     if (m_spCapture)
00379     {
00380         // Set the event to stop playback
00381         m_spCapture->StopCaptureAsync();
00382     }
00383 }
00384
Generated on Fri Nov 15 2024 22:18:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/Common/BasicLoader.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • Common

BasicLoader.cpp

Go to the documentation of this file.
00001 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 // PARTICULAR PURPOSE.
00005 //
00006 // Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "BasicLoader.h"
00010 #include "BasicShapes.h"
00011 #include "DDSTextureLoader.h"
00012 #include <cwctype>
00013
00014 BasicLoader::BasicLoader(
00015     _In_ winrt::com_ptr<ID3D11Device3> d3dDevice,
00016     _In_opt_ IWICImagingFactory2* wicFactory
00017     ) :
00018     m_d3dDevice(std::move(d3dDevice))
00019 {
00020     m_wicFactory.copy_from(wicFactory);
00021 }
00022
00023 template <class DeviceChildType>
00024 inline void BasicLoader::SetDebugName(
00025     _In_ DeviceChildType* object,
00026     _In_ winrt::hstring const& name
00027     )
00028 {
00029 #if defined(_DEBUG)
00030     // Only assign debug names in debug builds.
00031
00032     char nameString[1024];
00033     int nameStringLength = WideCharToMultiByte(
00034         CP_ACP,
00035         0,
00036         name.c_str(),
00037         -1,
00038         nameString,
00039         1024,
00040         nullptr,
00041         nullptr
00042         );
00043
00044     if (nameStringLength == 0)
00045     {
00046         char defaultNameString[] = "BasicLoaderObject";
00047         winrt::check_hresult(
00048             object->SetPrivateData(
00049                 WKPDID_D3DDebugObjectName,
00050                 sizeof(defaultNameString) - 1,
00051                 defaultNameString
00052                 )
00053             );
00054     }
00055     else
00056     {
00057         winrt::check_hresult(
00058             object->SetPrivateData(
00059                 WKPDID_D3DDebugObjectName,
00060                 nameStringLength - 1,
00061                 nameString
00062                 )
00063             );
00064     }
00065 #endif
00066 }
00067
00068 std::wstring BasicLoader::GetExtension(
00069     _In_ winrt::hstring const& filename
00070     )
00071 {
00072     std::wstring extension;
00073     auto lastDot = std::find(filename.rbegin(), filename.rend(), L'.');
00074     if (lastDot != filename.rend())
00075     {
00076         std::transform(lastDot.base(), filename.end(), std::back_inserter(extension),
00077             [](wchar_t c) { return std::towlower(c); });
00078     }
00079     return extension;
00080 }
00081
00082 void BasicLoader::CreateTexture(
00083     _In_ bool decodeAsDDS,
00084     _In_reads_bytes_(dataSize) const byte* data,
00085     _In_ uint32_t dataSize,
00086     _Out_opt_ ID3D11Texture2D** texture,
00087     _Out_opt_ ID3D11ShaderResourceView** textureView,
00088     _In_opt_ winrt::hstring const& debugName
00089     )
00090 {
00091     winrt::com_ptr<ID3D11ShaderResourceView> shaderResourceView;
00092     winrt::com_ptr<ID3D11Texture2D> texture2D;
00093
00094     if (decodeAsDDS)
00095     {
00096         winrt::com_ptr<ID3D11Resource> resource;
00097
00098         if (textureView == nullptr)
00099         {
00100             CreateDDSTextureFromMemory(
00101                 m_d3dDevice.get(),
00102                 data,
00103                 dataSize,
00104                 resource.put(),
00105                 nullptr
00106                 );
00107         }
00108         else
00109         {
00110             CreateDDSTextureFromMemory(
00111                 m_d3dDevice.get(),
00112                 data,
00113                 dataSize,
00114                 resource.put(),
00115                 shaderResourceView.put()
00116                 );
00117         }
00118
00119         texture2D = resource.as<ID3D11Texture2D>();
00120     }
00121     else
00122     {
00123         if (m_wicFactory.get() == nullptr)
00124         {
00125             // A WIC factory object is required in order to load texture
00126             // assets stored in non-DDS formats. If BasicLoader was not
00127             // initialized with one, create one as needed.
00128             winrt::check_hresult(
00129                 CoCreateInstance(
00130                     CLSID_WICImagingFactory,
00131                     nullptr,
00132                     CLSCTX_INPROC_SERVER,
00133                     IID_PPV_ARGS(&m_wicFactory)
00134                     )
00135                 );
00136         }
00137
00138         winrt::com_ptr<IWICStream> stream;
00139         winrt::check_hresult(
00140             m_wicFactory->CreateStream(stream.put())
00141             );
00142
00143         winrt::check_hresult(
00144             stream->InitializeFromMemory(
00145                 const_cast<WICInProcPointer>(data),
00146                 dataSize
00147                 )
00148             );
00149
00150         winrt::com_ptr<IWICBitmapDecoder> bitmapDecoder;
00151         winrt::check_hresult(
00152             m_wicFactory->CreateDecoderFromStream(
00153                 stream.get(),
00154                 nullptr,
00155                 WICDecodeMetadataCacheOnDemand,
00156                 bitmapDecoder.put()
00157                 )
00158             );
00159
00160         winrt::com_ptr<IWICBitmapFrameDecode> bitmapFrame;
00161         winrt::check_hresult(
00162             bitmapDecoder->GetFrame(0, bitmapFrame.put())
00163             );
00164
00165         winrt::com_ptr<IWICFormatConverter> formatConverter;
00166         winrt::check_hresult(
00167             m_wicFactory->CreateFormatConverter(formatConverter.put())
00168             );
00169
00170         winrt::check_hresult(
00171             formatConverter->Initialize(
00172                 bitmapFrame.get(),
00173                 GUID_WICPixelFormat32bppPBGRA,
00174                 WICBitmapDitherTypeNone,
00175                 nullptr,
00176                 0.0,
00177                 WICBitmapPaletteTypeCustom
00178                 )
00179             );
00180
00181         uint32_t width;
00182         uint32_t height;
00183         winrt::check_hresult(
00184             bitmapFrame->GetSize(&width, &height)
00185             );
00186
00187         std::unique_ptr<byte[]> bitmapPixels(new byte[width * height * 4]);
00188         winrt::check_hresult(
00189             formatConverter->CopyPixels(
00190                 nullptr,
00191                 width * 4,
00192                 width * height * 4,
00193                 bitmapPixels.get()
00194                 )
00195             );
00196
00197         D3D11_SUBRESOURCE_DATA initialData;
00198         ZeroMemory(&initialData, sizeof(initialData));
00199         initialData.pSysMem = bitmapPixels.get();
00200         initialData.SysMemPitch = width * 4;
00201         initialData.SysMemSlicePitch = 0;
00202
00203         CD3D11_TEXTURE2D_DESC textureDesc(
00204             DXGI_FORMAT_B8G8R8A8_UNORM,
00205             width,
00206             height,
00207             1,
00208             1
00209             );
00210
00211         winrt::check_hresult(
00212             m_d3dDevice->CreateTexture2D(
00213                 &textureDesc,
00214                 &initialData,
00215                 texture2D.put()
00216                 )
00217             );
00218
00219         if (textureView != nullptr)
00220         {
00221             CD3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceViewDesc(
00222                 texture2D.get(),
00223                 D3D11_SRV_DIMENSION_TEXTURE2D
00224                 );
00225
00226             winrt::check_hresult(
00227                 m_d3dDevice->CreateShaderResourceView(
00228                     texture2D.get(),
00229                     &shaderResourceViewDesc,
00230                     shaderResourceView.put()
00231                     )
00232                 );
00233         }
00234     }
00235
00236     SetDebugName(texture2D.get(), debugName);
00237
00238     if (texture != nullptr)
00239     {
00240         *texture = texture2D.detach();
00241     }
00242     if (textureView != nullptr)
00243     {
00244         *textureView = shaderResourceView.detach();
00245     }
00246 }
00247
00248 void BasicLoader::CreateInputLayout(
00249     _In_reads_bytes_(bytecodeSize) const byte* bytecode,
00250     _In_ uint32_t bytecodeSize,
00251     _In_reads_opt_(layoutDescNumElements) const D3D11_INPUT_ELEMENT_DESC* layoutDesc,
00252     _In_ uint32_t layoutDescNumElements,
00253     _Out_ ID3D11InputLayout** layout
00254     )
00255 {
00256     if (layoutDesc == nullptr)
00257     {
00258         // If no input layout is specified, use the BasicVertex layout.
00259         static constexpr D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] =
00260         {
00261             { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,  D3D11_INPUT_PER_VERTEX_DATA, 0 },
00262             { "NORMAL",   0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00263             { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT,    0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
00264         };
00265
00266         winrt::check_hresult(
00267             m_d3dDevice->CreateInputLayout(
00268                 basicVertexLayoutDesc,
00269                 ARRAYSIZE(basicVertexLayoutDesc),
00270                 bytecode,
00271                 bytecodeSize,
00272                 layout
00273                 )
00274             );
00275     }
00276     else
00277     {
00278         winrt::check_hresult(
00279             m_d3dDevice->CreateInputLayout(
00280                 layoutDesc,
00281                 layoutDescNumElements,
00282                 bytecode,
00283                 bytecodeSize,
00284                 layout
00285                 )
00286             );
00287     }
00288 }
00289
00290 void BasicLoader::CreateMesh(
00291     _In_ byte* meshData,
00292     _Out_ ID3D11Buffer** vertexBuffer,
00293     _Out_ ID3D11Buffer** indexBuffer,
00294     _Out_opt_ uint32_t* vertexCount,
00295     _Out_opt_ uint32_t* indexCount,
00296     _In_opt_ winrt::hstring const& debugName
00297     )
00298 {
00299     // The first 4 bytes of the BasicMesh format define the number of vertices in the mesh.
00300     uint32_t numVertices = *reinterpret_cast<uint32_t*>(meshData);
00301
00302     // The following 4 bytes define the number of indices in the mesh.
00303     uint32_t numIndices = *reinterpret_cast<uint32_t*>(meshData + sizeof(uint32_t));
00304
00305     // The next segment of the BasicMesh format contains the vertices of the mesh.
00306     BasicVertex* vertices = reinterpret_cast<BasicVertex*>(meshData + sizeof(uint32_t) * 2);
00307
00308     // The last segment of the BasicMesh format contains the indices of the mesh.
00309     uint16_t* indices = reinterpret_cast<uint16_t*>(meshData + sizeof(uint32_t) * 2 + sizeof(BasicVertex) * numVertices);
00310
00311     // Create the vertex and index buffers with the mesh data.
00312
00313     D3D11_SUBRESOURCE_DATA vertexBufferData = { 0 };
00314     vertexBufferData.pSysMem = vertices;
00315     vertexBufferData.SysMemPitch = 0;
00316     vertexBufferData.SysMemSlicePitch = 0;
00317     CD3D11_BUFFER_DESC vertexBufferDesc(numVertices * sizeof(BasicVertex), D3D11_BIND_VERTEX_BUFFER);
00318     winrt::check_hresult(
00319         m_d3dDevice->CreateBuffer(
00320             &vertexBufferDesc,
00321             &vertexBufferData,
00322             vertexBuffer
00323             )
00324         );
00325
00326     D3D11_SUBRESOURCE_DATA indexBufferData = { 0 };
00327     indexBufferData.pSysMem = indices;
00328     indexBufferData.SysMemPitch = 0;
00329     indexBufferData.SysMemSlicePitch = 0;
00330     CD3D11_BUFFER_DESC indexBufferDesc(numIndices * sizeof(uint16_t), D3D11_BIND_INDEX_BUFFER);
00331     winrt::check_hresult(
00332         m_d3dDevice->CreateBuffer(
00333             &indexBufferDesc,
00334             &indexBufferData,
00335             indexBuffer
00336             )
00337         );
00338
00339     SetDebugName(*vertexBuffer, debugName + L"_VertexBuffer");
00340     SetDebugName(*indexBuffer, debugName + L"_IndexBuffer");
00341
00342     if (vertexCount != nullptr)
00343     {
00344         *vertexCount = numVertices;
00345     }
00346     if (indexCount != nullptr)
00347     {
00348         *indexCount = numIndices;
00349     }
00350 }
00351
00352 void BasicLoader::LoadTexture(
00353     _In_ winrt::hstring const& filename,
00354     _Out_opt_ ID3D11Texture2D** texture,
00355     _Out_opt_ ID3D11ShaderResourceView** textureView
00356     )
00357 {
00358     auto textureData{ m_basicReaderWriter.ReadData(filename) };
00359
00360     CreateTexture(
00361         GetExtension(filename) == L"dds",
00362         textureData.data(),
00363         textureData.size(),
00364         texture,
00365         textureView,
00366         filename
00367         );
00368 }
00369
00370 winrt::Windows::Foundation::IAsyncAction BasicLoader::LoadTextureAsync(
00371     _In_ winrt::hstring filename,
00372     _Out_opt_ ID3D11Texture2D** texture,
00373     _Out_opt_ ID3D11ShaderResourceView** textureView
00374     )
00375 {
00376     auto textureData = co_await m_basicReaderWriter.ReadDataAsync(filename);
00377     CreateTexture(
00378         GetExtension(filename) == L"dds",
00379         textureData.data(),
00380         textureData.Length(),
00381         texture,
00382         textureView,
00383         filename
00384         );
00385 }
00386
00387 void BasicLoader::LoadShader(
00388     _In_ winrt::hstring const& filename,
00389     _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC const layoutDesc[],
00390     _In_ uint32_t layoutDescNumElements,
00391     _Out_ ID3D11VertexShader** shader,
00392     _Out_opt_ ID3D11InputLayout** layout
00393     )
00394 {
00395     std::vector<byte> bytecode{ m_basicReaderWriter.ReadData(filename) };
00396
00397     winrt::check_hresult(
00398         m_d3dDevice->CreateVertexShader(
00399             bytecode.data(),
00400             bytecode.size(),
00401             nullptr,
00402             shader
00403             )
00404         );
00405
00406     SetDebugName(*shader, filename);
00407
00408     if (layout != nullptr)
00409     {
00410         CreateInputLayout(
00411             bytecode.data(),
00412             bytecode.size(),
00413             layoutDesc,
00414             layoutDescNumElements,
00415             layout
00416             );
00417
00418         SetDebugName(*layout, filename);
00419     }
00420 }
00421
00422 winrt::Windows::Foundation::IAsyncAction BasicLoader::LoadShaderAsync(
00423     _In_ winrt::hstring filename,
00424     _In_reads_opt_(layoutDescNumElements) D3D11_INPUT_ELEMENT_DESC const layoutDesc[],
00425     _In_ uint32_t layoutDescNumElements,
00426     _Out_ ID3D11VertexShader** shader,
00427     _Out_opt_ ID3D11InputLayout** layout
00428     )
00429 {
00430     // This method assumes that the lifetime of input arguments may be shorter
00431     // than the duration of this operation. In order to ensure accurate results, a
00432     // copy of all arguments passed by pointer must be made. The method then
00433     // ensures that the lifetime of the copied data exceeds that of the coroutine.
00434
00435     // Create copies of the layoutDesc array as well as the SemanticName strings,
00436     // both of which are pointers to data whose lifetimes may be shorter than that
00437     // of this method's coroutine.
00438     std::vector<D3D11_INPUT_ELEMENT_DESC> layoutDescCopy;
00439     std::vector<std::string> layoutDescSemanticNamesCopy;
00440     if (layoutDesc != nullptr)
00441     {
00442         layoutDescCopy = { layoutDesc, layoutDesc + layoutDescNumElements };
00443         layoutDescSemanticNamesCopy.reserve(layoutDescNumElements);
00444
00445         for (auto&& desc : layoutDescCopy)
00446         {
00447             desc.SemanticName = layoutDescSemanticNamesCopy.emplace(layoutDescSemanticNamesCopy.end(), desc.SemanticName)->c_str();
00448         }
00449     }
00450
00451     auto bytecode = co_await m_basicReaderWriter.ReadDataAsync(filename);
00452
00453     winrt::check_hresult(
00454         m_d3dDevice->CreateVertexShader(
00455             bytecode.data(),
00456             bytecode.Length(),
00457             nullptr,
00458             shader
00459             )
00460         );
00461
00462     SetDebugName(*shader, filename);
00463
00464     if (layout != nullptr)
00465     {
00466         CreateInputLayout(
00467             bytecode.data(),
00468             bytecode.Length(),
00469             layoutDesc == nullptr ? nullptr : layoutDescCopy.data(),
00470             layoutDescNumElements,
00471             layout
00472             );
00473
00474         SetDebugName(*layout, filename);
00475     }
00476 }
00477
00478 void BasicLoader::LoadShader(
00479     _In_ winrt::hstring const& filename,
00480     _Out_ ID3D11PixelShader** shader
00481     )
00482 {
00483     std::vector<byte> bytecode{ m_basicReaderWriter.ReadData(filename) };
00484
00485     winrt::check_hresult(
00486         m_d3dDevice->CreatePixelShader(
00487             bytecode.data(),
00488             bytecode.size(),
00489             nullptr,
00490             shader
00491             )
00492         );
00493
00494     SetDebugName(*shader, filename);
00495 }
00496
00497 winrt::Windows::Foundation::IAsyncAction BasicLoader::LoadShaderAsync(
00498     _In_ winrt::hstring filename,
00499     _Out_ ID3D11PixelShader** shader
00500     )
00501 {
00502     auto bytecode = co_await m_basicReaderWriter.ReadDataAsync(filename);
00503
00504     winrt::check_hresult(
00505         m_d3dDevice->CreatePixelShader(
00506             bytecode.data(),
00507             bytecode.Length(),
00508             nullptr,
00509             shader
00510             )
00511         );
00512
00513     SetDebugName(*shader, filename);
00514 }
00515
00516 void BasicLoader::LoadShader(
00517     _In_ winrt::hstring const& filename,
00518     _Out_ ID3D11ComputeShader** shader
00519     )
00520 {
00521     std::vector<byte> bytecode{ m_basicReaderWriter.ReadData(filename) };
00522
00523     winrt::check_hresult(
00524         m_d3dDevice->CreateComputeShader(
00525             bytecode.data(),
00526             bytecode.size(),
00527             nullptr,
00528             shader
00529             )
00530         );
00531
00532     SetDebugName(*shader, filename);
00533 }
00534
00535 winrt::Windows::Foundation::IAsyncAction BasicLoader::LoadShaderAsync(
00536     _In_ winrt::hstring filename,
00537     _Out_ ID3D11ComputeShader** shader
00538     )
00539 {
00540     auto bytecode = co_await m_basicReaderWriter.ReadDataAsync(filename);
00541
00542     winrt::check_hresult(
00543         m_d3dDevice->CreateComputeShader(
00544             bytecode.data(),
00545             bytecode.Length(),
00546             nullptr,
00547             shader
00548             )
00549         );
00550
00551     SetDebugName(*shader, filename);
00552 }
00553
00554 void BasicLoader::LoadShader(
00555     _In_ winrt::hstring const& filename,
00556     _Out_ ID3D11GeometryShader** shader
00557     )
00558 {
00559     std::vector<byte> bytecode{ m_basicReaderWriter.ReadData(filename) };
00560
00561     winrt::check_hresult(
00562         m_d3dDevice->CreateGeometryShader(
00563             bytecode.data(),
00564             bytecode.size(),
00565             nullptr,
00566             shader
00567             )
00568         );
00569
00570     SetDebugName(*shader, filename);
00571 }
00572
00573 winrt::Windows::Foundation::IAsyncAction BasicLoader::LoadShaderAsync(
00574     _In_ winrt::hstring filename,
00575     _Out_ ID3D11GeometryShader** shader
00576     )
00577 {
00578     auto bytecode = co_await m_basicReaderWriter.ReadDataAsync(filename);
00579
00580     winrt::check_hresult(
00581         m_d3dDevice->CreateGeometryShader(
00582             bytecode.data(),
00583             bytecode.Length(),
00584             nullptr,
00585             shader
00586             )
00587         );
00588
00589     SetDebugName(*shader, filename);
00590 }
00591
00592 void BasicLoader::LoadShader(
00593     _In_ winrt::hstring const& filename,
00594     _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration,
00595     _In_ uint32_t numEntries,
00596     _In_reads_opt_(numStrides) const uint32_t* bufferStrides,
00597     _In_ uint32_t numStrides,
00598     _In_ uint32_t rasterizedStream,
00599     _Out_ ID3D11GeometryShader** shader
00600     )
00601 {
00602     std::vector<byte> bytecode{ m_basicReaderWriter.ReadData(filename) };
00603
00604     winrt::check_hresult(
00605         m_d3dDevice->CreateGeometryShaderWithStreamOutput(
00606             bytecode.data(),
00607             bytecode.size(),
00608             streamOutDeclaration,
00609             numEntries,
00610             bufferStrides,
00611             numStrides,
00612             rasterizedStream,
00613             nullptr,
00614             shader
00615             )
00616         );
00617
00618     SetDebugName(*shader, filename);
00619 }
00620
00621 winrt::Windows::Foundation::IAsyncAction BasicLoader::LoadShaderAsync(
00622     _In_ winrt::hstring filename,
00623     _In_reads_opt_(numEntries) const D3D11_SO_DECLARATION_ENTRY* streamOutDeclaration,
00624     _In_ uint32_t numEntries,
00625     _In_reads_opt_(numStrides) const uint32_t* bufferStrides,
00626     _In_ uint32_t numStrides,
00627     _In_ uint32_t rasterizedStream,
00628     _Out_ ID3D11GeometryShader** shader
00629     )
00630 {
00631     // This method assumes that the lifetime of input arguments may be shorter
00632     // than the duration of this coroutine. In order to ensure accurate results, a
00633     // copy of all arguments passed by pointer must be made. The method then
00634     // ensures that the lifetime of the copied data exceeds that of the coroutine.
00635
00636     // Create copies of the streamOutDeclaration array as well as the SemanticName
00637     // strings, both of which are pointers to data whose lifetimes may be shorter
00638     // than that of this method's coroutine.
00639     std::vector<D3D11_SO_DECLARATION_ENTRY> streamOutDeclarationCopy;
00640     std::vector<std::string> streamOutDeclarationSemanticNamesCopy;
00641     if (streamOutDeclaration != nullptr)
00642     {
00643         streamOutDeclarationCopy = { streamOutDeclaration, streamOutDeclaration + numEntries };
00644         streamOutDeclarationSemanticNamesCopy.reserve(numEntries);
00645
00646         for (auto&& desc : streamOutDeclarationCopy)
00647         {
00648             desc.SemanticName = streamOutDeclarationSemanticNamesCopy.emplace(streamOutDeclarationSemanticNamesCopy.end(), desc.SemanticName)->c_str();
00649         }
00650     }
00651
00652     // Create a copy of the bufferStrides array, which is a pointer to data
00653     // whose lifetime may be shorter than that of this method's coroutine.
00654     std::vector<uint32_t> bufferStridesCopy;
00655     if (bufferStrides != nullptr)
00656     {
00657         bufferStridesCopy = { bufferStrides, bufferStrides + numStrides };
00658     }
00659
00660     auto bytecode = co_await m_basicReaderWriter.ReadDataAsync(filename);
00661
00662     winrt::check_hresult(
00663         m_d3dDevice->CreateGeometryShaderWithStreamOutput(
00664             bytecode.data(),
00665             bytecode.Length(),
00666             streamOutDeclaration == nullptr ? nullptr : streamOutDeclarationCopy.data(),
00667             numEntries,
00668             bufferStrides == nullptr ? nullptr : bufferStridesCopy.data(),
00669             numStrides,
00670             rasterizedStream,
00671             nullptr,
00672             shader
00673             )
00674         );
00675
00676     SetDebugName(*shader, filename);
00677 }
00678
00679 void BasicLoader::LoadShader(
00680     _In_ winrt::hstring const& filename,
00681     _Out_ ID3D11HullShader** shader
00682     )
00683 {
00684     std::vector<byte> bytecode{ m_basicReaderWriter.ReadData(filename) };
00685
00686     winrt::check_hresult(
00687         m_d3dDevice->CreateHullShader(
00688             bytecode.data(),
00689             bytecode.size(),
00690             nullptr,
00691             shader
00692             )
00693         );
00694
00695     SetDebugName(*shader, filename);
00696 }
00697
00698 winrt::Windows::Foundation::IAsyncAction BasicLoader::LoadShaderAsync(
00699     _In_ winrt::hstring filename,
00700     _Out_ ID3D11HullShader** shader
00701     )
00702 {
00703     auto bytecode = co_await m_basicReaderWriter.ReadDataAsync(filename);
00704
00705     winrt::check_hresult(
00706         m_d3dDevice->CreateHullShader(
00707             bytecode.data(),
00708             bytecode.Length(),
00709             nullptr,
00710             shader
00711             )
00712         );
00713
00714     SetDebugName(*shader, filename);
00715 }
00716
00717 void BasicLoader::LoadShader(
00718     _In_ winrt::hstring const& filename,
00719     _Out_ ID3D11DomainShader** shader
00720     )
00721 {
00722     std::vector<byte> bytecode{ m_basicReaderWriter.ReadData(filename) };
00723
00724     winrt::check_hresult(
00725         m_d3dDevice->CreateDomainShader(
00726             bytecode.data(),
00727             bytecode.size(),
00728             nullptr,
00729             shader
00730             )
00731         );
00732
00733     SetDebugName(*shader, filename);
00734 }
00735
00736 winrt::Windows::Foundation::IAsyncAction BasicLoader::LoadShaderAsync(
00737     _In_ winrt::hstring filename,
00738     _Out_ ID3D11DomainShader** shader
00739     )
00740 {
00741     auto bytecode = co_await m_basicReaderWriter.ReadDataAsync(filename);
00742
00743     winrt::check_hresult(
00744         m_d3dDevice->CreateDomainShader(
00745             bytecode.data(),
00746             bytecode.Length(),
00747             nullptr,
00748             shader
00749             )
00750         );
00751
00752     SetDebugName(*shader, filename);
00753 }
00754
00755 void BasicLoader::LoadMesh(
00756     _In_ winrt::hstring const& filename,
00757     _Out_ ID3D11Buffer** vertexBuffer,
00758     _Out_ ID3D11Buffer** indexBuffer,
00759     _Out_opt_ uint32_t* vertexCount,
00760     _Out_opt_ uint32_t* indexCount
00761     )
00762 {
00763     std::vector<byte> meshData{ m_basicReaderWriter.ReadData(filename) };
00764
00765     CreateMesh(
00766         meshData.data(),
00767         vertexBuffer,
00768         indexBuffer,
00769         vertexCount,
00770         indexCount,
00771         filename
00772         );
00773 }
00774
00775 winrt::Windows::Foundation::IAsyncAction BasicLoader::LoadMeshAsync(
00776     _In_ winrt::hstring filename,
00777     _Out_ ID3D11Buffer** vertexBuffer,
00778     _Out_ ID3D11Buffer** indexBuffer,
00779     _Out_opt_ uint32_t* vertexCount,
00780     _Out_opt_ uint32_t* indexCount
00781     )
00782 {
00783     auto meshData = co_await m_basicReaderWriter.ReadDataAsync(filename);
00784
00785     CreateMesh(
00786         meshData.data(),
00787         vertexBuffer,
00788         indexBuffer,
00789         vertexCount,
00790         indexCount,
00791         filename
00792         );
00793 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: RemoteSystems/cs/Scenario1_Discovery.xaml.cs Source File

  • RemoteSystems
  • cs

Scenario1_Discovery.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Collections.ObjectModel;
00015 using System.Threading.Tasks;
00016 using Windows.Networking;
00017 using Windows.System.RemoteSystems;
00018 using Windows.UI.Core;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 namespace SDKTemplate
00024 {
00025     public sealed partial class Scenario1_Discovery : Page
00026     {
00027         private MainPage m_rootPage;
00028         private RemoteSystemWatcher m_remoteSystemWatcher;
00029
00030         public Scenario1_Discovery()
00031         {
00032             this.InitializeComponent();
00033             this.DataContext = this;
00034         }
00035
00036         protected override void OnNavigatedTo(NavigationEventArgs e)
00037         {
00038             m_rootPage = MainPage.Current;
00039             m_rootPage.systemList = new ObservableCollection<RemoteSystem>();
00040             m_rootPage.systemMap = new Dictionary<string, RemoteSystem>();
00041         }
00042
00043         public ObservableCollection<RemoteSystem> SystemList => m_rootPage.systemList;
00044
00045         private async void Search_Clicked(object sender, RoutedEventArgs e)
00046         {
00047             // Disable the Search button while watcher is being started to avoid a potential
00048             // race condition of having two RemoteSystemWatchers running in parallel.
00049             Button searchButton = sender as Button;
00050             searchButton.IsHitTestVisible = false;
00051
00052             // Cleaning up any existing systems from previous searches.
00053             SearchCleanup();
00054
00055             // Verify access for Remote Systems.
00056             // Note: RequestAccessAsync needs to called from the UI thread.
00057             RemoteSystemAccessStatus accessStatus = await RemoteSystem.RequestAccessAsync();
00058
00059             if (accessStatus == RemoteSystemAccessStatus.Allowed)
00060             {
00061                 if (HostNameSearch.IsChecked.Value)
00062                 {
00063                     await SearchByHostNameAsync();
00064                 }
00065                 else
00066                 {
00067                     SearchByRemoteSystemWatcher();
00068                 }
00069             }
00070             else
00071             {
00072                 UpdateStatus("Access to Remote Systems is " + accessStatus.ToString(), NotifyType.ErrorMessage);
00073             }
00074
00075             searchButton.IsHitTestVisible = true;
00076             DeviceInfoTextBlock.Visibility = Visibility.Visible;
00077         }
00078
00079         private async Task SearchByHostNameAsync()
00080         {
00081             if (!string.IsNullOrWhiteSpace(HostNameTextBox.Text))
00082             {
00083                 // Build hostname object.
00084                 HostName hostName = new HostName(HostNameTextBox.Text);
00085
00086                 // Get Remote System from HostName.
00087                 RemoteSystem remoteSystem = await RemoteSystem.FindByHostNameAsync(hostName);
00088
00089                 if (remoteSystem != null)
00090                 {
00091                     m_rootPage.systemList.Add(remoteSystem);
00092                     SystemListBox.Visibility = Visibility.Visible;
00093                     UpdateStatus("Found system - " + remoteSystem.DisplayName, NotifyType.StatusMessage);
00094                 }
00095                 else
00096                 {
00097                     UpdateStatus("Unable to find the system.", NotifyType.ErrorMessage);
00098                 }
00099             }
00100             else
00101             {
00102                 UpdateStatus("Enter a valid host name", NotifyType.ErrorMessage);
00103             }
00104         }
00105
00106         private void SearchByRemoteSystemWatcher()
00107         {
00108             if (FilterSearch.IsChecked.Value)
00109             {
00110                 // Build a watcher to continuously monitor for filtered remote systems.
00111                 m_remoteSystemWatcher = RemoteSystem.CreateWatcher(BuildFilters());
00112             }
00113             else
00114             {
00115                 // Build a watcher to continuously monitor for all remote systems.
00116                 m_remoteSystemWatcher = RemoteSystem.CreateWatcher();
00117             }
00118
00119             // Subscribing to the event that will be raised when a new remote system is found by the watcher.
00120             m_remoteSystemWatcher.RemoteSystemAdded += RemoteSystemWatcher_RemoteSystemAdded;
00121
00122             // Subscribing to the event that will be raised when a previously found remote system is no longer available.
00123             m_remoteSystemWatcher.RemoteSystemRemoved += RemoteSystemWatcher_RemoteSystemRemoved;
00124
00125             // Subscribing to the event that will be raised when a previously found remote system is updated.
00126             m_remoteSystemWatcher.RemoteSystemUpdated += RemoteSystemWatcher_RemoteSystemUpdated;
00127
00128             // Start the watcher.
00129             m_remoteSystemWatcher.Start();
00130
00131             UpdateStatus("Searching for systems...", NotifyType.StatusMessage);
00132             SystemListBox.Visibility = Visibility.Visible;
00133         }
00134
00135         private async void RemoteSystemWatcher_RemoteSystemUpdated(RemoteSystemWatcher sender, RemoteSystemUpdatedEventArgs args)
00136         {
00137             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00138             {
00139                 if (m_rootPage.systemMap.ContainsKey(args.RemoteSystem.Id))
00140                 {
00141                     m_rootPage.systemList.Remove(m_rootPage.systemMap[args.RemoteSystem.Id]);
00142                     m_rootPage.systemMap.Remove(args.RemoteSystem.Id);
00143                 }
00144                 m_rootPage.systemList.Add(args.RemoteSystem);
00145                 m_rootPage.systemMap.Add(args.RemoteSystem.Id, args.RemoteSystem);
00146                 UpdateStatus("System updated with Id = " + args.RemoteSystem.Id, NotifyType.StatusMessage);
00147             });
00148         }
00149
00150         private async void RemoteSystemWatcher_RemoteSystemRemoved(RemoteSystemWatcher sender, RemoteSystemRemovedEventArgs args)
00151         {
00152             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00153             {
00154                 if (m_rootPage.systemMap.ContainsKey(args.RemoteSystemId))
00155                 {
00156                     m_rootPage.systemList.Remove(m_rootPage.systemMap[args.RemoteSystemId]);
00157                     UpdateStatus(m_rootPage.systemMap[args.RemoteSystemId].DisplayName + " removed.", NotifyType.StatusMessage);
00158                     m_rootPage.systemMap.Remove(args.RemoteSystemId);
00159                 }
00160             });
00161         }
00162
00163         private async void RemoteSystemWatcher_RemoteSystemAdded(RemoteSystemWatcher sender, RemoteSystemAddedEventArgs args)
00164         {
00165             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00166             {
00167                 m_rootPage.systemList.Add(args.RemoteSystem);
00168                 m_rootPage.systemMap.Add(args.RemoteSystem.Id, args.RemoteSystem);
00169                 UpdateStatus(string.Format("Found {0} systems.", m_rootPage.systemList.Count), NotifyType.StatusMessage);
00170             });
00171         }
00172
00173         private List<IRemoteSystemFilter> BuildFilters()
00174         {
00175             List<IRemoteSystemFilter> filters = new List<IRemoteSystemFilter>();
00176             RemoteSystemDiscoveryTypeFilter discoveryFilter;
00177             RemoteSystemAuthorizationKindFilter authorizationKindFilter;
00178             List<string> kinds = new List<string>();
00179             RemoteSystemStatusTypeFilter statusFilter;
00180
00181             if (DiscoveryTypeOptions.IsChecked.Value)
00182             {
00183                 // Build discovery type filters
00184                 if (ProximalRadioButton.IsChecked.Value)
00185                 {
00186                     discoveryFilter = new RemoteSystemDiscoveryTypeFilter(RemoteSystemDiscoveryType.Proximal);
00187                 }
00188                 else if (CloudRadioButton.IsChecked.Value)
00189                 {
00190                     discoveryFilter = new RemoteSystemDiscoveryTypeFilter(RemoteSystemDiscoveryType.Cloud);
00191                 }
00192                 else if (SpatiallyProximalRadioButton.IsChecked.Value)
00193                 {
00194                     discoveryFilter = new RemoteSystemDiscoveryTypeFilter(RemoteSystemDiscoveryType.SpatiallyProximal);
00195                 }
00196                 else
00197                 {
00198                     discoveryFilter = new RemoteSystemDiscoveryTypeFilter(RemoteSystemDiscoveryType.Any);
00199                 }
00200                 filters.Add(discoveryFilter);
00201             }
00202
00203             if (AuthorizationTypeOptions.IsChecked.Value)
00204             {
00205                 // Build authorization type filters
00206                 if (AnonymousDiscoveryRadioButton.IsChecked.Value)
00207                 {
00208                     authorizationKindFilter = new RemoteSystemAuthorizationKindFilter(RemoteSystemAuthorizationKind.Anonymous);
00209                 }
00210                 else
00211                 {
00212                     authorizationKindFilter = new RemoteSystemAuthorizationKindFilter(RemoteSystemAuthorizationKind.SameUser);
00213                 }
00214                 filters.Add(authorizationKindFilter);
00215             }
00216
00217             if (SystemTypeOptions.IsChecked.Value)
00218             {
00219                 // Build system type filters
00220                 if (DesktopCheckBox.IsChecked.Value)
00221                 {
00222                     kinds.Add(RemoteSystemKinds.Desktop);
00223                 }
00224                 if (TabletCheckBox.IsChecked.Value)
00225                 {
00226                     kinds.Add(RemoteSystemKinds.Tablet);
00227                 }
00228                 if (LaptopCheckBox.IsChecked.Value)
00229                 {
00230                     kinds.Add(RemoteSystemKinds.Laptop);
00231                 }
00232                 if (IotCheckBox.IsChecked.Value)
00233                 {
00234                     kinds.Add(RemoteSystemKinds.Iot);
00235                 }
00236                 if (HolographicCheckBox.IsChecked.Value)
00237                 {
00238                     kinds.Add(RemoteSystemKinds.Holographic);
00239                 }
00240                 if (HubCheckBox.IsChecked.Value)
00241                 {
00242                     kinds.Add(RemoteSystemKinds.Hub);
00243                 }
00244                 if (PhoneCheckBox.IsChecked.Value)
00245                 {
00246                     kinds.Add(RemoteSystemKinds.Phone);
00247                 }
00248                 if (XboxCheckBox.IsChecked.Value)
00249                 {
00250                     kinds.Add(RemoteSystemKinds.Xbox);
00251                 }
00252                 if (kinds.Count == 0)
00253                 {
00254                     UpdateStatus("Select a system type filter.", NotifyType.ErrorMessage);
00255                 }
00256                 else
00257                 {
00258                     RemoteSystemKindFilter kindFilter = new RemoteSystemKindFilter(kinds);
00259                     filters.Add(kindFilter);
00260                 }
00261             }
00262
00263             if (StatusTypeOptions.IsChecked.Value)
00264             {
00265                 // Build status type filters
00266                 if (AvailableRadioButton.IsChecked.Value)
00267                 {
00268                     statusFilter = new RemoteSystemStatusTypeFilter(RemoteSystemStatusType.Available);
00269                 }
00270                 else
00271                 {
00272                     statusFilter = new RemoteSystemStatusTypeFilter(RemoteSystemStatusType.Any);
00273                 }
00274                 filters.Add(statusFilter);
00275             }
00276
00277             return filters;
00278         }
00279
00280         private void SearchCleanup()
00281         {
00282             if (m_remoteSystemWatcher != null)
00283             {
00284                 m_remoteSystemWatcher.Stop();
00285                 m_remoteSystemWatcher = null;
00286             }
00287             m_rootPage.systemList.Clear();
00288             m_rootPage.systemMap.Clear();
00289             DeviceInfoTextBlock.Visibility = Visibility.Collapsed;
00290             DeviceInfoTextBlock.Text = "Select a device from the list to see its properties.";
00291         }
00292
00293         private void UpdateStatus(string status, NotifyType statusType)
00294         {
00295             m_rootPage.NotifyUser(status, statusType);
00296         }
00297
00298         private void SystemListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
00299         {
00300             RemoteSystem selectedRemoteSystem = ((sender as ListBox).SelectedItem as RemoteSystem);
00301
00302             if (selectedRemoteSystem != null)
00303             {
00304                 DeviceInfoTextBlock.Text = Environment.NewLine + "Manufacturer: " + selectedRemoteSystem.ManufacturerDisplayName + Environment.NewLine + "Model: " + selectedRemoteSystem.ModelDisplayName + Environment.NewLine;
00305             }
00306         }
00307     }
00308 }
Generated on Fri Nov 15 2024 22:18:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_CheckConsentAvailability Member List

This is the complete list of members for Scenario1_CheckConsentAvailability, including all inherited members.
CheckAvailability_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario1_CheckConsentAvailability
Scenario1_CheckConsentAvailability() | Scenario1_CheckConsentAvailability
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JumpList/cppwinrt/Scenario1_Launched.h Source File

  • JumpList
  • cppwinrt

Scenario1_Launched.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Launched.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_Launched : Scenario1_LaunchedT<Scenario1_Launched>
00019     {
00020         Scenario1_Launched();
00021
00022         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario1_Launched : Scenario1_LaunchedT<Scenario1_Launched, implementation::Scenario1_Launched>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:20:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario11_DeleteCookie Member List

This is the complete list of members for Scenario11_DeleteCookie, including all inherited members.
DeleteCookie_Click(object sender, RoutedEventArgs e) | Scenario11_DeleteCookie | [inline, private]
rootPage | Scenario11_DeleteCookie | [private]
Scenario11_DeleteCookie() | Scenario11_DeleteCookie | [inline]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/ShareWebLink.xaml.cpp Source File

  • ShareSource
  • cpp

ShareWebLink.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ShareWebLink.xaml.cpp
00014 // Implementation of the ShareWebLink class
00015 //
00016
00017 #include "pch.h"
00018 #include "ShareWebLink.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::ApplicationModel::DataTransfer;
00025
00026 ShareWebLink::ShareWebLink()
00027 {
00028     InitializeComponent();
00029 }
00030
00031 bool ShareWebLink::GetShareContent(DataRequest^ request)
00032 {
00033     bool succeeded = false;
00034
00035     // The URI used in this sample is provided by the user so we need to ensure it's a well formatted absolute URI
00036     // before we try to share it.
00037     MainPage::Current->NotifyUser("", NotifyType::StatusMessage);
00038     Uri^ dataPackageUri = ValidateAndGetUri(UriToShare->Text);
00039     if (dataPackageUri != nullptr)
00040     {
00041         auto requestData = request->Data;
00042         requestData->Properties->Title = TitleInputBox->Text;
00043         requestData->Properties->Description = DescriptionInputBox->Text; // The description is optional.
00044         requestData->Properties->ContentSourceApplicationLink = ApplicationLink;
00045         requestData->SetWebLink(dataPackageUri);
00046         succeeded = true;
00047     }
00048     else
00049     {
00050         request->FailWithDisplayText("Enter the link you would like to share and try again.");
00051     }
00052     return succeeded;
00053 }
00054
00055 Uri^ ShareWebLink::ValidateAndGetUri(String^ uriString)
00056 {
00057     Uri^ uri = nullptr;
00058     try
00059     {
00060         uri = ref new Uri(uriString);
00061     }
00062     catch (InvalidArgumentException^)
00063     {
00064         MainPage::Current->NotifyUser("The link provided is not a valid absolute URI.", NotifyType::ErrorMessage);
00065     }
00066     catch (NullReferenceException^)
00067     {
00068         MainPage::Current->NotifyUser("Please provide a link to share.", NotifyType::ErrorMessage);
00069     }
00070     return uri;
00071 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlTailoredMultipleViews/cs/TailoredMultipleViews/MainPage.xaml.cs Source File

  • XamlTailoredMultipleViews
  • cs
  • TailoredMultipleViews

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿using OneHandedUse_TailoredMultipleViews.UserControls;
00002 using System;
00003 using System.Collections.Generic;
00004 using System.IO;
00005 using System.Linq;
00006 using System.Runtime.InteropServices.WindowsRuntime;
00007 using Windows.Foundation;
00008 using Windows.Foundation.Collections;
00009 using Windows.UI.Xaml;
00010 using Windows.UI.Xaml.Controls;
00011 using Windows.UI.Xaml.Controls.Primitives;
00012 using Windows.UI.Xaml.Data;
00013 using Windows.UI.Xaml.Input;
00014 using Windows.UI.Xaml.Media;
00015 using Windows.UI.Xaml.Navigation;
00016
00017 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00018
00019 namespace OneHandedUse_TailoredMultipleViews
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class MainPage : Page
00025     {
00026         public MainPage()
00027         {
00028             this.InitializeComponent();
00029             this.Loaded += MainPage_Loaded;
00030         }
00031
00032         private void MainPage_Loaded(object sender, RoutedEventArgs e)
00033         {
00034             list.SelectedIndex = 0;
00035         }
00036         private void SplitViewButton_Click(object sender, RoutedEventArgs e)
00037         {
00038             mainSplitview.IsPaneOpen = !mainSplitview.IsPaneOpen;
00039         }
00040
00041         private void list_SelectionChanged(object sender, SelectionChangedEventArgs e)
00042         {
00043             switch (list.SelectedIndex)
00044             {
00045                 case 0:
00046                     mainContentPC.Content = new Collections();
00047                     break;
00048                 case 1:
00049                     mainContentPC.Content = new Albums();
00050                     break;
00051                 case 2:
00052                     mainContentPC.Content = new Settings();
00053                     break;
00054             }
00055         }
00056     }
00057 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-SPI/cs/SampleConfiguration.cs Source File

  • IoT-SPI
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "SPI C# sample";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Read data from SPI device", ClassType=typeof(Scenario1_ReadData)},
00025         };
00026
00027     }
00028
00029     public class Scenario
00030     {
00031         public string Title { get; set; }
00032         public Type ClassType { get; set; }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundMediaPlayback/cs/Views/PlaylistView.xaml.cs Source File

  • BackgroundMediaPlayback
  • cs
  • Views

PlaylistView.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using BackgroundMediaPlayback.ViewModels;
00013 using System;
00014 using System.Collections.Generic;
00015 using System.Collections.ObjectModel;
00016 using System.ComponentModel;
00017 using System.IO;
00018 using System.Linq;
00019 using System.Runtime.InteropServices.WindowsRuntime;
00020 using Windows.Foundation;
00021 using Windows.Foundation.Collections;
00022 using Windows.UI.Xaml;
00023 using Windows.UI.Xaml.Controls;
00024 using Windows.UI.Xaml.Controls.Primitives;
00025 using Windows.UI.Xaml.Data;
00026 using Windows.UI.Xaml.Input;
00027 using Windows.UI.Xaml.Media;
00028 using Windows.UI.Xaml.Navigation;
00029
00030 namespace BackgroundMediaPlayback
00031 {
00032     /// <summary>
00033     /// A custom control for playlists that wraps a ListView.
00034     /// </summary>
00035     public sealed partial class PlaylistView : UserControl, INotifyPropertyChanged
00036     {
00037         MediaListViewModel mediaList;
00038
00039         public event PropertyChangedEventHandler PropertyChanged;
00040
00041         public PlaylistView()
00042         {
00043             this.InitializeComponent();
00044         }
00045
00046         /// <summary>
00047         /// Raised when an item is clicked
00048         /// </summary>
00049         public event ItemClickEventHandler ItemClick
00050         {
00051             add { listView.ItemClick += value; }
00052             remove { listView.ItemClick -= value; }
00053         }
00054
00055         /// <summary>
00056         /// Raised when the selection changes
00057         /// </summary>
00058         public event SelectionChangedEventHandler SelectionChanged
00059         {
00060             add { listView.SelectionChanged += value; }
00061             remove { listView.SelectionChanged -= value; }
00062         }
00063
00064         /// <summary>
00065         /// A collection of songs in the list to be displayed to the user
00066         /// </summary>
00067         public MediaListViewModel MediaList
00068         {
00069             get
00070             {
00071                 return mediaList;
00072             }
00073             set
00074             {
00075                 if (mediaList != value)
00076                 {
00077                     mediaList = value;
00078
00079                     // Setting ItemsSource = null on page unload throws, so avoid that
00080                     if (value != null)
00081                         listView.ItemsSource = mediaList;
00082
00083                     RaisePropertyChanged("MediaList");
00084                 }
00085             }
00086         }
00087
00088         void RaisePropertyChanged(string propertyName)
00089         {
00090             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
00091         }
00092     }
00093 }
Generated on Fri Nov 15 2024 22:18:21 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/Common/BasicShapes.h Source File

  • Simple3DGameDX
  • cppwinrt
  • Common

BasicShapes.h

Go to the documentation of this file.
00001 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 // PARTICULAR PURPOSE.
00005 //
00006 // Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include "BasicMath.h"
00011
00012 // Defines the vertex format for the shapes generated in the functions below.
00013 struct BasicVertex
00014 {
00015     float3 pos;  // position
00016     float3 norm; // surface normal vector
00017     float2 tex;  // texture coordinate
00018 };
00019
00020 // Defines the vertex format for all shapes generated in the functions below.
00021 struct TangentVertex
00022 {
00023     float3 pos;  // position
00024     float2 tex;  // texture coordinate
00025     float3 uTan; // texture coordinate u-tangent vector
00026     float3 vTan; // texture coordinate v-tangent vector
00027 };
00028
00029 // A helper class that provides convenient functions for creating common
00030 // geometrical shapes used by DirectX SDK samples.
00031 class BasicShapes
00032 {
00033     BasicShapes(ID3D11Device* d3dDevice);
00034
00035     void CreateCube(
00036         _Out_ ID3D11Buffer** vertexBuffer,
00037         _Out_ ID3D11Buffer** indexBuffer,
00038         _Out_opt_ unsigned int* vertexCount,
00039         _Out_opt_ unsigned int* indexCount
00040         );
00041     void CreateBox(
00042         float3 radii,
00043         _Out_ ID3D11Buffer** vertexBuffer,
00044         _Out_ ID3D11Buffer** indexBuffer,
00045         _Out_opt_ unsigned int* vertexCount,
00046         _Out_opt_ unsigned int* indexCount
00047         );
00048     void CreateSphere(
00049         _Out_ ID3D11Buffer** vertexBuffer,
00050         _Out_ ID3D11Buffer** indexBuffer,
00051         _Out_opt_ unsigned int* vertexCount,
00052         _Out_opt_ unsigned int* indexCount
00053         );
00054     void CreateTangentSphere(
00055         _Out_ ID3D11Buffer** vertexBuffer,
00056         _Out_ ID3D11Buffer** indexBuffer,
00057         _Out_opt_ unsigned int* vertexCount,
00058         _Out_opt_ unsigned int* indexCount
00059         );
00060     void CreateReferenceAxis(
00061         _Out_ ID3D11Buffer** vertexBuffer,
00062         _Out_ ID3D11Buffer** indexBuffer,
00063         _Out_opt_ unsigned int* vertexCount,
00064         _Out_opt_ unsigned int* indexCount
00065         );
00066
00067 private:
00068     winrt::com_ptr<ID3D11Device> m_d3dDevice;
00069
00070     void CreateVertexBuffer(
00071         _In_ unsigned int numVertices,
00072         _In_ BasicVertex* vertexData,
00073         _Out_ ID3D11Buffer** vertexBuffer
00074         );
00075
00076     void CreateIndexBuffer(
00077         _In_ unsigned int numIndices,
00078         _In_ unsigned short* indexData,
00079         _Out_ ID3D11Buffer** indexBuffer
00080         );
00081
00082     void CreateTangentVertexBuffer(
00083         _In_ unsigned int numVertices,
00084         _In_ TangentVertex* vertexData,
00085         _Out_ ID3D11Buffer** vertexBuffer
00086         );
00087
00088 };
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCloudFontIntegration/cpp/pch.cpp Source File

  • XamlCloudFontIntegration
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Include the standard header and generate the precompiled header.
00014 //
00015
00016 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisplayOrientation/cppwinrt/pch.h Source File

  • DisplayOrientation
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Graphics.Display.h"
00008 #include "winrt/Windows.System.h"
00009 #include "winrt/Windows.UI.Core.h"
00010 #include "winrt/Windows.UI.Xaml.h"
00011 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00012 #include "winrt/Windows.UI.Xaml.Controls.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00014 #include "winrt/Windows.UI.Xaml.Documents.h"
00015 #include "winrt/Windows.UI.Xaml.Interop.h"
00016 #include "winrt/Windows.UI.Xaml.Markup.h"
00017 #include "winrt/Windows.UI.Xaml.Media.h"
00018 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomHidDeviceAccess/cpp/Scenario2_FeatureReports.xaml.cpp Source File

  • CustomHidDeviceAccess
  • cpp

Scenario2_FeatureReports.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 //
00008 // Scenario2.xaml.cpp
00009 // Implementation of the Scenario2 class
00010 //
00011
00012 #include "pch.h"
00013 #include "Utilities.h"
00014 #include "EventHandlerForDevice.h"
00015 #include "Scenario2_FeatureReports.xaml.h"
00016 #include "MainPage.xaml.h"
00017
00018 using namespace SDKTemplate;
00019
00020 using namespace Platform;
00021 using namespace Platform::Collections;
00022 using namespace Concurrency;
00023 using namespace Windows::Devices::HumanInterfaceDevice;
00024 using namespace Windows::Storage::Streams;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Navigation;
00028
00029 FeatureReports::FeatureReports()
00030 {
00031     InitializeComponent();
00032 }
00033
00034 /// <summary>
00035 /// Invoked when this page is about to be displayed in a Frame.
00036 ///
00037 /// We will enable/disable parts of the UI if the device doesn't support it.
00038 /// </summary>
00039 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00040 /// property is typically used to configure the page.</param>
00041 void FeatureReports::OnNavigatedTo(NavigationEventArgs^ /* e */)
00042 {
00043     // We will disable the scenario that is not supported by the device.
00044     // If no devices are connected, none of the scenarios will be shown and an error will be displayed
00045     Platform::Collections::Map<DeviceType, UIElement^>^ deviceScenarios = ref new Platform::Collections::Map<DeviceType, UIElement^>();
00046     deviceScenarios->Insert(DeviceType::SuperMutt, SuperMuttScenario);
00047
00048     Utilities::SetUpDeviceScenarios(deviceScenarios, DeviceScenarioContainer);
00049 }
00050
00051 void FeatureReports::GetLedBlinkPattern_Click(Platform::Object^ /* sender */, Windows::UI::Xaml::RoutedEventArgs^ /* e */)
00052 {
00053     if (EventHandlerForDevice::Current->IsDeviceConnected)
00054     {
00055         ButtonGetLedBlinkPattern->IsEnabled = false;
00056
00057         // Re-enable get button after completing the get regardless of there was an error or not
00058         GetLedBlinkPatternAsync().then([this](task<void> getLedTask)
00059         {
00060             ButtonGetLedBlinkPattern->IsEnabled = true;
00061
00062             getLedTask.get();   // May throw exception if there was a problem getting Led pattern
00063         });
00064     }
00065     else
00066     {
00067         Utilities::NotifyDeviceNotConnected();
00068     }
00069 }
00070
00071 void FeatureReports::SetLedBlinkPattern_Click(Platform::Object^ /* sender */, Windows::UI::Xaml::RoutedEventArgs^ /* e */)
00072 {
00073     if (EventHandlerForDevice::Current->IsDeviceConnected)
00074     {
00075         ButtonSetLedBlinkPattern->IsEnabled = false;
00076
00077         uint8 pattern = static_cast<uint8>(LedBlinkPatternInput->SelectedIndex);
00078
00079         // Re-enable set button after completing the set regardless of there was an error or not
00080         SetLedBlinkPatternAsync(pattern).then([this](task<void> setLedTask)
00081         {
00082             ButtonSetLedBlinkPattern->IsEnabled = true;
00083
00084             setLedTask.get();   // May throw exception if there was an error reading
00085         });
00086     }
00087     else
00088     {
00089         Utilities::NotifyDeviceNotConnected();
00090     }
00091 }
00092
00093 /// <summary>
00094 /// Uses feature report to get the LED blink pattern.
00095 ///
00096 /// Any errors in async function will be passed down the task chain and will not be caught here because errors should
00097 /// be handled at the end of the task chain.
00098 ///
00099 /// The simplest way to obtain a byte from the buffer is by using a DataReader. DataReader provides a simple way
00100 /// to read from buffers (e.g. can return bytes, strings, ints).
00101 /// </summary>
00102 /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
00103 task<void> FeatureReports::GetLedBlinkPatternAsync()
00104 {
00105     return create_task(EventHandlerForDevice::Current->Device->GetFeatureReportAsync(SuperMutt::LedPattern::ReportId))
00106         .then([](task<HidFeatureReport^> featureReportTask)
00107     {
00108         HidFeatureReport^ featureReport = featureReportTask.get();    // Will throw an exception if there was an error getting the report
00109
00110         if (featureReport->Data->Length == 2)
00111         {
00112             Array<uint8>^ reportBuffer = ref new Array<uint8>(2);
00113             auto dataReader = DataReader::FromBuffer(featureReport->Data);
00114
00115             // Alternatively, you can call dataReader->ReadByte twice to get the second byte.
00116             dataReader->ReadBytes(reportBuffer);
00117
00118             // Report Id is always the first byte
00119             auto pattern = reportBuffer[1];
00120
00121             MainPage::Current->NotifyUser("The Led blink pattern is " + pattern.ToString(), NotifyType::StatusMessage);
00122         }
00123         else
00124         {
00125             MainPage::Current->NotifyUser("Expecting 2 bytes, but received " + featureReport->Data->Length, NotifyType::ErrorMessage);
00126         }
00127     });
00128 }
00129
00130 /// <summary>
00131 /// Uses a feature report to set the blink pattern on the SuperMutt's LED.
00132 ///
00133 /// Please note that when we create a FeatureReport, all data is nulled out in the report. Since we will only be modifying
00134 /// data we care about, the other bits that we don't care about, will be zeroed out. Controls will effectively do the same thing (
00135 /// all bits are zeroed out except for the bits we care about).
00136 ///
00137 /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be handled
00138 /// at the end of the task chain.
00139 ///
00140 /// The SuperMutt has the following patterns:
00141 /// 0 - LED always on
00142 /// 1 - LED flash 2 seconds on, 2 off, repeat
00143 /// 2 - LED flash 2 seconds on, 1 off, 2 on, 4 off, repeat
00144 /// ...
00145 /// 7 - 7 iterations of 2 on, 1 off, followed by 4 off, repeat
00146 /// </summary>
00147 /// <param name="pattern">A number from 0-7. Each number represents a different blinking pattern</param>
00148 /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
00149 task<void> FeatureReports::SetLedBlinkPatternAsync(uint8 pattern)
00150 {
00151     auto featureReport = EventHandlerForDevice::Current->Device->CreateFeatureReport(SuperMutt::LedPattern::ReportId);
00152
00153     auto dataWriter = ref new DataWriter();
00154
00155     // Report Id is always the first byte
00156     dataWriter->WriteByte((uint8)featureReport->Id);
00157     dataWriter->WriteByte(pattern);
00158
00159     featureReport->Data = dataWriter->DetachBuffer();
00160
00161     return create_task(EventHandlerForDevice::Current->Device->SendFeatureReportAsync(featureReport))
00162         .then([pattern](task<uint32> bytesWrittenTask)
00163     {
00164         bytesWrittenTask.get();    // If exception occured, let an exception flow down the task chain so it can be caught
00165
00166         MainPage::Current->NotifyUser("The Led blink pattern is set to " + pattern.ToString(), NotifyType::StatusMessage);
00167     });
00168 }
Generated on Fri Nov 15 2024 22:19:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFontImplementation/FontDownloadListener.h Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFontImplementation

FontDownloadListener.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "TextLayout.h"
00015
00016 namespace DWriteTextLayoutCloudFontImplementation
00017 {
00018     public delegate void FontDownloadCompletedHandler();
00019
00020
00021     // To use downloadable fonts, the app must implement
00022     // IDWriteFontDownloadListener.
00023     class Listener : public IDWriteFontDownloadListener
00024     {
00025     public:
00026         void STDMETHODCALLTYPE DownloadCompleted(
00027             _In_ IDWriteFontDownloadQueue* downloadQueue,
00028             _In_opt_ IUnknown* context,
00029             HRESULT downloadResult
00030             );
00031
00032         // IDWriteFontDownloadListener inherits from IUnknown
00033         HRESULT STDMETHODCALLTYPE QueryInterface(
00034             REFIID riid,
00035             _COM_Outptr_ void **obj
00036             ) override;
00037
00038         ULONG STDMETHODCALLTYPE AddRef() override;
00039
00040         ULONG STDMETHODCALLTYPE Release() override;
00041
00042     private:
00043         uint32 m_refCount = 0;
00044     };
00045
00046
00047     // This class wraps around the IDWriteFontDownloadListener
00048     // implementation to provide WinRT interop.
00049     public ref class FontDownloadListener sealed
00050     {
00051     public:
00052         FontDownloadListener();
00053         virtual ~FontDownloadListener();
00054
00055         static event FontDownloadCompletedHandler^ DownloadCompleted;
00056
00057         static void Initialize();
00058         static void BeginDownload();
00059
00060     internal:
00061         static void RaiseDownloadCompleted();
00062
00063     private:
00064         Microsoft::WRL::ComPtr<Listener>                    m_registeredListener; // native Listener class
00065         Microsoft::WRL::ComPtr<IDWriteFontDownloadQueue>    m_downloadQueue;
00066         uint32                                              m_token = 0;
00067     };
00068
00069 }
Generated on Fri Nov 15 2024 22:19:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario14_MeteredConnectionFilter.h Source File

  • HttpClient
  • cppwinrt

Scenario14_MeteredConnectionFilter.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario14_MeteredConnectionFilter.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario14_MeteredConnectionFilter : Scenario14_MeteredConnectionFilterT<Scenario14_MeteredConnectionFilter>
00020     {
00021         Scenario14_MeteredConnectionFilter();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025
00026         void OptInSwitch_Toggled(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         fire_and_forget Start_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void Cancel_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029
00030     private:
00031         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00032         HttpFilters::HttpMeteredConnectionFilter meteredConnectionFilter{ nullptr };
00033         Windows::Web::Http::HttpClient httpClient{ nullptr };
00034         Windows::Foundation::IAsyncAction pendingAction{ nullptr };
00035
00036         Windows::Foundation::IAsyncAction CancelableRequestAsync(Windows::Foundation::Uri resourceUri);
00037     };
00038 }
00039
00040 namespace winrt::SDKTemplate::factory_implementation
00041 {
00042     struct Scenario14_MeteredConnectionFilter : Scenario14_MeteredConnectionFilterT<Scenario14_MeteredConnectionFilter, implementation::Scenario14_MeteredConnectionFilter>
00043     {
00044     };
00045 }
Generated on Fri Nov 15 2024 22:19:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/ShareText.xaml.h Source File

  • ShareSource
  • cpp

ShareText.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ShareText.xaml.h
00014 // Declaration of the ShareText class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "SharePage.h"
00021 #include "ShareText.g.h"
00022 #include "MainPage.xaml.h"
00023
00024 namespace SDKTemplate
00025 {
00026     public ref class ShareText sealed
00027     {
00028     public:
00029         ShareText();
00030
00031     protected:
00032         virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request) override;
00033     };
00034 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MobileBroadband/cs/SampleConfiguration.cs Source File

  • MobileBroadband
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012
00013 using System;
00014 using System.Collections.Generic;
00015 using Windows.UI.Xaml.Controls;
00016 using MobileBroadband;
00017
00018 namespace SDKTemplate
00019 {
00020     public partial class MainPage : Page
00021     {
00022         public const string FEATURE_NAME = "MobileBroadband";
00023
00024
00025         List<Scenario> scenarios = new List<Scenario>
00026         {
00027             new Scenario() { Title = "Mobile Broadband Device", ClassType = typeof(MobileBroadband.BroadbandDevice) },
00028             new Scenario() { Title = "Network Account Watcher", ClassType = typeof(MobileBroadband.AccountWatcher) },
00029             new Scenario() { Title = "Connection UI", ClassType = typeof(MobileBroadband.ShowConnection) },
00030             new Scenario() { Title = "Get Connection Profiles", ClassType = typeof(MobileBroadband.GetConnectionProfiles) },
00031             new Scenario() { Title = "Modem information (New)", ClassType = typeof(MobileBroadband.ModemInformation) },
00032             new Scenario() { Title = "Device Services (New)", ClassType = typeof(MobileBroadband.ModemDeviceServices) },
00033             new Scenario() { Title = "SIM Card (New)", ClassType = typeof(MobileBroadband.SimCard) },
00034         };
00035     }
00036
00037     public class Scenario
00038     {
00039         public string Title { get; set; }
00040         public Type ClassType { get; set; }
00041     }
00042 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DescriptorTypeEntry Member List

This is the complete list of members for DescriptorTypeEntry, including all inherited members.
descriptorType | DescriptorTypeEntry | [private]
DescriptorType | DescriptorTypeEntry |
DescriptorTypeEntry(String name, Descriptor type) | DescriptorTypeEntry | [inline]
EntryName | DescriptorTypeEntry |
entryName | DescriptorTypeEntry | [private]
Generated on Fri Nov 15 2024 22:23:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cppwinrt/SampleConfiguration.h Source File

  • FileThumbnails
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014 #include "MainPage.h"
00015
00016 namespace winrt
00017 {
00018     hstring to_hstring(Windows::Storage::FileProperties::ThumbnailMode thumbnailMode);
00019 }
00020
00021 namespace winrt::SDKTemplate
00022 {
00023     struct FileExtensions
00024     {
00025         static std::vector<hstring> const& Document();
00026         static std::vector<hstring> const& Image();
00027         static std::vector<hstring> const& Music();
00028     };
00029
00030     struct Errors
00031     {
00032         static constexpr wchar_t NoExifThumbnail[] = L"No result (no EXIF thumbnail or cached thumbnail available for fast retrieval)";
00033         static constexpr wchar_t NoThumbnail[] = L"No result (no thumbnail could be obtained from the selected file)";
00034         static constexpr wchar_t NoAlbumArt[] = L"No result (no album art available for this song)";
00035         static constexpr wchar_t NoIcon[] = L"No result (no icon available for this document type)";
00036         static constexpr wchar_t NoImages[] = L"No result (no thumbnail could be obtained from the selected folder - make sure that the folder contains images)";
00037         static constexpr wchar_t FileGroupEmpty[] = L"No result (unexpected error: retrieved file group was null)";
00038         static constexpr wchar_t FileGroupLocation[] = L"File groups are only available for library locations, please select a folder from one of your libraries";
00039         static constexpr wchar_t Cancel[] = L"No result (operation cancelled, no item selected)";
00040         static constexpr wchar_t InvalidSize[] = L"Invalid size (specified size must be numerical and greater than zero)";
00041     };
00042
00043     struct Helpers
00044     {
00045         static Windows::UI::Xaml::Media::Imaging::BitmapImage PlaceholderImage();
00046         static void DisplayResult(
00047             Windows::UI::Xaml::Controls::Image const& image,
00048             Windows::UI::Xaml::Controls::TextBlock const& textBlock,
00049             Windows::Storage::FileProperties::ThumbnailMode thumbnailMode,
00050             uint32_t size,
00051             Windows::Storage::IStorageItem const& item,
00052             Windows::Storage::FileProperties::StorageItemThumbnail const& thumbnail,
00053             bool isGroup);
00054         static void ResetOutput(
00055             MainPage const& rootPage,
00056             Windows::UI::Xaml::Controls::Image const& image,
00057             Windows::UI::Xaml::Controls::TextBlock const& output,
00058             Windows::UI::Xaml::Controls::TextBlock const& outputDetails = nullptr);
00059     };
00060 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_Full Member List

This is the complete list of members for Scenario3_Full, including all inherited members.
rootPage | Scenario3_Full | [private]
Scenario3_Full() | Scenario3_Full | [inline]
ShowContactCard_Click(object sender, RoutedEventArgs e) | Scenario3_Full | [inline, private]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_ToggleMobileHotspot Member List

This is the complete list of members for Scenario2_ToggleMobileHotspot, including all inherited members.
MobileHotspotToggle_Toggled(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario2_ToggleMobileHotspot
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario2_ToggleMobileHotspot
Scenario2_ToggleMobileHotspot() | Scenario2_ToggleMobileHotspot
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDataVirtualization/cs/Scenario2/Scenario2.xaml.cs Source File

  • XamlDataVirtualization
  • cs
  • Scenario2

Scenario2.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using SDKTemplate;
00017 using Windows.Storage;
00018
00019 namespace DataVirtualizationSample
00020 {
00021     public sealed partial class Scenario2 : Page
00022     {
00023         public Scenario2()
00024         {
00025             this.InitializeComponent();
00026             Grid1.ContainerContentChanging += Grid1_ContainerContentChanging;
00027             initdata();
00028         }
00029
00030         private void Grid1_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
00031         {
00032             if (!args.InRecycleQueue)
00033             {
00034                 FrameworkElement ctr = (FrameworkElement)args.ItemContainer.ContentTemplateRoot;
00035                 if (ctr != null)
00036                 {
00037                     TextBlock t = (TextBlock)ctr.FindName("idx");
00038                     t.Text = args.ItemIndex.ToString();
00039                 }
00040             }
00041         }
00042
00043         async void initdata()
00044         {
00045             StorageLibrary pictures = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
00046             string path = pictures.SaveFolder.Path;
00047
00048             FileDataSource2 ds = await FileDataSource2.GetDataSoure(path);
00049             if (ds.Count > 0)
00050             {
00051                 Grid1.ItemsSource = ds;
00052             }
00053             else
00054             {
00055                 MainPage.Current.NotifyUser("Error: The pictures folder doesn't contain any files", NotifyType.ErrorMessage);
00056             }
00057         }
00058
00059         private void ForceReset_Click(object sender, RoutedEventArgs e)
00060         {
00061             FileDataSource2 ds = Grid1.ItemsSource as FileDataSource2;
00062             if (ds != null) ds.ResetCollection();
00063         }
00064     }
00065 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LiveDash/cs/LiveDash/Util/DashManifestParser.cs Source File

  • LiveDash
  • cs
  • LiveDash
  • Util

DashManifestParser.cs

Go to the documentation of this file.
00001 ﻿using LiveDash.Models;
00002 using System;
00003 using System.Collections.Generic;
00004 using System.Linq;
00005 using System.Text;
00006 using System.Threading.Tasks;
00007 using System.Xml;
00008 using Windows.Data.Xml.Dom;
00009 using System.Text.RegularExpressions;
00010
00011 namespace LiveDash.Util
00012 {
00013     public class DashManifestParser
00014     {
00015         public const string LiveProfile = "urn:mpeg:dash:profile:isoff-live:2011";
00016         private const string HttpPrefix = "http://";
00017         private const string HttpsPrefix = "https://";
00018         public const int LiveSegmentCount = int.MaxValue / 2;
00019         private Windows.Data.Xml.Dom.XmlDocument document;
00020         private Manifest manifest;
00021
00022         private bool hasPeriodStartAttribute;
00023         private TimeSpan periodStart;
00024         public DashManifestParser(Windows.Data.Xml.Dom.XmlDocument document, ref Manifest manifest)
00025         {
00026             this.document = document;
00027             this.manifest = manifest;
00028         }
00029         public bool Parse()
00030         {
00031             try
00032             {
00033 #if DEBUG
00034                 Logger.Log("Begin parsing DASH manifest");
00035 #endif
00036                 ParseMPDElement();
00037                 UpdateBaseUrl();
00038
00039                 var periods = document.DocumentElement.ChildNodes.Where(node => node.NodeName.Equals("Period"));
00040 #if DEBUG
00041                 Logger.Log(periods.Count().ToString() + " Periods found");
00042 #endif
00043                 foreach (var period in periods)
00044                 {
00045                     Period dashPeriod = new Period();
00046                     periodStart = TimeSpan.FromSeconds(0);
00047                     ParsePeriodElement(period, ref dashPeriod);
00048
00049                     var adaptationSets = period.ChildNodes.Where(node => node.NodeName.Equals("AdaptationSet"));
00050 #if DEBUG
00051                     Logger.Log(adaptationSets.Count().ToString() + " Adaptation Sets found");
00052 #endif
00053                     foreach (var adaptationSet in adaptationSets)
00054                     {
00055                         MediaStream stream = new MediaStream();
00056
00057                         if (adaptationSet.Attributes.GetNamedItem("mimeType") != null)
00058                         {
00059                             stream.MimeType = adaptationSet.Attributes.GetNamedItem("mimeType").InnerText;
00060                         }
00061                         if (adaptationSet.Attributes.GetNamedItem("lang") != null)
00062                         {
00063                             stream.Language = adaptationSet.Attributes.GetNamedItem("lang").InnerText.Replace(" ", string.Empty);
00064                         }
00065
00066                         var representations = adaptationSet.ChildNodes.Where(node => node.NodeName.Equals("Representation"));
00067                         //We are only grabbing one Representation in an Adaptation Set (the lowest one, just to be safe)
00068                         //(No support for adaptive streaming)
00069                         IXmlNode representation = GetLowestBitrateRepresentation(representations);
00070 #if DEBUG
00071                         Logger.Log(representations.Count().ToString() + " Representations in " + stream.MimeType + " Adaptation Set with bitrate " + uint.Parse(representation.Attributes.GetNamedItem("bandwidth").InnerText));
00072 #endif
00073
00074                         //Parse Representation Element
00075                         uint bitrate;
00076                         string repID = string.Empty;
00077                         ParseRepresentationElement(representation,
00078                             out bitrate,
00079                             out repID);
00080
00081                         var segmentTemplateQuery = adaptationSet.ChildNodes.Where(node => node.NodeName.Equals("SegmentTemplate"));
00082                         var segmentListQuery = adaptationSet.ChildNodes.Where(node => node.NodeName.Equals("SegmentList"));
00083                         var segmentBaseQuery = adaptationSet.ChildNodes.Where(node => node.NodeName.Equals("SegmentBase"));
00084                         if (segmentTemplateQuery.Count() != 0)
00085                         {
00086                             stream.SegmentInfoType = MediaStream.SegmentInformationType.Template;
00087                             //Parse Segment Template Element
00088                             UInt64 timescale = 1;
00089                             string initializationFormat = string.Empty;
00090                             string mediaFormat = string.Empty;
00091                             UInt64 segmentDuration = 0;
00092                             uint startNumber = 1;
00093                             UInt64 presentationTimeOffset = 0;
00094                             var segmentTemplate = segmentTemplateQuery.First();
00095
00096                             ParseSegmentTemplateElement(segmentTemplate,
00097                                 ref timescale, ref initializationFormat,
00098                                 ref mediaFormat, ref segmentDuration,
00099                                 ref startNumber, ref presentationTimeOffset);
00100
00101                             DeterminePeriodStart(presentationTimeOffset, period, ref dashPeriod);
00102
00103                             string initializationUrl;
00104                             //$Number$ and $Time$ will never be present in the initialization URL
00105                             ExpandDASHUrlSegmentTemplate(initializationFormat, manifest.BaseUrl,
00106                                 bitrate, repID, 0, 0, out initializationUrl);
00107                             stream.InitSegmentUrl = initializationUrl;
00108
00109                             var segmentTimelineQuery = segmentTemplate.ChildNodes.Where(node => node.NodeName.Equals("SegmentTimeline"));
00110
00111                             MediaSegmentInformation segmentInfo = new MediaSegmentInformation();
00112                             segmentInfo.Timescale = timescale;
00113                             segmentInfo.RepresentationID = repID;
00114                             segmentInfo.Bitrate = bitrate;
00115
00116                             //No timeline present.
00117                             //Instead of populating the segments in the stream, we will give just enough information to produce
00118                             //the information to construct media segment urls on the fly in the SourceBufferManager
00119                             if (segmentTimelineQuery.Count() == 0)
00120                             {
00121 #if DEBUG
00122                                 Logger.Log("Making number base segment info from SegmentTemplate");
00123 #endif
00124                                 stream.SegmentTemplateBase = MediaStream.SegmentTemplateIdentifier.Number;
00125
00126                                 segmentInfo.Duration = segmentDuration;
00127                                 segmentInfo.UrlTemplate = mediaFormat;
00128
00129                                 UInt64 segmentNumber = startNumber;
00130                                 if (manifest.IsLive)
00131                                 {
00132                                     var hnsFragmentDuration = ((segmentDuration * 10000000) / timescale);
00133                                     CalculateNumberIdentifierForLive(hnsFragmentDuration, ref segmentNumber);
00134                                 }
00135                                 segmentInfo.StartNumber = segmentNumber;
00136
00137                                 segmentInfo.StartTimestamp = segmentDuration * (segmentNumber - 1);
00138
00139                                 stream.CanGenerateSegmentsDynamically = true;
00140                             }
00141                             else
00142                             {
00143                                 stream.SegmentTemplateBase = MediaStream.SegmentTemplateIdentifier.Time;
00144
00145                                 MakeTimelineInfo(segmentTimelineQuery.First(), bitrate, timescale,
00146                                     repID, startNumber, presentationTimeOffset,
00147                                     mediaFormat, ref stream);
00148                             }
00149
00150                             stream.SegmentInformation = segmentInfo;
00151                         }
00152                         else if (segmentListQuery.Count() != 0)
00153                         {
00154 #if DEBUG
00155                             Logger.Log("Manifest parsing error: " + "Does not support a SegmentList implementation");
00156 #endif
00157                             stream.SegmentInfoType = MediaStream.SegmentInformationType.List;
00158                         }
00159                         else
00160                         {
00161 #if DEBUG
00162                             Logger.Log("Manifest parsing error: " + "Does not support a SegmentBase or BaseUrl implementation");
00163 #endif
00164                             stream.SegmentInfoType = MediaStream.SegmentInformationType.Base;
00165                         }
00166
00167
00168                         dashPeriod.AddStream(stream);
00169                     } // each adaptation set
00170
00171                     manifest.AddPeriod(dashPeriod);
00172                 }// each period
00173                 manifest.SetFirstSelectedPeriod();
00174             }
00175             catch (Exception e)
00176             {
00177 #if DEBUG
00178                 Logger.Log("Manifest parsing error " + Logger.Display(e));
00179 #endif
00180                 return false;
00181             }
00182             return true;
00183         }
00184
00185         private void DeterminePeriodStart(ulong presentationTimeOffset, IXmlNode periodNode, ref Period period)
00186         {
00187             if (hasPeriodStartAttribute)
00188             {
00189                 return;
00190             }
00191         }
00192
00193         private IXmlNode GetLowestBitrateRepresentation(IEnumerable<IXmlNode> representations)
00194         {
00195             uint minBitrate = uint.MaxValue;
00196             IXmlNode minBitrateRepresentation = null;
00197             foreach (var representation in representations)
00198             {
00199                 var bandwidthNode = representation.Attributes.GetNamedItem("bandwidth");
00200                 if (bandwidthNode != null)
00201                 {
00202                     uint bitrate = uint.Parse(bandwidthNode.InnerText);
00203                     if (bitrate < minBitrate)
00204                     {
00205                         minBitrateRepresentation = representation;
00206                         minBitrate = bitrate;
00207                     }
00208                 }
00209             }
00210             return minBitrateRepresentation;
00211         }
00212
00213         private void ParseMPDElement()
00214         {
00215             Windows.Data.Xml.Dom.XmlElement root = document.DocumentElement;
00216             if (root.GetAttribute("type").ToLower().Equals("dynamic"))
00217             {
00218                 manifest.IsLive = true;
00219             }
00220             if (root.GetAttribute("profiles").ToLower().Contains(LiveProfile))
00221             {
00222                 manifest.IsSupportedProfile = true;
00223             }
00224             if (!root.GetAttribute("availabilityStartTime").Equals(""))
00225             {
00226                 string availabilityStartTime = root.GetAttribute("availabilityStartTime");
00227                 manifest.AvailibilityStartTime = XmlConvert.ToDateTimeOffset(availabilityStartTime);
00228             }
00229             if (!root.GetAttribute("minBufferTime").Equals(""))
00230             {
00231                 string minBufferTime = root.GetAttribute("minBufferTime");
00232                 manifest.MinBufferTime = XmlConvert.ToTimeSpan(minBufferTime);
00233             }
00234             if (!root.GetAttribute("minimumUpdatePeriod").Equals(""))
00235             {
00236                 manifest.HasMinimumUpdatePeriod = true;
00237                 string minUpdatePeriod = root.GetAttribute("minimumUpdatePeriod");
00238                 manifest.MinimumUpdatePeriod = XmlConvert.ToTimeSpan(minUpdatePeriod);
00239             }
00240             if (!root.GetAttribute("mediaPresentationDuration").Equals(""))
00241             {
00242                 manifest.HasPresentationDuration = true;
00243                 string mediaPresentationDuration = root.GetAttribute("mediaPresentationDuration");
00244                 manifest.MediaPresentationDuration = XmlConvert.ToTimeSpan(mediaPresentationDuration);
00245             }
00246             if (!root.GetAttribute("timeShiftBufferDepth").Equals(""))
00247             {
00248                 string timeShiftBufferDepth = root.GetAttribute("timeShiftBufferDepth");
00249                 manifest.TimeShiftBufferDepth = XmlConvert.ToTimeSpan(timeShiftBufferDepth);
00250             }
00251             if (!root.GetAttribute("publishTime").Equals(""))
00252             {
00253                 string publishTime = root.GetAttribute("publishTime");
00254                 manifest.PublishTime = XmlConvert.ToDateTimeOffset(publishTime);
00255             }
00256             else
00257             {
00258                 manifest.PublishTime = DateTimeOffset.MinValue;
00259             }
00260             Windows.Data.Xml.Dom.XmlNodeList periods = root.GetElementsByTagName("Period");
00261             if (periods.Count() > 1)
00262             {
00263                 manifest.HasMultiplePeriods = true;
00264             }
00265
00266             IXmlNode lastPeriod = periods.Last<IXmlNode>();
00267             if (lastPeriod.Attributes.GetNamedItem("duration") != null)
00268             {
00269                 manifest.LastPeriodDuration = XmlConvert.ToTimeSpan(lastPeriod.Attributes.GetNamedItem("duration").InnerText);
00270             }
00271         }
00272
00273         private void ParsePeriodElement(IXmlNode periodElement, ref Period period)
00274         {
00275             if (periodElement.Attributes.GetNamedItem("id") != null)
00276             {
00277                 period.Id = periodElement.Attributes.GetNamedItem("id").InnerText;
00278             }
00279             if (periodElement.Attributes.GetNamedItem("duration") != null)
00280             {
00281                 string periodDuration = periodElement.Attributes.GetNamedItem("duration").InnerText;
00282                 period.Duration = XmlConvert.ToTimeSpan(periodDuration);
00283             }
00284             if (periodElement.Attributes.GetNamedItem("start") != null)
00285             {
00286                 string periodStart = periodElement.Attributes.GetNamedItem("start").InnerText;
00287                 period.Start = XmlConvert.ToTimeSpan(periodStart);
00288                 this.periodStart = period.Start;
00289                 hasPeriodStartAttribute = true;
00290             }
00291         }
00292
00293         private void ParseRepresentationElement(IXmlNode representaion, out uint bitrate, out string repID)
00294         {
00295             repID = string.Empty;
00296             if (representaion.Attributes.GetNamedItem("id") != null)
00297             {
00298                 repID = representaion.Attributes.GetNamedItem("id").InnerText;
00299             }
00300
00301             bitrate = 0;
00302             if (representaion.Attributes.GetNamedItem("bandwidth") != null)
00303             {
00304                 string bandwidthText = representaion.Attributes.GetNamedItem("bandwidth").InnerText;
00305                 bitrate = XmlConvert.ToUInt32(bandwidthText);
00306             }
00307         }
00308
00309         private void ParseSegmentTemplateElement(IXmlNode segmentTemplate,
00310             ref UInt64 timescale, ref string initializationFormat,
00311             ref string mediaFormat, ref UInt64 duration,
00312             ref uint startNumber, ref UInt64 presentationTimeOffset)
00313         {
00314             if (segmentTemplate.Attributes.GetNamedItem("duration") != null)
00315             {
00316                 string durationText = segmentTemplate.Attributes.GetNamedItem("duration").InnerText;
00317                 duration = XmlConvert.ToUInt64(durationText);
00318             }
00319             if (segmentTemplate.Attributes.GetNamedItem("initialization") != null)
00320             {
00321                 initializationFormat = segmentTemplate.Attributes.GetNamedItem("initialization").InnerText;
00322             }
00323             if (segmentTemplate.Attributes.GetNamedItem("media") != null)
00324             {
00325                 mediaFormat = segmentTemplate.Attributes.GetNamedItem("media").InnerText;
00326             }
00327             if (segmentTemplate.Attributes.GetNamedItem("startNumber") != null)
00328             {
00329                 string startNumberText = segmentTemplate.Attributes.GetNamedItem("startNumber").InnerText;
00330                 startNumber = XmlConvert.ToUInt32(startNumberText);
00331             }
00332             if (segmentTemplate.Attributes.GetNamedItem("timescale") != null)
00333             {
00334                 string timescaleText = segmentTemplate.Attributes.GetNamedItem("timescale").InnerText;
00335                 timescale = XmlConvert.ToUInt64(timescaleText);
00336             }
00337             if (segmentTemplate.Attributes.GetNamedItem("presentationTimeOffset") != null)
00338             {
00339                 string presentationTimeOffsetText = segmentTemplate.Attributes.GetNamedItem("presentationTimeOffset").InnerText;
00340                 presentationTimeOffset = XmlConvert.ToUInt64(presentationTimeOffsetText);
00341             }
00342         }
00343
00344         static internal void ExpandDASHUrlSegmentTemplate(string format, string baseUrl, uint bitrate, string repID, ulong number, ulong time, out string result)
00345         {
00346             result = string.Empty;
00347             //Use the base url if the template url is not based already
00348             if (format.StartsWith(HttpPrefix) || format.StartsWith(HttpsPrefix))
00349             {
00350                 result += format;
00351
00352             }
00353             else
00354             {
00355                 result += baseUrl;
00356
00357                 //Ensure there's one slash (and only one)
00358                 //seperating the base from the template url
00359                 if (!result.EndsWith("/") && !result.EndsWith("&")
00360                     && !result.EndsWith(";"))
00361                 {
00362                     result += '/';
00363                 }
00364
00365                 result += format;
00366
00367             }
00368
00369             result = result.Replace("$Bandwidth$", bitrate.ToString());
00370             result = result.Replace("$Number$", number.ToString());
00371             result = result.Replace("$Time$", time.ToString());
00372             result = result.Replace("$RepresentationID$", repID.ToString());
00373         }
00374
00375         private static string ResolvePadding(string template, string idMatch, ulong value)
00376         {
00377             Regex paddingRegex = new Regex("(%\\d+d)+");
00378
00379             var paddingMatch = paddingRegex.Match(idMatch);
00380
00381             string temp = String.Format(paddingMatch.Value, value);
00382
00383             temp = template.Replace(idMatch, temp);
00384
00385             return temp;
00386         }
00387
00388         private void MakeNumberBaseSegmentInfo(uint bitrate, UInt64 timescale,
00389             UInt64 segmentDuration, string repID,
00390             uint startNumber, string mediaFormat, ref MediaStream stream)
00391         {
00392             var hnsPresentationDuration = (Convert.ToUInt64(manifest.MediaPresentationDuration.TotalMilliseconds) * Convert.ToUInt64(10000));
00393             var hnsFragmentDuration = ((segmentDuration * 10000000) / timescale);
00394             UInt64 count = (uint)(hnsPresentationDuration / hnsFragmentDuration);
00395             UInt64 remain = (uint)(hnsPresentationDuration - (hnsFragmentDuration * count));
00396
00397             if (manifest.IsLive && count == 0)
00398             {
00399                 if (manifest.TimeShiftBufferDepth.TotalSeconds > 0 && hnsFragmentDuration > 0)
00400                 {
00401                     var hnsTimeShiftBufferDepth = (ulong)(manifest.TimeShiftBufferDepth.TotalSeconds * 10000000);
00402                     count = hnsTimeShiftBufferDepth / hnsFragmentDuration;
00403                 }
00404                 else
00405                 {
00406                     count = LiveSegmentCount;
00407                 }
00408             }
00409
00410             UInt64 time = 0;
00411
00412             UInt64 segmentNumber = startNumber;
00413             if (manifest.IsLive)
00414             {
00415                 CalculateNumberIdentifierForLive(hnsFragmentDuration, ref segmentNumber);
00416             }
00417             //Since we calculated the latest segment number, we will add to the front of the list
00418             for (UInt64 i = 0; i < count; i++)
00419             {
00420                 MediaSegment segment = new MediaSegment();
00421                 segment.Timestamp = time;
00422                 segment.Duration = segmentDuration;
00423                 segment.Number = segmentNumber;
00424
00425                 //Construct the mediaURL
00426                 string mediaSegmentUrl;
00427                 ExpandDASHUrlSegmentTemplate(mediaFormat, manifest.BaseUrl, bitrate,
00428                     repID, segmentNumber, time, out mediaSegmentUrl);
00429                 segment.SegmentUrl = mediaSegmentUrl;
00430
00431                 stream.PushBackSegment(segment);
00432                 segmentNumber++;
00433                 time += segmentDuration;
00434
00435             }
00436
00437             if (remain > 0)
00438             {
00439                 MediaSegment segment = new MediaSegment();
00440                 segment.Timestamp = time;
00441                 segment.Duration = remain / timescale;
00442                 segment.Number = segmentNumber;
00443
00444                 string mediaSegmentUrl;
00445                 ExpandDASHUrlSegmentTemplate(mediaFormat, manifest.BaseUrl, bitrate,
00446                     repID, segmentNumber, time, out mediaSegmentUrl);
00447                 segment.SegmentUrl = mediaSegmentUrl;
00448
00449                 stream.PushBackSegment(segment);
00450
00451 #if DEBUG
00452                 Logger.Log("Adding final segment to stream with MimeType:" + stream.MimeType + ". Segment{ Timestamp: " + time + "Duration: "
00453                         + segmentDuration + "Number: " + startNumber + "}"
00454                         + "\nURL: " + segment.SegmentUrl);
00455 #endif
00456                 time += segmentDuration;
00457             }
00458         }
00459
00460         private void CalculateNumberIdentifierForLive(ulong hnsFragmentDuration, ref ulong segmentNumber)
00461         {
00462             //This formula is to get the latest segment number.
00463             DateTimeOffset availStartTime = manifest.AvailibilityStartTime;
00464             DateTimeOffset now = GetWallClockTime();
00465
00466             if (manifest.HasPresentationDuration)
00467             {
00468                 var endOfPresentation = availStartTime.DateTime.AddSeconds(manifest.MediaPresentationDuration.TotalSeconds);
00469
00470
00471                 if (endOfPresentation < now.DateTime)
00472                 {
00473                     manifest.TreatAsOnDemand = true;
00474 #if DEBUG
00475                     Logger.Log("The time now is after the end of the presentation. Attempt to start from the beginning " + segmentNumber);
00476 #endif
00477                     return;
00478                 }
00479             }
00480
00481             TimeSpan timeSpanElapsed = now.DateTime - availStartTime.DateTime;
00482             var hnsTimeElapsed = (ulong)(timeSpanElapsed.TotalMilliseconds * 10000);
00483             hnsTimeElapsed -= (ulong)(hnsFragmentDuration * 1.5);
00484             var num = hnsTimeElapsed / hnsFragmentDuration;
00485 #if DEBUG
00486             Logger.Log("Number for Live Manifest " + num);
00487 #endif
00488             segmentNumber += num;
00489         }
00490
00491         private DateTimeOffset GetWallClockTime()
00492         {
00493             //CHANGE HOW TO RETRIEVE THE WALL CLOCK IN THIS LOCATION
00494             //If an element is present to retrieve from a server, use
00495             //the time from the server.
00496             return DateTimeOffset.UtcNow;
00497         }
00498
00499         private void MakeTimelineInfo(IXmlNode segmentTimeline, uint bitrate,
00500             ulong timescale, string repID,
00501             uint startNumber, ulong presentationTimeOffset,
00502             string mediaFormat, ref MediaStream stream)
00503         {
00504             var timeline = segmentTimeline.ChildNodes.Where(x => x.NodeName == "S");
00505
00506             uint segmentNumber = startNumber;
00507             ulong time = 0;
00508             //Set time equal to the @t attribute of first element, otherwise it is 0.
00509             //This is to replace the value of $Time$ in the media segment url
00510             var tAttribute = timeline.First().Attributes.GetNamedItem("t");
00511             if (tAttribute != null)
00512             {
00513                 time = ulong.Parse(tAttribute.InnerText);
00514             }
00515             foreach (var t in timeline)
00516             {
00517                 ulong duration = ulong.Parse(t.Attributes.GetNamedItem("d").InnerText);
00518                 var repeatAttribute = t.Attributes.GetNamedItem("r");
00519                 long repeats = 0;
00520                 if (repeatAttribute != null)
00521                 {
00522                     repeats = long.Parse(repeatAttribute.InnerText);
00523                 }
00524
00525                 for (int i = 0; i < repeats + 1; i++)
00526                 {
00527                     MediaSegment segment = new MediaSegment();
00528                     segment.Duration = duration;
00529                     segment.Timestamp = time - presentationTimeOffset;
00530                     segment.Number = segmentNumber;
00531
00532                     //Construct the mediaURL
00533                     string mediaSegmentUrl;
00534                     ExpandDASHUrlSegmentTemplate(mediaFormat, manifest.BaseUrl, bitrate,
00535                         repID, segmentNumber, time, out mediaSegmentUrl);
00536                     segment.SegmentUrl = mediaSegmentUrl;
00537
00538                     stream.PushBackSegment(segment);
00539                     time += duration;
00540                     segmentNumber++;
00541                 }
00542             }
00543
00544             double msStreamDuration = (double)time * (1000) / timescale;
00545 #if DEBUG
00546             Logger.Log("Found " + stream.Segments.Count() + " segments - Duration: " + msStreamDuration.ToString() + " miliseconds");
00547 #endif
00548
00549             if (msStreamDuration > manifest.MediaPresentationDuration.TotalMilliseconds)
00550             {
00551                 manifest.MediaPresentationDuration = TimeSpan.FromMilliseconds(msStreamDuration);
00552             }
00553         }
00554
00555         private void UpdateBaseUrl()
00556         {
00557             //This does not support all scenarios for the BaseUrl element.
00558             //It will find the first BaseUrl
00559             //Element in either the MPD element or the Period Element, top down
00560             //and append it to the base url of the manifest.
00561             var mpdBaseUrlElement = document.SelectNodes("*").Where(x => x.NodeName == "BaseURL");
00562             if (mpdBaseUrlElement.Count() != 0)
00563             {
00564                 string baseUrlText = mpdBaseUrlElement.First().InnerText;
00565                 if (baseUrlText.ToLower().StartsWith("http") || baseUrlText.ToLower().StartsWith("https"))
00566                 {
00567                     manifest.BaseUrl = baseUrlText;
00568                 }
00569                 else
00570                 {
00571                     manifest.AppendToBaseUrl(mpdBaseUrlElement.First().InnerText);
00572                 }
00573                 return;
00574             }
00575             var periodBaseUrlElement = document.SelectNodes("*").Where(x => x.NodeName == "BaseURL");
00576             if (periodBaseUrlElement.Count() != 0)
00577             {
00578                 string baseUrlText = periodBaseUrlElement.First().InnerText;
00579                 if (baseUrlText.ToLower().StartsWith("http") || baseUrlText.ToLower().StartsWith("https"))
00580                 {
00581                     manifest.BaseUrl = baseUrlText;
00582                 }
00583                 else
00584                 {
00585                     manifest.AppendToBaseUrl(periodBaseUrlElement.First().InnerText);
00586                 }
00587                 return;
00588             }
00589
00590         }
00591
00592     }
00593 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MessageDialog/cpp/SampleConfiguration.cpp Source File

  • MessageDialog
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Use custom commands", "SDKTemplate.CustomCommand" },
00012     { "Use default close command", "SDKTemplate.DefaultCloseCommand" },
00013     { "Use completed callback", "SDKTemplate.CompletedCallback" },
00014     { "Use cancel command", "SDKTemplate.CancelCommand" }
00015 };
Generated on Fri Nov 15 2024 22:17:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cpp/FileLoggingSessionScenario.h Source File

  • Logging
  • cpp

FileLoggingSessionScenario.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008 #include "LoggingScenarioEventArgs.h"
00009
00010 namespace SDKTemplate
00011 {
00012     ref class FileLoggingSessionScenario sealed
00013     {
00014     internal:
00015
00016         event StatusChangedHandler^ StatusChanged;
00017
00018         static property FileLoggingSessionScenario^ Instance
00019         {
00020             FileLoggingSessionScenario^ get()
00021             {
00022                 if (_instance == nullptr)
00023                 {
00024                     _instance = ref new FileLoggingSessionScenario();
00025                 }
00026                 return _instance;
00027             }
00028         }
00029
00030         property bool IsBusy
00031         {
00032             bool get() { return _isBusy; }
00033
00034         private:
00035
00036             void set(bool value)
00037             {
00038                 _isBusy = value;
00039                 StatusChanged(this, ref new LoggingScenarioEventArgs(LoggingScenarioEventType::BusyStatusChanged));
00040             }
00041         }
00042
00043         property int LogFileGeneratedCount
00044         {
00045             int get() { return _logFileGeneratedCount; }
00046         }
00047
00048         property bool LoggingEnabled
00049         {
00050             bool get() { return _session != nullptr; }
00051         }
00052
00053         concurrency::task<bool> ToggleLoggingEnabledDisabledAsync();
00054         void StartLogging();
00055
00056         concurrency::task<void> PrepareToSuspendAsync();
00057         void ResumeLoggingIfApplicable();
00058
00059         concurrency::task<void> DoScenarioAsync();
00060
00061     private:
00062
00063         FileLoggingSessionScenario();
00064         ~FileLoggingSessionScenario();
00065
00066         static void SetAppLocalSettingsValue(Platform::String^ key, Platform::Object^ value)
00067         {
00068             if (Windows::Storage::ApplicationData::Current->LocalSettings->Values->HasKey(key))
00069             {
00070                 Windows::Storage::ApplicationData::Current->LocalSettings->Values->Remove(key);
00071             }
00072             Windows::Storage::ApplicationData::Current->LocalSettings->Values->Insert(key, value);
00073         }
00074
00075         static bool IsAppLocalSettingsValue(Platform::String^ key)
00076         {
00077             return Windows::Storage::ApplicationData::Current->LocalSettings->Values->HasKey(key);
00078         }
00079
00080         static Platform::Object^ GetAppLocalSettingsValueAsObject(Platform::String^ key)
00081         {
00082             return Windows::Storage::ApplicationData::Current->LocalSettings->Values->Lookup(key);
00083         }
00084
00085         static bool GetAppLocalSettingsValueAsBool(Platform::String^ key)
00086         {
00087             Platform::Object^ obj = GetAppLocalSettingsValueAsObject(key);
00088             return safe_cast<bool>(obj);
00089         }
00090
00091         static Platform::String^ GetAppLocalSettingsValueAsString(Platform::String^ key)
00092         {
00093             Platform::Object^ obj = GetAppLocalSettingsValueAsObject(key);
00094             return safe_cast<Platform::String^>(obj);
00095         }
00096
00097         static FileLoggingSessionScenario^ _instance;
00098         Windows::Foundation::Diagnostics::FileLoggingSession^ _session;
00099         Windows::Foundation::Diagnostics::LoggingChannel^ _channel;
00100
00101         long _logFileGeneratedCount;
00102         bool _isPreparingForSuspend;
00103         bool _isBusy;
00104
00105         // The following are set when a LoggingChannel
00106         // calls OnChannelLoggingEnabled:
00107         bool _isChannelEnabled;
00108         Windows::Foundation::Diagnostics::LoggingLevel _channelLoggingLevel;
00109         Windows::Foundation::EventRegistrationToken _onChannelLoggingEnabledToken;
00110         void OnChannelLoggingEnabled(Windows::Foundation::Diagnostics::ILoggingChannel ^sender, Platform::Object ^args);
00111
00112         Windows::Foundation::EventRegistrationToken _onLogFileGeneratedToken;
00113         void OnLogFileGenerated(Windows::Foundation::Diagnostics::IFileLoggingSession^ sender, Windows::Foundation::Diagnostics::LogFileGeneratedEventArgs^ args);
00114
00115         concurrency::task<Windows::Storage::StorageFile^> CloseSessionSaveFinalLogFile();
00116         void OnAppSuspending(Platform::Object ^sender, Windows::ApplicationModel::SuspendingEventArgs ^e);
00117         void OnAppResuming(Platform::Object ^sender, Platform::Object ^args);
00118     };
00119 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Accelerometer/cpp/pch.h Source File

  • Accelerometer
  • cpp

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <collection.h>
00015 #include <ppltasks.h>
00016
00017 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ApplicationResources/cs/scenario9.xaml.cs Source File

  • ApplicationResources
  • cs

scenario9.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using SDKTemplate;
00015 using System;
00016 using Windows.ApplicationModel.Resources.Core;
00017 using System.Collections.Generic;
00018
00019 namespace SDKTemplate
00020 {
00021     /// <summary>
00022     /// An empty page that can be used on its own or navigated to within a Frame.
00023     /// </summary>
00024     public sealed partial class Scenario9 : Page
00025     {
00026         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00027         // as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         public Scenario9()
00031         {
00032             this.InitializeComponent();
00033         }
00034
00035         /// <summary>
00036         /// Invoked when this page is about to be displayed in a Frame.
00037         /// </summary>
00038         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00039         /// property is typically used to configure the page.</param>
00040         protected override void OnNavigatedTo(NavigationEventArgs e)
00041         {
00042         }
00043
00044         /// <summary>
00045         /// Invoked when the user has selected a different scenario and navigation away from
00046         /// this page is about to occur.
00047         /// </summary>
00048         /// <param name="e">Event data that describes the navigation that has unloaded this
00049         /// page.</param>
00050         protected override void OnNavigatedFrom(NavigationEventArgs e)
00051         {
00052             // Clearing qualifier value overrides set on the default context for the current
00053             // view so that an override set here doesn't impact other scenarios. See comments
00054             // below for additional information.
00055             ResourceContext.GetForCurrentView().Reset();
00056             base.OnNavigatedFrom(e);
00057         }
00058
00059         /// <summary>
00060         /// This is the click handler for the 'Scenario9Button_Show' button.  You would replace this with your own handler
00061         /// if you have a button or buttons on this page.
00062         /// </summary>
00063         /// <param name="sender"></param>
00064         /// <param name="e"></param>
00065         private void Scenario9Button_Show_Click(object sender, RoutedEventArgs e)
00066         {
00067             Button b = sender as Button;
00068             if (b != null)
00069             {
00070                 // A langauge override will be set on the default context for the current view.
00071                 // When navigating between different scenarios in this sample, the content for each
00072                 // scenario is loaded into a host page that remains constant. The view (meaning, the
00073                 // CoreWindow) remains the same, and so it is the same default context that's in use.
00074                 // Thus, an override set here can impact behavior in other scenarios.
00075                 //
00076                 // However, the description for the scenario may give the impression that a value
00077                 // being set is local to this scenario. Also, when entering this scenario, the combo
00078                 // box always gets set to the first item, which can add to the confusion. To avoid
00079                 // confusion when using this sample, the override that gets set here will be cleared
00080                 // when the user navigates away from this scenario (in the OnNavigatedFrom event
00081                 // handler). In a real app, whether and when to clear an override will depend on
00082                 // the desired behaviour and the design of the app.
00083
00084                 var context = ResourceContext.GetForCurrentView();
00085
00086                 var selectedLanguage = Scenario9ComboBox.SelectedValue;
00087                 if (selectedLanguage != null)
00088                 {
00089                     var lang = new List<string>();
00090                     lang.Add(selectedLanguage.ToString());
00091                     context.Languages = lang;
00092                     var resourceStringMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");
00093                     this.Scenario9TextBlock.Text = resourceStringMap.GetValue("string1", context).ValueAsString;
00094                 }
00095             }
00096         }
00097
00098     }
00099 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/HolographicMRCSampleMain.cpp Source File

  • HolographicMixedRealityCapture
  • cpp

HolographicMRCSampleMain.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "HolographicMRCSampleMain.h"
00003 #include "Common\DirectXHelper.h"
00004
00005 #include <windows.graphics.directx.direct3d11.interop.h>
00006 #include <Collection.h>
00007
00008
00009 using namespace HolographicMRCSample;
00010
00011 using namespace concurrency;
00012 using namespace Platform;
00013 using namespace Windows::Foundation;
00014 using namespace Windows::Foundation::Numerics;
00015 using namespace Windows::Graphics::Holographic;
00016 using namespace Windows::Perception::Spatial;
00017 using namespace Windows::UI::Input::Spatial;
00018 using namespace std::placeholders;
00019
00020 // Loads and initializes application assets when the application is loaded.
00021 HolographicMRCSampleMain::HolographicMRCSampleMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00022     m_deviceResources(deviceResources),
00023     m_recording(false)
00024 {
00025     // Register to be notified if the device is lost or recreated.
00026     m_deviceResources->RegisterDeviceNotify(this);
00027 }
00028
00029 void HolographicMRCSampleMain::SetHolographicSpace(HolographicSpace^ holographicSpace)
00030 {
00031     UnregisterHolographicEventHandlers();
00032
00033     m_holographicSpace = holographicSpace;
00034
00035 #ifdef DRAW_SAMPLE_CONTENT
00036     m_cursor = std::make_unique<Cursor>(0.01f, 0.01f);
00037     m_cursor->Initialize(m_deviceResources);
00038
00039     m_mainPanel = std::make_unique<Panel>(0.20f, 0.60f, 0.01f,      // Size
00040                                           0.5f, 0.5f, 0.5f, 1.0f);  // Color
00041     m_mainPanel->Initialize(m_deviceResources);
00042     m_mainPanel->SetPosition(Windows::Foundation::Numerics::float3(-0.25f, 0.0f, -2.0f));
00043
00044     // Init button
00045     m_initButton.reset(new Button(Windows::Foundation::Numerics::float3(0.14f, 0.07f, 0.01f),           // Size
00046                                   Windows::Foundation::Numerics::float4(1.0f, 1.0f, 0.5f, 1.0f),        // Color
00047                                   Windows::Foundation::Numerics::float4(1.0f, 1.0f, 0.9f, 1.0f),        // Focused Color
00048                                   Windows::Foundation::Numerics::float4(0.0f, 0.0f, 0.5f, 1.0f),        // Turned on Color
00049                                   DX::Texture_Init));
00050     m_initButton->Initialize(m_deviceResources);
00051     m_initButton->SetPosition(Windows::Foundation::Numerics::float3(0.0f, 0.25f, 0.01f));
00052     m_initButton->SetOnAirTapCallback(std::bind(&HolographicMRCSampleMain::OnButtonInitTapped, this));
00053     m_initButton->SetEnabled(true);
00054     m_mainPanel->AddChild(m_initButton);
00055
00056     // Photo button
00057     m_photoButton.reset(new Button(Windows::Foundation::Numerics::float3(0.14f, 0.07f, 0.01f),          // Size
00058                                    Windows::Foundation::Numerics::float4(1.0f, 1.0f, 0.5f, 1.0f),       // Color
00059                                    Windows::Foundation::Numerics::float4(1.0f, 1.0f, 0.9f, 1.0f),       // Focused Color
00060                                    Windows::Foundation::Numerics::float4(0.0f, 0.0f, 0.5f, 1.0f),       // Turned on Color
00061                                    DX::Texture_Photo));
00062     m_photoButton->Initialize(m_deviceResources);
00063     m_photoButton->SetPosition(Windows::Foundation::Numerics::float3(0.0f, 0.15f, 0.01f));
00064     m_photoButton->SetOnAirTapCallback(std::bind(&HolographicMRCSampleMain::OnButtonPhotoTapped, this));
00065     m_photoButton->SetEnabled(false);
00066     m_mainPanel->AddChild(m_photoButton);
00067
00068     // Video button
00069     m_videoButton.reset(new Button(Windows::Foundation::Numerics::float3(0.14f, 0.07f, 0.01f),          // Size
00070                                    Windows::Foundation::Numerics::float4(1.0f, 1.0f, 0.5f, 1.0f),       // Color
00071                                    Windows::Foundation::Numerics::float4(1.0f, 1.0f, 0.9f, 1.0f),       // Focused Color
00072                                    Windows::Foundation::Numerics::float4(0.0f, 0.0f, 0.5f, 1.0f),       // Turned on Color
00073                                    DX::Texture_Video));
00074     m_videoButton->Initialize(m_deviceResources);
00075     m_videoButton->SetPosition(Windows::Foundation::Numerics::float3(0.0f, 0.05f, 0.01f));
00076     m_videoButton->SetOnAirTapCallback(std::bind(&HolographicMRCSampleMain::OnButtonVideoTapped, this));
00077     m_videoButton->SetEnabled(false);
00078     m_mainPanel->AddChild(m_videoButton);
00079
00080     // Hologram button
00081     m_hologramButton.reset(new Button(Windows::Foundation::Numerics::float3(0.14f, 0.07f, 0.01f),       // Size
00082                                       Windows::Foundation::Numerics::float4(1.0f, 1.0f, 0.5f, 1.0f),    // Color
00083                                       Windows::Foundation::Numerics::float4(1.0f, 1.0f, 0.9f, 1.0f),    // Focused Color
00084                                       Windows::Foundation::Numerics::float4(0.0f, 0.0f, 0.5f, 1.0f),    // Turned on Color
00085                                       DX::Texture_Hologram));
00086     m_hologramButton->Initialize(m_deviceResources);
00087     m_hologramButton->SetPosition(Windows::Foundation::Numerics::float3(0.0f, -0.05f, 0.01f));
00088     m_hologramButton->SetOnAirTapCallback(std::bind(&HolographicMRCSampleMain::OnButtonHologramTapped, this));
00089     m_hologramButton->SetEnabled(true);
00090     m_mainPanel->AddChild(m_hologramButton);
00091
00092     // System Audio button
00093     m_sysAudioButton.reset(new Button(Windows::Foundation::Numerics::float3(0.14f, 0.07f, 0.01f),       // Size
00094                                       Windows::Foundation::Numerics::float4(1.0f, 1.0f, 0.5f, 1.0f),    // Color
00095                                       Windows::Foundation::Numerics::float4(1.0f, 1.0f, 0.9f, 1.0f),    // Focused Color
00096                                       Windows::Foundation::Numerics::float4(0.0f, 0.0f, 0.5f, 1.0f),    // Turned on Color
00097                                       DX::Texture_SysAudio));
00098     m_sysAudioButton->Initialize(m_deviceResources);
00099     m_sysAudioButton->SetPosition(Windows::Foundation::Numerics::float3(0.0f, -0.15f, 0.01f));
00100     m_sysAudioButton->SetOnAirTapCallback(std::bind(&HolographicMRCSampleMain::OnButtonSysAudioTapped, this));
00101     m_sysAudioButton->SetEnabled(true);
00102     m_mainPanel->AddChild(m_sysAudioButton);
00103
00104     // Spinning Cubes
00105     m_cube1 = std::make_unique<SpinningCubeRenderer>(m_deviceResources);
00106     m_cube1->SetPosition(Windows::Foundation::Numerics::float3(0.0f, 0.0f, -2.0f)); // Front
00107
00108     m_cube2 = std::make_unique<SpinningCubeRenderer>(m_deviceResources);
00109     m_cube2->SetPosition(Windows::Foundation::Numerics::float3(0.0f, 0.0f, 2.0f)); // Back
00110
00111     m_cube3 = std::make_unique<SpinningCubeRenderer>(m_deviceResources);
00112     m_cube3->SetPosition(Windows::Foundation::Numerics::float3(2.0f, 0.0f, 0.0f)); // Right
00113
00114     m_cube4 = std::make_unique<SpinningCubeRenderer>(m_deviceResources);
00115     m_cube4->SetPosition(Windows::Foundation::Numerics::float3(-2.0f, 0.0f, 0.0f)); // Left
00116
00117     // Spatial Input Handler
00118     m_spatialInputHandler = std::make_unique<SpatialInputHandler>();
00119
00120     // Media Capture Manager
00121     m_mediaCapture = std::make_unique<MediaCaptureManager>();
00122 #endif
00123
00124     // Use the default SpatialLocator to track the motion of the device.
00125     m_locator = SpatialLocator::GetDefault();
00126
00127     // Be able to respond to changes in the positional tracking state.
00128     m_locatabilityChangedToken =
00129         m_locator->LocatabilityChanged +=
00130             ref new Windows::Foundation::TypedEventHandler<SpatialLocator^, Object^>(
00131                 std::bind(&HolographicMRCSampleMain::OnLocatabilityChanged, this, _1, _2)
00132                 );
00133
00134     // Respond to camera added events by creating any resources that are specific
00135     // to that camera, such as the back buffer render target view.
00136     // When we add an event handler for CameraAdded, the API layer will avoid putting
00137     // the new camera in new HolographicFrames until we complete the deferral we created
00138     // for that handler, or return from the handler without creating a deferral. This
00139     // allows the app to take more than one frame to finish creating resources and
00140     // loading assets for the new holographic camera.
00141     // This function should be registered before the app creates any HolographicFrames.
00142     m_cameraAddedToken =
00143         m_holographicSpace->CameraAdded +=
00144             ref new Windows::Foundation::TypedEventHandler<HolographicSpace^, HolographicSpaceCameraAddedEventArgs^>(
00145                 std::bind(&HolographicMRCSampleMain::OnCameraAdded, this, _1, _2)
00146                 );
00147
00148     // Respond to camera removed events by releasing resources that were created for that
00149     // camera.
00150     // When the app receives a CameraRemoved event, it releases all references to the back
00151     // buffer right away. This includes render target views, Direct2D target bitmaps, and so on.
00152     // The app must also ensure that the back buffer is not attached as a render target, as
00153     // shown in DeviceResources::ReleaseResourcesForBackBuffer.
00154     m_cameraRemovedToken =
00155         m_holographicSpace->CameraRemoved +=
00156             ref new Windows::Foundation::TypedEventHandler<HolographicSpace^, HolographicSpaceCameraRemovedEventArgs^>(
00157                 std::bind(&HolographicMRCSampleMain::OnCameraRemoved, this, _1, _2)
00158                 );
00159
00160     // The simplest way to render world-locked holograms is to create a stationary reference frame
00161     // when the app is launched. This is roughly analogous to creating a "world" coordinate system
00162     // with the origin placed at the device's position as the app is launched.
00163     m_referenceFrame = m_locator->CreateStationaryFrameOfReferenceAtCurrentLocation();
00164
00165     // Notes on spatial tracking APIs:
00166     // * Stationary reference frames are designed to provide a best-fit position relative to the
00167     //   overall space. Individual positions within that reference frame are allowed to drift slightly
00168     //   as the device learns more about the environment.
00169     // * When precise placement of individual holograms is required, a SpatialAnchor should be used to
00170     //   anchor the individual hologram to a position in the real world - for example, a point the user
00171     //   indicates to be of special interest. Anchor positions do not drift, but can be corrected; the
00172     //   anchor will use the corrected position starting in the next frame after the correction has
00173     //   occurred.
00174 }
00175
00176 void HolographicMRCSampleMain::UnregisterHolographicEventHandlers()
00177 {
00178     if (m_holographicSpace != nullptr)
00179     {
00180         // Clear previous event registrations.
00181
00182         if (m_cameraAddedToken.Value != 0)
00183         {
00184             m_holographicSpace->CameraAdded -= m_cameraAddedToken;
00185             m_cameraAddedToken.Value = 0;
00186         }
00187
00188         if (m_cameraRemovedToken.Value != 0)
00189         {
00190             m_holographicSpace->CameraRemoved -= m_cameraRemovedToken;
00191             m_cameraRemovedToken.Value = 0;
00192         }
00193     }
00194
00195     if (m_locator != nullptr)
00196     {
00197         m_locator->LocatabilityChanged -= m_locatabilityChangedToken;
00198     }
00199 }
00200
00201 HolographicMRCSampleMain::~HolographicMRCSampleMain()
00202 {
00203     // Deregister device notification.
00204     m_deviceResources->RegisterDeviceNotify(nullptr);
00205
00206     UnregisterHolographicEventHandlers();
00207 }
00208
00209 // Updates the application state once per frame.
00210 HolographicFrame^ HolographicMRCSampleMain::Update()
00211 {
00212     if (m_holographicSpace)
00213     {
00214         // Before doing the timer update, there is some work to do per-frame
00215         // to maintain holographic rendering. First, we will get information
00216         // about the current frame.
00217
00218         // The HolographicFrame has information that the app needs in order
00219         // to update and render the current frame. The app begins each new
00220         // frame by calling CreateNextFrame.
00221         HolographicFrame^ holographicFrame = m_holographicSpace->CreateNextFrame();
00222
00223         // Get a prediction of where holographic cameras will be when this frame
00224         // is presented.
00225         HolographicFramePrediction^ prediction = holographicFrame->CurrentPrediction;
00226
00227         // Back buffers can change from frame to frame. Validate each buffer, and recreate
00228         // resource views and depth buffers as needed.
00229         m_deviceResources->EnsureCameraResources(holographicFrame, prediction);
00230
00231         // Next, we get a coordinate system from the attached frame of reference that is
00232         // associated with the current frame. Later, this coordinate system is used for
00233         // for creating the stereo view matrices when rendering the sample content.
00234         SpatialCoordinateSystem^ currentCoordinateSystem = m_referenceFrame->CoordinateSystem;
00235
00236 #ifdef DRAW_SAMPLE_CONTENT
00237         // Check for new input state since the last frame.
00238         SpatialInteractionSourceState^ pointerState = m_spatialInputHandler->CheckForInput();
00239 #endif
00240
00241         m_timer.Tick([&]()
00242         {
00243             //
00244             // Update scene objects.
00245             //
00246             // Put time-based updates here. By default this code will run once per frame,
00247             // but if you change the StepTimer to use a fixed time step this code will
00248             // run as many times as needed to get to the current step.
00249             //
00250
00251 #ifdef DRAW_SAMPLE_CONTENT
00252             m_cube1->Update(m_timer);
00253             m_cube2->Update(m_timer);
00254             m_cube3->Update(m_timer);
00255             m_cube4->Update(m_timer);
00256             m_mainPanel->Update(m_timer, holographicFrame, currentCoordinateSystem, pointerState);
00257
00258             DirectX::BoundingOrientedBox panelBoundingBox;
00259             m_mainPanel->GetBoundingBox(panelBoundingBox);
00260
00261             auto pointerPose = SpatialPointerPose::TryGetAtTimestamp(currentCoordinateSystem, prediction->Timestamp);
00262             if (pointerPose != nullptr)
00263             {
00264                 // Get the gaze direction relative to the given coordinate system.
00265                 const float3 position = pointerPose->Head->Position;
00266                 const float3 direction = pointerPose->Head->ForwardDirection;
00267
00268                 DirectX::XMFLOAT3 headPosition = DirectX::XMFLOAT3(position.x, position.y, position.z);
00269                 DirectX::XMFLOAT3 headDirection = DirectX::XMFLOAT3(direction.x, direction.y, direction.z);
00270                 float distance = 0.0f;
00271
00272                 if (panelBoundingBox.Intersects(XMLoadFloat3(&headPosition), XMLoadFloat3(&headDirection), distance))
00273                 {
00274                     m_cursor->SetDistance(distance - 0.05f);
00275                 }
00276                 else
00277                 {
00278                     m_cursor->SetDistance(2.0f);
00279                 }
00280             }
00281             else
00282             {
00283                 m_cursor->SetDistance(2.0f);
00284             }
00285
00286             m_cursor->Update(m_timer, holographicFrame, currentCoordinateSystem, nullptr);
00287 #endif
00288         });
00289
00290         // We complete the frame update by using information about our content positioning
00291         // to set the focus point.
00292
00293         for (auto cameraPose : prediction->CameraPoses)
00294         {
00295 #ifdef DRAW_SAMPLE_CONTENT
00296             // The HolographicCameraRenderingParameters class provides access to set
00297             // the image stabilization parameters.
00298             HolographicCameraRenderingParameters^ renderingParameters = holographicFrame->GetRenderingParameters(cameraPose);
00299
00300             // SetFocusPoint informs the system about a specific point in your scene to
00301             // prioritize for image stabilization. The focus point is set independently
00302             // for each holographic camera.
00303             // You should set the focus point near the content that the user is looking at.
00304             // In this example, we put the focus point at the center of the sample hologram,
00305             // since that is the only hologram available for the user to focus on.
00306             // You can also set the relative velocity and facing of that content; the sample
00307             // hologram is at a fixed point so we only need to indicate its position.
00308             renderingParameters->SetFocusPoint(
00309                 currentCoordinateSystem,
00310                 m_mainPanel->GetPosition()
00311             );
00312 #endif
00313         }
00314
00315         // The holographic frame will be used to get up-to-date view and projection matrices and
00316         // to present the swap chain.
00317         return holographicFrame;
00318     }
00319
00320     return nullptr;
00321 }
00322
00323 // Renders the current frame to each holographic camera, according to the
00324 // current application and spatial positioning state. Returns true if the
00325 // frame was rendered to at least one camera.
00326 bool HolographicMRCSampleMain::Render(Windows::Graphics::Holographic::HolographicFrame^ holographicFrame)
00327 {
00328     // Don't try to render anything before the first Update.
00329     if (m_timer.GetFrameCount() == 0)
00330     {
00331         return false;
00332     }
00333
00334     //
00335     // Take care of any tasks that are not specific to an individual holographic
00336     // camera. This includes anything that doesn't need the final view or projection
00337     // matrix, such as lighting maps.
00338     //
00339
00340     // Lock the set of holographic camera resources, then draw to each camera
00341     // in this frame.
00342     return m_deviceResources->UseHolographicCameraResources<bool>(
00343         [this, holographicFrame](std::map<UINT32, std::unique_ptr<DX::CameraResources>>& cameraResourceMap)
00344     {
00345         // Up-to-date frame predictions enhance the effectiveness of image stablization and
00346         // allow more accurate positioning of holograms.
00347         holographicFrame->UpdateCurrentPrediction();
00348         HolographicFramePrediction^ prediction = holographicFrame->CurrentPrediction;
00349
00350         bool atLeastOneCameraRendered = false;
00351         for (auto cameraPose : prediction->CameraPoses)
00352         {
00353             // This represents the device-based resources for a HolographicCamera.
00354             DX::CameraResources* pCameraResources = cameraResourceMap[cameraPose->HolographicCamera->Id].get();
00355
00356             // Get the device context.
00357             const auto context = m_deviceResources->GetD3DDeviceContext();
00358             const auto depthStencilView = pCameraResources->GetDepthStencilView();
00359             const auto blendState = pCameraResources->GetBlendState();
00360
00361             // Set render targets to the current holographic camera.
00362             ID3D11RenderTargetView *const targets[1] = { pCameraResources->GetBackBufferRenderTargetView() };
00363             context->OMSetRenderTargets(1, targets, depthStencilView);
00364
00365             // Set blend state
00366             context->OMSetBlendState(blendState, NULL, 0xffffffff);
00367
00368             // Clear the back buffer and depth stencil view.
00369             context->ClearRenderTargetView(targets[0], DirectX::Colors::Transparent);
00370             context->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
00371
00372             // The view and projection matrices for each holographic camera will change
00373             // every frame. This function refreshes the data in the constant buffer for
00374             // the holographic camera indicated by cameraPose.
00375             pCameraResources->UpdateViewProjectionBuffer(m_deviceResources, cameraPose, m_referenceFrame->CoordinateSystem);
00376
00377             // Attach the view/projection constant buffer for this camera to the graphics pipeline.
00378             bool cameraActive = pCameraResources->AttachViewProjectionBuffer(m_deviceResources);
00379
00380 #ifdef DRAW_SAMPLE_CONTENT
00381             // Only render world-locked content when positional tracking is active.
00382             if (cameraActive)
00383             {
00384                 m_cube1->Render();
00385                 m_cube2->Render();
00386                 m_cube3->Render();
00387                 m_cube4->Render();
00388                 m_mainPanel->Render();
00389                 m_cursor->Render();
00390             }
00391 #endif
00392             atLeastOneCameraRendered = true;
00393         }
00394
00395         return atLeastOneCameraRendered;
00396     });
00397 }
00398
00399 void HolographicMRCSampleMain::SaveAppState()
00400 {
00401 }
00402
00403 void HolographicMRCSampleMain::LoadAppState()
00404 {
00405 }
00406
00407 // Notifies classes that use Direct3D device resources that the device resources
00408 // need to be released before this method returns.
00409 void HolographicMRCSampleMain::OnDeviceLost()
00410 {
00411 #ifdef DRAW_SAMPLE_CONTENT
00412     m_cube1->ReleaseDeviceDependentResources();
00413     m_cube2->ReleaseDeviceDependentResources();
00414     m_cube3->ReleaseDeviceDependentResources();
00415     m_cube4->ReleaseDeviceDependentResources();
00416
00417     m_cursor->ReleaseDeviceDependentResources();
00418     m_mainPanel->ReleaseDeviceDependentResources();
00419 #endif
00420 }
00421
00422 // Notifies classes that use Direct3D device resources that the device resources
00423 // may now be recreated.
00424 void HolographicMRCSampleMain::OnDeviceRestored()
00425 {
00426 #ifdef DRAW_SAMPLE_CONTENT
00427     m_cube1->CreateDeviceDependentResources();
00428     m_cube2->CreateDeviceDependentResources();
00429     m_cube3->CreateDeviceDependentResources();
00430     m_cube4->CreateDeviceDependentResources();
00431
00432     m_cursor->CreateDeviceDependentResources();
00433     m_mainPanel->CreateDeviceDependentResources();
00434 #endif
00435 }
00436
00437 void HolographicMRCSampleMain::OnLocatabilityChanged(SpatialLocator^ sender, Object^ args)
00438 {
00439     switch (sender->Locatability)
00440     {
00441     case SpatialLocatability::Unavailable:
00442         // Holograms cannot be rendered.
00443         {
00444             String^ message = L"Warning! Positional tracking is " +
00445                                         sender->Locatability.ToString() + L".\n";
00446             OutputDebugStringW(message->Data());
00447         }
00448         break;
00449
00450     // In the following three cases, it is still possible to place holograms using a
00451     // SpatialLocatorAttachedFrameOfReference.
00452     case SpatialLocatability::PositionalTrackingActivating:
00453         // The system is preparing to use positional tracking.
00454
00455     case SpatialLocatability::OrientationOnly:
00456         // Positional tracking has not been activated.
00457
00458     case SpatialLocatability::PositionalTrackingInhibited:
00459         // Positional tracking is temporarily inhibited. User action may be required
00460         // in order to restore positional tracking.
00461         break;
00462
00463     case SpatialLocatability::PositionalTrackingActive:
00464         // Positional tracking is active. World-locked content can be rendered.
00465         break;
00466     }
00467 }
00468
00469 void HolographicMRCSampleMain::OnCameraAdded(
00470     HolographicSpace^ sender,
00471     HolographicSpaceCameraAddedEventArgs^ args
00472     )
00473 {
00474     Deferral^ deferral = args->GetDeferral();
00475     HolographicCamera^ holographicCamera = args->Camera;
00476     create_task([this, deferral, holographicCamera] ()
00477     {
00478         // Create device-based resources for the holographic camera and add it to the list of
00479         // cameras used for updates and rendering. Notes:
00480         //   * Since this function may be called at any time, the AddHolographicCamera function
00481         //     waits until it can get a lock on the set of holographic camera resources before
00482         //     adding the new camera. At 60 frames per second this wait should not take long.
00483         //   * A subsequent Update will take the back buffer from the RenderingParameters of this
00484         //     camera's CameraPose and use it to create the ID3D11RenderTargetView for this camera.
00485         //     Content can then be rendered for the HolographicCamera.
00486         m_deviceResources->AddHolographicCamera(holographicCamera);
00487
00488         // Holographic frame predictions will not include any information about this camera until
00489         // the deferral is completed.
00490         deferral->Complete();
00491     });
00492 }
00493
00494 void HolographicMRCSampleMain::OnCameraRemoved(
00495     HolographicSpace^ sender,
00496     HolographicSpaceCameraRemovedEventArgs^ args
00497     )
00498 {
00499     create_task([this]()
00500     {
00501     });
00502
00503     // Before letting this callback return, ensure that all references to the back buffer
00504     // are released.
00505     // Since this function may be called at any time, the RemoveHolographicCamera function
00506     // waits until it can get a lock on the set of holographic camera resources before
00507     // deallocating resources for this camera. At 60 frames per second this wait should
00508     // not take long.
00509     m_deviceResources->RemoveHolographicCamera(args->Camera);
00510 }
00511
00512 void HolographicMRCSampleMain::OnButtonInitTapped()
00513 {
00514     DisableAllButtons();
00515
00516     try
00517     {
00518         Concurrency::create_task(m_mediaCapture->InitializeAsync()).then([this]()
00519         {
00520             m_photoButton->SetEnabled(m_mediaCapture->CanTakePhoto());
00521             m_videoButton->SetEnabled(m_mediaCapture->CanToggleVideo());
00522             m_hologramButton->SetEnabled(true);
00523             m_sysAudioButton->SetEnabled(true);
00524         });
00525     }
00526     catch (Platform::Exception ^e)
00527     {
00528         OutputDebugString(e->Message->Data());
00529     }
00530 }
00531
00532 void HolographicMRCSampleMain::OnButtonVideoTapped()
00533 {
00534     DisableAllButtons();
00535
00536     if (m_recording)
00537     {
00538         try
00539         {
00540             // Stop Recording
00541             m_mediaCapture->StopRecordingAsync().then([this]()
00542             {
00543                 m_recording = false;
00544
00545                 m_initButton->SetEnabled(false);
00546                 m_photoButton->SetEnabled(m_mediaCapture->CanTakePhoto());
00547                 m_videoButton->SetEnabled(m_mediaCapture->CanToggleVideo());
00548                 m_hologramButton->SetEnabled(true);
00549                 m_sysAudioButton->SetEnabled(true);
00550             });
00551         }
00552         catch (Platform::Exception ^e)
00553         {
00554             OutputDebugString(e->Message->Data());
00555         }
00556     }
00557     else
00558     {
00559         try
00560         {
00561             // Start Recording
00562             m_mediaCapture->StartRecordingAsync().then([this]()
00563             {
00564                 m_recording = true;
00565
00566                 m_initButton->SetEnabled(false);
00567                 m_photoButton->SetEnabled(m_mediaCapture->CanTakePhoto());
00568                 m_videoButton->SetEnabled(m_mediaCapture->CanToggleVideo());
00569                 m_hologramButton->SetEnabled(false);
00570                 m_sysAudioButton->SetEnabled(false);
00571             });
00572         }
00573         catch (Platform::Exception ^e)
00574         {
00575             OutputDebugString(e->Message->Data());
00576         }
00577     }
00578 }
00579
00580 void HolographicMRCSampleMain::OnButtonPhotoTapped()
00581 {
00582     DisableAllButtons();
00583
00584     try
00585     {
00586         m_mediaCapture->TakePhotoAsync().then([this]()
00587         {
00588             m_initButton->SetEnabled(false);
00589             m_photoButton->SetEnabled(m_mediaCapture->CanTakePhoto());
00590             m_videoButton->SetEnabled(m_mediaCapture->CanToggleVideo());
00591             m_hologramButton->SetEnabled(true);
00592             m_sysAudioButton->SetEnabled(true);
00593         });
00594     }
00595     catch (Platform::Exception ^e)
00596     {
00597         OutputDebugString(e->Message->Data());
00598     }
00599 }
00600
00601 void HolographicMRCSampleMain::OnButtonHologramTapped()
00602 {
00603     // Toggle button switch state
00604     m_hologramButton->SetSwitch(!m_hologramButton->GetSwitch());
00605
00606     m_mediaCapture->SetHologramEnabled(m_hologramButton->GetSwitch());
00607 }
00608
00609 void HolographicMRCSampleMain::OnButtonSysAudioTapped()
00610 {
00611     // Toggle button switch state
00612     m_sysAudioButton->SetSwitch(!m_sysAudioButton->GetSwitch());
00613
00614     m_mediaCapture->SetSystemAudioEnabled(m_sysAudioButton->GetSwitch());
00615 }
00616
00617 void HolographicMRCSampleMain::DisableAllButtons()
00618 {
00619     m_initButton->SetEnabled(false);
00620     m_photoButton->SetEnabled(false);
00621     m_videoButton->SetEnabled(false);
00622     m_hologramButton->SetEnabled(false);
00623     m_sysAudioButton->SetEnabled(false);
00624 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

TypeToUIElementConverter Member List

This is the complete list of members for TypeToUIElementConverter, including all inherited members.
Convert(object value, Type targetType, object parameter, string language) | TypeToUIElementConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | TypeToUIElementConverter | [inline]
Generated on Fri Nov 15 2024 22:23:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cppwinrt/SampleConfiguration.h Source File

  • WiFiDirect
  • cppwinrt

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace winrt::SDKTemplate
00016 {
00017     // Helper function to take the selected item
00018     // and return its tag, which is assumed to be of type T.
00019     template<typename T, typename Control>
00020     T GetSelectedItemTag(Control&& control)
00021     {
00022         return unbox_value<T>(control.SelectedItem().as<Windows::UI::Xaml::FrameworkElement>().Tag());
00023     }
00024
00025     // Helper function to remove an item from a collection by value
00026     // rather than by index.
00027     template<typename T, typename V>
00028     bool RemoveByValue(T&& collection, V&& value)
00029     {
00030         uint32_t index;
00031         bool found = collection.IndexOf(std::forward<V>(value), index);
00032         if (found)
00033         {
00034             collection.RemoveAt(index);
00035         }
00036         return found;
00037     }
00038
00039
00040     fire_and_forget HandlePairing(Windows::UI::Core::CoreDispatcher dispatcher, Windows::Devices::Enumeration::DevicePairingRequestedEventArgs e);
00041
00042     static constexpr std::array<uint8_t, 3> CustomOui{ 0xAA, 0xBB, 0xCC };
00043     static constexpr uint8_t CustomOuiType{ 0xDD };
00044     static constexpr std::array<uint8_t, 3> WfaOui{ 0x50, 0x6F, 0x9A };
00045     static constexpr std::array<uint8_t, 3> MsftOui{ 0x00, 0x50, 0xF2 };
00046     static constexpr wchar_t ServerPortString[] = L"50001";
00047 }
00048
00049 namespace winrt
00050 {
00051     hstring to_hstring(Windows::Devices::Enumeration::DevicePairingResultStatus);
00052     hstring to_hstring(Windows::Devices::Enumeration::DeviceUnpairingResultStatus);
00053     hstring to_hstring(Windows::Devices::WiFiDirect::WiFiDirectAdvertisementPublisherStatus);
00054     hstring to_hstring(Windows::Devices::WiFiDirect::WiFiDirectConfigurationMethod);
00055     hstring to_hstring(Windows::Devices::WiFiDirect::WiFiDirectConnectionStatus);
00056     hstring to_hstring(Windows::Devices::WiFiDirect::WiFiDirectError);
00057 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/Scenario4_EdgeTappedListView.cpp Source File

  • XamlListView
  • cppwinrt

Scenario4_EdgeTappedListView.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Contact.h"
00014 #include "Scenario4_EdgeTappedListView.h"
00015 #include "Scenario4_EdgeTappedListView.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace winrt::Windows::Foundation;
00019 using namespace winrt::Windows::UI::Core;
00020 using namespace winrt::Windows::UI::Xaml;
00021 using namespace winrt::Windows::UI::Xaml::Controls;
00022 using namespace winrt::Windows::UI::Xaml::Navigation;
00023
00024 namespace winrt::SDKTemplate::implementation
00025 {
00026     Scenario4_EdgeTappedListView::Scenario4_EdgeTappedListView()
00027     {
00028         InitializeComponent();
00029
00030         Contacts = Contact::GetContacts(50);
00031         MyListView().ItemsSource(Contacts);
00032
00033         // We set the state of the commands on the appbar
00034         SetCommandsVisibility(MyListView());
00035     }
00036
00037     void Scenario4_EdgeTappedListView::OnNavigatedTo(NavigationEventArgs const&)
00038     {
00039         // This is how devs can handle the back button
00040         backRequestedToken = SystemNavigationManager::GetForCurrentView().BackRequested({ get_weak(), &Scenario4_EdgeTappedListView::OnBackRequested });
00041     }
00042
00043     void Scenario4_EdgeTappedListView::OnNavigatedFrom(NavigationEventArgs const&)
00044     {
00045         SystemNavigationManager::GetForCurrentView().BackRequested(backRequestedToken);
00046     }
00047
00048     void Scenario4_EdgeTappedListView::OnEdgeTapped(SDKTemplate::EdgeTappedListView const&, SDKTemplate::ListViewEdgeTappedEventArgs const&)
00049     {
00050         // When user releases the pointer after pressing on the left edge of the item,
00051         // the ListView will switch to Multiple Selection
00052         MyListView().SelectionMode(ListViewSelectionMode::Multiple);
00053         // Also, we want the Left Edge Tap funcionality will be no longer enable.
00054         MyListView().IsItemLeftEdgeTapEnabled(false);
00055         // It's desirable that the Appbar shows the actions available for multiselect
00056         SetCommandsVisibility(MyListView());
00057     }
00058
00059     void Scenario4_EdgeTappedListView::UpdateSelectionUI()
00060     {
00061         // When there are no selected items, the list returns to None selection mode.
00062         if (MyListView().SelectedItems().Size() == 0)
00063         {
00064             MyListView().SelectionMode(ListViewSelectionMode::None);
00065             MyListView().IsItemLeftEdgeTapEnabled(true);
00066             SetCommandsVisibility(MyListView());
00067         }
00068     }
00069
00070     void Scenario4_EdgeTappedListView::OnSelectionChanged(IInspectable const&, SelectionChangedEventArgs const&)
00071     {
00072         UpdateSelectionUI();
00073     }
00074
00075     void Scenario4_EdgeTappedListView::OnBackRequested(IInspectable const&, BackRequestedEventArgs const& e)
00076     {
00077         // We want to exit from the multiselect mode when pressing back button
00078         if (!e.Handled() && MyListView().SelectionMode() == ListViewSelectionMode::Multiple)
00079         {
00080             MyListView().SelectedItems().Clear();
00081             UpdateSelectionUI();
00082             e.Handled(true);
00083         }
00084     }
00085
00086     void Scenario4_EdgeTappedListView::SetCommandsVisibility(ListView const& listView)
00087     {
00088         if (listView.SelectionMode() == ListViewSelectionMode::Multiple || listView.SelectedItems().Size() > 1)
00089         {
00090             SelectAppBarBtn().Visibility(Visibility::Collapsed);
00091             CancelSelectionAppBarBtn().Visibility(Visibility::Visible);
00092             AddItemAppBarBtn().Visibility(Visibility::Collapsed);
00093             RemoveItemAppBarBtn().Visibility(Visibility::Visible);
00094             SystemNavigationManager::GetForCurrentView().AppViewBackButtonVisibility(AppViewBackButtonVisibility::Visible);
00095         }
00096         else
00097         {
00098             SelectAppBarBtn().Visibility(Visibility::Visible);
00099             CancelSelectionAppBarBtn().Visibility(Visibility::Collapsed);
00100             AddItemAppBarBtn().Visibility(Visibility::Visible);
00101             RemoveItemAppBarBtn().Visibility(Visibility::Collapsed);
00102             SystemNavigationManager::GetForCurrentView().AppViewBackButtonVisibility(AppViewBackButtonVisibility::Collapsed);
00103         }
00104     }
00105
00106     void Scenario4_EdgeTappedListView::SelectItems(IInspectable const&, RoutedEventArgs const&)
00107     {
00108         MyListView().SelectionMode(ListViewSelectionMode::Multiple);
00109         MyListView().IsItemLeftEdgeTapEnabled(false);
00110         SetCommandsVisibility(MyListView());
00111     }
00112
00113     void Scenario4_EdgeTappedListView::AddItem(IInspectable const&, RoutedEventArgs const&)
00114     {
00115         Contacts.Append(Contact::GetNewContact());
00116     }
00117
00118     void Scenario4_EdgeTappedListView::RemoveItem(IInspectable const&, RoutedEventArgs const&)
00119     {
00120         int32_t index;
00121         while ((index = MyListView().SelectedIndex()) != -1)
00122         {
00123             Contacts.RemoveAt(index);
00124         }
00125     }
00126
00127     void Scenario4_EdgeTappedListView::CancelSelection(IInspectable const&, RoutedEventArgs const&)
00128     {
00129         // If the list is multiple selection mode but there is no items selected,
00130         // then the list should return to the initial selection mode.
00131         if (MyListView().SelectedItems().Size() == 0)
00132         {
00133             MyListView().SelectionMode(ListViewSelectionMode::None);
00134             MyListView().IsItemLeftEdgeTapEnabled(true);
00135             SetCommandsVisibility(MyListView());
00136         }
00137         else
00138         {
00139             MyListView().SelectedItems().Clear();
00140         }
00141     }
00142
00143 }
Generated on Fri Nov 15 2024 22:22:32 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileSearch/cppwinrt/pch.cpp Source File

  • FileSearch
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IsApiPropertyPresentTrigger Member List

This is the complete list of members for IsApiPropertyPresentTrigger, including all inherited members.
_isPresent | IsApiPropertyPresentTrigger | [private]
_isPropertyPresent | IsApiPropertyPresentTrigger | [private]
_propertyName | IsApiPropertyPresentTrigger | [private]
_typeName | IsApiPropertyPresentTrigger | [private]
IsPresent | IsApiPropertyPresentTrigger |
PropertyName | IsApiPropertyPresentTrigger |
propertyPresence | IsApiPropertyPresentTrigger | [private, static]
TypeName | IsApiPropertyPresentTrigger |
UpdatePresence() | IsApiPropertyPresentTrigger | [inline, private]
UpdateState() | IsApiPropertyPresentTrigger | [inline, private]
Generated on Fri Nov 15 2024 22:23:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

OsrFx2 Member List

This is the complete list of members for OsrFx2, including all inherited members.
DevicePid | OsrFx2 |
DeviceVid | OsrFx2 |
SevenLedSegmentMask | OsrFx2 | [static]
Generated on Fri Nov 15 2024 22:23:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cpp/DisplayHelpers.cpp Source File

  • DeviceEnumerationAndPairing
  • cpp

DisplayHelpers.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include <ppltasks.h>
00006 #include <DisplayHelpers.h>
00007
00008 using namespace SDKTemplate;
00009 using namespace Platform;
00010 using namespace Platform::Collections;
00011 using namespace Windows::Foundation;
00012 using namespace Windows::Foundation::Collections;
00013 using namespace Windows::UI::Core;
00014 using namespace Windows::UI::Xaml::Data;
00015 using namespace Windows::UI::Xaml::Interop;
00016 using namespace Windows::UI::Xaml::Media::Imaging;
00017 using namespace Windows::Devices::Enumeration;
00018
00019 // NOTE: The following using statements are only needed in order to demonstrate many of the
00020 // different device selectors available from Windows Runtime APIs. You will only need to include
00021 // the namespace for the Windows Runtime API your actual scenario needs.
00022 using namespace Windows::Devices::HumanInterfaceDevice;
00023 using namespace Windows::Networking::Proximity;
00024 using namespace Windows::Devices::Bluetooth;
00025 using namespace Windows::Devices::WiFiDirect;
00026 using namespace Windows::Media::Casting;
00027 using namespace Windows::Media::DialProtocol;
00028 using namespace Windows::Devices::Sensors;
00029 using namespace Windows::Devices::PointOfService;
00030
00031 namespace SDKTemplate
00032 {
00033     // DeviceSelectorChoices
00034
00035     Windows::Foundation::Collections::IVectorView<DeviceSelectorInfo^>^ DeviceSelectorChoices::CommonDeviceSelectors::get()
00036     {
00037         Vector<DeviceSelectorInfo^>^ selectors = ref new Vector<DeviceSelectorInfo^>();
00038
00039         // Pre-canned device class selectors
00040         selectors->Append(ref new DeviceSelectorInfo("All Device Interfaces (default)", DeviceClass::All, nullptr));
00041         selectors->Append(ref new DeviceSelectorInfo("Audio Capture", DeviceClass::AudioCapture, nullptr));
00042         selectors->Append(ref new DeviceSelectorInfo("Audio Render", DeviceClass::AudioRender, nullptr));
00043         selectors->Append(ref new DeviceSelectorInfo("Image Scanner", DeviceClass::ImageScanner, nullptr));
00044         selectors->Append(ref new DeviceSelectorInfo("Location", DeviceClass::Location, nullptr));
00045         selectors->Append(ref new DeviceSelectorInfo("Portable Storage", DeviceClass::PortableStorageDevice, nullptr));
00046         selectors->Append(ref new DeviceSelectorInfo("Video Capture", DeviceClass::VideoCapture, nullptr));
00047
00048         // A few examples of selectors built dynamically by windows runtime apis.
00049         selectors->Append(ref new DeviceSelectorInfo("Human Interface (HID)", DeviceClass::All, HidDevice::GetDeviceSelector(0, 0)));
00050         selectors->Append(ref new DeviceSelectorInfo("Activity Sensor", DeviceClass::All, ActivitySensor::GetDeviceSelector()));
00051         selectors->Append(ref new DeviceSelectorInfo("Pedometer", DeviceClass::All, Pedometer::GetDeviceSelector()));
00052         selectors->Append(ref new DeviceSelectorInfo("Proximity", DeviceClass::All, ProximityDevice::GetDeviceSelector()));
00053         selectors->Append(ref new DeviceSelectorInfo("Proximity Sensor", DeviceClass::All, ProximityDevice::GetDeviceSelector()));
00054
00055         return selectors->GetView();
00056     }
00057
00058     DeviceSelectorInfo^ DeviceSelectorChoices::Bluetooth::get()
00059     {
00060         // Currently Bluetooth APIs don't provide a selector to get ALL devices that are both paired and non-paired.  Typically you wouldn't need this for common scenarios, but it's convenient to demonstrate the
00061         // various sample scenarios.
00062         return ref new DeviceSelectorInfo("Bluetooth", DeviceClass::All, "System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\"", DeviceInformationKind::AssociationEndpoint);
00063     }
00064
00065     DeviceSelectorInfo^ DeviceSelectorChoices::BluetoothUnpairedOnly::get()
00066     {
00067         return ref new DeviceSelectorInfo("Bluetooth (unpaired)", DeviceClass::All, BluetoothDevice::GetDeviceSelectorFromPairingState(false));
00068     }
00069
00070     DeviceSelectorInfo^ DeviceSelectorChoices::BluetoothPairedOnly::get()
00071     {
00072         return ref new DeviceSelectorInfo("Bluetooth (paired)", DeviceClass::All, BluetoothDevice::GetDeviceSelectorFromPairingState(true));
00073     }
00074
00075     DeviceSelectorInfo^ DeviceSelectorChoices::BluetoothLE::get()
00076     {
00077         // Currently Bluetooth APIs don't provide a selector to get ALL devices that are both paired and non-paired.  Typically you wouldn't need this for common scenarios, but it's convenient to demonstrate the
00078         // various sample scenarios.
00079         return ref new DeviceSelectorInfo("Bluetooth LE", DeviceClass::All, "System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\"", DeviceInformationKind::AssociationEndpoint);
00080     }
00081
00082     DeviceSelectorInfo^ DeviceSelectorChoices::BluetoothLEUnpairedOnly::get()
00083     {
00084         return ref new DeviceSelectorInfo("Bluetooth LE (unpaired)", DeviceClass::All, BluetoothLEDevice::GetDeviceSelectorFromPairingState(false));
00085     }
00086
00087     DeviceSelectorInfo^ DeviceSelectorChoices::BluetoothLEPairedOnly::get()
00088     {
00089         return ref new DeviceSelectorInfo("Bluetooth LE (paired)", DeviceClass::All, BluetoothLEDevice::GetDeviceSelectorFromPairingState(true));
00090     }
00091
00092     DeviceSelectorInfo^ DeviceSelectorChoices::WiFiDirect::get()
00093     {
00094         return ref new DeviceSelectorInfo("Wi-Fi Direct", DeviceClass::All, WiFiDirectDevice::GetDeviceSelector(WiFiDirectDeviceSelectorType::AssociationEndpoint));
00095     }
00096
00097     DeviceSelectorInfo^ DeviceSelectorChoices::WiFiDirectPairedOnly::get()
00098     {
00099         return ref new DeviceSelectorInfo("Wi-Fi Direct (paired)", DeviceClass::All, WiFiDirectDevice::GetDeviceSelector());
00100     }
00101
00102     DeviceSelectorInfo^ DeviceSelectorChoices::PointOfServicePrinter::get()
00103     {
00104         return ref new DeviceSelectorInfo("Point of Service Printer", DeviceClass::All, PosPrinter::GetDeviceSelector());
00105     }
00106
00107     DeviceSelectorInfo^ DeviceSelectorChoices::VideoCasting::get()
00108     {
00109         return ref new DeviceSelectorInfo("Video Casting", DeviceClass::All, CastingDevice::GetDeviceSelector(CastingPlaybackTypes::Video));
00110     }
00111
00112     DeviceSelectorInfo^ DeviceSelectorChoices::DialAllApps::get()
00113     {
00114         return ref new DeviceSelectorInfo("DIAL (All apps)", DeviceClass::All, DialDevice::GetDeviceSelector(""));
00115     }
00116
00117     // WSD and UPnP are unique in that there are currently no general WSD or UPnP APIs to USE the devices once you've discovered them.
00118     // You can pair the devices using DeviceInformation.Pairing.PairAsync etc, and you can USE them with the sockets APIs. However, since
00119     // there's no specific API right now, there's no *.GetDeviceSelector available.  That's why we just simply build the device selector
00120     // ourselves and specify the correct DeviceInformationKind (AssociationEndpoint).
00121     DeviceSelectorInfo^ DeviceSelectorChoices::Wsd::get()
00122     {
00123         return ref new DeviceSelectorInfo("Web Services on Devices (WSD)", DeviceClass::All, "System.Devices.Aep.ProtocolId:=\"{782232aa-a2f9-4993-971b-aedc551346b0}\"", DeviceInformationKind::AssociationEndpoint);
00124     }
00125
00126     DeviceSelectorInfo^ DeviceSelectorChoices::Upnp::get()
00127     {
00128         return ref new DeviceSelectorInfo("UPnP", DeviceClass::All, "System.Devices.Aep.ProtocolId:=\"{0e261de4-12f0-46e6-91ba-428607ccef64}\"", DeviceInformationKind::AssociationEndpoint);
00129     }
00130
00131     DeviceSelectorInfo^ DeviceSelectorChoices::NetworkCamera::get()
00132     {
00133         return ref new DeviceSelectorInfo("Web Services on Devices (NetworkCamera)", DeviceClass::All, "System.Devices.Aep.ProtocolId:=\"{43cc0de4-8ca8-4a56-805a-86fc63f21602}\"", DeviceInformationKind::AssociationEndpoint);
00134     }
00135
00136     void AddVideoCastingIfSupported(Vector<DeviceSelectorInfo^>^ selectors)
00137     {
00138         try
00139         {
00140             selectors->Append(DeviceSelectorChoices::VideoCasting);
00141         }
00142         catch (Exception^ ex)
00143         {
00144             if (ex->HResult == HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED))
00145             {
00146                 // Video casting not supported by the system.
00147             }
00148             else
00149             {
00150                 throw;
00151             }
00152         }
00153     }
00154
00155     IVectorView<DeviceSelectorInfo^>^ DeviceSelectorChoices::DevicePickerSelectors::get()
00156     {
00157         auto commonDeviceSelectors = CommonDeviceSelectors;
00158         Vector<DeviceSelectorInfo^>^ selectors = ref new Vector<DeviceSelectorInfo^>(begin(commonDeviceSelectors), end(commonDeviceSelectors));
00159         selectors->Append(BluetoothPairedOnly);
00160         selectors->Append(BluetoothUnpairedOnly);
00161         selectors->Append(BluetoothLEPairedOnly);
00162         selectors->Append(BluetoothLEUnpairedOnly);
00163         selectors->Append(WiFiDirect);
00164         selectors->Append(PointOfServicePrinter);
00165         AddVideoCastingIfSupported(selectors);
00166         selectors->Append(DialAllApps);
00167
00168         return selectors->GetView();
00169     }
00170
00171     IVectorView<DeviceSelectorInfo^>^ DeviceSelectorChoices::FindAllAsyncSelectors::get()
00172     {
00173         auto commonDeviceSelectors = CommonDeviceSelectors;
00174         Vector<DeviceSelectorInfo^>^ selectors = ref new Vector<DeviceSelectorInfo^>(begin(commonDeviceSelectors), end(commonDeviceSelectors));
00175         selectors->Append(BluetoothPairedOnly);
00176         selectors->Append(BluetoothLEPairedOnly);
00177         selectors->Append(WiFiDirectPairedOnly);
00178
00179         return selectors->GetView();
00180     }
00181
00182     IVectorView<DeviceSelectorInfo^>^ DeviceSelectorChoices::DeviceWatcherSelectors::get()
00183     {
00184         auto commonDeviceSelectors = CommonDeviceSelectors;
00185         Vector<DeviceSelectorInfo^>^ selectors = ref new Vector<DeviceSelectorInfo^>(begin(commonDeviceSelectors), end(commonDeviceSelectors));
00186         selectors->Append(Bluetooth);
00187         selectors->Append(BluetoothLE);
00188         selectors->Append(WiFiDirect);
00189         selectors->Append(PointOfServicePrinter);
00190         AddVideoCastingIfSupported(selectors);
00191         selectors->Append(DialAllApps);
00192         selectors->Append(Wsd);
00193         selectors->Append(Upnp);
00194
00195         return selectors->GetView();
00196     }
00197
00198     IVectorView<DeviceSelectorInfo^>^ DeviceSelectorChoices::BackgroundDeviceWatcherSelectors::get()
00199     {
00200         auto commonDeviceSelectors = CommonDeviceSelectors;
00201         Vector<DeviceSelectorInfo^>^ selectors = ref new Vector<DeviceSelectorInfo^>(begin(commonDeviceSelectors), end(commonDeviceSelectors));
00202         selectors->Append(BluetoothPairedOnly);
00203         selectors->Append(BluetoothLEPairedOnly);
00204         selectors->Append(WiFiDirectPairedOnly);
00205         selectors->Append(PointOfServicePrinter);
00206         AddVideoCastingIfSupported(selectors);
00207         selectors->Append(DialAllApps);
00208         selectors->Append(Wsd);
00209         selectors->Append(Upnp);
00210
00211         return selectors->GetView();
00212     }
00213
00214     IVectorView<DeviceSelectorInfo^>^ DeviceSelectorChoices::PairingSelectors::get()
00215     {
00216         Vector<DeviceSelectorInfo^>^ selectors = ref new Vector<DeviceSelectorInfo^>();
00217         selectors->Append(Bluetooth);
00218         selectors->Append(BluetoothLE);
00219         selectors->Append(WiFiDirect);
00220         selectors->Append(PointOfServicePrinter);
00221         AddVideoCastingIfSupported(selectors);
00222         selectors->Append(Wsd);
00223         selectors->Append(Upnp);
00224         selectors->Append(NetworkCamera);
00225
00226         return selectors->GetView();
00227     }
00228
00229     // DeviceInformationKindChoices
00230
00231     IVectorView<DeviceInformationKindChoice^>^ DeviceInformationKindChoices::Choices::get()
00232     {
00233         Vector<DeviceInformationKindChoice^>^ choices = ref new Vector<DeviceInformationKindChoice^>();
00234
00235         Vector<DeviceInformationKind>^ kinds;
00236
00237         kinds = ref new Vector<DeviceInformationKind>();
00238         kinds->Append(DeviceInformationKind::DeviceContainer);
00239         choices->Append(ref new DeviceInformationKindChoice("DeviceContainer", kinds->GetView()));
00240
00241         kinds = ref new Vector<DeviceInformationKind>();
00242         kinds->Append(DeviceInformationKind::Device);
00243         choices->Append(ref new DeviceInformationKindChoice("Device", kinds->GetView()));
00244
00245         kinds = ref new Vector<DeviceInformationKind>();
00246         kinds->Append(DeviceInformationKind::DeviceInterface);
00247         choices->Append(ref new DeviceInformationKindChoice("DeviceInterface", kinds->GetView()));
00248
00249         kinds = ref new Vector<DeviceInformationKind>();
00250         kinds->Append(DeviceInformationKind::DeviceInterfaceClass);
00251         choices->Append(ref new DeviceInformationKindChoice("DeviceInterfaceClass", kinds->GetView()));
00252
00253         kinds = ref new Vector<DeviceInformationKind>();
00254         kinds->Append(DeviceInformationKind::AssociationEndpointContainer);
00255         choices->Append(ref new DeviceInformationKindChoice("AssociationEndpointContainer", kinds->GetView()));
00256
00257         kinds = ref new Vector<DeviceInformationKind>();
00258         kinds->Append(DeviceInformationKind::AssociationEndpoint);
00259         choices->Append(ref new DeviceInformationKindChoice("AssociationEndpoint", kinds->GetView()));
00260
00261         kinds = ref new Vector<DeviceInformationKind>();
00262         kinds->Append(DeviceInformationKind::AssociationEndpointService);
00263         choices->Append(ref new DeviceInformationKindChoice("AssociationEndpointService", kinds->GetView()));
00264
00265         kinds = ref new Vector<DeviceInformationKind>();
00266         kinds->Append(DeviceInformationKind::AssociationEndpointService);
00267         kinds->Append(DeviceInformationKind::DeviceInterface);
00268         choices->Append(ref new DeviceInformationKindChoice("AssociationEndpointService and DeviceInterface", kinds->GetView()));
00269
00270         return choices->GetView();
00271     }
00272
00273     IVectorView<ProtectionLevelSelectorInfo^>^ ProtectionSelectorChoices::Selectors::get()
00274     {
00275         Vector<ProtectionLevelSelectorInfo^>^ selectors = ref new Vector<ProtectionLevelSelectorInfo^>();
00276
00277         selectors->Append(ref new ProtectionLevelSelectorInfo("Default", Windows::Devices::Enumeration::DevicePairingProtectionLevel::Default ));
00278         selectors->Append(ref new ProtectionLevelSelectorInfo("None", Windows::Devices::Enumeration::DevicePairingProtectionLevel::None ));
00279         selectors->Append(ref new ProtectionLevelSelectorInfo("Encryption", Windows::Devices::Enumeration::DevicePairingProtectionLevel::Encryption ));
00280         selectors->Append(ref new ProtectionLevelSelectorInfo("Encryption and authentication", Windows::Devices::Enumeration::DevicePairingProtectionLevel::EncryptionAndAuthentication ));
00281
00282         return selectors->GetView();
00283     }
00284
00285     // DeviceInformationDisplay
00286
00287     DeviceInformationDisplay::DeviceInformationDisplay(DeviceInformation^ deviceInfoIn)
00288     {
00289         deviceInfo = deviceInfoIn;
00290         UpdateGlyphBitmapImage();
00291     }
00292
00293     String^ DeviceInformationDisplay::KindString::get()
00294     {
00295         String^ str;
00296         switch (deviceInfo->Kind)
00297         {
00298         case DeviceInformationKind::DeviceContainer:
00299             str = "DeviceContainer";
00300             break;
00301         case DeviceInformationKind::Device:
00302             str = "Device";
00303             break;
00304         case DeviceInformationKind::DeviceInterface:
00305             str = "DeviceInterface";
00306             break;
00307         case DeviceInformationKind::DeviceInterfaceClass:
00308             str = "DeviceInterfaceClass";
00309             break;
00310         case DeviceInformationKind::AssociationEndpointContainer:
00311             str = "AssociationEndpointContainer";
00312             break;
00313         case DeviceInformationKind::AssociationEndpoint:
00314             str = "AssociationEndpoint";
00315             break;
00316         case DeviceInformationKind::AssociationEndpointService:
00317             str = "AssociationEndpointService";
00318             break;
00319         };
00320
00321         return str;
00322     }
00323
00324     void DeviceInformationDisplay::Update(DeviceInformationUpdate^ deviceInfoUpdateIn)
00325     {
00326         deviceInfo->Update(deviceInfoUpdateIn);
00327
00328         OnPropertyChanged("Kind");
00329         OnPropertyChanged("Id");
00330         OnPropertyChanged("Name");
00331         OnPropertyChanged("DeviceInformation");
00332         OnPropertyChanged("CanPair");
00333         OnPropertyChanged("IsPaired");
00334         OnPropertyChanged("GetPropertyForDisplay");
00335
00336         UpdateGlyphBitmapImage();
00337     }
00338
00339     void DeviceInformationDisplay::UpdateGlyphBitmapImage()
00340     {
00341         BitmapImage^ glyphBitmapImage;
00342         glyphBitmapImage = ref new BitmapImage();
00343
00344         concurrency::create_task(deviceInfo->GetGlyphThumbnailAsync()).then(
00345             [glyphBitmapImage](DeviceThumbnail^ result)
00346         {
00347             return glyphBitmapImage->SetSourceAsync(result);
00348         }).then(
00349             [this, glyphBitmapImage]()
00350         {
00351             GlyphBitmapImage = glyphBitmapImage;
00352             OnPropertyChanged("GlyphBitmapImage");
00353         });
00354     }
00355
00356     void DeviceInformationDisplay::OnPropertyChanged(String^ name)
00357     {
00358         MainPage::Current->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler(
00359             [this, name]()
00360         {
00361             PropertyChanged(this, ref new PropertyChangedEventArgs(name));
00362         }));
00363     }
00364
00365
00366     // GeneralPropertyValueConverter
00367
00368     Object^ GeneralPropertyValueConverter::Convert(
00369         Object^ value,
00370         TypeName targetType,
00371         Object^ parameter,
00372         String^ language)
00373     {
00374         Object^ property = nullptr;
00375         String^ strParameter = safe_cast<String^>(parameter);
00376
00377         if (nullptr != strParameter && !strParameter->IsEmpty())
00378         {
00379             IMapView<String^, Object^>^ properties = safe_cast<IMapView<String^, Object^>^>(value);
00380
00381             property = properties->Lookup(strParameter);
00382         }
00383
00384         return property;
00385     }
00386 }
Generated on Fri Nov 15 2024 22:19:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCustomMediaTransportControls/cs/Properties/AssemblyInfo.cs Source File

  • XamlCustomMediaTransportControls
  • cs
  • Properties

AssemblyInfo.cs

Go to the documentation of this file.
00001 ﻿using System.Reflection;
00002 using System.Runtime.CompilerServices;
00003 using System.Runtime.InteropServices;
00004
00005 // General Information about an assembly is controlled through the following
00006 // set of attributes. Change these attribute values to modify the information
00007 // associated with an assembly.
00008 [assembly: AssemblyTitle("CustomMediaTransportControls")]
00009 [assembly: AssemblyDescription("")]
00010 [assembly: AssemblyConfiguration("")]
00011 [assembly: AssemblyCompany("")]
00012 [assembly: AssemblyProduct("CustomMediaTransportControls")]
00013 [assembly: AssemblyCopyright("Copyright ©  2015")]
00014 [assembly: AssemblyTrademark("")]
00015 [assembly: AssemblyCulture("")]
00016
00017 // Version information for an assembly consists of the following four values:
00018 //
00019 //      Major Version
00020 //      Minor Version
00021 //      Build Number
00022 //      Revision
00023 //
00024 // You can specify all the values or you can default the Build and Revision Numbers
00025 // by using the '*' as shown below:
00026 // [assembly: AssemblyVersion("1.0.*")]
00027 [assembly: AssemblyVersion("1.0.0.0")]
00028 [assembly: AssemblyFileVersion("1.0.0.0")]
00029 [assembly: ComVisible(false)]
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_ReceiveFile Member List

This is the complete list of members for Scenario3_ReceiveFile, including all inherited members.
CreateTestFile() | Scenario3_ReceiveFile | [inline, private]
CreateTestFileWithNoExtension() | Scenario3_ReceiveFile | [inline, private]
Extension | Scenario3_ReceiveFile | [private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_ReceiveFile | [inline, protected]
RemoveTestFiles() | Scenario3_ReceiveFile | [inline, private]
rootPage | Scenario3_ReceiveFile | [private]
Scenario3_ReceiveFile() | Scenario3_ReceiveFile | [inline]
Generated on Fri Nov 15 2024 22:23:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: JapanesePhoneticAnalysis/cppwinrt/pch.h Source File

  • JapanesePhoneticAnalysis
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Globalization.h"
00008 #include "winrt/Windows.System.h"
00009 #include "winrt/Windows.UI.Core.h"
00010 #include "winrt/Windows.UI.Xaml.h"
00011 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00012 #include "winrt/Windows.UI.Xaml.Controls.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00014 #include "winrt/Windows.UI.Xaml.Documents.h"
00015 #include "winrt/Windows.UI.Xaml.Interop.h"
00016 #include "winrt/Windows.UI.Xaml.Markup.h"
00017 #include "winrt/Windows.UI.Xaml.Media.h"
00018 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SpatialInputHandler Member List

This is the complete list of members for SpatialInputHandler, including all inherited members.
CheckForInput() | SpatialInputHandler | [inline]
interactionManager | SpatialInputHandler | [private]
OnSourcePressed(SpatialInteractionManager sender, SpatialInteractionSourceEventArgs args) | SpatialInputHandler | [inline]
sourceState | SpatialInputHandler | [private]
SpatialInputHandler() | SpatialInputHandler | [inline]
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DiscoveredDevice Member List

This is the complete list of members for DiscoveredDevice, including all inherited members.
deviceInfo | DiscoveredDevice | [private]
DeviceInfo() | DiscoveredDevice | [inline]
DiscoveredDevice(Windows::Devices::Enumeration::DeviceInformation const &deviceInfoIn) | DiscoveredDevice | [inline]
DisplayName() | DiscoveredDevice | [inline]
propertyChanged | DiscoveredDevice | [private]
PropertyChanged(Windows::UI::Xaml::Data::PropertyChangedEventHandler const &handler) | DiscoveredDevice | [inline]
PropertyChanged(event_token token) | DiscoveredDevice | [inline]
UpdateDeviceInfo(Windows::Devices::Enumeration::DeviceInformationUpdate const &update) | DiscoveredDevice | [inline]
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MessageDialog/cs/CustomCommand.xaml.cs Source File

  • MessageDialog
  • cs

CustomCommand.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Popups;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Navigation;
00016 using System;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class CustomCommand : Page
00021     {
00022         MainPage rootPage = MainPage.Current;
00023
00024         public CustomCommand()
00025         {
00026             this.InitializeComponent();
00027         }
00028
00029         /// <summary>
00030         /// Click handler for the 'CustomCommandButton' button.
00031         /// Demonstrates the use of a message dialog with custom commands, command callbacks, and a default command.
00032         /// A message will be displayed indicating which command was invoked on the dialog.
00033         /// In this scenario, 'Install updates' is selected as the default choice.
00034         /// </summary>
00035         /// <param name="sender">The Object that caused this event to be fired.</param>
00036         /// <param name="e">State information and event data associated with the routed event.</param>
00037         private async void CustomCommandButton_Click(object sender, RoutedEventArgs e)
00038         {
00039             // Create the message dialog and set its content and title
00040             var messageDialog = new MessageDialog("New updates have been found for this program. Would you like to install the new updates?", "Updates available");
00041
00042             // Add commands and set their callbacks
00043             messageDialog.Commands.Add(new UICommand("Don't install", (command) =>
00044             {
00045                 rootPage.NotifyUser("The 'Don't install' command has been selected.", NotifyType.StatusMessage);
00046             }));
00047
00048             messageDialog.Commands.Add(new UICommand("Install updates", (command) =>
00049             {
00050                 rootPage.NotifyUser("The 'Install updates' command has been selected.", NotifyType.StatusMessage);
00051             }));
00052
00053             // Set the command that will be invoked by default
00054             messageDialog.DefaultCommandIndex = 1;
00055
00056             // Show the message dialog
00057             await messageDialog.ShowAsync();
00058         }
00059     }
00060 }
Generated on Fri Nov 15 2024 22:20:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Settings Member List

This is the complete list of members for Settings, including all inherited members.
Settings() | Settings | [inline]
ViewModel | Settings |
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario06_PostMultipart Member List

This is the complete list of members for Scenario06_PostMultipart, including all inherited members.
Cancel_Click(object sender, RoutedEventArgs e) | Scenario06_PostMultipart | [inline, private]
cts | Scenario06_PostMultipart | [private]
httpClient | Scenario06_PostMultipart | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario06_PostMultipart | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario06_PostMultipart | [inline, protected]
rootPage | Scenario06_PostMultipart | [private]
Scenario06_PostMultipart() | Scenario06_PostMultipart | [inline]
Start_Click(object sender, RoutedEventArgs e) | Scenario06_PostMultipart | [inline, private]
Generated on Fri Nov 15 2024 22:23:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LowLatencyInput/cpp/Common/DeviceResources.cpp Source File

  • LowLatencyInput
  • cpp
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DeviceResources.h"
00014 #include "DirectXHelper.h"
00015 #include <windows.ui.xaml.media.dxinterop.h>
00016
00017 using namespace D2D1;
00018 using namespace DirectX;
00019 using namespace Microsoft::WRL;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::UI::Core;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Platform;
00025
00026 // Constants used to calculate screen rotations.
00027 namespace ScreenRotation
00028 {
00029     // 0-degree Z-rotation
00030     static const XMFLOAT4X4 Rotation0(
00031         1.0f, 0.0f, 0.0f, 0.0f,
00032         0.0f, 1.0f, 0.0f, 0.0f,
00033         0.0f, 0.0f, 1.0f, 0.0f,
00034         0.0f, 0.0f, 0.0f, 1.0f
00035         );
00036
00037     // 90-degree Z-rotation
00038     static const XMFLOAT4X4 Rotation90(
00039         0.0f, 1.0f, 0.0f, 0.0f,
00040         -1.0f, 0.0f, 0.0f, 0.0f,
00041         0.0f, 0.0f, 1.0f, 0.0f,
00042         0.0f, 0.0f, 0.0f, 1.0f
00043         );
00044
00045     // 180-degree Z-rotation
00046     static const XMFLOAT4X4 Rotation180(
00047         -1.0f, 0.0f, 0.0f, 0.0f,
00048         0.0f, -1.0f, 0.0f, 0.0f,
00049         0.0f, 0.0f, 1.0f, 0.0f,
00050         0.0f, 0.0f, 0.0f, 1.0f
00051         );
00052
00053     // 270-degree Z-rotation
00054     static const XMFLOAT4X4 Rotation270(
00055         0.0f, -1.0f, 0.0f, 0.0f,
00056         1.0f, 0.0f, 0.0f, 0.0f,
00057         0.0f, 0.0f, 1.0f, 0.0f,
00058         0.0f, 0.0f, 0.0f, 1.0f
00059         );
00060 };
00061
00062 // Constructor for DeviceResources.
00063 DX::DeviceResources::DeviceResources() :
00064     m_screenViewport(),
00065     m_d3dFeatureLevel(D3D_FEATURE_LEVEL_9_1),
00066     m_d3dRenderTargetSize(),
00067     m_outputSize(),
00068     m_logicalSize(),
00069     m_nativeOrientation(DisplayOrientations::None),
00070     m_currentOrientation(DisplayOrientations::None),
00071     m_dpi(-1.0f),
00072     m_compositionScaleX(1.0f),
00073     m_compositionScaleY(1.0f),
00074     m_deviceNotify(nullptr)
00075 {
00076     CreateDeviceIndependentResources();
00077     CreateDeviceResources();
00078 }
00079
00080 // Configures resources that don't depend on the Direct3D device.
00081 void DX::DeviceResources::CreateDeviceIndependentResources()
00082 {
00083     // Initialize Direct2D resources.
00084     D2D1_FACTORY_OPTIONS options;
00085     ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
00086
00087 #if defined(_DEBUG)
00088     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00089     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00090 #endif
00091
00092     // Initialize the Direct2D Factory.
00093     DX::ThrowIfFailed(
00094         D2D1CreateFactory(
00095             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00096             __uuidof(ID2D1Factory2),
00097             &options,
00098             &m_d2dFactory
00099             )
00100         );
00101
00102     // Initialize the DirectWrite Factory.
00103     DX::ThrowIfFailed(
00104         DWriteCreateFactory(
00105             DWRITE_FACTORY_TYPE_SHARED,
00106             __uuidof(IDWriteFactory2),
00107             &m_dwriteFactory
00108             )
00109         );
00110
00111     // Initialize the Windows Imaging Component (WIC) Factory.
00112     DX::ThrowIfFailed(
00113         CoCreateInstance(
00114             CLSID_WICImagingFactory2,
00115             nullptr,
00116             CLSCTX_INPROC_SERVER,
00117             IID_PPV_ARGS(&m_wicFactory)
00118             )
00119         );
00120 }
00121
00122 // Configures the Direct3D device, and stores handles to it and the device context.
00123 void DX::DeviceResources::CreateDeviceResources()
00124 {
00125     // This flag adds support for surfaces with a different color channel ordering
00126     // than the API default. It is required for compatibility with Direct2D.
00127     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00128
00129 #if defined(_DEBUG)
00130     if (DX::SdkLayersAvailable())
00131     {
00132         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00133         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00134     }
00135 #endif
00136
00137     // This array defines the set of DirectX hardware feature levels this app will support.
00138     // Note the ordering should be preserved.
00139     // Don't forget to declare your application's minimum required feature level in its
00140     // description.  All applications are assumed to support 9.1 unless otherwise stated.
00141     D3D_FEATURE_LEVEL featureLevels[] =
00142     {
00143         D3D_FEATURE_LEVEL_11_1,
00144         D3D_FEATURE_LEVEL_11_0,
00145         D3D_FEATURE_LEVEL_10_1,
00146         D3D_FEATURE_LEVEL_10_0,
00147         D3D_FEATURE_LEVEL_9_3,
00148         D3D_FEATURE_LEVEL_9_2,
00149         D3D_FEATURE_LEVEL_9_1
00150     };
00151
00152     // Create the Direct3D 11 API device object and a corresponding context.
00153     ComPtr<ID3D11Device> device;
00154     ComPtr<ID3D11DeviceContext> context;
00155
00156     HRESULT hr = D3D11CreateDevice(
00157         nullptr,                    // Specify nullptr to use the default adapter.
00158         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00159         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00160         creationFlags,              // Set debug and Direct2D compatibility flags.
00161         featureLevels,              // List of feature levels this app can support.
00162         ARRAYSIZE(featureLevels),   // Size of the list above.
00163         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00164         &device,                    // Returns the Direct3D device created.
00165         &m_d3dFeatureLevel,         // Returns feature level of device created.
00166         &context                    // Returns the device immediate context.
00167         );
00168
00169     if (FAILED(hr))
00170     {
00171         // If the initialization fails, fall back to the WARP device.
00172         // For more information on WARP, see:
00173         // http://go.microsoft.com/fwlink/?LinkId=286690
00174         DX::ThrowIfFailed(
00175             D3D11CreateDevice(
00176                 nullptr,
00177                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00178                 0,
00179                 creationFlags,
00180                 featureLevels,
00181                 ARRAYSIZE(featureLevels),
00182                 D3D11_SDK_VERSION,
00183                 &device,
00184                 &m_d3dFeatureLevel,
00185                 &context
00186                 )
00187             );
00188     }
00189
00190     // Store pointers to the Direct3D 11.1 API device and immediate context.
00191     DX::ThrowIfFailed(
00192         device.As(&m_d3dDevice)
00193         );
00194
00195     DX::ThrowIfFailed(
00196         context.As(&m_d3dContext)
00197         );
00198
00199     // Create the Direct2D device object and a corresponding context.
00200     ComPtr<IDXGIDevice3> dxgiDevice;
00201     DX::ThrowIfFailed(
00202         m_d3dDevice.As(&dxgiDevice)
00203         );
00204
00205     DX::ThrowIfFailed(
00206         m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
00207         );
00208
00209     DX::ThrowIfFailed(
00210         m_d2dDevice->CreateDeviceContext(
00211             D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
00212             &m_d2dContext
00213             )
00214         );
00215 }
00216
00217 // These resources need to be recreated every time the window size is changed.
00218 void DX::DeviceResources::CreateWindowSizeDependentResources()
00219 {
00220     // Clear the previous window size specific context.
00221     ID3D11RenderTargetView* nullViews[] = {nullptr};
00222     m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr);
00223     m_d3dRenderTargetView = nullptr;
00224     m_d2dContext->SetTarget(nullptr);
00225     m_d2dTargetBitmap = nullptr;
00226     m_d3dDepthStencilView = nullptr;
00227     m_d3dContext->Flush();
00228
00229     // Calculate the necessary swap chain and render target size in pixels.
00230     m_outputSize.Width = m_logicalSize.Width * m_compositionScaleX;
00231     m_outputSize.Height = m_logicalSize.Height * m_compositionScaleY;
00232
00233     // Prevent zero size DirectX content from being created.
00234     m_outputSize.Width = max(m_outputSize.Width, 1);
00235     m_outputSize.Height = max(m_outputSize.Height, 1);
00236
00237     // The width and height of the swap chain must be based on the window's
00238     // natively-oriented width and height. If the window is not in the native
00239     // orientation, the dimensions must be reversed.
00240     DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation();
00241
00242     bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270;
00243     m_d3dRenderTargetSize.Width = swapDimensions ? m_outputSize.Height : m_outputSize.Width;
00244     m_d3dRenderTargetSize.Height = swapDimensions ? m_outputSize.Width : m_outputSize.Height;
00245
00246     if (m_swapChain != nullptr)
00247     {
00248         // If the swap chain already exists, resize it.
00249         HRESULT hr = m_swapChain->ResizeBuffers(
00250             2, // Single-buffered swap chain.
00251             lround(m_d3dRenderTargetSize.Width),
00252             lround(m_d3dRenderTargetSize.Height),
00253             DXGI_FORMAT_B8G8R8A8_UNORM,
00254             DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT //Enables GetFrameLatencyWaitableObject()
00255             );
00256
00257         if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00258         {
00259             // If the device was removed for any reason, a new device and swap chain will need to be created.
00260             HandleDeviceLost();
00261
00262             // Everything is set up now. Do not continue execution of this method. HandleDeviceLost will reenter this method
00263             // and correctly set up the new device.
00264             return;
00265         }
00266         else
00267         {
00268             DX::ThrowIfFailed(hr);
00269         }
00270     }
00271     else
00272     {
00273         // Otherwise, create a new one using the same adapter as the existing Direct3D device.
00274         DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
00275
00276         swapChainDesc.Width = lround(m_d3dRenderTargetSize.Width); // Match the size of the window.
00277         swapChainDesc.Height = lround(m_d3dRenderTargetSize.Height);
00278         swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swap chain format.
00279         swapChainDesc.Stereo = false;
00280         swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling.
00281         swapChainDesc.SampleDesc.Quality = 0;
00282         swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
00283         swapChainDesc.BufferCount = 2; // Use double-buffering to minimize latency.
00284         swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // All Windows Store apps must use this SwapEffect.
00285         //swapChainDesc.Flags = 0;
00286         swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; // Enable GetFrameLatencyWaitableObject()
00287         swapChainDesc.Scaling = DXGI_SCALING_STRETCH;
00288         swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
00289
00290         // This sequence obtains the DXGI factory that was used to create the Direct3D device above.
00291         ComPtr<IDXGIDevice3> dxgiDevice;
00292         DX::ThrowIfFailed(
00293             m_d3dDevice.As(&dxgiDevice)
00294             );
00295
00296         ComPtr<IDXGIAdapter> dxgiAdapter;
00297         DX::ThrowIfFailed(
00298             dxgiDevice->GetAdapter(&dxgiAdapter)
00299             );
00300
00301         ComPtr<IDXGIFactory2> dxgiFactory;
00302         DX::ThrowIfFailed(
00303             dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory))
00304             );
00305
00306         // When using XAML interop, the swap chain must be created for composition.
00307         DX::ThrowIfFailed(
00308             dxgiFactory->CreateSwapChainForComposition(
00309                 m_d3dDevice.Get(),
00310                 &swapChainDesc,
00311                 nullptr,
00312                 &m_swapChain
00313                 )
00314             );
00315
00316         // Associate swap chain with SwapChainPanel
00317         // UI changes will need to be dispatched back to the UI thread
00318         m_swapChainPanel->Dispatcher->RunAsync(CoreDispatcherPriority::High, ref new DispatchedHandler([=]()
00319         {
00320             // Get backing native interface for SwapChainPanel
00321             ComPtr<ISwapChainPanelNative> panelNative;
00322             DX::ThrowIfFailed(
00323                 reinterpret_cast<IUnknown*>(m_swapChainPanel)->QueryInterface(IID_PPV_ARGS(&panelNative))
00324                 );
00325
00326             DX::ThrowIfFailed(
00327                 panelNative->SetSwapChain(m_swapChain.Get()));
00328         }, CallbackContext::Any));
00329
00330         ComPtr<IDXGISwapChain2> swapChain2;
00331         DX::ThrowIfFailed(m_swapChain.As(&swapChain2));
00332
00333         // Get the frame latency waitable object, which is used by the WaitOnSwapChain method. This
00334         // requires that swap chain be created with the DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT
00335         // flag.
00336         m_frameLatencyWaitableObject = swapChain2->GetFrameLatencyWaitableObject();
00337     }
00338
00339     // Set the proper orientation for the swap chain, and generate 2D and
00340     // 3D matrix transformations for rendering to the rotated swap chain.
00341     // Note the rotation angle for the 2D and 3D transforms are different.
00342     // This is due to the difference in coordinate spaces.  Additionally,
00343     // the 3D matrix is specified explicitly to avoid rounding errors.
00344
00345     switch (displayRotation)
00346     {
00347     case DXGI_MODE_ROTATION_IDENTITY:
00348         m_orientationTransform2D = Matrix3x2F::Identity();
00349         m_orientationTransform3D = ScreenRotation::Rotation0;
00350         break;
00351
00352     case DXGI_MODE_ROTATION_ROTATE90:
00353         m_orientationTransform2D =
00354             Matrix3x2F::Rotation(90.0f) *
00355             Matrix3x2F::Translation(m_logicalSize.Height, 0.0f);
00356         m_orientationTransform3D = ScreenRotation::Rotation270;
00357         break;
00358
00359     case DXGI_MODE_ROTATION_ROTATE180:
00360         m_orientationTransform2D =
00361             Matrix3x2F::Rotation(180.0f) *
00362             Matrix3x2F::Translation(m_logicalSize.Width, m_logicalSize.Height);
00363         m_orientationTransform3D = ScreenRotation::Rotation180;
00364         break;
00365
00366     case DXGI_MODE_ROTATION_ROTATE270:
00367         m_orientationTransform2D =
00368             Matrix3x2F::Rotation(270.0f) *
00369             Matrix3x2F::Translation(0.0f, m_logicalSize.Width);
00370         m_orientationTransform3D = ScreenRotation::Rotation90;
00371         break;
00372
00373     default:
00374         throw ref new FailureException();
00375     }
00376
00377     DX::ThrowIfFailed(
00378         m_swapChain->SetRotation(displayRotation)
00379         );
00380
00381     //Setup inverse scale on the swap chain
00382     DXGI_MATRIX_3X2_F inverseScale = { 0 };
00383     inverseScale._11 = 1.0f / m_compositionScaleX;
00384     inverseScale._22 = 1.0f / m_compositionScaleY;
00385     ComPtr<IDXGISwapChain2> spSwapChain2;
00386     DX::ThrowIfFailed(
00387         m_swapChain.As<IDXGISwapChain2>(&spSwapChain2)
00388         );
00389
00390     DX::ThrowIfFailed(
00391         spSwapChain2->SetMatrixTransform(&inverseScale)
00392         );
00393
00394     // Create a render target view of the swap chain back buffer.
00395     ComPtr<ID3D11Texture2D> backBuffer;
00396     DX::ThrowIfFailed(
00397         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer))
00398         );
00399
00400     DX::ThrowIfFailed(
00401         m_d3dDevice->CreateRenderTargetView(
00402             backBuffer.Get(),
00403             nullptr,
00404             &m_d3dRenderTargetView
00405             )
00406         );
00407
00408     // Create a depth stencil view for use with 3D rendering if needed.
00409     CD3D11_TEXTURE2D_DESC depthStencilDesc(
00410         DXGI_FORMAT_D24_UNORM_S8_UINT,
00411         lround(m_d3dRenderTargetSize.Width),
00412         lround(m_d3dRenderTargetSize.Height),
00413         1, // This depth stencil view has only one texture.
00414         1, // Use a single mipmap level.
00415         D3D11_BIND_DEPTH_STENCIL
00416         );
00417
00418     ComPtr<ID3D11Texture2D> depthStencil;
00419     DX::ThrowIfFailed(
00420         m_d3dDevice->CreateTexture2D(
00421             &depthStencilDesc,
00422             nullptr,
00423             &depthStencil
00424             )
00425         );
00426
00427     CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
00428     DX::ThrowIfFailed(
00429         m_d3dDevice->CreateDepthStencilView(
00430             depthStencil.Get(),
00431             &depthStencilViewDesc,
00432             &m_d3dDepthStencilView
00433             )
00434         );
00435
00436     // Set the 3D rendering viewport to target the entire window.
00437     m_screenViewport = CD3D11_VIEWPORT(
00438         0.0f,
00439         0.0f,
00440         m_d3dRenderTargetSize.Width,
00441         m_d3dRenderTargetSize.Height
00442         );
00443
00444     m_d3dContext->RSSetViewports(1, &m_screenViewport);
00445
00446     // Create a Direct2D target bitmap associated with the
00447     // swap chain back buffer and set it as the current target.
00448     D2D1_BITMAP_PROPERTIES1 bitmapProperties =
00449         D2D1::BitmapProperties1(
00450             D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
00451             D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
00452             m_dpi,
00453             m_dpi
00454             );
00455
00456     ComPtr<IDXGISurface2> dxgiBackBuffer;
00457     DX::ThrowIfFailed(
00458         m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer))
00459         );
00460
00461     DX::ThrowIfFailed(
00462         m_d2dContext->CreateBitmapFromDxgiSurface(
00463             dxgiBackBuffer.Get(),
00464             &bitmapProperties,
00465             &m_d2dTargetBitmap
00466             )
00467         );
00468
00469     m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
00470
00471     // Grayscale text anti-aliasing is recommended for all Windows Store apps.
00472     m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
00473 }
00474
00475 // This method is called when the XAML control is created (or re-created).
00476 void DX::DeviceResources::SetSwapChainPanel(SwapChainPanel^ panel)
00477 {
00478     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00479
00480     m_swapChainPanel = panel;
00481     m_logicalSize = Windows::Foundation::Size(static_cast<float>(panel->ActualWidth), static_cast<float>(panel->ActualHeight));
00482     m_nativeOrientation = currentDisplayInformation->NativeOrientation;
00483     m_currentOrientation = currentDisplayInformation->CurrentOrientation;
00484     m_compositionScaleX = panel->CompositionScaleX;
00485     m_compositionScaleY = panel->CompositionScaleY;
00486     m_dpi = currentDisplayInformation->LogicalDpi;
00487     m_d2dContext->SetDpi(m_dpi, m_dpi);
00488
00489     CreateWindowSizeDependentResources();
00490 }
00491
00492 // This method is called in the event handler for the SizeChanged event.
00493 void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize)
00494 {
00495     if (m_logicalSize != logicalSize)
00496     {
00497         m_logicalSize = logicalSize;
00498         CreateWindowSizeDependentResources();
00499     }
00500 }
00501
00502 // This method is called in the event handler for the DpiChanged event.
00503 void DX::DeviceResources::SetDpi(float dpi)
00504 {
00505     if (dpi != m_dpi)
00506     {
00507         m_dpi = dpi;
00508         m_d2dContext->SetDpi(m_dpi, m_dpi);
00509         CreateWindowSizeDependentResources();
00510     }
00511 }
00512
00513 // This method is called in the event handler for the OrientationChanged event.
00514 void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation)
00515 {
00516     if (m_currentOrientation != currentOrientation)
00517     {
00518         m_currentOrientation = currentOrientation;
00519         CreateWindowSizeDependentResources();
00520     }
00521 }
00522
00523 // This method is called in the event handler for the CompositionScaleChanged event.
00524 void DX::DeviceResources::SetCompositionScale(float compositionScaleX, float compositionScaleY)
00525 {
00526     if (m_compositionScaleX != compositionScaleX ||
00527         m_compositionScaleY != compositionScaleY)
00528     {
00529         m_compositionScaleX = compositionScaleX;
00530         m_compositionScaleY = compositionScaleY;
00531         CreateWindowSizeDependentResources();
00532     }
00533 }
00534
00535 // This method is called in the event handler for the DisplayContentsInvalidated event.
00536 void DX::DeviceResources::ValidateDevice()
00537 {
00538     // The D3D Device is no longer valid if the default adapter changed since the device
00539     // was created or if the device has been removed.
00540
00541     // First, get the information for the default adapter from when the device was created.
00542
00543     ComPtr<IDXGIDevice3> dxgiDevice;
00544     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00545
00546     ComPtr<IDXGIAdapter> deviceAdapter;
00547     DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter));
00548
00549     ComPtr<IDXGIFactory2> deviceFactory;
00550     DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory)));
00551
00552     ComPtr<IDXGIAdapter1> previousDefaultAdapter;
00553     DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter));
00554
00555     DXGI_ADAPTER_DESC previousDesc;
00556     DX::ThrowIfFailed(previousDefaultAdapter->GetDesc(&previousDesc));
00557
00558     // Next, get the information for the current default adapter.
00559
00560     ComPtr<IDXGIFactory2> currentFactory;
00561     DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&currentFactory)));
00562
00563     ComPtr<IDXGIAdapter1> currentDefaultAdapter;
00564     DX::ThrowIfFailed(currentFactory->EnumAdapters1(0, &currentDefaultAdapter));
00565
00566     DXGI_ADAPTER_DESC currentDesc;
00567     DX::ThrowIfFailed(currentDefaultAdapter->GetDesc(&currentDesc));
00568
00569     // If the adapter LUIDs don't match, or if the device reports that it has been removed,
00570     // a new D3D device must be created.
00571
00572     if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart ||
00573         previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart ||
00574         FAILED(m_d3dDevice->GetDeviceRemovedReason()))
00575     {
00576         // Release references to resources related to the old device.
00577         dxgiDevice = nullptr;
00578         deviceAdapter = nullptr;
00579         deviceFactory = nullptr;
00580         previousDefaultAdapter = nullptr;
00581
00582         // Create a new device and swap chain.
00583         HandleDeviceLost();
00584     }
00585 }
00586
00587 // Recreate all device resources and set them back to the current state.
00588 void DX::DeviceResources::HandleDeviceLost()
00589 {
00590     m_swapChain = nullptr;
00591
00592     if (m_deviceNotify != nullptr)
00593     {
00594         // Notify the renderers that device resources need to be released.
00595         // This ensures all references to the existing swap chain are released so that a new one can be created.
00596         m_deviceNotify->OnDeviceLost();
00597     }
00598
00599     // Create the new device and swap chain.
00600     CreateDeviceResources();
00601     m_d2dContext->SetDpi(m_dpi, m_dpi);
00602     CreateWindowSizeDependentResources();
00603
00604     if (m_deviceNotify != nullptr)
00605     {
00606         // Notify the renderers that resources can now be created again.
00607         m_deviceNotify->OnDeviceRestored();
00608     }
00609 }
00610
00611 // Register our DeviceNotify to be informed on device lost and creation.
00612 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00613 {
00614     m_deviceNotify = deviceNotify;
00615 }
00616
00617 // Call this method when the app suspends. It provides a hint to the driver that the app
00618 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00619 void DX::DeviceResources::Trim()
00620 {
00621     ComPtr<IDXGIDevice3> dxgiDevice;
00622     m_d3dDevice.As(&dxgiDevice);
00623
00624     dxgiDevice->Trim();
00625 }
00626
00627 // Present the contents of the swap chain to the screen.
00628 void DX::DeviceResources::Present()
00629 {
00630     // The first argument instructs DXGI to block until VSync, putting the application
00631     // to sleep until the next VSync. This ensures we don't waste any cycles rendering
00632     // frames that will never be displayed to the screen.
00633     HRESULT hr = m_swapChain->Present(1, 0);
00634
00635     // Discard the contents of the render target.
00636     // This is a valid operation only when the existing contents will be entirely
00637     // overwritten. If dirty or scroll rects are used, this call should be removed.
00638     m_d3dContext->DiscardView(m_d3dRenderTargetView.Get());
00639
00640     // Discard the contents of the depth stencil.
00641     m_d3dContext->DiscardView(m_d3dDepthStencilView.Get());
00642
00643     // If the device was removed either by a disconnection or a driver upgrade, we
00644     // must recreate all device resources.
00645     if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
00646     {
00647         HandleDeviceLost();
00648     }
00649     else
00650     {
00651         DX::ThrowIfFailed(hr);
00652     }
00653 }
00654
00655 //Block the current thread until the swap chain has finished presenting.
00656 void DX::DeviceResources::WaitOnSwapChain()
00657 {
00658     DWORD result = WaitForSingleObjectEx(
00659         m_frameLatencyWaitableObject,
00660         INFINITE, // Infinite timeout (shouldn't ever occur)
00661         true
00662         );
00663 }
00664
00665 // This method determines the rotation between the display device's native Orientation and the
00666 // current display orientation.
00667 DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation()
00668 {
00669     DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED;
00670
00671     // Note: NativeOrientation can only be Landscape or Portrait even though
00672     // the DisplayOrientations enum has other values.
00673     switch (m_nativeOrientation)
00674     {
00675     case DisplayOrientations::Landscape:
00676         switch (m_currentOrientation)
00677         {
00678         case DisplayOrientations::Landscape:
00679             rotation = DXGI_MODE_ROTATION_IDENTITY;
00680             break;
00681
00682         case DisplayOrientations::Portrait:
00683             rotation = DXGI_MODE_ROTATION_ROTATE270;
00684             break;
00685
00686         case DisplayOrientations::LandscapeFlipped:
00687             rotation = DXGI_MODE_ROTATION_ROTATE180;
00688             break;
00689
00690         case DisplayOrientations::PortraitFlipped:
00691             rotation = DXGI_MODE_ROTATION_ROTATE90;
00692             break;
00693         }
00694         break;
00695
00696     case DisplayOrientations::Portrait:
00697         switch (m_currentOrientation)
00698         {
00699         case DisplayOrientations::Landscape:
00700             rotation = DXGI_MODE_ROTATION_ROTATE90;
00701             break;
00702
00703         case DisplayOrientations::Portrait:
00704             rotation = DXGI_MODE_ROTATION_IDENTITY;
00705             break;
00706
00707         case DisplayOrientations::LandscapeFlipped:
00708             rotation = DXGI_MODE_ROTATION_ROTATE270;
00709             break;
00710
00711         case DisplayOrientations::PortraitFlipped:
00712             rotation = DXGI_MODE_ROTATION_ROTATE180;
00713             break;
00714         }
00715         break;
00716     }
00717     return rotation;
00718 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Projection/cs/Scenario2.xaml.cs Source File

  • Projection
  • cs

Scenario2.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using SecondaryViewsHelpers;
00014 using System;
00015 using Windows.ApplicationModel.Core;
00016 using Windows.Foundation;
00017 using Windows.UI.Core;
00018 using Windows.UI.ViewManagement;
00019 using Windows.UI.Xaml;
00020 using Windows.UI.Xaml.Controls;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00024
00025 namespace SDKSample
00026 {
00027     /// <summary>
00028     /// An empty page that can be used on its own or navigated to within a Frame.
00029     /// </summary>
00030     public sealed partial class Scenario2:Page
00031     {
00032         MainPage rootPage = MainPage.Current;
00033         CoreDispatcher dispatcher;
00034         int thisViewId;
00035
00036         public Scenario2()
00037         {
00038             InitializeComponent();
00039             thisViewId = ApplicationView.GetForCurrentView().Id;
00040         }
00041
00042         protected override void OnNavigatedFrom(NavigationEventArgs e)
00043         {
00044             ProjectionManager.ProjectionDisplayAvailableChanged -= ProjectionManager_ProjectionDisplayAvailableChanged;
00045         }
00046
00047         protected override void OnNavigatedTo(NavigationEventArgs e)
00048         {
00049             // An app can query if a second display is available...
00050             UpdateTextBlock(ProjectionManager.ProjectionDisplayAvailable);
00051             // ...or listen for when a display is attached or detached
00052             ProjectionManager.ProjectionDisplayAvailableChanged += ProjectionManager_ProjectionDisplayAvailableChanged;
00053             dispatcher = Window.Current.Dispatcher;
00054         }
00055
00056         private async void ProjectionManager_ProjectionDisplayAvailableChanged(object sender, object e)
00057         {
00058             await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00059             {
00060                 UpdateTextBlock(ProjectionManager.ProjectionDisplayAvailable);
00061             });
00062         }
00063
00064         private void UpdateTextBlock(bool screenAvailable)
00065         {
00066             if (screenAvailable)
00067             {
00068                 this.displayAvailableStatus.Text = "Display is available";
00069                 this.startprojecting_button.Visibility = Visibility.Visible;
00070                 this.requestandstartprojecting_button.Visibility = Visibility.Collapsed;
00071             }
00072             else
00073             {
00074                 this.displayAvailableStatus.Text = "Display is not available, select one:";
00075                 this.startprojecting_button.Visibility = Visibility.Collapsed;
00076                 this.requestandstartprojecting_button.Visibility = Visibility.Visible;
00077             }
00078         }
00079
00080         private async void StartProjecting_Click(object sender, RoutedEventArgs e)
00081         {
00082             // If projection is already in progress, then it could be shown on the monitor again
00083             // Otherwise, we need to create a new view to show the presentation
00084             if (rootPage.ProjectionViewPageControl == null)
00085             {
00086                 // First, create a new, blank view
00087                 await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00088                 {
00089                     // ViewLifetimeControl is a wrapper to make sure the view is closed only
00090                     // when the app is done with it
00091                     rootPage.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView();
00092
00093                     // Assemble some data necessary for the new page
00094                     var initData = new ProjectionViewPageInitializationData();
00095                     initData.MainDispatcher = dispatcher;
00096                     initData.ProjectionViewPageControl = rootPage.ProjectionViewPageControl;
00097                     initData.MainViewId = thisViewId;
00098
00099                     // Display the page in the view. Note that the view will not become visible
00100                     // until "StartProjectingAsync" is called
00101                     var rootFrame = new Frame();
00102                     rootFrame.Navigate(typeof(ProjectionViewPage), initData);
00103                     Window.Current.Content = rootFrame;
00104
00105                     // The call to Window.Current.Activate is required starting in Windos 10.
00106                     // Without it, the view will never appear.
00107                     Window.Current.Activate();
00108                 });
00109             }
00110
00111             try
00112             {
00113                 // Start/StopViewInUse are used to signal that the app is interacting with the
00114                 // view, so it shouldn't be closed yet, even if the user loses access to it
00115                 rootPage.ProjectionViewPageControl.StartViewInUse();
00116
00117                 // Show the view on a second display (if available) or on the primary display
00118                 await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId);
00119
00120                 rootPage.ProjectionViewPageControl.StopViewInUse();
00121
00122                 rootPage.NotifyUser("Projection started with success", NotifyType.StatusMessage);
00123             }
00124             catch (InvalidOperationException)
00125             {
00126                 rootPage.NotifyUser("The projection view is being disposed", NotifyType.ErrorMessage);
00127             }
00128         }
00129
00130         private async void RequestAndStartProjecting_Click(object sender, RoutedEventArgs e)
00131         {
00132             // If projection is already in progress, then it could be shown on the monitor again
00133             // Otherwise, we need to create a new view to show the presentation
00134             if (rootPage.ProjectionViewPageControl == null)
00135             {
00136                 // First, create a new, blank view
00137                 var thisDispatcher = Window.Current.Dispatcher;
00138                 await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00139                 {
00140                     // ViewLifetimeControl is a wrapper to make sure the view is closed only
00141                     // when the app is done with it
00142                     rootPage.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView();
00143
00144                     // Assemble some data necessary for the new page
00145                     var initData = new ProjectionViewPageInitializationData();
00146                     initData.MainDispatcher = thisDispatcher;
00147                     initData.ProjectionViewPageControl = rootPage.ProjectionViewPageControl;
00148                     initData.MainViewId = thisViewId;
00149
00150                     // Display the page in the view. Note that the view will not become visible
00151                     // until "StartProjectingAsync" is called
00152                     var rootFrame = new Frame();
00153                     rootFrame.Navigate(typeof(ProjectionViewPage), initData);
00154                     Window.Current.Content = rootFrame;
00155                     Window.Current.Activate();
00156                 });
00157             }
00158
00159             try
00160             {
00161                 // Start/StopViewInUse are used to signal that the app is interacting with the
00162                 // view, so it shouldn't be closed yet, even if the user loses access to it
00163                 rootPage.ProjectionViewPageControl.StartViewInUse();
00164
00165                 // Show the view on a second display (if available) or on the primary display
00166                 Rect pickerLocation = new Rect(470.0, 0.0, 200.0, 300.0);
00167                 await ProjectionManager.RequestStartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId, pickerLocation, Windows.UI.Popups.Placement.Above);
00168
00169                 rootPage.ProjectionViewPageControl.StopViewInUse();
00170
00171                 rootPage.NotifyUser("Projection started with success", NotifyType.StatusMessage);
00172             }
00173             catch (InvalidOperationException)
00174             {
00175                 rootPage.NotifyUser("The projection view is being disposed", NotifyType.ErrorMessage);
00176             }
00177         }
00178
00179     }
00180 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/Service/Server/ServiceInstaller.h Source File

  • CustomCapability
  • Service
  • Server

ServiceInstaller.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 // The file declares functions that install and uninstall the service.
00013
00014 #pragma once
00015
00016 //
00017 //   FUNCTION: InstallService
00018 //
00019 //   PURPOSE: Install the current application as a service to the local
00020 //   service control manager database.
00021 //
00022 //   PARAMETERS:
00023 //   * pszServiceName - the name of the service to be installed
00024 //   * pszDisplayName - the display name of the service
00025 //   * dwStartType - the service start option. This parameter can be one of
00026 //     the following values: SERVICE_AUTO_START, SERVICE_BOOT_START,
00027 //     SERVICE_DEMAND_START, SERVICE_DISABLED, SERVICE_SYSTEM_START.
00028 //   * pszDependencies - a pointer to a double null-terminated array of null-
00029 //     separated names of services or load ordering groups that the system
00030 //     must start before this service.
00031 //   * pszAccount - the name of the account under which the service runs.
00032 //   * pszPassword - the password to the account name.
00033 //
00034 //   NOTE: If the function fails to install the service, it prints the error
00035 //   in the standard output stream for users to diagnose the problem.
00036 //
00037 void InstallService(PWSTR pszServiceName,
00038     PWSTR pszDisplayName,
00039     DWORD dwStartType,
00040     PWSTR pszDependencies,
00041     PWSTR pszAccount,
00042     PWSTR pszPassword);
00043
00044
00045 //
00046 //   FUNCTION: UninstallService
00047 //
00048 //   PURPOSE: Stop and remove the service from the local service control
00049 //   manager database.
00050 //
00051 //   PARAMETERS:
00052 //   * pszServiceName - the name of the service to be removed.
00053 //
00054 //   NOTE: If the function fails to uninstall the service, it prints the
00055 //   error in the standard output stream for users to diagnose the problem.
00056 //
00057 void UninstallService(PWSTR pszServiceName);
Generated on Fri Nov 15 2024 22:19:04 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PipeOut Member List

This is the complete list of members for PipeOut, including all inherited members.
__pad0__ | PipeOut |
events | PipeOut | [private]
FlushAsync() | PipeOut | [inline, virtual]
WriteAsync(IBuffer^buf) | PipeOut | [inline, virtual]
~PipeOut() | PipeOut | [inline, virtual]
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/Common/StepTimer.h Source File

  • HolographicVoiceInput
  • cpp
  • Common

StepTimer.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 namespace DX
00014 {
00015     // Helper class for animation and simulation timing.
00016     class StepTimer
00017     {
00018     public:
00019         StepTimer() :
00020             m_elapsedTicks(0),
00021             m_totalTicks(0),
00022             m_leftOverTicks(0),
00023             m_frameCount(0),
00024             m_framesPerSecond(0),
00025             m_framesThisSecond(0),
00026             m_qpcSecondCounter(0),
00027             m_isFixedTimeStep(false),
00028             m_targetElapsedTicks(TicksPerSecond / 60)
00029         {
00030             m_qpcFrequency = GetPerformanceFrequency();
00031
00032             // Initialize max delta to 1/10 of a second.
00033             m_qpcMaxDelta = m_qpcFrequency / 10;
00034         }
00035
00036         // Get elapsed time since the previous Update call.
00037         uint64 GetElapsedTicks() const                        { return m_elapsedTicks;                  }
00038         double GetElapsedSeconds() const                      { return TicksToSeconds(m_elapsedTicks);  }
00039
00040         // Get total time since the start of the program.
00041         uint64 GetTotalTicks() const                          { return m_totalTicks;                    }
00042         double GetTotalSeconds() const                        { return TicksToSeconds(m_totalTicks);    }
00043
00044         // Get total number of updates since start of the program.
00045         uint32 GetFrameCount() const                          { return m_frameCount;                    }
00046
00047         // Get the current framerate.
00048         uint32 GetFramesPerSecond() const                     { return m_framesPerSecond;               }
00049
00050         // Set whether to use fixed or variable timestep mode.
00051         void SetFixedTimeStep(bool isFixedTimestep)           { m_isFixedTimeStep = isFixedTimestep;    }
00052
00053         // Set how often to call Update when in fixed timestep mode.
00054         void SetTargetElapsedTicks(uint64 targetElapsed)      { m_targetElapsedTicks = targetElapsed;   }
00055         void SetTargetElapsedSeconds(double targetElapsed)    { m_targetElapsedTicks = SecondsToTicks(targetElapsed);   }
00056
00057         // Integer format represents time using 10,000,000 ticks per second.
00058         static const uint64 TicksPerSecond = 10'000'000;
00059
00060         static double TicksToSeconds(uint64 ticks)            { return static_cast<double>(ticks) / TicksPerSecond;     }
00061         static uint64 SecondsToTicks(double seconds)          { return static_cast<uint64>(seconds * TicksPerSecond);   }
00062
00063         // Convenient wrapper for QueryPerformanceFrequency. Throws an exception if
00064         // the call to QueryPerformanceFrequency fails.
00065         static inline uint64 GetPerformanceFrequency()
00066         {
00067             LARGE_INTEGER freq;
00068             if (!QueryPerformanceFrequency(&freq))
00069             {
00070                 throw ref new Platform::FailureException();
00071             }
00072             return freq.QuadPart;
00073         }
00074
00075         // Gets the current number of ticks from QueryPerformanceCounter. Throws an
00076         // exception if the call to QueryPerformanceCounter fails.
00077         static inline int64 GetTicks()
00078         {
00079             LARGE_INTEGER ticks;
00080             if (!QueryPerformanceCounter(&ticks))
00081             {
00082                 throw ref new Platform::FailureException();
00083             }
00084             return ticks.QuadPart;
00085         }
00086
00087         // After an intentional timing discontinuity (for instance a blocking IO operation)
00088         // call this to avoid having the fixed timestep logic attempt a set of catch-up
00089         // Update calls.
00090
00091         void ResetElapsedTime()
00092         {
00093             m_qpcLastTime = GetTicks();
00094
00095             m_leftOverTicks    = 0;
00096             m_framesPerSecond  = 0;
00097             m_framesThisSecond = 0;
00098             m_qpcSecondCounter = 0;
00099         }
00100
00101         // Update timer state, calling the specified Update function the appropriate number of times.
00102         template<typename TUpdate>
00103         void Tick(const TUpdate& update)
00104         {
00105             // Query the current time.
00106             uint64 currentTime = GetTicks();
00107             uint64 timeDelta   = currentTime - m_qpcLastTime;
00108
00109             m_qpcLastTime      = currentTime;
00110             m_qpcSecondCounter += timeDelta;
00111
00112             // Clamp excessively large time deltas (e.g. after paused in the debugger).
00113             if (timeDelta > m_qpcMaxDelta)
00114             {
00115                 timeDelta = m_qpcMaxDelta;
00116             }
00117
00118             // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp.
00119             timeDelta *= TicksPerSecond;
00120             timeDelta /= m_qpcFrequency;
00121
00122             uint32 lastFrameCount = m_frameCount;
00123
00124             if (m_isFixedTimeStep)
00125             {
00126                 // Fixed timestep update logic
00127
00128                 // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp
00129                 // the clock to exactly match the target value. This prevents tiny and irrelevant errors
00130                 // from accumulating over time. Without this clamping, a game that requested a 60 fps
00131                 // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually
00132                 // accumulate enough tiny errors that it would drop a frame. It is better to just round
00133                 // small deviations down to zero to leave things running smoothly.
00134
00135                 if (abs(static_cast<int64>(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000)
00136                 {
00137                     timeDelta = m_targetElapsedTicks;
00138                 }
00139
00140                 m_leftOverTicks += timeDelta;
00141
00142                 while (m_leftOverTicks >= m_targetElapsedTicks)
00143                 {
00144                     m_elapsedTicks   = m_targetElapsedTicks;
00145                     m_totalTicks    += m_targetElapsedTicks;
00146                     m_leftOverTicks -= m_targetElapsedTicks;
00147                     m_frameCount++;
00148
00149                     update();
00150                 }
00151             }
00152             else
00153             {
00154                 // Variable timestep update logic.
00155                 m_elapsedTicks  = timeDelta;
00156                 m_totalTicks   += timeDelta;
00157                 m_leftOverTicks = 0;
00158                 m_frameCount++;
00159
00160                 update();
00161             }
00162
00163             // Track the current framerate.
00164             if (m_frameCount != lastFrameCount)
00165             {
00166                 m_framesThisSecond++;
00167             }
00168
00169             if (m_qpcSecondCounter >= static_cast<uint64>(m_qpcFrequency))
00170             {
00171                 m_framesPerSecond   = m_framesThisSecond;
00172                 m_framesThisSecond  = 0;
00173                 m_qpcSecondCounter %= m_qpcFrequency;
00174             }
00175         }
00176
00177     private:
00178
00179         // Source timing data uses QPC units.
00180         uint64 m_qpcFrequency;
00181         uint64 m_qpcLastTime;
00182         uint64 m_qpcMaxDelta;
00183
00184         // Derived timing data uses a canonical tick format.
00185         uint64 m_elapsedTicks;
00186         uint64 m_totalTicks;
00187         uint64 m_leftOverTicks;
00188
00189         // Members for tracking the framerate.
00190         uint32 m_frameCount;
00191         uint32 m_framesPerSecond;
00192         uint32 m_framesThisSecond;
00193         uint64 m_qpcSecondCounter;
00194
00195         // Members for configuring fixed timestep mode.
00196         bool   m_isFixedTimeStep;
00197         uint64 m_targetElapsedTicks;
00198     };
00199 }
Generated on Fri Nov 15 2024 22:16:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlWebView/cs/Scenario1_NavToUrl.xaml.cs Source File

  • XamlWebView
  • cs

Scenario1_NavToUrl.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.UI.Xaml;
00014 using Windows.UI.Xaml.Controls;
00015 using Windows.UI.Xaml.Documents;
00016 using Windows.UI.Xaml.Input;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed partial class Scenario1_NavToUrl : Page
00021     {
00022         public Scenario1_NavToUrl()
00023         {
00024             this.InitializeComponent();
00025         }
00026
00027         static string UriToString(Uri uri)
00028         {
00029             return (uri != null) ? uri.ToString() : "";
00030         }
00031
00032         /// <summary>
00033         /// This is the click handler for the "Go" button.
00034         /// </summary>
00035         /// <param name="sender"></param>
00036         /// <param name="e"></param>
00037         private void GoButton_Click()
00038         {
00039             if (!pageIsLoading)
00040             {
00041                 NavigateWebview(AddressBox.Text);
00042             }
00043             else
00044             {
00045                 WebViewControl.Stop();
00046                 pageIsLoading = false;
00047             }
00048         }
00049
00050         /// <summary>
00051         /// Property to control the "Go" button text, forward/backward buttons and progress ring.
00052         /// </summary>
00053         private bool _pageIsLoading;
00054         bool pageIsLoading
00055         {
00056             get { return _pageIsLoading; }
00057             set
00058             {
00059                 _pageIsLoading = value;
00060                 GoButton.Content = (value ? "Stop" : "Go");
00061                 ProgressControl.IsActive = value;
00062
00063                 if (!value)
00064                 {
00065                     NavigateBackButton.IsEnabled = WebViewControl.CanGoBack;
00066                     NavigateForwardButton.IsEnabled = WebViewControl.CanGoForward;
00067                 }
00068             }
00069         }
00070
00071         /// <summary>
00072         /// Handler for the NavigateBackward button
00073         /// </summary>
00074         /// <param name="sender"></param>
00075         /// <param name="e"></param>
00076         private void NavigateBackward_Click()
00077         {
00078             if (WebViewControl.CanGoBack) WebViewControl.GoBack();
00079         }
00080
00081         /// <summary>
00082         /// Handler for the GoForward button
00083         /// </summary>
00084         /// <param name="sender"></param>
00085         /// <param name="e"></param>
00086         private void NavigateForward_Click()
00087         {
00088             if (WebViewControl.CanGoForward) WebViewControl.GoForward();
00089         }
00090
00091         /// <summary>
00092         /// This handles the enter key in the url address box
00093         /// </summary>
00094         /// <param name="sender"></param>
00095         /// <param name="e"></param>
00096         void Address_KeyUp(object sender, KeyRoutedEventArgs e)
00097         {
00098             if (e.Key == Windows.System.VirtualKey.Enter)
00099             {
00100                 NavigateWebview(AddressBox.Text);
00101             }
00102         }
00103
00104         /// <summary>
00105         /// Helper to perform the navigation in webview
00106         /// </summary>
00107         /// <param name="url"></param>
00108         private void NavigateWebview(string url)
00109         {
00110             try
00111             {
00112                 Uri targetUri = new Uri(url);
00113                 WebViewControl.Navigate(targetUri);
00114             }
00115             catch (UriFormatException ex)
00116             {
00117                 // Bad address
00118                 AppendLog($"Address is invalid, try again. Error: {ex.Message}.");
00119             }
00120         }
00121
00122         /// <summary>
00123         /// Handle the event that indicates that WebView is starting a navigation.
00124         /// </summary>
00125         /// <param name="sender"></param>
00126         /// <param name="args"></param>
00127         void WebViewControl_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
00128         {
00129             string url = UriToString(args.Uri);
00130             AddressBox.Text = url;
00131             AppendLog($"Starting navigation to: \"{url}\".");
00132             pageIsLoading = true;
00133         }
00134
00135         /// <summary>
00136         /// Handle the event that indicates that the WebView content is not a web page.
00137         /// For example, it may be a file download.
00138         /// </summary>
00139         /// <param name="sender"></param>
00140         /// <param name="args"></param>
00141         void WebViewControl_UnviewableContentIdentified(WebView sender, WebViewUnviewableContentIdentifiedEventArgs args)
00142         {
00143             AppendLog($"Content for \"{UriToString(args.Uri)}\" cannot be loaded into webview.");
00144             // We throw away the request. See the "Unviewable content" scenario for other
00145             // ways of handling the event.
00146             pageIsLoading = false;
00147         }
00148
00149         /// <summary>
00150         /// Handle the event that indicates that WebView has resolved the URI, and that it is loading HTML content.
00151         /// </summary>
00152         /// <param name="sender"></param>
00153         /// <param name="args"></param>
00154         void WebViewControl_ContentLoading(WebView sender, WebViewContentLoadingEventArgs args)
00155         {
00156             AppendLog($"Loading content for \"{UriToString(args.Uri)}\".");
00157         }
00158
00159
00160         /// <summary>
00161         /// Handle the event that indicates that the WebView content is fully loaded.
00162         /// If you need to invoke script, it is best to wait for this event.
00163         /// </summary>
00164         /// <param name="sender"></param>
00165         /// <param name="args"></param>
00166         void WebViewControl_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
00167         {
00168             AppendLog($"Content for \"{UriToString(args.Uri)}\" has finished loading.");
00169         }
00170
00171         /// <summary>
00172         /// Event to indicate webview has completed the navigation, either with success or failure.
00173         /// </summary>
00174         /// <param name="sender"></param>
00175         /// <param name="args"></param>
00176         void WebViewControl_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
00177         {
00178             pageIsLoading = false;
00179             if (args.IsSuccess)
00180             {
00181                 AppendLog($"Navigation to \"{UriToString(args.Uri)}\" completed successfully.");
00182             }
00183             else
00184             {
00185                 AppendLog($"Navigation to: \"{UriToString(args.Uri)}\" failed with error {args.WebErrorStatus}.");
00186             }
00187         }
00188
00189         /// <summary>
00190         /// Helper for logging
00191         /// </summary>
00192         /// <param name="logEntry"></param>
00193         void AppendLog(string logEntry)
00194         {
00195             logResults.Inlines.Add(new Run { Text = logEntry + "\n" });
00196             logScroller.ChangeView(0, logScroller.ScrollableHeight, null);
00197         }
00198     }
00199 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_NavToString Member List

This is the complete list of members for Scenario2_NavToString, including all inherited members.
LoadAsHtml() | Scenario2_NavToString | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario2_NavToString | [inline, protected]
Scenario2_NavToString() | Scenario2_NavToString | [inline]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlPivot/cs/MainPage.xaml.cs Source File

  • XamlPivot
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml;
00015 using Windows.UI.Xaml.Controls;
00016 using Windows.UI.Xaml.Data;
00017 using Windows.UI.Xaml.Media;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00021
00022 namespace SDKTemplate
00023 {
00024     /// <summary>
00025     /// An empty page that can be used on its own or navigated to within a Frame.
00026     /// </summary>
00027     public sealed partial class MainPage : Page
00028     {
00029         public static MainPage Current;
00030
00031         public MainPage()
00032         {
00033             this.InitializeComponent();
00034
00035             // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00036             // in order to call methods that are in this class.
00037             Current = this;
00038             SampleTitle.Text = FEATURE_NAME;
00039         }
00040
00041         protected override void OnNavigatedTo(NavigationEventArgs e)
00042         {
00043             // Populate the scenario list from the SampleConfiguration.cs file
00044             ScenarioControl.ItemsSource = scenarios;
00045             ScenarioControl.SelectedIndex = 0;
00046         }
00047
00048         /// <summary>
00049         /// Called whenever the user changes selection in the scenarios list.  This method will navigate to the respective
00050         /// sample scenario page.
00051         /// </summary>
00052         /// <param name="sender"></param>
00053         /// <param name="e"></param>
00054         private void ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
00055         {
00056             // Clear the status block when navigating scenarios.
00057             NotifyUser(String.Empty, NotifyType.StatusMessage);
00058
00059             ListView scenarioListBox = sender as ListView;
00060             Scenario s = scenarioListBox.SelectedItem as Scenario;
00061             if (s != null)
00062             {
00063                 ScenarioFrame.Navigate(s.ClassType);
00064                 if (Window.Current.Bounds.Width < 640)
00065                 {
00066                     Splitter.IsPaneOpen = false;
00067                     StatusBorder.Visibility = Visibility.Collapsed;
00068                 }
00069             }
00070         }
00071
00072         public List<Scenario> Scenarios
00073         {
00074             get { return this.scenarios; }
00075         }
00076
00077         /// <summary>
00078         /// Used to display messages to the user
00079         /// </summary>
00080         /// <param name="strMessage"></param>
00081         /// <param name="type"></param>
00082         public void NotifyUser(string strMessage, NotifyType type)
00083         {
00084             switch (type)
00085             {
00086                 case NotifyType.StatusMessage:
00087                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green);
00088                     break;
00089                 case NotifyType.ErrorMessage:
00090                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red);
00091                     break;
00092             }
00093             StatusBlock.Text = strMessage;
00094
00095             // Collapse the StatusBlock if it has no text to conserve real estate.
00096             StatusPanel.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed;
00097         }
00098
00099         async void Footer_Click(object sender, RoutedEventArgs e)
00100         {
00101             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00102         }
00103
00104         private void Button_Click(object sender, RoutedEventArgs e)
00105         {
00106             Splitter.IsPaneOpen = (Splitter.IsPaneOpen == true) ? false : true;
00107             StatusBorder.Visibility = Visibility.Collapsed;
00108         }
00109     }
00110     public enum NotifyType
00111     {
00112         StatusMessage,
00113         ErrorMessage
00114     };
00115
00116     public class ScenarioBindingConverter : IValueConverter
00117     {
00118         public object Convert(object value, Type targetType, object parameter, string language)
00119         {
00120             Scenario s = value as Scenario;
00121             return (MainPage.Current.Scenarios.IndexOf(s) + 1) + ") " + s.Title;
00122         }
00123
00124         public object ConvertBack(object value, Type targetType, object parameter, string language)
00125         {
00126             return true;
00127         }
00128     }
00129 }
00130
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AudioCategory/cs/AudioCategory/PlaybackControl.xaml.cs Source File

  • AudioCategory
  • cs
  • AudioCategory

PlaybackControl.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using SDKTemplate;
00015 using System;
00016 using Windows.UI.Xaml.Media;
00017 using Windows.UI.Core;
00018 using Windows.Foundation;
00019 using Windows.Media;
00020
00021 namespace PlaybackManager
00022 {
00023     /// <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026     public sealed partial class PlaybackControl
00027     {
00028         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00029         // as NotifyUser()
00030         MainPage rootPage = MainPage.Current;
00031
00032         CoreWindow cw = Window.Current.CoreWindow;
00033         bool IsPlaying = false;
00034
00035         SystemMediaTransportControls systemMediaControls = null;
00036
00037         public PlaybackControl()
00038         {
00039             this.InitializeComponent();
00040
00041             // add new handlers
00042             systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
00043             systemMediaControls.PropertyChanged += SystemMediaControls_PropertyChanged;
00044             systemMediaControls.ButtonPressed += SystemMediaControls_ButtonPressed;
00045             systemMediaControls.IsPlayEnabled = true;
00046             systemMediaControls.IsPauseEnabled = true;
00047             systemMediaControls.IsStopEnabled = true;
00048             systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Closed;
00049         }
00050
00051         ~PlaybackControl()
00052         {
00053             if (systemMediaControls != null)
00054             {
00055                 systemMediaControls.PropertyChanged -= SystemMediaControls_PropertyChanged;
00056                 systemMediaControls.ButtonPressed -= SystemMediaControls_ButtonPressed;
00057             }
00058         }
00059
00060         async public void Play()
00061         {
00062             await cw.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00063             {
00064                 OutputMedia.Play();
00065                 systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Playing;
00066             });
00067         }
00068
00069         async public void Pause()
00070         {
00071             await cw.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00072             {
00073                 OutputMedia.Pause();
00074                 systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Paused;
00075             });
00076         }
00077
00078         async public void Stop()
00079         {
00080             await cw.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00081             {
00082                 OutputMedia.Stop();
00083                 systemMediaControls.PlaybackStatus = MediaPlaybackStatus.Stopped;
00084             });
00085         }
00086
00087         public void SetAudioCategory(AudioCategory category)
00088         {
00089             OutputMedia.AudioCategory = category;
00090         }
00091
00092         public void SetAudioDeviceType(AudioDeviceType devicetype)
00093         {
00094             OutputMedia.AudioDeviceType = devicetype;
00095         }
00096
00097         public async void SelectFile()
00098         {
00099             Windows.Storage.Pickers.FileOpenPicker picker = new Windows.Storage.Pickers.FileOpenPicker();
00100             picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
00101             picker.FileTypeFilter.Add(".mp3");
00102             picker.FileTypeFilter.Add(".mp4");
00103             picker.FileTypeFilter.Add(".m4a");
00104             picker.FileTypeFilter.Add(".wma");
00105             picker.FileTypeFilter.Add(".wav");
00106             Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
00107             if (file != null)
00108             {
00109                 var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
00110                 OutputMedia.AutoPlay = false;
00111                 await cw.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00112                 {
00113                     OutputMedia.SetSource(stream, file.ContentType);
00114                 });
00115             }
00116         }
00117
00118         async void DisplayStatus(string text)
00119         {
00120             await cw.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00121             {
00122                 Status.Text += text + "\n";
00123             });
00124         }
00125
00126         string GetTimeStampedMessage(string eventText)
00127         {
00128             return eventText + "   " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString();
00129         }
00130
00131         //If your app is playing media you feel that a user should not miss if a VOIP call comes in, you may
00132         //want to consider pausing playback when your app receives a SoundLevel(Low) notification.
00133         //A SoundLevel(Low) means your app volume has been attenuated by the system (likely for a VOIP call).
00134
00135         string SoundLevelToString(SoundLevel level)
00136         {
00137             string LevelString;
00138
00139             switch (level)
00140             {
00141                 case SoundLevel.Muted:
00142                     LevelString = "Muted";
00143                     break;
00144                 case SoundLevel.Low:
00145                     LevelString = "Low";
00146                     break;
00147                 case SoundLevel.Full:
00148                     LevelString = "Full";
00149                     break;
00150                 default:
00151                     LevelString = "Unknown";
00152                     break;
00153             }
00154             return LevelString;
00155         }
00156
00157         async void AppMuted()
00158         {
00159             await cw.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00160             {
00161                 if (OutputMedia.CurrentState != MediaElementState.Paused)
00162                 {
00163                     IsPlaying = true;
00164                     Pause();
00165                 }
00166                 else
00167                 {
00168                     IsPlaying = false;
00169                 }
00170             });
00171             DisplayStatus(GetTimeStampedMessage("Muted"));
00172         }
00173
00174         async void AppUnmuted()
00175         {
00176             await cw.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00177             {
00178                 if (IsPlaying)
00179                 {
00180                     Play();
00181                 }
00182             });
00183             DisplayStatus(GetTimeStampedMessage("Unmuted"));
00184         }
00185
00186         void SystemMediaControls_PropertyChanged(SystemMediaTransportControls sender, SystemMediaTransportControlsPropertyChangedEventArgs e)
00187         {
00188             if (e.Property == SystemMediaTransportControlsProperty.SoundLevel)
00189             {
00190                 var soundLevelState = sender.SoundLevel;
00191
00192                 DisplayStatus(GetTimeStampedMessage("App sound level is [" + SoundLevelToString(soundLevelState) + "]"));
00193                 if (soundLevelState == SoundLevel.Muted)
00194                 {
00195                     AppMuted();
00196                 }
00197                 else
00198                 {
00199                     AppUnmuted();
00200                 }
00201             }
00202         }
00203
00204         void SystemMediaControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs e)
00205         {
00206             switch (e.Button)
00207             {
00208                 case SystemMediaTransportControlsButton.Play:
00209                     Play();
00210                     DisplayStatus(GetTimeStampedMessage("Play Pressed"));
00211                     break;
00212
00213                 case SystemMediaTransportControlsButton.Pause:
00214                     Pause();
00215                     DisplayStatus(GetTimeStampedMessage("Pause Pressed"));
00216                     break;
00217
00218                 case SystemMediaTransportControlsButton.Stop:
00219                     Stop();
00220                     DisplayStatus(GetTimeStampedMessage("Stop Pressed"));
00221                     break;
00222
00223                 default:
00224                     break;
00225             }
00226         }
00227
00228         private void Button_Play_Click(object sender, RoutedEventArgs e)
00229         {
00230             Play();
00231         }
00232
00233         private void Button_Pause_Click(object sender, RoutedEventArgs e)
00234         {
00235             Pause();
00236         }
00237
00238         private void Button_Stop_Click(object sender, RoutedEventArgs e)
00239         {
00240             Stop();
00241         }
00242     }
00243 }
Generated on Fri Nov 15 2024 22:18:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

SpatialInputHandler Member List

This is the complete list of members for SpatialInputHandler, including all inherited members.
CheckForInput() | SpatialInputHandler |
CheckForInput() | SpatialInputHandler |
m_interactionManager | SpatialInputHandler | [private]
m_interactionManager | SpatialInputHandler | [private]
m_sourcePressedEventToken | SpatialInputHandler | [private]
m_sourcePressedEventToken | SpatialInputHandler | [private]
m_sourceState | SpatialInputHandler | [private]
m_sourceState | SpatialInputHandler | [private]
OnSourcePressed(Windows::UI::Input::Spatial::SpatialInteractionManager^sender, Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs^args) | SpatialInputHandler | [private]
OnSourcePressed(winrt::Windows::UI::Input::Spatial::SpatialInteractionManager const &sender, winrt::Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs const &args) | SpatialInputHandler | [private]
SpatialInputHandler() | SpatialInputHandler |
SpatialInputHandler() | SpatialInputHandler |
~SpatialInputHandler() | SpatialInputHandler |
~SpatialInputHandler() | SpatialInputHandler |
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario5.xaml.cpp Source File

  • MapControl
  • cpp

Scenario5.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario5.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Devices::Geolocation;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Maps;
00023
00024 Scenario5::Scenario5()
00025 {
00026     InitializeComponent();
00027 }
00028
00029 void Scenario5::showStreetSideNearSpaceneedle_Click(Object^ sender, RoutedEventArgs^ e)
00030 {
00031     if (myMap->IsStreetsideSupported)
00032     {
00033         Geopoint^ spaceNeedlePoint = ref new Geopoint({ 47.6204, -122.3491 });
00034
00035         concurrency::create_task(StreetsidePanorama::FindNearbyAsync(spaceNeedlePoint)).then([this](StreetsidePanorama^ panoramaNearSpaceNeedle)
00036         {
00037             if (panoramaNearSpaceNeedle != nullptr)
00038             {
00039                 myMap->CustomExperience = ref new StreetsideExperience(panoramaNearSpaceNeedle);
00040             }
00041         });
00042     }
00043     else
00044     {
00045         rootPage->NotifyUser(L"Streetside views are not supported on this device.", NotifyType::ErrorMessage);
00046     }
00047 }
00048
00049 void Scenario5::myMap_Loaded(Object^ sender, RoutedEventArgs^ e)
00050 {
00051     myMap->Center = MainPage::SeattleGeopoint;
00052     myMap->ZoomLevel = 12;
00053 }
Generated on Fri Nov 15 2024 22:18:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/StereoProjection.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

StereoProjection.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "StereoProjection.h"
00014
00015 #if !defined(XMASSERT)
00016 #define XMASSERT(Expression) ((void)0)
00017 #endif // !XMASSERT
00018
00019 using namespace DirectX;
00020
00021 void StereoCreateDefaultParameters(_Out_ STEREO_PARAMETERS* stereoParameters)
00022 {
00023     XMASSERT(stereoParameters != nullptr);
00024
00025     // Default assumption is 1920x1200 resolution, a 22" LCD monitor, and a 2' viewing distance
00026     stereoParameters->viewerDistanceInches = 24.0f;
00027     stereoParameters->pixelResolutionWidth = 1920.0f;
00028     stereoParameters->pixelResolutionHeight = 1024.0f; // 480.0f; // 1200
00029     stereoParameters->displaySizeInches = 22.0f;
00030
00031     stereoParameters->stereoSeparationFactor = 1.0f;
00032     stereoParameters->stereoExaggerationFactor = 1.0f;
00033 }
00034
00035 __forceinline bool _XMMatrixStereoProjectionHelper(
00036     const STEREO_PARAMETERS* stereoParameters,
00037     _Out_ float* virtualProjection,
00038     _Out_ float* zNearWidth,
00039     _Out_ float* zNearHeight,
00040     float fovAngleY,
00041     float aspectHByW,
00042     float nearZ
00043     )
00044 {
00045     // note that most people have difficulty fusing images into 3D
00046     // if the separation equals even just the human average. by
00047     // reducing the separation (interocular distance) by 1/2, we
00048     // guarantee a larger subset of people will see full 3D
00049
00050     // the conservative setting should always be used. the only problem
00051     // with the conservative setting is that the 3D effect will be less
00052     // impressive on smaller screens (which makes sense, since your eye
00053     // cannot be tricked as easily based on the smaller fov). to simulate
00054     // the effect of a larger screen, use the liberal settings (debug only)
00055
00056     // Conservative Settings: * max acuity angle: 0.8f degrees * interoc distance: 1.25 inches
00057
00058     // Liberal Settings: * max acuity angle: 1.6f degrees * interoc distance: 2.5f inches
00059
00060     // maximum visual accuity angle allowed is 3.2 degrees for
00061     // a physical scene, and 1.6 degrees for a virtual one.
00062     // thus we cannot allow an object to appear any closer to
00063     // the viewer than 1.6 degrees (divided by two for most
00064     // half-angle calculations)
00065
00066     static const float maxStereoDistance = 85; // 780 inches (should be between 10 and 20m)
00067     static const float maxVisualAcuityAngle = 0.8f * (XM_PI / 180.0f);  // radians
00068     static const float interocularDistance = 1.25f; // inches
00069
00070     bool comfortableResult = true;
00071
00072     float displayHeight = stereoParameters->displaySizeInches / sqrtf(aspectHByW * aspectHByW + 1.0f);
00073     float displayWidth = displayHeight * aspectHByW;
00074     float halfInterocular = 0.5f * interocularDistance * stereoParameters->stereoExaggerationFactor;
00075     float halfPixelWidth = displayWidth / stereoParameters->pixelResolutionWidth * 0.5f;
00076     float halfMaximumAcuityAngle = maxVisualAcuityAngle * 0.5f * stereoParameters->stereoExaggerationFactor;
00077
00078     float maxSeparationAcuityAngle = atanf(halfInterocular / maxStereoDistance);
00079     float maxSeparationDistance = halfPixelWidth / tanf(maxSeparationAcuityAngle);
00080     float refinedMaxStereoDistance = maxStereoDistance - maxSeparationDistance;
00081     float fovHalfAngle = fovAngleY / 2.0f;
00082
00083     if (refinedMaxStereoDistance < 0.0f || maxSeparationDistance > 0.1f * maxStereoDistance)
00084     {
00085         // Pixel resolution is too low to offer a comfortable stereo experience
00086         comfortableResult = false;
00087     }
00088
00089     float refinedMaxSeparationAcuityAngle = atanf(halfInterocular / refinedMaxStereoDistance);
00090     float physicalZNearDistance = halfInterocular / tanf(halfMaximumAcuityAngle);
00091
00092     float nearZSeparation = tanf(refinedMaxSeparationAcuityAngle) * (refinedMaxStereoDistance - physicalZNearDistance);
00093
00094     *zNearHeight = cosf(fovHalfAngle) / sinf(fovHalfAngle);
00095     *zNearWidth = *zNearHeight / aspectHByW;
00096     *virtualProjection = (nearZSeparation * nearZ * (*zNearWidth * 4.0f)) / (2.0f * nearZ);
00097
00098     return comfortableResult;
00099 }
00100
00101
00102 XMMATRIX MatrixStereoProjectionFovLH(
00103     _In_opt_ const STEREO_PARAMETERS* stereoParameters,
00104     STEREO_CHANNEL channel,
00105     float fovAngleY,
00106     float aspectHByW,
00107     float nearZ,
00108     float farZ,
00109     STEREO_MODE stereoMode
00110     )
00111 {
00112     float virtualProjection = 0.0f;
00113     float zNearWidth = 0.0f;
00114     float zNearHeight = 0.0f;
00115     float invertedAngle;
00116     XMMATRIX patchedProjection;
00117     XMMATRIX proj;
00118     STEREO_PARAMETERS defaultParameters;
00119
00120     XMASSERT(channel == STEREO_CHANNEL::LEFT || channel == STEREO_CHANNEL::RIGHT);
00121     XMASSERT(stereoMode == STEREO_MODE::NORMAL || stereoMode == STEREO_MODE::INVERTED);
00122     XMASSERT(!XMScalarNearEqual(fovAngleY, 0.0f, 0.00001f * 2.0f));
00123     XMASSERT(!XMScalarNearEqual(aspectHByW, 0.0f, 0.00001f));
00124     XMASSERT(!XMScalarNearEqual(farZ, nearZ, 0.00001f));
00125
00126     proj = XMMatrixIdentity();
00127
00128     if (stereoParameters == nullptr)
00129     {
00130         StereoCreateDefaultParameters(&defaultParameters);
00131         stereoParameters = &defaultParameters;
00132     }
00133
00134     XMASSERT(pStereoParameters->stereoSeparationFactor >= 0.0f && stereoParameters->stereoSeparationFactor <= 1.0f);
00135     XMASSERT(pStereoParameters->stereoExaggerationFactor >= 1.0f && stereoParameters->stereoExaggerationFactor <= 2.0f);
00136
00137     _XMMatrixStereoProjectionHelper(stereoParameters, &virtualProjection, &zNearWidth, &zNearHeight, fovAngleY, aspectHByW, nearZ);
00138
00139     virtualProjection *= stereoParameters->stereoSeparationFactor; // incorporate developer defined bias
00140
00141     //
00142     // By applying a translation, we are forcing our cameras to be parallel
00143     //
00144
00145     invertedAngle = atanf(virtualProjection / (2.0f * nearZ));
00146
00147     proj = XMMatrixPerspectiveFovLH(fovAngleY, aspectHByW, nearZ, farZ);
00148
00149     if (channel == STEREO_CHANNEL::LEFT)
00150     {
00151         if (stereoMode > STEREO_MODE::NORMAL)
00152         {
00153             XMMATRIX rots, trans;
00154             rots = XMMatrixRotationY(invertedAngle);
00155             trans = XMMatrixTranslation(-virtualProjection, 0, 0);
00156             patchedProjection = XMMatrixMultiply(XMMatrixMultiply(rots, trans), proj);
00157         }
00158         else
00159         {
00160             XMMATRIX trans;
00161             trans = XMMatrixTranslation(-virtualProjection, 0, 0);
00162             patchedProjection = XMMatrixMultiply(trans, proj);
00163         }
00164     }
00165     else
00166     {
00167         if (stereoMode > STEREO_MODE::NORMAL)
00168         {
00169             XMMATRIX rots, trans;
00170             rots = XMMatrixRotationY(-invertedAngle);
00171             trans = XMMatrixTranslation(virtualProjection, 0, 0);
00172             patchedProjection = XMMatrixMultiply(XMMatrixMultiply(rots, trans), proj);
00173         }
00174         else
00175         {
00176             XMMATRIX trans;
00177             trans = XMMatrixTranslation(virtualProjection, 0, 0);
00178             patchedProjection = XMMatrixMultiply(trans, proj);
00179         }
00180     }
00181
00182     return patchedProjection;
00183 }
00184
Generated on Fri Nov 15 2024 22:21:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpeechRecognitionAndSynthesis/cs/AudioCapturePermissions.cs Source File

  • SpeechRecognitionAndSynthesis
  • cs

AudioCapturePermissions.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Media.Capture;
00015
00016 namespace SDKTemplate
00017 {
00018     public class AudioCapturePermissions
00019     {
00020         // If no recording device is attached, attempting to get access to audio capture devices will throw
00021         // a System.Exception object, with this HResult set.
00022         private static int NoCaptureDevicesHResult = -1072845856;
00023
00024         /// <summary>
00025         /// On desktop/tablet systems, users are prompted to give permission to use capture devices on a
00026         /// per-app basis. Along with declaring the microphone DeviceCapability in the package manifest,
00027         /// this method tests the privacy setting for microphone access for this application.
00028         /// Note that this only checks the Settings->Privacy->Microphone setting, it does not handle
00029         /// the Cortana/Dictation privacy check, however (Under Settings->Privacy->Speech, Inking and Typing).
00030         ///
00031         /// Developers should ideally perform a check like this every time their app gains focus, in order to
00032         /// check if the user has changed the setting while the app was suspended or not in focus.
00033         /// </summary>
00034         /// <returns>true if the microphone can be accessed without any permissions problems.</returns>
00035         public async static Task<bool> RequestMicrophonePermission()
00036         {
00037             try
00038             {
00039                 // Request access to the microphone only, to limit the number of capabilities we need
00040                 // to request in the package manifest.
00041                 MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();
00042                 settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
00043                 settings.MediaCategory = MediaCategory.Speech;
00044                 MediaCapture capture = new MediaCapture();
00045
00046                 await capture.InitializeAsync(settings);
00047             }
00048             catch (TypeLoadException)
00049             {
00050                 // On SKUs without media player (eg, the N SKUs), we may not have access to the Windows.Media.Capture
00051                 // namespace unless the media player pack is installed. Handle this gracefully.
00052                 var messageDialog = new Windows.UI.Popups.MessageDialog("Media player components are unavailable.");
00053                 await messageDialog.ShowAsync();
00054                 return false;
00055             }
00056             catch (UnauthorizedAccessException)
00057             {
00058                 // The user has turned off access to the microphone. If this occurs, we should show an error, or disable
00059                 // functionality within the app to ensure that further exceptions aren't generated when
00060                 // recognition is attempted.
00061                 return false;
00062             }
00063             catch (Exception exception)
00064             {
00065                 // This can be replicated by using remote desktop to a system, but not redirecting the microphone input.
00066                 // Can also occur if using the virtual machine console tool to access a VM instead of using remote desktop.
00067                 if (exception.HResult == NoCaptureDevicesHResult)
00068                 {
00069                     var messageDialog = new Windows.UI.Popups.MessageDialog("No Audio Capture devices are present on this system.");
00070                     await messageDialog.ShowAsync();
00071                     return false;
00072                 }
00073                 else
00074                 {
00075                     throw;
00076                 }
00077             }
00078             return true;
00079         }
00080     }
00081 }
Generated on Fri Nov 15 2024 22:21:40 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/Util/ViewLifetimeControl.cs Source File

  • AdvancedCasting
  • cs
  • Util

ViewLifetimeControl.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 // The objects defined here demonstrate how to make sure each of the views created remains alive as long as
00013 // the app needs them, but only when they're being used by the app or the user. Many of the scenarios contained in this
00014 // sample use these functions to keep track of the views available and ensure that the view is not closed while
00015 // the scenario is attempting to show it.
00016 //
00017 // As you can see in scenario 1, the ApplicationViewSwitcher.TryShowAsStandaloneAsync and
00018 // ProjectionManager.StartProjectingAsync methods let you show one view next to another. The Consolidated event
00019 // is fired when a view stops being visible separately from other views. Common cases where this will occur
00020 // is when the view falls out of the list of recently used apps, or when the user performs the close gesture on the view.
00021 // This is a good time to close the view, provided the app isn't trying to show the view at the same time. This event
00022 // is fired on the thread of the view that becomes consolidated.
00023 //
00024 // Each view lives on its own thread, so concurrency control is necessary. Also, as you'll see in the sample,
00025 // certain objects may be bound to UI on given threads. Properties of those objects should only be updated
00026 // on that UI thread.
00027
00028 using System;
00029 using System.ComponentModel;
00030 using Windows.UI.Core;
00031 using Windows.UI.ViewManagement;
00032
00033 namespace ScreenCasting.Util
00034 {
00035     // A custom event that fires whenever the secondary view is ready to be closed. You should
00036     // clean up any state (including deregistering for events) then close the window in this handler
00037     public delegate void ViewReleasedHandler(Object sender, EventArgs e);
00038
00039     // A ViewLifetimeControl is instantiated for every secondary view. ViewLifetimeControl's reference count
00040     // keeps track of when the secondary view thinks it's in usem and when the main view is interacting with the secondary view (about to show
00041     // it to the user, etc.) When the reference count drops to zero, the secondary view is closed.
00042     public sealed class ViewLifetimeControl : INotifyPropertyChanged
00043     {
00044         // Dispatcher for this view. Kept here for sending messages between this view and the main view.
00045         CoreDispatcher dispatcher;
00046
00047         // Window for this particular view. Used to register and unregister for events
00048         CoreWindow window;
00049
00050         // The title for the view shown in the list of recently used apps (by setting the title on
00051         // ApplicationView)
00052         string title;
00053
00054         // This class uses references counts to make sure the secondary views isn't closed prematurely.
00055         // Whenever the main view is about to interact with the secondary view, it should take a reference
00056         // by calling "StartViewInUse" on this object. When finished interacting, it should release the reference
00057         // by calling "StopViewInUse". You can see examples of this throughout the sample, especially in
00058         // scenario 1.
00059         int refCount = 0;
00060
00061         // Each view has a unique Id, found using the ApplicationView.Id property or
00062         // ApplicationView.GetApplicationViewIdForCoreWindow method. This id is used in all of the ApplicationViewSwitcher
00063         // and ProjectionManager APIs.
00064         int viewId;
00065
00066         // Tracks if this ViewLifetimeControl object is still valid. If this is true, then the view is in the process
00067         // of closing itself down
00068         bool released = false;
00069
00070         // Keeps track of if the consolidated event has fired yet. A view is consolidated with other views
00071         // when there's no way for the user to get to it (it's not in the list of recently used apps, cannot be
00072         // launched from Start, etc.) A view stops being consolidated when it's visible--at that point
00073         // the user can interact with it, move it on or off screen, etc.
00074         bool consolidated = true;
00075
00076         // Used to store pubicly registered events under the protection of a lock
00077         event ViewReleasedHandler InternalReleased;
00078
00079         // Instantiate views using "CreateForCurrentView"
00080         private ViewLifetimeControl(CoreWindow newWindow)
00081         {
00082             dispatcher = newWindow.Dispatcher;
00083             window = newWindow;
00084             viewId = ApplicationView.GetApplicationViewIdForWindow(window);
00085
00086             // This class will automatically tell the view when its time to close
00087             // or stay alive in a few cases
00088             RegisterForEvents();
00089         }
00090
00091         // Register for events on the current view
00092         private void RegisterForEvents()
00093         {
00094             // A view is consolidated with other views hen there's no way for the user to get to it (it's not in the list of recently used apps, cannot be
00095             // launched from Start, etc.) A view stops being consolidated when it's visible--at that point the user can interact with it, move it on or off screen, etc.
00096             // It's generally a good idea to close a view after it has been consolidated, but keep it open while it's visible.
00097             ApplicationView.GetForCurrentView().Consolidated += ViewConsolidated;
00098             window.VisibilityChanged += VisibilityChanged;
00099         }
00100
00101         // Unregister for events. Call this method before closing the view to prevent leaks.
00102         private void UnregisterForEvents()
00103         {
00104             ApplicationView.GetForCurrentView().Consolidated -= ViewConsolidated;
00105             window.VisibilityChanged -= VisibilityChanged;
00106         }
00107
00108         private void VisibilityChanged(object sender, VisibilityChangedEventArgs e)
00109         {
00110
00111             if (e.Visible)
00112             {
00113                 // A view is consolidated with other views hen there's no way for the user to get to it (it's not in the list of recently used apps, cannot be
00114                 // launched from Start, etc.) A view stops being consolidated when it's visible--at that point the user can interact with it, move it on or off screen, etc.
00115                 // It's generally a good idea to close a view after it has been consolidated, but keep it open while it's visible.
00116                 Consolidated = false;
00117             }
00118         }
00119
00120         // A view is consolidated with other views hen there's no way for the user to get to it (it's not in the list of recently used apps, cannot be
00121         // launched from Start, etc.) A view stops being consolidated when it's visible--at that point the user can interact with it, move it on or off screen, etc.
00122         // It's generally a good idea to close a view after it has been consolidated, but keep it open while it's visible.
00123         private void ViewConsolidated(ApplicationView sender, ApplicationViewConsolidatedEventArgs e)
00124         {
00125             Consolidated = true;
00126         }
00127
00128         // Called when a view has been "consolidated" (no longer accessible to the user)
00129         // and no other view is trying to interact with it. This should only be closed after the reference
00130         // count goes to 0 (including being consolidated). At the end of this, the view is closed.
00131         private void FinalizeRelease()
00132         {
00133             bool justReleased = false;
00134             lock (this)
00135             {
00136                 if (refCount == 0)
00137                 {
00138                     justReleased = true;
00139                     released = true;
00140                 }
00141             }
00142
00143             // This assumes that released will never be made false after it
00144             // it has been set to true
00145             if (justReleased)
00146             {
00147                 UnregisterForEvents();
00148                 InternalReleased(this, null);
00149             }
00150         }
00151
00152         // Creates ViewLifetimeControl for the particular view.
00153         // Only do this once per view.
00154         public static ViewLifetimeControl CreateForCurrentView()
00155         {
00156             return new ViewLifetimeControl(CoreWindow.GetForCurrentThread());
00157         }
00158
00159         // For purposes of this sample, the collection of views
00160         // is bound to a UI collection. This property is available for binding
00161         public string Title
00162         {
00163             get
00164             {
00165                 return title;
00166             }
00167             set
00168             {
00169                 if (title != value)
00170                 {
00171                     title = value;
00172                     if (PropertyChanged != null)
00173                     {
00174                         PropertyChanged(this, new PropertyChangedEventArgs("Title"));
00175                     }
00176                 }
00177             }
00178         }
00179
00180         // Necessary to communicate with the window
00181         public CoreDispatcher Dispatcher
00182         {
00183             get
00184             {
00185                 // This property never changes, so there's no need to lock
00186                 return dispatcher;
00187             }
00188         }
00189
00190         // Each view has a unique Id, found using the ApplicationView.Id property or
00191         // ApplicationView.GetApplicationViewIdForCoreWindow method. This id is used in all of the ApplicationViewSwitcher
00192         // and ProjectionManager APIs.
00193         public int Id
00194         {
00195             get
00196             {
00197                 // This property never changes, so there's no need to lock
00198                 return viewId;
00199             }
00200         }
00201
00202         // Keeps track of if the consolidated event has fired yet. A view is consolidated with other views
00203         // when there's no way for the user to get to it (it's not in the list of recently used apps, cannot be
00204         // launched from Start, etc.) A view stops being consolidated when it's visible--at that point
00205         // the user can interact with it, move it on or off screen, etc.
00206         public bool Consolidated
00207         {
00208             get
00209             {
00210                 // This property should only be accessed by the thread on which the view lives, so there's no need to lock
00211                 return consolidated;
00212             }
00213             set
00214             {
00215                 if (consolidated != value)
00216                 {
00217                     consolidated = value;
00218                     if (consolidated)
00219                     {
00220                         // The view isn't accessible to the user, so it's OK to close it.
00221                         StopViewInUse();
00222                     }
00223                     else
00224                     {
00225                         // The view has become visible, so do not close it until it's consolidated
00226                         StartViewInUse();
00227                     }
00228                 }
00229             }
00230         }
00231
00232         // Signals that the view is being interacted with by another view,
00233         // so it shouldn't be closed even if it becomes "consolidated"
00234         public int StartViewInUse()
00235         {
00236             bool releasedCopy = false;
00237             int refCountCopy = 0;
00238
00239             // This method is called from several different threads
00240             // (each view lives on its own thread)
00241             lock (this)
00242             {
00243                 releasedCopy = this.released;
00244                 if (!released)
00245                 {
00246                     refCountCopy = ++refCount;
00247                 }
00248             }
00249
00250             if (releasedCopy)
00251             {
00252                 throw new InvalidOperationException("This view is being disposed");
00253             }
00254
00255             return refCountCopy;
00256         }
00257
00258         // Should come after any call to StartViewInUse
00259         // Signals that the another view has finished interacting with the view tracked
00260         // by this object
00261         public int StopViewInUse()
00262         {
00263             int refCountCopy = 0;
00264             bool releasedCopy = false;
00265
00266             lock (this)
00267             {
00268                 releasedCopy = this.released;
00269                 if (!released)
00270                 {
00271                     refCountCopy = --refCount;
00272                     if (refCountCopy == 0)
00273                     {
00274                         // If no other view is interacting with this view, and
00275                         // the view isn't accessible to the user, it's appropriate
00276                         // to close it
00277                         //
00278                         // Before actually closing the view, make sure there are no
00279                         // other important events waiting in the queue (this low-priority item
00280                         // will run after other events)
00281                         dispatcher.RunAsync(CoreDispatcherPriority.Low, FinalizeRelease);
00282                     }
00283                 }
00284             }
00285
00286             if (releasedCopy)
00287             {
00288                 throw new InvalidOperationException("This view is being disposed");
00289             }
00290             return refCountCopy;
00291         }
00292
00293         // Signals to consumers that its time to close the view so that
00294         // they can clean up (including calling Window.Close() when finished)
00295         public event PropertyChangedEventHandler PropertyChanged;
00296         public event ViewReleasedHandler Released
00297         {
00298             add
00299             {
00300                 bool releasedCopy = false;
00301                 lock (this)
00302                 {
00303                     releasedCopy = released;
00304                     if (!released)
00305                     {
00306                         InternalReleased += value;
00307                     }
00308                 }
00309
00310                 if (releasedCopy)
00311                 {
00312                     throw new InvalidOperationException("This view is being disposed");
00313                 }
00314             }
00315
00316             remove
00317             {
00318                 lock (this)
00319                 {
00320                     InternalReleased -= value;
00321                 }
00322             }
00323         }
00324     }
00325 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CredentialPicker/cpp/Scenario1_Message.xaml.h Source File

  • CredentialPicker
  • cpp

Scenario1_Message.xaml.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Scenario1_Message.g.h"
00006 #include "MainPage.xaml.h"
00007
00008 namespace SDKTemplate
00009 {
00010     [Windows::Foundation::Metadata::WebHostHidden]
00011     public ref class Scenario1_Message sealed
00012     {
00013     public:
00014         Scenario1_Message();
00015     private:
00016         void Launch_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00017         void SetError(Platform::String^ errorText);
00018         void SetResult(Windows::Security::Credentials::UI::CredentialPickerResults^ res);
00019     };
00020 }
Generated on Fri Nov 15 2024 22:19:01 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DWriteTextLayoutCloudFont/cpp/DWriteTextLayoutCloudFont/Scenario_Document3.xaml.cpp Source File

  • DWriteTextLayoutCloudFont
  • cpp
  • DWriteTextLayoutCloudFont

Scenario_Document3.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario_Document3.xaml.h"
00014 #include "DocumentPresenter.h"
00015
00016 using namespace SDKTemplate;
00017 using namespace DWriteTextLayoutCloudFontImplementation;
00018
00019 using Platform::Object;
00020 using Platform::String;
00021 using Windows::UI::Color;
00022 using Windows::UI::ColorHelper;
00023 using Windows::UI::Xaml::SizeChangedEventArgs;
00024
00025
00026 // The DocumentPresenter class is used to handle, at a high level, the text layout that
00027 // uses downloadable fonts, the display of that layout, and interaction with DirectWrite's
00028 // font download mechanisms. The lower-level implementation is handled in classes that the
00029 // DocumentPresenter class uses. The TextLayout and FontDownloadListener classes are the
00030 // primary focus for this sample.
00031
00032
00033 Scenario_Document3::Scenario_Document3()
00034 {
00035     InitializeComponent();
00036
00037     String^ text =
00038         L"चिदंश रखते जिम्मे एसेएवं निर्माता जैसी दर्शाता विस्तरणक्षमता विकेन्द्रियकरण मुक्त प्रमान सभीकुछ नवंबर नीचे भारत संसाध मुश्किले प्रतिबध्दता बाजार और्४५० सोफ़्टवेर नाकर विश्व जनित बातसमय एकत्रित शुरुआत मर्यादित वर्ष सुचना कुशलता समस्याओ भाषा लेकिन स्थिति संस्थान सार्वजनिक लक्षण मानव प्रमान विकसित बनाकर रखति संस्था लचकनहि वातावरण मुखय बनाकर एवम् प्रदान ब्रौशर बनाना" L"\xd\xa\xd\xa"
00039         L"दोषसके निर्माण शारिरिक देने बढाता एवम् संस्थान वार्तालाप मुख्य आवश्यक अविरोधता विषय सदस्य बलवान सहायता केन्द्रिय एवम् कराना वर्तमान निर्देश कीसे पढने सारांश गटकउसि प्राधिकरन लेकिन विभाजन प्रेरना समस्याए करता पहेला देते ध्येय उद्योग सामूहिक भेदनक्षमता है।अभी कार्यकर्ता समाजो दारी संसाध";
00040
00041      String^ downloadableFontName = ref new String(L"Kokila");
00042
00043     // Set the colors to be used for the text layout. Also apply to the frame background.
00044      Color textColor = ColorHelper::FromArgb(0xFF, 0xFF, 0xFF, 0xFF);
00045      Color textBackgroundColor = ColorHelper::FromArgb(0xFF, 0x30, 0x30, 0x30);
00046
00047      // Create the DocumentPresenter for our document.
00048      m_documentPresenter = ref new DocumentPresenter(
00049          text,
00050          downloadableFontName,
00051          L"hi", // Language tag for the content (Hindi).
00052          textColor,
00053          textBackgroundColor,
00054          TextLayoutImage // The target image control for the SurfaceImageSource presenting the text layout.
00055      );
00056 }
00057
00058
00059
00060 // Event handlers:
00061
00062 void Scenario_Document3::OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00063 {
00064     m_documentPresenter = nullptr;
00065 }
00066
00067
00068 void Scenario_Document3::TextLayoutFrame_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
00069 {
00070     // Get the current available width and update the TextLayout if different.
00071     // The available width will be the actual width less the left and right padding.
00072     //
00073     // Note: when this page is presented in a narrow window, or if this page and
00074     // the navigation pane are both open simultanously on a narrow display, the
00075     // width of our containing frame could become very small, and subtracting the
00076     // left and right padding values could even result in a negative value. That
00077     // would result in an error when we try to revise the text layout. This issue
00078     // is avoided, however, by having a MinWidth set on the grid for this page in
00079     // the XAML markup.
00080     //
00081     // There's a related issue: setting the text layout to a narrow width causes
00082     // it to have a large height. When we create the SurfaceImageSource used for
00083     // displaying the text layout, that large height could exceed the graphics
00084     // device resources on older devices. A check for this is included in the
00085     // TextLayoutImageSource class, but it can result in some of the text layout
00086     // being clipped. This should not happen on devices that support D3D feature
00087     // level 9_3 or later. Managing graphics device resources is beyond the scope
00088     // of this sample, however, so that known issue is left as is.
00089
00090     double width = TextLayoutFrame->ActualWidth;
00091     auto padding = TextLayoutFrame->Padding;
00092     width -= (padding.Left + padding.Right);
00093
00094     // XAML uses DIPs expressed as double. DirectWrite uses DIPs expressed as float.
00095     // casting here.
00096     m_documentPresenter->SetLayoutWidth(static_cast<float>(width));
00097 }
00098
00099
Generated on Fri Nov 15 2024 22:19:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceConnect Member List

This is the complete list of members for DeviceConnect, including all inherited members.
CloseFx2Device() | DeviceConnect | [inline, private]
DeviceConnect() | DeviceConnect | [inline]
deviceConnectDevices_SelectionChanged(object sender, SelectionChangedEventArgs e) | DeviceConnect | [inline, private]
deviceConnectStart_Click(object sender, RoutedEventArgs e) | DeviceConnect | [inline, private]
deviceConnectStop_Click(object sender, RoutedEventArgs e) | DeviceConnect | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | DeviceConnect | [inline, protected]
OpenFx2DeviceAsync(string Id) | DeviceConnect | [inline, private]
rootPage | DeviceConnect | [private]
UpdateStartStopButtons() | DeviceConnect | [inline, private]
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraOpenCV/shared/OpenCVBridge/pch.cpp Source File

  • CameraOpenCV
  • shared
  • OpenCVBridge

pch.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario9 Member List

This is the complete list of members for Scenario9, including all inherited members.
Default_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario9 | [inline, private]
Scenario9() | Scenario9 | [inline]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

IntToDoubleConverter Member List

This is the complete list of members for IntToDoubleConverter, including all inherited members.
Convert(object value, Type targetType, object parameter, string language) | IntToDoubleConverter | [inline]
Convert(object value, Type targetType, object parameter, string language) | IntToDoubleConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | IntToDoubleConverter | [inline]
ConvertBack(object value, Type targetType, object parameter, string language) | IntToDoubleConverter | [inline]
Generated on Fri Nov 15 2024 22:24:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Scenario8_PairDevice.cpp Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

Scenario8_PairDevice.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario8_PairDevice.h"
00014 #include "DeviceHelpers.h"
00015 #include "SampleConfiguration.h"
00016 #include "Scenario8_PairDevice.g.cpp"
00017
00018 using namespace winrt;
00019 using namespace winrt::Windows::Devices::Enumeration;
00020 using namespace winrt::Windows::Foundation;
00021 using namespace winrt::Windows::UI::Xaml;
00022 using namespace winrt::Windows::UI::Xaml::Controls;
00023 using namespace winrt::Windows::UI::Xaml::Navigation;
00024
00025 namespace winrt::SDKTemplate::implementation
00026 {
00027     Scenario8_PairDevice::Scenario8_PairDevice()
00028     {
00029         InitializeComponent();
00030         deviceWatcherHelper->DeviceChanged({ get_weak(), &Scenario8_PairDevice::OnDeviceListChanged });
00031     }
00032
00033     void Scenario8_PairDevice::OnNavigatedTo(NavigationEventArgs const&)
00034     {
00035         resultsListView().ItemsSource(resultCollection);
00036
00037         selectorComboBox().ItemsSource(DeviceSelectorChoices::PairingSelectors());
00038         selectorComboBox().SelectedIndex(0);
00039     }
00040
00041     void Scenario8_PairDevice::OnNavigatedFrom(NavigationEventArgs const&)
00042     {
00043         deviceWatcherHelper->Reset();
00044     }
00045
00046     void Scenario8_PairDevice::StartWatcherButton_Click(IInspectable const&, RoutedEventArgs const&)
00047     {
00048         StartWatcher();
00049     }
00050
00051     void Scenario8_PairDevice::StopWatcherButton_Click(IInspectable const&, RoutedEventArgs const&)
00052     {
00053         StopWatcher();
00054     }
00055
00056     void Scenario8_PairDevice::StartWatcher()
00057     {
00058         startWatcherButton().IsEnabled(false);
00059         resultCollection.Clear();
00060
00061         // Get the device selector chosen by the UI then add additional constraints for devices that
00062         // can be paired or are already paired.
00063         DeviceSelectorInfo* deviceSelectorInfo = FromInspectable<DeviceSelectorInfo>(selectorComboBox().SelectedItem());
00064         hstring selector = L"(" + deviceSelectorInfo->Selector() + L") AND (System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True)";
00065
00066         DeviceWatcher deviceWatcher{ nullptr };
00067         if (deviceSelectorInfo->Kind() == DeviceInformationKind::Unknown)
00068         {
00069             // Kind will be determined by the selector
00070             deviceWatcher = DeviceInformation::CreateWatcher(
00071                 selector,
00072                 nullptr // don't request additional properties for this sample
00073             );
00074         }
00075         else
00076         {
00077             // Kind is specified in the selector info
00078             deviceWatcher = DeviceInformation::CreateWatcher(
00079                 selector,
00080                 nullptr, // don't request additional properties for this sample
00081                 deviceSelectorInfo->Kind());
00082         }
00083
00084         rootPage.NotifyUser(L"Starting Watcher...", NotifyType::StatusMessage);
00085         deviceWatcherHelper->StartWatcher(deviceWatcher);
00086         stopWatcherButton().IsEnabled(true);
00087     }
00088
00089     void Scenario8_PairDevice::StopWatcher()
00090     {
00091         stopWatcherButton().IsEnabled(false);
00092
00093         deviceWatcherHelper->StopWatcher();
00094
00095         startWatcherButton().IsEnabled(true);
00096     }
00097
00098     void Scenario8_PairDevice::OnDeviceListChanged(DeviceWatcher const&, hstring const& id)
00099     {
00100         // If the item being updated is currently "selected", then update the pairing buttons
00101         auto item = resultsListView().SelectedItem();
00102         DeviceInformationDisplay* deviceInformationDisplay = FromInspectable<DeviceInformationDisplay>(item);
00103         if ((deviceInformationDisplay != nullptr) && (deviceInformationDisplay->Id() == id))
00104         {
00105             UpdatePairingButtons();
00106         }
00107     }
00108
00109     fire_and_forget Scenario8_PairDevice::PairButton_Click(IInspectable const&, RoutedEventArgs const&)
00110     {
00111         auto lifetime = get_strong();
00112
00113         // Gray out the pair button and results view while pairing is in progress.
00114         resultsListView().IsEnabled(false);
00115         pairButton().IsEnabled(false);
00116         rootPage.NotifyUser(L"Pairing started. Please wait...", NotifyType::StatusMessage);
00117
00118         IInspectable item = resultsListView().SelectedItem();
00119         DeviceInformationDisplay* deviceInfoDisp = FromInspectable<DeviceInformationDisplay>(item);
00120
00121         DevicePairingResult result = co_await deviceInfoDisp->DeviceInformation().Pairing().PairAsync();
00122
00123         rootPage.NotifyUser(
00124             L"Pairing result = " + to_hstring(result.Status()),
00125             result.Status() == DevicePairingResultStatus::Paired ? NotifyType::StatusMessage : NotifyType::ErrorMessage);
00126
00127         UpdatePairingButtons();
00128         resultsListView().IsEnabled(true);
00129     }
00130
00131     fire_and_forget Scenario8_PairDevice::UnpairButton_Click(IInspectable const&, RoutedEventArgs const&)
00132     {
00133         auto lifetime = get_strong();
00134
00135         // Gray out the pair button and results view while unpairing is in progress.
00136         resultsListView().IsEnabled(false);
00137         unpairButton().IsEnabled(false);
00138         rootPage.NotifyUser(L"Unpairing started. Please wait...", NotifyType::StatusMessage);
00139
00140         IInspectable item = resultsListView().SelectedItem();
00141         DeviceInformationDisplay* deviceInfoDisp = FromInspectable<DeviceInformationDisplay>(item);
00142
00143         DeviceUnpairingResult result = co_await deviceInfoDisp->DeviceInformation().Pairing().UnpairAsync();
00144
00145         rootPage.NotifyUser(
00146             L"Unpairing result = " + to_hstring(result.Status()),
00147             result.Status() == DeviceUnpairingResultStatus::Unpaired ? NotifyType::StatusMessage : NotifyType::ErrorMessage);
00148
00149         UpdatePairingButtons();
00150         resultsListView().IsEnabled(true);
00151     }
00152
00153     void Scenario8_PairDevice::ResultsListView_SelectionChanged(IInspectable const&, SelectionChangedEventArgs const&)
00154     {
00155         UpdatePairingButtons();
00156     }
00157
00158     void Scenario8_PairDevice::UpdatePairingButtons()
00159     {
00160         auto item = resultsListView().SelectedItem();
00161         DeviceInformationDisplay* deviceInfoDisp = FromInspectable<DeviceInformationDisplay>(item);
00162         if (deviceInfoDisp != nullptr &&
00163             deviceInfoDisp->DeviceInformation().Pairing().CanPair() &&
00164             !deviceInfoDisp->DeviceInformation().Pairing().IsPaired())
00165         {
00166             pairButton().IsEnabled(true);
00167         }
00168         else
00169         {
00170             pairButton().IsEnabled(false);
00171         }
00172
00173         if (deviceInfoDisp != nullptr &&
00174             deviceInfoDisp->DeviceInformation().Pairing().IsPaired())
00175         {
00176             unpairButton().IsEnabled(true);
00177         }
00178         else
00179         {
00180             unpairButton().IsEnabled(false);
00181         }
00182     }
00183 }
00184
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MainPage Member List

This is the complete list of members for MainPage, including all inherited members.
Button_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
Current | MainPage | [static]
FEATURE_NAME | MainPage |
Footer_Click(object sender, RoutedEventArgs e) | MainPage | [inline, private]
LoadScenarios() | MainPage | [inline, private]
MainPage() | MainPage | [inline]
NavigateToScenario(Type scenarioType, object args) | MainPage | [inline, private]
NotifyUser(string strMessage, NotifyType type) | MainPage | [inline]
OnNavigatedTo(NavigationEventArgs e) | MainPage | [inline, protected]
ProjectionViewPageControl | MainPage |
ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) | MainPage | [inline, private]
scenarios | MainPage | [private]
Scenarios | MainPage |
Generated on Fri Nov 15 2024 22:23:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cppwinrt/pch.h Source File

  • WebSocket
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include <winrt/Windows.Foundation.h>
00005 #include <winrt/Windows.Foundation.Collections.h>
00006 #include <winrt/Windows.ApplicationModel.Activation.h>
00007 #include <winrt/Windows.Networking.Sockets.h>
00008 #include <winrt/Windows.Security.Cryptography.Certificates.h>
00009 #include <winrt/Windows.Storage.Streams.h>
00010 #include <winrt/Windows.System.h>
00011 #include <winrt/Windows.UI.Core.h>
00012 #include <winrt/Windows.UI.Xaml.h>
00013 #include <winrt/Windows.UI.Xaml.Automation.Peers.h>
00014 #include <winrt/Windows.UI.Xaml.Controls.h>
00015 #include <winrt/Windows.UI.Xaml.Controls.Primitives.h>
00016 #include <winrt/Windows.UI.Xaml.Documents.h>
00017 #include <winrt/Windows.UI.Xaml.Interop.h>
00018 #include <winrt/Windows.UI.Xaml.Markup.h>
00019 #include <winrt/Windows.UI.Xaml.Media.h>
00020 #include <winrt/Windows.UI.Xaml.Navigation.h>
00021 #include <winrt/Windows.Web.h>
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 360VideoPlayback/cs/Common/InteropStatics.cs Source File

  • 360VideoPlayback
  • cs
  • Common

InteropStatics.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Runtime.InteropServices;
00003
00004 namespace _360VideoPlayback.Common
00005 {
00006     public static class InteropStatics
00007     {
00008         public static Guid IInspectable = new Guid("AF86E2E0-B12D-4c6a-9C5A-D7AA65101E90");
00009         public static Guid ID3D11Resource = new Guid("dc8e63f3-d12b-4952-b47b-5e45026a862d");
00010         public static Guid IDXGIAdapter3 = new Guid("645967A4-1392-4310-A798-8053CE3E93FD");
00011
00012         [DllImport(
00013             "d3d11.dll",
00014             EntryPoint = "CreateDirect3D11DeviceFromDXGIDevice",
00015             SetLastError = true,
00016             CharSet = CharSet.Unicode,
00017             ExactSpelling = true,
00018             CallingConvention = CallingConvention.StdCall
00019             )]
00020         public static extern UInt32 CreateDirect3D11DeviceFromDXGIDevice(IntPtr dxgiDevice, out IntPtr graphicsDevice);
00021
00022         [DllImport(
00023             "d3d11.dll",
00024             EntryPoint = "CreateDirect3D11SurfaceFromDXGISurface",
00025             SetLastError = true,
00026             CharSet = CharSet.Unicode,
00027             ExactSpelling = true,
00028             CallingConvention = CallingConvention.StdCall
00029             )]
00030         public static extern UInt32 CreateDirect3D11SurfaceFromDXGISurface(IntPtr dxgiSurface, out IntPtr graphicsSurface);
00031
00032         [ComImport]
00033         [Guid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1")]
00034         [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
00035         [ComVisible(true)]
00036         public interface IDirect3DDxgiInterfaceAccess
00037         {
00038             IntPtr GetInterface([In] ref Guid iid);
00039         };
00040     }
00041 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: 3DPrinting/cppwinrt/Project.idl Source File

  • 3DPrinting
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_Print : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_Print();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_Launch : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_Launch();
00024     }
00025 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LampDevice/cpp/Scenario3_AvailabilityChanged.xaml.cpp Source File

  • LampDevice
  • cpp

Scenario3_AvailabilityChanged.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_AvailabilityChanged.xaml.h"
00014 #include <sstream>
00015
00016 using namespace Concurrency;
00017 using namespace Platform;
00018 using namespace SDKTemplate;
00019 using namespace Windows::Devices;
00020 using namespace Windows::Devices::Enumeration;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Media::Capture;
00024 using namespace Windows::UI::Core;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Controls::Primitives;
00028 using namespace Windows::UI::Xaml::Data;
00029 using namespace Windows::UI::Xaml::Input;
00030 using namespace Windows::UI::Xaml::Media;
00031 using namespace Windows::UI::Xaml::Navigation;
00032
00033 /// <summary>
00034 /// Initializes a new instance of the <see cref="Scenario3_AvailabilityChanged("/> class.
00035 /// </summary>
00036 Scenario3_AvailabilityChanged::Scenario3_AvailabilityChanged()
00037     : _rootPage(MainPage::Current)
00038     , _lamp(nullptr)
00039 {
00040     InitializeComponent();
00041 }
00042
00043 /// <summary>
00044 /// Event handler for the OnNavigatedTo event. In this scenario, we want
00045 /// to get a lamp object for the lifetime of the page, so when we first
00046 /// navigate to the page, we Initialize a private lamp object
00047 /// </summary>
00048 /// <param name="e">Contains state information and event data associated with the event</param>
00049 void Scenario3_AvailabilityChanged::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00050 {
00051     _rootPage = MainPage::Current;
00052     InitializeLampAsync()
00053         .then([this, e]()
00054     {
00055         Windows::UI::Xaml::Controls::Page::OnNavigatedTo(e);
00056     });
00057 }
00058
00059 /// <summary>
00060 /// Initialize the lamp acquiring the default instance
00061 /// </summary>
00062 /// <returns>async Task</returns>
00063 task<void> Scenario3_AvailabilityChanged::InitializeLampAsync()
00064 {
00065     return create_task(Lights::Lamp::GetDefaultAsync())
00066         .then([this](Lights::Lamp^ lamp)
00067     {
00068         if (lamp == nullptr)
00069         {
00070             LogStatusAsync("Error: No lamp device was found", NotifyType::ErrorMessage);
00071             lampToggle->IsEnabled = false;
00072             return;
00073         }
00074
00075         // Set our private member for later use
00076         _lamp = lamp;
00077
00078         std::wstringstream ss;
00079         ss << "Default lamp instance acquired, Device Id: " << lamp->DeviceId->Data();
00080         LogStatusAsync(ref new String(ss.str().c_str()), NotifyType::StatusMessage);
00081         lampToggle->IsEnabled = true;
00082     });
00083 }
00084
00085 /// <summary>
00086 /// Event handler for the OnNavigatingFrom event. Here
00087 /// we want to make sure to release the lamp before exiting this scenario page.
00088 /// </summary>
00089 /// <param name="e">Contains state information and event data associated with the event</param>
00090 void Scenario3_AvailabilityChanged::OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs^ e)
00091 {
00092     DisposeLamp();
00093     Windows::UI::Xaml::Controls::Page::OnNavigatingFrom(e);
00094 }
00095
00096 /// <summary>
00097 /// Method to dispose of current Lamp instance
00098 /// and release all resources
00099 /// </summary>
00100 void Scenario3_AvailabilityChanged::DisposeLamp()
00101 {
00102     if (_lamp == nullptr)
00103     {
00104         return;
00105     }
00106
00107     lampToggle->IsEnabled = false;
00108     _lamp->AvailabilityChanged -= _lampAvailabilutyChangedEventToken;
00109     _lamp->IsEnabled = false;
00110     _lamp = nullptr;
00111 }
00112
00113 /// <summary>
00114 /// Event Handler for Lamp Availability Changed. When it fires, we want to update to
00115 /// Lamp toggle UI to show that lamp is available or not
00116 /// </summary>
00117 /// <param name="sender">Contains information regarding  Lamp object that fired event</param>
00118 /// <param name="e">Contains state information and event data associated with the event</param>
00119 void Scenario3_AvailabilityChanged::Lamp_AvailabilityChanged(Lights::Lamp^ sender, Lights::LampAvailabilityChangedEventArgs^ args)
00120 {
00121     // Update the Lamp Toggle UI to indicate lamp has been consumed by another application
00122     create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, args]()
00123     {
00124         if (lampToggle->IsOn)
00125         {
00126             lampToggle->IsOn = args->IsAvailable;
00127         }
00128
00129         lampToggle->IsEnabled = args->IsAvailable;
00130     }))).then([this, args]()
00131     {
00132         std::wstringstream ss;
00133         ss << "Lamp Availability Changed Notification has fired, IsAvailable= " << args->IsAvailable;
00134         LogStatusAsync(ref new String(ss.str().c_str()), NotifyType::StatusMessage);
00135     });
00136 }
00137
00138 /// <summary>
00139 /// Event Handler for the register button click event
00140 /// </summary>
00141 /// <param name="sender">Contains information regarding button that fired event</param>
00142 /// <param name="e">Contains state information and event data associated with the event</param>
00143 void Scenario3_AvailabilityChanged::RegisterBtn_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00144 {
00145     if (_lamp == nullptr)
00146     {
00147         LogStatusAsync("Error: No lamp device was found", NotifyType::ErrorMessage);
00148         return;
00149     }
00150
00151     _lampAvailabilutyChangedEventToken =
00152         _lamp->AvailabilityChanged += ref new TypedEventHandler<Lights::Lamp^, Lights::LampAvailabilityChangedEventArgs^>(this, &Scenario3_AvailabilityChanged::Lamp_AvailabilityChanged);
00153     LogStatusAsync("Registered for Lamp Availability Changed Notification", NotifyType::StatusMessage);
00154 }
00155
00156 /// <summary>
00157 /// Event handler for the Unregister Availability Event
00158 /// </summary>
00159 /// <param name="sender">Contains information regarding button that fired event</param>
00160 /// <param name="e">Contains state information and event data associated with the event</param>
00161 void Scenario3_AvailabilityChanged::UnRegisterBtn_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00162 {
00163     if (_lamp == nullptr)
00164     {
00165         LogStatusAsync("Error: No lamp device was found", NotifyType::ErrorMessage);
00166         return;
00167     }
00168
00169     _lamp->AvailabilityChanged -= _lampAvailabilutyChangedEventToken;
00170     LogStatusAsync("Unregistered for Lamp Availability Changed Notification", NotifyType::StatusMessage);
00171 }
00172
00173 /// <summary>
00174 /// Event handler for Lamp Toggle Switch
00175 /// Toggling the switch will turn Lamp on or off
00176 /// </summary>
00177 /// <param name="sender">Contains information regarding toggle switch that fired event</param>
00178 /// <param name="e">Contains state information and event data associated with the event</param>
00179 void Scenario3_AvailabilityChanged::lampToggle_Toggled(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00180 {
00181     if (_lamp == nullptr)
00182     {
00183         LogStatusAsync("Error: No lamp device was found", NotifyType::ErrorMessage);
00184         return;
00185     }
00186
00187     ToggleSwitch^ toggleSwitch = static_cast<ToggleSwitch^>(sender);
00188     if (toggleSwitch != nullptr)
00189     {
00190         if (toggleSwitch->IsOn)
00191         {
00192             _lamp->IsEnabled = true;
00193             LogStatusAsync("Lamp is Enabled", NotifyType::StatusMessage);
00194         }
00195         else
00196         {
00197             _lamp->IsEnabled = false;
00198             LogStatusAsync("Lamp is Disabled", NotifyType::StatusMessage);
00199         }
00200     }
00201 }
00202
00203 /// <summary>
00204 /// Marshall log message to the UI thread and update outputBox, this method is for more general messages
00205 /// Note: This method is asynchronous and is not guaranteed to display messages in the order in
00206 /// which they were called without task chaining
00207 /// </summary>
00208 /// <param name="message">Message to log to the outputBox</param>
00209 task<void> Scenario3_AvailabilityChanged::LogStatusToOutputBoxAsync(String^ message)
00210 {
00211     return create_task(Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, message]()
00212     {
00213         outputBox->Text += message + "\r\n";
00214         outputScrollViewer->ChangeView(0.0, outputBox->ActualHeight, 1.0f);
00215     })));
00216 }
00217
00218 /// <summary>
00219 /// Method to log Status to Main Status block, this method is for important status messages to be
00220 /// displayed at bottom of scenario page
00221 /// Note: This method is asynchronous and is not guaranteed to display messages in the order in
00222 /// which they were called without task chaining
00223 /// </summary>
00224 /// <param name="message">Message to log to the output box</param>
00225 /// <param name="type">Notification Type for status message</param>
00226 task<void> Scenario3_AvailabilityChanged::LogStatusAsync(String^ message, NotifyType type)
00227 {
00228     return create_task(Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, message, type]()
00229     {
00230         _rootPage->NotifyUser(message, type);
00231     }))).then([this, message]()
00232     {
00233         return LogStatusToOutputBoxAsync(message);
00234     });
00235 }
Generated on Fri Nov 15 2024 22:20:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cs/Scenario5_DefiningCustomGlyphs.xaml.cs Source File

  • LineDisplay
  • cs

Scenario5_DefiningCustomGlyphs.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Threading.Tasks;
00014 using Windows.Devices.PointOfService;
00015 using Windows.Foundation;
00016 using Windows.Security.Cryptography;
00017 using Windows.Storage.Streams;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace SDKTemplate
00023 {
00024     public sealed partial class Scenario5_DefiningCustomGlyphs : Page
00025     {
00026         private MainPage rootPage = MainPage.Current;
00027         private ClaimedLineDisplay lineDisplay;
00028
00029         private IBuffer glyphBuffer;
00030
00031         public Scenario5_DefiningCustomGlyphs()
00032         {
00033             this.InitializeComponent();
00034             DataContext = this;
00035         }
00036
00037         protected override async void OnNavigatedTo(NavigationEventArgs e)
00038         {
00039             await InitializeAsync();
00040         }
00041
00042         protected override void OnNavigatedFrom(NavigationEventArgs e)
00043         {
00044             lineDisplay?.Dispose();
00045             lineDisplay = null;
00046         }
00047
00048         private async Task InitializeAsync()
00049         {
00050             ResetButton.IsEnabled = false;
00051             SupportedGlyphsComboBox.Items.Clear();
00052
00053             lineDisplay = await rootPage.ClaimScenarioLineDisplayAsync();
00054
00055             if ((lineDisplay != null) && lineDisplay.Capabilities.CanDisplayCustomGlyphs)
00056             {
00057                 string sampleText = "ABC";
00058                 foreach (uint glyphCode in lineDisplay.CustomGlyphs.SupportedGlyphCodes)
00059                 {
00060                     string glyphString = Char.ConvertFromUtf32((int)glyphCode);
00061                     SupportedGlyphsComboBox.Items.Add(new ComboBoxItem { Content = $"Code {glyphCode} (UTF-32 '{glyphString}')", Tag = glyphCode });
00062                     if (sampleText.Length < 10)
00063                     {
00064                         sampleText += glyphString;
00065                     }
00066                 }
00067
00068                 if (SupportedGlyphsComboBox.Items.Count > 0)
00069                 {
00070                     SupportedGlyphsComboBox.SelectedIndex = 0;
00071                 }
00072
00073                 Size glyphSize = lineDisplay.CustomGlyphs.SizeInPixels;
00074                 glyphBuffer = CreateSolidGlyphBuffer((int)glyphSize.Width, (int)glyphSize.Height);
00075
00076                 await lineDisplay.DefaultWindow.TryDisplayTextAsync(sampleText);
00077             }
00078
00079             ResetButton.IsEnabled = true;
00080         }
00081
00082         private async void DefineGlyphButton_Click(object sender, RoutedEventArgs e)
00083         {
00084             var selectedGlyphCode = Helpers.GetSelectedItemTag<uint>(SupportedGlyphsComboBox);
00085             if (await lineDisplay.CustomGlyphs.TryRedefineAsync((uint)selectedGlyphCode, glyphBuffer) &&
00086                 await lineDisplay.DefaultWindow.TryRefreshAsync())
00087             {
00088                 // Success. See results on the line display.
00089                 rootPage.NotifyUser($"Redefined glyph {selectedGlyphCode}.", NotifyType.ErrorMessage);
00090
00091             }
00092             else
00093             {
00094                 rootPage.NotifyUser("Unable to redefine glyph and refresh.", NotifyType.ErrorMessage);
00095             }
00096         }
00097
00098         private async void ResetButton_Click(object sender, RoutedEventArgs e)
00099         {
00100             lineDisplay?.Dispose();
00101             await InitializeAsync();
00102         }
00103
00104         private IBuffer CreateSolidGlyphBuffer(int widthInPixels, int heightInPixels)
00105         {
00106             // Data is sent in one byte chunks, so find the minimum number of whole bytes
00107             // needed to define each row of the glyph.
00108             int bytesPerRow = (widthInPixels + 7) / 8;
00109
00110             byte[] newGlyphBuffer = new byte[bytesPerRow * heightInPixels];
00111             for (int i = 0; i < newGlyphBuffer.Length; i++)
00112             {
00113                 // Set every bit so that we draw a solid rectangle.
00114                 newGlyphBuffer[i] = 0xFF;
00115             }
00116
00117             return CryptographicBuffer.CreateFromByteArray(newGlyphBuffer);
00118         }
00119
00120         // Helpers that are used by XAML binding to enable and disable buttons.
00121         public bool IsNonNull(object item) => item != null;
00122     }
00123 }
Generated on Fri Nov 15 2024 22:20:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAccountManagement/cpp/Scenario3_AAD.xaml.cpp Source File

  • WebAccountManagement
  • cpp

Scenario3_AAD.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario3_Aad.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace Platform;
00009 using namespace Windows::Foundation;
00010 using namespace Windows::Foundation::Collections;
00011 using namespace Windows::Security::Authentication::Web::Core;
00012 using namespace Windows::Security::Credentials;
00013 using namespace Windows::Storage;
00014 using namespace Windows::UI::Popups;
00015 using namespace Windows::UI::Xaml;
00016 using namespace Windows::UI::Xaml::Controls;
00017 using namespace Windows::UI::Xaml::Controls::Primitives;
00018 using namespace Windows::UI::Xaml::Data;
00019 using namespace Windows::UI::Xaml::Input;
00020 using namespace Windows::UI::Xaml::Media;
00021 using namespace Windows::UI::Xaml::Navigation;
00022 using namespace Windows::UI::ApplicationSettings;
00023 using namespace Windows::ApplicationModel::Background;
00024 using namespace Windows::UI::Xaml::Media::Imaging;
00025
00026 Scenario3_Aad::Scenario3_Aad() : rootPage(MainPage::Current)
00027 {
00028     InitializeComponent();
00029     InitalizeAccountsControlDialog();
00030 }
00031
00032 void Scenario3_Aad::OnNavigatedFrom(NavigationEventArgs^ e)
00033 {
00034     LogoffAndRemoveAccount();
00035     CleanupAccountsControlDialog();
00036 }
00037
00038 void SDKTemplate::Scenario3_Aad::Button_SignIn_Click(Object^ sender, RoutedEventArgs^ e)
00039 {
00040     // Inside OnAccountCommandsRequested we will determine that we need to show accounts
00041     // and providers eligible for sign in because there is no signed in account
00042     AccountsSettingsPane::Show();
00043 }
00044
00045 void SDKTemplate::Scenario3_Aad::Button_GetTokenSilently_Click(Object^ sender, RoutedEventArgs^ e)
00046 {
00047     AuthenticateWithRequestTokenSilent(m_provider, AAD_SCOPE_REQUESTED, AAD_CLIENT_ID, m_account);
00048 }
00049
00050 void SDKTemplate::Scenario3_Aad::Button_ManageAccounts_Click(Object^ sender, RoutedEventArgs^ e)
00051 {
00052     // Inside OnAccountCommandsRequested we will determine that we need to show the
00053     // active account since are signed into an account right now
00054     AccountsSettingsPane::Show();
00055 }
00056
00057 void SDKTemplate::Scenario3_Aad::Button_Reset_Click(Object^ sender, RoutedEventArgs^ e)
00058 {
00059     rootPage->NotifyUser("Resetting", NotifyType::StatusMessage);
00060
00061     LogoffAndRemoveAccount();
00062
00063     rootPage->NotifyUser("Done Resetting", NotifyType::StatusMessage);
00064 }
00065
00066 void SDKTemplate::Scenario3_Aad::InitalizeAccountsControlDialog()
00067 {
00068     // Add to the event AccountCommandsRequested to load our list of providers into the AccountSettingsPane
00069     m_accountCommandsRequestedRegistrationToken = AccountsSettingsPane::GetForCurrentView()->AccountCommandsRequested::add(
00070         ref new TypedEventHandler<AccountsSettingsPane^, AccountsSettingsPaneCommandsRequestedEventArgs^>(
00071         this,
00072         &SDKTemplate::Scenario3_Aad::OnAccountCommandsRequested)
00073         );
00074
00075     // Populate our list of providers with the AAD provider, and attempt to find any accounts saved.
00076     GetProvidersAndAccounts();
00077 }
00078
00079 void SDKTemplate::Scenario3_Aad::CleanupAccountsControlDialog()
00080 {
00081     // Remove the event handler from the AccountCommandsRequested
00082     AccountsSettingsPane::GetForCurrentView()->AccountCommandsRequested::remove(m_accountCommandsRequestedRegistrationToken);
00083 }
00084
00085 void SDKTemplate::Scenario3_Aad::OnAccountCommandsRequested(
00086     AccountsSettingsPane^ sender,
00087     AccountsSettingsPaneCommandsRequestedEventArgs^ e)
00088 {
00089     // This scenario only supports a single account at one time.
00090     // If there already is an account, we do not include a provider in the list
00091     if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
00092     {
00093         AddWebAccount(e);
00094     }
00095     else
00096     {
00097         AddWebAccountProvider(e);
00098     }
00099
00100     AddLinks(e);
00101 }
00102
00103 void SDKTemplate::Scenario3_Aad::GetProvidersAndAccounts()
00104 {
00105     // Make a task to get the AAD Provider by it's ID
00106     // When that task completes, save the AAD provider found
00107     concurrency::create_task(WebAuthenticationCoreManager::FindAccountProviderAsync(MICROSOFT_PROVIDER_ID, ORGANIZATION_AUTHORITY))
00108         .then([this](WebAccountProvider^ foundAadProvider)
00109     {
00110         if (foundAadProvider)
00111         {
00112             m_provider = foundAadProvider;
00113         }
00114         else
00115         {
00116             rootPage->NotifyUser("Provider not found for id: " + MICROSOFT_PROVIDER_ID + " and authority: " + ORGANIZATION_AUTHORITY, NotifyType::StatusMessage);
00117         }
00118     }).then([this]()
00119     {
00120         // Then check to see if there is a stored account id in local settings,
00121         // if so then get that account and save that as well
00122         if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
00123         {
00124             auto accountID = safe_cast<String^>(ApplicationData::Current->LocalSettings->Values->Lookup(STORED_ACCOUNT_ID_KEY));
00125
00126             concurrency::create_task(WebAuthenticationCoreManager::FindAccountAsync(m_provider, accountID)).then([this](WebAccount^ foundAadAccount)
00127             {
00128                 if (foundAadAccount)
00129                 {
00130                     SaveAccount(foundAadAccount);
00131                 }
00132             });
00133         }
00134     });
00135 }
00136
00137 //Creates a provider command object for our provider and adds it to the AccountsControl list of provider commands
00138 void SDKTemplate::Scenario3_Aad::AddWebAccountProvider(AccountsSettingsPaneCommandsRequestedEventArgs^ e)
00139 {
00140     e->HeaderText = "Describe what adding an account to your application will do for the user.";
00141
00142     // Create a new WebAccountProviderCommandInvokedHandler for the event fired when a user clicks on a provider in the AccountSettingsPane
00143     WebAccountProviderCommandInvokedHandler^ handler = ref new WebAccountProviderCommandInvokedHandler(this, &SDKTemplate::Scenario3_Aad::WebAccountProviderCommandInvoked);
00144
00145     // Make a new command based on the AAD provider and the click handler we just created
00146     WebAccountProviderCommand^ aadProviderCommand = ref new WebAccountProviderCommand(SDKTemplate::Scenario3_Aad::m_provider, handler);
00147
00148     // Append that command to the WebAccountProviderCommands list for the AccountSettingsPane
00149     e->WebAccountProviderCommands->Append(aadProviderCommand);
00150 }
00151
00152 //Creates a web account command object for our account, if we have one saved, and adds it to the AccountsControl list of web account commands
00153 void SDKTemplate::Scenario3_Aad::AddWebAccount(AccountsSettingsPaneCommandsRequestedEventArgs^ e)
00154 {
00155     e->HeaderText = "Describe what removing an account to your application will do.";
00156
00157     // Create a new WebAccountCommandInvokedHandler for the event fired when a user clicks on an account in the AccountSettingsPane
00158     WebAccountCommandInvokedHandler^ handler = ref new WebAccountCommandInvokedHandler(this, &SDKTemplate::Scenario3_Aad::WebAccountCommandInvoked);
00159
00160     // Make a new command based on the AAD account and the click handler we just created
00161     WebAccountCommand^ aadAccountCommand = ref new WebAccountCommand(m_account, handler, SupportedWebAccountActions::Remove);
00162
00163     // Append that command to the WebAccountProviderCommands list for the AccountSettingsPane
00164     e->WebAccountCommands->Append(aadAccountCommand);
00165 }
00166
00167 // Add optional descriptive text and buttons/commands to the AccountControl
00168 void SDKTemplate::Scenario3_Aad::AddLinks(AccountsSettingsPaneCommandsRequestedEventArgs^ e)
00169 {
00170     // You can add links such as privacy policy, help, general account settings
00171     e->Commands->Append(ref new SettingsCommand("privacypolicy", "Privacy Policy", ref new UICommandInvokedHandler(this, &SDKTemplate::Scenario3_Aad::PrivacyPolicyInvoked)));
00172     e->Commands->Append(ref new SettingsCommand("otherlink", "Other Link", ref new UICommandInvokedHandler(this, &SDKTemplate::Scenario3_Aad::OtherLinkInvoked)));
00173 }
00174
00175 // The function that will be called from AccountSettingsPane with the WebAccountProvider
00176 // that was clicked by the user
00177 void SDKTemplate::Scenario3_Aad::WebAccountProviderCommandInvoked(WebAccountProviderCommand^ command)
00178 {
00179     AuthenticateWithRequestToken(command->WebAccountProvider, AAD_SCOPE_REQUESTED, AAD_CLIENT_ID);
00180 }
00181
00182 // The function that will be called from AccountSettingsPane with the WebAccount
00183 // that was selected by the user.
00184 void SDKTemplate::Scenario3_Aad::WebAccountCommandInvoked(WebAccountCommand^ command, WebAccountInvokedArgs^ args)
00185 {
00186     if (args->Action == WebAccountAction::Remove)
00187     {
00188         LogoffAndRemoveAccount();
00189     }
00190 }
00191
00192 // Displays privacy policy message on clicking it in the AccountsControl
00193 void SDKTemplate::Scenario3_Aad::PrivacyPolicyInvoked(IUICommand^ command)
00194 {
00195     rootPage->NotifyUser("Privacy policy clicked by user", NotifyType::StatusMessage);
00196 }
00197
00198 // Displays other link message on clicking it in the AccountsControl
00199 void SDKTemplate::Scenario3_Aad::OtherLinkInvoked(IUICommand^ command)
00200 {
00201     rootPage->NotifyUser("Other link pressed by user", NotifyType::StatusMessage);
00202 }
00203
00204 // Create a new WebAccountManager WebTokenRequest based on the Provider, Scope, ClientID and then create a task to send
00205 // that request asynchronously to WebAccountManager's RequestTokenAsync API
00206 //
00207 // WebAccountManager will then try three steps, in order:
00208 //        (1): Check it's local cache to see if it has a valid token
00209 //        (2): Try to silently request a new token from the AAD service
00210 //        (3): Show the AAD UI for user interaction required (user credentials) before it may return a token.
00211 //
00212 // Because of WebAccountManager's ability to cache tokens, you should only need to call WebAccountManager when making token
00213 // based requests and not require the ability to store a cached token within your app.
00214 void SDKTemplate::Scenario3_Aad::AuthenticateWithRequestToken(WebAccountProvider^ passedProvider, String^ scope, String^ clientID)
00215 {
00216     rootPage->NotifyUser("Requested " + passedProvider->DisplayName + " from AccountsManager dialog.", NotifyType::StatusMessage);
00217
00218     auto wtr = ref new WebTokenRequest(passedProvider, scope, clientID);
00219
00220   //Include the resource for which the token is being requested as a property of WebTokenRequest
00221   wtr->Properties->Insert(L"resource", L"https://graph.windows.net");
00222
00223     // When our task finishes it will return result of the operation, and if successful it will contain a token
00224     // and WebAccount. We save the WebAccount as the "active" account.
00225     concurrency::create_task(WebAuthenticationCoreManager::RequestTokenAsync(wtr)).then([this](WebTokenRequestResult^ webTokenRequestResult)
00226     {
00227         if (webTokenRequestResult->ResponseStatus == WebTokenRequestStatus::Success)
00228         {
00229             if (webTokenRequestResult->ResponseData->GetAt(0)->WebAccount)
00230             {
00231                 if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
00232                 {
00233                     ApplicationData::Current->LocalSettings->Values->Remove(STORED_ACCOUNT_ID_KEY);
00234                 }
00235
00236                 WebAccount^ account = webTokenRequestResult->ResponseData->GetAt(0)->WebAccount;
00237                 SaveAccount(account);
00238             }
00239         }
00240
00241         OutputTokenResult(webTokenRequestResult);
00242     });
00243 }
00244
00245 // Create a new WebAccountManager WebTokenRequest based on the Provider, Scope, ClientID and then create a task to send
00246 // that request and the account to get the token for asynchronously to WebAccountManager's GetTokenSilentlyAsync API
00247 //
00248 // WebAccountManager's GetTokenSilentlyAsync will then try :
00249 //        (1): Check it's local cache to see if it has a valid token
00250 //        (2): Try to silently request a new token from the AAD service
00251 //        (3): Return a status of UserInteractionRequired if we need the user credentials
00252 //
00253 // Because of WebAccountManager's ability to cache tokens, you should only need to call WebAccountManager when making token
00254 // based requests and not require the ability to store a cached token within your app.
00255 void SDKTemplate::Scenario3_Aad::AuthenticateWithRequestTokenSilent(WebAccountProvider^ provider, String^ scope, String^ clientID, WebAccount^ account)
00256 {
00257     rootPage->NotifyUser("Requested " + provider->DisplayName + " from AccountsManager dialog.", NotifyType::StatusMessage);
00258
00259     auto wtr = ref new WebTokenRequest(provider, scope, clientID);
00260
00261     // When our task finishes it will return result of the operation, and if successful it will contain a token
00262     // and WebAccount. We save the WebAccount as the "active" account.
00263     concurrency::create_task(WebAuthenticationCoreManager::GetTokenSilentlyAsync(wtr, account)).then([this](WebTokenRequestResult^ webTokenRequestResult)
00264     {
00265         if (webTokenRequestResult->ResponseStatus == WebTokenRequestStatus::Success)
00266         {
00267             // Perform an operation with the token you just got
00268         }
00269
00270         OutputTokenResult(webTokenRequestResult);
00271     });
00272 }
00273
00274 // Displays the result of requesting a token asynchronously to the main page
00275 void SDKTemplate::Scenario3_Aad::OutputTokenResult(WebTokenRequestResult^ result)
00276 {
00277     if (result->ResponseStatus == WebTokenRequestStatus::Success)
00278     {
00279         rootPage->NotifyUser(result->ResponseStatus.ToString() + "!\nUser: " + result->ResponseData->GetAt(0)->WebAccount->Id + "\n    Token returned was: " + result->ResponseData->GetAt(0)->Token, NotifyType::StatusMessage);
00280     }
00281     else if (result->ResponseStatus == WebTokenRequestStatus::ProviderError)
00282     {
00283         // The account provider has passed us an error and we should handle it.
00284         rootPage->NotifyUser(result->ResponseStatus.ToString() + " " + result->ResponseError->ErrorCode + ": " + result->ResponseError->ErrorMessage, NotifyType::ErrorMessage);
00285     }
00286     else if (result->ResponseStatus == WebTokenRequestStatus::AccountProviderNotAvailable)
00287     {
00288         // The account provider is unavailable, this is a temporary error.
00289         rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::ErrorMessage);
00290     }
00291     else if (result->ResponseStatus == WebTokenRequestStatus::UserInteractionRequired)
00292     {
00293         // The account provider needs to display a UI, since we called request token silently we should call it
00294         // with RequestTokenAsync.
00295         rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::StatusMessage);
00296     }
00297     else if (result->ResponseStatus == WebTokenRequestStatus::UserCancel)
00298     {
00299         // The user cancelled the sign in process for the account provider, handle
00300         // that how you need to.
00301         rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::StatusMessage);
00302     }
00303     else
00304     {
00305         // An unexpected error was encountered
00306         rootPage->NotifyUser(result->ResponseStatus.ToString() + " " + result->ResponseError->ErrorCode + ": " + result->ResponseError->ErrorMessage, NotifyType::ErrorMessage);
00307     }
00308 }
00309
00310 // Saves the AccountId in LocalSettings and keeps an instance
00311 // of the WebAccount saved
00312 void SDKTemplate::Scenario3_Aad::SaveAccount(WebAccount^ account)
00313 {
00314     ApplicationData::Current->LocalSettings->Values->Insert(STORED_ACCOUNT_ID_KEY, account->Id);
00315     m_account = account;
00316
00317     // Update the UI
00318     button_SignIn->IsEnabled = false;
00319     button_GetTokenSilently->IsEnabled = true;
00320     button_ManageAccounts->IsEnabled = true;
00321     textblock_SignedInStatus->Text = "Signed in with:";
00322     textblock_SignedInStatus->Foreground = ref new SolidColorBrush(Windows::UI::Colors::Green);
00323     listview_SignedInAccounts->Items->Append(account->Id);
00324 }
00325
00326 // Signs out the account using the SignOutAsync Token Broker API
00327 // and removes our saved AccountId as it won't be valid when SignOutAsync finishes.
00328 void SDKTemplate::Scenario3_Aad::LogoffAndRemoveAccount()
00329 {
00330     if (m_account)
00331     {
00332         //concurrency::create_task(m_account->SignOutAsync(AAD_SCOPE_REQUESTED));
00333         m_account = nullptr;
00334     }
00335
00336     if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
00337     {
00338         rootPage->NotifyUser("Signed out account id: " + ApplicationData::Current->LocalSettings->Values->Lookup(STORED_ACCOUNT_ID_KEY), NotifyType::StatusMessage);
00339         ApplicationData::Current->LocalSettings->Values->Remove(STORED_ACCOUNT_ID_KEY);
00340
00341         // Update UI
00342         button_SignIn->IsEnabled = true;
00343         button_GetTokenSilently->IsEnabled = false;
00344         button_ManageAccounts->IsEnabled = false;
00345         textblock_SignedInStatus->Text = "Not signed in.";
00346         textblock_SignedInStatus->Foreground = ref new SolidColorBrush(Windows::UI::Colors::Red);
00347         listview_SignedInAccounts->Items->Clear();
00348     }
00349 }
Generated on Fri Nov 15 2024 22:21:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLInProcessWinRTComponent/cpp/cpp/SampleConfiguration.h Source File

  • WRLInProcessWinRTComponent
  • cpp
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "WRL In-process Windows Runtime Component";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LuminanceHeatmapEffect Member List

This is the complete list of members for LuminanceHeatmapEffect, including all inherited members.
CreateLuminanceHeatmapImpl(_Outptr_ IUnknown **ppEffectImpl) | LuminanceHeatmapEffect | [static]
dpi | LuminanceHeatmapEffect |
IFACEMETHODIMP_(UINT32) GetInputCount() const | LuminanceHeatmapEffect |
IFACEMETHODIMP_(ULONG) AddRef() | LuminanceHeatmapEffect |
IFACEMETHODIMP_(ULONG) Release() | LuminanceHeatmapEffect |
Initialize(_In_ ID2D1EffectContext *pContextInternal, _In_ ID2D1TransformGraph *pTransformGraph) | LuminanceHeatmapEffect |
LuminanceHeatmapEffect() | LuminanceHeatmapEffect | [private]
m_constants | LuminanceHeatmapEffect | [private]
m_dpi | LuminanceHeatmapEffect | [private]
m_drawInfo | LuminanceHeatmapEffect | [private]
m_effectContext | LuminanceHeatmapEffect | [private]
m_inputRect | LuminanceHeatmapEffect | [private]
m_refCount | LuminanceHeatmapEffect | [private]
MapInputRectsToOutputRect(_In_reads_(inputRectCount) CONST D2D1_RECT_L *pInputRects, _In_reads_(inputRectCount) CONST D2D1_RECT_L *pInputOpaqueSubRects, UINT32 inputRectCount, _Out_ D2D1_RECT_L *pOutputRect, _Out_ D2D1_RECT_L *pOutputOpaqueSubRect) | LuminanceHeatmapEffect |
MapInvalidRect(UINT32 inputIndex, D2D1_RECT_L invalidInputRect, _Out_ D2D1_RECT_L *pInvalidOutputRect) const | LuminanceHeatmapEffect |
MapOutputRectToInputRects(_In_ const D2D1_RECT_L *pOutputRect, _Out_writes_(inputRectCount) D2D1_RECT_L *pInputRects, UINT32 inputRectCount) const | LuminanceHeatmapEffect |
PrepareForRender(D2D1_CHANGE_TYPE changeType) | LuminanceHeatmapEffect |
QueryInterface(_In_ REFIID riid, _Outptr_ void **ppOutput) | LuminanceHeatmapEffect |
Register(_In_ ID2D1Factory1 *pFactory) | LuminanceHeatmapEffect | [static]
SetDrawInfo(_In_ ID2D1DrawInfo *pRenderInfo) | LuminanceHeatmapEffect |
SetGraph(_In_ ID2D1TransformGraph *pGraph) | LuminanceHeatmapEffect |
UpdateConstants() | LuminanceHeatmapEffect | [private]
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Launched Member List

This is the complete list of members for Scenario1_Launched, including all inherited members.
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario1_Launched
Scenario1_Launched() | Scenario1_Launched
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/HttpFilters/Project.idl Source File

  • HttpClient
  • HttpFilters

Project.idl

Go to the documentation of this file.
00001 namespace HttpFilters
00002 {
00003     enum MeteredConnectionPriority
00004     {
00005         Low = 0,
00006         Medium,
00007         High
00008     };
00009
00010     runtimeclass HttpRetryFilter : [default] Windows.Web.Http.Filters.IHttpFilter
00011     {
00012         HttpRetryFilter(Windows.Web.Http.Filters.IHttpFilter innerFilter);
00013     }
00014
00015     runtimeclass HttpMeteredConnectionFilter : [default] Windows.Web.Http.Filters.IHttpFilter
00016     {
00017         HttpMeteredConnectionFilter(Windows.Web.Http.Filters.IHttpFilter innerFilter);
00018         Boolean OptIn;
00019         static String MeteredConnectionPriorityPropertyName{ get; };
00020     }
00021 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LightSensor/cpp/Scenario1_DataEvents.xaml.cpp Source File

  • LightSensor
  • cpp

Scenario1_DataEvents.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_DataEvents.xaml.cpp
00014 // Implementation of the Scenario1_DataEvents class
00015 //
00016
00017 #include "pch.h"
00018 #include "Scenario1_DataEvents.xaml.h"
00019
00020 using namespace SDKTemplate;
00021
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Navigation;
00025 using namespace Windows::Devices::Sensors;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::UI::Core;
00028 using namespace Platform;
00029
00030 Scenario1_DataEvents::Scenario1_DataEvents() : rootPage(MainPage::Current), desiredReportInterval(0)
00031 {
00032     InitializeComponent();
00033
00034     sensor = LightSensor::GetDefault();
00035     if (sensor != nullptr)
00036     {
00037         // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
00038         // This value will be used later to activate the sensor.
00039         uint32 minReportInterval = sensor->MinimumReportInterval;
00040         desiredReportInterval = minReportInterval > 100 ? minReportInterval : 100;
00041     }
00042     else
00043     {
00044         rootPage->NotifyUser("No light sensor found", NotifyType::ErrorMessage);
00045     }
00046 }
00047
00048 /// <summary>
00049 /// Invoked when this page is about to be displayed in a Frame.
00050 /// </summary>
00051 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00052 /// property is typically used to configure the page.</param>
00053 void Scenario1_DataEvents::OnNavigatedTo(NavigationEventArgs^ e)
00054 {
00055     ScenarioEnableButton->IsEnabled = true;
00056     ScenarioDisableButton->IsEnabled = false;
00057 }
00058
00059 /// <summary>
00060 /// Invoked when this page is no longer displayed.
00061 /// </summary>
00062 /// <param name="e"></param>
00063 void Scenario1_DataEvents::OnNavigatedFrom(NavigationEventArgs^ e)
00064 {
00065     // If the navigation is external to the app do not clean up.
00066     // This can occur on Phone when suspending the app.
00067     if (e->NavigationMode == NavigationMode::Forward && e->Uri == nullptr)
00068     {
00069         return;
00070     }
00071
00072     if (ScenarioDisableButton->IsEnabled)
00073     {
00074         Window::Current->VisibilityChanged::remove(visibilityToken);
00075         sensor->ReadingChanged::remove(readingToken);
00076
00077         // Restore the default report interval to release resources while the sensor is not in use
00078         sensor->ReportInterval = 0;
00079     }
00080 }
00081
00082 /// <summary>
00083 /// This is the event handler for VisibilityChanged events. You would register for these notifications
00084 /// if handling sensor data when the app is not visible could cause unintended actions in the app.
00085 /// </summary>
00086 /// <param name="sender"></param>
00087 /// <param name="e">
00088 /// Event data that can be examined for the current visibility state.
00089 /// </param>
00090 void Scenario1_DataEvents::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
00091 {
00092     // The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
00093     if (ScenarioDisableButton->IsEnabled)
00094     {
00095         if (e->Visible)
00096         {
00097             // Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
00098             readingToken = sensor->ReadingChanged::add(ref new TypedEventHandler<LightSensor^, LightSensorReadingChangedEventArgs^>(this, &Scenario1_DataEvents::ReadingChanged));
00099         }
00100         else
00101         {
00102             // Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
00103             sensor->ReadingChanged::remove(readingToken);
00104         }
00105     }
00106 }
00107
00108 void Scenario1_DataEvents::ReadingChanged(LightSensor^ sender, LightSensorReadingChangedEventArgs^ e)
00109 {
00110     // We need to dispatch to the UI thread to display the output
00111     Dispatcher->RunAsync(
00112         CoreDispatcherPriority::Normal,
00113         ref new DispatchedHandler(
00114             [this, e]()
00115             {
00116                 LightSensorReading^ reading = e->Reading;
00117
00118                 ScenarioOutput_LUX->Text = reading->IlluminanceInLux.ToString();
00119             },
00120             CallbackContext::Any
00121             )
00122         );
00123 }
00124
00125 void Scenario1_DataEvents::ScenarioEnable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00126 {
00127     if (sensor != nullptr)
00128     {
00129         // Establish the report interval
00130         sensor->ReportInterval = desiredReportInterval;
00131
00132         visibilityToken = Window::Current->VisibilityChanged::add(ref new WindowVisibilityChangedEventHandler(this, &Scenario1_DataEvents::VisibilityChanged));
00133         readingToken = sensor->ReadingChanged::add(ref new TypedEventHandler<LightSensor^, LightSensorReadingChangedEventArgs^>(this, &Scenario1_DataEvents::ReadingChanged));
00134
00135         ScenarioEnableButton->IsEnabled = false;
00136         ScenarioDisableButton->IsEnabled = true;
00137     }
00138     else
00139     {
00140         rootPage->NotifyUser("No light sensor found", NotifyType::ErrorMessage);
00141     }
00142 }
00143
00144 void Scenario1_DataEvents::ScenarioDisable(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00145 {
00146     Window::Current->VisibilityChanged::remove(visibilityToken);
00147     sensor->ReadingChanged::remove(readingToken);
00148
00149     // Restore the default report interval to release resources while the sensor is not in use
00150     sensor->ReportInterval = 0;
00151
00152     ScenarioEnableButton->IsEnabled = true;
00153     ScenarioDisableButton->IsEnabled = false;
00154 }
Generated on Fri Nov 15 2024 22:17:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraResolution/cpp/Scenario2_PhotoSettings.xaml.cpp Source File

  • CameraResolution
  • cpp

Scenario2_PhotoSettings.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the Microsoft Public License.
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_PhotoSettings.xaml.h"
00014 #include "StreamResolutionHelper.h"
00015 #include <sstream>
00016
00017 using namespace Concurrency;
00018 using namespace Platform;
00019 using namespace SDKTemplate;
00020 using namespace Windows::Devices;
00021 using namespace Windows::Devices::Enumeration;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::Media::Capture;
00025 using namespace Windows::Media::MediaProperties;
00026 using namespace Windows::Storage;
00027 using namespace Windows::UI::Core;
00028 using namespace Windows::UI::Xaml;
00029 using namespace Windows::UI::Xaml::Controls;
00030 using namespace Windows::UI::Xaml::Controls::Primitives;
00031 using namespace Windows::UI::Xaml::Data;
00032 using namespace Windows::UI::Xaml::Input;
00033 using namespace Windows::UI::Xaml::Media;
00034 using namespace Windows::UI::Xaml::Navigation;
00035
00036 /// <summary>
00037 /// Initializes a new instance of the <see cref="Scenario2_EnableSettings"/> class.
00038 /// </summary>
00039 Scenario2_PhotoSettings::Scenario2_PhotoSettings()
00040     : _rootPage(MainPage::Current)
00041     , _mediaCapture(nullptr)
00042     , _isPreviewing(false)
00043     , _captureFolder(nullptr)
00044 {
00045     InitializeComponent();
00046 }
00047
00048 Scenario2_PhotoSettings::~Scenario2_PhotoSettings()
00049 {
00050     CleanupCameraAsync();
00051 }
00052
00053 void Scenario2_PhotoSettings::OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00054 {
00055     CleanupCameraAsync();
00056 }
00057
00058 /// <summary>
00059 /// Initializes the camera
00060 /// </summary>
00061 task<void> Scenario2_PhotoSettings::InitializeCameraAsync()
00062 {
00063     _mediaCapture = ref new MediaCapture();
00064     _mediaCaptureFailedEventToken =
00065         _mediaCapture->Failed += ref new MediaCaptureFailedEventHandler(this, &Scenario2_PhotoSettings::MediaCapture_Failed);
00066
00067     return create_task(_mediaCapture->InitializeAsync())
00068         .then([this]()
00069     {
00070         PreviewControl->Source = _mediaCapture.Get();
00071         return create_task(_mediaCapture->StartPreviewAsync());
00072     }).then([this]()
00073     {
00074         return create_task(StorageLibrary::GetLibraryAsync(KnownLibraryId::Pictures));
00075     }).then([this](StorageLibrary^ picturesLibrary)
00076     {
00077         _captureFolder = picturesLibrary->SaveFolder;
00078         if (_captureFolder == nullptr)
00079         {
00080             // In this case fall back to the local app storage since the Pictures Library is not available
00081             _captureFolder = ApplicationData::Current->LocalFolder;
00082         }
00083     }).then([this](task<void> previousTask)
00084     {
00085         try
00086         {
00087             _isPreviewing = true;
00088             previousTask.get();
00089             return previousTask;
00090         }
00091         catch (AccessDeniedException^)
00092         {
00093             _rootPage->Current->NotifyUser("The app was denied access to the camera", NotifyType::ErrorMessage);
00094             return CleanupCameraAsync();
00095         }
00096     });
00097 }
00098
00099 /// <summary>
00100 /// Cleans up the camera and state variables
00101 /// </summary>
00102 task<void> Scenario2_PhotoSettings::CleanupCameraAsync()
00103 {
00104     task<void> cleanupTask;
00105     if (_isPreviewing)
00106     {
00107         cleanupTask = create_task(_mediaCapture->StopPreviewAsync());
00108         _isPreviewing = false;
00109     }
00110     else
00111     {
00112         cleanupTask = create_task([]() {});
00113     }
00114
00115     return cleanupTask.then([this]()
00116     {
00117         if (_mediaCapture != nullptr)
00118         {
00119             _mediaCapture->Failed -= _mediaCaptureFailedEventToken;
00120             _mediaCapture = nullptr;
00121         }
00122     });
00123 }
00124
00125 /// <summary>
00126 /// Initializes the camera and populates the UI
00127 /// </summary>
00128 /// <param name="sender"></param>
00129 void Scenario2_PhotoSettings::InitializeCameraButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^)
00130 {
00131     Button^ button = static_cast<Button^>(sender);
00132     button->IsEnabled = false;
00133
00134     create_task(InitializeCameraAsync())
00135         .then([this, button]()
00136     {
00137         if (_isPreviewing)
00138         {
00139             button->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
00140             PreviewControl->Visibility = Windows::UI::Xaml::Visibility::Visible;
00141             CheckIfStreamsAreIdentical();
00142             PopulateComboBox(MediaStreamType::VideoPreview, PreviewSettings);
00143             PopulateComboBox(MediaStreamType::Photo, PhotoSettings, false);
00144             PhotoButton->IsEnabled = true;
00145         }
00146     });
00147 }
00148
00149 /// <summary>
00150 /// Takes a photo to and saves to a StorageFile
00151 /// </summary>
00152 void Scenario2_PhotoSettings::PhotoButton_Click(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^)
00153 {
00154     if (_isPreviewing)
00155     {
00156         // Disable the photo button while taking a photo
00157         PhotoButton->IsEnabled = false;
00158
00159         create_task(_captureFolder->CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption::GenerateUniqueName))
00160             .then([this](StorageFile^ file)
00161         {
00162             return create_task(_mediaCapture->CapturePhotoToStorageFileAsync(ImageEncodingProperties::CreateJpeg(), file))
00163                 .then([this, file]()
00164             {
00165                 // Done taking the photo, so re-enable the button
00166                 PhotoButton->IsEnabled = true;
00167
00168                 _rootPage->Current->NotifyUser(L"Photo taken, saved to: " + file->Path, NotifyType::StatusMessage);
00169             });
00170         }).then([this](task<void> previousTask)
00171         {
00172             try
00173             {
00174                 previousTask.get();
00175             }
00176             catch (Exception^ ex)
00177             {
00178                 // File I/O errors are reported as exceptions
00179                 _rootPage->Current->NotifyUser(L"Exception when taking a photo: " + ex->Message, NotifyType::ErrorMessage);
00180             }
00181         });
00182     }
00183 }
00184
00185 /// <summary>
00186 ///  Event handler for Preview settings combo box. Updates stream resolution based on the selection.
00187 /// </summary>
00188 /// <param name="sender"></param>
00189 void Scenario2_PhotoSettings::PreviewSettings_Changed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^)
00190 {
00191     if (_isPreviewing)
00192     {
00193         auto selectedItem = static_cast<ComboBoxItem^>(static_cast<ComboBox^>(sender)->SelectedItem);
00194         auto encodingProperties = static_cast<IMediaEncodingProperties^>(selectedItem->Tag);
00195         create_task(_rootPage->SetMediaStreamPropertiesAsync(_mediaCapture.Get(), PreviewControl, MediaStreamType::VideoPreview, encodingProperties));
00196     }
00197 }
00198
00199 /// <summary>
00200 /// Event handler for Photo settings combo box. Updates stream resolution based on the selection.
00201 /// </summary>
00202 /// <param name="sender"></param>
00203 void Scenario2_PhotoSettings::PhotoSettings_Changed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^)
00204 {
00205     if (_isPreviewing)
00206     {
00207         auto selectedItem = static_cast<ComboBoxItem^>(static_cast<ComboBox^>(sender)->SelectedItem);
00208         auto encodingProperties = static_cast<IMediaEncodingProperties^>(selectedItem->Tag);
00209         create_task(_rootPage->SetMediaStreamPropertiesAsync(_mediaCapture.Get(), PreviewControl, MediaStreamType::Photo, encodingProperties));
00210     }
00211 }
00212
00213 /// <summary>
00214 /// On some devices there may not be seperate streams for preview/photo/video. In this case, changing any of them
00215 /// will change all of them since they are the same stream
00216 /// </summary>
00217 void Scenario2_PhotoSettings::CheckIfStreamsAreIdentical()
00218 {
00219     if (_mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic == VideoDeviceCharacteristic::AllStreamsIdentical ||
00220         _mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic == VideoDeviceCharacteristic::PreviewPhotoStreamsIdentical)
00221     {
00222         _rootPage->Current->NotifyUser(L"Warning: Preview and photo streams for this device are identical, changing one will affect the other", NotifyType::ErrorMessage);
00223     }
00224 }
00225
00226 /// <summary>
00227 /// Populates the given combo box with all possible combinations of the given stream type settings returned by the camera driver
00228 /// </summary>
00229 /// <param name="streamType"></param>
00230 /// <param name="comboBox"></param>
00231 void Scenario2_PhotoSettings::PopulateComboBox(MediaStreamType streamType, ComboBox^ comboBox, bool showFrameRate)
00232 {
00233     // Query all properties of the device
00234     auto allProperties = _mediaCapture->VideoDeviceController->GetAvailableMediaStreamProperties(streamType);
00235
00236     // Populate the combo box with the entries
00237     for (auto encodingProperties : allProperties)
00238     {
00239         ComboBoxItem^ comboBoxItem = ref new ComboBoxItem();
00240         auto streamHelper = ref new StreamResolutionHelper(encodingProperties);
00241         comboBoxItem->Content = streamHelper->GetFriendlyName(showFrameRate);
00242         comboBoxItem->Tag = encodingProperties;
00243         comboBox->Items->Append(comboBoxItem);
00244     }
00245 }
00246
00247 void Scenario2_PhotoSettings::MediaCapture_Failed(MediaCapture^, MediaCaptureFailedEventArgs^ e)
00248 {
00249     String^ message = e->Message;
00250     Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, message]()
00251     {
00252         _rootPage->Current->NotifyUser("Preview stopped: " + message, NotifyType::ErrorMessage);
00253         _isPreviewing = false;
00254         CleanupCameraAsync();
00255     }));
00256 }
Generated on Fri Nov 15 2024 22:18:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cs/xBindSampleModel/EmployeeCollection.cs Source File

  • XamlBind
  • cs
  • xBindSampleModel

EmployeeCollection.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections;
00003 using System.Collections.Generic;
00004 using System.Collections.ObjectModel;
00005 using System.Collections.Specialized;
00006 using System.Linq;
00007 using Windows.Foundation.Collections;
00008
00009 namespace xBindSampleModel
00010 {
00011     public sealed class VectorChangedEventArgs : IVectorChangedEventArgs
00012     {
00013         public CollectionChange CollectionChange { get; set; }
00014         public uint Index { get; set; }
00015     }
00016
00017
00018     //Implements both IObservableVector and INotifyCollectionChanged and as its used from both C++ and C# apps
00019     public sealed class EmployeeCollection : Windows.Foundation.Collections.IObservableVector<IEmployee>, IList<IEmployee>, INotifyCollectionChanged, IList
00020     {
00021         private ObservableCollection<IEmployee> data;
00022         public event VectorChangedEventHandler<IEmployee> VectorChanged;
00023         public event NotifyCollectionChangedEventHandler CollectionChanged;
00024
00025         public EmployeeCollection()
00026         {
00027             data = new ObservableCollection<IEmployee>();
00028             data.CollectionChanged += Data_CollectionChanged;
00029         }
00030
00031         private void Data_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
00032         {
00033             if (VectorChanged != null)
00034             {
00035                 VectorChangedEventArgs args = new VectorChangedEventArgs();
00036                 args.CollectionChange = CollectionChange.Reset;
00037                 VectorChanged(this, args);
00038             }
00039
00040             if (CollectionChanged != null)
00041             {
00042                 CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
00043                 CollectionChanged(this, e);
00044             }
00045         }
00046
00047         #region IObservableVector
00048         //IObservableVector derives from IList<T> so most of the interface members are strongly typed
00049
00050         public IEmployee this[int index]
00051         {
00052             get { return data[index]; }
00053             set { data[index] = value; }
00054         }
00055
00056         public int Count { get { return data.Count; } }
00057         public bool IsReadOnly { get { return false; } }
00058
00059         public void Add(IEmployee item)
00060         {
00061             data.Add(item);
00062         }
00063
00064         public void Clear()
00065         {
00066             data.Clear();
00067         }
00068         public bool Contains(IEmployee item)
00069         {
00070             return data.Contains(item);
00071         }
00072
00073         public void CopyTo(IEmployee[] array, int arrayIndex)
00074         {
00075             data.CopyTo(array, arrayIndex);
00076         }
00077         public IEnumerator<IEmployee> GetEnumerator() { return data.GetEnumerator(); }
00078
00079         public int IndexOf(IEmployee item) { return data.IndexOf(item); }
00080
00081         public void Insert(int index, IEmployee item)
00082         {
00083             data.Insert(index, item);
00084         }
00085
00086         public bool Remove(IEmployee item)
00087         {
00088             return data.Remove(item);
00089         }
00090
00091         public void RemoveAt(int index)
00092         {
00093             data.RemoveAt(index);
00094         }
00095
00096         IEnumerator IEnumerable.GetEnumerator()
00097         {
00098             return data.GetEnumerator();
00099         }
00100         #endregion
00101
00102         #region INotifyCollectionChanged
00103         //INotifyCollection changed inherits from IList (non generic) so most of its members are not strongly typed
00104
00105         object IList.this[int index]
00106         {
00107             get { return data[index]; }
00108             set { data[index] = (Employee)value; }
00109         }
00110
00111         int ICollection.Count { get { return data.Count; } }
00112         bool IList.IsFixedSize { get { return false; } }
00113         bool ICollection.IsSynchronized { get { return false; } }
00114         object ICollection.SyncRoot { get { throw new NotImplementedException(); } }
00115
00116         int IList.Add(object item)
00117         {
00118             data.Add((IEmployee)item);
00119             return data.Count;
00120         }
00121
00122         bool IList.IsReadOnly { get { return false; } }
00123
00124         bool IList.Contains(object item) { return data.Contains(item); }
00125
00126         int IList.IndexOf(object item) { return data.IndexOf((IEmployee)item); }
00127
00128         void IList.Insert(int index, object item)
00129         {
00130             data.Insert(index, (IEmployee)item);
00131         }
00132
00133         void IList.Remove(object item)
00134         {
00135             data.Remove((IEmployee)item);
00136         }
00137
00138         void IList.Clear()
00139         {
00140             data.Clear();
00141         }
00142
00143         void IList.RemoveAt(int index)
00144         {
00145             data.RemoveAt(index);
00146         }
00147
00148         void ICollection.CopyTo(Array array, int index)
00149         {
00150             throw new NotImplementedException();
00151         }
00152         #endregion
00153     }
00154
00155     internal class MapChangedEventArgs<K> : IMapChangedEventArgs<K>
00156     {
00157         public CollectionChange CollectionChange { get; set; }
00158         public K Key { get; set; }
00159     }
00160
00161     public sealed class EmployeeDictionary : IDictionary<string, IEmployee>, IObservableMap<string, IEmployee>
00162     {
00163         private Dictionary<string, IEmployee> data = new Dictionary<string, IEmployee>();
00164         #region IObservable MAP
00165         public event MapChangedEventHandler<string, IEmployee> MapChanged;
00166
00167         private void FireMapChanged(CollectionChange change, string key)
00168         {
00169             if (MapChanged != null)
00170             {
00171                 MapChanged(this, new MapChangedEventArgs<string>() { CollectionChange = change, Key = key });
00172             }
00173         }
00174
00175         #endregion
00176
00177         #region Generic Dictionary
00178         public IEmployee this[string key]
00179         {
00180             get
00181             {
00182                 return data[key];
00183             }
00184             set
00185             {
00186                 data[key] = value;
00187                 FireMapChanged(CollectionChange.ItemChanged, key);
00188             }
00189         }
00190
00191         public int Count { get { return data.Count; } }
00192
00193         public bool IsReadOnly { get { return false; } }
00194
00195         public ICollection<string> Keys { get { return data.Keys; } }
00196
00197         public ICollection<IEmployee> Values { get { return data.Values; } }
00198
00199         public void Add(KeyValuePair<string, IEmployee> item)
00200         {
00201             data.Add(item.Key, item.Value);
00202             FireMapChanged(CollectionChange.ItemInserted, item.Key);
00203         }
00204
00205         public void Add(string key, IEmployee value)
00206         {
00207             data.Add(key, value);
00208             FireMapChanged(CollectionChange.ItemInserted, key);
00209         }
00210
00211         public void Clear()
00212         {
00213             data.Clear();
00214             FireMapChanged(CollectionChange.Reset, default(string));
00215         }
00216
00217         public bool Contains(KeyValuePair<string, IEmployee> item) { return data.Contains(item); }
00218
00219         public bool ContainsKey(string key) { return data.ContainsKey(key); }
00220
00221         public void CopyTo(KeyValuePair<string, IEmployee>[] array, int arrayIndex)
00222         {
00223             var keys = data.Keys.GetEnumerator();
00224             var values = data.Values.GetEnumerator();
00225             for (int i = 0; i < data.Count; i++)
00226             {
00227                 KeyValuePair<string, IEmployee> pair = new KeyValuePair<string, IEmployee>(keys.Current, values.Current);
00228                 array[arrayIndex + i] = pair;
00229                 keys.MoveNext();
00230                 values.MoveNext();
00231             }
00232         }
00233
00234         public IEnumerator<KeyValuePair<string, IEmployee>> GetEnumerator() { return data.GetEnumerator(); }
00235
00236         public bool Remove(KeyValuePair<string, IEmployee> item) { return Remove(item.Key); }
00237
00238         public bool Remove(string key)
00239         {
00240             bool removed = data.Remove(key);
00241             if (removed) { FireMapChanged(CollectionChange.ItemRemoved, key); }
00242             return removed;
00243         }
00244
00245         public bool TryGetValue(string key, out IEmployee value)
00246         {
00247             return data.TryGetValue(key, out value);
00248         }
00249
00250         IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)data).GetEnumerator(); }
00251         #endregion
00252
00253     }
00254
00255 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Level.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Level.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Level:
00015 // This is an abstract class from which all of the levels of the game are derived.
00016 // Each level potentially overrides up to four methods:
00017 //     Initialize - (required) takes a list of objects and enables the objects that
00018 //         are active for the level as well as setting their positions and
00019 //         any animations associated with the objects.
00020 //     Update - this method is called once per time step and is expected to
00021 //         determine if the level has been completed. The Level class provides
00022 //         a 'standard' Update method which checks each object that is a target
00023 //         and disables any active targets that have been hit. It returns true
00024 //         once there are no active targets remaining.
00025 //     SaveState - method to save any Level specific state. Default is defined as
00026 //         not saving any state.
00027 //     LoadState - method to restore any Level specific state. Default is defined
00028 //         as not restoring any state.
00029
00030 #include "GameObject.h"
00031 #include "PersistentState.h"
00032
00033 class Level
00034 {
00035 public:
00036     virtual void Initialize(
00037         std::vector<std::shared_ptr<GameObject>> const& objects
00038         ) = 0;
00039
00040     virtual bool Update(
00041         float time,
00042         float elapsedTime,
00043         float timeRemaining,
00044         std::vector<std::shared_ptr<GameObject>> const& objects
00045         );
00046
00047     virtual void SaveState(PersistentState& state);
00048     virtual void LoadState(PersistentState& state);
00049
00050     std::wstring const& Objective();
00051     float TimeLimit();
00052
00053 protected:
00054     std::wstring   m_objective;
00055     float          m_timeLimit;
00056 };
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicVoiceInput/cpp/pch.h Source File

  • HolographicVoiceInput
  • cpp

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 #pragma once
00012
00013 #include <agile.h>
00014 #include <array>
00015 #include <d2d1_2.h>
00016 #include <d3d11_4.h>
00017 #include <DirectXColors.h>
00018 #include <dwrite_2.h>
00019 #include <map>
00020 #include <mutex>
00021 #include <wincodec.h>
00022 #include <WindowsNumerics.h>
00023
00024 #include <wrl.h>
00025 #include <Mfidl.h>
00026 #include <Mfapi.h>
00027 #include <Mfreadwrite.h>
00028 #include <xaudio2.h>
00029 #include <xapo.h>
00030 #include <hrtfapoapi.h>
00031
00032 #include <collection.h>
00033 #include <vector>
00034 #include <ppltasks.h>
00035 #include "Common\PrintWstringToDebugConsole.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePicker/cpp/Scenario2_MultiFile.xaml.h Source File

  • FilePicker
  • cpp

Scenario2_MultiFile.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "pch.h"
00015 #include "Scenario2_MultiFile.g.h"
00016 #include "MainPage.xaml.h"
00017
00018 namespace SDKTemplate
00019 {
00020     public ref class Scenario2_MultiFile sealed
00021     {
00022     public:
00023         Scenario2_MultiFile();
00024
00025     private:
00026         MainPage^ rootPage;
00027
00028         void PickFilesButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00029     };
00030 }
Generated on Fri Nov 15 2024 22:19:45 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/LiveTiles/Notifications/SecondaryTiles/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • LiveTiles
  • Notifications
  • SecondaryTiles

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Notifications.Helpers;
00002 using System;
00003 using System.Linq;
00004 using Windows.Data.Xml.Dom;
00005 using Windows.UI.Notifications;
00006 using Windows.UI.StartScreen;
00007 using Windows.UI.Xaml;
00008 using Windows.UI.Xaml.Controls;
00009
00010 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00011
00012 namespace Notifications.ScenarioPages.LiveTiles.Notifications.SecondaryTiles
00013 {
00014     /// <summary>
00015     /// An empty page that can be used on its own or navigated to within a Frame.
00016     /// </summary>
00017     public sealed partial class ScenarioElement : UserControl
00018     {
00019         public ScenarioElement()
00020         {
00021             this.InitializeComponent();
00022         }
00023
00024         private string _tileId;
00025
00026         private void ButtonSendNotification_Click(object sender, RoutedEventArgs e)
00027         {
00028             string xml = $@"
00029                 <tile version='3'>
00030                     <visual branding='nameAndLogo'>
00031
00032                         <binding template='TileMedium'>
00033                             <text hint-wrap='true'>New tile notification</text>
00034                             <text hint-wrap='true' hint-style='captionSubtle'/>
00035                         </binding>
00036
00037                         <binding template='TileWide'>
00038                             <text hint-wrap='true'>New tile notification</text>
00039                             <text hint-wrap='true' hint-style='captionSubtle'/>
00040                         </binding>
00041
00042                         <binding template='TileLarge'>
00043                             <text hint-wrap='true'>New tile notification</text>
00044                             <text hint-wrap='true' hint-style='captionSubtle'/>
00045                         </binding>
00046
00047                 </visual>
00048             </tile>";
00049
00050             XmlDocument doc = new XmlDocument();
00051             doc.LoadXml(xml);
00052
00053             string nowTimeString = DateTime.Now.ToString();
00054
00055             // Assign date/time values through XmlDocument to avoid any xml escaping issues
00056             foreach (XmlElement textEl in doc.SelectNodes("//text").OfType<XmlElement>())
00057                 if (textEl.InnerText.Length == 0)
00058                     textEl.InnerText = nowTimeString;
00059
00060             TileNotification notification = new TileNotification(doc);
00061             TileUpdateManager.CreateTileUpdaterForSecondaryTile(_tileId).Update(notification);
00062         }
00063
00064         private async void ButtonPinTile_Click(object sender, RoutedEventArgs e)
00065         {
00066             base.IsEnabled = false;
00067
00068             _tileId = DateTime.Now.Ticks.ToString();
00069
00070             SecondaryTile tile = TilesHelper.GenerateSecondaryTile(_tileId, "Secondary notification");
00071             tile.VisualElements.ShowNameOnSquare150x150Logo = true;
00072             tile.VisualElements.ShowNameOnSquare310x310Logo = true;
00073             tile.VisualElements.ShowNameOnWide310x150Logo = true;
00074             await tile.RequestCreateAsync();
00075
00076             stepsControl.Step++;
00077             base.IsEnabled = true;
00078         }
00079     }
00080 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TextSuggestion/cs/Scenario2_Prediction.xaml.cs Source File

  • TextSuggestion
  • cs

Scenario2_Prediction.xaml.cs

Go to the documentation of this file.
00001 // Copyright (c) Microsoft Corporation. All rights reserved
00002
00003 using System;
00004 using Windows.Data.Text;
00005 using Windows.UI.Xaml;
00006 using Windows.UI.Xaml.Controls;
00007 using Windows.UI.Xaml.Navigation;
00008 using SDKTemplate;
00009
00010 namespace TextSuggestion
00011 {
00012     public sealed partial class Scenario2_Prediction : Page
00013     {
00014         private MainPage rootPage;
00015         private TextPredictionGenerator generator;
00016
00017         /// <summary>
00018         /// Page initializer.
00019         /// </summary>
00020         public Scenario2_Prediction()
00021         {
00022             this.InitializeComponent();
00023         }
00024
00025         /// <summary>
00026         /// Clean up the notification area when user navigate to prediction page
00027         /// </summary>
00028         /// <param name="e">Event data that describes the click action on the button.</param>
00029         protected override void OnNavigatedTo(NavigationEventArgs e)
00030         {
00031             rootPage = MainPage.Current;
00032
00033             // Clean notification area.
00034             rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
00035         }
00036
00037         /// <summary>
00038         /// This is the click handler for the 'Execute' button.
00039         /// When this button is activated, the text suggestion generator will get
00040         /// the prediction result for given input string and language tag, then
00041         /// print them in result column.
00042         /// Using 'async' keyword to indicate that this method runs asynchronously
00043         /// and contains one 'await' expression.
00044         /// </summary>
00045         /// <param name="sender">The object that raised the event.</param>
00046         /// <param name="e">Event data that describes the click action on the button.</param>
00047         private async void Execute_Click(object sender, RoutedEventArgs e)
00048         {
00049             // Clean up result column.
00050             resultView.ItemsSource = null;
00051
00052             // Clean notification area.
00053             rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
00054
00055             var input = Input.Text;
00056
00057             ComboBoxItem selectedItem = methods.SelectedItem as ComboBoxItem;
00058
00059             if ((generator != null) && (selectedItem != null) && !String.IsNullOrEmpty(input))
00060             {
00061                 // Specifiy the candidate number to get.
00062                 if ((selectedItem.Tag != null) && selectedItem.Tag.ToString().Equals("needMaxCount"))
00063                 {
00064                     uint MaxCandidates = 0;
00065                     UInt32.TryParse(maxCandidates.Text, out MaxCandidates);
00066
00067                     if (MaxCandidates != 0)
00068                     {
00069                         // Call the API with max candidate number user expect, and list the result when there are any candidates.
00070                         // Using 'await' expression here to suspend the execution of this method until the awaited task completes.
00071                         resultView.ItemsSource = await generator.GetCandidatesAsync(input, MaxCandidates);
00072
00073                         if (resultView.Items.Count == 0)
00074                         {
00075                             rootPage.NotifyUser(string.Format("No candidates."), NotifyType.StatusMessage);
00076                         }
00077                     }
00078                     else
00079                     {
00080                         rootPage.NotifyUser(string.Format("Not a valid candidate number. Expecting positive integer."), NotifyType.ErrorMessage);
00081                     }
00082                 }
00083                 else
00084                 {
00085                     // Call the API with default candidate number, and list the result when there are any candidates.
00086                     resultView.ItemsSource = await generator.GetCandidatesAsync(input);
00087
00088                     if (resultView.Items.Count == 0)
00089                     {
00090                         rootPage.NotifyUser(string.Format("No candidates."), NotifyType.StatusMessage);
00091                     }
00092                 }
00093             }
00094         }
00095
00096         /// <summary>
00097         /// Selecting the API interface to use.
00098         /// User can either specify the max candidate number to get, or use the default value.
00099         /// </summary>
00100         /// <param name="sender">The object that raised the event.</param>
00101         /// <param name="e">Event data that describes the click action on the button.</param>
00102         private void Methods_SelectionChanged(object sender, SelectionChangedEventArgs e)
00103         {
00104             ComboBoxItem selectedItem = methods.SelectedItem as ComboBoxItem;
00105
00106             if (maxCandidatesArea != null)
00107             {
00108                 // Only show the candidate number input control when user chooses to specify the number.
00109                 if ((selectedItem.Tag != null) && selectedItem.Tag.ToString().Equals("needMaxCount"))
00110                 {
00111                     maxCandidatesArea.Visibility = Visibility.Visible;
00112                 }
00113                 else
00114                 {
00115                     maxCandidatesArea.Visibility = Visibility.Collapsed;
00116                 }
00117             }
00118         }
00119
00120         /// <summary>
00121         /// This is the click handler for the 'Create Generator' button.
00122         /// When this button is activated, the Text Suggestion API will try
00123         /// to resolve the language tag provided by the user, and create a
00124         /// Prediction Generator.
00125         /// </summary>
00126         /// <param name="sender">The object that raised the event.</param>
00127         /// <param name="e">Event data that describes the click action on the button.</param>
00128         private void CreateGeneratorButton_Click(object sender, RoutedEventArgs e)
00129         {
00130             // Try to parse the language and create generator accordingly.
00131             generator = new TextPredictionGenerator(langTag.Text);
00132
00133             // Only allow generator operation when the language is available and installed.
00134             if (generator == null)
00135             {
00136                 if (GeneratorOperationArea != null)
00137                 {
00138                     GeneratorOperationArea.Visibility = Visibility.Collapsed;
00139                 }
00140
00141                 rootPage.NotifyUser(string.Format("Failed to instantiate a generator."), NotifyType.ErrorMessage);
00142             }
00143             else if (generator.ResolvedLanguage == "und")
00144             {
00145                 if (GeneratorOperationArea != null)
00146                 {
00147                     GeneratorOperationArea.Visibility = Visibility.Collapsed;
00148                 }
00149
00150                 rootPage.NotifyUser(string.Format("Unsupported language."), NotifyType.ErrorMessage);
00151             }
00152             else if (generator.LanguageAvailableButNotInstalled)
00153             {
00154                 if (GeneratorOperationArea != null)
00155                 {
00156                     GeneratorOperationArea.Visibility = Visibility.Collapsed;
00157                 }
00158
00159                 rootPage.NotifyUser(string.Format("Language available but not installed."), NotifyType.ErrorMessage);
00160             }
00161             else
00162             {
00163                 if (GeneratorOperationArea != null)
00164                 {
00165                     GeneratorOperationArea.Visibility = Visibility.Visible;
00166                 }
00167
00168                 rootPage.NotifyUser(string.Format("Successfully instantiated a generator."), NotifyType.StatusMessage);
00169             }
00170         }
00171     }
00172 }
Generated on Fri Nov 15 2024 22:21:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cppwinrt/DataHelpers.cpp Source File

  • BarcodeScanner
  • cppwinrt

DataHelpers.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <sstream>
00014 #include <iomanip>
00015 #include "DataHelpers.h"
00016
00017 namespace winrt
00018 {
00019     using namespace Windows::Storage::Streams;
00020     using namespace Windows::Devices::PointOfService;
00021 }
00022
00023 std::wstring GetDataString(winrt::IBuffer const& data)
00024 {
00025     if (!data)
00026     {
00027         return L"No data";
00028     }
00029
00030     // Just to show that we have the raw data, we'll print the value of the bytes.
00031     // Arbitrarily limit the number of bytes printed so the UI isn't overloaded.
00032     const unsigned int MAX_BYTES_TO_PRINT = 20;
00033     unsigned int byteCount = (std::min)(data.Length(), MAX_BYTES_TO_PRINT);
00034
00035     std::wstringstream buffer;
00036     buffer << std::setfill(L'0') << std::hex;
00037     for (uint32_t value : winrt::array_view(data.data(), byteCount))
00038     {
00039         buffer << std::setw(2) << value  << L" ";
00040     }
00041
00042     if (byteCount < data.Length())
00043     {
00044         buffer << L"...";
00045     }
00046
00047     return buffer.str();
00048 }
00049
00050 winrt::hstring GetDataLabelString(winrt::IBuffer const& data, uint32_t scanDataType)
00051 {
00052     // Only certain data types contain encoded text.
00053     //   To keep this simple, we'll just decode a few of them.
00054     if (!data)
00055     {
00056         return L"No data";
00057     }
00058
00059     if (scanDataType == winrt::BarcodeSymbologies::Upca() ||
00060         scanDataType == winrt::BarcodeSymbologies::UpcaAdd2() ||
00061         scanDataType == winrt::BarcodeSymbologies::UpcaAdd5() ||
00062         scanDataType == winrt::BarcodeSymbologies::Upce() ||
00063         scanDataType == winrt::BarcodeSymbologies::UpceAdd2() ||
00064         scanDataType == winrt::BarcodeSymbologies::UpceAdd5() ||
00065         scanDataType == winrt::BarcodeSymbologies::Ean8() ||
00066         scanDataType == winrt::BarcodeSymbologies::TfStd() ||
00067         scanDataType == winrt::BarcodeSymbologies::OcrA() ||
00068         scanDataType == winrt::BarcodeSymbologies::OcrB())
00069     {
00070         // The UPC, EAN8, and 2 of 5 families encode the digits 0..9
00071         // which are then sent to the app in a UTF8 string (like "01234")
00072
00073         // This is not an exhaustive list of symbologies that can be converted to a string
00074
00075         winrt::DataReader reader = winrt::DataReader::FromBuffer(data);
00076         return reader.ReadString(data.Length());
00077     }
00078     else
00079     {
00080         // Some other symbologies (typically 2-D symbologies) contain binary data that
00081         //  should not be converted to text.
00082         return winrt::hstring{ L"Decoded data unavailable. Raw label data: " + GetDataString(data) };
00083     }
00084 }
Generated on Fri Nov 15 2024 22:18:28 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Calendar/cpp/Scenario5_TimeZone.xaml.cpp Source File

  • Calendar
  • cpp

Scenario5_TimeZone.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario5_TimeZone.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Platform::Collections;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::Globalization;
00021
00022 Scenario5_TimeZone::Scenario5_TimeZone()
00023 {
00024     InitializeComponent();
00025 }
00026
00027 String^ Scenario5_TimeZone::ReportCalendarData(Calendar^ calendar)
00028 {
00029     // Display individual date/time elements.
00030     return
00031         "In " + calendar->GetTimeZone() +
00032         " time zone:   " + calendar->DayOfWeekAsSoloString() +
00033         "   " + calendar->MonthAsSoloString() +
00034         " " + calendar->DayAsPaddedString(2) +
00035         ", " + calendar->YearAsString() +
00036         "   " + calendar->HourAsPaddedString(2) +
00037         ":" + calendar->MinuteAsPaddedString(2) +
00038         ":" + calendar->SecondAsPaddedString(2) +
00039         " " + calendar->PeriodAsString() +
00040         "  " + calendar->TimeZoneAsString(3) +
00041         "\n";
00042 }
00043
00044 void Scenario5_TimeZone::ShowResults_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00045 {
00046     // This scenario illustrates time zone support in Windows.Globalization.Calendar class
00047
00048     // Displayed time zones in addition to the local time zone.
00049     String^ timeZones[] = { "UTC", "America/New_York", "Asia/Kolkata" };
00050
00051     // Store results here.
00052     String^ results = "";
00053
00054     // Create default Calendar object
00055     Calendar^ calendar = ref new Calendar();
00056     String^ localTimeZone = calendar->GetTimeZone();
00057
00058     // Show current time in local time zone
00059     results += "Current date and time:\n";
00060     results += ReportCalendarData(calendar) + "\n";
00061
00062     // Show current time in additional time zones
00063     for (String^ timeZone : timeZones)
00064     {
00065         calendar->ChangeTimeZone(timeZone);
00066         results += ReportCalendarData(calendar);
00067     }
00068     results += "\n";
00069
00070     // Change back to local time zone
00071     calendar->ChangeTimeZone(localTimeZone);
00072
00073     // Show a time on 14th day of second month of next year.
00074     // Note the effect of daylight saving time on the results.
00075     results += "Same time on 14th day of second month of next year:\n";
00076     calendar->AddYears(1); calendar->Month = 2; calendar->Day = 14;
00077     results += ReportCalendarData(calendar);
00078     for (String^ timeZone : timeZones)
00079     {
00080         calendar->ChangeTimeZone(timeZone);
00081         results += ReportCalendarData(calendar);
00082     }
00083     results += "\n";
00084
00085     // Change back to local time zone
00086     calendar->ChangeTimeZone(localTimeZone);
00087
00088     // Show a time on 14th day of tenth month of next year.
00089     // Note the effect of daylight saving time on the results.
00090     results += "Same time on 14th day of tenth month of next year:\n";
00091     calendar->AddMonths(8);
00092     results += ReportCalendarData(calendar);
00093     for (String^ timeZone : timeZones)
00094     {
00095         calendar->ChangeTimeZone(timeZone);
00096         results += ReportCalendarData(calendar);
00097     }
00098     results += "\n";
00099
00100     // Display the results
00101     OutputTextBlock->Text = results;
00102 }
Generated on Fri Nov 15 2024 22:18:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileThumbnails/cpp/pch.cpp Source File

  • FileThumbnails
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomHidDeviceAccess/cs/SampleConfiguration.cs Source File

  • CustomHidDeviceAccess
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using CustomHidDeviceAccess;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "CustomHidDeviceAccess";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title = "Connecting To Device", ClassType = typeof(DeviceConnect) },
00026             new Scenario() { Title = "Feature Reports", ClassType = typeof(FeatureReports) },
00027             new Scenario() { Title = "Input Report Events", ClassType = typeof(InputReportEvents) },
00028             new Scenario() { Title = "Input and Output Reports", ClassType = typeof(InputOutputReports) }
00029         };
00030     }
00031
00032     public class Scenario
00033     {
00034         public string Title { get; set; }
00035         public Type ClassType { get; set; }
00036     }
00037 }
00038
00039 namespace CustomHidDeviceAccess
00040 {
00041     public enum DeviceType
00042     {
00043         SuperMutt,
00044         Any,    // Can be any device
00045         None
00046     }
00047
00048     public class OnDeviceConnectedEventArgs
00049     {
00050         private Boolean isDeviceSuccessfullyConnected;
00051         private Windows.Devices.Enumeration.DeviceInformation deviceInformation;
00052
00053         public OnDeviceConnectedEventArgs(Boolean isDeviceSuccessfullyConnected, Windows.Devices.Enumeration.DeviceInformation deviceInformation)
00054         {
00055             this.isDeviceSuccessfullyConnected = isDeviceSuccessfullyConnected;
00056             this.deviceInformation = deviceInformation;
00057         }
00058
00059         public Boolean IsDeviceSuccessfullyConnected
00060         {
00061             get
00062             {
00063                 return isDeviceSuccessfullyConnected;
00064             }
00065         }
00066
00067         public Windows.Devices.Enumeration.DeviceInformation DeviceInformation
00068         {
00069             get
00070             {
00071                 return deviceInformation;
00072             }
00073         }
00074     }
00075
00076     public class DeviceProperties
00077     {
00078         public const String DeviceInstanceId = "System.Devices.DeviceInstanceId";
00079     }
00080
00081     /// <summary>
00082     /// This is the report descriptor for the support SuperMutt device
00083     ///
00084     /// 0x06, 0xAA, 0xFF,             // USAGE_PAGE (Vendor Defined Page 1)
00085     /// 0x09, 0x01,                   // USAGE (Vendor Usage  1)
00086     /// 0xa1, 0x01,                   // COLLECTION (Application)
00087     /// 0x85, 0x01,                   //     REPORT_ID (1)
00088     /// 0xa1, 0x00,                   //  COLLECTION (Physical)
00089     /// 0x05, 0x09,                   //     USAGE_PAGE (Button)
00090     /// 0x19, 0x01,                   //     USAGE_MINIMUM (Button 1)
00091     /// 0x29, 0x04,                   //     USAGE_MAXIMUM (Button 4)
00092     /// 0x15, 0x00,                   //     LOGICAL_MINIMUM (0)
00093     /// 0x25, 0x01,                   //     LOGICAL_MAXIMUM (1)
00094     /// 0x75, 0x01,                   //     REPORT_SIZE (1)
00095     /// 0x95, 0x04,                   //     REPORT_COUNT (4)
00096     /// 0x81, 0x02,                   //     INPUT (Data,Var,Abs)
00097     /// 0x05, 0x0c,                   //     USAGE_PAGE (Consumer Devices)
00098     /// 0x09, 0xe0,                   //     USAGE (Volume)
00099     /// 0x15, 0x00,                   //     LOGICAL_MINIMUM (0)
00100     /// 0x25, 0x0a,                   //     LOGICAL_MAXIMUM (10)
00101     /// 0x35, 0x00,                   //     PHYSICAL_MINIMUM (0)
00102     /// 0x45, 0x64,                   //     PHYSICAL_MAXIMUM (100)
00103     /// 0x75, 0x04,                   //     REPORT_SIZE (4)
00104     /// 0x95, 0x01,                   //     REPORT_COUNT (1)
00105     /// 0x81, 0x02,                   //     INPUT (Data,Var,Abs)
00106     /// 0xc0,                         //  END_COLLECTION
00107     /// 0xa1, 0x00,                   //  COLLECTION (Physical)
00108     /// 0x05, 0x09,                   //     USAGE_PAGE (Button)
00109     /// 0x19, 0x01,                   //     USAGE_MINIMUM (Button 1)
00110     /// 0x29, 0x04,                   //     USAGE_MAXIMUM (Button 4)
00111     /// 0x15, 0x00,                   //     LOGICAL_MINIMUM (0)
00112     /// 0x25, 0x01,                   //     LOGICAL_MAXIMUM (1)
00113     /// 0x75, 0x01,                   //     REPORT_SIZE (1)
00114     /// 0x95, 0x04,                   //     REPORT_COUNT (4)
00115     /// 0x91, 0x02,                   //     OUTPUT (Data,Var,Abs)
00116     /// 0x05, 0x0c,                   //     USAGE_PAGE (Consumer Devices)
00117     /// 0x09, 0xe0,                   //     USAGE (Volume)
00118     /// 0x15, 0x00,                   //     LOGICAL_MINIMUM (0)
00119     /// 0x25, 0x0a,                   //     LOGICAL_MAXIMUM (10)
00120     /// 0x35, 0x00,                   //     PHYSICAL_MINIMUM (0)
00121     /// 0x45, 0x64,                   //     PHYSICAL_MAXIMUM (100)
00122     /// 0x75, 0x04,                   //     REPORT_SIZE (4)
00123     /// 0x95, 0x01,                   //     REPORT_COUNT (1)
00124     /// 0x91, 0x02,                   //     OUTPUT (Data,Var,Abs)
00125     /// 0xc0,                         //  END_COLLECTION
00126     /// 0xa1, 0x02,                   //  COLLECTION (Logical)
00127     /// 0x85, 0x03,                   //     REPORT_ID (3)
00128     /// 0x06, 0xAA, 0xff,             //     USAGE_PAGE (Vendor Defined Page 1)
00129     /// 0x09, 0x01,                   //     USAGE (Vendor Usage  1)
00130     /// 0x15, 0x00,                   //     LOGICAL_MINIMUM (0)
00131     /// 0x25, 0x01,                   //     LOGICAL_MAXIMUM (1)
00132     /// 0x75, 0x01,                   //     REPORT_SIZE (1)
00133     /// 0x95, 0x01,                   //     REPORT_COUNT (1)
00134     /// 0x91, 0x02,                   //     OUTPUT (Data,Var,Abs)
00135     /// 0x95, 0x07,                   //     REPORT_COUNT (7)
00136     /// 0x91, 0x07,                   //     OUTPUT (Cnst,Var,Rel)
00137     /// 0xc0,                         //    END_COLLECTION
00138     /// 0xa1, 0x02,                   //  COLLECTION (Logical)
00139     /// 0x85, 0x04,                   //     REPORT_ID (4)
00140     /// 0x06, 0xAA, 0xff,             //     USAGE_PAGE (Vendor Defined Page 1)
00141     /// 0x09, 0x01,                   //     USAGE (Vendor Usage  1)
00142     /// 0x15, 0x00,                   //     LOGICAL_MINIMUM (0)
00143     /// 0x26, 0xff, 0x00,             //     LOGICAL_MAXIMUM (255)
00144     /// 0x75, 0x08,                   //     REPORT_SIZE (8)
00145     /// 0x95, 0x01,                   //     REPORT_COUNT (1)
00146     /// 0xb1, 0x02,                   //     FEATURE (Data,Var,Abs)
00147     /// 0xc0,                         //    END_COLLECTION
00148     /// 0x06, 0xDD, 0xff,             //   USAGE_PAGE (Vendor Defined Page 1)
00149     /// 0x09, 0x01,                   //   USAGE (Vendor Usage  1)
00150     /// 0xa1, 0x02,                   //  COLLECTION (Logical)
00151     /// 0x85, 0xff,                   //   REPORT_ID (255)
00152     /// 0x09, 0x01,                   //   USAGE (Vendor Usage  1)
00153     /// 0x15, 0x00,                   //   LOGICAL_MINIMUM (0)
00154     /// 0x26, 0xff, 0x00,             //   LOGICAL_MAXIMUM (255)
00155     /// 0x75, 0x08,                   //   REPORT_SIZE (8)
00156     /// 0x95, 0x01,                   //   REPORT_COUNT (1)
00157     /// 0xb1, 0x02,                   //   FEATURE (Data,Var,Abs)
00158     /// 0xc0,                          //  END_COLLECTION
00159     /// 0xc0                          // END_COLLECTION
00160     /// </summary>
00161     public class SuperMutt
00162     {
00163         /// <summary>
00164         /// Only available for Feature Reports
00165         /// </summary>
00166         public class LedPattern
00167         {
00168             public const UInt16 ReportId = 0x04;
00169             public const UInt16 UsagePage = 0xFF00;
00170             public const UInt16 UsageId = 0x01;
00171         }
00172
00173         /// <summary>
00174         /// Only available for Input/Output Reports
00175         /// </summary>
00176         public class ReadWriteBufferControlInformation
00177         {
00178             public const UInt16 ReportId = 0x01;
00179             public const UInt16 VolumeUsagePage = 0x0C;
00180             public const UInt16 VolumeUsageId = 0xE0;
00181             public const Byte VolumeDataStartBit = 4;  // Numeric data starts on bit 4
00182
00183             public const UInt16 ButtonUsagePage = 0x09;
00184
00185             /// <summary>
00186             /// Usage id corresponding to each button
00187             /// 0x19, 0x01,                   //     USAGE_MINIMUM (Button 1)
00188             /// 0x29, 0x04,                   //     USAGE_MAXIMUM (Button 4)
00189             /// </summary>
00190             public static UInt16[] ButtonUsageId = { 1, 2, 3, 4 };
00191
00192             public static Byte[] ButtonDataMask = {
00193                 0x01, // Button 1
00194                 0x02, // Button 2
00195                 0x04, // Button 3
00196                 0x08, // Button 4
00197             };
00198         }
00199
00200         /// <summary>
00201         /// Only available for output reports. The report Id is used to start and stop
00202         /// device input reports.
00203         /// Data:   0x01 will enable input reports
00204         //          0x00 will disable input reports
00205         /// </summary>
00206         public class DeviceInputReportControlInformation
00207         {
00208             public const UInt16 ReportId = 0x03;
00209             public const UInt16 UsagePage = 0xFF00;
00210             public const UInt16 UsageId = 0x01;
00211
00212             /// <summary>
00213             /// Values used to turn on/off the device interrupts
00214             /// </summary>
00215             public const Byte DataTurnOn = 0x01;
00216             public const Byte DataTurnOff = 0x00;
00217         }
00218
00219         public class Device
00220         {
00221             public const UInt16 Vid = 0x045E;
00222             public const UInt16 Pid = 0x0610;
00223             public const UInt16 UsagePage = 0xFFAA;
00224             public const UInt16 UsageId = 0x01;
00225         }
00226     }
00227 }
Generated on Fri Nov 15 2024 22:17:24 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_NavToFiles Member List

This is the complete list of members for Scenario5_NavToFiles, including all inherited members.
LoadFromLocalState_Click() | Scenario5_NavToFiles | [inline, private]
LoadFromPackage_Click() | Scenario5_NavToFiles | [inline, private]
rootPage | Scenario5_NavToFiles | [private]
Scenario5_NavToFiles() | Scenario5_NavToFiles | [inline]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cs/PlugInFilter.cs Source File

  • HttpClient
  • cs

PlugInFilter.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Runtime.InteropServices.WindowsRuntime;
00014 using Windows.Foundation;
00015 using Windows.Web.Http;
00016 using Windows.Web.Http.Filters;
00017
00018 namespace SDKTemplate
00019 {
00020     public sealed class PlugInFilter : IHttpFilter
00021     {
00022         private IHttpFilter innerFilter;
00023
00024         public PlugInFilter(IHttpFilter innerFilter)
00025         {
00026             if (innerFilter == null)
00027             {
00028                 throw new ArgumentException("innerFilter cannot be null.");
00029             }
00030             this.innerFilter = innerFilter;
00031         }
00032
00033         public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request)
00034         {
00035             return AsyncInfo.Run<HttpResponseMessage, HttpProgress>(async (cancellationToken, progress) =>
00036             {
00037                 request.Headers.Add("Custom-Header", "CustomRequestValue");
00038                 HttpResponseMessage response = await innerFilter.SendRequestAsync(request).AsTask(cancellationToken, progress);
00039
00040                 cancellationToken.ThrowIfCancellationRequested();
00041
00042                 response.Headers.Add("Custom-Header", "CustomResponseValue");
00043                 return response;
00044             });
00045         }
00046
00047         public void Dispose()
00048         {
00049             innerFilter.Dispose();
00050             GC.SuppressFinalize(this);
00051         }
00052     }
00053 }
Generated on Fri Nov 15 2024 22:19:59 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomHidDeviceAccess/cpp/Scenario3_InputReportEvents.xaml.cpp Source File

  • CustomHidDeviceAccess
  • cpp

Scenario3_InputReportEvents.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 //
00008 // Scenario3.xaml.cpp
00009 // Implementation of the Scenario3 class
00010 //
00011
00012 #include "pch.h"
00013 #include "Utilities.h"
00014 #include "Scenario3_InputReportEvents.xaml.h"
00015 #include "MainPage.xaml.h"
00016
00017 using namespace SDKTemplate;
00018
00019 using namespace Platform;
00020 using namespace Platform::Collections;
00021 using namespace Concurrency;
00022 using namespace Windows::Devices::Enumeration;
00023 using namespace Windows::Devices::HumanInterfaceDevice;
00024 using namespace Windows::Foundation;
00025 using namespace Windows::Storage::Streams;
00026 using namespace Windows::UI::Core;
00027 using namespace Windows::UI::Xaml;
00028 using namespace Windows::UI::Xaml::Controls;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 InputReportEvents::InputReportEvents(void) :
00032     isRegisteredForInputReportEvents(false),
00033     numInputReportEventsReceived(0),
00034     navigatedAway(false),
00035     registeredDevice(nullptr)
00036 {
00037     InitializeComponent();
00038 }
00039
00040 /// <summary>
00041 /// Invoked when this page is about to be displayed in a Frame.
00042 ///
00043 /// We will enable/disable parts of the UI if the device doesn't support it.
00044 ///
00045 /// The SuperMutt requires an output report to tell the device to start sending interrupts, so we will start it
00046 /// just in case we register for the events. We want this to be transparent because it doesn't demonstrate how
00047 /// to register for events.
00048 /// </summary>
00049 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00050 /// property is typically used to configure the page.</param>
00051 void InputReportEvents::OnNavigatedTo(NavigationEventArgs^ /* e */)
00052 {
00053     navigatedAway = false;
00054
00055     // We will disable the scenario that is not supported by the device.
00056     // If no devices are connected, none of the scenarios will be shown and an error will be displayed
00057     Platform::Collections::Map<DeviceType, UIElement^>^ deviceScenarios = ref new Platform::Collections::Map<DeviceType, UIElement^>();
00058     deviceScenarios->Insert(DeviceType::SuperMutt, SuperMuttScenario);
00059
00060     Utilities::SetUpDeviceScenarios(deviceScenarios, DeviceScenarioContainer);
00061
00062     // Get notified when the device is about to be closed so we can unregister eventd
00063     EventHandlerForDevice::Current->OnDeviceClose =
00064         ref new TypedEventHandler<EventHandlerForDevice^, DeviceInformation^>(this, &InputReportEvents::OnDeviceClosing);
00065
00066     UpdateRegisterEventButtons();
00067 }
00068
00069 /// <summary>
00070 /// Reset the device into a known state by undoing everything we did to the device (unregister interrupts and
00071 /// stop the device from creating interrupts)
00072 /// </summary>
00073 /// <param name="e"></param>
00074 void InputReportEvents::OnNavigatedFrom(NavigationEventArgs^ /* e */)
00075 {
00076     navigatedAway = true;
00077
00078     if (EventHandlerForDevice::Current->IsDeviceConnected)
00079     {
00080         UnregisterFromInputReportEvent();
00081
00082         // Stop interrupts after unregistering so that device interrupts do not effect the scenario (stopping before unregistering
00083         // will cause events to stop being raised, which will be noticable by the app; we want this to be transparent)
00084         StopSuperMuttInputReports();
00085     }
00086
00087     // We are leaving and no longer care about the device closing
00088     EventHandlerForDevice::Current->OnDeviceClose = nullptr;
00089 }
00090
00091 void InputReportEvents::OnDeviceClosing(EventHandlerForDevice^ /* sender */, DeviceInformation^ /* deviceInformation */)
00092 {
00093     UnregisterFromInputReportEvent();
00094
00095     MainPage::Current->Dispatcher->RunAsync(
00096         CoreDispatcherPriority::Normal,
00097         ref new DispatchedHandler([this]()
00098     {
00099         UpdateRegisterEventButtons();
00100     }));
00101 }
00102
00103 void InputReportEvents::RegisterForInputReportEvents_Click(Object^ /* sender */, RoutedEventArgs^ /* eventArgs */)
00104 {
00105     if (EventHandlerForDevice::Current->IsDeviceConnected)
00106     {
00107         // SuperMutt requires an output report to make the device send periodic input reports
00108         StartSuperMuttInputReports();
00109
00110         RegisterForInputReportEvents();
00111
00112         UpdateRegisterEventButtons();
00113     }
00114     else
00115     {
00116         Utilities::NotifyDeviceNotConnected();
00117     }
00118 }
00119
00120 void InputReportEvents::UnregisterFromInputReportEvents_Click(Object^ sender, RoutedEventArgs^ eventArgs)
00121 {
00122     if (EventHandlerForDevice::Current->IsDeviceConnected)
00123     {
00124         UnregisterFromInputReportEvent();
00125
00126         StopSuperMuttInputReports();
00127
00128         UpdateRegisterEventButtons();
00129     }
00130     else
00131     {
00132         Utilities::NotifyDeviceNotConnected();
00133     }
00134 }
00135
00136 /// <summary>
00137 /// Register for the event that is triggered when the device sends a report to us.
00138 ///
00139 /// All input reports share the same event in HidDevice, so once we register the event, all HidInputReports (regardless of the report id) will
00140 /// raise the event. Read the comment above OnInputReportEvent for more information on how to distinguish input reports.
00141 ///
00142 /// The function also saves the event token so that we can unregister from the event later on.
00143 /// </summary>
00144 void InputReportEvents::RegisterForInputReportEvents()
00145 {
00146     if (!isRegisteredForInputReportEvents)
00147     {
00148         // Remember which device we are registering the device with, in case there is a device disconnect and reconnect. We want to avoid unregistering
00149         // a stale token. Ideally, one should remove the event token (e.g. assign to null) upon the device removal to avoid using it again.
00150         registeredDevice = EventHandlerForDevice::Current->Device;
00151
00152         // Save event registration token so we can unregisted for events
00153         inputReportEventToken = registeredDevice->InputReportReceived +=
00154             ref new TypedEventHandler<HidDevice^, HidInputReportReceivedEventArgs^>(this, &InputReportEvents::OnInputReportEvent);
00155
00156         isRegisteredForInputReportEvents = true;
00157
00158         numInputReportEventsReceived = 0;
00159         totalNumberBytesReceived = 0;
00160     }
00161 }
00162
00163 /// <summary>
00164 /// Unregisters from the HidDevice's InputReportReceived event that was registered for in the RegisterForInputReportEvents();
00165 /// </summary>
00166 void InputReportEvents::UnregisterFromInputReportEvent()
00167 {
00168     if (isRegisteredForInputReportEvents)
00169     {
00170         // Don't unregister event token if the device was removed and reconnected because registration token is no longer valid
00171         if (registeredDevice == EventHandlerForDevice::Current->Device)
00172         {
00173             registeredDevice->InputReportReceived -= inputReportEventToken;
00174         }
00175
00176         registeredDevice = nullptr;
00177         isRegisteredForInputReportEvents = false;
00178     }
00179 }
00180
00181 /// <summary>
00182 /// This callback only increments the total number of events received and prints it
00183 ///
00184 /// This method is called whenever the device's state changes and sends a report. Since all input reports share the same event in
00185 /// HidDevice, the app needs to get the HidInputReport from eventArgs.Report and compare report ids and usages with the desired
00186 /// report.
00187 /// </summary>
00188 /// <param name="sender">HidDevice that the event is being raised from</param>
00189 /// <param name="eventArgs">Contains the HidInputReport that caused the event to raise</param>
00190 void InputReportEvents::OnInputReportEvent(HidDevice^ sender, HidInputReportReceivedEventArgs^ eventArgs)
00191 {
00192     // If we navigated away from this page, we don't need to process this event
00193     // This also prevents output from spilling into another page
00194     if (!navigatedAway)
00195     {
00196         numInputReportEventsReceived++;
00197
00198         // The data from the InputReport
00199         HidInputReport^ inputReport = eventArgs->Report;
00200         IBuffer^ buffer = inputReport->Data;
00201
00202         totalNumberBytesReceived += buffer->Length;
00203
00204         // Create a DispatchedHandler for the because we are interracting with the UI directly and the
00205         // thread that this function is running on may not be the UI thread; if a non-UI thread modifies
00206         // the UI, an exception is thrown
00207         MainPage::Current->Dispatcher->RunAsync(
00208             CoreDispatcherPriority::Normal,
00209             ref new DispatchedHandler([this, buffer]()
00210         {
00211             // If we navigated away from this page, do not print anything. The dispatch may be handled after
00212             // we move to a different page.
00213             if (!navigatedAway)
00214             {
00215                 MainPage::Current->NotifyUser(
00216                     "Total number of input report events received: " + numInputReportEventsReceived.ToString()
00217                     + "\nTotal number of bytes received: " + totalNumberBytesReceived.ToString() + " bytes",
00218                     NotifyType::StatusMessage);
00219             }
00220         }));
00221     }
00222 }
00223
00224 /// <summary>
00225 /// Tells the SuperMutt device to start creating interrupts. The app won't get any interrupts until after we register for the event.
00226 ///
00227 /// We are using an output report to start the interrupts, please go to Scenario4_InputOutputReports for more information on how to use
00228 /// output reports.
00229 /// </summary>
00230 void InputReportEvents::StartSuperMuttInputReports(void)
00231 {
00232     auto outputReport = EventHandlerForDevice::Current->Device->CreateOutputReport(SuperMutt::DeviceInputReportControlInformation::ReportId);
00233
00234     auto dataWriter = ref new DataWriter();
00235
00236     // Report Id is always the first byte
00237     dataWriter->WriteByte((uint8)outputReport->Id);
00238     dataWriter->WriteByte(SuperMutt::DeviceInputReportControlInformation::DataTurnOn);
00239
00240     outputReport->Data = dataWriter->DetachBuffer();
00241
00242     create_task(EventHandlerForDevice::Current->Device->SendOutputReportAsync(outputReport))
00243         .then([](task<uint32> bytesWrittenTask)
00244     {
00245         bytesWrittenTask.get();    // Make sure there was no error when turning on interrupts on the device
00246     });
00247 }
00248
00249 /// <summary>
00250 /// Tells the SuperMutt device to stop creating interrupts. The app will stop getting event raises unless we start the interrupts again.
00251 ///
00252 /// We are using an output report to start the interrupts, please go to Scenario4_InputOutputReports for more information on how to use
00253 /// output reports.
00254 /// </summary>
00255 void InputReportEvents::StopSuperMuttInputReports(void)
00256 {
00257     auto outputReport = EventHandlerForDevice::Current->Device->CreateOutputReport(SuperMutt::DeviceInputReportControlInformation::ReportId);
00258
00259     auto dataWriter = ref new DataWriter();
00260
00261     // Report Id is always the first byte
00262     dataWriter->WriteByte((uint8)outputReport->Id);
00263     dataWriter->WriteByte(SuperMutt::DeviceInputReportControlInformation::DataTurnOff);
00264
00265     outputReport->Data = dataWriter->DetachBuffer();
00266
00267     create_task(EventHandlerForDevice::Current->Device->SendOutputReportAsync(outputReport))
00268         .then([](task<uint32> bytesWrittenTask)
00269     {
00270         bytesWrittenTask.get();
00271     });
00272 }
00273
00274 void InputReportEvents::UpdateRegisterEventButtons(void)
00275 {
00276     ButtonRegisterForInputReportEvents->IsEnabled = !isRegisteredForInputReportEvents;
00277     ButtonUnregisterFromInputReportEvents->IsEnabled = isRegisteredForInputReportEvents;
00278 }
00279
Generated on Fri Nov 15 2024 22:19:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cppwinrt/Scenario8_PairDevice.h Source File

  • DeviceEnumerationAndPairing
  • cppwinrt

Scenario8_PairDevice.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario8_PairDevice.g.h"
00015 #include "MainPage.h"
00016 #include "DeviceWatcherHelper.h"
00017
00018 namespace winrt::SDKTemplate::implementation
00019 {
00020     struct Scenario8_PairDevice : Scenario8_PairDeviceT<Scenario8_PairDevice>
00021     {
00022         Scenario8_PairDevice();
00023
00024         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00026
00027         void StartWatcherButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void StopWatcherButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029         fire_and_forget PairButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00030         fire_and_forget UnpairButton_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00031         void ResultsListView_SelectionChanged(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs const& e);
00032
00033     private:
00034         SDKTemplate::MainPage rootPage{ SDKTemplate::implementation::MainPage::Current() };
00035         Windows::Foundation::Collections::IObservableVector<SDKTemplate::DeviceInformationDisplay> resultCollection = winrt::single_threaded_observable_vector<SDKTemplate::DeviceInformationDisplay>();
00036         com_ptr<DeviceWatcherHelper> deviceWatcherHelper = make_self<DeviceWatcherHelper>(resultCollection, Dispatcher());
00037
00038         void StartWatcher();
00039         void StopWatcher();
00040         void OnDeviceListChanged(Windows::Devices::Enumeration::DeviceWatcher const& sender, hstring const& id);
00041         void UpdatePairingButtons();
00042     };
00043 }
00044
00045 namespace winrt::SDKTemplate::factory_implementation
00046 {
00047     struct Scenario8_PairDevice : Scenario8_PairDeviceT<Scenario8_PairDevice, implementation::Scenario8_PairDevice>
00048     {
00049     };
00050 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GeneralAuthenticate Member List

This is the complete list of members for GeneralAuthenticate, including all inherited members.
Address | GeneralAuthenticate |
ApduCommand(byte cla, byte ins, byte p1, byte p2, byte[] commandData, byte?le) | ApduCommand | [inline]
ApduResponseType | ApduCommand |
CLA | ApduCommand |
CommandData | ApduCommand |
GeneralAuthenticate(ushort address, byte keySlotNumber, GeneralAuthenticateKeyType keyType) | GeneralAuthenticate | [inline]
Pcsc::GeneralAuthenticate::GeneralAuthenticate(GeneralAuthenticateVersionNumber version, ushort address, GeneralAuthenticateKeyType keyType, byte keyNo) | GeneralAuthenticate | [inline]
GeneralAuthenticateKeyType enum name | GeneralAuthenticate |
GeneralAuthenticateVersionNumber enum name | GeneralAuthenticate |
GetBuffer() | ApduCommand | [inline]
INS | ApduCommand |
KeyNumber | GeneralAuthenticate |
KeyType | GeneralAuthenticate |
Le | ApduCommand |
P1 | ApduCommand |
P2 | ApduCommand |
ToString() | ApduCommand | [inline]
VersionNumber | GeneralAuthenticate |
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PersonalDataEncryption/cs/SampleConfiguration.cs Source File

  • PersonalDataEncryption
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     public partial class MainPage : Page
00019     {
00020         public const string FEATURE_NAME = "Personal Data Encryption";
00021
00022         List<Scenario> scenarios = new List<Scenario>
00023         {
00024             new Scenario() { Title="Files and folders", ClassType=typeof(Scenario1_Files)},
00025             new Scenario() { Title="Memory", ClassType=typeof(Scenario2_Memory)},
00026         };
00027     }
00028
00029     public class Scenario
00030     {
00031         public string Title { get; set; }
00032         public Type ClassType { get; set; }
00033     }
00034 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Content/FaceTrackerProcessor.h Source File

  • HolographicFaceTracking
  • cpp
  • Content

FaceTrackerProcessor.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace HolographicFaceTracker
00015 {
00016     class VideoFrameProcessor;
00017
00018     // Class to manage the FaceAnalysis::FaceTracker object and process video frames from
00019     // media capture using the VideoFrameProcessor class
00020     class FaceTrackerProcessor
00021     {
00022     public:
00023         static concurrency::task<std::shared_ptr<FaceTrackerProcessor>> CreateAsync(
00024             std::shared_ptr<VideoFrameProcessor> processor);
00025
00026         FaceTrackerProcessor(
00027             Windows::Media::FaceAnalysis::FaceTracker^ tracker,
00028             std::shared_ptr<VideoFrameProcessor> processor);
00029
00030         ~FaceTrackerProcessor(void);
00031
00032         bool IsTrackingFaces(void) const;
00033         std::vector<Windows::Graphics::Imaging::BitmapBounds> GetLatestFaces(void) const;
00034
00035     protected:
00036         void ProcessFrame(void);
00037
00038         Windows::Media::FaceAnalysis::FaceTracker^            m_faceTracker;
00039         std::shared_ptr<VideoFrameProcessor>                  m_videoProcessor;
00040
00041         mutable std::shared_mutex                             m_propertiesLock;
00042         std::vector<Windows::Graphics::Imaging::BitmapBounds> m_latestFaces;
00043
00044         uint32_t                                              m_numFramesWithoutFaces = 0;
00045
00046         std::thread                                           m_workerThread;
00047         bool                                                  m_isRunning = false;
00048     };
00049 }
Generated on Fri Nov 15 2024 22:19:55 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario_CloudFontOverview Member List

This is the complete list of members for Scenario_CloudFontOverview, including all inherited members.
Scenario_CloudFontOverview() Scenario_CloudFontOverview [inline]
Generated on Fri Nov 15 2024 22:24:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiDirect/cppwinrt/Scenario1_Advertiser.cpp Source File

  • WiFiDirect
  • cppwinrt

Scenario1_Advertiser.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_Advertiser.h"
00014 #include "SampleConfiguration.h"
00015 #include "SocketReaderWriter.h"
00016 #include "Scenario1_Advertiser.g.cpp"
00017
00018 using namespace winrt;
00019 using namespace Windows::Devices::Enumeration;
00020 using namespace Windows::Devices::WiFiDirect;
00021 using namespace Windows::Foundation;
00022 using namespace Windows::Foundation::Collections;
00023 using namespace Windows::Networking::Sockets;
00024 using namespace Windows::Storage::Streams;
00025 using namespace Windows::Security::Credentials;
00026 using namespace Windows::Security::Cryptography;
00027 using namespace Windows::UI::Popups;
00028 using namespace Windows::UI::Xaml;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 namespace winrt::SDKTemplate::implementation
00032 {
00033     Scenario1_Advertiser::Scenario1_Advertiser()
00034     {
00035         InitializeComponent();
00036     }
00037
00038     void Scenario1_Advertiser::OnNavigatedFrom(NavigationEventArgs const&)
00039     {
00040         if (btnStopAdvertisement().IsEnabled())
00041         {
00042             StopAdvertisement();
00043         }
00044     }
00045
00046     void Scenario1_Advertiser::btnStartAdvertisement_Click(IInspectable const&, RoutedEventArgs const&)
00047     {
00048         publisher = WiFiDirectAdvertisementPublisher();
00049         statusChangedToken = publisher.StatusChanged({ get_weak(), &Scenario1_Advertiser::OnStatusChanged });
00050
00051         listener = WiFiDirectConnectionListener();
00052
00053         if (chkListener().IsChecked().Value())
00054         {
00055             try
00056             {
00057                 // This can raise an exception if the machine does not support WiFi. Sorry.
00058                 listener.ConnectionRequested({ get_weak(), &Scenario1_Advertiser::OnConnectionRequested });
00059             }
00060             catch (hresult_error const& ex)
00061             {
00062                 rootPage.NotifyUser(L"Error preparing Advertisement: " + ex.message(), NotifyType::ErrorMessage);
00063                 return;
00064             }
00065         }
00066
00067         auto discoverability = GetSelectedItemTag<WiFiDirectAdvertisementListenStateDiscoverability>(cmbListenState());
00068         publisher.Advertisement().ListenStateDiscoverability(discoverability);
00069
00070         publisher.Advertisement().IsAutonomousGroupOwnerEnabled(chkPreferGroupOwnerMode().IsChecked().Value());
00071
00072         // Legacy settings are meaningful only if IsAutonomousGroupOwnerEnabled is true.
00073         if (publisher.Advertisement().IsAutonomousGroupOwnerEnabled() && chkLegacySetting().IsChecked().Value())
00074         {
00075             publisher.Advertisement().LegacySettings().IsEnabled(true);
00076             if (!txtPassphrase().Text().empty())
00077             {
00078                 PasswordCredential creds;
00079                 creds.Password(txtPassphrase().Text());
00080                 publisher.Advertisement().LegacySettings().Passphrase(creds);
00081             }
00082
00083             if (!txtSsid().Text().empty())
00084             {
00085                 publisher.Advertisement().LegacySettings().Ssid(txtSsid().Text());
00086             }
00087         }
00088
00089         // Add the information elements.
00090         publisher.Advertisement().InformationElements().ReplaceAll(informationElements);
00091
00092         publisher.Start();
00093
00094         if (publisher.Status() == WiFiDirectAdvertisementPublisherStatus::Started)
00095         {
00096             btnStartAdvertisement().IsEnabled(false);
00097             btnStopAdvertisement().IsEnabled(true);
00098             rootPage.NotifyUser(L"Advertisement started.", NotifyType::StatusMessage);
00099         }
00100         else
00101         {
00102             rootPage.NotifyUser(L"Advertisement failed to start. Status is " + to_hstring(publisher.Status()), NotifyType::ErrorMessage);
00103         }
00104     }
00105
00106     void Scenario1_Advertiser::btnAddIe_Click(IInspectable const&, RoutedEventArgs const&)
00107     {
00108         WiFiDirectInformationElement informationElement;
00109
00110         // Information element blob
00111         DataWriter dataWriter;
00112         dataWriter.UnicodeEncoding(UnicodeEncoding::Utf8);
00113         dataWriter.ByteOrder(ByteOrder::LittleEndian);
00114         dataWriter.WriteUInt32(dataWriter.MeasureString(txtInformationElement().Text()));
00115         dataWriter.WriteString(txtInformationElement().Text());
00116         informationElement.Value(dataWriter.DetachBuffer());
00117
00118         // Organizational unit identifier (OUI)
00119         informationElement.Oui(CryptographicBuffer::CreateFromByteArray(CustomOui));
00120
00121         // OUI Type
00122         informationElement.OuiType(CustomOuiType);
00123
00124         // Save this information element so we can add it when we advertise.
00125         informationElements.push_back(informationElement);
00126
00127         txtInformationElement().Text({});
00128         rootPage.NotifyUser(L"IE added successfully", NotifyType::StatusMessage);
00129     }
00130
00131     void Scenario1_Advertiser::btnStopAdvertisement_Click(IInspectable const&, RoutedEventArgs const&)
00132     {
00133         StopAdvertisement();
00134         rootPage.NotifyUser(L"Advertisement stopped successfully", NotifyType::StatusMessage);
00135     }
00136
00137     void Scenario1_Advertiser::StopAdvertisement()
00138     {
00139         publisher.Stop();
00140         publisher.StatusChanged(statusChangedToken);
00141
00142         listener.ConnectionRequested(connectionRequestedToken);
00143
00144         connectionSettingsPanel().Reset();
00145         informationElements.clear();
00146
00147         btnStartAdvertisement().IsEnabled(true);
00148         btnStopAdvertisement().IsEnabled(false);
00149     }
00150
00151     IAsyncOperation<bool> Scenario1_Advertiser::HandleConnectionRequestAsync(WiFiDirectConnectionRequest connectionRequest)
00152     {
00153         auto lifetime = get_strong();
00154
00155         hstring deviceName = connectionRequest.DeviceInformation().Name();
00156
00157         DeviceInformationPairing pairing = connectionRequest.DeviceInformation().Pairing();
00158         bool isPaired = (pairing && pairing.IsPaired()) ||
00159             (co_await IsAepPairedAsync(connectionRequest.DeviceInformation().Id()));
00160
00161         // Show the prompt only in case of WiFiDirect reconnection or Legacy client connection.
00162         if (isPaired || publisher.Advertisement().LegacySettings().IsEnabled())
00163         {
00164             MessageDialog messageDialog{ L"Connection request received from " + deviceName, L"Connection Request" };
00165
00166             // Add two commands, distinguished by their tag.
00167             // The default command is "Decline", and if the user cancels, we treat it as "Decline".
00168             messageDialog.Commands().Append(UICommand(L"Accept", nullptr, box_value(true)));
00169             messageDialog.Commands().Append(UICommand(L"Decline", nullptr, nullptr));
00170
00171             messageDialog.DefaultCommandIndex(1);
00172             messageDialog.CancelCommandIndex(1);
00173
00174             // Show the message dialog
00175             auto commandChosen = co_await messageDialog.ShowAsync();
00176
00177             if (commandChosen.Id() == nullptr)
00178             {
00179                 // Decline
00180                 co_return false;
00181             }
00182
00183             rootPage.NotifyUser(L"Connecting to " + deviceName + L"...", NotifyType::StatusMessage);
00184
00185             // Pair device if not already paired and not using legacy settings
00186             if (!isPaired && !publisher.Advertisement().LegacySettings().IsEnabled())
00187             {
00188                 if (!co_await connectionSettingsPanel().RequestPairDeviceAsync(pairing))
00189                 {
00190                     co_return false;
00191                 }
00192             }
00193
00194             WiFiDirectDevice wfdDevice = nullptr;
00195             try
00196             {
00197                 // IMPORTANT: FromIdAsync needs to be called from the UI thread
00198                 wfdDevice = co_await WiFiDirectDevice::FromIdAsync(connectionRequest.DeviceInformation().Id());
00199             }
00200             catch (hresult_error const& ex)
00201             {
00202                 rootPage.NotifyUser(L"Exception in FromIdAsync: " + ex.message(), NotifyType::ErrorMessage);
00203                 co_return false;
00204             }
00205
00206             // Register for the ConnectionStatusChanged event handler
00207             connectionStatusChangedToken = wfdDevice.ConnectionStatusChanged({ get_weak(), &Scenario1_Advertiser::OnConnectionStatusChanged });
00208
00209             StreamSocketListener listenerSocket;
00210
00211             // Remembering this listenerSocket serves two purposes.
00212             // 1. It keeps the listenerSocket alive until the connection is received.
00213             // 2. It allows us to map the listenerSocket to the corresponding WiFiDirectDevice
00214             //    when the connection is received.
00215             {
00216                 auto lock = slim_lock_guard(pendingConnectionsMutex);
00217                 pendingConnections.insert_or_assign(listenerSocket, wfdDevice);
00218             }
00219             listenerSocket.ConnectionReceived({ get_weak(), &Scenario1_Advertiser::OnSocketConnectionReceived });
00220
00221             auto EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
00222             try
00223             {
00224                 co_await listenerSocket.BindEndpointAsync(EndpointPairs.GetAt(0).LocalHostName(), ServerPortString);
00225             }
00226             catch (hresult_error const& ex)
00227             {
00228                 rootPage.NotifyUser(L"Connect operation threw an exception: " + ex.message(), NotifyType::ErrorMessage);
00229                 co_return false;
00230             }
00231
00232             rootPage.NotifyUser(L"Devices connected on L2, listening on IP Address: " + EndpointPairs.GetAt(0).LocalHostName().DisplayName() +
00233                 L" Port: " + ServerPortString, NotifyType::StatusMessage);
00234             co_return true;
00235         }
00236     }
00237
00238     fire_and_forget Scenario1_Advertiser::OnConnectionRequested(WiFiDirectConnectionListener const&, WiFiDirectConnectionRequestedEventArgs const& e)
00239     {
00240         auto lifetime = get_strong();
00241
00242         WiFiDirectConnectionRequest connectionRequest = e.GetConnectionRequest();
00243         co_await resume_foreground(Dispatcher());
00244         if (!co_await HandleConnectionRequestAsync(connectionRequest))
00245         {
00246             // Decline the connection request
00247             rootPage.NotifyUser(L"Connection request from " + connectionRequest.DeviceInformation().Name() + L" was declined", NotifyType::ErrorMessage);
00248             connectionRequest.Close();
00249         }
00250     }
00251
00252     IAsyncOperation<bool> Scenario1_Advertiser::IsAepPairedAsync(hstring deviceId)
00253     {
00254         auto lifetime = get_strong();
00255
00256         DeviceInformation devInfo = nullptr;
00257         try
00258         {
00259             devInfo = co_await DeviceInformation::CreateFromIdAsync(deviceId, { L"System.Devices.Aep.DeviceAddress" });
00260         }
00261         catch (hresult_error const& ex)
00262         {
00263             rootPage.NotifyUser(L"DeviceInformation.CreateFromIdAsync threw an exception: " + ex.message(), NotifyType::ErrorMessage);
00264         }
00265
00266         if (devInfo == nullptr)
00267         {
00268             rootPage.NotifyUser(L"Device Information is null", NotifyType::ErrorMessage);
00269             co_return false;
00270         }
00271
00272         hstring deviceAddress = unbox_value<hstring>(devInfo.Properties().Lookup(L"System.Devices.Aep.DeviceAddress"));
00273         hstring deviceSelector = L"System.Devices.Aep.DeviceAddress:=\"" + deviceAddress + L"\"";
00274         DeviceInformationCollection pairedDeviceCollection = co_await DeviceInformation::FindAllAsync(deviceSelector, nullptr, DeviceInformationKind::Device);
00275         co_return pairedDeviceCollection.Size() > 0;
00276     }
00277
00278     fire_and_forget Scenario1_Advertiser::OnStatusChanged(WiFiDirectAdvertisementPublisher sender, WiFiDirectAdvertisementPublisherStatusChangedEventArgs e)
00279     {
00280         auto lifetime = get_strong();
00281
00282         if (e.Status() == WiFiDirectAdvertisementPublisherStatus::Started)
00283         {
00284             co_await resume_foreground(Dispatcher());
00285             if (sender.Advertisement().LegacySettings().IsEnabled())
00286             {
00287                 // Show the autogenerated passphrase and SSID.
00288                 if (txtPassphrase().Text().empty())
00289                 {
00290                     txtPassphrase().Text(publisher.Advertisement().LegacySettings().Passphrase().Password());
00291                 }
00292
00293                 if (txtSsid().Text().empty())
00294                 {
00295                     txtSsid().Text(publisher.Advertisement().LegacySettings().Ssid());
00296                 }
00297             }
00298         }
00299
00300         rootPage.NotifyUser(L"Advertisement: Status: " + to_hstring(e.Status()) + L", Error: " + to_hstring(e.Error()), NotifyType::StatusMessage);
00301         co_return;
00302     }
00303
00304     fire_and_forget Scenario1_Advertiser::OnSocketConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs e)
00305     {
00306         auto lifetime = get_strong();
00307
00308         co_await resume_foreground(Dispatcher());
00309         rootPage.NotifyUser(L"Connecting to remote side on L4 layer...", NotifyType::StatusMessage);
00310         StreamSocket serverSocket = e.Socket();
00311
00312         // Look up the WiFiDirectDevice associated with this StreamSocketListener.
00313         WiFiDirectDevice wfdDevice = nullptr;
00314         decltype(pendingConnections.extract(sender)) node;
00315         {
00316             auto lock = slim_lock_guard(pendingConnectionsMutex);
00317             node = pendingConnections.extract(sender);
00318             if (node)
00319             {
00320                 wfdDevice = node.mapped();
00321             }
00322         }
00323
00324         if (wfdDevice == nullptr)
00325         {
00326             rootPage.NotifyUser(L"Unexpected connection ignored.", NotifyType::ErrorMessage);
00327             serverSocket.Close();
00328             co_return;
00329         }
00330
00331         auto socketRW = make_self<SocketReaderWriter>(serverSocket, rootPage);
00332
00333         // The first message sent is the name of the connection.
00334         IReference<hstring> message = co_await socketRW->ReadMessageAsync();
00335
00336         // Add this connection to the list of active connections.
00337         connectedDevices.Append(make<ConnectedDevice>(message ? message.Value() : L"(unnamed)", wfdDevice, socketRW));
00338
00339         // Keep reading messages until the socket is closed.
00340         while (message)
00341         {
00342             message = co_await socketRW->ReadMessageAsync();
00343         }
00344     }
00345
00346     void Scenario1_Advertiser::OnConnectionStatusChanged(WiFiDirectDevice const& sender, IInspectable const&)
00347     {
00348         rootPage.NotifyUser(L"Connection status changed: " + to_hstring(sender.ConnectionStatus()), NotifyType::StatusMessage);
00349
00350         if (sender.ConnectionStatus() == WiFiDirectConnectionStatus::Disconnected)
00351         {
00352             // TODO: Should we remove this connection from the list?
00353             // (Yes, probably.)
00354         }
00355     }
00356
00357     fire_and_forget Scenario1_Advertiser::btnSendMessage_Click(IInspectable const&, RoutedEventArgs const&)
00358     {
00359         auto lifetime = get_strong();
00360
00361         auto connectedDevice = lvConnectedDevices().SelectedItem().as<SDKTemplate::ConnectedDevice>();
00362         co_await get_self<ConnectedDevice>(connectedDevice)->SocketRW()->WriteMessageAsync(txtSendMessage().Text());
00363     }
00364
00365     void Scenario1_Advertiser::btnCloseDevice_Click(IInspectable const&, RoutedEventArgs const&)
00366     {
00367         auto connectedDevice = lvConnectedDevices().SelectedItem().as<SDKTemplate::ConnectedDevice>();
00368         RemoveByValue(connectedDevices, connectedDevice);
00369
00370         // Close socket and WiFiDirect object
00371         connectedDevice.Close();
00372     }
00373 }
00374
00375
Generated on Fri Nov 15 2024 22:22:05 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PersonalDataEncryption/cppwinrt/pch.h Source File

  • PersonalDataEncryption
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Security.Cryptography.h"
00008 #include "winrt/Windows.Security.DataProtection.h"
00009 #include "winrt/Windows.Storage.h"
00010 #include "winrt/Windows.Storage.Pickers.h"
00011 #include "winrt/Windows.Storage.Streams.h"
00012 #include "winrt/Windows.System.h"
00013 #include "winrt/Windows.UI.Core.h"
00014 #include "winrt/Windows.UI.Xaml.h"
00015 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00016 #include "winrt/Windows.UI.Xaml.Controls.h"
00017 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00018 #include "winrt/Windows.UI.Xaml.Documents.h"
00019 #include "winrt/Windows.UI.Xaml.Interop.h"
00020 #include "winrt/Windows.UI.Xaml.Markup.h"
00021 #include "winrt/Windows.UI.Xaml.Media.h"
00022 #include "winrt/Windows.UI.Xaml.Navigation.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/Common/PersistentState.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • Common

PersistentState.cpp

Go to the documentation of this file.
00001 // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 // PARTICULAR PURPOSE.
00005 //
00006 // Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #include "pch.h"
00009 #include "PersistentState.h"
00010
00011 using namespace winrt::Windows::Foundation;
00012 using namespace winrt::Windows::Foundation::Collections;
00013 using namespace DirectX;
00014
00015 void PersistentState::Initialize(
00016     _In_ IPropertySet settingsValues,
00017     _In_ winrt::hstring const& key
00018     )
00019 {
00020     m_settingsValues = settingsValues;
00021     m_keyName = key;
00022 }
00023
00024 void PersistentState::SaveBool(winrt::hstring const& key, bool value)
00025 {
00026     m_settingsValues.Insert(m_keyName + key, winrt::box_value(value));
00027 }
00028
00029 void PersistentState::SaveInt32(winrt::hstring const& key, int value)
00030 {
00031     m_settingsValues.Insert(m_keyName + key, winrt::box_value(value));
00032 }
00033
00034 void PersistentState::SaveSingle(winrt::hstring const& key, float value)
00035 {
00036     m_settingsValues.Insert(m_keyName + key, winrt::box_value(value));
00037 }
00038
00039 void PersistentState::SaveXMFLOAT3(winrt::hstring const& key, DirectX::XMFLOAT3 value)
00040 {
00041     m_settingsValues.Insert(m_keyName + key, PropertyValue::CreateSingleArray({ value.x, value.y, value.z }));
00042 }
00043
00044 void PersistentState::SaveString(winrt::hstring const& key, winrt::hstring const& string)
00045 {
00046     m_settingsValues.Insert(m_keyName + key, winrt::box_value(string));
00047 }
00048
00049 bool PersistentState::LoadBool(winrt::hstring const& key, bool defaultValue)
00050 {
00051     return winrt::unbox_value_or(m_settingsValues.TryLookup(m_keyName + key), defaultValue);
00052 }
00053
00054 int PersistentState::LoadInt32(winrt::hstring const& key, int defaultValue)
00055 {
00056     return winrt::unbox_value_or(m_settingsValues.TryLookup(m_keyName + key), defaultValue);
00057 }
00058
00059 float PersistentState::LoadSingle(winrt::hstring const& key, float defaultValue)
00060 {
00061     return winrt::unbox_value_or(m_settingsValues.TryLookup(m_keyName + key), defaultValue);
00062 }
00063
00064 XMFLOAT3 PersistentState::LoadXMFLOAT3(winrt::hstring const& key, DirectX::XMFLOAT3 defaultValue)
00065 {
00066     auto propertyValue = winrt::unbox_value_or(m_settingsValues.TryLookup(m_keyName + key), winrt::Windows::Foundation::IPropertyValue{});
00067     if (propertyValue)
00068     {
00069         winrt::com_array<float> array3;
00070         propertyValue.GetSingleArray(array3);
00071         return { array3[0], array3[1], array3[2] };
00072     }
00073     return defaultValue;
00074 }
00075
00076 winrt::hstring PersistentState::LoadString(winrt::hstring const& key, winrt::hstring const& defaultValue)
00077 {
00078     return winrt::unbox_value_or<winrt::hstring>(m_settingsValues.TryLookup(m_keyName + key), defaultValue);
00079 }
Generated on Fri Nov 15 2024 22:21:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

App Member List

This is the complete list of members for App, including all inherited members.
App() | App | [inline]
NavigationService | App | [static]
OnActivated(IActivatedEventArgs args) | App | [inline, protected]
OnLaunched(LaunchActivatedEventArgs e) | App | [inline, protected]
OnNavigationFailed(object sender, NavigationFailedEventArgs e) | App | [inline, private]
OnSuspending(object sender, SuspendingEventArgs e) | App | [inline, private]
rootFrameNavigationHelper | App | [private]
SemanticInterpretation(string interpretationKey, SpeechRecognitionResult speechRecognitionResult) | App | [inline, private]
Generated on Fri Nov 15 2024 22:23:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LanguageFont/cppwinrt/SampleConfiguration.cpp Source File

  • LanguageFont
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace SDKTemplate;
00020
00021 hstring implementation::MainPage::FEATURE_NAME()
00022 {
00023     return L"LanguageFont C++/WinRT Sample";
00024 }
00025
00026 IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00027 {
00028     Scenario{ L"Fonts for UI", xaml_typename<SDKTemplate::Scenario1_UIFonts>() },
00029     Scenario{ L"Fonts for Documents", xaml_typename<SDKTemplate::Scenario2_DocumentFonts>() },
00030 });
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCloudFontIntegration/cpp/Scenario_CloudFontOverview.xaml.cpp Source File

  • XamlCloudFontIntegration
  • cpp

Scenario_CloudFontOverview.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario_CloudFontOverview.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls;
00022 using namespace Windows::UI::Xaml::Controls::Primitives;
00023 using namespace Windows::UI::Xaml::Data;
00024 using namespace Windows::UI::Xaml::Input;
00025 using namespace Windows::UI::Xaml::Media;
00026 using namespace Windows::UI::Xaml::Navigation;
00027
00028
00029 Scenario_CloudFontOverview::Scenario_CloudFontOverview()
00030 {
00031     InitializeComponent();
00032 }
Generated on Fri Nov 15 2024 22:19:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicFaceDetection/cppwinrt/Project.idl Source File

  • BasicFaceDetection
  • cppwinrt

Project.idl

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 namespace SDKTemplate
00013 {
00014     [default_interface]
00015     runtimeclass Scenario1_DetectInPhoto : Windows.UI.Xaml.Controls.Page
00016     {
00017         Scenario1_DetectInPhoto();
00018     }
00019
00020     [default_interface]
00021     runtimeclass Scenario2_DetectInWebcam : Windows.UI.Xaml.Controls.Page
00022     {
00023         Scenario2_DetectInWebcam();
00024     }
00025 }
Generated on Fri Nov 15 2024 22:17:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/SharePage.h Source File

  • ShareSource
  • cpp

SharePage.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // SharePage.h
00014 // Declaration of the SharePage class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "MainPage.xaml.h"
00021
00022 namespace SDKTemplate
00023 {
00024     [Windows::Foundation::Metadata::WebHostHidden]
00025     public ref class SharePage : Windows::UI::Xaml::Controls::Page
00026     {
00027     public:
00028         static Windows::Foundation::Uri^ GetApplicationLink(Platform::String^ sharePageFullName);
00029         property Windows::Foundation::Uri^ ApplicationLink
00030         {
00031             Windows::Foundation::Uri^ get()
00032             {
00033                 return GetApplicationLink(GetType()->FullName);
00034             }
00035         }
00036     protected:
00037         property MainPage^ RootPage { MainPage^ get() { return rootPage; } }
00038
00039         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00040         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00041         void ShowUIButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00042         virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request);
00043
00044     private:
00045         MainPage^ rootPage = MainPage::Current;
00046         Windows::Foundation::EventRegistrationToken dataRequestedToken{};
00047         Windows::Foundation::EventRegistrationToken targetApplicationChosenToken{};
00048
00049         void OnDataRequested(Windows::ApplicationModel::DataTransfer::DataTransferManager^ sender, Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs^ e);
00050         void OnTargetApplicationChosen(Windows::ApplicationModel::DataTransfer::DataTransferManager^ sender, Windows::ApplicationModel::DataTransfer::TargetApplicationChosenEventArgs^ e);
00051         void OnShareCompleted(Windows::ApplicationModel::DataTransfer::DataPackage^ sender, Windows::ApplicationModel::DataTransfer::ShareCompletedEventArgs^ e);
00052     };
00053 }
Generated on Fri Nov 15 2024 22:21:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebSocket/cppwinrt/Scenario4_PartialReadWrite.h Source File

  • WebSocket
  • cppwinrt

Scenario4_PartialReadWrite.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario4_PartialReadWrite.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario4_PartialReadWrite : Scenario4_PartialReadWriteT<Scenario4_PartialReadWrite>
00019     {
00020         Scenario4_PartialReadWrite();
00021
00022         Windows::Foundation::IAsyncAction OnConnect(Windows::Foundation::IInspectable sender, Windows::UI::Xaml::RoutedEventArgs e);
00023         Windows::Foundation::IAsyncAction OnSend(Windows::Foundation::IInspectable sender, Windows::UI::Xaml::RoutedEventArgs e);
00024         void OnDisconnect(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00025         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00026
00027     private:
00028         Windows::Foundation::IAsyncAction ConnectAsync();
00029         Windows::Foundation::IAsyncAction SendAsync();
00030         Windows::Foundation::IAsyncAction MessageReceived(Windows::Networking::Sockets::MessageWebSocket sender, Windows::Networking::Sockets::MessageWebSocketMessageReceivedEventArgs e);
00031         Windows::Foundation::IAsyncAction OnClosed(Windows::Networking::Sockets::IWebSocket sender, Windows::Networking::Sockets::WebSocketClosedEventArgs e);
00032         void CloseSocket();
00033         void AppendOutputLine(hstring const& value);
00034         void UpdateVisualState();
00035         void SetBusy(bool value);
00036
00037         SDKTemplate::MainPage m_rootPage{ MainPage::Current() };
00038         Windows::Networking::Sockets::MessageWebSocket m_messageWebSocket{ nullptr };
00039         Windows::Storage::Streams::DataWriter m_messageWriter{ nullptr };
00040         bool m_busy{ false };
00041     };
00042 }
00043
00044 namespace winrt::SDKTemplate::factory_implementation
00045 {
00046     struct Scenario4_PartialReadWrite : Scenario4_PartialReadWriteT<Scenario4_PartialReadWrite, implementation::Scenario4_PartialReadWrite>
00047     {
00048     };
00049 }
Generated on Fri Nov 15 2024 22:22:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AudioCategory/cs/AudioCategory/SampleConfiguration.cs Source File

  • AudioCategory
  • cs
  • AudioCategory

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using PlaybackManager;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         // Change the string below to reflect the name of your sample.
00022         // This is used on the main page as the title of the sample.
00023         public const string FEATURE_NAME = "Audio Category Sample";
00024
00025         // Change the array below to reflect the name of your scenarios.
00026         // This will be used to populate the list of scenarios on the main page with
00027         // which the user will choose the specific scenario that they are interested in.
00028         // These should be in the form: "Navigating to a web page".
00029         // The code in MainPage will take care of turning this into: "1) Navigating to a web page"
00030         List<Scenario> scenarios = new List<Scenario>
00031         {
00032             new Scenario() { Title = "Movie", ClassType = typeof(Scenario1) },
00033             new Scenario() { Title = "Media", ClassType = typeof(Scenario2) },
00034             new Scenario() { Title = "Game Chat", ClassType = typeof(Scenario3) },
00035             new Scenario() { Title = "Speech", ClassType = typeof(Scenario4) },
00036             new Scenario() { Title = "Communications", ClassType = typeof(Scenario5) },
00037             new Scenario() { Title = "Alerts", ClassType = typeof(Scenario6) },
00038             new Scenario() { Title = "Sound Effects", ClassType = typeof(Scenario7) },
00039             new Scenario() { Title = "Game Effects", ClassType = typeof(Scenario8) },
00040             new Scenario() { Title = "Game Media", ClassType = typeof(Scenario9) },
00041             new Scenario() { Title = "Other", ClassType = typeof(Scenario10) }
00042         };
00043     }
00044
00045     public class Scenario
00046     {
00047         public string Title { get; set; }
00048         public Type ClassType { get; set; }
00049     }
00050 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

StspSampleHeader Member List

This is the complete list of members for StspSampleHeader, including all inherited members.
dwFlagMasks | StspSampleHeader
dwFlags | StspSampleHeader
dwStreamId | StspSampleHeader
ullDuration | StspSampleHeader
ullTimestamp | StspSampleHeader
Generated on Fri Nov 15 2024 22:23:29 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DGradientMesh/cpp/pch.h Source File

  • D2DGradientMesh
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
00002 //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
00003 //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
00004 //// PARTICULAR PURPOSE.
00005 ////
00006 //// Copyright (c) Microsoft Corporation. All rights reserved
00007
00008 #pragma once
00009
00010 #include <wrl.h>
00011 #include <wrl/client.h>
00012 #include <d3d11_2.h>
00013 #include <d2d1_3.h>
00014 #include <dwrite_2.h>
00015 #include <wincodec.h>
00016 #include <DirectXMath.h>
00017 #include <memory>
00018 #include <ppltasks.h>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MicrosoftPassport/Server/Properties/AssemblyInfo.cs Source File

  • MicrosoftPassport
  • Server
  • Properties

AssemblyInfo.cs

Go to the documentation of this file.
00001 ﻿using System.Reflection;
00002 using System.Runtime.CompilerServices;
00003 using System.Runtime.InteropServices;
00004
00005 // General Information about an assembly is controlled through the following
00006 // set of attributes. Change these attribute values to modify the information
00007 // associated with an assembly.
00008 [assembly: AssemblyTitle("MicrosoftPassport.Server")]
00009 [assembly: AssemblyDescription("")]
00010 [assembly: AssemblyConfiguration("")]
00011 [assembly: AssemblyCompany("")]
00012 [assembly: AssemblyProduct("MicrosoftPassport.Server")]
00013 [assembly: AssemblyCopyright("Copyright ©  2015")]
00014 [assembly: AssemblyTrademark("")]
00015 [assembly: AssemblyCulture("")]
00016
00017 // Setting ComVisible to false makes the types in this assembly not visible
00018 // to COM components.  If you need to access a type in this assembly from
00019 // COM, set the ComVisible attribute to true on that type.
00020 [assembly: ComVisible(false)]
00021
00022 // The following GUID is for the ID of the typelib if this project is exposed to COM
00023 [assembly: Guid("1d4e6070-5994-49ad-9a1c-77ff4f554102")]
00024
00025 // Version information for an assembly consists of the following four values:
00026 //
00027 //      Major Version
00028 //      Minor Version
00029 //      Build Number
00030 //      Revision
00031 //
00032 // You can specify all the values or you can default the Revision and Build Numbers
00033 // by using the '*' as shown below:
00034 [assembly: AssemblyVersion("1.0.0.0")]
00035 [assembly: AssemblyFileVersion("1.0.0.0")]
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserConsentVerifier/cpp/Scenario1_CheckConsentAvailability.xaml.cpp Source File

  • UserConsentVerifier
  • cpp

Scenario1_CheckConsentAvailability.xaml.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "Scenario1_CheckConsentAvailability.xaml.h"
00005
00006 using namespace SDKTemplate;
00007
00008 using namespace concurrency;
00009 using namespace Platform;
00010 using namespace Windows::Security::Credentials::UI;
00011 using namespace Windows::UI::Xaml;
00012
00013 Scenario1_CheckConsentAvailability::Scenario1_CheckConsentAvailability()
00014 {
00015     InitializeComponent();
00016 }
00017
00018 // Check the availability of Windows Hello authentication through User Consent Verifier.
00019 void Scenario1_CheckConsentAvailability::CheckAvailability_Click(Object^ sender, RoutedEventArgs^ e)
00020 {
00021     CheckAvailabilityButton->IsEnabled = false;
00022
00023     create_task(UserConsentVerifier::CheckAvailabilityAsync())
00024         .then([this](UserConsentVerifierAvailability consentAvailability)
00025     {
00026         switch (consentAvailability)
00027         {
00028         case UserConsentVerifierAvailability::Available:
00029             MainPage::Current->NotifyUser("User consent verification is available.", NotifyType::StatusMessage);
00030             break;
00031
00032         case UserConsentVerifierAvailability::DeviceNotPresent:
00033             MainPage::Current->NotifyUser("No PIN or biometric device found, please set one up.", NotifyType::ErrorMessage);
00034             break;
00035
00036         default:
00037             MainPage::Current->NotifyUser("User consent verification is currently unavailable.", NotifyType::ErrorMessage);
00038             break;
00039         }
00040         CheckAvailabilityButton->IsEnabled = true;
00041     });
00042 }
00043
Generated on Fri Nov 15 2024 22:21:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AccessHandler Member List

This is the complete list of members for AccessHandler, including all inherited members.
AccessHandler(SmartCardConnection ScConnection) | AccessHandler | [inline]
connectionObject | AccessHandler | [private]
GetUidAsync() | AccessHandler | [inline]
ReadAsync(byte pageAddress) | AccessHandler | [inline]
TransparentExchangeAsync(byte[] commandData) | AccessHandler | [inline]
WriteAsync(byte pageAddress, byte[] data) | AccessHandler | [inline]
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks/ViewModel/ViewModelLocator.cpp Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks
  • ViewModel

ViewModelLocator.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "ViewModelLocator.h"
00013
00014 using namespace AdventureWorks;
00015
00016 using namespace Concurrency;
00017 using namespace AdventureWorks_Shared;
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::Foundation::Collections;
00021
00022 /// <summary> Create common trip store reference, set up view models.</summary>
00023 ViewModelLocator::ViewModelLocator()
00024 {
00025     this->store = ref new TripStore();
00026     this->modelSet = ref new Map<Platform::String^, ViewModelBase^>();
00027     this->modelSet->Insert(L"TripListViewModel", ref new AdventureWorks::TripListViewModel(store));
00028     this->modelSet->Insert(L"TripViewModel", ref new AdventureWorks::TripViewModel(store));
00029 }
00030
00031 AdventureWorks::TripListViewModel^ ViewModelLocator::TripListViewModel::get()
00032 {
00033     return (AdventureWorks::TripListViewModel^)this->modelSet->Lookup("TripListViewModel");
00034 }
00035
00036 AdventureWorks::TripViewModel^ ViewModelLocator::TripViewModel::get()
00037 {
00038     return (AdventureWorks::TripViewModel^)this->modelSet->Lookup("TripViewModel");
00039 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MultipleViews/cppwinrt/pch.cpp Source File

  • MultipleViews
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DPhotoAdjustment/cpp/DirectXPage.xaml.cpp Source File

  • D2DPhotoAdjustment
  • cpp

DirectXPage.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DirectXPage.xaml.h"
00014
00015 using namespace D2DPhotoAdjustment;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Foundation;
00020 using namespace Windows::Foundation::Collections;
00021 using namespace Windows::Graphics::Display;
00022 using namespace Windows::System::Threading;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Input;
00025 using namespace Windows::UI::Xaml;
00026 using namespace Windows::UI::Xaml::Controls;
00027 using namespace Windows::UI::Xaml::Controls::Primitives;
00028 using namespace Windows::UI::Xaml::Data;
00029 using namespace Windows::UI::Xaml::Input;
00030 using namespace Windows::UI::Xaml::Media;
00031 using namespace Windows::UI::Xaml::Navigation;
00032
00033 DirectXPage::DirectXPage() :
00034     m_isWindowVisible(true),
00035     m_suppressRendererUpdates(false),
00036     m_properties()
00037 {
00038     InitializeComponent();
00039
00040     // Register event handlers for page lifecycle.
00041     CoreWindow^ window = Window::Current->CoreWindow;
00042
00043     window->VisibilityChanged +=
00044         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &DirectXPage::OnVisibilityChanged);
00045
00046     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00047
00048     currentDisplayInformation->DpiChanged +=
00049         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnDpiChanged);
00050
00051     currentDisplayInformation->OrientationChanged +=
00052         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnOrientationChanged);
00053
00054     currentDisplayInformation->ColorProfileChanged +=
00055         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnColorProfileChanged);
00056
00057     DisplayInformation::DisplayContentsInvalidated +=
00058         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &DirectXPage::OnDisplayContentsInvalidated);
00059
00060     swapChainPanel->CompositionScaleChanged +=
00061         ref new TypedEventHandler<SwapChainPanel^, Object^>(this, &DirectXPage::OnCompositionScaleChanged);
00062
00063     swapChainPanel->SizeChanged +=
00064         ref new SizeChangedEventHandler(this, &DirectXPage::OnSwapChainPanelSizeChanged);
00065
00066     // At this point we have access to the device and
00067     // can create the device-dependent resources.
00068     m_deviceResources = std::make_shared<DX::DeviceResources>();
00069     m_deviceResources->SetSwapChainPanel(swapChainPanel);
00070
00071     CreateRenderer();
00072 }
00073
00074 DirectXPage::~DirectXPage()
00075 {
00076 }
00077
00078 void DirectXPage::CreateRenderer()
00079 {
00080     m_renderer = std::unique_ptr<PhotoAdjustmentRenderer>(new PhotoAdjustmentRenderer(m_deviceResources));
00081
00082     // Wait until the renderer has been created to reset the photo pipeline values.
00083     ResetPhotoAdjustmentValues();
00084 }
00085
00086 // Resets the UI sliders and PhotoAdjustmentRenderer state to "neutral" values.
00087 void DirectXPage::ResetPhotoAdjustmentValues()
00088 {
00089     // Temporarily suppress renderer updates because we are changing a bunch of
00090     // properties at once.
00091     m_suppressRendererUpdates = true;
00092
00093     // IsJpegIndexingEnabled persists across photo adjustment pipeline resets.
00094     this->StraightenValue = 0.0f;
00095     this->TemperatureValue = 0.0f;
00096     this->TintValue = 0.0f;
00097     this->SaturationValue = 1.0f; // D2D1_SATURATION_PROP_SATURATION defaults to 0.5.
00098     this->ContrastValue = 0.0f;
00099     this->ShadowsValue = 0.0f;
00100     this->ClarityValue = 0.0f;
00101     this->HighlightsValue = 0.0f;
00102     this->HsMaskRadiusValue = 1.25f;
00103
00104     m_suppressRendererUpdates = false;
00105
00106     TryUpdateRenderer();
00107 }
00108
00109
00110 void DirectXPage::Reset_Click(_In_ Object^ sender, _In_ RoutedEventArgs^ e)
00111 {
00112     ResetPhotoAdjustmentValues();
00113 }
00114
00115 // Saves the current state of the app for suspend and terminate events.
00116 void DirectXPage::SaveInternalState(_In_ IPropertySet^ state)
00117 {
00118     m_deviceResources->Trim();
00119 }
00120
00121 // Loads the current state of the app for resume events.
00122 void DirectXPage::LoadInternalState(_In_ IPropertySet^ state)
00123 {
00124 }
00125
00126 // Window event handlers.
00127
00128 void DirectXPage::OnVisibilityChanged(_In_ CoreWindow^ sender, _In_ VisibilityChangedEventArgs^ args)
00129 {
00130     m_isWindowVisible = args->Visible;
00131     if (m_isWindowVisible)
00132     {
00133         m_renderer->Draw();
00134     }
00135 }
00136
00137 // DisplayInformation event handlers.
00138
00139 void DirectXPage::OnDpiChanged(_In_ DisplayInformation^ sender, _In_ Object^ args)
00140 {
00141     m_deviceResources->SetDpi(sender->LogicalDpi);
00142     m_renderer->CreateWindowSizeDependentResources();
00143     m_renderer->Draw();
00144 }
00145
00146 void DirectXPage::OnOrientationChanged(_In_ DisplayInformation^ sender, _In_ Object^ args)
00147 {
00148     m_deviceResources->SetCurrentOrientation(sender->CurrentOrientation);
00149     m_renderer->CreateWindowSizeDependentResources();
00150     m_renderer->Draw();
00151 }
00152
00153 void DirectXPage::OnColorProfileChanged(_In_ DisplayInformation^ sender, _In_ Object^)
00154 {
00155     m_renderer->OnColorProfileChanged(sender);
00156     m_renderer->Draw();
00157 }
00158
00159 void DirectXPage::OnDisplayContentsInvalidated(_In_ DisplayInformation^ sender, _In_ Object^ args)
00160 {
00161     m_deviceResources->ValidateDevice();
00162     m_renderer->Draw();
00163 }
00164
00165 // Other event handlers.
00166
00167 void DirectXPage::OnCompositionScaleChanged(_In_ SwapChainPanel^ sender, _In_ Object^ args)
00168 {
00169     m_deviceResources->SetCompositionScale(sender->CompositionScaleX, sender->CompositionScaleY);
00170     m_renderer->CreateWindowSizeDependentResources();
00171     m_renderer->Draw();
00172 }
00173
00174 void DirectXPage::OnSwapChainPanelSizeChanged(_In_ Object^ sender, _In_ SizeChangedEventArgs^ e)
00175 {
00176     m_deviceResources->SetLogicalSize(e->NewSize);
00177     m_renderer->CreateWindowSizeDependentResources();
00178     m_renderer->Draw();
00179 }
00180
00181 // Update the PhotoAdjustmentRenderer with new property values.
00182 // Does nothing in cases where this operation is invalid.
00183 void DirectXPage::TryUpdateRenderer()
00184 {
00185     if (m_renderer != nullptr &&
00186         m_suppressRendererUpdates == false)
00187     {
00188         m_renderer->UpdatePhotoAdjustmentValues(m_properties);
00189         m_renderer->Draw();
00190     }
00191 }
00192
00193 // Databinding properties for the photo adjustment pipeline.
00194
00195 double DirectXPage::TemperatureValue::get() { return m_properties.TemperatureValue; }
00196 void   DirectXPage::TemperatureValue::set(double val)
00197 {
00198     m_properties.TemperatureValue = val;
00199     OnPropertyChanged("TemperatureValue");
00200     TryUpdateRenderer();
00201 }
00202
00203 double DirectXPage::TintValue::get() { return m_properties.TintValue; }
00204 void   DirectXPage::TintValue::set(double val)
00205 {
00206     m_properties.TintValue = val;
00207     OnPropertyChanged("TintValue");
00208     TryUpdateRenderer();
00209 }
00210
00211 double DirectXPage::SaturationValue::get() { return m_properties.SaturationValue; }
00212 void   DirectXPage::SaturationValue::set(double val)
00213 {
00214     m_properties.SaturationValue = val;
00215     OnPropertyChanged("SaturationValue");
00216     TryUpdateRenderer();
00217 }
00218
00219 double DirectXPage::ContrastValue::get() { return m_properties.ContrastValue; }
00220 void   DirectXPage::ContrastValue::set(double val)
00221 {
00222     m_properties.ContrastValue = val;
00223     OnPropertyChanged("ContrastValue");
00224     TryUpdateRenderer();
00225 }
00226
00227 double DirectXPage::ShadowsValue::get() { return m_properties.ShadowsValue; }
00228 void   DirectXPage::ShadowsValue::set(double val)
00229 {
00230     m_properties.ShadowsValue = val;
00231     OnPropertyChanged("ShadowsValue");
00232     TryUpdateRenderer();
00233 }
00234
00235 double DirectXPage::ClarityValue::get() { return m_properties.ClarityValue; }
00236 void   DirectXPage::ClarityValue::set(double val)
00237 {
00238     m_properties.ClarityValue = val;
00239     OnPropertyChanged("ClarityValue");
00240     TryUpdateRenderer();
00241 }
00242
00243 double DirectXPage::HighlightsValue::get() { return m_properties.HighlightsValue; }
00244 void   DirectXPage::HighlightsValue::set(double val)
00245 {
00246     m_properties.HighlightsValue = val;
00247     OnPropertyChanged("HighlightsValue");
00248     TryUpdateRenderer();
00249 }
00250
00251 double DirectXPage::StraightenValue::get() { return m_properties.StraightenValue; }
00252 void   DirectXPage::StraightenValue::set(double val)
00253 {
00254     m_properties.StraightenValue = val;
00255     OnPropertyChanged("StraightenValue");
00256     TryUpdateRenderer();
00257 }
00258
00259 double DirectXPage::HsMaskRadiusValue::get() { return m_properties.HsMaskRadiusValue; }
00260 void   DirectXPage::HsMaskRadiusValue::set(double val)
00261 {
00262     m_properties.HsMaskRadiusValue = val;
00263     OnPropertyChanged("HsMaskRadiusValue");
00264     TryUpdateRenderer();
00265 }
00266
00267 // INotifyPropertyChanged.
00268 void DirectXPage::OnPropertyChanged(String^ propertyName)
00269 {
00270     PropertyChanged(this, ref new PropertyChangedEventArgs(propertyName));
00271 }
Generated on Fri Nov 15 2024 22:19:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLOutOfProcessWinRTComponent/cpp/cs/Scenario2_CustomException.xaml.cs Source File

  • WRLOutOfProcessWinRTComponent
  • cpp
  • cs

Scenario2_CustomException.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 using Microsoft.SDKSamples.Kitchen;
00008
00009 using Windows.UI.Xaml;
00010 using Windows.UI.Xaml.Controls;
00011 using Windows.UI.Xaml.Navigation;
00012 using SDKTemplate;
00013 using System;
00014
00015 namespace WRLOutOfProcessWinRTComponent
00016 {
00017     public sealed partial class CustomException : Page
00018     {
00019         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00020         // as NotifyUser()
00021         MainPage rootPage = MainPage.Current;
00022
00023         public CustomException()
00024         {
00025             this.InitializeComponent();
00026         }
00027
00028         /// <summary>
00029         /// Invoked when this page is about to be displayed in a Frame.
00030         /// </summary>
00031         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00032         /// property is typically used to configure the page.</param>
00033         protected override void OnNavigatedTo(NavigationEventArgs e)
00034         {
00035         }
00036
00037         /// <summary>
00038         /// Handle a Windows Runtime error originated by the Oven Windows Runtime component.
00039         /// </summary>
00040         /// <param name="sender">Contains information about the button that fired the event.</param>
00041         /// <param name="e">Contains state information and event data associated with a routed event.</param>
00042         private void Start_Click(object sender, RoutedEventArgs e)
00043         {
00044             Oven myOven = new Oven();
00045
00046             try
00047             {
00048                 // Intentionally pass a bad parameter
00049                 myOven.ConfigurePreheatTemperature((OvenTemperature)5);
00050             }
00051             catch (System.ArgumentException)
00052             {
00053                 CustomExceptionOutput.Text += "Exception caught. Please attach a debugger and enable first chance native exceptions to view exception details.\n";
00054             }
00055         }
00056     }
00057 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GameTimer Member List

This is the complete list of members for GameTimer, including all inherited members.
Active() | GameTimer | [inline]
DeltaTime() | GameTimer |
GameTimer() | GameTimer |
m_active | GameTimer | [private]
m_baseTime | GameTimer | [private]
m_currentTime | GameTimer | [private]
m_deltaTime | GameTimer | [private]
m_pausedTime | GameTimer | [private]
m_previousTime | GameTimer | [private]
m_secondsPerCount | GameTimer | [private]
m_stopTime | GameTimer | [private]
PlayingTime() | GameTimer |
PlayingTime(float time) | GameTimer |
Reset() | GameTimer |
Start() | GameTimer |
Stop() | GameTimer |
Update() | GameTimer |
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MainPage_OneHanded Member List

This is the complete list of members for MainPage_OneHanded, including all inherited members.
MainPage_OneHanded() MainPage_OneHanded [inline]
Generated on Fri Nov 15 2024 22:23:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_UTF8 Member List

This is the complete list of members for Scenario1_UTF8, including all inherited members.
AppendOutputLine(hstring const &value) | Scenario1_UTF8 | [private]
CloseSocket() | Scenario1_UTF8 | [private]
ConnectAsync() | Scenario1_UTF8 | [private]
MessageReceived(Windows::Networking::Sockets::MessageWebSocket const &sender, Windows::Networking::Sockets::MessageWebSocketMessageReceivedEventArgs e) | Scenario1_UTF8 | [private]
OnClosed(Windows::Networking::Sockets::IWebSocket sender, Windows::Networking::Sockets::WebSocketClosedEventArgs e) | Scenario1_UTF8 | [private]
OnConnect(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1_UTF8 |
OnDisconnect(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1_UTF8 |
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &) | Scenario1_UTF8 |
OnSend(Windows::Foundation::IInspectable const &, Windows::UI::Xaml::RoutedEventArgs const &) | Scenario1_UTF8 |
OnServerCustomValidationRequested(Windows::Networking::Sockets::MessageWebSocket const &, Windows::Networking::Sockets::WebSocketServerCustomValidationRequestedEventArgs e) | Scenario1_UTF8 | [private]
Scenario1_UTF8() | Scenario1_UTF8 |
SendAsync() | Scenario1_UTF8 | [private]
SetBusy(bool value) | Scenario1_UTF8 | [private]
UpdateVisualState() | Scenario1_UTF8 | [private]
Generated on Fri Nov 15 2024 22:24:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/pch.h Source File

  • ShareSource
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "SampleConfiguration.h"
00011 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CritSec Member List

This is the complete list of members for CritSec, including all inherited members.
_Acquires_lock_(m_criticalSection) void Lock() | CritSec | [inline]
_Releases_lock_(m_criticalSection) void Unlock() | CritSec | [inline]
CritSec() | CritSec | [inline]
m_criticalSection | CritSec |
~CritSec() | CritSec | [inline]
Generated on Fri Nov 15 2024 22:23:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_RequestMany Member List

This is the complete list of members for Scenario2_RequestMany, including all inherited members.
RequestAccessButton_Click(object sender, RoutedEventArgs e) | Scenario2_RequestMany | [inline, private]
rootPage | Scenario2_RequestMany | [private]
Scenario2_RequestMany() | Scenario2_RequestMany | [inline]
Generated on Fri Nov 15 2024 22:23:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MobileHotspot/cppwinrt/SampleConfiguration.cpp Source File

  • MobileHotspot
  • cppwinrt

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include <winrt/SDKTemplate.h>
00014 #include "MainPage.h"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::Networking::Connectivity;
00021 using namespace Windows::Networking::NetworkOperators;
00022
00023 namespace winrt::SDKTemplate
00024 {
00025     hstring implementation::MainPage::FEATURE_NAME()
00026     {
00027         return L"MobileHotspot C++/WinRT Sample";
00028     }
00029
00030     IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
00031     {
00032         Scenario{ L"Configure Mobile Hotspot", xaml_typename<SDKTemplate::Scenario1_ConfigureMobileHotspot>() },
00033         Scenario{ L"Toggle Mobile Hotspot", xaml_typename<SDKTemplate::Scenario2_ToggleMobileHotspot>() },
00034     });
00035
00036
00037     NetworkOperatorTetheringManager TryGetCurrentNetworkOperatorTetheringManager()
00038     {
00039         // Get the connection profile associated with the internet connection currently used by the local machine.
00040         ConnectionProfile currentConnectionProfile = NetworkInformation::GetInternetConnectionProfile();
00041         if (currentConnectionProfile == nullptr)
00042         {
00043             MainPage::Current().NotifyUser(L"System is not connected to the Internet.", NotifyType::ErrorMessage);
00044             return nullptr;
00045         }
00046
00047         TetheringCapability tetheringCapability =
00048             NetworkOperatorTetheringManager::GetTetheringCapabilityFromConnectionProfile(currentConnectionProfile);
00049
00050         if (tetheringCapability != TetheringCapability::Enabled)
00051         {
00052             hstring message;
00053             switch (tetheringCapability)
00054             {
00055             case TetheringCapability::DisabledByGroupPolicy:
00056                 message = L"Tethering is disabled due to group policy.";
00057                 break;
00058             case TetheringCapability::DisabledByHardwareLimitation:
00059                 message = L"Tethering is not available due to hardware limitations.";
00060                 break;
00061             case TetheringCapability::DisabledByOperator:
00062                 message = L"Tethering operations are disabled for this account by the network operator.";
00063                 break;
00064             case TetheringCapability::DisabledByRequiredAppNotInstalled:
00065                 message = L"An application required for tethering operations is not available.";
00066                 break;
00067             case TetheringCapability::DisabledBySku:
00068                 message = L"Tethering is not supported by the current account services.";
00069                 break;
00070             case TetheringCapability::DisabledBySystemCapability:
00071                 // This will occur if the "wiFiControl" capability is missing from the App.
00072                 message = L"This app is not configured to access Wi-Fi devices on this machine.";
00073                 break;
00074             default:
00075                 message = L"Tethering is disabled on this machine. (Code " + to_hstring(static_cast<int32_t>(tetheringCapability)) + L").";
00076                 break;
00077             }
00078             MainPage::Current().NotifyUser(message, NotifyType::ErrorMessage);
00079             return nullptr;
00080         }
00081
00082         try
00083         {
00084             return NetworkOperatorTetheringManager::CreateFromConnectionProfile(currentConnectionProfile);
00085         }
00086         catch (hresult_error const& ex)
00087         {
00088             if (ex.code() == HRESULT_FROM_WIN32(ERROR_NOT_FOUND))
00089             {
00090                 MainPage::Current().NotifyUser(L"System has no Wi-Fi adapters.", NotifyType::ErrorMessage);
00091                 return nullptr;
00092             }
00093             throw;
00094         }
00095     }
00096
00097     hstring GetFriendlyName(TetheringWiFiBand value)
00098     {
00099         switch (value)
00100         {
00101         case TetheringWiFiBand::Auto: return L"Any available";
00102         case TetheringWiFiBand::TwoPointFourGigahertz: return L"2.4 GHz";
00103         case TetheringWiFiBand::FiveGigahertz: return L"5 Ghz";
00104         default: return L"Unknown (" + to_hstring(static_cast<uint32_t>(value)) + L")";
00105         }
00106     }
00107
00108     // Calls NetworkOperatorTetheringAccessPointConfiguration.IsBandSupported but handles
00109     // certain boundary cases.
00110
00111     bool IsBandSupported(NetworkOperatorTetheringAccessPointConfiguration const& configuration, TetheringWiFiBand band)
00112     {
00113         // "Auto" mode is always supported even though it is technically not a frequency band.
00114         if (band == TetheringWiFiBand::Auto)
00115         {
00116             return true;
00117         }
00118
00119         try
00120         {
00121             return configuration.IsBandSupported(band);
00122         }
00123         catch (hresult_error const& ex)
00124         {
00125             if (ex.code() == HRESULT_FROM_WIN32(ERROR_INVALID_STATE))
00126             {
00127                 // The WiFi device has been disconnected. Report that we support nothing.
00128                 return false;
00129             }
00130             throw;
00131         }
00132     }
00133 }
Generated on Fri Nov 15 2024 22:17:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdaptiveStreaming/cs/Helpers/CommonLicenseRequest.cs Source File

  • AdaptiveStreaming
  • cs
  • Helpers

CommonLicenseRequest.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012
00013
00014 using System;
00015 using System.Net;
00016 using System.Net.Http;
00017 using System.Threading.Tasks;
00018
00019 namespace SDKTemplate.Helpers
00020 {
00021     public class CommonLicenseRequest
00022     {
00023         private string lastErrorMessage;
00024         private HttpClient httpClient;
00025         public string GetLastErrorMessage()
00026         {
00027             return lastErrorMessage;
00028         }
00029         public CommonLicenseRequest(HttpClient client = null)
00030         {
00031             if (client == null)
00032                 httpClient = new HttpClient();
00033             else
00034                 httpClient = client;
00035             lastErrorMessage = string.Empty;
00036         }
00037         /// <summary>
00038         /// Invoked to acquire the PlayReady license.
00039         /// </summary>
00040         /// <param name="licenseServerUri">License Server URI to retrieve the PlayReady license.</param>
00041         /// <param name="httpRequestContent">HttpContent including the Challenge transmitted to the PlayReady server.</param>
00042         public async virtual Task<HttpContent> AcquireLicenseAsync(Uri licenseServerUri, HttpContent httpRequestContent)
00043         {
00044             try
00045             {
00046                 httpClient.DefaultRequestHeaders.Add("msprdrm_server_redirect_compat", "false");
00047                 httpClient.DefaultRequestHeaders.Add("msprdrm_server_exception_compat", "false");
00048
00049                 HttpResponseMessage response = await httpClient.PostAsync(licenseServerUri, httpRequestContent);
00050                 response.EnsureSuccessStatusCode();
00051
00052                 if (response.StatusCode == HttpStatusCode.OK)
00053                 {
00054                     lastErrorMessage = string.Empty;
00055                     return response.Content;
00056                 }
00057                 else
00058                 {
00059                     lastErrorMessage = "AcquireLicense - Http Response Status Code: " + response.StatusCode.ToString();
00060                 }
00061             }
00062             catch (Exception exception)
00063             {
00064                 lastErrorMessage = exception.Message;
00065                 return null;
00066             }
00067             return null;
00068         }
00069     }
00070 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cppwinrt/Scenario5_UnicodeExtensions.cpp Source File

  • DateTimeFormatting
  • cppwinrt

Scenario5_UnicodeExtensions.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario5_UnicodeExtensions.h"
00014 #include "Scenario5_UnicodeExtensions.g.cpp"
00015 #include "SampleConfiguration.h"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Globalization;
00020 using namespace Windows::Globalization::DateTimeFormatting;
00021 using namespace Windows::UI::Xaml;
00022
00023 namespace winrt::SDKTemplate::implementation
00024 {
00025     Scenario5_UnicodeExtensions::Scenario5_UnicodeExtensions()
00026     {
00027         InitializeComponent();
00028     }
00029
00030     void Scenario5_UnicodeExtensions::Display_Click(IInspectable const&, RoutedEventArgs const&)
00031     {
00032         // This scenario uses the Windows.Globalization.DateTimeFormatting.DateTimeFormatter class
00033         // to format a date/time by using a formatter that uses unicode extensions in the specified
00034         // language name
00035
00036         // Get the current application context language
00037         hstring currentLanguage = ApplicationLanguages::Languages().GetAt(0);
00038
00039         // Keep the results here
00040         std::wostringstream results;
00041         results << L"Current application context language: " << std::wstring_view(currentLanguage) << std::endl << std::endl;
00042
00043         // Formatters for dates and times
00044         std::array dateFormatters{
00045             // Default application context
00046             DateTimeFormatter(L"longdate longtime"),
00047
00048             // Telugu language, Gregorian Calendar and Latin Numeral System
00049             DateTimeFormatter(L"longdate longtime", { L"te-in-u-ca-gregory-nu-latn", L"en-US" }),
00050
00051             // Hebrew language and Arabic Numeral System - calendar NOT specified in constructor
00052             DateTimeFormatter(YearFormat::Default,
00053                 MonthFormat::Default,
00054                 DayFormat::Default,
00055                 DayOfWeekFormat::Default,
00056                 HourFormat::Default,
00057                 MinuteFormat::Default,
00058                 SecondFormat::Default,
00059                 { L"he-IL-u-nu-arab", L"en-US" }),
00060
00061                 // Hebrew language and calendar - calendar specified in constructor
00062                 // also, which overrides the one specified in Unicode extension
00063                 DateTimeFormatter(YearFormat::Default,
00064                     MonthFormat::Default,
00065                     DayFormat::Default,
00066                     DayOfWeekFormat::Default,
00067                     HourFormat::Default,
00068                     MinuteFormat::Default,
00069                     SecondFormat::Default,
00070                     { L"he-IL-u-ca-hebrew-co-phonebk", L"en-US" },
00071                     L"US",
00072                     CalendarIdentifiers::Gregorian(),
00073                     ClockIdentifiers::TwentyFourHour()),
00074         };
00075
00076         // Obtain the date that will be formatted.
00077         DateTime dateToFormat = clock::now();
00078
00079         // Format and display date/time along with other relevant properites
00080         for (auto&& formatter : dateFormatters)
00081         {
00082             // Perform the actual formatting.
00083             results << L"Result: " << std::wstring_view(formatter.Format(dateToFormat)) << std::endl;
00084             results << L"    Language List: " << std::wstring_view(StringJoin(L", ", formatter.Languages())) << std::endl;
00085             results << L"    Template: " << std::wstring_view(formatter.Template()) << std::endl;
00086             results << L"    Resolved Language: " << std::wstring_view(formatter.ResolvedLanguage()) << std::endl;
00087             results << L"    Calendar System: " << std::wstring_view(formatter.Calendar()) << std::endl;
00088             results << L"    Numeral System: " << std::wstring_view(formatter.NumeralSystem()) << std::endl << std::endl;
00089         }
00090
00091         // Display the results.
00092         OutputTextBlock().Text(results.str());
00093     }
00094 }
Generated on Fri Nov 15 2024 22:19:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DataReaderWriter/cs/Scenario2_ReadBytes.xaml.cs Source File

  • DataReaderWriter
  • cs

Scenario2_ReadBytes.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using Windows.UI.Xaml;
00012 using Windows.UI.Xaml.Controls;
00013 using Windows.UI.Xaml.Navigation;
00014 using SDKTemplate;
00015 using System;
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     public sealed partial class ReadBytes : Page
00023     {
00024         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00025         // as NotifyUser()
00026         MainPage rootPage = MainPage.Current;
00027
00028         private const int bytesPerRow = 16;
00029         private const int bytesPerSegment = 2;
00030         private const uint chunkSize = 4096;
00031
00032         public ReadBytes()
00033         {
00034             this.InitializeComponent();
00035         }
00036
00037         /// <summary>
00038         /// Invoked when this page is about to be displayed in a Frame.
00039         /// </summary>
00040         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00041         /// property is typically used to configure the page.</param>
00042         protected override void OnNavigatedTo(NavigationEventArgs e)
00043         {
00044         }
00045
00046         /// <summary>
00047         /// This is the click handler for the 'Hex Dump' button.  Open the image file we want to
00048         /// perform a hex dump on.  Then open a sequential-access stream over the file and use
00049         /// ReadBytes() to extract the binary data.  Finally, convert each byte to hexadecimal, and
00050         /// display the formatted output in the HexDump textblock.
00051         /// </summary>
00052         /// <param name="sender">Contains information about the button that fired the event.</param>
00053         /// <param name="e">Contains state information and event data associated with a routed event.</param>
00054         private async void HexDump(object sender, RoutedEventArgs e)
00055         {
00056             try
00057             {
00058                 // Retrieve the uri of the image and use that to load the file.
00059                 Uri uri = new Uri("ms-appx:///assets/microsoft-sdk.png");
00060                 var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
00061
00062                 // Open a sequential-access stream over the image file.
00063                 using (var inputStream = await file.OpenSequentialReadAsync())
00064                 {
00065                     // Pass the input stream to the DataReader.
00066                     using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream))
00067                     {
00068                         uint currChunk = 0;
00069                         uint numBytes;
00070                         ReadBytesOutput.Text = "";
00071
00072                         // Create a byte array which can hold enough bytes to populate a row of the hex dump.
00073                         var bytes = new byte[bytesPerRow];
00074
00075                         do
00076                         {
00077                             // Load the next chunk into the DataReader buffer.
00078                             numBytes = await dataReader.LoadAsync(chunkSize);
00079
00080                             // Read and print one row at a time.
00081                             var numBytesRemaining = numBytes;
00082                             while (numBytesRemaining >= bytesPerRow)
00083                             {
00084                                 // Use the DataReader and ReadBytes() to fill the byte array with one row worth of bytes.
00085                                 dataReader.ReadBytes(bytes);
00086
00087                                 PrintRow(bytes, (numBytes - numBytesRemaining) + (currChunk * chunkSize));
00088
00089                                 numBytesRemaining -= bytesPerRow;
00090                             }
00091
00092                             // If there are any bytes remaining to be read, allocate a new array that will hold
00093                             // the remaining bytes read from the DataReader and print the final row.
00094                             // Note: ReadBytes() fills the entire array so if the array being passed in is larger
00095                             // than what's remaining in the DataReader buffer, an exception will be thrown.
00096                             if (numBytesRemaining > 0)
00097                             {
00098                                 bytes = new byte[numBytesRemaining];
00099
00100                                 // Use the DataReader and ReadBytes() to fill the byte array with the last row worth of bytes.
00101                                 dataReader.ReadBytes(bytes);
00102
00103                                 PrintRow(bytes, (numBytes - numBytesRemaining) + (currChunk * chunkSize));
00104                             }
00105
00106                             currChunk++;
00107                         // If the number of bytes read is anything but the chunk size, then we've just retrieved the last
00108                         // chunk of data from the stream.  Otherwise, keep loading data into the DataReader buffer.
00109                         } while (numBytes == chunkSize);
00110                     }
00111                 }
00112             }
00113             catch (Exception ex)
00114             {
00115                 ReadBytesOutput.Text = ex.Message;
00116             }
00117         }
00118
00119         /// <summary>
00120         /// Format and print a row of the hex dump using the data retrieved by ReadBytes().
00121         /// </summary>
00122         /// <param name="bytes">An array that holds the data we want to format and output.</param>
00123         /// <param name="currByte">Value to be formatted into an address.</param>
00124         private void PrintRow(byte[] bytes, uint currByte)
00125         {
00126             var rowStr = "";
00127
00128             // Format the address of byte i to have 8 hexadecimal digits and add the address
00129             // of the current byte to the output string.
00130             rowStr += currByte.ToString("x8");
00131
00132             // Format the output:
00133             for (int i = 0; i < bytes.Length; i++)
00134             {
00135                 // If finished with a segment, add a space.
00136                 if (i % bytesPerSegment == 0)
00137                 {
00138                     rowStr += " ";
00139                 }
00140
00141                 // Convert the current byte value to hex and add it to the output string.
00142                 rowStr += bytes[i].ToString("x2");
00143             }
00144
00145             // Append the current row to the HexDump textblock.
00146             ReadBytesOutput.Text += rowStr + "\n";
00147         }
00148     }
00149 }
Generated on Fri Nov 15 2024 22:19:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/Animate.h Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

Animate.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 // Animate:
00015 // This is an abstract class for animations. It defines a set of
00016 // capabilities for animating XMFLOAT3 variables. An animation has the following
00017 // characteristics:
00018 //     Start - the time for the animation to start.
00019 //     Duration - the length of time the animation is to run.
00020 //     Continuous - whether the animation loops after duration is reached or just
00021 //         stops.
00022 // There are two query functions:
00023 //     IsActive - determines if the animation is active at time t.
00024 //     IsFinished - determines if the animation is done at time t.
00025 // It is expected that each derived class will provide an Evaluate method for the
00026 // specific kind of animation.
00027
00028 class Animate
00029 {
00030 public:
00031     Animate();
00032
00033     virtual DirectX::XMFLOAT3 Evaluate(_In_ float t) = 0;
00034
00035     bool  IsActive(_In_ float t) { return ((t >= m_startTime) && (m_continuous || (t < (m_startTime + m_duration)))); };
00036     bool  IsFinished(_In_ float t) { return (!m_continuous && (t >= (m_startTime + m_duration))); }
00037     float Start();
00038     void  Start(_In_ float start);
00039     float Duration();
00040     void  Duration(_In_ float duration);
00041     bool  Continuous();
00042     void  Continuous(_In_ bool continuous);
00043
00044 protected:
00045     bool  m_continuous;      // if true means at end cycle back to beginning
00046     float m_duration;        // for continuous this is the duration of 1 cycle through path
00047     float m_startTime;       // time at which animation begins
00048 };
00049
00050 // AnimateLinePosition:
00051 // This class is a specialization of Animate that defines an animation of a position vector
00052 // along a straight line defined in world coordinates from startPosition to endPosition.
00053
00054 class AnimateLinePosition : public Animate
00055 {
00056 public:
00057     AnimateLinePosition(
00058         _In_ DirectX::XMFLOAT3 startPosition,
00059         _In_ DirectX::XMFLOAT3 endPosition,
00060         _In_ float duration,
00061         _In_ bool continuous
00062         );
00063     virtual DirectX::XMFLOAT3 Evaluate(_In_ float t) override;
00064
00065 private:
00066     DirectX::XMFLOAT3 m_startPosition;
00067     DirectX::XMFLOAT3 m_endPosition;
00068     float             m_length;
00069 };
00070
00071 //----------------------------------------------------------------------
00072
00073 struct LineSegment
00074 {
00075     DirectX::XMFLOAT3 position;
00076     float             length;
00077     float             uStart;
00078     float             uLength;
00079 };
00080
00081 // AnimateLineListPosition:
00082 // This class is a specialization of Animate that defines an animation of a position vector
00083 // along a set of line segments defined by a set of points. The animation along the path is
00084 // such that the evaluation of the position along the path will be uniform independent of
00085 // the length of each of the line segments. A continuous loop can be achieved by having the
00086 // first and last points of the list be the same.
00087
00088 class AnimateLineListPosition : public Animate
00089 {
00090 public:
00091     AnimateLineListPosition(
00092         _In_ unsigned int count,
00093         _In_reads_(count) DirectX::XMFLOAT3 const position[],
00094         _In_ float duration,
00095         _In_ bool continuous
00096         );
00097     virtual DirectX::XMFLOAT3 Evaluate(_In_ float t) override;
00098
00099 private:
00100     unsigned int             m_count;
00101     float                    m_totalLength;
00102     std::vector<LineSegment> m_segment;
00103 };
00104
00105 // AnimateCirclePosition:
00106 // This class is a specialization of Animate that defines an animation of a position vector
00107 // along a circular path centered at 'center' with a starting point of 'startPosition'. The
00108 // distance between 'center' and 'startPosition' defines the radius of the circle. The plane
00109 // of the circle will pass through 'center' and 'startPosition' and have a normal of 'planeNormal'.
00110 // The direction of the animation can be either clockwise or counterclockwise based
00111 // on the 'clockwise' parameter.
00112
00113 class AnimateCirclePosition : public Animate
00114 {
00115 public:
00116     AnimateCirclePosition(
00117         _In_ DirectX::XMFLOAT3 center,
00118         _In_ DirectX::XMFLOAT3 startPosition,
00119         _In_ DirectX::XMFLOAT3 planeNormal,
00120         _In_ float duration,
00121         _In_ bool continuous,
00122         _In_ bool clockwise
00123         );
00124     virtual DirectX::XMFLOAT3 Evaluate(_In_ float t) override;
00125
00126 private:
00127     DirectX::XMFLOAT4X4 m_rotationMatrix;
00128     DirectX::XMFLOAT3   m_center;
00129     DirectX::XMFLOAT3   m_planeNormal;
00130     DirectX::XMFLOAT3   m_startPosition;
00131     float               m_radius;
00132     bool                m_clockwise;
00133 };
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicSuspension/cs/SubPage.xaml.cs Source File

  • BasicSuspension
  • cs

SubPage.xaml.cs

Go to the documentation of this file.
00001 ﻿using SDKTemplate.Common;
00002 using System;
00003 using System.Collections.Generic;
00004 using Windows.UI.Xaml.Controls;
00005 using Windows.UI.Xaml.Navigation;
00006 using Windows.UI.Core;
00007
00008 namespace SDKTemplate
00009 {
00010     public sealed partial class SubPage : Page
00011     {
00012         private readonly NavigationHelper navigationHelper;
00013         private int tapCount;
00014
00015         public SubPage()
00016         {
00017             this.InitializeComponent();
00018             this.navigationHelper = new NavigationHelper(this);
00019             this.navigationHelper.LoadState += LoadState;
00020             this.navigationHelper.SaveState += SaveState;
00021
00022             SystemNavigationManager.GetForCurrentView().BackRequested += Navigation_BackRequested;
00023         }
00024
00025         #region NavigationHelper registration
00026
00027         /// <summary>
00028         /// The methods provided in this section are simply used to allow
00029         /// NavigationHelper to respond to the page's navigation methods.
00030         /// <para>
00031         /// Page specific logic should be placed in event handlers for the
00032         /// <see cref="NavigationHelper.LoadState"/>
00033         /// and <see cref="NavigationHelper.SaveState"/>.
00034         /// The navigation parameter is available in the LoadState method
00035         /// in addition to page state preserved during an earlier session.
00036         /// </para>
00037         /// </summary>
00038         /// <param name="e">Provides data for navigation methods and event
00039         /// handlers that cannot cancel the navigation request.</param>
00040
00041         protected override void OnNavigatedTo(NavigationEventArgs e)
00042         {
00043             this.TitleTextBlock.Text = e.Parameter.ToString();
00044
00045             this.navigationHelper.OnNavigatedTo(e);
00046
00047             SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
00048                 this.Frame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;
00049         }
00050
00051         protected override void OnNavigatedFrom(NavigationEventArgs e)
00052         {
00053             this.navigationHelper.OnNavigatedFrom(e);
00054         }
00055
00056         private void LoadState(object sender, LoadStateEventArgs e)
00057         {
00058             tapCount = 0;
00059             if (e.PageState != null && e.PageState.ContainsKey("tapCount"))
00060             {
00061                 tapCount = (int)e.PageState["tapCount"];
00062             }
00063             TapCountRun.Text = tapCount.ToString();
00064         }
00065
00066         private void SaveState(object sender, SaveStateEventArgs e)
00067         {
00068             e.PageState["tapCount"] = tapCount;
00069         }
00070         #endregion
00071
00072         /// <summary>
00073         /// This method facilitates navigation when the back button is pressed.
00074         /// </summary>
00075         /// <param name="sender"></param>
00076         /// <param name="e"></param>
00077         private void Navigation_BackRequested(object sender, BackRequestedEventArgs e)
00078         {
00079             if (!e.Handled & this.Frame.CanGoBack)
00080             {
00081                 e.Handled = true;
00082                 this.Frame.GoBack();
00083             }
00084         }
00085
00086         private void Page_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
00087         {
00088             tapCount++;
00089             TapCountRun.Text = tapCount.ToString();
00090         }
00091     }
00092 }
Generated on Fri Nov 15 2024 22:18:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MediaEditing/cpp/Scenario2_AppendClips.xaml.h Source File

  • MediaEditing
  • cpp

Scenario2_AppendClips.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2_AppendClips.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario2_AppendClips sealed
00024     {
00025     public:
00026         Scenario2_AppendClips();
00027
00028     protected:
00029         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00030
00031     private:
00032         SDKTemplate::MainPage^ rootPage;
00033         Windows::Media::Editing::MediaComposition^ composition;
00034         Windows::Storage::StorageFile^ firstVideoFile;
00035         Windows::Storage::StorageFile^ secondVideoFile;
00036         Windows::Media::Core::MediaStreamSource^ mediaStreamSource;
00037
00038         void ChooseFirstVideo_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         void ChooseSecondVideo_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040         void AppendVideos_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00041     };
00042 }
Generated on Fri Nov 15 2024 22:20:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cs/Scenario6_AppListingURI.xaml.cs Source File

  • Store
  • cs

Scenario6_AppListingURI.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Services.Store;
00014 using Windows.UI.Xaml.Controls;
00015
00016 namespace SDKTemplate
00017 {
00018     /// <summary>
00019     /// A page for sixth scenario.
00020     /// </summary>
00021     public sealed partial class Scenario6_AppListingURI : Page
00022     {
00023         MainPage rootPage = MainPage.Current;
00024         private StoreContext storeContext = StoreContext.GetDefault();
00025
00026         public Scenario6_AppListingURI()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         private async void DisplayLink()
00032         {
00033             StoreProductResult result = await storeContext.GetStoreProductForCurrentAppAsync();
00034             if (result.ExtendedError != null)
00035             {
00036                 Utils.ReportExtendedError(result.ExtendedError);
00037                 return;
00038             }
00039
00040             await Windows.System.Launcher.LaunchUriAsync(result.Product.LinkUri);
00041         }
00042     }
00043 }
Generated on Fri Nov 15 2024 22:21:42 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PosPrinter/cpp/SampleConfiguration.h Source File

  • PosPrinter
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "POS Printer C++ Sample";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038         Windows::Devices::PointOfService::PosPrinter^ Printer = nullptr;
00039         Windows::Devices::PointOfService::ClaimedPosPrinter^ ClaimedPrinter = nullptr;
00040         Windows::Devices::Enumeration::DeviceInformation^ deviceInfo = nullptr;
00041
00042         bool IsAnImportantTransaction = true;
00043         std::function<void(void)> StateChanged;
00044
00045         void SubscribeToReleaseDeviceRequested();
00046         void ReleaseClaimedPrinter();
00047         void ReleaseAllPrinters();
00048
00049     private:
00050         static Platform::Array<Scenario>^ scenariosInner;
00051
00052         Windows::Foundation::EventRegistrationToken releaseDeviceRequestedToken;
00053         void ClaimedPrinter_ReleaseDeviceRequested(Windows::Devices::PointOfService::ClaimedPosPrinter^ sender, Windows::Devices::PointOfService::PosPrinterReleaseDeviceRequestedEventArgs^ args);
00054     };
00055
00056     public value struct Scenario
00057     {
00058         Platform::String^ Title;
00059         Platform::String^ ClassName;
00060     };
00061 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlAnimatedGif/cpp/Scenario1_Basic.xaml.h Source File

  • XamlAnimatedGif
  • cpp

Scenario1_Basic.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Basic.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario1_Basic sealed
00021     {
00022     public:
00023         Scenario1_Basic();
00024
00025     protected:
00026         void ClickToPlaySource_ImageOpened(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00027     };
00028 }
Generated on Fri Nov 15 2024 22:19:50 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: GlobalizationPreferences/cpp/Scenario1_Prefs.xaml.h Source File

  • GlobalizationPreferences
  • cpp

Scenario1_Prefs.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_Prefs.g.h"
00015
00016 namespace SDKTemplate
00017 {
00018     [Windows::Foundation::Metadata::WebHostHidden]
00019     public ref class Scenario1_Prefs sealed
00020     {
00021     public:
00022         Scenario1_Prefs();
00023         void ShowResults_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00024     };
00025 }
Generated on Fri Nov 15 2024 22:19:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/ListsAndTemplates.xaml.h Source File

  • XamlBind
  • cpp

ListsAndTemplates.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // ListsAndTemplates.xaml.h
00003 // Declaration of the ListsAndTemplates class
00004 //
00005
00006 #pragma once
00007
00008 #include "ListsAndTemplates.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     /// <summary>
00013     /// An empty page that can be used on its own or navigated to within a Frame.
00014     /// </summary>
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class ListsAndTemplates sealed
00017     {
00018     public:
00019         ListsAndTemplates();
00020
00021         property Windows::Foundation::Collections::IObservableVector<xBindSampleModel::IEmployee^>^ Employees;
00022         property xBindSampleModel::DataModel^ Model;
00023
00024     private:
00025         void InitializeValues();
00026         void UpdateValuesClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00027         void ResetValuesClick(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^ e);
00028
00029
00030
00031     };
00032 }
Generated on Fri Nov 15 2024 22:22:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_DeviceWatcher Member List

This is the complete list of members for Scenario2_DeviceWatcher, including all inherited members.
deviceWatcherHelper | Scenario2_DeviceWatcher | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario2_DeviceWatcher |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario2_DeviceWatcher |
resultCollection | Scenario2_DeviceWatcher | [private]
Scenario2_DeviceWatcher() | Scenario2_DeviceWatcher |
StartWatcher() | Scenario2_DeviceWatcher | [private]
StartWatcherButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_DeviceWatcher |
StopWatcher() | Scenario2_DeviceWatcher | [private]
StopWatcherButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario2_DeviceWatcher |
Generated on Fri Nov 15 2024 22:24:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: UserActivity/cs/SampleConfiguration.cs Source File

  • UserActivity
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.ApplicationModel.Activation;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017
00018 namespace SDKTemplate
00019 {
00020     public partial class MainPage : Page
00021     {
00022         public const string FEATURE_NAME = "UserActivity C# Sample";
00023
00024         List<Scenario> scenarios = new List<Scenario>
00025         {
00026             new Scenario() { Title="Basic User Activity", ClassType=typeof(Scenario1_BasicUserActivity) },
00027             new Scenario() { Title="Advanced User Activity", ClassType=typeof(Scenario2_AdvancedUserActivity) },
00028             new Scenario() { Title="Adaptive Cards", ClassType=typeof(Scenario3_AdaptiveCard) },
00029         };
00030
00031         public void NavigateToScenarioWithParameter(Scenario scenario, object parameter)
00032         {
00033             ScenarioControl.SelectedIndex = scenarios.IndexOf(scenario);
00034             ScenarioFrame.Navigate(scenario.ClassType, parameter);
00035         }
00036     }
00037
00038     public class Scenario
00039     {
00040         public string Title { get; set; }
00041         public Type ClassType { get; set; }
00042     }
00043
00044     public partial class App : Application
00045     {
00046         protected override void OnActivated(IActivatedEventArgs e)
00047         {
00048             if (e.Kind == ActivationKind.Protocol)
00049             {
00050                 Frame rootFrame = CreateRootFrame();
00051
00052                 if (rootFrame.Content == null)
00053                 {
00054                     if (!rootFrame.Navigate(typeof(MainPage)))
00055                     {
00056                         throw new Exception("Failed to create initial page");
00057                     }
00058                 }
00059
00060                 var mainPage = rootFrame.Content as MainPage;
00061
00062                 // If no matching page found, then just go to the first scenario.
00063                 Scenario destinationScenario = mainPage.Scenarios[0];
00064
00065                 // Look for a matching scenario page.
00066                 var protocolArgs = (IProtocolActivatedEventArgs)e;
00067                 var query = protocolArgs.Uri.Query;
00068                 if (query.StartsWith("?"))
00069                 {
00070                     var pageName = query.Substring(1);
00071                     foreach (var scenario in mainPage.Scenarios)
00072                     {
00073                         if (scenario.ClassType.Name == pageName)
00074                         {
00075                             destinationScenario = scenario;
00076                         }
00077                     }
00078                 }
00079
00080                 mainPage.NavigateToScenarioWithParameter(destinationScenario, $"Activated from URI: {protocolArgs.Uri}");
00081
00082                 // Ensure the current window is active
00083                 Window.Current.Activate();
00084             }
00085         }
00086     }
00087 }
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FileAccess/cpp/Scenario2_GetParent.xaml.cpp Source File

  • FileAccess
  • cpp

Scenario2_GetParent.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2_GetParent.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace concurrency;
00018 using namespace Platform;
00019 using namespace Windows::Storage;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Navigation;
00022
00023 Scenario2::Scenario2()
00024 {
00025     InitializeComponent();
00026 }
00027
00028 void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
00029 {
00030     rootPage->ValidateFile();
00031 }
00032
00033 void Scenario2::GetParent_Click(Object^ sender, RoutedEventArgs^ e)
00034 {
00035     StorageFile^ file = rootPage->SampleFile;
00036     if (file != nullptr)
00037     {
00038         create_task(file->GetParentAsync()).then([this, file](StorageFolder^ parentFolder)
00039         {
00040             if (parentFolder != nullptr)
00041             {
00042                 String^ outputText = "Item: " + file->Name + " (" + file->Path + ")";
00043                 outputText += "\nParent: " + parentFolder->Name + " (" + parentFolder->Path + ")";
00044                 rootPage->NotifyUser(outputText, NotifyType::StatusMessage);
00045             }
00046         });
00047     }
00048     else
00049     {
00050         rootPage->NotifyUserFileNotExist();
00051     }
00052 }
Generated on Fri Nov 15 2024 22:19:36 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

LiveDashPlayer Member List

This is the complete list of members for LiveDashPlayer, including all inherited members.
Close() | LiveDashPlayer | [inline]
DesiredLiveOffset(TimeSpan offset) | LiveDashPlayer | [inline]
GoToLive() | LiveDashPlayer | [inline]
haveSetLiveOffset | LiveDashPlayer | [private]
Initialize(Uri source, MediaElement mediaElement) | LiveDashPlayer | [inline]
liveOffset | LiveDashPlayer | [private]
player | LiveDashPlayer | [private]
Generated on Fri Nov 15 2024 22:23:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cppwinrt/pch.h Source File

  • DateTimeFormatting
  • cppwinrt

pch.h

Go to the documentation of this file.
00001 #pragma once
00002
00003 #include <hstring.h>
00004 #include "winrt/Windows.Foundation.h"
00005 #include "winrt/Windows.Foundation.Collections.h"
00006 #include "winrt/Windows.ApplicationModel.Activation.h"
00007 #include "winrt/Windows.Globalization.h"
00008 #include "winrt/Windows.Globalization.DateTimeFormatting.h"
00009 #include "winrt/Windows.System.h"
00010 #include "winrt/Windows.UI.Core.h"
00011 #include "winrt/Windows.UI.Xaml.h"
00012 #include "winrt/Windows.UI.Xaml.Automation.Peers.h"
00013 #include "winrt/Windows.UI.Xaml.Controls.h"
00014 #include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
00015 #include "winrt/Windows.UI.Xaml.Documents.h"
00016 #include "winrt/Windows.UI.Xaml.Interop.h"
00017 #include "winrt/Windows.UI.Xaml.Markup.h"
00018 #include "winrt/Windows.UI.Xaml.Media.h"
00019 #include "winrt/Windows.UI.Xaml.Navigation.h"
00020 #include <sstream>
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraManualControls/cs/MainPage.Flash.xaml.cs Source File

  • CameraManualControls
  • cs

MainPage.Flash.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017 using Windows.Media.Devices;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020
00021 namespace CameraManualControls
00022 {
00023     public sealed partial class MainPage : Page
00024     {
00025
00026         private void UpdateFlashControlCapabilities()
00027         {
00028             var flashControl = _mediaCapture.VideoDeviceController.FlashControl;
00029
00030             if (flashControl.Supported)
00031             {
00032                 FlashButton.Tag = Visibility.Visible;
00033
00034                 FlashAutoRadioButton.IsChecked = true;
00035
00036                 if (flashControl.RedEyeReductionSupported)
00037                 {
00038                     RedEyeFlashCheckBox.Visibility = Visibility.Visible;
00039                 }
00040
00041                 // Video light is not strictly part of flash, but users might expect to find it there
00042                 if (_mediaCapture.VideoDeviceController.TorchControl.Supported)
00043                 {
00044                     TorchCheckBox.Visibility = Visibility.Visible;
00045                 }
00046             }
00047             else
00048             {
00049                 FlashButton.Visibility = Visibility.Collapsed;
00050                 FlashButton.Tag = Visibility.Collapsed;
00051             }
00052         }
00053
00054         private void FlashOnRadioButton_Checked(object sender, RoutedEventArgs e)
00055         {
00056             // Note that the FlashControl only applies to photos. To turn on the light for video recording, use the _mediaCapture.VideoDeviceController.TorchControl
00057
00058             _mediaCapture.VideoDeviceController.FlashControl.Enabled = true;
00059             _mediaCapture.VideoDeviceController.FlashControl.Auto = false;
00060         }
00061
00062         private void FlashAutoRadioButton_Checked(object sender, RoutedEventArgs e)
00063         {
00064             _mediaCapture.VideoDeviceController.FlashControl.Enabled = true;
00065             _mediaCapture.VideoDeviceController.FlashControl.Auto = true;
00066         }
00067
00068         private void FlashOffRadioButton_Checked(object sender, RoutedEventArgs e)
00069         {
00070             _mediaCapture.VideoDeviceController.FlashControl.Enabled = false;
00071         }
00072
00073         private void RedEyeFlashCheckBox_CheckedChanged(object sender, RoutedEventArgs e)
00074         {
00075             _mediaCapture.VideoDeviceController.FlashControl.RedEyeReduction = (RedEyeFlashCheckBox.IsChecked == true);
00076         }
00077
00078         private void TorchCheckBox_CheckedChanged(object sender, RoutedEventArgs e)
00079         {
00080             _mediaCapture.VideoDeviceController.TorchControl.Enabled = (TorchCheckBox.IsChecked == true);
00081         }
00082
00083     }
00084 }
Generated on Fri Nov 15 2024 22:18:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PipeIn Member List

This is the complete list of members for PipeIn, including all inherited members.
__pad0__ | PipeIn |
events | PipeIn | [private]
ReadAsync(IBuffer^buf, unsigned int count, InputStreamOptions options) | PipeIn | [inline, virtual]
~PipeIn() | PipeIn | [inline, virtual]
Generated on Fri Nov 15 2024 22:23:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

WrlFinal Member List

This is the complete list of members for WrlFinal, including all inherited members.
GetActivationFactory(_In_ HSTRING activatableClassId, _COM_Outptr_ IInspectable **factory) WrlFinal [inline]
Generated on Fri Nov 15 2024 22:23:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

PlaceInfo Member List

This is the complete list of members for PlaceInfo, including all inherited members.
Location | PlaceInfo
Name | PlaceInfo
Name | PlaceInfo
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ExtendedExecution/cpp/pch.cpp Source File

  • ExtendedExecution
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: IoT-SPI/cpp/pch.h Source File

  • IoT-SPI
  • cpp

pch.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Header for standard system include files.
00014 //
00015
00016 #pragma once
00017
00018 #include <collection.h>
00019 #include <ppltasks.h>
00020
00021 #include "SampleConfiguration.h"
00022 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/Model/Scenarios.cs Source File

  • Notifications
  • cs
  • Notifications
  • Model

Scenarios.cs

Go to the documentation of this file.
00001 ﻿namespace Notifications.Model
00002 {
00003     public static class Scenarios
00004     {
00005         public static ScenarioGroup MainGroup = new ScenarioGroup("notifications scenarios", new IScenario[]
00006         {
00007             new ScenarioGroup("live tiles", new IScenario[]
00008             {
00009                 new Scenario("pinning secondary tile", typeof(ScenarioPages.LiveTiles.Pinning.ScenarioElement)),
00010
00011                 new ScenarioGroup("secondary tile properties", new IScenario[]
00012                 {
00013                     new ScenarioGroup("BackgroundColor", new IScenario[]
00014                     {
00015                         new Scenario("inherit from primary", typeof(ScenarioPages.LiveTiles.BasicState.BackgroundColor.InheritFromPrimary.ScenarioElement)),
00016                         new Scenario("transparent", typeof(ScenarioPages.LiveTiles.BasicState.BackgroundColor.Transparent.ScenarioElement)),
00017                         new Scenario("custom color", typeof(ScenarioPages.LiveTiles.BasicState.BackgroundColor.Custom.ScenarioElement))
00018                     }),
00019
00020                     new ScenarioGroup("Logos", new IScenario[]
00021                     {
00022                         new Scenario("from app package", typeof(ScenarioPages.LiveTiles.BasicState.Logos.Source.AppPackage.ScenarioElement)),
00023                         new Scenario("from app data", typeof(ScenarioPages.LiveTiles.BasicState.Logos.Source.AppData.ScenarioElement))
00024                     })
00025                 }),
00026
00027                 new Scenario("updating secondary tile", typeof(ScenarioPages.LiveTiles.Updating.ScenarioElement)),
00028
00029                 new ScenarioGroup("tile notifications", new IScenario[]
00030                 {
00031                     new ScenarioGroup("primary tile", new IScenario[]
00032                     {
00033                         new Scenario("sending notification", typeof(ScenarioPages.LiveTiles.Notifications.PrimaryTile.Sending.ScenarioElement)),
00034                         new Scenario("clearing notifications", typeof(ScenarioPages.LiveTiles.Notifications.PrimaryTile.Clearing.ScenarioElement))
00035                     }),
00036
00037                     new Scenario("secondary tile", typeof(ScenarioPages.LiveTiles.Notifications.SecondaryTiles.ScenarioElement)),
00038
00039                     new Scenario("expiring notification", typeof(ScenarioPages.LiveTiles.Notifications.ExpiringNotification.ScenarioElement)),
00040
00041                     new ScenarioGroup("adaptive tile templates", new IScenario[]
00042                     {
00043                         new Scenario("text styles", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.TextStyles.ScenarioElement)),
00044                         new Scenario("text wrapping", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.TextWrap.ScenarioElement)),
00045
00046                         new ScenarioGroup("images", new IScenario[]
00047                         {
00048                             new Scenario("from app package", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.Images.Source.FromAppPackage.ScenarioElement)),
00049                             new Scenario("from app data", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.Images.Source.FromAppData.ScenarioElement)),
00050                             new Scenario("from internet", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.Images.Source.FromInternet.ScenarioElement))
00051                         }),
00052
00053                         new ScenarioGroup("branding", new IScenario[]
00054                         {
00055                             new Scenario("branding none", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.Branding.None.ScenarioElement)),
00056                             new Scenario("branding name", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.Branding.Name.ScenarioElement)),
00057                             new Scenario("branding nameAndLogo", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.Branding.NameAndLogo.ScenarioElement)),
00058                             new Scenario("branding logo", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.Branding.Logo.ScenarioElement)),
00059                             new Scenario("branding default", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.Branding.Default.ScenarioElement))
00060                         }),
00061
00062                         new ScenarioGroup("hint-presentation", new IScenario[]
00063                         {
00064                             new Scenario("photos", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.HintPresentation.Photos.ScenarioElement)),
00065                             new Scenario("people", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.HintPresentation.People.ScenarioElement)),
00066                             new Scenario("contact", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.HintPresentation.Contact.ScenarioElement))
00067                         }),
00068
00069                         new Scenario("custom update", typeof(ScenarioPages.LiveTiles.AdaptiveTemplates.Custom.ScenarioElement))
00070                         })
00071                     }),
00072
00073
00074                 new Scenario("SecondaryTile.FindAllAsync()", typeof(ScenarioPages.LiveTiles.FindAllAsync.Visualizer.ScenarioElement)),
00075
00076                 new Scenario("unpin everything", typeof(ScenarioPages.LiveTiles.UnpinEverything.ScenarioElement))
00077             }),
00078
00079
00080             new ScenarioGroup("toasts", new IScenario[]
00081             {
00082                 new ScenarioGroup("adaptive templates", new IScenario[]
00083                 {
00084                     new ScenarioGroup("image", new IScenario[]
00085                     {
00086                         new ScenarioGroup("src", new IScenario[]
00087                         {
00088                             new Scenario("from app package", typeof(ScenarioPages.Toasts.AdaptiveTemplates.Image.Src.FromAppPackage.ScenarioElement)),
00089                             new Scenario("from app data", typeof(ScenarioPages.Toasts.AdaptiveTemplates.Image.Src.FromAppData.ScenarioElement)),
00090                             new Scenario("from internet", typeof(ScenarioPages.Toasts.AdaptiveTemplates.Image.Src.FromInternet.ScenarioElement))
00091                         })
00092                     })
00093                 }),
00094
00095                 new ScenarioGroup("actions", new IScenario[]
00096                 {
00097                     new ScenarioGroup("action (button)", new IScenario[]
00098                     {
00099                         new Scenario("text button", typeof(ScenarioPages.Toasts.Actions.Action.Text.ScenarioElement)),
00100                         new Scenario("text and image button", typeof(ScenarioPages.Toasts.Actions.Action.TextAndImage.ScenarioElement)),
00101                         new Scenario("quick reply button", typeof(ScenarioPages.Toasts.Actions.Action.QuickReply.ScenarioElement))
00102                     }),
00103
00104                     new ScenarioGroup("input text", new IScenario[]
00105                     {
00106                         new Scenario("input text - title", typeof(ScenarioPages.Toasts.Actions.InputText.Title.ScenarioElement)),
00107                         new Scenario("input text - placeholder content", typeof(ScenarioPages.Toasts.Actions.InputText.PlaceholderContent.ScenarioElement)),
00108                         new Scenario("input text - default input", typeof(ScenarioPages.Toasts.Actions.InputText.DefaultInput.ScenarioElement)),
00109                         new Scenario("input text - retrieving args", typeof(ScenarioPages.Toasts.Actions.InputText.RetrievingArgs.ScenarioElement))
00110                     }),
00111
00112                     new ScenarioGroup("hint-systemCommands", new IScenario[]
00113                     {
00114                         new Scenario("SnoozeAndDismiss", typeof(ScenarioPages.Toasts.Actions.SystemCommands.SnoozeAndDismiss.ScenarioElement))
00115                     })
00116                 }),
00117
00118                 new ScenarioGroup("activation types", new IScenario[]
00119                 {
00120                     new Scenario("foreground with app open", typeof(ScenarioPages.Toasts.ActivationTypes.ForegroundWithAppOpen.ScenarioElement)),
00121                     new Scenario("foreground with app closed", typeof(ScenarioPages.Toasts.ActivationTypes.ForegroundWithAppClosed.ScenarioElement)),
00122                     new Scenario("background with app open", typeof(ScenarioPages.Toasts.ActivationTypes.BackgroundWithAppOpen.ScenarioElement)),
00123                     new Scenario("background with app closed", typeof(ScenarioPages.Toasts.ActivationTypes.BackgroundWithAppClosed.ScenarioElement)),
00124                     new Scenario("protocol", typeof(ScenarioPages.Toasts.ActivationTypes.Protocol.ScenarioElement)),
00125                     new ScenarioGroup("system", new IScenario[]
00126                     {
00127                         new ScenarioGroup("Snooze", new IScenario[]
00128                         {
00129                             new Scenario("Auto Content", typeof(ScenarioPages.Toasts.ActivationTypes.System.Snooze.AutoContent.ScenarioElement)),
00130                             new Scenario("Custom Content", typeof(ScenarioPages.Toasts.ActivationTypes.System.Snooze.CustomContent.ScenarioElement)),
00131                             new Scenario("Snoozing", typeof(ScenarioPages.Toasts.ActivationTypes.System.Snooze.Snoozing.ScenarioElement))
00132                         }),
00133
00134                         new ScenarioGroup("Dismiss", new IScenario[]
00135                         {
00136                             new Scenario("Auto Content", typeof(ScenarioPages.Toasts.ActivationTypes.System.Dismiss.AutoContent.ScenarioElement)),
00137                             new Scenario("Custom Content", typeof(ScenarioPages.Toasts.ActivationTypes.System.Dismiss.CustomContent.ScenarioElement)),
00138                             new Scenario("Dismissing", typeof(ScenarioPages.Toasts.ActivationTypes.System.Dismiss.Dismissing.ScenarioElement))
00139                         })
00140                     })
00141                 }),
00142
00143                 new Scenario("expiring toast", typeof(ScenarioPages.Toasts.ExpiringToast.ScenarioElement)),
00144                 new Scenario("ghost toast", typeof(ScenarioPages.Toasts.GhostToast.ScenarioElement)),
00145
00146                 new ScenarioGroup("scenarios", new IScenario[]
00147                 {
00148                     new Scenario("scenario: default", typeof(ScenarioPages.Toasts.Scenarios.Default.ScenarioElement)),
00149                     new Scenario("scenario: alarm", typeof(ScenarioPages.Toasts.Scenarios.Alarm.ScenarioElement)),
00150                     new Scenario("scenario: reminder", typeof(ScenarioPages.Toasts.Scenarios.Reminder.ScenarioElement)),
00151                     new Scenario("scenario: incomingCall", typeof(ScenarioPages.Toasts.Scenarios.IncomingCall.ScenarioElement))
00152                 }),
00153
00154                 new ScenarioGroup("audio", new IScenario[]
00155                 {
00156                     new Scenario("default", typeof(ScenarioPages.Toasts.Audio.Default.ScenarioElement)),
00157                     new Scenario("system sound - email", typeof(ScenarioPages.Toasts.Audio.EmailSound.ScenarioElement)),
00158                     new Scenario("looping", typeof(ScenarioPages.Toasts.Audio.Looping.ScenarioElement)),
00159                     new Scenario("silent", typeof(ScenarioPages.Toasts.Audio.Silent.ScenarioElement))
00160                 }),
00161
00162                 new ScenarioGroup("ToastNotificationManager.History", new IScenario[]
00163                 {
00164                     new ScenarioGroup("Remove(...)", new IScenario[]
00165                     {
00166                         new Scenario("Remove(tag)", typeof(ScenarioPages.Toasts.ToastNotificationManagerHistory.Remove.ByTag.ScenarioElement)),
00167                         new Scenario("Remove(tag, group)", typeof(ScenarioPages.Toasts.ToastNotificationManagerHistory.Remove.ByTagAndGroup.ScenarioElement))
00168                     }),
00169
00170                     new ScenarioGroup("RemoveGroup(...)", new IScenario[]
00171                     {
00172                         new Scenario("RemoveGroup(group)", typeof(ScenarioPages.Toasts.ToastNotificationManagerHistory.RemoveGroup.ByGroup.ScenarioElement))
00173                     }),
00174
00175                     new Scenario("Clear()", typeof(ScenarioPages.Toasts.ToastNotificationManagerHistory.ClearAll.ScenarioElement)),
00176
00177                     new ScenarioGroup("GetHistory()", new IScenario[]
00178                     {
00179                         new Scenario("Visualizer", typeof(ScenarioPages.Toasts.ToastNotificationManagerHistory.GetHistory.Visualizer.ScenarioElement))
00180                     })
00181                 }),
00182
00183                  new ScenarioGroup("ToastNotificationHistoryChangedTrigger", new IScenario[] {
00184                     new Scenario("Responding to toast removal", typeof(ScenarioPages.Toasts.HistoryChangedTrigger.RespondingToToasts.ScenarioElement)),
00185                     new Scenario("Update badge on toast dismissal", typeof(ScenarioPages.Toasts.HistoryChangedTrigger.BadgeControl.ScenarioElement))
00186                 }),
00187
00188                 new Scenario("update toast", typeof(ScenarioPages.Toasts.UpdateToast.ScenarioElement)),
00189             }),
00190
00191
00192             new ScenarioGroup("badges", new IScenario[]
00193             {
00194                 new ScenarioGroup("primary tile badges", new IScenario[]
00195                 {
00196                     new Scenario("clear primary badge", typeof(ScenarioPages.Badges.Local.PrimaryTile.ClearBadge.ScenarioElement)),
00197                     new Scenario("update badge as number", typeof(ScenarioPages.Badges.Local.PrimaryTile.SetBadgeNumber.ScenarioElement)),
00198                     new Scenario("update badge as glyph", typeof(ScenarioPages.Badges.Local.PrimaryTile.SetBadgeGlyph.ScenarioElement))
00199                 }),
00200                 new Scenario("secondary tile badges", typeof(ScenarioPages.Badges.Local.SecondaryTileBadges.ScenarioElement))
00201             })
00202         });
00203     }
00204 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GeneratorIncrementalLoadingClass-g< T > Member List

This is the complete list of members for GeneratorIncrementalLoadingClass-g< T >, including all inherited members.
_count | GeneratorIncrementalLoadingClass-g< T > | [private]
_generator | GeneratorIncrementalLoadingClass-g< T > | [private]
_maxCount | GeneratorIncrementalLoadingClass-g< T > | [private]
Add(object value) | IncrementalLoadingBase | [inline]
Clear() | IncrementalLoadingBase | [inline]
CollectionChanged | IncrementalLoadingBase |
Contains(object value) | IncrementalLoadingBase | [inline]
CopyTo(Array array, int index) | IncrementalLoadingBase | [inline]
Count | IncrementalLoadingBase |
GeneratorIncrementalLoadingClass(uint maxCount, Func< int, T > generator) | GeneratorIncrementalLoadingClass-g< T > | [inline]
GetEnumerator() | IncrementalLoadingBase | [inline]
HasMoreItems | IncrementalLoadingBase |
HasMoreItemsOverride() | GeneratorIncrementalLoadingClass-g< T > | [inline, protected, virtual]
IndexOf(object value) | IncrementalLoadingBase | [inline]
Insert(int index, object value) | IncrementalLoadingBase | [inline]
IsFixedSize | IncrementalLoadingBase |
IsReadOnly | IncrementalLoadingBase |
IsSynchronized | IncrementalLoadingBase |
LoadMoreItemsAsync(uint count) | IncrementalLoadingBase | [inline]
LoadMoreItemsOverrideAsync(System.Threading.CancellationToken c, uint count) | GeneratorIncrementalLoadingClass-g< T > | [inline, protected]
DataBinding::IncrementalLoadingBase::LoadMoreItemsOverrideAsync(CancellationToken c, uint count) | IncrementalLoadingBase | [protected, pure virtual]
Remove(object value) | IncrementalLoadingBase | [inline]
RemoveAt(int index) | IncrementalLoadingBase | [inline]
SyncRoot | IncrementalLoadingBase |
this | IncrementalLoadingBase |
Generated on Fri Nov 15 2024 22:23:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: GlobalizationPreferences/cpp/SampleConfiguration.cpp Source File

  • GlobalizationPreferences
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014 #include "SampleConfiguration.h"
00015
00016 using namespace SDKTemplate;
00017
00018 using namespace Platform;
00019 using namespace Windows::Foundation::Collections;
00020
00021 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00022 {
00023     { "User preferences", "SDKTemplate.Scenario1_Prefs" },
00024     { "Language characteristics", "SDKTemplate.Scenario2_Lang" },
00025     { "Region characteristics", "SDKTemplate.Scenario3_Region" },
00026     { "Current input language", "SDKTemplate.Scenario4_Input" },
00027 };
00028
00029 String^ SDKTemplate::StringJoin(String^ delimiter, IVectorView<String^>^ vector)
00030 {
00031     String^ result = "";
00032
00033     if (vector->Size > 0)
00034     {
00035         result = vector->GetAt(0);
00036         for (unsigned int index = 1; index < vector->Size; index++)
00037         {
00038             result += delimiter + vector->GetAt(index);
00039         }
00040     }
00041     return result;
00042 }
Generated on Fri Nov 15 2024 22:17:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WiFiScan/cpp/Scenario3_RegisterForUpdates.xaml.cpp Source File

  • WiFiScan
  • cpp

Scenario3_RegisterForUpdates.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario3_RegisterForUpdates.xaml.h"
00014
00015 using namespace SDKTemplate;
00016 using namespace SDKTemplate::WiFiScan;
00017
00018 using namespace Platform;
00019 using namespace Platform::Collections;
00020 using namespace Windows::Devices::Enumeration;
00021 using namespace Windows::Devices::WiFi;
00022 using namespace Windows::Foundation;
00023 using namespace Windows::Foundation::Collections;
00024 using namespace Windows::Globalization::DateTimeFormatting;
00025 using namespace Windows::UI::Core;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Controls::Primitives;
00029 using namespace Windows::UI::Xaml::Data;
00030 using namespace Windows::UI::Xaml::Input;
00031 using namespace Windows::UI::Xaml::Media;
00032 using namespace Windows::UI::Xaml::Navigation;
00033 using namespace concurrency;
00034
00035 Scenario3_RegisterForUpdates::Scenario3_RegisterForUpdates() : _rootPage(MainPage::Current)
00036 {
00037     InitializeComponent();
00038 }
00039
00040 void Scenario3_RegisterForUpdates::Button_Click_Register(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00041 {
00042     _registrationToken = _firstAdapter->AvailableNetworksChanged +=
00043         ref new Windows::Foundation::TypedEventHandler<Windows::Devices::WiFi::WiFiAdapter ^, Platform::Object ^>(this, &WiFiScan::Scenario3_RegisterForUpdates::OnAvailableNetworksChanged);
00044
00045     RegisterButton->IsEnabled = false;
00046     UnregisterButton->IsEnabled = true;
00047 }
00048
00049 void Scenario3_RegisterForUpdates::Button_Click_Unregister(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00050 {
00051     _firstAdapter->AvailableNetworksChanged -= _registrationToken;
00052
00053     UnregisterButton->IsEnabled = false;
00054     RegisterButton->IsEnabled = true;
00055 }
00056
00057 void Scenario3_RegisterForUpdates::OnNavigatedTo(NavigationEventArgs^ e)
00058 {
00059     ResultCollection = ref new Vector<WiFiNetworkDisplay^>();
00060     DataContext = this;
00061
00062     // RequestAccessAsync must have been called at least once by the app before using the API
00063     // Calling it multiple times is fine but not necessary
00064     // RequestAccessAsync must be called from the UI thread
00065     auto requestAccessOperation = WiFiAdapter::RequestAccessAsync();
00066     auto requestAccessTask = create_task(requestAccessOperation);
00067
00068     requestAccessTask.then([this](WiFiAccessStatus access)
00069     {
00070         if (access != WiFiAccessStatus::Allowed)
00071         {
00072             _rootPage->NotifyUser(L"Access denied", SDKTemplate::NotifyType::ErrorMessage);
00073         }
00074         else
00075         {
00076             auto enumerationOperation = DeviceInformation::FindAllAsync(WiFiAdapter::GetDeviceSelector());
00077             auto enumerationTask = create_task(enumerationOperation);
00078
00079             enumerationTask.then([this](DeviceInformationCollection^ result)
00080             {
00081                 if (result->Size >= 1)
00082                 {
00083                     auto firstAdapterOperation = WiFiAdapter::FromIdAsync(result->GetAt(0)->Id);
00084                     auto firstAdapterTask = create_task(firstAdapterOperation);
00085
00086                     firstAdapterTask.then([this](WiFiAdapter^ adapter)
00087                     {
00088                         _firstAdapter = adapter;
00089                         RegisterButton->IsEnabled = true;
00090                     });
00091                 }
00092                 else
00093                 {
00094                     _rootPage->NotifyUser(L"No WiFi Adapters detected on this machine", SDKTemplate::NotifyType::ErrorMessage);
00095                 }
00096             });
00097         }
00098     });
00099 }
00100
00101 void Scenario3_RegisterForUpdates::DisplayNetworkReport(WiFiNetworkReport^ report, WiFiAdapter^ adapter)
00102 {
00103     auto timestampString = DateTimeFormatter::LongDate->Format(report->Timestamp);
00104     auto message = L"Network Report Timestamp: " + timestampString;
00105     // there is no guarantee of what thread the AvailableNetworksChanged callback is run on
00106     _rootPage->Dispatcher->RunAsync(CoreDispatcherPriority::Normal,
00107         ref new DispatchedHandler([this, message, report, adapter]
00108     {
00109         _rootPage->NotifyUser(message, SDKTemplate::NotifyType::StatusMessage);
00110         ResultCollection->Clear();
00111         for (auto network : report->AvailableNetworks)
00112         {
00113             ResultCollection->Append(ref new WiFiNetworkDisplay(network, adapter));
00114         }
00115     }));
00116
00117 }
00118
00119 void Scenario3_RegisterForUpdates::OnAvailableNetworksChanged(Windows::Devices::WiFi::WiFiAdapter ^sender, Platform::Object ^args)
00120 {
00121     DisplayNetworkReport(sender->NetworkReport, sender);
00122 }
Generated on Fri Nov 15 2024 22:22:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario5_RelativePositioning Member List

This is the complete list of members for Scenario5_RelativePositioning, including all inherited members.
appWindow | Scenario5_RelativePositioning | [private]
appWindowFrame | Scenario5_RelativePositioning | [private]
OnNavigatedFrom(NavigationEventArgs e) | Scenario5_RelativePositioning | [inline, protected]
Scenario5_RelativePositioning() | Scenario5_RelativePositioning | [inline]
ShowWindowBtn_Click(object sender, RoutedEventArgs e) | Scenario5_RelativePositioning | [inline, private]
Generated on Fri Nov 15 2024 22:23:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlContextMenu/cpp/SampleDataModel.h Source File

  • XamlContextMenu
  • cpp

SampleDataModel.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 namespace SDKTemplate
00015 {
00016     public ref class SampleDataModel sealed
00017     {
00018     public:
00019         property Platform::String^ Title {
00020             Platform::String^ get() { return m_title; }
00021         }
00022         property Platform::String^ ImagePath {
00023             Platform::String^ get() { return m_imagePath; }
00024         }
00025
00026         SampleDataModel(Platform::String^ title, Platform::String^ imagePath)
00027             : m_title(title), m_imagePath(imagePath)
00028         {
00029         }
00030
00031         static Windows::Foundation::Collections::IVector<SampleDataModel^>^ GetSampleData()
00032         {
00033             return ref new Platform::Collections::Vector<SampleDataModel^>{
00034                 ref new SampleDataModel("Cliff", "Assets/cliff.jpg"),
00035                 ref new SampleDataModel("Grapes", "Assets/grapes.jpg"),
00036                 ref new SampleDataModel("Rainier", "Assets/Rainier.jpg"),
00037                 ref new SampleDataModel("Sunset", "Assets/Sunset.jpg"),
00038                 ref new SampleDataModel("Treetops", "Assets/Treetops.jpg"),
00039                 ref new SampleDataModel("Valley", "Assets/Valley.jpg"),
00040             };
00041         }
00042
00043     private:
00044         Platform::String^ m_title;
00045         Platform::String^ m_imagePath;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:22:27 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_BackgroundWatcher Member List

This is the complete list of members for Scenario3_BackgroundWatcher, including all inherited members.
App_Resuming(object sender, object e) | Scenario3_BackgroundWatcher | [inline, private]
App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) | Scenario3_BackgroundWatcher | [inline, private]
OnBackgroundTaskCompleted(BackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs eventArgs) | Scenario3_BackgroundWatcher | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario3_BackgroundWatcher | [inline, protected]
OnNavigatingFrom(NavigatingCancelEventArgs e) | Scenario3_BackgroundWatcher | [inline, protected]
rootPage | Scenario3_BackgroundWatcher | [private]
RunButton_Click(object sender, RoutedEventArgs e) | Scenario3_BackgroundWatcher | [inline, private]
Scenario3_BackgroundWatcher() | Scenario3_BackgroundWatcher | [inline]
StopButton_Click(object sender, RoutedEventArgs e) | Scenario3_BackgroundWatcher | [inline, private]
taskEntryPoint | Scenario3_BackgroundWatcher | [private]
taskName | Scenario3_BackgroundWatcher | [private]
taskRegistration | Scenario3_BackgroundWatcher | [private]
trigger | Scenario3_BackgroundWatcher | [private]
Generated on Fri Nov 15 2024 22:23:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2_ControlTransfer Member List

This is the complete list of members for Scenario2_ControlTransfer, including all inherited members.
GetOsrFx2SevenSegmentAsync() | Scenario2_ControlTransfer | [inline, private]
GetOsrFx2SevenSegmentSetting_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_ControlTransfer | [inline, private]
GetSuperMuttLedBlinkPattern_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_ControlTransfer | [inline, private]
GetSuperMuttLedBlinkPatternAsync() | Scenario2_ControlTransfer | [inline, private]
OnNavigatedTo(NavigationEventArgs eventArgs) | Scenario2_ControlTransfer | [inline, protected]
rootPage | Scenario2_ControlTransfer | [private]
Scenario2_ControlTransfer() | Scenario2_ControlTransfer | [inline]
SendVendorControlTransferInToDeviceRecipientAsync(Byte vendorCommand, UInt32 dataPacketLength) | Scenario2_ControlTransfer | [inline, private]
SetOsrFx2SevenSegmentAsync(Byte numericValue) | Scenario2_ControlTransfer | [inline, private]
SetOsrFx2SevenSegmentSetting_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_ControlTransfer | [inline, private]
SetSuperMuttLedBlinkPattern_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) | Scenario2_ControlTransfer | [inline, private]
SetSuperMuttLedBlinkPatternAsync(Byte pattern) | Scenario2_ControlTransfer | [inline, private]
Generated on Fri Nov 15 2024 22:23:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LowLatencyInput/cpp/App.xaml.cpp Source File

  • LowLatencyInput
  • cpp

App.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::ApplicationModel::Activation;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Controls::Primitives;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::UI::Xaml::Input;
00027 using namespace Windows::UI::Xaml::Interop;
00028 using namespace Windows::UI::Xaml::Media;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409
00032
00033 /// <summary>
00034 /// Initializes the singleton application object.  This is the first line of authored code
00035 /// executed, and as such is the logical equivalent of main() or WinMain().
00036 /// </summary>
00037 App::App()
00038 {
00039     InitializeComponent();
00040     Suspending += ref new Windows::UI::Xaml::SuspendingEventHandler(this, &SDKTemplate::App::OnSuspending);
00041 }
00042
00043 /// <summary>
00044 /// Invoked when the application is launched normally by the end user.  Other entry points
00045 /// will be used such as when the application is launched to open a specific file.
00046 /// </summary>
00047 /// <param name="e">Details about the launch request and process.</param>
00048 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
00049 {
00050 #if _DEBUG
00051     // Show graphics profiling information while debugging.
00052     if (IsDebuggerPresent())
00053     {
00054         // Display the current frame rate counters
00055         DebugSettings->EnableFrameRateCounter = false;
00056     }
00057 #endif
00058
00059     auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00060
00061     // Do not repeat app initialization when the Window already has content,
00062     // just ensure that the window is active
00063     if (rootFrame == nullptr)
00064     {
00065         // Create a Frame to act as the navigation context and associate it with
00066         // a SuspensionManager key
00067         rootFrame = ref new Frame();
00068
00069         // Set the default language
00070         rootFrame->Language = Windows::Globalization::ApplicationLanguages::Languages->GetAt(0);
00071
00072         rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed);
00073
00074         if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
00075         {
00076             // TODO: Restore the saved session state only when appropriate, scheduling the
00077             // final launch steps after the restore is complete
00078         }
00079
00080         if (rootFrame->Content == nullptr)
00081         {
00082             // When the navigation stack isn't restored navigate to the first page,
00083             // configuring the new page by passing required information as a navigation
00084             // parameter
00085             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00086         }
00087         // Place the frame in the current Window
00088         Window::Current->Content = rootFrame;
00089         // Ensure the current window is active
00090         Window::Current->Activate();
00091     }
00092     else
00093     {
00094         if (rootFrame->Content == nullptr)
00095         {
00096             // When the navigation stack isn't restored navigate to the first page,
00097             // configuring the new page by passing required information as a navigation
00098             // parameter
00099             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00100         }
00101         // Ensure the current window is active
00102         Window::Current->Activate();
00103     }
00104 }
00105
00106 /// <summary>
00107 /// Invoked when application execution is being suspended.  Application state is saved
00108 /// without knowing whether the application will be terminated or resumed with the contents
00109 /// of memory still intact.
00110 /// </summary>
00111 /// <param name="sender">The source of the suspend request.</param>
00112 /// <param name="e">Details about the suspend request.</param>
00113 void App::OnSuspending(Object^ /* sender */, SuspendingEventArgs^ /* e */)
00114 {
00115     //TODO: Save application state and stop any background activity
00116 }
00117
00118 /// <summary>
00119 /// Invoked when Navigation to a certain page fails
00120 /// </summary>
00121 /// <param name="sender">The Frame which failed navigation</param>
00122 /// <param name="e">Details about the navigation failure</param>
00123 void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e)
00124 {
00125     throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name);
00126 }
Generated on Fri Nov 15 2024 22:16:48 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Printing/cpp/SampleConfiguration.cpp Source File

  • Printing
  • cpp

SampleConfiguration.cpp

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #include "pch.h"
00004 #include "MainPage.xaml.h"
00005 #include "SampleConfiguration.h"
00006
00007 using namespace SDKTemplate;
00008
00009 Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
00010 {
00011     { "Basic", "SDKTemplate.Scenario1Basic" },
00012     { "Standard Options", "SDKTemplate.Scenario2StandardOptions" },
00013     { "Custom Options", "SDKTemplate.Scenario3CustomOptions" },
00014     { "Page Range", "SDKTemplate.Scenario4PageRange" },
00015     { "Photos", "SDKTemplate.Scenario5Photos" },
00016     { "Disable Preview", "SDKTemplate.Scenario6DisablePreview" }
00017 };
Generated on Fri Nov 15 2024 22:17:18 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CortanaVoiceCommand/cpp/AdventureWorks/ViewModel/TripListViewModel.h Source File

  • CortanaVoiceCommand
  • cpp
  • AdventureWorks
  • ViewModel

TripListViewModel.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #pragma once
00012 #include "ViewModel\ViewModelBase.h"
00013
00014 namespace AdventureWorks
00015 {
00016     [Windows::UI::Xaml::Data::Bindable]
00017     public ref class TripListViewModel sealed :
00018         public ViewModelBase
00019     {
00020     public:
00021         TripListViewModel(AdventureWorks_Shared::TripStore^ store);
00022
00023         property Windows::Foundation::Collections::IObservableVector<AdventureWorks_Shared::Trip^>^ Trips
00024         {
00025             Windows::Foundation::Collections::IObservableVector<AdventureWorks_Shared::Trip^>^ get();
00026         }
00027
00028         property AdventureWorks_Shared::Trip^ SelectedTrip
00029         {
00030             AdventureWorks_Shared::Trip^ get();
00031             void set(AdventureWorks_Shared::Trip^ value);
00032         }
00033
00034         property Windows::UI::Xaml::Input::ICommand^ AddTripCommand
00035         {
00036             Windows::UI::Xaml::Input::ICommand^ get();
00037         }
00038
00039         void LoadTrips();
00040         void SelectionChanged();
00041     private:
00042         Windows::UI::Xaml::Input::ICommand^ addTripCommand;
00043         Windows::Foundation::Collections::IObservableVector<AdventureWorks_Shared::Trip^>^ trips;
00044         AdventureWorks_Shared::Trip^ selectedTrip;
00045         AdventureWorks_Shared::TripStore^ store;
00046
00047         void AddTrip();
00048
00049
00050     };
00051 }
Generated on Fri Nov 15 2024 22:19:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cppwinrt/DetailsPage.h Source File

  • XamlListView
  • cppwinrt

DetailsPage.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "DetailsPage.g.h"
00014
00015 namespace winrt::SDKTemplate::implementation
00016 {
00017     struct DetailsPage : DetailsPageT<DetailsPage>
00018     {
00019         DetailsPage();
00020
00021         auto SelectedContact() { return selectedContact; }
00022
00023         void OnLoaded(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00024         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00026         void OnUnloaded(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00027         void DeleteItem(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
00028
00029     private:
00030         SDKTemplate::Contact selectedContact{ nullptr };
00031         event_token backRequestedToken{};
00032         event_token windowSizeChangedToken{};
00033
00034         void OnBackRequested(Windows::Foundation::IInspectable const&, Windows::UI::Core::BackRequestedEventArgs const& e);
00035         void NavigateBackForWideState(bool useTransition);
00036         bool ShouldGoToWideState();
00037         void OnWindowSizeChanged(Windows::Foundation::IInspectable const&, Windows::UI::Core::WindowSizeChangedEventArgs const&);
00038     };
00039 }
00040
00041 namespace winrt::SDKTemplate::factory_implementation
00042 {
00043     struct DetailsPage : DetailsPageT<DetailsPage, implementation::DetailsPage>
00044     {
00045     };
00046 }
Generated on Fri Nov 15 2024 22:22:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlCloudFontIntegration/cs/Scenario_Document2.xaml.cs Source File

  • XamlCloudFontIntegration
  • cs

Scenario_Document2.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml.Controls;
00013
00014
00015 namespace SDKTemplate
00016 {
00017     public sealed partial class Scenario_Document2 : Page
00018     {
00019         public Scenario_Document2()
00020         {
00021             this.InitializeComponent();
00022         }
00023
00024         private void Page_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
00025         {
00026             // Font formatting is being applied on page load rather than in XAML markup
00027             // so that the on-demand cloud font behavior can be experienced when the
00028             // app runs rather than when the XAML file is viewed in Visual Studio.
00029
00030             // Formatting will be applied to all content elements in the page that don't
00031             // already have FontFamily set.
00032             this.FontFamily = new Windows.UI.Xaml.Media.FontFamily("FangSong");
00033         }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:22:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

HttpMeteredConnectionFilter Member List

This is the complete list of members for HttpMeteredConnectionFilter, including all inherited members.
CheckPriority(MeteredConnectionPriority priority) | HttpMeteredConnectionFilter | [private]
Close() | HttpMeteredConnectionFilter | [inline]
Conservative enum value | HttpMeteredConnectionFilter | [private]
GetBehavior() | HttpMeteredConnectionFilter | [private, static]
HttpMeteredConnectionFilter(Windows::Web::Http::Filters::IHttpFilter const &innerFilter) | HttpMeteredConnectionFilter |
m_innerFilter | HttpMeteredConnectionFilter | [private]
m_optIn | HttpMeteredConnectionFilter | [private]
MeteredConnectionBehavior enum name | HttpMeteredConnectionFilter | [private]
MeteredConnectionPriorityPropertyName() | HttpMeteredConnectionFilter | [inline, static]
MeteredConnectionPriorityPropertyNameLiteral | HttpMeteredConnectionFilter | [private, static]
None enum value | HttpMeteredConnectionFilter | [private]
Normal enum value | HttpMeteredConnectionFilter | [private]
OptIn enum value | HttpMeteredConnectionFilter | [private]
OptIn() | HttpMeteredConnectionFilter | [inline]
OptIn(bool value) | HttpMeteredConnectionFilter | [inline]
SendRequestAsync(Windows::Web::Http::HttpRequestMessage request) | HttpMeteredConnectionFilter |
Generated on Fri Nov 15 2024 22:24:10 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MediaList Member List

This is the complete list of members for MediaList, including all inherited members.
Back() const | List< MediaItem > | [inline, protected]
Clear(FN &clear_fn) | List< MediaItem > | [inline]
Clear() | List< MediaItem > | [inline, virtual]
EndPosition() const | List< MediaItem > | [inline]
Front() const | List< MediaItem > | [inline, protected]
FrontPosition() | List< MediaItem > | [inline]
GetBack(MediaItem *ppItem) | List< MediaItem > | [inline]
GetCount() const | List< MediaItem > | [inline]
GetFront(MediaItem *ppItem) | List< MediaItem > | [inline]
GetItem(const Node *pNode, MediaItem *ppItem) | List< MediaItem > | [inline, protected, virtual]
GetItemPos(POSITION pos, MediaItem *ppItem) | List< MediaItem > | [inline]
InsertAfter(MediaItemitem, Node *pBefore) | List< MediaItem > | [inline, protected, virtual]
InsertBack(MediaItemitem) | List< MediaItem > | [inline]
InsertFront(MediaItemitem) | List< MediaItem > | [inline]
InsertPos(POSITION pos, MediaItemitem) | List< MediaItem > | [inline]
IsEmpty() const | List< MediaItem > | [inline]
List() | List< MediaItem > | [inline]
LoadFromApplicationUriAsync(string uri) | MediaList | [inline]
LoadFromApplicationUriAsync(Uri uri) | MediaList | [inline]
LoadItem(JsonObject json) | MediaList | [inline, private]
m_anchor | List< MediaItem > | [protected]
m_count | List< MediaItem > | [protected]
MediaList() | MediaList | [inline]
Next(const POSITION pos) | List< MediaItem > | [inline]
Remove(POSITION &pos, MediaItem *ppItem) | List< MediaItem > | [inline]
RemoveBack(MediaItem *ppItem) | List< MediaItem > | [inline]
RemoveFront(MediaItem *ppItem) | List< MediaItem > | [inline]
RemoveItem(Node *pNode, MediaItem *ppItem) | List< MediaItem > | [inline, protected, virtual]
Title | MediaList |
ToPlaybackList() | MediaList | [inline]
~List() | List< MediaItem > | [inline, virtual]
Generated on Fri Nov 15 2024 22:23:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

GetHistoricalBytes Member List

This is the complete list of members for GetHistoricalBytes, including all inherited members.
ApduCommand(byte cla, byte ins, byte p1, byte p2, byte[] commandData, byte?le) | ApduCommand | [inline]
ApduResponseType | ApduCommand |
CLA | ApduCommand |
CommandData | ApduCommand |
GetBuffer() | ApduCommand | [inline]
GetData(GetDataDataType type) | GetData | [inline]
GetDataDataType enum name | GetData |
GetHistoricalBytes() | GetHistoricalBytes | [inline]
INS | ApduCommand |
Le | ApduCommand |
P1 | ApduCommand |
P2 | ApduCommand |
ToString() | ApduCommand | [inline]
Type | GetData |
Generated on Fri Nov 15 2024 22:23:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario2StandardOptions Member List

This is the complete list of members for Scenario2StandardOptions, including all inherited members.
OnNavigatedFrom(NavigationEventArgs e) | Scenario2StandardOptions | [inline, protected]
OnNavigatedTo(NavigationEventArgs e) | Scenario2StandardOptions | [inline, protected]
OnPrintButtonClick(object sender, RoutedEventArgs e) | Scenario2StandardOptions | [inline, private]
printHelper | Scenario2StandardOptions | [private]
Scenario2StandardOptions() | Scenario2StandardOptions | [inline]
Generated on Fri Nov 15 2024 22:23:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: FilePickerContracts/cs/MainPage_SaveFile.xaml.cs Source File

  • FilePickerContracts
  • cs

MainPage_SaveFile.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 using SDKTemplate;
00012
00013 using System;
00014 using Windows.Storage;
00015 using Windows.Storage.Pickers;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace FilePickerContracts
00021 {
00022     /// <summary>
00023     /// An empty page that can be used on its own or navigated to within a Frame.
00024     /// </summary>
00025     public sealed partial class MainPage_SaveFile : Page
00026     {
00027         public MainPage_SaveFile()
00028         {
00029             this.InitializeComponent();
00030             ThisAppTitle.Text = MainPage.APP_TITLE;
00031             SaveFileButton.Click += new RoutedEventHandler(SaveFileButton_Click);
00032         }
00033
00034         private async void SaveFileButton_Click(object sender, RoutedEventArgs e)
00035         {
00036             MainPage page = MainPage.Current;
00037
00038             //$$page.ResetScenarioOutput(OutputTextBlock);
00039             // Set up and launch the Save Picker
00040             FileSavePicker fileSavePicker = new FileSavePicker();
00041             fileSavePicker.FileTypeChoices.Add("PNG", new string[] { ".png" });
00042
00043             StorageFile file = await fileSavePicker.PickSaveFileAsync();
00044             if (file != null)
00045             {
00046                 // At this point, the app can begin writing to the provided save file
00047                 OutputTextBlock.Text = file.Name;
00048             }
00049         }
00050     }
00051 }
Generated on Fri Nov 15 2024 22:19:47 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleInk/cs/Scenario8.xaml.cs Source File

  • SimpleInk
  • cs

Scenario8.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Foundation;
00014 using Windows.UI.Input.Inking;
00015 using Windows.UI.Input.Inking.Core;
00016 using Windows.UI.Xaml;
00017 using Windows.UI.Xaml.Controls;
00018 using Windows.UI.Xaml.Navigation;
00019
00020 namespace SDKTemplate
00021 {
00022     /// <summary>
00023     /// This page shows the code to do ink recognition
00024     /// </summary>
00025     public sealed partial class Scenario8 : Page
00026     {
00027         const float radius = 150.0f;
00028         const float circleStrokeThickness = 2.0f;
00029         const float penSize = 4.0f;
00030         Point circleCenter;
00031
00032         CoreWetStrokeUpdateSource coreWetStrokeUpdateSource;
00033
00034         // Follow Circle is true if Ink input should be redirected to the circle edge
00035         bool followCircle = false;
00036
00037         // discontinueStroke is true is the Ink input that follows for the wet stroke is to be ignored
00038         bool discontinueStroke = false;
00039
00040         // disableFollowCircle is set to true to disable Follow Circle behavior for the current stroke
00041         bool disableFollowCircle = false;
00042
00043         public Scenario8()
00044         {
00045             this.InitializeComponent();
00046
00047             inkCanvas.InkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Mouse | Windows.UI.Core.CoreInputDeviceTypes.Pen;
00048
00049             var drawingAttributes = inkCanvas.InkPresenter.CopyDefaultDrawingAttributes();
00050             drawingAttributes.Size = new Size(penSize, penSize);
00051             inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
00052         }
00053
00054         protected override void OnNavigatedTo(NavigationEventArgs e)
00055         {
00056             // Registering handlers for Wet Stroke events
00057             coreWetStrokeUpdateSource = CoreWetStrokeUpdateSource.Create(inkCanvas.InkPresenter);
00058             coreWetStrokeUpdateSource.WetStrokeStarting += CoreWetStrokeUpdateSource_WetStrokeStarting;
00059             coreWetStrokeUpdateSource.WetStrokeContinuing += CoreWetStrokeUpdateSource_WetStrokeContinuing;
00060             coreWetStrokeUpdateSource.WetStrokeStopping += CoreWetStrokeUpdateSource_WetStrokeStopping;
00061             coreWetStrokeUpdateSource.WetStrokeCompleted += CoreWetStrokeUpdateSource_WetStrokeCompleted;
00062             coreWetStrokeUpdateSource.WetStrokeCanceled += CoreWetStrokeUpdateSource_WetStrokeCanceled;
00063         }
00064
00065         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00066         {
00067             // Unegistering handlers for Wet Stroke events
00068             coreWetStrokeUpdateSource.WetStrokeStarting -= CoreWetStrokeUpdateSource_WetStrokeStarting;
00069             coreWetStrokeUpdateSource.WetStrokeContinuing -= CoreWetStrokeUpdateSource_WetStrokeContinuing;
00070             coreWetStrokeUpdateSource.WetStrokeStopping -= CoreWetStrokeUpdateSource_WetStrokeStopping;
00071             coreWetStrokeUpdateSource.WetStrokeCompleted -= CoreWetStrokeUpdateSource_WetStrokeCompleted;
00072             coreWetStrokeUpdateSource.WetStrokeCanceled -= CoreWetStrokeUpdateSource_WetStrokeCanceled;
00073         }
00074
00075         private void InkStackPanel_Loaded(object sender, RoutedEventArgs e)
00076         {
00077             inkCanvas.Width = InkStackPanel.ActualWidth;
00078             inkCanvas.Height = InkStackPanel.ActualHeight;
00079
00080             circleCenter = new Point(inkCanvas.Width / 2.0f, inkCanvas.Height / 2.0f);
00081             InkCircle.Center = circleCenter;
00082             InkCircle.RadiusX = radius;
00083             InkCircle.RadiusY = radius;
00084             InkCirclePath.StrokeThickness = circleStrokeThickness;
00085         }
00086
00087         private void CoreWetStrokeUpdateSource_WetStrokeStarting(CoreWetStrokeUpdateSource sender, CoreWetStrokeUpdateEventArgs args)
00088         {
00089             followCircle = disableFollowCircle ? false : FollowCircleTest(args);
00090             if (followCircle)
00091             {
00092                 HandleFollowCircleInput(args);
00093             }
00094             else
00095             {
00096                 disableFollowCircle = true;
00097                 HandleRegularInput(args);
00098             }
00099         }
00100
00101         private void CoreWetStrokeUpdateSource_WetStrokeContinuing(CoreWetStrokeUpdateSource sender, CoreWetStrokeUpdateEventArgs args)
00102         {
00103             if (followCircle)
00104             {
00105                 HandleFollowCircleInput(args);
00106             }
00107             else
00108             {
00109                 HandleRegularInput(args);
00110             }
00111         }
00112
00113         private void CoreWetStrokeUpdateSource_WetStrokeStopping(CoreWetStrokeUpdateSource sender, CoreWetStrokeUpdateEventArgs args)
00114         {
00115             if (followCircle)
00116             {
00117                 HandleFollowCircleInput(args);
00118             }
00119             else
00120             {
00121                 HandleRegularInput(args);
00122             }
00123
00124             disableFollowCircle = false;
00125         }
00126
00127         private void CoreWetStrokeUpdateSource_WetStrokeCompleted(CoreWetStrokeUpdateSource sender, CoreWetStrokeUpdateEventArgs args)
00128         {
00129             followCircle = false;
00130             discontinueStroke = false;
00131         }
00132
00133         private void CoreWetStrokeUpdateSource_WetStrokeCanceled(CoreWetStrokeUpdateSource sender, CoreWetStrokeUpdateEventArgs args)
00134         {
00135             followCircle = false;
00136             discontinueStroke = false;
00137             disableFollowCircle = false;
00138         }
00139
00140         private bool FollowCircleTest(CoreWetStrokeUpdateEventArgs args)
00141         {
00142             var position = args.NewInkPoints[0].Position;
00143             var distanceFromCenter = DistanceFromCenter(position);
00144
00145             return InCircleEdgeZone(distanceFromCenter);
00146         }
00147
00148         private void HandleFollowCircleInput(CoreWetStrokeUpdateEventArgs args)
00149         {
00150             if (!discontinueStroke)
00151             {
00152                 for (int i = 0; i < args.NewInkPoints.Count; i++)
00153                 {
00154                     var position = args.NewInkPoints[i].Position;
00155                     var distanceFromCenter = DistanceFromCenter(position);
00156
00157                     if (InCircleEdgeZone(distanceFromCenter))
00158                     {
00159                         // Calculate position of new InkPoint so that it lies on the edge of the circle
00160                         var radians = Math.Atan2(position.Y - circleCenter.Y, position.X - circleCenter.X);
00161                         var totalRadius = (radius + circleStrokeThickness / 2.0f + penSize / 2.0f);
00162                         Point newPoint = new Point((Math.Cos(radians) * totalRadius) + circleCenter.X, (Math.Sin(radians) * totalRadius) + circleCenter.Y);
00163
00164                         args.NewInkPoints[i] = new InkPoint(newPoint, 0.5f);
00165                     }
00166                     else
00167                     {
00168                         // InkPoint is not in the follow circle zone, add no more InkPoints to Stroke
00169                         discontinueStroke = true;
00170
00171                         for (int j = args.NewInkPoints.Count - 1; j >= i; j--)
00172                         {
00173                             args.NewInkPoints.RemoveAt(j);
00174                         }
00175                         break;
00176                     }
00177                 }
00178             }
00179             else
00180             {
00181                 // Stroke has been discontinued, remove all InkPoints
00182                 for (int j = args.NewInkPoints.Count - 1; j >= 0; j--)
00183                 {
00184                     args.NewInkPoints.RemoveAt(j);
00185                 }
00186             }
00187         }
00188
00189         private void HandleRegularInput(CoreWetStrokeUpdateEventArgs args)
00190         {
00191             for (int i = 0; i < args.NewInkPoints.Count; i++)
00192             {
00193                 var position = args.NewInkPoints[i].Position;
00194                 var distanceFromCenter = DistanceFromCenter(position);
00195
00196                 if (distanceFromCenter < radius + circleStrokeThickness / 2 + penSize / 2)
00197                 {
00198                     // Ink input entered the circle. Handle this by removing remaining InkPoints
00199                     // and completing the stroke.
00200
00201                     for (int j = args.NewInkPoints.Count - 1; j >= i; j--)
00202                     {
00203                         args.NewInkPoints.RemoveAt(j);
00204                     }
00205
00206                     args.Disposition = CoreWetStrokeDisposition.Completed;
00207                     break;
00208                 }
00209             }
00210         }
00211
00212         private double DistanceFromCenter(Point position)
00213         {
00214             return Math.Sqrt((position.X - circleCenter.X) * (position.X - circleCenter.X) +
00215                              (position.Y - circleCenter.Y) * (position.Y - circleCenter.Y));
00216         }
00217
00218         private bool InCircleEdgeZone(double distanceFromCenter)
00219         {
00220             return (distanceFromCenter > radius * 0.8) && (distanceFromCenter < radius * 1.5);
00221         }
00222     }
00223 }
Generated on Fri Nov 15 2024 22:18:15 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: D2DCustomEffects/cpp/PixelShader/CustomPixelShaderMain.cpp Source File

  • D2DCustomEffects
  • cpp
  • PixelShader

CustomPixelShaderMain.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "CustomPixelShaderMain.h"
00014 #include "DirectXHelper.h"
00015
00016 using namespace CustomPixelShader;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::System::Threading;
00020 using namespace Windows::UI::Core;
00021 using namespace Concurrency;
00022
00023 // Loads and initializes application assets when the application is loaded.
00024 CustomPixelShaderMain::CustomPixelShaderMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00025     m_deviceResources(deviceResources)
00026 {
00027     // Register to be notified if the Device is lost or recreated.
00028     m_deviceResources->RegisterDeviceNotify(this);
00029
00030     m_sceneRenderer = std::unique_ptr<CustomPixelShaderRenderer>(new CustomPixelShaderRenderer(m_deviceResources));
00031     m_sampleOverlay = std::unique_ptr<SampleOverlay>(new SampleOverlay(m_deviceResources, L"Direct2D Custom Pixel Shader Effect"));
00032 }
00033
00034 CustomPixelShaderMain::~CustomPixelShaderMain()
00035 {
00036     // Deregister device notification.
00037     m_deviceResources->RegisterDeviceNotify(nullptr);
00038 }
00039
00040 // Updates application state when the window size changes (e.g. device orientation change)
00041 void CustomPixelShaderMain::CreateWindowSizeDependentResources()
00042 {
00043     m_sceneRenderer->CreateWindowSizeDependentResources();
00044     m_sampleOverlay->CreateWindowSizeDependentResources();
00045 }
00046
00047 void CustomPixelShaderMain::UpdatePointer(_In_ PointerEventArgs^ args)
00048 {
00049     m_sceneRenderer->UpdatePointer(args);
00050 }
00051
00052 // Updates the application state once per frame.
00053 void CustomPixelShaderMain::Update()
00054 {
00055     m_sceneRenderer->Update();
00056 }
00057
00058 // Renders the current frame according to the current application state.
00059 // Returns true if the frame was rendered and is ready to be displayed.
00060 bool CustomPixelShaderMain::Render()
00061 {
00062     m_sceneRenderer->Render();
00063     m_sampleOverlay->Render();
00064
00065     return true;
00066 }
00067
00068 // Notifies renderers that device resources need to be released.
00069 void CustomPixelShaderMain::OnDeviceLost()
00070 {
00071     m_sceneRenderer->ReleaseDeviceDependentResources();
00072     m_sampleOverlay->ReleaseDeviceDependentResources();
00073 }
00074
00075 // Notifies renderers that device resources may now be recreated.
00076 void CustomPixelShaderMain::OnDeviceRestored()
00077 {
00078     m_sceneRenderer->CreateDeviceDependentResources();
00079     m_sampleOverlay->CreateDeviceDependentResources();
00080     CreateWindowSizeDependentResources();
00081 }
00082
00083 void CustomPixelShaderMain::SaveInternalState(_In_ IPropertySet ^ state)
00084 {
00085     m_sceneRenderer->SaveInternalState(state);
00086 }
00087
00088 void CustomPixelShaderMain::LoadInternalState(_In_ IPropertySet ^ state)
00089 {
00090     m_sceneRenderer->LoadInternalState(state);
00091 }
Generated on Fri Nov 15 2024 22:19:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geotag/cpp/pch.h Source File

  • Geotag
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContentIndexer/cpp/SampleConfiguration.h Source File

  • ContentIndexer
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004 #include "pch.h"
00005
00006 namespace SDKTemplate
00007 {
00008     value struct Scenario;
00009
00010     partial ref class MainPage
00011     {
00012     internal:
00013         static property Platform::String^ FEATURE_NAME
00014         {
00015             Platform::String^ get()
00016             {
00017                 return "Content indexer C++ sample";
00018             }
00019         }
00020
00021         static property Platform::Array<Scenario>^ scenarios
00022         {
00023             Platform::Array<Scenario>^ get()
00024             {
00025                 return scenariosInner;
00026             }
00027         }
00028
00029     private:
00030         static Platform::Array<Scenario>^ scenariosInner;
00031     };
00032
00033     public value struct Scenario
00034     {
00035         Platform::String^ Title;
00036         Platform::String^ ClassName;
00037     };
00038 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PlayReady/cs/ViewModels/PlayReadyInfoViewModel.cs Source File

  • PlayReady
  • cs
  • ViewModels

PlayReadyInfoViewModel.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.ApplicationModel.Core;
00014 using Windows.Media.Protection.PlayReady;
00015 using Windows.UI.Core;
00016
00017 namespace SDKTemplate.ViewModels
00018 {
00019     public class PlayReadyInfoViewModel : ViewModelBase
00020     {
00021
00022         public async void RefreshStatics()
00023         {
00024             var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
00025             await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00026             {
00027                 try
00028                 {
00029                     SecurityLevel = PlayReadyStatics.PlayReadyCertificateSecurityLevel;
00030                     PlayReadySecurityVersion = PlayReadyStatics.PlayReadySecurityVersion;
00031                     HasHardwareDRM = PlayReadyStatics.CheckSupportedHardware(PlayReadyHardwareDRMFeatures.HardwareDRM);
00032                     HasHEVCSupport = PlayReadyStatics.CheckSupportedHardware(PlayReadyHardwareDRMFeatures.HEVC);
00033                 }
00034                 catch
00035                 {
00036                     ViewModelBase.Log("PlayReadyStatics not yet available");
00037                 }
00038             });
00039
00040
00041         }
00042
00043         private uint playReadySecurityVersion;
00044
00045         public uint PlayReadySecurityVersion
00046         {
00047             get { return playReadySecurityVersion; }
00048             private set
00049             {
00050                 if (playReadySecurityVersion != value)
00051                 {
00052                     playReadySecurityVersion = value;
00053                     RaisePropertyChanged();
00054                 }
00055             }
00056         }
00057
00058
00059         private uint securityLevel;
00060         public uint SecurityLevel
00061         {
00062             get
00063             {
00064                 return securityLevel;
00065             }
00066             private set
00067             {
00068                 if (securityLevel != value)
00069                 {
00070                     securityLevel = value;
00071                     RaisePropertyChanged();
00072                 }
00073             }
00074         }
00075
00076         private bool hasHEVCSupport;
00077         public bool HasHEVCSupport
00078         {
00079             get
00080             {
00081                 return hasHEVCSupport;
00082             }
00083             private set
00084             {
00085                 if (hasHEVCSupport != value)
00086                 {
00087                     hasHEVCSupport = value;
00088                     RaisePropertyChanged();
00089                 }
00090             }
00091         }
00092
00093         private bool hasHardwareDRM;
00094         public bool HasHardwareDRM
00095         {
00096             get
00097             {
00098                 return hasHardwareDRM;
00099             }
00100             private set
00101             {
00102                 if (hasHardwareDRM != value)
00103                 {
00104                     hasHardwareDRM = value;
00105                     RaisePropertyChanged();
00106                 }
00107             }
00108         }
00109
00110     }
00111 }
Generated on Fri Nov 15 2024 22:20:56 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdaptiveStreaming/cs/Scenario1_SimplestAdaptiveStreaming.xaml.cs Source File

  • AdaptiveStreaming
  • cs

Scenario1_SimplestAdaptiveStreaming.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate.Helpers;
00013 using SDKTemplate.Models;
00014 using System;
00015 using Windows.Media.Core;
00016 using Windows.Media.Playback;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     /// See the README.md for discussion of this scenario.
00024     public sealed partial class Scenario1_SimplestAdaptiveStreaming : Page
00025     {
00026         public Scenario1_SimplestAdaptiveStreaming()
00027         {
00028             this.InitializeComponent();
00029         }
00030
00031         protected override void OnNavigatedFrom(NavigationEventArgs e)
00032         {
00033             var mp = mediaPlayerElement.MediaPlayer;
00034             if (mp != null)
00035             {
00036                 // Ensure MediaPlayerElement drops its reference to MediaPlayer.
00037                 mediaPlayerElement.SetMediaPlayer(null);
00038
00039                 // Finally the app can also explicitly clean up the MediaPlayer.
00040                 mp.Dispose();
00041             }
00042         }
00043
00044         private void Load_Click(object sender, RoutedEventArgs e)
00045         {
00046             // NOTE: Change this to 115 to see DASH with PlayReady scenario
00047             const int contentIdForCMS = 1;
00048
00049             AdaptiveContentModel adaptiveContentModel = MainPage.FindContentById(contentIdForCMS);
00050
00051             if (adaptiveContentModel.PlayReady)
00052             {
00053                 // For PlayReady, we need to create and setup MediaPlayer.MediaProtectionManager
00054                 // All scenarios use a helper class to do this, see Helpers\PlayReadyHelper.cs
00055                 var mp = new MediaPlayer();
00056                 var prHelper = new PlayReadyHelper(); // From SDKTemplate.Helpers.PlayReadyHelper
00057                 prHelper.SetUpProtectionManager(mp);
00058                 mediaPlayerElement.SetMediaPlayer(mp);
00059             }
00060
00061             mediaPlayerElement.Source = MediaSource.CreateFromUri(adaptiveContentModel.ManifestUri);
00062         }
00063     }
00064 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PlayReady/cs/Shared/RelayCommand.cs Source File

  • PlayReady
  • cs
  • Shared

RelayCommand.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Linq;
00015 using System.Text;
00016 using System.Threading.Tasks;
00017 using System.Windows.Input;
00018
00019 namespace SDKTemplate.Shared
00020 {
00021     /// <summary>
00022     /// A command whose sole purpose is to relay its functionality
00023     /// to other objects by invoking delegates.
00024     /// The default return value for the CanExecute method is 'true'.
00025     /// <see cref="RaiseCanExecuteChanged"/> needs to be called whenever
00026     /// <see cref="CanExecute"/> is expected to return a different value.
00027     /// </summary>
00028     public class RelayCommand : ICommand
00029     {
00030         private readonly Action _execute;
00031         private readonly Func<bool> _canExecute;
00032
00033         /// <summary>
00034         /// Raised when RaiseCanExecuteChanged is called.
00035         /// </summary>
00036         public event EventHandler CanExecuteChanged;
00037
00038         /// <summary>
00039         /// Creates a new command that can always execute.
00040         /// </summary>
00041         /// <param name="execute">The execution logic.</param>
00042         public RelayCommand(Action execute)
00043             : this(execute, null)
00044         {
00045         }
00046
00047         /// <summary>
00048         /// Creates a new command.
00049         /// </summary>
00050         /// <param name="execute">The execution logic.</param>
00051         /// <param name="canExecute">The execution status logic.</param>
00052         public RelayCommand(Action execute, Func<bool> canExecute)
00053         {
00054             if (execute == null)
00055                 throw new ArgumentNullException("execute");
00056             _execute = execute;
00057             _canExecute = canExecute;
00058         }
00059
00060         /// <summary>
00061         /// Determines whether this <see cref="RelayCommand"/> can execute in its current state.
00062         /// </summary>
00063         /// <param name="parameter">
00064         /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
00065         /// </param>
00066         /// <returns>true if this command can be executed; otherwise, false.</returns>
00067         public bool CanExecute(object parameter)
00068         {
00069             return _canExecute == null ? true : _canExecute();
00070         }
00071
00072         /// <summary>
00073         /// Executes the <see cref="RelayCommand"/> on the current command target.
00074         /// </summary>
00075         /// <param name="parameter">
00076         /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
00077         /// </param>
00078         public void Execute(object parameter)
00079         {
00080             _execute();
00081         }
00082
00083         /// <summary>
00084         /// Method used to raise the <see cref="CanExecuteChanged"/> event
00085         /// to indicate that the return value of the <see cref="CanExecute"/>
00086         /// method has changed.
00087         /// </summary>
00088         public void RaiseCanExecuteChanged()
00089         {
00090             var handler = CanExecuteChanged;
00091             if (handler != null)
00092             {
00093                 handler(this, EventArgs.Empty);
00094             }
00095         }
00096     }
00097 }
Generated on Fri Nov 15 2024 22:17:38 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Unicode/cppwinrt/Scenario1_FindId.h Source File

  • Unicode
  • cppwinrt

Scenario1_FindId.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_FindId.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario1_FindId : Scenario1_FindIdT<Scenario1_FindId>
00020     {
00021         Scenario1_FindId();
00022
00023         void Default_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024     };
00025 }
00026
00027 namespace winrt::SDKTemplate::factory_implementation
00028 {
00029     struct Scenario1_FindId : Scenario1_FindIdT<Scenario1_FindId, implementation::Scenario1_FindId>
00030     {
00031     };
00032 }
Generated on Fri Nov 15 2024 22:21:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BackgroundTransfer/cpp/BackgroundTransfer/Scenario1_Download.xaml.h Source File

  • BackgroundTransfer
  • cpp
  • BackgroundTransfer

Scenario1_Download.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // Scenario1_Download.xaml.h
00014 // Declaration of the Scenario1_Download class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "Scenario1_Download.g.h"
00021 #include "MainPage.xaml.h"
00022
00023 namespace SDKTemplate
00024 {
00025     struct GuidComparer
00026     {
00027         bool operator() (const Platform::Guid&, const Platform::Guid&) const
00028         {
00029             return false;
00030         }
00031     };
00032
00033     /// <summary>
00034     /// An empty page that can be used on its own or navigated to within a Frame.
00035     /// </summary>
00036     [Windows::Foundation::Metadata::WebHostHidden]
00037     public ref class Scenario1_Download sealed
00038     {
00039     public:
00040         Scenario1_Download();
00041
00042     protected:
00043         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00044
00045     private:
00046         SDKTemplate::MainPage^ rootPage;
00047         Concurrency::cancellation_token_source* cancellationToken;
00048         std::map<int /*Platform::Guid*/, Windows::Networking::BackgroundTransfer::DownloadOperation^> activeDownloads;
00049
00050         void StartDownload_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00051         void StartHighPriorityDownload_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00052         void CancelAll_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00053         void ResumeAll_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00054         void PauseAll_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00055
00056         void HandleDownloadAsync(Windows::Networking::BackgroundTransfer::DownloadOperation^ download, boolean start);
00057         void DownloadProgress(
00058             Windows::Foundation::IAsyncOperationWithProgress<Windows::Networking::BackgroundTransfer::DownloadOperation^, Windows::Networking::BackgroundTransfer::DownloadOperation^>^ operation,
00059             Windows::Networking::BackgroundTransfer::DownloadOperation^);
00060         void DiscoverActiveDownloads();
00061         void LogException(Platform::String^ title, Platform::Exception^ ex);
00062         void MarshalLog(Platform::String^ value);
00063         void Log(Platform::String^ message);
00064         void LogStatus(Platform::String^ message, SDKTemplate::NotifyType type);
00065         void StartDownload(Windows::Networking::BackgroundTransfer::BackgroundTransferPriority priority);
00066
00067         ~Scenario1_Download();
00068     };
00069 }
Generated on Fri Nov 15 2024 22:18:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cppwinrt/Scenario1_LongAndShortFormats.h Source File

  • DateTimeFormatting
  • cppwinrt

Scenario1_LongAndShortFormats.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_LongAndShortFormats.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario1_LongAndShortFormats : Scenario1_LongAndShortFormatsT<Scenario1_LongAndShortFormats>
00019     {
00020         Scenario1_LongAndShortFormats();
00021
00022         void Display_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023     };
00024 }
00025
00026 namespace winrt::SDKTemplate::factory_implementation
00027 {
00028     struct Scenario1_LongAndShortFormats : Scenario1_LongAndShortFormatsT<Scenario1_LongAndShortFormats, implementation::Scenario1_LongAndShortFormats>
00029     {
00030     };
00031 }
Generated on Fri Nov 15 2024 22:19:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Store/cpp/pch.h Source File

  • Store
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // pch.h
00014 // Header for standard system include files.
00015 //
00016
00017 #pragma once
00018
00019 #include <ppltasks.h>
00020 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario14_MeteredConnectionFilter Member List

This is the complete list of members for Scenario14_MeteredConnectionFilter, including all inherited members.
Cancel_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario14_MeteredConnectionFilter |
CancelableRequestAsync(Windows::Foundation::Uri resourceUri) | Scenario14_MeteredConnectionFilter | [private]
OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario14_MeteredConnectionFilter |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | Scenario14_MeteredConnectionFilter |
OptInSwitch_Toggled(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario14_MeteredConnectionFilter |
Scenario14_MeteredConnectionFilter() | Scenario14_MeteredConnectionFilter |
Start_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario14_MeteredConnectionFilter |
Generated on Fri Nov 15 2024 22:24:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CashDrawer/cpp/Scenario3_MultipleDrawers.xaml.h Source File

  • CashDrawer
  • cpp

Scenario3_MultipleDrawers.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_MultipleDrawers.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     [Windows::Foundation::Metadata::WebHostHidden]
00023     public ref class Scenario3_MultipleDrawers sealed
00024     {
00025     public:
00026         Scenario3_MultipleDrawers();
00027
00028     private:
00029         MainPage^ rootPage;
00030
00031         Windows::Devices::PointOfService::CashDrawer^ cashDrawerInstance1 = nullptr;
00032         Windows::Devices::PointOfService::CashDrawer^ cashDrawerInstance2 = nullptr;
00033         Windows::Devices::PointOfService::ClaimedCashDrawer^ claimedCashDrawerInstance1 = nullptr;
00034         Windows::Devices::PointOfService::ClaimedCashDrawer^ claimedCashDrawerInstance2 = nullptr;
00035
00036         void ClaimButton1_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00037         void ClaimButton2_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00038         void ReleaseButton1_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00039         void ReleaseButton2_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00040
00041         enum CashDrawerInstance
00042         {
00043             Instance1,
00044             Instance2
00045         };
00046
00047         Windows::Foundation::EventRegistrationToken releaseRequestedToken1;
00048         Windows::Foundation::EventRegistrationToken releaseRequestedToken2;
00049
00050         void claimedCashDrawerInstance1_ReleaseDeviceRequested(Windows::Devices::PointOfService::ClaimedCashDrawer^ sender, Platform::Object^ e);
00051         void claimedCashDrawerInstance2_ReleaseDeviceRequested(Windows::Devices::PointOfService::ClaimedCashDrawer^ sender, Platform::Object^ e);
00052
00053         concurrency::task<bool> CreateDefaultCashDrawerObject(CashDrawerInstance instance);
00054         concurrency::task<bool> ClaimCashDrawer(CashDrawerInstance instance);
00055
00056         void ResetScenarioState();
00057         void SetClaimedUI(CashDrawerInstance instance);
00058         void SetReleasedUI(CashDrawerInstance instance);
00059
00060     protected:
00061         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00062         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00063     };
00064
00065 }
Generated on Fri Nov 15 2024 22:18:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProxyStubsForWinRTComponents/cpp/cpp/Scenario3_CustomException.xaml.cpp Source File

  • ProxyStubsForWinRTComponents
  • cpp
  • cpp

Scenario3_CustomException.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #include "pch.h"
00008 #include "Scenario3_CustomException.xaml.h"
00009 #include "MainPage.xaml.h"
00010 #include "..\Server\Microsoft.SDKSamples.Kitchen.h"
00011
00012 using namespace SDKSample;
00013 using namespace SDKSample::ProxyStubsForWinRTComponents;
00014
00015 using namespace Microsoft::SDKSamples::Kitchen;
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019
00020 CustomException::CustomException()
00021 {
00022     InitializeComponent();
00023 }
00024
00025 void ProxyStubsForWinRTComponents::CustomException::Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00026 {
00027     // Component Creation
00028     Oven^ myOven = ref new Oven();
00029
00030     try
00031     {
00032         // Intentionally pass an invalid value
00033         myOven->ConfigurePreheatTemperature(static_cast<Microsoft::SDKSamples::Kitchen::OvenTemperature>(5));
00034     }
00035     catch (Platform::InvalidArgumentException^ e)
00036     {
00037         CustomExceptionOutput->Text += L"Exception caught. Please attach a debugger and enable first chance native exceptions to view exception details.\n";
00038     }
00039 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: TitleBar/cppwinrt/pch.cpp Source File

  • TitleBar
  • cppwinrt

pch.cpp

Go to the documentation of this file.
00001 ﻿//
00002 // pch.cpp
00003 // Include the standard header and generate the precompiled header.
00004 //
00005
00006 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/Common/InkEventLogger.h Source File

  • ComplexInk
  • cpp
  • Common

InkEventLogger.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "Resources.h"
00006
00007 class InkEventLogger
00008 {
00009 public:
00010     InkEventLogger();
00011     void SetConfiguration(LogEventTypes config);
00012     void EnableLoggingConfiguration(LogEventTypes type, bool addConfig);
00013     void Log(LogEventAction eventAction);
00014     std::wstring GetLog() { return _log; };
00015     void ClearLog() { _log = L""; };
00016
00017 private:
00018     LogEventTypes   _currentConfig;
00019     std::wstring    _log;
00020
00021     unsigned long _countOfCoalescedIndependentInput;
00022     unsigned long _countOfCoalescedStrokeMessages;
00023     unsigned long _countOfCoalescedUnprocessedInput;
00024 };
00025
Generated on Fri Nov 15 2024 22:18:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Dimensions Member List

This is the complete list of members for Dimensions, including all inherited members.
Depth | Dimensions
Height | Dimensions
Width | Dimensions
Generated on Fri Nov 15 2024 22:23:30 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cs/Scenario7_DeviceInformationKind.xaml.cs Source File

  • DeviceEnumerationAndPairing
  • cs

Scenario7_DeviceInformationKind.xaml.cs

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 using System;
00004 using System.Collections.Generic;
00005 using System.Collections.ObjectModel;
00006 using Windows.Devices.Enumeration;
00007 using Windows.Foundation;
00008 using Windows.UI.Core;
00009 using Windows.UI.Xaml;
00010 using Windows.UI.Xaml.Controls;
00011 using Windows.UI.Xaml.Navigation;
00012
00013 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00014
00015 namespace SDKTemplate
00016 {
00017     /// <summary>
00018     /// An empty page that can be used on its own or navigated to within a Frame.
00019     /// </summary>
00020     public sealed partial class Scenario7_DeviceInformationKind : Page
00021     {
00022         private MainPage rootPage = MainPage.Current;
00023
00024         private List<DeviceWatcherHelper> deviceWatcherHelpers = new List<DeviceWatcherHelper>();
00025
00026         private ObservableCollection<DeviceInformationDisplay> resultCollection = new ObservableCollection<DeviceInformationDisplay>();
00027
00028         public Scenario7_DeviceInformationKind()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         protected override void OnNavigatedTo(NavigationEventArgs e)
00034         {
00035             resultsListView.ItemsSource = resultCollection;
00036
00037             kindComboBox.ItemsSource = DeviceInformationKindChoices.Choices;
00038             kindComboBox.SelectedIndex = 0;
00039         }
00040
00041         protected override void OnNavigatedFrom(NavigationEventArgs e)
00042         {
00043             StopWatchers(/* reset */ true);
00044         }
00045
00046         private void StartWatcherButton_Click(object sender, RoutedEventArgs e)
00047         {
00048             StartWatchers();
00049         }
00050
00051         private void StopWatcherButton_Click(object sender, RoutedEventArgs e)
00052         {
00053             StopWatchers();
00054         }
00055
00056         private void StartWatchers()
00057         {
00058             startWatcherButton.IsEnabled = false;
00059             resultCollection.Clear();
00060
00061             // Create a watcher for each DeviceInformationKind selected by the user
00062             foreach (DeviceInformationKind deviceInfoKind in ((DeviceInformationKindChoice)kindComboBox.SelectedItem).DeviceInformationKinds)
00063             {
00064                 DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher(
00065                         "", // AQS Filter string
00066                         null, // requested properties
00067                         deviceInfoKind);
00068
00069                 DeviceWatcherHelper deviceWatcherHelper = new DeviceWatcherHelper(resultCollection, Dispatcher);
00070                 deviceWatcherHelper.UpdateStatus = false; // we will show our own status messages
00071                 deviceWatcherHelper.DeviceChanged += OnDeviceListChanged;
00072                 deviceWatcherHelpers.Add(deviceWatcherHelper);
00073
00074                 deviceWatcherHelper.StartWatcher(deviceWatcher);
00075             }
00076
00077             stopWatcherButton.IsEnabled = true;
00078             stopWatcherButton.Focus(FocusState.Keyboard);
00079         }
00080
00081         private void StopWatchers(bool reset = false)
00082         {
00083             stopWatcherButton.IsEnabled = false;
00084
00085             foreach (DeviceWatcherHelper deviceWatcherHelper in deviceWatcherHelpers)
00086             {
00087                 deviceWatcherHelper.StopWatcher();
00088                 if (reset)
00089                 {
00090                     deviceWatcherHelper.Reset();
00091                 }
00092             }
00093             deviceWatcherHelpers.Clear();
00094
00095             startWatcherButton.IsEnabled = true;
00096             startWatcherButton.Focus(FocusState.Keyboard);
00097         }
00098
00099         private void OnDeviceListChanged(DeviceWatcher sender, string id)
00100         {
00101             int watchersRunning = 0;
00102
00103             // Count running watchers
00104             foreach (DeviceWatcherHelper deviceWatcherHelper in deviceWatcherHelpers)
00105             {
00106                 if (deviceWatcherHelper.IsWatcherRunning())
00107                 {
00108                     watchersRunning++;
00109                 }
00110             }
00111
00112             string message = $"{watchersRunning}/{deviceWatcherHelpers.Count} watchers running. {resultCollection.Count} devices found.";
00113             rootPage.NotifyUser(message, NotifyType.StatusMessage);
00114         }
00115     }
00116 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HttpClient/cppwinrt/Scenario01_GetText.h Source File

  • HttpClient
  • cppwinrt

Scenario01_GetText.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario01_GetText.g.h"
00015 #include "MainPage.h"
00016
00017 namespace winrt::SDKTemplate::implementation
00018 {
00019     struct Scenario01_GetText : Scenario01_GetTextT<Scenario01_GetText>
00020     {
00021         Scenario01_GetText();
00022
00023         void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00024         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00025
00026         fire_and_forget Start_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         void Cancel_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         void MaxHttpVersionToggle_Toggled(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029
00030     private:
00031         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00032         Windows::Web::Http::Filters::HttpBaseProtocolFilter filter{ nullptr };
00033         Windows::Web::Http::HttpClient httpClient{ nullptr };
00034         Windows::Foundation::IAsyncAction pendingAction{ nullptr };
00035         bool isFilterUsed = false;
00036
00037     private:
00038         Windows::Foundation::IAsyncAction CancelableRequestAsync(Windows::Foundation::Uri resourceUri);
00039     };
00040 }
00041
00042 namespace winrt::SDKTemplate::factory_implementation
00043 {
00044     struct Scenario01_GetText : Scenario01_GetTextT<Scenario01_GetText, implementation::Scenario01_GetText>
00045     {
00046     };
00047 }
Generated on Fri Nov 15 2024 22:19:57 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContentIndexer/cs/S7_RetrieveWithAppContent.xaml.cs Source File

  • ContentIndexer
  • cs

S7_RetrieveWithAppContent.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using Windows.UI.Xaml;
00013 using Windows.UI.Xaml.Controls;
00014 using Windows.UI.Xaml.Navigation;
00015 using System;
00016
00017 namespace SDKTemplate
00018 {
00019     /// <summary>
00020     /// An empty page that can be used on its own or navigated to within a Frame.
00021     /// </summary>
00022     public sealed partial class S7_RetrieveWithAppContent
00023     {
00024         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00025         // as NotifyUser()
00026         MainPage rootPage = MainPage.Current;
00027
00028         public S7_RetrieveWithAppContent()
00029         {
00030             this.InitializeComponent();
00031             Helpers.InitializeRevisionNumber();
00032         }
00033
00034         /// <summary>
00035         /// Invoked when this page is about to be displayed in a Frame.
00036         /// </summary>
00037         /// <param name="e">Event data that describes how this page was reached.  The Parameter
00038         /// property is typically used to configure the page.</param>
00039         protected override void OnNavigatedTo(NavigationEventArgs e)
00040         {
00041         }
00042
00043         private async void AddToIndex_Click(object sender, RoutedEventArgs e)
00044         {
00045             var outputString = await Helpers.AddAppContentFilesToIndexedFolder();
00046             rootPage.NotifyUser(outputString, NotifyType.StatusMessage);
00047         }
00048
00049         delegate Windows.Storage.Search.StorageFileQueryResult GetQueryDelegate(Windows.Storage.StorageFolder folder);
00050
00051         private async void RetrieveAppContentHelper(GetQueryDelegate getQuery)
00052         {
00053             var indexedFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("Indexed", Windows.Storage.CreationCollisionOption.OpenIfExists);
00054             var query = getQuery(indexedFolder);
00055             var files = await query.GetFilesAsync();
00056             string[] propertyKeys =
00057             {
00058                 Windows.Storage.SystemProperties.ItemNameDisplay,
00059                 Windows.Storage.SystemProperties.Keywords,
00060                 Windows.Storage.SystemProperties.Comment,
00061                 Windows.Storage.SystemProperties.Title
00062             };
00063             var outputString = "";
00064             foreach (var file in files)
00065             {
00066                 var retrievedProperties = await file.Properties.RetrievePropertiesAsync(propertyKeys);
00067                 outputString += "Name: " + Helpers.StringifyProperty(retrievedProperties[Windows.Storage.SystemProperties.ItemNameDisplay]) + "\n";
00068                 outputString += "Keywords: " + Helpers.StringifyProperty(retrievedProperties[Windows.Storage.SystemProperties.Keywords]) + "\n";
00069                 outputString += "Comment: " + Helpers.StringifyProperty(retrievedProperties[Windows.Storage.SystemProperties.Comment]) + "\n";
00070                 outputString += "Title: " + Helpers.StringifyProperty(retrievedProperties[Windows.Storage.SystemProperties.Title]) + "\n\n";
00071             }
00072             rootPage.NotifyUser(outputString, NotifyType.StatusMessage);
00073         }
00074
00075         /// <summary>
00076         /// This function retrieves all items added to the index through the app's appcontent-ms files
00077         /// </summary>
00078         private void RetrieveAllItems_Click(object sender, RoutedEventArgs e)
00079         {
00080             // Query for all files in the "LocalState\Indexed" folder and sort the results by name
00081             RetrieveAppContentHelper(folder => folder.CreateFileQuery(Windows.Storage.Search.CommonFileQuery.OrderByName));
00082         }
00083
00084         /// <summary>
00085         /// This function retrieves all items added to the index through the app's appcontent-ms files which
00086         /// have an ItemNameDisplay property containing "Sample 1"
00087         /// </summary>
00088         private void RetrieveMatchedItems_Click(object sender, RoutedEventArgs e)
00089         {
00090             var queryOptions = new Windows.Storage.Search.QueryOptions();
00091             // Include only items returned via the index in the search results
00092             queryOptions.IndexerOption = Windows.Storage.Search.IndexerOption.OnlyUseIndexer;
00093             // Create an AQS (Advanced Query Syntax) query which will look for ItemNameDisplay properties which contain "Sample 1"
00094             queryOptions.ApplicationSearchFilter = Windows.Storage.SystemProperties.ItemNameDisplay + ":\"Sample 1\"";
00095             RetrieveAppContentHelper(folder => folder.CreateFileQueryWithOptions(queryOptions));
00096         }
00097     }
00098 }
Generated on Fri Nov 15 2024 22:18:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlTailoredMultipleViews/cs/TailoredMultipleViews/UserControls/Albums.xaml.cs Source File

  • XamlTailoredMultipleViews
  • cs
  • TailoredMultipleViews
  • UserControls

Albums.xaml.cs

Go to the documentation of this file.
00001 ﻿using OneHandedUse_TailoredMultipleViews.ViewModel;
00002 using System;
00003 using System.Collections.Generic;
00004 using System.IO;
00005 using System.Linq;
00006 using System.Runtime.InteropServices.WindowsRuntime;
00007 using Windows.Foundation;
00008 using Windows.Foundation.Collections;
00009 using Windows.UI.Xaml;
00010 using Windows.UI.Xaml.Controls;
00011 using Windows.UI.Xaml.Controls.Primitives;
00012 using Windows.UI.Xaml.Data;
00013 using Windows.UI.Xaml.Input;
00014 using Windows.UI.Xaml.Media;
00015 using Windows.UI.Xaml.Navigation;
00016
00017 // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
00018
00019 namespace OneHandedUse_TailoredMultipleViews.UserControls
00020 {
00021     public sealed partial class Albums : UserControl
00022     {
00023         private MainViewModel vm = new MainViewModel();
00024         public Albums()
00025         {
00026             this.InitializeComponent();
00027             this.DataContext = vm.GetAlbums();
00028         }
00029     }
00030 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

BarcodeScannerInfo Member List

This is the complete list of members for BarcodeScannerInfo, including all inherited members.
BarcodeScannerInfo(winrt::hstring const &deviceName, winrt::hstring const &deviceId) | BarcodeScannerInfo | [inline]
DeviceId() const | BarcodeScannerInfo | [inline]
m_deviceId | BarcodeScannerInfo | [private]
m_deviceName | BarcodeScannerInfo | [private]
Name() const | BarcodeScannerInfo | [inline]
Generated on Fri Nov 15 2024 22:24:12 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomHidDeviceAccess/cpp/Scenario3_InputReportEvents.xaml.h Source File

  • CustomHidDeviceAccess
  • cpp

Scenario3_InputReportEvents.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 //
00008 // Scenario3.xaml.h
00009 // Declaration of the Scenario3 class
00010 //
00011
00012 #pragma once
00013 #include "EventHandlerForDevice.h"
00014 #include "Scenario3_InputReportEvents.g.h"
00015
00016 namespace SDKTemplate
00017 {
00018     /// <summary>
00019     /// An empty page that can be used on its own or navigated to within a Frame.
00020     /// </summary>
00021     [Windows::Foundation::Metadata::WebHostHidden]
00022     public ref class InputReportEvents sealed
00023     {
00024     public:
00025         InputReportEvents();
00026     protected:
00027         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00028         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00029     private:
00030         Windows::Foundation::EventRegistrationToken inputReportEventToken;
00031         bool isRegisteredForInputReportEvents;
00032
00033         // Device that we registered for events with
00034         Windows::Devices::HumanInterfaceDevice::HidDevice^ registeredDevice;
00035
00036         uint32 numInputReportEventsReceived;
00037         uint32 totalNumberBytesReceived;
00038
00039         // Did we navigate away from this page?
00040         bool navigatedAway;
00041
00042         void OnDeviceClosing(EventHandlerForDevice^ sender, Windows::Devices::Enumeration::DeviceInformation^ deviceInformation);
00043
00044         void RegisterForInputReportEvents_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ eventArgs);
00045         void UnregisterFromInputReportEvents_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ eventArgs);
00046
00047         void RegisterForInputReportEvents();
00048
00049         void UnregisterFromInputReportEvent(void);
00050
00051         void OnInputReportEvent(
00052             Windows::Devices::HumanInterfaceDevice::HidDevice^ sender,
00053             Windows::Devices::HumanInterfaceDevice::HidInputReportReceivedEventArgs^ eventArgs);
00054
00055         void StartSuperMuttInputReports(void);
00056         void StopSuperMuttInputReports(void);
00057
00058         void UpdateRegisterEventButtons(void);
00059     };
00060 }
Generated on Fri Nov 15 2024 22:19:06 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/LiveTiles/AdaptiveTemplates/HintPresentation/Photos/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • LiveTiles
  • AdaptiveTemplates
  • HintPresentation
  • Photos

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Xaml.Controls;
00002
00003 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00004
00005 namespace Notifications.ScenarioPages.LiveTiles.AdaptiveTemplates.HintPresentation.Photos
00006 {
00007     /// <summary>
00008     /// An empty page that can be used on its own or navigated to within a Frame.
00009     /// </summary>
00010     public sealed partial class ScenarioElement : UserControl
00011     {
00012         public ScenarioElement()
00013         {
00014             this.InitializeComponent();
00015
00016             // Because different densities might be able to display more, we just set tons of text wrapped to make sure it overflows at some point
00017             updateFourTilesControl.SetTilePayload($@"
00018                 <tile>
00019                     <visual>
00020
00021                         <binding template='TileMedium' hint-presentation='photos'>
00022                             <image src='Assets/Photos/1.jpg'/>
00023                             <image src='Assets/Photos/2.jpg'/>
00024                             <image src='Assets/Photos/3.jpg'/>
00025                             <image src='Assets/Photos/4.jpg'/>
00026                             <image src='Assets/Photos/5.jpg'/>
00027                             <image src='Assets/Photos/6.jpg'/>
00028                             <image src='Assets/Photos/7.jpg'/>
00029                             <image src='Assets/Photos/8.jpg'/>
00030                             <image src='Assets/Photos/9.jpg'/>
00031                             <image src='Assets/Photos/10.jpg'/>
00032                         </binding>
00033
00034                         <binding template='TileWide' hint-presentation='photos'>
00035                             <image src='Assets/Photos/1.jpg'/>
00036                             <image src='Assets/Photos/2.jpg'/>
00037                             <image src='Assets/Photos/3.jpg'/>
00038                             <image src='Assets/Photos/4.jpg'/>
00039                             <image src='Assets/Photos/5.jpg'/>
00040                             <image src='Assets/Photos/6.jpg'/>
00041                             <image src='Assets/Photos/7.jpg'/>
00042                             <image src='Assets/Photos/8.jpg'/>
00043                             <image src='Assets/Photos/9.jpg'/>
00044                             <image src='Assets/Photos/10.jpg'/>
00045                         </binding>
00046
00047                         <binding template='TileLarge' hint-presentation='photos'>
00048                             <image src='Assets/Photos/1.jpg'/>
00049                             <image src='Assets/Photos/2.jpg'/>
00050                             <image src='Assets/Photos/3.jpg'/>
00051                             <image src='Assets/Photos/4.jpg'/>
00052                             <image src='Assets/Photos/5.jpg'/>
00053                             <image src='Assets/Photos/6.jpg'/>
00054                             <image src='Assets/Photos/7.jpg'/>
00055                             <image src='Assets/Photos/8.jpg'/>
00056                             <image src='Assets/Photos/9.jpg'/>
00057                             <image src='Assets/Photos/10.jpg'/>
00058                         </binding>
00059
00060                     </visual>
00061                 </tile>");
00062         }
00063     }
00064 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario1_Data Member List

This is the complete list of members for Scenario1_Data, including all inherited members.
ReportCalendarData(Calendar calendar, string calendarLabel) | Scenario1_Data | [inline, private]
Scenario1_Data() | Scenario1_Data | [inline]
ShowResults_Click(object sender, RoutedEventArgs e) | Scenario1_Data | [inline, private]
Generated on Fri Nov 15 2024 22:23:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario8_TransferMediaPlayer1 Member List

This is the complete list of members for Scenario8_TransferMediaPlayer1, including all inherited members.
CreateMediaPlayer_Click(object sender, RoutedEventArgs e) | Scenario8_TransferMediaPlayer1 | [inline, private]
OnNavigatedFrom(object sender, RoutedEventArgs e) | Scenario8_TransferMediaPlayer1 | [inline, private]
OnNavigatedTo(NavigationEventArgs e) | Scenario8_TransferMediaPlayer1 | [inline, protected]
rootPage | Scenario8_TransferMediaPlayer1 | [private]
Scenario8_TransferMediaPlayer1() | Scenario8_TransferMediaPlayer1 | [inline]
Generated on Fri Nov 15 2024 22:24:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DateTimeFormatting/cpp/SampleConfiguration.h Source File

  • DateTimeFormatting
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Date and time formatting";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038     private:
00039         static Platform::Array<Scenario>^ scenariosInner;
00040     };
00041
00042     public value struct Scenario
00043     {
00044         Platform::String^ Title;
00045         Platform::String^ ClassName;
00046     };
00047 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geotag/cpp/pch.cpp Source File

  • Geotag
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/05_Multi_View_Media_Application.xaml.cs Source File

  • AdvancedCasting
  • cs

05_Multi_View_Media_Application.xaml.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using ScreenCasting.Controls;
00013 using ScreenCasting.Data.Azure;
00014 using ScreenCasting.Data.Common;
00015 using ScreenCasting.Util;
00016 using System;
00017 using Windows.ApplicationModel.Core;
00018 using Windows.Devices.Enumeration;
00019 using Windows.Foundation;
00020 using Windows.UI.Core;
00021 using Windows.UI.ViewManagement;
00022 using Windows.UI.Xaml;
00023 using Windows.UI.Xaml.Controls;
00024 using Windows.UI.Xaml.Media;
00025 using Windows.UI.Xaml.Media.Imaging;
00026 using Windows.UI.Xaml.Navigation;
00027
00028 namespace ScreenCasting
00029 {
00030     public sealed partial class Scenario05 : Page
00031     {
00032         private MainPage rootPage;
00033         private DevicePicker picker;
00034         private VideoMetaData video = null;
00035         ProjectionViewBroker pvb = new ProjectionViewBroker();
00036         DeviceInformation activeDevice = null;
00037
00038         int thisViewId;
00039
00040         public Scenario05()
00041         {
00042             this.InitializeComponent();
00043
00044             rootPage = MainPage.Current;
00045
00046             //Subscribe to player events
00047             player.MediaOpened += Player_MediaOpened;
00048             player.MediaFailed += Player_MediaFailed;
00049             player.CurrentStateChanged += Player_CurrentStateChanged;
00050
00051             // Get an Azure hosted video
00052             AzureDataProvider dataProvider = new AzureDataProvider();
00053             video = dataProvider.GetRandomVideo();
00054
00055             //Set the source on the player
00056             rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage);
00057             this.player.Source = video.VideoLink;
00058             this.LicenseText.Text = "License: " + video.License;
00059
00060             //Subscribe for the clicked event on the custom cast button
00061             ((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked;
00062
00063             // Instantiate the Device Picker
00064             picker = new DevicePicker ();
00065
00066             // Get the device selecter for Miracast devices
00067             picker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector());
00068
00069             //Hook up device selected event
00070             picker.DeviceSelected += Picker_DeviceSelected;
00071
00072             //Hook up device disconnected event
00073             picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked;
00074
00075             //Hook up picker dismissed event
00076             picker.DevicePickerDismissed += Picker_DevicePickerDismissed;
00077
00078             // Hook up the events that are received when projection is stoppped
00079             pvb.ProjectionStopping += Pvb_ProjectionStopping;
00080         }
00081
00082         private void TransportControls_CastButtonClicked(object sender, EventArgs e)
00083         {
00084             rootPage.NotifyUser("Custom Cast Button Clicked", NotifyType.StatusMessage);
00085
00086             //Pause Current Playback
00087             player.Pause();
00088
00089             //Get the custom transport controls
00090             MediaTransportControlsWithCustomCastButton mtc = (MediaTransportControlsWithCustomCastButton)this.player.TransportControls;
00091
00092             //Retrieve the location of the casting button
00093             GeneralTransform transform = mtc.CastButton.TransformToVisual(Window.Current.Content as UIElement);
00094             Point pt = transform.TransformPoint(new Point(0, 0));
00095
00096             //Show the picker above our custom cast button
00097             picker.Show(new Rect(pt.X, pt.Y, mtc.CastButton.ActualWidth, mtc.CastButton.ActualHeight), Windows.UI.Popups.Placement.Above);
00098         }
00099         private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
00100         {
00101             //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
00102             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
00103             {
00104                 try
00105                 {
00106                 // Set status to Connecting
00107                 picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress);
00108
00109                 // Getting the selected device improves debugging
00110                 DeviceInformation selectedDevice = args.SelectedDevice;
00111
00112                 thisViewId = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Id;
00113
00114                 // If projection is already in progress, then it could be shown on the monitor again
00115                 // Otherwise, we need to create a new view to show the presentation
00116                 if (rootPage.ProjectionViewPageControl == null)
00117                 {
00118                     // First, create a new, blank view
00119                     var thisDispatcher = Window.Current.Dispatcher;
00120                     await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00121                     {
00122                         // ViewLifetimeControl is a wrapper to make sure the view is closed only
00123                         // when the app is done with it
00124                         rootPage.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView();
00125
00126                         // Assemble some data necessary for the new page
00127                         pvb.MainPageDispatcher = thisDispatcher;
00128                         pvb.ProjectionViewPageControl = rootPage.ProjectionViewPageControl;
00129                         pvb.MainViewId = thisViewId;
00130
00131                         // Display the page in the view. Note that the view will not become visible
00132                         // until "StartProjectingAsync" is called
00133                         var rootFrame = new Frame();
00134                         rootFrame.Navigate(typeof(ProjectionViewPage), pvb);
00135                         Window.Current.Content = rootFrame;
00136
00137                         Window.Current.Activate();
00138                     });
00139                 }
00140
00141                 try
00142                 {
00143                     // Start/StopViewInUse are used to signal that the app is interacting with the
00144                     // view, so it shouldn't be closed yet, even if the user loses access to it
00145                     rootPage.ProjectionViewPageControl.StartViewInUse();
00146
00147                     try
00148                     {
00149                         await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId, selectedDevice);
00150
00151                     }
00152                     catch (Exception ex)
00153                     {
00154                         if (!ProjectionManager.ProjectionDisplayAvailable || pvb.ProjectedPage == null)
00155                             throw ex;
00156                     }
00157
00158                     // ProjectionManager currently can throw an exception even when projection has started.\
00159                     // Re-throw the exception when projection has not been started after calling StartProjectingAsync
00160                     if (ProjectionManager.ProjectionDisplayAvailable && pvb.ProjectedPage != null)
00161                     {
00162                         this.player.Pause();
00163                         await pvb.ProjectedPage.SetMediaSource(this.player.Source, this.player.Position);
00164                         activeDevice = selectedDevice;
00165                         // Set status to Connected
00166                         picker.SetDisplayStatus(args.SelectedDevice, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
00167                         picker.Hide();
00168                     }
00169                     else
00170                     {
00171                         rootPage.NotifyUser(string.Format("Projection has failed to '{0}'", selectedDevice.Name), NotifyType.ErrorMessage);
00172                         // Set status to Failed
00173                         picker.SetDisplayStatus(args.SelectedDevice, "Connection Failed", DevicePickerDisplayStatusOptions.ShowRetryButton);
00174                     }
00175                 }
00176                 catch (Exception)
00177                 {
00178                     rootPage.NotifyUser(string.Format("Projection has failed to '{0}'", selectedDevice.Name), NotifyType.ErrorMessage);
00179                     // Set status to Failed
00180                     try { picker.SetDisplayStatus(args.SelectedDevice, "Connection Failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { }
00181                 }
00182                 }
00183                 catch (Exception ex)
00184                 {
00185                     UnhandledExceptionPage.ShowUnhandledException(ex);
00186                 }
00187             });
00188         }
00189         private async void Picker_DevicePickerDismissed(DevicePicker sender, object args)
00190         {
00191             //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
00192             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00193             {
00194                 if (activeDevice == null)
00195                 {
00196                     player.Play();
00197                 }
00198             });
00199         }
00200         private async void Picker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args)
00201         {
00202             //Casting must occur from the UI thread.  This dispatches the casting calls to the UI thread.
00203             await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00204             {
00205                 rootPage.NotifyUser("Disconnect Button clicked", NotifyType.StatusMessage);
00206                 //Update the display status for the selected device.
00207                 sender.SetDisplayStatus(args.Device, "Disconnecting", DevicePickerDisplayStatusOptions.ShowProgress);
00208
00209                 if (this.pvb.ProjectedPage != null)
00210                     this.pvb.ProjectedPage.StopProjecting();
00211
00212                 //Update the display status for the selected device.
00213                 sender.SetDisplayStatus(args.Device, "Disconnected", DevicePickerDisplayStatusOptions.None);
00214                 rootPage.NotifyUser("Disconnected", NotifyType.StatusMessage);
00215
00216                 // Set the active device variables to null
00217                 activeDevice = null;
00218             });
00219         }
00220
00221         private async void Pvb_ProjectionStopping(object sender, EventArgs e)
00222         {
00223             ProjectionViewBroker broker = sender as ProjectionViewBroker;
00224
00225             TimeSpan position;
00226             Uri source = null;
00227
00228             await broker.ProjectedPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00229             {
00230                 position = broker.ProjectedPage.Player.Position;
00231                 source = broker.ProjectedPage.Player.Source;
00232             });
00233
00234             await rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
00235             {
00236                 rootPage.NotifyUser("Resuming playback on the first screen", NotifyType.StatusMessage);
00237                 this.player.Source = source;
00238
00239                 this.player.Position = position;
00240                 this.player.Play();
00241                 rootPage.ProjectionViewPageControl = null;
00242             });
00243         }
00244
00245         #region MediaElement Status Methods
00246         private void Player_CurrentStateChanged(object sender, RoutedEventArgs e)
00247         {
00248             // Update status
00249             rootPage.NotifyUser(string.Format("{0} '{1}'", this.player.CurrentState, video.Title), NotifyType.StatusMessage);
00250         }
00251         private void Player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
00252         {
00253             rootPage.NotifyUser(string.Format("Failed to load '{0}'", video.Title), NotifyType.ErrorMessage);
00254         }
00255         private void Player_MediaOpened(object sender, RoutedEventArgs e)
00256         {
00257             rootPage.NotifyUser(string.Format("Openend '{0}'", video.Title), NotifyType.StatusMessage);
00258
00259             player.Play();
00260         }
00261
00262         #endregion
00263
00264         protected override void OnNavigatedTo(NavigationEventArgs e)
00265         {
00266             rootPage = MainPage.Current;
00267         }
00268     }
00269 }
Generated on Fri Nov 15 2024 22:17:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlTailoredMultipleViews/cs/TailoredMultipleViews/DisplaySizeHelper/pch.h Source File

  • XamlTailoredMultipleViews
  • cs
  • TailoredMultipleViews
  • DisplaySizeHelper

pch.h

Go to the documentation of this file.
00001 ﻿#pragma once
00002
00003 #include <collection.h>
00004 #include <ppltasks.h>
Generated on Fri Nov 15 2024 22:17:08 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleCommunication/cpp/SampleConfiguration.h Source File

  • SimpleCommunication
  • cpp

SampleConfiguration.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "pch.h"
00014
00015 namespace SDKTemplate
00016 {
00017     value struct Scenario;
00018
00019     partial ref class MainPage
00020     {
00021     internal:
00022         static property Platform::String^ FEATURE_NAME
00023         {
00024             Platform::String^ get()
00025             {
00026                 return "Simple Communication";
00027             }
00028         }
00029
00030         static property Platform::Array<Scenario>^ scenarios
00031         {
00032             Platform::Array<Scenario>^ get()
00033             {
00034                 return scenariosInner;
00035             }
00036         }
00037
00038         static void EnsureExtensionRegistration()
00039         {
00040             if (mediaExtensionManager == nullptr)
00041             {
00042                 mediaExtensionManager = ref new Windows::Media::MediaExtensionManager();
00043                 mediaExtensionManager->RegisterSchemeHandler("Microsoft.Samples.SimpleCommunication.StspSchemeHandler", "stsp:");
00044             }
00045         }
00046
00047     private:
00048         static Platform::Array<Scenario>^ scenariosInner;
00049         static Windows::Media::MediaExtensionManager^ mediaExtensionManager;
00050     };
00051
00052     public value struct Scenario
00053     {
00054         Platform::String^ Title;
00055         Platform::String^ ClassName;
00056     };
00057 }
Generated on Fri Nov 15 2024 22:17:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BarcodeScanner/cs/SampleConfiguration.cs Source File

  • BarcodeScanner
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using System.Threading.Tasks;
00015 using Windows.Devices.PointOfService;
00016 using Windows.Security.Cryptography;
00017 using Windows.Storage.Streams;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Data;
00021
00022 namespace SDKTemplate
00023 {
00024     public partial class MainPage : Page
00025     {
00026         public const string FEATURE_NAME = "Barcode Scanner";
00027
00028         List<Scenario> scenarios = new List<Scenario>
00029         {
00030             new Scenario() { Title = "DataReceived event", ClassType = typeof(Scenario1_BasicFunctionality) },
00031             new Scenario() { Title = "Release/Retain functionality", ClassType = typeof(Scenario2_MultipleScanners) },
00032             new Scenario() { Title = "Active Symbologies", ClassType = typeof(Scenario3_ActiveSymbologies) },
00033             new Scenario() { Title = "Symbology Attributes", ClassType = typeof(Scenario4_SymbologyAttributes) },
00034             new Scenario() { Title = "Displaying a Barcode Preview", ClassType = typeof(Scenario5_DisplayingBarcodePreview) },
00035         };
00036     }
00037
00038     public class Scenario
00039     {
00040         public string Title { get; set; }
00041         public Type ClassType { get; set; }
00042     }
00043
00044     public partial class DeviceHelpers
00045     {
00046         public static async Task<BarcodeScanner> GetFirstBarcodeScannerAsync(PosConnectionTypes connectionTypes = PosConnectionTypes.All)
00047         {
00048             return await DeviceHelpers.GetFirstDeviceAsync(BarcodeScanner.GetDeviceSelector(connectionTypes), async (id) => await BarcodeScanner.FromIdAsync(id));
00049         }
00050     }
00051
00052     public partial class DataHelpers
00053     {
00054         public static string GetDataString(IBuffer data)
00055         {
00056             if (data == null)
00057             {
00058                 return "No data";
00059             }
00060
00061             // Just to show that we have the raw data, we'll print the value of the bytes.
00062             // Arbitrarily limit the number of bytes printed to 20 so the UI isn't overloaded.
00063             string result = CryptographicBuffer.EncodeToHexString(data);
00064             if (result.Length > 40)
00065             {
00066                 result = result.Substring(0, 40) + "...";
00067             }
00068             return result;
00069         }
00070
00071         public static string GetDataLabelString(IBuffer data, uint scanDataType)
00072         {
00073             // Only certain data types contain encoded text.
00074             // To keep this simple, we'll just decode a few of them.
00075             if (data == null)
00076             {
00077                 return "No data";
00078             }
00079
00080             // This is not an exhaustive list of symbologies that can be converted to a string.
00081             if (scanDataType == BarcodeSymbologies.Upca ||
00082                 scanDataType == BarcodeSymbologies.UpcaAdd2 ||
00083                 scanDataType == BarcodeSymbologies.UpcaAdd5 ||
00084                 scanDataType == BarcodeSymbologies.Upce ||
00085                 scanDataType == BarcodeSymbologies.UpceAdd2 ||
00086                 scanDataType == BarcodeSymbologies.UpceAdd5 ||
00087                 scanDataType == BarcodeSymbologies.Ean8 ||
00088                 scanDataType == BarcodeSymbologies.TfStd ||
00089                 scanDataType == BarcodeSymbologies.OcrA ||
00090                 scanDataType == BarcodeSymbologies.OcrB)
00091             {
00092                 // The UPC, EAN8, and 2 of 5 families encode the digits 0..9
00093                 // which are then sent to the app in a UTF8 string (like "01234").
00094                 return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, data);
00095             }
00096
00097             // Some other symbologies (typically 2-D symbologies) contain binary data that
00098             // should not be converted to text.
00099             return string.Format("Decoded data unavailable. Raw label data: {0}", DataHelpers.GetDataString(data));
00100         }
00101     }
00102
00103     public partial class BindingHelpers
00104     {
00105         // Inverters for binding.
00106         public static bool Not(bool value) => !value;
00107         public static Visibility CollapsedIf(bool value) => value ? Visibility.Collapsed : Visibility.Visible;
00108     }
00109
00110     /// <summary>
00111     /// This class is used for data-binding.
00112     /// </summary>
00113     public class BarcodeScannerInfo
00114     {
00115         public BarcodeScannerInfo(String deviceName, String deviceId)
00116         {
00117             DeviceName = deviceName;
00118             DeviceId = deviceId;
00119         }
00120
00121         public String Name => $"{DeviceName} ({DeviceId})";
00122         public String DeviceId { get; private set; }
00123         private string DeviceName;
00124     }
00125
00126     /// <summary>
00127     /// This class is used for data-binding.
00128     /// </summary>
00129     public class SymbologyListEntry
00130     {
00131         public SymbologyListEntry(uint symbologyId, bool symbologyEnabled = true)
00132         {
00133             Id = symbologyId;
00134             IsEnabled = symbologyEnabled;
00135         }
00136
00137         public uint Id { get; private set; }
00138         public bool IsEnabled { get; set; }
00139         public String Name => BarcodeSymbologies.GetName(Id);
00140     }
00141 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PresenceSensor/cppwinrt/Scenario3_Choosing.h Source File

  • PresenceSensor
  • cppwinrt

Scenario3_Choosing.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario3_Choosing.g.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario3_Choosing : Scenario3_ChoosingT<Scenario3_Choosing>
00019     {
00020         Scenario3_Choosing();
00021
00022         void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
00023
00024         // These methods are public so they can be called by binding.
00025         fire_and_forget ScenarioPick_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00026         void ScenarioStart_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00027         void ScenarioStop_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00028         fire_and_forget ScenarioReadSelected_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00029
00030     private:
00031         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00032         Windows::Devices::Enumeration::DeviceWatcher watcher{ nullptr };
00033
00034         fire_and_forget OnHumanPresenceSensorAdded(Windows::Devices::Enumeration::DeviceWatcher const& sender, Windows::Devices::Enumeration::DeviceInformation deviceInfo);
00035         fire_and_forget OnHumanPresenceSensorRemoved(Windows::Devices::Enumeration::DeviceWatcher const& sender, Windows::Devices::Enumeration::DeviceInformationUpdate update);
00036         fire_and_forget OnHumanPresenceSensorUpdated(Windows::Devices::Enumeration::DeviceWatcher const& sender, Windows::Devices::Enumeration::DeviceInformationUpdate update);
00037         fire_and_forget OnHumanPresenceSensorEnumerationCompleted(Windows::Devices::Enumeration::DeviceWatcher const& sender, Windows::Foundation::IInspectable const& e);
00038
00039         Windows::Foundation::IAsyncAction ReadOneReadingFromSensorAsync(Windows::Devices::Enumeration::DeviceInformation deviceInfo);
00040     };
00041 }
00042
00043 namespace winrt::SDKTemplate::factory_implementation
00044 {
00045     struct Scenario3_Choosing : Scenario3_ChoosingT<Scenario3_Choosing, implementation::Scenario3_Choosing>
00046     {
00047     };
00048 }
Generated on Fri Nov 15 2024 22:20:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

NoOp< T > Member List

This is the complete list of members for NoOp< T >, including all inherited members.
operator()(T &t) NoOp< T > [inline]
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicFaceTracking/cpp/Common/DeviceResources.cpp Source File

  • HolographicFaceTracking
  • cpp
  • Common

DeviceResources.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "DeviceResources.h"
00014 #include "DirectXHelper.h"
00015
00016 #include <Collection.h>
00017 #include <windows.graphics.directx.direct3d11.interop.h>
00018
00019 using namespace D2D1;
00020 using namespace Microsoft::WRL;
00021 using namespace Windows::Graphics::DirectX::Direct3D11;
00022 using namespace Windows::Graphics::Display;
00023 using namespace Windows::Graphics::Holographic;
00024
00025 // Constructor for DeviceResources.
00026 DX::DeviceResources::DeviceResources()
00027 {
00028     CreateDeviceIndependentResources();
00029 }
00030
00031 // Configures resources that don't depend on the Direct3D device.
00032 void DX::DeviceResources::CreateDeviceIndependentResources()
00033 {
00034     // Initialize Direct2D resources.
00035     D2D1_FACTORY_OPTIONS options {};
00036
00037 #if defined(_DEBUG)
00038     // If the project is in a debug build, enable Direct2D debugging via SDK Layers.
00039     options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
00040 #endif
00041
00042     // Initialize the Direct2D Factory.
00043     DX::ThrowIfFailed(
00044         D2D1CreateFactory(
00045             D2D1_FACTORY_TYPE_SINGLE_THREADED,
00046             __uuidof(ID2D1Factory2),
00047             &options,
00048             &m_d2dFactory
00049             )
00050         );
00051
00052     // Initialize the DirectWrite Factory.
00053     DX::ThrowIfFailed(
00054         DWriteCreateFactory(
00055             DWRITE_FACTORY_TYPE_SHARED,
00056             __uuidof(IDWriteFactory2),
00057             &m_dwriteFactory
00058             )
00059         );
00060
00061     // Initialize the Windows Imaging Component (WIC) Factory.
00062     DX::ThrowIfFailed(
00063         CoCreateInstance(
00064             CLSID_WICImagingFactory2,
00065             nullptr,
00066             CLSCTX_INPROC_SERVER,
00067             IID_PPV_ARGS(&m_wicFactory)
00068             )
00069         );
00070 }
00071
00072 void DX::DeviceResources::SetHolographicSpace(HolographicSpace^ holographicSpace)
00073 {
00074     // Cache the holographic space. Used to re-initalize during device-lost scenarios.
00075     m_holographicSpace = holographicSpace;
00076
00077     InitializeUsingHolographicSpace();
00078 }
00079
00080 void DX::DeviceResources::InitializeUsingHolographicSpace()
00081 {
00082     // The holographic space might need to determine which adapter supports
00083     // holograms, in which case it will specify a non-zero PrimaryAdapterId.
00084     LUID id =
00085     {
00086         m_holographicSpace->PrimaryAdapterId.LowPart,
00087         m_holographicSpace->PrimaryAdapterId.HighPart
00088     };
00089
00090     // When a primary adapter ID is given to the app, the app should find
00091     // the corresponding DXGI adapter and use it to create Direct3D devices
00092     // and device contexts. Otherwise, there is no restriction on the DXGI
00093     // adapter the app can use.
00094     if ((id.HighPart != 0) && (id.LowPart != 0))
00095     {
00096         UINT createFlags = 0;
00097 #ifdef DEBUG
00098         if (DX::SdkLayersAvailable())
00099         {
00100             createFlags |= DXGI_CREATE_FACTORY_DEBUG;
00101         }
00102 #endif
00103         // Create the DXGI factory.
00104         ComPtr<IDXGIFactory1> dxgiFactory;
00105         DX::ThrowIfFailed(
00106             CreateDXGIFactory2(
00107                 createFlags,
00108                 IID_PPV_ARGS(&dxgiFactory)
00109                 )
00110             );
00111         ComPtr<IDXGIFactory4> dxgiFactory4;
00112         DX::ThrowIfFailed(dxgiFactory.As(&dxgiFactory4));
00113
00114         // Retrieve the adapter specified by the holographic space.
00115         DX::ThrowIfFailed(
00116             dxgiFactory4->EnumAdapterByLuid(
00117                 id,
00118                 IID_PPV_ARGS(&m_dxgiAdapter)
00119                 )
00120             );
00121     }
00122     else
00123     {
00124         m_dxgiAdapter.Reset();
00125     }
00126
00127     CreateDeviceResources();
00128
00129     m_holographicSpace->SetDirect3D11Device(m_d3dInteropDevice);
00130 }
00131
00132 // Configures the Direct3D device, and stores handles to it and the device context.
00133 void DX::DeviceResources::CreateDeviceResources()
00134 {
00135     // This flag adds support for surfaces with a different color channel ordering
00136     // than the default. It is required for compatibility with Direct2D.
00137     UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
00138
00139 #if defined(_DEBUG)
00140     if (DX::SdkLayersAvailable())
00141     {
00142         // If the project is in a debug build, enable debugging via SDK Layers with this flag.
00143         creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
00144     }
00145 #endif
00146
00147     // This array defines the set of DirectX hardware feature levels this app will support.
00148     // Note the ordering should be preserved.
00149     // Note that HoloLens supports feature level 11.1. The HoloLens emulator is also capable
00150     // of running on graphics cards starting with feature level 10.0.
00151     D3D_FEATURE_LEVEL featureLevels [] =
00152     {
00153         D3D_FEATURE_LEVEL_12_1,
00154         D3D_FEATURE_LEVEL_12_0,
00155         D3D_FEATURE_LEVEL_11_1,
00156         D3D_FEATURE_LEVEL_11_0,
00157         D3D_FEATURE_LEVEL_10_1,
00158         D3D_FEATURE_LEVEL_10_0
00159     };
00160
00161     // Create the Direct3D 11 device object and a corresponding context.
00162     ComPtr<ID3D11Device> device;
00163     ComPtr<ID3D11DeviceContext> context;
00164
00165     const HRESULT hr = D3D11CreateDevice(
00166         m_dxgiAdapter.Get(),        // Either nullptr, or the primary adapter determined by Windows Holographic.
00167         D3D_DRIVER_TYPE_HARDWARE,   // Create a device using the hardware graphics driver.
00168         0,                          // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
00169         creationFlags,              // Set debug and Direct2D compatibility flags.
00170         featureLevels,              // List of feature levels this app can support.
00171         ARRAYSIZE(featureLevels),   // Size of the list above.
00172         D3D11_SDK_VERSION,          // Always set this to D3D11_SDK_VERSION for Windows Runtime apps.
00173         &device,                    // Returns the Direct3D device created.
00174         &m_d3dFeatureLevel,         // Returns feature level of device created.
00175         &context                    // Returns the device immediate context.
00176         );
00177
00178     if (FAILED(hr))
00179     {
00180         // If the initialization fails, fall back to the WARP device.
00181         // For more information on WARP, see:
00182         // http://go.microsoft.com/fwlink/?LinkId=286690
00183         DX::ThrowIfFailed(
00184             D3D11CreateDevice(
00185                 nullptr,              // Use the default DXGI adapter for WARP.
00186                 D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
00187                 0,
00188                 creationFlags,
00189                 featureLevels,
00190                 ARRAYSIZE(featureLevels),
00191                 D3D11_SDK_VERSION,
00192                 &device,
00193                 &m_d3dFeatureLevel,
00194                 &context
00195                 )
00196             );
00197     }
00198
00199     // Store pointers to the Direct3D device and immediate context.
00200     DX::ThrowIfFailed(
00201         device.As(&m_d3dDevice)
00202         );
00203
00204     DX::ThrowIfFailed(
00205         context.As(&m_d3dContext)
00206         );
00207
00208     // Acquire the DXGI interface for the Direct3D device.
00209     ComPtr<IDXGIDevice3> dxgiDevice;
00210     DX::ThrowIfFailed(
00211         m_d3dDevice.As(&dxgiDevice)
00212         );
00213
00214     // Wrap the native device using a WinRT interop object.
00215     m_d3dInteropDevice = CreateDirect3DDevice(dxgiDevice.Get());
00216
00217     // Cache the DXGI adapter.
00218     // This is for the case of no preferred DXGI adapter, or fallback to WARP.
00219     ComPtr<IDXGIAdapter> dxgiAdapter;
00220     DX::ThrowIfFailed(
00221         dxgiDevice->GetAdapter(&dxgiAdapter)
00222         );
00223     DX::ThrowIfFailed(
00224         dxgiAdapter.As(&m_dxgiAdapter)
00225         );
00226
00227     // Check for device support for the optional feature that allows setting the render target array index from the vertex shader stage.
00228     D3D11_FEATURE_DATA_D3D11_OPTIONS3 options;
00229     m_d3dDevice->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS3, &options, sizeof(options));
00230     if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer)
00231     {
00232         m_supportsVprt = true;
00233     }
00234 }
00235
00236 // Validates the back buffer for each HolographicCamera and recreates
00237 // resources for back buffers that have changed.
00238 // Locks the set of holographic camera resources until the function exits.
00239 void DX::DeviceResources::EnsureCameraResources(
00240     HolographicFrame^ frame,
00241     HolographicFramePrediction^ prediction)
00242 {
00243     UseHolographicCameraResources<void>([this, frame, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00244     {
00245         for (HolographicCameraPose^ pose : prediction->CameraPoses)
00246         {
00247             HolographicCameraRenderingParameters^ renderingParameters = frame->GetRenderingParameters(pose);
00248             CameraResources* pCameraResources = cameraResourceMap[pose->HolographicCamera->Id].get();
00249
00250             pCameraResources->CreateResourcesForBackBuffer(this, renderingParameters);
00251         }
00252     });
00253 }
00254
00255 // Prepares to allocate resources and adds resource views for a camera.
00256 // Locks the set of holographic camera resources until the function exits.
00257 void DX::DeviceResources::AddHolographicCamera(HolographicCamera^ camera)
00258 {
00259     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00260     {
00261         cameraResourceMap[camera->Id] = std::make_unique<CameraResources>(camera);
00262     });
00263 }
00264
00265 // Deallocates resources for a camera and removes the camera from the set.
00266 // Locks the set of holographic camera resources until the function exits.
00267 void DX::DeviceResources::RemoveHolographicCamera(HolographicCamera^ camera)
00268 {
00269     UseHolographicCameraResources<void>([this, camera](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00270     {
00271         CameraResources* pCameraResources = cameraResourceMap[camera->Id].get();
00272
00273         if (pCameraResources != nullptr)
00274         {
00275             pCameraResources->ReleaseResourcesForBackBuffer(this);
00276             cameraResourceMap.erase(camera->Id);
00277         }
00278     });
00279 }
00280
00281 // Recreate all device resources and set them back to the current state.
00282 // Locks the set of holographic camera resources until the function exits.
00283 void DX::DeviceResources::HandleDeviceLost()
00284 {
00285     if (m_deviceNotify != nullptr)
00286     {
00287         m_deviceNotify->OnDeviceLost();
00288     }
00289
00290     UseHolographicCameraResources<void>([this](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00291     {
00292         for (auto& pair : cameraResourceMap)
00293         {
00294             CameraResources* pCameraResources = pair.second.get();
00295             pCameraResources->ReleaseResourcesForBackBuffer(this);
00296         }
00297     });
00298
00299     InitializeUsingHolographicSpace();
00300
00301     if (m_deviceNotify != nullptr)
00302     {
00303         m_deviceNotify->OnDeviceRestored();
00304     }
00305 }
00306
00307 // Register our DeviceNotify to be informed on device lost and creation.
00308 void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify)
00309 {
00310     m_deviceNotify = deviceNotify;
00311 }
00312
00313 // Call this method when the app suspends. It provides a hint to the driver that the app
00314 // is entering an idle state and that temporary buffers can be reclaimed for use by other apps.
00315 void DX::DeviceResources::Trim()
00316 {
00317     m_d3dContext->ClearState();
00318
00319     ComPtr<IDXGIDevice3> dxgiDevice;
00320     DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice));
00321     dxgiDevice->Trim();
00322 }
00323
00324 // Present the contents of the swap chain to the screen.
00325 // Locks the set of holographic camera resources until the function exits.
00326 void DX::DeviceResources::Present(HolographicFrame^ frame)
00327 {
00328     // By default, the PresentUsingCurrentPrediction method waits for the frame to finish
00329     // before it returns. Holographic apps should wait for the previous frame to finish
00330     // before starting work on a new frame. This allows for better results from
00331     // holographic frame predictions.
00332     HolographicFramePresentResult presentResult = frame->PresentUsingCurrentPrediction();
00333
00334     HolographicFramePrediction^ prediction = frame->CurrentPrediction;
00335     UseHolographicCameraResources<void>([this, prediction](std::map<UINT32, std::unique_ptr<CameraResources>>& cameraResourceMap)
00336     {
00337         for (auto cameraPose : prediction->CameraPoses)
00338         {
00339             // This represents the device-based resources for a HolographicCamera.
00340             DX::CameraResources* pCameraResources = cameraResourceMap[cameraPose->HolographicCamera->Id].get();
00341
00342             // Discard the contents of the render target.
00343             // This is a valid operation only when the existing contents will be
00344             // entirely overwritten. If dirty or scroll rects are used, this call
00345             // should be removed.
00346             m_d3dContext->DiscardView(pCameraResources->GetBackBufferRenderTargetView());
00347
00348             // Discard the contents of the depth stencil.
00349             m_d3dContext->DiscardView(pCameraResources->GetDepthStencilView());
00350         }
00351     });
00352
00353     // The PresentUsingCurrentPrediction method detects when the graphics device
00354     // changes or becomes invalid. When this happens, it is considered a Direct3D
00355     // device lost scenario.
00356     if (presentResult == HolographicFramePresentResult::DeviceRemoved)
00357     {
00358         // The Direct3D device, context, and resources should be recreated.
00359         HandleDeviceLost();
00360     }
00361 }
Generated on Fri Nov 15 2024 22:16:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraVideoStabilization/cpp/pch.h Source File

  • CameraVideoStabilization
  • cpp

pch.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include <collection.h>
00015 #include <ppltasks.h>
00016
00017 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Projection/cpp/pch.h Source File

  • Projection
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlContextMenu/cpp/Scenario2.xaml.h Source File

  • XamlContextMenu
  • cpp

Scenario2.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario2.g.h"
00015 #include "MainPage.xaml.h"
00016 #include "SampleDataModel.h"
00017
00018 namespace SDKTemplate
00019 {
00020     [Windows::Foundation::Metadata::WebHostHidden]
00021     public ref class Scenario2 sealed
00022     {
00023     public:
00024         Scenario2();
00025
00026     property Windows::Foundation::Collections::IVector<SampleDataModel^>^ AllItems;
00027
00028     private:
00029         MainPage^ rootPage = MainPage::Current;
00030
00031         SampleDataModel^ GetDataModelForCurrentListViewFlyout();
00032         void OpenMenuItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00033         void PrintMenuItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00034         void DeleteMenuItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00035     };
00036 }
Generated on Fri Nov 15 2024 22:18:00 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCoordinateMapper/cpp/App.cpp Source File

  • CameraStreamCoordinateMapper
  • cpp

App.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "App.h"
00014
00015 #include "CameraStreamCoordinateMapperMain.h"
00016
00017 using namespace CameraStreamCoordinateMapper;
00018
00019 using namespace concurrency;
00020 using namespace Windows::ApplicationModel;
00021 using namespace Windows::ApplicationModel::Core;
00022 using namespace Windows::ApplicationModel::Activation;
00023 using namespace Windows::UI::Core;
00024 using namespace Windows::UI::Input;
00025 using namespace Windows::System;
00026 using namespace Windows::Foundation;
00027 using namespace Windows::Graphics::Display;
00028
00029 // The main function is only used to initialize our IFrameworkView class.
00030 [Platform::MTAThread]
00031 int main(Platform::Array<Platform::String^>^)
00032 {
00033     auto direct3DApplicationSource = ref new Direct3DApplicationSource();
00034     CoreApplication::Run(direct3DApplicationSource);
00035     return 0;
00036 }
00037
00038 IFrameworkView^ Direct3DApplicationSource::CreateView()
00039 {
00040     return ref new App();
00041 }
00042
00043 App::App() :
00044     m_windowClosed(false),
00045     m_windowVisible(true)
00046 {
00047 }
00048
00049 // The first method called when the IFrameworkView is being created.
00050 void App::Initialize(CoreApplicationView^ applicationView)
00051 {
00052     // Register event handlers for app lifecycle. This example includes Activated, so that we
00053     // can make the CoreWindow active and start rendering on the window.
00054     applicationView->Activated +=
00055         ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated);
00056
00057     CoreApplication::Suspending +=
00058         ref new EventHandler<SuspendingEventArgs^>(this, &App::OnSuspending);
00059
00060     CoreApplication::Resuming +=
00061         ref new EventHandler<Platform::Object^>(this, &App::OnResuming);
00062
00063     // At this point we have access to the device.
00064     // We can create the device-dependent resources.
00065     m_deviceResources = std::make_shared<DX::DeviceResources>();
00066 }
00067
00068 // Called when the CoreWindow object is created (or re-created).
00069 void App::SetWindow(CoreWindow^ window)
00070 {
00071     window->SizeChanged +=
00072         ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &App::OnWindowSizeChanged);
00073
00074     window->VisibilityChanged +=
00075         ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &App::OnVisibilityChanged);
00076
00077     window->Closed +=
00078         ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::OnWindowClosed);
00079
00080     DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
00081
00082     currentDisplayInformation->DpiChanged +=
00083         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDpiChanged);
00084
00085     currentDisplayInformation->OrientationChanged +=
00086         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnOrientationChanged);
00087
00088     DisplayInformation::DisplayContentsInvalidated +=
00089         ref new TypedEventHandler<DisplayInformation^, Object^>(this, &App::OnDisplayContentsInvalidated);
00090
00091     m_deviceResources->SetWindow(window);
00092 }
00093
00094 // Initializes scene resources, or loads a previously saved app state.
00095 void App::Load(Platform::String^ entryPoint)
00096 {
00097     if (m_main == nullptr)
00098     {
00099         m_main = std::make_unique<CameraStreamCoordinateMapperMain>(m_deviceResources);
00100     }
00101 }
00102
00103 // This method is called after the window becomes active.
00104 void App::Run()
00105 {
00106     while (!m_windowClosed)
00107     {
00108         if (m_windowVisible)
00109         {
00110             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
00111
00112             m_main->Update();
00113
00114             if (m_main->Render())
00115             {
00116                 m_deviceResources->Present();
00117             }
00118         }
00119         else
00120         {
00121             CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
00122         }
00123     }
00124 }
00125
00126 // Required for IFrameworkView.
00127 // Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
00128 // class is torn down while the app is in the foreground.
00129 void App::Uninitialize()
00130 {
00131 }
00132
00133 // Application lifecycle event handlers.
00134
00135 void App::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
00136 {
00137     // Run() won't start until the CoreWindow is activated.
00138     CoreWindow::GetForCurrentThread()->Activate();
00139 }
00140
00141 void App::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
00142 {
00143     // Save app state asynchronously after requesting a deferral. Holding a deferral
00144     // indicates that the application is busy performing suspending operations. Be
00145     // aware that a deferral may not be held indefinitely. After about five seconds,
00146     // the app will be forced to exit.
00147     SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
00148
00149     create_task([this, deferral]
00150     {
00151         m_deviceResources->Trim();
00152
00153         return m_main->OnSuspendingAsync().then([deferral] {
00154             deferral->Complete();
00155         });
00156     });
00157 }
00158
00159 void App::OnResuming(Platform::Object^ sender, Platform::Object^ args)
00160 {
00161     // Restore any data or state that was unloaded on suspend. By default, data
00162     // and state are persisted when resuming from suspend. Note that this event
00163     // does not occur if the app was previously terminated.
00164
00165     m_main->OnResuming();
00166 }
00167
00168 // Window event handlers.
00169
00170 void App::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
00171 {
00172     m_deviceResources->SetLogicalSize(Size(sender->Bounds.Width, sender->Bounds.Height));
00173     m_main->CreateWindowSizeDependentResources();
00174 }
00175
00176 void App::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
00177 {
00178     m_windowVisible = args->Visible;
00179 }
00180
00181 void App::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
00182 {
00183     m_windowClosed = true;
00184 }
00185
00186 // DisplayInformation event handlers.
00187
00188 void App::OnDpiChanged(DisplayInformation^ sender, Object^ args)
00189 {
00190     // Note: The value for LogicalDpi retrieved here may not match the effective DPI of the app
00191     // if it is being scaled for high resolution devices. Once the DPI is set on DeviceResources,
00192     // you should always retrieve it using the GetDpi method.
00193     // See DeviceResources.cpp for more details.
00194     m_deviceResources->SetDpi(sender->LogicalDpi);
00195     m_main->CreateWindowSizeDependentResources();
00196 }
00197
00198 void App::OnOrientationChanged(DisplayInformation^ sender, Object^ args)
00199 {
00200     m_deviceResources->SetCurrentOrientation(sender->CurrentOrientation);
00201     m_main->CreateWindowSizeDependentResources();
00202 }
00203
00204 void App::OnDisplayContentsInvalidated(DisplayInformation^ sender, Object^ args)
00205 {
00206     m_deviceResources->ValidateDevice();
00207 }
Generated on Fri Nov 15 2024 22:18:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WRLOutOfProcessWinRTComponent/cpp/cpp/Scenario4_CustomExceptionWRL.xaml.h Source File

  • WRLOutOfProcessWinRTComponent
  • cpp
  • cpp

Scenario4_CustomExceptionWRL.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 //
00005 //*********************************************************
00006
00007 #pragma once
00008 #include "Scenario4_CustomExceptionWRL.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     namespace WRLOutOfProcessWinRTComponent
00013     {
00014         public ref class CustomExceptionWRL sealed
00015         {
00016         public:
00017             CustomExceptionWRL();
00018
00019         private:
00020             void Start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00021         };
00022     }
00023 }
Generated on Fri Nov 15 2024 22:21:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

OtherScenarios Member List

This is the complete list of members for OtherScenarios, including all inherited members.
ClearOutput() | OtherScenarios | [private]
ClearOutputButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | OtherScenarios |
DisplayFormats() | OtherScenarios | [private]
EmptyClipboardButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | OtherScenarios |
OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const &e) | OtherScenarios |
OtherScenarios() | OtherScenarios |
RegisterClipboardContentChanged_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | OtherScenarios |
registerContentChanged | OtherScenarios | [private, static]
ShowFormatButton_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | OtherScenarios |
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SpatialInteractionSource/cpp/Content/Whiteboard.cpp Source File

  • SpatialInteractionSource
  • cpp
  • Content

Whiteboard.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "Whiteboard.h"
00003 #include "..\Common\DirectXHelper.h"
00004
00005 using namespace HolographicPaint;
00006 using namespace DirectX;
00007 using namespace Windows::UI;
00008 using namespace Windows::Foundation::Numerics;
00009
00010 const float WhiteboardDepth = .005f;
00011
00012 Whiteboard::Whiteboard(float width, float height, float3 position)
00013     : m_width(width), m_height(height), m_position(position)
00014 {
00015     const XMMATRIX modelRotation = XMMatrixIdentity();
00016
00017     const XMMATRIX modelScale = XMMatrixScaling(width, height, WhiteboardDepth);
00018
00019     const XMMATRIX modelTranslation = XMMatrixTranslationFromVector(XMLoadFloat3(&position));
00020
00021     // Multiply to get the transform matrix.
00022     // Note that this transform does not enforce a particular coordinate system. The calling
00023     // class is responsible for rendering this content in a consistent manner.
00024     const XMMATRIX modelTransform = modelScale * modelRotation * modelTranslation;
00025
00026     // The view and projection matrices are provided by the system; they are associated
00027     // with holographic cameras, and updated on a per-camera basis.
00028     // Here, we provide the model transform for the sample hologram. The model transform
00029     // matrix is transposed to prepare it for the shader.
00030     XMStoreFloat4x4(&m_modelConstantBufferData.model, XMMatrixTranspose(modelTransform));
00031
00032     m_modelConstantBufferData.color = DX::GetDXColor(ColorHelper::FromArgb(0x40, 0xFf, 0xFF, 0xFF));
00033
00034
00035     XMFLOAT3 boundingPosition(position.x, position.y, position.z);
00036     XMFLOAT3 boundingExtents(width / 2.0f, height / 2.0f, WhiteboardDepth / 2.0f);
00037     m_boundingBox = BoundingBox(boundingPosition, boundingExtents);
00038 }
00039
00040 void Whiteboard::Update(ID3D11DeviceContext* pDeviceContext)
00041 {
00042     // Whiteboard do not move and hence update do not have to do anything special
00043 }
00044
00045 void Whiteboard::Render(ID3D11DeviceContext* pDeviceContext, IRenderer* pRenderingHelper)
00046 {
00047     pRenderingHelper->SetConstantBuffer(&m_modelConstantBufferData);
00048     pRenderingHelper->DrawCube();
00049 }
00050
00051 bool Whiteboard::Intersects(const float3& origin, const float3& direction, float* distance)
00052 {
00053     XMVECTOR originVector = XMLoadFloat3(&origin);
00054     XMVECTOR directionVector = XMLoadFloat3(&direction);
00055     return m_boundingBox.Intersects(originVector, directionVector, *distance);
00056 }
00057
00058 bool Whiteboard::IsValidPosition(const Windows::Foundation::Numerics::float3& position)
00059 {
00060     // As the whiteboard is axis-aligned and we do not take z into count, the test is simple
00061     return fabs(position.x - m_position.x) <= m_width / 2.0f && fabs(position.y - m_position.y) <= m_height / 2.0f;
00062 }
Generated on Fri Nov 15 2024 22:21:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraGetPreviewFrame/cpp/App.xaml.cpp Source File

  • CameraGetPreviewFrame
  • cpp

App.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MainPage.xaml.h"
00014
00015 using namespace CameraGetPreviewFrame;
00016
00017 using namespace Platform;
00018 using namespace Windows::ApplicationModel;
00019 using namespace Windows::ApplicationModel::Activation;
00020 using namespace Windows::Foundation;
00021 using namespace Windows::Foundation::Collections;
00022 using namespace Windows::UI::Xaml;
00023 using namespace Windows::UI::Xaml::Controls;
00024 using namespace Windows::UI::Xaml::Controls::Primitives;
00025 using namespace Windows::UI::Xaml::Data;
00026 using namespace Windows::UI::Xaml::Input;
00027 using namespace Windows::UI::Xaml::Interop;
00028 using namespace Windows::UI::Xaml::Media;
00029 using namespace Windows::UI::Xaml::Navigation;
00030
00031 /// <summary>
00032 /// Initializes the singleton application object.  This is the first line of authored code
00033 /// executed, and as such is the logical equivalent of main() or WinMain().
00034 /// </summary>
00035 App::App()
00036 {
00037     InitializeComponent();
00038 }
00039
00040 /// <summary>
00041 /// Invoked when the application is launched normally by the end user.  Other entry points
00042 /// will be used such as when the application is launched to open a specific file.
00043 /// </summary>
00044 /// <param name="e">Details about the launch request and process.</param>
00045 void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
00046 {
00047
00048 #if _DEBUG
00049         // Show graphics profiling information while debugging.
00050         if (IsDebuggerPresent())
00051         {
00052             // Display the current frame rate counters
00053              DebugSettings->EnableFrameRateCounter = true;
00054         }
00055 #endif
00056
00057     auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
00058
00059     // Do not repeat app initialization when the Window already has content,
00060     // just ensure that the window is active
00061     if (rootFrame == nullptr)
00062     {
00063         // Create a Frame to act as the navigation context and associate it with
00064         // a SuspensionManager key
00065         rootFrame = ref new Frame();
00066
00067         rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed);
00068
00069         if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
00070         {
00071             // Restore the saved session state only when appropriate, scheduling the
00072             // final launch steps after the restore is complete
00073
00074         }
00075
00076         if (rootFrame->Content == nullptr)
00077         {
00078             // When the navigation stack isn't restored navigate to the first page,
00079             // configuring the new page by passing required information as a navigation
00080             // parameter
00081             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00082         }
00083         // Place the frame in the current Window
00084         Window::Current->Content = rootFrame;
00085         // Ensure the current window is active
00086         Window::Current->Activate();
00087     }
00088     else
00089     {
00090         if (rootFrame->Content == nullptr)
00091         {
00092             // When the navigation stack isn't restored navigate to the first page,
00093             // configuring the new page by passing required information as a navigation
00094             // parameter
00095             rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
00096         }
00097         // Ensure the current window is active
00098         Window::Current->Activate();
00099     }
00100 }
00101
00102 /// <summary>
00103 /// Invoked when Navigation to a certain page fails
00104 /// </summary>
00105 /// <param name="sender">The Frame which failed navigation</param>
00106 /// <param name="e">Details about the navigation failure</param>
00107 void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e)
00108 {
00109     throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name);
00110 }
Generated on Fri Nov 15 2024 22:16:43 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ComplexInk/cpp/Renderers/SceneComposer.h Source File

  • ComplexInk
  • cpp
  • Renderers

SceneComposer.h

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 #pragma once
00004
00005 #include "..\Common\DeviceResources.h"
00006 #include "InkRenderer.h"
00007 #include "ShapeRenderer.h"
00008 #include "WindowsNumerics.h"
00009
00010 #define RECT_DELTA  3   // Inflate the invalidate rect to cover borderlines
00011
00012 namespace SDKTemplate
00013 {
00014     class SceneComposer : public IVirtualSurfaceUpdatesCallbackNative
00015     {
00016     public:
00017         SceneComposer() {};
00018         ~SceneComposer();
00019         Windows::UI::Xaml::Media::Imaging::VirtualSurfaceImageSource^ Initialize(
00020             Windows::Foundation::Size sizeContent,
00021             Windows::Foundation::Size sizeViewPort);
00022         // Adds strokes to the collection and calls the renderer to display the new scene
00023         void UpdateInk(Windows::Foundation::Collections::IVectorView<Windows::UI::Input::Inking::InkStroke^>^ strokes);
00024         // Adds shapes to the collection and calls the renderer to display the new scene
00025         void UpdateShape();
00026         // Invalidate the area to be redrawn
00027         void Invalidate(_In_opt_ RECT* pInvalidateRect = nullptr);
00028         // Selects the strokes and call the renderer to update with new drawing attributes
00029         void SelectSceneObjects(Windows::Foundation::Collections::IVector<Windows::Foundation::Point>^ selectionPoints);
00030         // Updates the size of the device resources and updates the scene
00031         void OnViewSizeChanged(Windows::Foundation::Size newSize);
00032         // Unselects all strokes in the scene
00033         void UnselectSceneObjects();
00034         // Destroy cache of objects and clear the renderers
00035         void ClearScene();
00036         // Creates the resources for drawing the lasso
00037         void StartLassoSelection(Windows::Foundation::Point pt);
00038         // Render the lasso rectangle that will select strokes
00039         void DrawLasso(Windows::Foundation::Point pt);
00040         // Erases the stroke that cross the line from prevPt to currPt
00041         void DoErase(Windows::Foundation::Point prevPt, Windows::Foundation::Point currPt);
00042         // Set the current context window's content size
00043         void SetContentSize(Windows::Foundation::Size contentSize) {
00044             if (_deviceResources != nullptr) {
00045                 _deviceResources->SetContentSize(contentSize);
00046             };
00047         };
00048         // Set the current context window's DPI value
00049         void SetDPI(float dpi) {
00050             if (_deviceResources != nullptr) {
00051                 _deviceResources->SetDPI(dpi);
00052             };
00053         };
00054         // Get the current context window's DPI value
00055         float GetDPI() { return (_deviceResources != nullptr) ? _deviceResources->GetDPI() : 0; };
00056         // Set the current context window's content zoom factor
00057         void SetContentZoomFactor(float contentZoomFactor) {
00058             if (_deviceResources != nullptr) {
00059                 _deviceResources->SetContentZoomFactor(contentZoomFactor);
00060             }
00061         };
00062         void Trim() {
00063             if (_deviceResources != nullptr) {
00064                 _deviceResources->Trim();
00065             };
00066         };
00067
00068         void CopySelected();
00069         void CutSelected();
00070         void PasteSelected(Windows::Foundation::Point pastePosition);
00071
00072         // Scene accessors
00073         Windows::Foundation::Rect GetSceneSelectionRect();
00074         bool CanPaste() { return _inkRenderer->GetStrokeContainer()->CanPasteFromClipboard(); };
00075
00076         // Ink Synchronizer
00077         void SetInkSynchronizer(Windows::UI::Input::Inking::InkSynchronizer^ inkSynchronizer) {
00078             _inkSynchronizer = inkSynchronizer;
00079         };
00080
00081         void DoCustomDry();
00082
00083         // IVirtualSurfaceUpdatesCallbackNative
00084         virtual HRESULT STDMETHODCALLTYPE UpdatesNeeded() override;
00085
00086         virtual HRESULT STDMETHODCALLTYPE QueryInterface(
00087             REFIID uuid,
00088             _Outptr_ void** object
00089             ) override;
00090
00091         virtual ULONG STDMETHODCALLTYPE AddRef() override;
00092
00093         virtual ULONG STDMETHODCALLTYPE Release() override;
00094
00095     private:
00096
00097         // Scene object is the base class for ink and shape objects
00098
00099         enum SCENEOBJECT_TYPES {
00100             SOT_Ink = 0, SOT_Shape = 1, SOT_Generic = 2
00101         };
00102
00103         class SceneObject
00104         {
00105         public:
00106             virtual SCENEOBJECT_TYPES getType() { return SCENEOBJECT_TYPES::SOT_Generic; };
00107         };
00108
00109         class InkObject : public SceneObject
00110         {
00111         public:
00112             static float GetSelectedStrokeSize()
00113             {
00114                 static const float selectedStrokeSize = 5.0f;
00115                 return selectedStrokeSize;
00116             }
00117
00118             static Windows::Foundation::Size GetDefaultStrokeSize()
00119             {
00120                 static const Windows::Foundation::Size defaultStrokeSize = Windows::Foundation::Size(2.0f, 2.0f);
00121                 return defaultStrokeSize;
00122             }
00123
00124             // Constructor - set the drawing attributes for the custom dried stroke
00125             InkObject(Windows::UI::Input::Inking::InkStroke^ s) :_stroke(s)
00126             {
00127                 _highlighterStroke = nullptr;
00128             };
00129
00130             virtual SCENEOBJECT_TYPES getType() { return SCENEOBJECT_TYPES::SOT_Ink; };
00131
00132             bool IsStrokeSelected() { return _stroke->Selected; };
00133             Windows::UI::Input::Inking::InkStroke^ GetInkStroke() { return _stroke; };
00134
00135             // Retrieve the stroke with highlighter (for the "hollow" effect) if selected
00136             Platform::Collections::Vector<Windows::UI::Input::Inking::InkStroke^>^  getStrokes()
00137             {
00138                 Platform::Collections::Vector<Windows::UI::Input::Inking::InkStroke^>^ strokes = ref new Platform::Collections::Vector<Windows::UI::Input::Inking::InkStroke^>();
00139                 strokes->Append(_stroke);
00140                 if (_stroke->Selected)
00141                 {
00142                     strokes->Append(_highlighterStroke);
00143                 }
00144                 return strokes;
00145             };
00146
00147             // If selected, we clone the stroke to create a highlighted stroke that will be on top of the original
00148             // to give a hollow effect
00149             void SelectStroke(Windows::UI::Input::Inking::InkStrokeContainer^ strokeContainerForTemp) {
00150                 if (_stroke != nullptr)
00151                 {
00152                     // Get the drawing attributes to modify them according to its state (inking or selection mode)
00153                     auto strokeDrawingAttributes = _stroke->DrawingAttributes;
00154
00155                     if (_stroke->Selected)
00156                     {
00157                         // Create the highlighter stroke to give it a hollow effect
00158                         _highlighterStroke = _stroke->Clone();
00159                         _highlighterStroke->Selected = true;
00160                         auto highlighterAttributes = _highlighterStroke->DrawingAttributes;
00161                         highlighterAttributes->Color = CanvasBackgroundColor;
00162                         highlighterAttributes->Size = GetDefaultStrokeSize();
00163                         _highlighterStroke->DrawingAttributes = highlighterAttributes;
00164
00165                         // Note that the Clone method must be used with AddStroke (InkManager) or AddStroke (InkStrokeContainer)
00166                         assert(strokeContainerForTemp != nullptr);
00167                         strokeContainerForTemp->AddStroke(_highlighterStroke);
00168
00169                         strokeDrawingAttributes->Size = Windows::Foundation::Size(GetSelectedStrokeSize(), GetSelectedStrokeSize());
00170                         _stroke->DrawingAttributes = strokeDrawingAttributes;
00171                     }
00172                     else
00173                     {
00174                         // reset the pointer to highlighter stroke and set the corresponding inkstroke to the default drawing attributes
00175                         if (_highlighterStroke != nullptr)
00176                         {
00177                             _highlighterStroke = nullptr;
00178                         }
00179                         strokeDrawingAttributes->Size = GetDefaultStrokeSize();
00180                         _stroke->DrawingAttributes = strokeDrawingAttributes;
00181                     }
00182                 }
00183             };
00184
00185         private:
00186             Windows::UI::Input::Inking::InkStroke^ _stroke;
00187             Windows::UI::Input::Inking::InkStroke^ _highlighterStroke;
00188         };
00189
00190         class ShapeObject : public SceneObject
00191         {
00192         public:
00193             ShapeObject(Shape s) : _shape(s) {};
00194             virtual SCENEOBJECT_TYPES getType() { return SCENEOBJECT_TYPES::SOT_Shape; };
00195             Shape getShape() { return _shape; };
00196         private:
00197             Shape _shape;
00198         };
00199
00200         // Renders the cache of objects
00201         void Render();
00202         void DeleteSceneObjects();
00203         void SelectInkSceneObject();
00204         void DeleteSelectedAndUpdate();
00205         void RemoveSelectedStrokesFromSceneObjects();
00206         void RestoreDefaultStrokeSize();
00207         RECT ConvertUpdateRect(Windows::Foundation::Rect const& updateRect);
00208         bool Draw(_In_opt_ const RECT* pUpdateRect = nullptr);
00209
00210         // This vector will contain all objects in the canvas (ink and shapes)
00211         std::vector<SceneObject*> _sceneObjects;
00212         std::unique_ptr<DX::DeviceResources> _deviceResources;
00213         std::unique_ptr<InkRenderer> _inkRenderer;
00214         std::unique_ptr<ShapeRenderer> _shapeRenderer;
00215
00216         // Initial point for lasso rectangle
00217         Windows::Foundation::Point _ptInitial;
00218         // Current end point for lasso rectangle
00219         Windows::Foundation::Point _ptCurrent;
00220         // Flag to indicate lasso selection is going on
00221         bool _inLassoSelection;
00222
00223         Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> _selectionBrush;
00224         Microsoft::WRL::ComPtr<ID2D1StrokeStyle> _strokeStyle;
00225
00226         Windows::UI::Input::Inking::InkSynchronizer^ _inkSynchronizer;
00227         bool _EndDryPending;
00228
00229         ULONG _refCount;
00230     };
00231 }
Generated on Fri Nov 15 2024 22:18:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LockScreenApps/cppwinrt/Scenario3_SecondaryTiles.h Source File

  • LockScreenApps
  • cppwinrt

Scenario3_SecondaryTiles.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013 #include "Scenario3_SecondaryTiles.g.h"
00014 #include "MainPage.h"
00015
00016 namespace winrt::SDKTemplate::implementation
00017 {
00018     struct Scenario3_SecondaryTiles : Scenario3_SecondaryTilesT<Scenario3_SecondaryTiles>
00019     {
00020         Scenario3_SecondaryTiles();
00021
00022         fire_and_forget CreateBadgeTile_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00023         fire_and_forget CreateBadgeAndTextTile_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
00024
00025     private:
00026         SDKTemplate::MainPage rootPage{ MainPage::Current() };
00027
00028         static constexpr wchar_t BADGE_TILE_ID[] = L"ST_BADGE";
00029         static constexpr wchar_t TEXT_TILE_ID[] = L"ST_BADGE_AND_TEXT";
00030
00031         static Windows::Foundation::Rect GetElementRect(Windows::UI::Xaml::FrameworkElement const& element);
00032     };
00033 }
00034
00035 namespace winrt::SDKTemplate::factory_implementation
00036 {
00037     struct Scenario3_SecondaryTiles : Scenario3_SecondaryTilesT<Scenario3_SecondaryTiles, implementation::Scenario3_SecondaryTiles>
00038     {
00039     };
00040 }
Generated on Fri Nov 15 2024 22:20:19 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Nfc/PcscSdk/Iso7816.cs Source File

  • Nfc
  • PcscSdk

Iso7816.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.IO;
00014 using System.Linq;
00015 using Windows.Storage.Streams;
00016 using System.Runtime.InteropServices.WindowsRuntime;
00017
00018 namespace Iso7816
00019 {
00020     /// <summary>
00021     /// Class ApduCommand implments the ISO 7816 apdu commands
00022     /// </summary>
00023     public class ApduCommand
00024     {
00025         public ApduCommand(byte cla, byte ins, byte p1, byte p2, byte[] commandData, byte? le)
00026         {
00027             if (commandData != null && commandData.Length > 254)
00028             {
00029                 throw new NotImplementedException();
00030             }
00031             CLA = cla;
00032             INS = ins;
00033             P1 = p1;
00034             P2 = p2;
00035             CommandData = commandData;
00036             Le = le;
00037
00038             ApduResponseType = typeof(Iso7816.ApduResponse);
00039         }
00040         /// <summary>
00041         /// Class of instructions
00042         /// </summary>
00043         public byte CLA { get; set; }
00044         /// <summary>
00045         /// Instruction code
00046         /// </summary>
00047         public byte INS { get; set; }
00048         /// <summary>
00049         /// Instruction parameter 1
00050         /// </summary>
00051         public byte P1 { get; set; }
00052         /// <summary>
00053         /// Instruction parameter 2
00054         /// </summary>
00055         public byte P2 { get; set; }
00056         /// <summary>
00057         /// Maximum number of bytes expected in the response ot this command
00058         /// </summary>
00059         public byte? Le { get; set; }
00060         /// <summary>
00061         /// Contiguous array of bytes representing commands data
00062         /// </summary>
00063         public byte[] CommandData { get; set; }
00064         /// <summary>
00065         /// Expected response type for this command.
00066         /// Provides mechanism to bind commands to responses
00067         /// </summary>
00068         public Type ApduResponseType { set; get; }
00069         /// <summary>
00070         /// Packs the current command into contiguous buffer bytes
00071         /// </summary>
00072         /// <returns>
00073         /// buffer holds the current wire/air format of the command
00074         /// </returns>
00075         public IBuffer GetBuffer()
00076         {
00077             using (DataWriter writer = new DataWriter())
00078             {
00079                 writer.WriteByte(CLA);
00080                 writer.WriteByte(INS);
00081                 writer.WriteByte(P1);
00082                 writer.WriteByte(P2);
00083
00084                 if (CommandData != null && CommandData.Length > 0)
00085                 {
00086                     writer.WriteByte((byte)CommandData.Length);
00087                     writer.WriteBytes(CommandData);
00088                 }
00089
00090                 if (Le != null)
00091                 {
00092                     writer.WriteByte((byte)Le);
00093                 }
00094
00095                 return writer.DetachBuffer();
00096             }
00097         }
00098         /// <summary>
00099         /// Helper method to print the command in a readable format
00100         /// </summary>
00101         /// <returns>
00102         /// return string formatted command
00103         /// </returns>
00104         public override string ToString()
00105         {
00106             return "ApduCommand CLA=" + CLA.ToString("X2") + ",INS=" + INS.ToString("X2") + ",P1=" + P1.ToString("X2") + ",P2=" + P2.ToString("X2") + ((CommandData != null && CommandData.Length > 0) ? (",Data=" + BitConverter.ToString(CommandData).Replace("-", "")) : "");
00107         }
00108     }
00109     /// <summary>
00110     /// Class ApduResponse implments handler for the ISO 7816 apdu response
00111     /// </summary>
00112     public class ApduResponse
00113     {
00114         public const byte TAG_MULTI_BYTE_MASK = 0x1F;
00115         public const byte TAG_COMPREHENSION_MASK = 0x80;
00116         public const byte TAG_LENGTH_MULTI_BYTE_MASK = 0x80;
00117
00118         /// <summary>
00119         /// Class constructor
00120         /// </summary>
00121         public ApduResponse() { }
00122         /// <summary>
00123         /// method to extract the response data, status and qualifier
00124         /// </summary>
00125         /// <param name="response"></param>
00126         public virtual void ExtractResponse(IBuffer response)
00127         {
00128             if (response.Length < 2)
00129             {
00130                 throw new InvalidOperationException("APDU response must be at least 2 bytes");
00131             }
00132             using (DataReader reader = DataReader.FromBuffer(response))
00133             {
00134                 ResponseData = new byte[response.Length - 2];
00135                 reader.ReadBytes(ResponseData);
00136                 SW1 = reader.ReadByte();
00137                 SW2 = reader.ReadByte();
00138             }
00139         }
00140         /// <summary>
00141         /// method to extract the matching TLV data object from response data
00142         /// </summary>
00143         public byte[] ExtractTlvDataObject(byte[] referenceTag)
00144         {
00145             using (var reader = DataReader.FromBuffer(ResponseData.AsBuffer()))
00146             {
00147                 byte nextByte;
00148
00149                 while (reader.UnconsumedBufferLength > 0)
00150                 {
00151                     int lengthLength = 0, valueLength = 0;
00152                     MemoryStream tag = new MemoryStream(), value = new MemoryStream();
00153
00154                     nextByte = reader.ReadByte();
00155                     tag.WriteByte(nextByte);
00156
00157                     if ((nextByte & TAG_MULTI_BYTE_MASK) == TAG_MULTI_BYTE_MASK)
00158                     {
00159                         while (reader.UnconsumedBufferLength > 0)
00160                         {
00161                             nextByte = reader.ReadByte();
00162                             tag.WriteByte(nextByte);
00163
00164                             if ((nextByte & TAG_COMPREHENSION_MASK) != TAG_COMPREHENSION_MASK)
00165                                 break;
00166                         }
00167                     }
00168
00169                     if (reader.UnconsumedBufferLength == 0)
00170                         throw new Exception("Invalid length for TLV response");
00171
00172                     valueLength = reader.ReadByte();
00173                     lengthLength = 1;
00174
00175                     if ((valueLength & TAG_LENGTH_MULTI_BYTE_MASK) == TAG_LENGTH_MULTI_BYTE_MASK)
00176                         lengthLength += (valueLength & ~TAG_LENGTH_MULTI_BYTE_MASK);
00177
00178                     while (--lengthLength > 0)
00179                         valueLength = (valueLength << 8) | reader.ReadByte();
00180
00181                     while (valueLength != 0 && valueLength-- > 0)
00182                         value.WriteByte(reader.ReadByte());
00183
00184                     if (referenceTag.SequenceEqual(tag.ToArray()))
00185                         return value.ToArray();
00186                 }
00187
00188                 throw new Exception("Tag not found in the TLV response");
00189             }
00190         }
00191         /// <summary>
00192         /// Detects if the command has succeeded
00193         /// </summary>
00194         /// <returns></returns>
00195         public virtual bool Succeeded
00196         {
00197             get
00198             {
00199                 return SW == 0x9000;
00200             }
00201         }
00202         /// <summary>
00203         /// command processing status
00204         /// </summary>
00205         public byte SW1 { get; set; }
00206         /// <summary>
00207         /// command processing qualifier
00208         /// </summary>
00209         public byte SW2 { get; set; }
00210         /// <summary>
00211         /// Wrapper property to read both response status and qualifer
00212         /// </summary>
00213         public ushort SW
00214         {
00215             get
00216             {
00217                 return (ushort)(((ushort)SW1 << 8) | (ushort)SW2);
00218             }
00219             set
00220             {
00221                 SW1 = (byte)(value >> 8);
00222                 SW2 = (byte)(value & 0xFF);
00223             }
00224         }
00225         /// <summary>
00226         /// Response data
00227         /// </summary>
00228         public byte[] ResponseData { get; set; }
00229         /// <summary>
00230         /// Mapping response status and qualifer to human readable format
00231         /// </summary>
00232         public virtual string SWTranslation
00233         {
00234             get
00235             {
00236                 switch (SW)
00237                 {
00238                     case 0x9000:
00239                         return "Success";
00240
00241                     case 0x6700:
00242                         return "Incorrect length or address range error";
00243
00244                     case 0x6800:
00245                         return "The requested function is not supported by the card";
00246
00247                     default:
00248                         return "Unknown";
00249                 }
00250             }
00251         }
00252         /// <summary>
00253         /// Helper method to print the response in a readable format
00254         /// </summary>
00255         /// <returns>
00256         /// return string formatted response
00257         /// </returns>
00258         public override string ToString()
00259         {
00260             return "ApduResponse SW=" + SW.ToString("X4") + " (" + SWTranslation + ")" + ((ResponseData != null && ResponseData.Length > 0) ? (",Data=" + BitConverter.ToString(ResponseData).Replace("-", "")) : "");
00261         }
00262     }
00263     /// <summary>
00264     /// Class that implements select command
00265     /// </summary>
00266     public class SelectCommand : ApduCommand
00267     {
00268         public SelectCommand(byte[] aid, byte? le)
00269             : base((byte)Iso7816.Cla.CompliantCmd0x, (byte)Iso7816.Ins.SelectFile, 0x04, 0x00, aid, le)
00270         {
00271         }
00272
00273         public byte[] AID
00274         {
00275             set { CommandData = value; }
00276             get { return CommandData; }
00277         }
00278         public override string ToString()
00279         {
00280             return "SelectCommand AID=" + BitConverter.ToString(CommandData).Replace("-", "");
00281         }
00282     }
00283 }
Generated on Fri Nov 15 2024 22:20:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlListView/cs/Contact.cs Source File

  • XamlListView
  • cs

Contact.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 using System;
00012 using System.Collections.Generic;
00013 using System.Collections.ObjectModel;
00014 using System.Linq;
00015
00016 namespace SDKTemplate
00017 {
00018     public class Contact
00019     {
00020         private static Random random = new Random();
00021
00022         #region Properties
00023         public string Id { get; } = Guid.NewGuid().ToString();
00024         public string Initials => InitialOf(FirstName) + InitialOf(LastName);
00025         public string Name => FirstName + " " + LastName;
00026         public string LastName { get; } = GenerateLastName();
00027         public string FirstName { get; } = GenerateFirstName();
00028         public string Position { get; } = GeneratePosition();
00029         public string PhoneNumber { get; } = GeneratePhoneNumber();
00030         public string Biography { get; } = GenerateBiography();
00031         #endregion
00032
00033         public Contact()
00034         {
00035         }
00036
00037         #region Public Methods
00038         public static Contact GetNewContact()
00039         {
00040             return new Contact();
00041         }
00042         public static ObservableCollection<Contact> GetContacts(int numberOfContacts)
00043         {
00044             ObservableCollection<Contact> contacts = new ObservableCollection<Contact>();
00045
00046             for (int i = 0; i < numberOfContacts; i++)
00047             {
00048                 contacts.Add(GetNewContact());
00049             }
00050             return contacts;
00051         }
00052         public static ObservableCollection<GroupInfoList> GetContactsGrouped(int numberOfContacts)
00053         {
00054             ObservableCollection<GroupInfoList> groups = new ObservableCollection<GroupInfoList>();
00055
00056             // Group by uppercase first letter of last name.
00057             var query = from item in GetContacts(numberOfContacts)
00058                         group item by item.LastName.Substring(0, 1).ToUpper() into g
00059                         orderby g.Key
00060                         select g;
00061
00062             foreach (var g in query)
00063             {
00064                 var info = new GroupInfoList();
00065                 info.Key = g.Key;
00066                 info.AddRange(g);
00067                 groups.Add(info);
00068             }
00069
00070             return groups;
00071         }
00072
00073         public override string ToString()
00074         {
00075             return Name;
00076         }
00077         #endregion
00078
00079         #region Helpers
00080         private static string InitialOf(string word)
00081         {
00082             return string.IsNullOrEmpty(word) ? string.Empty : word.Substring(0, 1);
00083         }
00084         private static string GeneratePosition()
00085         {
00086             List<string> positions = new List<string>() { "Program Manager", "Developer", "Product Manager", "Evangelist" };
00087             return positions[random.Next(0, positions.Count)];
00088         }
00089         private static string GenerateBiography()
00090         {
00091             List<string> biographies = new List<string>()
00092             {
00093                 @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer id facilisis lectus. Cras nec convallis ante, quis pulvinar tellus. Integer dictum accumsan pulvinar. Pellentesque eget enim sodales sapien vestibulum consequat.",
00094                 @"Maecenas eu sapien ac urna aliquam dictum.",
00095                 @"Nullam eget mattis metus. Donec pharetra, tellus in mattis tincidunt, magna ipsum gravida nibh, vitae lobortis ante odio vel quam.",
00096                 @"Quisque accumsan pretium ligula in faucibus. Mauris sollicitudin augue vitae lorem cursus condimentum quis ac mauris. Pellentesque quis turpis non nunc pretium sagittis. Nulla facilisi. Maecenas eu lectus ante. Proin eleifend vel lectus non tincidunt. Fusce condimentum luctus nisi, in elementum ante tincidunt nec.",
00097                 @"Aenean in nisl at elit venenatis blandit ut vitae lectus. Praesent in sollicitudin nunc. Pellentesque justo augue, pretium at sem lacinia, scelerisque semper erat. Ut cursus tortor at metus lacinia dapibus.",
00098                 @"Ut consequat magna luctus justo egestas vehicula. Integer pharetra risus libero, et posuere justo mattis et.",
00099                 @"Proin malesuada, libero vitae aliquam venenatis, diam est faucibus felis, vitae efficitur erat nunc non mauris. Suspendisse at sodales erat.",
00100                 @"Aenean vulputate, turpis non tincidunt ornare, metus est sagittis erat, id lobortis orci odio eget quam. Suspendisse ex purus, lobortis quis suscipit a, volutpat vitae turpis.",
00101                 @"Duis facilisis, quam ut laoreet commodo, elit ex aliquet massa, non varius tellus lectus et nunc. Donec vitae risus ut ante pretium semper. Phasellus consectetur volutpat orci, eu dapibus turpis. Fusce varius sapien eu mattis pharetra.",
00102                 @"Nam vulputate eu erat ornare blandit. Proin eget lacinia erat. Praesent nisl lectus, pretium eget leo et, dapibus dapibus velit. Integer at bibendum mi, et fringilla sem."
00103             };
00104             return biographies[random.Next(0, biographies.Count)];
00105         }
00106
00107         private static string GeneratePhoneNumber()
00108         {
00109             return string.Format("{0:(###)} {1:###}-{2:####}", random.Next(100, 1000), random.Next(100, 1000), random.Next(1000, 10000));
00110         }
00111         private static string GenerateFirstName()
00112         {
00113             List<string> names = new List<string>() { "Lilly", "Mukhtar", "Sophie", "Femke", "Abdul-Rafi'", "Chirag-ud-D...", "Mariana", "Aarif", "Sara", "Ibadah", "Fakhr", "Ilene", "Sardar", "Hanna", "Julie", "Iain", "Natalia", "Henrik", "Rasa", "Quentin", "Gadi", "Pernille", "Ishtar", "Jimme", "Justina", "Lale", "Elize", "Rand", "Roshanara", "Rajab", "Bijou", "Marcus", "Marcus", "Alima", "Francisco", "Thaqib", "Andreas", "Mariana", "Amalie", "Rodney", "Dena", "Fadl", "Ammar", "Anna", "Nasreen", "Reem", "Tomas", "Filipa", "Frank", "Bari'ah", "Parvaiz", "Jibran", "Tomas", "Elli", "Carlos", "Diego", "Henrik", "Aruna", "Vahid", "Eliana", "Roxane", "Amanda", "Ingrid", "Wander", "Malika", "Basim", "Eisa", "Alina", "Andreas", "Deeba", "Diya", "Parveen", "Bakr", "Celine", "Bakr", "Marcus", "Daniel", "Mathea", "Edmee", "Hedda", "Maria", "Maja", "Alhasan", "Alina", "Hedda", "Victor", "Aaftab", "Guilherme", "Maria", "Kai", "Sabien", "Abdel", "Fadl", "Bahaar", "Vasco", "Jibran", "Parsa", "Catalina", "Fouad", "Colette" };
00114             return names[random.Next(0, names.Count)];
00115         }
00116
00117         private static string GenerateLastName()
00118         {
00119             List<string> lastnames = new List<string>() { "Carlson", "Attia", "Quint", "Hollenberg", "Khoury", "Araujo", "Hakimi", "Seegers", "Abadi", "al", "Krommenhoek", "Siavashi", "Kvistad", "Sjo", "Vanderslik", "Fernandes", "Dehli", "Sheibani", "Laamers", "Batlouni", "Lyngvær", "Oveisi", "Veenhuizen", "Gardenier", "Siavashi", "Mutlu", "Karzai", "Mousavi", "Natsheh", "Seegers", "Nevland", "Lægreid", "Bishara", "Cunha", "Hotaki", "Kyvik", "Cardoso", "Pilskog", "Pennekamp", "Nuijten", "Bettar", "Borsboom", "Skistad", "Asef", "Sayegh", "Sousa", "Medeiros", "Kregel", "Shamoun", "Behzadi", "Kuzbari", "Ferreira", "Van", "Barros", "Fernandes", "Formo", "Nolet", "Shahrestaani", "Correla", "Amiri", "Sousa", "Fretheim", "Van", "Hamade", "Baba", "Mustafa", "Bishara", "Formo", "Hemmati", "Nader", "Hatami", "Natsheh", "Langen", "Maloof", "Berger", "Ostrem", "Bardsen", "Kramer", "Bekken", "Salcedo", "Holter", "Nader", "Bettar", "Georgsen", "Cunha", "Zardooz", "Araujo", "Batalha", "Antunes", "Vanderhoorn", "Nader", "Abadi", "Siavashi", "Montes", "Sherzai", "Vanderschans", "Neves", "Sarraf", "Kuiters" };
00120             return lastnames[random.Next(0, lastnames.Count)];
00121         }
00122         #endregion
00123     }
00124 }
Generated on Fri Nov 15 2024 22:22:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

ExitButton Member List

This is the complete list of members for ExitButton, including all inherited members.
AddChildElement(const std::shared_ptr< BaseElement > &childElement) | BaseElement |
ArrangeElements() override | Button | [virtual]
BaseElement() | BaseElement |
Button(UINT initialSize=BUTTON_SIZE, ButtonShape shape=ButtonShape::Rectangle) | Button |
ExitButton() | ExitButton |
FocusableElement() | FocusableElement |
FocusUpdate() override | Button | [virtual]
GetElementMargin() | BaseElement | [inline]
GetElementSize() | BaseElement | [inline]
GetIgnoreLayout() | BaseElement | [inline]
GetIsRenderPassNeeded() | BaseElement | [inline]
GetIsVisible() | BaseElement | [inline]
Initialize() override | ExitButton | [virtual]
IsFocused() | FocusableElement | [inline, virtual]
m_brush | Button | [protected]
m_buttonState | Button | [protected]
m_deviceResources | BaseElement | [protected]
m_elementCoordIntersectionPoint | FocusableElement | [protected]
m_elementMargin | BaseElement | [protected]
m_elementSize | BaseElement | [protected]
m_exitText | ExitButton | [private]
m_forceIconCentered | Button | [protected]
m_ignoreLayout | BaseElement | [protected]
m_isFocused | FocusableElement | [protected]
m_isFocusIntersectionCalculated | FocusableElement | [protected]
m_isInitialized | BaseElement | [protected]
m_isLayoutHorizontal | BaseElement | [protected]
m_isParentFocused | FocusableElement | [protected]
m_isRenderPassNeeded | BaseElement | [protected]
m_isVisible | BaseElement | [protected]
m_maxSecondsInPressingState | Button | [protected]
m_parentControlTransform | Button | [protected]
m_parentFocusedPosition | FocusableElement | [protected]
m_parentTextureHeight | FocusableElement | [protected]
m_parentTextureWidth | FocusableElement | [protected]
m_parentTranslation | BaseElement | [protected]
m_pressingTimeOut | Button | [protected]
m_shape | Button | [protected]
m_transformedTranslation | BaseElement | [protected]
m_transformMatrix | BaseElement | [protected]
m_transformRecalculationNeeded | BaseElement | [protected]
m_translation | BaseElement | [protected]
PerformAction() override | ExitButton | [virtual]
Render() | BaseElement | [protected, virtual]
SetBrush(ID2D1SolidColorBrush *brush) | BaseElement |
SetElementMargin(ElementMargin margin) | BaseElement | [inline]
SetElementSize(Windows::Foundation::Numerics::float2 size) | BaseElement | [inline]
SetIgnoreLayout(bool ignoreLayout) | BaseElement | [inline]
SetIsVisible(bool visible) | BaseElement |
SetLayoutHorizontal(bool isLayoutHorizontal) | BaseElement | [inline]
SetParentControlInformation(bool focused, Windows::Foundation::Numerics::float2 focusedPosition, UINT parentTextureWidth, UINT parentTextureHeight) | FocusableElement | [virtual]
SetParentTransform(Windows::Foundation::Numerics::float2 translation) | BaseElement |
SetTranslation(Windows::Foundation::Numerics::float2 translation) | BaseElement | [virtual]
TryRender() | BaseElement |
Update(const DX::StepTimer &timer, Windows::UI::Input::Spatial::SpatialPointerPose^cameraPose) override | Button | [virtual]
~BaseElement() | BaseElement | [virtual]
~FocusableElement() | FocusableElement | [virtual]
Generated on Fri Nov 15 2024 22:23:22 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/SampleConfiguration.cs Source File

  • AdvancedCasting
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using ScreenCasting;
00016 using System.Reflection;
00017 using ScreenCasting.Util;
00018
00019 namespace ScreenCasting
00020 {
00021     public partial class MainPage : Page
00022     {
00023         public const string FEATURE_NAME = "ScreenCasting";
00024         private List<Scenario> scenarios;
00025
00026         private void LoadScenarios()
00027         {
00028             if (ApiInformation.IsTypePresent("Windows.Devices.Enumeration.DevicePicker"))
00029             {
00030                 scenarios = new List<Scenario>
00031                 {
00032                     new Scenario() { Title="1 - Media Element Casting 101", ClassType=Type.GetType("ScreenCasting.Scenario01",false)}
00033                     ,new Scenario() { Title="2 - Casting APIs and a Custom Cast Button", ClassType=Type.GetType("ScreenCasting.Scenario02",false)}
00034                     ,new Scenario() { Title="3 - DIAL Sender Universal Windows app", ClassType=Type.GetType("ScreenCasting.Scenario03",false)}
00035                     ,new Scenario() { Title="4 - DIAL Receiver Windows Universal app", ClassType=Type.GetType("ScreenCasting.Scenario04")}
00036                     ,new Scenario() { Title="5 - Multi-View Media Application", ClassType=Type.GetType("ScreenCasting.Scenario05")}
00037                     ,new Scenario() { Title="6 - Combine Casting Methods", ClassType=Type.GetType("ScreenCasting.Scenario06")}
00038
00039               };
00040             }
00041             else
00042             {
00043                 scenarios = new List<Scenario> {
00044                     new Scenario() { Title="DIAL Receiver Windows Universal Application", ClassType=typeof(Scenario04)}
00045                 };
00046             }
00047         }
00048     }
00049
00050     public class Scenario
00051     {
00052         public string Title { get; set; }
00053         public Type ClassType { get; set; }
00054     }
00055 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DeviceInformationKindChoice Member List

This is the complete list of members for DeviceInformationKindChoice, including all inherited members.
DeviceInformationKindChoice(hstring displayName, std::vector< Windows::Devices::Enumeration::DeviceInformationKind > kinds) | DeviceInformationKindChoice | [inline]
DisplayName() const | DeviceInformationKindChoice | [inline]
displayName | DeviceInformationKindChoice | [private]
kinds | DeviceInformationKindChoice | [private]
Kinds() const | DeviceInformationKindChoice | [inline]
Generated on Fri Nov 15 2024 22:24:13 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: LineDisplay/cpp/pch.h Source File

  • LineDisplay
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <experimental/resumable>
00009 #include <ppltasks.h>
00010 #include <pplawait.h>
00011
00012 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WindowsAudioSession/cpp/Scenario1.xaml.cpp Source File

  • WindowsAudioSession
  • cpp

Scenario1.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00005 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00006 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00007 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00008 //
00009 //*********************************************************
00010
00011 //
00012 // Scenario1.xaml.cpp
00013 // Implementation of the Scenario1 class
00014 //
00015
00016 #include "pch.h"
00017 #include "Scenario1.xaml.h"
00018
00019 using namespace SDKSample;
00020 using namespace SDKSample::WASAPIAudio;
00021
00022 using namespace Platform;
00023 using namespace Windows::Foundation;
00024 using namespace Windows::Media::Devices;
00025 using namespace Windows::UI::Core;
00026 using namespace Windows::UI::Xaml;
00027 using namespace Windows::UI::Xaml::Controls;
00028 using namespace Windows::UI::Xaml::Navigation;
00029
00030
00031 Scenario1::Scenario1()
00032 {
00033  InitializeComponent();
00034  m_DevicesList = safe_cast<ListBox^>(static_cast<IFrameworkElement^>(this)->FindName("DevicesList"));
00035 }
00036
00037 /// <summary>
00038 /// Invoked when this page is about to be displayed in a Frame.
00039 /// </summary>
00040 /// <param name="e">Event data that describes how this page was reached.  The Parameter
00041 /// property is typically used to configure the page.</param>
00042 void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
00043 {
00044  // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00045  // as NotifyUser()
00046  rootPage = MainPage::Current;
00047 }
00048
00049 void Scenario1::ShowStatusMessage( Platform::String^ str, NotifyType messageType )
00050 {
00051  rootPage->NotifyUser( str, messageType );
00052 }
00053
00054 void Scenario1::Enumerate_Click( Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e )
00055 {
00056  Button^ b = safe_cast<Button^>(sender);
00057  if (b != nullptr)
00058  {
00059   m_DevicesList->Items->Clear();
00060   EnumerateAudioDevicesAsync();
00061  }
00062 }
00063
00064 void Scenario1::EnumerateAudioDevicesAsync()
00065 {
00066  // Get the string identifier of the audio renderer
00067  String^ AudioSelector = MediaDevice::GetAudioRenderSelector();
00068
00069  // Add custom properties to the query
00070  auto PropertyList = ref new Platform::Collections::Vector<String^>();
00071  PropertyList->Append( PKEY_AudioEndpoint_Supports_EventDriven_Mode );
00072
00073  // Setup the asynchronous callback
00074  Concurrency::task<DeviceInformationCollection^> enumOperation( DeviceInformation::FindAllAsync( AudioSelector, PropertyList ) );
00075  enumOperation.then([this](DeviceInformationCollection^ DeviceInfoCollection)
00076  {
00077   if ( (DeviceInfoCollection == nullptr) || (DeviceInfoCollection->Size == 0) )
00078   {
00079    this->ShowStatusMessage( "No Devices Found.", NotifyType::ErrorMessage );
00080   }
00081   else
00082   {
00083    try
00084    {
00085     // Enumerate through the devices and the custom properties
00086     for(unsigned int i = 0; i < DeviceInfoCollection->Size; i++)
00087     {
00088      DeviceInformation^ deviceInfo = DeviceInfoCollection->GetAt(i);
00089      String^ DeviceInfoString = deviceInfo->Name;
00090
00091      if (deviceInfo->Properties->Size > 0)
00092      {
00093       // Pull out the custom property
00094       Object^ DevicePropString = deviceInfo->Properties->Lookup( PKEY_AudioEndpoint_Supports_EventDriven_Mode );
00095
00096       if (nullptr != DevicePropString)
00097       {
00098        DeviceInfoString = DeviceInfoString + " --> EventDriven(" + DevicePropString + ")";
00099       }
00100      }
00101
00102      this->m_DevicesList->Items->Append( DeviceInfoString );
00103     }
00104
00105     String^ strMsg = "Enumerated " + DeviceInfoCollection->Size + " Device(s).";
00106     this->ShowStatusMessage( strMsg, NotifyType::StatusMessage );
00107    }
00108    catch ( Platform::Exception^ e )
00109    {
00110     this->ShowStatusMessage( e->Message, NotifyType::ErrorMessage );
00111    }
00112   }
00113  });
00114 }
00115
00116
Generated on Fri Nov 15 2024 22:17:51 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AllJoyn/Common/Scenario2WinRTComponent/pch.cpp Source File

  • AllJoyn
  • Common
  • Scenario2WinRTComponent

pch.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 //-----------------------------------------------------------------------------
00012 // <auto-generated>
00013 //   This code was generated by a tool.
00014 //
00015 //   Changes to this file may cause incorrect behavior and will be lost if
00016 //   the code is regenerated.
00017 //
00018 //   For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246
00019 // </auto-generated>
00020 //-----------------------------------------------------------------------------
00021 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

DistanceFieldRenderer Member List

This is the complete list of members for DistanceFieldRenderer, including all inherited members.
CreateDeviceDependentResources() | DistanceFieldRenderer |
DistanceFieldRenderer(const std::shared_ptr< DX::DeviceResources > &deviceResources, unsigned int const &textureWidth, unsigned int const &textureHeight) | DistanceFieldRenderer |
GetRenderCount() const | DistanceFieldRenderer | [inline]
GetTexture() const | DistanceFieldRenderer | [inline]
m_d3dDepthStencilView | DistanceFieldRenderer | [private]
m_deviceResources | DistanceFieldRenderer | [private]
m_indexBuffer | DistanceFieldRenderer | [private]
m_indexCount | DistanceFieldRenderer | [private]
m_inputLayout | DistanceFieldRenderer | [private]
m_loadingComplete | DistanceFieldRenderer | [private]
m_pixelShader | DistanceFieldRenderer | [private]
m_renderCount | DistanceFieldRenderer | [private]
m_renderTargetView | DistanceFieldRenderer | [private]
m_shaderResourceView | DistanceFieldRenderer | [private]
m_texture | DistanceFieldRenderer | [private]
m_textureHeight | DistanceFieldRenderer | [private]
m_textureWidth | DistanceFieldRenderer | [private]
m_vertexBuffer | DistanceFieldRenderer | [private]
m_vertexShader | DistanceFieldRenderer | [private]
m_vertexStride | DistanceFieldRenderer | [private]
ReleaseDeviceDependentResources() | DistanceFieldRenderer |
RenderDistanceField(ID3D11ShaderResourceView *texture) | DistanceFieldRenderer |
Generated on Fri Nov 15 2024 22:23:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlDragAndDrop/cpp/pch.cpp Source File

  • XamlDragAndDrop
  • cpp

pch.cpp

Go to the documentation of this file.
00001 //
00002 // Include the standard header and generate the precompiled header.
00003 //
00004
00005 #include "pch.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: MapControl/cpp/Scenario8.xaml.h Source File

  • MapControl
  • cpp

Scenario8.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario8.g.h"
00015 #include "MainPage.xaml.h"
00016
00017 namespace SDKTemplate
00018 {
00019     [Windows::Foundation::Metadata::WebHostHidden]
00020     public ref class Scenario8 sealed
00021     {
00022     public:
00023         Scenario8();
00024     private:
00025         MainPage^ rootPage = MainPage::Current;
00026         void myMap_Loaded(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00027         void findAtCenterButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00028         void addToResultGrid(Windows::Services::Maps::OfflineMaps::OfflineMapPackage^ package);
00029         static unsigned long long nearestMegabyte(unsigned long long bytes);
00030         static bool canDownload(Windows::Services::Maps::OfflineMaps::OfflineMapPackage^ package);
00031     };
00032 }
Generated on Fri Nov 15 2024 22:18:14 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ResizeAppView/cpp/Scenario1_Basic.xaml.cpp Source File

  • ResizeAppView
  • cpp

Scenario1_Basic.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011 #include "pch.h"
00012 #include "Scenario1_Basic.xaml.h"
00013
00014 using namespace SDKTemplate;
00015
00016 using namespace Platform;
00017 using namespace Windows::Foundation;
00018 using namespace Windows::Foundation::Collections;
00019 using namespace Windows::UI::Core;
00020 using namespace Windows::UI::ViewManagement;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Controls;
00023 using namespace Windows::UI::Xaml::Input;
00024
00025 using namespace Windows::UI;
00026
00027 // This is a clone of IUIContentRoot but is not exclusiveto
00028 [uuid(1DFCBAC6-B36B-5CB9-9BC5-2B7A0EDDC378)]
00029 public interface class IUIContentRootClone
00030 {
00031     property Windows::UI::UIContext^ UIContext
00032     {
00033         Windows::UI::UIContext^ get();
00034     }
00035 };
00036 ref class MockUIContentRoot : public IUIContentRootClone {
00037 public:
00038     property Windows::UI::UIContext^ UIContext
00039     { virtual Windows::UI::UIContext^ get() { return nullptr; }}
00040
00041 };
00042 Scenario1_Basic::Scenario1_Basic() : rootPage(MainPage::Current)
00043 {
00044     UIContentRoot^ root = safe_cast<UIContentRoot^>(reinterpret_cast<Object^>(ref new MockUIContentRoot()));
00045     __debugbreak();
00046     Windows::UI::UIContext^ c = root->UIContext;
00047     InitializeComponent();
00048 }
00049
00050 void Scenario1_Basic::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00051 {
00052     windowSizeChangedToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &Scenario1_Basic::OnWindowSizeChanged);
00053     UpdateContent();
00054 }
00055
00056 void Scenario1_Basic::OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00057 {
00058     Window::Current->SizeChanged -= windowSizeChangedToken;
00059 }
00060
00061 void Scenario1_Basic::ResizeView_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00062 {
00063     ApplicationView^ view = ApplicationView::GetForCurrentView();
00064     if (view->TryResizeView(Size(600, 500)))
00065     {
00066         rootPage->NotifyUser("Resizing to 600 \u00D7 500", NotifyType::StatusMessage);
00067         // The SizeChanged event will be raised when the resize is complete.
00068     }
00069     else
00070     {
00071         // The system does not support resizing, or the provided size is out of range.
00072         rootPage->NotifyUser("Failed to resize view", NotifyType::ErrorMessage);
00073     }
00074 }
00075
00076 void Scenario1_Basic::SetMinimumSize_Click(Platform::Object^ sender, RoutedEventArgs^ e)
00077 {
00078     ApplicationView^ view = ApplicationView::GetForCurrentView();
00079     if (SetMinimumSize->IsChecked->Value)
00080     {
00081         // If this size is not permitted by the system, the nearest permitted value is used.
00082         view->SetPreferredMinSize(Size(300, 200));
00083     }
00084     else
00085     {
00086         // Passing width = height = 0 returns to the default system behavior.
00087         view->SetPreferredMinSize(Size());
00088     }
00089 }
00090
00091 void Scenario1_Basic::OnWindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e)
00092 {
00093     UpdateContent();
00094 }
00095
00096 void Scenario1_Basic::UpdateContent()
00097 {
00098     Rect bounds = Window::Current->Bounds;
00099     ReportViewWidth->Text = bounds.Width.ToString();
00100     ReportViewHeight->Text = bounds.Height.ToString();
00101 }
Generated on Fri Nov 15 2024 22:19:49 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ProximitySensor/cs/Scenario1_DataEvents.xaml.cs Source File

  • ProximitySensor
  • cs

Scenario1_DataEvents.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using SDKTemplate;
00013 using System;
00014 using Windows.Devices.Enumeration;
00015 using Windows.Devices.Sensors;
00016 using Windows.Foundation;
00017 using Windows.UI.Core;
00018 using Windows.UI.Xaml;
00019 using Windows.UI.Xaml.Controls;
00020 using Windows.UI.Xaml.Navigation;
00021
00022 namespace ProximityCS
00023 {
00024     public sealed partial class Scenario1_DataEvents : Page
00025     {
00026         // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
00027         // as NotifyUser()
00028         MainPage rootPage = MainPage.Current;
00029
00030         private ProximitySensor sensor;
00031         private DeviceWatcher watcher;
00032
00033         public Scenario1_DataEvents()
00034         {
00035             this.InitializeComponent();
00036
00037             watcher = DeviceInformation.CreateWatcher(ProximitySensor.GetDeviceSelector());
00038             watcher.Added += OnProximitySensorAdded;
00039             watcher.Start();
00040         }
00041
00042         /// <summary>
00043         /// Invoked when the device watcher finds a proximity sensor
00044         /// </summary>
00045         /// <param name="sender">The device watcher</param>
00046         /// <param name="device">Device information for the proximity sensor that was found</param>
00047         private async void OnProximitySensorAdded(DeviceWatcher sender, DeviceInformation device)
00048         {
00049             if (null == sensor)
00050             {
00051                 ProximitySensor foundSensor = ProximitySensor.FromId(device.Id);
00052                 if (null != foundSensor)
00053                 {
00054                     if (null != foundSensor.MaxDistanceInMillimeters)
00055                     {
00056                         // Check if this is the sensor that matches our ranges.
00057
00058                         // TODO: Customize these values to your application's needs.
00059                         // Here, we are looking for a sensor that can detect close objects
00060                         // up to 3cm away, so we check the upper bound of the detection range.
00061                         const uint distanceInMillimetersLValue = 30; // 3 cm
00062                         const uint distanceInMillimetersRValue = 50; // 5 cm
00063
00064                         if (foundSensor.MaxDistanceInMillimeters >= distanceInMillimetersLValue &&
00065                             foundSensor.MaxDistanceInMillimeters <= distanceInMillimetersRValue)
00066                         {
00067                             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00068                             {
00069                                 rootPage.NotifyUser("Found a proximity sensor that meets the detection range", NotifyType.StatusMessage);
00070                             });
00071                         }
00072                         else
00073                         {
00074                             // We'll use the sensor anyway, to demonstrate how events work.
00075                             // Your app may decide not to use the sensor.
00076                             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00077                             {
00078                                 rootPage.NotifyUser("Proximity sensor does not meet the detection range, using it anyway", NotifyType.StatusMessage);
00079                             });
00080                         }
00081                     }
00082                     else
00083                     {
00084                         await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00085                         {
00086                             rootPage.NotifyUser("Proximity sensor does not report detection ranges, using it anyway", NotifyType.StatusMessage);
00087                         });
00088                     }
00089
00090                     if (null != foundSensor)
00091                     {
00092                         sensor = foundSensor;
00093                     }
00094                 }
00095                 else
00096                 {
00097                     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00098                     {
00099                         rootPage.NotifyUser("Could not get a proximity sensor from the device id", NotifyType.ErrorMessage);
00100                     });
00101                 }
00102             }
00103         }
00104
00105         /// <summary>
00106         /// Invoked when this page is about to be displayed in a Frame.
00107         /// </summary>
00108         /// <param name="e">Event data that describes how this page was reached. The Parameter
00109         /// property is typically used to configure the page.</param>
00110         protected override void OnNavigatedTo(NavigationEventArgs e)
00111         {
00112             ScenarioEnableButton.IsEnabled = true;
00113             ScenarioDisableButton.IsEnabled = false;
00114         }
00115
00116         /// <summary>
00117         /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
00118         /// </summary>
00119         /// <param name="e">
00120         /// Event data that can be examined by overriding code. The event data is representative
00121         /// of the navigation that will unload the current Page unless canceled. The
00122         /// navigation can potentially be canceled by setting Cancel.
00123         /// </param>
00124         protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
00125         {
00126             if (ScenarioDisableButton.IsEnabled)
00127             {
00128                 sensor.ReadingChanged -= new TypedEventHandler<ProximitySensor, ProximitySensorReadingChangedEventArgs>(ReadingChanged);
00129             }
00130
00131             base.OnNavigatingFrom(e);
00132         }
00133
00134         /// <summary>
00135         /// This is the click handler for the 'Enable' button.
00136         /// </summary>
00137         /// <param name="sender"></param>
00138         /// <param name="e"></param>
00139         private void ScenarioEnable(object sender, RoutedEventArgs e)
00140         {
00141             if (null != sensor)
00142             {
00143                 sensor.ReadingChanged += new TypedEventHandler<ProximitySensor, ProximitySensorReadingChangedEventArgs>(ReadingChanged);
00144
00145                 ScenarioEnableButton.IsEnabled = false;
00146                 ScenarioDisableButton.IsEnabled = true;
00147             }
00148             else
00149             {
00150                 rootPage.NotifyUser("No proximity sensors found", NotifyType.ErrorMessage);
00151             }
00152         }
00153
00154         /// <summary>
00155         /// This is the click handler for the 'Disable' button.
00156         /// </summary>
00157         /// <param name="sender"></param>
00158         /// <param name="e"></param>
00159         private void ScenarioDisable(object sender, RoutedEventArgs e)
00160         {
00161             sensor.ReadingChanged -= new TypedEventHandler<ProximitySensor, ProximitySensorReadingChangedEventArgs>(ReadingChanged);
00162
00163             ScenarioEnableButton.IsEnabled = true;
00164             ScenarioDisableButton.IsEnabled = false;
00165         }
00166
00167         /// <summary>
00168         /// This is the event handler for ReadingChanged events.
00169         /// </summary>
00170         /// <param name="sender">The proximity sensor that sent the reading change</param>
00171         /// <param name="e"></param>
00172         async private void ReadingChanged(ProximitySensor sender, ProximitySensorReadingChangedEventArgs e)
00173         {
00174             await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
00175             {
00176                 ProximitySensorReading reading = e.Reading;
00177                 if (null != reading)
00178                 {
00179                     ScenarioOutput_DetectionState.Text = reading.IsDetected ? "Detected" : "Not detected";
00180                     ScenarioOutput_Timestamp.Text = reading.Timestamp.ToString("u");
00181
00182                     // Show the detection distance, if available
00183                     if (null != reading.DistanceInMillimeters)
00184                     {
00185                         ScenarioOutput_DetectionDistance.Text = reading.DistanceInMillimeters.ToString();
00186                     }
00187                 }
00188             });
00189         }
00190     }
00191 }
Generated on Fri Nov 15 2024 22:17:33 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Simple3DGameDX/cppwinrt/GameContent/MediaReader.cpp Source File

  • Simple3DGameDX
  • cppwinrt
  • GameContent

MediaReader.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "MediaReader.h"
00014
00015 using namespace winrt::Windows::ApplicationModel;
00016
00017 MediaReader::MediaReader()
00018 {
00019     ZeroMemory(&m_waveFormat, sizeof(m_waveFormat));
00020     m_installedLocation = Package::Current().InstalledLocation();
00021     m_installedLocationPath = m_installedLocation.Path() + L"\\";
00022 }
00023
00024 WAVEFORMATEX* MediaReader::GetOutputWaveFormatEx()
00025 {
00026     return &m_waveFormat;
00027 }
00028
00029 std::vector<byte> MediaReader::LoadMedia(_In_ winrt::hstring const& filename)
00030 {
00031     winrt::check_hresult(
00032         MFStartup(MF_VERSION)
00033         );
00034
00035     winrt::com_ptr<IMFSourceReader> reader;
00036     winrt::check_hresult(
00037         MFCreateSourceReaderFromURL(
00038         (m_installedLocationPath + filename).c_str(),
00039             nullptr,
00040             reader.put()
00041             )
00042         );
00043
00044     // Set the decoded output format as PCM.
00045     // XAudio2 on Windows can process PCM and ADPCM-encoded buffers.
00046     // When using MediaFoundation, this sample always decodes into PCM.
00047     winrt::com_ptr<IMFMediaType> mediaType;
00048     winrt::check_hresult(
00049         MFCreateMediaType(mediaType.put())
00050         );
00051
00052     winrt::check_hresult(
00053         mediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio)
00054         );
00055
00056     winrt::check_hresult(
00057         mediaType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM)
00058         );
00059
00060     winrt::check_hresult(
00061         reader->SetCurrentMediaType(static_cast<uint32_t>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), 0, mediaType.get())
00062         );
00063
00064     // Get the complete WAVEFORMAT from the Media Type.
00065     winrt::com_ptr<IMFMediaType> outputMediaType;
00066     winrt::check_hresult(
00067         reader->GetCurrentMediaType(static_cast<uint32_t>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), outputMediaType.put())
00068         );
00069
00070     UINT32 size = 0;
00071     WAVEFORMATEX* waveFormat;
00072     winrt::check_hresult(
00073         MFCreateWaveFormatExFromMFMediaType(outputMediaType.get(), &waveFormat, &size)
00074         );
00075
00076     CopyMemory(&m_waveFormat, waveFormat, sizeof(m_waveFormat));
00077     CoTaskMemFree(waveFormat);
00078
00079     PROPVARIANT propVariant;
00080     winrt::check_hresult(
00081         reader->GetPresentationAttribute(static_cast<uint32_t>(MF_SOURCE_READER_MEDIASOURCE), MF_PD_DURATION, &propVariant)
00082         );
00083     // 'duration' is in 100ns units; convert to seconds, and round up
00084     // to the nearest whole byte.
00085     LONGLONG duration = propVariant.uhVal.QuadPart;
00086     unsigned int maxStreamLengthInBytes =
00087         static_cast<unsigned int>(
00088             ((duration * static_cast<ULONGLONG>(m_waveFormat.nAvgBytesPerSec)) + 10000000) /
00089             10000000
00090             );
00091
00092     std::vector<byte> fileData(maxStreamLengthInBytes);
00093
00094     winrt::com_ptr<IMFSample> sample;
00095     winrt::com_ptr<IMFMediaBuffer> mediaBuffer;
00096     DWORD flags = 0;
00097
00098     int positionInData = 0;
00099     bool done = false;
00100     while (!done)
00101     {
00102         sample = nullptr;
00103         mediaBuffer = nullptr;
00104         winrt::check_hresult(
00105             reader->ReadSample(static_cast<uint32_t>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), 0, nullptr, &flags, nullptr, sample.put())
00106             );
00107
00108         if (sample != nullptr)
00109         {
00110             winrt::check_hresult(
00111                 sample->ConvertToContiguousBuffer(mediaBuffer.put())
00112                 );
00113
00114             BYTE* audioData = nullptr;
00115             DWORD sampleBufferLength = 0;
00116             winrt::check_hresult(
00117                 mediaBuffer->Lock(&audioData, nullptr, &sampleBufferLength)
00118                 );
00119
00120             for (DWORD i = 0; i < sampleBufferLength; i++)
00121             {
00122                 fileData[positionInData++] = audioData[i];
00123             }
00124         }
00125         if (flags & MF_SOURCE_READERF_ENDOFSTREAM)
00126         {
00127             done = true;
00128         }
00129     }
00130
00131     return fileData;
00132 }
Generated on Fri Nov 15 2024 22:21:16 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CustomCapability/cpp/Scenario1_MeteringData.xaml.cpp Source File

  • CustomCapability
  • cpp

Scenario1_MeteringData.xaml.cpp

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario1_MeteringData.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Platform;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Foundation::Collections;
00020 using namespace Windows::UI::Xaml;
00021 using namespace Windows::UI::Xaml::Controls::Primitives;
00022
00023 MeteringData::MeteringData()
00024 {
00025     InitializeComponent();
00026     ViewModel = ServiceViewModel::Current;
00027 }
00028
00029 void SDKTemplate::MeteringData::button_Click_StartMetering(Object^ sender, RoutedEventArgs^ e)
00030 {
00031     ViewModel->StartMetering((int)SamplePeriodSlider->Value);
00032 }
00033
00034 void SDKTemplate::MeteringData::button_Click_StopMetering(Object^ sender, RoutedEventArgs^ e)
00035 {
00036     ViewModel->StopMetering();
00037 }
00038
00039 void SDKTemplate::MeteringData::slider_ValueChanged(Object^ sender, RangeBaseValueChangedEventArgs^ e)
00040 {
00041     // Ignore slider value changes prior to ViewModel initialization.
00042     if (ViewModel != nullptr)
00043     {
00044         // Update the sample period in response to slider change.
00045         ViewModel->SetSamplePeriod((int)SamplePeriodSlider->Value);
00046     }
00047 }
Generated on Fri Nov 15 2024 22:19:02 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DeviceEnumerationAndPairing/cs/Scenario4_Snapshot.xaml.cs Source File

  • DeviceEnumerationAndPairing
  • cs

Scenario4_Snapshot.xaml.cs

Go to the documentation of this file.
00001 // Copyright (c) Microsoft. All rights reserved.
00002
00003 using System;
00004 using System.Collections.ObjectModel;
00005 using Windows.Devices.Enumeration;
00006 using Windows.UI.Xaml;
00007 using Windows.UI.Xaml.Controls;
00008 using Windows.UI.Xaml.Navigation;
00009
00010 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00011
00012 namespace SDKTemplate
00013 {
00014     /// <summary>
00015     /// An empty page that can be used on its own or navigated to within a Frame.
00016     /// </summary>
00017     public sealed partial class Scenario4_Snapshot : Page
00018     {
00019         private MainPage rootPage = MainPage.Current;
00020
00021         private ObservableCollection<DeviceInformationDisplay> resultCollection = new ObservableCollection<DeviceInformationDisplay>();
00022
00023         public Scenario4_Snapshot()
00024         {
00025             this.InitializeComponent();
00026         }
00027
00028         protected override void OnNavigatedTo(NavigationEventArgs e)
00029         {
00030             resultsListView.ItemsSource = resultCollection;
00031
00032             selectorComboBox.ItemsSource = DeviceSelectorChoices.FindAllAsyncSelectors;
00033             selectorComboBox.SelectedIndex = 0;
00034         }
00035
00036         private async void FindButton_Click(object sender, RoutedEventArgs e)
00037         {
00038             DeviceSelectorInfo deviceSelectorInfo;
00039             DeviceInformationCollection deviceInfoCollection;
00040
00041             findButton.IsEnabled = false;
00042             resultCollection.Clear();
00043
00044             // First get the device selector chosen by the UI.
00045             deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;
00046
00047             rootPage.NotifyUser("FindAllAsync operation started...", NotifyType.StatusMessage);
00048
00049             if (null == deviceSelectorInfo.Selector)
00050             {
00051                 // If the a pre-canned device class selector was chosen, call the DeviceClass overload
00052                 deviceInfoCollection = await DeviceInformation.FindAllAsync(deviceSelectorInfo.DeviceClassSelector);
00053             }
00054             else
00055             {
00056                 // Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
00057                 deviceInfoCollection = await DeviceInformation.FindAllAsync(
00058                     deviceSelectorInfo.Selector,
00059                     null // don't request additional properties for this sample
00060                     );
00061             }
00062
00063             rootPage.NotifyUser(
00064                 String.Format("FindAllAsync operation completed. {0} devices found.", deviceInfoCollection.Count),
00065                 NotifyType.StatusMessage);
00066
00067             foreach (DeviceInformation deviceInfo in deviceInfoCollection)
00068             {
00069                 resultCollection.Add(new DeviceInformationDisplay(deviceInfo));
00070             }
00071
00072             findButton.IsEnabled = true;
00073         }
00074     }
00075 }
Generated on Fri Nov 15 2024 22:19:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ShareSource/cpp/ShareCustomData.xaml.h Source File

  • ShareSource
  • cpp

ShareCustomData.xaml.h

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 //
00013 // ShareCustomData.xaml.h
00014 // Declaration of the ShareCustomData class
00015 //
00016
00017 #pragma once
00018
00019 #include "pch.h"
00020 #include "SharePage.h"
00021 #include "ShareCustomData.g.h"
00022 #include "MainPage.xaml.h"
00023
00024 namespace SDKTemplate
00025 {
00026     [Windows::Foundation::Metadata::WebHostHidden]
00027     public ref class ShareCustomData sealed
00028     {
00029     public:
00030         ShareCustomData();
00031
00032     protected:
00033         virtual bool GetShareContent(Windows::ApplicationModel::DataTransfer::DataRequest^ request) override;
00034     };
00035 }
Generated on Fri Nov 15 2024 22:21:11 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_AdaptiveSync Member List

This is the complete list of members for Scenario3_AdaptiveSync, including all inherited members.
EnablePlaybackControls(bool enabled) | Scenario3_AdaptiveSync | [inline, private]
LastPositionUpdate | Scenario3_AdaptiveSync | [private]
Load_Click(object sender, RoutedEventArgs e) | Scenario3_AdaptiveSync | [inline, private]
maxNaturalDurationForController | Scenario3_AdaptiveSync | [private]
MediaPlayer_MediaOpened(MediaPlayer mediaPlayer, object args) | Scenario3_AdaptiveSync | [inline, private]
mediaPlayerElements | Scenario3_AdaptiveSync | [private]
MediaTimelineController_PositionChanged(MediaTimelineController sender, object args) | Scenario3_AdaptiveSync | [inline, private]
MediaTimelineController_StateChanged(MediaTimelineController sender, object args) | Scenario3_AdaptiveSync | [inline, private]
openedMediaCount | Scenario3_AdaptiveSync | [private]
Page_OnLoaded(object sender, RoutedEventArgs e) | Scenario3_AdaptiveSync | [inline, private]
Page_OnUnloaded(object sender, RoutedEventArgs e) | Scenario3_AdaptiveSync | [inline, private]
PlayPause_Click(object sender, RoutedEventArgs e) | Scenario3_AdaptiveSync | [inline, private]
PositionChangeThreshold | Scenario3_AdaptiveSync | [private]
rootPage | Scenario3_AdaptiveSync | [private]
Scenario3_AdaptiveSync() | Scenario3_AdaptiveSync | [inline]
Seek2SecondsBack_Click(object sender, RoutedEventArgs e) | Scenario3_AdaptiveSync | [inline, private]
Seek2SecondsForward_Click(object sender, RoutedEventArgs e) | Scenario3_AdaptiveSync | [inline, private]
Seek30SecondsBack_Click(object sender, RoutedEventArgs e) | Scenario3_AdaptiveSync | [inline, private]
Seek30SecondsForward_Click(object sender, RoutedEventArgs e) | Scenario3_AdaptiveSync | [inline, private]
SeekDelta(TimeSpan amount) | Scenario3_AdaptiveSync | [inline, private]
timelineController | Scenario3_AdaptiveSync | [private]
Generated on Fri Nov 15 2024 22:23:54 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: BasicMediaCasting/cs/SampleConfiguration.cs Source File

  • BasicMediaCasting
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using BasicMediaCasting;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "BasicMediaCasting";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title="Basic Media Casting", ClassType=typeof(Scenario1)},
00026             new Scenario() { Title="Casting Using Casting Picker", ClassType=typeof(Scenario2)},
00027             new Scenario() { Title="Casting Using Custom Picker", ClassType=typeof(Scenario3)},
00028         };
00029     }
00030
00031     public class Scenario
00032     {
00033         public string Title { get; set; }
00034         public Type ClassType { get; set; }
00035     }
00036 }
Generated on Fri Nov 15 2024 22:17:23 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: WebAuthenticationBroker/cs/SampleConfiguration.cs Source File

  • WebAuthenticationBroker
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using WebAuthentication;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Web authentication broker sample";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title = "Connect to Facebook Services", ClassType = typeof(Scenario1_Facebook) },
00026             new Scenario() { Title = "Connect to Twitter Services", ClassType = typeof(Scenario2_Twitter) },
00027             new Scenario() { Title = "Connect to Flickr Services", ClassType = typeof(Scenario3_Flickr) },
00028         };
00029     }
00030
00031     public class Scenario
00032     {
00033         public string Title { get; set; }
00034         public Type ClassType { get; set; }
00035     }
00036
00037     public static class FormDecoderExtensions
00038     {
00039         public static string TryGetValue(this Windows.Foundation.WwwFormUrlDecoder decoder, string name)
00040         {
00041             try
00042             {
00043                 return decoder.GetFirstValueByName(name);
00044             }
00045             catch (ArgumentException)
00046             {
00047                 return null;
00048             }
00049         }
00050     }
00051 }
00052
Generated on Fri Nov 15 2024 22:17:26 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: ContextMenu/cs/Scenario1.xaml.cs Source File

  • ContextMenu
  • cs

Scenario1.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using Windows.Foundation;
00014 using Windows.UI.Popups;
00015 using Windows.UI.Xaml;
00016 using Windows.UI.Xaml.Controls;
00017 using Windows.UI.Xaml.Input;
00018 using Windows.UI.Xaml.Media;
00019 using Windows.UI.Xaml.Navigation;
00020
00021 namespace SDKTemplate
00022 {
00023     /// <summary>
00024     /// An empty page that can be used on its own or navigated to within a Frame.
00025     /// </summary>
00026     public sealed partial class Scenario1 : Page
00027     {
00028         public Scenario1()
00029         {
00030             this.InitializeComponent();
00031         }
00032
00033         public static Rect GetElementRect(FrameworkElement element)
00034         {
00035             GeneralTransform buttonTransform = element.TransformToVisual(null);
00036             Point point = buttonTransform.TransformPoint(new Point());
00037             return new Rect(point, new Size(element.ActualWidth, element.ActualHeight));
00038         }
00039
00040         private async void AttachmentImage_RightTapped(object sender, RightTappedRoutedEventArgs e)
00041         {
00042             // Create a menu and add commands specifying a callback delegate for each.
00043             // Since command delegates are unique, no need to specify command Ids.
00044             var menu = new PopupMenu();
00045             menu.Commands.Add(new UICommand("Open with", (command) =>
00046             {
00047                 OutputTextBlock.Text = "'" + command.Label + "' selected";
00048             }));
00049             menu.Commands.Add(new UICommand("Save attachment", (command) =>
00050             {
00051                 OutputTextBlock.Text = "'" + command.Label + "' selected";
00052             }));
00053
00054             // We don't want to obscure content, so pass in a rectangle representing the sender of the context menu event.
00055             // We registered command callbacks; no need to handle the menu completion event
00056             OutputTextBlock.Text = "Context menu shown";
00057             var chosenCommand = await menu.ShowForSelectionAsync(GetElementRect((FrameworkElement)sender));
00058             if (chosenCommand == null) // The command is null if no command was invoked.
00059             {
00060                 OutputTextBlock.Text = "Context menu dismissed";
00061             }
00062         }
00063     }
00064 }
Generated on Fri Nov 15 2024 22:17:39 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

CustomTrigger Member List

This is the complete list of members for CustomTrigger, including all inherited members.
CustomTrigger() | CustomTrigger | [inline]
customTriggerTaskName | CustomTrigger | [private]
guidCustomSystemEventId_OsrUsbFx2 | CustomTrigger | [private]
IsFx2CustomTriggerTaskRegistered() | CustomTrigger | [inline, private]
OnNavigatedFrom(NavigationEventArgs e) | CustomTrigger | [inline, protected]
RegisterCustomTrigger_Click(Object sender, RoutedEventArgs e) | CustomTrigger | [inline, private]
rootPage | CustomTrigger | [private]
taskRegistration | CustomTrigger | [private]
UnregisterCustomTrigger_Click(Object sender, RoutedEventArgs e) | CustomTrigger | [inline, private]
UnregisterTask() | CustomTrigger | [inline, private]
UpdateUI() | CustomTrigger | [inline, private]
Generated on Fri Nov 15 2024 22:23:44 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

Scenario3_CurrencyFormatting Member List

This is the complete list of members for Scenario3_CurrencyFormatting, including all inherited members.
Display_Click(Windows::Foundation::IInspectable const &sender, Windows::UI::Xaml::RoutedEventArgs const &e) | Scenario3_CurrencyFormatting
Scenario3_CurrencyFormatting() | Scenario3_CurrencyFormatting
Generated on Fri Nov 15 2024 22:24:17 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: PenHaptics/cppwinrt/Scenario2_SupportedTactileFeedback.cpp Source File

  • PenHaptics
  • cppwinrt

Scenario2_SupportedTactileFeedback.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "SampleConfiguration.h"
00014 #include "Scenario2_SupportedTactileFeedback.h"
00015 #include "Scenario2_SupportedTactileFeedback.g.cpp"
00016
00017 using namespace winrt;
00018 using namespace Windows::Foundation;
00019 using namespace Windows::Devices::Haptics;
00020 using namespace Windows::Devices::Input;
00021 using namespace Windows::UI::Xaml;
00022 using namespace Windows::UI::Xaml::Input;
00023
00024 // This sample shows how to query the pen currently providing input to the system to see
00025 // if it supports tactile feedback and, if so, what features it supports
00026 namespace winrt::SDKTemplate::implementation
00027 {
00028     Scenario2_SupportedTactileFeedback::Scenario2_SupportedTactileFeedback()
00029     {
00030         InitializeComponent();
00031     }
00032
00033     // The PointerEnter event will get fired as soon as Pointer input is received.
00034     // This event handler implementation will query the device providing input to see if it's a pen and
00035     // then check to see the pen supports tactile feedback and, if so, what features it supports
00036     void Scenario2_SupportedTactileFeedback::Pointer_Entered(IInspectable const&, PointerRoutedEventArgs const& e)
00037     {
00038         // If the current Pointer device is not a pen, exit
00039         if (e.Pointer().PointerDeviceType() != PointerDeviceType::Pen)
00040         {
00041             supportedFeatures().Text(L"");
00042             supportedFeedback().Text(L"");
00043             return;
00044         }
00045
00046         // Attempt to retrieve the PenDevice from the current PointerId
00047         penDevice = PenDevice::GetFromPointerId(e.Pointer().PointerId());
00048
00049         // If a PenDevice cannot be retrieved based on the PointerId, it does not support
00050         // advanced pen features, such as tactile feedback
00051         if (penDevice == nullptr)
00052         {
00053             statusText().Text(L"Advanced pen features not supported");
00054             supportedFeatures().Text(L"");
00055             supportedFeedback().Text(L"");
00056             return;
00057         }
00058
00059         // Check to see if the current PenDevice supports tactile feedback by seeing if it
00060         // has a SimpleHapticsController
00061         hapticsController = penDevice.SimpleHapticsController();
00062         if (hapticsController == nullptr)
00063         {
00064             statusText().Text(L"This pen does not provide tactile feedback");
00065             return;
00066         }
00067
00068         // Check which tactile feedback features are supported
00069         std::wstring message = L"Supported Haptics Features:\n";
00070         if (hapticsController.IsIntensitySupported())
00071         {
00072             message.append(L"Intensity\n");
00073         }
00074         if (hapticsController.IsPlayCountSupported())
00075         {
00076             message.append(L"PlayCount\n");
00077         }
00078         if (hapticsController.IsPlayDurationSupported())
00079         {
00080             message.append(L"PlayDuration\n");
00081         }
00082         if (hapticsController.IsReplayPauseIntervalSupported())
00083         {
00084             message.append(L"ReplayPauseInterval\n");
00085         }
00086         supportedFeatures().Text(message);
00087
00088         // Check which feedback waveforms are supported
00089         message = L"Supported Feedback:\n";
00090         for (SimpleHapticsControllerFeedback feedback : hapticsController.SupportedFeedback())
00091         {
00092             uint16_t waveform = feedback.Waveform();
00093             for (auto [name, value] : WaveformNamesMap())
00094             {
00095                 if (waveform == value)
00096                 {
00097                     message.append(name);
00098                     message.append(L"\n");
00099                     break;
00100                 }
00101             }
00102         }
00103         supportedFeedback().Text(message);
00104         statusText().Text(L"");
00105     }
00106
00107     // Clear the current penDevice and hapticsController on PointerExit
00108     void Scenario2_SupportedTactileFeedback::Pointer_Exited(IInspectable const&, PointerRoutedEventArgs const&)
00109     {
00110         penDevice = nullptr;
00111         hapticsController = nullptr;
00112     }
00113 }
Generated on Fri Nov 15 2024 22:20:52 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: SimpleOrientationSensor/cs/SampleConfiguration.cs Source File

  • SimpleOrientationSensor
  • cs

SampleConfiguration.cs

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using System;
00013 using System.Collections.Generic;
00014 using Windows.UI.Xaml.Controls;
00015 using SimpleOrientationCS;
00016
00017 namespace SDKTemplate
00018 {
00019     public partial class MainPage : Page
00020     {
00021         public const string FEATURE_NAME = "Simple Orientation Sensor";
00022
00023         List<Scenario> scenarios = new List<Scenario>
00024         {
00025             new Scenario() { Title = "Data Events", ClassType = typeof(SimpleOrientationCS.Scenario1_DataEvents) },
00026             new Scenario() { Title = "Polling", ClassType = typeof(SimpleOrientationCS.Scenario2_Polling) }
00027         };
00028     }
00029
00030     public class Scenario
00031     {
00032         public string Title { get; set; }
00033         public Type ClassType { get; set; }
00034     }
00035 }
Generated on Fri Nov 15 2024 22:17:25 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Logging/cpp/Scenario2.xaml.cpp Source File

  • Logging
  • cpp

Scenario2.xaml.cpp

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #include "pch.h"
00013 #include "Scenario2.xaml.h"
00014
00015 using namespace SDKTemplate;
00016
00017 using namespace Windows::UI::Xaml;
00018 using namespace Windows::UI::Xaml::Controls;
00019 using namespace concurrency;
00020
00021 Scenario2::Scenario2()
00022 {
00023     // This sample UI is interested in events from
00024     // the LoggingSessionScenario class so the UI can be updated.
00025     LoggingScenario->StatusChanged += ref new StatusChangedHandler(this, &Scenario2::OnStatusChanged);
00026     InitializeComponent();
00027 }
00028
00029 void Scenario2::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e)
00030 {
00031     UpdateControls();
00032 }
00033
00034 Windows::UI::Xaml::Controls::ScrollViewer^ Scenario2::FindScrollViewer(DependencyObject^ depObject)
00035 {
00036     if (depObject == nullptr)
00037     {
00038         return nullptr;
00039     }
00040
00041     int countThisLevel = Windows::UI::Xaml::Media::VisualTreeHelper::GetChildrenCount(depObject);
00042     if (countThisLevel <= 0)
00043     {
00044         return nullptr;
00045     }
00046
00047     for (int childIndex = 0; childIndex < countThisLevel; childIndex++)
00048     {
00049         DependencyObject^ childDepObject = Windows::UI::Xaml::Media::VisualTreeHelper::GetChild(depObject, childIndex);
00050         ScrollViewer^ sv = dynamic_cast<ScrollViewer^>(childDepObject);
00051         if (sv != nullptr)
00052         {
00053             return sv;
00054         }
00055
00056         sv = FindScrollViewer(childDepObject);
00057         if (sv != nullptr)
00058         {
00059             return sv;
00060         }
00061     }
00062
00063     return nullptr;
00064 }
00065
00066 // Add a message to the UI control which displays status while the sample is running.
00067 void Scenario2::AddMessage(Platform::String^ message)
00068 {
00069     Platform::String^ messageToAdd = "";
00070     messageToAdd += message;
00071     messageToAdd += "\r\n";
00072
00073     StatusMessageList->Text += messageToAdd;
00074     StatusMessageList->Select(StatusMessageList->Text->Length(), 0);
00075
00076     ScrollViewer^ sv = FindScrollViewer(StatusMessageList);
00077     if (sv != nullptr)
00078     {
00079         sv->ChangeView(nullptr, StatusMessageList->ActualHeight, nullptr);
00080     }
00081
00082 }
00083
00084 // Call AddMessage on the UI thread.
00085 task<void> Scenario2::AddMessageDispatch(Platform::String^ message)
00086 {
00087     return create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]() {
00088         AddMessage(message);
00089     })));
00090 }
00091
00092 // AddLogFileMessageDispatch updates the UI with status information when
00093 // a new log file is created.
00094 task<void> Scenario2::AddLogFileMessageDispatch(Platform::String^ message, const std::wstring& logFileFullPath)
00095 {
00096     return create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]() {
00097
00098         // On the UI thread...
00099
00100         Platform::String^ finalMessage;
00101         if (!logFileFullPath.empty())
00102         {
00103             // Add a message to the UI indicating a new log file was created.
00104             Platform::String^ path = ref new Platform::String(logFileFullPath.c_str());
00105             Platform::String^ directoryName;
00106             Platform::String^ fileName;
00107             std::wstring::size_type posLastSlash = logFileFullPath.find_last_of(L'\\');
00108             if (posLastSlash > 0 && posLastSlash < logFileFullPath.size() - 1)
00109             {
00110                 directoryName = ref new Platform::String(logFileFullPath.substr(0, posLastSlash).c_str());
00111                 fileName = ref new Platform::String(logFileFullPath.substr(posLastSlash + 1, logFileFullPath.size() - (posLastSlash + 1)).c_str());
00112             }
00113             else
00114             {
00115                 directoryName = "";
00116                 fileName = "";
00117             }
00118             finalMessage = message + ": " + fileName;
00119             finalMessage = message + ": " + fileName;
00120             ViewLogInfo->Text =
00121                 "Log folder: \"" + directoryName + "\"\r\n" +
00122                 "- To view with tracerpt: tracerpt.exe \"" + path + "\" -of XML -o LogFile.xml\r\n" +
00123                 "- To view with Windows Performance Toolkit (WPT):\n" +
00124                 "   xperf -merge \"" + path + "\" merged.etl\n" +
00125                 "   wpa.exe merged.etl";
00126         }
00127         else
00128         {
00129             finalMessage = message + ": none, nothing logged since saving the last file.";
00130         }
00131         AddMessage(finalMessage);
00132     })));
00133 }
00134
00135 void Scenario2::OnStatusChanged(Platform::Object^ sender, LoggingScenarioEventArgs^ e)
00136 {
00137     if (e->Type == LoggingScenarioEventType::BusyStatusChanged)
00138     {
00139         create_task(Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]() {
00140             UpdateControls();
00141         })));
00142     }
00143     else if (e->Type == LoggingScenarioEventType::LogFileGenerated)
00144     {
00145         AddLogFileMessageDispatch("LogFileGenerated", e->LogFileFullPath).then([]() {
00146         });
00147     }
00148     else if (e->Type == LoggingScenarioEventType::LoggingEnabledDisabled)
00149     {
00150         Platform::String^ message = "Logging has been " + (e->Enabled ? "enabled" : "disabled") + ".";
00151         AddMessageDispatch(message);
00152     }
00153 }
00154
00155 void Scenario2::UpdateControls()
00156 {
00157     if (LoggingScenario->LoggingEnabled)
00158     {
00159         InputTextBlock1->Text = "Logging is enabled. Click 'Disable Logging' to disable logging. With logging enabled, you can click 'Log Messages' to use the logging API to generate log files.";
00160         EnableDisableLoggingButton->Content = "Disable Logging";
00161
00162         if (LoggingScenario->IsBusy)
00163         {
00164             EnableDisableLoggingButton->IsEnabled = false;
00165             DoScenarioButton->IsEnabled = false;
00166         }
00167         else
00168         {
00169             EnableDisableLoggingButton->IsEnabled = true;
00170             DoScenarioButton->IsEnabled = true;
00171         }
00172     }
00173     else
00174     {
00175         InputTextBlock1->Text = "Logging is disabled. Click 'Enable Logging' to enable logging. After you enable logging you can click 'Log Messages' to use the logging API to generate log files.";
00176         EnableDisableLoggingButton->Content = "Enable Logging";
00177         DoScenarioButton->IsEnabled = false;
00178
00179         if (LoggingScenario->IsBusy)
00180         {
00181             EnableDisableLoggingButton->IsEnabled = false;
00182         }
00183         else
00184         {
00185             EnableDisableLoggingButton->IsEnabled = true;
00186         }
00187     }
00188 }
00189
00190 // Enabled/disabled logging.
00191 void Scenario2::EnableDisableLogging(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00192 {
00193     if (LoggingScenario->LoggingEnabled)
00194     {
00195         MainPage::Current->NotifyUser("Disabling logging...", NotifyType::StatusMessage);
00196     }
00197     else
00198     {
00199         MainPage::Current->NotifyUser("Enabling logging...", NotifyType::StatusMessage);
00200     }
00201
00202     LoggingScenario->ToggleLoggingEnabledDisabled();
00203     UpdateControls();
00204
00205     if (this->LoggingScenario->LoggingEnabled)
00206     {
00207         MainPage::Current->NotifyUser("Logging enabled.", NotifyType::StatusMessage);
00208     }
00209     else
00210     {
00211         MainPage::Current->NotifyUser("Logging disabled.", NotifyType::StatusMessage);
00212     }
00213 }
00214
00215 // Run a sample scenario which logs lots of messages to produce several log files.
00216 void Scenario2::DoScenario(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
00217 {
00218     DoScenarioButton->IsEnabled = false;
00219     MainPage::Current->NotifyUser("Scenario running...", NotifyType::StatusMessage);
00220     // Allow the UI to update...
00221     create_task(DoScenarioButton->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::High, ref new Windows::UI::Core::DispatchedHandler([=]() {}))).then([this]()
00222     {
00223         // Run the scenario asynchronously.
00224         return LoggingScenario->DoScenarioAsync();
00225     }).then([this](task<void> previousTask) {
00226         // After the scenario completes, re-enable UI controls and display a message.
00227         DoScenarioButton->IsEnabled = true;
00228         MainPage::Current->NotifyUser("Scenario finished.", NotifyType::StatusMessage);
00229     }, task_continuation_context::use_current());
00230 }
Generated on Fri Nov 15 2024 22:17:58 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: CameraStreamCorrelation/cpp/Scenario1_CorrelateStreams.xaml.h Source File

  • CameraStreamCorrelation
  • cpp

Scenario1_CorrelateStreams.xaml.h

Go to the documentation of this file.
00001 //*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 #pragma once
00013
00014 #include "Scenario1_CorrelateStreams.g.h"
00015 #include "MainPage.xaml.h"
00016 #include "SkeletalFrameRenderer.h"
00017 #include "SimpleLogger.h"
00018 #include "FrameRenderer.h"
00019 #include <wrl.h>
00020 #include <wrl/client.h>
00021
00022 namespace SDKTemplate
00023 {
00024     // This structure stores information related to a frame source.
00025     struct FrameSourceState
00026     {
00027         bool enabled = false; // Whether or not this source is enabled for rendering.
00028
00029         Windows::Media::Capture::Frames::MediaFrameSourceInfo^ sourceInfo = nullptr; // The source info associated with this source.
00030         Windows::Media::Capture::Frames::MediaFrameReference^ latestFrame = nullptr;  // The latest frame from this source.
00031         Windows::Media::Capture::Frames::MediaFrameReader^ reader = nullptr; // The reader we are using to read this source.
00032
00033         Windows::Foundation::EventRegistrationToken frameArrivedEventToken;
00034     };
00035
00036     [Windows::Foundation::Metadata::WebHostHidden]
00037     public ref class Scenario1_CorrelateStreams sealed
00038     {
00039     public:
00040         Scenario1_CorrelateStreams();
00041
00042     protected:
00043         /// <summary>
00044         /// Called when user navigates to this Scenario.
00045         /// Immediately start streaming from first available source group.
00046         /// </summary>
00047         virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00048
00049         /// <summary>
00050         /// Called when user navigates away from this Scenario.
00051         /// Stops streaming and disposes of all objects.
00052         /// </summary>
00053         virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
00054
00055     private:
00056         void NextButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00057         void ToggleDepth_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00058         void ToggleSkeletons_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
00059
00060     private: // Private methods
00061         /// <summary>
00062         /// Enable and disable the stream toggle buttons and set their output message if they are disabled.
00063         /// </summary>
00064         void UpdateUI();
00065
00066         /// <summary>
00067         /// Pick the next source group and start streaming from it.
00068         /// </summary>
00069         concurrency::task<void> PickNextMediaSourceAsync();
00070
00071         /// <summary>
00072         /// Switch to the next eligible media source.
00073         /// </summary>
00074         concurrency::task<void> PickNextMediaSourceWorkerAsync();
00075
00076         /// <summary>
00077         /// Creates a reader for the frame source described by the MediaFrameSourceInfo.
00078         /// On frame arrived will render the output to the supplied software bitmap source.
00079         /// </summary>
00080         concurrency::task<void> CreateReaderAsync(Windows::Media::Capture::Frames::MediaFrameSourceInfo^ sourceInfo);
00081
00082         /// <summary>
00083         /// Initialize the media capture object.
00084         /// Must be called from the UI thread.
00085         /// </summary>
00086         concurrency::task<bool> TryInitializeMediaCaptureAsync(Windows::Media::Capture::Frames::MediaFrameSourceGroup^ group);
00087
00088         /// <summary>
00089         /// Unregisters FrameArrived event handlers, stops and disposes frame readers
00090         /// and disposes the MediaCapture object.
00091         /// </summary>
00092         concurrency::task<void> CleanupMediaCaptureAsync();
00093
00094         /// <summary>
00095         /// Handler for frames which arrive from the MediaFrameReader.
00096         /// Buffers the required frames for rendering and renders based on which sources are enabled and available.
00097         /// </summary>
00098         void FrameReader_FrameArrived(
00099             Windows::Media::Capture::Frames::MediaFrameReader^ sender,
00100             Windows::Media::Capture::Frames::MediaFrameArrivedEventArgs^ args);
00101
00102     private: // Private data.
00103         SDKTemplate::MainPage^ rootPage;
00104
00105         UINT32 m_selectedSourceGroupIndex = 0;
00106
00107         Platform::Agile<Windows::Media::Capture::MediaCapture^> m_mediaCapture;
00108
00109         Microsoft::WRL::Wrappers::SRWLock m_frameLock;
00110
00111         std::map<Windows::Media::Capture::Frames::MediaFrameSourceKind, FrameSourceState> m_frameSources;
00112
00113         std::unique_ptr<FrameRenderer> m_correlatedFrameRenderer;
00114
00115         SDKTemplate::SimpleLogger^ m_logger;
00116     };
00117 } // SDKTemplate
Generated on Fri Nov 15 2024 22:18:46 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Notifications/cs/Notifications/ScenarioPages/Toasts/Scenarios/IncomingCall/ScenarioElement.xaml.cs Source File

  • Notifications
  • cs
  • Notifications
  • ScenarioPages
  • Toasts
  • Scenarios
  • IncomingCall

ScenarioElement.xaml.cs

Go to the documentation of this file.
00001 ﻿using Windows.UI.Notifications;
00002 using Windows.UI.Xaml;
00003 using Windows.UI.Xaml.Controls;
00004
00005 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
00006
00007 namespace Notifications.ScenarioPages.Toasts.Scenarios.IncomingCall
00008 {
00009     /// <summary>
00010     /// An empty page that can be used on its own or navigated to within a Frame.
00011     /// </summary>
00012     public sealed partial class ScenarioElement : UserControl
00013     {
00014         public ScenarioElement()
00015         {
00016             this.InitializeComponent();
00017         }
00018
00019         private void UserControl_Loaded(object sender, RoutedEventArgs e)
00020         {
00021             Initialize();
00022         }
00023
00024         private void Initialize()
00025         {
00026             // Clear all existing notifications
00027             ToastNotificationManager.History.Clear();
00028
00029             // Pop incoming call notification
00030             popToastControl.Payload =
00031                 $@"
00032                 <toast launch='args' scenario='incomingCall'>
00033                     <visual>
00034                         <binding template='ToastGeneric'>
00035                             <text>Incoming Call</text>
00036                             <text>Second Line of Text</text>
00037                         </binding>
00038                     </visual>
00039                     <actions>
00040
00041                         <action arguments = 'answer'
00042                                 content = 'answer' />
00043
00044                         <action arguments = 'ignore'
00045                                 content = 'ignore' />
00046
00047                     </actions>
00048                 </toast>";
00049         }
00050     }
00051 }
Generated on Fri Nov 15 2024 22:20:35 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlStateTriggers/cs/CustomTriggers/DeviceFamilyTrigger.cs Source File

  • XamlStateTriggers
  • cs
  • CustomTriggers

DeviceFamilyTrigger.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006 using Windows.UI.Xaml;
00007
00008 namespace StateTriggersSample.CustomTriggers
00009 {
00010     public class DeviceFamilyTrigger : StateTriggerBase
00011     {
00012         //private variables
00013         private string _currentDeviceFamily, _queriedDeviceFamily;
00014         //Public property
00015         public string DeviceFamily
00016         {
00017             get
00018             {
00019                 return _queriedDeviceFamily;
00020             }
00021             set
00022             {
00023                 _queriedDeviceFamily = value;
00024                 //Get the current device family
00025                 _currentDeviceFamily = Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily;
00026                 //The trigger will be activated if the current device family matches the device family value in XAML
00027                 SetActive(_queriedDeviceFamily == _currentDeviceFamily);
00028             }
00029         }
00030     }
00031 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: AdvancedCasting/cs/MainPage.xaml.cs Source File

  • AdvancedCasting
  • cs

MainPage.xaml.cs

Go to the documentation of this file.
00001 ﻿//*********************************************************
00002 //
00003 // Copyright (c) Microsoft. All rights reserved.
00004 // This code is licensed under the MIT License (MIT).
00005 // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
00006 // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
00007 // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
00008 // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
00009 //
00010 //*********************************************************
00011
00012 using ScreenCasting.Util;
00013 using System;
00014 using System.Collections.Generic;
00015 using Windows.ApplicationModel.Activation;
00016 using Windows.UI.ViewManagement;
00017 using Windows.UI.Xaml;
00018 using Windows.UI.Xaml.Controls;
00019 using Windows.UI.Xaml.Data;
00020 using Windows.UI.Xaml.Media;
00021 using Windows.UI.Xaml.Navigation;
00022
00023 // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
00024
00025 namespace ScreenCasting
00026 {
00027     /// <summary>
00028     /// An empty page that can be used on its own or navigated to within a Frame.
00029     /// </summary>
00030     public sealed partial class MainPage : Page
00031     {
00032         public static MainPage Current;
00033         public ViewLifetimeControl ProjectionViewPageControl;
00034         public MainPage()
00035         {
00036             LoadScenarios();
00037
00038             this.DataContext = this;
00039
00040             this.InitializeComponent();
00041
00042             // This is a static public property that allows downstream pages to get a handle to the MainPage instance
00043             // in order to call methods that are in this class.
00044             Current = this;
00045             SampleTitle.Text = FEATURE_NAME;
00046         }
00047
00048         protected override void OnNavigatedTo(NavigationEventArgs e)
00049         {
00050             ApplicationView.GetForCurrentView().ExitFullScreenMode();
00051             this.ScenarioControl.SelectionChanged += ScenarioControl_SelectionChanged;
00052
00053             try
00054             {
00055                 // Populate the scenario list from the SampleConfiguration.cs file
00056                 ScenarioControl.ItemsSource = Scenarios;
00057
00058                 if (e.Parameter is DialReceiverActivatedEventArgs)
00059                 {
00060                     NavigateToScenario(typeof(Scenario04), e.Parameter);
00061                 }
00062                 else
00063                 {
00064                     ScenarioControl.SelectedIndex = 0;
00065                 }
00066
00067             }
00068             catch (Exception ex)
00069             {
00070                 Window.Current.Content = new Frame();
00071                 Frame rootFrame = Window.Current.Content as Frame;
00072                 rootFrame.Navigate(typeof(UnhandledExceptionPage), null);
00073                 ((UnhandledExceptionPage)rootFrame.Content).StatusMessage = ex.Message + ex.StackTrace;
00074             }
00075         }
00076
00077         /// <summary>
00078         /// Called whenever the user changes selection in the scenarios list.  This method will navigate to the respective
00079         /// sample scenario page.
00080         /// </summary>
00081         /// <param name="sender"></param>
00082         /// <param name="e"></param>
00083         private void ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
00084         {
00085             // Clear the status block when navigating scenarios.
00086             NotifyUser(String.Empty, NotifyType.StatusMessage);
00087
00088             ListBox scenarioListBox = sender as ListBox;
00089             Scenario s = Scenarios[scenarioListBox.SelectedIndex];
00090             if (s != null)
00091             {
00092                 ScenarioFrame.Navigate(s.ClassType);
00093                 if (Window.Current.Bounds.Width < 640)
00094                 {
00095                     Splitter.IsPaneOpen = false;
00096                     StatusBorder.Visibility = Visibility.Collapsed;
00097                 }
00098                 else
00099                 {
00100                     Splitter.IsPaneOpen = true;
00101                     StatusBorder.Visibility = Visibility.Visible;
00102                 }
00103             }
00104         }
00105
00106
00107
00108         internal void NavigateToScenario(Type scenarioType, object args)
00109         {
00110             try
00111             {
00112                 // Clear the status block when navigating scenarios.
00113                 NotifyUser(String.Empty, NotifyType.StatusMessage);
00114
00115                 ListBox scenarioListBox = this.ScenarioControl;
00116
00117                 int selectedIndex = -1;
00118
00119                 this.ScenarioControl.SelectionChanged -= ScenarioControl_SelectionChanged;
00120                 for (int idx = 0; idx < scenarioListBox.Items.Count; idx++)
00121                 {
00122                     if (((Scenario)scenarioListBox.Items[idx]).ClassType == scenarioType)
00123                     {
00124                         selectedIndex = idx;
00125                         break;
00126                     }
00127                 }
00128
00129                 if (selectedIndex > -1)
00130                     scenarioListBox.SelectedIndex = selectedIndex;
00131
00132                 Scenario s = scenarioListBox.SelectedItem as Scenario;
00133
00134                 if (s != null)
00135                 {
00136                     ScenarioFrame.Navigate(s.ClassType, args);
00137                     if (Window.Current.Bounds.Width < 640)
00138                     {
00139                         Splitter.IsPaneOpen = false;
00140                         StatusBorder.Visibility = Visibility.Collapsed;
00141                     }
00142                     else
00143                     {
00144                         Splitter.IsPaneOpen = true;
00145                         StatusBorder.Visibility = Visibility.Visible;
00146                     }
00147                 }
00148                 this.ScenarioControl.SelectionChanged += ScenarioControl_SelectionChanged;
00149             }
00150             catch(Exception ex)
00151             {
00152                 Frame rootFrame = Window.Current.Content as Frame;
00153
00154                 Window.Current.Content = new Frame();
00155                 rootFrame.Navigate(typeof(UnhandledExceptionPage), ex.Message);
00156                 ((UnhandledExceptionPage)rootFrame.Content).StatusMessage = ex.Message + ex.StackTrace;
00157             }
00158         }
00159
00160
00161         public List<Scenario> Scenarios
00162         {
00163             get { return this.scenarios; }
00164         }
00165
00166         /// <summary>
00167         /// Used to display messages to the user
00168         /// </summary>
00169         /// <param name="strMessage"></param>
00170         /// <param name="type"></param>
00171         public void NotifyUser(string strMessage, NotifyType type)
00172         {
00173             switch (type)
00174             {
00175                 case NotifyType.StatusMessage:
00176                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green);
00177                     break;
00178                 case NotifyType.ErrorMessage:
00179                     StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red);
00180                     break;
00181             }
00182             StatusBlock.Text = strMessage;
00183
00184             // Collapse the StatusBlock if it has no text to conserve real estate.
00185             StatusBorder.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed;
00186         }
00187
00188         async void Footer_Click(object sender, RoutedEventArgs e)
00189         {
00190             await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString()));
00191         }
00192
00193         private void Button_Click(object sender, RoutedEventArgs e)
00194         {
00195             Splitter.IsPaneOpen = (Splitter.IsPaneOpen == true) ? false : true;
00196             StatusBorder.Visibility = Visibility.Collapsed;
00197         }
00198     }
00199     public enum NotifyType
00200     {
00201         StatusMessage,
00202         ErrorMessage
00203     };
00204
00205     //public class ScenarioBindingConverter : IValueConverter
00206     //{
00207     //    public object Convert(object value, Type targetType, object parameter, string language)
00208     //    {
00209     //        Scenario s = value as Scenario;
00210     //        return (MainPage.Current.Scenarios.IndexOf(s) + 1) + ") " + s.Title;
00211     //    }
00212
00213     //    public object ConvertBack(object value, Type targetType, object parameter, string language)
00214     //    {
00215     //        return true;
00216     //    }
00217     //}
00218 }
Generated on Fri Nov 15 2024 22:17:09 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlBind/cpp/Templates.xaml.h Source File

  • XamlBind
  • cpp

Templates.xaml.h

Go to the documentation of this file.
00001 ﻿//
00002 // Templates.xaml.h
00003 // Declaration of the Templates class
00004 //
00005
00006 #pragma once
00007
00008 #include "Templates.g.h"
00009
00010 namespace SDKTemplate
00011 {
00012     /// <summary>
00013     /// An empty page that can be used on its own or navigated to within a Frame.
00014     /// </summary>
00015     [Windows::Foundation::Metadata::WebHostHidden]
00016     public ref class Templates sealed
00017     {
00018     public:
00019         Templates();
00020     };
00021 }
Generated on Fri Nov 15 2024 22:22:20 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: XamlMasterDetail/cs/ViewModels/ItemViewModel.cs Source File

  • XamlMasterDetail
  • cs
  • ViewModels

ItemViewModel.cs

Go to the documentation of this file.
00001 ﻿using System;
00002 using System.Collections.Generic;
00003 using System.Linq;
00004 using System.Text;
00005 using System.Threading.Tasks;
00006
00007 using MasterDetailApp.Data;
00008 using Windows.Globalization.DateTimeFormatting;
00009
00010 namespace MasterDetailApp.ViewModels
00011 {
00012     public class ItemViewModel
00013     {
00014         private int _itemId;
00015
00016         public int ItemId
00017         {
00018             get
00019             {
00020                 return _itemId;
00021             }
00022         }
00023
00024         public string DateCreatedHourMinute
00025         {
00026             get
00027             {
00028                 var formatter = new DateTimeFormatter("hour minute");
00029                 return formatter.Format(DateCreated);
00030             }
00031         }
00032
00033         public string Title { get; set; }
00034         public string Text { get; set; }
00035         public DateTime DateCreated { get; set; }
00036
00037         public ItemViewModel()
00038         {
00039         }
00040
00041         public static ItemViewModel FromItem(Item item)
00042         {
00043             var viewModel = new ItemViewModel();
00044
00045             viewModel._itemId = item.Id;
00046             viewModel.DateCreated = item.DateCreated;
00047             viewModel.Title = item.Title;
00048             viewModel.Text = item.Text;
00049
00050             return viewModel;
00051         }
00052     }
00053 }
Generated on Fri Nov 15 2024 22:22:34 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

FaceMesh Member List

This is the complete list of members for FaceMesh, including all inherited members.
FaceMesh(_In_ winrt::com_ptr< ID3D11Device3 > const &device) | FaceMesh |
m_indexBuffer | MeshObject | [protected]
m_indexCount | MeshObject | [protected]
m_vertexBuffer | MeshObject | [protected]
m_vertexCount | MeshObject | [protected]
MeshObject() | MeshObject |
Render(_In_ ID3D11DeviceContext *context) | MeshObject | [virtual]
Generated on Fri Nov 15 2024 22:23:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: HolographicMixedRealityCapture/cpp/Content/SpinningCubeRenderer.cpp Source File

  • HolographicMixedRealityCapture
  • cpp
  • Content

SpinningCubeRenderer.cpp

Go to the documentation of this file.
00001 #include "pch.h"
00002 #include "SpinningCubeRenderer.h"
00003 #include "Common\DirectXHelper.h"
00004
00005 using namespace HolographicMRCSample;
00006 using namespace Concurrency;
00007 using namespace DirectX;
00008 using namespace Windows::Foundation::Numerics;
00009 using namespace Windows::UI::Input::Spatial;
00010
00011 // Loads vertex and pixel shaders from files and instantiates the cube geometry.
00012 SpinningCubeRenderer::SpinningCubeRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
00013     m_deviceResources(deviceResources)
00014 {
00015     CreateDeviceDependentResources();
00016 }
00017
00018 // This function uses a SpatialPointerPose to position the world-locked hologram
00019 // two meters in front of the user's heading.
00020 void SpinningCubeRenderer::PositionHologram(SpatialPointerPose^ pointerPose)
00021 {
00022     if (pointerPose != nullptr)
00023     {
00024         // Get the gaze direction relative to the given coordinate system.
00025         const float3 headPosition    = pointerPose->Head->Position;
00026         const float3 headDirection   = pointerPose->Head->ForwardDirection;
00027
00028         // The hologram is positioned two meters along the user's gaze direction.
00029         static const float distanceFromUser = 2.0f; // meters
00030         const float3 gazeAtTwoMeters        = headPosition + (distanceFromUser * headDirection);
00031
00032         // This will be used as the translation component of the hologram's
00033         // model transform.
00034         SetPosition(gazeAtTwoMeters);
00035     }
00036 }
00037
00038 // Called once per frame. Rotates the cube, and calculates and sets the model matrix
00039 // relative to the position transform indicated by hologramPositionTransform.
00040 void SpinningCubeRenderer::Update(const DX::StepTimer& timer)
00041 {
00042     // Rotate the cube.
00043     // Convert degrees to radians, then convert seconds to rotation angle.
00044     const float    radiansPerSecond = XMConvertToRadians(m_degreesPerSecond);
00045     const double   totalRotation    = timer.GetTotalSeconds() * radiansPerSecond;
00046     const float    radians          = static_cast<float>(fmod(totalRotation, XM_2PI));
00047     const XMMATRIX modelRotation    = XMMatrixRotationY(-radians);
00048
00049     // Position the cube.
00050     const XMMATRIX modelTranslation = XMMatrixTranslationFromVector(XMLoadFloat3(&m_position));
00051
00052     // Multiply to get the transform matrix.
00053     // Note that this transform does not enforce a particular coordinate system. The calling
00054     // class is responsible for rendering this content in a consistent manner.
00055     const XMMATRIX modelTransform   = XMMatrixMultiply(modelRotation, modelTranslation);
00056
00057     // The view and projection matrices are provided by the system; they are associated
00058     // with holographic cameras, and updated on a per-camera basis.
00059     // Here, we provide the model transform for the sample hologram. The model transform
00060     // matrix is transposed to prepare it for the shader.
00061     XMStoreFloat4x4(&m_modelConstantBufferData.model, XMMatrixTranspose(modelTransform));
00062
00063     // Loading is asynchronous. Resources must be created before they can be updated.
00064     if (!m_loadingComplete)
00065     {
00066         return;
00067     }
00068
00069     // Use the D3D device context to update Direct3D device-based resources.
00070     const auto context = m_deviceResources->GetD3DDeviceContext();
00071
00072     // Update the model transform buffer for the hologram.
00073     context->UpdateSubresource(
00074         m_modelConstantBuffer.Get(),
00075         0,
00076         nullptr,
00077         &m_modelConstantBufferData,
00078         0,
00079         0
00080         );
00081 }
00082
00083 // Renders one frame using the vertex and pixel shaders.
00084 // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00085 // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00086 // a pass-through geometry shader is also used to set the render
00087 // target array index.
00088 void SpinningCubeRenderer::Render()
00089 {
00090     // Loading is asynchronous. Resources must be created before drawing can occur.
00091     if (!m_loadingComplete)
00092     {
00093         return;
00094     }
00095
00096     const auto context = m_deviceResources->GetD3DDeviceContext();
00097
00098     // Each vertex is one instance of the VertexPositionColor struct.
00099     const UINT stride = sizeof(VertexPositionColor);
00100     const UINT offset = 0;
00101     context->IASetVertexBuffers(
00102         0,
00103         1,
00104         m_vertexBuffer.GetAddressOf(),
00105         &stride,
00106         &offset
00107         );
00108     context->IASetIndexBuffer(
00109         m_indexBuffer.Get(),
00110         DXGI_FORMAT_R16_UINT, // Each index is one 16-bit unsigned integer (short).
00111         0
00112         );
00113     context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
00114     context->IASetInputLayout(m_inputLayout.Get());
00115
00116     // Attach the vertex shader.
00117     context->VSSetShader(
00118         m_vertexShader.Get(),
00119         nullptr,
00120         0
00121         );
00122     // Apply the model constant buffer to the vertex shader.
00123     context->VSSetConstantBuffers(
00124         0,
00125         1,
00126         m_modelConstantBuffer.GetAddressOf()
00127         );
00128
00129     if (!m_usingVprtShaders)
00130     {
00131         // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3::
00132         // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature,
00133         // a pass-through geometry shader is used to set the render target
00134         // array index.
00135         context->GSSetShader(
00136             m_geometryShader.Get(),
00137             nullptr,
00138             0
00139             );
00140     }
00141
00142     // Attach the pixel shader.
00143     context->PSSetShader(
00144         m_pixelShader.Get(),
00145         nullptr,
00146         0
00147         );
00148
00149     // Draw the objects.
00150     context->DrawIndexedInstanced(
00151         m_indexCount,   // Index count per instance.
00152         2,              // Instance count.
00153         0,              // Start index location.
00154         0,              // Base vertex location.
00155         0               // Start instance location.
00156         );
00157 }
00158
00159 void SpinningCubeRenderer::CreateDeviceDependentResources()
00160 {
00161     m_usingVprtShaders = m_deviceResources->GetDeviceSupportsVprt();
00162
00163     // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3::
00164     // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature
00165     // we can avoid using a pass-through geometry shader to set the render
00166     // target array index, thus avoiding any overhead that would be
00167     // incurred by setting the geometry shader stage.
00168
00169     m_vertexShader = m_deviceResources->GetVertexShader(DX::VertexShader_Simple);
00170     m_inputLayout = m_deviceResources->GetInputLayout(DX::VertexShader_Simple);
00171     m_pixelShader = m_deviceResources->GetPixelShader(DX::PixelShader_Simple);
00172
00173     if (!m_usingVprtShaders)
00174     {
00175         m_geometryShader = m_deviceResources->GetGeometryShader(DX::GeometryShader_Simple);
00176     }
00177
00178     const CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelConstantBuffer), D3D11_BIND_CONSTANT_BUFFER);
00179     DX::ThrowIfFailed(
00180         m_deviceResources->GetD3DDevice()->CreateBuffer(
00181             &constantBufferDesc,
00182             nullptr,
00183             &m_modelConstantBuffer
00184         )
00185     );
00186
00187     // Load mesh vertices. Each vertex has a position and a color.
00188     // Note that the cube size has changed from the default DirectX app
00189     // template. Windows Holographic is scaled in meters, so to draw the
00190     // cube at a comfortable size we made the cube width 0.2 m (20 cm).
00191     static const VertexPositionColor cubeVertices[] =
00192     {
00193         { XMFLOAT3(-0.1f, -0.1f, -0.1f), XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f) },
00194         { XMFLOAT3(-0.1f, -0.1f,  0.1f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f) },
00195         { XMFLOAT3(-0.1f,  0.1f, -0.1f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f) },
00196         { XMFLOAT3(-0.1f,  0.1f,  0.1f), XMFLOAT4(0.0f, 1.0f, 1.0f, 1.0f) },
00197         { XMFLOAT3( 0.1f, -0.1f, -0.1f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f) },
00198         { XMFLOAT3( 0.1f, -0.1f,  0.1f), XMFLOAT4(1.0f, 0.0f, 1.0f, 1.0f) },
00199         { XMFLOAT3( 0.1f,  0.1f, -0.1f), XMFLOAT4(1.0f, 1.0f, 0.0f, 1.0f) },
00200         { XMFLOAT3( 0.1f,  0.1f,  0.1f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f) },
00201     };
00202
00203     D3D11_SUBRESOURCE_DATA vertexBufferData = {0};
00204     vertexBufferData.pSysMem = cubeVertices;
00205     vertexBufferData.SysMemPitch = 0;
00206     vertexBufferData.SysMemSlicePitch = 0;
00207     const CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(cubeVertices), D3D11_BIND_VERTEX_BUFFER);
00208     DX::ThrowIfFailed(
00209         m_deviceResources->GetD3DDevice()->CreateBuffer(
00210             &vertexBufferDesc,
00211             &vertexBufferData,
00212             &m_vertexBuffer
00213             )
00214         );
00215
00216     // Load mesh indices. Each trio of indices represents
00217     // a triangle to be rendered on the screen.
00218     // For example: 2,1,0 means that the vertices with indexes
00219     // 2, 1, and 0 from the vertex buffer compose the
00220     // first triangle of this mesh.
00221     // Note that the winding order is clockwise by default.
00222     static const unsigned short cubeIndices [] =
00223     {
00224         2,1,0, // -x
00225         2,3,1,
00226
00227         6,4,5, // +x
00228         6,5,7,
00229
00230         0,1,5, // -y
00231         0,5,4,
00232
00233         2,6,7, // +y
00234         2,7,3,
00235
00236         0,4,6, // -z
00237         0,6,2,
00238
00239         1,3,7, // +z
00240         1,7,5,
00241     };
00242
00243     m_indexCount = ARRAYSIZE(cubeIndices);
00244
00245     D3D11_SUBRESOURCE_DATA indexBufferData = {0};
00246     indexBufferData.pSysMem          = cubeIndices;
00247     indexBufferData.SysMemPitch      = 0;
00248     indexBufferData.SysMemSlicePitch = 0;
00249     const CD3D11_BUFFER_DESC indexBufferDesc(sizeof(cubeIndices), D3D11_BIND_INDEX_BUFFER);
00250     DX::ThrowIfFailed(
00251         m_deviceResources->GetD3DDevice()->CreateBuffer(
00252             &indexBufferDesc,
00253             &indexBufferData,
00254             &m_indexBuffer
00255             )
00256         );
00257
00258     // Once the cube is loaded, the object is ready to be rendered.
00259     m_loadingComplete = true;
00260 }
00261
00262 void SpinningCubeRenderer::ReleaseDeviceDependentResources()
00263 {
00264     m_loadingComplete  = false;
00265     m_usingVprtShaders = false;
00266     m_vertexShader.Reset();
00267     m_inputLayout.Reset();
00268     m_pixelShader.Reset();
00269     m_geometryShader.Reset();
00270     m_modelConstantBuffer.Reset();
00271     m_vertexBuffer.Reset();
00272     m_indexBuffer.Reset();
00273 }
Generated on Fri Nov 15 2024 22:18:31 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Geolocation/cppwinrt/Tasks/VisitBackgroundTask.cpp Source File

  • Geolocation
  • cppwinrt
  • Tasks

VisitBackgroundTask.cpp

Go to the documentation of this file.
00001 ﻿#include "pch.h"
00002 #include "Helpers.h"
00003 #include "VisitBackgroundTask.h"
00004 #include "VisitBackgroundTask.g.cpp"
00005
00006 using namespace winrt;
00007 using namespace winrt::Windows::ApplicationModel::Background;
00008 using namespace winrt::Windows::Data::Json;
00009 using namespace winrt::Windows::Data::Xml::Dom;
00010 using namespace winrt::Windows::Devices::Geolocation;
00011 using namespace winrt::Windows::Foundation;
00012 using namespace winrt::Windows::Foundation::Collections;
00013 using namespace winrt::Windows::UI::Notifications;
00014
00015 namespace winrt::BackgroundTask::implementation
00016 {
00017     void VisitBackgroundTask::Run(IBackgroundTaskInstance const& taskInstance)
00018     {
00019         BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
00020
00021         GeovisitTriggerDetails triggerDetails = taskInstance.TriggerDetails().as<GeovisitTriggerDetails>();
00022
00023         ProcessVisitReports(triggerDetails);
00024
00025         deferral.Complete();
00026     }
00027
00028     void VisitBackgroundTask::ProcessVisitReports(GeovisitTriggerDetails const& triggerDetails)
00029     {
00030         // Load the values saved from last time.
00031         JsonArray visitBackgroundEvents = LoadSavedJson(L"BackgroundVisitEventCollection");
00032
00033         // Read reports from the triggerDetails.
00034         hstring description;
00035         IVectorView<Geovisit> reports = triggerDetails.ReadReports();
00036         for (Geovisit report : reports)
00037         {
00038             description = GenerateVisitDescription(report);
00039
00040             // Add to the collection, trimming old events if necessary.
00041             if (visitBackgroundEvents.Size() == maxEventDescriptors)
00042             {
00043                 visitBackgroundEvents.RemoveAtEnd();
00044             }
00045
00046             visitBackgroundEvents.InsertAt(0, JsonValue::CreateStringValue(description));
00047         }
00048
00049         uint32_t numReports = reports.Size();
00050         if (numReports > 0)
00051         {
00052             // Save the modified results for next time.
00053             m_values.Insert(L"BackgroundVisitEventCollection", box_value(visitBackgroundEvents.Stringify()));
00054
00055             if (numReports > 1)
00056             {
00057                 description = L"There are " + to_hstring(numReports) + L" new visit events";
00058             }
00059             DisplayToast(description);
00060         }
00061     }
00062
00063     hstring VisitBackgroundTask::GenerateVisitDescription(Geovisit const& visit)
00064     {
00065         hstring result = FormatDateTime(visit.Timestamp(), L"shortdate shorttime") + L" " + to_hstring(visit.StateChange());
00066
00067         // Check if the report has a valid position.
00068         if (visit.Position() != nullptr)
00069         {
00070             result = result + L" (" +
00071                 to_brief_hstring(visit.Position().Coordinate().Point().Position().Latitude) + L"," +
00072                 to_brief_hstring(visit.Position().Coordinate().Point().Position().Longitude) + L")";
00073         }
00074         return result;
00075     }
00076 }
Generated on Fri Nov 15 2024 22:19:53 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

AccountOverviewPage Member List

This is the complete list of members for AccountOverviewPage, including all inherited members.
AccountOverviewPage() | AccountOverviewPage | [inline]
SignOut() | AccountOverviewPage | [inline, private]
Generated on Fri Nov 15 2024 22:23:37 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: DisplayOrientation/cpp/pch.h Source File

  • DisplayOrientation
  • cpp

pch.h

Go to the documentation of this file.
00001 //
00002 // Header for standard system include files.
00003 //
00004
00005 #pragma once
00006
00007 #include <collection.h>
00008 #include <ppltasks.h>
00009
00010 #include "App.xaml.h"
Generated on Fri Nov 15 2024 22:17:07 for Windows-Universal-Examples by doxygen 1.7.1


Windows-Universal-Examples: Member List

  • Class List
  • Class Index
  • Class Hierarchy
  • Class Members

MediaFoundationConstants Member List

This is the complete list of members for MediaFoundationConstants, including all inherited members.
eAVEncH264VLevel enum name | MediaFoundationConstants |
MF_MT_VIDEO_LEVEL | MediaFoundationConstants | [static]
Generated on Fri Nov 15 2024 22:23:47 for Windows-Universal-Examples by doxygen 1.7.1